_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 |
|---|---|---|---|---|---|---|---|---|
af9f1dfd397012b9ba42f6db826e970a281ef32a94f81b3a0e5621a587d127b6 | conscell/hugs-android | Lazy.hs | -----------------------------------------------------------------------------
-- |
Module : Control . . ST.Lazy
Copyright : ( c ) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer :
-- Stability : provisional
-- Portability : non-portable (requires universal quantification for runST)
--
This module presents an identical interface to " Control . Monad . ST " ,
-- except that the monad delays evaluation of state operations until
-- a value depending on them is required.
--
-----------------------------------------------------------------------------
module Control.Monad.ST.Lazy (
-- * The 'ST' monad
ST,
runST,
fixST,
-- * Converting between strict and lazy 'ST'
strictToLazyST, lazyToStrictST,
-- * Converting 'ST' To 'IO'
RealWorld,
stToIO,
-- * Unsafe operations
unsafeInterleaveST,
unsafeIOToST
) where
import Prelude
import Control.Monad.Fix
import Control.Monad.ST (RealWorld)
import qualified Control.Monad.ST as ST
import Hugs.LazyST
instance MonadFix (ST s) where
mfix = fixST
-- ---------------------------------------------------------------------------
-- Strict <--> Lazy
unsafeIOToST :: IO a -> ST s a
unsafeIOToST = strictToLazyST . ST.unsafeIOToST
-- | A monad transformer embedding lazy state transformers in the 'IO'
-- monad. The 'RealWorld' parameter indicates that the internal state
-- used by the 'ST' computation is a special one supplied by the 'IO'
-- monad, and thus distinct from those used by invocations of 'runST'.
stToIO :: ST RealWorld a -> IO a
stToIO = ST.stToIO . lazyToStrictST
| null | https://raw.githubusercontent.com/conscell/hugs-android/31e5861bc1a1dd9931e6b2471a9f45c14e3c6c7e/hugs/lib/hugs/packages/base/Control/Monad/ST/Lazy.hs | haskell | ---------------------------------------------------------------------------
|
License : BSD-style (see the file libraries/base/LICENSE)
Maintainer :
Stability : provisional
Portability : non-portable (requires universal quantification for runST)
except that the monad delays evaluation of state operations until
a value depending on them is required.
---------------------------------------------------------------------------
* The 'ST' monad
* Converting between strict and lazy 'ST'
* Converting 'ST' To 'IO'
* Unsafe operations
---------------------------------------------------------------------------
Strict <--> Lazy
| A monad transformer embedding lazy state transformers in the 'IO'
monad. The 'RealWorld' parameter indicates that the internal state
used by the 'ST' computation is a special one supplied by the 'IO'
monad, and thus distinct from those used by invocations of 'runST'. | Module : Control . . ST.Lazy
Copyright : ( c ) The University of Glasgow 2001
This module presents an identical interface to " Control . Monad . ST " ,
module Control.Monad.ST.Lazy (
ST,
runST,
fixST,
strictToLazyST, lazyToStrictST,
RealWorld,
stToIO,
unsafeInterleaveST,
unsafeIOToST
) where
import Prelude
import Control.Monad.Fix
import Control.Monad.ST (RealWorld)
import qualified Control.Monad.ST as ST
import Hugs.LazyST
instance MonadFix (ST s) where
mfix = fixST
unsafeIOToST :: IO a -> ST s a
unsafeIOToST = strictToLazyST . ST.unsafeIOToST
stToIO :: ST RealWorld a -> IO a
stToIO = ST.stToIO . lazyToStrictST
|
f227e4ec9d3fe9c0c802b3f48afaac38f58835f10b60542da305886e897dd411 | wireapp/wire-server | Cassandra.hs | module Brig.Effects.BlacklistPhonePrefixStore.Cassandra
( interpretBlacklistPhonePrefixStoreToCassandra,
)
where
import Brig.Effects.BlacklistPhonePrefixStore
import Brig.Types.Common
import Cassandra
import Imports
import Polysemy
import Wire.API.User.Identity
interpretBlacklistPhonePrefixStoreToCassandra ::
forall m r a.
(MonadClient m, Member (Embed m) r) =>
Sem (BlacklistPhonePrefixStore ': r) a ->
Sem r a
interpretBlacklistPhonePrefixStoreToCassandra =
interpret $
embed @m . \case
Insert ep -> insertPrefix ep
Delete pp -> deletePrefix pp
ExistsAny uk -> existsAnyPrefix uk
GetAll pp -> getAllPrefixes pp
--------------------------------------------------------------------------------
-- Excluded phone prefixes
insertPrefix :: MonadClient m => ExcludedPrefix -> m ()
insertPrefix prefix = retry x5 $ write ins (params LocalQuorum (phonePrefix prefix, comment prefix))
where
ins :: PrepQuery W (PhonePrefix, Text) ()
ins = "INSERT INTO excluded_phones (prefix, comment) VALUES (?, ?)"
deletePrefix :: MonadClient m => PhonePrefix -> m ()
deletePrefix prefix = retry x5 $ write del (params LocalQuorum (Identity prefix))
where
del :: PrepQuery W (Identity PhonePrefix) ()
del = "DELETE FROM excluded_phones WHERE prefix = ?"
getAllPrefixes :: MonadClient m => PhonePrefix -> m [ExcludedPrefix]
getAllPrefixes prefix = do
let prefixes = fromPhonePrefix <$> allPrefixes (fromPhonePrefix prefix)
selectPrefixes prefixes
existsAnyPrefix :: MonadClient m => Phone -> m Bool
existsAnyPrefix phone = do
let prefixes = fromPhonePrefix <$> allPrefixes (fromPhone phone)
not . null <$> selectPrefixes prefixes
selectPrefixes :: MonadClient m => [Text] -> m [ExcludedPrefix]
selectPrefixes prefixes = do
results <- retry x1 (query sel (params LocalQuorum (Identity $ prefixes)))
pure $ uncurry ExcludedPrefix <$> results
where
sel :: PrepQuery R (Identity [Text]) (PhonePrefix, Text)
sel = "SELECT prefix, comment FROM excluded_phones WHERE prefix IN ?"
| null | https://raw.githubusercontent.com/wireapp/wire-server/e084f131c4fec095ee62d703d7a21638d89cbf24/services/brig/src/Brig/Effects/BlacklistPhonePrefixStore/Cassandra.hs | haskell | ------------------------------------------------------------------------------
Excluded phone prefixes | module Brig.Effects.BlacklistPhonePrefixStore.Cassandra
( interpretBlacklistPhonePrefixStoreToCassandra,
)
where
import Brig.Effects.BlacklistPhonePrefixStore
import Brig.Types.Common
import Cassandra
import Imports
import Polysemy
import Wire.API.User.Identity
interpretBlacklistPhonePrefixStoreToCassandra ::
forall m r a.
(MonadClient m, Member (Embed m) r) =>
Sem (BlacklistPhonePrefixStore ': r) a ->
Sem r a
interpretBlacklistPhonePrefixStoreToCassandra =
interpret $
embed @m . \case
Insert ep -> insertPrefix ep
Delete pp -> deletePrefix pp
ExistsAny uk -> existsAnyPrefix uk
GetAll pp -> getAllPrefixes pp
insertPrefix :: MonadClient m => ExcludedPrefix -> m ()
insertPrefix prefix = retry x5 $ write ins (params LocalQuorum (phonePrefix prefix, comment prefix))
where
ins :: PrepQuery W (PhonePrefix, Text) ()
ins = "INSERT INTO excluded_phones (prefix, comment) VALUES (?, ?)"
deletePrefix :: MonadClient m => PhonePrefix -> m ()
deletePrefix prefix = retry x5 $ write del (params LocalQuorum (Identity prefix))
where
del :: PrepQuery W (Identity PhonePrefix) ()
del = "DELETE FROM excluded_phones WHERE prefix = ?"
getAllPrefixes :: MonadClient m => PhonePrefix -> m [ExcludedPrefix]
getAllPrefixes prefix = do
let prefixes = fromPhonePrefix <$> allPrefixes (fromPhonePrefix prefix)
selectPrefixes prefixes
existsAnyPrefix :: MonadClient m => Phone -> m Bool
existsAnyPrefix phone = do
let prefixes = fromPhonePrefix <$> allPrefixes (fromPhone phone)
not . null <$> selectPrefixes prefixes
selectPrefixes :: MonadClient m => [Text] -> m [ExcludedPrefix]
selectPrefixes prefixes = do
results <- retry x1 (query sel (params LocalQuorum (Identity $ prefixes)))
pure $ uncurry ExcludedPrefix <$> results
where
sel :: PrepQuery R (Identity [Text]) (PhonePrefix, Text)
sel = "SELECT prefix, comment FROM excluded_phones WHERE prefix IN ?"
|
3e62df1f8a76a7d00a9c0fa1929e5b906d04727ec5336561a04b951beea8bebb | slyrus/mcclim-old | port.lisp | ;;; -*- Mode: Lisp; Package: CLIM-CLX; -*-
( c ) copyright 1998,1999,2000 by ( )
( c ) copyright 2000,2001 by
;;; Iban Hatchondo ()
( )
( )
;;; This library 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 ( at your option ) any later version .
;;;
;;; This library is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details .
;;;
You should have received a copy of the GNU Library 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 .
(in-package :clim-clx)
(declaim (inline round-coordinate))
(defun round-coordinate (x)
"Function used for rounding coordinates."
We use " mercantile rounding " , instead of the CL round to nearest
;; even number, when in doubt.
;;
Reason : As the CLIM drawing model is specified , you quite often
want to operate with coordinates , which are multiples of 1/2 .
Using CL : ROUND gives you " random " results . Using " mercantile
;; rounding" gives you consistent results.
;;
Note that CLIM defines pixel coordinates to be at the corners ,
;; while in X11 they are at the centers. We don't do much about the
discrepancy , but rounding up at half pixel boundaries seems to
;; work well.
(floor (+ x .5)))
CLX - PORT class
(defclass clx-pointer (standard-pointer)
((cursor :accessor pointer-cursor :initform :upper-left)))
#|
Perhaps this belongs elsewhere
We have a couple of problems, one is character-sets.
Unfortunately no-one seems to define what a character-set is, really.
So, I define a character-set as being the same as a language, since
a language is far more useful.
This is important, since a given language may include many characters
from what might be traditionally considered disparate character-sets.
Also it is important, since we cannot simply map a character to a glyph
in a language independent fashion, since the style of the character may
have some language component.
In our rendering/translation mechanism we switch fonts when a font fails
to supply the glyph that we want. So, to facilitate this we need a given
fontset with a set of disjoint ranges mapped to particular font/encoding
pairs.
For the time being, an alist should do here.
We assume that we're given disjoint ranges for now, which is optimistic.
Currently building a fontset will be a tricksy business, think about how
to generalise this for the future.
|#
; this is to inform the text renderer which fontset it should be using.
; it is a complement to the graphics-context stuff, effectively.
; the #'translate uses/needs this to switch fonts
(defclass fontset () (
; of the form ((start . stop) font translator)
(name
:type simple-string
:initform "fontset"
:initarg :name
:reader fontset-name)
(default-font
:initform nil
:reader fontset-default-font)
(ranges
:type list
:initform nil
:initarg :ranges)
(ascent
:type integer
:initform 0
:initarg :ascent
:reader fontset-ascent)
(descent
:type integer
:initform 0
:initarg :ascent
:reader fontset-descent)
(height
:type integer
:initform 0
:initarg :ascent
:reader fontset-height)
(width
:type integer
:initform 0
:initarg :ascent
:reader fontset-width)))
(defvar *fontset* nil)
(defmethod print-object ((object fontset) stream)
(format stream "#<fontset ~A>" (fontset-name object)))
(defmacro make-fontset (name &body entries)
(let ((fontset (gensym)))
`(let ((,fontset (make-instance 'fontset :name ,name)))
,@(mapcar (lambda (entry)
(destructuring-bind (start finish font translator) entry
`(set-fontset-range ,fontset ,font ,translator ,start ,finish)))
entries)
,fontset)))
(defmethod set-fontset-range ((fontset fontset) font translator start finish)
should check ordering invariants , disjointity , etc
(with-slots (ranges ascent descent height default-font) fontset
(unless default-font
(setf default-font font))
(push (list (cons start finish) font translator) ranges)
(setf ascent (max (xlib:font-ascent font) ascent))
(setf descent (max (xlib:font-descent font) descent))
(setf height (+ ascent descent))))
(defun fontset-point-width (point &optional (fontset *fontset*))
(let ((entry (fontset-point point fontset)))
(if entry
(destructuring-bind ((range-start . range-stop) font translator) entry
(declare (ignore range-start range-stop))
(xlib:char-width font (funcall translator point)))
0)))
(defun fontset-point (point &optional (fontset *fontset*))
(%fontset-point fontset point))
(defmethod %fontset-point ((fontset fontset) point)
(with-slots (ranges) fontset
(assoc point ranges :test (lambda (point range)
(<= (car range) point (cdr range))))))
(defclass clx-port (clim-xcommon:keysym-port-mixin basic-port)
((display :initform nil
:accessor clx-port-display)
(screen :initform nil
:accessor clx-port-screen)
(window :initform nil
:accessor clx-port-window)
(color-table :initform (make-hash-table :test #'eq))
(cursor-table :initform (make-hash-table :test #'eq)
:accessor clx-port-cursor-table)
(design-cache :initform (make-hash-table :test #'eq))
(pointer :reader port-pointer)
(pointer-grab-sheet :accessor pointer-grab-sheet :initform nil)
(selection-owner :initform nil :accessor selection-owner)
(selection-timestamp :initform nil :accessor selection-timestamp)
(font-families :accessor font-families)))
(defun automagic-clx-server-path ()
(let ((name (get-environment-variable "DISPLAY")))
(assert name (name)
"Environment variable DISPLAY is not set")
(let* (; this code courtesy telent-clx.
(slash-i (or (position #\/ name) -1))
(colon-i (position #\: name :start (1+ slash-i)))
(decnet-colon-p (eql (elt name (1+ colon-i)) #\:))
(host (subseq name (1+ slash-i) colon-i))
(dot-i (and colon-i (position #\. name :start colon-i)))
(display (and colon-i
(parse-integer name
:start (if decnet-colon-p
(+ colon-i 2)
(1+ colon-i))
:end dot-i)))
(screen (and dot-i
(parse-integer name :start (1+ dot-i))))
(protocol
(cond ((or (string= host "") (string-equal host "unix")) :local)
(decnet-colon-p :decnet)
((> slash-i -1) (intern
(string-upcase (subseq name 0 slash-i))
:keyword))
(t :internet))))
(list :clx
:host host
:display-id (or display 0)
:screen-id (or screen 0)
:protocol protocol))))
(defun helpfully-automagic-clx-server-path ()
(restart-case (automagic-clx-server-path)
(use-localhost ()
:report "Use local unix display"
(parse-clx-server-path '(:clx :host "" :protocol :unix)))))
(defun parse-clx-server-path (path)
(pop path)
(if path
(list :clx
:host (getf path :host "localhost")
:display-id (getf path :display-id 0)
:screen-id (getf path :screen-id 0)
:protocol (getf path :protocol :internet))
(helpfully-automagic-clx-server-path)))
(setf (get :x11 :port-type) 'clx-port)
(setf (get :x11 :server-path-parser) 'parse-clx-server-path)
(setf (get :clx :port-type) 'clx-port)
(setf (get :clx :server-path-parser) 'parse-clx-server-path)
(defmethod initialize-instance :after ((port clx-port) &rest args)
(declare (ignore args))
(push (make-instance 'clx-frame-manager :port port) (slot-value port 'frame-managers))
(setf (slot-value port 'pointer)
(make-instance 'clx-pointer :port port))
(initialize-clx port))
(defmethod print-object ((object clx-port) stream)
(print-unreadable-object (object stream :identity t :type t)
(when (slot-boundp object 'display)
(let ((display (slot-value object 'display)))
(when display
(format stream "~S ~S ~S ~S"
:host (xlib:display-host display)
:display-id (xlib:display-display display)))))))
(defun clx-error-handler (display error-name &rest args &key major &allow-other-keys)
42 is SetInputFocus , we ignore match - errors from that
(eq error-name 'xlib:match-error))
(format *error-output* "Received CLX ~A in process ~W~%"
error-name (clim-sys:process-name (clim-sys:current-process)))
(apply #'xlib:default-error-handler display error-name args)))
(defvar *clx-cursor-mapping*
These are taken from the Franz CLIM User 's Guide
(:busy 150)
(:button 60)
(:default 68)
(:horizontal-scroll 108)
(:horizontal-thumb 108)
(:lower-left 12)
(:lower-right 14)
(:move 52)
(:position 130)
(:prompt 152)
(:scroll-down 106)
(:scroll-left 110)
(:scroll-right 112)
(:scroll-up 114)
(:upper-left 134)
(:upper-right 136)
(:vertical-scroll 116)
(:vertical-thumb 116)
The following are not in the docs , but might be useful .
(:i-beam 152)
(:vertical-pointer 22)
(:pencil 86)
(:rotate 50)
(:choose 60)))
(defun make-cursor-table (port)
(declare (optimize (safety 3) (debug 3) (speed 0) (space 0)))
(let ((font (xlib:open-font (clx-port-display port) "cursor")))
(loop for (symbol code) in *clx-cursor-mapping*
do (setf (gethash symbol (clx-port-cursor-table port))
(xlib:create-glyph-cursor :foreground (xlib:make-color :red 0.0 :green 0.0 :blue 0.0)
:background (xlib:make-color :red 1.0 :green 1.0 :blue 1.0)
:source-font font
:source-char code
:mask-font font
:mask-char (1+ code))))
(xlib:close-font font)))
(defmethod initialize-clx ((port clx-port))
(let ((options (cdr (port-server-path port))))
(setf (clx-port-display port)
(xlib:open-display (getf options :host)
:display (getf options :display-id)
:protocol (getf options :protocol)))
(progn
(setf (xlib:display-error-handler (clx-port-display port))
#'clx-error-handler)
Uncomment this when debugging CLX backend if asynchronous errors become troublesome ..
(setf (xlib:display-after-function (clx-port-display port)) #'xlib:display-finish-output))
(setf (clx-port-screen port) (nth (getf options :screen-id)
(xlib:display-roots (clx-port-display port))))
(setf (clx-port-window port) (xlib:screen-root (clx-port-screen port)))
(make-cursor-table port)
(make-graft port)
(when clim-sys:*multiprocessing-p*
(setf (port-event-process port)
(clim-sys:make-process
(lambda ()
(loop
(with-simple-restart
(restart-event-loop
"Restart CLIM's event loop.")
(loop
(process-next-event port)) )))
:name (format nil "~S's event process." port)))
#+nil(format *trace-output* "~&Started CLX event loop process ~A~%" (port-event-process port))) ))
#+nil
(defmethod (setf sheet-mirror-transformation) :after (new-value (sheet mirrored-sheet-mixin))
)
(defmethod port-set-mirror-region ((port clx-port) mirror mirror-region)
(setf (xlib:drawable-width mirror) (floor (bounding-rectangle-max-x mirror-region))
(xlib:drawable-height mirror) (floor (bounding-rectangle-max-y mirror-region))))
(defmethod port-set-mirror-transformation ((port clx-port) mirror mirror-transformation)
(setf (xlib:drawable-x mirror) (floor (nth-value 0 (transform-position mirror-transformation 0 0)))
(xlib:drawable-y mirror) (floor (nth-value 1 (transform-position mirror-transformation 0 0)))))
(defun invent-sheet-mirror-transformation-and-region (sheet)
;; -> tr region
(let* ((r (sheet-region sheet))
(r* (transform-region
(sheet-native-transformation (sheet-parent sheet))
(transform-region (sheet-transformation sheet) r)))
#+nil
(r*
(bounding-rectangle
(region-intersection
r*
(make-rectangle* 0 0
(port-mirror-width (port sheet) (sheet-parent sheet))
(port-mirror-height (port sheet) (sheet-parent sheet))))))
(mirror-transformation
(if (region-equal r* +nowhere+)
(make-translation-transformation 0 0)
(make-translation-transformation
(bounding-rectangle-min-x r*)
(bounding-rectangle-min-y r*))))
(mirror-region
(untransform-region mirror-transformation r*)))
(values
mirror-transformation
mirror-region)))
(defun realize-mirror-aux (port sheet
&key (width 100) (height 100) (x 0) (y 0)
(border-width 0) (border 0)
(override-redirect :off)
(map t)
(backing-store :not-useful)
(save-under :off)
(event-mask `(:exposure
:key-press :key-release
:button-press :button-release
:enter-window :leave-window
:structure-notify
:pointer-motion
:button-motion)))
;; I am declaring BORDER-WIDTH ignore to get a cleaner build, but I
;; don't really understand why the use of it is commented out in favor
of the constant 0 . -- RS 2007 - 07 - 22
(declare (ignore border-width))
(when (null (port-lookup-mirror port sheet))
(update-mirror-geometry sheet)
(let* ((desired-color (typecase sheet
(sheet-with-medium-mixin
(medium-background sheet))
CHECKME [ is this sensible ? ] seems to be
(let ((background (pane-background sheet)))
(if (typep background 'color)
background
+white+)))
(t
+white+)))
(color (multiple-value-bind (r g b)
(color-rgb desired-color)
(xlib:make-color :red r :green g :blue b)))
(pixel (xlib:alloc-color (xlib:screen-default-colormap (clx-port-screen port)) color))
(window (xlib:create-window
:parent (sheet-mirror (sheet-parent sheet))
:width (if (%sheet-mirror-region sheet)
(round-coordinate (bounding-rectangle-width (%sheet-mirror-region sheet)))
width)
:height (if (%sheet-mirror-region sheet)
(round-coordinate (bounding-rectangle-height (%sheet-mirror-region sheet)))
height)
:x (if (%sheet-mirror-transformation sheet)
(round-coordinate (nth-value 0 (transform-position
(%sheet-mirror-transformation sheet)
0 0)))
x)
:y (if (%sheet-mirror-transformation sheet)
(round-coordinate (nth-value 1 (transform-position
(%sheet-mirror-transformation sheet)
0 0)))
y)
:border-width 0 ;;border-width
:border border
:override-redirect override-redirect
:backing-store backing-store
:save-under save-under
:gravity :north-west
;; Evil Hack -- but helps enormously (Has anybody
;; a good idea how to sneak the concept of
bit - gravity into CLIM ) ? --GB
:bit-gravity (if (typep sheet 'climi::extended-output-stream)
:north-west
:forget)
:background pixel
:event-mask (apply #'xlib:make-event-mask
event-mask))))
(port-register-mirror (port sheet) sheet window)
(when map
(xlib:map-window window)
)))
(port-lookup-mirror port sheet))
(defmethod realize-mirror ((port clx-port) (sheet mirrored-sheet-mixin))
(realize-mirror-aux port sheet
:border-width 0
:map (sheet-enabled-p sheet)))
(defmethod realize-mirror ((port clx-port) (sheet border-pane))
;;(rotatef (medium-background (sheet-medium sheet)) (medium-foreground (sheet-medium sheet)))
(realize-mirror-aux port sheet
:border-width 0 ; (border-pane-width sheet)
:event-mask '(:exposure
:structure-notify)
:map (sheet-enabled-p sheet)))
(defmethod realize-mirror ((port clx-port) (sheet top-level-sheet-pane))
(let ((q (compose-space sheet)))
#+nil ; SHEET and its descendants are grafted, but unmirrored :-\ -- APD
(allocate-space sheet
(space-requirement-width q)
(space-requirement-height q))
(let ((frame (pane-frame sheet))
(window (realize-mirror-aux port sheet
:map nil
:width (round-coordinate (space-requirement-width q))
:height (round-coordinate (space-requirement-height q))
:event-mask '(:key-press :key-release))))
(setf (xlib:wm-hints window) (xlib:make-wm-hints :input :on))
(setf (xlib:wm-name window) (frame-pretty-name frame))
(setf (xlib:wm-icon-name window) (frame-pretty-name frame))
(xlib:set-wm-class
window
(string-downcase (frame-name frame))
(string-capitalize (string-downcase (frame-name frame))))
(setf (xlib:wm-protocols window) `(:wm_delete_window))
(xlib:change-property window
:WM_CLIENT_LEADER (list (xlib:window-id window))
:WINDOW 32))))
(defmethod realize-mirror ((port clx-port) (sheet unmanaged-top-level-sheet-pane))
(realize-mirror-aux port sheet
:override-redirect :on
:save-under :on
:map nil
:event-mask '(:structure-notify)))
(defmethod realize-mirror ((port clx-port) (sheet menu-button-pane))
(realize-mirror-aux port sheet
:event-mask '(:exposure
:key-press :key-release
:button-press :button-release
:enter-window :leave-window
:structure-notify
;:pointer-motion
:button-motion
:owner-grab-button)
:map (sheet-enabled-p sheet)))
(defmethod realize-mirror ((port clx-port) (sheet clim-stream-pane))
(realize-mirror-aux port sheet
:event-mask '(:exposure
:key-press :key-release
:button-press :button-release
:enter-window :leave-window
:structure-notify
:pointer-motion :pointer-motion-hint
:button-motion
:owner-grab-button)
:map (sheet-enabled-p sheet)))
(defmethod destroy-mirror ((port clx-port) (sheet mirrored-sheet-mixin))
(when (port-lookup-mirror port sheet)
(xlib:destroy-window (port-lookup-mirror port sheet))
(port-unregister-mirror port sheet (sheet-mirror sheet))))
(defmethod raise-mirror ((port clx-port) (sheet basic-sheet))
(let ((mirror (sheet-mirror sheet)))
(when (and mirror
(typep mirror 'xlib:window))
(xlib:circulate-window-up mirror))))
(defmethod bury-mirror ((port clx-port) (sheet basic-sheet))
(let ((mirror (sheet-mirror sheet)))
(when (and mirror
(typep mirror 'xlib:window))
(xlib:circulate-window-down mirror))))
(defmethod mirror-transformation ((port clx-port) mirror)
(make-translation-transformation (xlib:drawable-x mirror)
(xlib:drawable-y mirror)))
(defmethod port-set-sheet-region ((port clx-port) (graft graft) region)
(declare (ignore region))
nil)
(defmethod port-set-sheet-transformation ((port clx-port) (graft graft) transformation)
(declare (ignore transformation))
nil)
#+nil
(defmethod port-set-sheet-transformation ((port clx-port) (pane application-pane) transformation)
(declare (ignore transformation))
nil)
#+nil
(defmethod port-set-sheet-transformation ((port clx-port) (pane interactor-pane) transformation)
(declare (ignore transformation))
nil)
(defmethod port-set-sheet-transformation ((port clx-port) (sheet mirrored-sheet-mixin) transformation)
(declare (ignore transformation)) ;; why?
(break) ;obsolete now
(let ((mirror (sheet-direct-mirror sheet)))
(multiple-value-bind (tr rg) (invent-sheet-mirror-transformation-and-region sheet)
(multiple-value-bind (x y) (transform-position tr 0 0)
(multiple-value-bind (x1 y1 x2 y2) (if (eql rg +nowhere+)
(values 0 0 0 0)
(bounding-rectangle* rg))
(declare (ignore x1 y1)) ;XXX assumed to be 0
(setf (xlib:drawable-x mirror) (round x)
(xlib:drawable-y mirror) (round y))
(setf (xlib:drawable-width mirror) (clamp 1 (round x2) #xFFFF)
(xlib:drawable-height mirror) (clamp 1 (round y2) #xFFFF))
( : clear - area mirror : exposures - p t )
(invalidate-cached-transformations sheet)
)))))
(defmethod port-set-sheet-region ((port clx-port) (sheet mirrored-sheet-mixin) region)
(declare (ignore region)) ;; why?
(let ((mirror (sheet-direct-mirror sheet)))
(multiple-value-bind (tr rg) (invent-sheet-mirror-transformation-and-region sheet)
(declare (ignore tr))
(multiple-value-bind (x1 y1 x2 y2) (if (eql rg +nowhere+)
(values 0 0 0 0)
(bounding-rectangle* rg))
(declare (ignore x1 y1)) ;XXX assumed to be 0
(setf x2 (round x2))
(setf y2 (round y2))
(cond ((or (<= x2 0) (<= y2 0))
;; XXX
now X does not allow for a zero width / height window ,
;; we should unmap instead ...
;; Nevertheless we simply clamp
))
(setf (xlib:drawable-width mirror) (clamp x2 1 #xFFFF)
(xlib:drawable-height mirror) (clamp y2 1 #xFFFF))))))
(defmethod port-enable-sheet ((port clx-port) (mirror mirrored-sheet-mixin))
(xlib:map-window (sheet-direct-mirror mirror)) )
(defmethod port-disable-sheet ((port clx-port) (mirror mirrored-sheet-mixin))
(xlib:unmap-window (sheet-direct-mirror mirror)) )
(defmethod destroy-port :before ((port clx-port))
(handler-case
(xlib:close-display (clx-port-display port))
(stream-error ()
(xlib:close-display (clx-port-display port) :abort t))))
(defmethod port-motion-hints ((port clx-port) (sheet mirrored-sheet-mixin))
(let ((event-mask (xlib:window-event-mask (sheet-direct-mirror sheet))))
(if (zerop (logand event-mask
#.(xlib:make-event-mask :pointer-motion-hint)))
nil
t)))
(defmethod (setf port-motion-hints)
(val (port clx-port) (sheet mirrored-sheet-mixin))
(let* ((mirror (sheet-direct-mirror sheet))
(event-mask (xlib:window-event-mask mirror)))
(setf (xlib:window-event-mask mirror)
(if val
(logior event-mask #.(xlib:make-event-mask :pointer-motion-hint))
(logandc2 event-mask
#.(xlib:make-event-mask :pointer-motion-hint)))))
val)
; think about rewriting this macro to be nicer
(defmacro peek-event ((display &rest keys) &body body)
(let ((escape (gensym)))
`(block ,escape
(xlib:process-event ,display :timeout 0 :peek-p t :handler
#'(lambda (&key ,@keys &allow-other-keys)
(return-from ,escape
(progn
,@body)))))))
(defun decode-x-button-code (code)
(let ((button-mapping #.(vector +pointer-left-button+
+pointer-middle-button+
+pointer-right-button+
+pointer-wheel-up+
+pointer-wheel-down+
+pointer-wheel-left+
+pointer-wheel-right+))
(code (1- code)))
(when (and (>= code 0)
(< code (length button-mapping)))
(aref button-mapping code))))
From " Inter - Client Communication Conventions Manual " , Version 2.0.xf86.1 ,
section 4.1.5 :
;;
| Advice to Implementors
;; |
;; | Clients cannot distinguish between the case where a top-level
;; | window is resized and moved from the case where the window is
| resized but not moved , since a real ConfigureNotify event will be
;; | received in both cases. Clients that are concerned with keeping
;; | track of the absolute position of a top-level window should keep
;; | a piece of state indicating whether they are certain of its
| position . Upon receipt of a real ConfigureNotify event on the
;; | top-level window, the client should note that the position is
| unknown . Upon receipt of a synthetic ConfigureNotify event , the
;; | client should note the position as known, using the position in
| this event . If the client receives a KeyPress , KeyRelease ,
| ButtonPress , ButtonRelease , MotionNotify , EnterNotify , or
| LeaveNotify event on the window ( or on any descendant ) , the
;; | client can deduce the top-level window's position from the
;; | difference between the (event-x, event-y) and (root-x, root-y)
;; | coordinates in these events. Only when the position is unknown
| does the client need to use the TranslateCoordinates request to
;; | find the position of a top-level window.
;; |
;; The moral is that we need to distinguish between synthetic and
;; genuine configure-notify events. We expect that synthetic configure
;; notify events come from the window manager and state the correct
;; size and position, while genuine configure events only state the
;; correct size.
;; NOTE: Although it might be tempting to compress (consolidate)
;; events here, this is the wrong place. In our current architecture
;; the process calling this function (the port's event handler
process ) just reads the events from the X server , and does it
;; with almost no lack behind the reality. While the application
;; frame's event top level loop does the actual processing of events
;; and thus may produce lack. So the events have to be compressed in
;; the frame's event queue.
;;
;; So event compression is implemented in EVENT-QUEUE-APPEND.
;;
;; This changes for possible _real_ immediate repainting sheets,
;; here a possible solution for the port's event handler loop can be
;; to read all available events off into a temponary queue (and
;; event compression for immediate events is done there) and then
;; dispatch all events from there as usual.
;;
;;--GB
;; XXX :button code -> :button (decode-x-button-code code)
;;
;; Only button and keypress events get a :code keyword argument! For mouse
;; button events, one should use decode-x-button-code; otherwise one needs to
look at the state argument to get the current button state . The CLIM spec
;; says that pointer motion events are a subclass of pointer-event, which is
;; reasonable, but unfortunately they use the same button slot, whose value
;; should only be a single button. Yet pointer-button-state can return the
logical or of the button values ... . For now I 'll canonicalize the
;; value going into the button slot and think about adding a
pointer - event - buttons slot to pointer events . --
;;
(defvar *clx-port*)
(defun event-handler (&key display window event-key code state mode time
type width height x y root-x root-y
data override-redirect-p send-event-p hint-p
target property requestor selection
request first-keycode count
&allow-other-keys)
(declare (ignore display request first-keycode count))
(let ((sheet (and window (port-lookup-sheet *clx-port* window))))
(when sheet
(case event-key
((:key-press :key-release)
(multiple-value-bind (keyname modifier-state keysym-keyword)
(x-event-to-key-name-and-modifiers *clx-port*
event-key code state)
(make-instance (if (eq event-key :key-press)
'key-press-event
'key-release-event)
:key-name keysym-keyword
:key-character (and (characterp keyname) keyname)
:x x :y y
:graft-x root-x
:graft-y root-y
:sheet (or (frame-properties (pane-frame sheet) 'focus) sheet)
:modifier-state modifier-state :timestamp time)))
((:button-press :button-release)
(let ((modifier-state (clim-xcommon:x-event-state-modifiers *clx-port*
state)))
(make-instance (if (eq event-key :button-press)
'pointer-button-press-event
'pointer-button-release-event)
:pointer 0
:button (decode-x-button-code code) :x x :y y
:graft-x root-x
:graft-y root-y
:sheet sheet :modifier-state modifier-state
:timestamp time)))
(:enter-notify
(make-instance 'pointer-enter-event :pointer 0 :button code :x x :y y
:graft-x root-x
:graft-y root-y
:sheet sheet
:modifier-state (clim-xcommon:x-event-state-modifiers
*clx-port* state)
:timestamp time))
(:leave-notify
(make-instance (if (eq mode :ungrab)
'pointer-ungrab-event
'pointer-exit-event)
:pointer 0 :button code
:x x :y y
:graft-x root-x
:graft-y root-y
:sheet sheet
:modifier-state (clim-xcommon:x-event-state-modifiers
*clx-port* state)
:timestamp time))
;;
(:configure-notify
(cond ((and (eq (sheet-parent sheet) (graft sheet))
(graft sheet)
(not override-redirect-p)
(not send-event-p))
;; this is genuine event for a top-level sheet (with
;; override-redirect off)
;;
;; Since the root window is not our real parent, but
;; there the window managers decoration in between,
;; only the size is correct, so we need to deduce the
;; position from our idea of it.
;; I believe the code below is totally wrong, because
;; sheet-native-transformation will not be up to date.
;; Instead, query the new coordinates from the X server,
;; and later the event handler will set the correct
;; native-transformation using those. --Hefner
; (multiple-value-bind (x y) (transform-position
; (compose-transformations
; (sheet-transformation sheet)
; (sheet-native-transformation (graft sheet)))
; 0 0)
;; Easier to let X compute the position relative to the root window for us.
(multiple-value-bind (x y)
(xlib:translate-coordinates window 0 0 (clx-port-window *clx-port*))
(make-instance 'window-configuration-event
:sheet sheet
:x x
:y y
:width width :height height)))
(t
;; nothing special here
(make-instance 'window-configuration-event
:sheet sheet
:x x :y y :width width :height height))))
(:destroy-notify
(make-instance 'window-destroy-event :sheet sheet))
(:motion-notify
(let ((modifier-state (clim-xcommon:x-event-state-modifiers *clx-port*
state)))
(if hint-p
(multiple-value-bind (x y same-screen-p child mask
root-x root-y)
(xlib:query-pointer window)
(declare (ignore mask))
;; If not same-screen-p or the child is different
;; from the original event, assume we're way out of date
;; and don't return an event.
(when (and same-screen-p (not child))
(make-instance 'pointer-motion-hint-event
:pointer 0 :button code
:x x :y y
:graft-x root-x :graft-y root-y
:sheet sheet
:modifier-state modifier-state
:timestamp time)))
(progn
(make-instance 'pointer-motion-event
:pointer 0 :button code
:x x :y y
:graft-x root-x
:graft-y root-y
:sheet sheet
:modifier-state modifier-state
:timestamp time)))))
;;
((:exposure :display :graphics-exposure)
Notes :
;; . Do not compare count with 0 here, last rectangle in an
;; :exposure event sequence does not cover the whole region.
;;
;; . Do not transform the event region here, since
;; WINDOW-EVENT-REGION does it already. And rightfully so.
;; (think about changing a sheet's native transformation).
;;--GB
;;
says :
One of the lisps is bogusly sending a : display event instead of an
: exposure event . I do n't remember if it 's CMUCL or SBCL . So the
;; :display event should be left in.
;;
(make-instance 'window-repaint-event
:timestamp time
:sheet sheet
:region (make-rectangle* x y (+ x width) (+ y height))))
;;
(:selection-notify
(make-instance 'clx-selection-notify-event
:sheet sheet
:selection selection
:target target
:property property))
(:selection-clear
(make-instance 'selection-clear-event
:sheet sheet
:selection selection))
(:selection-request
(make-instance 'clx-selection-request-event
:sheet sheet
:selection selection
:requestor requestor
:target target
:property property
:timestamp time))
(:client-message
(port-client-message sheet time type data))
(t
(unless (xlib:event-listen (clx-port-display *clx-port*))
(xlib:display-force-output (clx-port-display *clx-port*)))
nil)))))
;; Handling of X client messages
(defmethod port-client-message (sheet time (type (eql :wm_protocols)) data)
(port-wm-protocols-message sheet time
(xlib:atom-name (slot-value *clx-port* 'display) (aref data 0))
data))
(defmethod port-client-message (sheet time (type t) data)
(warn "Unprocessed client message: ~:_type = ~S;~:_ data = ~S;~_ sheet = ~S."
type data sheet))
;;; this client message is only necessary if we advertise that we
;;; participate in the :WM_TAKE_FOCUS protocol; otherwise, the window
;;; manager is responsible for all setting of input focus for us. If
;;; we want to do something more complicated with server input focus,
;;; then this method should be adjusted appropriately and the
top - level - sheet REALIZE - MIRROR method should be adjusted to add
: WM_TAKE_FOCUS to XLIB : WM - PROTOCOLS . CSR , 2009 - 02 - 18
(defmethod port-wm-protocols-message (sheet time (message (eql :wm_take_focus)) data)
(let ((timestamp (elt data 1))
(mirror (sheet-mirror sheet)))
(when mirror
(xlib:set-input-focus (clx-port-display *clx-port*)
mirror :parent timestamp))
nil))
(defmethod port-wm-protocols-message (sheet time (message (eql :wm_delete_window)) data)
(declare (ignore data))
(make-instance 'window-manager-delete-event :sheet sheet :timestamp time))
(defmethod port-wm-protocols-message (sheet time (message t) data)
(warn "Unprocessed WM Protocols message: ~:_message = ~S;~:_ data = ~S;~_ sheet = ~S."
message data sheet))
(defmethod get-next-event ((port clx-port) &key wait-function (timeout nil))
(declare (ignore wait-function))
(let* ((*clx-port* port)
(display (clx-port-display port)))
(unless (xlib:event-listen display)
(xlib:display-force-output (clx-port-display port)))
; temporary solution
(or (xlib:process-event (clx-port-display port) :timeout timeout :handler #'event-handler :discard-p t)
:timeout)))
[ Mike ] Timeout and wait - functions are both implementation
;; specific and hence best done in the backends.
(defmethod make-graft ((port clx-port) &key (orientation :default) (units :device))
(let ((graft (make-instance 'clx-graft
:port port :mirror (clx-port-window port)
:orientation orientation :units units)))
(setf (sheet-region graft) (make-bounding-rectangle 0 0 (xlib:screen-width (clx-port-screen port)) (xlib:screen-height (clx-port-screen port))))
(push graft (port-grafts port))
graft))
(defmethod make-medium ((port clx-port) sheet)
(make-instance 'clx-medium
;; :port port
;; :graft (find-graft :port port)
:sheet sheet))
(defconstant *clx-text-families* '(:fix "adobe-courier"
:serif "adobe-times"
:sans-serif "adobe-helvetica"))
(defconstant *clx-text-faces* '(:roman "medium-r"
:bold "bold-r"
:italic "medium-i"
:bold-italic "bold-i"
:italic-bold "bold-i"))
(defparameter *clx-text-sizes* '(:normal 14
:tiny 8
:very-small 10
:small 12
:large 18
:very-large 20
:huge 24))
(defparameter *clx-text-family+face-map*
'(:fix
#-nil
("adobe-courier"
(:roman "medium-r"
:bold "bold-r"
:italic "medium-o"
:bold-italic "bold-o"
:italic-bold "bold-o"))
#+nil
("*-lucidatypewriter"
(:roman "medium-r"
:bold "bold-r"
:italic "medium-r"
:bold-italic "bold-r"
:italic-bold "bold-r"))
:sans-serif
("adobe-helvetica"
(:roman "medium-r"
:bold "bold-r"
:italic "medium-o"
:bold-italic "bold-o"
:italic-bold "bold-o"))
:serif
("adobe-times"
(:roman "medium-r"
:bold "bold-r"
:italic "medium-i"
:bold-italic "bold-i"
:italic-bold "bold-i")) ))
(defun open-font (display font-name)
(let ((fonts (xlib:list-font-names display font-name :max-fonts 1)))
(if fonts
(xlib:open-font display (first fonts))
(xlib:open-font display "fixed"))))
(defmethod text-style-mapping ((port clx-port) text-style
&optional character-set)
(declare (ignore character-set))
(let ((table (port-text-style-mappings port)))
(or (car (gethash text-style table))
(multiple-value-bind (family face size)
(text-style-components text-style)
(destructuring-bind (family-name face-table)
(if (stringp family)
(list family *clx-text-faces*)
(or (getf *clx-text-family+face-map* family)
(getf *clx-text-family+face-map* :fix)))
(let* ((face-name (if (stringp face)
face
(or (getf face-table
(if (listp face)
(intern (format nil "~A-~A"
(symbol-name (first face))
(symbol-name (second face)))
:keyword)
face))
(getf *clx-text-faces* :roman))))
(size-number (if (numberp size)
(round size)
(or (getf *clx-text-sizes* size)
(getf *clx-text-sizes* :normal)))))
(flet ((try (encoding)
(let* ((fn (format nil "-~A-~A-*-*-~D-*-*-*-*-*-~A"
family-name face-name size-number
encoding))
(font (open-font (clx-port-display port) fn)))
(and font (cons fn font)))))
(let ((fn-font
(or
(and (> char-code-limit #x100) (try "iso10646-1"))
(try "iso8859-1")
(try "*-*"))))
(setf (gethash text-style table) fn-font)
(car fn-font)))))))))
(defmethod (setf text-style-mapping) (font-name (port clx-port)
(text-style text-style)
&optional character-set)
(declare (ignore character-set))
(setf (gethash text-style (port-text-style-mappings port))
(cons font-name (open-font (clx-port-display port) font-name)))
font-name)
(defun text-style-to-X-font (port text-style)
(let ((text-style (parse-text-style text-style)))
(text-style-mapping port text-style)
(cdr (gethash text-style (port-text-style-mappings port)))))
(defmethod port-character-width ((port clx-port) text-style char)
(let* ((font (text-style-to-X-font port text-style))
(width (xlib:char-width font (char-code char))))
width))
(defmethod port-string-width ((port clx-port) text-style string &key (start 0) end)
(xlib:text-width (text-style-to-X-font port text-style)
string :start start :end end))
(defmethod X-pixel ((port clx-port) color)
(let ((table (slot-value port 'color-table)))
(or (gethash color table)
(setf (gethash color table)
(multiple-value-bind (r g b) (color-rgb color)
(xlib:alloc-color (xlib:screen-default-colormap
(clx-port-screen port))
(xlib:make-color :red r :green g :blue b)))))))
(defmethod port-mirror-width ((port clx-port) sheet)
(let ((mirror (port-lookup-mirror port sheet)))
(xlib:drawable-width mirror)))
(defmethod port-mirror-height ((port clx-port) sheet)
(let ((mirror (port-lookup-mirror port sheet)))
(xlib:drawable-height mirror)))
(defmethod graft ((port clx-port))
(first (port-grafts port)))
;;; Pixmap
(defmethod realize-mirror ((port clx-port) (pixmap pixmap))
(when (null (port-lookup-mirror port pixmap))
(let* ((window (sheet-direct-mirror (pixmap-sheet pixmap)))
(pix (xlib:create-pixmap
:width (round (pixmap-width pixmap))
:height (round (pixmap-height pixmap))
:depth (xlib:drawable-depth window)
:drawable window)))
(port-register-mirror port pixmap pix))
(values)))
(defmethod destroy-mirror ((port clx-port) (pixmap pixmap))
(when (port-lookup-mirror port pixmap)
(xlib:free-pixmap (port-lookup-mirror port pixmap))
(port-unregister-mirror port pixmap (port-lookup-mirror port pixmap))))
(defmethod port-allocate-pixmap ((port clx-port) sheet width height)
(let ((pixmap (make-instance 'mirrored-pixmap
:sheet sheet
:width width
:height height
:port port)))
(when (sheet-grafted-p sheet)
(realize-mirror port pixmap))
pixmap))
(defmethod port-deallocate-pixmap ((port clx-port) pixmap)
(when (port-lookup-mirror port pixmap)
(destroy-mirror port pixmap)))
;; Top-level-sheet
;; this is evil.
(defmethod allocate-space :after ((pane top-level-sheet-pane) width height)
(when (sheet-direct-mirror pane)
(with-slots (space-requirement) pane
'(setf (xlib:wm-normal-hints (sheet-direct-mirror pane))
(xlib:make-wm-size-hints
:width (round width)
:height (round height)
:max-width (min 65535 (round (space-requirement-max-width space-requirement)))
:max-height (min 65535 (round (space-requirement-max-height space-requirement)))
:min-width (round (space-requirement-min-width space-requirement))
:min-height (round (space-requirement-min-height space-requirement)))))))
(defmethod pointer-position ((pointer clx-pointer))
(let* ((port (port pointer))
(sheet (port-pointer-sheet port)))
(when sheet
(multiple-value-bind (x y same-screen-p)
(xlib:query-pointer (sheet-direct-mirror sheet))
(when same-screen-p
(untransform-position (sheet-native-transformation sheet) x y))))))
;;; pointer button bits in the state mask
;;; Happily, The McCLIM pointer constants correspond directly to the X
;;; constants.
(defconstant +right-button-mask+ #x100)
(defconstant +middle-button-mask+ #x200)
(defconstant +left-button-mask+ #x400)
(defconstant +wheel-up-mask+ #x800)
(defconstant +wheel-down-mask+ #x1000)
(defmethod pointer-button-state ((pointer clx-pointer))
(multiple-value-bind (x y same-screen-p child mask)
(xlib:query-pointer (clx-port-window (port pointer)))
(declare (ignore x y same-screen-p child))
(ldb (byte 5 8) mask)))
In button events we do n't want to see more than one button , according to
;;; the spec, so pick a canonical ordering. :P The mask is that state mask
;;; from an X event.
(defun button-from-state (mask)
(cond ((logtest +right-button-mask+ mask)
+pointer-right-button+)
((logtest +middle-button-mask+ mask)
+pointer-middle-button+)
((logtest +left-button-mask+ mask)
+pointer-left-button+)
((logtest +wheel-up-mask+ mask)
+pointer-wheel-up+)
((logtest +wheel-down-mask+ mask)
+pointer-wheel-down+)
(t 0)))
#+nil
(defmethod pointer-modifier-state ((pointer clx-pointer))
(multiple-value-bind (x y same-screen-p child mask)
(xlib:query-pointer (clx-port-window (port pointer)))
(declare (ignore x y same-screen-p child))
(clim-xcommon:x-event-state-modifiers (port pointer) mask)))
(defmethod port-modifier-state ((port clx-port))
(multiple-value-bind (x y same-screen-p child mask)
(xlib:query-pointer (clx-port-window port))
(declare (ignore x y same-screen-p child))
(clim-xcommon:x-event-state-modifiers port mask)))
XXX Should we rely on port - pointer - sheet being correct ? --
(defmethod synthesize-pointer-motion-event ((pointer clx-pointer))
(let* ((port (port pointer))
(sheet (port-pointer-sheet port)))
(when sheet
(let ((mirror (sheet-direct-mirror sheet)))
(when mirror
(multiple-value-bind (x y same-screen-p child mask root-x root-y)
(xlib:query-pointer mirror)
(declare (ignore child))
(when same-screen-p
(make-instance
'pointer-motion-event
:pointer 0 :button (button-from-state mask)
:x x :y y
:graft-x root-x
:graft-y root-y
:sheet sheet
:modifier-state (clim-xcommon:x-event-state-modifiers port mask)
;; The event initialization code will give us a
;; reasonable timestamp.
:timestamp 0))))))))
(defmethod port-frame-keyboard-input-focus ((port clx-port) frame)
(frame-properties frame 'focus))
(defmethod (setf port-frame-keyboard-input-focus) (focus (port clx-port) frame)
(setf (frame-properties frame 'focus) focus))
(defmethod port-force-output ((port clx-port))
(xlib:display-force-output (clx-port-display port)))
FIXME : What happens when CLIM code calls tracking - pointer recursively ?
I expect the : grab - pointer call will fail , and so the call to
;; xlib:ungrab-pointer will ungrab prematurely.
;;; XXX Locks around pointer-grab-sheet!!!
(defmethod port-grab-pointer ((port clx-port) pointer sheet)
;; FIXME: Use timestamps?
(let ((grab-result (xlib:grab-pointer
(sheet-mirror sheet)
'(:button-press :button-release
:leave-window :enter-window
:pointer-motion :pointer-motion-hint)
;; Probably we want to set :cursor here..
:owner-p t)))
(if (eq grab-result :success)
(setf (pointer-grab-sheet port) sheet)
nil)))
(defmethod port-ungrab-pointer ((port clx-port) pointer sheet)
(declare (ignore pointer))
(when (eq (pointer-grab-sheet port) sheet)
(xlib:ungrab-pointer (clx-port-display port))
(setf (pointer-grab-sheet port) nil)))
(defmethod distribute-event :around ((port clx-port) event)
(let ((grab-sheet (pointer-grab-sheet port)))
(if grab-sheet
(queue-event grab-sheet event)
(call-next-method))))
(defmethod set-sheet-pointer-cursor ((port clx-port) sheet cursor)
(let ((cursor (gethash cursor (clx-port-cursor-table port))))
(when cursor
(setf (xlib:window-cursor (sheet-mirror sheet)) cursor))))
;;; Modifier cache support
(defmethod clim-xcommon:modifier-mapping ((port clx-port))
(let* ((display (clx-port-display port))
(x-modifiers (multiple-value-list (xlib:modifier-mapping display)))
(modifier-map (make-array (length x-modifiers) :initial-element nil)))
(loop
for keycodes in x-modifiers
for i from 0
do (setf (aref modifier-map i)
(mapcan (lambda (keycode)
(modifier-keycode->keysyms display keycode))
keycodes)))
modifier-map))
;;;; Backend component of text selection support
;;; Event classes
(defclass clx-selection-notify-event (selection-notify-event)
((target :initarg :target
:reader selection-event-target)
(property :initarg :property
:reader selection-event-property)))
(defclass clx-selection-request-event (selection-request-event)
((target :initarg :target
:reader selection-event-target)
(property :initarg :property
:reader selection-event-property)))
;;; Conversions
;; we at least want to support:
;;; :TEXT, :STRING
;;;
;;; :UTF8_STRING
;;; As seen from xterm [make that the preferred encoding]
;;;
;;; :COMPOUND_TEXT
Perhaps relatively easy to produce , hard to grok .
;;;
;;; :TARGETS
;;; Clients want legitimately to find out what we support.
;;;
;;; :TIMESTAMP
;;; Clients want to know when we took ownership of the selection.
Utilities
(defun utf8-string-encode (code-points)
(let ((res (make-array (length code-points)
:adjustable t
:fill-pointer 0)))
(map 'nil
(lambda (code-point)
(cond ((< code-point (expt 2 7))
(vector-push-extend code-point res))
((< code-point (expt 2 11))
(vector-push-extend (logior #b11000000 (ldb (byte 5 6) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 0) code-point)) res))
((< code-point (expt 2 16))
(vector-push-extend (logior #b11100000 (ldb (byte 4 12) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 6) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 0) code-point)) res))
((< code-point (1- (expt 2 21)))
(vector-push-extend (logior #b11110000 (ldb (byte 3 18) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 12) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 6) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 0) code-point)) res))
((< code-point (1- (expt 2 26)))
(vector-push-extend (logior #b11110000 (ldb (byte 2 24) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 18) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 12) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 6) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 0) code-point)) res))
((< code-point (1- (expt 2 31)))
(vector-push-extend (logior #b11110000 (ldb (byte 1 30) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 24) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 18) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 12) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 6) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 0) code-point)) res))
(t
(error "Bad code point: ~D." code-point))))
code-points)
res))
Protocol functions
(defmethod bind-selection ((port clx-port) window &optional time)
(xlib:set-selection-owner
(xlib:window-display (sheet-direct-mirror window))
:primary (sheet-direct-mirror window) time)
(eq (xlib:selection-owner
(xlib:window-display (sheet-direct-mirror window))
:primary)
(sheet-direct-mirror window)))
(defmethod release-selection ((port clx-port) &optional time)
(xlib:set-selection-owner
(clx-port-display port)
:primary nil time)
(setf (selection-owner port) nil)
(setf (selection-timestamp port) nil))
(defmethod request-selection ((port clx-port) requestor time)
(xlib:convert-selection :primary :STRING requestor :bounce time))
(defmethod get-selection-from-event ((port clx-port) (event clx-selection-notify-event))
; (describe event *trace-output*)
(if (null (selection-event-property event))
(progn
(format *trace-output* "~&;; Oops, selection-notify property is null. Trying the cut buffer instead..~%")
(xlib:cut-buffer (clx-port-display port)))
(map 'string #'code-char
(xlib:get-property (sheet-direct-mirror (event-sheet event))
(selection-event-property event)
;; :type :text
:delete-p t
:result-type 'vector))))
;; Incredibly crappy broken unportable Latin 1 encoder which should be
;; replaced by various implementation-specific versions.
(flet ((latin1-code-p (x)
(not (or (< x 9) (< 10 x 32) (< #x7f x #xa0) (> x 255)))))
(defun string-encode (string)
(delete-if-not #'latin1-code-p (map 'vector #'char-code string)))
(defun exactly-encodable-as-string-p (string)
(every #'latin1-code-p (map 'vector #'char-code string))))
TODO : INCR property ?
;;;
FIXME : per ICCCM we MUST support : MULTIPLE
(defmethod send-selection ((port clx-port) (event clx-selection-request-event) string)
(let ((requestor (selection-event-requestor event))
(property (selection-event-property event))
(target (selection-event-target event))
(time (event-timestamp event)))
(when (null property)
(format *trace-output* "~&* Requestor property is null! *~%"))
#+nil ; debugging output
(progn
(describe event *trace-output*)
(force-output *trace-output*))
(flet ((send-event (&key target (property property))
;; debugging output, but the KDE Klipper client turns out
;; to poll other clients for selection, which means it
;; would be bad to print at every request.
#+nil
(format *trace-output*
"~&;; clim-clx::send-selection - Requested target ~A, sent ~A to property ~A. time ~S~%"
(selection-event-target event)
target
property time)
(xlib:send-event requestor
:selection-notify nil
:window requestor
:event-window requestor
:selection (climi::selection-event-selection event)
:target target
:property property
:time time)))
(case target
((:UTF8_STRING)
(xlib:change-property requestor property
(utf8-string-encode
(map 'vector #'char-code string))
:UTF8_STRING 8)
(send-event :target :UTF8_STRING))
((:STRING :COMPOUND_TEXT)
(xlib:change-property requestor property
(string-encode string)
target 8)
(send-event :target target))
((:TEXT)
(cond
((exactly-encodable-as-string-p string)
(xlib:change-property requestor property
(string-encode string)
:STRING 8)
(send-event :target :STRING))
(t
(xlib:change-property requestor property
(utf8-string-encode
(map 'vector #'char-code string))
:UTF8_STRING 8)
(send-event :target :UTF8_STRING))))
((:TARGETS)
(let* ((display (clx-port-display port))
(targets (mapcar (lambda (x) (xlib:intern-atom display x))
'(:TARGETS :STRING :TEXT :UTF8_STRING
:COMPOUND_TEXT :TIMESTAMP))))
(xlib:change-property requestor property targets target 32))
(send-event :target :TARGETS))
((:TIMESTAMP)
(when (null (selection-timestamp port))
(format *trace-output* "~&;; selection-timestamp is null!~%"))
(xlib:change-property requestor property
(list (selection-timestamp port))
target 32)
(send-event :target :TIMESTAMP))
(t
(format *trace-output*
"~&;; Warning, unhandled type \"~A\". ~
Sending property NIL to target.~%" target)
(send-event :target target :property nil))))
(xlib:display-force-output (xlib:window-display requestor))))
XXX CLX in ACL does n't use local sockets , so here 's a fix . This is gross
and should obviously be included in ' clx and portable clx , but I
;;; believe that enough users will find that their X servers don't listen for
;;; TCP connections that it is worthwhile to include this code here
;;; temporarily.
#+allegro
(defun xlib::open-x-stream (host display protocol)
(declare (ignore protocol)) ;; Derive from host
(let ((stream (if (or (string= host "") (string= host "unix"))
(socket:make-socket
:address-family :file
:remote-filename (format nil "/tmp/.X11-unix/X~D" display)
:format :binary)
(socket:make-socket :remote-host (string host)
:remote-port (+ xlib::*x-tcp-port*
display)
:format :binary))))
(if (streamp stream)
stream
(error "Cannot connect to server: ~A:~D" host display))))
;;;; Font listing implementation:
(defclass clx-font-family (clim-extensions:font-family)
((all-faces :initform nil
:accessor all-faces
:reader clim-extensions:font-family-all-faces)))
(defclass clx-font-face (clim-extensions:font-face)
((all-sizes :initform nil
:accessor all-sizes
:reader clim-extensions:font-face-all-sizes)))
(defun split-font-name (name)
(loop
repeat 12
for next = (position #\- name :start 0)
:then (position #\- name :start (1+ next))
and prev = nil then next
while next
when prev
collect (subseq name (1+ prev) next)))
(defun reload-font-table (port)
(let ((table (make-hash-table :test 'equal)))
(dolist (font (xlib:list-font-names (clx-port-display port) "*"))
(destructuring-bind
(&optional foundry family weight slant setwidth style pixelsize
yresolution
spacing averagewidth registry encoding
)
(split-font-name font)
(declare (ignore setwidth style ignore))
(when family
(let* ((family-name (format nil "~A ~A" foundry family))
(family-instance
(or (gethash family-name table)
(setf (gethash family-name table)
(make-instance 'clx-font-family
:port port
:name family-name))))
(face-name (format nil "~A ~A" weight slant))
(face-instance
(find face-name (all-faces family-instance)
:key #'clim-extensions:font-face-name
:test #'equal)))
(unless face-instance
(setf face-instance
(make-instance 'clx-font-face
:family family-instance
:name face-name))
(push face-instance (all-faces family-instance)))
(pushnew (parse-integer
FIXME : Python thinks pixelsize is NIL , resulting
;; in a full WARNING. Let's COERCE to make it work.
(coerce pixelsize 'string))
(all-sizes face-instance))))))
(setf (font-families port)
(sort (loop
for family being each hash-value in table
do
(setf (all-faces family)
(sort (all-faces family)
#'string<
:key #'clim-extensions:font-face-name))
(dolist (face (all-faces family))
(setf (all-sizes face) (sort (all-sizes face) #'<)))
collect family)
#'string<
:key #'clim-extensions:font-family-name))))
(defmethod clim-extensions:port-all-font-families
((port clx-port) &key invalidate-cache)
(when (or (not (slot-boundp port 'font-families)) invalidate-cache)
(reload-font-table port))
(font-families port))
(defmethod clim-extensions:font-face-scalable-p ((face clx-font-face))
nil)
(defun make-unfriendly-name (str)
(substitute #\- #\space str))
(defmethod clim-extensions:font-face-text-style
((face clx-font-face) &optional size)
(make-text-style (make-unfriendly-name
(clim-extensions:font-family-name
(clim-extensions:font-face-family face)))
(make-unfriendly-name
(clim-extensions:font-face-name face))
size))
| null | https://raw.githubusercontent.com/slyrus/mcclim-old/354cdf73c1a4c70e619ccd7d390cb2f416b21c1a/Backends/CLX/port.lisp | lisp | -*- Mode: Lisp; Package: CLIM-CLX; -*-
Iban Hatchondo ()
This library is free software; you can redistribute it and/or
either
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
License along with this library; if not, write to the
even number, when in doubt.
rounding" gives you consistent results.
while in X11 they are at the centers. We don't do much about the
work well.
Perhaps this belongs elsewhere
We have a couple of problems, one is character-sets.
Unfortunately no-one seems to define what a character-set is, really.
So, I define a character-set as being the same as a language, since
a language is far more useful.
This is important, since a given language may include many characters
from what might be traditionally considered disparate character-sets.
Also it is important, since we cannot simply map a character to a glyph
in a language independent fashion, since the style of the character may
have some language component.
In our rendering/translation mechanism we switch fonts when a font fails
to supply the glyph that we want. So, to facilitate this we need a given
fontset with a set of disjoint ranges mapped to particular font/encoding
pairs.
For the time being, an alist should do here.
We assume that we're given disjoint ranges for now, which is optimistic.
Currently building a fontset will be a tricksy business, think about how
to generalise this for the future.
this is to inform the text renderer which fontset it should be using.
it is a complement to the graphics-context stuff, effectively.
the #'translate uses/needs this to switch fonts
of the form ((start . stop) font translator)
this code courtesy telent-clx.
-> tr region
I am declaring BORDER-WIDTH ignore to get a cleaner build, but I
don't really understand why the use of it is commented out in favor
border-width
Evil Hack -- but helps enormously (Has anybody
a good idea how to sneak the concept of
(rotatef (medium-background (sheet-medium sheet)) (medium-foreground (sheet-medium sheet)))
(border-pane-width sheet)
SHEET and its descendants are grafted, but unmirrored :-\ -- APD
:pointer-motion
why?
obsolete now
XXX assumed to be 0
why?
XXX assumed to be 0
XXX
we should unmap instead ...
Nevertheless we simply clamp
think about rewriting this macro to be nicer
|
| Clients cannot distinguish between the case where a top-level
| window is resized and moved from the case where the window is
| received in both cases. Clients that are concerned with keeping
| track of the absolute position of a top-level window should keep
| a piece of state indicating whether they are certain of its
| top-level window, the client should note that the position is
| client should note the position as known, using the position in
| client can deduce the top-level window's position from the
| difference between the (event-x, event-y) and (root-x, root-y)
| coordinates in these events. Only when the position is unknown
| find the position of a top-level window.
|
The moral is that we need to distinguish between synthetic and
genuine configure-notify events. We expect that synthetic configure
notify events come from the window manager and state the correct
size and position, while genuine configure events only state the
correct size.
NOTE: Although it might be tempting to compress (consolidate)
events here, this is the wrong place. In our current architecture
the process calling this function (the port's event handler
with almost no lack behind the reality. While the application
frame's event top level loop does the actual processing of events
and thus may produce lack. So the events have to be compressed in
the frame's event queue.
So event compression is implemented in EVENT-QUEUE-APPEND.
This changes for possible _real_ immediate repainting sheets,
here a possible solution for the port's event handler loop can be
to read all available events off into a temponary queue (and
event compression for immediate events is done there) and then
dispatch all events from there as usual.
--GB
XXX :button code -> :button (decode-x-button-code code)
Only button and keypress events get a :code keyword argument! For mouse
button events, one should use decode-x-button-code; otherwise one needs to
says that pointer motion events are a subclass of pointer-event, which is
reasonable, but unfortunately they use the same button slot, whose value
should only be a single button. Yet pointer-button-state can return the
value going into the button slot and think about adding a
this is genuine event for a top-level sheet (with
override-redirect off)
Since the root window is not our real parent, but
there the window managers decoration in between,
only the size is correct, so we need to deduce the
position from our idea of it.
I believe the code below is totally wrong, because
sheet-native-transformation will not be up to date.
Instead, query the new coordinates from the X server,
and later the event handler will set the correct
native-transformation using those. --Hefner
(multiple-value-bind (x y) (transform-position
(compose-transformations
(sheet-transformation sheet)
(sheet-native-transformation (graft sheet)))
0 0)
Easier to let X compute the position relative to the root window for us.
nothing special here
If not same-screen-p or the child is different
from the original event, assume we're way out of date
and don't return an event.
. Do not compare count with 0 here, last rectangle in an
:exposure event sequence does not cover the whole region.
. Do not transform the event region here, since
WINDOW-EVENT-REGION does it already. And rightfully so.
(think about changing a sheet's native transformation).
--GB
:display event should be left in.
Handling of X client messages
this client message is only necessary if we advertise that we
participate in the :WM_TAKE_FOCUS protocol; otherwise, the window
manager is responsible for all setting of input focus for us. If
we want to do something more complicated with server input focus,
then this method should be adjusted appropriately and the
temporary solution
specific and hence best done in the backends.
:port port
:graft (find-graft :port port)
Pixmap
Top-level-sheet
this is evil.
pointer button bits in the state mask
Happily, The McCLIM pointer constants correspond directly to the X
constants.
the spec, so pick a canonical ordering. :P The mask is that state mask
from an X event.
The event initialization code will give us a
reasonable timestamp.
xlib:ungrab-pointer will ungrab prematurely.
XXX Locks around pointer-grab-sheet!!!
FIXME: Use timestamps?
Probably we want to set :cursor here..
Modifier cache support
Backend component of text selection support
Event classes
Conversions
we at least want to support:
:TEXT, :STRING
:UTF8_STRING
As seen from xterm [make that the preferred encoding]
:COMPOUND_TEXT
:TARGETS
Clients want legitimately to find out what we support.
:TIMESTAMP
Clients want to know when we took ownership of the selection.
(describe event *trace-output*)
:type :text
Incredibly crappy broken unportable Latin 1 encoder which should be
replaced by various implementation-specific versions.
debugging output
debugging output, but the KDE Klipper client turns out
to poll other clients for selection, which means it
would be bad to print at every request.
believe that enough users will find that their X servers don't listen for
TCP connections that it is worthwhile to include this code here
temporarily.
Derive from host
Font listing implementation:
in a full WARNING. Let's COERCE to make it work. |
( c ) copyright 1998,1999,2000 by ( )
( c ) copyright 2000,2001 by
( )
( )
modify it under the terms of the GNU Library General Public
version 2 of the License , or ( at your option ) any later version .
Library General Public License for more details .
You should have received a copy of the GNU Library General Public
Free Software Foundation , Inc. , 59 Temple Place - Suite 330 ,
Boston , MA 02111 - 1307 USA .
(in-package :clim-clx)
(declaim (inline round-coordinate))
(defun round-coordinate (x)
"Function used for rounding coordinates."
We use " mercantile rounding " , instead of the CL round to nearest
Reason : As the CLIM drawing model is specified , you quite often
want to operate with coordinates , which are multiples of 1/2 .
Using CL : ROUND gives you " random " results . Using " mercantile
Note that CLIM defines pixel coordinates to be at the corners ,
discrepancy , but rounding up at half pixel boundaries seems to
(floor (+ x .5)))
CLX - PORT class
(defclass clx-pointer (standard-pointer)
((cursor :accessor pointer-cursor :initform :upper-left)))
(defclass fontset () (
(name
:type simple-string
:initform "fontset"
:initarg :name
:reader fontset-name)
(default-font
:initform nil
:reader fontset-default-font)
(ranges
:type list
:initform nil
:initarg :ranges)
(ascent
:type integer
:initform 0
:initarg :ascent
:reader fontset-ascent)
(descent
:type integer
:initform 0
:initarg :ascent
:reader fontset-descent)
(height
:type integer
:initform 0
:initarg :ascent
:reader fontset-height)
(width
:type integer
:initform 0
:initarg :ascent
:reader fontset-width)))
(defvar *fontset* nil)
(defmethod print-object ((object fontset) stream)
(format stream "#<fontset ~A>" (fontset-name object)))
(defmacro make-fontset (name &body entries)
(let ((fontset (gensym)))
`(let ((,fontset (make-instance 'fontset :name ,name)))
,@(mapcar (lambda (entry)
(destructuring-bind (start finish font translator) entry
`(set-fontset-range ,fontset ,font ,translator ,start ,finish)))
entries)
,fontset)))
(defmethod set-fontset-range ((fontset fontset) font translator start finish)
should check ordering invariants , disjointity , etc
(with-slots (ranges ascent descent height default-font) fontset
(unless default-font
(setf default-font font))
(push (list (cons start finish) font translator) ranges)
(setf ascent (max (xlib:font-ascent font) ascent))
(setf descent (max (xlib:font-descent font) descent))
(setf height (+ ascent descent))))
(defun fontset-point-width (point &optional (fontset *fontset*))
(let ((entry (fontset-point point fontset)))
(if entry
(destructuring-bind ((range-start . range-stop) font translator) entry
(declare (ignore range-start range-stop))
(xlib:char-width font (funcall translator point)))
0)))
(defun fontset-point (point &optional (fontset *fontset*))
(%fontset-point fontset point))
(defmethod %fontset-point ((fontset fontset) point)
(with-slots (ranges) fontset
(assoc point ranges :test (lambda (point range)
(<= (car range) point (cdr range))))))
(defclass clx-port (clim-xcommon:keysym-port-mixin basic-port)
((display :initform nil
:accessor clx-port-display)
(screen :initform nil
:accessor clx-port-screen)
(window :initform nil
:accessor clx-port-window)
(color-table :initform (make-hash-table :test #'eq))
(cursor-table :initform (make-hash-table :test #'eq)
:accessor clx-port-cursor-table)
(design-cache :initform (make-hash-table :test #'eq))
(pointer :reader port-pointer)
(pointer-grab-sheet :accessor pointer-grab-sheet :initform nil)
(selection-owner :initform nil :accessor selection-owner)
(selection-timestamp :initform nil :accessor selection-timestamp)
(font-families :accessor font-families)))
(defun automagic-clx-server-path ()
(let ((name (get-environment-variable "DISPLAY")))
(assert name (name)
"Environment variable DISPLAY is not set")
(slash-i (or (position #\/ name) -1))
(colon-i (position #\: name :start (1+ slash-i)))
(decnet-colon-p (eql (elt name (1+ colon-i)) #\:))
(host (subseq name (1+ slash-i) colon-i))
(dot-i (and colon-i (position #\. name :start colon-i)))
(display (and colon-i
(parse-integer name
:start (if decnet-colon-p
(+ colon-i 2)
(1+ colon-i))
:end dot-i)))
(screen (and dot-i
(parse-integer name :start (1+ dot-i))))
(protocol
(cond ((or (string= host "") (string-equal host "unix")) :local)
(decnet-colon-p :decnet)
((> slash-i -1) (intern
(string-upcase (subseq name 0 slash-i))
:keyword))
(t :internet))))
(list :clx
:host host
:display-id (or display 0)
:screen-id (or screen 0)
:protocol protocol))))
(defun helpfully-automagic-clx-server-path ()
(restart-case (automagic-clx-server-path)
(use-localhost ()
:report "Use local unix display"
(parse-clx-server-path '(:clx :host "" :protocol :unix)))))
(defun parse-clx-server-path (path)
(pop path)
(if path
(list :clx
:host (getf path :host "localhost")
:display-id (getf path :display-id 0)
:screen-id (getf path :screen-id 0)
:protocol (getf path :protocol :internet))
(helpfully-automagic-clx-server-path)))
(setf (get :x11 :port-type) 'clx-port)
(setf (get :x11 :server-path-parser) 'parse-clx-server-path)
(setf (get :clx :port-type) 'clx-port)
(setf (get :clx :server-path-parser) 'parse-clx-server-path)
(defmethod initialize-instance :after ((port clx-port) &rest args)
(declare (ignore args))
(push (make-instance 'clx-frame-manager :port port) (slot-value port 'frame-managers))
(setf (slot-value port 'pointer)
(make-instance 'clx-pointer :port port))
(initialize-clx port))
(defmethod print-object ((object clx-port) stream)
(print-unreadable-object (object stream :identity t :type t)
(when (slot-boundp object 'display)
(let ((display (slot-value object 'display)))
(when display
(format stream "~S ~S ~S ~S"
:host (xlib:display-host display)
:display-id (xlib:display-display display)))))))
(defun clx-error-handler (display error-name &rest args &key major &allow-other-keys)
42 is SetInputFocus , we ignore match - errors from that
(eq error-name 'xlib:match-error))
(format *error-output* "Received CLX ~A in process ~W~%"
error-name (clim-sys:process-name (clim-sys:current-process)))
(apply #'xlib:default-error-handler display error-name args)))
(defvar *clx-cursor-mapping*
These are taken from the Franz CLIM User 's Guide
(:busy 150)
(:button 60)
(:default 68)
(:horizontal-scroll 108)
(:horizontal-thumb 108)
(:lower-left 12)
(:lower-right 14)
(:move 52)
(:position 130)
(:prompt 152)
(:scroll-down 106)
(:scroll-left 110)
(:scroll-right 112)
(:scroll-up 114)
(:upper-left 134)
(:upper-right 136)
(:vertical-scroll 116)
(:vertical-thumb 116)
The following are not in the docs , but might be useful .
(:i-beam 152)
(:vertical-pointer 22)
(:pencil 86)
(:rotate 50)
(:choose 60)))
(defun make-cursor-table (port)
(declare (optimize (safety 3) (debug 3) (speed 0) (space 0)))
(let ((font (xlib:open-font (clx-port-display port) "cursor")))
(loop for (symbol code) in *clx-cursor-mapping*
do (setf (gethash symbol (clx-port-cursor-table port))
(xlib:create-glyph-cursor :foreground (xlib:make-color :red 0.0 :green 0.0 :blue 0.0)
:background (xlib:make-color :red 1.0 :green 1.0 :blue 1.0)
:source-font font
:source-char code
:mask-font font
:mask-char (1+ code))))
(xlib:close-font font)))
(defmethod initialize-clx ((port clx-port))
(let ((options (cdr (port-server-path port))))
(setf (clx-port-display port)
(xlib:open-display (getf options :host)
:display (getf options :display-id)
:protocol (getf options :protocol)))
(progn
(setf (xlib:display-error-handler (clx-port-display port))
#'clx-error-handler)
Uncomment this when debugging CLX backend if asynchronous errors become troublesome ..
(setf (xlib:display-after-function (clx-port-display port)) #'xlib:display-finish-output))
(setf (clx-port-screen port) (nth (getf options :screen-id)
(xlib:display-roots (clx-port-display port))))
(setf (clx-port-window port) (xlib:screen-root (clx-port-screen port)))
(make-cursor-table port)
(make-graft port)
(when clim-sys:*multiprocessing-p*
(setf (port-event-process port)
(clim-sys:make-process
(lambda ()
(loop
(with-simple-restart
(restart-event-loop
"Restart CLIM's event loop.")
(loop
(process-next-event port)) )))
:name (format nil "~S's event process." port)))
#+nil(format *trace-output* "~&Started CLX event loop process ~A~%" (port-event-process port))) ))
#+nil
(defmethod (setf sheet-mirror-transformation) :after (new-value (sheet mirrored-sheet-mixin))
)
(defmethod port-set-mirror-region ((port clx-port) mirror mirror-region)
(setf (xlib:drawable-width mirror) (floor (bounding-rectangle-max-x mirror-region))
(xlib:drawable-height mirror) (floor (bounding-rectangle-max-y mirror-region))))
(defmethod port-set-mirror-transformation ((port clx-port) mirror mirror-transformation)
(setf (xlib:drawable-x mirror) (floor (nth-value 0 (transform-position mirror-transformation 0 0)))
(xlib:drawable-y mirror) (floor (nth-value 1 (transform-position mirror-transformation 0 0)))))
(defun invent-sheet-mirror-transformation-and-region (sheet)
(let* ((r (sheet-region sheet))
(r* (transform-region
(sheet-native-transformation (sheet-parent sheet))
(transform-region (sheet-transformation sheet) r)))
#+nil
(r*
(bounding-rectangle
(region-intersection
r*
(make-rectangle* 0 0
(port-mirror-width (port sheet) (sheet-parent sheet))
(port-mirror-height (port sheet) (sheet-parent sheet))))))
(mirror-transformation
(if (region-equal r* +nowhere+)
(make-translation-transformation 0 0)
(make-translation-transformation
(bounding-rectangle-min-x r*)
(bounding-rectangle-min-y r*))))
(mirror-region
(untransform-region mirror-transformation r*)))
(values
mirror-transformation
mirror-region)))
(defun realize-mirror-aux (port sheet
&key (width 100) (height 100) (x 0) (y 0)
(border-width 0) (border 0)
(override-redirect :off)
(map t)
(backing-store :not-useful)
(save-under :off)
(event-mask `(:exposure
:key-press :key-release
:button-press :button-release
:enter-window :leave-window
:structure-notify
:pointer-motion
:button-motion)))
of the constant 0 . -- RS 2007 - 07 - 22
(declare (ignore border-width))
(when (null (port-lookup-mirror port sheet))
(update-mirror-geometry sheet)
(let* ((desired-color (typecase sheet
(sheet-with-medium-mixin
(medium-background sheet))
CHECKME [ is this sensible ? ] seems to be
(let ((background (pane-background sheet)))
(if (typep background 'color)
background
+white+)))
(t
+white+)))
(color (multiple-value-bind (r g b)
(color-rgb desired-color)
(xlib:make-color :red r :green g :blue b)))
(pixel (xlib:alloc-color (xlib:screen-default-colormap (clx-port-screen port)) color))
(window (xlib:create-window
:parent (sheet-mirror (sheet-parent sheet))
:width (if (%sheet-mirror-region sheet)
(round-coordinate (bounding-rectangle-width (%sheet-mirror-region sheet)))
width)
:height (if (%sheet-mirror-region sheet)
(round-coordinate (bounding-rectangle-height (%sheet-mirror-region sheet)))
height)
:x (if (%sheet-mirror-transformation sheet)
(round-coordinate (nth-value 0 (transform-position
(%sheet-mirror-transformation sheet)
0 0)))
x)
:y (if (%sheet-mirror-transformation sheet)
(round-coordinate (nth-value 1 (transform-position
(%sheet-mirror-transformation sheet)
0 0)))
y)
:border border
:override-redirect override-redirect
:backing-store backing-store
:save-under save-under
:gravity :north-west
bit - gravity into CLIM ) ? --GB
:bit-gravity (if (typep sheet 'climi::extended-output-stream)
:north-west
:forget)
:background pixel
:event-mask (apply #'xlib:make-event-mask
event-mask))))
(port-register-mirror (port sheet) sheet window)
(when map
(xlib:map-window window)
)))
(port-lookup-mirror port sheet))
(defmethod realize-mirror ((port clx-port) (sheet mirrored-sheet-mixin))
(realize-mirror-aux port sheet
:border-width 0
:map (sheet-enabled-p sheet)))
(defmethod realize-mirror ((port clx-port) (sheet border-pane))
(realize-mirror-aux port sheet
:event-mask '(:exposure
:structure-notify)
:map (sheet-enabled-p sheet)))
(defmethod realize-mirror ((port clx-port) (sheet top-level-sheet-pane))
(let ((q (compose-space sheet)))
(allocate-space sheet
(space-requirement-width q)
(space-requirement-height q))
(let ((frame (pane-frame sheet))
(window (realize-mirror-aux port sheet
:map nil
:width (round-coordinate (space-requirement-width q))
:height (round-coordinate (space-requirement-height q))
:event-mask '(:key-press :key-release))))
(setf (xlib:wm-hints window) (xlib:make-wm-hints :input :on))
(setf (xlib:wm-name window) (frame-pretty-name frame))
(setf (xlib:wm-icon-name window) (frame-pretty-name frame))
(xlib:set-wm-class
window
(string-downcase (frame-name frame))
(string-capitalize (string-downcase (frame-name frame))))
(setf (xlib:wm-protocols window) `(:wm_delete_window))
(xlib:change-property window
:WM_CLIENT_LEADER (list (xlib:window-id window))
:WINDOW 32))))
(defmethod realize-mirror ((port clx-port) (sheet unmanaged-top-level-sheet-pane))
(realize-mirror-aux port sheet
:override-redirect :on
:save-under :on
:map nil
:event-mask '(:structure-notify)))
(defmethod realize-mirror ((port clx-port) (sheet menu-button-pane))
(realize-mirror-aux port sheet
:event-mask '(:exposure
:key-press :key-release
:button-press :button-release
:enter-window :leave-window
:structure-notify
:button-motion
:owner-grab-button)
:map (sheet-enabled-p sheet)))
(defmethod realize-mirror ((port clx-port) (sheet clim-stream-pane))
(realize-mirror-aux port sheet
:event-mask '(:exposure
:key-press :key-release
:button-press :button-release
:enter-window :leave-window
:structure-notify
:pointer-motion :pointer-motion-hint
:button-motion
:owner-grab-button)
:map (sheet-enabled-p sheet)))
(defmethod destroy-mirror ((port clx-port) (sheet mirrored-sheet-mixin))
(when (port-lookup-mirror port sheet)
(xlib:destroy-window (port-lookup-mirror port sheet))
(port-unregister-mirror port sheet (sheet-mirror sheet))))
(defmethod raise-mirror ((port clx-port) (sheet basic-sheet))
(let ((mirror (sheet-mirror sheet)))
(when (and mirror
(typep mirror 'xlib:window))
(xlib:circulate-window-up mirror))))
(defmethod bury-mirror ((port clx-port) (sheet basic-sheet))
(let ((mirror (sheet-mirror sheet)))
(when (and mirror
(typep mirror 'xlib:window))
(xlib:circulate-window-down mirror))))
(defmethod mirror-transformation ((port clx-port) mirror)
(make-translation-transformation (xlib:drawable-x mirror)
(xlib:drawable-y mirror)))
(defmethod port-set-sheet-region ((port clx-port) (graft graft) region)
(declare (ignore region))
nil)
(defmethod port-set-sheet-transformation ((port clx-port) (graft graft) transformation)
(declare (ignore transformation))
nil)
#+nil
(defmethod port-set-sheet-transformation ((port clx-port) (pane application-pane) transformation)
(declare (ignore transformation))
nil)
#+nil
(defmethod port-set-sheet-transformation ((port clx-port) (pane interactor-pane) transformation)
(declare (ignore transformation))
nil)
(defmethod port-set-sheet-transformation ((port clx-port) (sheet mirrored-sheet-mixin) transformation)
(let ((mirror (sheet-direct-mirror sheet)))
(multiple-value-bind (tr rg) (invent-sheet-mirror-transformation-and-region sheet)
(multiple-value-bind (x y) (transform-position tr 0 0)
(multiple-value-bind (x1 y1 x2 y2) (if (eql rg +nowhere+)
(values 0 0 0 0)
(bounding-rectangle* rg))
(setf (xlib:drawable-x mirror) (round x)
(xlib:drawable-y mirror) (round y))
(setf (xlib:drawable-width mirror) (clamp 1 (round x2) #xFFFF)
(xlib:drawable-height mirror) (clamp 1 (round y2) #xFFFF))
( : clear - area mirror : exposures - p t )
(invalidate-cached-transformations sheet)
)))))
(defmethod port-set-sheet-region ((port clx-port) (sheet mirrored-sheet-mixin) region)
(let ((mirror (sheet-direct-mirror sheet)))
(multiple-value-bind (tr rg) (invent-sheet-mirror-transformation-and-region sheet)
(declare (ignore tr))
(multiple-value-bind (x1 y1 x2 y2) (if (eql rg +nowhere+)
(values 0 0 0 0)
(bounding-rectangle* rg))
(setf x2 (round x2))
(setf y2 (round y2))
(cond ((or (<= x2 0) (<= y2 0))
now X does not allow for a zero width / height window ,
))
(setf (xlib:drawable-width mirror) (clamp x2 1 #xFFFF)
(xlib:drawable-height mirror) (clamp y2 1 #xFFFF))))))
(defmethod port-enable-sheet ((port clx-port) (mirror mirrored-sheet-mixin))
(xlib:map-window (sheet-direct-mirror mirror)) )
(defmethod port-disable-sheet ((port clx-port) (mirror mirrored-sheet-mixin))
(xlib:unmap-window (sheet-direct-mirror mirror)) )
(defmethod destroy-port :before ((port clx-port))
(handler-case
(xlib:close-display (clx-port-display port))
(stream-error ()
(xlib:close-display (clx-port-display port) :abort t))))
(defmethod port-motion-hints ((port clx-port) (sheet mirrored-sheet-mixin))
(let ((event-mask (xlib:window-event-mask (sheet-direct-mirror sheet))))
(if (zerop (logand event-mask
#.(xlib:make-event-mask :pointer-motion-hint)))
nil
t)))
(defmethod (setf port-motion-hints)
(val (port clx-port) (sheet mirrored-sheet-mixin))
(let* ((mirror (sheet-direct-mirror sheet))
(event-mask (xlib:window-event-mask mirror)))
(setf (xlib:window-event-mask mirror)
(if val
(logior event-mask #.(xlib:make-event-mask :pointer-motion-hint))
(logandc2 event-mask
#.(xlib:make-event-mask :pointer-motion-hint)))))
val)
(defmacro peek-event ((display &rest keys) &body body)
(let ((escape (gensym)))
`(block ,escape
(xlib:process-event ,display :timeout 0 :peek-p t :handler
#'(lambda (&key ,@keys &allow-other-keys)
(return-from ,escape
(progn
,@body)))))))
(defun decode-x-button-code (code)
(let ((button-mapping #.(vector +pointer-left-button+
+pointer-middle-button+
+pointer-right-button+
+pointer-wheel-up+
+pointer-wheel-down+
+pointer-wheel-left+
+pointer-wheel-right+))
(code (1- code)))
(when (and (>= code 0)
(< code (length button-mapping)))
(aref button-mapping code))))
From " Inter - Client Communication Conventions Manual " , Version 2.0.xf86.1 ,
section 4.1.5 :
| Advice to Implementors
| resized but not moved , since a real ConfigureNotify event will be
| position . Upon receipt of a real ConfigureNotify event on the
| unknown . Upon receipt of a synthetic ConfigureNotify event , the
| this event . If the client receives a KeyPress , KeyRelease ,
| ButtonPress , ButtonRelease , MotionNotify , EnterNotify , or
| LeaveNotify event on the window ( or on any descendant ) , the
| does the client need to use the TranslateCoordinates request to
process ) just reads the events from the X server , and does it
look at the state argument to get the current button state . The CLIM spec
logical or of the button values ... . For now I 'll canonicalize the
pointer - event - buttons slot to pointer events . --
(defvar *clx-port*)
(defun event-handler (&key display window event-key code state mode time
type width height x y root-x root-y
data override-redirect-p send-event-p hint-p
target property requestor selection
request first-keycode count
&allow-other-keys)
(declare (ignore display request first-keycode count))
(let ((sheet (and window (port-lookup-sheet *clx-port* window))))
(when sheet
(case event-key
((:key-press :key-release)
(multiple-value-bind (keyname modifier-state keysym-keyword)
(x-event-to-key-name-and-modifiers *clx-port*
event-key code state)
(make-instance (if (eq event-key :key-press)
'key-press-event
'key-release-event)
:key-name keysym-keyword
:key-character (and (characterp keyname) keyname)
:x x :y y
:graft-x root-x
:graft-y root-y
:sheet (or (frame-properties (pane-frame sheet) 'focus) sheet)
:modifier-state modifier-state :timestamp time)))
((:button-press :button-release)
(let ((modifier-state (clim-xcommon:x-event-state-modifiers *clx-port*
state)))
(make-instance (if (eq event-key :button-press)
'pointer-button-press-event
'pointer-button-release-event)
:pointer 0
:button (decode-x-button-code code) :x x :y y
:graft-x root-x
:graft-y root-y
:sheet sheet :modifier-state modifier-state
:timestamp time)))
(:enter-notify
(make-instance 'pointer-enter-event :pointer 0 :button code :x x :y y
:graft-x root-x
:graft-y root-y
:sheet sheet
:modifier-state (clim-xcommon:x-event-state-modifiers
*clx-port* state)
:timestamp time))
(:leave-notify
(make-instance (if (eq mode :ungrab)
'pointer-ungrab-event
'pointer-exit-event)
:pointer 0 :button code
:x x :y y
:graft-x root-x
:graft-y root-y
:sheet sheet
:modifier-state (clim-xcommon:x-event-state-modifiers
*clx-port* state)
:timestamp time))
(:configure-notify
(cond ((and (eq (sheet-parent sheet) (graft sheet))
(graft sheet)
(not override-redirect-p)
(not send-event-p))
(multiple-value-bind (x y)
(xlib:translate-coordinates window 0 0 (clx-port-window *clx-port*))
(make-instance 'window-configuration-event
:sheet sheet
:x x
:y y
:width width :height height)))
(t
(make-instance 'window-configuration-event
:sheet sheet
:x x :y y :width width :height height))))
(:destroy-notify
(make-instance 'window-destroy-event :sheet sheet))
(:motion-notify
(let ((modifier-state (clim-xcommon:x-event-state-modifiers *clx-port*
state)))
(if hint-p
(multiple-value-bind (x y same-screen-p child mask
root-x root-y)
(xlib:query-pointer window)
(declare (ignore mask))
(when (and same-screen-p (not child))
(make-instance 'pointer-motion-hint-event
:pointer 0 :button code
:x x :y y
:graft-x root-x :graft-y root-y
:sheet sheet
:modifier-state modifier-state
:timestamp time)))
(progn
(make-instance 'pointer-motion-event
:pointer 0 :button code
:x x :y y
:graft-x root-x
:graft-y root-y
:sheet sheet
:modifier-state modifier-state
:timestamp time)))))
((:exposure :display :graphics-exposure)
Notes :
says :
One of the lisps is bogusly sending a : display event instead of an
: exposure event . I do n't remember if it 's CMUCL or SBCL . So the
(make-instance 'window-repaint-event
:timestamp time
:sheet sheet
:region (make-rectangle* x y (+ x width) (+ y height))))
(:selection-notify
(make-instance 'clx-selection-notify-event
:sheet sheet
:selection selection
:target target
:property property))
(:selection-clear
(make-instance 'selection-clear-event
:sheet sheet
:selection selection))
(:selection-request
(make-instance 'clx-selection-request-event
:sheet sheet
:selection selection
:requestor requestor
:target target
:property property
:timestamp time))
(:client-message
(port-client-message sheet time type data))
(t
(unless (xlib:event-listen (clx-port-display *clx-port*))
(xlib:display-force-output (clx-port-display *clx-port*)))
nil)))))
(defmethod port-client-message (sheet time (type (eql :wm_protocols)) data)
(port-wm-protocols-message sheet time
(xlib:atom-name (slot-value *clx-port* 'display) (aref data 0))
data))
(defmethod port-client-message (sheet time (type t) data)
(warn "Unprocessed client message: ~:_type = ~S;~:_ data = ~S;~_ sheet = ~S."
type data sheet))
top - level - sheet REALIZE - MIRROR method should be adjusted to add
: WM_TAKE_FOCUS to XLIB : WM - PROTOCOLS . CSR , 2009 - 02 - 18
(defmethod port-wm-protocols-message (sheet time (message (eql :wm_take_focus)) data)
(let ((timestamp (elt data 1))
(mirror (sheet-mirror sheet)))
(when mirror
(xlib:set-input-focus (clx-port-display *clx-port*)
mirror :parent timestamp))
nil))
(defmethod port-wm-protocols-message (sheet time (message (eql :wm_delete_window)) data)
(declare (ignore data))
(make-instance 'window-manager-delete-event :sheet sheet :timestamp time))
(defmethod port-wm-protocols-message (sheet time (message t) data)
(warn "Unprocessed WM Protocols message: ~:_message = ~S;~:_ data = ~S;~_ sheet = ~S."
message data sheet))
(defmethod get-next-event ((port clx-port) &key wait-function (timeout nil))
(declare (ignore wait-function))
(let* ((*clx-port* port)
(display (clx-port-display port)))
(unless (xlib:event-listen display)
(xlib:display-force-output (clx-port-display port)))
(or (xlib:process-event (clx-port-display port) :timeout timeout :handler #'event-handler :discard-p t)
:timeout)))
[ Mike ] Timeout and wait - functions are both implementation
(defmethod make-graft ((port clx-port) &key (orientation :default) (units :device))
(let ((graft (make-instance 'clx-graft
:port port :mirror (clx-port-window port)
:orientation orientation :units units)))
(setf (sheet-region graft) (make-bounding-rectangle 0 0 (xlib:screen-width (clx-port-screen port)) (xlib:screen-height (clx-port-screen port))))
(push graft (port-grafts port))
graft))
(defmethod make-medium ((port clx-port) sheet)
(make-instance 'clx-medium
:sheet sheet))
(defconstant *clx-text-families* '(:fix "adobe-courier"
:serif "adobe-times"
:sans-serif "adobe-helvetica"))
(defconstant *clx-text-faces* '(:roman "medium-r"
:bold "bold-r"
:italic "medium-i"
:bold-italic "bold-i"
:italic-bold "bold-i"))
(defparameter *clx-text-sizes* '(:normal 14
:tiny 8
:very-small 10
:small 12
:large 18
:very-large 20
:huge 24))
(defparameter *clx-text-family+face-map*
'(:fix
#-nil
("adobe-courier"
(:roman "medium-r"
:bold "bold-r"
:italic "medium-o"
:bold-italic "bold-o"
:italic-bold "bold-o"))
#+nil
("*-lucidatypewriter"
(:roman "medium-r"
:bold "bold-r"
:italic "medium-r"
:bold-italic "bold-r"
:italic-bold "bold-r"))
:sans-serif
("adobe-helvetica"
(:roman "medium-r"
:bold "bold-r"
:italic "medium-o"
:bold-italic "bold-o"
:italic-bold "bold-o"))
:serif
("adobe-times"
(:roman "medium-r"
:bold "bold-r"
:italic "medium-i"
:bold-italic "bold-i"
:italic-bold "bold-i")) ))
(defun open-font (display font-name)
(let ((fonts (xlib:list-font-names display font-name :max-fonts 1)))
(if fonts
(xlib:open-font display (first fonts))
(xlib:open-font display "fixed"))))
(defmethod text-style-mapping ((port clx-port) text-style
&optional character-set)
(declare (ignore character-set))
(let ((table (port-text-style-mappings port)))
(or (car (gethash text-style table))
(multiple-value-bind (family face size)
(text-style-components text-style)
(destructuring-bind (family-name face-table)
(if (stringp family)
(list family *clx-text-faces*)
(or (getf *clx-text-family+face-map* family)
(getf *clx-text-family+face-map* :fix)))
(let* ((face-name (if (stringp face)
face
(or (getf face-table
(if (listp face)
(intern (format nil "~A-~A"
(symbol-name (first face))
(symbol-name (second face)))
:keyword)
face))
(getf *clx-text-faces* :roman))))
(size-number (if (numberp size)
(round size)
(or (getf *clx-text-sizes* size)
(getf *clx-text-sizes* :normal)))))
(flet ((try (encoding)
(let* ((fn (format nil "-~A-~A-*-*-~D-*-*-*-*-*-~A"
family-name face-name size-number
encoding))
(font (open-font (clx-port-display port) fn)))
(and font (cons fn font)))))
(let ((fn-font
(or
(and (> char-code-limit #x100) (try "iso10646-1"))
(try "iso8859-1")
(try "*-*"))))
(setf (gethash text-style table) fn-font)
(car fn-font)))))))))
(defmethod (setf text-style-mapping) (font-name (port clx-port)
(text-style text-style)
&optional character-set)
(declare (ignore character-set))
(setf (gethash text-style (port-text-style-mappings port))
(cons font-name (open-font (clx-port-display port) font-name)))
font-name)
(defun text-style-to-X-font (port text-style)
(let ((text-style (parse-text-style text-style)))
(text-style-mapping port text-style)
(cdr (gethash text-style (port-text-style-mappings port)))))
(defmethod port-character-width ((port clx-port) text-style char)
(let* ((font (text-style-to-X-font port text-style))
(width (xlib:char-width font (char-code char))))
width))
(defmethod port-string-width ((port clx-port) text-style string &key (start 0) end)
(xlib:text-width (text-style-to-X-font port text-style)
string :start start :end end))
(defmethod X-pixel ((port clx-port) color)
(let ((table (slot-value port 'color-table)))
(or (gethash color table)
(setf (gethash color table)
(multiple-value-bind (r g b) (color-rgb color)
(xlib:alloc-color (xlib:screen-default-colormap
(clx-port-screen port))
(xlib:make-color :red r :green g :blue b)))))))
(defmethod port-mirror-width ((port clx-port) sheet)
(let ((mirror (port-lookup-mirror port sheet)))
(xlib:drawable-width mirror)))
(defmethod port-mirror-height ((port clx-port) sheet)
(let ((mirror (port-lookup-mirror port sheet)))
(xlib:drawable-height mirror)))
(defmethod graft ((port clx-port))
(first (port-grafts port)))
(defmethod realize-mirror ((port clx-port) (pixmap pixmap))
(when (null (port-lookup-mirror port pixmap))
(let* ((window (sheet-direct-mirror (pixmap-sheet pixmap)))
(pix (xlib:create-pixmap
:width (round (pixmap-width pixmap))
:height (round (pixmap-height pixmap))
:depth (xlib:drawable-depth window)
:drawable window)))
(port-register-mirror port pixmap pix))
(values)))
(defmethod destroy-mirror ((port clx-port) (pixmap pixmap))
(when (port-lookup-mirror port pixmap)
(xlib:free-pixmap (port-lookup-mirror port pixmap))
(port-unregister-mirror port pixmap (port-lookup-mirror port pixmap))))
(defmethod port-allocate-pixmap ((port clx-port) sheet width height)
(let ((pixmap (make-instance 'mirrored-pixmap
:sheet sheet
:width width
:height height
:port port)))
(when (sheet-grafted-p sheet)
(realize-mirror port pixmap))
pixmap))
(defmethod port-deallocate-pixmap ((port clx-port) pixmap)
(when (port-lookup-mirror port pixmap)
(destroy-mirror port pixmap)))
(defmethod allocate-space :after ((pane top-level-sheet-pane) width height)
(when (sheet-direct-mirror pane)
(with-slots (space-requirement) pane
'(setf (xlib:wm-normal-hints (sheet-direct-mirror pane))
(xlib:make-wm-size-hints
:width (round width)
:height (round height)
:max-width (min 65535 (round (space-requirement-max-width space-requirement)))
:max-height (min 65535 (round (space-requirement-max-height space-requirement)))
:min-width (round (space-requirement-min-width space-requirement))
:min-height (round (space-requirement-min-height space-requirement)))))))
(defmethod pointer-position ((pointer clx-pointer))
(let* ((port (port pointer))
(sheet (port-pointer-sheet port)))
(when sheet
(multiple-value-bind (x y same-screen-p)
(xlib:query-pointer (sheet-direct-mirror sheet))
(when same-screen-p
(untransform-position (sheet-native-transformation sheet) x y))))))
(defconstant +right-button-mask+ #x100)
(defconstant +middle-button-mask+ #x200)
(defconstant +left-button-mask+ #x400)
(defconstant +wheel-up-mask+ #x800)
(defconstant +wheel-down-mask+ #x1000)
(defmethod pointer-button-state ((pointer clx-pointer))
(multiple-value-bind (x y same-screen-p child mask)
(xlib:query-pointer (clx-port-window (port pointer)))
(declare (ignore x y same-screen-p child))
(ldb (byte 5 8) mask)))
In button events we do n't want to see more than one button , according to
(defun button-from-state (mask)
(cond ((logtest +right-button-mask+ mask)
+pointer-right-button+)
((logtest +middle-button-mask+ mask)
+pointer-middle-button+)
((logtest +left-button-mask+ mask)
+pointer-left-button+)
((logtest +wheel-up-mask+ mask)
+pointer-wheel-up+)
((logtest +wheel-down-mask+ mask)
+pointer-wheel-down+)
(t 0)))
#+nil
(defmethod pointer-modifier-state ((pointer clx-pointer))
(multiple-value-bind (x y same-screen-p child mask)
(xlib:query-pointer (clx-port-window (port pointer)))
(declare (ignore x y same-screen-p child))
(clim-xcommon:x-event-state-modifiers (port pointer) mask)))
(defmethod port-modifier-state ((port clx-port))
(multiple-value-bind (x y same-screen-p child mask)
(xlib:query-pointer (clx-port-window port))
(declare (ignore x y same-screen-p child))
(clim-xcommon:x-event-state-modifiers port mask)))
XXX Should we rely on port - pointer - sheet being correct ? --
(defmethod synthesize-pointer-motion-event ((pointer clx-pointer))
(let* ((port (port pointer))
(sheet (port-pointer-sheet port)))
(when sheet
(let ((mirror (sheet-direct-mirror sheet)))
(when mirror
(multiple-value-bind (x y same-screen-p child mask root-x root-y)
(xlib:query-pointer mirror)
(declare (ignore child))
(when same-screen-p
(make-instance
'pointer-motion-event
:pointer 0 :button (button-from-state mask)
:x x :y y
:graft-x root-x
:graft-y root-y
:sheet sheet
:modifier-state (clim-xcommon:x-event-state-modifiers port mask)
:timestamp 0))))))))
(defmethod port-frame-keyboard-input-focus ((port clx-port) frame)
(frame-properties frame 'focus))
(defmethod (setf port-frame-keyboard-input-focus) (focus (port clx-port) frame)
(setf (frame-properties frame 'focus) focus))
(defmethod port-force-output ((port clx-port))
(xlib:display-force-output (clx-port-display port)))
FIXME : What happens when CLIM code calls tracking - pointer recursively ?
I expect the : grab - pointer call will fail , and so the call to
(defmethod port-grab-pointer ((port clx-port) pointer sheet)
(let ((grab-result (xlib:grab-pointer
(sheet-mirror sheet)
'(:button-press :button-release
:leave-window :enter-window
:pointer-motion :pointer-motion-hint)
:owner-p t)))
(if (eq grab-result :success)
(setf (pointer-grab-sheet port) sheet)
nil)))
(defmethod port-ungrab-pointer ((port clx-port) pointer sheet)
(declare (ignore pointer))
(when (eq (pointer-grab-sheet port) sheet)
(xlib:ungrab-pointer (clx-port-display port))
(setf (pointer-grab-sheet port) nil)))
(defmethod distribute-event :around ((port clx-port) event)
(let ((grab-sheet (pointer-grab-sheet port)))
(if grab-sheet
(queue-event grab-sheet event)
(call-next-method))))
(defmethod set-sheet-pointer-cursor ((port clx-port) sheet cursor)
(let ((cursor (gethash cursor (clx-port-cursor-table port))))
(when cursor
(setf (xlib:window-cursor (sheet-mirror sheet)) cursor))))
(defmethod clim-xcommon:modifier-mapping ((port clx-port))
(let* ((display (clx-port-display port))
(x-modifiers (multiple-value-list (xlib:modifier-mapping display)))
(modifier-map (make-array (length x-modifiers) :initial-element nil)))
(loop
for keycodes in x-modifiers
for i from 0
do (setf (aref modifier-map i)
(mapcan (lambda (keycode)
(modifier-keycode->keysyms display keycode))
keycodes)))
modifier-map))
(defclass clx-selection-notify-event (selection-notify-event)
((target :initarg :target
:reader selection-event-target)
(property :initarg :property
:reader selection-event-property)))
(defclass clx-selection-request-event (selection-request-event)
((target :initarg :target
:reader selection-event-target)
(property :initarg :property
:reader selection-event-property)))
Perhaps relatively easy to produce , hard to grok .
Utilities
(defun utf8-string-encode (code-points)
(let ((res (make-array (length code-points)
:adjustable t
:fill-pointer 0)))
(map 'nil
(lambda (code-point)
(cond ((< code-point (expt 2 7))
(vector-push-extend code-point res))
((< code-point (expt 2 11))
(vector-push-extend (logior #b11000000 (ldb (byte 5 6) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 0) code-point)) res))
((< code-point (expt 2 16))
(vector-push-extend (logior #b11100000 (ldb (byte 4 12) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 6) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 0) code-point)) res))
((< code-point (1- (expt 2 21)))
(vector-push-extend (logior #b11110000 (ldb (byte 3 18) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 12) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 6) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 0) code-point)) res))
((< code-point (1- (expt 2 26)))
(vector-push-extend (logior #b11110000 (ldb (byte 2 24) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 18) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 12) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 6) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 0) code-point)) res))
((< code-point (1- (expt 2 31)))
(vector-push-extend (logior #b11110000 (ldb (byte 1 30) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 24) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 18) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 12) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 6) code-point)) res)
(vector-push-extend (logior #b10000000 (ldb (byte 6 0) code-point)) res))
(t
(error "Bad code point: ~D." code-point))))
code-points)
res))
Protocol functions
(defmethod bind-selection ((port clx-port) window &optional time)
(xlib:set-selection-owner
(xlib:window-display (sheet-direct-mirror window))
:primary (sheet-direct-mirror window) time)
(eq (xlib:selection-owner
(xlib:window-display (sheet-direct-mirror window))
:primary)
(sheet-direct-mirror window)))
(defmethod release-selection ((port clx-port) &optional time)
(xlib:set-selection-owner
(clx-port-display port)
:primary nil time)
(setf (selection-owner port) nil)
(setf (selection-timestamp port) nil))
(defmethod request-selection ((port clx-port) requestor time)
(xlib:convert-selection :primary :STRING requestor :bounce time))
(defmethod get-selection-from-event ((port clx-port) (event clx-selection-notify-event))
(if (null (selection-event-property event))
(progn
(format *trace-output* "~&;; Oops, selection-notify property is null. Trying the cut buffer instead..~%")
(xlib:cut-buffer (clx-port-display port)))
(map 'string #'code-char
(xlib:get-property (sheet-direct-mirror (event-sheet event))
(selection-event-property event)
:delete-p t
:result-type 'vector))))
(flet ((latin1-code-p (x)
(not (or (< x 9) (< 10 x 32) (< #x7f x #xa0) (> x 255)))))
(defun string-encode (string)
(delete-if-not #'latin1-code-p (map 'vector #'char-code string)))
(defun exactly-encodable-as-string-p (string)
(every #'latin1-code-p (map 'vector #'char-code string))))
TODO : INCR property ?
FIXME : per ICCCM we MUST support : MULTIPLE
(defmethod send-selection ((port clx-port) (event clx-selection-request-event) string)
(let ((requestor (selection-event-requestor event))
(property (selection-event-property event))
(target (selection-event-target event))
(time (event-timestamp event)))
(when (null property)
(format *trace-output* "~&* Requestor property is null! *~%"))
(progn
(describe event *trace-output*)
(force-output *trace-output*))
(flet ((send-event (&key target (property property))
#+nil
(format *trace-output*
"~&;; clim-clx::send-selection - Requested target ~A, sent ~A to property ~A. time ~S~%"
(selection-event-target event)
target
property time)
(xlib:send-event requestor
:selection-notify nil
:window requestor
:event-window requestor
:selection (climi::selection-event-selection event)
:target target
:property property
:time time)))
(case target
((:UTF8_STRING)
(xlib:change-property requestor property
(utf8-string-encode
(map 'vector #'char-code string))
:UTF8_STRING 8)
(send-event :target :UTF8_STRING))
((:STRING :COMPOUND_TEXT)
(xlib:change-property requestor property
(string-encode string)
target 8)
(send-event :target target))
((:TEXT)
(cond
((exactly-encodable-as-string-p string)
(xlib:change-property requestor property
(string-encode string)
:STRING 8)
(send-event :target :STRING))
(t
(xlib:change-property requestor property
(utf8-string-encode
(map 'vector #'char-code string))
:UTF8_STRING 8)
(send-event :target :UTF8_STRING))))
((:TARGETS)
(let* ((display (clx-port-display port))
(targets (mapcar (lambda (x) (xlib:intern-atom display x))
'(:TARGETS :STRING :TEXT :UTF8_STRING
:COMPOUND_TEXT :TIMESTAMP))))
(xlib:change-property requestor property targets target 32))
(send-event :target :TARGETS))
((:TIMESTAMP)
(when (null (selection-timestamp port))
(format *trace-output* "~&;; selection-timestamp is null!~%"))
(xlib:change-property requestor property
(list (selection-timestamp port))
target 32)
(send-event :target :TIMESTAMP))
(t
(format *trace-output*
"~&;; Warning, unhandled type \"~A\". ~
Sending property NIL to target.~%" target)
(send-event :target target :property nil))))
(xlib:display-force-output (xlib:window-display requestor))))
XXX CLX in ACL does n't use local sockets , so here 's a fix . This is gross
and should obviously be included in ' clx and portable clx , but I
#+allegro
(defun xlib::open-x-stream (host display protocol)
(let ((stream (if (or (string= host "") (string= host "unix"))
(socket:make-socket
:address-family :file
:remote-filename (format nil "/tmp/.X11-unix/X~D" display)
:format :binary)
(socket:make-socket :remote-host (string host)
:remote-port (+ xlib::*x-tcp-port*
display)
:format :binary))))
(if (streamp stream)
stream
(error "Cannot connect to server: ~A:~D" host display))))
(defclass clx-font-family (clim-extensions:font-family)
((all-faces :initform nil
:accessor all-faces
:reader clim-extensions:font-family-all-faces)))
(defclass clx-font-face (clim-extensions:font-face)
((all-sizes :initform nil
:accessor all-sizes
:reader clim-extensions:font-face-all-sizes)))
(defun split-font-name (name)
(loop
repeat 12
for next = (position #\- name :start 0)
:then (position #\- name :start (1+ next))
and prev = nil then next
while next
when prev
collect (subseq name (1+ prev) next)))
(defun reload-font-table (port)
(let ((table (make-hash-table :test 'equal)))
(dolist (font (xlib:list-font-names (clx-port-display port) "*"))
(destructuring-bind
(&optional foundry family weight slant setwidth style pixelsize
yresolution
spacing averagewidth registry encoding
)
(split-font-name font)
(declare (ignore setwidth style ignore))
(when family
(let* ((family-name (format nil "~A ~A" foundry family))
(family-instance
(or (gethash family-name table)
(setf (gethash family-name table)
(make-instance 'clx-font-family
:port port
:name family-name))))
(face-name (format nil "~A ~A" weight slant))
(face-instance
(find face-name (all-faces family-instance)
:key #'clim-extensions:font-face-name
:test #'equal)))
(unless face-instance
(setf face-instance
(make-instance 'clx-font-face
:family family-instance
:name face-name))
(push face-instance (all-faces family-instance)))
(pushnew (parse-integer
FIXME : Python thinks pixelsize is NIL , resulting
(coerce pixelsize 'string))
(all-sizes face-instance))))))
(setf (font-families port)
(sort (loop
for family being each hash-value in table
do
(setf (all-faces family)
(sort (all-faces family)
#'string<
:key #'clim-extensions:font-face-name))
(dolist (face (all-faces family))
(setf (all-sizes face) (sort (all-sizes face) #'<)))
collect family)
#'string<
:key #'clim-extensions:font-family-name))))
(defmethod clim-extensions:port-all-font-families
((port clx-port) &key invalidate-cache)
(when (or (not (slot-boundp port 'font-families)) invalidate-cache)
(reload-font-table port))
(font-families port))
(defmethod clim-extensions:font-face-scalable-p ((face clx-font-face))
nil)
(defun make-unfriendly-name (str)
(substitute #\- #\space str))
(defmethod clim-extensions:font-face-text-style
((face clx-font-face) &optional size)
(make-text-style (make-unfriendly-name
(clim-extensions:font-family-name
(clim-extensions:font-face-family face)))
(make-unfriendly-name
(clim-extensions:font-face-name face))
size))
|
7be84796531e333fc45fcb1edb4c3b46d9c9dbd1925b939f7ea2081ddee4189a | clojure-emacs/refactor-nrepl | middleware.clj | (ns refactor-nrepl.middleware
(:require
[cider.nrepl.middleware.util.cljs :as cljs]
[clojure.stacktrace :refer [print-cause-trace]]
[clojure.walk :as walk]
[refactor-nrepl.config :as config]
[refactor-nrepl.core :as core]
[refactor-nrepl.ns.libspec-allowlist :as libspec-allowlist]
[refactor-nrepl.stubs-for-interface :refer [stubs-for-interface]]))
;; Compatibility with the legacy tools.nrepl.
;; It is not recommended to use the legacy tools.nrepl,
;; therefore it is guarded with a system property.
;; Specifically, we don't want to require it by chance.
(when-not (resolve 'set-descriptor!)
(if (and (System/getProperty "refactor-nrepl.internal.try-requiring-tools-nrepl")
(try
(require 'clojure.tools.nrepl)
true
(catch Exception _
false)))
(require
'[clojure.tools.nrepl.middleware :refer [set-descriptor!]]
'[clojure.tools.nrepl.misc :refer [response-for]]
'[clojure.tools.nrepl.transport :as transport])
(require
'[nrepl.middleware :refer [set-descriptor!]]
'[nrepl.misc :refer [response-for]]
'[nrepl.transport :as transport])))
(defn- require-and-resolve [sym]
(locking core/require-lock
(require (symbol (namespace sym))))
(resolve sym))
(defn err-info
[ex status]
{:ex (str (class ex))
:err (with-out-str (print-cause-trace ex))
:status #{status :done}})
(defmacro ^:private with-errors-being-passed-on [transport msg & body]
`(try
~@body
(catch clojure.lang.ExceptionInfo e#
(transport/send
~transport (response-for ~msg :error (.toString e#) :status :done)))
(catch IllegalArgumentException e#
(transport/send
~transport (response-for ~msg :error (.getMessage e#) :status :done)))
(catch IllegalStateException e#
(transport/send
~transport (response-for ~msg :error (.getMessage e#) :status :done)))
(catch Exception e#
(transport/send
~transport (response-for ~msg (err-info e# :refactor-nrepl-error))))
(catch Error e#
(transport/send
~transport (response-for ~msg (err-info e# :refactor-nrepl-error))))))
(defmacro ^:private reply [transport msg & kvs]
`(libspec-allowlist/with-memoized-libspec-allowlist
(with-errors-being-passed-on ~transport ~msg
(config/with-config ~msg
(transport/send ~transport
(response-for ~msg ~(apply hash-map kvs)))))))
(defn- bencode-friendly-data [data]
Bencode only supports byte strings , integers , lists and maps .
;; To prevent the bencode serializer in nrepl blowing up we manually
;; convert certain data types.
;; See refactor-nrepl#180 for more details.
(walk/postwalk (fn [v]
(cond
(or (keyword? v) (symbol? v))
(if-let [prefix (core/prefix v)]
(core/fully-qualify prefix v)
(name v))
(set? v) (list v)
:else v))
data))
(defn- serialize-response [{:keys [serialization-format]} response]
(binding [*print-length* nil
*print-level* nil]
(condp = serialization-format
"edn" (pr-str response)
"bencode" (bencode-friendly-data response)
(pr-str response) ; edn as default
)))
(def ^:private resolve-missing
(delay
(require-and-resolve 'refactor-nrepl.ns.resolve-missing/resolve-missing)))
(defn resolve-missing-reply [{:keys [transport] :as msg}]
(reply transport msg :candidates (@resolve-missing msg) :status :done))
(def ^:private find-symbol
(delay
(require-and-resolve 'refactor-nrepl.find.find-symbol/find-symbol)))
(defn- find-symbol-reply [{:keys [transport] :as msg}]
(let [occurrences (@find-symbol msg)]
(doseq [occurrence occurrences]
(reply transport msg :occurrence (serialize-response msg occurrence)))
(reply transport msg :count (count occurrences) :status :done)))
(def ^:private artifact-list
(delay (require-and-resolve 'refactor-nrepl.artifacts/artifact-list)))
(def ^:private artifact-versions
(delay (require-and-resolve 'refactor-nrepl.artifacts/artifact-versions)))
(def ^:private hotload-dependency
(delay (require-and-resolve 'refactor-nrepl.artifacts/hotload-dependency)))
(defn- artifact-list-reply [{:keys [transport] :as msg}]
(reply transport msg :artifacts (@artifact-list msg) :status :done))
(defn- artifact-versions-reply [{:keys [transport] :as msg}]
(reply transport msg :versions (@artifact-versions msg) :status :done))
(defn- hotload-dependency-reply [{:keys [transport] :as msg}]
(reply transport msg :status :done :dependency (@hotload-dependency msg)))
(def ^:private clean-ns
(delay
(require-and-resolve 'refactor-nrepl.ns.clean-ns/clean-ns)))
(def ^:private pprint-ns
(delay
(require-and-resolve 'refactor-nrepl.ns.pprint/pprint-ns)))
(defn- clean-ns-reply [{:keys [transport] :as msg}]
(reply transport msg :ns (some-> msg (@clean-ns) (@pprint-ns)) :status :done))
(def ^:private find-used-locals
(delay
(require-and-resolve 'refactor-nrepl.find.find-locals/find-used-locals)))
(defn- find-used-locals-reply [{:keys [transport] :as msg}]
(reply transport msg :used-locals (@find-used-locals msg) :status :done))
(defn- version-reply [{:keys [transport] :as msg}]
(reply transport msg :status :done :version (core/version)))
(def ^:private warm-ast-cache
(delay
(require-and-resolve 'refactor-nrepl.analyzer/warm-ast-cache)))
(defn- warm-ast-cache-reply [{:keys [transport] :as msg}]
(reply transport msg :status :done
:ast-statuses (serialize-response msg (@warm-ast-cache))))
(def ^:private warm-macro-occurrences-cache
(delay (require-and-resolve 'refactor-nrepl.find.find-macros/warm-macro-occurrences-cache)))
(defn- warm-macro-occurrences-cache-reply [{:keys [transport] :as msg}]
(@warm-macro-occurrences-cache)
(reply transport msg :status :done))
(defn- stubs-for-interface-reply [{:keys [transport] :as msg}]
(reply transport msg :status :done
:functions (serialize-response msg (stubs-for-interface msg))))
(def ^:private extract-definition
(delay
(require-and-resolve 'refactor-nrepl.extract-definition/extract-definition)))
(defn- extract-definition-reply [{:keys [transport] :as msg}]
(reply transport msg :status :done :definition (pr-str (@extract-definition msg))))
(def ^:private rename-file-or-dir
(delay
(require-and-resolve 'refactor-nrepl.rename-file-or-dir/rename-file-or-dir)))
(defn- rename-file-or-dir-reply [{:keys [transport old-path new-path ignore-errors] :as msg}]
(reply transport msg :touched (@rename-file-or-dir old-path new-path (= ignore-errors "true"))
:status :done))
(def namespace-aliases
(delay
(require-and-resolve 'refactor-nrepl.ns.libspecs/namespace-aliases-response)))
(defn- namespace-aliases-reply [{:keys [transport] :as msg}]
(let [aliases (@namespace-aliases msg)]
(reply transport msg
:namespace-aliases (serialize-response msg aliases)
:status :done)))
(def suggest-libspecs
(delay
(require-and-resolve 'refactor-nrepl.ns.suggest-libspecs/suggest-libspecs-response)))
(defn- suggest-libspecs-reply [{:keys [transport] :as msg}]
(reply transport
msg
:suggestions (serialize-response msg (@suggest-libspecs msg))
:status :done))
(def ^:private find-used-publics
(delay (require-and-resolve 'refactor-nrepl.find.find-used-publics/find-used-publics)))
(defn- find-used-publics-reply [{:keys [transport] :as msg}]
(reply transport msg
:used-publics (serialize-response msg (@find-used-publics msg)) :status :done))
(def refactor-nrepl-ops
{"artifact-list" artifact-list-reply
"artifact-versions" artifact-versions-reply
"clean-ns" clean-ns-reply
"cljr-suggest-libspecs" suggest-libspecs-reply
"extract-definition" extract-definition-reply
"find-symbol" find-symbol-reply
"find-used-locals" find-used-locals-reply
"hotload-dependency" hotload-dependency-reply
"namespace-aliases" namespace-aliases-reply
"rename-file-or-dir" rename-file-or-dir-reply
"resolve-missing" resolve-missing-reply
"stubs-for-interface" stubs-for-interface-reply
"find-used-publics" find-used-publics-reply
"version" version-reply
"warm-ast-cache" warm-ast-cache-reply
"warm-macro-occurrences-cache" warm-macro-occurrences-cache-reply})
(defn wrap-refactor
[handler]
(fn [{:keys [op] :as msg}]
((get refactor-nrepl-ops op handler) msg)))
(set-descriptor!
#'wrap-refactor
(cljs/requires-piggieback
{:handles (zipmap (keys refactor-nrepl-ops)
(repeat {:doc "See the refactor-nrepl README"
:returns {} :requires {}}))}))
| null | https://raw.githubusercontent.com/clojure-emacs/refactor-nrepl/74dada947f0f2e1775719eb3d8c0a96b837e65f0/src/refactor_nrepl/middleware.clj | clojure | Compatibility with the legacy tools.nrepl.
It is not recommended to use the legacy tools.nrepl,
therefore it is guarded with a system property.
Specifically, we don't want to require it by chance.
To prevent the bencode serializer in nrepl blowing up we manually
convert certain data types.
See refactor-nrepl#180 for more details.
edn as default | (ns refactor-nrepl.middleware
(:require
[cider.nrepl.middleware.util.cljs :as cljs]
[clojure.stacktrace :refer [print-cause-trace]]
[clojure.walk :as walk]
[refactor-nrepl.config :as config]
[refactor-nrepl.core :as core]
[refactor-nrepl.ns.libspec-allowlist :as libspec-allowlist]
[refactor-nrepl.stubs-for-interface :refer [stubs-for-interface]]))
(when-not (resolve 'set-descriptor!)
(if (and (System/getProperty "refactor-nrepl.internal.try-requiring-tools-nrepl")
(try
(require 'clojure.tools.nrepl)
true
(catch Exception _
false)))
(require
'[clojure.tools.nrepl.middleware :refer [set-descriptor!]]
'[clojure.tools.nrepl.misc :refer [response-for]]
'[clojure.tools.nrepl.transport :as transport])
(require
'[nrepl.middleware :refer [set-descriptor!]]
'[nrepl.misc :refer [response-for]]
'[nrepl.transport :as transport])))
(defn- require-and-resolve [sym]
(locking core/require-lock
(require (symbol (namespace sym))))
(resolve sym))
(defn err-info
[ex status]
{:ex (str (class ex))
:err (with-out-str (print-cause-trace ex))
:status #{status :done}})
(defmacro ^:private with-errors-being-passed-on [transport msg & body]
`(try
~@body
(catch clojure.lang.ExceptionInfo e#
(transport/send
~transport (response-for ~msg :error (.toString e#) :status :done)))
(catch IllegalArgumentException e#
(transport/send
~transport (response-for ~msg :error (.getMessage e#) :status :done)))
(catch IllegalStateException e#
(transport/send
~transport (response-for ~msg :error (.getMessage e#) :status :done)))
(catch Exception e#
(transport/send
~transport (response-for ~msg (err-info e# :refactor-nrepl-error))))
(catch Error e#
(transport/send
~transport (response-for ~msg (err-info e# :refactor-nrepl-error))))))
(defmacro ^:private reply [transport msg & kvs]
`(libspec-allowlist/with-memoized-libspec-allowlist
(with-errors-being-passed-on ~transport ~msg
(config/with-config ~msg
(transport/send ~transport
(response-for ~msg ~(apply hash-map kvs)))))))
(defn- bencode-friendly-data [data]
Bencode only supports byte strings , integers , lists and maps .
(walk/postwalk (fn [v]
(cond
(or (keyword? v) (symbol? v))
(if-let [prefix (core/prefix v)]
(core/fully-qualify prefix v)
(name v))
(set? v) (list v)
:else v))
data))
(defn- serialize-response [{:keys [serialization-format]} response]
(binding [*print-length* nil
*print-level* nil]
(condp = serialization-format
"edn" (pr-str response)
"bencode" (bencode-friendly-data response)
)))
(def ^:private resolve-missing
(delay
(require-and-resolve 'refactor-nrepl.ns.resolve-missing/resolve-missing)))
(defn resolve-missing-reply [{:keys [transport] :as msg}]
(reply transport msg :candidates (@resolve-missing msg) :status :done))
(def ^:private find-symbol
(delay
(require-and-resolve 'refactor-nrepl.find.find-symbol/find-symbol)))
(defn- find-symbol-reply [{:keys [transport] :as msg}]
(let [occurrences (@find-symbol msg)]
(doseq [occurrence occurrences]
(reply transport msg :occurrence (serialize-response msg occurrence)))
(reply transport msg :count (count occurrences) :status :done)))
(def ^:private artifact-list
(delay (require-and-resolve 'refactor-nrepl.artifacts/artifact-list)))
(def ^:private artifact-versions
(delay (require-and-resolve 'refactor-nrepl.artifacts/artifact-versions)))
(def ^:private hotload-dependency
(delay (require-and-resolve 'refactor-nrepl.artifacts/hotload-dependency)))
(defn- artifact-list-reply [{:keys [transport] :as msg}]
(reply transport msg :artifacts (@artifact-list msg) :status :done))
(defn- artifact-versions-reply [{:keys [transport] :as msg}]
(reply transport msg :versions (@artifact-versions msg) :status :done))
(defn- hotload-dependency-reply [{:keys [transport] :as msg}]
(reply transport msg :status :done :dependency (@hotload-dependency msg)))
(def ^:private clean-ns
(delay
(require-and-resolve 'refactor-nrepl.ns.clean-ns/clean-ns)))
(def ^:private pprint-ns
(delay
(require-and-resolve 'refactor-nrepl.ns.pprint/pprint-ns)))
(defn- clean-ns-reply [{:keys [transport] :as msg}]
(reply transport msg :ns (some-> msg (@clean-ns) (@pprint-ns)) :status :done))
(def ^:private find-used-locals
(delay
(require-and-resolve 'refactor-nrepl.find.find-locals/find-used-locals)))
(defn- find-used-locals-reply [{:keys [transport] :as msg}]
(reply transport msg :used-locals (@find-used-locals msg) :status :done))
(defn- version-reply [{:keys [transport] :as msg}]
(reply transport msg :status :done :version (core/version)))
(def ^:private warm-ast-cache
(delay
(require-and-resolve 'refactor-nrepl.analyzer/warm-ast-cache)))
(defn- warm-ast-cache-reply [{:keys [transport] :as msg}]
(reply transport msg :status :done
:ast-statuses (serialize-response msg (@warm-ast-cache))))
(def ^:private warm-macro-occurrences-cache
(delay (require-and-resolve 'refactor-nrepl.find.find-macros/warm-macro-occurrences-cache)))
(defn- warm-macro-occurrences-cache-reply [{:keys [transport] :as msg}]
(@warm-macro-occurrences-cache)
(reply transport msg :status :done))
(defn- stubs-for-interface-reply [{:keys [transport] :as msg}]
(reply transport msg :status :done
:functions (serialize-response msg (stubs-for-interface msg))))
(def ^:private extract-definition
(delay
(require-and-resolve 'refactor-nrepl.extract-definition/extract-definition)))
(defn- extract-definition-reply [{:keys [transport] :as msg}]
(reply transport msg :status :done :definition (pr-str (@extract-definition msg))))
(def ^:private rename-file-or-dir
(delay
(require-and-resolve 'refactor-nrepl.rename-file-or-dir/rename-file-or-dir)))
(defn- rename-file-or-dir-reply [{:keys [transport old-path new-path ignore-errors] :as msg}]
(reply transport msg :touched (@rename-file-or-dir old-path new-path (= ignore-errors "true"))
:status :done))
(def namespace-aliases
(delay
(require-and-resolve 'refactor-nrepl.ns.libspecs/namespace-aliases-response)))
(defn- namespace-aliases-reply [{:keys [transport] :as msg}]
(let [aliases (@namespace-aliases msg)]
(reply transport msg
:namespace-aliases (serialize-response msg aliases)
:status :done)))
(def suggest-libspecs
(delay
(require-and-resolve 'refactor-nrepl.ns.suggest-libspecs/suggest-libspecs-response)))
(defn- suggest-libspecs-reply [{:keys [transport] :as msg}]
(reply transport
msg
:suggestions (serialize-response msg (@suggest-libspecs msg))
:status :done))
(def ^:private find-used-publics
(delay (require-and-resolve 'refactor-nrepl.find.find-used-publics/find-used-publics)))
(defn- find-used-publics-reply [{:keys [transport] :as msg}]
(reply transport msg
:used-publics (serialize-response msg (@find-used-publics msg)) :status :done))
(def refactor-nrepl-ops
{"artifact-list" artifact-list-reply
"artifact-versions" artifact-versions-reply
"clean-ns" clean-ns-reply
"cljr-suggest-libspecs" suggest-libspecs-reply
"extract-definition" extract-definition-reply
"find-symbol" find-symbol-reply
"find-used-locals" find-used-locals-reply
"hotload-dependency" hotload-dependency-reply
"namespace-aliases" namespace-aliases-reply
"rename-file-or-dir" rename-file-or-dir-reply
"resolve-missing" resolve-missing-reply
"stubs-for-interface" stubs-for-interface-reply
"find-used-publics" find-used-publics-reply
"version" version-reply
"warm-ast-cache" warm-ast-cache-reply
"warm-macro-occurrences-cache" warm-macro-occurrences-cache-reply})
(defn wrap-refactor
[handler]
(fn [{:keys [op] :as msg}]
((get refactor-nrepl-ops op handler) msg)))
(set-descriptor!
#'wrap-refactor
(cljs/requires-piggieback
{:handles (zipmap (keys refactor-nrepl-ops)
(repeat {:doc "See the refactor-nrepl README"
:returns {} :requires {}}))}))
|
a3fc05b6b9ade9e6602cf5c3ad807e333d779c7d8b15eecab68067abed0ba461 | Incubaid/baardskeerder | flog.mli |
* This file is part of Baardskeerder .
*
* Copyright ( C ) 2012 Incubaid BVBA
*
* Baardskeerder 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 .
*
* Baardskeerder 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 Baardskeerder . If not , see < / > .
* This file is part of Baardskeerder.
*
* Copyright (C) 2012 Incubaid BVBA
*
* Baardskeerder 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.
*
* Baardskeerder 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 Baardskeerder. If not, see </>.
*)
module Flog : functor (S:Bs_internal.STORE) -> Log.LOG with type 'a m = 'a S.m
| null | https://raw.githubusercontent.com/Incubaid/baardskeerder/3975cb7f0e92e1f35eeab17beeb906344e43dae0/src/flog.mli | ocaml |
* This file is part of Baardskeerder .
*
* Copyright ( C ) 2012 Incubaid BVBA
*
* Baardskeerder 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 .
*
* Baardskeerder 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 Baardskeerder . If not , see < / > .
* This file is part of Baardskeerder.
*
* Copyright (C) 2012 Incubaid BVBA
*
* Baardskeerder 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.
*
* Baardskeerder 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 Baardskeerder. If not, see </>.
*)
module Flog : functor (S:Bs_internal.STORE) -> Log.LOG with type 'a m = 'a S.m
| |
47f9378fd918321729db65293871575444f9a555899008e01b46f445afe5e0e9 | gar1t/lambdapad | lpad_json.erl | Copyright 2014 < >
%%%
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(lpad_json).
-behavior(lpad_data_loader).
-export([load/1, handle_data_spec/2]).
%%%===================================================================
%%% Load
%%%===================================================================
load(File) ->
handle_json_file(file:read_file(File), File).
handle_json_file({ok, Bin}, _File) ->
structs_to_proplists(jiffy:decode(Bin));
handle_json_file({error, Err}, File) ->
error({read_file, File, Err}).
structs_to_proplists({Proplist}) ->
[{Name, structs_to_proplists(Val)} || {Name, Val} <- Proplist];
structs_to_proplists(Other) ->
Other.
%%%===================================================================
%%% Data loader support
%%%===================================================================
handle_data_spec({Name, {json, File}}, DState) ->
{ok, lpad_util:load_file_data(Name, File, fun load/1, DState)};
handle_data_spec({json, File}, {'$root', Sources}) ->
{ok, lpad_util:load_file_root_data(File, fun load/1, Sources)};
handle_data_spec(_, DState) ->
{continue, DState}.
| null | https://raw.githubusercontent.com/gar1t/lambdapad/483b67694723923a82fc699aa37d580d035bd420/src/lpad_json.erl | erlang |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
===================================================================
Load
===================================================================
===================================================================
Data loader support
=================================================================== | Copyright 2014 < >
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(lpad_json).
-behavior(lpad_data_loader).
-export([load/1, handle_data_spec/2]).
load(File) ->
handle_json_file(file:read_file(File), File).
handle_json_file({ok, Bin}, _File) ->
structs_to_proplists(jiffy:decode(Bin));
handle_json_file({error, Err}, File) ->
error({read_file, File, Err}).
structs_to_proplists({Proplist}) ->
[{Name, structs_to_proplists(Val)} || {Name, Val} <- Proplist];
structs_to_proplists(Other) ->
Other.
handle_data_spec({Name, {json, File}}, DState) ->
{ok, lpad_util:load_file_data(Name, File, fun load/1, DState)};
handle_data_spec({json, File}, {'$root', Sources}) ->
{ok, lpad_util:load_file_root_data(File, fun load/1, Sources)};
handle_data_spec(_, DState) ->
{continue, DState}.
|
ce69bdb837272b0418c0351b60c55fa471cc2319a42a5c4b43abc0b320bc9732 | Shimuuar/fixed-vector | Fixed.hs | {-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE PatternSynonyms #-}
# LANGUAGE PolyKinds #
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
-- |
-- Generic API for vectors with fixed length.
--
-- For encoding of vector size library uses Peano naturals defined in
-- the library. At come point in the future it would make sense to
switch to new GHC type level numerals .
--
-- [@Common pitfalls@]
--
Library provide instances for tuples . But there 's a catch . Tuples
are monomorphic in element type . Let consider 2 - tuple @(Int , Int)@.
Vector type @v@ is @ ( , ) Int@ and only allowed element type is
-- @Int@. Because of that we cannot change element type and following
-- code will fail:
--
> > > > map (= = 1 ) ( ( 1,2 ) : : ( Int , Int ) )
-- >
-- > <interactive>:3:1:
-- > Couldn't match type `Int' with `Bool'
> In the expression : F.map (= = 1 ) ( ( 1 , 2 ) : : ( Int , Int ) )
> In an equation for ` it ' : it = map (= = 1 ) ( ( 1 , 2 ) : : ( Int , Int ) )
--
-- To make it work we need to change vector type as well. Functions
-- from module "Data.Vector.Fixed.Generic" provide this functionality.
--
> > > > map (= = 1 ) ( ( 1,2 ) : : ( Int , Int ) ) : : ( Bool , )
-- > (True,False)
module Data.Vector.Fixed (
-- * Vector type class
-- ** Vector size
Dim
-- ** Type class
, Vector(..)
, VectorN
, Arity
, Fun(..)
, length
-- * Constructors
-- $construction
-- ** Small dimensions
-- $smallDim
, mk0
, mk1
, mk2
, mk3
, mk4
, mk5
, mk6
, mk7
, mk8
, mkN
-- ** Pattern for low-dimension vectors
, pattern V2
, pattern V3
, pattern V4
-- ** Continuation-based vectors
, ContVec
, empty
, vector
, C.cvec
-- ** Functions
, replicate
, replicateM
, generate
, generateM
, unfoldr
, basis
-- * Modifying vectors
-- ** Transformations
, head
, tail
, cons
, snoc
, concat
, reverse
-- ** Indexing & lenses
-- , C.Index
, (!)
, index
, set
, element
, elementTy
-- ** Comparison
, eq
, ord
-- ** Maps
, map
, mapM
, mapM_
, imap
, imapM
, imapM_
, scanl
, scanl1
, sequence
, sequence_
, sequenceA
, traverse
, distribute
, collect
-- * Folding
, foldl
, foldr
, foldl1
, fold
, foldMap
, ifoldl
, ifoldr
, foldM
, ifoldM
-- ** Special folds
, sum
, maximum
, minimum
, and
, or
, all
, any
, find
*
, zipWith
, zipWith3
, zipWithM
, zipWithM_
, izipWith
, izipWith3
, izipWithM
, izipWithM_
-- * Storable methods
-- $storable
, StorableViaFixed(..)
, defaultAlignemnt
, defaultSizeOf
, defaultPeek
, defaultPoke
-- * NFData
, defaultRnf
-- * Conversion
, convert
, toList
, fromList
, fromList'
, fromListM
, fromFoldable
-- * Data types
, VecList(..)
, VecPeano(..)
, Only(..)
, Empty(..)
-- ** Tuple synonyms
, Tuple2
, Tuple3
, Tuple4
, Tuple5
) where
import Control.Applicative (Applicative(..),(<$>))
import Control.DeepSeq (NFData(..))
import Data.Coerce
import Data.Data (Typeable,Data)
import Data.Monoid (Monoid(..))
import Data.Semigroup (Semigroup(..))
import qualified Data.Foldable as F
import qualified Data.Traversable as T
import Foreign.Storable (Storable(..))
import Foreign.Ptr (castPtr)
import GHC.TypeLits
import Data.Vector.Fixed.Cont (Vector(..),VectorN,Dim,length,ContVec,PeanoNum(..),
vector,empty,Arity,Fun(..),accum,apply,vector)
import qualified Data.Vector.Fixed.Cont as C
import Data.Vector.Fixed.Internal
import Prelude (Show(..),Eq(..),Ord(..),Functor(..),id,(.),($),undefined)
-- $construction
--
-- There are several ways to construct fixed vectors except using
-- their constructor if it's available. For small ones it's possible
-- to use functions 'mk1', 'mk2', etc.
--
> > > mk3 ' a ' ' b ' ' c ' : : ( , , )
-- ('a','b','c')
--
-- Alternatively one could use 'mkN'. See its documentation for
-- examples.
--
-- Another option is to create tuple and 'convert' it to desired
-- vector type. For example:
--
-- > v = convert (x,y,z)
--
It will work on if type of @v@ is know from elsewhere . Same trick
-- could be used to pattern match on the vector with opaque
-- representation using view patterns
--
> function : : - > ...
-- > function (convert -> (x,y,z)) = ...
--
-- For small vectors pattern synonyms @V2@, @V3$, @V4@ are provided
-- that use same trick internally.
-- $smallDim
--
-- Constructors for vectors with small dimensions.
-- $storable
--
-- Default implementation of methods for Storable type class assumes
-- that individual elements of vector are stored as N-element array.
-- | Type-based vector with statically known length parametrized by
GHC 's type naturals
newtype VecList (n :: Nat) a = VecList (VecPeano (C.Peano n) a)
-- | Standard GADT-based vector with statically known length
parametrized by numbers .
data VecPeano (n :: PeanoNum) a where
Nil :: VecPeano 'Z a
Cons :: a -> VecPeano n a -> VecPeano ('S n) a
deriving (Typeable)
instance (Arity n, NFData a) => NFData (VecList n a) where
rnf = defaultRnf
# INLINE rnf #
type instance Dim (VecList n) = n
instance Arity n => Vector (VecList n) a where
construct = fmap VecList $ accum
(\(T_List f) a -> T_List (f . Cons a))
(\(T_List f) -> f Nil)
(T_List id :: T_List a (C.Peano n) (C.Peano n))
inspect (VecList v)
= inspect (apply step (Flip v) :: C.ContVec n a)
where
step :: Flip VecPeano a ('S k) -> (a, Flip VecPeano a k)
step (Flip (Cons a xs)) = (a, Flip xs)
{-# INLINE construct #-}
{-# INLINE inspect #-}
instance Arity n => VectorN VecList n a
newtype Flip f a n = Flip (f n a)
newtype T_List a n k = T_List (VecPeano k a -> VecPeano n a)
-- Standard instances
instance (Show a, Arity n) => Show (VecList n a) where
show = show . foldr (:) []
instance (Eq a, Arity n) => Eq (VecList n a) where
(==) = eq
instance (Ord a, Arity n) => Ord (VecList n a) where
compare = ord
instance Arity n => Functor (VecList n) where
fmap = map
instance Arity n => Applicative (VecList n) where
pure = replicate
(<*>) = zipWith ($)
instance Arity n => F.Foldable (VecList n) where
foldr = foldr
instance Arity n => T.Traversable (VecList n) where
sequenceA = sequenceA
traverse = traverse
instance (Arity n, Monoid a) => Monoid (VecList n a) where
mempty = replicate mempty
mappend = (<>)
# INLINE mempty #
# INLINE mappend #
instance (Arity n, Semigroup a) => Semigroup (VecList n a) where
(<>) = zipWith (<>)
{-# INLINE (<>) #-}
instance (Storable a, Arity n) => Storable (VecList n a) where
alignment = defaultAlignemnt
sizeOf = defaultSizeOf
peek = defaultPeek
poke = defaultPoke
# INLINE alignment #
# INLINE sizeOf #
{-# INLINE peek #-}
{-# INLINE poke #-}
| Newtype for deriving ' ' instance for data types which has
-- instance of 'Vector'
newtype StorableViaFixed v a = StorableViaFixed (v a)
instance (Vector v a, Storable a) => Storable (StorableViaFixed v a) where
alignment = coerce (defaultAlignemnt @a @v)
sizeOf = coerce (defaultSizeOf @a @v)
peek = coerce (defaultPeek @a @v)
poke = coerce (defaultPoke @a @v)
# INLINE alignment #
# INLINE sizeOf #
{-# INLINE peek #-}
{-# INLINE poke #-}
-- | Single-element tuple.
newtype Only a = Only a
deriving (Show,Eq,Ord,Typeable,Data,Functor,F.Foldable,T.Traversable)
instance Monoid a => Monoid (Only a) where
mempty = Only mempty
Only a `mappend` Only b = Only $ mappend a b
instance (Semigroup a) => Semigroup (Only a) where
Only a <> Only b = Only (a <> b)
{-# INLINE (<>) #-}
instance NFData a => NFData (Only a) where
rnf (Only a) = rnf a
type instance Dim Only = 1
instance Vector Only a where
construct = Fun Only
inspect (Only a) (Fun f) = f a
{-# INLINE construct #-}
{-# INLINE inspect #-}
instance (Storable a) => Storable (Only a) where
alignment _ = alignment (undefined :: a)
sizeOf _ = sizeOf (undefined :: a)
peek p = Only <$> peek (castPtr p)
poke p (Only a) = poke (castPtr p) a
# INLINE alignment #
# INLINE sizeOf #
{-# INLINE peek #-}
{-# INLINE poke #-}
-- | Empty tuple.
data Empty a = Empty
deriving (Show,Eq,Ord,Typeable,Data,Functor,F.Foldable,T.Traversable)
instance NFData (Empty a) where
rnf Empty = ()
type instance Dim Empty = 0
instance Vector Empty a where
construct = Fun Empty
inspect _ (Fun b) = b
{-# INLINE construct #-}
{-# INLINE inspect #-}
type Tuple2 a = (a,a)
type Tuple3 a = (a,a,a)
type Tuple4 a = (a,a,a,a)
type Tuple5 a = (a,a,a,a,a)
----------------------------------------------------------------
-- Patterns
----------------------------------------------------------------
pattern V2 :: (Vector v a, Dim v ~ 2) => a -> a -> v a
pattern V2 x y <- (convert -> (x,y)) where
V2 x y = mk2 x y
#if MIN_VERSION_base(4,16,0)
# INLINE V2 #
#endif
pattern V3 :: (Vector v a, Dim v ~ 3) => a -> a -> a -> v a
pattern V3 x y z <- (convert -> (x,y,z)) where
V3 x y z = mk3 x y z
#if MIN_VERSION_base(4,16,0)
# INLINE V3 #
#endif
pattern V4 :: (Vector v a, Dim v ~ 4) => a -> a -> a -> a -> v a
pattern V4 t x y z <- (convert -> (t,x,y,z)) where
V4 t x y z = mk4 t x y z
#if MIN_VERSION_base(4,16,0)
# INLINE V4 #
#endif
-- $setup
--
> > > import Data .
| null | https://raw.githubusercontent.com/Shimuuar/fixed-vector/cf731f17dc276ab35b2012f777d3fd49fc7b45e2/fixed-vector/Data/Vector/Fixed.hs | haskell | # LANGUAGE CPP #
# LANGUAGE DataKinds #
# LANGUAGE DeriveDataTypeable #
# LANGUAGE DeriveTraversable #
# LANGUAGE FlexibleContexts #
# LANGUAGE PatternSynonyms #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeOperators #
|
Generic API for vectors with fixed length.
For encoding of vector size library uses Peano naturals defined in
the library. At come point in the future it would make sense to
[@Common pitfalls@]
@Int@. Because of that we cannot change element type and following
code will fail:
>
> <interactive>:3:1:
> Couldn't match type `Int' with `Bool'
To make it work we need to change vector type as well. Functions
from module "Data.Vector.Fixed.Generic" provide this functionality.
> (True,False)
* Vector type class
** Vector size
** Type class
* Constructors
$construction
** Small dimensions
$smallDim
** Pattern for low-dimension vectors
** Continuation-based vectors
** Functions
* Modifying vectors
** Transformations
** Indexing & lenses
, C.Index
** Comparison
** Maps
* Folding
** Special folds
* Storable methods
$storable
* NFData
* Conversion
* Data types
** Tuple synonyms
$construction
There are several ways to construct fixed vectors except using
their constructor if it's available. For small ones it's possible
to use functions 'mk1', 'mk2', etc.
('a','b','c')
Alternatively one could use 'mkN'. See its documentation for
examples.
Another option is to create tuple and 'convert' it to desired
vector type. For example:
> v = convert (x,y,z)
could be used to pattern match on the vector with opaque
representation using view patterns
> function (convert -> (x,y,z)) = ...
For small vectors pattern synonyms @V2@, @V3$, @V4@ are provided
that use same trick internally.
$smallDim
Constructors for vectors with small dimensions.
$storable
Default implementation of methods for Storable type class assumes
that individual elements of vector are stored as N-element array.
| Type-based vector with statically known length parametrized by
| Standard GADT-based vector with statically known length
# INLINE construct #
# INLINE inspect #
Standard instances
# INLINE (<>) #
# INLINE peek #
# INLINE poke #
instance of 'Vector'
# INLINE peek #
# INLINE poke #
| Single-element tuple.
# INLINE (<>) #
# INLINE construct #
# INLINE inspect #
# INLINE peek #
# INLINE poke #
| Empty tuple.
# INLINE construct #
# INLINE inspect #
--------------------------------------------------------------
Patterns
--------------------------------------------------------------
$setup
| # LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
switch to new GHC type level numerals .
Library provide instances for tuples . But there 's a catch . Tuples
are monomorphic in element type . Let consider 2 - tuple @(Int , Int)@.
Vector type @v@ is @ ( , ) Int@ and only allowed element type is
> > > > map (= = 1 ) ( ( 1,2 ) : : ( Int , Int ) )
> In the expression : F.map (= = 1 ) ( ( 1 , 2 ) : : ( Int , Int ) )
> In an equation for ` it ' : it = map (= = 1 ) ( ( 1 , 2 ) : : ( Int , Int ) )
> > > > map (= = 1 ) ( ( 1,2 ) : : ( Int , Int ) ) : : ( Bool , )
module Data.Vector.Fixed (
Dim
, Vector(..)
, VectorN
, Arity
, Fun(..)
, length
, mk0
, mk1
, mk2
, mk3
, mk4
, mk5
, mk6
, mk7
, mk8
, mkN
, pattern V2
, pattern V3
, pattern V4
, ContVec
, empty
, vector
, C.cvec
, replicate
, replicateM
, generate
, generateM
, unfoldr
, basis
, head
, tail
, cons
, snoc
, concat
, reverse
, (!)
, index
, set
, element
, elementTy
, eq
, ord
, map
, mapM
, mapM_
, imap
, imapM
, imapM_
, scanl
, scanl1
, sequence
, sequence_
, sequenceA
, traverse
, distribute
, collect
, foldl
, foldr
, foldl1
, fold
, foldMap
, ifoldl
, ifoldr
, foldM
, ifoldM
, sum
, maximum
, minimum
, and
, or
, all
, any
, find
*
, zipWith
, zipWith3
, zipWithM
, zipWithM_
, izipWith
, izipWith3
, izipWithM
, izipWithM_
, StorableViaFixed(..)
, defaultAlignemnt
, defaultSizeOf
, defaultPeek
, defaultPoke
, defaultRnf
, convert
, toList
, fromList
, fromList'
, fromListM
, fromFoldable
, VecList(..)
, VecPeano(..)
, Only(..)
, Empty(..)
, Tuple2
, Tuple3
, Tuple4
, Tuple5
) where
import Control.Applicative (Applicative(..),(<$>))
import Control.DeepSeq (NFData(..))
import Data.Coerce
import Data.Data (Typeable,Data)
import Data.Monoid (Monoid(..))
import Data.Semigroup (Semigroup(..))
import qualified Data.Foldable as F
import qualified Data.Traversable as T
import Foreign.Storable (Storable(..))
import Foreign.Ptr (castPtr)
import GHC.TypeLits
import Data.Vector.Fixed.Cont (Vector(..),VectorN,Dim,length,ContVec,PeanoNum(..),
vector,empty,Arity,Fun(..),accum,apply,vector)
import qualified Data.Vector.Fixed.Cont as C
import Data.Vector.Fixed.Internal
import Prelude (Show(..),Eq(..),Ord(..),Functor(..),id,(.),($),undefined)
> > > mk3 ' a ' ' b ' ' c ' : : ( , , )
It will work on if type of @v@ is know from elsewhere . Same trick
> function : : - > ...
GHC 's type naturals
newtype VecList (n :: Nat) a = VecList (VecPeano (C.Peano n) a)
parametrized by numbers .
data VecPeano (n :: PeanoNum) a where
Nil :: VecPeano 'Z a
Cons :: a -> VecPeano n a -> VecPeano ('S n) a
deriving (Typeable)
instance (Arity n, NFData a) => NFData (VecList n a) where
rnf = defaultRnf
# INLINE rnf #
type instance Dim (VecList n) = n
instance Arity n => Vector (VecList n) a where
construct = fmap VecList $ accum
(\(T_List f) a -> T_List (f . Cons a))
(\(T_List f) -> f Nil)
(T_List id :: T_List a (C.Peano n) (C.Peano n))
inspect (VecList v)
= inspect (apply step (Flip v) :: C.ContVec n a)
where
step :: Flip VecPeano a ('S k) -> (a, Flip VecPeano a k)
step (Flip (Cons a xs)) = (a, Flip xs)
instance Arity n => VectorN VecList n a
newtype Flip f a n = Flip (f n a)
newtype T_List a n k = T_List (VecPeano k a -> VecPeano n a)
instance (Show a, Arity n) => Show (VecList n a) where
show = show . foldr (:) []
instance (Eq a, Arity n) => Eq (VecList n a) where
(==) = eq
instance (Ord a, Arity n) => Ord (VecList n a) where
compare = ord
instance Arity n => Functor (VecList n) where
fmap = map
instance Arity n => Applicative (VecList n) where
pure = replicate
(<*>) = zipWith ($)
instance Arity n => F.Foldable (VecList n) where
foldr = foldr
instance Arity n => T.Traversable (VecList n) where
sequenceA = sequenceA
traverse = traverse
instance (Arity n, Monoid a) => Monoid (VecList n a) where
mempty = replicate mempty
mappend = (<>)
# INLINE mempty #
# INLINE mappend #
instance (Arity n, Semigroup a) => Semigroup (VecList n a) where
(<>) = zipWith (<>)
instance (Storable a, Arity n) => Storable (VecList n a) where
alignment = defaultAlignemnt
sizeOf = defaultSizeOf
peek = defaultPeek
poke = defaultPoke
# INLINE alignment #
# INLINE sizeOf #
| Newtype for deriving ' ' instance for data types which has
newtype StorableViaFixed v a = StorableViaFixed (v a)
instance (Vector v a, Storable a) => Storable (StorableViaFixed v a) where
alignment = coerce (defaultAlignemnt @a @v)
sizeOf = coerce (defaultSizeOf @a @v)
peek = coerce (defaultPeek @a @v)
poke = coerce (defaultPoke @a @v)
# INLINE alignment #
# INLINE sizeOf #
newtype Only a = Only a
deriving (Show,Eq,Ord,Typeable,Data,Functor,F.Foldable,T.Traversable)
instance Monoid a => Monoid (Only a) where
mempty = Only mempty
Only a `mappend` Only b = Only $ mappend a b
instance (Semigroup a) => Semigroup (Only a) where
Only a <> Only b = Only (a <> b)
instance NFData a => NFData (Only a) where
rnf (Only a) = rnf a
type instance Dim Only = 1
instance Vector Only a where
construct = Fun Only
inspect (Only a) (Fun f) = f a
instance (Storable a) => Storable (Only a) where
alignment _ = alignment (undefined :: a)
sizeOf _ = sizeOf (undefined :: a)
peek p = Only <$> peek (castPtr p)
poke p (Only a) = poke (castPtr p) a
# INLINE alignment #
# INLINE sizeOf #
data Empty a = Empty
deriving (Show,Eq,Ord,Typeable,Data,Functor,F.Foldable,T.Traversable)
instance NFData (Empty a) where
rnf Empty = ()
type instance Dim Empty = 0
instance Vector Empty a where
construct = Fun Empty
inspect _ (Fun b) = b
type Tuple2 a = (a,a)
type Tuple3 a = (a,a,a)
type Tuple4 a = (a,a,a,a)
type Tuple5 a = (a,a,a,a,a)
pattern V2 :: (Vector v a, Dim v ~ 2) => a -> a -> v a
pattern V2 x y <- (convert -> (x,y)) where
V2 x y = mk2 x y
#if MIN_VERSION_base(4,16,0)
# INLINE V2 #
#endif
pattern V3 :: (Vector v a, Dim v ~ 3) => a -> a -> a -> v a
pattern V3 x y z <- (convert -> (x,y,z)) where
V3 x y z = mk3 x y z
#if MIN_VERSION_base(4,16,0)
# INLINE V3 #
#endif
pattern V4 :: (Vector v a, Dim v ~ 4) => a -> a -> a -> a -> v a
pattern V4 t x y z <- (convert -> (t,x,y,z)) where
V4 t x y z = mk4 t x y z
#if MIN_VERSION_base(4,16,0)
# INLINE V4 #
#endif
> > > import Data .
|
d4e583342c10b2e5bfd31bf713bc1f2ddf50b63628bb2668f352f16fb8b7cccb | onedata/op-worker | atm_workflow_execution_finish_tests.erl | %%%-------------------------------------------------------------------
@author
( C ) 2022 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
%%% @end
%%%-------------------------------------------------------------------
%%% @doc
%%% Tests concerning successfully finished automation workflow execution.
%%% @end
%%%-------------------------------------------------------------------
-module(atm_workflow_execution_finish_tests).
-author("Bartosz Walkowicz").
-include("atm_workflow_execution_test.hrl").
-include("modules/automation/atm_execution.hrl").
-export([
finish_atm_workflow_execution/0
]).
-define(ITERATED_STORE_SCHEMA_ID, <<"iterated_store_id">>).
-define(TARGET_STORE_SCHEMA_ID, <<"target_store_id">>).
-define(ATM_TASK_SCHEMA_DRAFT(__ID), #atm_task_schema_draft{
id = __ID,
lambda_id = ?ECHO_LAMBDA_ID,
lambda_revision_number = ?ECHO_LAMBDA_REVISION_NUM,
argument_mappings = [?ITERATED_ITEM_ARG_MAPPER(?ECHO_ARG_NAME)],
result_mappings = [#atm_task_schema_result_mapper{
result_name = ?ECHO_ARG_NAME,
store_schema_id = ?TARGET_STORE_SCHEMA_ID,
store_content_update_options = #atm_list_store_content_update_options{
function = append
}
}]
}).
-define(ATM_WORKFLOW_SCHEMA_DRAFT, #atm_workflow_schema_dump_draft{
name = str_utils:to_binary(?FUNCTION_NAME),
revision_num = 1,
revision = #atm_workflow_schema_revision_draft{
stores = [
?INTEGER_ATM_LIST_STORE_SCHEMA_DRAFT(?ITERATED_STORE_SCHEMA_ID, lists:seq(1, 10)),
?INTEGER_ATM_LIST_STORE_SCHEMA_DRAFT(?TARGET_STORE_SCHEMA_ID)
],
lanes = [#atm_lane_schema_draft{
parallel_boxes = [#atm_parallel_box_schema_draft{tasks = [
?ATM_TASK_SCHEMA_DRAFT(<<"task0">>)
]}],
store_iterator_spec = #atm_store_iterator_spec_draft{
store_schema_id = ?ITERATED_STORE_SCHEMA_ID
},
max_retries = 2
}]
},
supplementary_lambdas = #{
?ECHO_LAMBDA_ID => #{?ECHO_LAMBDA_REVISION_NUM => ?ECHO_LAMBDA_DRAFT(
?ATM_NUMBER_DATA_SPEC, ?RAND_ELEMENT([return_value, file_pipe])
)}
}
}).
%%%===================================================================
%%% Tests
%%%===================================================================
finish_atm_workflow_execution() ->
AssertActionsNotPossibleOnNotStoppedExecution = fun(AtmMockCallCtx) ->
atm_workflow_execution_test_utils:assert_not_stopped_workflow_execution_can_not_be_repeated_resumed_nor_discarded(
{1, 1}, AtmMockCallCtx
)
end,
Lane1Run1StepMockSpecBase = #atm_step_mock_spec{
before_step_hook = AssertActionsNotPossibleOnNotStoppedExecution,
after_step_hook = AssertActionsNotPossibleOnNotStoppedExecution
},
atm_workflow_execution_test_runner:run(#atm_workflow_execution_test_spec{
workflow_schema_dump_or_draft = ?ATM_WORKFLOW_SCHEMA_DRAFT,
incarnations = [#atm_workflow_execution_incarnation_test_spec{
incarnation_num = 1,
lane_runs = [#atm_lane_run_execution_test_spec{
selector = {1, 1},
prepare_lane = Lane1Run1StepMockSpecBase,
create_run = Lane1Run1StepMockSpecBase,
run_task_for_item = Lane1Run1StepMockSpecBase,
process_task_result_for_item = Lane1Run1StepMockSpecBase,
handle_task_execution_stopped = Lane1Run1StepMockSpecBase,
handle_lane_execution_stopped = #atm_step_mock_spec{
before_step_hook = AssertActionsNotPossibleOnNotStoppedExecution,
after_step_hook = fun(AtmMockCallCtx) ->
% While atm workflow execution as whole has not yet transition to finished status
% (last step remaining) the current lane run did. At this point stopping it
% is no longer possible (execution is treated as successfully ended)
lists:foreach(fun(StoppingReason) ->
?assertEqual(
?ERROR_ATM_INVALID_STATUS_TRANSITION(?FINISHED_STATUS, ?STOPPING_STATUS),
atm_workflow_execution_test_utils:stop_workflow_execution(
StoppingReason, AtmMockCallCtx
)
)
end, ?STOPPING_REASONS),
AssertActionsNotPossibleOnNotStoppedExecution(AtmMockCallCtx)
end
}
}],
handle_workflow_execution_stopped = #atm_step_mock_spec{
after_step_exp_state_diff = [
{lane_runs, [{1, 1}], rerunable},
workflow_finished
]
},
after_hook = fun atm_workflow_execution_test_utils:assert_ended_workflow_execution_can_be_neither_stopped_nor_resumed/1
}]
}).
| null | https://raw.githubusercontent.com/onedata/op-worker/2c347ac8c1a3f7f9723d4b1825bd915df0f49dde/test_distributed/suites/automation/execution/atm_workflow_execution_finish_tests.erl | erlang | -------------------------------------------------------------------
@end
-------------------------------------------------------------------
@doc
Tests concerning successfully finished automation workflow execution.
@end
-------------------------------------------------------------------
===================================================================
Tests
===================================================================
While atm workflow execution as whole has not yet transition to finished status
(last step remaining) the current lane run did. At this point stopping it
is no longer possible (execution is treated as successfully ended) | @author
( C ) 2022 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
-module(atm_workflow_execution_finish_tests).
-author("Bartosz Walkowicz").
-include("atm_workflow_execution_test.hrl").
-include("modules/automation/atm_execution.hrl").
-export([
finish_atm_workflow_execution/0
]).
-define(ITERATED_STORE_SCHEMA_ID, <<"iterated_store_id">>).
-define(TARGET_STORE_SCHEMA_ID, <<"target_store_id">>).
-define(ATM_TASK_SCHEMA_DRAFT(__ID), #atm_task_schema_draft{
id = __ID,
lambda_id = ?ECHO_LAMBDA_ID,
lambda_revision_number = ?ECHO_LAMBDA_REVISION_NUM,
argument_mappings = [?ITERATED_ITEM_ARG_MAPPER(?ECHO_ARG_NAME)],
result_mappings = [#atm_task_schema_result_mapper{
result_name = ?ECHO_ARG_NAME,
store_schema_id = ?TARGET_STORE_SCHEMA_ID,
store_content_update_options = #atm_list_store_content_update_options{
function = append
}
}]
}).
-define(ATM_WORKFLOW_SCHEMA_DRAFT, #atm_workflow_schema_dump_draft{
name = str_utils:to_binary(?FUNCTION_NAME),
revision_num = 1,
revision = #atm_workflow_schema_revision_draft{
stores = [
?INTEGER_ATM_LIST_STORE_SCHEMA_DRAFT(?ITERATED_STORE_SCHEMA_ID, lists:seq(1, 10)),
?INTEGER_ATM_LIST_STORE_SCHEMA_DRAFT(?TARGET_STORE_SCHEMA_ID)
],
lanes = [#atm_lane_schema_draft{
parallel_boxes = [#atm_parallel_box_schema_draft{tasks = [
?ATM_TASK_SCHEMA_DRAFT(<<"task0">>)
]}],
store_iterator_spec = #atm_store_iterator_spec_draft{
store_schema_id = ?ITERATED_STORE_SCHEMA_ID
},
max_retries = 2
}]
},
supplementary_lambdas = #{
?ECHO_LAMBDA_ID => #{?ECHO_LAMBDA_REVISION_NUM => ?ECHO_LAMBDA_DRAFT(
?ATM_NUMBER_DATA_SPEC, ?RAND_ELEMENT([return_value, file_pipe])
)}
}
}).
finish_atm_workflow_execution() ->
AssertActionsNotPossibleOnNotStoppedExecution = fun(AtmMockCallCtx) ->
atm_workflow_execution_test_utils:assert_not_stopped_workflow_execution_can_not_be_repeated_resumed_nor_discarded(
{1, 1}, AtmMockCallCtx
)
end,
Lane1Run1StepMockSpecBase = #atm_step_mock_spec{
before_step_hook = AssertActionsNotPossibleOnNotStoppedExecution,
after_step_hook = AssertActionsNotPossibleOnNotStoppedExecution
},
atm_workflow_execution_test_runner:run(#atm_workflow_execution_test_spec{
workflow_schema_dump_or_draft = ?ATM_WORKFLOW_SCHEMA_DRAFT,
incarnations = [#atm_workflow_execution_incarnation_test_spec{
incarnation_num = 1,
lane_runs = [#atm_lane_run_execution_test_spec{
selector = {1, 1},
prepare_lane = Lane1Run1StepMockSpecBase,
create_run = Lane1Run1StepMockSpecBase,
run_task_for_item = Lane1Run1StepMockSpecBase,
process_task_result_for_item = Lane1Run1StepMockSpecBase,
handle_task_execution_stopped = Lane1Run1StepMockSpecBase,
handle_lane_execution_stopped = #atm_step_mock_spec{
before_step_hook = AssertActionsNotPossibleOnNotStoppedExecution,
after_step_hook = fun(AtmMockCallCtx) ->
lists:foreach(fun(StoppingReason) ->
?assertEqual(
?ERROR_ATM_INVALID_STATUS_TRANSITION(?FINISHED_STATUS, ?STOPPING_STATUS),
atm_workflow_execution_test_utils:stop_workflow_execution(
StoppingReason, AtmMockCallCtx
)
)
end, ?STOPPING_REASONS),
AssertActionsNotPossibleOnNotStoppedExecution(AtmMockCallCtx)
end
}
}],
handle_workflow_execution_stopped = #atm_step_mock_spec{
after_step_exp_state_diff = [
{lane_runs, [{1, 1}], rerunable},
workflow_finished
]
},
after_hook = fun atm_workflow_execution_test_utils:assert_ended_workflow_execution_can_be_neither_stopped_nor_resumed/1
}]
}).
|
3a527101ef4db8a7cc96f5d4200b142cdced63dd142348903f24c5b6857d54e9 | jorinvo/letsdo.events | settings.clj | (ns lde.core.settings
(:require [buddy.core.codecs :refer [bytes->str bytes->hex str->bytes]]
[buddy.core.codecs.base64 :as base64]
[buddy.core.nonce :as nonce]
[lde.core.db :as db]))
(defn get-cookie-secret [ctx]
(db/tx ctx
(if-let [secret (db/get-key ctx :settings/cookie-secret)]
(base64/decode (str->bytes secret))
(let [new-secret (nonce/random-bytes 16)]
(db/set-key! ctx :settings/cookie-secret (bytes->str (base64/encode new-secret)))
new-secret))))
(defn get-jwt-secret [ctx]
(db/tx ctx
(if-let [secret (db/get-key ctx :settings/jwt-secret)]
secret
(let [new-secret (bytes->hex (nonce/random-bytes 32))]
(db/set-key! ctx :settings/jwt-secret new-secret)
new-secret))))
| null | https://raw.githubusercontent.com/jorinvo/letsdo.events/4cd2a5d401d37524c0bac265f48923ab5f91b220/src/lde/core/settings.clj | clojure | (ns lde.core.settings
(:require [buddy.core.codecs :refer [bytes->str bytes->hex str->bytes]]
[buddy.core.codecs.base64 :as base64]
[buddy.core.nonce :as nonce]
[lde.core.db :as db]))
(defn get-cookie-secret [ctx]
(db/tx ctx
(if-let [secret (db/get-key ctx :settings/cookie-secret)]
(base64/decode (str->bytes secret))
(let [new-secret (nonce/random-bytes 16)]
(db/set-key! ctx :settings/cookie-secret (bytes->str (base64/encode new-secret)))
new-secret))))
(defn get-jwt-secret [ctx]
(db/tx ctx
(if-let [secret (db/get-key ctx :settings/jwt-secret)]
secret
(let [new-secret (bytes->hex (nonce/random-bytes 32))]
(db/set-key! ctx :settings/jwt-secret new-secret)
new-secret))))
| |
f1c8e350f7620b746d537282feceb1b12d5caf7f3958ed4606dd3ece9756fa78 | adamrk/scheme2luac | Spec.hs | import Assembler
import CodeGenerator
import Test.Hspec
import Test.QuickCheck
import System.Process
import System.FilePath
import System.Exit
import System.Directory
import qualified Data.Map as M
import Data.List (nub, sort, groupBy)
import Data.Char (isAlpha)
endVal :: String -> String
endVal s = let ls = lines s
n = length ls
in drop 8 $ ls !! (n - 5)
fileExCompare :: [String] -> String -> SpecWith ()
fileExCompare res s =
let outfile = replaceExtension s "luac"
resultfile = replaceExtension s "result"
in
do
(exitcode, b, _) <- runIO $ do
f <- compileFromFile s
case maybeToEither f >>= finalBuilder of
Right bs -> writeBuilder outfile bs
Left s -> print $ "assembly error: " ++ s
readCreateProcessWithExitCode (shell $ "lua " ++ outfile) ""
a <- if resultfile `elem` res
then runIO $ readFile resultfile
else runIO $ do
(_,r,_) <- readCreateProcessWithExitCode (shell $ "scheme < " ++ s) ""
return (endVal r)
it s $ do
exitcode `shouldBe` ExitSuccess
a `shouldBe` (head . lines $ b)
bytecodeParses :: String -> LuaFunc -> SpecWith ()
bytecodeParses s luafunc = do
(exitCode, stdOut, stdErr) <- runIO $
case finalBuilder luafunc of
Right bs -> writeBuilder outfile bs >> do
readCreateProcessWithExitCode (shell $ "luac -l -l " ++ outfile) ""
Left s -> return (ExitFailure 101, "AssemblyError: " ++ s, "AssemblyError: " ++ s)
it (s ++ " assembled") $ exitCode `shouldNotBe` (ExitFailure 101)
it (s ++ " valid bytecode") $ exitCode `shouldBe` ExitSuccess
where outfile = "test/testfiles/temp.luac"
main :: IO ()
main = hspec $ do
(testFiles, resultFiles) <- runIO $ do
files <- listDirectory "test/testfiles"
let test = groupBy (\x y -> (takeWhile isAlpha x == takeWhile isAlpha y))
. sort
. filter ((== ".scm") . takeExtension)
$ files
results = filter ((== ".result") . takeExtension) files
return $ (test, results)
mapM_ (run (map ("test/testfiles/" ++) resultFiles)) testFiles
describe "bytecodeParses"
$ mapM_ (uncurry bytecodeParses) primitives
where
run res xs = let name = takeWhile isAlpha (head xs)
in describe (name ++ " tests") $
mapM_ (fileExCompare res . ("test/testfiles/" ++)) xs | null | https://raw.githubusercontent.com/adamrk/scheme2luac/5e64008b57a574c0afce72513363a176c7dcf299/test/Spec.hs | haskell | import Assembler
import CodeGenerator
import Test.Hspec
import Test.QuickCheck
import System.Process
import System.FilePath
import System.Exit
import System.Directory
import qualified Data.Map as M
import Data.List (nub, sort, groupBy)
import Data.Char (isAlpha)
endVal :: String -> String
endVal s = let ls = lines s
n = length ls
in drop 8 $ ls !! (n - 5)
fileExCompare :: [String] -> String -> SpecWith ()
fileExCompare res s =
let outfile = replaceExtension s "luac"
resultfile = replaceExtension s "result"
in
do
(exitcode, b, _) <- runIO $ do
f <- compileFromFile s
case maybeToEither f >>= finalBuilder of
Right bs -> writeBuilder outfile bs
Left s -> print $ "assembly error: " ++ s
readCreateProcessWithExitCode (shell $ "lua " ++ outfile) ""
a <- if resultfile `elem` res
then runIO $ readFile resultfile
else runIO $ do
(_,r,_) <- readCreateProcessWithExitCode (shell $ "scheme < " ++ s) ""
return (endVal r)
it s $ do
exitcode `shouldBe` ExitSuccess
a `shouldBe` (head . lines $ b)
bytecodeParses :: String -> LuaFunc -> SpecWith ()
bytecodeParses s luafunc = do
(exitCode, stdOut, stdErr) <- runIO $
case finalBuilder luafunc of
Right bs -> writeBuilder outfile bs >> do
readCreateProcessWithExitCode (shell $ "luac -l -l " ++ outfile) ""
Left s -> return (ExitFailure 101, "AssemblyError: " ++ s, "AssemblyError: " ++ s)
it (s ++ " assembled") $ exitCode `shouldNotBe` (ExitFailure 101)
it (s ++ " valid bytecode") $ exitCode `shouldBe` ExitSuccess
where outfile = "test/testfiles/temp.luac"
main :: IO ()
main = hspec $ do
(testFiles, resultFiles) <- runIO $ do
files <- listDirectory "test/testfiles"
let test = groupBy (\x y -> (takeWhile isAlpha x == takeWhile isAlpha y))
. sort
. filter ((== ".scm") . takeExtension)
$ files
results = filter ((== ".result") . takeExtension) files
return $ (test, results)
mapM_ (run (map ("test/testfiles/" ++) resultFiles)) testFiles
describe "bytecodeParses"
$ mapM_ (uncurry bytecodeParses) primitives
where
run res xs = let name = takeWhile isAlpha (head xs)
in describe (name ++ " tests") $
mapM_ (fileExCompare res . ("test/testfiles/" ++)) xs | |
87f0b5b7268c06b58342edf8b6cfc068ee85d7cc2edffbd070816aee4722e555 | qiao/sicp-solutions | 3.48.scm | If a process want to acquire a2 , then it must acquire a1 first ,
and two processes can not acquire a1 at the same time , therefore ,
;; the deadlock is avoided.
(define (make-account number balance)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance account))
balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount))
balance)
(let ((protected (make-serializer)))
(define (dispatch m)
(cond ((eq? m 'withdraw) (protected withdraw))
((eq? m 'deposit) (protected deposit))
((eq? m 'serializer) protected)
((eq? m 'balance) balance)
((eq? m 'number) number)
(else (error "Unknown request -- MAKE-ACCOUNT"
m))))
dispatch))
(define (serialized-exchange account1 account2)
(let ((serializer1 (account1 'serializer))
(serializer2 (account2 'serializer))
(number1 (account1 'number))
(number2 (account2 'number)))
(if (< number1 number2)
((serializer2 (serializer1 exchange)) account1 account2)
((serializer1 (serializer2 exchange)) account1 account2))))
| null | https://raw.githubusercontent.com/qiao/sicp-solutions/a2fe069ba6909710a0867bdb705b2e58b2a281af/chapter3/3.48.scm | scheme | the deadlock is avoided. | If a process want to acquire a2 , then it must acquire a1 first ,
and two processes can not acquire a1 at the same time , therefore ,
(define (make-account number balance)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance account))
balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount))
balance)
(let ((protected (make-serializer)))
(define (dispatch m)
(cond ((eq? m 'withdraw) (protected withdraw))
((eq? m 'deposit) (protected deposit))
((eq? m 'serializer) protected)
((eq? m 'balance) balance)
((eq? m 'number) number)
(else (error "Unknown request -- MAKE-ACCOUNT"
m))))
dispatch))
(define (serialized-exchange account1 account2)
(let ((serializer1 (account1 'serializer))
(serializer2 (account2 'serializer))
(number1 (account1 'number))
(number2 (account2 'number)))
(if (< number1 number2)
((serializer2 (serializer1 exchange)) account1 account2)
((serializer1 (serializer2 exchange)) account1 account2))))
|
5a0f46e86305eb13dfaee885bf4fef48eb79b3dbbba0fb85ec14fcc3d8f7986b | mbutterick/aoc-racket | star1.rkt | 4144
165,1,255,31,87,52,24,113,0,91,148,254,158,2,73,153 | null | https://raw.githubusercontent.com/mbutterick/aoc-racket/2c6cb2f3ad876a91a82f33ce12844f7758b969d6/2017/d10/star1.rkt | racket | 4144
165,1,255,31,87,52,24,113,0,91,148,254,158,2,73,153 | |
a70964363318298f42a71c504ad2c9f239f9afc33194aec2c5df3a29b748269b | screenshotbot/screenshotbot-oss | test-store.lisp | ;;;; Copyright 2018-Present Modern Interpreters Inc.
;;;;
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(uiop:define-package :util/tests/test-store
(:use #:cl
#:fiveam
#:alexandria)
(:import-from #:util/store
#:with-snapshot-lock
#:*snapshot-hooks*
#:dispatch-snapshot-hooks
#:location-for-oid
#:def-store-local
#:find-any-refs
#:register-ref
#:with-test-store
#:parse-timetag
#:*object-store*
#:object-store)
(:import-from #:local-time
#:timestamp=)
(:import-from #:bknr.datastore
#:store-object)
(:import-from #:bknr.datastore
#:persistent-class)
(:import-from #:bknr.datastore
#:all-store-objects)
(:import-from #:bknr.indices
#:hash-index)
(:import-from #:bknr.datastore
#:delete-object)
(:import-from #:bknr.datastore
#:*store*))
(in-package :util/tests/test-store)
(util/fiveam:def-suite)
(test object-store
(tmpdir:with-tmpdir (tmp)
(let ((*object-store* (namestring (path:catfile tmp "dummy/"))))
(is (pathnamep (object-store)))
(is (path:-d (object-store)))))
(tmpdir:with-tmpdir (tmp)
(let ((*object-store* (namestring (path:catfile tmp "dummy"))))
(is (pathnamep (object-store)))
(is (path:-d (object-store)))))
#+nil ;; bad test that modifies global state
(let ((*object-store* "~/zoidberg/bar/"))
(is (equal #P "~/zoidberg/bar/" (object-store)))
(is (path:-d (object-store)))))
#+lispworks
(test parse-timetag
(is
(timestamp=
(local-time:parse-timestring "2021-10-09T06:00:00")
(parse-timetag "20211009T060000"))))
(defclass dummy-class (store-object)
((name :initarg :name
:index-type hash-index
:index-initargs (:test #'equal)
:index-reader dummy-class-for-name))
(:metaclass persistent-class))
(test with-test-store
(with-test-store ()
(make-instance 'dummy-class)
(make-instance 'dummy-class :name "bleh")
(is (eql 2 (length (all-store-objects))))
(is (eql 1 (length (dummy-class-for-name "bleh")))))
(is (eql 0 (length (all-store-objects))))
(is (eql 0 (length (dummy-class-for-name "bleh"))))
(with-test-store ()
(is (eql 0 (length (all-store-objects)))))
(is (eql 0 (length (dummy-class-for-name "bleh")))))
(defclass xyz (store-object)
()
(:metaclass persistent-class))
(defclass abc (store-object)
((ref :initarg :ref))
(:metaclass persistent-class))
(def-fixture refs ()
(with-test-store ()
(&body)))
(test create-object-and-reference
(with-test-store ()
(let* ((xyz (make-instance 'xyz))
(xyz-2 (make-instance 'xyz))
(abc (make-instance 'abc :ref xyz)))
(is (equal (list xyz abc) (find-any-refs (list xyz)))))
(let* ((xyz (make-instance 'xyz))
(abc (make-instance 'abc :ref (list xyz))))
(is (equal (list xyz abc) (find-any-refs (list xyz)))))
(let* ((xyz (make-instance 'xyz))
(abc (make-instance 'abc :ref (make-array 1 :initial-contents (list xyz)))))
(is (equal (list xyz abc) (find-any-refs (list xyz)))))))
(test transitive-refs
(with-test-store ()
(let* ((xyz (make-instance 'xyz))
(abc-1 (make-instance 'abc :ref xyz))
(abc (make-instance 'abc :ref abc-1)))
(is (equal (list xyz abc-1 abc) (find-any-refs (list xyz))))))
(with-test-store ()
(let* ((xyz (make-instance 'xyz))
(abc-1 (make-instance 'abc :ref xyz))
(abc (make-instance 'abc :ref abc-1)))
(is (equal (list xyz abc-1 abc) (find-any-refs (list abc-1 xyz)))))))
(test nested-in-list-refs
(with-test-store ()
(let* ((xyz (make-instance 'xyz))
(abc-1 (make-instance 'abc :ref xyz))
(abc (make-instance 'abc :ref (list 1 2 abc-1))))
(is (equal (list xyz abc-1 abc) (find-any-refs (list xyz))))))
(with-test-store ()
(let* ((xyz (make-instance 'xyz))
(abc-1 (make-instance 'abc :ref xyz))
(abc (make-instance 'abc :ref (list xyz 2 abc-1))))
(is (equal (list xyz abc-1 abc) (find-any-refs (list xyz))))))
(with-test-store ()
(let* ((xyz (make-instance 'xyz))
(abc-1 (make-instance 'abc :ref xyz))
(abc (make-instance 'abc :ref (list abc-1 2 xyz))))
(is (equal (list xyz abc-1 abc) (find-any-refs (list xyz)))))))
(def-store-local *store-local* (make-hash-table)
"A test cache")
(test store-local
(let (one two)
(with-test-store ()
(setf one *store-local*)
(is (eql one *store-local*)))
(with-test-store ()
(setf two *store-local*)
(is (not (eql one two))))))
(test setf-store-local
(let (one two)
(with-test-store ()
(setf *store-local* 'foo)
(is (eql *store-local* 'foo)))
(with-test-store ()
(is (not (eql 'foo *store-local*)))
(setf *store-local* 'bar)
(is (eql 'bar *store-local*)))))
(test store-local-with-a-store
(signals unbound-variable *store-local*))
(defun fix-for-windows (x)
(cond
((uiop:os-windows-p)
(str:replace-all "/" "\\" x))
(t
x)))
(test location-for-oid--ensure-directory-is-writeable
(with-test-store ()
(with-open-file (file (location-for-oid #P"foo-bar/" (mongoid:oid))
:direction :output)
(write-string "hello" file))
(pass)))
(test location-for-oid/expected-pathname
(with-test-store ()
(let ((pathname (location-for-oid #P "foo-bar/" #(#xab #xbc #x01 #x23
#xab #xbc #x01 #x23
#xab #xbc #x01 #x23))))
(is (str:ends-with-p
(fix-for-windows "foo-bar/ab/bc/0123abbc0123abbc0123")
(namestring pathname)))
;; Ensure absolute
(is (not (str:starts-with-p "foo-bar" (namestring pathname)))))))
(test location-for-oid/expected-relative-path
(with-test-store ()
(let ((pathname (nth-value
1
(location-for-oid #P "foo-bar/" #(#xab #xbc #x01 #x23
#xab #xbc #x01 #x23
#xab #xbc #x01 #x23)))))
(is (string=
(fix-for-windows "foo-bar/ab/bc/0123abbc0123abbc0123")
(namestring pathname))))))
(test location-for-oid/with-suffix
(with-test-store ()
(let ((pathname (location-for-oid #P "foo-bar/" #(#xab #xbc #x01 #x23
#xab #xbc #x01 #x23
#xab #xbc #x01 #x23)
:suffix "metadata")))
(is (str:ends-with-p
(fix-for-windows "foo-bar/ab/bc/0123abbc0123abbc0123-metadata")
(namestring pathname))))))
(test cant-access-deleted-object-slots
"This is checking some changes we have in bknr.datastore. In particular,
making sure our slot-value-using-class is correctly wired. (See
indexed-class.lisp or D5784)"
(with-test-store ()
(let ((obj (make-instance 'dummy-class :name "foo")))
(is (equal "foo" (slot-value obj 'name)))
(delete-object obj)
(handler-case
(progn
(slot-value obj 'name)
(fail "expected error"))
(error (e)
(is (str:containsp "Can not get slot NAME of destroyed"
(format nil "~a" e))))))))
(test dispatch-snapshot-hooks
(with-test-store ()
(let (ret)
(flet ((hook (store dir)
(push dir ret)))
(let ((*snapshot-hooks* (list #'hook)))
(dispatch-snapshot-hooks :foo))
(is (equal (list :foo) ret))))))
(test safe-snapshot-happy-path
(with-test-store ()
(let ((*snapshot-hooks* nil))
(util:safe-snapshot "dummy"))))
(test |body get's called :/|
(let ((calledp nil))
(with-test-store ()
(setf calledp t))
(is-true calledp)))
(test snapshot-lock
(with-test-store ()
(is
(eql :foo
(with-snapshot-lock (*store*)
:foo)))))
| null | https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/d05cdcf1f180de4c4dd3f5f8f81aaae727e2a99d/src/util/tests/test-store.lisp | lisp | Copyright 2018-Present Modern Interpreters Inc.
bad test that modifies global state
Ensure absolute | 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 /.
(uiop:define-package :util/tests/test-store
(:use #:cl
#:fiveam
#:alexandria)
(:import-from #:util/store
#:with-snapshot-lock
#:*snapshot-hooks*
#:dispatch-snapshot-hooks
#:location-for-oid
#:def-store-local
#:find-any-refs
#:register-ref
#:with-test-store
#:parse-timetag
#:*object-store*
#:object-store)
(:import-from #:local-time
#:timestamp=)
(:import-from #:bknr.datastore
#:store-object)
(:import-from #:bknr.datastore
#:persistent-class)
(:import-from #:bknr.datastore
#:all-store-objects)
(:import-from #:bknr.indices
#:hash-index)
(:import-from #:bknr.datastore
#:delete-object)
(:import-from #:bknr.datastore
#:*store*))
(in-package :util/tests/test-store)
(util/fiveam:def-suite)
(test object-store
(tmpdir:with-tmpdir (tmp)
(let ((*object-store* (namestring (path:catfile tmp "dummy/"))))
(is (pathnamep (object-store)))
(is (path:-d (object-store)))))
(tmpdir:with-tmpdir (tmp)
(let ((*object-store* (namestring (path:catfile tmp "dummy"))))
(is (pathnamep (object-store)))
(is (path:-d (object-store)))))
(let ((*object-store* "~/zoidberg/bar/"))
(is (equal #P "~/zoidberg/bar/" (object-store)))
(is (path:-d (object-store)))))
#+lispworks
(test parse-timetag
(is
(timestamp=
(local-time:parse-timestring "2021-10-09T06:00:00")
(parse-timetag "20211009T060000"))))
(defclass dummy-class (store-object)
((name :initarg :name
:index-type hash-index
:index-initargs (:test #'equal)
:index-reader dummy-class-for-name))
(:metaclass persistent-class))
(test with-test-store
(with-test-store ()
(make-instance 'dummy-class)
(make-instance 'dummy-class :name "bleh")
(is (eql 2 (length (all-store-objects))))
(is (eql 1 (length (dummy-class-for-name "bleh")))))
(is (eql 0 (length (all-store-objects))))
(is (eql 0 (length (dummy-class-for-name "bleh"))))
(with-test-store ()
(is (eql 0 (length (all-store-objects)))))
(is (eql 0 (length (dummy-class-for-name "bleh")))))
(defclass xyz (store-object)
()
(:metaclass persistent-class))
(defclass abc (store-object)
((ref :initarg :ref))
(:metaclass persistent-class))
(def-fixture refs ()
(with-test-store ()
(&body)))
(test create-object-and-reference
(with-test-store ()
(let* ((xyz (make-instance 'xyz))
(xyz-2 (make-instance 'xyz))
(abc (make-instance 'abc :ref xyz)))
(is (equal (list xyz abc) (find-any-refs (list xyz)))))
(let* ((xyz (make-instance 'xyz))
(abc (make-instance 'abc :ref (list xyz))))
(is (equal (list xyz abc) (find-any-refs (list xyz)))))
(let* ((xyz (make-instance 'xyz))
(abc (make-instance 'abc :ref (make-array 1 :initial-contents (list xyz)))))
(is (equal (list xyz abc) (find-any-refs (list xyz)))))))
(test transitive-refs
(with-test-store ()
(let* ((xyz (make-instance 'xyz))
(abc-1 (make-instance 'abc :ref xyz))
(abc (make-instance 'abc :ref abc-1)))
(is (equal (list xyz abc-1 abc) (find-any-refs (list xyz))))))
(with-test-store ()
(let* ((xyz (make-instance 'xyz))
(abc-1 (make-instance 'abc :ref xyz))
(abc (make-instance 'abc :ref abc-1)))
(is (equal (list xyz abc-1 abc) (find-any-refs (list abc-1 xyz)))))))
(test nested-in-list-refs
(with-test-store ()
(let* ((xyz (make-instance 'xyz))
(abc-1 (make-instance 'abc :ref xyz))
(abc (make-instance 'abc :ref (list 1 2 abc-1))))
(is (equal (list xyz abc-1 abc) (find-any-refs (list xyz))))))
(with-test-store ()
(let* ((xyz (make-instance 'xyz))
(abc-1 (make-instance 'abc :ref xyz))
(abc (make-instance 'abc :ref (list xyz 2 abc-1))))
(is (equal (list xyz abc-1 abc) (find-any-refs (list xyz))))))
(with-test-store ()
(let* ((xyz (make-instance 'xyz))
(abc-1 (make-instance 'abc :ref xyz))
(abc (make-instance 'abc :ref (list abc-1 2 xyz))))
(is (equal (list xyz abc-1 abc) (find-any-refs (list xyz)))))))
(def-store-local *store-local* (make-hash-table)
"A test cache")
(test store-local
(let (one two)
(with-test-store ()
(setf one *store-local*)
(is (eql one *store-local*)))
(with-test-store ()
(setf two *store-local*)
(is (not (eql one two))))))
(test setf-store-local
(let (one two)
(with-test-store ()
(setf *store-local* 'foo)
(is (eql *store-local* 'foo)))
(with-test-store ()
(is (not (eql 'foo *store-local*)))
(setf *store-local* 'bar)
(is (eql 'bar *store-local*)))))
(test store-local-with-a-store
(signals unbound-variable *store-local*))
(defun fix-for-windows (x)
(cond
((uiop:os-windows-p)
(str:replace-all "/" "\\" x))
(t
x)))
(test location-for-oid--ensure-directory-is-writeable
(with-test-store ()
(with-open-file (file (location-for-oid #P"foo-bar/" (mongoid:oid))
:direction :output)
(write-string "hello" file))
(pass)))
(test location-for-oid/expected-pathname
(with-test-store ()
(let ((pathname (location-for-oid #P "foo-bar/" #(#xab #xbc #x01 #x23
#xab #xbc #x01 #x23
#xab #xbc #x01 #x23))))
(is (str:ends-with-p
(fix-for-windows "foo-bar/ab/bc/0123abbc0123abbc0123")
(namestring pathname)))
(is (not (str:starts-with-p "foo-bar" (namestring pathname)))))))
(test location-for-oid/expected-relative-path
(with-test-store ()
(let ((pathname (nth-value
1
(location-for-oid #P "foo-bar/" #(#xab #xbc #x01 #x23
#xab #xbc #x01 #x23
#xab #xbc #x01 #x23)))))
(is (string=
(fix-for-windows "foo-bar/ab/bc/0123abbc0123abbc0123")
(namestring pathname))))))
(test location-for-oid/with-suffix
(with-test-store ()
(let ((pathname (location-for-oid #P "foo-bar/" #(#xab #xbc #x01 #x23
#xab #xbc #x01 #x23
#xab #xbc #x01 #x23)
:suffix "metadata")))
(is (str:ends-with-p
(fix-for-windows "foo-bar/ab/bc/0123abbc0123abbc0123-metadata")
(namestring pathname))))))
(test cant-access-deleted-object-slots
"This is checking some changes we have in bknr.datastore. In particular,
making sure our slot-value-using-class is correctly wired. (See
indexed-class.lisp or D5784)"
(with-test-store ()
(let ((obj (make-instance 'dummy-class :name "foo")))
(is (equal "foo" (slot-value obj 'name)))
(delete-object obj)
(handler-case
(progn
(slot-value obj 'name)
(fail "expected error"))
(error (e)
(is (str:containsp "Can not get slot NAME of destroyed"
(format nil "~a" e))))))))
(test dispatch-snapshot-hooks
(with-test-store ()
(let (ret)
(flet ((hook (store dir)
(push dir ret)))
(let ((*snapshot-hooks* (list #'hook)))
(dispatch-snapshot-hooks :foo))
(is (equal (list :foo) ret))))))
(test safe-snapshot-happy-path
(with-test-store ()
(let ((*snapshot-hooks* nil))
(util:safe-snapshot "dummy"))))
(test |body get's called :/|
(let ((calledp nil))
(with-test-store ()
(setf calledp t))
(is-true calledp)))
(test snapshot-lock
(with-test-store ()
(is
(eql :foo
(with-snapshot-lock (*store*)
:foo)))))
|
5e84fd87df2d7440937e595c4e7fc2b7e15cc32f95d73874dbff78b759b42134 | naproche/naproche | Verify.hs | -- |
Authors : ( 2001 - 2008 ) ,
( 2017 - 2018 ) ,
( 2021 - 2022 )
--
--Main verification loop.
module SAD.Core.Verify (verifyRoot) where
import Data.IORef (readIORef)
import Data.Maybe (isJust)
import Control.Monad.Reader
import Data.Text.Lazy qualified as Text
import SAD.Core.Base
import SAD.Core.Check (fillDef)
import SAD.Core.Extract (addDefinition, addEvaluation, extractRewriteRule)
import SAD.Core.ProofTask (generateProofTask)
import SAD.Core.Reason (proveThesis)
import SAD.Core.Rewrite (equalityReasoning)
import SAD.Core.Thesis (inferNewThesis)
import SAD.Data.Formula
import SAD.Data.Instr
import SAD.Data.Text.Block (Block(Block), ProofText(..), Section(..))
import SAD.Data.Text.Context (Context(Context))
import SAD.Helpers (notNull)
import SAD.Core.Message qualified as Message
import SAD.Data.Tag qualified as Tag
import SAD.Data.Text.Block qualified as Block
import SAD.Data.Text.Context qualified as Context
import SAD.Prove.MESON qualified as MESON
import SAD.Export.Prover qualified as Prover
import Isabelle.Library (trim_line, make_bytes)
import Isabelle.Position qualified as Position
-- | verify proof text (document root)
verifyRoot :: MESON.Cache -> Prover.Cache -> Position.T -> [ProofText] -> IO (Bool, [Tracker])
verifyRoot mesonCache proverCache filePos text = do
Message.outputReasoner Message.TRACING filePos "verification started"
state <- initVState mesonCache proverCache
result <- runVerifyMonad state (verify text)
trackers <- readIORef (trackers state)
let ignoredFails = sumCounter trackers FailedGoals
let success = isJust result && ignoredFails == 0
Message.outputReasoner Message.TRACING filePos $
"verification " <> (if success then "successful" else "failed")
return (success, trackers)
Main verification loop , based on mutual functions :
verify , verifyBlock , verifyProof
verify :: [ProofText] -> VerifyMonad [ProofText]
verify [] = do
motivated <- asks thesisMotivated
prove <- asks (getInstruction proveParam)
when (motivated && prove) verifyThesis >> return []
verify (ProofTextBlock block : rest) = verifyBlock block rest
verify (ProofTextInstr pos (Command cmd) : rest) = command cmd >> verify rest
where
command :: Command -> VerifyMonad ()
command PrintRules = do
rules <- asks rewriteRules
message $ "current ruleset: " <> "\n" <> unlines (map show (reverse rules))
command PrintThesis = do
motivated <- asks thesisMotivated
thesis <- asks currentThesis
let motivation = if motivated then "(motivated): " else "(not motivated): "
message $ "current thesis " <> motivation <> show (Context.formula thesis)
command PrintContext = do
context <- asks currentContext
message $ "current context:\n" <>
concatMap (\form -> " " <> show (Context.formula form) <> "\n") (reverse context)
command PrintContextFiltered = do
context <- asks currentContext
let topLevelContext = filter Context.isTopLevel context
message $ "current filtered top-level context:\n" <>
concatMap (\form -> " " <> show (Context.formula form) <> "\n") (reverse topLevelContext)
command _ = do
message "unsupported instruction"
message :: String -> VerifyMonad ()
message msg = reasonLog Message.WRITELN (Position.no_range_position pos) msg
verify (ProofTextInstr _ instr : rest) = local (addInstruction instr) (verify rest)
verify (ProofTextDrop _ instr : rest) = local (dropInstruction instr) (verify rest)
verify (_ : rest) = verify rest
verifyThesis :: VerifyMonad ()
verifyThesis = do
thesis <- asks currentThesis
let block = Context.head thesis
let text = Text.unpack $ Block.text block
let pos = Block.position block
whenInstruction printgoalParam $ reasonLog Message.TRACING pos $ "goal: " <> text
if hasDEC (Context.formula thesis) --computational reasoning
then do
incrementCounter Equations
timeWith SimplifyTimer (equalityReasoning pos thesis) <|> (
reasonLog Message.WARNING pos "equation failed" >>
guardInstruction skipfailParam >> incrementCounter FailedEquations)
else do
unless (isTop . Context.formula $ thesis) $ incrementCounter Goals
proveThesis pos <|> (
reasonLog Message.ERROR pos "goal failed" >>
guardInstruction skipfailParam >> incrementCounter FailedGoals)
verifyBlock :: Block -> [ProofText] -> VerifyMonad [ProofText]
verifyBlock block rest = do
state <- ask
let VState {
thesisMotivated = motivated,
rewriteRules = rules,
currentThesis = thesis,
currentBranch = branch,
currentContext = context,
mesonRules = mRules,
definitions = defs,
guards = grds,
evaluations = evaluations } = state
let Block f body kind _ _ _ _ = block
-- statistics and user communication
incrementCounter Sections
whenInstruction printsectionParam $ justIO $
Message.outputForTheL Message.WRITELN (Block.position block) $
make_bytes (trim_line (Block.showForm 0 block ""))
let newBranch = block : branch
let contextBlock = Context f newBranch []
whenInstruction translationParam $
unless (Block.isTopLevel block) $
translateLog Message.WRITELN (Block.position block) $ Text.pack $ show f
fortifiedFormula <-
if Block.isTopLevel block
then return f
-- For low-level blocks we check definitions and fortify terms (by supplying evidence).
else
fillDef (Block.position block) contextBlock
let proofTask = generateProofTask kind (Block.declaredNames block) fortifiedFormula
let freshThesis = Context proofTask newBranch []
let toBeProved = Block.needsProof block && not (Block.isTopLevel block)
proofBody <- do
flat <- asks (getInstruction flatParam)
if flat
then return []
else return body
whenInstruction printthesisParam $ when (
toBeProved && notNull proofBody &&
not (hasDEC $ Context.formula freshThesis)) $
thesisLog Message.WRITELN (Block.position block) (length branch - 1) $
"thesis: " <> show (Context.formula freshThesis)
fortifiedProof <-
local (\st -> st {
thesisMotivated = toBeProved,
currentThesis = freshThesis,
currentBranch = newBranch }) $
verifyProof (if toBeProved then proofBody else body)
-- in what follows we prepare the current block to contribute to the context,
-- extract rules, definitions and compute the new thesis
thesisSetting <- asks (getInstruction thesisParam)
let newBlock = block {
Block.formula = deleteInductionOrCase fortifiedFormula,
Block.body = fortifiedProof }
let formulaImage = Block.formulate newBlock
skolem <- asks skolemCounter
let (mesonRules, intermediateSkolem) = MESON.contras (deTag formulaImage) skolem
let (newDefinitions, newGuards) =
if kind == Definition || kind == Signature
then addDefinition (defs, grds) formulaImage
else (defs, grds)
let newContextBlock = Context formulaImage newBranch (uncurry (++) mesonRules)
let newContext = newContextBlock : context
let newRules =
if Block.isTopLevel block
then MESON.addRules mesonRules mRules
else mRules
let (newMotivation, hasChanged , newThesis) =
if thesisSetting
then inferNewThesis defs newContext thesis
else (Block.needsProof block, False, thesis)
whenInstruction printthesisParam $ when (
hasChanged && motivated && newMotivation &&
not (hasDEC $ Block.formula $ head branch) ) $
thesisLog Message.WRITELN (Block.position block) (length branch - 2) $
"new thesis: " <> show (Context.formula newThesis)
when (not newMotivation && motivated) $
thesisLog Message.WARNING (Block.position block) (length branch - 2) "unmotivated assumption"
let newRewriteRules = extractRewriteRule (head newContext) ++ rules
let newEvaluations =
if kind `elem` [LowDefinition, Definition]
then addEvaluation evaluations formulaImage
else evaluations-- extract evaluations
-- Now we are done with the block. Move on and verify the rest.
newBlocks <-
local (\st -> st {
thesisMotivated = motivated && newMotivation,
guards = newGuards,
rewriteRules = newRewriteRules,
evaluations = newEvaluations,
currentThesis = newThesis,
currentContext = newContext,
mesonRules = newRules,
definitions = newDefinitions,
skolemCounter = intermediateSkolem}) $ verifyProof rest
-- If this block made the thesis unmotivated, we must discharge a composite
-- (and possibly quite difficult) prove task
let finalThesis = Imp (Block.compose $ ProofTextBlock newBlock : newBlocks) (Context.formula thesis)
-- notice that the following is only really executed if
-- motivated && not newMotivated == True
local (\st -> st {
thesisMotivated = motivated && not newMotivation,
currentThesis = Context.setFormula thesis finalThesis }) $ verifyProof []
-- put everything together
return (ProofTextBlock newBlock : newBlocks)
{- some automated processing steps: add induction hypothesis and case hypothesis
at the right point in the context; extract rewriteRules from them and further
refine the currentThesis. Then move on with the verification loop.
If neither inductive nor case hypothesis is present this is the same as
verify state -}
verifyProof :: [ProofText] -> VerifyMonad [ProofText]
verifyProof restProofText = do
state <- ask
let VState {
rewriteRules = rules,
currentThesis = thesis,
currentContext = context,
currentBranch = branch} = state
let
process :: [Context] -> Formula -> VerifyMonad [ProofText]
process newContext f = do
let newRules = extractRewriteRule (head newContext) ++ rules
(_, _, newThesis) =
inferNewThesis (definitions state) newContext $ Context.setFormula thesis f
whenInstruction printthesisParam $ when (
noInductionOrCase (Context.formula newThesis) && not (null $ restProofText)) $
thesisLog Message.WRITELN
(Block.position $ head $ Context.branch $ head context) (length branch - 2) $
"new thesis " <> show (Context.formula newThesis)
local (\st -> st {
rewriteRules = newRules,
currentThesis = newThesis,
currentContext = newContext}) $ verifyProof restProofText
let
dive :: (Formula -> Formula) -> [Context] -> Formula -> VerifyMonad [ProofText]
dive construct context (Imp (Tag InductionHypothesis f) g)
| isClosed f = process (Context.setFormula thesis f : context) (construct g)
dive construct context (Imp (Tag Tag.CaseHypothesis f) g)
| isClosed f = process (thesis {Context.formula = f} : context) (construct g)
dive construct context (Imp f g) = dive (construct . Imp f) context g
dive construct context (All v f) = dive (construct . All v) context f
dive construct context (Tag tag f) = dive (construct . Tag tag) context f
dive _ _ _ = verify restProofText
-- extract rules, compute new thesis and move on with the verification
dive id context $ Context.formula thesis
{- checks that a formula containt neither induction nor case hyothesis -}
noInductionOrCase :: Formula -> Bool
noInductionOrCase (Tag InductionHypothesis _) = False
noInductionOrCase (Tag Tag.CaseHypothesis _) = False
noInductionOrCase f = allF noInductionOrCase f
{- delete induction or case hypothesis from a formula -}
deleteInductionOrCase :: Formula -> Formula
deleteInductionOrCase = dive id
where
dive :: (Formula -> a) -> Formula -> a
dive c (Imp (Tag InductionHypothesis _) f) = c f
dive c (Imp (Tag Tag.CaseHypothesis f) _) = c $ Not f
dive c (Imp f g) = dive (c . Imp f) g
dive c (All v f) = dive (c . All v) f
dive c f = c f
| null | https://raw.githubusercontent.com/naproche/naproche/6284a64b4b84eaa53dd0eb7ecb39737fb9135a0d/src/SAD/Core/Verify.hs | haskell | |
Main verification loop.
| verify proof text (document root)
computational reasoning
statistics and user communication
For low-level blocks we check definitions and fortify terms (by supplying evidence).
in what follows we prepare the current block to contribute to the context,
extract rules, definitions and compute the new thesis
extract evaluations
Now we are done with the block. Move on and verify the rest.
If this block made the thesis unmotivated, we must discharge a composite
(and possibly quite difficult) prove task
notice that the following is only really executed if
motivated && not newMotivated == True
put everything together
some automated processing steps: add induction hypothesis and case hypothesis
at the right point in the context; extract rewriteRules from them and further
refine the currentThesis. Then move on with the verification loop.
If neither inductive nor case hypothesis is present this is the same as
verify state
extract rules, compute new thesis and move on with the verification
checks that a formula containt neither induction nor case hyothesis
delete induction or case hypothesis from a formula | Authors : ( 2001 - 2008 ) ,
( 2017 - 2018 ) ,
( 2021 - 2022 )
module SAD.Core.Verify (verifyRoot) where
import Data.IORef (readIORef)
import Data.Maybe (isJust)
import Control.Monad.Reader
import Data.Text.Lazy qualified as Text
import SAD.Core.Base
import SAD.Core.Check (fillDef)
import SAD.Core.Extract (addDefinition, addEvaluation, extractRewriteRule)
import SAD.Core.ProofTask (generateProofTask)
import SAD.Core.Reason (proveThesis)
import SAD.Core.Rewrite (equalityReasoning)
import SAD.Core.Thesis (inferNewThesis)
import SAD.Data.Formula
import SAD.Data.Instr
import SAD.Data.Text.Block (Block(Block), ProofText(..), Section(..))
import SAD.Data.Text.Context (Context(Context))
import SAD.Helpers (notNull)
import SAD.Core.Message qualified as Message
import SAD.Data.Tag qualified as Tag
import SAD.Data.Text.Block qualified as Block
import SAD.Data.Text.Context qualified as Context
import SAD.Prove.MESON qualified as MESON
import SAD.Export.Prover qualified as Prover
import Isabelle.Library (trim_line, make_bytes)
import Isabelle.Position qualified as Position
verifyRoot :: MESON.Cache -> Prover.Cache -> Position.T -> [ProofText] -> IO (Bool, [Tracker])
verifyRoot mesonCache proverCache filePos text = do
Message.outputReasoner Message.TRACING filePos "verification started"
state <- initVState mesonCache proverCache
result <- runVerifyMonad state (verify text)
trackers <- readIORef (trackers state)
let ignoredFails = sumCounter trackers FailedGoals
let success = isJust result && ignoredFails == 0
Message.outputReasoner Message.TRACING filePos $
"verification " <> (if success then "successful" else "failed")
return (success, trackers)
Main verification loop , based on mutual functions :
verify , verifyBlock , verifyProof
verify :: [ProofText] -> VerifyMonad [ProofText]
verify [] = do
motivated <- asks thesisMotivated
prove <- asks (getInstruction proveParam)
when (motivated && prove) verifyThesis >> return []
verify (ProofTextBlock block : rest) = verifyBlock block rest
verify (ProofTextInstr pos (Command cmd) : rest) = command cmd >> verify rest
where
command :: Command -> VerifyMonad ()
command PrintRules = do
rules <- asks rewriteRules
message $ "current ruleset: " <> "\n" <> unlines (map show (reverse rules))
command PrintThesis = do
motivated <- asks thesisMotivated
thesis <- asks currentThesis
let motivation = if motivated then "(motivated): " else "(not motivated): "
message $ "current thesis " <> motivation <> show (Context.formula thesis)
command PrintContext = do
context <- asks currentContext
message $ "current context:\n" <>
concatMap (\form -> " " <> show (Context.formula form) <> "\n") (reverse context)
command PrintContextFiltered = do
context <- asks currentContext
let topLevelContext = filter Context.isTopLevel context
message $ "current filtered top-level context:\n" <>
concatMap (\form -> " " <> show (Context.formula form) <> "\n") (reverse topLevelContext)
command _ = do
message "unsupported instruction"
message :: String -> VerifyMonad ()
message msg = reasonLog Message.WRITELN (Position.no_range_position pos) msg
verify (ProofTextInstr _ instr : rest) = local (addInstruction instr) (verify rest)
verify (ProofTextDrop _ instr : rest) = local (dropInstruction instr) (verify rest)
verify (_ : rest) = verify rest
verifyThesis :: VerifyMonad ()
verifyThesis = do
thesis <- asks currentThesis
let block = Context.head thesis
let text = Text.unpack $ Block.text block
let pos = Block.position block
whenInstruction printgoalParam $ reasonLog Message.TRACING pos $ "goal: " <> text
then do
incrementCounter Equations
timeWith SimplifyTimer (equalityReasoning pos thesis) <|> (
reasonLog Message.WARNING pos "equation failed" >>
guardInstruction skipfailParam >> incrementCounter FailedEquations)
else do
unless (isTop . Context.formula $ thesis) $ incrementCounter Goals
proveThesis pos <|> (
reasonLog Message.ERROR pos "goal failed" >>
guardInstruction skipfailParam >> incrementCounter FailedGoals)
verifyBlock :: Block -> [ProofText] -> VerifyMonad [ProofText]
verifyBlock block rest = do
state <- ask
let VState {
thesisMotivated = motivated,
rewriteRules = rules,
currentThesis = thesis,
currentBranch = branch,
currentContext = context,
mesonRules = mRules,
definitions = defs,
guards = grds,
evaluations = evaluations } = state
let Block f body kind _ _ _ _ = block
incrementCounter Sections
whenInstruction printsectionParam $ justIO $
Message.outputForTheL Message.WRITELN (Block.position block) $
make_bytes (trim_line (Block.showForm 0 block ""))
let newBranch = block : branch
let contextBlock = Context f newBranch []
whenInstruction translationParam $
unless (Block.isTopLevel block) $
translateLog Message.WRITELN (Block.position block) $ Text.pack $ show f
fortifiedFormula <-
if Block.isTopLevel block
then return f
else
fillDef (Block.position block) contextBlock
let proofTask = generateProofTask kind (Block.declaredNames block) fortifiedFormula
let freshThesis = Context proofTask newBranch []
let toBeProved = Block.needsProof block && not (Block.isTopLevel block)
proofBody <- do
flat <- asks (getInstruction flatParam)
if flat
then return []
else return body
whenInstruction printthesisParam $ when (
toBeProved && notNull proofBody &&
not (hasDEC $ Context.formula freshThesis)) $
thesisLog Message.WRITELN (Block.position block) (length branch - 1) $
"thesis: " <> show (Context.formula freshThesis)
fortifiedProof <-
local (\st -> st {
thesisMotivated = toBeProved,
currentThesis = freshThesis,
currentBranch = newBranch }) $
verifyProof (if toBeProved then proofBody else body)
thesisSetting <- asks (getInstruction thesisParam)
let newBlock = block {
Block.formula = deleteInductionOrCase fortifiedFormula,
Block.body = fortifiedProof }
let formulaImage = Block.formulate newBlock
skolem <- asks skolemCounter
let (mesonRules, intermediateSkolem) = MESON.contras (deTag formulaImage) skolem
let (newDefinitions, newGuards) =
if kind == Definition || kind == Signature
then addDefinition (defs, grds) formulaImage
else (defs, grds)
let newContextBlock = Context formulaImage newBranch (uncurry (++) mesonRules)
let newContext = newContextBlock : context
let newRules =
if Block.isTopLevel block
then MESON.addRules mesonRules mRules
else mRules
let (newMotivation, hasChanged , newThesis) =
if thesisSetting
then inferNewThesis defs newContext thesis
else (Block.needsProof block, False, thesis)
whenInstruction printthesisParam $ when (
hasChanged && motivated && newMotivation &&
not (hasDEC $ Block.formula $ head branch) ) $
thesisLog Message.WRITELN (Block.position block) (length branch - 2) $
"new thesis: " <> show (Context.formula newThesis)
when (not newMotivation && motivated) $
thesisLog Message.WARNING (Block.position block) (length branch - 2) "unmotivated assumption"
let newRewriteRules = extractRewriteRule (head newContext) ++ rules
let newEvaluations =
if kind `elem` [LowDefinition, Definition]
then addEvaluation evaluations formulaImage
newBlocks <-
local (\st -> st {
thesisMotivated = motivated && newMotivation,
guards = newGuards,
rewriteRules = newRewriteRules,
evaluations = newEvaluations,
currentThesis = newThesis,
currentContext = newContext,
mesonRules = newRules,
definitions = newDefinitions,
skolemCounter = intermediateSkolem}) $ verifyProof rest
let finalThesis = Imp (Block.compose $ ProofTextBlock newBlock : newBlocks) (Context.formula thesis)
local (\st -> st {
thesisMotivated = motivated && not newMotivation,
currentThesis = Context.setFormula thesis finalThesis }) $ verifyProof []
return (ProofTextBlock newBlock : newBlocks)
verifyProof :: [ProofText] -> VerifyMonad [ProofText]
verifyProof restProofText = do
state <- ask
let VState {
rewriteRules = rules,
currentThesis = thesis,
currentContext = context,
currentBranch = branch} = state
let
process :: [Context] -> Formula -> VerifyMonad [ProofText]
process newContext f = do
let newRules = extractRewriteRule (head newContext) ++ rules
(_, _, newThesis) =
inferNewThesis (definitions state) newContext $ Context.setFormula thesis f
whenInstruction printthesisParam $ when (
noInductionOrCase (Context.formula newThesis) && not (null $ restProofText)) $
thesisLog Message.WRITELN
(Block.position $ head $ Context.branch $ head context) (length branch - 2) $
"new thesis " <> show (Context.formula newThesis)
local (\st -> st {
rewriteRules = newRules,
currentThesis = newThesis,
currentContext = newContext}) $ verifyProof restProofText
let
dive :: (Formula -> Formula) -> [Context] -> Formula -> VerifyMonad [ProofText]
dive construct context (Imp (Tag InductionHypothesis f) g)
| isClosed f = process (Context.setFormula thesis f : context) (construct g)
dive construct context (Imp (Tag Tag.CaseHypothesis f) g)
| isClosed f = process (thesis {Context.formula = f} : context) (construct g)
dive construct context (Imp f g) = dive (construct . Imp f) context g
dive construct context (All v f) = dive (construct . All v) context f
dive construct context (Tag tag f) = dive (construct . Tag tag) context f
dive _ _ _ = verify restProofText
dive id context $ Context.formula thesis
noInductionOrCase :: Formula -> Bool
noInductionOrCase (Tag InductionHypothesis _) = False
noInductionOrCase (Tag Tag.CaseHypothesis _) = False
noInductionOrCase f = allF noInductionOrCase f
deleteInductionOrCase :: Formula -> Formula
deleteInductionOrCase = dive id
where
dive :: (Formula -> a) -> Formula -> a
dive c (Imp (Tag InductionHypothesis _) f) = c f
dive c (Imp (Tag Tag.CaseHypothesis f) _) = c $ Not f
dive c (Imp f g) = dive (c . Imp f) g
dive c (All v f) = dive (c . All v) f
dive c f = c f
|
c4eaeedb8d6ecd014722ab01dfb50b3cbe71c02713d7a13bb702559a3ab30139 | lspitzner/brittany | Test490.hs | -- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
func = do
abc <- foo
abc
return ()
| null | https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test490.hs | haskell | brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft } | func = do
abc <- foo
abc
return ()
|
4272adae3220c03e4b4fa4d044875d100bf087348878056abddb59861db304d7 | clojupyter/clojupyter | log.clj | (ns clojupyter.log
(:require [clojupyter.kernel.config :as cfg]
[clojure.pprint :as pp]
[clojure.string :as str]
[io.simplect.compose :refer [def- c C p P]]
[taoensso.timbre :as timbre]))
(defmacro debug
[& args]
`(timbre/debug ~@args))
(defmacro info
[& args]
`(timbre/info ~@args))
(defmacro error
[& args]
`(timbre/error ~@args))
(defmacro with-level
[level & body]
`(timbre/with-level ~level ~@body))
(defn ppstr
[v]
(with-out-str
(println)
(println ">>>>>>>")
(pp/pprint v)
(println "<<<<<<<<")))
(defonce ^:private ORG-CONFIG timbre/*config*)
(def- fmt-level
(C name str/upper-case first))
(defn- fmt-origin
[?ns-str ?file]
(str/replace (or ?ns-str ?file "?") #"^clojupyter\." "c8r."))
(defn output-fn
([ data] (output-fn nil data))
([opts data]
(let [{:keys [no-stacktrace?]} opts
{:keys [level ?err msg_ ?ns-str ?file hostname_
timestamp_ ?line]} data]
(str "["
(fmt-level level) " "
(force timestamp_) " "
"Clojupyter" "] "
(str (fmt-origin ?ns-str ?file)
(when ?line (str ":" ?line))) " -- "
(force msg_)
(when-not no-stacktrace?
(when-let [err ?err]
(str "\n" (timbre/stacktrace err opts))))))))
(def CONFIG {:timestamp-opts {:pattern "HH:mm:ss.SSS", :locale :jvm-default, :timezone :utc}
:ns-blacklist ["io.pedestal.*"]
:output-fn output-fn})
(defn- set-clojupyter-config!
[]
(timbre/merge-config! CONFIG))
(defn- reset-config!
[]
(timbre/set-config! ORG-CONFIG))
(defn init!
[]
(set-clojupyter-config!)
(timbre/set-level! (cfg/log-level)))
avoid spurious debug messages from io.pedestal when loading with testing turned on
| null | https://raw.githubusercontent.com/clojupyter/clojupyter/742d64f26b60945075298a9f8d46e457f79266d7/src/clojupyter/log.clj | clojure | (ns clojupyter.log
(:require [clojupyter.kernel.config :as cfg]
[clojure.pprint :as pp]
[clojure.string :as str]
[io.simplect.compose :refer [def- c C p P]]
[taoensso.timbre :as timbre]))
(defmacro debug
[& args]
`(timbre/debug ~@args))
(defmacro info
[& args]
`(timbre/info ~@args))
(defmacro error
[& args]
`(timbre/error ~@args))
(defmacro with-level
[level & body]
`(timbre/with-level ~level ~@body))
(defn ppstr
[v]
(with-out-str
(println)
(println ">>>>>>>")
(pp/pprint v)
(println "<<<<<<<<")))
(defonce ^:private ORG-CONFIG timbre/*config*)
(def- fmt-level
(C name str/upper-case first))
(defn- fmt-origin
[?ns-str ?file]
(str/replace (or ?ns-str ?file "?") #"^clojupyter\." "c8r."))
(defn output-fn
([ data] (output-fn nil data))
([opts data]
(let [{:keys [no-stacktrace?]} opts
{:keys [level ?err msg_ ?ns-str ?file hostname_
timestamp_ ?line]} data]
(str "["
(fmt-level level) " "
(force timestamp_) " "
"Clojupyter" "] "
(str (fmt-origin ?ns-str ?file)
(when ?line (str ":" ?line))) " -- "
(force msg_)
(when-not no-stacktrace?
(when-let [err ?err]
(str "\n" (timbre/stacktrace err opts))))))))
(def CONFIG {:timestamp-opts {:pattern "HH:mm:ss.SSS", :locale :jvm-default, :timezone :utc}
:ns-blacklist ["io.pedestal.*"]
:output-fn output-fn})
(defn- set-clojupyter-config!
[]
(timbre/merge-config! CONFIG))
(defn- reset-config!
[]
(timbre/set-config! ORG-CONFIG))
(defn init!
[]
(set-clojupyter-config!)
(timbre/set-level! (cfg/log-level)))
avoid spurious debug messages from io.pedestal when loading with testing turned on
| |
33cc3fd4c79c0691fda34b5b7051da92e54b5a94d2f319cfa6a0f1c2899c4fcf | janestreet/krb | conn_type.mli | open! Core
* Levels of Kerberos protection on the connection , in order of increasing strength :
{ ul
[ Auth ] : The client is authenticated to the server , but all information is sent in
plaintext afterward }
{ li [ Safe ] : The client is authenticated . Afterward all information is sent in plaintext
but contains a checksum to check for integrity . }
{ li [ Priv ] : The client is authenticated , and all communication is encrypted . }
}
The client and server each communicate a set of levels they will accept and settle on
using the strongest one acceptable to both sides .
{ul
{li [Auth]: The client is authenticated to the server, but all information is sent in
plaintext afterward}
{li [Safe]: The client is authenticated. Afterward all information is sent in plaintext
but contains a checksum to check for integrity.}
{li [Priv]: The client is authenticated, and all communication is encrypted.}
}
The client and server each communicate a set of levels they will accept and settle on
using the strongest one acceptable to both sides.
*)
type t =
| Auth
| Safe
| Priv
[@@deriving compare, enumerate, hash, sexp_of]
include Comparable.S_plain with type t := t
include Stringable.S with type t := t
val strongest : Set.t -> t option
(** Find the strongest connection type supported by [us] and [peer], if any *)
val negotiate_strongest : us:Set.t -> peer:Set.t -> t Or_error.t
val is_as_strong : t -> as_:t -> bool
val flag : t list Command.Param.t
val optional_flag : t list option Command.Param.t
module Stable : sig
module V1 : sig
type nonrec t = t =
| Auth
| Safe
| Priv
[@@deriving bin_io, compare, sexp]
type nonrec comparator_witness = comparator_witness
include
Comparable.Stable.V1.S
with type comparable := t
with type comparator_witness := comparator_witness
end
end
| null | https://raw.githubusercontent.com/janestreet/krb/e3f1bfde3610a742e4f5421321e5bd27f6987fc5/src/conn_type.mli | ocaml | * Find the strongest connection type supported by [us] and [peer], if any | open! Core
* Levels of Kerberos protection on the connection , in order of increasing strength :
{ ul
[ Auth ] : The client is authenticated to the server , but all information is sent in
plaintext afterward }
{ li [ Safe ] : The client is authenticated . Afterward all information is sent in plaintext
but contains a checksum to check for integrity . }
{ li [ Priv ] : The client is authenticated , and all communication is encrypted . }
}
The client and server each communicate a set of levels they will accept and settle on
using the strongest one acceptable to both sides .
{ul
{li [Auth]: The client is authenticated to the server, but all information is sent in
plaintext afterward}
{li [Safe]: The client is authenticated. Afterward all information is sent in plaintext
but contains a checksum to check for integrity.}
{li [Priv]: The client is authenticated, and all communication is encrypted.}
}
The client and server each communicate a set of levels they will accept and settle on
using the strongest one acceptable to both sides.
*)
type t =
| Auth
| Safe
| Priv
[@@deriving compare, enumerate, hash, sexp_of]
include Comparable.S_plain with type t := t
include Stringable.S with type t := t
val strongest : Set.t -> t option
val negotiate_strongest : us:Set.t -> peer:Set.t -> t Or_error.t
val is_as_strong : t -> as_:t -> bool
val flag : t list Command.Param.t
val optional_flag : t list option Command.Param.t
module Stable : sig
module V1 : sig
type nonrec t = t =
| Auth
| Safe
| Priv
[@@deriving bin_io, compare, sexp]
type nonrec comparator_witness = comparator_witness
include
Comparable.Stable.V1.S
with type comparable := t
with type comparator_witness := comparator_witness
end
end
|
76c839e781ace61d8ebfdf56d089e285b13eb63ee9f2312499820a509a33b9ed | ptal/AbSolute | schedulable_abstract_domain.ml | Copyright 2019
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. *)
open Domains.Abstract_domain
module type Schedulable_abstract_domain =
sig
include Abstract_domain
(** [exec_task t task] executes the `task` inside the abstract domain `t`.
It maps to `true` if the task is entailed, `false` otherwise.
Precondition:
- The UID of the task corresponds to the one of the abstract element.
- The task ID was obtained through `drain_tasks`. *)
val exec_task: t -> task -> (t * bool)
(** [drain_tasks t] returns the list of tasks of `t` that need to be register in `Event_loop` for scheduling.
Each task is executed whenever one of the events in the list occurs. *)
val drain_tasks: t -> (t * (task * event list) list)
* [ remove t c ] discards a constraint ` c ` previously added through ` weak_incremental_closure ` .
Next time ` exec_task ` is called , the constraint will be considered entailed .
Rational : It is necessary to move a constraint from a domain to another such as in ` Delayed_product ` .
Next time `exec_task` is called, the constraint will be considered entailed.
Rational: It is necessary to move a constraint from a domain to another such as in `Delayed_product`. *)
val remove: t -> I.rconstraint -> t
end
| null | https://raw.githubusercontent.com/ptal/AbSolute/469159d87e3a717499573c1e187e5cfa1b569829/src/transformers/event_loop/schedulable_abstract_domain.ml | ocaml | * [exec_task t task] executes the `task` inside the abstract domain `t`.
It maps to `true` if the task is entailed, `false` otherwise.
Precondition:
- The UID of the task corresponds to the one of the abstract element.
- The task ID was obtained through `drain_tasks`.
* [drain_tasks t] returns the list of tasks of `t` that need to be register in `Event_loop` for scheduling.
Each task is executed whenever one of the events in the list occurs. | Copyright 2019
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. *)
open Domains.Abstract_domain
module type Schedulable_abstract_domain =
sig
include Abstract_domain
val exec_task: t -> task -> (t * bool)
val drain_tasks: t -> (t * (task * event list) list)
* [ remove t c ] discards a constraint ` c ` previously added through ` weak_incremental_closure ` .
Next time ` exec_task ` is called , the constraint will be considered entailed .
Rational : It is necessary to move a constraint from a domain to another such as in ` Delayed_product ` .
Next time `exec_task` is called, the constraint will be considered entailed.
Rational: It is necessary to move a constraint from a domain to another such as in `Delayed_product`. *)
val remove: t -> I.rconstraint -> t
end
|
797d80cab17a9c9a4c7373166a74f8dced054e426c1da93e9b729817682013e3 | mbenke/zpf2012 | App4g.hs | # LANGUAGE ExplicitForAll , RankNTypes #
{-# LANGUAGE GADTs #-} -- for syntax only
module App4g where
import Data.Char(isDigit,digitToInt)
import Applicative
import Monoid
data Steps a where
Step :: Steps a -> Steps a
Fail :: Steps a
Done :: a -> Steps a
deriving Show
noAlts :: Steps a
noAlts = Fail
best :: Steps a -> Steps a -> Steps a
best Fail r = r
best l Fail = l
OBS laziness !
-- best x@(Step _) (Done _) = x -- prefer longer parse
-- best (Done _) x@(Step _) = x
best _ _ = error "incorrect parser" -- ambiguity
bestg :: Steps a -> Steps a -> Steps a
bestg l r = best l r
(<<|>) :: Parser a -> Parser a -> Parser a
(Ph p) <<|> (Ph q) = Ph (\k s -> p k s `bestg` q k s)
instance Monoid (Steps a) where
mempty = noAlts
mappend = best
eval :: Steps a -> a
eval (Step l) = eval l
eval (Done v) = v
eval Fail = error "this should not happen: eval Fail"
newtype Ph a = Ph {unPh :: forall r.
(a -> String -> Steps r)
-> String -> Steps r}
type Parser a = Ph a
runParser :: Ph a -> String -> Steps a
runParser (Ph p) input = p (\a s -> checkEmpty a s) input where
checkEmpty a [] = Done a
checkEmpty a _ = Fail
-- parse :: Ph a -> String -> String -> Either () a
parse p name input = result (runParser p input) where
result (Done a) = Right a
result Fail = Left ()
result (Step x) = result x
satisfy :: (Char->Bool) -> Ph Char
satisfy p = Ph $ \k s -> case s of
(c:cs) | p c -> Step (k c cs)
_ -> Fail
eof :: Ph ()
eof = Ph $ \k s -> case s of
[] -> k () []
_ -> Fail
first :: (a->b) -> (a,c) -> (b,c)
first f (a,c) = (f a,c)
second :: (a->b) -> (d,a) -> (d,b)
second f (d,a) = (d,f a)
for = flip map
instance Functor Ph where
-- (a->b) -> (forall r. (a -> String -> Steps r)
-- -> String -> Steps r)
-- -> (forall r h. (b -> String -> Steps r)
-- -> String -> Steps r)
fmap f (Ph p) = Ph (\k -> p (k . f))
instance Applicative Ph where
pure a = Ph (\k -> k a)
(Ph p) <*> (Ph q) = Ph (\k -> p (\f -> q (k . f)))
instance Alternative Ph where
empty = Ph $ \k s -> mempty
(Ph p) <|> (Ph q) = Ph (p `mappend` q)
( \k s - > p k s ` mappend ` q k s )
opt :: Parser a -> a -> Parser a
p `opt` v = p <<|> pure v
many, many1 :: Parser a -> Parser [a]
NB greedy
many1 p = (:) <$> p <*> many p
digit :: Parser Char
digit = satisfy isDigit
char :: Char -> Parser Char
char c = satisfy (==c)
test1 = runParser digit "123"
test2 = runParser (many1 digit <* eof) "123"
-- S -> ( S ) S | epsilon
parens = (\_ s _ s2 -> max (1+s) s2) <$>
char '(' <*> parens <*> char ')' <*> parens
<|> pure 0
parens2 = (\s s2 -> max (1+s) s2) <$>
(char '(' *> parens) <* char ')' <*> parens
<|> pure 0
-- C1 -> T C
-- C -> op T C | empty
chainr1 :: Parser a -> Parser (a->a->a) -> Parser a
chainr1 x pop = x < * * > f where
chainr1 x pop = (flip ($)) <$> x <*> f where
f : : ( a - > a )
f = (flip <$> pop <*> chainr1 x pop) `opt` id
pop : : ( a->a->a )
flip pop : : ( a->a->a )
flip < $ > pop < * > chainr1 x pop : : ( a->a )
applyAll :: a -> [a->a] -> a
applyAll x [] = x
applyAll x (f:fs) = applyAll (f x) fs
-- applyAll x [f] = f x
chainl1 :: Parser a -> Parser (a->a->a) -> Parser a
chainl1 pt pop = applyAll <$> pt <*> many (flip <$> pop <*> pt)
| null | https://raw.githubusercontent.com/mbenke/zpf2012/faad6468f9400059de1c0735e12a84a2fdf24bb4/Code/Parse2/App4g.hs | haskell | # LANGUAGE GADTs #
for syntax only
best x@(Step _) (Done _) = x -- prefer longer parse
best (Done _) x@(Step _) = x
ambiguity
parse :: Ph a -> String -> String -> Either () a
(a->b) -> (forall r. (a -> String -> Steps r)
-> String -> Steps r)
-> (forall r h. (b -> String -> Steps r)
-> String -> Steps r)
S -> ( S ) S | epsilon
C1 -> T C
C -> op T C | empty
applyAll x [f] = f x | # LANGUAGE ExplicitForAll , RankNTypes #
module App4g where
import Data.Char(isDigit,digitToInt)
import Applicative
import Monoid
data Steps a where
Step :: Steps a -> Steps a
Fail :: Steps a
Done :: a -> Steps a
deriving Show
noAlts :: Steps a
noAlts = Fail
best :: Steps a -> Steps a -> Steps a
best Fail r = r
best l Fail = l
OBS laziness !
bestg :: Steps a -> Steps a -> Steps a
bestg l r = best l r
(<<|>) :: Parser a -> Parser a -> Parser a
(Ph p) <<|> (Ph q) = Ph (\k s -> p k s `bestg` q k s)
instance Monoid (Steps a) where
mempty = noAlts
mappend = best
eval :: Steps a -> a
eval (Step l) = eval l
eval (Done v) = v
eval Fail = error "this should not happen: eval Fail"
newtype Ph a = Ph {unPh :: forall r.
(a -> String -> Steps r)
-> String -> Steps r}
type Parser a = Ph a
runParser :: Ph a -> String -> Steps a
runParser (Ph p) input = p (\a s -> checkEmpty a s) input where
checkEmpty a [] = Done a
checkEmpty a _ = Fail
parse p name input = result (runParser p input) where
result (Done a) = Right a
result Fail = Left ()
result (Step x) = result x
satisfy :: (Char->Bool) -> Ph Char
satisfy p = Ph $ \k s -> case s of
(c:cs) | p c -> Step (k c cs)
_ -> Fail
eof :: Ph ()
eof = Ph $ \k s -> case s of
[] -> k () []
_ -> Fail
first :: (a->b) -> (a,c) -> (b,c)
first f (a,c) = (f a,c)
second :: (a->b) -> (d,a) -> (d,b)
second f (d,a) = (d,f a)
for = flip map
instance Functor Ph where
fmap f (Ph p) = Ph (\k -> p (k . f))
instance Applicative Ph where
pure a = Ph (\k -> k a)
(Ph p) <*> (Ph q) = Ph (\k -> p (\f -> q (k . f)))
instance Alternative Ph where
empty = Ph $ \k s -> mempty
(Ph p) <|> (Ph q) = Ph (p `mappend` q)
( \k s - > p k s ` mappend ` q k s )
opt :: Parser a -> a -> Parser a
p `opt` v = p <<|> pure v
many, many1 :: Parser a -> Parser [a]
NB greedy
many1 p = (:) <$> p <*> many p
digit :: Parser Char
digit = satisfy isDigit
char :: Char -> Parser Char
char c = satisfy (==c)
test1 = runParser digit "123"
test2 = runParser (many1 digit <* eof) "123"
parens = (\_ s _ s2 -> max (1+s) s2) <$>
char '(' <*> parens <*> char ')' <*> parens
<|> pure 0
parens2 = (\s s2 -> max (1+s) s2) <$>
(char '(' *> parens) <* char ')' <*> parens
<|> pure 0
chainr1 :: Parser a -> Parser (a->a->a) -> Parser a
chainr1 x pop = x < * * > f where
chainr1 x pop = (flip ($)) <$> x <*> f where
f : : ( a - > a )
f = (flip <$> pop <*> chainr1 x pop) `opt` id
pop : : ( a->a->a )
flip pop : : ( a->a->a )
flip < $ > pop < * > chainr1 x pop : : ( a->a )
applyAll :: a -> [a->a] -> a
applyAll x [] = x
applyAll x (f:fs) = applyAll (f x) fs
chainl1 :: Parser a -> Parser (a->a->a) -> Parser a
chainl1 pt pop = applyAll <$> pt <*> many (flip <$> pop <*> pt)
|
f2aca1decbf8190c81b1f749c8c3fad79b93c79d02985ca47809251a3b15c2b9 | thierry-martinez/stdcompat | stdLabels.mli | module Array :
sig
external length : 'a array -> int = "%array_length"
external get : 'a array -> int -> 'a = "%array_safe_get"
external set : 'a array -> int -> 'a -> unit = "%array_safe_set"
external make : int -> 'a -> 'a array = "caml_make_vect"
external create : int -> 'a -> 'a array = "caml_make_vect"
val init : int -> f:(int -> 'a) -> 'a array
val make_matrix : dimx:int -> dimy:int -> 'a -> 'a array array
val create_matrix : dimx:int -> dimy:int -> 'a -> 'a array array
val append : 'a array -> 'a array -> 'a array
val concat : 'a array list -> 'a array
val sub : 'a array -> pos:int -> len:int -> 'a array
val copy : 'a array -> 'a array
val fill : 'a array -> pos:int -> len:int -> 'a -> unit
val blit :
src:'a array ->
src_pos:int -> dst:'a array -> dst_pos:int -> len:int -> unit
val to_list : 'a array -> 'a list
val of_list : 'a list -> 'a array
val iter : f:('a -> unit) -> 'a array -> unit
val map : f:('a -> 'b) -> 'a array -> 'b array
val iteri : f:(int -> 'a -> unit) -> 'a array -> unit
val mapi : f:(int -> 'a -> 'b) -> 'a array -> 'b array
val fold_left : f:('a -> 'b -> 'a) -> init:'a -> 'b array -> 'a
val fold_right : f:('b -> 'a -> 'a) -> 'b array -> init:'a -> 'a
val exists : f:('a -> bool) -> 'a array -> bool
val for_all : f:('a -> bool) -> 'a array -> bool
val mem : 'a -> set:'a array -> bool
val memq : 'a -> set:'a array -> bool
external create_float : int -> float array = "caml_make_float_vect"
val make_float : int -> float array
val sort : cmp:('a -> 'a -> int) -> 'a array -> unit
val stable_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
val fast_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
external unsafe_get : 'a array -> int -> 'a = "%array_unsafe_get"
external unsafe_set : 'a array -> int -> 'a -> unit = "%array_unsafe_set"
end
module Bytes :
sig
external length : bytes -> int = "%string_length"
external get : bytes -> int -> char = "%string_safe_get"
external set : bytes -> int -> char -> unit = "%string_safe_set"
external create : int -> bytes = "caml_create_string"
val make : int -> char -> bytes
val init : int -> f:(int -> char) -> bytes
val empty : bytes
val copy : bytes -> bytes
val of_string : string -> bytes
val to_string : bytes -> string
val sub : bytes -> pos:int -> len:int -> bytes
val sub_string : bytes -> int -> int -> string
val fill : bytes -> pos:int -> len:int -> char -> unit
val blit :
src:bytes -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
val concat : sep:bytes -> bytes list -> bytes
val iter : f:(char -> unit) -> bytes -> unit
val iteri : f:(int -> char -> unit) -> bytes -> unit
val map : f:(char -> char) -> bytes -> bytes
val mapi : f:(int -> char -> char) -> bytes -> bytes
val trim : bytes -> bytes
val escaped : bytes -> bytes
val index : bytes -> char -> int
val rindex : bytes -> char -> int
val index_from : bytes -> int -> char -> int
val rindex_from : bytes -> int -> char -> int
val contains : bytes -> char -> bool
val contains_from : bytes -> int -> char -> bool
val rcontains_from : bytes -> int -> char -> bool
val uppercase : bytes -> bytes
val lowercase : bytes -> bytes
val capitalize : bytes -> bytes
val uncapitalize : bytes -> bytes
type t = bytes
val compare : t -> t -> int
external unsafe_get : bytes -> int -> char = "%string_unsafe_get"
external unsafe_set : bytes -> int -> char -> unit = "%string_unsafe_set"
external unsafe_blit :
src:bytes -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit =
"caml_blit_string"[@@noalloc ]
external unsafe_fill :
bytes -> pos:int -> len:int -> char -> unit = "caml_fill_string"[@@noalloc
]
val unsafe_to_string : bytes -> string
val unsafe_of_string : string -> bytes
end
module List :
sig
val length : 'a list -> int
val hd : 'a list -> 'a
val tl : 'a list -> 'a list
val nth : 'a list -> int -> 'a
val rev : 'a list -> 'a list
val append : 'a list -> 'a list -> 'a list
val rev_append : 'a list -> 'a list -> 'a list
val concat : 'a list list -> 'a list
val flatten : 'a list list -> 'a list
val iter : f:('a -> unit) -> 'a list -> unit
val iteri : f:(int -> 'a -> unit) -> 'a list -> unit
val map : f:('a -> 'b) -> 'a list -> 'b list
val mapi : f:(int -> 'a -> 'b) -> 'a list -> 'b list
val rev_map : f:('a -> 'b) -> 'a list -> 'b list
val fold_left : f:('a -> 'b -> 'a) -> init:'a -> 'b list -> 'a
val fold_right : f:('a -> 'b -> 'b) -> 'a list -> init:'b -> 'b
val iter2 : f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit
val map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
val rev_map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
val fold_left2 :
f:('a -> 'b -> 'c -> 'a) -> init:'a -> 'b list -> 'c list -> 'a
val fold_right2 :
f:('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> init:'c -> 'c
val for_all : f:('a -> bool) -> 'a list -> bool
val exists : f:('a -> bool) -> 'a list -> bool
val for_all2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool
val exists2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool
val mem : 'a -> set:'a list -> bool
val memq : 'a -> set:'a list -> bool
val find : f:('a -> bool) -> 'a list -> 'a
val filter : f:('a -> bool) -> 'a list -> 'a list
val find_all : f:('a -> bool) -> 'a list -> 'a list
val partition : f:('a -> bool) -> 'a list -> ('a list * 'a list)
val assoc : 'a -> ('a * 'b) list -> 'b
val assq : 'a -> ('a * 'b) list -> 'b
val mem_assoc : 'a -> map:('a * 'b) list -> bool
val mem_assq : 'a -> map:('a * 'b) list -> bool
val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list
val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list
val split : ('a * 'b) list -> ('a list * 'b list)
val combine : 'a list -> 'b list -> ('a * 'b) list
val sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
val stable_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
val fast_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
val sort_uniq : cmp:('a -> 'a -> int) -> 'a list -> 'a list
val merge : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> 'a list
end
module String :
sig
external length : string -> int = "%string_length"
external get : string -> int -> char = "%string_safe_get"
external set : bytes -> int -> char -> unit = "%string_safe_set"
external create : int -> bytes = "caml_create_string"
val make : int -> char -> string
val init : int -> f:(int -> char) -> string
val copy : string -> string
val sub : string -> pos:int -> len:int -> string
val fill : bytes -> pos:int -> len:int -> char -> unit
val blit :
src:string -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
val concat : sep:string -> string list -> string
val iter : f:(char -> unit) -> string -> unit
val iteri : f:(int -> char -> unit) -> string -> unit
val map : f:(char -> char) -> string -> string
val mapi : f:(int -> char -> char) -> string -> string
val trim : string -> string
val escaped : string -> string
val index : string -> char -> int
val rindex : string -> char -> int
val index_from : string -> int -> char -> int
val rindex_from : string -> int -> char -> int
val contains : string -> char -> bool
val contains_from : string -> int -> char -> bool
val rcontains_from : string -> int -> char -> bool
val uppercase : string -> string
val lowercase : string -> string
val capitalize : string -> string
val uncapitalize : string -> string
type t = string
val compare : t -> t -> int
external unsafe_get : string -> int -> char = "%string_unsafe_get"
external unsafe_set : bytes -> int -> char -> unit = "%string_unsafe_set"
external unsafe_blit :
src:string -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
= "caml_blit_string"[@@noalloc ]
external unsafe_fill :
bytes -> pos:int -> len:int -> char -> unit = "caml_fill_string"[@@noalloc
]
end
| null | https://raw.githubusercontent.com/thierry-martinez/stdcompat/83d786cdb17fae0caadf5c342e283c3dcfee2279/interfaces/4.03/stdLabels.mli | ocaml | module Array :
sig
external length : 'a array -> int = "%array_length"
external get : 'a array -> int -> 'a = "%array_safe_get"
external set : 'a array -> int -> 'a -> unit = "%array_safe_set"
external make : int -> 'a -> 'a array = "caml_make_vect"
external create : int -> 'a -> 'a array = "caml_make_vect"
val init : int -> f:(int -> 'a) -> 'a array
val make_matrix : dimx:int -> dimy:int -> 'a -> 'a array array
val create_matrix : dimx:int -> dimy:int -> 'a -> 'a array array
val append : 'a array -> 'a array -> 'a array
val concat : 'a array list -> 'a array
val sub : 'a array -> pos:int -> len:int -> 'a array
val copy : 'a array -> 'a array
val fill : 'a array -> pos:int -> len:int -> 'a -> unit
val blit :
src:'a array ->
src_pos:int -> dst:'a array -> dst_pos:int -> len:int -> unit
val to_list : 'a array -> 'a list
val of_list : 'a list -> 'a array
val iter : f:('a -> unit) -> 'a array -> unit
val map : f:('a -> 'b) -> 'a array -> 'b array
val iteri : f:(int -> 'a -> unit) -> 'a array -> unit
val mapi : f:(int -> 'a -> 'b) -> 'a array -> 'b array
val fold_left : f:('a -> 'b -> 'a) -> init:'a -> 'b array -> 'a
val fold_right : f:('b -> 'a -> 'a) -> 'b array -> init:'a -> 'a
val exists : f:('a -> bool) -> 'a array -> bool
val for_all : f:('a -> bool) -> 'a array -> bool
val mem : 'a -> set:'a array -> bool
val memq : 'a -> set:'a array -> bool
external create_float : int -> float array = "caml_make_float_vect"
val make_float : int -> float array
val sort : cmp:('a -> 'a -> int) -> 'a array -> unit
val stable_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
val fast_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
external unsafe_get : 'a array -> int -> 'a = "%array_unsafe_get"
external unsafe_set : 'a array -> int -> 'a -> unit = "%array_unsafe_set"
end
module Bytes :
sig
external length : bytes -> int = "%string_length"
external get : bytes -> int -> char = "%string_safe_get"
external set : bytes -> int -> char -> unit = "%string_safe_set"
external create : int -> bytes = "caml_create_string"
val make : int -> char -> bytes
val init : int -> f:(int -> char) -> bytes
val empty : bytes
val copy : bytes -> bytes
val of_string : string -> bytes
val to_string : bytes -> string
val sub : bytes -> pos:int -> len:int -> bytes
val sub_string : bytes -> int -> int -> string
val fill : bytes -> pos:int -> len:int -> char -> unit
val blit :
src:bytes -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
val concat : sep:bytes -> bytes list -> bytes
val iter : f:(char -> unit) -> bytes -> unit
val iteri : f:(int -> char -> unit) -> bytes -> unit
val map : f:(char -> char) -> bytes -> bytes
val mapi : f:(int -> char -> char) -> bytes -> bytes
val trim : bytes -> bytes
val escaped : bytes -> bytes
val index : bytes -> char -> int
val rindex : bytes -> char -> int
val index_from : bytes -> int -> char -> int
val rindex_from : bytes -> int -> char -> int
val contains : bytes -> char -> bool
val contains_from : bytes -> int -> char -> bool
val rcontains_from : bytes -> int -> char -> bool
val uppercase : bytes -> bytes
val lowercase : bytes -> bytes
val capitalize : bytes -> bytes
val uncapitalize : bytes -> bytes
type t = bytes
val compare : t -> t -> int
external unsafe_get : bytes -> int -> char = "%string_unsafe_get"
external unsafe_set : bytes -> int -> char -> unit = "%string_unsafe_set"
external unsafe_blit :
src:bytes -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit =
"caml_blit_string"[@@noalloc ]
external unsafe_fill :
bytes -> pos:int -> len:int -> char -> unit = "caml_fill_string"[@@noalloc
]
val unsafe_to_string : bytes -> string
val unsafe_of_string : string -> bytes
end
module List :
sig
val length : 'a list -> int
val hd : 'a list -> 'a
val tl : 'a list -> 'a list
val nth : 'a list -> int -> 'a
val rev : 'a list -> 'a list
val append : 'a list -> 'a list -> 'a list
val rev_append : 'a list -> 'a list -> 'a list
val concat : 'a list list -> 'a list
val flatten : 'a list list -> 'a list
val iter : f:('a -> unit) -> 'a list -> unit
val iteri : f:(int -> 'a -> unit) -> 'a list -> unit
val map : f:('a -> 'b) -> 'a list -> 'b list
val mapi : f:(int -> 'a -> 'b) -> 'a list -> 'b list
val rev_map : f:('a -> 'b) -> 'a list -> 'b list
val fold_left : f:('a -> 'b -> 'a) -> init:'a -> 'b list -> 'a
val fold_right : f:('a -> 'b -> 'b) -> 'a list -> init:'b -> 'b
val iter2 : f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit
val map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
val rev_map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
val fold_left2 :
f:('a -> 'b -> 'c -> 'a) -> init:'a -> 'b list -> 'c list -> 'a
val fold_right2 :
f:('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> init:'c -> 'c
val for_all : f:('a -> bool) -> 'a list -> bool
val exists : f:('a -> bool) -> 'a list -> bool
val for_all2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool
val exists2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool
val mem : 'a -> set:'a list -> bool
val memq : 'a -> set:'a list -> bool
val find : f:('a -> bool) -> 'a list -> 'a
val filter : f:('a -> bool) -> 'a list -> 'a list
val find_all : f:('a -> bool) -> 'a list -> 'a list
val partition : f:('a -> bool) -> 'a list -> ('a list * 'a list)
val assoc : 'a -> ('a * 'b) list -> 'b
val assq : 'a -> ('a * 'b) list -> 'b
val mem_assoc : 'a -> map:('a * 'b) list -> bool
val mem_assq : 'a -> map:('a * 'b) list -> bool
val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list
val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list
val split : ('a * 'b) list -> ('a list * 'b list)
val combine : 'a list -> 'b list -> ('a * 'b) list
val sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
val stable_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
val fast_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
val sort_uniq : cmp:('a -> 'a -> int) -> 'a list -> 'a list
val merge : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> 'a list
end
module String :
sig
external length : string -> int = "%string_length"
external get : string -> int -> char = "%string_safe_get"
external set : bytes -> int -> char -> unit = "%string_safe_set"
external create : int -> bytes = "caml_create_string"
val make : int -> char -> string
val init : int -> f:(int -> char) -> string
val copy : string -> string
val sub : string -> pos:int -> len:int -> string
val fill : bytes -> pos:int -> len:int -> char -> unit
val blit :
src:string -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
val concat : sep:string -> string list -> string
val iter : f:(char -> unit) -> string -> unit
val iteri : f:(int -> char -> unit) -> string -> unit
val map : f:(char -> char) -> string -> string
val mapi : f:(int -> char -> char) -> string -> string
val trim : string -> string
val escaped : string -> string
val index : string -> char -> int
val rindex : string -> char -> int
val index_from : string -> int -> char -> int
val rindex_from : string -> int -> char -> int
val contains : string -> char -> bool
val contains_from : string -> int -> char -> bool
val rcontains_from : string -> int -> char -> bool
val uppercase : string -> string
val lowercase : string -> string
val capitalize : string -> string
val uncapitalize : string -> string
type t = string
val compare : t -> t -> int
external unsafe_get : string -> int -> char = "%string_unsafe_get"
external unsafe_set : bytes -> int -> char -> unit = "%string_unsafe_set"
external unsafe_blit :
src:string -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit
= "caml_blit_string"[@@noalloc ]
external unsafe_fill :
bytes -> pos:int -> len:int -> char -> unit = "caml_fill_string"[@@noalloc
]
end
| |
3848a9b7e2fcb4193a0a84ce8dd037c85509573a1c7c9237430e8956eb5e5a37 | fccm/glMLite | morph3d.ml | $ I d : morph3d.ml , v 1.2 2005/10/17 11:27:04 garrigue Exp $
open LablGL
open StdLabels
open Printf
-
* morph3d.c - Shows 3D morphing objects ( TK Version )
*
* This program was inspired on a WindowsNT(R ) 's screen saver . It was written
* from scratch and it was not based on any other source code .
*
* Porting it to xlock ( the final objective of this code since the moment I
* decided to create it ) was possible by comparing the original Mesa 's gear
* demo with it 's ported version , so thanks for for his indirect
* help ( look at gear.c in xlock source tree ) . NOTE : At the moment this code
* was sent to for package inclusion , the XLock Version was not
* available . In fact , I 'll wait it to appear on the next Mesa release ( If you
* are reading this , it means THIS release ) to send it for xlock package
* inclusion ) . It will probably there be a GLUT version too .
*
* Thanks goes also to for making it possible and inexpensive
* to use OpenGL at home .
*
* Since I 'm not a native english speaker , my apologies for any gramatical
* mistake .
*
* My e - mail addresses are
*
*
* and
*
*
* ( Feb-13 - 1997 )
* morph3d.c - Shows 3D morphing objects (TK Version)
*
* This program was inspired on a WindowsNT(R)'s screen saver. It was written
* from scratch and it was not based on any other source code.
*
* Porting it to xlock (the final objective of this code since the moment I
* decided to create it) was possible by comparing the original Mesa's gear
* demo with it's ported version, so thanks for Danny Sung for his indirect
* help (look at gear.c in xlock source tree). NOTE: At the moment this code
* was sent to Brian Paul for package inclusion, the XLock Version was not
* available. In fact, I'll wait it to appear on the next Mesa release (If you
* are reading this, it means THIS release) to send it for xlock package
* inclusion). It will probably there be a GLUT version too.
*
* Thanks goes also to Brian Paul for making it possible and inexpensive
* to use OpenGL at home.
*
* Since I'm not a native english speaker, my apologies for any gramatical
* mistake.
*
* My e-mail addresses are
*
*
* and
*
*
* Marcelo F. Vianna (Feb-13-1997)
*)
This document is VERY incomplete , but tries to describe the mathematics used
in the program . At this moment it just describes how the polyhedra are
generated . On futhurer versions , this document will be probabbly improved .
Since I 'm not a native english speaker , my apologies for any gramatical
mistake .
at Catholic Pontifical University
- of Rio de Janeiro ( PUC - Rio ) Brasil .
- e - mail : or
- Feb-13 - 1997
POLYHEDRA GENERATION
For the purpose of this program it 's not sufficient to know the polyhedra
vertexes coordinates . Since the morphing algorithm applies a nonlinear
transformation over the surfaces ( faces ) of the polyhedron , each face has
to be divided into smaller ones . The morphing algorithm needs to transform
each vertex of these smaller faces individually . It 's a very time consoming
task .
In order to reduce calculation overload , and since all the macro faces of
the polyhedron are transformed by the same way , the generation is made by
creating only one face of the polyhedron , morphing it and then rotating it
around the polyhedron center .
What we need to know is the face radius of the polyhedron ( the radius of
the inscribed sphere ) and the angle between the center of two adjacent
faces using the center of the sphere as the angle 's vertex .
The face radius of the regular polyhedra are known values which I decided
to not waste my time calculating . Following is a table of face radius for
the regular polyhedra with edge length = 1 :
TETRAHEDRON : 1/(2*sqrt(2))/sqrt(3 )
CUBE : 1/2
OCTAHEDRON : 1 / sqrt(6 )
DODECAHEDRON : T^2 * sqrt((T+2)/5 ) / 2 - > where
ICOSAHEDRON : ( 3*sqrt(3)+sqrt(15))/12
I 've not found any reference about the mentioned angles , so I needed to
calculate them , not a trivial task until I figured out how :)
Curiously these angles are the same for the tetrahedron and octahedron .
A way to obtain this value is inscribing the tetrahedron inside the cube
by matching their vertexes . So you 'll notice that the remaining unmatched
vertexes are in the same straight line starting in the cube / tetrahedron
center and crossing the center of each tetrahedron 's face . At this point
it 's easy to obtain the bigger angle of the isosceles triangle formed by
the center of the cube and two opposite vertexes on the same cube face .
The edges of this triangle have the following lenghts : sqrt(2 ) for the base
and sqrt(3)/2 for the other two other edges . So the angle we want is :
+ -----------------------------------------------------------+
| 2*ARCSIN(sqrt(2)/sqrt(3 ) ) = 109.47122063449069174 degrees |
+ -----------------------------------------------------------+
For the cube this angle is obvious , but just for formality it can be
easily obtained because we also know it 's isosceles edge lenghts :
sqrt(2)/2 for the base and 1/2 for the other two edges . So the angle we
want is :
+ -----------------------------------------------------------+
| 2*ARCSIN((sqrt(2)/2)/1 ) = 90.000000000000000000 degrees |
+ -----------------------------------------------------------+
For the octahedron we use the same idea used for the tetrahedron , but now
we inscribe the cube inside the octahedron so that all cubes 's vertexes
matches excatly the center of each octahedron 's face . It 's now clear that
this angle is the same of the thetrahedron one :
+ -----------------------------------------------------------+
| 2*ARCSIN(sqrt(2)/sqrt(3 ) ) = 109.47122063449069174 degrees |
+ -----------------------------------------------------------+
For the dodecahedron it 's a little bit harder because it 's only relationship
with the cube is useless to us . So we need to solve the problem by another
way . The concept of Face radius also exists on 2D polygons with the name
Edge radius :
Edge Radius For Pentagon ( ERp )
ERp = ( 1/2)/TAN(36 degrees ) * VRp = 0.6881909602355867905
( VRp is the pentagon 's vertex radio ) .
Face Radius For Dodecahedron
FRd = T^2 * sqrt((T+2)/5 ) / 2 = 1.1135163644116068404
Why we need ERp ? Well , ERp and FRd segments forms a 90 degrees angle ,
completing this triangle , the lesser angle is a half of the angle we are
looking for , so this angle is :
+ -----------------------------------------------------------+
| 2*ARCTAN(ERp / FRd ) = 63.434948822922009981 degrees |
+ -----------------------------------------------------------+
For the icosahedron we can use the same method used for dodecahedron ( well
the method used for dodecahedron may be used for all regular polyhedra )
Edge Radius For Triangle ( this one is well known : 1/3 of the triangle height )
ERt = sin(60)/3 = sqrt(3)/6 = 0.2886751345948128655
Face Radius For Icosahedron
FRi= ( 3*sqrt(3)+sqrt(15))/12 = 0.7557613140761707538
So the angle is :
+ -----------------------------------------------------------+
| 2*ARCTAN(ERt / FRi ) = 41.810314895778596167 degrees |
+ -----------------------------------------------------------+
This document is VERY incomplete, but tries to describe the mathematics used
in the program. At this moment it just describes how the polyhedra are
generated. On futhurer versions, this document will be probabbly improved.
Since I'm not a native english speaker, my apologies for any gramatical
mistake.
Marcelo Fernandes Vianna
- Undergraduate in Computer Engeneering at Catholic Pontifical University
- of Rio de Janeiro (PUC-Rio) Brasil.
- e-mail: or
- Feb-13-1997
POLYHEDRA GENERATION
For the purpose of this program it's not sufficient to know the polyhedra
vertexes coordinates. Since the morphing algorithm applies a nonlinear
transformation over the surfaces (faces) of the polyhedron, each face has
to be divided into smaller ones. The morphing algorithm needs to transform
each vertex of these smaller faces individually. It's a very time consoming
task.
In order to reduce calculation overload, and since all the macro faces of
the polyhedron are transformed by the same way, the generation is made by
creating only one face of the polyhedron, morphing it and then rotating it
around the polyhedron center.
What we need to know is the face radius of the polyhedron (the radius of
the inscribed sphere) and the angle between the center of two adjacent
faces using the center of the sphere as the angle's vertex.
The face radius of the regular polyhedra are known values which I decided
to not waste my time calculating. Following is a table of face radius for
the regular polyhedra with edge length = 1:
TETRAHEDRON : 1/(2*sqrt(2))/sqrt(3)
CUBE : 1/2
OCTAHEDRON : 1/sqrt(6)
DODECAHEDRON : T^2 * sqrt((T+2)/5) / 2 -> where T=(sqrt(5)+1)/2
ICOSAHEDRON : (3*sqrt(3)+sqrt(15))/12
I've not found any reference about the mentioned angles, so I needed to
calculate them, not a trivial task until I figured out how :)
Curiously these angles are the same for the tetrahedron and octahedron.
A way to obtain this value is inscribing the tetrahedron inside the cube
by matching their vertexes. So you'll notice that the remaining unmatched
vertexes are in the same straight line starting in the cube/tetrahedron
center and crossing the center of each tetrahedron's face. At this point
it's easy to obtain the bigger angle of the isosceles triangle formed by
the center of the cube and two opposite vertexes on the same cube face.
The edges of this triangle have the following lenghts: sqrt(2) for the base
and sqrt(3)/2 for the other two other edges. So the angle we want is:
+-----------------------------------------------------------+
| 2*ARCSIN(sqrt(2)/sqrt(3)) = 109.47122063449069174 degrees |
+-----------------------------------------------------------+
For the cube this angle is obvious, but just for formality it can be
easily obtained because we also know it's isosceles edge lenghts:
sqrt(2)/2 for the base and 1/2 for the other two edges. So the angle we
want is:
+-----------------------------------------------------------+
| 2*ARCSIN((sqrt(2)/2)/1) = 90.000000000000000000 degrees |
+-----------------------------------------------------------+
For the octahedron we use the same idea used for the tetrahedron, but now
we inscribe the cube inside the octahedron so that all cubes's vertexes
matches excatly the center of each octahedron's face. It's now clear that
this angle is the same of the thetrahedron one:
+-----------------------------------------------------------+
| 2*ARCSIN(sqrt(2)/sqrt(3)) = 109.47122063449069174 degrees |
+-----------------------------------------------------------+
For the dodecahedron it's a little bit harder because it's only relationship
with the cube is useless to us. So we need to solve the problem by another
way. The concept of Face radius also exists on 2D polygons with the name
Edge radius:
Edge Radius For Pentagon (ERp)
ERp = (1/2)/TAN(36 degrees) * VRp = 0.6881909602355867905
(VRp is the pentagon's vertex radio).
Face Radius For Dodecahedron
FRd = T^2 * sqrt((T+2)/5) / 2 = 1.1135163644116068404
Why we need ERp? Well, ERp and FRd segments forms a 90 degrees angle,
completing this triangle, the lesser angle is a half of the angle we are
looking for, so this angle is:
+-----------------------------------------------------------+
| 2*ARCTAN(ERp/FRd) = 63.434948822922009981 degrees |
+-----------------------------------------------------------+
For the icosahedron we can use the same method used for dodecahedron (well
the method used for dodecahedron may be used for all regular polyhedra)
Edge Radius For Triangle (this one is well known: 1/3 of the triangle height)
ERt = sin(60)/3 = sqrt(3)/6 = 0.2886751345948128655
Face Radius For Icosahedron
FRi= (3*sqrt(3)+sqrt(15))/12 = 0.7557613140761707538
So the angle is:
+-----------------------------------------------------------+
| 2*ARCTAN(ERt/FRi) = 41.810314895778596167 degrees |
+-----------------------------------------------------------+
*)
let scale = 0.3
let vect_mul (x1,y1,z1) (x2,y2,z2) =
(y1 *. z2 -. z1 *. y2, z1 *. x2 -. x1 *. z2, x1 *. y2 -. y1 *. x2)
let sqr a = a *. a
(* Increasing this values produces better image quality, the price is speed. *)
(* Very low values produces erroneous/incorrect plotting *)
let tetradivisions = 23
let cubedivisions = 20
let octadivisions = 21
let dodecadivisions = 10
let icodivisions = 15
let tetraangle = 109.47122063449069174
let cubeangle = 90.000000000000000000
let octaangle = 109.47122063449069174
let dodecaangle = 63.434948822922009981
let icoangle = 41.810314895778596167
let pi = acos (-1.)
let sqrt2 = sqrt 2.
let sqrt3 = sqrt 3.
let sqrt5 = sqrt 5.
let sqrt6 = sqrt 6.
let sqrt15 = sqrt 15.
let cossec36_2 = 0.8506508083520399322
let cosd x = cos (float x /. 180. *. pi)
let sind x = sin (float x /. 180. *. pi)
let cos72 = cosd 72
let sin72 = sind 72
let cos36 = cosd 36
let sin36 = sind 36
(*************************************************************************)
let front_shininess = 60.0
let front_specular = 0.7, 0.7, 0.7, 1.0
let ambient = 0.0, 0.0, 0.0, 1.0
let diffuse = 1.0, 1.0, 1.0, 1.0
let position0 = 1.0, 1.0, 1.0, 0.0
let position1 = -1.0,-1.0, 1.0, 0.0
let lmodel_ambient = 0.5, 0.5, 0.5, 1.0
let lmodel_twoside = true
let materialRed = 0.7, 0.0, 0.0, 1.0
let materialGreen = 0.1, 0.5, 0.2, 1.0
let materialBlue = 0.0, 0.0, 0.7, 1.0
let materialCyan = 0.2, 0.5, 0.7, 1.0
let materialYellow = 0.7, 0.7, 0.0, 1.0
let materialMagenta = 0.6, 0.2, 0.5, 1.0
let materialWhite = 0.7, 0.7, 0.7, 1.0
let materialGray = 0.2, 0.2, 0.2, 1.0
let all_gray = Array.create 20 materialGray
let vertex ~xf ~yf ~zf ~ampvr2 =
let xa = xf +. 0.01 and yb = yf +. 0.01 in
let xf2 = sqr xf and yf2 = sqr yf in
let factor = 1. -. (xf2 +. yf2) *. ampvr2
and factor1 = 1. -. (sqr xa +. yf2) *. ampvr2
and factor2 = 1. -. (xf2 +. sqr yb) *. ampvr2 in
let vertx = factor *. xf and verty = factor *. yf
and vertz = factor *. zf in
let neiax = factor1 *. xa -. vertx and neiay = factor1 *. yf -. verty
and neiaz = factor1 *. zf -. vertz and neibx = factor2 *. xf -. vertx
and neiby = factor2 *. yb -. verty and neibz = factor2 *. zf -. vertz in
GlDraw.normal3 (vect_mul (neiax, neiay, neiaz) (neibx, neiby, neibz));
GlDraw.vertex3 (vertx, verty, vertz)
let triangle ~edge ~amp ~divisions ~z =
let divi = float divisions in
let vr = edge *. sqrt3 /. 3. in
let ampvr2 = amp /. sqr vr
and zf = edge *. z in
let ax = edge *. (0.5 /. divi)
and ay = edge *. (-0.5 *. sqrt3 /. divi)
and bx = edge *. (-0.5 /. divi) in
for ri = 1 to divisions do
GlDraw.begins `triangle_strip;
for ti = 0 to ri - 1 do
vertex ~zf ~ampvr2
~xf:(float (ri-ti) *. ax +. float ti *. bx)
~yf:(vr +. float (ri-ti) *. ay +. float ti *. ay);
vertex ~zf ~ampvr2
~xf:(float (ri-ti-1) *. ax +. float ti *. bx)
~yf:(vr +. float (ri-ti-1) *. ay +. float ti *. ay)
done;
vertex ~xf:(float ri *. bx) ~yf:(vr +. float ri *. ay) ~zf ~ampvr2;
GlDraw.ends ()
done
let square ~edge ~amp ~divisions ~z =
let divi = float divisions in
let zf = edge *. z
and ampvr2 = amp /. sqr (edge *. sqrt2 /. 2.) in
for yi = 0 to divisions - 1 do
let yf = edge *. (-0.5 +. float yi /. divi) in
let y = yf +. 1.0 /. divi *. edge in
GlDraw.begins `quad_strip;
for xi = 0 to divisions do
let xf = edge *. (-0.5 +. float xi /. divi) in
vertex ~xf ~yf:y ~zf ~ampvr2;
vertex ~xf ~yf ~zf ~ampvr2
done;
GlDraw.ends ()
done
let pentagon ~edge ~amp ~divisions ~z =
let divi = float divisions in
let zf = edge *. z
and ampvr2 = amp /. sqr(edge *. cossec36_2) in
let x =
Array.init 6
~f:(fun fi -> -. cos (float fi *. 2. *. pi /. 5. +. pi /. 10.)
/. divi *. cossec36_2 *. edge)
and y =
Array.init 6
~f:(fun fi -> sin (float fi *. 2. *. pi /. 5. +. pi /. 10.)
/. divi *. cossec36_2 *. edge)
in
for ri = 1 to divisions do
for fi = 0 to 4 do
GlDraw.begins `triangle_strip;
for ti = 0 to ri-1 do
vertex ~zf ~ampvr2
~xf:(float(ri-ti) *. x.(fi) +. float ti *. x.(fi+1))
~yf:(float(ri-ti) *. y.(fi) +. float ti *. y.(fi+1));
vertex ~zf ~ampvr2
~xf:(float(ri-ti-1) *. x.(fi) +. float ti *. x.(fi+1))
~yf:(float(ri-ti-1) *. y.(fi) +. float ti *. y.(fi+1))
done;
vertex ~xf:(float ri *. x.(fi+1)) ~yf:(float ri *. y.(fi+1)) ~zf ~ampvr2;
GlDraw.ends ()
done
done
let call_list list color =
GlLight.material ~face:`both (`diffuse color);
GlList.call list
let draw_tetra ~amp ~divisions ~color =
let list = GlList.create `compile in
triangle ~edge:2.0 ~amp ~divisions ~z:(0.5 /. sqrt6);
GlList.ends();
call_list list color.(0);
GlMat.push();
GlMat.rotate ~angle:180.0 ~z:1.0 ();
GlMat.rotate ~angle:(-.tetraangle) ~x:1.0 ();
call_list list color.(1);
GlMat.pop();
GlMat.push();
GlMat.rotate ~angle:180.0 ~y:1.0 ();
GlMat.rotate ~angle:(-180.0 +. tetraangle) ~x:0.5 ~y:(sqrt3 /. 2.) ();
call_list list color.(2);
GlMat.pop();
GlMat.rotate ~angle:180.0 ~y:1.0 ();
GlMat.rotate ~angle:(-180.0 +. tetraangle) ~x:0.5 ~y:(-.sqrt3 /. 2.) ();
call_list list color.(3);
GlList.delete list
let draw_cube ~amp ~divisions ~color =
let list = GlList.create `compile in
square ~edge:2.0 ~amp ~divisions ~z:0.5;
GlList.ends ();
call_list list color.(0);
for i = 1 to 3 do
GlMat.rotate ~angle:cubeangle ~x:1.0 ();
call_list list color.(i)
done;
GlMat.rotate ~angle:cubeangle ~y:1.0 ();
call_list list color.(4);
GlMat.rotate ~angle:(2.0 *. cubeangle) ~y:1.0 ();
call_list list color.(5);
GlList.delete list
let draw_octa ~amp ~divisions ~color =
let list = GlList.create `compile in
triangle ~edge:2.0 ~amp ~divisions ~z:(1.0 /. sqrt6);
GlList.ends ();
let do_list (i,y) =
GlMat.push();
GlMat.rotate ~angle:180.0 ~y:1.0 ();
GlMat.rotate ~angle:(-.octaangle) ~x:0.5 ~y ();
call_list list color.(i);
GlMat.pop()
in
call_list list color.(0);
GlMat.push();
GlMat.rotate ~angle:180.0 ~z:1.0 ();
GlMat.rotate ~angle:(-180.0 +. octaangle) ~x:1.0 ();
call_list list color.(1);
GlMat.pop();
List.iter [2, sqrt3 /. 2.0; 3, -.sqrt3 /. 2.0] ~f:do_list;
GlMat.rotate ~angle:180.0 ~x:1.0 ();
GlLight.material ~face:`both (`diffuse color.(4));
GlList.call list;
GlMat.push();
GlMat.rotate ~angle:180.0 ~z:1.0 ();
GlMat.rotate ~angle:(-180.0 +. octaangle) ~x:1.0 ();
GlLight.material ~face:`both (`diffuse color.(5));
GlList.call list;
GlMat.pop();
List.iter [6, sqrt3 /. 2.0; 7, -.sqrt3 /. 2.0] ~f:do_list;
GlList.delete list
let draw_dodeca ~amp ~divisions ~color =
let tau = (sqrt5 +. 1.0) /. 2.0 in
let list = GlList.create `compile in
pentagon ~edge:2.0 ~amp ~divisions
~z:(sqr(tau) *. sqrt ((tau+.2.0)/.5.0) /. 2.0);
GlList.ends ();
let do_list (i,angle,x,y) =
GlMat.push();
GlMat.rotate ~angle:angle ~x ~y ();
call_list list color.(i);
GlMat.pop();
in
GlMat.push ();
call_list list color.(0);
GlMat.rotate ~angle:180.0 ~z:1.0 ();
List.iter ~f:do_list
[ 1, -.dodecaangle, 1.0, 0.0;
2, -.dodecaangle, cos72, sin72;
3, -.dodecaangle, cos72, -.sin72;
4, dodecaangle, cos36, -.sin36;
5, dodecaangle, cos36, sin36 ];
GlMat.pop ();
GlMat.rotate ~angle:180.0 ~x:1.0 ();
call_list list color.(6);
GlMat.rotate ~angle:180.0 ~z:1.0 ();
List.iter ~f:do_list
[ 7, -.dodecaangle, 1.0, 0.0;
8, -.dodecaangle, cos72, sin72;
9, -.dodecaangle, cos72, -.sin72;
10, dodecaangle, cos36, -.sin36 ];
GlMat.rotate ~angle:dodecaangle ~x:cos36 ~y:sin36 ();
call_list list color.(11);
GlList.delete list
let draw_ico ~amp ~divisions ~color =
let list = GlList.create `compile in
triangle ~edge:1.5 ~amp ~divisions
~z:((3.0 *. sqrt3 +. sqrt15) /. 12.0);
GlList.ends ();
let do_list1 i =
GlMat.rotate ~angle:180.0 ~y:1.0 ();
GlMat.rotate ~angle:(-180.0 +. icoangle) ~x:0.5 ~y:(sqrt3/.2.0) ();
call_list list color.(i)
and do_list2 i =
GlMat.rotate ~angle:180.0 ~y:1.0 ();
GlMat.rotate ~angle:(-180.0 +. icoangle) ~x:0.5 ~y:(-.sqrt3/.2.0) ();
call_list list color.(i)
and do_list3 i =
GlMat.rotate ~angle:180.0 ~z:1.0 ();
GlMat.rotate ~angle:(-.icoangle) ~x:1.0 ();
call_list list color.(i)
in
GlMat.push ();
call_list list color.(0);
GlMat.push ();
do_list3 1;
GlMat.push ();
do_list1 2;
GlMat.pop ();
do_list2 3;
GlMat.pop ();
GlMat.push ();
do_list1 4;
GlMat.push ();
do_list1 5;
GlMat.pop();
do_list3 6;
GlMat.pop ();
do_list2 7;
GlMat.push ();
do_list2 8;
GlMat.pop ();
do_list3 9;
GlMat.pop ();
GlMat.rotate ~angle:180.0 ~x:1.0 ();
call_list list color.(10);
GlMat.push ();
do_list3 11;
GlMat.push ();
do_list1 12;
GlMat.pop ();
do_list2 13;
GlMat.pop ();
GlMat.push ();
do_list1 14;
GlMat.push ();
do_list1 15;
GlMat.pop ();
do_list3 16;
GlMat.pop ();
do_list2 17;
GlMat.push ();
do_list2 18;
GlMat.pop ();
do_list3 19;
GlList.delete list
class view = object (self)
val mutable smooth = true
val mutable step = 0.
val mutable obj = 1
val mutable draw_object = fun ~amp -> ()
val mutable magnitude = 0.
val mutable my_width = 640
val mutable my_height = 480
method width = my_width
method height = my_height
method draw =
let ratio = float self#height /. float self#width in
GlClear.clear [`color;`depth];
GlMat.push ();
GlMat.translate () ~z:(-10.0);
GlMat.scale () ~x:(scale *. ratio) ~y:scale ~z:scale;
GlMat.translate ()
~x:(2.5 *. ratio *. sin (step *. 1.11))
~y:(2.5 *. cos (step *. 1.25 *. 1.11));
GlMat.rotate ~angle:(step *. 100.) ~x:1.0 ();
GlMat.rotate ~angle:(step *. 95.) ~y:1.0 ();
GlMat.rotate ~angle:(step *. 90.) ~z:1.0 ();
draw_object ~amp:((sin step +. 1.0/.3.0) *. (4.0/.5.0) *. magnitude);
GlMat.pop();
Gl.flush();
Glut.swapBuffers ();
step <- step +. 0.05
method reshape ~w ~h =
my_width <- w;
my_height <- h;
GlDraw.viewport ~x:0 ~y:0 ~w:self#width ~h:self#height;
GlMat.mode `projection;
GlMat.load_identity();
GlMat.frustum ~x:(-1.0, 1.0) ~y:(-1.0, 1.0) ~z:(5.0, 15.0);
GlMat.mode `modelview
method keyboard key =
begin
match (char_of_int key) with
| '1' -> obj <- 1
| '2' -> obj <- 2
| '3' -> obj <- 3
| '4' -> obj <- 4
| '5' -> obj <- 5
| _ -> match key with
| 10(*return*) -> smooth <- not smooth
| 27(*escape*) -> exit 0
| _ -> ();
end;
self#pinit
method pinit =
begin match obj with
1 ->
draw_object <- draw_tetra
~divisions:tetradivisions
~color:[|materialRed; materialGreen;
materialBlue; materialWhite|];
magnitude <- 2.5
| 2 ->
draw_object <- draw_cube
~divisions:cubedivisions
~color:[|materialRed; materialGreen; materialCyan;
materialMagenta; materialYellow; materialBlue|];
magnitude <- 2.0
| 3 ->
draw_object <- draw_octa
~divisions:octadivisions
~color:[|materialRed; materialGreen; materialBlue;
materialWhite; materialCyan; materialMagenta;
materialGray; materialYellow|];
magnitude <- 2.5
| 4 ->
draw_object <- draw_dodeca
~divisions:dodecadivisions
~color:[|materialRed; materialGreen; materialCyan;
materialBlue; materialMagenta; materialYellow;
materialGreen; materialCyan; materialRed;
materialMagenta; materialBlue; materialYellow|];
magnitude <- 2.0
| 5 ->
draw_object <- draw_ico
~divisions:icodivisions
~color:[|materialRed; materialGreen; materialBlue;
materialCyan; materialYellow; materialMagenta;
materialRed; materialGreen; materialBlue;
materialWhite; materialCyan; materialYellow;
materialMagenta; materialRed; materialGreen;
materialBlue; materialCyan; materialYellow;
materialMagenta; materialGray|];
magnitude <- 3.5
| _ -> ()
end;
GlDraw.shade_model (if smooth then `smooth else `flat)
end
let main () =
List.iter ~f:print_string
[ "Morph 3D - Shows morphing platonic polyhedra\n";
"Author: Marcelo Fernandes Vianna ()\n";
"Ported to LablGL by Jacques Garrigue\n";
"Ported to lablglut by Issac Trotts\n\n";
" [1] - Tetrahedron\n";
" [2] - Hexahedron (Cube)\n";
" [3] - Octahedron\n";
" [4] - Dodecahedron\n";
" [5] - Icosahedron\n";
(* "[RETURN] - Toggle smooth/flat shading\n"; *) (* not working ... ??? *)
" [ESC] - Quit\n" ];
flush stdout;
ignore(Glut.init Sys.argv);
Glut.initDisplayMode ~alpha:false ~double_buffer:true ~depth:true ();
Glut.initWindowSize ~w:640 ~h:480;
ignore(Glut.createWindow ~title:"Morph 3D - Shows morphing platonic polyhedra");
GlClear.depth 1.0;
GlClear.color (0.0, 0.0, 0.0);
GlDraw.color (1.0, 1.0, 1.0);
GlClear.clear [`color;`depth];
Gl.flush();
Glut.swapBuffers();
List.iter ~f:(GlLight.light ~num:0)
[`ambient ambient; `diffuse diffuse; `position position0];
List.iter ~f:(GlLight.light ~num:1)
[`ambient ambient; `diffuse diffuse; `position position1];
GlLight.light_model (`ambient lmodel_ambient);
GlLight.light_model (`two_side lmodel_twoside);
List.iter ~f:Gl.enable
[`lighting;`light0;`light1;`depth_test;`normalize];
GlLight.material ~face:`both (`shininess front_shininess);
GlLight.material ~face:`both (`specular front_specular);
GlMisc.hint `fog `fastest;
GlMisc.hint `perspective_correction `fastest;
GlMisc.hint `polygon_smooth `fastest;
let view = new view in
view#pinit;
Glut.displayFunc ~cb:(fun () -> view#draw);
Glut.reshapeFunc ~cb:(fun ~w ~h -> view#reshape w h);
let rec idle ~value = view#draw; Glut.timerFunc ~ms:20 ~cb:idle ~value:0 in
Glut.timerFunc ~ms:20 ~cb:idle ~value:0;
Glut.keyboardFunc ~cb:(fun ~key ~x ~y -> view#keyboard key);
Glut.mainLoop ()
let _ = main ()
| null | https://raw.githubusercontent.com/fccm/glMLite/c52cd806909581e49d9b660195576c8a932f6d33/LablGL/lablGL_samples/morph3d.ml | ocaml | Increasing this values produces better image quality, the price is speed.
Very low values produces erroneous/incorrect plotting
***********************************************************************
return
escape
"[RETURN] - Toggle smooth/flat shading\n";
not working ... ??? | $ I d : morph3d.ml , v 1.2 2005/10/17 11:27:04 garrigue Exp $
open LablGL
open StdLabels
open Printf
-
* morph3d.c - Shows 3D morphing objects ( TK Version )
*
* This program was inspired on a WindowsNT(R ) 's screen saver . It was written
* from scratch and it was not based on any other source code .
*
* Porting it to xlock ( the final objective of this code since the moment I
* decided to create it ) was possible by comparing the original Mesa 's gear
* demo with it 's ported version , so thanks for for his indirect
* help ( look at gear.c in xlock source tree ) . NOTE : At the moment this code
* was sent to for package inclusion , the XLock Version was not
* available . In fact , I 'll wait it to appear on the next Mesa release ( If you
* are reading this , it means THIS release ) to send it for xlock package
* inclusion ) . It will probably there be a GLUT version too .
*
* Thanks goes also to for making it possible and inexpensive
* to use OpenGL at home .
*
* Since I 'm not a native english speaker , my apologies for any gramatical
* mistake .
*
* My e - mail addresses are
*
*
* and
*
*
* ( Feb-13 - 1997 )
* morph3d.c - Shows 3D morphing objects (TK Version)
*
* This program was inspired on a WindowsNT(R)'s screen saver. It was written
* from scratch and it was not based on any other source code.
*
* Porting it to xlock (the final objective of this code since the moment I
* decided to create it) was possible by comparing the original Mesa's gear
* demo with it's ported version, so thanks for Danny Sung for his indirect
* help (look at gear.c in xlock source tree). NOTE: At the moment this code
* was sent to Brian Paul for package inclusion, the XLock Version was not
* available. In fact, I'll wait it to appear on the next Mesa release (If you
* are reading this, it means THIS release) to send it for xlock package
* inclusion). It will probably there be a GLUT version too.
*
* Thanks goes also to Brian Paul for making it possible and inexpensive
* to use OpenGL at home.
*
* Since I'm not a native english speaker, my apologies for any gramatical
* mistake.
*
* My e-mail addresses are
*
*
* and
*
*
* Marcelo F. Vianna (Feb-13-1997)
*)
This document is VERY incomplete , but tries to describe the mathematics used
in the program . At this moment it just describes how the polyhedra are
generated . On futhurer versions , this document will be probabbly improved .
Since I 'm not a native english speaker , my apologies for any gramatical
mistake .
at Catholic Pontifical University
- of Rio de Janeiro ( PUC - Rio ) Brasil .
- e - mail : or
- Feb-13 - 1997
POLYHEDRA GENERATION
For the purpose of this program it 's not sufficient to know the polyhedra
vertexes coordinates . Since the morphing algorithm applies a nonlinear
transformation over the surfaces ( faces ) of the polyhedron , each face has
to be divided into smaller ones . The morphing algorithm needs to transform
each vertex of these smaller faces individually . It 's a very time consoming
task .
In order to reduce calculation overload , and since all the macro faces of
the polyhedron are transformed by the same way , the generation is made by
creating only one face of the polyhedron , morphing it and then rotating it
around the polyhedron center .
What we need to know is the face radius of the polyhedron ( the radius of
the inscribed sphere ) and the angle between the center of two adjacent
faces using the center of the sphere as the angle 's vertex .
The face radius of the regular polyhedra are known values which I decided
to not waste my time calculating . Following is a table of face radius for
the regular polyhedra with edge length = 1 :
TETRAHEDRON : 1/(2*sqrt(2))/sqrt(3 )
CUBE : 1/2
OCTAHEDRON : 1 / sqrt(6 )
DODECAHEDRON : T^2 * sqrt((T+2)/5 ) / 2 - > where
ICOSAHEDRON : ( 3*sqrt(3)+sqrt(15))/12
I 've not found any reference about the mentioned angles , so I needed to
calculate them , not a trivial task until I figured out how :)
Curiously these angles are the same for the tetrahedron and octahedron .
A way to obtain this value is inscribing the tetrahedron inside the cube
by matching their vertexes . So you 'll notice that the remaining unmatched
vertexes are in the same straight line starting in the cube / tetrahedron
center and crossing the center of each tetrahedron 's face . At this point
it 's easy to obtain the bigger angle of the isosceles triangle formed by
the center of the cube and two opposite vertexes on the same cube face .
The edges of this triangle have the following lenghts : sqrt(2 ) for the base
and sqrt(3)/2 for the other two other edges . So the angle we want is :
+ -----------------------------------------------------------+
| 2*ARCSIN(sqrt(2)/sqrt(3 ) ) = 109.47122063449069174 degrees |
+ -----------------------------------------------------------+
For the cube this angle is obvious , but just for formality it can be
easily obtained because we also know it 's isosceles edge lenghts :
sqrt(2)/2 for the base and 1/2 for the other two edges . So the angle we
want is :
+ -----------------------------------------------------------+
| 2*ARCSIN((sqrt(2)/2)/1 ) = 90.000000000000000000 degrees |
+ -----------------------------------------------------------+
For the octahedron we use the same idea used for the tetrahedron , but now
we inscribe the cube inside the octahedron so that all cubes 's vertexes
matches excatly the center of each octahedron 's face . It 's now clear that
this angle is the same of the thetrahedron one :
+ -----------------------------------------------------------+
| 2*ARCSIN(sqrt(2)/sqrt(3 ) ) = 109.47122063449069174 degrees |
+ -----------------------------------------------------------+
For the dodecahedron it 's a little bit harder because it 's only relationship
with the cube is useless to us . So we need to solve the problem by another
way . The concept of Face radius also exists on 2D polygons with the name
Edge radius :
Edge Radius For Pentagon ( ERp )
ERp = ( 1/2)/TAN(36 degrees ) * VRp = 0.6881909602355867905
( VRp is the pentagon 's vertex radio ) .
Face Radius For Dodecahedron
FRd = T^2 * sqrt((T+2)/5 ) / 2 = 1.1135163644116068404
Why we need ERp ? Well , ERp and FRd segments forms a 90 degrees angle ,
completing this triangle , the lesser angle is a half of the angle we are
looking for , so this angle is :
+ -----------------------------------------------------------+
| 2*ARCTAN(ERp / FRd ) = 63.434948822922009981 degrees |
+ -----------------------------------------------------------+
For the icosahedron we can use the same method used for dodecahedron ( well
the method used for dodecahedron may be used for all regular polyhedra )
Edge Radius For Triangle ( this one is well known : 1/3 of the triangle height )
ERt = sin(60)/3 = sqrt(3)/6 = 0.2886751345948128655
Face Radius For Icosahedron
FRi= ( 3*sqrt(3)+sqrt(15))/12 = 0.7557613140761707538
So the angle is :
+ -----------------------------------------------------------+
| 2*ARCTAN(ERt / FRi ) = 41.810314895778596167 degrees |
+ -----------------------------------------------------------+
This document is VERY incomplete, but tries to describe the mathematics used
in the program. At this moment it just describes how the polyhedra are
generated. On futhurer versions, this document will be probabbly improved.
Since I'm not a native english speaker, my apologies for any gramatical
mistake.
Marcelo Fernandes Vianna
- Undergraduate in Computer Engeneering at Catholic Pontifical University
- of Rio de Janeiro (PUC-Rio) Brasil.
- e-mail: or
- Feb-13-1997
POLYHEDRA GENERATION
For the purpose of this program it's not sufficient to know the polyhedra
vertexes coordinates. Since the morphing algorithm applies a nonlinear
transformation over the surfaces (faces) of the polyhedron, each face has
to be divided into smaller ones. The morphing algorithm needs to transform
each vertex of these smaller faces individually. It's a very time consoming
task.
In order to reduce calculation overload, and since all the macro faces of
the polyhedron are transformed by the same way, the generation is made by
creating only one face of the polyhedron, morphing it and then rotating it
around the polyhedron center.
What we need to know is the face radius of the polyhedron (the radius of
the inscribed sphere) and the angle between the center of two adjacent
faces using the center of the sphere as the angle's vertex.
The face radius of the regular polyhedra are known values which I decided
to not waste my time calculating. Following is a table of face radius for
the regular polyhedra with edge length = 1:
TETRAHEDRON : 1/(2*sqrt(2))/sqrt(3)
CUBE : 1/2
OCTAHEDRON : 1/sqrt(6)
DODECAHEDRON : T^2 * sqrt((T+2)/5) / 2 -> where T=(sqrt(5)+1)/2
ICOSAHEDRON : (3*sqrt(3)+sqrt(15))/12
I've not found any reference about the mentioned angles, so I needed to
calculate them, not a trivial task until I figured out how :)
Curiously these angles are the same for the tetrahedron and octahedron.
A way to obtain this value is inscribing the tetrahedron inside the cube
by matching their vertexes. So you'll notice that the remaining unmatched
vertexes are in the same straight line starting in the cube/tetrahedron
center and crossing the center of each tetrahedron's face. At this point
it's easy to obtain the bigger angle of the isosceles triangle formed by
the center of the cube and two opposite vertexes on the same cube face.
The edges of this triangle have the following lenghts: sqrt(2) for the base
and sqrt(3)/2 for the other two other edges. So the angle we want is:
+-----------------------------------------------------------+
| 2*ARCSIN(sqrt(2)/sqrt(3)) = 109.47122063449069174 degrees |
+-----------------------------------------------------------+
For the cube this angle is obvious, but just for formality it can be
easily obtained because we also know it's isosceles edge lenghts:
sqrt(2)/2 for the base and 1/2 for the other two edges. So the angle we
want is:
+-----------------------------------------------------------+
| 2*ARCSIN((sqrt(2)/2)/1) = 90.000000000000000000 degrees |
+-----------------------------------------------------------+
For the octahedron we use the same idea used for the tetrahedron, but now
we inscribe the cube inside the octahedron so that all cubes's vertexes
matches excatly the center of each octahedron's face. It's now clear that
this angle is the same of the thetrahedron one:
+-----------------------------------------------------------+
| 2*ARCSIN(sqrt(2)/sqrt(3)) = 109.47122063449069174 degrees |
+-----------------------------------------------------------+
For the dodecahedron it's a little bit harder because it's only relationship
with the cube is useless to us. So we need to solve the problem by another
way. The concept of Face radius also exists on 2D polygons with the name
Edge radius:
Edge Radius For Pentagon (ERp)
ERp = (1/2)/TAN(36 degrees) * VRp = 0.6881909602355867905
(VRp is the pentagon's vertex radio).
Face Radius For Dodecahedron
FRd = T^2 * sqrt((T+2)/5) / 2 = 1.1135163644116068404
Why we need ERp? Well, ERp and FRd segments forms a 90 degrees angle,
completing this triangle, the lesser angle is a half of the angle we are
looking for, so this angle is:
+-----------------------------------------------------------+
| 2*ARCTAN(ERp/FRd) = 63.434948822922009981 degrees |
+-----------------------------------------------------------+
For the icosahedron we can use the same method used for dodecahedron (well
the method used for dodecahedron may be used for all regular polyhedra)
Edge Radius For Triangle (this one is well known: 1/3 of the triangle height)
ERt = sin(60)/3 = sqrt(3)/6 = 0.2886751345948128655
Face Radius For Icosahedron
FRi= (3*sqrt(3)+sqrt(15))/12 = 0.7557613140761707538
So the angle is:
+-----------------------------------------------------------+
| 2*ARCTAN(ERt/FRi) = 41.810314895778596167 degrees |
+-----------------------------------------------------------+
*)
let scale = 0.3
let vect_mul (x1,y1,z1) (x2,y2,z2) =
(y1 *. z2 -. z1 *. y2, z1 *. x2 -. x1 *. z2, x1 *. y2 -. y1 *. x2)
let sqr a = a *. a
let tetradivisions = 23
let cubedivisions = 20
let octadivisions = 21
let dodecadivisions = 10
let icodivisions = 15
let tetraangle = 109.47122063449069174
let cubeangle = 90.000000000000000000
let octaangle = 109.47122063449069174
let dodecaangle = 63.434948822922009981
let icoangle = 41.810314895778596167
let pi = acos (-1.)
let sqrt2 = sqrt 2.
let sqrt3 = sqrt 3.
let sqrt5 = sqrt 5.
let sqrt6 = sqrt 6.
let sqrt15 = sqrt 15.
let cossec36_2 = 0.8506508083520399322
let cosd x = cos (float x /. 180. *. pi)
let sind x = sin (float x /. 180. *. pi)
let cos72 = cosd 72
let sin72 = sind 72
let cos36 = cosd 36
let sin36 = sind 36
let front_shininess = 60.0
let front_specular = 0.7, 0.7, 0.7, 1.0
let ambient = 0.0, 0.0, 0.0, 1.0
let diffuse = 1.0, 1.0, 1.0, 1.0
let position0 = 1.0, 1.0, 1.0, 0.0
let position1 = -1.0,-1.0, 1.0, 0.0
let lmodel_ambient = 0.5, 0.5, 0.5, 1.0
let lmodel_twoside = true
let materialRed = 0.7, 0.0, 0.0, 1.0
let materialGreen = 0.1, 0.5, 0.2, 1.0
let materialBlue = 0.0, 0.0, 0.7, 1.0
let materialCyan = 0.2, 0.5, 0.7, 1.0
let materialYellow = 0.7, 0.7, 0.0, 1.0
let materialMagenta = 0.6, 0.2, 0.5, 1.0
let materialWhite = 0.7, 0.7, 0.7, 1.0
let materialGray = 0.2, 0.2, 0.2, 1.0
let all_gray = Array.create 20 materialGray
let vertex ~xf ~yf ~zf ~ampvr2 =
let xa = xf +. 0.01 and yb = yf +. 0.01 in
let xf2 = sqr xf and yf2 = sqr yf in
let factor = 1. -. (xf2 +. yf2) *. ampvr2
and factor1 = 1. -. (sqr xa +. yf2) *. ampvr2
and factor2 = 1. -. (xf2 +. sqr yb) *. ampvr2 in
let vertx = factor *. xf and verty = factor *. yf
and vertz = factor *. zf in
let neiax = factor1 *. xa -. vertx and neiay = factor1 *. yf -. verty
and neiaz = factor1 *. zf -. vertz and neibx = factor2 *. xf -. vertx
and neiby = factor2 *. yb -. verty and neibz = factor2 *. zf -. vertz in
GlDraw.normal3 (vect_mul (neiax, neiay, neiaz) (neibx, neiby, neibz));
GlDraw.vertex3 (vertx, verty, vertz)
let triangle ~edge ~amp ~divisions ~z =
let divi = float divisions in
let vr = edge *. sqrt3 /. 3. in
let ampvr2 = amp /. sqr vr
and zf = edge *. z in
let ax = edge *. (0.5 /. divi)
and ay = edge *. (-0.5 *. sqrt3 /. divi)
and bx = edge *. (-0.5 /. divi) in
for ri = 1 to divisions do
GlDraw.begins `triangle_strip;
for ti = 0 to ri - 1 do
vertex ~zf ~ampvr2
~xf:(float (ri-ti) *. ax +. float ti *. bx)
~yf:(vr +. float (ri-ti) *. ay +. float ti *. ay);
vertex ~zf ~ampvr2
~xf:(float (ri-ti-1) *. ax +. float ti *. bx)
~yf:(vr +. float (ri-ti-1) *. ay +. float ti *. ay)
done;
vertex ~xf:(float ri *. bx) ~yf:(vr +. float ri *. ay) ~zf ~ampvr2;
GlDraw.ends ()
done
let square ~edge ~amp ~divisions ~z =
let divi = float divisions in
let zf = edge *. z
and ampvr2 = amp /. sqr (edge *. sqrt2 /. 2.) in
for yi = 0 to divisions - 1 do
let yf = edge *. (-0.5 +. float yi /. divi) in
let y = yf +. 1.0 /. divi *. edge in
GlDraw.begins `quad_strip;
for xi = 0 to divisions do
let xf = edge *. (-0.5 +. float xi /. divi) in
vertex ~xf ~yf:y ~zf ~ampvr2;
vertex ~xf ~yf ~zf ~ampvr2
done;
GlDraw.ends ()
done
let pentagon ~edge ~amp ~divisions ~z =
let divi = float divisions in
let zf = edge *. z
and ampvr2 = amp /. sqr(edge *. cossec36_2) in
let x =
Array.init 6
~f:(fun fi -> -. cos (float fi *. 2. *. pi /. 5. +. pi /. 10.)
/. divi *. cossec36_2 *. edge)
and y =
Array.init 6
~f:(fun fi -> sin (float fi *. 2. *. pi /. 5. +. pi /. 10.)
/. divi *. cossec36_2 *. edge)
in
for ri = 1 to divisions do
for fi = 0 to 4 do
GlDraw.begins `triangle_strip;
for ti = 0 to ri-1 do
vertex ~zf ~ampvr2
~xf:(float(ri-ti) *. x.(fi) +. float ti *. x.(fi+1))
~yf:(float(ri-ti) *. y.(fi) +. float ti *. y.(fi+1));
vertex ~zf ~ampvr2
~xf:(float(ri-ti-1) *. x.(fi) +. float ti *. x.(fi+1))
~yf:(float(ri-ti-1) *. y.(fi) +. float ti *. y.(fi+1))
done;
vertex ~xf:(float ri *. x.(fi+1)) ~yf:(float ri *. y.(fi+1)) ~zf ~ampvr2;
GlDraw.ends ()
done
done
let call_list list color =
GlLight.material ~face:`both (`diffuse color);
GlList.call list
let draw_tetra ~amp ~divisions ~color =
let list = GlList.create `compile in
triangle ~edge:2.0 ~amp ~divisions ~z:(0.5 /. sqrt6);
GlList.ends();
call_list list color.(0);
GlMat.push();
GlMat.rotate ~angle:180.0 ~z:1.0 ();
GlMat.rotate ~angle:(-.tetraangle) ~x:1.0 ();
call_list list color.(1);
GlMat.pop();
GlMat.push();
GlMat.rotate ~angle:180.0 ~y:1.0 ();
GlMat.rotate ~angle:(-180.0 +. tetraangle) ~x:0.5 ~y:(sqrt3 /. 2.) ();
call_list list color.(2);
GlMat.pop();
GlMat.rotate ~angle:180.0 ~y:1.0 ();
GlMat.rotate ~angle:(-180.0 +. tetraangle) ~x:0.5 ~y:(-.sqrt3 /. 2.) ();
call_list list color.(3);
GlList.delete list
let draw_cube ~amp ~divisions ~color =
let list = GlList.create `compile in
square ~edge:2.0 ~amp ~divisions ~z:0.5;
GlList.ends ();
call_list list color.(0);
for i = 1 to 3 do
GlMat.rotate ~angle:cubeangle ~x:1.0 ();
call_list list color.(i)
done;
GlMat.rotate ~angle:cubeangle ~y:1.0 ();
call_list list color.(4);
GlMat.rotate ~angle:(2.0 *. cubeangle) ~y:1.0 ();
call_list list color.(5);
GlList.delete list
let draw_octa ~amp ~divisions ~color =
let list = GlList.create `compile in
triangle ~edge:2.0 ~amp ~divisions ~z:(1.0 /. sqrt6);
GlList.ends ();
let do_list (i,y) =
GlMat.push();
GlMat.rotate ~angle:180.0 ~y:1.0 ();
GlMat.rotate ~angle:(-.octaangle) ~x:0.5 ~y ();
call_list list color.(i);
GlMat.pop()
in
call_list list color.(0);
GlMat.push();
GlMat.rotate ~angle:180.0 ~z:1.0 ();
GlMat.rotate ~angle:(-180.0 +. octaangle) ~x:1.0 ();
call_list list color.(1);
GlMat.pop();
List.iter [2, sqrt3 /. 2.0; 3, -.sqrt3 /. 2.0] ~f:do_list;
GlMat.rotate ~angle:180.0 ~x:1.0 ();
GlLight.material ~face:`both (`diffuse color.(4));
GlList.call list;
GlMat.push();
GlMat.rotate ~angle:180.0 ~z:1.0 ();
GlMat.rotate ~angle:(-180.0 +. octaangle) ~x:1.0 ();
GlLight.material ~face:`both (`diffuse color.(5));
GlList.call list;
GlMat.pop();
List.iter [6, sqrt3 /. 2.0; 7, -.sqrt3 /. 2.0] ~f:do_list;
GlList.delete list
let draw_dodeca ~amp ~divisions ~color =
let tau = (sqrt5 +. 1.0) /. 2.0 in
let list = GlList.create `compile in
pentagon ~edge:2.0 ~amp ~divisions
~z:(sqr(tau) *. sqrt ((tau+.2.0)/.5.0) /. 2.0);
GlList.ends ();
let do_list (i,angle,x,y) =
GlMat.push();
GlMat.rotate ~angle:angle ~x ~y ();
call_list list color.(i);
GlMat.pop();
in
GlMat.push ();
call_list list color.(0);
GlMat.rotate ~angle:180.0 ~z:1.0 ();
List.iter ~f:do_list
[ 1, -.dodecaangle, 1.0, 0.0;
2, -.dodecaangle, cos72, sin72;
3, -.dodecaangle, cos72, -.sin72;
4, dodecaangle, cos36, -.sin36;
5, dodecaangle, cos36, sin36 ];
GlMat.pop ();
GlMat.rotate ~angle:180.0 ~x:1.0 ();
call_list list color.(6);
GlMat.rotate ~angle:180.0 ~z:1.0 ();
List.iter ~f:do_list
[ 7, -.dodecaangle, 1.0, 0.0;
8, -.dodecaangle, cos72, sin72;
9, -.dodecaangle, cos72, -.sin72;
10, dodecaangle, cos36, -.sin36 ];
GlMat.rotate ~angle:dodecaangle ~x:cos36 ~y:sin36 ();
call_list list color.(11);
GlList.delete list
let draw_ico ~amp ~divisions ~color =
let list = GlList.create `compile in
triangle ~edge:1.5 ~amp ~divisions
~z:((3.0 *. sqrt3 +. sqrt15) /. 12.0);
GlList.ends ();
let do_list1 i =
GlMat.rotate ~angle:180.0 ~y:1.0 ();
GlMat.rotate ~angle:(-180.0 +. icoangle) ~x:0.5 ~y:(sqrt3/.2.0) ();
call_list list color.(i)
and do_list2 i =
GlMat.rotate ~angle:180.0 ~y:1.0 ();
GlMat.rotate ~angle:(-180.0 +. icoangle) ~x:0.5 ~y:(-.sqrt3/.2.0) ();
call_list list color.(i)
and do_list3 i =
GlMat.rotate ~angle:180.0 ~z:1.0 ();
GlMat.rotate ~angle:(-.icoangle) ~x:1.0 ();
call_list list color.(i)
in
GlMat.push ();
call_list list color.(0);
GlMat.push ();
do_list3 1;
GlMat.push ();
do_list1 2;
GlMat.pop ();
do_list2 3;
GlMat.pop ();
GlMat.push ();
do_list1 4;
GlMat.push ();
do_list1 5;
GlMat.pop();
do_list3 6;
GlMat.pop ();
do_list2 7;
GlMat.push ();
do_list2 8;
GlMat.pop ();
do_list3 9;
GlMat.pop ();
GlMat.rotate ~angle:180.0 ~x:1.0 ();
call_list list color.(10);
GlMat.push ();
do_list3 11;
GlMat.push ();
do_list1 12;
GlMat.pop ();
do_list2 13;
GlMat.pop ();
GlMat.push ();
do_list1 14;
GlMat.push ();
do_list1 15;
GlMat.pop ();
do_list3 16;
GlMat.pop ();
do_list2 17;
GlMat.push ();
do_list2 18;
GlMat.pop ();
do_list3 19;
GlList.delete list
class view = object (self)
val mutable smooth = true
val mutable step = 0.
val mutable obj = 1
val mutable draw_object = fun ~amp -> ()
val mutable magnitude = 0.
val mutable my_width = 640
val mutable my_height = 480
method width = my_width
method height = my_height
method draw =
let ratio = float self#height /. float self#width in
GlClear.clear [`color;`depth];
GlMat.push ();
GlMat.translate () ~z:(-10.0);
GlMat.scale () ~x:(scale *. ratio) ~y:scale ~z:scale;
GlMat.translate ()
~x:(2.5 *. ratio *. sin (step *. 1.11))
~y:(2.5 *. cos (step *. 1.25 *. 1.11));
GlMat.rotate ~angle:(step *. 100.) ~x:1.0 ();
GlMat.rotate ~angle:(step *. 95.) ~y:1.0 ();
GlMat.rotate ~angle:(step *. 90.) ~z:1.0 ();
draw_object ~amp:((sin step +. 1.0/.3.0) *. (4.0/.5.0) *. magnitude);
GlMat.pop();
Gl.flush();
Glut.swapBuffers ();
step <- step +. 0.05
method reshape ~w ~h =
my_width <- w;
my_height <- h;
GlDraw.viewport ~x:0 ~y:0 ~w:self#width ~h:self#height;
GlMat.mode `projection;
GlMat.load_identity();
GlMat.frustum ~x:(-1.0, 1.0) ~y:(-1.0, 1.0) ~z:(5.0, 15.0);
GlMat.mode `modelview
method keyboard key =
begin
match (char_of_int key) with
| '1' -> obj <- 1
| '2' -> obj <- 2
| '3' -> obj <- 3
| '4' -> obj <- 4
| '5' -> obj <- 5
| _ -> match key with
| _ -> ();
end;
self#pinit
method pinit =
begin match obj with
1 ->
draw_object <- draw_tetra
~divisions:tetradivisions
~color:[|materialRed; materialGreen;
materialBlue; materialWhite|];
magnitude <- 2.5
| 2 ->
draw_object <- draw_cube
~divisions:cubedivisions
~color:[|materialRed; materialGreen; materialCyan;
materialMagenta; materialYellow; materialBlue|];
magnitude <- 2.0
| 3 ->
draw_object <- draw_octa
~divisions:octadivisions
~color:[|materialRed; materialGreen; materialBlue;
materialWhite; materialCyan; materialMagenta;
materialGray; materialYellow|];
magnitude <- 2.5
| 4 ->
draw_object <- draw_dodeca
~divisions:dodecadivisions
~color:[|materialRed; materialGreen; materialCyan;
materialBlue; materialMagenta; materialYellow;
materialGreen; materialCyan; materialRed;
materialMagenta; materialBlue; materialYellow|];
magnitude <- 2.0
| 5 ->
draw_object <- draw_ico
~divisions:icodivisions
~color:[|materialRed; materialGreen; materialBlue;
materialCyan; materialYellow; materialMagenta;
materialRed; materialGreen; materialBlue;
materialWhite; materialCyan; materialYellow;
materialMagenta; materialRed; materialGreen;
materialBlue; materialCyan; materialYellow;
materialMagenta; materialGray|];
magnitude <- 3.5
| _ -> ()
end;
GlDraw.shade_model (if smooth then `smooth else `flat)
end
let main () =
List.iter ~f:print_string
[ "Morph 3D - Shows morphing platonic polyhedra\n";
"Author: Marcelo Fernandes Vianna ()\n";
"Ported to LablGL by Jacques Garrigue\n";
"Ported to lablglut by Issac Trotts\n\n";
" [1] - Tetrahedron\n";
" [2] - Hexahedron (Cube)\n";
" [3] - Octahedron\n";
" [4] - Dodecahedron\n";
" [5] - Icosahedron\n";
" [ESC] - Quit\n" ];
flush stdout;
ignore(Glut.init Sys.argv);
Glut.initDisplayMode ~alpha:false ~double_buffer:true ~depth:true ();
Glut.initWindowSize ~w:640 ~h:480;
ignore(Glut.createWindow ~title:"Morph 3D - Shows morphing platonic polyhedra");
GlClear.depth 1.0;
GlClear.color (0.0, 0.0, 0.0);
GlDraw.color (1.0, 1.0, 1.0);
GlClear.clear [`color;`depth];
Gl.flush();
Glut.swapBuffers();
List.iter ~f:(GlLight.light ~num:0)
[`ambient ambient; `diffuse diffuse; `position position0];
List.iter ~f:(GlLight.light ~num:1)
[`ambient ambient; `diffuse diffuse; `position position1];
GlLight.light_model (`ambient lmodel_ambient);
GlLight.light_model (`two_side lmodel_twoside);
List.iter ~f:Gl.enable
[`lighting;`light0;`light1;`depth_test;`normalize];
GlLight.material ~face:`both (`shininess front_shininess);
GlLight.material ~face:`both (`specular front_specular);
GlMisc.hint `fog `fastest;
GlMisc.hint `perspective_correction `fastest;
GlMisc.hint `polygon_smooth `fastest;
let view = new view in
view#pinit;
Glut.displayFunc ~cb:(fun () -> view#draw);
Glut.reshapeFunc ~cb:(fun ~w ~h -> view#reshape w h);
let rec idle ~value = view#draw; Glut.timerFunc ~ms:20 ~cb:idle ~value:0 in
Glut.timerFunc ~ms:20 ~cb:idle ~value:0;
Glut.keyboardFunc ~cb:(fun ~key ~x ~y -> view#keyboard key);
Glut.mainLoop ()
let _ = main ()
|
3563f78262a31783164989d4eac6668bf89543c4a296c25f18dbd94133803f95 | ceramic/ceramic | misc.lisp | (in-package :cl-user)
(defpackage ceramic-test.misc
(:use :cl :fiveam)
(:export :misc))
(in-package :ceramic-test.misc)
(def-suite misc
:description "Miscellaneous tests.")
(in-suite misc)
(test runtime
(let ((ceramic.runtime:*releasep* t))
(is
(pathnamep (ceramic.runtime:executable-pathname)))
(is
(pathnamep (ceramic.runtime:executable-relative-pathname #p"file.txt"))))
(let ((ceramic.runtime:*releasep* nil))
(signals ceramic.error:not-in-release
(ceramic.runtime:executable-pathname))))
(test os
(is (keywordp (ceramic.os::detect-operating-system)))
(is (keywordp (ceramic.os::detect-architecture))))
| null | https://raw.githubusercontent.com/ceramic/ceramic/5d81e2bd954440a6adebde31fac9c730a698c74b/t/misc.lisp | lisp | (in-package :cl-user)
(defpackage ceramic-test.misc
(:use :cl :fiveam)
(:export :misc))
(in-package :ceramic-test.misc)
(def-suite misc
:description "Miscellaneous tests.")
(in-suite misc)
(test runtime
(let ((ceramic.runtime:*releasep* t))
(is
(pathnamep (ceramic.runtime:executable-pathname)))
(is
(pathnamep (ceramic.runtime:executable-relative-pathname #p"file.txt"))))
(let ((ceramic.runtime:*releasep* nil))
(signals ceramic.error:not-in-release
(ceramic.runtime:executable-pathname))))
(test os
(is (keywordp (ceramic.os::detect-operating-system)))
(is (keywordp (ceramic.os::detect-architecture))))
| |
b0164c1bac668d60b0611c1b9b36a6608c02255359c347ef40efc2e60516eb8f | input-output-hk/marlowe-cardano | ViaSerialise.hs | # LANGUAGE ImportQualifiedPost #
module Data.Aeson.ViaSerialise
where
import qualified Codec.CBOR.Write as CBOR.Write
import Codec.Serialise (Serialise, decode, deserialiseOrFail, encode)
import qualified Data.Aeson as Aeson
import Data.ByteString.Base16.Aeson as Base16.Aeson
import qualified Data.ByteString.Lazy as BSL
newtype ViaSerialise a = ViaSerialise a
unViaSerialise (ViaSerialise a) = a
instance Serialise a => Aeson.ToJSON (ViaSerialise a) where
toJSON (ViaSerialise a) = Base16.Aeson.byteStringToJSON . CBOR.Write.toStrictByteString . encode $ a
instance Serialise a => Aeson.FromJSON (ViaSerialise a) where
parseJSON v = ViaSerialise <$> do
EncodeBase16 bs <- Aeson.parseJSON v
case deserialiseOrFail . BSL.fromStrict $ bs of
Left err -> fail (show err)
Right res -> pure res
encodeToJSON :: Serialise a => a -> Aeson.Value
encodeToJSON a = Aeson.toJSON (ViaSerialise a)
decodeToJSON :: Serialise a => Aeson.Value -> Aeson.Result a
decodeToJSON v = unViaSerialise <$> Aeson.fromJSON v
| null | https://raw.githubusercontent.com/input-output-hk/marlowe-cardano/78a3dbb1cd692146b7d1a32e1e66faed884f2432/libs/aeson-via-serialise/src/Data/Aeson/ViaSerialise.hs | haskell | # LANGUAGE ImportQualifiedPost #
module Data.Aeson.ViaSerialise
where
import qualified Codec.CBOR.Write as CBOR.Write
import Codec.Serialise (Serialise, decode, deserialiseOrFail, encode)
import qualified Data.Aeson as Aeson
import Data.ByteString.Base16.Aeson as Base16.Aeson
import qualified Data.ByteString.Lazy as BSL
newtype ViaSerialise a = ViaSerialise a
unViaSerialise (ViaSerialise a) = a
instance Serialise a => Aeson.ToJSON (ViaSerialise a) where
toJSON (ViaSerialise a) = Base16.Aeson.byteStringToJSON . CBOR.Write.toStrictByteString . encode $ a
instance Serialise a => Aeson.FromJSON (ViaSerialise a) where
parseJSON v = ViaSerialise <$> do
EncodeBase16 bs <- Aeson.parseJSON v
case deserialiseOrFail . BSL.fromStrict $ bs of
Left err -> fail (show err)
Right res -> pure res
encodeToJSON :: Serialise a => a -> Aeson.Value
encodeToJSON a = Aeson.toJSON (ViaSerialise a)
decodeToJSON :: Serialise a => Aeson.Value -> Aeson.Result a
decodeToJSON v = unViaSerialise <$> Aeson.fromJSON v
| |
c36629d7d84560b94091c8248e186b65913166d8840943361c64b1856313b321 | lambduli/minilog | Token.hs | module Token where
data Token = Atom String
| Var String
| If
| Comma
| Period
| Paren'Open
| Paren'Close
| Underscore
| Equal
| EOF
deriving (Eq, Show)
| null | https://raw.githubusercontent.com/lambduli/minilog/a1b9d7fabba0b38db4707295fe6ca3efa6785c57/src/Token.hs | haskell | module Token where
data Token = Atom String
| Var String
| If
| Comma
| Period
| Paren'Open
| Paren'Close
| Underscore
| Equal
| EOF
deriving (Eq, Show)
| |
168857a6d7dbf3a5c518970cbaa7475f5a1cb5a95d907a1c65d2edbd47c1536f | input-output-hk/cardano-base | Vectors.hs | # LANGUAGE FlexibleContexts #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module Test.Crypto.Vector.Vectors
( defaultSKey,
defaultMessage,
signAndVerifyTestVectors,
wrongEcdsaVerKeyTestVector,
wrongSchnorrVerKeyTestVector,
wrongLengthMessageHashTestVectors,
ecdsaVerKeyAndSigVerifyTestVectors,
schnorrVerKeyAndSigVerifyTestVectors,
ecdsaMismatchMessageAndSignature,
schnorrMismatchMessageAndSignature,
verKeyNotOnCurveTestVectorRaw,
wrongLengthVerKeyTestVectorsRaw,
ecdsaWrongLengthSigTestVectorsRaw,
schnorrWrongLengthSigTestVectorsRaw,
ecdsaNegSigTestVectors,
)
where
import Cardano.Binary (FromCBOR)
import Cardano.Crypto.DSIGN
( DSIGNAlgorithm (SigDSIGN, SignKeyDSIGN, VerKeyDSIGN),
EcdsaSecp256k1DSIGN,
SchnorrSecp256k1DSIGN,
)
import Data.ByteString (ByteString)
import Test.Crypto.Vector.SerializationUtils
( HexStringInCBOR (..),
sKeyParser,
sigParser,
vKeyParser,
)
defaultSKey :: forall d. (FromCBOR (SignKeyDSIGN d)) => SignKeyDSIGN d
defaultSKey = sKeyParser "B7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF"
defaultMessage :: ByteString
defaultMessage = "243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"
These vectors contains secret key which first signs the given message and verifies using generated signature and derived vKey
signAndVerifyTestVectors :: forall d. (FromCBOR (SignKeyDSIGN d)) => [(SignKeyDSIGN d, ByteString)]
signAndVerifyTestVectors =
map
(\(sk, m) -> (sKeyParser sk, m))
[ ( "0000000000000000000000000000000000000000000000000000000000000003",
"0000000000000000000000000000000000000000000000000000000000000000"
),
( "B7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF",
"243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"
),
( "C90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B14E5C9",
"7E2D58D8B3BCDF1ABADEC7829054F90DDA9805AAB56C77333024B9D0A508B75C"
),
( "0B432B2677937381AEF05BB02A66ECD012773062CF3FA2549E44F58ED2401710",
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
)
]
It is used for testing already given message , signature and vKey so that should be sucessful without needing secret key to sign the message for ecdsa .
ecdsaVerKeyAndSigVerifyTestVectors :: (VerKeyDSIGN EcdsaSecp256k1DSIGN, ByteString, SigDSIGN EcdsaSecp256k1DSIGN)
ecdsaVerKeyAndSigVerifyTestVectors =
( vKeyParser "02599de3e582e2a3779208a210dfeae8f330b9af00a47a7fb22e9bb8ef596f301b",
"0000000000000000000000000000000000000000000000000000000000000000",
sigParser "354b868c757ef0b796003f7c23dd754d2d1726629145be2c7b7794a25fec80a06254f0915935f33b91bceb16d46ff2814f659e9b6791a4a21ff8764b78d7e114"
)
ecdsaNegSigTestVectors :: (VerKeyDSIGN EcdsaSecp256k1DSIGN, ByteString, SigDSIGN EcdsaSecp256k1DSIGN)
ecdsaNegSigTestVectors =
( vKeyParser "02599de3e582e2a3779208a210dfeae8f330b9af00a47a7fb22e9bb8ef596f301b",
"0000000000000000000000000000000000000000000000000000000000000000",
sigParser "354b868c757ef0b796003f7c23dd754d2d1726629145be2c7b7794a25fec80a09dab0f6ea6ca0cc46e4314e92b900d7d6b493e4b47b6fb999fd9e841575e602d"
)
It is used for testing already given message , signature and vKey so that should be sucessful without needing secret key to sign the message for .
schnorrVerKeyAndSigVerifyTestVectors :: (VerKeyDSIGN SchnorrSecp256k1DSIGN, ByteString, SigDSIGN SchnorrSecp256k1DSIGN)
schnorrVerKeyAndSigVerifyTestVectors =
( vKeyParser "599de3e582e2a3779208a210dfeae8f330b9af00a47a7fb22e9bb8ef596f301b",
"0000000000000000000000000000000000000000000000000000000000000000",
sigParser "5a56da88e6fd8419181dec4d3dd6997bab953d2fc71ab65e23cfc9e7e3d1a310613454a60f6703819a39fdac2a410a094442afd1fc083354443e8d8bb4461a9b"
)
-- Wrong length message hash are used to test ecdsa toMessageHash function
wrongLengthMessageHashTestVectors :: [ByteString]
wrongLengthMessageHashTestVectors =
[ "0",
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE"
]
wrongEcdsaVerKeyTestVector :: VerKeyDSIGN EcdsaSecp256k1DSIGN
wrongEcdsaVerKeyTestVector = vKeyParser "02D69C3509BB99E412E68B0FE8544E72837DFA30746D8BE2AA65975F29D22DC7B9"
wrongSchnorrVerKeyTestVector :: VerKeyDSIGN SchnorrSecp256k1DSIGN
wrongSchnorrVerKeyTestVector = vKeyParser "D69C3509BB99E412E68B0FE8544E72837DFA30746D8BE2AA65975F29D22DC7B9"
-- Raw string verification key that is not on the curve should result in ver key parse failed
verKeyNotOnCurveTestVectorRaw :: HexStringInCBOR
verKeyNotOnCurveTestVectorRaw = "02EEFDEA4CDB677750A420FEE807EACF21EB9898AE79B9768766E4FAA04A2D4A34"
Parse these vectors and expect the errors on tests with parity bit
wrongLengthVerKeyTestVectorsRaw :: [HexStringInCBOR]
wrongLengthVerKeyTestVectorsRaw =
Ver key of length 30 bytes
"02DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B50",
Ver key of length 34 bytes
"02DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659FF"
]
Raw hexstring to be used in invalid length signature parser tests for ecdsa
ecdsaWrongLengthSigTestVectorsRaw :: [HexStringInCBOR]
ecdsaWrongLengthSigTestVectorsRaw =
[ "354b868c757ef0b796003f7c23dd754d2d1726629145be2c7b7794a25fec80a06254f0915935f33b91bceb16d46ff2814f659e9b6791a4a21ff8764b78d7e1",
"354b868c757ef0b796003f7c23dd754d2d1726629145be2c7b7794a25fec80a06254f0915935f33b91bceb16d46ff2814f659e9b6791a4a21ff8764b78d7e114FF"
]
Raw hexstring to be used in invalid length signature parser tests for schnorr
schnorrWrongLengthSigTestVectorsRaw :: [HexStringInCBOR]
schnorrWrongLengthSigTestVectorsRaw =
[ "5a56da88e6fd8419181dec4d3dd6997bab953d2fc71ab65e23cfc9e7e3d1a310613454a60f6703819a39fdac2a410a094442afd1fc083354443e8d8bb4461a",
"5a56da88e6fd8419181dec4d3dd6997bab953d2fc71ab65e23cfc9e7e3d1a310613454a60f6703819a39fdac2a410a094442afd1fc083354443e8d8bb4461a9bFF"
]
ecdsaMismatchMessageAndSignature :: [(ByteString, VerKeyDSIGN EcdsaSecp256k1DSIGN, SigDSIGN EcdsaSecp256k1DSIGN)]
ecdsaMismatchMessageAndSignature =
map
(\(vm, vKey, sig) -> (vm, vKeyParser vKey, sigParser sig))
verifyMessage , vKey , signature
[ ( "243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89",
"0325d1dff95105f5253c4022f628a996ad3a0d95fbf21d468a1b33f8c160d8f517",
"3dccc57be49991e95b112954217e8b4fe884d4d26843dfec794feb370981407b79151d1e5af85aba21721876896957adb2b35bcbb84986dcf82daa520a87a9f9" -- wrong verify message but right signature
),
( "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
"0325d1dff95105f5253c4022f628a996ad3a0d95fbf21d468a1b33f8c160d8f517",
"5ef63d477c5d1572550016ccf72a2310c7368beeb843c85b1b5697290872222a09e7519702cb2c9a65bbce92d273080a0193b77588bc2eac6dbcbfc15c6dfefd" -- right verify message but wrong signature
)
]
schnorrMismatchMessageAndSignature :: [(ByteString, VerKeyDSIGN SchnorrSecp256k1DSIGN, SigDSIGN SchnorrSecp256k1DSIGN)]
schnorrMismatchMessageAndSignature =
map
(\(vm, vKey, sig) -> (vm, vKeyParser vKey, sigParser sig))
verifyMessage , vKey , signature
[ ( "243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89",
"599de3e582e2a3779208a210dfeae8f330b9af00a47a7fb22e9bb8ef596f301b",
"5a56da88e6fd8419181dec4d3dd6997bab953d2fc71ab65e23cfc9e7e3d1a310613454a60f6703819a39fdac2a410a094442afd1fc083354443e8d8bb4461a9b" -- wrong verify message but right signature
),
( "0000000000000000000000000000000000000000000000000000000000000000",
"599de3e582e2a3779208a210dfeae8f330b9af00a47a7fb22e9bb8ef596f301b",
"18a66fb829009a9df6312e1d7f4b53af0ac8a6aa17c2b7ff5941b57a27b24c23531f01bd11135dd844318f814241ea41040cc68958a6c47da489a32f0e22b805" -- right verify message but wrong signature
)
]
| null | https://raw.githubusercontent.com/input-output-hk/cardano-base/b403b76ba1f70df1a6c9f861591d9e2a332abb13/cardano-crypto-tests/src/Test/Crypto/Vector/Vectors.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
Wrong length message hash are used to test ecdsa toMessageHash function
Raw string verification key that is not on the curve should result in ver key parse failed
wrong verify message but right signature
right verify message but wrong signature
wrong verify message but right signature
right verify message but wrong signature | # LANGUAGE FlexibleContexts #
module Test.Crypto.Vector.Vectors
( defaultSKey,
defaultMessage,
signAndVerifyTestVectors,
wrongEcdsaVerKeyTestVector,
wrongSchnorrVerKeyTestVector,
wrongLengthMessageHashTestVectors,
ecdsaVerKeyAndSigVerifyTestVectors,
schnorrVerKeyAndSigVerifyTestVectors,
ecdsaMismatchMessageAndSignature,
schnorrMismatchMessageAndSignature,
verKeyNotOnCurveTestVectorRaw,
wrongLengthVerKeyTestVectorsRaw,
ecdsaWrongLengthSigTestVectorsRaw,
schnorrWrongLengthSigTestVectorsRaw,
ecdsaNegSigTestVectors,
)
where
import Cardano.Binary (FromCBOR)
import Cardano.Crypto.DSIGN
( DSIGNAlgorithm (SigDSIGN, SignKeyDSIGN, VerKeyDSIGN),
EcdsaSecp256k1DSIGN,
SchnorrSecp256k1DSIGN,
)
import Data.ByteString (ByteString)
import Test.Crypto.Vector.SerializationUtils
( HexStringInCBOR (..),
sKeyParser,
sigParser,
vKeyParser,
)
defaultSKey :: forall d. (FromCBOR (SignKeyDSIGN d)) => SignKeyDSIGN d
defaultSKey = sKeyParser "B7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF"
defaultMessage :: ByteString
defaultMessage = "243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"
These vectors contains secret key which first signs the given message and verifies using generated signature and derived vKey
signAndVerifyTestVectors :: forall d. (FromCBOR (SignKeyDSIGN d)) => [(SignKeyDSIGN d, ByteString)]
signAndVerifyTestVectors =
map
(\(sk, m) -> (sKeyParser sk, m))
[ ( "0000000000000000000000000000000000000000000000000000000000000003",
"0000000000000000000000000000000000000000000000000000000000000000"
),
( "B7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF",
"243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"
),
( "C90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B14E5C9",
"7E2D58D8B3BCDF1ABADEC7829054F90DDA9805AAB56C77333024B9D0A508B75C"
),
( "0B432B2677937381AEF05BB02A66ECD012773062CF3FA2549E44F58ED2401710",
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
)
]
It is used for testing already given message , signature and vKey so that should be sucessful without needing secret key to sign the message for ecdsa .
ecdsaVerKeyAndSigVerifyTestVectors :: (VerKeyDSIGN EcdsaSecp256k1DSIGN, ByteString, SigDSIGN EcdsaSecp256k1DSIGN)
ecdsaVerKeyAndSigVerifyTestVectors =
( vKeyParser "02599de3e582e2a3779208a210dfeae8f330b9af00a47a7fb22e9bb8ef596f301b",
"0000000000000000000000000000000000000000000000000000000000000000",
sigParser "354b868c757ef0b796003f7c23dd754d2d1726629145be2c7b7794a25fec80a06254f0915935f33b91bceb16d46ff2814f659e9b6791a4a21ff8764b78d7e114"
)
ecdsaNegSigTestVectors :: (VerKeyDSIGN EcdsaSecp256k1DSIGN, ByteString, SigDSIGN EcdsaSecp256k1DSIGN)
ecdsaNegSigTestVectors =
( vKeyParser "02599de3e582e2a3779208a210dfeae8f330b9af00a47a7fb22e9bb8ef596f301b",
"0000000000000000000000000000000000000000000000000000000000000000",
sigParser "354b868c757ef0b796003f7c23dd754d2d1726629145be2c7b7794a25fec80a09dab0f6ea6ca0cc46e4314e92b900d7d6b493e4b47b6fb999fd9e841575e602d"
)
It is used for testing already given message , signature and vKey so that should be sucessful without needing secret key to sign the message for .
schnorrVerKeyAndSigVerifyTestVectors :: (VerKeyDSIGN SchnorrSecp256k1DSIGN, ByteString, SigDSIGN SchnorrSecp256k1DSIGN)
schnorrVerKeyAndSigVerifyTestVectors =
( vKeyParser "599de3e582e2a3779208a210dfeae8f330b9af00a47a7fb22e9bb8ef596f301b",
"0000000000000000000000000000000000000000000000000000000000000000",
sigParser "5a56da88e6fd8419181dec4d3dd6997bab953d2fc71ab65e23cfc9e7e3d1a310613454a60f6703819a39fdac2a410a094442afd1fc083354443e8d8bb4461a9b"
)
wrongLengthMessageHashTestVectors :: [ByteString]
wrongLengthMessageHashTestVectors =
[ "0",
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE"
]
wrongEcdsaVerKeyTestVector :: VerKeyDSIGN EcdsaSecp256k1DSIGN
wrongEcdsaVerKeyTestVector = vKeyParser "02D69C3509BB99E412E68B0FE8544E72837DFA30746D8BE2AA65975F29D22DC7B9"
wrongSchnorrVerKeyTestVector :: VerKeyDSIGN SchnorrSecp256k1DSIGN
wrongSchnorrVerKeyTestVector = vKeyParser "D69C3509BB99E412E68B0FE8544E72837DFA30746D8BE2AA65975F29D22DC7B9"
verKeyNotOnCurveTestVectorRaw :: HexStringInCBOR
verKeyNotOnCurveTestVectorRaw = "02EEFDEA4CDB677750A420FEE807EACF21EB9898AE79B9768766E4FAA04A2D4A34"
Parse these vectors and expect the errors on tests with parity bit
wrongLengthVerKeyTestVectorsRaw :: [HexStringInCBOR]
wrongLengthVerKeyTestVectorsRaw =
Ver key of length 30 bytes
"02DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B50",
Ver key of length 34 bytes
"02DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659FF"
]
Raw hexstring to be used in invalid length signature parser tests for ecdsa
ecdsaWrongLengthSigTestVectorsRaw :: [HexStringInCBOR]
ecdsaWrongLengthSigTestVectorsRaw =
[ "354b868c757ef0b796003f7c23dd754d2d1726629145be2c7b7794a25fec80a06254f0915935f33b91bceb16d46ff2814f659e9b6791a4a21ff8764b78d7e1",
"354b868c757ef0b796003f7c23dd754d2d1726629145be2c7b7794a25fec80a06254f0915935f33b91bceb16d46ff2814f659e9b6791a4a21ff8764b78d7e114FF"
]
Raw hexstring to be used in invalid length signature parser tests for schnorr
schnorrWrongLengthSigTestVectorsRaw :: [HexStringInCBOR]
schnorrWrongLengthSigTestVectorsRaw =
[ "5a56da88e6fd8419181dec4d3dd6997bab953d2fc71ab65e23cfc9e7e3d1a310613454a60f6703819a39fdac2a410a094442afd1fc083354443e8d8bb4461a",
"5a56da88e6fd8419181dec4d3dd6997bab953d2fc71ab65e23cfc9e7e3d1a310613454a60f6703819a39fdac2a410a094442afd1fc083354443e8d8bb4461a9bFF"
]
ecdsaMismatchMessageAndSignature :: [(ByteString, VerKeyDSIGN EcdsaSecp256k1DSIGN, SigDSIGN EcdsaSecp256k1DSIGN)]
ecdsaMismatchMessageAndSignature =
map
(\(vm, vKey, sig) -> (vm, vKeyParser vKey, sigParser sig))
verifyMessage , vKey , signature
[ ( "243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89",
"0325d1dff95105f5253c4022f628a996ad3a0d95fbf21d468a1b33f8c160d8f517",
),
( "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
"0325d1dff95105f5253c4022f628a996ad3a0d95fbf21d468a1b33f8c160d8f517",
)
]
schnorrMismatchMessageAndSignature :: [(ByteString, VerKeyDSIGN SchnorrSecp256k1DSIGN, SigDSIGN SchnorrSecp256k1DSIGN)]
schnorrMismatchMessageAndSignature =
map
(\(vm, vKey, sig) -> (vm, vKeyParser vKey, sigParser sig))
verifyMessage , vKey , signature
[ ( "243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89",
"599de3e582e2a3779208a210dfeae8f330b9af00a47a7fb22e9bb8ef596f301b",
),
( "0000000000000000000000000000000000000000000000000000000000000000",
"599de3e582e2a3779208a210dfeae8f330b9af00a47a7fb22e9bb8ef596f301b",
)
]
|
9e705531192cbbc29df5a6d6e93895e5a033a187c6d63d1f036638cdad3eb47a | Helium4Haskell/Top | Classes.hs | -----------------------------------------------------------------------------
-- | License : GPL
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- Type classes and the standard reduction instances. A part of the code
was taken from the paper " Typing Haskell in Haskell " .
--
-----------------------------------------------------------------------------
module Top.Types.Classes where
import Top.Types.Primitive
import Top.Types.Substitution
import Top.Types.Unification
import Top.Types.Synonym
import Top.Types.Qualification
import Control.Monad
import qualified Data.Map as M
----------------------------------------------------------------------
-- * Class predicates
type Predicates = [Predicate]
data Predicate = Predicate String Tp deriving Eq
instance Show Predicate where
show (Predicate s tp) = if priorityOfType tp == 2
then s ++ " " ++ show tp
else s ++ " (" ++ show tp ++ ")"
instance Substitutable Predicate where
sub |-> (Predicate s tp) = Predicate s (sub |-> tp)
ftv (Predicate _ tp) = ftv tp
instance HasTypes Predicate where
getTypes (Predicate _ tp) = [tp]
changeTypes f (Predicate s tp) = Predicate s (f tp)
instance ShowQualifiers Predicate
----------------------------------------------------------------------
-- * Class environments and instances
type ClassEnvironment = M.Map String Class
-- | (Superclasses, Instances)
type Class = ([String], Instances)
type Instances = [Instance]
type Instance = (Predicate, Predicates)
-- |The empty class environment
emptyClassEnvironment :: ClassEnvironment
emptyClassEnvironment = M.empty
matchPredicates :: OrderedTypeSynonyms -> Predicate -> Predicate -> Maybe MapSubstitution
matchPredicates synonyms (Predicate s1 t1) (Predicate s2 t2)
| s1 == s2 = case mguWithTypeSynonyms synonyms (freezeVariablesInType t1) t2 of
Left _ -> Nothing
Right (_, s) -> Just (M.map unfreezeVariablesInType s)
| otherwise = Nothing
insertInstance :: String -> Instance -> ClassEnvironment -> ClassEnvironment
insertInstance className inst env =
case M.lookup className env of
Nothing -> M.insert className ([], [inst]) env
Just (parents, insts) -> M.insert className (parents, inst:insts) env
----------------------------------------------------------------------
-- * Class environment
inClassEnvironment :: String -> ClassEnvironment -> Bool
inClassEnvironment = M.member
superclassPaths :: String -> String -> ClassEnvironment -> [[String]]
superclassPaths from to cs
| from == to = [[to]]
| otherwise = [ from : path | sc <- superclasses from cs, path <- superclassPaths sc to cs ]
|For example , is a superclass of Ord
superclasses :: String -> ClassEnvironment -> [String]
superclasses s cs = maybe [] fst (M.lookup s cs)
instances :: String -> ClassEnvironment -> Instances
instances s cs = maybe [] snd (M.lookup s cs)
----------------------------------------------------------------------
-- * Head normal form
inHeadNormalForm :: Predicate -> Bool
inHeadNormalForm (Predicate _ tp) = hnf tp
where hnf (TVar _) = True
hnf (TCon _) = False
hnf (TApp t _) = hnf t
listToHeadNormalForm :: OrderedTypeSynonyms -> ClassEnvironment -> Predicates -> Maybe Predicates
listToHeadNormalForm synonyms classes ps =
do pss <- mapM (toHeadNormalForm synonyms classes) ps
return (concat pss)
toHeadNormalForm :: OrderedTypeSynonyms -> ClassEnvironment -> Predicate -> Maybe Predicates
toHeadNormalForm synonyms classes p
| inHeadNormalForm p = Just [p]
| otherwise = do ps <- byInstance synonyms classes p
listToHeadNormalForm synonyms classes ps
----------------------------------------------------------------------
-- * Entailment
bySuperclass :: ClassEnvironment -> Predicate -> Predicates
bySuperclass classes p@(Predicate s tp) =
p : concat [ bySuperclass classes (Predicate s' tp) | s' <- superclasses s classes ]
byInstance :: OrderedTypeSynonyms -> ClassEnvironment -> Predicate -> Maybe Predicates
byInstance synonyms classes p@(Predicate s _) =
let tryInstance (p',list) = do sub <- matchPredicates synonyms p p'
Just (sub |-> list)
in msum [ tryInstance it | it <- instances s classes ]
entail :: OrderedTypeSynonyms -> ClassEnvironment -> Predicates -> Predicate -> Bool
entail synonyms classes ps p =
scEntail classes ps p ||
case byInstance synonyms classes p of
Nothing -> False
Just qs -> all (entail synonyms classes ps) qs
entailList :: OrderedTypeSynonyms -> ClassEnvironment -> Predicates -> Predicates -> Bool
entailList synonyms classes ps = all (entail synonyms classes ps)
scEntail :: ClassEnvironment -> Predicates -> Predicate -> Bool
scEntail classes ps p = any (p `elem`) (map (bySuperclass classes) ps)
----------------------------------------------------------------------
-- * Context reduction
newtype ReductionError a = ReductionError a
deriving Show
contextReduction :: OrderedTypeSynonyms -> ClassEnvironment -> Predicates ->
(Predicates, [ReductionError Predicate])
contextReduction synonyms classes ps =
let op p (a,b) = case toHeadNormalForm synonyms classes p of
Just qs -> (qs++a,b)
Nothing -> (a,ReductionError p : b)
(predicates, errors) = foldr op ([], []) ps
loop rs [] = rs
loop rs (x:xs) | scEntail classes (rs++xs) x = loop rs xs
| otherwise = loop (x:rs) xs
in (loop [] predicates, errors)
associatedContextReduction :: OrderedTypeSynonyms -> ClassEnvironment -> [(Predicate, a)] ->
([(Predicate,a)], [ReductionError (Predicate, a)])
associatedContextReduction synonyms classes ps =
let op (predicate, a) (reduced, es) =
case toHeadNormalForm synonyms classes predicate of
Just qs -> ([(p,a) | p <- qs]++reduced,es)
Nothing -> (reduced,ReductionError (predicate, a) : es)
(predicates, errors) = foldr op ([], []) ps
loop rs [] = rs
loop rs (q:qs) | entailed = loop rs qs
| otherwise = loop (q:rs) qs
where entailed = scEntail classes (map fst (rs++qs)) (fst q)
in (loop [] predicates, errors)
| null | https://raw.githubusercontent.com/Helium4Haskell/Top/5e900184d6b2ab6d7ce69945287d782252e5ea68/src/Top/Types/Classes.hs | haskell | ---------------------------------------------------------------------------
| License : GPL
Maintainer :
Stability : provisional
Portability : portable
Type classes and the standard reduction instances. A part of the code
---------------------------------------------------------------------------
--------------------------------------------------------------------
* Class predicates
--------------------------------------------------------------------
* Class environments and instances
| (Superclasses, Instances)
|The empty class environment
--------------------------------------------------------------------
* Class environment
--------------------------------------------------------------------
* Head normal form
--------------------------------------------------------------------
* Entailment
--------------------------------------------------------------------
* Context reduction | was taken from the paper " Typing Haskell in Haskell " .
module Top.Types.Classes where
import Top.Types.Primitive
import Top.Types.Substitution
import Top.Types.Unification
import Top.Types.Synonym
import Top.Types.Qualification
import Control.Monad
import qualified Data.Map as M
type Predicates = [Predicate]
data Predicate = Predicate String Tp deriving Eq
instance Show Predicate where
show (Predicate s tp) = if priorityOfType tp == 2
then s ++ " " ++ show tp
else s ++ " (" ++ show tp ++ ")"
instance Substitutable Predicate where
sub |-> (Predicate s tp) = Predicate s (sub |-> tp)
ftv (Predicate _ tp) = ftv tp
instance HasTypes Predicate where
getTypes (Predicate _ tp) = [tp]
changeTypes f (Predicate s tp) = Predicate s (f tp)
instance ShowQualifiers Predicate
type ClassEnvironment = M.Map String Class
type Class = ([String], Instances)
type Instances = [Instance]
type Instance = (Predicate, Predicates)
emptyClassEnvironment :: ClassEnvironment
emptyClassEnvironment = M.empty
matchPredicates :: OrderedTypeSynonyms -> Predicate -> Predicate -> Maybe MapSubstitution
matchPredicates synonyms (Predicate s1 t1) (Predicate s2 t2)
| s1 == s2 = case mguWithTypeSynonyms synonyms (freezeVariablesInType t1) t2 of
Left _ -> Nothing
Right (_, s) -> Just (M.map unfreezeVariablesInType s)
| otherwise = Nothing
insertInstance :: String -> Instance -> ClassEnvironment -> ClassEnvironment
insertInstance className inst env =
case M.lookup className env of
Nothing -> M.insert className ([], [inst]) env
Just (parents, insts) -> M.insert className (parents, inst:insts) env
inClassEnvironment :: String -> ClassEnvironment -> Bool
inClassEnvironment = M.member
superclassPaths :: String -> String -> ClassEnvironment -> [[String]]
superclassPaths from to cs
| from == to = [[to]]
| otherwise = [ from : path | sc <- superclasses from cs, path <- superclassPaths sc to cs ]
|For example , is a superclass of Ord
superclasses :: String -> ClassEnvironment -> [String]
superclasses s cs = maybe [] fst (M.lookup s cs)
instances :: String -> ClassEnvironment -> Instances
instances s cs = maybe [] snd (M.lookup s cs)
inHeadNormalForm :: Predicate -> Bool
inHeadNormalForm (Predicate _ tp) = hnf tp
where hnf (TVar _) = True
hnf (TCon _) = False
hnf (TApp t _) = hnf t
listToHeadNormalForm :: OrderedTypeSynonyms -> ClassEnvironment -> Predicates -> Maybe Predicates
listToHeadNormalForm synonyms classes ps =
do pss <- mapM (toHeadNormalForm synonyms classes) ps
return (concat pss)
toHeadNormalForm :: OrderedTypeSynonyms -> ClassEnvironment -> Predicate -> Maybe Predicates
toHeadNormalForm synonyms classes p
| inHeadNormalForm p = Just [p]
| otherwise = do ps <- byInstance synonyms classes p
listToHeadNormalForm synonyms classes ps
bySuperclass :: ClassEnvironment -> Predicate -> Predicates
bySuperclass classes p@(Predicate s tp) =
p : concat [ bySuperclass classes (Predicate s' tp) | s' <- superclasses s classes ]
byInstance :: OrderedTypeSynonyms -> ClassEnvironment -> Predicate -> Maybe Predicates
byInstance synonyms classes p@(Predicate s _) =
let tryInstance (p',list) = do sub <- matchPredicates synonyms p p'
Just (sub |-> list)
in msum [ tryInstance it | it <- instances s classes ]
entail :: OrderedTypeSynonyms -> ClassEnvironment -> Predicates -> Predicate -> Bool
entail synonyms classes ps p =
scEntail classes ps p ||
case byInstance synonyms classes p of
Nothing -> False
Just qs -> all (entail synonyms classes ps) qs
entailList :: OrderedTypeSynonyms -> ClassEnvironment -> Predicates -> Predicates -> Bool
entailList synonyms classes ps = all (entail synonyms classes ps)
scEntail :: ClassEnvironment -> Predicates -> Predicate -> Bool
scEntail classes ps p = any (p `elem`) (map (bySuperclass classes) ps)
newtype ReductionError a = ReductionError a
deriving Show
contextReduction :: OrderedTypeSynonyms -> ClassEnvironment -> Predicates ->
(Predicates, [ReductionError Predicate])
contextReduction synonyms classes ps =
let op p (a,b) = case toHeadNormalForm synonyms classes p of
Just qs -> (qs++a,b)
Nothing -> (a,ReductionError p : b)
(predicates, errors) = foldr op ([], []) ps
loop rs [] = rs
loop rs (x:xs) | scEntail classes (rs++xs) x = loop rs xs
| otherwise = loop (x:rs) xs
in (loop [] predicates, errors)
associatedContextReduction :: OrderedTypeSynonyms -> ClassEnvironment -> [(Predicate, a)] ->
([(Predicate,a)], [ReductionError (Predicate, a)])
associatedContextReduction synonyms classes ps =
let op (predicate, a) (reduced, es) =
case toHeadNormalForm synonyms classes predicate of
Just qs -> ([(p,a) | p <- qs]++reduced,es)
Nothing -> (reduced,ReductionError (predicate, a) : es)
(predicates, errors) = foldr op ([], []) ps
loop rs [] = rs
loop rs (q:qs) | entailed = loop rs qs
| otherwise = loop (q:rs) qs
where entailed = scEntail classes (map fst (rs++qs)) (fst q)
in (loop [] predicates, errors)
|
a447770b8bd4e83d540c1eb0ee77d6cae2eac60206692de07781203b495cb184 | nuttycom/aftok | PaymentsSpec.hs | {-# OPTIONS_GHC -Wwarn -fno-warn-orphans #-}
module Aftok.PaymentsSpec
( main,
spec,
)
where
import Test.Hspec
spec :: Spec
spec = do
describe "finding unbilled dates" $ do
pure ()
--it "returns the billing date in the presence of an expired payment request" $
-- forAll ((,) <$> genSatoshi <*> listOf genBid) $
-- \(raiseAmount', bids) ->
case ' raiseAmount ' bids of
-- WinningBids xs -> bidsTotal xs == raiseAmount'
InsufficientBids t - > t = = ( raiseAmount ' - bidsTotal bids )
main :: IO ()
main = hspec spec
| null | https://raw.githubusercontent.com/nuttycom/aftok/54e7812859054a4b59fb802a1996ffb4de6c9bed/test/Aftok/PaymentsSpec.hs | haskell | # OPTIONS_GHC -Wwarn -fno-warn-orphans #
it "returns the billing date in the presence of an expired payment request" $
forAll ((,) <$> genSatoshi <*> listOf genBid) $
\(raiseAmount', bids) ->
WinningBids xs -> bidsTotal xs == raiseAmount' |
module Aftok.PaymentsSpec
( main,
spec,
)
where
import Test.Hspec
spec :: Spec
spec = do
describe "finding unbilled dates" $ do
pure ()
case ' raiseAmount ' bids of
InsufficientBids t - > t = = ( raiseAmount ' - bidsTotal bids )
main :: IO ()
main = hspec spec
|
69299ad023d3d326afcca0c69de01706801fde495d3a8add4dad55551db71cc4 | rafaeldelboni/nota | pagination.cljs | (ns nota.ui.posts.pagination
(:require [com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.data-fetch :as df]
[com.fulcrologic.fulcro.dom :as dom]
[com.fulcrologic.fulcro.mutations :as m]
[com.fulcrologic.fulcro.routing.dynamic-routing :as dr]
[nota.ui.posts :as ui.posts]))
(def pagination-page-max-size 10)
(defn page-exists? [state-map page-number]
(let [page-items (get-in state-map [:pagination/by-number page-number :pagination/posts])]
(boolean (seq page-items))))
(defn clear-page
"Clear the given page (and associated items) from the app database."
[state-map page-number]
(let [page (get-in state-map [:pagination/by-number page-number])
item-idents (:pagination/posts page)
item-ids (map second item-idents)]
(as-> state-map s
(update s :pagination/by-number dissoc page-number)
(reduce (fn [acc id] (update acc :posts/by-id dissoc id)) s item-ids))))
(defn gc-distant-pages
"Clears loaded items from pages 5 or more steps away from the given page number."
[state-map page-number]
(reduce (fn [s n]
(if (< 4 (Math/abs (- page-number n)))
(clear-page s n)
s))
state-map
(keys (:pagination/by-number state-map))))
(defn init-page
"An idempotent init function that just ensures enough of a page exists to make the UI work.
Doesn't affect the items."
[state-map page-number]
(assoc-in state-map [:pagination/by-number page-number :pagination/number] page-number))
(defn set-current-page
"Point the current list's current page to the correct page entity in the db (via ident)."
[state-map page-number]
(assoc-in state-map [:posts/by-id 1 :posts/current-page] [:pagination/by-number page-number]))
(defn load-if-missing [{:keys [app state]} page-number]
(when-not (page-exists? @state page-number)
(let [page (dec page-number)]
(df/load! app :paginate/posts ui.posts/ListPost {:params {:page page :page-size pagination-page-max-size}
:marker :page
:target [:pagination/by-number page-number :pagination/posts]}))))
(m/defmutation goto-page [{:keys [page-number]}]
(action [{:keys [state] :as env}]
(load-if-missing env page-number)
(swap! state (fn [s]
(-> s
(init-page page-number)
(set-current-page page-number)
(gc-distant-pages page-number))))))
(defn initialize
"To be used as started-callback. Load the first page."
[{:keys [app]}]
(comp/transact! app [(goto-page {:page-number 1})]))
(defsc ListPaginationPosts [_this {:keys [pagination/posts] :as props}]
{:initial-state {:pagination/number 1 :pagination/posts []}
:query [:pagination/number {:pagination/posts (comp/get-query ui.posts/ListPost)}
[df/marker-table :pagination]]
:ident [:pagination/by-number :pagination/number]}
(let [status (get props [df/marker-table :pagination])]
(dom/div
(if (df/loading? status)
(dom/div "Loading...")
(dom/div (mapv ui.posts/ui-list-post posts))))))
(def ui-list-pagination-posts (comp/factory ListPaginationPosts {:keyfn :pagination/number}))
(defsc LargeListPosts [this {:keys [posts/current-page]}]
{:initial-state (fn [_] {:posts/current-page (comp/get-initial-state ListPaginationPosts {})})
:query [{:posts/current-page (comp/get-query ListPaginationPosts)}]
:ident (fn [] [:posts/by-id 1])}
(let [{:keys [pagination/number]} current-page]
(dom/div
(ui-list-pagination-posts current-page)
(dom/p
(when (not= 1 number)
(dom/button {:classes ["button" "button-clear"]
:disabled (= 1 number)
:onClick #(comp/transact! this [(goto-page {:page-number (dec number)})])}
"Recent posts"))
(when (= pagination-page-max-size (count (:pagination/posts current-page)))
(dom/button {:classes ["button" "button-clear"]
:disabled (not= pagination-page-max-size (count (:pagination/posts current-page)))
:onClick #(comp/transact! this [(goto-page {:page-number (inc number)})])}
"Older posts"))))))
(def ui-large-list-posts (comp/factory LargeListPosts))
(defsc PaginatedPosts [_this {:keys [pagination/list]}]
{:initial-state (fn [_] {:pagination/list (comp/get-initial-state LargeListPosts {})})
:query [{:pagination/list (comp/get-query LargeListPosts)}]
:ident (fn [] [:component/id :list-posts])
:route-segment ["posts" "list"]
:will-enter (fn [app _route-params]
(dr/route-deferred
[:component/id :list-posts]
#(do
(initialize {:app app})
(dr/target-ready! app [:component/id :list-posts]))))}
(dom/div
(ui-large-list-posts list)))
| null | https://raw.githubusercontent.com/rafaeldelboni/nota/9ef882bb493d1cec67b6232fd31d7dd69ff807b9/src/nota/ui/posts/pagination.cljs | clojure | (ns nota.ui.posts.pagination
(:require [com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.data-fetch :as df]
[com.fulcrologic.fulcro.dom :as dom]
[com.fulcrologic.fulcro.mutations :as m]
[com.fulcrologic.fulcro.routing.dynamic-routing :as dr]
[nota.ui.posts :as ui.posts]))
(def pagination-page-max-size 10)
(defn page-exists? [state-map page-number]
(let [page-items (get-in state-map [:pagination/by-number page-number :pagination/posts])]
(boolean (seq page-items))))
(defn clear-page
"Clear the given page (and associated items) from the app database."
[state-map page-number]
(let [page (get-in state-map [:pagination/by-number page-number])
item-idents (:pagination/posts page)
item-ids (map second item-idents)]
(as-> state-map s
(update s :pagination/by-number dissoc page-number)
(reduce (fn [acc id] (update acc :posts/by-id dissoc id)) s item-ids))))
(defn gc-distant-pages
"Clears loaded items from pages 5 or more steps away from the given page number."
[state-map page-number]
(reduce (fn [s n]
(if (< 4 (Math/abs (- page-number n)))
(clear-page s n)
s))
state-map
(keys (:pagination/by-number state-map))))
(defn init-page
"An idempotent init function that just ensures enough of a page exists to make the UI work.
Doesn't affect the items."
[state-map page-number]
(assoc-in state-map [:pagination/by-number page-number :pagination/number] page-number))
(defn set-current-page
"Point the current list's current page to the correct page entity in the db (via ident)."
[state-map page-number]
(assoc-in state-map [:posts/by-id 1 :posts/current-page] [:pagination/by-number page-number]))
(defn load-if-missing [{:keys [app state]} page-number]
(when-not (page-exists? @state page-number)
(let [page (dec page-number)]
(df/load! app :paginate/posts ui.posts/ListPost {:params {:page page :page-size pagination-page-max-size}
:marker :page
:target [:pagination/by-number page-number :pagination/posts]}))))
(m/defmutation goto-page [{:keys [page-number]}]
(action [{:keys [state] :as env}]
(load-if-missing env page-number)
(swap! state (fn [s]
(-> s
(init-page page-number)
(set-current-page page-number)
(gc-distant-pages page-number))))))
(defn initialize
"To be used as started-callback. Load the first page."
[{:keys [app]}]
(comp/transact! app [(goto-page {:page-number 1})]))
(defsc ListPaginationPosts [_this {:keys [pagination/posts] :as props}]
{:initial-state {:pagination/number 1 :pagination/posts []}
:query [:pagination/number {:pagination/posts (comp/get-query ui.posts/ListPost)}
[df/marker-table :pagination]]
:ident [:pagination/by-number :pagination/number]}
(let [status (get props [df/marker-table :pagination])]
(dom/div
(if (df/loading? status)
(dom/div "Loading...")
(dom/div (mapv ui.posts/ui-list-post posts))))))
(def ui-list-pagination-posts (comp/factory ListPaginationPosts {:keyfn :pagination/number}))
(defsc LargeListPosts [this {:keys [posts/current-page]}]
{:initial-state (fn [_] {:posts/current-page (comp/get-initial-state ListPaginationPosts {})})
:query [{:posts/current-page (comp/get-query ListPaginationPosts)}]
:ident (fn [] [:posts/by-id 1])}
(let [{:keys [pagination/number]} current-page]
(dom/div
(ui-list-pagination-posts current-page)
(dom/p
(when (not= 1 number)
(dom/button {:classes ["button" "button-clear"]
:disabled (= 1 number)
:onClick #(comp/transact! this [(goto-page {:page-number (dec number)})])}
"Recent posts"))
(when (= pagination-page-max-size (count (:pagination/posts current-page)))
(dom/button {:classes ["button" "button-clear"]
:disabled (not= pagination-page-max-size (count (:pagination/posts current-page)))
:onClick #(comp/transact! this [(goto-page {:page-number (inc number)})])}
"Older posts"))))))
(def ui-large-list-posts (comp/factory LargeListPosts))
(defsc PaginatedPosts [_this {:keys [pagination/list]}]
{:initial-state (fn [_] {:pagination/list (comp/get-initial-state LargeListPosts {})})
:query [{:pagination/list (comp/get-query LargeListPosts)}]
:ident (fn [] [:component/id :list-posts])
:route-segment ["posts" "list"]
:will-enter (fn [app _route-params]
(dr/route-deferred
[:component/id :list-posts]
#(do
(initialize {:app app})
(dr/target-ready! app [:component/id :list-posts]))))}
(dom/div
(ui-large-list-posts list)))
| |
e421c91b064c581380da1b81a36d464667d59d223a129c6069d38c7c8dd3efa8 | input-output-hk/marlowe-cardano | Gen.hs | # OPTIONS_GHC -Wno - orphans #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
module Language.Marlowe.Runtime.Core.Gen
where
import Data.Foldable (Foldable(fold))
import qualified Language.Marlowe.Core.V1.Semantics as V1
import Language.Marlowe.Runtime.ChainSync.Gen ()
import Language.Marlowe.Runtime.Core.Api
import Language.Marlowe.Runtime.Plutus.V2.Api (toPlutusCurrencySymbol)
import Spec.Marlowe.Semantics.Arbitrary ()
import Test.QuickCheck hiding (shrinkMap)
import Test.QuickCheck.Instances ()
instance Arbitrary ContractId where
arbitrary = ContractId <$> arbitrary
instance Arbitrary SomeMarloweVersion where
arbitrary = pure $ SomeMarloweVersion MarloweV1
class
( Arbitrary (Contract v)
, Arbitrary (Datum v)
, Arbitrary (Inputs v)
, Arbitrary (PayoutDatum v)
, IsMarloweVersion v
) => ArbitraryMarloweVersion v
instance ArbitraryMarloweVersion 'V1
instance ArbitraryMarloweVersion v => Arbitrary (Transaction v) where
arbitrary = Transaction
<$> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
instance Arbitrary V1.MarloweParams where
arbitrary = V1.MarloweParams . toPlutusCurrencySymbol <$> arbitrary
instance Arbitrary V1.MarloweData where
arbitrary = V1.MarloweData <$> arbitrary <*> arbitrary <*> arbitrary
shrink = genericShrink
instance ArbitraryMarloweVersion v => Arbitrary (TransactionOutput v) where
arbitrary = TransactionOutput <$> arbitrary <*> arbitrary
shrink = genericShrink
instance ArbitraryMarloweVersion v => Arbitrary (Payout v) where
arbitrary = Payout <$> arbitrary <*> arbitrary <*> arbitrary
shrink (Payout address assets datum) = fold
[ [ Payout address assets' datum | assets' <- shrink assets ]
, [ Payout address assets datum' | datum' <- shrink datum ]
]
instance ArbitraryMarloweVersion v => Arbitrary (TransactionScriptOutput v) where
arbitrary = TransactionScriptOutput <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
shrink (TransactionScriptOutput address assets utxo datum) = fold
[ [ TransactionScriptOutput address assets' utxo datum | assets' <- shrink assets ]
, [ TransactionScriptOutput address assets utxo datum' | datum' <- shrink datum ]
]
| null | https://raw.githubusercontent.com/input-output-hk/marlowe-cardano/3d7d6381baca1b827ffaa519f130c5ad17a5f318/marlowe-runtime/gen/Language/Marlowe/Runtime/Core/Gen.hs | haskell | # OPTIONS_GHC -Wno - orphans #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
module Language.Marlowe.Runtime.Core.Gen
where
import Data.Foldable (Foldable(fold))
import qualified Language.Marlowe.Core.V1.Semantics as V1
import Language.Marlowe.Runtime.ChainSync.Gen ()
import Language.Marlowe.Runtime.Core.Api
import Language.Marlowe.Runtime.Plutus.V2.Api (toPlutusCurrencySymbol)
import Spec.Marlowe.Semantics.Arbitrary ()
import Test.QuickCheck hiding (shrinkMap)
import Test.QuickCheck.Instances ()
instance Arbitrary ContractId where
arbitrary = ContractId <$> arbitrary
instance Arbitrary SomeMarloweVersion where
arbitrary = pure $ SomeMarloweVersion MarloweV1
class
( Arbitrary (Contract v)
, Arbitrary (Datum v)
, Arbitrary (Inputs v)
, Arbitrary (PayoutDatum v)
, IsMarloweVersion v
) => ArbitraryMarloweVersion v
instance ArbitraryMarloweVersion 'V1
instance ArbitraryMarloweVersion v => Arbitrary (Transaction v) where
arbitrary = Transaction
<$> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
instance Arbitrary V1.MarloweParams where
arbitrary = V1.MarloweParams . toPlutusCurrencySymbol <$> arbitrary
instance Arbitrary V1.MarloweData where
arbitrary = V1.MarloweData <$> arbitrary <*> arbitrary <*> arbitrary
shrink = genericShrink
instance ArbitraryMarloweVersion v => Arbitrary (TransactionOutput v) where
arbitrary = TransactionOutput <$> arbitrary <*> arbitrary
shrink = genericShrink
instance ArbitraryMarloweVersion v => Arbitrary (Payout v) where
arbitrary = Payout <$> arbitrary <*> arbitrary <*> arbitrary
shrink (Payout address assets datum) = fold
[ [ Payout address assets' datum | assets' <- shrink assets ]
, [ Payout address assets datum' | datum' <- shrink datum ]
]
instance ArbitraryMarloweVersion v => Arbitrary (TransactionScriptOutput v) where
arbitrary = TransactionScriptOutput <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
shrink (TransactionScriptOutput address assets utxo datum) = fold
[ [ TransactionScriptOutput address assets' utxo datum | assets' <- shrink assets ]
, [ TransactionScriptOutput address assets utxo datum' | datum' <- shrink datum ]
]
| |
dd9dd8d6636282c07cd352c2a1e7d5680adc39a7dd5c06e520b3eb65b58b6759 | racket/compatibility | defmacro.rkt | #lang racket/base
;; defmacro - for legacy macros only
(require (for-syntax racket/base syntax/stx))
(provide define-macro
defmacro)
(define-syntax define-macro
(lambda (stx)
(syntax-case stx ()
[(_ (name . args) proc0 proc ...)
(begin
(unless (identifier? (syntax name))
(raise-syntax-error
#f
"expected an identifier for the macro name"
stx
(syntax name)))
(let loop ([args (syntax args)])
(cond
[(stx-null? args) 'ok]
[(identifier? args) 'ok]
[(stx-pair? args)
(unless (identifier? (stx-car args))
(raise-syntax-error
#f
"expected an identifier for a macro argument"
stx
(stx-car args)))
(loop (stx-cdr args))]
[else (raise-syntax-error
#f
"not a valid argument sequence after the macro name"
stx)]))
(syntax
(define-macro name (lambda args proc0 proc ...))))]
[(_ name proc)
(begin
(unless (identifier? (syntax name))
(raise-syntax-error
#f
"expected an identifier for the macro name"
stx
(syntax name)))
(syntax
(define-syntax name
(let ([p proc])
(unless (procedure? p)
(raise-type-error
'define-macro
"procedure (arity 1)"
p))
(lambda (stx)
(let ([l (syntax->list stx)])
(unless (and l (procedure-arity-includes? p (sub1 (length l))))
(raise-syntax-error
#f
"bad form"
stx))
(let ([ht (make-hash)])
(datum->syntax
stx
(dm-subst
ht
(apply p (cdr (dm-syntax->datum stx ht))))
stx))))))))])))
(define-syntax defmacro
(syntax-rules ()
[(_ name formals body1 body ...)
(define-macro (name . formals) body1 body ...)]))
;; helper submodule
;;
;; defined as a submodule because swindle requires it
(module dmhelp racket/base
(require syntax/stx)
(provide dm-syntax->datum
dm-subst)
;; `dm-syntax->datum' is like syntax-object->datum, but it also
;; builds a hash table that maps generated data to original syntax
;; objects. The hash table can then be used with `dm-subst' to
;; replace each re-used, unmodified datum with the original syntax
;; object.
(define (dm-syntax->datum stx ht)
;; Easiest to handle cycles by letting `syntax-object->datum'
;; do all the work.
(let ([v (syntax->datum stx)])
(let loop ([stx stx][v v])
(let ([already (hash-ref ht v (lambda () #f))])
(if already
(hash-set! ht v #t) ;; not stx => don't subst later
(hash-set! ht v stx))
(cond
[(stx-pair? stx)
(loop (stx-car stx) (car v))
(loop (stx-cdr stx) (cdr v))]
[(stx-null? stx) null]
[(vector? (syntax-e stx))
(for-each
loop
(vector->list
(syntax-e stx))
(vector->list v))]
[(box? (syntax-e stx))
(loop (unbox (syntax-e stx))
(unbox v))]
[else (void)])))
v))
(define (dm-subst ht v)
(define cycle-ht (make-hash))
(let loop ([v v])
(if (hash-ref cycle-ht v (lambda () #f))
v
(begin
(hash-set! cycle-ht v #t)
(let ([m (hash-ref ht v (lambda () #f))])
(cond
[(syntax? m) m] ;; subst back!
[(pair? v) (cons (loop (car v))
(loop (cdr v)))]
[(vector? v) (list->vector
(map
loop
(vector->list v)))]
[(box? v) (box (loop (unbox v)))]
[else v])))))))
;; this require has to be here after the submodule
(require (for-syntax 'dmhelp))
| null | https://raw.githubusercontent.com/racket/compatibility/492030dac6f095045ce8a13dca75204dd5f34e32/compatibility-lib/compatibility/defmacro.rkt | racket | defmacro - for legacy macros only
helper submodule
defined as a submodule because swindle requires it
`dm-syntax->datum' is like syntax-object->datum, but it also
builds a hash table that maps generated data to original syntax
objects. The hash table can then be used with `dm-subst' to
replace each re-used, unmodified datum with the original syntax
object.
Easiest to handle cycles by letting `syntax-object->datum'
do all the work.
not stx => don't subst later
subst back!
this require has to be here after the submodule | #lang racket/base
(require (for-syntax racket/base syntax/stx))
(provide define-macro
defmacro)
(define-syntax define-macro
(lambda (stx)
(syntax-case stx ()
[(_ (name . args) proc0 proc ...)
(begin
(unless (identifier? (syntax name))
(raise-syntax-error
#f
"expected an identifier for the macro name"
stx
(syntax name)))
(let loop ([args (syntax args)])
(cond
[(stx-null? args) 'ok]
[(identifier? args) 'ok]
[(stx-pair? args)
(unless (identifier? (stx-car args))
(raise-syntax-error
#f
"expected an identifier for a macro argument"
stx
(stx-car args)))
(loop (stx-cdr args))]
[else (raise-syntax-error
#f
"not a valid argument sequence after the macro name"
stx)]))
(syntax
(define-macro name (lambda args proc0 proc ...))))]
[(_ name proc)
(begin
(unless (identifier? (syntax name))
(raise-syntax-error
#f
"expected an identifier for the macro name"
stx
(syntax name)))
(syntax
(define-syntax name
(let ([p proc])
(unless (procedure? p)
(raise-type-error
'define-macro
"procedure (arity 1)"
p))
(lambda (stx)
(let ([l (syntax->list stx)])
(unless (and l (procedure-arity-includes? p (sub1 (length l))))
(raise-syntax-error
#f
"bad form"
stx))
(let ([ht (make-hash)])
(datum->syntax
stx
(dm-subst
ht
(apply p (cdr (dm-syntax->datum stx ht))))
stx))))))))])))
(define-syntax defmacro
(syntax-rules ()
[(_ name formals body1 body ...)
(define-macro (name . formals) body1 body ...)]))
(module dmhelp racket/base
(require syntax/stx)
(provide dm-syntax->datum
dm-subst)
(define (dm-syntax->datum stx ht)
(let ([v (syntax->datum stx)])
(let loop ([stx stx][v v])
(let ([already (hash-ref ht v (lambda () #f))])
(if already
(hash-set! ht v stx))
(cond
[(stx-pair? stx)
(loop (stx-car stx) (car v))
(loop (stx-cdr stx) (cdr v))]
[(stx-null? stx) null]
[(vector? (syntax-e stx))
(for-each
loop
(vector->list
(syntax-e stx))
(vector->list v))]
[(box? (syntax-e stx))
(loop (unbox (syntax-e stx))
(unbox v))]
[else (void)])))
v))
(define (dm-subst ht v)
(define cycle-ht (make-hash))
(let loop ([v v])
(if (hash-ref cycle-ht v (lambda () #f))
v
(begin
(hash-set! cycle-ht v #t)
(let ([m (hash-ref ht v (lambda () #f))])
(cond
[(pair? v) (cons (loop (car v))
(loop (cdr v)))]
[(vector? v) (list->vector
(map
loop
(vector->list v)))]
[(box? v) (box (loop (unbox v)))]
[else v])))))))
(require (for-syntax 'dmhelp))
|
4d3a3a34c0e3f224ad710d835704b7b89003bdad8114392d192092e767eb10c2 | alevy/postgresql-orm | migration.hs | {-# LANGUAGE OverloadedStrings #-}
import Database.PostgreSQL.Migrations
import Database.PostgreSQL.Simple
up :: Connection -> IO ()
up = migrate $
error "Not implemented"
down :: Connection -> IO ()
down = migrate $ do
error "Not implemented"
main :: IO ()
main = defaultMain up down
| null | https://raw.githubusercontent.com/alevy/postgresql-orm/9316db2f226c512036c2b72983020f6bdefd41bd/static/migration.hs | haskell | # LANGUAGE OverloadedStrings # | import Database.PostgreSQL.Migrations
import Database.PostgreSQL.Simple
up :: Connection -> IO ()
up = migrate $
error "Not implemented"
down :: Connection -> IO ()
down = migrate $ do
error "Not implemented"
main :: IO ()
main = defaultMain up down
|
07262b2a5e7bb5e386168f0610f5e914224351a8a4f596ca2c0ee181daf1d602 | alasconnect/auth0 | GetToken.hs | module Auth0.Authentication.GetToken where
--------------------------------------------------------------------------------
import Data.Aeson
import Data.Proxy
import Data.Text
import GHC.Generics
import Servant.API
import Servant.Client
--------------------------------------------------------------------------------
import Auth0.Types
--------------------------------------------------------------------------------
data GetTokenResponse
= GetTokenResponse
{ accessToken :: AccessToken
, refreshToken :: Maybe Text
, idToken :: Maybe Text
, tokenType :: Text
, expiresIn :: Int
, recoveryCode :: Maybe Text
, scope :: Maybe Text
} deriving (Generic, Show)
instance FromJSON GetTokenResponse where
parseJSON =
genericParseJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
--------------------------------------------------------------------------------
-- POST /oauth/token
-- Authorize Code
data GetToken
= GetToken
{ grantType :: GrantType
, clientId :: ClientId
, clientSecret :: ClientSecret
, code :: Text
, redirectUri :: Maybe Text
} deriving (Generic, Show)
instance ToJSON GetToken where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
type GetTokenApi
= ReqBody '[JSON] GetToken
:> Post '[JSON] GetTokenResponse
getToken ::
GetToken
-> ClientM GetTokenResponse
--------------------------------------------------------------------------------
-- POST /oauth/token
Authorize Code ( PKCE )
data GetTokenPKCE
= GetTokenPKCE
{ grantType :: GrantType
, clientId :: ClientId
, code :: Text
, codeVerifier :: Text
, redirectUri :: Maybe Text
} deriving (Generic, Show)
instance ToJSON GetTokenPKCE where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
type GetTokenPKCEApi
= ReqBody '[JSON] GetTokenPKCE
:> Post '[JSON] GetTokenResponse
getTokenPKCE ::
GetTokenPKCE
-> ClientM GetTokenResponse
--------------------------------------------------------------------------------
-- POST /oauth/token
-- Client Credentials
data GetTokenClientCreds
= GetTokenClientCreds
{ grantType :: GrantType
, clientId :: ClientId
, clientSecret :: ClientSecret
, audience :: Text
} deriving (Generic, Show)
instance ToJSON GetTokenClientCreds where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
type GetTokenClientCredsApi
= ReqBody '[JSON] GetTokenClientCreds
:> Post '[JSON] GetTokenResponse
getTokenClientCreds ::
GetTokenClientCreds
-> ClientM GetTokenResponse
--------------------------------------------------------------------------------
-- POST /oauth/token
-- Resource Owner Password
data GetTokenResourceOwner
= GetTokenResourceOwner
{ grantType :: GrantType
, clientId :: ClientId
, clientSecret :: Maybe ClientSecret
, audience :: Maybe Text
, username :: Text
, password :: Text
, scope :: Maybe Text
, realm :: Maybe Text
} deriving (Generic, Show)
instance ToJSON GetTokenResourceOwner where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
type GetTokenResourceOwnerApi
= ReqBody '[JSON] GetTokenResourceOwner
:> Post '[JSON] GetTokenResponse
getTokenResourceOwner ::
GetTokenResourceOwner
-> ClientM GetTokenResponse
--------------------------------------------------------------------------------
type GetTokenAllApi
= "oauth"
:> "token" :>
(
GetTokenApi
:<|> GetTokenPKCEApi
:<|> GetTokenClientCredsApi
:<|> GetTokenResourceOwnerApi
)
getTokenApi :: Proxy GetTokenAllApi
getTokenApi = Proxy
getToken
:<|> getTokenPKCE
:<|> getTokenClientCreds
:<|> getTokenResourceOwner
= client getTokenApi
--------------------------------------------------------------------------------
-- POST /mfa/challenge
Resource Owner Password and MFA
data GetTokenResourceOwnerMFA
= GetTokenResourceOwnerMFA
{ mfaToken :: Text
, clientId :: ClientId
, clientSecret :: Maybe ClientSecret
, challengeType :: Maybe Text
} deriving (Generic, Show)
instance ToJSON GetTokenResourceOwnerMFA where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
type GetTokenResourceOwnerMFAApi
= "/mfa/challenge"
:> ReqBody '[JSON] GetTokenResourceOwnerMFA
:> Post '[JSON] GetTokenResourceOwnerMFAResponse
getTokenResourceOwnerMFA ::
GetTokenResourceOwnerMFA
-> ClientM GetTokenResourceOwnerMFAResponse
-- Response
data GetTokenResourceOwnerMFAResponse
= GetTokenResourceOwnerMFAResponse
{ challengeType :: Text
, bindingMethod :: Maybe Text
, oobCode :: Maybe Text
} deriving (Generic, Show)
instance FromJSON GetTokenResourceOwnerMFAResponse where
parseJSON =
genericParseJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
getTokenResourceOwnerMFAApi :: Proxy GetTokenResourceOwnerMFAApi
getTokenResourceOwnerMFAApi = Proxy
getTokenResourceOwnerMFA = client getTokenResourceOwnerMFAApi
--------------------------------------------------------------------------------
-- TODO: The following
--------------------------------------------------------------------------------
-- POST /oauth/token
Verify MFA using OTP
data GetTokenVerifyMFAOTP
= GetTokenVerifyMFAOTP
{ grantType :: GrantType
, clientId :: ClientId
, clientSecret :: Maybe ClientSecret
, mfaToken :: Text
, otp :: Text
} deriving (Generic, Show)
instance ToJSON GetTokenVerifyMFAOTP where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
--------------------------------------------------------------------------------
-- POST /oauth/token
Verify MFA using OOB challenge
data GetTokenVerifyMFAOOB
= GetTokenVerifyMFAOOB
{ grantType :: GrantType
, clientId :: ClientId
, clientSecret :: Maybe ClientSecret
, mfaToken :: Text
, oobCode :: Text
, bindingCode :: Maybe Text
} deriving (Generic, Show)
instance ToJSON GetTokenVerifyMFAOOB where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
Verify MFA using a recovery code
data GetTokenVerifyRecoveryCode
= GetTokenVerifyRecoveryCode
{ grantType :: GrantType
, clientId :: ClientId
, clientSecret :: Maybe ClientSecret
, mfaToken :: Text
, recoveryCode :: Text
} deriving (Generic, Show)
instance ToJSON GetTokenVerifyRecoveryCode where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
-- Refresh Token
data GetTokenRefresh
= GetTokenRefresh
{ grantType :: GrantType
, clientId :: ClientId
, clientSecret :: Maybe ClientSecret
, refreshToken :: Text
} deriving (Generic, Show)
instance ToJSON GetTokenRefresh where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
| null | https://raw.githubusercontent.com/alasconnect/auth0/6e868552885729487e60a2dfe6073f485b505651/src/Auth0/Authentication/GetToken.hs | haskell | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
POST /oauth/token
Authorize Code
------------------------------------------------------------------------------
POST /oauth/token
------------------------------------------------------------------------------
POST /oauth/token
Client Credentials
------------------------------------------------------------------------------
POST /oauth/token
Resource Owner Password
------------------------------------------------------------------------------
------------------------------------------------------------------------------
POST /mfa/challenge
Response
------------------------------------------------------------------------------
TODO: The following
------------------------------------------------------------------------------
POST /oauth/token
------------------------------------------------------------------------------
POST /oauth/token
Refresh Token | module Auth0.Authentication.GetToken where
import Data.Aeson
import Data.Proxy
import Data.Text
import GHC.Generics
import Servant.API
import Servant.Client
import Auth0.Types
data GetTokenResponse
= GetTokenResponse
{ accessToken :: AccessToken
, refreshToken :: Maybe Text
, idToken :: Maybe Text
, tokenType :: Text
, expiresIn :: Int
, recoveryCode :: Maybe Text
, scope :: Maybe Text
} deriving (Generic, Show)
instance FromJSON GetTokenResponse where
parseJSON =
genericParseJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
data GetToken
= GetToken
{ grantType :: GrantType
, clientId :: ClientId
, clientSecret :: ClientSecret
, code :: Text
, redirectUri :: Maybe Text
} deriving (Generic, Show)
instance ToJSON GetToken where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
type GetTokenApi
= ReqBody '[JSON] GetToken
:> Post '[JSON] GetTokenResponse
getToken ::
GetToken
-> ClientM GetTokenResponse
Authorize Code ( PKCE )
data GetTokenPKCE
= GetTokenPKCE
{ grantType :: GrantType
, clientId :: ClientId
, code :: Text
, codeVerifier :: Text
, redirectUri :: Maybe Text
} deriving (Generic, Show)
instance ToJSON GetTokenPKCE where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
type GetTokenPKCEApi
= ReqBody '[JSON] GetTokenPKCE
:> Post '[JSON] GetTokenResponse
getTokenPKCE ::
GetTokenPKCE
-> ClientM GetTokenResponse
data GetTokenClientCreds
= GetTokenClientCreds
{ grantType :: GrantType
, clientId :: ClientId
, clientSecret :: ClientSecret
, audience :: Text
} deriving (Generic, Show)
instance ToJSON GetTokenClientCreds where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
type GetTokenClientCredsApi
= ReqBody '[JSON] GetTokenClientCreds
:> Post '[JSON] GetTokenResponse
getTokenClientCreds ::
GetTokenClientCreds
-> ClientM GetTokenResponse
data GetTokenResourceOwner
= GetTokenResourceOwner
{ grantType :: GrantType
, clientId :: ClientId
, clientSecret :: Maybe ClientSecret
, audience :: Maybe Text
, username :: Text
, password :: Text
, scope :: Maybe Text
, realm :: Maybe Text
} deriving (Generic, Show)
instance ToJSON GetTokenResourceOwner where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
type GetTokenResourceOwnerApi
= ReqBody '[JSON] GetTokenResourceOwner
:> Post '[JSON] GetTokenResponse
getTokenResourceOwner ::
GetTokenResourceOwner
-> ClientM GetTokenResponse
type GetTokenAllApi
= "oauth"
:> "token" :>
(
GetTokenApi
:<|> GetTokenPKCEApi
:<|> GetTokenClientCredsApi
:<|> GetTokenResourceOwnerApi
)
getTokenApi :: Proxy GetTokenAllApi
getTokenApi = Proxy
getToken
:<|> getTokenPKCE
:<|> getTokenClientCreds
:<|> getTokenResourceOwner
= client getTokenApi
Resource Owner Password and MFA
data GetTokenResourceOwnerMFA
= GetTokenResourceOwnerMFA
{ mfaToken :: Text
, clientId :: ClientId
, clientSecret :: Maybe ClientSecret
, challengeType :: Maybe Text
} deriving (Generic, Show)
instance ToJSON GetTokenResourceOwnerMFA where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
type GetTokenResourceOwnerMFAApi
= "/mfa/challenge"
:> ReqBody '[JSON] GetTokenResourceOwnerMFA
:> Post '[JSON] GetTokenResourceOwnerMFAResponse
getTokenResourceOwnerMFA ::
GetTokenResourceOwnerMFA
-> ClientM GetTokenResourceOwnerMFAResponse
data GetTokenResourceOwnerMFAResponse
= GetTokenResourceOwnerMFAResponse
{ challengeType :: Text
, bindingMethod :: Maybe Text
, oobCode :: Maybe Text
} deriving (Generic, Show)
instance FromJSON GetTokenResourceOwnerMFAResponse where
parseJSON =
genericParseJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
getTokenResourceOwnerMFAApi :: Proxy GetTokenResourceOwnerMFAApi
getTokenResourceOwnerMFAApi = Proxy
getTokenResourceOwnerMFA = client getTokenResourceOwnerMFAApi
Verify MFA using OTP
data GetTokenVerifyMFAOTP
= GetTokenVerifyMFAOTP
{ grantType :: GrantType
, clientId :: ClientId
, clientSecret :: Maybe ClientSecret
, mfaToken :: Text
, otp :: Text
} deriving (Generic, Show)
instance ToJSON GetTokenVerifyMFAOTP where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
Verify MFA using OOB challenge
data GetTokenVerifyMFAOOB
= GetTokenVerifyMFAOOB
{ grantType :: GrantType
, clientId :: ClientId
, clientSecret :: Maybe ClientSecret
, mfaToken :: Text
, oobCode :: Text
, bindingCode :: Maybe Text
} deriving (Generic, Show)
instance ToJSON GetTokenVerifyMFAOOB where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
Verify MFA using a recovery code
data GetTokenVerifyRecoveryCode
= GetTokenVerifyRecoveryCode
{ grantType :: GrantType
, clientId :: ClientId
, clientSecret :: Maybe ClientSecret
, mfaToken :: Text
, recoveryCode :: Text
} deriving (Generic, Show)
instance ToJSON GetTokenVerifyRecoveryCode where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
data GetTokenRefresh
= GetTokenRefresh
{ grantType :: GrantType
, clientId :: ClientId
, clientSecret :: Maybe ClientSecret
, refreshToken :: Text
} deriving (Generic, Show)
instance ToJSON GetTokenRefresh where
toJSON =
genericToJSON defaultOptions { omitNothingFields = True, fieldLabelModifier = camelTo2 '_' }
|
88e14ccb451dbb5a15ec0e164b7ffc3fa91940b44d387a2aa8b62c55ea2c1329 | rethab/h-gpgme | KeyGenTest.hs | {-# LANGUAGE OverloadedStrings #-}
module KeyGenTest (tests) where
import Test.Tasty (TestTree)
import Test.Tasty.HUnit (testCase)
import Test.HUnit
import Text.Email.Validate
import System.FilePath ((</>))
import System.Directory ( removeDirectoryRecursive )
import System.IO ( hPutStr
, hPutStrLn
, IOMode (..)
, withFile
, hGetContents
)
import Data.Time.Calendar
import Data.Time.Clock
import Data.Default
import Data.List ( isPrefixOf )
import Data.ByteString.Char8 ( unpack )
import Crypto.Gpgme
import qualified Crypto.Gpgme.Key.Gen as G
import TestUtil
tests :: [TestTree]
tests = [ testCase "allGenKeyParameters" allGenKeyParameters
, testCase "expireDateDays" expireDateDays
, testCase "expireDateWeeks" expireDateWeeks
, testCase "expireDateMonths" expireDateMonths
, testCase "expireDateYears" expireDateYears
, testCase "expireDateSeconds" expireDateSeconds
, testCase "creationDateSeconds" creationDateSeconds
, testCase "genKeyNoCi" genKey
, testCase "progressCallbackNoCi" progressCallback
]
-- For getting values from Either
errorOnLeft :: Either String a -> a
errorOnLeft (Right x) = x
errorOnLeft (Left s) = error s
-- Test parameter list generation for generating keys
allGenKeyParameters :: Assertion
allGenKeyParameters =
let params = (def :: G.GenKeyParams) -- G.defaultGenKeyParams
{ G.keyType = Just Dsa
, G.keyLength = Just $ errorOnLeft $ G.bitSize 1024
, G.keyGrip = "123abc"
, G.keyUsage = Just $ (def :: G.UsageList) {
G.encrypt = Just G.Encrypt
, G.sign = Just G.Sign
, G.auth = Just G.Auth
}
, G.subkeyType = Just ElgE
, G.subkeyLength = Just $ errorOnLeft $ G.bitSize 1024
, G.passphrase = "easy to guess"
, G.nameReal = "Foo Bar"
, G.nameComment = "A great comment"
, G.nameEmail = Just $ errorOnLeft $ validate ""
, G.expireDate = Just $ G.ExpireT $ UTCTime (fromGregorian 2050 8 15) 52812
, G.creationDate = Just $ G.CreationT $
UTCTime (fromGregorian 2040 8 16) 52813
, G.preferences = "Some preference"
, G.revoker = "RSA:fpr sensitive"
, G.keyserver = "/"
, G.handle = "Key handle here"
}
in G.toParamsString params @?=
"<GnupgKeyParms format=\"internal\">\n\
\Key-Type: DSA\n\
\Key-Length: 1024\n\
\Key-Grip: 123abc\n\
\Key-Usage: encrypt,sign,auth\n\
\Subkey-Type: ELG-E\n\
\Subkey-Length: 1024\n\
\Passphrase: easy to guess\n\
\Name-Real: Foo Bar\n\
\Name-Comment: A great comment\n\
\Name-Email: \n\
\Expire-Date: 20500815T144012\n\
\Creation-Date: 20400816T144013\n\
\Preferences: Some preference\n\
\Revoker: RSA:fpr sensitive\n\
\Keyserver: /\n\
\Handle: Key handle here\n\
\</GnupgKeyParms>\n"
genKey :: Assertion
genKey = do
tmpDir <- createTemporaryTestDir "genKey"
ret <- withCtx tmpDir "C" OpenPGP $ \ctx -> do
let params = (def :: G.GenKeyParams)
{ G.keyType = Just Dsa
, G.keyLength = Just $ errorOnLeft $ G.bitSize 1024
, G.rawParams =
"Subkey-Type: ELG-E\n\
\Subkey-Length: 1024\n\
\Name-Real: Joe Tester\n\
\Name-Comment: (pp=abc)\n\
\Name-Email: \n\
\Expire-Date: 0\n\
\Passphrase: abc\n"
}
G.genKey ctx params
-- Cleanup temporary directory
removeDirectoryRecursive tmpDir
either
(\l -> assertFailure $ "Left was return value " ++ show l)
(\r -> assertBool ("Fingerprint ("
++ unpack r
++ ") starts with '0x' indicating it is actually a pointer.")
(not $ isPrefixOf "0x" (unpack r))) ret
Other ExpireDate to string possibilities
expireDateDays :: Assertion
expireDateDays =
let (Just p) = G.toPositive 10
params = (def :: G.GenKeyParams) {
G.expireDate = Just $ G.ExpireD p
}
in G.toParamsString params @?=
"<GnupgKeyParms format=\"internal\">\n\
\Key-Type: default\n\
\Expire-Date: 10d\n\
\</GnupgKeyParms>\n"
expireDateWeeks :: Assertion
expireDateWeeks =
let (Just p) = G.toPositive 10
params = (def :: G.GenKeyParams) {
G.expireDate = Just $ G.ExpireW p
}
in G.toParamsString params @?=
"<GnupgKeyParms format=\"internal\">\n\
\Key-Type: default\n\
\Expire-Date: 10w\n\
\</GnupgKeyParms>\n"
expireDateMonths :: Assertion
expireDateMonths =
let (Just p) = G.toPositive 10
params = (def :: G.GenKeyParams) {
G.expireDate = Just $ G.ExpireM p
}
in G.toParamsString params @?=
"<GnupgKeyParms format=\"internal\">\n\
\Key-Type: default\n\
\Expire-Date: 10m\n\
\</GnupgKeyParms>\n"
expireDateYears :: Assertion
expireDateYears =
let (Just p) = G.toPositive 10
params = (def :: G.GenKeyParams) {
G.expireDate = Just $ G.ExpireY p
}
in G.toParamsString params @?=
"<GnupgKeyParms format=\"internal\">\n\
\Key-Type: default\n\
\Expire-Date: 10y\n\
\</GnupgKeyParms>\n"
expireDateSeconds :: Assertion
expireDateSeconds =
let (Just p) = G.toPositive 123456
params = (def :: G.GenKeyParams) {
G.expireDate = Just $ G.ExpireS p
}
in G.toParamsString params @?=
"<GnupgKeyParms format=\"internal\">\n\
\Key-Type: default\n\
\Expire-Date: seconds=123456\n\
\</GnupgKeyParms>\n"
creationDateSeconds :: Assertion
creationDateSeconds =
let (Just p) = G.toPositive 123456
params = (def :: G.GenKeyParams) {
G.creationDate = Just $ G.CreationS p
}
in G.toParamsString params @?=
"<GnupgKeyParms format=\"internal\">\n\
\Key-Type: default\n\
\Creation-Date: seconds=123456\n\
\</GnupgKeyParms>\n"
progressCallback :: Assertion
progressCallback = do
tmpDir <- createTemporaryTestDir "progress_callback"
-- Setup context
genRet <- withCtx tmpDir "C" OpenPGP $ \ctx -> do
-- Setup generation parameters
let params = (def :: G.GenKeyParams)
{ G.keyType = Just Rsa
, G.keyLength = Just $ errorOnLeft $ G.bitSize 2048
, G.nameReal = "Joe Tester"
, G.nameEmail = Just $ errorOnLeft $ validate ""
, G.passphrase = "abc"
}
-- Setup callback which writes to temporary file.
testProgressCb what char cur total =
withFile (tmpDir </> "testProgress.log") AppendMode (\h -> do
hPutStr h ("what: " ++ what)
hPutStr h (" char: " ++ show char)
hPutStr h (" cur: " ++ show cur)
hPutStr h (" total: " ++ show total)
hPutStrLn h "")
setProgressCallback ctx (Just testProgressCb)
-- Run key generation
G.genKey ctx params
-- Make sure the file has some evidence of progress notifications
ret <- withFile (tmpDir </> "testProgress.log") ReadMode (\h -> do
contents <- hGetContents h
not (null (lines contents)) @? "No lines in progress file")
-- Cleanup test
removeDirectoryRecursive tmpDir
assertBool ("Left was return value: " ++ show ret) (either (const False) (const True) genRet)
return ret
| null | https://raw.githubusercontent.com/rethab/h-gpgme/2067468bec84601a8f6fcdb79bd180a4713c0b3c/test/KeyGenTest.hs | haskell | # LANGUAGE OverloadedStrings #
For getting values from Either
Test parameter list generation for generating keys
G.defaultGenKeyParams
Cleanup temporary directory
Setup context
Setup generation parameters
Setup callback which writes to temporary file.
Run key generation
Make sure the file has some evidence of progress notifications
Cleanup test | module KeyGenTest (tests) where
import Test.Tasty (TestTree)
import Test.Tasty.HUnit (testCase)
import Test.HUnit
import Text.Email.Validate
import System.FilePath ((</>))
import System.Directory ( removeDirectoryRecursive )
import System.IO ( hPutStr
, hPutStrLn
, IOMode (..)
, withFile
, hGetContents
)
import Data.Time.Calendar
import Data.Time.Clock
import Data.Default
import Data.List ( isPrefixOf )
import Data.ByteString.Char8 ( unpack )
import Crypto.Gpgme
import qualified Crypto.Gpgme.Key.Gen as G
import TestUtil
tests :: [TestTree]
tests = [ testCase "allGenKeyParameters" allGenKeyParameters
, testCase "expireDateDays" expireDateDays
, testCase "expireDateWeeks" expireDateWeeks
, testCase "expireDateMonths" expireDateMonths
, testCase "expireDateYears" expireDateYears
, testCase "expireDateSeconds" expireDateSeconds
, testCase "creationDateSeconds" creationDateSeconds
, testCase "genKeyNoCi" genKey
, testCase "progressCallbackNoCi" progressCallback
]
errorOnLeft :: Either String a -> a
errorOnLeft (Right x) = x
errorOnLeft (Left s) = error s
allGenKeyParameters :: Assertion
allGenKeyParameters =
{ G.keyType = Just Dsa
, G.keyLength = Just $ errorOnLeft $ G.bitSize 1024
, G.keyGrip = "123abc"
, G.keyUsage = Just $ (def :: G.UsageList) {
G.encrypt = Just G.Encrypt
, G.sign = Just G.Sign
, G.auth = Just G.Auth
}
, G.subkeyType = Just ElgE
, G.subkeyLength = Just $ errorOnLeft $ G.bitSize 1024
, G.passphrase = "easy to guess"
, G.nameReal = "Foo Bar"
, G.nameComment = "A great comment"
, G.nameEmail = Just $ errorOnLeft $ validate ""
, G.expireDate = Just $ G.ExpireT $ UTCTime (fromGregorian 2050 8 15) 52812
, G.creationDate = Just $ G.CreationT $
UTCTime (fromGregorian 2040 8 16) 52813
, G.preferences = "Some preference"
, G.revoker = "RSA:fpr sensitive"
, G.keyserver = "/"
, G.handle = "Key handle here"
}
in G.toParamsString params @?=
"<GnupgKeyParms format=\"internal\">\n\
\Key-Type: DSA\n\
\Key-Length: 1024\n\
\Key-Grip: 123abc\n\
\Key-Usage: encrypt,sign,auth\n\
\Subkey-Type: ELG-E\n\
\Subkey-Length: 1024\n\
\Passphrase: easy to guess\n\
\Name-Real: Foo Bar\n\
\Name-Comment: A great comment\n\
\Name-Email: \n\
\Expire-Date: 20500815T144012\n\
\Creation-Date: 20400816T144013\n\
\Preferences: Some preference\n\
\Revoker: RSA:fpr sensitive\n\
\Keyserver: /\n\
\Handle: Key handle here\n\
\</GnupgKeyParms>\n"
genKey :: Assertion
genKey = do
tmpDir <- createTemporaryTestDir "genKey"
ret <- withCtx tmpDir "C" OpenPGP $ \ctx -> do
let params = (def :: G.GenKeyParams)
{ G.keyType = Just Dsa
, G.keyLength = Just $ errorOnLeft $ G.bitSize 1024
, G.rawParams =
"Subkey-Type: ELG-E\n\
\Subkey-Length: 1024\n\
\Name-Real: Joe Tester\n\
\Name-Comment: (pp=abc)\n\
\Name-Email: \n\
\Expire-Date: 0\n\
\Passphrase: abc\n"
}
G.genKey ctx params
removeDirectoryRecursive tmpDir
either
(\l -> assertFailure $ "Left was return value " ++ show l)
(\r -> assertBool ("Fingerprint ("
++ unpack r
++ ") starts with '0x' indicating it is actually a pointer.")
(not $ isPrefixOf "0x" (unpack r))) ret
Other ExpireDate to string possibilities
expireDateDays :: Assertion
expireDateDays =
let (Just p) = G.toPositive 10
params = (def :: G.GenKeyParams) {
G.expireDate = Just $ G.ExpireD p
}
in G.toParamsString params @?=
"<GnupgKeyParms format=\"internal\">\n\
\Key-Type: default\n\
\Expire-Date: 10d\n\
\</GnupgKeyParms>\n"
expireDateWeeks :: Assertion
expireDateWeeks =
let (Just p) = G.toPositive 10
params = (def :: G.GenKeyParams) {
G.expireDate = Just $ G.ExpireW p
}
in G.toParamsString params @?=
"<GnupgKeyParms format=\"internal\">\n\
\Key-Type: default\n\
\Expire-Date: 10w\n\
\</GnupgKeyParms>\n"
expireDateMonths :: Assertion
expireDateMonths =
let (Just p) = G.toPositive 10
params = (def :: G.GenKeyParams) {
G.expireDate = Just $ G.ExpireM p
}
in G.toParamsString params @?=
"<GnupgKeyParms format=\"internal\">\n\
\Key-Type: default\n\
\Expire-Date: 10m\n\
\</GnupgKeyParms>\n"
expireDateYears :: Assertion
expireDateYears =
let (Just p) = G.toPositive 10
params = (def :: G.GenKeyParams) {
G.expireDate = Just $ G.ExpireY p
}
in G.toParamsString params @?=
"<GnupgKeyParms format=\"internal\">\n\
\Key-Type: default\n\
\Expire-Date: 10y\n\
\</GnupgKeyParms>\n"
expireDateSeconds :: Assertion
expireDateSeconds =
let (Just p) = G.toPositive 123456
params = (def :: G.GenKeyParams) {
G.expireDate = Just $ G.ExpireS p
}
in G.toParamsString params @?=
"<GnupgKeyParms format=\"internal\">\n\
\Key-Type: default\n\
\Expire-Date: seconds=123456\n\
\</GnupgKeyParms>\n"
creationDateSeconds :: Assertion
creationDateSeconds =
let (Just p) = G.toPositive 123456
params = (def :: G.GenKeyParams) {
G.creationDate = Just $ G.CreationS p
}
in G.toParamsString params @?=
"<GnupgKeyParms format=\"internal\">\n\
\Key-Type: default\n\
\Creation-Date: seconds=123456\n\
\</GnupgKeyParms>\n"
progressCallback :: Assertion
progressCallback = do
tmpDir <- createTemporaryTestDir "progress_callback"
genRet <- withCtx tmpDir "C" OpenPGP $ \ctx -> do
let params = (def :: G.GenKeyParams)
{ G.keyType = Just Rsa
, G.keyLength = Just $ errorOnLeft $ G.bitSize 2048
, G.nameReal = "Joe Tester"
, G.nameEmail = Just $ errorOnLeft $ validate ""
, G.passphrase = "abc"
}
testProgressCb what char cur total =
withFile (tmpDir </> "testProgress.log") AppendMode (\h -> do
hPutStr h ("what: " ++ what)
hPutStr h (" char: " ++ show char)
hPutStr h (" cur: " ++ show cur)
hPutStr h (" total: " ++ show total)
hPutStrLn h "")
setProgressCallback ctx (Just testProgressCb)
G.genKey ctx params
ret <- withFile (tmpDir </> "testProgress.log") ReadMode (\h -> do
contents <- hGetContents h
not (null (lines contents)) @? "No lines in progress file")
removeDirectoryRecursive tmpDir
assertBool ("Left was return value: " ++ show ret) (either (const False) (const True) genRet)
return ret
|
555f8bcd25257580c849f8aff6472dbf7e37a15c638183db6aabd284beda1c78 | LesBoloss-es/sorting | arrays.ml | open Genlib.Genarray
open Table
open Sorting_array
let spf = Format.sprintf
let usage_msg = spf "%s [OPTION ...]\n\nOPTION can be:" Sys.argv.(0)
let default_lengths = List.init 5 (fun i -> (i+ 1) * 30000)
let lengths = ref default_lengths
let set_lengths s =
s
|> String.split_on_char ','
|> List.map int_of_string
|> (:=) lengths
let default_sorters = all_sorters
let sorters = ref default_sorters
let set_sorters s =
s
|> String.split_on_char ','
|> List.map (fun sorter_name ->
List.find (fun sorter -> sorter.name = sorter_name) all_sorters)
|> (:=) sorters
let default_repeat = 50
let repeat = ref 50
let speclist = [
"--lengths", Arg.String set_lengths, "INTS Lengths to use (default: ...)";
"--sorters", Arg.String set_sorters, "STRS Sorters to use (default: ...)";
"--repeat", Arg.Set_int repeat, spf "INT Repetitions (default: %d)" default_repeat;
] |> Arg.align
let anon_fun _ = assert false
let () = Arg.parse speclist anon_fun usage_msg
let log2_fact n =
let rec log2_fact res = function
| 0 -> res
| n -> log2_fact (res +. log (float_of_int n)) (n - 1)
in
log2_fact 0. n /. log 2. |> ceil |> int_of_float
let list_concat_map f l =
l |> List.map f |> List.flatten
let bench_one ~measure ~algorithm ~inputs () =
let inputs = List.map Array.copy inputs in
measure (fun cmp -> List.iter (algorithm cmp) inputs)
let runtime f =
let open Unix in
let before = times () in
f Int.compare;
let after = times () in
after.tms_utime -. before.tms_utime
let comparisons f =
let count = ref 0 in
let int_compare_count a b = incr count; Int.compare a b in
f int_compare_count;
float_of_int !count
let () =
Format.printf "lengths:@.";
List.iter (Format.printf " %d@.") !lengths
let () =
Format.printf "sorters:@.";
List.iteri (fun i sorter -> Format.printf " [%d] %s@." (i+1) sorter.name) !sorters
let () = Format.printf "repeat: %d@." !repeat
let () = Format.printf "@."
type result =
{ runtime : float ;
comparisons : float }
type bench =
{ by_sorter : (string, (int, result) Hashtbl.t) Hashtbl.t ;
by_length : (int, (string, result) Hashtbl.t) Hashtbl.t }
let new_bench () =
{ by_sorter = Hashtbl.create 8 ;
by_length = Hashtbl.create 8 }
let add_bench ~sorter ~length ~runtime ~comparisons bench =
let by_sorter =
match Hashtbl.find_opt bench.by_sorter sorter.name with
| None ->
let tbl = Hashtbl.create 8 in
Hashtbl.add bench.by_sorter sorter.name tbl;
tbl
| Some tbl -> tbl
in
let by_length =
match Hashtbl.find_opt bench.by_length length with
| None ->
let tbl = Hashtbl.create 8 in
Hashtbl.add bench.by_length length tbl;
tbl
| Some tbl -> tbl
in
if Hashtbl.mem by_sorter length || Hashtbl.mem by_length sorter.name then
failwith "add_bench: this sorter and length pair is already known";
Hashtbl.add by_sorter length { runtime ; comparisons };
Hashtbl.add by_length sorter.name { runtime ; comparisons }
let get_bench_result ~sorter ~length bench =
Hashtbl.find (Hashtbl.find bench.by_sorter sorter.name) length
let compute_benchs ~generator =
let results = new_bench () in
(
!lengths |> List.iter @@ fun length ->
Format.printf "[%d]@." length;
let inputs = List.init !repeat (fun _ -> generator length) in
(
let nb_sorters = List.length !sorters in
!sorters |> List.iteri @@ fun i sorter ->
Format.printf " [%d/%d] %s@." (i+1) nb_sorters sorter.name;
let runtime = bench_one ~measure:runtime ~algorithm:sorter.sorter ~inputs () in
let comparisons = bench_one ~measure:comparisons ~algorithm:sorter.sorter ~inputs () in
let repeat = float_of_int !repeat in
add_bench ~sorter ~length ~runtime:(runtime /. repeat *. 1000.) ~comparisons:(comparisons /. repeat) results
)
);
results
let slowdown ~from ~to_ = (to_ -. from) /. from *. 100.
let reference benchs getter length =
let by_length = Hashtbl.find benchs.by_length length in
List.fold_left
(fun best sorter ->
min best (getter (Hashtbl.find by_length sorter.name)))
infinity
!sorters
let build_bench_table benchs getter fmt =
let heading =
string_cell "lengths"
:: string_cell "stable"
:: list_concat_map (fun length -> [ int_cell length ; string_cell "%" ]) !lengths
in
let content =
!sorters |> List.map @@ fun sorter ->
string_cell sorter.name
:: string_cell (if sorter.stable then "yes" else "no")
:: (
!lengths |> list_concat_map @@ fun length ->
let reference = reference benchs getter length in
let result = getter (get_bench_result ~sorter ~length benchs) in
let slowdown = Format.sprintf "%.0f" (slowdown ~from:reference ~to_:result) in
[ fmt_cell (fun () -> result) ~fmt ;
string_cell (if slowdown = "0" then "" else Format.sprintf "(%s%%)" slowdown) ]
)
in
(heading, content)
let cell_styles =
("", Left)
:: (" | ", Right)
:: (List.map (fun _ -> [ (" | ", Right) ; (" ", Right) ]) !lengths
|> List.flatten)
let print_bench_table title benchs getter fmt =
let (heading, content) = build_bench_table benchs getter fmt in
print_table ~title ~cell_styles ~heading content
let () = Format.printf "Computing benchmarks on uniformly chosen arrays...@."
let benchs_unif = compute_benchs ~generator:gen_unif
let () = Format.printf "@."
let () = Format.printf "Computing benchmarks on arrays with 5 runs...@."
let benchs_5runs = compute_benchs ~generator:(gen_k_runs 5)
let () = Format.printf "@."
let () = print_bench_table "Unif - Runtime" benchs_unif (fun result -> result.runtime) "%.2f"
let () = Format.printf "@."
let () = print_bench_table "Unif - Comparisons" benchs_unif (fun result -> result.comparisons) "%.0f"
let () = Format.printf "@."
let () = print_bench_table "5-Runs - Runtime" benchs_5runs (fun result -> result.runtime) "%.2f"
let () = Format.printf "@."
let () = print_bench_table "5-Runs - Comparisons" benchs_5runs (fun result -> result.comparisons) "%.0f"
let () = Format.printf "@."
| null | https://raw.githubusercontent.com/LesBoloss-es/sorting/1ef7f02d06b4a3e51ac488ce69808921819ff17e/bench/arrays.ml | ocaml | open Genlib.Genarray
open Table
open Sorting_array
let spf = Format.sprintf
let usage_msg = spf "%s [OPTION ...]\n\nOPTION can be:" Sys.argv.(0)
let default_lengths = List.init 5 (fun i -> (i+ 1) * 30000)
let lengths = ref default_lengths
let set_lengths s =
s
|> String.split_on_char ','
|> List.map int_of_string
|> (:=) lengths
let default_sorters = all_sorters
let sorters = ref default_sorters
let set_sorters s =
s
|> String.split_on_char ','
|> List.map (fun sorter_name ->
List.find (fun sorter -> sorter.name = sorter_name) all_sorters)
|> (:=) sorters
let default_repeat = 50
let repeat = ref 50
let speclist = [
"--lengths", Arg.String set_lengths, "INTS Lengths to use (default: ...)";
"--sorters", Arg.String set_sorters, "STRS Sorters to use (default: ...)";
"--repeat", Arg.Set_int repeat, spf "INT Repetitions (default: %d)" default_repeat;
] |> Arg.align
let anon_fun _ = assert false
let () = Arg.parse speclist anon_fun usage_msg
let log2_fact n =
let rec log2_fact res = function
| 0 -> res
| n -> log2_fact (res +. log (float_of_int n)) (n - 1)
in
log2_fact 0. n /. log 2. |> ceil |> int_of_float
let list_concat_map f l =
l |> List.map f |> List.flatten
let bench_one ~measure ~algorithm ~inputs () =
let inputs = List.map Array.copy inputs in
measure (fun cmp -> List.iter (algorithm cmp) inputs)
let runtime f =
let open Unix in
let before = times () in
f Int.compare;
let after = times () in
after.tms_utime -. before.tms_utime
let comparisons f =
let count = ref 0 in
let int_compare_count a b = incr count; Int.compare a b in
f int_compare_count;
float_of_int !count
let () =
Format.printf "lengths:@.";
List.iter (Format.printf " %d@.") !lengths
let () =
Format.printf "sorters:@.";
List.iteri (fun i sorter -> Format.printf " [%d] %s@." (i+1) sorter.name) !sorters
let () = Format.printf "repeat: %d@." !repeat
let () = Format.printf "@."
type result =
{ runtime : float ;
comparisons : float }
type bench =
{ by_sorter : (string, (int, result) Hashtbl.t) Hashtbl.t ;
by_length : (int, (string, result) Hashtbl.t) Hashtbl.t }
let new_bench () =
{ by_sorter = Hashtbl.create 8 ;
by_length = Hashtbl.create 8 }
let add_bench ~sorter ~length ~runtime ~comparisons bench =
let by_sorter =
match Hashtbl.find_opt bench.by_sorter sorter.name with
| None ->
let tbl = Hashtbl.create 8 in
Hashtbl.add bench.by_sorter sorter.name tbl;
tbl
| Some tbl -> tbl
in
let by_length =
match Hashtbl.find_opt bench.by_length length with
| None ->
let tbl = Hashtbl.create 8 in
Hashtbl.add bench.by_length length tbl;
tbl
| Some tbl -> tbl
in
if Hashtbl.mem by_sorter length || Hashtbl.mem by_length sorter.name then
failwith "add_bench: this sorter and length pair is already known";
Hashtbl.add by_sorter length { runtime ; comparisons };
Hashtbl.add by_length sorter.name { runtime ; comparisons }
let get_bench_result ~sorter ~length bench =
Hashtbl.find (Hashtbl.find bench.by_sorter sorter.name) length
let compute_benchs ~generator =
let results = new_bench () in
(
!lengths |> List.iter @@ fun length ->
Format.printf "[%d]@." length;
let inputs = List.init !repeat (fun _ -> generator length) in
(
let nb_sorters = List.length !sorters in
!sorters |> List.iteri @@ fun i sorter ->
Format.printf " [%d/%d] %s@." (i+1) nb_sorters sorter.name;
let runtime = bench_one ~measure:runtime ~algorithm:sorter.sorter ~inputs () in
let comparisons = bench_one ~measure:comparisons ~algorithm:sorter.sorter ~inputs () in
let repeat = float_of_int !repeat in
add_bench ~sorter ~length ~runtime:(runtime /. repeat *. 1000.) ~comparisons:(comparisons /. repeat) results
)
);
results
let slowdown ~from ~to_ = (to_ -. from) /. from *. 100.
let reference benchs getter length =
let by_length = Hashtbl.find benchs.by_length length in
List.fold_left
(fun best sorter ->
min best (getter (Hashtbl.find by_length sorter.name)))
infinity
!sorters
let build_bench_table benchs getter fmt =
let heading =
string_cell "lengths"
:: string_cell "stable"
:: list_concat_map (fun length -> [ int_cell length ; string_cell "%" ]) !lengths
in
let content =
!sorters |> List.map @@ fun sorter ->
string_cell sorter.name
:: string_cell (if sorter.stable then "yes" else "no")
:: (
!lengths |> list_concat_map @@ fun length ->
let reference = reference benchs getter length in
let result = getter (get_bench_result ~sorter ~length benchs) in
let slowdown = Format.sprintf "%.0f" (slowdown ~from:reference ~to_:result) in
[ fmt_cell (fun () -> result) ~fmt ;
string_cell (if slowdown = "0" then "" else Format.sprintf "(%s%%)" slowdown) ]
)
in
(heading, content)
let cell_styles =
("", Left)
:: (" | ", Right)
:: (List.map (fun _ -> [ (" | ", Right) ; (" ", Right) ]) !lengths
|> List.flatten)
let print_bench_table title benchs getter fmt =
let (heading, content) = build_bench_table benchs getter fmt in
print_table ~title ~cell_styles ~heading content
let () = Format.printf "Computing benchmarks on uniformly chosen arrays...@."
let benchs_unif = compute_benchs ~generator:gen_unif
let () = Format.printf "@."
let () = Format.printf "Computing benchmarks on arrays with 5 runs...@."
let benchs_5runs = compute_benchs ~generator:(gen_k_runs 5)
let () = Format.printf "@."
let () = print_bench_table "Unif - Runtime" benchs_unif (fun result -> result.runtime) "%.2f"
let () = Format.printf "@."
let () = print_bench_table "Unif - Comparisons" benchs_unif (fun result -> result.comparisons) "%.0f"
let () = Format.printf "@."
let () = print_bench_table "5-Runs - Runtime" benchs_5runs (fun result -> result.runtime) "%.2f"
let () = Format.printf "@."
let () = print_bench_table "5-Runs - Comparisons" benchs_5runs (fun result -> result.comparisons) "%.0f"
let () = Format.printf "@."
| |
d32aee3387abbf717a6e224f86672dbec7e7b004dc2f86cbd9cfd00ca8dd8c95 | puppetlabs/clj-http-client | sync_plaintext_test.clj | (ns puppetlabs.http.client.sync-plaintext-test
(:import (com.puppetlabs.http.client Sync RequestOptions SimpleRequestOptions
ResponseBodyType ClientOptions
HttpClientException)
(java.io ByteArrayInputStream InputStream)
(org.apache.http.impl.nio.client HttpAsyncClients)
(java.net ConnectException ServerSocket SocketTimeoutException URI))
(:require [clojure.test :refer :all]
[puppetlabs.http.client.test-common :refer :all]
[puppetlabs.trapperkeeper.core :as tk]
[puppetlabs.trapperkeeper.testutils.bootstrap :as testutils]
[puppetlabs.trapperkeeper.testutils.logging :as testlogging]
[puppetlabs.trapperkeeper.testutils.webserver :as testwebserver]
[puppetlabs.trapperkeeper.services.webserver.jetty9-service :as jetty9]
[puppetlabs.http.client.sync :as sync]
[puppetlabs.http.client.common :as common]
[schema.test :as schema-test]
[clojure.java.io :as io]
[ring.middleware.cookies :refer [wrap-cookies]]))
(use-fixtures :once schema-test/validate-schemas)
(defn app
[_]
{:status 200
:body "Hello, World!"})
(defn cookie-handler
[_]
{:status 200
:body "cookie has been set"
:cookies {"session_id" {:value "session-id-hash"}}})
(defn check-cookie-handler
[req]
(if (empty? (get req :cookies))
{:status 400
:body "cookie has not been set"}
{:status 200
:body "cookie has been set"}))
(tk/defservice test-web-service
[[:WebserverService add-ring-handler]]
(init [this context]
(add-ring-handler app "/hello")
context))
(tk/defservice test-cookie-service
[[:WebserverService add-ring-handler]]
(init [this context]
(add-ring-handler (wrap-cookies cookie-handler) "/cookietest")
(add-ring-handler (wrap-cookies check-cookie-handler) "/cookiecheck")
context))
(defn basic-test
[http-method java-method clj-fn]
(testing (format "sync client: HTTP method: '%s'" http-method)
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service test-web-service]
{:webserver {:port 10000}}
(testing "java sync client"
(let [request-options (SimpleRequestOptions. (URI. ":10000/hello/"))
response (java-method request-options)]
(is (= 200 (.getStatus response)))
(is (= "OK" (.getReasonPhrase response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "clojure sync client"
(let [response (clj-fn ":10000/hello/")]
(is (= 200 (:status response)))
(is (= "OK" (:reason-phrase response)))
(is (= "Hello, World!" (slurp (:body response))))))))))
(deftest sync-client-head-test
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service test-web-service]
{:webserver {:port 10000}}
(testing "java sync client"
(let [request-options (SimpleRequestOptions. (URI. ":10000/hello/"))
response (Sync/head request-options)]
(is (= 200 (.getStatus response)))
(is (= nil (.getBody response)))))
(testing "clojure sync client"
(let [response (sync/head ":10000/hello/")]
(is (= 200 (:status response)))
(is (= nil (:body response)))))
(testing "not found"
(let [response (sync/head ":10000/missing")]
(is (= 404 (:status response)))
(is (= "Not Found" (:reason-phrase response))))))))
(deftest sync-client-get-test
(basic-test "GET" #(Sync/get %) sync/get))
(deftest sync-client-post-test
(basic-test "POST" #(Sync/post %) sync/post))
(deftest sync-client-put-test
(basic-test "PUT" #(Sync/put %) sync/put))
(deftest sync-client-delete-test
(basic-test "DELETE" #(Sync/delete %) sync/delete))
(deftest sync-client-trace-test
(basic-test "TRACE" #(Sync/trace %) sync/trace))
(deftest sync-client-options-test
(basic-test "OPTIONS" #(Sync/options %) sync/options))
(deftest sync-client-patch-test
(basic-test "PATCH" #(Sync/patch %) sync/patch))
(deftest sync-client-persistent-test
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service test-web-service]
{:webserver {:port 10000}}
(testing "persistent java client"
(let [request-options (RequestOptions. ":10000/hello/")
client-options (ClientOptions.)
client (Sync/createClient client-options)]
(testing "HEAD request with persistent sync client"
(let [response (.head client request-options)]
(is (= 200 (.getStatus response)))
(is (= nil (.getBody response)))))
(testing "GET request with persistent sync client"
(let [response (.get client request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "POST request with persistent sync client"
(let [response (.post client request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "PUT request with persistent sync client"
(let [response (.put client request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "DELETE request with persistent sync client"
(let [response (.delete client request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "TRACE request with persistent sync client"
(let [response (.trace client request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "OPTIONS request with persistent sync client"
(let [response (.options client request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "PATCH request with persistent sync client"
(let [response (.patch client request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "client closes properly"
(.close client)
(is (thrown? HttpClientException
(.get client request-options))))))
(testing "persistent clojure client"
(let [client (sync/create-client {})]
(testing "HEAD request with persistent sync client"
(let [response (common/head client ":10000/hello/")]
(is (= 200 (:status response)))
(is (= nil (:body response)))))
(testing "GET request with persistent sync client"
(let [response (common/get client ":10000/hello/")]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "POST request with persistent sync client"
(let [response (common/post client ":10000/hello/")]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "PUT request with persistent sync client"
(let [response (common/put client ":10000/hello/")]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "DELETE request with persistent sync client"
(let [response (common/delete client ":10000/hello/")]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "TRACE request with persistent sync client"
(let [response (common/trace client ":10000/hello/")]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "OPTIONS request with persistent sync client"
(let [response (common/options client ":10000/hello/")]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "PATCH request with persistent sync client"
(let [response (common/patch client ":10000/hello/")]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "GET request via request function with persistent sync client"
(let [response (common/make-request client ":10000/hello/" :get)]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "Bad verb request via request function with persistent sync client"
(is (thrown? IllegalArgumentException
(common/make-request client
":10000/hello/"
:bad))))
(testing "client closes properly"
(common/close client)
(is (thrown? IllegalStateException
(common/get client
":10000/hello")))))))))
(deftest sync-client-as-test
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service test-web-service]
{:webserver {:port 10000}}
(testing "java sync client: :as unspecified"
(let [request-options (SimpleRequestOptions. (URI. ":10000/hello/"))
response (Sync/get request-options)]
(is (= 200 (.getStatus response)))
(is (instance? InputStream (.getBody response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "java sync client: :as :stream"
(let [request-options (.. (SimpleRequestOptions. (URI. ":10000/hello/"))
(setAs ResponseBodyType/STREAM))
response (Sync/get request-options)]
(is (= 200 (.getStatus response)))
(is (instance? InputStream (.getBody response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "java sync client: :as :text"
(let [request-options (.. (SimpleRequestOptions. (URI. ":10000/hello/"))
(setAs ResponseBodyType/TEXT))
response (Sync/get request-options)]
(is (= 200 (.getStatus response)))
(is (string? (.getBody response)))
(is (= "Hello, World!" (.getBody response)))))
(testing "clojure sync client: :as unspecified"
(let [response (sync/get ":10000/hello/")]
(is (= 200 (:status response)))
(is (instance? InputStream (:body response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "clojure sync client: :as :stream"
(let [response (sync/get ":10000/hello/" {:as :stream})]
(is (= 200 (:status response)))
(is (instance? InputStream (:body response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "clojure sync client: :as :text"
(let [response (sync/get ":10000/hello/" {:as :text})]
(is (= 200 (:status response)))
(is (string? (:body response)))
(is (= "Hello, World!" (:body response))))))))
(deftest request-with-client-test
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service test-web-service]
{:webserver {:port 10000}}
(let [client (HttpAsyncClients/createDefault)
opts {:method :get :url ":10000/hello/"}]
(.start client)
(testing "GET request works with request-with-client"
(let [response (sync/request-with-client opts client)]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "Client persists when passed to request-with-client"
(let [response (sync/request-with-client opts client)]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(.close client)))))
(deftest java-api-cookie-test
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service test-cookie-service]
{:webserver {:port 10000}}
(let [client (Sync/createClient (ClientOptions.))]
(testing "Set a cookie using Java API"
(let [response (.get client (RequestOptions. ":10000/cookietest"))]
(is (= 200 (.getStatus response)))))
(testing "Check if cookie still exists"
(let [response (.get client (RequestOptions. ":10000/cookiecheck"))]
(is (= 200 (.getStatus response)))))))))
(deftest clj-api-cookie-test
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service test-cookie-service]
{:webserver {:port 10000}}
(let [client (sync/create-client {})]
(testing "Set a cookie using Clojure API"
(let [response (common/get client ":10000/cookietest")]
(is (= 200 (:status response)))))
(testing "Check if cookie still exists"
(let [response (common/get client ":10000/cookiecheck")]
(is (= 200 (:status response)))))))))
(defn header-app
[req]
(let [val (get-in req [:headers "fooheader"])]
{:status 200
:headers {"myrespheader" val}
:body val}))
(tk/defservice test-header-web-service
[[:WebserverService add-ring-handler]]
(init [this context]
(add-ring-handler header-app "/hello")
context))
(deftest sync-client-request-headers-test
(testlogging/with-test-logging
(testutils/with-app-with-config header-app
[jetty9/jetty9-service test-header-web-service]
{:webserver {:port 10000}}
(testing "java sync client"
(let [request-options (-> (SimpleRequestOptions. (URI. ":10000/hello/"))
(.setHeaders {"fooheader" "foo"}))
response (Sync/post request-options)]
(is (= 200 (.getStatus response)))
(is (= "foo" (slurp (.getBody response))))
(is (= "foo" (-> (.getHeaders response) (.get "myrespheader"))))))
(testing "clojure sync client"
(let [response (sync/post ":10000/hello/" {:headers {"fooheader" "foo"}})]
(is (= 200 (:status response)))
(is (= "foo" (slurp (:body response))))
(is (= "foo" (get-in response [:headers "myrespheader"]))))))))
(defn req-body-app
[req]
{:status 200
:headers (if-let [content-type (:content-type req)]
{"Content-Type" (:content-type req)})
:body (slurp (:body req))})
(tk/defservice test-body-web-service
[[:WebserverService add-ring-handler]]
(init [this context]
(add-ring-handler req-body-app "/hello")
context))
(defn- validate-java-request
[body-to-send headers-to-send expected-content-type expected-response-body]
(let [request-options (-> (SimpleRequestOptions. (URI. ":10000/hello/"))
(.setBody body-to-send)
(.setHeaders headers-to-send))
response (Sync/post request-options)]
(is (= 200 (.getStatus response)))
(is (= (-> (.getHeaders response)
(.get "content-type"))
expected-content-type))
(is (= expected-response-body (slurp (.getBody response))))))
(defn- validate-clj-request
[body-to-send headers-to-send expected-content-type expected-response-body]
(let [response (sync/post ":10000/hello/"
{:body body-to-send
:headers headers-to-send})]
(is (= 200 (:status response)))
(is (= (get-in response [:headers "content-type"])
expected-content-type))
(is (= expected-response-body (slurp (:body response))))))
(deftest sync-client-request-body-test
(testlogging/with-test-logging
(testutils/with-app-with-config req-body-app
[jetty9/jetty9-service test-body-web-service]
{:webserver {:port 10000}}
(testing "java sync client: string body for post request with explicit
content type and UTF-8 encoding uses UTF-8 encoding"
(validate-java-request "foo�"
{"Content-Type" "text/plain; charset=utf-8"}
"text/plain;charset=utf-8"
"foo�"))
(testing "java sync client: string body for post request with explicit
content type and ISO-8859-1 encoding uses ISO-8859-1 encoding"
(validate-java-request "foo�"
{"Content-Type" "text/plain; charset=iso-8859-1"}
"text/plain;charset=iso-8859-1"
"foo?"))
(testing "java sync client: string body for post request with explicit
content type but without explicit encoding uses UTF-8 encoding"
(validate-java-request "foo�"
{"Content-Type" "text/plain"}
"text/plain;charset=utf-8"
"foo�"))
(testing "java sync client: string body for post request without explicit
content or encoding uses ISO-8859-1 encoding"
(validate-java-request "foo�"
nil
"text/plain;charset=iso-8859-1"
"foo?"))
(testing "java sync client: input stream body for post request"
(let [request-options (-> (SimpleRequestOptions. (URI. ":10000/hello/"))
(.setBody (ByteArrayInputStream.
(.getBytes "foo�" "UTF-8")))
(.setHeaders {"Content-Type"
"text/plain; charset=UTF-8"}))
response (Sync/post request-options)]
(is (= 200 (.getStatus response)))
(is (= "foo�" (slurp (.getBody response))))))
(testing "clojure sync client: string body for post request with explicit
content type and UTF-8 encoding uses UTF-8 encoding"
(validate-clj-request "foo�"
{"content-type" "text/plain; charset=utf-8"}
"text/plain;charset=utf-8"
"foo�"))
(testing "clojure sync client: string body for post request with explicit
content type and ISO-8859 encoding uses ISO-8859-1 encoding"
(validate-clj-request "foo�"
{"content-type" "text/plain; charset=iso-8859-1"}
"text/plain;charset=iso-8859-1"
"foo?"))
(testing "clojure sync client: string body for post request with explicit
content type but without explicit encoding uses UTF-8 encoding"
(validate-clj-request "foo�"
{"content-type" "text/plain"}
"text/plain;charset=utf-8"
"foo�"))
(testing "clojure sync client: string body for post request without explicit
content type or encoding uses ISO-8859-1 encoding"
(validate-clj-request "foo�"
{}
"text/plain;charset=iso-8859-1"
"foo?"))
(testing "clojure sync client: input stream body for post request"
(let [response (sync/post ":10000/hello/"
{:body (io/input-stream
(.getBytes "foo�" "UTF-8"))
:headers {"content-type"
"text/plain; charset=UTF-8"}})]
(is (= 200 (:status response)))
(is (= "foo�" (slurp (:body response)))))))))
(def compressible-body (apply str (repeat 1000 "f")))
(defn compression-app
[req]
{:status 200
:headers {"orig-accept-encoding" (get-in req [:headers "accept-encoding"])
"content-type" "text/plain"
"charset" "UTF-8"}
:body compressible-body})
(tk/defservice test-compression-web-service
[[:WebserverService add-ring-handler]]
(init [this context]
(add-ring-handler compression-app "/hello")
context))
(defn test-compression
[desc opts accept-encoding content-encoding content-should-match?]
(testlogging/with-test-logging
(testutils/with-app-with-config req-body-app
[jetty9/jetty9-service test-compression-web-service]
{:webserver {:port 10000}}
(testing (str "java sync client: compression headers / response: " desc)
(let [request-opts (cond-> (SimpleRequestOptions. (URI. ":10000/hello/"))
(contains? opts :decompress-body) (.setDecompressBody (:decompress-body opts))
(contains? opts :headers) (.setHeaders (:headers opts)))
response (Sync/get request-opts)]
(is (= 200 (.getStatus response)))
(is (= accept-encoding (.. response getHeaders (get "orig-accept-encoding"))))
(is (= content-encoding (.. response getOrigContentEncoding)))
(if content-should-match?
(is (= compressible-body (slurp (.getBody response))))
(is (not= compressible-body (slurp (.getBody response)))))))
(testing (str "clojure sync client: compression headers / response: " desc)
(let [response (sync/post ":10000/hello/" opts)]
(is (= 200 (:status response)))
(is (= accept-encoding (get-in response [:headers "orig-accept-encoding"])))
(is (= content-encoding (:orig-content-encoding response)))
(if content-should-match?
(is (= compressible-body (slurp (:body response))))
(is (not= compressible-body (slurp (:body response))))))))))
(deftest sync-client-compression-test
(test-compression "default" {} "gzip, deflate" "gzip" true))
(deftest sync-client-compression-gzip-test
(test-compression "explicit gzip" {:headers {"accept-encoding" "gzip"}} "gzip" "gzip" true))
(deftest sync-client-compression-disabled-test
(test-compression "explicit disable" {:decompress-body false} nil nil true))
(deftest sync-client-decompression-disabled-test
(test-compression "explicit disable" {:headers {"accept-encoding" "gzip"}
:decompress-body false} "gzip" "gzip" false))
(deftest query-params-test-sync
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service test-params-web-service]
{:webserver {:port 8080}}
(testing "URL Query Parameters work with the Java client"
(let [request-options (SimpleRequestOptions. (URI. ":8080/params?foo=bar&baz=lux"))]
(let [response (Sync/get request-options)]
(is (= 200 (.getStatus response)))
(is (= queryparams (read-string (slurp (.getBody response))))))))
(testing "URL Query Parameters work with the clojure client"
(let [opts {:method :get
:url ":8080/params/"
:query-params queryparams
:as :text}
response (sync/get ":8080/params" opts)]
(is (= 200 (:status response)))
(is (= queryparams (read-string (:body response)))))))))
(deftest redirect-test-sync
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service redirect-web-service]
{:webserver {:port 8080}}
(testing (str "redirects on POST not followed by Java client "
"when forceRedirects option not set to true")
(let [request-options (SimpleRequestOptions. (URI. ":8080/hello"))
response (Sync/post request-options)]
(is (= 302 (.getStatus response)))))
(testing "redirects on POST followed by Java client when option is set"
(let [request-options (.. (SimpleRequestOptions. (URI. ":8080/hello"))
(setForceRedirects true))
response (Sync/post request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "redirects not followed by Java client when :follow-redirects is false"
(let [request-options (.. (SimpleRequestOptions. (URI. ":8080/hello"))
(setFollowRedirects false))
response (Sync/get request-options)]
(is (= 302 (.getStatus response)))))
(testing ":follow-redirects overrides :force-redirects for Java client"
(let [request-options (.. (SimpleRequestOptions. (URI. ":8080/hello"))
(setFollowRedirects false)
(setForceRedirects true))
response (Sync/get request-options)]
(is (= 302 (.getStatus response)))))
(testing (str "redirects on POST not followed by clojure client "
"when :force-redirects is not set to true")
(let [opts {:method :post
:url ":8080/hello"
:as :text
:force-redirects false}
response (sync/post ":8080/hello" opts)]
(is (= 302 (:status response)))))
(testing "redirects on POST followed by clojure client when option is set"
(let [opts {:method :post
:url ":8080/hello"
:as :text
:force-redirects true}
response (sync/post ":8080/hello" opts)]
(is (= 200 (:status response)))
(is (= "Hello, World!" (:body response)))))
(testing (str "redirects not followed by clojure client when :follow-redirects "
"is set to false")
(let [response (sync/get ":8080/hello" {:as :text
:follow-redirects false})]
(is (= 302 (:status response)))))
(testing ":follow-redirects overrides :force-redirects with clojure client"
(let [response (sync/get ":8080/hello" {:as :text
:follow-redirects false
:force-redirects true})]
(is (= 302 (:status response)))))
(testing (str "redirects on POST followed by persistent clojure client "
"when option is set")
(let [client (sync/create-client {:force-redirects true})
response (common/post client ":8080/hello" {:as :text})]
(is (= 200 (:status response)))
(is (= "Hello, World!" (:body response)))
(common/close client)))
(testing (str "persistent clojure client does not follow redirects when "
":follow-redirects is set to false")
(let [client (sync/create-client {:follow-redirects false})
response (common/get client ":8080/hello" {:as :text})]
(is (= 302 (:status response)))
(common/close client)))
(testing ":follow-redirects overrides :force-redirects with persistent clj client"
(let [client (sync/create-client {:follow-redirects false
:force-redirects true})
response (common/get client ":8080/hello" {:as :text})]
(is (= 302 (:status response)))
(common/close client))))))
(defmacro wrapped-connect-exception-thrown?
[& body]
`(try
(testlogging/with-test-logging ~@body)
(throw (IllegalStateException.
"Expected HttpClientException but none thrown!"))
(catch HttpClientException e#
(if-let [cause# (.getCause e#)]
(or (instance? SocketTimeoutException cause#)
(instance? ConnectException cause#)
(throw (IllegalStateException.
(str
"Expected SocketTimeoutException or ConnectException "
"cause but found: " cause#))))
(throw (IllegalStateException.
(str
"Expected SocketTimeoutException or ConnectException but "
"no cause found. Message:" (.getMessage e#))))))))
(defmacro wrapped-timeout-exception-thrown?
[& body]
`(try
(testlogging/with-test-logging ~@body)
(throw (IllegalStateException.
"Expected HttpClientException but none thrown!"))
(catch HttpClientException e#
(if-let [cause# (.getCause e#)]
(or (instance? SocketTimeoutException cause#)
(throw (IllegalStateException.
(str
"Expected SocketTimeoutException cause but found: "
cause#))))
(throw (IllegalStateException.
(str
"Expected SocketTimeoutException but no cause found. "
"Message: " (.getMessage e#))))))))
(deftest short-connect-timeout-nonpersistent-java-test-sync
(testing (str "connection times out properly for non-persistent java sync "
"request with short timeout")
(let [request-options (-> ":65535"
(SimpleRequestOptions.)
(.setConnectTimeoutMilliseconds 250))
time-before-connect (System/currentTimeMillis)]
(is (wrapped-connect-exception-thrown?
(Sync/get request-options))
"Unexpected result for connection attempt")
(is (elapsed-within-range? time-before-connect 2000)
"Connection attempt took significantly longer than timeout"))))
(deftest short-connect-timeout-persistent-java-test-sync
(testing (str "connection times out properly for java persistent client sync "
"request with short timeout")
(with-open [client (-> (ClientOptions.)
(.setConnectTimeoutMilliseconds 250)
(Sync/createClient))]
(let [request-options (RequestOptions. ":65535")
time-before-connect (System/currentTimeMillis)]
(is (wrapped-connect-exception-thrown?
(.get client request-options))
"Unexpected result for connection attempt")
(is (elapsed-within-range? time-before-connect 2000)
"Connection attempt took significantly longer than timeout")))))
(deftest short-connect-timeout-nonpersistent-clojure-test-sync
(testing (str "connection times out properly for non-persistent clojure sync "
"request with short timeout")
(let [time-before-connect (System/currentTimeMillis)]
(is (connect-exception-thrown?
(sync/get ":65535"
{:connect-timeout-milliseconds 250}))
"Unexpected result for connection attempt")
(is (elapsed-within-range? time-before-connect 2000)
"Connection attempt took significantly longer than timeout"))))
(deftest short-connect-timeout-persistent-clojure-test-sync
(testing (str "connection times out properly for clojure persistent client "
"sync request with short timeout")
(with-open [client (sync/create-client
{:connect-timeout-milliseconds 250})]
(let [time-before-connect (System/currentTimeMillis)]
(is (connect-exception-thrown?
(common/get client ":65535"))
"Unexpected result for connection attempt")
(is (elapsed-within-range? time-before-connect 2000)
"Connection attempt took significantly longer than timeout")))))
(deftest longer-connect-timeout-test-sync
(testing "connection succeeds for sync request with longer connect timeout"
(testlogging/with-test-logging
(testwebserver/with-test-webserver app port
(let [url (str ":" port "/hello")]
(testing "java non-persistent sync client"
(let [request-options (.. (SimpleRequestOptions. url)
(setConnectTimeoutMilliseconds 2000))
response (Sync/get request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "java persistent sync client"
(with-open [client (-> (ClientOptions.)
(.setConnectTimeoutMilliseconds 2000)
(Sync/createClient))]
(let [response (.get client (RequestOptions. url))]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response)))))))
(testing "clojure non-persistent sync client"
(let [response (sync/get url
{:as :text
:connect-timeout-milliseconds 2000})]
(is (= 200 (:status response)))
(is (= "Hello, World!" (:body response)))))
(testing "clojure persistent sync client"
(with-open [client (sync/create-client
{:connect-timeout-milliseconds 2000})]
(let [response (common/get client url {:as :text})]
(is (= 200 (:status response)))
(is (= "Hello, World!" (:body response)))))))))))
(deftest short-socket-timeout-nonpersistent-java-test-sync
(testing (str "socket read times out properly for non-persistent java sync "
"request with short timeout")
(with-open [server (ServerSocket. 0)]
(let [request-options (-> ":"
(str (.getLocalPort server))
(SimpleRequestOptions.)
(.setSocketTimeoutMilliseconds 250))
time-before-connect (System/currentTimeMillis)]
(is (wrapped-timeout-exception-thrown? (Sync/get request-options))
"Unexpected result for get attempt")
(is (elapsed-within-range? time-before-connect 2000)
"Get attempt took significantly longer than timeout")))))
(deftest short-socket-timeout-persistent-java-test-sync
(testing (str "socket read times out properly for persistent java sync "
"request with short timeout")
(with-open [client (-> (ClientOptions.)
(.setSocketTimeoutMilliseconds 250)
(Sync/createClient))
server (ServerSocket. 0)]
(let [request-options (-> ":"
(str (.getLocalPort server))
(RequestOptions.))
time-before-connect (System/currentTimeMillis)]
(is (wrapped-timeout-exception-thrown? (.get client request-options))
"Unexpected result for get attempt")
(is (elapsed-within-range? time-before-connect 2000)
"Get attempt took significantly longer than timeout")))))
(deftest short-socket-timeout-nonpersistent-clojure-test-sync
(testing (str "socket read times out properly for non-persistent clojure "
"sync request with short timeout")
(with-open [server (ServerSocket. 0)]
(let [url (str ":" (.getLocalPort server))
time-before-connect (System/currentTimeMillis)]
(is (thrown? SocketTimeoutException
(sync/get url {:socket-timeout-milliseconds 250}))
"Unexpected result for get attempt")
(is (elapsed-within-range? time-before-connect 2000)
"Get attempt took significantly longer than timeout")))))
(deftest short-socket-timeout-persistent-clojure-test-sync
(testing (str "socket read times out properly for clojure persistent client "
"sync request with short timeout")
(with-open [client (sync/create-client
{:socket-timeout-milliseconds 250})
server (ServerSocket. 0)]
(let [url (str ":" (.getLocalPort server))
time-before-connect (System/currentTimeMillis)]
(is (thrown? SocketTimeoutException (common/get client url))
"Unexpected result for get attempt")
(is (elapsed-within-range? time-before-connect 2000)
"Get attempt took significantly longer than timeout")))))
(deftest longer-socket-timeout-test-sync
(testing "get succeeds for sync request with longer socket timeout"
(testlogging/with-test-logging
(testwebserver/with-test-webserver app port
(let [url (str ":" port "/hello")]
(testing "java non-persistent sync client"
(let [request-options (.. (SimpleRequestOptions. url)
(setSocketTimeoutMilliseconds 2000))
response (Sync/get request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "java persistent sync client"
(with-open [client (-> (ClientOptions.)
(.setSocketTimeoutMilliseconds 2000)
(Sync/createClient))]
(let [response (.get client (RequestOptions. url))]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response)))))))
(testing "clojure non-persistent sync client"
(let [response (sync/get url
{:as :text
:socket-timeout-milliseconds 2000})]
(is (= 200 (:status response)))
(is (= "Hello, World!" (:body response)))))
(testing "clojure persistent sync client"
(with-open [client (sync/create-client
{:socket-timeout-milliseconds 2000})]
(let [response (common/get client url {:as :text})]
(is (= 200 (:status response)))
(is (= "Hello, World!" (:body response)))))))))))
| null | https://raw.githubusercontent.com/puppetlabs/clj-http-client/93b0264446f5bf70a575912f574f9dec77a58bf8/test/puppetlabs/http/client/sync_plaintext_test.clj | clojure | (ns puppetlabs.http.client.sync-plaintext-test
(:import (com.puppetlabs.http.client Sync RequestOptions SimpleRequestOptions
ResponseBodyType ClientOptions
HttpClientException)
(java.io ByteArrayInputStream InputStream)
(org.apache.http.impl.nio.client HttpAsyncClients)
(java.net ConnectException ServerSocket SocketTimeoutException URI))
(:require [clojure.test :refer :all]
[puppetlabs.http.client.test-common :refer :all]
[puppetlabs.trapperkeeper.core :as tk]
[puppetlabs.trapperkeeper.testutils.bootstrap :as testutils]
[puppetlabs.trapperkeeper.testutils.logging :as testlogging]
[puppetlabs.trapperkeeper.testutils.webserver :as testwebserver]
[puppetlabs.trapperkeeper.services.webserver.jetty9-service :as jetty9]
[puppetlabs.http.client.sync :as sync]
[puppetlabs.http.client.common :as common]
[schema.test :as schema-test]
[clojure.java.io :as io]
[ring.middleware.cookies :refer [wrap-cookies]]))
(use-fixtures :once schema-test/validate-schemas)
(defn app
[_]
{:status 200
:body "Hello, World!"})
(defn cookie-handler
[_]
{:status 200
:body "cookie has been set"
:cookies {"session_id" {:value "session-id-hash"}}})
(defn check-cookie-handler
[req]
(if (empty? (get req :cookies))
{:status 400
:body "cookie has not been set"}
{:status 200
:body "cookie has been set"}))
(tk/defservice test-web-service
[[:WebserverService add-ring-handler]]
(init [this context]
(add-ring-handler app "/hello")
context))
(tk/defservice test-cookie-service
[[:WebserverService add-ring-handler]]
(init [this context]
(add-ring-handler (wrap-cookies cookie-handler) "/cookietest")
(add-ring-handler (wrap-cookies check-cookie-handler) "/cookiecheck")
context))
(defn basic-test
[http-method java-method clj-fn]
(testing (format "sync client: HTTP method: '%s'" http-method)
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service test-web-service]
{:webserver {:port 10000}}
(testing "java sync client"
(let [request-options (SimpleRequestOptions. (URI. ":10000/hello/"))
response (java-method request-options)]
(is (= 200 (.getStatus response)))
(is (= "OK" (.getReasonPhrase response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "clojure sync client"
(let [response (clj-fn ":10000/hello/")]
(is (= 200 (:status response)))
(is (= "OK" (:reason-phrase response)))
(is (= "Hello, World!" (slurp (:body response))))))))))
(deftest sync-client-head-test
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service test-web-service]
{:webserver {:port 10000}}
(testing "java sync client"
(let [request-options (SimpleRequestOptions. (URI. ":10000/hello/"))
response (Sync/head request-options)]
(is (= 200 (.getStatus response)))
(is (= nil (.getBody response)))))
(testing "clojure sync client"
(let [response (sync/head ":10000/hello/")]
(is (= 200 (:status response)))
(is (= nil (:body response)))))
(testing "not found"
(let [response (sync/head ":10000/missing")]
(is (= 404 (:status response)))
(is (= "Not Found" (:reason-phrase response))))))))
(deftest sync-client-get-test
(basic-test "GET" #(Sync/get %) sync/get))
(deftest sync-client-post-test
(basic-test "POST" #(Sync/post %) sync/post))
(deftest sync-client-put-test
(basic-test "PUT" #(Sync/put %) sync/put))
(deftest sync-client-delete-test
(basic-test "DELETE" #(Sync/delete %) sync/delete))
(deftest sync-client-trace-test
(basic-test "TRACE" #(Sync/trace %) sync/trace))
(deftest sync-client-options-test
(basic-test "OPTIONS" #(Sync/options %) sync/options))
(deftest sync-client-patch-test
(basic-test "PATCH" #(Sync/patch %) sync/patch))
(deftest sync-client-persistent-test
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service test-web-service]
{:webserver {:port 10000}}
(testing "persistent java client"
(let [request-options (RequestOptions. ":10000/hello/")
client-options (ClientOptions.)
client (Sync/createClient client-options)]
(testing "HEAD request with persistent sync client"
(let [response (.head client request-options)]
(is (= 200 (.getStatus response)))
(is (= nil (.getBody response)))))
(testing "GET request with persistent sync client"
(let [response (.get client request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "POST request with persistent sync client"
(let [response (.post client request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "PUT request with persistent sync client"
(let [response (.put client request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "DELETE request with persistent sync client"
(let [response (.delete client request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "TRACE request with persistent sync client"
(let [response (.trace client request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "OPTIONS request with persistent sync client"
(let [response (.options client request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "PATCH request with persistent sync client"
(let [response (.patch client request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "client closes properly"
(.close client)
(is (thrown? HttpClientException
(.get client request-options))))))
(testing "persistent clojure client"
(let [client (sync/create-client {})]
(testing "HEAD request with persistent sync client"
(let [response (common/head client ":10000/hello/")]
(is (= 200 (:status response)))
(is (= nil (:body response)))))
(testing "GET request with persistent sync client"
(let [response (common/get client ":10000/hello/")]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "POST request with persistent sync client"
(let [response (common/post client ":10000/hello/")]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "PUT request with persistent sync client"
(let [response (common/put client ":10000/hello/")]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "DELETE request with persistent sync client"
(let [response (common/delete client ":10000/hello/")]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "TRACE request with persistent sync client"
(let [response (common/trace client ":10000/hello/")]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "OPTIONS request with persistent sync client"
(let [response (common/options client ":10000/hello/")]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "PATCH request with persistent sync client"
(let [response (common/patch client ":10000/hello/")]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "GET request via request function with persistent sync client"
(let [response (common/make-request client ":10000/hello/" :get)]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "Bad verb request via request function with persistent sync client"
(is (thrown? IllegalArgumentException
(common/make-request client
":10000/hello/"
:bad))))
(testing "client closes properly"
(common/close client)
(is (thrown? IllegalStateException
(common/get client
":10000/hello")))))))))
(deftest sync-client-as-test
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service test-web-service]
{:webserver {:port 10000}}
(testing "java sync client: :as unspecified"
(let [request-options (SimpleRequestOptions. (URI. ":10000/hello/"))
response (Sync/get request-options)]
(is (= 200 (.getStatus response)))
(is (instance? InputStream (.getBody response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "java sync client: :as :stream"
(let [request-options (.. (SimpleRequestOptions. (URI. ":10000/hello/"))
(setAs ResponseBodyType/STREAM))
response (Sync/get request-options)]
(is (= 200 (.getStatus response)))
(is (instance? InputStream (.getBody response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "java sync client: :as :text"
(let [request-options (.. (SimpleRequestOptions. (URI. ":10000/hello/"))
(setAs ResponseBodyType/TEXT))
response (Sync/get request-options)]
(is (= 200 (.getStatus response)))
(is (string? (.getBody response)))
(is (= "Hello, World!" (.getBody response)))))
(testing "clojure sync client: :as unspecified"
(let [response (sync/get ":10000/hello/")]
(is (= 200 (:status response)))
(is (instance? InputStream (:body response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "clojure sync client: :as :stream"
(let [response (sync/get ":10000/hello/" {:as :stream})]
(is (= 200 (:status response)))
(is (instance? InputStream (:body response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "clojure sync client: :as :text"
(let [response (sync/get ":10000/hello/" {:as :text})]
(is (= 200 (:status response)))
(is (string? (:body response)))
(is (= "Hello, World!" (:body response))))))))
(deftest request-with-client-test
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service test-web-service]
{:webserver {:port 10000}}
(let [client (HttpAsyncClients/createDefault)
opts {:method :get :url ":10000/hello/"}]
(.start client)
(testing "GET request works with request-with-client"
(let [response (sync/request-with-client opts client)]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(testing "Client persists when passed to request-with-client"
(let [response (sync/request-with-client opts client)]
(is (= 200 (:status response)))
(is (= "Hello, World!" (slurp (:body response))))))
(.close client)))))
(deftest java-api-cookie-test
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service test-cookie-service]
{:webserver {:port 10000}}
(let [client (Sync/createClient (ClientOptions.))]
(testing "Set a cookie using Java API"
(let [response (.get client (RequestOptions. ":10000/cookietest"))]
(is (= 200 (.getStatus response)))))
(testing "Check if cookie still exists"
(let [response (.get client (RequestOptions. ":10000/cookiecheck"))]
(is (= 200 (.getStatus response)))))))))
(deftest clj-api-cookie-test
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service test-cookie-service]
{:webserver {:port 10000}}
(let [client (sync/create-client {})]
(testing "Set a cookie using Clojure API"
(let [response (common/get client ":10000/cookietest")]
(is (= 200 (:status response)))))
(testing "Check if cookie still exists"
(let [response (common/get client ":10000/cookiecheck")]
(is (= 200 (:status response)))))))))
(defn header-app
[req]
(let [val (get-in req [:headers "fooheader"])]
{:status 200
:headers {"myrespheader" val}
:body val}))
(tk/defservice test-header-web-service
[[:WebserverService add-ring-handler]]
(init [this context]
(add-ring-handler header-app "/hello")
context))
(deftest sync-client-request-headers-test
(testlogging/with-test-logging
(testutils/with-app-with-config header-app
[jetty9/jetty9-service test-header-web-service]
{:webserver {:port 10000}}
(testing "java sync client"
(let [request-options (-> (SimpleRequestOptions. (URI. ":10000/hello/"))
(.setHeaders {"fooheader" "foo"}))
response (Sync/post request-options)]
(is (= 200 (.getStatus response)))
(is (= "foo" (slurp (.getBody response))))
(is (= "foo" (-> (.getHeaders response) (.get "myrespheader"))))))
(testing "clojure sync client"
(let [response (sync/post ":10000/hello/" {:headers {"fooheader" "foo"}})]
(is (= 200 (:status response)))
(is (= "foo" (slurp (:body response))))
(is (= "foo" (get-in response [:headers "myrespheader"]))))))))
(defn req-body-app
[req]
{:status 200
:headers (if-let [content-type (:content-type req)]
{"Content-Type" (:content-type req)})
:body (slurp (:body req))})
(tk/defservice test-body-web-service
[[:WebserverService add-ring-handler]]
(init [this context]
(add-ring-handler req-body-app "/hello")
context))
(defn- validate-java-request
[body-to-send headers-to-send expected-content-type expected-response-body]
(let [request-options (-> (SimpleRequestOptions. (URI. ":10000/hello/"))
(.setBody body-to-send)
(.setHeaders headers-to-send))
response (Sync/post request-options)]
(is (= 200 (.getStatus response)))
(is (= (-> (.getHeaders response)
(.get "content-type"))
expected-content-type))
(is (= expected-response-body (slurp (.getBody response))))))
(defn- validate-clj-request
[body-to-send headers-to-send expected-content-type expected-response-body]
(let [response (sync/post ":10000/hello/"
{:body body-to-send
:headers headers-to-send})]
(is (= 200 (:status response)))
(is (= (get-in response [:headers "content-type"])
expected-content-type))
(is (= expected-response-body (slurp (:body response))))))
(deftest sync-client-request-body-test
(testlogging/with-test-logging
(testutils/with-app-with-config req-body-app
[jetty9/jetty9-service test-body-web-service]
{:webserver {:port 10000}}
(testing "java sync client: string body for post request with explicit
content type and UTF-8 encoding uses UTF-8 encoding"
(validate-java-request "foo�"
{"Content-Type" "text/plain; charset=utf-8"}
"text/plain;charset=utf-8"
"foo�"))
(testing "java sync client: string body for post request with explicit
content type and ISO-8859-1 encoding uses ISO-8859-1 encoding"
(validate-java-request "foo�"
{"Content-Type" "text/plain; charset=iso-8859-1"}
"text/plain;charset=iso-8859-1"
"foo?"))
(testing "java sync client: string body for post request with explicit
content type but without explicit encoding uses UTF-8 encoding"
(validate-java-request "foo�"
{"Content-Type" "text/plain"}
"text/plain;charset=utf-8"
"foo�"))
(testing "java sync client: string body for post request without explicit
content or encoding uses ISO-8859-1 encoding"
(validate-java-request "foo�"
nil
"text/plain;charset=iso-8859-1"
"foo?"))
(testing "java sync client: input stream body for post request"
(let [request-options (-> (SimpleRequestOptions. (URI. ":10000/hello/"))
(.setBody (ByteArrayInputStream.
(.getBytes "foo�" "UTF-8")))
(.setHeaders {"Content-Type"
"text/plain; charset=UTF-8"}))
response (Sync/post request-options)]
(is (= 200 (.getStatus response)))
(is (= "foo�" (slurp (.getBody response))))))
(testing "clojure sync client: string body for post request with explicit
content type and UTF-8 encoding uses UTF-8 encoding"
(validate-clj-request "foo�"
{"content-type" "text/plain; charset=utf-8"}
"text/plain;charset=utf-8"
"foo�"))
(testing "clojure sync client: string body for post request with explicit
content type and ISO-8859 encoding uses ISO-8859-1 encoding"
(validate-clj-request "foo�"
{"content-type" "text/plain; charset=iso-8859-1"}
"text/plain;charset=iso-8859-1"
"foo?"))
(testing "clojure sync client: string body for post request with explicit
content type but without explicit encoding uses UTF-8 encoding"
(validate-clj-request "foo�"
{"content-type" "text/plain"}
"text/plain;charset=utf-8"
"foo�"))
(testing "clojure sync client: string body for post request without explicit
content type or encoding uses ISO-8859-1 encoding"
(validate-clj-request "foo�"
{}
"text/plain;charset=iso-8859-1"
"foo?"))
(testing "clojure sync client: input stream body for post request"
(let [response (sync/post ":10000/hello/"
{:body (io/input-stream
(.getBytes "foo�" "UTF-8"))
:headers {"content-type"
"text/plain; charset=UTF-8"}})]
(is (= 200 (:status response)))
(is (= "foo�" (slurp (:body response)))))))))
(def compressible-body (apply str (repeat 1000 "f")))
(defn compression-app
[req]
{:status 200
:headers {"orig-accept-encoding" (get-in req [:headers "accept-encoding"])
"content-type" "text/plain"
"charset" "UTF-8"}
:body compressible-body})
(tk/defservice test-compression-web-service
[[:WebserverService add-ring-handler]]
(init [this context]
(add-ring-handler compression-app "/hello")
context))
(defn test-compression
[desc opts accept-encoding content-encoding content-should-match?]
(testlogging/with-test-logging
(testutils/with-app-with-config req-body-app
[jetty9/jetty9-service test-compression-web-service]
{:webserver {:port 10000}}
(testing (str "java sync client: compression headers / response: " desc)
(let [request-opts (cond-> (SimpleRequestOptions. (URI. ":10000/hello/"))
(contains? opts :decompress-body) (.setDecompressBody (:decompress-body opts))
(contains? opts :headers) (.setHeaders (:headers opts)))
response (Sync/get request-opts)]
(is (= 200 (.getStatus response)))
(is (= accept-encoding (.. response getHeaders (get "orig-accept-encoding"))))
(is (= content-encoding (.. response getOrigContentEncoding)))
(if content-should-match?
(is (= compressible-body (slurp (.getBody response))))
(is (not= compressible-body (slurp (.getBody response)))))))
(testing (str "clojure sync client: compression headers / response: " desc)
(let [response (sync/post ":10000/hello/" opts)]
(is (= 200 (:status response)))
(is (= accept-encoding (get-in response [:headers "orig-accept-encoding"])))
(is (= content-encoding (:orig-content-encoding response)))
(if content-should-match?
(is (= compressible-body (slurp (:body response))))
(is (not= compressible-body (slurp (:body response))))))))))
(deftest sync-client-compression-test
(test-compression "default" {} "gzip, deflate" "gzip" true))
(deftest sync-client-compression-gzip-test
(test-compression "explicit gzip" {:headers {"accept-encoding" "gzip"}} "gzip" "gzip" true))
(deftest sync-client-compression-disabled-test
(test-compression "explicit disable" {:decompress-body false} nil nil true))
(deftest sync-client-decompression-disabled-test
(test-compression "explicit disable" {:headers {"accept-encoding" "gzip"}
:decompress-body false} "gzip" "gzip" false))
(deftest query-params-test-sync
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service test-params-web-service]
{:webserver {:port 8080}}
(testing "URL Query Parameters work with the Java client"
(let [request-options (SimpleRequestOptions. (URI. ":8080/params?foo=bar&baz=lux"))]
(let [response (Sync/get request-options)]
(is (= 200 (.getStatus response)))
(is (= queryparams (read-string (slurp (.getBody response))))))))
(testing "URL Query Parameters work with the clojure client"
(let [opts {:method :get
:url ":8080/params/"
:query-params queryparams
:as :text}
response (sync/get ":8080/params" opts)]
(is (= 200 (:status response)))
(is (= queryparams (read-string (:body response)))))))))
(deftest redirect-test-sync
(testlogging/with-test-logging
(testutils/with-app-with-config app
[jetty9/jetty9-service redirect-web-service]
{:webserver {:port 8080}}
(testing (str "redirects on POST not followed by Java client "
"when forceRedirects option not set to true")
(let [request-options (SimpleRequestOptions. (URI. ":8080/hello"))
response (Sync/post request-options)]
(is (= 302 (.getStatus response)))))
(testing "redirects on POST followed by Java client when option is set"
(let [request-options (.. (SimpleRequestOptions. (URI. ":8080/hello"))
(setForceRedirects true))
response (Sync/post request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "redirects not followed by Java client when :follow-redirects is false"
(let [request-options (.. (SimpleRequestOptions. (URI. ":8080/hello"))
(setFollowRedirects false))
response (Sync/get request-options)]
(is (= 302 (.getStatus response)))))
(testing ":follow-redirects overrides :force-redirects for Java client"
(let [request-options (.. (SimpleRequestOptions. (URI. ":8080/hello"))
(setFollowRedirects false)
(setForceRedirects true))
response (Sync/get request-options)]
(is (= 302 (.getStatus response)))))
(testing (str "redirects on POST not followed by clojure client "
"when :force-redirects is not set to true")
(let [opts {:method :post
:url ":8080/hello"
:as :text
:force-redirects false}
response (sync/post ":8080/hello" opts)]
(is (= 302 (:status response)))))
(testing "redirects on POST followed by clojure client when option is set"
(let [opts {:method :post
:url ":8080/hello"
:as :text
:force-redirects true}
response (sync/post ":8080/hello" opts)]
(is (= 200 (:status response)))
(is (= "Hello, World!" (:body response)))))
(testing (str "redirects not followed by clojure client when :follow-redirects "
"is set to false")
(let [response (sync/get ":8080/hello" {:as :text
:follow-redirects false})]
(is (= 302 (:status response)))))
(testing ":follow-redirects overrides :force-redirects with clojure client"
(let [response (sync/get ":8080/hello" {:as :text
:follow-redirects false
:force-redirects true})]
(is (= 302 (:status response)))))
(testing (str "redirects on POST followed by persistent clojure client "
"when option is set")
(let [client (sync/create-client {:force-redirects true})
response (common/post client ":8080/hello" {:as :text})]
(is (= 200 (:status response)))
(is (= "Hello, World!" (:body response)))
(common/close client)))
(testing (str "persistent clojure client does not follow redirects when "
":follow-redirects is set to false")
(let [client (sync/create-client {:follow-redirects false})
response (common/get client ":8080/hello" {:as :text})]
(is (= 302 (:status response)))
(common/close client)))
(testing ":follow-redirects overrides :force-redirects with persistent clj client"
(let [client (sync/create-client {:follow-redirects false
:force-redirects true})
response (common/get client ":8080/hello" {:as :text})]
(is (= 302 (:status response)))
(common/close client))))))
(defmacro wrapped-connect-exception-thrown?
[& body]
`(try
(testlogging/with-test-logging ~@body)
(throw (IllegalStateException.
"Expected HttpClientException but none thrown!"))
(catch HttpClientException e#
(if-let [cause# (.getCause e#)]
(or (instance? SocketTimeoutException cause#)
(instance? ConnectException cause#)
(throw (IllegalStateException.
(str
"Expected SocketTimeoutException or ConnectException "
"cause but found: " cause#))))
(throw (IllegalStateException.
(str
"Expected SocketTimeoutException or ConnectException but "
"no cause found. Message:" (.getMessage e#))))))))
(defmacro wrapped-timeout-exception-thrown?
[& body]
`(try
(testlogging/with-test-logging ~@body)
(throw (IllegalStateException.
"Expected HttpClientException but none thrown!"))
(catch HttpClientException e#
(if-let [cause# (.getCause e#)]
(or (instance? SocketTimeoutException cause#)
(throw (IllegalStateException.
(str
"Expected SocketTimeoutException cause but found: "
cause#))))
(throw (IllegalStateException.
(str
"Expected SocketTimeoutException but no cause found. "
"Message: " (.getMessage e#))))))))
(deftest short-connect-timeout-nonpersistent-java-test-sync
(testing (str "connection times out properly for non-persistent java sync "
"request with short timeout")
(let [request-options (-> ":65535"
(SimpleRequestOptions.)
(.setConnectTimeoutMilliseconds 250))
time-before-connect (System/currentTimeMillis)]
(is (wrapped-connect-exception-thrown?
(Sync/get request-options))
"Unexpected result for connection attempt")
(is (elapsed-within-range? time-before-connect 2000)
"Connection attempt took significantly longer than timeout"))))
(deftest short-connect-timeout-persistent-java-test-sync
(testing (str "connection times out properly for java persistent client sync "
"request with short timeout")
(with-open [client (-> (ClientOptions.)
(.setConnectTimeoutMilliseconds 250)
(Sync/createClient))]
(let [request-options (RequestOptions. ":65535")
time-before-connect (System/currentTimeMillis)]
(is (wrapped-connect-exception-thrown?
(.get client request-options))
"Unexpected result for connection attempt")
(is (elapsed-within-range? time-before-connect 2000)
"Connection attempt took significantly longer than timeout")))))
(deftest short-connect-timeout-nonpersistent-clojure-test-sync
(testing (str "connection times out properly for non-persistent clojure sync "
"request with short timeout")
(let [time-before-connect (System/currentTimeMillis)]
(is (connect-exception-thrown?
(sync/get ":65535"
{:connect-timeout-milliseconds 250}))
"Unexpected result for connection attempt")
(is (elapsed-within-range? time-before-connect 2000)
"Connection attempt took significantly longer than timeout"))))
(deftest short-connect-timeout-persistent-clojure-test-sync
(testing (str "connection times out properly for clojure persistent client "
"sync request with short timeout")
(with-open [client (sync/create-client
{:connect-timeout-milliseconds 250})]
(let [time-before-connect (System/currentTimeMillis)]
(is (connect-exception-thrown?
(common/get client ":65535"))
"Unexpected result for connection attempt")
(is (elapsed-within-range? time-before-connect 2000)
"Connection attempt took significantly longer than timeout")))))
(deftest longer-connect-timeout-test-sync
(testing "connection succeeds for sync request with longer connect timeout"
(testlogging/with-test-logging
(testwebserver/with-test-webserver app port
(let [url (str ":" port "/hello")]
(testing "java non-persistent sync client"
(let [request-options (.. (SimpleRequestOptions. url)
(setConnectTimeoutMilliseconds 2000))
response (Sync/get request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "java persistent sync client"
(with-open [client (-> (ClientOptions.)
(.setConnectTimeoutMilliseconds 2000)
(Sync/createClient))]
(let [response (.get client (RequestOptions. url))]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response)))))))
(testing "clojure non-persistent sync client"
(let [response (sync/get url
{:as :text
:connect-timeout-milliseconds 2000})]
(is (= 200 (:status response)))
(is (= "Hello, World!" (:body response)))))
(testing "clojure persistent sync client"
(with-open [client (sync/create-client
{:connect-timeout-milliseconds 2000})]
(let [response (common/get client url {:as :text})]
(is (= 200 (:status response)))
(is (= "Hello, World!" (:body response)))))))))))
(deftest short-socket-timeout-nonpersistent-java-test-sync
(testing (str "socket read times out properly for non-persistent java sync "
"request with short timeout")
(with-open [server (ServerSocket. 0)]
(let [request-options (-> ":"
(str (.getLocalPort server))
(SimpleRequestOptions.)
(.setSocketTimeoutMilliseconds 250))
time-before-connect (System/currentTimeMillis)]
(is (wrapped-timeout-exception-thrown? (Sync/get request-options))
"Unexpected result for get attempt")
(is (elapsed-within-range? time-before-connect 2000)
"Get attempt took significantly longer than timeout")))))
(deftest short-socket-timeout-persistent-java-test-sync
(testing (str "socket read times out properly for persistent java sync "
"request with short timeout")
(with-open [client (-> (ClientOptions.)
(.setSocketTimeoutMilliseconds 250)
(Sync/createClient))
server (ServerSocket. 0)]
(let [request-options (-> ":"
(str (.getLocalPort server))
(RequestOptions.))
time-before-connect (System/currentTimeMillis)]
(is (wrapped-timeout-exception-thrown? (.get client request-options))
"Unexpected result for get attempt")
(is (elapsed-within-range? time-before-connect 2000)
"Get attempt took significantly longer than timeout")))))
(deftest short-socket-timeout-nonpersistent-clojure-test-sync
(testing (str "socket read times out properly for non-persistent clojure "
"sync request with short timeout")
(with-open [server (ServerSocket. 0)]
(let [url (str ":" (.getLocalPort server))
time-before-connect (System/currentTimeMillis)]
(is (thrown? SocketTimeoutException
(sync/get url {:socket-timeout-milliseconds 250}))
"Unexpected result for get attempt")
(is (elapsed-within-range? time-before-connect 2000)
"Get attempt took significantly longer than timeout")))))
(deftest short-socket-timeout-persistent-clojure-test-sync
(testing (str "socket read times out properly for clojure persistent client "
"sync request with short timeout")
(with-open [client (sync/create-client
{:socket-timeout-milliseconds 250})
server (ServerSocket. 0)]
(let [url (str ":" (.getLocalPort server))
time-before-connect (System/currentTimeMillis)]
(is (thrown? SocketTimeoutException (common/get client url))
"Unexpected result for get attempt")
(is (elapsed-within-range? time-before-connect 2000)
"Get attempt took significantly longer than timeout")))))
(deftest longer-socket-timeout-test-sync
(testing "get succeeds for sync request with longer socket timeout"
(testlogging/with-test-logging
(testwebserver/with-test-webserver app port
(let [url (str ":" port "/hello")]
(testing "java non-persistent sync client"
(let [request-options (.. (SimpleRequestOptions. url)
(setSocketTimeoutMilliseconds 2000))
response (Sync/get request-options)]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response))))))
(testing "java persistent sync client"
(with-open [client (-> (ClientOptions.)
(.setSocketTimeoutMilliseconds 2000)
(Sync/createClient))]
(let [response (.get client (RequestOptions. url))]
(is (= 200 (.getStatus response)))
(is (= "Hello, World!" (slurp (.getBody response)))))))
(testing "clojure non-persistent sync client"
(let [response (sync/get url
{:as :text
:socket-timeout-milliseconds 2000})]
(is (= 200 (:status response)))
(is (= "Hello, World!" (:body response)))))
(testing "clojure persistent sync client"
(with-open [client (sync/create-client
{:socket-timeout-milliseconds 2000})]
(let [response (common/get client url {:as :text})]
(is (= 200 (:status response)))
(is (= "Hello, World!" (:body response)))))))))))
| |
430cc11edd5a2c9fb4ead5bddce2e8ef232daec162c8dadeb52bc9052984c205 | na4zagin3/satyrographos | command_opam_install__doc.ml | module StdList = List
open Satyrographos_testlib
open TestLib
open Shexp_process
let satyristes =
{|
(version "0.0.2")
(library
(name "grcnum")
(version "0.2")
(sources
((package "grcnum.satyh" "./grcnum.satyh")
(font "grcnum-font.ttf" "./font.ttf")
(hash "fonts.satysfi-hash" "./fonts.satysfi-hash")
; (file "doc/grcnum.md" "README.md")
))
(opam "satysfi-grcnum.opam")
(dependencies ((fonts-theano ())))
(compatibility ((satyrographos 0.0.1))))
(libraryDoc
(name "grcnum-doc")
(version "0.2")
(build
((satysfi "doc-grcnum.saty" "-o" "doc-grcnum-ja.pdf")))
(sources
((doc "doc-grcnum-ja.pdf" "./doc-grcnum-ja.pdf")))
(opam "satysfi-grcnum-doc.opam")
(dependencies ((grcnum ())
(fonts-theano ()))))
|}
let fontHash =
{|{
"grcnum:grcnum-font":<"Single":{"src-dist":"grcnum/grcnum-font.ttf"}>
}|}
let env ~dest_dir:_ ~temp_dir : Satyrographos.Environment.t t =
let open Shexp_process.Infix in
let pkg_dir = FilePath.concat temp_dir "pkg" in
let prepare_pkg =
PrepareDist.empty pkg_dir
>> stdout_to (FilePath.concat pkg_dir "Satyristes") (echo satyristes)
>> stdout_to (FilePath.concat pkg_dir "README.md") (echo "@@README.md@@")
>> stdout_to (FilePath.concat pkg_dir "fonts.satysfi-hash") (echo fontHash)
>> stdout_to (FilePath.concat pkg_dir "grcnum.satyh") (echo "@@grcnum.satyh@@")
>> stdout_to (FilePath.concat pkg_dir "font.ttf") (echo "@@font.ttf@@")
>> stdout_to (FilePath.concat pkg_dir "doc-grcnum-ja.pdf") (echo "@@doc-grcnum-ja.pdf@@")
in
let empty_dist = FilePath.concat temp_dir "empty_dist" in
let prepare_dist = PrepareDist.empty empty_dist in
let opam_reg = FilePath.concat temp_dir "opam_reg" in
let prepare_opam_reg =
PrepareOpamReg.(prepare opam_reg theanoFiles)
>> PrepareOpamReg.(prepare opam_reg grcnumFiles)
>> PrepareOpamReg.(prepare opam_reg classGreekFiles)
>> PrepareOpamReg.(prepare opam_reg baseFiles)
in
prepare_pkg
>> prepare_dist
>> prepare_opam_reg
>>| read_env ~opam_reg ~dist_library_dir:empty_dist
let () =
let verbose = true in
let main env ~dest_dir ~temp_dir =
let name = Some "grcnum-doc" in
let dest_dir = FilePath.concat dest_dir "dest" in
Satyrographos_command.Opam.(with_build_script install_opam ~verbose ~prefix:dest_dir ~buildscript_path:(FilePath.concat temp_dir "pkg/Satyristes") ~env ~name) () in
eval (test_install env main)
| null | https://raw.githubusercontent.com/na4zagin3/satyrographos/9dbccf05138510c977a67c859bbbb48755470c7f/test/testcases/command_opam_install__doc.ml | ocaml | module StdList = List
open Satyrographos_testlib
open TestLib
open Shexp_process
let satyristes =
{|
(version "0.0.2")
(library
(name "grcnum")
(version "0.2")
(sources
((package "grcnum.satyh" "./grcnum.satyh")
(font "grcnum-font.ttf" "./font.ttf")
(hash "fonts.satysfi-hash" "./fonts.satysfi-hash")
; (file "doc/grcnum.md" "README.md")
))
(opam "satysfi-grcnum.opam")
(dependencies ((fonts-theano ())))
(compatibility ((satyrographos 0.0.1))))
(libraryDoc
(name "grcnum-doc")
(version "0.2")
(build
((satysfi "doc-grcnum.saty" "-o" "doc-grcnum-ja.pdf")))
(sources
((doc "doc-grcnum-ja.pdf" "./doc-grcnum-ja.pdf")))
(opam "satysfi-grcnum-doc.opam")
(dependencies ((grcnum ())
(fonts-theano ()))))
|}
let fontHash =
{|{
"grcnum:grcnum-font":<"Single":{"src-dist":"grcnum/grcnum-font.ttf"}>
}|}
let env ~dest_dir:_ ~temp_dir : Satyrographos.Environment.t t =
let open Shexp_process.Infix in
let pkg_dir = FilePath.concat temp_dir "pkg" in
let prepare_pkg =
PrepareDist.empty pkg_dir
>> stdout_to (FilePath.concat pkg_dir "Satyristes") (echo satyristes)
>> stdout_to (FilePath.concat pkg_dir "README.md") (echo "@@README.md@@")
>> stdout_to (FilePath.concat pkg_dir "fonts.satysfi-hash") (echo fontHash)
>> stdout_to (FilePath.concat pkg_dir "grcnum.satyh") (echo "@@grcnum.satyh@@")
>> stdout_to (FilePath.concat pkg_dir "font.ttf") (echo "@@font.ttf@@")
>> stdout_to (FilePath.concat pkg_dir "doc-grcnum-ja.pdf") (echo "@@doc-grcnum-ja.pdf@@")
in
let empty_dist = FilePath.concat temp_dir "empty_dist" in
let prepare_dist = PrepareDist.empty empty_dist in
let opam_reg = FilePath.concat temp_dir "opam_reg" in
let prepare_opam_reg =
PrepareOpamReg.(prepare opam_reg theanoFiles)
>> PrepareOpamReg.(prepare opam_reg grcnumFiles)
>> PrepareOpamReg.(prepare opam_reg classGreekFiles)
>> PrepareOpamReg.(prepare opam_reg baseFiles)
in
prepare_pkg
>> prepare_dist
>> prepare_opam_reg
>>| read_env ~opam_reg ~dist_library_dir:empty_dist
let () =
let verbose = true in
let main env ~dest_dir ~temp_dir =
let name = Some "grcnum-doc" in
let dest_dir = FilePath.concat dest_dir "dest" in
Satyrographos_command.Opam.(with_build_script install_opam ~verbose ~prefix:dest_dir ~buildscript_path:(FilePath.concat temp_dir "pkg/Satyristes") ~env ~name) () in
eval (test_install env main)
| |
13a7f6520a4c11304e608c2ea41ed8af450edcf2c99d252c80707c69ed515d38 | fortytools/holumbus | Index.hs | -- ----------------------------------------------------------------------------
|
Module : . Build . Crawl
Copyright : Copyright ( C ) 2008
License : MIT
Maintainer : ( )
Stability : experimental
Portability : portable
Version : 0.1
Indexer functions
Module : Holumbus.Build.Crawl
Copyright : Copyright (C) 2008 Sebastian M. Schlatt
License : MIT
Maintainer : Sebastian M. Schlatt ()
Stability : experimental
Portability: portable
Version : 0.1
Indexer functions
-}
-- -----------------------------------------------------------------------------
{-# OPTIONS -XFlexibleContexts #-}
-- -----------------------------------------------------------------------------
module Holumbus.Build.Index
(
-- * Building indexes
buildIndex
, buildIndexM
-- * Indexer Configuration
, IndexerConfig (..)
, ContextConfig (..)
, mergeIndexerConfigs
, getTexts
)
where
-- import Data.List
import qualified Data.Map as M
import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import Data.Maybe
-- import Control.Exception
-- import Control.Monad
import Holumbus.Build.Config
import Holumbus.Control.MapReduce.MapReducible
import Holumbus.Control.MapReduce.ParallelWithClass
import Holumbus.Index.Common
import Holumbus.Utility
import System.Time
import Text.XML.HXT.Core
-- -----------------------------------------------------------------------------
buildIndex :: (HolDocuments d a, HolIndex i, HolCache c, MapReducible i (Context, Word) Occurrences) =>
Int -- ^ Number of parallel threads for MapReduce
-> Int -- ^ TraceLevel for Arrows
-> d a -- ^ List of input Data
-> IndexerConfig -- ^ Configuration for the Indexing process
^ An empty HolIndex . This is used to determine which kind of index to use .
-> Maybe c
^ returns a HolIndex
buildIndex workerThreads traceLevel docs idxConfig emptyIndex cache
= let docs' = (map (\(i,d) -> (i, uri d)) (IM.toList $ toMap docs)) in
-- assert ((sizeWords emptyIndex) == 0)
(mapReduce
workerThreads
( ic_indexerTimeOut )
( ( fromMaybe " /tmp/ " ( ic_tempPath ) ) + + " MapReduce.db " )
emptyIndex
(computeOccurrences traceLevel
(isJust $ ic_tempPath idxConfig)
(ic_contextConfigs idxConfig)
(ic_readAttributes idxConfig)
cache
)
docs'
)
buildIndexM :: (HolDocuments d a, HolIndexM m i, HolCache c, MapReducible i (Context, Word) Occurrences) =>
Int -- ^ Number of parallel threads for MapReduce
-> Int -- ^ TraceLevel for Arrows
-> d a -- ^ List of input Data
-> IndexerConfig -- ^ Configuration for the Indexing process
-> i -- ^ An empty HolIndexM. This is used to determine which kind of index to use.
^ Just HolCache switches cache construction on
-> IO i -- ^ returns a HolIndexM
buildIndexM workerThreads traceLevel docs idxConfig emptyIndex cache
= let docs' = (map (\(i,d) -> (i, uri d)) (IM.toList $ toMap docs)) in
-- assert ((sizeWords emptyIndex) == 0)
(mapReduce
workerThreads
( ic_indexerTimeOut )
( ( fromMaybe " /tmp/ " ( ic_tempPath ) ) + + " MapReduce.db " )
emptyIndex
(computeOccurrences traceLevel
(isJust $ ic_tempPath idxConfig)
(ic_contextConfigs idxConfig)
(ic_readAttributes idxConfig)
cache
)
docs'
)
-- | The MAP function in a MapReduce computation for building indexes.
The first three parameters have to be passed to the function to receive
-- a function with a valid MapReduce-map signature.
--
-- The function optionally outputs some debug information and then starts
-- the processing of a file by passing it together with the configuration
-- for different contexts to the @processDocument@ function where the file
-- is read and then the interesting parts configured in the
-- context configurations are extracted.
computeOccurrences :: HolCache c =>
Int -> Bool -> [ContextConfig] -> SysConfigList -> Maybe c
-> DocId -> String -> IO [((Context, Word), Occurrences)]
computeOccurrences traceLevel fromTmp contextConfigs attrs cache docId theUri
= do
clt <- getClockTime
cat <- toCalendarTime clt
res <- runX ( setTraceLevel traceLevel
>>> traceMsg 1 ((calendarTimeToString cat) ++ " - indexing document: "
++ show docId ++ " -> "
++ show theUri)
>>> processDocument traceLevel attrs' contextConfigs cache docId theUri
-- >>> arr (\ (c, w, d, p) -> (c, (w, d, p)))
>>> strictA
)
return $ buildPositions res
where
attrs' = if fromTmp then attrs ++ standardReadTmpDocumentAttributes else attrs
buildPositions :: [(Context, Word, DocId, Position)] -> [((Context, Word), Occurrences)]
buildPositions l = M.foldWithKey (\(c,w,d) ps acc -> ((c,w),IM.singleton d ps) : acc) [] $
foldl (\m (c,w,d,p) -> M.insertWith IS.union (c,w,d) (IS.singleton p) m) M.empty l
-- -----------------------------------------------------------------------------
-- | Downloads a document and calls the function to process the data for the
-- different contexts of the index
processDocument :: HolCache c =>
Int
-> SysConfigList
-> [ContextConfig]
-> Maybe c
-> DocId
-> URI
-> IOSLA (XIOState s) b (Context, Word, DocId, Position)
processDocument traceLevel attrs ccs cache docId theUri =
withTraceLevel (traceLevel - traceOffset) (readDocument attrs theUri)
>>> (catA $ map (processContext cache docId) ccs ) -- process all context configurations
-- | Process a Context. Applies the given context configuration to extract information from
-- the XmlTree that is passed in the arrow.
processContext ::
( HolCache c) =>
Maybe c
-> DocId
-> ContextConfig
-> IOSLA (XIOState s) XmlTree (Context, Word, DocId, Position)
processContext cache docId cc
= cc_preFilter cc -- convert XmlTree
>>>
fromLA extractWords
>>>
( if ( isJust cache
&&
cc_addToCache cc
)
then perform (arrIO storeInCache)
else this
)
>>>
arrL genWordList
>>>
strictA
where
extractWords :: LA XmlTree [String]
extractWords
= listA
( xshow ( (cc_fExtract cc) -- extract interesting parts
>>>
getTexts
)
>>>
arrL ( filter (not . null) . cc_fTokenize cc )
)
genWordList :: [String] -> [(Context, Word, DocId, Position)]
genWordList
= zip [1..] -- number words
>>> -- arrow for pure functions
filter (not . (cc_fIsStopWord cc) . snd) -- delete boring words
>>>
map ( \ (p, w) -> (cc_name cc, w, docId, p) ) -- attach context and docId
storeInCache s
= let
t = unwords s
in
if t /= ""
then putDocText (fromJust cache) (cc_name cc) docId t
else return ()
getTexts :: LA XmlTree XmlTree
getTexts -- select all text nodes
= choiceA
[ isText :-> this -- take the text nodes
, isElem :-> ( space -- substitute tags by a single space
<+> -- so tags act as word delimiter
(getChildren >>> getTexts)
<+>
space
) -- tags are interpreted as word delimiter
, isAttr :-> ( getChildren >>> getTexts ) -- take the attribute value
, this :-> none -- ignore anything else
]
where
space = txt " "
-- older and slower version . only for sentimentality
processContext cache docId cc =
( cc_preFilter cc ) -- convert XmlTree
> > > listA (
( cc_fExtract cc ) -- extract interesting parts
> > > deep isText -- Search deep for text nodes
> > > getText
)
> > > arr concat -- convert text nodes into strings
> > > ( cc_fTokenize cc ) -- apply tokenizer function
> > > arr ( filter ( \w - > w /= " " ) ) -- filter empty words
> > > perform ( ( const $ ( isJust cache ) & & ( cc_addToCache cc ) ) -- write cache data if configured
` guardsP `
( arr unwords > > > arrIO ( putDocText ( fromJust cache ) ( cc_name cc ) docId ) )
)
> > > arr ( zip [ 1 .. ] ) -- number words
> > > arr ( filter ( \(_,s ) - > not ( ( cc_fIsStopWord cc ) s ) ) ) -- remove stop words
> > > arrL ( map ( \(p , w ) - > ( cc_name cc , w , docId , p ) ) ) -- make a list of result tupels
> > > strictA -- force strict evaluation
-- older and slower version. only for sentimentality
processContext cache docId cc =
(cc_preFilter cc) -- convert XmlTree
>>> listA (
(cc_fExtract cc) -- extract interesting parts
>>> deep isText -- Search deep for text nodes
>>> getText
)
>>> arr concat -- convert text nodes into strings
>>> arr (cc_fTokenize cc) -- apply tokenizer function
>>> arr (filter (\w -> w /= "")) -- filter empty words
>>> perform ( (const $ (isJust cache) && (cc_addToCache cc)) -- write cache data if configured
`guardsP`
( arr unwords >>> arrIO ( putDocText (fromJust cache) (cc_name cc) docId))
)
>>> arr (zip [1..]) -- number words
>>> arr (filter (\(_,s) -> not ((cc_fIsStopWord cc) s))) -- remove stop words
>>> arrL (map (\(p, w) -> (cc_name cc, w, docId, p) )) -- make a list of result tupels
>>> strictA -- force strict evaluation
-}
| null | https://raw.githubusercontent.com/fortytools/holumbus/4b2f7b832feab2715a4d48be0b07dca018eaa8e8/searchengine/source/Holumbus/Build/Index.hs | haskell | ----------------------------------------------------------------------------
-----------------------------------------------------------------------------
# OPTIONS -XFlexibleContexts #
-----------------------------------------------------------------------------
* Building indexes
* Indexer Configuration
import Data.List
import Control.Exception
import Control.Monad
-----------------------------------------------------------------------------
^ Number of parallel threads for MapReduce
^ TraceLevel for Arrows
^ List of input Data
^ Configuration for the Indexing process
assert ((sizeWords emptyIndex) == 0)
^ Number of parallel threads for MapReduce
^ TraceLevel for Arrows
^ List of input Data
^ Configuration for the Indexing process
^ An empty HolIndexM. This is used to determine which kind of index to use.
^ returns a HolIndexM
assert ((sizeWords emptyIndex) == 0)
| The MAP function in a MapReduce computation for building indexes.
a function with a valid MapReduce-map signature.
The function optionally outputs some debug information and then starts
the processing of a file by passing it together with the configuration
for different contexts to the @processDocument@ function where the file
is read and then the interesting parts configured in the
context configurations are extracted.
>>> arr (\ (c, w, d, p) -> (c, (w, d, p)))
-----------------------------------------------------------------------------
| Downloads a document and calls the function to process the data for the
different contexts of the index
process all context configurations
| Process a Context. Applies the given context configuration to extract information from
the XmlTree that is passed in the arrow.
convert XmlTree
extract interesting parts
number words
arrow for pure functions
delete boring words
attach context and docId
select all text nodes
take the text nodes
substitute tags by a single space
so tags act as word delimiter
tags are interpreted as word delimiter
take the attribute value
ignore anything else
older and slower version . only for sentimentality
convert XmlTree
extract interesting parts
Search deep for text nodes
convert text nodes into strings
apply tokenizer function
filter empty words
write cache data if configured
number words
remove stop words
make a list of result tupels
force strict evaluation
older and slower version. only for sentimentality
convert XmlTree
extract interesting parts
Search deep for text nodes
convert text nodes into strings
apply tokenizer function
filter empty words
write cache data if configured
number words
remove stop words
make a list of result tupels
force strict evaluation |
|
Module : . Build . Crawl
Copyright : Copyright ( C ) 2008
License : MIT
Maintainer : ( )
Stability : experimental
Portability : portable
Version : 0.1
Indexer functions
Module : Holumbus.Build.Crawl
Copyright : Copyright (C) 2008 Sebastian M. Schlatt
License : MIT
Maintainer : Sebastian M. Schlatt ()
Stability : experimental
Portability: portable
Version : 0.1
Indexer functions
-}
module Holumbus.Build.Index
(
buildIndex
, buildIndexM
, IndexerConfig (..)
, ContextConfig (..)
, mergeIndexerConfigs
, getTexts
)
where
import qualified Data.Map as M
import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import Data.Maybe
import Holumbus.Build.Config
import Holumbus.Control.MapReduce.MapReducible
import Holumbus.Control.MapReduce.ParallelWithClass
import Holumbus.Index.Common
import Holumbus.Utility
import System.Time
import Text.XML.HXT.Core
buildIndex :: (HolDocuments d a, HolIndex i, HolCache c, MapReducible i (Context, Word) Occurrences) =>
^ An empty HolIndex . This is used to determine which kind of index to use .
-> Maybe c
^ returns a HolIndex
buildIndex workerThreads traceLevel docs idxConfig emptyIndex cache
= let docs' = (map (\(i,d) -> (i, uri d)) (IM.toList $ toMap docs)) in
(mapReduce
workerThreads
( ic_indexerTimeOut )
( ( fromMaybe " /tmp/ " ( ic_tempPath ) ) + + " MapReduce.db " )
emptyIndex
(computeOccurrences traceLevel
(isJust $ ic_tempPath idxConfig)
(ic_contextConfigs idxConfig)
(ic_readAttributes idxConfig)
cache
)
docs'
)
buildIndexM :: (HolDocuments d a, HolIndexM m i, HolCache c, MapReducible i (Context, Word) Occurrences) =>
^ Just HolCache switches cache construction on
buildIndexM workerThreads traceLevel docs idxConfig emptyIndex cache
= let docs' = (map (\(i,d) -> (i, uri d)) (IM.toList $ toMap docs)) in
(mapReduce
workerThreads
( ic_indexerTimeOut )
( ( fromMaybe " /tmp/ " ( ic_tempPath ) ) + + " MapReduce.db " )
emptyIndex
(computeOccurrences traceLevel
(isJust $ ic_tempPath idxConfig)
(ic_contextConfigs idxConfig)
(ic_readAttributes idxConfig)
cache
)
docs'
)
The first three parameters have to be passed to the function to receive
computeOccurrences :: HolCache c =>
Int -> Bool -> [ContextConfig] -> SysConfigList -> Maybe c
-> DocId -> String -> IO [((Context, Word), Occurrences)]
computeOccurrences traceLevel fromTmp contextConfigs attrs cache docId theUri
= do
clt <- getClockTime
cat <- toCalendarTime clt
res <- runX ( setTraceLevel traceLevel
>>> traceMsg 1 ((calendarTimeToString cat) ++ " - indexing document: "
++ show docId ++ " -> "
++ show theUri)
>>> processDocument traceLevel attrs' contextConfigs cache docId theUri
>>> strictA
)
return $ buildPositions res
where
attrs' = if fromTmp then attrs ++ standardReadTmpDocumentAttributes else attrs
buildPositions :: [(Context, Word, DocId, Position)] -> [((Context, Word), Occurrences)]
buildPositions l = M.foldWithKey (\(c,w,d) ps acc -> ((c,w),IM.singleton d ps) : acc) [] $
foldl (\m (c,w,d,p) -> M.insertWith IS.union (c,w,d) (IS.singleton p) m) M.empty l
processDocument :: HolCache c =>
Int
-> SysConfigList
-> [ContextConfig]
-> Maybe c
-> DocId
-> URI
-> IOSLA (XIOState s) b (Context, Word, DocId, Position)
processDocument traceLevel attrs ccs cache docId theUri =
withTraceLevel (traceLevel - traceOffset) (readDocument attrs theUri)
processContext ::
( HolCache c) =>
Maybe c
-> DocId
-> ContextConfig
-> IOSLA (XIOState s) XmlTree (Context, Word, DocId, Position)
processContext cache docId cc
>>>
fromLA extractWords
>>>
( if ( isJust cache
&&
cc_addToCache cc
)
then perform (arrIO storeInCache)
else this
)
>>>
arrL genWordList
>>>
strictA
where
extractWords :: LA XmlTree [String]
extractWords
= listA
>>>
getTexts
)
>>>
arrL ( filter (not . null) . cc_fTokenize cc )
)
genWordList :: [String] -> [(Context, Word, DocId, Position)]
genWordList
>>>
storeInCache s
= let
t = unwords s
in
if t /= ""
then putDocText (fromJust cache) (cc_name cc) docId t
else return ()
getTexts :: LA XmlTree XmlTree
= choiceA
(getChildren >>> getTexts)
<+>
space
]
where
space = txt " "
processContext cache docId cc =
> > > listA (
> > > getText
)
` guardsP `
( arr unwords > > > arrIO ( putDocText ( fromJust cache ) ( cc_name cc ) docId ) )
)
processContext cache docId cc =
>>> listA (
>>> getText
)
`guardsP`
( arr unwords >>> arrIO ( putDocText (fromJust cache) (cc_name cc) docId))
)
-}
|
bb683723e1931151f2b20b429a5ea9ce0e9715f2d394b7f26d2b9c65825c4da8 | kpblc2000/KpblcLispLib | _kpblc-conv-value-color-to-int.lsp | (defun _kpblc-conv-value-color-to-int (color)
;|
* Ôóíêöèÿ ïðåîáðàçîâàíèÿ ïåðåäàííîãî çíà÷åíèÿ öâåòà â integer äëÿ
* óñòàíîâêè öâåòîâ.
* Ïàðàìåòðû âûçîâà:
îáðàáàòûâàåìûé öâåò . nil - > " "
|;
(cond ((not color) (_kpblc-conv-value-color-to-int "bylayer"))
((= (type color) 'str)
(cond ((= (strcase color t) "bylayer") 256)
((= (strcase color t) "byblock") 0)
(t (_kpblc-conv-value-color-to-int "bylayer"))
) ;_ end of cond
)
(t color)
) ;_ end of cond
) ;_ end of defun
| null | https://raw.githubusercontent.com/kpblc2000/KpblcLispLib/49d1d9d29078b4167cc65dc881bea61b706c620d/lsp/conv/value/_kpblc-conv-value-color-to-int.lsp | lisp | |
_ end of cond
_ end of cond
_ end of defun
| (defun _kpblc-conv-value-color-to-int (color)
* Ôóíêöèÿ ïðåîáðàçîâàíèÿ ïåðåäàííîãî çíà÷åíèÿ öâåòà â integer äëÿ
* óñòàíîâêè öâåòîâ.
* Ïàðàìåòðû âûçîâà:
îáðàáàòûâàåìûé öâåò . nil - > " "
(cond ((not color) (_kpblc-conv-value-color-to-int "bylayer"))
((= (type color) 'str)
(cond ((= (strcase color t) "bylayer") 256)
((= (strcase color t) "byblock") 0)
(t (_kpblc-conv-value-color-to-int "bylayer"))
)
(t color)
|
74b49913c81590a12440f73bd66382cb9c37e4981e3de29be1ef668db319bb9f | flybot-sg/lasagna-pull | options.clj | ;;# Introduction to options
(ns options
(:require [sg.flybot.pullable :as pull]))
In addition to basic query , Lasagna - pull support pattern options , it is a decorator
;; on the key part of a pattern, let you fine tune the query.
;; An option is a pair, a keyword followed by its arguments.
;;## General options
;; These options does not require a value in a specific type.
# # # ` : not - found ` option
;; The easiest option is `:not-found`, it provides a default value if a value is not
;; found.
(-> (pull/run-query '{(:a :not-found 0) ?a} {:b 3}) (pull/lvar-val '?a))
# # # ` : when ` option
;; `:when` option has a predict function as it argument, a match only succeed when this
;; predict fulfilled by the value.
(def q (pull/query {(list :a :when odd?) '?a}))
(-> (q {:a 3 :b 3}) (pull/lvar-val '?a))
;; This will failed to match:
(-> (q {:a 2 :b 3}) (pull/lvar-val '?a))
;; Note that the basic filter can also be thought as a `:when` option.
;; You can combine options together, they will be applied by their order:
(pull/run-query {(list :a :when even? :not-found 0) '?} {:a -1 :b 3})
# # Options requires values be a specific type
# # # ` : seq ` option
;; If you are about to match a big sequence, you might want to do pagination. It is essential
;; if you values are lazy.
(-> (pull/run-query '{(:a :seq [5 5]) ?} {:a (range 1000)}))
;; The design of putting options in the key part of the patterns, enable us
;; to do nested query.
(def data {:a (map (fn [i] {:b i}) (range 100))})
(-> (pull/run-query '{(:a :seq [5 5]) [{:b ?} ?b]} data) (pull/lvar-val '?b))
# # # ` : with ` and ` : batch ` options
;; You may store a function as a value in your map, then when querying it, you
;; can apply arguments to it, `:with` enable you to do it:
(defn square [x] (* x x))
(-> (pull/run-query '{(:a :with [5]) ?a} {:a square}) (pull/lvar-val '?a))
;; And `:batch` will apply many times on it, as if it is a sequence:
(-> (pull/run-query {(list :a :batch (mapv vector (range 100)) :seq [5 5]) '?a}
{:a square})
(pull/lvar-val '?a))
These options not just for conviniece , if the embeded functions invoked by
;; a query has side effects, these options could do
[ GraphQL 's mutation]( / learn / queries/#mutations ) .
(def a (atom 0))
(-> (pull/run-query {(list :a :with [5]) '?a} {:a (fn [x] (swap! a + x))})
(pull/lvar-val '?a))
;; And the atom has been changed:
@a | null | https://raw.githubusercontent.com/flybot-sg/lasagna-pull/fc7fe7defdbdec07730f87cbd72593cd59bd5ac2/notebook/options.clj | clojure | # Introduction to options
on the key part of a pattern, let you fine tune the query.
An option is a pair, a keyword followed by its arguments.
## General options
These options does not require a value in a specific type.
The easiest option is `:not-found`, it provides a default value if a value is not
found.
`:when` option has a predict function as it argument, a match only succeed when this
predict fulfilled by the value.
This will failed to match:
Note that the basic filter can also be thought as a `:when` option.
You can combine options together, they will be applied by their order:
If you are about to match a big sequence, you might want to do pagination. It is essential
if you values are lazy.
The design of putting options in the key part of the patterns, enable us
to do nested query.
You may store a function as a value in your map, then when querying it, you
can apply arguments to it, `:with` enable you to do it:
And `:batch` will apply many times on it, as if it is a sequence:
a query has side effects, these options could do
And the atom has been changed: | (ns options
(:require [sg.flybot.pullable :as pull]))
In addition to basic query , Lasagna - pull support pattern options , it is a decorator
# # # ` : not - found ` option
(-> (pull/run-query '{(:a :not-found 0) ?a} {:b 3}) (pull/lvar-val '?a))
# # # ` : when ` option
(def q (pull/query {(list :a :when odd?) '?a}))
(-> (q {:a 3 :b 3}) (pull/lvar-val '?a))
(-> (q {:a 2 :b 3}) (pull/lvar-val '?a))
(pull/run-query {(list :a :when even? :not-found 0) '?} {:a -1 :b 3})
# # Options requires values be a specific type
# # # ` : seq ` option
(-> (pull/run-query '{(:a :seq [5 5]) ?} {:a (range 1000)}))
(def data {:a (map (fn [i] {:b i}) (range 100))})
(-> (pull/run-query '{(:a :seq [5 5]) [{:b ?} ?b]} data) (pull/lvar-val '?b))
# # # ` : with ` and ` : batch ` options
(defn square [x] (* x x))
(-> (pull/run-query '{(:a :with [5]) ?a} {:a square}) (pull/lvar-val '?a))
(-> (pull/run-query {(list :a :batch (mapv vector (range 100)) :seq [5 5]) '?a}
{:a square})
(pull/lvar-val '?a))
These options not just for conviniece , if the embeded functions invoked by
[ GraphQL 's mutation]( / learn / queries/#mutations ) .
(def a (atom 0))
(-> (pull/run-query {(list :a :with [5]) '?a} {:a (fn [x] (swap! a + x))})
(pull/lvar-val '?a))
@a |
c3cf844136c30911ea02d2b0ade1a7227409874b7712c1235a675eb4a596827f | elastic/eui-cljs | markdown_editor.cljs | (ns eui.markdown-editor
(:require ["@elastic/eui/lib/components/markdown_editor/markdown_editor.js" :as eui]))
(def EuiMarkdownEditor eui/EuiMarkdownEditor)
| null | https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/markdown_editor.cljs | clojure | (ns eui.markdown-editor
(:require ["@elastic/eui/lib/components/markdown_editor/markdown_editor.js" :as eui]))
(def EuiMarkdownEditor eui/EuiMarkdownEditor)
| |
0b19c1a25d40a0370cd1e3e4ddc01a03579533775173933762660fc94a8140ff | exercism/clojure | project.clj | (defproject yacht "0.1.0-SNAPSHOT"
:description "yacht exercise."
:url ""
:dependencies [[org.clojure/clojure "1.10.0"]])
| null | https://raw.githubusercontent.com/exercism/clojure/0195fb9faef084ae4bce38d955d46be0c0322196/exercises/practice/yacht/project.clj | clojure | (defproject yacht "0.1.0-SNAPSHOT"
:description "yacht exercise."
:url ""
:dependencies [[org.clojure/clojure "1.10.0"]])
| |
42ea80e667291790ff7b24e1cccfe956f5bf536b93220b68daa14b240b4a332c | janestreet/sexp | utils.mli | open! Core
val simple_query : Syntax.Query.t -> Sexp.t -> Sexp.t list
(** [ get_fields sexp field ] searches for field recursively *)
val get_fields : Sexp.t -> string -> Sexp.t list
* [ get_one_field sexp field ] searches for field recursively and returns the value ,
or error if there is not exactly one result .
or error if there is not exactly one result. *)
val get_one_field : Sexp.t -> string -> Sexp.t Or_error.t
(** [ get_immediate_fields sexp ] returns an association list of field names to
field values, or error if the sexp does not conform to the normal structure of an
ocaml record. *)
val immediate_fields : Sexp.t -> (string, Sexp.t) List.Assoc.t Or_error.t
(** [ to_record_sexp by_field ] converts an association list of field names to
field values into a record-like sexp. *)
val to_record_sexp : (string, Sexp.t) List.Assoc.t -> Sexp.t
(** [ sexp_rewrite sexp ~f ] returns the rewritten sexp where f is applied
to sexp and its descendents. *)
val sexp_rewrite : Sexp.t -> f:(Sexp.t -> [ `Unchanged | `Changed of Sexp.t ]) -> Sexp.t
(** [ replace_field ~field ~value sexp scope ] replaces either the field with the
given value, or returns an error if no match is found in the designated scope.
If `Recursive is chosen, it will replace as many instances as appear, or error
if none are found. *)
val replace_field
: field:string
-> value:Sexp.t
-> Sexp.t
-> [ `Immediate | `Recursive ]
-> Sexp.t Or_error.t
| null | https://raw.githubusercontent.com/janestreet/sexp/56e485b3cbf8a43e1a8d7647b0df31b27053febf/sexp_app/src/utils.mli | ocaml | * [ get_fields sexp field ] searches for field recursively
* [ get_immediate_fields sexp ] returns an association list of field names to
field values, or error if the sexp does not conform to the normal structure of an
ocaml record.
* [ to_record_sexp by_field ] converts an association list of field names to
field values into a record-like sexp.
* [ sexp_rewrite sexp ~f ] returns the rewritten sexp where f is applied
to sexp and its descendents.
* [ replace_field ~field ~value sexp scope ] replaces either the field with the
given value, or returns an error if no match is found in the designated scope.
If `Recursive is chosen, it will replace as many instances as appear, or error
if none are found. | open! Core
val simple_query : Syntax.Query.t -> Sexp.t -> Sexp.t list
val get_fields : Sexp.t -> string -> Sexp.t list
* [ get_one_field sexp field ] searches for field recursively and returns the value ,
or error if there is not exactly one result .
or error if there is not exactly one result. *)
val get_one_field : Sexp.t -> string -> Sexp.t Or_error.t
val immediate_fields : Sexp.t -> (string, Sexp.t) List.Assoc.t Or_error.t
val to_record_sexp : (string, Sexp.t) List.Assoc.t -> Sexp.t
val sexp_rewrite : Sexp.t -> f:(Sexp.t -> [ `Unchanged | `Changed of Sexp.t ]) -> Sexp.t
val replace_field
: field:string
-> value:Sexp.t
-> Sexp.t
-> [ `Immediate | `Recursive ]
-> Sexp.t Or_error.t
|
3e1879d83c96ffd232e138fdf931205bc60d6a65b67170f2473a834a8302e05a | kovasb/gamma | insert_declarations.cljs | (ns gamma.compiler.insert-declarations
(:use [gamma.ast :only [id? gen-term-id]]
[gamma.compiler.common :only [get-element map-path assoc-in-location assoc-elements]]
[gamma.compiler.core :only [transform]])
)
(defn walk [db pre]
(transform
db
(fn walk-fn [db path]
[(pre db path) [[:body (map-path walk-fn)]]])))
(defn variables [db]
(let [a (atom #{})]
(walk db (fn [db location]
(let [e (get-element db location)]
(if (= :literal (:head e))
(if (= :variable (:tag (:value e)))
(do
(swap! a conj (:value e))
(if (:type (:value e))
nil
(println location))
))))
db))
@a))
| null | https://raw.githubusercontent.com/kovasb/gamma/3c9edcfdfc392103b0e78edba3ca930a60746fd1/src/gamma/compiler/insert_declarations.cljs | clojure | (ns gamma.compiler.insert-declarations
(:use [gamma.ast :only [id? gen-term-id]]
[gamma.compiler.common :only [get-element map-path assoc-in-location assoc-elements]]
[gamma.compiler.core :only [transform]])
)
(defn walk [db pre]
(transform
db
(fn walk-fn [db path]
[(pre db path) [[:body (map-path walk-fn)]]])))
(defn variables [db]
(let [a (atom #{})]
(walk db (fn [db location]
(let [e (get-element db location)]
(if (= :literal (:head e))
(if (= :variable (:tag (:value e)))
(do
(swap! a conj (:value e))
(if (:type (:value e))
nil
(println location))
))))
db))
@a))
| |
66b097caf7e6e22d604f28f6dec4cccdc3af67144c385ed277d3ea81915da857 | awslabs/s2n-bignum | bignum_add.ml |
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved .
* SPDX - License - Identifier : Apache-2.0 OR ISC
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 OR ISC
*)
(* ========================================================================= *)
(* Addition of bignums. *)
(* ========================================================================= *)
* * * print_literal_from_elf " x86 / generic / " ; ;
* * *
****)
let bignum_add_mc =
define_assert_from_elf "bignum_add_mc" "x86/generic/bignum_add.o"
[
0x4d; 0x31; 0xd2; (* XOR (% r10) (% r10) *)
CMP ( % rdi ) ( % rdx )
CMOVB ( % rdx ) ( % rdi )
CMP ( % rdi ) ( % r8 )
CMOVB ( % r8 ) ( % rdi )
CMP ( % rdx ) ( % r8 )
JB ( Imm8 ( word 71 ) )
0x48; 0x29; 0xd7; (* SUB (% rdi) (% rdx) *)
SUB ( % rdx ) ( % r8 )
0x48; 0xff; 0xc2; (* INC (% rdx) *)
0x4d; 0x85; 0xc0; (* TEST (% r8) (% r8) *)
JE ( Imm8 ( word 37 ) )
MOV ( % rax ) ( ( % % % ( rcx,3,r10 ) ) )
ADC ( % rax ) ( ( % % % ( r9,3,r10 ) ) )
MOV ( ( % % % ( rsi,3,r10 ) ) ) ( % rax )
0x49; 0xff; 0xc2; (* INC (% r10) *)
DEC ( % r8 )
JNE ( Imm8 ( word 236 ) )
JMP ( Imm8 ( word 15 ) )
MOV ( % rax ) ( ( % % % ( rcx,3,r10 ) ) )
0x48; 0x83; 0xd0; 0x00; (* ADC (% rax) (Imm8 (word 0)) *)
MOV ( ( % % % ( rsi,3,r10 ) ) ) ( % rax )
0x49; 0xff; 0xc2; (* INC (% r10) *)
DEC ( % rdx )
JNE ( Imm8 ( word 236 ) )
0xb8; 0x00; 0x00; 0x00; 0x00;
MOV ( % eax ) ( Imm32 ( word 0 ) )
0x48; 0x83; 0xd0; 0x00; (* ADC (% rax) (Imm8 (word 0)) *)
0x48; 0x85; 0xff; (* TEST (% rdi) (% rdi) *)
JNE ( Imm8 ( word 67 ) )
RET
0x4c; 0x29; 0xc7; (* SUB (% rdi) (% r8) *)
0x49; 0x29; 0xd0; (* SUB (% r8) (% rdx) *)
0x48; 0x85; 0xd2; (* TEST (% rdx) (% rdx) *)
JE ( Imm8 ( word 20 ) )
MOV ( % rax ) ( ( % % % ( rcx,3,r10 ) ) )
ADC ( % rax ) ( ( % % % ( r9,3,r10 ) ) )
MOV ( ( % % % ( rsi,3,r10 ) ) ) ( % rax )
0x49; 0xff; 0xc2; (* INC (% r10) *)
DEC ( % rdx )
JNE ( Imm8 ( word 236 ) )
MOV ( % rax ) ( ( % % % ( r9,3,r10 ) ) )
0x48; 0x83; 0xd0; 0x00; (* ADC (% rax) (Imm8 (word 0)) *)
MOV ( ( % % % ( rsi,3,r10 ) ) ) ( % rax )
0x49; 0xff; 0xc2; (* INC (% r10) *)
DEC ( % r8 )
JNE ( Imm8 ( word 236 ) )
0xb8; 0x00; 0x00; 0x00; 0x00;
MOV ( % eax ) ( Imm32 ( word 0 ) )
0x48; 0x83; 0xd0; 0x00; (* ADC (% rax) (Imm8 (word 0)) *)
0x48; 0x85; 0xff; (* TEST (% rdi) (% rdi) *)
JNE ( Imm8 ( word 1 ) )
RET
MOV ( ( % % % ( rsi,3,r10 ) ) ) ( % rax )
0x48; 0x31; 0xc0; (* XOR (% rax) (% rax) *)
JMP ( Imm8 ( word 4 ) )
MOV ( ( % % % ( rsi,3,r10 ) ) ) ( % rax )
0x49; 0xff; 0xc2; (* INC (% r10) *)
DEC ( % rdi )
JNE ( Imm8 ( word 244 ) )
RET
];;
let BIGNUM_ADD_EXEC = X86_MK_EXEC_RULE bignum_add_mc;;
(* ------------------------------------------------------------------------- *)
Common tactic for slightly different standard and Windows variants .
(* ------------------------------------------------------------------------- *)
let tac execth cleanpost offset =
W64_GEN_TAC `p:num` THEN X_GEN_TAC `z:int64` THEN
W64_GEN_TAC `m:num` THEN MAP_EVERY X_GEN_TAC [`x:int64`; `a:num`] THEN
W64_GEN_TAC `n:num` THEN MAP_EVERY X_GEN_TAC [`y:int64`; `b:num`] THEN
X_GEN_TAC `pc:num` THEN REWRITE_TAC[NONOVERLAPPING_CLAUSES] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS] THEN DISCH_TAC THEN
(*** Remove redundancy in the conclusion ***)
ENSURES_POSTCONDITION_TAC cleanpost THEN REWRITE_TAC[] THEN CONJ_TAC THENL
[X_GEN_TAC `s:x86state` THEN MATCH_MP_TAC MONO_AND THEN REWRITE_TAC[] THEN
ASM_SIMP_TAC[lowdigits; MOD_LT] THEN
DISCH_THEN(MP_TAC o AP_TERM `\x. x MOD 2 EXP (64 * p)`) THEN
SIMP_TAC[MOD_MULT_ADD; MOD_LT; BIGNUM_FROM_MEMORY_BOUND] THEN
CONV_TAC MOD_DOWN_CONV THEN REWRITE_TAC[];
ALL_TAC] THEN
(*** Reshuffle to handle clamping and just assume m <= p and n <= p ***)
ENSURES_SEQUENCE_TAC (offset 0x11)
`\s. read RDI s = word p /\
read RSI s = z /\
read RDX s = word(MIN m p) /\
read RCX s = x /\
read R8 s = word(MIN n p) /\
read R9 s = y /\
read R10 s = word 0 /\
bignum_from_memory(x,MIN m p) s = lowdigits a p /\
bignum_from_memory(y,MIN n p) s = lowdigits b p` THEN
CONJ_TAC THENL
[X86_SIM_TAC execth (1--5) THEN
ASM_REWRITE_TAC[lowdigits; REWRITE_RULE[BIGNUM_FROM_MEMORY_BYTES]
(GSYM BIGNUM_FROM_MEMORY_MOD)] THEN
GEN_REWRITE_TAC (BINOP_CONV o LAND_CONV) [GSYM COND_RAND] THEN
CONJ_TAC THEN AP_TERM_TAC THEN ARITH_TAC;
FIRST_X_ASSUM(CONJUNCTS_THEN MP_TAC)] THEN
SUBGOAL_THEN
`lowdigits (a + b) p = lowdigits (lowdigits a p + lowdigits b p) p`
SUBST1_TAC THENL
[REWRITE_TAC[lowdigits] THEN CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
ALL_TAC] THEN
SUBGOAL_THEN
`!w n. w = z \/
nonoverlapping_modulo (2 EXP 64) (val w,8 * n) (val z,8 * p)
==> w:int64 = z \/
nonoverlapping_modulo (2 EXP 64)
(val w,8 * MIN n p) (val z,8 * p)`
(fun th -> DISCH_THEN(CONJUNCTS_THEN(MP_TAC o MATCH_MP th)))
THENL
[POP_ASSUM_LIST(K ALL_TAC) THEN REPEAT GEN_TAC THEN
MATCH_MP_TAC MONO_OR THEN REWRITE_TAC[] THEN
DISCH_TAC THEN NONOVERLAPPING_TAC;
ALL_TAC] THEN
MAP_EVERY UNDISCH_TAC [`p < 2 EXP 64`; `val(word p:int64) = p`] THEN
SUBGOAL_THEN `MIN m p < 2 EXP 64 /\ MIN n p < 2 EXP 64` MP_TAC THENL
[ASM_ARITH_TAC; POP_ASSUM_LIST(K ALL_TAC)] THEN
MP_TAC(ARITH_RULE `MIN m p <= p /\ MIN n p <= p`) THEN
MAP_EVERY SPEC_TAC
[`lowdigits a p`,`a:num`; `lowdigits b p`,`b:num`;
`MIN m p`,`m:num`; `MIN n p`,`n:num`] THEN
REPEAT GEN_TAC THEN STRIP_TAC THEN STRIP_TAC THEN REPEAT DISCH_TAC THEN
MAP_EVERY VAL_INT64_TAC [`m:num`; `n:num`] THEN
BIGNUM_RANGE_TAC "m" "a" THEN BIGNUM_RANGE_TAC "n" "b" THEN
* * Get a basic bound on p from the nonoverlapping assumptions * *
FIRST_ASSUM(MP_TAC o MATCH_MP (ONCE_REWRITE_RULE[IMP_CONJ]
NONOVERLAPPING_IMP_SMALL_RIGHT_ALT)) THEN
ANTS_TAC THENL [CONV_TAC NUM_REDUCE_CONV; DISCH_TAC] THEN
(*** Case split following the initial branch, m >= n case then m < n ***)
ASM_CASES_TAC `n:num <= m` THENL
[SUBGOAL_THEN `~(m:num < n)` ASSUME_TAC THENL
[ASM_REWRITE_TAC[NOT_LT]; ALL_TAC] THEN
SUBGOAL_THEN `b < 2 EXP (64 * m)` ASSUME_TAC THENL
[TRANS_TAC LTE_TRANS `2 EXP (64 * n)` THEN
ASM_REWRITE_TAC[LE_EXP; ARITH_EQ; LE_MULT_LCANCEL];
ALL_TAC] THEN
ENSURES_SEQUENCE_TAC (offset 0x49)
`\s. read RDI s = word(p - m) /\
read RSI s = z /\
read RDX s = word(m - n + 1) /\
read RCX s = x /\
read R9 s = y /\
read R10 s = word n /\
bignum_from_memory (word_add x (word(8 * n)),m - n) s =
highdigits a n /\
2 EXP (64 * n) * bitval(read CF s) + bignum_from_memory(z,n) s =
lowdigits a n + lowdigits b n` THEN
CONJ_TAC THENL
[ASM_CASES_TAC `n = 0` THENL
[UNDISCH_THEN `n = 0` SUBST_ALL_TAC THEN
ASM_REWRITE_TAC[SUB_0] THEN X86_SIM_TAC execth (1--7) THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0; BITVAL_CLAUSES] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[WORD_SUB] THEN CONV_TAC WORD_RULE;
ALL_TAC] THEN
ENSURES_WHILE_PUP_TAC `n:num` (offset 0x24) (offset 0x36)
`\i s. (read RDI s = word(p - m) /\
read RSI s = z /\
read RDX s = word(m - n + 1) /\
read RCX s = x /\
read R9 s = y /\
read R8 s = word(n - i) /\
read R10 s = word i /\
bignum_from_memory (word_add x (word(8 * i)),m - i) s =
highdigits a i /\
bignum_from_memory (word_add y (word(8 * i)),n - i) s =
highdigits b i /\
2 EXP (64 * i) * bitval(read CF s) + bignum_from_memory(z,i) s =
lowdigits a i + lowdigits b i) /\
(read ZF s <=> i = n)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[SUB_0] THEN X86_SIM_TAC execth (1--7) THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0; BITVAL_CLAUSES] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[WORD_ADD; WORD_SUB];
ALL_TAC; (*** Main loop invariant ***)
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[] THEN X86_SIM_TAC execth [1];
X86_SIM_TAC execth (1--2)] THEN
X_GEN_TAC `i:num` THEN STRIP_TAC THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
SUBGOAL_THEN `i:num < m` ASSUME_TAC THENL
[SIMPLE_ARITH_TAC; ALL_TAC] THEN
VAL_INT64_TAC `i:num` THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN ENSURES_INIT_TAC "s0" THEN
REPEAT(FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I
[ONCE_REWRITE_RULE[BIGNUM_FROM_MEMORY_BYTES]
BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS])) THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN STRIP_TAC THEN STRIP_TAC THEN
X86_STEPS_TAC execth (1--5) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
ASM_REWRITE_TAC[ARITH_RULE `n - (i + 1) = n - i - 1`] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < n ==> 1 <= n - i`];
DISCH_THEN SUBST1_TAC] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
ASM_SIMP_TAC[ARITH_RULE `i < n ==> (i + 1 = n <=> n - i - 1 = 0)`] THEN
CONJ_TAC THENL
[ALL_TAC; VAL_INT64_TAC `n - i - 1` THEN ASM_REWRITE_TAC[]] THEN
REWRITE_TAC[ARITH_RULE `64 * (i + 1) = 64 * i + 64`; EXP_ADD] THEN
REWRITE_TAC[GSYM ACCUMULATE_ADC; ARITH_RULE
`(t * e) * x + z + t * y:num = t * (e * x + y) + z`] THEN
ASM_REWRITE_TAC[LEFT_ADD_DISTRIB; GSYM ADD_ASSOC; VAL_WORD_BITVAL] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES] THEN ARITH_TAC;
ALL_TAC] THEN
ENSURES_SEQUENCE_TAC (offset 0x57)
`\s. read RDI s = word(p - m) /\
read RSI s = z /\
read R10 s = word m /\
2 EXP (64 * m) * val(read RAX s) + bignum_from_memory(z,m) s =
lowdigits a m + lowdigits b m` THEN
CONJ_TAC THENL
[ASM_CASES_TAC `m:num = n` THENL
[UNDISCH_THEN `m:num = n` SUBST_ALL_TAC THEN ASM_REWRITE_TAC[] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
X86_SIM_TAC execth (1--4) THEN
ASM_REWRITE_TAC[VAL_WORD_BITVAL];
ALL_TAC] THEN
SUBGOAL_THEN `n < m /\ 0 < m - n /\ ~(m - n = 0)` STRIP_ASSUME_TAC THENL
[SIMPLE_ARITH_TAC; ALL_TAC] THEN
VAL_INT64_TAC `m - n:num` THEN
ENSURES_WHILE_PUP_TAC `m - n:num` (offset 0x3a) (offset 0x4c)
`\i s. (read RDI s = word(p - m) /\
read RSI s = z /\
read RCX s = x /\
read RDX s = word(m - n - i) /\
read R10 s = word(n + i) /\
bignum_from_memory(word_add x (word(8 * (n + i))),
m - (n + i)) s =
highdigits a (n + i) /\
2 EXP (64 * (n + i)) * bitval(read CF s) +
bignum_from_memory(z,n + i) s =
lowdigits a (n + i) + lowdigits b (n + i)) /\
(read ZF s <=> i = m - n)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[SUB_0] THEN X86_SIM_TAC execth (1--2) THEN
ASM_REWRITE_TAC[ADD_CLAUSES] THEN
REWRITE_TAC[VAL_EQ; WORD_RULE
`word(a + 1):int64 = word 1 <=> word a:int64 = word 0`] THEN
CONJ_TAC THENL [ALL_TAC; CONV_TAC WORD_RULE] THEN
ASM_REWRITE_TAC[GSYM VAL_EQ_0];
ALL_TAC; (*** Main loop invariant ***)
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[] THEN X86_SIM_TAC execth [1];
ASM_SIMP_TAC[ARITH_RULE `n:num <= m ==> n + m - n = m`] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
X86_SIM_TAC execth (1--3) THEN
ASM_REWRITE_TAC[VAL_WORD_BITVAL]] THEN
ASM_SIMP_TAC[ARITH_RULE
`n:num < m
==> (i < m - n <=> n + i < m) /\ (i = m - n <=> n + i = m)`] THEN
REWRITE_TAC[ARITH_RULE `m - n - i:num = m - (n + i)`] THEN
REWRITE_TAC[ARITH_RULE `n + i + 1 = (n + i) + 1`] THEN
X_GEN_TAC `j:num` THEN MP_TAC(ARITH_RULE `n <= n + j`) THEN
SPEC_TAC(`n + j:num`,`i:num`) THEN REPEAT STRIP_TAC THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
VAL_INT64_TAC `i:num` THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN ENSURES_INIT_TAC "s0" THEN
FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I
[ONCE_REWRITE_RULE[BIGNUM_FROM_MEMORY_BYTES]
BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS]) THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN STRIP_TAC THEN
X86_STEPS_TAC execth (1--5) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
ASM_REWRITE_TAC[ARITH_RULE `n - (i + 1) = n - i - 1`] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < n ==> 1 <= n - i`];
DISCH_THEN SUBST1_TAC] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
ASM_SIMP_TAC[ARITH_RULE `i < n ==> (i + 1 = n <=> n - i - 1 = 0)`] THEN
CONJ_TAC THENL
[ALL_TAC; VAL_INT64_TAC `m - i - 1` THEN ASM_REWRITE_TAC[]] THEN
REWRITE_TAC[ARITH_RULE `64 * (i + 1) = 64 * i + 64`; EXP_ADD] THEN
REWRITE_TAC[GSYM ACCUMULATE_ADC_0; ADD_CLAUSES; ARITH_RULE
`(t * e) * x + z + t * y:num = t * (e * x + y) + z`] THEN
ASM_REWRITE_TAC[LEFT_ADD_DISTRIB; GSYM ADD_ASSOC; VAL_WORD_BITVAL] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES; GSYM ADD_ASSOC; EQ_ADD_LCANCEL] THEN
MATCH_MP_TAC(NUM_RING `b = 0 ==> x = e * b + x`) THEN
MATCH_MP_TAC BIGDIGIT_ZERO THEN TRANS_TAC LTE_TRANS `2 EXP (64 * n)` THEN
ASM_REWRITE_TAC[LE_EXP; ARITH_EQ; LE_MULT_LCANCEL];
ALL_TAC] THEN
ASM_CASES_TAC `m:num = p` THENL
[UNDISCH_THEN `m:num = p` SUBST_ALL_TAC THEN ASM_REWRITE_TAC[] THEN
X86_SIM_TAC execth (1--2) THEN ASM_REWRITE_TAC[] THEN
BINOP_TAC THEN MATCH_MP_TAC LOWDIGITS_SELF THEN ASM_REWRITE_TAC[];
ALL_TAC] THEN
SUBGOAL_THEN `0 < p - m /\ ~(p - m = 0)` STRIP_ASSUME_TAC THENL
[SIMPLE_ARITH_TAC; ALL_TAC] THEN
VAL_INT64_TAC `p - m:num` THEN
ENSURES_SEQUENCE_TAC (offset 0xac)
`\s. read RDI s = word(p - m) /\
read RSI s = z /\
read R10 s = word m /\
read RAX s = word 0 /\
bignum_from_memory(z,m + 1) s = a + b` THEN
CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN ASM_REWRITE_TAC[] THEN
GHOST_INTRO_TAC `d:int64` `read RAX` THEN
X86_SIM_TAC execth (1--5) THEN
GEN_REWRITE_TAC LAND_CONV [ADD_SYM] THEN ASM_REWRITE_TAC[] THEN
BINOP_TAC THEN MATCH_MP_TAC LOWDIGITS_SELF THEN ASM_REWRITE_TAC[];
ALL_TAC] THEN
ASM_CASES_TAC `p = m + 1` THENL
[UNDISCH_THEN `p = m + 1` SUBST_ALL_TAC THEN REWRITE_TAC[ADD_SUB2] THEN
RULE_ASSUM_TAC(REWRITE_RULE[ADD_SUB2]) THEN
X86_SIM_TAC execth (1--3) THEN
REWRITE_TAC[VAL_WORD_0; ADD_CLAUSES; MULT_CLAUSES];
ALL_TAC] THEN
SUBGOAL_THEN
`0 < p - (m + 1) /\ ~(p - (m + 1) = 0) /\ ~(p - m = 1) /\ m + 1 <= p`
STRIP_ASSUME_TAC THENL [SIMPLE_ARITH_TAC; ALL_TAC] THEN
ENSURES_WHILE_PUP_TAC `p - (m + 1):num` (offset 0xa8) (offset 0xb2)
`\i s. (read RDI s = word(p - (m + 1) - i) /\
read R10 s = word((m + 1) + i) /\
read RSI s = z /\
read RAX s = word 0 /\
bignum_from_memory(z,(m + 1) + i) s = a + b) /\
(read ZF s <=> i = p - (m + 1))` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[SUB_0] THEN X86_SIM_TAC execth (1--3) THEN
ASM_REWRITE_TAC[ADD_CLAUSES; VAL_WORD_1] THEN
CONJ_TAC THENL [ALL_TAC; CONV_TAC WORD_RULE] THEN
REWRITE_TAC[ARITH_RULE `p - (m + 1) = p - m - 1`] THEN
GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN SIMPLE_ARITH_TAC;
ALL_TAC; (*** Main loop invariant ***)
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
X86_SIM_TAC execth [1];
ASM_SIMP_TAC[ARITH_RULE `0 < m - n ==> n + m - n = m`] THEN
X86_SIM_TAC execth [1] THEN
REWRITE_TAC[VAL_WORD_0; ADD_CLAUSES; MULT_CLAUSES]] THEN
X_GEN_TAC `j:num` THEN MP_TAC(ARITH_RULE `m + 1 <= (m + 1) + j`) THEN
REWRITE_TAC[ARITH_RULE
`p - (m + 1) - (j + 1) = p - ((m + 1) + (j + 1))`] THEN
REWRITE_TAC[ARITH_RULE `p - (m + 1) - j = p - ((m + 1) + j)`] THEN
REWRITE_TAC[ARITH_RULE `(m + 1) + (j + 1) = ((m + 1) + j) + 1`] THEN
ASM_SIMP_TAC[ARITH_RULE
`0 < p - (m + 1)
==> (j + 1 = p - (m + 1) <=> ((m + 1) + j) + 1 = p) /\
(j < p - (m + 1) <=> (m + 1) + j < p) /\
(j = p - (m + 1) <=> (m + 1) + j = p)`] THEN
SPEC_TAC(`(m + 1) + j:num`,`i:num`) THEN REPEAT STRIP_TAC THEN
VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
X86_SIM_TAC execth (1--3) THEN
REWRITE_TAC[VAL_WORD_0; MULT_CLAUSES; ADD_CLAUSES] THEN
REWRITE_TAC[ARITH_RULE `p - (i + 1) = p - i - 1`] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < n ==> 1 <= n - i`];
DISCH_THEN SUBST1_TAC] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
ASM_SIMP_TAC[ARITH_RULE `i < p ==> (i + 1 = p <=> p - i = 1)`] THEN
REWRITE_TAC[VAL_EQ] THEN MATCH_MP_TAC WORD_EQ_IMP THEN
REWRITE_TAC[DIMINDEX_64] THEN UNDISCH_TAC `p < 2 EXP 64` THEN ARITH_TAC;
(**** The other branch, very similar mutatis mutandis ***)
RULE_ASSUM_TAC(REWRITE_RULE[NOT_LE]) THEN
SUBGOAL_THEN `m:num <= n` ASSUME_TAC THENL
[ASM_SIMP_TAC[LT_IMP_LE]; ALL_TAC] THEN
SUBGOAL_THEN `a < 2 EXP (64 * n)` ASSUME_TAC THENL
[TRANS_TAC LTE_TRANS `2 EXP (64 * m)` THEN
ASM_REWRITE_TAC[LE_EXP; ARITH_EQ; LE_MULT_LCANCEL];
ALL_TAC] THEN
ENSURES_SEQUENCE_TAC (offset 0x7c)
`\s. read RDI s = word(p - n) /\
read RSI s = z /\
read R8 s = word(n - m) /\
read R9 s = y /\
read RCX s = x /\
read R10 s = word m /\
bignum_from_memory (word_add y (word(8 * m)),n - m) s =
highdigits b m /\
2 EXP (64 * m) * bitval(read CF s) + bignum_from_memory(z,m) s =
lowdigits a m + lowdigits b m` THEN
CONJ_TAC THENL
[ASM_CASES_TAC `m = 0` THENL
[UNDISCH_THEN `m = 0` SUBST_ALL_TAC THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
X86_SIM_TAC execth (1--6) THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0; BITVAL_CLAUSES] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[WORD_SUB] THEN CONV_TAC WORD_RULE;
ALL_TAC] THEN
ENSURES_WHILE_PUP_TAC `m:num` (offset 0x68) (offset 0x7a)
`\i s. (read RDI s = word(p - n) /\
read RSI s = z /\
read R8 s = word(n - m) /\
read R9 s = y /\
read RCX s = x /\
read RDX s = word(m - i) /\
read R10 s = word i /\
bignum_from_memory (word_add y (word(8 * i)),n - i) s =
highdigits b i /\
bignum_from_memory (word_add x (word(8 * i)),m - i) s =
highdigits a i /\
2 EXP (64 * i) * bitval(read CF s) + bignum_from_memory(z,i) s =
lowdigits a i + lowdigits b i) /\
(read ZF s <=> i = m)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[SUB_0] THEN X86_SIM_TAC execth (1--6) THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0; BITVAL_CLAUSES] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[WORD_ADD; WORD_SUB];
ALL_TAC; (*** Main loop invariant ***)
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
X86_SIM_TAC execth [1];
X86_SIM_TAC execth [1]] THEN
X_GEN_TAC `i:num` THEN STRIP_TAC THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
SUBGOAL_THEN `i:num < n` ASSUME_TAC THENL
[SIMPLE_ARITH_TAC; ALL_TAC] THEN
VAL_INT64_TAC `i:num` THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN ENSURES_INIT_TAC "s0" THEN
REPEAT(FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I
[ONCE_REWRITE_RULE[BIGNUM_FROM_MEMORY_BYTES]
BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS])) THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN STRIP_TAC THEN STRIP_TAC THEN
X86_STEPS_TAC execth (1--5) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
ASM_REWRITE_TAC[ARITH_RULE `m - (i + 1) = m - i - 1`] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < m ==> 1 <= m - i`];
DISCH_THEN SUBST1_TAC] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
ASM_SIMP_TAC[ARITH_RULE `i < m ==> (i + 1 = m <=> m - i - 1 = 0)`] THEN
CONJ_TAC THENL
[ALL_TAC; VAL_INT64_TAC `m - i - 1` THEN ASM_REWRITE_TAC[]] THEN
REWRITE_TAC[ARITH_RULE `64 * (i + 1) = 64 * i + 64`; EXP_ADD] THEN
REWRITE_TAC[GSYM ACCUMULATE_ADC; ARITH_RULE
`(t * e) * y + z + t * x:num = t * (e * y + x) + z`] THEN
ASM_REWRITE_TAC[LEFT_ADD_DISTRIB; GSYM ADD_ASSOC; VAL_WORD_BITVAL] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES] THEN ARITH_TAC;
ALL_TAC] THEN
ENSURES_SEQUENCE_TAC (offset 0x99)
`\s. read RDI s = word(p - n) /\
read RSI s = z /\
read R10 s = word n /\
2 EXP (64 * n) * val(read RAX s) + bignum_from_memory(z,n) s =
lowdigits a n + lowdigits b n` THEN
CONJ_TAC THENL
[SUBGOAL_THEN `~(m = n) /\ 0 < n - m /\ ~(n - m = 0)`
STRIP_ASSUME_TAC THENL [SIMPLE_ARITH_TAC; ALL_TAC] THEN
VAL_INT64_TAC `n - m:num` THEN
ENSURES_WHILE_PUP_TAC `n - m:num` (offset 0x7c) (offset 0x8e)
`\i s. (read RDI s = word(p - n) /\
read RSI s = z /\
read R9 s = y /\
read R8 s = word(n - m - i) /\
read R10 s = word(m + i) /\
bignum_from_memory(word_add y (word(8 * (m + i))),
n - (m + i)) s =
highdigits b (m + i) /\
2 EXP (64 * (m + i)) * bitval(read CF s) +
bignum_from_memory(z,m + i) s =
lowdigits a (m + i) + lowdigits b (m + i)) /\
(read ZF s <=> i = n - m)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[ADD_CLAUSES] THEN
ASM_REWRITE_TAC[WORD_RULE `word_sub (word(m + 1)) (word 1) = word m`];
ALL_TAC; (*** Main loop invariant ***)
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[] THEN X86_SIM_TAC execth [1];
ASM_SIMP_TAC[ARITH_RULE `m:num <= n ==> m + n - m = n`] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN ASM_REWRITE_TAC[] THEN
X86_SIM_TAC execth (1--3) THEN
ASM_REWRITE_TAC[VAL_WORD_BITVAL]] THEN
ASM_SIMP_TAC[ARITH_RULE
`m:num < n
==> (i < n - m <=> m + i < n) /\ (i = n - m <=> m + i = n)`] THEN
REWRITE_TAC[ARITH_RULE `n - m - i:num = n - (m + i)`] THEN
REWRITE_TAC[ARITH_RULE `m + i + 1 = (m + i) + 1`] THEN
X_GEN_TAC `j:num` THEN MP_TAC(ARITH_RULE `m <= m + j`) THEN
SPEC_TAC(`m + j:num`,`i:num`) THEN REPEAT STRIP_TAC THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
VAL_INT64_TAC `i:num` THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN ENSURES_INIT_TAC "s0" THEN
FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I
[ONCE_REWRITE_RULE[BIGNUM_FROM_MEMORY_BYTES]
BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS]) THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN STRIP_TAC THEN
X86_STEPS_TAC execth (1--5) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
ASM_REWRITE_TAC[ARITH_RULE `m - (i + 1) = m - i - 1`] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < m ==> 1 <= m - i`];
DISCH_THEN SUBST1_TAC] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
ASM_SIMP_TAC[ARITH_RULE `i < m ==> (i + 1 = m <=> m - i - 1 = 0)`] THEN
CONJ_TAC THENL
[ALL_TAC; VAL_INT64_TAC `n - i - 1` THEN ASM_REWRITE_TAC[]] THEN
REWRITE_TAC[ARITH_RULE `64 * (i + 1) = 64 * i + 64`; EXP_ADD] THEN
REWRITE_TAC[GSYM ACCUMULATE_ADC_0; ADD_CLAUSES; ARITH_RULE
`(t * e) * y + z + t * x:num = t * (e * y + x) + z`] THEN
ASM_REWRITE_TAC[LEFT_ADD_DISTRIB; GSYM ADD_ASSOC; VAL_WORD_BITVAL] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES; GSYM ADD_ASSOC; EQ_ADD_LCANCEL] THEN
MATCH_MP_TAC(NUM_RING `a = 0 ==> x + y + z = e * a + y + x + z`) THEN
MATCH_MP_TAC BIGDIGIT_ZERO THEN TRANS_TAC LTE_TRANS `2 EXP (64 * m)` THEN
ASM_REWRITE_TAC[LE_EXP; ARITH_EQ; LE_MULT_LCANCEL];
ALL_TAC] THEN
ASM_CASES_TAC `n:num = p` THENL
[UNDISCH_THEN `n:num = p` SUBST_ALL_TAC THEN ASM_REWRITE_TAC[] THEN
X86_SIM_TAC execth (1--2) THEN
BINOP_TAC THEN MATCH_MP_TAC LOWDIGITS_SELF THEN ASM_REWRITE_TAC[];
ALL_TAC] THEN
SUBGOAL_THEN `0 < p - n /\ ~(p - n = 0)` STRIP_ASSUME_TAC THENL
[SIMPLE_ARITH_TAC; ALL_TAC] THEN
VAL_INT64_TAC `p - n:num` THEN
ENSURES_SEQUENCE_TAC (offset 0xac)
`\s. read RDI s = word(p - n) /\
read RSI s = z /\
read R10 s = word n /\
read RAX s = word 0 /\
bignum_from_memory(z,n + 1) s = a + b` THEN
CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN ASM_REWRITE_TAC[] THEN
GHOST_INTRO_TAC `d:int64` `read RAX` THEN
X86_SIM_TAC execth (1--5) THEN
GEN_REWRITE_TAC LAND_CONV [ADD_SYM] THEN ASM_REWRITE_TAC[] THEN
BINOP_TAC THEN MATCH_MP_TAC LOWDIGITS_SELF THEN ASM_REWRITE_TAC[];
ALL_TAC] THEN
ASM_CASES_TAC `p = n + 1` THENL
[UNDISCH_THEN `p = n + 1` SUBST_ALL_TAC THEN REWRITE_TAC[ADD_SUB2] THEN
RULE_ASSUM_TAC(REWRITE_RULE[ADD_SUB2]) THEN
X86_SIM_TAC execth (1--3) THEN
REWRITE_TAC[VAL_WORD_0; ADD_CLAUSES; MULT_CLAUSES];
ALL_TAC] THEN
SUBGOAL_THEN
`0 < p - (n + 1) /\ ~(p - (n + 1) = 0) /\ ~(p - n = 1) /\ n + 1 <= p`
STRIP_ASSUME_TAC THENL [SIMPLE_ARITH_TAC; ALL_TAC] THEN
ENSURES_WHILE_PUP_TAC `p - (n + 1):num` (offset 0xa8) (offset 0xb2)
`\i s. (read RDI s = word(p - (n + 1) - i) /\
read R10 s = word((n + 1) + i) /\
read RSI s = z /\
read RAX s = word 0 /\
bignum_from_memory(z,(n + 1) + i) s = a + b) /\
(read ZF s <=> i = p - (n + 1))` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[SUB_0] THEN
X86_SIM_TAC execth (1--3) THEN
ASM_REWRITE_TAC[ADD_CLAUSES; VAL_WORD_1] THEN
ASM_REWRITE_TAC[VAL_EQ_0; WORD_SUB_EQ_0; GSYM VAL_EQ_1] THEN
CONJ_TAC THENL [ALL_TAC; CONV_TAC WORD_RULE] THEN
REWRITE_TAC[ARITH_RULE `p - (n + 1) = p - n - 1`] THEN
GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN SIMPLE_ARITH_TAC;
ALL_TAC; (*** Main loop invariant ***)
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[] THEN X86_SIM_TAC execth [1];
ASM_SIMP_TAC[ARITH_RULE `0 < n - m ==> m + n - m = n`] THEN
X86_SIM_TAC execth [1] THEN
REWRITE_TAC[VAL_WORD_0; ADD_CLAUSES; MULT_CLAUSES]] THEN
X_GEN_TAC `j:num` THEN MP_TAC(ARITH_RULE `n + 1 <= (n + 1) + j`) THEN
REWRITE_TAC[ARITH_RULE
`p - (n + 1) - (j + 1) = p - ((n + 1) + (j + 1))`] THEN
REWRITE_TAC[ARITH_RULE `p - (n + 1) - j = p - ((n + 1) + j)`] THEN
REWRITE_TAC[ARITH_RULE `(n + 1) + (j + 1) = ((n + 1) + j) + 1`] THEN
ASM_SIMP_TAC[ARITH_RULE
`0 < p - (n + 1)
==> (j + 1 = p - (n + 1) <=> ((n + 1) + j) + 1 = p) /\
(j < p - (n + 1) <=> (n + 1) + j < p) /\
(j = p - (n + 1) <=> (n + 1) + j = p)`] THEN
SPEC_TAC(`(n + 1) + j:num`,`i:num`) THEN REPEAT STRIP_TAC THEN
VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
X86_SIM_TAC execth (1--3) THEN
REWRITE_TAC[VAL_WORD_0; MULT_CLAUSES; ADD_CLAUSES] THEN
REWRITE_TAC[ARITH_RULE `p - (i + 1) = p - i - 1`] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < m ==> 1 <= m - i`];
DISCH_THEN SUBST1_TAC] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
ASM_SIMP_TAC[ARITH_RULE `i < p ==> (i + 1 = p <=> p - i = 1)`] THEN
REWRITE_TAC[VAL_EQ] THEN MATCH_MP_TAC WORD_EQ_IMP THEN
REWRITE_TAC[DIMINDEX_64] THEN UNDISCH_TAC `p < 2 EXP 64` THEN ARITH_TAC];;
(* ------------------------------------------------------------------------- *)
Correctness of standard ABI version .
(* ------------------------------------------------------------------------- *)
let BIGNUM_ADD_CORRECT = prove
(`!p z m x a n y b pc.
nonoverlapping (word pc,0xb5) (z,8 * val p) /\
(x = z \/ nonoverlapping(x,8 * val m) (z,8 * val p)) /\
(y = z \/ nonoverlapping(y,8 * val n) (z,8 * val p))
==> ensures x86
(\s. bytes_loaded s (word pc) bignum_add_mc /\
read RIP s = word pc /\
C_ARGUMENTS [p;z;m;x;n;y] s /\
bignum_from_memory (x,val m) s = a /\
bignum_from_memory (y,val n) s = b)
(\s. (read RIP s = word(pc + 0x5c) \/
read RIP s = word(pc + 0x9e) \/
read RIP s = word(pc + 0xb4)) /\
bignum_from_memory (z,val p) s =
(a + b) MOD 2 EXP (64 * val p) /\
2 EXP (64 * val p) * val(C_RETURN s) +
bignum_from_memory (z,val p) s =
lowdigits a (val p) + lowdigits b (val p))
(MAYCHANGE [RIP; RAX; RDI; RDX; R8; R10] ,,
MAYCHANGE SOME_FLAGS ,,
MAYCHANGE [memory :> bignum(z,val p)])`,
tac BIGNUM_ADD_EXEC
`\s. (read RIP s = word(pc + 0x5c) \/
read RIP s = word(pc + 0x9e) \/
read RIP s = word(pc + 0xb4)) /\
2 EXP (64 * p) * val(read RAX s) +
bignum_from_memory (z,p) s = lowdigits a p + lowdigits b p`
(curry mk_comb `(+) (pc:num)` o mk_small_numeral));;
let BIGNUM_ADD_SUBROUTINE_CORRECT = prove
(`!p z m x a n y b pc stackpointer returnaddress.
ALL (nonoverlapping (z,8 * val p)) [(word pc,0xb5); (stackpointer,8)] /\
(x = z \/ nonoverlapping(x,8 * val m) (z,8 * val p)) /\
(y = z \/ nonoverlapping(y,8 * val n) (z,8 * val p))
==> ensures x86
(\s. bytes_loaded s (word pc) bignum_add_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
C_ARGUMENTS [p;z;m;x;n;y] s /\
bignum_from_memory (x,val m) s = a /\
bignum_from_memory (y,val n) s = b)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
bignum_from_memory (z,val p) s =
(a + b) MOD 2 EXP (64 * val p) /\
2 EXP (64 * val p) * val(C_RETURN s) +
bignum_from_memory (z,val p) s =
lowdigits a (val p) + lowdigits b (val p))
(MAYCHANGE [RIP; RSP; RAX; RDI; RDX; R8; R10] ,,
MAYCHANGE SOME_FLAGS ,,
MAYCHANGE [memory :> bignum(z,val p)])`,
X86_ADD_RETURN_NOSTACK_TAC BIGNUM_ADD_EXEC BIGNUM_ADD_CORRECT);;
(* ------------------------------------------------------------------------- *)
(* Correctness of Windows ABI version. *)
(* ------------------------------------------------------------------------- *)
let windows_bignum_add_mc = define_from_elf
"windows_bignum_add_mc" "x86/generic/bignum_add.obj";;
let WINDOWS_BIGNUM_ADD_CORRECT = prove
(`!p z m x a n y b pc.
nonoverlapping (word pc,0xd3) (z,8 * val p) /\
(x = z \/ nonoverlapping(x,8 * val m) (z,8 * val p)) /\
(y = z \/ nonoverlapping(y,8 * val n) (z,8 * val p))
==> ensures x86
(\s. bytes_loaded s (word pc) windows_bignum_add_mc /\
read RIP s = word(pc + 0x18) /\
C_ARGUMENTS [p;z;m;x;n;y] s /\
bignum_from_memory (x,val m) s = a /\
bignum_from_memory (y,val n) s = b)
(\s. (read RIP s = word(pc + 0x74) \/
read RIP s = word(pc + 0xb8) \/
read RIP s = word(pc + 0xd0)) /\
bignum_from_memory (z,val p) s =
(a + b) MOD 2 EXP (64 * val p) /\
2 EXP (64 * val p) * val(C_RETURN s) +
bignum_from_memory (z,val p) s =
lowdigits a (val p) + lowdigits b (val p))
(MAYCHANGE [RIP; RAX; RDI; RDX; R8; R10] ,,
MAYCHANGE SOME_FLAGS ,,
MAYCHANGE [memory :> bignum(z,val p)])`,
tac (X86_MK_EXEC_RULE windows_bignum_add_mc)
`\s. (read RIP s = word(pc + 0x74) \/
read RIP s = word(pc + 0xb8) \/
read RIP s = word(pc + 0xd0)) /\
2 EXP (64 * p) * val(read RAX s) +
bignum_from_memory (z,p) s = lowdigits a p + lowdigits b p`
(curry mk_comb `(+) (pc:num)` o mk_small_numeral o
(fun n -> if n < 0x5c then n + 24
else if n < 0x9e then n + 26
else n + 28)));;
let WINDOWS_BIGNUM_ADD_SUBROUTINE_CORRECT = prove
(`!p z m x a n y b pc stackpointer returnaddress.
ALL (nonoverlapping (word_sub stackpointer (word 16),16))
[(word pc,0xd3); (x,8 * val m); (y,8 * val n)] /\
ALL (nonoverlapping (z,8 * val p))
[(word pc,0xd3); (word_sub stackpointer (word 16),24)] /\
(x = z \/ nonoverlapping(x,8 * val m) (z,8 * val p)) /\
(y = z \/ nonoverlapping(y,8 * val n) (z,8 * val p))
==> ensures x86
(\s. bytes_loaded s (word pc) windows_bignum_add_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
WINDOWS_C_ARGUMENTS [p;z;m;x;n;y] s /\
bignum_from_memory (x,val m) s = a /\
bignum_from_memory (y,val n) s = b)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
bignum_from_memory (z,val p) s =
(a + b) MOD 2 EXP (64 * val p) /\
2 EXP (64 * val p) * val(WINDOWS_C_RETURN s) +
bignum_from_memory (z,val p) s =
lowdigits a (val p) + lowdigits b (val p))
(MAYCHANGE [RIP; RSP; R9; RCX; RAX; RDX; R8; R10] ,,
MAYCHANGE SOME_FLAGS ,,
MAYCHANGE [memory :> bignum(z,val p);
memory :> bytes(word_sub stackpointer (word 16),16)])`,
REWRITE_TAC[WINDOWS_ABI_STACK_THM] THEN
GEN_X86_ADD_RETURN_STACK_TAC (X86_MK_EXEC_RULE windows_bignum_add_mc)
WINDOWS_BIGNUM_ADD_CORRECT
`[RDI; RSI]` 16 (8,3));;
| null | https://raw.githubusercontent.com/awslabs/s2n-bignum/824c15f908d7a343af1b2f378cfedd36e880bdde/x86/proofs/bignum_add.ml | ocaml | =========================================================================
Addition of bignums.
=========================================================================
XOR (% r10) (% r10)
SUB (% rdi) (% rdx)
INC (% rdx)
TEST (% r8) (% r8)
INC (% r10)
ADC (% rax) (Imm8 (word 0))
INC (% r10)
ADC (% rax) (Imm8 (word 0))
TEST (% rdi) (% rdi)
SUB (% rdi) (% r8)
SUB (% r8) (% rdx)
TEST (% rdx) (% rdx)
INC (% r10)
ADC (% rax) (Imm8 (word 0))
INC (% r10)
ADC (% rax) (Imm8 (word 0))
TEST (% rdi) (% rdi)
XOR (% rax) (% rax)
INC (% r10)
-------------------------------------------------------------------------
-------------------------------------------------------------------------
** Remove redundancy in the conclusion **
** Reshuffle to handle clamping and just assume m <= p and n <= p **
** Case split following the initial branch, m >= n case then m < n **
** Main loop invariant **
** Main loop invariant **
** Main loop invariant **
*** The other branch, very similar mutatis mutandis **
** Main loop invariant **
** Main loop invariant **
** Main loop invariant **
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Correctness of Windows ABI version.
------------------------------------------------------------------------- |
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved .
* SPDX - License - Identifier : Apache-2.0 OR ISC
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 OR ISC
*)
* * * print_literal_from_elf " x86 / generic / " ; ;
* * *
****)
let bignum_add_mc =
define_assert_from_elf "bignum_add_mc" "x86/generic/bignum_add.o"
[
CMP ( % rdi ) ( % rdx )
CMOVB ( % rdx ) ( % rdi )
CMP ( % rdi ) ( % r8 )
CMOVB ( % r8 ) ( % rdi )
CMP ( % rdx ) ( % r8 )
JB ( Imm8 ( word 71 ) )
SUB ( % rdx ) ( % r8 )
JE ( Imm8 ( word 37 ) )
MOV ( % rax ) ( ( % % % ( rcx,3,r10 ) ) )
ADC ( % rax ) ( ( % % % ( r9,3,r10 ) ) )
MOV ( ( % % % ( rsi,3,r10 ) ) ) ( % rax )
DEC ( % r8 )
JNE ( Imm8 ( word 236 ) )
JMP ( Imm8 ( word 15 ) )
MOV ( % rax ) ( ( % % % ( rcx,3,r10 ) ) )
MOV ( ( % % % ( rsi,3,r10 ) ) ) ( % rax )
DEC ( % rdx )
JNE ( Imm8 ( word 236 ) )
0xb8; 0x00; 0x00; 0x00; 0x00;
MOV ( % eax ) ( Imm32 ( word 0 ) )
JNE ( Imm8 ( word 67 ) )
RET
JE ( Imm8 ( word 20 ) )
MOV ( % rax ) ( ( % % % ( rcx,3,r10 ) ) )
ADC ( % rax ) ( ( % % % ( r9,3,r10 ) ) )
MOV ( ( % % % ( rsi,3,r10 ) ) ) ( % rax )
DEC ( % rdx )
JNE ( Imm8 ( word 236 ) )
MOV ( % rax ) ( ( % % % ( r9,3,r10 ) ) )
MOV ( ( % % % ( rsi,3,r10 ) ) ) ( % rax )
DEC ( % r8 )
JNE ( Imm8 ( word 236 ) )
0xb8; 0x00; 0x00; 0x00; 0x00;
MOV ( % eax ) ( Imm32 ( word 0 ) )
JNE ( Imm8 ( word 1 ) )
RET
MOV ( ( % % % ( rsi,3,r10 ) ) ) ( % rax )
JMP ( Imm8 ( word 4 ) )
MOV ( ( % % % ( rsi,3,r10 ) ) ) ( % rax )
DEC ( % rdi )
JNE ( Imm8 ( word 244 ) )
RET
];;
let BIGNUM_ADD_EXEC = X86_MK_EXEC_RULE bignum_add_mc;;
Common tactic for slightly different standard and Windows variants .
let tac execth cleanpost offset =
W64_GEN_TAC `p:num` THEN X_GEN_TAC `z:int64` THEN
W64_GEN_TAC `m:num` THEN MAP_EVERY X_GEN_TAC [`x:int64`; `a:num`] THEN
W64_GEN_TAC `n:num` THEN MAP_EVERY X_GEN_TAC [`y:int64`; `b:num`] THEN
X_GEN_TAC `pc:num` THEN REWRITE_TAC[NONOVERLAPPING_CLAUSES] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS] THEN DISCH_TAC THEN
ENSURES_POSTCONDITION_TAC cleanpost THEN REWRITE_TAC[] THEN CONJ_TAC THENL
[X_GEN_TAC `s:x86state` THEN MATCH_MP_TAC MONO_AND THEN REWRITE_TAC[] THEN
ASM_SIMP_TAC[lowdigits; MOD_LT] THEN
DISCH_THEN(MP_TAC o AP_TERM `\x. x MOD 2 EXP (64 * p)`) THEN
SIMP_TAC[MOD_MULT_ADD; MOD_LT; BIGNUM_FROM_MEMORY_BOUND] THEN
CONV_TAC MOD_DOWN_CONV THEN REWRITE_TAC[];
ALL_TAC] THEN
ENSURES_SEQUENCE_TAC (offset 0x11)
`\s. read RDI s = word p /\
read RSI s = z /\
read RDX s = word(MIN m p) /\
read RCX s = x /\
read R8 s = word(MIN n p) /\
read R9 s = y /\
read R10 s = word 0 /\
bignum_from_memory(x,MIN m p) s = lowdigits a p /\
bignum_from_memory(y,MIN n p) s = lowdigits b p` THEN
CONJ_TAC THENL
[X86_SIM_TAC execth (1--5) THEN
ASM_REWRITE_TAC[lowdigits; REWRITE_RULE[BIGNUM_FROM_MEMORY_BYTES]
(GSYM BIGNUM_FROM_MEMORY_MOD)] THEN
GEN_REWRITE_TAC (BINOP_CONV o LAND_CONV) [GSYM COND_RAND] THEN
CONJ_TAC THEN AP_TERM_TAC THEN ARITH_TAC;
FIRST_X_ASSUM(CONJUNCTS_THEN MP_TAC)] THEN
SUBGOAL_THEN
`lowdigits (a + b) p = lowdigits (lowdigits a p + lowdigits b p) p`
SUBST1_TAC THENL
[REWRITE_TAC[lowdigits] THEN CONV_TAC MOD_DOWN_CONV THEN REFL_TAC;
ALL_TAC] THEN
SUBGOAL_THEN
`!w n. w = z \/
nonoverlapping_modulo (2 EXP 64) (val w,8 * n) (val z,8 * p)
==> w:int64 = z \/
nonoverlapping_modulo (2 EXP 64)
(val w,8 * MIN n p) (val z,8 * p)`
(fun th -> DISCH_THEN(CONJUNCTS_THEN(MP_TAC o MATCH_MP th)))
THENL
[POP_ASSUM_LIST(K ALL_TAC) THEN REPEAT GEN_TAC THEN
MATCH_MP_TAC MONO_OR THEN REWRITE_TAC[] THEN
DISCH_TAC THEN NONOVERLAPPING_TAC;
ALL_TAC] THEN
MAP_EVERY UNDISCH_TAC [`p < 2 EXP 64`; `val(word p:int64) = p`] THEN
SUBGOAL_THEN `MIN m p < 2 EXP 64 /\ MIN n p < 2 EXP 64` MP_TAC THENL
[ASM_ARITH_TAC; POP_ASSUM_LIST(K ALL_TAC)] THEN
MP_TAC(ARITH_RULE `MIN m p <= p /\ MIN n p <= p`) THEN
MAP_EVERY SPEC_TAC
[`lowdigits a p`,`a:num`; `lowdigits b p`,`b:num`;
`MIN m p`,`m:num`; `MIN n p`,`n:num`] THEN
REPEAT GEN_TAC THEN STRIP_TAC THEN STRIP_TAC THEN REPEAT DISCH_TAC THEN
MAP_EVERY VAL_INT64_TAC [`m:num`; `n:num`] THEN
BIGNUM_RANGE_TAC "m" "a" THEN BIGNUM_RANGE_TAC "n" "b" THEN
* * Get a basic bound on p from the nonoverlapping assumptions * *
FIRST_ASSUM(MP_TAC o MATCH_MP (ONCE_REWRITE_RULE[IMP_CONJ]
NONOVERLAPPING_IMP_SMALL_RIGHT_ALT)) THEN
ANTS_TAC THENL [CONV_TAC NUM_REDUCE_CONV; DISCH_TAC] THEN
ASM_CASES_TAC `n:num <= m` THENL
[SUBGOAL_THEN `~(m:num < n)` ASSUME_TAC THENL
[ASM_REWRITE_TAC[NOT_LT]; ALL_TAC] THEN
SUBGOAL_THEN `b < 2 EXP (64 * m)` ASSUME_TAC THENL
[TRANS_TAC LTE_TRANS `2 EXP (64 * n)` THEN
ASM_REWRITE_TAC[LE_EXP; ARITH_EQ; LE_MULT_LCANCEL];
ALL_TAC] THEN
ENSURES_SEQUENCE_TAC (offset 0x49)
`\s. read RDI s = word(p - m) /\
read RSI s = z /\
read RDX s = word(m - n + 1) /\
read RCX s = x /\
read R9 s = y /\
read R10 s = word n /\
bignum_from_memory (word_add x (word(8 * n)),m - n) s =
highdigits a n /\
2 EXP (64 * n) * bitval(read CF s) + bignum_from_memory(z,n) s =
lowdigits a n + lowdigits b n` THEN
CONJ_TAC THENL
[ASM_CASES_TAC `n = 0` THENL
[UNDISCH_THEN `n = 0` SUBST_ALL_TAC THEN
ASM_REWRITE_TAC[SUB_0] THEN X86_SIM_TAC execth (1--7) THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0; BITVAL_CLAUSES] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[WORD_SUB] THEN CONV_TAC WORD_RULE;
ALL_TAC] THEN
ENSURES_WHILE_PUP_TAC `n:num` (offset 0x24) (offset 0x36)
`\i s. (read RDI s = word(p - m) /\
read RSI s = z /\
read RDX s = word(m - n + 1) /\
read RCX s = x /\
read R9 s = y /\
read R8 s = word(n - i) /\
read R10 s = word i /\
bignum_from_memory (word_add x (word(8 * i)),m - i) s =
highdigits a i /\
bignum_from_memory (word_add y (word(8 * i)),n - i) s =
highdigits b i /\
2 EXP (64 * i) * bitval(read CF s) + bignum_from_memory(z,i) s =
lowdigits a i + lowdigits b i) /\
(read ZF s <=> i = n)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[SUB_0] THEN X86_SIM_TAC execth (1--7) THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0; BITVAL_CLAUSES] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[WORD_ADD; WORD_SUB];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[] THEN X86_SIM_TAC execth [1];
X86_SIM_TAC execth (1--2)] THEN
X_GEN_TAC `i:num` THEN STRIP_TAC THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
SUBGOAL_THEN `i:num < m` ASSUME_TAC THENL
[SIMPLE_ARITH_TAC; ALL_TAC] THEN
VAL_INT64_TAC `i:num` THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN ENSURES_INIT_TAC "s0" THEN
REPEAT(FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I
[ONCE_REWRITE_RULE[BIGNUM_FROM_MEMORY_BYTES]
BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS])) THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN STRIP_TAC THEN STRIP_TAC THEN
X86_STEPS_TAC execth (1--5) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
ASM_REWRITE_TAC[ARITH_RULE `n - (i + 1) = n - i - 1`] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < n ==> 1 <= n - i`];
DISCH_THEN SUBST1_TAC] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
ASM_SIMP_TAC[ARITH_RULE `i < n ==> (i + 1 = n <=> n - i - 1 = 0)`] THEN
CONJ_TAC THENL
[ALL_TAC; VAL_INT64_TAC `n - i - 1` THEN ASM_REWRITE_TAC[]] THEN
REWRITE_TAC[ARITH_RULE `64 * (i + 1) = 64 * i + 64`; EXP_ADD] THEN
REWRITE_TAC[GSYM ACCUMULATE_ADC; ARITH_RULE
`(t * e) * x + z + t * y:num = t * (e * x + y) + z`] THEN
ASM_REWRITE_TAC[LEFT_ADD_DISTRIB; GSYM ADD_ASSOC; VAL_WORD_BITVAL] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES] THEN ARITH_TAC;
ALL_TAC] THEN
ENSURES_SEQUENCE_TAC (offset 0x57)
`\s. read RDI s = word(p - m) /\
read RSI s = z /\
read R10 s = word m /\
2 EXP (64 * m) * val(read RAX s) + bignum_from_memory(z,m) s =
lowdigits a m + lowdigits b m` THEN
CONJ_TAC THENL
[ASM_CASES_TAC `m:num = n` THENL
[UNDISCH_THEN `m:num = n` SUBST_ALL_TAC THEN ASM_REWRITE_TAC[] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
X86_SIM_TAC execth (1--4) THEN
ASM_REWRITE_TAC[VAL_WORD_BITVAL];
ALL_TAC] THEN
SUBGOAL_THEN `n < m /\ 0 < m - n /\ ~(m - n = 0)` STRIP_ASSUME_TAC THENL
[SIMPLE_ARITH_TAC; ALL_TAC] THEN
VAL_INT64_TAC `m - n:num` THEN
ENSURES_WHILE_PUP_TAC `m - n:num` (offset 0x3a) (offset 0x4c)
`\i s. (read RDI s = word(p - m) /\
read RSI s = z /\
read RCX s = x /\
read RDX s = word(m - n - i) /\
read R10 s = word(n + i) /\
bignum_from_memory(word_add x (word(8 * (n + i))),
m - (n + i)) s =
highdigits a (n + i) /\
2 EXP (64 * (n + i)) * bitval(read CF s) +
bignum_from_memory(z,n + i) s =
lowdigits a (n + i) + lowdigits b (n + i)) /\
(read ZF s <=> i = m - n)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[SUB_0] THEN X86_SIM_TAC execth (1--2) THEN
ASM_REWRITE_TAC[ADD_CLAUSES] THEN
REWRITE_TAC[VAL_EQ; WORD_RULE
`word(a + 1):int64 = word 1 <=> word a:int64 = word 0`] THEN
CONJ_TAC THENL [ALL_TAC; CONV_TAC WORD_RULE] THEN
ASM_REWRITE_TAC[GSYM VAL_EQ_0];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[] THEN X86_SIM_TAC execth [1];
ASM_SIMP_TAC[ARITH_RULE `n:num <= m ==> n + m - n = m`] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN
X86_SIM_TAC execth (1--3) THEN
ASM_REWRITE_TAC[VAL_WORD_BITVAL]] THEN
ASM_SIMP_TAC[ARITH_RULE
`n:num < m
==> (i < m - n <=> n + i < m) /\ (i = m - n <=> n + i = m)`] THEN
REWRITE_TAC[ARITH_RULE `m - n - i:num = m - (n + i)`] THEN
REWRITE_TAC[ARITH_RULE `n + i + 1 = (n + i) + 1`] THEN
X_GEN_TAC `j:num` THEN MP_TAC(ARITH_RULE `n <= n + j`) THEN
SPEC_TAC(`n + j:num`,`i:num`) THEN REPEAT STRIP_TAC THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
VAL_INT64_TAC `i:num` THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN ENSURES_INIT_TAC "s0" THEN
FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I
[ONCE_REWRITE_RULE[BIGNUM_FROM_MEMORY_BYTES]
BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS]) THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN STRIP_TAC THEN
X86_STEPS_TAC execth (1--5) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
ASM_REWRITE_TAC[ARITH_RULE `n - (i + 1) = n - i - 1`] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < n ==> 1 <= n - i`];
DISCH_THEN SUBST1_TAC] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
ASM_SIMP_TAC[ARITH_RULE `i < n ==> (i + 1 = n <=> n - i - 1 = 0)`] THEN
CONJ_TAC THENL
[ALL_TAC; VAL_INT64_TAC `m - i - 1` THEN ASM_REWRITE_TAC[]] THEN
REWRITE_TAC[ARITH_RULE `64 * (i + 1) = 64 * i + 64`; EXP_ADD] THEN
REWRITE_TAC[GSYM ACCUMULATE_ADC_0; ADD_CLAUSES; ARITH_RULE
`(t * e) * x + z + t * y:num = t * (e * x + y) + z`] THEN
ASM_REWRITE_TAC[LEFT_ADD_DISTRIB; GSYM ADD_ASSOC; VAL_WORD_BITVAL] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES; GSYM ADD_ASSOC; EQ_ADD_LCANCEL] THEN
MATCH_MP_TAC(NUM_RING `b = 0 ==> x = e * b + x`) THEN
MATCH_MP_TAC BIGDIGIT_ZERO THEN TRANS_TAC LTE_TRANS `2 EXP (64 * n)` THEN
ASM_REWRITE_TAC[LE_EXP; ARITH_EQ; LE_MULT_LCANCEL];
ALL_TAC] THEN
ASM_CASES_TAC `m:num = p` THENL
[UNDISCH_THEN `m:num = p` SUBST_ALL_TAC THEN ASM_REWRITE_TAC[] THEN
X86_SIM_TAC execth (1--2) THEN ASM_REWRITE_TAC[] THEN
BINOP_TAC THEN MATCH_MP_TAC LOWDIGITS_SELF THEN ASM_REWRITE_TAC[];
ALL_TAC] THEN
SUBGOAL_THEN `0 < p - m /\ ~(p - m = 0)` STRIP_ASSUME_TAC THENL
[SIMPLE_ARITH_TAC; ALL_TAC] THEN
VAL_INT64_TAC `p - m:num` THEN
ENSURES_SEQUENCE_TAC (offset 0xac)
`\s. read RDI s = word(p - m) /\
read RSI s = z /\
read R10 s = word m /\
read RAX s = word 0 /\
bignum_from_memory(z,m + 1) s = a + b` THEN
CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN ASM_REWRITE_TAC[] THEN
GHOST_INTRO_TAC `d:int64` `read RAX` THEN
X86_SIM_TAC execth (1--5) THEN
GEN_REWRITE_TAC LAND_CONV [ADD_SYM] THEN ASM_REWRITE_TAC[] THEN
BINOP_TAC THEN MATCH_MP_TAC LOWDIGITS_SELF THEN ASM_REWRITE_TAC[];
ALL_TAC] THEN
ASM_CASES_TAC `p = m + 1` THENL
[UNDISCH_THEN `p = m + 1` SUBST_ALL_TAC THEN REWRITE_TAC[ADD_SUB2] THEN
RULE_ASSUM_TAC(REWRITE_RULE[ADD_SUB2]) THEN
X86_SIM_TAC execth (1--3) THEN
REWRITE_TAC[VAL_WORD_0; ADD_CLAUSES; MULT_CLAUSES];
ALL_TAC] THEN
SUBGOAL_THEN
`0 < p - (m + 1) /\ ~(p - (m + 1) = 0) /\ ~(p - m = 1) /\ m + 1 <= p`
STRIP_ASSUME_TAC THENL [SIMPLE_ARITH_TAC; ALL_TAC] THEN
ENSURES_WHILE_PUP_TAC `p - (m + 1):num` (offset 0xa8) (offset 0xb2)
`\i s. (read RDI s = word(p - (m + 1) - i) /\
read R10 s = word((m + 1) + i) /\
read RSI s = z /\
read RAX s = word 0 /\
bignum_from_memory(z,(m + 1) + i) s = a + b) /\
(read ZF s <=> i = p - (m + 1))` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[SUB_0] THEN X86_SIM_TAC execth (1--3) THEN
ASM_REWRITE_TAC[ADD_CLAUSES; VAL_WORD_1] THEN
CONJ_TAC THENL [ALL_TAC; CONV_TAC WORD_RULE] THEN
REWRITE_TAC[ARITH_RULE `p - (m + 1) = p - m - 1`] THEN
GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN SIMPLE_ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
X86_SIM_TAC execth [1];
ASM_SIMP_TAC[ARITH_RULE `0 < m - n ==> n + m - n = m`] THEN
X86_SIM_TAC execth [1] THEN
REWRITE_TAC[VAL_WORD_0; ADD_CLAUSES; MULT_CLAUSES]] THEN
X_GEN_TAC `j:num` THEN MP_TAC(ARITH_RULE `m + 1 <= (m + 1) + j`) THEN
REWRITE_TAC[ARITH_RULE
`p - (m + 1) - (j + 1) = p - ((m + 1) + (j + 1))`] THEN
REWRITE_TAC[ARITH_RULE `p - (m + 1) - j = p - ((m + 1) + j)`] THEN
REWRITE_TAC[ARITH_RULE `(m + 1) + (j + 1) = ((m + 1) + j) + 1`] THEN
ASM_SIMP_TAC[ARITH_RULE
`0 < p - (m + 1)
==> (j + 1 = p - (m + 1) <=> ((m + 1) + j) + 1 = p) /\
(j < p - (m + 1) <=> (m + 1) + j < p) /\
(j = p - (m + 1) <=> (m + 1) + j = p)`] THEN
SPEC_TAC(`(m + 1) + j:num`,`i:num`) THEN REPEAT STRIP_TAC THEN
VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
X86_SIM_TAC execth (1--3) THEN
REWRITE_TAC[VAL_WORD_0; MULT_CLAUSES; ADD_CLAUSES] THEN
REWRITE_TAC[ARITH_RULE `p - (i + 1) = p - i - 1`] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < n ==> 1 <= n - i`];
DISCH_THEN SUBST1_TAC] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
ASM_SIMP_TAC[ARITH_RULE `i < p ==> (i + 1 = p <=> p - i = 1)`] THEN
REWRITE_TAC[VAL_EQ] THEN MATCH_MP_TAC WORD_EQ_IMP THEN
REWRITE_TAC[DIMINDEX_64] THEN UNDISCH_TAC `p < 2 EXP 64` THEN ARITH_TAC;
RULE_ASSUM_TAC(REWRITE_RULE[NOT_LE]) THEN
SUBGOAL_THEN `m:num <= n` ASSUME_TAC THENL
[ASM_SIMP_TAC[LT_IMP_LE]; ALL_TAC] THEN
SUBGOAL_THEN `a < 2 EXP (64 * n)` ASSUME_TAC THENL
[TRANS_TAC LTE_TRANS `2 EXP (64 * m)` THEN
ASM_REWRITE_TAC[LE_EXP; ARITH_EQ; LE_MULT_LCANCEL];
ALL_TAC] THEN
ENSURES_SEQUENCE_TAC (offset 0x7c)
`\s. read RDI s = word(p - n) /\
read RSI s = z /\
read R8 s = word(n - m) /\
read R9 s = y /\
read RCX s = x /\
read R10 s = word m /\
bignum_from_memory (word_add y (word(8 * m)),n - m) s =
highdigits b m /\
2 EXP (64 * m) * bitval(read CF s) + bignum_from_memory(z,m) s =
lowdigits a m + lowdigits b m` THEN
CONJ_TAC THENL
[ASM_CASES_TAC `m = 0` THENL
[UNDISCH_THEN `m = 0` SUBST_ALL_TAC THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
X86_SIM_TAC execth (1--6) THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0; BITVAL_CLAUSES] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[WORD_SUB] THEN CONV_TAC WORD_RULE;
ALL_TAC] THEN
ENSURES_WHILE_PUP_TAC `m:num` (offset 0x68) (offset 0x7a)
`\i s. (read RDI s = word(p - n) /\
read RSI s = z /\
read R8 s = word(n - m) /\
read R9 s = y /\
read RCX s = x /\
read RDX s = word(m - i) /\
read R10 s = word i /\
bignum_from_memory (word_add y (word(8 * i)),n - i) s =
highdigits b i /\
bignum_from_memory (word_add x (word(8 * i)),m - i) s =
highdigits a i /\
2 EXP (64 * i) * bitval(read CF s) + bignum_from_memory(z,i) s =
lowdigits a i + lowdigits b i) /\
(read ZF s <=> i = m)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[SUB_0] THEN X86_SIM_TAC execth (1--6) THEN
ASM_REWRITE_TAC[LOWDIGITS_0; HIGHDIGITS_0; BITVAL_CLAUSES] THEN
REWRITE_TAC[GSYM BIGNUM_FROM_MEMORY_BYTES] THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_TRIVIAL] THEN
ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; WORD_ADD_0] THEN
ASM_REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
ASM_REWRITE_TAC[WORD_ADD; WORD_SUB];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
X86_SIM_TAC execth [1];
X86_SIM_TAC execth [1]] THEN
X_GEN_TAC `i:num` THEN STRIP_TAC THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
SUBGOAL_THEN `i:num < n` ASSUME_TAC THENL
[SIMPLE_ARITH_TAC; ALL_TAC] THEN
VAL_INT64_TAC `i:num` THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN ENSURES_INIT_TAC "s0" THEN
REPEAT(FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I
[ONCE_REWRITE_RULE[BIGNUM_FROM_MEMORY_BYTES]
BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS])) THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN STRIP_TAC THEN STRIP_TAC THEN
X86_STEPS_TAC execth (1--5) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
ASM_REWRITE_TAC[ARITH_RULE `m - (i + 1) = m - i - 1`] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < m ==> 1 <= m - i`];
DISCH_THEN SUBST1_TAC] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
ASM_SIMP_TAC[ARITH_RULE `i < m ==> (i + 1 = m <=> m - i - 1 = 0)`] THEN
CONJ_TAC THENL
[ALL_TAC; VAL_INT64_TAC `m - i - 1` THEN ASM_REWRITE_TAC[]] THEN
REWRITE_TAC[ARITH_RULE `64 * (i + 1) = 64 * i + 64`; EXP_ADD] THEN
REWRITE_TAC[GSYM ACCUMULATE_ADC; ARITH_RULE
`(t * e) * y + z + t * x:num = t * (e * y + x) + z`] THEN
ASM_REWRITE_TAC[LEFT_ADD_DISTRIB; GSYM ADD_ASSOC; VAL_WORD_BITVAL] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES] THEN ARITH_TAC;
ALL_TAC] THEN
ENSURES_SEQUENCE_TAC (offset 0x99)
`\s. read RDI s = word(p - n) /\
read RSI s = z /\
read R10 s = word n /\
2 EXP (64 * n) * val(read RAX s) + bignum_from_memory(z,n) s =
lowdigits a n + lowdigits b n` THEN
CONJ_TAC THENL
[SUBGOAL_THEN `~(m = n) /\ 0 < n - m /\ ~(n - m = 0)`
STRIP_ASSUME_TAC THENL [SIMPLE_ARITH_TAC; ALL_TAC] THEN
VAL_INT64_TAC `n - m:num` THEN
ENSURES_WHILE_PUP_TAC `n - m:num` (offset 0x7c) (offset 0x8e)
`\i s. (read RDI s = word(p - n) /\
read RSI s = z /\
read R9 s = y /\
read R8 s = word(n - m - i) /\
read R10 s = word(m + i) /\
bignum_from_memory(word_add y (word(8 * (m + i))),
n - (m + i)) s =
highdigits b (m + i) /\
2 EXP (64 * (m + i)) * bitval(read CF s) +
bignum_from_memory(z,m + i) s =
lowdigits a (m + i) + lowdigits b (m + i)) /\
(read ZF s <=> i = n - m)` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES; SUB_0] THEN
ENSURES_INIT_TAC "s0" THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[ADD_CLAUSES] THEN
ASM_REWRITE_TAC[WORD_RULE `word_sub (word(m + 1)) (word 1) = word m`];
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[] THEN X86_SIM_TAC execth [1];
ASM_SIMP_TAC[ARITH_RULE `m:num <= n ==> m + n - m = n`] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN ASM_REWRITE_TAC[] THEN
X86_SIM_TAC execth (1--3) THEN
ASM_REWRITE_TAC[VAL_WORD_BITVAL]] THEN
ASM_SIMP_TAC[ARITH_RULE
`m:num < n
==> (i < n - m <=> m + i < n) /\ (i = n - m <=> m + i = n)`] THEN
REWRITE_TAC[ARITH_RULE `n - m - i:num = n - (m + i)`] THEN
REWRITE_TAC[ARITH_RULE `m + i + 1 = (m + i) + 1`] THEN
X_GEN_TAC `j:num` THEN MP_TAC(ARITH_RULE `m <= m + j`) THEN
SPEC_TAC(`m + j:num`,`i:num`) THEN REPEAT STRIP_TAC THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
VAL_INT64_TAC `i:num` THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN
GHOST_INTRO_TAC `cin:bool` `read CF` THEN ENSURES_INIT_TAC "s0" THEN
FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I
[ONCE_REWRITE_RULE[BIGNUM_FROM_MEMORY_BYTES]
BIGNUM_FROM_MEMORY_OFFSET_EQ_HIGHDIGITS]) THEN
ASM_REWRITE_TAC[SUB_EQ_0; GSYM NOT_LT] THEN STRIP_TAC THEN
X86_STEPS_TAC execth (1--5) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN
ASM_REWRITE_TAC[ARITH_RULE `m - (i + 1) = m - i - 1`] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < m ==> 1 <= m - i`];
DISCH_THEN SUBST1_TAC] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
ASM_SIMP_TAC[ARITH_RULE `i < m ==> (i + 1 = m <=> m - i - 1 = 0)`] THEN
CONJ_TAC THENL
[ALL_TAC; VAL_INT64_TAC `n - i - 1` THEN ASM_REWRITE_TAC[]] THEN
REWRITE_TAC[ARITH_RULE `64 * (i + 1) = 64 * i + 64`; EXP_ADD] THEN
REWRITE_TAC[GSYM ACCUMULATE_ADC_0; ADD_CLAUSES; ARITH_RULE
`(t * e) * y + z + t * x:num = t * (e * y + x) + z`] THEN
ASM_REWRITE_TAC[LEFT_ADD_DISTRIB; GSYM ADD_ASSOC; VAL_WORD_BITVAL] THEN
SIMP_TAC[VAL_WORD_EQ; DIMINDEX_64; BIGDIGIT_BOUND] THEN
REWRITE_TAC[LOWDIGITS_CLAUSES; GSYM ADD_ASSOC; EQ_ADD_LCANCEL] THEN
MATCH_MP_TAC(NUM_RING `a = 0 ==> x + y + z = e * a + y + x + z`) THEN
MATCH_MP_TAC BIGDIGIT_ZERO THEN TRANS_TAC LTE_TRANS `2 EXP (64 * m)` THEN
ASM_REWRITE_TAC[LE_EXP; ARITH_EQ; LE_MULT_LCANCEL];
ALL_TAC] THEN
ASM_CASES_TAC `n:num = p` THENL
[UNDISCH_THEN `n:num = p` SUBST_ALL_TAC THEN ASM_REWRITE_TAC[] THEN
X86_SIM_TAC execth (1--2) THEN
BINOP_TAC THEN MATCH_MP_TAC LOWDIGITS_SELF THEN ASM_REWRITE_TAC[];
ALL_TAC] THEN
SUBGOAL_THEN `0 < p - n /\ ~(p - n = 0)` STRIP_ASSUME_TAC THENL
[SIMPLE_ARITH_TAC; ALL_TAC] THEN
VAL_INT64_TAC `p - n:num` THEN
ENSURES_SEQUENCE_TAC (offset 0xac)
`\s. read RDI s = word(p - n) /\
read RSI s = z /\
read R10 s = word n /\
read RAX s = word 0 /\
bignum_from_memory(z,n + 1) s = a + b` THEN
CONJ_TAC THENL
[REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN ASM_REWRITE_TAC[] THEN
GHOST_INTRO_TAC `d:int64` `read RAX` THEN
X86_SIM_TAC execth (1--5) THEN
GEN_REWRITE_TAC LAND_CONV [ADD_SYM] THEN ASM_REWRITE_TAC[] THEN
BINOP_TAC THEN MATCH_MP_TAC LOWDIGITS_SELF THEN ASM_REWRITE_TAC[];
ALL_TAC] THEN
ASM_CASES_TAC `p = n + 1` THENL
[UNDISCH_THEN `p = n + 1` SUBST_ALL_TAC THEN REWRITE_TAC[ADD_SUB2] THEN
RULE_ASSUM_TAC(REWRITE_RULE[ADD_SUB2]) THEN
X86_SIM_TAC execth (1--3) THEN
REWRITE_TAC[VAL_WORD_0; ADD_CLAUSES; MULT_CLAUSES];
ALL_TAC] THEN
SUBGOAL_THEN
`0 < p - (n + 1) /\ ~(p - (n + 1) = 0) /\ ~(p - n = 1) /\ n + 1 <= p`
STRIP_ASSUME_TAC THENL [SIMPLE_ARITH_TAC; ALL_TAC] THEN
ENSURES_WHILE_PUP_TAC `p - (n + 1):num` (offset 0xa8) (offset 0xb2)
`\i s. (read RDI s = word(p - (n + 1) - i) /\
read R10 s = word((n + 1) + i) /\
read RSI s = z /\
read RAX s = word 0 /\
bignum_from_memory(z,(n + 1) + i) s = a + b) /\
(read ZF s <=> i = p - (n + 1))` THEN
ASM_REWRITE_TAC[] THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[SUB_0] THEN
X86_SIM_TAC execth (1--3) THEN
ASM_REWRITE_TAC[ADD_CLAUSES; VAL_WORD_1] THEN
ASM_REWRITE_TAC[VAL_EQ_0; WORD_SUB_EQ_0; GSYM VAL_EQ_1] THEN
CONJ_TAC THENL [ALL_TAC; CONV_TAC WORD_RULE] THEN
REWRITE_TAC[ARITH_RULE `p - (n + 1) = p - n - 1`] THEN
GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN SIMPLE_ARITH_TAC;
X_GEN_TAC `i:num` THEN STRIP_TAC THEN VAL_INT64_TAC `i:num` THEN
ASM_REWRITE_TAC[] THEN X86_SIM_TAC execth [1];
ASM_SIMP_TAC[ARITH_RULE `0 < n - m ==> m + n - m = n`] THEN
X86_SIM_TAC execth [1] THEN
REWRITE_TAC[VAL_WORD_0; ADD_CLAUSES; MULT_CLAUSES]] THEN
X_GEN_TAC `j:num` THEN MP_TAC(ARITH_RULE `n + 1 <= (n + 1) + j`) THEN
REWRITE_TAC[ARITH_RULE
`p - (n + 1) - (j + 1) = p - ((n + 1) + (j + 1))`] THEN
REWRITE_TAC[ARITH_RULE `p - (n + 1) - j = p - ((n + 1) + j)`] THEN
REWRITE_TAC[ARITH_RULE `(n + 1) + (j + 1) = ((n + 1) + j) + 1`] THEN
ASM_SIMP_TAC[ARITH_RULE
`0 < p - (n + 1)
==> (j + 1 = p - (n + 1) <=> ((n + 1) + j) + 1 = p) /\
(j < p - (n + 1) <=> (n + 1) + j < p) /\
(j = p - (n + 1) <=> (n + 1) + j = p)`] THEN
SPEC_TAC(`(n + 1) + j:num`,`i:num`) THEN REPEAT STRIP_TAC THEN
VAL_INT64_TAC `i:num` THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_STEP] THEN
X86_SIM_TAC execth (1--3) THEN
REWRITE_TAC[VAL_WORD_0; MULT_CLAUSES; ADD_CLAUSES] THEN
REWRITE_TAC[ARITH_RULE `p - (i + 1) = p - i - 1`] THEN
MATCH_MP_TAC(TAUT `p /\ (p ==> q) ==> p /\ q`) THEN CONJ_TAC THENL
[GEN_REWRITE_TAC RAND_CONV [WORD_SUB] THEN
ASM_SIMP_TAC[ARITH_RULE `i < m ==> 1 <= m - i`];
DISCH_THEN SUBST1_TAC] THEN
CONJ_TAC THENL [CONV_TAC WORD_RULE; ALL_TAC] THEN
ASM_SIMP_TAC[ARITH_RULE `i < p ==> (i + 1 = p <=> p - i = 1)`] THEN
REWRITE_TAC[VAL_EQ] THEN MATCH_MP_TAC WORD_EQ_IMP THEN
REWRITE_TAC[DIMINDEX_64] THEN UNDISCH_TAC `p < 2 EXP 64` THEN ARITH_TAC];;
Correctness of standard ABI version .
let BIGNUM_ADD_CORRECT = prove
(`!p z m x a n y b pc.
nonoverlapping (word pc,0xb5) (z,8 * val p) /\
(x = z \/ nonoverlapping(x,8 * val m) (z,8 * val p)) /\
(y = z \/ nonoverlapping(y,8 * val n) (z,8 * val p))
==> ensures x86
(\s. bytes_loaded s (word pc) bignum_add_mc /\
read RIP s = word pc /\
C_ARGUMENTS [p;z;m;x;n;y] s /\
bignum_from_memory (x,val m) s = a /\
bignum_from_memory (y,val n) s = b)
(\s. (read RIP s = word(pc + 0x5c) \/
read RIP s = word(pc + 0x9e) \/
read RIP s = word(pc + 0xb4)) /\
bignum_from_memory (z,val p) s =
(a + b) MOD 2 EXP (64 * val p) /\
2 EXP (64 * val p) * val(C_RETURN s) +
bignum_from_memory (z,val p) s =
lowdigits a (val p) + lowdigits b (val p))
(MAYCHANGE [RIP; RAX; RDI; RDX; R8; R10] ,,
MAYCHANGE SOME_FLAGS ,,
MAYCHANGE [memory :> bignum(z,val p)])`,
tac BIGNUM_ADD_EXEC
`\s. (read RIP s = word(pc + 0x5c) \/
read RIP s = word(pc + 0x9e) \/
read RIP s = word(pc + 0xb4)) /\
2 EXP (64 * p) * val(read RAX s) +
bignum_from_memory (z,p) s = lowdigits a p + lowdigits b p`
(curry mk_comb `(+) (pc:num)` o mk_small_numeral));;
let BIGNUM_ADD_SUBROUTINE_CORRECT = prove
(`!p z m x a n y b pc stackpointer returnaddress.
ALL (nonoverlapping (z,8 * val p)) [(word pc,0xb5); (stackpointer,8)] /\
(x = z \/ nonoverlapping(x,8 * val m) (z,8 * val p)) /\
(y = z \/ nonoverlapping(y,8 * val n) (z,8 * val p))
==> ensures x86
(\s. bytes_loaded s (word pc) bignum_add_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
C_ARGUMENTS [p;z;m;x;n;y] s /\
bignum_from_memory (x,val m) s = a /\
bignum_from_memory (y,val n) s = b)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
bignum_from_memory (z,val p) s =
(a + b) MOD 2 EXP (64 * val p) /\
2 EXP (64 * val p) * val(C_RETURN s) +
bignum_from_memory (z,val p) s =
lowdigits a (val p) + lowdigits b (val p))
(MAYCHANGE [RIP; RSP; RAX; RDI; RDX; R8; R10] ,,
MAYCHANGE SOME_FLAGS ,,
MAYCHANGE [memory :> bignum(z,val p)])`,
X86_ADD_RETURN_NOSTACK_TAC BIGNUM_ADD_EXEC BIGNUM_ADD_CORRECT);;
let windows_bignum_add_mc = define_from_elf
"windows_bignum_add_mc" "x86/generic/bignum_add.obj";;
let WINDOWS_BIGNUM_ADD_CORRECT = prove
(`!p z m x a n y b pc.
nonoverlapping (word pc,0xd3) (z,8 * val p) /\
(x = z \/ nonoverlapping(x,8 * val m) (z,8 * val p)) /\
(y = z \/ nonoverlapping(y,8 * val n) (z,8 * val p))
==> ensures x86
(\s. bytes_loaded s (word pc) windows_bignum_add_mc /\
read RIP s = word(pc + 0x18) /\
C_ARGUMENTS [p;z;m;x;n;y] s /\
bignum_from_memory (x,val m) s = a /\
bignum_from_memory (y,val n) s = b)
(\s. (read RIP s = word(pc + 0x74) \/
read RIP s = word(pc + 0xb8) \/
read RIP s = word(pc + 0xd0)) /\
bignum_from_memory (z,val p) s =
(a + b) MOD 2 EXP (64 * val p) /\
2 EXP (64 * val p) * val(C_RETURN s) +
bignum_from_memory (z,val p) s =
lowdigits a (val p) + lowdigits b (val p))
(MAYCHANGE [RIP; RAX; RDI; RDX; R8; R10] ,,
MAYCHANGE SOME_FLAGS ,,
MAYCHANGE [memory :> bignum(z,val p)])`,
tac (X86_MK_EXEC_RULE windows_bignum_add_mc)
`\s. (read RIP s = word(pc + 0x74) \/
read RIP s = word(pc + 0xb8) \/
read RIP s = word(pc + 0xd0)) /\
2 EXP (64 * p) * val(read RAX s) +
bignum_from_memory (z,p) s = lowdigits a p + lowdigits b p`
(curry mk_comb `(+) (pc:num)` o mk_small_numeral o
(fun n -> if n < 0x5c then n + 24
else if n < 0x9e then n + 26
else n + 28)));;
let WINDOWS_BIGNUM_ADD_SUBROUTINE_CORRECT = prove
(`!p z m x a n y b pc stackpointer returnaddress.
ALL (nonoverlapping (word_sub stackpointer (word 16),16))
[(word pc,0xd3); (x,8 * val m); (y,8 * val n)] /\
ALL (nonoverlapping (z,8 * val p))
[(word pc,0xd3); (word_sub stackpointer (word 16),24)] /\
(x = z \/ nonoverlapping(x,8 * val m) (z,8 * val p)) /\
(y = z \/ nonoverlapping(y,8 * val n) (z,8 * val p))
==> ensures x86
(\s. bytes_loaded s (word pc) windows_bignum_add_mc /\
read RIP s = word pc /\
read RSP s = stackpointer /\
read (memory :> bytes64 stackpointer) s = returnaddress /\
WINDOWS_C_ARGUMENTS [p;z;m;x;n;y] s /\
bignum_from_memory (x,val m) s = a /\
bignum_from_memory (y,val n) s = b)
(\s. read RIP s = returnaddress /\
read RSP s = word_add stackpointer (word 8) /\
bignum_from_memory (z,val p) s =
(a + b) MOD 2 EXP (64 * val p) /\
2 EXP (64 * val p) * val(WINDOWS_C_RETURN s) +
bignum_from_memory (z,val p) s =
lowdigits a (val p) + lowdigits b (val p))
(MAYCHANGE [RIP; RSP; R9; RCX; RAX; RDX; R8; R10] ,,
MAYCHANGE SOME_FLAGS ,,
MAYCHANGE [memory :> bignum(z,val p);
memory :> bytes(word_sub stackpointer (word 16),16)])`,
REWRITE_TAC[WINDOWS_ABI_STACK_THM] THEN
GEN_X86_ADD_RETURN_STACK_TAC (X86_MK_EXEC_RULE windows_bignum_add_mc)
WINDOWS_BIGNUM_ADD_CORRECT
`[RDI; RSI]` 16 (8,3));;
|
a937dbbae282a9f4f3766c5d7f434ee4adc5900c71b10234aff14c4540bd2caf | mbj/stratosphere | ServerSideEncryptionConfigurationProperty.hs | module Stratosphere.Wisdom.KnowledgeBase.ServerSideEncryptionConfigurationProperty (
ServerSideEncryptionConfigurationProperty(..),
mkServerSideEncryptionConfigurationProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data ServerSideEncryptionConfigurationProperty
= ServerSideEncryptionConfigurationProperty {kmsKeyId :: (Prelude.Maybe (Value Prelude.Text))}
mkServerSideEncryptionConfigurationProperty ::
ServerSideEncryptionConfigurationProperty
mkServerSideEncryptionConfigurationProperty
= ServerSideEncryptionConfigurationProperty
{kmsKeyId = Prelude.Nothing}
instance ToResourceProperties ServerSideEncryptionConfigurationProperty where
toResourceProperties ServerSideEncryptionConfigurationProperty {..}
= ResourceProperties
{awsType = "AWS::Wisdom::KnowledgeBase.ServerSideEncryptionConfiguration",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes [(JSON..=) "KmsKeyId" Prelude.<$> kmsKeyId])}
instance JSON.ToJSON ServerSideEncryptionConfigurationProperty where
toJSON ServerSideEncryptionConfigurationProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes [(JSON..=) "KmsKeyId" Prelude.<$> kmsKeyId]))
instance Property "KmsKeyId" ServerSideEncryptionConfigurationProperty where
type PropertyType "KmsKeyId" ServerSideEncryptionConfigurationProperty = Value Prelude.Text
set newValue ServerSideEncryptionConfigurationProperty {}
= ServerSideEncryptionConfigurationProperty
{kmsKeyId = Prelude.pure newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/wisdom/gen/Stratosphere/Wisdom/KnowledgeBase/ServerSideEncryptionConfigurationProperty.hs | haskell | module Stratosphere.Wisdom.KnowledgeBase.ServerSideEncryptionConfigurationProperty (
ServerSideEncryptionConfigurationProperty(..),
mkServerSideEncryptionConfigurationProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data ServerSideEncryptionConfigurationProperty
= ServerSideEncryptionConfigurationProperty {kmsKeyId :: (Prelude.Maybe (Value Prelude.Text))}
mkServerSideEncryptionConfigurationProperty ::
ServerSideEncryptionConfigurationProperty
mkServerSideEncryptionConfigurationProperty
= ServerSideEncryptionConfigurationProperty
{kmsKeyId = Prelude.Nothing}
instance ToResourceProperties ServerSideEncryptionConfigurationProperty where
toResourceProperties ServerSideEncryptionConfigurationProperty {..}
= ResourceProperties
{awsType = "AWS::Wisdom::KnowledgeBase.ServerSideEncryptionConfiguration",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes [(JSON..=) "KmsKeyId" Prelude.<$> kmsKeyId])}
instance JSON.ToJSON ServerSideEncryptionConfigurationProperty where
toJSON ServerSideEncryptionConfigurationProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes [(JSON..=) "KmsKeyId" Prelude.<$> kmsKeyId]))
instance Property "KmsKeyId" ServerSideEncryptionConfigurationProperty where
type PropertyType "KmsKeyId" ServerSideEncryptionConfigurationProperty = Value Prelude.Text
set newValue ServerSideEncryptionConfigurationProperty {}
= ServerSideEncryptionConfigurationProperty
{kmsKeyId = Prelude.pure newValue, ..} | |
49df157447a9fcfa406e78c048904d044d9f1bb96858add568a1dd516deb5018 | OCamlPro/numcaml | floats.ml | open Tests
open Numcaml
let test_add () =
let x = $(1.4 + 2) in
let y = $(3.4) in
"values match" @? (x=y)
let test_mul () =
let x = $(1.3+2*3.1) in
let y = Math.Float (1.3 +. 2. *. 3.1) in
"value match" @? (x=y)
let suite = [
"float_add" >:: test_add;
"float_mul" >:: test_mul;
]
| null | https://raw.githubusercontent.com/OCamlPro/numcaml/5c12b3aa62b09670ba7712006b5aa0254b8bdea3/tests/floats.ml | ocaml | open Tests
open Numcaml
let test_add () =
let x = $(1.4 + 2) in
let y = $(3.4) in
"values match" @? (x=y)
let test_mul () =
let x = $(1.3+2*3.1) in
let y = Math.Float (1.3 +. 2. *. 3.1) in
"value match" @? (x=y)
let suite = [
"float_add" >:: test_add;
"float_mul" >:: test_mul;
]
| |
55dec322a461d07d9e39c6952a58e460994ad7bd5c238f48848ff7cd8f782c6d | ericclack/racket-examples | stars2.rkt | #lang racket
Version 2 , in 3D
(require 2htdp/universe 2htdp/image)
(require "util.rkt")
;; Screen size
(define WIDTH 600)
(define HEIGHT 600)
;; - to + of this value for new stars
(define MAX-STAR-XY 25000)
(define MAX-STARS 100)
(define TICK-RATE 1/25)
(define ACCEL 1)
(define START-Z 100)
;; -----------------------------------------------------------
(struct starfield (stars) #:transparent)
(struct astar (x y z) #:transparent)
(define (start-space)
(big-bang (starfield (times-repeat MAX-STARS (new-star)))
(on-tick fly TICK-RATE)
(to-draw render-space)
(stop-when end-flight)))
(define (screen-x s) (+ (/ (astar-x s) (astar-z s)) (/ WIDTH 2)))
(define (screen-y s) (+ (/ (astar-y s) (astar-z s)) (/ HEIGHT 2)))
(define (random-star-xy) (- (random MAX-STAR-XY) (/ MAX-STAR-XY 2)))
(define (new-star)
(astar (random-star-xy)
(random-star-xy)
(+ (random START-Z) 10)))
(define (move-star s)
(astar (astar-x s) (astar-y s) (- (astar-z s) ACCEL)))
(define (stars-in-view stars)
(define (replace-star s)
(if (star-out-of-view? s) (new-star) s))
(map replace-star stars))
(define (star-out-of-view? s)
(<= (astar-z s) 1))
(define (fly w)
(starfield (map move-star (stars-in-view (starfield-stars w)))))
;; -----------------------------------------------------------
(define (render-space w)
(stars+scene (starfield-stars w) (empty-scene WIDTH HEIGHT "black")))
(define (stars+scene stars scene)
(foldl (λ (s scene)
(place-image (circle (star-size s) "solid" (star-colour s))
(screen-x s)
(screen-y s)
scene))
scene stars))
(define (star-size s)
(define z (astar-z s))
(cond [(> z 75) 1]
[else (+ 1 (/ (- 75 z) 20)) ]))
(define (star-colour s)
(define z (astar-z s))
(cond [(> z 90) (color 255 255 255 20)]
[else (color 255 255 255 (+ 20 (* 2 (- 90 z))))]))
(define (end-flight w) #f)
;;(start-space) | null | https://raw.githubusercontent.com/ericclack/racket-examples/ee858daac3577ead0c8463b9701a8653220039de/stars2.rkt | racket | Screen size
- to + of this value for new stars
-----------------------------------------------------------
-----------------------------------------------------------
(start-space) | #lang racket
Version 2 , in 3D
(require 2htdp/universe 2htdp/image)
(require "util.rkt")
(define WIDTH 600)
(define HEIGHT 600)
(define MAX-STAR-XY 25000)
(define MAX-STARS 100)
(define TICK-RATE 1/25)
(define ACCEL 1)
(define START-Z 100)
(struct starfield (stars) #:transparent)
(struct astar (x y z) #:transparent)
(define (start-space)
(big-bang (starfield (times-repeat MAX-STARS (new-star)))
(on-tick fly TICK-RATE)
(to-draw render-space)
(stop-when end-flight)))
(define (screen-x s) (+ (/ (astar-x s) (astar-z s)) (/ WIDTH 2)))
(define (screen-y s) (+ (/ (astar-y s) (astar-z s)) (/ HEIGHT 2)))
(define (random-star-xy) (- (random MAX-STAR-XY) (/ MAX-STAR-XY 2)))
(define (new-star)
(astar (random-star-xy)
(random-star-xy)
(+ (random START-Z) 10)))
(define (move-star s)
(astar (astar-x s) (astar-y s) (- (astar-z s) ACCEL)))
(define (stars-in-view stars)
(define (replace-star s)
(if (star-out-of-view? s) (new-star) s))
(map replace-star stars))
(define (star-out-of-view? s)
(<= (astar-z s) 1))
(define (fly w)
(starfield (map move-star (stars-in-view (starfield-stars w)))))
(define (render-space w)
(stars+scene (starfield-stars w) (empty-scene WIDTH HEIGHT "black")))
(define (stars+scene stars scene)
(foldl (λ (s scene)
(place-image (circle (star-size s) "solid" (star-colour s))
(screen-x s)
(screen-y s)
scene))
scene stars))
(define (star-size s)
(define z (astar-z s))
(cond [(> z 75) 1]
[else (+ 1 (/ (- 75 z) 20)) ]))
(define (star-colour s)
(define z (astar-z s))
(cond [(> z 90) (color 255 255 255 20)]
[else (color 255 255 255 (+ 20 (* 2 (- 90 z))))]))
(define (end-flight w) #f)
|
af2901d274bf49b6044ef301f2db477541b513e25285afc304760a05b90c17ff | billstclair/trubanc-lisp | tests.lisp | ; -*- mode: lisp -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Test code for Trubanc client and server
;;;
(in-package :trubanc-test)
(defvar *test-pathname*
(or *load-pathname* "~/loom/web/trubanc/lisp/src/tests.lisp"))
(defparameter *www-dir*
(directory-namestring (merge-pathnames "../www/" *test-pathname*)))
(defun make-test-state (db-dir &rest rest &key dont-erase passphrase port network-p)
(declare (ignore dont-erase passphrase port network-p))
(apply #'make-instance 'test-state
:db-dir db-dir
rest))
(defclass test-state ()
((db-dir :accessor db-dir
:initarg :db-dir)
(port :accessor port
:initarg :port
:initform 8081)
(passphrase :accessor passphrase
:initarg :passphrase
:initform "passphrase")
(server :accessor server
:initform nil)
(client :accessor client
:initform nil)))
(defmethod initialize-instance :after ((ts test-state) &key
dont-erase
(network-p nil))
(let* ((db-dir (ensure-directory-pathname (db-dir ts)))
(port (port ts))
(passphrase (passphrase ts))
(server-dir (merge-pathnames "serverdb" db-dir))
(client-dir (merge-pathnames "clientdb" db-dir)))
(when network-p
(stop-web-server port))
(unless dont-erase
(ignore-errors (recursive-delete-directory server-dir))
(ignore-errors (recursive-delete-directory client-dir)))
(setf (server ts) (make-server
server-dir passphrase
:bankname "Test Bank"
:bankurl (format nil ":~d/" port)
:privkey-size 512)
(client ts) (make-client client-dir
:test-server (unless network-p (server ts))))
(when network-p
(start-test-web-server ts))))
(defmethod start-test-web-server ((ts test-state))
(trubanc-web-server (server ts) :www-dir *www-dir* :port (port ts)))
(defmethod stop-test-web-server ((ts test-state))
(stop-web-server (port ts)))
(defmethod getinbox ((ts test-state) &optional includeraw)
(getinbox (client ts) includeraw))
(defmethod getoutbox ((ts test-state) &optional includeraw)
(getoutbox (client ts) includeraw))
(defmethod getbalance ((ts test-state) &optional acct assetid includeraw)
(getbalance (client ts) acct assetid includeraw))
(defmethod getfraction ((ts test-state) &optional assetid includeraw)
(getfraction (client ts) assetid includeraw))
(defmethod getstoragefee ((ts test-state) &optional assetid)
(getstoragefee (client ts) assetid))
(defmethod id ((ts test-state))
(id (client ts)))
(defmethod bankid ((ts test-state))
(bankid (server ts)))
(defmethod getassets ((ts test-state))
(getassets (client ts)))
(defmethod tokenid ((ts test-state))
(tokenid (client ts)))
(defmethod login-bank ((ts test-state))
(let* ((server (server ts))
(client (client ts))
(bankid (bankid server))
(passphrase (passphrase ts)))
(handler-case (login client passphrase)
(error ()
(let ((privkey (decode-rsa-private-key
(encode-rsa-private-key (privkey server)))))
(newuser client
:passphrase passphrase
:privkey privkey))))
(handler-case (setbank client bankid)
(error ()
(addbank client (bankurl server))
(let ((balance (getbalance client))
(tokenid (tokenid server)))
(loop
for (acct . bals) in balance
do
(unless (equal acct $MAIN)
(error "Found non-main acct: ~s" acct))
(dolist (bal bals)
(let ((assetid (balance-assetid bal))
(assetname (balance-assetname bal))
(amount (balance-amount bal))
(formatted-amount (balance-formatted-amount bal)))
(assert (equal tokenid assetid))
(assert (equal assetname "Test Bank Usage Tokens"))
(assert (equal amount "-1"))
(assert (equal formatted-amount "-0"))))))))
(id client)))
(defmethod login-user ((ts test-state) passphrase &optional (name passphrase))
(let ((client (client ts))
(server (server ts)))
(handler-case (login client passphrase)
(error ()
(newuser client :passphrase passphrase :privkey 512)))
(handler-case (setbank client (bankid server))
(error ()
(handler-case (addbank client (bankurl server) name)
(error ()
(let ((id (id client)))
(login-bank ts)
(spend client id (tokenid server) "200" nil "Welcome to my bank")
(login client passphrase)
(addbank client (bankurl server) name))))))
(id client)))
(defmethod accept-inbox ((ts test-state) &optional (accept-p t))
(loop with client = (client ts)
for inbox = (getinbox client)
for directions = nil
while inbox
do
(dolist (item inbox)
(push (make-process-inbox
:time (inbox-time item)
:request (if accept-p $SPENDACCEPT $SPENDREJECT)
:note (format nil "~a ~a"
(if accept-p "Accepting" "Rejecting")
(or (inbox-msgtime item) (inbox-time item))))
directions))
(processinbox client directions)))
(defmethod cancel-outbox ((ts test-state))
(accept-inbox ts)
(let* ((client (client ts))
(outbox (getoutbox client)))
(dolist (item outbox)
(when (equal (outbox-request item) $SPEND)
(let ((time (outbox-time item)))
(spendreject client time)
(accept-inbox ts)
(return time))))))
(defmethod getbal ((ts test-state) asset &optional (acct $MAIN))
(let* ((client (client ts))
(bal (getbalance client acct asset)))
(and bal (balance-amount bal))))
(defmethod give-tokens ((ts test-state) user amount)
(let* ((client (client ts))
(id (login-user ts user))
(fee-asset (fee-assetid (getfees client))))
(login-bank ts)
(spend client id fee-asset amount)
(login-user ts user)
(accept-inbox ts)))
(defun set-standard-fees (ts)
(let ((client (client ts)))
(login-bank ts)
(setfees client)
(let ((permissions (get-permissions client nil t)))
(dolist (permission permissions)
(deny client
(permission-toid permission)
(permission-permission permission))))))
(defmethod tokens-test ((ts test-state))
(set-standard-fees ts)
(let* ((john (prog1 (login-user ts "john") (accept-inbox ts)))
(bill (login-user ts "bill"))
(client (client ts))
(fee (getfees client))
(fee-asset (fee-assetid fee))
(fee-amount (fee-amount fee))
bill-tokens)
;; Make sure bill has enough tokens
(give-tokens ts "bill" "14")
Spend 10 tokens from bill to . accepts .
(setq bill-tokens (getbal ts fee-asset))
(spend client john fee-asset "10" nil (strcat john bill))
(assert (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens 10 fee-amount)))
nil
"Balance mismatch after spend")
(login-user ts "john")
(accept-inbox ts)
(login-user ts "bill")
(accept-inbox ts)
(assert (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens 10)))
nil
"Balance mismatch after accept")
Spend 10 tokens from bill to . rejects
(setq bill-tokens (getbal ts fee-asset))
(spend client john fee-asset "10" nil (strcat john bill))
(assert (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens 10 fee-amount)))
nil
"Balance mismatch after spend")
(login-user ts "john")
(accept-inbox ts nil)
(login-user ts "bill")
(accept-inbox ts)
(assert (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens 2)))
nil
"Balance mismatch after accept")
Spend 10 tokens from bill to . cancels
(setq bill-tokens (getbal ts fee-asset))
(spend client john fee-asset "10" nil (strcat john bill))
(assert (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens 10 fee-amount)))
nil
"Balance mismatch after spend")
(cancel-outbox ts)
(assert (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens 2)))
nil
"Balance mismatch after cancel")))
(defmethod bill-goldgrams-assetid ((ts test-state) &optional (percent nil))
(set-standard-fees ts)
(login-user ts "bill")
(accept-inbox ts)
(let* ((client (client ts))
(precision "7")
(scale "3")
(name "Bill GoldGrams")
(assetid (assetid (id client) precision scale name))
(asset (ignore-errors (getasset client assetid))))
(unless (and asset (equal percent (asset-percent asset)))
(addasset client precision scale name percent))
assetid))
(defmethod goldgrams-test ((ts test-state))
(set-standard-fees ts)
(let* ((john (prog1 (login-user ts "john") (accept-inbox ts)))
(bill (login-user ts "bill"))
(client (client ts))
(fee (getfees client))
(fee-asset (fee-assetid fee))
(fee-amount (fee-amount fee))
(assetid (bill-goldgrams-assetid ts))
(scale (asset-scale (getasset client assetid)))
(formatted-amount "100")
(amount (bcmul formatted-amount (bcpow 10 scale)))
bill-tokens
bill-grams)
;; Make sure bill has enough tokens
(give-tokens ts "bill" "4")
Spend 10 goldgrams from bill to . accepts .
(setq bill-tokens (getbal ts fee-asset)
bill-grams (getbal ts assetid))
(spend client john assetid formatted-amount nil (strcat john bill))
(assert (and (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens fee-amount)))
(eql 0 (bccomp (getbal ts assetid)
(bcsub bill-grams amount))))
nil
"Balance mismatch after spend")
(login-user ts "john")
(accept-inbox ts)
(login-user ts "bill")
(accept-inbox ts)
(assert (and (eql 0 (bccomp (getbal ts fee-asset) bill-tokens))
(eql 0 (bccomp (getbal ts assetid)
(bcsub bill-grams amount))))
nil
"Balance mismatch after accept")
Spend 10 goldgrams from bill to . rejects
(setq bill-tokens (getbal ts fee-asset)
bill-grams (getbal ts assetid))
(spend client john assetid formatted-amount nil (strcat john bill))
(assert (and (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens fee-amount)))
(eql 0 (bccomp (getbal ts assetid)
(bcsub bill-grams amount))))
nil
"Balance mismatch after spend")
(login-user ts "john")
(accept-inbox ts nil)
(login-user ts "bill")
(accept-inbox ts)
(assert (and (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens 2)))
(eql 0 (wbp (scale)
(bccomp (getbal ts assetid) bill-grams))))
nil
"Balance mismatch after reject")
Spend 10 goldgrams from bill to . cancels .
(setq bill-tokens (getbal ts fee-asset)
bill-grams (getbal ts assetid))
(spend client john assetid formatted-amount nil (strcat john bill))
(assert (and (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens fee-amount)))
(eql 0 (bccomp (getbal ts assetid)
(bcsub bill-grams amount))))
nil
"Balance mismatch after spend")
(cancel-outbox ts)
(accept-inbox ts)
(assert (and (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens 2)))
(eql 0 (bccomp (getbal ts assetid) bill-grams)))
nil
"Balance mismatch after reject")
))
(defmethod storage-test ((ts test-state))
(set-standard-fees ts)
(let* ((john (prog1 (login-user ts "john") (accept-inbox ts)))
(client (client ts))
(percent "1.0")
(assetid (bill-goldgrams-assetid ts percent))
(bill (id client))
(scale (asset-scale (getasset client assetid)))
(formatted-amount "100")
(amount (bcmul formatted-amount (bcpow 10 scale))))
(declare (ignore amount))
;; Make sure bill has enough tokens
(give-tokens ts "bill" "4")
Spend to . He accepts .
(spend client john assetid (bcadd formatted-amount 1))
(login-user ts "john")
(sleep 1)
(accept-inbox ts)
(login-user ts "bill")
(accept-inbox ts)
Spend to . He rejects
(spend client john assetid formatted-amount)
(login-user ts "john")
(sleep 1)
(accept-inbox ts nil)
(login-user ts "bill")
(accept-inbox ts)
Spend to . Cancel the spend .
(spend client john assetid formatted-amount)
(cancel-outbox ts)
(accept-inbox ts)
Make sure has enough tokens
(give-tokens ts "john" "4")
Spend from . Cancel the spend .
(spend client bill assetid formatted-amount)
(sleep 1)
(cancel-outbox ts)
(accept-inbox ts)
Spend from . rejects .
(spend client bill assetid formatted-amount)
(login-user ts "bill")
(accept-inbox ts nil)
(sleep 1)
(login-user ts "john")
(accept-inbox ts)
Spend from . accepts
(spend client bill assetid formatted-amount)
(login-user ts "bill")
(accept-inbox ts)
(login-user ts "john")
(accept-inbox ts)
(let ((bill-bal (progn (login-user ts "bill")
(getbalance client $MAIN assetid)))
(bill-fee (getstoragefee client assetid))
(john-bal (progn (login-user ts "john")
(getbalance client $MAIN assetid)))
(john-frac (getfraction client assetid)))
(values bill-bal bill-fee john-bal john-frac))))
(defmethod transfer-test ((ts test-state))
(set-standard-fees ts)
(give-tokens ts "bill" "3")
(let* ((bill (login-user ts "bill"))
(client (client ts))
(fee (getfees client))
(tokenid (fee-assetid fee))
(assetid (bill-goldgrams-assetid ts))
(tokenbal (getbal ts tokenid))
(balance (getbalance ts t))
(acct (loop for i from 0
for acct = (format nil "a~d" i)
do
(unless (assoc acct balance :test #'equal)
(return acct)))))
(spend client bill tokenid "1" (list nil acct))
(spend client bill assetid "1" (list nil acct))
(let* ((newbal (getbal ts tokenid))
(diff (bcsub tokenbal (getbal ts tokenid)))
1 spent , 2 new file fees
(unless (bc= diff sb)
(error "Diff sb: ~a, was: ~a, tokenbal: ~a, newbal: ~a"
sb diff tokenbal newbal)))
acct))
(defmethod fee-test ((ts test-state))
(set-standard-fees ts)
(let* ((john (prog1 (login-user ts "john") (accept-inbox ts)))
(bill (prog1 (login-user ts "bill") (accept-inbox ts)))
(client (client ts))
(tokenid (fee-assetid (getfees client)))
(fees (list (make-fee :type $TRANFEE :assetid tokenid :amount 1)
(make-fee :type $REGFEE :assetid tokenid :amount 10)))
(goldgrams (bill-goldgrams-assetid ts)))
(login-bank ts)
(apply #'setfees client
`(,@fees
,(make-fee :type $SPEND :assetid tokenid :amount 2)
,(make-fee :type $TRANSFER :assetid tokenid :amount 3)))
(give-tokens ts "bill" (+ 10 1 2 10 3))
(let ((bank-tokens (progn (login-bank ts)
(reinit-balances client)
(balance-amount (getbalance ts $MAIN tokenid))))
(tokens (progn (login-user ts "bill")
(balance-amount (getbalance ts $MAIN tokenid))))
(backup-p (getbalance ts "backup" tokenid)))
(spend client john tokenid "10")
(let ((sb (bcsub tokens 10 1 2))
(was (balance-amount (getbalance ts $MAIN tokenid)))
(bank-sb (bcadd bank-tokens 2))
(bank-was (progn
(login-bank ts)
(storagefees client)
(accept-inbox ts)
(prog1 (balance-amount (getbalance ts $MAIN tokenid))
(login-user ts "bill")))))
(unless (bc= sb was)
(error "Outspend w/token fee mismatch. Old: ~s, SB: ~s, Was: ~s"
tokens sb was))
(setf tokens was)
(unless (bc= bank-sb bank-was)
(error "Outspend w/token fee bank mismatch. Old: ~s, SB: ~s, Was: ~s"
bank-tokens bank-sb bank-was))
(setf bank-tokens bank-was))
(spend client bill tokenid "10" `(,$MAIN "backup"))
(let ((sb (bcsub tokens 10 3 (if backup-p 0 1)))
(was (balance-amount (getbalance ts $MAIN tokenid))))
(unless (bc= sb was)
(error "Transfer w/token fee mismatch. Old: ~s SB: ~s, Was: ~s"
tokens sb was))))
;; Test with goldgrams as a fee
(login-bank ts)
(apply #'setfees client
`(,@fees
,(make-fee :type $SPEND :assetid goldgrams
:formatted-amount "0.001")
,(make-fee :type $TRANSFER :assetid goldgrams
:formatted-amount "0.002")))
(login-user ts "bill")
(let ((gg (balance-formatted-amount (getbalance client $MAIN goldgrams))))
(spend client john goldgrams "1.1")
(let ((sb (wbp (7) (bcsub gg "1.1")))
(was (balance-formatted-amount (getbalance client $MAIN goldgrams))))
(unless (bc= sb was)
(error "Spend goldgrams issuer mismatch. Old: ~s, sb: ~s, was: ~s"
gg sb was))))
(login-user ts "john")
(accept-inbox ts)
(let ((bankgg (progn
(login-bank ts)
(storagefees client)
(accept-inbox ts)
(let ((bal (getbalance client $MAIN goldgrams)))
(if bal
(balance-formatted-amount bal)
"0"))))
(gg (progn
(login-user ts "john")
(balance-formatted-amount
(getbalance client $MAIN goldgrams)))))
(spend client john goldgrams "1" `(,$MAIN "backup"))
(let ((banksb (wbp (7) (bcadd bankgg ".002")))
(bankwas (progn
(login-bank ts)
(storagefees client)
(accept-inbox ts)
(balance-formatted-amount
(getbalance client $MAIN goldgrams))))
(sb (wbp (7) (bcsub gg "1" "0.002")))
(was (progn
(login-user ts "john")
(balance-formatted-amount
(getbalance client $MAIN goldgrams)))))
(unless (bc= banksb bankwas)
(error "Spend goldgrams transfer bank mismatch. Old:~s, sb: ~s, was: ~s"
bankgg banksb bankwas))
(setf bankgg bankwas)
(unless (bc= sb was)
(error "Spend goldgrams transfer mismatch. Old: ~s, sb: ~s, was: ~s"
gg sb was)))
(setf gg (balance-formatted-amount
(getbalance client "backup" goldgrams)))
(spend client bill goldgrams "0.5" "backup")
(let ((banksb (wbp (7) (bcadd bankgg ".001")))
(bankwas (progn
(login-bank ts)
(storagefees client)
(accept-inbox ts)
(balance-formatted-amount
(getbalance client $MAIN goldgrams))))
(sb (wbp (7) (bcsub gg "0.5" "0.001")))
(was (progn
(login-user ts "john")
(balance-formatted-amount
(getbalance client "backup" goldgrams)))))
(unless (bc= banksb bankwas)
(error "Spend goldgrams bank mismatch. Old:~s, sb: ~s, was: ~s"
bankgg banksb bankwas))
(setf bankgg bankwas)
(unless (bc= sb was)
(error "Spend goldgrams mismatch. Old: ~s, sb: ~s, was: ~s"
gg sb was))
(setf gg was)))
;; Test with goldgrams as a fee with storage fees
(bill-goldgrams-assetid ts "1")
(give-tokens ts john "12")
(login-user ts "john")
(spend client john goldgrams "0.2" `("backup" ,$MAIN))
(sleep 0.5)
(spend client bill goldgrams "0.1")
(sleep 0.5)
(spend client bill tokenid "10")
(login-bank ts)
(storagefees client)
(accept-inbox ts)
(values
(getbalance ts t)
(progn (login-user ts "john")
(getbalance ts t)))
))
(defun permissions-test (ts)
(set-standard-fees ts)
(let ((client (client ts))
(bankid (bankid ts))
(tokenid (tokenid ts))
(bill (prog1 (login-user ts "bill") (accept-inbox ts)))
(john (prog1 (login-user ts "john") (accept-inbox ts)))
(mike (prog1 (login-user ts "mike") (accept-inbox ts)))
(goldgrams (bill-goldgrams-assetid ts)))
(login-bank ts)
;; Test $MINT-TOKENS permission
(assert (nth-value 1 (ignore-errors (grant client bill $MINT-TOKENS t))))
(grant client bankid $MINT-TOKENS t)
(grant client bill $MINT-TOKENS t)
(give-tokens ts "bill" 12)
(multiple-value-bind (permissions grant-p)
(get-permissions client $MINT-TOKENS t)
(assert grant-p)
(assert (eql (length permissions) 1))
(let ((perm (car permissions)))
(assert (and (equal (permission-id perm) bankid)
(equal (permission-toid perm) bill)
(equal (permission-permission perm) $MINT-TOKENS)
(permission-grant-p perm)))))
(spend client $COUPON tokenid 10)
(cancel-outbox ts)
(give-tokens ts "john" 12)
(assert (null (get-permissions client $MINT-TOKENS t)))
(assert (nth-value 1 (ignore-errors (spend client $COUPON tokenid 10))))
;; Test multiple grants
(login-bank ts)
(grant client mike $MINT-TOKENS t)
(login-user ts "mike")
(grant client john $MINT-TOKENS)
(login-user ts "bill")
(grant client john $MINT-TOKENS t)
(login-user ts "john")
(multiple-value-bind (permissions grant-p)
(get-permissions client $MINT-TOKENS t)
(assert (and (find bill permissions :test #'equal :key #'permission-id)
(find mike permissions :test #'equal :key #'permission-id)
grant-p)))
(login-bank ts)
(deny client bill $MINT-TOKENS)
(login-user ts "john")
(multiple-value-bind (permissions grant-p)
(get-permissions client $MINT-TOKENS t)
(assert (and (eql 1 (length permissions))
(find mike permissions :test #'equal :key #'permission-id)
(not grant-p))))
(login-bank ts)
(deny client mike $MINT-TOKENS)
(login-user ts "john")
(multiple-value-bind (permissions grant-p)
(get-permissions client $MINT-TOKENS t)
(assert (and (null permissions) (null grant-p))))
;; Test circular grants
(login-bank ts)
(grant client bill $MINT-TOKENS t)
(login-user ts "bill")
(grant client john $MINT-TOKENS t)
(login-user ts "john")
(grant client bill $MINT-TOKENS t)
(login-bank ts)
(deny client bill $MINT-TOKENS)
(login-user ts "bill")
(assert (not (get-permissions client $MINT-TOKENS t)))
(login-user ts "john")
(assert (not (get-permissions client $MINT-TOKENS t)))
;; Test MINT-COUPON permission
(login-user ts "bill")
(assert (nth-value 1 (ignore-errors (spend client $COUPON tokenid 10))))
(spend client $COUPON goldgrams 1)
(cancel-outbox ts)
(login-bank ts)
(grant client bankid $MINT-COUPONS t)
(login-user ts "bill")
(assert (nth-value 1 (ignore-errors (spend client $COUPON tokenid 10))))
(assert (nth-value 1 (ignore-errors (spend client $COUPON goldgrams 1))))
(login-bank ts)
(grant client bill $MINT-COUPONS t)
(login-user ts "bill")
(assert (nth-value 1 (ignore-errors (spend client $COUPON tokenid 10))))
(let* ((pubkey (rsa-generate-key 512))
(id (pubkey-id (encode-rsa-public-key pubkey))))
(rsa-free pubkey)
(assert (nth-value 1 (ignore-errors (spend client id tokenid 10)))))
(spend client $COUPON goldgrams 1)
(cancel-outbox ts)
;; Test ADD-ASSET permission
;; Already made bill goldgrams asset with no permission in place
(login-bank ts)
(grant client bankid $ADD-ASSET t)
(login-user ts "bill")
(assert (nth-value 1 (ignore-errors
(addasset client 7 3 "Bill Silver Grams"))))
(login-bank ts)
(grant client bill $ADD-ASSET)
(addasset client 7 3 "Bill Silver Grams")
nil))
(defun run-all-tests (ts-or-dir &rest rest &key dont-erase passphrase port network-p)
(declare (ignore dont-erase passphrase port network-p))
(let ((ts ts-or-dir))
(unless (typep ts 'test-state)
(setf ts (apply #'make-test-state ts-or-dir rest)))
(format t "tokens...") (finish-output)
(tokens-test ts)
(format t " goldgrams...") (finish-output)
(goldgrams-test ts)
(format t " storage...") (finish-output)
(storage-test ts)
(format t " transfer...") (finish-output)
(transfer-test ts)
(format t " fees...") (finish-output)
(fee-test ts)
(format t " permissions...")
(permissions-test ts)
ts))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Copyright 2009 - 2010 Bill St. Clair
;;;
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.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
| null | https://raw.githubusercontent.com/billstclair/trubanc-lisp/5436d2eca5b1ed10bc47eec7080f6cb90f98ca65/src/tests.lisp | lisp | -*- mode: lisp -*-
Make sure bill has enough tokens
Make sure bill has enough tokens
Make sure bill has enough tokens
Test with goldgrams as a fee
Test with goldgrams as a fee with storage fees
Test $MINT-TOKENS permission
Test multiple grants
Test circular grants
Test MINT-COUPON permission
Test ADD-ASSET permission
Already made bill goldgrams asset with no permission in place
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.
|
Test code for Trubanc client and server
(in-package :trubanc-test)
(defvar *test-pathname*
(or *load-pathname* "~/loom/web/trubanc/lisp/src/tests.lisp"))
(defparameter *www-dir*
(directory-namestring (merge-pathnames "../www/" *test-pathname*)))
(defun make-test-state (db-dir &rest rest &key dont-erase passphrase port network-p)
(declare (ignore dont-erase passphrase port network-p))
(apply #'make-instance 'test-state
:db-dir db-dir
rest))
(defclass test-state ()
((db-dir :accessor db-dir
:initarg :db-dir)
(port :accessor port
:initarg :port
:initform 8081)
(passphrase :accessor passphrase
:initarg :passphrase
:initform "passphrase")
(server :accessor server
:initform nil)
(client :accessor client
:initform nil)))
(defmethod initialize-instance :after ((ts test-state) &key
dont-erase
(network-p nil))
(let* ((db-dir (ensure-directory-pathname (db-dir ts)))
(port (port ts))
(passphrase (passphrase ts))
(server-dir (merge-pathnames "serverdb" db-dir))
(client-dir (merge-pathnames "clientdb" db-dir)))
(when network-p
(stop-web-server port))
(unless dont-erase
(ignore-errors (recursive-delete-directory server-dir))
(ignore-errors (recursive-delete-directory client-dir)))
(setf (server ts) (make-server
server-dir passphrase
:bankname "Test Bank"
:bankurl (format nil ":~d/" port)
:privkey-size 512)
(client ts) (make-client client-dir
:test-server (unless network-p (server ts))))
(when network-p
(start-test-web-server ts))))
(defmethod start-test-web-server ((ts test-state))
(trubanc-web-server (server ts) :www-dir *www-dir* :port (port ts)))
(defmethod stop-test-web-server ((ts test-state))
(stop-web-server (port ts)))
(defmethod getinbox ((ts test-state) &optional includeraw)
(getinbox (client ts) includeraw))
(defmethod getoutbox ((ts test-state) &optional includeraw)
(getoutbox (client ts) includeraw))
(defmethod getbalance ((ts test-state) &optional acct assetid includeraw)
(getbalance (client ts) acct assetid includeraw))
(defmethod getfraction ((ts test-state) &optional assetid includeraw)
(getfraction (client ts) assetid includeraw))
(defmethod getstoragefee ((ts test-state) &optional assetid)
(getstoragefee (client ts) assetid))
(defmethod id ((ts test-state))
(id (client ts)))
(defmethod bankid ((ts test-state))
(bankid (server ts)))
(defmethod getassets ((ts test-state))
(getassets (client ts)))
(defmethod tokenid ((ts test-state))
(tokenid (client ts)))
(defmethod login-bank ((ts test-state))
(let* ((server (server ts))
(client (client ts))
(bankid (bankid server))
(passphrase (passphrase ts)))
(handler-case (login client passphrase)
(error ()
(let ((privkey (decode-rsa-private-key
(encode-rsa-private-key (privkey server)))))
(newuser client
:passphrase passphrase
:privkey privkey))))
(handler-case (setbank client bankid)
(error ()
(addbank client (bankurl server))
(let ((balance (getbalance client))
(tokenid (tokenid server)))
(loop
for (acct . bals) in balance
do
(unless (equal acct $MAIN)
(error "Found non-main acct: ~s" acct))
(dolist (bal bals)
(let ((assetid (balance-assetid bal))
(assetname (balance-assetname bal))
(amount (balance-amount bal))
(formatted-amount (balance-formatted-amount bal)))
(assert (equal tokenid assetid))
(assert (equal assetname "Test Bank Usage Tokens"))
(assert (equal amount "-1"))
(assert (equal formatted-amount "-0"))))))))
(id client)))
(defmethod login-user ((ts test-state) passphrase &optional (name passphrase))
(let ((client (client ts))
(server (server ts)))
(handler-case (login client passphrase)
(error ()
(newuser client :passphrase passphrase :privkey 512)))
(handler-case (setbank client (bankid server))
(error ()
(handler-case (addbank client (bankurl server) name)
(error ()
(let ((id (id client)))
(login-bank ts)
(spend client id (tokenid server) "200" nil "Welcome to my bank")
(login client passphrase)
(addbank client (bankurl server) name))))))
(id client)))
(defmethod accept-inbox ((ts test-state) &optional (accept-p t))
(loop with client = (client ts)
for inbox = (getinbox client)
for directions = nil
while inbox
do
(dolist (item inbox)
(push (make-process-inbox
:time (inbox-time item)
:request (if accept-p $SPENDACCEPT $SPENDREJECT)
:note (format nil "~a ~a"
(if accept-p "Accepting" "Rejecting")
(or (inbox-msgtime item) (inbox-time item))))
directions))
(processinbox client directions)))
(defmethod cancel-outbox ((ts test-state))
(accept-inbox ts)
(let* ((client (client ts))
(outbox (getoutbox client)))
(dolist (item outbox)
(when (equal (outbox-request item) $SPEND)
(let ((time (outbox-time item)))
(spendreject client time)
(accept-inbox ts)
(return time))))))
(defmethod getbal ((ts test-state) asset &optional (acct $MAIN))
(let* ((client (client ts))
(bal (getbalance client acct asset)))
(and bal (balance-amount bal))))
(defmethod give-tokens ((ts test-state) user amount)
(let* ((client (client ts))
(id (login-user ts user))
(fee-asset (fee-assetid (getfees client))))
(login-bank ts)
(spend client id fee-asset amount)
(login-user ts user)
(accept-inbox ts)))
(defun set-standard-fees (ts)
(let ((client (client ts)))
(login-bank ts)
(setfees client)
(let ((permissions (get-permissions client nil t)))
(dolist (permission permissions)
(deny client
(permission-toid permission)
(permission-permission permission))))))
(defmethod tokens-test ((ts test-state))
(set-standard-fees ts)
(let* ((john (prog1 (login-user ts "john") (accept-inbox ts)))
(bill (login-user ts "bill"))
(client (client ts))
(fee (getfees client))
(fee-asset (fee-assetid fee))
(fee-amount (fee-amount fee))
bill-tokens)
(give-tokens ts "bill" "14")
Spend 10 tokens from bill to . accepts .
(setq bill-tokens (getbal ts fee-asset))
(spend client john fee-asset "10" nil (strcat john bill))
(assert (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens 10 fee-amount)))
nil
"Balance mismatch after spend")
(login-user ts "john")
(accept-inbox ts)
(login-user ts "bill")
(accept-inbox ts)
(assert (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens 10)))
nil
"Balance mismatch after accept")
Spend 10 tokens from bill to . rejects
(setq bill-tokens (getbal ts fee-asset))
(spend client john fee-asset "10" nil (strcat john bill))
(assert (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens 10 fee-amount)))
nil
"Balance mismatch after spend")
(login-user ts "john")
(accept-inbox ts nil)
(login-user ts "bill")
(accept-inbox ts)
(assert (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens 2)))
nil
"Balance mismatch after accept")
Spend 10 tokens from bill to . cancels
(setq bill-tokens (getbal ts fee-asset))
(spend client john fee-asset "10" nil (strcat john bill))
(assert (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens 10 fee-amount)))
nil
"Balance mismatch after spend")
(cancel-outbox ts)
(assert (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens 2)))
nil
"Balance mismatch after cancel")))
(defmethod bill-goldgrams-assetid ((ts test-state) &optional (percent nil))
(set-standard-fees ts)
(login-user ts "bill")
(accept-inbox ts)
(let* ((client (client ts))
(precision "7")
(scale "3")
(name "Bill GoldGrams")
(assetid (assetid (id client) precision scale name))
(asset (ignore-errors (getasset client assetid))))
(unless (and asset (equal percent (asset-percent asset)))
(addasset client precision scale name percent))
assetid))
(defmethod goldgrams-test ((ts test-state))
(set-standard-fees ts)
(let* ((john (prog1 (login-user ts "john") (accept-inbox ts)))
(bill (login-user ts "bill"))
(client (client ts))
(fee (getfees client))
(fee-asset (fee-assetid fee))
(fee-amount (fee-amount fee))
(assetid (bill-goldgrams-assetid ts))
(scale (asset-scale (getasset client assetid)))
(formatted-amount "100")
(amount (bcmul formatted-amount (bcpow 10 scale)))
bill-tokens
bill-grams)
(give-tokens ts "bill" "4")
Spend 10 goldgrams from bill to . accepts .
(setq bill-tokens (getbal ts fee-asset)
bill-grams (getbal ts assetid))
(spend client john assetid formatted-amount nil (strcat john bill))
(assert (and (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens fee-amount)))
(eql 0 (bccomp (getbal ts assetid)
(bcsub bill-grams amount))))
nil
"Balance mismatch after spend")
(login-user ts "john")
(accept-inbox ts)
(login-user ts "bill")
(accept-inbox ts)
(assert (and (eql 0 (bccomp (getbal ts fee-asset) bill-tokens))
(eql 0 (bccomp (getbal ts assetid)
(bcsub bill-grams amount))))
nil
"Balance mismatch after accept")
Spend 10 goldgrams from bill to . rejects
(setq bill-tokens (getbal ts fee-asset)
bill-grams (getbal ts assetid))
(spend client john assetid formatted-amount nil (strcat john bill))
(assert (and (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens fee-amount)))
(eql 0 (bccomp (getbal ts assetid)
(bcsub bill-grams amount))))
nil
"Balance mismatch after spend")
(login-user ts "john")
(accept-inbox ts nil)
(login-user ts "bill")
(accept-inbox ts)
(assert (and (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens 2)))
(eql 0 (wbp (scale)
(bccomp (getbal ts assetid) bill-grams))))
nil
"Balance mismatch after reject")
Spend 10 goldgrams from bill to . cancels .
(setq bill-tokens (getbal ts fee-asset)
bill-grams (getbal ts assetid))
(spend client john assetid formatted-amount nil (strcat john bill))
(assert (and (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens fee-amount)))
(eql 0 (bccomp (getbal ts assetid)
(bcsub bill-grams amount))))
nil
"Balance mismatch after spend")
(cancel-outbox ts)
(accept-inbox ts)
(assert (and (eql 0 (bccomp (getbal ts fee-asset)
(bcsub bill-tokens 2)))
(eql 0 (bccomp (getbal ts assetid) bill-grams)))
nil
"Balance mismatch after reject")
))
(defmethod storage-test ((ts test-state))
(set-standard-fees ts)
(let* ((john (prog1 (login-user ts "john") (accept-inbox ts)))
(client (client ts))
(percent "1.0")
(assetid (bill-goldgrams-assetid ts percent))
(bill (id client))
(scale (asset-scale (getasset client assetid)))
(formatted-amount "100")
(amount (bcmul formatted-amount (bcpow 10 scale))))
(declare (ignore amount))
(give-tokens ts "bill" "4")
Spend to . He accepts .
(spend client john assetid (bcadd formatted-amount 1))
(login-user ts "john")
(sleep 1)
(accept-inbox ts)
(login-user ts "bill")
(accept-inbox ts)
Spend to . He rejects
(spend client john assetid formatted-amount)
(login-user ts "john")
(sleep 1)
(accept-inbox ts nil)
(login-user ts "bill")
(accept-inbox ts)
Spend to . Cancel the spend .
(spend client john assetid formatted-amount)
(cancel-outbox ts)
(accept-inbox ts)
Make sure has enough tokens
(give-tokens ts "john" "4")
Spend from . Cancel the spend .
(spend client bill assetid formatted-amount)
(sleep 1)
(cancel-outbox ts)
(accept-inbox ts)
Spend from . rejects .
(spend client bill assetid formatted-amount)
(login-user ts "bill")
(accept-inbox ts nil)
(sleep 1)
(login-user ts "john")
(accept-inbox ts)
Spend from . accepts
(spend client bill assetid formatted-amount)
(login-user ts "bill")
(accept-inbox ts)
(login-user ts "john")
(accept-inbox ts)
(let ((bill-bal (progn (login-user ts "bill")
(getbalance client $MAIN assetid)))
(bill-fee (getstoragefee client assetid))
(john-bal (progn (login-user ts "john")
(getbalance client $MAIN assetid)))
(john-frac (getfraction client assetid)))
(values bill-bal bill-fee john-bal john-frac))))
(defmethod transfer-test ((ts test-state))
(set-standard-fees ts)
(give-tokens ts "bill" "3")
(let* ((bill (login-user ts "bill"))
(client (client ts))
(fee (getfees client))
(tokenid (fee-assetid fee))
(assetid (bill-goldgrams-assetid ts))
(tokenbal (getbal ts tokenid))
(balance (getbalance ts t))
(acct (loop for i from 0
for acct = (format nil "a~d" i)
do
(unless (assoc acct balance :test #'equal)
(return acct)))))
(spend client bill tokenid "1" (list nil acct))
(spend client bill assetid "1" (list nil acct))
(let* ((newbal (getbal ts tokenid))
(diff (bcsub tokenbal (getbal ts tokenid)))
1 spent , 2 new file fees
(unless (bc= diff sb)
(error "Diff sb: ~a, was: ~a, tokenbal: ~a, newbal: ~a"
sb diff tokenbal newbal)))
acct))
(defmethod fee-test ((ts test-state))
(set-standard-fees ts)
(let* ((john (prog1 (login-user ts "john") (accept-inbox ts)))
(bill (prog1 (login-user ts "bill") (accept-inbox ts)))
(client (client ts))
(tokenid (fee-assetid (getfees client)))
(fees (list (make-fee :type $TRANFEE :assetid tokenid :amount 1)
(make-fee :type $REGFEE :assetid tokenid :amount 10)))
(goldgrams (bill-goldgrams-assetid ts)))
(login-bank ts)
(apply #'setfees client
`(,@fees
,(make-fee :type $SPEND :assetid tokenid :amount 2)
,(make-fee :type $TRANSFER :assetid tokenid :amount 3)))
(give-tokens ts "bill" (+ 10 1 2 10 3))
(let ((bank-tokens (progn (login-bank ts)
(reinit-balances client)
(balance-amount (getbalance ts $MAIN tokenid))))
(tokens (progn (login-user ts "bill")
(balance-amount (getbalance ts $MAIN tokenid))))
(backup-p (getbalance ts "backup" tokenid)))
(spend client john tokenid "10")
(let ((sb (bcsub tokens 10 1 2))
(was (balance-amount (getbalance ts $MAIN tokenid)))
(bank-sb (bcadd bank-tokens 2))
(bank-was (progn
(login-bank ts)
(storagefees client)
(accept-inbox ts)
(prog1 (balance-amount (getbalance ts $MAIN tokenid))
(login-user ts "bill")))))
(unless (bc= sb was)
(error "Outspend w/token fee mismatch. Old: ~s, SB: ~s, Was: ~s"
tokens sb was))
(setf tokens was)
(unless (bc= bank-sb bank-was)
(error "Outspend w/token fee bank mismatch. Old: ~s, SB: ~s, Was: ~s"
bank-tokens bank-sb bank-was))
(setf bank-tokens bank-was))
(spend client bill tokenid "10" `(,$MAIN "backup"))
(let ((sb (bcsub tokens 10 3 (if backup-p 0 1)))
(was (balance-amount (getbalance ts $MAIN tokenid))))
(unless (bc= sb was)
(error "Transfer w/token fee mismatch. Old: ~s SB: ~s, Was: ~s"
tokens sb was))))
(login-bank ts)
(apply #'setfees client
`(,@fees
,(make-fee :type $SPEND :assetid goldgrams
:formatted-amount "0.001")
,(make-fee :type $TRANSFER :assetid goldgrams
:formatted-amount "0.002")))
(login-user ts "bill")
(let ((gg (balance-formatted-amount (getbalance client $MAIN goldgrams))))
(spend client john goldgrams "1.1")
(let ((sb (wbp (7) (bcsub gg "1.1")))
(was (balance-formatted-amount (getbalance client $MAIN goldgrams))))
(unless (bc= sb was)
(error "Spend goldgrams issuer mismatch. Old: ~s, sb: ~s, was: ~s"
gg sb was))))
(login-user ts "john")
(accept-inbox ts)
(let ((bankgg (progn
(login-bank ts)
(storagefees client)
(accept-inbox ts)
(let ((bal (getbalance client $MAIN goldgrams)))
(if bal
(balance-formatted-amount bal)
"0"))))
(gg (progn
(login-user ts "john")
(balance-formatted-amount
(getbalance client $MAIN goldgrams)))))
(spend client john goldgrams "1" `(,$MAIN "backup"))
(let ((banksb (wbp (7) (bcadd bankgg ".002")))
(bankwas (progn
(login-bank ts)
(storagefees client)
(accept-inbox ts)
(balance-formatted-amount
(getbalance client $MAIN goldgrams))))
(sb (wbp (7) (bcsub gg "1" "0.002")))
(was (progn
(login-user ts "john")
(balance-formatted-amount
(getbalance client $MAIN goldgrams)))))
(unless (bc= banksb bankwas)
(error "Spend goldgrams transfer bank mismatch. Old:~s, sb: ~s, was: ~s"
bankgg banksb bankwas))
(setf bankgg bankwas)
(unless (bc= sb was)
(error "Spend goldgrams transfer mismatch. Old: ~s, sb: ~s, was: ~s"
gg sb was)))
(setf gg (balance-formatted-amount
(getbalance client "backup" goldgrams)))
(spend client bill goldgrams "0.5" "backup")
(let ((banksb (wbp (7) (bcadd bankgg ".001")))
(bankwas (progn
(login-bank ts)
(storagefees client)
(accept-inbox ts)
(balance-formatted-amount
(getbalance client $MAIN goldgrams))))
(sb (wbp (7) (bcsub gg "0.5" "0.001")))
(was (progn
(login-user ts "john")
(balance-formatted-amount
(getbalance client "backup" goldgrams)))))
(unless (bc= banksb bankwas)
(error "Spend goldgrams bank mismatch. Old:~s, sb: ~s, was: ~s"
bankgg banksb bankwas))
(setf bankgg bankwas)
(unless (bc= sb was)
(error "Spend goldgrams mismatch. Old: ~s, sb: ~s, was: ~s"
gg sb was))
(setf gg was)))
(bill-goldgrams-assetid ts "1")
(give-tokens ts john "12")
(login-user ts "john")
(spend client john goldgrams "0.2" `("backup" ,$MAIN))
(sleep 0.5)
(spend client bill goldgrams "0.1")
(sleep 0.5)
(spend client bill tokenid "10")
(login-bank ts)
(storagefees client)
(accept-inbox ts)
(values
(getbalance ts t)
(progn (login-user ts "john")
(getbalance ts t)))
))
(defun permissions-test (ts)
(set-standard-fees ts)
(let ((client (client ts))
(bankid (bankid ts))
(tokenid (tokenid ts))
(bill (prog1 (login-user ts "bill") (accept-inbox ts)))
(john (prog1 (login-user ts "john") (accept-inbox ts)))
(mike (prog1 (login-user ts "mike") (accept-inbox ts)))
(goldgrams (bill-goldgrams-assetid ts)))
(login-bank ts)
(assert (nth-value 1 (ignore-errors (grant client bill $MINT-TOKENS t))))
(grant client bankid $MINT-TOKENS t)
(grant client bill $MINT-TOKENS t)
(give-tokens ts "bill" 12)
(multiple-value-bind (permissions grant-p)
(get-permissions client $MINT-TOKENS t)
(assert grant-p)
(assert (eql (length permissions) 1))
(let ((perm (car permissions)))
(assert (and (equal (permission-id perm) bankid)
(equal (permission-toid perm) bill)
(equal (permission-permission perm) $MINT-TOKENS)
(permission-grant-p perm)))))
(spend client $COUPON tokenid 10)
(cancel-outbox ts)
(give-tokens ts "john" 12)
(assert (null (get-permissions client $MINT-TOKENS t)))
(assert (nth-value 1 (ignore-errors (spend client $COUPON tokenid 10))))
(login-bank ts)
(grant client mike $MINT-TOKENS t)
(login-user ts "mike")
(grant client john $MINT-TOKENS)
(login-user ts "bill")
(grant client john $MINT-TOKENS t)
(login-user ts "john")
(multiple-value-bind (permissions grant-p)
(get-permissions client $MINT-TOKENS t)
(assert (and (find bill permissions :test #'equal :key #'permission-id)
(find mike permissions :test #'equal :key #'permission-id)
grant-p)))
(login-bank ts)
(deny client bill $MINT-TOKENS)
(login-user ts "john")
(multiple-value-bind (permissions grant-p)
(get-permissions client $MINT-TOKENS t)
(assert (and (eql 1 (length permissions))
(find mike permissions :test #'equal :key #'permission-id)
(not grant-p))))
(login-bank ts)
(deny client mike $MINT-TOKENS)
(login-user ts "john")
(multiple-value-bind (permissions grant-p)
(get-permissions client $MINT-TOKENS t)
(assert (and (null permissions) (null grant-p))))
(login-bank ts)
(grant client bill $MINT-TOKENS t)
(login-user ts "bill")
(grant client john $MINT-TOKENS t)
(login-user ts "john")
(grant client bill $MINT-TOKENS t)
(login-bank ts)
(deny client bill $MINT-TOKENS)
(login-user ts "bill")
(assert (not (get-permissions client $MINT-TOKENS t)))
(login-user ts "john")
(assert (not (get-permissions client $MINT-TOKENS t)))
(login-user ts "bill")
(assert (nth-value 1 (ignore-errors (spend client $COUPON tokenid 10))))
(spend client $COUPON goldgrams 1)
(cancel-outbox ts)
(login-bank ts)
(grant client bankid $MINT-COUPONS t)
(login-user ts "bill")
(assert (nth-value 1 (ignore-errors (spend client $COUPON tokenid 10))))
(assert (nth-value 1 (ignore-errors (spend client $COUPON goldgrams 1))))
(login-bank ts)
(grant client bill $MINT-COUPONS t)
(login-user ts "bill")
(assert (nth-value 1 (ignore-errors (spend client $COUPON tokenid 10))))
(let* ((pubkey (rsa-generate-key 512))
(id (pubkey-id (encode-rsa-public-key pubkey))))
(rsa-free pubkey)
(assert (nth-value 1 (ignore-errors (spend client id tokenid 10)))))
(spend client $COUPON goldgrams 1)
(cancel-outbox ts)
(login-bank ts)
(grant client bankid $ADD-ASSET t)
(login-user ts "bill")
(assert (nth-value 1 (ignore-errors
(addasset client 7 3 "Bill Silver Grams"))))
(login-bank ts)
(grant client bill $ADD-ASSET)
(addasset client 7 3 "Bill Silver Grams")
nil))
(defun run-all-tests (ts-or-dir &rest rest &key dont-erase passphrase port network-p)
(declare (ignore dont-erase passphrase port network-p))
(let ((ts ts-or-dir))
(unless (typep ts 'test-state)
(setf ts (apply #'make-test-state ts-or-dir rest)))
(format t "tokens...") (finish-output)
(tokens-test ts)
(format t " goldgrams...") (finish-output)
(goldgrams-test ts)
(format t " storage...") (finish-output)
(storage-test ts)
(format t " transfer...") (finish-output)
(transfer-test ts)
(format t " fees...") (finish-output)
(fee-test ts)
(format t " permissions...")
(permissions-test ts)
ts))
Copyright 2009 - 2010 Bill St. Clair
distributed under the License is distributed on an " AS IS " BASIS ,
|
b0738c44768af6a8f43cb44f9f1ab3456c6b65f32ca87b177644676081165ed3 | defndaines/meiro | hunt_and_kill_test.clj | (ns meiro.hunt-and-kill-test
(:require [clojure.test :refer [deftest testing is]]
[meiro.core :as meiro]
[meiro.hunt-and-kill :as hunt-and-kill]))
(deftest create-test
(testing "Ensure all cells are linked."
(is (every? #(not-any? empty? %)
(hunt-and-kill/create (meiro/init 10 12))))))
| null | https://raw.githubusercontent.com/defndaines/meiro/f91d4dee2842c056a162c861baf8b71bb4fb140c/test/meiro/hunt_and_kill_test.clj | clojure | (ns meiro.hunt-and-kill-test
(:require [clojure.test :refer [deftest testing is]]
[meiro.core :as meiro]
[meiro.hunt-and-kill :as hunt-and-kill]))
(deftest create-test
(testing "Ensure all cells are linked."
(is (every? #(not-any? empty? %)
(hunt-and-kill/create (meiro/init 10 12))))))
| |
fac63a94bb08bc0034b46b076023bb2f3397b4ed8f8c652499098875e230ea2a | kupl/LearnML | patch.ml | type nat = ZERO | SUCC of nat
let rec natadd (n1 : nat) (n2 : nat) : nat =
match n1 with
| ZERO -> n2
| SUCC a -> if a = ZERO then SUCC n2 else SUCC (natadd a n2)
let rec natmul (n1 : nat) (n2 : nat) : nat =
if n1 = ZERO then ZERO
else match n1 with ZERO -> ZERO | SUCC __s11 -> natadd n2 (natmul n2 __s11)
| null | https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/nat/sub13/patch.ml | ocaml | type nat = ZERO | SUCC of nat
let rec natadd (n1 : nat) (n2 : nat) : nat =
match n1 with
| ZERO -> n2
| SUCC a -> if a = ZERO then SUCC n2 else SUCC (natadd a n2)
let rec natmul (n1 : nat) (n2 : nat) : nat =
if n1 = ZERO then ZERO
else match n1 with ZERO -> ZERO | SUCC __s11 -> natadd n2 (natmul n2 __s11)
| |
395207c419f6d5d49a1ea4f0a505c9da627bf2c7d7c3e91bad36ca9047c0c1a9 | ds-wizard/engine-backend | Components.hs | module Shared.Database.Migration.Development.Component.Data.Components where
import Shared.Model.Component.Component
import Shared.Util.Date
mailComponent :: Component
mailComponent =
Component
{ name = "Mail Component"
, version = "1.0.0"
, builtAt = dt' 2018 1 21
, createdAt = dt' 2018 1 21
, updatedAt = dt' 2018 1 21
}
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/b87f6d481205dd7f0f00fd770145f8ee5c4be193/engine-shared/src/Shared/Database/Migration/Development/Component/Data/Components.hs | haskell | module Shared.Database.Migration.Development.Component.Data.Components where
import Shared.Model.Component.Component
import Shared.Util.Date
mailComponent :: Component
mailComponent =
Component
{ name = "Mail Component"
, version = "1.0.0"
, builtAt = dt' 2018 1 21
, createdAt = dt' 2018 1 21
, updatedAt = dt' 2018 1 21
}
| |
6f0d0e07de3fd334bc36b88e620eb6ab22b0cca9c998e73402054b32fccefdbf | sheyll/mediabus | RawSpec.hs | module Data.MediaBus.Media.Audio.RawSpec (spec) where
import Control.Lens
import Control.Monad (forM)
import Data.Data (Proxy (Proxy))
import Data.MediaBus
import Foreign (Storable (peekByteOff, pokeByteOff, sizeOf), allocaArray)
import Test.Hspec
import Test.QuickCheck
spec :: Spec
spec = do
describe "Raw Sample Conversion" $ do
it "pcmMonoS16ConversionApiIsNice" $ property pcmMonoS16ConversionApiIsNice
it "pcmMonoS16AudioConversionApiIsNice" $ property pcmMonoS16AudioConversionApiIsNice
describe "Storable" $ do
describe "storing a buffer won't change the buffer" $ do
it "Audio (Hz 48000) Mono (Raw S16)" $ property (p1 @Mono @S16)
it "Audio (Hz 48000) Stereo (Raw S16)" $ property (p1 @Stereo @S16)
it "Audio (Hz 48000) Mono (Raw Alaw)" $ property (p1 @Mono @ALaw)
it "Audio (Hz 48000) Stereo (Raw Alaw)" $ property (p1 @Stereo @ALaw)
describe "CanGenerateBlankMedia" $ do
describe "for each duration generates a value such that getDuration equals that duration" $ do
it "Audio (Hz 48000) Mono (Raw S16)" $ property (p2 (Proxy @Mono) (Proxy @S16))
it "Audio (Hz 48000) Stereo (Raw S16)" $ property (p2 (Proxy @Stereo) (Proxy @S16))
it "Audio (Hz 48000) Mono (Raw ALaw)" $ property (p2 (Proxy @Mono) (Proxy @ALaw))
it "Audio (Hz 48000) Stereo (Raw ALaw)" $ property (p2 (Proxy @Stereo) (Proxy @ALaw))
pcmMonoS16ConversionApiIsNice :: Pcm Mono S16 -> Bool
pcmMonoS16ConversionApiIsNice x =
-- try to map over the sample
over eachChannel' id x == x
pcmMonoS16AudioConversionApiIsNice :: Audio (Hz 16000) Mono (Raw S16) -> Bool
pcmMonoS16AudioConversionApiIsNice x =
-- try to map over the sample
over eachSample' id x == x
p1 :: forall c t. (Show (Pcm c t), CanBeSample (Pcm c t)) => Audio (Hz 48000) c (Raw t) -> Property
p1 inAudio = do
let len = mediaBufferLength inBuf
inBuf = inAudio ^. mediaBufferLens
ioProperty $
allocaArray @(Pcm c t) len $ \bufPtr -> do
outList <- forM [0 .. len - 1] $ \i -> do
let offset = i * sizeOf (undefined :: Pcm c t)
mapM_ (pokeByteOff bufPtr offset) (inBuf ^? ix i)
peekByteOff bufPtr offset
return $ mediaBufferToList inBuf === outList
p2 ::
forall c t.
(Show (Pcm c t), CanBeBlank (Pcm c t), CanBeSample (Pcm c t)) =>
Proxy c ->
Proxy t ->
Positive Integer ->
Property
p2 _ _ (Positive someDuration) =
let x :: Audio (Hz 48000) c (Raw t)
x = blankFor (fromInteger someDuration)
epsilonTicks :: Ticks (Hz 48000) Integer
epsilonTicks = MkTicks 1
epsilon = epsilonTicks ^. nominalDiffTime
in fromIntegral someDuration - epsilon <= getDuration x
.&&. getDuration x < fromIntegral someDuration + epsilon
| null | https://raw.githubusercontent.com/sheyll/mediabus/9432a32a01808385ef88e4fad2b59620d27285bc/specs/Data/MediaBus/Media/Audio/RawSpec.hs | haskell | try to map over the sample
try to map over the sample | module Data.MediaBus.Media.Audio.RawSpec (spec) where
import Control.Lens
import Control.Monad (forM)
import Data.Data (Proxy (Proxy))
import Data.MediaBus
import Foreign (Storable (peekByteOff, pokeByteOff, sizeOf), allocaArray)
import Test.Hspec
import Test.QuickCheck
spec :: Spec
spec = do
describe "Raw Sample Conversion" $ do
it "pcmMonoS16ConversionApiIsNice" $ property pcmMonoS16ConversionApiIsNice
it "pcmMonoS16AudioConversionApiIsNice" $ property pcmMonoS16AudioConversionApiIsNice
describe "Storable" $ do
describe "storing a buffer won't change the buffer" $ do
it "Audio (Hz 48000) Mono (Raw S16)" $ property (p1 @Mono @S16)
it "Audio (Hz 48000) Stereo (Raw S16)" $ property (p1 @Stereo @S16)
it "Audio (Hz 48000) Mono (Raw Alaw)" $ property (p1 @Mono @ALaw)
it "Audio (Hz 48000) Stereo (Raw Alaw)" $ property (p1 @Stereo @ALaw)
describe "CanGenerateBlankMedia" $ do
describe "for each duration generates a value such that getDuration equals that duration" $ do
it "Audio (Hz 48000) Mono (Raw S16)" $ property (p2 (Proxy @Mono) (Proxy @S16))
it "Audio (Hz 48000) Stereo (Raw S16)" $ property (p2 (Proxy @Stereo) (Proxy @S16))
it "Audio (Hz 48000) Mono (Raw ALaw)" $ property (p2 (Proxy @Mono) (Proxy @ALaw))
it "Audio (Hz 48000) Stereo (Raw ALaw)" $ property (p2 (Proxy @Stereo) (Proxy @ALaw))
pcmMonoS16ConversionApiIsNice :: Pcm Mono S16 -> Bool
pcmMonoS16ConversionApiIsNice x =
over eachChannel' id x == x
pcmMonoS16AudioConversionApiIsNice :: Audio (Hz 16000) Mono (Raw S16) -> Bool
pcmMonoS16AudioConversionApiIsNice x =
over eachSample' id x == x
p1 :: forall c t. (Show (Pcm c t), CanBeSample (Pcm c t)) => Audio (Hz 48000) c (Raw t) -> Property
p1 inAudio = do
let len = mediaBufferLength inBuf
inBuf = inAudio ^. mediaBufferLens
ioProperty $
allocaArray @(Pcm c t) len $ \bufPtr -> do
outList <- forM [0 .. len - 1] $ \i -> do
let offset = i * sizeOf (undefined :: Pcm c t)
mapM_ (pokeByteOff bufPtr offset) (inBuf ^? ix i)
peekByteOff bufPtr offset
return $ mediaBufferToList inBuf === outList
p2 ::
forall c t.
(Show (Pcm c t), CanBeBlank (Pcm c t), CanBeSample (Pcm c t)) =>
Proxy c ->
Proxy t ->
Positive Integer ->
Property
p2 _ _ (Positive someDuration) =
let x :: Audio (Hz 48000) c (Raw t)
x = blankFor (fromInteger someDuration)
epsilonTicks :: Ticks (Hz 48000) Integer
epsilonTicks = MkTicks 1
epsilon = epsilonTicks ^. nominalDiffTime
in fromIntegral someDuration - epsilon <= getDuration x
.&&. getDuration x < fromIntegral someDuration + epsilon
|
6c65ae6cd16bddcc93500b501807db02792ae07b3660173697d275595d68e704 | macalimlim/programming-in-haskell | Scratch.hs | module Scratch where
import Prelude hiding ((&&), (||))
f :: (a -> a) -> a
f g = undefined
remove :: Int -> [a] -> [a]
remove n xs = take n xs ++ drop (n + 1) xs
funct :: Int -> [a] -> [a]
funct x xs = take (x + 1) xs ++ drop x xs
e3 x = x * 2
e4 (x, y) = x
e6 x y = x * y
e10 (x, y) = [x, y]
e11 :: (Char, Bool)
e11 = ('\a', True)
e13 :: Int -> Int -> Int
e13 x y = x + y * y
| null | https://raw.githubusercontent.com/macalimlim/programming-in-haskell/47d7d9b92c3d79eeedc1123e6eb690f96fa8a4fc/Scratch.hs | haskell | module Scratch where
import Prelude hiding ((&&), (||))
f :: (a -> a) -> a
f g = undefined
remove :: Int -> [a] -> [a]
remove n xs = take n xs ++ drop (n + 1) xs
funct :: Int -> [a] -> [a]
funct x xs = take (x + 1) xs ++ drop x xs
e3 x = x * 2
e4 (x, y) = x
e6 x y = x * y
e10 (x, y) = [x, y]
e11 :: (Char, Bool)
e11 = ('\a', True)
e13 :: Int -> Int -> Int
e13 x y = x + y * y
| |
9831659c9aeefef942f84c25da546ffcd7cd82f8e71f664aa9f043552cee1114 | Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library | SubscriptionScheduleAddInvoiceItem.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 SubscriptionScheduleAddInvoiceItem
module StripeAPI.Types.SubscriptionScheduleAddInvoiceItem 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 {-# SOURCE #-} StripeAPI.Types.DeletedPrice
import {-# SOURCE #-} StripeAPI.Types.Price
import {-# SOURCE #-} StripeAPI.Types.TaxRate
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
-- | Defines the object schema located at @components.schemas.subscription_schedule_add_invoice_item@ in the specification.
--
-- An Add Invoice Item describes the prices and quantities that will be added as pending invoice items when entering a phase.
data SubscriptionScheduleAddInvoiceItem = SubscriptionScheduleAddInvoiceItem
{ -- | price: ID of the price used to generate the invoice item.
subscriptionScheduleAddInvoiceItemPrice :: SubscriptionScheduleAddInvoiceItemPrice'Variants,
-- | quantity: The quantity of the invoice item.
subscriptionScheduleAddInvoiceItemQuantity :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable GHC.Types.Int)),
-- | tax_rates: The tax rates which apply to the item. When set, the \`default_tax_rates\` do not apply to this item.
subscriptionScheduleAddInvoiceItemTaxRates :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable ([TaxRate])))
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON SubscriptionScheduleAddInvoiceItem where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["price" Data.Aeson.Types.ToJSON..= subscriptionScheduleAddInvoiceItemPrice obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("quantity" Data.Aeson.Types.ToJSON..=)) (subscriptionScheduleAddInvoiceItemQuantity obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("tax_rates" Data.Aeson.Types.ToJSON..=)) (subscriptionScheduleAddInvoiceItemTaxRates obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["price" Data.Aeson.Types.ToJSON..= subscriptionScheduleAddInvoiceItemPrice obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("quantity" Data.Aeson.Types.ToJSON..=)) (subscriptionScheduleAddInvoiceItemQuantity obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("tax_rates" Data.Aeson.Types.ToJSON..=)) (subscriptionScheduleAddInvoiceItemTaxRates obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON SubscriptionScheduleAddInvoiceItem where
parseJSON = Data.Aeson.Types.FromJSON.withObject "SubscriptionScheduleAddInvoiceItem" (\obj -> ((GHC.Base.pure SubscriptionScheduleAddInvoiceItem GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "price")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "quantity")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "tax_rates"))
| Create a new ' ' with all required fields .
mkSubscriptionScheduleAddInvoiceItem ::
-- | 'subscriptionScheduleAddInvoiceItemPrice'
SubscriptionScheduleAddInvoiceItemPrice'Variants ->
SubscriptionScheduleAddInvoiceItem
mkSubscriptionScheduleAddInvoiceItem subscriptionScheduleAddInvoiceItemPrice =
SubscriptionScheduleAddInvoiceItem
{ subscriptionScheduleAddInvoiceItemPrice = subscriptionScheduleAddInvoiceItemPrice,
subscriptionScheduleAddInvoiceItemQuantity = GHC.Maybe.Nothing,
subscriptionScheduleAddInvoiceItemTaxRates = GHC.Maybe.Nothing
}
| Defines the oneOf schema located at @components.schemas.subscription_schedule_add_invoice_item.properties.price.anyOf@ in the specification .
--
-- ID of the price used to generate the invoice item.
data SubscriptionScheduleAddInvoiceItemPrice'Variants
= SubscriptionScheduleAddInvoiceItemPrice'Text Data.Text.Internal.Text
| SubscriptionScheduleAddInvoiceItemPrice'Price Price
| SubscriptionScheduleAddInvoiceItemPrice'DeletedPrice DeletedPrice
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON SubscriptionScheduleAddInvoiceItemPrice'Variants where
toJSON (SubscriptionScheduleAddInvoiceItemPrice'Text a) = Data.Aeson.Types.ToJSON.toJSON a
toJSON (SubscriptionScheduleAddInvoiceItemPrice'Price a) = Data.Aeson.Types.ToJSON.toJSON a
toJSON (SubscriptionScheduleAddInvoiceItemPrice'DeletedPrice a) = Data.Aeson.Types.ToJSON.toJSON a
instance Data.Aeson.Types.FromJSON.FromJSON SubscriptionScheduleAddInvoiceItemPrice'Variants where
parseJSON val = case (SubscriptionScheduleAddInvoiceItemPrice'Text Data.Functor.<$> Data.Aeson.Types.FromJSON.fromJSON val) GHC.Base.<|> ((SubscriptionScheduleAddInvoiceItemPrice'Price Data.Functor.<$> Data.Aeson.Types.FromJSON.fromJSON val) GHC.Base.<|> ((SubscriptionScheduleAddInvoiceItemPrice'DeletedPrice Data.Functor.<$> Data.Aeson.Types.FromJSON.fromJSON val) GHC.Base.<|> Data.Aeson.Types.Internal.Error "No variant matched")) of
Data.Aeson.Types.Internal.Success a -> GHC.Base.pure a
Data.Aeson.Types.Internal.Error a -> Control.Monad.Fail.fail a
| null | https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Types/SubscriptionScheduleAddInvoiceItem.hs | haskell | # LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
# SOURCE #
# SOURCE #
# SOURCE #
| Defines the object schema located at @components.schemas.subscription_schedule_add_invoice_item@ in the specification.
An Add Invoice Item describes the prices and quantities that will be added as pending invoice items when entering a phase.
| price: ID of the price used to generate the invoice item.
| quantity: The quantity of the invoice item.
| tax_rates: The tax rates which apply to the item. When set, the \`default_tax_rates\` do not apply to this item.
| 'subscriptionScheduleAddInvoiceItemPrice'
ID of the price used to generate the invoice item. | 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 SubscriptionScheduleAddInvoiceItem
module StripeAPI.Types.SubscriptionScheduleAddInvoiceItem 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 SubscriptionScheduleAddInvoiceItem = SubscriptionScheduleAddInvoiceItem
subscriptionScheduleAddInvoiceItemPrice :: SubscriptionScheduleAddInvoiceItemPrice'Variants,
subscriptionScheduleAddInvoiceItemQuantity :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable GHC.Types.Int)),
subscriptionScheduleAddInvoiceItemTaxRates :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable ([TaxRate])))
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON SubscriptionScheduleAddInvoiceItem where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["price" Data.Aeson.Types.ToJSON..= subscriptionScheduleAddInvoiceItemPrice obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("quantity" Data.Aeson.Types.ToJSON..=)) (subscriptionScheduleAddInvoiceItemQuantity obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("tax_rates" Data.Aeson.Types.ToJSON..=)) (subscriptionScheduleAddInvoiceItemTaxRates obj) : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["price" Data.Aeson.Types.ToJSON..= subscriptionScheduleAddInvoiceItemPrice obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("quantity" Data.Aeson.Types.ToJSON..=)) (subscriptionScheduleAddInvoiceItemQuantity obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("tax_rates" Data.Aeson.Types.ToJSON..=)) (subscriptionScheduleAddInvoiceItemTaxRates obj) : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON SubscriptionScheduleAddInvoiceItem where
parseJSON = Data.Aeson.Types.FromJSON.withObject "SubscriptionScheduleAddInvoiceItem" (\obj -> ((GHC.Base.pure SubscriptionScheduleAddInvoiceItem GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "price")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "quantity")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "tax_rates"))
| Create a new ' ' with all required fields .
mkSubscriptionScheduleAddInvoiceItem ::
SubscriptionScheduleAddInvoiceItemPrice'Variants ->
SubscriptionScheduleAddInvoiceItem
mkSubscriptionScheduleAddInvoiceItem subscriptionScheduleAddInvoiceItemPrice =
SubscriptionScheduleAddInvoiceItem
{ subscriptionScheduleAddInvoiceItemPrice = subscriptionScheduleAddInvoiceItemPrice,
subscriptionScheduleAddInvoiceItemQuantity = GHC.Maybe.Nothing,
subscriptionScheduleAddInvoiceItemTaxRates = GHC.Maybe.Nothing
}
| Defines the oneOf schema located at @components.schemas.subscription_schedule_add_invoice_item.properties.price.anyOf@ in the specification .
data SubscriptionScheduleAddInvoiceItemPrice'Variants
= SubscriptionScheduleAddInvoiceItemPrice'Text Data.Text.Internal.Text
| SubscriptionScheduleAddInvoiceItemPrice'Price Price
| SubscriptionScheduleAddInvoiceItemPrice'DeletedPrice DeletedPrice
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON SubscriptionScheduleAddInvoiceItemPrice'Variants where
toJSON (SubscriptionScheduleAddInvoiceItemPrice'Text a) = Data.Aeson.Types.ToJSON.toJSON a
toJSON (SubscriptionScheduleAddInvoiceItemPrice'Price a) = Data.Aeson.Types.ToJSON.toJSON a
toJSON (SubscriptionScheduleAddInvoiceItemPrice'DeletedPrice a) = Data.Aeson.Types.ToJSON.toJSON a
instance Data.Aeson.Types.FromJSON.FromJSON SubscriptionScheduleAddInvoiceItemPrice'Variants where
parseJSON val = case (SubscriptionScheduleAddInvoiceItemPrice'Text Data.Functor.<$> Data.Aeson.Types.FromJSON.fromJSON val) GHC.Base.<|> ((SubscriptionScheduleAddInvoiceItemPrice'Price Data.Functor.<$> Data.Aeson.Types.FromJSON.fromJSON val) GHC.Base.<|> ((SubscriptionScheduleAddInvoiceItemPrice'DeletedPrice Data.Functor.<$> Data.Aeson.Types.FromJSON.fromJSON val) GHC.Base.<|> Data.Aeson.Types.Internal.Error "No variant matched")) of
Data.Aeson.Types.Internal.Success a -> GHC.Base.pure a
Data.Aeson.Types.Internal.Error a -> Control.Monad.Fail.fail a
|
c7634468caa0b112f1deed5a5402ca7cdd5a7da3b78cf80ebac4804963dd3b12 | technomancy/leiningen | search.clj | (ns leiningen.search
"Search Central and Clojars for published artifacts."
(:require [clojure.string :as string]
[clojure.xml :as xml]
[leiningen.core.project :as project]
[leiningen.core.main :as main])
(:import (java.net URLEncoder)
(javax.xml.parsers SAXParser)
(org.xml.sax.helpers DefaultHandler)))
(defn- decruft-central-xml [content]
(zipmap (map #(get-in % [:attrs :name]) content)
(map #(get-in % [:content 0]) content)))
;; replace clojure.xml version with one that doesn't do illegal access
(defn- startparse [^String url ^DefaultHandler ch]
(let [^SAXParser p (xml/disable-external-entities (xml/sax-parser))]
(.parse p url ch)))
(defn parse [url]
(try (xml/parse url startparse)
(catch Exception e
(main/warn "Could not retrieve search results from" url "because of"
(class e))
(when main/*debug*
(.printStackTrace e)))))
(defn search-central [query]
(let [url (str "=" query)]
(doseq [doc (get-in (parse url) [:content 1 :content])]
(let [result (decruft-central-xml (:content doc))
dep (if (= (result "a") (result "g"))
(result "a")
(str (result "g") "/" (result "a")))]
(println (format "[%s \"%s\"]" dep (result "latestVersion")))))))
(defn search-clojars [query]
(let [url (str "=" query)]
(doseq [{result :attrs} (:content (parse url))]
(let [dep (if (= (result :jar_name) (result :group_name))
(result :jar_name)
(str (result :group_name) "/" (result :jar_name)))]
(println (format "[%s \"%s\"]" dep (result :version)))
(when-let [desc (and (not= (string/trim (result :description "")) "")
(result :description))]
(println " " (string/trim (first (string/split desc #"\n")))))))))
(defn ^:no-project-needed search
"Search Central and Clojars for published artifacts."
[project query]
(let [project (or project (project/make {}))
repos (into {} (:repositories project))]
(doseq [[repo searcher] [["central" search-central]
["clojars" search-clojars]]]
(when (repos repo)
(try (println "Searching" repo "...")
(searcher (URLEncoder/encode query "UTF-8"))
(catch java.io.IOException e
(binding [*out* *err*]
(if (re-find #"HTTP response code: (400|505)" (str e))
(println "Query syntax unsupported.")
(println "Remote error" (.getMessage e))))))))))
| null | https://raw.githubusercontent.com/technomancy/leiningen/24fb93936133bd7fc30c393c127e9e69bb5f2392/src/leiningen/search.clj | clojure | replace clojure.xml version with one that doesn't do illegal access | (ns leiningen.search
"Search Central and Clojars for published artifacts."
(:require [clojure.string :as string]
[clojure.xml :as xml]
[leiningen.core.project :as project]
[leiningen.core.main :as main])
(:import (java.net URLEncoder)
(javax.xml.parsers SAXParser)
(org.xml.sax.helpers DefaultHandler)))
(defn- decruft-central-xml [content]
(zipmap (map #(get-in % [:attrs :name]) content)
(map #(get-in % [:content 0]) content)))
(defn- startparse [^String url ^DefaultHandler ch]
(let [^SAXParser p (xml/disable-external-entities (xml/sax-parser))]
(.parse p url ch)))
(defn parse [url]
(try (xml/parse url startparse)
(catch Exception e
(main/warn "Could not retrieve search results from" url "because of"
(class e))
(when main/*debug*
(.printStackTrace e)))))
(defn search-central [query]
(let [url (str "=" query)]
(doseq [doc (get-in (parse url) [:content 1 :content])]
(let [result (decruft-central-xml (:content doc))
dep (if (= (result "a") (result "g"))
(result "a")
(str (result "g") "/" (result "a")))]
(println (format "[%s \"%s\"]" dep (result "latestVersion")))))))
(defn search-clojars [query]
(let [url (str "=" query)]
(doseq [{result :attrs} (:content (parse url))]
(let [dep (if (= (result :jar_name) (result :group_name))
(result :jar_name)
(str (result :group_name) "/" (result :jar_name)))]
(println (format "[%s \"%s\"]" dep (result :version)))
(when-let [desc (and (not= (string/trim (result :description "")) "")
(result :description))]
(println " " (string/trim (first (string/split desc #"\n")))))))))
(defn ^:no-project-needed search
"Search Central and Clojars for published artifacts."
[project query]
(let [project (or project (project/make {}))
repos (into {} (:repositories project))]
(doseq [[repo searcher] [["central" search-central]
["clojars" search-clojars]]]
(when (repos repo)
(try (println "Searching" repo "...")
(searcher (URLEncoder/encode query "UTF-8"))
(catch java.io.IOException e
(binding [*out* *err*]
(if (re-find #"HTTP response code: (400|505)" (str e))
(println "Query syntax unsupported.")
(println "Remote error" (.getMessage e))))))))))
|
81e93a5da2285a3644975552714b529b8d7065fc34261dda4dcbc05ccde2114b | PacktWorkshops/The-Clojure-Workshop | core_test.cljs | (ns hello-drag-and-drop.core-test
(:require
[cljs.test :refer-macros [deftest is testing]]
[hello-drag-and-drop.core])) | null | https://raw.githubusercontent.com/PacktWorkshops/The-Clojure-Workshop/3d309bb0e46a41ce2c93737870433b47ce0ba6a2/Chapter09/Exercise9.09/hello-drag-and-drop/test/hello_drag_and_drop/core_test.cljs | clojure | (ns hello-drag-and-drop.core-test
(:require
[cljs.test :refer-macros [deftest is testing]]
[hello-drag-and-drop.core])) | |
2af18865bfcc4d2e3d17262557c8f4c28a117a92cb830c0c4908c77f22edc121 | abs/connection_pool | psql_pool.erl | %
( c ) Rdio 2011
%
-module(psql_pool).
-export([initialize/2, close/1, num_connections/0,
spec/1, spec/2]).
num_connections() -> 15.
spec(Module, {Name, Details}) ->
{connection_pool:get_proc_name({Module, Name}),
{connection_pool, start_link, [{Module, Name}, Details]},
permanent, 2000, worker, case Module of ?MODULE -> []; _ -> [Module] end ++ [connection_pool, ?MODULE]}.
spec(Details) ->
spec(?MODULE, Details).
connect(Name) ->
{conn_opts, ConnOpts} = lists:keyfind(conn_opts, 1, connection_pool:endpoint_details(Name)),
case apply(pgsql, connect, ConnOpts) of
{ok, Conn} ->
Conn;
Err ->
exit({pgsql, Err})
end.
initialize(Name, Loop) ->
Conn = connect(Name),
true = link(Conn),
Loop({Name, Conn}).
close(Conn) ->
ok = pgsql:close(Conn).
| null | https://raw.githubusercontent.com/abs/connection_pool/cf864a647b322d636a79550c60957828885ef2d5/src/psql_pool.erl | erlang | ( c ) Rdio 2011
-module(psql_pool).
-export([initialize/2, close/1, num_connections/0,
spec/1, spec/2]).
num_connections() -> 15.
spec(Module, {Name, Details}) ->
{connection_pool:get_proc_name({Module, Name}),
{connection_pool, start_link, [{Module, Name}, Details]},
permanent, 2000, worker, case Module of ?MODULE -> []; _ -> [Module] end ++ [connection_pool, ?MODULE]}.
spec(Details) ->
spec(?MODULE, Details).
connect(Name) ->
{conn_opts, ConnOpts} = lists:keyfind(conn_opts, 1, connection_pool:endpoint_details(Name)),
case apply(pgsql, connect, ConnOpts) of
{ok, Conn} ->
Conn;
Err ->
exit({pgsql, Err})
end.
initialize(Name, Loop) ->
Conn = connect(Name),
true = link(Conn),
Loop({Name, Conn}).
close(Conn) ->
ok = pgsql:close(Conn).
| |
ca4efea1479bd830aff9ff6189db82411d2c58988c2780f9a92d331f20e5e854 | thi-ng/demos | utils.clj | (ns ws-bra-1.utils
(:require
[thi.ng.math.core :as m]
[thi.ng.geom.core :as g]
[thi.ng.geom.vector :as v :refer [vec2 vec3]]
[thi.ng.geom.matrix :as mat]
[thi.ng.geom.circle :refer [circle]]
[thi.ng.geom.polygon :refer [polygon2]]
[thi.ng.geom.line :as l]
[thi.ng.geom.bezier :as b]
[thi.ng.geom.path :as path]
[thi.ng.dstruct.core :as d]))
(defn smooth-polygon
([poly base amount]
(let [c (g/centroid poly)
points (g/vertices poly)
points (d/wrap-seq points [(last points)] [(first points)])]
(->> points
(partition 3 1)
(map
(fn [[p q r]]
(-> (m/- p q)
(m/+ (m/- r q))
(m/+ (m/* (m/- q c) base))
(m/* amount)
(m/+ q))))
(polygon2))))
([poly base amount iter]
(d/iterate-n iter #(smooth-polygon % base amount) poly)))
(defn poly-as-linestrip
[poly]
(let [verts (g/vertices poly)]
(l/linestrip2 (conj verts (first verts)))))
(defn shape-vertices-as-circles
[shape r] (map (fn [v] (circle v r)) (g/vertices shape)))
| null | https://raw.githubusercontent.com/thi-ng/demos/048cd131099a7db29be56b965c053908acad4166/ws-bra-1/src/ws_bra_1/utils.clj | clojure | (ns ws-bra-1.utils
(:require
[thi.ng.math.core :as m]
[thi.ng.geom.core :as g]
[thi.ng.geom.vector :as v :refer [vec2 vec3]]
[thi.ng.geom.matrix :as mat]
[thi.ng.geom.circle :refer [circle]]
[thi.ng.geom.polygon :refer [polygon2]]
[thi.ng.geom.line :as l]
[thi.ng.geom.bezier :as b]
[thi.ng.geom.path :as path]
[thi.ng.dstruct.core :as d]))
(defn smooth-polygon
([poly base amount]
(let [c (g/centroid poly)
points (g/vertices poly)
points (d/wrap-seq points [(last points)] [(first points)])]
(->> points
(partition 3 1)
(map
(fn [[p q r]]
(-> (m/- p q)
(m/+ (m/- r q))
(m/+ (m/* (m/- q c) base))
(m/* amount)
(m/+ q))))
(polygon2))))
([poly base amount iter]
(d/iterate-n iter #(smooth-polygon % base amount) poly)))
(defn poly-as-linestrip
[poly]
(let [verts (g/vertices poly)]
(l/linestrip2 (conj verts (first verts)))))
(defn shape-vertices-as-circles
[shape r] (map (fn [v] (circle v r)) (g/vertices shape)))
| |
9f551cda3e7f69ace0f260b33873b3a5d345a2a8e74664a6319c6078245ba109 | bobzhang/fan | parse_plc.ml |
let list_of_list_option = fun
| Some l -> l
| None -> []
let term_list _loc ts e =
List.fold_right
(fun t c ->
(Comp (Names.cons,[t;c],_loc) : Ast_plc.term)) ts
(match e with
| Some t -> t
| None -> Comp (Names.nil,[],_loc))
let group_rs = ref Compile_plc.group_rs;;
let unwrap_rule_or_masks rd =
List.fold_left (fun m -> fun
| `Rule (p,ts,body,_loc) ->
let (l1,l2) = try Ast_plc.PredMap.find p m with Not_found -> ([],[]) in
Ast_plc.PredMap.add p ((ts,body,_loc)::l1,l2) m
| `Mask (p,args,_loc) ->
let (l1,l2) = try Ast_plc.PredMap.find p m with Not_found -> ([],[]) in
Ast_plc.PredMap.add p (l1,(args,_loc)::l2) m)
Ast_plc.PredMap.empty rd
;;
%create{prog rule_or_mask rule body args term bar_term mask arg_mask};;
%extend{
prog:
[ L0 rule_or_mask as rd %{
let res = unwrap_rule_or_masks rd in
%stru{ ${Ast_gen.sem_of_list (Compile_plc.prog_statics _loc res)} ;;
${Ast_gen.sem_of_list (Compile_plc.prog_rules _loc !group_rs res)} }
}]
rule_or_mask: [ rule as x %{`Rule x} | mask as x %{`Mask x} ]
rule:
[ Lid x; ? args as t; ? body as b; "." %{
let t = list_of_list_option t and b = list_of_list_option b in
((x,List.length t),t,b,_loc) }]
body: [ ":-"; L1 term SEP "," as r %{r} ]
args: [ "("; L1 term SEP "," as r; ")" %{r} ]
term: 10
[ S as x; ("="|"\\="|"is"|"=:="|"=\\="|"<"|"=<"|">"|">=" as op );
S as y %{Comp (Names.transform op,[x;y],_loc)}]
term: 20
[ S as x; ("+"|"-" as op ); S as y %{Comp (Names.transform op,[x;y],_loc)}]
term: 30
FIXME - NRG
| "-"; S as x %{Comp (Names.neg,[x],_loc)} ]
term: 40
[ Lid x; ? args as t %{
(match (x,t) with
| (x,None) -> Comp (x,[],_loc)
| (x,Some t) -> Comp (x,t,_loc))}
| "_" %{Anon _loc}
| "!" %{Comp (Names.cut,[],_loc)}
| Uid x %{Var (x,_loc)}
| Int s %{Integer (int_of_string s, _loc)}
| "("; S as t; ")" %{t}
| "["; L0 S SEP "," as t; ? bar_term as e; "]" %{ term_list _loc t e}]
bar_term: [ "|"; term as t %{t} ]
mask: [ "%:"; Lid x; "("; L1 arg_mask SEP "," as t; ")" %{((x, List.length t),t,_loc)} ]
arg_mask:
[ "+"; ? Uid %{ArgClosed _loc}
| "-"; ? Uid %{ArgOpen _loc}
| "?"; ? Uid %{ArgAny _loc}]};;
let () =
begin
Options.add ("-nogroup",
(Unit (fun () -> group_rs := Compile_plc.nogroup_rs)),
"Don't try to optimally group predicate rules" );
Ast_quotation.of_stru ~lexer:Lex_plc.from_stream ~name:{domain = Ns.lang;name="plc"} ~entry:prog ()
end
| null | https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/thirdparty/plc/parse_plc.ml | ocaml |
let list_of_list_option = fun
| Some l -> l
| None -> []
let term_list _loc ts e =
List.fold_right
(fun t c ->
(Comp (Names.cons,[t;c],_loc) : Ast_plc.term)) ts
(match e with
| Some t -> t
| None -> Comp (Names.nil,[],_loc))
let group_rs = ref Compile_plc.group_rs;;
let unwrap_rule_or_masks rd =
List.fold_left (fun m -> fun
| `Rule (p,ts,body,_loc) ->
let (l1,l2) = try Ast_plc.PredMap.find p m with Not_found -> ([],[]) in
Ast_plc.PredMap.add p ((ts,body,_loc)::l1,l2) m
| `Mask (p,args,_loc) ->
let (l1,l2) = try Ast_plc.PredMap.find p m with Not_found -> ([],[]) in
Ast_plc.PredMap.add p (l1,(args,_loc)::l2) m)
Ast_plc.PredMap.empty rd
;;
%create{prog rule_or_mask rule body args term bar_term mask arg_mask};;
%extend{
prog:
[ L0 rule_or_mask as rd %{
let res = unwrap_rule_or_masks rd in
%stru{ ${Ast_gen.sem_of_list (Compile_plc.prog_statics _loc res)} ;;
${Ast_gen.sem_of_list (Compile_plc.prog_rules _loc !group_rs res)} }
}]
rule_or_mask: [ rule as x %{`Rule x} | mask as x %{`Mask x} ]
rule:
[ Lid x; ? args as t; ? body as b; "." %{
let t = list_of_list_option t and b = list_of_list_option b in
((x,List.length t),t,b,_loc) }]
body: [ ":-"; L1 term SEP "," as r %{r} ]
args: [ "("; L1 term SEP "," as r; ")" %{r} ]
term: 10
[ S as x; ("="|"\\="|"is"|"=:="|"=\\="|"<"|"=<"|">"|">=" as op );
S as y %{Comp (Names.transform op,[x;y],_loc)}]
term: 20
[ S as x; ("+"|"-" as op ); S as y %{Comp (Names.transform op,[x;y],_loc)}]
term: 30
FIXME - NRG
| "-"; S as x %{Comp (Names.neg,[x],_loc)} ]
term: 40
[ Lid x; ? args as t %{
(match (x,t) with
| (x,None) -> Comp (x,[],_loc)
| (x,Some t) -> Comp (x,t,_loc))}
| "_" %{Anon _loc}
| "!" %{Comp (Names.cut,[],_loc)}
| Uid x %{Var (x,_loc)}
| Int s %{Integer (int_of_string s, _loc)}
| "("; S as t; ")" %{t}
| "["; L0 S SEP "," as t; ? bar_term as e; "]" %{ term_list _loc t e}]
bar_term: [ "|"; term as t %{t} ]
mask: [ "%:"; Lid x; "("; L1 arg_mask SEP "," as t; ")" %{((x, List.length t),t,_loc)} ]
arg_mask:
[ "+"; ? Uid %{ArgClosed _loc}
| "-"; ? Uid %{ArgOpen _loc}
| "?"; ? Uid %{ArgAny _loc}]};;
let () =
begin
Options.add ("-nogroup",
(Unit (fun () -> group_rs := Compile_plc.nogroup_rs)),
"Don't try to optimally group predicate rules" );
Ast_quotation.of_stru ~lexer:Lex_plc.from_stream ~name:{domain = Ns.lang;name="plc"} ~entry:prog ()
end
| |
cdf552109c179509f3a9d85a5132321de94895bfd521954f6b671f5d1aa7c730 | Helium4Haskell/helium | NonDerivableEq.hs | data X = X (Int -> Int) deriving (Eq, Show)
data Y = Y Ordering deriving Eq
| null | https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/staticerrors/NonDerivableEq.hs | haskell | data X = X (Int -> Int) deriving (Eq, Show)
data Y = Y Ordering deriving Eq
| |
3ef57a7ab99b41776583dda2fbec217de3d0ee30217e0d56dbe1180f1f11ad5b | dradtke/Lisp-Text-Editor | pattern.lisp | (in-package :cl-cairo2)
(defclass pattern (cairo-object)
())
(defmethod lowlevel-destroy ((pattern pattern))
(cairo_pattern_destroy (get-pointer pattern)))
(defmethod lowlevel-status ((pattern pattern))
(lookup-cairo-enum (cairo_pattern_status (get-pointer pattern)) table-status))
(defmacro define-create-pattern (type &rest args)
"make create-<type>-pattern defun"
`(defun ,(prepend-intern "create-" type :suffix "-pattern") ,args
(let ((pattern (make-instance 'pattern)))
(with-checked-status pattern
(setf (slot-value pattern 'pointer) (,(prepend-intern "cairo_pattern_create_" type :replace-dash nil) ,@args))
(let ((ptr (slot-value pattern 'pointer)))
;; See CREATE-CONTEXT for why (lowlevel-destroy object) cannot be used here
(tg:finalize pattern #'(lambda () (cairo_pattern_destroy ptr))))))))
(define-create-pattern :rgb red green blue)
(define-create-pattern :rgba red green blue alpha)
(define-create-pattern :linear start-x start-y end-x end-y)
(define-create-pattern :radial center0-x center0-y radius0 center1-x center1-y radius1)
(defun create-pattern-for-surface (image)
(with-alive-object (image i-pointer)
(let ((pattern (make-instance 'pattern)))
(with-checked-status pattern
(setf (slot-value pattern 'pointer) (cairo_pattern_create_for_surface i-pointer))
(let ((ptr (slot-value pattern 'pointer)))
;; See CREATE-CONTEXT for why (lowlevel-destroy object) cannot be used here
(tg:finalize pattern #'(lambda () (cairo_pattern_destroy ptr))))))))
(defmacro define-pattern-function-flexible (name (pattern-name pointer-name &rest args) &body body)
"make a defun of the appropriate name with a wrapped body and the pattern's pointer bound to ,pointer-name"
`(defun ,(prepend-intern "pattern-" name :replace-dash nil) ,(cons pattern-name args)
(with-alive-object (,pattern-name ,pointer-name)
(with-checked-status ,pattern-name
,@body))))
(defmacro define-pattern-function (name &rest args)
"define pattern function which don't require wrapping anything except the pattern itself"
`(define-pattern-function-flexible ,name (pattern pointer ,@args)
(,(prepend-intern "cairo_pattern_" name :replace-dash t) pointer ,@args)))
( - function ( name & rest args )
; (with-unique-names (pattern-name pointer-name)
; `(defun ,(prepend-intern "pattern-" name) ,(cons pattern-name args)
; (with-alive-object (,pattern-name ,pointer-name)
; (with-checked-status ,pattern-name
( , ( prepend - intern " cairo - pattern- " name ) , pointer - name , @args ) ) ) ) ) )
(define-pattern-function add-color-stop-rgb offset red green blue)
(define-pattern-function add-color-stop-rgba offset red green blue alpha)
(define-pattern-function-flexible set-matrix (pattern pattern-pointer matrix)
(with-trans-matrix-in matrix matrix-pointer
(cairo_pattern_set_matrix pattern-pointer matrix-pointer)))
(define-pattern-function-flexible get-matrix (pattern pattern-pointer)
(with-trans-matrix-out matrix-pointer
(cairo_pattern_get_matrix pattern-pointer matrix-pointer)))
;maybe extend the define-get-set-using-table macro to support the cairo_pattern_set_... naming scheme?
(define-pattern-function-flexible get-type (pattern pattern-pointer)
(lookup-cairo-enum (cairo_pattern_get_type pattern-pointer) table-pattern-type))
(define-pattern-function-flexible get-extend (pattern pattern-pointer)
(lookup-cairo-enum (cairo_pattern_get_extend pattern-pointer) table-extend))
(define-pattern-function-flexible set-extend (pattern pattern-pointer extend)
(cairo_pattern_set_extend pattern-pointer (lookup-enum extend table-extend)))
(define-pattern-function-flexible get-filter (pattern pattern-pointer)
(lookup-cairo-enum (cairo_pattern_get_extend pattern-pointer) table-filter))
(define-pattern-function-flexible set-filter (pattern pattern-pointer filter)
(cairo_pattern_set_filter pattern-pointer (lookup-enum filter table-filter)))
;; the following functions are missing:
;get-rgba
;get-surface
;get-source
;get-color-stop-rgba
;get-color-stop-count
;get-linear-points
;get-radial-circles
(define-flexible (set-source context-pointer pattern)
;set a context's source to pattern
(with-alive-object (pattern pattern-pointer)
(with-checked-status pattern
(cairo_set_source context-pointer pattern-pointer))))
(define-flexible (mask context-pointer pattern)
(with-alive-object (pattern pattern-pointer)
(with-checked-status pattern
(cairo_mask context-pointer pattern-pointer))))
;;;;
;;;; convenience methods and macros for use with cl-colors:
;;;;
;;;;
(defgeneric create-color-pattern (color)
(:documentation "create a rgb or rgba pattern from the supplied color"))
(defmethod create-color-pattern ((color rgb))
(create-rgb-pattern (red color) (green color) (blue color)))
(defmethod create-color-pattern ((color rgba))
(create-rgba-pattern (red color) (green color) (blue color) (alpha color)))
(defgeneric pattern-add-color-stop (pattern offset color) ;todo: remove leading "pattern-"?
(:documentation "add a color stop to the pattern. color must be of class rgb, rgba or a list (r g b) or (r g b a)"))
(defmethod pattern-add-color-stop :around ((pattern pattern) offset color)
(declare (ignore offset color))
(if (member (pattern-get-type pattern) '(:linear :radial))
(call-next-method)
(error "cannot add a color stop to this pattern type")))
(defmethod pattern-add-color-stop ((pattern pattern) (offset number) (color cl-colors:rgb))
(pattern-add-color-stop-rgb pattern offset
(red color)
(green color)
(blue color)))
(defmethod pattern-add-color-stop ((pattern pattern) (offset number) (color cl-colors:rgba))
(pattern-add-color-stop-rgba pattern offset
(red color)
(green color)
(blue color)
(alpha color)))
(defmethod pattern-add-color-stop ((pattern pattern) (offset number) (color cons))
(unless (every #'numberp color)
(error "invalid color given: not a number"))
(apply (case (length color)
(3 #'pattern-add-color-stop-rgb)
(4 #'pattern-add-color-stop-rgba)
(otherwise (error "invalid color given: list is not of length 3 or 4")))
pattern offset color))
(defmacro make-with-pattern (type &rest args)
"makes a macro that creates and binds a <type> pattern to pattern-name, adds color stops to the pattern
(calling each element of color-stops with pattern-add-color-stop) before evaluating a body and destroying
the pattern."
`(defmacro ,(prepend-intern "with-" type :suffix "-pattern") (pattern-name ,args color-stops &body body)
(with-unique-names (offset-name color-name)
`(let ((,pattern-name ,(list ',(prepend-intern "create-" type :suffix "-pattern") ,@args)))
(loop for (,offset-name ,color-name) in ,color-stops
do (format t "~a~%" (class-of ,color-name))
do (pattern-add-color-stop ,pattern-name ,offset-name ,color-name))
(prog1
(progn ,@body)
(destroy ,pattern-name))))))
(make-with-pattern :radial center0-x center0-y radius0 center1-x center1-y radius1)
(make-with-pattern :linear start-x start-y end-x end-y)
(defun pattern-forms-p (pflist)
"pattern-forms := (pattern-form+)
pattern-form := (pattern-name (create-xxxx-pattern args))"
(if (consp pflist)
(dolist (pf pflist t)
(if (and (consp pf) (eql (length pf) 2))
(if (and (atom (car pf)) (consp (cadr pf)))
t
(error "invalid create-xxx-pattern form:~A" pf))
(error "invalid pattern-form:~A" pf)))
(error "invalid pattern-forms:~A" pflist)))
(defmacro with-patterns (pattern-forms &body body)
"create patterns from pattern-forms, each has its name as specified in the corresponding pattern-form,
and then execute body in which the patterns can be referenced using the names."
(when (pattern-forms-p pattern-forms)
`(let ,(loop for f in pattern-forms collect `(,(car f) ,(cadr f)))
(unwind-protect (progn ,@body)
(progn
,@(loop for f in pattern-forms collect
`(destroy ,(car f))))))))
| null | https://raw.githubusercontent.com/dradtke/Lisp-Text-Editor/b0947828eda82d7edd0df8ec2595e7491a633580/quicklisp/dists/quicklisp/software/cl-cairo2-20120208-git/src/pattern.lisp | lisp | See CREATE-CONTEXT for why (lowlevel-destroy object) cannot be used here
See CREATE-CONTEXT for why (lowlevel-destroy object) cannot be used here
(with-unique-names (pattern-name pointer-name)
`(defun ,(prepend-intern "pattern-" name) ,(cons pattern-name args)
(with-alive-object (,pattern-name ,pointer-name)
(with-checked-status ,pattern-name
maybe extend the define-get-set-using-table macro to support the cairo_pattern_set_... naming scheme?
the following functions are missing:
get-rgba
get-surface
get-source
get-color-stop-rgba
get-color-stop-count
get-linear-points
get-radial-circles
set a context's source to pattern
convenience methods and macros for use with cl-colors:
todo: remove leading "pattern-"? | (in-package :cl-cairo2)
(defclass pattern (cairo-object)
())
(defmethod lowlevel-destroy ((pattern pattern))
(cairo_pattern_destroy (get-pointer pattern)))
(defmethod lowlevel-status ((pattern pattern))
(lookup-cairo-enum (cairo_pattern_status (get-pointer pattern)) table-status))
(defmacro define-create-pattern (type &rest args)
"make create-<type>-pattern defun"
`(defun ,(prepend-intern "create-" type :suffix "-pattern") ,args
(let ((pattern (make-instance 'pattern)))
(with-checked-status pattern
(setf (slot-value pattern 'pointer) (,(prepend-intern "cairo_pattern_create_" type :replace-dash nil) ,@args))
(let ((ptr (slot-value pattern 'pointer)))
(tg:finalize pattern #'(lambda () (cairo_pattern_destroy ptr))))))))
(define-create-pattern :rgb red green blue)
(define-create-pattern :rgba red green blue alpha)
(define-create-pattern :linear start-x start-y end-x end-y)
(define-create-pattern :radial center0-x center0-y radius0 center1-x center1-y radius1)
(defun create-pattern-for-surface (image)
(with-alive-object (image i-pointer)
(let ((pattern (make-instance 'pattern)))
(with-checked-status pattern
(setf (slot-value pattern 'pointer) (cairo_pattern_create_for_surface i-pointer))
(let ((ptr (slot-value pattern 'pointer)))
(tg:finalize pattern #'(lambda () (cairo_pattern_destroy ptr))))))))
(defmacro define-pattern-function-flexible (name (pattern-name pointer-name &rest args) &body body)
"make a defun of the appropriate name with a wrapped body and the pattern's pointer bound to ,pointer-name"
`(defun ,(prepend-intern "pattern-" name :replace-dash nil) ,(cons pattern-name args)
(with-alive-object (,pattern-name ,pointer-name)
(with-checked-status ,pattern-name
,@body))))
(defmacro define-pattern-function (name &rest args)
"define pattern function which don't require wrapping anything except the pattern itself"
`(define-pattern-function-flexible ,name (pattern pointer ,@args)
(,(prepend-intern "cairo_pattern_" name :replace-dash t) pointer ,@args)))
( - function ( name & rest args )
( , ( prepend - intern " cairo - pattern- " name ) , pointer - name , @args ) ) ) ) ) )
(define-pattern-function add-color-stop-rgb offset red green blue)
(define-pattern-function add-color-stop-rgba offset red green blue alpha)
(define-pattern-function-flexible set-matrix (pattern pattern-pointer matrix)
(with-trans-matrix-in matrix matrix-pointer
(cairo_pattern_set_matrix pattern-pointer matrix-pointer)))
(define-pattern-function-flexible get-matrix (pattern pattern-pointer)
(with-trans-matrix-out matrix-pointer
(cairo_pattern_get_matrix pattern-pointer matrix-pointer)))
(define-pattern-function-flexible get-type (pattern pattern-pointer)
(lookup-cairo-enum (cairo_pattern_get_type pattern-pointer) table-pattern-type))
(define-pattern-function-flexible get-extend (pattern pattern-pointer)
(lookup-cairo-enum (cairo_pattern_get_extend pattern-pointer) table-extend))
(define-pattern-function-flexible set-extend (pattern pattern-pointer extend)
(cairo_pattern_set_extend pattern-pointer (lookup-enum extend table-extend)))
(define-pattern-function-flexible get-filter (pattern pattern-pointer)
(lookup-cairo-enum (cairo_pattern_get_extend pattern-pointer) table-filter))
(define-pattern-function-flexible set-filter (pattern pattern-pointer filter)
(cairo_pattern_set_filter pattern-pointer (lookup-enum filter table-filter)))
(define-flexible (set-source context-pointer pattern)
(with-alive-object (pattern pattern-pointer)
(with-checked-status pattern
(cairo_set_source context-pointer pattern-pointer))))
(define-flexible (mask context-pointer pattern)
(with-alive-object (pattern pattern-pointer)
(with-checked-status pattern
(cairo_mask context-pointer pattern-pointer))))
(defgeneric create-color-pattern (color)
(:documentation "create a rgb or rgba pattern from the supplied color"))
(defmethod create-color-pattern ((color rgb))
(create-rgb-pattern (red color) (green color) (blue color)))
(defmethod create-color-pattern ((color rgba))
(create-rgba-pattern (red color) (green color) (blue color) (alpha color)))
(:documentation "add a color stop to the pattern. color must be of class rgb, rgba or a list (r g b) or (r g b a)"))
(defmethod pattern-add-color-stop :around ((pattern pattern) offset color)
(declare (ignore offset color))
(if (member (pattern-get-type pattern) '(:linear :radial))
(call-next-method)
(error "cannot add a color stop to this pattern type")))
(defmethod pattern-add-color-stop ((pattern pattern) (offset number) (color cl-colors:rgb))
(pattern-add-color-stop-rgb pattern offset
(red color)
(green color)
(blue color)))
(defmethod pattern-add-color-stop ((pattern pattern) (offset number) (color cl-colors:rgba))
(pattern-add-color-stop-rgba pattern offset
(red color)
(green color)
(blue color)
(alpha color)))
(defmethod pattern-add-color-stop ((pattern pattern) (offset number) (color cons))
(unless (every #'numberp color)
(error "invalid color given: not a number"))
(apply (case (length color)
(3 #'pattern-add-color-stop-rgb)
(4 #'pattern-add-color-stop-rgba)
(otherwise (error "invalid color given: list is not of length 3 or 4")))
pattern offset color))
(defmacro make-with-pattern (type &rest args)
"makes a macro that creates and binds a <type> pattern to pattern-name, adds color stops to the pattern
(calling each element of color-stops with pattern-add-color-stop) before evaluating a body and destroying
the pattern."
`(defmacro ,(prepend-intern "with-" type :suffix "-pattern") (pattern-name ,args color-stops &body body)
(with-unique-names (offset-name color-name)
`(let ((,pattern-name ,(list ',(prepend-intern "create-" type :suffix "-pattern") ,@args)))
(loop for (,offset-name ,color-name) in ,color-stops
do (format t "~a~%" (class-of ,color-name))
do (pattern-add-color-stop ,pattern-name ,offset-name ,color-name))
(prog1
(progn ,@body)
(destroy ,pattern-name))))))
(make-with-pattern :radial center0-x center0-y radius0 center1-x center1-y radius1)
(make-with-pattern :linear start-x start-y end-x end-y)
(defun pattern-forms-p (pflist)
"pattern-forms := (pattern-form+)
pattern-form := (pattern-name (create-xxxx-pattern args))"
(if (consp pflist)
(dolist (pf pflist t)
(if (and (consp pf) (eql (length pf) 2))
(if (and (atom (car pf)) (consp (cadr pf)))
t
(error "invalid create-xxx-pattern form:~A" pf))
(error "invalid pattern-form:~A" pf)))
(error "invalid pattern-forms:~A" pflist)))
(defmacro with-patterns (pattern-forms &body body)
"create patterns from pattern-forms, each has its name as specified in the corresponding pattern-form,
and then execute body in which the patterns can be referenced using the names."
(when (pattern-forms-p pattern-forms)
`(let ,(loop for f in pattern-forms collect `(,(car f) ,(cadr f)))
(unwind-protect (progn ,@body)
(progn
,@(loop for f in pattern-forms collect
`(destroy ,(car f))))))))
|
fa2f6acc17d7a00712588fde65f7b10e7d866f15dc9ce8353182143b429ce80a | saltysystems/overworld | ow_dl_handler.erl | -module(ow_dl_handler).
-behaviour(cowboy_handler).
-export([init/2]).
init(Req, State) ->
#{peer := {IP, _Port}} = Req,
logger:info("Got a request for API package from ~p", [IP]),
% Compile the latest code
ClientAPI = ow_binding:print(),
Apps = ow_protocol:registered_apps(),
ProtoFiles = protofiles(Apps),
{ok, {"file", Zip}} = zip:create(
"file", [{"libow.gd", ClientAPI} | ProtoFiles], [memory]
),
logger:info("Successfully generated libow.zip!"),
Req2 = cowboy_req:reply(
200,
#{
<<"content-type">> => <<"application/zip">>,
<<"content-disposition">> =>
<<"attachment; filename=libow.zip">>
},
Zip,
Req
),
{ok, Req2, State}.
-spec protofiles(list()) -> [{string(), binary()}, ...].
protofiles(FileList) ->
protofiles(FileList, []).
protofiles([], Acc) ->
Acc;
protofiles([H | T], Acc) ->
Files = {atom_to_list(H) ++ ".proto", protofile(H)},
protofiles(T, [Files | Acc]).
% return the path of the proto file for the given application
-spec protofile(atom()) -> binary().
protofile(App) ->
D = code:priv_dir(App),
% Very hard-coded and rudimentary.
F = D ++ "/proto/" ++ atom_to_list(App) ++ ".proto",
{ok, Proto} = file:read_file(F),
Proto.
| null | https://raw.githubusercontent.com/saltysystems/overworld/8bbf48d3033c22fa5c8e1f2323996a7a1153b160/src/ow_dl_handler.erl | erlang | Compile the latest code
return the path of the proto file for the given application
Very hard-coded and rudimentary. | -module(ow_dl_handler).
-behaviour(cowboy_handler).
-export([init/2]).
init(Req, State) ->
#{peer := {IP, _Port}} = Req,
logger:info("Got a request for API package from ~p", [IP]),
ClientAPI = ow_binding:print(),
Apps = ow_protocol:registered_apps(),
ProtoFiles = protofiles(Apps),
{ok, {"file", Zip}} = zip:create(
"file", [{"libow.gd", ClientAPI} | ProtoFiles], [memory]
),
logger:info("Successfully generated libow.zip!"),
Req2 = cowboy_req:reply(
200,
#{
<<"content-type">> => <<"application/zip">>,
<<"content-disposition">> =>
<<"attachment; filename=libow.zip">>
},
Zip,
Req
),
{ok, Req2, State}.
-spec protofiles(list()) -> [{string(), binary()}, ...].
protofiles(FileList) ->
protofiles(FileList, []).
protofiles([], Acc) ->
Acc;
protofiles([H | T], Acc) ->
Files = {atom_to_list(H) ++ ".proto", protofile(H)},
protofiles(T, [Files | Acc]).
-spec protofile(atom()) -> binary().
protofile(App) ->
D = code:priv_dir(App),
F = D ++ "/proto/" ++ atom_to_list(App) ++ ".proto",
{ok, Proto} = file:read_file(F),
Proto.
|
00bc49f0dac98aacd0de224c9aa584b73914e5504f9438a17e20893423fa7961 | KULeuven-CS/CPL | 1.22.rkt | #lang eopl
(require rackunit)
; ex 1.22
(define filter-in
(lambda (pred lst)
(if (null? lst)
'()
(if (pred (car lst))
(cons (car lst) (filter-in pred (cdr lst)))
(filter-in pred (cdr lst))))))
(check-equal? (filter-in number? '(a 2 (1 3) b 7)) '(2 7))
(check-equal? (filter-in symbol? '(a (b c) 17 foo)) '(a foo)) | null | https://raw.githubusercontent.com/KULeuven-CS/CPL/0c62cca832edc43218ac63c4e8233e3c3f05d20a/chapter1/1.22.rkt | racket | ex 1.22 | #lang eopl
(require rackunit)
(define filter-in
(lambda (pred lst)
(if (null? lst)
'()
(if (pred (car lst))
(cons (car lst) (filter-in pred (cdr lst)))
(filter-in pred (cdr lst))))))
(check-equal? (filter-in number? '(a 2 (1 3) b 7)) '(2 7))
(check-equal? (filter-in symbol? '(a (b c) 17 foo)) '(a foo)) |
f8b0507213a77fcb2b9a94c5df554236f32be40c613d708899dd57fdad5b6a64 | gsakkas/rite | 3529.ml |
let rec listReverse l =
match l with | [] -> [] | _::tl -> (listReverse tl) + tl;;
fix
let rec l = match l with | [ ] - > [ ] | _ : : tl - > ; ;
let rec listReverse l = match l with | [] -> [] | _::tl -> listReverse tl;;
*)
changed spans
( 3,38)-(3,59 )
AppG [ VarG ]
(3,38)-(3,59)
listReverse tl
AppG [VarG]
*)
type error slice
( 2,4)-(3,61 )
( 2,21)-(3,59 )
( 3,3)-(3,59 )
( 3,24)-(3,26 )
( 3,38)-(3,54 )
( 3,38)-(3,59 )
( 3,39)-(3,50 )
( 3,57)-(3,59 )
(2,4)-(3,61)
(2,21)-(3,59)
(3,3)-(3,59)
(3,24)-(3,26)
(3,38)-(3,54)
(3,38)-(3,59)
(3,39)-(3,50)
(3,57)-(3,59)
*)
| null | https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/data/sp14_min/3529.ml | ocaml |
let rec listReverse l =
match l with | [] -> [] | _::tl -> (listReverse tl) + tl;;
fix
let rec l = match l with | [ ] - > [ ] | _ : : tl - > ; ;
let rec listReverse l = match l with | [] -> [] | _::tl -> listReverse tl;;
*)
changed spans
( 3,38)-(3,59 )
AppG [ VarG ]
(3,38)-(3,59)
listReverse tl
AppG [VarG]
*)
type error slice
( 2,4)-(3,61 )
( 2,21)-(3,59 )
( 3,3)-(3,59 )
( 3,24)-(3,26 )
( 3,38)-(3,54 )
( 3,38)-(3,59 )
( 3,39)-(3,50 )
( 3,57)-(3,59 )
(2,4)-(3,61)
(2,21)-(3,59)
(3,3)-(3,59)
(3,24)-(3,26)
(3,38)-(3,54)
(3,38)-(3,59)
(3,39)-(3,50)
(3,57)-(3,59)
*)
| |
677fffa2ca4d49f16fa3c4a495e42f56d6b119c10d5ca561bd7d2572a8165b0a | Tclv/HaskellBook | intermission04.hs | data Mood = Blah | Woot deriving Show
changeMood :: Mood -> Mood
changeMood Blah = Woot
changeMood _ = Blah
| null | https://raw.githubusercontent.com/Tclv/HaskellBook/78eaa5c67579526b0f00f85a10be3156bc304c14/ch4/intermission04.hs | haskell | data Mood = Blah | Woot deriving Show
changeMood :: Mood -> Mood
changeMood Blah = Woot
changeMood _ = Blah
| |
b328c0bf428859e449c83213cc82bdc15bc6c335a4aca391a40b179c0acc9431 | nd/bird | 3.4.2.hs | -- x = (x div y) * y + x mod y
-- x mod y = x - (x div y) * y
-- if x > 0:
x div y < 0 and x div y > = x div ( abs y ) ( because we use floor ) = > ( x div y ) * y > = x = > x - ( x div y ) * y < = 0 = > x mod y < = 0
-- if x = 0:
x mod y = 0 - ( 0 div y ) * y = 0
-- if x < 0:
x div y > 0 and ( abs ( x div y ) * y ) > = ( abs x ) ( because we use floor ) = > ( since ( x div y ) * y < 0 ) x - ( x div y ) * y < = 0 = > x mod y < = 0 | null | https://raw.githubusercontent.com/nd/bird/06dba97af7cfb11f558eaeb31a75bd04cacf7201/ch03/3.4.2.hs | haskell | x = (x div y) * y + x mod y
x mod y = x - (x div y) * y
if x > 0:
if x = 0:
if x < 0: | x div y < 0 and x div y > = x div ( abs y ) ( because we use floor ) = > ( x div y ) * y > = x = > x - ( x div y ) * y < = 0 = > x mod y < = 0
x mod y = 0 - ( 0 div y ) * y = 0
x div y > 0 and ( abs ( x div y ) * y ) > = ( abs x ) ( because we use floor ) = > ( since ( x div y ) * y < 0 ) x - ( x div y ) * y < = 0 = > x mod y < = 0 |
7e65bc426936fe3f0bcf63719844f9720d27c52ba4ee0382e528123e61c1ffb0 | metosin/compojure-api | dates.clj | (ns examples.dates
(:require [compojure.api.sweet :refer :all]
[schema.core :as s]
[ring.util.http-response :refer :all])
(:import (java.util Date)
(org.joda.time LocalDate DateTime)))
(s/defschema Dates {:date Date
:date-time DateTime
:local-date LocalDate})
(defn sample [] {:date (Date.)
:date-time (DateTime.)
:local-date (LocalDate.)})
(def date-routes
(routes
(GET "/dates" []
:return Dates
:summary "returns dates"
(ok (sample)))
(POST "/dates" []
:return Dates
:body [sample (describe Dates "read response from GET /dates in here to see symmetric handling of dates")]
:summary "echos date input."
(ok sample))))
| null | https://raw.githubusercontent.com/metosin/compojure-api/5c88f32fe56cdb6fcdb3cc506bb956943fcd8c17/examples/thingie/src/examples/dates.clj | clojure | (ns examples.dates
(:require [compojure.api.sweet :refer :all]
[schema.core :as s]
[ring.util.http-response :refer :all])
(:import (java.util Date)
(org.joda.time LocalDate DateTime)))
(s/defschema Dates {:date Date
:date-time DateTime
:local-date LocalDate})
(defn sample [] {:date (Date.)
:date-time (DateTime.)
:local-date (LocalDate.)})
(def date-routes
(routes
(GET "/dates" []
:return Dates
:summary "returns dates"
(ok (sample)))
(POST "/dates" []
:return Dates
:body [sample (describe Dates "read response from GET /dates in here to see symmetric handling of dates")]
:summary "echos date input."
(ok sample))))
| |
ad9cbbcd03228f2e2b974054a8f8cfbc6c01328a8dcb35eed512aafda4a4a9f2 | bgamari/bayes-stack | RunSampler.hs | module RunSampler ( SamplerModel (..)
, SamplerOpts (..), samplerOpts
, runSampler
, createSweeps
) where
import Options.Applicative
import Data.Monoid ((<>))
import System.FilePath.Posix ((</>))
import System.Directory
import Control.Monad (when, forM_, void)
import qualified Control.Monad.Trans.State as S
import Control.Monad.IO.Class
import Data.Binary
import qualified Data.ByteString as BS
import Text.Printf
import Control.Concurrent
import Control.Concurrent.STM
import System.Random.MWC
import Data.Random
import Numeric.Log
import BayesStack.Gibbs.Concurrent
data SamplerOpts = SamplerOpts { burnin :: Int
, lag :: Int
, iterations :: Maybe Int
, updateBlock :: Int
, sweepsDir :: FilePath
, nCaps :: Int
, hyperEstOpts :: HyperEstOpts
}
samplerOpts = SamplerOpts
<$> option ( long "burnin"
<> short 'b'
<> metavar "N"
<> value 100
<> help "Number of sweeps to run before taking samples"
)
<*> option ( long "lag"
<> short 'l'
<> metavar "N"
<> value 10
<> help "Number of sweeps between diagnostic samples"
)
<*> option ( long "iterations"
<> short 'i'
<> metavar "N"
<> value Nothing
<> reader (pure . auto)
<> help "Number of sweeps to run for"
)
<*> option ( long "diff-batch"
<> short 'u'
<> metavar "N"
<> value 100
<> help "Number of update diffs to batch before updating global state"
)
<*> strOption ( long "sweeps"
<> short 'S'
<> metavar "DIR"
<> value "sweeps"
<> help "Directory in which to place model state output"
)
<*> option ( long "threads"
<> short 'N'
<> value 1
<> metavar "INT"
<> help "Number of worker threads to start"
)
<*> hyperEstOpts'
data HyperEstOpts = HyperEstOpts { hyperEst :: Bool
, hyperBurnin :: Int
, hyperLag :: Int
}
hyperEstOpts' = HyperEstOpts
<$> switch ( long "hyper"
<> short 'H'
<> help "Enable hyperparameter estimation"
)
<*> option ( long "hyper-burnin"
<> metavar "N"
<> value 10
<> help "Number of sweeps before starting hyperparameter estimations (must be multiple of --lag)"
)
<*> option ( long "hyper-lag"
<> metavar "L"
<> value 10
<> help "Number of sweeps between hyperparameter estimations (must be multiple of --lag)"
)
class Binary ms => SamplerModel ms where
modelLikelihood :: ms -> Log Double
estimateHypers :: ms -> ms
summarizeHypers :: ms -> String
processSweep :: SamplerModel ms => SamplerOpts -> TVar (Log Double) -> Int -> ms -> IO ()
processSweep opts lastMaxV sweepN m = do
let l = modelLikelihood m
putStr $ printf "Sweep %d: %f\n" sweepN (ln l)
appendFile (sweepsDir opts </> "likelihood.log")
$ printf "%d\t%f\n" sweepN (ln l)
when (sweepN >= burnin opts) $ do
newMax <- atomically $ do oldL <- readTVar lastMaxV
if l > oldL then writeTVar lastMaxV l >> return True
else return False
when (newMax && sweepN >= burnin opts) $
let fname = sweepsDir opts </> printf "%05d.state" sweepN
in encodeFile fname m
doEstimateHypers :: SamplerModel ms => SamplerOpts -> Int -> S.StateT ms IO ()
doEstimateHypers opts@(SamplerOpts {hyperEstOpts=HyperEstOpts True burnin lag}) iterN
| iterN >= burnin && iterN `mod` lag == 0 = do
liftIO $ putStrLn "Parameter estimation"
m <- S.get
S.modify estimateHypers
m' <- S.get
void $ liftIO $ forkIO
$ appendFile (sweepsDir opts </> "hyperparams.log")
$ printf "%5d\t%f\t%f\t%s\n"
iterN
(ln $ modelLikelihood m)
(ln $ modelLikelihood m')
(summarizeHypers m')
doEstimateHypers _ _ = return ()
withSystemRandomIO = withSystemRandom :: (GenIO -> IO a) -> IO a
samplerIter :: SamplerModel ms => SamplerOpts -> [WrappedUpdateUnit ms]
-> TMVar () -> TVar (Log Double)
-> Int -> S.StateT ms IO ()
samplerIter opts uus processSweepRunning lastMaxV lagN = do
let sweepN = lagN * lag opts
shuffledUus <- liftIO $ withSystemRandomIO $ \mwc->runRVar (shuffle uus) mwc
let uus' = concat $ replicate (lag opts) shuffledUus
m <- S.get
S.put =<< liftIO (gibbsUpdate (nCaps opts) (updateBlock opts) m uus')
when (sweepN == burnin opts) $ liftIO $ putStrLn "Burn-in complete"
S.get >>= \m->do liftIO $ atomically $ takeTMVar processSweepRunning
void $ liftIO $ forkIO $ do
processSweep opts lastMaxV sweepN m
liftIO $ atomically $ putTMVar processSweepRunning ()
doEstimateHypers opts sweepN
checkOpts :: SamplerOpts -> IO ()
checkOpts opts = do
let hyperOpts = hyperEstOpts opts
when (burnin opts `mod` lag opts /= 0)
$ error "--burnin must be multiple of --lag"
when (hyperEst hyperOpts && hyperBurnin hyperOpts `mod` lag opts /= 0)
$ error "--hyper-burnin must be multiple of --lag"
when (hyperEst hyperOpts && hyperLag hyperOpts `mod` lag opts /= 0)
$ error "--hyper-lag must be multiple of --lag"
runSampler :: SamplerModel ms => SamplerOpts -> ms -> [WrappedUpdateUnit ms] -> IO ()
runSampler opts m uus = do
checkOpts opts
setNumCapabilities (nCaps opts)
createDirectoryIfMissing False (sweepsDir opts)
putStrLn "Starting sampler..."
putStrLn $ "Initial likelihood = "++show (ln $ modelLikelihood m)
putStrLn $ "Burning in for "++show (burnin opts)++" samples"
let lagNs = maybe [0..] (\n->[0..n `div` lag opts]) $ iterations opts
lastMaxV <- atomically $ newTVar 0
processSweepRunning <- atomically $ newTMVar ()
void $ S.runStateT (forM_ lagNs (samplerIter opts uus processSweepRunning lastMaxV)) m
atomically $ takeTMVar processSweepRunning
createSweeps :: SamplerOpts -> IO ()
createSweeps (SamplerOpts {sweepsDir=sweepsDir}) = do
exists <- doesDirectoryExist sweepsDir
if exists
then error "Sweeps directory already exists"
else createDirectory sweepsDir
| null | https://raw.githubusercontent.com/bgamari/bayes-stack/020df7bb7263104fdea254e57d6c7daf7806da3e/network-topic-models/RunSampler.hs | haskell | module RunSampler ( SamplerModel (..)
, SamplerOpts (..), samplerOpts
, runSampler
, createSweeps
) where
import Options.Applicative
import Data.Monoid ((<>))
import System.FilePath.Posix ((</>))
import System.Directory
import Control.Monad (when, forM_, void)
import qualified Control.Monad.Trans.State as S
import Control.Monad.IO.Class
import Data.Binary
import qualified Data.ByteString as BS
import Text.Printf
import Control.Concurrent
import Control.Concurrent.STM
import System.Random.MWC
import Data.Random
import Numeric.Log
import BayesStack.Gibbs.Concurrent
data SamplerOpts = SamplerOpts { burnin :: Int
, lag :: Int
, iterations :: Maybe Int
, updateBlock :: Int
, sweepsDir :: FilePath
, nCaps :: Int
, hyperEstOpts :: HyperEstOpts
}
samplerOpts = SamplerOpts
<$> option ( long "burnin"
<> short 'b'
<> metavar "N"
<> value 100
<> help "Number of sweeps to run before taking samples"
)
<*> option ( long "lag"
<> short 'l'
<> metavar "N"
<> value 10
<> help "Number of sweeps between diagnostic samples"
)
<*> option ( long "iterations"
<> short 'i'
<> metavar "N"
<> value Nothing
<> reader (pure . auto)
<> help "Number of sweeps to run for"
)
<*> option ( long "diff-batch"
<> short 'u'
<> metavar "N"
<> value 100
<> help "Number of update diffs to batch before updating global state"
)
<*> strOption ( long "sweeps"
<> short 'S'
<> metavar "DIR"
<> value "sweeps"
<> help "Directory in which to place model state output"
)
<*> option ( long "threads"
<> short 'N'
<> value 1
<> metavar "INT"
<> help "Number of worker threads to start"
)
<*> hyperEstOpts'
data HyperEstOpts = HyperEstOpts { hyperEst :: Bool
, hyperBurnin :: Int
, hyperLag :: Int
}
hyperEstOpts' = HyperEstOpts
<$> switch ( long "hyper"
<> short 'H'
<> help "Enable hyperparameter estimation"
)
<*> option ( long "hyper-burnin"
<> metavar "N"
<> value 10
<> help "Number of sweeps before starting hyperparameter estimations (must be multiple of --lag)"
)
<*> option ( long "hyper-lag"
<> metavar "L"
<> value 10
<> help "Number of sweeps between hyperparameter estimations (must be multiple of --lag)"
)
class Binary ms => SamplerModel ms where
modelLikelihood :: ms -> Log Double
estimateHypers :: ms -> ms
summarizeHypers :: ms -> String
processSweep :: SamplerModel ms => SamplerOpts -> TVar (Log Double) -> Int -> ms -> IO ()
processSweep opts lastMaxV sweepN m = do
let l = modelLikelihood m
putStr $ printf "Sweep %d: %f\n" sweepN (ln l)
appendFile (sweepsDir opts </> "likelihood.log")
$ printf "%d\t%f\n" sweepN (ln l)
when (sweepN >= burnin opts) $ do
newMax <- atomically $ do oldL <- readTVar lastMaxV
if l > oldL then writeTVar lastMaxV l >> return True
else return False
when (newMax && sweepN >= burnin opts) $
let fname = sweepsDir opts </> printf "%05d.state" sweepN
in encodeFile fname m
doEstimateHypers :: SamplerModel ms => SamplerOpts -> Int -> S.StateT ms IO ()
doEstimateHypers opts@(SamplerOpts {hyperEstOpts=HyperEstOpts True burnin lag}) iterN
| iterN >= burnin && iterN `mod` lag == 0 = do
liftIO $ putStrLn "Parameter estimation"
m <- S.get
S.modify estimateHypers
m' <- S.get
void $ liftIO $ forkIO
$ appendFile (sweepsDir opts </> "hyperparams.log")
$ printf "%5d\t%f\t%f\t%s\n"
iterN
(ln $ modelLikelihood m)
(ln $ modelLikelihood m')
(summarizeHypers m')
doEstimateHypers _ _ = return ()
withSystemRandomIO = withSystemRandom :: (GenIO -> IO a) -> IO a
samplerIter :: SamplerModel ms => SamplerOpts -> [WrappedUpdateUnit ms]
-> TMVar () -> TVar (Log Double)
-> Int -> S.StateT ms IO ()
samplerIter opts uus processSweepRunning lastMaxV lagN = do
let sweepN = lagN * lag opts
shuffledUus <- liftIO $ withSystemRandomIO $ \mwc->runRVar (shuffle uus) mwc
let uus' = concat $ replicate (lag opts) shuffledUus
m <- S.get
S.put =<< liftIO (gibbsUpdate (nCaps opts) (updateBlock opts) m uus')
when (sweepN == burnin opts) $ liftIO $ putStrLn "Burn-in complete"
S.get >>= \m->do liftIO $ atomically $ takeTMVar processSweepRunning
void $ liftIO $ forkIO $ do
processSweep opts lastMaxV sweepN m
liftIO $ atomically $ putTMVar processSweepRunning ()
doEstimateHypers opts sweepN
checkOpts :: SamplerOpts -> IO ()
checkOpts opts = do
let hyperOpts = hyperEstOpts opts
when (burnin opts `mod` lag opts /= 0)
$ error "--burnin must be multiple of --lag"
when (hyperEst hyperOpts && hyperBurnin hyperOpts `mod` lag opts /= 0)
$ error "--hyper-burnin must be multiple of --lag"
when (hyperEst hyperOpts && hyperLag hyperOpts `mod` lag opts /= 0)
$ error "--hyper-lag must be multiple of --lag"
runSampler :: SamplerModel ms => SamplerOpts -> ms -> [WrappedUpdateUnit ms] -> IO ()
runSampler opts m uus = do
checkOpts opts
setNumCapabilities (nCaps opts)
createDirectoryIfMissing False (sweepsDir opts)
putStrLn "Starting sampler..."
putStrLn $ "Initial likelihood = "++show (ln $ modelLikelihood m)
putStrLn $ "Burning in for "++show (burnin opts)++" samples"
let lagNs = maybe [0..] (\n->[0..n `div` lag opts]) $ iterations opts
lastMaxV <- atomically $ newTVar 0
processSweepRunning <- atomically $ newTMVar ()
void $ S.runStateT (forM_ lagNs (samplerIter opts uus processSweepRunning lastMaxV)) m
atomically $ takeTMVar processSweepRunning
createSweeps :: SamplerOpts -> IO ()
createSweeps (SamplerOpts {sweepsDir=sweepsDir}) = do
exists <- doesDirectoryExist sweepsDir
if exists
then error "Sweeps directory already exists"
else createDirectory sweepsDir
| |
0d3af98758075ad91f79e442af0c40b015e46e3dd76c6fe2796aa21db1c818e1 | input-output-hk/cardano-rest | Types.hs | module Cardano.TxSubmit.CLI.Types
( ConfigFile (..)
, GenesisFile (..)
, SocketPath (..)
, TxSubmitNodeParams (..)
) where
import Cardano.Api.Protocol
( Protocol (..) )
import Cardano.Api.Typed
( NetworkId (..) )
import Cardano.Rest.Types
( WebserverConfig )
-- | The product type of all command line arguments
data TxSubmitNodeParams = TxSubmitNodeParams
{ tspConfigFile :: !ConfigFile
, tspProtocol :: !Protocol
, tspNetworkId :: !NetworkId
, tspSocketPath :: !SocketPath
, tspWebserverConfig :: !WebserverConfig
}
newtype ConfigFile = ConfigFile
{ unConfigFile :: FilePath
}
newtype GenesisFile = GenesisFile
{ unGenesisFile :: FilePath
}
newtype SocketPath = SocketPath
{ unSocketPath :: FilePath
}
| null | https://raw.githubusercontent.com/input-output-hk/cardano-rest/040b123b45af06060aae04479d92fada68820f12/submit-api/src/Cardano/TxSubmit/CLI/Types.hs | haskell | | The product type of all command line arguments | module Cardano.TxSubmit.CLI.Types
( ConfigFile (..)
, GenesisFile (..)
, SocketPath (..)
, TxSubmitNodeParams (..)
) where
import Cardano.Api.Protocol
( Protocol (..) )
import Cardano.Api.Typed
( NetworkId (..) )
import Cardano.Rest.Types
( WebserverConfig )
data TxSubmitNodeParams = TxSubmitNodeParams
{ tspConfigFile :: !ConfigFile
, tspProtocol :: !Protocol
, tspNetworkId :: !NetworkId
, tspSocketPath :: !SocketPath
, tspWebserverConfig :: !WebserverConfig
}
newtype ConfigFile = ConfigFile
{ unConfigFile :: FilePath
}
newtype GenesisFile = GenesisFile
{ unGenesisFile :: FilePath
}
newtype SocketPath = SocketPath
{ unSocketPath :: FilePath
}
|
723d09f2664e644b8f9c486a6e8b5a0c4dab68a0b81e9697f640b73ad71bfb85 | brendanhay/gogol | Get.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
-- |
Module : . Storage . Buckets . Get
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
-- Returns metadata for the specified bucket.
--
-- /See:/ </ Cloud Storage JSON API Reference> for @storage.buckets.get@.
module Gogol.Storage.Buckets.Get
( -- * Resource
StorageBucketsGetResource,
-- ** Constructing a Request
StorageBucketsGet (..),
newStorageBucketsGet,
)
where
import qualified Gogol.Prelude as Core
import Gogol.Storage.Types
| A resource alias for @storage.buckets.get@ method which the
-- 'StorageBucketsGet' request conforms to.
type StorageBucketsGetResource =
"storage"
Core.:> "v1"
Core.:> "b"
Core.:> Core.Capture "bucket" Core.Text
Core.:> Core.QueryParam "ifMetagenerationMatch" Core.Int64
Core.:> Core.QueryParam "ifMetagenerationNotMatch" Core.Int64
Core.:> Core.QueryParam "projection" BucketsGetProjection
Core.:> Core.QueryParam "provisionalUserProject" Core.Text
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "userProject" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.Get '[Core.JSON] Bucket
-- | Returns metadata for the specified bucket.
--
-- /See:/ 'newStorageBucketsGet' smart constructor.
data StorageBucketsGet = StorageBucketsGet
{ -- | Name of a bucket.
bucket :: Core.Text,
-- | Makes the return of the bucket metadata conditional on whether the bucket\'s current metageneration matches the given value.
ifMetagenerationMatch :: (Core.Maybe Core.Int64),
-- | Makes the return of the bucket metadata conditional on whether the bucket\'s current metageneration does not match the given value.
ifMetagenerationNotMatch :: (Core.Maybe Core.Int64),
| Set of properties to return . Defaults to noAcl .
projection :: (Core.Maybe BucketsGetProjection),
-- | The project to be billed for this request if the target bucket is requester-pays bucket.
provisionalUserProject :: (Core.Maybe Core.Text),
| Upload protocol for media ( e.g. \"media\ " , \"multipart\ " , \"resumable\ " ) .
uploadType :: (Core.Maybe Core.Text),
-- | The project to be billed for this request. Required for Requester Pays buckets.
userProject :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'StorageBucketsGet' with the minimum fields required to make a request.
newStorageBucketsGet ::
-- | Name of a bucket. See 'bucket'.
Core.Text ->
StorageBucketsGet
newStorageBucketsGet bucket =
StorageBucketsGet
{ bucket = bucket,
ifMetagenerationMatch = Core.Nothing,
ifMetagenerationNotMatch = Core.Nothing,
projection = Core.Nothing,
provisionalUserProject = Core.Nothing,
uploadType = Core.Nothing,
userProject = Core.Nothing
}
instance Core.GoogleRequest StorageBucketsGet where
type Rs StorageBucketsGet = Bucket
type
Scopes StorageBucketsGet =
'[ CloudPlatform'FullControl,
CloudPlatform'ReadOnly,
Devstorage'FullControl,
Devstorage'ReadOnly,
Devstorage'ReadWrite
]
requestClient StorageBucketsGet {..} =
go
bucket
ifMetagenerationMatch
ifMetagenerationNotMatch
projection
provisionalUserProject
uploadType
userProject
(Core.Just Core.AltJSON)
storageService
where
go =
Core.buildClient
(Core.Proxy :: Core.Proxy StorageBucketsGetResource)
Core.mempty
| null | https://raw.githubusercontent.com/brendanhay/gogol/fffd4d98a1996d0ffd4cf64545c5e8af9c976cda/lib/services/gogol-storage/gen/Gogol/Storage/Buckets/Get.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
Returns metadata for the specified bucket.
/See:/ </ Cloud Storage JSON API Reference> for @storage.buckets.get@.
* Resource
** Constructing a Request
'StorageBucketsGet' request conforms to.
| Returns metadata for the specified bucket.
/See:/ 'newStorageBucketsGet' smart constructor.
| Name of a bucket.
| Makes the return of the bucket metadata conditional on whether the bucket\'s current metageneration matches the given value.
| Makes the return of the bucket metadata conditional on whether the bucket\'s current metageneration does not match the given value.
| The project to be billed for this request if the target bucket is requester-pays bucket.
| The project to be billed for this request. Required for Requester Pays buckets.
| Creates a value of 'StorageBucketsGet' with the minimum fields required to make a request.
| Name of a bucket. See 'bucket'. | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Module : . Storage . Buckets . Get
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Gogol.Storage.Buckets.Get
StorageBucketsGetResource,
StorageBucketsGet (..),
newStorageBucketsGet,
)
where
import qualified Gogol.Prelude as Core
import Gogol.Storage.Types
| A resource alias for @storage.buckets.get@ method which the
type StorageBucketsGetResource =
"storage"
Core.:> "v1"
Core.:> "b"
Core.:> Core.Capture "bucket" Core.Text
Core.:> Core.QueryParam "ifMetagenerationMatch" Core.Int64
Core.:> Core.QueryParam "ifMetagenerationNotMatch" Core.Int64
Core.:> Core.QueryParam "projection" BucketsGetProjection
Core.:> Core.QueryParam "provisionalUserProject" Core.Text
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "userProject" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.Get '[Core.JSON] Bucket
data StorageBucketsGet = StorageBucketsGet
bucket :: Core.Text,
ifMetagenerationMatch :: (Core.Maybe Core.Int64),
ifMetagenerationNotMatch :: (Core.Maybe Core.Int64),
| Set of properties to return . Defaults to noAcl .
projection :: (Core.Maybe BucketsGetProjection),
provisionalUserProject :: (Core.Maybe Core.Text),
| Upload protocol for media ( e.g. \"media\ " , \"multipart\ " , \"resumable\ " ) .
uploadType :: (Core.Maybe Core.Text),
userProject :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newStorageBucketsGet ::
Core.Text ->
StorageBucketsGet
newStorageBucketsGet bucket =
StorageBucketsGet
{ bucket = bucket,
ifMetagenerationMatch = Core.Nothing,
ifMetagenerationNotMatch = Core.Nothing,
projection = Core.Nothing,
provisionalUserProject = Core.Nothing,
uploadType = Core.Nothing,
userProject = Core.Nothing
}
instance Core.GoogleRequest StorageBucketsGet where
type Rs StorageBucketsGet = Bucket
type
Scopes StorageBucketsGet =
'[ CloudPlatform'FullControl,
CloudPlatform'ReadOnly,
Devstorage'FullControl,
Devstorage'ReadOnly,
Devstorage'ReadWrite
]
requestClient StorageBucketsGet {..} =
go
bucket
ifMetagenerationMatch
ifMetagenerationNotMatch
projection
provisionalUserProject
uploadType
userProject
(Core.Just Core.AltJSON)
storageService
where
go =
Core.buildClient
(Core.Proxy :: Core.Proxy StorageBucketsGetResource)
Core.mempty
|
e480452de7450e5b48572e864540e0652abbac2686ff4c162de826ef7d4d5c55 | jgertm/lang | lexer.clj | (ns lang.parser.lexer
(:require [blancas.kern.core :refer :all]
[blancas.kern.lexer :as lexer]))
(def ^:private identifier-start
(<|> letter (one-of* "*&^%$!_-+=<>?/")))
(def ^:private identifier-next
(<|> alpha-num (one-of* "*&^%$!_-+=<>?")))
(let [parsers
(lexer/make-parsers
(merge lexer/basic-def
{:comment-line ";"
:identifier-start identifier-start
:identifier-letter identifier-next}))]
(def trim (:trim parsers))
(def lexeme (:lexeme parsers))
(def sym (:sym parsers))
(def new-line (:new-line parsers))
(def one-of (:one-of parsers))
(def none-of (:none-of parsers))
(def token (:token parsers))
(def word (:word parsers))
;; (def identifier (:identifier parsers))
;; (def field (:field parsers))
(def char-lit (:char-lit parsers))
(def string-lit (:string-lit parsers))
(def dec-lit (:dec-lit parsers))
(def oct-lit (:oct-lit parsers))
(def hex-lit (:hex-lit parsers))
(def float-lit (:float-lit parsers))
(def bool-lit (:bool-lit parsers))
(def nil-lit (:nil-lit parsers))
(def parens (:parens parsers))
(def braces (:braces parsers))
(def angles (:angles parsers))
(def brackets (:brackets parsers))
(def semi (:semi parsers))
(def comma (:comma parsers))
(def colon (:colon parsers))
(def dot (:dot parsers))
(def semi-sep (:semi-sep parsers))
(def semi-sep1 (:semi-sep1 parsers))
(def comma-sep (:comma-sep parsers))
(def comma-sep1 (:comma-sep1 parsers)))
(def identifier
(<+> identifier-start (many0 identifier-next)))
| null | https://raw.githubusercontent.com/jgertm/lang/cdd8b08cb23bfa07938b28f917971ee7e4927668/src/lang/parser/lexer.clj | clojure | (def identifier (:identifier parsers))
(def field (:field parsers)) | (ns lang.parser.lexer
(:require [blancas.kern.core :refer :all]
[blancas.kern.lexer :as lexer]))
(def ^:private identifier-start
(<|> letter (one-of* "*&^%$!_-+=<>?/")))
(def ^:private identifier-next
(<|> alpha-num (one-of* "*&^%$!_-+=<>?")))
(let [parsers
(lexer/make-parsers
(merge lexer/basic-def
{:comment-line ";"
:identifier-start identifier-start
:identifier-letter identifier-next}))]
(def trim (:trim parsers))
(def lexeme (:lexeme parsers))
(def sym (:sym parsers))
(def new-line (:new-line parsers))
(def one-of (:one-of parsers))
(def none-of (:none-of parsers))
(def token (:token parsers))
(def word (:word parsers))
(def char-lit (:char-lit parsers))
(def string-lit (:string-lit parsers))
(def dec-lit (:dec-lit parsers))
(def oct-lit (:oct-lit parsers))
(def hex-lit (:hex-lit parsers))
(def float-lit (:float-lit parsers))
(def bool-lit (:bool-lit parsers))
(def nil-lit (:nil-lit parsers))
(def parens (:parens parsers))
(def braces (:braces parsers))
(def angles (:angles parsers))
(def brackets (:brackets parsers))
(def semi (:semi parsers))
(def comma (:comma parsers))
(def colon (:colon parsers))
(def dot (:dot parsers))
(def semi-sep (:semi-sep parsers))
(def semi-sep1 (:semi-sep1 parsers))
(def comma-sep (:comma-sep parsers))
(def comma-sep1 (:comma-sep1 parsers)))
(def identifier
(<+> identifier-start (many0 identifier-next)))
|
aad8ab2980910175bfce223a7f45dfb7c8b7065ad230f2413b3fd3f5a2c6031c | spurious/chibi-scheme-mirror | chibi-prelude.scm |
(import (chibi time) (scheme cxr) (srfi 33) (srfi 39))
(define (timeval->milliseconds tv)
(quotient (+ (* 1000000 (timeval-seconds tv)) (timeval-microseconds tv))
1000))
(define (time* thunk)
(call-with-output-string
(lambda (out)
(let* ((start (car (get-time-of-day)))
(result (parameterize ((current-output-port out)) (thunk)))
(end (car (get-time-of-day)))
(msecs (- (timeval->milliseconds end)
(timeval->milliseconds start))))
(display "user: ")
(display msecs)
(display " system: 0")
(display " real: ")
(display msecs)
(display " gc: 0")
(newline)
(display "result: ")
(write result)
(newline)
result))))
(define-syntax time
(syntax-rules ()
((_ expr) (time* (lambda () expr)))))
| null | https://raw.githubusercontent.com/spurious/chibi-scheme-mirror/49168ab073f64a95c834b5f584a9aaea3469594d/benchmarks/gabriel/chibi-prelude.scm | scheme |
(import (chibi time) (scheme cxr) (srfi 33) (srfi 39))
(define (timeval->milliseconds tv)
(quotient (+ (* 1000000 (timeval-seconds tv)) (timeval-microseconds tv))
1000))
(define (time* thunk)
(call-with-output-string
(lambda (out)
(let* ((start (car (get-time-of-day)))
(result (parameterize ((current-output-port out)) (thunk)))
(end (car (get-time-of-day)))
(msecs (- (timeval->milliseconds end)
(timeval->milliseconds start))))
(display "user: ")
(display msecs)
(display " system: 0")
(display " real: ")
(display msecs)
(display " gc: 0")
(newline)
(display "result: ")
(write result)
(newline)
result))))
(define-syntax time
(syntax-rules ()
((_ expr) (time* (lambda () expr)))))
| |
97d13c801367269c256c0b79ad66e2d4370f6f2e444141bc54978c05af5f6cc1 | disconcision/fructure | code-beauty-shot-partial-mockup.rkt | #lang racket
(provide mode:navigate)
#;(define (mode:navigate key state)
; navigation major mode
(define-from state
stx mode transforms messages)
(define update
(curry hash-set* state))
(match key
["down"
(update
'stx
(match stx
; move cursor ▹ down to closest contained handle ⊃
[(⋱ c⋱ (/ ▹ a/
(⋱ d⋱ (/ ⊃ b/ b))))
(⋱ c⋱ (/ a/
(⋱ d⋱ (/ ▹ ⊃ b/ b))))]
[x x]))]
["up"
(update
'stx
(match stx
; move cursor ▹ up to closest containing handle ⊃
[(⋱ c⋱ (and (/ ⊃ a/
(⋱ d⋱ (/ ▹ b/ b)))
(not (/ ⊃ _/
(⋱ (/ ⊃ _/
(⋱ (/ ▹ _/ _))))))))
(⋱ c⋱ (/ ▹ ⊃ a/
(⋱ d⋱ (/ b/ b))))]
[x x]))]
["right"
(update 'stx
; move ▹ right in a preorder traversal of handles ⊃
(match stx
[; if there's a ⊃ under ▹
(⋱ c⋱ (/ ▹ a/
(▹ (⋱ d⋱ (/ ⊃ b/ b)))))
; and ▹ it
(⋱ c⋱ (/ a/
(⋱ d⋱ (/ ▹ ⊃ b/ b))))]
; otherwise gather the ⊃s in the context of ▹
[(⋱+ c⋱ (capture-when
(or (/ ▹ _/ _)
(/ ⊃ _/ (not (⋱ (/ ▹ _/ _))))))
`(,as ... ,(/ ▹ b/ b) ,(/ ⊃ c/ c) ,ds ...))
; and move ▹ rightwards therein
(⋱+ c⋱
`(,as ... ,(/ b/ b) ,(/ ▹ ⊃ c/ c) ,ds ...))]
[x x]))]
["left"
; moves the cursor left in a preorder traversal
1 . if there is a left - sibling to the cursor which contains - or - is a handle ,
; select its rightmost handle not containing another handle
2 . otherwise , find the most immediate containing handle ;
; that is, a containing handle not containing a handle containing ▹
(define new-stx
(f/match stx
[(⋱c1 ⋱ `(,as ...
,(⋱c2 ⋱ (capture-when (handle _ ... / (not (_ ⋱ (handle _ ... / _)))))
`(,bs ... ,(cs ... / c)))
,ds ... ,(▹ es ... / e) ,fs ...))
(⋱c1 ⋱ `(,@as ,(⋱c2 ⋱... `(,@bs ,(▹ cs ... / c)))
,@ds ,(es ... / e) ,@fs))]
[(⋱c1 ⋱ (and (handle as ... / (⋱c2 ⋱ (▹ bs ... / b)))
(not (handle _ ... / (_ ⋱ (handle _ ... / (_ ⋱ (▹ _ ... / _))))))))
(⋱c1 ⋱ (▹ handle as ... / (⋱c2 ⋱ (bs ... / b))))]
[x x]))
(update 'stx new-stx)]
["\r"
; ENTER: insert a menu and switch to transform mode
; todo: if possible, factor out insert-menu-at for encapsulation
(update
'mode 'menu
'stx (match stx
[(⋱x c⋱ (/ as/
(▹ a)))
(⋱x c⋱ (/ [transform
(insert-menu-at-cursor (/ as/ (▹ a)) stx)]
as/ a))]))]
["\t"
(println "metavar case")
(update
'stx (match stx
[(⋱+x c⋱ #;(capture-when (or (/ _ (▹ _)) (/ [metavar _] _ _)))
(and ls (or (/ _ (▹ (not (⋱x (/ [metavar _] _ _))))) (/ [metavar _] _ _))))
(println ls)
(⋱+x c⋱
(map (λ (t m) (match t [(/ x/ x)
(println `(matched-painting ,(/ [metavar m] x/ x)))
(/ [metavar m] x/ x)]))
ls (range 0 (length ls))))]))]
["escape"
(define (erase-metavars fr)
(match fr
[(/ metavar a/ a)
(/ a/ (erase-metavars a))]
[(? list? a)
(map erase-metavars a)]
[_ fr]))
(update 'stx (erase-metavars stx))]
#;[","
; COMMA: undo (BUG: currently completely broken)
; at minimum, would need to include do-seq and initial-state
(match transforms
['() (update 'messages
`("no undo states" ,messages))]
[_ (update 'messages `("reverting to previous state" ,@messages)
'stx (do-seq (hash-ref initial-state 'stx)
(reverse (rest transforms)))
'transforms (rest transforms))])]
[_
; fallthrough: legacy transformation mode
(println "warning: legacy fallthrough binding")
(mode:legacy key state) ])) | null | https://raw.githubusercontent.com/disconcision/fructure/d434086052eab3c450f631b7b14dcbf9358f45b7/archive/code-beauty-shot-partial-mockup.rkt | racket | (define (mode:navigate key state)
navigation major mode
move cursor ▹ down to closest contained handle ⊃
move cursor ▹ up to closest containing handle ⊃
move ▹ right in a preorder traversal of handles ⊃
if there's a ⊃ under ▹
and ▹ it
otherwise gather the ⊃s in the context of ▹
and move ▹ rightwards therein
moves the cursor left in a preorder traversal
select its rightmost handle not containing another handle
that is, a containing handle not containing a handle containing ▹
ENTER: insert a menu and switch to transform mode
todo: if possible, factor out insert-menu-at for encapsulation
(capture-when (or (/ _ (▹ _)) (/ [metavar _] _ _)))
[","
COMMA: undo (BUG: currently completely broken)
at minimum, would need to include do-seq and initial-state
fallthrough: legacy transformation mode | #lang racket
(provide mode:navigate)
(define-from state
stx mode transforms messages)
(define update
(curry hash-set* state))
(match key
["down"
(update
'stx
(match stx
[(⋱ c⋱ (/ ▹ a/
(⋱ d⋱ (/ ⊃ b/ b))))
(⋱ c⋱ (/ a/
(⋱ d⋱ (/ ▹ ⊃ b/ b))))]
[x x]))]
["up"
(update
'stx
(match stx
[(⋱ c⋱ (and (/ ⊃ a/
(⋱ d⋱ (/ ▹ b/ b)))
(not (/ ⊃ _/
(⋱ (/ ⊃ _/
(⋱ (/ ▹ _/ _))))))))
(⋱ c⋱ (/ ▹ ⊃ a/
(⋱ d⋱ (/ b/ b))))]
[x x]))]
["right"
(update 'stx
(match stx
(⋱ c⋱ (/ ▹ a/
(▹ (⋱ d⋱ (/ ⊃ b/ b)))))
(⋱ c⋱ (/ a/
(⋱ d⋱ (/ ▹ ⊃ b/ b))))]
[(⋱+ c⋱ (capture-when
(or (/ ▹ _/ _)
(/ ⊃ _/ (not (⋱ (/ ▹ _/ _))))))
`(,as ... ,(/ ▹ b/ b) ,(/ ⊃ c/ c) ,ds ...))
(⋱+ c⋱
`(,as ... ,(/ b/ b) ,(/ ▹ ⊃ c/ c) ,ds ...))]
[x x]))]
["left"
1 . if there is a left - sibling to the cursor which contains - or - is a handle ,
(define new-stx
(f/match stx
[(⋱c1 ⋱ `(,as ...
,(⋱c2 ⋱ (capture-when (handle _ ... / (not (_ ⋱ (handle _ ... / _)))))
`(,bs ... ,(cs ... / c)))
,ds ... ,(▹ es ... / e) ,fs ...))
(⋱c1 ⋱ `(,@as ,(⋱c2 ⋱... `(,@bs ,(▹ cs ... / c)))
,@ds ,(es ... / e) ,@fs))]
[(⋱c1 ⋱ (and (handle as ... / (⋱c2 ⋱ (▹ bs ... / b)))
(not (handle _ ... / (_ ⋱ (handle _ ... / (_ ⋱ (▹ _ ... / _))))))))
(⋱c1 ⋱ (▹ handle as ... / (⋱c2 ⋱ (bs ... / b))))]
[x x]))
(update 'stx new-stx)]
["\r"
(update
'mode 'menu
'stx (match stx
[(⋱x c⋱ (/ as/
(▹ a)))
(⋱x c⋱ (/ [transform
(insert-menu-at-cursor (/ as/ (▹ a)) stx)]
as/ a))]))]
["\t"
(println "metavar case")
(update
'stx (match stx
(and ls (or (/ _ (▹ (not (⋱x (/ [metavar _] _ _))))) (/ [metavar _] _ _))))
(println ls)
(⋱+x c⋱
(map (λ (t m) (match t [(/ x/ x)
(println `(matched-painting ,(/ [metavar m] x/ x)))
(/ [metavar m] x/ x)]))
ls (range 0 (length ls))))]))]
["escape"
(define (erase-metavars fr)
(match fr
[(/ metavar a/ a)
(/ a/ (erase-metavars a))]
[(? list? a)
(map erase-metavars a)]
[_ fr]))
(update 'stx (erase-metavars stx))]
(match transforms
['() (update 'messages
`("no undo states" ,messages))]
[_ (update 'messages `("reverting to previous state" ,@messages)
'stx (do-seq (hash-ref initial-state 'stx)
(reverse (rest transforms)))
'transforms (rest transforms))])]
[_
(println "warning: legacy fallthrough binding")
(mode:legacy key state) ])) |
4cc60fd7178ce13b4905d6fd95c5bf26dfb180dc06c30074110cf097120831fe | commercialhaskell/stack | Spec.hs | import Lib
main :: IO ()
main = pure ()
| null | https://raw.githubusercontent.com/commercialhaskell/stack/b846eae85d9f30d28d7a4fa33fea139e7d1420c7/test/integration/tests/multi-test/files/test-2/Spec.hs | haskell | import Lib
main :: IO ()
main = pure ()
| |
23d95804fac6d535854df19aad6b6229a00003428869d08472cdecc047e012d7 | haskell-repa/repa | Vector.hs | {-# LANGUAGE PackageImports, FlexibleContexts #-}
-- | Read and write vectors as ASCII text files.
--
-- The file format is like:
--
-- @
-- VECTOR -- header
100 -- length of vector
1.23 1.56 1.23 ... -- data , separated by whitespace
-- ....
-- @
module Data.Array.Repa.IO.Vector
( readVectorFromTextFile
, writeVectorToTextFile)
where
import Data.Array.Repa as A
import Data.Array.Repa.Repr.Unboxed as A
import Data.Array.Repa.IO.Internals.Text
import Data.List as L
import Prelude as P
import System.IO
import Control.Monad
import Data.Char
-- | Read a vector from a text file.
--
-- * WARNING: This is implemented fairly naively, just using `Strings`
-- under the covers. It will be slow for large data files.
--
-- * It also doesn't do graceful error handling.
-- If the file has the wrong format you'll get a confusing `error`.
--
readVectorFromTextFile
:: (Num e, Read e, Unbox e)
=> FilePath
-> IO (Array U DIM1 e)
readVectorFromTextFile fileName
= do handle <- openFile fileName ReadMode
"VECTOR" <- hGetLine handle
[len] <- liftM (P.map readInt . words) $ hGetLine handle
str <- hGetContents handle
let vals = readValues str
let dims = Z :. len
return $ fromListUnboxed dims vals
readInt :: String -> Int
readInt str
| and $ P.map isDigit str
= read str
| otherwise
= error "Data.Array.Repa.IO.Vector.readVectorFromTextFile parse error when reading data"
-- | Write a vector as a text file.
writeVectorToTextFile
:: (Show e, Source r e)
=> Array r DIM1 e
-> FilePath
-> IO ()
writeVectorToTextFile arr fileName
= do file <- openFile fileName WriteMode
hPutStrLn file "VECTOR"
let Z :. len
= extent arr
hPutStrLn file $ show len
hWriteValues file $ toList arr
hClose file
hFlush file
| null | https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/repa-io/Data/Array/Repa/IO/Vector.hs | haskell | # LANGUAGE PackageImports, FlexibleContexts #
| Read and write vectors as ASCII text files.
The file format is like:
@
VECTOR -- header
length of vector
data , separated by whitespace
....
@
| Read a vector from a text file.
* WARNING: This is implemented fairly naively, just using `Strings`
under the covers. It will be slow for large data files.
* It also doesn't do graceful error handling.
If the file has the wrong format you'll get a confusing `error`.
| Write a vector as a text file. | module Data.Array.Repa.IO.Vector
( readVectorFromTextFile
, writeVectorToTextFile)
where
import Data.Array.Repa as A
import Data.Array.Repa.Repr.Unboxed as A
import Data.Array.Repa.IO.Internals.Text
import Data.List as L
import Prelude as P
import System.IO
import Control.Monad
import Data.Char
readVectorFromTextFile
:: (Num e, Read e, Unbox e)
=> FilePath
-> IO (Array U DIM1 e)
readVectorFromTextFile fileName
= do handle <- openFile fileName ReadMode
"VECTOR" <- hGetLine handle
[len] <- liftM (P.map readInt . words) $ hGetLine handle
str <- hGetContents handle
let vals = readValues str
let dims = Z :. len
return $ fromListUnboxed dims vals
readInt :: String -> Int
readInt str
| and $ P.map isDigit str
= read str
| otherwise
= error "Data.Array.Repa.IO.Vector.readVectorFromTextFile parse error when reading data"
writeVectorToTextFile
:: (Show e, Source r e)
=> Array r DIM1 e
-> FilePath
-> IO ()
writeVectorToTextFile arr fileName
= do file <- openFile fileName WriteMode
hPutStrLn file "VECTOR"
let Z :. len
= extent arr
hPutStrLn file $ show len
hWriteValues file $ toList arr
hClose file
hFlush file
|
32f1350cb1ed9ff79a32b02096dc3a838f5a3bb795e35cbed0b7c214c22b2c34 | james-iohk/plutus-scripts | CheckSameInlineDatumAtMultipleInputs.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NamedFieldPuns #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE OverloadedStrings #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
module CheckSameInlineDatumAtMultipleInputs
( printRedeemer,
serialisedScript,
scriptSBS,
script,
writeSerialisedScript,
)
where
import Cardano.Api (writeFileTextEnvelope)
import Cardano.Api.Shelley (PlutusScript (..),
PlutusScriptV2,
ScriptDataJsonSchema (ScriptDataJsonDetailedSchema),
fromPlutusData,
scriptDataToJson)
import Codec.Serialise
import Data.Aeson as A
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Short as SBS
import Data.Functor (void)
import qualified Ledger.Typed.Scripts as Scripts
import qualified Plutus.Script.Utils.V2.Typed.Scripts as PSU.V2
import qualified Plutus.V2.Ledger.Api as PlutusV2
import qualified Plutus.V2.Ledger.Contexts as PlutusV2
import Plutus.V2.Ledger.Tx
import qualified PlutusTx
import PlutusTx.Prelude as P hiding
(Semigroup (..),
unless, (.))
import Prelude (IO, Semigroup (..),
print, (.))
Expected inline datum to use in redeemer
Expected inline datum to use in redeemer
-}
myDatum = PlutusV2.Datum $ PlutusTx.dataToBuiltinData $ PlutusTx.toData (42 :: Integer)
{-
Redeemer
-}
redeemer = [
PlutusV2.TxOutRef {txOutRefId = "2b1a7a149c1a3574f5d0c5afda47a4fef7c03df69a41551465503ffb6eddc996", txOutRefIdx = 1} ,
PlutusV2.TxOutRef {txOutRefId = "2b1a7a149c1a3574f5d0c5afda47a4fef7c03df69a41551465503ffb6eddc996", txOutRefIdx = 2}
]
printRedeemer = print $ "Script Data: " <> A.encode (scriptDataToJson ScriptDataJsonDetailedSchema $ fromPlutusData $ PlutusV2.toData redeemer)
{-
The validator script
-}
# INLINEABLE expectedInlinePolicy #
expectedInlinePolicy :: PlutusV2.Datum -> [PlutusV2.TxOutRef] -> PlutusV2.ScriptContext -> Bool
expectedInlinePolicy d refs ctx = traceIfFalse "Unexpected inline datum at each regular input" (P.all (P.== True) (map (txoDatumIs42 . findTxIn) refs)) &&
traceIfFalse "Unexpected inline datum at each reference input" (P.all (P.== True) (map (txoDatumIs42 . findRefTxIn) refs))
where
info :: PlutusV2.TxInfo
info = PlutusV2.scriptContextTxInfo ctx
fromJust' :: BuiltinString -> Maybe a -> a -- should be built-in
fromJust' err Nothing = traceError err
fromJust' _ (Just x) = x
findTxIn :: PlutusV2.TxOutRef -> PlutusV2.TxInInfo
findTxIn r = fromJust' "txIn doesn't exist" $ PlutusV2.findTxInByTxOutRef r info
findRefTxInByTxOutRef :: TxOutRef -> PlutusV2.TxInfo -> Maybe PlutusV2.TxInInfo -- similar to findTxInByTxOutRef, should be a built-in context
findRefTxInByTxOutRef outRef PlutusV2.TxInfo{txInfoReferenceInputs} = find (\PlutusV2.TxInInfo{txInInfoOutRef} -> txInInfoOutRef == outRef) txInfoReferenceInputs
findRefTxIn :: PlutusV2.TxOutRef -> PlutusV2.TxInInfo
findRefTxIn r = fromJust' "txRefIn doesn't exist" $ findRefTxInByTxOutRef r info
txoDatumIs42 :: PlutusV2.TxInInfo -> Bool
txoDatumIs42 txin = PlutusV2.OutputDatum d P.== PlutusV2.txOutDatum (PlutusV2.txInInfoResolved txin)
{-
As a Minting Policy
-}
policy :: PlutusV2.Datum -> Scripts.MintingPolicy
policy d = PlutusV2.mkMintingPolicyScript $
$$(PlutusTx.compile [||Scripts.mkUntypedMintingPolicy . expectedInlinePolicy||])
`PlutusTx.applyCode`
PlutusTx.liftCode d
{-
As a Script
-}
script :: PlutusV2.Script
script = PlutusV2.unMintingPolicyScript $ policy myDatum
{-
As a Short Byte String
-}
scriptSBS :: SBS.ShortByteString
scriptSBS = SBS.toShort . LBS.toStrict $ serialise script
{-
As a Serialised Script
-}
serialisedScript :: PlutusScript PlutusScriptV2
serialisedScript = PlutusScriptSerialised scriptSBS
writeSerialisedScript :: IO ()
writeSerialisedScript = void $ writeFileTextEnvelope "check-same-inline-datum-at-multiple-inputs.plutus" Nothing serialisedScript
| null | https://raw.githubusercontent.com/james-iohk/plutus-scripts/d504776f14be3d127837702068e5b5c3a1b935eb/src/CheckSameInlineDatumAtMultipleInputs.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DeriveAnyClass #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeOperators #
Redeemer
The validator script
should be built-in
similar to findTxInByTxOutRef, should be a built-in context
As a Minting Policy
As a Script
As a Short Byte String
As a Serialised Script
| # LANGUAGE MultiParamTypeClasses #
# LANGUAGE NamedFieldPuns #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module CheckSameInlineDatumAtMultipleInputs
( printRedeemer,
serialisedScript,
scriptSBS,
script,
writeSerialisedScript,
)
where
import Cardano.Api (writeFileTextEnvelope)
import Cardano.Api.Shelley (PlutusScript (..),
PlutusScriptV2,
ScriptDataJsonSchema (ScriptDataJsonDetailedSchema),
fromPlutusData,
scriptDataToJson)
import Codec.Serialise
import Data.Aeson as A
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Short as SBS
import Data.Functor (void)
import qualified Ledger.Typed.Scripts as Scripts
import qualified Plutus.Script.Utils.V2.Typed.Scripts as PSU.V2
import qualified Plutus.V2.Ledger.Api as PlutusV2
import qualified Plutus.V2.Ledger.Contexts as PlutusV2
import Plutus.V2.Ledger.Tx
import qualified PlutusTx
import PlutusTx.Prelude as P hiding
(Semigroup (..),
unless, (.))
import Prelude (IO, Semigroup (..),
print, (.))
Expected inline datum to use in redeemer
Expected inline datum to use in redeemer
-}
myDatum = PlutusV2.Datum $ PlutusTx.dataToBuiltinData $ PlutusTx.toData (42 :: Integer)
redeemer = [
PlutusV2.TxOutRef {txOutRefId = "2b1a7a149c1a3574f5d0c5afda47a4fef7c03df69a41551465503ffb6eddc996", txOutRefIdx = 1} ,
PlutusV2.TxOutRef {txOutRefId = "2b1a7a149c1a3574f5d0c5afda47a4fef7c03df69a41551465503ffb6eddc996", txOutRefIdx = 2}
]
printRedeemer = print $ "Script Data: " <> A.encode (scriptDataToJson ScriptDataJsonDetailedSchema $ fromPlutusData $ PlutusV2.toData redeemer)
# INLINEABLE expectedInlinePolicy #
expectedInlinePolicy :: PlutusV2.Datum -> [PlutusV2.TxOutRef] -> PlutusV2.ScriptContext -> Bool
expectedInlinePolicy d refs ctx = traceIfFalse "Unexpected inline datum at each regular input" (P.all (P.== True) (map (txoDatumIs42 . findTxIn) refs)) &&
traceIfFalse "Unexpected inline datum at each reference input" (P.all (P.== True) (map (txoDatumIs42 . findRefTxIn) refs))
where
info :: PlutusV2.TxInfo
info = PlutusV2.scriptContextTxInfo ctx
fromJust' err Nothing = traceError err
fromJust' _ (Just x) = x
findTxIn :: PlutusV2.TxOutRef -> PlutusV2.TxInInfo
findTxIn r = fromJust' "txIn doesn't exist" $ PlutusV2.findTxInByTxOutRef r info
findRefTxInByTxOutRef outRef PlutusV2.TxInfo{txInfoReferenceInputs} = find (\PlutusV2.TxInInfo{txInInfoOutRef} -> txInInfoOutRef == outRef) txInfoReferenceInputs
findRefTxIn :: PlutusV2.TxOutRef -> PlutusV2.TxInInfo
findRefTxIn r = fromJust' "txRefIn doesn't exist" $ findRefTxInByTxOutRef r info
txoDatumIs42 :: PlutusV2.TxInInfo -> Bool
txoDatumIs42 txin = PlutusV2.OutputDatum d P.== PlutusV2.txOutDatum (PlutusV2.txInInfoResolved txin)
policy :: PlutusV2.Datum -> Scripts.MintingPolicy
policy d = PlutusV2.mkMintingPolicyScript $
$$(PlutusTx.compile [||Scripts.mkUntypedMintingPolicy . expectedInlinePolicy||])
`PlutusTx.applyCode`
PlutusTx.liftCode d
script :: PlutusV2.Script
script = PlutusV2.unMintingPolicyScript $ policy myDatum
scriptSBS :: SBS.ShortByteString
scriptSBS = SBS.toShort . LBS.toStrict $ serialise script
serialisedScript :: PlutusScript PlutusScriptV2
serialisedScript = PlutusScriptSerialised scriptSBS
writeSerialisedScript :: IO ()
writeSerialisedScript = void $ writeFileTextEnvelope "check-same-inline-datum-at-multiple-inputs.plutus" Nothing serialisedScript
|
3ce599e720ecfb4d9cd83cd6eaee8c82ab2f9be27fe07aed8c360adc8da9f16d | larcenists/larceny | bibfreq2.scm | ;;; find the most frequently referenced word in the bible.
( Nov 2007 )
modified by ( Nov 2007 )
to use symbol - hash instead of eq ?
(import (scheme base)
(scheme read)
(scheme write)
(scheme time)
(scheme file)
(scheme list)
(scheme char)
(scheme sort)
(except (scheme hash-table)
string-hash string-ci-hash)
(scheme comparator))
(define (fill input-file h)
(let ((p (open-input-file input-file))
(updater (lambda (x) (+ x 1)))
(if-missing (lambda () 0)))
(define (put ls)
(hash-table-update! h
(string->symbol
(list->string
(reverse ls)))
updater
if-missing))
(define (alpha ls)
(let ((c (read-char p)))
(cond
((eof-object? c)
(put ls))
((char-alphabetic? c)
(alpha (cons (char-downcase c) ls)))
(else (put ls) (non-alpha)))))
(define (non-alpha)
(let ((c (read-char p)))
(cond
((eof-object? c) (values))
((char-alphabetic? c)
(alpha (list (char-downcase c))))
(else (non-alpha)))))
(non-alpha)
(close-input-port p)))
(define symbol-comparator
(make-comparator symbol?
eq?
(lambda (x y)
(string<? (symbol->string x)
(symbol->string y)))
symbol-hash))
(define properties (make-hash-table symbol-comparator))
(define (go input-file)
(let* ((symbol-comparator
(make-comparator symbol?
eq?
(lambda (x y)
(string<? (symbol->string x)
(symbol->string y)))
symbol-hash))
(h (make-hash-table symbol-comparator)))
(fill input-file h)
(let-values (((keys vals) (hash-table-entries h)))
(let ((ls (map cons keys vals)))
(take
(list-sort (lambda (a b) (> (cdr a) (cdr b))) ls)
10)))))
(define (main)
(let* ((count (read))
(input1 (read))
(output (read))
(s2 (number->string count))
(s1 input1)
(name "bibfreq2"))
(run-r7rs-benchmark
(string-append name ":" s2)
count
(lambda () (go (hide count input1)))
(lambda (result) (equal? result output)))))
| null | https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/test/Benchmarking/R7RS/src/bibfreq2.scm | scheme | find the most frequently referenced word in the bible. | ( Nov 2007 )
modified by ( Nov 2007 )
to use symbol - hash instead of eq ?
(import (scheme base)
(scheme read)
(scheme write)
(scheme time)
(scheme file)
(scheme list)
(scheme char)
(scheme sort)
(except (scheme hash-table)
string-hash string-ci-hash)
(scheme comparator))
(define (fill input-file h)
(let ((p (open-input-file input-file))
(updater (lambda (x) (+ x 1)))
(if-missing (lambda () 0)))
(define (put ls)
(hash-table-update! h
(string->symbol
(list->string
(reverse ls)))
updater
if-missing))
(define (alpha ls)
(let ((c (read-char p)))
(cond
((eof-object? c)
(put ls))
((char-alphabetic? c)
(alpha (cons (char-downcase c) ls)))
(else (put ls) (non-alpha)))))
(define (non-alpha)
(let ((c (read-char p)))
(cond
((eof-object? c) (values))
((char-alphabetic? c)
(alpha (list (char-downcase c))))
(else (non-alpha)))))
(non-alpha)
(close-input-port p)))
(define symbol-comparator
(make-comparator symbol?
eq?
(lambda (x y)
(string<? (symbol->string x)
(symbol->string y)))
symbol-hash))
(define properties (make-hash-table symbol-comparator))
(define (go input-file)
(let* ((symbol-comparator
(make-comparator symbol?
eq?
(lambda (x y)
(string<? (symbol->string x)
(symbol->string y)))
symbol-hash))
(h (make-hash-table symbol-comparator)))
(fill input-file h)
(let-values (((keys vals) (hash-table-entries h)))
(let ((ls (map cons keys vals)))
(take
(list-sort (lambda (a b) (> (cdr a) (cdr b))) ls)
10)))))
(define (main)
(let* ((count (read))
(input1 (read))
(output (read))
(s2 (number->string count))
(s1 input1)
(name "bibfreq2"))
(run-r7rs-benchmark
(string-append name ":" s2)
count
(lambda () (go (hide count input1)))
(lambda (result) (equal? result output)))))
|
bb1ecfd84c710f89fbfa35904ef2c9889891e5e22e8778601e2817efeec689d3 | tomgstevensphd/Common-Lisp-Utilities-in-Lispworks | U-file&buffers.lisp | ;;********************** U-file&buffers.lisp *************************
;;
;;
* * * ALSO SEE : U - BUFFERS.LISP
U - files&buffers - Frames.lisp
U - LW - editor
GET - FILE - LINES
2020
ddd
(defun get-file-lines (pathname start-line-n &optional end-line-n
&key mark-at-lines-start mark-at-lines-end
(return-formated-string-p T) (line-width 200)
add-newlines (left-margin-spaces 3)
(file-max-lines 25000))
"U-files&buffers RETURNS: (values all-selected-lines start-line end-line file-pos-start-line file-pos-end-line) "
(let
(;;(line)
(all-selected-lines)
(n-lines 0)
(start-line)
(end-line)
(file-pos-start-line)
(file-pos-end-line)
(formated-string)
)
;;read the file lines
(with-open-file (stream pathname :direction :io :if-exists :overwrite)
(loop
for n from 1 to file-max-lines
do
(let*
((line (read-line stream nil 'eof ))
)
(cond
((and (numberp start-line-n)(= n start-line-n))
(setf start-line line
all-selected-lines (append all-selected-lines (list line))
file-pos-start-line (file-position stream))
(when mark-at-lines-start
(format stream ";;~A~%" mark-at-lines-start))
(when (null end-line-n)
(return))
)
((and (numberp end-line-n )(= n end-line-n))
(setf end-line line
all-selected-lines (append all-selected-lines (list line))
file-pos-end-line (file-position stream))
(when mark-at-lines-end
(format stream ";;~A~%" mark-at-lines-end))
(return))
((and (numberp start-line-n)(> n start-line-n)
(numberp end-line-n )(< n end-line-n))
(setf all-selected-lines (append all-selected-lines (list line))))
( format stream " ~A " mark - at - lines - start )
(T nil))
;;end let,loop, with
)))
(when return-formated-string-p
(setf formated-string
(format-string-list all-selected-lines :line-width line-width
:add-newlines add-newlines
:left-margin-spaces left-margin-spaces)))
(values all-selected-lines start-line end-line file-pos-start-line file-pos-end-line formated-string)
;;end let,get-file-lines
))
;;TEST
;; (get-file-lines "C:\\3-TS\\LISP PROJECTS TS\\CogSys-Model\\cs-memory-test.lisp" 5 11)
works= ( " ( defparameter * memtest - list2 " " ' ( hat hand dog mailbox egg hammer lightbulb needle onion can ) ) " " ( defparameter * memtest - list3 nil ) " " ( defparameter * memtest - list4 nil ) " " ( defparameter * memtest - list5 nil ) " " " " ; ; RESULTS " ) " ( defparameter * memtest - list2 " " ; ; RESULTS " 210 394
( get - file - lines " C:\\3 - TS\\LISP PROJECTS TS\\CogSys - Model\\cs - memory - test.lisp " 5 )
works= ( " ( defparameter * memtest - list2 " ) " ( defparameter * memtest - list2 " NIL 210 NIL
1 MARK
( get - file - lines " C:\\3 - TS\\LISP PROJECTS TS\\CogSys - Model\\cs - memory - test.lisp " 5 NIL : mark - at - lines - start " MARK " )
2 MARKS
( get - file - lines " C:\\3 - TS\\LISP PROJECTS TS\\CogSys - Model\\cs - memory - test.lisp " 5 12 : mark - at - lines - start " MK1 " : mark - at - lines - end " MK2 " )
works= ( " ( defparameter * memtest - list2 " " " " box egg hammer lightbulb needle onion can ) ) " " ( defparameter * memtest - list3 nil ) " " ( defparameter * memtest - list4 nil ) " " ( defparameter * memtest - list5 nil ) " " " " ; ; MK2 " )
;;"(defparameter *memtest-list2"
" ; ; MK2 " 210 378
COUNT - FILE - LINES
2020
ddd
(defun count-file-lines (pathname &key (start-line 1) end-line
(file-max-lines 25000))
"U-files. Counts file lines"
(let*
((n-lines 0)
(count-lines-p)
)
(with-open-file (instr pathname :direction :input)
(loop
for n from 1 to file-max-lines
do
(let*
((line (read-line instr nil 'eof))
)
(when (equal line 'eof)
(return))
(cond
((= start-line n)
(setf count-lines-p T))
((and (numberp end-line)
(= end-line n))
(setf count-lines-p NIL))
(count-lines-p
(incf n-lines))
(T nil))
;;end let,loop,with
)))
n-lines
;;end let,count-file-lines
))
;;TEST
;; (count-file-lines "C:\\3-TS\\LISP PROJECTS TS\\MyUtilities\\U-math.lisp")
works= 2393
( count - file - lines " C:\\3 - TS\\LISP PROJECTS TS\\MyUtilities\\U - math.lisp " : start - line 75 ) = 2317
( count - file - lines " C:\\3 - TS\\LISP PROJECTS TS\\MyUtilities\\U - math.lisp " : start - line 75 : end - line 2100 ) = 2024
LIST - BUFFER - UNWRITEABLE - CHARS -- SSS FIX ? ?
2020
ddd
(defun list-buffer-unwriteable-chars (buffer-name)
"U-file&buffers RETURNS unwriteable-chars INPUT: "
(let*
((buffer-obj (editor:get-buffer buffer-name))
(unwriteable-chars) ;; (editor::list-unwritable-characters-command buffer-obj))
(info
(format nil " THIS FUNC NEEDS FIXING-USE EDITOR COMMAND?
==> FROM LISPWORKS:
3.5.3.2 UNWRITABLE CHARACTERS
**There are two ways to resolve this:
1. Set the external format to one which includes char, or
2. Delete char from the buffer before saving.
You may want a file which is Unicode UTF-16 encoded (external format :unicode), UTF-8 encoding (:utf-8) or a language-specific encoding such as :shift-jis or :gbk. Or you may want a Latin-1 encoded file, in which case you could supply :latin-1-safe.
USE Editor Command: FIND UNWRITABLE CHARACTER
Arguments: None Key sequence: None
Finds the next occurrence of a character in the current buffer that cannot be written using the buffer external format. The prefix argument is ignored.
--OR--
USE Editor Command LIST UNWRITABLE CHARACTERS
Arguments: None Key sequence: None
Lists the characters in the current buffer that cannot be written with the buffer external format. The prefix argument is ignored."))
)
(values info unwriteable-chars)
;;end let, list-buffer-unwriteable-chars
))
;;TEST
;; (list-buffer-unwriteable-chars "U-file&buffers.lisp") | null | https://raw.githubusercontent.com/tomgstevensphd/Common-Lisp-Utilities-in-Lispworks/a937e4f5f0ecc2430ac50560b14e87ec3b56ea37/U-file%26buffers.lisp | lisp | ********************** U-file&buffers.lisp *************************
(line)
read the file lines
end let,loop, with
end let,get-file-lines
TEST
(get-file-lines "C:\\3-TS\\LISP PROJECTS TS\\CogSys-Model\\cs-memory-test.lisp" 5 11)
"(defparameter *memtest-list2"
end let,loop,with
end let,count-file-lines
TEST
(count-file-lines "C:\\3-TS\\LISP PROJECTS TS\\MyUtilities\\U-math.lisp")
(editor::list-unwritable-characters-command buffer-obj))
end let, list-buffer-unwriteable-chars
TEST
(list-buffer-unwriteable-chars "U-file&buffers.lisp") | * * * ALSO SEE : U - BUFFERS.LISP
U - files&buffers - Frames.lisp
U - LW - editor
GET - FILE - LINES
2020
ddd
(defun get-file-lines (pathname start-line-n &optional end-line-n
&key mark-at-lines-start mark-at-lines-end
(return-formated-string-p T) (line-width 200)
add-newlines (left-margin-spaces 3)
(file-max-lines 25000))
"U-files&buffers RETURNS: (values all-selected-lines start-line end-line file-pos-start-line file-pos-end-line) "
(let
(all-selected-lines)
(n-lines 0)
(start-line)
(end-line)
(file-pos-start-line)
(file-pos-end-line)
(formated-string)
)
(with-open-file (stream pathname :direction :io :if-exists :overwrite)
(loop
for n from 1 to file-max-lines
do
(let*
((line (read-line stream nil 'eof ))
)
(cond
((and (numberp start-line-n)(= n start-line-n))
(setf start-line line
all-selected-lines (append all-selected-lines (list line))
file-pos-start-line (file-position stream))
(when mark-at-lines-start
(format stream ";;~A~%" mark-at-lines-start))
(when (null end-line-n)
(return))
)
((and (numberp end-line-n )(= n end-line-n))
(setf end-line line
all-selected-lines (append all-selected-lines (list line))
file-pos-end-line (file-position stream))
(when mark-at-lines-end
(format stream ";;~A~%" mark-at-lines-end))
(return))
((and (numberp start-line-n)(> n start-line-n)
(numberp end-line-n )(< n end-line-n))
(setf all-selected-lines (append all-selected-lines (list line))))
( format stream " ~A " mark - at - lines - start )
(T nil))
)))
(when return-formated-string-p
(setf formated-string
(format-string-list all-selected-lines :line-width line-width
:add-newlines add-newlines
:left-margin-spaces left-margin-spaces)))
(values all-selected-lines start-line end-line file-pos-start-line file-pos-end-line formated-string)
))
works= ( " ( defparameter * memtest - list2 " " ' ( hat hand dog mailbox egg hammer lightbulb needle onion can ) ) " " ( defparameter * memtest - list3 nil ) " " ( defparameter * memtest - list4 nil ) " " ( defparameter * memtest - list5 nil ) " " " " ; ; RESULTS " ) " ( defparameter * memtest - list2 " " ; ; RESULTS " 210 394
( get - file - lines " C:\\3 - TS\\LISP PROJECTS TS\\CogSys - Model\\cs - memory - test.lisp " 5 )
works= ( " ( defparameter * memtest - list2 " ) " ( defparameter * memtest - list2 " NIL 210 NIL
1 MARK
( get - file - lines " C:\\3 - TS\\LISP PROJECTS TS\\CogSys - Model\\cs - memory - test.lisp " 5 NIL : mark - at - lines - start " MARK " )
2 MARKS
( get - file - lines " C:\\3 - TS\\LISP PROJECTS TS\\CogSys - Model\\cs - memory - test.lisp " 5 12 : mark - at - lines - start " MK1 " : mark - at - lines - end " MK2 " )
works= ( " ( defparameter * memtest - list2 " " " " box egg hammer lightbulb needle onion can ) ) " " ( defparameter * memtest - list3 nil ) " " ( defparameter * memtest - list4 nil ) " " ( defparameter * memtest - list5 nil ) " " " " ; ; MK2 " )
" ; ; MK2 " 210 378
COUNT - FILE - LINES
2020
ddd
(defun count-file-lines (pathname &key (start-line 1) end-line
(file-max-lines 25000))
"U-files. Counts file lines"
(let*
((n-lines 0)
(count-lines-p)
)
(with-open-file (instr pathname :direction :input)
(loop
for n from 1 to file-max-lines
do
(let*
((line (read-line instr nil 'eof))
)
(when (equal line 'eof)
(return))
(cond
((= start-line n)
(setf count-lines-p T))
((and (numberp end-line)
(= end-line n))
(setf count-lines-p NIL))
(count-lines-p
(incf n-lines))
(T nil))
)))
n-lines
))
works= 2393
( count - file - lines " C:\\3 - TS\\LISP PROJECTS TS\\MyUtilities\\U - math.lisp " : start - line 75 ) = 2317
( count - file - lines " C:\\3 - TS\\LISP PROJECTS TS\\MyUtilities\\U - math.lisp " : start - line 75 : end - line 2100 ) = 2024
LIST - BUFFER - UNWRITEABLE - CHARS -- SSS FIX ? ?
2020
ddd
(defun list-buffer-unwriteable-chars (buffer-name)
"U-file&buffers RETURNS unwriteable-chars INPUT: "
(let*
((buffer-obj (editor:get-buffer buffer-name))
(info
(format nil " THIS FUNC NEEDS FIXING-USE EDITOR COMMAND?
==> FROM LISPWORKS:
3.5.3.2 UNWRITABLE CHARACTERS
**There are two ways to resolve this:
1. Set the external format to one which includes char, or
2. Delete char from the buffer before saving.
You may want a file which is Unicode UTF-16 encoded (external format :unicode), UTF-8 encoding (:utf-8) or a language-specific encoding such as :shift-jis or :gbk. Or you may want a Latin-1 encoded file, in which case you could supply :latin-1-safe.
USE Editor Command: FIND UNWRITABLE CHARACTER
Arguments: None Key sequence: None
Finds the next occurrence of a character in the current buffer that cannot be written using the buffer external format. The prefix argument is ignored.
--OR--
USE Editor Command LIST UNWRITABLE CHARACTERS
Arguments: None Key sequence: None
Lists the characters in the current buffer that cannot be written with the buffer external format. The prefix argument is ignored."))
)
(values info unwriteable-chars)
))
|
d7657a51f1f60ea9370f09b5dc70d2dccd1fe96b1791366624f6015ecdcf7692 | jyh/metaprl | nuprl_nat_extra.ml | extends Ma_tree_1
open Dtactic
interactive nuprl_id_increasing :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
sequent { <H> >- "increasing"[]{"lambda"[]{"i".'"i"};'"k"} }
interactive nuprl_increasing_implies :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f" '"x" in "int"[]{} } -->
sequent { <H> >- "increasing"[]{'"f";'"k"} } -->
sequent { <H> >- "guard"[]{"all"[]{"int_seg"[]{"number"[0:n]{};'"k"};"x"."all"[]{"int_seg"[]{"number"[0:n]{};'"k"};"y"."implies"[]{"lt"[]{'"x";'"y"};"lt"[]{('"f" '"x");('"f" '"y")}}}}} }
interactive nuprl_increasing_implies_le :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f" '"x" in "int"[]{} } -->
sequent { <H> >- "increasing"[]{'"f";'"k"} } -->
sequent { <H> >- "guard"[]{"all"[]{"int_seg"[]{"number"[0:n]{};'"k"};"x"."all"[]{"int_seg"[]{"number"[0:n]{};'"k"};"y"."implies"[]{"le"[]{'"x";'"y"};"le"[]{('"f" '"x");('"f" '"y")}}}}} }
interactive nuprl_compose_increasing '"m" :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"m"} >- '"g" '"x" in "int"[]{} } -->
sequent { <H> >- "increasing"[]{'"f";'"k"} } -->
sequent { <H> >- "increasing"[]{'"g";'"m"} } -->
sequent { <H> >- "increasing"[]{"compose"[]{'"g";'"f"};'"k"} }
interactive nuprl_increasing_inj :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
sequent { <H> >- "increasing"[]{'"f";'"k"} } -->
sequent { <H> >- "inject"[]{"int_seg"[]{"number"[0:n]{};'"k"};"int_seg"[]{"number"[0:n]{};'"m"};'"f"} }
interactive nuprl_increasing_le :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
sequent { <H> >- "exists"[]{"fun"[]{"int_seg"[]{"number"[0:n]{};'"k"};""."int_seg"[]{"number"[0:n]{};'"m"}};"f"."increasing"[]{'"f";'"k"}} } -->
sequent { <H> >- "le"[]{'"k";'"m"} }
interactive nuprl_increasing_is_id '"k" :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "increasing"[]{'"f";'"k"} } -->
[wf] sequent { <H> >- '"i" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "equal"[]{"int"[]{};('"f" '"i");'"i"} }
interactive nuprl_increasing_lower_bound '"k" :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f" '"x" in "int"[]{} } -->
[wf] sequent { <H> >- '"x" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "increasing"[]{'"f";'"k"} } -->
sequent { <H> >- "le"[]{"add"[]{('"f" "number"[0:n]{});'"x"};('"f" '"x")} }
interactive nuprl_injection_le :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
sequent { <H> >- "exists"[]{"fun"[]{"int_seg"[]{"number"[0:n]{};'"k"};""."int_seg"[]{"number"[0:n]{};'"m"}};"f"."inject"[]{"int_seg"[]{"number"[0:n]{};'"k"};"int_seg"[]{"number"[0:n]{};'"m"};'"f"}} } -->
sequent { <H> >- "le"[]{'"k";'"m"} }
interactive nuprl_disjoint_increasing_onto '"f" '"g" :
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"g" '"x" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
sequent { <H> >- "increasing"[]{'"f";'"n"} } -->
sequent { <H> >- "increasing"[]{'"g";'"k"} } -->
sequent { <H>; "i": "int_seg"[]{"number"[0:n]{};'"m"} >- "or"[]{"exists"[]{"int_seg"[]{"number"[0:n]{};'"n"};"j"."equal"[]{"int"[]{};'"i";('"f" '"j")}};"exists"[]{"int_seg"[]{"number"[0:n]{};'"k"};"j"."equal"[]{"int"[]{};'"i";('"g" '"j")}}} } -->
sequent { <H>; "j1": "int_seg"[]{"number"[0:n]{};'"n"} ; "j2": "int_seg"[]{"number"[0:n]{};'"k"} >- "not"[]{"equal"[]{"int"[]{};('"f" '"j1");('"g" '"j2")}} } -->
sequent { <H> >- "equal"[]{"nat"[]{};'"m";"add"[]{'"n";'"k"}} }
interactive nuprl_bijection_restriction :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "lt"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "biject"[]{"int_seg"[]{"number"[0:n]{};'"k"};"int_seg"[]{"number"[0:n]{};'"k"};'"f"} } -->
sequent { <H> >- "equal"[]{"int"[]{};('"f" "sub"[]{'"k";"number"[1:n]{}});"sub"[]{'"k";"number"[1:n]{}}} } -->
sequent { <H> >- "guard"[]{"and"[]{('"f" in "fun"[]{"int_seg"[]{"number"[0:n]{};"sub"[]{'"k";"number"[1:n]{}}};""."int_seg"[]{"number"[0:n]{};"sub"[]{'"k";"number"[1:n]{}}}});"biject"[]{"int_seg"[]{"number"[0:n]{};"sub"[]{'"k";"number"[1:n]{}}};"int_seg"[]{"number"[0:n]{};"sub"[]{'"k";"number"[1:n]{}}};'"f"}}} }
define unfold_primrec : "primrec"[]{'"n";'"b";'"c"} <-->
(("ycomb"[]{} "lambda"[]{"primrec"."lambda"[]{"n"."ifthenelse"[]{"beq_int"[]{'"n";"number"[0:n]{}};'"b";(('"c" "sub"[]{'"n";"number"[1:n]{}}) ('"primrec" "sub"[]{'"n";"number"[1:n]{}}))}}}) '"n")
interactive nuprl_primrec_wf {| intro[] |} :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"b" in '"T" } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"};"x1": '"T" >- '"c" '"x" '"x1" in '"T" } -->
sequent { <H> >- ("primrec"[]{'"n";'"b";'"c"} in '"T") }
interactive nuprl_primrec_add :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H> >- '"b" in '"T" } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};"add"[]{'"n";'"m"}};"x1": '"T" >- '"c" '"x" '"x1" in '"T" } -->
sequent { <H> >- "equal"[]{'"T";"primrec"[]{"add"[]{'"n";'"m"};'"b";'"c"};"primrec"[]{'"n";"primrec"[]{'"m";'"b";'"c"};"lambda"[]{"i"."lambda"[]{"t".(('"c" "add"[]{'"i";'"m"}) '"t")}}}} }
define unfold_nondecreasing : "nondecreasing"[]{'"f";'"k"} <-->
"all"[]{"int_seg"[]{"number"[0:n]{};"sub"[]{'"k";"number"[1:n]{}}};"i"."le"[]{('"f" '"i");('"f" "add"[]{'"i";"number"[1:n]{}})}}
interactive nuprl_nondecreasing_wf {| intro[] |} :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f" '"x" in "int"[]{} } -->
sequent { <H> >- ("nondecreasing"[]{'"f";'"k"} in "univ"[level:l]{}) }
interactive nuprl_const_nondecreasing :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"x" in "int"[]{} } -->
sequent { <H> >- "nondecreasing"[]{"lambda"[]{"i".'"x"};'"k"} }
define unfold_fadd : "fadd"[]{'"f";'"g"} <-->
"lambda"[]{"i"."add"[]{('"f" '"i");('"g" '"i")}}
interactive nuprl_fadd_wf {| intro[] |} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"g" '"x" in "int_seg"[]{"number"[0:n]{};"add"[]{'"k";"number"[1:n]{}}} } -->
sequent { <H> >- ("fadd"[]{'"f";'"g"} in "fun"[]{"int_seg"[]{"number"[0:n]{};'"n"};""."int_seg"[]{"number"[0:n]{};"add"[]{'"m";'"k"}}}) }
interactive nuprl_fadd_increasing :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f" '"x" in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"g" '"x" in "int"[]{} } -->
sequent { <H> >- "increasing"[]{'"f";'"n"} } -->
sequent { <H> >- "nondecreasing"[]{'"g";'"n"} } -->
sequent { <H> >- "increasing"[]{"fadd"[]{'"f";'"g"};'"n"} }
define unfold_fshift : "fshift"[]{'"f";'"x"} <-->
"lambda"[]{"i"."ifthenelse"[]{"beq_int"[]{'"i";"number"[0:n]{}};'"x";('"f" "sub"[]{'"i";"number"[1:n]{}})}}
interactive nuprl_fshift_wf {| intro[] |} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
[wf] sequent { <H> >- '"x" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- ("fshift"[]{'"f";'"x"} in "fun"[]{"int_seg"[]{"number"[0:n]{};"add"[]{'"n";"number"[1:n]{}}};""."int_seg"[]{"number"[0:n]{};'"k"}}) }
interactive nuprl_fshift_increasing :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"x" in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f" '"x" in "int"[]{} } -->
sequent { <H> >- "increasing"[]{'"f";'"n"} } -->
sequent { <H> >- "lt"[]{"number"[0:n]{};'"n"} } -->
sequent { <H> >- "lt"[]{'"x";('"f" "number"[0:n]{})} } -->
sequent { <H> >- "increasing"[]{"fshift"[]{'"f";'"x"};"add"[]{'"n";"number"[1:n]{}}} }
define unfold_finite : "finite"[]{'"T"} <-->
"all"[]{"fun"[]{'"T";"".'"T"};"f"."implies"[]{"inject"[]{'"T";'"T";'"f"};"surject"[]{'"T";'"T";'"f"}}}
interactive nuprl_finite_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
sequent { <H> >- ("finite"[]{'"T"} in "univ"[level:l]{}) }
interactive nuprl_nsub_finite :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
sequent { <H> >- "finite"[]{"int_seg"[]{"number"[0:n]{};'"n"}} }
define unfold_fappend : "fappend"[]{'"f";'"n";'"x"} <-->
"lambda"[]{"i"."ifthenelse"[]{"beq_int"[]{'"i";'"n"};'"x";('"f" '"i")}}
interactive nuprl_fappend_wf {| intro[] |} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
[wf] sequent { <H> >- '"x" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
sequent { <H> >- ("fappend"[]{'"f";'"n";'"x"} in "fun"[]{"int_seg"[]{"number"[0:n]{};"add"[]{'"n";"number"[1:n]{}}};""."int_seg"[]{"number"[0:n]{};'"m"}}) }
interactive nuprl_increasing_split :
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"m"} >- "type"{'"P" '"x" } } -->
sequent { <H>; "i": "int_seg"[]{"number"[0:n]{};'"m"} >- "decidable"[]{('"P" '"i")} } -->
sequent { <H> >- "exists"[]{"nat"[]{};"n"."exists"[]{"nat"[]{};"k"."exists"[]{"fun"[]{"int_seg"[]{"number"[0:n]{};'"n"};""."int_seg"[]{"number"[0:n]{};'"m"}};"f"."exists"[]{"fun"[]{"int_seg"[]{"number"[0:n]{};'"k"};""."int_seg"[]{"number"[0:n]{};'"m"}};"g"."and"[]{"increasing"[]{'"f";'"n"};"and"[]{"increasing"[]{'"g";'"k"};"and"[]{"all"[]{"int_seg"[]{"number"[0:n]{};'"n"};"i".('"P" ('"f" '"i"))};"and"[]{"all"[]{"int_seg"[]{"number"[0:n]{};'"k"};"j"."not"[]{('"P" ('"g" '"j"))}};"all"[]{"int_seg"[]{"number"[0:n]{};'"m"};"i"."or"[]{"exists"[]{"int_seg"[]{"number"[0:n]{};'"n"};"j"."equal"[]{"int"[]{};'"i";('"f" '"j")}};"exists"[]{"int_seg"[]{"number"[0:n]{};'"k"};"j"."equal"[]{"int"[]{};'"i";('"g" '"j")}}}}}}}}}}}} }
define unfold_sum : "sum"[]{'"k";"x".'"f"['"x"]} <-->
"primrec"[]{'"k";"number"[0:n]{};"lambda"[]{"x"."lambda"[]{"n"."add"[]{'"n";'"f"['"x"]}}}}
interactive nuprl_sum_wf {| intro[] |} '"n" "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
sequent { <H> >- ("sum"[]{'"n";"x".'"f"['"x"]} in "int"[]{}) }
interactive nuprl_non_neg_sum '"n" "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"n"} >- "le"[]{"number"[0:n]{};'"f"['"x"]} } -->
sequent { <H> >- "le"[]{"number"[0:n]{};"sum"[]{'"n";"x".'"f"['"x"]}} }
interactive nuprl_sum_linear '"n" "lambda"[]{"x".'"g"['"x"]} "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"g"['"x"] in "int"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"add"[]{"sum"[]{'"n";"x".'"f"['"x"]};"sum"[]{'"n";"x".'"g"['"x"]}};"sum"[]{'"n";"x"."add"[]{'"f"['"x"];'"g"['"x"]}}} }
interactive nuprl_sum_scalar_mult '"n" "lambda"[]{"x".'"f"['"x"]} '"a" :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H> >- '"a" in "int"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"mul"[]{'"a";"sum"[]{'"n";"x".'"f"['"x"]}};"sum"[]{'"n";"x"."mul"[]{'"a";'"f"['"x"]}}} }
interactive nuprl_sum_constant :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"a" in "int"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"a"};"mul"[]{'"a";'"n"}} }
interactive nuprl_sum_functionality '"n" "lambda"[]{"x".'"g"['"x"]} "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"g"['"x"] in "int"[]{} } -->
sequent { <H>; "i": "int_seg"[]{"number"[0:n]{};'"n"} >- "equal"[]{"int"[]{};'"f"['"i"];'"g"['"i"]} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"f"['"x"]};"sum"[]{'"n";"x".'"g"['"x"]}} }
interactive nuprl_sum_difference '"n" '"d" "lambda"[]{"x".'"g"['"x"]} "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"g"['"x"] in "int"[]{} } -->
[wf] sequent { <H> >- '"d" in "int"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x"."sub"[]{'"f"['"x"];'"g"['"x"]}};'"d"} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"f"['"x"]};"add"[]{"sum"[]{'"n";"x".'"g"['"x"]};'"d"}} }
interactive nuprl_sum_le '"k" "lambda"[]{"x".'"g"['"x"]} "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"g"['"x"] in "int"[]{} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"k"} >- "le"[]{'"f"['"x"];'"g"['"x"]} } -->
sequent { <H> >- "le"[]{"sum"[]{'"k";"x".'"f"['"x"]};"sum"[]{'"k";"x".'"g"['"x"]}} }
interactive nuprl_sum_bound '"k" '"b" "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"b" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f"['"x"] in "int"[]{} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"k"} >- "le"[]{'"f"['"x"];'"b"} } -->
sequent { <H> >- "le"[]{"sum"[]{'"k";"x".'"f"['"x"]};"mul"[]{'"b";'"k"}} }
interactive nuprl_sum_lower_bound '"k" "lambda"[]{"x".'"f"['"x"]} '"b" :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"b" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f"['"x"] in "int"[]{} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"k"} >- "le"[]{'"b";'"f"['"x"]} } -->
sequent { <H> >- "le"[]{"mul"[]{'"b";'"k"};"sum"[]{'"k";"x".'"f"['"x"]}} }
interactive nuprl_sum__ite '"k" "lambda"[]{"x".'"g"['"x"]} "lambda"[]{"x".'"f"['"x"]} "lambda"[]{"x".'"p"['"x"]} :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"g"['"x"] in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"p"['"x"] in "bool"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"k";"i"."ifthenelse"[]{'"p"['"i"];"add"[]{'"f"['"i"];'"g"['"i"]};'"f"['"i"]}};"add"[]{"sum"[]{'"k";"i".'"f"['"i"]};"sum"[]{'"k";"i"."ifthenelse"[]{'"p"['"i"];'"g"['"i"];"number"[0:n]{}}}}} }
interactive nuprl_sum_arith1 :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"a" in "int"[]{} } -->
[wf] sequent { <H> >- '"b" in "int"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"mul"[]{"sum"[]{'"n";"i"."add"[]{'"a";"mul"[]{'"b";'"i"}}};"number"[2:n]{}};"mul"[]{'"n";"add"[]{'"a";"add"[]{'"a";"mul"[]{'"b";"sub"[]{'"n";"number"[1:n]{}}}}}}} }
interactive nuprl_sum_arith :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"a" in "int"[]{} } -->
[wf] sequent { <H> >- '"b" in "int"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"i"."add"[]{'"a";"mul"[]{'"b";'"i"}}};"div"[]{"mul"[]{'"n";"add"[]{'"a";"add"[]{'"a";"mul"[]{'"b";"sub"[]{'"n";"number"[1:n]{}}}}}};"number"[2:n]{}}} }
interactive nuprl_finite__partition :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"c" '"x" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "exists"[]{"fun"[]{"int_seg"[]{"number"[0:n]{};'"k"};""."list"[]{"nat"[]{}}};"p"."and"[]{"equal"[]{"int"[]{};"sum"[]{'"k";"j"."length"[]{('"p" '"j")}};'"n"};"and"[]{"all"[]{"int_seg"[]{"number"[0:n]{};'"k"};"j"."all"[]{"int_seg"[]{"number"[0:n]{};"length"[]{('"p" '"j")}};"x"."all"[]{"int_seg"[]{"number"[0:n]{};"length"[]{('"p" '"j")}};"y"."implies"[]{"lt"[]{'"x";'"y"};"gt"[]{"select"[]{'"x";('"p" '"j")};"select"[]{'"y";('"p" '"j")}}}}}};"all"[]{"int_seg"[]{"number"[0:n]{};'"k"};"j"."all"[]{"int_seg"[]{"number"[0:n]{};"length"[]{('"p" '"j")}};"x"."cand"[]{"lt"[]{"select"[]{'"x";('"p" '"j")};'"n"};"equal"[]{"int"[]{};('"c" "select"[]{'"x";('"p" '"j")});'"j"}}}}}}} }
interactive nuprl_pigeon__hole '"f" :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
sequent { <H> >- "inject"[]{"int_seg"[]{"number"[0:n]{};'"n"};"int_seg"[]{"number"[0:n]{};'"m"};'"f"} } -->
sequent { <H> >- "le"[]{'"n";'"m"} }
interactive nuprl_isolate_summand '"n" '"m" "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H> >- '"m" in "int_seg"[]{"number"[0:n]{};'"n"} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"f"['"x"]};"add"[]{'"f"['"m"];"sum"[]{'"n";"x"."ifthenelse"[]{"beq_int"[]{'"x";'"m"};"number"[0:n]{};'"f"['"x"]}}}} }
interactive nuprl_empty_support '"n" "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"n"} >- "equal"[]{"int"[]{};'"f"['"x"];"number"[0:n]{}} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"f"['"x"]};"number"[0:n]{}} }
interactive nuprl_singleton_support_sum '"n" "lambda"[]{"x".'"f"['"x"]} '"m" :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H> >- '"m" in "int_seg"[]{"number"[0:n]{};'"n"} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"n"} ; "not"[]{"equal"[]{"int"[]{};'"x";'"m"}} >- "equal"[]{"int"[]{};'"f"['"x"];"number"[0:n]{}} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"f"['"x"]};'"f"['"m"]} }
interactive nuprl_pair_support '"n" '"k" '"m" "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H> >- '"m" in "int_seg"[]{"number"[0:n]{};'"n"} } -->
[wf] sequent { <H> >- '"k" in "int_seg"[]{"number"[0:n]{};'"n"} } -->
sequent { <H> >- "not"[]{"equal"[]{"int"[]{};'"m";'"k"}} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"n"} ; "not"[]{"equal"[]{"int"[]{};'"x";'"m"}} ; "not"[]{"equal"[]{"int"[]{};'"x";'"k"}} >- "equal"[]{"int"[]{};'"f"['"x"];"number"[0:n]{}} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"f"['"x"]};"add"[]{'"f"['"m"];'"f"['"k"]}} }
interactive nuprl_sum_split '"n" '"m" "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H> >- '"m" in "int_seg"[]{"number"[0:n]{};"add"[]{'"n";"number"[1:n]{}}} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"f"['"x"]};"add"[]{"sum"[]{'"m";"x".'"f"['"x"]};"sum"[]{"sub"[]{'"n";'"m"};"x".'"f"["add"[]{'"x";'"m"}]}}} }
define unfold_double_sum : "double_sum"[]{'"n";'"m";"x", "y".'"f"['"x";'"y"]} <-->
"sum"[]{'"n";"x"."sum"[]{'"m";"y".'"f"['"x";'"y"]}}
interactive nuprl_double_sum_wf {| intro[] |} '"m" '"n" "lambda"[]{"x1", "x".'"f"['"x1";'"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"};"x1": "int_seg"[]{"number"[0:n]{};'"m"} >- '"f"['"x";'"x1"] in "int"[]{} } -->
sequent { <H> >- ("double_sum"[]{'"n";'"m";"x", "y".'"f"['"x";'"y"]} in "int"[]{}) }
interactive nuprl_pair_support_double_sum '"m" '"n" '"y2" '"y1" '"x2" '"x1" "lambda"[]{"x1", "x".'"f"['"x1";'"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"};"x1": "int_seg"[]{"number"[0:n]{};'"m"} >- '"f"['"x";'"x1"] in "int"[]{} } -->
[wf] sequent { <H> >- '"x1" in "int_seg"[]{"number"[0:n]{};'"n"} } -->
[wf] sequent { <H> >- '"x2" in "int_seg"[]{"number"[0:n]{};'"n"} } -->
[wf] sequent { <H> >- '"y1" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
[wf] sequent { <H> >- '"y2" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
sequent { <H> >- "or"[]{"not"[]{"equal"[]{"int"[]{};'"x1";'"x2"}};"not"[]{"equal"[]{"int"[]{};'"y1";'"y2"}}} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"n"} ; "y": "int_seg"[]{"number"[0:n]{};'"m"} ; "not"[]{"and"[]{"equal"[]{"int"[]{};'"x";'"x1"};"equal"[]{"int"[]{};'"y";'"y1"}}} ; "not"[]{"and"[]{"equal"[]{"int"[]{};'"x";'"x2"};"equal"[]{"int"[]{};'"y";'"y2"}}} >- "equal"[]{"int"[]{};'"f"['"x";'"y"];"number"[0:n]{}} } -->
sequent { <H> >- "equal"[]{"int"[]{};"double_sum"[]{'"n";'"m";"x", "y".'"f"['"x";'"y"]};"add"[]{'"f"['"x1";'"y1"];'"f"['"x2";'"y2"]}} }
interactive nuprl_double_sum_difference '"m" '"n" '"d" "lambda"[]{"x1", "x".'"g"['"x1";'"x"]} "lambda"[]{"x1", "x".'"f"['"x1";'"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"};"x1": "int_seg"[]{"number"[0:n]{};'"m"} >- '"f"['"x";'"x1"] in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"};"x1": "int_seg"[]{"number"[0:n]{};'"m"} >- '"g"['"x";'"x1"] in "int"[]{} } -->
[wf] sequent { <H> >- '"d" in "int"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"double_sum"[]{'"n";'"m";"x", "y"."sub"[]{'"f"['"x";'"y"];'"g"['"x";'"y"]}};'"d"} } -->
sequent { <H> >- "equal"[]{"int"[]{};"double_sum"[]{'"n";'"m";"x", "y".'"f"['"x";'"y"]};"add"[]{"double_sum"[]{'"n";'"m";"x", "y".'"g"['"x";'"y"]};'"d"}} }
interactive nuprl_double_sum_functionality '"m" '"n" "lambda"[]{"x1", "x".'"g"['"x1";'"x"]} "lambda"[]{"x1", "x".'"f"['"x1";'"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"};"x1": "int_seg"[]{"number"[0:n]{};'"m"} >- '"f"['"x";'"x1"] in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"};"x1": "int_seg"[]{"number"[0:n]{};'"m"} >- '"g"['"x";'"x1"] in "int"[]{} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"n"} ; "y": "int_seg"[]{"number"[0:n]{};'"m"} >- "equal"[]{"int"[]{};'"f"['"x";'"y"];'"g"['"x";'"y"]} } -->
sequent { <H> >- "equal"[]{"int"[]{};"double_sum"[]{'"n";'"m";"x", "y".'"f"['"x";'"y"]};"double_sum"[]{'"n";'"m";"x", "y".'"g"['"x";'"y"]}} }
define unfold_rel_exp : "rel_exp"[]{'"T";'"R";'"n"} <-->
(("ycomb"[]{} "lambda"[]{"rel_exp"."lambda"[]{"n"."ifthenelse"[]{"beq_int"[]{'"n";"number"[0:n]{}};"lambda"[]{"x"."lambda"[]{"y"."equal"[]{'"T";'"x";'"y"}}};"lambda"[]{"x"."lambda"[]{"y"."exists"[]{'"T";"z"."and"[]{"infix_ap"[]{'"R";'"x";'"z"};"infix_ap"[]{('"rel_exp" "sub"[]{'"n";"number"[1:n]{}});'"z";'"y"}}}}}}}}) '"n")
interactive nuprl_rel_exp_wf {| intro[] |} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R" '"x" '"x1" in "univ"[level:l]{} } -->
sequent { <H> >- ("rel_exp"[]{'"T";'"R";'"n"} in "fun"[]{'"T";""."fun"[]{'"T";""."univ"[level:l]{}}}) }
interactive nuprl_decidable__rel_exp :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"};"x1": "int_seg"[]{"number"[0:n]{};'"n"} >- "type"{'"R" '"x" '"x1" } } -->
sequent { <H>; "i": "int_seg"[]{"number"[0:n]{};'"n"} ; "j": "int_seg"[]{"number"[0:n]{};'"n"} >- "decidable"[]{"infix_ap"[]{'"R";'"i";'"j"}} } -->
[wf] sequent { <H> >- '"i" in "int_seg"[]{"number"[0:n]{};'"n"} } -->
[wf] sequent { <H> >- '"j" in "int_seg"[]{"number"[0:n]{};'"n"} } -->
sequent { <H> >- "decidable"[]{"infix_ap"[]{"rel_exp"[]{"int_seg"[]{"number"[0:n]{};'"n"};'"R";'"k"};'"i";'"j"}} }
interactive nuprl_rel_exp_add '"y" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
[wf] sequent { <H> >- '"z" in '"T" } -->
sequent { <H> >- "infix_ap"[]{"rel_exp"[]{'"T";'"R";'"m"};'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{"rel_exp"[]{'"T";'"R";'"n"};'"y";'"z"} } -->
sequent { <H> >- "infix_ap"[]{"rel_exp"[]{'"T";'"R";"add"[]{'"m";'"n"}};'"x";'"z"} }
define unfold_rel_implies : "rel_implies"[]{'"T";'"R1";'"R2"} <-->
"all"[]{'"T";"x"."all"[]{'"T";"y"."implies"[]{"infix_ap"[]{'"R1";'"x";'"y"};"infix_ap"[]{'"R2";'"x";'"y"}}}}
interactive nuprl_rel_implies_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R1" '"x" '"x1" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R2" '"x" '"x1" in "univ"[level:l]{} } -->
sequent { <H> >- ("rel_implies"[]{'"T";'"R1";'"R2"} in "univ"[level:l]{}) }
interactive nuprl_rel_exp_monotone :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "rel_implies"[]{'"T";'"R1";'"R2"} } -->
sequent { <H> >- "rel_implies"[]{'"T";"rel_exp"[]{'"T";'"R1";'"n"};"rel_exp"[]{'"T";'"R2";'"n"}} }
define unfold_preserved_by : "preserved_by"[]{'"T";'"R";'"P"} <-->
"all"[]{'"T";"x"."all"[]{'"T";"y"."implies"[]{('"P" '"x");"implies"[]{"infix_ap"[]{'"R";'"x";'"y"};('"P" '"y")}}}}
interactive nuprl_preserved_by_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"P" '"x" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R" '"x" '"x1" in "univ"[level:l]{} } -->
sequent { <H> >- ("preserved_by"[]{'"T";'"R";'"P"} in "univ"[level:l]{}) }
interactive nuprl_preserved_by_monotone '"R2" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H>; "x": '"T" ; "y": '"T" ; "infix_ap"[]{'"R1";'"x";'"y"} >- "infix_ap"[]{'"R2";'"x";'"y"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R2";'"P"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R1";'"P"} }
define unfold_cond_rel_implies : "cond_rel_implies"[]{'"T";'"P";'"R1";'"R2"} <-->
"all"[]{'"T";"x"."all"[]{'"T";"y"."implies"[]{('"P" '"x");"implies"[]{"infix_ap"[]{'"R1";'"x";'"y"};"infix_ap"[]{'"R2";'"x";'"y"}}}}}
interactive nuprl_cond_rel_implies_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"P" '"x" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R1" '"x" '"x1" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R2" '"x" '"x1" in "univ"[level:l]{} } -->
sequent { <H> >- ("cond_rel_implies"[]{'"T";'"P";'"R1";'"R2"} in "univ"[level:l]{}) }
interactive nuprl_cond_rel_exp_monotone :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "cond_rel_implies"[]{'"T";'"P";'"R1";'"R2"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R1";'"P"} } -->
sequent { <H> >- "cond_rel_implies"[]{'"T";'"P";"rel_exp"[]{'"T";'"R1";'"n"};"rel_exp"[]{'"T";'"R2";'"n"}} }
define unfold_rel_star : "rel_star"[]{'"T";'"R"} <-->
"lambda"[]{"x"."lambda"[]{"y"."exists"[]{"nat"[]{};"n"."infix_ap"[]{"rel_exp"[]{'"T";'"R";'"n"};'"x";'"y"}}}}
interactive nuprl_rel_star_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R" '"x" '"x1" in "univ"[level:l]{} } -->
sequent { <H> >- ("rel_star"[]{'"T";'"R"} in "fun"[]{'"T";""."fun"[]{'"T";""."univ"[level:l]{}}}) }
interactive nuprl_rel_star_monotone :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "rel_implies"[]{'"T";'"R1";'"R2"} } -->
sequent { <H> >- "rel_implies"[]{'"T";"rel_star"[]{'"T";'"R1"};"rel_star"[]{'"T";'"R2"}} }
interactive nuprl_cond_rel_star_monotone :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "cond_rel_implies"[]{'"T";'"P";'"R1";'"R2"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R1";'"P"} } -->
sequent { <H> >- "cond_rel_implies"[]{'"T";'"P";"rel_star"[]{'"T";'"R1"};"rel_star"[]{'"T";'"R2"}} }
interactive nuprl_rel_star_transitivity '"y" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
[wf] sequent { <H> >- '"z" in '"T" } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"y";'"z"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"z"} }
interactive nuprl_rel_star_monotonic '"R1" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- "rel_implies"[]{'"T";'"R1";'"R2"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R1"};'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R2"};'"x";'"y"} }
interactive nuprl_cond_rel_star_monotonic '"R1" '"P" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "cond_rel_implies"[]{'"T";'"P";'"R1";'"R2"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R1";'"P"} } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- ('"P" '"x") } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R1"};'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R2"};'"x";'"y"} }
interactive nuprl_preserved_by_star :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R";'"P"} } -->
sequent { <H> >- "preserved_by"[]{'"T";"rel_star"[]{'"T";'"R"};'"P"} }
interactive nuprl_rel_star_closure '"T" "lambda"[]{"x1", "x".'"R2"['"x1";'"x"]} '"R" '"y" '"x" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2"['"x";'"x1"] } } -->
sequent { <H> >- "trans"[]{'"T";"_1", "_2".'"R2"['"_1";'"_2"]} } -->
sequent { <H>; "x": '"T" ; "y": '"T" ; "infix_ap"[]{'"R";'"x";'"y"} >- "infix_ap"[]{"lambda"[]{"x1"."lambda"[]{"x".'"R2"['"x1";'"x"]}};'"x";'"y"} } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"y"} } -->
sequent { <H> >- "or"[]{"infix_ap"[]{"lambda"[]{"x1"."lambda"[]{"x".'"R2"['"x1";'"x"]}};'"x";'"y"};"equal"[]{'"T";'"x";'"y"}} }
interactive nuprl_rel_star_closure2 '"T" "lambda"[]{"x1", "x".'"R2"['"x1";'"x"]} '"R" '"y" '"x" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2"['"x";'"x1"] } } -->
sequent { <H> >- "refl"[]{'"T";"_1", "_2".'"R2"['"_1";'"_2"]} } -->
sequent { <H> >- "trans"[]{'"T";"_1", "_2".'"R2"['"_1";'"_2"]} } -->
sequent { <H>; "x": '"T" ; "y": '"T" ; "infix_ap"[]{'"R";'"x";'"y"} >- '"R2"['"x";'"y"] } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"y"} } -->
sequent { <H> >- '"R2"['"x";'"y"] }
interactive nuprl_rel_star_of_equiv '"T" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"E" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- "equiv_rel"[]{'"T";"_1", "_2"."infix_ap"[]{'"E";'"_1";'"_2"}} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"E"};'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{'"E";'"x";'"y"} }
interactive nuprl_cond_rel_star_equiv :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"E" '"x" '"x1" } } -->
sequent { <H> >- "equiv_rel"[]{'"T";"_1", "_2"."infix_ap"[]{'"E";'"_1";'"_2"}} } -->
sequent { <H> >- "cond_rel_implies"[]{'"T";'"P";'"R1";'"E"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R1";'"P"} } -->
sequent { <H> >- "cond_rel_implies"[]{'"T";'"P";"rel_star"[]{'"T";'"R1"};'"E"} }
interactive nuprl_rel_rel_star :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- "infix_ap"[]{'"R";'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"y"} }
interactive nuprl_rel_star_trans '"y" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
[wf] sequent { <H> >- '"z" in '"T" } -->
sequent { <H> >- "infix_ap"[]{'"R";'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"y";'"z"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"z"} }
interactive nuprl_rel_star_weakening :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
sequent { <H> >- "equal"[]{'"T";'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"y"} }
define unfold_rel_inverse : "rel_inverse"[]{'"R"} <-->
"lambda"[]{"x"."lambda"[]{"y"."infix_ap"[]{'"R";'"y";'"x"}}}
interactive nuprl_rel_inverse_wf {| intro[] |} :
[wf] sequent { <H> >- '"T1" in "univ"[level:l]{} } -->
[wf] sequent { <H> >- '"T2" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T1";"x1": '"T2" >- '"R" '"x" '"x1" in "univ"[level:l]{} } -->
sequent { <H> >- ("rel_inverse"[]{'"R"} in "fun"[]{'"T2";""."fun"[]{'"T1";""."univ"[level:l]{}}}) }
interactive nuprl_rel_inverse_exp :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- "iff"[]{"infix_ap"[]{"rel_inverse"[]{"rel_exp"[]{'"T";'"R";'"n"}};'"x";'"y"};"infix_ap"[]{"rel_exp"[]{'"T";"rel_inverse"[]{'"R"};'"n"};'"x";'"y"}} }
interactive nuprl_rel_inverse_star :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- "iff"[]{"infix_ap"[]{"rel_inverse"[]{"rel_star"[]{'"T";'"R"}};'"x";'"y"};"infix_ap"[]{"rel_star"[]{'"T";"rel_inverse"[]{'"R"}};'"x";'"y"}} }
interactive nuprl_rel_star_symmetric :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
sequent { <H> >- "sym"[]{'"T";"x", "y"."infix_ap"[]{'"R";'"x";'"y"}} } -->
sequent { <H> >- "sym"[]{'"T";"x", "y"."infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"y"}} }
interactive nuprl_rel_star_symmetric_2 :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- "sym"[]{'"T";"x", "y"."infix_ap"[]{'"R";'"x";'"y"}} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"y";'"x"} }
interactive nuprl_preserved_by_symmetric :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
sequent { <H> >- "sym"[]{'"T";"x", "y"."infix_ap"[]{'"R";'"x";'"y"}} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R";'"P"} } -->
sequent { <H> >- "preserved_by"[]{'"T";"rel_inverse"[]{'"R"};'"P"} }
define unfold_rel_or : "rel_or"[]{'"R1";'"R2"} <-->
"lambda"[]{"x"."lambda"[]{"y"."or"[]{"infix_ap"[]{'"R1";'"x";'"y"};"infix_ap"[]{'"R2";'"x";'"y"}}}}
interactive nuprl_rel_or_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R1" '"x" '"x1" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R2" '"x" '"x1" in "univ"[level:l]{} } -->
sequent { <H> >- ("rel_or"[]{'"R1";'"R2"} in "fun"[]{'"T";""."fun"[]{'"T";""."univ"[level:l]{}}}) }
interactive nuprl_rel_implies_or_left :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "rel_implies"[]{'"T";'"R1";"rel_or"[]{'"R1";'"R2"}} }
interactive nuprl_rel_implies_or_right :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "rel_implies"[]{'"T";'"R2";"rel_or"[]{'"R1";'"R2"}} }
interactive nuprl_symmetric_rel_or :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "sym"[]{'"T";"x", "y"."infix_ap"[]{'"R1";'"x";'"y"}} } -->
sequent { <H> >- "sym"[]{'"T";"x", "y"."infix_ap"[]{'"R2";'"x";'"y"}} } -->
sequent { <H> >- "sym"[]{'"T";"x", "y"."infix_ap"[]{"rel_or"[]{'"R1";'"R2"};'"x";'"y"}} }
interactive nuprl_preserved_by_or :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R1";'"P"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R2";'"P"} } -->
sequent { <H> >- "preserved_by"[]{'"T";"rel_or"[]{'"R1";'"R2"};'"P"} }
define unfold_as_strong : "as_strong"[]{'"T";'"Q";'"P"} <-->
"all"[]{'"T";"x"."implies"[]{('"P" '"x");('"Q" '"x")}}
interactive nuprl_as_strong_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"Q" '"x" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"P" '"x" in "univ"[level:l]{} } -->
sequent { <H> >- ("as_strong"[]{'"T";'"Q";'"P"} in "univ"[level:l]{}) }
interactive nuprl_as_strong_transitivity '"Q" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"Q" '"x" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"R" '"x" } } -->
sequent { <H> >- "as_strong"[]{'"T";'"Q";'"P"} } -->
sequent { <H> >- "as_strong"[]{'"T";'"R";'"Q"} } -->
sequent { <H> >- "as_strong"[]{'"T";'"R";'"P"} }
define unfold_fun_exp : "fun_exp"[]{'"f";'"n"} <-->
"primrec"[]{'"n";"lambda"[]{"x".'"x"};"lambda"[]{"i"."lambda"[]{"g"."compose"[]{'"f";'"g"}}}}
interactive nuprl_fun_exp_wf {| intro[] |} :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"f" '"x" in '"T" } -->
sequent { <H> >- ("fun_exp"[]{'"f";'"n"} in "fun"[]{'"T";"".'"T"}) }
interactive nuprl_comb_for_fun_exp_wf :
sequent { <H> >- ("lambda"[]{"T"."lambda"[]{"n"."lambda"[]{"f"."lambda"[]{"z"."fun_exp"[]{'"f";'"n"}}}}} in "fun"[]{"univ"[level:l]{};"T"."fun"[]{"nat"[]{};"n"."fun"[]{"fun"[]{'"T";"".'"T"};"f"."fun"[]{"squash"[]{"true"[]{}};""."fun"[]{'"T";"".'"T"}}}}}) }
interactive nuprl_fun_exp_compose :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"h" '"x" in '"T" } -->
[wf] sequent { <H>;"x": '"T" >- '"f" '"x" in '"T" } -->
sequent { <H> >- "equal"[]{"fun"[]{'"T";"".'"T"};"compose"[]{"fun_exp"[]{'"f";'"n"};'"h"};"primrec"[]{'"n";'"h";"lambda"[]{"i"."lambda"[]{"g"."compose"[]{'"f";'"g"}}}}} }
interactive nuprl_fun_exp_add :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"f" '"x" in '"T" } -->
sequent { <H> >- "equal"[]{"fun"[]{'"T";"".'"T"};"fun_exp"[]{'"f";"add"[]{'"n";'"m"}};"compose"[]{"fun_exp"[]{'"f";'"n"};"fun_exp"[]{'"f";'"m"}}} }
interactive nuprl_fun_exp_add1 :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- '"f" '"x" in '"T" } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
sequent { <H> >- "equal"[]{'"T";('"f" ("fun_exp"[]{'"f";'"n"} '"x"));("fun_exp"[]{'"f";"add"[]{'"n";"number"[1:n]{}}} '"x")} }
interactive nuprl_fun_exp_add1_sub :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- '"f" '"x" in '"T" } -->
[wf] sequent { <H> >- '"n" in "nat_plus"[]{} } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
sequent { <H> >- "equal"[]{'"T";('"f" ("fun_exp"[]{'"f";"sub"[]{'"n";"number"[1:n]{}}} '"x"));("fun_exp"[]{'"f";'"n"} '"x")} }
interactive nuprl_iteration_terminates '"m" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- '"f" '"x" in '"T" } -->
[wf] sequent { <H>;"x": '"T" >- '"m" '"x" in "nat"[]{} } -->
sequent { <H>; "x": '"T" >- "and"[]{"le"[]{('"m" ('"f" '"x"));('"m" '"x")};"implies"[]{"equal"[]{"int"[]{};('"m" ('"f" '"x"));('"m" '"x")};"equal"[]{'"T";('"f" '"x");'"x"}}} } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
sequent { <H> >- "exists"[]{"nat"[]{};"n"."equal"[]{'"T";('"f" ("fun_exp"[]{'"f";'"n"} '"x"));("fun_exp"[]{'"f";'"n"} '"x")}} }
define unfold_flip : "flip"[]{'"i";'"j"} <-->
"lambda"[]{"x"."ifthenelse"[]{"beq_int"[]{'"x";'"i"};'"j";"ifthenelse"[]{"beq_int"[]{'"x";'"j"};'"i";'"x"}}}
interactive nuprl_flip_wf {| intro[] |} :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"i" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
[wf] sequent { <H> >- '"j" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- ("flip"[]{'"i";'"j"} in "fun"[]{"int_seg"[]{"number"[0:n]{};'"k"};""."int_seg"[]{"number"[0:n]{};'"k"}}) }
interactive nuprl_sum_switch '"n" '"i" "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H> >- '"i" in "int_seg"[]{"number"[0:n]{};"sub"[]{'"n";"number"[1:n]{}}} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"f"[("flip"[]{'"i";"add"[]{'"i";"number"[1:n]{}}} '"x")]};"sum"[]{'"n";"x".'"f"['"x"]}} }
interactive nuprl_flip_symmetry :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"i" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
[wf] sequent { <H> >- '"j" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "equal"[]{"fun"[]{"int_seg"[]{"number"[0:n]{};'"k"};""."int_seg"[]{"number"[0:n]{};'"k"}};"flip"[]{'"i";'"j"};"flip"[]{'"j";'"i"}} }
interactive nuprl_flip_bijection :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"i" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
[wf] sequent { <H> >- '"j" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "biject"[]{"int_seg"[]{"number"[0:n]{};'"k"};"int_seg"[]{"number"[0:n]{};'"k"};"flip"[]{'"i";'"j"}} }
interactive nuprl_flip_inverse :
[wf] sequent { <H> >- '"k" in "int"[]{} } -->
[wf] sequent { <H> >- '"x" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
[wf] sequent { <H> >- '"y" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "equal"[]{"fun"[]{"int_seg"[]{"number"[0:n]{};'"k"};""."int_seg"[]{"number"[0:n]{};'"k"}};"compose"[]{"flip"[]{'"y";'"x"};"flip"[]{'"y";'"x"}};"lambda"[]{"x".'"x"}} }
interactive nuprl_flip_twice '"k" :
[wf] sequent { <H> >- '"k" in "int"[]{} } -->
[wf] sequent { <H> >- '"x" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
[wf] sequent { <H> >- '"y" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
[wf] sequent { <H> >- '"i" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "equal"[]{"int"[]{};("flip"[]{'"y";'"x"} ("flip"[]{'"y";'"x"} '"i"));'"i"} }
define unfold_search : "search"[]{'"k";'"P"} <-->
"primrec"[]{'"k";"number"[0:n]{};"lambda"[]{"i"."lambda"[]{"j"."ifthenelse"[]{"lt_bool"[]{"number"[0:n]{};'"j"};'"j";"ifthenelse"[]{('"P" '"i");"add"[]{'"i";"number"[1:n]{}};"number"[0:n]{}}}}}}
interactive nuprl_search_wf {| intro[] |} :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"P" '"x" in "bool"[]{} } -->
sequent { <H> >- ("search"[]{'"k";'"P"} in "int_seg"[]{"number"[0:n]{};"add"[]{'"k";"number"[1:n]{}}}) }
interactive nuprl_search_property :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"P" '"x" in "bool"[]{} } -->
sequent { <H> >- "and"[]{"iff"[]{"exists"[]{"int_seg"[]{"number"[0:n]{};'"k"};"i"."assert"[]{('"P" '"i")}};"lt"[]{"number"[0:n]{};"search"[]{'"k";'"P"}}};"implies"[]{"lt"[]{"number"[0:n]{};"search"[]{'"k";'"P"}};"and"[]{"assert"[]{('"P" "sub"[]{"search"[]{'"k";'"P"};"number"[1:n]{}})};"all"[]{"int_seg"[]{"number"[0:n]{};'"k"};"j"."implies"[]{"lt"[]{'"j";"sub"[]{"search"[]{'"k";'"P"};"number"[1:n]{}}};"not"[]{"assert"[]{('"P" '"j")}}}}}}} }
interactive nuprl_search_succ :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};"add"[]{'"k";"number"[1:n]{}}} >- '"P" '"x" in "bool"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"search"[]{"add"[]{'"k";"number"[1:n]{}};'"P"};"ifthenelse"[]{('"P" "number"[0:n]{});"number"[1:n]{};"ifthenelse"[]{"lt_bool"[]{"number"[0:n]{};"search"[]{'"k";"lambda"[]{"i".('"P" "add"[]{'"i";"number"[1:n]{}})}}};"add"[]{"search"[]{'"k";"lambda"[]{"i".('"P" "add"[]{'"i";"number"[1:n]{}})}};"number"[1:n]{}};"number"[0:n]{}}}} }
define unfold_prop_and : "prop_and"[]{'"P";'"Q"} <-->
"lambda"[]{"L"."and"[]{('"P" '"L");('"Q" '"L")}}
interactive nuprl_prop_and_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"P" '"x" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"Q" '"x" in "univ"[level:l]{} } -->
sequent { <H> >- ("prop_and"[]{'"P";'"Q"} in "fun"[]{'"T";""."univ"[level:l]{}}) }
interactive nuprl_and_preserved_by :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"Q" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R";'"P"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R";'"Q"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R";"prop_and"[]{'"P";'"Q"}} }
define unfold_preserved_by2 : "preserved_by2"[]{'"T";'"R";'"P"} <-->
"all"[]{'"T";"x"."all"[]{'"T";"y"."all"[]{'"T";"z"."implies"[]{('"P" '"x");"implies"[]{('"P" '"y");"implies"[]{((('"R" '"x") '"y") '"z");('"P" '"z")}}}}}}
interactive nuprl_preserved_by2_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"P" '"x" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T";"x2": '"T" >- '"R" '"x" '"x1" '"x2" in "univ"[level:l]{} } -->
sequent { <H> >- ("preserved_by2"[]{'"T";'"R";'"P"} in "univ"[level:l]{}) }
interactive nuprl_and_preserved_by2 :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"Q" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T";"x2": '"T" >- "type"{'"R" '"x" '"x1" '"x2" } } -->
sequent { <H> >- "preserved_by2"[]{'"T";'"R";'"P"} } -->
sequent { <H> >- "preserved_by2"[]{'"T";'"R";'"Q"} } -->
sequent { <H> >- "preserved_by2"[]{'"T";'"R";"prop_and"[]{'"P";'"Q"}} }
(**** display forms ****)
dform nuprl_primrec_df : except_mode[src] :: "primrec"[]{'"n";'"b";'"c"} =
`"primrec(" slot{'"n"} `";" slot{'"b"} `";" slot{'"c"} `")"
dform nuprl_nondecreasing_df : except_mode[src] :: "nondecreasing"[]{'"f";'"k"} =
`"nondecreasing(" slot{'"f"} `";" slot{'"k"} `")"
dform nuprl_fadd_df : except_mode[src] :: "fadd"[]{'"f";'"g"} =
`"fadd(" slot{'"f"} `";" slot{'"g"} `")"
dform nuprl_fshift_df : except_mode[src] :: "fshift"[]{'"f";'"x"} =
`"fshift(" slot{'"f"} `";" slot{'"x"} `")"
dform nuprl_finite_df : except_mode[src] :: "finite"[]{'"T"} =
`"finite(" slot{'"T"} `")"
dform nuprl_fappend_df : except_mode[src] :: "fappend"[]{'"f";'"n";'"x"} =
`"" slot{'"f"} `"[" slot{'"n"} `":=" slot{'"x"} `"]"
dform nuprl_sum_df : except_mode[src] :: "sum"[]{'"k";"x".'"f"} =
`"sum(" slot{'"k"} `";" slot{'"x"} `"." slot{'"f"} `")"
dform nuprl_sum_df : except_mode[src] :: "sum"[]{'"k";"x".'"f"} =
`"sum(" slot{'"f"} `" | " slot{'"x"} `" < " slot{'"k"} `")"
dform nuprl_double_sum_df : except_mode[src] :: "double_sum"[]{'"n";'"m";"x", "y".'"f"} =
`"double_sum(" slot{'"n"} `";" slot{'"m"} `";" slot{'"x"} `"," slot{'"y"} `"."
slot{'"f"} `")"
dform nuprl_double_sum_df : except_mode[src] :: "double_sum"[]{'"n";'"m";"x", "y".'"f"} =
`"sum(" slot{'"f"} `" | " slot{'"x"} `" < " slot{'"n"} `"; " slot{'"y"} `" < "
slot{'"m"} `")"
dform nuprl_rel_exp_df1 : except_mode[src] :: "rel_exp"[]{'"T";'"R";'"n"} =
`"rel_exp(" slot{'"T"} `";" slot{'"R"} `";" slot{'"n"} `")"
dform nuprl_rel_exp_df : except_mode[src] :: "rel_exp"[]{'"T";'"R";'"n"} =
`"rel_exp(" slot{'"T"} `";" slot{'"R"} `";" slot{'"n"} `")"
dform nuprl_rel_exp_df : except_mode[src] :: "rel_exp"[]{'"T";'"R";'"n"} =
`"" slot{'"R"} `"" `"" `"" `"" slot{'"n"} `"" `"" `""
dform nuprl_rel_exp_df : except_mode[src] :: "rel_exp"[]{'"T";'"R";'"n"} =
`"" slot{'"R"} `"^" `"" slot{'"n"} `""
dform nuprl_rel_implies_df : except_mode[src] :: "rel_implies"[]{'"T";'"R1";'"R2"} =
`"rel_implies(" slot{'"T"} `";" slot{'"R1"} `";" slot{'"R2"} `")"
dform nuprl_rel_implies_df : except_mode[src] :: "rel_implies"[]{'"T";'"R1";'"R2"} =
`"" slot{'"R1"} `" => " slot{'"R2"} `""
dform nuprl_preserved_by_df : except_mode[src] :: "preserved_by"[]{'"T";'"R";'"P"} =
`"preserved_by(" slot{'"T"} `";" slot{'"R"} `";" slot{'"P"} `")"
dform nuprl_preserved_by_df : except_mode[src] :: "preserved_by"[]{'"T";'"R";'"P"} =
`"" slot{'"R"} `" preserves " slot{'"P"} `""
dform nuprl_cond_rel_implies_df : except_mode[src] :: "cond_rel_implies"[]{'"T";'"P";'"R1";'"R2"} =
`"cond_rel_implies(" slot{'"T"} `";" slot{'"P"} `";" slot{'"R1"} `";"
slot{'"R2"} `")"
dform nuprl_cond_rel_implies_df : except_mode[src] :: "cond_rel_implies"[]{'"T";'"P";'"R1";'"R2"} =
`"when " slot{'"P"} `", " slot{'"R1"} `" => " slot{'"R2"} `""
dform nuprl_rel_star_df : except_mode[src] :: "rel_star"[]{'"T";'"R"} =
`"rel_star(" slot{'"T"} `";" slot{'"R"} `")"
dform nuprl_rel_star_df : except_mode[src] :: "rel_star"[]{'"T";'"R"} =
`"" slot{'"R"} `"" `"" `"" `"*" `"" `"" `""
dform nuprl_rel_star_df : except_mode[src] :: "rel_star"[]{'"T";'"R"} =
`"" slot{'"R"} `"^*"
dform nuprl_rel_inverse_df : except_mode[src] :: "rel_inverse"[]{'"R"} =
`"rel_inverse(" slot{'"R"} `")"
dform nuprl_rel_inverse_df : except_mode[src] :: "rel_inverse"[]{'"R"} =
`"" slot{'"R"} `"^-1"
dform nuprl_rel_or_df : except_mode[src] :: "rel_or"[]{'"R1";'"R2"} =
`"rel_or(" slot{'"R1"} `";" slot{'"R2"} `")"
dform nuprl_rel_or_df : except_mode[src] :: "rel_or"[]{'"P";'"Q"} =
`"" szone `"" slot{'"P"} `"" sbreak[""," "] `"" vee `" " pushm[0:n] `"" slot{'"Q"}
`"" popm `"" ezone `""
dform nuprl_rel_or_df : except_mode[src] :: "rel_or"[]{'"P";'"#"} =
`"" szone `"" pushm[0:n] `"" slot{'"P"} `"" popm `"" sbreak[""," "] `"" vee `" "
slot{'"#"} `"" ezone `""
dform nuprl_rel_or_df : except_mode[src] :: "rel_or"[]{'"P";'"Q"} =
`"" pushm[0:n] `"" slot{'"P"} `"" popm `"" sbreak[""," "] `"" vee `" " pushm[0:n]
`"" slot{'"Q"} `"" popm `""
dform nuprl_rel_or_df : except_mode[src] :: "rel_or"[]{'"P";'"#"} =
`"" pushm[0:n] `"" slot{'"P"} `"" popm `"" sbreak[""," "] `"" vee `" " slot{'"#"}
`""
dform nuprl_as_strong_df : except_mode[src] :: "as_strong"[]{'"T";'"Q";'"P"} =
`"as_strong(" slot{'"T"} `";" slot{'"Q"} `";" slot{'"P"} `")"
dform nuprl_as_strong_df : except_mode[src] :: "as_strong"[]{'"T";'"Q";'"P"} =
`"" szone `"" pushm[0:n] `"" slot{'"P"} `"" sbreak[""," "] `"as strong as"
sbreak[""," "] `"" slot{'"Q"} `"" popm ezone `" "
dform nuprl_fun_exp_df : except_mode[src] :: "fun_exp"[]{'"f";'"n"} =
`"fun_exp(" slot{'"f"} `";" slot{'"n"} `")"
dform nuprl_fun_exp_df : except_mode[src] :: "fun_exp"[]{'"f";'"n"} =
`"" slot{'"f"} `"^" slot{'"n"} `""
dform nuprl_flip_df : except_mode[src] :: "flip"[]{'"i";'"j"} =
`"flip(" slot{'"i"} `";" slot{'"j"} `")"
dform nuprl_flip_df : except_mode[src] :: "flip"[]{'"i";'"j"} =
`"(" slot{'"i"} `", " slot{'"j"} `")"
dform nuprl_search_df : except_mode[src] :: "search"[]{'"k";'"P"} =
`"search(" slot{'"k"} `";" slot{'"P"} `")"
dform nuprl_prop_and_df : except_mode[src] :: "prop_and"[]{'"P";'"Q"} =
`"" szone `"" slot{'"P"} `"" sbreak[""," "] `"" wedge `" " pushm[0:n] `"" slot{'"Q"}
`"" popm `"" ezone `""
dform nuprl_prop_and_df : except_mode[src] :: "prop_and"[]{'"P";'"#"} =
`"" szone `"" pushm[0:n] `"" slot{'"P"} `"" popm `"" sbreak[""," "] `"" wedge `" "
slot{'"#"} `"" ezone `""
dform nuprl_prop_and_df : except_mode[src] :: "prop_and"[]{'"P";'"Q"} =
`"" pushm[0:n] `"" slot{'"P"} `"" popm `"" sbreak[""," "] `"" wedge `" " pushm[0:n]
`"" slot{'"Q"} `"" popm `""
dform nuprl_prop_and_df : except_mode[src] :: "prop_and"[]{'"P";'"#"} =
`"" pushm[0:n] `"" slot{'"P"} `"" popm `"" sbreak[""," "] `"" wedge `" " slot{'"#"}
`""
dform nuprl_preserved_by2_df : except_mode[src] :: "preserved_by2"[]{'"T";'"R";'"P"} =
`"preserved_by2(" slot{'"T"} `";" slot{'"R"} `";" slot{'"P"} `")"
dform nuprl_preserved_by2_df : except_mode[src] :: "preserved_by2"[]{'"T";'"R";'"P"} =
`"(ternary) " slot{'"R"} `" preserves " slot{'"P"} `" "
| null | https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/theories/mesa/nuprl_nat_extra.ml | ocaml | *** display forms *** | extends Ma_tree_1
open Dtactic
interactive nuprl_id_increasing :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
sequent { <H> >- "increasing"[]{"lambda"[]{"i".'"i"};'"k"} }
interactive nuprl_increasing_implies :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f" '"x" in "int"[]{} } -->
sequent { <H> >- "increasing"[]{'"f";'"k"} } -->
sequent { <H> >- "guard"[]{"all"[]{"int_seg"[]{"number"[0:n]{};'"k"};"x"."all"[]{"int_seg"[]{"number"[0:n]{};'"k"};"y"."implies"[]{"lt"[]{'"x";'"y"};"lt"[]{('"f" '"x");('"f" '"y")}}}}} }
interactive nuprl_increasing_implies_le :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f" '"x" in "int"[]{} } -->
sequent { <H> >- "increasing"[]{'"f";'"k"} } -->
sequent { <H> >- "guard"[]{"all"[]{"int_seg"[]{"number"[0:n]{};'"k"};"x"."all"[]{"int_seg"[]{"number"[0:n]{};'"k"};"y"."implies"[]{"le"[]{'"x";'"y"};"le"[]{('"f" '"x");('"f" '"y")}}}}} }
interactive nuprl_compose_increasing '"m" :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"m"} >- '"g" '"x" in "int"[]{} } -->
sequent { <H> >- "increasing"[]{'"f";'"k"} } -->
sequent { <H> >- "increasing"[]{'"g";'"m"} } -->
sequent { <H> >- "increasing"[]{"compose"[]{'"g";'"f"};'"k"} }
interactive nuprl_increasing_inj :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
sequent { <H> >- "increasing"[]{'"f";'"k"} } -->
sequent { <H> >- "inject"[]{"int_seg"[]{"number"[0:n]{};'"k"};"int_seg"[]{"number"[0:n]{};'"m"};'"f"} }
interactive nuprl_increasing_le :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
sequent { <H> >- "exists"[]{"fun"[]{"int_seg"[]{"number"[0:n]{};'"k"};""."int_seg"[]{"number"[0:n]{};'"m"}};"f"."increasing"[]{'"f";'"k"}} } -->
sequent { <H> >- "le"[]{'"k";'"m"} }
interactive nuprl_increasing_is_id '"k" :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "increasing"[]{'"f";'"k"} } -->
[wf] sequent { <H> >- '"i" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "equal"[]{"int"[]{};('"f" '"i");'"i"} }
interactive nuprl_increasing_lower_bound '"k" :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f" '"x" in "int"[]{} } -->
[wf] sequent { <H> >- '"x" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "increasing"[]{'"f";'"k"} } -->
sequent { <H> >- "le"[]{"add"[]{('"f" "number"[0:n]{});'"x"};('"f" '"x")} }
interactive nuprl_injection_le :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
sequent { <H> >- "exists"[]{"fun"[]{"int_seg"[]{"number"[0:n]{};'"k"};""."int_seg"[]{"number"[0:n]{};'"m"}};"f"."inject"[]{"int_seg"[]{"number"[0:n]{};'"k"};"int_seg"[]{"number"[0:n]{};'"m"};'"f"}} } -->
sequent { <H> >- "le"[]{'"k";'"m"} }
interactive nuprl_disjoint_increasing_onto '"f" '"g" :
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"g" '"x" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
sequent { <H> >- "increasing"[]{'"f";'"n"} } -->
sequent { <H> >- "increasing"[]{'"g";'"k"} } -->
sequent { <H>; "i": "int_seg"[]{"number"[0:n]{};'"m"} >- "or"[]{"exists"[]{"int_seg"[]{"number"[0:n]{};'"n"};"j"."equal"[]{"int"[]{};'"i";('"f" '"j")}};"exists"[]{"int_seg"[]{"number"[0:n]{};'"k"};"j"."equal"[]{"int"[]{};'"i";('"g" '"j")}}} } -->
sequent { <H>; "j1": "int_seg"[]{"number"[0:n]{};'"n"} ; "j2": "int_seg"[]{"number"[0:n]{};'"k"} >- "not"[]{"equal"[]{"int"[]{};('"f" '"j1");('"g" '"j2")}} } -->
sequent { <H> >- "equal"[]{"nat"[]{};'"m";"add"[]{'"n";'"k"}} }
interactive nuprl_bijection_restriction :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "lt"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "biject"[]{"int_seg"[]{"number"[0:n]{};'"k"};"int_seg"[]{"number"[0:n]{};'"k"};'"f"} } -->
sequent { <H> >- "equal"[]{"int"[]{};('"f" "sub"[]{'"k";"number"[1:n]{}});"sub"[]{'"k";"number"[1:n]{}}} } -->
sequent { <H> >- "guard"[]{"and"[]{('"f" in "fun"[]{"int_seg"[]{"number"[0:n]{};"sub"[]{'"k";"number"[1:n]{}}};""."int_seg"[]{"number"[0:n]{};"sub"[]{'"k";"number"[1:n]{}}}});"biject"[]{"int_seg"[]{"number"[0:n]{};"sub"[]{'"k";"number"[1:n]{}}};"int_seg"[]{"number"[0:n]{};"sub"[]{'"k";"number"[1:n]{}}};'"f"}}} }
define unfold_primrec : "primrec"[]{'"n";'"b";'"c"} <-->
(("ycomb"[]{} "lambda"[]{"primrec"."lambda"[]{"n"."ifthenelse"[]{"beq_int"[]{'"n";"number"[0:n]{}};'"b";(('"c" "sub"[]{'"n";"number"[1:n]{}}) ('"primrec" "sub"[]{'"n";"number"[1:n]{}}))}}}) '"n")
interactive nuprl_primrec_wf {| intro[] |} :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"b" in '"T" } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"};"x1": '"T" >- '"c" '"x" '"x1" in '"T" } -->
sequent { <H> >- ("primrec"[]{'"n";'"b";'"c"} in '"T") }
interactive nuprl_primrec_add :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H> >- '"b" in '"T" } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};"add"[]{'"n";'"m"}};"x1": '"T" >- '"c" '"x" '"x1" in '"T" } -->
sequent { <H> >- "equal"[]{'"T";"primrec"[]{"add"[]{'"n";'"m"};'"b";'"c"};"primrec"[]{'"n";"primrec"[]{'"m";'"b";'"c"};"lambda"[]{"i"."lambda"[]{"t".(('"c" "add"[]{'"i";'"m"}) '"t")}}}} }
define unfold_nondecreasing : "nondecreasing"[]{'"f";'"k"} <-->
"all"[]{"int_seg"[]{"number"[0:n]{};"sub"[]{'"k";"number"[1:n]{}}};"i"."le"[]{('"f" '"i");('"f" "add"[]{'"i";"number"[1:n]{}})}}
interactive nuprl_nondecreasing_wf {| intro[] |} :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f" '"x" in "int"[]{} } -->
sequent { <H> >- ("nondecreasing"[]{'"f";'"k"} in "univ"[level:l]{}) }
interactive nuprl_const_nondecreasing :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"x" in "int"[]{} } -->
sequent { <H> >- "nondecreasing"[]{"lambda"[]{"i".'"x"};'"k"} }
define unfold_fadd : "fadd"[]{'"f";'"g"} <-->
"lambda"[]{"i"."add"[]{('"f" '"i");('"g" '"i")}}
interactive nuprl_fadd_wf {| intro[] |} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"g" '"x" in "int_seg"[]{"number"[0:n]{};"add"[]{'"k";"number"[1:n]{}}} } -->
sequent { <H> >- ("fadd"[]{'"f";'"g"} in "fun"[]{"int_seg"[]{"number"[0:n]{};'"n"};""."int_seg"[]{"number"[0:n]{};"add"[]{'"m";'"k"}}}) }
interactive nuprl_fadd_increasing :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f" '"x" in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"g" '"x" in "int"[]{} } -->
sequent { <H> >- "increasing"[]{'"f";'"n"} } -->
sequent { <H> >- "nondecreasing"[]{'"g";'"n"} } -->
sequent { <H> >- "increasing"[]{"fadd"[]{'"f";'"g"};'"n"} }
define unfold_fshift : "fshift"[]{'"f";'"x"} <-->
"lambda"[]{"i"."ifthenelse"[]{"beq_int"[]{'"i";"number"[0:n]{}};'"x";('"f" "sub"[]{'"i";"number"[1:n]{}})}}
interactive nuprl_fshift_wf {| intro[] |} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
[wf] sequent { <H> >- '"x" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- ("fshift"[]{'"f";'"x"} in "fun"[]{"int_seg"[]{"number"[0:n]{};"add"[]{'"n";"number"[1:n]{}}};""."int_seg"[]{"number"[0:n]{};'"k"}}) }
interactive nuprl_fshift_increasing :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"x" in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f" '"x" in "int"[]{} } -->
sequent { <H> >- "increasing"[]{'"f";'"n"} } -->
sequent { <H> >- "lt"[]{"number"[0:n]{};'"n"} } -->
sequent { <H> >- "lt"[]{'"x";('"f" "number"[0:n]{})} } -->
sequent { <H> >- "increasing"[]{"fshift"[]{'"f";'"x"};"add"[]{'"n";"number"[1:n]{}}} }
define unfold_finite : "finite"[]{'"T"} <-->
"all"[]{"fun"[]{'"T";"".'"T"};"f"."implies"[]{"inject"[]{'"T";'"T";'"f"};"surject"[]{'"T";'"T";'"f"}}}
interactive nuprl_finite_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
sequent { <H> >- ("finite"[]{'"T"} in "univ"[level:l]{}) }
interactive nuprl_nsub_finite :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
sequent { <H> >- "finite"[]{"int_seg"[]{"number"[0:n]{};'"n"}} }
define unfold_fappend : "fappend"[]{'"f";'"n";'"x"} <-->
"lambda"[]{"i"."ifthenelse"[]{"beq_int"[]{'"i";'"n"};'"x";('"f" '"i")}}
interactive nuprl_fappend_wf {| intro[] |} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
[wf] sequent { <H> >- '"x" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
sequent { <H> >- ("fappend"[]{'"f";'"n";'"x"} in "fun"[]{"int_seg"[]{"number"[0:n]{};"add"[]{'"n";"number"[1:n]{}}};""."int_seg"[]{"number"[0:n]{};'"m"}}) }
interactive nuprl_increasing_split :
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"m"} >- "type"{'"P" '"x" } } -->
sequent { <H>; "i": "int_seg"[]{"number"[0:n]{};'"m"} >- "decidable"[]{('"P" '"i")} } -->
sequent { <H> >- "exists"[]{"nat"[]{};"n"."exists"[]{"nat"[]{};"k"."exists"[]{"fun"[]{"int_seg"[]{"number"[0:n]{};'"n"};""."int_seg"[]{"number"[0:n]{};'"m"}};"f"."exists"[]{"fun"[]{"int_seg"[]{"number"[0:n]{};'"k"};""."int_seg"[]{"number"[0:n]{};'"m"}};"g"."and"[]{"increasing"[]{'"f";'"n"};"and"[]{"increasing"[]{'"g";'"k"};"and"[]{"all"[]{"int_seg"[]{"number"[0:n]{};'"n"};"i".('"P" ('"f" '"i"))};"and"[]{"all"[]{"int_seg"[]{"number"[0:n]{};'"k"};"j"."not"[]{('"P" ('"g" '"j"))}};"all"[]{"int_seg"[]{"number"[0:n]{};'"m"};"i"."or"[]{"exists"[]{"int_seg"[]{"number"[0:n]{};'"n"};"j"."equal"[]{"int"[]{};'"i";('"f" '"j")}};"exists"[]{"int_seg"[]{"number"[0:n]{};'"k"};"j"."equal"[]{"int"[]{};'"i";('"g" '"j")}}}}}}}}}}}} }
define unfold_sum : "sum"[]{'"k";"x".'"f"['"x"]} <-->
"primrec"[]{'"k";"number"[0:n]{};"lambda"[]{"x"."lambda"[]{"n"."add"[]{'"n";'"f"['"x"]}}}}
interactive nuprl_sum_wf {| intro[] |} '"n" "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
sequent { <H> >- ("sum"[]{'"n";"x".'"f"['"x"]} in "int"[]{}) }
interactive nuprl_non_neg_sum '"n" "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"n"} >- "le"[]{"number"[0:n]{};'"f"['"x"]} } -->
sequent { <H> >- "le"[]{"number"[0:n]{};"sum"[]{'"n";"x".'"f"['"x"]}} }
interactive nuprl_sum_linear '"n" "lambda"[]{"x".'"g"['"x"]} "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"g"['"x"] in "int"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"add"[]{"sum"[]{'"n";"x".'"f"['"x"]};"sum"[]{'"n";"x".'"g"['"x"]}};"sum"[]{'"n";"x"."add"[]{'"f"['"x"];'"g"['"x"]}}} }
interactive nuprl_sum_scalar_mult '"n" "lambda"[]{"x".'"f"['"x"]} '"a" :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H> >- '"a" in "int"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"mul"[]{'"a";"sum"[]{'"n";"x".'"f"['"x"]}};"sum"[]{'"n";"x"."mul"[]{'"a";'"f"['"x"]}}} }
interactive nuprl_sum_constant :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"a" in "int"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"a"};"mul"[]{'"a";'"n"}} }
interactive nuprl_sum_functionality '"n" "lambda"[]{"x".'"g"['"x"]} "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"g"['"x"] in "int"[]{} } -->
sequent { <H>; "i": "int_seg"[]{"number"[0:n]{};'"n"} >- "equal"[]{"int"[]{};'"f"['"i"];'"g"['"i"]} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"f"['"x"]};"sum"[]{'"n";"x".'"g"['"x"]}} }
interactive nuprl_sum_difference '"n" '"d" "lambda"[]{"x".'"g"['"x"]} "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"g"['"x"] in "int"[]{} } -->
[wf] sequent { <H> >- '"d" in "int"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x"."sub"[]{'"f"['"x"];'"g"['"x"]}};'"d"} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"f"['"x"]};"add"[]{"sum"[]{'"n";"x".'"g"['"x"]};'"d"}} }
interactive nuprl_sum_le '"k" "lambda"[]{"x".'"g"['"x"]} "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"g"['"x"] in "int"[]{} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"k"} >- "le"[]{'"f"['"x"];'"g"['"x"]} } -->
sequent { <H> >- "le"[]{"sum"[]{'"k";"x".'"f"['"x"]};"sum"[]{'"k";"x".'"g"['"x"]}} }
interactive nuprl_sum_bound '"k" '"b" "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"b" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f"['"x"] in "int"[]{} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"k"} >- "le"[]{'"f"['"x"];'"b"} } -->
sequent { <H> >- "le"[]{"sum"[]{'"k";"x".'"f"['"x"]};"mul"[]{'"b";'"k"}} }
interactive nuprl_sum_lower_bound '"k" "lambda"[]{"x".'"f"['"x"]} '"b" :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"b" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f"['"x"] in "int"[]{} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"k"} >- "le"[]{'"b";'"f"['"x"]} } -->
sequent { <H> >- "le"[]{"mul"[]{'"b";'"k"};"sum"[]{'"k";"x".'"f"['"x"]}} }
interactive nuprl_sum__ite '"k" "lambda"[]{"x".'"g"['"x"]} "lambda"[]{"x".'"f"['"x"]} "lambda"[]{"x".'"p"['"x"]} :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"g"['"x"] in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"p"['"x"] in "bool"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"k";"i"."ifthenelse"[]{'"p"['"i"];"add"[]{'"f"['"i"];'"g"['"i"]};'"f"['"i"]}};"add"[]{"sum"[]{'"k";"i".'"f"['"i"]};"sum"[]{'"k";"i"."ifthenelse"[]{'"p"['"i"];'"g"['"i"];"number"[0:n]{}}}}} }
interactive nuprl_sum_arith1 :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"a" in "int"[]{} } -->
[wf] sequent { <H> >- '"b" in "int"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"mul"[]{"sum"[]{'"n";"i"."add"[]{'"a";"mul"[]{'"b";'"i"}}};"number"[2:n]{}};"mul"[]{'"n";"add"[]{'"a";"add"[]{'"a";"mul"[]{'"b";"sub"[]{'"n";"number"[1:n]{}}}}}}} }
interactive nuprl_sum_arith :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"a" in "int"[]{} } -->
[wf] sequent { <H> >- '"b" in "int"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"i"."add"[]{'"a";"mul"[]{'"b";'"i"}}};"div"[]{"mul"[]{'"n";"add"[]{'"a";"add"[]{'"a";"mul"[]{'"b";"sub"[]{'"n";"number"[1:n]{}}}}}};"number"[2:n]{}}} }
interactive nuprl_finite__partition :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"c" '"x" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "exists"[]{"fun"[]{"int_seg"[]{"number"[0:n]{};'"k"};""."list"[]{"nat"[]{}}};"p"."and"[]{"equal"[]{"int"[]{};"sum"[]{'"k";"j"."length"[]{('"p" '"j")}};'"n"};"and"[]{"all"[]{"int_seg"[]{"number"[0:n]{};'"k"};"j"."all"[]{"int_seg"[]{"number"[0:n]{};"length"[]{('"p" '"j")}};"x"."all"[]{"int_seg"[]{"number"[0:n]{};"length"[]{('"p" '"j")}};"y"."implies"[]{"lt"[]{'"x";'"y"};"gt"[]{"select"[]{'"x";('"p" '"j")};"select"[]{'"y";('"p" '"j")}}}}}};"all"[]{"int_seg"[]{"number"[0:n]{};'"k"};"j"."all"[]{"int_seg"[]{"number"[0:n]{};"length"[]{('"p" '"j")}};"x"."cand"[]{"lt"[]{"select"[]{'"x";('"p" '"j")};'"n"};"equal"[]{"int"[]{};('"c" "select"[]{'"x";('"p" '"j")});'"j"}}}}}}} }
interactive nuprl_pigeon__hole '"f" :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f" '"x" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
sequent { <H> >- "inject"[]{"int_seg"[]{"number"[0:n]{};'"n"};"int_seg"[]{"number"[0:n]{};'"m"};'"f"} } -->
sequent { <H> >- "le"[]{'"n";'"m"} }
interactive nuprl_isolate_summand '"n" '"m" "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H> >- '"m" in "int_seg"[]{"number"[0:n]{};'"n"} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"f"['"x"]};"add"[]{'"f"['"m"];"sum"[]{'"n";"x"."ifthenelse"[]{"beq_int"[]{'"x";'"m"};"number"[0:n]{};'"f"['"x"]}}}} }
interactive nuprl_empty_support '"n" "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"n"} >- "equal"[]{"int"[]{};'"f"['"x"];"number"[0:n]{}} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"f"['"x"]};"number"[0:n]{}} }
interactive nuprl_singleton_support_sum '"n" "lambda"[]{"x".'"f"['"x"]} '"m" :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H> >- '"m" in "int_seg"[]{"number"[0:n]{};'"n"} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"n"} ; "not"[]{"equal"[]{"int"[]{};'"x";'"m"}} >- "equal"[]{"int"[]{};'"f"['"x"];"number"[0:n]{}} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"f"['"x"]};'"f"['"m"]} }
interactive nuprl_pair_support '"n" '"k" '"m" "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H> >- '"m" in "int_seg"[]{"number"[0:n]{};'"n"} } -->
[wf] sequent { <H> >- '"k" in "int_seg"[]{"number"[0:n]{};'"n"} } -->
sequent { <H> >- "not"[]{"equal"[]{"int"[]{};'"m";'"k"}} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"n"} ; "not"[]{"equal"[]{"int"[]{};'"x";'"m"}} ; "not"[]{"equal"[]{"int"[]{};'"x";'"k"}} >- "equal"[]{"int"[]{};'"f"['"x"];"number"[0:n]{}} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"f"['"x"]};"add"[]{'"f"['"m"];'"f"['"k"]}} }
interactive nuprl_sum_split '"n" '"m" "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H> >- '"m" in "int_seg"[]{"number"[0:n]{};"add"[]{'"n";"number"[1:n]{}}} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"f"['"x"]};"add"[]{"sum"[]{'"m";"x".'"f"['"x"]};"sum"[]{"sub"[]{'"n";'"m"};"x".'"f"["add"[]{'"x";'"m"}]}}} }
define unfold_double_sum : "double_sum"[]{'"n";'"m";"x", "y".'"f"['"x";'"y"]} <-->
"sum"[]{'"n";"x"."sum"[]{'"m";"y".'"f"['"x";'"y"]}}
interactive nuprl_double_sum_wf {| intro[] |} '"m" '"n" "lambda"[]{"x1", "x".'"f"['"x1";'"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"};"x1": "int_seg"[]{"number"[0:n]{};'"m"} >- '"f"['"x";'"x1"] in "int"[]{} } -->
sequent { <H> >- ("double_sum"[]{'"n";'"m";"x", "y".'"f"['"x";'"y"]} in "int"[]{}) }
interactive nuprl_pair_support_double_sum '"m" '"n" '"y2" '"y1" '"x2" '"x1" "lambda"[]{"x1", "x".'"f"['"x1";'"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"};"x1": "int_seg"[]{"number"[0:n]{};'"m"} >- '"f"['"x";'"x1"] in "int"[]{} } -->
[wf] sequent { <H> >- '"x1" in "int_seg"[]{"number"[0:n]{};'"n"} } -->
[wf] sequent { <H> >- '"x2" in "int_seg"[]{"number"[0:n]{};'"n"} } -->
[wf] sequent { <H> >- '"y1" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
[wf] sequent { <H> >- '"y2" in "int_seg"[]{"number"[0:n]{};'"m"} } -->
sequent { <H> >- "or"[]{"not"[]{"equal"[]{"int"[]{};'"x1";'"x2"}};"not"[]{"equal"[]{"int"[]{};'"y1";'"y2"}}} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"n"} ; "y": "int_seg"[]{"number"[0:n]{};'"m"} ; "not"[]{"and"[]{"equal"[]{"int"[]{};'"x";'"x1"};"equal"[]{"int"[]{};'"y";'"y1"}}} ; "not"[]{"and"[]{"equal"[]{"int"[]{};'"x";'"x2"};"equal"[]{"int"[]{};'"y";'"y2"}}} >- "equal"[]{"int"[]{};'"f"['"x";'"y"];"number"[0:n]{}} } -->
sequent { <H> >- "equal"[]{"int"[]{};"double_sum"[]{'"n";'"m";"x", "y".'"f"['"x";'"y"]};"add"[]{'"f"['"x1";'"y1"];'"f"['"x2";'"y2"]}} }
interactive nuprl_double_sum_difference '"m" '"n" '"d" "lambda"[]{"x1", "x".'"g"['"x1";'"x"]} "lambda"[]{"x1", "x".'"f"['"x1";'"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"};"x1": "int_seg"[]{"number"[0:n]{};'"m"} >- '"f"['"x";'"x1"] in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"};"x1": "int_seg"[]{"number"[0:n]{};'"m"} >- '"g"['"x";'"x1"] in "int"[]{} } -->
[wf] sequent { <H> >- '"d" in "int"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"double_sum"[]{'"n";'"m";"x", "y"."sub"[]{'"f"['"x";'"y"];'"g"['"x";'"y"]}};'"d"} } -->
sequent { <H> >- "equal"[]{"int"[]{};"double_sum"[]{'"n";'"m";"x", "y".'"f"['"x";'"y"]};"add"[]{"double_sum"[]{'"n";'"m";"x", "y".'"g"['"x";'"y"]};'"d"}} }
interactive nuprl_double_sum_functionality '"m" '"n" "lambda"[]{"x1", "x".'"g"['"x1";'"x"]} "lambda"[]{"x1", "x".'"f"['"x1";'"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"};"x1": "int_seg"[]{"number"[0:n]{};'"m"} >- '"f"['"x";'"x1"] in "int"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"};"x1": "int_seg"[]{"number"[0:n]{};'"m"} >- '"g"['"x";'"x1"] in "int"[]{} } -->
sequent { <H>; "x": "int_seg"[]{"number"[0:n]{};'"n"} ; "y": "int_seg"[]{"number"[0:n]{};'"m"} >- "equal"[]{"int"[]{};'"f"['"x";'"y"];'"g"['"x";'"y"]} } -->
sequent { <H> >- "equal"[]{"int"[]{};"double_sum"[]{'"n";'"m";"x", "y".'"f"['"x";'"y"]};"double_sum"[]{'"n";'"m";"x", "y".'"g"['"x";'"y"]}} }
define unfold_rel_exp : "rel_exp"[]{'"T";'"R";'"n"} <-->
(("ycomb"[]{} "lambda"[]{"rel_exp"."lambda"[]{"n"."ifthenelse"[]{"beq_int"[]{'"n";"number"[0:n]{}};"lambda"[]{"x"."lambda"[]{"y"."equal"[]{'"T";'"x";'"y"}}};"lambda"[]{"x"."lambda"[]{"y"."exists"[]{'"T";"z"."and"[]{"infix_ap"[]{'"R";'"x";'"z"};"infix_ap"[]{('"rel_exp" "sub"[]{'"n";"number"[1:n]{}});'"z";'"y"}}}}}}}}) '"n")
interactive nuprl_rel_exp_wf {| intro[] |} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R" '"x" '"x1" in "univ"[level:l]{} } -->
sequent { <H> >- ("rel_exp"[]{'"T";'"R";'"n"} in "fun"[]{'"T";""."fun"[]{'"T";""."univ"[level:l]{}}}) }
interactive nuprl_decidable__rel_exp :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"};"x1": "int_seg"[]{"number"[0:n]{};'"n"} >- "type"{'"R" '"x" '"x1" } } -->
sequent { <H>; "i": "int_seg"[]{"number"[0:n]{};'"n"} ; "j": "int_seg"[]{"number"[0:n]{};'"n"} >- "decidable"[]{"infix_ap"[]{'"R";'"i";'"j"}} } -->
[wf] sequent { <H> >- '"i" in "int_seg"[]{"number"[0:n]{};'"n"} } -->
[wf] sequent { <H> >- '"j" in "int_seg"[]{"number"[0:n]{};'"n"} } -->
sequent { <H> >- "decidable"[]{"infix_ap"[]{"rel_exp"[]{"int_seg"[]{"number"[0:n]{};'"n"};'"R";'"k"};'"i";'"j"}} }
interactive nuprl_rel_exp_add '"y" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
[wf] sequent { <H> >- '"z" in '"T" } -->
sequent { <H> >- "infix_ap"[]{"rel_exp"[]{'"T";'"R";'"m"};'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{"rel_exp"[]{'"T";'"R";'"n"};'"y";'"z"} } -->
sequent { <H> >- "infix_ap"[]{"rel_exp"[]{'"T";'"R";"add"[]{'"m";'"n"}};'"x";'"z"} }
define unfold_rel_implies : "rel_implies"[]{'"T";'"R1";'"R2"} <-->
"all"[]{'"T";"x"."all"[]{'"T";"y"."implies"[]{"infix_ap"[]{'"R1";'"x";'"y"};"infix_ap"[]{'"R2";'"x";'"y"}}}}
interactive nuprl_rel_implies_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R1" '"x" '"x1" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R2" '"x" '"x1" in "univ"[level:l]{} } -->
sequent { <H> >- ("rel_implies"[]{'"T";'"R1";'"R2"} in "univ"[level:l]{}) }
interactive nuprl_rel_exp_monotone :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "rel_implies"[]{'"T";'"R1";'"R2"} } -->
sequent { <H> >- "rel_implies"[]{'"T";"rel_exp"[]{'"T";'"R1";'"n"};"rel_exp"[]{'"T";'"R2";'"n"}} }
define unfold_preserved_by : "preserved_by"[]{'"T";'"R";'"P"} <-->
"all"[]{'"T";"x"."all"[]{'"T";"y"."implies"[]{('"P" '"x");"implies"[]{"infix_ap"[]{'"R";'"x";'"y"};('"P" '"y")}}}}
interactive nuprl_preserved_by_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"P" '"x" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R" '"x" '"x1" in "univ"[level:l]{} } -->
sequent { <H> >- ("preserved_by"[]{'"T";'"R";'"P"} in "univ"[level:l]{}) }
interactive nuprl_preserved_by_monotone '"R2" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H>; "x": '"T" ; "y": '"T" ; "infix_ap"[]{'"R1";'"x";'"y"} >- "infix_ap"[]{'"R2";'"x";'"y"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R2";'"P"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R1";'"P"} }
define unfold_cond_rel_implies : "cond_rel_implies"[]{'"T";'"P";'"R1";'"R2"} <-->
"all"[]{'"T";"x"."all"[]{'"T";"y"."implies"[]{('"P" '"x");"implies"[]{"infix_ap"[]{'"R1";'"x";'"y"};"infix_ap"[]{'"R2";'"x";'"y"}}}}}
interactive nuprl_cond_rel_implies_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"P" '"x" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R1" '"x" '"x1" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R2" '"x" '"x1" in "univ"[level:l]{} } -->
sequent { <H> >- ("cond_rel_implies"[]{'"T";'"P";'"R1";'"R2"} in "univ"[level:l]{}) }
interactive nuprl_cond_rel_exp_monotone :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "cond_rel_implies"[]{'"T";'"P";'"R1";'"R2"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R1";'"P"} } -->
sequent { <H> >- "cond_rel_implies"[]{'"T";'"P";"rel_exp"[]{'"T";'"R1";'"n"};"rel_exp"[]{'"T";'"R2";'"n"}} }
define unfold_rel_star : "rel_star"[]{'"T";'"R"} <-->
"lambda"[]{"x"."lambda"[]{"y"."exists"[]{"nat"[]{};"n"."infix_ap"[]{"rel_exp"[]{'"T";'"R";'"n"};'"x";'"y"}}}}
interactive nuprl_rel_star_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R" '"x" '"x1" in "univ"[level:l]{} } -->
sequent { <H> >- ("rel_star"[]{'"T";'"R"} in "fun"[]{'"T";""."fun"[]{'"T";""."univ"[level:l]{}}}) }
interactive nuprl_rel_star_monotone :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "rel_implies"[]{'"T";'"R1";'"R2"} } -->
sequent { <H> >- "rel_implies"[]{'"T";"rel_star"[]{'"T";'"R1"};"rel_star"[]{'"T";'"R2"}} }
interactive nuprl_cond_rel_star_monotone :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "cond_rel_implies"[]{'"T";'"P";'"R1";'"R2"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R1";'"P"} } -->
sequent { <H> >- "cond_rel_implies"[]{'"T";'"P";"rel_star"[]{'"T";'"R1"};"rel_star"[]{'"T";'"R2"}} }
interactive nuprl_rel_star_transitivity '"y" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
[wf] sequent { <H> >- '"z" in '"T" } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"y";'"z"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"z"} }
interactive nuprl_rel_star_monotonic '"R1" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- "rel_implies"[]{'"T";'"R1";'"R2"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R1"};'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R2"};'"x";'"y"} }
interactive nuprl_cond_rel_star_monotonic '"R1" '"P" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "cond_rel_implies"[]{'"T";'"P";'"R1";'"R2"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R1";'"P"} } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- ('"P" '"x") } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R1"};'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R2"};'"x";'"y"} }
interactive nuprl_preserved_by_star :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R";'"P"} } -->
sequent { <H> >- "preserved_by"[]{'"T";"rel_star"[]{'"T";'"R"};'"P"} }
interactive nuprl_rel_star_closure '"T" "lambda"[]{"x1", "x".'"R2"['"x1";'"x"]} '"R" '"y" '"x" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2"['"x";'"x1"] } } -->
sequent { <H> >- "trans"[]{'"T";"_1", "_2".'"R2"['"_1";'"_2"]} } -->
sequent { <H>; "x": '"T" ; "y": '"T" ; "infix_ap"[]{'"R";'"x";'"y"} >- "infix_ap"[]{"lambda"[]{"x1"."lambda"[]{"x".'"R2"['"x1";'"x"]}};'"x";'"y"} } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"y"} } -->
sequent { <H> >- "or"[]{"infix_ap"[]{"lambda"[]{"x1"."lambda"[]{"x".'"R2"['"x1";'"x"]}};'"x";'"y"};"equal"[]{'"T";'"x";'"y"}} }
interactive nuprl_rel_star_closure2 '"T" "lambda"[]{"x1", "x".'"R2"['"x1";'"x"]} '"R" '"y" '"x" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2"['"x";'"x1"] } } -->
sequent { <H> >- "refl"[]{'"T";"_1", "_2".'"R2"['"_1";'"_2"]} } -->
sequent { <H> >- "trans"[]{'"T";"_1", "_2".'"R2"['"_1";'"_2"]} } -->
sequent { <H>; "x": '"T" ; "y": '"T" ; "infix_ap"[]{'"R";'"x";'"y"} >- '"R2"['"x";'"y"] } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"y"} } -->
sequent { <H> >- '"R2"['"x";'"y"] }
interactive nuprl_rel_star_of_equiv '"T" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"E" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- "equiv_rel"[]{'"T";"_1", "_2"."infix_ap"[]{'"E";'"_1";'"_2"}} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"E"};'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{'"E";'"x";'"y"} }
interactive nuprl_cond_rel_star_equiv :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"E" '"x" '"x1" } } -->
sequent { <H> >- "equiv_rel"[]{'"T";"_1", "_2"."infix_ap"[]{'"E";'"_1";'"_2"}} } -->
sequent { <H> >- "cond_rel_implies"[]{'"T";'"P";'"R1";'"E"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R1";'"P"} } -->
sequent { <H> >- "cond_rel_implies"[]{'"T";'"P";"rel_star"[]{'"T";'"R1"};'"E"} }
interactive nuprl_rel_rel_star :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- "infix_ap"[]{'"R";'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"y"} }
interactive nuprl_rel_star_trans '"y" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
[wf] sequent { <H> >- '"z" in '"T" } -->
sequent { <H> >- "infix_ap"[]{'"R";'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"y";'"z"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"z"} }
interactive nuprl_rel_star_weakening :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
sequent { <H> >- "equal"[]{'"T";'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"y"} }
define unfold_rel_inverse : "rel_inverse"[]{'"R"} <-->
"lambda"[]{"x"."lambda"[]{"y"."infix_ap"[]{'"R";'"y";'"x"}}}
interactive nuprl_rel_inverse_wf {| intro[] |} :
[wf] sequent { <H> >- '"T1" in "univ"[level:l]{} } -->
[wf] sequent { <H> >- '"T2" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T1";"x1": '"T2" >- '"R" '"x" '"x1" in "univ"[level:l]{} } -->
sequent { <H> >- ("rel_inverse"[]{'"R"} in "fun"[]{'"T2";""."fun"[]{'"T1";""."univ"[level:l]{}}}) }
interactive nuprl_rel_inverse_exp :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- "iff"[]{"infix_ap"[]{"rel_inverse"[]{"rel_exp"[]{'"T";'"R";'"n"}};'"x";'"y"};"infix_ap"[]{"rel_exp"[]{'"T";"rel_inverse"[]{'"R"};'"n"};'"x";'"y"}} }
interactive nuprl_rel_inverse_star :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- "iff"[]{"infix_ap"[]{"rel_inverse"[]{"rel_star"[]{'"T";'"R"}};'"x";'"y"};"infix_ap"[]{"rel_star"[]{'"T";"rel_inverse"[]{'"R"}};'"x";'"y"}} }
interactive nuprl_rel_star_symmetric :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
sequent { <H> >- "sym"[]{'"T";"x", "y"."infix_ap"[]{'"R";'"x";'"y"}} } -->
sequent { <H> >- "sym"[]{'"T";"x", "y"."infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"y"}} }
interactive nuprl_rel_star_symmetric_2 :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
[wf] sequent { <H> >- '"y" in '"T" } -->
sequent { <H> >- "sym"[]{'"T";"x", "y"."infix_ap"[]{'"R";'"x";'"y"}} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"x";'"y"} } -->
sequent { <H> >- "infix_ap"[]{"rel_star"[]{'"T";'"R"};'"y";'"x"} }
interactive nuprl_preserved_by_symmetric :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
sequent { <H> >- "sym"[]{'"T";"x", "y"."infix_ap"[]{'"R";'"x";'"y"}} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R";'"P"} } -->
sequent { <H> >- "preserved_by"[]{'"T";"rel_inverse"[]{'"R"};'"P"} }
define unfold_rel_or : "rel_or"[]{'"R1";'"R2"} <-->
"lambda"[]{"x"."lambda"[]{"y"."or"[]{"infix_ap"[]{'"R1";'"x";'"y"};"infix_ap"[]{'"R2";'"x";'"y"}}}}
interactive nuprl_rel_or_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R1" '"x" '"x1" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- '"R2" '"x" '"x1" in "univ"[level:l]{} } -->
sequent { <H> >- ("rel_or"[]{'"R1";'"R2"} in "fun"[]{'"T";""."fun"[]{'"T";""."univ"[level:l]{}}}) }
interactive nuprl_rel_implies_or_left :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "rel_implies"[]{'"T";'"R1";"rel_or"[]{'"R1";'"R2"}} }
interactive nuprl_rel_implies_or_right :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "rel_implies"[]{'"T";'"R2";"rel_or"[]{'"R1";'"R2"}} }
interactive nuprl_symmetric_rel_or :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "sym"[]{'"T";"x", "y"."infix_ap"[]{'"R1";'"x";'"y"}} } -->
sequent { <H> >- "sym"[]{'"T";"x", "y"."infix_ap"[]{'"R2";'"x";'"y"}} } -->
sequent { <H> >- "sym"[]{'"T";"x", "y"."infix_ap"[]{"rel_or"[]{'"R1";'"R2"};'"x";'"y"}} }
interactive nuprl_preserved_by_or :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R1" '"x" '"x1" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R2" '"x" '"x1" } } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R1";'"P"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R2";'"P"} } -->
sequent { <H> >- "preserved_by"[]{'"T";"rel_or"[]{'"R1";'"R2"};'"P"} }
define unfold_as_strong : "as_strong"[]{'"T";'"Q";'"P"} <-->
"all"[]{'"T";"x"."implies"[]{('"P" '"x");('"Q" '"x")}}
interactive nuprl_as_strong_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"Q" '"x" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"P" '"x" in "univ"[level:l]{} } -->
sequent { <H> >- ("as_strong"[]{'"T";'"Q";'"P"} in "univ"[level:l]{}) }
interactive nuprl_as_strong_transitivity '"Q" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"Q" '"x" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"R" '"x" } } -->
sequent { <H> >- "as_strong"[]{'"T";'"Q";'"P"} } -->
sequent { <H> >- "as_strong"[]{'"T";'"R";'"Q"} } -->
sequent { <H> >- "as_strong"[]{'"T";'"R";'"P"} }
define unfold_fun_exp : "fun_exp"[]{'"f";'"n"} <-->
"primrec"[]{'"n";"lambda"[]{"x".'"x"};"lambda"[]{"i"."lambda"[]{"g"."compose"[]{'"f";'"g"}}}}
interactive nuprl_fun_exp_wf {| intro[] |} :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"f" '"x" in '"T" } -->
sequent { <H> >- ("fun_exp"[]{'"f";'"n"} in "fun"[]{'"T";"".'"T"}) }
interactive nuprl_comb_for_fun_exp_wf :
sequent { <H> >- ("lambda"[]{"T"."lambda"[]{"n"."lambda"[]{"f"."lambda"[]{"z"."fun_exp"[]{'"f";'"n"}}}}} in "fun"[]{"univ"[level:l]{};"T"."fun"[]{"nat"[]{};"n"."fun"[]{"fun"[]{'"T";"".'"T"};"f"."fun"[]{"squash"[]{"true"[]{}};""."fun"[]{'"T";"".'"T"}}}}}) }
interactive nuprl_fun_exp_compose :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"h" '"x" in '"T" } -->
[wf] sequent { <H>;"x": '"T" >- '"f" '"x" in '"T" } -->
sequent { <H> >- "equal"[]{"fun"[]{'"T";"".'"T"};"compose"[]{"fun_exp"[]{'"f";'"n"};'"h"};"primrec"[]{'"n";'"h";"lambda"[]{"i"."lambda"[]{"g"."compose"[]{'"f";'"g"}}}}} }
interactive nuprl_fun_exp_add :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"m" in "nat"[]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"f" '"x" in '"T" } -->
sequent { <H> >- "equal"[]{"fun"[]{'"T";"".'"T"};"fun_exp"[]{'"f";"add"[]{'"n";'"m"}};"compose"[]{"fun_exp"[]{'"f";'"n"};"fun_exp"[]{'"f";'"m"}}} }
interactive nuprl_fun_exp_add1 :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- '"f" '"x" in '"T" } -->
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
sequent { <H> >- "equal"[]{'"T";('"f" ("fun_exp"[]{'"f";'"n"} '"x"));("fun_exp"[]{'"f";"add"[]{'"n";"number"[1:n]{}}} '"x")} }
interactive nuprl_fun_exp_add1_sub :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- '"f" '"x" in '"T" } -->
[wf] sequent { <H> >- '"n" in "nat_plus"[]{} } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
sequent { <H> >- "equal"[]{'"T";('"f" ("fun_exp"[]{'"f";"sub"[]{'"n";"number"[1:n]{}}} '"x"));("fun_exp"[]{'"f";'"n"} '"x")} }
interactive nuprl_iteration_terminates '"m" :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- '"f" '"x" in '"T" } -->
[wf] sequent { <H>;"x": '"T" >- '"m" '"x" in "nat"[]{} } -->
sequent { <H>; "x": '"T" >- "and"[]{"le"[]{('"m" ('"f" '"x"));('"m" '"x")};"implies"[]{"equal"[]{"int"[]{};('"m" ('"f" '"x"));('"m" '"x")};"equal"[]{'"T";('"f" '"x");'"x"}}} } -->
[wf] sequent { <H> >- '"x" in '"T" } -->
sequent { <H> >- "exists"[]{"nat"[]{};"n"."equal"[]{'"T";('"f" ("fun_exp"[]{'"f";'"n"} '"x"));("fun_exp"[]{'"f";'"n"} '"x")}} }
define unfold_flip : "flip"[]{'"i";'"j"} <-->
"lambda"[]{"x"."ifthenelse"[]{"beq_int"[]{'"x";'"i"};'"j";"ifthenelse"[]{"beq_int"[]{'"x";'"j"};'"i";'"x"}}}
interactive nuprl_flip_wf {| intro[] |} :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"i" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
[wf] sequent { <H> >- '"j" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- ("flip"[]{'"i";'"j"} in "fun"[]{"int_seg"[]{"number"[0:n]{};'"k"};""."int_seg"[]{"number"[0:n]{};'"k"}}) }
interactive nuprl_sum_switch '"n" '"i" "lambda"[]{"x".'"f"['"x"]} :
[wf] sequent { <H> >- '"n" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"n"} >- '"f"['"x"] in "int"[]{} } -->
[wf] sequent { <H> >- '"i" in "int_seg"[]{"number"[0:n]{};"sub"[]{'"n";"number"[1:n]{}}} } -->
sequent { <H> >- "equal"[]{"int"[]{};"sum"[]{'"n";"x".'"f"[("flip"[]{'"i";"add"[]{'"i";"number"[1:n]{}}} '"x")]};"sum"[]{'"n";"x".'"f"['"x"]}} }
interactive nuprl_flip_symmetry :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"i" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
[wf] sequent { <H> >- '"j" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "equal"[]{"fun"[]{"int_seg"[]{"number"[0:n]{};'"k"};""."int_seg"[]{"number"[0:n]{};'"k"}};"flip"[]{'"i";'"j"};"flip"[]{'"j";'"i"}} }
interactive nuprl_flip_bijection :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H> >- '"i" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
[wf] sequent { <H> >- '"j" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "biject"[]{"int_seg"[]{"number"[0:n]{};'"k"};"int_seg"[]{"number"[0:n]{};'"k"};"flip"[]{'"i";'"j"}} }
interactive nuprl_flip_inverse :
[wf] sequent { <H> >- '"k" in "int"[]{} } -->
[wf] sequent { <H> >- '"x" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
[wf] sequent { <H> >- '"y" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "equal"[]{"fun"[]{"int_seg"[]{"number"[0:n]{};'"k"};""."int_seg"[]{"number"[0:n]{};'"k"}};"compose"[]{"flip"[]{'"y";'"x"};"flip"[]{'"y";'"x"}};"lambda"[]{"x".'"x"}} }
interactive nuprl_flip_twice '"k" :
[wf] sequent { <H> >- '"k" in "int"[]{} } -->
[wf] sequent { <H> >- '"x" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
[wf] sequent { <H> >- '"y" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
[wf] sequent { <H> >- '"i" in "int_seg"[]{"number"[0:n]{};'"k"} } -->
sequent { <H> >- "equal"[]{"int"[]{};("flip"[]{'"y";'"x"} ("flip"[]{'"y";'"x"} '"i"));'"i"} }
define unfold_search : "search"[]{'"k";'"P"} <-->
"primrec"[]{'"k";"number"[0:n]{};"lambda"[]{"i"."lambda"[]{"j"."ifthenelse"[]{"lt_bool"[]{"number"[0:n]{};'"j"};'"j";"ifthenelse"[]{('"P" '"i");"add"[]{'"i";"number"[1:n]{}};"number"[0:n]{}}}}}}
interactive nuprl_search_wf {| intro[] |} :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"P" '"x" in "bool"[]{} } -->
sequent { <H> >- ("search"[]{'"k";'"P"} in "int_seg"[]{"number"[0:n]{};"add"[]{'"k";"number"[1:n]{}}}) }
interactive nuprl_search_property :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};'"k"} >- '"P" '"x" in "bool"[]{} } -->
sequent { <H> >- "and"[]{"iff"[]{"exists"[]{"int_seg"[]{"number"[0:n]{};'"k"};"i"."assert"[]{('"P" '"i")}};"lt"[]{"number"[0:n]{};"search"[]{'"k";'"P"}}};"implies"[]{"lt"[]{"number"[0:n]{};"search"[]{'"k";'"P"}};"and"[]{"assert"[]{('"P" "sub"[]{"search"[]{'"k";'"P"};"number"[1:n]{}})};"all"[]{"int_seg"[]{"number"[0:n]{};'"k"};"j"."implies"[]{"lt"[]{'"j";"sub"[]{"search"[]{'"k";'"P"};"number"[1:n]{}}};"not"[]{"assert"[]{('"P" '"j")}}}}}}} }
interactive nuprl_search_succ :
[wf] sequent { <H> >- '"k" in "nat"[]{} } -->
[wf] sequent { <H>;"x": "int_seg"[]{"number"[0:n]{};"add"[]{'"k";"number"[1:n]{}}} >- '"P" '"x" in "bool"[]{} } -->
sequent { <H> >- "equal"[]{"int"[]{};"search"[]{"add"[]{'"k";"number"[1:n]{}};'"P"};"ifthenelse"[]{('"P" "number"[0:n]{});"number"[1:n]{};"ifthenelse"[]{"lt_bool"[]{"number"[0:n]{};"search"[]{'"k";"lambda"[]{"i".('"P" "add"[]{'"i";"number"[1:n]{}})}}};"add"[]{"search"[]{'"k";"lambda"[]{"i".('"P" "add"[]{'"i";"number"[1:n]{}})}};"number"[1:n]{}};"number"[0:n]{}}}} }
define unfold_prop_and : "prop_and"[]{'"P";'"Q"} <-->
"lambda"[]{"L"."and"[]{('"P" '"L");('"Q" '"L")}}
interactive nuprl_prop_and_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"P" '"x" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"Q" '"x" in "univ"[level:l]{} } -->
sequent { <H> >- ("prop_and"[]{'"P";'"Q"} in "fun"[]{'"T";""."univ"[level:l]{}}) }
interactive nuprl_and_preserved_by :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"Q" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T" >- "type"{'"R" '"x" '"x1" } } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R";'"P"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R";'"Q"} } -->
sequent { <H> >- "preserved_by"[]{'"T";'"R";"prop_and"[]{'"P";'"Q"}} }
define unfold_preserved_by2 : "preserved_by2"[]{'"T";'"R";'"P"} <-->
"all"[]{'"T";"x"."all"[]{'"T";"y"."all"[]{'"T";"z"."implies"[]{('"P" '"x");"implies"[]{('"P" '"y");"implies"[]{((('"R" '"x") '"y") '"z");('"P" '"z")}}}}}}
interactive nuprl_preserved_by2_wf {| intro[] |} :
[wf] sequent { <H> >- '"T" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T" >- '"P" '"x" in "univ"[level:l]{} } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T";"x2": '"T" >- '"R" '"x" '"x1" '"x2" in "univ"[level:l]{} } -->
sequent { <H> >- ("preserved_by2"[]{'"T";'"R";'"P"} in "univ"[level:l]{}) }
interactive nuprl_and_preserved_by2 :
[wf] sequent { <H> >- "type"{'"T" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"P" '"x" } } -->
[wf] sequent { <H>;"x": '"T" >- "type"{'"Q" '"x" } } -->
[wf] sequent { <H>;"x": '"T";"x1": '"T";"x2": '"T" >- "type"{'"R" '"x" '"x1" '"x2" } } -->
sequent { <H> >- "preserved_by2"[]{'"T";'"R";'"P"} } -->
sequent { <H> >- "preserved_by2"[]{'"T";'"R";'"Q"} } -->
sequent { <H> >- "preserved_by2"[]{'"T";'"R";"prop_and"[]{'"P";'"Q"}} }
dform nuprl_primrec_df : except_mode[src] :: "primrec"[]{'"n";'"b";'"c"} =
`"primrec(" slot{'"n"} `";" slot{'"b"} `";" slot{'"c"} `")"
dform nuprl_nondecreasing_df : except_mode[src] :: "nondecreasing"[]{'"f";'"k"} =
`"nondecreasing(" slot{'"f"} `";" slot{'"k"} `")"
dform nuprl_fadd_df : except_mode[src] :: "fadd"[]{'"f";'"g"} =
`"fadd(" slot{'"f"} `";" slot{'"g"} `")"
dform nuprl_fshift_df : except_mode[src] :: "fshift"[]{'"f";'"x"} =
`"fshift(" slot{'"f"} `";" slot{'"x"} `")"
dform nuprl_finite_df : except_mode[src] :: "finite"[]{'"T"} =
`"finite(" slot{'"T"} `")"
dform nuprl_fappend_df : except_mode[src] :: "fappend"[]{'"f";'"n";'"x"} =
`"" slot{'"f"} `"[" slot{'"n"} `":=" slot{'"x"} `"]"
dform nuprl_sum_df : except_mode[src] :: "sum"[]{'"k";"x".'"f"} =
`"sum(" slot{'"k"} `";" slot{'"x"} `"." slot{'"f"} `")"
dform nuprl_sum_df : except_mode[src] :: "sum"[]{'"k";"x".'"f"} =
`"sum(" slot{'"f"} `" | " slot{'"x"} `" < " slot{'"k"} `")"
dform nuprl_double_sum_df : except_mode[src] :: "double_sum"[]{'"n";'"m";"x", "y".'"f"} =
`"double_sum(" slot{'"n"} `";" slot{'"m"} `";" slot{'"x"} `"," slot{'"y"} `"."
slot{'"f"} `")"
dform nuprl_double_sum_df : except_mode[src] :: "double_sum"[]{'"n";'"m";"x", "y".'"f"} =
`"sum(" slot{'"f"} `" | " slot{'"x"} `" < " slot{'"n"} `"; " slot{'"y"} `" < "
slot{'"m"} `")"
dform nuprl_rel_exp_df1 : except_mode[src] :: "rel_exp"[]{'"T";'"R";'"n"} =
`"rel_exp(" slot{'"T"} `";" slot{'"R"} `";" slot{'"n"} `")"
dform nuprl_rel_exp_df : except_mode[src] :: "rel_exp"[]{'"T";'"R";'"n"} =
`"rel_exp(" slot{'"T"} `";" slot{'"R"} `";" slot{'"n"} `")"
dform nuprl_rel_exp_df : except_mode[src] :: "rel_exp"[]{'"T";'"R";'"n"} =
`"" slot{'"R"} `"" `"" `"" `"" slot{'"n"} `"" `"" `""
dform nuprl_rel_exp_df : except_mode[src] :: "rel_exp"[]{'"T";'"R";'"n"} =
`"" slot{'"R"} `"^" `"" slot{'"n"} `""
dform nuprl_rel_implies_df : except_mode[src] :: "rel_implies"[]{'"T";'"R1";'"R2"} =
`"rel_implies(" slot{'"T"} `";" slot{'"R1"} `";" slot{'"R2"} `")"
dform nuprl_rel_implies_df : except_mode[src] :: "rel_implies"[]{'"T";'"R1";'"R2"} =
`"" slot{'"R1"} `" => " slot{'"R2"} `""
dform nuprl_preserved_by_df : except_mode[src] :: "preserved_by"[]{'"T";'"R";'"P"} =
`"preserved_by(" slot{'"T"} `";" slot{'"R"} `";" slot{'"P"} `")"
dform nuprl_preserved_by_df : except_mode[src] :: "preserved_by"[]{'"T";'"R";'"P"} =
`"" slot{'"R"} `" preserves " slot{'"P"} `""
dform nuprl_cond_rel_implies_df : except_mode[src] :: "cond_rel_implies"[]{'"T";'"P";'"R1";'"R2"} =
`"cond_rel_implies(" slot{'"T"} `";" slot{'"P"} `";" slot{'"R1"} `";"
slot{'"R2"} `")"
dform nuprl_cond_rel_implies_df : except_mode[src] :: "cond_rel_implies"[]{'"T";'"P";'"R1";'"R2"} =
`"when " slot{'"P"} `", " slot{'"R1"} `" => " slot{'"R2"} `""
dform nuprl_rel_star_df : except_mode[src] :: "rel_star"[]{'"T";'"R"} =
`"rel_star(" slot{'"T"} `";" slot{'"R"} `")"
dform nuprl_rel_star_df : except_mode[src] :: "rel_star"[]{'"T";'"R"} =
`"" slot{'"R"} `"" `"" `"" `"*" `"" `"" `""
dform nuprl_rel_star_df : except_mode[src] :: "rel_star"[]{'"T";'"R"} =
`"" slot{'"R"} `"^*"
dform nuprl_rel_inverse_df : except_mode[src] :: "rel_inverse"[]{'"R"} =
`"rel_inverse(" slot{'"R"} `")"
dform nuprl_rel_inverse_df : except_mode[src] :: "rel_inverse"[]{'"R"} =
`"" slot{'"R"} `"^-1"
dform nuprl_rel_or_df : except_mode[src] :: "rel_or"[]{'"R1";'"R2"} =
`"rel_or(" slot{'"R1"} `";" slot{'"R2"} `")"
dform nuprl_rel_or_df : except_mode[src] :: "rel_or"[]{'"P";'"Q"} =
`"" szone `"" slot{'"P"} `"" sbreak[""," "] `"" vee `" " pushm[0:n] `"" slot{'"Q"}
`"" popm `"" ezone `""
dform nuprl_rel_or_df : except_mode[src] :: "rel_or"[]{'"P";'"#"} =
`"" szone `"" pushm[0:n] `"" slot{'"P"} `"" popm `"" sbreak[""," "] `"" vee `" "
slot{'"#"} `"" ezone `""
dform nuprl_rel_or_df : except_mode[src] :: "rel_or"[]{'"P";'"Q"} =
`"" pushm[0:n] `"" slot{'"P"} `"" popm `"" sbreak[""," "] `"" vee `" " pushm[0:n]
`"" slot{'"Q"} `"" popm `""
dform nuprl_rel_or_df : except_mode[src] :: "rel_or"[]{'"P";'"#"} =
`"" pushm[0:n] `"" slot{'"P"} `"" popm `"" sbreak[""," "] `"" vee `" " slot{'"#"}
`""
dform nuprl_as_strong_df : except_mode[src] :: "as_strong"[]{'"T";'"Q";'"P"} =
`"as_strong(" slot{'"T"} `";" slot{'"Q"} `";" slot{'"P"} `")"
dform nuprl_as_strong_df : except_mode[src] :: "as_strong"[]{'"T";'"Q";'"P"} =
`"" szone `"" pushm[0:n] `"" slot{'"P"} `"" sbreak[""," "] `"as strong as"
sbreak[""," "] `"" slot{'"Q"} `"" popm ezone `" "
dform nuprl_fun_exp_df : except_mode[src] :: "fun_exp"[]{'"f";'"n"} =
`"fun_exp(" slot{'"f"} `";" slot{'"n"} `")"
dform nuprl_fun_exp_df : except_mode[src] :: "fun_exp"[]{'"f";'"n"} =
`"" slot{'"f"} `"^" slot{'"n"} `""
dform nuprl_flip_df : except_mode[src] :: "flip"[]{'"i";'"j"} =
`"flip(" slot{'"i"} `";" slot{'"j"} `")"
dform nuprl_flip_df : except_mode[src] :: "flip"[]{'"i";'"j"} =
`"(" slot{'"i"} `", " slot{'"j"} `")"
dform nuprl_search_df : except_mode[src] :: "search"[]{'"k";'"P"} =
`"search(" slot{'"k"} `";" slot{'"P"} `")"
dform nuprl_prop_and_df : except_mode[src] :: "prop_and"[]{'"P";'"Q"} =
`"" szone `"" slot{'"P"} `"" sbreak[""," "] `"" wedge `" " pushm[0:n] `"" slot{'"Q"}
`"" popm `"" ezone `""
dform nuprl_prop_and_df : except_mode[src] :: "prop_and"[]{'"P";'"#"} =
`"" szone `"" pushm[0:n] `"" slot{'"P"} `"" popm `"" sbreak[""," "] `"" wedge `" "
slot{'"#"} `"" ezone `""
dform nuprl_prop_and_df : except_mode[src] :: "prop_and"[]{'"P";'"Q"} =
`"" pushm[0:n] `"" slot{'"P"} `"" popm `"" sbreak[""," "] `"" wedge `" " pushm[0:n]
`"" slot{'"Q"} `"" popm `""
dform nuprl_prop_and_df : except_mode[src] :: "prop_and"[]{'"P";'"#"} =
`"" pushm[0:n] `"" slot{'"P"} `"" popm `"" sbreak[""," "] `"" wedge `" " slot{'"#"}
`""
dform nuprl_preserved_by2_df : except_mode[src] :: "preserved_by2"[]{'"T";'"R";'"P"} =
`"preserved_by2(" slot{'"T"} `";" slot{'"R"} `";" slot{'"P"} `")"
dform nuprl_preserved_by2_df : except_mode[src] :: "preserved_by2"[]{'"T";'"R";'"P"} =
`"(ternary) " slot{'"R"} `" preserves " slot{'"P"} `" "
|
f7ef3b61b23064670b66c4dcd57f8f50e430c2f4fd8447cfe3f60ae94d01f645 | unisonweb/unison | Operations.hs | module U.Codebase.Sqlite.Operations
( -- * branches
saveRootBranch,
loadRootCausalHash,
expectRootCausalHash,
expectRootCausal,
expectRootBranchHash,
loadCausalHashAtPath,
expectCausalHashAtPath,
saveBranch,
loadCausalBranchByCausalHash,
expectCausalBranchByCausalHash,
expectBranchByBranchHash,
expectNamespaceStatsByHash,
expectNamespaceStatsByHashId,
-- * terms
Q.saveTermComponent,
loadTermComponent,
loadTermByReference,
loadTypeOfTermByTermReference,
-- * decls
Q.saveDeclComponent,
loadDeclComponent,
loadDeclByReference,
expectDeclTypeById,
-- * terms/decls
getCycleLen,
-- * patches
savePatch,
expectPatch,
-- * test for stuff in codebase
objectExistsForHash,
-- * watch expression cache
saveWatch,
loadWatch,
listWatches,
Q.clearWatches,
-- * indexes
-- ** nearest common ancestor
before,
lca,
-- ** prefix index
componentReferencesByPrefix,
termReferentsByPrefix,
declReferentsByPrefix,
causalHashesByPrefix,
-- ** dependents index
dependents,
dependentsOfComponent,
-- ** type index
Q.addTypeToIndexForTerm,
termsHavingType,
-- ** type mentions index
Q.addTypeMentionsToIndexForTerm,
termsMentioningType,
-- ** name lookup index
rootNamesByPath,
NamesByPath (..),
checkBranchHashNameLookupExists,
buildNameLookupForBranchHash,
-- * reflog
getReflog,
appendReflog,
-- * low-level stuff
expectDbBranch,
saveDbBranch,
saveDbBranchUnderHashId,
expectDbPatch,
saveDbPatch,
expectDbBranchByCausalHashId,
namespaceStatsForDbBranch,
-- * somewhat unexpectedly unused definitions
c2sReferenceId,
c2sReferentId,
diffPatch,
decodeTermElementWithType,
loadTermWithTypeByReference,
Q.s2cTermWithType,
Q.s2cDecl,
declReferencesByPrefix,
namespaceHashesByPrefix,
derivedDependencies,
)
where
import Control.Lens hiding (children)
import qualified Control.Monad.Extra as Monad
import Data.Bitraversable (Bitraversable (bitraverse))
import qualified Data.Foldable as Foldable
import qualified Data.Map as Map
import qualified Data.Map.Merge.Lazy as Map
import qualified Data.Set as Set
import qualified Data.Text as Text
import Data.Tuple.Extra (uncurry3, (***))
import U.Codebase.Branch.Type (NamespaceStats (..))
import qualified U.Codebase.Branch.Type as C.Branch
import qualified U.Codebase.Causal as C
import U.Codebase.Decl (ConstructorId)
import qualified U.Codebase.Decl as C
import qualified U.Codebase.Decl as C.Decl
import U.Codebase.HashTags (BranchHash (..), CausalHash (..), PatchHash (..))
import qualified U.Codebase.Reference as C
import qualified U.Codebase.Reference as C.Reference
import qualified U.Codebase.Referent as C
import qualified U.Codebase.Referent as C.Referent
import qualified U.Codebase.Reflog as Reflog
import U.Codebase.ShortHash (ShortCausalHash (..), ShortNamespaceHash (..))
import qualified U.Codebase.Sqlite.Branch.Diff as S.Branch
import qualified U.Codebase.Sqlite.Branch.Diff as S.Branch.Diff
import qualified U.Codebase.Sqlite.Branch.Diff as S.BranchDiff
import qualified U.Codebase.Sqlite.Branch.Format as S
import qualified U.Codebase.Sqlite.Branch.Format as S.BranchFormat
import qualified U.Codebase.Sqlite.Branch.Full as S
import qualified U.Codebase.Sqlite.Branch.Full as S.Branch.Full
import qualified U.Codebase.Sqlite.Branch.Full as S.MetadataSet
import qualified U.Codebase.Sqlite.DbId as Db
import qualified U.Codebase.Sqlite.Decl.Format as S.Decl
import U.Codebase.Sqlite.Decode
import U.Codebase.Sqlite.HashHandle (HashHandle (..))
import U.Codebase.Sqlite.LocalIds
( LocalIds,
WatchLocalIds,
)
import qualified U.Codebase.Sqlite.LocalizeObject as LocalizeObject
import qualified U.Codebase.Sqlite.NamedRef as S
import qualified U.Codebase.Sqlite.ObjectType as ObjectType
import qualified U.Codebase.Sqlite.Patch.Diff as S
import qualified U.Codebase.Sqlite.Patch.Format as S
import qualified U.Codebase.Sqlite.Patch.Format as S.Patch.Format
import qualified U.Codebase.Sqlite.Patch.Full as S (LocalPatch, Patch, Patch' (..))
import qualified U.Codebase.Sqlite.Patch.TermEdit as S
import qualified U.Codebase.Sqlite.Patch.TermEdit as S.TermEdit
import qualified U.Codebase.Sqlite.Patch.TypeEdit as S
import qualified U.Codebase.Sqlite.Patch.TypeEdit as S.TypeEdit
import qualified U.Codebase.Sqlite.Queries as Q
import qualified U.Codebase.Sqlite.Reference as S
import qualified U.Codebase.Sqlite.Reference as S.Reference
import qualified U.Codebase.Sqlite.Referent as S
import qualified U.Codebase.Sqlite.Referent as S.Referent
import qualified U.Codebase.Sqlite.Serialization as S
import U.Codebase.Sqlite.Symbol (Symbol)
import qualified U.Codebase.Sqlite.Term.Format as S.Term
import qualified U.Codebase.Term as C
import qualified U.Codebase.Term as C.Term
import qualified U.Codebase.TermEdit as C
import qualified U.Codebase.TermEdit as C.TermEdit
import qualified U.Codebase.TypeEdit as C
import qualified U.Codebase.TypeEdit as C.TypeEdit
import U.Codebase.WatchKind (WatchKind)
import qualified U.Util.Base32Hex as Base32Hex
import qualified U.Util.Serialization as S
import qualified Unison.Hash as H
import qualified Unison.Hash32 as Hash32
import Unison.NameSegment (NameSegment (NameSegment))
import qualified Unison.NameSegment as NameSegment
import Unison.Prelude
import Unison.Sqlite
import qualified Unison.Util.Map as Map
import qualified Unison.Util.Set as Set
-- * Error handling
debug :: Bool
debug = False
newtype NeedTypeForBuiltinMetadata
= NeedTypeForBuiltinMetadata Text
deriving stock (Show)
deriving anyclass (SqliteExceptionReason)
-- * Database lookups
objectExistsForHash :: H.Hash -> Transaction Bool
objectExistsForHash h =
isJust <$> runMaybeT do
id <- MaybeT . Q.loadHashId . Hash32.fromHash $ h
MaybeT $ Q.loadObjectIdForAnyHashId id
expectValueHashByCausalHashId :: Db.CausalHashId -> Transaction BranchHash
expectValueHashByCausalHashId = loadValueHashById <=< Q.expectCausalValueHashId
where
loadValueHashById :: Db.BranchHashId -> Transaction BranchHash
loadValueHashById = fmap BranchHash . Q.expectHash . Db.unBranchHashId
expectRootCausalHash :: Transaction CausalHash
expectRootCausalHash = Q.expectCausalHash =<< Q.expectNamespaceRoot
expectRootBranchHash :: Transaction BranchHash
expectRootBranchHash = do
rootCausalHashId <- Q.expectNamespaceRoot
expectValueHashByCausalHashId rootCausalHashId
loadRootCausalHash :: Transaction (Maybe CausalHash)
loadRootCausalHash =
runMaybeT $
lift . Q.expectCausalHash =<< MaybeT Q.loadNamespaceRoot
-- | Load the causal hash at the given path from the root.
--
FIXME should we move some Path type here ?
loadCausalHashAtPath :: [Text] -> Transaction (Maybe CausalHash)
loadCausalHashAtPath =
let go :: Db.CausalHashId -> [Text] -> MaybeT Transaction CausalHash
go hashId = \case
[] -> lift (Q.expectCausalHash hashId)
t : ts -> do
tid <- MaybeT (Q.loadTextId t)
S.Branch {children} <- MaybeT (loadDbBranchByCausalHashId hashId)
(_, hashId') <- MaybeT (pure (Map.lookup tid children))
go hashId' ts
in \path -> do
hashId <- Q.expectNamespaceRoot
runMaybeT (go hashId path)
-- | Expect the causal hash at the given path from the root.
--
FIXME should we move some Path type here ?
expectCausalHashAtPath :: [Text] -> Transaction CausalHash
expectCausalHashAtPath =
let go :: Db.CausalHashId -> [Text] -> Transaction CausalHash
go hashId = \case
[] -> Q.expectCausalHash hashId
t : ts -> do
tid <- Q.expectTextId t
S.Branch {children} <- expectDbBranchByCausalHashId hashId
let (_, hashId') = children Map.! tid
go hashId' ts
in \path -> do
hashId <- Q.expectNamespaceRoot
go hashId path
-- * Reference transformations
-- ** read existing references
-- | Assumes that a derived reference would already exist in the database
-- (by virtue of dependencies being stored before dependents), but does
-- not assume a builtin reference would.
c2sReference :: C.Reference -> Transaction S.Reference
c2sReference = bitraverse Q.saveText Q.expectObjectIdForPrimaryHash
c2sTextReference :: C.Reference -> S.TextReference
c2sTextReference = bimap id H.toBase32Hex
s2cReference :: S.Reference -> Transaction C.Reference
s2cReference = bitraverse Q.expectText Q.expectPrimaryHashByObjectId
s2cTextReference :: S.TextReference -> C.Reference
s2cTextReference = bimap id H.fromBase32Hex
c2sReferenceId :: C.Reference.Id -> Transaction S.Reference.Id
c2sReferenceId = C.Reference.idH Q.expectObjectIdForPrimaryHash
s2cReferenceId :: S.Reference.Id -> Transaction C.Reference.Id
s2cReferenceId = C.Reference.idH Q.expectPrimaryHashByObjectId
h2cReferenceId :: S.Reference.IdH -> Transaction C.Reference.Id
h2cReferenceId = C.Reference.idH Q.expectHash
h2cReference :: S.ReferenceH -> Transaction C.Reference
h2cReference = bitraverse Q.expectText Q.expectHash
c2hReference :: C.Reference -> MaybeT Transaction S.ReferenceH
c2hReference = bitraverse (MaybeT . Q.loadTextId) (MaybeT . Q.loadHashIdByHash)
s2cReferent :: S.Referent -> Transaction C.Referent
s2cReferent = bitraverse s2cReference s2cReference
s2cTextReferent :: S.TextReferent -> C.Referent
s2cTextReferent = bimap s2cTextReference s2cTextReference
s2cConstructorType :: S.ConstructorType -> C.ConstructorType
s2cConstructorType = \case
S.DataConstructor -> C.DataConstructor
S.EffectConstructor -> C.EffectConstructor
c2sConstructorType :: C.ConstructorType -> S.ConstructorType
c2sConstructorType = \case
C.DataConstructor -> S.DataConstructor
C.EffectConstructor -> S.EffectConstructor
s2cReferentId :: S.Referent.Id -> Transaction C.Referent.Id
s2cReferentId = bitraverse Q.expectPrimaryHashByObjectId Q.expectPrimaryHashByObjectId
c2sReferent :: C.Referent -> Transaction S.Referent
c2sReferent = bitraverse c2sReference c2sReference
c2sTextReferent :: C.Referent -> S.TextReferent
c2sTextReferent = bimap c2sTextReference c2sTextReference
c2sReferentId :: C.Referent.Id -> Transaction S.Referent.Id
c2sReferentId = bitraverse Q.expectObjectIdForPrimaryHash Q.expectObjectIdForPrimaryHash
h2cReferent :: S.ReferentH -> Transaction C.Referent
h2cReferent = bitraverse h2cReference h2cReference
-- ** convert and save references
saveReferentH :: C.Referent -> Transaction S.ReferentH
saveReferentH = bitraverse Q.saveReferenceH Q.saveReferenceH
-- ** Edits transformations
s2cTermEdit :: S.TermEdit -> Transaction C.TermEdit
s2cTermEdit = \case
S.TermEdit.Replace r t -> C.TermEdit.Replace <$> s2cReferent r <*> pure (s2cTyping t)
S.TermEdit.Deprecate -> pure C.TermEdit.Deprecate
s2cTyping :: S.TermEdit.Typing -> C.TermEdit.Typing
s2cTyping = \case
S.TermEdit.Same -> C.TermEdit.Same
S.TermEdit.Subtype -> C.TermEdit.Subtype
S.TermEdit.Different -> C.TermEdit.Different
c2sTyping :: C.TermEdit.Typing -> S.TermEdit.Typing
c2sTyping = \case
C.TermEdit.Same -> S.TermEdit.Same
C.TermEdit.Subtype -> S.TermEdit.Subtype
C.TermEdit.Different -> S.TermEdit.Different
s2cTypeEdit :: S.TypeEdit -> Transaction C.TypeEdit
s2cTypeEdit = \case
S.TypeEdit.Replace r -> C.TypeEdit.Replace <$> s2cReference r
S.TypeEdit.Deprecate -> pure C.TypeEdit.Deprecate
| assumes that all relevant defns are already in the DB
c2sPatch :: C.Branch.Patch -> Transaction S.Patch
c2sPatch (C.Branch.Patch termEdits typeEdits) =
S.Patch
<$> Map.bitraverse saveReferentH (Set.traverse c2sTermEdit) termEdits
<*> Map.bitraverse Q.saveReferenceH (Set.traverse c2sTypeEdit) typeEdits
where
c2sTermEdit = \case
C.TermEdit.Replace r t -> S.TermEdit.Replace <$> c2sReferent r <*> pure (c2sTyping t)
C.TermEdit.Deprecate -> pure S.TermEdit.Deprecate
c2sTypeEdit = \case
C.TypeEdit.Replace r -> S.TypeEdit.Replace <$> c2sReference r
C.TypeEdit.Deprecate -> pure S.TypeEdit.Deprecate
-- | produces a diff
-- diff = full - ref; full = diff + ref
diffPatch :: S.LocalPatch -> S.LocalPatch -> S.LocalPatchDiff
diffPatch (S.Patch fullTerms fullTypes) (S.Patch refTerms refTypes) =
(S.PatchDiff addTermEdits addTypeEdits removeTermEdits removeTypeEdits)
where
-- add: present in full. but absent in ref.
addTermEdits = Map.merge Map.preserveMissing Map.dropMissing addDiffSet fullTerms refTerms
addTypeEdits = Map.merge Map.preserveMissing Map.dropMissing addDiffSet fullTypes refTypes
-- remove: present in ref. but absent in full.
removeTermEdits = Map.merge Map.dropMissing Map.preserveMissing removeDiffSet fullTerms refTerms
removeTypeEdits = Map.merge Map.dropMissing Map.preserveMissing removeDiffSet fullTypes refTypes
-- things that are present in full but absent in ref
addDiffSet,
removeDiffSet ::
(Ord k, Ord a) => Map.WhenMatched Identity k (Set a) (Set a) (Set a)
addDiffSet = Map.zipWithMatched (const Set.difference)
removeDiffSet = Map.zipWithMatched (const (flip Set.difference))
getCycleLen :: H.Hash -> Transaction (Maybe Word64)
getCycleLen h = do
when debug $ traceM $ "\ngetCycleLen " ++ (Text.unpack . Base32Hex.toText $ H.toBase32Hex h)
runMaybeT do
-- actually want Nothing in case of non term/decl component hash
oid <- MaybeT (Q.loadObjectIdForAnyHash h)
-- todo: decodeComponentLengthOnly is unintentionally a hack that relies on
the fact the two things that references can refer to ( term and
components ) have the same basic serialized structure : first a format
-- byte that is always 0 for now, followed by a framed array representing
-- the strongly-connected component. :grimace:
lift (Q.expectObject oid decodeComponentLengthOnly)
| Get the ' C.DeclType . DeclType ' of a ' C.Reference . Id ' .
expectDeclTypeById :: C.Reference.Id -> Transaction C.Decl.DeclType
expectDeclTypeById =
fmap C.Decl.declType . expectDeclByReference
componentByObjectId :: Db.ObjectId -> Transaction [S.Reference.Id]
componentByObjectId id = do
when debug . traceM $ "Operations.componentByObjectId " ++ show id
len <- Q.expectObject id decodeComponentLengthOnly
pure [C.Reference.Id id i | i <- [0 .. len - 1]]
* Codebase operations
-- ** Saving & loading terms
loadTermComponent :: H.Hash -> MaybeT Transaction [(C.Term Symbol, C.Term.Type Symbol)]
loadTermComponent h = do
oid <- MaybeT (Q.loadObjectIdForAnyHash h)
S.Term.Term (S.Term.LocallyIndexedComponent elements) <- MaybeT (Q.loadTermObject oid decodeTermFormat)
lift . traverse (uncurry3 Q.s2cTermWithType) $ Foldable.toList elements
loadTermWithTypeByReference :: C.Reference.Id -> MaybeT Transaction (C.Term Symbol, C.Term.Type Symbol)
loadTermWithTypeByReference (C.Reference.Id h i) = do
oid <- MaybeT (Q.loadObjectIdForPrimaryHash h)
-- retrieve and deserialize the blob
(localIds, term, typ) <- MaybeT (Q.loadTermObject oid (decodeTermElementWithType i))
lift (Q.s2cTermWithType localIds term typ)
loadTermByReference :: C.Reference.Id -> MaybeT Transaction (C.Term Symbol)
loadTermByReference r@(C.Reference.Id h i) = do
when debug . traceM $ "loadTermByReference " ++ show r
oid <- MaybeT (Q.loadObjectIdForPrimaryHash h)
-- retrieve and deserialize the blob
(localIds, term) <- MaybeT (Q.loadTermObject oid (decodeTermElementDiscardingType i))
lift (s2cTerm localIds term)
loadTypeOfTermByTermReference :: C.Reference.Id -> MaybeT Transaction (C.Term.Type Symbol)
loadTypeOfTermByTermReference id@(C.Reference.Id h i) = do
when debug . traceM $ "loadTypeOfTermByTermReference " ++ show id
oid <- MaybeT (Q.loadObjectIdForPrimaryHash h)
-- retrieve and deserialize the blob
(localIds, typ) <- MaybeT (Q.loadTermObject oid (decodeTermElementDiscardingTerm i))
lift (s2cTypeOfTerm localIds typ)
s2cTerm :: LocalIds -> S.Term.Term -> Transaction (C.Term Symbol)
s2cTerm ids tm = do
(substText, substHash) <- Q.localIdsToLookups Q.expectText Q.expectPrimaryHashByObjectId ids
pure $ Q.x2cTerm substText substHash tm
s2cTypeOfTerm :: LocalIds -> S.Term.Type -> Transaction (C.Term.Type Symbol)
s2cTypeOfTerm ids tp = do
(substText, substHash) <- Q.localIdsToLookups Q.expectText Q.expectPrimaryHashByObjectId ids
pure $ Q.x2cTType substText substHash tp
-- *** Watch expressions
listWatches :: WatchKind -> Transaction [C.Reference.Id]
listWatches k = Q.loadWatchesByWatchKind k >>= traverse h2cReferenceId
-- | returns Nothing if the expression isn't cached.
loadWatch :: WatchKind -> C.Reference.Id -> MaybeT Transaction (C.Term Symbol)
loadWatch k r = do
r' <- C.Reference.idH (lift . Q.saveHashHash) r
S.Term.WatchResult wlids t <- MaybeT (Q.loadWatch k r' decodeWatchResultFormat)
lift (w2cTerm wlids t)
saveWatch :: WatchKind -> C.Reference.Id -> C.Term Symbol -> Transaction ()
saveWatch w r t = do
rs <- C.Reference.idH Q.saveHashHash r
wterm <- c2wTerm t
let bytes = S.putBytes S.putWatchResultFormat (uncurry S.Term.WatchResult wterm)
Q.saveWatch w rs bytes
c2wTerm :: C.Term Symbol -> Transaction (WatchLocalIds, S.Term.Term)
c2wTerm tm = Q.c2xTerm Q.saveText Q.saveHashHash tm Nothing <&> \(w, tm, _) -> (w, tm)
w2cTerm :: WatchLocalIds -> S.Term.Term -> Transaction (C.Term Symbol)
w2cTerm ids tm = do
(substText, substHash) <- Q.localIdsToLookups Q.expectText Q.expectHash ids
pure $ Q.x2cTerm substText substHash tm
-- ** Saving & loading type decls
loadDeclComponent :: H.Hash -> MaybeT Transaction [C.Decl Symbol]
loadDeclComponent h = do
oid <- MaybeT (Q.loadObjectIdForAnyHash h)
S.Decl.Decl (S.Decl.LocallyIndexedComponent elements) <- MaybeT (Q.loadDeclObject oid decodeDeclFormat)
lift . traverse (uncurry Q.s2cDecl) $ Foldable.toList elements
loadDeclByReference :: C.Reference.Id -> MaybeT Transaction (C.Decl Symbol)
loadDeclByReference r@(C.Reference.Id h i) = do
when debug . traceM $ "loadDeclByReference " ++ show r
oid <- MaybeT (Q.loadObjectIdForPrimaryHash h)
(localIds, decl) <- MaybeT (Q.loadDeclObject oid (decodeDeclElement i))
lift (Q.s2cDecl localIds decl)
expectDeclByReference :: C.Reference.Id -> Transaction (C.Decl Symbol)
expectDeclByReference r@(C.Reference.Id h i) = do
when debug . traceM $ "expectDeclByReference " ++ show r
-- retrieve the blob
Q.expectObjectIdForPrimaryHash h
>>= (\oid -> Q.expectDeclObject oid (decodeDeclElement i))
>>= uncurry Q.s2cDecl
-- * Branch transformation
s2cBranch :: S.DbBranch -> Transaction (C.Branch.Branch Transaction)
s2cBranch (S.Branch.Full.Branch tms tps patches children) =
C.Branch.Branch
<$> doTerms tms
<*> doTypes tps
<*> doPatches patches
<*> doChildren children
where
loadMetadataType :: S.Reference -> Transaction C.Reference
loadMetadataType = \case
C.ReferenceBuiltin tId ->
Q.expectTextCheck tId (Left . NeedTypeForBuiltinMetadata)
C.ReferenceDerived id ->
typeReferenceForTerm id >>= h2cReference
loadTypesForMetadata :: Set S.Reference -> Transaction (Map C.Reference C.Reference)
loadTypesForMetadata rs =
Map.fromList
<$> traverse
(\r -> (,) <$> s2cReference r <*> loadMetadataType r)
(Foldable.toList rs)
doTerms ::
Map Db.TextId (Map S.Referent S.DbMetadataSet) ->
Transaction (Map NameSegment (Map C.Referent (Transaction C.Branch.MdValues)))
doTerms =
Map.bitraverse
(fmap NameSegment . Q.expectText)
( Map.bitraverse s2cReferent \case
S.MetadataSet.Inline rs ->
pure $ C.Branch.MdValues <$> loadTypesForMetadata rs
)
doTypes ::
Map Db.TextId (Map S.Reference S.DbMetadataSet) ->
Transaction (Map NameSegment (Map C.Reference (Transaction C.Branch.MdValues)))
doTypes =
Map.bitraverse
(fmap NameSegment . Q.expectText)
( Map.bitraverse s2cReference \case
S.MetadataSet.Inline rs ->
pure $ C.Branch.MdValues <$> loadTypesForMetadata rs
)
doPatches ::
Map Db.TextId Db.PatchObjectId ->
Transaction (Map NameSegment (PatchHash, Transaction C.Branch.Patch))
doPatches = Map.bitraverse (fmap NameSegment . Q.expectText) \patchId -> do
h <- PatchHash <$> (Q.expectPrimaryHashByObjectId . Db.unPatchObjectId) patchId
pure (h, expectPatch patchId)
doChildren ::
Map Db.TextId (Db.BranchObjectId, Db.CausalHashId) ->
Transaction (Map NameSegment (C.Causal Transaction CausalHash BranchHash (C.Branch.Branch Transaction)))
doChildren = Map.bitraverse (fmap NameSegment . Q.expectText) \(boId, chId) ->
C.Causal
<$> Q.expectCausalHash chId
<*> expectValueHashByCausalHashId chId
<*> headParents chId
<*> pure (expectBranch boId)
where
headParents ::
Db.CausalHashId ->
Transaction
( Map
CausalHash
(Transaction (C.Causal Transaction CausalHash BranchHash (C.Branch.Branch Transaction)))
)
headParents chId = do
parentsChIds <- Q.loadCausalParents chId
fmap Map.fromList $ traverse pairParent parentsChIds
pairParent ::
Db.CausalHashId ->
Transaction
( CausalHash,
Transaction (C.Causal Transaction CausalHash BranchHash (C.Branch.Branch Transaction))
)
pairParent chId = do
h <- Q.expectCausalHash chId
pure (h, loadCausal chId)
loadCausal ::
Db.CausalHashId ->
Transaction (C.Causal Transaction CausalHash BranchHash (C.Branch.Branch Transaction))
loadCausal chId = do
C.Causal
<$> Q.expectCausalHash chId
<*> expectValueHashByCausalHashId chId
<*> headParents chId
<*> pure (loadValue chId)
loadValue :: Db.CausalHashId -> Transaction (C.Branch.Branch Transaction)
loadValue chId = do
boId <- Q.expectBranchObjectIdByCausalHashId chId
expectBranch boId
saveRootBranch ::
HashHandle ->
C.Branch.CausalBranch Transaction ->
Transaction (Db.BranchObjectId, Db.CausalHashId)
saveRootBranch hh c = do
when debug $ traceM $ "Operations.saveRootBranch " ++ show (C.causalHash c)
(boId, chId) <- saveBranch hh c
Q.setNamespaceRoot chId
pure (boId, chId)
-- saveBranch is kind of a "deep save causal"
-- we want a "shallow save causal" that could take a
forall m m CausalHash BranchHash e
--
-- data Identity a = Identity
-- e == ()
--
data C.Branch m = Branch
-- { terms :: Map NameSegment (Map Referent (m MdValues)),
-- types :: Map NameSegment (Map Reference (m MdValues)),
patches : : Map NameSegment ( PatchHash , m Patch ) ,
-- children :: Map NameSegment (Causal m)
-- }
--
U.Codebase . Sqlite . Branch . Full . Branch '
type ShallowBranch = Branch ' NameSegment Hash PatchHash CausalHash
data ShallowBranch causalHash patchHash = ShallowBranch
-- { terms :: Map NameSegment (Map Referent MdValues),
-- types :: Map NameSegment (Map Reference MdValues),
-- patches :: Map NameSegment patchHash,
-- children :: Map NameSegment causalHash
-- }
--
-- data Causal m hc he e = Causal
-- { causalHash :: hc,
-- valueHash :: he,
-- parents :: Map hc (m (Causal m hc he e)),
-- value :: m e
-- }
data ShallowCausal causalHash branchHash = ShallowCausal
-- { causalHash :: causalHash,
-- valueHash :: branchHash,
-- parents :: Set causalHash,
-- }
--
-- References, but also values
-- Shallow - Hash? representation of the database relationships
saveBranch ::
HashHandle ->
C.Branch.CausalBranch Transaction ->
Transaction (Db.BranchObjectId, Db.CausalHashId)
saveBranch hh (C.Causal hc he parents me) = do
when debug $ traceM $ "\nOperations.saveBranch \n hc = " ++ show hc ++ ",\n he = " ++ show he ++ ",\n parents = " ++ show (Map.keys parents)
-- Save the causal
(chId, bhId) <- whenNothingM (Q.loadCausalByCausalHash hc) do
-- if not exist, create these
chId <- Q.saveCausalHash hc
bhId <- Q.saveBranchHash he
parentCausalHashIds <-
-- so try to save each parent (recursively) before continuing to save hc
for (Map.toList parents) $ \(parentHash, mcausal) ->
-- check if we can short circuit the parent before loading it,
-- by checking if there are causal parents associated with hc
(flip Monad.fromMaybeM)
(Q.loadCausalHashIdByCausalHash parentHash)
(mcausal >>= fmap snd . saveBranch hh)
-- Save these CausalHashIds to the causal_parents table,
Q.saveCausal hh chId bhId parentCausalHashIds
pure (chId, bhId)
-- Save the namespace
boId <- flip Monad.fromMaybeM (Q.loadBranchObjectIdByBranchHashId bhId) do
branch <- me
dbBranch <- c2sBranch branch
stats <- namespaceStatsForDbBranch dbBranch
boId <- saveDbBranchUnderHashId hh bhId stats dbBranch
pure boId
pure (boId, chId)
where
c2sBranch :: C.Branch.Branch Transaction -> Transaction S.DbBranch
c2sBranch (C.Branch.Branch terms types patches children) =
S.Branch
<$> Map.bitraverse saveNameSegment (Map.bitraverse c2sReferent c2sMetadata) terms
<*> Map.bitraverse saveNameSegment (Map.bitraverse c2sReference c2sMetadata) types
<*> Map.bitraverse saveNameSegment savePatchObjectId patches
<*> Map.bitraverse saveNameSegment (saveBranch hh) children
saveNameSegment :: NameSegment -> Transaction Db.TextId
saveNameSegment = Q.saveText . NameSegment.toText
c2sMetadata :: Transaction C.Branch.MdValues -> Transaction S.Branch.Full.DbMetadataSet
c2sMetadata mm = do
C.Branch.MdValues m <- mm
S.Branch.Full.Inline <$> Set.traverse c2sReference (Map.keysSet m)
savePatchObjectId :: (PatchHash, Transaction C.Branch.Patch) -> Transaction Db.PatchObjectId
savePatchObjectId (h, mp) = do
Q.loadPatchObjectIdForPrimaryHash h >>= \case
Just patchOID -> pure patchOID
Nothing -> do
patch <- mp
savePatch hh h patch
expectRootCausal :: Transaction (C.Branch.CausalBranch Transaction)
expectRootCausal = Q.expectNamespaceRoot >>= expectCausalBranchByCausalHashId
loadCausalBranchByCausalHash :: CausalHash -> Transaction (Maybe (C.Branch.CausalBranch Transaction))
loadCausalBranchByCausalHash hc = do
Q.loadCausalHashIdByCausalHash hc >>= \case
Just chId -> Just <$> expectCausalBranchByCausalHashId chId
Nothing -> pure Nothing
expectCausalBranchByCausalHashId :: Db.CausalHashId -> Transaction (C.Branch.CausalBranch Transaction)
expectCausalBranchByCausalHashId id = do
hc <- Q.expectCausalHash id
hb <- expectValueHashByCausalHashId id
parentHashIds <- Q.loadCausalParents id
loadParents <- for parentHashIds \hId -> do
h <- Q.expectCausalHash hId
pure (h, expectCausalBranchByCausalHashId hId)
pure $ C.Causal hc hb (Map.fromList loadParents) (expectBranchByCausalHashId id)
expectCausalBranchByCausalHash :: CausalHash -> Transaction (C.Branch.CausalBranch Transaction)
expectCausalBranchByCausalHash hash = do
chId <- Q.expectCausalHashIdByCausalHash hash
expectCausalBranchByCausalHashId chId
expectBranchByCausalHashId :: Db.CausalHashId -> Transaction (C.Branch.Branch Transaction)
expectBranchByCausalHashId id = do
boId <- Q.expectBranchObjectIdByCausalHashId id
expectBranch boId
-- | Load a branch value given its causal hash id.
loadDbBranchByCausalHashId :: Db.CausalHashId -> Transaction (Maybe S.DbBranch)
loadDbBranchByCausalHashId causalHashId =
Q.loadBranchObjectIdByCausalHashId causalHashId >>= \case
Nothing -> pure Nothing
Just branchObjectId -> Just <$> expectDbBranch branchObjectId
expectBranchByBranchHashId :: Db.BranchHashId -> Transaction (C.Branch.Branch Transaction)
expectBranchByBranchHashId bhId = do
boId <- Q.expectBranchObjectIdByBranchHashId bhId
expectBranch boId
expectBranchByBranchHash :: BranchHash -> Transaction (C.Branch.Branch Transaction)
expectBranchByBranchHash bh = do
bhId <- Q.saveBranchHash bh
expectBranchByBranchHashId bhId
-- | Expect a branch value given its causal hash id.
expectDbBranchByCausalHashId :: Db.CausalHashId -> Transaction S.DbBranch
expectDbBranchByCausalHashId causalHashId = do
branchObjectId <- Q.expectBranchObjectIdByCausalHashId causalHashId
expectDbBranch branchObjectId
expectDbBranch :: Db.BranchObjectId -> Transaction S.DbBranch
expectDbBranch id =
deserializeBranchObject id >>= \case
S.BranchFormat.Full li f -> pure (S.BranchFormat.localToDbBranch li f)
S.BranchFormat.Diff r li d -> doDiff r [S.BranchFormat.localToDbDiff li d]
where
deserializeBranchObject :: Db.BranchObjectId -> Transaction S.BranchFormat
deserializeBranchObject id = do
when debug $ traceM $ "deserializeBranchObject " ++ show id
Q.expectNamespaceObject (Db.unBranchObjectId id) decodeBranchFormat
doDiff :: Db.BranchObjectId -> [S.Branch.Diff] -> Transaction S.DbBranch
doDiff ref ds =
deserializeBranchObject ref >>= \case
S.BranchFormat.Full li f -> pure (joinFull (S.BranchFormat.localToDbBranch li f) ds)
S.BranchFormat.Diff ref' li' d' -> doDiff ref' (S.BranchFormat.localToDbDiff li' d' : ds)
where
joinFull :: S.DbBranch -> [S.Branch.Diff] -> S.DbBranch
joinFull f [] = f
joinFull
(S.Branch.Full.Branch tms tps patches children)
(S.Branch.Diff tms' tps' patches' children' : ds) = joinFull f' ds
where
f' =
S.Branch.Full.Branch
(mergeDefns tms tms')
(mergeDefns tps tps')
(mergePatches patches patches')
(mergeChildren children children')
mergeChildren ::
(Ord ns) =>
Map ns (Db.BranchObjectId, Db.CausalHashId) ->
Map ns S.BranchDiff.ChildOp ->
Map ns (Db.BranchObjectId, Db.CausalHashId)
mergeChildren =
Map.merge
Map.preserveMissing
(Map.mapMissing fromChildOp)
(Map.zipWithMaybeMatched mergeChildOp)
mergeChildOp ::
ns ->
(Db.BranchObjectId, Db.CausalHashId) ->
S.BranchDiff.ChildOp ->
Maybe (Db.BranchObjectId, Db.CausalHashId)
mergeChildOp =
const . const \case
S.BranchDiff.ChildAddReplace id -> Just id
S.BranchDiff.ChildRemove -> Nothing
fromChildOp :: ns -> S.BranchDiff.ChildOp -> (Db.BranchObjectId, Db.CausalHashId)
fromChildOp = const \case
S.BranchDiff.ChildAddReplace id -> id
S.BranchDiff.ChildRemove -> error "diff tries to remove a nonexistent child"
mergePatches ::
(Ord ns) =>
Map ns Db.PatchObjectId ->
Map ns S.BranchDiff.PatchOp ->
Map ns Db.PatchObjectId
mergePatches =
Map.merge Map.preserveMissing (Map.mapMissing fromPatchOp) (Map.zipWithMaybeMatched mergePatchOp)
fromPatchOp :: ns -> S.BranchDiff.PatchOp -> Db.PatchObjectId
fromPatchOp = const \case
S.BranchDiff.PatchAddReplace id -> id
S.BranchDiff.PatchRemove -> error "diff tries to remove a nonexistent child"
mergePatchOp :: ns -> Db.PatchObjectId -> S.BranchDiff.PatchOp -> Maybe Db.PatchObjectId
mergePatchOp =
const . const \case
S.BranchDiff.PatchAddReplace id -> Just id
S.BranchDiff.PatchRemove -> Nothing
mergeDefns ::
(Ord ns, Ord r) =>
Map ns (Map r S.MetadataSet.DbMetadataSet) ->
Map ns (Map r S.BranchDiff.DefinitionOp) ->
Map ns (Map r S.MetadataSet.DbMetadataSet)
mergeDefns =
Map.merge
Map.preserveMissing
(Map.mapMissing (const (fmap fromDefnOp)))
(Map.zipWithMatched (const mergeDefnOp))
fromDefnOp :: S.BranchDiff.DefinitionOp -> S.MetadataSet.DbMetadataSet
fromDefnOp = \case
S.Branch.Diff.AddDefWithMetadata md -> S.MetadataSet.Inline md
S.Branch.Diff.RemoveDef -> error "diff tries to remove a nonexistent definition"
S.Branch.Diff.AlterDefMetadata _md -> error "diff tries to change metadata for a nonexistent definition"
mergeDefnOp ::
(Ord r) =>
Map r S.MetadataSet.DbMetadataSet ->
Map r S.BranchDiff.DefinitionOp ->
Map r S.MetadataSet.DbMetadataSet
mergeDefnOp =
Map.merge
Map.preserveMissing
(Map.mapMissing (const fromDefnOp))
(Map.zipWithMaybeMatched (const mergeDefnOp'))
mergeDefnOp' ::
S.MetadataSet.DbMetadataSet ->
S.BranchDiff.DefinitionOp ->
Maybe S.MetadataSet.DbMetadataSet
mergeDefnOp' (S.MetadataSet.Inline md) = \case
S.Branch.Diff.AddDefWithMetadata _md ->
error "diff tries to create a child that already exists"
S.Branch.Diff.RemoveDef -> Nothing
S.Branch.Diff.AlterDefMetadata md' ->
let (Set.fromList -> adds, Set.fromList -> removes) = S.BranchDiff.addsRemoves md'
in Just . S.MetadataSet.Inline $ (Set.union adds $ Set.difference md removes)
-- | Save a 'S.DbBranch', given its hash (which the caller is expected to produce from the branch).
--
-- Note: long-standing question: should this package depend on the hashing package? (If so, we would only need to take
-- the DbBranch, and hash internally).
saveDbBranch ::
HashHandle ->
BranchHash ->
C.Branch.NamespaceStats ->
S.DbBranch ->
Transaction Db.BranchObjectId
saveDbBranch hh hash stats branch = do
hashId <- Q.saveBranchHash hash
saveDbBranchUnderHashId hh hashId stats branch
-- | Variant of 'saveDbBranch' that might be preferred by callers that already have a hash id, not a hash.
saveDbBranchUnderHashId ::
HashHandle ->
Db.BranchHashId ->
C.Branch.NamespaceStats ->
S.DbBranch ->
Transaction Db.BranchObjectId
saveDbBranchUnderHashId hh bhId@(Db.unBranchHashId -> hashId) stats branch = do
let (localBranchIds, localBranch) = LocalizeObject.localizeBranch branch
when debug $
traceM $
"saveBranchObject\n\tid = "
++ show bhId
++ "\n\tli = "
++ show localBranchIds
++ "\n\tlBranch = "
++ show localBranch
let bytes = S.putBytes S.putBranchFormat $ S.BranchFormat.Full localBranchIds localBranch
oId <- Q.saveObject hh hashId ObjectType.Namespace bytes
Q.saveNamespaceStats bhId stats
pure $ Db.BranchObjectId oId
expectBranch :: Db.BranchObjectId -> Transaction (C.Branch.Branch Transaction)
expectBranch id =
expectDbBranch id >>= s2cBranch
-- * Patch transformation
expectPatch :: Db.PatchObjectId -> Transaction C.Branch.Patch
expectPatch patchId =
expectDbPatch patchId >>= s2cPatch
expectDbPatch :: Db.PatchObjectId -> Transaction S.Patch
expectDbPatch patchId =
deserializePatchObject patchId >>= \case
S.Patch.Format.Full li p -> pure (S.Patch.Format.localPatchToPatch li p)
S.Patch.Format.Diff ref li d -> doDiff ref [S.Patch.Format.localPatchDiffToPatchDiff li d]
where
doDiff :: Db.PatchObjectId -> [S.PatchDiff] -> Transaction S.Patch
doDiff ref ds =
deserializePatchObject ref >>= \case
S.Patch.Format.Full li f -> pure (S.Patch.Format.applyPatchDiffs (S.Patch.Format.localPatchToPatch li f) ds)
S.Patch.Format.Diff ref' li' d' -> doDiff ref' (S.Patch.Format.localPatchDiffToPatchDiff li' d' : ds)
savePatch ::
HashHandle ->
PatchHash ->
C.Branch.Patch ->
Transaction Db.PatchObjectId
savePatch hh h c = do
(li, lPatch) <- LocalizeObject.localizePatch <$> c2sPatch c
saveDbPatch hh h (S.Patch.Format.Full li lPatch)
saveDbPatch ::
HashHandle ->
PatchHash ->
S.PatchFormat ->
Transaction Db.PatchObjectId
saveDbPatch hh hash patch = do
hashId <- Q.saveHashHash (unPatchHash hash)
let bytes = S.putBytes S.putPatchFormat patch
Db.PatchObjectId <$> Q.saveObject hh hashId ObjectType.Patch bytes
s2cPatch :: S.Patch -> Transaction C.Branch.Patch
s2cPatch (S.Patch termEdits typeEdits) =
C.Branch.Patch
<$> Map.bitraverse h2cReferent (Set.traverse s2cTermEdit) termEdits
<*> Map.bitraverse h2cReference (Set.traverse s2cTypeEdit) typeEdits
deserializePatchObject :: Db.PatchObjectId -> Transaction S.PatchFormat
deserializePatchObject id = do
when debug $ traceM $ "Operations.deserializePatchObject " ++ show id
Q.expectPatchObject (Db.unPatchObjectId id) decodePatchFormat
lca :: CausalHash -> CausalHash -> Transaction (Maybe CausalHash)
lca h1 h2 = runMaybeT do
chId1 <- MaybeT $ Q.loadCausalHashIdByCausalHash h1
chId2 <- MaybeT $ Q.loadCausalHashIdByCausalHash h2
chId3 <- MaybeT $ Q.lca chId1 chId2
lift (Q.expectCausalHash chId3)
before :: CausalHash -> CausalHash -> Transaction (Maybe Bool)
before h1 h2 = runMaybeT do
chId2 <- MaybeT $ Q.loadCausalHashIdByCausalHash h2
lift (Q.loadCausalHashIdByCausalHash h1) >>= \case
Just chId1 -> lift (Q.before chId1 chId2)
Nothing -> pure False
-- * Searches
termsHavingType :: C.Reference -> Transaction (Set C.Referent.Id)
termsHavingType cTypeRef =
runMaybeT (c2hReference cTypeRef) >>= \case
Nothing -> pure Set.empty
Just sTypeRef -> do
sIds <- Q.getReferentsByType sTypeRef
set <- traverse s2cReferentId sIds
pure (Set.fromList set)
typeReferenceForTerm :: S.Reference.Id -> Transaction S.ReferenceH
typeReferenceForTerm = Q.getTypeReferenceForReferent . C.Referent.RefId
termsMentioningType :: C.Reference -> Transaction (Set C.Referent.Id)
termsMentioningType cTypeRef =
runMaybeT (c2hReference cTypeRef) >>= \case
Nothing -> pure Set.empty
Just sTypeRef -> do
sIds <- Q.getReferentsByTypeMention sTypeRef
set <- traverse s2cReferentId sIds
pure (Set.fromList set)
something kind of funny here . first , we do n't need to enumerate all the reference pos if we 're just picking one
second , it would be nice if we could leave these as S.References a little longer
-- so that we remember how to blow up if they're missing
componentReferencesByPrefix :: ObjectType.ObjectType -> Text -> Maybe C.Reference.Pos -> Transaction [S.Reference.Id]
componentReferencesByPrefix ot b32prefix pos = do
oIds :: [Db.ObjectId] <- Q.objectIdByBase32Prefix ot b32prefix
let test = maybe (const True) (==) pos
let filterComponent l = [x | x@(C.Reference.Id _ pos) <- l, test pos]
join <$> traverse (fmap filterComponent . componentByObjectId) oIds
-- | Get the set of user-defined terms whose hash matches the given prefix.
termReferencesByPrefix :: Text -> Maybe Word64 -> Transaction [C.Reference.Id]
termReferencesByPrefix t w =
componentReferencesByPrefix ObjectType.TermComponent t w
>>= traverse (C.Reference.idH Q.expectPrimaryHashByObjectId)
declReferencesByPrefix :: Text -> Maybe Word64 -> Transaction [C.Reference.Id]
declReferencesByPrefix t w =
componentReferencesByPrefix ObjectType.DeclComponent t w
>>= traverse (C.Reference.idH Q.expectPrimaryHashByObjectId)
termReferentsByPrefix :: Text -> Maybe Word64 -> Transaction [C.Referent.Id]
termReferentsByPrefix b32prefix pos =
fmap C.Referent.RefId <$> termReferencesByPrefix b32prefix pos
-- todo: simplify this if we stop caring about constructor type
todo : remove the cycle length once we drop it from Unison . Reference
declReferentsByPrefix ::
Text ->
Maybe C.Reference.Pos ->
Maybe ConstructorId ->
Transaction [(H.Hash, C.Reference.Pos, C.DeclType, [C.Decl.ConstructorId])]
declReferentsByPrefix b32prefix pos cid = do
componentReferencesByPrefix ObjectType.DeclComponent b32prefix pos
>>= traverse (loadConstructors cid)
where
loadConstructors ::
Maybe Word64 ->
S.Reference.Id ->
Transaction (H.Hash, C.Reference.Pos, C.DeclType, [ConstructorId])
loadConstructors cid rid@(C.Reference.Id oId pos) = do
(dt, ctorCount) <- getDeclCtorCount rid
h <- Q.expectPrimaryHashByObjectId oId
let cids =
case cid of
Nothing -> take ctorCount [0 :: ConstructorId ..]
Just cid -> if fromIntegral cid < ctorCount then [cid] else []
pure (h, pos, dt, cids)
getDeclCtorCount :: S.Reference.Id -> Transaction (C.Decl.DeclType, Int)
getDeclCtorCount id@(C.Reference.Id r i) = do
when debug $ traceM $ "getDeclCtorCount " ++ show id
(_localIds, decl) <- Q.expectDeclObject r (decodeDeclElement i)
pure (C.Decl.declType decl, length (C.Decl.constructorTypes decl))
namespaceHashesByPrefix :: ShortNamespaceHash -> Transaction (Set BranchHash)
namespaceHashesByPrefix (ShortNamespaceHash b32prefix) = do
hashIds <- Q.namespaceHashIdByBase32Prefix b32prefix
hashes <- traverse (Q.expectHash . Db.unBranchHashId) hashIds
pure $ Set.fromList . map BranchHash $ hashes
causalHashesByPrefix :: ShortCausalHash -> Transaction (Set CausalHash)
causalHashesByPrefix (ShortCausalHash b32prefix) = do
hashIds <- Q.causalHashIdByBase32Prefix b32prefix
hashes <- traverse (Q.expectHash . Db.unCausalHashId) hashIds
pure $ Set.fromList . map CausalHash $ hashes
-- | returns a list of known definitions referencing `r`
dependents :: Q.DependentsSelector -> C.Reference -> Transaction (Set C.Reference.Id)
dependents selector r = do
mr <- case r of
C.ReferenceBuiltin {} -> pure (Just r)
C.ReferenceDerived id_ ->
objectExistsForHash (view C.idH id_) <&> \case
True -> Just r
False -> Nothing
case mr of
Nothing -> pure mempty
Just r -> do
r' <- c2sReference r
sIds <- Q.getDependentsForDependency selector r'
Set.traverse s2cReferenceId sIds
-- | returns a list of known definitions referencing `h`
dependentsOfComponent :: H.Hash -> Transaction (Set C.Reference.Id)
dependentsOfComponent h = do
oId <- Q.expectObjectIdForPrimaryHash h
sIds :: [S.Reference.Id] <- Q.getDependentsForDependencyComponent oId
cIds <- traverse s2cReferenceId sIds
pure $ Set.fromList cIds
| returns empty set for unknown inputs ; does n't distinguish between term and
derivedDependencies :: C.Reference.Id -> Transaction (Set C.Reference.Id)
derivedDependencies cid = do
sid <- c2sReferenceId cid
sids <- Q.getDependencyIdsForDependent sid
cids <- traverse s2cReferenceId sids
pure $ Set.fromList cids
-- | Apply a set of name updates to an existing index.
buildNameLookupForBranchHash ::
-- The existing name lookup index to copy before applying the diff.
-- If Nothing, run the diff against an empty index.
-- If Just, the name lookup must exist or an error will be thrown.
Maybe BranchHash ->
BranchHash ->
-- | (add terms, remove terms)
([S.NamedRef (C.Referent, Maybe C.ConstructorType)], [S.NamedRef C.Referent]) ->
-- | (add types, remove types)
([S.NamedRef C.Reference], [S.NamedRef C.Reference]) ->
Transaction ()
buildNameLookupForBranchHash mayExistingBranchIndex newBranchHash (newTermNames, removedTermNames) (newTypeNames, removedTypeNames) = do
newBranchHashId <- Q.saveBranchHash newBranchHash
Q.trackNewBranchHashNameLookup newBranchHashId
case mayExistingBranchIndex of
Nothing -> pure ()
Just existingBranchIndex -> do
unlessM (checkBranchHashNameLookupExists existingBranchIndex) $ error "buildNameLookupForBranchHash: existingBranchIndex was provided, but no index was found for that branch hash."
existingBranchHashId <- Q.saveBranchHash existingBranchIndex
Q.copyScopedNameLookup existingBranchHashId newBranchHashId
Q.removeScopedTermNames newBranchHashId ((fmap c2sTextReferent <$> removedTermNames))
Q.removeScopedTypeNames newBranchHashId ((fmap c2sTextReference <$> removedTypeNames))
Q.insertScopedTermNames newBranchHashId (fmap (c2sTextReferent *** fmap c2sConstructorType) <$> newTermNames)
Q.insertScopedTypeNames newBranchHashId (fmap c2sTextReference <$> newTypeNames)
-- | Check whether we've already got an index for a given causal hash.
checkBranchHashNameLookupExists :: BranchHash -> Transaction Bool
checkBranchHashNameLookupExists bh = do
bhId <- Q.saveBranchHash bh
Q.checkBranchHashNameLookupExists bhId
data NamesByPath = NamesByPath
{ termNamesInPath :: [S.NamedRef (C.Referent, Maybe C.ConstructorType)],
typeNamesInPath :: [S.NamedRef C.Reference]
}
-- | Get all the term and type names for the root namespace from the lookup table.
-- Requires that an index for this branch hash already exists, which is currently
-- only true on Share.
rootNamesByPath ::
-- | A relative namespace string, e.g. Just "base.List"
Maybe Text ->
Transaction NamesByPath
rootNamesByPath path = do
bhId <- Q.expectNamespaceRootBranchHashId
termNamesInPath <- Q.termNamesWithinNamespace bhId path
typeNamesInPath <- Q.typeNamesWithinNamespace bhId path
pure $
NamesByPath
{ termNamesInPath = convertTerms <$> termNamesInPath,
typeNamesInPath = convertTypes <$> typeNamesInPath
}
where
convertTerms = fmap (bimap s2cTextReferent (fmap s2cConstructorType))
convertTypes = fmap s2cTextReference
-- | Looks up statistics for a given branch, if none exist, we compute them and save them
-- then return them.
expectNamespaceStatsByHash :: BranchHash -> Transaction C.Branch.NamespaceStats
expectNamespaceStatsByHash bh = do
bhId <- Q.saveBranchHash bh
expectNamespaceStatsByHashId bhId
-- | Looks up statistics for a given branch, if none exist, we compute them and save them
-- then return them.
expectNamespaceStatsByHashId :: Db.BranchHashId -> Transaction C.Branch.NamespaceStats
expectNamespaceStatsByHashId bhId = do
Q.loadNamespaceStatsByHashId bhId `whenNothingM` do
boId <- Db.BranchObjectId <$> Q.expectObjectIdForPrimaryHashId (Db.unBranchHashId bhId)
dbBranch <- expectDbBranch boId
stats <- namespaceStatsForDbBranch dbBranch
Q.saveNamespaceStats bhId stats
pure stats
namespaceStatsForDbBranch :: S.DbBranch -> Transaction NamespaceStats
namespaceStatsForDbBranch S.Branch {terms, types, patches, children} = do
childStats <- for children \(_boId, chId) -> do
bhId <- Q.expectCausalValueHashId chId
expectNamespaceStatsByHashId bhId
pure $
NamespaceStats
{ numContainedTerms =
let childTermCount = sumOf (folded . to numContainedTerms) childStats
termCount = lengthOf (folded . folded) terms
in childTermCount + termCount,
numContainedTypes =
let childTypeCount = sumOf (folded . to numContainedTypes) childStats
typeCount = lengthOf (folded . folded) types
in childTypeCount + typeCount,
numContainedPatches =
let childPatchCount = sumOf (folded . to numContainedPatches) childStats
patchCount = Map.size patches
in childPatchCount + patchCount
}
| Gets the specified number of reflog entries in chronological order , most recent first .
getReflog :: Int -> Transaction [Reflog.Entry CausalHash Text]
getReflog numEntries = do
entries <- Q.getReflog numEntries
traverse (bitraverse Q.expectCausalHash pure) entries
appendReflog :: Reflog.Entry CausalHash Text -> Transaction ()
appendReflog entry = do
dbEntry <- (bitraverse Q.saveCausalHash pure) entry
Q.appendReflog dbEntry
| null | https://raw.githubusercontent.com/unisonweb/unison/649215726982e20b45952f514ad20def213c86ea/codebase2/codebase-sqlite/U/Codebase/Sqlite/Operations.hs | haskell | * branches
* terms
* decls
* terms/decls
* patches
* test for stuff in codebase
* watch expression cache
* indexes
** nearest common ancestor
** prefix index
** dependents index
** type index
** type mentions index
** name lookup index
* reflog
* low-level stuff
* somewhat unexpectedly unused definitions
* Error handling
* Database lookups
| Load the causal hash at the given path from the root.
| Expect the causal hash at the given path from the root.
* Reference transformations
** read existing references
| Assumes that a derived reference would already exist in the database
(by virtue of dependencies being stored before dependents), but does
not assume a builtin reference would.
** convert and save references
** Edits transformations
| produces a diff
diff = full - ref; full = diff + ref
add: present in full. but absent in ref.
remove: present in ref. but absent in full.
things that are present in full but absent in ref
actually want Nothing in case of non term/decl component hash
todo: decodeComponentLengthOnly is unintentionally a hack that relies on
byte that is always 0 for now, followed by a framed array representing
the strongly-connected component. :grimace:
** Saving & loading terms
retrieve and deserialize the blob
retrieve and deserialize the blob
retrieve and deserialize the blob
*** Watch expressions
| returns Nothing if the expression isn't cached.
** Saving & loading type decls
retrieve the blob
* Branch transformation
saveBranch is kind of a "deep save causal"
we want a "shallow save causal" that could take a
data Identity a = Identity
e == ()
{ terms :: Map NameSegment (Map Referent (m MdValues)),
types :: Map NameSegment (Map Reference (m MdValues)),
children :: Map NameSegment (Causal m)
}
{ terms :: Map NameSegment (Map Referent MdValues),
types :: Map NameSegment (Map Reference MdValues),
patches :: Map NameSegment patchHash,
children :: Map NameSegment causalHash
}
data Causal m hc he e = Causal
{ causalHash :: hc,
valueHash :: he,
parents :: Map hc (m (Causal m hc he e)),
value :: m e
}
{ causalHash :: causalHash,
valueHash :: branchHash,
parents :: Set causalHash,
}
References, but also values
Shallow - Hash? representation of the database relationships
Save the causal
if not exist, create these
so try to save each parent (recursively) before continuing to save hc
check if we can short circuit the parent before loading it,
by checking if there are causal parents associated with hc
Save these CausalHashIds to the causal_parents table,
Save the namespace
| Load a branch value given its causal hash id.
| Expect a branch value given its causal hash id.
| Save a 'S.DbBranch', given its hash (which the caller is expected to produce from the branch).
Note: long-standing question: should this package depend on the hashing package? (If so, we would only need to take
the DbBranch, and hash internally).
| Variant of 'saveDbBranch' that might be preferred by callers that already have a hash id, not a hash.
* Patch transformation
* Searches
so that we remember how to blow up if they're missing
| Get the set of user-defined terms whose hash matches the given prefix.
todo: simplify this if we stop caring about constructor type
| returns a list of known definitions referencing `r`
| returns a list of known definitions referencing `h`
| Apply a set of name updates to an existing index.
The existing name lookup index to copy before applying the diff.
If Nothing, run the diff against an empty index.
If Just, the name lookup must exist or an error will be thrown.
| (add terms, remove terms)
| (add types, remove types)
| Check whether we've already got an index for a given causal hash.
| Get all the term and type names for the root namespace from the lookup table.
Requires that an index for this branch hash already exists, which is currently
only true on Share.
| A relative namespace string, e.g. Just "base.List"
| Looks up statistics for a given branch, if none exist, we compute them and save them
then return them.
| Looks up statistics for a given branch, if none exist, we compute them and save them
then return them. | module U.Codebase.Sqlite.Operations
saveRootBranch,
loadRootCausalHash,
expectRootCausalHash,
expectRootCausal,
expectRootBranchHash,
loadCausalHashAtPath,
expectCausalHashAtPath,
saveBranch,
loadCausalBranchByCausalHash,
expectCausalBranchByCausalHash,
expectBranchByBranchHash,
expectNamespaceStatsByHash,
expectNamespaceStatsByHashId,
Q.saveTermComponent,
loadTermComponent,
loadTermByReference,
loadTypeOfTermByTermReference,
Q.saveDeclComponent,
loadDeclComponent,
loadDeclByReference,
expectDeclTypeById,
getCycleLen,
savePatch,
expectPatch,
objectExistsForHash,
saveWatch,
loadWatch,
listWatches,
Q.clearWatches,
before,
lca,
componentReferencesByPrefix,
termReferentsByPrefix,
declReferentsByPrefix,
causalHashesByPrefix,
dependents,
dependentsOfComponent,
Q.addTypeToIndexForTerm,
termsHavingType,
Q.addTypeMentionsToIndexForTerm,
termsMentioningType,
rootNamesByPath,
NamesByPath (..),
checkBranchHashNameLookupExists,
buildNameLookupForBranchHash,
getReflog,
appendReflog,
expectDbBranch,
saveDbBranch,
saveDbBranchUnderHashId,
expectDbPatch,
saveDbPatch,
expectDbBranchByCausalHashId,
namespaceStatsForDbBranch,
c2sReferenceId,
c2sReferentId,
diffPatch,
decodeTermElementWithType,
loadTermWithTypeByReference,
Q.s2cTermWithType,
Q.s2cDecl,
declReferencesByPrefix,
namespaceHashesByPrefix,
derivedDependencies,
)
where
import Control.Lens hiding (children)
import qualified Control.Monad.Extra as Monad
import Data.Bitraversable (Bitraversable (bitraverse))
import qualified Data.Foldable as Foldable
import qualified Data.Map as Map
import qualified Data.Map.Merge.Lazy as Map
import qualified Data.Set as Set
import qualified Data.Text as Text
import Data.Tuple.Extra (uncurry3, (***))
import U.Codebase.Branch.Type (NamespaceStats (..))
import qualified U.Codebase.Branch.Type as C.Branch
import qualified U.Codebase.Causal as C
import U.Codebase.Decl (ConstructorId)
import qualified U.Codebase.Decl as C
import qualified U.Codebase.Decl as C.Decl
import U.Codebase.HashTags (BranchHash (..), CausalHash (..), PatchHash (..))
import qualified U.Codebase.Reference as C
import qualified U.Codebase.Reference as C.Reference
import qualified U.Codebase.Referent as C
import qualified U.Codebase.Referent as C.Referent
import qualified U.Codebase.Reflog as Reflog
import U.Codebase.ShortHash (ShortCausalHash (..), ShortNamespaceHash (..))
import qualified U.Codebase.Sqlite.Branch.Diff as S.Branch
import qualified U.Codebase.Sqlite.Branch.Diff as S.Branch.Diff
import qualified U.Codebase.Sqlite.Branch.Diff as S.BranchDiff
import qualified U.Codebase.Sqlite.Branch.Format as S
import qualified U.Codebase.Sqlite.Branch.Format as S.BranchFormat
import qualified U.Codebase.Sqlite.Branch.Full as S
import qualified U.Codebase.Sqlite.Branch.Full as S.Branch.Full
import qualified U.Codebase.Sqlite.Branch.Full as S.MetadataSet
import qualified U.Codebase.Sqlite.DbId as Db
import qualified U.Codebase.Sqlite.Decl.Format as S.Decl
import U.Codebase.Sqlite.Decode
import U.Codebase.Sqlite.HashHandle (HashHandle (..))
import U.Codebase.Sqlite.LocalIds
( LocalIds,
WatchLocalIds,
)
import qualified U.Codebase.Sqlite.LocalizeObject as LocalizeObject
import qualified U.Codebase.Sqlite.NamedRef as S
import qualified U.Codebase.Sqlite.ObjectType as ObjectType
import qualified U.Codebase.Sqlite.Patch.Diff as S
import qualified U.Codebase.Sqlite.Patch.Format as S
import qualified U.Codebase.Sqlite.Patch.Format as S.Patch.Format
import qualified U.Codebase.Sqlite.Patch.Full as S (LocalPatch, Patch, Patch' (..))
import qualified U.Codebase.Sqlite.Patch.TermEdit as S
import qualified U.Codebase.Sqlite.Patch.TermEdit as S.TermEdit
import qualified U.Codebase.Sqlite.Patch.TypeEdit as S
import qualified U.Codebase.Sqlite.Patch.TypeEdit as S.TypeEdit
import qualified U.Codebase.Sqlite.Queries as Q
import qualified U.Codebase.Sqlite.Reference as S
import qualified U.Codebase.Sqlite.Reference as S.Reference
import qualified U.Codebase.Sqlite.Referent as S
import qualified U.Codebase.Sqlite.Referent as S.Referent
import qualified U.Codebase.Sqlite.Serialization as S
import U.Codebase.Sqlite.Symbol (Symbol)
import qualified U.Codebase.Sqlite.Term.Format as S.Term
import qualified U.Codebase.Term as C
import qualified U.Codebase.Term as C.Term
import qualified U.Codebase.TermEdit as C
import qualified U.Codebase.TermEdit as C.TermEdit
import qualified U.Codebase.TypeEdit as C
import qualified U.Codebase.TypeEdit as C.TypeEdit
import U.Codebase.WatchKind (WatchKind)
import qualified U.Util.Base32Hex as Base32Hex
import qualified U.Util.Serialization as S
import qualified Unison.Hash as H
import qualified Unison.Hash32 as Hash32
import Unison.NameSegment (NameSegment (NameSegment))
import qualified Unison.NameSegment as NameSegment
import Unison.Prelude
import Unison.Sqlite
import qualified Unison.Util.Map as Map
import qualified Unison.Util.Set as Set
debug :: Bool
debug = False
newtype NeedTypeForBuiltinMetadata
= NeedTypeForBuiltinMetadata Text
deriving stock (Show)
deriving anyclass (SqliteExceptionReason)
objectExistsForHash :: H.Hash -> Transaction Bool
objectExistsForHash h =
isJust <$> runMaybeT do
id <- MaybeT . Q.loadHashId . Hash32.fromHash $ h
MaybeT $ Q.loadObjectIdForAnyHashId id
expectValueHashByCausalHashId :: Db.CausalHashId -> Transaction BranchHash
expectValueHashByCausalHashId = loadValueHashById <=< Q.expectCausalValueHashId
where
loadValueHashById :: Db.BranchHashId -> Transaction BranchHash
loadValueHashById = fmap BranchHash . Q.expectHash . Db.unBranchHashId
expectRootCausalHash :: Transaction CausalHash
expectRootCausalHash = Q.expectCausalHash =<< Q.expectNamespaceRoot
expectRootBranchHash :: Transaction BranchHash
expectRootBranchHash = do
rootCausalHashId <- Q.expectNamespaceRoot
expectValueHashByCausalHashId rootCausalHashId
loadRootCausalHash :: Transaction (Maybe CausalHash)
loadRootCausalHash =
runMaybeT $
lift . Q.expectCausalHash =<< MaybeT Q.loadNamespaceRoot
FIXME should we move some Path type here ?
loadCausalHashAtPath :: [Text] -> Transaction (Maybe CausalHash)
loadCausalHashAtPath =
let go :: Db.CausalHashId -> [Text] -> MaybeT Transaction CausalHash
go hashId = \case
[] -> lift (Q.expectCausalHash hashId)
t : ts -> do
tid <- MaybeT (Q.loadTextId t)
S.Branch {children} <- MaybeT (loadDbBranchByCausalHashId hashId)
(_, hashId') <- MaybeT (pure (Map.lookup tid children))
go hashId' ts
in \path -> do
hashId <- Q.expectNamespaceRoot
runMaybeT (go hashId path)
FIXME should we move some Path type here ?
expectCausalHashAtPath :: [Text] -> Transaction CausalHash
expectCausalHashAtPath =
let go :: Db.CausalHashId -> [Text] -> Transaction CausalHash
go hashId = \case
[] -> Q.expectCausalHash hashId
t : ts -> do
tid <- Q.expectTextId t
S.Branch {children} <- expectDbBranchByCausalHashId hashId
let (_, hashId') = children Map.! tid
go hashId' ts
in \path -> do
hashId <- Q.expectNamespaceRoot
go hashId path
c2sReference :: C.Reference -> Transaction S.Reference
c2sReference = bitraverse Q.saveText Q.expectObjectIdForPrimaryHash
c2sTextReference :: C.Reference -> S.TextReference
c2sTextReference = bimap id H.toBase32Hex
s2cReference :: S.Reference -> Transaction C.Reference
s2cReference = bitraverse Q.expectText Q.expectPrimaryHashByObjectId
s2cTextReference :: S.TextReference -> C.Reference
s2cTextReference = bimap id H.fromBase32Hex
c2sReferenceId :: C.Reference.Id -> Transaction S.Reference.Id
c2sReferenceId = C.Reference.idH Q.expectObjectIdForPrimaryHash
s2cReferenceId :: S.Reference.Id -> Transaction C.Reference.Id
s2cReferenceId = C.Reference.idH Q.expectPrimaryHashByObjectId
h2cReferenceId :: S.Reference.IdH -> Transaction C.Reference.Id
h2cReferenceId = C.Reference.idH Q.expectHash
h2cReference :: S.ReferenceH -> Transaction C.Reference
h2cReference = bitraverse Q.expectText Q.expectHash
c2hReference :: C.Reference -> MaybeT Transaction S.ReferenceH
c2hReference = bitraverse (MaybeT . Q.loadTextId) (MaybeT . Q.loadHashIdByHash)
s2cReferent :: S.Referent -> Transaction C.Referent
s2cReferent = bitraverse s2cReference s2cReference
s2cTextReferent :: S.TextReferent -> C.Referent
s2cTextReferent = bimap s2cTextReference s2cTextReference
s2cConstructorType :: S.ConstructorType -> C.ConstructorType
s2cConstructorType = \case
S.DataConstructor -> C.DataConstructor
S.EffectConstructor -> C.EffectConstructor
c2sConstructorType :: C.ConstructorType -> S.ConstructorType
c2sConstructorType = \case
C.DataConstructor -> S.DataConstructor
C.EffectConstructor -> S.EffectConstructor
s2cReferentId :: S.Referent.Id -> Transaction C.Referent.Id
s2cReferentId = bitraverse Q.expectPrimaryHashByObjectId Q.expectPrimaryHashByObjectId
c2sReferent :: C.Referent -> Transaction S.Referent
c2sReferent = bitraverse c2sReference c2sReference
c2sTextReferent :: C.Referent -> S.TextReferent
c2sTextReferent = bimap c2sTextReference c2sTextReference
c2sReferentId :: C.Referent.Id -> Transaction S.Referent.Id
c2sReferentId = bitraverse Q.expectObjectIdForPrimaryHash Q.expectObjectIdForPrimaryHash
h2cReferent :: S.ReferentH -> Transaction C.Referent
h2cReferent = bitraverse h2cReference h2cReference
saveReferentH :: C.Referent -> Transaction S.ReferentH
saveReferentH = bitraverse Q.saveReferenceH Q.saveReferenceH
s2cTermEdit :: S.TermEdit -> Transaction C.TermEdit
s2cTermEdit = \case
S.TermEdit.Replace r t -> C.TermEdit.Replace <$> s2cReferent r <*> pure (s2cTyping t)
S.TermEdit.Deprecate -> pure C.TermEdit.Deprecate
s2cTyping :: S.TermEdit.Typing -> C.TermEdit.Typing
s2cTyping = \case
S.TermEdit.Same -> C.TermEdit.Same
S.TermEdit.Subtype -> C.TermEdit.Subtype
S.TermEdit.Different -> C.TermEdit.Different
c2sTyping :: C.TermEdit.Typing -> S.TermEdit.Typing
c2sTyping = \case
C.TermEdit.Same -> S.TermEdit.Same
C.TermEdit.Subtype -> S.TermEdit.Subtype
C.TermEdit.Different -> S.TermEdit.Different
s2cTypeEdit :: S.TypeEdit -> Transaction C.TypeEdit
s2cTypeEdit = \case
S.TypeEdit.Replace r -> C.TypeEdit.Replace <$> s2cReference r
S.TypeEdit.Deprecate -> pure C.TypeEdit.Deprecate
| assumes that all relevant defns are already in the DB
c2sPatch :: C.Branch.Patch -> Transaction S.Patch
c2sPatch (C.Branch.Patch termEdits typeEdits) =
S.Patch
<$> Map.bitraverse saveReferentH (Set.traverse c2sTermEdit) termEdits
<*> Map.bitraverse Q.saveReferenceH (Set.traverse c2sTypeEdit) typeEdits
where
c2sTermEdit = \case
C.TermEdit.Replace r t -> S.TermEdit.Replace <$> c2sReferent r <*> pure (c2sTyping t)
C.TermEdit.Deprecate -> pure S.TermEdit.Deprecate
c2sTypeEdit = \case
C.TypeEdit.Replace r -> S.TypeEdit.Replace <$> c2sReference r
C.TypeEdit.Deprecate -> pure S.TypeEdit.Deprecate
diffPatch :: S.LocalPatch -> S.LocalPatch -> S.LocalPatchDiff
diffPatch (S.Patch fullTerms fullTypes) (S.Patch refTerms refTypes) =
(S.PatchDiff addTermEdits addTypeEdits removeTermEdits removeTypeEdits)
where
addTermEdits = Map.merge Map.preserveMissing Map.dropMissing addDiffSet fullTerms refTerms
addTypeEdits = Map.merge Map.preserveMissing Map.dropMissing addDiffSet fullTypes refTypes
removeTermEdits = Map.merge Map.dropMissing Map.preserveMissing removeDiffSet fullTerms refTerms
removeTypeEdits = Map.merge Map.dropMissing Map.preserveMissing removeDiffSet fullTypes refTypes
addDiffSet,
removeDiffSet ::
(Ord k, Ord a) => Map.WhenMatched Identity k (Set a) (Set a) (Set a)
addDiffSet = Map.zipWithMatched (const Set.difference)
removeDiffSet = Map.zipWithMatched (const (flip Set.difference))
getCycleLen :: H.Hash -> Transaction (Maybe Word64)
getCycleLen h = do
when debug $ traceM $ "\ngetCycleLen " ++ (Text.unpack . Base32Hex.toText $ H.toBase32Hex h)
runMaybeT do
oid <- MaybeT (Q.loadObjectIdForAnyHash h)
the fact the two things that references can refer to ( term and
components ) have the same basic serialized structure : first a format
lift (Q.expectObject oid decodeComponentLengthOnly)
| Get the ' C.DeclType . DeclType ' of a ' C.Reference . Id ' .
expectDeclTypeById :: C.Reference.Id -> Transaction C.Decl.DeclType
expectDeclTypeById =
fmap C.Decl.declType . expectDeclByReference
componentByObjectId :: Db.ObjectId -> Transaction [S.Reference.Id]
componentByObjectId id = do
when debug . traceM $ "Operations.componentByObjectId " ++ show id
len <- Q.expectObject id decodeComponentLengthOnly
pure [C.Reference.Id id i | i <- [0 .. len - 1]]
* Codebase operations
loadTermComponent :: H.Hash -> MaybeT Transaction [(C.Term Symbol, C.Term.Type Symbol)]
loadTermComponent h = do
oid <- MaybeT (Q.loadObjectIdForAnyHash h)
S.Term.Term (S.Term.LocallyIndexedComponent elements) <- MaybeT (Q.loadTermObject oid decodeTermFormat)
lift . traverse (uncurry3 Q.s2cTermWithType) $ Foldable.toList elements
loadTermWithTypeByReference :: C.Reference.Id -> MaybeT Transaction (C.Term Symbol, C.Term.Type Symbol)
loadTermWithTypeByReference (C.Reference.Id h i) = do
oid <- MaybeT (Q.loadObjectIdForPrimaryHash h)
(localIds, term, typ) <- MaybeT (Q.loadTermObject oid (decodeTermElementWithType i))
lift (Q.s2cTermWithType localIds term typ)
loadTermByReference :: C.Reference.Id -> MaybeT Transaction (C.Term Symbol)
loadTermByReference r@(C.Reference.Id h i) = do
when debug . traceM $ "loadTermByReference " ++ show r
oid <- MaybeT (Q.loadObjectIdForPrimaryHash h)
(localIds, term) <- MaybeT (Q.loadTermObject oid (decodeTermElementDiscardingType i))
lift (s2cTerm localIds term)
loadTypeOfTermByTermReference :: C.Reference.Id -> MaybeT Transaction (C.Term.Type Symbol)
loadTypeOfTermByTermReference id@(C.Reference.Id h i) = do
when debug . traceM $ "loadTypeOfTermByTermReference " ++ show id
oid <- MaybeT (Q.loadObjectIdForPrimaryHash h)
(localIds, typ) <- MaybeT (Q.loadTermObject oid (decodeTermElementDiscardingTerm i))
lift (s2cTypeOfTerm localIds typ)
s2cTerm :: LocalIds -> S.Term.Term -> Transaction (C.Term Symbol)
s2cTerm ids tm = do
(substText, substHash) <- Q.localIdsToLookups Q.expectText Q.expectPrimaryHashByObjectId ids
pure $ Q.x2cTerm substText substHash tm
s2cTypeOfTerm :: LocalIds -> S.Term.Type -> Transaction (C.Term.Type Symbol)
s2cTypeOfTerm ids tp = do
(substText, substHash) <- Q.localIdsToLookups Q.expectText Q.expectPrimaryHashByObjectId ids
pure $ Q.x2cTType substText substHash tp
listWatches :: WatchKind -> Transaction [C.Reference.Id]
listWatches k = Q.loadWatchesByWatchKind k >>= traverse h2cReferenceId
loadWatch :: WatchKind -> C.Reference.Id -> MaybeT Transaction (C.Term Symbol)
loadWatch k r = do
r' <- C.Reference.idH (lift . Q.saveHashHash) r
S.Term.WatchResult wlids t <- MaybeT (Q.loadWatch k r' decodeWatchResultFormat)
lift (w2cTerm wlids t)
saveWatch :: WatchKind -> C.Reference.Id -> C.Term Symbol -> Transaction ()
saveWatch w r t = do
rs <- C.Reference.idH Q.saveHashHash r
wterm <- c2wTerm t
let bytes = S.putBytes S.putWatchResultFormat (uncurry S.Term.WatchResult wterm)
Q.saveWatch w rs bytes
c2wTerm :: C.Term Symbol -> Transaction (WatchLocalIds, S.Term.Term)
c2wTerm tm = Q.c2xTerm Q.saveText Q.saveHashHash tm Nothing <&> \(w, tm, _) -> (w, tm)
w2cTerm :: WatchLocalIds -> S.Term.Term -> Transaction (C.Term Symbol)
w2cTerm ids tm = do
(substText, substHash) <- Q.localIdsToLookups Q.expectText Q.expectHash ids
pure $ Q.x2cTerm substText substHash tm
loadDeclComponent :: H.Hash -> MaybeT Transaction [C.Decl Symbol]
loadDeclComponent h = do
oid <- MaybeT (Q.loadObjectIdForAnyHash h)
S.Decl.Decl (S.Decl.LocallyIndexedComponent elements) <- MaybeT (Q.loadDeclObject oid decodeDeclFormat)
lift . traverse (uncurry Q.s2cDecl) $ Foldable.toList elements
loadDeclByReference :: C.Reference.Id -> MaybeT Transaction (C.Decl Symbol)
loadDeclByReference r@(C.Reference.Id h i) = do
when debug . traceM $ "loadDeclByReference " ++ show r
oid <- MaybeT (Q.loadObjectIdForPrimaryHash h)
(localIds, decl) <- MaybeT (Q.loadDeclObject oid (decodeDeclElement i))
lift (Q.s2cDecl localIds decl)
expectDeclByReference :: C.Reference.Id -> Transaction (C.Decl Symbol)
expectDeclByReference r@(C.Reference.Id h i) = do
when debug . traceM $ "expectDeclByReference " ++ show r
Q.expectObjectIdForPrimaryHash h
>>= (\oid -> Q.expectDeclObject oid (decodeDeclElement i))
>>= uncurry Q.s2cDecl
s2cBranch :: S.DbBranch -> Transaction (C.Branch.Branch Transaction)
s2cBranch (S.Branch.Full.Branch tms tps patches children) =
C.Branch.Branch
<$> doTerms tms
<*> doTypes tps
<*> doPatches patches
<*> doChildren children
where
loadMetadataType :: S.Reference -> Transaction C.Reference
loadMetadataType = \case
C.ReferenceBuiltin tId ->
Q.expectTextCheck tId (Left . NeedTypeForBuiltinMetadata)
C.ReferenceDerived id ->
typeReferenceForTerm id >>= h2cReference
loadTypesForMetadata :: Set S.Reference -> Transaction (Map C.Reference C.Reference)
loadTypesForMetadata rs =
Map.fromList
<$> traverse
(\r -> (,) <$> s2cReference r <*> loadMetadataType r)
(Foldable.toList rs)
doTerms ::
Map Db.TextId (Map S.Referent S.DbMetadataSet) ->
Transaction (Map NameSegment (Map C.Referent (Transaction C.Branch.MdValues)))
doTerms =
Map.bitraverse
(fmap NameSegment . Q.expectText)
( Map.bitraverse s2cReferent \case
S.MetadataSet.Inline rs ->
pure $ C.Branch.MdValues <$> loadTypesForMetadata rs
)
doTypes ::
Map Db.TextId (Map S.Reference S.DbMetadataSet) ->
Transaction (Map NameSegment (Map C.Reference (Transaction C.Branch.MdValues)))
doTypes =
Map.bitraverse
(fmap NameSegment . Q.expectText)
( Map.bitraverse s2cReference \case
S.MetadataSet.Inline rs ->
pure $ C.Branch.MdValues <$> loadTypesForMetadata rs
)
doPatches ::
Map Db.TextId Db.PatchObjectId ->
Transaction (Map NameSegment (PatchHash, Transaction C.Branch.Patch))
doPatches = Map.bitraverse (fmap NameSegment . Q.expectText) \patchId -> do
h <- PatchHash <$> (Q.expectPrimaryHashByObjectId . Db.unPatchObjectId) patchId
pure (h, expectPatch patchId)
doChildren ::
Map Db.TextId (Db.BranchObjectId, Db.CausalHashId) ->
Transaction (Map NameSegment (C.Causal Transaction CausalHash BranchHash (C.Branch.Branch Transaction)))
doChildren = Map.bitraverse (fmap NameSegment . Q.expectText) \(boId, chId) ->
C.Causal
<$> Q.expectCausalHash chId
<*> expectValueHashByCausalHashId chId
<*> headParents chId
<*> pure (expectBranch boId)
where
headParents ::
Db.CausalHashId ->
Transaction
( Map
CausalHash
(Transaction (C.Causal Transaction CausalHash BranchHash (C.Branch.Branch Transaction)))
)
headParents chId = do
parentsChIds <- Q.loadCausalParents chId
fmap Map.fromList $ traverse pairParent parentsChIds
pairParent ::
Db.CausalHashId ->
Transaction
( CausalHash,
Transaction (C.Causal Transaction CausalHash BranchHash (C.Branch.Branch Transaction))
)
pairParent chId = do
h <- Q.expectCausalHash chId
pure (h, loadCausal chId)
loadCausal ::
Db.CausalHashId ->
Transaction (C.Causal Transaction CausalHash BranchHash (C.Branch.Branch Transaction))
loadCausal chId = do
C.Causal
<$> Q.expectCausalHash chId
<*> expectValueHashByCausalHashId chId
<*> headParents chId
<*> pure (loadValue chId)
loadValue :: Db.CausalHashId -> Transaction (C.Branch.Branch Transaction)
loadValue chId = do
boId <- Q.expectBranchObjectIdByCausalHashId chId
expectBranch boId
saveRootBranch ::
HashHandle ->
C.Branch.CausalBranch Transaction ->
Transaction (Db.BranchObjectId, Db.CausalHashId)
saveRootBranch hh c = do
when debug $ traceM $ "Operations.saveRootBranch " ++ show (C.causalHash c)
(boId, chId) <- saveBranch hh c
Q.setNamespaceRoot chId
pure (boId, chId)
forall m m CausalHash BranchHash e
data C.Branch m = Branch
patches : : Map NameSegment ( PatchHash , m Patch ) ,
U.Codebase . Sqlite . Branch . Full . Branch '
type ShallowBranch = Branch ' NameSegment Hash PatchHash CausalHash
data ShallowBranch causalHash patchHash = ShallowBranch
data ShallowCausal causalHash branchHash = ShallowCausal
saveBranch ::
HashHandle ->
C.Branch.CausalBranch Transaction ->
Transaction (Db.BranchObjectId, Db.CausalHashId)
saveBranch hh (C.Causal hc he parents me) = do
when debug $ traceM $ "\nOperations.saveBranch \n hc = " ++ show hc ++ ",\n he = " ++ show he ++ ",\n parents = " ++ show (Map.keys parents)
(chId, bhId) <- whenNothingM (Q.loadCausalByCausalHash hc) do
chId <- Q.saveCausalHash hc
bhId <- Q.saveBranchHash he
parentCausalHashIds <-
for (Map.toList parents) $ \(parentHash, mcausal) ->
(flip Monad.fromMaybeM)
(Q.loadCausalHashIdByCausalHash parentHash)
(mcausal >>= fmap snd . saveBranch hh)
Q.saveCausal hh chId bhId parentCausalHashIds
pure (chId, bhId)
boId <- flip Monad.fromMaybeM (Q.loadBranchObjectIdByBranchHashId bhId) do
branch <- me
dbBranch <- c2sBranch branch
stats <- namespaceStatsForDbBranch dbBranch
boId <- saveDbBranchUnderHashId hh bhId stats dbBranch
pure boId
pure (boId, chId)
where
c2sBranch :: C.Branch.Branch Transaction -> Transaction S.DbBranch
c2sBranch (C.Branch.Branch terms types patches children) =
S.Branch
<$> Map.bitraverse saveNameSegment (Map.bitraverse c2sReferent c2sMetadata) terms
<*> Map.bitraverse saveNameSegment (Map.bitraverse c2sReference c2sMetadata) types
<*> Map.bitraverse saveNameSegment savePatchObjectId patches
<*> Map.bitraverse saveNameSegment (saveBranch hh) children
saveNameSegment :: NameSegment -> Transaction Db.TextId
saveNameSegment = Q.saveText . NameSegment.toText
c2sMetadata :: Transaction C.Branch.MdValues -> Transaction S.Branch.Full.DbMetadataSet
c2sMetadata mm = do
C.Branch.MdValues m <- mm
S.Branch.Full.Inline <$> Set.traverse c2sReference (Map.keysSet m)
savePatchObjectId :: (PatchHash, Transaction C.Branch.Patch) -> Transaction Db.PatchObjectId
savePatchObjectId (h, mp) = do
Q.loadPatchObjectIdForPrimaryHash h >>= \case
Just patchOID -> pure patchOID
Nothing -> do
patch <- mp
savePatch hh h patch
expectRootCausal :: Transaction (C.Branch.CausalBranch Transaction)
expectRootCausal = Q.expectNamespaceRoot >>= expectCausalBranchByCausalHashId
loadCausalBranchByCausalHash :: CausalHash -> Transaction (Maybe (C.Branch.CausalBranch Transaction))
loadCausalBranchByCausalHash hc = do
Q.loadCausalHashIdByCausalHash hc >>= \case
Just chId -> Just <$> expectCausalBranchByCausalHashId chId
Nothing -> pure Nothing
expectCausalBranchByCausalHashId :: Db.CausalHashId -> Transaction (C.Branch.CausalBranch Transaction)
expectCausalBranchByCausalHashId id = do
hc <- Q.expectCausalHash id
hb <- expectValueHashByCausalHashId id
parentHashIds <- Q.loadCausalParents id
loadParents <- for parentHashIds \hId -> do
h <- Q.expectCausalHash hId
pure (h, expectCausalBranchByCausalHashId hId)
pure $ C.Causal hc hb (Map.fromList loadParents) (expectBranchByCausalHashId id)
expectCausalBranchByCausalHash :: CausalHash -> Transaction (C.Branch.CausalBranch Transaction)
expectCausalBranchByCausalHash hash = do
chId <- Q.expectCausalHashIdByCausalHash hash
expectCausalBranchByCausalHashId chId
expectBranchByCausalHashId :: Db.CausalHashId -> Transaction (C.Branch.Branch Transaction)
expectBranchByCausalHashId id = do
boId <- Q.expectBranchObjectIdByCausalHashId id
expectBranch boId
loadDbBranchByCausalHashId :: Db.CausalHashId -> Transaction (Maybe S.DbBranch)
loadDbBranchByCausalHashId causalHashId =
Q.loadBranchObjectIdByCausalHashId causalHashId >>= \case
Nothing -> pure Nothing
Just branchObjectId -> Just <$> expectDbBranch branchObjectId
expectBranchByBranchHashId :: Db.BranchHashId -> Transaction (C.Branch.Branch Transaction)
expectBranchByBranchHashId bhId = do
boId <- Q.expectBranchObjectIdByBranchHashId bhId
expectBranch boId
expectBranchByBranchHash :: BranchHash -> Transaction (C.Branch.Branch Transaction)
expectBranchByBranchHash bh = do
bhId <- Q.saveBranchHash bh
expectBranchByBranchHashId bhId
expectDbBranchByCausalHashId :: Db.CausalHashId -> Transaction S.DbBranch
expectDbBranchByCausalHashId causalHashId = do
branchObjectId <- Q.expectBranchObjectIdByCausalHashId causalHashId
expectDbBranch branchObjectId
expectDbBranch :: Db.BranchObjectId -> Transaction S.DbBranch
expectDbBranch id =
deserializeBranchObject id >>= \case
S.BranchFormat.Full li f -> pure (S.BranchFormat.localToDbBranch li f)
S.BranchFormat.Diff r li d -> doDiff r [S.BranchFormat.localToDbDiff li d]
where
deserializeBranchObject :: Db.BranchObjectId -> Transaction S.BranchFormat
deserializeBranchObject id = do
when debug $ traceM $ "deserializeBranchObject " ++ show id
Q.expectNamespaceObject (Db.unBranchObjectId id) decodeBranchFormat
doDiff :: Db.BranchObjectId -> [S.Branch.Diff] -> Transaction S.DbBranch
doDiff ref ds =
deserializeBranchObject ref >>= \case
S.BranchFormat.Full li f -> pure (joinFull (S.BranchFormat.localToDbBranch li f) ds)
S.BranchFormat.Diff ref' li' d' -> doDiff ref' (S.BranchFormat.localToDbDiff li' d' : ds)
where
joinFull :: S.DbBranch -> [S.Branch.Diff] -> S.DbBranch
joinFull f [] = f
joinFull
(S.Branch.Full.Branch tms tps patches children)
(S.Branch.Diff tms' tps' patches' children' : ds) = joinFull f' ds
where
f' =
S.Branch.Full.Branch
(mergeDefns tms tms')
(mergeDefns tps tps')
(mergePatches patches patches')
(mergeChildren children children')
mergeChildren ::
(Ord ns) =>
Map ns (Db.BranchObjectId, Db.CausalHashId) ->
Map ns S.BranchDiff.ChildOp ->
Map ns (Db.BranchObjectId, Db.CausalHashId)
mergeChildren =
Map.merge
Map.preserveMissing
(Map.mapMissing fromChildOp)
(Map.zipWithMaybeMatched mergeChildOp)
mergeChildOp ::
ns ->
(Db.BranchObjectId, Db.CausalHashId) ->
S.BranchDiff.ChildOp ->
Maybe (Db.BranchObjectId, Db.CausalHashId)
mergeChildOp =
const . const \case
S.BranchDiff.ChildAddReplace id -> Just id
S.BranchDiff.ChildRemove -> Nothing
fromChildOp :: ns -> S.BranchDiff.ChildOp -> (Db.BranchObjectId, Db.CausalHashId)
fromChildOp = const \case
S.BranchDiff.ChildAddReplace id -> id
S.BranchDiff.ChildRemove -> error "diff tries to remove a nonexistent child"
mergePatches ::
(Ord ns) =>
Map ns Db.PatchObjectId ->
Map ns S.BranchDiff.PatchOp ->
Map ns Db.PatchObjectId
mergePatches =
Map.merge Map.preserveMissing (Map.mapMissing fromPatchOp) (Map.zipWithMaybeMatched mergePatchOp)
fromPatchOp :: ns -> S.BranchDiff.PatchOp -> Db.PatchObjectId
fromPatchOp = const \case
S.BranchDiff.PatchAddReplace id -> id
S.BranchDiff.PatchRemove -> error "diff tries to remove a nonexistent child"
mergePatchOp :: ns -> Db.PatchObjectId -> S.BranchDiff.PatchOp -> Maybe Db.PatchObjectId
mergePatchOp =
const . const \case
S.BranchDiff.PatchAddReplace id -> Just id
S.BranchDiff.PatchRemove -> Nothing
mergeDefns ::
(Ord ns, Ord r) =>
Map ns (Map r S.MetadataSet.DbMetadataSet) ->
Map ns (Map r S.BranchDiff.DefinitionOp) ->
Map ns (Map r S.MetadataSet.DbMetadataSet)
mergeDefns =
Map.merge
Map.preserveMissing
(Map.mapMissing (const (fmap fromDefnOp)))
(Map.zipWithMatched (const mergeDefnOp))
fromDefnOp :: S.BranchDiff.DefinitionOp -> S.MetadataSet.DbMetadataSet
fromDefnOp = \case
S.Branch.Diff.AddDefWithMetadata md -> S.MetadataSet.Inline md
S.Branch.Diff.RemoveDef -> error "diff tries to remove a nonexistent definition"
S.Branch.Diff.AlterDefMetadata _md -> error "diff tries to change metadata for a nonexistent definition"
mergeDefnOp ::
(Ord r) =>
Map r S.MetadataSet.DbMetadataSet ->
Map r S.BranchDiff.DefinitionOp ->
Map r S.MetadataSet.DbMetadataSet
mergeDefnOp =
Map.merge
Map.preserveMissing
(Map.mapMissing (const fromDefnOp))
(Map.zipWithMaybeMatched (const mergeDefnOp'))
mergeDefnOp' ::
S.MetadataSet.DbMetadataSet ->
S.BranchDiff.DefinitionOp ->
Maybe S.MetadataSet.DbMetadataSet
mergeDefnOp' (S.MetadataSet.Inline md) = \case
S.Branch.Diff.AddDefWithMetadata _md ->
error "diff tries to create a child that already exists"
S.Branch.Diff.RemoveDef -> Nothing
S.Branch.Diff.AlterDefMetadata md' ->
let (Set.fromList -> adds, Set.fromList -> removes) = S.BranchDiff.addsRemoves md'
in Just . S.MetadataSet.Inline $ (Set.union adds $ Set.difference md removes)
saveDbBranch ::
HashHandle ->
BranchHash ->
C.Branch.NamespaceStats ->
S.DbBranch ->
Transaction Db.BranchObjectId
saveDbBranch hh hash stats branch = do
hashId <- Q.saveBranchHash hash
saveDbBranchUnderHashId hh hashId stats branch
saveDbBranchUnderHashId ::
HashHandle ->
Db.BranchHashId ->
C.Branch.NamespaceStats ->
S.DbBranch ->
Transaction Db.BranchObjectId
saveDbBranchUnderHashId hh bhId@(Db.unBranchHashId -> hashId) stats branch = do
let (localBranchIds, localBranch) = LocalizeObject.localizeBranch branch
when debug $
traceM $
"saveBranchObject\n\tid = "
++ show bhId
++ "\n\tli = "
++ show localBranchIds
++ "\n\tlBranch = "
++ show localBranch
let bytes = S.putBytes S.putBranchFormat $ S.BranchFormat.Full localBranchIds localBranch
oId <- Q.saveObject hh hashId ObjectType.Namespace bytes
Q.saveNamespaceStats bhId stats
pure $ Db.BranchObjectId oId
expectBranch :: Db.BranchObjectId -> Transaction (C.Branch.Branch Transaction)
expectBranch id =
expectDbBranch id >>= s2cBranch
expectPatch :: Db.PatchObjectId -> Transaction C.Branch.Patch
expectPatch patchId =
expectDbPatch patchId >>= s2cPatch
expectDbPatch :: Db.PatchObjectId -> Transaction S.Patch
expectDbPatch patchId =
deserializePatchObject patchId >>= \case
S.Patch.Format.Full li p -> pure (S.Patch.Format.localPatchToPatch li p)
S.Patch.Format.Diff ref li d -> doDiff ref [S.Patch.Format.localPatchDiffToPatchDiff li d]
where
doDiff :: Db.PatchObjectId -> [S.PatchDiff] -> Transaction S.Patch
doDiff ref ds =
deserializePatchObject ref >>= \case
S.Patch.Format.Full li f -> pure (S.Patch.Format.applyPatchDiffs (S.Patch.Format.localPatchToPatch li f) ds)
S.Patch.Format.Diff ref' li' d' -> doDiff ref' (S.Patch.Format.localPatchDiffToPatchDiff li' d' : ds)
savePatch ::
HashHandle ->
PatchHash ->
C.Branch.Patch ->
Transaction Db.PatchObjectId
savePatch hh h c = do
(li, lPatch) <- LocalizeObject.localizePatch <$> c2sPatch c
saveDbPatch hh h (S.Patch.Format.Full li lPatch)
saveDbPatch ::
HashHandle ->
PatchHash ->
S.PatchFormat ->
Transaction Db.PatchObjectId
saveDbPatch hh hash patch = do
hashId <- Q.saveHashHash (unPatchHash hash)
let bytes = S.putBytes S.putPatchFormat patch
Db.PatchObjectId <$> Q.saveObject hh hashId ObjectType.Patch bytes
s2cPatch :: S.Patch -> Transaction C.Branch.Patch
s2cPatch (S.Patch termEdits typeEdits) =
C.Branch.Patch
<$> Map.bitraverse h2cReferent (Set.traverse s2cTermEdit) termEdits
<*> Map.bitraverse h2cReference (Set.traverse s2cTypeEdit) typeEdits
deserializePatchObject :: Db.PatchObjectId -> Transaction S.PatchFormat
deserializePatchObject id = do
when debug $ traceM $ "Operations.deserializePatchObject " ++ show id
Q.expectPatchObject (Db.unPatchObjectId id) decodePatchFormat
lca :: CausalHash -> CausalHash -> Transaction (Maybe CausalHash)
lca h1 h2 = runMaybeT do
chId1 <- MaybeT $ Q.loadCausalHashIdByCausalHash h1
chId2 <- MaybeT $ Q.loadCausalHashIdByCausalHash h2
chId3 <- MaybeT $ Q.lca chId1 chId2
lift (Q.expectCausalHash chId3)
before :: CausalHash -> CausalHash -> Transaction (Maybe Bool)
before h1 h2 = runMaybeT do
chId2 <- MaybeT $ Q.loadCausalHashIdByCausalHash h2
lift (Q.loadCausalHashIdByCausalHash h1) >>= \case
Just chId1 -> lift (Q.before chId1 chId2)
Nothing -> pure False
termsHavingType :: C.Reference -> Transaction (Set C.Referent.Id)
termsHavingType cTypeRef =
runMaybeT (c2hReference cTypeRef) >>= \case
Nothing -> pure Set.empty
Just sTypeRef -> do
sIds <- Q.getReferentsByType sTypeRef
set <- traverse s2cReferentId sIds
pure (Set.fromList set)
typeReferenceForTerm :: S.Reference.Id -> Transaction S.ReferenceH
typeReferenceForTerm = Q.getTypeReferenceForReferent . C.Referent.RefId
termsMentioningType :: C.Reference -> Transaction (Set C.Referent.Id)
termsMentioningType cTypeRef =
runMaybeT (c2hReference cTypeRef) >>= \case
Nothing -> pure Set.empty
Just sTypeRef -> do
sIds <- Q.getReferentsByTypeMention sTypeRef
set <- traverse s2cReferentId sIds
pure (Set.fromList set)
something kind of funny here . first , we do n't need to enumerate all the reference pos if we 're just picking one
second , it would be nice if we could leave these as S.References a little longer
componentReferencesByPrefix :: ObjectType.ObjectType -> Text -> Maybe C.Reference.Pos -> Transaction [S.Reference.Id]
componentReferencesByPrefix ot b32prefix pos = do
oIds :: [Db.ObjectId] <- Q.objectIdByBase32Prefix ot b32prefix
let test = maybe (const True) (==) pos
let filterComponent l = [x | x@(C.Reference.Id _ pos) <- l, test pos]
join <$> traverse (fmap filterComponent . componentByObjectId) oIds
termReferencesByPrefix :: Text -> Maybe Word64 -> Transaction [C.Reference.Id]
termReferencesByPrefix t w =
componentReferencesByPrefix ObjectType.TermComponent t w
>>= traverse (C.Reference.idH Q.expectPrimaryHashByObjectId)
declReferencesByPrefix :: Text -> Maybe Word64 -> Transaction [C.Reference.Id]
declReferencesByPrefix t w =
componentReferencesByPrefix ObjectType.DeclComponent t w
>>= traverse (C.Reference.idH Q.expectPrimaryHashByObjectId)
termReferentsByPrefix :: Text -> Maybe Word64 -> Transaction [C.Referent.Id]
termReferentsByPrefix b32prefix pos =
fmap C.Referent.RefId <$> termReferencesByPrefix b32prefix pos
todo : remove the cycle length once we drop it from Unison . Reference
declReferentsByPrefix ::
Text ->
Maybe C.Reference.Pos ->
Maybe ConstructorId ->
Transaction [(H.Hash, C.Reference.Pos, C.DeclType, [C.Decl.ConstructorId])]
declReferentsByPrefix b32prefix pos cid = do
componentReferencesByPrefix ObjectType.DeclComponent b32prefix pos
>>= traverse (loadConstructors cid)
where
loadConstructors ::
Maybe Word64 ->
S.Reference.Id ->
Transaction (H.Hash, C.Reference.Pos, C.DeclType, [ConstructorId])
loadConstructors cid rid@(C.Reference.Id oId pos) = do
(dt, ctorCount) <- getDeclCtorCount rid
h <- Q.expectPrimaryHashByObjectId oId
let cids =
case cid of
Nothing -> take ctorCount [0 :: ConstructorId ..]
Just cid -> if fromIntegral cid < ctorCount then [cid] else []
pure (h, pos, dt, cids)
getDeclCtorCount :: S.Reference.Id -> Transaction (C.Decl.DeclType, Int)
getDeclCtorCount id@(C.Reference.Id r i) = do
when debug $ traceM $ "getDeclCtorCount " ++ show id
(_localIds, decl) <- Q.expectDeclObject r (decodeDeclElement i)
pure (C.Decl.declType decl, length (C.Decl.constructorTypes decl))
namespaceHashesByPrefix :: ShortNamespaceHash -> Transaction (Set BranchHash)
namespaceHashesByPrefix (ShortNamespaceHash b32prefix) = do
hashIds <- Q.namespaceHashIdByBase32Prefix b32prefix
hashes <- traverse (Q.expectHash . Db.unBranchHashId) hashIds
pure $ Set.fromList . map BranchHash $ hashes
causalHashesByPrefix :: ShortCausalHash -> Transaction (Set CausalHash)
causalHashesByPrefix (ShortCausalHash b32prefix) = do
hashIds <- Q.causalHashIdByBase32Prefix b32prefix
hashes <- traverse (Q.expectHash . Db.unCausalHashId) hashIds
pure $ Set.fromList . map CausalHash $ hashes
dependents :: Q.DependentsSelector -> C.Reference -> Transaction (Set C.Reference.Id)
dependents selector r = do
mr <- case r of
C.ReferenceBuiltin {} -> pure (Just r)
C.ReferenceDerived id_ ->
objectExistsForHash (view C.idH id_) <&> \case
True -> Just r
False -> Nothing
case mr of
Nothing -> pure mempty
Just r -> do
r' <- c2sReference r
sIds <- Q.getDependentsForDependency selector r'
Set.traverse s2cReferenceId sIds
dependentsOfComponent :: H.Hash -> Transaction (Set C.Reference.Id)
dependentsOfComponent h = do
oId <- Q.expectObjectIdForPrimaryHash h
sIds :: [S.Reference.Id] <- Q.getDependentsForDependencyComponent oId
cIds <- traverse s2cReferenceId sIds
pure $ Set.fromList cIds
| returns empty set for unknown inputs ; does n't distinguish between term and
derivedDependencies :: C.Reference.Id -> Transaction (Set C.Reference.Id)
derivedDependencies cid = do
sid <- c2sReferenceId cid
sids <- Q.getDependencyIdsForDependent sid
cids <- traverse s2cReferenceId sids
pure $ Set.fromList cids
buildNameLookupForBranchHash ::
Maybe BranchHash ->
BranchHash ->
([S.NamedRef (C.Referent, Maybe C.ConstructorType)], [S.NamedRef C.Referent]) ->
([S.NamedRef C.Reference], [S.NamedRef C.Reference]) ->
Transaction ()
buildNameLookupForBranchHash mayExistingBranchIndex newBranchHash (newTermNames, removedTermNames) (newTypeNames, removedTypeNames) = do
newBranchHashId <- Q.saveBranchHash newBranchHash
Q.trackNewBranchHashNameLookup newBranchHashId
case mayExistingBranchIndex of
Nothing -> pure ()
Just existingBranchIndex -> do
unlessM (checkBranchHashNameLookupExists existingBranchIndex) $ error "buildNameLookupForBranchHash: existingBranchIndex was provided, but no index was found for that branch hash."
existingBranchHashId <- Q.saveBranchHash existingBranchIndex
Q.copyScopedNameLookup existingBranchHashId newBranchHashId
Q.removeScopedTermNames newBranchHashId ((fmap c2sTextReferent <$> removedTermNames))
Q.removeScopedTypeNames newBranchHashId ((fmap c2sTextReference <$> removedTypeNames))
Q.insertScopedTermNames newBranchHashId (fmap (c2sTextReferent *** fmap c2sConstructorType) <$> newTermNames)
Q.insertScopedTypeNames newBranchHashId (fmap c2sTextReference <$> newTypeNames)
checkBranchHashNameLookupExists :: BranchHash -> Transaction Bool
checkBranchHashNameLookupExists bh = do
bhId <- Q.saveBranchHash bh
Q.checkBranchHashNameLookupExists bhId
data NamesByPath = NamesByPath
{ termNamesInPath :: [S.NamedRef (C.Referent, Maybe C.ConstructorType)],
typeNamesInPath :: [S.NamedRef C.Reference]
}
rootNamesByPath ::
Maybe Text ->
Transaction NamesByPath
rootNamesByPath path = do
bhId <- Q.expectNamespaceRootBranchHashId
termNamesInPath <- Q.termNamesWithinNamespace bhId path
typeNamesInPath <- Q.typeNamesWithinNamespace bhId path
pure $
NamesByPath
{ termNamesInPath = convertTerms <$> termNamesInPath,
typeNamesInPath = convertTypes <$> typeNamesInPath
}
where
convertTerms = fmap (bimap s2cTextReferent (fmap s2cConstructorType))
convertTypes = fmap s2cTextReference
expectNamespaceStatsByHash :: BranchHash -> Transaction C.Branch.NamespaceStats
expectNamespaceStatsByHash bh = do
bhId <- Q.saveBranchHash bh
expectNamespaceStatsByHashId bhId
expectNamespaceStatsByHashId :: Db.BranchHashId -> Transaction C.Branch.NamespaceStats
expectNamespaceStatsByHashId bhId = do
Q.loadNamespaceStatsByHashId bhId `whenNothingM` do
boId <- Db.BranchObjectId <$> Q.expectObjectIdForPrimaryHashId (Db.unBranchHashId bhId)
dbBranch <- expectDbBranch boId
stats <- namespaceStatsForDbBranch dbBranch
Q.saveNamespaceStats bhId stats
pure stats
namespaceStatsForDbBranch :: S.DbBranch -> Transaction NamespaceStats
namespaceStatsForDbBranch S.Branch {terms, types, patches, children} = do
childStats <- for children \(_boId, chId) -> do
bhId <- Q.expectCausalValueHashId chId
expectNamespaceStatsByHashId bhId
pure $
NamespaceStats
{ numContainedTerms =
let childTermCount = sumOf (folded . to numContainedTerms) childStats
termCount = lengthOf (folded . folded) terms
in childTermCount + termCount,
numContainedTypes =
let childTypeCount = sumOf (folded . to numContainedTypes) childStats
typeCount = lengthOf (folded . folded) types
in childTypeCount + typeCount,
numContainedPatches =
let childPatchCount = sumOf (folded . to numContainedPatches) childStats
patchCount = Map.size patches
in childPatchCount + patchCount
}
| Gets the specified number of reflog entries in chronological order , most recent first .
getReflog :: Int -> Transaction [Reflog.Entry CausalHash Text]
getReflog numEntries = do
entries <- Q.getReflog numEntries
traverse (bitraverse Q.expectCausalHash pure) entries
appendReflog :: Reflog.Entry CausalHash Text -> Transaction ()
appendReflog entry = do
dbEntry <- (bitraverse Q.saveCausalHash pure) entry
Q.appendReflog dbEntry
|
d368b6fa4138965eb8f1cdc804ed42e7c710314dbe39891e2d62cab055eb8242 | lambe-lang/nethra | pass.ml | module Impl = struct
type _ input = string
type _ output = Nethra_toy_cst.Binding.t list
type _ error = Nethra_syntax_source.Location.t * string
let run input =
let open Preface_stdlib.Result in
let open Nethra_syntax_parser in
let open Nethra_syntax_source in
let module Parsec = Parsers.Parsec (Sources.FromChars) in
let module Bindings = Bindings.Impl (Parsec) in
Response.Destruct.fold
~success:(fun (r, _, _) -> Ok r)
~failure:(fun (m, _, s) ->
let message = function None -> "" | Some m -> ": " ^ m in
Error (Sources.FromChars.Access.location s, message m) )
(Bindings.bindings @@ Parsec.source @@ Utils.chars_of_string input)
end
| null | https://raw.githubusercontent.com/lambe-lang/nethra/2ac839aa086a683d8e15abfa2f042b53875af36b/lib/nethra/toy/system/t01_parser/pass.ml | ocaml | module Impl = struct
type _ input = string
type _ output = Nethra_toy_cst.Binding.t list
type _ error = Nethra_syntax_source.Location.t * string
let run input =
let open Preface_stdlib.Result in
let open Nethra_syntax_parser in
let open Nethra_syntax_source in
let module Parsec = Parsers.Parsec (Sources.FromChars) in
let module Bindings = Bindings.Impl (Parsec) in
Response.Destruct.fold
~success:(fun (r, _, _) -> Ok r)
~failure:(fun (m, _, s) ->
let message = function None -> "" | Some m -> ": " ^ m in
Error (Sources.FromChars.Access.location s, message m) )
(Bindings.bindings @@ Parsec.source @@ Utils.chars_of_string input)
end
| |
3422ea5a617d0dbf84e5294c02e5b557ff5549e1f20935ad19f03f345d711436 | sdiehl/write-you-a-haskell | Eval.hs | module Eval where
import Syntax
import Data.Maybe
import Data.Functor
isNum :: Expr -> Bool
isNum Zero = True
isNum (Succ t) = isNum t
isNum _ = False
isVal :: Expr -> Bool
isVal Tr = True
isVal Fl = True
isVal t | isNum t = True
isVal _ = False
eval' :: Expr -> Maybe Expr
eval' x = case x of
IsZero Zero -> Just Tr
IsZero (Succ t) | isNum t -> Just Fl
IsZero t -> IsZero <$> (eval' t)
Succ t -> Succ <$> (eval' t)
Pred Zero -> Just Zero
Pred (Succ t) | isNum t -> Just t
Pred t -> Pred <$> (eval' t)
If Tr c _ -> Just c
If Fl _ a -> Just a
If t c a -> (\t' -> If t' c a) <$> eval' t
_ -> Nothing
nf :: Expr -> Expr
nf x = fromMaybe x (nf <$> eval' x)
eval :: Expr -> Maybe Expr
eval t = case nf t of
nft | isVal nft -> Just nft
| otherwise -> Nothing -- term is "stuck"
| null | https://raw.githubusercontent.com/sdiehl/write-you-a-haskell/ae73485e045ef38f50846b62bd91777a9943d1f7/chapter3/calc/Eval.hs | haskell | term is "stuck" | module Eval where
import Syntax
import Data.Maybe
import Data.Functor
isNum :: Expr -> Bool
isNum Zero = True
isNum (Succ t) = isNum t
isNum _ = False
isVal :: Expr -> Bool
isVal Tr = True
isVal Fl = True
isVal t | isNum t = True
isVal _ = False
eval' :: Expr -> Maybe Expr
eval' x = case x of
IsZero Zero -> Just Tr
IsZero (Succ t) | isNum t -> Just Fl
IsZero t -> IsZero <$> (eval' t)
Succ t -> Succ <$> (eval' t)
Pred Zero -> Just Zero
Pred (Succ t) | isNum t -> Just t
Pred t -> Pred <$> (eval' t)
If Tr c _ -> Just c
If Fl _ a -> Just a
If t c a -> (\t' -> If t' c a) <$> eval' t
_ -> Nothing
nf :: Expr -> Expr
nf x = fromMaybe x (nf <$> eval' x)
eval :: Expr -> Maybe Expr
eval t = case nf t of
nft | isVal nft -> Just nft
|
40dda1295a6359165a2cd5a2d4d8091cc832d3b5464b2173ecfe4d756d462ac9 | mirage/ethernet | ethernet.mli |
* Copyright ( c ) 2010 - 2019 Anil Madhavapeddy < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2010-2019 Anil Madhavapeddy <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
* OCaml Ethernet ( IEEE 802.3 ) layer
* Ethernet ( IEEE 802.3 ) is a widely used data link layer . The hardware is
usually a twisted pair or fibre connection , on the software side it consists
of an Ethernet header where source and destination mac addresses , and a type
field , indicating the type of the next layer , are present . The Ethernet layer
consists of network card mac address and MTU information , and provides
decapsulation and encapsulation .
usually a twisted pair or fibre connection, on the software side it consists
of an Ethernet header where source and destination mac addresses, and a type
field, indicating the type of the next layer, are present. The Ethernet layer
consists of network card mac address and MTU information, and provides
decapsulation and encapsulation. *)
* { 2 Ethernet layer }
module Packet : sig
(** Ethernet protocols. *)
type proto = [ `ARP | `IPv4 | `IPv6 ]
(** [pp_proto ppf proto] pretty-prints the ethernet protocol [proto] on [ppf]. *)
val pp_proto: proto Fmt.t
(** The type of an Ethernet packet. *)
type t = {
source : Macaddr.t;
destination : Macaddr.t;
ethertype : proto;
}
(** [sizeof_ethernet] is the byte size of the ethernet header. *)
val sizeof_ethernet : int
(** [of_cstruct buffer] attempts to decode the buffer as ethernet packet. It
may result an error if the buffer is too small, or the protocol is not
supported. *)
val of_cstruct : Cstruct.t -> (t * Cstruct.t, string) result
(** [into_cstruct t cs] attempts to encode the ethernet packet [t] into the
buffer [cs] (at offset 0). This may fail if the buffer is not big
enough. *)
val into_cstruct : t -> Cstruct.t -> (unit, string) result
(** [make_cstruct t] encodes the ethernet packet [t] into a freshly allocated
buffer. *)
val make_cstruct : t -> Cstruct.t
end
module type S = sig
type nonrec error = private [> `Exceeds_mtu ]
(** The type for ethernet interface errors. *)
val pp_error: error Fmt.t
(** [pp_error] is the pretty-printer for errors. *)
type t
(** The type representing the internal state of the ethernet layer. *)
val disconnect: t -> unit Lwt.t
(** Disconnect from the ethernet layer. While this might take some time to
complete, it can never result in an error. *)
val write: t -> ?src:Macaddr.t -> Macaddr.t -> Packet.proto -> ?size:int ->
(Cstruct.t -> int) -> (unit, error) result Lwt.t
* [ write eth ~src dst proto ~size payload ] outputs an ethernet frame which
header is filled by [ eth ] , and its payload is the buffer from the call to
[ payload ] . [ Payload ] gets a buffer of [ size ] ( defaults to mtu ) to fill with
their payload . If [ size ] exceeds { ! , an error is returned .
header is filled by [eth], and its payload is the buffer from the call to
[payload]. [Payload] gets a buffer of [size] (defaults to mtu) to fill with
their payload. If [size] exceeds {!mtu}, an error is returned. *)
val mac: t -> Macaddr.t
* [ ] is the MAC address of [ eth ] .
val mtu: t -> int
* [ ] is the Maximum Transmission Unit of the [ eth ] i.e. the maximum
size of the payload , excluding the ethernet frame header .
size of the payload, excluding the ethernet frame header. *)
val input:
arpv4:(Cstruct.t -> unit Lwt.t) ->
ipv4:(Cstruct.t -> unit Lwt.t) ->
ipv6:(Cstruct.t -> unit Lwt.t) ->
t -> Cstruct.t -> unit Lwt.t
* [ input ~arpv4 ~ipv4 buffer ] decodes the buffer and demultiplexes
it depending on the protocol to the callback .
it depending on the protocol to the callback. *)
end
module Make (N : Mirage_net.S) : sig
include S
val connect : N.t -> t Lwt.t
(** [connect netif] connects an ethernet layer on top of the raw
network device [netif]. *)
end
| null | https://raw.githubusercontent.com/mirage/ethernet/0a69cc5cb3ff14fc008c956c6af39371a44f5b3c/src/ethernet.mli | ocaml | * Ethernet protocols.
* [pp_proto ppf proto] pretty-prints the ethernet protocol [proto] on [ppf].
* The type of an Ethernet packet.
* [sizeof_ethernet] is the byte size of the ethernet header.
* [of_cstruct buffer] attempts to decode the buffer as ethernet packet. It
may result an error if the buffer is too small, or the protocol is not
supported.
* [into_cstruct t cs] attempts to encode the ethernet packet [t] into the
buffer [cs] (at offset 0). This may fail if the buffer is not big
enough.
* [make_cstruct t] encodes the ethernet packet [t] into a freshly allocated
buffer.
* The type for ethernet interface errors.
* [pp_error] is the pretty-printer for errors.
* The type representing the internal state of the ethernet layer.
* Disconnect from the ethernet layer. While this might take some time to
complete, it can never result in an error.
* [connect netif] connects an ethernet layer on top of the raw
network device [netif]. |
* Copyright ( c ) 2010 - 2019 Anil Madhavapeddy < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2010-2019 Anil Madhavapeddy <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
* OCaml Ethernet ( IEEE 802.3 ) layer
* Ethernet ( IEEE 802.3 ) is a widely used data link layer . The hardware is
usually a twisted pair or fibre connection , on the software side it consists
of an Ethernet header where source and destination mac addresses , and a type
field , indicating the type of the next layer , are present . The Ethernet layer
consists of network card mac address and MTU information , and provides
decapsulation and encapsulation .
usually a twisted pair or fibre connection, on the software side it consists
of an Ethernet header where source and destination mac addresses, and a type
field, indicating the type of the next layer, are present. The Ethernet layer
consists of network card mac address and MTU information, and provides
decapsulation and encapsulation. *)
* { 2 Ethernet layer }
module Packet : sig
type proto = [ `ARP | `IPv4 | `IPv6 ]
val pp_proto: proto Fmt.t
type t = {
source : Macaddr.t;
destination : Macaddr.t;
ethertype : proto;
}
val sizeof_ethernet : int
val of_cstruct : Cstruct.t -> (t * Cstruct.t, string) result
val into_cstruct : t -> Cstruct.t -> (unit, string) result
val make_cstruct : t -> Cstruct.t
end
module type S = sig
type nonrec error = private [> `Exceeds_mtu ]
val pp_error: error Fmt.t
type t
val disconnect: t -> unit Lwt.t
val write: t -> ?src:Macaddr.t -> Macaddr.t -> Packet.proto -> ?size:int ->
(Cstruct.t -> int) -> (unit, error) result Lwt.t
* [ write eth ~src dst proto ~size payload ] outputs an ethernet frame which
header is filled by [ eth ] , and its payload is the buffer from the call to
[ payload ] . [ Payload ] gets a buffer of [ size ] ( defaults to mtu ) to fill with
their payload . If [ size ] exceeds { ! , an error is returned .
header is filled by [eth], and its payload is the buffer from the call to
[payload]. [Payload] gets a buffer of [size] (defaults to mtu) to fill with
their payload. If [size] exceeds {!mtu}, an error is returned. *)
val mac: t -> Macaddr.t
* [ ] is the MAC address of [ eth ] .
val mtu: t -> int
* [ ] is the Maximum Transmission Unit of the [ eth ] i.e. the maximum
size of the payload , excluding the ethernet frame header .
size of the payload, excluding the ethernet frame header. *)
val input:
arpv4:(Cstruct.t -> unit Lwt.t) ->
ipv4:(Cstruct.t -> unit Lwt.t) ->
ipv6:(Cstruct.t -> unit Lwt.t) ->
t -> Cstruct.t -> unit Lwt.t
* [ input ~arpv4 ~ipv4 buffer ] decodes the buffer and demultiplexes
it depending on the protocol to the callback .
it depending on the protocol to the callback. *)
end
module Make (N : Mirage_net.S) : sig
include S
val connect : N.t -> t Lwt.t
end
|
99a6996129d48bb483f026bf3a6aa636fd856c2f7d1b59ebbe9fff2a2218d560 | chetmurthy/poly-protobuf | test07_ml.ml | module T = Test07_types
module Pb = Test07_pb
module Pp = Test07_pp
let decode_ref_data () = {
T.value = 1l;
T.left = T.Node {T.value = 2l; T.left = T.Empty 0l ; T.right = T.Empty 0l};
T.right = T.Node {T.value = 3l; T.left = T.Empty 0l ; T.right = T.Empty 0l};
}
let () =
let mode = Test_util.parse_args () in
match mode with
| Test_util.Decode ->
Test_util.decode "test07.c2ml.data" Pb.decode_node Pp.pp_node (decode_ref_data ())
| Test_util.Encode ->
Test_util.encode "test07.ml2c.data" Pb.encode_node (decode_ref_data ())
| null | https://raw.githubusercontent.com/chetmurthy/poly-protobuf/1f80774af6472fa30ee2fb10d0ef91905a13a144/tests/testdata/integration-tests/test07_ml.ml | ocaml | module T = Test07_types
module Pb = Test07_pb
module Pp = Test07_pp
let decode_ref_data () = {
T.value = 1l;
T.left = T.Node {T.value = 2l; T.left = T.Empty 0l ; T.right = T.Empty 0l};
T.right = T.Node {T.value = 3l; T.left = T.Empty 0l ; T.right = T.Empty 0l};
}
let () =
let mode = Test_util.parse_args () in
match mode with
| Test_util.Decode ->
Test_util.decode "test07.c2ml.data" Pb.decode_node Pp.pp_node (decode_ref_data ())
| Test_util.Encode ->
Test_util.encode "test07.ml2c.data" Pb.encode_node (decode_ref_data ())
| |
af514524e06443a9a23d9a13dc4ffe4dd88f3b0093a8a2fea9b5cf4ee182c02c | braidchat/braid | group.clj | (ns braid.chat.db.group
(:require
[clojure.edn :as edn]
[datomic.api :as d]
[braid.core.server.db :as db]
[braid.chat.db.common :refer [create-entity-txn db->group db->user db->tag group-pull-pattern user-pull-pattern]]
[braid.chat.db.thread :as thread]
[braid.chat.db.user :as user]))
(defn group-exists?
[group-name]
(some? (d/pull (db/db) '[:group/id] [:group/name group-name])))
(defn group-by-id
[group-id]
(some-> (d/pull (db/db) group-pull-pattern [:group/id group-id])
db->group))
(defn group-by-slug
[group-slug]
(when-let [g (d/pull (db/db) group-pull-pattern [:group/slug group-slug])]
(db->group g)))
(defn group-users
[group-id]
(->> (d/q '[:find (pull ?u pull-pattern)
:in $ ?group-id pull-pattern
:where
[?g :group/id ?group-id]
[?g :group/user ?u]]
(db/db)
group-id
user-pull-pattern)
(map (comp db->user first))
set))
(defn group-settings
[group-id]
(->> (d/pull (db/db) [:group/settings] [:group/id group-id])
:group/settings
((fnil edn/read-string "{}"))))
(defn group-tags
[group-id]
(->> (d/q '[:find (pull ?t [:tag/id
:tag/name
:tag/description
{:tag/group [:group/id :group/name]}])
:in $ ?group-id
:where
[?g :group/id ?group-id]
[?t :tag/group ?g]]
(db/db) group-id)
(map (comp db->tag first))))
(defn user-groups
[user-id]
(->> (d/q '[:find [(pull ?g pull-pattern) ...]
:in $ ?user-id pull-pattern
:where
[?u :user/id ?user-id]
[?g :group/user ?u]]
(db/db) user-id group-pull-pattern)
(map db->group)
set))
(defn user-in-group?
[user-id group-id]
(-> (d/q '[:find ?g
:in $ ?user-id ?group-id
:where
[?u :user/id ?user-id]
[?g :group/id ?group-id]
[?g :group/user ?u]]
(db/db)
user-id group-id)
seq
boolean))
(defn group-users-joined-at
[group-id]
(->>
(d/q '[:find ?user-id (min ?inst)
:in $ ?group-id
:where
[?g :group/id ?group-id]
[?u :user/id ?user-id]
[?g :group/user ?u ?tx true]
[?tx :db/txInstant ?inst]]
(d/history (db/db))
group-id)
(filter (comp #(user-in-group? % group-id) first))
(into {})))
(defn user-is-group-admin?
[user-id group-id]
(some?
(d/q '[:find ?u .
:in $ ?user-id ?group-id
:where
[?g :group/id ?group-id]
[?u :user/id ?user-id]
[?g :group/admins ?u]]
(db/db) user-id group-id)))
;; Transactions
(defn create-group-txn
[{:keys [name slug id]}]
(create-entity-txn
{:group/id id
:group/slug slug
:group/name name}
db->group))
(defn group-set-txn
"Set a key to a value for the group's settings This will throw if
settings are changed in between reading & setting"
[group-id k v]
(let [old-prefs (-> (d/pull (db/db) [:group/settings] [:group/id group-id])
:group/settings)
new-prefs (-> ((fnil edn/read-string "{}") old-prefs)
(assoc k v)
pr-str)]
[[:db.fn/cas [:group/id group-id] :group/settings old-prefs new-prefs]]))
(defn user-add-to-group-txn
[user-id group-id]
[[:db/add [:group/id group-id] :group/user [:user/id user-id]]])
(defn user-leave-group-txn
[user-id group-id]
(concat
[[:db/retract [:group/id group-id] :group/user [:user/id user-id]]]
; unsubscribe from threads
(->>
(d/q '[:find [?t ...]
:in $ ?user-id ?group-id
:where
[?u :user/id ?user-id]
[?g :group/id ?group-id]
[?t :thread/group ?g]
[?u :user/subscribed-thread ?t]]
(db/db) user-id group-id)
(map (fn [t] [:db/retract [:user/id user-id] :user/subscribed-thread t])))
; remove mentions
(->> (d/q '[:find [?t ...]
:in $ ?user-id ?group-id
:where
[?u :user/id ?user-id]
[?g :group/id ?group-id]
[?t :thread/group ?g]
[?t :thread/mentioned ?u]]
(db/db) user-id group-id)
(map (fn [t] [:db/retract t :thread/mentioned [:user/id user-id]])))
; remove group from custom sort order
(if-let [order (user/user-get-preference user-id :groups-order)]
(user/user-set-preference-txn
user-id :groups-order (vec (remove (partial = group-id) order)))
[])))
(defn user-make-group-admin-txn
[user-id group-id]
[[:db/add [:group/id group-id] :group/user [:user/id user-id]]
[:db/add [:group/id group-id] :group/admins [:user/id user-id]]])
(defn user-subscribe-to-group-tags-txn
"Subscribe the user to all current tags in the group"
[user-id group-id]
(->>
(d/q '[:find ?tag
:in $ ?group-id
:where
[?tag :tag/group ?g]
[?g :group/id ?group-id]]
(db/db) group-id)
(map (fn [[tag]] [:db/add [:user/id user-id] :user/subscribed-tag tag]))))
(defn user-subscribe-to-all-tagged-threads
"Subscribe the user to all tagged conversation threads (ie. public).
Without this, threads that were started *before* a new user registered
would not show up for that user even if new messages were posted on those threads."
[user-id group-id]
(->> (d/q '[:find [?thread ...]
:in $ ?group-id
:where
[?group :group/id ?group-id]
[?tag :tag/group ?group]
[?thread :thread/tag ?tag]
[?thread :thread/group ?group]]
(db/db) group-id)
(map (fn [thread]
[:db/add [:user/id user-id] :user/subscribed-thread thread]))))
(defn user-join-group-txn
"Add a user to the given group, subscribe them to the group tags,
and subscribe them to the five most recent threads in the group."
[user-id group-id]
(concat
(user-add-to-group-txn user-id group-id)
(user-subscribe-to-group-tags-txn user-id group-id)
(user-subscribe-to-all-tagged-threads user-id group-id)))
(defn user-open-recent-threads
"Opens last 10 visible threads for new user.
This can't be done in same tx as 'user-join-group' b/c that txn is the one that makes threads available for the user."
[user-id group-id]
(mapcat
(fn [t] (thread/user-show-thread-txn user-id (t :id)))
(thread/recent-threads {:user-id user-id
:group-id group-id
:num-threads 10})))
| null | https://raw.githubusercontent.com/braidchat/braid/545fd58fe586cc7350101e95e82bdfb5b129878b/src/braid/chat/db/group.clj | clojure | Transactions
unsubscribe from threads
remove mentions
remove group from custom sort order | (ns braid.chat.db.group
(:require
[clojure.edn :as edn]
[datomic.api :as d]
[braid.core.server.db :as db]
[braid.chat.db.common :refer [create-entity-txn db->group db->user db->tag group-pull-pattern user-pull-pattern]]
[braid.chat.db.thread :as thread]
[braid.chat.db.user :as user]))
(defn group-exists?
[group-name]
(some? (d/pull (db/db) '[:group/id] [:group/name group-name])))
(defn group-by-id
[group-id]
(some-> (d/pull (db/db) group-pull-pattern [:group/id group-id])
db->group))
(defn group-by-slug
[group-slug]
(when-let [g (d/pull (db/db) group-pull-pattern [:group/slug group-slug])]
(db->group g)))
(defn group-users
[group-id]
(->> (d/q '[:find (pull ?u pull-pattern)
:in $ ?group-id pull-pattern
:where
[?g :group/id ?group-id]
[?g :group/user ?u]]
(db/db)
group-id
user-pull-pattern)
(map (comp db->user first))
set))
(defn group-settings
[group-id]
(->> (d/pull (db/db) [:group/settings] [:group/id group-id])
:group/settings
((fnil edn/read-string "{}"))))
(defn group-tags
[group-id]
(->> (d/q '[:find (pull ?t [:tag/id
:tag/name
:tag/description
{:tag/group [:group/id :group/name]}])
:in $ ?group-id
:where
[?g :group/id ?group-id]
[?t :tag/group ?g]]
(db/db) group-id)
(map (comp db->tag first))))
(defn user-groups
[user-id]
(->> (d/q '[:find [(pull ?g pull-pattern) ...]
:in $ ?user-id pull-pattern
:where
[?u :user/id ?user-id]
[?g :group/user ?u]]
(db/db) user-id group-pull-pattern)
(map db->group)
set))
(defn user-in-group?
[user-id group-id]
(-> (d/q '[:find ?g
:in $ ?user-id ?group-id
:where
[?u :user/id ?user-id]
[?g :group/id ?group-id]
[?g :group/user ?u]]
(db/db)
user-id group-id)
seq
boolean))
(defn group-users-joined-at
[group-id]
(->>
(d/q '[:find ?user-id (min ?inst)
:in $ ?group-id
:where
[?g :group/id ?group-id]
[?u :user/id ?user-id]
[?g :group/user ?u ?tx true]
[?tx :db/txInstant ?inst]]
(d/history (db/db))
group-id)
(filter (comp #(user-in-group? % group-id) first))
(into {})))
(defn user-is-group-admin?
[user-id group-id]
(some?
(d/q '[:find ?u .
:in $ ?user-id ?group-id
:where
[?g :group/id ?group-id]
[?u :user/id ?user-id]
[?g :group/admins ?u]]
(db/db) user-id group-id)))
(defn create-group-txn
[{:keys [name slug id]}]
(create-entity-txn
{:group/id id
:group/slug slug
:group/name name}
db->group))
(defn group-set-txn
"Set a key to a value for the group's settings This will throw if
settings are changed in between reading & setting"
[group-id k v]
(let [old-prefs (-> (d/pull (db/db) [:group/settings] [:group/id group-id])
:group/settings)
new-prefs (-> ((fnil edn/read-string "{}") old-prefs)
(assoc k v)
pr-str)]
[[:db.fn/cas [:group/id group-id] :group/settings old-prefs new-prefs]]))
(defn user-add-to-group-txn
[user-id group-id]
[[:db/add [:group/id group-id] :group/user [:user/id user-id]]])
(defn user-leave-group-txn
[user-id group-id]
(concat
[[:db/retract [:group/id group-id] :group/user [:user/id user-id]]]
(->>
(d/q '[:find [?t ...]
:in $ ?user-id ?group-id
:where
[?u :user/id ?user-id]
[?g :group/id ?group-id]
[?t :thread/group ?g]
[?u :user/subscribed-thread ?t]]
(db/db) user-id group-id)
(map (fn [t] [:db/retract [:user/id user-id] :user/subscribed-thread t])))
(->> (d/q '[:find [?t ...]
:in $ ?user-id ?group-id
:where
[?u :user/id ?user-id]
[?g :group/id ?group-id]
[?t :thread/group ?g]
[?t :thread/mentioned ?u]]
(db/db) user-id group-id)
(map (fn [t] [:db/retract t :thread/mentioned [:user/id user-id]])))
(if-let [order (user/user-get-preference user-id :groups-order)]
(user/user-set-preference-txn
user-id :groups-order (vec (remove (partial = group-id) order)))
[])))
(defn user-make-group-admin-txn
[user-id group-id]
[[:db/add [:group/id group-id] :group/user [:user/id user-id]]
[:db/add [:group/id group-id] :group/admins [:user/id user-id]]])
(defn user-subscribe-to-group-tags-txn
"Subscribe the user to all current tags in the group"
[user-id group-id]
(->>
(d/q '[:find ?tag
:in $ ?group-id
:where
[?tag :tag/group ?g]
[?g :group/id ?group-id]]
(db/db) group-id)
(map (fn [[tag]] [:db/add [:user/id user-id] :user/subscribed-tag tag]))))
(defn user-subscribe-to-all-tagged-threads
"Subscribe the user to all tagged conversation threads (ie. public).
Without this, threads that were started *before* a new user registered
would not show up for that user even if new messages were posted on those threads."
[user-id group-id]
(->> (d/q '[:find [?thread ...]
:in $ ?group-id
:where
[?group :group/id ?group-id]
[?tag :tag/group ?group]
[?thread :thread/tag ?tag]
[?thread :thread/group ?group]]
(db/db) group-id)
(map (fn [thread]
[:db/add [:user/id user-id] :user/subscribed-thread thread]))))
(defn user-join-group-txn
"Add a user to the given group, subscribe them to the group tags,
and subscribe them to the five most recent threads in the group."
[user-id group-id]
(concat
(user-add-to-group-txn user-id group-id)
(user-subscribe-to-group-tags-txn user-id group-id)
(user-subscribe-to-all-tagged-threads user-id group-id)))
(defn user-open-recent-threads
"Opens last 10 visible threads for new user.
This can't be done in same tx as 'user-join-group' b/c that txn is the one that makes threads available for the user."
[user-id group-id]
(mapcat
(fn [t] (thread/user-show-thread-txn user-id (t :id)))
(thread/recent-threads {:user-id user-id
:group-id group-id
:num-threads 10})))
|
833eca14ac6673c5e9db173a26c123da8cd2832fb78e1e8f7e16ea06ff33be88 | alavrik/piqi | main.ml |
Copyright 2009 , 2010 , 2011 , 2012 , 2013 , 2014
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2009, 2010, 2011, 2012, 2013, 2014 Anton Lavrik
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.
*)
* utilities for running piqi in command - line mode
* utilities for running piqi in command-line mode
*)
(* interfaces for defining sub-command *)
type command =
{
name : string;
descr : string;
run : (unit -> unit);
}
let commands :command list ref = ref []
let register_command f name descr =
let cmd = { name = name; descr = descr; run = f } in
commands := cmd :: !commands
let find_command name =
List.find (function x when x.name = name -> true | _ -> false) !commands
let usage () =
prerr_endline "\
Usage: piqi <command> [<command-options>]
piqi [--version]
Commands:";
List.iter
(fun cmd -> Printf.eprintf " %-15s%s\n" cmd.name cmd.descr)
(List.rev !commands);
prerr_endline "\n\
See 'piqi <command> --help' for more information on a specific command.
Options:
--version Print Piqi version and exit\n"
let exit_usage () =
usage ();
exit 2
let run_subcommand argv1 =
match argv1 with
| "--version" ->
print_endline Piqi_version.version
| "help" | "--help" | "-h" ->
usage ()
| _ ->
find command by command name passed as the first argument
let cmd =
try find_command argv1
with Not_found ->
exit_usage ()
in
Arg.current := 1; (* subcommand -- skip argv[0] *)
Piqi_command.run_command cmd.run
(* called by Piqi_run *)
let run () =
if !Sys.interactive
then () (* don't do anything in interactive (toplevel) mode *)
else
if Array.length Sys.argv < 2
then exit_usage ()
else run_subcommand Sys.argv.(1)
(* include commonly used functions in the module's namespace *)
include Piqi_command
| null | https://raw.githubusercontent.com/alavrik/piqi/bcea4d44997966198dc295df0609591fa787b1d2/src/main.ml | ocaml | interfaces for defining sub-command
subcommand -- skip argv[0]
called by Piqi_run
don't do anything in interactive (toplevel) mode
include commonly used functions in the module's namespace |
Copyright 2009 , 2010 , 2011 , 2012 , 2013 , 2014
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2009, 2010, 2011, 2012, 2013, 2014 Anton Lavrik
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.
*)
* utilities for running piqi in command - line mode
* utilities for running piqi in command-line mode
*)
type command =
{
name : string;
descr : string;
run : (unit -> unit);
}
let commands :command list ref = ref []
let register_command f name descr =
let cmd = { name = name; descr = descr; run = f } in
commands := cmd :: !commands
let find_command name =
List.find (function x when x.name = name -> true | _ -> false) !commands
let usage () =
prerr_endline "\
Usage: piqi <command> [<command-options>]
piqi [--version]
Commands:";
List.iter
(fun cmd -> Printf.eprintf " %-15s%s\n" cmd.name cmd.descr)
(List.rev !commands);
prerr_endline "\n\
See 'piqi <command> --help' for more information on a specific command.
Options:
--version Print Piqi version and exit\n"
let exit_usage () =
usage ();
exit 2
let run_subcommand argv1 =
match argv1 with
| "--version" ->
print_endline Piqi_version.version
| "help" | "--help" | "-h" ->
usage ()
| _ ->
find command by command name passed as the first argument
let cmd =
try find_command argv1
with Not_found ->
exit_usage ()
in
Piqi_command.run_command cmd.run
let run () =
if !Sys.interactive
else
if Array.length Sys.argv < 2
then exit_usage ()
else run_subcommand Sys.argv.(1)
include Piqi_command
|
b453933796d9c22a4506a15cb6d707c26bcd67a0a2c593948baeea93e34a5ebf | pjotrp/guix | cross-base.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2013 , 2014 , 2015 < >
Copyright © 2014 , 2015 < >
;;;
;;; 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 (gnu packages cross-base)
#:use-module (guix licenses)
#:use-module (gnu packages)
#:use-module (gnu packages gcc)
#:use-module (gnu packages base)
#:use-module (gnu packages commencement)
#:use-module (gnu packages linux)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix utils)
#:use-module (guix build-system gnu)
#:use-module (guix build-system trivial)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-26)
#:use-module (ice-9 match)
#:export (cross-binutils
cross-libc
cross-gcc))
(define %xgcc
GCC package used as the basis for cross - compilation . It does n't have to
;; be 'gcc' and can be a specific variant such as 'gcc-4.8'.
gcc)
(define (cross p target)
(package (inherit p)
(name (string-append (package-name p) "-cross-" target))
(arguments
(substitute-keyword-arguments (package-arguments p)
((#:configure-flags flags)
`(cons ,(string-append "--target=" target)
,flags))))))
(define (package-with-patch original patch)
"Return package ORIGINAL with PATCH applied."
(package (inherit original)
(source (origin (inherit (package-source original))
(patches (list patch))))))
(define (cross-binutils target)
"Return a cross-Binutils for TARGET."
(let ((binutils (package (inherit binutils)
(arguments
(substitute-keyword-arguments (package-arguments
binutils)
((#:configure-flags flags)
;; Build with `--with-sysroot' so that ld honors
DT_RUNPATH entries when searching for a needed
;; library. This works because as a side effect
;; `genscripts.sh' sets `USE_LIBPATH=yes', which tells
elf32.em to use DT_RUNPATH in its search list .
;; See <-05/msg00312.html>.
;;
;; In theory choosing / as the sysroot could lead ld
to pick up native libs instead of target ones . In
practice the RUNPATH of target libs only refers to
target libs , not native libs , so this is safe .
`(cons "--with-sysroot=/" ,flags)))))))
For , apply Qualcomm 's patch .
(cross (if (string-prefix? "xtensa-" target)
(package-with-patch binutils
(search-patch
"ath9k-htc-firmware-binutils.patch"))
binutils)
target)))
(define (cross-gcc-arguments target libc)
"Return build system arguments for a cross-gcc for TARGET, using LIBC (which
may be either a libc package or #f.)"
;; Set the current target system so that 'glibc-dynamic-linker' returns the
;; right name.
(parameterize ((%current-target-system target))
;; Disable stripping as this can break binaries, with object files of
;; libgcc.a showing up as having an unknown architecture. See
;; <-August/000663.html>
;; for instance.
(let ((args `(#:strip-binaries? #f
,@(package-arguments %xgcc))))
(substitute-keyword-arguments args
((#:configure-flags flags)
`(append (list ,(string-append "--target=" target)
,@(if libc
`( ;; Disable libcilkrts because it is not
ported to GNU / .
"--disable-libcilkrts")
`( ;; Disable features not needed at this stage.
"--disable-shared" "--enable-static"
;; Disable C++ because libstdc++'s configure
;; script otherwise fails with "Link tests are not
allowed after . "
"--enable-languages=c"
libgcc , would need libc
"--disable-libatomic"
"--disable-libmudflap"
"--disable-libgomp"
"--disable-libssp"
"--disable-libquadmath"
"--disable-decimal-float" ;would need libc
"--disable-libcilkrts"
)))
,(if libc
flags
`(remove (cut string-match "--enable-languages.*" <>)
,flags))))
((#:make-flags flags)
(if libc
`(let ((libc (assoc-ref %build-inputs "libc")))
;; FLAGS_FOR_TARGET are needed for the target libraries to receive
;; the -Bxxx for the startfiles.
(cons (string-append "FLAGS_FOR_TARGET=-B" libc "/lib")
,flags))
flags))
((#:phases phases)
(let ((phases
`(alist-cons-after
'install 'make-cross-binutils-visible
(lambda* (#:key outputs inputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(libexec (string-append out "/libexec/gcc/"
,target))
(binutils (string-append
(assoc-ref inputs "binutils-cross")
"/bin/" ,target "-"))
(wrapper (string-append
(assoc-ref inputs "ld-wrapper-cross")
"/bin/" ,target "-ld")))
(for-each (lambda (file)
(symlink (string-append binutils file)
(string-append libexec "/"
file)))
'("as" "nm"))
(symlink wrapper (string-append libexec "/ld"))
#t))
(alist-replace
'install
(lambda _
;; Unlike our 'strip' phase, this will do the right thing
;; for cross-compilers.
(zero? (system* "make" "install-strip")))
,phases))))
(if libc
`(alist-cons-before
'configure 'set-cross-path
(lambda* (#:key inputs #:allow-other-keys)
Add the cross Linux headers to CROSS_CPATH , and remove them
;; from CPATH.
(let ((libc (assoc-ref inputs "libc"))
(linux (assoc-ref inputs "xlinux-headers")))
(define (cross? x)
Return # t if X is a cross - libc or cross Linux .
(or (string-prefix? libc x)
(string-prefix? linux x)))
(setenv "CROSS_CPATH"
(string-append libc "/include:"
linux "/include"))
(setenv "CROSS_LIBRARY_PATH"
(string-append libc "/lib"))
(let ((cpath (search-path-as-string->list
(getenv "CPATH")))
(libpath (search-path-as-string->list
(getenv "LIBRARY_PATH"))))
(setenv "CPATH"
(list->search-path-as-string
(remove cross? cpath) ":"))
(setenv "LIBRARY_PATH"
(list->search-path-as-string
(remove cross? libpath) ":"))
#t)))
,phases)
phases)))))))
(define (cross-gcc-patches target)
"Return GCC patches needed for TARGET."
(cond ((string-prefix? "xtensa-" target)
Patch by Qualcomm needed to build the ath9k - htc firmware .
(list (search-patch "ath9k-htc-firmware-gcc.patch")))
(else '())))
(define* (cross-gcc target
#:optional (xbinutils (cross-binutils target)) libc)
"Return a cross-compiler for TARGET, where TARGET is a GNU triplet. Use
XBINUTILS as the associated cross-Binutils. If LIBC is false, then build a
GCC that does not target a libc; otherwise, target that libc."
(package (inherit %xgcc)
(name (string-append "gcc-cross-"
(if libc "" "sans-libc-")
target))
(source (origin (inherit (package-source %xgcc))
(patches
(append
(origin-patches (package-source %xgcc))
(cons (search-patch "gcc-cross-environment-variables.patch")
(cross-gcc-patches target))))))
For simplicity , use a single output . Otherwise libgcc_s & co. are not
;; found by default, etc.
(outputs '("out"))
(arguments
`(#:implicit-inputs? #f
#:modules ((guix build gnu-build-system)
(guix build utils)
(ice-9 regex)
(srfi srfi-1)
(srfi srfi-26))
,@(cross-gcc-arguments target libc)))
(native-inputs
`(("ld-wrapper-cross" ,(make-ld-wrapper
(string-append "ld-wrapper-" target)
#:target target
#:binutils xbinutils))
("binutils-cross" ,xbinutils)
;; Call it differently so that the builder can check whether the "libc"
input is # f.
("libc-native" ,@(assoc-ref %final-inputs "libc"))
;; Remaining inputs.
,@(let ((inputs (append (package-inputs %xgcc)
(alist-delete "libc" %final-inputs))))
(if libc
`(("libc" ,libc)
("xlinux-headers" ;the target headers
,@(assoc-ref (package-propagated-inputs libc)
"linux-headers"))
,@inputs)
inputs))))
(inputs '())
;; Only search target inputs, not host inputs.
(search-paths
(list (search-path-specification
(variable "CROSS_CPATH")
(files '("include")))
(search-path-specification
(variable "CROSS_LIBRARY_PATH")
(files '("lib" "lib64")))))
(native-search-paths '())))
(define* (cross-libc target
#:optional
(xgcc (cross-gcc target))
(xbinutils (cross-binutils target)))
"Return a libc cross-built for TARGET, a GNU triplet. Use XGCC and
XBINUTILS and the cross tool chain."
(define xlinux-headers
(package (inherit linux-libre-headers)
(name (string-append (package-name linux-libre-headers)
"-cross-" target))
(arguments
(substitute-keyword-arguments
`(#:implicit-cross-inputs? #f
,@(package-arguments linux-libre-headers))
((#:phases phases)
`(alist-replace
'build
(lambda _
(setenv "ARCH" ,(system->linux-architecture target))
(format #t "`ARCH' set to `~a' (cross compiling)~%" (getenv "ARCH"))
(and (zero? (system* "make" "defconfig"))
(zero? (system* "make" "mrproper" "headers_check"))))
,phases))))
(native-inputs `(("cross-gcc" ,xgcc)
("cross-binutils" ,xbinutils)
,@(package-native-inputs linux-libre-headers)))))
(package (inherit glibc)
(name (string-append "glibc-cross-" target))
(arguments
(substitute-keyword-arguments
`(;; Disable stripping (see above.)
#:strip-binaries? #f
;; This package is used as a target input, but it should not have
;; the usual cross-compilation inputs since that would include
;; itself.
#:implicit-cross-inputs? #f
,@(package-arguments glibc))
((#:configure-flags flags)
`(cons ,(string-append "--host=" target)
,flags))
((#:phases phases)
`(alist-cons-before
'configure 'set-cross-linux-headers-path
(lambda* (#:key inputs #:allow-other-keys)
(let ((linux (assoc-ref inputs "linux-headers")))
(setenv "CROSS_CPATH"
(string-append linux "/include"))
#t))
,phases))))
Shadow the native " linux - headers " because glibc 's recipe expects the
;; "linux-headers" input to point to the right thing.
(propagated-inputs `(("linux-headers" ,xlinux-headers)))
FIXME : ' static - bash ' should really be an input , not a native input , but
;; to do that will require building an intermediate cross libc.
(inputs '())
(native-inputs `(("cross-gcc" ,xgcc)
("cross-binutils" ,xbinutils)
,@(package-inputs glibc) ;FIXME: static-bash
,@(package-native-inputs glibc)))))
;;;
;;; Concrete cross toolchains.
;;;
(define-public xgcc-mips64el
N64 ABI
(xgcc (cross-gcc triplet
(cross-binutils triplet)
(cross-libc triplet))))
;; Don't attempt to build this cross-compiler on i686;
;; see <>.
(package (inherit xgcc)
(supported-systems (fold delete
(package-supported-systems xgcc)
'("mips64el-linux" "i686-linux"))))))
(define-public xgcc-avr
AVR cross - compiler , used to build AVR - Libc .
(let ((triplet "avr"))
(cross-gcc triplet
(cross-binutils triplet))))
(define-public xgcc-xtensa
Bare - bones , used to build the Atheros firmware .
(cross-gcc "xtensa-elf"))
(define-public xgcc-armhf
(let* ((triplet "arm-linux-gnueabihf")
(xgcc (cross-gcc triplet
(cross-binutils triplet)
(cross-libc triplet))))
(package (inherit xgcc)
(supported-systems (delete "armhf-linux" %supported-systems)))))
;; (define-public xgcc-armel
;; (let ((triplet "armel-linux-gnueabi"))
;; (cross-gcc triplet
;; (cross-binutils triplet)
;; (cross-libc triplet))))
| null | https://raw.githubusercontent.com/pjotrp/guix/96250294012c2f1520b67f12ea80bfd6b98075a2/gnu/packages/cross-base.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.
be 'gcc' and can be a specific variant such as 'gcc-4.8'.
Build with `--with-sysroot' so that ld honors
library. This works because as a side effect
`genscripts.sh' sets `USE_LIBPATH=yes', which tells
See <-05/msg00312.html>.
In theory choosing / as the sysroot could lead ld
Set the current target system so that 'glibc-dynamic-linker' returns the
right name.
Disable stripping as this can break binaries, with object files of
libgcc.a showing up as having an unknown architecture. See
<-August/000663.html>
for instance.
Disable libcilkrts because it is not
Disable features not needed at this stage.
Disable C++ because libstdc++'s configure
script otherwise fails with "Link tests are not
would need libc
FLAGS_FOR_TARGET are needed for the target libraries to receive
the -Bxxx for the startfiles.
Unlike our 'strip' phase, this will do the right thing
for cross-compilers.
from CPATH.
otherwise, target that libc."
found by default, etc.
Call it differently so that the builder can check whether the "libc"
Remaining inputs.
the target headers
Only search target inputs, not host inputs.
Disable stripping (see above.)
This package is used as a target input, but it should not have
the usual cross-compilation inputs since that would include
itself.
"linux-headers" input to point to the right thing.
to do that will require building an intermediate cross libc.
FIXME: static-bash
Concrete cross toolchains.
Don't attempt to build this cross-compiler on i686;
see <>.
(define-public xgcc-armel
(let ((triplet "armel-linux-gnueabi"))
(cross-gcc triplet
(cross-binutils triplet)
(cross-libc triplet)))) | Copyright © 2013 , 2014 , 2015 < >
Copyright © 2014 , 2015 < >
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 (gnu packages cross-base)
#:use-module (guix licenses)
#:use-module (gnu packages)
#:use-module (gnu packages gcc)
#:use-module (gnu packages base)
#:use-module (gnu packages commencement)
#:use-module (gnu packages linux)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix utils)
#:use-module (guix build-system gnu)
#:use-module (guix build-system trivial)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-26)
#:use-module (ice-9 match)
#:export (cross-binutils
cross-libc
cross-gcc))
(define %xgcc
GCC package used as the basis for cross - compilation . It does n't have to
gcc)
(define (cross p target)
(package (inherit p)
(name (string-append (package-name p) "-cross-" target))
(arguments
(substitute-keyword-arguments (package-arguments p)
((#:configure-flags flags)
`(cons ,(string-append "--target=" target)
,flags))))))
(define (package-with-patch original patch)
"Return package ORIGINAL with PATCH applied."
(package (inherit original)
(source (origin (inherit (package-source original))
(patches (list patch))))))
(define (cross-binutils target)
"Return a cross-Binutils for TARGET."
(let ((binutils (package (inherit binutils)
(arguments
(substitute-keyword-arguments (package-arguments
binutils)
((#:configure-flags flags)
DT_RUNPATH entries when searching for a needed
elf32.em to use DT_RUNPATH in its search list .
to pick up native libs instead of target ones . In
practice the RUNPATH of target libs only refers to
target libs , not native libs , so this is safe .
`(cons "--with-sysroot=/" ,flags)))))))
For , apply Qualcomm 's patch .
(cross (if (string-prefix? "xtensa-" target)
(package-with-patch binutils
(search-patch
"ath9k-htc-firmware-binutils.patch"))
binutils)
target)))
(define (cross-gcc-arguments target libc)
"Return build system arguments for a cross-gcc for TARGET, using LIBC (which
may be either a libc package or #f.)"
(parameterize ((%current-target-system target))
(let ((args `(#:strip-binaries? #f
,@(package-arguments %xgcc))))
(substitute-keyword-arguments args
((#:configure-flags flags)
`(append (list ,(string-append "--target=" target)
,@(if libc
ported to GNU / .
"--disable-libcilkrts")
"--disable-shared" "--enable-static"
allowed after . "
"--enable-languages=c"
libgcc , would need libc
"--disable-libatomic"
"--disable-libmudflap"
"--disable-libgomp"
"--disable-libssp"
"--disable-libquadmath"
"--disable-libcilkrts"
)))
,(if libc
flags
`(remove (cut string-match "--enable-languages.*" <>)
,flags))))
((#:make-flags flags)
(if libc
`(let ((libc (assoc-ref %build-inputs "libc")))
(cons (string-append "FLAGS_FOR_TARGET=-B" libc "/lib")
,flags))
flags))
((#:phases phases)
(let ((phases
`(alist-cons-after
'install 'make-cross-binutils-visible
(lambda* (#:key outputs inputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(libexec (string-append out "/libexec/gcc/"
,target))
(binutils (string-append
(assoc-ref inputs "binutils-cross")
"/bin/" ,target "-"))
(wrapper (string-append
(assoc-ref inputs "ld-wrapper-cross")
"/bin/" ,target "-ld")))
(for-each (lambda (file)
(symlink (string-append binutils file)
(string-append libexec "/"
file)))
'("as" "nm"))
(symlink wrapper (string-append libexec "/ld"))
#t))
(alist-replace
'install
(lambda _
(zero? (system* "make" "install-strip")))
,phases))))
(if libc
`(alist-cons-before
'configure 'set-cross-path
(lambda* (#:key inputs #:allow-other-keys)
Add the cross Linux headers to CROSS_CPATH , and remove them
(let ((libc (assoc-ref inputs "libc"))
(linux (assoc-ref inputs "xlinux-headers")))
(define (cross? x)
Return # t if X is a cross - libc or cross Linux .
(or (string-prefix? libc x)
(string-prefix? linux x)))
(setenv "CROSS_CPATH"
(string-append libc "/include:"
linux "/include"))
(setenv "CROSS_LIBRARY_PATH"
(string-append libc "/lib"))
(let ((cpath (search-path-as-string->list
(getenv "CPATH")))
(libpath (search-path-as-string->list
(getenv "LIBRARY_PATH"))))
(setenv "CPATH"
(list->search-path-as-string
(remove cross? cpath) ":"))
(setenv "LIBRARY_PATH"
(list->search-path-as-string
(remove cross? libpath) ":"))
#t)))
,phases)
phases)))))))
(define (cross-gcc-patches target)
"Return GCC patches needed for TARGET."
(cond ((string-prefix? "xtensa-" target)
Patch by Qualcomm needed to build the ath9k - htc firmware .
(list (search-patch "ath9k-htc-firmware-gcc.patch")))
(else '())))
(define* (cross-gcc target
#:optional (xbinutils (cross-binutils target)) libc)
"Return a cross-compiler for TARGET, where TARGET is a GNU triplet. Use
XBINUTILS as the associated cross-Binutils. If LIBC is false, then build a
(package (inherit %xgcc)
(name (string-append "gcc-cross-"
(if libc "" "sans-libc-")
target))
(source (origin (inherit (package-source %xgcc))
(patches
(append
(origin-patches (package-source %xgcc))
(cons (search-patch "gcc-cross-environment-variables.patch")
(cross-gcc-patches target))))))
For simplicity , use a single output . Otherwise libgcc_s & co. are not
(outputs '("out"))
(arguments
`(#:implicit-inputs? #f
#:modules ((guix build gnu-build-system)
(guix build utils)
(ice-9 regex)
(srfi srfi-1)
(srfi srfi-26))
,@(cross-gcc-arguments target libc)))
(native-inputs
`(("ld-wrapper-cross" ,(make-ld-wrapper
(string-append "ld-wrapper-" target)
#:target target
#:binutils xbinutils))
("binutils-cross" ,xbinutils)
input is # f.
("libc-native" ,@(assoc-ref %final-inputs "libc"))
,@(let ((inputs (append (package-inputs %xgcc)
(alist-delete "libc" %final-inputs))))
(if libc
`(("libc" ,libc)
,@(assoc-ref (package-propagated-inputs libc)
"linux-headers"))
,@inputs)
inputs))))
(inputs '())
(search-paths
(list (search-path-specification
(variable "CROSS_CPATH")
(files '("include")))
(search-path-specification
(variable "CROSS_LIBRARY_PATH")
(files '("lib" "lib64")))))
(native-search-paths '())))
(define* (cross-libc target
#:optional
(xgcc (cross-gcc target))
(xbinutils (cross-binutils target)))
"Return a libc cross-built for TARGET, a GNU triplet. Use XGCC and
XBINUTILS and the cross tool chain."
(define xlinux-headers
(package (inherit linux-libre-headers)
(name (string-append (package-name linux-libre-headers)
"-cross-" target))
(arguments
(substitute-keyword-arguments
`(#:implicit-cross-inputs? #f
,@(package-arguments linux-libre-headers))
((#:phases phases)
`(alist-replace
'build
(lambda _
(setenv "ARCH" ,(system->linux-architecture target))
(format #t "`ARCH' set to `~a' (cross compiling)~%" (getenv "ARCH"))
(and (zero? (system* "make" "defconfig"))
(zero? (system* "make" "mrproper" "headers_check"))))
,phases))))
(native-inputs `(("cross-gcc" ,xgcc)
("cross-binutils" ,xbinutils)
,@(package-native-inputs linux-libre-headers)))))
(package (inherit glibc)
(name (string-append "glibc-cross-" target))
(arguments
(substitute-keyword-arguments
#:strip-binaries? #f
#:implicit-cross-inputs? #f
,@(package-arguments glibc))
((#:configure-flags flags)
`(cons ,(string-append "--host=" target)
,flags))
((#:phases phases)
`(alist-cons-before
'configure 'set-cross-linux-headers-path
(lambda* (#:key inputs #:allow-other-keys)
(let ((linux (assoc-ref inputs "linux-headers")))
(setenv "CROSS_CPATH"
(string-append linux "/include"))
#t))
,phases))))
Shadow the native " linux - headers " because glibc 's recipe expects the
(propagated-inputs `(("linux-headers" ,xlinux-headers)))
FIXME : ' static - bash ' should really be an input , not a native input , but
(inputs '())
(native-inputs `(("cross-gcc" ,xgcc)
("cross-binutils" ,xbinutils)
,@(package-native-inputs glibc)))))
(define-public xgcc-mips64el
N64 ABI
(xgcc (cross-gcc triplet
(cross-binutils triplet)
(cross-libc triplet))))
(package (inherit xgcc)
(supported-systems (fold delete
(package-supported-systems xgcc)
'("mips64el-linux" "i686-linux"))))))
(define-public xgcc-avr
AVR cross - compiler , used to build AVR - Libc .
(let ((triplet "avr"))
(cross-gcc triplet
(cross-binutils triplet))))
(define-public xgcc-xtensa
Bare - bones , used to build the Atheros firmware .
(cross-gcc "xtensa-elf"))
(define-public xgcc-armhf
(let* ((triplet "arm-linux-gnueabihf")
(xgcc (cross-gcc triplet
(cross-binutils triplet)
(cross-libc triplet))))
(package (inherit xgcc)
(supported-systems (delete "armhf-linux" %supported-systems)))))
|
acac6d2226fe2a9d2fc77e324b9e28968fb9c84b6d84c5caf6dc14a35c76af5a | zalky/runway | core.clj | (ns runway.core
(:require [axle.core :as watch]
[beckon :as sig]
[cinch.core :as util]
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.tools.cli :as cli]
[clojure.tools.namespace.dependency :as deps]
[clojure.tools.namespace.dir :as dir]
[clojure.tools.namespace.reload :as reload]
[clojure.tools.namespace.track :as track]
[com.stuartsierra.component :as component]
[com.stuartsierra.dependency :as c-deps]
[taoensso.timbre :as log])
(:import [clojure.lang ExceptionInfo IPending Namespace]
com.stuartsierra.component.SystemMap
java.io.FileNotFoundException
java.lang.management.ManagementFactory))
(defonce system-sym
Symbol for global system constructor fn . Careful , defonce will
;; not prevent this var from being thrown out by c.t.n. If this
;; namespace gets reloaded, the system will get in an unrecoverable
;; state since we forget where to find the root system
;; component. This should never be a problem in projects that use
;; this library, only when developing on this namespace directly.
nil)
(defonce system
;; Global system var.
nil)
(defn- apply-components
[components]
(reduce-kv
(fn [acc k [c & args]]
(assoc acc k (apply c args)))
{}
components))
(defn assemble-system
"Assembles system given components and a dependencies map."
[components dependencies]
(as-> (apply-components components) %
(mapcat identity %)
(apply component/system-map %)
(component/system-using % dependencies)))
(defn merge-deps
"Merges a component dependency graph, preserving vectors."
[& deps]
(apply merge-with (comp vec distinct concat) deps))
(defn- init
"Constructs the current system."
[]
(->> ((find-var system-sym))
(constantly)
(alter-var-root #'system)))
(defprotocol Recover
(recoverable-system [sys failed-id]
"Given a system that has failed a lifecycle method, and the id of
the component that threw the error, returns the largest subsystem
that can be fully stopped to cleanly recover from the error."))
(defn recoverable-system-map
"Recover implementation for a SystemMap."
[sys failed-id]
(let [failed (-> sys
(component/dependency-graph (keys sys))
(c-deps/transitive-dependents failed-id)
(conj failed-id))]
(apply dissoc sys ::state failed)))
(extend SystemMap
Recover
{:recoverable-system recoverable-system-map})
(defn- recover-system
[e]
(let [{f :function
id :system-key
sys :system} (ex-data e)]
(try
(log/error e "Lifecycle failed" f)
(log/info "Stopping recoverable system")
(-> (recoverable-system sys id)
(component/stop)
(assoc ::state ::stopped))
(catch ExceptionInfo e
(log/error e "Unrecoverable system error")
(throw e)))))
(defn- alter-system
[f]
(letfn [(try-recover [sys]
(try
(f sys)
(catch ExceptionInfo e
(recover-system e))))]
(alter-var-root #'system try-recover)))
(defn start
"Starts the current system if not already started."
[]
(alter-system
(fn [sys]
(if (not= ::running (::state sys))
(do (log/info "Starting" system-sym)
(-> ((find-var system-sym))
(component/start)
(assoc ::state ::running)))
sys))))
(defn stop
"Shuts down and destroys the currently running system."
[]
(alter-system
(fn [sys]
(if (= ::running (::state sys))
(do (log/info "Stopping" system-sym)
(-> sys
(component/stop)
(assoc ::state ::stopped)))
sys))))
(defn restart
[]
(stop)
(start))
(defn- jvm-start-time
[]
(.getStartTime (ManagementFactory/getRuntimeMXBean)))
(defn- ns-loaded?
[sym]
(try
(the-ns sym)
(catch Exception e
false)))
(defn- resolve-error
[sym {:keys [on-error]}]
(let [msg "Failed require or resolve"]
(case on-error
:throw (throw (ex-info msg {:sym sym}))
:log (log/error msg sym)
nil nil))
false)
(defn try-require
[sym & opts]
(try
(do (-> sym
(name)
(symbol)
(require))
true)
(catch FileNotFoundException _
(resolve-error sym opts))))
(defn resolve-sym
"Prefer to requiring-resolve for backwards compatibility"
[sym & opts]
(try
(let [n (symbol (name sym))
ns (symbol (namespace sym))]
(require ns)
(var-get (ns-resolve (find-ns ns) n)))
(catch Exception _
(resolve-error sym opts))))
(defn- not-loaded-dependents
[{dc :dependencies
dt :dependents}]
(loop [unloaded #{}
[c & more] (remove dt (keys dc))]
(if c
(if (ns-loaded? c)
(recur unloaded more)
(recur (conj unloaded c)
(concat more (get dc c))))
unloaded)))
(defn scan-dirs
[tracker dirs]
(let [{deps ::track/deps
config ::config
:as t} (dir/scan-dirs tracker dirs)]
(if (:lazy-dependents config)
(let [f (->> deps
(not-loaded-dependents)
(partial remove))]
(-> t
(update ::track/load f)
(update ::track/unload f)))
t)))
(defn tracker
"Returns a new tracker with a full dependency graph, watching for
changes since JVM start."
[{dirs :source-dirs
:as config}]
(-> (track/tracker)
(assoc ::config config)
(scan-dirs dirs)
(dissoc ::track/load ::track/unload)
(assoc ::dir/time (jvm-start-time))))
(defn remove-fx
[tracker fx]
(update tracker ::fx (partial remove fx)))
(defmulti do-fx ::current-fx)
(defmethod do-fx ::scan-dirs
[{{dirs :source-dirs} ::config
:as tracker}]
(scan-dirs tracker dirs))
(defmethod do-fx ::start
[tracker]
(when (and system-sym system)
(start))
tracker)
(defmethod do-fx ::stop
[tracker]
(when (and system-sym system)
(stop))
tracker)
(defn- system-ns?
[sym]
(and system-sym
(= (str sym)
(namespace system-sym))))
(defn- component-dependent?
[tracker sym]
(-> tracker
(get-in [::track/deps :dependencies sym])
(contains? 'com.stuartsierra.component)))
(defn- get-restart-fn
[tracker]
(let [restart? (-> tracker
(::config)
(:restart-fn component-dependent?))]
(fn [sym]
(or (system-ns? sym)
(restart? tracker sym)))))
(defn- restart-paths?
[{events ::events
{:keys [restart-paths]} ::config}]
(letfn [(event-path [e]
(-> e
(:path)
(io/file)
(.getCanonicalPath)))
(restart-re [r-p]
(->> r-p
(io/file)
(.getCanonicalPath)
(str "^")
(re-pattern)))]
(distinct
(for [r-p restart-paths
e-p (map event-path events)
:when (re-find (restart-re r-p) e-p)]
e-p))))
(defmethod do-fx ::restart
[{::track/keys [load unload]
:as tracker}]
(let [reload (distinct (concat load unload))
restart (-> (get-restart-fn tracker)
(filter reload)
(concat (restart-paths? tracker)))]
(cond-> tracker
(empty? restart) (remove-fx #{::start ::stop})
(empty? reload) (remove-fx #{::reload-namespaces
::refresh-repl}))))
(defn- log-removed-ns
[{::track/keys [unload load]
:as tracker}]
(some->> (seq (remove (set load) unload))
(log/info "Removed namespaces")))
(defn- log-loaded-ns
[{::track/keys [load]
:as tracker}]
(some->> (seq load)
(log/info "Loading namespaces")))
(defmethod do-fx ::reload-namespaces
[tracker]
(log-removed-ns tracker)
(log-loaded-ns tracker)
(reload/track-reload tracker))
(defn re-alias!
[^Namespace ns]
(doseq [[dep-alias dep] (ns-aliases ns)]
(try
(let [new-dep (the-ns (ns-name dep))]
(doto ns
(.removeAlias dep-alias)
(.addAlias dep-alias new-dep)))
(catch Exception e))))
(defn re-refer!
[^Namespace ns]
(doseq [[sym var] (ns-refers ns)]
(let [m (meta var)
source-sym (:name m)
source-ns (find-ns (ns-name (:ns m)))
source-ns-name (ns-name source-ns)]
(when-not (= 'clojure.core source-ns-name)
(ns-unmap ns sym)
(->> source-sym
(ns-resolve source-ns)
(.refer ns sym))))))
(defn- refresh-ns!
[sym]
(let [ns (the-ns sym)]
(re-alias! ns)
(re-refer! ns)))
(defn- resource-path
[sym]
(-> (name sym)
(str/replace #"\." "/")
(str/replace #"-" "_")))
(defn- backing-resource
[sym]
(let [r (resource-path sym)]
(or (io/resource (str r ".clj"))
(io/resource (str r ".cljc"))
(io/resource (str r "__init.class")))))
(defn- refresh-ns?
[cache ctn-nses sym]
(not (or (contains? ctn-nses sym)
(if (contains? cache sym)
(get cache sym)
(backing-resource sym)))))
(defn- refresh-repl
"Refreshes ns aliases and refers for any namespace that is not backed
by a Clojure resource. These are generally REPL nses and are not
maintained by c.t.n. The aliases and refers in these nses must be
kept consistent with the updating namespace graph. We maintain a
refresh-cache in the tracker to reduce the number of resource
lookups, and keep things fast."
[{cache ::refresh-cache
deps ::track/deps
:as tracker}]
(let [ctn-nses (deps/nodes deps)]
(letfn [(f [new-cache sym]
(let [r (refresh-ns? cache ctn-nses sym)]
(when r (refresh-ns! sym))
(assoc new-cache sym r)))]
(->> (all-ns)
(map ns-name)
(reduce f {})
(assoc tracker ::resource-index)))))
(defmethod do-fx ::refresh-repl
;; Because the REPL namespace is not backed by source, c.t.n. cannot
reload it . This is good , otherwise REPL vars would not persist
;; across reloads. However, this also means REPL aliases and refers
;; can reference stale namespace objects after reloads, and must be
;; refreshed manually.
[tracker]
(refresh-repl tracker))
(defmethod do-fx ::check-errors
[{error ::reload/error
error-ns ::reload/error-ns
:as tracker}]
(if error
(do (log/error error "Compiler exception in" error-ns)
(remove-fx tracker #{::start}))
tracker))
(defn- try-fx
[{id ::current-fx :as tracker}]
(try
(do-fx tracker)
(catch Exception e
(when-not (contains? #{::start ::stop} id)
(log/error e "Uncaught watcher error" id))
(dissoc tracker ::fx))))
(defn reduce-fx
[fx tracker events]
(loop [t (assoc tracker ::fx fx)]
(let [[id & more] (::fx t)]
(if id
(recur (try-fx (assoc t
::fx more
::current-fx id
::events events)))
t))))
(defn- resolve-restart-fn
[args]
(util/update-contains args :restart-fn resolve-sym :on-error :throw))
(defn watcher-config
[args]
(merge
{:watch-fx [::scan-dirs
::restart
::stop
::reload-namespaces
::refresh-repl
::check-errors
::start]}
(resolve-restart-fn args)
{:source-dirs (util/get-source-dirs)}))
(defn watcher
"Starts a task that watches your Clojure files, reloads their
corresponding namespaces when they change, and then if necessary,
restarts the running application. Has the options:
:watch-fx - Accepts a sequence of runway.core/do-fx
multimethod dispatch values.
See runway.core/watcher-config for the default
list. You can extend watcher functionality via
the runway.core/do-fx multimethod. Each method
accepts a c.t.n. tracker map and returns and
updated one. Just take care: like middleware,
the order of fx methods is not commutative.
:lazy-dependents - Whether to load dependent namespaces eagerly
or lazily. See the section on reloading
heuristics for more details.
:restart-fn - A symbol to a predicate function that when
given a c.t.n. tracker and a namespace symbol,
returns a boolean whether or not the system
requires a restart due to the reloading of that
namespace. This allows you to override why and
when the running application is restarted.
:restart-paths - A list of paths that should trigger an
application restart on change. Note that the
paths can be either files or directories, with
directories also being matched on changed
contents. This is useful if your reloaded
workflow depends on static resources that are not
Clojure code, but may affect the running
application."
[args]
(let [{fx :watch-fx
r-paths :restart-paths
s-dirs :source-dirs
:as config} (watcher-config args)]
(log/info "Watching system...")
(watch/watch!
{:paths (concat s-dirs r-paths)
:context (tracker config)
:handler (->> (partial reduce-fx fx)
(watch/window 10))})
{:runway/block true}))
(def default-shutdown-signals
["SIGINT"
"SIGTERM"
"SIGHUP"])
(defn- shutdown-once-fn
"Idempotent shutown on POSIX signals of type sig."
[sig]
(let [nonce (atom false)]
(fn []
(when-not (-> nonce
(reset-vals! true)
(first))
(stop)
(sig/reinit! sig)
(sig/raise! sig)))))
(defn- trim-signal
[sig]
(str/replace-first sig #"^SIG" ""))
(defn init-shutdown-handlers
[signals]
(doseq [sig signals]
(let [sig* (trim-signal sig)]
(reset! (sig/signal-atom sig*)
[(shutdown-once-fn sig*)]))))
(defn- reloadable-system?
[sym]
(let [sys ((find-var sym))]
(and (satisfies? component/Lifecycle sys)
(satisfies? Recover sys))))
(defn go
"Launches the system once at boot. Options:
:system - A qualified symbol that refers to a function
that when invoked returns a thing that implements
both com.stuartsierra.component/Lifecycle, and
runway.core/Recover.
:shutdown-signal - A list of POSIX signal names on which to attempt
a clean system shutdown. POSIX signal names are
provided in truncated from, where SIG is dropped
from the beginning of the string. For example:
SIGINT becomes INT."
[{sym :system
signals :shutdown-signals
:or {signals default-shutdown-signals}
:as args}]
(when-not (qualified-symbol? sym)
(throw (ex-info "Not a fully qualified symbol" args)))
(require (symbol (namespace sym)))
(alter-var-root #'system-sym (constantly sym))
(when-not (find-var sym)
(throw (ex-info "Could not find system var" args)))
(when-not (reloadable-system? sym)
(throw (ex-info "Not a reloadable system" {:system sym})))
(try
(init-shutdown-handlers signals)
(start)
{:runway/block true}
(catch Exception e nil)))
(defn- sym->ns
[x]
(when (symbol? x)
(or (some-> x namespace symbol) x)))
(defn- exec-fn?
[k]
(and (qualified-symbol? k) (resolve k)))
(defn- load!
[acc k v ns]
(require ns)
(cond-> (update acc :loaded-nses conj ns)
(exec-fn? k) (update :exec-fns assoc k v)))
(defn- assert-exec-arg-key
[k]
(when-not (or (symbol? k) (keyword? k))
(-> ":exec-args environment key %s error: must be symbol or keyword"
(format k)
(Exception.)
(throw))))
(defn- assert-exec-arg-val
[k v]
(when-not (string? v)
(-> ":exec-args environment key %s error: value %s must be a string"
(format k v)
(Exception.)
(throw))))
(defn- parse-and-load-rf
[acc k v]
(if-let [ns (sym->ns k)]
(if v
(try
(load! acc k v ns)
(catch FileNotFoundException e
(-> "Could not load namespace %s"
(format k)
(Exception.)
(throw))))
acc)
(do (assert-exec-arg-key k)
(assert-exec-arg-val k v)
(assoc-in acc [:env k] v))))
(defn- parse-and-load!
[exec-args]
(reduce-kv parse-and-load-rf
{:exec-fns {}
:exec-args exec-args
:loaded-nses #{}
:env {}}
exec-args))
(defn- log-env!
[env]
(if (try-require 'environ.core)
(log/info "Merged env" env)
(log/info "No environ.core, skipping")))
(defn- log-loaded!
[{:keys [exec-fns exec-args loaded-nses env]}]
(when (:verbose env)
(let [fns (seq (map first exec-fns))]
(log-env! env)
(log/info "Loaded namespaces" (seq loaded-nses))
(log/info "Exec fns found" fns)
(log/info "Exec args" (select-keys exec-args fns)))))
(defn- merge-env!
[{env :env}]
(when (try-require 'environ.core)
(-> (find-var 'environ.core/env)
(alter-var-root merge env))))
(defn- exec-fns!
[{exec-fns :exec-fns}]
(doall
(for [[sym exec-args] exec-fns]
(if-let [f (var-get (resolve sym))]
(f exec-args)
(throw (ex-info "Could not resolve exec-fn" {:exec-fn sym}))))))
(defn boot-time
[]
(-> (System/currentTimeMillis)
(- (jvm-start-time))
(/ 1000)
(float)))
(defn- response-rf
[block? resp]
(if (map? resp)
(let [{b :runway/block
r :runway/ready} resp]
(when (instance? IPending r) @r)
(or block? b))
block?))
(defn- maybe-block
[responses]
(let [block? (reduce response-rf false responses)
t (boot-time)]
(log/info (format "Boot time: %.2fs" t))
(when block? @(promise))))
(defn exec
"Launches multiple concurrent functions via clojure :exec-args. See
the README.md for usage details."
[args]
(let [config (parse-and-load! args)]
(log-loaded! config)
(merge-env! config)
(maybe-block (exec-fns! config))))
(def cli-opts
[["-s" "--system SYSTEM_SYM" "System symbol"
:id :system
:parse-fn symbol]
[nil "--shutdown-signals SHUTDOWN_SIGNALS" "List of truncated POSIX signals"
:id :shutdown-signals
:parse-fn edn/read-string]
["-h" "--help"]])
(defn cli-args
"Parses CLI options for `runway.core/go` when running a dependent
ptoject as a main program. During development you should prefer
clojure -X invocation with `runway.core/exec`."
[args]
(cli/parse-opts args cli-opts))
(defn -main
[& args]
(let [{options :options
summary :summary
:as parsed} (cli-args args)]
(if (:help options)
(println summary)
(do (go options)
@(promise)))))
| null | https://raw.githubusercontent.com/zalky/runway/343f2b6d6b1808f623939d9e537ab2d3272f87e8/src/runway/core.clj | clojure | not prevent this var from being thrown out by c.t.n. If this
namespace gets reloaded, the system will get in an unrecoverable
state since we forget where to find the root system
component. This should never be a problem in projects that use
this library, only when developing on this namespace directly.
Global system var.
Because the REPL namespace is not backed by source, c.t.n. cannot
across reloads. However, this also means REPL aliases and refers
can reference stale namespace objects after reloads, and must be
refreshed manually. | (ns runway.core
(:require [axle.core :as watch]
[beckon :as sig]
[cinch.core :as util]
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.tools.cli :as cli]
[clojure.tools.namespace.dependency :as deps]
[clojure.tools.namespace.dir :as dir]
[clojure.tools.namespace.reload :as reload]
[clojure.tools.namespace.track :as track]
[com.stuartsierra.component :as component]
[com.stuartsierra.dependency :as c-deps]
[taoensso.timbre :as log])
(:import [clojure.lang ExceptionInfo IPending Namespace]
com.stuartsierra.component.SystemMap
java.io.FileNotFoundException
java.lang.management.ManagementFactory))
(defonce system-sym
Symbol for global system constructor fn . Careful , defonce will
nil)
(defonce system
nil)
(defn- apply-components
[components]
(reduce-kv
(fn [acc k [c & args]]
(assoc acc k (apply c args)))
{}
components))
(defn assemble-system
"Assembles system given components and a dependencies map."
[components dependencies]
(as-> (apply-components components) %
(mapcat identity %)
(apply component/system-map %)
(component/system-using % dependencies)))
(defn merge-deps
"Merges a component dependency graph, preserving vectors."
[& deps]
(apply merge-with (comp vec distinct concat) deps))
(defn- init
"Constructs the current system."
[]
(->> ((find-var system-sym))
(constantly)
(alter-var-root #'system)))
(defprotocol Recover
(recoverable-system [sys failed-id]
"Given a system that has failed a lifecycle method, and the id of
the component that threw the error, returns the largest subsystem
that can be fully stopped to cleanly recover from the error."))
(defn recoverable-system-map
"Recover implementation for a SystemMap."
[sys failed-id]
(let [failed (-> sys
(component/dependency-graph (keys sys))
(c-deps/transitive-dependents failed-id)
(conj failed-id))]
(apply dissoc sys ::state failed)))
(extend SystemMap
Recover
{:recoverable-system recoverable-system-map})
(defn- recover-system
[e]
(let [{f :function
id :system-key
sys :system} (ex-data e)]
(try
(log/error e "Lifecycle failed" f)
(log/info "Stopping recoverable system")
(-> (recoverable-system sys id)
(component/stop)
(assoc ::state ::stopped))
(catch ExceptionInfo e
(log/error e "Unrecoverable system error")
(throw e)))))
(defn- alter-system
[f]
(letfn [(try-recover [sys]
(try
(f sys)
(catch ExceptionInfo e
(recover-system e))))]
(alter-var-root #'system try-recover)))
(defn start
"Starts the current system if not already started."
[]
(alter-system
(fn [sys]
(if (not= ::running (::state sys))
(do (log/info "Starting" system-sym)
(-> ((find-var system-sym))
(component/start)
(assoc ::state ::running)))
sys))))
(defn stop
"Shuts down and destroys the currently running system."
[]
(alter-system
(fn [sys]
(if (= ::running (::state sys))
(do (log/info "Stopping" system-sym)
(-> sys
(component/stop)
(assoc ::state ::stopped)))
sys))))
(defn restart
[]
(stop)
(start))
(defn- jvm-start-time
[]
(.getStartTime (ManagementFactory/getRuntimeMXBean)))
(defn- ns-loaded?
[sym]
(try
(the-ns sym)
(catch Exception e
false)))
(defn- resolve-error
[sym {:keys [on-error]}]
(let [msg "Failed require or resolve"]
(case on-error
:throw (throw (ex-info msg {:sym sym}))
:log (log/error msg sym)
nil nil))
false)
(defn try-require
[sym & opts]
(try
(do (-> sym
(name)
(symbol)
(require))
true)
(catch FileNotFoundException _
(resolve-error sym opts))))
(defn resolve-sym
"Prefer to requiring-resolve for backwards compatibility"
[sym & opts]
(try
(let [n (symbol (name sym))
ns (symbol (namespace sym))]
(require ns)
(var-get (ns-resolve (find-ns ns) n)))
(catch Exception _
(resolve-error sym opts))))
(defn- not-loaded-dependents
[{dc :dependencies
dt :dependents}]
(loop [unloaded #{}
[c & more] (remove dt (keys dc))]
(if c
(if (ns-loaded? c)
(recur unloaded more)
(recur (conj unloaded c)
(concat more (get dc c))))
unloaded)))
(defn scan-dirs
[tracker dirs]
(let [{deps ::track/deps
config ::config
:as t} (dir/scan-dirs tracker dirs)]
(if (:lazy-dependents config)
(let [f (->> deps
(not-loaded-dependents)
(partial remove))]
(-> t
(update ::track/load f)
(update ::track/unload f)))
t)))
(defn tracker
"Returns a new tracker with a full dependency graph, watching for
changes since JVM start."
[{dirs :source-dirs
:as config}]
(-> (track/tracker)
(assoc ::config config)
(scan-dirs dirs)
(dissoc ::track/load ::track/unload)
(assoc ::dir/time (jvm-start-time))))
(defn remove-fx
[tracker fx]
(update tracker ::fx (partial remove fx)))
(defmulti do-fx ::current-fx)
(defmethod do-fx ::scan-dirs
[{{dirs :source-dirs} ::config
:as tracker}]
(scan-dirs tracker dirs))
(defmethod do-fx ::start
[tracker]
(when (and system-sym system)
(start))
tracker)
(defmethod do-fx ::stop
[tracker]
(when (and system-sym system)
(stop))
tracker)
(defn- system-ns?
[sym]
(and system-sym
(= (str sym)
(namespace system-sym))))
(defn- component-dependent?
[tracker sym]
(-> tracker
(get-in [::track/deps :dependencies sym])
(contains? 'com.stuartsierra.component)))
(defn- get-restart-fn
[tracker]
(let [restart? (-> tracker
(::config)
(:restart-fn component-dependent?))]
(fn [sym]
(or (system-ns? sym)
(restart? tracker sym)))))
(defn- restart-paths?
[{events ::events
{:keys [restart-paths]} ::config}]
(letfn [(event-path [e]
(-> e
(:path)
(io/file)
(.getCanonicalPath)))
(restart-re [r-p]
(->> r-p
(io/file)
(.getCanonicalPath)
(str "^")
(re-pattern)))]
(distinct
(for [r-p restart-paths
e-p (map event-path events)
:when (re-find (restart-re r-p) e-p)]
e-p))))
(defmethod do-fx ::restart
[{::track/keys [load unload]
:as tracker}]
(let [reload (distinct (concat load unload))
restart (-> (get-restart-fn tracker)
(filter reload)
(concat (restart-paths? tracker)))]
(cond-> tracker
(empty? restart) (remove-fx #{::start ::stop})
(empty? reload) (remove-fx #{::reload-namespaces
::refresh-repl}))))
(defn- log-removed-ns
[{::track/keys [unload load]
:as tracker}]
(some->> (seq (remove (set load) unload))
(log/info "Removed namespaces")))
(defn- log-loaded-ns
[{::track/keys [load]
:as tracker}]
(some->> (seq load)
(log/info "Loading namespaces")))
(defmethod do-fx ::reload-namespaces
[tracker]
(log-removed-ns tracker)
(log-loaded-ns tracker)
(reload/track-reload tracker))
(defn re-alias!
[^Namespace ns]
(doseq [[dep-alias dep] (ns-aliases ns)]
(try
(let [new-dep (the-ns (ns-name dep))]
(doto ns
(.removeAlias dep-alias)
(.addAlias dep-alias new-dep)))
(catch Exception e))))
(defn re-refer!
[^Namespace ns]
(doseq [[sym var] (ns-refers ns)]
(let [m (meta var)
source-sym (:name m)
source-ns (find-ns (ns-name (:ns m)))
source-ns-name (ns-name source-ns)]
(when-not (= 'clojure.core source-ns-name)
(ns-unmap ns sym)
(->> source-sym
(ns-resolve source-ns)
(.refer ns sym))))))
(defn- refresh-ns!
[sym]
(let [ns (the-ns sym)]
(re-alias! ns)
(re-refer! ns)))
(defn- resource-path
[sym]
(-> (name sym)
(str/replace #"\." "/")
(str/replace #"-" "_")))
(defn- backing-resource
[sym]
(let [r (resource-path sym)]
(or (io/resource (str r ".clj"))
(io/resource (str r ".cljc"))
(io/resource (str r "__init.class")))))
(defn- refresh-ns?
[cache ctn-nses sym]
(not (or (contains? ctn-nses sym)
(if (contains? cache sym)
(get cache sym)
(backing-resource sym)))))
(defn- refresh-repl
"Refreshes ns aliases and refers for any namespace that is not backed
by a Clojure resource. These are generally REPL nses and are not
maintained by c.t.n. The aliases and refers in these nses must be
kept consistent with the updating namespace graph. We maintain a
refresh-cache in the tracker to reduce the number of resource
lookups, and keep things fast."
[{cache ::refresh-cache
deps ::track/deps
:as tracker}]
(let [ctn-nses (deps/nodes deps)]
(letfn [(f [new-cache sym]
(let [r (refresh-ns? cache ctn-nses sym)]
(when r (refresh-ns! sym))
(assoc new-cache sym r)))]
(->> (all-ns)
(map ns-name)
(reduce f {})
(assoc tracker ::resource-index)))))
(defmethod do-fx ::refresh-repl
reload it . This is good , otherwise REPL vars would not persist
[tracker]
(refresh-repl tracker))
(defmethod do-fx ::check-errors
[{error ::reload/error
error-ns ::reload/error-ns
:as tracker}]
(if error
(do (log/error error "Compiler exception in" error-ns)
(remove-fx tracker #{::start}))
tracker))
(defn- try-fx
[{id ::current-fx :as tracker}]
(try
(do-fx tracker)
(catch Exception e
(when-not (contains? #{::start ::stop} id)
(log/error e "Uncaught watcher error" id))
(dissoc tracker ::fx))))
(defn reduce-fx
[fx tracker events]
(loop [t (assoc tracker ::fx fx)]
(let [[id & more] (::fx t)]
(if id
(recur (try-fx (assoc t
::fx more
::current-fx id
::events events)))
t))))
(defn- resolve-restart-fn
[args]
(util/update-contains args :restart-fn resolve-sym :on-error :throw))
(defn watcher-config
[args]
(merge
{:watch-fx [::scan-dirs
::restart
::stop
::reload-namespaces
::refresh-repl
::check-errors
::start]}
(resolve-restart-fn args)
{:source-dirs (util/get-source-dirs)}))
(defn watcher
"Starts a task that watches your Clojure files, reloads their
corresponding namespaces when they change, and then if necessary,
restarts the running application. Has the options:
:watch-fx - Accepts a sequence of runway.core/do-fx
multimethod dispatch values.
See runway.core/watcher-config for the default
list. You can extend watcher functionality via
the runway.core/do-fx multimethod. Each method
accepts a c.t.n. tracker map and returns and
updated one. Just take care: like middleware,
the order of fx methods is not commutative.
:lazy-dependents - Whether to load dependent namespaces eagerly
or lazily. See the section on reloading
heuristics for more details.
:restart-fn - A symbol to a predicate function that when
given a c.t.n. tracker and a namespace symbol,
returns a boolean whether or not the system
requires a restart due to the reloading of that
namespace. This allows you to override why and
when the running application is restarted.
:restart-paths - A list of paths that should trigger an
application restart on change. Note that the
paths can be either files or directories, with
directories also being matched on changed
contents. This is useful if your reloaded
workflow depends on static resources that are not
Clojure code, but may affect the running
application."
[args]
(let [{fx :watch-fx
r-paths :restart-paths
s-dirs :source-dirs
:as config} (watcher-config args)]
(log/info "Watching system...")
(watch/watch!
{:paths (concat s-dirs r-paths)
:context (tracker config)
:handler (->> (partial reduce-fx fx)
(watch/window 10))})
{:runway/block true}))
(def default-shutdown-signals
["SIGINT"
"SIGTERM"
"SIGHUP"])
(defn- shutdown-once-fn
"Idempotent shutown on POSIX signals of type sig."
[sig]
(let [nonce (atom false)]
(fn []
(when-not (-> nonce
(reset-vals! true)
(first))
(stop)
(sig/reinit! sig)
(sig/raise! sig)))))
(defn- trim-signal
[sig]
(str/replace-first sig #"^SIG" ""))
(defn init-shutdown-handlers
[signals]
(doseq [sig signals]
(let [sig* (trim-signal sig)]
(reset! (sig/signal-atom sig*)
[(shutdown-once-fn sig*)]))))
(defn- reloadable-system?
[sym]
(let [sys ((find-var sym))]
(and (satisfies? component/Lifecycle sys)
(satisfies? Recover sys))))
(defn go
"Launches the system once at boot. Options:
:system - A qualified symbol that refers to a function
that when invoked returns a thing that implements
both com.stuartsierra.component/Lifecycle, and
runway.core/Recover.
:shutdown-signal - A list of POSIX signal names on which to attempt
a clean system shutdown. POSIX signal names are
provided in truncated from, where SIG is dropped
from the beginning of the string. For example:
SIGINT becomes INT."
[{sym :system
signals :shutdown-signals
:or {signals default-shutdown-signals}
:as args}]
(when-not (qualified-symbol? sym)
(throw (ex-info "Not a fully qualified symbol" args)))
(require (symbol (namespace sym)))
(alter-var-root #'system-sym (constantly sym))
(when-not (find-var sym)
(throw (ex-info "Could not find system var" args)))
(when-not (reloadable-system? sym)
(throw (ex-info "Not a reloadable system" {:system sym})))
(try
(init-shutdown-handlers signals)
(start)
{:runway/block true}
(catch Exception e nil)))
(defn- sym->ns
[x]
(when (symbol? x)
(or (some-> x namespace symbol) x)))
(defn- exec-fn?
[k]
(and (qualified-symbol? k) (resolve k)))
(defn- load!
[acc k v ns]
(require ns)
(cond-> (update acc :loaded-nses conj ns)
(exec-fn? k) (update :exec-fns assoc k v)))
(defn- assert-exec-arg-key
[k]
(when-not (or (symbol? k) (keyword? k))
(-> ":exec-args environment key %s error: must be symbol or keyword"
(format k)
(Exception.)
(throw))))
(defn- assert-exec-arg-val
[k v]
(when-not (string? v)
(-> ":exec-args environment key %s error: value %s must be a string"
(format k v)
(Exception.)
(throw))))
(defn- parse-and-load-rf
[acc k v]
(if-let [ns (sym->ns k)]
(if v
(try
(load! acc k v ns)
(catch FileNotFoundException e
(-> "Could not load namespace %s"
(format k)
(Exception.)
(throw))))
acc)
(do (assert-exec-arg-key k)
(assert-exec-arg-val k v)
(assoc-in acc [:env k] v))))
(defn- parse-and-load!
[exec-args]
(reduce-kv parse-and-load-rf
{:exec-fns {}
:exec-args exec-args
:loaded-nses #{}
:env {}}
exec-args))
(defn- log-env!
[env]
(if (try-require 'environ.core)
(log/info "Merged env" env)
(log/info "No environ.core, skipping")))
(defn- log-loaded!
[{:keys [exec-fns exec-args loaded-nses env]}]
(when (:verbose env)
(let [fns (seq (map first exec-fns))]
(log-env! env)
(log/info "Loaded namespaces" (seq loaded-nses))
(log/info "Exec fns found" fns)
(log/info "Exec args" (select-keys exec-args fns)))))
(defn- merge-env!
[{env :env}]
(when (try-require 'environ.core)
(-> (find-var 'environ.core/env)
(alter-var-root merge env))))
(defn- exec-fns!
[{exec-fns :exec-fns}]
(doall
(for [[sym exec-args] exec-fns]
(if-let [f (var-get (resolve sym))]
(f exec-args)
(throw (ex-info "Could not resolve exec-fn" {:exec-fn sym}))))))
(defn boot-time
[]
(-> (System/currentTimeMillis)
(- (jvm-start-time))
(/ 1000)
(float)))
(defn- response-rf
[block? resp]
(if (map? resp)
(let [{b :runway/block
r :runway/ready} resp]
(when (instance? IPending r) @r)
(or block? b))
block?))
(defn- maybe-block
[responses]
(let [block? (reduce response-rf false responses)
t (boot-time)]
(log/info (format "Boot time: %.2fs" t))
(when block? @(promise))))
(defn exec
"Launches multiple concurrent functions via clojure :exec-args. See
the README.md for usage details."
[args]
(let [config (parse-and-load! args)]
(log-loaded! config)
(merge-env! config)
(maybe-block (exec-fns! config))))
(def cli-opts
[["-s" "--system SYSTEM_SYM" "System symbol"
:id :system
:parse-fn symbol]
[nil "--shutdown-signals SHUTDOWN_SIGNALS" "List of truncated POSIX signals"
:id :shutdown-signals
:parse-fn edn/read-string]
["-h" "--help"]])
(defn cli-args
"Parses CLI options for `runway.core/go` when running a dependent
ptoject as a main program. During development you should prefer
clojure -X invocation with `runway.core/exec`."
[args]
(cli/parse-opts args cli-opts))
(defn -main
[& args]
(let [{options :options
summary :summary
:as parsed} (cli-args args)]
(if (:help options)
(println summary)
(do (go options)
@(promise)))))
|
5ef9a52de7d7d4d1aa369c8040524c9b223108e4a7fd51fd307c756538d6943e | erlang/rebar3 | rebar_prv_release.erl | -*- erlang - indent - level : 4;indent - tabs - mode : nil -*-
%% ex: ts=4 sw=4 et
-module(rebar_prv_release).
-behaviour(provider).
-export([init/1,
do/1,
format_error/1]).
-include_lib("providers/include/providers.hrl").
-include("rebar.hrl").
-define(PROVIDER, release).
-define(DEPS, [compile]).
%% ===================================================================
%% Public API
%% ===================================================================
-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
State1 = rebar_state:add_provider(State, providers:create([{name, ?PROVIDER},
{module, ?MODULE},
{bare, true},
{deps, ?DEPS},
{example, "rebar3 release"},
{short_desc, "Build release of project."},
{desc, "Build release of project."},
{opts, rebar_relx:opt_spec_list()}])),
{ok, State1}.
-spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
do(State) ->
rebar_relx:do(?PROVIDER, State).
-spec format_error(any()) -> iolist().
format_error(Reason) ->
io_lib:format("~p", [Reason]).
| null | https://raw.githubusercontent.com/erlang/rebar3/048412ed4593e19097f4fa91747593aac6706afb/apps/rebar/src/rebar_prv_release.erl | erlang | ex: ts=4 sw=4 et
===================================================================
Public API
=================================================================== | -*- erlang - indent - level : 4;indent - tabs - mode : nil -*-
-module(rebar_prv_release).
-behaviour(provider).
-export([init/1,
do/1,
format_error/1]).
-include_lib("providers/include/providers.hrl").
-include("rebar.hrl").
-define(PROVIDER, release).
-define(DEPS, [compile]).
-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
State1 = rebar_state:add_provider(State, providers:create([{name, ?PROVIDER},
{module, ?MODULE},
{bare, true},
{deps, ?DEPS},
{example, "rebar3 release"},
{short_desc, "Build release of project."},
{desc, "Build release of project."},
{opts, rebar_relx:opt_spec_list()}])),
{ok, State1}.
-spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
do(State) ->
rebar_relx:do(?PROVIDER, State).
-spec format_error(any()) -> iolist().
format_error(Reason) ->
io_lib:format("~p", [Reason]).
|
80fe517222c38e5c571db6c61217ab59cd16c6b6665e6b992b8fac4c1d2bbe5f | GoNZooo/gotyno-hs | generics.hs | {-# LANGUAGE StrictData #-}
# LANGUAGE TemplateHaskell #
module GotynoOutput.Generics where
import Data.Aeson (FromJSON (..), ToJSON (..))
import qualified Data.Aeson as JSON
import GHC.Generics (Generic)
import qualified Gotyno.Helpers as Helpers
import Qtility
import qualified GotynoOutput.Basic as Basic
import qualified GotynoOutput.HasGeneric as HasGeneric
data UsingGenerics = UsingGenerics
{ _usingGenericsField1 :: (Basic.Maybe' Text),
_usingGenericsField2 :: (Basic.Either' Text Int)
}
deriving (Eq, Show, Generic)
deriveLensAndJSON ''UsingGenerics
data UsingOwnGenerics t = UsingOwnGenerics
{ _usingOwnGenericsField1 :: (Basic.Maybe' t)
}
deriving (Eq, Show, Generic)
instance (FromJSON t) => FromJSON (UsingOwnGenerics t) where
parseJSON =
JSON.genericParseJSON
JSON.defaultOptions
{JSON.fieldLabelModifier = drop @[] (length "_UsingOwnGenerics") >>> lowerCaseFirst}
instance (ToJSON t) => ToJSON (UsingOwnGenerics t) where
toJSON =
JSON.genericToJSON
JSON.defaultOptions
{JSON.fieldLabelModifier = drop @[] (length "_UsingOwnGenerics") >>> lowerCaseFirst}
makeLenses ''UsingOwnGenerics
data KnownForMovie = KnownForMovie
{ _knownForMovieMedia_type :: Text,
_knownForMoviePoster_path :: (Maybe Text),
_knownForMovieId :: Int,
_knownForMovieTitle :: (Maybe Text),
_knownForMovieVote_average :: Float,
_knownForMovieRelease_date :: (Maybe Text),
_knownForMovieOverview :: Text
}
deriving (Eq, Show, Generic)
deriveLensAndJSON ''KnownForMovie
data KnownForShow = KnownForShow
{ _knownForShowMedia_type :: Text,
_knownForShowPoster_path :: (Maybe Text),
_knownForShowId :: Int,
_knownForShowVote_average :: Float,
_knownForShowOverview :: Text,
_knownForShowFirst_air_date :: (Maybe Text),
_knownForShowName :: (Maybe Text)
}
deriving (Eq, Show, Generic)
deriveLensAndJSON ''KnownForShow
data KnownFor
= KnownForKnownForShow KnownForShow
| KnownForKnownForMovie KnownForMovie
| KnownForString Text
| KnownForF32 Float
deriving (Eq, Show, Generic)
instance FromJSON KnownFor where
parseJSON v =
(KnownForKnownForShow <$> parseJSON v)
<|> (KnownForKnownForMovie <$> parseJSON v)
<|> (KnownForString <$> parseJSON v)
<|> (KnownForF32 <$> parseJSON v)
instance ToJSON KnownFor where
toJSON (KnownForKnownForShow v) = toJSON v
toJSON (KnownForKnownForMovie v) = toJSON v
toJSON (KnownForString v) = toJSON v
toJSON (KnownForF32 v) = toJSON v
data KnownForMovieWithoutTypeTag = KnownForMovieWithoutTypeTag
{ _knownForMovieWithoutTypeTagPoster_path :: (Maybe Text),
_knownForMovieWithoutTypeTagId :: Int,
_knownForMovieWithoutTypeTagTitle :: (Maybe Text),
_knownForMovieWithoutTypeTagVote_average :: Float,
_knownForMovieWithoutTypeTagRelease_date :: (Maybe Text),
_knownForMovieWithoutTypeTagOverview :: Text
}
deriving (Eq, Show, Generic)
deriveLensAndJSON ''KnownForMovieWithoutTypeTag
data KnownForShowWithoutTypeTag = KnownForShowWithoutTypeTag
{ _knownForShowWithoutTypeTagPoster_path :: (Maybe Text),
_knownForShowWithoutTypeTagId :: Int,
_knownForShowWithoutTypeTagVote_average :: Float,
_knownForShowWithoutTypeTagOverview :: Text,
_knownForShowWithoutTypeTagFirst_air_date :: (Maybe Text),
_knownForShowWithoutTypeTagName :: (Maybe Text)
}
deriving (Eq, Show, Generic)
deriveLensAndJSON ''KnownForShowWithoutTypeTag
data KnownForEmbedded
= MovieStartingWithLowercase KnownForMovieWithoutTypeTag
| TvStartingWithLowercase KnownForShowWithoutTypeTag
deriving (Eq, Show, Generic)
instance ToJSON KnownForEmbedded where
toJSON (MovieStartingWithLowercase payload) = toJSON payload & atKey "media_type" ?~ String "movieStartingWithLowercase"
toJSON (TvStartingWithLowercase payload) = toJSON payload & atKey "media_type" ?~ String "tvStartingWithLowercase"
instance FromJSON KnownForEmbedded where
parseJSON = withObject "KnownForEmbedded" $ \o -> do
t :: Text <- o .: "media_type"
case t of
"movieStartingWithLowercase" -> MovieStartingWithLowercase <$> parseJSON (Object o)
"tvStartingWithLowercase" -> TvStartingWithLowercase <$> parseJSON (Object o)
tagValue -> fail $ "Invalid type tag: " <> show tagValue
data KnownForEmbeddedWithUpperCase
= Movie KnownForMovieWithoutTypeTag
| Tv KnownForShowWithoutTypeTag
deriving (Eq, Show, Generic)
instance ToJSON KnownForEmbeddedWithUpperCase where
toJSON (Movie payload) = toJSON payload & atKey "media_type" ?~ String "Movie"
toJSON (Tv payload) = toJSON payload & atKey "media_type" ?~ String "Tv"
instance FromJSON KnownForEmbeddedWithUpperCase where
parseJSON = withObject "KnownForEmbeddedWithUpperCase" $ \o -> do
t :: Text <- o .: "media_type"
case t of
"Movie" -> Movie <$> parseJSON (Object o)
"Tv" -> Tv <$> parseJSON (Object o)
tagValue -> fail $ "Invalid type tag: " <> show tagValue
| null | https://raw.githubusercontent.com/GoNZooo/gotyno-hs/722f1856e9d55d5f43ccb0938c5933472f9eef07/test/reference-output/generics.hs | haskell | # LANGUAGE StrictData # | # LANGUAGE TemplateHaskell #
module GotynoOutput.Generics where
import Data.Aeson (FromJSON (..), ToJSON (..))
import qualified Data.Aeson as JSON
import GHC.Generics (Generic)
import qualified Gotyno.Helpers as Helpers
import Qtility
import qualified GotynoOutput.Basic as Basic
import qualified GotynoOutput.HasGeneric as HasGeneric
data UsingGenerics = UsingGenerics
{ _usingGenericsField1 :: (Basic.Maybe' Text),
_usingGenericsField2 :: (Basic.Either' Text Int)
}
deriving (Eq, Show, Generic)
deriveLensAndJSON ''UsingGenerics
data UsingOwnGenerics t = UsingOwnGenerics
{ _usingOwnGenericsField1 :: (Basic.Maybe' t)
}
deriving (Eq, Show, Generic)
instance (FromJSON t) => FromJSON (UsingOwnGenerics t) where
parseJSON =
JSON.genericParseJSON
JSON.defaultOptions
{JSON.fieldLabelModifier = drop @[] (length "_UsingOwnGenerics") >>> lowerCaseFirst}
instance (ToJSON t) => ToJSON (UsingOwnGenerics t) where
toJSON =
JSON.genericToJSON
JSON.defaultOptions
{JSON.fieldLabelModifier = drop @[] (length "_UsingOwnGenerics") >>> lowerCaseFirst}
makeLenses ''UsingOwnGenerics
data KnownForMovie = KnownForMovie
{ _knownForMovieMedia_type :: Text,
_knownForMoviePoster_path :: (Maybe Text),
_knownForMovieId :: Int,
_knownForMovieTitle :: (Maybe Text),
_knownForMovieVote_average :: Float,
_knownForMovieRelease_date :: (Maybe Text),
_knownForMovieOverview :: Text
}
deriving (Eq, Show, Generic)
deriveLensAndJSON ''KnownForMovie
data KnownForShow = KnownForShow
{ _knownForShowMedia_type :: Text,
_knownForShowPoster_path :: (Maybe Text),
_knownForShowId :: Int,
_knownForShowVote_average :: Float,
_knownForShowOverview :: Text,
_knownForShowFirst_air_date :: (Maybe Text),
_knownForShowName :: (Maybe Text)
}
deriving (Eq, Show, Generic)
deriveLensAndJSON ''KnownForShow
data KnownFor
= KnownForKnownForShow KnownForShow
| KnownForKnownForMovie KnownForMovie
| KnownForString Text
| KnownForF32 Float
deriving (Eq, Show, Generic)
instance FromJSON KnownFor where
parseJSON v =
(KnownForKnownForShow <$> parseJSON v)
<|> (KnownForKnownForMovie <$> parseJSON v)
<|> (KnownForString <$> parseJSON v)
<|> (KnownForF32 <$> parseJSON v)
instance ToJSON KnownFor where
toJSON (KnownForKnownForShow v) = toJSON v
toJSON (KnownForKnownForMovie v) = toJSON v
toJSON (KnownForString v) = toJSON v
toJSON (KnownForF32 v) = toJSON v
data KnownForMovieWithoutTypeTag = KnownForMovieWithoutTypeTag
{ _knownForMovieWithoutTypeTagPoster_path :: (Maybe Text),
_knownForMovieWithoutTypeTagId :: Int,
_knownForMovieWithoutTypeTagTitle :: (Maybe Text),
_knownForMovieWithoutTypeTagVote_average :: Float,
_knownForMovieWithoutTypeTagRelease_date :: (Maybe Text),
_knownForMovieWithoutTypeTagOverview :: Text
}
deriving (Eq, Show, Generic)
deriveLensAndJSON ''KnownForMovieWithoutTypeTag
data KnownForShowWithoutTypeTag = KnownForShowWithoutTypeTag
{ _knownForShowWithoutTypeTagPoster_path :: (Maybe Text),
_knownForShowWithoutTypeTagId :: Int,
_knownForShowWithoutTypeTagVote_average :: Float,
_knownForShowWithoutTypeTagOverview :: Text,
_knownForShowWithoutTypeTagFirst_air_date :: (Maybe Text),
_knownForShowWithoutTypeTagName :: (Maybe Text)
}
deriving (Eq, Show, Generic)
deriveLensAndJSON ''KnownForShowWithoutTypeTag
data KnownForEmbedded
= MovieStartingWithLowercase KnownForMovieWithoutTypeTag
| TvStartingWithLowercase KnownForShowWithoutTypeTag
deriving (Eq, Show, Generic)
instance ToJSON KnownForEmbedded where
toJSON (MovieStartingWithLowercase payload) = toJSON payload & atKey "media_type" ?~ String "movieStartingWithLowercase"
toJSON (TvStartingWithLowercase payload) = toJSON payload & atKey "media_type" ?~ String "tvStartingWithLowercase"
instance FromJSON KnownForEmbedded where
parseJSON = withObject "KnownForEmbedded" $ \o -> do
t :: Text <- o .: "media_type"
case t of
"movieStartingWithLowercase" -> MovieStartingWithLowercase <$> parseJSON (Object o)
"tvStartingWithLowercase" -> TvStartingWithLowercase <$> parseJSON (Object o)
tagValue -> fail $ "Invalid type tag: " <> show tagValue
data KnownForEmbeddedWithUpperCase
= Movie KnownForMovieWithoutTypeTag
| Tv KnownForShowWithoutTypeTag
deriving (Eq, Show, Generic)
instance ToJSON KnownForEmbeddedWithUpperCase where
toJSON (Movie payload) = toJSON payload & atKey "media_type" ?~ String "Movie"
toJSON (Tv payload) = toJSON payload & atKey "media_type" ?~ String "Tv"
instance FromJSON KnownForEmbeddedWithUpperCase where
parseJSON = withObject "KnownForEmbeddedWithUpperCase" $ \o -> do
t :: Text <- o .: "media_type"
case t of
"Movie" -> Movie <$> parseJSON (Object o)
"Tv" -> Tv <$> parseJSON (Object o)
tagValue -> fail $ "Invalid type tag: " <> show tagValue
|
0dfcaad71d2df4f2bed9c351d995bf50ff1f21ec005448aab1013d61827fe558 | camlp5/camlp5 | pa_sexp.ml | (* camlp5r *)
pa_sexp.ml , v
Copyright ( c ) INRIA 2007 - 2017
open Asttools;
open MLast;
open Pcaml;
value sexp_eoi = Grammar.Entry.create gram "sexp_eoi";
value sexp_atom a = Sexp.Atom a ;
value sexp_nil = Sexp.Nil ;
value sexp_cons e1 e2 = Sexp.Cons e1 e2 ;
EXTEND
GLOBAL: sexp_eoi;
sexp: [
[
a = atom -> sexp_atom a
| "(" ; l1 = LIST1 sexp ; opt_e2 = OPT [ "." ; e2 = sexp -> e2 ] ; ")" ->
match opt_e2 with [
None -> List.fold_right sexp_cons l1 sexp_nil
| Some e2 -> List.fold_right sexp_cons l1 e2
]
| "(" ; ")" ->
sexp_nil
]
| [ s = ANTIQUOT_LOC "" -> Sexp.SeXtr loc s
| s = ANTIQUOT_LOC "anti" -> Sexp.SeXtr loc s
| s = ANTIQUOT_LOC "exp" -> Sexp.SeXtr loc s
| s = ANTIQUOT_LOC "atom" -> do {
Sexp.SeXtr loc s
}
]
]
;
sexp_eoi: [ [ x = sexp; EOI -> x ] ];
atom: [[ i = LIDENT -> i | i = UIDENT -> i | i = INT -> i ]] ;
END;
| null | https://raw.githubusercontent.com/camlp5/camlp5/15e03f56f55b2856dafe7dd3ca232799069f5dda/tutorials/sexp_example/pa_sexp.ml | ocaml | camlp5r | pa_sexp.ml , v
Copyright ( c ) INRIA 2007 - 2017
open Asttools;
open MLast;
open Pcaml;
value sexp_eoi = Grammar.Entry.create gram "sexp_eoi";
value sexp_atom a = Sexp.Atom a ;
value sexp_nil = Sexp.Nil ;
value sexp_cons e1 e2 = Sexp.Cons e1 e2 ;
EXTEND
GLOBAL: sexp_eoi;
sexp: [
[
a = atom -> sexp_atom a
| "(" ; l1 = LIST1 sexp ; opt_e2 = OPT [ "." ; e2 = sexp -> e2 ] ; ")" ->
match opt_e2 with [
None -> List.fold_right sexp_cons l1 sexp_nil
| Some e2 -> List.fold_right sexp_cons l1 e2
]
| "(" ; ")" ->
sexp_nil
]
| [ s = ANTIQUOT_LOC "" -> Sexp.SeXtr loc s
| s = ANTIQUOT_LOC "anti" -> Sexp.SeXtr loc s
| s = ANTIQUOT_LOC "exp" -> Sexp.SeXtr loc s
| s = ANTIQUOT_LOC "atom" -> do {
Sexp.SeXtr loc s
}
]
]
;
sexp_eoi: [ [ x = sexp; EOI -> x ] ];
atom: [[ i = LIDENT -> i | i = UIDENT -> i | i = INT -> i ]] ;
END;
|
dadf7814c3761b6c2d5d17977a5300abce11b9a1654f53b72a81695ef3a271c0 | sile/h264 | bit-stream.lisp | (in-package :h264.bit-stream)
(defstruct bit-stream
(source t :type stream)
(octets t :type list)
(pos t :type (integer 1 8)))
(defun make-input-stream (source)
(make-bit-stream :source source
:octets '()
:pos 8))
(defmacro with-input-stream ((in source) &body body)
`(let ((,in (make-input-stream ,source)))
,@body))
(defmacro with-input-from-octets ((in octets) &body body)
(let ((source (gensym)))
`(flexi-streams:with-input-from-sequence (,source (the octets ,octets))
(let ((,in (make-input-stream ,source)))
,@body))))
(defun eos? (in)
(declare (bit-stream in))
(with-slots (source octets) in
(and (not (listen source))
(null octets))))
;; XXX: 不正確
(defun more-rbsp-data? (in)
(declare (bit-stream in))
(with-slots (source octets) in
(loop WHILE (listen source)
DO
(when (> (length octets) 1)
(return-from more-rbsp-data? t))
(setf octets (append octets (list (read-byte source)))))
nil))
(defun byte-aligned? (in)
(declare (bit-stream in))
(with-slots (pos) in
(= pos 8)))
(defun read-impl (octets pos bit-length)
(cond ((zerop bit-length)
(values 0 octets pos))
((<= bit-length pos)
(let ((new-pos (- pos bit-length)))
(values (ldb (byte bit-length new-pos) (or (car octets) 0))
(if (zerop new-pos) (cdr octets) octets)
(if (zerop new-pos) 8 new-pos))))
(t
(multiple-value-bind (value new-octets new-pos)
(read-impl (cdr octets) 8 (- bit-length pos))
(values (+ (ash (ldb (byte pos 0) (or (car octets) 0))
(- bit-length pos))
value)
new-octets
new-pos)))))
(defun fill-octets (in bit-length)
(with-slots (source octets pos) in
(loop REPEAT (- (ceiling (+ bit-length (- 8 pos)) 8) (length octets))
WHILE (listen source)
DO (setf octets (append octets (list (read-byte source)))))))
(defun read (in bit-length)
(declare (bit-stream in)
(fixnum bit-length))
(fill-octets in bit-length)
(with-slots (octets pos) in
(multiple-value-bind (value new-octets new-pos)
(read-impl octets pos bit-length)
(setf octets new-octets
pos new-pos)
value)))
(defun peek (in bit-length)
(declare (bit-stream in)
(fixnum bit-length))
(fill-octets in bit-length)
(with-slots (octets pos) in
(values (read-impl octets pos bit-length))))
| null | https://raw.githubusercontent.com/sile/h264/93d48582a36c79e734f9933a5103e1b1505b6742/bit-stream/bit-stream.lisp | lisp | XXX: 不正確 | (in-package :h264.bit-stream)
(defstruct bit-stream
(source t :type stream)
(octets t :type list)
(pos t :type (integer 1 8)))
(defun make-input-stream (source)
(make-bit-stream :source source
:octets '()
:pos 8))
(defmacro with-input-stream ((in source) &body body)
`(let ((,in (make-input-stream ,source)))
,@body))
(defmacro with-input-from-octets ((in octets) &body body)
(let ((source (gensym)))
`(flexi-streams:with-input-from-sequence (,source (the octets ,octets))
(let ((,in (make-input-stream ,source)))
,@body))))
(defun eos? (in)
(declare (bit-stream in))
(with-slots (source octets) in
(and (not (listen source))
(null octets))))
(defun more-rbsp-data? (in)
(declare (bit-stream in))
(with-slots (source octets) in
(loop WHILE (listen source)
DO
(when (> (length octets) 1)
(return-from more-rbsp-data? t))
(setf octets (append octets (list (read-byte source)))))
nil))
(defun byte-aligned? (in)
(declare (bit-stream in))
(with-slots (pos) in
(= pos 8)))
(defun read-impl (octets pos bit-length)
(cond ((zerop bit-length)
(values 0 octets pos))
((<= bit-length pos)
(let ((new-pos (- pos bit-length)))
(values (ldb (byte bit-length new-pos) (or (car octets) 0))
(if (zerop new-pos) (cdr octets) octets)
(if (zerop new-pos) 8 new-pos))))
(t
(multiple-value-bind (value new-octets new-pos)
(read-impl (cdr octets) 8 (- bit-length pos))
(values (+ (ash (ldb (byte pos 0) (or (car octets) 0))
(- bit-length pos))
value)
new-octets
new-pos)))))
(defun fill-octets (in bit-length)
(with-slots (source octets pos) in
(loop REPEAT (- (ceiling (+ bit-length (- 8 pos)) 8) (length octets))
WHILE (listen source)
DO (setf octets (append octets (list (read-byte source)))))))
(defun read (in bit-length)
(declare (bit-stream in)
(fixnum bit-length))
(fill-octets in bit-length)
(with-slots (octets pos) in
(multiple-value-bind (value new-octets new-pos)
(read-impl octets pos bit-length)
(setf octets new-octets
pos new-pos)
value)))
(defun peek (in bit-length)
(declare (bit-stream in)
(fixnum bit-length))
(fill-octets in bit-length)
(with-slots (octets pos) in
(values (read-impl octets pos bit-length))))
|
b15e0d04930785fe1fe9224ea8d8f1feb7dc9b0786eeaaa5bda120fc7c25a0e4 | namin/biohacker | suspend.lisp | ;; -*- Mode: Lisp; -*-
;;;; Candidate generation via constraint suspension
Last edited : 1/29/93 , by KDF
Copyright ( c ) 1993 , , Northwestern University ,
and , the Xerox Corporation .
;;; All rights reserved.
;;; See the file legal.txt for a paragraph stating scope of permission
;;; and disclaimer of warranty. The above copyright notice and that
;;; paragraph must be included in any separate copy of this file.
(in-package :COMMON-LISP-USER)
;;;; Candidate generation algorithm
(defun generate-candidates (*tcon* inputs outputs
&optional (debugging? nil)
&aux diffs candidates
hypotheses result)
Step 1 : Insert inputs and collect discrepancies
(setup-inputs inputs *tcon*)
(setq diffs (find-discrepancies inputs outputs *tcon*))
(when debugging? (format T "~% ~D discrepancies found."
(length diffs))
(when diffs
(dolist (diff diffs)
(format t "~% ~A was ~A, should be ~A."
(caar diff) (cdr diff) (cdar diff)))))
(unless diffs (return-from generate-candidates :OKAY))
Step 2 : Select initial candidates
(do ((ds diffs (cdr ds))
(contributors nil)
(any? nil))
((null ds))
(setq contributors
(find-contributors (car ds) debugging?))
(if any?
(setq candidates
(intersection contributors candidates))
(setq candidates contributors any? t)))
(when debugging?
(format t "~% Candidates are ~A." candidates))
Step 3 : Evaluate candidate consistency
(dolist (candidate candidates)
(when (setq result
(evaluate-candidate candidate outputs
debugging?))
(push result hypotheses)))
(retract-inputs (mapcar 'car inputs))
hypotheses)
Network manipulations and discrepancy finding
(defun setup-inputs (inputs tcon)
(dolist (input-entry inputs)
(set! (eval (car input-entry))
(cdr input-entry) tcon))
(enforce-constraints tcon))
(defun retract-inputs (inputs &aux cell)
(dolist (cspec inputs)
(setq cell (eval cspec))
(forget! cell (cell-tcon cell)))
(enforce-constraints (cell-tcon cell)))
(defun find-discrepancies (inputs outputs *tcon*
&aux cell diffs)
(dolist (output-entry outputs diffs)
(setq cell (eval (car output-entry)))
(cond ((not (known? cell))
(error "~A not determined by inputs ~A."
(cell-pretty-name cell)
(mapcar 'car inputs)))
((coincidence? (cell-value cell)
(cdr output-entry) *tcon*))
(t (push (cons output-entry (cell-value cell))
diffs)))))
;;;; Support for candidate generation
(defun find-contributors (diff &optional (debugging? nil)
&aux candidates cell marker)
(setq cell (eval (caar diff))
marker (list cell))
(when (or (not (known? cell))
(ground-justification?
(cell-informant cell)))
(error "Output ~A not computed!" cell))
(do ((queue (list cell)
(nconc (cdr queue) new-cells))
(qc nil)
(new-cells nil nil))
((null queue)
(if debugging?
(format t
"~% Contributors to ~A being ~A instead of ~A: ~% ~A"
(caar diff) (cdr diff) (cdar diff) candidates))
candidates)
(setq qc (car queue))
(unless (eq (getf (cell-plist qc) :MARKER) marker)
(setf (getf (cell-plist qc) :MARKER) marker)
(unless (ground-justification? (cell-informant qc))
(unless (eq (constraint-name (cdr (cell-informant qc)))
'1<=>2)
(pushnew (cdr (cell-informant qc)) candidates))
(setq new-cells (rule-uses (cell-informant qc)))))))
(defun evaluate-candidate (candidate outputs
&optional (debugging? nil)
&aux result)
(when debugging? (format t "~% Suspending ~A.." candidate))
(suspend-constraint candidate)
(unwind-protect
(setq result
(catch 'eval-candidate-tag
(with-contradiction-handler *tcon*
'suspension-contra-handler
(dolist (output-entry outputs)
(set! (eval (car output-entry))
(cdr output-entry) *tcon*))
(enforce-constraints *tcon*)
;; If here, must not have got a contradiction
;; so record symptoms
(delete nil
(mapcar #'(lambda (cell)
(if (known? cell)
(cons cell
(cell-value cell))))
(constraint-cells candidate))))))
(progn (retract-inputs (mapcar 'car outputs))
(unsuspend-constraint candidate)))
(if debugging?
(if result (format t "~% .. ~A possible." candidate)
(format t "~% .. ~A exonerated." candidate)))
(if result (cons candidate result)))
(defun suspension-contra-handler (cell newval newsetter tcon)
(declare (ignore cell newval newsetter tcon))
(throw 'eval-candidate-tag nil))
Constraint suspension
(defun suspend-constraint (con)
;; Retracts conclusions from the constraint and
;; temporarily unwires it from the network.
(suspend-constraint1 con)
(enforce-constraints (constraint-tcon con)))
(defun suspend-constraint1 (con &aux part)
(dolist (part-entry (constraint-parts con))
(cond ((cell? (setq part (cdr part-entry)))
(unwire-cell part con))
(t (suspend-constraint1 part)))))
(defun unwire-cell (cell con &aux role)
;; Retract if necessary and then unwire it
(if (and (known? cell)
(listp (cell-informant cell))
(eq (cdr (cell-informant cell)) con))
(forget! cell (cell-informant cell)))
(setq role (rassoc con (cell-roles cell)))
(unless role
(error "~A not part of ~A!" cell con))
(setf (cell-roles cell)
(delete role (cell-roles cell) :COUNT 1))
(setf (getf (cell-plist cell) :SUSPENDED) role))
(defun unsuspend-constraint (con)
(unsuspend-constraint1 con)
(enforce-constraints (constraint-tcon con)))
(defun unsuspend-constraint1 (con &aux part)
(dolist (part-entry (constraint-parts con))
(cond ((cell? (setq part (cdr part-entry)))
(rewire-cell part con))
(t (unsuspend-constraint1 part)))))
(defun rewire-cell (cell con &aux role)
(setq role (getf (cell-plist cell) :SUSPENDED))
(unless role
(error "~A of ~A not really suspended." cell con))
(setf (getf (cell-plist cell) :SUSPENDED) nil)
(push role (cell-roles cell))
(beg! cell))
;;;; Test procedure
(defvar *suspend-file*
#+ILS "/u/bps/code/tcon/polybox"
#+PARC "virgo:/virgo/dekleer/bps/code/tcon/polybox"
#+MCL "Macintosh HD:BPS:tcon:polybox"
#+ACLPC "E:\\code\\tcon\\polybox")
(defun setup-cs-example (&optional (debugging? nil))
(create-tcon "Polybox Example" :DEBUGGING debugging?
:PROTOTYPE-FILE *suspend-file*)
(create 'ex 'Polybox-Example))
(defvar *in1* '(((>> a ex) . 3)((>> b ex) . 2)
((>> c ex) . 2)((>> d ex) . 3)
((>> e ex) . 3)))
(defvar *out1* '(((>> f ex) . 10)((>> g ex) . 12)))
(defvar *out2* '(((>> f ex) . 3)((>> g ex) . 3)))
(defvar *out3* '(((>> F EX) . 8) ((>> G EX) . 16)))
(defun test-constraint-suspension
(&optional (debugging? nil)
(inputs *in1*)
(outputs *out1*))
(setup-cs-example debugging?)
(generate-candidates *tcon* inputs outputs t))
| null | https://raw.githubusercontent.com/namin/biohacker/6b5da4c51c9caa6b5e1a68b046af171708d1af64/BPS/tcon/suspend.lisp | lisp | -*- Mode: Lisp; -*-
Candidate generation via constraint suspension
All rights reserved.
See the file legal.txt for a paragraph stating scope of permission
and disclaimer of warranty. The above copyright notice and that
paragraph must be included in any separate copy of this file.
Candidate generation algorithm
Support for candidate generation
If here, must not have got a contradiction
so record symptoms
Retracts conclusions from the constraint and
temporarily unwires it from the network.
Retract if necessary and then unwire it
Test procedure |
Last edited : 1/29/93 , by KDF
Copyright ( c ) 1993 , , Northwestern University ,
and , the Xerox Corporation .
(in-package :COMMON-LISP-USER)
(defun generate-candidates (*tcon* inputs outputs
&optional (debugging? nil)
&aux diffs candidates
hypotheses result)
Step 1 : Insert inputs and collect discrepancies
(setup-inputs inputs *tcon*)
(setq diffs (find-discrepancies inputs outputs *tcon*))
(when debugging? (format T "~% ~D discrepancies found."
(length diffs))
(when diffs
(dolist (diff diffs)
(format t "~% ~A was ~A, should be ~A."
(caar diff) (cdr diff) (cdar diff)))))
(unless diffs (return-from generate-candidates :OKAY))
Step 2 : Select initial candidates
(do ((ds diffs (cdr ds))
(contributors nil)
(any? nil))
((null ds))
(setq contributors
(find-contributors (car ds) debugging?))
(if any?
(setq candidates
(intersection contributors candidates))
(setq candidates contributors any? t)))
(when debugging?
(format t "~% Candidates are ~A." candidates))
Step 3 : Evaluate candidate consistency
(dolist (candidate candidates)
(when (setq result
(evaluate-candidate candidate outputs
debugging?))
(push result hypotheses)))
(retract-inputs (mapcar 'car inputs))
hypotheses)
Network manipulations and discrepancy finding
(defun setup-inputs (inputs tcon)
(dolist (input-entry inputs)
(set! (eval (car input-entry))
(cdr input-entry) tcon))
(enforce-constraints tcon))
(defun retract-inputs (inputs &aux cell)
(dolist (cspec inputs)
(setq cell (eval cspec))
(forget! cell (cell-tcon cell)))
(enforce-constraints (cell-tcon cell)))
(defun find-discrepancies (inputs outputs *tcon*
&aux cell diffs)
(dolist (output-entry outputs diffs)
(setq cell (eval (car output-entry)))
(cond ((not (known? cell))
(error "~A not determined by inputs ~A."
(cell-pretty-name cell)
(mapcar 'car inputs)))
((coincidence? (cell-value cell)
(cdr output-entry) *tcon*))
(t (push (cons output-entry (cell-value cell))
diffs)))))
(defun find-contributors (diff &optional (debugging? nil)
&aux candidates cell marker)
(setq cell (eval (caar diff))
marker (list cell))
(when (or (not (known? cell))
(ground-justification?
(cell-informant cell)))
(error "Output ~A not computed!" cell))
(do ((queue (list cell)
(nconc (cdr queue) new-cells))
(qc nil)
(new-cells nil nil))
((null queue)
(if debugging?
(format t
"~% Contributors to ~A being ~A instead of ~A: ~% ~A"
(caar diff) (cdr diff) (cdar diff) candidates))
candidates)
(setq qc (car queue))
(unless (eq (getf (cell-plist qc) :MARKER) marker)
(setf (getf (cell-plist qc) :MARKER) marker)
(unless (ground-justification? (cell-informant qc))
(unless (eq (constraint-name (cdr (cell-informant qc)))
'1<=>2)
(pushnew (cdr (cell-informant qc)) candidates))
(setq new-cells (rule-uses (cell-informant qc)))))))
(defun evaluate-candidate (candidate outputs
&optional (debugging? nil)
&aux result)
(when debugging? (format t "~% Suspending ~A.." candidate))
(suspend-constraint candidate)
(unwind-protect
(setq result
(catch 'eval-candidate-tag
(with-contradiction-handler *tcon*
'suspension-contra-handler
(dolist (output-entry outputs)
(set! (eval (car output-entry))
(cdr output-entry) *tcon*))
(enforce-constraints *tcon*)
(delete nil
(mapcar #'(lambda (cell)
(if (known? cell)
(cons cell
(cell-value cell))))
(constraint-cells candidate))))))
(progn (retract-inputs (mapcar 'car outputs))
(unsuspend-constraint candidate)))
(if debugging?
(if result (format t "~% .. ~A possible." candidate)
(format t "~% .. ~A exonerated." candidate)))
(if result (cons candidate result)))
(defun suspension-contra-handler (cell newval newsetter tcon)
(declare (ignore cell newval newsetter tcon))
(throw 'eval-candidate-tag nil))
Constraint suspension
(defun suspend-constraint (con)
(suspend-constraint1 con)
(enforce-constraints (constraint-tcon con)))
(defun suspend-constraint1 (con &aux part)
(dolist (part-entry (constraint-parts con))
(cond ((cell? (setq part (cdr part-entry)))
(unwire-cell part con))
(t (suspend-constraint1 part)))))
(defun unwire-cell (cell con &aux role)
(if (and (known? cell)
(listp (cell-informant cell))
(eq (cdr (cell-informant cell)) con))
(forget! cell (cell-informant cell)))
(setq role (rassoc con (cell-roles cell)))
(unless role
(error "~A not part of ~A!" cell con))
(setf (cell-roles cell)
(delete role (cell-roles cell) :COUNT 1))
(setf (getf (cell-plist cell) :SUSPENDED) role))
(defun unsuspend-constraint (con)
(unsuspend-constraint1 con)
(enforce-constraints (constraint-tcon con)))
(defun unsuspend-constraint1 (con &aux part)
(dolist (part-entry (constraint-parts con))
(cond ((cell? (setq part (cdr part-entry)))
(rewire-cell part con))
(t (unsuspend-constraint1 part)))))
(defun rewire-cell (cell con &aux role)
(setq role (getf (cell-plist cell) :SUSPENDED))
(unless role
(error "~A of ~A not really suspended." cell con))
(setf (getf (cell-plist cell) :SUSPENDED) nil)
(push role (cell-roles cell))
(beg! cell))
(defvar *suspend-file*
#+ILS "/u/bps/code/tcon/polybox"
#+PARC "virgo:/virgo/dekleer/bps/code/tcon/polybox"
#+MCL "Macintosh HD:BPS:tcon:polybox"
#+ACLPC "E:\\code\\tcon\\polybox")
(defun setup-cs-example (&optional (debugging? nil))
(create-tcon "Polybox Example" :DEBUGGING debugging?
:PROTOTYPE-FILE *suspend-file*)
(create 'ex 'Polybox-Example))
(defvar *in1* '(((>> a ex) . 3)((>> b ex) . 2)
((>> c ex) . 2)((>> d ex) . 3)
((>> e ex) . 3)))
(defvar *out1* '(((>> f ex) . 10)((>> g ex) . 12)))
(defvar *out2* '(((>> f ex) . 3)((>> g ex) . 3)))
(defvar *out3* '(((>> F EX) . 8) ((>> G EX) . 16)))
(defun test-constraint-suspension
(&optional (debugging? nil)
(inputs *in1*)
(outputs *out1*))
(setup-cs-example debugging?)
(generate-candidates *tcon* inputs outputs t))
|
69f468e88f755d75ca2d30c85b0740d70eaeb4ad9c374359fcdb18b67f96a754 | ermine/sulci | en_time.ml | let expand_time_proc _cause years months days hours minutes seconds =
(if years = 0 then "" else
Printf.sprintf "%d %s " years
(match years with
| 1 -> "year"
| _ -> "years")) ^
(if months = 0 then "" else
Printf.sprintf "%d %s " months
(match months with
| 1 -> "month"
| _ -> "months")) ^
(if days = 0 then "" else
Printf.sprintf "%d %s " days
(match days with
| 1 -> "day"
| _ -> "days")) ^
(if hours = 0 then "" else
Printf.sprintf "%d %s " hours
(match hours with
| 1 -> "hour"
| _ -> "hours")) ^
(if minutes = 0 then "" else
Printf.sprintf "%d %s " minutes
(match minutes with
| 1 -> "minute"
| _ -> "minutes")) ^
(if seconds = 0 && (years <> 0 || months <> 0 || days <> 0 || hours <> 0
|| minutes <> 0) then "" else
Printf.sprintf "%d %s " seconds
(match seconds with
| 1 -> "second"
| _ -> "seconds"))
let float_seconds_proc _cause seconds =
Printf.sprintf "%.3g seconds" seconds
open Lang
let _ =
langtime :=
LangTime.add "en"
{expand_time = expand_time_proc;
float_seconds = float_seconds_proc}
!langtime
| null | https://raw.githubusercontent.com/ermine/sulci/3ee4bd609b01e2093a6d37bf74579728d0a93b70/lang/en_time.ml | ocaml | let expand_time_proc _cause years months days hours minutes seconds =
(if years = 0 then "" else
Printf.sprintf "%d %s " years
(match years with
| 1 -> "year"
| _ -> "years")) ^
(if months = 0 then "" else
Printf.sprintf "%d %s " months
(match months with
| 1 -> "month"
| _ -> "months")) ^
(if days = 0 then "" else
Printf.sprintf "%d %s " days
(match days with
| 1 -> "day"
| _ -> "days")) ^
(if hours = 0 then "" else
Printf.sprintf "%d %s " hours
(match hours with
| 1 -> "hour"
| _ -> "hours")) ^
(if minutes = 0 then "" else
Printf.sprintf "%d %s " minutes
(match minutes with
| 1 -> "minute"
| _ -> "minutes")) ^
(if seconds = 0 && (years <> 0 || months <> 0 || days <> 0 || hours <> 0
|| minutes <> 0) then "" else
Printf.sprintf "%d %s " seconds
(match seconds with
| 1 -> "second"
| _ -> "seconds"))
let float_seconds_proc _cause seconds =
Printf.sprintf "%.3g seconds" seconds
open Lang
let _ =
langtime :=
LangTime.add "en"
{expand_time = expand_time_proc;
float_seconds = float_seconds_proc}
!langtime
| |
938417ff077fa12320fbfbd4938b1ac240a29c094eaa2c17e2eef0ba7176da7e | agda/agda | Position.hs | # LANGUAGE TemplateHaskell #
module Internal.Syntax.Position ( tests ) where
import Agda.Syntax.Position
import Agda.Syntax.TopLevelModuleName
import Agda.Utils.FileName
import qualified Agda.Utils.Maybe.Strict as Strict
import Agda.Utils.List ( distinct )
import qualified Agda.Utils.List1 as List1
import Agda.Utils.Null ( null )
import Control.Monad
import Data.Int
import Data.List (sort)
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Text as T
import Internal.Helpers
import Internal.Syntax.Common ()
import Internal.Utils.FileName (rootPath)
import Internal.Utils.Maybe.Strict ()
import Prelude hiding ( null )
import System.FilePath
------------------------------------------------------------------------
-- Test suite
-- | The positions corresponding to the interval. The positions do not
-- refer to characters, but to the positions between characters, with
zero pointing to the position before the first character .
iPositions :: Interval' a -> Set Int32
iPositions i = Set.fromList [posPos (iStart i) .. posPos (iEnd i)]
-- | The positions corresponding to the range, including the
-- end-points.
rPositions :: Range' a -> Set Int32
rPositions r = Set.unions (map iPositions $ rangeIntervals r)
-- | Constructs the least interval containing all the elements in the
-- set.
makeInterval :: Set Int32 -> Set Int32
makeInterval s
| Set.null s = Set.empty
| otherwise = Set.fromList [Set.findMin s .. Set.findMax s]
prop_iLength :: Interval' Integer -> Bool
prop_iLength i = iLength i >= 0
prop_startPos' :: Bool
prop_startPos' = positionInvariant (startPos' ())
prop_startPos :: Maybe RangeFile -> Bool
prop_startPos = positionInvariant . startPos
prop_noRange :: Bool
prop_noRange = rangeInvariant (noRange :: Range)
prop_posToRange' ::
Integer -> PositionWithoutFile -> PositionWithoutFile -> Bool
prop_posToRange' f p1 p2 =
rangeInvariant (posToRange' f p1 p2)
prop_posToRange :: Position' Integer -> Position' Integer -> Bool
prop_posToRange p1 p2 =
rangeInvariant (posToRange p1 (p2 { srcFile = srcFile p1 }))
prop_intervalToRange :: Integer -> IntervalWithoutFile -> Bool
prop_intervalToRange f i = rangeInvariant (intervalToRange f i)
rangeToIntervalPropertyTemplate ::
Ord a =>
(Range' Integer -> Maybe (Interval' a)) ->
Range' Integer -> Bool
rangeToIntervalPropertyTemplate r2i r = case r2i r of
Nothing -> r == noRange
Just i ->
r /= noRange
&&
intervalInvariant i
&&
iPositions i == makeInterval (rPositions r)
prop_rangeToIntervalWithFile :: Range' Integer -> Bool
prop_rangeToIntervalWithFile =
rangeToIntervalPropertyTemplate rangeToIntervalWithFile
prop_rangeToInterval :: Range' Integer -> Bool
prop_rangeToInterval =
rangeToIntervalPropertyTemplate rangeToInterval
prop_continuous :: Range -> Bool
prop_continuous r =
rangeInvariant cr &&
rPositions cr == makeInterval (rPositions r)
where cr = continuous r
prop_continuousPerLine :: Range -> Bool
prop_continuousPerLine r =
rangeInvariant r'
&&
distinct lineNumbers
&&
rangeFile r' == rangeFile r
where
r' = continuousPerLine r
lineNumbers = concatMap lines (rangeIntervals r')
where
lines i | s == e = [s]
| otherwise = [s, e]
where
s = posLine (iStart i)
e = posLine (iEnd i)
prop_fuseIntervals :: Interval' Integer -> Property
prop_fuseIntervals i1 =
forAll (intervalInSameFileAs i1) $ \i2 ->
let i = fuseIntervals i1 i2 in
intervalInvariant i &&
iPositions i ==
makeInterval (Set.union (iPositions i1) (iPositions i2))
prop_fuseRanges :: Range -> Property
prop_fuseRanges r1 =
forAll (rangeInSameFileAs r1) $ \r2 ->
let r = fuseRanges r1 r2 in
rangeInvariant r
&&
rPositions r == Set.union (rPositions r1) (rPositions r2)
prop_beginningOf :: Range -> Bool
prop_beginningOf r = rangeInvariant (beginningOf r)
prop_beginningOfFile :: Range -> Bool
prop_beginningOfFile r = rangeInvariant (beginningOfFile r)
instance Arbitrary a => Arbitrary (Position' a) where
arbitrary = do
srcFile <- arbitrary
Positive pos' <- arbitrary
let pos = fromInteger pos'
line = pred pos `div` 10 + 1
col = pred pos `mod` 10 + 1
return (Pn {srcFile = srcFile, posPos = pos,
posLine = line, posCol = col })
-- | Generates an interval located in the same file as the given
-- interval.
intervalInSameFileAs ::
(Arbitrary a, Ord a) => Interval' a -> Gen (Interval' a)
intervalInSameFileAs i =
setIntervalFile (srcFile $ iStart i) <$>
(arbitrary :: Gen IntervalWithoutFile)
prop_intervalInSameFileAs :: Interval' Integer -> Property
prop_intervalInSameFileAs i =
forAll (intervalInSameFileAs i) $ \i' ->
intervalInvariant i' &&
srcFile (iStart i) == srcFile (iStart i')
-- | Generates a range located in the same file as the given
-- range (if possible).
rangeInSameFileAs :: (Arbitrary a, Ord a) => Range' a -> Gen (Range' a)
rangeInSameFileAs NoRange = arbitrary
rangeInSameFileAs (Range f is) = do
Range _f is <- arbitrary `suchThat` (not . null)
return $ Range (f `asTypeOf` _f) is
prop_rangeInSameFileAs :: Range' Integer -> Property
prop_rangeInSameFileAs r =
forAll (rangeInSameFileAs r) $ \r' ->
rangeInvariant r'
&&
case (r, r') of
(NoRange, _) -> True
(Range f _, Range f' _) -> f == f'
(Range _ _, NoRange) -> False
instance Arbitrary RawTopLevelModuleName where
arbitrary = do
r <- arbitrary
parts <- list1Of (T.pack <$> listOf1 (elements "AB"))
return $ RawTopLevelModuleName
{ rawModuleNameRange = r
, rawModuleNameParts = parts
}
instance Arbitrary TopLevelModuleName where
arbitrary = do
raw <- arbitrary
return $
unsafeTopLevelModuleName raw
(hashRawTopLevelModuleName raw)
instance CoArbitrary TopLevelModuleName where
coarbitrary = coarbitrary . moduleNameId
instance Arbitrary RangeFile where
arbitrary = do
top <- arbitrary
extra <- take 2 . map (take 2) <$> listOf (listOf1 (elements "a1"))
let f = mkAbsolute $ joinPath $
rootPath : extra ++
map T.unpack (List1.toList (moduleNameParts top))
return $ mkRangeFile f (Just top)
instance (Arbitrary a, Ord a) => Arbitrary (Interval' a) where
arbitrary = do
(p1, p2 :: Position' a) <- liftM2 (,) arbitrary arbitrary
let [p1', p2'] = sort [p1, p2 { srcFile = srcFile p1 }]
return (Interval p1' p2')
instance (Ord a, Arbitrary a) => Arbitrary (Range' a) where
arbitrary = do
f <- arbitrary
intervalsToRange f . fuse . sort <$> arbitrary
where
fuse (i1 : i2 : is)
| iEnd i1 >= iStart i2 = fuse (fuseIntervals i1 i2 : is)
| otherwise = i1 : fuse (i2 : is)
fuse is = is
instance CoArbitrary RangeFile
instance CoArbitrary a => CoArbitrary (Position' a)
instance CoArbitrary a => CoArbitrary (Interval' a)
instance CoArbitrary a => CoArbitrary (Range' a)
prop_positionInvariant :: Position' Integer -> Bool
prop_positionInvariant = positionInvariant
prop_intervalInvariant :: Interval' Integer -> Bool
prop_intervalInvariant = intervalInvariant
prop_rangeInvariant :: Range -> Bool
prop_rangeInvariant = rangeInvariant
------------------------------------------------------------------------
-- * All tests
------------------------------------------------------------------------
Template Haskell hack to make the following $ allProperties work
under ghc-7.8 .
return [] -- KEEP!
| All tests as collected by ' allProperties ' .
--
Using ' allProperties ' is convenient and superior to the manual
-- enumeration of tests, since the name of the property is added
-- automatically.
tests :: TestTree
tests = testProperties "Internal.Syntax.Position" $allProperties
| null | https://raw.githubusercontent.com/agda/agda/c859b5e8737a006b559723a1048bba10806bda2d/test/Internal/Syntax/Position.hs | haskell | ----------------------------------------------------------------------
Test suite
| The positions corresponding to the interval. The positions do not
refer to characters, but to the positions between characters, with
| The positions corresponding to the range, including the
end-points.
| Constructs the least interval containing all the elements in the
set.
| Generates an interval located in the same file as the given
interval.
| Generates a range located in the same file as the given
range (if possible).
----------------------------------------------------------------------
* All tests
----------------------------------------------------------------------
KEEP!
enumeration of tests, since the name of the property is added
automatically. | # LANGUAGE TemplateHaskell #
module Internal.Syntax.Position ( tests ) where
import Agda.Syntax.Position
import Agda.Syntax.TopLevelModuleName
import Agda.Utils.FileName
import qualified Agda.Utils.Maybe.Strict as Strict
import Agda.Utils.List ( distinct )
import qualified Agda.Utils.List1 as List1
import Agda.Utils.Null ( null )
import Control.Monad
import Data.Int
import Data.List (sort)
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Text as T
import Internal.Helpers
import Internal.Syntax.Common ()
import Internal.Utils.FileName (rootPath)
import Internal.Utils.Maybe.Strict ()
import Prelude hiding ( null )
import System.FilePath
zero pointing to the position before the first character .
iPositions :: Interval' a -> Set Int32
iPositions i = Set.fromList [posPos (iStart i) .. posPos (iEnd i)]
rPositions :: Range' a -> Set Int32
rPositions r = Set.unions (map iPositions $ rangeIntervals r)
makeInterval :: Set Int32 -> Set Int32
makeInterval s
| Set.null s = Set.empty
| otherwise = Set.fromList [Set.findMin s .. Set.findMax s]
prop_iLength :: Interval' Integer -> Bool
prop_iLength i = iLength i >= 0
prop_startPos' :: Bool
prop_startPos' = positionInvariant (startPos' ())
prop_startPos :: Maybe RangeFile -> Bool
prop_startPos = positionInvariant . startPos
prop_noRange :: Bool
prop_noRange = rangeInvariant (noRange :: Range)
prop_posToRange' ::
Integer -> PositionWithoutFile -> PositionWithoutFile -> Bool
prop_posToRange' f p1 p2 =
rangeInvariant (posToRange' f p1 p2)
prop_posToRange :: Position' Integer -> Position' Integer -> Bool
prop_posToRange p1 p2 =
rangeInvariant (posToRange p1 (p2 { srcFile = srcFile p1 }))
prop_intervalToRange :: Integer -> IntervalWithoutFile -> Bool
prop_intervalToRange f i = rangeInvariant (intervalToRange f i)
rangeToIntervalPropertyTemplate ::
Ord a =>
(Range' Integer -> Maybe (Interval' a)) ->
Range' Integer -> Bool
rangeToIntervalPropertyTemplate r2i r = case r2i r of
Nothing -> r == noRange
Just i ->
r /= noRange
&&
intervalInvariant i
&&
iPositions i == makeInterval (rPositions r)
prop_rangeToIntervalWithFile :: Range' Integer -> Bool
prop_rangeToIntervalWithFile =
rangeToIntervalPropertyTemplate rangeToIntervalWithFile
prop_rangeToInterval :: Range' Integer -> Bool
prop_rangeToInterval =
rangeToIntervalPropertyTemplate rangeToInterval
prop_continuous :: Range -> Bool
prop_continuous r =
rangeInvariant cr &&
rPositions cr == makeInterval (rPositions r)
where cr = continuous r
prop_continuousPerLine :: Range -> Bool
prop_continuousPerLine r =
rangeInvariant r'
&&
distinct lineNumbers
&&
rangeFile r' == rangeFile r
where
r' = continuousPerLine r
lineNumbers = concatMap lines (rangeIntervals r')
where
lines i | s == e = [s]
| otherwise = [s, e]
where
s = posLine (iStart i)
e = posLine (iEnd i)
prop_fuseIntervals :: Interval' Integer -> Property
prop_fuseIntervals i1 =
forAll (intervalInSameFileAs i1) $ \i2 ->
let i = fuseIntervals i1 i2 in
intervalInvariant i &&
iPositions i ==
makeInterval (Set.union (iPositions i1) (iPositions i2))
prop_fuseRanges :: Range -> Property
prop_fuseRanges r1 =
forAll (rangeInSameFileAs r1) $ \r2 ->
let r = fuseRanges r1 r2 in
rangeInvariant r
&&
rPositions r == Set.union (rPositions r1) (rPositions r2)
prop_beginningOf :: Range -> Bool
prop_beginningOf r = rangeInvariant (beginningOf r)
prop_beginningOfFile :: Range -> Bool
prop_beginningOfFile r = rangeInvariant (beginningOfFile r)
instance Arbitrary a => Arbitrary (Position' a) where
arbitrary = do
srcFile <- arbitrary
Positive pos' <- arbitrary
let pos = fromInteger pos'
line = pred pos `div` 10 + 1
col = pred pos `mod` 10 + 1
return (Pn {srcFile = srcFile, posPos = pos,
posLine = line, posCol = col })
intervalInSameFileAs ::
(Arbitrary a, Ord a) => Interval' a -> Gen (Interval' a)
intervalInSameFileAs i =
setIntervalFile (srcFile $ iStart i) <$>
(arbitrary :: Gen IntervalWithoutFile)
prop_intervalInSameFileAs :: Interval' Integer -> Property
prop_intervalInSameFileAs i =
forAll (intervalInSameFileAs i) $ \i' ->
intervalInvariant i' &&
srcFile (iStart i) == srcFile (iStart i')
rangeInSameFileAs :: (Arbitrary a, Ord a) => Range' a -> Gen (Range' a)
rangeInSameFileAs NoRange = arbitrary
rangeInSameFileAs (Range f is) = do
Range _f is <- arbitrary `suchThat` (not . null)
return $ Range (f `asTypeOf` _f) is
prop_rangeInSameFileAs :: Range' Integer -> Property
prop_rangeInSameFileAs r =
forAll (rangeInSameFileAs r) $ \r' ->
rangeInvariant r'
&&
case (r, r') of
(NoRange, _) -> True
(Range f _, Range f' _) -> f == f'
(Range _ _, NoRange) -> False
instance Arbitrary RawTopLevelModuleName where
arbitrary = do
r <- arbitrary
parts <- list1Of (T.pack <$> listOf1 (elements "AB"))
return $ RawTopLevelModuleName
{ rawModuleNameRange = r
, rawModuleNameParts = parts
}
instance Arbitrary TopLevelModuleName where
arbitrary = do
raw <- arbitrary
return $
unsafeTopLevelModuleName raw
(hashRawTopLevelModuleName raw)
instance CoArbitrary TopLevelModuleName where
coarbitrary = coarbitrary . moduleNameId
instance Arbitrary RangeFile where
arbitrary = do
top <- arbitrary
extra <- take 2 . map (take 2) <$> listOf (listOf1 (elements "a1"))
let f = mkAbsolute $ joinPath $
rootPath : extra ++
map T.unpack (List1.toList (moduleNameParts top))
return $ mkRangeFile f (Just top)
instance (Arbitrary a, Ord a) => Arbitrary (Interval' a) where
arbitrary = do
(p1, p2 :: Position' a) <- liftM2 (,) arbitrary arbitrary
let [p1', p2'] = sort [p1, p2 { srcFile = srcFile p1 }]
return (Interval p1' p2')
instance (Ord a, Arbitrary a) => Arbitrary (Range' a) where
arbitrary = do
f <- arbitrary
intervalsToRange f . fuse . sort <$> arbitrary
where
fuse (i1 : i2 : is)
| iEnd i1 >= iStart i2 = fuse (fuseIntervals i1 i2 : is)
| otherwise = i1 : fuse (i2 : is)
fuse is = is
instance CoArbitrary RangeFile
instance CoArbitrary a => CoArbitrary (Position' a)
instance CoArbitrary a => CoArbitrary (Interval' a)
instance CoArbitrary a => CoArbitrary (Range' a)
prop_positionInvariant :: Position' Integer -> Bool
prop_positionInvariant = positionInvariant
prop_intervalInvariant :: Interval' Integer -> Bool
prop_intervalInvariant = intervalInvariant
prop_rangeInvariant :: Range -> Bool
prop_rangeInvariant = rangeInvariant
Template Haskell hack to make the following $ allProperties work
under ghc-7.8 .
| All tests as collected by ' allProperties ' .
Using ' allProperties ' is convenient and superior to the manual
tests :: TestTree
tests = testProperties "Internal.Syntax.Position" $allProperties
|
147ddc282a8d1651f171a8f391e18fa4cc79b62c0b25f1cfd43c070036d6dbb4 | sheepduke/silver-brain | concept-map.lisp | (in-package silver-brain-tests.service)
(setup
(config:set-profile :test)
(db:setup))
(teardown
(db::delete-file))
(defun setup-test ()
"Setup for each test."
)
| null | https://raw.githubusercontent.com/sheepduke/silver-brain/9d088bcd30948decc174f3569e2ad7bc0b3b50c1/backend/tests/service/concept-map.lisp | lisp | (in-package silver-brain-tests.service)
(setup
(config:set-profile :test)
(db:setup))
(teardown
(db::delete-file))
(defun setup-test ()
"Setup for each test."
)
| |
25c7ee0cb6d8d63fa0da97830a629b908159dd04cc87734827076f77a60795ba | clojure-interop/google-cloud-clients | HttpResourceManagerRpc.clj | (ns com.google.cloud.resourcemanager.spi.v1beta1.HttpResourceManagerRpc
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.resourcemanager.spi.v1beta1 HttpResourceManagerRpc]))
(defn ->http-resource-manager-rpc
"Constructor.
options - `com.google.cloud.resourcemanager.ResourceManagerOptions`"
(^HttpResourceManagerRpc [^com.google.cloud.resourcemanager.ResourceManagerOptions options]
(new HttpResourceManagerRpc options)))
(defn test-permissions
"Description copied from interface: ResourceManagerRpc
project-id - `java.lang.String`
permissions - `java.util.List`
returns: `java.util.List<java.lang.Boolean>`
throws: com.google.cloud.resourcemanager.ResourceManagerException - upon failure"
(^java.util.List [^HttpResourceManagerRpc this ^java.lang.String project-id ^java.util.List permissions]
(-> this (.testPermissions project-id permissions))))
(defn list
"Description copied from interface: ResourceManagerRpc
options - `java.util.Map`
returns: `com.google.cloud.Tuple<java.lang.String,java.lang.Iterable<com.google.api.services.cloudresourcemanager.model.Project>>`"
(^com.google.cloud.Tuple [^HttpResourceManagerRpc this ^java.util.Map options]
(-> this (.list options))))
(defn delete
"Description copied from interface: ResourceManagerRpc
project-id - `java.lang.String`"
([^HttpResourceManagerRpc this ^java.lang.String project-id]
(-> this (.delete project-id))))
(defn undelete
"Description copied from interface: ResourceManagerRpc
project-id - `java.lang.String`"
([^HttpResourceManagerRpc this ^java.lang.String project-id]
(-> this (.undelete project-id))))
(defn replace
"Description copied from interface: ResourceManagerRpc
project - `com.google.api.services.cloudresourcemanager.model.Project`
returns: `com.google.api.services.cloudresourcemanager.model.Project`"
(^com.google.api.services.cloudresourcemanager.model.Project [^HttpResourceManagerRpc this ^com.google.api.services.cloudresourcemanager.model.Project project]
(-> this (.replace project))))
(defn get-policy
"Description copied from interface: ResourceManagerRpc
project-id - `java.lang.String`
returns: `com.google.api.services.cloudresourcemanager.model.Policy`
throws: com.google.cloud.resourcemanager.ResourceManagerException - upon failure"
(^com.google.api.services.cloudresourcemanager.model.Policy [^HttpResourceManagerRpc this ^java.lang.String project-id]
(-> this (.getPolicy project-id))))
(defn create
"Description copied from interface: ResourceManagerRpc
project - `com.google.api.services.cloudresourcemanager.model.Project`
returns: `com.google.api.services.cloudresourcemanager.model.Project`"
(^com.google.api.services.cloudresourcemanager.model.Project [^HttpResourceManagerRpc this ^com.google.api.services.cloudresourcemanager.model.Project project]
(-> this (.create project))))
(defn replace-policy
"Description copied from interface: ResourceManagerRpc
project-id - `java.lang.String`
new-policy - `com.google.api.services.cloudresourcemanager.model.Policy`
returns: `com.google.api.services.cloudresourcemanager.model.Policy`
throws: com.google.cloud.resourcemanager.ResourceManagerException - upon failure"
(^com.google.api.services.cloudresourcemanager.model.Policy [^HttpResourceManagerRpc this ^java.lang.String project-id ^com.google.api.services.cloudresourcemanager.model.Policy new-policy]
(-> this (.replacePolicy project-id new-policy))))
(defn get
"Description copied from interface: ResourceManagerRpc
project-id - `java.lang.String`
options - `java.util.Map`
returns: `com.google.api.services.cloudresourcemanager.model.Project`"
(^com.google.api.services.cloudresourcemanager.model.Project [^HttpResourceManagerRpc this ^java.lang.String project-id ^java.util.Map options]
(-> this (.get project-id options))))
| null | https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.resourcemanager/src/com/google/cloud/resourcemanager/spi/v1beta1/HttpResourceManagerRpc.clj | clojure | (ns com.google.cloud.resourcemanager.spi.v1beta1.HttpResourceManagerRpc
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.resourcemanager.spi.v1beta1 HttpResourceManagerRpc]))
(defn ->http-resource-manager-rpc
"Constructor.
options - `com.google.cloud.resourcemanager.ResourceManagerOptions`"
(^HttpResourceManagerRpc [^com.google.cloud.resourcemanager.ResourceManagerOptions options]
(new HttpResourceManagerRpc options)))
(defn test-permissions
"Description copied from interface: ResourceManagerRpc
project-id - `java.lang.String`
permissions - `java.util.List`
returns: `java.util.List<java.lang.Boolean>`
throws: com.google.cloud.resourcemanager.ResourceManagerException - upon failure"
(^java.util.List [^HttpResourceManagerRpc this ^java.lang.String project-id ^java.util.List permissions]
(-> this (.testPermissions project-id permissions))))
(defn list
"Description copied from interface: ResourceManagerRpc
options - `java.util.Map`
returns: `com.google.cloud.Tuple<java.lang.String,java.lang.Iterable<com.google.api.services.cloudresourcemanager.model.Project>>`"
(^com.google.cloud.Tuple [^HttpResourceManagerRpc this ^java.util.Map options]
(-> this (.list options))))
(defn delete
"Description copied from interface: ResourceManagerRpc
project-id - `java.lang.String`"
([^HttpResourceManagerRpc this ^java.lang.String project-id]
(-> this (.delete project-id))))
(defn undelete
"Description copied from interface: ResourceManagerRpc
project-id - `java.lang.String`"
([^HttpResourceManagerRpc this ^java.lang.String project-id]
(-> this (.undelete project-id))))
(defn replace
"Description copied from interface: ResourceManagerRpc
project - `com.google.api.services.cloudresourcemanager.model.Project`
returns: `com.google.api.services.cloudresourcemanager.model.Project`"
(^com.google.api.services.cloudresourcemanager.model.Project [^HttpResourceManagerRpc this ^com.google.api.services.cloudresourcemanager.model.Project project]
(-> this (.replace project))))
(defn get-policy
"Description copied from interface: ResourceManagerRpc
project-id - `java.lang.String`
returns: `com.google.api.services.cloudresourcemanager.model.Policy`
throws: com.google.cloud.resourcemanager.ResourceManagerException - upon failure"
(^com.google.api.services.cloudresourcemanager.model.Policy [^HttpResourceManagerRpc this ^java.lang.String project-id]
(-> this (.getPolicy project-id))))
(defn create
"Description copied from interface: ResourceManagerRpc
project - `com.google.api.services.cloudresourcemanager.model.Project`
returns: `com.google.api.services.cloudresourcemanager.model.Project`"
(^com.google.api.services.cloudresourcemanager.model.Project [^HttpResourceManagerRpc this ^com.google.api.services.cloudresourcemanager.model.Project project]
(-> this (.create project))))
(defn replace-policy
"Description copied from interface: ResourceManagerRpc
project-id - `java.lang.String`
new-policy - `com.google.api.services.cloudresourcemanager.model.Policy`
returns: `com.google.api.services.cloudresourcemanager.model.Policy`
throws: com.google.cloud.resourcemanager.ResourceManagerException - upon failure"
(^com.google.api.services.cloudresourcemanager.model.Policy [^HttpResourceManagerRpc this ^java.lang.String project-id ^com.google.api.services.cloudresourcemanager.model.Policy new-policy]
(-> this (.replacePolicy project-id new-policy))))
(defn get
"Description copied from interface: ResourceManagerRpc
project-id - `java.lang.String`
options - `java.util.Map`
returns: `com.google.api.services.cloudresourcemanager.model.Project`"
(^com.google.api.services.cloudresourcemanager.model.Project [^HttpResourceManagerRpc this ^java.lang.String project-id ^java.util.Map options]
(-> this (.get project-id options))))
| |
e8cb974ffc294cf27ffc15cac34a0cab950d6fcc040e6572131fe6432ab64151 | fukamachi/clozure-cl | apropos-window.lisp | ;;;-*-Mode: LISP; Package: GUI -*-
;;;
Copyright ( C ) 2007 Clozure Associates
(in-package "GUI")
(defclass package-combo-box (ns:ns-combo-box)
((packages :initform nil))
(:metaclass ns:+ns-object))
;;; This is a premature optimization. Instead of calling LIST-ALL-PACKAGES
;;; so frequently, just get a fresh copy when the user clicks in the
;;; combo box.
(objc:defmethod (#/becomeFirstResponder :<BOOL>) ((self package-combo-box))
(with-slots (packages) self
(setf packages (coerce (list-all-packages) 'vector))
(setf packages (sort packages #'string-lessp :key #'package-name)))
(call-next-method))
(defclass apropos-window-controller (ns:ns-window-controller)
((apropos-array :foreign-type :id :initform +null-ptr+
:reader apropos-array
:documentation "Bound to NSArrayController in nib file")
(array-controller :foreign-type :id :accessor array-controller)
(combo-box :foreign-type :id :accessor combo-box)
(table-view :foreign-type :id :accessor table-view)
(text-view :foreign-type :id :accessor text-view)
(external-symbols-checkbox :foreign-type :id
:accessor external-symbols-checkbox)
(shows-external-symbols :initform nil)
(symbol-list :initform nil)
(package :initform nil)
(input :initform nil)
(previous-input :initform nil :accessor previous-input
:documentation "Last string entered"))
(:metaclass ns:+ns-object))
(defmethod (setf apropos-array) (value (self apropos-window-controller))
(with-slots (apropos-array) self
(unless (eql value apropos-array)
(#/release apropos-array)
(setf apropos-array (#/retain value)))))
Diasable automatic KVO notifications , since having our class swizzled
out from underneath us confuses CLOS . ( Leopard does n't hose us ,
and we can use automatic KVO notifications there . )
(objc:defmethod (#/automaticallyNotifiesObserversForKey: :<BOOL>) ((self +apropos-window-controller)
key)
(declare (ignore key))
nil)
(objc:defmethod (#/awakeFromNib :void) ((self apropos-window-controller))
(with-slots (table-view text-view) self
(#/setString: text-view #@"")
(#/setDelegate: table-view self)
(#/setDoubleAction: table-view (@selector #/definitionForSelectedSymbol:))))
(objc:defmethod #/init ((self apropos-window-controller))
(prog1
(#/initWithWindowNibName: self #@"apropos")
(#/setShouldCascadeWindows: self nil)
(#/setWindowFrameAutosaveName: self #@"apropos panel")
(setf (apropos-array self) (#/array ns:ns-mutable-array))))
(objc:defmethod (#/dealloc :void) ((self apropos-window-controller))
(#/release (slot-value self 'apropos-array))
(call-next-method))
(objc:defmethod (#/toggleShowsExternalSymbols: :void)
((self apropos-window-controller) sender)
(declare (ignore sender))
(with-slots (shows-external-symbols) self
(setf shows-external-symbols (not shows-external-symbols))
(update-symbol-list self)
(update-apropos-array self)))
(objc:defmethod (#/setPackage: :void) ((self apropos-window-controller)
sender)
(with-slots (combo-box package) self
(assert (eql sender combo-box))
(with-slots (packages) sender
(let ((index (#/indexOfSelectedItem sender)))
(if (minusp index)
(setf package nil) ;search all packages
(setf package (svref packages index))))))
(update-symbol-list self)
(update-apropos-array self))
(defmethod update-symbol-list ((self apropos-window-controller))
(with-slots (input package shows-external-symbols symbol-list) self
(when (plusp (length input))
(setf symbol-list nil)
(if package
(if shows-external-symbols
(do-external-symbols (sym package)
(when (ccl::%apropos-substring-p input (symbol-name sym))
(push sym symbol-list)))
(do-symbols (sym package)
(when (ccl::%apropos-substring-p input (symbol-name sym))
(push sym symbol-list))))
(if shows-external-symbols
(dolist (p (list-all-packages))
(do-external-symbols (sym p)
(when (ccl::%apropos-substring-p input (symbol-name sym))
(push sym symbol-list))))
(do-all-symbols (sym)
(when (ccl::%apropos-substring-p input (symbol-name sym))
(push sym symbol-list)))))
(setf symbol-list (sort symbol-list #'string-lessp)))))
(defmethod update-apropos-array ((self apropos-window-controller))
(with-slots (input apropos-array symbol-list package) self
(when (plusp (length input))
(let ((new-array (#/array ns:ns-mutable-array))
(*package* (or package (find-package "COMMON-LISP-USER")))
(n 0))
(dolist (s symbol-list)
(#/addObject: new-array (#/dictionaryWithObjectsAndKeys:
ns:ns-dictionary
(#/autorelease
(%make-nsstring
(prin1-to-string s)))
#@"symbol"
(#/numberWithInt: ns:ns-number n)
#@"index"
(#/autorelease
(%make-nsstring
(inspector::symbol-type-line s)))
#@"kind"
+null-ptr+))
(incf n))
(#/willChangeValueForKey: self #@"aproposArray")
(setf apropos-array new-array)
(#/didChangeValueForKey: self #@"aproposArray")))))
(objc:defmethod (#/apropos: :void) ((self apropos-window-controller) sender)
(let* ((input (lisp-string-from-nsstring (#/stringValue sender))))
(when (and (plusp (length input))
(not (string-equal input (previous-input self))))
(setf (slot-value self 'input) input)
(setf (previous-input self) input)
(update-symbol-list self)
(update-apropos-array self))))
(objc:defmethod (#/inspectSelectedSymbol: :void) ((self apropos-window-controller) sender)
(declare (ignorable sender))
(let* ((row (#/clickedRow (table-view self))))
(unless (minusp row)
(with-slots (array-controller symbol-list) self
(let* ((number (#/valueForKeyPath: array-controller #@"selection.index"))
(i (#/intValue number))
(sym (elt symbol-list i)))
(inspect sym))))))
(objc:defmethod (#/definitionForSelectedSymbol: :void) ((self apropos-window-controller) sender)
(declare (ignorable sender))
(let* ((row (#/clickedRow (table-view self))))
(unless (minusp row)
(with-slots (array-controller symbol-list) self
(let* ((number (#/valueForKeyPath: array-controller #@"selection.index"))
(i (#/intValue number))
(sym (elt symbol-list i)))
(hemlock::edit-definition sym))))))
;;; Data source methods for package combo box
(objc:defmethod (#/numberOfItemsInComboBox: :<NSI>nteger) ((self apropos-window-controller)
combo-box)
(declare (ignore combo-box))
(length (list-all-packages)))
(objc:defmethod #/comboBox:objectValueForItemAtIndex: ((self apropos-window-controller)
combo-box
(index :<NSI>nteger))
(with-slots (packages) combo-box
(let* ((pkg-name (package-name (svref packages index))))
(if pkg-name
(#/autorelease (%make-nsstring pkg-name))
+null-ptr+))))
(objc:defmethod #/comboBox:completedString: ((self apropos-window-controller)
combo-box
partial-string)
(flet ((string-prefix-p (s1 s2)
"Is s1 a prefix of s2?"
(string-equal s1 s2 :end2 (min (length s1) (length s2)))))
(with-slots (packages) combo-box
(let* ((s (lisp-string-from-nsstring partial-string)))
(dotimes (i (length packages) +null-ptr+)
(let ((name (package-name (svref packages i))))
(when (string-prefix-p s name)
(return (#/autorelease (%make-nsstring name))))))))))
(objc:defmethod (#/comboBox:indexOfItemWithStringValue: :<NSUI>nteger)
((self apropos-window-controller)
combo-box
string)
(with-slots (packages) combo-box
(let* ((s (lisp-string-from-nsstring string)))
(or (position s packages :test #'(lambda (str pkg)
(string-equal str (package-name pkg))))
#$NSNotFound))))
;;; Table view delegate methods
(objc:defmethod (#/tableViewSelectionDidChange: :void) ((self apropos-window-controller)
notification)
(with-slots (array-controller symbol-list text-view) self
(let* ((tv (#/object notification))
(row (#/selectedRow tv)))
(unless (minusp row)
(let* ((number (#/valueForKeyPath:
array-controller #@"selection.index"))
(i (#/intValue number))
(sym (elt symbol-list i))
(info (make-array '(0) :element-type 'base-char
:fill-pointer 0 :adjustable t)))
(with-output-to-string (s info)
(dolist (doctype '(compiler-macro function method-combination
setf structure t type variable))
(let ((docstring (documentation sym doctype)))
(when docstring
(format s "~&~a" docstring))
(when (eq doctype 'function)
(format s "~&arglist: ~s" (arglist sym))))))
(if (plusp (length info))
(#/setString: text-view (#/autorelease (%make-nsstring info)))
(#/setString: text-view #@"")))))))
| null | https://raw.githubusercontent.com/fukamachi/clozure-cl/4b0c69452386ae57b08984ed815d9b50b4bcc8a2/cocoa-ide/apropos-window.lisp | lisp | -*-Mode: LISP; Package: GUI -*-
This is a premature optimization. Instead of calling LIST-ALL-PACKAGES
so frequently, just get a fresh copy when the user clicks in the
combo box.
search all packages
Data source methods for package combo box
Table view delegate methods | Copyright ( C ) 2007 Clozure Associates
(in-package "GUI")
(defclass package-combo-box (ns:ns-combo-box)
((packages :initform nil))
(:metaclass ns:+ns-object))
(objc:defmethod (#/becomeFirstResponder :<BOOL>) ((self package-combo-box))
(with-slots (packages) self
(setf packages (coerce (list-all-packages) 'vector))
(setf packages (sort packages #'string-lessp :key #'package-name)))
(call-next-method))
(defclass apropos-window-controller (ns:ns-window-controller)
((apropos-array :foreign-type :id :initform +null-ptr+
:reader apropos-array
:documentation "Bound to NSArrayController in nib file")
(array-controller :foreign-type :id :accessor array-controller)
(combo-box :foreign-type :id :accessor combo-box)
(table-view :foreign-type :id :accessor table-view)
(text-view :foreign-type :id :accessor text-view)
(external-symbols-checkbox :foreign-type :id
:accessor external-symbols-checkbox)
(shows-external-symbols :initform nil)
(symbol-list :initform nil)
(package :initform nil)
(input :initform nil)
(previous-input :initform nil :accessor previous-input
:documentation "Last string entered"))
(:metaclass ns:+ns-object))
(defmethod (setf apropos-array) (value (self apropos-window-controller))
(with-slots (apropos-array) self
(unless (eql value apropos-array)
(#/release apropos-array)
(setf apropos-array (#/retain value)))))
Diasable automatic KVO notifications , since having our class swizzled
out from underneath us confuses CLOS . ( Leopard does n't hose us ,
and we can use automatic KVO notifications there . )
(objc:defmethod (#/automaticallyNotifiesObserversForKey: :<BOOL>) ((self +apropos-window-controller)
key)
(declare (ignore key))
nil)
(objc:defmethod (#/awakeFromNib :void) ((self apropos-window-controller))
(with-slots (table-view text-view) self
(#/setString: text-view #@"")
(#/setDelegate: table-view self)
(#/setDoubleAction: table-view (@selector #/definitionForSelectedSymbol:))))
(objc:defmethod #/init ((self apropos-window-controller))
(prog1
(#/initWithWindowNibName: self #@"apropos")
(#/setShouldCascadeWindows: self nil)
(#/setWindowFrameAutosaveName: self #@"apropos panel")
(setf (apropos-array self) (#/array ns:ns-mutable-array))))
(objc:defmethod (#/dealloc :void) ((self apropos-window-controller))
(#/release (slot-value self 'apropos-array))
(call-next-method))
(objc:defmethod (#/toggleShowsExternalSymbols: :void)
((self apropos-window-controller) sender)
(declare (ignore sender))
(with-slots (shows-external-symbols) self
(setf shows-external-symbols (not shows-external-symbols))
(update-symbol-list self)
(update-apropos-array self)))
(objc:defmethod (#/setPackage: :void) ((self apropos-window-controller)
sender)
(with-slots (combo-box package) self
(assert (eql sender combo-box))
(with-slots (packages) sender
(let ((index (#/indexOfSelectedItem sender)))
(if (minusp index)
(setf package (svref packages index))))))
(update-symbol-list self)
(update-apropos-array self))
(defmethod update-symbol-list ((self apropos-window-controller))
(with-slots (input package shows-external-symbols symbol-list) self
(when (plusp (length input))
(setf symbol-list nil)
(if package
(if shows-external-symbols
(do-external-symbols (sym package)
(when (ccl::%apropos-substring-p input (symbol-name sym))
(push sym symbol-list)))
(do-symbols (sym package)
(when (ccl::%apropos-substring-p input (symbol-name sym))
(push sym symbol-list))))
(if shows-external-symbols
(dolist (p (list-all-packages))
(do-external-symbols (sym p)
(when (ccl::%apropos-substring-p input (symbol-name sym))
(push sym symbol-list))))
(do-all-symbols (sym)
(when (ccl::%apropos-substring-p input (symbol-name sym))
(push sym symbol-list)))))
(setf symbol-list (sort symbol-list #'string-lessp)))))
(defmethod update-apropos-array ((self apropos-window-controller))
(with-slots (input apropos-array symbol-list package) self
(when (plusp (length input))
(let ((new-array (#/array ns:ns-mutable-array))
(*package* (or package (find-package "COMMON-LISP-USER")))
(n 0))
(dolist (s symbol-list)
(#/addObject: new-array (#/dictionaryWithObjectsAndKeys:
ns:ns-dictionary
(#/autorelease
(%make-nsstring
(prin1-to-string s)))
#@"symbol"
(#/numberWithInt: ns:ns-number n)
#@"index"
(#/autorelease
(%make-nsstring
(inspector::symbol-type-line s)))
#@"kind"
+null-ptr+))
(incf n))
(#/willChangeValueForKey: self #@"aproposArray")
(setf apropos-array new-array)
(#/didChangeValueForKey: self #@"aproposArray")))))
(objc:defmethod (#/apropos: :void) ((self apropos-window-controller) sender)
(let* ((input (lisp-string-from-nsstring (#/stringValue sender))))
(when (and (plusp (length input))
(not (string-equal input (previous-input self))))
(setf (slot-value self 'input) input)
(setf (previous-input self) input)
(update-symbol-list self)
(update-apropos-array self))))
(objc:defmethod (#/inspectSelectedSymbol: :void) ((self apropos-window-controller) sender)
(declare (ignorable sender))
(let* ((row (#/clickedRow (table-view self))))
(unless (minusp row)
(with-slots (array-controller symbol-list) self
(let* ((number (#/valueForKeyPath: array-controller #@"selection.index"))
(i (#/intValue number))
(sym (elt symbol-list i)))
(inspect sym))))))
(objc:defmethod (#/definitionForSelectedSymbol: :void) ((self apropos-window-controller) sender)
(declare (ignorable sender))
(let* ((row (#/clickedRow (table-view self))))
(unless (minusp row)
(with-slots (array-controller symbol-list) self
(let* ((number (#/valueForKeyPath: array-controller #@"selection.index"))
(i (#/intValue number))
(sym (elt symbol-list i)))
(hemlock::edit-definition sym))))))
(objc:defmethod (#/numberOfItemsInComboBox: :<NSI>nteger) ((self apropos-window-controller)
combo-box)
(declare (ignore combo-box))
(length (list-all-packages)))
(objc:defmethod #/comboBox:objectValueForItemAtIndex: ((self apropos-window-controller)
combo-box
(index :<NSI>nteger))
(with-slots (packages) combo-box
(let* ((pkg-name (package-name (svref packages index))))
(if pkg-name
(#/autorelease (%make-nsstring pkg-name))
+null-ptr+))))
(objc:defmethod #/comboBox:completedString: ((self apropos-window-controller)
combo-box
partial-string)
(flet ((string-prefix-p (s1 s2)
"Is s1 a prefix of s2?"
(string-equal s1 s2 :end2 (min (length s1) (length s2)))))
(with-slots (packages) combo-box
(let* ((s (lisp-string-from-nsstring partial-string)))
(dotimes (i (length packages) +null-ptr+)
(let ((name (package-name (svref packages i))))
(when (string-prefix-p s name)
(return (#/autorelease (%make-nsstring name))))))))))
(objc:defmethod (#/comboBox:indexOfItemWithStringValue: :<NSUI>nteger)
((self apropos-window-controller)
combo-box
string)
(with-slots (packages) combo-box
(let* ((s (lisp-string-from-nsstring string)))
(or (position s packages :test #'(lambda (str pkg)
(string-equal str (package-name pkg))))
#$NSNotFound))))
(objc:defmethod (#/tableViewSelectionDidChange: :void) ((self apropos-window-controller)
notification)
(with-slots (array-controller symbol-list text-view) self
(let* ((tv (#/object notification))
(row (#/selectedRow tv)))
(unless (minusp row)
(let* ((number (#/valueForKeyPath:
array-controller #@"selection.index"))
(i (#/intValue number))
(sym (elt symbol-list i))
(info (make-array '(0) :element-type 'base-char
:fill-pointer 0 :adjustable t)))
(with-output-to-string (s info)
(dolist (doctype '(compiler-macro function method-combination
setf structure t type variable))
(let ((docstring (documentation sym doctype)))
(when docstring
(format s "~&~a" docstring))
(when (eq doctype 'function)
(format s "~&arglist: ~s" (arglist sym))))))
(if (plusp (length info))
(#/setString: text-view (#/autorelease (%make-nsstring info)))
(#/setString: text-view #@"")))))))
|
6848c262c1db07184f78a50efc7fe89ff8edacd061d2f72d241f8c0e10957404 | cpeikert/Lol | SimpleCycRepBenches.hs | |
Module : Crypto . Lol . Benchmarks . SimpleCycRepBenches
Description : Benchmarks for the ' CycRep ' interface , without benchmark harness .
Copyright : ( c ) , 2011 - 2017
, 2011 - 2017
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Benchmarks for the ' CycRep ' interface , without benchmark
harness ( for performance comparison ) .
Module : Crypto.Lol.Benchmarks.SimpleCycRepBenches
Description : Benchmarks for the 'CycRep' interface, without benchmark harness.
Copyright : (c) Eric Crockett, 2011-2017
Chris Peikert, 2011-2017
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Benchmarks for the 'CycRep' interface, without benchmark
harness (for performance comparison).
-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE NoImplicitPrelude #
# LANGUAGE PartialTypeSignatures #
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
# OPTIONS_GHC -fno - warn - partial - type - signatures #
module Crypto.Lol.Benchmarks.SimpleCycRepBenches
( simpleCycRepBenches1, simpleCycRepBenches2
) where
import Control.Applicative
import Control.Monad.Random hiding (lift)
import Crypto.Lol.Cyclotomic.CycRep
import Crypto.Lol.Prelude
import Crypto.Lol.Types
import Crypto.Random
import Criterion
| Benchmarks for single - index operations . There must be a CRT basis for \(O_m\ ) over @r@.
# INLINE simpleCycRepBenches1 #
simpleCycRepBenches1 :: forall t m r (gen :: *) . _
=> Proxy '(t,m,r) -> Proxy gen -> IO Benchmark
simpleCycRepBenches1 _ _ = do
-- x1 :: CycRep t P m (r, r) <- getRandom
-- let x1' = toDec x1
-- (Right x2) :: CycRepPC t m (r, r) <- getRandom
x3 :: CycRepEC t m r <- pcToEC <$> getRandom
x4 :: CycRep t P m r <- getRandom
let x5 = toDec x4
(Right x6) :: CycRepPC t m r <- getRandom
let x4' = mulGPow x4
x5' = mulGDec x5
gen <- newGenIO
return $ bgroup "SCycRep" [
-- bench "unzipPow" $ nf unzipPow x1,
-- bench "unzipDec" $ nf unzipDec x1',
-- bench "unzipCRT" $ nf unzipCRTC x2,
bench "zipWith (*)" $ nf (x3*) x3,
bench "crt" $ nf toCRT x4,
bench "crtInv" $ nf toPow x6,
bench "l" $ nf toPow x5,
bench "lInv" $ nf toDec x4,
bench "*g Pow" $ nf mulGPow x4,
bench "*g Dec" $ nf mulGDec x5,
bench "*g CRT" $ nf mulGCRTC x6,
bench "divg Pow" $ nf divGPow x4',
bench "divg Dec" $ nf divGDec x5',
bench "divg CRT" $ nf divGCRTC x6,
bench "lift" $ nf lift x4,
bench "error" $ nf (evalRand (roundedGaussian (0.1 :: Double) :: Rand (CryptoRand gen) (CycRep t D m Int64))) gen
]
| Benchmarks for inter - ring operations . There must be a CRT basis for ) over @r@.
# INLINE simpleCycRepBenches2 #
simpleCycRepBenches2 :: forall t m m' r . (m `Divides` m', _) => Proxy '(t,m,m',r) -> IO Benchmark
simpleCycRepBenches2 _ = do
x4 :: CycRep t P m' r <- getRandom
let x5 = toDec x4
(Right x6) :: CycRepPC t m' r <- getRandom
x7 :: CycRep t P m r <- getRandom
-- let x8 = toDec x7
(Right x9) :: CycRepPC t m r <- getRandom
return $ bgroup "SCycRep" [
bench "twacePow" $ nf (twacePow :: CycRep t P m' r -> CycRep t P m r) x4,
bench "twaceDec" $ nf (twaceDec :: CycRep t D m' r -> CycRep t D m r) x5,
bench "twaceCRT" $ nf (twaceCRTC :: CycRep t C m' r -> CycRepPC t m r) x6,
bench "embedPow" $ nf (embedPow :: CycRep t P m r -> CycRep t P m' r) x7,
-- bench "embedDec" $ nf (embedDec :: CycRep t D m r -> CycRep t D m' r) x8,
bench "embedCRT" $ nf (embedCRTC :: CycRep t C m r -> CycRepPC t m' r) x9
]
pcToEC :: CycRepPC t m r -> CycRepEC t m r
pcToEC (Right x) = Right x
| null | https://raw.githubusercontent.com/cpeikert/Lol/4416ac4f03b0bff08cb1115c72a45eed1fa48ec3/lol/Crypto/Lol/Benchmarks/SimpleCycRepBenches.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
x1 :: CycRep t P m (r, r) <- getRandom
let x1' = toDec x1
(Right x2) :: CycRepPC t m (r, r) <- getRandom
bench "unzipPow" $ nf unzipPow x1,
bench "unzipDec" $ nf unzipDec x1',
bench "unzipCRT" $ nf unzipCRTC x2,
let x8 = toDec x7
bench "embedDec" $ nf (embedDec :: CycRep t D m r -> CycRep t D m' r) x8, | |
Module : Crypto . Lol . Benchmarks . SimpleCycRepBenches
Description : Benchmarks for the ' CycRep ' interface , without benchmark harness .
Copyright : ( c ) , 2011 - 2017
, 2011 - 2017
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Benchmarks for the ' CycRep ' interface , without benchmark
harness ( for performance comparison ) .
Module : Crypto.Lol.Benchmarks.SimpleCycRepBenches
Description : Benchmarks for the 'CycRep' interface, without benchmark harness.
Copyright : (c) Eric Crockett, 2011-2017
Chris Peikert, 2011-2017
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Benchmarks for the 'CycRep' interface, without benchmark
harness (for performance comparison).
-}
# LANGUAGE NoImplicitPrelude #
# LANGUAGE PartialTypeSignatures #
# LANGUAGE TypeFamilies #
# OPTIONS_GHC -fno - warn - partial - type - signatures #
module Crypto.Lol.Benchmarks.SimpleCycRepBenches
( simpleCycRepBenches1, simpleCycRepBenches2
) where
import Control.Applicative
import Control.Monad.Random hiding (lift)
import Crypto.Lol.Cyclotomic.CycRep
import Crypto.Lol.Prelude
import Crypto.Lol.Types
import Crypto.Random
import Criterion
| Benchmarks for single - index operations . There must be a CRT basis for \(O_m\ ) over @r@.
# INLINE simpleCycRepBenches1 #
simpleCycRepBenches1 :: forall t m r (gen :: *) . _
=> Proxy '(t,m,r) -> Proxy gen -> IO Benchmark
simpleCycRepBenches1 _ _ = do
x3 :: CycRepEC t m r <- pcToEC <$> getRandom
x4 :: CycRep t P m r <- getRandom
let x5 = toDec x4
(Right x6) :: CycRepPC t m r <- getRandom
let x4' = mulGPow x4
x5' = mulGDec x5
gen <- newGenIO
return $ bgroup "SCycRep" [
bench "zipWith (*)" $ nf (x3*) x3,
bench "crt" $ nf toCRT x4,
bench "crtInv" $ nf toPow x6,
bench "l" $ nf toPow x5,
bench "lInv" $ nf toDec x4,
bench "*g Pow" $ nf mulGPow x4,
bench "*g Dec" $ nf mulGDec x5,
bench "*g CRT" $ nf mulGCRTC x6,
bench "divg Pow" $ nf divGPow x4',
bench "divg Dec" $ nf divGDec x5',
bench "divg CRT" $ nf divGCRTC x6,
bench "lift" $ nf lift x4,
bench "error" $ nf (evalRand (roundedGaussian (0.1 :: Double) :: Rand (CryptoRand gen) (CycRep t D m Int64))) gen
]
| Benchmarks for inter - ring operations . There must be a CRT basis for ) over @r@.
# INLINE simpleCycRepBenches2 #
simpleCycRepBenches2 :: forall t m m' r . (m `Divides` m', _) => Proxy '(t,m,m',r) -> IO Benchmark
simpleCycRepBenches2 _ = do
x4 :: CycRep t P m' r <- getRandom
let x5 = toDec x4
(Right x6) :: CycRepPC t m' r <- getRandom
x7 :: CycRep t P m r <- getRandom
(Right x9) :: CycRepPC t m r <- getRandom
return $ bgroup "SCycRep" [
bench "twacePow" $ nf (twacePow :: CycRep t P m' r -> CycRep t P m r) x4,
bench "twaceDec" $ nf (twaceDec :: CycRep t D m' r -> CycRep t D m r) x5,
bench "twaceCRT" $ nf (twaceCRTC :: CycRep t C m' r -> CycRepPC t m r) x6,
bench "embedPow" $ nf (embedPow :: CycRep t P m r -> CycRep t P m' r) x7,
bench "embedCRT" $ nf (embedCRTC :: CycRep t C m r -> CycRepPC t m' r) x9
]
pcToEC :: CycRepPC t m r -> CycRepEC t m r
pcToEC (Right x) = Right x
|
5c3b5f50bdcbf17b9c98d4d7b57878ee6f661bd76397faa08598bb7d01a7497c | racket/htdp | htdp-beginner.rkt | ;; Implements the Beginner Scheme language, at least in terms of the
;; forms and procedures. The reader-level aspects of the language
;; (e.g., case-sensitivity) are not implemented here.
#lang scheme/base
(require mzlib/etc
mzlib/list
syntax/docprovide
"private/rewrite-error-message.rkt"
(for-syntax "private/rewrite-error-message.rkt")
(for-syntax scheme/base))
(require "private/provide-and-scribble.rkt")
;; Implements the forms:
(require "private/teach.rkt"
"private/teach-module-begin.rkt"
test-engine/racket-tests)
;; syntax:
(provide (rename-out
[beginner-define define]
[beginner-define-struct define-struct]
[beginner-lambda lambda]
[beginner-lambda λ]
[beginner-app #%app]
[beginner-top #%top]
[beginner-cond cond]
[beginner-else else]
[beginner-if if]
[beginner-and and]
[beginner-or or]
[beginner-quote quote]
[beginner-module-begin #%module-begin]
[beginner-require require]
[beginner-dots ..]
[beginner-dots ...]
[beginner-dots ....]
[beginner-dots .....]
[beginner-dots ......]
[beginner-true true]
[beginner-false false]
)
check-expect
check-random
check-satisfied
check-within
check-error
check-member-of
check-range
#%datum
#%top-interaction
empty
signature : - > mixed one - of predicate combined
Number Real Rational Integer Natural Boolean True False String Symbol - list Any
; cons-of
; Property
; check-property for-all ==> expect expect-within expect-member-of expect-range
)
;; procedures:
(provide-and-scribble
procedures
(begin)
(all-from beginner: (submod lang/private/beginner-funs with-wrapper) procedures))
special case , as suggested by
(require (only-in lang/posn beginner-posn*))
(provide (rename-out (beginner-posn* posn)))
| null | https://raw.githubusercontent.com/racket/htdp/aa78794fa1788358d6abd11dad54b3c9f4f5a80b/htdp-lib/lang/htdp-beginner.rkt | racket | Implements the Beginner Scheme language, at least in terms of the
forms and procedures. The reader-level aspects of the language
(e.g., case-sensitivity) are not implemented here.
Implements the forms:
syntax:
cons-of
Property
check-property for-all ==> expect expect-within expect-member-of expect-range
procedures: |
#lang scheme/base
(require mzlib/etc
mzlib/list
syntax/docprovide
"private/rewrite-error-message.rkt"
(for-syntax "private/rewrite-error-message.rkt")
(for-syntax scheme/base))
(require "private/provide-and-scribble.rkt")
(require "private/teach.rkt"
"private/teach-module-begin.rkt"
test-engine/racket-tests)
(provide (rename-out
[beginner-define define]
[beginner-define-struct define-struct]
[beginner-lambda lambda]
[beginner-lambda λ]
[beginner-app #%app]
[beginner-top #%top]
[beginner-cond cond]
[beginner-else else]
[beginner-if if]
[beginner-and and]
[beginner-or or]
[beginner-quote quote]
[beginner-module-begin #%module-begin]
[beginner-require require]
[beginner-dots ..]
[beginner-dots ...]
[beginner-dots ....]
[beginner-dots .....]
[beginner-dots ......]
[beginner-true true]
[beginner-false false]
)
check-expect
check-random
check-satisfied
check-within
check-error
check-member-of
check-range
#%datum
#%top-interaction
empty
signature : - > mixed one - of predicate combined
Number Real Rational Integer Natural Boolean True False String Symbol - list Any
)
(provide-and-scribble
procedures
(begin)
(all-from beginner: (submod lang/private/beginner-funs with-wrapper) procedures))
special case , as suggested by
(require (only-in lang/posn beginner-posn*))
(provide (rename-out (beginner-posn* posn)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.