_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 |
|---|---|---|---|---|---|---|---|---|
753a911aee1b41f26c41cc026657820d228017ff554325200e102a6b475a4aef | weblocks-framework/weblocks | html-template.lisp |
(in-package :cm)
(export '(html-template with-widget-header render-widget-body))
(defwidget html-template (widget)
((tp :accessor tp :initform nil)
(src :type string :accessor src :initarg :src :initform nil)
(file :type pathname :accessor file :initarg :file :initform nil)
(vars :type list :accessor vars :initarg :vars :initform nil))
(:documentation "Models a HTML-TEMPLATE from a file."))
(defmethod initialize-instance :after ((obj html-template) &rest args)
(unless (or (file obj) (src obj)
(error "You need to specify either a template file (initarg :FILE) or a template
string (initarg :SRC) when creating a HTML-TEMPLATE widget.")))
(setf (tp obj) (html-template:create-template-printer (or (src obj)
(pathname (file obj))))))
(defmethod with-widget-header ((widget html-template) body-fn &rest args)
(apply body-fn widget args))
(defmethod render-widget-body ((widget html-template) &rest args)
(html-template:fill-and-print-template (tp widget) (vars widget)
:stream *weblocks-output-stream*))
| null | https://raw.githubusercontent.com/weblocks-framework/weblocks/fe96152458c8eb54d74751b3201db42dafe1708b/contrib/nunb/templates-crufty/html-template.lisp | lisp |
(in-package :cm)
(export '(html-template with-widget-header render-widget-body))
(defwidget html-template (widget)
((tp :accessor tp :initform nil)
(src :type string :accessor src :initarg :src :initform nil)
(file :type pathname :accessor file :initarg :file :initform nil)
(vars :type list :accessor vars :initarg :vars :initform nil))
(:documentation "Models a HTML-TEMPLATE from a file."))
(defmethod initialize-instance :after ((obj html-template) &rest args)
(unless (or (file obj) (src obj)
(error "You need to specify either a template file (initarg :FILE) or a template
string (initarg :SRC) when creating a HTML-TEMPLATE widget.")))
(setf (tp obj) (html-template:create-template-printer (or (src obj)
(pathname (file obj))))))
(defmethod with-widget-header ((widget html-template) body-fn &rest args)
(apply body-fn widget args))
(defmethod render-widget-body ((widget html-template) &rest args)
(html-template:fill-and-print-template (tp widget) (vars widget)
:stream *weblocks-output-stream*))
| |
ac4ea9d396a8b8dbf4e6ebb2cff3d75b01b77bc0ec72e51d8616cbad6c37a49c | cdfa/frugel | Prelude.hs | # LANGUAGE KindSignatures #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
module Prelude
( module Prelude
, module Relude
, module Control.Monad.Reader
, (><)
, toList
, dup
) where
import Control.Monad.Reader
( MonadReader(..), Reader, ReaderT(ReaderT), asks, mapReader, mapReaderT
, runReader, runReaderT, withReader, withReaderT )
import qualified Data.Foldable as Foldable
import Data.List ( groupBy )
import Data.Sequence ( (><) )
import GHC.Exts
import Relude
hiding ( Sum, abs, group, newEmptyMVar, newMVar, putMVar, readMVar, swapMVar
, takeMVar, toList, truncate, tryPutMVar, tryReadMVar, tryTakeMVar )
import Relude.Extra.Tuple
infixl 4 <<$>
(<<$>) :: (Functor f, Functor g) => a -> f (g b) -> f (g a)
(<<$>) a ffb = (a <$) <$> ffb
infixr 9 <.>
(<.>) :: Functor f => (a -> b) -> (c -> f a) -> c -> f b
f1 <.> f2 = fmap f1 . f2
lift2 :: forall (s :: (Type -> Type)
-> Type
-> Type) t m a.
(MonadTrans s, MonadTrans t, Monad (t m), Monad m)
=> m a
-> s (t m) a
lift2 = lift . lift
-- From -ht-0.0.16/docs/src/Data.Function.HT.Private.html#nest
{-# INLINE nTimes #-}
nTimes :: Int -> (a -> a) -> a -> a
nTimes 0 _ x = x
nTimes n f x = f (nTimes (n - 1) f x)
applyWhen :: Bool -> (a -> a) -> a -> a
applyWhen condition f = chain @Maybe (f <$ guard condition)
chain :: Foldable t => t (a -> a) -> a -> a
chain = foldr (.) id
-- >>> concatBy leftToMaybe Left [Left "h", Left "i", Right 1]
[ Left " hi",Right 1 ]
concatBy :: Monoid b => (a -> Maybe b) -> (b -> a) -> [a] -> [a]
concatBy _ _ [] = []
concatBy toMonoid toElement xs = case spanMaybe toMonoid xs of
([], y : ys) -> y : concatBy' ys
(zs, ys) -> toElement (mconcat zs) : concatBy' ys
where
concatBy' = concatBy toMonoid toElement
-- From -3.4.0.0/docs/src/Distribution.Utils.Generic.html#spanMaybe
-- >>> spanMaybe leftToMaybe [Left "h", Left "i", Right 1]
-- (["h","i"],[Right 1])
spanMaybe :: (t -> Maybe a) -> [t] -> ([a], [t])
spanMaybe _ xs@[] = ([], xs)
spanMaybe p xs@(x : xs') = case p x of
Just y -> let (ys, zs) = spanMaybe p xs' in (y : ys, zs)
Nothing -> ([], xs)
spanEnd :: (a -> Bool) -> [a] -> ([a], [a])
spanEnd p = swap . bimap reverse reverse . span p . reverse
-- Modified from -lib-1.20.4/docs/src/Hledger.Utils.html#splitAtElement
-- >>> splitOn ' ' " switch the accumulator to the other mode "
-- ["","switch","","","the","accumulator","to","the","other","mode","","",""]
splitOn :: Eq a => a -> [a] -> [[a]]
splitOn x l = prefix : rest'
where
(prefix, rest) = break (x ==) l
rest' = case rest of
[] -> []
e : es | e == x -> splitOn x es
es -> splitOn x es
From :
-- | Fair n-way interleaving: given a finite number of (possibly infinite)
lists , produce a single list such that whenever @v@ has finite index in one
of the input lists , @v@ also has finite index in the output list . No list 's
-- elements occur more frequently (on average) than another's.
interleave :: [[a]] -> [a]
interleave = concat . transpose
{-# INLINE fromFoldable #-}
| Convert from ' Data . Foldable . Foldable ' to an ' IsList ' type .
fromFoldable :: (Foldable f, IsList a) => f (Item a) -> a
fromFoldable = fromList . Foldable.toList
-- foldAlt :: (Foldable t, Alternative f) => t a -> f a
foldAlt = getAlt . ( Alt . pure )
Copied from -1.7.9/docs/src/Data.List.Extra.html#groupSort
groupSortOn :: Ord b => (a -> b) -> [a] -> [[a]]
groupSortOn f
= map (map snd)
. groupBy ((==) `on` fst)
. sortBy (compare `on` fst)
. map (f &&& id)
Copied from -0.4.0.1/docs/src/Data.List.Index.html#insertAt
{- |
'insertAt' inserts an element at the given position:
@
(insertAt i x xs) !! i == x
@
If the index is negative or exceeds list length, the original list will be returned. (If the index is equal to the list length, the insertion can be carried out.)
-}
insertAt :: Int -> a -> [a] -> [a]
insertAt i a ls | i < 0 = ls
| otherwise = go i ls
where
go 0 xs = a : xs
go n (x : xs) = x : go (n - 1) xs
go _ [] = []
| null | https://raw.githubusercontent.com/cdfa/frugel/9c59f2281c06bfa5e13bd575866d165dbc0ce411/prelude/Prelude.hs | haskell | From -ht-0.0.16/docs/src/Data.Function.HT.Private.html#nest
# INLINE nTimes #
>>> concatBy leftToMaybe Left [Left "h", Left "i", Right 1]
From -3.4.0.0/docs/src/Distribution.Utils.Generic.html#spanMaybe
>>> spanMaybe leftToMaybe [Left "h", Left "i", Right 1]
(["h","i"],[Right 1])
Modified from -lib-1.20.4/docs/src/Hledger.Utils.html#splitAtElement
>>> splitOn ' ' " switch the accumulator to the other mode "
["","switch","","","the","accumulator","to","the","other","mode","","",""]
| Fair n-way interleaving: given a finite number of (possibly infinite)
elements occur more frequently (on average) than another's.
# INLINE fromFoldable #
foldAlt :: (Foldable t, Alternative f) => t a -> f a
|
'insertAt' inserts an element at the given position:
@
(insertAt i x xs) !! i == x
@
If the index is negative or exceeds list length, the original list will be returned. (If the index is equal to the list length, the insertion can be carried out.)
| # LANGUAGE KindSignatures #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
module Prelude
( module Prelude
, module Relude
, module Control.Monad.Reader
, (><)
, toList
, dup
) where
import Control.Monad.Reader
( MonadReader(..), Reader, ReaderT(ReaderT), asks, mapReader, mapReaderT
, runReader, runReaderT, withReader, withReaderT )
import qualified Data.Foldable as Foldable
import Data.List ( groupBy )
import Data.Sequence ( (><) )
import GHC.Exts
import Relude
hiding ( Sum, abs, group, newEmptyMVar, newMVar, putMVar, readMVar, swapMVar
, takeMVar, toList, truncate, tryPutMVar, tryReadMVar, tryTakeMVar )
import Relude.Extra.Tuple
infixl 4 <<$>
(<<$>) :: (Functor f, Functor g) => a -> f (g b) -> f (g a)
(<<$>) a ffb = (a <$) <$> ffb
infixr 9 <.>
(<.>) :: Functor f => (a -> b) -> (c -> f a) -> c -> f b
f1 <.> f2 = fmap f1 . f2
lift2 :: forall (s :: (Type -> Type)
-> Type
-> Type) t m a.
(MonadTrans s, MonadTrans t, Monad (t m), Monad m)
=> m a
-> s (t m) a
lift2 = lift . lift
nTimes :: Int -> (a -> a) -> a -> a
nTimes 0 _ x = x
nTimes n f x = f (nTimes (n - 1) f x)
applyWhen :: Bool -> (a -> a) -> a -> a
applyWhen condition f = chain @Maybe (f <$ guard condition)
chain :: Foldable t => t (a -> a) -> a -> a
chain = foldr (.) id
[ Left " hi",Right 1 ]
concatBy :: Monoid b => (a -> Maybe b) -> (b -> a) -> [a] -> [a]
concatBy _ _ [] = []
concatBy toMonoid toElement xs = case spanMaybe toMonoid xs of
([], y : ys) -> y : concatBy' ys
(zs, ys) -> toElement (mconcat zs) : concatBy' ys
where
concatBy' = concatBy toMonoid toElement
spanMaybe :: (t -> Maybe a) -> [t] -> ([a], [t])
spanMaybe _ xs@[] = ([], xs)
spanMaybe p xs@(x : xs') = case p x of
Just y -> let (ys, zs) = spanMaybe p xs' in (y : ys, zs)
Nothing -> ([], xs)
spanEnd :: (a -> Bool) -> [a] -> ([a], [a])
spanEnd p = swap . bimap reverse reverse . span p . reverse
splitOn :: Eq a => a -> [a] -> [[a]]
splitOn x l = prefix : rest'
where
(prefix, rest) = break (x ==) l
rest' = case rest of
[] -> []
e : es | e == x -> splitOn x es
es -> splitOn x es
From :
lists , produce a single list such that whenever @v@ has finite index in one
of the input lists , @v@ also has finite index in the output list . No list 's
interleave :: [[a]] -> [a]
interleave = concat . transpose
| Convert from ' Data . Foldable . Foldable ' to an ' IsList ' type .
fromFoldable :: (Foldable f, IsList a) => f (Item a) -> a
fromFoldable = fromList . Foldable.toList
foldAlt = getAlt . ( Alt . pure )
Copied from -1.7.9/docs/src/Data.List.Extra.html#groupSort
groupSortOn :: Ord b => (a -> b) -> [a] -> [[a]]
groupSortOn f
= map (map snd)
. groupBy ((==) `on` fst)
. sortBy (compare `on` fst)
. map (f &&& id)
Copied from -0.4.0.1/docs/src/Data.List.Index.html#insertAt
insertAt :: Int -> a -> [a] -> [a]
insertAt i a ls | i < 0 = ls
| otherwise = go i ls
where
go 0 xs = a : xs
go n (x : xs) = x : go (n - 1) xs
go _ [] = []
|
5538066000df729dbd701171b6d13454c76b90ff61a7f3161ebcbfc8d19e6d87 | ShamoX/cash | durf.ml | #!/usr/local/adm/src/caml/bin/cash -r
-I /usr/local/adm/src/cash
!#
open Cash;
(* We see parent after children, so we'll backpatch the parent field. *)
type dir =
{ name : string; subtree_size : int; children : list dir; parent : mutable option dir }
;
value dname n =
let slash_i = Env_3_11.internal_rindex '/' n (String.length n) in
if slash_i < 1 then n else String.sub n 0 slash_i
;
value get_children name last =
loop [last] where rec loop children =
fun
[ [last :: roots] when name = dname last.name -> loop [last :: children] roots
| roots -> (roots, children) ]
;
value load =
let rex = Pcre.regexp "^\s*(\d+)\s+(\S.*)$"
and novalues = (-1, "") in
fun line roots ->
match
try
let substrs = Pcre.extract ~rex ~full_match:False line in
(int_of_string substrs.(0), substrs.(1))
with
[ Not_found ->
do { prerr_string "Can't understand line:\n"; prerr_endline line; novalues } ]
with
[ (-1, _) -> roots
| (size, name) ->
match roots with
[ [last :: roots] when name = dname last.name ->
let (newroots, children) = get_children name last roots in
let thisdir =
{name = name; subtree_size = size; children = children; parent = None}
in
do {
(* Backpatch children. *)
(let sdir = Some thisdir in
List.iter (fun child -> child.parent := sdir) children);
[thisdir :: newroots]
}
| _ ->
(* a new root or a last's brother. *)
[{name = name; subtree_size = size; children = []; parent = None} ::
roots] ] ]
;
value print_long total_size size name =
Printf.printf "\n%3d%% %6d %s\n" (100 * size / total_size) size name
;
value print_short total_size subtree_size percent_char size name =
let sub_percent = size * 100 / subtree_size
and percent = size * 100 / total_size in
Printf.printf " %3d%c %3d%c %6d %s\n" percent percent_char sub_percent
percent_char size name
;
value rec do_subtree apply_threshold total_size dir =
let subtree_size = dir.subtree_size in
do {
print_long total_size subtree_size dir.name;
let dot_size =
List.fold_left (fun sz child -> sz - child.subtree_size) subtree_size dir.children
in
let dot_name = dir.name ^ "/." in
let dot = {name = dot_name; subtree_size = dot_size; children = []; parent = None} in
let children =
List.sort (fun a b -> compare b.subtree_size a.subtree_size)
(List.filter apply_threshold [dot :: dir.children])
in
(* XXX. *)
let num_components = List.length (split_file_name dir.name) in
ignore
(let print_short = print_short total_size subtree_size in
List.fold_left
(fun percent_char child ->
let name = List.nth (split_file_name child.name) num_components in
do { print_short percent_char child.subtree_size name; ' ' })
'%' children);
List.iter (do_subtree apply_threshold total_size) (List.filter (\<> dot) children)
}
;
value disk_usage_report_formatter threshold threshold_is_percent du_chan =
(* # Load input, while establishing list of roots. *)
let root_list = fold_in_channel du_chan read_line load [] in
(* # Calculate total size. *)
let total_size = List.fold_left (fun tot root -> tot + root.subtree_size) 0 root_list in
do {
(* print headers. *)
print_string "Tot% Blocks Full-pathname\n";
print_string " Tot% Sub% Blocks Child\n";
let threshold =
if threshold_is_percent then threshold * total_size / 100 else threshold
in
let apply_threshold child = child.subtree_size >= threshold in
(* Output formatted tree for each root. *)
List.iter (do_subtree apply_threshold total_size) root_list
}
;
(* # Prepare file handle. *)
value mkdu use_stdin du_args =
if use_stdin then do {
set_chan_buffering_in stdin Block; (* probably a file, anyway. *)
stdin
}
else run_with_in_channel (fun () -> exec_path "du" du_args)
;
value disk_usage_report_formatter_from_sh () =
let threshold = ref 1
and threshold_is_percent = ref True
and use_stdin = ref False
and du_args = ref [] in
let spec =
[("-t",
Arg.String
(fun s ->
let lci = pred (String.length s) in
do {
threshold_is_percent.val := s.[lci] = '%';
threshold.val :=
int_of_string (if threshold_is_percent.val then String.sub s 0 lci else s)
}),
"threshold[%]\n\t Only show directories at or above threshold blocks.\n\t \
With \"%\", only show directories at or above threshold percent\n\t \
of the total. Default is \"1%\"");
("-", Arg.Set use_stdin, "\t Read standard input for 'du' listing.")]
and usage =
"Usage: durf [-t #[%]] [{du-args|-}]\nLike 'du', but formatted differently."
in
do {
Arg.parse spec (fun arg -> du_args.val := [arg :: du_args.val]) usage;
disk_usage_report_formatter threshold.val threshold_is_percent.val
(mkdu use_stdin.val du_args.val)
}
;
if Sys.interactive.val then() else disk_usage_report_formatter_from_sh ();
| null | https://raw.githubusercontent.com/ShamoX/cash/aa97231154c3f64c9d0a62823e1ed71e32ab8718/examples/durf.ml | ocaml | We see parent after children, so we'll backpatch the parent field.
Backpatch children.
a new root or a last's brother.
XXX.
# Load input, while establishing list of roots.
# Calculate total size.
print headers.
Output formatted tree for each root.
# Prepare file handle.
probably a file, anyway. | #!/usr/local/adm/src/caml/bin/cash -r
-I /usr/local/adm/src/cash
!#
open Cash;
type dir =
{ name : string; subtree_size : int; children : list dir; parent : mutable option dir }
;
value dname n =
let slash_i = Env_3_11.internal_rindex '/' n (String.length n) in
if slash_i < 1 then n else String.sub n 0 slash_i
;
value get_children name last =
loop [last] where rec loop children =
fun
[ [last :: roots] when name = dname last.name -> loop [last :: children] roots
| roots -> (roots, children) ]
;
value load =
let rex = Pcre.regexp "^\s*(\d+)\s+(\S.*)$"
and novalues = (-1, "") in
fun line roots ->
match
try
let substrs = Pcre.extract ~rex ~full_match:False line in
(int_of_string substrs.(0), substrs.(1))
with
[ Not_found ->
do { prerr_string "Can't understand line:\n"; prerr_endline line; novalues } ]
with
[ (-1, _) -> roots
| (size, name) ->
match roots with
[ [last :: roots] when name = dname last.name ->
let (newroots, children) = get_children name last roots in
let thisdir =
{name = name; subtree_size = size; children = children; parent = None}
in
do {
(let sdir = Some thisdir in
List.iter (fun child -> child.parent := sdir) children);
[thisdir :: newroots]
}
| _ ->
[{name = name; subtree_size = size; children = []; parent = None} ::
roots] ] ]
;
value print_long total_size size name =
Printf.printf "\n%3d%% %6d %s\n" (100 * size / total_size) size name
;
value print_short total_size subtree_size percent_char size name =
let sub_percent = size * 100 / subtree_size
and percent = size * 100 / total_size in
Printf.printf " %3d%c %3d%c %6d %s\n" percent percent_char sub_percent
percent_char size name
;
value rec do_subtree apply_threshold total_size dir =
let subtree_size = dir.subtree_size in
do {
print_long total_size subtree_size dir.name;
let dot_size =
List.fold_left (fun sz child -> sz - child.subtree_size) subtree_size dir.children
in
let dot_name = dir.name ^ "/." in
let dot = {name = dot_name; subtree_size = dot_size; children = []; parent = None} in
let children =
List.sort (fun a b -> compare b.subtree_size a.subtree_size)
(List.filter apply_threshold [dot :: dir.children])
in
let num_components = List.length (split_file_name dir.name) in
ignore
(let print_short = print_short total_size subtree_size in
List.fold_left
(fun percent_char child ->
let name = List.nth (split_file_name child.name) num_components in
do { print_short percent_char child.subtree_size name; ' ' })
'%' children);
List.iter (do_subtree apply_threshold total_size) (List.filter (\<> dot) children)
}
;
value disk_usage_report_formatter threshold threshold_is_percent du_chan =
let root_list = fold_in_channel du_chan read_line load [] in
let total_size = List.fold_left (fun tot root -> tot + root.subtree_size) 0 root_list in
do {
print_string "Tot% Blocks Full-pathname\n";
print_string " Tot% Sub% Blocks Child\n";
let threshold =
if threshold_is_percent then threshold * total_size / 100 else threshold
in
let apply_threshold child = child.subtree_size >= threshold in
List.iter (do_subtree apply_threshold total_size) root_list
}
;
value mkdu use_stdin du_args =
if use_stdin then do {
stdin
}
else run_with_in_channel (fun () -> exec_path "du" du_args)
;
value disk_usage_report_formatter_from_sh () =
let threshold = ref 1
and threshold_is_percent = ref True
and use_stdin = ref False
and du_args = ref [] in
let spec =
[("-t",
Arg.String
(fun s ->
let lci = pred (String.length s) in
do {
threshold_is_percent.val := s.[lci] = '%';
threshold.val :=
int_of_string (if threshold_is_percent.val then String.sub s 0 lci else s)
}),
"threshold[%]\n\t Only show directories at or above threshold blocks.\n\t \
With \"%\", only show directories at or above threshold percent\n\t \
of the total. Default is \"1%\"");
("-", Arg.Set use_stdin, "\t Read standard input for 'du' listing.")]
and usage =
"Usage: durf [-t #[%]] [{du-args|-}]\nLike 'du', but formatted differently."
in
do {
Arg.parse spec (fun arg -> du_args.val := [arg :: du_args.val]) usage;
disk_usage_report_formatter threshold.val threshold_is_percent.val
(mkdu use_stdin.val du_args.val)
}
;
if Sys.interactive.val then() else disk_usage_report_formatter_from_sh ();
|
b59574b2f6f787ddbb1f5754c126ac154da989972fd686dc1d6c96b1d8d69362 | tvraman/aster-math | tts.lisp | ;;; -*- Syntax: Common-Lisp; Mode: LISP -*- ;;;
tts.lisp -- Common Lisp interface to Emacspeak speech server
;;; $Author: tv.raman.tv $
;;; Description: Interface Common Lisp to Emacspeak TTS servers
Keywords : AsTeR , Emacspeak , Audio Desktop
;;{{{ Copyright:
Copyright ( C ) 2011 -- 2016 , >
All Rights Reserved .
;;;
This file is not part of GNU Emacs , but the same permissions apply .
;;;
GNU Emacs is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 , or ( at your option )
;;; any later version.
;;;
GNU Emacs 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 Emacs ; see the file COPYING . If not , write to
the Free Software Foundation , 675 Mass Ave , Cambridge , , USA .
;;}}}
;;{{{ Introduction:
;;; Commentary:
;;; Interface Common Lisp to Emacspeak TTS servers
;;}}}
;;{{{ Setup:
(in-package :afl)
(export
'(tts-init tts-stop tts-speak tts-force tts-queue
tts-silence tts-beep with-surrounding-pause
high-intonation low-intonation high-low-intonation subclause-boundary
comma-intonation period-intonation set-period-pause set-comma-pause
interrogative exclamation primary-stress secondary-stress
exclamatory-stress))
A TTS structure holds :
;; the engine name, process handle, and input/output streams.
(defstruct tts engine process input output )
(defvar *tts-log* nil
"Flag to toggle TTS logging.")
(defun tts-location (engine)
"Return location of specified engine."
(declare (special *tts-log*))
(concatenate
'string
(uiop:getenv "EMACSPEAK_DIR")
"servers/"
(if *tts-log* "log-" "")
engine))
(defvar *tts* nil
"Handle to tts server connection.")
(defun tts-init (&key (engine "dtk-soft"))
"Initialize TTS system if needed."
(declare (special *tts*))
(when
(or
(null *tts*)
(null (tts-process *tts*))
(not (eq :running (process-status (tts-process *tts*)))))
(setq *tts*
(make-tts :engine (tts-location engine)))
(tts-open)))
(defun tts ()
"Return handle to TTS server."
(declare (special *tts*))
*tts*)
;;}}}
;;{{{macros:
(defun tts-silence (ms)
"Send silence"
(when (> ms 0)
(let ((i (tts-input (tts))))
(format i "sh {~a}~%" ms)
(finish-output i))))
(defmacro with-surrounding-pause (pause-amount &body body)
"Execute body with surrounding pause specified by pause-amount"
`(progn
(tts-silence ,pause-amount)
,@body
(tts-silence ,pause-amount)))
;;}}}
;;{{{Internal Functions
(defun tts-open ()
"Open a TTS session."
(let ((handle (tts)))
(setf (tts-process handle)
(run-program
(tts-engine handle) nil :wait nil :input :stream))
(setf (tts-input handle) (process-input (tts-process handle)))
(write-line (format nil "tts_set_punctuations some") (tts-input handle))
(force-output (tts-input handle))))
(defun icon-file (icon)
"Convert auditory icon name to a sound-file name."
(declare (special *emacspeak*))
(format nil "~a/sounds/pan-chimes/~a.wav" *emacspeak* icon))
;;}}}
;;{{{Exported Functions
(defun tts-shutdown ()
"Shutdown a TTS session."
(let ((handle (tts)))
(when (tts-input handle)
(close (tts-input handle)))
(setf (tts-input handle) nil)))
(defun tts-code (cmd)
"Queue TTS code."
(let ((i (tts-input (tts))))
(unless i (setq i (tts-open)))
(format i "c {~a}~%" cmd)
(finish-output i)))
(defun tts-icon (icon)
"play icon"
(let ((i (tts-input (tts))))
(unless i (setq i (tts-open)))
(format i "a {~a}~%" (icon-file icon))
(finish-output i)))
(defun tts-queue (text)
"Queue text to speak."
(let ((i (tts-input (tts))))
(unless i (setq i (tts-open)))
(unless (stringp text)
(setq text (string-downcase (format nil " ~a " text))))
(format i "q {~a}~%" text)
(finish-output i)))
(defun tts-beep (freq duration)
"Produce a beep using the Dectalk."
(tts-code (format nil "[:tone ~a ~a]~%" freq duration))
(tts-force))
(defun tts-force ()
"Speak all queued text."
(let ((i (tts-input (tts))))
(format i "d~%" )
(finish-output i)))
(defun tts-stop ()
"Stop speech."
(let ((i (tts-input (tts))))
(format i "s~%")
(finish-output i)))
(defun tts-speak (text)
"Speak text."
(unless (tts-input (tts)) (tts-open))
(let ((i (tts-input (tts))))
(format i "q {~a}~%" text)
(format i "d~%")
(finish-output i)))
(defun tts-say (text)
"Say text."
(unless (tts-input (tts)) (tts-open))
(let ((i (tts-input (tts))))
(format i "tts_say {~a}~%" text)
(format i "d~%")
(finish-output i)))
(defun tts-speak-list (lines)
"Speak an arbitrary number of lines."
(mapc 'tts-queue lines)
(tts-force))
;;}}}
;;{{{Various: Intonation Functions:
(defun high-intonation ()
"Generate H*"
(tts-queue "[/]" ))
(defun low-intonation ()
"Generate L*"
(tts-queue "[\]" ))
(defun high-low-intonation ()
"Generate Hl*"
(tts-queue "[/\]"))
(defun comma-intonation ()
"Generate a comma intonation"
(tts-queue "[_,] "))
(defun period-intonation ()
"Generate a period intonation"
(tts-queue " "))
(defun interrogative ()
"Send an interrogative. "
(tts-queue " "))
(defun primary-stress ()
"Send a primary-stress. "
(tts-queue " "))
(defun secondary-stress ()
"Send a secondary-stress. "
(tts-queue " "))
(defun set-period-pause (ms)
"Set Period Pause."
(tts-code (format nil "[:pp ~a]" ms)))
(defun set-comma-pause (ms)
"Set comma Pause."
(tts-code (format nil "[:cp ~a]" ms)))
(defun subclause-boundary ()
"Send subclause boundary."
(tts-queue "[)]")
)
;;}}}
(provide 'tts)
;;{{{ end of file
;;; local variables:
;;; folded-file: t
;;; end:
;;}}}
| null | https://raw.githubusercontent.com/tvraman/aster-math/6fc3203bc66f63ad3142fc1a71b95f67d81816e1/lisp/afl/tts.lisp | lisp | -*- Syntax: Common-Lisp; Mode: LISP -*- ;;;
$Author: tv.raman.tv $
Description: Interface Common Lisp to Emacspeak TTS servers
{{{ Copyright:
you can redistribute it and/or modify
either version 2 , or ( at your option )
any later version.
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.
see the file COPYING . If not , write to
}}}
{{{ Introduction:
Commentary:
Interface Common Lisp to Emacspeak TTS servers
}}}
{{{ Setup:
the engine name, process handle, and input/output streams.
}}}
{{{macros:
}}}
{{{Internal Functions
}}}
{{{Exported Functions
}}}
{{{Various: Intonation Functions:
}}}
{{{ end of file
local variables:
folded-file: t
end:
}}} | tts.lisp -- Common Lisp interface to Emacspeak speech server
Keywords : AsTeR , Emacspeak , Audio Desktop
Copyright ( C ) 2011 -- 2016 , >
All Rights Reserved .
This file is not part of GNU Emacs , but the same permissions apply .
it under the terms of the GNU General Public License as published by
GNU Emacs is distributed in the hope that it will be useful ,
You should have received a copy of the GNU General Public License
the Free Software Foundation , 675 Mass Ave , Cambridge , , USA .
(in-package :afl)
(export
'(tts-init tts-stop tts-speak tts-force tts-queue
tts-silence tts-beep with-surrounding-pause
high-intonation low-intonation high-low-intonation subclause-boundary
comma-intonation period-intonation set-period-pause set-comma-pause
interrogative exclamation primary-stress secondary-stress
exclamatory-stress))
A TTS structure holds :
(defstruct tts engine process input output )
(defvar *tts-log* nil
"Flag to toggle TTS logging.")
(defun tts-location (engine)
"Return location of specified engine."
(declare (special *tts-log*))
(concatenate
'string
(uiop:getenv "EMACSPEAK_DIR")
"servers/"
(if *tts-log* "log-" "")
engine))
(defvar *tts* nil
"Handle to tts server connection.")
(defun tts-init (&key (engine "dtk-soft"))
"Initialize TTS system if needed."
(declare (special *tts*))
(when
(or
(null *tts*)
(null (tts-process *tts*))
(not (eq :running (process-status (tts-process *tts*)))))
(setq *tts*
(make-tts :engine (tts-location engine)))
(tts-open)))
(defun tts ()
"Return handle to TTS server."
(declare (special *tts*))
*tts*)
(defun tts-silence (ms)
"Send silence"
(when (> ms 0)
(let ((i (tts-input (tts))))
(format i "sh {~a}~%" ms)
(finish-output i))))
(defmacro with-surrounding-pause (pause-amount &body body)
"Execute body with surrounding pause specified by pause-amount"
`(progn
(tts-silence ,pause-amount)
,@body
(tts-silence ,pause-amount)))
(defun tts-open ()
"Open a TTS session."
(let ((handle (tts)))
(setf (tts-process handle)
(run-program
(tts-engine handle) nil :wait nil :input :stream))
(setf (tts-input handle) (process-input (tts-process handle)))
(write-line (format nil "tts_set_punctuations some") (tts-input handle))
(force-output (tts-input handle))))
(defun icon-file (icon)
"Convert auditory icon name to a sound-file name."
(declare (special *emacspeak*))
(format nil "~a/sounds/pan-chimes/~a.wav" *emacspeak* icon))
(defun tts-shutdown ()
"Shutdown a TTS session."
(let ((handle (tts)))
(when (tts-input handle)
(close (tts-input handle)))
(setf (tts-input handle) nil)))
(defun tts-code (cmd)
"Queue TTS code."
(let ((i (tts-input (tts))))
(unless i (setq i (tts-open)))
(format i "c {~a}~%" cmd)
(finish-output i)))
(defun tts-icon (icon)
"play icon"
(let ((i (tts-input (tts))))
(unless i (setq i (tts-open)))
(format i "a {~a}~%" (icon-file icon))
(finish-output i)))
(defun tts-queue (text)
"Queue text to speak."
(let ((i (tts-input (tts))))
(unless i (setq i (tts-open)))
(unless (stringp text)
(setq text (string-downcase (format nil " ~a " text))))
(format i "q {~a}~%" text)
(finish-output i)))
(defun tts-beep (freq duration)
"Produce a beep using the Dectalk."
(tts-code (format nil "[:tone ~a ~a]~%" freq duration))
(tts-force))
(defun tts-force ()
"Speak all queued text."
(let ((i (tts-input (tts))))
(format i "d~%" )
(finish-output i)))
(defun tts-stop ()
"Stop speech."
(let ((i (tts-input (tts))))
(format i "s~%")
(finish-output i)))
(defun tts-speak (text)
"Speak text."
(unless (tts-input (tts)) (tts-open))
(let ((i (tts-input (tts))))
(format i "q {~a}~%" text)
(format i "d~%")
(finish-output i)))
(defun tts-say (text)
"Say text."
(unless (tts-input (tts)) (tts-open))
(let ((i (tts-input (tts))))
(format i "tts_say {~a}~%" text)
(format i "d~%")
(finish-output i)))
(defun tts-speak-list (lines)
"Speak an arbitrary number of lines."
(mapc 'tts-queue lines)
(tts-force))
(defun high-intonation ()
"Generate H*"
(tts-queue "[/]" ))
(defun low-intonation ()
"Generate L*"
(tts-queue "[\]" ))
(defun high-low-intonation ()
"Generate Hl*"
(tts-queue "[/\]"))
(defun comma-intonation ()
"Generate a comma intonation"
(tts-queue "[_,] "))
(defun period-intonation ()
"Generate a period intonation"
(tts-queue " "))
(defun interrogative ()
"Send an interrogative. "
(tts-queue " "))
(defun primary-stress ()
"Send a primary-stress. "
(tts-queue " "))
(defun secondary-stress ()
"Send a secondary-stress. "
(tts-queue " "))
(defun set-period-pause (ms)
"Set Period Pause."
(tts-code (format nil "[:pp ~a]" ms)))
(defun set-comma-pause (ms)
"Set comma Pause."
(tts-code (format nil "[:cp ~a]" ms)))
(defun subclause-boundary ()
"Send subclause boundary."
(tts-queue "[)]")
)
(provide 'tts)
|
0a0b67b1e000113af31d58fb678df0108defe8ecfdd60f4af909d1737f67632b | NorfairKing/easyspec | ChunksSimilarityType.hs | module EasySpec.Discover.SignatureInference.ChunksSimilarityType where
import Import
import EasySpec.Discover.SignatureInference.ChunksUtils
import EasySpec.Discover.SignatureInference.SimilarityUtils
import EasySpec.Discover.SignatureInference.SyntacticSimilarityType
import EasySpec.Discover.Types
inferChunksSimilarityType :: Int -> SignatureInferenceStrategy
inferChunksSimilarityType i =
SignatureInferenceStrategy
{ sigInfStratName = "chunks-similarity-type-" ++ show i
, inferSignature = inferChunksFrom $ diffChoice i simDiffType
}
| null | https://raw.githubusercontent.com/NorfairKing/easyspec/b038b45a375cc0bed2b00c255b508bc06419c986/easyspec/src/EasySpec/Discover/SignatureInference/ChunksSimilarityType.hs | haskell | module EasySpec.Discover.SignatureInference.ChunksSimilarityType where
import Import
import EasySpec.Discover.SignatureInference.ChunksUtils
import EasySpec.Discover.SignatureInference.SimilarityUtils
import EasySpec.Discover.SignatureInference.SyntacticSimilarityType
import EasySpec.Discover.Types
inferChunksSimilarityType :: Int -> SignatureInferenceStrategy
inferChunksSimilarityType i =
SignatureInferenceStrategy
{ sigInfStratName = "chunks-similarity-type-" ++ show i
, inferSignature = inferChunksFrom $ diffChoice i simDiffType
}
| |
02fd471afcf139e597d65fa1ca1ada02deb6070958db2ce88f4aa92aa6c86c91 | tweag/linear-base | Instances.hs | {-# OPTIONS -Wno-orphans #-}
# LANGUAGE DerivingVia #
{-# LANGUAGE LinearTypes #-}
# LANGUAGE QuantifiedConstraints #
# LANGUAGE RebindableSyntax #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TupleSections #
# LANGUAGE NoImplicitPrelude #
{-# OPTIONS_HADDOCK hide #-}
module Control.Functor.Linear.Internal.Instances
( Data (..),
)
where
import Control.Functor.Linear.Internal.Class
import qualified Data.Functor.Linear.Internal.Applicative as Data
import qualified Data.Functor.Linear.Internal.Functor as Data
-- # Deriving Data.XXX in terms of Control.XXX
-------------------------------------------------------------------------------
-- | This is a newtype for deriving Data.XXX classes from
-- Control.XXX classes.
newtype Data f a = Data (f a)
-- # Basic instances
-------------------------------------------------------------------------------
instance Functor f => Data.Functor (Data f) where
fmap f (Data x) = Data (fmap f x)
instance Applicative f => Data.Applicative (Data f) where
pure x = Data (pure x)
Data f <*> Data x = Data (f <*> x)
| null | https://raw.githubusercontent.com/tweag/linear-base/9d82f67f1415dda385a6349954bf55f9bfa4e62e/src/Control/Functor/Linear/Internal/Instances.hs | haskell | # OPTIONS -Wno-orphans #
# LANGUAGE LinearTypes #
# OPTIONS_HADDOCK hide #
# Deriving Data.XXX in terms of Control.XXX
-----------------------------------------------------------------------------
| This is a newtype for deriving Data.XXX classes from
Control.XXX classes.
# Basic instances
----------------------------------------------------------------------------- | # LANGUAGE DerivingVia #
# LANGUAGE QuantifiedConstraints #
# LANGUAGE RebindableSyntax #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TupleSections #
# LANGUAGE NoImplicitPrelude #
module Control.Functor.Linear.Internal.Instances
( Data (..),
)
where
import Control.Functor.Linear.Internal.Class
import qualified Data.Functor.Linear.Internal.Applicative as Data
import qualified Data.Functor.Linear.Internal.Functor as Data
newtype Data f a = Data (f a)
instance Functor f => Data.Functor (Data f) where
fmap f (Data x) = Data (fmap f x)
instance Applicative f => Data.Applicative (Data f) where
pure x = Data (pure x)
Data f <*> Data x = Data (f <*> x)
|
317adffa1e98523f10971ea1e08c217a06edab36744969fe342850944ddf9f69 | camllight/camllight | builtin_text.ml | (* Not a string as such, more like a symbol *)
(* type *)
type textMark == string
;;
/type
let cCAMLtoTKtextMark x = TkToken x
;;
let cTKtoCAMLtextMark x = x
;;
(* type *)
type textTag == string
;;
/type
let cCAMLtoTKtextTag x = TkToken x
;;
let cTKtoCAMLtextTag x = x
;;
(* type *)
type textModifier =
tk keyword : + /-
| LineOffset of int (* tk keyword: +/- Xlines *)
| LineStart (* tk keyword: linestart *)
| LineEnd (* tk keyword: lineend *)
tk keyword : wordstart
| WordEnd (* tk keyword: wordend *)
;;
/type
TextModifiers are never returned by Tk
let ppTextModifier = function
CharOffset n ->
if n > 0 then "+" ^ (string_of_int n) ^ "chars"
else if n = 0 then ""
else (string_of_int n) ^ "chars"
| LineOffset n ->
if n > 0 then "+" ^ (string_of_int n) ^ "lines"
else if n = 0 then ""
else (string_of_int n) ^ "lines"
| LineStart -> " linestart"
| LineEnd -> " lineend"
| WordStart -> " wordstart"
| WordEnd -> " wordend"
;;
(* type *)
type textIndex =
TextIndex of index * textModifier list
| TextIndexNone
;;
/type
let ppTextIndex = function
TextIndexNone -> ""
| TextIndex (base, ml) ->
match cCAMLtoTKindex index_text_table base with
| TkToken ppbase -> it_list (prefix ^) ppbase (map ppTextModifier ml)
| _ -> raise (TkError "ppTextIndex")
;;
let cCAMLtoTKtextIndex i =
TkToken (ppTextIndex i)
;;
| null | https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/sources/contrib/camltk4/libsupport/builtin_text.ml | ocaml | Not a string as such, more like a symbol
type
type
type
tk keyword: +/- Xlines
tk keyword: linestart
tk keyword: lineend
tk keyword: wordend
type |
type textMark == string
;;
/type
let cCAMLtoTKtextMark x = TkToken x
;;
let cTKtoCAMLtextMark x = x
;;
type textTag == string
;;
/type
let cCAMLtoTKtextTag x = TkToken x
;;
let cTKtoCAMLtextTag x = x
;;
type textModifier =
tk keyword : + /-
tk keyword : wordstart
;;
/type
TextModifiers are never returned by Tk
let ppTextModifier = function
CharOffset n ->
if n > 0 then "+" ^ (string_of_int n) ^ "chars"
else if n = 0 then ""
else (string_of_int n) ^ "chars"
| LineOffset n ->
if n > 0 then "+" ^ (string_of_int n) ^ "lines"
else if n = 0 then ""
else (string_of_int n) ^ "lines"
| LineStart -> " linestart"
| LineEnd -> " lineend"
| WordStart -> " wordstart"
| WordEnd -> " wordend"
;;
type textIndex =
TextIndex of index * textModifier list
| TextIndexNone
;;
/type
let ppTextIndex = function
TextIndexNone -> ""
| TextIndex (base, ml) ->
match cCAMLtoTKindex index_text_table base with
| TkToken ppbase -> it_list (prefix ^) ppbase (map ppTextModifier ml)
| _ -> raise (TkError "ppTextIndex")
;;
let cCAMLtoTKtextIndex i =
TkToken (ppTextIndex i)
;;
|
d1c2eb6997d9a3f041e2939dbe55044e7cc1e329063dcece93c33120b0c9aa3b | purenix-org/purenix | Main.hs | # LANGUAGE NoImplicitPrelude #
module PureNix.Main where
import qualified Data.Aeson as Aeson
import Data.Aeson.Types (parseEither)
import Data.Foldable (toList)
import Data.List (intercalate)
import qualified Data.Text.Lazy.IO as TL
import qualified Language.PureScript.CoreFn as P
import Language.PureScript.CoreFn.FromJSON (moduleFromJSON)
import PureNix.Convert (ModuleInfo (ModuleInfo), convert)
import PureNix.Prelude
import PureNix.Print (renderExpr)
import qualified System.Directory as Dir
import qualified System.Exit as Sys
import System.FilePath ((</>))
import qualified System.FilePath as FP
import System.IO
defaultMain :: IO ()
defaultMain = do
let workdir = "."
let moduleRoot = workdir </> "output"
moduleDirs <- filter (not . FP.isExtensionOf "json") <$> Dir.listDirectory moduleRoot
forM_ moduleDirs $ \rel -> do
let dir = moduleRoot </> rel
let file = dir </> "corefn.json"
value <- Aeson.eitherDecodeFileStrict file >>= either Sys.die pure
(_version, module') <- either Sys.die pure $ parseEither moduleFromJSON value
let (nix, ModuleInfo usesFFI interpolations) = convert module'
TL.writeFile (dir </> "default.nix") (renderExpr nix)
let modulePath = P.modulePath module'
foreignSrc = workdir </> FP.replaceExtension modulePath "nix"
foreignTrg = dir </> "foreign.nix"
hasForeign <- Dir.doesFileExist foreignSrc
case (hasForeign, usesFFI) of
(True, True) -> Dir.copyFile foreignSrc foreignTrg
(True, False) -> hPutStrLn stderr $ "Warning: " <> modulePath <> " has an FFI file, but does not use FFI!"
(False, True) -> hPutStrLn stderr $ "Warning: " <> modulePath <> " calls foreign functions, but has no associated FFI file!"
(False, False) -> pure ()
unless (null interpolations) $ do
hPutStrLn stderr $
unlines
[ "Warning: " <> modulePath <> " appears to perform Nix string interpolation in the following locations:",
" " <> intercalate ", " (show <$> toList interpolations),
"Nix string interpolations are currently not officially supported and may cause unexpected behavior."
]
| null | https://raw.githubusercontent.com/purenix-org/purenix/5587e599a39811d6d1645e7d2cfed559506e3637/src/PureNix/Main.hs | haskell | # LANGUAGE NoImplicitPrelude #
module PureNix.Main where
import qualified Data.Aeson as Aeson
import Data.Aeson.Types (parseEither)
import Data.Foldable (toList)
import Data.List (intercalate)
import qualified Data.Text.Lazy.IO as TL
import qualified Language.PureScript.CoreFn as P
import Language.PureScript.CoreFn.FromJSON (moduleFromJSON)
import PureNix.Convert (ModuleInfo (ModuleInfo), convert)
import PureNix.Prelude
import PureNix.Print (renderExpr)
import qualified System.Directory as Dir
import qualified System.Exit as Sys
import System.FilePath ((</>))
import qualified System.FilePath as FP
import System.IO
defaultMain :: IO ()
defaultMain = do
let workdir = "."
let moduleRoot = workdir </> "output"
moduleDirs <- filter (not . FP.isExtensionOf "json") <$> Dir.listDirectory moduleRoot
forM_ moduleDirs $ \rel -> do
let dir = moduleRoot </> rel
let file = dir </> "corefn.json"
value <- Aeson.eitherDecodeFileStrict file >>= either Sys.die pure
(_version, module') <- either Sys.die pure $ parseEither moduleFromJSON value
let (nix, ModuleInfo usesFFI interpolations) = convert module'
TL.writeFile (dir </> "default.nix") (renderExpr nix)
let modulePath = P.modulePath module'
foreignSrc = workdir </> FP.replaceExtension modulePath "nix"
foreignTrg = dir </> "foreign.nix"
hasForeign <- Dir.doesFileExist foreignSrc
case (hasForeign, usesFFI) of
(True, True) -> Dir.copyFile foreignSrc foreignTrg
(True, False) -> hPutStrLn stderr $ "Warning: " <> modulePath <> " has an FFI file, but does not use FFI!"
(False, True) -> hPutStrLn stderr $ "Warning: " <> modulePath <> " calls foreign functions, but has no associated FFI file!"
(False, False) -> pure ()
unless (null interpolations) $ do
hPutStrLn stderr $
unlines
[ "Warning: " <> modulePath <> " appears to perform Nix string interpolation in the following locations:",
" " <> intercalate ", " (show <$> toList interpolations),
"Nix string interpolations are currently not officially supported and may cause unexpected behavior."
]
| |
ec26e759d8f39b125eaa1b356c16f4341edb98d82b1efe8b72dcb06f157f9089 | earl-ducaine/cl-garnet | menuinter.lisp | -*- Mode : LISP ; Syntax : Common - Lisp ; Package : INTERACTORS ; Base : 10 -*-
;;;
The Garnet User Interface Development Environment .
;;;
This code was written as part of the Garnet project at Carnegie
Mellon University , and has been placed in the public domain . If
you are using this code or any part of Garnet , please contact
;;; to be put on the mailing list.
;;; This file contains the mouse interactors to handle menus. It
should be loaded after Interactor and after MoveGrowInter
;;;
Designed and implemented by
(in-package "INTERACTORS")
;;; Utility procedures
;;; parts of :slots-to-set list
(defun check-slots-to-set (inter)
(let ((slots (g-value inter :slots-to-set)))
(unless (and (listp slots)
(= 3 (length slots))
(or (null (first slots)) (keywordp (first slots)))
(or (null (second slots)) (keywordp (second slots)))
(or (null (third slots)) (keywordp (third slots))))
(error "the :slots-to-set of ~s must be a list of three nils or keywords"
inter))))
(defun interim-sel-slot (inter)
(first (g-value inter :slots-to-set)))
(defun obj-sel-slot (inter)
(second (g-value inter :slots-to-set)))
;; there always must be an aggregate selected slot because used for
;; final-feedback
(defun agg-sel-slot (inter)
(or (third (g-value inter :slots-to-set))
:*inter-agg-selected*))
;;; final feedback objects
(defun clear-finals (an-interactor feedback-objs-in-use)
(dolist (f feedback-objs-in-use)
(dbprint-feed :obj-over f nil an-interactor)
(s-value f :obj-over nil)))
;; this clears the final feedback objects and resets the list in the
;; interactor.
(defun clear-finals-and-set (an-interactor feedback-objs-in-use)
(clear-finals an-interactor feedback-objs-in-use)
(if-debug an-interactor (format t "clearing interactor final feedback slots~%"))
(s-value an-interactor :final-feed-avail
(append (g-value an-interactor :final-feed-avail)
feedback-objs-in-use))
(s-value an-interactor :final-feed-inuse nil))
;;; destroys any objects created to be extra final feedback objects. this
;;; is called when the interactor is destroyed.
(defun destroy-extra-final-feedback-objs (an-interactor erase)
(if-debug an-interactor
(format t "destroying extra final feedback objects~%"))
(let ((final-feedback-protos
(get-local-value an-interactor :final-feedback-protos)))
(when final-feedback-protos
(dolist (obj (get-local-value an-interactor :final-feed-avail))
(when (schema-p obj)
(unless (member obj final-feedback-protos)
(with-constants-disabled
(opal:destroy obj erase)))))
(s-value an-interactor :final-feed-avail nil)
(dolist (obj (get-local-value an-interactor :final-feed-inuse))
(when (schema-p obj)
(unless (member obj final-feedback-protos)
(with-constants-disabled
(opal:destroy obj erase)))))
(s-value an-interactor :final-feed-inuse nil))))
;;; Sets the final feedback object to be only new-sel-obj, or if
;;; new-sel-obj is nil, then sets there to be no final-feedback-objs.
There always must be at least one final - feedback - obj ( the
;;; prototype itself), so this procedure does not need to worry about
;;; allocating any.
(defun one-final-feedback-obj (an-interactor new-sel-obj)
(let ((final-feedback-proto (g-value an-interactor :final-feedback-obj)))
(when final-feedback-proto ; otherwise, just exit
(let ((feedback-objs-in-use
(get-local-value an-interactor :final-feed-inuse)))
(clear-finals-and-set an-interactor feedback-objs-in-use)
(when new-sel-obj
;; set feedback obj to it
(let* ((final-feedback (find-final-feedback-obj an-interactor
final-feedback-proto)))
(dbprint-feed :obj-over final-feedback new-sel-obj an-interactor)
(s-value final-feedback :obj-over new-sel-obj)))))))
;;; Adds (if add-p is t) or removes (if add-p is nil) any final-feedback
;;; objs refering to newval, but leaves rest of the final feedback
;;; objects alone
(defun list-final-feedback-obj (an-interactor newval add-p)
(let ((final-feedback-proto (g-value an-interactor :final-feedback-obj)))
(when final-feedback-proto ; otherwise, just exit
(let ((feedback-objs-avail
(get-local-value an-interactor :final-feed-avail))
(feedback-objs-in-use
(get-local-value an-interactor :final-feed-inuse))
feed-for-newval)
(dolist (f feedback-objs-in-use)
(when (eq newval (g-value f :obj-over))
(setq feed-for-newval f)
(return)))
(if add-p
; add new feedback obj unless one is there
(unless feed-for-newval
; get a feedback obj to use
(setq feed-for-newval
(find-final-feedback-obj an-interactor
final-feedback-proto))
(dbprint-feed :obj-over feed-for-newval newval an-interactor)
(s-value feed-for-newval :obj-over newval))
; else remove the feedback obj
(when feed-for-newval
(dbprint-feed :obj-over feed-for-newval nil an-interactor)
(s-value feed-for-newval :obj-over nil)
(s-value an-interactor :final-feed-avail
(cons feed-for-newval feedback-objs-avail))
(s-value an-interactor :final-feed-inuse
(delete feed-for-newval feedback-objs-in-use))))))))
;;; Create an instance of final-feedback-proto unless it is a constant
(defun get-new-feedback-obj (final-feedback-proto)
(let ((new-obj (create-instance nil final-feedback-proto)))
(with-constants-disabled
(opal:add-component (g-value final-feedback-proto :parent)
new-obj))
new-obj))
;;; Find an instance of final-feedback-proto in the available list of
;;; final feedback objects. This allows the prototype to change,
;;; e.g. because there is a formula in the :final-feedback-obj slots
;;; which might depend on the object that the mouse is over. This
;;; routine maintains the slots :final-feed-avail, :final-feed-inuse
;;; and :final-feedback-proto, so don't set the slots after calling
;;; this function.
(defun find-final-feedback-obj (inter final-feedback-proto)
(let ((available-objs (get-local-value inter :final-feed-avail))
final-feedback-obj final-feedback-protos)
search if one of the current type is availble
(setf final-feedback-obj (car (member final-feedback-proto available-objs
:test #'(lambda (item list-obj)
(is-a-p list-obj item)))))
(cond (final-feedback-obj)
;; If there is no final feedback object of the desired type
;; available, check to see if the the prototype final
;; feedback has been added to the :final-feedback-protos
;; list. If it has not, add it to this list and make the
;; final feedback object be the prototype.
((not (member final-feedback-proto
(setf final-feedback-protos
(get-local-value inter :final-feedback-protos))))
(setf final-feedback-obj final-feedback-proto)
(s-value inter :final-feedback-protos
(push final-feedback-proto final-feedback-protos)))
;; Create an instance of the final feedback prototype
(t (setf final-feedback-obj
(get-new-feedback-obj final-feedback-proto))
(if-debug inter
(format t "----allocating final feedback obj:~s~%"
final-feedback-obj))))
;; now have a final-feedback-obj
(s-value inter :final-feed-avail ;; no-op if not there
(delete final-feedback-obj available-objs))
(s-value inter :final-feed-inuse
(cons final-feedback-obj
(get-local-value inter :final-feed-inuse)))
final-feedback-obj))
Initialize the final - feedback internal slots if necessary --
;;; should not be necessary in new version. Keep around just in case
;;; code is needed.
(defun check-start-final-feedback-obj (an-interactor)
(declare (ignore an-interactor)))
;; (when (and (g-value an-interactor :final-feedback-obj)
;; (null (get-local-value an-interactor :final-feed-avail))
;; (null (get-local-value an-interactor :final-feed-inuse)))
;; (s-value an-interactor :final-feed-avail
;; (list (g-value an-interactor :final-feedback-obj)))))
;;; Exported "useful" functions
(defun return-final-selection-objs (an-interactor)
"returns a list of all the final-feedback objects currently in use
by the interactor. This can be used to have another interactor
operate on the final feedback objects (e.g., moving from the
selection handles)."
(when (g-value an-interactor :final-feedback-obj)
(copy-list (get-local-value an-interactor :final-feed-inuse))))
(defun deselectobj (an-interactor obj)
"Cause obj to no longer be selected. Turns off the final-feedback
objects and clears the various selected slots appropriately. If obj
is not selected, this does nothing."
(let ((how-set (g-value an-interactor :how-set))
(main-agg (g-value an-interactor :main-aggregate))
(obj-sel-slot (obj-sel-slot an-interactor)))
(check-start-final-feedback-obj an-interactor)
(when (null main-agg) ; hasn't been run yet
(setq main-agg
(s-value an-interactor :main-aggregate
(get-gob-of-where (g-value an-interactor :start-where)))))
(setq how-set
(case how-set
((:list-add :list-remove :list-toggle) :list-remove)
((:set :clear :toggle) :clear)))
First do object itself
(when obj-sel-slot
(dbprint-sel obj-sel-slot obj nil an-interactor)
(s-value obj obj-sel-slot nil))
; Now do aggregate
(if (eq main-agg obj)
;; If no aggregate, then just clear any final-feedbacks
(clear-finals-and-set an-interactor
(get-local-value an-interactor :final-feed-inuse))
;; Otherwise, do the aggregate and any final-feedback objects
(calc-set-agg-slot an-interactor main-agg obj how-set))
obj))
(defun selectobj (an-interactor obj)
"cause obj to be selected. turns on the final-feedback objects and
sets the various selected slots appropriately. does not check
whether obj is part of the domain of an-interactor (in
start-where)."
(let ((how-set (g-value an-interactor :how-set))
(main-agg (g-value an-interactor :main-aggregate))
(agg-selected-slot (agg-sel-slot an-interactor)))
(check-start-final-feedback-obj an-interactor)
;; Hasn't been run yet
(when (null main-agg)
(setq main-agg
(s-value an-interactor :main-aggregate
(get-gob-of-where (g-value an-interactor :start-where)))))
(setq how-set
(case how-set
((:list-add :list-remove :list-toggle) :list-add)
((:set :clear :toggle) :set)))
First do object itself
(calc-set-obj-slot an-interactor obj how-set
(if (eq obj main-agg)
nil
(g-value main-agg agg-selected-slot)))
; Now do aggregate
(if (eq main-agg obj)
;; if no aggregate, then just set the final-feedback, if any
(one-final-feedback-obj an-interactor obj)
;; otherwise, do the aggregate and any final-feedback objects
(calc-set-agg-slot an-interactor main-agg obj how-set))
obj))
;;; Calculating how to set the selected slots
(defun how-set-error (how-set)
(error
"** bad how-set: ~s. options are :set :clear :toggle
:list-add :list-remove :list-toggle <num> (<num> <num>)" how-set))
;;; Sets the selected slot of the object according to how-set.
;;; other-obj contains the other objects that may need
;;; to be cleared because this one was set.
;;; Does handle when obj or other-obj are not schemas.
(defun calc-set-obj-slot (an-interactor obj how-set other-obj)
(if-debug an-interactor (format t "how-set=~s~%" how-set))
;; first clear other object, if necessary and if not same as the main obj
(let ((obj-sel-slot (obj-sel-slot an-interactor)))
(when obj-sel-slot
(if (and other-obj (not (eq other-obj obj)))
(case how-set
((:list-add :list-remove :list-toggle)) ; do nothing for these
((:set :clear :toggle) (if (listp other-obj)
;; then assume that used to be a list and
;; now isn't, so undo each element
(dolist (o other-obj)
(when (and (schema-p o)
(not (eq o obj)))
(dbprint-sel obj-sel-slot o nil
an-interactor)
(s-value o obj-sel-slot nil)))
otherwise , only one object to de - select
(when (schema-p other-obj)
(dbprint-sel obj-sel-slot other-obj nil
an-interactor)
(s-value other-obj obj-sel-slot nil))))
(otherwise))) ; is a number so do nothing
;; now set the selected slot of the new object
(let (val)
(when (schema-p obj);; otherwise, can't set its selected slot!
(case how-set
((:set :list-add) (dbprint-sel obj-sel-slot obj t an-interactor)
(s-value obj obj-sel-slot t))
((:clear :list-remove) (dbprint-sel obj-sel-slot obj nil an-interactor)
(s-value obj obj-sel-slot nil))
((:toggle :list-toggle)
(setq val (if (g-value obj obj-sel-slot) nil t))
(dbprint-sel obj-sel-slot obj val an-interactor)
(s-value obj obj-sel-slot val))
(otherwise (cond ((numberp how-set)
(incf (g-value obj obj-sel-slot) how-set)
(dbprint-sel obj-sel-slot obj
(g-value obj obj-sel-slot)
an-interactor))
((and (listp how-set)(numberp (first how-set))
(numberp (second how-set))) ; mod
(setq val (mod (+ (g-value obj obj-sel-slot)
(first how-set))
(second how-set)))
(dbprint-sel obj-sel-slot obj val an-interactor)
(s-value obj obj-sel-slot val))
(t (how-set-error how-set))))))))))
;; Used when the new values is :none, this clears out all the
;; selections from the aggregate and the final-feedback-objects
(defun clear-all-selected (an-interactor main-agg)
(if-debug an-interactor (format t "clearing all selections from ~s~%"
main-agg))
(when (schema-p main-agg)
(let* ((agg-sel-slot (agg-sel-slot an-interactor))
(obj-sel-slot (obj-sel-slot an-interactor))
(other-obj (g-value main-agg agg-sel-slot)))
;; first, clear the selected slots of any other objects
(when obj-sel-slot
(if (listp other-obj)
; undo each element
(dolist (o other-obj)
(when (and (schema-p o) (kr::schema-name o))
(dbprint-sel obj-sel-slot o nil an-interactor)
(s-value o obj-sel-slot nil)))
otherwise , only one object to de - select
(when (and (schema-p other-obj) (kr::schema-name other-obj))
(dbprint-sel obj-sel-slot other-obj nil an-interactor)
(s-value other-obj obj-sel-slot nil))))
;; then clear out the aggregate's slot
(s-value main-agg agg-sel-slot nil)))
(when (g-value an-interactor :final-feedback-obj) ; then we are doing final
; feedback objects
(clear-finals-and-set an-interactor
(get-local-value an-interactor :final-feed-inuse))))
;;; Sets the selected slot of the aggregate that the selected object
;;; is in according to how-set. newval is the new object selected.
(defun calc-set-agg-slot (an-interactor agg newval how-set)
(let* ((agg-sel-slot (agg-sel-slot an-interactor))
(old-sel (g-value agg agg-sel-slot))
val)
(when (schema-p agg)
(case how-set
(:set (dbprint-sel agg-sel-slot agg newval an-interactor)
(s-value agg agg-sel-slot newval)
(one-final-feedback-obj an-interactor newval))
(:clear (dbprint-sel agg-sel-slot agg nil an-interactor)
(s-value agg agg-sel-slot nil)
(one-final-feedback-obj an-interactor nil))
(:toggle (setq val
(if (listp old-sel)
;; Then converting from a list to a single
;; value
(if (member newval old-sel)
;; if used to be selected, then clear
nil
else select just this one
newval)
;; Otherwise, just check the old single
;; value
(if (eq old-sel newval)
;; if used to be selected, then clear
nil
else select this one
newval)))
(dbprint-sel agg-sel-slot agg val an-interactor)
(s-value agg agg-sel-slot val)
(one-final-feedback-obj an-interactor val))
(:list-add
(cond ((listp old-sel)
(pushnew newval (g-value agg agg-sel-slot))
(dbprint-sel agg-sel-slot
agg (g-value agg agg-sel-slot) an-interactor))
((schema-p old-sel)
;; Make it into a list (in case how-set changed
;; from single-selectable to be multiple selectable).
;; if new obj same as old, only include once, however.
(setq val (if (eq newval old-sel)
(list newval)
(list newval old-sel)))
(dbprint-sel agg-sel-slot agg val an-interactor)
(s-value agg agg-sel-slot val))
;; otherwise, throw away old value
(t (setq val (list newval))
(dbprint-sel agg-sel-slot agg val an-interactor)
(s-value agg agg-sel-slot val)))
(list-final-feedback-obj an-interactor newval t)) ; add newval
(:list-remove
(cond ((listp old-sel)
(setq val (delete newval (g-value agg agg-sel-slot)))
(dbprint-sel agg-sel-slot agg val an-interactor)
(s-value agg agg-sel-slot val)
(mark-as-changed agg agg-sel-slot)) ;; s-value may not cause
;slot to be marked since its value is
;a list which will be
;destructively modified by delete
;; else convert to a list
((eq old-sel newval) (dbprint-sel agg-sel-slot agg nil
an-interactor)
(s-value agg agg-sel-slot nil)) ;remove old
((schema-p old-sel) (setq val (list old-sel))
(dbprint-sel agg-sel-slot agg val an-interactor)
(s-value agg agg-sel-slot val)) ;keep old
(t (dbprint-sel agg-sel-slot agg nil an-interactor)
(s-value agg agg-sel-slot nil))) ; bad old value, remove it
(list-final-feedback-obj an-interactor newval nil)) ; remove newval
(:list-toggle
(cond ((listp old-sel)
(if (member newval old-sel)
(progn
(setq val (delete newval old-sel))
(dbprint-sel agg-sel-slot agg val an-interactor)
(s-value agg agg-sel-slot val)
;; s-value may not cause slot to be marked since
;; its value is a list which will be
;; destructively modified by delete
(mark-as-changed agg agg-sel-slot)
(list-final-feedback-obj an-interactor newval nil)) ;remove
(progn
(push newval (g-value agg agg-sel-slot))
(dbprint-sel agg-sel-slot agg (g-value agg agg-sel-slot)
an-interactor)
(list-final-feedback-obj an-interactor newval t)))) ;add
;; Otherwise, if was the old value, now none
((eq old-sel newval) (dbprint-sel agg-sel-slot agg nil
an-interactor)
(s-value agg agg-sel-slot nil)
(list-final-feedback-obj an-interactor newval nil)) ;remove
;; If was a different object, use both
((schema-p old-sel)
(setq val (list newval old-sel))
(dbprint-sel agg-sel-slot agg val an-interactor)
(s-value agg agg-sel-slot val)
;; add
(list-final-feedback-obj an-interactor newval t))
;; bad old val, remove it
(t (setq val (list newval))
(dbprint-sel agg-sel-slot agg val an-interactor)
(s-value agg agg-sel-slot val)
(list-final-feedback-obj an-interactor newval t)))) ;add
;; is a number, already incremented object's selected slot,
(otherwise
;; here just note newval
(dbprint-sel agg-sel-slot agg newval an-interactor)
(s-value agg agg-sel-slot newval)
(list-final-feedback-obj an-interactor newval t)))))) ;add
;;; Menu interactors
;;; default procedures to go into the slots
(declaim (special menu-interactor))
(defun menu-interactor-initialize (new-menu-schema)
(if-debug new-menu-schema (format t "menu initialize ~s~%" new-menu-schema))
(check-interactor-type new-menu-schema inter:menu-interactor)
(check-required-slots new-menu-schema)
(check-slots-to-set new-menu-schema)
(set-up-defaults new-menu-schema)
(s-value new-menu-schema :remembered-last-object nil) ; this slot must be local
) ;end initialize procedure
(defun menu-int-running-action (an-interactor prev-obj-over new-obj-over)
(if-debug an-interactor (format t "menu int-running, old = ~s, new= ~s~%"
prev-obj-over new-obj-over))
(unless (eq prev-obj-over new-obj-over)
(let ((interim-sel-slot (interim-sel-slot an-interactor))
(feedbackobj (g-value an-interactor :feedback-obj)))
(when feedbackobj
(dbprint-feed :obj-over feedbackobj new-obj-over an-interactor)
(s-value feedbackobj :obj-over new-obj-over))
(when (and interim-sel-slot prev-obj-over
(schema-p prev-obj-over))
(dbprint interim-sel-slot prev-obj-over nil an-interactor)
(s-value prev-obj-over interim-sel-slot nil))
(when (and interim-sel-slot
new-obj-over (schema-p new-obj-over))
(dbprint interim-sel-slot new-obj-over t an-interactor)
(s-value new-obj-over interim-sel-slot t)))))
(defun menu-int-start-action (an-interactor obj-under-mouse)
(if-debug an-interactor (format t "menu int-start over ~s~%" obj-under-mouse))
(kr-send an-interactor :running-action
an-interactor nil obj-under-mouse)) ;turn on feedback
(defun menu-int-outside-action (an-interactor outside-control prev-obj-over)
(if-debug an-interactor (format t "menu int-outside, old = ~s~%" prev-obj-over))
(unless (eq :last outside-control)
(kr-send an-interactor :running-action
an-interactor prev-obj-over nil)))
(defun menu-int-back-inside-action (an-interactor outside-control
prev-obj-over new-obj-over)
(if-debug an-interactor (format t "menu int-back-inside, old = ~s, new= ~s~%"
prev-obj-over new-obj-over))
(kr-send an-interactor :running-action an-interactor
(if (eq :last outside-control) prev-obj-over nil)
new-obj-over))
(defun menu-int-stop-action (an-interactor final-obj-over)
(if-debug an-interactor (format t "menu int-stop over ~s~%" final-obj-over))
(let ((feedbackobj (g-value an-interactor :feedback-obj))
(how-set (g-value an-interactor :how-set))
(main-agg (g-value an-interactor :main-aggregate))
(interim-sel-slot (interim-sel-slot an-interactor))
(agg-sel-slot (agg-sel-slot an-interactor))
(obj-sel-slot (obj-sel-slot an-interactor)))
(when feedbackobj
(dbprint-feed :obj-over feedbackobj nil an-interactor)
(s-value feedbackobj :obj-over nil))
(when final-obj-over
(when (and interim-sel-slot (schema-p final-obj-over))
(dbprint interim-sel-slot final-obj-over nil an-interactor)
(s-value final-obj-over interim-sel-slot nil))
(when (schema-p main-agg)
(calc-set-obj-slot an-interactor
final-obj-over how-set
; old-object is the one that used to be selected,
; and get it from the aggregate, if any
(if (eq final-obj-over main-agg)
nil
(g-value main-agg agg-sel-slot)))))
(if (eq :none final-obj-over)
(clear-all-selected an-interactor main-agg)
; else handle the new object normally
(when (and main-agg (schema-p main-agg))
(if (eq final-obj-over main-agg) ;; if eq, then selected already set,
; but still need to do final-feedback-obj
(one-final-feedback-obj an-interactor
(if (and obj-sel-slot
(g-value final-obj-over obj-sel-slot))
final-obj-over nil))
;; else set the selected slot of the main-agg. this procedure
;; will also handle the final-feedback-obj
(calc-set-agg-slot an-interactor main-agg
final-obj-over how-set))))
(kr-send an-interactor :final-function an-interactor final-obj-over)))
(defun menu-int-abort-action (an-interactor final-obj-over)
(if-debug an-interactor (format t "menu int-abort over ~s~%" final-obj-over))
(kr-send an-interactor :running-action an-interactor
final-obj-over nil))
;;; go procedure utilities
;;; remove from running level, put on start level, change state to
;;; start, call abort procedure. become-inactive ignored because :active
;;; set before this is called
(defun menu-do-abort (an-interactor become-inactive event)
(declare (ignore event become-inactive))
(if-debug an-interactor (format t "menu aborting~%"))
(gotostartstate an-interactor t)
(kr-send an-interactor :abort-action an-interactor
(get-local-value an-interactor :remembered-last-object)))
;;; if continuous: (remove from start level, add to stop and abort
;;; level, change state to running)
;;; save object over, call start procedure.
(defun menu-do-start (an-interactor new-obj-over event)
(declare (ignore event))
(if-debug an-interactor (format t "menu starting over ~s~%" new-obj-over))
(s-value an-interactor :remembered-last-object new-obj-over)
(fix-running-where an-interactor new-obj-over)
(s-value an-interactor :main-aggregate
(get-gob-of-where (get-running-where an-interactor)))
(check-start-final-feedback-obj an-interactor)
(if (g-value an-interactor :continuous) ;then will go to running state
(progn
(gotorunningstate an-interactor t)
(kr-send an-interactor :start-action an-interactor new-obj-over))
;else call stop-action
(progn
(gotostartstate an-interactor nil)
(kr-send an-interactor :stop-action an-interactor new-obj-over))))
;;; call outside procedure, clear saved obj, change state to outside
(defun menu-do-outside (an-interactor)
(if-debug an-interactor (format t "menu outside~%"))
(s-value an-interactor :current-state :outside)
(kr-send an-interactor :outside-action an-interactor
(g-value an-interactor :outside)
(g-value an-interactor :remembered-last-object))
(unless (eq :last (g-value an-interactor :outside))
(s-value an-interactor :remembered-last-object nil)))
;;;check to see if need to stop or abort based on whether :outside = :last
(defun menu-do-outside-stop (an-interactor event)
(if-debug an-interactor (format t "menu stop outside~%"))
(if (eq :last (g-value an-interactor :outside))
(menu-do-stop an-interactor (g-value an-interactor
:remembered-last-object) event)
(menu-do-abort an-interactor nil event)))
;;; call back-inside procedure, change state to running
(defun menu-do-back-inside (an-interactor new-obj-over event)
(declare (ignore event))
(if-debug an-interactor (format t "menu back-inside over ~s~%" new-obj-over))
(s-value an-interactor :current-state :running)
(let ((prev-obj-over (g-value an-interactor :remembered-last-object)))
(kr-send an-interactor :back-inside-action an-interactor
(g-value an-interactor :outside) prev-obj-over new-obj-over)
(s-value an-interactor :remembered-last-object new-obj-over)))
;;;if new object is different from old one, call running-procedure
(defun menu-do-running (an-interactor new-obj-over event)
(declare (ignore event))
(if-debug an-interactor (format t "menu running over ~s~%" new-obj-over))
(let ((prev-obj-over (g-value an-interactor :remembered-last-object)))
(unless (eq prev-obj-over new-obj-over)
(kr-send an-interactor :running-action an-interactor prev-obj-over
new-obj-over)
(s-value an-interactor :remembered-last-object new-obj-over))))
;;; If new-obj-over not equal to :remembered-last-object, then call
;;; running-action on :remembered-last-object so its interim-feedback can
;;; be removed. then, remove from running level, add to start level
;;; change state to start, call stop procedure
(defun menu-do-stop (an-interactor new-obj-over event)
(declare (ignore event))
(if-debug an-interactor (format t "menu stop over ~s~%" new-obj-over))
(let ((prev-obj-over (g-value an-interactor :remembered-last-object)))
(unless (eq prev-obj-over new-obj-over)
(kr-send an-interactor :running-action an-interactor prev-obj-over
new-obj-over)
(s-value an-interactor :remembered-last-object new-obj-over)))
(gotostartstate an-interactor t)
(kr-send an-interactor :stop-action an-interactor new-obj-over))
;;; This is used if explicitly call stop-interactor. it uses the last
;;; selected object
(defun menu-explicit-stop (an-interactor)
(if-debug an-interactor (format t "menu explicit stop~%"))
(let ((prev-obj-over (g-value an-interactor :remembered-last-object)))
(if prev-obj-over
(progn
(gotostartstate an-interactor t)
(kr-send an-interactor :stop-action an-interactor prev-obj-over))
(menu-do-abort an-interactor nil nil))))
;;; menu schema
(create-schema 'inter:menu-interactor
(:is-a inter:interactor)
(:name :first-menu-interactor)
(:start-action 'menu-int-start-action)
(:running-action 'menu-int-running-action)
(:stop-action 'menu-int-stop-action)
(:abort-action 'menu-int-abort-action)
(:outside-action 'menu-int-outside-action)
(:back-inside-action 'menu-int-back-inside-action)
(:how-set :set)
(:slots-to-set '(:interim-selected :selected :selected))
;; slots: interim, in object, in aggregate
(:remembered-last-object nil)
(:main-aggregate nil)
(:go 'general-go)
;; Proc executed when events happen. These are called
;; by go to do for stop-interactor the real work. they
;; call the appropriate action procedures
(:do-start 'menu-do-start)
(:do-running 'menu-do-running)
(:do-stop 'menu-do-stop)
(:do-explicit-stop 'menu-explicit-stop)
(:do-abort 'menu-do-abort)
(:do-outside 'menu-do-outside)
(:do-back-inside 'menu-do-back-inside)
(:do-outside-stop 'menu-do-outside-stop)
;; proc to call when created
(:initialize 'menu-interactor-initialize))
;;; need special destroy to remove the extra final feedback objects
;;; that may have been allocated.
(define-method :destroy-me
menu-interactor (an-interactor &optional (erase t))
(if-debug
an-interactor
(format t "menu special destroy ~s erase=~s~%" an-interactor erase))
(destroy-extra-final-feedback-objs an-interactor erase)
(call-prototype-method an-interactor erase))
| null | https://raw.githubusercontent.com/earl-ducaine/cl-garnet/f0095848513ba69c370ed1dc51ee01f0bb4dd108/src/inter/menuinter.lisp | lisp | Syntax : Common - Lisp ; Package : INTERACTORS ; Base : 10 -*-
to be put on the mailing list.
This file contains the mouse interactors to handle menus. It
Utility procedures
parts of :slots-to-set list
there always must be an aggregate selected slot because used for
final-feedback
final feedback objects
this clears the final feedback objects and resets the list in the
interactor.
destroys any objects created to be extra final feedback objects. this
is called when the interactor is destroyed.
Sets the final feedback object to be only new-sel-obj, or if
new-sel-obj is nil, then sets there to be no final-feedback-objs.
prototype itself), so this procedure does not need to worry about
allocating any.
otherwise, just exit
set feedback obj to it
Adds (if add-p is t) or removes (if add-p is nil) any final-feedback
objs refering to newval, but leaves rest of the final feedback
objects alone
otherwise, just exit
add new feedback obj unless one is there
get a feedback obj to use
else remove the feedback obj
Create an instance of final-feedback-proto unless it is a constant
Find an instance of final-feedback-proto in the available list of
final feedback objects. This allows the prototype to change,
e.g. because there is a formula in the :final-feedback-obj slots
which might depend on the object that the mouse is over. This
routine maintains the slots :final-feed-avail, :final-feed-inuse
and :final-feedback-proto, so don't set the slots after calling
this function.
If there is no final feedback object of the desired type
available, check to see if the the prototype final
feedback has been added to the :final-feedback-protos
list. If it has not, add it to this list and make the
final feedback object be the prototype.
Create an instance of the final feedback prototype
now have a final-feedback-obj
no-op if not there
should not be necessary in new version. Keep around just in case
code is needed.
(when (and (g-value an-interactor :final-feedback-obj)
(null (get-local-value an-interactor :final-feed-avail))
(null (get-local-value an-interactor :final-feed-inuse)))
(s-value an-interactor :final-feed-avail
(list (g-value an-interactor :final-feedback-obj)))))
Exported "useful" functions
hasn't been run yet
Now do aggregate
If no aggregate, then just clear any final-feedbacks
Otherwise, do the aggregate and any final-feedback objects
Hasn't been run yet
Now do aggregate
if no aggregate, then just set the final-feedback, if any
otherwise, do the aggregate and any final-feedback objects
Calculating how to set the selected slots
Sets the selected slot of the object according to how-set.
other-obj contains the other objects that may need
to be cleared because this one was set.
Does handle when obj or other-obj are not schemas.
first clear other object, if necessary and if not same as the main obj
do nothing for these
then assume that used to be a list and
now isn't, so undo each element
is a number so do nothing
now set the selected slot of the new object
otherwise, can't set its selected slot!
mod
Used when the new values is :none, this clears out all the
selections from the aggregate and the final-feedback-objects
first, clear the selected slots of any other objects
undo each element
then clear out the aggregate's slot
then we are doing final
feedback objects
Sets the selected slot of the aggregate that the selected object
is in according to how-set. newval is the new object selected.
Then converting from a list to a single
value
if used to be selected, then clear
Otherwise, just check the old single
value
if used to be selected, then clear
Make it into a list (in case how-set changed
from single-selectable to be multiple selectable).
if new obj same as old, only include once, however.
otherwise, throw away old value
add newval
s-value may not cause
slot to be marked since its value is
a list which will be
destructively modified by delete
else convert to a list
remove old
keep old
bad old value, remove it
remove newval
s-value may not cause slot to be marked since
its value is a list which will be
destructively modified by delete
remove
add
Otherwise, if was the old value, now none
remove
If was a different object, use both
add
bad old val, remove it
add
is a number, already incremented object's selected slot,
here just note newval
add
Menu interactors
default procedures to go into the slots
this slot must be local
end initialize procedure
turn on feedback
old-object is the one that used to be selected,
and get it from the aggregate, if any
else handle the new object normally
if eq, then selected already set,
but still need to do final-feedback-obj
else set the selected slot of the main-agg. this procedure
will also handle the final-feedback-obj
go procedure utilities
remove from running level, put on start level, change state to
start, call abort procedure. become-inactive ignored because :active
set before this is called
if continuous: (remove from start level, add to stop and abort
level, change state to running)
save object over, call start procedure.
then will go to running state
else call stop-action
call outside procedure, clear saved obj, change state to outside
check to see if need to stop or abort based on whether :outside = :last
call back-inside procedure, change state to running
if new object is different from old one, call running-procedure
If new-obj-over not equal to :remembered-last-object, then call
running-action on :remembered-last-object so its interim-feedback can
be removed. then, remove from running level, add to start level
change state to start, call stop procedure
This is used if explicitly call stop-interactor. it uses the last
selected object
menu schema
slots: interim, in object, in aggregate
Proc executed when events happen. These are called
by go to do for stop-interactor the real work. they
call the appropriate action procedures
proc to call when created
need special destroy to remove the extra final feedback objects
that may have been allocated. | The Garnet User Interface Development Environment .
This code was written as part of the Garnet project at Carnegie
Mellon University , and has been placed in the public domain . If
you are using this code or any part of Garnet , please contact
should be loaded after Interactor and after MoveGrowInter
Designed and implemented by
(in-package "INTERACTORS")
(defun check-slots-to-set (inter)
(let ((slots (g-value inter :slots-to-set)))
(unless (and (listp slots)
(= 3 (length slots))
(or (null (first slots)) (keywordp (first slots)))
(or (null (second slots)) (keywordp (second slots)))
(or (null (third slots)) (keywordp (third slots))))
(error "the :slots-to-set of ~s must be a list of three nils or keywords"
inter))))
(defun interim-sel-slot (inter)
(first (g-value inter :slots-to-set)))
(defun obj-sel-slot (inter)
(second (g-value inter :slots-to-set)))
(defun agg-sel-slot (inter)
(or (third (g-value inter :slots-to-set))
:*inter-agg-selected*))
(defun clear-finals (an-interactor feedback-objs-in-use)
(dolist (f feedback-objs-in-use)
(dbprint-feed :obj-over f nil an-interactor)
(s-value f :obj-over nil)))
(defun clear-finals-and-set (an-interactor feedback-objs-in-use)
(clear-finals an-interactor feedback-objs-in-use)
(if-debug an-interactor (format t "clearing interactor final feedback slots~%"))
(s-value an-interactor :final-feed-avail
(append (g-value an-interactor :final-feed-avail)
feedback-objs-in-use))
(s-value an-interactor :final-feed-inuse nil))
(defun destroy-extra-final-feedback-objs (an-interactor erase)
(if-debug an-interactor
(format t "destroying extra final feedback objects~%"))
(let ((final-feedback-protos
(get-local-value an-interactor :final-feedback-protos)))
(when final-feedback-protos
(dolist (obj (get-local-value an-interactor :final-feed-avail))
(when (schema-p obj)
(unless (member obj final-feedback-protos)
(with-constants-disabled
(opal:destroy obj erase)))))
(s-value an-interactor :final-feed-avail nil)
(dolist (obj (get-local-value an-interactor :final-feed-inuse))
(when (schema-p obj)
(unless (member obj final-feedback-protos)
(with-constants-disabled
(opal:destroy obj erase)))))
(s-value an-interactor :final-feed-inuse nil))))
There always must be at least one final - feedback - obj ( the
(defun one-final-feedback-obj (an-interactor new-sel-obj)
(let ((final-feedback-proto (g-value an-interactor :final-feedback-obj)))
(let ((feedback-objs-in-use
(get-local-value an-interactor :final-feed-inuse)))
(clear-finals-and-set an-interactor feedback-objs-in-use)
(when new-sel-obj
(let* ((final-feedback (find-final-feedback-obj an-interactor
final-feedback-proto)))
(dbprint-feed :obj-over final-feedback new-sel-obj an-interactor)
(s-value final-feedback :obj-over new-sel-obj)))))))
(defun list-final-feedback-obj (an-interactor newval add-p)
(let ((final-feedback-proto (g-value an-interactor :final-feedback-obj)))
(let ((feedback-objs-avail
(get-local-value an-interactor :final-feed-avail))
(feedback-objs-in-use
(get-local-value an-interactor :final-feed-inuse))
feed-for-newval)
(dolist (f feedback-objs-in-use)
(when (eq newval (g-value f :obj-over))
(setq feed-for-newval f)
(return)))
(if add-p
(unless feed-for-newval
(setq feed-for-newval
(find-final-feedback-obj an-interactor
final-feedback-proto))
(dbprint-feed :obj-over feed-for-newval newval an-interactor)
(s-value feed-for-newval :obj-over newval))
(when feed-for-newval
(dbprint-feed :obj-over feed-for-newval nil an-interactor)
(s-value feed-for-newval :obj-over nil)
(s-value an-interactor :final-feed-avail
(cons feed-for-newval feedback-objs-avail))
(s-value an-interactor :final-feed-inuse
(delete feed-for-newval feedback-objs-in-use))))))))
(defun get-new-feedback-obj (final-feedback-proto)
(let ((new-obj (create-instance nil final-feedback-proto)))
(with-constants-disabled
(opal:add-component (g-value final-feedback-proto :parent)
new-obj))
new-obj))
(defun find-final-feedback-obj (inter final-feedback-proto)
(let ((available-objs (get-local-value inter :final-feed-avail))
final-feedback-obj final-feedback-protos)
search if one of the current type is availble
(setf final-feedback-obj (car (member final-feedback-proto available-objs
:test #'(lambda (item list-obj)
(is-a-p list-obj item)))))
(cond (final-feedback-obj)
((not (member final-feedback-proto
(setf final-feedback-protos
(get-local-value inter :final-feedback-protos))))
(setf final-feedback-obj final-feedback-proto)
(s-value inter :final-feedback-protos
(push final-feedback-proto final-feedback-protos)))
(t (setf final-feedback-obj
(get-new-feedback-obj final-feedback-proto))
(if-debug inter
(format t "----allocating final feedback obj:~s~%"
final-feedback-obj))))
(delete final-feedback-obj available-objs))
(s-value inter :final-feed-inuse
(cons final-feedback-obj
(get-local-value inter :final-feed-inuse)))
final-feedback-obj))
Initialize the final - feedback internal slots if necessary --
(defun check-start-final-feedback-obj (an-interactor)
(declare (ignore an-interactor)))
(defun return-final-selection-objs (an-interactor)
"returns a list of all the final-feedback objects currently in use
by the interactor. This can be used to have another interactor
operate on the final feedback objects (e.g., moving from the
selection handles)."
(when (g-value an-interactor :final-feedback-obj)
(copy-list (get-local-value an-interactor :final-feed-inuse))))
(defun deselectobj (an-interactor obj)
"Cause obj to no longer be selected. Turns off the final-feedback
objects and clears the various selected slots appropriately. If obj
is not selected, this does nothing."
(let ((how-set (g-value an-interactor :how-set))
(main-agg (g-value an-interactor :main-aggregate))
(obj-sel-slot (obj-sel-slot an-interactor)))
(check-start-final-feedback-obj an-interactor)
(setq main-agg
(s-value an-interactor :main-aggregate
(get-gob-of-where (g-value an-interactor :start-where)))))
(setq how-set
(case how-set
((:list-add :list-remove :list-toggle) :list-remove)
((:set :clear :toggle) :clear)))
First do object itself
(when obj-sel-slot
(dbprint-sel obj-sel-slot obj nil an-interactor)
(s-value obj obj-sel-slot nil))
(if (eq main-agg obj)
(clear-finals-and-set an-interactor
(get-local-value an-interactor :final-feed-inuse))
(calc-set-agg-slot an-interactor main-agg obj how-set))
obj))
(defun selectobj (an-interactor obj)
"cause obj to be selected. turns on the final-feedback objects and
sets the various selected slots appropriately. does not check
whether obj is part of the domain of an-interactor (in
start-where)."
(let ((how-set (g-value an-interactor :how-set))
(main-agg (g-value an-interactor :main-aggregate))
(agg-selected-slot (agg-sel-slot an-interactor)))
(check-start-final-feedback-obj an-interactor)
(when (null main-agg)
(setq main-agg
(s-value an-interactor :main-aggregate
(get-gob-of-where (g-value an-interactor :start-where)))))
(setq how-set
(case how-set
((:list-add :list-remove :list-toggle) :list-add)
((:set :clear :toggle) :set)))
First do object itself
(calc-set-obj-slot an-interactor obj how-set
(if (eq obj main-agg)
nil
(g-value main-agg agg-selected-slot)))
(if (eq main-agg obj)
(one-final-feedback-obj an-interactor obj)
(calc-set-agg-slot an-interactor main-agg obj how-set))
obj))
(defun how-set-error (how-set)
(error
"** bad how-set: ~s. options are :set :clear :toggle
:list-add :list-remove :list-toggle <num> (<num> <num>)" how-set))
(defun calc-set-obj-slot (an-interactor obj how-set other-obj)
(if-debug an-interactor (format t "how-set=~s~%" how-set))
(let ((obj-sel-slot (obj-sel-slot an-interactor)))
(when obj-sel-slot
(if (and other-obj (not (eq other-obj obj)))
(case how-set
((:set :clear :toggle) (if (listp other-obj)
(dolist (o other-obj)
(when (and (schema-p o)
(not (eq o obj)))
(dbprint-sel obj-sel-slot o nil
an-interactor)
(s-value o obj-sel-slot nil)))
otherwise , only one object to de - select
(when (schema-p other-obj)
(dbprint-sel obj-sel-slot other-obj nil
an-interactor)
(s-value other-obj obj-sel-slot nil))))
(let (val)
(case how-set
((:set :list-add) (dbprint-sel obj-sel-slot obj t an-interactor)
(s-value obj obj-sel-slot t))
((:clear :list-remove) (dbprint-sel obj-sel-slot obj nil an-interactor)
(s-value obj obj-sel-slot nil))
((:toggle :list-toggle)
(setq val (if (g-value obj obj-sel-slot) nil t))
(dbprint-sel obj-sel-slot obj val an-interactor)
(s-value obj obj-sel-slot val))
(otherwise (cond ((numberp how-set)
(incf (g-value obj obj-sel-slot) how-set)
(dbprint-sel obj-sel-slot obj
(g-value obj obj-sel-slot)
an-interactor))
((and (listp how-set)(numberp (first how-set))
(setq val (mod (+ (g-value obj obj-sel-slot)
(first how-set))
(second how-set)))
(dbprint-sel obj-sel-slot obj val an-interactor)
(s-value obj obj-sel-slot val))
(t (how-set-error how-set))))))))))
(defun clear-all-selected (an-interactor main-agg)
(if-debug an-interactor (format t "clearing all selections from ~s~%"
main-agg))
(when (schema-p main-agg)
(let* ((agg-sel-slot (agg-sel-slot an-interactor))
(obj-sel-slot (obj-sel-slot an-interactor))
(other-obj (g-value main-agg agg-sel-slot)))
(when obj-sel-slot
(if (listp other-obj)
(dolist (o other-obj)
(when (and (schema-p o) (kr::schema-name o))
(dbprint-sel obj-sel-slot o nil an-interactor)
(s-value o obj-sel-slot nil)))
otherwise , only one object to de - select
(when (and (schema-p other-obj) (kr::schema-name other-obj))
(dbprint-sel obj-sel-slot other-obj nil an-interactor)
(s-value other-obj obj-sel-slot nil))))
(s-value main-agg agg-sel-slot nil)))
(clear-finals-and-set an-interactor
(get-local-value an-interactor :final-feed-inuse))))
(defun calc-set-agg-slot (an-interactor agg newval how-set)
(let* ((agg-sel-slot (agg-sel-slot an-interactor))
(old-sel (g-value agg agg-sel-slot))
val)
(when (schema-p agg)
(case how-set
(:set (dbprint-sel agg-sel-slot agg newval an-interactor)
(s-value agg agg-sel-slot newval)
(one-final-feedback-obj an-interactor newval))
(:clear (dbprint-sel agg-sel-slot agg nil an-interactor)
(s-value agg agg-sel-slot nil)
(one-final-feedback-obj an-interactor nil))
(:toggle (setq val
(if (listp old-sel)
(if (member newval old-sel)
nil
else select just this one
newval)
(if (eq old-sel newval)
nil
else select this one
newval)))
(dbprint-sel agg-sel-slot agg val an-interactor)
(s-value agg agg-sel-slot val)
(one-final-feedback-obj an-interactor val))
(:list-add
(cond ((listp old-sel)
(pushnew newval (g-value agg agg-sel-slot))
(dbprint-sel agg-sel-slot
agg (g-value agg agg-sel-slot) an-interactor))
((schema-p old-sel)
(setq val (if (eq newval old-sel)
(list newval)
(list newval old-sel)))
(dbprint-sel agg-sel-slot agg val an-interactor)
(s-value agg agg-sel-slot val))
(t (setq val (list newval))
(dbprint-sel agg-sel-slot agg val an-interactor)
(s-value agg agg-sel-slot val)))
(:list-remove
(cond ((listp old-sel)
(setq val (delete newval (g-value agg agg-sel-slot)))
(dbprint-sel agg-sel-slot agg val an-interactor)
(s-value agg agg-sel-slot val)
((eq old-sel newval) (dbprint-sel agg-sel-slot agg nil
an-interactor)
((schema-p old-sel) (setq val (list old-sel))
(dbprint-sel agg-sel-slot agg val an-interactor)
(t (dbprint-sel agg-sel-slot agg nil an-interactor)
(:list-toggle
(cond ((listp old-sel)
(if (member newval old-sel)
(progn
(setq val (delete newval old-sel))
(dbprint-sel agg-sel-slot agg val an-interactor)
(s-value agg agg-sel-slot val)
(mark-as-changed agg agg-sel-slot)
(progn
(push newval (g-value agg agg-sel-slot))
(dbprint-sel agg-sel-slot agg (g-value agg agg-sel-slot)
an-interactor)
((eq old-sel newval) (dbprint-sel agg-sel-slot agg nil
an-interactor)
(s-value agg agg-sel-slot nil)
((schema-p old-sel)
(setq val (list newval old-sel))
(dbprint-sel agg-sel-slot agg val an-interactor)
(s-value agg agg-sel-slot val)
(list-final-feedback-obj an-interactor newval t))
(t (setq val (list newval))
(dbprint-sel agg-sel-slot agg val an-interactor)
(s-value agg agg-sel-slot val)
(otherwise
(dbprint-sel agg-sel-slot agg newval an-interactor)
(s-value agg agg-sel-slot newval)
(declaim (special menu-interactor))
(defun menu-interactor-initialize (new-menu-schema)
(if-debug new-menu-schema (format t "menu initialize ~s~%" new-menu-schema))
(check-interactor-type new-menu-schema inter:menu-interactor)
(check-required-slots new-menu-schema)
(check-slots-to-set new-menu-schema)
(set-up-defaults new-menu-schema)
(defun menu-int-running-action (an-interactor prev-obj-over new-obj-over)
(if-debug an-interactor (format t "menu int-running, old = ~s, new= ~s~%"
prev-obj-over new-obj-over))
(unless (eq prev-obj-over new-obj-over)
(let ((interim-sel-slot (interim-sel-slot an-interactor))
(feedbackobj (g-value an-interactor :feedback-obj)))
(when feedbackobj
(dbprint-feed :obj-over feedbackobj new-obj-over an-interactor)
(s-value feedbackobj :obj-over new-obj-over))
(when (and interim-sel-slot prev-obj-over
(schema-p prev-obj-over))
(dbprint interim-sel-slot prev-obj-over nil an-interactor)
(s-value prev-obj-over interim-sel-slot nil))
(when (and interim-sel-slot
new-obj-over (schema-p new-obj-over))
(dbprint interim-sel-slot new-obj-over t an-interactor)
(s-value new-obj-over interim-sel-slot t)))))
(defun menu-int-start-action (an-interactor obj-under-mouse)
(if-debug an-interactor (format t "menu int-start over ~s~%" obj-under-mouse))
(kr-send an-interactor :running-action
(defun menu-int-outside-action (an-interactor outside-control prev-obj-over)
(if-debug an-interactor (format t "menu int-outside, old = ~s~%" prev-obj-over))
(unless (eq :last outside-control)
(kr-send an-interactor :running-action
an-interactor prev-obj-over nil)))
(defun menu-int-back-inside-action (an-interactor outside-control
prev-obj-over new-obj-over)
(if-debug an-interactor (format t "menu int-back-inside, old = ~s, new= ~s~%"
prev-obj-over new-obj-over))
(kr-send an-interactor :running-action an-interactor
(if (eq :last outside-control) prev-obj-over nil)
new-obj-over))
(defun menu-int-stop-action (an-interactor final-obj-over)
(if-debug an-interactor (format t "menu int-stop over ~s~%" final-obj-over))
(let ((feedbackobj (g-value an-interactor :feedback-obj))
(how-set (g-value an-interactor :how-set))
(main-agg (g-value an-interactor :main-aggregate))
(interim-sel-slot (interim-sel-slot an-interactor))
(agg-sel-slot (agg-sel-slot an-interactor))
(obj-sel-slot (obj-sel-slot an-interactor)))
(when feedbackobj
(dbprint-feed :obj-over feedbackobj nil an-interactor)
(s-value feedbackobj :obj-over nil))
(when final-obj-over
(when (and interim-sel-slot (schema-p final-obj-over))
(dbprint interim-sel-slot final-obj-over nil an-interactor)
(s-value final-obj-over interim-sel-slot nil))
(when (schema-p main-agg)
(calc-set-obj-slot an-interactor
final-obj-over how-set
(if (eq final-obj-over main-agg)
nil
(g-value main-agg agg-sel-slot)))))
(if (eq :none final-obj-over)
(clear-all-selected an-interactor main-agg)
(when (and main-agg (schema-p main-agg))
(one-final-feedback-obj an-interactor
(if (and obj-sel-slot
(g-value final-obj-over obj-sel-slot))
final-obj-over nil))
(calc-set-agg-slot an-interactor main-agg
final-obj-over how-set))))
(kr-send an-interactor :final-function an-interactor final-obj-over)))
(defun menu-int-abort-action (an-interactor final-obj-over)
(if-debug an-interactor (format t "menu int-abort over ~s~%" final-obj-over))
(kr-send an-interactor :running-action an-interactor
final-obj-over nil))
(defun menu-do-abort (an-interactor become-inactive event)
(declare (ignore event become-inactive))
(if-debug an-interactor (format t "menu aborting~%"))
(gotostartstate an-interactor t)
(kr-send an-interactor :abort-action an-interactor
(get-local-value an-interactor :remembered-last-object)))
(defun menu-do-start (an-interactor new-obj-over event)
(declare (ignore event))
(if-debug an-interactor (format t "menu starting over ~s~%" new-obj-over))
(s-value an-interactor :remembered-last-object new-obj-over)
(fix-running-where an-interactor new-obj-over)
(s-value an-interactor :main-aggregate
(get-gob-of-where (get-running-where an-interactor)))
(check-start-final-feedback-obj an-interactor)
(progn
(gotorunningstate an-interactor t)
(kr-send an-interactor :start-action an-interactor new-obj-over))
(progn
(gotostartstate an-interactor nil)
(kr-send an-interactor :stop-action an-interactor new-obj-over))))
(defun menu-do-outside (an-interactor)
(if-debug an-interactor (format t "menu outside~%"))
(s-value an-interactor :current-state :outside)
(kr-send an-interactor :outside-action an-interactor
(g-value an-interactor :outside)
(g-value an-interactor :remembered-last-object))
(unless (eq :last (g-value an-interactor :outside))
(s-value an-interactor :remembered-last-object nil)))
(defun menu-do-outside-stop (an-interactor event)
(if-debug an-interactor (format t "menu stop outside~%"))
(if (eq :last (g-value an-interactor :outside))
(menu-do-stop an-interactor (g-value an-interactor
:remembered-last-object) event)
(menu-do-abort an-interactor nil event)))
(defun menu-do-back-inside (an-interactor new-obj-over event)
(declare (ignore event))
(if-debug an-interactor (format t "menu back-inside over ~s~%" new-obj-over))
(s-value an-interactor :current-state :running)
(let ((prev-obj-over (g-value an-interactor :remembered-last-object)))
(kr-send an-interactor :back-inside-action an-interactor
(g-value an-interactor :outside) prev-obj-over new-obj-over)
(s-value an-interactor :remembered-last-object new-obj-over)))
(defun menu-do-running (an-interactor new-obj-over event)
(declare (ignore event))
(if-debug an-interactor (format t "menu running over ~s~%" new-obj-over))
(let ((prev-obj-over (g-value an-interactor :remembered-last-object)))
(unless (eq prev-obj-over new-obj-over)
(kr-send an-interactor :running-action an-interactor prev-obj-over
new-obj-over)
(s-value an-interactor :remembered-last-object new-obj-over))))
(defun menu-do-stop (an-interactor new-obj-over event)
(declare (ignore event))
(if-debug an-interactor (format t "menu stop over ~s~%" new-obj-over))
(let ((prev-obj-over (g-value an-interactor :remembered-last-object)))
(unless (eq prev-obj-over new-obj-over)
(kr-send an-interactor :running-action an-interactor prev-obj-over
new-obj-over)
(s-value an-interactor :remembered-last-object new-obj-over)))
(gotostartstate an-interactor t)
(kr-send an-interactor :stop-action an-interactor new-obj-over))
(defun menu-explicit-stop (an-interactor)
(if-debug an-interactor (format t "menu explicit stop~%"))
(let ((prev-obj-over (g-value an-interactor :remembered-last-object)))
(if prev-obj-over
(progn
(gotostartstate an-interactor t)
(kr-send an-interactor :stop-action an-interactor prev-obj-over))
(menu-do-abort an-interactor nil nil))))
(create-schema 'inter:menu-interactor
(:is-a inter:interactor)
(:name :first-menu-interactor)
(:start-action 'menu-int-start-action)
(:running-action 'menu-int-running-action)
(:stop-action 'menu-int-stop-action)
(:abort-action 'menu-int-abort-action)
(:outside-action 'menu-int-outside-action)
(:back-inside-action 'menu-int-back-inside-action)
(:how-set :set)
(:slots-to-set '(:interim-selected :selected :selected))
(:remembered-last-object nil)
(:main-aggregate nil)
(:go 'general-go)
(:do-start 'menu-do-start)
(:do-running 'menu-do-running)
(:do-stop 'menu-do-stop)
(:do-explicit-stop 'menu-explicit-stop)
(:do-abort 'menu-do-abort)
(:do-outside 'menu-do-outside)
(:do-back-inside 'menu-do-back-inside)
(:do-outside-stop 'menu-do-outside-stop)
(:initialize 'menu-interactor-initialize))
(define-method :destroy-me
menu-interactor (an-interactor &optional (erase t))
(if-debug
an-interactor
(format t "menu special destroy ~s erase=~s~%" an-interactor erase))
(destroy-extra-final-feedback-objs an-interactor erase)
(call-prototype-method an-interactor erase))
|
57a384145c27c4d0d975007846efc687a219fa89889c08752340fc181040a10b | fourmolu/fourmolu | qualified-ops-four-out.hs | lenses =
Just $
M.fromList $
"type" Foo..= ("user.connection" :: Text)
Bar.# "connection" Foo..= uc
Bar.# "user" Foo..= case name of
Just n -> Just $ object ["name" .= n]
Nothing -> Nothing
Bar.# []
| null | https://raw.githubusercontent.com/fourmolu/fourmolu/1f8903a92c8d5001dc1ec8ecfd4a04a3b61c3283/data/examples/declaration/value/function/infix/qualified-ops-four-out.hs | haskell | lenses =
Just $
M.fromList $
"type" Foo..= ("user.connection" :: Text)
Bar.# "connection" Foo..= uc
Bar.# "user" Foo..= case name of
Just n -> Just $ object ["name" .= n]
Nothing -> Nothing
Bar.# []
| |
7ad57674dbd2c808f4fabca0b2180adb3de5f45040ccd2847b48f140f28bcec8 | lukstafi/invargent | Invariants.mli | * Solving second - order i.e. formula variables for InvarGenT.
Released under the GNU General Public Licence ( version 2 or
higher ) , NO WARRANTY of correctness etc . ( C ) 2013
@author ( AT ) gmail.com
@since Mar 2013
Released under the GNU General Public Licence (version 2 or
higher), NO WARRANTY of correctness etc. (C) Lukasz Stafiniak 2013
@author Lukasz Stafiniak lukstafi (AT) gmail.com
@since Mar 2013
*)
val early_postcond_abd : bool ref
val timeout_count : int ref
val timeout_flag : bool ref
val unfinished_postcond_flag : bool ref
val use_prior_discards : bool ref
* If [ true ] , do not use specific heuristic settings for definitions
with assertions . Currently , when [ false ] , { ! }
is set to [ -1 ] for definitions with assertions .
with assertions. Currently, when [false], {!NumS.reward_constrn}
is set to [-1] for definitions with assertions. *)
val same_with_assertions : bool ref
* Breakdown of steps through the main iteration to achieve
convergence , counting from 0 . The iteration :
* [ disj_step.(0 ) ] is when inferring any postconditions starts ,
* [ ) ] is when inferring numerical postconditions starts ,
* [ disj_step.(2 ) ] is when using only non - rec branches ends ,
* [ disj_step.(3 ) ] is when second - phase abduction starts ,
* [ disj_step.(4 ) ] is when guessing in constraint generation ends ,
* [ disj_step.(5 ) ] is when convergence of postconditions is enforced .
convergence, counting from 0. The iteration:
* [disj_step.(0)] is when inferring any postconditions starts,
* [disj_step.(1)] is when inferring numerical postconditions starts,
* [disj_step.(2)] is when using only non-rec branches ends,
* [disj_step.(3)] is when second-phase abduction starts,
* [disj_step.(4)] is when guessing in constraint generation ends,
* [disj_step.(5)] is when convergence of postconditions is enforced.
*)
val disj_step : int array
type chi_subst = (int * (Defs.var_name list * Terms.formula)) list
val neg_constrns : bool ref
val solve :
uses_pos_assertions:bool ->
Defs.quant_ops -> (int * Defs.loc) list -> (int, int) Hashtbl.t ->
(Terms.formula * Terms.formula) list ->
Defs.quant_ops * Terms.formula * chi_subst
| null | https://raw.githubusercontent.com/lukstafi/invargent/e25d8b12d9f9a8e2d5269001dd14cf93abcb7549/src/Invariants.mli | ocaml | * Solving second - order i.e. formula variables for InvarGenT.
Released under the GNU General Public Licence ( version 2 or
higher ) , NO WARRANTY of correctness etc . ( C ) 2013
@author ( AT ) gmail.com
@since Mar 2013
Released under the GNU General Public Licence (version 2 or
higher), NO WARRANTY of correctness etc. (C) Lukasz Stafiniak 2013
@author Lukasz Stafiniak lukstafi (AT) gmail.com
@since Mar 2013
*)
val early_postcond_abd : bool ref
val timeout_count : int ref
val timeout_flag : bool ref
val unfinished_postcond_flag : bool ref
val use_prior_discards : bool ref
* If [ true ] , do not use specific heuristic settings for definitions
with assertions . Currently , when [ false ] , { ! }
is set to [ -1 ] for definitions with assertions .
with assertions. Currently, when [false], {!NumS.reward_constrn}
is set to [-1] for definitions with assertions. *)
val same_with_assertions : bool ref
* Breakdown of steps through the main iteration to achieve
convergence , counting from 0 . The iteration :
* [ disj_step.(0 ) ] is when inferring any postconditions starts ,
* [ ) ] is when inferring numerical postconditions starts ,
* [ disj_step.(2 ) ] is when using only non - rec branches ends ,
* [ disj_step.(3 ) ] is when second - phase abduction starts ,
* [ disj_step.(4 ) ] is when guessing in constraint generation ends ,
* [ disj_step.(5 ) ] is when convergence of postconditions is enforced .
convergence, counting from 0. The iteration:
* [disj_step.(0)] is when inferring any postconditions starts,
* [disj_step.(1)] is when inferring numerical postconditions starts,
* [disj_step.(2)] is when using only non-rec branches ends,
* [disj_step.(3)] is when second-phase abduction starts,
* [disj_step.(4)] is when guessing in constraint generation ends,
* [disj_step.(5)] is when convergence of postconditions is enforced.
*)
val disj_step : int array
type chi_subst = (int * (Defs.var_name list * Terms.formula)) list
val neg_constrns : bool ref
val solve :
uses_pos_assertions:bool ->
Defs.quant_ops -> (int * Defs.loc) list -> (int, int) Hashtbl.t ->
(Terms.formula * Terms.formula) list ->
Defs.quant_ops * Terms.formula * chi_subst
| |
8128d2e71fdbf4da694bd735292d7b25c9870f6231d1fa5b4b4d0d5ffb4be074 | hstreamdb/hstream | Exception.hs | {-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
# LANGUAGE TypeApplications #
module HStream.SQL.Exception
( Position
, SomeSQLException (..)
, SomeSQLExceptionInfo (..)
, SomeRuntimeException (..)
, buildSQLException
, throwSQLException
, throwRuntimeException
, formatSomeSQLException
, isEOF
) where
import Control.Exception (Exception, throw, try)
import GHC.Stack (CallStack, HasCallStack, callStack,
prettyCallStack)
import HStream.SQL.Abs (BNFC'Position)
--------------------------------------------------------------------------------
-- | Position in a SQL input text. 'Nothing' means that the position information
-- has been erased.
type Position = BNFC'Position
--------------------------------------------------------------------------------
-- | The root type of all SQL exceptions, you can catch some SQL exception
-- by catching this root type.
data SomeSQLException where
ParseException :: HasCallStack => SomeSQLExceptionInfo -> SomeSQLException
RefineException :: HasCallStack => SomeSQLExceptionInfo -> SomeSQLException
CodegenException :: HasCallStack => SomeSQLExceptionInfo -> SomeSQLException
GenExecPlanException :: HasCallStack => SomeSQLExceptionInfo -> SomeSQLException
instance Show SomeSQLException where
show (ParseException info) = "ParseException at " ++ show info ++ "\n" ++ prettyCallStack callStack
show (RefineException info) = "RefineException at " ++ show info ++ "\n" ++ prettyCallStack callStack
show (CodegenException info) = "CodegenException at " ++ show info ++ "\n" ++ prettyCallStack callStack
show (GenExecPlanException info) = "GenExecPlanException at " ++ show info ++ "\n" ++ prettyCallStack callStack
instance Exception SomeSQLException
formatSomeSQLException :: SomeSQLException -> String
formatSomeSQLException (ParseException info) = "Parse exception " ++ formatParseExceptionInfo info
formatSomeSQLException (RefineException info) = "Refine exception at " ++ show info
formatSomeSQLException (CodegenException info) = "Codegen exception at " ++ show info
formatSomeSQLException (GenExecPlanException info) = "Generate execution plan exception at " ++ show info
formatParseExceptionInfo :: SomeSQLExceptionInfo -> String
formatParseExceptionInfo SomeSQLExceptionInfo{..} =
case words sqlExceptionMessage of
"syntax" : "error" : "at" : "line" : x : "column" : y : ss ->
"at <line " ++ x ++ "column " ++ y ++ ">: syntax error " ++ unwords ss ++ "."
_ ->
let detailedSqlExceptionMessage = if sqlExceptionMessage /= eofErrMsg
then sqlExceptionMessage
else sqlExceptionMessage <> ": expected a \";\" at the end of a statement"
in posInfo ++ detailedSqlExceptionMessage ++ "."
where
posInfo = case sqlExceptionPosition of
Just (l,c) -> "at <line " ++ show l ++ ", column " ++ show c ++ ">"
Nothing -> ""
-- | SomeSQLException information.
data SomeSQLExceptionInfo = SomeSQLExceptionInfo
{ sqlExceptionPosition :: Position -- ^ position of SQL input text where exception was thrown
, sqlExceptionMessage :: String -- ^ description for this exception
^ lightweight partial
}
instance Show SomeSQLExceptionInfo where
show SomeSQLExceptionInfo{..} =
let posInfo = case sqlExceptionPosition of
Nothing -> "<unknown position>"
Just (l,c) -> "<line " ++ show l ++ ", column " ++ show c ++ ">"
in posInfo ++ ": " ++ sqlExceptionMessage
-- | Build an SQL exception from its type, position and description. It won't be thrown.
buildSQLException :: (SomeSQLExceptionInfo -> SomeSQLException)
-> Position
-> String
-> SomeSQLException
buildSQLException exceptionType exceptionPos exceptionMsg =
exceptionType (SomeSQLExceptionInfo exceptionPos exceptionMsg callStack)
-- | Build an SQL exception from its type, position and description then throw it.
throwSQLException :: (SomeSQLExceptionInfo -> SomeSQLException)
-> Position
-> String
-> a
throwSQLException exceptionType exceptionPos exceptionMsg =
throw $ buildSQLException exceptionType exceptionPos exceptionMsg
isEOF :: SomeSQLException -> Bool
isEOF xs =
case xs of
ParseException info ->
let SomeSQLExceptionInfo _ msg _ = info in
msg == eofErrMsg
_ -> False
eofErrMsg :: String
eofErrMsg = "syntax error at end of file"
--------------------------------------------------------------------------------
data SomeRuntimeException = SomeRuntimeException
{ runtimeExceptionMessage :: String
, runtimeExceptionCallStack :: CallStack
}
instance Show SomeRuntimeException where
show SomeRuntimeException{..} = runtimeExceptionMessage
instance Exception SomeRuntimeException
throwRuntimeException :: String -> a
throwRuntimeException msg =
throw $ SomeRuntimeException { runtimeExceptionMessage = msg
, runtimeExceptionCallStack = callStack
}
| null | https://raw.githubusercontent.com/hstreamdb/hstream/3a6df1337747e2e080712d7708ed05824d069664/hstream-sql/src/HStream/SQL/Exception.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
------------------------------------------------------------------------------
| Position in a SQL input text. 'Nothing' means that the position information
has been erased.
------------------------------------------------------------------------------
| The root type of all SQL exceptions, you can catch some SQL exception
by catching this root type.
| SomeSQLException information.
^ position of SQL input text where exception was thrown
^ description for this exception
| Build an SQL exception from its type, position and description. It won't be thrown.
| Build an SQL exception from its type, position and description then throw it.
------------------------------------------------------------------------------ | # LANGUAGE RecordWildCards #
# LANGUAGE TypeApplications #
module HStream.SQL.Exception
( Position
, SomeSQLException (..)
, SomeSQLExceptionInfo (..)
, SomeRuntimeException (..)
, buildSQLException
, throwSQLException
, throwRuntimeException
, formatSomeSQLException
, isEOF
) where
import Control.Exception (Exception, throw, try)
import GHC.Stack (CallStack, HasCallStack, callStack,
prettyCallStack)
import HStream.SQL.Abs (BNFC'Position)
type Position = BNFC'Position
data SomeSQLException where
ParseException :: HasCallStack => SomeSQLExceptionInfo -> SomeSQLException
RefineException :: HasCallStack => SomeSQLExceptionInfo -> SomeSQLException
CodegenException :: HasCallStack => SomeSQLExceptionInfo -> SomeSQLException
GenExecPlanException :: HasCallStack => SomeSQLExceptionInfo -> SomeSQLException
instance Show SomeSQLException where
show (ParseException info) = "ParseException at " ++ show info ++ "\n" ++ prettyCallStack callStack
show (RefineException info) = "RefineException at " ++ show info ++ "\n" ++ prettyCallStack callStack
show (CodegenException info) = "CodegenException at " ++ show info ++ "\n" ++ prettyCallStack callStack
show (GenExecPlanException info) = "GenExecPlanException at " ++ show info ++ "\n" ++ prettyCallStack callStack
instance Exception SomeSQLException
formatSomeSQLException :: SomeSQLException -> String
formatSomeSQLException (ParseException info) = "Parse exception " ++ formatParseExceptionInfo info
formatSomeSQLException (RefineException info) = "Refine exception at " ++ show info
formatSomeSQLException (CodegenException info) = "Codegen exception at " ++ show info
formatSomeSQLException (GenExecPlanException info) = "Generate execution plan exception at " ++ show info
formatParseExceptionInfo :: SomeSQLExceptionInfo -> String
formatParseExceptionInfo SomeSQLExceptionInfo{..} =
case words sqlExceptionMessage of
"syntax" : "error" : "at" : "line" : x : "column" : y : ss ->
"at <line " ++ x ++ "column " ++ y ++ ">: syntax error " ++ unwords ss ++ "."
_ ->
let detailedSqlExceptionMessage = if sqlExceptionMessage /= eofErrMsg
then sqlExceptionMessage
else sqlExceptionMessage <> ": expected a \";\" at the end of a statement"
in posInfo ++ detailedSqlExceptionMessage ++ "."
where
posInfo = case sqlExceptionPosition of
Just (l,c) -> "at <line " ++ show l ++ ", column " ++ show c ++ ">"
Nothing -> ""
data SomeSQLExceptionInfo = SomeSQLExceptionInfo
^ lightweight partial
}
instance Show SomeSQLExceptionInfo where
show SomeSQLExceptionInfo{..} =
let posInfo = case sqlExceptionPosition of
Nothing -> "<unknown position>"
Just (l,c) -> "<line " ++ show l ++ ", column " ++ show c ++ ">"
in posInfo ++ ": " ++ sqlExceptionMessage
buildSQLException :: (SomeSQLExceptionInfo -> SomeSQLException)
-> Position
-> String
-> SomeSQLException
buildSQLException exceptionType exceptionPos exceptionMsg =
exceptionType (SomeSQLExceptionInfo exceptionPos exceptionMsg callStack)
throwSQLException :: (SomeSQLExceptionInfo -> SomeSQLException)
-> Position
-> String
-> a
throwSQLException exceptionType exceptionPos exceptionMsg =
throw $ buildSQLException exceptionType exceptionPos exceptionMsg
isEOF :: SomeSQLException -> Bool
isEOF xs =
case xs of
ParseException info ->
let SomeSQLExceptionInfo _ msg _ = info in
msg == eofErrMsg
_ -> False
eofErrMsg :: String
eofErrMsg = "syntax error at end of file"
data SomeRuntimeException = SomeRuntimeException
{ runtimeExceptionMessage :: String
, runtimeExceptionCallStack :: CallStack
}
instance Show SomeRuntimeException where
show SomeRuntimeException{..} = runtimeExceptionMessage
instance Exception SomeRuntimeException
throwRuntimeException :: String -> a
throwRuntimeException msg =
throw $ SomeRuntimeException { runtimeExceptionMessage = msg
, runtimeExceptionCallStack = callStack
}
|
1423e4f607f7eecb43bc0793addd5ed505c9f3fcff1399fdc5cf0b263b3b8241 | reborg/clojure-essential-reference | 2.clj | (def coll [])
< 1 >
;; :empty
< 2 >
;; :empty
(if (not-empty coll) :full :empty) ; <3>
;; :empty | null | https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/Sequences/SequentialCollections/seqandsequence/2.clj | clojure | :empty
:empty
<3>
:empty | (def coll [])
< 1 >
< 2 >
|
95f1781fc1000201249693482c5d611ac967655fe915bb19335f80995a04316b | supki/envparse | Error.hs | -- | This module contains an extensible error infrastructure.
--
-- Each kind of errors gets a separate type class which encodes
-- a 'Prism' (roughly a getter and a constructor). The 'Reader's, then,
-- have the constraints for precisely the set of errors they can return.
module Env.Internal.Error
( Error(..)
, AsUnset(..)
, AsEmpty(..)
, AsUnread(..)
) where
| The type of errors returned by @envparse@ 's ' Reader 's . These fall into 3
-- categories:
--
-- * Variables that are unset in the environment.
-- * Variables whose value is empty.
-- * Variables whose value cannot be parsed.
data Error
= UnsetError
| EmptyError
| UnreadError String
deriving (Show, Eq)
-- | The class of types that contain and can be constructed from
-- the error returned from parsing unset variables.
class AsUnset e where
unset :: e
tryUnset :: e -> Maybe ()
instance AsUnset Error where
unset = UnsetError
tryUnset err =
case err of
UnsetError -> Just ()
_ -> Nothing
-- | The class of types that contain and can be constructed from
-- the error returned from parsing variables whose value is empty.
class AsEmpty e where
empty :: e
tryEmpty :: e -> Maybe ()
instance AsEmpty Error where
empty = EmptyError
tryEmpty err =
case err of
EmptyError -> Just ()
_ -> Nothing
-- | The class of types that contain and can be constructed from
-- the error returned from parsing variable whose value cannot be parsed.
class AsUnread e where
unread :: String -> e
tryUnread :: e -> Maybe String
instance AsUnread Error where
unread = UnreadError
tryUnread err =
case err of
UnreadError msg -> Just msg
_ -> Nothing
| null | https://raw.githubusercontent.com/supki/envparse/de5944fb09e9d941fafa35c0f05446af348e7b4d/src/Env/Internal/Error.hs | haskell | | This module contains an extensible error infrastructure.
Each kind of errors gets a separate type class which encodes
a 'Prism' (roughly a getter and a constructor). The 'Reader's, then,
have the constraints for precisely the set of errors they can return.
categories:
* Variables that are unset in the environment.
* Variables whose value is empty.
* Variables whose value cannot be parsed.
| The class of types that contain and can be constructed from
the error returned from parsing unset variables.
| The class of types that contain and can be constructed from
the error returned from parsing variables whose value is empty.
| The class of types that contain and can be constructed from
the error returned from parsing variable whose value cannot be parsed. | module Env.Internal.Error
( Error(..)
, AsUnset(..)
, AsEmpty(..)
, AsUnread(..)
) where
| The type of errors returned by @envparse@ 's ' Reader 's . These fall into 3
data Error
= UnsetError
| EmptyError
| UnreadError String
deriving (Show, Eq)
class AsUnset e where
unset :: e
tryUnset :: e -> Maybe ()
instance AsUnset Error where
unset = UnsetError
tryUnset err =
case err of
UnsetError -> Just ()
_ -> Nothing
class AsEmpty e where
empty :: e
tryEmpty :: e -> Maybe ()
instance AsEmpty Error where
empty = EmptyError
tryEmpty err =
case err of
EmptyError -> Just ()
_ -> Nothing
class AsUnread e where
unread :: String -> e
tryUnread :: e -> Maybe String
instance AsUnread Error where
unread = UnreadError
tryUnread err =
case err of
UnreadError msg -> Just msg
_ -> Nothing
|
6f23e028464cc95e82d66bcdd6b472081c335ed20810a41038b3c434335694b1 | iconnect/api-tools | Lens.hs | {-# LANGUAGE TemplateHaskell #-}
module Data.API.Tools.Lens
( lensTool
, binary
) where
import Data.API.Tools.Combinators
import Data.API.Tools.Datatypes
import Data.API.Types
import Control.Lens
-- | Tool to make lenses for fields in generated types.
lensTool :: APITool
lensTool = apiDataTypeTool $ mkTool $ \ ts an ->
if ok ts an then makeLenses $ rep_type_nm an else return []
where
-- Exclude newtypes if we are using smart constructors, because
-- the lens can be used to bypass the invariant
ok ts an | SpNewtype (SpecNewtype _ (Just _)) <- anSpec an = not (newtypeSmartConstructors ts)
| otherwise = True
$(makeLenses ''Binary)
| null | https://raw.githubusercontent.com/iconnect/api-tools/3d7b4dfadf82c7cb859b515d033447bd1d8ef6c6/src/Data/API/Tools/Lens.hs | haskell | # LANGUAGE TemplateHaskell #
| Tool to make lenses for fields in generated types.
Exclude newtypes if we are using smart constructors, because
the lens can be used to bypass the invariant | module Data.API.Tools.Lens
( lensTool
, binary
) where
import Data.API.Tools.Combinators
import Data.API.Tools.Datatypes
import Data.API.Types
import Control.Lens
lensTool :: APITool
lensTool = apiDataTypeTool $ mkTool $ \ ts an ->
if ok ts an then makeLenses $ rep_type_nm an else return []
where
ok ts an | SpNewtype (SpecNewtype _ (Just _)) <- anSpec an = not (newtypeSmartConstructors ts)
| otherwise = True
$(makeLenses ''Binary)
|
f7685781f173054f3f126bf8518cab96073fb0fcbdd87957618a663b48c6d537 | processone/esip | esip_dialog.erl | %%%----------------------------------------------------------------------
%%% File : esip_dialog.erl
Author : < >
%%% Purpose :
Created : 29 Dec 2010 by < >
%%%
%%%
Copyright ( C ) 2002 - 2022 ProcessOne , SARL . All Rights Reserved .
%%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%%% you may not use this file except in compliance with the License.
%%% You may obtain a copy of the License at
%%%
%%% -2.0
%%%
%%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%% See the License for the specific language governing permissions and
%%% limitations under the License.
%%%
%%%----------------------------------------------------------------------
-module(esip_dialog).
-behaviour(gen_server).
%% API
-export([start_link/0, open/4, id/2, close/1, lookup/1, prepare_request/2,
update_remote_seqnum/2, update_local_seqnum/2]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-include("esip.hrl").
-include("esip_lib.hrl").
-record(state, {}).
%%%===================================================================
%%% API
%%%===================================================================
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
id(Type, #sip{hdrs = Hdrs}) ->
CallID = esip:to_lower(esip:get_hdr('call-id', Hdrs)),
{_, _, ToParams} = esip:get_hdr('to', Hdrs),
{_, _, FromParams} = esip:get_hdr('from', Hdrs),
ToTag = esip:to_lower(esip:get_param(<<"tag">>, ToParams)),
FromTag = esip:to_lower(esip:get_param(<<"tag">>, FromParams)),
case Type of
uac ->
#dialog_id{'call-id' = CallID,
remote_tag = ToTag,
local_tag = FromTag};
uas ->
#dialog_id{'call-id' = CallID,
remote_tag = FromTag,
local_tag = ToTag}
end.
open(Req, #sip{type = response, hdrs = RespHdrs, status = Status}, uas, TU) ->
{_, _, ToParams} = esip:get_hdr('to', RespHdrs),
LocalTag = esip:get_param(<<"tag">>, ToParams),
open(Req, LocalTag, state(Status), TU);
open(#sip{type = request, uri = URI, hdrs = ReqHdrs},
#sip{type = response, hdrs = RespHdrs, status = Status}, uac, TU) ->
case esip:get_hdr('contact', RespHdrs) of
[{_, RemoteTarget, _}|_] ->
[#via{transport = Transport}|_] = esip:get_hdr('via', ReqHdrs),
Secure = (esip_transport:via_transport_to_atom(Transport) == tls)
and (URI#uri.scheme == <<"sips">>),
RouteSet = lists:foldl(
fun({_, U, _}, Acc) ->
[U|Acc]
end, [], esip:get_hdrs('record-route', RespHdrs)),
LocalSeqNum = esip:get_hdr('cseq', ReqHdrs),
CallID = esip:get_hdr('call-id', ReqHdrs),
{_, LocalURI, FromParams} = esip:get_hdr('from', ReqHdrs),
{_, RemoteURI, ToParams} = esip:get_hdr('to', RespHdrs),
LocalTag = esip:get_param(<<"tag">>, FromParams),
RemoteTag = esip:get_param(<<"tag">>, ToParams),
Dialog = #dialog{secure = Secure,
route_set = RouteSet,
remote_target = RemoteTarget,
local_seq_num = LocalSeqNum,
'call-id' = CallID,
local_tag = LocalTag,
remote_tag = RemoteTag,
remote_uri = RemoteURI,
local_uri = LocalURI,
state = state(Status)},
DialogID = #dialog_id{'call-id' = esip:to_lower(CallID),
remote_tag = esip:to_lower(RemoteTag),
local_tag = esip:to_lower(LocalTag)},
case call({open, DialogID, Dialog, TU}) of
ok ->
{ok, DialogID};
Err ->
Err
end;
_ ->
{error, no_contact_header}
end;
open(#sip{type = request, uri = URI, hdrs = Hdrs}, LocalTag, State, TU) ->
case esip:get_hdr('contact', Hdrs) of
[{_, RemoteTarget, _}|_] ->
[#via{transport = Transport}|_] = esip:get_hdr('via', Hdrs),
Secure = (esip_transport:via_transport_to_atom(Transport) == tls)
and (URI#uri.scheme == <<"sips">>),
RouteSet = [U || {_, U, _} <- esip:get_hdrs('record-route', Hdrs)],
RemoteSeqNum = esip:get_hdr('cseq', Hdrs),
CallID = esip:get_hdr('call-id', Hdrs),
{_, RemoteURI, FromParams} = esip:get_hdr('from', Hdrs),
{_, LocalURI, _} = esip:get_hdr('to', Hdrs),
RemoteTag = esip:get_param(<<"tag">>, FromParams),
Dialog = #dialog{secure = Secure,
route_set = RouteSet,
remote_target = RemoteTarget,
remote_seq_num = RemoteSeqNum,
'call-id' = CallID,
local_tag = LocalTag,
remote_tag = RemoteTag,
remote_uri = RemoteURI,
local_uri = LocalURI,
state = State},
DialogID = #dialog_id{'call-id' = esip:to_lower(CallID),
remote_tag = esip:to_lower(RemoteTag),
local_tag = esip:to_lower(LocalTag)},
case call({open, DialogID, Dialog, TU}) of
ok ->
{ok, DialogID};
Err ->
Err
end;
_ ->
{error, no_contact_header}
end.
prepare_request(DialogID,
#sip{type = request, method = Method, hdrs = Hdrs} = Req) ->
case lookup(DialogID) of
{ok, _TU, #dialog{secure = _Secure,
route_set = RouteSet,
local_seq_num = LocalSeqNum,
remote_target = RemoteTarget,
'call-id' = CallID,
remote_uri = RemoteURI,
local_uri = LocalURI}} ->
ToParams = if DialogID#dialog_id.remote_tag /= <<>> ->
[{<<"tag">>, DialogID#dialog_id.remote_tag}];
true ->
[]
end,
FromParams = if DialogID#dialog_id.local_tag /= <<>> ->
[{<<"tag">>, DialogID#dialog_id.local_tag}];
true ->
[]
end,
To = {<<>>, RemoteURI, ToParams},
From = {<<>>, LocalURI, FromParams},
CSeq = if is_integer(LocalSeqNum) ->
if Method /= <<"CANCEL">>, Method /= <<"ACK">> ->
LocalSeqNum + 1;
true ->
LocalSeqNum
end;
true ->
esip:make_cseq()
end,
update_local_seqnum(DialogID, CSeq),
{RequestURI, Routes} =
case RouteSet of
[] ->
{RemoteTarget, []};
[#uri{params = Params} = URI|URIs] ->
case esip:has_param(<<"lr">>, Params) of
true ->
{RemoteTarget,
[{'route', [{<<>>, U, []}]} || U <- RouteSet]};
false ->
{URI,
[{'route', [{<<>>, U, []}]} ||
U <- URIs ++ [RemoteTarget]]}
end
end,
{_, NewHdrs} = esip:split_hdrs(['from', 'to', 'cseq',
'route', 'call-id'], Hdrs),
Req#sip{uri = RequestURI,
hdrs = Routes ++ [{'to', To},
{'from', From},
{'cseq', CSeq},
{'call-id', CallID}|NewHdrs]};
_ ->
Req
end.
update_remote_seqnum(DialogID, CSeq) ->
gen_server:cast(?MODULE, {update_seqnum, remote, DialogID, CSeq}).
update_local_seqnum(DialogID, CSeq) ->
gen_server:cast(?MODULE, {update_seqnum, local, DialogID, CSeq}).
close(DialogID) ->
call({close, DialogID}).
lookup(DialogID) ->
call({lookup, DialogID}).
call(Msg) ->
case catch gen_server:call(?MODULE, Msg, 5000) of
{'EXIT', _} = Err ->
?ERROR_MSG("failed to comlete dialog operation:~n"
"** Msg: ~p~n"
"** Err: ~p",
[Msg, Err]),
{error, internal_server_error};
Res ->
Res
end.
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
init([]) ->
ets:new(esip_dialog, [named_table, public]),
{ok, #state{}}.
handle_call({open, DialogID, Dialog, TU}, _From, State) ->
ets:insert(esip_dialog, {DialogID, TU, Dialog}),
{reply, ok, State};
handle_call({close, DialogID}, _From, State) ->
ets:delete(esip_dialog, DialogID),
{reply, ok, State};
handle_call({lookup, DialogID}, _From, State) ->
case ets:lookup(esip_dialog, DialogID) of
[{_, TU, Dialog}] ->
{reply, {ok, TU, Dialog}, State};
_ ->
{reply, {error, enoent}, State}
end;
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast({update_seqnum, Type, DialogID, CSeq}, State) ->
case ets:lookup(esip_dialog, DialogID) of
[{_, TU, Dialog}] ->
NewDialog = case Type of
remote ->
Dialog#dialog{remote_seq_num = CSeq};
local ->
Dialog#dialog{local_seq_num = CSeq}
end,
ets:insert(esip_dialog, {DialogID, TU, NewDialog}),
{noreply, State};
_ ->
{noreply, State}
end;
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%===================================================================
Internal functions
%%%===================================================================
state(Status) when Status < 200 ->
early;
state(_) ->
confirmed.
| null | https://raw.githubusercontent.com/processone/esip/a2ee6c2506b86e937fc7bbf5e4a8fa1bffacc741/src/esip_dialog.erl | erlang | ----------------------------------------------------------------------
File : esip_dialog.erl
Purpose :
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
----------------------------------------------------------------------
API
gen_server callbacks
===================================================================
API
===================================================================
===================================================================
gen_server callbacks
===================================================================
===================================================================
=================================================================== | Author : < >
Created : 29 Dec 2010 by < >
Copyright ( C ) 2002 - 2022 ProcessOne , SARL . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(esip_dialog).
-behaviour(gen_server).
-export([start_link/0, open/4, id/2, close/1, lookup/1, prepare_request/2,
update_remote_seqnum/2, update_local_seqnum/2]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-include("esip.hrl").
-include("esip_lib.hrl").
-record(state, {}).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
id(Type, #sip{hdrs = Hdrs}) ->
CallID = esip:to_lower(esip:get_hdr('call-id', Hdrs)),
{_, _, ToParams} = esip:get_hdr('to', Hdrs),
{_, _, FromParams} = esip:get_hdr('from', Hdrs),
ToTag = esip:to_lower(esip:get_param(<<"tag">>, ToParams)),
FromTag = esip:to_lower(esip:get_param(<<"tag">>, FromParams)),
case Type of
uac ->
#dialog_id{'call-id' = CallID,
remote_tag = ToTag,
local_tag = FromTag};
uas ->
#dialog_id{'call-id' = CallID,
remote_tag = FromTag,
local_tag = ToTag}
end.
open(Req, #sip{type = response, hdrs = RespHdrs, status = Status}, uas, TU) ->
{_, _, ToParams} = esip:get_hdr('to', RespHdrs),
LocalTag = esip:get_param(<<"tag">>, ToParams),
open(Req, LocalTag, state(Status), TU);
open(#sip{type = request, uri = URI, hdrs = ReqHdrs},
#sip{type = response, hdrs = RespHdrs, status = Status}, uac, TU) ->
case esip:get_hdr('contact', RespHdrs) of
[{_, RemoteTarget, _}|_] ->
[#via{transport = Transport}|_] = esip:get_hdr('via', ReqHdrs),
Secure = (esip_transport:via_transport_to_atom(Transport) == tls)
and (URI#uri.scheme == <<"sips">>),
RouteSet = lists:foldl(
fun({_, U, _}, Acc) ->
[U|Acc]
end, [], esip:get_hdrs('record-route', RespHdrs)),
LocalSeqNum = esip:get_hdr('cseq', ReqHdrs),
CallID = esip:get_hdr('call-id', ReqHdrs),
{_, LocalURI, FromParams} = esip:get_hdr('from', ReqHdrs),
{_, RemoteURI, ToParams} = esip:get_hdr('to', RespHdrs),
LocalTag = esip:get_param(<<"tag">>, FromParams),
RemoteTag = esip:get_param(<<"tag">>, ToParams),
Dialog = #dialog{secure = Secure,
route_set = RouteSet,
remote_target = RemoteTarget,
local_seq_num = LocalSeqNum,
'call-id' = CallID,
local_tag = LocalTag,
remote_tag = RemoteTag,
remote_uri = RemoteURI,
local_uri = LocalURI,
state = state(Status)},
DialogID = #dialog_id{'call-id' = esip:to_lower(CallID),
remote_tag = esip:to_lower(RemoteTag),
local_tag = esip:to_lower(LocalTag)},
case call({open, DialogID, Dialog, TU}) of
ok ->
{ok, DialogID};
Err ->
Err
end;
_ ->
{error, no_contact_header}
end;
open(#sip{type = request, uri = URI, hdrs = Hdrs}, LocalTag, State, TU) ->
case esip:get_hdr('contact', Hdrs) of
[{_, RemoteTarget, _}|_] ->
[#via{transport = Transport}|_] = esip:get_hdr('via', Hdrs),
Secure = (esip_transport:via_transport_to_atom(Transport) == tls)
and (URI#uri.scheme == <<"sips">>),
RouteSet = [U || {_, U, _} <- esip:get_hdrs('record-route', Hdrs)],
RemoteSeqNum = esip:get_hdr('cseq', Hdrs),
CallID = esip:get_hdr('call-id', Hdrs),
{_, RemoteURI, FromParams} = esip:get_hdr('from', Hdrs),
{_, LocalURI, _} = esip:get_hdr('to', Hdrs),
RemoteTag = esip:get_param(<<"tag">>, FromParams),
Dialog = #dialog{secure = Secure,
route_set = RouteSet,
remote_target = RemoteTarget,
remote_seq_num = RemoteSeqNum,
'call-id' = CallID,
local_tag = LocalTag,
remote_tag = RemoteTag,
remote_uri = RemoteURI,
local_uri = LocalURI,
state = State},
DialogID = #dialog_id{'call-id' = esip:to_lower(CallID),
remote_tag = esip:to_lower(RemoteTag),
local_tag = esip:to_lower(LocalTag)},
case call({open, DialogID, Dialog, TU}) of
ok ->
{ok, DialogID};
Err ->
Err
end;
_ ->
{error, no_contact_header}
end.
prepare_request(DialogID,
#sip{type = request, method = Method, hdrs = Hdrs} = Req) ->
case lookup(DialogID) of
{ok, _TU, #dialog{secure = _Secure,
route_set = RouteSet,
local_seq_num = LocalSeqNum,
remote_target = RemoteTarget,
'call-id' = CallID,
remote_uri = RemoteURI,
local_uri = LocalURI}} ->
ToParams = if DialogID#dialog_id.remote_tag /= <<>> ->
[{<<"tag">>, DialogID#dialog_id.remote_tag}];
true ->
[]
end,
FromParams = if DialogID#dialog_id.local_tag /= <<>> ->
[{<<"tag">>, DialogID#dialog_id.local_tag}];
true ->
[]
end,
To = {<<>>, RemoteURI, ToParams},
From = {<<>>, LocalURI, FromParams},
CSeq = if is_integer(LocalSeqNum) ->
if Method /= <<"CANCEL">>, Method /= <<"ACK">> ->
LocalSeqNum + 1;
true ->
LocalSeqNum
end;
true ->
esip:make_cseq()
end,
update_local_seqnum(DialogID, CSeq),
{RequestURI, Routes} =
case RouteSet of
[] ->
{RemoteTarget, []};
[#uri{params = Params} = URI|URIs] ->
case esip:has_param(<<"lr">>, Params) of
true ->
{RemoteTarget,
[{'route', [{<<>>, U, []}]} || U <- RouteSet]};
false ->
{URI,
[{'route', [{<<>>, U, []}]} ||
U <- URIs ++ [RemoteTarget]]}
end
end,
{_, NewHdrs} = esip:split_hdrs(['from', 'to', 'cseq',
'route', 'call-id'], Hdrs),
Req#sip{uri = RequestURI,
hdrs = Routes ++ [{'to', To},
{'from', From},
{'cseq', CSeq},
{'call-id', CallID}|NewHdrs]};
_ ->
Req
end.
update_remote_seqnum(DialogID, CSeq) ->
gen_server:cast(?MODULE, {update_seqnum, remote, DialogID, CSeq}).
update_local_seqnum(DialogID, CSeq) ->
gen_server:cast(?MODULE, {update_seqnum, local, DialogID, CSeq}).
close(DialogID) ->
call({close, DialogID}).
lookup(DialogID) ->
call({lookup, DialogID}).
call(Msg) ->
case catch gen_server:call(?MODULE, Msg, 5000) of
{'EXIT', _} = Err ->
?ERROR_MSG("failed to comlete dialog operation:~n"
"** Msg: ~p~n"
"** Err: ~p",
[Msg, Err]),
{error, internal_server_error};
Res ->
Res
end.
init([]) ->
ets:new(esip_dialog, [named_table, public]),
{ok, #state{}}.
handle_call({open, DialogID, Dialog, TU}, _From, State) ->
ets:insert(esip_dialog, {DialogID, TU, Dialog}),
{reply, ok, State};
handle_call({close, DialogID}, _From, State) ->
ets:delete(esip_dialog, DialogID),
{reply, ok, State};
handle_call({lookup, DialogID}, _From, State) ->
case ets:lookup(esip_dialog, DialogID) of
[{_, TU, Dialog}] ->
{reply, {ok, TU, Dialog}, State};
_ ->
{reply, {error, enoent}, State}
end;
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast({update_seqnum, Type, DialogID, CSeq}, State) ->
case ets:lookup(esip_dialog, DialogID) of
[{_, TU, Dialog}] ->
NewDialog = case Type of
remote ->
Dialog#dialog{remote_seq_num = CSeq};
local ->
Dialog#dialog{local_seq_num = CSeq}
end,
ets:insert(esip_dialog, {DialogID, TU, NewDialog}),
{noreply, State};
_ ->
{noreply, State}
end;
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
state(Status) when Status < 200 ->
early;
state(_) ->
confirmed.
|
32f8a1db61e3b1f76be4994c9c4b233fac632b6875f1963d41782982a398ba67 | gedge-platform/gedge-platform | jose_jwa_curve448.erl | -*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*-
%% vim: ts=4 sw=4 ft=erlang noet
%%%-------------------------------------------------------------------
@author < >
2014 - 2016 ,
%%% @doc
%%%
%%% @end
Created : 07 Jan 2016 by < >
%%%-------------------------------------------------------------------
-module(jose_jwa_curve448).
-behaviour(jose_curve448).
jose_curve448 callbacks
-export([eddsa_keypair/0]).
-export([eddsa_keypair/1]).
-export([eddsa_secret_to_public/1]).
-export([ed448_sign/2]).
-export([ed448_sign/3]).
-export([ed448_verify/3]).
-export([ed448_verify/4]).
-export([ed448ph_sign/2]).
-export([ed448ph_sign/3]).
-export([ed448ph_verify/3]).
-export([ed448ph_verify/4]).
-export([x448_keypair/0]).
-export([x448_keypair/1]).
-export([x448_secret_to_public/1]).
-export([x448_shared_secret/2]).
%%====================================================================
jose_curve448 callbacks
%%====================================================================
EdDSA
eddsa_keypair() ->
jose_jwa_ed448:keypair().
eddsa_keypair(Seed)
when is_binary(Seed) ->
jose_jwa_ed448:keypair(Seed).
eddsa_secret_to_public(SecretKey)
when is_binary(SecretKey) ->
jose_jwa_ed448:secret_to_pk(SecretKey).
% Ed448
ed448_sign(Message, SecretKey)
when is_binary(Message)
andalso is_binary(SecretKey) ->
jose_jwa_ed448:sign(Message, SecretKey).
ed448_sign(Message, SecretKey, Context)
when is_binary(Message)
andalso is_binary(SecretKey)
andalso is_binary(Context) ->
jose_jwa_ed448:sign(Message, SecretKey, Context).
ed448_verify(Signature, Message, PublicKey)
when is_binary(Signature)
andalso is_binary(Message)
andalso is_binary(PublicKey) ->
try
jose_jwa_ed448:verify(Signature, Message, PublicKey)
catch
_:_ ->
false
end.
ed448_verify(Signature, Message, PublicKey, Context)
when is_binary(Signature)
andalso is_binary(Message)
andalso is_binary(PublicKey)
andalso is_binary(Context) ->
try
jose_jwa_ed448:verify(Signature, Message, PublicKey, Context)
catch
_:_ ->
false
end.
% Ed448ph
ed448ph_sign(Message, SecretKey)
when is_binary(Message)
andalso is_binary(SecretKey) ->
jose_jwa_ed448:sign_with_prehash(Message, SecretKey).
ed448ph_sign(Message, SecretKey, Context)
when is_binary(Message)
andalso is_binary(SecretKey)
andalso is_binary(Context) ->
jose_jwa_ed448:sign_with_prehash(Message, SecretKey, Context).
ed448ph_verify(Signature, Message, PublicKey)
when is_binary(Signature)
andalso is_binary(Message)
andalso is_binary(PublicKey) ->
try
jose_jwa_ed448:verify_with_prehash(Signature, Message, PublicKey)
catch
_:_ ->
false
end.
ed448ph_verify(Signature, Message, PublicKey, Context)
when is_binary(Signature)
andalso is_binary(Message)
andalso is_binary(PublicKey)
andalso is_binary(Context) ->
try
jose_jwa_ed448:verify_with_prehash(Signature, Message, PublicKey, Context)
catch
_:_ ->
false
end.
X448
x448_keypair() ->
jose_jwa_x448:keypair().
x448_keypair(Seed)
when is_binary(Seed) ->
jose_jwa_x448:keypair(Seed).
x448_secret_to_public(SecretKey)
when is_binary(SecretKey) ->
jose_jwa_x448:sk_to_pk(SecretKey).
x448_shared_secret(MySecretKey, YourPublicKey)
when is_binary(MySecretKey)
andalso is_binary(YourPublicKey) ->
jose_jwa_x448:x448(MySecretKey, YourPublicKey).
| null | https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/jose/src/jwa/jose_jwa_curve448.erl | erlang | vim: ts=4 sw=4 ft=erlang noet
-------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
====================================================================
====================================================================
Ed448
Ed448ph | -*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*-
@author < >
2014 - 2016 ,
Created : 07 Jan 2016 by < >
-module(jose_jwa_curve448).
-behaviour(jose_curve448).
jose_curve448 callbacks
-export([eddsa_keypair/0]).
-export([eddsa_keypair/1]).
-export([eddsa_secret_to_public/1]).
-export([ed448_sign/2]).
-export([ed448_sign/3]).
-export([ed448_verify/3]).
-export([ed448_verify/4]).
-export([ed448ph_sign/2]).
-export([ed448ph_sign/3]).
-export([ed448ph_verify/3]).
-export([ed448ph_verify/4]).
-export([x448_keypair/0]).
-export([x448_keypair/1]).
-export([x448_secret_to_public/1]).
-export([x448_shared_secret/2]).
jose_curve448 callbacks
EdDSA
eddsa_keypair() ->
jose_jwa_ed448:keypair().
eddsa_keypair(Seed)
when is_binary(Seed) ->
jose_jwa_ed448:keypair(Seed).
eddsa_secret_to_public(SecretKey)
when is_binary(SecretKey) ->
jose_jwa_ed448:secret_to_pk(SecretKey).
ed448_sign(Message, SecretKey)
when is_binary(Message)
andalso is_binary(SecretKey) ->
jose_jwa_ed448:sign(Message, SecretKey).
ed448_sign(Message, SecretKey, Context)
when is_binary(Message)
andalso is_binary(SecretKey)
andalso is_binary(Context) ->
jose_jwa_ed448:sign(Message, SecretKey, Context).
ed448_verify(Signature, Message, PublicKey)
when is_binary(Signature)
andalso is_binary(Message)
andalso is_binary(PublicKey) ->
try
jose_jwa_ed448:verify(Signature, Message, PublicKey)
catch
_:_ ->
false
end.
ed448_verify(Signature, Message, PublicKey, Context)
when is_binary(Signature)
andalso is_binary(Message)
andalso is_binary(PublicKey)
andalso is_binary(Context) ->
try
jose_jwa_ed448:verify(Signature, Message, PublicKey, Context)
catch
_:_ ->
false
end.
ed448ph_sign(Message, SecretKey)
when is_binary(Message)
andalso is_binary(SecretKey) ->
jose_jwa_ed448:sign_with_prehash(Message, SecretKey).
ed448ph_sign(Message, SecretKey, Context)
when is_binary(Message)
andalso is_binary(SecretKey)
andalso is_binary(Context) ->
jose_jwa_ed448:sign_with_prehash(Message, SecretKey, Context).
ed448ph_verify(Signature, Message, PublicKey)
when is_binary(Signature)
andalso is_binary(Message)
andalso is_binary(PublicKey) ->
try
jose_jwa_ed448:verify_with_prehash(Signature, Message, PublicKey)
catch
_:_ ->
false
end.
ed448ph_verify(Signature, Message, PublicKey, Context)
when is_binary(Signature)
andalso is_binary(Message)
andalso is_binary(PublicKey)
andalso is_binary(Context) ->
try
jose_jwa_ed448:verify_with_prehash(Signature, Message, PublicKey, Context)
catch
_:_ ->
false
end.
X448
x448_keypair() ->
jose_jwa_x448:keypair().
x448_keypair(Seed)
when is_binary(Seed) ->
jose_jwa_x448:keypair(Seed).
x448_secret_to_public(SecretKey)
when is_binary(SecretKey) ->
jose_jwa_x448:sk_to_pk(SecretKey).
x448_shared_secret(MySecretKey, YourPublicKey)
when is_binary(MySecretKey)
andalso is_binary(YourPublicKey) ->
jose_jwa_x448:x448(MySecretKey, YourPublicKey).
|
226e818195b0392d59aa9ee09467a6f2234658f05045deebce90b09efa01e4fb | dgtized/shimmers | wave_function_collapse.cljs | (ns shimmers.sketches.wave-function-collapse
(:require
[cljs.core.async :as async :include-macros true]
[shimmers.algorithm.wave-function-collapse :as wfc]
[shimmers.common.sequence :as cs]
[shimmers.common.svg :as csvg]
[shimmers.common.ui.controls :as ctrl]
[shimmers.common.ui.debug :as debug]
[shimmers.sketch :as sketch :include-macros true]
[thi.ng.geom.core :as g]
[thi.ng.geom.rect :as rect]
[thi.ng.geom.vector :as gv]
[thi.ng.math.core :as tm])
(:require-macros [cljs.core.async.macros :refer [go-loop]]))
(def width 900)
(def height 600)
(defn rv [x y]
(gv/vec2 (* width x) (* height y)))
(def color-map
{"A" "#4444dd"
"B" "#cdcd00"
"C" "#228b22"})
(defn cancel-active! [state]
(when-let [cancel (:cancel @state)]
(async/close! cancel)
(swap! state assoc
:message nil
:cancel nil)))
(defn set-cell! [state loc value]
(cancel-active! state)
(let [{:keys [wfc-state]} @state
{:keys [tiles grid]} wfc-state
;; reset won't work if it's the only current legal tile
;; maybe need to track "dependents" and unset those too?
values (if (= (count (get grid loc)) 1)
(set (range (count tiles)))
#{value})
{:keys [changes] :as wfc-state'}
(wfc/set-cell wfc-state loc values)]
(swap! state assoc
:highlight (conj changes loc)
:wfc-state wfc-state')))
(def subdivisions {1 {:cols 1 :rows 1}
2 {:cols 1 :rows 2}
3 {:cols 3 :rows 1}
4 {:cols 2 :rows 2}
5 {:cols 2 :rows 3}
6 {:cols 3 :rows 2}
7 {:cols 3 :rows 3}
8 {:cols 3 :rows 3}
9 {:cols 3 :rows 3}
10 {:cols 4 :rows 3}
11 {:cols 4 :rows 3}
12 {:cols 4 :rows 3}})
(defn cell-tile [value piece]
(if (string? value)
(vary-meta piece assoc :fill (get color-map value))
(->> (g/subdivide piece {:cols (count (first value)) :rows (count value)})
(map (fn [pixel cell]
(vary-meta cell assoc :fill (get color-map pixel)))
(seq (apply str value))))))
(defn cell-subdivisions
[cell loc values {:keys [tiles on-click]}]
(let [options (count values)
divisions (get subdivisions options
(let [s (Math/sqrt options)]
{:cols (Math/ceil s) :rows (Math/ceil s)}))]
(->> (g/subdivide cell divisions)
(map (fn [value piece]
(let [tile (if (integer? value)
(nth tiles value)
value)]
(csvg/group (cond-> {:class "wfc-cell"}
on-click
(assoc :on-click (partial on-click loc value)))
(cell-tile tile piece))))
values))))
(def rule-a
(wfc/str->matrix
"AAA
ABA
AAA"))
(def rule-b
(wfc/str->matrix
"AAAAA
ABBBA
ABCBA
ABBBA
AAAAA"))
(def rule-c
(wfc/str->matrix
"AAAAAA
ABBBBA
ABCCBA
ABCCBA
ABBBBA
AAAAAA"))
(def rule-d
(wfc/str->matrix
"AAAAAAAA
AAAAAAAA
AABBBBAA
AABCCBAA
AABCCBAA
AABBBBAA
AAAAAAAA
AAAAAAAA"))
(def rule-e
(wfc/str->matrix
"AAAAAAAAA
AAABBBAAA
AABBCBBAA
AABCCCBBB
AABCCCCCC
AABCCCBBB
AABBBBBAA
AAAAAAAAA
AAAAAAAAA"))
(defn scene
[[width height]
grid
& {:keys [highlight tiles]
:or {highlight #{} tiles []}
:as args}]
(let [[cols rows] (:dims grid)
w (/ width cols)
h (/ height rows)
n-tiles (count tiles)]
(csvg/svg {:width width
:height height
:stroke "none"
:fill "none"}
(for [j (range rows)
i (range cols)]
(let [loc (gv/vec2 i j)
values (get grid loc)
cell (rect/rect (* w i) (* h j) w h)
changed? (contains? highlight loc)
options (count values)]
(csvg/group {:class "wfc-tile"
:stroke (if changed? "red" "none")}
(if (<= options 16)
(cell-subdivisions cell loc values args)
(vary-meta cell assoc :fill
(csvg/hsl 0 0 (/ options n-tiles))))))))))
(defn generate-tileset [matrix rotations]
(let [directions wfc/cardinal-directions
pattern (wfc/matrix->grid matrix directions)
tiles ((if rotations wfc/pattern->rotated-tiles
wfc/pattern->oriented-tiles)
matrix 3)
rules (wfc/adjacency-rules tiles)]
(wfc/build-state
{:dims [30 20]
:directions directions
:pattern pattern
:tiles tiles
:rules rules})))
(defn generate-cellset [matrix]
(let [directions wfc/directions-8
pattern (wfc/matrix->grid matrix directions)
rules (wfc/rules pattern)
tiles (vec (wfc/all-tiles rules))]
(wfc/build-state
{:dims [30 20]
:directions directions
:pattern pattern
:tiles tiles
:rules rules})))
(def modes {:cells generate-cellset
:tileset generate-tileset})
(defn init-state [mode matrix rotations]
{:highlight #{}
:cancel nil
:message nil
:mode mode
:rotations rotations
:show-rules false
:wfc-state ((get modes mode) matrix rotations)})
(defn reset [state]
(cancel-active! state)
(let [{:keys [mode rotations] {:keys [pattern]} :wfc-state} @state]
(reset! state (init-state mode (wfc/grid->matrix pattern) rotations))))
(defn solve-step [state]
(try
(let [{:keys [changes] :as wfc-state} (wfc/solve-one (:wfc-state @state))]
(swap! state assoc
:message nil
:wfc-state wfc-state
:highlight changes)
true)
(catch :default e
(cancel-active! state)
(swap! state assoc :message e)
false)))
(defn solve [state]
(if-let [cancel (:cancel @state)]
(async/close! cancel)
(let [new-cancel (async/chan 1)]
(swap! state assoc :cancel new-cancel)
(go-loop [state state]
(let [[_ c] (async/alts! [new-cancel (async/timeout 1)])]
(if (and (not= c new-cancel) (solve-step state))
(recur state)
(swap! state assoc :cancel nil)))))))
(defn action-dispatch [state event]
(case event
:reset
(fn [] (reset state))
:solve
(fn [] (solve state))
:solve-one
(fn []
(cancel-active! state)
(solve-step state))
:pattern-edit-click
(fn [loc _]
(cancel-active! state)
(swap! state update-in [:wfc-state :pattern loc] (partial cs/cycle-next ["A" "B" "C"]))
(reset state))
:pattern-clear
(fn []
(cancel-active! state)
(swap! state update-in [:wfc-state :pattern]
(fn [{[cols rows] :dims :as pattern}]
(merge pattern
(into {}
(for [i (range cols)
j (range rows)]
{(gv/vec2 i j) "A"})))))
(reset state))
:pattern-reset
(fn []
(cancel-active! state)
(swap! state assoc-in [:wfc-state :pattern]
(wfc/matrix->grid rule-e wfc/cardinal-directions))
(reset state))
:toggle-rotations
(fn []
(cancel-active! state)
(swap! state update-in [:rotations] not)
(reset state))
:toggle-show-rules
(fn []
(swap! state update :show-rules not))))
(defn svg-tile [tile]
(csvg/svg {:width 20
:height 20
:stroke "none"
:fill "none"}
[(cell-tile tile (rect/rect 20))]))
(def direction-name
(zipmap wfc/directions-8
[" N " " E " " S " " W "
" NE " " SE " " SW " " NW "]))
(defn svg-adjacency [tile direction other]
(let [d 20
[x y] direction
orient (cond (= 0 y) :horizontal
(= 0 x) :vertical
:else :diagonal)
[w h] (case orient
:horizontal [(* 2 d) d]
:vertical [d (* 2 d)]
:diagonal [(* 2 d) (* 2 d)])
base (case orient
:horizontal (gv/vec2 (if (> x 0) 0 d) 0)
:vertical (gv/vec2 0 (if (> y 0) 0 d))
:diagonal (gv/vec2 (if (> x 0) 0 d) (if (> y 0) 0 d)))
r1 (g/translate (rect/rect d) base)
r2 (g/translate
(rect/rect d)
(tm/+ base (tm/* direction d)))]
(csvg/svg {:width w
:height h
:stroke "none"
:fill "none"}
[[:title (get direction-name direction)]
(cell-tile tile r1)
(cell-tile other r2)
(vary-meta r2 assoc :opacity 0.25 :fill "white")])))
(defn tile-set [tiles]
[:div
[:h4 (str "Tiles (" (count tiles) ")")]
[:div {:style {:column-count 12}}
(for [[idx tile] (map-indexed vector tiles)]
[:div {:key (str "ts-" idx)}
(svg-tile tile)])]])
(defn rule-set [rules tiles show-rules emit]
[:div
[:h4 (str "Rules (" (count rules) ") ")
[:button.link {:on-click (emit :toggle-show-rules)}
(if show-rules "(hide)" "(show)")]]
(when show-rules
[:div {:style {:column-count 8}}
(let [simplified (sort-by first (group-by identity rules))
numbered (some (fn [[_ e]] (> (count e) 1)) simplified)]
(for [[idx [[tile-idx dir other-idx] examples]] (map-indexed vector simplified)]
[:div {:key (str "rule-" idx)}
(when numbered
[:span (count examples) ": "])
(svg-adjacency (nth tiles tile-idx) dir (nth tiles other-idx))]))])])
(defn display-patterns [state emit]
(let [{:keys [wfc-state mode show-rules rotations]} state
{:keys [pattern tiles rules]} wfc-state]
[:div
[:div.flexcols
[:div
[:h4 "Pattern"]
(scene [150 150] pattern :on-click (emit :pattern-edit-click))]
(when (= mode :tileset)
[:div
[:h4 "Settings"]
[:div [:button {:on-click (emit :pattern-clear)} "Clear Pattern"]]
[:div [:button {:on-click (emit :pattern-reset)} "Reset Pattern"]]
[:div.label-set {:key "Include Rotations"}
[:input {:type "checkbox" :checked rotations
:on-change (emit :toggle-rotations)}]
[:label "Include Rotations"]]])
[tile-set tiles]]
[rule-set rules tiles show-rules emit]]))
(defn page []
(let [state (ctrl/state (init-state :tileset rule-e true))
emit (partial action-dispatch state)]
(fn []
(let [{:keys [wfc-state highlight cancel message]} @state
{:keys [grid tiles]} wfc-state
pattern-set (select-keys @state [:wfc-state :mode :show-rules :rotations])]
[:div
[:div.canvas-frame [scene [width height] grid
:tiles tiles
:highlight highlight
:on-click (partial set-cell! state)]]
[:div#interface.contained
[:div.flexcols
[:div [ctrl/change-mode state (keys modes) {:on-change (emit :reset)}]
(when message
[:div {:style {:color "red"}}
(debug/pre-edn message)])]
[:button.generate {:on-click (emit :reset)} "Reset"]
[:button.generate {:on-click (emit :solve-one)} "Solve One"]
[:button.generate {:on-click (emit :solve)} (if cancel "Stop" "Solve")]]
[:p.readable
"Click on a cell above to collapse it to a specific tile, or to
expand it to the set of all legal tiles. Click on a cell in the pattern
below to derive new tiles and rules."]
[:p.readable "Does not yet support backtracking."]
[display-patterns pattern-set emit]]]))))
(sketch/definition wave-function-collapse
{:created-at "2022-04-26"
:type :svg
:tags #{}}
(ctrl/mount page "sketch-host"))
| null | https://raw.githubusercontent.com/dgtized/shimmers/f096c20d7ebcb9796c7830efcd7e3f24767a46db/src/shimmers/sketches/wave_function_collapse.cljs | clojure | reset won't work if it's the only current legal tile
maybe need to track "dependents" and unset those too? | (ns shimmers.sketches.wave-function-collapse
(:require
[cljs.core.async :as async :include-macros true]
[shimmers.algorithm.wave-function-collapse :as wfc]
[shimmers.common.sequence :as cs]
[shimmers.common.svg :as csvg]
[shimmers.common.ui.controls :as ctrl]
[shimmers.common.ui.debug :as debug]
[shimmers.sketch :as sketch :include-macros true]
[thi.ng.geom.core :as g]
[thi.ng.geom.rect :as rect]
[thi.ng.geom.vector :as gv]
[thi.ng.math.core :as tm])
(:require-macros [cljs.core.async.macros :refer [go-loop]]))
(def width 900)
(def height 600)
(defn rv [x y]
(gv/vec2 (* width x) (* height y)))
(def color-map
{"A" "#4444dd"
"B" "#cdcd00"
"C" "#228b22"})
(defn cancel-active! [state]
(when-let [cancel (:cancel @state)]
(async/close! cancel)
(swap! state assoc
:message nil
:cancel nil)))
(defn set-cell! [state loc value]
(cancel-active! state)
(let [{:keys [wfc-state]} @state
{:keys [tiles grid]} wfc-state
values (if (= (count (get grid loc)) 1)
(set (range (count tiles)))
#{value})
{:keys [changes] :as wfc-state'}
(wfc/set-cell wfc-state loc values)]
(swap! state assoc
:highlight (conj changes loc)
:wfc-state wfc-state')))
(def subdivisions {1 {:cols 1 :rows 1}
2 {:cols 1 :rows 2}
3 {:cols 3 :rows 1}
4 {:cols 2 :rows 2}
5 {:cols 2 :rows 3}
6 {:cols 3 :rows 2}
7 {:cols 3 :rows 3}
8 {:cols 3 :rows 3}
9 {:cols 3 :rows 3}
10 {:cols 4 :rows 3}
11 {:cols 4 :rows 3}
12 {:cols 4 :rows 3}})
(defn cell-tile [value piece]
(if (string? value)
(vary-meta piece assoc :fill (get color-map value))
(->> (g/subdivide piece {:cols (count (first value)) :rows (count value)})
(map (fn [pixel cell]
(vary-meta cell assoc :fill (get color-map pixel)))
(seq (apply str value))))))
(defn cell-subdivisions
[cell loc values {:keys [tiles on-click]}]
(let [options (count values)
divisions (get subdivisions options
(let [s (Math/sqrt options)]
{:cols (Math/ceil s) :rows (Math/ceil s)}))]
(->> (g/subdivide cell divisions)
(map (fn [value piece]
(let [tile (if (integer? value)
(nth tiles value)
value)]
(csvg/group (cond-> {:class "wfc-cell"}
on-click
(assoc :on-click (partial on-click loc value)))
(cell-tile tile piece))))
values))))
(def rule-a
(wfc/str->matrix
"AAA
ABA
AAA"))
(def rule-b
(wfc/str->matrix
"AAAAA
ABBBA
ABCBA
ABBBA
AAAAA"))
(def rule-c
(wfc/str->matrix
"AAAAAA
ABBBBA
ABCCBA
ABCCBA
ABBBBA
AAAAAA"))
(def rule-d
(wfc/str->matrix
"AAAAAAAA
AAAAAAAA
AABBBBAA
AABCCBAA
AABCCBAA
AABBBBAA
AAAAAAAA
AAAAAAAA"))
(def rule-e
(wfc/str->matrix
"AAAAAAAAA
AAABBBAAA
AABBCBBAA
AABCCCBBB
AABCCCCCC
AABCCCBBB
AABBBBBAA
AAAAAAAAA
AAAAAAAAA"))
(defn scene
[[width height]
grid
& {:keys [highlight tiles]
:or {highlight #{} tiles []}
:as args}]
(let [[cols rows] (:dims grid)
w (/ width cols)
h (/ height rows)
n-tiles (count tiles)]
(csvg/svg {:width width
:height height
:stroke "none"
:fill "none"}
(for [j (range rows)
i (range cols)]
(let [loc (gv/vec2 i j)
values (get grid loc)
cell (rect/rect (* w i) (* h j) w h)
changed? (contains? highlight loc)
options (count values)]
(csvg/group {:class "wfc-tile"
:stroke (if changed? "red" "none")}
(if (<= options 16)
(cell-subdivisions cell loc values args)
(vary-meta cell assoc :fill
(csvg/hsl 0 0 (/ options n-tiles))))))))))
(defn generate-tileset [matrix rotations]
(let [directions wfc/cardinal-directions
pattern (wfc/matrix->grid matrix directions)
tiles ((if rotations wfc/pattern->rotated-tiles
wfc/pattern->oriented-tiles)
matrix 3)
rules (wfc/adjacency-rules tiles)]
(wfc/build-state
{:dims [30 20]
:directions directions
:pattern pattern
:tiles tiles
:rules rules})))
(defn generate-cellset [matrix]
(let [directions wfc/directions-8
pattern (wfc/matrix->grid matrix directions)
rules (wfc/rules pattern)
tiles (vec (wfc/all-tiles rules))]
(wfc/build-state
{:dims [30 20]
:directions directions
:pattern pattern
:tiles tiles
:rules rules})))
(def modes {:cells generate-cellset
:tileset generate-tileset})
(defn init-state [mode matrix rotations]
{:highlight #{}
:cancel nil
:message nil
:mode mode
:rotations rotations
:show-rules false
:wfc-state ((get modes mode) matrix rotations)})
(defn reset [state]
(cancel-active! state)
(let [{:keys [mode rotations] {:keys [pattern]} :wfc-state} @state]
(reset! state (init-state mode (wfc/grid->matrix pattern) rotations))))
(defn solve-step [state]
(try
(let [{:keys [changes] :as wfc-state} (wfc/solve-one (:wfc-state @state))]
(swap! state assoc
:message nil
:wfc-state wfc-state
:highlight changes)
true)
(catch :default e
(cancel-active! state)
(swap! state assoc :message e)
false)))
(defn solve [state]
(if-let [cancel (:cancel @state)]
(async/close! cancel)
(let [new-cancel (async/chan 1)]
(swap! state assoc :cancel new-cancel)
(go-loop [state state]
(let [[_ c] (async/alts! [new-cancel (async/timeout 1)])]
(if (and (not= c new-cancel) (solve-step state))
(recur state)
(swap! state assoc :cancel nil)))))))
(defn action-dispatch [state event]
(case event
:reset
(fn [] (reset state))
:solve
(fn [] (solve state))
:solve-one
(fn []
(cancel-active! state)
(solve-step state))
:pattern-edit-click
(fn [loc _]
(cancel-active! state)
(swap! state update-in [:wfc-state :pattern loc] (partial cs/cycle-next ["A" "B" "C"]))
(reset state))
:pattern-clear
(fn []
(cancel-active! state)
(swap! state update-in [:wfc-state :pattern]
(fn [{[cols rows] :dims :as pattern}]
(merge pattern
(into {}
(for [i (range cols)
j (range rows)]
{(gv/vec2 i j) "A"})))))
(reset state))
:pattern-reset
(fn []
(cancel-active! state)
(swap! state assoc-in [:wfc-state :pattern]
(wfc/matrix->grid rule-e wfc/cardinal-directions))
(reset state))
:toggle-rotations
(fn []
(cancel-active! state)
(swap! state update-in [:rotations] not)
(reset state))
:toggle-show-rules
(fn []
(swap! state update :show-rules not))))
(defn svg-tile [tile]
(csvg/svg {:width 20
:height 20
:stroke "none"
:fill "none"}
[(cell-tile tile (rect/rect 20))]))
(def direction-name
(zipmap wfc/directions-8
[" N " " E " " S " " W "
" NE " " SE " " SW " " NW "]))
(defn svg-adjacency [tile direction other]
(let [d 20
[x y] direction
orient (cond (= 0 y) :horizontal
(= 0 x) :vertical
:else :diagonal)
[w h] (case orient
:horizontal [(* 2 d) d]
:vertical [d (* 2 d)]
:diagonal [(* 2 d) (* 2 d)])
base (case orient
:horizontal (gv/vec2 (if (> x 0) 0 d) 0)
:vertical (gv/vec2 0 (if (> y 0) 0 d))
:diagonal (gv/vec2 (if (> x 0) 0 d) (if (> y 0) 0 d)))
r1 (g/translate (rect/rect d) base)
r2 (g/translate
(rect/rect d)
(tm/+ base (tm/* direction d)))]
(csvg/svg {:width w
:height h
:stroke "none"
:fill "none"}
[[:title (get direction-name direction)]
(cell-tile tile r1)
(cell-tile other r2)
(vary-meta r2 assoc :opacity 0.25 :fill "white")])))
(defn tile-set [tiles]
[:div
[:h4 (str "Tiles (" (count tiles) ")")]
[:div {:style {:column-count 12}}
(for [[idx tile] (map-indexed vector tiles)]
[:div {:key (str "ts-" idx)}
(svg-tile tile)])]])
(defn rule-set [rules tiles show-rules emit]
[:div
[:h4 (str "Rules (" (count rules) ") ")
[:button.link {:on-click (emit :toggle-show-rules)}
(if show-rules "(hide)" "(show)")]]
(when show-rules
[:div {:style {:column-count 8}}
(let [simplified (sort-by first (group-by identity rules))
numbered (some (fn [[_ e]] (> (count e) 1)) simplified)]
(for [[idx [[tile-idx dir other-idx] examples]] (map-indexed vector simplified)]
[:div {:key (str "rule-" idx)}
(when numbered
[:span (count examples) ": "])
(svg-adjacency (nth tiles tile-idx) dir (nth tiles other-idx))]))])])
(defn display-patterns [state emit]
(let [{:keys [wfc-state mode show-rules rotations]} state
{:keys [pattern tiles rules]} wfc-state]
[:div
[:div.flexcols
[:div
[:h4 "Pattern"]
(scene [150 150] pattern :on-click (emit :pattern-edit-click))]
(when (= mode :tileset)
[:div
[:h4 "Settings"]
[:div [:button {:on-click (emit :pattern-clear)} "Clear Pattern"]]
[:div [:button {:on-click (emit :pattern-reset)} "Reset Pattern"]]
[:div.label-set {:key "Include Rotations"}
[:input {:type "checkbox" :checked rotations
:on-change (emit :toggle-rotations)}]
[:label "Include Rotations"]]])
[tile-set tiles]]
[rule-set rules tiles show-rules emit]]))
(defn page []
(let [state (ctrl/state (init-state :tileset rule-e true))
emit (partial action-dispatch state)]
(fn []
(let [{:keys [wfc-state highlight cancel message]} @state
{:keys [grid tiles]} wfc-state
pattern-set (select-keys @state [:wfc-state :mode :show-rules :rotations])]
[:div
[:div.canvas-frame [scene [width height] grid
:tiles tiles
:highlight highlight
:on-click (partial set-cell! state)]]
[:div#interface.contained
[:div.flexcols
[:div [ctrl/change-mode state (keys modes) {:on-change (emit :reset)}]
(when message
[:div {:style {:color "red"}}
(debug/pre-edn message)])]
[:button.generate {:on-click (emit :reset)} "Reset"]
[:button.generate {:on-click (emit :solve-one)} "Solve One"]
[:button.generate {:on-click (emit :solve)} (if cancel "Stop" "Solve")]]
[:p.readable
"Click on a cell above to collapse it to a specific tile, or to
expand it to the set of all legal tiles. Click on a cell in the pattern
below to derive new tiles and rules."]
[:p.readable "Does not yet support backtracking."]
[display-patterns pattern-set emit]]]))))
(sketch/definition wave-function-collapse
{:created-at "2022-04-26"
:type :svg
:tags #{}}
(ctrl/mount page "sketch-host"))
|
3f2430534e335a588267937990711abd344a0d35024d5bc8d4584538769b8755 | ocaml-ppx/ppx | test.ml | let () =
Printf.printf "%s %d\n" [%plop.Foobar] [%omp_test]
| null | https://raw.githubusercontent.com/ocaml-ppx/ppx/40e5a35a4386d969effaf428078c900bd03b78ec/test/driver/omp-integration/test/test.ml | ocaml | let () =
Printf.printf "%s %d\n" [%plop.Foobar] [%omp_test]
| |
2e724ac8530ef1d0dc51b4736c65730926ba90f9f0f48a969710c8ef12267918 | 0install/0install | stream.ml | module LList = struct
type 'a item = Nil | Cons of 'a * 'a t
and 'a t = 'a item Lazy.t
let rec of_list = function
| [] -> lazy Nil
| x :: xs -> lazy (Cons (x, of_list xs))
let rec from fn =
lazy (
match fn () with
| None -> Nil
| Some x -> Cons (x, from fn)
)
end
type 'a t = {
mutable next : 'a LList.t;
mutable count : int;
}
exception Failure
let of_lazy x = { next = x; count = 0 }
let of_list x = of_lazy (LList.of_list x)
let count t = t.count
let empty t =
match t.next with
| lazy Nil -> ()
| _ -> raise Failure
let from fn = of_lazy (LList.from fn)
let next t =
match Lazy.force t.next with
| Nil -> raise Failure
| Cons (x, next) ->
t.next <- next;
t.count <- t.count + 1;
x
let junk t = ignore (next t)
let npeek n t =
let rec aux (next : _ LList.t) = function
| 0 -> []
| i ->
match Lazy.force next with
| Nil -> []
| Cons (x, next) ->
x :: aux next (i - 1)
in
aux t.next n
let peek t =
match Lazy.force t.next with
| Nil -> None
| Cons (x, _) -> Some x
| null | https://raw.githubusercontent.com/0install/0install/b3d7e5fdabb42c495c0ba3a97056b21264064f4f/src/support/stream.ml | ocaml | module LList = struct
type 'a item = Nil | Cons of 'a * 'a t
and 'a t = 'a item Lazy.t
let rec of_list = function
| [] -> lazy Nil
| x :: xs -> lazy (Cons (x, of_list xs))
let rec from fn =
lazy (
match fn () with
| None -> Nil
| Some x -> Cons (x, from fn)
)
end
type 'a t = {
mutable next : 'a LList.t;
mutable count : int;
}
exception Failure
let of_lazy x = { next = x; count = 0 }
let of_list x = of_lazy (LList.of_list x)
let count t = t.count
let empty t =
match t.next with
| lazy Nil -> ()
| _ -> raise Failure
let from fn = of_lazy (LList.from fn)
let next t =
match Lazy.force t.next with
| Nil -> raise Failure
| Cons (x, next) ->
t.next <- next;
t.count <- t.count + 1;
x
let junk t = ignore (next t)
let npeek n t =
let rec aux (next : _ LList.t) = function
| 0 -> []
| i ->
match Lazy.force next with
| Nil -> []
| Cons (x, next) ->
x :: aux next (i - 1)
in
aux t.next n
let peek t =
match Lazy.force t.next with
| Nil -> None
| Cons (x, _) -> Some x
| |
d896b3f17f16e07b4c7e8106b03b9a7c01993ecfe743eacae3f1f578da0b7098 | haskell/cabal | cabal.test.hs | import Test.Cabal.Prelude
` default - language ` need ≥1.10 .
main = cabalTest $
fails $ cabal "check" []
| null | https://raw.githubusercontent.com/haskell/cabal/1cfe7c4c7257aa7ae450209d34b4a359e6703a10/cabal-testsuite/PackageTests/Check/ConfiguredPackage/CabalVersion/DefaultLanguage/cabal.test.hs | haskell | import Test.Cabal.Prelude
` default - language ` need ≥1.10 .
main = cabalTest $
fails $ cabal "check" []
| |
48c97a6c43ffa3cc870a04e9ea470b83ba6093fbe14d11e5f81f46e8c1f42b03 | ku-fpg/kansas-lava | Protocols.hs | # LANGUAGE ScopedTypeVariables , RankNTypes , TypeFamilies , FlexibleContexts , ExistentialQuantification , DataKinds #
module Protocols where
import Language.KansasLava
import Test
import Data.Sized.Fin
import Data.Sized.Unsigned
import Data.Sized.Matrix (matrix, Matrix)
import Data.Array.IArray
import GHC.TypeLits
--import qualified Data.Sized.Matrix as M
--import Debug.Trace
type instance (5 + 5) = 10
type instance (3 * 5) = 15
tests :: Tests ()
tests = do
return ()
This needs re - written
-- testing Streams
let fifoTest : : forall w . ( Rep w , , Show w , SingI ( W w ) )
= > String
- > Patch ( Seq ( Enabled w ) ) ( Seq ( Enabled w ) ) ( Seq Ack ) ( Seq Ack ) - > StreamTest w w
fifoTest n f = StreamTest
{ theStream = f
, correctnessCondition = \ ins outs - > -- trace ( show ( " cc",length ins , length outs ) ) $
case ( ) of
( ) | outs /= take ( length outs ) ins - > return " in / out differences "
( ) | length outs < fromIntegral count
- > return ( " to few transfers : " + + show ( length outs ) )
| otherwise - > Nothing
, theStreamTestCount = count
, theStreamTestCycles = 10000
, theStreamName = n
}
where
count = 100
{ -
let bridge ' : : forall w . ( Rep w , , Show w , ( W w ) )
= > ( Seq ( Enabled w ) , Seq Full ) - > ( Seq Ack , Seq ( Enabled w ) )
bridge ' = bridge ` connect ` shallowFIFO ` connect ` bridge
This needs re-written
-- testing Streams
let fifoTest :: forall w . (Rep w, Eq w, Show w, SingI (W w))
=> String
-> Patch (Seq (Enabled w)) (Seq (Enabled w)) (Seq Ack) (Seq Ack) -> StreamTest w w
fifoTest n f = StreamTest
{ theStream = f
, correctnessCondition = \ ins outs -> -- trace (show ("cc",length ins,length outs)) $
case () of
() | outs /= take (length outs) ins -> return "in/out differences"
() | length outs < fromIntegral count
-> return ("to few transfers: " ++ show (length outs))
| otherwise -> Nothing
, theStreamTestCount = count
, theStreamTestCycles = 10000
, theStreamName = n
}
where
count = 100
{-
let bridge' :: forall w . (Rep w,Eq w, Show w, Size (W w))
=> (Seq (Enabled w), Seq Full) -> (Seq Ack, Seq (Enabled w))
bridge' = bridge `connect` shallowFIFO `connect` bridge
-}
testStream test "U5" (fifoTest "emptyP" emptyP :: StreamTest U5 U5)
testStream test "Bool" (fifoTest "emptyP" emptyP :: StreamTest Bool Bool)
testStream test "U5" (fifoTest "fifo1" fifo1 :: StreamTest U5 U5)
testStream test "Bool" (fifoTest "fifo1" fifo1 :: StreamTest Bool Bool)
testStream test "U5" (fifoTest "fifo2" fifo2 :: StreamTest U5 U5)
testStream test "Bool" (fifoTest "fifo2" fifo2 :: StreamTest Bool Bool)
This tests dupP and
let patchTest1 :: forall w . (Rep w,Eq w, Show w, SingI (W w), Num w)
=> StreamTest w (w,w)
patchTest1 = StreamTest
{ theStream = dupP $$ fstP (forwardP $ mapEnabled (+1)) $$ zipP
, correctnessCondition = \ ins outs -> -- trace (show ("cc",length ins,length outs)) $
-- trace (show (ins,outs)) $
case () of
() | length outs /= length ins -> return "in/out differences"
| any (\ (x,y) -> x - 1 /= y) outs -> return "bad result value"
| ins /= map snd outs -> return "result not as expected"
| otherwise -> Nothing
, theStreamTestCount = count
, theStreamTestCycles = 10000
, theStreamName = "dupP-zipP"
}
where
count = 100
testStream test "U5" (patchTest1 :: StreamTest U5 (U5,U5))
-- This tests matrixDupP and matrixZipP
let patchTest2 :: forall w . (Rep w,Eq w, Show w, SingI (W w), Num w)
=> StreamTest w (Matrix (Fin 3) w)
patchTest2 = StreamTest
{ theStream = matrixDupP $$ matrixStackP (matrix [
forwardP $ mapEnabled (+0),
forwardP $ mapEnabled (+1),
forwardP $ mapEnabled (+2)]
) $$ matrixZipP
, correctnessCondition = \ ins outs -> -- trace (show ("cc",length ins,length outs)) $
-- trace (show (ins,outs)) $
case () of
() | length outs /= length ins -> return "in/out differences"
| any (\ m -> m ! 0 /= (m ! 1) - 1) outs -> return "bad result value 0,1"
| any (\ m -> m ! 0 /= (m ! 2) - 2) outs -> return $ "bad result value 0,2"
| ins /= map (! 0) outs -> return "result not as expected"
| otherwise -> Nothing
, theStreamTestCount = count
, theStreamTestCycles = 10000
, theStreamName = "matrixDupP-matrixZipP"
}
where
count = 100
testStream test "U5" (patchTest2 :: StreamTest U5 (Matrix (Fin 3) U5))
This tests muxP ( and )
let patchTest3 :: forall w . (Rep w,Eq w, Show w, SingI (W w), Num w, w ~ U5)
=> StreamTest w w
patchTest3 = StreamTest
{ theStream =
fifo1 $$
dupP $$
stackP (forwardP (mapEnabled (*2)) $$ fifo1)
(forwardP (mapEnabled (*3)) $$ fifo1) $$
openP $$
fstP (cycleP (matrix [True,False] :: Matrix (Fin 2) Bool) $$ fifo1) $$
muxP
, correctnessCondition = \ ins outs -> -- trace (show ("cc",length ins,length outs)) $
-- trace (show (ins,outs)) $
case () of
() | length outs /= length ins * 2 -> return "in/out size issues"
| outs /= concat [ [n * 2,n * 3] | n <- ins ]
-> return "value out distored"
| otherwise -> Nothing
, theStreamTestCount = count
, theStreamTestCycles = 10000
, theStreamName = "muxP"
}
where
count = 100
testStream test "U5" (patchTest3 :: StreamTest U5 U5)
This tests deMuxP ( and ) , and
let patchTest4 :: forall w . (Rep w,Eq w, Show w, SingI (W w), Num w, w ~ U5)
=> StreamTest w (w,w)
patchTest4 = StreamTest
{ theStream =
openP $$
fstP (cycleP (matrix [True,False] :: Matrix (Fin 2) Bool) $$ fifo1) $$
deMuxP $$
stackP (fifo1) (fifo1) $$
zipP
, correctnessCondition = \ ins outs -> -- trace (show ("cc",length ins,length outs)) $
-- trace (show (ins,outs)) $
case () of
() | length outs /= length ins `div` 2 -> return "in/out size issues"
| concat [ [a,b] | (a,b) <- outs ] /= ins
-> return "value out distored"
| otherwise -> Nothing
, theStreamTestCount = count
, theStreamTestCycles = 10000
, theStreamName = "deMuxP-zipP"
}
where
count = 100
testStream test "U5" (patchTest4 :: StreamTest U5 (U5,U5))
return ()
-} | null | https://raw.githubusercontent.com/ku-fpg/kansas-lava/cc0be29bd8392b57060c3c11e7f3b799a6d437e1/tests/Protocols.hs | haskell | import qualified Data.Sized.Matrix as M
import Debug.Trace
testing Streams
trace ( show ( " cc",length ins , length outs ) ) $
testing Streams
trace (show ("cc",length ins,length outs)) $
let bridge' :: forall w . (Rep w,Eq w, Show w, Size (W w))
=> (Seq (Enabled w), Seq Full) -> (Seq Ack, Seq (Enabled w))
bridge' = bridge `connect` shallowFIFO `connect` bridge
trace (show ("cc",length ins,length outs)) $
trace (show (ins,outs)) $
This tests matrixDupP and matrixZipP
trace (show ("cc",length ins,length outs)) $
trace (show (ins,outs)) $
trace (show ("cc",length ins,length outs)) $
trace (show (ins,outs)) $
trace (show ("cc",length ins,length outs)) $
trace (show (ins,outs)) $ | # LANGUAGE ScopedTypeVariables , RankNTypes , TypeFamilies , FlexibleContexts , ExistentialQuantification , DataKinds #
module Protocols where
import Language.KansasLava
import Test
import Data.Sized.Fin
import Data.Sized.Unsigned
import Data.Sized.Matrix (matrix, Matrix)
import Data.Array.IArray
import GHC.TypeLits
type instance (5 + 5) = 10
type instance (3 * 5) = 15
tests :: Tests ()
tests = do
return ()
This needs re - written
let fifoTest : : forall w . ( Rep w , , Show w , SingI ( W w ) )
= > String
- > Patch ( Seq ( Enabled w ) ) ( Seq ( Enabled w ) ) ( Seq Ack ) ( Seq Ack ) - > StreamTest w w
fifoTest n f = StreamTest
{ theStream = f
case ( ) of
( ) | outs /= take ( length outs ) ins - > return " in / out differences "
( ) | length outs < fromIntegral count
- > return ( " to few transfers : " + + show ( length outs ) )
| otherwise - > Nothing
, theStreamTestCount = count
, theStreamTestCycles = 10000
, theStreamName = n
}
where
count = 100
{ -
let bridge ' : : forall w . ( Rep w , , Show w , ( W w ) )
= > ( Seq ( Enabled w ) , Seq Full ) - > ( Seq Ack , Seq ( Enabled w ) )
bridge ' = bridge ` connect ` shallowFIFO ` connect ` bridge
This needs re-written
let fifoTest :: forall w . (Rep w, Eq w, Show w, SingI (W w))
=> String
-> Patch (Seq (Enabled w)) (Seq (Enabled w)) (Seq Ack) (Seq Ack) -> StreamTest w w
fifoTest n f = StreamTest
{ theStream = f
case () of
() | outs /= take (length outs) ins -> return "in/out differences"
() | length outs < fromIntegral count
-> return ("to few transfers: " ++ show (length outs))
| otherwise -> Nothing
, theStreamTestCount = count
, theStreamTestCycles = 10000
, theStreamName = n
}
where
count = 100
testStream test "U5" (fifoTest "emptyP" emptyP :: StreamTest U5 U5)
testStream test "Bool" (fifoTest "emptyP" emptyP :: StreamTest Bool Bool)
testStream test "U5" (fifoTest "fifo1" fifo1 :: StreamTest U5 U5)
testStream test "Bool" (fifoTest "fifo1" fifo1 :: StreamTest Bool Bool)
testStream test "U5" (fifoTest "fifo2" fifo2 :: StreamTest U5 U5)
testStream test "Bool" (fifoTest "fifo2" fifo2 :: StreamTest Bool Bool)
This tests dupP and
let patchTest1 :: forall w . (Rep w,Eq w, Show w, SingI (W w), Num w)
=> StreamTest w (w,w)
patchTest1 = StreamTest
{ theStream = dupP $$ fstP (forwardP $ mapEnabled (+1)) $$ zipP
case () of
() | length outs /= length ins -> return "in/out differences"
| any (\ (x,y) -> x - 1 /= y) outs -> return "bad result value"
| ins /= map snd outs -> return "result not as expected"
| otherwise -> Nothing
, theStreamTestCount = count
, theStreamTestCycles = 10000
, theStreamName = "dupP-zipP"
}
where
count = 100
testStream test "U5" (patchTest1 :: StreamTest U5 (U5,U5))
let patchTest2 :: forall w . (Rep w,Eq w, Show w, SingI (W w), Num w)
=> StreamTest w (Matrix (Fin 3) w)
patchTest2 = StreamTest
{ theStream = matrixDupP $$ matrixStackP (matrix [
forwardP $ mapEnabled (+0),
forwardP $ mapEnabled (+1),
forwardP $ mapEnabled (+2)]
) $$ matrixZipP
case () of
() | length outs /= length ins -> return "in/out differences"
| any (\ m -> m ! 0 /= (m ! 1) - 1) outs -> return "bad result value 0,1"
| any (\ m -> m ! 0 /= (m ! 2) - 2) outs -> return $ "bad result value 0,2"
| ins /= map (! 0) outs -> return "result not as expected"
| otherwise -> Nothing
, theStreamTestCount = count
, theStreamTestCycles = 10000
, theStreamName = "matrixDupP-matrixZipP"
}
where
count = 100
testStream test "U5" (patchTest2 :: StreamTest U5 (Matrix (Fin 3) U5))
This tests muxP ( and )
let patchTest3 :: forall w . (Rep w,Eq w, Show w, SingI (W w), Num w, w ~ U5)
=> StreamTest w w
patchTest3 = StreamTest
{ theStream =
fifo1 $$
dupP $$
stackP (forwardP (mapEnabled (*2)) $$ fifo1)
(forwardP (mapEnabled (*3)) $$ fifo1) $$
openP $$
fstP (cycleP (matrix [True,False] :: Matrix (Fin 2) Bool) $$ fifo1) $$
muxP
case () of
() | length outs /= length ins * 2 -> return "in/out size issues"
| outs /= concat [ [n * 2,n * 3] | n <- ins ]
-> return "value out distored"
| otherwise -> Nothing
, theStreamTestCount = count
, theStreamTestCycles = 10000
, theStreamName = "muxP"
}
where
count = 100
testStream test "U5" (patchTest3 :: StreamTest U5 U5)
This tests deMuxP ( and ) , and
let patchTest4 :: forall w . (Rep w,Eq w, Show w, SingI (W w), Num w, w ~ U5)
=> StreamTest w (w,w)
patchTest4 = StreamTest
{ theStream =
openP $$
fstP (cycleP (matrix [True,False] :: Matrix (Fin 2) Bool) $$ fifo1) $$
deMuxP $$
stackP (fifo1) (fifo1) $$
zipP
case () of
() | length outs /= length ins `div` 2 -> return "in/out size issues"
| concat [ [a,b] | (a,b) <- outs ] /= ins
-> return "value out distored"
| otherwise -> Nothing
, theStreamTestCount = count
, theStreamTestCycles = 10000
, theStreamName = "deMuxP-zipP"
}
where
count = 100
testStream test "U5" (patchTest4 :: StreamTest U5 (U5,U5))
return ()
-} |
a9f350057356497f021d5ac6d3c55ca43b65ec0f2104b7afe234e0193f968cd7 | yesodweb/persistent | ImplicitIdColSpec.hs | # LANGUAGE DataKinds #
# LANGUAGE DerivingStrategies #
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE QuasiQuotes #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Database.Persist.TH.ImplicitIdColSpec where
import TemplateTestImports
import Data.Text (Text)
import Database.Persist.ImplicitIdDef
import Database.Persist.ImplicitIdDef.Internal (fieldTypeFromTypeable)
do
let
uuidDef =
mkImplicitIdDef @Text "uuid_generate_v1mc()"
settings =
setImplicitIdDef uuidDef sqlSettings
mkPersist settings [persistLowerCase|
User
name String
age Int
|]
pass :: IO ()
pass = pure ()
asIO :: IO a -> IO a
asIO = id
spec :: Spec
spec = describe "ImplicitIdColSpec" $ do
describe "UserKey" $ do
it "has type Text -> Key User" $ do
let
userKey = UserKey "Hello"
_ = UserKey :: Text -> UserId
pass
describe "getEntityId" $ do
let
EntityIdField idField =
getEntityId (entityDef (Nothing @User))
it "has SqlString SqlType" $ asIO $ do
fieldSqlType idField `shouldBe` SqlString
it "has Text FieldType" $ asIO $ do
pendingWith "currently returns UserId, may not be an issue"
fieldType idField
`shouldBe`
fieldTypeFromTypeable @Text
| null | https://raw.githubusercontent.com/yesodweb/persistent/eaf9d561a66a7b7a8fcbdf6bd0e9800fa525cc13/persistent/test/Database/Persist/TH/ImplicitIdColSpec.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE DataKinds #
# LANGUAGE DerivingStrategies #
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE QuasiQuotes #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Database.Persist.TH.ImplicitIdColSpec where
import TemplateTestImports
import Data.Text (Text)
import Database.Persist.ImplicitIdDef
import Database.Persist.ImplicitIdDef.Internal (fieldTypeFromTypeable)
do
let
uuidDef =
mkImplicitIdDef @Text "uuid_generate_v1mc()"
settings =
setImplicitIdDef uuidDef sqlSettings
mkPersist settings [persistLowerCase|
User
name String
age Int
|]
pass :: IO ()
pass = pure ()
asIO :: IO a -> IO a
asIO = id
spec :: Spec
spec = describe "ImplicitIdColSpec" $ do
describe "UserKey" $ do
it "has type Text -> Key User" $ do
let
userKey = UserKey "Hello"
_ = UserKey :: Text -> UserId
pass
describe "getEntityId" $ do
let
EntityIdField idField =
getEntityId (entityDef (Nothing @User))
it "has SqlString SqlType" $ asIO $ do
fieldSqlType idField `shouldBe` SqlString
it "has Text FieldType" $ asIO $ do
pendingWith "currently returns UserId, may not be an issue"
fieldType idField
`shouldBe`
fieldTypeFromTypeable @Text
|
ddb110bf27deb81c0e1fb8eb5d0a8216d8e921333f503d2693d9c87f47517995 | GaloisInc/saw-script | Monad.hs | # LANGUAGE FlexibleInstances #
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE FlexibleContexts #
{-# LANGUAGE RankNTypes #-}
|
Module : Verifier . SAW.Translation . Coq
Copyright : Galois , Inc. 2018
License : :
Stability : experimental
Portability : portable
Module : Verifier.SAW.Translation.Coq
Copyright : Galois, Inc. 2018
License : BSD3
Maintainer :
Stability : experimental
Portability : portable
-}
module Verifier.SAW.Translation.Coq.Monad
( TranslationConfiguration(..)
, TranslationConfigurationMonad
, TranslationMonad
, TranslationError(..)
, WithTranslationConfiguration(..)
, runTranslationMonad
) where
import qualified Control.Monad.Except as Except
import Control.Monad.Reader hiding (fail)
import Control.Monad.State hiding (fail, state)
import Prelude hiding (fail)
import Verifier.SAW.SharedTerm
import Verifier . SAW.Term . CtxTerm
import Verifier . SAW.Term . Pretty
import qualified Verifier . SAW.UntypedAST as Un
data TranslationError a
= NotSupported a
| NotExpr a
| NotType a
| LocalVarOutOfBounds a
| BadTerm a
| CannotCreateDefaultValue a
instance {-# OVERLAPPING #-} Show (TranslationError Term) where
show = showError showTerm
instance {-# OVERLAPPABLE #-} Show a => Show (TranslationError a) where
show = showError show
showError :: (a -> String) -> TranslationError a -> String
showError printer err = case err of
NotSupported a -> "Not supported: " ++ printer a
NotExpr a -> "Expecting an expression term: " ++ printer a
NotType a -> "Expecting a type term: " ++ printer a
LocalVarOutOfBounds a -> "Local variable reference is out of bounds: " ++ printer a
BadTerm a -> "Malformed term: " ++ printer a
CannotCreateDefaultValue a -> "Unable to generate a default value of the given type: " ++ printer a
data TranslationConfiguration = TranslationConfiguration
{ constantRenaming :: [(String, String)]
^ A map from ' ImportedName 's of constants to names that should be used to
realize them in Coq ; this is generally used to map cryptol operators like
@||@ or @&&@ to nicer names in Coq , but works on any imported names
, constantSkips :: [String]
^ A list of ' ImportedName 's to skip , i.e. , not translate when encountered
, monadicTranslation :: Bool
-- ^ Whether to wrap everything in a free monad construction.
-- - Advantage: fixpoints can be readily represented
-- - Disadvantage: pure computations look more gnarly
, postPreamble :: String
^ Text to be concatenated at the end of the Coq preamble , before the code
-- generated by the translation. Usually consists of extra file imports,
-- module imports, scopes openings.
, vectorModule :: String
-- ^ all vector operations will be prepended with this module name, i.e.
-- "<VectorModule>.append", etc. So that it can be retargeted easily.
-- Current provided options are:
-- - SAWCoreVectorsAsCoqLists
-- - SAWCoreVectorsAsCoqVectors
-- Currently considering adding:
-- - SAWCoreVectorsAsSSReflectSeqs
}
-- | The functional dependency of 'MonadReader' makes it not compositional, so
-- we have to jam together different structures that want to be in the 'Reader'
-- into a single datatype. This type allows adding extra configuration on top
-- of the translation configuration.
data WithTranslationConfiguration r = WithTranslationConfiguration
{ translationConfiguration :: TranslationConfiguration
, otherConfiguration :: r
}
-- | Some computations will rely solely on access to the configuration, so we
-- provide it separately.
type TranslationConfigurationMonad r m =
( MonadReader (WithTranslationConfiguration r) m
)
type TranslationMonad r s m =
( Except.MonadError (TranslationError Term) m
, TranslationConfigurationMonad r m
, MonadState s m
)
runTranslationMonad ::
TranslationConfiguration ->
r ->
s ->
(forall m. TranslationMonad r s m => m a) ->
Either (TranslationError Term) (a, s)
runTranslationMonad configuration r s m =
runStateT (runReaderT m (WithTranslationConfiguration configuration r)) s
| null | https://raw.githubusercontent.com/GaloisInc/saw-script/cd3f1416b2f416b15cd3d9e628256052b0b862d6/saw-core-coq/src/Verifier/SAW/Translation/Coq/Monad.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE RankNTypes #
# OVERLAPPING #
# OVERLAPPABLE #
^ Whether to wrap everything in a free monad construction.
- Advantage: fixpoints can be readily represented
- Disadvantage: pure computations look more gnarly
generated by the translation. Usually consists of extra file imports,
module imports, scopes openings.
^ all vector operations will be prepended with this module name, i.e.
"<VectorModule>.append", etc. So that it can be retargeted easily.
Current provided options are:
- SAWCoreVectorsAsCoqLists
- SAWCoreVectorsAsCoqVectors
Currently considering adding:
- SAWCoreVectorsAsSSReflectSeqs
| The functional dependency of 'MonadReader' makes it not compositional, so
we have to jam together different structures that want to be in the 'Reader'
into a single datatype. This type allows adding extra configuration on top
of the translation configuration.
| Some computations will rely solely on access to the configuration, so we
provide it separately. | # LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
|
Module : Verifier . SAW.Translation . Coq
Copyright : Galois , Inc. 2018
License : :
Stability : experimental
Portability : portable
Module : Verifier.SAW.Translation.Coq
Copyright : Galois, Inc. 2018
License : BSD3
Maintainer :
Stability : experimental
Portability : portable
-}
module Verifier.SAW.Translation.Coq.Monad
( TranslationConfiguration(..)
, TranslationConfigurationMonad
, TranslationMonad
, TranslationError(..)
, WithTranslationConfiguration(..)
, runTranslationMonad
) where
import qualified Control.Monad.Except as Except
import Control.Monad.Reader hiding (fail)
import Control.Monad.State hiding (fail, state)
import Prelude hiding (fail)
import Verifier.SAW.SharedTerm
import Verifier . SAW.Term . CtxTerm
import Verifier . SAW.Term . Pretty
import qualified Verifier . SAW.UntypedAST as Un
data TranslationError a
= NotSupported a
| NotExpr a
| NotType a
| LocalVarOutOfBounds a
| BadTerm a
| CannotCreateDefaultValue a
show = showError showTerm
show = showError show
showError :: (a -> String) -> TranslationError a -> String
showError printer err = case err of
NotSupported a -> "Not supported: " ++ printer a
NotExpr a -> "Expecting an expression term: " ++ printer a
NotType a -> "Expecting a type term: " ++ printer a
LocalVarOutOfBounds a -> "Local variable reference is out of bounds: " ++ printer a
BadTerm a -> "Malformed term: " ++ printer a
CannotCreateDefaultValue a -> "Unable to generate a default value of the given type: " ++ printer a
data TranslationConfiguration = TranslationConfiguration
{ constantRenaming :: [(String, String)]
^ A map from ' ImportedName 's of constants to names that should be used to
realize them in Coq ; this is generally used to map cryptol operators like
@||@ or @&&@ to nicer names in Coq , but works on any imported names
, constantSkips :: [String]
^ A list of ' ImportedName 's to skip , i.e. , not translate when encountered
, monadicTranslation :: Bool
, postPreamble :: String
^ Text to be concatenated at the end of the Coq preamble , before the code
, vectorModule :: String
}
data WithTranslationConfiguration r = WithTranslationConfiguration
{ translationConfiguration :: TranslationConfiguration
, otherConfiguration :: r
}
type TranslationConfigurationMonad r m =
( MonadReader (WithTranslationConfiguration r) m
)
type TranslationMonad r s m =
( Except.MonadError (TranslationError Term) m
, TranslationConfigurationMonad r m
, MonadState s m
)
runTranslationMonad ::
TranslationConfiguration ->
r ->
s ->
(forall m. TranslationMonad r s m => m a) ->
Either (TranslationError Term) (a, s)
runTranslationMonad configuration r s m =
runStateT (runReaderT m (WithTranslationConfiguration configuration r)) s
|
d922991c179d559a10d3482c29dfb6fb0fda119938cf0d26fa7ee679f7b5af70 | crategus/cl-cffi-gtk | revealer-icon.lisp | ;;;; Example Revealer Icon - 2021-12-4
;;;;
GtkRevealer is a container that animates showing and hiding
;;;; of its sole child with nice transitions.
;;;;
;;;; TODO: This example uses the gtk-widget-mapped function, but the
;;;; documentation says: This function should only ever be called in a derived
;;;; "map" or "unmap" implementation of the widget.
;;;; What is a better implementation?
(in-package :gtk-example)
(defun example-revealer-icon (&optional (application nil))
(within-main-loop
(let* ((count 0)
(timeout 0)
(builder (gtk-builder-new-from-file (sys-path "revealer-icon.ui")))
(window (gtk-builder-object builder "window")))
(g-signal-connect window "destroy"
(lambda (widget)
(declare (ignore widget))
(when (not (= timeout 0))
(g-source-remove timeout)
(setf timeout 0))
(leave-gtk-main)))
(setf (gtk-window-application window) application)
(setf timeout
(g-timeout-add 690
(lambda ()
(let* ((name (format nil "revealer~d" count))
(revealer (gtk-builder-object builder name)))
(setf (gtk-revealer-reveal-child revealer) t)
(g-signal-connect revealer "notify::child-revealed"
(lambda (widget pspec)
(declare (ignore pspec))
(when (gtk-widget-mapped widget)
(setf (gtk-revealer-reveal-child widget)
(not (gtk-revealer-child-revealed widget))))))
(setf count (+ count 1))
(if (>= count 9)
(progn
(setf timeout 0)
nil)
t)))))
(gtk-widget-show-all window))))
| null | https://raw.githubusercontent.com/crategus/cl-cffi-gtk/ba198f7d29cb06de1e8965e1b8a78522d5430516/demo/gtk-example/revealer-icon.lisp | lisp | Example Revealer Icon - 2021-12-4
of its sole child with nice transitions.
TODO: This example uses the gtk-widget-mapped function, but the
documentation says: This function should only ever be called in a derived
"map" or "unmap" implementation of the widget.
What is a better implementation? | GtkRevealer is a container that animates showing and hiding
(in-package :gtk-example)
(defun example-revealer-icon (&optional (application nil))
(within-main-loop
(let* ((count 0)
(timeout 0)
(builder (gtk-builder-new-from-file (sys-path "revealer-icon.ui")))
(window (gtk-builder-object builder "window")))
(g-signal-connect window "destroy"
(lambda (widget)
(declare (ignore widget))
(when (not (= timeout 0))
(g-source-remove timeout)
(setf timeout 0))
(leave-gtk-main)))
(setf (gtk-window-application window) application)
(setf timeout
(g-timeout-add 690
(lambda ()
(let* ((name (format nil "revealer~d" count))
(revealer (gtk-builder-object builder name)))
(setf (gtk-revealer-reveal-child revealer) t)
(g-signal-connect revealer "notify::child-revealed"
(lambda (widget pspec)
(declare (ignore pspec))
(when (gtk-widget-mapped widget)
(setf (gtk-revealer-reveal-child widget)
(not (gtk-revealer-child-revealed widget))))))
(setf count (+ count 1))
(if (>= count 9)
(progn
(setf timeout 0)
nil)
t)))))
(gtk-widget-show-all window))))
|
0d501feb479ba50c673b459797119d3bb5bed05a4c67efca6ca6034c73546c9c | juxt/roll | utils.cljs | (ns roll.utils
(:require [lumo.io]
[cljstache.core :refer [render]]
[clojure.string]))
(defn resolve-path [path]
(clojure.string/join "_" (map name path)))
(defn ->snake [s]
(clojure.string/replace (name s) "-" "_"))
(defn tf-path-to [path]
(->> path
(map ->snake)
(clojure.string/join ".")))
(defn $ [path]
(str "${" (tf-path-to path) "}"))
(defn render-mustache [m t]
(let [t (lumo.io/slurp (lumo.io/resource t))]
(render t m)))
(defn ->json
[m]
(js/JSON.stringify (clj->js m) nil 4))
| null | https://raw.githubusercontent.com/juxt/roll/1ef07d72f05b5604eec4f7d6a5dbf0d21ec3c8b3/src/roll/utils.cljs | clojure | (ns roll.utils
(:require [lumo.io]
[cljstache.core :refer [render]]
[clojure.string]))
(defn resolve-path [path]
(clojure.string/join "_" (map name path)))
(defn ->snake [s]
(clojure.string/replace (name s) "-" "_"))
(defn tf-path-to [path]
(->> path
(map ->snake)
(clojure.string/join ".")))
(defn $ [path]
(str "${" (tf-path-to path) "}"))
(defn render-mustache [m t]
(let [t (lumo.io/slurp (lumo.io/resource t))]
(render t m)))
(defn ->json
[m]
(js/JSON.stringify (clj->js m) nil 4))
| |
f3f087ac44b94669c8347449c5931bbaf2ff29118a3114864af52685e28b286b | chrisdone/sandbox | conduit-tcp-server.hs | #!/usr/bin/env stack
-- stack --resolver lts-12.12 script
{-# LANGUAGE OverloadedStrings #-}
import Data.Conduit.Network
import Conduit
main =
runTCPServer
(serverSettings 2019 "*")
(\app -> do
putStrLn "Someone connected!"
let loop = do
oneMessageMaybe <-
runConduit (appSource app .| mapMC print .| await)
case oneMessageMaybe of
Nothing -> putStrLn "No more messages in upstream, done!"
Just message -> do
print message
loop
loop)
where
myparser = do
len <- P.anyWord8
bytes <- P.take (fromIntegral len)
return bytes
| null | https://raw.githubusercontent.com/chrisdone/sandbox/c43975a01119a7c70ffe83c49a629c45f7f2543a/conduit-tcp-server.hs | haskell | stack --resolver lts-12.12 script
# LANGUAGE OverloadedStrings # | #!/usr/bin/env stack
import Data.Conduit.Network
import Conduit
main =
runTCPServer
(serverSettings 2019 "*")
(\app -> do
putStrLn "Someone connected!"
let loop = do
oneMessageMaybe <-
runConduit (appSource app .| mapMC print .| await)
case oneMessageMaybe of
Nothing -> putStrLn "No more messages in upstream, done!"
Just message -> do
print message
loop
loop)
where
myparser = do
len <- P.anyWord8
bytes <- P.take (fromIntegral len)
return bytes
|
81f930de20e8a14d64126e30473f7b52c3e22d6850f6f041cd3df88daac870a3 | dpiponi/Moodler | xmidi11.hs |
do
(x0, y0) <- mouse
let (x, y) = quantise2 quantum (x0, y0)
root <- currentPlane
keyboard11 <- new' "input"
alias "keyboard11" keyboard11
trigger11 <- new' "input"
alias "trigger11" trigger11
modulation11 <- new' "input"
alias "modulation11" modulation11
bend11 <- new' "input"
alias "bend11" bend11
container0 <- container' "panel_xkeyboard11.png" (x+456-456.0,y-36+36.0) (Inside root)
out1 <- plugout' (keyboard11 ! "result") (x+456-396.0,y-36+60.0+48) (Outside container0)
setColour out1 "#control"
out2 <- plugout' (trigger11 ! "result") (x+456-396.0,y-36+12.0+48) (Outside container0)
setColour out2 "#control"
out3 <- plugout' (modulation11 ! "result") (x+456-396.0,y-36+12.0) (Outside container0)
setColour out3 "#control"
out4 <- plugout' (bend11 ! "result") (x+456-396.0,y-36+12.0-48) (Outside container0)
setColour out4 "#control"
| null | https://raw.githubusercontent.com/dpiponi/Moodler/a0c984c36abae52668d00f25eb3749e97e8936d3/Moodler/scripts/xmidi11.hs | haskell |
do
(x0, y0) <- mouse
let (x, y) = quantise2 quantum (x0, y0)
root <- currentPlane
keyboard11 <- new' "input"
alias "keyboard11" keyboard11
trigger11 <- new' "input"
alias "trigger11" trigger11
modulation11 <- new' "input"
alias "modulation11" modulation11
bend11 <- new' "input"
alias "bend11" bend11
container0 <- container' "panel_xkeyboard11.png" (x+456-456.0,y-36+36.0) (Inside root)
out1 <- plugout' (keyboard11 ! "result") (x+456-396.0,y-36+60.0+48) (Outside container0)
setColour out1 "#control"
out2 <- plugout' (trigger11 ! "result") (x+456-396.0,y-36+12.0+48) (Outside container0)
setColour out2 "#control"
out3 <- plugout' (modulation11 ! "result") (x+456-396.0,y-36+12.0) (Outside container0)
setColour out3 "#control"
out4 <- plugout' (bend11 ! "result") (x+456-396.0,y-36+12.0-48) (Outside container0)
setColour out4 "#control"
| |
c0b5da80481b3e0ceaa3efbcbbbd459bd8cd51424b7bb9b6bc0beef611f948ed | ijvcms/chuanqi_dev | player_extra_lib.erl | %%%-------------------------------------------------------------------
%%% @author qhb
( C ) 2016 , < COMPANY >
%%% @doc
玩家的扩展属性或状态 , 可随时动态增加 ,
%%% @end
Created : 19 . 2016 下午9:52
%%%-------------------------------------------------------------------
-module(player_extra_lib).
-author("qhb").
-include("record.hrl").
-include("proto.hrl").
%%
%% API
-export([
request/2
]).
%%请求服务端发送状态数据,参数为需要推送的协议
request(PlayerState, ProList) ->
lists:foreach(fun(Pro) ->
push(Pro, PlayerState)
end, ProList).
临时加 , 推送开服第几天
push(11056, PlayerState) ->
{{OpenY, OpenM, OpenD}, {_, _, _}} = config:get_start_time_str(),
BeginTime = util_date:time_tuple_to_unixtime({{OpenY, OpenM, OpenD}, {0, 0, 0}}),
Day = max(1, util_erl:ceil((util_date:unixtime() - BeginTime) / 86400)),
Rep = #rep_instance_king_round_time_left{time_left = Day},
net_send:send_to_client(PlayerState#player_state.socket, 11056, Rep);
%%推送王城乱斗的排行
push(11057, PlayerState) ->
instance_king_lib:push_player_rank(PlayerState);
结盟状态
push(17092, PlayerState) ->
alliance_lib:check_state(PlayerState);
push(_ProId, _) ->
ok. | null | https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/business/player/player_extra_lib.erl | erlang | -------------------------------------------------------------------
@author qhb
@doc
@end
-------------------------------------------------------------------
API
请求服务端发送状态数据,参数为需要推送的协议
推送王城乱斗的排行 | ( C ) 2016 , < COMPANY >
玩家的扩展属性或状态 , 可随时动态增加 ,
Created : 19 . 2016 下午9:52
-module(player_extra_lib).
-author("qhb").
-include("record.hrl").
-include("proto.hrl").
-export([
request/2
]).
request(PlayerState, ProList) ->
lists:foreach(fun(Pro) ->
push(Pro, PlayerState)
end, ProList).
临时加 , 推送开服第几天
push(11056, PlayerState) ->
{{OpenY, OpenM, OpenD}, {_, _, _}} = config:get_start_time_str(),
BeginTime = util_date:time_tuple_to_unixtime({{OpenY, OpenM, OpenD}, {0, 0, 0}}),
Day = max(1, util_erl:ceil((util_date:unixtime() - BeginTime) / 86400)),
Rep = #rep_instance_king_round_time_left{time_left = Day},
net_send:send_to_client(PlayerState#player_state.socket, 11056, Rep);
push(11057, PlayerState) ->
instance_king_lib:push_player_rank(PlayerState);
结盟状态
push(17092, PlayerState) ->
alliance_lib:check_state(PlayerState);
push(_ProId, _) ->
ok. |
6d7ecbddc8c33c33ad071f8f56b700490d181feef923e9070139afef5c5c5842 | marcoheisig/simplified-types | simplified-types.lisp | (in-package #:simplified-types)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Simplified Floating-Point Type Specifiers
(defmacro define-floating-point-types ()
(let ((floating-point-types
(remove-duplicates
(list 'short-float 'single-float 'long-float 'double-float)
:test #'alexandria:type=)))
(flet ((find-type (type)
(or (find type floating-point-types :test #'alexandria:type=)
(error "Invalid floating point type: ~S." type))))
`(progn
(deftype simplified-floating-point-type-specifier ()
'(member ,@floating-point-types))
(alexandria:define-constant +short-float-type+ ',(find-type 'short-float))
(alexandria:define-constant +single-float-type+ ',(find-type 'single-float))
(alexandria:define-constant +double-float-type+ ',(find-type 'double-float))
(alexandria:define-constant +long-float-type+ ',(find-type 'long-float))))))
(define-floating-point-types)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Simplified Complex Type Specifiers
(defmacro define-complex-types ()
(let ((complex-types
(remove-duplicates
(list '(complex short-float)
'(complex single-float)
'(complex long-float)
'(complex double-float))
:test #'alexandria:type=)))
(flet ((find-type (type)
(or (find type complex-types :test #'alexandria:type=)
(error "Invalid complex type: ~S." type))))
`(progn
(deftype simplified-complex-type-specifier ()
'(or
(eql t) ; Non-float complex numbers are upgraded to the type T.
(cons
(eql complex)
(cons (or ,@(loop for (nil type) in complex-types collect `(eql ,type)))
null))))
(alexandria:define-constant +complex-short-float-type+ ',(find-type '(complex short-float)) :test 'equal)
(alexandria:define-constant +complex-single-float-type+ ',(find-type '(complex single-float)) :test 'equal)
(alexandria:define-constant +complex-double-float-type+ ',(find-type '(complex double-float)) :test 'equal)
(alexandria:define-constant +complex-long-float-type+ ',(find-type '(complex long-float)) :test 'equal)))))
(define-complex-types)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Simplified Integer Type Specifiers
(deftype simplified-integer-type-specifier ()
'(cons (eql integer)
(cons (or (eql *) integer)
(cons (or (eql *) integer)
null))))
(defvar *precise-integer-types* t
"Whether the lower- and upper-limit of simplified integer type specifiers
should be as accurate as possible, or whether it is permissible that one or
both of them can be upgraded to a wider bound or the symbol *.
When the value of this variable is false, working with simplified types is
guaranteed to be non-consing.")
(defun make-integer-type (lower-limit upper-limit)
(if *precise-integer-types*
`(integer ,lower-limit ,upper-limit)
'(integer * *)))
(define-compiler-macro make-integer-type (&whole whole lower-limit upper-limit)
(if (and (constantp lower-limit)
(constantp upper-limit))
`(load-time-value `(integer ,,lower-limit ,,upper-limit) t)
whole))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
General
(deftype simplified-number-type-specifier ()
'(or
simplified-integer-type-specifier
simplified-floating-point-type-specifier
simplified-complex-type-specifier))
(deftype simplified-type-specifier ()
'(or
(member t function character symbol cons nil)
simplified-number-type-specifier))
| null | https://raw.githubusercontent.com/marcoheisig/simplified-types/8fd0727a70a9de76289ac62c1567b8d278e7434e/code/simplified-types.lisp | lisp |
Simplified Floating-Point Type Specifiers
Simplified Complex Type Specifiers
Non-float complex numbers are upgraded to the type T.
Simplified Integer Type Specifiers
| (in-package #:simplified-types)
(defmacro define-floating-point-types ()
(let ((floating-point-types
(remove-duplicates
(list 'short-float 'single-float 'long-float 'double-float)
:test #'alexandria:type=)))
(flet ((find-type (type)
(or (find type floating-point-types :test #'alexandria:type=)
(error "Invalid floating point type: ~S." type))))
`(progn
(deftype simplified-floating-point-type-specifier ()
'(member ,@floating-point-types))
(alexandria:define-constant +short-float-type+ ',(find-type 'short-float))
(alexandria:define-constant +single-float-type+ ',(find-type 'single-float))
(alexandria:define-constant +double-float-type+ ',(find-type 'double-float))
(alexandria:define-constant +long-float-type+ ',(find-type 'long-float))))))
(define-floating-point-types)
(defmacro define-complex-types ()
(let ((complex-types
(remove-duplicates
(list '(complex short-float)
'(complex single-float)
'(complex long-float)
'(complex double-float))
:test #'alexandria:type=)))
(flet ((find-type (type)
(or (find type complex-types :test #'alexandria:type=)
(error "Invalid complex type: ~S." type))))
`(progn
(deftype simplified-complex-type-specifier ()
'(or
(cons
(eql complex)
(cons (or ,@(loop for (nil type) in complex-types collect `(eql ,type)))
null))))
(alexandria:define-constant +complex-short-float-type+ ',(find-type '(complex short-float)) :test 'equal)
(alexandria:define-constant +complex-single-float-type+ ',(find-type '(complex single-float)) :test 'equal)
(alexandria:define-constant +complex-double-float-type+ ',(find-type '(complex double-float)) :test 'equal)
(alexandria:define-constant +complex-long-float-type+ ',(find-type '(complex long-float)) :test 'equal)))))
(define-complex-types)
(deftype simplified-integer-type-specifier ()
'(cons (eql integer)
(cons (or (eql *) integer)
(cons (or (eql *) integer)
null))))
(defvar *precise-integer-types* t
"Whether the lower- and upper-limit of simplified integer type specifiers
should be as accurate as possible, or whether it is permissible that one or
both of them can be upgraded to a wider bound or the symbol *.
When the value of this variable is false, working with simplified types is
guaranteed to be non-consing.")
(defun make-integer-type (lower-limit upper-limit)
(if *precise-integer-types*
`(integer ,lower-limit ,upper-limit)
'(integer * *)))
(define-compiler-macro make-integer-type (&whole whole lower-limit upper-limit)
(if (and (constantp lower-limit)
(constantp upper-limit))
`(load-time-value `(integer ,,lower-limit ,,upper-limit) t)
whole))
General
(deftype simplified-number-type-specifier ()
'(or
simplified-integer-type-specifier
simplified-floating-point-type-specifier
simplified-complex-type-specifier))
(deftype simplified-type-specifier ()
'(or
(member t function character symbol cons nil)
simplified-number-type-specifier))
|
e9e3c058dc1adfebced3db45afb06bc29973ee72392e9bf8d56ff3ef3b715fa4 | jkoppel/ecta | ECTA.hs | {-# Language OverloadedStrings #-}
module Test.Generators.ECTA () where
import Prelude hiding ( max )
import Control.Monad ( replicateM )
import Data.List ( subsequences, (\\) )
import Test.QuickCheck
import Data.ECTA
import Data.ECTA.Internal.ECTA.Type
import Data.ECTA.Paths
import Data.ECTA.Term
-----------------------------------------------------------------------------------------------
size at 3 whenever you will generate all denotations
_MAX_NODE_DEPTH :: Int
_MAX_NODE_DEPTH = 5
capSize :: Int -> Gen a -> Gen a
capSize max g = sized $ \n -> if n > max then
resize max g
else
g
instance Arbitrary Node where
arbitrary = capSize _MAX_NODE_DEPTH $ sized $ \_n -> do
k <- chooseInt (1, 3) -- TODO: Should this depend on n?
Node <$> replicateM k arbitrary
shrink EmptyNode = []
shrink (Node es) = [Node es' | s <- subsequences es \\ [es], es' <- mapM shrink s] ++ concatMap (\e -> edgeChildren e) es
shrink (Mu _) = []
shrink (Rec _) = []
testEdgeTypes :: [(Symbol, Int)]
testEdgeTypes = [ ("f", 1)
, ("g", 2)
, ("h", 1)
, ("w", 3)
, ("a", 0)
, ("b", 0)
, ("c", 0)
]
testConstants :: [Symbol]
testConstants = map fst $ filter ((== 0) . snd) testEdgeTypes
randPathPair :: [Node] -> Gen [Path]
randPathPair ns = do p1 <- randPath ns
p2 <- randPath ns
return [p1, p2]
randPath :: [Node] -> Gen Path
randPath [] = return EmptyPath
randPath ns = do i <- chooseInt (0, length ns - 1)
let Node es = ns !! i
ns' <- edgeChildren <$> elements es
b <- arbitrary
if b then return (path [i]) else ConsPath i <$> randPath ns'
instance Arbitrary Edge where
arbitrary =
sized $ \n -> case n of
0 -> Edge <$> elements testConstants <*> pure []
_ -> do (sym, arity) <- elements testEdgeTypes
ns <- replicateM arity (resize (n-1) (arbitrary `suchThat` (/= EmptyNode)))
numConstraintPairs <- elements [0,0,1,1,2,3]
ps <- replicateM numConstraintPairs (randPathPair ns)
return $ mkEdge sym ns (mkEqConstraints ps)
shrink e = mkEdge (edgeSymbol e) <$> (mapM shrink (edgeChildren e)) <*> pure (edgeEcs e)
| null | https://raw.githubusercontent.com/jkoppel/ecta/865cf95fea1c875c2732991db6415d963c5d6189/test/Test/Generators/ECTA.hs | haskell | # Language OverloadedStrings #
---------------------------------------------------------------------------------------------
TODO: Should this depend on n? |
module Test.Generators.ECTA () where
import Prelude hiding ( max )
import Control.Monad ( replicateM )
import Data.List ( subsequences, (\\) )
import Test.QuickCheck
import Data.ECTA
import Data.ECTA.Internal.ECTA.Type
import Data.ECTA.Paths
import Data.ECTA.Term
size at 3 whenever you will generate all denotations
_MAX_NODE_DEPTH :: Int
_MAX_NODE_DEPTH = 5
capSize :: Int -> Gen a -> Gen a
capSize max g = sized $ \n -> if n > max then
resize max g
else
g
instance Arbitrary Node where
arbitrary = capSize _MAX_NODE_DEPTH $ sized $ \_n -> do
Node <$> replicateM k arbitrary
shrink EmptyNode = []
shrink (Node es) = [Node es' | s <- subsequences es \\ [es], es' <- mapM shrink s] ++ concatMap (\e -> edgeChildren e) es
shrink (Mu _) = []
shrink (Rec _) = []
testEdgeTypes :: [(Symbol, Int)]
testEdgeTypes = [ ("f", 1)
, ("g", 2)
, ("h", 1)
, ("w", 3)
, ("a", 0)
, ("b", 0)
, ("c", 0)
]
testConstants :: [Symbol]
testConstants = map fst $ filter ((== 0) . snd) testEdgeTypes
randPathPair :: [Node] -> Gen [Path]
randPathPair ns = do p1 <- randPath ns
p2 <- randPath ns
return [p1, p2]
randPath :: [Node] -> Gen Path
randPath [] = return EmptyPath
randPath ns = do i <- chooseInt (0, length ns - 1)
let Node es = ns !! i
ns' <- edgeChildren <$> elements es
b <- arbitrary
if b then return (path [i]) else ConsPath i <$> randPath ns'
instance Arbitrary Edge where
arbitrary =
sized $ \n -> case n of
0 -> Edge <$> elements testConstants <*> pure []
_ -> do (sym, arity) <- elements testEdgeTypes
ns <- replicateM arity (resize (n-1) (arbitrary `suchThat` (/= EmptyNode)))
numConstraintPairs <- elements [0,0,1,1,2,3]
ps <- replicateM numConstraintPairs (randPathPair ns)
return $ mkEdge sym ns (mkEqConstraints ps)
shrink e = mkEdge (edgeSymbol e) <$> (mapM shrink (edgeChildren e)) <*> pure (edgeEcs e)
|
bbb99bf81ef8e0cf142ad74adfb327e982f7d58c399960f21f6cb200b92c1227 | robertmeta/cowboy-examples | hello_world_rest_handler.erl | -module(hello_world_rest_handler).
-export([init/3, content_types_provided/2, get_text_plain/2]).
init(_Transport, _Req, _Opts) ->
{upgrade, protocol, cowboy_http_rest}.
content_types_provided(Req, State) ->
{[{{<<"text">>, <<"plain">>, []}, get_text_plain}], Req, State}.
get_text_plain(Req, State) ->
{<<"This is REST!">>, Req, State}.
| null | https://raw.githubusercontent.com/robertmeta/cowboy-examples/d03c289c9fb0d750eca11e3f1671e74d1841bd09/apps/hello_world_rest/src/hello_world_rest_handler.erl | erlang | -module(hello_world_rest_handler).
-export([init/3, content_types_provided/2, get_text_plain/2]).
init(_Transport, _Req, _Opts) ->
{upgrade, protocol, cowboy_http_rest}.
content_types_provided(Req, State) ->
{[{{<<"text">>, <<"plain">>, []}, get_text_plain}], Req, State}.
get_text_plain(Req, State) ->
{<<"This is REST!">>, Req, State}.
| |
7df7854b961f5109ea63359b7815f2948b3ebbffa931be7072a255f5d857216f | static-analysis-engineering/codehawk | jCHLoopCostAbstractor.ml | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author :
------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2020 Kestrel Technology LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author: Anca Browne
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2020 Kestrel Technology LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
chlib
open CHLanguage
open CHNumerical
open CHPretty
(* chutil *)
open CHUtils
open CHPrettyUtil
module H = Hashtbl
module LF = CHOnlineCodeSet.LanguageFactory
let make_label pc = new symbol_t (string_of_int pc)
let loophead_to_incoming = ref (new IntCollections.table_t)
let remove_loops
(cost_chif:procedure_int)
(loopstructure: CHLoopStructure.loop_structure_int):procedure_int =
loophead_to_incoming := new IntCollections.table_t ;
let cfg =
match cost_chif#getBody#getCmdAt 0 with
| CFG (_, cfg) -> cfg
| _ -> raise (JCHBasicTypes.JCH_failure (STR "expected CFG")) in
let transform_state (state_name: symbol_t) : state_int =
let state = cfg#getState state_name in
let get_loophead =
try
let pc = int_of_string state_name#getBaseName in
if loopstructure#is_loophead pc then Some pc
else None
with _ -> None in
match get_loophead with
| Some hpc ->
let new_state = LF.mkState state_name state#getCode in
let loop_edges = ref [] in
let is_not_inloop s =
try
let pc = int_of_string s#getBaseName in
if loopstructure#is_inloop_with_loophead pc hpc then
begin
loop_edges := s :: !loop_edges ;
false
end
else true
with _ -> true in
let new_incoming_edges =
List.filter is_not_inloop state#getIncomingEdges in
!loophead_to_incoming#set hpc (SymbolCollections.set_of_list !loop_edges);
List.iter new_state#addIncomingEdge new_incoming_edges ;
new_state
| _ ->
let new_state = LF.mkState state_name state#getCode in
List.iter new_state#addIncomingEdge state#getIncomingEdges ;
new_state in
let states = List.map transform_state cfg#getStates in
let add_out (state: state_int) (state'_name: symbol_t) =
let state' : state_int =
List.find (fun s -> s#getLabel#equal state'_name) states in
state'#addOutgoingEdge state#getLabel in
List.iter (fun state ->
List.iter (add_out state) state#getIncomingEdges) states ;
let new_cfg = LF.mkCFG cfg#getEntry cfg#getExit in
new_cfg#addStates states ;
let new_body = LF.mkCode [CFG (cost_chif#getName, new_cfg)] in
LF.mkProcedure
cost_chif#getName
~signature:[]
~bindings:[]
~scope:cost_chif#getScope
~body:new_body
let reduce_to_loop
(cost_chif: procedure_int)
(cvar: variable_t)
(bvar: variable_t)
(hpc: int)
(pcs: int list) : procedure_int =
let cfg =
match cost_chif#getBody#getCmdAt 0 with
| CFG (_, cfg) -> cfg
| _ -> raise (JCHBasicTypes.JCH_failure (STR "expected CFG")) in
let loop_scope = cost_chif#getScope in
let entry_name = new symbol_t "entry" in
let exit_name = new symbol_t "exit" in
let loop_state_name = make_label hpc in
let initassign =
OPERATION ({op_name = new symbol_t ~atts:["0"] "set_to_0" ;
op_args = [("dst", cvar, WRITE)] }) in
let invop =
OPERATION ( { op_name = new symbol_t ~atts:["methodexit"] "invariant" ;
op_args = [("cvar", cvar, READ_WRITE)] }) in
let entry_state = LF.mkState entry_name (LF.mkCode [initassign]) in
let exit_state = LF.mkState exit_name (LF.mkCode [invop]) in
let loop_cfg = LF.mkCFG entry_state exit_state in
let is_in_pcs s =
let pc = int_of_string s#getBaseName in
List.mem pc pcs in
let rec work first state_names new_state_names =
match new_state_names with
| new_state_name :: rest_new_state_names ->
if List.mem new_state_name#getBaseName state_names then
begin
work false state_names rest_new_state_names
end
else
begin
let state = cfg#getState new_state_name in
let new_state = LF.mkState new_state_name state#getCode in
loop_cfg#addState new_state ;
let new_ins =
if first then
match !loophead_to_incoming#get hpc with
| Some set -> set#toList
| _ -> []
else
begin
List.filter is_in_pcs state#getIncomingEdges
end in
if first then
begin
List.iter (fun s -> exit_state#addIncomingEdge s) new_ins ;
new_state#addIncomingEdge entry_name
end
else
List.iter (fun s -> new_state#addIncomingEdge s) new_ins;
work false (new_state_name#getBaseName :: state_names)
(List.rev_append rest_new_state_names new_ins) ;
end
| [] -> () in
work
true [entry_name#getBaseName; exit_name#getBaseName] [loop_state_name] ;
let add_out_edges new_state_name =
let new_state = loop_cfg#getState new_state_name in
let add_out_edge s =
let new_s = loop_cfg#getState s in
new_s#addOutgoingEdge new_state_name in
List.iter add_out_edge new_state#getIncomingEdges in
List.iter add_out_edges loop_cfg#getStates;
let loop_procname =
new symbol_t (cost_chif#getName#getBaseName^"_loop_"^(string_of_int hpc)) in
let loop_body = LF.mkCode [CFG (loop_procname, loop_cfg)] in
LF.mkProcedure
loop_procname
~signature:[]
~bindings:[]
~scope:loop_scope
~body:loop_body
let remove_dead_end_states
(cost_chif: procedure_int)
(loopstructure: CHLoopStructure.loop_structure_int) =
let not_in_loop state_name =
try
let pc = int_of_string state_name#getBaseName in
not (loopstructure#is_inloop pc)
|| (loopstructure#is_loophead pc) && (loopstructure#get_nesting_level pc = 1)
with _ -> true in
let cfg =
match cost_chif#getBody#getCmdAt 0 with
| CFG (_, cfg) -> cfg
| _ -> raise (JCHBasicTypes.JCH_failure (STR "expected CFG")) in
let states_not_in_loops = List.filter not_in_loop cfg#getStates in
let new_states = ref [] in
let new_state_names = ref [] in
let rec work state_names =
match state_names with
| state_name :: rest_state_names ->
let state_name_str = state_name#getBaseName in
if List.mem state_name_str !new_state_names then work rest_state_names
else
begin
let state = cfg#getState state_name in
let new_state = LF.mkState state_name state#getCode in
new_states := new_state :: !new_states ;
new_state_names := state_name_str :: !new_state_names ;
let ins = state#getIncomingEdges in
List.iter (fun s -> new_state#addIncomingEdge s) ins;
work (List.rev_append rest_state_names ins)
end
| _ -> () in
work states_not_in_loops ;
let add_out (state: state_int) (state'_name: symbol_t) =
let state':state_int =
List.find (fun s -> s#getLabel#equal state'_name) !new_states in
state'#addOutgoingEdge state#getLabel in
List.iter
(fun state -> List.iter (add_out state) state#getIncomingEdges) !new_states ;
let new_cfg = LF.mkCFG cfg#getEntry cfg#getExit in
new_cfg#addStates !new_states ;
let new_body = LF.mkCode [CFG (cost_chif#getName, new_cfg)] in
LF.mkProcedure
cost_chif#getName
~signature:[]
~bindings:[]
~scope:cost_chif#getScope
~body:new_body
| null | https://raw.githubusercontent.com/static-analysis-engineering/codehawk/98ced4d5e6d7989575092df232759afc2cb851f6/CodeHawk/CHJ/jchcost/jCHLoopCostAbstractor.ml | ocaml | chutil | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author :
------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2020 Kestrel Technology LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author: Anca Browne
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2020 Kestrel Technology LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
chlib
open CHLanguage
open CHNumerical
open CHPretty
open CHUtils
open CHPrettyUtil
module H = Hashtbl
module LF = CHOnlineCodeSet.LanguageFactory
let make_label pc = new symbol_t (string_of_int pc)
let loophead_to_incoming = ref (new IntCollections.table_t)
let remove_loops
(cost_chif:procedure_int)
(loopstructure: CHLoopStructure.loop_structure_int):procedure_int =
loophead_to_incoming := new IntCollections.table_t ;
let cfg =
match cost_chif#getBody#getCmdAt 0 with
| CFG (_, cfg) -> cfg
| _ -> raise (JCHBasicTypes.JCH_failure (STR "expected CFG")) in
let transform_state (state_name: symbol_t) : state_int =
let state = cfg#getState state_name in
let get_loophead =
try
let pc = int_of_string state_name#getBaseName in
if loopstructure#is_loophead pc then Some pc
else None
with _ -> None in
match get_loophead with
| Some hpc ->
let new_state = LF.mkState state_name state#getCode in
let loop_edges = ref [] in
let is_not_inloop s =
try
let pc = int_of_string s#getBaseName in
if loopstructure#is_inloop_with_loophead pc hpc then
begin
loop_edges := s :: !loop_edges ;
false
end
else true
with _ -> true in
let new_incoming_edges =
List.filter is_not_inloop state#getIncomingEdges in
!loophead_to_incoming#set hpc (SymbolCollections.set_of_list !loop_edges);
List.iter new_state#addIncomingEdge new_incoming_edges ;
new_state
| _ ->
let new_state = LF.mkState state_name state#getCode in
List.iter new_state#addIncomingEdge state#getIncomingEdges ;
new_state in
let states = List.map transform_state cfg#getStates in
let add_out (state: state_int) (state'_name: symbol_t) =
let state' : state_int =
List.find (fun s -> s#getLabel#equal state'_name) states in
state'#addOutgoingEdge state#getLabel in
List.iter (fun state ->
List.iter (add_out state) state#getIncomingEdges) states ;
let new_cfg = LF.mkCFG cfg#getEntry cfg#getExit in
new_cfg#addStates states ;
let new_body = LF.mkCode [CFG (cost_chif#getName, new_cfg)] in
LF.mkProcedure
cost_chif#getName
~signature:[]
~bindings:[]
~scope:cost_chif#getScope
~body:new_body
let reduce_to_loop
(cost_chif: procedure_int)
(cvar: variable_t)
(bvar: variable_t)
(hpc: int)
(pcs: int list) : procedure_int =
let cfg =
match cost_chif#getBody#getCmdAt 0 with
| CFG (_, cfg) -> cfg
| _ -> raise (JCHBasicTypes.JCH_failure (STR "expected CFG")) in
let loop_scope = cost_chif#getScope in
let entry_name = new symbol_t "entry" in
let exit_name = new symbol_t "exit" in
let loop_state_name = make_label hpc in
let initassign =
OPERATION ({op_name = new symbol_t ~atts:["0"] "set_to_0" ;
op_args = [("dst", cvar, WRITE)] }) in
let invop =
OPERATION ( { op_name = new symbol_t ~atts:["methodexit"] "invariant" ;
op_args = [("cvar", cvar, READ_WRITE)] }) in
let entry_state = LF.mkState entry_name (LF.mkCode [initassign]) in
let exit_state = LF.mkState exit_name (LF.mkCode [invop]) in
let loop_cfg = LF.mkCFG entry_state exit_state in
let is_in_pcs s =
let pc = int_of_string s#getBaseName in
List.mem pc pcs in
let rec work first state_names new_state_names =
match new_state_names with
| new_state_name :: rest_new_state_names ->
if List.mem new_state_name#getBaseName state_names then
begin
work false state_names rest_new_state_names
end
else
begin
let state = cfg#getState new_state_name in
let new_state = LF.mkState new_state_name state#getCode in
loop_cfg#addState new_state ;
let new_ins =
if first then
match !loophead_to_incoming#get hpc with
| Some set -> set#toList
| _ -> []
else
begin
List.filter is_in_pcs state#getIncomingEdges
end in
if first then
begin
List.iter (fun s -> exit_state#addIncomingEdge s) new_ins ;
new_state#addIncomingEdge entry_name
end
else
List.iter (fun s -> new_state#addIncomingEdge s) new_ins;
work false (new_state_name#getBaseName :: state_names)
(List.rev_append rest_new_state_names new_ins) ;
end
| [] -> () in
work
true [entry_name#getBaseName; exit_name#getBaseName] [loop_state_name] ;
let add_out_edges new_state_name =
let new_state = loop_cfg#getState new_state_name in
let add_out_edge s =
let new_s = loop_cfg#getState s in
new_s#addOutgoingEdge new_state_name in
List.iter add_out_edge new_state#getIncomingEdges in
List.iter add_out_edges loop_cfg#getStates;
let loop_procname =
new symbol_t (cost_chif#getName#getBaseName^"_loop_"^(string_of_int hpc)) in
let loop_body = LF.mkCode [CFG (loop_procname, loop_cfg)] in
LF.mkProcedure
loop_procname
~signature:[]
~bindings:[]
~scope:loop_scope
~body:loop_body
let remove_dead_end_states
(cost_chif: procedure_int)
(loopstructure: CHLoopStructure.loop_structure_int) =
let not_in_loop state_name =
try
let pc = int_of_string state_name#getBaseName in
not (loopstructure#is_inloop pc)
|| (loopstructure#is_loophead pc) && (loopstructure#get_nesting_level pc = 1)
with _ -> true in
let cfg =
match cost_chif#getBody#getCmdAt 0 with
| CFG (_, cfg) -> cfg
| _ -> raise (JCHBasicTypes.JCH_failure (STR "expected CFG")) in
let states_not_in_loops = List.filter not_in_loop cfg#getStates in
let new_states = ref [] in
let new_state_names = ref [] in
let rec work state_names =
match state_names with
| state_name :: rest_state_names ->
let state_name_str = state_name#getBaseName in
if List.mem state_name_str !new_state_names then work rest_state_names
else
begin
let state = cfg#getState state_name in
let new_state = LF.mkState state_name state#getCode in
new_states := new_state :: !new_states ;
new_state_names := state_name_str :: !new_state_names ;
let ins = state#getIncomingEdges in
List.iter (fun s -> new_state#addIncomingEdge s) ins;
work (List.rev_append rest_state_names ins)
end
| _ -> () in
work states_not_in_loops ;
let add_out (state: state_int) (state'_name: symbol_t) =
let state':state_int =
List.find (fun s -> s#getLabel#equal state'_name) !new_states in
state'#addOutgoingEdge state#getLabel in
List.iter
(fun state -> List.iter (add_out state) state#getIncomingEdges) !new_states ;
let new_cfg = LF.mkCFG cfg#getEntry cfg#getExit in
new_cfg#addStates !new_states ;
let new_body = LF.mkCode [CFG (cost_chif#getName, new_cfg)] in
LF.mkProcedure
cost_chif#getName
~signature:[]
~bindings:[]
~scope:cost_chif#getScope
~body:new_body
|
b68dd2203af04ce42d98cac8090952a5aec8e706d71c01f7c9434ddb120d2e3a | channable/icepeak | Main.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
module Main (main) where
import Control.Exception (fromException, catch, handle, AsyncException, SomeException)
import Control.Monad (forM, void, when)
import Data.Foldable (forM_)
import Options.Applicative (execParser)
import System.Environment (getEnvironment)
import System.IO (BufferMode (..), hSetBuffering, stdout)
import qualified Control.Concurrent.Async as Async
import qualified Data.Text as Text
import qualified Prometheus
import qualified Prometheus.Metric.GHC
import qualified System.Posix.Signals as Signals
import Config (Config (..), configInfo)
import Core (Core (..))
import Persistence (getDataFile, setupStorageBackend)
import Logger (Logger, LogLevel(..), postLog)
import qualified Core
import qualified HttpServer
import qualified Server
import qualified WebsocketServer
import qualified Logger
import qualified Metrics
import qualified MetricsServer
-- Install SIGTERM and SIGINT handlers to do a graceful exit.
installHandlers :: Core -> IO ()
installHandlers core =
let
logHandle = do
postLog (coreLogger core) LogInfo "\nTermination sequence initiated ..."
Core.postQuit core
handler = Signals.CatchOnce logHandle
blockSignals = Nothing
installHandler signal = Signals.installHandler signal handler blockSignals
in do
void $ installHandler Signals.sigTERM
void $ installHandler Signals.sigINT
main :: IO ()
main = do
-- make sure output is flushed regularly
hSetBuffering stdout LineBuffering
env <- getEnvironment
config <- execParser (configInfo env)
-- make sure the storage file exists and that it has the right format - otherwise, fail early
let dataFile = getDataFile (configStorageBackend config) (configDataFile config)
setupStorageBackend (configStorageBackend config) dataFile
-- start logging as early as possible
logger <- Logger.newLogger config
loggerThread <- Async.async $ Logger.processLogRecords logger
handle (\e -> postLog logger LogError . Text.pack . show $ (e :: SomeException)) $ do
-- setup metrics if enabled
icepeakMetrics <- forM (configMetricsEndpoint config) $ const $ do
void $ Prometheus.register Prometheus.Metric.GHC.ghcMetrics
Metrics.createAndRegisterIcepeakMetrics
eitherCore <- Core.newCore config logger icepeakMetrics
either (postLog logger LogError . Text.pack) runCore eitherCore
-- only stop logging when everything else has stopped
Logger.postStop logger
Async.wait loggerThread
runCore :: Core -> IO ()
runCore core = do
let config = coreConfig core
let logger = coreLogger core
httpServer <- HttpServer.new core
let wsServer = WebsocketServer.acceptConnection core
-- start threads
commandLoopThread <- Async.async $ catchRunCoreResult CommandLoopException $ Core.runCommandLoop core
webSocketThread <- Async.async $ catchRunCoreResult WebSocketsException $ WebsocketServer.processUpdates core
httpThread <- Async.async $ catchRunCoreResult HttpException $ Server.runServer logger wsServer httpServer (configPort config)
syncThread <- Async.async $ Core.runSyncTimer core
metricsThread <- Async.async
$ forM_ (configMetricsEndpoint config) (MetricsServer.runMetricsServer logger)
installHandlers core
logAuthSettings config logger
logQueueSettings config logger
logSyncSettings config logger
postLog logger LogInfo "System online. ** robot sounds **"
-- Everything should stop when any of these stops
(_, runCoreResult) <- Async.waitAny [commandLoopThread, webSocketThread, httpThread]
logRunCoreResult logger runCoreResult
kill all threads when one of the main threads ended
should stop commandLoopThread
Async.cancel webSocketThread
Async.cancel httpThread
Async.cancel metricsThread
Async.cancel syncThread
void $ Async.wait commandLoopThread
| Data type to hold results for the async that finishes first
data RunCoreResult
= CommandLoopException SomeException
| WebSocketsException SomeException
| HttpException SomeException
| ThreadOk
-- | If a threads fails, catch the error and tag it so we know how to log it
catchRunCoreResult :: (SomeException -> RunCoreResult) -> IO () -> IO RunCoreResult
catchRunCoreResult tag action = catch (action >> pure ThreadOk) $ \exc -> case fromException exc of
Just (_ :: AsyncException) -> pure ThreadOk
_ -> pure (tag exc) -- we only worry about non-async exceptions
logRunCoreResult :: Logger -> RunCoreResult -> IO ()
logRunCoreResult logger rcr = do
case rcr of
CommandLoopException exc -> handleLog "core" exc
WebSocketsException exc -> handleLog "web sockets server" exc
HttpException exc -> handleLog "http server" exc
ThreadOk -> pure ()
where
handleLog name exc
| Just (_ :: AsyncException) <- fromException exc = pure ()
| otherwise = do
Logger.postLog logger LogError $ name <> " stopped with an exception: " <> Text.pack (show exc)
logAuthSettings :: Config -> Logger -> IO ()
logAuthSettings cfg logger
| configEnableJwtAuth cfg = case configJwtSecret cfg of
Just _ -> postLog logger LogInfo "JWT authorization enabled and secret provided, tokens will be verified."
Nothing -> postLog logger LogInfo "JWT authorization enabled but no secret provided, tokens will NOT be verified."
| otherwise = case configJwtSecret cfg of
Just _ -> postLog logger LogInfo "WARNING a JWT secret has been provided, but JWT authorization is disabled."
Nothing -> postLog logger LogInfo "JWT authorization disabled."
logQueueSettings :: Config -> Logger -> IO ()
logQueueSettings cfg logger =
postLog logger LogInfo ("Queue capacity is set to " <> Text.pack (show (configQueueCapacity cfg)) <> ".")
logSyncSettings :: Config -> Logger -> IO ()
logSyncSettings cfg logger = case configSyncIntervalMicroSeconds cfg of
Nothing -> do
postLog logger LogInfo "Sync: Persisting after every modification"
when (configEnableJournaling cfg) $ do
postLog logger LogInfo "Journaling has no effect when periodic syncing is disabled"
Just musecs -> do
postLog logger LogInfo ("Sync: every " <> Text.pack (show musecs) <> " microseconds.")
when (configEnableJournaling cfg) $ do
postLog logger LogInfo "Journaling enabled"
| null | https://raw.githubusercontent.com/channable/icepeak/46eaa1cad65a97adad87a1b36cbec5d98fffd0b9/server/app/Icepeak/Main.hs | haskell | # LANGUAGE OverloadedStrings #
Install SIGTERM and SIGINT handlers to do a graceful exit.
make sure output is flushed regularly
make sure the storage file exists and that it has the right format - otherwise, fail early
start logging as early as possible
setup metrics if enabled
only stop logging when everything else has stopped
start threads
Everything should stop when any of these stops
| If a threads fails, catch the error and tag it so we know how to log it
we only worry about non-async exceptions | # LANGUAGE ScopedTypeVariables #
module Main (main) where
import Control.Exception (fromException, catch, handle, AsyncException, SomeException)
import Control.Monad (forM, void, when)
import Data.Foldable (forM_)
import Options.Applicative (execParser)
import System.Environment (getEnvironment)
import System.IO (BufferMode (..), hSetBuffering, stdout)
import qualified Control.Concurrent.Async as Async
import qualified Data.Text as Text
import qualified Prometheus
import qualified Prometheus.Metric.GHC
import qualified System.Posix.Signals as Signals
import Config (Config (..), configInfo)
import Core (Core (..))
import Persistence (getDataFile, setupStorageBackend)
import Logger (Logger, LogLevel(..), postLog)
import qualified Core
import qualified HttpServer
import qualified Server
import qualified WebsocketServer
import qualified Logger
import qualified Metrics
import qualified MetricsServer
installHandlers :: Core -> IO ()
installHandlers core =
let
logHandle = do
postLog (coreLogger core) LogInfo "\nTermination sequence initiated ..."
Core.postQuit core
handler = Signals.CatchOnce logHandle
blockSignals = Nothing
installHandler signal = Signals.installHandler signal handler blockSignals
in do
void $ installHandler Signals.sigTERM
void $ installHandler Signals.sigINT
main :: IO ()
main = do
hSetBuffering stdout LineBuffering
env <- getEnvironment
config <- execParser (configInfo env)
let dataFile = getDataFile (configStorageBackend config) (configDataFile config)
setupStorageBackend (configStorageBackend config) dataFile
logger <- Logger.newLogger config
loggerThread <- Async.async $ Logger.processLogRecords logger
handle (\e -> postLog logger LogError . Text.pack . show $ (e :: SomeException)) $ do
icepeakMetrics <- forM (configMetricsEndpoint config) $ const $ do
void $ Prometheus.register Prometheus.Metric.GHC.ghcMetrics
Metrics.createAndRegisterIcepeakMetrics
eitherCore <- Core.newCore config logger icepeakMetrics
either (postLog logger LogError . Text.pack) runCore eitherCore
Logger.postStop logger
Async.wait loggerThread
runCore :: Core -> IO ()
runCore core = do
let config = coreConfig core
let logger = coreLogger core
httpServer <- HttpServer.new core
let wsServer = WebsocketServer.acceptConnection core
commandLoopThread <- Async.async $ catchRunCoreResult CommandLoopException $ Core.runCommandLoop core
webSocketThread <- Async.async $ catchRunCoreResult WebSocketsException $ WebsocketServer.processUpdates core
httpThread <- Async.async $ catchRunCoreResult HttpException $ Server.runServer logger wsServer httpServer (configPort config)
syncThread <- Async.async $ Core.runSyncTimer core
metricsThread <- Async.async
$ forM_ (configMetricsEndpoint config) (MetricsServer.runMetricsServer logger)
installHandlers core
logAuthSettings config logger
logQueueSettings config logger
logSyncSettings config logger
postLog logger LogInfo "System online. ** robot sounds **"
(_, runCoreResult) <- Async.waitAny [commandLoopThread, webSocketThread, httpThread]
logRunCoreResult logger runCoreResult
kill all threads when one of the main threads ended
should stop commandLoopThread
Async.cancel webSocketThread
Async.cancel httpThread
Async.cancel metricsThread
Async.cancel syncThread
void $ Async.wait commandLoopThread
| Data type to hold results for the async that finishes first
data RunCoreResult
= CommandLoopException SomeException
| WebSocketsException SomeException
| HttpException SomeException
| ThreadOk
catchRunCoreResult :: (SomeException -> RunCoreResult) -> IO () -> IO RunCoreResult
catchRunCoreResult tag action = catch (action >> pure ThreadOk) $ \exc -> case fromException exc of
Just (_ :: AsyncException) -> pure ThreadOk
logRunCoreResult :: Logger -> RunCoreResult -> IO ()
logRunCoreResult logger rcr = do
case rcr of
CommandLoopException exc -> handleLog "core" exc
WebSocketsException exc -> handleLog "web sockets server" exc
HttpException exc -> handleLog "http server" exc
ThreadOk -> pure ()
where
handleLog name exc
| Just (_ :: AsyncException) <- fromException exc = pure ()
| otherwise = do
Logger.postLog logger LogError $ name <> " stopped with an exception: " <> Text.pack (show exc)
logAuthSettings :: Config -> Logger -> IO ()
logAuthSettings cfg logger
| configEnableJwtAuth cfg = case configJwtSecret cfg of
Just _ -> postLog logger LogInfo "JWT authorization enabled and secret provided, tokens will be verified."
Nothing -> postLog logger LogInfo "JWT authorization enabled but no secret provided, tokens will NOT be verified."
| otherwise = case configJwtSecret cfg of
Just _ -> postLog logger LogInfo "WARNING a JWT secret has been provided, but JWT authorization is disabled."
Nothing -> postLog logger LogInfo "JWT authorization disabled."
logQueueSettings :: Config -> Logger -> IO ()
logQueueSettings cfg logger =
postLog logger LogInfo ("Queue capacity is set to " <> Text.pack (show (configQueueCapacity cfg)) <> ".")
logSyncSettings :: Config -> Logger -> IO ()
logSyncSettings cfg logger = case configSyncIntervalMicroSeconds cfg of
Nothing -> do
postLog logger LogInfo "Sync: Persisting after every modification"
when (configEnableJournaling cfg) $ do
postLog logger LogInfo "Journaling has no effect when periodic syncing is disabled"
Just musecs -> do
postLog logger LogInfo ("Sync: every " <> Text.pack (show musecs) <> " microseconds.")
when (configEnableJournaling cfg) $ do
postLog logger LogInfo "Journaling enabled"
|
b004e9fee41be9b3ae24e95fc983f1ce4f5ec2dfd58fe61513029fb4f750a91b | serokell/universum | String.hs | {-# LANGUAGE Safe #-}
-- | Type classes for convertion between different string representations.
module Universum.String
( module Universum.String.Conversion
, module Universum.String.Reexport
) where
import Universum.String.Conversion
import Universum.String.Reexport
| null | https://raw.githubusercontent.com/serokell/universum/7fc5dd3951d1177d1873e36b0678c759aeb5dc08/src/Universum/String.hs | haskell | # LANGUAGE Safe #
| Type classes for convertion between different string representations. |
module Universum.String
( module Universum.String.Conversion
, module Universum.String.Reexport
) where
import Universum.String.Conversion
import Universum.String.Reexport
|
261258b10ae7b9c6568be1b55f8fcc3f65fa9b1d7ba6cdf211c20c83c84266b3 | TorXakis/TorXakis | RandIncrementBins.hs |
TorXakis - Model Based Testing
Copyright ( c ) 2015 - 2017 TNO and Radboud University
See LICENSE at root directory of this repository .
TorXakis - Model Based Testing
Copyright (c) 2015-2017 TNO and Radboud University
See LICENSE at root directory of this repository.
-}
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
module RandIncrementBins
-- ----------------------------------------------------------------------------------------- --
--
Module RandIncrementBins : Randomization of SMT solutions
Solving by incrementally fixing one variable at a time
-- When the variable can be changed,
-- bins are created and shuffled to find a random solution.
--
-- ----------------------------------------------------------------------------------------- --
-- export
( randValExprsSolveIncrementBins
, ParamIncrementBins (..)
)
where
-- ----------------------------------------------------------------------------------------- --
-- import
import Control.Monad.State
import qualified Data.Char as Char
import qualified Data.Map as Map
import Data.Maybe
import Data.Monoid
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import System.IO
import System.Random
import System.Random.Shuffle
import Constant
import CstrDef
import CstrId
import FuncId
import SMT
import SMTData
import Solve.Params
import SolveDefs
import SortId
import SortOf
import ValExpr
import Variable
data ParamIncrementBins =
ParamIncrementBins { maxDepth :: Int
, next :: Next
, nrOfBins :: Int
}
deriving (Eq,Ord,Read,Show)
-- ---------------------------
step :: Integer
step = 10
nextFunction :: ParamIncrementBins -> Integer -> Integer
nextFunction p =
case RandIncrementBins.next p of
Linear -> (step +)
Power -> (step *)
Exponent -> nextExponent
nextExponent :: Integer -> Integer
nextExponent n = n * n
mkRanges :: (Integer -> Integer) -> Integer -> Integer -> [(Integer, Integer)]
mkRanges nxt lw hgh = (lw, hgh-1): mkRanges nxt hgh (nxt hgh)
basicIntRanges :: ParamIncrementBins -> [(Integer, Integer)]
basicIntRanges p = take (nrOfBins p) (mkRanges (nextFunction p) 0 step)
basicStringLengthRanges :: [(Integer, Integer)]
basicStringLengthRanges = take 3 (mkRanges (3*) 0 3)
-- from ascending boundary values make intervals
mkIntConstraintBins :: forall v. Ord v => ValExpr v -> [Integer] -> [ValExpr v]
mkIntConstraintBins _ [] = [cstrConst (Cbool True)] -- no boundary values, single interval
mkIntConstraintBins v l@(x:_) = cstrLE v (cstrConst (Cint x)) : mkRestBins l
where
mkRestBins :: Ord v => [Integer] -> [ValExpr v]
mkRestBins [y] = [cstrLT (cstrConst (Cint y)) v]
mkRestBins (y1:y2:ys) = cstrAnd ( Set.fromList [cstrLT (cstrConst (Cint y1)) v, cstrLE v (cstrConst (Cint y2)) ] ) : mkRestBins (y2:ys)
mkRestBins [] = error "mkIntConstraintBins - Should not happen - at least one element in mkRestBins"
mkRndIntBins :: Ord v => ParamIncrementBins -> ValExpr v -> IO [ValExpr v]
mkRndIntBins p v = do
neg <- mapM randomRIO (basicIntRanges p) -- faster to reuse the same bins for positive and negative?
pos <- mapM randomRIO (basicIntRanges p)
let boundaryValues = reverse (map negate neg) ++ pos
bins = mkIntConstraintBins v boundaryValues
shuffleM bins
findRndValue :: Variable v => v -> [ValExpr v] -> SMT Constant
findRndValue _ [] = error "findRndValue - Solution exists, yet no solution found in all bins"
findRndValue v (x:xs) = do
push
addAssertions [x]
sat <- getSolvable
case sat of
Sat -> do
sol <- getSolution [v]
pop
let val = fromMaybe (error "findRndValue - SMT hasn't returned the value of requested variable.")
(Map.lookup v sol)
return val
_ -> do
pop
findRndValue v xs
-- ----------------------------------------------------------------------------------------- --
-- give a random solution for constraint vexps with free variables vars
randValExprsSolveIncrementBins :: (Variable v) => ParamIncrementBins -> [v] -> [ValExpr v] -> SMT (SolveProblem v)
randValExprsSolveIncrementBins p freevars exprs =
-- if not all constraints are of type boolean: stop, otherwise solve the constraints
if all ( (sortIdBool == ) . sortOf ) exprs
then do
push
addDeclarations freevars
addAssertions exprs
sat <- getSolvable
sp <- case sat of
Sat -> do
shuffledVars <- shuffleM freevars
randomSolve p (zip shuffledVars (map (const (maxDepth p)) [1::Integer .. ]) ) 0
sat2 <- getSolvable
case sat2 of
Sat -> Solved <$> getSolution freevars
_ -> do
lift $ hPutStrLn stderr "TXS RandIncrementBins randValExprsSolveIncrementBins: Problem no longer solvable\n"
return UnableToSolve
Unsat -> return Unsolvable
Unknown -> return UnableToSolve
pop
return sp
else do
lift $ hPutStrLn stderr "TXS RandIncrementBins randValExprsSolveIncrementBins: Not all added constraints are Bool\n"
return UnableToSolve
toRegexString :: Int -> Text
toRegexString 45 = "\\-"
toRegexString 91 = "\\["
toRegexString 92 = "\\\\"
toRegexString 93 = "\\]"
toRegexString 94 = "\\^"
toRegexString c = T.singleton (Char.chr c)
-- * configuration parameters
-- * List of tuples of (Variable, Depth)
-- * available variable id
randomSolve :: Variable v => ParamIncrementBins -> [(v, Int)] -> Int -> SMT ()
randomSolve _ [] _ = return () -- empty list -> done
randomSolve _ ((_,0):_) _ = error "At maximum depth: should not be added"
randomSolve p vs@((v,_):xs) i = do
sat <- getSolvable
case sat of
Sat -> do
sol <- getSolution [v]
let val = fromMaybe (error "randomSolve - SMT hasn't returned the value of requested variable.")
(Map.lookup v sol)
push
addAssertions [ cstrNot ( cstrEqual (cstrVar v) (cstrConst val) ) ]
sat2 <- getSolvable
pop
case sat2 of
Sat -> randomSolveBins p vs i
_ -> do
addAssertions [ cstrEqual (cstrVar v) (cstrConst val) ]
randomSolve p xs i
_ -> error "randomSolve - Unexpected SMT issue - previous solution is no longer valid"
randomSolveBins :: Variable v => ParamIncrementBins -> [(v, Int)] -> Int -> SMT ()
randomSolveBins _ [] _ = error "randomSolveBins - should always be called with no empty list"
randomSolveBins p ((v,_):xs) i | vsort v == sortIdBool =
since the variable can be changed both values are possible : pick one and be done
do
b <- liftIO randomIO
addAssertions [ cstrEqual (cstrVar v) (cstrConst (Cbool b) ) ]
randomSolve p xs i
randomSolveBins p ((v,_):xs) i | vsort v == sortIdInt =
do
rndBins <- liftIO $ mkRndIntBins p (cstrVar v)
val@Cint{} <- findRndValue v rndBins
addAssertions [ cstrEqual (cstrVar v) (cstrConst val) ]
randomSolve p xs i
randomSolveBins p ((v,-123):xs) i | vsort v == sortIdString = -- abuse depth to encode char versus string
let nrofChars :: Int
nrofChars = 256 -- nrofChars == nrOfRanges * nrofCharsInRange
nrOfRanges :: Int
nrOfRanges = 8
nrofCharsInRange :: Int
nrofCharsInRange = 32
low :: Int
low = 0
high :: Int
high = nrofChars -1
boundaries :: [Int]
boundaries = take (nrOfRanges-1) [0, nrofCharsInRange .. ]
in do
offset <- liftIO $ randomRIO (0,nrofCharsInRange-1)
let rndBins = case offset of
0 -> map ( toConstraint v . toCharGroup . (\b -> toCharRange b (b+nrofCharsInRange-1)) ) (nrofChars-nrofCharsInRange:boundaries)
1 -> map ( toConstraint v . toCharGroup ) ( toCharRange (nrofChars - nrofCharsInRange + 1) high <> toRegexString low
: map (\b -> toCharRange (b+1) (b+nrofCharsInRange)) boundaries
)
n | n == nrofCharsInRange -1 -> map ( toConstraint v . toCharGroup ) ( toRegexString high <> toCharRange low (nrofCharsInRange-2)
: map ( (\b -> toCharRange b (b+nrofCharsInRange-1)) . (offset+) ) boundaries
)
_ -> map ( toConstraint v . toCharGroup ) ( toCharRange (nrofChars - nrofCharsInRange + offset) high <> toCharRange low (offset-1)
: map ( (\b -> toCharRange b (b+nrofCharsInRange-1)) . (offset+) ) boundaries
)
val@(Cstring s) <- findRndValue v rndBins
if T.length s /= 1
then error "randomSolveBins - Unexpected Result - length of char must be 1"
else do
addAssertions [ cstrEqual (cstrVar v) (cstrConst val) ]
randomSolve p xs i
where
toCharGroup :: Text -> Text
toCharGroup t = "[" <> t <> "]"
toCharRange :: Int -> Int -> Text
toCharRange l h = toRegexString l <> "-" <> toRegexString h
toConstraint :: v -> Text -> ValExpr v
toConstraint v' t = cstrStrInRe (cstrVar v') (cstrConst (Cregex t))
randomSolveBins p ((v,d):xs) i | vsort v == sortIdString =
do
let lengthStringVar = cstrVariable ("$$$l$" ++ show i) (10000000+i) sortIdInt
addDeclarations [lengthStringVar]
addAssertions [cstrEqual (cstrLength (cstrVar v)) (cstrVar lengthStringVar)]
boundaryValues <- liftIO $ mapM randomRIO basicStringLengthRanges
let bins = mkIntConstraintBins (cstrVar lengthStringVar) boundaryValues
rndBins <- shuffleM bins
val@(Cint l) <- findRndValue lengthStringVar rndBins
addAssertions [ cstrEqual (cstrVar lengthStringVar) (cstrConst val) ]
if l > 0 && d > 1
then do
let charVars = map (\iNew -> cstrVariable ("$$$t$" ++ show iNew) (10000000+iNew) sortIdString) [i+1 .. i+fromIntegral l]
addDeclarations charVars
let exprs = map (\(vNew,pos) -> cstrEqual (cstrVar vNew) (cstrAt (cstrVar v) (cstrConst (Cint pos)))) (zip charVars [0..])
addAssertions exprs
shuffledVars <- shuffleM (xs ++ zip charVars (map (const (-123)) [1::Integer .. ]) )
randomSolve p shuffledVars (i+1+fromIntegral l)
else randomSolve p xs (i+1)
randomSolveBins p ((v,d):xs) i =
do
let sid = vsort v
cstrs <- lookupCstrIds sid
(cid, d') <- case cstrs of
[] -> error $ "Unexpected: no constructor for " ++ show v
[cid'] -> return (cid', d) -- No choice, no decrease of depth
_ -> do
shuffledCstrs <- shuffleM cstrs
let shuffledBins = map (\tempCid -> cstrIsCstr tempCid (cstrVar v)) shuffledCstrs
Ccstr{cstrId = cid'} <- findRndValue v shuffledBins
return (cid', d-1)
addIsConstructor v cid
fieldVars <- if d' > 1 then addFields v i cid
else return []
let l = length fieldVars
if l > 0
then do
shuffledVars <- shuffleM (xs ++ zip fieldVars (map (const d') [1::Integer .. ]) )
randomSolve p shuffledVars (i+l)
else
randomSolve p xs i
-- lookup constructors given its sort id
lookupCstrIds :: SortId -> SMT [CstrId]
lookupCstrIds sid = do
edefs <- gets envDefs
return [cstrid | cstrid@CstrId{cstrsort = sid'} <- Map.keys (cstrDefs edefs), sid == sid']
addIsConstructor :: (Variable v) => v -> CstrId -> SMT ()
addIsConstructor v cid = addAssertions [cstrIsCstr cid (cstrVar v)]
addFields :: (Variable v) => v -> Int -> CstrId -> SMT [v]
addFields v i cid@CstrId{ cstrargs = args' } = do
let fieldVars = map (\(iNew,sNew) -> cstrVariable ("$$$t$" ++ show iNew) (10000000+iNew) sNew) (zip [i .. ] args')
addDeclarations fieldVars
edefs <- gets envDefs
let mcdef = Map.lookup cid (cstrDefs edefs)
case mcdef of
Nothing -> error $ "Unexpected: no constructor definition for " ++ show cid
Just (CstrDef _ fIds) -> do
let names = map FuncId.name fIds
exprs = map (\(nm, pos, fieldVar) -> cstrEqual (cstrVar fieldVar) (cstrAccess cid nm pos (cstrVar v))) (zip3 names [0..] fieldVars)
addAssertions exprs
return fieldVars
-- ----------------------------------------------------------------------------------------- --
-- --
-- ----------------------------------------------------------------------------------------- --
| null | https://raw.githubusercontent.com/TorXakis/TorXakis/038463824b3d358df6b6b3ff08732335b7dbdb53/sys/solve/src/RandIncrementBins.hs | haskell | # LANGUAGE OverloadedStrings #
----------------------------------------------------------------------------------------- --
When the variable can be changed,
bins are created and shuffled to find a random solution.
----------------------------------------------------------------------------------------- --
export
----------------------------------------------------------------------------------------- --
import
---------------------------
from ascending boundary values make intervals
no boundary values, single interval
faster to reuse the same bins for positive and negative?
----------------------------------------------------------------------------------------- --
give a random solution for constraint vexps with free variables vars
if not all constraints are of type boolean: stop, otherwise solve the constraints
* configuration parameters
* List of tuples of (Variable, Depth)
* available variable id
empty list -> done
abuse depth to encode char versus string
nrofChars == nrOfRanges * nrofCharsInRange
No choice, no decrease of depth
lookup constructors given its sort id
----------------------------------------------------------------------------------------- --
--
----------------------------------------------------------------------------------------- -- |
TorXakis - Model Based Testing
Copyright ( c ) 2015 - 2017 TNO and Radboud University
See LICENSE at root directory of this repository .
TorXakis - Model Based Testing
Copyright (c) 2015-2017 TNO and Radboud University
See LICENSE at root directory of this repository.
-}
# LANGUAGE ScopedTypeVariables #
module RandIncrementBins
Module RandIncrementBins : Randomization of SMT solutions
Solving by incrementally fixing one variable at a time
( randValExprsSolveIncrementBins
, ParamIncrementBins (..)
)
where
import Control.Monad.State
import qualified Data.Char as Char
import qualified Data.Map as Map
import Data.Maybe
import Data.Monoid
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import System.IO
import System.Random
import System.Random.Shuffle
import Constant
import CstrDef
import CstrId
import FuncId
import SMT
import SMTData
import Solve.Params
import SolveDefs
import SortId
import SortOf
import ValExpr
import Variable
data ParamIncrementBins =
ParamIncrementBins { maxDepth :: Int
, next :: Next
, nrOfBins :: Int
}
deriving (Eq,Ord,Read,Show)
step :: Integer
step = 10
nextFunction :: ParamIncrementBins -> Integer -> Integer
nextFunction p =
case RandIncrementBins.next p of
Linear -> (step +)
Power -> (step *)
Exponent -> nextExponent
nextExponent :: Integer -> Integer
nextExponent n = n * n
mkRanges :: (Integer -> Integer) -> Integer -> Integer -> [(Integer, Integer)]
mkRanges nxt lw hgh = (lw, hgh-1): mkRanges nxt hgh (nxt hgh)
basicIntRanges :: ParamIncrementBins -> [(Integer, Integer)]
basicIntRanges p = take (nrOfBins p) (mkRanges (nextFunction p) 0 step)
basicStringLengthRanges :: [(Integer, Integer)]
basicStringLengthRanges = take 3 (mkRanges (3*) 0 3)
mkIntConstraintBins :: forall v. Ord v => ValExpr v -> [Integer] -> [ValExpr v]
mkIntConstraintBins v l@(x:_) = cstrLE v (cstrConst (Cint x)) : mkRestBins l
where
mkRestBins :: Ord v => [Integer] -> [ValExpr v]
mkRestBins [y] = [cstrLT (cstrConst (Cint y)) v]
mkRestBins (y1:y2:ys) = cstrAnd ( Set.fromList [cstrLT (cstrConst (Cint y1)) v, cstrLE v (cstrConst (Cint y2)) ] ) : mkRestBins (y2:ys)
mkRestBins [] = error "mkIntConstraintBins - Should not happen - at least one element in mkRestBins"
mkRndIntBins :: Ord v => ParamIncrementBins -> ValExpr v -> IO [ValExpr v]
mkRndIntBins p v = do
pos <- mapM randomRIO (basicIntRanges p)
let boundaryValues = reverse (map negate neg) ++ pos
bins = mkIntConstraintBins v boundaryValues
shuffleM bins
findRndValue :: Variable v => v -> [ValExpr v] -> SMT Constant
findRndValue _ [] = error "findRndValue - Solution exists, yet no solution found in all bins"
findRndValue v (x:xs) = do
push
addAssertions [x]
sat <- getSolvable
case sat of
Sat -> do
sol <- getSolution [v]
pop
let val = fromMaybe (error "findRndValue - SMT hasn't returned the value of requested variable.")
(Map.lookup v sol)
return val
_ -> do
pop
findRndValue v xs
randValExprsSolveIncrementBins :: (Variable v) => ParamIncrementBins -> [v] -> [ValExpr v] -> SMT (SolveProblem v)
randValExprsSolveIncrementBins p freevars exprs =
if all ( (sortIdBool == ) . sortOf ) exprs
then do
push
addDeclarations freevars
addAssertions exprs
sat <- getSolvable
sp <- case sat of
Sat -> do
shuffledVars <- shuffleM freevars
randomSolve p (zip shuffledVars (map (const (maxDepth p)) [1::Integer .. ]) ) 0
sat2 <- getSolvable
case sat2 of
Sat -> Solved <$> getSolution freevars
_ -> do
lift $ hPutStrLn stderr "TXS RandIncrementBins randValExprsSolveIncrementBins: Problem no longer solvable\n"
return UnableToSolve
Unsat -> return Unsolvable
Unknown -> return UnableToSolve
pop
return sp
else do
lift $ hPutStrLn stderr "TXS RandIncrementBins randValExprsSolveIncrementBins: Not all added constraints are Bool\n"
return UnableToSolve
toRegexString :: Int -> Text
toRegexString 45 = "\\-"
toRegexString 91 = "\\["
toRegexString 92 = "\\\\"
toRegexString 93 = "\\]"
toRegexString 94 = "\\^"
toRegexString c = T.singleton (Char.chr c)
randomSolve :: Variable v => ParamIncrementBins -> [(v, Int)] -> Int -> SMT ()
randomSolve _ ((_,0):_) _ = error "At maximum depth: should not be added"
randomSolve p vs@((v,_):xs) i = do
sat <- getSolvable
case sat of
Sat -> do
sol <- getSolution [v]
let val = fromMaybe (error "randomSolve - SMT hasn't returned the value of requested variable.")
(Map.lookup v sol)
push
addAssertions [ cstrNot ( cstrEqual (cstrVar v) (cstrConst val) ) ]
sat2 <- getSolvable
pop
case sat2 of
Sat -> randomSolveBins p vs i
_ -> do
addAssertions [ cstrEqual (cstrVar v) (cstrConst val) ]
randomSolve p xs i
_ -> error "randomSolve - Unexpected SMT issue - previous solution is no longer valid"
randomSolveBins :: Variable v => ParamIncrementBins -> [(v, Int)] -> Int -> SMT ()
randomSolveBins _ [] _ = error "randomSolveBins - should always be called with no empty list"
randomSolveBins p ((v,_):xs) i | vsort v == sortIdBool =
since the variable can be changed both values are possible : pick one and be done
do
b <- liftIO randomIO
addAssertions [ cstrEqual (cstrVar v) (cstrConst (Cbool b) ) ]
randomSolve p xs i
randomSolveBins p ((v,_):xs) i | vsort v == sortIdInt =
do
rndBins <- liftIO $ mkRndIntBins p (cstrVar v)
val@Cint{} <- findRndValue v rndBins
addAssertions [ cstrEqual (cstrVar v) (cstrConst val) ]
randomSolve p xs i
let nrofChars :: Int
nrOfRanges :: Int
nrOfRanges = 8
nrofCharsInRange :: Int
nrofCharsInRange = 32
low :: Int
low = 0
high :: Int
high = nrofChars -1
boundaries :: [Int]
boundaries = take (nrOfRanges-1) [0, nrofCharsInRange .. ]
in do
offset <- liftIO $ randomRIO (0,nrofCharsInRange-1)
let rndBins = case offset of
0 -> map ( toConstraint v . toCharGroup . (\b -> toCharRange b (b+nrofCharsInRange-1)) ) (nrofChars-nrofCharsInRange:boundaries)
1 -> map ( toConstraint v . toCharGroup ) ( toCharRange (nrofChars - nrofCharsInRange + 1) high <> toRegexString low
: map (\b -> toCharRange (b+1) (b+nrofCharsInRange)) boundaries
)
n | n == nrofCharsInRange -1 -> map ( toConstraint v . toCharGroup ) ( toRegexString high <> toCharRange low (nrofCharsInRange-2)
: map ( (\b -> toCharRange b (b+nrofCharsInRange-1)) . (offset+) ) boundaries
)
_ -> map ( toConstraint v . toCharGroup ) ( toCharRange (nrofChars - nrofCharsInRange + offset) high <> toCharRange low (offset-1)
: map ( (\b -> toCharRange b (b+nrofCharsInRange-1)) . (offset+) ) boundaries
)
val@(Cstring s) <- findRndValue v rndBins
if T.length s /= 1
then error "randomSolveBins - Unexpected Result - length of char must be 1"
else do
addAssertions [ cstrEqual (cstrVar v) (cstrConst val) ]
randomSolve p xs i
where
toCharGroup :: Text -> Text
toCharGroup t = "[" <> t <> "]"
toCharRange :: Int -> Int -> Text
toCharRange l h = toRegexString l <> "-" <> toRegexString h
toConstraint :: v -> Text -> ValExpr v
toConstraint v' t = cstrStrInRe (cstrVar v') (cstrConst (Cregex t))
randomSolveBins p ((v,d):xs) i | vsort v == sortIdString =
do
let lengthStringVar = cstrVariable ("$$$l$" ++ show i) (10000000+i) sortIdInt
addDeclarations [lengthStringVar]
addAssertions [cstrEqual (cstrLength (cstrVar v)) (cstrVar lengthStringVar)]
boundaryValues <- liftIO $ mapM randomRIO basicStringLengthRanges
let bins = mkIntConstraintBins (cstrVar lengthStringVar) boundaryValues
rndBins <- shuffleM bins
val@(Cint l) <- findRndValue lengthStringVar rndBins
addAssertions [ cstrEqual (cstrVar lengthStringVar) (cstrConst val) ]
if l > 0 && d > 1
then do
let charVars = map (\iNew -> cstrVariable ("$$$t$" ++ show iNew) (10000000+iNew) sortIdString) [i+1 .. i+fromIntegral l]
addDeclarations charVars
let exprs = map (\(vNew,pos) -> cstrEqual (cstrVar vNew) (cstrAt (cstrVar v) (cstrConst (Cint pos)))) (zip charVars [0..])
addAssertions exprs
shuffledVars <- shuffleM (xs ++ zip charVars (map (const (-123)) [1::Integer .. ]) )
randomSolve p shuffledVars (i+1+fromIntegral l)
else randomSolve p xs (i+1)
randomSolveBins p ((v,d):xs) i =
do
let sid = vsort v
cstrs <- lookupCstrIds sid
(cid, d') <- case cstrs of
[] -> error $ "Unexpected: no constructor for " ++ show v
_ -> do
shuffledCstrs <- shuffleM cstrs
let shuffledBins = map (\tempCid -> cstrIsCstr tempCid (cstrVar v)) shuffledCstrs
Ccstr{cstrId = cid'} <- findRndValue v shuffledBins
return (cid', d-1)
addIsConstructor v cid
fieldVars <- if d' > 1 then addFields v i cid
else return []
let l = length fieldVars
if l > 0
then do
shuffledVars <- shuffleM (xs ++ zip fieldVars (map (const d') [1::Integer .. ]) )
randomSolve p shuffledVars (i+l)
else
randomSolve p xs i
lookupCstrIds :: SortId -> SMT [CstrId]
lookupCstrIds sid = do
edefs <- gets envDefs
return [cstrid | cstrid@CstrId{cstrsort = sid'} <- Map.keys (cstrDefs edefs), sid == sid']
addIsConstructor :: (Variable v) => v -> CstrId -> SMT ()
addIsConstructor v cid = addAssertions [cstrIsCstr cid (cstrVar v)]
addFields :: (Variable v) => v -> Int -> CstrId -> SMT [v]
addFields v i cid@CstrId{ cstrargs = args' } = do
let fieldVars = map (\(iNew,sNew) -> cstrVariable ("$$$t$" ++ show iNew) (10000000+iNew) sNew) (zip [i .. ] args')
addDeclarations fieldVars
edefs <- gets envDefs
let mcdef = Map.lookup cid (cstrDefs edefs)
case mcdef of
Nothing -> error $ "Unexpected: no constructor definition for " ++ show cid
Just (CstrDef _ fIds) -> do
let names = map FuncId.name fIds
exprs = map (\(nm, pos, fieldVar) -> cstrEqual (cstrVar fieldVar) (cstrAccess cid nm pos (cstrVar v))) (zip3 names [0..] fieldVars)
addAssertions exprs
return fieldVars
|
5dcd8fe2752242345f7d77aefbd51a5cb2339b12b7be7d71bccd5f62a1b21f27 | fukamachi/psychiq | scheduled.lisp | (in-package :cl-user)
(defpackage psychiq.launcher.scheduled
(:use #:cl
#:psychiq.util
#:psychiq.specials)
(:import-from #:psychiq.connection
#:with-connection
#:make-connection
#:disconnect)
(:import-from #:psychiq.queue
#:enqueue-to-queue)
(:import-from #:psychiq.coder
#:decode-object)
(:import-from #:local-time
#:timestamp-to-unix
#:now)
(:export #:scheduled
#:scheduled-status
#:scheduled-thread
#:start
#:stop
#:kill
#:make-scheduled))
(in-package :psychiq.launcher.scheduled)
(defstruct (scheduled (:constructor %make-scheduled))
connection
thread
(status :stopped))
(defun make-scheduled (&key (host *default-redis-host*) (port *default-redis-port*) db)
(let ((conn (make-connection :host host :port port :db db)))
(%make-scheduled :connection conn)))
(defun start (scheduled)
(when (eq (scheduled-status scheduled) :running)
(error "Scheduled thread is already running"))
(setf (scheduled-status scheduled) :running)
(let* ((conn (scheduled-connection scheduled))
(thread
(bt:make-thread
(lambda ()
(unwind-protect
(loop while (eq (scheduled-status scheduled) :running)
do (handler-case (with-connection conn
(enqueue-jobs (timestamp-to-unix (now))))
(redis:redis-connection-error (e)
(vom:error "polling scheduled: ~A" e)
(disconnect conn)))
(sleep (scaled-poll-interval)))
(disconnect (scheduled-connection scheduled))
(setf (scheduled-thread scheduled) nil)
(setf (scheduled-status scheduled) :stopped)))
:initial-bindings `((*standard-output* . ,*standard-output*)
(*error-output* . ,*error-output*))
:name "psychiq scheduled")))
(setf (scheduled-thread scheduled) thread))
scheduled)
(defun scaled-poll-interval ()
Should be changed to the number of Psychiq processes
(process-count 1)
(poll-interval-average (* process-count 2)))
(+ (* poll-interval-average (random 1.0))
(/ poll-interval-average 2))))
(defun stop (scheduled)
(unless (eq (scheduled-status scheduled) :running)
(return-from stop nil))
(setf (scheduled-status scheduled) :stopping))
(defun kill (scheduled)
(setf (scheduled-status scheduled) :stopping)
(let ((thread (scheduled-thread scheduled)))
(when (and (bt:threadp thread)
(bt:thread-alive-p thread))
(bt:destroy-thread thread)))
t)
(defun enqueue-jobs (now)
(dolist (queue '("retry" "schedule"))
(loop for payload = (first
(red:zrangebyscore (redis-key queue)
"-inf"
now
:limit '(0 . 1)))
while payload
do (red:zrem (redis-key queue) payload)
(let* ((job-info (decode-object payload))
(queue (or (aget job-info "queue") *default-queue-name*)))
(enqueue-to-queue queue job-info)
(vom:debug "Enqueued to ~A: ~S" queue job-info)))))
| null | https://raw.githubusercontent.com/fukamachi/psychiq/602fbb51d4c871de5909ec0c5a159652f4ae9ad3/src/launcher/scheduled.lisp | lisp | (in-package :cl-user)
(defpackage psychiq.launcher.scheduled
(:use #:cl
#:psychiq.util
#:psychiq.specials)
(:import-from #:psychiq.connection
#:with-connection
#:make-connection
#:disconnect)
(:import-from #:psychiq.queue
#:enqueue-to-queue)
(:import-from #:psychiq.coder
#:decode-object)
(:import-from #:local-time
#:timestamp-to-unix
#:now)
(:export #:scheduled
#:scheduled-status
#:scheduled-thread
#:start
#:stop
#:kill
#:make-scheduled))
(in-package :psychiq.launcher.scheduled)
(defstruct (scheduled (:constructor %make-scheduled))
connection
thread
(status :stopped))
(defun make-scheduled (&key (host *default-redis-host*) (port *default-redis-port*) db)
(let ((conn (make-connection :host host :port port :db db)))
(%make-scheduled :connection conn)))
(defun start (scheduled)
(when (eq (scheduled-status scheduled) :running)
(error "Scheduled thread is already running"))
(setf (scheduled-status scheduled) :running)
(let* ((conn (scheduled-connection scheduled))
(thread
(bt:make-thread
(lambda ()
(unwind-protect
(loop while (eq (scheduled-status scheduled) :running)
do (handler-case (with-connection conn
(enqueue-jobs (timestamp-to-unix (now))))
(redis:redis-connection-error (e)
(vom:error "polling scheduled: ~A" e)
(disconnect conn)))
(sleep (scaled-poll-interval)))
(disconnect (scheduled-connection scheduled))
(setf (scheduled-thread scheduled) nil)
(setf (scheduled-status scheduled) :stopped)))
:initial-bindings `((*standard-output* . ,*standard-output*)
(*error-output* . ,*error-output*))
:name "psychiq scheduled")))
(setf (scheduled-thread scheduled) thread))
scheduled)
(defun scaled-poll-interval ()
Should be changed to the number of Psychiq processes
(process-count 1)
(poll-interval-average (* process-count 2)))
(+ (* poll-interval-average (random 1.0))
(/ poll-interval-average 2))))
(defun stop (scheduled)
(unless (eq (scheduled-status scheduled) :running)
(return-from stop nil))
(setf (scheduled-status scheduled) :stopping))
(defun kill (scheduled)
(setf (scheduled-status scheduled) :stopping)
(let ((thread (scheduled-thread scheduled)))
(when (and (bt:threadp thread)
(bt:thread-alive-p thread))
(bt:destroy-thread thread)))
t)
(defun enqueue-jobs (now)
(dolist (queue '("retry" "schedule"))
(loop for payload = (first
(red:zrangebyscore (redis-key queue)
"-inf"
now
:limit '(0 . 1)))
while payload
do (red:zrem (redis-key queue) payload)
(let* ((job-info (decode-object payload))
(queue (or (aget job-info "queue") *default-queue-name*)))
(enqueue-to-queue queue job-info)
(vom:debug "Enqueued to ~A: ~S" queue job-info)))))
| |
3a70a2fdb4f606ef2d7c223380c3218d0288030f389be7fb02ae5b7e7c088bc8 | mainland/nikola | Main.hs | # LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
# LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell #
module Main where
import Prelude hiding (map)
import qualified Data.Vector.Storable as V
import Language.C.Quote.CUDA
import qualified Language.C.Syntax as C
#if !MIN_VERSION_template_haskell(2,7,0)
import qualified Data.Loc
import qualified Data.Symbol
import qualified Language.C.Syntax
#endif /* !MIN_VERSION_template_haskell(2,7,0) */
import Data.Array.Nikola.Backend.CUDA
import Data.Array.Nikola.Backend.CUDA.CodeGen
main :: IO ()
main = withNewContext $ \_ -> do
test
test :: IO ()
test = do
print (g v)
where
g :: V.Vector Float -> V.Vector Float
g = compile f2
v :: V.Vector Float
v = V.fromList [0..31]
f :: Exp (V.Vector Float) -> Exp (V.Vector Float)
f = map inc
inc :: Exp Float -> Exp Float
inc = vapply $ \x -> x + 1
f2 :: CFun (Exp (V.Vector Float) -> Exp (V.Vector Float))
f2 = CFun { cfunName = "f2"
, cfunDefs = defs
, cfunAllocs = [vectorArgT FloatT (ParamIdx 0)]
, cfunExecConfig = ExecConfig { gridDimX = fromIntegral 240
, gridDimY = 1
, blockDimX = fromIntegral 128
, blockDimY = 1
, blockDimZ = 1
}
}
where
defs :: [C.Definition]
defs = [cunit|
__device__ float f0(float x2)
{
float v4;
v4 = x2 + 1.0F;
return v4;
}
extern "C" __global__ void f2(float* x0, int x0n, float* temp, int* tempn)
{
for (int i = (blockIdx.x + blockIdx.y * gridDim.x) * 128 + threadIdx.x; i <
x0n; i += 128 * 240) {
if (i < x0n) {
{
float temp0;
temp0 = f0(x0[i]);
temp[i] = temp0;
}
if (i == 0)
*tempn = x0n;
}
}
__syncthreads();
}
|]
| null | https://raw.githubusercontent.com/mainland/nikola/d86398888c0a76f8ad1556a269a708de9dd92644/tests/Main.hs | haskell | # LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
# LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell #
module Main where
import Prelude hiding (map)
import qualified Data.Vector.Storable as V
import Language.C.Quote.CUDA
import qualified Language.C.Syntax as C
#if !MIN_VERSION_template_haskell(2,7,0)
import qualified Data.Loc
import qualified Data.Symbol
import qualified Language.C.Syntax
#endif /* !MIN_VERSION_template_haskell(2,7,0) */
import Data.Array.Nikola.Backend.CUDA
import Data.Array.Nikola.Backend.CUDA.CodeGen
main :: IO ()
main = withNewContext $ \_ -> do
test
test :: IO ()
test = do
print (g v)
where
g :: V.Vector Float -> V.Vector Float
g = compile f2
v :: V.Vector Float
v = V.fromList [0..31]
f :: Exp (V.Vector Float) -> Exp (V.Vector Float)
f = map inc
inc :: Exp Float -> Exp Float
inc = vapply $ \x -> x + 1
f2 :: CFun (Exp (V.Vector Float) -> Exp (V.Vector Float))
f2 = CFun { cfunName = "f2"
, cfunDefs = defs
, cfunAllocs = [vectorArgT FloatT (ParamIdx 0)]
, cfunExecConfig = ExecConfig { gridDimX = fromIntegral 240
, gridDimY = 1
, blockDimX = fromIntegral 128
, blockDimY = 1
, blockDimZ = 1
}
}
where
defs :: [C.Definition]
defs = [cunit|
__device__ float f0(float x2)
{
float v4;
v4 = x2 + 1.0F;
return v4;
}
extern "C" __global__ void f2(float* x0, int x0n, float* temp, int* tempn)
{
for (int i = (blockIdx.x + blockIdx.y * gridDim.x) * 128 + threadIdx.x; i <
x0n; i += 128 * 240) {
if (i < x0n) {
{
float temp0;
temp0 = f0(x0[i]);
temp[i] = temp0;
}
if (i == 0)
*tempn = x0n;
}
}
__syncthreads();
}
|]
| |
81761af071e3c292577cbb1978314fc2baeeeec869c41c4cfe3c6ca68de77c5b | inguardians/kismapping | KismetPoints.hs | {-# LANGUAGE OverloadedStrings #-}
module Kismapping.Input.KismetPoints where
import Data.Foldable
import Data.HashMap.Lazy (HashMap)
import qualified Data.HashMap.Lazy as HashMap
import Data.Hashable
import Data.Monoid
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Text (Text)
import Data.Vector (Vector)
import qualified Data.Vector as Vector
import Kismapping.Types
import qualified Statistics.Sample as Statistics
type EssidMap = HashMap Text BssidMap
type BssidMap = HashMap Text APReadings
APReadings is a Map from points in space ( using polar coordinates ) to signal readings
type APReadings = HashMap HashablePolar (Seq Double)
newtype HashablePolar =
HashablePolar Polar
deriving (Eq)
instance Hashable HashablePolar where
hashWithSalt salt (HashablePolar (Polar x)) = hashWithSalt salt x
| Given a Map of BSSID keys to ESSID values , get the for a given BSSID .
If none is found , use " < HIDDEN > " as the , because the BSSID has no
corresponding ESSID .
lookupEssid :: HashMap Text Text -> Text -> Text
lookupEssid ssidMap bssid = HashMap.lookupDefault "" bssid ssidMap
Unify two BSSID maps , preserving datapoints from both .
unionBssidMaps :: BssidMap -> BssidMap -> BssidMap
unionBssidMaps = HashMap.unionWith (HashMap.unionWith (<>))
unionEssidMaps :: EssidMap -> EssidMap -> EssidMap
unionEssidMaps = HashMap.unionWith unionBssidMaps
Creates a BssidMap for a single datapoint
bssidMapSingleton :: Text -> Polar -> Double -> BssidMap
bssidMapSingleton bssid loc db =
HashMap.singleton
bssid
(HashMap.singleton (HashablePolar loc) (Seq.singleton db))
insertGpsPoint :: Text -> Text -> Polar -> Double -> EssidMap -> EssidMap
insertGpsPoint essid bssid loc db =
HashMap.insertWith unionBssidMaps essid (bssidMapSingleton bssid loc db)
toHeatpoints :: BssidMap -> Vector (Vector HeatPoint)
toHeatpoints bssidMap =
let meanHeatpoint (HashablePolar p, dbSeq) =
HeatPoint
(fromPolar p)
(Statistics.mean (Vector.fromList (toList dbSeq)))
bssidHeatpoints apReadings =
Vector.fromList (fmap meanHeatpoint (HashMap.toList apReadings))
in Vector.fromList (toList (fmap bssidHeatpoints bssidMap))
| null | https://raw.githubusercontent.com/inguardians/kismapping/98b8511cb60595db45f89746d4586bd9d3a60e6a/library/Kismapping/Input/KismetPoints.hs | haskell | # LANGUAGE OverloadedStrings # |
module Kismapping.Input.KismetPoints where
import Data.Foldable
import Data.HashMap.Lazy (HashMap)
import qualified Data.HashMap.Lazy as HashMap
import Data.Hashable
import Data.Monoid
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Text (Text)
import Data.Vector (Vector)
import qualified Data.Vector as Vector
import Kismapping.Types
import qualified Statistics.Sample as Statistics
type EssidMap = HashMap Text BssidMap
type BssidMap = HashMap Text APReadings
APReadings is a Map from points in space ( using polar coordinates ) to signal readings
type APReadings = HashMap HashablePolar (Seq Double)
newtype HashablePolar =
HashablePolar Polar
deriving (Eq)
instance Hashable HashablePolar where
hashWithSalt salt (HashablePolar (Polar x)) = hashWithSalt salt x
| Given a Map of BSSID keys to ESSID values , get the for a given BSSID .
If none is found , use " < HIDDEN > " as the , because the BSSID has no
corresponding ESSID .
lookupEssid :: HashMap Text Text -> Text -> Text
lookupEssid ssidMap bssid = HashMap.lookupDefault "" bssid ssidMap
Unify two BSSID maps , preserving datapoints from both .
unionBssidMaps :: BssidMap -> BssidMap -> BssidMap
unionBssidMaps = HashMap.unionWith (HashMap.unionWith (<>))
unionEssidMaps :: EssidMap -> EssidMap -> EssidMap
unionEssidMaps = HashMap.unionWith unionBssidMaps
Creates a BssidMap for a single datapoint
bssidMapSingleton :: Text -> Polar -> Double -> BssidMap
bssidMapSingleton bssid loc db =
HashMap.singleton
bssid
(HashMap.singleton (HashablePolar loc) (Seq.singleton db))
insertGpsPoint :: Text -> Text -> Polar -> Double -> EssidMap -> EssidMap
insertGpsPoint essid bssid loc db =
HashMap.insertWith unionBssidMaps essid (bssidMapSingleton bssid loc db)
toHeatpoints :: BssidMap -> Vector (Vector HeatPoint)
toHeatpoints bssidMap =
let meanHeatpoint (HashablePolar p, dbSeq) =
HeatPoint
(fromPolar p)
(Statistics.mean (Vector.fromList (toList dbSeq)))
bssidHeatpoints apReadings =
Vector.fromList (fmap meanHeatpoint (HashMap.toList apReadings))
in Vector.fromList (toList (fmap bssidHeatpoints bssidMap))
|
7a06a45e28ce061685a168b2d459a27068f33d4070f0f7d032cbc9b2c0e00df1 | stepcut/isomaniac | Types.hs | # LANGUAGE ExistentialQuantification , FlexibleContexts , FlexibleInstances , GADTs , JavaScriptFFI , ScopedTypeVariables , TemplateHaskell , TypeFamilies #
# language GeneralizedNewtypeDeriving #
module Web.ISO.Types where
import Control.Applicative (Applicative, Alternative)
import Control.Monad (Monad, MonadPlus)
import Control.Lens ((^.))
import Control.Lens.TH (makeLenses)
import Control.Monad (when)
import Control.Monad.Trans (MonadIO(..))
import Data.Maybe (fromJust)
import Data.Aeson.Types (Parser, Result(..), parse)
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.JSString as JS
import Data.JSString.Text (textToJSString, textFromJSString)
import qualified Data.Text as Text
-- import GHCJS.Prim (ToJSString(..), FromJSString(..))
import JavaScript . TypedArray . ArrayBuffer ( ArrayBuffer )
import GHCJS.Buffer
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (OnBlocked(..), Callback, asyncCallback1, syncCallback1)
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(pToJSVal), PFromJSVal(pFromJSVal))
import GHCJS.Nullable (Nullable(..), nullableToMaybe, maybeToNullable)
import GHCJS.Types (JSVal(..), JSString(..), nullRef, isNull, isUndefined)
instance Eq JSVal where
a == b = js_eq a b
foreign import javascript unsafe
"$1===$2" js_eq :: JSVal -> JSVal -> Bool
maybeJSNullOrUndefined :: JSVal -> Maybe JSVal
maybeJSNullOrUndefined r | isNull r || isUndefined r = Nothing
maybeJSNullOrUndefined r = Just r
newtype EIO a = EIO { eioToIO :: IO a }
deriving (Functor, Applicative, Alternative, Monad, MonadPlus)
fromJSValUnchecked : : ( a ) = > a - > IO a
fromJSValUnchecked j =
do x < - fromJSVal j
case x of
Nothing - > error " failed . "
( Just a ) - > return a
fromJSValUnchecked :: (FromJSVal a) => JSVal a -> IO a
fromJSValUnchecked j =
do x <- fromJSVal j
case x of
Nothing -> error "failed."
(Just a) -> return a
-}
-- * JSNode
newtype JSNode = JSNode JSVal
unJSNode (JSNode o) = o
instance ToJSVal JSNode where
toJSVal = toJSVal . unJSNode
# INLINE toJSVal #
instance FromJSVal JSNode where
fromJSVal = return . fmap JSNode . maybeJSNullOrUndefined
# INLINE fromJSVal #
-- * IsJSNode
class IsJSNode obj where
toJSNode :: (IsJSNode obj) => obj -> JSNode
instance IsJSNode JSNode where
toJSNode = id
-- * JSNodeList
newtype JSNodeList = JSNodeList JSVal
unJSNodeList (JSNodeList o) = o
instance ToJSVal JSNodeList where
toJSVal = return . unJSNodeList
# INLINE toJSVal #
instance FromJSVal JSNodeList where
fromJSVal = return . fmap JSNodeList . maybeJSNullOrUndefined
# INLINE fromJSVal #
instance IsJSNode JSNodeList where
toJSNode = JSNode . unJSNodeList
foreign import javascript unsafe "$1[\"item\"]($2)" js_item ::
JSNodeList -> Word -> IO JSNode
| < -US/docs/Web/API/NodeList.item Mozilla NodeList.item documentation >
item ::
(MonadIO m) => JSNodeList -> Word -> m (Maybe JSNode)
item self index
= liftIO
((js_item (self) index) >>= return . Just)
foreign import javascript unsafe "$1[\"length\"]" js_length ::
JSNode -> IO Word
| < -US/docs/Web/API/NodeList.item Mozilla NodeList.item documentation >
getLength :: (MonadIO m, IsJSNode self) => self -> m Word
getLength self
= liftIO (js_length ( (toJSNode self))) -- >>= fromJSValUnchecked)
foreign import javascript unsafe " $ 1[\"length\ " ] " : :
- > IO Word
-- * parentNode
foreign import javascript unsafe "$1[\"parentNode\"]"
js_parentNode :: JSNode -> IO JSVal
parentNode :: (MonadIO m, IsJSNode self) => self -> m (Maybe JSNode)
parentNode self =
liftIO (fromJSVal =<< js_parentNode (toJSNode self))
-- * JSDocument
newtype JSDocument = JSDocument JSVal
unJSDocument (JSDocument o) = o
instance ToJSVal JSDocument where
toJSVal = return . unJSDocument
# INLINE toJSVal #
instance FromJSVal JSDocument where
fromJSVal = return . fmap JSDocument . maybeJSNullOrUndefined
# INLINE fromJSVal #
instance IsJSNode JSDocument where
toJSNode = JSNode . unJSDocument
foreign import javascript unsafe "new window[\"Document\"]()"
js_newDocument :: IO JSDocument
instance IsEventTarget JSDocument where
toEventTarget = EventTarget . unJSDocument
| < -US/docs/Web/API/Document Mozilla Document documentation >
newJSDocument :: (MonadIO m) => m JSDocument
newJSDocument = liftIO js_newDocument
foreign import javascript unsafe "$r = document"
ghcjs_currentDocument :: IO JSDocument
currentDocument :: IO (Maybe JSDocument)
currentDocument = Just <$> ghcjs_currentDocument
-- * JSWindow
newtype JSWindow = JSWindow { unJSWindow :: JSVal }
instance ToJSVal JSWindow where
toJSVal = return . unJSWindow
# INLINE toJSVal #
instance FromJSVal JSWindow where
fromJSVal = return . fmap JSWindow . maybeJSNullOrUndefined
# INLINE fromJSVal #
foreign import javascript unsafe "$r = window"
js_window :: IO JSWindow
instance IsEventTarget JSWindow where
toEventTarget = EventTarget . unJSWindow
window :: (MonadIO m) => m JSWindow
window = liftIO js_window
foreign import javascript unsafe "$1[\"devicePixelRatio\"]"
js_devicePixelRatio :: JSWindow -> IO JSVal
devicePixelRatio :: (MonadIO m) => JSWindow -> m (Maybe Double)
devicePixelRatio w = liftIO (fromJSVal =<< js_devicePixelRatio w)
foreign import javascript unsafe "$1[\"getSelection\"]()"
js_getSelection :: JSWindow -> IO Selection
getSelection :: (MonadIO m) => JSWindow -> m Selection
getSelection w = liftIO (js_getSelection w)
-- * JSElement
newtype JSElement = JSElement JSVal
unJSElement (JSElement o) = o
instance ToJSVal JSElement where
toJSVal = return . unJSElement
# INLINE toJSVal #
instance FromJSVal JSElement where
fromJSVal = return . fmap JSElement . maybeJSNullOrUndefined
# INLINE fromJSVal #
instance IsJSNode JSElement where
toJSNode = JSNode . unJSElement
foreign import javascript unsafe "$1[\"clientLeft\"]"
js_getClientLeft :: JSElement -> IO Double
getClientLeft :: (MonadIO m) => JSElement -> m Double
getClientLeft = liftIO . js_getClientLeft
foreign import javascript unsafe "$1[\"clientTop\"]"
js_getClientTop :: JSElement -> IO Double
getClientTop :: (MonadIO m) => JSElement -> m Double
getClientTop = liftIO . js_getClientTop
foreign import javascript unsafe "$1[\"clientWidth\"]"
js_getClientWidth :: JSElement -> IO Double
getClientWidth :: (MonadIO m) => JSElement -> m Double
getClientWidth = liftIO . js_getClientWidth
foreign import javascript unsafe "$1[\"clientHeight\"]"
js_getClientHeight :: JSElement -> IO Double
getClientHeight :: (MonadIO m) => JSElement -> m Double
getClientHeight = liftIO . js_getClientHeight
-- * createJSElement
foreign import javascript unsafe "$1[\"createElement\"]($2)"
js_createJSElement ::
JSDocument -> JSString -> IO JSElement
-- | <-US/docs/Web/API/JSDocument.createJSElement Mozilla JSDocument.createJSElement documentation>
createJSElement ::
(MonadIO m) =>
JSDocument -> Text -> m (Maybe JSElement)
createJSElement document tagName
= liftIO ((js_createJSElement document (textToJSString tagName))
>>= return . Just)
* innerHTML
foreign import javascript unsafe "$1[\"innerHTML\"] = $2"
js_setInnerHTML :: JSElement -> JSString -> IO ()
setInnerHTML :: (MonadIO m) => JSElement -> JSString -> m ()
setInnerHTML elm content = liftIO $ js_setInnerHTML elm content
-- * childNodes
foreign import javascript unsafe "$1[\"childNodes\"]"
js_childNodes :: JSNode -> IO JSNodeList
childNodes :: (MonadIO m, IsJSNode self) => self -> m JSNodeList
childNodes self
= liftIO (js_childNodes (toJSNode self))
-- * getElementsByName
foreign import javascript unsafe "$1[\"getElementsByName\"]($2)"
js_getElementsByName ::
JSDocument -> JSString -> IO JSNodeList
-- | <-US/docs/Web/API/Document.getElementsByName Mozilla Document.getElementsByName documentation>
getElementsByName ::
(MonadIO m) =>
JSDocument -> JSString -> m (Maybe JSNodeList)
getElementsByName self elementName
= liftIO
((js_getElementsByName self) elementName
>>= return . Just)
foreign import javascript unsafe "$1[\"getElementsByTagName\"]($2)"
js_getElementsByTagName ::
JSDocument -> JSString -> IO JSNodeList
-- | <-US/docs/Web/API/Document.getElementsByTagName Mozilla Document.getElementsByTagName documentation>
getElementsByTagName ::
(MonadIO m) =>
JSDocument -> JSString -> m (Maybe JSNodeList)
getElementsByTagName self tagname
= liftIO
((js_getElementsByTagName self tagname)
>>= return . Just)
foreign import javascript unsafe "$1[\"getElementById\"]($2)"
js_getElementsById ::
JSDocument -> JSString -> IO JSElement
| < -US/docs/Web/API/Document.getElementsByTagName Mozilla Document.getElementsById documentation >
getElementById ::
(MonadIO m) =>
JSDocument -> JSString -> m (Maybe JSElement)
getElementById self ident
= liftIO
((js_getElementsById self ident)
>>= return . Just)
*
foreign import javascript unsafe "$1[\"appendChild\"]($2)"
js_appendChild :: JSNode -> JSNode -> IO JSNode
| < -US/docs/Web/API/Node.appendChild Mozilla Node.appendChild documentation >
appendChild :: (MonadIO m, IsJSNode self, IsJSNode newChild) =>
self
-> Maybe newChild
-> m (Maybe JSNode)
appendChild self newChild
= liftIO
((js_appendChild ( (toJSNode self))
(maybe (JSNode jsNull) ( toJSNode) newChild))
>>= return . Just)
probably broken on IE9
-- * textContent
foreign import javascript unsafe " $ 1[\"textContent\ " ] = $ 2 "
js_setTextContent : : JSString - > IO ( )
setTextContent : : ( MonadIO m , IsJSNode self , ToJSString content ) = >
self
- > content
- > m ( )
setTextContent self content =
liftIO $ ( js_setTextContent ( ( toJSNode self ) ) ( toJSString content ) )
probably broken on IE9
-- * textContent
foreign import javascript unsafe "$1[\"textContent\"] = $2"
js_setTextContent :: JSVal JSNode -> JSString -> IO ()
setTextContent :: (MonadIO m, IsJSNode self, ToJSString content) =>
self
-> content
-> m ()
setTextContent self content =
liftIO $ (js_setTextContent (unJSNode (toJSNode self)) (toJSString content))
-}
-- * replaceData
-- FIMXE: perhaps only a TextNode?
foreign import javascript unsafe "$1[\"replaceData\"]($2, $3, $4)" js_replaceData
:: JSNode
-> Word
-> Word
-> JSString
-> IO ()
replaceData :: (MonadIO m, IsJSNode self) =>
self
-> Word
-> Word
-> Text
-> m ()
replaceData self start length string =
liftIO (js_replaceData (toJSNode self) start length (textToJSString string))
* removeChild
foreign import javascript unsafe "$1[\"removeChild\"]($2)"
js_removeChild :: JSNode -> JSNode -> IO JSNode
| < -US/docs/Web/API/Node.removeChild Mozilla Node.removeChild documentation >
removeChild :: -- FIMXE: really a maybe?
(MonadIO m, IsJSNode self, IsJSNode oldChild) =>
self -> Maybe oldChild -> m (Maybe JSNode)
removeChild self oldChild
= liftIO
((js_removeChild (toJSNode self)
(maybe (JSNode jsNull) toJSNode oldChild))
>>= return . Just)
-- * replaceChild
foreign import javascript unsafe "$1[\"replaceChild\"]($2, $3)"
js_replaceChild :: JSNode -> JSNode -> JSNode -> IO JSNode
replaceChild ::
(MonadIO m, IsJSNode self, IsJSNode newChild, IsJSNode oldChild) =>
self -> newChild -> oldChild -> m (Maybe JSNode)
replaceChild self newChild oldChild
= liftIO
(js_replaceChild ((toJSNode self))
((toJSNode) newChild)
((toJSNode) oldChild)
>>= return . Just)
-- * firstChild
foreign import javascript unsafe "$1[\"firstChild\"]"
js_getFirstChild :: JSNode -> IO JSVal
| < -US/docs/Web/API/Node.firstChild Mozilla Node.firstChild documentation >
getFirstChild :: (MonadIO m, IsJSNode self) => self -> m (Maybe JSNode)
getFirstChild self
= liftIO ((js_getFirstChild ((toJSNode self))) >>= fromJSVal)
removeChildren
:: (MonadIO m, IsJSNode self) =>
self
-> m ()
removeChildren self =
do mc <- getFirstChild self
case mc of
Nothing -> return ()
(Just _) ->
do removeChild self mc
removeChildren self
foreign import javascript unsafe "$1[\"setAttribute\"]($2, $3)"
js_setAttribute :: JSElement -> JSString -> JSString -> IO ()
| < -US/docs/Web/API/Element.setAttribute Mozilla Element.setAttribute documentation >
setAttribute ::
(MonadIO m) =>
JSElement -> Text -> Text -> m ()
setAttribute self name value
= liftIO
(js_setAttribute self (textToJSString name) (textToJSString value))
foreign import javascript unsafe "$1[\"getAttribute\"]($2)"
js_getAttribute :: JSElement -> JSString -> IO JSVal
| < -US/docs/Web/API/Element.setAttribute Mozilla Element.setAttribute documentation >
getAttribute :: (MonadIO m) =>
JSElement
-> JSString
-> m (Maybe JSString)
getAttribute self name = liftIO (js_getAttribute self name >>= fromJSVal)
foreign import javascript unsafe "$1[\"style\"][$2] = $3"
setStyle :: JSElement -> JSString -> JSString -> IO ()
{-
setCSS :: (MonadIO m) =>
JSElement
-> JSString
-> JSString
-> m ()
setCSS elem name value =
liftIO $ js_setCSS elem name value
-}
-- * value
foreign import javascript unsafe "$1[\"value\"]"
js_getValue :: JSNode -> IO JSString
getValue :: (MonadIO m, IsJSNode self) => self -> m (Maybe JSString)
getValue self
= liftIO ((js_getValue (toJSNode self)) >>= return . Just)
foreign import javascript unsafe "$1[\"value\"] = $2"
js_setValue :: JSNode -> JSString -> IO ()
setValue :: (MonadIO m, IsJSNode self) => self -> Text -> m ()
setValue self str =
liftIO (js_setValue (toJSNode self) (textToJSString str))
-- * dataset
foreign import javascript unsafe "$1[\"dataset\"][$2]"
js_getData :: JSNode -> JSString -> IO (Nullable JSString)
getData :: (MonadIO m, IsJSNode self) => self -> JSString -> m (Maybe JSString)
getData self name = liftIO (nullableToMaybe <$> js_getData (toJSNode self) name)
--getData self name = liftIO (fmap fromJSVal <$> maybeJSNullOrUndefined <$> (js_getData (toJSNode self) name))
foreign import javascript unsafe "$1[\"dataset\"][$2] = $3"
js_setData :: JSNode -> JSString -> JSString -> IO ()
setData :: (MonadIO m, IsJSNode self) => self -> JSString -> JSString -> m ()
setData self name value = liftIO (js_setData (toJSNode self) name value)
-- * JSTextNode
newtype JSTextNode = JSTextNode JSVal -- deriving (Eq)
unJSTextNode (JSTextNode o) = o
instance ToJSVal JSTextNode where
toJSVal = return . unJSTextNode
# INLINE toJSVal #
instance FromJSVal JSTextNode where
fromJSVal = return . fmap JSTextNode . maybeJSNullOrUndefined
# INLINE fromJSVal #
instance IsJSNode JSTextNode where
toJSNode = JSNode . unJSTextNode
-- * createTextNode
foreign import javascript unsafe "$1[\"createTextNode\"]($2)"
js_createTextNode :: JSDocument -> JSString -> IO JSTextNode
| < -US/docs/Web/API/Document.createTextNode Mozilla Document.createTextNode documentation >
createJSTextNode ::
(MonadIO m) =>
JSDocument -> Text -> m (Maybe JSTextNode)
createJSTextNode document data'
= liftIO
((js_createTextNode document
(textToJSString data'))
>>= return . Just)
-- * Events
newtype EventTarget = EventTarget { unEventTarget :: JSVal }
instance Eq (EventTarget) where
(EventTarget a) == (EventTarget b) = js_eq a b
instance ToJSVal EventTarget where
toJSVal = return . unEventTarget
# INLINE toJSVal #
instance FromJSVal EventTarget where
fromJSVal = return . fmap EventTarget . maybeJSNullOrUndefined
# INLINE fromJSVal #
class IsEventTarget o where
toEventTarget :: o -> EventTarget
-- toEventTarget = EventTarget
instance IsEventTarget JSElement where
toEventTarget = EventTarget . unJSElement
class IsEvent ev where
eventToJSString :: ev -> JSString
data Event
= ReadyStateChange
deriving (Eq, Show, Read)
instance IsEvent Event where
eventToJSString ReadyStateChange = JS.pack "readystatechange"
data MouseEvent
= Click
| ContextMenu
| DblClick
| MouseDown
| MouseEnter
| MouseLeave
| MouseMove
| MouseOver
| MouseOut
| MouseUp
deriving (Eq, Ord, Show, Read)
instance IsEvent MouseEvent where
eventToJSString Click = JS.pack "click"
eventToJSString ContextMenu = JS.pack "contextmenu"
eventToJSString DblClick = JS.pack "dblclick"
eventToJSString MouseDown = JS.pack "MouseDown"
eventToJSString MouseEnter = JS.pack "MouseEnter"
eventToJSString MouseLeave = JS.pack "MouseLeave"
eventToJSString MouseMove = JS.pack "MouseMove"
eventToJSString MouseOver = JS.pack "MouseOver"
eventToJSString MouseOut = JS.pack "MouseOut"
eventToJSString MouseUp = JS.pack "MouseUp"
data KeyboardEvent
= KeyDown
| KeyPress
| KeyUp
deriving (Eq, Ord, Show, Read)
instance IsEvent KeyboardEvent where
eventToJSString KeyDown = JS.pack "keydown"
eventToJSString KeyPress = JS.pack "keypress"
eventToJSString KeyUp = JS.pack "keyup"
data FrameEvent
= FrameAbort
| BeforeUnload
| FrameError
| HashChange
| FrameLoad
| PageShow
| PageHide
| Resize
| Scroll
| Unload
deriving (Eq, Ord, Show, Read)
data FocusEvent
= Blur
| Focus
| FocusIn
| FocusOut
data FormEvent
= Change
| Input
| Invalid
| Reset
-- | Search
-- | Select
| Submit
deriving (Eq, Ord, Show, Read)
instance IsEvent FormEvent where
-- eventToJSString Blur = JS.pack "blur"
eventToJSString Change = JS.pack "change"
-- eventToJSString Focus = JS.pack "focus"
eventToJSString FocusIn = JS.pack " focusin "
eventToJSString = JS.pack " focusout "
eventToJSString Input = JS.pack "input"
eventToJSString Invalid = JS.pack "invalid"
eventToJSString Reset = JS.pack "reset"
-- eventToJSString Search = JS.pack "search"
-- eventToJSString Select = JS.pack "select"
eventToJSString Submit = JS.pack "submit"
data DragEvent
= Drag
| DragEnd
| DragEnter
| DragLeave
| DragOver
| DragStart
| Drop
deriving (Eq, Ord, Show, Read)
data PrintEvent
= AfterPrint
| BeforePrint
deriving (Eq, Ord, Show, Read)
data MediaEvent
= CanPlay
| CanPlayThrough
| DurationChange
| Emptied
| Ended
| MediaError
| LoadedData
| LoadedMetaData
| Pause
| Play
| Playing
| RateChange
| Seeked
| Seeking
| Stalled
| Suspend
| TimeUpdate
| VolumeChange
| Waiting
deriving (Eq, Ord, Show, Read)
data ProgressEvent
= LoadStart
| Progress
| ProgressAbort
| ProgressError
| ProgressLoad
| Timeout
| LoadEnd
deriving (Eq, Ord, Show, Read)
instance IsEvent ProgressEvent where
eventToJSString LoadStart = JS.pack "loadstart"
eventToJSString Progress = JS.pack "progress"
eventToJSString ProgressAbort = JS.pack "abort"
eventToJSString ProgressError = JS.pack "error"
eventToJSString ProgressLoad = JS.pack "load"
eventToJSString Timeout = JS.pack "timeout"
eventToJSString LoadEnd = JS.pack "loadend"
data AnimationEvent
= AnimationEnd
| AnimationInteration
| AnimationStart
deriving (Eq, Ord, Show, Read)
data TransitionEvent
= TransitionEnd
deriving (Eq, Ord, Show, Read)
data ServerSentEvent
= ServerError
| ServerMessage
| Open
deriving (Eq, Ord, Show, Read)
data MiscEvent
= MiscMessage
| Online
| Offline
| PopState
| MiscShow
| Storage
| Toggle
| Wheel
deriving (Eq, Ord, Show, Read)
data TouchEvent
= TouchCancel
| TouchEnd
| TouchMove
| TouchStart
deriving (Eq, Ord, Show, Read)
-- -US/docs/Web/API/ProgressEvent
-- data ProgressEvent =
data EventType
= MouseEvent MouseEvent
| KeyboardEvent KeyboardEvent
| FrameEvent FrameEvent
| FormEvent FormEvent
| DragEvent DragEvent
| ClipboardEvent ClipboardEvent
| PrintEvent PrintEvent
| MediaEvent MediaEvent
| AnimationEvent AnimationEvent
| TransitionEvent TransitionEvent
| ServerSentEvent ServerSentEvent
| MiscEvent MiscEvent
| TouchEvent TouchEvent
deriving (Eq, Ord, Show, Read)
-- * Event Objects
--
class IsEventObject obj where
asEventObject :: obj -> EventObject
* EventObject
newtype EventObject = EventObject { unEventObject :: JSVal }
instance Show EventObject where
show _ = "EventObject"
instance ToJSVal EventObject where
toJSVal = return . unEventObject
# INLINE toJSVal #
instance FromJSVal EventObject where
fromJSVal = return . fmap EventObject . maybeJSNullOrUndefined
# INLINE fromJSVal #
instance IsEventObject EventObject where
asEventObject = id
foreign import javascript unsafe "$1[\"defaultPrevented\"]" js_defaultPrevented ::
EventObject -> IO Bool
defaultPrevented :: (IsEventObject obj, MonadIO m) => obj -> m Bool
defaultPrevented obj = liftIO (js_defaultPrevented (asEventObject obj))
foreign import javascript unsafe "$1[\"target\"]" js_target ::
EventObject -> JSVal
target :: (IsEventObject obj) => obj -> JSElement
target obj = JSElement (js_target (asEventObject obj))
-- target :: (IsEventObject obj, MonadIO m) => obj -> m JSElement
-- target obj = liftIO (fromJSValUnchecked =<< (js_target (asEventObject obj)))
foreign import javascript unsafe "$1[\"preventDefault\"]()" js_preventDefault ::
EventObject -> IO ()
-- preventDefault :: (IsEventObject obj, MonadIO m) => obj -> m ()
preventDefault :: (IsEventObject obj) => obj -> EIO ()
preventDefault obj = EIO (js_preventDefault (asEventObject obj))
foreign import javascript unsafe "$1[\"stopPropagation\"]()" js_stopPropagation ::
EventObject -> IO ()
-- stopPropagation :: (IsEventObject obj, MonadIO m) => obj -> m ()
stopPropagation :: (IsEventObject obj) => obj -> EIO ()
stopPropagation obj = EIO (js_stopPropagation (asEventObject obj))
* MouseEventObject
newtype MouseEventObject = MouseEventObject { unMouseEventObject :: JSVal }
instance Show MouseEventObject where
show _ = "MouseEventObject"
instance ToJSVal MouseEventObject where
toJSVal = return . unMouseEventObject
# INLINE toJSVal #
instance FromJSVal MouseEventObject where
fromJSVal = return . fmap MouseEventObject . maybeJSNullOrUndefined
# INLINE fromJSVal #
instance IsEventObject MouseEventObject where
asEventObject (MouseEventObject jsval) = EventObject jsval
foreign import javascript unsafe "$1[\"clientX\"]" clientX ::
MouseEventObject -> Double
foreign import javascript unsafe "$1[\"clientY\"]" clientY ::
MouseEventObject -> Double
foreign import javascript unsafe "$1[\"button\"]" button ::
MouseEventObject -> Int
-- * KeyboardEventObject
newtype KeyboardEventObject = KeyboardEventObject { unKeyboardEventObject :: JSVal }
instance ToJSVal KeyboardEventObject where
toJSVal = return . unKeyboardEventObject
# INLINE toJSVal #
instance FromJSVal KeyboardEventObject where
fromJSVal = return . fmap KeyboardEventObject . maybeJSNullOrUndefined
# INLINE fromJSVal #
instance IsEventObject KeyboardEventObject where
asEventObject (KeyboardEventObject jsval) = EventObject jsval
foreign import javascript unsafe "$1[\"charCode\"]" charCode ::
KeyboardEventObject -> Int
foreign import javascript unsafe "$1[\"keyCode\"]" keyCode ::
KeyboardEventObject -> Int
-- * ProgressEventObject
newtype ProgressEventObject = ProgressEventObject { unProgressEventObject :: JSVal }
instance ToJSVal ProgressEventObject where
toJSVal = return . unProgressEventObject
# INLINE toJSVal #
instance FromJSVal ProgressEventObject where
fromJSVal = return . fmap ProgressEventObject . maybeJSNullOrUndefined
# INLINE fromJSVal #
-- charCode :: (MonadIO m) => KeyboardEventObject -> IO
-- * EventObjectOf
type family EventObjectOf event :: *
type instance EventObjectOf Event = EventObject
type instance EventObjectOf MouseEvent = MouseEventObject
type instance EventObjectOf KeyboardEvent = KeyboardEventObject
type instance EventObjectOf FormEvent = EventObject
type instance EventObjectOf ProgressEvent = ProgressEventObject
type instance EventObjectOf ClipboardEvent = ClipboardEventObject
* DOMRect
newtype DOMClientRect = DomClientRect { unDomClientRect :: JSVal }
foreign import javascript unsafe "$1[\"width\"]" width ::
DOMClientRect -> Double
foreign import javascript unsafe "$1[\"top\"]" rectTop ::
DOMClientRect -> Double
foreign import javascript unsafe "$1[\"left\"]" rectLeft ::
DOMClientRect -> Double
foreign import javascript unsafe "$1[\"right\"]" rectRight ::
DOMClientRect -> Double
foreign import javascript unsafe "$1[\"bottom\"]" rectBottom ::
DOMClientRect -> Double
foreign import javascript unsafe "$1[\"height\"]" height ::
DOMClientRect -> Double
foreign import javascript unsafe "$1[\"getBoundingClientRect\"]()" js_getBoundingClientRect ::
JSElement -> IO DOMClientRect
getBoundingClientRect :: (MonadIO m) => JSElement -> m DOMClientRect
getBoundingClientRect = liftIO . js_getBoundingClientRect
-- * addEventListener
-- FIXME: Element is overly restrictive
foreign import javascript unsafe "$1[\"addEventListener\"]($2, $3,\n$4)"
js_addEventListener :: EventTarget -> JSString -> Callback (JSVal -> IO ()) -> Bool -> IO ()
addEventListener :: (MonadIO m, IsEventTarget self, IsEvent event, FromJSVal (EventObjectOf event)) =>
self
-> event
-> (EventObjectOf event -> IO ())
-> Bool
-> m ()
addEventListener self event callback useCapture = liftIO $
do cb <- syncCallback1 ThrowWouldBlock callback'
js_addEventListener (toEventTarget self) (eventToJSString event) cb useCapture
where
callback' = \ev ->
do (Just eventObject) <- fromJSVal ev
callback eventObject
-- | < -US/docs/Web/API/EventTarget.addEventListener Mozilla EventTarget.addEventListener documentation >
addEventListener
: : ( MonadIO m , IsEventTarget self ) = >
self
- > EventType
- > Callback ( IO ( ) )
- > ( )
addEventListener self type ' listener = liftIO
( ( toEventTarget self )
type ''
listener
-- ( maybe jsNull pToJSVal listener )
)
where
type '' = case type ' of
Change - > JS.pack " change "
Click - > JS.pack " click "
Input - > JS.pack " input "
Blur - > JS.pack " blur "
Keydown - > JS.pack " keydown "
Keyup - > JS.pack " keyup "
Keypress - > JS.pack " keypress "
ReadyStateChange - > JS.pack " readystatechange "
EventTxt s - > s
-- | <-US/docs/Web/API/EventTarget.addEventListener Mozilla EventTarget.addEventListener documentation>
addEventListener
:: (MonadIO m, IsEventTarget self) =>
self
-> EventType
-> Callback (IO ())
-> Bool
-> m ()
addEventListener self type' listener useCapture
= liftIO
(js_addEventListener (toEventTarget self)
type''
listener
-- (maybe jsNull pToJSVal listener)
useCapture)
where
type'' = case type' of
Change -> JS.pack "change"
Click -> JS.pack "click"
Input -> JS.pack "input"
Blur -> JS.pack "blur"
Keydown -> JS.pack "keydown"
Keyup -> JS.pack "keyup"
Keypress -> JS.pack "keypress"
ReadyStateChange -> JS.pack "readystatechange"
EventTxt s -> s
-}
-- * XMLHttpRequest
newtype XMLHttpRequest = XMLHttpRequest { unXMLHttpRequest :: JSVal }
instance Eq (XMLHttpRequest) where
(XMLHttpRequest a) == (XMLHttpRequest b) = js_eq a b
instance IsEventTarget XMLHttpRequest where
toEventTarget = EventTarget . unXMLHttpRequest
instance PToJSVal XMLHttpRequest where
pToJSVal = unXMLHttpRequest
{ - # INLINE pToJSVal #
instance PToJSVal XMLHttpRequest where
pToJSVal = unXMLHttpRequest
{-# INLINE pToJSVal #-}
instance PFromJSVal XMLHttpRequest where
pFromJSVal = XMLHttpRequest
# INLINE pFromJSVal #
-}
instance ToJSVal XMLHttpRequest where
toJSVal = return . unXMLHttpRequest
# INLINE toJSVal #
instance FromJSVal XMLHttpRequest where
fromJSVal = return . fmap XMLHttpRequest . maybeJSNullOrUndefined
# INLINE fromJSVal #
foreign import javascript unsafe "new window[\"XMLHttpRequest\"]()"
js_newXMLHttpRequest :: IO XMLHttpRequest
| < -US/docs/Web/API/XMLHttpRequest Mozilla XMLHttpRequest documentation >
newXMLHttpRequest :: (MonadIO m) => m XMLHttpRequest
newXMLHttpRequest
= liftIO js_newXMLHttpRequest
foreign import javascript unsafe "$1[\"open\"]($2, $3, $4)"
js_open ::
XMLHttpRequest ->
JSString -> JSString -> Bool -> {- JSString -> JSString -> -} IO ()
| < -US/docs/Web/API/XMLHttpRequest.open Mozilla XMLHttpRequest.open documentation >
open ::
(MonadIO m) =>
XMLHttpRequest -> Text -> Text -> Bool -> m ()
open self method url async
= liftIO (js_open self (textToJSString method) (textToJSString url) async)
foreign import javascript unsafe "$1[\"setRequestHeader\"]($2,$3)"
js_setRequestHeader
:: XMLHttpRequest
-> JSString
-> JSString
-> IO ()
setRequestHeader :: (MonadIO m) =>
XMLHttpRequest
-> Text
-> Text
-> m ()
setRequestHeader self header value =
liftIO (js_setRequestHeader self (textToJSString header) (textToJSString value))
foreign import javascript interruptible " h$dom$sendXHR($1 , $ 2 , $ c ) ; " js_send : : ( ) - > IO Int
-- | < -US/docs/Web/API/XMLHttpRequest#send ( ) Mozilla XMLHttpRequest.send documentation >
send : : ( MonadIO m ) = > XMLHttpRequest - > m ( )
send self = liftIO $ js_send ( unXMLHttpRequest self ) jsNull > > return ( ) -- > > = throwXHRError
-- | <-US/docs/Web/API/XMLHttpRequest#send() Mozilla XMLHttpRequest.send documentation>
send :: (MonadIO m) => XMLHttpRequest -> m ()
send self = liftIO $ js_send (unXMLHttpRequest self) jsNull >> return () -- >>= throwXHRError
-}
foreign import javascript unsafe "$1[\"send\"]()" js_send ::
XMLHttpRequest -> IO ()
| < -US/docs/Web/API/XMLHttpRequest#send ( ) Mozilla XMLHttpRequest.send documentation >
send :: (MonadIO m) => XMLHttpRequest -> m ()
send self =
liftIO $ js_send self >> return () -- >>= throwXHRError
foreign import javascript unsafe "$1[\"send\"]($2)" js_sendString ::
XMLHttpRequest -> JSString -> IO ()
| < -US/docs/Web/API/XMLHttpRequest#send ( ) Mozilla XMLHttpRequest.send documentation >
sendString :: (MonadIO m) => XMLHttpRequest -> JSString -> m ()
sendString self str =
liftIO $ js_sendString self str >> return () -- >>= throwXHRError
foreign import javascript unsafe "$1[\"send\"]($2)" js_sendArrayBuffer ::
XMLHttpRequest -> JSVal -> IO ()
sendArrayBuffer :: (MonadIO m) => XMLHttpRequest -> Buffer -> m ()
sendArrayBuffer xhr buf =
liftIO $ do ref <- fmap (pToJSVal . getArrayBuffer) (thaw buf)
js_sendArrayBuffer xhr ref
foreign import javascript unsafe "$1[\"send\"]($2)" js_sendData ::
XMLHttpRequest
-> JSVal
-> IO ()
foreign import javascript unsafe "$1[\"readyState\"]"
js_getReadyState :: XMLHttpRequest -> IO Word
-- | <-US/docs/Web/API/XMLHttpRequest.readyState Mozilla XMLHttpRequest.readyState documentation>
getReadyState :: (MonadIO m) => XMLHttpRequest -> m Word
getReadyState self
= liftIO (js_getReadyState self)
foreign import javascript unsafe "$1[\"responseType\"]"
js_getResponseType ::
XMLHttpRequest -> IO JSString -- XMLHttpRequestResponseType
| < Https-US/docs/Web/API/XMLHttpRequest.responseType Mozilla XMLHttpRequest.responseType documentation >
getResponseType ::
(MonadIO m) => XMLHttpRequest -> m Text
getResponseType self
= liftIO (textFromJSString <$> js_getResponseType self)
foreign import javascript unsafe "$1[\"responseType\"] = $2"
js_setResponseType ::
XMLHttpRequest -> JSString -> IO () -- XMLHttpRequestResponseType
setResponseType :: (MonadIO m) =>
XMLHttpRequest
-> Text
-> m ()
setResponseType self typ =
liftIO $ js_setResponseType self (textToJSString typ)
data XMLHttpRequestResponseType = XMLHttpRequestResponseType
| XMLHttpRequestResponseTypeArraybuffer
| XMLHttpRequestResponseTypeBlob
| XMLHttpRequestResponseTypeDocument
| XMLHttpRequestResponseTypeJson
| XMLHttpRequestResponseTypeText
foreign import javascript unsafe "\"\""
js_XMLHttpRequestResponseType :: JSVal -- XMLHttpRequestResponseType
foreign import javascript unsafe "\"arraybuffer\""
js_XMLHttpRequestResponseTypeArraybuffer ::
JSVal -- XMLHttpRequestResponseType
foreign import javascript unsafe "\"blob\""
js_XMLHttpRequestResponseTypeBlob ::
JSVal -- XMLHttpRequestResponseType
foreign import javascript unsafe "\"document\""
js_XMLHttpRequestResponseTypeDocument ::
JSVal -- XMLHttpRequestResponseType
foreign import javascript unsafe "\"json\""
js_XMLHttpRequestResponseTypeJson ::
JSVal -- XMLHttpRequestResponseType
foreign import javascript unsafe "\"text\""
js_XMLHttpRequestResponseTypeText ::
JSVal -- XMLHttpRequestResponseType
instance PToJSVal XMLHttpRequestResponseType where
pToJSVal XMLHttpRequestResponseType = js_XMLHttpRequestResponseType
pToJSVal XMLHttpRequestResponseTypeArraybuffer
= js_XMLHttpRequestResponseTypeArraybuffer
pToJSVal XMLHttpRequestResponseTypeBlob
= js_XMLHttpRequestResponseTypeBlob
pToJSVal XMLHttpRequestResponseTypeDocument
= js_XMLHttpRequestResponseTypeDocument
pToJSVal XMLHttpRequestResponseTypeJson
= js_XMLHttpRequestResponseTypeJson
pToJSVal
= js_XMLHttpRequestResponseTypeText
instance PToJSVal XMLHttpRequestResponseType where
pToJSVal XMLHttpRequestResponseType = js_XMLHttpRequestResponseType
pToJSVal XMLHttpRequestResponseTypeArraybuffer
= js_XMLHttpRequestResponseTypeArraybuffer
pToJSVal XMLHttpRequestResponseTypeBlob
= js_XMLHttpRequestResponseTypeBlob
pToJSVal XMLHttpRequestResponseTypeDocument
= js_XMLHttpRequestResponseTypeDocument
pToJSVal XMLHttpRequestResponseTypeJson
= js_XMLHttpRequestResponseTypeJson
pToJSVal XMLHttpRequestResponseTypeText
= js_XMLHttpRequestResponseTypeText
-}
instance ToJSVal XMLHttpRequestResponseType where
toJSVal XMLHttpRequestResponseType
= return js_XMLHttpRequestResponseType
toJSVal XMLHttpRequestResponseTypeArraybuffer
= return js_XMLHttpRequestResponseTypeArraybuffer
toJSVal XMLHttpRequestResponseTypeBlob
= return js_XMLHttpRequestResponseTypeBlob
toJSVal XMLHttpRequestResponseTypeDocument
= return js_XMLHttpRequestResponseTypeDocument
toJSVal XMLHttpRequestResponseTypeJson
= return js_XMLHttpRequestResponseTypeJson
toJSVal XMLHttpRequestResponseTypeText
= return js_XMLHttpRequestResponseTypeText
{-
instance PFromJSVal XMLHttpRequestResponseType where
pFromJSVal x
| x == js_XMLHttpRequestResponseType = XMLHttpRequestResponseType
pFromJSVal x
| x == js_XMLHttpRequestResponseTypeArraybuffer =
XMLHttpRequestResponseTypeArraybuffer
pFromJSVal x
| x == js_XMLHttpRequestResponseTypeBlob =
XMLHttpRequestResponseTypeBlob
pFromJSVal x
| x == js_XMLHttpRequestResponseTypeDocument =
XMLHttpRequestResponseTypeDocument
pFromJSVal x
| x == js_XMLHttpRequestResponseTypeJson =
XMLHttpRequestResponseTypeJson
pFromJSVal x
| x == js_XMLHttpRequestResponseTypeText =
XMLHttpRequestResponseTypeText
-}
instance FromJSVal XMLHttpRequestResponseType where
-- fromJSValUnchecked = return . pFromJSVal
fromJSVal x
| x == js_XMLHttpRequestResponseType =
return (Just XMLHttpRequestResponseType)
| x == js_XMLHttpRequestResponseTypeArraybuffer =
return (Just XMLHttpRequestResponseTypeArraybuffer)
| x == js_XMLHttpRequestResponseTypeBlob =
return (Just XMLHttpRequestResponseTypeBlob)
| x == js_XMLHttpRequestResponseTypeDocument =
return (Just XMLHttpRequestResponseTypeDocument)
| x == js_XMLHttpRequestResponseTypeJson =
return (Just XMLHttpRequestResponseTypeJson)
| x == js_XMLHttpRequestResponseTypeText =
return (Just XMLHttpRequestResponseTypeText)
foreign import javascript unsafe "$1[\"response\"]" js_getResponse
:: XMLHttpRequest
-> IO JSVal
| < -US/docs/Web/API/XMLHttpRequest.response Mozilla XMLHttpRequest.response documentation >
getResponse :: (MonadIO m) =>
XMLHttpRequest
-> m JSVal
getResponse self =
liftIO (js_getResponse self)
foreign import javascript unsafe "$1[\"responseText\"]"
js_getResponseText :: XMLHttpRequest -> IO JSString
| < -US/docs/Web/API/XMLHttpRequest.responseText Mozilla XMLHttpRequest.responseText documentation >
getResponseText ::
(MonadIO m) => XMLHttpRequest -> m Text
getResponseText self
= liftIO
(textFromJSString <$> js_getResponseText self)
foreign import javascript unsafe "$1[\"status\"]" js_getStatus ::
XMLHttpRequest -> IO Word
| < -US/docs/Web/API/XMLHttpRequest.status Mozilla XMLHttpRequest.status documentation >
getStatus :: (MonadIO m) => XMLHttpRequest -> m Word
getStatus self = liftIO (js_getStatus self)
foreign import javascript unsafe "$1[\"statusText\"]"
js_getStatusText :: XMLHttpRequest -> IO JSString
| < -US/docs/Web/API/XMLHttpRequest.statusText Mozilla XMLHttpRequest.statusText documentation >
getStatusText ::
(MonadIO m) => XMLHttpRequest -> m Text
getStatusText self
= liftIO
(textFromJSString <$> js_getStatusText self)
foreign import javascript unsafe "$1[\"responseURL\"]"
js_getResponseURL :: XMLHttpRequest -> IO JSString
-- * Selection
newtype Selection = Selection { unSelection :: JSVal }
instance ToJSVal Selection where
toJSVal = pure . unSelection
# INLINE toJSVal #
instance FromJSVal Selection where
fromJSVal = pure . fmap Selection . maybeJSNullOrUndefined
# INLINE fromJSVal #
foreign import javascript unsafe "$1[\"getRangeAt\"]($2)"
js_getRangeAt :: Selection -> Int -> IO Range
getRangeAt :: (MonadIO m) => Selection -> Int -> m Range
getRangeAt selection index = liftIO (js_getRangeAt selection index)
foreign import javascript unsafe "$1[\"rangeCount\"]"
js_getRangeCount :: Selection -> IO Int
getRangeCount :: (MonadIO m) => Selection -> m Int
getRangeCount selection = liftIO (js_getRangeCount selection)
foreign import javascript unsafe "$1[\"toString\"]()"
selectionToString :: Selection -> IO JSString
-- * Range
newtype Range = Range { unRange :: JSVal }
instance ToJSVal Range where
toJSVal = pure . unRange
# INLINE toJSVal #
instance FromJSVal Range where
fromJSVal = pure . fmap Range . maybeJSNullOrUndefined
# INLINE fromJSVal #
foreign import javascript unsafe "$1[\"startContainer\"]"
js_getStartContainer :: Range -> IO JSNode
getStartContainer :: (MonadIO m) => Range -> m JSNode
getStartContainer r = liftIO (js_getStartContainer r)
foreign import javascript unsafe "$1[\"startOffset\"]"
js_getStartOffset :: Range -> IO Int
getStartOffset :: (MonadIO m) => Range -> m Int
getStartOffset r = liftIO (js_getStartOffset r)
foreign import javascript unsafe "$1[\"endContainer\"]"
js_getEndContainer :: Range -> IO JSNode
getEndContainer :: (MonadIO m) => Range -> m JSNode
getEndContainer r = liftIO (js_getEndContainer r)
foreign import javascript unsafe "$1[\"endOffset\"]"
js_getEndOffset :: Range -> IO Int
getEndOffset :: (MonadIO m) => Range -> m Int
getEndOffset r = liftIO (js_getEndOffset r)
-- * Pure HTML
data Attr action where
Attr :: Text -> Text -> Attr action
Event :: (FromJSVal (EventObjectOf event), IsEvent event) => event -> (EventObjectOf event -> EIO action) -> Attr action
-- | FIXME: this instances is not really right, but was added for the sake of the test suite
instance Eq (Attr action) where
(Attr k1 v1) == (Attr k2 v2) = (k1 == k2) && (v1 == v2)
_ == _ = False
data HTML action
= forall a. Element { elementName :: Text
, elementAttrs :: [Attr action]
, elementKey :: Maybe Text
, elementDescendants :: Int
, elementChildren :: [HTML action]
}
| CDATA Bool Text
-- | Children [HTML action]
deriving Eq
instance Show (Attr action) where
show (Attr k v) = (Text.unpack k) <> " := " <> (Text.unpack v) <> " "
show (Event _eventType _) = "Event " -- ++ show eventType ++ " <function>"
instance Show (HTML action) where
show (Element tagName attrs _key _count children) =
(Text.unpack tagName) <> " [" <> concat (map show attrs) <> "]\n" <> concat (map showChild children)
where
showChild c = " " <> show c <> "\n"
show (CDATA b txt) = Text.unpack txt
descendants :: [HTML action] -> Int
descendants elems = sum [ d | Element _ _ _ d _ <- elems] + (length elems)
renderHTML :: forall action m. (MonadIO m) => (action -> IO ()) -> JSDocument -> HTML action -> m (Maybe JSNode)
renderHTML _ doc (CDATA _ t) = fmap (fmap toJSNode) $ createJSTextNode doc t
renderHTML handle doc (Element tag {- events -} attrs _ _ children) =
do me <- createJSElement doc tag
case me of
Nothing -> return Nothing
(Just e) ->
do mapM_ (\c -> appendChild e =<< renderHTML handle doc c) children
mapM_ (doAttr e) attrs
let events ' = [ ev | ev@(Event ev f ) < - attrs ]
' = [ ( k , v ) | Attr k v < - attrs ]
liftIO $ mapM _ ( \(k , v ) - > setAttribute e k v ) attrs '
liftIO $ mapM _ ( handleEvent e ) events '
let events' = [ ev | ev@(Event ev f) <- attrs]
attrs' = [ (k,v) | Attr k v <- attrs]
liftIO $ mapM_ (\(k, v) -> setAttribute e k v) attrs'
liftIO $ mapM_ (handleEvent e) events'
-}
return (Just $ toJSNode e)
where
doAttr elem (Attr k v) = setAttribute elem k v
doAttr elem (Event eventType toAction) =
addEventListener elem eventType (\e -> handle =<< eioToIO (toAction e)) False
{-
handle' :: JSElement -> (Maybe JSString -> action) -> IO ()
handle' elem toAction =
do ms <- getValue elem
handle (toAction ms)
-}
-- handleEvent :: JSElement -> Attr (event, EventObjectOf event -> action) -> IO ()
{-
handleEvent elem (Event eventType toAction) =
addEventListener elem eventType (\e -> handle =<< toAction e) False
-}
{-
do cb <- asyncCallback (handle' elem toAction) -- FIXME: free ?
addEventListener elem eventType cb False
-}
-- * DataTransfer
newtype DataTransfer = DataTransfer { unDataTransfer :: JSVal }
instance Show DataTransfer where
show _ = "DataTransfer"
instance ToJSVal DataTransfer where
toJSVal = pure . unDataTransfer
# INLINE toJSVal #
instance FromJSVal DataTransfer where
fromJSVal = pure . fmap DataTransfer . maybeJSNullOrUndefined
# INLINE fromJSVal #
foreign import javascript unsafe "$1[\"getData\"]($2)" js_getDataTransferData ::
DataTransfer -> JSString -> IO JSString
getDataTransferData :: -- (MonadIO m) =>
DataTransfer
-> JSString -- ^ format
-> EIO JSString
getDataTransferData dt format = EIO (js_getDataTransferData dt format)
foreign import javascript unsafe "$1[\"setData\"]($2, $3)" js_setDataTransferData ::
DataTransfer -> JSString -> JSString -> IO ()
setDataTransferData :: DataTransfer
-> JSString -- ^ format
-> JSString -- ^ data
-> EIO ()
setDataTransferData dataTransfer format data_ = EIO (js_setDataTransferData dataTransfer format data_)
-- * Clipboard
data ClipboardEvent
= Copy
| Cut
| Paste
deriving (Eq, Ord, Show, Read)
instance IsEvent ClipboardEvent where
eventToJSString Copy = JS.pack "copy"
eventToJSString Cut = JS.pack "cut"
eventToJSString Paste = JS.pack "paste"
*
newtype ClipboardEventObject = ClipboardEventObject { unClipboardEventObject :: JSVal }
instance Show ClipboardEventObject where
show _ = "ClipboardEventObject"
instance ToJSVal ClipboardEventObject where
toJSVal = pure . unClipboardEventObject
# INLINE toJSVal #
instance FromJSVal ClipboardEventObject where
fromJSVal = pure . fmap ClipboardEventObject . maybeJSNullOrUndefined
# INLINE fromJSVal #
instance IsEventObject ClipboardEventObject where
asEventObject (ClipboardEventObject jsval) = EventObject jsval
foreign import javascript unsafe "$1[\"clipboardData\"]" clipboardData ::
ClipboardEventObject -> EIO DataTransfer
-- * Canvas
newtype JSContext2D = JSContext2D { unJSContext :: JSVal }
instance ToJSVal JSContext2D where
toJSVal = return . unJSContext
# INLINE toJSVal #
instance FromJSVal JSContext2D where
fromJSVal = return . fmap JSContext2D . maybeJSNullOrUndefined
# INLINE fromJSVal #
foreign import javascript unsafe "$1[\"getContext\"](\"2d\")"
js_getContext2d ::
JSElement -> IO JSVal
getContext2D :: (MonadIO m) => JSElement -> m (Maybe JSContext2D)
getContext2D elem = liftIO $ fromJSVal =<< js_getContext2d elem
foreign import javascript unsafe "$1[\"fillRect\"]($2, $3, $4, $5)"
js_fillRect ::
JSContext2D -> Double -> Double -> Double -> Double -> IO ()
fillRect :: JSContext2D -> Double -> Double -> Double -> Double -> IO ()
fillRect = js_fillRect
foreign import javascript unsafe "$1[\"clearRect\"]($2, $3, $4, $5)"
js_clearRect ::
JSContext2D -> Double -> Double -> Double -> Double -> IO ()
clearRect :: JSContext2D -> Double -> Double -> Double -> Double -> IO ()
clearRect = js_clearRect
renderColor :: Color -> JSString
renderColor (ColorName c) = c
renderStyle :: Style -> JSString
renderStyle (StyleColor color) = renderColor color
foreign import javascript unsafe "$1[\"fillStyle\"] = $2"
js_fillStyle ::
JSContext2D -> JSString -> IO ()
setFillStyle :: JSContext2D -> Style -> IO ()
setFillStyle ctx style = js_fillStyle ctx (renderStyle style)
foreign import javascript unsafe "$1[\"strokeStyle\"] = $2"
js_strokeStyle ::
JSContext2D -> JSString -> IO ()
setStrokeStyle :: JSContext2D -> Style -> IO ()
setStrokeStyle ctx style = js_strokeStyle ctx (renderStyle style)
foreign import javascript unsafe "$1[\"save\"]()"
js_save ::
JSContext2D -> IO ()
save :: (MonadIO m) => JSContext2D -> m ()
save = liftIO . js_save
foreign import javascript unsafe "$1[\"restore\"]()"
js_restore ::
JSContext2D -> IO ()
restore :: (MonadIO m) => JSContext2D -> m ()
restore = liftIO . js_restore
foreign import javascript unsafe "$1[\"moveTo\"]($2, $3)"
js_moveTo ::
JSContext2D -> Double -> Double -> IO ()
moveTo :: (MonadIO m) => JSContext2D -> Double -> Double -> m ()
moveTo ctx x y = liftIO $ js_moveTo ctx x y
foreign import javascript unsafe "$1[\"lineTo\"]($2, $3)"
js_lineTo ::
JSContext2D -> Double -> Double -> IO ()
lineTo :: (MonadIO m) => JSContext2D -> Double -> Double -> m ()
lineTo ctx x y = liftIO $ js_lineTo ctx x y
foreign import javascript unsafe "$1[\"arc\"]($2, $3, $4, $5, $6, $7)"
js_arc ::
JSContext2D -> Double -> Double -> Double -> Double -> Double -> Bool -> IO ()
arc :: (MonadIO m) => JSContext2D -> Double -> Double -> Double -> Double -> Double -> Bool -> m ()
arc ctx x y radius startAngle endAngle counterClockwise = liftIO $ js_arc ctx x y radius startAngle endAngle counterClockwise
foreign import javascript unsafe "$1[\"beginPath\"]()"
js_beginPath ::
JSContext2D -> IO ()
beginPath :: (MonadIO m) => JSContext2D -> m ()
beginPath = liftIO . js_beginPath
foreign import javascript unsafe "$1[\"stroke\"]()"
js_stroke ::
JSContext2D -> IO ()
stroke :: (MonadIO m) => JSContext2D -> m ()
stroke = liftIO . js_stroke
foreign import javascript unsafe "$1[\"fill\"]()"
js_fill ::
JSContext2D -> IO ()
fill :: (MonadIO m) => JSContext2D -> m ()
fill = liftIO . js_fill
foreign import javascript unsafe "$1[\"lineWidth\"] = $2"
js_setLineWidth ::
JSContext2D -> Double -> IO ()
setLineWidth :: (MonadIO m) => JSContext2D -> Double -> m ()
setLineWidth ctx w = liftIO $ js_setLineWidth ctx w
-- * Font/Text
foreign import javascript unsafe "$1[\"font\"] = $2"
js_font ::
JSContext2D -> JSString -> IO ()
setFont :: (MonadIO m) => JSContext2D -> JSString -> m ()
setFont ctx font = liftIO $ js_font ctx font
foreign import javascript unsafe "$1[\"textAlign\"] = $2"
js_textAlign ::
JSContext2D -> JSString -> IO ()
data TextAlign
= AlignStart
| AlignEnd
| AlignLeft
| AlignCenter
| AlignRight
deriving (Eq, Ord, Show, Read)
textAlignToJSString :: TextAlign -> JSString
textAlignToJSString AlignStart = JS.pack "start"
textAlignToJSString AlignEnd = JS.pack "end"
textAlignToJSString AlignLeft = JS.pack "left"
textAlignToJSString AlignCenter = JS.pack "center"
textAlignToJSString AlignRight = JS.pack "right"
setTextAlign :: (MonadIO m) => JSContext2D -> TextAlign -> m ()
setTextAlign ctx align = liftIO $ js_textAlign ctx (textAlignToJSString align)
foreign import javascript unsafe "$1[\"fillText\"]($2, $3, $4)"
js_fillText :: JSContext2D -> JSString -> Double -> Double -> IO ()
foreign import javascript unsafe "$1[\"fillText\"]($2, $3, $4, $5)"
js_fillTextMaxWidth ::
JSContext2D -> JSString -> Double -> Double -> Double -> IO ()
fillText :: (MonadIO m) =>
JSContext2D
-> JSString
-> Double
-> Double
-> Maybe Double
-> m ()
fillText ctx txt x y Nothing = liftIO $ js_fillText ctx txt x y
fillText ctx txt x y (Just maxWidth) = liftIO $ js_fillTextMaxWidth ctx txt x y maxWidth
-- * Various Transformations
foreign import javascript unsafe "$1[\"scale\"]($2, $3)"
js_scale :: JSContext2D -> Double -> Double -> IO ()
foreign import javascript unsafe "alert($1)"
js_alert :: JSString -> IO ()
scale :: (MonadIO m) => JSContext2D -> Double -> Double -> m ()
scale ctx x y = liftIO $ js_scale ctx x y
foreign import javascript unsafe "$1[\"rotate\"]($2)"
js_rotate :: JSContext2D -> Double -> IO ()
-- | apply rotation to commands that draw on the canvas
rotate :: (MonadIO m) =>
JSContext2D -- ^ canvas to affect
-> Double -- ^ rotation in radians
-> m ()
rotate ctx r = liftIO $ js_rotate ctx r
foreign import javascript unsafe "$1[\"translate\"]($2, $3)"
js_translate :: JSContext2D -> Double -> Double -> IO ()
-- | apply translation to commands that draw on the canvas
translate :: (MonadIO m) =>
JSContext2D -- ^ canvas
-> Double -- ^ x translation
-> Double -- ^ y translation
-> m ()
translate ctx x y = liftIO $ js_translate ctx x y
data Gradient = Gradient
deriving (Eq, Ord, Show, Read)
data Pattern = Pattern
deriving (Eq, Ord, Show, Read)
type Percentage = Double
type Alpha = Double
data Color
= ColorName JSString
| RGBA Percentage Percentage Percentage Alpha
deriving (Eq, Ord, Show, Read)
data Style
= StyleColor Color
| StyleGradient Gradient
| StylePattern Pattern
deriving (Eq, Ord, Show, Read)
data Rect
= Rect { _rectX :: Double
, _rectY :: Double
, _rectWidth :: Double
, _rectHeight :: Double
}
deriving (Eq, Ord, Show, Read)
-- -US/docs/Web/API/Path2D
data Path2D
= MoveTo Double Double
| LineTo Double Double
| PathRect Rect
| Arc Double Double Double Double Double Bool
deriving (Eq, Ord, Show, Read)
data Draw
= FillRect Rect
| ClearRect Rect
| Stroke [Path2D]
| Fill [Path2D]
| FillText JSString Double Double (Maybe Double)
deriving (Eq, Ord, Show, Read)
data Context2D
= FillStyle Style
| StrokeStyle Style
| LineWidth Double
| Font JSString
| TextAlign TextAlign
| Scale Double Double
| Translate Double Double
| Rotate Double
deriving (Eq, Read, Show)
-- | this is not sustainable. A Set of attributes is probably a better choice
data Canvas = Canvas
{ _canvasId :: Text
, _canvas :: Canvas2D
}
deriving (Eq, Show, Read)
data Canvas2D
= WithContext2D [Context2D] [ Canvas2D ]
| Draw Draw
deriving (Eq, Show, Read)
mkPath :: (MonadIO m) => JSContext2D -> [Path2D] -> m ()
mkPath ctx segments =
do beginPath ctx
mapM_ (mkSegment ctx) segments
where
mkSegment ctx segment =
case segment of
(MoveTo x y) -> moveTo ctx x y
(LineTo x y) -> lineTo ctx x y
(Arc x y radius startAngle endAngle counterClockwise) -> arc ctx x y radius startAngle endAngle counterClockwise
( ( Rect x y w h ) ) - > rect x y w h
--
drawCanvas :: Canvas -> IO ()
drawCanvas (Canvas cid content) =
do (Just document) <- currentDocument
mCanvasElem <- getElementById document (textToJSString cid)
case mCanvasElem of
Nothing -> pure ()
(Just canvasElem) ->
/
-- NOTE: backingStorePixelRatio is deprecated, we just ignore it
do rescaleCanvas <- do ms <- getData canvasElem (JS.pack "rescale")
case ms of
Nothing -> pure True
(Just s) ->
case (JS.unpack s) of
"true" -> pure True
_ -> pure False
ratio <- fmap (fromMaybe 1) (devicePixelRatio =<< window)
(w, h) <-
if rescaleCanvas
then do (Just oldWidth) <- fmap (read . JS.unpack) <$> getAttribute canvasElem (JS.pack "width")
(Just oldHeight) <- fmap (read . JS.unpack) <$> getAttribute canvasElem (JS.pack "height")
js_setAttribute canvasElem (JS.pack "width") (JS.pack $ show $ oldWidth * ratio)
js_setAttribute canvasElem (JS.pack "height") (JS.pack $ show $ oldHeight * ratio)
setStyle canvasElem (JS.pack "width") (JS.pack $ (show oldWidth) ++ "px")
setStyle canvasElem (JS.pack "height") (JS.pack $ (show oldHeight) ++ "px")
setData canvasElem (JS.pack "rescale") (JS.pack "false")
pure (oldWidth * ratio, oldHeight * ratio)
else do (Just width) <- fmap (read . JS.unpack) <$> getAttribute canvasElem (JS.pack "width")
(Just height) <- fmap (read . JS.unpack) <$> getAttribute canvasElem (JS.pack "height")
pure (width, height)
mctx <- getContext2D canvasElem
case mctx of
Nothing -> pure ()
(Just ctx) -> do
when (rescaleCanvas) (scale ctx ratio ratio)
clearRect ctx 0 0 w h
drawCanvas' ctx content
where
drawCanvas' ctx (Draw (FillRect (Rect x y w h))) =
fillRect ctx x y w h
drawCanvas' ctx (Draw (ClearRect (Rect x y w h))) =
clearRect ctx x y w h
drawCanvas' ctx (Draw (Stroke path2D)) =
do mkPath ctx path2D
stroke ctx
drawCanvas' ctx (Draw (Fill path2D)) =
do mkPath ctx path2D
fill ctx
drawCanvas' ctx (Draw (FillText text x y maxWidth)) =
do fillText ctx text x y maxWidth
drawCanvas' ctx (WithContext2D ctx2d content) =
do save ctx
mapM_ (setContext2D ctx) ctx2d
mapM_ (drawCanvas' ctx) content
restore ctx
where
setContext2D ctx op =
case op of
(FillStyle style) -> setFillStyle ctx style
(StrokeStyle style) -> setStrokeStyle ctx style
(LineWidth w) -> setLineWidth ctx w
(Font font) -> setFont ctx font
(TextAlign a) -> setTextAlign ctx a
(Scale x y) -> scale ctx x y
(Translate x y) -> translate ctx x y
(Rotate r ) -> rotate ctx r
| null | https://raw.githubusercontent.com/stepcut/isomaniac/ee4ab64bb5571b66335a913287d1385dcf9584fe/Web/ISO/Types.hs | haskell | import GHCJS.Prim (ToJSString(..), FromJSString(..))
* JSNode
* IsJSNode
* JSNodeList
>>= fromJSValUnchecked)
* parentNode
* JSDocument
* JSWindow
* JSElement
* createJSElement
| <-US/docs/Web/API/JSDocument.createJSElement Mozilla JSDocument.createJSElement documentation>
* childNodes
* getElementsByName
| <-US/docs/Web/API/Document.getElementsByName Mozilla Document.getElementsByName documentation>
| <-US/docs/Web/API/Document.getElementsByTagName Mozilla Document.getElementsByTagName documentation>
* textContent
* textContent
* replaceData
FIMXE: perhaps only a TextNode?
FIMXE: really a maybe?
* replaceChild
* firstChild
setCSS :: (MonadIO m) =>
JSElement
-> JSString
-> JSString
-> m ()
setCSS elem name value =
liftIO $ js_setCSS elem name value
* value
* dataset
getData self name = liftIO (fmap fromJSVal <$> maybeJSNullOrUndefined <$> (js_getData (toJSNode self) name))
* JSTextNode
deriving (Eq)
* createTextNode
* Events
toEventTarget = EventTarget
| Search
| Select
eventToJSString Blur = JS.pack "blur"
eventToJSString Focus = JS.pack "focus"
eventToJSString Search = JS.pack "search"
eventToJSString Select = JS.pack "select"
-US/docs/Web/API/ProgressEvent
data ProgressEvent =
* Event Objects
target :: (IsEventObject obj, MonadIO m) => obj -> m JSElement
target obj = liftIO (fromJSValUnchecked =<< (js_target (asEventObject obj)))
preventDefault :: (IsEventObject obj, MonadIO m) => obj -> m ()
stopPropagation :: (IsEventObject obj, MonadIO m) => obj -> m ()
* KeyboardEventObject
* ProgressEventObject
charCode :: (MonadIO m) => KeyboardEventObject -> IO
* EventObjectOf
* addEventListener
FIXME: Element is overly restrictive
| < -US/docs/Web/API/EventTarget.addEventListener Mozilla EventTarget.addEventListener documentation >
( maybe jsNull pToJSVal listener )
| <-US/docs/Web/API/EventTarget.addEventListener Mozilla EventTarget.addEventListener documentation>
(maybe jsNull pToJSVal listener)
* XMLHttpRequest
# INLINE pToJSVal #
JSString -> JSString ->
| < -US/docs/Web/API/XMLHttpRequest#send ( ) Mozilla XMLHttpRequest.send documentation >
> > = throwXHRError
| <-US/docs/Web/API/XMLHttpRequest#send() Mozilla XMLHttpRequest.send documentation>
>>= throwXHRError
>>= throwXHRError
>>= throwXHRError
| <-US/docs/Web/API/XMLHttpRequest.readyState Mozilla XMLHttpRequest.readyState documentation>
XMLHttpRequestResponseType
XMLHttpRequestResponseType
XMLHttpRequestResponseType
XMLHttpRequestResponseType
XMLHttpRequestResponseType
XMLHttpRequestResponseType
XMLHttpRequestResponseType
XMLHttpRequestResponseType
instance PFromJSVal XMLHttpRequestResponseType where
pFromJSVal x
| x == js_XMLHttpRequestResponseType = XMLHttpRequestResponseType
pFromJSVal x
| x == js_XMLHttpRequestResponseTypeArraybuffer =
XMLHttpRequestResponseTypeArraybuffer
pFromJSVal x
| x == js_XMLHttpRequestResponseTypeBlob =
XMLHttpRequestResponseTypeBlob
pFromJSVal x
| x == js_XMLHttpRequestResponseTypeDocument =
XMLHttpRequestResponseTypeDocument
pFromJSVal x
| x == js_XMLHttpRequestResponseTypeJson =
XMLHttpRequestResponseTypeJson
pFromJSVal x
| x == js_XMLHttpRequestResponseTypeText =
XMLHttpRequestResponseTypeText
fromJSValUnchecked = return . pFromJSVal
* Selection
* Range
* Pure HTML
| FIXME: this instances is not really right, but was added for the sake of the test suite
| Children [HTML action]
++ show eventType ++ " <function>"
events
handle' :: JSElement -> (Maybe JSString -> action) -> IO ()
handle' elem toAction =
do ms <- getValue elem
handle (toAction ms)
handleEvent :: JSElement -> Attr (event, EventObjectOf event -> action) -> IO ()
handleEvent elem (Event eventType toAction) =
addEventListener elem eventType (\e -> handle =<< toAction e) False
do cb <- asyncCallback (handle' elem toAction) -- FIXME: free ?
addEventListener elem eventType cb False
* DataTransfer
(MonadIO m) =>
^ format
^ format
^ data
* Clipboard
* Canvas
* Font/Text
* Various Transformations
| apply rotation to commands that draw on the canvas
^ canvas to affect
^ rotation in radians
| apply translation to commands that draw on the canvas
^ canvas
^ x translation
^ y translation
-US/docs/Web/API/Path2D
| this is not sustainable. A Set of attributes is probably a better choice
NOTE: backingStorePixelRatio is deprecated, we just ignore it | # LANGUAGE ExistentialQuantification , FlexibleContexts , FlexibleInstances , GADTs , JavaScriptFFI , ScopedTypeVariables , TemplateHaskell , TypeFamilies #
# language GeneralizedNewtypeDeriving #
module Web.ISO.Types where
import Control.Applicative (Applicative, Alternative)
import Control.Monad (Monad, MonadPlus)
import Control.Lens ((^.))
import Control.Lens.TH (makeLenses)
import Control.Monad (when)
import Control.Monad.Trans (MonadIO(..))
import Data.Maybe (fromJust)
import Data.Aeson.Types (Parser, Result(..), parse)
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.JSString as JS
import Data.JSString.Text (textToJSString, textFromJSString)
import qualified Data.Text as Text
import JavaScript . TypedArray . ArrayBuffer ( ArrayBuffer )
import GHCJS.Buffer
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (OnBlocked(..), Callback, asyncCallback1, syncCallback1)
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(pToJSVal), PFromJSVal(pFromJSVal))
import GHCJS.Nullable (Nullable(..), nullableToMaybe, maybeToNullable)
import GHCJS.Types (JSVal(..), JSString(..), nullRef, isNull, isUndefined)
instance Eq JSVal where
a == b = js_eq a b
foreign import javascript unsafe
"$1===$2" js_eq :: JSVal -> JSVal -> Bool
maybeJSNullOrUndefined :: JSVal -> Maybe JSVal
maybeJSNullOrUndefined r | isNull r || isUndefined r = Nothing
maybeJSNullOrUndefined r = Just r
newtype EIO a = EIO { eioToIO :: IO a }
deriving (Functor, Applicative, Alternative, Monad, MonadPlus)
fromJSValUnchecked : : ( a ) = > a - > IO a
fromJSValUnchecked j =
do x < - fromJSVal j
case x of
Nothing - > error " failed . "
( Just a ) - > return a
fromJSValUnchecked :: (FromJSVal a) => JSVal a -> IO a
fromJSValUnchecked j =
do x <- fromJSVal j
case x of
Nothing -> error "failed."
(Just a) -> return a
-}
newtype JSNode = JSNode JSVal
unJSNode (JSNode o) = o
instance ToJSVal JSNode where
toJSVal = toJSVal . unJSNode
# INLINE toJSVal #
instance FromJSVal JSNode where
fromJSVal = return . fmap JSNode . maybeJSNullOrUndefined
# INLINE fromJSVal #
class IsJSNode obj where
toJSNode :: (IsJSNode obj) => obj -> JSNode
instance IsJSNode JSNode where
toJSNode = id
newtype JSNodeList = JSNodeList JSVal
unJSNodeList (JSNodeList o) = o
instance ToJSVal JSNodeList where
toJSVal = return . unJSNodeList
# INLINE toJSVal #
instance FromJSVal JSNodeList where
fromJSVal = return . fmap JSNodeList . maybeJSNullOrUndefined
# INLINE fromJSVal #
instance IsJSNode JSNodeList where
toJSNode = JSNode . unJSNodeList
foreign import javascript unsafe "$1[\"item\"]($2)" js_item ::
JSNodeList -> Word -> IO JSNode
| < -US/docs/Web/API/NodeList.item Mozilla NodeList.item documentation >
item ::
(MonadIO m) => JSNodeList -> Word -> m (Maybe JSNode)
item self index
= liftIO
((js_item (self) index) >>= return . Just)
foreign import javascript unsafe "$1[\"length\"]" js_length ::
JSNode -> IO Word
| < -US/docs/Web/API/NodeList.item Mozilla NodeList.item documentation >
getLength :: (MonadIO m, IsJSNode self) => self -> m Word
getLength self
foreign import javascript unsafe " $ 1[\"length\ " ] " : :
- > IO Word
foreign import javascript unsafe "$1[\"parentNode\"]"
js_parentNode :: JSNode -> IO JSVal
parentNode :: (MonadIO m, IsJSNode self) => self -> m (Maybe JSNode)
parentNode self =
liftIO (fromJSVal =<< js_parentNode (toJSNode self))
newtype JSDocument = JSDocument JSVal
unJSDocument (JSDocument o) = o
instance ToJSVal JSDocument where
toJSVal = return . unJSDocument
# INLINE toJSVal #
instance FromJSVal JSDocument where
fromJSVal = return . fmap JSDocument . maybeJSNullOrUndefined
# INLINE fromJSVal #
instance IsJSNode JSDocument where
toJSNode = JSNode . unJSDocument
foreign import javascript unsafe "new window[\"Document\"]()"
js_newDocument :: IO JSDocument
instance IsEventTarget JSDocument where
toEventTarget = EventTarget . unJSDocument
| < -US/docs/Web/API/Document Mozilla Document documentation >
newJSDocument :: (MonadIO m) => m JSDocument
newJSDocument = liftIO js_newDocument
foreign import javascript unsafe "$r = document"
ghcjs_currentDocument :: IO JSDocument
currentDocument :: IO (Maybe JSDocument)
currentDocument = Just <$> ghcjs_currentDocument
newtype JSWindow = JSWindow { unJSWindow :: JSVal }
instance ToJSVal JSWindow where
toJSVal = return . unJSWindow
# INLINE toJSVal #
instance FromJSVal JSWindow where
fromJSVal = return . fmap JSWindow . maybeJSNullOrUndefined
# INLINE fromJSVal #
foreign import javascript unsafe "$r = window"
js_window :: IO JSWindow
instance IsEventTarget JSWindow where
toEventTarget = EventTarget . unJSWindow
window :: (MonadIO m) => m JSWindow
window = liftIO js_window
foreign import javascript unsafe "$1[\"devicePixelRatio\"]"
js_devicePixelRatio :: JSWindow -> IO JSVal
devicePixelRatio :: (MonadIO m) => JSWindow -> m (Maybe Double)
devicePixelRatio w = liftIO (fromJSVal =<< js_devicePixelRatio w)
foreign import javascript unsafe "$1[\"getSelection\"]()"
js_getSelection :: JSWindow -> IO Selection
getSelection :: (MonadIO m) => JSWindow -> m Selection
getSelection w = liftIO (js_getSelection w)
newtype JSElement = JSElement JSVal
unJSElement (JSElement o) = o
instance ToJSVal JSElement where
toJSVal = return . unJSElement
# INLINE toJSVal #
instance FromJSVal JSElement where
fromJSVal = return . fmap JSElement . maybeJSNullOrUndefined
# INLINE fromJSVal #
instance IsJSNode JSElement where
toJSNode = JSNode . unJSElement
foreign import javascript unsafe "$1[\"clientLeft\"]"
js_getClientLeft :: JSElement -> IO Double
getClientLeft :: (MonadIO m) => JSElement -> m Double
getClientLeft = liftIO . js_getClientLeft
foreign import javascript unsafe "$1[\"clientTop\"]"
js_getClientTop :: JSElement -> IO Double
getClientTop :: (MonadIO m) => JSElement -> m Double
getClientTop = liftIO . js_getClientTop
foreign import javascript unsafe "$1[\"clientWidth\"]"
js_getClientWidth :: JSElement -> IO Double
getClientWidth :: (MonadIO m) => JSElement -> m Double
getClientWidth = liftIO . js_getClientWidth
foreign import javascript unsafe "$1[\"clientHeight\"]"
js_getClientHeight :: JSElement -> IO Double
getClientHeight :: (MonadIO m) => JSElement -> m Double
getClientHeight = liftIO . js_getClientHeight
foreign import javascript unsafe "$1[\"createElement\"]($2)"
js_createJSElement ::
JSDocument -> JSString -> IO JSElement
createJSElement ::
(MonadIO m) =>
JSDocument -> Text -> m (Maybe JSElement)
createJSElement document tagName
= liftIO ((js_createJSElement document (textToJSString tagName))
>>= return . Just)
* innerHTML
foreign import javascript unsafe "$1[\"innerHTML\"] = $2"
js_setInnerHTML :: JSElement -> JSString -> IO ()
setInnerHTML :: (MonadIO m) => JSElement -> JSString -> m ()
setInnerHTML elm content = liftIO $ js_setInnerHTML elm content
foreign import javascript unsafe "$1[\"childNodes\"]"
js_childNodes :: JSNode -> IO JSNodeList
childNodes :: (MonadIO m, IsJSNode self) => self -> m JSNodeList
childNodes self
= liftIO (js_childNodes (toJSNode self))
foreign import javascript unsafe "$1[\"getElementsByName\"]($2)"
js_getElementsByName ::
JSDocument -> JSString -> IO JSNodeList
getElementsByName ::
(MonadIO m) =>
JSDocument -> JSString -> m (Maybe JSNodeList)
getElementsByName self elementName
= liftIO
((js_getElementsByName self) elementName
>>= return . Just)
foreign import javascript unsafe "$1[\"getElementsByTagName\"]($2)"
js_getElementsByTagName ::
JSDocument -> JSString -> IO JSNodeList
getElementsByTagName ::
(MonadIO m) =>
JSDocument -> JSString -> m (Maybe JSNodeList)
getElementsByTagName self tagname
= liftIO
((js_getElementsByTagName self tagname)
>>= return . Just)
foreign import javascript unsafe "$1[\"getElementById\"]($2)"
js_getElementsById ::
JSDocument -> JSString -> IO JSElement
| < -US/docs/Web/API/Document.getElementsByTagName Mozilla Document.getElementsById documentation >
getElementById ::
(MonadIO m) =>
JSDocument -> JSString -> m (Maybe JSElement)
getElementById self ident
= liftIO
((js_getElementsById self ident)
>>= return . Just)
*
foreign import javascript unsafe "$1[\"appendChild\"]($2)"
js_appendChild :: JSNode -> JSNode -> IO JSNode
| < -US/docs/Web/API/Node.appendChild Mozilla Node.appendChild documentation >
appendChild :: (MonadIO m, IsJSNode self, IsJSNode newChild) =>
self
-> Maybe newChild
-> m (Maybe JSNode)
appendChild self newChild
= liftIO
((js_appendChild ( (toJSNode self))
(maybe (JSNode jsNull) ( toJSNode) newChild))
>>= return . Just)
probably broken on IE9
foreign import javascript unsafe " $ 1[\"textContent\ " ] = $ 2 "
js_setTextContent : : JSString - > IO ( )
setTextContent : : ( MonadIO m , IsJSNode self , ToJSString content ) = >
self
- > content
- > m ( )
setTextContent self content =
liftIO $ ( js_setTextContent ( ( toJSNode self ) ) ( toJSString content ) )
probably broken on IE9
foreign import javascript unsafe "$1[\"textContent\"] = $2"
js_setTextContent :: JSVal JSNode -> JSString -> IO ()
setTextContent :: (MonadIO m, IsJSNode self, ToJSString content) =>
self
-> content
-> m ()
setTextContent self content =
liftIO $ (js_setTextContent (unJSNode (toJSNode self)) (toJSString content))
-}
foreign import javascript unsafe "$1[\"replaceData\"]($2, $3, $4)" js_replaceData
:: JSNode
-> Word
-> Word
-> JSString
-> IO ()
replaceData :: (MonadIO m, IsJSNode self) =>
self
-> Word
-> Word
-> Text
-> m ()
replaceData self start length string =
liftIO (js_replaceData (toJSNode self) start length (textToJSString string))
* removeChild
foreign import javascript unsafe "$1[\"removeChild\"]($2)"
js_removeChild :: JSNode -> JSNode -> IO JSNode
| < -US/docs/Web/API/Node.removeChild Mozilla Node.removeChild documentation >
(MonadIO m, IsJSNode self, IsJSNode oldChild) =>
self -> Maybe oldChild -> m (Maybe JSNode)
removeChild self oldChild
= liftIO
((js_removeChild (toJSNode self)
(maybe (JSNode jsNull) toJSNode oldChild))
>>= return . Just)
foreign import javascript unsafe "$1[\"replaceChild\"]($2, $3)"
js_replaceChild :: JSNode -> JSNode -> JSNode -> IO JSNode
replaceChild ::
(MonadIO m, IsJSNode self, IsJSNode newChild, IsJSNode oldChild) =>
self -> newChild -> oldChild -> m (Maybe JSNode)
replaceChild self newChild oldChild
= liftIO
(js_replaceChild ((toJSNode self))
((toJSNode) newChild)
((toJSNode) oldChild)
>>= return . Just)
foreign import javascript unsafe "$1[\"firstChild\"]"
js_getFirstChild :: JSNode -> IO JSVal
| < -US/docs/Web/API/Node.firstChild Mozilla Node.firstChild documentation >
getFirstChild :: (MonadIO m, IsJSNode self) => self -> m (Maybe JSNode)
getFirstChild self
= liftIO ((js_getFirstChild ((toJSNode self))) >>= fromJSVal)
removeChildren
:: (MonadIO m, IsJSNode self) =>
self
-> m ()
removeChildren self =
do mc <- getFirstChild self
case mc of
Nothing -> return ()
(Just _) ->
do removeChild self mc
removeChildren self
foreign import javascript unsafe "$1[\"setAttribute\"]($2, $3)"
js_setAttribute :: JSElement -> JSString -> JSString -> IO ()
| < -US/docs/Web/API/Element.setAttribute Mozilla Element.setAttribute documentation >
setAttribute ::
(MonadIO m) =>
JSElement -> Text -> Text -> m ()
setAttribute self name value
= liftIO
(js_setAttribute self (textToJSString name) (textToJSString value))
foreign import javascript unsafe "$1[\"getAttribute\"]($2)"
js_getAttribute :: JSElement -> JSString -> IO JSVal
| < -US/docs/Web/API/Element.setAttribute Mozilla Element.setAttribute documentation >
getAttribute :: (MonadIO m) =>
JSElement
-> JSString
-> m (Maybe JSString)
getAttribute self name = liftIO (js_getAttribute self name >>= fromJSVal)
foreign import javascript unsafe "$1[\"style\"][$2] = $3"
setStyle :: JSElement -> JSString -> JSString -> IO ()
foreign import javascript unsafe "$1[\"value\"]"
js_getValue :: JSNode -> IO JSString
getValue :: (MonadIO m, IsJSNode self) => self -> m (Maybe JSString)
getValue self
= liftIO ((js_getValue (toJSNode self)) >>= return . Just)
foreign import javascript unsafe "$1[\"value\"] = $2"
js_setValue :: JSNode -> JSString -> IO ()
setValue :: (MonadIO m, IsJSNode self) => self -> Text -> m ()
setValue self str =
liftIO (js_setValue (toJSNode self) (textToJSString str))
foreign import javascript unsafe "$1[\"dataset\"][$2]"
js_getData :: JSNode -> JSString -> IO (Nullable JSString)
getData :: (MonadIO m, IsJSNode self) => self -> JSString -> m (Maybe JSString)
getData self name = liftIO (nullableToMaybe <$> js_getData (toJSNode self) name)
foreign import javascript unsafe "$1[\"dataset\"][$2] = $3"
js_setData :: JSNode -> JSString -> JSString -> IO ()
setData :: (MonadIO m, IsJSNode self) => self -> JSString -> JSString -> m ()
setData self name value = liftIO (js_setData (toJSNode self) name value)
unJSTextNode (JSTextNode o) = o
instance ToJSVal JSTextNode where
toJSVal = return . unJSTextNode
# INLINE toJSVal #
instance FromJSVal JSTextNode where
fromJSVal = return . fmap JSTextNode . maybeJSNullOrUndefined
# INLINE fromJSVal #
instance IsJSNode JSTextNode where
toJSNode = JSNode . unJSTextNode
foreign import javascript unsafe "$1[\"createTextNode\"]($2)"
js_createTextNode :: JSDocument -> JSString -> IO JSTextNode
| < -US/docs/Web/API/Document.createTextNode Mozilla Document.createTextNode documentation >
createJSTextNode ::
(MonadIO m) =>
JSDocument -> Text -> m (Maybe JSTextNode)
createJSTextNode document data'
= liftIO
((js_createTextNode document
(textToJSString data'))
>>= return . Just)
newtype EventTarget = EventTarget { unEventTarget :: JSVal }
instance Eq (EventTarget) where
(EventTarget a) == (EventTarget b) = js_eq a b
instance ToJSVal EventTarget where
toJSVal = return . unEventTarget
# INLINE toJSVal #
instance FromJSVal EventTarget where
fromJSVal = return . fmap EventTarget . maybeJSNullOrUndefined
# INLINE fromJSVal #
class IsEventTarget o where
toEventTarget :: o -> EventTarget
instance IsEventTarget JSElement where
toEventTarget = EventTarget . unJSElement
class IsEvent ev where
eventToJSString :: ev -> JSString
data Event
= ReadyStateChange
deriving (Eq, Show, Read)
instance IsEvent Event where
eventToJSString ReadyStateChange = JS.pack "readystatechange"
data MouseEvent
= Click
| ContextMenu
| DblClick
| MouseDown
| MouseEnter
| MouseLeave
| MouseMove
| MouseOver
| MouseOut
| MouseUp
deriving (Eq, Ord, Show, Read)
instance IsEvent MouseEvent where
eventToJSString Click = JS.pack "click"
eventToJSString ContextMenu = JS.pack "contextmenu"
eventToJSString DblClick = JS.pack "dblclick"
eventToJSString MouseDown = JS.pack "MouseDown"
eventToJSString MouseEnter = JS.pack "MouseEnter"
eventToJSString MouseLeave = JS.pack "MouseLeave"
eventToJSString MouseMove = JS.pack "MouseMove"
eventToJSString MouseOver = JS.pack "MouseOver"
eventToJSString MouseOut = JS.pack "MouseOut"
eventToJSString MouseUp = JS.pack "MouseUp"
data KeyboardEvent
= KeyDown
| KeyPress
| KeyUp
deriving (Eq, Ord, Show, Read)
instance IsEvent KeyboardEvent where
eventToJSString KeyDown = JS.pack "keydown"
eventToJSString KeyPress = JS.pack "keypress"
eventToJSString KeyUp = JS.pack "keyup"
data FrameEvent
= FrameAbort
| BeforeUnload
| FrameError
| HashChange
| FrameLoad
| PageShow
| PageHide
| Resize
| Scroll
| Unload
deriving (Eq, Ord, Show, Read)
data FocusEvent
= Blur
| Focus
| FocusIn
| FocusOut
data FormEvent
= Change
| Input
| Invalid
| Reset
| Submit
deriving (Eq, Ord, Show, Read)
instance IsEvent FormEvent where
eventToJSString Change = JS.pack "change"
eventToJSString FocusIn = JS.pack " focusin "
eventToJSString = JS.pack " focusout "
eventToJSString Input = JS.pack "input"
eventToJSString Invalid = JS.pack "invalid"
eventToJSString Reset = JS.pack "reset"
eventToJSString Submit = JS.pack "submit"
data DragEvent
= Drag
| DragEnd
| DragEnter
| DragLeave
| DragOver
| DragStart
| Drop
deriving (Eq, Ord, Show, Read)
data PrintEvent
= AfterPrint
| BeforePrint
deriving (Eq, Ord, Show, Read)
data MediaEvent
= CanPlay
| CanPlayThrough
| DurationChange
| Emptied
| Ended
| MediaError
| LoadedData
| LoadedMetaData
| Pause
| Play
| Playing
| RateChange
| Seeked
| Seeking
| Stalled
| Suspend
| TimeUpdate
| VolumeChange
| Waiting
deriving (Eq, Ord, Show, Read)
data ProgressEvent
= LoadStart
| Progress
| ProgressAbort
| ProgressError
| ProgressLoad
| Timeout
| LoadEnd
deriving (Eq, Ord, Show, Read)
instance IsEvent ProgressEvent where
eventToJSString LoadStart = JS.pack "loadstart"
eventToJSString Progress = JS.pack "progress"
eventToJSString ProgressAbort = JS.pack "abort"
eventToJSString ProgressError = JS.pack "error"
eventToJSString ProgressLoad = JS.pack "load"
eventToJSString Timeout = JS.pack "timeout"
eventToJSString LoadEnd = JS.pack "loadend"
data AnimationEvent
= AnimationEnd
| AnimationInteration
| AnimationStart
deriving (Eq, Ord, Show, Read)
data TransitionEvent
= TransitionEnd
deriving (Eq, Ord, Show, Read)
data ServerSentEvent
= ServerError
| ServerMessage
| Open
deriving (Eq, Ord, Show, Read)
data MiscEvent
= MiscMessage
| Online
| Offline
| PopState
| MiscShow
| Storage
| Toggle
| Wheel
deriving (Eq, Ord, Show, Read)
data TouchEvent
= TouchCancel
| TouchEnd
| TouchMove
| TouchStart
deriving (Eq, Ord, Show, Read)
data EventType
= MouseEvent MouseEvent
| KeyboardEvent KeyboardEvent
| FrameEvent FrameEvent
| FormEvent FormEvent
| DragEvent DragEvent
| ClipboardEvent ClipboardEvent
| PrintEvent PrintEvent
| MediaEvent MediaEvent
| AnimationEvent AnimationEvent
| TransitionEvent TransitionEvent
| ServerSentEvent ServerSentEvent
| MiscEvent MiscEvent
| TouchEvent TouchEvent
deriving (Eq, Ord, Show, Read)
class IsEventObject obj where
asEventObject :: obj -> EventObject
* EventObject
newtype EventObject = EventObject { unEventObject :: JSVal }
instance Show EventObject where
show _ = "EventObject"
instance ToJSVal EventObject where
toJSVal = return . unEventObject
# INLINE toJSVal #
instance FromJSVal EventObject where
fromJSVal = return . fmap EventObject . maybeJSNullOrUndefined
# INLINE fromJSVal #
instance IsEventObject EventObject where
asEventObject = id
foreign import javascript unsafe "$1[\"defaultPrevented\"]" js_defaultPrevented ::
EventObject -> IO Bool
defaultPrevented :: (IsEventObject obj, MonadIO m) => obj -> m Bool
defaultPrevented obj = liftIO (js_defaultPrevented (asEventObject obj))
foreign import javascript unsafe "$1[\"target\"]" js_target ::
EventObject -> JSVal
target :: (IsEventObject obj) => obj -> JSElement
target obj = JSElement (js_target (asEventObject obj))
foreign import javascript unsafe "$1[\"preventDefault\"]()" js_preventDefault ::
EventObject -> IO ()
preventDefault :: (IsEventObject obj) => obj -> EIO ()
preventDefault obj = EIO (js_preventDefault (asEventObject obj))
foreign import javascript unsafe "$1[\"stopPropagation\"]()" js_stopPropagation ::
EventObject -> IO ()
stopPropagation :: (IsEventObject obj) => obj -> EIO ()
stopPropagation obj = EIO (js_stopPropagation (asEventObject obj))
* MouseEventObject
newtype MouseEventObject = MouseEventObject { unMouseEventObject :: JSVal }
instance Show MouseEventObject where
show _ = "MouseEventObject"
instance ToJSVal MouseEventObject where
toJSVal = return . unMouseEventObject
# INLINE toJSVal #
instance FromJSVal MouseEventObject where
fromJSVal = return . fmap MouseEventObject . maybeJSNullOrUndefined
# INLINE fromJSVal #
instance IsEventObject MouseEventObject where
asEventObject (MouseEventObject jsval) = EventObject jsval
foreign import javascript unsafe "$1[\"clientX\"]" clientX ::
MouseEventObject -> Double
foreign import javascript unsafe "$1[\"clientY\"]" clientY ::
MouseEventObject -> Double
foreign import javascript unsafe "$1[\"button\"]" button ::
MouseEventObject -> Int
newtype KeyboardEventObject = KeyboardEventObject { unKeyboardEventObject :: JSVal }
instance ToJSVal KeyboardEventObject where
toJSVal = return . unKeyboardEventObject
# INLINE toJSVal #
instance FromJSVal KeyboardEventObject where
fromJSVal = return . fmap KeyboardEventObject . maybeJSNullOrUndefined
# INLINE fromJSVal #
instance IsEventObject KeyboardEventObject where
asEventObject (KeyboardEventObject jsval) = EventObject jsval
foreign import javascript unsafe "$1[\"charCode\"]" charCode ::
KeyboardEventObject -> Int
foreign import javascript unsafe "$1[\"keyCode\"]" keyCode ::
KeyboardEventObject -> Int
newtype ProgressEventObject = ProgressEventObject { unProgressEventObject :: JSVal }
instance ToJSVal ProgressEventObject where
toJSVal = return . unProgressEventObject
# INLINE toJSVal #
instance FromJSVal ProgressEventObject where
fromJSVal = return . fmap ProgressEventObject . maybeJSNullOrUndefined
# INLINE fromJSVal #
type family EventObjectOf event :: *
type instance EventObjectOf Event = EventObject
type instance EventObjectOf MouseEvent = MouseEventObject
type instance EventObjectOf KeyboardEvent = KeyboardEventObject
type instance EventObjectOf FormEvent = EventObject
type instance EventObjectOf ProgressEvent = ProgressEventObject
type instance EventObjectOf ClipboardEvent = ClipboardEventObject
* DOMRect
newtype DOMClientRect = DomClientRect { unDomClientRect :: JSVal }
foreign import javascript unsafe "$1[\"width\"]" width ::
DOMClientRect -> Double
foreign import javascript unsafe "$1[\"top\"]" rectTop ::
DOMClientRect -> Double
foreign import javascript unsafe "$1[\"left\"]" rectLeft ::
DOMClientRect -> Double
foreign import javascript unsafe "$1[\"right\"]" rectRight ::
DOMClientRect -> Double
foreign import javascript unsafe "$1[\"bottom\"]" rectBottom ::
DOMClientRect -> Double
foreign import javascript unsafe "$1[\"height\"]" height ::
DOMClientRect -> Double
foreign import javascript unsafe "$1[\"getBoundingClientRect\"]()" js_getBoundingClientRect ::
JSElement -> IO DOMClientRect
getBoundingClientRect :: (MonadIO m) => JSElement -> m DOMClientRect
getBoundingClientRect = liftIO . js_getBoundingClientRect
foreign import javascript unsafe "$1[\"addEventListener\"]($2, $3,\n$4)"
js_addEventListener :: EventTarget -> JSString -> Callback (JSVal -> IO ()) -> Bool -> IO ()
addEventListener :: (MonadIO m, IsEventTarget self, IsEvent event, FromJSVal (EventObjectOf event)) =>
self
-> event
-> (EventObjectOf event -> IO ())
-> Bool
-> m ()
addEventListener self event callback useCapture = liftIO $
do cb <- syncCallback1 ThrowWouldBlock callback'
js_addEventListener (toEventTarget self) (eventToJSString event) cb useCapture
where
callback' = \ev ->
do (Just eventObject) <- fromJSVal ev
callback eventObject
addEventListener
: : ( MonadIO m , IsEventTarget self ) = >
self
- > EventType
- > Callback ( IO ( ) )
- > ( )
addEventListener self type ' listener = liftIO
( ( toEventTarget self )
type ''
listener
)
where
type '' = case type ' of
Change - > JS.pack " change "
Click - > JS.pack " click "
Input - > JS.pack " input "
Blur - > JS.pack " blur "
Keydown - > JS.pack " keydown "
Keyup - > JS.pack " keyup "
Keypress - > JS.pack " keypress "
ReadyStateChange - > JS.pack " readystatechange "
EventTxt s - > s
addEventListener
:: (MonadIO m, IsEventTarget self) =>
self
-> EventType
-> Callback (IO ())
-> Bool
-> m ()
addEventListener self type' listener useCapture
= liftIO
(js_addEventListener (toEventTarget self)
type''
listener
useCapture)
where
type'' = case type' of
Change -> JS.pack "change"
Click -> JS.pack "click"
Input -> JS.pack "input"
Blur -> JS.pack "blur"
Keydown -> JS.pack "keydown"
Keyup -> JS.pack "keyup"
Keypress -> JS.pack "keypress"
ReadyStateChange -> JS.pack "readystatechange"
EventTxt s -> s
-}
newtype XMLHttpRequest = XMLHttpRequest { unXMLHttpRequest :: JSVal }
instance Eq (XMLHttpRequest) where
(XMLHttpRequest a) == (XMLHttpRequest b) = js_eq a b
instance IsEventTarget XMLHttpRequest where
toEventTarget = EventTarget . unXMLHttpRequest
instance PToJSVal XMLHttpRequest where
pToJSVal = unXMLHttpRequest
{ - # INLINE pToJSVal #
instance PToJSVal XMLHttpRequest where
pToJSVal = unXMLHttpRequest
instance PFromJSVal XMLHttpRequest where
pFromJSVal = XMLHttpRequest
# INLINE pFromJSVal #
-}
instance ToJSVal XMLHttpRequest where
toJSVal = return . unXMLHttpRequest
# INLINE toJSVal #
instance FromJSVal XMLHttpRequest where
fromJSVal = return . fmap XMLHttpRequest . maybeJSNullOrUndefined
# INLINE fromJSVal #
foreign import javascript unsafe "new window[\"XMLHttpRequest\"]()"
js_newXMLHttpRequest :: IO XMLHttpRequest
| < -US/docs/Web/API/XMLHttpRequest Mozilla XMLHttpRequest documentation >
newXMLHttpRequest :: (MonadIO m) => m XMLHttpRequest
newXMLHttpRequest
= liftIO js_newXMLHttpRequest
foreign import javascript unsafe "$1[\"open\"]($2, $3, $4)"
js_open ::
XMLHttpRequest ->
| < -US/docs/Web/API/XMLHttpRequest.open Mozilla XMLHttpRequest.open documentation >
open ::
(MonadIO m) =>
XMLHttpRequest -> Text -> Text -> Bool -> m ()
open self method url async
= liftIO (js_open self (textToJSString method) (textToJSString url) async)
foreign import javascript unsafe "$1[\"setRequestHeader\"]($2,$3)"
js_setRequestHeader
:: XMLHttpRequest
-> JSString
-> JSString
-> IO ()
setRequestHeader :: (MonadIO m) =>
XMLHttpRequest
-> Text
-> Text
-> m ()
setRequestHeader self header value =
liftIO (js_setRequestHeader self (textToJSString header) (textToJSString value))
foreign import javascript interruptible " h$dom$sendXHR($1 , $ 2 , $ c ) ; " js_send : : ( ) - > IO Int
send : : ( MonadIO m ) = > XMLHttpRequest - > m ( )
send :: (MonadIO m) => XMLHttpRequest -> m ()
-}
foreign import javascript unsafe "$1[\"send\"]()" js_send ::
XMLHttpRequest -> IO ()
| < -US/docs/Web/API/XMLHttpRequest#send ( ) Mozilla XMLHttpRequest.send documentation >
send :: (MonadIO m) => XMLHttpRequest -> m ()
send self =
foreign import javascript unsafe "$1[\"send\"]($2)" js_sendString ::
XMLHttpRequest -> JSString -> IO ()
| < -US/docs/Web/API/XMLHttpRequest#send ( ) Mozilla XMLHttpRequest.send documentation >
sendString :: (MonadIO m) => XMLHttpRequest -> JSString -> m ()
sendString self str =
foreign import javascript unsafe "$1[\"send\"]($2)" js_sendArrayBuffer ::
XMLHttpRequest -> JSVal -> IO ()
sendArrayBuffer :: (MonadIO m) => XMLHttpRequest -> Buffer -> m ()
sendArrayBuffer xhr buf =
liftIO $ do ref <- fmap (pToJSVal . getArrayBuffer) (thaw buf)
js_sendArrayBuffer xhr ref
foreign import javascript unsafe "$1[\"send\"]($2)" js_sendData ::
XMLHttpRequest
-> JSVal
-> IO ()
foreign import javascript unsafe "$1[\"readyState\"]"
js_getReadyState :: XMLHttpRequest -> IO Word
getReadyState :: (MonadIO m) => XMLHttpRequest -> m Word
getReadyState self
= liftIO (js_getReadyState self)
foreign import javascript unsafe "$1[\"responseType\"]"
js_getResponseType ::
| < Https-US/docs/Web/API/XMLHttpRequest.responseType Mozilla XMLHttpRequest.responseType documentation >
getResponseType ::
(MonadIO m) => XMLHttpRequest -> m Text
getResponseType self
= liftIO (textFromJSString <$> js_getResponseType self)
foreign import javascript unsafe "$1[\"responseType\"] = $2"
js_setResponseType ::
setResponseType :: (MonadIO m) =>
XMLHttpRequest
-> Text
-> m ()
setResponseType self typ =
liftIO $ js_setResponseType self (textToJSString typ)
data XMLHttpRequestResponseType = XMLHttpRequestResponseType
| XMLHttpRequestResponseTypeArraybuffer
| XMLHttpRequestResponseTypeBlob
| XMLHttpRequestResponseTypeDocument
| XMLHttpRequestResponseTypeJson
| XMLHttpRequestResponseTypeText
foreign import javascript unsafe "\"\""
foreign import javascript unsafe "\"arraybuffer\""
js_XMLHttpRequestResponseTypeArraybuffer ::
foreign import javascript unsafe "\"blob\""
js_XMLHttpRequestResponseTypeBlob ::
foreign import javascript unsafe "\"document\""
js_XMLHttpRequestResponseTypeDocument ::
foreign import javascript unsafe "\"json\""
js_XMLHttpRequestResponseTypeJson ::
foreign import javascript unsafe "\"text\""
js_XMLHttpRequestResponseTypeText ::
instance PToJSVal XMLHttpRequestResponseType where
pToJSVal XMLHttpRequestResponseType = js_XMLHttpRequestResponseType
pToJSVal XMLHttpRequestResponseTypeArraybuffer
= js_XMLHttpRequestResponseTypeArraybuffer
pToJSVal XMLHttpRequestResponseTypeBlob
= js_XMLHttpRequestResponseTypeBlob
pToJSVal XMLHttpRequestResponseTypeDocument
= js_XMLHttpRequestResponseTypeDocument
pToJSVal XMLHttpRequestResponseTypeJson
= js_XMLHttpRequestResponseTypeJson
pToJSVal
= js_XMLHttpRequestResponseTypeText
instance PToJSVal XMLHttpRequestResponseType where
pToJSVal XMLHttpRequestResponseType = js_XMLHttpRequestResponseType
pToJSVal XMLHttpRequestResponseTypeArraybuffer
= js_XMLHttpRequestResponseTypeArraybuffer
pToJSVal XMLHttpRequestResponseTypeBlob
= js_XMLHttpRequestResponseTypeBlob
pToJSVal XMLHttpRequestResponseTypeDocument
= js_XMLHttpRequestResponseTypeDocument
pToJSVal XMLHttpRequestResponseTypeJson
= js_XMLHttpRequestResponseTypeJson
pToJSVal XMLHttpRequestResponseTypeText
= js_XMLHttpRequestResponseTypeText
-}
instance ToJSVal XMLHttpRequestResponseType where
toJSVal XMLHttpRequestResponseType
= return js_XMLHttpRequestResponseType
toJSVal XMLHttpRequestResponseTypeArraybuffer
= return js_XMLHttpRequestResponseTypeArraybuffer
toJSVal XMLHttpRequestResponseTypeBlob
= return js_XMLHttpRequestResponseTypeBlob
toJSVal XMLHttpRequestResponseTypeDocument
= return js_XMLHttpRequestResponseTypeDocument
toJSVal XMLHttpRequestResponseTypeJson
= return js_XMLHttpRequestResponseTypeJson
toJSVal XMLHttpRequestResponseTypeText
= return js_XMLHttpRequestResponseTypeText
instance FromJSVal XMLHttpRequestResponseType where
fromJSVal x
| x == js_XMLHttpRequestResponseType =
return (Just XMLHttpRequestResponseType)
| x == js_XMLHttpRequestResponseTypeArraybuffer =
return (Just XMLHttpRequestResponseTypeArraybuffer)
| x == js_XMLHttpRequestResponseTypeBlob =
return (Just XMLHttpRequestResponseTypeBlob)
| x == js_XMLHttpRequestResponseTypeDocument =
return (Just XMLHttpRequestResponseTypeDocument)
| x == js_XMLHttpRequestResponseTypeJson =
return (Just XMLHttpRequestResponseTypeJson)
| x == js_XMLHttpRequestResponseTypeText =
return (Just XMLHttpRequestResponseTypeText)
foreign import javascript unsafe "$1[\"response\"]" js_getResponse
:: XMLHttpRequest
-> IO JSVal
| < -US/docs/Web/API/XMLHttpRequest.response Mozilla XMLHttpRequest.response documentation >
getResponse :: (MonadIO m) =>
XMLHttpRequest
-> m JSVal
getResponse self =
liftIO (js_getResponse self)
foreign import javascript unsafe "$1[\"responseText\"]"
js_getResponseText :: XMLHttpRequest -> IO JSString
| < -US/docs/Web/API/XMLHttpRequest.responseText Mozilla XMLHttpRequest.responseText documentation >
getResponseText ::
(MonadIO m) => XMLHttpRequest -> m Text
getResponseText self
= liftIO
(textFromJSString <$> js_getResponseText self)
foreign import javascript unsafe "$1[\"status\"]" js_getStatus ::
XMLHttpRequest -> IO Word
| < -US/docs/Web/API/XMLHttpRequest.status Mozilla XMLHttpRequest.status documentation >
getStatus :: (MonadIO m) => XMLHttpRequest -> m Word
getStatus self = liftIO (js_getStatus self)
foreign import javascript unsafe "$1[\"statusText\"]"
js_getStatusText :: XMLHttpRequest -> IO JSString
| < -US/docs/Web/API/XMLHttpRequest.statusText Mozilla XMLHttpRequest.statusText documentation >
getStatusText ::
(MonadIO m) => XMLHttpRequest -> m Text
getStatusText self
= liftIO
(textFromJSString <$> js_getStatusText self)
foreign import javascript unsafe "$1[\"responseURL\"]"
js_getResponseURL :: XMLHttpRequest -> IO JSString
newtype Selection = Selection { unSelection :: JSVal }
instance ToJSVal Selection where
toJSVal = pure . unSelection
# INLINE toJSVal #
instance FromJSVal Selection where
fromJSVal = pure . fmap Selection . maybeJSNullOrUndefined
# INLINE fromJSVal #
foreign import javascript unsafe "$1[\"getRangeAt\"]($2)"
js_getRangeAt :: Selection -> Int -> IO Range
getRangeAt :: (MonadIO m) => Selection -> Int -> m Range
getRangeAt selection index = liftIO (js_getRangeAt selection index)
foreign import javascript unsafe "$1[\"rangeCount\"]"
js_getRangeCount :: Selection -> IO Int
getRangeCount :: (MonadIO m) => Selection -> m Int
getRangeCount selection = liftIO (js_getRangeCount selection)
foreign import javascript unsafe "$1[\"toString\"]()"
selectionToString :: Selection -> IO JSString
newtype Range = Range { unRange :: JSVal }
instance ToJSVal Range where
toJSVal = pure . unRange
# INLINE toJSVal #
instance FromJSVal Range where
fromJSVal = pure . fmap Range . maybeJSNullOrUndefined
# INLINE fromJSVal #
foreign import javascript unsafe "$1[\"startContainer\"]"
js_getStartContainer :: Range -> IO JSNode
getStartContainer :: (MonadIO m) => Range -> m JSNode
getStartContainer r = liftIO (js_getStartContainer r)
foreign import javascript unsafe "$1[\"startOffset\"]"
js_getStartOffset :: Range -> IO Int
getStartOffset :: (MonadIO m) => Range -> m Int
getStartOffset r = liftIO (js_getStartOffset r)
foreign import javascript unsafe "$1[\"endContainer\"]"
js_getEndContainer :: Range -> IO JSNode
getEndContainer :: (MonadIO m) => Range -> m JSNode
getEndContainer r = liftIO (js_getEndContainer r)
foreign import javascript unsafe "$1[\"endOffset\"]"
js_getEndOffset :: Range -> IO Int
getEndOffset :: (MonadIO m) => Range -> m Int
getEndOffset r = liftIO (js_getEndOffset r)
data Attr action where
Attr :: Text -> Text -> Attr action
Event :: (FromJSVal (EventObjectOf event), IsEvent event) => event -> (EventObjectOf event -> EIO action) -> Attr action
instance Eq (Attr action) where
(Attr k1 v1) == (Attr k2 v2) = (k1 == k2) && (v1 == v2)
_ == _ = False
data HTML action
= forall a. Element { elementName :: Text
, elementAttrs :: [Attr action]
, elementKey :: Maybe Text
, elementDescendants :: Int
, elementChildren :: [HTML action]
}
| CDATA Bool Text
deriving Eq
instance Show (Attr action) where
show (Attr k v) = (Text.unpack k) <> " := " <> (Text.unpack v) <> " "
instance Show (HTML action) where
show (Element tagName attrs _key _count children) =
(Text.unpack tagName) <> " [" <> concat (map show attrs) <> "]\n" <> concat (map showChild children)
where
showChild c = " " <> show c <> "\n"
show (CDATA b txt) = Text.unpack txt
descendants :: [HTML action] -> Int
descendants elems = sum [ d | Element _ _ _ d _ <- elems] + (length elems)
renderHTML :: forall action m. (MonadIO m) => (action -> IO ()) -> JSDocument -> HTML action -> m (Maybe JSNode)
renderHTML _ doc (CDATA _ t) = fmap (fmap toJSNode) $ createJSTextNode doc t
do me <- createJSElement doc tag
case me of
Nothing -> return Nothing
(Just e) ->
do mapM_ (\c -> appendChild e =<< renderHTML handle doc c) children
mapM_ (doAttr e) attrs
let events ' = [ ev | ev@(Event ev f ) < - attrs ]
' = [ ( k , v ) | Attr k v < - attrs ]
liftIO $ mapM _ ( \(k , v ) - > setAttribute e k v ) attrs '
liftIO $ mapM _ ( handleEvent e ) events '
let events' = [ ev | ev@(Event ev f) <- attrs]
attrs' = [ (k,v) | Attr k v <- attrs]
liftIO $ mapM_ (\(k, v) -> setAttribute e k v) attrs'
liftIO $ mapM_ (handleEvent e) events'
-}
return (Just $ toJSNode e)
where
doAttr elem (Attr k v) = setAttribute elem k v
doAttr elem (Event eventType toAction) =
addEventListener elem eventType (\e -> handle =<< eioToIO (toAction e)) False
newtype DataTransfer = DataTransfer { unDataTransfer :: JSVal }
instance Show DataTransfer where
show _ = "DataTransfer"
instance ToJSVal DataTransfer where
toJSVal = pure . unDataTransfer
# INLINE toJSVal #
instance FromJSVal DataTransfer where
fromJSVal = pure . fmap DataTransfer . maybeJSNullOrUndefined
# INLINE fromJSVal #
foreign import javascript unsafe "$1[\"getData\"]($2)" js_getDataTransferData ::
DataTransfer -> JSString -> IO JSString
DataTransfer
-> EIO JSString
getDataTransferData dt format = EIO (js_getDataTransferData dt format)
foreign import javascript unsafe "$1[\"setData\"]($2, $3)" js_setDataTransferData ::
DataTransfer -> JSString -> JSString -> IO ()
setDataTransferData :: DataTransfer
-> EIO ()
setDataTransferData dataTransfer format data_ = EIO (js_setDataTransferData dataTransfer format data_)
data ClipboardEvent
= Copy
| Cut
| Paste
deriving (Eq, Ord, Show, Read)
instance IsEvent ClipboardEvent where
eventToJSString Copy = JS.pack "copy"
eventToJSString Cut = JS.pack "cut"
eventToJSString Paste = JS.pack "paste"
*
newtype ClipboardEventObject = ClipboardEventObject { unClipboardEventObject :: JSVal }
instance Show ClipboardEventObject where
show _ = "ClipboardEventObject"
instance ToJSVal ClipboardEventObject where
toJSVal = pure . unClipboardEventObject
# INLINE toJSVal #
instance FromJSVal ClipboardEventObject where
fromJSVal = pure . fmap ClipboardEventObject . maybeJSNullOrUndefined
# INLINE fromJSVal #
instance IsEventObject ClipboardEventObject where
asEventObject (ClipboardEventObject jsval) = EventObject jsval
foreign import javascript unsafe "$1[\"clipboardData\"]" clipboardData ::
ClipboardEventObject -> EIO DataTransfer
newtype JSContext2D = JSContext2D { unJSContext :: JSVal }
instance ToJSVal JSContext2D where
toJSVal = return . unJSContext
# INLINE toJSVal #
instance FromJSVal JSContext2D where
fromJSVal = return . fmap JSContext2D . maybeJSNullOrUndefined
# INLINE fromJSVal #
foreign import javascript unsafe "$1[\"getContext\"](\"2d\")"
js_getContext2d ::
JSElement -> IO JSVal
getContext2D :: (MonadIO m) => JSElement -> m (Maybe JSContext2D)
getContext2D elem = liftIO $ fromJSVal =<< js_getContext2d elem
foreign import javascript unsafe "$1[\"fillRect\"]($2, $3, $4, $5)"
js_fillRect ::
JSContext2D -> Double -> Double -> Double -> Double -> IO ()
fillRect :: JSContext2D -> Double -> Double -> Double -> Double -> IO ()
fillRect = js_fillRect
foreign import javascript unsafe "$1[\"clearRect\"]($2, $3, $4, $5)"
js_clearRect ::
JSContext2D -> Double -> Double -> Double -> Double -> IO ()
clearRect :: JSContext2D -> Double -> Double -> Double -> Double -> IO ()
clearRect = js_clearRect
renderColor :: Color -> JSString
renderColor (ColorName c) = c
renderStyle :: Style -> JSString
renderStyle (StyleColor color) = renderColor color
foreign import javascript unsafe "$1[\"fillStyle\"] = $2"
js_fillStyle ::
JSContext2D -> JSString -> IO ()
setFillStyle :: JSContext2D -> Style -> IO ()
setFillStyle ctx style = js_fillStyle ctx (renderStyle style)
foreign import javascript unsafe "$1[\"strokeStyle\"] = $2"
js_strokeStyle ::
JSContext2D -> JSString -> IO ()
setStrokeStyle :: JSContext2D -> Style -> IO ()
setStrokeStyle ctx style = js_strokeStyle ctx (renderStyle style)
foreign import javascript unsafe "$1[\"save\"]()"
js_save ::
JSContext2D -> IO ()
save :: (MonadIO m) => JSContext2D -> m ()
save = liftIO . js_save
foreign import javascript unsafe "$1[\"restore\"]()"
js_restore ::
JSContext2D -> IO ()
restore :: (MonadIO m) => JSContext2D -> m ()
restore = liftIO . js_restore
foreign import javascript unsafe "$1[\"moveTo\"]($2, $3)"
js_moveTo ::
JSContext2D -> Double -> Double -> IO ()
moveTo :: (MonadIO m) => JSContext2D -> Double -> Double -> m ()
moveTo ctx x y = liftIO $ js_moveTo ctx x y
foreign import javascript unsafe "$1[\"lineTo\"]($2, $3)"
js_lineTo ::
JSContext2D -> Double -> Double -> IO ()
lineTo :: (MonadIO m) => JSContext2D -> Double -> Double -> m ()
lineTo ctx x y = liftIO $ js_lineTo ctx x y
foreign import javascript unsafe "$1[\"arc\"]($2, $3, $4, $5, $6, $7)"
js_arc ::
JSContext2D -> Double -> Double -> Double -> Double -> Double -> Bool -> IO ()
arc :: (MonadIO m) => JSContext2D -> Double -> Double -> Double -> Double -> Double -> Bool -> m ()
arc ctx x y radius startAngle endAngle counterClockwise = liftIO $ js_arc ctx x y radius startAngle endAngle counterClockwise
foreign import javascript unsafe "$1[\"beginPath\"]()"
js_beginPath ::
JSContext2D -> IO ()
beginPath :: (MonadIO m) => JSContext2D -> m ()
beginPath = liftIO . js_beginPath
foreign import javascript unsafe "$1[\"stroke\"]()"
js_stroke ::
JSContext2D -> IO ()
stroke :: (MonadIO m) => JSContext2D -> m ()
stroke = liftIO . js_stroke
foreign import javascript unsafe "$1[\"fill\"]()"
js_fill ::
JSContext2D -> IO ()
fill :: (MonadIO m) => JSContext2D -> m ()
fill = liftIO . js_fill
foreign import javascript unsafe "$1[\"lineWidth\"] = $2"
js_setLineWidth ::
JSContext2D -> Double -> IO ()
setLineWidth :: (MonadIO m) => JSContext2D -> Double -> m ()
setLineWidth ctx w = liftIO $ js_setLineWidth ctx w
foreign import javascript unsafe "$1[\"font\"] = $2"
js_font ::
JSContext2D -> JSString -> IO ()
setFont :: (MonadIO m) => JSContext2D -> JSString -> m ()
setFont ctx font = liftIO $ js_font ctx font
foreign import javascript unsafe "$1[\"textAlign\"] = $2"
js_textAlign ::
JSContext2D -> JSString -> IO ()
data TextAlign
= AlignStart
| AlignEnd
| AlignLeft
| AlignCenter
| AlignRight
deriving (Eq, Ord, Show, Read)
textAlignToJSString :: TextAlign -> JSString
textAlignToJSString AlignStart = JS.pack "start"
textAlignToJSString AlignEnd = JS.pack "end"
textAlignToJSString AlignLeft = JS.pack "left"
textAlignToJSString AlignCenter = JS.pack "center"
textAlignToJSString AlignRight = JS.pack "right"
setTextAlign :: (MonadIO m) => JSContext2D -> TextAlign -> m ()
setTextAlign ctx align = liftIO $ js_textAlign ctx (textAlignToJSString align)
foreign import javascript unsafe "$1[\"fillText\"]($2, $3, $4)"
js_fillText :: JSContext2D -> JSString -> Double -> Double -> IO ()
foreign import javascript unsafe "$1[\"fillText\"]($2, $3, $4, $5)"
js_fillTextMaxWidth ::
JSContext2D -> JSString -> Double -> Double -> Double -> IO ()
fillText :: (MonadIO m) =>
JSContext2D
-> JSString
-> Double
-> Double
-> Maybe Double
-> m ()
fillText ctx txt x y Nothing = liftIO $ js_fillText ctx txt x y
fillText ctx txt x y (Just maxWidth) = liftIO $ js_fillTextMaxWidth ctx txt x y maxWidth
foreign import javascript unsafe "$1[\"scale\"]($2, $3)"
js_scale :: JSContext2D -> Double -> Double -> IO ()
foreign import javascript unsafe "alert($1)"
js_alert :: JSString -> IO ()
scale :: (MonadIO m) => JSContext2D -> Double -> Double -> m ()
scale ctx x y = liftIO $ js_scale ctx x y
foreign import javascript unsafe "$1[\"rotate\"]($2)"
js_rotate :: JSContext2D -> Double -> IO ()
rotate :: (MonadIO m) =>
-> m ()
rotate ctx r = liftIO $ js_rotate ctx r
foreign import javascript unsafe "$1[\"translate\"]($2, $3)"
js_translate :: JSContext2D -> Double -> Double -> IO ()
translate :: (MonadIO m) =>
-> m ()
translate ctx x y = liftIO $ js_translate ctx x y
data Gradient = Gradient
deriving (Eq, Ord, Show, Read)
data Pattern = Pattern
deriving (Eq, Ord, Show, Read)
type Percentage = Double
type Alpha = Double
data Color
= ColorName JSString
| RGBA Percentage Percentage Percentage Alpha
deriving (Eq, Ord, Show, Read)
data Style
= StyleColor Color
| StyleGradient Gradient
| StylePattern Pattern
deriving (Eq, Ord, Show, Read)
data Rect
= Rect { _rectX :: Double
, _rectY :: Double
, _rectWidth :: Double
, _rectHeight :: Double
}
deriving (Eq, Ord, Show, Read)
data Path2D
= MoveTo Double Double
| LineTo Double Double
| PathRect Rect
| Arc Double Double Double Double Double Bool
deriving (Eq, Ord, Show, Read)
data Draw
= FillRect Rect
| ClearRect Rect
| Stroke [Path2D]
| Fill [Path2D]
| FillText JSString Double Double (Maybe Double)
deriving (Eq, Ord, Show, Read)
data Context2D
= FillStyle Style
| StrokeStyle Style
| LineWidth Double
| Font JSString
| TextAlign TextAlign
| Scale Double Double
| Translate Double Double
| Rotate Double
deriving (Eq, Read, Show)
data Canvas = Canvas
{ _canvasId :: Text
, _canvas :: Canvas2D
}
deriving (Eq, Show, Read)
data Canvas2D
= WithContext2D [Context2D] [ Canvas2D ]
| Draw Draw
deriving (Eq, Show, Read)
mkPath :: (MonadIO m) => JSContext2D -> [Path2D] -> m ()
mkPath ctx segments =
do beginPath ctx
mapM_ (mkSegment ctx) segments
where
mkSegment ctx segment =
case segment of
(MoveTo x y) -> moveTo ctx x y
(LineTo x y) -> lineTo ctx x y
(Arc x y radius startAngle endAngle counterClockwise) -> arc ctx x y radius startAngle endAngle counterClockwise
( ( Rect x y w h ) ) - > rect x y w h
drawCanvas :: Canvas -> IO ()
drawCanvas (Canvas cid content) =
do (Just document) <- currentDocument
mCanvasElem <- getElementById document (textToJSString cid)
case mCanvasElem of
Nothing -> pure ()
(Just canvasElem) ->
/
do rescaleCanvas <- do ms <- getData canvasElem (JS.pack "rescale")
case ms of
Nothing -> pure True
(Just s) ->
case (JS.unpack s) of
"true" -> pure True
_ -> pure False
ratio <- fmap (fromMaybe 1) (devicePixelRatio =<< window)
(w, h) <-
if rescaleCanvas
then do (Just oldWidth) <- fmap (read . JS.unpack) <$> getAttribute canvasElem (JS.pack "width")
(Just oldHeight) <- fmap (read . JS.unpack) <$> getAttribute canvasElem (JS.pack "height")
js_setAttribute canvasElem (JS.pack "width") (JS.pack $ show $ oldWidth * ratio)
js_setAttribute canvasElem (JS.pack "height") (JS.pack $ show $ oldHeight * ratio)
setStyle canvasElem (JS.pack "width") (JS.pack $ (show oldWidth) ++ "px")
setStyle canvasElem (JS.pack "height") (JS.pack $ (show oldHeight) ++ "px")
setData canvasElem (JS.pack "rescale") (JS.pack "false")
pure (oldWidth * ratio, oldHeight * ratio)
else do (Just width) <- fmap (read . JS.unpack) <$> getAttribute canvasElem (JS.pack "width")
(Just height) <- fmap (read . JS.unpack) <$> getAttribute canvasElem (JS.pack "height")
pure (width, height)
mctx <- getContext2D canvasElem
case mctx of
Nothing -> pure ()
(Just ctx) -> do
when (rescaleCanvas) (scale ctx ratio ratio)
clearRect ctx 0 0 w h
drawCanvas' ctx content
where
drawCanvas' ctx (Draw (FillRect (Rect x y w h))) =
fillRect ctx x y w h
drawCanvas' ctx (Draw (ClearRect (Rect x y w h))) =
clearRect ctx x y w h
drawCanvas' ctx (Draw (Stroke path2D)) =
do mkPath ctx path2D
stroke ctx
drawCanvas' ctx (Draw (Fill path2D)) =
do mkPath ctx path2D
fill ctx
drawCanvas' ctx (Draw (FillText text x y maxWidth)) =
do fillText ctx text x y maxWidth
drawCanvas' ctx (WithContext2D ctx2d content) =
do save ctx
mapM_ (setContext2D ctx) ctx2d
mapM_ (drawCanvas' ctx) content
restore ctx
where
setContext2D ctx op =
case op of
(FillStyle style) -> setFillStyle ctx style
(StrokeStyle style) -> setStrokeStyle ctx style
(LineWidth w) -> setLineWidth ctx w
(Font font) -> setFont ctx font
(TextAlign a) -> setTextAlign ctx a
(Scale x y) -> scale ctx x y
(Translate x y) -> translate ctx x y
(Rotate r ) -> rotate ctx r
|
15ca6331b2042c5e072dc520707fe21892d0756e1e844d3a5a8b7c0221b41303 | mjambon/moving-percentile | mv_var.mli |
State that tracks moving average and moving variance based on that
moving average , for a given signal .
State that tracks moving average and moving variance based on that
moving average, for a given signal.
*)
type state = private {
avg: Mv_avg.state;
var: Mv_avg.state;
mutable stdev: float;
(* square root of the estimated variance *)
mutable normalized: float;
( signal - mean ) / stdev
}
val init :
?alpha_avg:float ->
?alpha_var:float ->
unit -> state
val update : state -> float -> unit
(* Add an observation *)
val get_average : state -> float
Return the exponential moving average , which is maintained
in order to compute the exponential moving variance .
We need 1 observation before returning a regular float ( not a nan )
in order to compute the exponential moving variance.
We need 1 observation before returning a regular float (not a nan) *)
val get_variance : state -> float
Return the exponential moving variance .
We need 2 observations before returning a regular float ( not a nan )
We need 2 observations before returning a regular float (not a nan) *)
val get_stdev : state -> float
(* Square root of the estimated variance *)
val get_normalized : state -> float
Normalized signal , defined as ( x - mean ) / stdev
val get_count : state -> int
(* Return the number of observations so far, i.e. the number of times
`update` was called successfully. *)
| null | https://raw.githubusercontent.com/mjambon/moving-percentile/d39e68069acf0b188542459896d237a142ced4b6/mv_var.mli | ocaml | square root of the estimated variance
Add an observation
Square root of the estimated variance
Return the number of observations so far, i.e. the number of times
`update` was called successfully. |
State that tracks moving average and moving variance based on that
moving average , for a given signal .
State that tracks moving average and moving variance based on that
moving average, for a given signal.
*)
type state = private {
avg: Mv_avg.state;
var: Mv_avg.state;
mutable stdev: float;
mutable normalized: float;
( signal - mean ) / stdev
}
val init :
?alpha_avg:float ->
?alpha_var:float ->
unit -> state
val update : state -> float -> unit
val get_average : state -> float
Return the exponential moving average , which is maintained
in order to compute the exponential moving variance .
We need 1 observation before returning a regular float ( not a nan )
in order to compute the exponential moving variance.
We need 1 observation before returning a regular float (not a nan) *)
val get_variance : state -> float
Return the exponential moving variance .
We need 2 observations before returning a regular float ( not a nan )
We need 2 observations before returning a regular float (not a nan) *)
val get_stdev : state -> float
val get_normalized : state -> float
Normalized signal , defined as ( x - mean ) / stdev
val get_count : state -> int
|
77bc208981918f7940ffcac1722af5708c8a2c663d391179dd76b0e0b491a989 | MyDataFlow/ttalk-server | exo_montest.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2014 Basho Technologies , Inc. All Rights Reserved .
%%
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 /.
%%
%% -------------------------------------------------------------------
%%
%% @doc Demo module for `exometer_folsom_monitor' behaviours.
%%
%% This module simply
%% @end
-module(exo_montest).
-behaviour(exometer_folsom_monitor).
-behaviour(exometer_entry).
-export([copy_folsom/3]).
-export([behaviour/0,
delete/3,
get_datapoints/3,
get_value/4,
new/3,
reset/3,
sample/3,
setopts/3,
update/4]).
behaviour() ->
entry.
copy_folsom(Name, Type, Opts) when is_tuple(Name) ->
{tuple_to_list(Name), ad_hoc, [{folsom_name, Name},
{module, ?MODULE},
{type, Type}
| options(Type, Opts)]};
copy_folsom(_, _, _) ->
false.
new(N, _, Opts) ->
{ok, {proplists:get_value(type, Opts, unknown),
proplists:get_value(folsom_name, Opts, N)}}.
update(_, Value, counter, {_, Name}) ->
folsom_metrics:notify_existing_metric(Name, {inc,Value}, counter);
update(_, Value, Type, {_, Name}) ->
folsom_metrics:notify_existing_metric(Name, Value, Type).
reset(_, _, _) ->
{error, unsupported}.
get_value(_, Type, {_, Name}, DPs) ->
exometer_folsom:get_value(Name, Type, [], DPs).
sample(_, _, _) ->
{error, unsupported}.
setopts(_, _, _) ->
ok.
delete(_, _, _) ->
{error, unsupported}.
get_datapoints(Name, Type, _) ->
exometer_folsom:get_datapoints(Name, Type, []).
options(history, [Size]) ->
[{size, Size}];
options(histogram, [SampleType, SampleSize, Alpha]) ->
[{sample_type, SampleType},
{sample_size, SampleSize},
{alpha, Alpha}];
options(duration , [SampleType, SampleSize, Alpha]) ->
[{sample_type, SampleType},
{sample_size, SampleSize},
{alpha, Alpha}];
options(meter_reader, []) -> [];
options(spiral , []) -> [];
options(meter , []) -> [];
options(gauge , []) -> [];
options(counter , []) -> [].
| null | https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/exometer/src/exo_montest.erl | erlang | -------------------------------------------------------------------
-------------------------------------------------------------------
@doc Demo module for `exometer_folsom_monitor' behaviours.
This module simply
@end | Copyright ( c ) 2014 Basho Technologies , Inc. All Rights Reserved .
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
-module(exo_montest).
-behaviour(exometer_folsom_monitor).
-behaviour(exometer_entry).
-export([copy_folsom/3]).
-export([behaviour/0,
delete/3,
get_datapoints/3,
get_value/4,
new/3,
reset/3,
sample/3,
setopts/3,
update/4]).
behaviour() ->
entry.
copy_folsom(Name, Type, Opts) when is_tuple(Name) ->
{tuple_to_list(Name), ad_hoc, [{folsom_name, Name},
{module, ?MODULE},
{type, Type}
| options(Type, Opts)]};
copy_folsom(_, _, _) ->
false.
new(N, _, Opts) ->
{ok, {proplists:get_value(type, Opts, unknown),
proplists:get_value(folsom_name, Opts, N)}}.
update(_, Value, counter, {_, Name}) ->
folsom_metrics:notify_existing_metric(Name, {inc,Value}, counter);
update(_, Value, Type, {_, Name}) ->
folsom_metrics:notify_existing_metric(Name, Value, Type).
reset(_, _, _) ->
{error, unsupported}.
get_value(_, Type, {_, Name}, DPs) ->
exometer_folsom:get_value(Name, Type, [], DPs).
sample(_, _, _) ->
{error, unsupported}.
setopts(_, _, _) ->
ok.
delete(_, _, _) ->
{error, unsupported}.
get_datapoints(Name, Type, _) ->
exometer_folsom:get_datapoints(Name, Type, []).
options(history, [Size]) ->
[{size, Size}];
options(histogram, [SampleType, SampleSize, Alpha]) ->
[{sample_type, SampleType},
{sample_size, SampleSize},
{alpha, Alpha}];
options(duration , [SampleType, SampleSize, Alpha]) ->
[{sample_type, SampleType},
{sample_size, SampleSize},
{alpha, Alpha}];
options(meter_reader, []) -> [];
options(spiral , []) -> [];
options(meter , []) -> [];
options(gauge , []) -> [];
options(counter , []) -> [].
|
dff26f8a57e1eb2aa7541b6ec04462185b4950f013a5b2749fa9d7c2953c1ef8 | geoffder/olm-ml | inboundGroupSession.mli | open Core
type t = { buf : char Ctypes.ptr
; igs : C.Types.InboundGroupSession.t Ctypes_static.ptr
}
(** [clear igs]
Clear memory backing the given [igs] pointer. *)
val clear : C.Types.InboundGroupSession.t Ctypes_static.ptr -> (int, [> `OlmError ]) result
* [ check_error t ret ]
Check whether return code [ ret ] is equal to ` olm_error ( ) ` ( -1 ) , returning the
return value as an int if not , and the ` last_error ` from the inbound group
session [ t ] if so .
Check whether return code [ret] is equal to `olm_error()` ( -1 ), returning the
return value as an int if not, and the `last_error` from the inbound group
session [t] if so. *)
val check_error : t -> Unsigned.size_t -> (int, [> OlmError.t ]) result
* [ alloc ( ) ]
Allocate an [ C.Types . InboundGroupSession.t ] and return the pointers in a [ t ] .
Allocate an [C.Types.InboundGroupSession.t] and return the pointers in a [t]. *)
val alloc : unit -> t
(** [create outbound_session_key]
Start a new inbound group session, using an exported [outbound_session_key],
(obtained with [OutboundGroupSession.session_key]). *)
val create : string -> (t, [> OlmError.t ]) result
* [ pickle ? pass t ]
Stores an inbound group session object [ t ] as a base64 string . Encrypting
it using the optionally supplied passphrase [ pass ] . Returns a base64
encoded string of the pickled inbound group session on success .
Stores an inbound group session object [t] as a base64 string. Encrypting
it using the optionally supplied passphrase [pass]. Returns a base64
encoded string of the pickled inbound group session on success. *)
val pickle : ?pass:string -> t -> (string, [> OlmError.t ]) result
* [ from_pickle ? pass pickle ]
Loads an inbound group session from a pickled base64 - encoded string [ pickle ]
and returns a [ t ] , decrypted with the optionally supplied passphrase
[ pass ] . If the passphrase does n't match the one used to encrypt the account
then the error will be [ ` BadAccountKey ] . If the base64 could n't be decoded
then the error will be [ ` InvalidBase64 ] .
Loads an inbound group session from a pickled base64-encoded string [pickle]
and returns a [t], decrypted with the optionally supplied passphrase
[pass]. If the passphrase doesn't match the one used to encrypt the account
then the error will be [`BadAccountKey]. If the base64 couldn't be decoded
then the error will be [`InvalidBase64]. *)
val from_pickle : ?pass:string -> string -> (t, [> OlmError.t | `ValueError of string ]) result
(** [decrypt t ciphertext]
Returns a tuple of the plain-text decrypted from [ciphertext] by [t] and the
message index of the decrypted message or an error on failure. Invalid unicode
characters are replaced with [Uutf.u_rep] unless [ignore_unicode_errors] is
set to true. Possible olm errors include:
* [`InvalidBase64] if the message is not valid base64
* [`BadMessageVersion] if the message was encrypted with an unsupported
version of the protocol
* [`BadMessageFormat] if the message headers could not be decoded
* [`BadMessageMac] if the message could not be verified
* [`UnknownMessageIndex] if we do not have a session key
corresponding to the message's index (i.e., it was sent before
the session key was shared with us) *)
val decrypt
: ?ignore_unicode_errors:bool
-> t
-> string
-> (string * int, [> OlmError.t | `ValueError of string | `UnicodeError ]) result
(** [id t]
A base64 encoded identifier for the session [t]. *)
val id : t -> (string, [> OlmError.t ]) result
* [ first_known_index t ]
The first message index we know how to decrypt for [ t ] .
The first message index we know how to decrypt for [t]. *)
val first_known_index : t -> int
(** [export_session t message_index]
Export the base64-encoded ratchet key for the session [t], at the given
[message_index], in a format which can be used by [import_session]. Error
will be [`UnknownMessageIndex] if we do not have a session key for
[message_index] (i.e., it was sent before the session key was shared with
us) *)
val export_session : t -> int -> (string, [> OlmError.t ]) result
(** [import_session exported_key]
Creates an inbound group session with an [exported_key] from an (previously)
existing inbound group session. If the [exported_key] is not valid, the
error will be [`BadSessionKey]. *)
val import_session : string -> (t, [> OlmError.t ]) result
(** [is_verified t]
Check if the session has been verified as a valid session. (A session is
verified either because the original session share was signed, or because we
have subsequently successfully decrypted a message.) *)
val is_verified : t -> bool
| null | https://raw.githubusercontent.com/geoffder/olm-ml/6ab791c5f4cacb54cf8939d78bd2a6820ec136b3/olm/lib/inboundGroupSession.mli | ocaml | * [clear igs]
Clear memory backing the given [igs] pointer.
* [create outbound_session_key]
Start a new inbound group session, using an exported [outbound_session_key],
(obtained with [OutboundGroupSession.session_key]).
* [decrypt t ciphertext]
Returns a tuple of the plain-text decrypted from [ciphertext] by [t] and the
message index of the decrypted message or an error on failure. Invalid unicode
characters are replaced with [Uutf.u_rep] unless [ignore_unicode_errors] is
set to true. Possible olm errors include:
* [`InvalidBase64] if the message is not valid base64
* [`BadMessageVersion] if the message was encrypted with an unsupported
version of the protocol
* [`BadMessageFormat] if the message headers could not be decoded
* [`BadMessageMac] if the message could not be verified
* [`UnknownMessageIndex] if we do not have a session key
corresponding to the message's index (i.e., it was sent before
the session key was shared with us)
* [id t]
A base64 encoded identifier for the session [t].
* [export_session t message_index]
Export the base64-encoded ratchet key for the session [t], at the given
[message_index], in a format which can be used by [import_session]. Error
will be [`UnknownMessageIndex] if we do not have a session key for
[message_index] (i.e., it was sent before the session key was shared with
us)
* [import_session exported_key]
Creates an inbound group session with an [exported_key] from an (previously)
existing inbound group session. If the [exported_key] is not valid, the
error will be [`BadSessionKey].
* [is_verified t]
Check if the session has been verified as a valid session. (A session is
verified either because the original session share was signed, or because we
have subsequently successfully decrypted a message.) | open Core
type t = { buf : char Ctypes.ptr
; igs : C.Types.InboundGroupSession.t Ctypes_static.ptr
}
val clear : C.Types.InboundGroupSession.t Ctypes_static.ptr -> (int, [> `OlmError ]) result
* [ check_error t ret ]
Check whether return code [ ret ] is equal to ` olm_error ( ) ` ( -1 ) , returning the
return value as an int if not , and the ` last_error ` from the inbound group
session [ t ] if so .
Check whether return code [ret] is equal to `olm_error()` ( -1 ), returning the
return value as an int if not, and the `last_error` from the inbound group
session [t] if so. *)
val check_error : t -> Unsigned.size_t -> (int, [> OlmError.t ]) result
* [ alloc ( ) ]
Allocate an [ C.Types . InboundGroupSession.t ] and return the pointers in a [ t ] .
Allocate an [C.Types.InboundGroupSession.t] and return the pointers in a [t]. *)
val alloc : unit -> t
val create : string -> (t, [> OlmError.t ]) result
* [ pickle ? pass t ]
Stores an inbound group session object [ t ] as a base64 string . Encrypting
it using the optionally supplied passphrase [ pass ] . Returns a base64
encoded string of the pickled inbound group session on success .
Stores an inbound group session object [t] as a base64 string. Encrypting
it using the optionally supplied passphrase [pass]. Returns a base64
encoded string of the pickled inbound group session on success. *)
val pickle : ?pass:string -> t -> (string, [> OlmError.t ]) result
* [ from_pickle ? pass pickle ]
Loads an inbound group session from a pickled base64 - encoded string [ pickle ]
and returns a [ t ] , decrypted with the optionally supplied passphrase
[ pass ] . If the passphrase does n't match the one used to encrypt the account
then the error will be [ ` BadAccountKey ] . If the base64 could n't be decoded
then the error will be [ ` InvalidBase64 ] .
Loads an inbound group session from a pickled base64-encoded string [pickle]
and returns a [t], decrypted with the optionally supplied passphrase
[pass]. If the passphrase doesn't match the one used to encrypt the account
then the error will be [`BadAccountKey]. If the base64 couldn't be decoded
then the error will be [`InvalidBase64]. *)
val from_pickle : ?pass:string -> string -> (t, [> OlmError.t | `ValueError of string ]) result
val decrypt
: ?ignore_unicode_errors:bool
-> t
-> string
-> (string * int, [> OlmError.t | `ValueError of string | `UnicodeError ]) result
val id : t -> (string, [> OlmError.t ]) result
* [ first_known_index t ]
The first message index we know how to decrypt for [ t ] .
The first message index we know how to decrypt for [t]. *)
val first_known_index : t -> int
val export_session : t -> int -> (string, [> OlmError.t ]) result
val import_session : string -> (t, [> OlmError.t ]) result
val is_verified : t -> bool
|
54e0130d63c6420748ec458787abe003a832f69ba06e35441e4a5ec3ba932dc1 | MyDataFlow/ttalk-server | ranch_tcp.erl | Copyright ( c ) 2011 - 2014 , < >
%%
%% Permission to use, copy, modify, and/or 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.
-module(ranch_tcp).
-behaviour(ranch_transport).
-export([name/0]).
-export([messages/0]).
-export([listen/1]).
-export([accept/2]).
-export([accept_ack/2]).
-export([connect/3]).
-export([connect/4]).
-export([recv/3]).
-export([send/2]).
-export([sendfile/2]).
-export([sendfile/4]).
-export([sendfile/5]).
-export([setopts/2]).
-export([controlling_process/2]).
-export([peername/1]).
-export([sockname/1]).
-export([shutdown/2]).
-export([close/1]).
-type opts() :: [{backlog, non_neg_integer()}
| {ip, inet:ip_address()}
| {linger, {boolean(), non_neg_integer()}}
| {nodelay, boolean()}
| {port, inet:port_number()}
| {raw, non_neg_integer(), non_neg_integer(),
non_neg_integer() | binary()}
| {send_timeout, timeout()}
| {send_timeout_close, boolean()}].
-export_type([opts/0]).
name() -> tcp.
messages() -> {tcp, tcp_closed, tcp_error}.
-spec listen(opts()) -> {ok, inet:socket()} | {error, atom()}.
listen(Opts) ->
Opts2 = ranch:set_option_default(Opts, backlog, 1024),
Opts3 = ranch:set_option_default(Opts2, send_timeout, 30000),
Opts4 = ranch:set_option_default(Opts3, send_timeout_close, true),
We set the port to 0 because it is given in the Opts directly .
%% The port in the options takes precedence over the one in the
first argument .
gen_tcp:listen(0, ranch:filter_options(Opts4,
[backlog, ip, linger, nodelay, port, raw,
send_timeout, send_timeout_close],
[binary, {active, false}, {packet, raw},
{reuseaddr, true}, {nodelay, true}])).
-spec accept(inet:socket(), timeout())
-> {ok, inet:socket()} | {error, closed | timeout | atom()}.
accept(LSocket, Timeout) ->
gen_tcp:accept(LSocket, Timeout).
-spec accept_ack(inet:socket(), timeout()) -> ok.
accept_ack(_, _) ->
ok.
@todo Probably filter Opts ?
-spec connect(inet:ip_address() | inet:hostname(),
inet:port_number(), any())
-> {ok, inet:socket()} | {error, atom()}.
connect(Host, Port, Opts) when is_integer(Port) ->
gen_tcp:connect(Host, Port,
Opts ++ [binary, {active, false}, {packet, raw}]).
@todo Probably filter Opts ?
-spec connect(inet:ip_address() | inet:hostname(),
inet:port_number(), any(), timeout())
-> {ok, inet:socket()} | {error, atom()}.
connect(Host, Port, Opts, Timeout) when is_integer(Port) ->
gen_tcp:connect(Host, Port,
Opts ++ [binary, {active, false}, {packet, raw}],
Timeout).
-spec recv(inet:socket(), non_neg_integer(), timeout())
-> {ok, any()} | {error, closed | atom()}.
recv(Socket, Length, Timeout) ->
gen_tcp:recv(Socket, Length, Timeout).
-spec send(inet:socket(), iodata()) -> ok | {error, atom()}.
send(Socket, Packet) ->
gen_tcp:send(Socket, Packet).
-spec sendfile(inet:socket(), file:name_all() | file:fd())
-> {ok, non_neg_integer()} | {error, atom()}.
sendfile(Socket, Filename) ->
sendfile(Socket, Filename, 0, 0, []).
-spec sendfile(inet:socket(), file:name_all() | file:fd(), non_neg_integer(),
non_neg_integer())
-> {ok, non_neg_integer()} | {error, atom()}.
sendfile(Socket, File, Offset, Bytes) ->
sendfile(Socket, File, Offset, Bytes, []).
-spec sendfile(inet:socket(), file:name_all() | file:fd(), non_neg_integer(),
non_neg_integer(), [{chunk_size, non_neg_integer()}])
-> {ok, non_neg_integer()} | {error, atom()}.
sendfile(Socket, Filename, Offset, Bytes, Opts)
when is_list(Filename) orelse is_atom(Filename)
orelse is_binary(Filename) ->
case file:open(Filename, [read, raw, binary]) of
{ok, RawFile} ->
try sendfile(Socket, RawFile, Offset, Bytes, Opts) of
Result -> Result
after
ok = file:close(RawFile)
end;
{error, _} = Error ->
Error
end;
sendfile(Socket, RawFile, Offset, Bytes, Opts) ->
Opts2 = case Opts of
[] -> [{chunk_size, 16#1FFF}];
_ -> Opts
end,
try file:sendfile(RawFile, Socket, Offset, Bytes, Opts2) of
Result -> Result
catch
error:{badmatch, {error, enotconn}} ->
file : sendfile/5 might fail by throwing a
{ badmatch , { error , enotconn } } . This is because its
%% implementation fails with a badmatch in
%% prim_file:sendfile/10 if the socket is not connected.
{error, closed}
end.
@todo Probably filter Opts ?
-spec setopts(inet:socket(), list()) -> ok | {error, atom()}.
setopts(Socket, Opts) ->
inet:setopts(Socket, Opts).
-spec controlling_process(inet:socket(), pid())
-> ok | {error, closed | not_owner | atom()}.
controlling_process(Socket, Pid) ->
gen_tcp:controlling_process(Socket, Pid).
-spec peername(inet:socket())
-> {ok, {inet:ip_address(), inet:port_number()}} | {error, atom()}.
peername(Socket) ->
inet:peername(Socket).
-spec sockname(inet:socket())
-> {ok, {inet:ip_address(), inet:port_number()}} | {error, atom()}.
sockname(Socket) ->
inet:sockname(Socket).
-spec shutdown(inet:socket(), read | write | read_write)
-> ok | {error, atom()}.
shutdown(Socket, How) ->
gen_tcp:shutdown(Socket, How).
-spec close(inet:socket()) -> ok.
close(Socket) ->
gen_tcp:close(Socket).
| null | https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/ranch/src/ranch_tcp.erl | erlang |
Permission to use, copy, modify, and/or 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.
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
The port in the options takes precedence over the one in the
implementation fails with a badmatch in
prim_file:sendfile/10 if the socket is not connected. | Copyright ( c ) 2011 - 2014 , < >
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
-module(ranch_tcp).
-behaviour(ranch_transport).
-export([name/0]).
-export([messages/0]).
-export([listen/1]).
-export([accept/2]).
-export([accept_ack/2]).
-export([connect/3]).
-export([connect/4]).
-export([recv/3]).
-export([send/2]).
-export([sendfile/2]).
-export([sendfile/4]).
-export([sendfile/5]).
-export([setopts/2]).
-export([controlling_process/2]).
-export([peername/1]).
-export([sockname/1]).
-export([shutdown/2]).
-export([close/1]).
-type opts() :: [{backlog, non_neg_integer()}
| {ip, inet:ip_address()}
| {linger, {boolean(), non_neg_integer()}}
| {nodelay, boolean()}
| {port, inet:port_number()}
| {raw, non_neg_integer(), non_neg_integer(),
non_neg_integer() | binary()}
| {send_timeout, timeout()}
| {send_timeout_close, boolean()}].
-export_type([opts/0]).
name() -> tcp.
messages() -> {tcp, tcp_closed, tcp_error}.
-spec listen(opts()) -> {ok, inet:socket()} | {error, atom()}.
listen(Opts) ->
Opts2 = ranch:set_option_default(Opts, backlog, 1024),
Opts3 = ranch:set_option_default(Opts2, send_timeout, 30000),
Opts4 = ranch:set_option_default(Opts3, send_timeout_close, true),
We set the port to 0 because it is given in the Opts directly .
first argument .
gen_tcp:listen(0, ranch:filter_options(Opts4,
[backlog, ip, linger, nodelay, port, raw,
send_timeout, send_timeout_close],
[binary, {active, false}, {packet, raw},
{reuseaddr, true}, {nodelay, true}])).
-spec accept(inet:socket(), timeout())
-> {ok, inet:socket()} | {error, closed | timeout | atom()}.
accept(LSocket, Timeout) ->
gen_tcp:accept(LSocket, Timeout).
-spec accept_ack(inet:socket(), timeout()) -> ok.
accept_ack(_, _) ->
ok.
@todo Probably filter Opts ?
-spec connect(inet:ip_address() | inet:hostname(),
inet:port_number(), any())
-> {ok, inet:socket()} | {error, atom()}.
connect(Host, Port, Opts) when is_integer(Port) ->
gen_tcp:connect(Host, Port,
Opts ++ [binary, {active, false}, {packet, raw}]).
@todo Probably filter Opts ?
-spec connect(inet:ip_address() | inet:hostname(),
inet:port_number(), any(), timeout())
-> {ok, inet:socket()} | {error, atom()}.
connect(Host, Port, Opts, Timeout) when is_integer(Port) ->
gen_tcp:connect(Host, Port,
Opts ++ [binary, {active, false}, {packet, raw}],
Timeout).
-spec recv(inet:socket(), non_neg_integer(), timeout())
-> {ok, any()} | {error, closed | atom()}.
recv(Socket, Length, Timeout) ->
gen_tcp:recv(Socket, Length, Timeout).
-spec send(inet:socket(), iodata()) -> ok | {error, atom()}.
send(Socket, Packet) ->
gen_tcp:send(Socket, Packet).
-spec sendfile(inet:socket(), file:name_all() | file:fd())
-> {ok, non_neg_integer()} | {error, atom()}.
sendfile(Socket, Filename) ->
sendfile(Socket, Filename, 0, 0, []).
-spec sendfile(inet:socket(), file:name_all() | file:fd(), non_neg_integer(),
non_neg_integer())
-> {ok, non_neg_integer()} | {error, atom()}.
sendfile(Socket, File, Offset, Bytes) ->
sendfile(Socket, File, Offset, Bytes, []).
-spec sendfile(inet:socket(), file:name_all() | file:fd(), non_neg_integer(),
non_neg_integer(), [{chunk_size, non_neg_integer()}])
-> {ok, non_neg_integer()} | {error, atom()}.
sendfile(Socket, Filename, Offset, Bytes, Opts)
when is_list(Filename) orelse is_atom(Filename)
orelse is_binary(Filename) ->
case file:open(Filename, [read, raw, binary]) of
{ok, RawFile} ->
try sendfile(Socket, RawFile, Offset, Bytes, Opts) of
Result -> Result
after
ok = file:close(RawFile)
end;
{error, _} = Error ->
Error
end;
sendfile(Socket, RawFile, Offset, Bytes, Opts) ->
Opts2 = case Opts of
[] -> [{chunk_size, 16#1FFF}];
_ -> Opts
end,
try file:sendfile(RawFile, Socket, Offset, Bytes, Opts2) of
Result -> Result
catch
error:{badmatch, {error, enotconn}} ->
file : sendfile/5 might fail by throwing a
{ badmatch , { error , enotconn } } . This is because its
{error, closed}
end.
@todo Probably filter Opts ?
-spec setopts(inet:socket(), list()) -> ok | {error, atom()}.
setopts(Socket, Opts) ->
inet:setopts(Socket, Opts).
-spec controlling_process(inet:socket(), pid())
-> ok | {error, closed | not_owner | atom()}.
controlling_process(Socket, Pid) ->
gen_tcp:controlling_process(Socket, Pid).
-spec peername(inet:socket())
-> {ok, {inet:ip_address(), inet:port_number()}} | {error, atom()}.
peername(Socket) ->
inet:peername(Socket).
-spec sockname(inet:socket())
-> {ok, {inet:ip_address(), inet:port_number()}} | {error, atom()}.
sockname(Socket) ->
inet:sockname(Socket).
-spec shutdown(inet:socket(), read | write | read_write)
-> ok | {error, atom()}.
shutdown(Socket, How) ->
gen_tcp:shutdown(Socket, How).
-spec close(inet:socket()) -> ok.
close(Socket) ->
gen_tcp:close(Socket).
|
3dacac549c198b65cde4c1a485d1d1219ee3c06148b91ae2e5f022033e2cec6b | sethfowler/pygmalion | Orphans.hs | # OPTIONS_GHC -fno - warn - orphans #
module Pygmalion.Database.Orphans () where
import Database.SQLite.Simple.ToField (ToField (..))
import Database.SQLite.Simple.ToRow (ToRow (..))
instance (ToField a, ToField b, ToField c, ToField d, ToField e, ToField f,
ToField g, ToField h, ToField i, ToField j, ToField k)
=> ToRow (a,b,c,d,e,f,g,h,i,j,k) where
toRow (a,b,c,d,e,f,g,h,i,j,k) =
[toField a, toField b, toField c, toField d, toField e, toField f,
toField g, toField h, toField i, toField j, toField k]
| null | https://raw.githubusercontent.com/sethfowler/pygmalion/d58cc3411d6a17cd05c3b0263824cd6a2f862409/src/Pygmalion/Database/Orphans.hs | haskell | # OPTIONS_GHC -fno - warn - orphans #
module Pygmalion.Database.Orphans () where
import Database.SQLite.Simple.ToField (ToField (..))
import Database.SQLite.Simple.ToRow (ToRow (..))
instance (ToField a, ToField b, ToField c, ToField d, ToField e, ToField f,
ToField g, ToField h, ToField i, ToField j, ToField k)
=> ToRow (a,b,c,d,e,f,g,h,i,j,k) where
toRow (a,b,c,d,e,f,g,h,i,j,k) =
[toField a, toField b, toField c, toField d, toField e, toField f,
toField g, toField h, toField i, toField j, toField k]
| |
e935bb6acee6693044e31dd794c24fac95bb4a605e4cd5b4f85dad0b8c57382c | panda-planner-dev/ipc2020-domains | d-17.lisp | (defdomain domain (
(:operator (!obtain_permit ?op_h)
;; preconditions
(
(type_Hazardous ?op_h)
(not (Have_Permit ?op_h))
)
;; delete effects
()
;; add effects
((Have_Permit ?op_h))
)
(:operator (!collect_fees ?cf_p)
;; preconditions
(
(type_Package ?cf_p)
(not (Fees_Collected ?cf_p))
)
;; delete effects
()
;; add effects
((Fees_Collected ?cf_p))
)
(:operator (!collect_insurance ?ci_v)
;; preconditions
(
(type_Valuable ?ci_v)
(not (Insured ?ci_v))
)
;; delete effects
()
;; add effects
((Insured ?ci_v))
)
(:operator (!go_through_tcenter_cc ?gttc_lo ?gttc_ld ?gttc_co ?gttc_cd ?gttc_tc)
;; preconditions
(
(type_Not_TCenter ?gttc_lo) (type_Not_TCenter ?gttc_ld) (type_City ?gttc_co) (type_City ?gttc_cd) (type_TCenter ?gttc_tc)
(In_City ?gttc_lo ?gttc_co) (In_City ?gttc_ld ?gttc_cd) (Serves ?gttc_tc ?gttc_co) (Serves ?gttc_tc ?gttc_cd) (Available ?gttc_tc)
)
;; delete effects
()
;; add effects
()
)
(:operator (!go_through_two_tcenters_cities_ottd ?gtttcc_lo ?gtttcc_ld ?gtttcc_co ?gtttcc_cd ?gtttcc_t1 ?gtttcc_t2)
;; preconditions
(
(type_Not_TCenter ?gtttcc_lo) (type_Not_TCenter ?gtttcc_ld) (type_City ?gtttcc_co) (type_City ?gtttcc_cd) (type_TCenter ?gtttcc_t1) (type_TCenter ?gtttcc_t2)
(In_City ?gtttcc_lo ?gtttcc_co) (In_City ?gtttcc_ld ?gtttcc_cd) (Serves ?gtttcc_t1 ?gtttcc_co) (Serves ?gtttcc_t2 ?gtttcc_cd)
)
;; delete effects
()
;; add effects
()
)
(:operator (!go_through_two_tcenters_cities_otd ?gtttccotd_ld ?gtttccotd_co ?gtttccotd_cd ?gtttccotd_to ?gtttccotd_t1)
;; preconditions
(
(type_Not_TCenter ?gtttccotd_ld) (type_City ?gtttccotd_co) (type_City ?gtttccotd_cd) (type_TCenter ?gtttccotd_to) (type_TCenter ?gtttccotd_t1)
(In_City ?gtttccotd_to ?gtttccotd_co) (In_City ?gtttccotd_ld ?gtttccotd_cd) (Serves ?gtttccotd_t1 ?gtttccotd_cd)
)
;; delete effects
()
;; add effects
()
)
(:operator (!go_through_two_tcenters_cities_ott ?gtttccott_ld ?gtttccott_co ?gtttccott_cd ?gtttccott_to ?gtttccott_td)
;; preconditions
(
(type_City_Location ?gtttccott_ld) (type_City ?gtttccott_co) (type_City ?gtttccott_cd) (type_TCenter ?gtttccott_to) (type_TCenter ?gtttccott_td)
(In_City ?gtttccott_ld ?gtttccott_co) (In_City ?gtttccott_td ?gtttccott_cd) (Serves ?gtttccott_to ?gtttccott_co)
)
;; delete effects
()
;; add effects
()
)
(:operator (!go_through_two_tcenters ?gtttc_to ?gtttc_td)
;; preconditions
(
(type_TCenter ?gtttc_to) (type_TCenter ?gtttc_td)
(Available ?gtttc_to) (Available ?gtttc_td)
)
;; delete effects
()
;; add effects
()
)
(:operator (!go_through_two_tcenters_tt ?gtttctt_to ?gtttctt_td ?gtttctt_co ?gtttctt_cd)
;; preconditions
(
(type_TCenter ?gtttctt_to) (type_TCenter ?gtttctt_td) (type_City ?gtttctt_co) (type_City ?gtttctt_cd)
(In_City ?gtttctt_to ?gtttctt_co) (In_City ?gtttctt_td ?gtttctt_cd)
)
;; delete effects
()
;; add effects
()
)
(:operator (!go_through_two_tcenters_via_hub_hazardous ?gtttcvhh_to ?gtttcvhh_td ?gtttcvhh_h ?gtttcvhh_co ?gtttcvhh_ch ?gtttcvhh_cd ?gtttcvhh_ro ?gtttcvhh_rd)
;; preconditions
(
(type_TCenter ?gtttcvhh_to) (type_TCenter ?gtttcvhh_td) (type_Hub ?gtttcvhh_h) (type_City ?gtttcvhh_co) (type_City ?gtttcvhh_ch) (type_City ?gtttcvhh_cd) (type_Region ?gtttcvhh_ro) (type_Region ?gtttcvhh_rd)
(Available ?gtttcvhh_to) (Available ?gtttcvhh_td) (In_City ?gtttcvhh_h ?gtttcvhh_ch) (City_Hazardous_Compatible ?gtttcvhh_ch) (In_City ?gtttcvhh_to ?gtttcvhh_co) (In_City ?gtttcvhh_td ?gtttcvhh_cd) (In_Region ?gtttcvhh_co ?gtttcvhh_ro) (In_Region ?gtttcvhh_cd ?gtttcvhh_rd) (Serves ?gtttcvhh_h ?gtttcvhh_ro) (Serves ?gtttcvhh_h ?gtttcvhh_rd) (Available ?gtttcvhh_h)
)
;; delete effects
()
;; add effects
()
)
(:operator (!go_through_two_tcenters_via_hub_not_hazardous ?gtttcvhnh_to ?gtttcvhnh_td ?gtttcvhnh_co ?gtttcvhnh_cd ?gtttcvhnh_ro ?gtttcvhnh_rd ?gtttcvhnh_h)
;; preconditions
(
(type_TCenter ?gtttcvhnh_to) (type_TCenter ?gtttcvhnh_td) (type_City ?gtttcvhnh_co) (type_City ?gtttcvhnh_cd) (type_Region ?gtttcvhnh_ro) (type_Region ?gtttcvhnh_rd) (type_Hub ?gtttcvhnh_h)
(Available ?gtttcvhnh_to) (Available ?gtttcvhnh_td) (In_City ?gtttcvhnh_to ?gtttcvhnh_co) (In_City ?gtttcvhnh_td ?gtttcvhnh_cd) (In_Region ?gtttcvhnh_co ?gtttcvhnh_ro) (In_Region ?gtttcvhnh_cd ?gtttcvhnh_rd) (Serves ?gtttcvhnh_h ?gtttcvhnh_ro) (Serves ?gtttcvhnh_h ?gtttcvhnh_rd) (Available ?gtttcvhnh_h)
)
;; delete effects
()
;; add effects
()
)
(:operator (!deliver_p ?dp_p)
;; preconditions
(
(type_Package ?dp_p)
(Fees_Collected ?dp_p)
)
;; delete effects
((Fees_Collected ?dp_p))
;; add effects
((Delivered ?dp_p))
)
(:operator (!deliver_h ?dh_h)
;; preconditions
(
(type_Hazardous ?dh_h)
(Fees_Collected ?dh_h) (Have_Permit ?dh_h)
)
;; delete effects
((Have_Permit ?dh_h) (Fees_Collected ?dh_h))
;; add effects
((Delivered ?dh_h))
)
(:operator (!deliver_v ?dv_v)
;; preconditions
(
(type_Valuable ?dv_v)
(Fees_Collected ?dv_v) (Insured ?dv_v)
)
;; delete effects
((Fees_Collected ?dv_v) (Insured ?dv_v))
;; add effects
((Delivered ?dv_v))
)
(:operator (!post_guard_outside ?pco_a)
;; preconditions
(
(type_Armored ?pco_a)
)
;; delete effects
((Guard_Inside ?pco_a))
;; add effects
((Guard_Outside ?pco_a))
)
(:operator (!post_guard_inside ?pci_a)
;; preconditions
(
(type_Armored ?pci_a)
)
;; delete effects
((Guard_Outside ?pci_a))
;; add effects
((Guard_Inside ?pci_a))
)
(:operator (!remove_guard ?mc_a)
;; preconditions
(
(type_Armored ?mc_a)
)
;; delete effects
((Guard_Outside ?mc_a) (Guard_Inside ?mc_a))
;; add effects
()
)
(:operator (!decontaminate_interior ?di_v)
;; preconditions
(
(type_Vehicle ?di_v)
)
;; delete effects
()
;; add effects
((Decontaminated_Interior ?di_v))
)
(:operator (!affix_warning_signs ?fws_v)
;; preconditions
(
(type_Vehicle ?fws_v)
(not (Warning_Signs_Affixed ?fws_v))
)
;; delete effects
()
;; add effects
((Warning_Signs_Affixed ?fws_v))
)
(:operator (!remove_warning_signs ?mws_v)
;; preconditions
(
(type_Vehicle ?mws_v)
(Warning_Signs_Affixed ?mws_v)
)
;; delete effects
((Warning_Signs_Affixed ?mws_v))
;; add effects
()
)
(:operator (!attach_train_car ?atc_t ?atc_tc ?atc_l)
;; preconditions
(
(type_Train ?atc_t) (type_Traincar ?atc_tc) (type_Location ?atc_l)
(At_Vehicle ?atc_tc ?atc_l) (At_Vehicle ?atc_t ?atc_l) (not (Connected_To ?atc_tc ?atc_t))
)
;; delete effects
((At_Vehicle ?atc_tc ?atc_l))
;; add effects
((Connected_To ?atc_tc ?atc_t))
)
(:operator (!detach_train_car ?dtc_t ?dtc_tc ?dtc_l)
;; preconditions
(
(type_Train ?dtc_t) (type_Traincar ?dtc_tc) (type_Location ?dtc_l)
(At_Vehicle ?dtc_t ?dtc_l) (Connected_To ?dtc_tc ?dtc_t)
)
;; delete effects
((Connected_To ?dtc_tc ?dtc_t))
;; add effects
((At_Vehicle ?dtc_tc ?dtc_l))
)
(:operator (!connect_hose ?ch_tv ?ch_l)
;; preconditions
(
(type_Tanker_Vehicle ?ch_tv) (type_Liquid ?ch_l)
(not (Hose_Connected ?ch_tv ?ch_l))
)
;; delete effects
()
;; add effects
((Hose_Connected ?ch_tv ?ch_l))
)
(:operator (!disconnect_hose ?dch_tv ?dch_l)
;; preconditions
(
(type_Tanker_Vehicle ?dch_tv) (type_Liquid ?dch_l)
(Hose_Connected ?dch_tv ?dch_l)
)
;; delete effects
((Hose_Connected ?dch_tv ?dch_l))
;; add effects
()
)
(:operator (!open_valve ?ov_tv)
;; preconditions
(
(type_Tanker_Vehicle ?ov_tv)
(not (Valve_Open ?ov_tv))
)
;; delete effects
()
;; add effects
((Valve_Open ?ov_tv))
)
(:operator (!close_valve ?cv_tv)
;; preconditions
(
(type_Tanker_Vehicle ?cv_tv)
(Valve_Open ?cv_tv)
)
;; delete effects
((Valve_Open ?cv_tv))
;; add effects
()
)
(:operator (!fill_tank ?ft_tv ?ft_li ?ft_lo)
;; preconditions
(
(type_Tanker_Vehicle ?ft_tv) (type_Liquid ?ft_li) (type_Location ?ft_lo)
(Hose_Connected ?ft_tv ?ft_li) (Valve_Open ?ft_tv) (At_Package ?ft_li ?ft_lo) (At_Vehicle ?ft_tv ?ft_lo) (PV_Compatible ?ft_li ?ft_tv)
)
;; delete effects
((At_Package ?ft_li ?ft_lo))
;; add effects
((At_Package ?ft_li ?ft_tv))
)
(:operator (!empty_tank ?et_tv ?et_li ?et_lo)
;; preconditions
(
(type_Tanker_Vehicle ?et_tv) (type_Liquid ?et_li) (type_Location ?et_lo)
(Hose_Connected ?et_tv ?et_li) (Valve_Open ?et_tv) (At_Package ?et_li ?et_tv) (At_Vehicle ?et_tv ?et_lo)
)
;; delete effects
((At_Package ?et_li ?et_tv))
;; add effects
((At_Package ?et_li ?et_lo))
)
(:operator (!load_cars ?lc_c ?lc_v ?lc_l)
;; preconditions
(
(type_Cars ?lc_c) (type_Auto_Vehicle ?lc_v) (type_Location ?lc_l)
(At_Package ?lc_c ?lc_l) (At_Vehicle ?lc_v ?lc_l) (Ramp_Down ?lc_v) (PV_Compatible ?lc_c ?lc_v)
)
;; delete effects
((At_Package ?lc_c ?lc_l))
;; add effects
((At_Package ?lc_c ?lc_v))
)
(:operator (!unload_cars ?uc_c ?uc_v ?uc_l)
;; preconditions
(
(type_Cars ?uc_c) (type_Auto_Vehicle ?uc_v) (type_Location ?uc_l)
(At_Package ?uc_c ?uc_v) (At_Vehicle ?uc_v ?uc_l) (Ramp_Down ?uc_v)
)
;; delete effects
((At_Package ?uc_c ?uc_v))
;; add effects
((At_Package ?uc_c ?uc_l))
)
(:operator (!raise_ramp ?rr_v)
;; preconditions
(
(type_Vehicle ?rr_v)
(Ramp_Down ?rr_v)
)
;; delete effects
((Ramp_Down ?rr_v))
;; add effects
()
)
(:operator (!lower_ramp ?lr_v)
;; preconditions
(
(type_Vehicle ?lr_v)
(not (Ramp_Down ?lr_v))
)
;; delete effects
()
;; add effects
((Ramp_Down ?lr_v))
)
(:operator (!load_livestock ?ll_p ?ll_v ?ll_l)
;; preconditions
(
(type_Livestock_Package ?ll_p) (type_Livestock_Vehicle ?ll_v) (type_Location ?ll_l)
(At_Package ?ll_p ?ll_l) (At_Vehicle ?ll_v ?ll_l) (Ramp_Down ?ll_v) (PV_Compatible ?ll_p ?ll_v)
)
;; delete effects
((At_Package ?ll_p ?ll_l) (Clean_Interior ?ll_v))
;; add effects
((At_Package ?ll_p ?ll_v))
)
(:operator (!unload_livestock ?ull_p ?ull_v ?ull_l)
;; preconditions
(
(type_Livestock_Package ?ull_p) (type_Livestock_Vehicle ?ull_v) (type_Location ?ull_l)
(At_Package ?ull_p ?ull_v) (At_Vehicle ?ull_v ?ull_l) (Ramp_Down ?ull_v)
)
;; delete effects
((At_Package ?ull_p ?ull_v) (Trough_Full ?ull_v))
;; add effects
((At_Package ?ull_p ?ull_l))
)
(:operator (!fill_trough ?ftr_v)
;; preconditions
(
(type_Livestock_Vehicle ?ftr_v)
)
;; delete effects
()
;; add effects
((Trough_Full ?ftr_v))
)
(:operator (!do_clean_interior ?cli_v)
;; preconditions
(
(type_Vehicle ?cli_v)
)
;; delete effects
()
;; add effects
((Clean_Interior ?cli_v))
)
(:operator (!attach_conveyor_ramp ?acr_ap ?acr_pr ?acr_l)
;; preconditions
(
(type_Airplane ?acr_ap) (type_Plane_Ramp ?acr_pr) (type_Location ?acr_l)
(Available ?acr_pr) (At_Equipment ?acr_pr ?acr_l) (At_Vehicle ?acr_ap ?acr_l)
)
;; delete effects
((Available ?acr_pr))
;; add effects
((Ramp_Connected ?acr_pr ?acr_ap))
)
(:operator (!detach_conveyor_ramp ?dcr_ap ?dcr_pr ?dcr_l)
;; preconditions
(
(type_Airplane ?dcr_ap) (type_Plane_Ramp ?dcr_pr) (type_Location ?dcr_l)
(Ramp_Connected ?dcr_pr ?dcr_ap) (At_Equipment ?dcr_pr ?dcr_l) (At_Vehicle ?dcr_ap ?dcr_l)
)
;; delete effects
((Ramp_Connected ?dcr_pr ?dcr_ap))
;; add effects
((Available ?dcr_pr))
)
(:operator (!connect_chute ?cc_h)
;; preconditions
(
(type_Hopper_Vehicle ?cc_h)
(not (Chute_Connected ?cc_h))
)
;; delete effects
()
;; add effects
((Chute_Connected ?cc_h))
)
(:operator (!disconnect_chute ?dc_h)
;; preconditions
(
(type_Hopper_Vehicle ?dc_h)
(Chute_Connected ?dc_h)
)
;; delete effects
((Chute_Connected ?dc_h))
;; add effects
()
)
(:operator (!fill_hopper ?fh_p ?fh_hv ?fh_l)
;; preconditions
(
(type_Package ?fh_p) (type_Hopper_Vehicle ?fh_hv) (type_Location ?fh_l)
(Chute_Connected ?fh_hv) (At_Vehicle ?fh_hv ?fh_l) (At_Package ?fh_p ?fh_l) (PV_Compatible ?fh_p ?fh_hv)
)
;; delete effects
((At_Package ?fh_p ?fh_l))
;; add effects
((At_Package ?fh_p ?fh_hv))
)
(:operator (!empty_hopper ?eh_p ?eh_hv ?eh_l)
;; preconditions
(
(type_Package ?eh_p) (type_Hopper_Vehicle ?eh_hv) (type_Location ?eh_l)
(Chute_Connected ?eh_hv) (At_Vehicle ?eh_hv ?eh_l) (At_Package ?eh_p ?eh_hv)
)
;; delete effects
((At_Package ?eh_p ?eh_hv))
;; add effects
((At_Package ?eh_p ?eh_l))
)
(:operator (!pick_up_package_ground ?pupg_p ?pupg_c ?pupg_l)
;; preconditions
(
(type_Package ?pupg_p) (type_Crane ?pupg_c) (type_Location ?pupg_l)
(Empty ?pupg_c) (Available ?pupg_c) (At_Equipment ?pupg_c ?pupg_l) (At_Package ?pupg_p ?pupg_l)
)
;; delete effects
((Empty ?pupg_c) (At_Package ?pupg_p ?pupg_l))
;; add effects
((At_Package ?pupg_p ?pupg_c))
)
(:operator (!put_down_package_ground ?pdpg_p ?pdpg_c ?pdpg_l)
;; preconditions
(
(type_Package ?pdpg_p) (type_Crane ?pdpg_c) (type_Location ?pdpg_l)
(Available ?pdpg_c) (At_Equipment ?pdpg_c ?pdpg_l) (At_Package ?pdpg_p ?pdpg_c)
)
;; delete effects
((At_Package ?pdpg_p ?pdpg_c))
;; add effects
((At_Package ?pdpg_p ?pdpg_l) (Empty ?pdpg_c))
)
(:operator (!pick_up_package_vehicle ?pupv_p ?pupv_c ?pupv_fv ?pupv_l)
;; preconditions
(
(type_Package ?pupv_p) (type_Crane ?pupv_c) (type_Flatbed_Vehicle ?pupv_fv) (type_Location ?pupv_l)
(Empty ?pupv_c) (Available ?pupv_c) (At_Equipment ?pupv_c ?pupv_l) (At_Package ?pupv_p ?pupv_fv) (At_Vehicle ?pupv_fv ?pupv_l)
)
;; delete effects
((Empty ?pupv_c) (At_Package ?pupv_p ?pupv_fv))
;; add effects
((At_Package ?pupv_p ?pupv_c))
)
(:operator (!put_down_package_vehicle ?pdpv_p ?pdpv_c ?pdpv_fv ?pdpv_l)
;; preconditions
(
(type_Package ?pdpv_p) (type_Crane ?pdpv_c) (type_Flatbed_Vehicle ?pdpv_fv) (type_Location ?pdpv_l)
(Available ?pdpv_c) (At_Package ?pdpv_p ?pdpv_c) (At_Equipment ?pdpv_c ?pdpv_l) (At_Vehicle ?pdpv_fv ?pdpv_l) (PV_Compatible ?pdpv_p ?pdpv_fv)
)
;; delete effects
((At_Package ?pdpv_p ?pdpv_c))
;; add effects
((Empty ?pdpv_c) (At_Package ?pdpv_p ?pdpv_fv))
)
(:operator (!open_door ?od_rv)
;; preconditions
(
(type_Regular_Vehicle ?od_rv)
(not (Door_Open ?od_rv))
)
;; delete effects
()
;; add effects
((Door_Open ?od_rv))
)
(:operator (!close_door ?cd_rv)
;; preconditions
(
(type_Regular_Vehicle ?cd_rv)
(Door_Open ?cd_rv)
)
;; delete effects
((Door_Open ?cd_rv))
;; add effects
()
)
(:operator (!load_package ?lp_p ?lp_v ?lp_l)
;; preconditions
(
(type_Package ?lp_p) (type_Vehicle ?lp_v) (type_Location ?lp_l)
(At_Package ?lp_p ?lp_l) (At_Vehicle ?lp_v ?lp_l) (PV_Compatible ?lp_p ?lp_v)
)
;; delete effects
((At_Package ?lp_p ?lp_l))
;; add effects
((At_Package ?lp_p ?lp_v))
)
(:operator (!unload_package ?up_p ?up_v ?up_l)
;; preconditions
(
(type_Package ?up_p) (type_Vehicle ?up_v) (type_Location ?up_l)
(At_Package ?up_p ?up_v) (At_Vehicle ?up_v ?up_l)
)
;; delete effects
((At_Package ?up_p ?up_v))
;; add effects
((At_Package ?up_p ?up_l))
)
(:operator (!move_vehicle_no_traincar ?hmnt_v ?hmnt_o ?hmnt_r ?hmnt_d)
;; preconditions
(
(type_Vehicle ?hmnt_v) (type_Location ?hmnt_o) (type_Route ?hmnt_r) (type_Location ?hmnt_d)
(Connects ?hmnt_r ?hmnt_o ?hmnt_d) (Available ?hmnt_v) (Available ?hmnt_r) (RV_Compatible ?hmnt_r ?hmnt_v) (At_Vehicle ?hmnt_v ?hmnt_o)
)
;; delete effects
((At_Vehicle ?hmnt_v ?hmnt_o))
;; add effects
((At_Vehicle ?hmnt_v ?hmnt_d))
)
(:method (__top)
__top_method
(
(type_sort_for_O27 ?var_for_O27_1) (type_sort_for_O28 ?var_for_O28_2) (type_sort_for_Toshiba_Laptops ?var_for_Toshiba_Laptops_3)
)
((transport ?var_for_Toshiba_Laptops_3 ?var_for_O27_1 ?var_for_O28_2))
)
(:method (carry ?mccd_cd_p ?mccd_cd_lo ?mccd_cd_ld)
method_carry_cd
(
(type_Package ?mccd_cd_p) (type_Location ?mccd_cd_lo) (type_Location ?mccd_cd_ld)
(type_Location ?mccd_cd_ld) (type_Location ?mccd_cd_lo) (type_Package ?mccd_cd_p)
)
((carry_direct ?mccd_cd_p ?mccd_cd_lo ?mccd_cd_ld))
)
(:method (carry ?mch_hctt_p ?mch_hctt_o ?mch_hctt_d)
method_carry_cvh
(
(type_Package ?mch_hctt_p) (type_Location ?mch_hctt_o) (type_Location ?mch_hctt_d)
(type_City ?mch_hctt_cd) (type_City ?mch_hctt_co) (type_TCenter ?mch_hctt_d) (type_TCenter ?mch_hctt_o) (type_Package ?mch_hctt_p)
)
((helper_carry_tt ?mch_hctt_p ?mch_hctt_o ?mch_hctt_co ?mch_hctt_d ?mch_hctt_cd))
)
(:method (carry ?mccct_hcott_p ?mccct_hcott_o ?mccct_hcott_d)
method_carry_cd_cbtc
(
(type_Package ?mccct_hcott_p) (type_Location ?mccct_hcott_o) (type_Location ?mccct_hcott_d)
(type_City ?mccct_hcott_cd) (type_City ?mccct_hcott_co) (type_TCenter ?mccct_hcott_d) (type_City_Location ?mccct_hcott_o) (type_Package ?mccct_hcott_p) (type_TCenter ?mccct_hcott_t1)
)
((helper_carry_ott ?mccct_hcott_p ?mccct_hcott_o ?mccct_hcott_co ?mccct_hcott_t1 ?mccct_hcott_d ?mccct_hcott_cd))
)
(:method (carry ?mcctc_hcotd_p ?mcctc_hcotd_o ?mcctc_hcotd_d)
method_carry_cbtc_cd
(
(type_Package ?mcctc_hcotd_p) (type_Location ?mcctc_hcotd_o) (type_Location ?mcctc_hcotd_d)
(type_City ?mcctc_hcotd_cd) (type_City ?mcctc_hcotd_co) (type_Not_TCenter ?mcctc_hcotd_d) (type_TCenter ?mcctc_hcotd_o) (type_Package ?mcctc_hcotd_p) (type_TCenter ?mcctc_hcotd_t1)
)
((helper_carry_otd ?mcctc_hcotd_p ?mcctc_hcotd_o ?mcctc_hcotd_co ?mcctc_hcotd_t1 ?mcctc_hcotd_d ?mcctc_hcotd_cd))
)
(:method (carry ?mcccc_hcottd_p ?mcccc_hcottd_o ?mcccc_hcottd_d)
method_carry_cd_cbtc_cd
(
(type_Package ?mcccc_hcottd_p) (type_Location ?mcccc_hcottd_o) (type_Location ?mcccc_hcottd_d)
(type_City ?mcccc_hcottd_cd) (type_City ?mcccc_hcottd_co) (type_Not_TCenter ?mcccc_hcottd_d) (type_Not_TCenter ?mcccc_hcottd_o) (type_Package ?mcccc_hcottd_p) (type_TCenter ?mcccc_hcottd_t1) (type_TCenter ?mcccc_hcottd_t2)
)
((helper_carry_ottd ?mcccc_hcottd_p ?mcccc_hcottd_o ?mcccc_hcottd_co ?mcccc_hcottd_t1 ?mcccc_hcottd_t2 ?mcccc_hcottd_d ?mcccc_hcottd_cd))
)
(:method (carry ?mccc_hccc_p ?mccc_hccc_o ?mccc_hccc_d)
method_carry_cd_cd
(
(type_Package ?mccc_hccc_p) (type_Location ?mccc_hccc_o) (type_Location ?mccc_hccc_d)
(type_City ?mccc_hccc_cd) (type_City ?mccc_hccc_co) (type_Not_TCenter ?mccc_hccc_d) (type_Not_TCenter ?mccc_hccc_o) (type_Package ?mccc_hccc_p) (type_TCenter ?mccc_hccc_t)
)
((helper_carry_cc ?mccc_hccc_p ?mccc_hccc_o ?mccc_hccc_co ?mccc_hccc_t ?mccc_hccc_d ?mccc_hccc_cd))
)
(:method (carry_between_tcenters ?mcbtc_cd_p ?mcbtc_gtttc_to ?mcbtc_gtttc_td)
method_carry_between_tcenters_cd
(
(type_Package ?mcbtc_cd_p) (type_TCenter ?mcbtc_gtttc_to) (type_TCenter ?mcbtc_gtttc_td)
(type_Package ?mcbtc_cd_p) (type_TCenter ?mcbtc_gtttc_td) (type_TCenter ?mcbtc_gtttc_to)
)
(:unordered (!go_through_two_tcenters ?mcbtc_gtttc_to ?mcbtc_gtttc_td) (carry_direct ?mcbtc_cd_p ?mcbtc_gtttc_to ?mcbtc_gtttc_td))
)
(:method (carry_between_tcenters ?mcbth_tch_p ?mcbth_tch_tco ?mcbth_tch_tcd)
method_carry_between_tcenters_cvh
(
(type_Package ?mcbth_tch_p) (type_TCenter ?mcbth_tch_tco) (type_TCenter ?mcbth_tch_tcd)
(type_Package ?mcbth_tch_p) (type_TCenter ?mcbth_tch_tcd) (type_TCenter ?mcbth_tch_tco)
)
((carry_via_hub ?mcbth_tch_p ?mcbth_tch_tco ?mcbth_tch_tcd))
)
(:method (carry_direct ?mcd_hmcd_p ?mcd_hmcd_o ?mcd_hmcd_d)
method_carry_direct
(
(type_Package ?mcd_hmcd_p) (type_Location ?mcd_hmcd_o) (type_Location ?mcd_hmcd_d)
(type_Location ?mcd_hmcd_d) (type_Location ?mcd_hmcd_o) (type_Package ?mcd_hmcd_p) (type_Vehicle ?mcd_hmcd_v)
)
((helper_carry_direct ?mcd_hmcd_v ?mcd_hmcd_p ?mcd_hmcd_o ?mcd_hmcd_d))
)
(:method (carry_via_hub ?mcvhn_hcvhn_p ?mcvhn_hcvhn_tco ?mcvhn_hcvhn_tcd)
method_carry_via_hub_not_hazardous
(
(type_Package ?mcvhn_hcvhn_p) (type_TCenter ?mcvhn_hcvhn_tco) (type_TCenter ?mcvhn_hcvhn_tcd)
(type_City ?mcvhn_hcvhn_ctcd) (type_City ?mcvhn_hcvhn_ctco) (type_Hub ?mcvhn_hcvhn_h) (type_Package ?mcvhn_hcvhn_p) (type_Region ?mcvhn_hcvhn_rctcd) (type_Region ?mcvhn_hcvhn_rctco) (type_TCenter ?mcvhn_hcvhn_tcd) (type_TCenter ?mcvhn_hcvhn_tco)
)
((helper_carry_via_hub_not_hazardous ?mcvhn_hcvhn_p ?mcvhn_hcvhn_tco ?mcvhn_hcvhn_ctco ?mcvhn_hcvhn_rctco ?mcvhn_hcvhn_h ?mcvhn_hcvhn_tcd ?mcvhn_hcvhn_ctcd ?mcvhn_hcvhn_rctcd))
)
(:method (carry_via_hub ?mcvhh_hcvhh_p ?mcvhh_hcvhh_tco ?mcvhh_hcvhh_tcd)
method_carry_via_hub_hazardous
(
(type_Package ?mcvhh_hcvhh_p) (type_TCenter ?mcvhh_hcvhh_tco) (type_TCenter ?mcvhh_hcvhh_tcd)
(type_City ?mcvhh_hcvhh_ch) (type_City ?mcvhh_hcvhh_ctcd) (type_City ?mcvhh_hcvhh_ctco) (type_Hub ?mcvhh_hcvhh_h) (type_Package ?mcvhh_hcvhh_p) (type_Region ?mcvhh_hcvhh_rctcd) (type_Region ?mcvhh_hcvhh_rctco) (type_TCenter ?mcvhh_hcvhh_tcd) (type_TCenter ?mcvhh_hcvhh_tco)
)
((helper_carry_via_hub_hazardous ?mcvhh_hcvhh_p ?mcvhh_hcvhh_tco ?mcvhh_hcvhh_ctco ?mcvhh_hcvhh_rctco ?mcvhh_hcvhh_h ?mcvhh_hcvhh_ch ?mcvhh_hcvhh_tcd ?mcvhh_hcvhh_ctcd ?mcvhh_hcvhh_rctcd))
)
(:method (deliver ?mddp_dp_p)
method_deliver_dp
(
(type_Package ?mddp_dp_p)
(type_Package ?mddp_dp_p)
)
((!deliver_p ?mddp_dp_p))
)
(:method (deliver ?mddv_dv_v)
method_deliver_dv
(
(type_Package ?mddv_dv_v)
(type_Valuable ?mddv_dv_v)
)
((!deliver_v ?mddv_dv_v))
)
(:method (deliver ?mddh_dh_h)
method_deliver_dh
(
(type_Package ?mddh_dh_h)
(type_Hazardous ?mddh_dh_h)
)
((!deliver_h ?mddh_dh_h))
)
(:method (helper_carry_cc ?mhccc_cdd_p ?mhccc_gttc_lo ?mhccc_gttc_co ?mhccc_gttc_tc ?mhccc_gttc_ld ?mhccc_gttc_cd)
method_helper_carry_cd_cd
(
(type_Package ?mhccc_cdd_p) (type_Not_TCenter ?mhccc_gttc_lo) (type_City ?mhccc_gttc_co) (type_TCenter ?mhccc_gttc_tc) (type_Not_TCenter ?mhccc_gttc_ld) (type_City ?mhccc_gttc_cd)
(type_Package ?mhccc_cdd_p) (type_City ?mhccc_gttc_cd) (type_City ?mhccc_gttc_co) (type_Not_TCenter ?mhccc_gttc_ld) (type_Not_TCenter ?mhccc_gttc_lo) (type_TCenter ?mhccc_gttc_tc)
)
((carry_direct ?mhccc_cdd_p ?mhccc_gttc_lo ?mhccc_gttc_tc) (!go_through_tcenter_cc ?mhccc_gttc_lo ?mhccc_gttc_ld ?mhccc_gttc_co ?mhccc_gttc_cd ?mhccc_gttc_tc) (carry_direct ?mhccc_cdd_p ?mhccc_gttc_tc ?mhccc_gttc_ld))
)
(:method (helper_carry_direct ?mhcd_ult_v ?mhcd_ult_p ?mhcd_mvd_lo ?mhcd_ult_l)
method_helper_carry_direct
(
(type_Vehicle ?mhcd_ult_v) (type_Package ?mhcd_ult_p) (type_Location ?mhcd_mvd_lo) (type_Location ?mhcd_ult_l)
(type_Location ?mhcd_mvd_lo) (type_Location ?mhcd_mvo_lo) (type_Location ?mhcd_ult_l) (type_Package ?mhcd_ult_p) (type_Vehicle ?mhcd_ult_v)
)
((move ?mhcd_ult_v ?mhcd_mvo_lo ?mhcd_mvd_lo) (load_top ?mhcd_ult_p ?mhcd_ult_v ?mhcd_mvd_lo) (move ?mhcd_ult_v ?mhcd_mvd_lo ?mhcd_ult_l) (unload_top ?mhcd_ult_p ?mhcd_ult_v ?mhcd_ult_l))
)
(:method (helper_carry_direct ?mhcdo_ult_v ?mhcdo_ult_p ?mhcdo_m_lo ?mhcdo_ult_l)
method_helper_carry_direct_noMoveFirst
(
(type_Vehicle ?mhcdo_ult_v) (type_Package ?mhcdo_ult_p) (type_Location ?mhcdo_m_lo) (type_Location ?mhcdo_ult_l)
(type_Location ?mhcdo_m_lo) (type_Location ?mhcdo_ult_l) (type_Package ?mhcdo_ult_p) (type_Vehicle ?mhcdo_ult_v)
)
((load_top ?mhcdo_ult_p ?mhcdo_ult_v ?mhcdo_m_lo) (move ?mhcdo_ult_v ?mhcdo_m_lo ?mhcdo_ult_l) (unload_top ?mhcdo_ult_p ?mhcdo_ult_v ?mhcdo_ult_l))
)
(:method (helper_carry_otd ?mhcctc_cd_p ?mhcctc_gtttccotd_o ?mhcctc_gtttccotd_co ?mhcctc_gtttccotd_t1 ?mhcctc_gtttccotd_cl ?mhcctc_gtttccotd_cd)
method_helper_carry_cbtc_cd
(
(type_Package ?mhcctc_cd_p) (type_TCenter ?mhcctc_gtttccotd_o) (type_City ?mhcctc_gtttccotd_co) (type_TCenter ?mhcctc_gtttccotd_t1) (type_Not_TCenter ?mhcctc_gtttccotd_cl) (type_City ?mhcctc_gtttccotd_cd)
(type_Package ?mhcctc_cd_p) (type_City ?mhcctc_gtttccotd_cd) (type_Not_TCenter ?mhcctc_gtttccotd_cl) (type_City ?mhcctc_gtttccotd_co) (type_TCenter ?mhcctc_gtttccotd_o) (type_TCenter ?mhcctc_gtttccotd_t1)
)
((carry_between_tcenters ?mhcctc_cd_p ?mhcctc_gtttccotd_o ?mhcctc_gtttccotd_t1) (!go_through_two_tcenters_cities_otd ?mhcctc_gtttccotd_cl ?mhcctc_gtttccotd_co ?mhcctc_gtttccotd_cd ?mhcctc_gtttccotd_o ?mhcctc_gtttccotd_t1) (carry_direct ?mhcctc_cd_p ?mhcctc_gtttccotd_t1 ?mhcctc_gtttccotd_cl))
)
(:method (helper_carry_ott ?mhccct_cbt_p ?mhccct_gtttccott_cl ?mhccct_gtttccott_co ?mhccct_gtttccott_to ?mhccct_gtttccott_td ?mhccct_gtttccott_cd)
method_helper_carry_cd_cbtc
(
(type_Package ?mhccct_cbt_p) (type_City_Location ?mhccct_gtttccott_cl) (type_City ?mhccct_gtttccott_co) (type_TCenter ?mhccct_gtttccott_to) (type_TCenter ?mhccct_gtttccott_td) (type_City ?mhccct_gtttccott_cd)
(type_Package ?mhccct_cbt_p) (type_City ?mhccct_gtttccott_cd) (type_City_Location ?mhccct_gtttccott_cl) (type_City ?mhccct_gtttccott_co) (type_TCenter ?mhccct_gtttccott_td) (type_TCenter ?mhccct_gtttccott_to)
)
((carry_direct ?mhccct_cbt_p ?mhccct_gtttccott_cl ?mhccct_gtttccott_to) (!go_through_two_tcenters_cities_ott ?mhccct_gtttccott_cl ?mhccct_gtttccott_co ?mhccct_gtttccott_cd ?mhccct_gtttccott_to ?mhccct_gtttccott_td) (carry_between_tcenters ?mhccct_cbt_p ?mhccct_gtttccott_to ?mhccct_gtttccott_td))
)
(:method (helper_carry_ottd ?mhcccc_cdd_p ?mhcccc_gtttc_lo ?mhcccc_gtttc_co ?mhcccc_gtttc_t1 ?mhcccc_gtttc_t2 ?mhcccc_gtttc_ld ?mhcccc_gtttc_cd)
method_helper_carry_cd_cbtc_cd
(
(type_Package ?mhcccc_cdd_p) (type_Not_TCenter ?mhcccc_gtttc_lo) (type_City ?mhcccc_gtttc_co) (type_TCenter ?mhcccc_gtttc_t1) (type_TCenter ?mhcccc_gtttc_t2) (type_Not_TCenter ?mhcccc_gtttc_ld) (type_City ?mhcccc_gtttc_cd)
(type_Package ?mhcccc_cdd_p) (type_City ?mhcccc_gtttc_cd) (type_City ?mhcccc_gtttc_co) (type_Not_TCenter ?mhcccc_gtttc_ld) (type_Not_TCenter ?mhcccc_gtttc_lo) (type_TCenter ?mhcccc_gtttc_t1) (type_TCenter ?mhcccc_gtttc_t2)
)
((carry_direct ?mhcccc_cdd_p ?mhcccc_gtttc_lo ?mhcccc_gtttc_t1) (!go_through_two_tcenters_cities_ottd ?mhcccc_gtttc_lo ?mhcccc_gtttc_ld ?mhcccc_gtttc_co ?mhcccc_gtttc_cd ?mhcccc_gtttc_t1 ?mhcccc_gtttc_t2) (carry_between_tcenters ?mhcccc_cdd_p ?mhcccc_gtttc_t1 ?mhcccc_gtttc_t2) (carry_direct ?mhcccc_cdd_p ?mhcccc_gtttc_t2 ?mhcccc_gtttc_ld))
)
(:method (helper_carry_tt ?mhch_tch_p ?mhch_gtttctt_to ?mhch_gtttctt_co ?mhch_gtttctt_td ?mhch_gtttctt_cd)
method_helper_carry_cvh
(
(type_Package ?mhch_tch_p) (type_TCenter ?mhch_gtttctt_to) (type_City ?mhch_gtttctt_co) (type_TCenter ?mhch_gtttctt_td) (type_City ?mhch_gtttctt_cd)
(type_City ?mhch_gtttctt_cd) (type_City ?mhch_gtttctt_co) (type_TCenter ?mhch_gtttctt_td) (type_TCenter ?mhch_gtttctt_to) (type_Package ?mhch_tch_p)
)
((carry_via_hub ?mhch_tch_p ?mhch_gtttctt_to ?mhch_gtttctt_td) (!go_through_two_tcenters_tt ?mhch_gtttctt_to ?mhch_gtttctt_td ?mhch_gtttctt_co ?mhch_gtttctt_cd))
)
(:method (helper_carry_via_hub_hazardous ?mhcvhh_cd2_p ?mhcvhh_gtttcvhh_to ?mhcvhh_gtttcvhh_co ?mhcvhh_gtttcvhh_ro ?mhcvhh_gtttcvhh_h ?mhcvhh_gtttcvhh_ch ?mhcvhh_gtttcvhh_td ?mhcvhh_gtttcvhh_cd ?mhcvhh_gtttcvhh_rd)
method_helper_carry_via_hub_hazardous
(
(type_Package ?mhcvhh_cd2_p) (type_TCenter ?mhcvhh_gtttcvhh_to) (type_City ?mhcvhh_gtttcvhh_co) (type_Region ?mhcvhh_gtttcvhh_ro) (type_Hub ?mhcvhh_gtttcvhh_h) (type_City ?mhcvhh_gtttcvhh_ch) (type_TCenter ?mhcvhh_gtttcvhh_td) (type_City ?mhcvhh_gtttcvhh_cd) (type_Region ?mhcvhh_gtttcvhh_rd)
(type_Package ?mhcvhh_cd2_p) (type_City ?mhcvhh_gtttcvhh_cd) (type_City ?mhcvhh_gtttcvhh_ch) (type_City ?mhcvhh_gtttcvhh_co) (type_Hub ?mhcvhh_gtttcvhh_h) (type_Region ?mhcvhh_gtttcvhh_rd) (type_Region ?mhcvhh_gtttcvhh_ro) (type_TCenter ?mhcvhh_gtttcvhh_td) (type_TCenter ?mhcvhh_gtttcvhh_to)
)
((carry_direct ?mhcvhh_cd2_p ?mhcvhh_gtttcvhh_to ?mhcvhh_gtttcvhh_h) (!go_through_two_tcenters_via_hub_hazardous ?mhcvhh_gtttcvhh_to ?mhcvhh_gtttcvhh_td ?mhcvhh_gtttcvhh_h ?mhcvhh_gtttcvhh_co ?mhcvhh_gtttcvhh_ch ?mhcvhh_gtttcvhh_cd ?mhcvhh_gtttcvhh_ro ?mhcvhh_gtttcvhh_rd) (carry_direct ?mhcvhh_cd2_p ?mhcvhh_gtttcvhh_h ?mhcvhh_gtttcvhh_td))
)
(:method (helper_carry_via_hub_not_hazardous ?mhcvhn_cd2_p ?mhcvhn_gtttcvhnh_to ?mhcvhn_gtttcvhnh_co ?mhcvhn_gtttcvhnh_ro ?mhcvhn_gtttcvhnh_h ?mhcvhn_gtttcvhnh_td ?mhcvhn_gtttcvhnh_cd ?mhcvhn_gtttcvhnh_rd)
method_helper_carry_via_hub_not_hazardous
(
(type_Package ?mhcvhn_cd2_p) (type_TCenter ?mhcvhn_gtttcvhnh_to) (type_City ?mhcvhn_gtttcvhnh_co) (type_Region ?mhcvhn_gtttcvhnh_ro) (type_Hub ?mhcvhn_gtttcvhnh_h) (type_TCenter ?mhcvhn_gtttcvhnh_td) (type_City ?mhcvhn_gtttcvhnh_cd) (type_Region ?mhcvhn_gtttcvhnh_rd)
(type_Package ?mhcvhn_cd2_p) (type_City ?mhcvhn_gtttcvhnh_cd) (type_City ?mhcvhn_gtttcvhnh_co) (type_Hub ?mhcvhn_gtttcvhnh_h) (type_Region ?mhcvhn_gtttcvhnh_rd) (type_Region ?mhcvhn_gtttcvhnh_ro) (type_TCenter ?mhcvhn_gtttcvhnh_td) (type_TCenter ?mhcvhn_gtttcvhnh_to)
)
((carry_direct ?mhcvhn_cd2_p ?mhcvhn_gtttcvhnh_to ?mhcvhn_gtttcvhnh_h) (!go_through_two_tcenters_via_hub_not_hazardous ?mhcvhn_gtttcvhnh_to ?mhcvhn_gtttcvhnh_td ?mhcvhn_gtttcvhnh_co ?mhcvhn_gtttcvhnh_cd ?mhcvhn_gtttcvhnh_ro ?mhcvhn_gtttcvhnh_rd ?mhcvhn_gtttcvhnh_h) (carry_direct ?mhcvhn_cd2_p ?mhcvhn_gtttcvhnh_h ?mhcvhn_gtttcvhnh_td))
)
(:method (helper_move_traincar ?mhmt_dtc_tc ?mhmt_dtc_t ?mhmt_md_lo ?mhmt_dtc_l)
method_helper_move_traincar
(
(type_Traincar ?mhmt_dtc_tc) (type_Train ?mhmt_dtc_t) (type_Location ?mhmt_md_lo) (type_Location ?mhmt_dtc_l)
(type_Location ?mhmt_dtc_l) (type_Train ?mhmt_dtc_t) (type_Traincar ?mhmt_dtc_tc) (type_Location ?mhmt_md_lo) (type_Location ?mhmt_mo_lo)
)
((move ?mhmt_dtc_t ?mhmt_mo_lo ?mhmt_md_lo) (!attach_train_car ?mhmt_dtc_t ?mhmt_dtc_tc ?mhmt_md_lo) (move ?mhmt_dtc_t ?mhmt_md_lo ?mhmt_dtc_l) (!detach_train_car ?mhmt_dtc_t ?mhmt_dtc_tc ?mhmt_dtc_l))
)
(:method (helper_move_traincar ?mhmtn_dtc_tc ?mhmtn_dtc_t ?mhmtn_md_lo ?mhmtn_dtc_l)
method_helper_move_traincar_noMoveFirst
(
(type_Traincar ?mhmtn_dtc_tc) (type_Train ?mhmtn_dtc_t) (type_Location ?mhmtn_md_lo) (type_Location ?mhmtn_dtc_l)
(type_Location ?mhmtn_dtc_l) (type_Train ?mhmtn_dtc_t) (type_Traincar ?mhmtn_dtc_tc) (type_Location ?mhmtn_md_lo)
)
((!attach_train_car ?mhmtn_dtc_t ?mhmtn_dtc_tc ?mhmtn_md_lo) (move ?mhmtn_dtc_t ?mhmtn_md_lo ?mhmtn_dtc_l) (!detach_train_car ?mhmtn_dtc_t ?mhmtn_dtc_tc ?mhmtn_dtc_l))
)
(:method (load ?mlr_lp_p ?mlr_cd_rv ?mlr_lp_l)
method_load_regular
(
(type_Package ?mlr_lp_p) (type_Vehicle ?mlr_cd_rv) (type_Location ?mlr_lp_l)
(type_Regular_Vehicle ?mlr_cd_rv) (type_Location ?mlr_lp_l) (type_Package ?mlr_lp_p)
)
((!open_door ?mlr_cd_rv) (!load_package ?mlr_lp_p ?mlr_cd_rv ?mlr_lp_l) (!close_door ?mlr_cd_rv))
)
(:method (load ?mlf_pdpv_p ?mlf_pdpv_fv ?mlf_pdpv_l)
method_load_flatbed
(
(type_Package ?mlf_pdpv_p) (type_Vehicle ?mlf_pdpv_fv) (type_Location ?mlf_pdpv_l)
(type_Crane ?mlf_pdpv_c) (type_Flatbed_Vehicle ?mlf_pdpv_fv) (type_Location ?mlf_pdpv_l) (type_Package ?mlf_pdpv_p)
)
((!pick_up_package_ground ?mlf_pdpv_p ?mlf_pdpv_c ?mlf_pdpv_l) (!put_down_package_vehicle ?mlf_pdpv_p ?mlf_pdpv_c ?mlf_pdpv_fv ?mlf_pdpv_l))
)
(:method (load ?mlh_fh_p ?mlh_dc_h ?mlh_fh_l)
method_load_hopper
(
(type_Package ?mlh_fh_p) (type_Vehicle ?mlh_dc_h) (type_Location ?mlh_fh_l)
(type_Hopper_Vehicle ?mlh_dc_h) (type_Location ?mlh_fh_l) (type_Package ?mlh_fh_p)
)
((!connect_chute ?mlh_dc_h) (!fill_hopper ?mlh_fh_p ?mlh_dc_h ?mlh_fh_l) (!disconnect_chute ?mlh_dc_h))
)
(:method (load ?mlt_dch_l ?mlt_dch_tv ?mlt_ft_lo)
method_load_tanker
(
(type_Package ?mlt_dch_l) (type_Vehicle ?mlt_dch_tv) (type_Location ?mlt_ft_lo)
(type_Liquid ?mlt_dch_l) (type_Tanker_Vehicle ?mlt_dch_tv) (type_Location ?mlt_ft_lo)
)
((!connect_hose ?mlt_dch_tv ?mlt_dch_l) (!open_valve ?mlt_dch_tv) (!fill_tank ?mlt_dch_tv ?mlt_dch_l ?mlt_ft_lo) (!close_valve ?mlt_dch_tv) (!disconnect_hose ?mlt_dch_tv ?mlt_dch_l))
)
(:method (load ?mll_ll_p ?mll_rr_v ?mll_ll_l)
method_load_livestock
(
(type_Package ?mll_ll_p) (type_Vehicle ?mll_rr_v) (type_Location ?mll_ll_l)
(type_Location ?mll_ll_l) (type_Livestock_Package ?mll_ll_p) (type_Vehicle ?mll_rr_v)
)
((!lower_ramp ?mll_rr_v) (!fill_trough ?mll_rr_v) (!load_livestock ?mll_ll_p ?mll_rr_v ?mll_ll_l) (!raise_ramp ?mll_rr_v))
)
(:method (load ?mlc_lc_c ?mlc_rr_v ?mlc_lc_l)
method_load_cars
(
(type_Package ?mlc_lc_c) (type_Vehicle ?mlc_rr_v) (type_Location ?mlc_lc_l)
(type_Cars ?mlc_lc_c) (type_Location ?mlc_lc_l) (type_Vehicle ?mlc_rr_v)
)
((!lower_ramp ?mlc_rr_v) (!load_cars ?mlc_lc_c ?mlc_rr_v ?mlc_lc_l) (!raise_ramp ?mlc_rr_v))
)
(:method (load ?mla_lp_p ?mla_dcr_ap ?mla_dcr_l)
method_load_airplane
(
(type_Package ?mla_lp_p) (type_Vehicle ?mla_dcr_ap) (type_Location ?mla_dcr_l)
(type_Airplane ?mla_dcr_ap) (type_Location ?mla_dcr_l) (type_Plane_Ramp ?mla_dcr_pr) (type_Package ?mla_lp_p)
)
((!attach_conveyor_ramp ?mla_dcr_ap ?mla_dcr_pr ?mla_dcr_l) (!open_door ?mla_dcr_ap) (!load_package ?mla_lp_p ?mla_dcr_ap ?mla_dcr_l) (!close_door ?mla_dcr_ap) (!detach_conveyor_ramp ?mla_dcr_ap ?mla_dcr_pr ?mla_dcr_l))
)
(:method (load_top ?mlmn_l_p ?mlmn_l_v ?mlmn_l_l)
method_load_top_normal
(
(type_Package ?mlmn_l_p) (type_Vehicle ?mlmn_l_v) (type_Location ?mlmn_l_l)
(type_Location ?mlmn_l_l) (type_Package ?mlmn_l_p) (type_Vehicle ?mlmn_l_v)
)
((load ?mlmn_l_p ?mlmn_l_v ?mlmn_l_l))
)
(:method (load_top ?mlmh_l_p ?mlmh_l_v ?mlmh_l_l)
method_load_top_hazardous
(
(type_Package ?mlmh_l_p) (type_Vehicle ?mlmh_l_v) (type_Location ?mlmh_l_l)
(type_Location ?mlmh_l_l) (type_Package ?mlmh_l_p) (type_Vehicle ?mlmh_l_v)
)
((!affix_warning_signs ?mlmh_l_v) (load ?mlmh_l_p ?mlmh_l_v ?mlmh_l_l))
)
(:method (load_top ?mlmv_l_p ?mlmv_pci_a ?mlmv_l_l)
method_load_top_valuable
(
(type_Package ?mlmv_l_p) (type_Vehicle ?mlmv_pci_a) (type_Location ?mlmv_l_l)
(type_Location ?mlmv_l_l) (type_Package ?mlmv_l_p) (type_Armored ?mlmv_pci_a)
)
((!post_guard_outside ?mlmv_pci_a) (load ?mlmv_l_p ?mlmv_pci_a ?mlmv_l_l) (!post_guard_inside ?mlmv_pci_a))
)
(:method (move ?mmnt_mvnt_v ?mmnt_mvnt_o ?mmnt_mvnt_d)
method_move_no_traincar
(
(type_Vehicle ?mmnt_mvnt_v) (type_Location ?mmnt_mvnt_o) (type_Location ?mmnt_mvnt_d)
(type_Location ?mmnt_mvnt_d) (type_Location ?mmnt_mvnt_o) (type_Route ?mmnt_mvnt_r) (type_Vehicle ?mmnt_mvnt_v)
)
((!move_vehicle_no_traincar ?mmnt_mvnt_v ?mmnt_mvnt_o ?mmnt_mvnt_r ?mmnt_mvnt_d))
)
(:method (move ?mmt_hmt_v ?mmt_hmt_o ?mmt_hmt_d)
method_move_traincar
(
(type_Vehicle ?mmt_hmt_v) (type_Location ?mmt_hmt_o) (type_Location ?mmt_hmt_d)
(type_Location ?mmt_hmt_d) (type_Location ?mmt_hmt_o) (type_Train ?mmt_hmt_t) (type_Traincar ?mmt_hmt_v)
)
((helper_move_traincar ?mmt_hmt_v ?mmt_hmt_t ?mmt_hmt_o ?mmt_hmt_d))
)
(:method (pickup ?mpn_cf_p)
method_pickup_normal
(
(type_Package ?mpn_cf_p)
(type_Package ?mpn_cf_p)
)
((!collect_fees ?mpn_cf_p))
)
(:method (pickup ?mph_op_h)
method_pickup_hazardous
(
(type_Package ?mph_op_h)
(type_Hazardous ?mph_op_h)
)
((!collect_fees ?mph_op_h) (!obtain_permit ?mph_op_h))
)
(:method (pickup ?mpv_ci_v)
method_pickup_valuable
(
(type_Package ?mpv_ci_v)
(type_Valuable ?mpv_ci_v)
)
((!collect_fees ?mpv_ci_v) (!collect_insurance ?mpv_ci_v))
)
(:method (transport ?mtpcd_de_p ?mtpcd_ca_lo ?mtpcd_ca_ld)
method_transport_pi_ca_de
(
(type_Package ?mtpcd_de_p) (type_Location ?mtpcd_ca_lo) (type_Location ?mtpcd_ca_ld)
(type_Location ?mtpcd_ca_ld) (type_Location ?mtpcd_ca_lo) (type_Package ?mtpcd_de_p)
)
((pickup ?mtpcd_de_p) (carry ?mtpcd_de_p ?mtpcd_ca_lo ?mtpcd_ca_ld) (deliver ?mtpcd_de_p))
)
(:method (unload ?mur_up_p ?mur_cd_rv ?mur_up_l)
method_unload_regular
(
(type_Package ?mur_up_p) (type_Vehicle ?mur_cd_rv) (type_Location ?mur_up_l)
(type_Regular_Vehicle ?mur_cd_rv) (type_Location ?mur_up_l) (type_Package ?mur_up_p)
)
((!open_door ?mur_cd_rv) (!unload_package ?mur_up_p ?mur_cd_rv ?mur_up_l) (!close_door ?mur_cd_rv))
)
(:method (unload ?muf_pdpg_p ?muf_pupv_fv ?muf_pdpg_l)
method_unload_flatbed
(
(type_Package ?muf_pdpg_p) (type_Vehicle ?muf_pupv_fv) (type_Location ?muf_pdpg_l)
(type_Crane ?muf_pdpg_c) (type_Location ?muf_pdpg_l) (type_Package ?muf_pdpg_p) (type_Flatbed_Vehicle ?muf_pupv_fv)
)
((!pick_up_package_vehicle ?muf_pdpg_p ?muf_pdpg_c ?muf_pupv_fv ?muf_pdpg_l) (!put_down_package_ground ?muf_pdpg_p ?muf_pdpg_c ?muf_pdpg_l))
)
(:method (unload ?muh_eh_p ?muh_dc_h ?muh_eh_l)
method_unload_hopper
(
(type_Package ?muh_eh_p) (type_Vehicle ?muh_dc_h) (type_Location ?muh_eh_l)
(type_Hopper_Vehicle ?muh_dc_h) (type_Location ?muh_eh_l) (type_Package ?muh_eh_p)
)
((!connect_chute ?muh_dc_h) (!empty_hopper ?muh_eh_p ?muh_dc_h ?muh_eh_l) (!disconnect_chute ?muh_dc_h))
)
(:method (unload ?mut_dch_l ?mut_dch_tv ?mut_et_lo)
method_unload_tanker
(
(type_Package ?mut_dch_l) (type_Vehicle ?mut_dch_tv) (type_Location ?mut_et_lo)
(type_Liquid ?mut_dch_l) (type_Tanker_Vehicle ?mut_dch_tv) (type_Location ?mut_et_lo)
)
((!connect_hose ?mut_dch_tv ?mut_dch_l) (!open_valve ?mut_dch_tv) (!empty_tank ?mut_dch_tv ?mut_dch_l ?mut_et_lo) (!close_valve ?mut_dch_tv) (!disconnect_hose ?mut_dch_tv ?mut_dch_l))
)
(:method (unload ?mul_ull_p ?mul_rr_v ?mul_ull_l)
method_unload_livestock
(
(type_Package ?mul_ull_p) (type_Vehicle ?mul_rr_v) (type_Location ?mul_ull_l)
(type_Vehicle ?mul_rr_v) (type_Location ?mul_ull_l) (type_Livestock_Package ?mul_ull_p)
)
((!lower_ramp ?mul_rr_v) (!unload_livestock ?mul_ull_p ?mul_rr_v ?mul_ull_l) (!do_clean_interior ?mul_rr_v) (!raise_ramp ?mul_rr_v))
)
(:method (unload ?muc_uc_c ?muc_rr_v ?muc_uc_l)
method_unload_cars
(
(type_Package ?muc_uc_c) (type_Vehicle ?muc_rr_v) (type_Location ?muc_uc_l)
(type_Vehicle ?muc_rr_v) (type_Cars ?muc_uc_c) (type_Location ?muc_uc_l)
)
((!lower_ramp ?muc_rr_v) (!unload_cars ?muc_uc_c ?muc_rr_v ?muc_uc_l) (!raise_ramp ?muc_rr_v))
)
(:method (unload ?mua_up_p ?mua_dcr_ap ?mua_dcr_l)
method_unload_airplane
(
(type_Package ?mua_up_p) (type_Vehicle ?mua_dcr_ap) (type_Location ?mua_dcr_l)
(type_Airplane ?mua_dcr_ap) (type_Location ?mua_dcr_l) (type_Plane_Ramp ?mua_dcr_pr) (type_Package ?mua_up_p)
)
((!attach_conveyor_ramp ?mua_dcr_ap ?mua_dcr_pr ?mua_dcr_l) (!open_door ?mua_dcr_ap) (!unload_package ?mua_up_p ?mua_dcr_ap ?mua_dcr_l) (!close_door ?mua_dcr_ap) (!detach_conveyor_ramp ?mua_dcr_ap ?mua_dcr_pr ?mua_dcr_l))
)
(:method (unload_top ?mumn_ul_p ?mumn_ul_v ?mumn_ul_l)
method_unload_top_normal
(
(type_Package ?mumn_ul_p) (type_Vehicle ?mumn_ul_v) (type_Location ?mumn_ul_l)
(type_Location ?mumn_ul_l) (type_Package ?mumn_ul_p) (type_Vehicle ?mumn_ul_v)
)
((unload ?mumn_ul_p ?mumn_ul_v ?mumn_ul_l))
)
(:method (unload_top ?mumh_ul_p ?mumh_ul_v ?mumh_ul_l)
method_unload_top_hazardous
(
(type_Package ?mumh_ul_p) (type_Vehicle ?mumh_ul_v) (type_Location ?mumh_ul_l)
(type_Location ?mumh_ul_l) (type_Package ?mumh_ul_p) (type_Vehicle ?mumh_ul_v)
)
((unload ?mumh_ul_p ?mumh_ul_v ?mumh_ul_l) (!decontaminate_interior ?mumh_ul_v) (!remove_warning_signs ?mumh_ul_v))
)
(:method (unload_top ?mumv_ul_p ?mumv_ul_v ?mumv_ul_l)
method_unload_top_valuable
(
(type_Package ?mumv_ul_p) (type_Vehicle ?mumv_ul_v) (type_Location ?mumv_ul_l)
(type_Location ?mumv_ul_l) (type_Package ?mumv_ul_p) (type_Vehicle ?mumv_ul_v)
)
((!post_guard_outside ?mumv_ul_v) (unload ?mumv_ul_p ?mumv_ul_v ?mumv_ul_l) (!remove_guard ?mumv_ul_v))
)
))
| null | https://raw.githubusercontent.com/panda-planner-dev/ipc2020-domains/9adb54325d3df35907adc7115fcc65f0ce5953cc/partial-order/UM-Translog/other/SHOP2/d-17.lisp | lisp | preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects | (defdomain domain (
(:operator (!obtain_permit ?op_h)
(
(type_Hazardous ?op_h)
(not (Have_Permit ?op_h))
)
()
((Have_Permit ?op_h))
)
(:operator (!collect_fees ?cf_p)
(
(type_Package ?cf_p)
(not (Fees_Collected ?cf_p))
)
()
((Fees_Collected ?cf_p))
)
(:operator (!collect_insurance ?ci_v)
(
(type_Valuable ?ci_v)
(not (Insured ?ci_v))
)
()
((Insured ?ci_v))
)
(:operator (!go_through_tcenter_cc ?gttc_lo ?gttc_ld ?gttc_co ?gttc_cd ?gttc_tc)
(
(type_Not_TCenter ?gttc_lo) (type_Not_TCenter ?gttc_ld) (type_City ?gttc_co) (type_City ?gttc_cd) (type_TCenter ?gttc_tc)
(In_City ?gttc_lo ?gttc_co) (In_City ?gttc_ld ?gttc_cd) (Serves ?gttc_tc ?gttc_co) (Serves ?gttc_tc ?gttc_cd) (Available ?gttc_tc)
)
()
()
)
(:operator (!go_through_two_tcenters_cities_ottd ?gtttcc_lo ?gtttcc_ld ?gtttcc_co ?gtttcc_cd ?gtttcc_t1 ?gtttcc_t2)
(
(type_Not_TCenter ?gtttcc_lo) (type_Not_TCenter ?gtttcc_ld) (type_City ?gtttcc_co) (type_City ?gtttcc_cd) (type_TCenter ?gtttcc_t1) (type_TCenter ?gtttcc_t2)
(In_City ?gtttcc_lo ?gtttcc_co) (In_City ?gtttcc_ld ?gtttcc_cd) (Serves ?gtttcc_t1 ?gtttcc_co) (Serves ?gtttcc_t2 ?gtttcc_cd)
)
()
()
)
(:operator (!go_through_two_tcenters_cities_otd ?gtttccotd_ld ?gtttccotd_co ?gtttccotd_cd ?gtttccotd_to ?gtttccotd_t1)
(
(type_Not_TCenter ?gtttccotd_ld) (type_City ?gtttccotd_co) (type_City ?gtttccotd_cd) (type_TCenter ?gtttccotd_to) (type_TCenter ?gtttccotd_t1)
(In_City ?gtttccotd_to ?gtttccotd_co) (In_City ?gtttccotd_ld ?gtttccotd_cd) (Serves ?gtttccotd_t1 ?gtttccotd_cd)
)
()
()
)
(:operator (!go_through_two_tcenters_cities_ott ?gtttccott_ld ?gtttccott_co ?gtttccott_cd ?gtttccott_to ?gtttccott_td)
(
(type_City_Location ?gtttccott_ld) (type_City ?gtttccott_co) (type_City ?gtttccott_cd) (type_TCenter ?gtttccott_to) (type_TCenter ?gtttccott_td)
(In_City ?gtttccott_ld ?gtttccott_co) (In_City ?gtttccott_td ?gtttccott_cd) (Serves ?gtttccott_to ?gtttccott_co)
)
()
()
)
(:operator (!go_through_two_tcenters ?gtttc_to ?gtttc_td)
(
(type_TCenter ?gtttc_to) (type_TCenter ?gtttc_td)
(Available ?gtttc_to) (Available ?gtttc_td)
)
()
()
)
(:operator (!go_through_two_tcenters_tt ?gtttctt_to ?gtttctt_td ?gtttctt_co ?gtttctt_cd)
(
(type_TCenter ?gtttctt_to) (type_TCenter ?gtttctt_td) (type_City ?gtttctt_co) (type_City ?gtttctt_cd)
(In_City ?gtttctt_to ?gtttctt_co) (In_City ?gtttctt_td ?gtttctt_cd)
)
()
()
)
(:operator (!go_through_two_tcenters_via_hub_hazardous ?gtttcvhh_to ?gtttcvhh_td ?gtttcvhh_h ?gtttcvhh_co ?gtttcvhh_ch ?gtttcvhh_cd ?gtttcvhh_ro ?gtttcvhh_rd)
(
(type_TCenter ?gtttcvhh_to) (type_TCenter ?gtttcvhh_td) (type_Hub ?gtttcvhh_h) (type_City ?gtttcvhh_co) (type_City ?gtttcvhh_ch) (type_City ?gtttcvhh_cd) (type_Region ?gtttcvhh_ro) (type_Region ?gtttcvhh_rd)
(Available ?gtttcvhh_to) (Available ?gtttcvhh_td) (In_City ?gtttcvhh_h ?gtttcvhh_ch) (City_Hazardous_Compatible ?gtttcvhh_ch) (In_City ?gtttcvhh_to ?gtttcvhh_co) (In_City ?gtttcvhh_td ?gtttcvhh_cd) (In_Region ?gtttcvhh_co ?gtttcvhh_ro) (In_Region ?gtttcvhh_cd ?gtttcvhh_rd) (Serves ?gtttcvhh_h ?gtttcvhh_ro) (Serves ?gtttcvhh_h ?gtttcvhh_rd) (Available ?gtttcvhh_h)
)
()
()
)
(:operator (!go_through_two_tcenters_via_hub_not_hazardous ?gtttcvhnh_to ?gtttcvhnh_td ?gtttcvhnh_co ?gtttcvhnh_cd ?gtttcvhnh_ro ?gtttcvhnh_rd ?gtttcvhnh_h)
(
(type_TCenter ?gtttcvhnh_to) (type_TCenter ?gtttcvhnh_td) (type_City ?gtttcvhnh_co) (type_City ?gtttcvhnh_cd) (type_Region ?gtttcvhnh_ro) (type_Region ?gtttcvhnh_rd) (type_Hub ?gtttcvhnh_h)
(Available ?gtttcvhnh_to) (Available ?gtttcvhnh_td) (In_City ?gtttcvhnh_to ?gtttcvhnh_co) (In_City ?gtttcvhnh_td ?gtttcvhnh_cd) (In_Region ?gtttcvhnh_co ?gtttcvhnh_ro) (In_Region ?gtttcvhnh_cd ?gtttcvhnh_rd) (Serves ?gtttcvhnh_h ?gtttcvhnh_ro) (Serves ?gtttcvhnh_h ?gtttcvhnh_rd) (Available ?gtttcvhnh_h)
)
()
()
)
(:operator (!deliver_p ?dp_p)
(
(type_Package ?dp_p)
(Fees_Collected ?dp_p)
)
((Fees_Collected ?dp_p))
((Delivered ?dp_p))
)
(:operator (!deliver_h ?dh_h)
(
(type_Hazardous ?dh_h)
(Fees_Collected ?dh_h) (Have_Permit ?dh_h)
)
((Have_Permit ?dh_h) (Fees_Collected ?dh_h))
((Delivered ?dh_h))
)
(:operator (!deliver_v ?dv_v)
(
(type_Valuable ?dv_v)
(Fees_Collected ?dv_v) (Insured ?dv_v)
)
((Fees_Collected ?dv_v) (Insured ?dv_v))
((Delivered ?dv_v))
)
(:operator (!post_guard_outside ?pco_a)
(
(type_Armored ?pco_a)
)
((Guard_Inside ?pco_a))
((Guard_Outside ?pco_a))
)
(:operator (!post_guard_inside ?pci_a)
(
(type_Armored ?pci_a)
)
((Guard_Outside ?pci_a))
((Guard_Inside ?pci_a))
)
(:operator (!remove_guard ?mc_a)
(
(type_Armored ?mc_a)
)
((Guard_Outside ?mc_a) (Guard_Inside ?mc_a))
()
)
(:operator (!decontaminate_interior ?di_v)
(
(type_Vehicle ?di_v)
)
()
((Decontaminated_Interior ?di_v))
)
(:operator (!affix_warning_signs ?fws_v)
(
(type_Vehicle ?fws_v)
(not (Warning_Signs_Affixed ?fws_v))
)
()
((Warning_Signs_Affixed ?fws_v))
)
(:operator (!remove_warning_signs ?mws_v)
(
(type_Vehicle ?mws_v)
(Warning_Signs_Affixed ?mws_v)
)
((Warning_Signs_Affixed ?mws_v))
()
)
(:operator (!attach_train_car ?atc_t ?atc_tc ?atc_l)
(
(type_Train ?atc_t) (type_Traincar ?atc_tc) (type_Location ?atc_l)
(At_Vehicle ?atc_tc ?atc_l) (At_Vehicle ?atc_t ?atc_l) (not (Connected_To ?atc_tc ?atc_t))
)
((At_Vehicle ?atc_tc ?atc_l))
((Connected_To ?atc_tc ?atc_t))
)
(:operator (!detach_train_car ?dtc_t ?dtc_tc ?dtc_l)
(
(type_Train ?dtc_t) (type_Traincar ?dtc_tc) (type_Location ?dtc_l)
(At_Vehicle ?dtc_t ?dtc_l) (Connected_To ?dtc_tc ?dtc_t)
)
((Connected_To ?dtc_tc ?dtc_t))
((At_Vehicle ?dtc_tc ?dtc_l))
)
(:operator (!connect_hose ?ch_tv ?ch_l)
(
(type_Tanker_Vehicle ?ch_tv) (type_Liquid ?ch_l)
(not (Hose_Connected ?ch_tv ?ch_l))
)
()
((Hose_Connected ?ch_tv ?ch_l))
)
(:operator (!disconnect_hose ?dch_tv ?dch_l)
(
(type_Tanker_Vehicle ?dch_tv) (type_Liquid ?dch_l)
(Hose_Connected ?dch_tv ?dch_l)
)
((Hose_Connected ?dch_tv ?dch_l))
()
)
(:operator (!open_valve ?ov_tv)
(
(type_Tanker_Vehicle ?ov_tv)
(not (Valve_Open ?ov_tv))
)
()
((Valve_Open ?ov_tv))
)
(:operator (!close_valve ?cv_tv)
(
(type_Tanker_Vehicle ?cv_tv)
(Valve_Open ?cv_tv)
)
((Valve_Open ?cv_tv))
()
)
(:operator (!fill_tank ?ft_tv ?ft_li ?ft_lo)
(
(type_Tanker_Vehicle ?ft_tv) (type_Liquid ?ft_li) (type_Location ?ft_lo)
(Hose_Connected ?ft_tv ?ft_li) (Valve_Open ?ft_tv) (At_Package ?ft_li ?ft_lo) (At_Vehicle ?ft_tv ?ft_lo) (PV_Compatible ?ft_li ?ft_tv)
)
((At_Package ?ft_li ?ft_lo))
((At_Package ?ft_li ?ft_tv))
)
(:operator (!empty_tank ?et_tv ?et_li ?et_lo)
(
(type_Tanker_Vehicle ?et_tv) (type_Liquid ?et_li) (type_Location ?et_lo)
(Hose_Connected ?et_tv ?et_li) (Valve_Open ?et_tv) (At_Package ?et_li ?et_tv) (At_Vehicle ?et_tv ?et_lo)
)
((At_Package ?et_li ?et_tv))
((At_Package ?et_li ?et_lo))
)
(:operator (!load_cars ?lc_c ?lc_v ?lc_l)
(
(type_Cars ?lc_c) (type_Auto_Vehicle ?lc_v) (type_Location ?lc_l)
(At_Package ?lc_c ?lc_l) (At_Vehicle ?lc_v ?lc_l) (Ramp_Down ?lc_v) (PV_Compatible ?lc_c ?lc_v)
)
((At_Package ?lc_c ?lc_l))
((At_Package ?lc_c ?lc_v))
)
(:operator (!unload_cars ?uc_c ?uc_v ?uc_l)
(
(type_Cars ?uc_c) (type_Auto_Vehicle ?uc_v) (type_Location ?uc_l)
(At_Package ?uc_c ?uc_v) (At_Vehicle ?uc_v ?uc_l) (Ramp_Down ?uc_v)
)
((At_Package ?uc_c ?uc_v))
((At_Package ?uc_c ?uc_l))
)
(:operator (!raise_ramp ?rr_v)
(
(type_Vehicle ?rr_v)
(Ramp_Down ?rr_v)
)
((Ramp_Down ?rr_v))
()
)
(:operator (!lower_ramp ?lr_v)
(
(type_Vehicle ?lr_v)
(not (Ramp_Down ?lr_v))
)
()
((Ramp_Down ?lr_v))
)
(:operator (!load_livestock ?ll_p ?ll_v ?ll_l)
(
(type_Livestock_Package ?ll_p) (type_Livestock_Vehicle ?ll_v) (type_Location ?ll_l)
(At_Package ?ll_p ?ll_l) (At_Vehicle ?ll_v ?ll_l) (Ramp_Down ?ll_v) (PV_Compatible ?ll_p ?ll_v)
)
((At_Package ?ll_p ?ll_l) (Clean_Interior ?ll_v))
((At_Package ?ll_p ?ll_v))
)
(:operator (!unload_livestock ?ull_p ?ull_v ?ull_l)
(
(type_Livestock_Package ?ull_p) (type_Livestock_Vehicle ?ull_v) (type_Location ?ull_l)
(At_Package ?ull_p ?ull_v) (At_Vehicle ?ull_v ?ull_l) (Ramp_Down ?ull_v)
)
((At_Package ?ull_p ?ull_v) (Trough_Full ?ull_v))
((At_Package ?ull_p ?ull_l))
)
(:operator (!fill_trough ?ftr_v)
(
(type_Livestock_Vehicle ?ftr_v)
)
()
((Trough_Full ?ftr_v))
)
(:operator (!do_clean_interior ?cli_v)
(
(type_Vehicle ?cli_v)
)
()
((Clean_Interior ?cli_v))
)
(:operator (!attach_conveyor_ramp ?acr_ap ?acr_pr ?acr_l)
(
(type_Airplane ?acr_ap) (type_Plane_Ramp ?acr_pr) (type_Location ?acr_l)
(Available ?acr_pr) (At_Equipment ?acr_pr ?acr_l) (At_Vehicle ?acr_ap ?acr_l)
)
((Available ?acr_pr))
((Ramp_Connected ?acr_pr ?acr_ap))
)
(:operator (!detach_conveyor_ramp ?dcr_ap ?dcr_pr ?dcr_l)
(
(type_Airplane ?dcr_ap) (type_Plane_Ramp ?dcr_pr) (type_Location ?dcr_l)
(Ramp_Connected ?dcr_pr ?dcr_ap) (At_Equipment ?dcr_pr ?dcr_l) (At_Vehicle ?dcr_ap ?dcr_l)
)
((Ramp_Connected ?dcr_pr ?dcr_ap))
((Available ?dcr_pr))
)
(:operator (!connect_chute ?cc_h)
(
(type_Hopper_Vehicle ?cc_h)
(not (Chute_Connected ?cc_h))
)
()
((Chute_Connected ?cc_h))
)
(:operator (!disconnect_chute ?dc_h)
(
(type_Hopper_Vehicle ?dc_h)
(Chute_Connected ?dc_h)
)
((Chute_Connected ?dc_h))
()
)
(:operator (!fill_hopper ?fh_p ?fh_hv ?fh_l)
(
(type_Package ?fh_p) (type_Hopper_Vehicle ?fh_hv) (type_Location ?fh_l)
(Chute_Connected ?fh_hv) (At_Vehicle ?fh_hv ?fh_l) (At_Package ?fh_p ?fh_l) (PV_Compatible ?fh_p ?fh_hv)
)
((At_Package ?fh_p ?fh_l))
((At_Package ?fh_p ?fh_hv))
)
(:operator (!empty_hopper ?eh_p ?eh_hv ?eh_l)
(
(type_Package ?eh_p) (type_Hopper_Vehicle ?eh_hv) (type_Location ?eh_l)
(Chute_Connected ?eh_hv) (At_Vehicle ?eh_hv ?eh_l) (At_Package ?eh_p ?eh_hv)
)
((At_Package ?eh_p ?eh_hv))
((At_Package ?eh_p ?eh_l))
)
(:operator (!pick_up_package_ground ?pupg_p ?pupg_c ?pupg_l)
(
(type_Package ?pupg_p) (type_Crane ?pupg_c) (type_Location ?pupg_l)
(Empty ?pupg_c) (Available ?pupg_c) (At_Equipment ?pupg_c ?pupg_l) (At_Package ?pupg_p ?pupg_l)
)
((Empty ?pupg_c) (At_Package ?pupg_p ?pupg_l))
((At_Package ?pupg_p ?pupg_c))
)
(:operator (!put_down_package_ground ?pdpg_p ?pdpg_c ?pdpg_l)
(
(type_Package ?pdpg_p) (type_Crane ?pdpg_c) (type_Location ?pdpg_l)
(Available ?pdpg_c) (At_Equipment ?pdpg_c ?pdpg_l) (At_Package ?pdpg_p ?pdpg_c)
)
((At_Package ?pdpg_p ?pdpg_c))
((At_Package ?pdpg_p ?pdpg_l) (Empty ?pdpg_c))
)
(:operator (!pick_up_package_vehicle ?pupv_p ?pupv_c ?pupv_fv ?pupv_l)
(
(type_Package ?pupv_p) (type_Crane ?pupv_c) (type_Flatbed_Vehicle ?pupv_fv) (type_Location ?pupv_l)
(Empty ?pupv_c) (Available ?pupv_c) (At_Equipment ?pupv_c ?pupv_l) (At_Package ?pupv_p ?pupv_fv) (At_Vehicle ?pupv_fv ?pupv_l)
)
((Empty ?pupv_c) (At_Package ?pupv_p ?pupv_fv))
((At_Package ?pupv_p ?pupv_c))
)
(:operator (!put_down_package_vehicle ?pdpv_p ?pdpv_c ?pdpv_fv ?pdpv_l)
(
(type_Package ?pdpv_p) (type_Crane ?pdpv_c) (type_Flatbed_Vehicle ?pdpv_fv) (type_Location ?pdpv_l)
(Available ?pdpv_c) (At_Package ?pdpv_p ?pdpv_c) (At_Equipment ?pdpv_c ?pdpv_l) (At_Vehicle ?pdpv_fv ?pdpv_l) (PV_Compatible ?pdpv_p ?pdpv_fv)
)
((At_Package ?pdpv_p ?pdpv_c))
((Empty ?pdpv_c) (At_Package ?pdpv_p ?pdpv_fv))
)
(:operator (!open_door ?od_rv)
(
(type_Regular_Vehicle ?od_rv)
(not (Door_Open ?od_rv))
)
()
((Door_Open ?od_rv))
)
(:operator (!close_door ?cd_rv)
(
(type_Regular_Vehicle ?cd_rv)
(Door_Open ?cd_rv)
)
((Door_Open ?cd_rv))
()
)
(:operator (!load_package ?lp_p ?lp_v ?lp_l)
(
(type_Package ?lp_p) (type_Vehicle ?lp_v) (type_Location ?lp_l)
(At_Package ?lp_p ?lp_l) (At_Vehicle ?lp_v ?lp_l) (PV_Compatible ?lp_p ?lp_v)
)
((At_Package ?lp_p ?lp_l))
((At_Package ?lp_p ?lp_v))
)
(:operator (!unload_package ?up_p ?up_v ?up_l)
(
(type_Package ?up_p) (type_Vehicle ?up_v) (type_Location ?up_l)
(At_Package ?up_p ?up_v) (At_Vehicle ?up_v ?up_l)
)
((At_Package ?up_p ?up_v))
((At_Package ?up_p ?up_l))
)
(:operator (!move_vehicle_no_traincar ?hmnt_v ?hmnt_o ?hmnt_r ?hmnt_d)
(
(type_Vehicle ?hmnt_v) (type_Location ?hmnt_o) (type_Route ?hmnt_r) (type_Location ?hmnt_d)
(Connects ?hmnt_r ?hmnt_o ?hmnt_d) (Available ?hmnt_v) (Available ?hmnt_r) (RV_Compatible ?hmnt_r ?hmnt_v) (At_Vehicle ?hmnt_v ?hmnt_o)
)
((At_Vehicle ?hmnt_v ?hmnt_o))
((At_Vehicle ?hmnt_v ?hmnt_d))
)
(:method (__top)
__top_method
(
(type_sort_for_O27 ?var_for_O27_1) (type_sort_for_O28 ?var_for_O28_2) (type_sort_for_Toshiba_Laptops ?var_for_Toshiba_Laptops_3)
)
((transport ?var_for_Toshiba_Laptops_3 ?var_for_O27_1 ?var_for_O28_2))
)
(:method (carry ?mccd_cd_p ?mccd_cd_lo ?mccd_cd_ld)
method_carry_cd
(
(type_Package ?mccd_cd_p) (type_Location ?mccd_cd_lo) (type_Location ?mccd_cd_ld)
(type_Location ?mccd_cd_ld) (type_Location ?mccd_cd_lo) (type_Package ?mccd_cd_p)
)
((carry_direct ?mccd_cd_p ?mccd_cd_lo ?mccd_cd_ld))
)
(:method (carry ?mch_hctt_p ?mch_hctt_o ?mch_hctt_d)
method_carry_cvh
(
(type_Package ?mch_hctt_p) (type_Location ?mch_hctt_o) (type_Location ?mch_hctt_d)
(type_City ?mch_hctt_cd) (type_City ?mch_hctt_co) (type_TCenter ?mch_hctt_d) (type_TCenter ?mch_hctt_o) (type_Package ?mch_hctt_p)
)
((helper_carry_tt ?mch_hctt_p ?mch_hctt_o ?mch_hctt_co ?mch_hctt_d ?mch_hctt_cd))
)
(:method (carry ?mccct_hcott_p ?mccct_hcott_o ?mccct_hcott_d)
method_carry_cd_cbtc
(
(type_Package ?mccct_hcott_p) (type_Location ?mccct_hcott_o) (type_Location ?mccct_hcott_d)
(type_City ?mccct_hcott_cd) (type_City ?mccct_hcott_co) (type_TCenter ?mccct_hcott_d) (type_City_Location ?mccct_hcott_o) (type_Package ?mccct_hcott_p) (type_TCenter ?mccct_hcott_t1)
)
((helper_carry_ott ?mccct_hcott_p ?mccct_hcott_o ?mccct_hcott_co ?mccct_hcott_t1 ?mccct_hcott_d ?mccct_hcott_cd))
)
(:method (carry ?mcctc_hcotd_p ?mcctc_hcotd_o ?mcctc_hcotd_d)
method_carry_cbtc_cd
(
(type_Package ?mcctc_hcotd_p) (type_Location ?mcctc_hcotd_o) (type_Location ?mcctc_hcotd_d)
(type_City ?mcctc_hcotd_cd) (type_City ?mcctc_hcotd_co) (type_Not_TCenter ?mcctc_hcotd_d) (type_TCenter ?mcctc_hcotd_o) (type_Package ?mcctc_hcotd_p) (type_TCenter ?mcctc_hcotd_t1)
)
((helper_carry_otd ?mcctc_hcotd_p ?mcctc_hcotd_o ?mcctc_hcotd_co ?mcctc_hcotd_t1 ?mcctc_hcotd_d ?mcctc_hcotd_cd))
)
(:method (carry ?mcccc_hcottd_p ?mcccc_hcottd_o ?mcccc_hcottd_d)
method_carry_cd_cbtc_cd
(
(type_Package ?mcccc_hcottd_p) (type_Location ?mcccc_hcottd_o) (type_Location ?mcccc_hcottd_d)
(type_City ?mcccc_hcottd_cd) (type_City ?mcccc_hcottd_co) (type_Not_TCenter ?mcccc_hcottd_d) (type_Not_TCenter ?mcccc_hcottd_o) (type_Package ?mcccc_hcottd_p) (type_TCenter ?mcccc_hcottd_t1) (type_TCenter ?mcccc_hcottd_t2)
)
((helper_carry_ottd ?mcccc_hcottd_p ?mcccc_hcottd_o ?mcccc_hcottd_co ?mcccc_hcottd_t1 ?mcccc_hcottd_t2 ?mcccc_hcottd_d ?mcccc_hcottd_cd))
)
(:method (carry ?mccc_hccc_p ?mccc_hccc_o ?mccc_hccc_d)
method_carry_cd_cd
(
(type_Package ?mccc_hccc_p) (type_Location ?mccc_hccc_o) (type_Location ?mccc_hccc_d)
(type_City ?mccc_hccc_cd) (type_City ?mccc_hccc_co) (type_Not_TCenter ?mccc_hccc_d) (type_Not_TCenter ?mccc_hccc_o) (type_Package ?mccc_hccc_p) (type_TCenter ?mccc_hccc_t)
)
((helper_carry_cc ?mccc_hccc_p ?mccc_hccc_o ?mccc_hccc_co ?mccc_hccc_t ?mccc_hccc_d ?mccc_hccc_cd))
)
(:method (carry_between_tcenters ?mcbtc_cd_p ?mcbtc_gtttc_to ?mcbtc_gtttc_td)
method_carry_between_tcenters_cd
(
(type_Package ?mcbtc_cd_p) (type_TCenter ?mcbtc_gtttc_to) (type_TCenter ?mcbtc_gtttc_td)
(type_Package ?mcbtc_cd_p) (type_TCenter ?mcbtc_gtttc_td) (type_TCenter ?mcbtc_gtttc_to)
)
(:unordered (!go_through_two_tcenters ?mcbtc_gtttc_to ?mcbtc_gtttc_td) (carry_direct ?mcbtc_cd_p ?mcbtc_gtttc_to ?mcbtc_gtttc_td))
)
(:method (carry_between_tcenters ?mcbth_tch_p ?mcbth_tch_tco ?mcbth_tch_tcd)
method_carry_between_tcenters_cvh
(
(type_Package ?mcbth_tch_p) (type_TCenter ?mcbth_tch_tco) (type_TCenter ?mcbth_tch_tcd)
(type_Package ?mcbth_tch_p) (type_TCenter ?mcbth_tch_tcd) (type_TCenter ?mcbth_tch_tco)
)
((carry_via_hub ?mcbth_tch_p ?mcbth_tch_tco ?mcbth_tch_tcd))
)
(:method (carry_direct ?mcd_hmcd_p ?mcd_hmcd_o ?mcd_hmcd_d)
method_carry_direct
(
(type_Package ?mcd_hmcd_p) (type_Location ?mcd_hmcd_o) (type_Location ?mcd_hmcd_d)
(type_Location ?mcd_hmcd_d) (type_Location ?mcd_hmcd_o) (type_Package ?mcd_hmcd_p) (type_Vehicle ?mcd_hmcd_v)
)
((helper_carry_direct ?mcd_hmcd_v ?mcd_hmcd_p ?mcd_hmcd_o ?mcd_hmcd_d))
)
(:method (carry_via_hub ?mcvhn_hcvhn_p ?mcvhn_hcvhn_tco ?mcvhn_hcvhn_tcd)
method_carry_via_hub_not_hazardous
(
(type_Package ?mcvhn_hcvhn_p) (type_TCenter ?mcvhn_hcvhn_tco) (type_TCenter ?mcvhn_hcvhn_tcd)
(type_City ?mcvhn_hcvhn_ctcd) (type_City ?mcvhn_hcvhn_ctco) (type_Hub ?mcvhn_hcvhn_h) (type_Package ?mcvhn_hcvhn_p) (type_Region ?mcvhn_hcvhn_rctcd) (type_Region ?mcvhn_hcvhn_rctco) (type_TCenter ?mcvhn_hcvhn_tcd) (type_TCenter ?mcvhn_hcvhn_tco)
)
((helper_carry_via_hub_not_hazardous ?mcvhn_hcvhn_p ?mcvhn_hcvhn_tco ?mcvhn_hcvhn_ctco ?mcvhn_hcvhn_rctco ?mcvhn_hcvhn_h ?mcvhn_hcvhn_tcd ?mcvhn_hcvhn_ctcd ?mcvhn_hcvhn_rctcd))
)
(:method (carry_via_hub ?mcvhh_hcvhh_p ?mcvhh_hcvhh_tco ?mcvhh_hcvhh_tcd)
method_carry_via_hub_hazardous
(
(type_Package ?mcvhh_hcvhh_p) (type_TCenter ?mcvhh_hcvhh_tco) (type_TCenter ?mcvhh_hcvhh_tcd)
(type_City ?mcvhh_hcvhh_ch) (type_City ?mcvhh_hcvhh_ctcd) (type_City ?mcvhh_hcvhh_ctco) (type_Hub ?mcvhh_hcvhh_h) (type_Package ?mcvhh_hcvhh_p) (type_Region ?mcvhh_hcvhh_rctcd) (type_Region ?mcvhh_hcvhh_rctco) (type_TCenter ?mcvhh_hcvhh_tcd) (type_TCenter ?mcvhh_hcvhh_tco)
)
((helper_carry_via_hub_hazardous ?mcvhh_hcvhh_p ?mcvhh_hcvhh_tco ?mcvhh_hcvhh_ctco ?mcvhh_hcvhh_rctco ?mcvhh_hcvhh_h ?mcvhh_hcvhh_ch ?mcvhh_hcvhh_tcd ?mcvhh_hcvhh_ctcd ?mcvhh_hcvhh_rctcd))
)
(:method (deliver ?mddp_dp_p)
method_deliver_dp
(
(type_Package ?mddp_dp_p)
(type_Package ?mddp_dp_p)
)
((!deliver_p ?mddp_dp_p))
)
(:method (deliver ?mddv_dv_v)
method_deliver_dv
(
(type_Package ?mddv_dv_v)
(type_Valuable ?mddv_dv_v)
)
((!deliver_v ?mddv_dv_v))
)
(:method (deliver ?mddh_dh_h)
method_deliver_dh
(
(type_Package ?mddh_dh_h)
(type_Hazardous ?mddh_dh_h)
)
((!deliver_h ?mddh_dh_h))
)
(:method (helper_carry_cc ?mhccc_cdd_p ?mhccc_gttc_lo ?mhccc_gttc_co ?mhccc_gttc_tc ?mhccc_gttc_ld ?mhccc_gttc_cd)
method_helper_carry_cd_cd
(
(type_Package ?mhccc_cdd_p) (type_Not_TCenter ?mhccc_gttc_lo) (type_City ?mhccc_gttc_co) (type_TCenter ?mhccc_gttc_tc) (type_Not_TCenter ?mhccc_gttc_ld) (type_City ?mhccc_gttc_cd)
(type_Package ?mhccc_cdd_p) (type_City ?mhccc_gttc_cd) (type_City ?mhccc_gttc_co) (type_Not_TCenter ?mhccc_gttc_ld) (type_Not_TCenter ?mhccc_gttc_lo) (type_TCenter ?mhccc_gttc_tc)
)
((carry_direct ?mhccc_cdd_p ?mhccc_gttc_lo ?mhccc_gttc_tc) (!go_through_tcenter_cc ?mhccc_gttc_lo ?mhccc_gttc_ld ?mhccc_gttc_co ?mhccc_gttc_cd ?mhccc_gttc_tc) (carry_direct ?mhccc_cdd_p ?mhccc_gttc_tc ?mhccc_gttc_ld))
)
(:method (helper_carry_direct ?mhcd_ult_v ?mhcd_ult_p ?mhcd_mvd_lo ?mhcd_ult_l)
method_helper_carry_direct
(
(type_Vehicle ?mhcd_ult_v) (type_Package ?mhcd_ult_p) (type_Location ?mhcd_mvd_lo) (type_Location ?mhcd_ult_l)
(type_Location ?mhcd_mvd_lo) (type_Location ?mhcd_mvo_lo) (type_Location ?mhcd_ult_l) (type_Package ?mhcd_ult_p) (type_Vehicle ?mhcd_ult_v)
)
((move ?mhcd_ult_v ?mhcd_mvo_lo ?mhcd_mvd_lo) (load_top ?mhcd_ult_p ?mhcd_ult_v ?mhcd_mvd_lo) (move ?mhcd_ult_v ?mhcd_mvd_lo ?mhcd_ult_l) (unload_top ?mhcd_ult_p ?mhcd_ult_v ?mhcd_ult_l))
)
(:method (helper_carry_direct ?mhcdo_ult_v ?mhcdo_ult_p ?mhcdo_m_lo ?mhcdo_ult_l)
method_helper_carry_direct_noMoveFirst
(
(type_Vehicle ?mhcdo_ult_v) (type_Package ?mhcdo_ult_p) (type_Location ?mhcdo_m_lo) (type_Location ?mhcdo_ult_l)
(type_Location ?mhcdo_m_lo) (type_Location ?mhcdo_ult_l) (type_Package ?mhcdo_ult_p) (type_Vehicle ?mhcdo_ult_v)
)
((load_top ?mhcdo_ult_p ?mhcdo_ult_v ?mhcdo_m_lo) (move ?mhcdo_ult_v ?mhcdo_m_lo ?mhcdo_ult_l) (unload_top ?mhcdo_ult_p ?mhcdo_ult_v ?mhcdo_ult_l))
)
(:method (helper_carry_otd ?mhcctc_cd_p ?mhcctc_gtttccotd_o ?mhcctc_gtttccotd_co ?mhcctc_gtttccotd_t1 ?mhcctc_gtttccotd_cl ?mhcctc_gtttccotd_cd)
method_helper_carry_cbtc_cd
(
(type_Package ?mhcctc_cd_p) (type_TCenter ?mhcctc_gtttccotd_o) (type_City ?mhcctc_gtttccotd_co) (type_TCenter ?mhcctc_gtttccotd_t1) (type_Not_TCenter ?mhcctc_gtttccotd_cl) (type_City ?mhcctc_gtttccotd_cd)
(type_Package ?mhcctc_cd_p) (type_City ?mhcctc_gtttccotd_cd) (type_Not_TCenter ?mhcctc_gtttccotd_cl) (type_City ?mhcctc_gtttccotd_co) (type_TCenter ?mhcctc_gtttccotd_o) (type_TCenter ?mhcctc_gtttccotd_t1)
)
((carry_between_tcenters ?mhcctc_cd_p ?mhcctc_gtttccotd_o ?mhcctc_gtttccotd_t1) (!go_through_two_tcenters_cities_otd ?mhcctc_gtttccotd_cl ?mhcctc_gtttccotd_co ?mhcctc_gtttccotd_cd ?mhcctc_gtttccotd_o ?mhcctc_gtttccotd_t1) (carry_direct ?mhcctc_cd_p ?mhcctc_gtttccotd_t1 ?mhcctc_gtttccotd_cl))
)
(:method (helper_carry_ott ?mhccct_cbt_p ?mhccct_gtttccott_cl ?mhccct_gtttccott_co ?mhccct_gtttccott_to ?mhccct_gtttccott_td ?mhccct_gtttccott_cd)
method_helper_carry_cd_cbtc
(
(type_Package ?mhccct_cbt_p) (type_City_Location ?mhccct_gtttccott_cl) (type_City ?mhccct_gtttccott_co) (type_TCenter ?mhccct_gtttccott_to) (type_TCenter ?mhccct_gtttccott_td) (type_City ?mhccct_gtttccott_cd)
(type_Package ?mhccct_cbt_p) (type_City ?mhccct_gtttccott_cd) (type_City_Location ?mhccct_gtttccott_cl) (type_City ?mhccct_gtttccott_co) (type_TCenter ?mhccct_gtttccott_td) (type_TCenter ?mhccct_gtttccott_to)
)
((carry_direct ?mhccct_cbt_p ?mhccct_gtttccott_cl ?mhccct_gtttccott_to) (!go_through_two_tcenters_cities_ott ?mhccct_gtttccott_cl ?mhccct_gtttccott_co ?mhccct_gtttccott_cd ?mhccct_gtttccott_to ?mhccct_gtttccott_td) (carry_between_tcenters ?mhccct_cbt_p ?mhccct_gtttccott_to ?mhccct_gtttccott_td))
)
(:method (helper_carry_ottd ?mhcccc_cdd_p ?mhcccc_gtttc_lo ?mhcccc_gtttc_co ?mhcccc_gtttc_t1 ?mhcccc_gtttc_t2 ?mhcccc_gtttc_ld ?mhcccc_gtttc_cd)
method_helper_carry_cd_cbtc_cd
(
(type_Package ?mhcccc_cdd_p) (type_Not_TCenter ?mhcccc_gtttc_lo) (type_City ?mhcccc_gtttc_co) (type_TCenter ?mhcccc_gtttc_t1) (type_TCenter ?mhcccc_gtttc_t2) (type_Not_TCenter ?mhcccc_gtttc_ld) (type_City ?mhcccc_gtttc_cd)
(type_Package ?mhcccc_cdd_p) (type_City ?mhcccc_gtttc_cd) (type_City ?mhcccc_gtttc_co) (type_Not_TCenter ?mhcccc_gtttc_ld) (type_Not_TCenter ?mhcccc_gtttc_lo) (type_TCenter ?mhcccc_gtttc_t1) (type_TCenter ?mhcccc_gtttc_t2)
)
((carry_direct ?mhcccc_cdd_p ?mhcccc_gtttc_lo ?mhcccc_gtttc_t1) (!go_through_two_tcenters_cities_ottd ?mhcccc_gtttc_lo ?mhcccc_gtttc_ld ?mhcccc_gtttc_co ?mhcccc_gtttc_cd ?mhcccc_gtttc_t1 ?mhcccc_gtttc_t2) (carry_between_tcenters ?mhcccc_cdd_p ?mhcccc_gtttc_t1 ?mhcccc_gtttc_t2) (carry_direct ?mhcccc_cdd_p ?mhcccc_gtttc_t2 ?mhcccc_gtttc_ld))
)
(:method (helper_carry_tt ?mhch_tch_p ?mhch_gtttctt_to ?mhch_gtttctt_co ?mhch_gtttctt_td ?mhch_gtttctt_cd)
method_helper_carry_cvh
(
(type_Package ?mhch_tch_p) (type_TCenter ?mhch_gtttctt_to) (type_City ?mhch_gtttctt_co) (type_TCenter ?mhch_gtttctt_td) (type_City ?mhch_gtttctt_cd)
(type_City ?mhch_gtttctt_cd) (type_City ?mhch_gtttctt_co) (type_TCenter ?mhch_gtttctt_td) (type_TCenter ?mhch_gtttctt_to) (type_Package ?mhch_tch_p)
)
((carry_via_hub ?mhch_tch_p ?mhch_gtttctt_to ?mhch_gtttctt_td) (!go_through_two_tcenters_tt ?mhch_gtttctt_to ?mhch_gtttctt_td ?mhch_gtttctt_co ?mhch_gtttctt_cd))
)
(:method (helper_carry_via_hub_hazardous ?mhcvhh_cd2_p ?mhcvhh_gtttcvhh_to ?mhcvhh_gtttcvhh_co ?mhcvhh_gtttcvhh_ro ?mhcvhh_gtttcvhh_h ?mhcvhh_gtttcvhh_ch ?mhcvhh_gtttcvhh_td ?mhcvhh_gtttcvhh_cd ?mhcvhh_gtttcvhh_rd)
method_helper_carry_via_hub_hazardous
(
(type_Package ?mhcvhh_cd2_p) (type_TCenter ?mhcvhh_gtttcvhh_to) (type_City ?mhcvhh_gtttcvhh_co) (type_Region ?mhcvhh_gtttcvhh_ro) (type_Hub ?mhcvhh_gtttcvhh_h) (type_City ?mhcvhh_gtttcvhh_ch) (type_TCenter ?mhcvhh_gtttcvhh_td) (type_City ?mhcvhh_gtttcvhh_cd) (type_Region ?mhcvhh_gtttcvhh_rd)
(type_Package ?mhcvhh_cd2_p) (type_City ?mhcvhh_gtttcvhh_cd) (type_City ?mhcvhh_gtttcvhh_ch) (type_City ?mhcvhh_gtttcvhh_co) (type_Hub ?mhcvhh_gtttcvhh_h) (type_Region ?mhcvhh_gtttcvhh_rd) (type_Region ?mhcvhh_gtttcvhh_ro) (type_TCenter ?mhcvhh_gtttcvhh_td) (type_TCenter ?mhcvhh_gtttcvhh_to)
)
((carry_direct ?mhcvhh_cd2_p ?mhcvhh_gtttcvhh_to ?mhcvhh_gtttcvhh_h) (!go_through_two_tcenters_via_hub_hazardous ?mhcvhh_gtttcvhh_to ?mhcvhh_gtttcvhh_td ?mhcvhh_gtttcvhh_h ?mhcvhh_gtttcvhh_co ?mhcvhh_gtttcvhh_ch ?mhcvhh_gtttcvhh_cd ?mhcvhh_gtttcvhh_ro ?mhcvhh_gtttcvhh_rd) (carry_direct ?mhcvhh_cd2_p ?mhcvhh_gtttcvhh_h ?mhcvhh_gtttcvhh_td))
)
(:method (helper_carry_via_hub_not_hazardous ?mhcvhn_cd2_p ?mhcvhn_gtttcvhnh_to ?mhcvhn_gtttcvhnh_co ?mhcvhn_gtttcvhnh_ro ?mhcvhn_gtttcvhnh_h ?mhcvhn_gtttcvhnh_td ?mhcvhn_gtttcvhnh_cd ?mhcvhn_gtttcvhnh_rd)
method_helper_carry_via_hub_not_hazardous
(
(type_Package ?mhcvhn_cd2_p) (type_TCenter ?mhcvhn_gtttcvhnh_to) (type_City ?mhcvhn_gtttcvhnh_co) (type_Region ?mhcvhn_gtttcvhnh_ro) (type_Hub ?mhcvhn_gtttcvhnh_h) (type_TCenter ?mhcvhn_gtttcvhnh_td) (type_City ?mhcvhn_gtttcvhnh_cd) (type_Region ?mhcvhn_gtttcvhnh_rd)
(type_Package ?mhcvhn_cd2_p) (type_City ?mhcvhn_gtttcvhnh_cd) (type_City ?mhcvhn_gtttcvhnh_co) (type_Hub ?mhcvhn_gtttcvhnh_h) (type_Region ?mhcvhn_gtttcvhnh_rd) (type_Region ?mhcvhn_gtttcvhnh_ro) (type_TCenter ?mhcvhn_gtttcvhnh_td) (type_TCenter ?mhcvhn_gtttcvhnh_to)
)
((carry_direct ?mhcvhn_cd2_p ?mhcvhn_gtttcvhnh_to ?mhcvhn_gtttcvhnh_h) (!go_through_two_tcenters_via_hub_not_hazardous ?mhcvhn_gtttcvhnh_to ?mhcvhn_gtttcvhnh_td ?mhcvhn_gtttcvhnh_co ?mhcvhn_gtttcvhnh_cd ?mhcvhn_gtttcvhnh_ro ?mhcvhn_gtttcvhnh_rd ?mhcvhn_gtttcvhnh_h) (carry_direct ?mhcvhn_cd2_p ?mhcvhn_gtttcvhnh_h ?mhcvhn_gtttcvhnh_td))
)
(:method (helper_move_traincar ?mhmt_dtc_tc ?mhmt_dtc_t ?mhmt_md_lo ?mhmt_dtc_l)
method_helper_move_traincar
(
(type_Traincar ?mhmt_dtc_tc) (type_Train ?mhmt_dtc_t) (type_Location ?mhmt_md_lo) (type_Location ?mhmt_dtc_l)
(type_Location ?mhmt_dtc_l) (type_Train ?mhmt_dtc_t) (type_Traincar ?mhmt_dtc_tc) (type_Location ?mhmt_md_lo) (type_Location ?mhmt_mo_lo)
)
((move ?mhmt_dtc_t ?mhmt_mo_lo ?mhmt_md_lo) (!attach_train_car ?mhmt_dtc_t ?mhmt_dtc_tc ?mhmt_md_lo) (move ?mhmt_dtc_t ?mhmt_md_lo ?mhmt_dtc_l) (!detach_train_car ?mhmt_dtc_t ?mhmt_dtc_tc ?mhmt_dtc_l))
)
(:method (helper_move_traincar ?mhmtn_dtc_tc ?mhmtn_dtc_t ?mhmtn_md_lo ?mhmtn_dtc_l)
method_helper_move_traincar_noMoveFirst
(
(type_Traincar ?mhmtn_dtc_tc) (type_Train ?mhmtn_dtc_t) (type_Location ?mhmtn_md_lo) (type_Location ?mhmtn_dtc_l)
(type_Location ?mhmtn_dtc_l) (type_Train ?mhmtn_dtc_t) (type_Traincar ?mhmtn_dtc_tc) (type_Location ?mhmtn_md_lo)
)
((!attach_train_car ?mhmtn_dtc_t ?mhmtn_dtc_tc ?mhmtn_md_lo) (move ?mhmtn_dtc_t ?mhmtn_md_lo ?mhmtn_dtc_l) (!detach_train_car ?mhmtn_dtc_t ?mhmtn_dtc_tc ?mhmtn_dtc_l))
)
(:method (load ?mlr_lp_p ?mlr_cd_rv ?mlr_lp_l)
method_load_regular
(
(type_Package ?mlr_lp_p) (type_Vehicle ?mlr_cd_rv) (type_Location ?mlr_lp_l)
(type_Regular_Vehicle ?mlr_cd_rv) (type_Location ?mlr_lp_l) (type_Package ?mlr_lp_p)
)
((!open_door ?mlr_cd_rv) (!load_package ?mlr_lp_p ?mlr_cd_rv ?mlr_lp_l) (!close_door ?mlr_cd_rv))
)
(:method (load ?mlf_pdpv_p ?mlf_pdpv_fv ?mlf_pdpv_l)
method_load_flatbed
(
(type_Package ?mlf_pdpv_p) (type_Vehicle ?mlf_pdpv_fv) (type_Location ?mlf_pdpv_l)
(type_Crane ?mlf_pdpv_c) (type_Flatbed_Vehicle ?mlf_pdpv_fv) (type_Location ?mlf_pdpv_l) (type_Package ?mlf_pdpv_p)
)
((!pick_up_package_ground ?mlf_pdpv_p ?mlf_pdpv_c ?mlf_pdpv_l) (!put_down_package_vehicle ?mlf_pdpv_p ?mlf_pdpv_c ?mlf_pdpv_fv ?mlf_pdpv_l))
)
(:method (load ?mlh_fh_p ?mlh_dc_h ?mlh_fh_l)
method_load_hopper
(
(type_Package ?mlh_fh_p) (type_Vehicle ?mlh_dc_h) (type_Location ?mlh_fh_l)
(type_Hopper_Vehicle ?mlh_dc_h) (type_Location ?mlh_fh_l) (type_Package ?mlh_fh_p)
)
((!connect_chute ?mlh_dc_h) (!fill_hopper ?mlh_fh_p ?mlh_dc_h ?mlh_fh_l) (!disconnect_chute ?mlh_dc_h))
)
(:method (load ?mlt_dch_l ?mlt_dch_tv ?mlt_ft_lo)
method_load_tanker
(
(type_Package ?mlt_dch_l) (type_Vehicle ?mlt_dch_tv) (type_Location ?mlt_ft_lo)
(type_Liquid ?mlt_dch_l) (type_Tanker_Vehicle ?mlt_dch_tv) (type_Location ?mlt_ft_lo)
)
((!connect_hose ?mlt_dch_tv ?mlt_dch_l) (!open_valve ?mlt_dch_tv) (!fill_tank ?mlt_dch_tv ?mlt_dch_l ?mlt_ft_lo) (!close_valve ?mlt_dch_tv) (!disconnect_hose ?mlt_dch_tv ?mlt_dch_l))
)
(:method (load ?mll_ll_p ?mll_rr_v ?mll_ll_l)
method_load_livestock
(
(type_Package ?mll_ll_p) (type_Vehicle ?mll_rr_v) (type_Location ?mll_ll_l)
(type_Location ?mll_ll_l) (type_Livestock_Package ?mll_ll_p) (type_Vehicle ?mll_rr_v)
)
((!lower_ramp ?mll_rr_v) (!fill_trough ?mll_rr_v) (!load_livestock ?mll_ll_p ?mll_rr_v ?mll_ll_l) (!raise_ramp ?mll_rr_v))
)
(:method (load ?mlc_lc_c ?mlc_rr_v ?mlc_lc_l)
method_load_cars
(
(type_Package ?mlc_lc_c) (type_Vehicle ?mlc_rr_v) (type_Location ?mlc_lc_l)
(type_Cars ?mlc_lc_c) (type_Location ?mlc_lc_l) (type_Vehicle ?mlc_rr_v)
)
((!lower_ramp ?mlc_rr_v) (!load_cars ?mlc_lc_c ?mlc_rr_v ?mlc_lc_l) (!raise_ramp ?mlc_rr_v))
)
(:method (load ?mla_lp_p ?mla_dcr_ap ?mla_dcr_l)
method_load_airplane
(
(type_Package ?mla_lp_p) (type_Vehicle ?mla_dcr_ap) (type_Location ?mla_dcr_l)
(type_Airplane ?mla_dcr_ap) (type_Location ?mla_dcr_l) (type_Plane_Ramp ?mla_dcr_pr) (type_Package ?mla_lp_p)
)
((!attach_conveyor_ramp ?mla_dcr_ap ?mla_dcr_pr ?mla_dcr_l) (!open_door ?mla_dcr_ap) (!load_package ?mla_lp_p ?mla_dcr_ap ?mla_dcr_l) (!close_door ?mla_dcr_ap) (!detach_conveyor_ramp ?mla_dcr_ap ?mla_dcr_pr ?mla_dcr_l))
)
(:method (load_top ?mlmn_l_p ?mlmn_l_v ?mlmn_l_l)
method_load_top_normal
(
(type_Package ?mlmn_l_p) (type_Vehicle ?mlmn_l_v) (type_Location ?mlmn_l_l)
(type_Location ?mlmn_l_l) (type_Package ?mlmn_l_p) (type_Vehicle ?mlmn_l_v)
)
((load ?mlmn_l_p ?mlmn_l_v ?mlmn_l_l))
)
(:method (load_top ?mlmh_l_p ?mlmh_l_v ?mlmh_l_l)
method_load_top_hazardous
(
(type_Package ?mlmh_l_p) (type_Vehicle ?mlmh_l_v) (type_Location ?mlmh_l_l)
(type_Location ?mlmh_l_l) (type_Package ?mlmh_l_p) (type_Vehicle ?mlmh_l_v)
)
((!affix_warning_signs ?mlmh_l_v) (load ?mlmh_l_p ?mlmh_l_v ?mlmh_l_l))
)
(:method (load_top ?mlmv_l_p ?mlmv_pci_a ?mlmv_l_l)
method_load_top_valuable
(
(type_Package ?mlmv_l_p) (type_Vehicle ?mlmv_pci_a) (type_Location ?mlmv_l_l)
(type_Location ?mlmv_l_l) (type_Package ?mlmv_l_p) (type_Armored ?mlmv_pci_a)
)
((!post_guard_outside ?mlmv_pci_a) (load ?mlmv_l_p ?mlmv_pci_a ?mlmv_l_l) (!post_guard_inside ?mlmv_pci_a))
)
(:method (move ?mmnt_mvnt_v ?mmnt_mvnt_o ?mmnt_mvnt_d)
method_move_no_traincar
(
(type_Vehicle ?mmnt_mvnt_v) (type_Location ?mmnt_mvnt_o) (type_Location ?mmnt_mvnt_d)
(type_Location ?mmnt_mvnt_d) (type_Location ?mmnt_mvnt_o) (type_Route ?mmnt_mvnt_r) (type_Vehicle ?mmnt_mvnt_v)
)
((!move_vehicle_no_traincar ?mmnt_mvnt_v ?mmnt_mvnt_o ?mmnt_mvnt_r ?mmnt_mvnt_d))
)
(:method (move ?mmt_hmt_v ?mmt_hmt_o ?mmt_hmt_d)
method_move_traincar
(
(type_Vehicle ?mmt_hmt_v) (type_Location ?mmt_hmt_o) (type_Location ?mmt_hmt_d)
(type_Location ?mmt_hmt_d) (type_Location ?mmt_hmt_o) (type_Train ?mmt_hmt_t) (type_Traincar ?mmt_hmt_v)
)
((helper_move_traincar ?mmt_hmt_v ?mmt_hmt_t ?mmt_hmt_o ?mmt_hmt_d))
)
(:method (pickup ?mpn_cf_p)
method_pickup_normal
(
(type_Package ?mpn_cf_p)
(type_Package ?mpn_cf_p)
)
((!collect_fees ?mpn_cf_p))
)
(:method (pickup ?mph_op_h)
method_pickup_hazardous
(
(type_Package ?mph_op_h)
(type_Hazardous ?mph_op_h)
)
((!collect_fees ?mph_op_h) (!obtain_permit ?mph_op_h))
)
(:method (pickup ?mpv_ci_v)
method_pickup_valuable
(
(type_Package ?mpv_ci_v)
(type_Valuable ?mpv_ci_v)
)
((!collect_fees ?mpv_ci_v) (!collect_insurance ?mpv_ci_v))
)
(:method (transport ?mtpcd_de_p ?mtpcd_ca_lo ?mtpcd_ca_ld)
method_transport_pi_ca_de
(
(type_Package ?mtpcd_de_p) (type_Location ?mtpcd_ca_lo) (type_Location ?mtpcd_ca_ld)
(type_Location ?mtpcd_ca_ld) (type_Location ?mtpcd_ca_lo) (type_Package ?mtpcd_de_p)
)
((pickup ?mtpcd_de_p) (carry ?mtpcd_de_p ?mtpcd_ca_lo ?mtpcd_ca_ld) (deliver ?mtpcd_de_p))
)
(:method (unload ?mur_up_p ?mur_cd_rv ?mur_up_l)
method_unload_regular
(
(type_Package ?mur_up_p) (type_Vehicle ?mur_cd_rv) (type_Location ?mur_up_l)
(type_Regular_Vehicle ?mur_cd_rv) (type_Location ?mur_up_l) (type_Package ?mur_up_p)
)
((!open_door ?mur_cd_rv) (!unload_package ?mur_up_p ?mur_cd_rv ?mur_up_l) (!close_door ?mur_cd_rv))
)
(:method (unload ?muf_pdpg_p ?muf_pupv_fv ?muf_pdpg_l)
method_unload_flatbed
(
(type_Package ?muf_pdpg_p) (type_Vehicle ?muf_pupv_fv) (type_Location ?muf_pdpg_l)
(type_Crane ?muf_pdpg_c) (type_Location ?muf_pdpg_l) (type_Package ?muf_pdpg_p) (type_Flatbed_Vehicle ?muf_pupv_fv)
)
((!pick_up_package_vehicle ?muf_pdpg_p ?muf_pdpg_c ?muf_pupv_fv ?muf_pdpg_l) (!put_down_package_ground ?muf_pdpg_p ?muf_pdpg_c ?muf_pdpg_l))
)
(:method (unload ?muh_eh_p ?muh_dc_h ?muh_eh_l)
method_unload_hopper
(
(type_Package ?muh_eh_p) (type_Vehicle ?muh_dc_h) (type_Location ?muh_eh_l)
(type_Hopper_Vehicle ?muh_dc_h) (type_Location ?muh_eh_l) (type_Package ?muh_eh_p)
)
((!connect_chute ?muh_dc_h) (!empty_hopper ?muh_eh_p ?muh_dc_h ?muh_eh_l) (!disconnect_chute ?muh_dc_h))
)
(:method (unload ?mut_dch_l ?mut_dch_tv ?mut_et_lo)
method_unload_tanker
(
(type_Package ?mut_dch_l) (type_Vehicle ?mut_dch_tv) (type_Location ?mut_et_lo)
(type_Liquid ?mut_dch_l) (type_Tanker_Vehicle ?mut_dch_tv) (type_Location ?mut_et_lo)
)
((!connect_hose ?mut_dch_tv ?mut_dch_l) (!open_valve ?mut_dch_tv) (!empty_tank ?mut_dch_tv ?mut_dch_l ?mut_et_lo) (!close_valve ?mut_dch_tv) (!disconnect_hose ?mut_dch_tv ?mut_dch_l))
)
(:method (unload ?mul_ull_p ?mul_rr_v ?mul_ull_l)
method_unload_livestock
(
(type_Package ?mul_ull_p) (type_Vehicle ?mul_rr_v) (type_Location ?mul_ull_l)
(type_Vehicle ?mul_rr_v) (type_Location ?mul_ull_l) (type_Livestock_Package ?mul_ull_p)
)
((!lower_ramp ?mul_rr_v) (!unload_livestock ?mul_ull_p ?mul_rr_v ?mul_ull_l) (!do_clean_interior ?mul_rr_v) (!raise_ramp ?mul_rr_v))
)
(:method (unload ?muc_uc_c ?muc_rr_v ?muc_uc_l)
method_unload_cars
(
(type_Package ?muc_uc_c) (type_Vehicle ?muc_rr_v) (type_Location ?muc_uc_l)
(type_Vehicle ?muc_rr_v) (type_Cars ?muc_uc_c) (type_Location ?muc_uc_l)
)
((!lower_ramp ?muc_rr_v) (!unload_cars ?muc_uc_c ?muc_rr_v ?muc_uc_l) (!raise_ramp ?muc_rr_v))
)
(:method (unload ?mua_up_p ?mua_dcr_ap ?mua_dcr_l)
method_unload_airplane
(
(type_Package ?mua_up_p) (type_Vehicle ?mua_dcr_ap) (type_Location ?mua_dcr_l)
(type_Airplane ?mua_dcr_ap) (type_Location ?mua_dcr_l) (type_Plane_Ramp ?mua_dcr_pr) (type_Package ?mua_up_p)
)
((!attach_conveyor_ramp ?mua_dcr_ap ?mua_dcr_pr ?mua_dcr_l) (!open_door ?mua_dcr_ap) (!unload_package ?mua_up_p ?mua_dcr_ap ?mua_dcr_l) (!close_door ?mua_dcr_ap) (!detach_conveyor_ramp ?mua_dcr_ap ?mua_dcr_pr ?mua_dcr_l))
)
(:method (unload_top ?mumn_ul_p ?mumn_ul_v ?mumn_ul_l)
method_unload_top_normal
(
(type_Package ?mumn_ul_p) (type_Vehicle ?mumn_ul_v) (type_Location ?mumn_ul_l)
(type_Location ?mumn_ul_l) (type_Package ?mumn_ul_p) (type_Vehicle ?mumn_ul_v)
)
((unload ?mumn_ul_p ?mumn_ul_v ?mumn_ul_l))
)
(:method (unload_top ?mumh_ul_p ?mumh_ul_v ?mumh_ul_l)
method_unload_top_hazardous
(
(type_Package ?mumh_ul_p) (type_Vehicle ?mumh_ul_v) (type_Location ?mumh_ul_l)
(type_Location ?mumh_ul_l) (type_Package ?mumh_ul_p) (type_Vehicle ?mumh_ul_v)
)
((unload ?mumh_ul_p ?mumh_ul_v ?mumh_ul_l) (!decontaminate_interior ?mumh_ul_v) (!remove_warning_signs ?mumh_ul_v))
)
(:method (unload_top ?mumv_ul_p ?mumv_ul_v ?mumv_ul_l)
method_unload_top_valuable
(
(type_Package ?mumv_ul_p) (type_Vehicle ?mumv_ul_v) (type_Location ?mumv_ul_l)
(type_Location ?mumv_ul_l) (type_Package ?mumv_ul_p) (type_Vehicle ?mumv_ul_v)
)
((!post_guard_outside ?mumv_ul_v) (unload ?mumv_ul_p ?mumv_ul_v ?mumv_ul_l) (!remove_guard ?mumv_ul_v))
)
))
|
220c41e0d05754d4eaf18beb543663ccae0152b9bf682010a97ccaab9cc56062 | threatgrid/clj-momo | http.clj | (ns clj-momo.test-helpers.http
(:refer-clojure :exclude [get])
(:require [cheshire.core :as json]
[clj-http.client :as http]
[clj-momo.lib.url :as url]
[clojure
[edn :as edn]
[pprint :refer [pprint]]
[string :as str]]))
(defn url [path port]
(let [url (format ":%d/%s" port path)]
(assert (url/encoded? url)
(format "URL '%s' is not encoded" url))
url))
(defn content-type? [expected-str]
(fn [test-str]
(if (some? test-str)
(str/includes? (name test-str) expected-str)
false)))
(def json? (content-type? "json"))
(def edn? (content-type? "edn"))
(defn parse-body
([http-response]
(parse-body http-response nil))
([{{content-type "Content-Type"} :headers
body :body}
default]
(try
(cond
(edn? content-type) (edn/read-string body)
(json? content-type) (json/parse-string body)
:else default)
(catch Exception e
(binding [*out* *err*]
(println "------- BODY ----------")
(pprint body)
(println "------- EXCEPTION ----------")
(pprint e))))))
(defn encode-body
[body content-type]
(cond
(edn? content-type) (pr-str body)
(json? content-type) (json/generate-string body)
:else body))
(defn get [path port & {:as options}]
(let [options
(merge {:accept :edn
:throw-exceptions false
:socket-timeout 10000
:conn-timeout 10000}
options)
response
(http/get (url path port)
options)]
(assoc response :parsed-body (parse-body response))))
(defn post [path port & {:as options}]
(let [{:keys [body content-type]
:as options}
(merge {:content-type :edn
:accept :edn
:throw-exceptions false
:socket-timeout 10000
:conn-timeout 10000}
options)
response
(http/post (url path port)
(-> options
(cond-> body (assoc :body (encode-body body content-type)))))]
(assoc response :parsed-body (parse-body response))))
(defn delete [path port & {:as options}]
(http/delete (url path port)
(merge {:throw-exceptions false}
options)))
(defn put [path port & {:as options}]
(let [{:keys [body content-type]
:as options}
(merge {:content-type :edn
:accept :edn
:throw-exceptions false
:socket-timeout 10000
:conn-timeout 10000}
options)
response
(http/put (url path port)
(-> options
(cond-> body (assoc :body (encode-body body content-type)))))]
(assoc response :parsed-body (parse-body response))))
(defn patch [path port & {:as options}]
(let [{:keys [body content-type]
:as options}
(merge {:content-type :edn
:accept :edn
:throw-exceptions false
:socket-timeout 10000
:conn-timeout 10000}
options)
response
(http/patch (url path port)
(-> options
(cond-> body (assoc :body (encode-body body content-type)))))]
(assoc response :parsed-body (parse-body response))))
(defn encode [s]
(assert (string? s)
(format "Assert Failed: %s of type %s must be a string"
s (type s)))
(assert (seq s)
(format "Assert Failed: %s of type %s must be a seq"
s (type s)))
(url/encode s))
(defn decode [s]
(assert (string? s)
(format "Assert Failed: %s of type %s must be a string"
s (type s)))
(assert (seq s)
(format "Assert Failed: %s of type %s must be a seq"
s (type s)))
(url/decode s))
(defn with-port-fn
"Helper to compose a fn that knows how to lookup an HTTP port with
an HTTP method fn (from above)
Example:
(def post (http/with-port-fn get-http-port http/post))"
[port-fn http-fn]
(fn [path & options]
(apply (partial http-fn path (port-fn)) options)))
| null | https://raw.githubusercontent.com/threatgrid/clj-momo/7bc0a411593eee4a939b6a3d0f628413518e09e2/src/clj_momo/test_helpers/http.clj | clojure | (ns clj-momo.test-helpers.http
(:refer-clojure :exclude [get])
(:require [cheshire.core :as json]
[clj-http.client :as http]
[clj-momo.lib.url :as url]
[clojure
[edn :as edn]
[pprint :refer [pprint]]
[string :as str]]))
(defn url [path port]
(let [url (format ":%d/%s" port path)]
(assert (url/encoded? url)
(format "URL '%s' is not encoded" url))
url))
(defn content-type? [expected-str]
(fn [test-str]
(if (some? test-str)
(str/includes? (name test-str) expected-str)
false)))
(def json? (content-type? "json"))
(def edn? (content-type? "edn"))
(defn parse-body
([http-response]
(parse-body http-response nil))
([{{content-type "Content-Type"} :headers
body :body}
default]
(try
(cond
(edn? content-type) (edn/read-string body)
(json? content-type) (json/parse-string body)
:else default)
(catch Exception e
(binding [*out* *err*]
(println "------- BODY ----------")
(pprint body)
(println "------- EXCEPTION ----------")
(pprint e))))))
(defn encode-body
[body content-type]
(cond
(edn? content-type) (pr-str body)
(json? content-type) (json/generate-string body)
:else body))
(defn get [path port & {:as options}]
(let [options
(merge {:accept :edn
:throw-exceptions false
:socket-timeout 10000
:conn-timeout 10000}
options)
response
(http/get (url path port)
options)]
(assoc response :parsed-body (parse-body response))))
(defn post [path port & {:as options}]
(let [{:keys [body content-type]
:as options}
(merge {:content-type :edn
:accept :edn
:throw-exceptions false
:socket-timeout 10000
:conn-timeout 10000}
options)
response
(http/post (url path port)
(-> options
(cond-> body (assoc :body (encode-body body content-type)))))]
(assoc response :parsed-body (parse-body response))))
(defn delete [path port & {:as options}]
(http/delete (url path port)
(merge {:throw-exceptions false}
options)))
(defn put [path port & {:as options}]
(let [{:keys [body content-type]
:as options}
(merge {:content-type :edn
:accept :edn
:throw-exceptions false
:socket-timeout 10000
:conn-timeout 10000}
options)
response
(http/put (url path port)
(-> options
(cond-> body (assoc :body (encode-body body content-type)))))]
(assoc response :parsed-body (parse-body response))))
(defn patch [path port & {:as options}]
(let [{:keys [body content-type]
:as options}
(merge {:content-type :edn
:accept :edn
:throw-exceptions false
:socket-timeout 10000
:conn-timeout 10000}
options)
response
(http/patch (url path port)
(-> options
(cond-> body (assoc :body (encode-body body content-type)))))]
(assoc response :parsed-body (parse-body response))))
(defn encode [s]
(assert (string? s)
(format "Assert Failed: %s of type %s must be a string"
s (type s)))
(assert (seq s)
(format "Assert Failed: %s of type %s must be a seq"
s (type s)))
(url/encode s))
(defn decode [s]
(assert (string? s)
(format "Assert Failed: %s of type %s must be a string"
s (type s)))
(assert (seq s)
(format "Assert Failed: %s of type %s must be a seq"
s (type s)))
(url/decode s))
(defn with-port-fn
"Helper to compose a fn that knows how to lookup an HTTP port with
an HTTP method fn (from above)
Example:
(def post (http/with-port-fn get-http-port http/post))"
[port-fn http-fn]
(fn [path & options]
(apply (partial http-fn path (port-fn)) options)))
| |
333bb9cf5b871a1c2689e65adaf143d5ce096122c11c582e971d9108a494bed4 | rjnw/sham | types.rkt | #lang racket
(require sham/llvm/ir/ast
sham/ir/ast
sham/ir/rkt
sham/md
sham/ir/env)
(require ffi/unsafe)
(provide rkt-cast-jit-ptr)
(define ((build-rkt-types s-env))
(match-define (sham-env s-mod ll-env s-md) s-env)
(match-define (sham-module s-ast ll-ast ext) s-mod)
(match-define (sham:def:module #:md m-info mod-id defs ...) s-ast)
(define def-map (for/hash ([d defs])
(values (if (sham:def? d) (sham:def-id d) (llvm:def-id d)) d)))
(for/hash ([d defs]
#:when (sham:def:function? d))
(match-define (sham:def:function #:md f-md f-name t-ast f-body) d)
(values f-name (or (ref-function-md-jit-rkt-type f-md) (to-rkt-type t-ast def-map)))))
(define (try-populate-rkt-types! s-env)
(match-define (sham-env s-mod ll-env s-md) s-env)
(md-ref! s-md sham-env-md-rkt-types
(build-rkt-types s-env)))
(define (sham-env-rkt-type s-env name)
(match-define (sham-env s-mod ll-env s-md) s-env)
(try-populate-rkt-types! s-env)
(hash-ref (ref-sham-env-md-rkt-types s-md) name))
(define (uintptr->ptr->rkt uintptr type)
(cast (cast uintptr _uintptr _pointer) _pointer type))
(define (rkt-cast-jit-ptr s-env name uintptr)
(define rkt-type (sham-env-rkt-type s-env name))
(uintptr->ptr->rkt uintptr rkt-type))
| null | https://raw.githubusercontent.com/rjnw/sham/6e0524b1eb01bcda83ae7a5be6339da4257c6781/sham-base/sham/rkt/types.rkt | racket | #lang racket
(require sham/llvm/ir/ast
sham/ir/ast
sham/ir/rkt
sham/md
sham/ir/env)
(require ffi/unsafe)
(provide rkt-cast-jit-ptr)
(define ((build-rkt-types s-env))
(match-define (sham-env s-mod ll-env s-md) s-env)
(match-define (sham-module s-ast ll-ast ext) s-mod)
(match-define (sham:def:module #:md m-info mod-id defs ...) s-ast)
(define def-map (for/hash ([d defs])
(values (if (sham:def? d) (sham:def-id d) (llvm:def-id d)) d)))
(for/hash ([d defs]
#:when (sham:def:function? d))
(match-define (sham:def:function #:md f-md f-name t-ast f-body) d)
(values f-name (or (ref-function-md-jit-rkt-type f-md) (to-rkt-type t-ast def-map)))))
(define (try-populate-rkt-types! s-env)
(match-define (sham-env s-mod ll-env s-md) s-env)
(md-ref! s-md sham-env-md-rkt-types
(build-rkt-types s-env)))
(define (sham-env-rkt-type s-env name)
(match-define (sham-env s-mod ll-env s-md) s-env)
(try-populate-rkt-types! s-env)
(hash-ref (ref-sham-env-md-rkt-types s-md) name))
(define (uintptr->ptr->rkt uintptr type)
(cast (cast uintptr _uintptr _pointer) _pointer type))
(define (rkt-cast-jit-ptr s-env name uintptr)
(define rkt-type (sham-env-rkt-type s-env name))
(uintptr->ptr->rkt uintptr rkt-type))
| |
380ec6e9d2b920c3b51867a45d06d430ff8e61966159f1cac9694a71ee8c49e0 | vedang/clj_fdb | transaction.clj | (ns me.vedang.clj-fdb.transaction
(:refer-clojure :exclude [get set read])
(:import clojure.lang.IFn
[com.apple.foundationdb MutationType Range Transaction TransactionContext]
com.apple.foundationdb.async.AsyncIterable
java.util.concurrent.CompletableFuture
[java.util.function Function Supplier]))
(defn- as-function
"Takes a clojure fn and returns a `reify`'d version which implements
`java.util.function.Function`.
Note: The fn should accept a single argument."
[f]
(reify Function
(apply [_this arg] (f arg))))
(defn- as-supplier
"Takes a clojure fn and returns a `reify`'d version which implements
`java.util.function.Supplier`.
Note: The fn should accept 0 arguments"
[f]
(reify Supplier
(get [_this] (f))))
(defn run
"Takes a `TransactionContext` and a `fn`, and runs the function once
against this Transaction. The call blocks while user code is
executing, returning the result of that code on completion."
[^TransactionContext tc ^IFn tr-fn]
(.run tc (as-function tr-fn)))
(defn ^CompletableFuture run-async!
"Takes a `TransactionContext` and a `fn`. Depending on the type of
context, this may execute the supplied function multiple times if an
error is encountered. This call is non-blocking -- control flow will
return immediately with a `CompletableFuture` that will be set when
the process is complete."
[^TransactionContext tc ^IFn tr-fn]
(.runAsync tc
(as-function
(fn [tr]
(. CompletableFuture
(supplyAsync (as-supplier (fn [] (tr-fn tr)))))))))
(defn read
"Takes a `TransactionContext` and runs a function `fn` in this context
that takes a read-only transaction. Depending on the type of
context, this may execute the supplied function multiple times if an
error is encountered. This method is blocking -- control will not
return from this call until work is complete."
[^TransactionContext tc ^IFn tr-fn]
(.read tc (as-function tr-fn)))
(defn ^CompletableFuture read-async!
"Takes a `TransactionContext` and runs a function `fn` in this context
that takes a read-only transaction. Depending on the type of
context, this may execute the supplied function multiple times if an
error is encountered. This method is non-blocking -- control flow
returns immediately with a `CompletableFuture`."
[^TransactionContext tc ^IFn tr-fn]
(.readAsync tc
(as-function
(fn [tr]
(. CompletableFuture
(supplyAsync (as-supplier (fn [] (tr-fn tr)))))))))
(defn set
"Sets the value for a given key."
[^Transaction tr ^"[B" k ^"[B" v]
(.set tr k v))
(defn ^CompletableFuture get
"Gets a value from the database. The call will return null if the
key is not present in the database."
[^Transaction tr ^"[B" k]
(.get tr k))
(defn ^AsyncIterable get-range
"Gets an ordered range of keys and values from the database. The
begin and end keys are specified by byte[] arrays, with the begin
key inclusive and the end key exclusive. Ranges are returned from
calls to Tuple.range() and Range.startsWith(byte[])."
[^Transaction tr ^Range rg]
(.getRange tr rg))
(defn clear-key
"When given a Transaction and a key, clears a given key from the
database. This will not affect the database until commit() is
called."
[^Transaction tr ^"[B" k]
(.clear tr k))
(defn clear-range
"When given a Range, clears a range of keys in the database. The
that is , the key ( if one
exists) that is specified as the end of the range will NOT be
cleared as part of this operation. Range clears are efficient with
FoundationDB -- clearing large amounts of data will be fast. This
will not affect the database until commit() is called."
[^Transaction tr ^Range rg]
(.clear tr rg))
(defn mutate!
"An atomic operation is a single database command that carries out
several logical steps: reading the value of a key, performing a
transformation on that value, and writing the result."
[^Transaction tr ^MutationType mut ^"[B" k ^"[B" param]
(.mutate tr mut k param))
| null | https://raw.githubusercontent.com/vedang/clj_fdb/58aae585273f291a1dbd69d5a2a355f177e20b61/src/me/vedang/clj_fdb/transaction.clj | clojure | (ns me.vedang.clj-fdb.transaction
(:refer-clojure :exclude [get set read])
(:import clojure.lang.IFn
[com.apple.foundationdb MutationType Range Transaction TransactionContext]
com.apple.foundationdb.async.AsyncIterable
java.util.concurrent.CompletableFuture
[java.util.function Function Supplier]))
(defn- as-function
"Takes a clojure fn and returns a `reify`'d version which implements
`java.util.function.Function`.
Note: The fn should accept a single argument."
[f]
(reify Function
(apply [_this arg] (f arg))))
(defn- as-supplier
"Takes a clojure fn and returns a `reify`'d version which implements
`java.util.function.Supplier`.
Note: The fn should accept 0 arguments"
[f]
(reify Supplier
(get [_this] (f))))
(defn run
"Takes a `TransactionContext` and a `fn`, and runs the function once
against this Transaction. The call blocks while user code is
executing, returning the result of that code on completion."
[^TransactionContext tc ^IFn tr-fn]
(.run tc (as-function tr-fn)))
(defn ^CompletableFuture run-async!
"Takes a `TransactionContext` and a `fn`. Depending on the type of
context, this may execute the supplied function multiple times if an
error is encountered. This call is non-blocking -- control flow will
return immediately with a `CompletableFuture` that will be set when
the process is complete."
[^TransactionContext tc ^IFn tr-fn]
(.runAsync tc
(as-function
(fn [tr]
(. CompletableFuture
(supplyAsync (as-supplier (fn [] (tr-fn tr)))))))))
(defn read
"Takes a `TransactionContext` and runs a function `fn` in this context
that takes a read-only transaction. Depending on the type of
context, this may execute the supplied function multiple times if an
error is encountered. This method is blocking -- control will not
return from this call until work is complete."
[^TransactionContext tc ^IFn tr-fn]
(.read tc (as-function tr-fn)))
(defn ^CompletableFuture read-async!
"Takes a `TransactionContext` and runs a function `fn` in this context
that takes a read-only transaction. Depending on the type of
context, this may execute the supplied function multiple times if an
error is encountered. This method is non-blocking -- control flow
returns immediately with a `CompletableFuture`."
[^TransactionContext tc ^IFn tr-fn]
(.readAsync tc
(as-function
(fn [tr]
(. CompletableFuture
(supplyAsync (as-supplier (fn [] (tr-fn tr)))))))))
(defn set
"Sets the value for a given key."
[^Transaction tr ^"[B" k ^"[B" v]
(.set tr k v))
(defn ^CompletableFuture get
"Gets a value from the database. The call will return null if the
key is not present in the database."
[^Transaction tr ^"[B" k]
(.get tr k))
(defn ^AsyncIterable get-range
"Gets an ordered range of keys and values from the database. The
begin and end keys are specified by byte[] arrays, with the begin
key inclusive and the end key exclusive. Ranges are returned from
calls to Tuple.range() and Range.startsWith(byte[])."
[^Transaction tr ^Range rg]
(.getRange tr rg))
(defn clear-key
"When given a Transaction and a key, clears a given key from the
database. This will not affect the database until commit() is
called."
[^Transaction tr ^"[B" k]
(.clear tr k))
(defn clear-range
"When given a Range, clears a range of keys in the database. The
that is , the key ( if one
exists) that is specified as the end of the range will NOT be
cleared as part of this operation. Range clears are efficient with
FoundationDB -- clearing large amounts of data will be fast. This
will not affect the database until commit() is called."
[^Transaction tr ^Range rg]
(.clear tr rg))
(defn mutate!
"An atomic operation is a single database command that carries out
several logical steps: reading the value of a key, performing a
transformation on that value, and writing the result."
[^Transaction tr ^MutationType mut ^"[B" k ^"[B" param]
(.mutate tr mut k param))
| |
f808df45ed7d002f352690fb210d3e9d5327f306e053714f457b33bfb641cfc0 | yi-editor/yi-rope | MainBenchmarkSuite.hs | # OPTIONS_GHC -fno - warn - orphans #
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Char (isSpace)
import Control.DeepSeq
import Criterion.Main
import qualified Criterion.Main as C
import Data.Text (unlines, Text, replicate)
import Prelude hiding (unlines)
import qualified Yi.Rope as F
longText :: Text
longText = force . Data.Text.unlines
$ Prelude.replicate 1000 "Lorem Спасибопожалусто dolor 中文測試 amet"
# NOINLINE longText #
longTextTree :: F.YiString
longTextTree = force . F.fromText . Data.Text.unlines
$ Prelude.replicate 1000 "Lorem Спасибопожалусто dolor 中文測試 amet"
# NOINLINE longTextTree #
longFRope :: F.YiString
longFRope = force (F.fromText longText)
# NOINLINE longFRope #
wideText :: Text
wideText = force . unlines
$ Prelude.replicate 10
$ Data.Text.replicate 100 "Lorem Спасибопожалусто dolor 中文測試 amet "
# NOINLINE wideText #
shortText :: Text
shortText = force . unlines
$ Prelude.replicate 3 "Lorem Спасибопожалусто dolor 中文測試 amet"
# NOINLINE shortText #
tinyText :: Text
tinyText = force $ "Lorem Спасибопожалусто dolor 中文測試 amet"
# NOINLINE tinyText #
wideFRope :: F.YiString
wideFRope = force (F.fromText wideText)
# NOINLINE wideFRope #
benchOnText :: NFData b => a -> String -> (a -> b) -> Benchmark
benchOnText text name f
= C.bench name
$ C.nf f text
benchSplitAt :: NFData a => a -> String
-> (Int -> a -> (a, a))
-> C.Benchmark
benchSplitAt text name f
= C.bench name
$ C.nf (\x -> Prelude.foldr ((fst .) . f) x [1000, 999 .. 1]) text
benchTakeDrop :: NFData a => a -> String -> (Int -> a -> a) -> C.Benchmark
benchTakeDrop text name f
= C.bench name
$ C.nf (\x -> foldr f x [1000, 999 .. 1]) text
| Chunk sizes to test with .
chunkSizes :: [Int]
chunkSizes = [1200]
wideTexts :: (Int -> String, [(Int, F.YiString)])
wideTexts = (\x -> "wide " ++ show x, mkTextSample wideText)
longTexts :: (Int -> String, [(Int, F.YiString)])
longTexts = (\x -> "long " ++ show x, mkTextSample longText)
shortTexts :: (Int -> [Char], [(Int, F.YiString)])
shortTexts = (\x -> "short " ++ show x, mkTextSample shortText)
tinyTexts :: (Int -> String, [(Int, F.YiString)])
tinyTexts = (\x -> "tiny " ++ show x, mkTextSample tinyText)
mkTextSample :: Text -> [(Int, F.YiString)]
mkTextSample s = force $ zipWith mkTexts chunkSizes (Prelude.repeat s)
where
mkTexts :: Int -> Text -> (Int, F.YiString)
mkTexts x t = (x, F.fromText' x t)
allTexts :: [(Int -> String, [(Int, F.YiString)])]
allTexts = [longTexts, wideTexts, shortTexts, tinyTexts]
allChars :: [(Int -> String, [(Int, Char)])]
allChars = map mkChar "λa"
where
mkChar c = (\x -> unwords [ "char", [c], show x ], [(1, c)])
-- | Sample usage:
--
> mkGroup " drop " F.drop allTexts benchOnText
mkGroup :: String -- ^ Group name
-> f -- ^ Function being benchmarked
-> [(chsize -> String, [(chsize, input)])]
-> (input -> String -> f -> Benchmark)
-> Benchmark
mkGroup n f subs r = bgroup n tests
where
mkTest s (l, t) = r t (s l) f
tests = Prelude.concat $ map (\(s, t) -> map (mkTest s) t) subs
onTextGroup :: NFData a => String -> (F.YiString -> a) -> Benchmark
onTextGroup n f = mkGroup n f allTexts benchOnText
onCharGroup :: NFData a => String -> (Char -> a) -> Benchmark
onCharGroup n f = mkGroup n f allChars benchOnText
onIntGroup :: String -> (Int -> F.YiString -> F.YiString) -> Benchmark
onIntGroup n f = mkGroup n f allTexts benchTakeDrop
onSplitGroup :: String
-> (Int -> F.YiString -> (F.YiString, F.YiString))
-> Benchmark
onSplitGroup n f = mkGroup n f allTexts benchSplitAt
splitBench :: [Benchmark]
splitBench =
[ onTextGroup "split none" (F.split (== '×'))
, onTextGroup "split lots" (F.split (\x -> x == 'a' || x == 'o'))
, onTextGroup "split all" (F.split (const True))
]
wordsBench :: [Benchmark]
wordsBench =
-- The replicate here inflates the benchmark like mad, should be
-- moved out.
[ onTextGroup "unwords" (\x -> F.unwords (Prelude.replicate 100 x))
, onTextGroup "words" F.words
]
spanBreakBench :: [Benchmark]
spanBreakBench =
[ onTextGroup "spanTrue" $ F.span (const True)
, onTextGroup "spanFalse" $ F.span (const False)
, onTextGroup "spanSpace" $ F.span isSpace
, onTextGroup "breakTrue" $ F.break (const True)
, onTextGroup "breakFalse" $ F.break (const False)
, onTextGroup "breakSpace" $ F.break isSpace
]
foldBench :: [Benchmark]
foldBench =
[ onTextGroup "foldCount" $ F.foldl' (\x _ -> x + 1) (0 :: Integer)
, onTextGroup "foldId" $ F.foldl' F.snoc F.empty
, onTextGroup "foldReverse" $ F.foldl' (\x y -> F.cons y x) F.empty
]
main :: IO ()
main = defaultMain $
[ onIntGroup "drop" F.drop
, onIntGroup "take" F.take
, onTextGroup "cons" (F.cons 'λ')
, onTextGroup "snoc" (`F.snoc` 'λ')
, onCharGroup "singleton" F.singleton
, onTextGroup "countNewLines" F.countNewLines
, onTextGroup "lines" F.lines
, onTextGroup "lines'" F.lines'
, onSplitGroup "splitAt" F.splitAt
, onSplitGroup "splitAtLine" F.splitAtLine
, onTextGroup "toReverseString" F.toReverseString
, onTextGroup "toReverseText" F.toReverseText
, onTextGroup "toText" F.toText
, onTextGroup "length" F.length
, onTextGroup "reverse" F.reverse
, onTextGroup "null" F.null
, onTextGroup "empty" $ const F.empty
, onTextGroup "append" (\x -> F.append x x)
, onTextGroup "concat x100" $ F.concat . Prelude.replicate 100
, onTextGroup "any OK, (== '中')" $ F.any (== '中')
, onTextGroup "any bad, (== '×')" $ F.any (== '×')
, onTextGroup "all OK (/= '×')" $ F.all (== '×')
, onTextGroup "all bad, (== '中')" $ F.all (== '中')
, onTextGroup "init" F.init
, onTextGroup "tail" F.tail
, onTextGroup "replicate 50" (F.replicate 50)
] ++ splitBench
++ wordsBench
++ spanBreakBench
++ foldBench | null | https://raw.githubusercontent.com/yi-editor/yi-rope/f3b925e2f4c55092957cecc3c037f36baff582bb/bench/MainBenchmarkSuite.hs | haskell | # LANGUAGE OverloadedStrings #
| Sample usage:
^ Group name
^ Function being benchmarked
The replicate here inflates the benchmark like mad, should be
moved out. | # OPTIONS_GHC -fno - warn - orphans #
module Main where
import Data.Char (isSpace)
import Control.DeepSeq
import Criterion.Main
import qualified Criterion.Main as C
import Data.Text (unlines, Text, replicate)
import Prelude hiding (unlines)
import qualified Yi.Rope as F
longText :: Text
longText = force . Data.Text.unlines
$ Prelude.replicate 1000 "Lorem Спасибопожалусто dolor 中文測試 amet"
# NOINLINE longText #
longTextTree :: F.YiString
longTextTree = force . F.fromText . Data.Text.unlines
$ Prelude.replicate 1000 "Lorem Спасибопожалусто dolor 中文測試 amet"
# NOINLINE longTextTree #
longFRope :: F.YiString
longFRope = force (F.fromText longText)
# NOINLINE longFRope #
wideText :: Text
wideText = force . unlines
$ Prelude.replicate 10
$ Data.Text.replicate 100 "Lorem Спасибопожалусто dolor 中文測試 amet "
# NOINLINE wideText #
shortText :: Text
shortText = force . unlines
$ Prelude.replicate 3 "Lorem Спасибопожалусто dolor 中文測試 amet"
# NOINLINE shortText #
tinyText :: Text
tinyText = force $ "Lorem Спасибопожалусто dolor 中文測試 amet"
# NOINLINE tinyText #
wideFRope :: F.YiString
wideFRope = force (F.fromText wideText)
# NOINLINE wideFRope #
benchOnText :: NFData b => a -> String -> (a -> b) -> Benchmark
benchOnText text name f
= C.bench name
$ C.nf f text
benchSplitAt :: NFData a => a -> String
-> (Int -> a -> (a, a))
-> C.Benchmark
benchSplitAt text name f
= C.bench name
$ C.nf (\x -> Prelude.foldr ((fst .) . f) x [1000, 999 .. 1]) text
benchTakeDrop :: NFData a => a -> String -> (Int -> a -> a) -> C.Benchmark
benchTakeDrop text name f
= C.bench name
$ C.nf (\x -> foldr f x [1000, 999 .. 1]) text
| Chunk sizes to test with .
chunkSizes :: [Int]
chunkSizes = [1200]
wideTexts :: (Int -> String, [(Int, F.YiString)])
wideTexts = (\x -> "wide " ++ show x, mkTextSample wideText)
longTexts :: (Int -> String, [(Int, F.YiString)])
longTexts = (\x -> "long " ++ show x, mkTextSample longText)
shortTexts :: (Int -> [Char], [(Int, F.YiString)])
shortTexts = (\x -> "short " ++ show x, mkTextSample shortText)
tinyTexts :: (Int -> String, [(Int, F.YiString)])
tinyTexts = (\x -> "tiny " ++ show x, mkTextSample tinyText)
mkTextSample :: Text -> [(Int, F.YiString)]
mkTextSample s = force $ zipWith mkTexts chunkSizes (Prelude.repeat s)
where
mkTexts :: Int -> Text -> (Int, F.YiString)
mkTexts x t = (x, F.fromText' x t)
allTexts :: [(Int -> String, [(Int, F.YiString)])]
allTexts = [longTexts, wideTexts, shortTexts, tinyTexts]
allChars :: [(Int -> String, [(Int, Char)])]
allChars = map mkChar "λa"
where
mkChar c = (\x -> unwords [ "char", [c], show x ], [(1, c)])
> mkGroup " drop " F.drop allTexts benchOnText
-> [(chsize -> String, [(chsize, input)])]
-> (input -> String -> f -> Benchmark)
-> Benchmark
mkGroup n f subs r = bgroup n tests
where
mkTest s (l, t) = r t (s l) f
tests = Prelude.concat $ map (\(s, t) -> map (mkTest s) t) subs
onTextGroup :: NFData a => String -> (F.YiString -> a) -> Benchmark
onTextGroup n f = mkGroup n f allTexts benchOnText
onCharGroup :: NFData a => String -> (Char -> a) -> Benchmark
onCharGroup n f = mkGroup n f allChars benchOnText
onIntGroup :: String -> (Int -> F.YiString -> F.YiString) -> Benchmark
onIntGroup n f = mkGroup n f allTexts benchTakeDrop
onSplitGroup :: String
-> (Int -> F.YiString -> (F.YiString, F.YiString))
-> Benchmark
onSplitGroup n f = mkGroup n f allTexts benchSplitAt
splitBench :: [Benchmark]
splitBench =
[ onTextGroup "split none" (F.split (== '×'))
, onTextGroup "split lots" (F.split (\x -> x == 'a' || x == 'o'))
, onTextGroup "split all" (F.split (const True))
]
wordsBench :: [Benchmark]
wordsBench =
[ onTextGroup "unwords" (\x -> F.unwords (Prelude.replicate 100 x))
, onTextGroup "words" F.words
]
spanBreakBench :: [Benchmark]
spanBreakBench =
[ onTextGroup "spanTrue" $ F.span (const True)
, onTextGroup "spanFalse" $ F.span (const False)
, onTextGroup "spanSpace" $ F.span isSpace
, onTextGroup "breakTrue" $ F.break (const True)
, onTextGroup "breakFalse" $ F.break (const False)
, onTextGroup "breakSpace" $ F.break isSpace
]
foldBench :: [Benchmark]
foldBench =
[ onTextGroup "foldCount" $ F.foldl' (\x _ -> x + 1) (0 :: Integer)
, onTextGroup "foldId" $ F.foldl' F.snoc F.empty
, onTextGroup "foldReverse" $ F.foldl' (\x y -> F.cons y x) F.empty
]
main :: IO ()
main = defaultMain $
[ onIntGroup "drop" F.drop
, onIntGroup "take" F.take
, onTextGroup "cons" (F.cons 'λ')
, onTextGroup "snoc" (`F.snoc` 'λ')
, onCharGroup "singleton" F.singleton
, onTextGroup "countNewLines" F.countNewLines
, onTextGroup "lines" F.lines
, onTextGroup "lines'" F.lines'
, onSplitGroup "splitAt" F.splitAt
, onSplitGroup "splitAtLine" F.splitAtLine
, onTextGroup "toReverseString" F.toReverseString
, onTextGroup "toReverseText" F.toReverseText
, onTextGroup "toText" F.toText
, onTextGroup "length" F.length
, onTextGroup "reverse" F.reverse
, onTextGroup "null" F.null
, onTextGroup "empty" $ const F.empty
, onTextGroup "append" (\x -> F.append x x)
, onTextGroup "concat x100" $ F.concat . Prelude.replicate 100
, onTextGroup "any OK, (== '中')" $ F.any (== '中')
, onTextGroup "any bad, (== '×')" $ F.any (== '×')
, onTextGroup "all OK (/= '×')" $ F.all (== '×')
, onTextGroup "all bad, (== '中')" $ F.all (== '中')
, onTextGroup "init" F.init
, onTextGroup "tail" F.tail
, onTextGroup "replicate 50" (F.replicate 50)
] ++ splitBench
++ wordsBench
++ spanBreakBench
++ foldBench |
58329f37f9b7acaef48dba8a97dec29e2c2e4814308f7c412e698d2029401b09 | mcorbin/tour-of-clojure | loop.clj | (ns tourofclojure.pages.loop
(:require [hiccup.element :refer [link-to]]
[clojure.java.io :as io]
[tourofclojure.pages.util :refer [navigation-block]]))
(def code
(slurp (io/resource "public/pages/code/loop.clj")))
(defn desc
[previous next lang]
(condp = lang
"fr" [:div
[:h2 "loop"]
[:p "La récursivité en Clojure pose le même problème qu'en Java ou"
" en JavaScript: la stack overflow."]
[:p [:b "loop"] " permet de réaliser de manière sûre ce genre de"
" récursion. Tout d'abord, " [:b "loop"] " ressemble à " [:b "let"]
" car la même syntaxe est utilisée pour définir une ou des valeurs"
" initiales."]
[:p "Ensuite, loop prendra une form. Cette form contiendra"
" généralement une condition d'arrêt, et le mot clé " [:b "recur"] "."]
[:p [:b "recur"] " fera revenir l'exécution au début de " [:b "loop"] ","
" sauf que les valeurs par des variables déclarés vaudront maintenant"
" les paramètres passés à " [:b "recur"] " et non les valeurs initiales."]
[:p "La condition d'arrêt est là pour arrêter l'exécution et retourner un"
" résultat."]
[:h3 "Exemple détaillé"]
[:p "Prenons par exemple le code suivant:"]
[:pre [:code "(loop [counter 5
result []]
(if (= counter 0)
(println result "\n")
(recur (dec counter)
(conj result counter))))"]]
[:p "L'exécution peut être visualisée comme suit:"]
[:ul
[:li [:p "Au début, les variables " [:b "counter"] " et " [:b "result"]
" valent respectivement " [:b "5"] " et " [:b "[]"] "."]]
[:li [:b "counter"] " n'est pas égal à " [:b "0"] ", " [:b "recur"] " est"
" donc appelé avec les résultats de " [:b "(dec counter)"] " et "
[:b "(conj result counter)"] ", c'est à dire " [:b "(recur 4 [5])"] "."]
[:li [:b "recur"] " ayant été appelé, nous revenons au début de "
[:b "loop"] " sauf que maintenant " [:b "counter"] " vaudra " [:b "4"]
" et " [:b "result"] " vaudra " [:b "[5]"] "."]
[:li [:b "counter"] " n'est toujours pas égal à " [:b "0"] ", "
[:b "recur"] " est donc rappelé avec les nouveaux résultats "
"de " [:b "(dec counter)"] " et " [:b "(conj result counter)"] ", c'est"
" à dire " [:b "(recur 3 [5 4])"] "."]
[:li "L'itération se répète jusqu'à ce que " [:b "counter"] " soit"
" à " [:b "0"] ". A ce moment là, " [:b "recur"] " n'est pas appelé"
", on appelle " [:b "println"] " et l'on sort de la loop."]]
[:p [:b "loop"] " est une construction intéressante, mais en Clojure"
" son utilisation est très limitée. Il est plus intéressant d'utiliser"
" des fonctions comme " [:b "map"] ", " [:b "reduce"] " ou " [:b "filter"]
" que nous verrons dans la suite de ce tutoriel."]
(navigation-block previous next)]
[:h2 "Language not supported."]))
(defn page
[previous next lang]
[(desc previous next lang)
code])
| null | https://raw.githubusercontent.com/mcorbin/tour-of-clojure/57f97b68ca1a8c96904bfb960f515217eeda24a6/src/tourofclojure/pages/loop.clj | clojure | (ns tourofclojure.pages.loop
(:require [hiccup.element :refer [link-to]]
[clojure.java.io :as io]
[tourofclojure.pages.util :refer [navigation-block]]))
(def code
(slurp (io/resource "public/pages/code/loop.clj")))
(defn desc
[previous next lang]
(condp = lang
"fr" [:div
[:h2 "loop"]
[:p "La récursivité en Clojure pose le même problème qu'en Java ou"
" en JavaScript: la stack overflow."]
[:p [:b "loop"] " permet de réaliser de manière sûre ce genre de"
" récursion. Tout d'abord, " [:b "loop"] " ressemble à " [:b "let"]
" car la même syntaxe est utilisée pour définir une ou des valeurs"
" initiales."]
[:p "Ensuite, loop prendra une form. Cette form contiendra"
" généralement une condition d'arrêt, et le mot clé " [:b "recur"] "."]
[:p [:b "recur"] " fera revenir l'exécution au début de " [:b "loop"] ","
" sauf que les valeurs par des variables déclarés vaudront maintenant"
" les paramètres passés à " [:b "recur"] " et non les valeurs initiales."]
[:p "La condition d'arrêt est là pour arrêter l'exécution et retourner un"
" résultat."]
[:h3 "Exemple détaillé"]
[:p "Prenons par exemple le code suivant:"]
[:pre [:code "(loop [counter 5
result []]
(if (= counter 0)
(println result "\n")
(recur (dec counter)
(conj result counter))))"]]
[:p "L'exécution peut être visualisée comme suit:"]
[:ul
[:li [:p "Au début, les variables " [:b "counter"] " et " [:b "result"]
" valent respectivement " [:b "5"] " et " [:b "[]"] "."]]
[:li [:b "counter"] " n'est pas égal à " [:b "0"] ", " [:b "recur"] " est"
" donc appelé avec les résultats de " [:b "(dec counter)"] " et "
[:b "(conj result counter)"] ", c'est à dire " [:b "(recur 4 [5])"] "."]
[:li [:b "recur"] " ayant été appelé, nous revenons au début de "
[:b "loop"] " sauf que maintenant " [:b "counter"] " vaudra " [:b "4"]
" et " [:b "result"] " vaudra " [:b "[5]"] "."]
[:li [:b "counter"] " n'est toujours pas égal à " [:b "0"] ", "
[:b "recur"] " est donc rappelé avec les nouveaux résultats "
"de " [:b "(dec counter)"] " et " [:b "(conj result counter)"] ", c'est"
" à dire " [:b "(recur 3 [5 4])"] "."]
[:li "L'itération se répète jusqu'à ce que " [:b "counter"] " soit"
" à " [:b "0"] ". A ce moment là, " [:b "recur"] " n'est pas appelé"
", on appelle " [:b "println"] " et l'on sort de la loop."]]
[:p [:b "loop"] " est une construction intéressante, mais en Clojure"
" son utilisation est très limitée. Il est plus intéressant d'utiliser"
" des fonctions comme " [:b "map"] ", " [:b "reduce"] " ou " [:b "filter"]
" que nous verrons dans la suite de ce tutoriel."]
(navigation-block previous next)]
[:h2 "Language not supported."]))
(defn page
[previous next lang]
[(desc previous next lang)
code])
| |
660d5d4899e357acd87e2019518657a3418adfb31923a4b28fbcec36f587d553 | jackfirth/rebellion | range-set-interface.rkt | #lang racket/base
(require racket/contract/base)
(provide
(contract-out
[range-set? predicate/c]
[immutable-range-set? predicate/c]
[mutable-range-set? predicate/c]
[in-range-set (->* (range-set?) (#:descending? boolean?) (sequence/c nonempty-range?))]
[range-set-comparator (-> range-set? comparator?)]
[range-set-empty? (-> range-set? boolean?)]
[range-set-size (-> range-set? exact-nonnegative-integer?)]
[range-set-contains? (-> range-set? any/c boolean?)]
[range-set-contains-all? (-> range-set? (sequence/c any/c) boolean?)]
[range-set-encloses? (-> range-set? range? boolean?)]
[range-set-encloses-all? (-> range-set? (sequence/c range?) boolean?)]
[range-set-intersects? (-> range-set? range? boolean?)]
[range-set-range-containing (->* (range-set? any/c) (failure-result/c) any)]
[range-set-range-containing-or-absent (-> range-set? any/c (option/c range?))]
[range-set-span (->* (range-set?) (failure-result/c) any)]
[range-set-span-or-absent (-> range-set? (option/c range?))]
[range-set-add (-> immutable-range-set? range? immutable-range-set?)]
[range-set-add! (-> mutable-range-set? range? void?)]
[range-set-add-all (-> immutable-range-set? (sequence/c range?) immutable-range-set?)]
[range-set-add-all! (-> mutable-range-set? (sequence/c range?) void?)]
[range-set-remove (-> immutable-range-set? range? immutable-range-set?)]
[range-set-remove! (-> mutable-range-set? range? void?)]
[range-set-remove-all (-> immutable-range-set? (sequence/c range?) immutable-range-set?)]
[range-set-remove-all! (-> mutable-range-set? (sequence/c range?) void?)]
[range-set-clear! (-> mutable-range-set? void?)]
[range-subset (-> range-set? range? range-set?)]))
;; The APIs for creating the generic, extensible hierarchy of collection implementations exist only to
make it easier to organize Rebellion 's various implementations . They are * not * designed for
;; external consumption, and no promises of API stability or quality are made. Please do not make your
;; own implementations of these interfaces; instead file an issue at
;; describing your use case. These APIs might be made
;; public in the future, depending on feedback from users.
(module+ private-for-rebellion-only
(provide
(struct-out abstract-range-set)
(struct-out abstract-mutable-range-set)
(struct-out abstract-immutable-range-set)
gen:range-set
gen:mutable-range-set
gen:immutable-range-set
(contract-out
[default-range-set-value-not-contained-failure-result (-> any/c range-set? failure-result/c)]
[default-empty-range-set-span-failure-result failure-result/c])))
(require racket/generic
racket/match
racket/sequence
racket/unsafe/ops
rebellion/base/comparator
rebellion/base/option
rebellion/base/range
rebellion/private/guarded-block
rebellion/private/printer-markup
rebellion/private/static-name)
;@----------------------------------------------------------------------------------------------------
This is the API for * unmodifiable * range sets . Unmodifiable range sets do not expose an API for
;; clients to mutate them, but they make no guarantees that they will not mutate of their own accord.
For example , one module may wish to provide an * unmodifiable view * of a mutable range set to
;; clients to prevent uncontrolled external mutation. Such a view is unmodifiable, but not immutable,
;; as the underlying map backing the view may mutate.
(define-generics range-set
;; descending? should always default to false
(in-range-set range-set #:descending? [descending?])
(range-set-comparator range-set)
(range-set-empty? range-set)
(range-set-size range-set)
(range-set-contains? range-set value)
(range-set-contains-all? range-set values)
(range-set-encloses? range-set range)
(range-set-encloses-all? range-set ranges)
(range-set-intersects? range-set range)
(range-set-range-containing range-set value [failure-result])
(range-set-range-containing-or-absent range-set value)
(range-set-span range-set [failure-result])
(range-set-span-or-absent range-set)
(range-subset range-set subrange)
#:fallbacks
[(define/generic generic-size range-set-size)
(define/generic generic-contains? range-set-contains?)
(define/generic generic-encloses? range-set-encloses?)
(define/generic generic-range-containing-or-absent range-set-range-containing-or-absent)
(define/generic generic-span-or-absent range-set-span-or-absent)
(define (range-set-empty? this)
(zero? (generic-size this)))
(define (range-set-contains-all? this values)
(for/and ([value values])
(generic-contains? this value)))
(define (range-set-encloses-all? this ranges)
(for/and ([range ranges])
(generic-encloses? this range)))
(define
(range-set-range-containing
this
value
[failure-result (default-range-set-value-not-contained-failure-result this value)])
(match (generic-range-containing-or-absent this value)
[(present range) range]
[(== absent) (if (procedure? failure-result) (failure-result) failure-result)]))
(define (range-set-span this [failure-result default-empty-range-set-span-failure-result])
(match (generic-span-or-absent this)
[(present span) span]
[(== absent) (if (procedure? failure-result) (failure-result) failure-result)]))])
(define ((default-range-set-value-not-contained-failure-result range-set value))
(define message
(format "~a: no range containing value;\n ranges: ~e value: ~e\n"
(name range-set-range-containing) range-set value))
(raise (make-exn:fail:contract message (current-continuation-marks))))
(define (default-empty-range-set-span-failure-result)
(define message
(format "~a: range set is empty and has no span" (name range-set-span)))
(raise (make-exn:fail:contract message (current-continuation-marks))))
;; Subtypes must implement the gen:range-set interface.
(struct abstract-range-set ()
#:property prop:sequence in-range-set
#:methods gen:custom-write
[(define write-proc (make-constructor-style-printer-with-markup 'range-set in-range-set))])
;@----------------------------------------------------------------------------------------------------
(define-generics immutable-range-set
(range-set-add immutable-range-set range)
(range-set-add-all immutable-range-set ranges)
(range-set-remove immutable-range-set range)
(range-set-remove-all immutable-range-set ranges)
#:fallbacks
[(define/generic generic-add range-set-add)
(define/generic generic-remove range-set-remove)
(define (range-set-add-all this ranges)
(for/fold ([this this])
([range ranges])
(generic-add this range)))
(define (range-set-remove-all this ranges)
(for/fold ([this this])
([range ranges])
(generic-remove this range)))])
;; Subtypes must implement the gen:range-set interface *and* the gen:immutable-range-set interface.
(struct abstract-immutable-range-set abstract-range-set ()
#:methods gen:custom-write
[(define write-proc
(make-constructor-style-printer-with-markup 'immutable-range-set in-range-set))]
Immutable range sets are always compared structurally . Two immutable range sets are equal if
;; they use equal comparators and they contain the same ranges.
#:methods gen:equal+hash
[(define/guard (equal-proc this other recur)
(guard (recur (range-set-comparator this) (range-set-comparator other)) else
#false)
;; We check emptiness as a fast path, since empty collections are common in practice and
;; easy to optimize for.
(guard (range-set-empty? this) then
(range-set-empty? other))
(guard (range-set-empty? other) then
#false)
;; We check the size before comparing elements so that we can avoid paying the O(n) range
;; comparison cost most of the time.
(and (recur (range-set-size this) (range-set-size other))
(for/and ([this-range (in-range-set this)]
[other-range (in-range-set other)])
(recur this-range other-range))))
(define (hash-proc this recur)
(for/fold ([hash-code (recur (range-set-comparator this))])
([range (in-range-set this)])
(unsafe-fx+/wraparound hash-code (recur range))))
(define hash2-proc hash-proc)])
;@----------------------------------------------------------------------------------------------------
(define-generics mutable-range-set
(range-set-add! mutable-range-set range)
(range-set-add-all! mutable-range-set ranges)
(range-set-remove! mutable-range-set range)
(range-set-remove-all! mutable-range-set ranges)
(range-set-clear! mutable-range-set)
#:fallbacks
[(define/generic generic-add! range-set-add!)
(define/generic generic-remove! range-set-remove!)
(define (range-set-add-all! this ranges)
(for ([range ranges])
(generic-add! this range)))
(define (range-set-remove-all! this ranges)
(for ([range ranges])
(generic-remove! this range)))])
;; Subtypes must implement the gen:range-set interface *and* the gen:mutable-range-set interface.
Mutable range sets do n't implement gen : equal+hash because two mutable objects should only be equal
;; if they have the same identity: that is, if mutations to one are reflected by the other. This does
;; not necessarily mean only eq? mutable objects should be equal?, as it's perfectly fine for a
;; wrapper or view of a mutable object to be equal? to that object.
(struct abstract-mutable-range-set abstract-range-set ()
#:methods gen:custom-write
[(define write-proc (make-constructor-style-printer-with-markup 'mutable-range-set in-range-set))])
| null | https://raw.githubusercontent.com/jackfirth/rebellion/69dce215e231e62889389bc40be11f5b4387b304/collection/private/range-set-interface.rkt | racket | The APIs for creating the generic, extensible hierarchy of collection implementations exist only to
external consumption, and no promises of API stability or quality are made. Please do not make your
own implementations of these interfaces; instead file an issue at
describing your use case. These APIs might be made
public in the future, depending on feedback from users.
@----------------------------------------------------------------------------------------------------
clients to mutate them, but they make no guarantees that they will not mutate of their own accord.
clients to prevent uncontrolled external mutation. Such a view is unmodifiable, but not immutable,
as the underlying map backing the view may mutate.
descending? should always default to false
Subtypes must implement the gen:range-set interface.
@----------------------------------------------------------------------------------------------------
Subtypes must implement the gen:range-set interface *and* the gen:immutable-range-set interface.
they use equal comparators and they contain the same ranges.
We check emptiness as a fast path, since empty collections are common in practice and
easy to optimize for.
We check the size before comparing elements so that we can avoid paying the O(n) range
comparison cost most of the time.
@----------------------------------------------------------------------------------------------------
Subtypes must implement the gen:range-set interface *and* the gen:mutable-range-set interface.
if they have the same identity: that is, if mutations to one are reflected by the other. This does
not necessarily mean only eq? mutable objects should be equal?, as it's perfectly fine for a
wrapper or view of a mutable object to be equal? to that object. | #lang racket/base
(require racket/contract/base)
(provide
(contract-out
[range-set? predicate/c]
[immutable-range-set? predicate/c]
[mutable-range-set? predicate/c]
[in-range-set (->* (range-set?) (#:descending? boolean?) (sequence/c nonempty-range?))]
[range-set-comparator (-> range-set? comparator?)]
[range-set-empty? (-> range-set? boolean?)]
[range-set-size (-> range-set? exact-nonnegative-integer?)]
[range-set-contains? (-> range-set? any/c boolean?)]
[range-set-contains-all? (-> range-set? (sequence/c any/c) boolean?)]
[range-set-encloses? (-> range-set? range? boolean?)]
[range-set-encloses-all? (-> range-set? (sequence/c range?) boolean?)]
[range-set-intersects? (-> range-set? range? boolean?)]
[range-set-range-containing (->* (range-set? any/c) (failure-result/c) any)]
[range-set-range-containing-or-absent (-> range-set? any/c (option/c range?))]
[range-set-span (->* (range-set?) (failure-result/c) any)]
[range-set-span-or-absent (-> range-set? (option/c range?))]
[range-set-add (-> immutable-range-set? range? immutable-range-set?)]
[range-set-add! (-> mutable-range-set? range? void?)]
[range-set-add-all (-> immutable-range-set? (sequence/c range?) immutable-range-set?)]
[range-set-add-all! (-> mutable-range-set? (sequence/c range?) void?)]
[range-set-remove (-> immutable-range-set? range? immutable-range-set?)]
[range-set-remove! (-> mutable-range-set? range? void?)]
[range-set-remove-all (-> immutable-range-set? (sequence/c range?) immutable-range-set?)]
[range-set-remove-all! (-> mutable-range-set? (sequence/c range?) void?)]
[range-set-clear! (-> mutable-range-set? void?)]
[range-subset (-> range-set? range? range-set?)]))
make it easier to organize Rebellion 's various implementations . They are * not * designed for
(module+ private-for-rebellion-only
(provide
(struct-out abstract-range-set)
(struct-out abstract-mutable-range-set)
(struct-out abstract-immutable-range-set)
gen:range-set
gen:mutable-range-set
gen:immutable-range-set
(contract-out
[default-range-set-value-not-contained-failure-result (-> any/c range-set? failure-result/c)]
[default-empty-range-set-span-failure-result failure-result/c])))
(require racket/generic
racket/match
racket/sequence
racket/unsafe/ops
rebellion/base/comparator
rebellion/base/option
rebellion/base/range
rebellion/private/guarded-block
rebellion/private/printer-markup
rebellion/private/static-name)
This is the API for * unmodifiable * range sets . Unmodifiable range sets do not expose an API for
For example , one module may wish to provide an * unmodifiable view * of a mutable range set to
(define-generics range-set
(in-range-set range-set #:descending? [descending?])
(range-set-comparator range-set)
(range-set-empty? range-set)
(range-set-size range-set)
(range-set-contains? range-set value)
(range-set-contains-all? range-set values)
(range-set-encloses? range-set range)
(range-set-encloses-all? range-set ranges)
(range-set-intersects? range-set range)
(range-set-range-containing range-set value [failure-result])
(range-set-range-containing-or-absent range-set value)
(range-set-span range-set [failure-result])
(range-set-span-or-absent range-set)
(range-subset range-set subrange)
#:fallbacks
[(define/generic generic-size range-set-size)
(define/generic generic-contains? range-set-contains?)
(define/generic generic-encloses? range-set-encloses?)
(define/generic generic-range-containing-or-absent range-set-range-containing-or-absent)
(define/generic generic-span-or-absent range-set-span-or-absent)
(define (range-set-empty? this)
(zero? (generic-size this)))
(define (range-set-contains-all? this values)
(for/and ([value values])
(generic-contains? this value)))
(define (range-set-encloses-all? this ranges)
(for/and ([range ranges])
(generic-encloses? this range)))
(define
(range-set-range-containing
this
value
[failure-result (default-range-set-value-not-contained-failure-result this value)])
(match (generic-range-containing-or-absent this value)
[(present range) range]
[(== absent) (if (procedure? failure-result) (failure-result) failure-result)]))
(define (range-set-span this [failure-result default-empty-range-set-span-failure-result])
(match (generic-span-or-absent this)
[(present span) span]
[(== absent) (if (procedure? failure-result) (failure-result) failure-result)]))])
(define ((default-range-set-value-not-contained-failure-result range-set value))
(define message
(format "~a: no range containing value;\n ranges: ~e value: ~e\n"
(name range-set-range-containing) range-set value))
(raise (make-exn:fail:contract message (current-continuation-marks))))
(define (default-empty-range-set-span-failure-result)
(define message
(format "~a: range set is empty and has no span" (name range-set-span)))
(raise (make-exn:fail:contract message (current-continuation-marks))))
(struct abstract-range-set ()
#:property prop:sequence in-range-set
#:methods gen:custom-write
[(define write-proc (make-constructor-style-printer-with-markup 'range-set in-range-set))])
(define-generics immutable-range-set
(range-set-add immutable-range-set range)
(range-set-add-all immutable-range-set ranges)
(range-set-remove immutable-range-set range)
(range-set-remove-all immutable-range-set ranges)
#:fallbacks
[(define/generic generic-add range-set-add)
(define/generic generic-remove range-set-remove)
(define (range-set-add-all this ranges)
(for/fold ([this this])
([range ranges])
(generic-add this range)))
(define (range-set-remove-all this ranges)
(for/fold ([this this])
([range ranges])
(generic-remove this range)))])
(struct abstract-immutable-range-set abstract-range-set ()
#:methods gen:custom-write
[(define write-proc
(make-constructor-style-printer-with-markup 'immutable-range-set in-range-set))]
Immutable range sets are always compared structurally . Two immutable range sets are equal if
#:methods gen:equal+hash
[(define/guard (equal-proc this other recur)
(guard (recur (range-set-comparator this) (range-set-comparator other)) else
#false)
(guard (range-set-empty? this) then
(range-set-empty? other))
(guard (range-set-empty? other) then
#false)
(and (recur (range-set-size this) (range-set-size other))
(for/and ([this-range (in-range-set this)]
[other-range (in-range-set other)])
(recur this-range other-range))))
(define (hash-proc this recur)
(for/fold ([hash-code (recur (range-set-comparator this))])
([range (in-range-set this)])
(unsafe-fx+/wraparound hash-code (recur range))))
(define hash2-proc hash-proc)])
(define-generics mutable-range-set
(range-set-add! mutable-range-set range)
(range-set-add-all! mutable-range-set ranges)
(range-set-remove! mutable-range-set range)
(range-set-remove-all! mutable-range-set ranges)
(range-set-clear! mutable-range-set)
#:fallbacks
[(define/generic generic-add! range-set-add!)
(define/generic generic-remove! range-set-remove!)
(define (range-set-add-all! this ranges)
(for ([range ranges])
(generic-add! this range)))
(define (range-set-remove-all! this ranges)
(for ([range ranges])
(generic-remove! this range)))])
Mutable range sets do n't implement gen : equal+hash because two mutable objects should only be equal
(struct abstract-mutable-range-set abstract-range-set ()
#:methods gen:custom-write
[(define write-proc (make-constructor-style-printer-with-markup 'mutable-range-set in-range-set))])
|
f767fb8b40100981c40c191aa8cf94cfaadcff907a967244aba45496627e92d7 | janestreet/merlin-jst | oprint.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
Projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2002 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open Format
open Outcometree
exception Ellipsis
let cautious f ppf arg =
try f ppf arg with
Ellipsis -> fprintf ppf "..."
let print_lident ppf = function
| "::" -> pp_print_string ppf "(::)"
| s -> pp_print_string ppf s
let rec print_ident ppf =
function
Oide_ident s -> print_lident ppf s.printed_name
| Oide_dot (id, s) ->
print_ident ppf id; pp_print_char ppf '.'; print_lident ppf s
| Oide_apply (id1, id2) ->
fprintf ppf "%a(%a)" print_ident id1 print_ident id2
let out_ident = ref print_ident
(* Check a character matches the [identchar_latin1] class from the lexer *)
let is_ident_char c =
match c with
| 'A'..'Z' | 'a'..'z' | '_' | '\192'..'\214' | '\216'..'\246'
| '\248'..'\255' | '\'' | '0'..'9' -> true
| _ -> false
let all_ident_chars s =
let rec loop s len i =
if i < len then begin
if is_ident_char s.[i] then loop s len (i+1)
else false
end else begin
true
end
in
let len = String.length s in
loop s len 0
let parenthesized_ident name =
(List.mem name ["or"; "mod"; "land"; "lor"; "lxor"; "lsl"; "lsr"; "asr"])
|| not (all_ident_chars name)
let value_ident ppf name =
if parenthesized_ident name then
fprintf ppf "( %s )" name
else
pp_print_string ppf name
(* Values *)
let valid_float_lexeme s =
let l = String.length s in
let rec loop i =
if i >= l then s ^ "." else
match s.[i] with
| '0' .. '9' | '-' -> loop (i+1)
| _ -> s
in loop 0
let float_repres f =
match classify_float f with
FP_nan -> "nan"
| FP_infinite ->
if f < 0.0 then "neg_infinity" else "infinity"
| _ ->
let float_val =
let s1 = Printf.sprintf "%.12g" f in
if f = float_of_string s1 then s1 else
let s2 = Printf.sprintf "%.15g" f in
if f = float_of_string s2 then s2 else
Printf.sprintf "%.18g" f
in valid_float_lexeme float_val
let parenthesize_if_neg ppf fmt v isneg =
if isneg then pp_print_char ppf '(';
fprintf ppf fmt v;
if isneg then pp_print_char ppf ')'
let escape_string s =
(* Escape only C0 control characters (bytes <= 0x1F), DEL(0x7F), '\\'
and '"' *)
let n = ref 0 in
for i = 0 to String.length s - 1 do
n := !n +
(match String.unsafe_get s i with
| '\"' | '\\' | '\n' | '\t' | '\r' | '\b' -> 2
| '\x00' .. '\x1F'
| '\x7F' -> 4
| _ -> 1)
done;
if !n = String.length s then s else begin
let s' = Bytes.create !n in
n := 0;
for i = 0 to String.length s - 1 do
begin match String.unsafe_get s i with
| ('\"' | '\\') as c ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n c
| '\n' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'n'
| '\t' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 't'
| '\r' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'r'
| '\b' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'b'
| '\x00' .. '\x1F' | '\x7F' as c ->
let a = Char.code c in
Bytes.unsafe_set s' !n '\\';
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + a / 100));
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + (a / 10) mod 10));
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + a mod 10));
| c -> Bytes.unsafe_set s' !n c
end;
incr n
done;
Bytes.to_string s'
end
let rec print_typlist print_elem sep ppf =
function
[] -> ()
| [ty] -> print_elem ppf ty
| ty :: tyl ->
print_elem ppf ty;
pp_print_string ppf sep;
pp_print_space ppf ();
print_typlist print_elem sep ppf tyl
let print_out_string ppf s =
let not_escaped =
(* let the user dynamically choose if strings should be escaped: *)
match Sys.getenv_opt "OCAMLTOP_UTF_8" with
| None -> true
| Some x ->
match bool_of_string_opt x with
| None -> true
| Some f -> f in
if not_escaped then
fprintf ppf "\"%s\"" (escape_string s)
else
fprintf ppf "%S" s
let print_out_value ppf tree =
let rec print_tree_1 ppf =
function
| Oval_constr (name, [param]) ->
fprintf ppf "@[<1>%a@ %a@]" print_ident name print_constr_param param
| Oval_constr (name, (_ :: _ as params)) ->
fprintf ppf "@[<1>%a@ (%a)@]" print_ident name
(print_tree_list print_tree_1 ",") params
| Oval_variant (name, Some param) ->
fprintf ppf "@[<2>`%s@ %a@]" name print_constr_param param
| tree -> print_simple_tree ppf tree
and print_constr_param ppf = function
| Oval_int i -> parenthesize_if_neg ppf "%i" i (i < 0)
| Oval_int32 i -> parenthesize_if_neg ppf "%lil" i (i < 0l)
| Oval_int64 i -> parenthesize_if_neg ppf "%LiL" i (i < 0L)
| Oval_nativeint i -> parenthesize_if_neg ppf "%nin" i (i < 0n)
| Oval_float f ->
parenthesize_if_neg ppf "%s" (float_repres f)
(f < 0.0 || 1. /. f = neg_infinity)
| Oval_string (_,_, Ostr_bytes) as tree ->
pp_print_char ppf '(';
print_simple_tree ppf tree;
pp_print_char ppf ')';
| tree -> print_simple_tree ppf tree
and print_simple_tree ppf =
function
Oval_int i -> fprintf ppf "%i" i
| Oval_int32 i -> fprintf ppf "%lil" i
| Oval_int64 i -> fprintf ppf "%LiL" i
| Oval_nativeint i -> fprintf ppf "%nin" i
| Oval_float f -> pp_print_string ppf (float_repres f)
| Oval_char c -> fprintf ppf "%C" c
| Oval_string (s, maxlen, kind) ->
begin try
let len = String.length s in
let maxlen = max maxlen 8 in (* always show a little prefix *)
let s = if len > maxlen then String.sub s 0 maxlen else s in
begin match kind with
| Ostr_bytes -> fprintf ppf "Bytes.of_string %S" s
| Ostr_string -> print_out_string ppf s
end;
(if len > maxlen then
fprintf ppf
"... (* string length %d; truncated *)" len
)
with
Invalid_argument _ (* "String.create" *)-> fprintf ppf "<huge string>"
end
| Oval_list tl ->
fprintf ppf "@[<1>[%a]@]" (print_tree_list print_tree_1 ";") tl
| Oval_array tl ->
fprintf ppf "@[<2>[|%a|]@]" (print_tree_list print_tree_1 ";") tl
| Oval_constr (name, []) -> print_ident ppf name
| Oval_variant (name, None) -> fprintf ppf "`%s" name
| Oval_stuff s -> pp_print_string ppf s
| Oval_record fel ->
fprintf ppf "@[<1>{%a}@]" (cautious (print_fields true)) fel
| Oval_ellipsis -> raise Ellipsis
| Oval_printer f -> f ppf
| Oval_tuple tree_list ->
fprintf ppf "@[<1>(%a)@]" (print_tree_list print_tree_1 ",") tree_list
| tree -> fprintf ppf "@[<1>(%a)@]" (cautious print_tree_1) tree
and print_fields first ppf =
function
[] -> ()
| (name, tree) :: fields ->
if not first then fprintf ppf ";@ ";
fprintf ppf "@[<1>%a@ =@ %a@]" print_ident name (cautious print_tree_1)
tree;
print_fields false ppf fields
and print_tree_list print_item sep ppf tree_list =
let rec print_list first ppf =
function
[] -> ()
| tree :: tree_list ->
if not first then fprintf ppf "%s@ " sep;
print_item ppf tree;
print_list false ppf tree_list
in
cautious (print_list true) ppf tree_list
in
cautious print_tree_1 ppf tree
let out_value = ref print_out_value
(* Types *)
let rec print_list_init pr sep ppf =
function
[] -> ()
| a :: l -> sep ppf; pr ppf a; print_list_init pr sep ppf l
let rec print_list pr sep ppf =
function
[] -> ()
| [a] -> pr ppf a
| a :: l -> pr ppf a; sep ppf; print_list pr sep ppf l
let pr_present =
print_list (fun ppf s -> fprintf ppf "`%s" s) (fun ppf -> fprintf ppf "@ ")
let pr_var = Pprintast.tyvar
let pr_vars =
print_list pr_var (fun ppf -> fprintf ppf "@ ")
let join_modes rm1 am2 =
match rm1, am2 with
| Oam_local, _ -> Oam_local
| _, Oam_local -> Oam_local
| Oam_unknown, _ -> Oam_unknown
| _, Oam_unknown -> Oam_unknown
| Oam_global, Oam_global -> Oam_global
let rec print_out_type_0 mode ppf =
function
| Otyp_alias (ty, s) ->
fprintf ppf "@[%a@ as %a@]" (print_out_type_0 mode) ty pr_var s
| Otyp_poly (sl, ty) ->
fprintf ppf "@[<hov 2>%a.@ %a@]"
pr_vars sl
(print_out_type_0 mode) ty
| ty ->
print_out_type_1 mode ppf ty
and print_out_type_1 mode ppf =
function
| Otyp_arrow (lab, am, ty1, rm, ty2) ->
pp_open_box ppf 0;
if lab <> "" then (pp_print_string ppf lab; pp_print_char ppf ':');
print_out_arg am ppf ty1;
pp_print_string ppf " ->";
pp_print_space ppf ();
let mode = join_modes mode am in
print_out_ret mode rm ppf ty2;
pp_close_box ppf ()
| ty ->
match mode with
| Oam_local ->
print_out_type_local mode ppf ty
| Oam_unknown -> print_out_type_2 mode ppf ty
| Oam_global -> print_out_type_2 mode ppf ty
and print_out_arg am ppf ty =
match am with
| Oam_local ->
print_out_type_local am ppf ty
| Oam_global -> print_out_type_2 am ppf ty
| Oam_unknown -> print_out_type_2 am ppf ty
and print_out_ret mode rm ppf ty =
match mode, rm with
| Oam_local, Oam_local
| Oam_global, Oam_global
| Oam_unknown, _
| _, Oam_unknown -> print_out_type_1 rm ppf ty
| _, Oam_local ->
print_out_type_local rm ppf ty
| _, Oam_global -> print_out_type_2 rm ppf ty
and print_out_type_local m ppf ty =
if Clflags.Extension.is_enabled Local then begin
pp_print_string ppf "local_";
pp_print_space ppf ();
print_out_type_2 m ppf ty
end else begin
print_out_type ppf (Otyp_attribute (ty, {oattr_name="local"}))
end
and print_out_type_2 mode ppf =
function
Otyp_tuple tyl ->
fprintf ppf "@[<0>%a@]" (print_typlist print_simple_out_type " *") tyl
| ty -> print_out_type_3 mode ppf ty
and print_out_type_3 mode ppf =
function
Otyp_class (ng, id, tyl) ->
fprintf ppf "@[%a%s#%a@]" print_typargs tyl (if ng then "_" else "")
print_ident id
| Otyp_constr (id, tyl) ->
pp_open_box ppf 0;
print_typargs ppf tyl;
print_ident ppf id;
pp_close_box ppf ()
| Otyp_object (fields, rest) ->
fprintf ppf "@[<2>< %a >@]" (print_fields rest) fields
| Otyp_stuff s -> pp_print_string ppf s
| Otyp_var (ng, s) -> pr_var ppf (if ng then "_" ^ s else s)
| Otyp_variant (non_gen, row_fields, closed, tags) ->
let print_present ppf =
function
None | Some [] -> ()
| Some l -> fprintf ppf "@;<1 -2>> @[<hov>%a@]" pr_present l
in
let print_fields ppf =
function
Ovar_fields fields ->
print_list print_row_field (fun ppf -> fprintf ppf "@;<1 -2>| ")
ppf fields
| Ovar_typ typ ->
print_simple_out_type ppf typ
in
fprintf ppf "%s@[<hov>[%s@[<hv>@[<hv>%a@]%a@]@ ]@]"
(if non_gen then "_" else "")
(if closed then if tags = None then " " else "< "
else if tags = None then "> " else "? ")
print_fields row_fields
print_present tags
| Otyp_alias _ | Otyp_poly _ | Otyp_arrow _ | Otyp_tuple _ as ty ->
pp_open_box ppf 1;
pp_print_char ppf '(';
print_out_type_0 mode ppf ty;
pp_print_char ppf ')';
pp_close_box ppf ()
| Otyp_abstract | Otyp_open
| Otyp_sum _ | Otyp_manifest (_, _) -> ()
| Otyp_record lbls -> print_record_decl ppf lbls
| Otyp_module (p, fl) ->
fprintf ppf "@[<1>(module %a" print_ident p;
let first = ref true in
List.iter
(fun (s, t) ->
let sep = if !first then (first := false; "with") else "and" in
fprintf ppf " %s type %s = %a" sep s print_out_type t
)
fl;
fprintf ppf ")@]"
| Otyp_attribute (t, attr) ->
fprintf ppf "@[<1>(%a [@@%s])@]"
(print_out_type_0 mode) t attr.oattr_name
and print_out_type ppf typ =
print_out_type_0 Oam_global ppf typ
and print_simple_out_type ppf typ =
print_out_type_3 Oam_global ppf typ
and print_record_decl ppf lbls =
fprintf ppf "{%a@;<1 -2>}"
(print_list_init print_out_label (fun ppf -> fprintf ppf "@ ")) lbls
and print_fields rest ppf =
function
[] ->
begin match rest with
Some non_gen -> fprintf ppf "%s.." (if non_gen then "_" else "")
| None -> ()
end
| [s, t] ->
fprintf ppf "%s : %a" s print_out_type t;
begin match rest with
Some _ -> fprintf ppf ";@ "
| None -> ()
end;
print_fields rest ppf []
| (s, t) :: l ->
fprintf ppf "%s : %a;@ %a" s print_out_type t (print_fields rest) l
and print_row_field ppf (l, opt_amp, tyl) =
let pr_of ppf =
if opt_amp then fprintf ppf " of@ &@ "
else if tyl <> [] then fprintf ppf " of@ "
else fprintf ppf ""
in
fprintf ppf "@[<hv 2>`%s%t%a@]" l pr_of (print_typlist print_out_type " &")
tyl
and print_typargs ppf =
function
[] -> ()
| [ty1] -> print_simple_out_type ppf ty1; pp_print_space ppf ()
| tyl ->
pp_open_box ppf 1;
pp_print_char ppf '(';
print_typlist print_out_type "," ppf tyl;
pp_print_char ppf ')';
pp_close_box ppf ();
pp_print_space ppf ()
and print_out_label ppf (name, mut_or_gbl, arg) =
if Clflags.Extension.is_enabled Local then
let flag =
match mut_or_gbl with
| Ogom_mutable -> "mutable "
| Ogom_global -> "global_ "
| Ogom_nonlocal -> "nonlocal_ "
| Ogom_immutable -> ""
in
fprintf ppf "@[<2>%s%s :@ %a@];" flag name print_out_type arg
else
match mut_or_gbl with
| Ogom_mutable -> fprintf ppf "@[mutable %s :@ %a@];" name print_out_type arg
| Ogom_immutable -> fprintf ppf "@[%s :@ %a@];" name print_out_type arg
| Ogom_global -> fprintf ppf "@[%s :@ %a@];" name print_out_type
(Otyp_attribute (arg, {oattr_name="global"}))
| Ogom_nonlocal -> fprintf ppf "@[%s :@ %a@];" name print_out_type
(Otyp_attribute (arg, {oattr_name="nonlocal"}))
let out_label = ref print_out_label
let out_type = ref print_out_type
(* Class types *)
let print_type_parameter ppf s =
if s = "_" then fprintf ppf "_" else pr_var ppf s
let type_parameter ppf (ty, (var, inj)) =
let open Asttypes in
fprintf ppf "%s%s%a"
(match var with Covariant -> "+" | Contravariant -> "-" | NoVariance -> "")
(match inj with Injective -> "!" | NoInjectivity -> "")
print_type_parameter ty
let print_out_class_params ppf =
function
[] -> ()
| tyl ->
fprintf ppf "@[<1>[%a]@]@ "
(print_list type_parameter (fun ppf -> fprintf ppf ", "))
tyl
let rec print_out_class_type ppf =
function
Octy_constr (id, tyl) ->
let pr_tyl ppf =
function
[] -> ()
| tyl ->
fprintf ppf "@[<1>[%a]@]@ " (print_typlist !out_type ",") tyl
in
fprintf ppf "@[%a%a@]" pr_tyl tyl print_ident id
| Octy_arrow (lab, ty, cty) ->
fprintf ppf "@[%s%a ->@ %a@]" (if lab <> "" then lab ^ ":" else "")
(print_out_type_2 Oam_global) ty print_out_class_type cty
| Octy_signature (self_ty, csil) ->
let pr_param ppf =
function
Some ty -> fprintf ppf "@ @[(%a)@]" !out_type ty
| None -> ()
in
fprintf ppf "@[<hv 2>@[<2>object%a@]@ %a@;<1 -2>end@]" pr_param self_ty
(print_list print_out_class_sig_item (fun ppf -> fprintf ppf "@ "))
csil
and print_out_class_sig_item ppf =
function
Ocsg_constraint (ty1, ty2) ->
fprintf ppf "@[<2>constraint %a =@ %a@]" !out_type ty1
!out_type ty2
| Ocsg_method (name, priv, virt, ty) ->
fprintf ppf "@[<2>method %s%s%s :@ %a@]"
(if priv then "private " else "") (if virt then "virtual " else "")
name !out_type ty
| Ocsg_value (name, mut, vr, ty) ->
fprintf ppf "@[<2>val %s%s%s :@ %a@]"
(if mut then "mutable " else "")
(if vr then "virtual " else "")
name !out_type ty
let out_class_type = ref print_out_class_type
Signature
let out_module_type = ref (fun _ -> failwith "Oprint.out_module_type")
let out_sig_item = ref (fun _ -> failwith "Oprint.out_sig_item")
let out_signature = ref (fun _ -> failwith "Oprint.out_signature")
let out_type_extension = ref (fun _ -> failwith "Oprint.out_type_extension")
let out_functor_parameters =
ref (fun _ -> failwith "Oprint.out_functor_parameters")
(* For anonymous functor arguments, the logic to choose between
the long-form
functor (_ : S) -> ...
and the short-form
S -> ...
is as follows: if we are already printing long-form functor arguments,
we use the long form unless all remaining functor arguments can use
the short form. (Otherwise use the short form.)
For example,
functor (X : S1) (_ : S2) (Y : S3) (_ : S4) (_ : S5) -> sig end
will get printed as
functor (X : S1) (_ : S2) (Y : S3) -> S4 -> S5 -> sig end
but
functor (_ : S1) (_ : S2) (Y : S3) (_ : S4) (_ : S5) -> sig end
gets printed as
S1 -> S2 -> functor (Y : S3) -> S4 -> S5 -> sig end
*)
(* take a module type that may be a functor type,
and return the longest prefix list of arguments
that should be printed in long form. *)
let rec collect_functor_args acc = function
| Omty_functor (param, mty_res) ->
collect_functor_args (param :: acc) mty_res
| non_functor -> (acc, non_functor)
let collect_functor_args mty =
let l, rest = collect_functor_args [] mty in
List.rev l, rest
let constructor_of_extension_constructor
(ext : out_extension_constructor) : out_constructor
=
{
ocstr_name = ext.oext_name;
ocstr_args = ext.oext_args;
ocstr_return_type = ext.oext_ret_type;
}
let split_anon_functor_arguments params =
let rec uncollect_anonymous_suffix acc rest = match acc with
| Some (None, mty_arg) :: acc ->
uncollect_anonymous_suffix acc
(Some (None, mty_arg) :: rest)
| _ :: _ | [] ->
(acc, rest)
in
let (acc, rest) = uncollect_anonymous_suffix (List.rev params) [] in
(List.rev acc, rest)
let rec print_out_module_type ppf mty =
print_out_functor ppf mty
and print_out_functor_parameters ppf l =
let print_nonanon_arg ppf = function
| None ->
fprintf ppf "()"
| Some (param, mty) ->
fprintf ppf "(%s : %a)"
(Option.value param ~default:"_")
print_out_module_type mty
in
let rec print_args ppf = function
| [] -> ()
| Some (None, mty_arg) :: l ->
fprintf ppf "%a ->@ %a"
print_simple_out_module_type mty_arg
print_args l
| _ :: _ as non_anonymous_functor ->
let args, anons = split_anon_functor_arguments non_anonymous_functor in
fprintf ppf "@[<2>functor@ %a@]@ ->@ %a"
(pp_print_list ~pp_sep:pp_print_space print_nonanon_arg) args
print_args anons
in
print_args ppf l
and print_out_functor ppf t =
let params, non_functor = collect_functor_args t in
fprintf ppf "@[<2>%a%a@]"
print_out_functor_parameters params
print_simple_out_module_type non_functor
and print_simple_out_module_type ppf =
function
Omty_abstract -> ()
| Omty_ident id -> fprintf ppf "%a" print_ident id
| Omty_signature sg ->
begin match sg with
| [] -> fprintf ppf "sig end"
| sg ->
fprintf ppf "@[<hv 2>sig@ %a@;<1 -2>end@]" print_out_signature sg
end
| Omty_alias id -> fprintf ppf "(module %a)" print_ident id
| Omty_functor _ as non_simple ->
fprintf ppf "(%a)" print_out_module_type non_simple
| Omty_hole -> fprintf ppf "_"
and print_out_signature ppf =
function
[] -> ()
| [item] -> !out_sig_item ppf item
| Osig_typext(ext, Oext_first) :: items ->
(* Gather together the extension constructors *)
let rec gather_extensions acc items =
match items with
Osig_typext(ext, Oext_next) :: items ->
gather_extensions
(constructor_of_extension_constructor ext :: acc)
items
| _ -> (List.rev acc, items)
in
let exts, items =
gather_extensions
[constructor_of_extension_constructor ext]
items
in
let te =
{ otyext_name = ext.oext_type_name;
otyext_params = ext.oext_type_params;
otyext_constructors = exts;
otyext_private = ext.oext_private }
in
fprintf ppf "%a@ %a" !out_type_extension te print_out_signature items
| item :: items ->
fprintf ppf "%a@ %a" !out_sig_item item print_out_signature items
and print_out_sig_item ppf =
function
Osig_class (vir_flag, name, params, clt, rs) ->
fprintf ppf "@[<2>%s%s@ %a%s@ :@ %a@]"
(if rs = Orec_next then "and" else "class")
(if vir_flag then " virtual" else "") print_out_class_params params
name !out_class_type clt
| Osig_class_type (vir_flag, name, params, clt, rs) ->
fprintf ppf "@[<2>%s%s@ %a%s@ =@ %a@]"
(if rs = Orec_next then "and" else "class type")
(if vir_flag then " virtual" else "") print_out_class_params params
name !out_class_type clt
| Osig_typext (ext, Oext_exception) ->
fprintf ppf "@[<2>exception %a@]"
print_out_constr (constructor_of_extension_constructor ext)
| Osig_typext (ext, _es) ->
print_out_extension_constructor ppf ext
| Osig_modtype (name, Omty_abstract) ->
fprintf ppf "@[<2>module type %s@]" name
| Osig_modtype (name, mty) ->
fprintf ppf "@[<2>module type %s =@ %a@]" name !out_module_type mty
| Osig_module (name, Omty_alias id, _) ->
fprintf ppf "@[<2>module %s =@ %a@]" name print_ident id
| Osig_module (name, mty, rs) ->
fprintf ppf "@[<2>%s %s :@ %a@]"
(match rs with Orec_not -> "module"
| Orec_first -> "module rec"
| Orec_next -> "and")
name !out_module_type mty
| Osig_type(td, rs) ->
print_out_type_decl
(match rs with
| Orec_not -> "type nonrec"
| Orec_first -> "type"
| Orec_next -> "and")
ppf td
| Osig_value vd ->
let kwd = if vd.oval_prims = [] then "val" else "external" in
let pr_prims ppf =
function
[] -> ()
| s :: sl ->
fprintf ppf "@ = \"%s\"" s;
List.iter (fun s -> fprintf ppf "@ \"%s\"" s) sl
in
fprintf ppf "@[<2>%s %a :@ %a%a%a@]" kwd value_ident vd.oval_name
!out_type vd.oval_type pr_prims vd.oval_prims
(fun ppf -> List.iter (fun a -> fprintf ppf "@ [@@@@%s]" a.oattr_name))
vd.oval_attributes
| Osig_ellipsis ->
fprintf ppf "..."
and print_out_type_decl kwd ppf td =
let print_constraints ppf =
List.iter
(fun (ty1, ty2) ->
fprintf ppf "@ @[<2>constraint %a =@ %a@]" !out_type ty1
!out_type ty2)
td.otype_cstrs
in
let type_defined ppf =
match td.otype_params with
[] -> pp_print_string ppf td.otype_name
| [param] -> fprintf ppf "@[%a@ %s@]" type_parameter param td.otype_name
| _ ->
fprintf ppf "@[(@[%a)@]@ %s@]"
(print_list type_parameter (fun ppf -> fprintf ppf ",@ "))
td.otype_params
td.otype_name
in
let print_manifest ppf =
function
Otyp_manifest (ty, _) -> fprintf ppf " =@ %a" !out_type ty
| _ -> ()
in
let print_name_params ppf =
fprintf ppf "%s %t%a" kwd type_defined print_manifest td.otype_type
in
let ty =
match td.otype_type with
Otyp_manifest (_, ty) -> ty
| _ -> td.otype_type
in
let print_private ppf = function
Asttypes.Private -> fprintf ppf " private"
| Asttypes.Public -> ()
in
let print_immediate ppf =
match td.otype_immediate with
| Unknown -> ()
| Always -> fprintf ppf " [%@%@immediate]"
| Always_on_64bits -> fprintf ppf " [%@%@immediate64]"
in
let print_unboxed ppf =
if td.otype_unboxed then fprintf ppf " [%@%@unboxed]" else ()
in
let print_out_tkind ppf = function
| Otyp_abstract -> ()
| Otyp_record lbls ->
fprintf ppf " =%a %a"
print_private td.otype_private
print_record_decl lbls
| Otyp_sum constrs ->
let variants fmt constrs =
if constrs = [] then fprintf fmt "|" else
fprintf fmt "%a" (print_list print_out_constr
(fun ppf -> fprintf ppf "@ | ")) constrs in
fprintf ppf " =%a@;<1 2>%a"
print_private td.otype_private variants constrs
| Otyp_open ->
fprintf ppf " =%a .."
print_private td.otype_private
| ty ->
fprintf ppf " =%a@;<1 2>%a"
print_private td.otype_private
!out_type ty
in
fprintf ppf "@[<2>@[<hv 2>%t%a@]%t%t%t@]"
print_name_params
print_out_tkind ty
print_constraints
print_immediate
print_unboxed
and print_simple_out_gf_type ppf (ty, gf) =
let locals_enabled = Clflags.Extension.is_enabled Local in
match gf with
| Ogf_global ->
if locals_enabled then begin
pp_print_string ppf "global_";
pp_print_space ppf ();
print_simple_out_type ppf ty
end else begin
print_out_type ppf (Otyp_attribute (ty, {oattr_name="global"}))
end
| Ogf_nonlocal ->
if locals_enabled then begin
pp_print_string ppf "nonlocal_";
pp_print_space ppf ();
print_simple_out_type ppf ty
end else begin
print_out_type ppf (Otyp_attribute (ty, {oattr_name="nonlocal"}))
end
| Ogf_unrestricted ->
print_simple_out_type ppf ty
and print_out_constr_args ppf tyl =
print_typlist print_simple_out_gf_type " *" ppf tyl
and print_out_constr ppf constr =
let {
ocstr_name = name;
ocstr_args = tyl;
ocstr_return_type = return_type;
} = constr in
let name =
match name with
# 7200
| s -> s
in
match return_type with
| None ->
begin match tyl with
| [] ->
pp_print_string ppf name
| _ ->
fprintf ppf "@[<2>%s of@ %a@]" name
print_out_constr_args tyl
end
| Some ret_type ->
begin match tyl with
| [] ->
fprintf ppf "@[<2>%s :@ %a@]" name print_simple_out_type ret_type
| _ ->
fprintf ppf "@[<2>%s :@ %a -> %a@]" name
print_out_constr_args tyl print_simple_out_type ret_type
end
and print_out_extension_constructor ppf ext =
let print_extended_type ppf =
match ext.oext_type_params with
[] -> fprintf ppf "%s" ext.oext_type_name
| [ty_param] ->
fprintf ppf "@[%a@ %s@]"
print_type_parameter
ty_param
ext.oext_type_name
| _ ->
fprintf ppf "@[(@[%a)@]@ %s@]"
(print_list print_type_parameter (fun ppf -> fprintf ppf ",@ "))
ext.oext_type_params
ext.oext_type_name
in
fprintf ppf "@[<hv 2>type %t +=%s@;<1 2>%a@]"
print_extended_type
(if ext.oext_private = Asttypes.Private then " private" else "")
print_out_constr
(constructor_of_extension_constructor ext)
and print_out_type_extension ppf te =
let print_extended_type ppf =
match te.otyext_params with
[] -> fprintf ppf "%s" te.otyext_name
| [param] ->
fprintf ppf "@[%a@ %s@]"
print_type_parameter param
te.otyext_name
| _ ->
fprintf ppf "@[(@[%a)@]@ %s@]"
(print_list print_type_parameter (fun ppf -> fprintf ppf ",@ "))
te.otyext_params
te.otyext_name
in
fprintf ppf "@[<hv 2>type %t +=%s@;<1 2>%a@]"
print_extended_type
(if te.otyext_private = Asttypes.Private then " private" else "")
(print_list print_out_constr (fun ppf -> fprintf ppf "@ | "))
te.otyext_constructors
let out_constr = ref print_out_constr
let out_constr_args = ref print_out_constr_args
let _ = out_module_type := print_out_module_type
let _ = out_signature := print_out_signature
let _ = out_sig_item := print_out_sig_item
let _ = out_type_extension := print_out_type_extension
let _ = out_functor_parameters := print_out_functor_parameters
(* Phrases *)
let print_out_exception ppf exn outv =
match exn with
Sys.Break -> fprintf ppf "Interrupted.@."
| Out_of_memory -> fprintf ppf "Out of memory during evaluation.@."
| Stack_overflow ->
fprintf ppf "Stack overflow during evaluation (looping recursion?).@."
| _ -> match Printexc.use_printers exn with
| None -> fprintf ppf "@[Exception:@ %a.@]@." !out_value outv
| Some s -> fprintf ppf "@[Exception:@ %s@]@." s
let rec print_items ppf =
function
[] -> ()
| (Osig_typext(ext, Oext_first), None) :: items ->
(* Gather together extension constructors *)
let rec gather_extensions acc items =
match items with
(Osig_typext(ext, Oext_next), None) :: items ->
gather_extensions
(constructor_of_extension_constructor ext :: acc)
items
| _ -> (List.rev acc, items)
in
let exts, items =
gather_extensions
[constructor_of_extension_constructor ext]
items
in
let te =
{ otyext_name = ext.oext_type_name;
otyext_params = ext.oext_type_params;
otyext_constructors = exts;
otyext_private = ext.oext_private }
in
fprintf ppf "@[%a@]" !out_type_extension te;
if items <> [] then fprintf ppf "@ %a" print_items items
| (tree, valopt) :: items ->
begin match valopt with
Some v ->
fprintf ppf "@[<2>%a =@ %a@]" !out_sig_item tree
!out_value v
| None -> fprintf ppf "@[%a@]" !out_sig_item tree
end;
if items <> [] then fprintf ppf "@ %a" print_items items
let print_out_phrase ppf =
function
Ophr_eval (outv, ty) ->
fprintf ppf "@[- : %a@ =@ %a@]@." !out_type ty !out_value outv
| Ophr_signature [] -> ()
| Ophr_signature items -> fprintf ppf "@[<v>%a@]@." print_items items
| Ophr_exception (exn, outv) -> print_out_exception ppf exn outv
let out_phrase = ref print_out_phrase
| null | https://raw.githubusercontent.com/janestreet/merlin-jst/980b574405617fa0dfb0b79a84a66536b46cd71b/src/ocaml/typing/oprint.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Check a character matches the [identchar_latin1] class from the lexer
Values
Escape only C0 control characters (bytes <= 0x1F), DEL(0x7F), '\\'
and '"'
let the user dynamically choose if strings should be escaped:
always show a little prefix
"String.create"
Types
Class types
For anonymous functor arguments, the logic to choose between
the long-form
functor (_ : S) -> ...
and the short-form
S -> ...
is as follows: if we are already printing long-form functor arguments,
we use the long form unless all remaining functor arguments can use
the short form. (Otherwise use the short form.)
For example,
functor (X : S1) (_ : S2) (Y : S3) (_ : S4) (_ : S5) -> sig end
will get printed as
functor (X : S1) (_ : S2) (Y : S3) -> S4 -> S5 -> sig end
but
functor (_ : S1) (_ : S2) (Y : S3) (_ : S4) (_ : S5) -> sig end
gets printed as
S1 -> S2 -> functor (Y : S3) -> S4 -> S5 -> sig end
take a module type that may be a functor type,
and return the longest prefix list of arguments
that should be printed in long form.
Gather together the extension constructors
Phrases
Gather together extension constructors | Projet Cristal , INRIA Rocquencourt
Copyright 2002 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Format
open Outcometree
exception Ellipsis
let cautious f ppf arg =
try f ppf arg with
Ellipsis -> fprintf ppf "..."
let print_lident ppf = function
| "::" -> pp_print_string ppf "(::)"
| s -> pp_print_string ppf s
let rec print_ident ppf =
function
Oide_ident s -> print_lident ppf s.printed_name
| Oide_dot (id, s) ->
print_ident ppf id; pp_print_char ppf '.'; print_lident ppf s
| Oide_apply (id1, id2) ->
fprintf ppf "%a(%a)" print_ident id1 print_ident id2
let out_ident = ref print_ident
let is_ident_char c =
match c with
| 'A'..'Z' | 'a'..'z' | '_' | '\192'..'\214' | '\216'..'\246'
| '\248'..'\255' | '\'' | '0'..'9' -> true
| _ -> false
let all_ident_chars s =
let rec loop s len i =
if i < len then begin
if is_ident_char s.[i] then loop s len (i+1)
else false
end else begin
true
end
in
let len = String.length s in
loop s len 0
let parenthesized_ident name =
(List.mem name ["or"; "mod"; "land"; "lor"; "lxor"; "lsl"; "lsr"; "asr"])
|| not (all_ident_chars name)
let value_ident ppf name =
if parenthesized_ident name then
fprintf ppf "( %s )" name
else
pp_print_string ppf name
let valid_float_lexeme s =
let l = String.length s in
let rec loop i =
if i >= l then s ^ "." else
match s.[i] with
| '0' .. '9' | '-' -> loop (i+1)
| _ -> s
in loop 0
let float_repres f =
match classify_float f with
FP_nan -> "nan"
| FP_infinite ->
if f < 0.0 then "neg_infinity" else "infinity"
| _ ->
let float_val =
let s1 = Printf.sprintf "%.12g" f in
if f = float_of_string s1 then s1 else
let s2 = Printf.sprintf "%.15g" f in
if f = float_of_string s2 then s2 else
Printf.sprintf "%.18g" f
in valid_float_lexeme float_val
let parenthesize_if_neg ppf fmt v isneg =
if isneg then pp_print_char ppf '(';
fprintf ppf fmt v;
if isneg then pp_print_char ppf ')'
let escape_string s =
let n = ref 0 in
for i = 0 to String.length s - 1 do
n := !n +
(match String.unsafe_get s i with
| '\"' | '\\' | '\n' | '\t' | '\r' | '\b' -> 2
| '\x00' .. '\x1F'
| '\x7F' -> 4
| _ -> 1)
done;
if !n = String.length s then s else begin
let s' = Bytes.create !n in
n := 0;
for i = 0 to String.length s - 1 do
begin match String.unsafe_get s i with
| ('\"' | '\\') as c ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n c
| '\n' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'n'
| '\t' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 't'
| '\r' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'r'
| '\b' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'b'
| '\x00' .. '\x1F' | '\x7F' as c ->
let a = Char.code c in
Bytes.unsafe_set s' !n '\\';
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + a / 100));
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + (a / 10) mod 10));
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + a mod 10));
| c -> Bytes.unsafe_set s' !n c
end;
incr n
done;
Bytes.to_string s'
end
let rec print_typlist print_elem sep ppf =
function
[] -> ()
| [ty] -> print_elem ppf ty
| ty :: tyl ->
print_elem ppf ty;
pp_print_string ppf sep;
pp_print_space ppf ();
print_typlist print_elem sep ppf tyl
let print_out_string ppf s =
let not_escaped =
match Sys.getenv_opt "OCAMLTOP_UTF_8" with
| None -> true
| Some x ->
match bool_of_string_opt x with
| None -> true
| Some f -> f in
if not_escaped then
fprintf ppf "\"%s\"" (escape_string s)
else
fprintf ppf "%S" s
let print_out_value ppf tree =
let rec print_tree_1 ppf =
function
| Oval_constr (name, [param]) ->
fprintf ppf "@[<1>%a@ %a@]" print_ident name print_constr_param param
| Oval_constr (name, (_ :: _ as params)) ->
fprintf ppf "@[<1>%a@ (%a)@]" print_ident name
(print_tree_list print_tree_1 ",") params
| Oval_variant (name, Some param) ->
fprintf ppf "@[<2>`%s@ %a@]" name print_constr_param param
| tree -> print_simple_tree ppf tree
and print_constr_param ppf = function
| Oval_int i -> parenthesize_if_neg ppf "%i" i (i < 0)
| Oval_int32 i -> parenthesize_if_neg ppf "%lil" i (i < 0l)
| Oval_int64 i -> parenthesize_if_neg ppf "%LiL" i (i < 0L)
| Oval_nativeint i -> parenthesize_if_neg ppf "%nin" i (i < 0n)
| Oval_float f ->
parenthesize_if_neg ppf "%s" (float_repres f)
(f < 0.0 || 1. /. f = neg_infinity)
| Oval_string (_,_, Ostr_bytes) as tree ->
pp_print_char ppf '(';
print_simple_tree ppf tree;
pp_print_char ppf ')';
| tree -> print_simple_tree ppf tree
and print_simple_tree ppf =
function
Oval_int i -> fprintf ppf "%i" i
| Oval_int32 i -> fprintf ppf "%lil" i
| Oval_int64 i -> fprintf ppf "%LiL" i
| Oval_nativeint i -> fprintf ppf "%nin" i
| Oval_float f -> pp_print_string ppf (float_repres f)
| Oval_char c -> fprintf ppf "%C" c
| Oval_string (s, maxlen, kind) ->
begin try
let len = String.length s in
let s = if len > maxlen then String.sub s 0 maxlen else s in
begin match kind with
| Ostr_bytes -> fprintf ppf "Bytes.of_string %S" s
| Ostr_string -> print_out_string ppf s
end;
(if len > maxlen then
fprintf ppf
"... (* string length %d; truncated *)" len
)
with
end
| Oval_list tl ->
fprintf ppf "@[<1>[%a]@]" (print_tree_list print_tree_1 ";") tl
| Oval_array tl ->
fprintf ppf "@[<2>[|%a|]@]" (print_tree_list print_tree_1 ";") tl
| Oval_constr (name, []) -> print_ident ppf name
| Oval_variant (name, None) -> fprintf ppf "`%s" name
| Oval_stuff s -> pp_print_string ppf s
| Oval_record fel ->
fprintf ppf "@[<1>{%a}@]" (cautious (print_fields true)) fel
| Oval_ellipsis -> raise Ellipsis
| Oval_printer f -> f ppf
| Oval_tuple tree_list ->
fprintf ppf "@[<1>(%a)@]" (print_tree_list print_tree_1 ",") tree_list
| tree -> fprintf ppf "@[<1>(%a)@]" (cautious print_tree_1) tree
and print_fields first ppf =
function
[] -> ()
| (name, tree) :: fields ->
if not first then fprintf ppf ";@ ";
fprintf ppf "@[<1>%a@ =@ %a@]" print_ident name (cautious print_tree_1)
tree;
print_fields false ppf fields
and print_tree_list print_item sep ppf tree_list =
let rec print_list first ppf =
function
[] -> ()
| tree :: tree_list ->
if not first then fprintf ppf "%s@ " sep;
print_item ppf tree;
print_list false ppf tree_list
in
cautious (print_list true) ppf tree_list
in
cautious print_tree_1 ppf tree
let out_value = ref print_out_value
let rec print_list_init pr sep ppf =
function
[] -> ()
| a :: l -> sep ppf; pr ppf a; print_list_init pr sep ppf l
let rec print_list pr sep ppf =
function
[] -> ()
| [a] -> pr ppf a
| a :: l -> pr ppf a; sep ppf; print_list pr sep ppf l
let pr_present =
print_list (fun ppf s -> fprintf ppf "`%s" s) (fun ppf -> fprintf ppf "@ ")
let pr_var = Pprintast.tyvar
let pr_vars =
print_list pr_var (fun ppf -> fprintf ppf "@ ")
let join_modes rm1 am2 =
match rm1, am2 with
| Oam_local, _ -> Oam_local
| _, Oam_local -> Oam_local
| Oam_unknown, _ -> Oam_unknown
| _, Oam_unknown -> Oam_unknown
| Oam_global, Oam_global -> Oam_global
let rec print_out_type_0 mode ppf =
function
| Otyp_alias (ty, s) ->
fprintf ppf "@[%a@ as %a@]" (print_out_type_0 mode) ty pr_var s
| Otyp_poly (sl, ty) ->
fprintf ppf "@[<hov 2>%a.@ %a@]"
pr_vars sl
(print_out_type_0 mode) ty
| ty ->
print_out_type_1 mode ppf ty
and print_out_type_1 mode ppf =
function
| Otyp_arrow (lab, am, ty1, rm, ty2) ->
pp_open_box ppf 0;
if lab <> "" then (pp_print_string ppf lab; pp_print_char ppf ':');
print_out_arg am ppf ty1;
pp_print_string ppf " ->";
pp_print_space ppf ();
let mode = join_modes mode am in
print_out_ret mode rm ppf ty2;
pp_close_box ppf ()
| ty ->
match mode with
| Oam_local ->
print_out_type_local mode ppf ty
| Oam_unknown -> print_out_type_2 mode ppf ty
| Oam_global -> print_out_type_2 mode ppf ty
and print_out_arg am ppf ty =
match am with
| Oam_local ->
print_out_type_local am ppf ty
| Oam_global -> print_out_type_2 am ppf ty
| Oam_unknown -> print_out_type_2 am ppf ty
and print_out_ret mode rm ppf ty =
match mode, rm with
| Oam_local, Oam_local
| Oam_global, Oam_global
| Oam_unknown, _
| _, Oam_unknown -> print_out_type_1 rm ppf ty
| _, Oam_local ->
print_out_type_local rm ppf ty
| _, Oam_global -> print_out_type_2 rm ppf ty
and print_out_type_local m ppf ty =
if Clflags.Extension.is_enabled Local then begin
pp_print_string ppf "local_";
pp_print_space ppf ();
print_out_type_2 m ppf ty
end else begin
print_out_type ppf (Otyp_attribute (ty, {oattr_name="local"}))
end
and print_out_type_2 mode ppf =
function
Otyp_tuple tyl ->
fprintf ppf "@[<0>%a@]" (print_typlist print_simple_out_type " *") tyl
| ty -> print_out_type_3 mode ppf ty
and print_out_type_3 mode ppf =
function
Otyp_class (ng, id, tyl) ->
fprintf ppf "@[%a%s#%a@]" print_typargs tyl (if ng then "_" else "")
print_ident id
| Otyp_constr (id, tyl) ->
pp_open_box ppf 0;
print_typargs ppf tyl;
print_ident ppf id;
pp_close_box ppf ()
| Otyp_object (fields, rest) ->
fprintf ppf "@[<2>< %a >@]" (print_fields rest) fields
| Otyp_stuff s -> pp_print_string ppf s
| Otyp_var (ng, s) -> pr_var ppf (if ng then "_" ^ s else s)
| Otyp_variant (non_gen, row_fields, closed, tags) ->
let print_present ppf =
function
None | Some [] -> ()
| Some l -> fprintf ppf "@;<1 -2>> @[<hov>%a@]" pr_present l
in
let print_fields ppf =
function
Ovar_fields fields ->
print_list print_row_field (fun ppf -> fprintf ppf "@;<1 -2>| ")
ppf fields
| Ovar_typ typ ->
print_simple_out_type ppf typ
in
fprintf ppf "%s@[<hov>[%s@[<hv>@[<hv>%a@]%a@]@ ]@]"
(if non_gen then "_" else "")
(if closed then if tags = None then " " else "< "
else if tags = None then "> " else "? ")
print_fields row_fields
print_present tags
| Otyp_alias _ | Otyp_poly _ | Otyp_arrow _ | Otyp_tuple _ as ty ->
pp_open_box ppf 1;
pp_print_char ppf '(';
print_out_type_0 mode ppf ty;
pp_print_char ppf ')';
pp_close_box ppf ()
| Otyp_abstract | Otyp_open
| Otyp_sum _ | Otyp_manifest (_, _) -> ()
| Otyp_record lbls -> print_record_decl ppf lbls
| Otyp_module (p, fl) ->
fprintf ppf "@[<1>(module %a" print_ident p;
let first = ref true in
List.iter
(fun (s, t) ->
let sep = if !first then (first := false; "with") else "and" in
fprintf ppf " %s type %s = %a" sep s print_out_type t
)
fl;
fprintf ppf ")@]"
| Otyp_attribute (t, attr) ->
fprintf ppf "@[<1>(%a [@@%s])@]"
(print_out_type_0 mode) t attr.oattr_name
and print_out_type ppf typ =
print_out_type_0 Oam_global ppf typ
and print_simple_out_type ppf typ =
print_out_type_3 Oam_global ppf typ
and print_record_decl ppf lbls =
fprintf ppf "{%a@;<1 -2>}"
(print_list_init print_out_label (fun ppf -> fprintf ppf "@ ")) lbls
and print_fields rest ppf =
function
[] ->
begin match rest with
Some non_gen -> fprintf ppf "%s.." (if non_gen then "_" else "")
| None -> ()
end
| [s, t] ->
fprintf ppf "%s : %a" s print_out_type t;
begin match rest with
Some _ -> fprintf ppf ";@ "
| None -> ()
end;
print_fields rest ppf []
| (s, t) :: l ->
fprintf ppf "%s : %a;@ %a" s print_out_type t (print_fields rest) l
and print_row_field ppf (l, opt_amp, tyl) =
let pr_of ppf =
if opt_amp then fprintf ppf " of@ &@ "
else if tyl <> [] then fprintf ppf " of@ "
else fprintf ppf ""
in
fprintf ppf "@[<hv 2>`%s%t%a@]" l pr_of (print_typlist print_out_type " &")
tyl
and print_typargs ppf =
function
[] -> ()
| [ty1] -> print_simple_out_type ppf ty1; pp_print_space ppf ()
| tyl ->
pp_open_box ppf 1;
pp_print_char ppf '(';
print_typlist print_out_type "," ppf tyl;
pp_print_char ppf ')';
pp_close_box ppf ();
pp_print_space ppf ()
and print_out_label ppf (name, mut_or_gbl, arg) =
if Clflags.Extension.is_enabled Local then
let flag =
match mut_or_gbl with
| Ogom_mutable -> "mutable "
| Ogom_global -> "global_ "
| Ogom_nonlocal -> "nonlocal_ "
| Ogom_immutable -> ""
in
fprintf ppf "@[<2>%s%s :@ %a@];" flag name print_out_type arg
else
match mut_or_gbl with
| Ogom_mutable -> fprintf ppf "@[mutable %s :@ %a@];" name print_out_type arg
| Ogom_immutable -> fprintf ppf "@[%s :@ %a@];" name print_out_type arg
| Ogom_global -> fprintf ppf "@[%s :@ %a@];" name print_out_type
(Otyp_attribute (arg, {oattr_name="global"}))
| Ogom_nonlocal -> fprintf ppf "@[%s :@ %a@];" name print_out_type
(Otyp_attribute (arg, {oattr_name="nonlocal"}))
let out_label = ref print_out_label
let out_type = ref print_out_type
let print_type_parameter ppf s =
if s = "_" then fprintf ppf "_" else pr_var ppf s
let type_parameter ppf (ty, (var, inj)) =
let open Asttypes in
fprintf ppf "%s%s%a"
(match var with Covariant -> "+" | Contravariant -> "-" | NoVariance -> "")
(match inj with Injective -> "!" | NoInjectivity -> "")
print_type_parameter ty
let print_out_class_params ppf =
function
[] -> ()
| tyl ->
fprintf ppf "@[<1>[%a]@]@ "
(print_list type_parameter (fun ppf -> fprintf ppf ", "))
tyl
let rec print_out_class_type ppf =
function
Octy_constr (id, tyl) ->
let pr_tyl ppf =
function
[] -> ()
| tyl ->
fprintf ppf "@[<1>[%a]@]@ " (print_typlist !out_type ",") tyl
in
fprintf ppf "@[%a%a@]" pr_tyl tyl print_ident id
| Octy_arrow (lab, ty, cty) ->
fprintf ppf "@[%s%a ->@ %a@]" (if lab <> "" then lab ^ ":" else "")
(print_out_type_2 Oam_global) ty print_out_class_type cty
| Octy_signature (self_ty, csil) ->
let pr_param ppf =
function
Some ty -> fprintf ppf "@ @[(%a)@]" !out_type ty
| None -> ()
in
fprintf ppf "@[<hv 2>@[<2>object%a@]@ %a@;<1 -2>end@]" pr_param self_ty
(print_list print_out_class_sig_item (fun ppf -> fprintf ppf "@ "))
csil
and print_out_class_sig_item ppf =
function
Ocsg_constraint (ty1, ty2) ->
fprintf ppf "@[<2>constraint %a =@ %a@]" !out_type ty1
!out_type ty2
| Ocsg_method (name, priv, virt, ty) ->
fprintf ppf "@[<2>method %s%s%s :@ %a@]"
(if priv then "private " else "") (if virt then "virtual " else "")
name !out_type ty
| Ocsg_value (name, mut, vr, ty) ->
fprintf ppf "@[<2>val %s%s%s :@ %a@]"
(if mut then "mutable " else "")
(if vr then "virtual " else "")
name !out_type ty
let out_class_type = ref print_out_class_type
Signature
let out_module_type = ref (fun _ -> failwith "Oprint.out_module_type")
let out_sig_item = ref (fun _ -> failwith "Oprint.out_sig_item")
let out_signature = ref (fun _ -> failwith "Oprint.out_signature")
let out_type_extension = ref (fun _ -> failwith "Oprint.out_type_extension")
let out_functor_parameters =
ref (fun _ -> failwith "Oprint.out_functor_parameters")
let rec collect_functor_args acc = function
| Omty_functor (param, mty_res) ->
collect_functor_args (param :: acc) mty_res
| non_functor -> (acc, non_functor)
let collect_functor_args mty =
let l, rest = collect_functor_args [] mty in
List.rev l, rest
let constructor_of_extension_constructor
(ext : out_extension_constructor) : out_constructor
=
{
ocstr_name = ext.oext_name;
ocstr_args = ext.oext_args;
ocstr_return_type = ext.oext_ret_type;
}
let split_anon_functor_arguments params =
let rec uncollect_anonymous_suffix acc rest = match acc with
| Some (None, mty_arg) :: acc ->
uncollect_anonymous_suffix acc
(Some (None, mty_arg) :: rest)
| _ :: _ | [] ->
(acc, rest)
in
let (acc, rest) = uncollect_anonymous_suffix (List.rev params) [] in
(List.rev acc, rest)
let rec print_out_module_type ppf mty =
print_out_functor ppf mty
and print_out_functor_parameters ppf l =
let print_nonanon_arg ppf = function
| None ->
fprintf ppf "()"
| Some (param, mty) ->
fprintf ppf "(%s : %a)"
(Option.value param ~default:"_")
print_out_module_type mty
in
let rec print_args ppf = function
| [] -> ()
| Some (None, mty_arg) :: l ->
fprintf ppf "%a ->@ %a"
print_simple_out_module_type mty_arg
print_args l
| _ :: _ as non_anonymous_functor ->
let args, anons = split_anon_functor_arguments non_anonymous_functor in
fprintf ppf "@[<2>functor@ %a@]@ ->@ %a"
(pp_print_list ~pp_sep:pp_print_space print_nonanon_arg) args
print_args anons
in
print_args ppf l
and print_out_functor ppf t =
let params, non_functor = collect_functor_args t in
fprintf ppf "@[<2>%a%a@]"
print_out_functor_parameters params
print_simple_out_module_type non_functor
and print_simple_out_module_type ppf =
function
Omty_abstract -> ()
| Omty_ident id -> fprintf ppf "%a" print_ident id
| Omty_signature sg ->
begin match sg with
| [] -> fprintf ppf "sig end"
| sg ->
fprintf ppf "@[<hv 2>sig@ %a@;<1 -2>end@]" print_out_signature sg
end
| Omty_alias id -> fprintf ppf "(module %a)" print_ident id
| Omty_functor _ as non_simple ->
fprintf ppf "(%a)" print_out_module_type non_simple
| Omty_hole -> fprintf ppf "_"
and print_out_signature ppf =
function
[] -> ()
| [item] -> !out_sig_item ppf item
| Osig_typext(ext, Oext_first) :: items ->
let rec gather_extensions acc items =
match items with
Osig_typext(ext, Oext_next) :: items ->
gather_extensions
(constructor_of_extension_constructor ext :: acc)
items
| _ -> (List.rev acc, items)
in
let exts, items =
gather_extensions
[constructor_of_extension_constructor ext]
items
in
let te =
{ otyext_name = ext.oext_type_name;
otyext_params = ext.oext_type_params;
otyext_constructors = exts;
otyext_private = ext.oext_private }
in
fprintf ppf "%a@ %a" !out_type_extension te print_out_signature items
| item :: items ->
fprintf ppf "%a@ %a" !out_sig_item item print_out_signature items
and print_out_sig_item ppf =
function
Osig_class (vir_flag, name, params, clt, rs) ->
fprintf ppf "@[<2>%s%s@ %a%s@ :@ %a@]"
(if rs = Orec_next then "and" else "class")
(if vir_flag then " virtual" else "") print_out_class_params params
name !out_class_type clt
| Osig_class_type (vir_flag, name, params, clt, rs) ->
fprintf ppf "@[<2>%s%s@ %a%s@ =@ %a@]"
(if rs = Orec_next then "and" else "class type")
(if vir_flag then " virtual" else "") print_out_class_params params
name !out_class_type clt
| Osig_typext (ext, Oext_exception) ->
fprintf ppf "@[<2>exception %a@]"
print_out_constr (constructor_of_extension_constructor ext)
| Osig_typext (ext, _es) ->
print_out_extension_constructor ppf ext
| Osig_modtype (name, Omty_abstract) ->
fprintf ppf "@[<2>module type %s@]" name
| Osig_modtype (name, mty) ->
fprintf ppf "@[<2>module type %s =@ %a@]" name !out_module_type mty
| Osig_module (name, Omty_alias id, _) ->
fprintf ppf "@[<2>module %s =@ %a@]" name print_ident id
| Osig_module (name, mty, rs) ->
fprintf ppf "@[<2>%s %s :@ %a@]"
(match rs with Orec_not -> "module"
| Orec_first -> "module rec"
| Orec_next -> "and")
name !out_module_type mty
| Osig_type(td, rs) ->
print_out_type_decl
(match rs with
| Orec_not -> "type nonrec"
| Orec_first -> "type"
| Orec_next -> "and")
ppf td
| Osig_value vd ->
let kwd = if vd.oval_prims = [] then "val" else "external" in
let pr_prims ppf =
function
[] -> ()
| s :: sl ->
fprintf ppf "@ = \"%s\"" s;
List.iter (fun s -> fprintf ppf "@ \"%s\"" s) sl
in
fprintf ppf "@[<2>%s %a :@ %a%a%a@]" kwd value_ident vd.oval_name
!out_type vd.oval_type pr_prims vd.oval_prims
(fun ppf -> List.iter (fun a -> fprintf ppf "@ [@@@@%s]" a.oattr_name))
vd.oval_attributes
| Osig_ellipsis ->
fprintf ppf "..."
and print_out_type_decl kwd ppf td =
let print_constraints ppf =
List.iter
(fun (ty1, ty2) ->
fprintf ppf "@ @[<2>constraint %a =@ %a@]" !out_type ty1
!out_type ty2)
td.otype_cstrs
in
let type_defined ppf =
match td.otype_params with
[] -> pp_print_string ppf td.otype_name
| [param] -> fprintf ppf "@[%a@ %s@]" type_parameter param td.otype_name
| _ ->
fprintf ppf "@[(@[%a)@]@ %s@]"
(print_list type_parameter (fun ppf -> fprintf ppf ",@ "))
td.otype_params
td.otype_name
in
let print_manifest ppf =
function
Otyp_manifest (ty, _) -> fprintf ppf " =@ %a" !out_type ty
| _ -> ()
in
let print_name_params ppf =
fprintf ppf "%s %t%a" kwd type_defined print_manifest td.otype_type
in
let ty =
match td.otype_type with
Otyp_manifest (_, ty) -> ty
| _ -> td.otype_type
in
let print_private ppf = function
Asttypes.Private -> fprintf ppf " private"
| Asttypes.Public -> ()
in
let print_immediate ppf =
match td.otype_immediate with
| Unknown -> ()
| Always -> fprintf ppf " [%@%@immediate]"
| Always_on_64bits -> fprintf ppf " [%@%@immediate64]"
in
let print_unboxed ppf =
if td.otype_unboxed then fprintf ppf " [%@%@unboxed]" else ()
in
let print_out_tkind ppf = function
| Otyp_abstract -> ()
| Otyp_record lbls ->
fprintf ppf " =%a %a"
print_private td.otype_private
print_record_decl lbls
| Otyp_sum constrs ->
let variants fmt constrs =
if constrs = [] then fprintf fmt "|" else
fprintf fmt "%a" (print_list print_out_constr
(fun ppf -> fprintf ppf "@ | ")) constrs in
fprintf ppf " =%a@;<1 2>%a"
print_private td.otype_private variants constrs
| Otyp_open ->
fprintf ppf " =%a .."
print_private td.otype_private
| ty ->
fprintf ppf " =%a@;<1 2>%a"
print_private td.otype_private
!out_type ty
in
fprintf ppf "@[<2>@[<hv 2>%t%a@]%t%t%t@]"
print_name_params
print_out_tkind ty
print_constraints
print_immediate
print_unboxed
and print_simple_out_gf_type ppf (ty, gf) =
let locals_enabled = Clflags.Extension.is_enabled Local in
match gf with
| Ogf_global ->
if locals_enabled then begin
pp_print_string ppf "global_";
pp_print_space ppf ();
print_simple_out_type ppf ty
end else begin
print_out_type ppf (Otyp_attribute (ty, {oattr_name="global"}))
end
| Ogf_nonlocal ->
if locals_enabled then begin
pp_print_string ppf "nonlocal_";
pp_print_space ppf ();
print_simple_out_type ppf ty
end else begin
print_out_type ppf (Otyp_attribute (ty, {oattr_name="nonlocal"}))
end
| Ogf_unrestricted ->
print_simple_out_type ppf ty
and print_out_constr_args ppf tyl =
print_typlist print_simple_out_gf_type " *" ppf tyl
and print_out_constr ppf constr =
let {
ocstr_name = name;
ocstr_args = tyl;
ocstr_return_type = return_type;
} = constr in
let name =
match name with
# 7200
| s -> s
in
match return_type with
| None ->
begin match tyl with
| [] ->
pp_print_string ppf name
| _ ->
fprintf ppf "@[<2>%s of@ %a@]" name
print_out_constr_args tyl
end
| Some ret_type ->
begin match tyl with
| [] ->
fprintf ppf "@[<2>%s :@ %a@]" name print_simple_out_type ret_type
| _ ->
fprintf ppf "@[<2>%s :@ %a -> %a@]" name
print_out_constr_args tyl print_simple_out_type ret_type
end
and print_out_extension_constructor ppf ext =
let print_extended_type ppf =
match ext.oext_type_params with
[] -> fprintf ppf "%s" ext.oext_type_name
| [ty_param] ->
fprintf ppf "@[%a@ %s@]"
print_type_parameter
ty_param
ext.oext_type_name
| _ ->
fprintf ppf "@[(@[%a)@]@ %s@]"
(print_list print_type_parameter (fun ppf -> fprintf ppf ",@ "))
ext.oext_type_params
ext.oext_type_name
in
fprintf ppf "@[<hv 2>type %t +=%s@;<1 2>%a@]"
print_extended_type
(if ext.oext_private = Asttypes.Private then " private" else "")
print_out_constr
(constructor_of_extension_constructor ext)
and print_out_type_extension ppf te =
let print_extended_type ppf =
match te.otyext_params with
[] -> fprintf ppf "%s" te.otyext_name
| [param] ->
fprintf ppf "@[%a@ %s@]"
print_type_parameter param
te.otyext_name
| _ ->
fprintf ppf "@[(@[%a)@]@ %s@]"
(print_list print_type_parameter (fun ppf -> fprintf ppf ",@ "))
te.otyext_params
te.otyext_name
in
fprintf ppf "@[<hv 2>type %t +=%s@;<1 2>%a@]"
print_extended_type
(if te.otyext_private = Asttypes.Private then " private" else "")
(print_list print_out_constr (fun ppf -> fprintf ppf "@ | "))
te.otyext_constructors
let out_constr = ref print_out_constr
let out_constr_args = ref print_out_constr_args
let _ = out_module_type := print_out_module_type
let _ = out_signature := print_out_signature
let _ = out_sig_item := print_out_sig_item
let _ = out_type_extension := print_out_type_extension
let _ = out_functor_parameters := print_out_functor_parameters
let print_out_exception ppf exn outv =
match exn with
Sys.Break -> fprintf ppf "Interrupted.@."
| Out_of_memory -> fprintf ppf "Out of memory during evaluation.@."
| Stack_overflow ->
fprintf ppf "Stack overflow during evaluation (looping recursion?).@."
| _ -> match Printexc.use_printers exn with
| None -> fprintf ppf "@[Exception:@ %a.@]@." !out_value outv
| Some s -> fprintf ppf "@[Exception:@ %s@]@." s
let rec print_items ppf =
function
[] -> ()
| (Osig_typext(ext, Oext_first), None) :: items ->
let rec gather_extensions acc items =
match items with
(Osig_typext(ext, Oext_next), None) :: items ->
gather_extensions
(constructor_of_extension_constructor ext :: acc)
items
| _ -> (List.rev acc, items)
in
let exts, items =
gather_extensions
[constructor_of_extension_constructor ext]
items
in
let te =
{ otyext_name = ext.oext_type_name;
otyext_params = ext.oext_type_params;
otyext_constructors = exts;
otyext_private = ext.oext_private }
in
fprintf ppf "@[%a@]" !out_type_extension te;
if items <> [] then fprintf ppf "@ %a" print_items items
| (tree, valopt) :: items ->
begin match valopt with
Some v ->
fprintf ppf "@[<2>%a =@ %a@]" !out_sig_item tree
!out_value v
| None -> fprintf ppf "@[%a@]" !out_sig_item tree
end;
if items <> [] then fprintf ppf "@ %a" print_items items
let print_out_phrase ppf =
function
Ophr_eval (outv, ty) ->
fprintf ppf "@[- : %a@ =@ %a@]@." !out_type ty !out_value outv
| Ophr_signature [] -> ()
| Ophr_signature items -> fprintf ppf "@[<v>%a@]@." print_items items
| Ophr_exception (exn, outv) -> print_out_exception ppf exn outv
let out_phrase = ref print_out_phrase
|
db12262b144c183e511a49bd9e4adf7b6c5acfa04440c3ea7bc71a984e655005 | atgreen/red-light-green-light | interpret.lisp | -*- Mode : LISP ; Syntax : Ansi - Common - Lisp ; Base : 10 ; Package : CL - POSTGRES ; -*-
(in-package :cl-postgres)
(defparameter *timestamp-format* :unbound
"This is used to communicate the format \(integer or float) used for
timestamps and intervals in the current connection, so that the
interpreters for those types know how to parse them.")
(defparameter *sql-readtable* (make-hash-table)
"The exported special var holding the current read table, a hash
mapping OIDs to instances of the type-interpreter class that contain
functions for retreiving values from the database in text, and
possible binary, form.
For simple use, you will not have to touch this, but it is possible that code
within a Lisp image requires different readers in different situations, in which
case you can create separate read tables.")
(defun interpret-as-text (stream size)
"This interpreter is used for types that we have no specific
interpreter for -- it just reads the value as a string. \(Values of
unknown types are passed in text form.)"
(enc-read-string stream :byte-length size))
(defclass type-interpreter ()
((oid :initarg :oid :accessor type-interpreter-oid)
(use-binary :initarg :use-binary :accessor type-interpreter-use-binary)
(binary-reader :initarg :binary-reader :accessor type-interpreter-binary-reader)
(text-reader :initarg :text-reader :accessor type-interpreter-text-reader))
(:documentation "Information about type interpreter for types coming
back from the database. use-binary is either T for binary, nil for
text, or a function of no arguments to be called to determine if
binary or text should be used. The idea is that there will always be
a text reader, there may be a binary reader, and there may be times
when one wants to use the text reader."))
(defun interpreter-binary-p (interp)
"If the interpreter's use-binary field is a function, call it and
return the value, otherwise, return T or nil as appropriate."
(let ((val (type-interpreter-use-binary interp)))
(typecase val
(function (funcall val))
(t val))))
(defun interpreter-reader (interp)
"Determine if we went the text or binary reader for this type
interpreter and return the appropriate reader."
(if (interpreter-binary-p interp)
(type-interpreter-binary-reader interp)
(type-interpreter-text-reader interp)))
(let ((default-interpreter (make-instance 'type-interpreter
:oid :default
:use-binary nil
:text-reader #'interpret-as-text)))
(defun get-type-interpreter (oid)
"Returns a type-interpreter containing interpretation rules for
this type."
(gethash oid *sql-readtable* default-interpreter)))
(defun set-sql-reader (oid function &key (table *sql-readtable*) binary-p)
"Define a new reader for a given type. table defaults to *sql-readtable*.
The reader function should take a single argument, a string, and transform
that into some kind of equivalent Lisp value. When binary-p is true, the reader
function is supposed to directly read the binary representation of the value.
In most cases this is not recommended, but if you want to use it: provide a
function that takes a binary input stream and an integer (the size of the
value, in bytes), and reads the value from that stream. Note that reading
less or more bytes than the given size will horribly break your connection."
(assert (integerp oid))
(if function
(setf (gethash oid table)
(make-instance
'type-interpreter
:oid oid
:use-binary binary-p
:binary-reader
(when binary-p function)
:text-reader
(if binary-p
'interpret-as-text
(lambda (stream size)
(funcall function
(enc-read-string stream :byte-length size))))))
(remhash oid table))
table)
(defmacro binary-reader (fields &body value)
"A slightly convoluted macro for defining interpreter functions. It
allows two forms. The first is to pass a single type identifier, in
which case a value of this type will be read and returned directly.
The second is to pass a list of lists containing names and types, and
then a body. In this case the names will be bound to values read from
the socket and interpreted as the given types, and then the body will
be run in the resulting environment. If the last field is of type
bytes, string, or uint2s, all remaining data will be read and
interpreted as an array of the given type."
(let ((stream-name (gensym))
(size-name (gensym))
(length-used 0))
(flet ((read-type (type &optional modifier)
(ecase type
(bytes `(read-bytes ,stream-name (- ,size-name ,length-used)))
(string `(enc-read-string ,stream-name
:byte-length (- ,size-name ,length-used)))
(uint2s `(let* ((size (/ (- ,size-name ,length-used) 2))
(result
(make-array size
:element-type '(unsigned-byte 16)
:initial-element 0)))
(dotimes (i size)
(setf (elt result i) (read-uint2 ,stream-name)))
result))
(int (assert (integerp modifier))
(incf length-used modifier)
`(,(integer-reader-name modifier t) ,stream-name))
(uint (assert (integerp modifier))
(incf length-used modifier)
`(,(integer-reader-name modifier nil) ,stream-name)))))
`(lambda (,stream-name ,size-name)
(declare (type stream ,stream-name)
(type integer ,size-name)
(ignorable ,size-name))
,(if (consp fields)
(progn
`(let ,(loop :for field :in fields
:collect `(,(first field)
,(apply #'read-type (cdr field))))
,@value))
(read-type fields (car value)))))))
(defmacro define-interpreter (oid name fields &body value)
"Shorthand for defining binary readers."
(declare (ignore name)) ;; Names are there just for clarity
`(set-sql-reader ,oid (binary-reader ,fields ,@value) :binary-p t))
(define-interpreter oid:+char+ "char" int 1)
(define-interpreter oid:+int2+ "int2" int 2)
(define-interpreter oid:+int4+ "int4" int 4)
(define-interpreter oid:+int8+ "int8" int 8)
(define-interpreter oid:+oid+ "oid" uint 4)
(define-interpreter oid:+bool+ "bool" ((value int 1))
(if (zerop value) nil t))
(define-interpreter oid:+bytea+ "bytea" bytes)
(define-interpreter oid:+text+ "text" string)
(define-interpreter oid:+bpchar+ "bpchar" string)
(define-interpreter oid:+varchar+ "varchar" string)
(define-interpreter oid:+json+ "json" string)
(define-interpreter oid:+jsonb+ "jsonb" ((version int 1)
(content string))
(unless (= 1 version)
(warn "Unexpected JSONB version: ~S." version))
content)
(defun read-row-value (stream size)
(declare (type stream stream)
(type integer size))
(let ((num-fields (read-uint4 stream)))
(loop for i below num-fields
collect (let ((oid (read-uint4 stream))
(size (read-int4 stream)))
(declare (type (signed-byte 32) size))
(if #-abcl (eq size -1)
#+abcl (eql size -1)
:null
(funcall (interpreter-reader (get-type-interpreter oid))
stream size))))))
;; "row" types
(defparameter *read-row-values-as-binary* nil
"Controls whether row values (as in select row(1, 'foo') ) should be
received from the database in text or binary form. The default value
is nil, specifying that the results be sent back as text. Set this
to t to cause the results to be read as binary.")
(set-sql-reader oid:+record+ #'read-row-value
:binary-p (lambda ()
*read-row-values-as-binary*))
(defmacro with-binary-row-values (&body body)
"Helper macro to locally set *read-row-values-as-binary* to t while
executing body so that row values will be returned as binary."
`(let ((*read-row-values-as-binary* t))
,@body))
(defmacro with-text-row-values (&body body)
"Helper macro to locally set *read-row-values-as-binary* to nil while
executing body so that row values will be returned as t."
`(let ((*read-row-values-as-binary* nil))
,@body))
(defun read-binary-bits (stream size)
(declare (type stream stream)
(type integer size))
(let ((byte-count (- size 4))
(bit-count (read-uint4 stream)))
(let ((bit-bytes (read-bytes stream byte-count))
(bit-array (make-array (list bit-count)
:element-type 'bit
:initial-element 0)))
(loop for i below bit-count
do (let ((cur-byte (ash i -3))
(cur-bit (ldb (byte 3 0) i)))
(setf (aref bit-array i)
(ldb (byte 1 (logxor cur-bit 7)) (aref bit-bytes cur-byte)))))
bit-array)))
(set-sql-reader oid:+bit+ #'read-binary-bits :binary-p t)
(set-sql-reader oid:+varbit+ #'read-binary-bits :binary-p t)
(defun read-binary-array-value (stream size)
(declare (type stream stream)
(type integer size))
(let ((num-dims (read-uint4 stream))
(has-null (read-uint4 stream))
(element-type (read-uint4 stream)))
(cond
((zerop num-dims)
;; Should we return nil or a (make-array nil) when num-dims is
;; 0? Returning nil for now.
nil)
(t
(let* ((array-dims
(loop for i below num-dims
collect (let ((dim (read-uint4 stream))
(lb (read-uint4 stream)))
(declare (ignore lb))
dim)))
(num-items (reduce #'* array-dims)))
(let ((results (make-array array-dims)))
(loop for i below num-items
do (let ((size (read-int4 stream)))
(declare (type (signed-byte 32) size))
(setf (row-major-aref results i)
(if #-abcl (eq size -1)
#+abcl (eql size -1)
:null
(funcall
(interpreter-reader
(get-type-interpreter element-type))
stream size)))))
results))))))
(dolist (oid (list oid:+bool-array+
oid:+bytea-array+
oid:+char-array+
oid:+name-array+ ;; (internal PG type)
oid:+int2-array+
oid:+int4-array+
oid:+text-array+
oid:+bpchar-array+
oid:+varchar-array+
oid:+int8-array+
oid:+point-array+
oid:+lseg-array+
oid:+box-array+
oid:+float4-array+
oid:+float8-array+
oid:+oid-array+
oid:+timestamp-array+
oid:+date-array+
oid:+time-array+
oid:+timestamptz-array+
oid:+interval-array+
oid:+bit-array+
oid:+varbit-array+
oid:+numeric-array+))
(set-sql-reader oid #'read-binary-array-value :binary-p t))
;; record arrays
;;
;; NOTE: need to treat this separately because if we want
;; the record (row types) to come back as text, we have to read the
;; array value as text.
(set-sql-reader oid:+record-array+ #'read-binary-array-value
:binary-p (lambda () *read-row-values-as-binary*))
(define-interpreter oid:+point+ "point" ((point-x-bits uint 8)
(point-y-bits uint 8))
(list (cl-postgres-ieee-floats:decode-float64 point-x-bits)
(cl-postgres-ieee-floats:decode-float64 point-y-bits)))
(define-interpreter oid:+lseg+ "lseg" ((point-x1-bits uint 8)
(point-y1-bits uint 8)
(point-x2-bits uint 8)
(point-y2-bits uint 8))
(list (list (cl-postgres-ieee-floats:decode-float64 point-x1-bits)
(cl-postgres-ieee-floats:decode-float64 point-y1-bits))
(list (cl-postgres-ieee-floats:decode-float64 point-x2-bits)
(cl-postgres-ieee-floats:decode-float64 point-y2-bits))))
(define-interpreter oid:+box+ "box" ((point-x1-bits uint 8)
(point-y1-bits uint 8)
(point-x2-bits uint 8)
(point-y2-bits uint 8))
(list (list (cl-postgres-ieee-floats:decode-float64 point-x1-bits)
(cl-postgres-ieee-floats:decode-float64 point-y1-bits))
(list (cl-postgres-ieee-floats:decode-float64 point-x2-bits)
(cl-postgres-ieee-floats:decode-float64 point-y2-bits))))
(define-interpreter oid:+float4+ "float4" ((bits uint 4))
(cl-postgres-ieee-floats:decode-float32 bits))
(define-interpreter oid:+float8+ "float8" ((bits uint 8))
(cl-postgres-ieee-floats:decode-float64 bits))
;; Numeric types are rather involved. I got some clues on their
;; structure from
;; -interfaces/2004-08/msg00000.php
(define-interpreter oid:+numeric+ "numeric"
((length uint 2)
(weight int 2)
(sign int 2)
(dscale int 2)
(digits uint2s))
(declare (ignore dscale))
(let ((total (loop :for i :from (1- length) :downto 0
:for scale = 1 :then (* scale #.(expt 10 4))
:summing (* scale (elt digits i))))
(scale (- length weight 1)))
(unless (zerop sign)
(setf total (- total)))
(/ total (expt 10000 scale))))
;; Since date and time types are the most likely to require custom
;; readers, there is a hook for easily adding binary readers for them.
(defun set-date-reader (f table)
(set-sql-reader oid:+date+ (binary-reader ((days int 4))
(funcall f days))
:table table
:binary-p t))
(defun interpret-usec-bits (bits)
"Decode a 64 bit time-related value based on the timestamp format
used. Correct for sign bit when using integer format."
(ecase *timestamp-format*
(:float (round (* (cl-postgres-ieee-floats:decode-float64 bits) 1000000)))
(:integer (if (logbitp 63 bits)
(dpb bits (byte 63 0) -1)
bits))))
(defun set-interval-reader (f table)
(set-sql-reader oid:+interval+
(binary-reader ((usec-bits uint 8) (days int 4)
(months int 4))
(funcall f months days
(interpret-usec-bits usec-bits)))
:table table
:binary-p t))
(defun set-usec-reader (oid f table)
(set-sql-reader oid
(binary-reader ((usec-bits uint 8))
(funcall f (interpret-usec-bits usec-bits)))
:table table
:binary-p t))
;; Public interface for adding date/time readers
(defun set-sql-datetime-readers (&key date timestamp timestamp-with-timezone
interval time
(table *sql-readtable*))
"Since there is no widely recognised standard way of representing dates and
times in Common Lisp, and reading these from string representation is clunky
and slow, this function provides a way to easily plug in binary readers for
the date, time, timestamp, and interval types. It should be given functions
with the following signatures:
- :date (days)
Where days is the amount of days since January 1st, 2000.
- :timestamp (useconds)
Timestamps have a microsecond resolution. Again, the zero point is the start
of the year 2000, UTC.
- :timestamp-with-timezone
Like :timestamp, but for values of the 'timestamp with time zone' type (which
PostgreSQL internally stores exactly the same as regular timestamps).
- :time (useconds)
Refers to a time of day, counting from midnight.
- :interval (months days useconds)
An interval is represented as several separate components. The reason that days
and microseconds are separated is that you might want to take leap seconds into
account.
Defaults are provided as follows:
#'default-date-reader
#'default-timestamp-reader
#'default-interval-reader
#'default-time-reader
e.g.
(defun make-temp-postgres-query-requiring-unix-timestamps ()
(flet ((temp-timestamp-reader (useconds-since-2000)
(- (+ +start-of-2000+ (floor useconds-since-2000 1000000))
(encode-universal-time 0 0 0 1 1 1970 0))))
(set-sql-datetime-readers
:date #'temp-timestamp-reader)
(let ((query (make-postgres-query-requiring-unix-timestamps))
(set-sql-datetime-readers
:date #'default-timestamp-reader)
query))))
"
(when date (set-date-reader date table))
(when timestamp (set-usec-reader oid:+timestamp+ timestamp table))
(when timestamp-with-timezone (set-usec-reader oid:+timestamptz+
timestamp-with-timezone table))
(when interval (set-interval-reader interval table))
(when time (set-usec-reader oid:+time+ time table))
table)
;; Provide meaningful defaults for the date/time readers.
(defconstant +start-of-2000+ (encode-universal-time 0 0 0 1 1 2000 0))
(defconstant +seconds-in-day+ (* 60 60 24))
(defun default-date-reader (days-since-2000)
(+ +start-of-2000+ (* days-since-2000 +seconds-in-day+)))
(defun default-timestamp-reader (useconds-since-2000)
(+ +start-of-2000+ (floor useconds-since-2000 1000000)))
(defun default-interval-reader (months days useconds)
(multiple-value-bind (sec us) (floor useconds 1000000)
`((:months ,months) (:days ,days) (:seconds ,sec)
(:useconds ,us))))
(defun default-time-reader (usecs)
(multiple-value-bind (seconds usecs)
(floor usecs 1000000)
(multiple-value-bind (minutes seconds)
(floor seconds 60)
(multiple-value-bind (hours minutes)
(floor minutes 60)
`((:hours ,hours) (:minutes ,minutes) (:seconds ,seconds)
(:microseconds ,usecs))))))
(set-sql-datetime-readers
:date #'default-date-reader
:timestamp #'default-timestamp-reader
:timestamp-with-timezone #'default-timestamp-reader
:interval #'default-interval-reader
:time #'default-time-reader)
;; Readers for a few of the array types
(defun read-array-value (transform)
(declare #.*optimize*)
(lambda (value)
(declare (type string value))
(let ((pos 0))
(declare (type fixnum pos))
(labels ((readelt ()
(case (char value pos)
(#\" (interpret
(with-output-to-string (out)
(loop :with escaped := nil
:for ch := (char value (incf pos)) :do
(when (and (char= ch #\") (not escaped))
(return))
(setf escaped (and (not escaped)
(char= ch #\\)))
(unless escaped (write-char ch out)))
(incf pos))))
(#\{ (incf pos)
(unless (char= (char value pos) #\})
(loop :for val := (readelt) :collect val :into vals :do
(let ((next (char value pos)))
(incf pos)
(ecase next (#\,) (#\} (return vals)))))))
(t (let ((start pos))
(loop :for ch := (char value pos) :do
(when (or (char= ch #\,) (char= ch #\}))
(return (interpret (subseq value start pos))))
(incf pos))))))
(interpret (word)
(if (string= word "NULL")
:null
(funcall transform word))))
(let* ((arr (readelt))
(dim (if arr (loop :for x := arr :then (car x) :while (consp x)
:collect (length x))
'(0))))
(make-array dim :initial-contents arr))))))
;; Working with tables.
(defun copy-sql-readtable (&optional (table *sql-readtable*))
"Copies a given readtable."
(let ((new-table (make-hash-table)))
(maphash (lambda (oid interpreter) (setf (gethash oid new-table)
interpreter))
table)
new-table))
(defparameter *default-sql-readtable* (copy-sql-readtable *sql-readtable*)
"A copy of the default readtable that client code can fall back
on.")
(defun default-sql-readtable ()
"Returns the default readtable, containing only the readers defined by
CL-postgres itself."
*default-sql-readtable*)
| null | https://raw.githubusercontent.com/atgreen/red-light-green-light/f067507721bbab4aa973866db5276c83df3e8784/local-projects/postmodern-20220220-git/cl-postgres/interpret.lisp | lisp | Syntax : Ansi - Common - Lisp ; Base : 10 ; Package : CL - POSTGRES ; -*-
Names are there just for clarity
"row" types
Should we return nil or a (make-array nil) when num-dims is
0? Returning nil for now.
(internal PG type)
record arrays
NOTE: need to treat this separately because if we want
the record (row types) to come back as text, we have to read the
array value as text.
Numeric types are rather involved. I got some clues on their
structure from
-interfaces/2004-08/msg00000.php
Since date and time types are the most likely to require custom
readers, there is a hook for easily adding binary readers for them.
Public interface for adding date/time readers
Provide meaningful defaults for the date/time readers.
Readers for a few of the array types
Working with tables. | (in-package :cl-postgres)
(defparameter *timestamp-format* :unbound
"This is used to communicate the format \(integer or float) used for
timestamps and intervals in the current connection, so that the
interpreters for those types know how to parse them.")
(defparameter *sql-readtable* (make-hash-table)
"The exported special var holding the current read table, a hash
mapping OIDs to instances of the type-interpreter class that contain
functions for retreiving values from the database in text, and
possible binary, form.
For simple use, you will not have to touch this, but it is possible that code
within a Lisp image requires different readers in different situations, in which
case you can create separate read tables.")
(defun interpret-as-text (stream size)
"This interpreter is used for types that we have no specific
interpreter for -- it just reads the value as a string. \(Values of
unknown types are passed in text form.)"
(enc-read-string stream :byte-length size))
(defclass type-interpreter ()
((oid :initarg :oid :accessor type-interpreter-oid)
(use-binary :initarg :use-binary :accessor type-interpreter-use-binary)
(binary-reader :initarg :binary-reader :accessor type-interpreter-binary-reader)
(text-reader :initarg :text-reader :accessor type-interpreter-text-reader))
(:documentation "Information about type interpreter for types coming
back from the database. use-binary is either T for binary, nil for
text, or a function of no arguments to be called to determine if
binary or text should be used. The idea is that there will always be
a text reader, there may be a binary reader, and there may be times
when one wants to use the text reader."))
(defun interpreter-binary-p (interp)
"If the interpreter's use-binary field is a function, call it and
return the value, otherwise, return T or nil as appropriate."
(let ((val (type-interpreter-use-binary interp)))
(typecase val
(function (funcall val))
(t val))))
(defun interpreter-reader (interp)
"Determine if we went the text or binary reader for this type
interpreter and return the appropriate reader."
(if (interpreter-binary-p interp)
(type-interpreter-binary-reader interp)
(type-interpreter-text-reader interp)))
(let ((default-interpreter (make-instance 'type-interpreter
:oid :default
:use-binary nil
:text-reader #'interpret-as-text)))
(defun get-type-interpreter (oid)
"Returns a type-interpreter containing interpretation rules for
this type."
(gethash oid *sql-readtable* default-interpreter)))
(defun set-sql-reader (oid function &key (table *sql-readtable*) binary-p)
"Define a new reader for a given type. table defaults to *sql-readtable*.
The reader function should take a single argument, a string, and transform
that into some kind of equivalent Lisp value. When binary-p is true, the reader
function is supposed to directly read the binary representation of the value.
In most cases this is not recommended, but if you want to use it: provide a
function that takes a binary input stream and an integer (the size of the
value, in bytes), and reads the value from that stream. Note that reading
less or more bytes than the given size will horribly break your connection."
(assert (integerp oid))
(if function
(setf (gethash oid table)
(make-instance
'type-interpreter
:oid oid
:use-binary binary-p
:binary-reader
(when binary-p function)
:text-reader
(if binary-p
'interpret-as-text
(lambda (stream size)
(funcall function
(enc-read-string stream :byte-length size))))))
(remhash oid table))
table)
(defmacro binary-reader (fields &body value)
"A slightly convoluted macro for defining interpreter functions. It
allows two forms. The first is to pass a single type identifier, in
which case a value of this type will be read and returned directly.
The second is to pass a list of lists containing names and types, and
then a body. In this case the names will be bound to values read from
the socket and interpreted as the given types, and then the body will
be run in the resulting environment. If the last field is of type
bytes, string, or uint2s, all remaining data will be read and
interpreted as an array of the given type."
(let ((stream-name (gensym))
(size-name (gensym))
(length-used 0))
(flet ((read-type (type &optional modifier)
(ecase type
(bytes `(read-bytes ,stream-name (- ,size-name ,length-used)))
(string `(enc-read-string ,stream-name
:byte-length (- ,size-name ,length-used)))
(uint2s `(let* ((size (/ (- ,size-name ,length-used) 2))
(result
(make-array size
:element-type '(unsigned-byte 16)
:initial-element 0)))
(dotimes (i size)
(setf (elt result i) (read-uint2 ,stream-name)))
result))
(int (assert (integerp modifier))
(incf length-used modifier)
`(,(integer-reader-name modifier t) ,stream-name))
(uint (assert (integerp modifier))
(incf length-used modifier)
`(,(integer-reader-name modifier nil) ,stream-name)))))
`(lambda (,stream-name ,size-name)
(declare (type stream ,stream-name)
(type integer ,size-name)
(ignorable ,size-name))
,(if (consp fields)
(progn
`(let ,(loop :for field :in fields
:collect `(,(first field)
,(apply #'read-type (cdr field))))
,@value))
(read-type fields (car value)))))))
(defmacro define-interpreter (oid name fields &body value)
"Shorthand for defining binary readers."
`(set-sql-reader ,oid (binary-reader ,fields ,@value) :binary-p t))
(define-interpreter oid:+char+ "char" int 1)
(define-interpreter oid:+int2+ "int2" int 2)
(define-interpreter oid:+int4+ "int4" int 4)
(define-interpreter oid:+int8+ "int8" int 8)
(define-interpreter oid:+oid+ "oid" uint 4)
(define-interpreter oid:+bool+ "bool" ((value int 1))
(if (zerop value) nil t))
(define-interpreter oid:+bytea+ "bytea" bytes)
(define-interpreter oid:+text+ "text" string)
(define-interpreter oid:+bpchar+ "bpchar" string)
(define-interpreter oid:+varchar+ "varchar" string)
(define-interpreter oid:+json+ "json" string)
(define-interpreter oid:+jsonb+ "jsonb" ((version int 1)
(content string))
(unless (= 1 version)
(warn "Unexpected JSONB version: ~S." version))
content)
(defun read-row-value (stream size)
(declare (type stream stream)
(type integer size))
(let ((num-fields (read-uint4 stream)))
(loop for i below num-fields
collect (let ((oid (read-uint4 stream))
(size (read-int4 stream)))
(declare (type (signed-byte 32) size))
(if #-abcl (eq size -1)
#+abcl (eql size -1)
:null
(funcall (interpreter-reader (get-type-interpreter oid))
stream size))))))
(defparameter *read-row-values-as-binary* nil
"Controls whether row values (as in select row(1, 'foo') ) should be
received from the database in text or binary form. The default value
is nil, specifying that the results be sent back as text. Set this
to t to cause the results to be read as binary.")
(set-sql-reader oid:+record+ #'read-row-value
:binary-p (lambda ()
*read-row-values-as-binary*))
(defmacro with-binary-row-values (&body body)
"Helper macro to locally set *read-row-values-as-binary* to t while
executing body so that row values will be returned as binary."
`(let ((*read-row-values-as-binary* t))
,@body))
(defmacro with-text-row-values (&body body)
"Helper macro to locally set *read-row-values-as-binary* to nil while
executing body so that row values will be returned as t."
`(let ((*read-row-values-as-binary* nil))
,@body))
(defun read-binary-bits (stream size)
(declare (type stream stream)
(type integer size))
(let ((byte-count (- size 4))
(bit-count (read-uint4 stream)))
(let ((bit-bytes (read-bytes stream byte-count))
(bit-array (make-array (list bit-count)
:element-type 'bit
:initial-element 0)))
(loop for i below bit-count
do (let ((cur-byte (ash i -3))
(cur-bit (ldb (byte 3 0) i)))
(setf (aref bit-array i)
(ldb (byte 1 (logxor cur-bit 7)) (aref bit-bytes cur-byte)))))
bit-array)))
(set-sql-reader oid:+bit+ #'read-binary-bits :binary-p t)
(set-sql-reader oid:+varbit+ #'read-binary-bits :binary-p t)
(defun read-binary-array-value (stream size)
(declare (type stream stream)
(type integer size))
(let ((num-dims (read-uint4 stream))
(has-null (read-uint4 stream))
(element-type (read-uint4 stream)))
(cond
((zerop num-dims)
nil)
(t
(let* ((array-dims
(loop for i below num-dims
collect (let ((dim (read-uint4 stream))
(lb (read-uint4 stream)))
(declare (ignore lb))
dim)))
(num-items (reduce #'* array-dims)))
(let ((results (make-array array-dims)))
(loop for i below num-items
do (let ((size (read-int4 stream)))
(declare (type (signed-byte 32) size))
(setf (row-major-aref results i)
(if #-abcl (eq size -1)
#+abcl (eql size -1)
:null
(funcall
(interpreter-reader
(get-type-interpreter element-type))
stream size)))))
results))))))
(dolist (oid (list oid:+bool-array+
oid:+bytea-array+
oid:+char-array+
oid:+int2-array+
oid:+int4-array+
oid:+text-array+
oid:+bpchar-array+
oid:+varchar-array+
oid:+int8-array+
oid:+point-array+
oid:+lseg-array+
oid:+box-array+
oid:+float4-array+
oid:+float8-array+
oid:+oid-array+
oid:+timestamp-array+
oid:+date-array+
oid:+time-array+
oid:+timestamptz-array+
oid:+interval-array+
oid:+bit-array+
oid:+varbit-array+
oid:+numeric-array+))
(set-sql-reader oid #'read-binary-array-value :binary-p t))
(set-sql-reader oid:+record-array+ #'read-binary-array-value
:binary-p (lambda () *read-row-values-as-binary*))
(define-interpreter oid:+point+ "point" ((point-x-bits uint 8)
(point-y-bits uint 8))
(list (cl-postgres-ieee-floats:decode-float64 point-x-bits)
(cl-postgres-ieee-floats:decode-float64 point-y-bits)))
(define-interpreter oid:+lseg+ "lseg" ((point-x1-bits uint 8)
(point-y1-bits uint 8)
(point-x2-bits uint 8)
(point-y2-bits uint 8))
(list (list (cl-postgres-ieee-floats:decode-float64 point-x1-bits)
(cl-postgres-ieee-floats:decode-float64 point-y1-bits))
(list (cl-postgres-ieee-floats:decode-float64 point-x2-bits)
(cl-postgres-ieee-floats:decode-float64 point-y2-bits))))
(define-interpreter oid:+box+ "box" ((point-x1-bits uint 8)
(point-y1-bits uint 8)
(point-x2-bits uint 8)
(point-y2-bits uint 8))
(list (list (cl-postgres-ieee-floats:decode-float64 point-x1-bits)
(cl-postgres-ieee-floats:decode-float64 point-y1-bits))
(list (cl-postgres-ieee-floats:decode-float64 point-x2-bits)
(cl-postgres-ieee-floats:decode-float64 point-y2-bits))))
(define-interpreter oid:+float4+ "float4" ((bits uint 4))
(cl-postgres-ieee-floats:decode-float32 bits))
(define-interpreter oid:+float8+ "float8" ((bits uint 8))
(cl-postgres-ieee-floats:decode-float64 bits))
(define-interpreter oid:+numeric+ "numeric"
((length uint 2)
(weight int 2)
(sign int 2)
(dscale int 2)
(digits uint2s))
(declare (ignore dscale))
(let ((total (loop :for i :from (1- length) :downto 0
:for scale = 1 :then (* scale #.(expt 10 4))
:summing (* scale (elt digits i))))
(scale (- length weight 1)))
(unless (zerop sign)
(setf total (- total)))
(/ total (expt 10000 scale))))
(defun set-date-reader (f table)
(set-sql-reader oid:+date+ (binary-reader ((days int 4))
(funcall f days))
:table table
:binary-p t))
(defun interpret-usec-bits (bits)
"Decode a 64 bit time-related value based on the timestamp format
used. Correct for sign bit when using integer format."
(ecase *timestamp-format*
(:float (round (* (cl-postgres-ieee-floats:decode-float64 bits) 1000000)))
(:integer (if (logbitp 63 bits)
(dpb bits (byte 63 0) -1)
bits))))
(defun set-interval-reader (f table)
(set-sql-reader oid:+interval+
(binary-reader ((usec-bits uint 8) (days int 4)
(months int 4))
(funcall f months days
(interpret-usec-bits usec-bits)))
:table table
:binary-p t))
(defun set-usec-reader (oid f table)
(set-sql-reader oid
(binary-reader ((usec-bits uint 8))
(funcall f (interpret-usec-bits usec-bits)))
:table table
:binary-p t))
(defun set-sql-datetime-readers (&key date timestamp timestamp-with-timezone
interval time
(table *sql-readtable*))
"Since there is no widely recognised standard way of representing dates and
times in Common Lisp, and reading these from string representation is clunky
and slow, this function provides a way to easily plug in binary readers for
the date, time, timestamp, and interval types. It should be given functions
with the following signatures:
- :date (days)
Where days is the amount of days since January 1st, 2000.
- :timestamp (useconds)
Timestamps have a microsecond resolution. Again, the zero point is the start
of the year 2000, UTC.
- :timestamp-with-timezone
Like :timestamp, but for values of the 'timestamp with time zone' type (which
PostgreSQL internally stores exactly the same as regular timestamps).
- :time (useconds)
Refers to a time of day, counting from midnight.
- :interval (months days useconds)
An interval is represented as several separate components. The reason that days
and microseconds are separated is that you might want to take leap seconds into
account.
Defaults are provided as follows:
#'default-date-reader
#'default-timestamp-reader
#'default-interval-reader
#'default-time-reader
e.g.
(defun make-temp-postgres-query-requiring-unix-timestamps ()
(flet ((temp-timestamp-reader (useconds-since-2000)
(- (+ +start-of-2000+ (floor useconds-since-2000 1000000))
(encode-universal-time 0 0 0 1 1 1970 0))))
(set-sql-datetime-readers
:date #'temp-timestamp-reader)
(let ((query (make-postgres-query-requiring-unix-timestamps))
(set-sql-datetime-readers
:date #'default-timestamp-reader)
query))))
"
(when date (set-date-reader date table))
(when timestamp (set-usec-reader oid:+timestamp+ timestamp table))
(when timestamp-with-timezone (set-usec-reader oid:+timestamptz+
timestamp-with-timezone table))
(when interval (set-interval-reader interval table))
(when time (set-usec-reader oid:+time+ time table))
table)
(defconstant +start-of-2000+ (encode-universal-time 0 0 0 1 1 2000 0))
(defconstant +seconds-in-day+ (* 60 60 24))
(defun default-date-reader (days-since-2000)
(+ +start-of-2000+ (* days-since-2000 +seconds-in-day+)))
(defun default-timestamp-reader (useconds-since-2000)
(+ +start-of-2000+ (floor useconds-since-2000 1000000)))
(defun default-interval-reader (months days useconds)
(multiple-value-bind (sec us) (floor useconds 1000000)
`((:months ,months) (:days ,days) (:seconds ,sec)
(:useconds ,us))))
(defun default-time-reader (usecs)
(multiple-value-bind (seconds usecs)
(floor usecs 1000000)
(multiple-value-bind (minutes seconds)
(floor seconds 60)
(multiple-value-bind (hours minutes)
(floor minutes 60)
`((:hours ,hours) (:minutes ,minutes) (:seconds ,seconds)
(:microseconds ,usecs))))))
(set-sql-datetime-readers
:date #'default-date-reader
:timestamp #'default-timestamp-reader
:timestamp-with-timezone #'default-timestamp-reader
:interval #'default-interval-reader
:time #'default-time-reader)
(defun read-array-value (transform)
(declare #.*optimize*)
(lambda (value)
(declare (type string value))
(let ((pos 0))
(declare (type fixnum pos))
(labels ((readelt ()
(case (char value pos)
(#\" (interpret
(with-output-to-string (out)
(loop :with escaped := nil
:for ch := (char value (incf pos)) :do
(when (and (char= ch #\") (not escaped))
(return))
(setf escaped (and (not escaped)
(char= ch #\\)))
(unless escaped (write-char ch out)))
(incf pos))))
(#\{ (incf pos)
(unless (char= (char value pos) #\})
(loop :for val := (readelt) :collect val :into vals :do
(let ((next (char value pos)))
(incf pos)
(ecase next (#\,) (#\} (return vals)))))))
(t (let ((start pos))
(loop :for ch := (char value pos) :do
(when (or (char= ch #\,) (char= ch #\}))
(return (interpret (subseq value start pos))))
(incf pos))))))
(interpret (word)
(if (string= word "NULL")
:null
(funcall transform word))))
(let* ((arr (readelt))
(dim (if arr (loop :for x := arr :then (car x) :while (consp x)
:collect (length x))
'(0))))
(make-array dim :initial-contents arr))))))
(defun copy-sql-readtable (&optional (table *sql-readtable*))
"Copies a given readtable."
(let ((new-table (make-hash-table)))
(maphash (lambda (oid interpreter) (setf (gethash oid new-table)
interpreter))
table)
new-table))
(defparameter *default-sql-readtable* (copy-sql-readtable *sql-readtable*)
"A copy of the default readtable that client code can fall back
on.")
(defun default-sql-readtable ()
"Returns the default readtable, containing only the readers defined by
CL-postgres itself."
*default-sql-readtable*)
|
fef8fa2d90c470de5a352ef7bf4adff4d824d3791277d2d2120a81be3903de7c | vito/atomo | Types.hs | # LANGUAGE DeriveDataTypeable , OverloadedStrings , TypeSynonymInstances #
module Atomo.Format.Types where
import Control.Monad.RWS
import Data.Typeable
import Text.PrettyPrint
import qualified Data.Text as T
import Atomo.Pretty
import Atomo.Types
-- | The core types of formats to use.
data Segment
-- | Arbitrary text.
= SChunk T.Text
-- | %s
| SString
-- | %d
| SDecimal
-- | %x
| SHex
-- | %o
| SOctal
-- | %b
| SBinary
-- | %r
| SRadix
-- | %f
| SFloat
-- | %e
| SExponent
-- | %g
| SGeneral
-- | %c
| SCharacter
-- | %a
| SAsString
-- | %v
| SAny
-- | %p(...)
| SPluralize [Flagged] (Maybe [Flagged])
-- | %l(...)
| SLowercase [Flagged]
-- | %c(...)
| SCapitalize [Flagged]
-- | %u(...)
| SUppercase [Flagged]
-- | %_
| SSkip
-- | %%
| SIndirection
-- | %{...}
| SIterate [Flagged]
-- | %^
| SBreak
| % [ ... ] + ( ... ) ? where + = one or more and ? = optional ( the default )
| SConditional [[Flagged]] (Maybe [Flagged])
| % j( ... )+ where + = one or more
| SJustify [[Flagged]]
deriving (Show, Typeable)
-- Various modifiers, for our segments.
data Flag
|
-- The Maybe is Nothing if they used #, in which case we use the number
-- of remaining values.
= FNumber (Maybe Int)
-- | FSome symbol presumeably known by the segment.
| FSymbol Char
-- | FUsed by %f and %d
| FZeroPad
-- | FUsed by %f
| FPrecision Int
deriving (Eq, Show, Typeable)
data FormatState =
FormatState
{ fsInput :: [Value]
, fsPosition :: Int
, fsStop :: Bool
, fsIterating :: [Value]
}
type Flagged = (Segment, [Flag])
type FormatterT = RWST Format T.Text FormatState
type Formatter = FormatterT VM
type Format = [Flagged]
instance Pretty Format where
prettyFrom _ fs = hcat (map pretty fs)
instance Pretty Flagged where
prettyFrom _ (SChunk s, _) = text (T.unpack (T.replace "\"" "\\\"" s))
prettyFrom _ (s, fs) = char '%' <> hcat (map pretty fs) <> pretty s
instance Pretty Flag where
prettyFrom _ (FNumber Nothing) = char '#'
prettyFrom _ (FNumber (Just n)) = int n
prettyFrom _ (FSymbol c) = char c
prettyFrom _ FZeroPad = char '0'
prettyFrom _ (FPrecision n) = char '.' <> int n
instance Pretty Segment where
prettyFrom _ (SChunk _) = error "pretty-printing a Chunk segment"
prettyFrom _ SString = char 's'
prettyFrom _ SDecimal = char 'd'
prettyFrom _ SHex = char 'x'
prettyFrom _ SOctal = char 'o'
prettyFrom _ SBinary = char 'b'
prettyFrom _ SRadix = char 'r'
prettyFrom _ SFloat = char 'f'
prettyFrom _ SExponent = char 'e'
prettyFrom _ SGeneral = char 'g'
prettyFrom _ SCharacter = char 'c'
prettyFrom _ SAsString = char 'a'
prettyFrom _ SAny = char 'v'
prettyFrom _ (SPluralize s Nothing) = char 'p' <> parens (pretty s)
prettyFrom _ (SPluralize s (Just p)) =
char 'p' <> parens (pretty s) <> parens (pretty p)
prettyFrom _ (SLowercase fs) = char 'l' <> parens (pretty fs)
prettyFrom _ (SCapitalize fs) = char 'c' <> parens (pretty fs)
prettyFrom _ (SUppercase fs) = char 'u' <> parens (pretty fs)
prettyFrom _ SSkip = char '_'
prettyFrom _ SIndirection = char '%'
prettyFrom _ (SIterate fs) = braces (pretty fs)
prettyFrom _ SBreak = char '^'
prettyFrom _ (SConditional bs Nothing) =
hcat (map (brackets . pretty) bs)
prettyFrom _ (SConditional bs (Just d)) =
hcat (map (brackets . pretty) bs) <> parens (pretty d)
prettyFrom _ (SJustify fs) =
char 'j' <> hcat (map (parens . pretty) fs)
startState :: [Value] -> FormatState
startState vs = FormatState vs 0 False [] | null | https://raw.githubusercontent.com/vito/atomo/df22fcb3fbe80abb30b9ab3c6f5d50d3b8477f90/src/Atomo/Format/Types.hs | haskell | | The core types of formats to use.
| Arbitrary text.
| %s
| %d
| %x
| %o
| %b
| %r
| %f
| %e
| %g
| %c
| %a
| %v
| %p(...)
| %l(...)
| %c(...)
| %u(...)
| %_
| %%
| %{...}
| %^
Various modifiers, for our segments.
The Maybe is Nothing if they used #, in which case we use the number
of remaining values.
| FSome symbol presumeably known by the segment.
| FUsed by %f and %d
| FUsed by %f | # LANGUAGE DeriveDataTypeable , OverloadedStrings , TypeSynonymInstances #
module Atomo.Format.Types where
import Control.Monad.RWS
import Data.Typeable
import Text.PrettyPrint
import qualified Data.Text as T
import Atomo.Pretty
import Atomo.Types
data Segment
= SChunk T.Text
| SString
| SDecimal
| SHex
| SOctal
| SBinary
| SRadix
| SFloat
| SExponent
| SGeneral
| SCharacter
| SAsString
| SAny
| SPluralize [Flagged] (Maybe [Flagged])
| SLowercase [Flagged]
| SCapitalize [Flagged]
| SUppercase [Flagged]
| SSkip
| SIndirection
| SIterate [Flagged]
| SBreak
| % [ ... ] + ( ... ) ? where + = one or more and ? = optional ( the default )
| SConditional [[Flagged]] (Maybe [Flagged])
| % j( ... )+ where + = one or more
| SJustify [[Flagged]]
deriving (Show, Typeable)
data Flag
|
= FNumber (Maybe Int)
| FSymbol Char
| FZeroPad
| FPrecision Int
deriving (Eq, Show, Typeable)
data FormatState =
FormatState
{ fsInput :: [Value]
, fsPosition :: Int
, fsStop :: Bool
, fsIterating :: [Value]
}
type Flagged = (Segment, [Flag])
type FormatterT = RWST Format T.Text FormatState
type Formatter = FormatterT VM
type Format = [Flagged]
instance Pretty Format where
prettyFrom _ fs = hcat (map pretty fs)
instance Pretty Flagged where
prettyFrom _ (SChunk s, _) = text (T.unpack (T.replace "\"" "\\\"" s))
prettyFrom _ (s, fs) = char '%' <> hcat (map pretty fs) <> pretty s
instance Pretty Flag where
prettyFrom _ (FNumber Nothing) = char '#'
prettyFrom _ (FNumber (Just n)) = int n
prettyFrom _ (FSymbol c) = char c
prettyFrom _ FZeroPad = char '0'
prettyFrom _ (FPrecision n) = char '.' <> int n
instance Pretty Segment where
prettyFrom _ (SChunk _) = error "pretty-printing a Chunk segment"
prettyFrom _ SString = char 's'
prettyFrom _ SDecimal = char 'd'
prettyFrom _ SHex = char 'x'
prettyFrom _ SOctal = char 'o'
prettyFrom _ SBinary = char 'b'
prettyFrom _ SRadix = char 'r'
prettyFrom _ SFloat = char 'f'
prettyFrom _ SExponent = char 'e'
prettyFrom _ SGeneral = char 'g'
prettyFrom _ SCharacter = char 'c'
prettyFrom _ SAsString = char 'a'
prettyFrom _ SAny = char 'v'
prettyFrom _ (SPluralize s Nothing) = char 'p' <> parens (pretty s)
prettyFrom _ (SPluralize s (Just p)) =
char 'p' <> parens (pretty s) <> parens (pretty p)
prettyFrom _ (SLowercase fs) = char 'l' <> parens (pretty fs)
prettyFrom _ (SCapitalize fs) = char 'c' <> parens (pretty fs)
prettyFrom _ (SUppercase fs) = char 'u' <> parens (pretty fs)
prettyFrom _ SSkip = char '_'
prettyFrom _ SIndirection = char '%'
prettyFrom _ (SIterate fs) = braces (pretty fs)
prettyFrom _ SBreak = char '^'
prettyFrom _ (SConditional bs Nothing) =
hcat (map (brackets . pretty) bs)
prettyFrom _ (SConditional bs (Just d)) =
hcat (map (brackets . pretty) bs) <> parens (pretty d)
prettyFrom _ (SJustify fs) =
char 'j' <> hcat (map (parens . pretty) fs)
startState :: [Value] -> FormatState
startState vs = FormatState vs 0 False [] |
cf4eb1566faee50a3a9cbe85b74de78fe404b0f54949156614040091c69040d7 | siraben/haoc-2021 | day4.hs | # LANGUAGE TupleSections #
import Control.Applicative
import Control.Monad
import Criterion.Main
import Data.Foldable
import Data.Function
import Data.List
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
-- Slow splitOn for prototyping
splitOn :: String -> String -> [String]
splitOn sep s = T.unpack <$> T.splitOn (T.pack sep) (T.pack s)
type Bingo = [[(Int, Bool)]]
mark :: Bingo -> Int -> Bingo
mark b n = map (map change) b
where
change e@(m, b)
| m == n = (m, True)
| otherwise = e
unmarked :: Bingo -> [Int]
unmarked = map fst . filter snd . concat
initBoard :: [[Int]] -> Bingo
initBoard = map (map (,False))
f ns (b, y) = unmarkedNums * finalNum
where
unmarkedNums = sum $ map fst $ filter (not . snd) $ concat finalBoard
finalNum = last nums
finalBoard = foldl' mark (initBoard b) nums
nums = take y ns
part1 (ns, inp') = f ns $ minimumBy (compare `on` snd) . zip inp' $ g ns . initBoard <$> inp'
part2 (ns, inp') = f ns $ maximumBy (compare `on` snd) . zip inp' $ g ns . initBoard <$> inp'
solved b = check b || check (transpose b)
where
check = any (all snd)
g ns b =
scanl' mark b ns
& map solved
& findIndex id
& fromJust
main = do
let dayNumber = 4 :: Int
let dayString = "day" <> show dayNumber
let dayFilename = dayString <> ".txt"
inp <- unlines . map (dropWhile (== ' ')) . lines <$> readFile dayFilename
let (ns' : inp'') = splitOn "\n\n" inp
let ns = map (read :: String -> Int) $ splitOn "," ns'
let inp' = map (map (read :: String -> Int) . words) . lines <$> inp''
print (part1 (ns, inp'))
print (part2 (ns, inp'))
defaultMain
[ bgroup
dayString
[ bench "part1" $ whnf part1 (ns, inp'),
bench "part2" $ whnf part2 (ns, inp')
]
]
| null | https://raw.githubusercontent.com/siraben/haoc-2021/d928c251a82e58b3a20f31638bf0720eb82e5a77/day4.hs | haskell | Slow splitOn for prototyping | # LANGUAGE TupleSections #
import Control.Applicative
import Control.Monad
import Criterion.Main
import Data.Foldable
import Data.Function
import Data.List
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
splitOn :: String -> String -> [String]
splitOn sep s = T.unpack <$> T.splitOn (T.pack sep) (T.pack s)
type Bingo = [[(Int, Bool)]]
mark :: Bingo -> Int -> Bingo
mark b n = map (map change) b
where
change e@(m, b)
| m == n = (m, True)
| otherwise = e
unmarked :: Bingo -> [Int]
unmarked = map fst . filter snd . concat
initBoard :: [[Int]] -> Bingo
initBoard = map (map (,False))
f ns (b, y) = unmarkedNums * finalNum
where
unmarkedNums = sum $ map fst $ filter (not . snd) $ concat finalBoard
finalNum = last nums
finalBoard = foldl' mark (initBoard b) nums
nums = take y ns
part1 (ns, inp') = f ns $ minimumBy (compare `on` snd) . zip inp' $ g ns . initBoard <$> inp'
part2 (ns, inp') = f ns $ maximumBy (compare `on` snd) . zip inp' $ g ns . initBoard <$> inp'
solved b = check b || check (transpose b)
where
check = any (all snd)
g ns b =
scanl' mark b ns
& map solved
& findIndex id
& fromJust
main = do
let dayNumber = 4 :: Int
let dayString = "day" <> show dayNumber
let dayFilename = dayString <> ".txt"
inp <- unlines . map (dropWhile (== ' ')) . lines <$> readFile dayFilename
let (ns' : inp'') = splitOn "\n\n" inp
let ns = map (read :: String -> Int) $ splitOn "," ns'
let inp' = map (map (read :: String -> Int) . words) . lines <$> inp''
print (part1 (ns, inp'))
print (part2 (ns, inp'))
defaultMain
[ bgroup
dayString
[ bench "part1" $ whnf part1 (ns, inp'),
bench "part2" $ whnf part2 (ns, inp')
]
]
|
b76ae12f7183e739e2d65ab11047346893e7a86352f58182012b8e1ae214014d | Andromedans/andromeda | form.ml | (** Formation of judgements from rules *)
open Nucleus_types
let form_alpha_equal_type t1 t2 =
match Alpha_equal.is_type t1 t2 with
| false -> None
| true -> Some (Mk.eq_type Assumption.empty t1 t2)
* Compare two terms for alpha equality .
let form_alpha_equal_term sgn e1 e2 =
let t1 = Sanity.type_of_term sgn e1
and t2 = Sanity.type_of_term sgn e2
in
XXX if e1 and e2 are α - equal , we may apply uniqueness of typing to
conclude that their types are equal , so we do n't have to compute t1 , t2 ,
and t1 = α= t2 .
conclude that their types are equal, so we don't have to compute t1, t2,
and t1 =α= t2. *)
match Alpha_equal.is_type t1 t2 with
| false -> Error.raise (AlphaEqualTypeMismatch (t1, t2))
| true ->
begin match Alpha_equal.is_term e1 e2 with
| false -> None
| true ->
We may keep the assumptions empty here . One might worry
that the assumptions needed for [ e2 : t2 ] have to be included ,
but this does not seem to be the case : we have [ e2 : t2 ] and
[ t1 = = t2 ] ( without assumptions as they are alpha - equal ! ) ,
hence by conversion [ e2 : t1 ] , and whatever assumptions are
required for [ e2 : t2 ] , they 're already present in [ e2 ] .
that the assumptions needed for [e2 : t2] have to be included,
but this does not seem to be the case: we have [e2 : t2] and
[t1 == t2] (without assumptions as they are alpha-equal!),
hence by conversion [e2 : t1], and whatever assumptions are
required for [e2 : t2], they're already present in [e2]. *)
Some (Mk.eq_term Assumption.empty e1 e2 t1)
end
let rec form_alpha_equal_abstraction equal_u abstr1 abstr2 =
match abstr1, abstr2 with
| NotAbstract u1, NotAbstract u2 ->
begin match equal_u u1 u2 with
| None -> None
| Some eq -> Some (Mk.not_abstract eq)
end
| Abstract (x1, t1, abstr1), Abstract (x2, t2, abstr2) ->
let x = Name.prefer x1 x2 in
begin match Alpha_equal.is_type t1 t2 with
| false -> None
| true ->
begin match form_alpha_equal_abstraction equal_u abstr1 abstr2 with
| None -> None
| Some eq -> Some (Mk.abstract x t1 eq)
end
end
| (NotAbstract _, Abstract _)
| (Abstract _, NotAbstract _) -> None
(** Partial rule applications *)
(** Form a rule application for the given constructor [c] *)
let form_constructor_rap sgn c =
let rec fold args = function
| Premise ({meta_boundary=prem;_}, rl) ->
let bdry = Instantiate_meta.abstraction Form_rule.instantiate_premise ~lvl:0 args prem in
let rap abstr =
if not (Check.judgement_boundary_abstraction sgn abstr bdry)
then Error.raise InvalidArgument ;
let arg = Coerce.to_argument abstr in
let args = arg :: args in
fold args rl
in
RapMore (bdry, rap)
| Conclusion (BoundaryIsType ()) ->
RapDone (JudgementIsType (Mk.type_constructor c (Indices.to_list args)))
| Conclusion (BoundaryIsTerm _) ->
RapDone (JudgementIsTerm (Mk.term_constructor c (Indices.to_list args)))
| Conclusion (BoundaryEqType (lhs_schema, rhs_schema)) ->
(* order of arguments not important in [Collect_assumptions.arguments],
we could try avoiding a list reversal caused by [Indices.to_list]. *)
let asmp = Collect_assumptions.arguments (Indices.to_list args)
and lhs = Instantiate_meta.is_type ~lvl:0 args lhs_schema
and rhs = Instantiate_meta.is_type ~lvl:0 args rhs_schema
in
RapDone (JudgementEqType (Mk.eq_type asmp lhs rhs))
| Conclusion (BoundaryEqTerm (e1_schema, e2_schema, t_schema)) ->
(* order of arguments not important in [Collect_assumptions.arguments],
we could try avoiding a list reversal caused by [Indices.to_list]. *)
let asmp = Collect_assumptions.arguments (Indices.to_list args)
and e1 = Instantiate_meta.is_term ~lvl:0 args e1_schema
and e2 = Instantiate_meta.is_term ~lvl:0 args e2_schema
and t = Instantiate_meta.is_type ~lvl:0 args t_schema
in
RapDone (JudgementEqTerm (Mk.eq_term asmp e1 e2 t))
in
let rl = Signature.lookup_rule c sgn in
fold [] rl
(** Form a meta-variable application for the given meta-variable [mv] *)
let form_meta_rap sgn mv =
let rec fold es = function
| Abstract (_, t, bdry) ->
let t = Instantiate_bound.is_type_fully ~lvl:0 es t in
let t_bdry = NotAbstract (BoundaryIsTerm t) in
let rap = function
| NotAbstract (JudgementIsTerm e) ->
if not (Check.is_term_boundary sgn e t)
then Error.raise InvalidArgument ;
let es = e :: es in
fold es bdry
| Abstract _
| NotAbstract (JudgementIsType _ | JudgementEqType _ | JudgementEqTerm _)
-> Error.raise InvalidArgument
in
RapMore (t_bdry, rap)
| NotAbstract bdry ->
let args = List.rev es in
let jdg =
match bdry with
| BoundaryIsType _ -> JudgementIsType (Mk.type_meta (MetaFree mv) args)
| BoundaryIsTerm _ -> JudgementIsTerm (Mk.term_meta (MetaFree mv) args)
| BoundaryEqType (t1, t2) ->
let t1 = Instantiate_bound.is_type_fully ~lvl:0 es t1
and t2 = Instantiate_bound.is_type_fully ~lvl:0 es t2 in
JudgementEqType (Mk.eq_type_meta (MetaFree mv) t1 t2)
| BoundaryEqTerm (e1, e2, t) ->
let e1 = Instantiate_bound.is_term_fully ~lvl:0 es e1
and e2 = Instantiate_bound.is_term_fully ~lvl:0 es e2
and t = Instantiate_bound.is_type_fully ~lvl:0 es t in
JudgementEqTerm (Mk.eq_term_meta (MetaFree mv) e1 e2 t)
in
RapDone jdg
in
fold [] mv.meta_boundary
(** Form a rap from a rule *)
let form_rule_rap sgn inst rl =
let rec fold args = function
| Premise ({meta_boundary=prem;_}, drv) ->
let bdry = Instantiate_meta.abstraction Form_rule.instantiate_premise ~lvl:0 args prem in
let rap abstr =
if not (Check.judgement_boundary_abstraction sgn abstr bdry)
then Error.raise InvalidArgument ;
let arg = Coerce.to_argument abstr in
let args = arg :: args in
fold args drv
in
RapMore (bdry, rap)
| Conclusion concl ->
let concl = inst args concl in
RapDone concl
in
fold [] rl
let form_derivation_rap sgn drv =
form_rule_rap sgn (Instantiate_meta.judgement ~lvl:0) drv
let form_is_type_rap sgn drv =
form_rule_rap sgn (Instantiate_meta.is_type ~lvl:0) drv
let form_is_term_rap sgn drv =
form_rule_rap sgn (Instantiate_meta.is_term ~lvl:0) drv
let form_eq_type_rap sgn drv =
form_rule_rap sgn (Instantiate_meta.eq_type ~lvl:0) drv
let form_eq_term_rap sgn drv =
form_rule_rap sgn (Instantiate_meta.eq_term ~lvl:0) drv
(* A rather finicky and dangerous operation that directly makes a derivation out
of a primitive rule, by directly manipulating bound meta-variables. *)
let rule_as_derivation sgn cnstr =
(* look up the rule *)
let rl = Signature.lookup_rule cnstr sgn in
(* compute the arity of the rule *)
let arity =
let rec count = function
| Conclusion _ -> 0
| Premise (_, bdry) -> 1 + count bdry
in
count rl
in
let rec fold k args = function
| Conclusion bdry ->
let args = List.rev args in
let jdg =
match bdry with
| BoundaryIsType () -> JudgementIsType (Mk.type_constructor cnstr args)
| BoundaryIsTerm _ -> JudgementIsTerm (Mk.term_constructor cnstr args)
| BoundaryEqType (t1, t2) ->
let asmp = Collect_assumptions.arguments args in
JudgementEqType (Mk.eq_type asmp t1 t2)
| BoundaryEqTerm (e1, e2, t) ->
let asmp = Collect_assumptions.arguments args in
JudgementEqTerm (Mk.eq_term asmp e1 e2 t)
in
Conclusion jdg
| Premise (prem, bdry) ->
(* compute the k-th argument *)
let rec mk_arg i args = function
| NotAbstract bdry ->
let args = List.rev args in
let jdg =
match bdry with
| BoundaryIsType () -> JudgementIsType (Mk.type_meta (MetaBound k) args)
| BoundaryIsTerm _ -> JudgementIsTerm (Mk.term_meta (MetaBound k) args)
| BoundaryEqType (t1, t2) ->
let t1 = Shift_meta.is_type (k+1) t1
and t2 = Shift_meta.is_type (k+1) t2 in
let asmp = Collect_assumptions.term_arguments ~lvl:k args in
JudgementEqType (Mk.eq_type asmp t1 t2)
| BoundaryEqTerm (e1, e2, t) ->
let e1 = Shift_meta.is_term (k+1) e1
and e2 = Shift_meta.is_term (k+1) e2
and t = Shift_meta.is_type (k+1) t in
let asmp = Collect_assumptions.term_arguments ~lvl:k args in
JudgementEqTerm (Mk.eq_term asmp e1 e2 t)
in
Arg_NotAbstract jdg
| Abstract (x, t, bdry) ->
let args = (TermBoundVar i) :: args in
Arg_Abstract (x, mk_arg (i+1) args bdry)
in
let arg = mk_arg 0 [] prem.meta_boundary in
let drv = fold (k-1) (arg :: args) bdry in
Premise (prem, drv)
in
fold (arity-1) [] rl
(** Formation of a term from an atom *)
let form_is_term_atom = Mk.atom
let reflexivity_type t = Mk.eq_type Assumption.empty t t
let reflexivity_term sgn e =
let t = Sanity.type_of_term sgn e in
Mk.eq_term Assumption.empty e e t
exception ObjectJudgementExpected
let reflexivity_judgement_abstraction sgn abstr =
let rec fold abstr =
match Invert.invert_judgement_abstraction abstr with
| Stump_Abstract (atm, abstr) ->
let abstr = fold abstr in
Abstract.judgement_abstraction atm abstr
| Stump_NotAbstract (JudgementIsType t) ->
Abstract.not_abstract (JudgementEqType (reflexivity_type t))
| Stump_NotAbstract (JudgementIsTerm e) ->
Abstract.not_abstract (JudgementEqTerm (reflexivity_term sgn e))
| Stump_NotAbstract (JudgementEqType _ | JudgementEqTerm _) ->
raise ObjectJudgementExpected
in
try
Some (fold abstr)
with
| ObjectJudgementExpected -> None
let symmetry_term (EqTerm (asmp, e1, e2, t)) = Mk.eq_term asmp e2 e1 t
let symmetry_type (EqType (asmp, t1, t2)) = Mk.eq_type asmp t2 t1
let transitivity_term (EqTerm (asmp, e1, e2, t)) (EqTerm (asmp', e1', e2', t')) =
match Alpha_equal.is_term e2 e1' with
| false -> Error.raise (AlphaEqualTermMismatch (e2, e1'))
| true ->
let asmp = Assumption.union asmp (Assumption.union asmp' (Collect_assumptions.is_term e1'))
in Mk.eq_term asmp e1 e2' t
let transitivity_term' (EqTerm (asmp, e1, e2, t)) (EqTerm (asmp', e1', e2', t')) =
match Alpha_equal.is_term e2 e1' with
| false -> Error.raise (AlphaEqualTermMismatch (e2, e1'))
| true ->
let asmp = Assumption.union asmp (Assumption.union asmp' (Collect_assumptions.is_term e2))
in Mk.eq_term asmp e1 e2' t'
let transitivity_type (EqType (asmp1, t1, t2)) (EqType (asmp2, u1, u2)) =
begin match Alpha_equal.is_type t2 u1 with
| false -> Error.raise (AlphaEqualTypeMismatch (t2, u1))
| true ->
(* XXX could use assumptions of [u1] instead, or whichever is better. *)
let asmp = Assumption.union asmp1 (Assumption.union asmp2 (Collect_assumptions.is_type t2))
in Mk.eq_type asmp t1 u2
end
(** Formation of boundaries *)
let form_is_type_boundary = BoundaryIsType ()
let form_is_term_boundary t = BoundaryIsTerm t
let form_eq_type_boundary t1 t2 = BoundaryEqType (t1, t2)
let form_eq_term_boundary sgn e1 e2 =
let t1 = Sanity.type_of_term sgn e1
and t2 = Sanity.type_of_term sgn e2 in
if Alpha_equal.is_type t1 t2 then
BoundaryEqTerm (e1, e2, t1)
else
Error.raise (AlphaEqualTypeMismatch (t1, t2))
let rec form_is_term_boundary_abstraction = function
| NotAbstract t ->
NotAbstract (form_is_term_boundary t)
| Abstract (x, t, abstr) ->
Abstract (x, t, form_is_term_boundary_abstraction abstr)
| null | https://raw.githubusercontent.com/Andromedans/andromeda/a5c678450e6c6d4a7cd5eee1196bde558541b994/src/nucleus/form.ml | ocaml | * Formation of judgements from rules
* Partial rule applications
* Form a rule application for the given constructor [c]
order of arguments not important in [Collect_assumptions.arguments],
we could try avoiding a list reversal caused by [Indices.to_list].
order of arguments not important in [Collect_assumptions.arguments],
we could try avoiding a list reversal caused by [Indices.to_list].
* Form a meta-variable application for the given meta-variable [mv]
* Form a rap from a rule
A rather finicky and dangerous operation that directly makes a derivation out
of a primitive rule, by directly manipulating bound meta-variables.
look up the rule
compute the arity of the rule
compute the k-th argument
* Formation of a term from an atom
XXX could use assumptions of [u1] instead, or whichever is better.
* Formation of boundaries |
open Nucleus_types
let form_alpha_equal_type t1 t2 =
match Alpha_equal.is_type t1 t2 with
| false -> None
| true -> Some (Mk.eq_type Assumption.empty t1 t2)
* Compare two terms for alpha equality .
let form_alpha_equal_term sgn e1 e2 =
let t1 = Sanity.type_of_term sgn e1
and t2 = Sanity.type_of_term sgn e2
in
XXX if e1 and e2 are α - equal , we may apply uniqueness of typing to
conclude that their types are equal , so we do n't have to compute t1 , t2 ,
and t1 = α= t2 .
conclude that their types are equal, so we don't have to compute t1, t2,
and t1 =α= t2. *)
match Alpha_equal.is_type t1 t2 with
| false -> Error.raise (AlphaEqualTypeMismatch (t1, t2))
| true ->
begin match Alpha_equal.is_term e1 e2 with
| false -> None
| true ->
We may keep the assumptions empty here . One might worry
that the assumptions needed for [ e2 : t2 ] have to be included ,
but this does not seem to be the case : we have [ e2 : t2 ] and
[ t1 = = t2 ] ( without assumptions as they are alpha - equal ! ) ,
hence by conversion [ e2 : t1 ] , and whatever assumptions are
required for [ e2 : t2 ] , they 're already present in [ e2 ] .
that the assumptions needed for [e2 : t2] have to be included,
but this does not seem to be the case: we have [e2 : t2] and
[t1 == t2] (without assumptions as they are alpha-equal!),
hence by conversion [e2 : t1], and whatever assumptions are
required for [e2 : t2], they're already present in [e2]. *)
Some (Mk.eq_term Assumption.empty e1 e2 t1)
end
let rec form_alpha_equal_abstraction equal_u abstr1 abstr2 =
match abstr1, abstr2 with
| NotAbstract u1, NotAbstract u2 ->
begin match equal_u u1 u2 with
| None -> None
| Some eq -> Some (Mk.not_abstract eq)
end
| Abstract (x1, t1, abstr1), Abstract (x2, t2, abstr2) ->
let x = Name.prefer x1 x2 in
begin match Alpha_equal.is_type t1 t2 with
| false -> None
| true ->
begin match form_alpha_equal_abstraction equal_u abstr1 abstr2 with
| None -> None
| Some eq -> Some (Mk.abstract x t1 eq)
end
end
| (NotAbstract _, Abstract _)
| (Abstract _, NotAbstract _) -> None
let form_constructor_rap sgn c =
let rec fold args = function
| Premise ({meta_boundary=prem;_}, rl) ->
let bdry = Instantiate_meta.abstraction Form_rule.instantiate_premise ~lvl:0 args prem in
let rap abstr =
if not (Check.judgement_boundary_abstraction sgn abstr bdry)
then Error.raise InvalidArgument ;
let arg = Coerce.to_argument abstr in
let args = arg :: args in
fold args rl
in
RapMore (bdry, rap)
| Conclusion (BoundaryIsType ()) ->
RapDone (JudgementIsType (Mk.type_constructor c (Indices.to_list args)))
| Conclusion (BoundaryIsTerm _) ->
RapDone (JudgementIsTerm (Mk.term_constructor c (Indices.to_list args)))
| Conclusion (BoundaryEqType (lhs_schema, rhs_schema)) ->
let asmp = Collect_assumptions.arguments (Indices.to_list args)
and lhs = Instantiate_meta.is_type ~lvl:0 args lhs_schema
and rhs = Instantiate_meta.is_type ~lvl:0 args rhs_schema
in
RapDone (JudgementEqType (Mk.eq_type asmp lhs rhs))
| Conclusion (BoundaryEqTerm (e1_schema, e2_schema, t_schema)) ->
let asmp = Collect_assumptions.arguments (Indices.to_list args)
and e1 = Instantiate_meta.is_term ~lvl:0 args e1_schema
and e2 = Instantiate_meta.is_term ~lvl:0 args e2_schema
and t = Instantiate_meta.is_type ~lvl:0 args t_schema
in
RapDone (JudgementEqTerm (Mk.eq_term asmp e1 e2 t))
in
let rl = Signature.lookup_rule c sgn in
fold [] rl
let form_meta_rap sgn mv =
let rec fold es = function
| Abstract (_, t, bdry) ->
let t = Instantiate_bound.is_type_fully ~lvl:0 es t in
let t_bdry = NotAbstract (BoundaryIsTerm t) in
let rap = function
| NotAbstract (JudgementIsTerm e) ->
if not (Check.is_term_boundary sgn e t)
then Error.raise InvalidArgument ;
let es = e :: es in
fold es bdry
| Abstract _
| NotAbstract (JudgementIsType _ | JudgementEqType _ | JudgementEqTerm _)
-> Error.raise InvalidArgument
in
RapMore (t_bdry, rap)
| NotAbstract bdry ->
let args = List.rev es in
let jdg =
match bdry with
| BoundaryIsType _ -> JudgementIsType (Mk.type_meta (MetaFree mv) args)
| BoundaryIsTerm _ -> JudgementIsTerm (Mk.term_meta (MetaFree mv) args)
| BoundaryEqType (t1, t2) ->
let t1 = Instantiate_bound.is_type_fully ~lvl:0 es t1
and t2 = Instantiate_bound.is_type_fully ~lvl:0 es t2 in
JudgementEqType (Mk.eq_type_meta (MetaFree mv) t1 t2)
| BoundaryEqTerm (e1, e2, t) ->
let e1 = Instantiate_bound.is_term_fully ~lvl:0 es e1
and e2 = Instantiate_bound.is_term_fully ~lvl:0 es e2
and t = Instantiate_bound.is_type_fully ~lvl:0 es t in
JudgementEqTerm (Mk.eq_term_meta (MetaFree mv) e1 e2 t)
in
RapDone jdg
in
fold [] mv.meta_boundary
let form_rule_rap sgn inst rl =
let rec fold args = function
| Premise ({meta_boundary=prem;_}, drv) ->
let bdry = Instantiate_meta.abstraction Form_rule.instantiate_premise ~lvl:0 args prem in
let rap abstr =
if not (Check.judgement_boundary_abstraction sgn abstr bdry)
then Error.raise InvalidArgument ;
let arg = Coerce.to_argument abstr in
let args = arg :: args in
fold args drv
in
RapMore (bdry, rap)
| Conclusion concl ->
let concl = inst args concl in
RapDone concl
in
fold [] rl
let form_derivation_rap sgn drv =
form_rule_rap sgn (Instantiate_meta.judgement ~lvl:0) drv
let form_is_type_rap sgn drv =
form_rule_rap sgn (Instantiate_meta.is_type ~lvl:0) drv
let form_is_term_rap sgn drv =
form_rule_rap sgn (Instantiate_meta.is_term ~lvl:0) drv
let form_eq_type_rap sgn drv =
form_rule_rap sgn (Instantiate_meta.eq_type ~lvl:0) drv
let form_eq_term_rap sgn drv =
form_rule_rap sgn (Instantiate_meta.eq_term ~lvl:0) drv
let rule_as_derivation sgn cnstr =
let rl = Signature.lookup_rule cnstr sgn in
let arity =
let rec count = function
| Conclusion _ -> 0
| Premise (_, bdry) -> 1 + count bdry
in
count rl
in
let rec fold k args = function
| Conclusion bdry ->
let args = List.rev args in
let jdg =
match bdry with
| BoundaryIsType () -> JudgementIsType (Mk.type_constructor cnstr args)
| BoundaryIsTerm _ -> JudgementIsTerm (Mk.term_constructor cnstr args)
| BoundaryEqType (t1, t2) ->
let asmp = Collect_assumptions.arguments args in
JudgementEqType (Mk.eq_type asmp t1 t2)
| BoundaryEqTerm (e1, e2, t) ->
let asmp = Collect_assumptions.arguments args in
JudgementEqTerm (Mk.eq_term asmp e1 e2 t)
in
Conclusion jdg
| Premise (prem, bdry) ->
let rec mk_arg i args = function
| NotAbstract bdry ->
let args = List.rev args in
let jdg =
match bdry with
| BoundaryIsType () -> JudgementIsType (Mk.type_meta (MetaBound k) args)
| BoundaryIsTerm _ -> JudgementIsTerm (Mk.term_meta (MetaBound k) args)
| BoundaryEqType (t1, t2) ->
let t1 = Shift_meta.is_type (k+1) t1
and t2 = Shift_meta.is_type (k+1) t2 in
let asmp = Collect_assumptions.term_arguments ~lvl:k args in
JudgementEqType (Mk.eq_type asmp t1 t2)
| BoundaryEqTerm (e1, e2, t) ->
let e1 = Shift_meta.is_term (k+1) e1
and e2 = Shift_meta.is_term (k+1) e2
and t = Shift_meta.is_type (k+1) t in
let asmp = Collect_assumptions.term_arguments ~lvl:k args in
JudgementEqTerm (Mk.eq_term asmp e1 e2 t)
in
Arg_NotAbstract jdg
| Abstract (x, t, bdry) ->
let args = (TermBoundVar i) :: args in
Arg_Abstract (x, mk_arg (i+1) args bdry)
in
let arg = mk_arg 0 [] prem.meta_boundary in
let drv = fold (k-1) (arg :: args) bdry in
Premise (prem, drv)
in
fold (arity-1) [] rl
let form_is_term_atom = Mk.atom
let reflexivity_type t = Mk.eq_type Assumption.empty t t
let reflexivity_term sgn e =
let t = Sanity.type_of_term sgn e in
Mk.eq_term Assumption.empty e e t
exception ObjectJudgementExpected
let reflexivity_judgement_abstraction sgn abstr =
let rec fold abstr =
match Invert.invert_judgement_abstraction abstr with
| Stump_Abstract (atm, abstr) ->
let abstr = fold abstr in
Abstract.judgement_abstraction atm abstr
| Stump_NotAbstract (JudgementIsType t) ->
Abstract.not_abstract (JudgementEqType (reflexivity_type t))
| Stump_NotAbstract (JudgementIsTerm e) ->
Abstract.not_abstract (JudgementEqTerm (reflexivity_term sgn e))
| Stump_NotAbstract (JudgementEqType _ | JudgementEqTerm _) ->
raise ObjectJudgementExpected
in
try
Some (fold abstr)
with
| ObjectJudgementExpected -> None
let symmetry_term (EqTerm (asmp, e1, e2, t)) = Mk.eq_term asmp e2 e1 t
let symmetry_type (EqType (asmp, t1, t2)) = Mk.eq_type asmp t2 t1
let transitivity_term (EqTerm (asmp, e1, e2, t)) (EqTerm (asmp', e1', e2', t')) =
match Alpha_equal.is_term e2 e1' with
| false -> Error.raise (AlphaEqualTermMismatch (e2, e1'))
| true ->
let asmp = Assumption.union asmp (Assumption.union asmp' (Collect_assumptions.is_term e1'))
in Mk.eq_term asmp e1 e2' t
let transitivity_term' (EqTerm (asmp, e1, e2, t)) (EqTerm (asmp', e1', e2', t')) =
match Alpha_equal.is_term e2 e1' with
| false -> Error.raise (AlphaEqualTermMismatch (e2, e1'))
| true ->
let asmp = Assumption.union asmp (Assumption.union asmp' (Collect_assumptions.is_term e2))
in Mk.eq_term asmp e1 e2' t'
let transitivity_type (EqType (asmp1, t1, t2)) (EqType (asmp2, u1, u2)) =
begin match Alpha_equal.is_type t2 u1 with
| false -> Error.raise (AlphaEqualTypeMismatch (t2, u1))
| true ->
let asmp = Assumption.union asmp1 (Assumption.union asmp2 (Collect_assumptions.is_type t2))
in Mk.eq_type asmp t1 u2
end
let form_is_type_boundary = BoundaryIsType ()
let form_is_term_boundary t = BoundaryIsTerm t
let form_eq_type_boundary t1 t2 = BoundaryEqType (t1, t2)
let form_eq_term_boundary sgn e1 e2 =
let t1 = Sanity.type_of_term sgn e1
and t2 = Sanity.type_of_term sgn e2 in
if Alpha_equal.is_type t1 t2 then
BoundaryEqTerm (e1, e2, t1)
else
Error.raise (AlphaEqualTypeMismatch (t1, t2))
let rec form_is_term_boundary_abstraction = function
| NotAbstract t ->
NotAbstract (form_is_term_boundary t)
| Abstract (x, t, abstr) ->
Abstract (x, t, form_is_term_boundary_abstraction abstr)
|
a7c2abd90eb4370fff24da8b07295cd27c40e9586b4956bfc73c8dd4f251ecde | haslab/HAAP | RunT3.hs | module Main where
import LI11718
import qualified Tarefa3_2017li1g180 as T3
import System.Environment
import Text.Read
main = do
args <- getArgs
case args of
["movimenta"] -> do
str <- getContents
let params = readMaybe str
case params of
Nothing -> error "parâmetros inválidos"
Just (mapa,tempo,carro) -> print $ T3.movimenta mapa tempo carro
["testes"] -> print $ T3.testesT3
otherwise -> error "RunT3 argumentos inválidos" | null | https://raw.githubusercontent.com/haslab/HAAP/5acf9efaf0e5f6cba1c2482e51bda703f405a86f/examples/plab/svn/2017li1g180/src/RunT3.hs | haskell | module Main where
import LI11718
import qualified Tarefa3_2017li1g180 as T3
import System.Environment
import Text.Read
main = do
args <- getArgs
case args of
["movimenta"] -> do
str <- getContents
let params = readMaybe str
case params of
Nothing -> error "parâmetros inválidos"
Just (mapa,tempo,carro) -> print $ T3.movimenta mapa tempo carro
["testes"] -> print $ T3.testesT3
otherwise -> error "RunT3 argumentos inválidos" | |
15511b6d68fd9b97d591b878f49d3b0ed90b3f152dd46311efdda444ed0aef9e | pflanze/chj-schemelib | debuggable-promise-everywhere.scm | Copyright 2017 by < >
;;; This file is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License ( GPL ) as published
by the Free Software Foundation , either version 2 of the License , or
;;; (at your option) any later version.
(require define-macro-star
debuggable-promise)
(export make-promise)
(set! make-promise debuggable#make-promise)
| null | https://raw.githubusercontent.com/pflanze/chj-schemelib/59ff8476e39f207c2f1d807cfc9670581c8cedd3/debuggable-promise-everywhere.scm | scheme | This file is free software; you can redistribute it and/or modify
(at your option) any later version. | Copyright 2017 by < >
it under the terms of the GNU General Public License ( GPL ) as published
by the Free Software Foundation , either version 2 of the License , or
(require define-macro-star
debuggable-promise)
(export make-promise)
(set! make-promise debuggable#make-promise)
|
30d631d55fbb2db273aa2e2735cd003eaa409e9cb60f6bacc6e5fefaebd06aff | jmingtan/clonings | maps1.clj | ;; maps1.clj
;; Make me compile by filling in the ??? parts, scroll down for hints :)
(ns collections.maps1)
;; maps are associative collections of key-value pairs, created with the {} literal
(def a-map #{:a 1
:b 2
:c 3
:d 4
:e 5})
Here are two possible ways to retrieve an element from a map :
First method :
returns 2
Second method :
returns 2
The second method works because keyword types also act as a function ,
;; which behaves as if calling the `get` function on it.
#Keywords
;; try creating your own map here!
(def my-map ???)
(defn -main []
(if (map? my-map)
(println "I'm going to be reading your map now...")
(do
(println "Hey! It doesn't look like you've given me a valid map!")
(throw (IllegalArgumentException. "Make me a map!"))))
(println "There are" (count my-map) "elements in your map!")
(if (not-empty my-map)
(let [random-key (rand-nth (keys my-map))]
(println (format "A random pair from your map is... %s => %s!" random-key (get random-key my-map))))
(do
(println "It looks like your map is empty, why don't you try putting in some items?")
(throw (IllegalArgumentException. "Give me some items, please :)")))))
| null | https://raw.githubusercontent.com/jmingtan/clonings/ca64b031ab26a1924bed91f5c9c98b6dd69fc129/exercises/collections/maps1.clj | clojure | maps1.clj
Make me compile by filling in the ??? parts, scroll down for hints :)
maps are associative collections of key-value pairs, created with the {} literal
which behaves as if calling the `get` function on it.
try creating your own map here! |
(ns collections.maps1)
(def a-map #{:a 1
:b 2
:c 3
:d 4
:e 5})
Here are two possible ways to retrieve an element from a map :
First method :
returns 2
Second method :
returns 2
The second method works because keyword types also act as a function ,
#Keywords
(def my-map ???)
(defn -main []
(if (map? my-map)
(println "I'm going to be reading your map now...")
(do
(println "Hey! It doesn't look like you've given me a valid map!")
(throw (IllegalArgumentException. "Make me a map!"))))
(println "There are" (count my-map) "elements in your map!")
(if (not-empty my-map)
(let [random-key (rand-nth (keys my-map))]
(println (format "A random pair from your map is... %s => %s!" random-key (get random-key my-map))))
(do
(println "It looks like your map is empty, why don't you try putting in some items?")
(throw (IllegalArgumentException. "Give me some items, please :)")))))
|
e6f87c07a156352f7bddff3c83d0d3bab981b72ea914bf7c0333a89119cf4478 | geoffder/dometyl-keyboard | key.ml | open! OCADml
open! OSCADml
module Face = struct
type t =
{ path : Path3.t
; points : Points.t
; bounds : Points.t
; normal : V3.t [@cad.unit]
}
[@@deriving cad]
let direction { points = { top_left; top_right; _ }; _ } =
V3.normalize V3.(top_left -@ top_right)
end
module Faces = struct
type t =
{ north : Face.t [@cad.d3]
; south : Face.t
; east : Face.t
; west : Face.t
}
[@@deriving cad]
let map f t = { north = f t.north; south = f t.south; east = f t.east; west = f t.west }
let fold f init t =
let f' = Fun.flip f in
f init t.north |> f' t.south |> f' t.east |> f' t.west
let face t = function
| `North -> t.north
| `South -> t.south
| `East -> t.east
| `West -> t.west
end
type config =
{ outer_w : float
; outer_h : float
; inner_w : float
; inner_h : float
; thickness : float
; clip : Scad.d3 -> Scad.d3
; cap_height : float
; clearance : float
; corner : Path3.Round.corner option
; fn : int option
}
type t =
{ config : config [@cad.ignore]
; scad : Scad.d3
; origin : V3.t
; faces : Faces.t
; cap : Scad.d3 option
; cutout : Scad.d3 option
}
[@@deriving cad]
let orthogonal t side = (Faces.face t.faces side).normal
let normal t =
let Points.{ top_left; bot_left; _ } = (Faces.face t.faces `North).points in
V3.(normalize (top_left -@ bot_left))
let rotate_about_origin r t = rotate ~about:t.origin r t
let quaternion_about_origin angle t =
let q = Quaternion.make (normal t) angle in
quaternion ~about:t.origin q t
let cycle_faces ({ faces = { north; south; east; west }; _ } as t) =
{ t with faces = { north = west; south = east; east = north; west = south } }
let make
?(render = true)
?cap
?cutout
( { outer_w; outer_h; inner_w; inner_h; thickness; clip; cap_height; corner; fn; _ }
as config )
=
let sq =
Path3.square ~center:true ~plane:Plane.(neg xz) (v2 outer_w thickness)
|> Path3.ytrans (outer_h /. -2.)
in
let front =
match corner with
| Some corner ->
Path3.(roundover ?fn ~overrun:`Fix @@ Round.flat ~corner ~closed:true sq)
| None -> sq
in
let hole =
let outer = Scad.of_mesh @@ Mesh.of_rows [ Path3.ytrans outer_h front; front ]
and inner = Scad.cube ~center:true (v3 inner_w inner_h (thickness +. 0.1)) in
clip @@ Scad.sub outer inner
in
let faces =
let edges path =
match Path3.segment ~closed:true path with
| s0 :: s1 :: segs ->
let f ((a, a_len, b, b_len) as acc) (s : V3.line) =
let s_len = V3.distance s.a s.b in
if a_len > b_len && s_len > b_len
then a, a_len, s, s_len
else if s_len > a_len
then s, s_len, b, b_len
else acc
in
let a, _, b, _ =
List.fold_left f (s0, V3.distance s0.a s0.b, s1, V3.distance s1.a s1.b) segs
in
if V3.z a.a > 0. then a, b else b, a
| _ -> failwith "unreachable"
in
let south =
let top_edge, bot_edge = edges front in
let points =
Points.
{ top_left = top_edge.b
; top_right = top_edge.a
; bot_left = bot_edge.a
; bot_right = bot_edge.b
; centre = v3 0. (outer_h /. -2.) 0.
}
and normal = v3 0. (-1.) 0. in
Face.{ path = front; points; bounds = Points.of_ccw_path sq; normal }
in
let north = Face.zrot Float.pi south in
let east =
let sq =
[ north.points.bot_right
; south.points.bot_left
; south.points.top_left
; north.points.top_right
]
in
let path =
match corner with
| Some corner ->
Path3.(roundover ?fn ~overrun:`Fix @@ Round.flat ~corner ~closed:true sq)
| None -> sq
in
let top_edge, bot_edge = edges path
and centre = v3 (outer_w /. 2.) 0. 0. in
let points =
Points.
{ top_left = top_edge.b
; top_right = top_edge.a
; bot_left = bot_edge.a
; bot_right = bot_edge.b
; centre
}
and bounds =
Points.
{ top_left = north.points.top_right
; top_right = south.points.top_left
; bot_left = north.points.bot_right
; bot_right = south.points.bot_left
; centre
}
and normal = v3 1. 0. 0. in
Face.{ path; points; bounds; normal }
in
let west = Face.zrot Float.pi east in
Faces.{ north; south; east; west }
in
{ config
; scad = (if render then Scad.render hole else hole)
; origin = v3 0. 0. 0.
; faces
; cap = Option.map (Scad.translate (v3 0. 0. (cap_height +. (thickness /. 2.)))) cap
; cutout = (if render then Option.map Scad.render cutout else cutout)
}
let mirror_internals t =
{ t with
scad = Scad.mirror (v3 1. 0. 0.) t.scad
; cutout = Option.map (Scad.mirror (v3 1. 0. 0.)) t.cutout
}
let to_scad = function
| { scad; cutout = Some cut; _ } -> Scad.difference scad [ cut ]
| { scad; _ } -> scad
| null | https://raw.githubusercontent.com/geoffder/dometyl-keyboard/d6af46ea157a38167b50cc492e16428644806ddb/lib/key.ml | ocaml | open! OCADml
open! OSCADml
module Face = struct
type t =
{ path : Path3.t
; points : Points.t
; bounds : Points.t
; normal : V3.t [@cad.unit]
}
[@@deriving cad]
let direction { points = { top_left; top_right; _ }; _ } =
V3.normalize V3.(top_left -@ top_right)
end
module Faces = struct
type t =
{ north : Face.t [@cad.d3]
; south : Face.t
; east : Face.t
; west : Face.t
}
[@@deriving cad]
let map f t = { north = f t.north; south = f t.south; east = f t.east; west = f t.west }
let fold f init t =
let f' = Fun.flip f in
f init t.north |> f' t.south |> f' t.east |> f' t.west
let face t = function
| `North -> t.north
| `South -> t.south
| `East -> t.east
| `West -> t.west
end
type config =
{ outer_w : float
; outer_h : float
; inner_w : float
; inner_h : float
; thickness : float
; clip : Scad.d3 -> Scad.d3
; cap_height : float
; clearance : float
; corner : Path3.Round.corner option
; fn : int option
}
type t =
{ config : config [@cad.ignore]
; scad : Scad.d3
; origin : V3.t
; faces : Faces.t
; cap : Scad.d3 option
; cutout : Scad.d3 option
}
[@@deriving cad]
let orthogonal t side = (Faces.face t.faces side).normal
let normal t =
let Points.{ top_left; bot_left; _ } = (Faces.face t.faces `North).points in
V3.(normalize (top_left -@ bot_left))
let rotate_about_origin r t = rotate ~about:t.origin r t
let quaternion_about_origin angle t =
let q = Quaternion.make (normal t) angle in
quaternion ~about:t.origin q t
let cycle_faces ({ faces = { north; south; east; west }; _ } as t) =
{ t with faces = { north = west; south = east; east = north; west = south } }
let make
?(render = true)
?cap
?cutout
( { outer_w; outer_h; inner_w; inner_h; thickness; clip; cap_height; corner; fn; _ }
as config )
=
let sq =
Path3.square ~center:true ~plane:Plane.(neg xz) (v2 outer_w thickness)
|> Path3.ytrans (outer_h /. -2.)
in
let front =
match corner with
| Some corner ->
Path3.(roundover ?fn ~overrun:`Fix @@ Round.flat ~corner ~closed:true sq)
| None -> sq
in
let hole =
let outer = Scad.of_mesh @@ Mesh.of_rows [ Path3.ytrans outer_h front; front ]
and inner = Scad.cube ~center:true (v3 inner_w inner_h (thickness +. 0.1)) in
clip @@ Scad.sub outer inner
in
let faces =
let edges path =
match Path3.segment ~closed:true path with
| s0 :: s1 :: segs ->
let f ((a, a_len, b, b_len) as acc) (s : V3.line) =
let s_len = V3.distance s.a s.b in
if a_len > b_len && s_len > b_len
then a, a_len, s, s_len
else if s_len > a_len
then s, s_len, b, b_len
else acc
in
let a, _, b, _ =
List.fold_left f (s0, V3.distance s0.a s0.b, s1, V3.distance s1.a s1.b) segs
in
if V3.z a.a > 0. then a, b else b, a
| _ -> failwith "unreachable"
in
let south =
let top_edge, bot_edge = edges front in
let points =
Points.
{ top_left = top_edge.b
; top_right = top_edge.a
; bot_left = bot_edge.a
; bot_right = bot_edge.b
; centre = v3 0. (outer_h /. -2.) 0.
}
and normal = v3 0. (-1.) 0. in
Face.{ path = front; points; bounds = Points.of_ccw_path sq; normal }
in
let north = Face.zrot Float.pi south in
let east =
let sq =
[ north.points.bot_right
; south.points.bot_left
; south.points.top_left
; north.points.top_right
]
in
let path =
match corner with
| Some corner ->
Path3.(roundover ?fn ~overrun:`Fix @@ Round.flat ~corner ~closed:true sq)
| None -> sq
in
let top_edge, bot_edge = edges path
and centre = v3 (outer_w /. 2.) 0. 0. in
let points =
Points.
{ top_left = top_edge.b
; top_right = top_edge.a
; bot_left = bot_edge.a
; bot_right = bot_edge.b
; centre
}
and bounds =
Points.
{ top_left = north.points.top_right
; top_right = south.points.top_left
; bot_left = north.points.bot_right
; bot_right = south.points.bot_left
; centre
}
and normal = v3 1. 0. 0. in
Face.{ path; points; bounds; normal }
in
let west = Face.zrot Float.pi east in
Faces.{ north; south; east; west }
in
{ config
; scad = (if render then Scad.render hole else hole)
; origin = v3 0. 0. 0.
; faces
; cap = Option.map (Scad.translate (v3 0. 0. (cap_height +. (thickness /. 2.)))) cap
; cutout = (if render then Option.map Scad.render cutout else cutout)
}
let mirror_internals t =
{ t with
scad = Scad.mirror (v3 1. 0. 0.) t.scad
; cutout = Option.map (Scad.mirror (v3 1. 0. 0.)) t.cutout
}
let to_scad = function
| { scad; cutout = Some cut; _ } -> Scad.difference scad [ cut ]
| { scad; _ } -> scad
| |
20846bb9285bd2c7e232fe3f1218653315270b6400aa29ce921fed28d5b165a1 | ocaml-multicore/tezos | fitness_repr.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
type t = {
level : Raw_level_repr.t;
locked_round : Round_repr.t option;
predecessor_round : Round_repr.t;
by convention , predecessor_round is 0 in case of protocol migration
round : Round_repr.t;
}
let encoding =
let open Data_encoding in
def
"fitness"
(conv_with_guard
(fun {level; locked_round; predecessor_round; round} ->
(level, locked_round, predecessor_round, round))
(fun (level, locked_round, predecessor_round, round) ->
match locked_round with
| None -> ok {level; locked_round; predecessor_round; round}
| Some locked_round_val ->
if Round_repr.(round <= locked_round_val) then
Error "Locked round must be smaller than round."
else ok {level; locked_round; predecessor_round; round})
(obj4
(req "level" Raw_level_repr.encoding)
(req "locked_round" (option Round_repr.encoding))
(req "predecessor_round" Round_repr.encoding)
(req "round" Round_repr.encoding)))
let pp ppf f =
let minus_sign =
if Round_repr.(f.predecessor_round = Round_repr.zero) then "" else "-"
in
let locked_round ppf locked_round =
match locked_round with
| None -> Format.pp_print_string ppf "unlocked"
| Some round -> Format.fprintf ppf "locked: %a" Round_repr.pp round
in
Format.fprintf
ppf
"(%a, %a, %s%a, %a)"
Raw_level_repr.pp
f.level
locked_round
f.locked_round
minus_sign
Round_repr.pp
f.predecessor_round
Round_repr.pp
f.round
type error +=
| (* `Permanent *) Invalid_fitness
| (* `Permanent *) Wrong_fitness
| (* `Permanent *) Outdated_fitness
| (* `Permanent *)
Locked_round_not_less_than_round of {
round : Round_repr.t;
locked_round : Round_repr.t;
}
let () =
register_error_kind
`Permanent
~id:"invalid_fitness"
~title:"Invalid fitness"
~description:
"Fitness representation should be exactly 4 times 4 bytes long."
~pp:(fun ppf () -> Format.fprintf ppf "Invalid fitness")
Data_encoding.empty
(function Invalid_fitness -> Some () | _ -> None)
(fun () -> Invalid_fitness) ;
register_error_kind
`Permanent
~id:"wrong_fitness"
~title:"Wrong fitness"
~description:"Wrong fitness."
~pp:(fun ppf () -> Format.fprintf ppf "Wrong fitness.")
Data_encoding.empty
(function Wrong_fitness -> Some () | _ -> None)
(fun () -> Wrong_fitness) ;
register_error_kind
`Permanent
~id:"outdated_fitness"
~title:"Outdated fitness"
~description:"Outdated fitness: referring to a previous version"
~pp:(fun ppf () ->
Format.fprintf ppf "Outdated fitness: referring to a previous version.")
Data_encoding.empty
(function Outdated_fitness -> Some () | _ -> None)
(fun () -> Outdated_fitness) ;
register_error_kind
`Permanent
~id:"locked_round_not_less_than_round"
~title:"Locked round not smaller than round"
~description:"The round is smaller than or equal to the locked round."
~pp:(fun ppf (round, locked_round) ->
Format.fprintf
ppf
"Incorrect fitness: round %a is less than or equal to locked round %a."
Round_repr.pp
round
Round_repr.pp
locked_round)
Data_encoding.(
obj2
(req "round" Round_repr.encoding)
(req "locked_round" Round_repr.encoding))
(function
| Locked_round_not_less_than_round {round; locked_round} ->
Some (round, locked_round)
| _ -> None)
(fun (round, locked_round) ->
Locked_round_not_less_than_round {round; locked_round})
let create_without_locked_round ~level ~predecessor_round ~round =
{level; locked_round = None; predecessor_round; round}
let create ~level ~locked_round ~predecessor_round ~round =
match locked_round with
| None -> ok {level; locked_round; predecessor_round; round}
| Some locked_round_val ->
error_when
Round_repr.(round <= locked_round_val)
(Locked_round_not_less_than_round
{round; locked_round = locked_round_val})
>>? fun () -> ok {level; locked_round; predecessor_round; round}
let int32_to_bytes i =
let b = Bytes.make 4 '\000' in
TzEndian.set_int32 b 0 i ;
b
let int32_of_bytes b =
if Compare.Int.(Bytes.length b <> 4) then error Invalid_fitness
else ok (TzEndian.get_int32 b 0)
(* Locked round is an option. And we want None to be smaller than any other
value. The way the shell handles the order makes the empty Bytes smaller
than any other *)
let locked_round_to_bytes = function
| None -> Bytes.empty
| Some locked_round -> int32_to_bytes (Round_repr.to_int32 locked_round)
let locked_round_of_bytes b =
match Bytes.length b with
| 0 -> ok None
| 4 -> Round_repr.of_int32 (TzEndian.get_int32 b 0) >>? fun r -> ok (Some r)
| _ -> error Invalid_fitness
let predecessor_round_of_bytes neg_predecessor_round =
int32_of_bytes neg_predecessor_round >>? fun neg_predecessor_round ->
Round_repr.of_int32 @@ Int32.pred (Int32.neg neg_predecessor_round)
let round_of_bytes round = int32_of_bytes round >>? Round_repr.of_int32
let to_raw {level; locked_round; predecessor_round; round} =
[
Bytes.of_string Constants_repr.fitness_version_number;
int32_to_bytes (Raw_level_repr.to_int32 level);
locked_round_to_bytes locked_round;
int32_to_bytes
(Int32.pred (Int32.neg (Round_repr.to_int32 predecessor_round)));
int32_to_bytes (Round_repr.to_int32 round);
]
let from_raw = function
| [version; level; locked_round; neg_predecessor_round; round]
when Compare.String.(
Bytes.to_string version = Constants_repr.fitness_version_number) ->
int32_of_bytes level >>? Raw_level_repr.of_int32 >>? fun level ->
locked_round_of_bytes locked_round >>? fun locked_round ->
predecessor_round_of_bytes neg_predecessor_round
>>? fun predecessor_round ->
round_of_bytes round >>? fun round ->
create ~level ~locked_round ~predecessor_round ~round
| [version; _]
when Compare.String.(
Bytes.to_string version < Constants_repr.fitness_version_number) ->
error Outdated_fitness
| [] (* genesis fitness *) -> error Outdated_fitness
| _ -> error Invalid_fitness
let round_from_raw = function
| [version; _level; _locked_round; _neg_predecessor_round; round]
when Compare.String.(
Bytes.to_string version = Constants_repr.fitness_version_number) ->
round_of_bytes round
| [version; _]
when Compare.String.(
Bytes.to_string version < Constants_repr.fitness_version_number) ->
ok Round_repr.zero
| [] (* genesis fitness *) -> ok Round_repr.zero
| _ -> error Invalid_fitness
let predecessor_round_from_raw = function
| [version; _level; _locked_round; neg_predecessor_round; _round]
when Compare.String.(
Bytes.to_string version = Constants_repr.fitness_version_number) ->
predecessor_round_of_bytes neg_predecessor_round
| [version; _]
when Compare.String.(
Bytes.to_string version < Constants_repr.fitness_version_number) ->
ok Round_repr.zero
| [] (* genesis fitness *) -> ok Round_repr.zero
| _ -> error Invalid_fitness
let check_except_locked_round fitness ~level ~predecessor_round =
let {
level = expected_level;
locked_round = _;
predecessor_round = expected_predecessor_round;
round = _;
} =
fitness
in
let correct =
Raw_level_repr.(level = expected_level)
&& Round_repr.(predecessor_round = expected_predecessor_round)
in
error_unless correct Wrong_fitness
let check_locked_round fitness ~locked_round =
let {
level = _;
locked_round = expected_locked_round;
predecessor_round = _;
round = _;
} =
fitness
in
let correct =
match (locked_round, expected_locked_round) with
| (None, None) -> true
| (Some _, None) | (None, Some _) -> false
| (Some v, Some v') -> Round_repr.(v = v')
in
error_unless correct Wrong_fitness
let level fitness = fitness.level
let round fitness = fitness.round
let locked_round fitness = fitness.locked_round
let predecessor_round fitness = fitness.predecessor_round
module Internal_for_tests = struct
module ListInt32Compare = Compare.List (Compare.Int32)
let compare f ff =
let unopt l =
match l with Some l -> Round_repr.to_int32 l | None -> -1l
in
let to_list {level; locked_round; predecessor_round; round} =
Int32.
[
Raw_level_repr.to_int32 level;
unopt locked_round;
neg (Round_repr.to_int32 predecessor_round);
Round_repr.to_int32 round;
]
in
ListInt32Compare.compare (to_list f) (to_list ff)
end
| null | https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_012_Psithaca/lib_protocol/fitness_repr.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
`Permanent
`Permanent
`Permanent
`Permanent
Locked round is an option. And we want None to be smaller than any other
value. The way the shell handles the order makes the empty Bytes smaller
than any other
genesis fitness
genesis fitness
genesis fitness | Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
type t = {
level : Raw_level_repr.t;
locked_round : Round_repr.t option;
predecessor_round : Round_repr.t;
by convention , predecessor_round is 0 in case of protocol migration
round : Round_repr.t;
}
let encoding =
let open Data_encoding in
def
"fitness"
(conv_with_guard
(fun {level; locked_round; predecessor_round; round} ->
(level, locked_round, predecessor_round, round))
(fun (level, locked_round, predecessor_round, round) ->
match locked_round with
| None -> ok {level; locked_round; predecessor_round; round}
| Some locked_round_val ->
if Round_repr.(round <= locked_round_val) then
Error "Locked round must be smaller than round."
else ok {level; locked_round; predecessor_round; round})
(obj4
(req "level" Raw_level_repr.encoding)
(req "locked_round" (option Round_repr.encoding))
(req "predecessor_round" Round_repr.encoding)
(req "round" Round_repr.encoding)))
let pp ppf f =
let minus_sign =
if Round_repr.(f.predecessor_round = Round_repr.zero) then "" else "-"
in
let locked_round ppf locked_round =
match locked_round with
| None -> Format.pp_print_string ppf "unlocked"
| Some round -> Format.fprintf ppf "locked: %a" Round_repr.pp round
in
Format.fprintf
ppf
"(%a, %a, %s%a, %a)"
Raw_level_repr.pp
f.level
locked_round
f.locked_round
minus_sign
Round_repr.pp
f.predecessor_round
Round_repr.pp
f.round
type error +=
Locked_round_not_less_than_round of {
round : Round_repr.t;
locked_round : Round_repr.t;
}
let () =
register_error_kind
`Permanent
~id:"invalid_fitness"
~title:"Invalid fitness"
~description:
"Fitness representation should be exactly 4 times 4 bytes long."
~pp:(fun ppf () -> Format.fprintf ppf "Invalid fitness")
Data_encoding.empty
(function Invalid_fitness -> Some () | _ -> None)
(fun () -> Invalid_fitness) ;
register_error_kind
`Permanent
~id:"wrong_fitness"
~title:"Wrong fitness"
~description:"Wrong fitness."
~pp:(fun ppf () -> Format.fprintf ppf "Wrong fitness.")
Data_encoding.empty
(function Wrong_fitness -> Some () | _ -> None)
(fun () -> Wrong_fitness) ;
register_error_kind
`Permanent
~id:"outdated_fitness"
~title:"Outdated fitness"
~description:"Outdated fitness: referring to a previous version"
~pp:(fun ppf () ->
Format.fprintf ppf "Outdated fitness: referring to a previous version.")
Data_encoding.empty
(function Outdated_fitness -> Some () | _ -> None)
(fun () -> Outdated_fitness) ;
register_error_kind
`Permanent
~id:"locked_round_not_less_than_round"
~title:"Locked round not smaller than round"
~description:"The round is smaller than or equal to the locked round."
~pp:(fun ppf (round, locked_round) ->
Format.fprintf
ppf
"Incorrect fitness: round %a is less than or equal to locked round %a."
Round_repr.pp
round
Round_repr.pp
locked_round)
Data_encoding.(
obj2
(req "round" Round_repr.encoding)
(req "locked_round" Round_repr.encoding))
(function
| Locked_round_not_less_than_round {round; locked_round} ->
Some (round, locked_round)
| _ -> None)
(fun (round, locked_round) ->
Locked_round_not_less_than_round {round; locked_round})
let create_without_locked_round ~level ~predecessor_round ~round =
{level; locked_round = None; predecessor_round; round}
let create ~level ~locked_round ~predecessor_round ~round =
match locked_round with
| None -> ok {level; locked_round; predecessor_round; round}
| Some locked_round_val ->
error_when
Round_repr.(round <= locked_round_val)
(Locked_round_not_less_than_round
{round; locked_round = locked_round_val})
>>? fun () -> ok {level; locked_round; predecessor_round; round}
let int32_to_bytes i =
let b = Bytes.make 4 '\000' in
TzEndian.set_int32 b 0 i ;
b
let int32_of_bytes b =
if Compare.Int.(Bytes.length b <> 4) then error Invalid_fitness
else ok (TzEndian.get_int32 b 0)
let locked_round_to_bytes = function
| None -> Bytes.empty
| Some locked_round -> int32_to_bytes (Round_repr.to_int32 locked_round)
let locked_round_of_bytes b =
match Bytes.length b with
| 0 -> ok None
| 4 -> Round_repr.of_int32 (TzEndian.get_int32 b 0) >>? fun r -> ok (Some r)
| _ -> error Invalid_fitness
let predecessor_round_of_bytes neg_predecessor_round =
int32_of_bytes neg_predecessor_round >>? fun neg_predecessor_round ->
Round_repr.of_int32 @@ Int32.pred (Int32.neg neg_predecessor_round)
let round_of_bytes round = int32_of_bytes round >>? Round_repr.of_int32
let to_raw {level; locked_round; predecessor_round; round} =
[
Bytes.of_string Constants_repr.fitness_version_number;
int32_to_bytes (Raw_level_repr.to_int32 level);
locked_round_to_bytes locked_round;
int32_to_bytes
(Int32.pred (Int32.neg (Round_repr.to_int32 predecessor_round)));
int32_to_bytes (Round_repr.to_int32 round);
]
let from_raw = function
| [version; level; locked_round; neg_predecessor_round; round]
when Compare.String.(
Bytes.to_string version = Constants_repr.fitness_version_number) ->
int32_of_bytes level >>? Raw_level_repr.of_int32 >>? fun level ->
locked_round_of_bytes locked_round >>? fun locked_round ->
predecessor_round_of_bytes neg_predecessor_round
>>? fun predecessor_round ->
round_of_bytes round >>? fun round ->
create ~level ~locked_round ~predecessor_round ~round
| [version; _]
when Compare.String.(
Bytes.to_string version < Constants_repr.fitness_version_number) ->
error Outdated_fitness
| _ -> error Invalid_fitness
let round_from_raw = function
| [version; _level; _locked_round; _neg_predecessor_round; round]
when Compare.String.(
Bytes.to_string version = Constants_repr.fitness_version_number) ->
round_of_bytes round
| [version; _]
when Compare.String.(
Bytes.to_string version < Constants_repr.fitness_version_number) ->
ok Round_repr.zero
| _ -> error Invalid_fitness
let predecessor_round_from_raw = function
| [version; _level; _locked_round; neg_predecessor_round; _round]
when Compare.String.(
Bytes.to_string version = Constants_repr.fitness_version_number) ->
predecessor_round_of_bytes neg_predecessor_round
| [version; _]
when Compare.String.(
Bytes.to_string version < Constants_repr.fitness_version_number) ->
ok Round_repr.zero
| _ -> error Invalid_fitness
let check_except_locked_round fitness ~level ~predecessor_round =
let {
level = expected_level;
locked_round = _;
predecessor_round = expected_predecessor_round;
round = _;
} =
fitness
in
let correct =
Raw_level_repr.(level = expected_level)
&& Round_repr.(predecessor_round = expected_predecessor_round)
in
error_unless correct Wrong_fitness
let check_locked_round fitness ~locked_round =
let {
level = _;
locked_round = expected_locked_round;
predecessor_round = _;
round = _;
} =
fitness
in
let correct =
match (locked_round, expected_locked_round) with
| (None, None) -> true
| (Some _, None) | (None, Some _) -> false
| (Some v, Some v') -> Round_repr.(v = v')
in
error_unless correct Wrong_fitness
let level fitness = fitness.level
let round fitness = fitness.round
let locked_round fitness = fitness.locked_round
let predecessor_round fitness = fitness.predecessor_round
module Internal_for_tests = struct
module ListInt32Compare = Compare.List (Compare.Int32)
let compare f ff =
let unopt l =
match l with Some l -> Round_repr.to_int32 l | None -> -1l
in
let to_list {level; locked_round; predecessor_round; round} =
Int32.
[
Raw_level_repr.to_int32 level;
unopt locked_round;
neg (Round_repr.to_int32 predecessor_round);
Round_repr.to_int32 round;
]
in
ListInt32Compare.compare (to_list f) (to_list ff)
end
|
a3a5df7397ed412e58a9b1f93f38655bc4ec23a5c3ee3c265f96d32b83d44448 | haskell-hvr/missingh | ControlParser.hs | {-# LANGUAGE Safe #-}
arch - tag : for Debian control file
Copyright ( c ) 2004 - 2011 < >
All rights reserved .
For license and copyright information , see the file LICENSE
Copyright (c) 2004-2011 John Goerzen <>
All rights reserved.
For license and copyright information, see the file LICENSE
-}
|
Module : System . Debian . ControlParser
Copyright : Copyright ( C ) 2004 - 2011 SPDX - License - Identifier : BSD-3 - Clause
Stability : stable
Portability : portable
This module provides various helpful utilities for dealing with Debian
files and programs .
Written by , jgoerzen\@complete.org
Module : System.Debian.ControlParser
Copyright : Copyright (C) 2004-2011 John Goerzen
SPDX-License-Identifier: BSD-3-Clause
Stability : stable
Portability: portable
This module provides various helpful utilities for dealing with Debian
files and programs.
Written by John Goerzen, jgoerzen\@complete.org
-}
module System.Debian.ControlParser(control, depPart)
where
import safe Data.List.Utils ( split )
import safe Text.ParserCombinators.Parsec
( char,
noneOf,
oneOf,
string,
many1,
manyTill,
(<?>),
(<|>),
many,
try,
GenParser,
CharParser )
eol, extline :: GenParser Char st String
eol = (try (string "\r\n"))
<|> string "\n" <?> "EOL"
extline = try (do _ <- char ' '
content <- many (noneOf "\r\n")
_ <- eol
return content )
entry :: GenParser Char st (String, String)
entry = do key <- many1 (noneOf ":\r\n")
_ <- char ':'
val <- many (noneOf "\r\n")
_ <- eol
exts <- many extline
return (key, unlines ([val] ++ exts))
{- | Main parser for the control file -}
control :: CharParser a [(String, String)]
control = do _ <- many header
retval <- many entry
return retval
headerPGP, blankLine, header, headerHash :: GenParser Char st ()
headerPGP = do _ <- string "-----BEGIN PGP"
_ <- manyTill (noneOf "\r\n") eol
return ()
blankLine = do _ <- many (oneOf " \t")
_ <- eol
return ()
headerHash = do _ <- string "Hash: "
_ <- manyTill (noneOf "\r\n") eol
return ()
header = (try headerPGP) <|> (try blankLine) <|> (try headerHash)
{- | Dependency parser.
Returns (package name, Maybe version, arch list)
version is (operator, operand) -}
depPart :: CharParser a (String, (Maybe (String, String)), [String])
depPart = do packagename <- many1 (noneOf " (")
_ <- many (char ' ')
version <- (do _ <- char '('
op <- many1 (oneOf "<>=")
_ <- many (char ' ')
vers <- many1 (noneOf ") ")
_ <- many (char ' ')
_ <- char ')'
return $ Just (op, vers)
) <|> return Nothing
_ <- many (char ' ')
archs <- (do _ <- char '['
t <- many1 (noneOf "]")
_ <- many (char ' ')
_ <- char ']'
return (split " " t)
) <|> return []
return (packagename, version, archs)
| null | https://raw.githubusercontent.com/haskell-hvr/missingh/e1a73bd9547db967b4e8d76a443000d06ce95ac4/src/System/Debian/ControlParser.hs | haskell | # LANGUAGE Safe #
| Main parser for the control file
| Dependency parser.
Returns (package name, Maybe version, arch list)
version is (operator, operand) |
arch - tag : for Debian control file
Copyright ( c ) 2004 - 2011 < >
All rights reserved .
For license and copyright information , see the file LICENSE
Copyright (c) 2004-2011 John Goerzen <>
All rights reserved.
For license and copyright information, see the file LICENSE
-}
|
Module : System . Debian . ControlParser
Copyright : Copyright ( C ) 2004 - 2011 SPDX - License - Identifier : BSD-3 - Clause
Stability : stable
Portability : portable
This module provides various helpful utilities for dealing with Debian
files and programs .
Written by , jgoerzen\@complete.org
Module : System.Debian.ControlParser
Copyright : Copyright (C) 2004-2011 John Goerzen
SPDX-License-Identifier: BSD-3-Clause
Stability : stable
Portability: portable
This module provides various helpful utilities for dealing with Debian
files and programs.
Written by John Goerzen, jgoerzen\@complete.org
-}
module System.Debian.ControlParser(control, depPart)
where
import safe Data.List.Utils ( split )
import safe Text.ParserCombinators.Parsec
( char,
noneOf,
oneOf,
string,
many1,
manyTill,
(<?>),
(<|>),
many,
try,
GenParser,
CharParser )
eol, extline :: GenParser Char st String
eol = (try (string "\r\n"))
<|> string "\n" <?> "EOL"
extline = try (do _ <- char ' '
content <- many (noneOf "\r\n")
_ <- eol
return content )
entry :: GenParser Char st (String, String)
entry = do key <- many1 (noneOf ":\r\n")
_ <- char ':'
val <- many (noneOf "\r\n")
_ <- eol
exts <- many extline
return (key, unlines ([val] ++ exts))
control :: CharParser a [(String, String)]
control = do _ <- many header
retval <- many entry
return retval
headerPGP, blankLine, header, headerHash :: GenParser Char st ()
headerPGP = do _ <- string "-----BEGIN PGP"
_ <- manyTill (noneOf "\r\n") eol
return ()
blankLine = do _ <- many (oneOf " \t")
_ <- eol
return ()
headerHash = do _ <- string "Hash: "
_ <- manyTill (noneOf "\r\n") eol
return ()
header = (try headerPGP) <|> (try blankLine) <|> (try headerHash)
depPart :: CharParser a (String, (Maybe (String, String)), [String])
depPart = do packagename <- many1 (noneOf " (")
_ <- many (char ' ')
version <- (do _ <- char '('
op <- many1 (oneOf "<>=")
_ <- many (char ' ')
vers <- many1 (noneOf ") ")
_ <- many (char ' ')
_ <- char ')'
return $ Just (op, vers)
) <|> return Nothing
_ <- many (char ' ')
archs <- (do _ <- char '['
t <- many1 (noneOf "]")
_ <- many (char ' ')
_ <- char ']'
return (split " " t)
) <|> return []
return (packagename, version, archs)
|
1cc4127cba8fd329a5438cf413acf47cb13c0862068d93c2f068a13c6d23a5b6 | facebookarchive/pfff | printexc.mli | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
$ I d : printexc.mli 11156 2011 - 07 - 27 14:17:02Z doligez $
(** Facilities for printing exceptions. *)
val to_string: exn -> string
(** [Printexc.to_string e] returns a string representation of
the exception [e]. *)
val print: ('a -> 'b) -> 'a -> 'b
(** [Printexc.print fn x] applies [fn] to [x] and returns the result.
If the evaluation of [fn x] raises any exception, the
name of the exception is printed on standard error output,
and the exception is raised again.
The typical use is to catch and report exceptions that
escape a function application. *)
val catch: ('a -> 'b) -> 'a -> 'b
* [ Printexc.catch fn x ] is similar to { ! Printexc.print } , but
aborts the program with exit code 2 after printing the
uncaught exception . This function is deprecated : the runtime
system is now able to print uncaught exceptions as precisely
as [ Printexc.catch ] does . Moreover , calling [ Printexc.catch ]
makes it harder to track the location of the exception
using the debugger or the stack backtrace facility .
So , do not use [ Printexc.catch ] in new code .
aborts the program with exit code 2 after printing the
uncaught exception. This function is deprecated: the runtime
system is now able to print uncaught exceptions as precisely
as [Printexc.catch] does. Moreover, calling [Printexc.catch]
makes it harder to track the location of the exception
using the debugger or the stack backtrace facility.
So, do not use [Printexc.catch] in new code. *)
val print_backtrace: out_channel -> unit
* [ Printexc.print_backtrace oc ] prints an exception backtrace
on the output channel [ oc ] . The backtrace lists the program
locations where the most - recently raised exception was raised
and where it was propagated through function calls .
@since 3.11.0
on the output channel [oc]. The backtrace lists the program
locations where the most-recently raised exception was raised
and where it was propagated through function calls.
@since 3.11.0
*)
val get_backtrace: unit -> string
* [ Printexc.get_backtrace ( ) ] returns a string containing the
same exception backtrace that [ ] would
print .
@since 3.11.0
same exception backtrace that [Printexc.print_backtrace] would
print.
@since 3.11.0
*)
val record_backtrace: bool -> unit
* [ Printexc.record_backtrace b ] turns recording of exception backtraces
on ( if [ b = true ] ) or off ( if [ b = false ] ) . Initially , backtraces
are not recorded , unless the [ b ] flag is given to the program
through the [ OCAMLRUNPARAM ] variable .
@since 3.11.0
on (if [b = true]) or off (if [b = false]). Initially, backtraces
are not recorded, unless the [b] flag is given to the program
through the [OCAMLRUNPARAM] variable.
@since 3.11.0
*)
val backtrace_status: unit -> bool
* [ Printexc.backtrace_status ( ) ] returns [ true ] if exception
backtraces are currently recorded , [ false ] if not .
@since 3.11.0
backtraces are currently recorded, [false] if not.
@since 3.11.0
*)
val register_printer: (exn -> string option) -> unit
* [ Printexc.register_printer fn ] registers [ fn ] as an exception
printer . The printer should return [ None ] or raise an exception
if it does not know how to convert the passed exception , and [ Some
s ] with [ s ] the resulting string if it can convert the passed
exception . Exceptions raised by the printer are ignored .
When converting an exception into a string , the printers will be invoked
in the reverse order of their registrations , until a printer returns
a [ Some s ] value ( if no such printer exists , the runtime will use a
generic printer ) .
When using this mechanism , one should be aware that an exception backtrace
is attached to the thread that saw it raised , rather than to the exception
itself . Practically , it means that the code related to [ fn ] should not use
the backtrace if it has itself raised an exception before .
@since 3.11.2
printer. The printer should return [None] or raise an exception
if it does not know how to convert the passed exception, and [Some
s] with [s] the resulting string if it can convert the passed
exception. Exceptions raised by the printer are ignored.
When converting an exception into a string, the printers will be invoked
in the reverse order of their registrations, until a printer returns
a [Some s] value (if no such printer exists, the runtime will use a
generic printer).
When using this mechanism, one should be aware that an exception backtrace
is attached to the thread that saw it raised, rather than to the exception
itself. Practically, it means that the code related to [fn] should not use
the backtrace if it has itself raised an exception before.
@since 3.11.2
*)
| null | https://raw.githubusercontent.com/facebookarchive/pfff/ec21095ab7d445559576513a63314e794378c367/external/stdlib/printexc.mli | ocaml | *********************************************************************
OCaml
the special exception on linking described in file ../LICENSE.
*********************************************************************
* Facilities for printing exceptions.
* [Printexc.to_string e] returns a string representation of
the exception [e].
* [Printexc.print fn x] applies [fn] to [x] and returns the result.
If the evaluation of [fn x] raises any exception, the
name of the exception is printed on standard error output,
and the exception is raised again.
The typical use is to catch and report exceptions that
escape a function application. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ I d : printexc.mli 11156 2011 - 07 - 27 14:17:02Z doligez $
val to_string: exn -> string
val print: ('a -> 'b) -> 'a -> 'b
val catch: ('a -> 'b) -> 'a -> 'b
* [ Printexc.catch fn x ] is similar to { ! Printexc.print } , but
aborts the program with exit code 2 after printing the
uncaught exception . This function is deprecated : the runtime
system is now able to print uncaught exceptions as precisely
as [ Printexc.catch ] does . Moreover , calling [ Printexc.catch ]
makes it harder to track the location of the exception
using the debugger or the stack backtrace facility .
So , do not use [ Printexc.catch ] in new code .
aborts the program with exit code 2 after printing the
uncaught exception. This function is deprecated: the runtime
system is now able to print uncaught exceptions as precisely
as [Printexc.catch] does. Moreover, calling [Printexc.catch]
makes it harder to track the location of the exception
using the debugger or the stack backtrace facility.
So, do not use [Printexc.catch] in new code. *)
val print_backtrace: out_channel -> unit
* [ Printexc.print_backtrace oc ] prints an exception backtrace
on the output channel [ oc ] . The backtrace lists the program
locations where the most - recently raised exception was raised
and where it was propagated through function calls .
@since 3.11.0
on the output channel [oc]. The backtrace lists the program
locations where the most-recently raised exception was raised
and where it was propagated through function calls.
@since 3.11.0
*)
val get_backtrace: unit -> string
* [ Printexc.get_backtrace ( ) ] returns a string containing the
same exception backtrace that [ ] would
print .
@since 3.11.0
same exception backtrace that [Printexc.print_backtrace] would
print.
@since 3.11.0
*)
val record_backtrace: bool -> unit
* [ Printexc.record_backtrace b ] turns recording of exception backtraces
on ( if [ b = true ] ) or off ( if [ b = false ] ) . Initially , backtraces
are not recorded , unless the [ b ] flag is given to the program
through the [ OCAMLRUNPARAM ] variable .
@since 3.11.0
on (if [b = true]) or off (if [b = false]). Initially, backtraces
are not recorded, unless the [b] flag is given to the program
through the [OCAMLRUNPARAM] variable.
@since 3.11.0
*)
val backtrace_status: unit -> bool
* [ Printexc.backtrace_status ( ) ] returns [ true ] if exception
backtraces are currently recorded , [ false ] if not .
@since 3.11.0
backtraces are currently recorded, [false] if not.
@since 3.11.0
*)
val register_printer: (exn -> string option) -> unit
* [ Printexc.register_printer fn ] registers [ fn ] as an exception
printer . The printer should return [ None ] or raise an exception
if it does not know how to convert the passed exception , and [ Some
s ] with [ s ] the resulting string if it can convert the passed
exception . Exceptions raised by the printer are ignored .
When converting an exception into a string , the printers will be invoked
in the reverse order of their registrations , until a printer returns
a [ Some s ] value ( if no such printer exists , the runtime will use a
generic printer ) .
When using this mechanism , one should be aware that an exception backtrace
is attached to the thread that saw it raised , rather than to the exception
itself . Practically , it means that the code related to [ fn ] should not use
the backtrace if it has itself raised an exception before .
@since 3.11.2
printer. The printer should return [None] or raise an exception
if it does not know how to convert the passed exception, and [Some
s] with [s] the resulting string if it can convert the passed
exception. Exceptions raised by the printer are ignored.
When converting an exception into a string, the printers will be invoked
in the reverse order of their registrations, until a printer returns
a [Some s] value (if no such printer exists, the runtime will use a
generic printer).
When using this mechanism, one should be aware that an exception backtrace
is attached to the thread that saw it raised, rather than to the exception
itself. Practically, it means that the code related to [fn] should not use
the backtrace if it has itself raised an exception before.
@since 3.11.2
*)
|
77378aeecb0f183a562ec66c3fd20f5c78c84833c271ac6d047f5d5cc77bb4c0 | anwarmamat/cmsc330spring19-public | public.ml | open OUnit2
open P5.SmallCTypes
open TestUtils
open P5.TokenTypes
let test_assign1 = create_system_test "../../../test/public_inputs/assign1.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), NoOp)))
let test_assign_exp = create_system_test "../../../test/public_inputs/assign-exp.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Mult(Int 100, ID "a")), Seq(Print(ID "a"), NoOp))))
let test_define_1 = create_system_test "../../../test/public_inputs/define1.c"
(Seq(Declare(Int_Type, "a"), NoOp))
let test_equal = create_system_test "../../../test/public_inputs/equal.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(If(Equal(ID "a", Int 100), Seq(Assign("a", Int 200), Seq(Print(ID "a"), NoOp)), NoOp), NoOp))))
let test_exp_1 = create_system_test "../../../test/public_inputs/exp1.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Add(Int 2, Mult(Int 5, Pow(Int 4, Int 3)))), Seq(Print(ID "a"), NoOp))))
let test_exp_2 = create_system_test "../../../test/public_inputs/exp2.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Add(Int 2, Pow(Mult(Int 5, Int 4), Int 3))), Seq(Print(ID "a"), NoOp))))
let test_greater = create_system_test "../../../test/public_inputs/greater.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(If(Greater(ID "a", Int 10), Seq(Assign("a", Int 200), Seq(Print(ID "a"), NoOp)), NoOp), NoOp))))
let test_if = create_system_test "../../../test/public_inputs/if.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(If(Greater(ID "a", Int 10), Seq(Assign("a", Int 200), NoOp), NoOp), NoOp))))
let test_ifelse = create_system_test "../../../test/public_inputs/ifelse.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(If(Greater(ID "a", Int 10), Seq(Assign("a", Int 200), NoOp), Seq(Assign("a", Int 300), NoOp)), NoOp))))
let test_if_else_while = create_system_test "../../../test/public_inputs/if-else-while.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(Declare(Int_Type, "b"), Seq(If(Greater(ID "a", Int 10), Seq(Assign("a", Int 200), NoOp), Seq(Assign("b", Int 10), Seq(While(Less(Mult(ID "b", Int 2), ID "a"), Seq(Assign("b", Add(ID "b", Int 2)), Seq(Print(ID "b"), NoOp))), Seq(Assign("a", Int 300), NoOp)))), NoOp)))))
let test_less = create_system_test "../../../test/public_inputs/less.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(If(Less(ID "a", Int 200), Seq(Assign("a", Int 200), Seq(Print(ID "a"), NoOp)), NoOp), NoOp))))
let test_main = create_system_test "../../../test/public_inputs/main.c"
NoOp
let test_nested_if = create_system_test "../../../test/public_inputs/nested-if.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(If(Greater(ID "a", Int 10), Seq(Assign("a", Int 200), Seq(If(Less(ID "a", Int 20), Seq(Assign("a", Int 300), NoOp), Seq(Assign("a", Int 400), NoOp)), NoOp)), NoOp), NoOp))))
let test_nested_ifelse = create_system_test "../../../test/public_inputs/nested-ifelse.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(If(Greater(ID "a", Int 10), Seq(Assign("a", Int 200), Seq(If(Less(ID "a", Int 20), Seq(Assign("a", Int 300), NoOp), Seq(Assign("a", Int 400), NoOp)), NoOp)), Seq(Assign("a", Int 500), NoOp)), NoOp))))
let test_nested_while = create_system_test "../../../test/public_inputs/nested-while.c"
(Seq(Declare(Int_Type, "i"), Seq(Declare(Int_Type, "j"), Seq(Assign("i", Int 1), Seq(Declare(Int_Type, "sum"), Seq(Assign("sum", Int 0), Seq(While(Less(ID "i", Int 10), Seq(Assign("j", Int 1), Seq(While(Less(ID "j", Int 10), Seq(Assign("sum", Add(ID "sum", ID "j")), Seq(Assign("j", Add(ID "j", Int 1)), NoOp))), Seq(Assign("i", Add(ID "i", Int 1)), NoOp)))), NoOp)))))))
let test_print = create_system_test "../../../test/public_inputs/print.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(Print(ID "a"), NoOp))))
let test_test1 = create_system_test "../../../test/public_inputs/test1.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 10), Seq(Declare(Int_Type, "b"), Seq(Assign("b", Int 1), Seq(Declare(Int_Type, "sum"), Seq(Assign("sum", Int 0), Seq(While(Less(ID "b", ID "a"), Seq(Assign("sum", Add(ID "sum", ID "b")), Seq(Assign("b", Add(ID "b", Int 1)), Seq(Print(ID "sum"), Seq(If(Greater(ID "a", ID "b"), Seq(Print(Int 10), NoOp), Seq(Print(Int 20), NoOp)), Seq(Print(ID "sum"), NoOp)))))), NoOp))))))))
let test_test2 = create_system_test "../../../test/public_inputs/test2.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 10), Seq(Declare(Int_Type, "b"), Seq(Assign("b", Int 20), Seq(Declare(Int_Type, "c"), Seq(If(Less(ID "a", ID "b"), Seq(If(Less(Pow(ID "a", Int 2), Pow(ID "b", Int 3)), Seq(Print(ID "a"), NoOp), Seq(Print(ID "b"), NoOp)), NoOp), Seq(Assign("c", Int 1), Seq(While(Less(ID "c", ID "a"), Seq(Print(ID "c"), Seq(Assign("c", Add(ID "c", Int 1)), NoOp))), NoOp))), NoOp)))))))
let test_test3 = create_system_test "../../../test/public_inputs/test3.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 10), Seq(Declare(Int_Type, "b"), Seq(Assign("b", Int 2), Seq(Declare(Int_Type, "c"), Seq(Assign("c", Add(ID "a", Mult(ID "b", Pow(Int 3, Int 3)))), Seq(Print(Equal(ID "c", Int 1)), NoOp))))))))
let test_test4 = create_system_test "../../../test/public_inputs/test4.c"
(Seq(Declare(Int_Type, "x"), Seq(Declare(Int_Type, "y"), Seq(Declare(Int_Type, "a"), Seq(While(Equal(ID "x", ID "y"), Seq(Assign("a", Int 100), NoOp)), Seq(If(Equal(ID "a", ID "b"), Seq(Print(Int 20), NoOp), Seq(Print(Int 10), NoOp)), NoOp))))))
let test_test_assoc1 = create_system_test "../../../test/public_inputs/test-assoc1.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Add(Int 2, Add(Int 3, Int 4))), Seq(Declare(Int_Type, "b"), Seq(Assign("b", Mult(Int 2, Mult(Int 3, Int 4))), Seq(Declare(Int_Type, "c"), Seq(Assign("c", Pow(Int 2, Pow(Int 3, Int 4))), Seq(Declare(Int_Type, "d"), Seq(If(Greater(Int 5, Greater(Int 6, Int 1)), Seq(Print(Int 10), NoOp), NoOp), Seq(Print(ID "a"), Seq(Print(ID "b"), Seq(Print(ID "c"), NoOp))))))))))))
let test_while = create_system_test "../../../test/public_inputs/while.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 10), Seq(Declare(Int_Type, "b"), Seq(Assign("b", Int 1), Seq(While(Less(ID "b", ID "a"), Seq(Print(ID "b"), Seq(Assign("b", Add(ID "b", Int 2)), NoOp))), NoOp))))))
let test_do_while = create_system_test "../../../test/public_inputs/do-while.c"
(Seq(Declare(Int_Type, "i"), Seq (DoWhile(Seq(Assign("i", Sub(ID "i", Int 1)), NoOp), GreaterEqual(ID "i", Int 1)), NoOp)))
let suite =
"public" >::: [
"assign1" >:: test_assign1;
"assign_exp" >:: test_assign_exp;
"define1" >:: test_define_1;
"equal" >:: test_equal;
"exp1" >:: test_exp_1;
"exp2" >:: test_exp_2;
"greater" >:: test_greater;
"if" >:: test_if;
"ifelse" >:: test_ifelse;
"if_else_while" >:: test_if_else_while;
"less" >:: test_less;
"main" >:: test_main;
"nested_if" >:: test_nested_if;
"nested_ifelse" >:: test_nested_ifelse;
"nested_while" >:: test_nested_while;
"print" >:: test_print;
"test1" >:: test_test1;
"test2" >:: test_test2;
"test3" >:: test_test3;
"test4" >:: test_test4;
"test_assoc1" >:: test_test_assoc1;
"while" >:: test_while;
"do_while" >:: test_do_while
]
let _ = run_test_tt_main suite
| null | https://raw.githubusercontent.com/anwarmamat/cmsc330spring19-public/98af1e8efc3d8756972731eaca19e55fe8febb69/project5/test/public.ml | ocaml | open OUnit2
open P5.SmallCTypes
open TestUtils
open P5.TokenTypes
let test_assign1 = create_system_test "../../../test/public_inputs/assign1.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), NoOp)))
let test_assign_exp = create_system_test "../../../test/public_inputs/assign-exp.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Mult(Int 100, ID "a")), Seq(Print(ID "a"), NoOp))))
let test_define_1 = create_system_test "../../../test/public_inputs/define1.c"
(Seq(Declare(Int_Type, "a"), NoOp))
let test_equal = create_system_test "../../../test/public_inputs/equal.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(If(Equal(ID "a", Int 100), Seq(Assign("a", Int 200), Seq(Print(ID "a"), NoOp)), NoOp), NoOp))))
let test_exp_1 = create_system_test "../../../test/public_inputs/exp1.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Add(Int 2, Mult(Int 5, Pow(Int 4, Int 3)))), Seq(Print(ID "a"), NoOp))))
let test_exp_2 = create_system_test "../../../test/public_inputs/exp2.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Add(Int 2, Pow(Mult(Int 5, Int 4), Int 3))), Seq(Print(ID "a"), NoOp))))
let test_greater = create_system_test "../../../test/public_inputs/greater.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(If(Greater(ID "a", Int 10), Seq(Assign("a", Int 200), Seq(Print(ID "a"), NoOp)), NoOp), NoOp))))
let test_if = create_system_test "../../../test/public_inputs/if.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(If(Greater(ID "a", Int 10), Seq(Assign("a", Int 200), NoOp), NoOp), NoOp))))
let test_ifelse = create_system_test "../../../test/public_inputs/ifelse.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(If(Greater(ID "a", Int 10), Seq(Assign("a", Int 200), NoOp), Seq(Assign("a", Int 300), NoOp)), NoOp))))
let test_if_else_while = create_system_test "../../../test/public_inputs/if-else-while.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(Declare(Int_Type, "b"), Seq(If(Greater(ID "a", Int 10), Seq(Assign("a", Int 200), NoOp), Seq(Assign("b", Int 10), Seq(While(Less(Mult(ID "b", Int 2), ID "a"), Seq(Assign("b", Add(ID "b", Int 2)), Seq(Print(ID "b"), NoOp))), Seq(Assign("a", Int 300), NoOp)))), NoOp)))))
let test_less = create_system_test "../../../test/public_inputs/less.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(If(Less(ID "a", Int 200), Seq(Assign("a", Int 200), Seq(Print(ID "a"), NoOp)), NoOp), NoOp))))
let test_main = create_system_test "../../../test/public_inputs/main.c"
NoOp
let test_nested_if = create_system_test "../../../test/public_inputs/nested-if.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(If(Greater(ID "a", Int 10), Seq(Assign("a", Int 200), Seq(If(Less(ID "a", Int 20), Seq(Assign("a", Int 300), NoOp), Seq(Assign("a", Int 400), NoOp)), NoOp)), NoOp), NoOp))))
let test_nested_ifelse = create_system_test "../../../test/public_inputs/nested-ifelse.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(If(Greater(ID "a", Int 10), Seq(Assign("a", Int 200), Seq(If(Less(ID "a", Int 20), Seq(Assign("a", Int 300), NoOp), Seq(Assign("a", Int 400), NoOp)), NoOp)), Seq(Assign("a", Int 500), NoOp)), NoOp))))
let test_nested_while = create_system_test "../../../test/public_inputs/nested-while.c"
(Seq(Declare(Int_Type, "i"), Seq(Declare(Int_Type, "j"), Seq(Assign("i", Int 1), Seq(Declare(Int_Type, "sum"), Seq(Assign("sum", Int 0), Seq(While(Less(ID "i", Int 10), Seq(Assign("j", Int 1), Seq(While(Less(ID "j", Int 10), Seq(Assign("sum", Add(ID "sum", ID "j")), Seq(Assign("j", Add(ID "j", Int 1)), NoOp))), Seq(Assign("i", Add(ID "i", Int 1)), NoOp)))), NoOp)))))))
let test_print = create_system_test "../../../test/public_inputs/print.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 100), Seq(Print(ID "a"), NoOp))))
let test_test1 = create_system_test "../../../test/public_inputs/test1.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 10), Seq(Declare(Int_Type, "b"), Seq(Assign("b", Int 1), Seq(Declare(Int_Type, "sum"), Seq(Assign("sum", Int 0), Seq(While(Less(ID "b", ID "a"), Seq(Assign("sum", Add(ID "sum", ID "b")), Seq(Assign("b", Add(ID "b", Int 1)), Seq(Print(ID "sum"), Seq(If(Greater(ID "a", ID "b"), Seq(Print(Int 10), NoOp), Seq(Print(Int 20), NoOp)), Seq(Print(ID "sum"), NoOp)))))), NoOp))))))))
let test_test2 = create_system_test "../../../test/public_inputs/test2.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 10), Seq(Declare(Int_Type, "b"), Seq(Assign("b", Int 20), Seq(Declare(Int_Type, "c"), Seq(If(Less(ID "a", ID "b"), Seq(If(Less(Pow(ID "a", Int 2), Pow(ID "b", Int 3)), Seq(Print(ID "a"), NoOp), Seq(Print(ID "b"), NoOp)), NoOp), Seq(Assign("c", Int 1), Seq(While(Less(ID "c", ID "a"), Seq(Print(ID "c"), Seq(Assign("c", Add(ID "c", Int 1)), NoOp))), NoOp))), NoOp)))))))
let test_test3 = create_system_test "../../../test/public_inputs/test3.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 10), Seq(Declare(Int_Type, "b"), Seq(Assign("b", Int 2), Seq(Declare(Int_Type, "c"), Seq(Assign("c", Add(ID "a", Mult(ID "b", Pow(Int 3, Int 3)))), Seq(Print(Equal(ID "c", Int 1)), NoOp))))))))
let test_test4 = create_system_test "../../../test/public_inputs/test4.c"
(Seq(Declare(Int_Type, "x"), Seq(Declare(Int_Type, "y"), Seq(Declare(Int_Type, "a"), Seq(While(Equal(ID "x", ID "y"), Seq(Assign("a", Int 100), NoOp)), Seq(If(Equal(ID "a", ID "b"), Seq(Print(Int 20), NoOp), Seq(Print(Int 10), NoOp)), NoOp))))))
let test_test_assoc1 = create_system_test "../../../test/public_inputs/test-assoc1.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Add(Int 2, Add(Int 3, Int 4))), Seq(Declare(Int_Type, "b"), Seq(Assign("b", Mult(Int 2, Mult(Int 3, Int 4))), Seq(Declare(Int_Type, "c"), Seq(Assign("c", Pow(Int 2, Pow(Int 3, Int 4))), Seq(Declare(Int_Type, "d"), Seq(If(Greater(Int 5, Greater(Int 6, Int 1)), Seq(Print(Int 10), NoOp), NoOp), Seq(Print(ID "a"), Seq(Print(ID "b"), Seq(Print(ID "c"), NoOp))))))))))))
let test_while = create_system_test "../../../test/public_inputs/while.c"
(Seq(Declare(Int_Type, "a"), Seq(Assign("a", Int 10), Seq(Declare(Int_Type, "b"), Seq(Assign("b", Int 1), Seq(While(Less(ID "b", ID "a"), Seq(Print(ID "b"), Seq(Assign("b", Add(ID "b", Int 2)), NoOp))), NoOp))))))
let test_do_while = create_system_test "../../../test/public_inputs/do-while.c"
(Seq(Declare(Int_Type, "i"), Seq (DoWhile(Seq(Assign("i", Sub(ID "i", Int 1)), NoOp), GreaterEqual(ID "i", Int 1)), NoOp)))
let suite =
"public" >::: [
"assign1" >:: test_assign1;
"assign_exp" >:: test_assign_exp;
"define1" >:: test_define_1;
"equal" >:: test_equal;
"exp1" >:: test_exp_1;
"exp2" >:: test_exp_2;
"greater" >:: test_greater;
"if" >:: test_if;
"ifelse" >:: test_ifelse;
"if_else_while" >:: test_if_else_while;
"less" >:: test_less;
"main" >:: test_main;
"nested_if" >:: test_nested_if;
"nested_ifelse" >:: test_nested_ifelse;
"nested_while" >:: test_nested_while;
"print" >:: test_print;
"test1" >:: test_test1;
"test2" >:: test_test2;
"test3" >:: test_test3;
"test4" >:: test_test4;
"test_assoc1" >:: test_test_assoc1;
"while" >:: test_while;
"do_while" >:: test_do_while
]
let _ = run_test_tt_main suite
| |
9da94efb836513a94bed8b966209ad02afd3adae64f313eb57057f2174d75e0d | tsloughter/kuberl | kuberl_v1_custom_resource_definition_version.erl | -module(kuberl_v1_custom_resource_definition_version).
-export([encode/1]).
-export_type([kuberl_v1_custom_resource_definition_version/0]).
-type kuberl_v1_custom_resource_definition_version() ::
#{ 'additionalPrinterColumns' => list(),
'name' := binary(),
'schema' => kuberl_v1_custom_resource_validation:kuberl_v1_custom_resource_validation(),
'served' := boolean(),
'storage' := boolean(),
'subresources' => kuberl_v1_custom_resource_subresources:kuberl_v1_custom_resource_subresources()
}.
encode(#{ 'additionalPrinterColumns' := AdditionalPrinterColumns,
'name' := Name,
'schema' := Schema,
'served' := Served,
'storage' := Storage,
'subresources' := Subresources
}) ->
#{ 'additionalPrinterColumns' => AdditionalPrinterColumns,
'name' => Name,
'schema' => Schema,
'served' => Served,
'storage' => Storage,
'subresources' => Subresources
}.
| null | https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1_custom_resource_definition_version.erl | erlang | -module(kuberl_v1_custom_resource_definition_version).
-export([encode/1]).
-export_type([kuberl_v1_custom_resource_definition_version/0]).
-type kuberl_v1_custom_resource_definition_version() ::
#{ 'additionalPrinterColumns' => list(),
'name' := binary(),
'schema' => kuberl_v1_custom_resource_validation:kuberl_v1_custom_resource_validation(),
'served' := boolean(),
'storage' := boolean(),
'subresources' => kuberl_v1_custom_resource_subresources:kuberl_v1_custom_resource_subresources()
}.
encode(#{ 'additionalPrinterColumns' := AdditionalPrinterColumns,
'name' := Name,
'schema' := Schema,
'served' := Served,
'storage' := Storage,
'subresources' := Subresources
}) ->
#{ 'additionalPrinterColumns' => AdditionalPrinterColumns,
'name' => Name,
'schema' => Schema,
'served' => Served,
'storage' => Storage,
'subresources' => Subresources
}.
| |
ef4695846146a08980e0bc581fa4969c64b6d390be752b3f2776ad66852d7b3d | cabalism/hpack-dhall | Options.hs | # LANGUAGE RecordWildCards #
# LANGUAGE ApplicativeDo #
module Options
( Options(..)
, parseNumericVersion
, parseVersion
, parseOptions
, parsePkgFile
, parseForce
, parseQuiet
) where
import Hpack.Dhall (packageConfig)
import Options.Applicative
newtype Options = Options {pkgFile :: FilePath}
parseOptions :: Parser Options
parseOptions = helper <*> do
pkgFile <- parsePkgFile
return Options{..}
parsePkgFile :: Parser FilePath
parsePkgFile =
strOption $
long "package-dhall"
<> metavar "FILE"
<> value packageConfig
<> showDefault
<> help "A record of hpack fields"
parseNumericVersion :: Parser ()
parseNumericVersion =
flag' () $
long "numeric-version"
<> help "Show version only"
parseVersion :: Parser ()
parseVersion =
flag' () $
long "version"
<> help "Show app name and version"
parseForce :: Parser Bool
parseForce =
flag False True $
long "force"
<> short 'f'
<> help "Overwrite of the output .cabal file unnecessarily"
parseQuiet :: Parser Bool
parseQuiet =
flag False True $
long "silent"
<> help "Suppress logging"
| null | https://raw.githubusercontent.com/cabalism/hpack-dhall/4f5671164098dedcaa3dd92624e0106d49899507/exe/options/Options.hs | haskell | # LANGUAGE RecordWildCards #
# LANGUAGE ApplicativeDo #
module Options
( Options(..)
, parseNumericVersion
, parseVersion
, parseOptions
, parsePkgFile
, parseForce
, parseQuiet
) where
import Hpack.Dhall (packageConfig)
import Options.Applicative
newtype Options = Options {pkgFile :: FilePath}
parseOptions :: Parser Options
parseOptions = helper <*> do
pkgFile <- parsePkgFile
return Options{..}
parsePkgFile :: Parser FilePath
parsePkgFile =
strOption $
long "package-dhall"
<> metavar "FILE"
<> value packageConfig
<> showDefault
<> help "A record of hpack fields"
parseNumericVersion :: Parser ()
parseNumericVersion =
flag' () $
long "numeric-version"
<> help "Show version only"
parseVersion :: Parser ()
parseVersion =
flag' () $
long "version"
<> help "Show app name and version"
parseForce :: Parser Bool
parseForce =
flag False True $
long "force"
<> short 'f'
<> help "Overwrite of the output .cabal file unnecessarily"
parseQuiet :: Parser Bool
parseQuiet =
flag False True $
long "silent"
<> help "Suppress logging"
| |
70cf69d40ef8af491e4837b9447d37d90bf2ace0e6ca322bb4301737004b4cbb | mflatt/not-a-box | port.rkt | #lang racket/base
(require "port.rkt"
(only-in racket/base
[open-input-file c:open-input-file]
[port-count-lines! c:port-count-lines!]
[read-string c:read-string]
[close-input-port c:close-input-port]
[bytes->string/utf-8 c:bytes->string/utf-8]
[string->bytes/utf-8 c:string->bytes/utf-8]))
(time
(let loop ([j 10])
(unless (zero? j)
(let ()
(define p (open-input-file "port.rktl"))
(port-count-lines! p)
(let loop ()
(define s (read-string 100 p))
(unless (eof-object? s)
(loop)))
(close-input-port p)
(loop (sub1 j))))))
'|Same, but in C....|
(time
(let loop ([j 10])
(unless (zero? j)
(let ()
(define p (c:open-input-file "port.rktl"))
(c:port-count-lines! p)
(let loop ()
(define s (c:read-string 100 p))
(unless (eof-object? s)
(loop)))
(c:close-input-port p)
(loop (sub1 j))))))
(time
(let loop ([j 10])
(unless (zero? j)
(let ()
(define p (open-input-file "port.rktl"))
(port-count-lines! p)
(let loop ()
(unless (eof-object? (read-byte p))
(loop)))
(close-input-port p)
(loop (sub1 j))))))
(time
(let loop ([i 1000000] [v #f])
(if (zero? i)
v
(loop (sub1 i)
(bytes->string/utf-8 (string->bytes/utf-8 "ap\x3BB;ple"))))))
'|Same, but in C...|
(time
(let loop ([i 1000000] [v #f])
(if (zero? i)
v
(loop (sub1 i)
(c:bytes->string/utf-8 (c:string->bytes/utf-8 "ap\x3BB;ple"))))))
| null | https://raw.githubusercontent.com/mflatt/not-a-box/b6c1af4fb0eb877610a3a20b5265a8c8d2dd28e9/demo/port.rkt | racket | #lang racket/base
(require "port.rkt"
(only-in racket/base
[open-input-file c:open-input-file]
[port-count-lines! c:port-count-lines!]
[read-string c:read-string]
[close-input-port c:close-input-port]
[bytes->string/utf-8 c:bytes->string/utf-8]
[string->bytes/utf-8 c:string->bytes/utf-8]))
(time
(let loop ([j 10])
(unless (zero? j)
(let ()
(define p (open-input-file "port.rktl"))
(port-count-lines! p)
(let loop ()
(define s (read-string 100 p))
(unless (eof-object? s)
(loop)))
(close-input-port p)
(loop (sub1 j))))))
'|Same, but in C....|
(time
(let loop ([j 10])
(unless (zero? j)
(let ()
(define p (c:open-input-file "port.rktl"))
(c:port-count-lines! p)
(let loop ()
(define s (c:read-string 100 p))
(unless (eof-object? s)
(loop)))
(c:close-input-port p)
(loop (sub1 j))))))
(time
(let loop ([j 10])
(unless (zero? j)
(let ()
(define p (open-input-file "port.rktl"))
(port-count-lines! p)
(let loop ()
(unless (eof-object? (read-byte p))
(loop)))
(close-input-port p)
(loop (sub1 j))))))
(time
(let loop ([i 1000000] [v #f])
(if (zero? i)
v
(loop (sub1 i)
(bytes->string/utf-8 (string->bytes/utf-8 "ap\x3BB;ple"))))))
'|Same, but in C...|
(time
(let loop ([i 1000000] [v #f])
(if (zero? i)
v
(loop (sub1 i)
(c:bytes->string/utf-8 (c:string->bytes/utf-8 "ap\x3BB;ple"))))))
| |
1335a6dfe78d7a686a7d5c0e8d2d3c0d9943b53eee71976958d60bd951a46871 | yetanalytics/flint | where.cljc | (ns com.yetanalytics.flint.spec.where
(:require [clojure.spec.alpha :as s]
[com.yetanalytics.flint.spec.axiom :as ax]
[com.yetanalytics.flint.spec.expr :as es]
[com.yetanalytics.flint.spec.modifier :as ms]
[com.yetanalytics.flint.spec.select :as ss]
[com.yetanalytics.flint.spec.triple :as ts]
[com.yetanalytics.flint.spec.values :as vs])
#?(:clj (:require
[com.yetanalytics.flint.spec :refer [sparql-keys]])
:cljs (:require-macros
[com.yetanalytics.flint.spec :refer [sparql-keys]])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Sub-SELECT query
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def key-order-map
{:select 2
:select-distinct 2
:select-reduced 2
:where 5
:group-by 6
:order-by 7
:having 8
:limit 9
:offset 10
:values 11})
(defn- key-comp
[k1 k2]
(let [n1 (get key-order-map k1 100)
n2 (get key-order-map k2 100)]
(- n1 n2)))
(s/def ::select
(sparql-keys :req-un [(or ::ss/select
::ss/select-distinct
::ss/select-reduced)
::where]
:opt-un [::vs/values
;; s/merge does not result in correct conformation
::ms/group-by
::ms/order-by
::ms/having
::ms/limit
::ms/offset]
:key-comp-fn key-comp))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; WHERE clause
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmulti where-special-form-mm
"Accepts a special WHERE form/graph pattern in the form `[:keyword ...]`
and returns the appropriate regex spec. The spec applies an additional
conformer in order to allow for identification during formatting."
first)
(defmethod where-special-form-mm :where [_] ; recursion
(s/& (s/cat :k #{:where}
:v ::where)
(s/conformer (fn [{:keys [v]}] [:where/recurse v]))))
(defmethod where-special-form-mm :union [_]
(s/& (s/cat :k #{:union}
:v (s/+ ::where))
(s/conformer (fn [{:keys [v]}] [:where/union v]))))
(defmethod where-special-form-mm :optional [_]
(s/& (s/cat :k #{:optional}
:v ::where)
(s/conformer (fn [{:keys [v]}] [:where/optional v]))))
(defmethod where-special-form-mm :minus [_]
(s/& (s/cat :k #{:minus}
:v ::where)
(s/conformer (fn [{:keys [v]}] [:where/minus v]))))
(defmethod where-special-form-mm :graph [_]
(s/& (s/cat :k #{:graph}
:v1 ax/iri-or-var-spec
:v2 ::where)
(s/conformer (fn [{:keys [v1 v2]}] [:where/graph [v1 v2]]))))
(defmethod where-special-form-mm :service [_]
(s/& (s/cat :k #{:service}
:v1 ax/iri-or-var-spec
:v2 ::where)
(s/conformer (fn [{:keys [v1 v2]}] [:where/service [v1 v2]]))))
(defmethod where-special-form-mm :service-silent [_]
(s/& (s/cat :k #{:service-silent}
:v1 ax/iri-or-var-spec
:v2 ::where)
(s/conformer (fn [{:keys [v1 v2]}] [:where/service-silent [v1 v2]]))))
(defmethod where-special-form-mm :filter [_]
(s/& (s/cat :k #{:filter}
:v ::es/expr)
(s/conformer (fn [{:keys [v]}] [:where/filter v]))))
(defmethod where-special-form-mm :bind [_]
(s/& (s/cat :k #{:bind}
:v ::es/expr-as-var)
(s/conformer (fn [{:keys [v]}] [:where/bind v]))))
(defmethod where-special-form-mm :values [_]
(s/& (s/cat :k #{:values}
:v ::vs/values)
(s/conformer (fn [{:keys [v]}] [:where/values v]))))
(def where-special-form-spec
"Specs for special WHERE forms/graph patterns, which should be
of the form `[:keyword ...]`."
(s/and vector? (s/multi-spec where-special-form-mm first)))
(s/def ::where
(s/or :where-sub/select
::select
:where-sub/where
(s/coll-of (s/or :where/special where-special-form-spec
:triple/vec ts/triple-vec-spec
:triple/nform ts/normal-form-spec)
:min-count 1
:kind vector?)
:where-sub/empty
(s/and vector? empty?)))
| null | https://raw.githubusercontent.com/yetanalytics/flint/b0a2530582e04f5592869b0152b846864c283d77/src/main/com/yetanalytics/flint/spec/where.cljc | clojure |
Sub-SELECT query
s/merge does not result in correct conformation
WHERE clause
recursion | (ns com.yetanalytics.flint.spec.where
(:require [clojure.spec.alpha :as s]
[com.yetanalytics.flint.spec.axiom :as ax]
[com.yetanalytics.flint.spec.expr :as es]
[com.yetanalytics.flint.spec.modifier :as ms]
[com.yetanalytics.flint.spec.select :as ss]
[com.yetanalytics.flint.spec.triple :as ts]
[com.yetanalytics.flint.spec.values :as vs])
#?(:clj (:require
[com.yetanalytics.flint.spec :refer [sparql-keys]])
:cljs (:require-macros
[com.yetanalytics.flint.spec :refer [sparql-keys]])))
(def key-order-map
{:select 2
:select-distinct 2
:select-reduced 2
:where 5
:group-by 6
:order-by 7
:having 8
:limit 9
:offset 10
:values 11})
(defn- key-comp
[k1 k2]
(let [n1 (get key-order-map k1 100)
n2 (get key-order-map k2 100)]
(- n1 n2)))
(s/def ::select
(sparql-keys :req-un [(or ::ss/select
::ss/select-distinct
::ss/select-reduced)
::where]
:opt-un [::vs/values
::ms/group-by
::ms/order-by
::ms/having
::ms/limit
::ms/offset]
:key-comp-fn key-comp))
(defmulti where-special-form-mm
"Accepts a special WHERE form/graph pattern in the form `[:keyword ...]`
and returns the appropriate regex spec. The spec applies an additional
conformer in order to allow for identification during formatting."
first)
(s/& (s/cat :k #{:where}
:v ::where)
(s/conformer (fn [{:keys [v]}] [:where/recurse v]))))
(defmethod where-special-form-mm :union [_]
(s/& (s/cat :k #{:union}
:v (s/+ ::where))
(s/conformer (fn [{:keys [v]}] [:where/union v]))))
(defmethod where-special-form-mm :optional [_]
(s/& (s/cat :k #{:optional}
:v ::where)
(s/conformer (fn [{:keys [v]}] [:where/optional v]))))
(defmethod where-special-form-mm :minus [_]
(s/& (s/cat :k #{:minus}
:v ::where)
(s/conformer (fn [{:keys [v]}] [:where/minus v]))))
(defmethod where-special-form-mm :graph [_]
(s/& (s/cat :k #{:graph}
:v1 ax/iri-or-var-spec
:v2 ::where)
(s/conformer (fn [{:keys [v1 v2]}] [:where/graph [v1 v2]]))))
(defmethod where-special-form-mm :service [_]
(s/& (s/cat :k #{:service}
:v1 ax/iri-or-var-spec
:v2 ::where)
(s/conformer (fn [{:keys [v1 v2]}] [:where/service [v1 v2]]))))
(defmethod where-special-form-mm :service-silent [_]
(s/& (s/cat :k #{:service-silent}
:v1 ax/iri-or-var-spec
:v2 ::where)
(s/conformer (fn [{:keys [v1 v2]}] [:where/service-silent [v1 v2]]))))
(defmethod where-special-form-mm :filter [_]
(s/& (s/cat :k #{:filter}
:v ::es/expr)
(s/conformer (fn [{:keys [v]}] [:where/filter v]))))
(defmethod where-special-form-mm :bind [_]
(s/& (s/cat :k #{:bind}
:v ::es/expr-as-var)
(s/conformer (fn [{:keys [v]}] [:where/bind v]))))
(defmethod where-special-form-mm :values [_]
(s/& (s/cat :k #{:values}
:v ::vs/values)
(s/conformer (fn [{:keys [v]}] [:where/values v]))))
(def where-special-form-spec
"Specs for special WHERE forms/graph patterns, which should be
of the form `[:keyword ...]`."
(s/and vector? (s/multi-spec where-special-form-mm first)))
(s/def ::where
(s/or :where-sub/select
::select
:where-sub/where
(s/coll-of (s/or :where/special where-special-form-spec
:triple/vec ts/triple-vec-spec
:triple/nform ts/normal-form-spec)
:min-count 1
:kind vector?)
:where-sub/empty
(s/and vector? empty?)))
|
183920fd7c9c644e7553dca5ec4854c0b15125155361f2bf177d0c869a6c0de3 | bscarlet/llvm-general | Exceptable.hs | # LANGUAGE
GeneralizedNewtypeDeriving ,
MultiParamTypeClasses ,
UndecidableInstances ,
CPP
#
GeneralizedNewtypeDeriving,
MultiParamTypeClasses,
UndecidableInstances,
CPP
#-}
module Control.Monad.Exceptable (
-- * MonadError class
MonadError(..),
* The monad
Exceptable,
exceptable,
runExceptable,
mapExceptable,
withExceptable,
makeExceptableT,
-- * The ExceptT monad transformer
ExceptableT(ExceptableT),
unExceptableT,
runExceptableT,
mapExceptableT,
withExceptableT,
-- * Exception operations
throwE,
catchE,
-- * Lifting other operations
liftCallCC,
liftListen,
liftPass,
-- * underlying ExceptT type
Except.Except,
Except.ExceptT,
module Control.Monad.Fix,
module Control.Monad.Trans,
* Example 1 : Custom Error Data Type
$ customErrorExample
* Example 2 : Using ExceptT Monad Transformer
$ ExceptTExample
) where
import Prelude
import qualified Control.Monad.Trans.Except as Except
import Control.Monad.Trans
import Control.Monad.Signatures
import Data.Functor.Classes
import Data.Functor.Identity
import Control.Monad.State.Class as State
import Control.Monad.Error.Class as Error
import Control.Applicative
import Control.Monad
import Control.Monad.Fix
#if __GLASGOW_HASKELL__ < 710
import Data.Foldable
import Data.Traversable (Traversable(traverse))
#endif
|
Why does the Exceptable module exist ? The present llvm general design
is around the use of the ExceptT transformer , first defined in transformers 0.4 .
Well , the goal of this module is to allow LLVM - General to be compatible with
GHC 7.8 apis , and GHC 7.8 comes bundled with transformers 0.3 . Thus LLVM - General
must be compatible with transformers 0.3 ( via the use of transformers - compat )
in order to be usable in conjunction with usage of GHC as a library .
At some future point where the active " power users " base of LLVM - General
no longer needs to support GHC 7.8 heavily , removing this Module and reverting other
changes elsewhere to using ExceptT / Except will be a good idea .
A good " signpost " for reverting will be around GHC 7.12 's release ,
because then there will be > = 2 GHC major version releases that come bundled with
Transformers > = 0.4
Why does the Exceptable module exist? The present llvm general design
is around the use of the ExceptT transformer, first defined in transformers 0.4.
Well, the goal of this module is to allow LLVM-General to be compatible with
GHC 7.8 apis, and GHC 7.8 comes bundled with transformers 0.3. Thus LLVM-General
must be compatible with transformers 0.3 (via the use of transformers-compat)
in order to be usable in conjunction with usage of GHC as a library.
At some future point where the active "power users" base of LLVM-General
no longer needs to support GHC 7.8 heavily, removing this Module and reverting other
changes elsewhere to using ExceptT / Except will be a good idea.
A good "signpost" for reverting will be around GHC 7.12's release,
because then there will be >=2 GHC major version releases that come bundled with
Transformers >= 0.4
-}
type Exceptable e = ExceptableT e Identity
-- | Constructor for computations in the exception monad.
( The inverse of ' runExcept ' ) .
except :: Either e a -> Exceptable e a
except m = makeExceptableT (Identity m)
exceptable :: Except.Except e a -> Exceptable e a
exceptable = ExceptableT
-- | Extractor for computations in the exception monad.
-- (The inverse of 'except').
runExceptable :: Exceptable e a -> Either e a
runExceptable (ExceptableT m) = runIdentity $ Except.runExceptT m
-- | Map the unwrapped computation using the given function.
--
* @'runExcept ' ( ' mapExcept ' f m ) = f ( ' runExcept ' m)@
mapExceptable :: (Either e a -> Either e' b)
-> Exceptable e a
-> Exceptable e' b
mapExceptable f = mapExceptableT (Identity . f . runIdentity)
-- | Transform any exceptions thrown by the computation using the given
-- function (a specialization of 'withExceptT').
withExceptable :: (e -> e') -> Exceptable e a -> Exceptable e' a
withExceptable = withExceptableT
newtype ExceptableT e m a = ExceptableT { unExceptableT :: Except.ExceptT e m a }
deriving (
Eq,
Eq1,
Ord,
Ord1,
Functor,
Foldable,
Applicative,
Alternative,
Monad,
MonadPlus,
MonadTrans,
MonadIO
)
instance MonadState s m => MonadState s (ExceptableT e m) where
get = lift get
put = lift . put
state = lift . state
instance Monad m => MonadError e (ExceptableT e m) where
throwError = throwE
catchError = catchE
instance (Traversable f) => Traversable (ExceptableT e f) where
traverse f a =
(ExceptableT . Except.ExceptT) <$>
traverse (either (pure . Left) (fmap Right . f)) (runExceptableT a)
instance (Read e, Read1 m, Read a) => Read (ExceptableT e m a) where
readsPrec = readsData $ readsUnary1 "ExceptableT" ExceptableT
instance (Show e, Show1 m, Show a) => Show (ExceptableT e m a) where
showsPrec d (ExceptableT m) = showsUnary1 "ExceptableT" d m
instance (Read e, Read1 m) => Read1 (ExceptableT e m) where readsPrec1 = readsPrec
instance (Show e, Show1 m) => Show1 (ExceptableT e m) where showsPrec1 = showsPrec
runExceptableT :: ExceptableT e m a -> m (Either e a)
runExceptableT = Except.runExceptT . unExceptableT
makeExceptableT :: m (Either e a) -> ExceptableT e m a
makeExceptableT = ExceptableT . Except.ExceptT
-- | Map the unwrapped computation using the given function.
--
-- * @'runExceptT' ('mapExceptT' f m) = f ('runExceptT' m)@
mapExceptableT :: (m (Either e a) -> n (Either e' b))
-> ExceptableT e m a
-> ExceptableT e' n b
mapExceptableT f m = makeExceptableT $ f (runExceptableT m)
-- | Transform any exceptions thrown by the computation using the
-- given function.
withExceptableT :: (Functor m) => (e -> e') -> ExceptableT e m a -> ExceptableT e' m a
withExceptableT f = mapExceptableT $ fmap $ either (Left . f) Right
-- | Signal an exception value @e@.
--
-- * @'runExceptT' ('throwE' e) = 'return' ('Left' e)@
--
-- * @'throwE' e >>= m = 'throwE' e@
throwE :: (Monad m) => e -> ExceptableT e m a
throwE = makeExceptableT . return . Left
-- | Handle an exception.
--
-- * @'catchE' h ('lift' m) = 'lift' m@
--
-- * @'catchE' h ('throwE' e) = h e@
catchE :: (Monad m) =>
ExceptableT e m a -- ^ the inner computation
-> (e -> ExceptableT e' m a) -- ^ a handler for exceptions in the inner
-- computation
-> ExceptableT e' m a
m `catchE` h = makeExceptableT $ do
a <- runExceptableT m
case a of
Left l -> runExceptableT (h l)
Right r -> return (Right r)
-- | Lift a @callCC@ operation to the new monad.
liftCallCC :: CallCC m (Either e a) (Either e b) -> CallCC (ExceptableT e m) a b
liftCallCC callCC f = makeExceptableT $
callCC $ \ c ->
runExceptableT (f (\ a -> makeExceptableT $ c (Right a)))
-- | Lift a @listen@ operation to the new monad.
liftListen :: (Monad m) => Listen w m (Either e a) -> Listen w (ExceptableT e m) a
liftListen listen = mapExceptableT $ \ m -> do
(a, w) <- listen m
return $! fmap (\ r -> (r, w)) a
| Lift a @pass@ operation to the new monad .
liftPass :: (Monad m) => Pass w m (Either e a) -> Pass w (ExceptableT e m) a
liftPass pass = mapExceptableT $ \ m -> pass $ do
a <- m
return $! case a of
Left l -> (Left l, id)
Right (r, f) -> (Right r, f)
| null | https://raw.githubusercontent.com/bscarlet/llvm-general/61fd03639063283e7dc617698265cc883baf0eec/llvm-general/src/Control/Monad/Exceptable.hs | haskell | * MonadError class
* The ExceptT monad transformer
* Exception operations
* Lifting other operations
* underlying ExceptT type
| Constructor for computations in the exception monad.
| Extractor for computations in the exception monad.
(The inverse of 'except').
| Map the unwrapped computation using the given function.
| Transform any exceptions thrown by the computation using the given
function (a specialization of 'withExceptT').
| Map the unwrapped computation using the given function.
* @'runExceptT' ('mapExceptT' f m) = f ('runExceptT' m)@
| Transform any exceptions thrown by the computation using the
given function.
| Signal an exception value @e@.
* @'runExceptT' ('throwE' e) = 'return' ('Left' e)@
* @'throwE' e >>= m = 'throwE' e@
| Handle an exception.
* @'catchE' h ('lift' m) = 'lift' m@
* @'catchE' h ('throwE' e) = h e@
^ the inner computation
^ a handler for exceptions in the inner
computation
| Lift a @callCC@ operation to the new monad.
| Lift a @listen@ operation to the new monad. | # LANGUAGE
GeneralizedNewtypeDeriving ,
MultiParamTypeClasses ,
UndecidableInstances ,
CPP
#
GeneralizedNewtypeDeriving,
MultiParamTypeClasses,
UndecidableInstances,
CPP
#-}
module Control.Monad.Exceptable (
MonadError(..),
* The monad
Exceptable,
exceptable,
runExceptable,
mapExceptable,
withExceptable,
makeExceptableT,
ExceptableT(ExceptableT),
unExceptableT,
runExceptableT,
mapExceptableT,
withExceptableT,
throwE,
catchE,
liftCallCC,
liftListen,
liftPass,
Except.Except,
Except.ExceptT,
module Control.Monad.Fix,
module Control.Monad.Trans,
* Example 1 : Custom Error Data Type
$ customErrorExample
* Example 2 : Using ExceptT Monad Transformer
$ ExceptTExample
) where
import Prelude
import qualified Control.Monad.Trans.Except as Except
import Control.Monad.Trans
import Control.Monad.Signatures
import Data.Functor.Classes
import Data.Functor.Identity
import Control.Monad.State.Class as State
import Control.Monad.Error.Class as Error
import Control.Applicative
import Control.Monad
import Control.Monad.Fix
#if __GLASGOW_HASKELL__ < 710
import Data.Foldable
import Data.Traversable (Traversable(traverse))
#endif
|
Why does the Exceptable module exist ? The present llvm general design
is around the use of the ExceptT transformer , first defined in transformers 0.4 .
Well , the goal of this module is to allow LLVM - General to be compatible with
GHC 7.8 apis , and GHC 7.8 comes bundled with transformers 0.3 . Thus LLVM - General
must be compatible with transformers 0.3 ( via the use of transformers - compat )
in order to be usable in conjunction with usage of GHC as a library .
At some future point where the active " power users " base of LLVM - General
no longer needs to support GHC 7.8 heavily , removing this Module and reverting other
changes elsewhere to using ExceptT / Except will be a good idea .
A good " signpost " for reverting will be around GHC 7.12 's release ,
because then there will be > = 2 GHC major version releases that come bundled with
Transformers > = 0.4
Why does the Exceptable module exist? The present llvm general design
is around the use of the ExceptT transformer, first defined in transformers 0.4.
Well, the goal of this module is to allow LLVM-General to be compatible with
GHC 7.8 apis, and GHC 7.8 comes bundled with transformers 0.3. Thus LLVM-General
must be compatible with transformers 0.3 (via the use of transformers-compat)
in order to be usable in conjunction with usage of GHC as a library.
At some future point where the active "power users" base of LLVM-General
no longer needs to support GHC 7.8 heavily, removing this Module and reverting other
changes elsewhere to using ExceptT / Except will be a good idea.
A good "signpost" for reverting will be around GHC 7.12's release,
because then there will be >=2 GHC major version releases that come bundled with
Transformers >= 0.4
-}
type Exceptable e = ExceptableT e Identity
( The inverse of ' runExcept ' ) .
except :: Either e a -> Exceptable e a
except m = makeExceptableT (Identity m)
exceptable :: Except.Except e a -> Exceptable e a
exceptable = ExceptableT
runExceptable :: Exceptable e a -> Either e a
runExceptable (ExceptableT m) = runIdentity $ Except.runExceptT m
* @'runExcept ' ( ' mapExcept ' f m ) = f ( ' runExcept ' m)@
mapExceptable :: (Either e a -> Either e' b)
-> Exceptable e a
-> Exceptable e' b
mapExceptable f = mapExceptableT (Identity . f . runIdentity)
withExceptable :: (e -> e') -> Exceptable e a -> Exceptable e' a
withExceptable = withExceptableT
newtype ExceptableT e m a = ExceptableT { unExceptableT :: Except.ExceptT e m a }
deriving (
Eq,
Eq1,
Ord,
Ord1,
Functor,
Foldable,
Applicative,
Alternative,
Monad,
MonadPlus,
MonadTrans,
MonadIO
)
instance MonadState s m => MonadState s (ExceptableT e m) where
get = lift get
put = lift . put
state = lift . state
instance Monad m => MonadError e (ExceptableT e m) where
throwError = throwE
catchError = catchE
instance (Traversable f) => Traversable (ExceptableT e f) where
traverse f a =
(ExceptableT . Except.ExceptT) <$>
traverse (either (pure . Left) (fmap Right . f)) (runExceptableT a)
instance (Read e, Read1 m, Read a) => Read (ExceptableT e m a) where
readsPrec = readsData $ readsUnary1 "ExceptableT" ExceptableT
instance (Show e, Show1 m, Show a) => Show (ExceptableT e m a) where
showsPrec d (ExceptableT m) = showsUnary1 "ExceptableT" d m
instance (Read e, Read1 m) => Read1 (ExceptableT e m) where readsPrec1 = readsPrec
instance (Show e, Show1 m) => Show1 (ExceptableT e m) where showsPrec1 = showsPrec
runExceptableT :: ExceptableT e m a -> m (Either e a)
runExceptableT = Except.runExceptT . unExceptableT
makeExceptableT :: m (Either e a) -> ExceptableT e m a
makeExceptableT = ExceptableT . Except.ExceptT
mapExceptableT :: (m (Either e a) -> n (Either e' b))
-> ExceptableT e m a
-> ExceptableT e' n b
mapExceptableT f m = makeExceptableT $ f (runExceptableT m)
withExceptableT :: (Functor m) => (e -> e') -> ExceptableT e m a -> ExceptableT e' m a
withExceptableT f = mapExceptableT $ fmap $ either (Left . f) Right
throwE :: (Monad m) => e -> ExceptableT e m a
throwE = makeExceptableT . return . Left
catchE :: (Monad m) =>
-> ExceptableT e' m a
m `catchE` h = makeExceptableT $ do
a <- runExceptableT m
case a of
Left l -> runExceptableT (h l)
Right r -> return (Right r)
liftCallCC :: CallCC m (Either e a) (Either e b) -> CallCC (ExceptableT e m) a b
liftCallCC callCC f = makeExceptableT $
callCC $ \ c ->
runExceptableT (f (\ a -> makeExceptableT $ c (Right a)))
liftListen :: (Monad m) => Listen w m (Either e a) -> Listen w (ExceptableT e m) a
liftListen listen = mapExceptableT $ \ m -> do
(a, w) <- listen m
return $! fmap (\ r -> (r, w)) a
| Lift a @pass@ operation to the new monad .
liftPass :: (Monad m) => Pass w m (Either e a) -> Pass w (ExceptableT e m) a
liftPass pass = mapExceptableT $ \ m -> pass $ do
a <- m
return $! case a of
Left l -> (Left l, id)
Right (r, f) -> (Right r, f)
|
35f642b7d8ff5f8fec64f0fe24478d1e70064e5e199a19ef5af2ed362b4e4b98 | ejgallego/coq-serapi | ser_environ.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2016
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(************************************************************************)
(* Coq serialization API/Plugin *)
Copyright 2016 - 2020 MINES ParisTech / INRIA
(************************************************************************)
(* Status: Experimental *)
(************************************************************************)
open Sexplib.Std
open Ppx_hash_lib.Std.Hash.Builtin
open Ppx_compare_lib.Builtin
module Stdlib = Ser_stdlib
module CEphemeron = Ser_cEphemeron
module Range = Ser_range
module Names = Ser_names
module Constr = Ser_constr
module Univ = Ser_univ
module Nativevalues = Ser_nativevalues
module Opaqueproof = Ser_opaqueproof
module Retroknowledge = Ser_retroknowledge
module UGraph = Ser_uGraph
module Declarations = Ser_declarations
(* type stratification =
* [%import: Environ.stratification]
* [@@deriving sexp_of] *)
type rel_context_val =
[%import: Environ.rel_context_val]
[@@deriving sexp_of]
type named_context_val =
[%import: Environ.named_context_val]
[@@deriving sexp_of]
type link_info =
[%import: Environ.link_info]
[@@deriving sexp,yojson,hash,compare]
type key =
[%import: Environ.key]
[@@deriving sexp,yojson,hash,compare]
type constant_key =
[%import: Environ.constant_key]
[@@deriving sexp,yojson,hash,compare]
type mind_key =
[%import: Environ.mind_key]
[@@deriving sexp,yojson,hash,compare]
module Globals = struct
module PierceSpec = struct
type t = Environ.Globals.t
type _t = [%import: Environ.Globals.view]
[@@deriving sexp,yojson,hash,compare]
end
include SerType.Pierce(PierceSpec)
end
type env =
[%import: Environ.env]
[@@deriving sexp_of]
let env_of_sexp = Serlib_base.opaque_of_sexp ~typ:"Environ.env"
let abstract_env = ref false
let sexp_of_env env =
if !abstract_env
then Serlib_base.sexp_of_opaque ~typ:"Environ.env" env
else sexp_of_env env
type ('constr, 'term) punsafe_judgment =
[%import: ('constr, 'term) Environ.punsafe_judgment]
[@@deriving sexp]
type unsafe_judgment =
[%import: Environ.unsafe_judgment]
[@@deriving sexp]
| null | https://raw.githubusercontent.com/ejgallego/coq-serapi/9c799e3d8965a78dce6b5af29a61e1997c8e17a4/serlib/ser_environ.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
**********************************************************************
Coq serialization API/Plugin
**********************************************************************
Status: Experimental
**********************************************************************
type stratification =
* [%import: Environ.stratification]
* [@@deriving sexp_of] | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2016
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Copyright 2016 - 2020 MINES ParisTech / INRIA
open Sexplib.Std
open Ppx_hash_lib.Std.Hash.Builtin
open Ppx_compare_lib.Builtin
module Stdlib = Ser_stdlib
module CEphemeron = Ser_cEphemeron
module Range = Ser_range
module Names = Ser_names
module Constr = Ser_constr
module Univ = Ser_univ
module Nativevalues = Ser_nativevalues
module Opaqueproof = Ser_opaqueproof
module Retroknowledge = Ser_retroknowledge
module UGraph = Ser_uGraph
module Declarations = Ser_declarations
type rel_context_val =
[%import: Environ.rel_context_val]
[@@deriving sexp_of]
type named_context_val =
[%import: Environ.named_context_val]
[@@deriving sexp_of]
type link_info =
[%import: Environ.link_info]
[@@deriving sexp,yojson,hash,compare]
type key =
[%import: Environ.key]
[@@deriving sexp,yojson,hash,compare]
type constant_key =
[%import: Environ.constant_key]
[@@deriving sexp,yojson,hash,compare]
type mind_key =
[%import: Environ.mind_key]
[@@deriving sexp,yojson,hash,compare]
module Globals = struct
module PierceSpec = struct
type t = Environ.Globals.t
type _t = [%import: Environ.Globals.view]
[@@deriving sexp,yojson,hash,compare]
end
include SerType.Pierce(PierceSpec)
end
type env =
[%import: Environ.env]
[@@deriving sexp_of]
let env_of_sexp = Serlib_base.opaque_of_sexp ~typ:"Environ.env"
let abstract_env = ref false
let sexp_of_env env =
if !abstract_env
then Serlib_base.sexp_of_opaque ~typ:"Environ.env" env
else sexp_of_env env
type ('constr, 'term) punsafe_judgment =
[%import: ('constr, 'term) Environ.punsafe_judgment]
[@@deriving sexp]
type unsafe_judgment =
[%import: Environ.unsafe_judgment]
[@@deriving sexp]
|
7025c99e07c7bf36c5d052b6fdef3cbded6290d3b51127ce6c0c6e7d6771eeed | froggey/Mezzano | network-setup.lisp | Network initialization and link management
(in-package :mezzano.network)
;; Everything in the network stack uses a single serial queue for the moment...
(defvar *network-serial-queue*)
These three variables are only accessed from the network serial queue
;; and don't need additional synchronization.
(defvar *receive-sources* (make-hash-table))
(defvar *boot-source* nil)
(defvar *interface-config* (make-hash-table))
(defvar *static-configurations*
'((t :dhcp) ; match all interfaces
This is the old static IP configuration , for use in VirtualBox / qemu .
#+(or)
(t ; match all interfaces
:static
:local-ip "10.0.2.15"
Use a prefix - length of 24 instead of 8 , so people
;; running the file-server on non-10.0.2.0 10/8 networks
:prefix-length 24
:gateway "10.0.2.2"
Use Google DNS , as Virtualbox does not provide a DNS
server within the NAT .
:dns-servers ("8.8.8.8")))
"A list of known INTERFACEs and configurations to use with them.")
(defun match-static-configuration (interface)
(dolist (conf *static-configurations* nil)
(when (or (eql (first conf) t) ; wildcard configuration
(equal (first conf) (mezzano.driver.network-card:mac-address interface)))
(return (rest conf)))))
(defmethod configure-interface (interface (configuration-type (eql :static)) &key local-ip prefix-length gateway dns-servers)
(let ((local-ip (mezzano.network.ip:make-ipv4-address local-ip)))
;; Bring interfaces up.
(mezzano.network.ip::ifup interface local-ip prefix-length)
;; Add routes.
;; Local network.
(mezzano.network.ip:add-route
(mezzano.network.ip:address-network local-ip prefix-length)
prefix-length
interface
interface)
;; Default route.
(when gateway
(mezzano.network.ip:add-route
"0.0.0.0" 0
(mezzano.network.ip:make-ipv4-address gateway)
interface))
(dolist (dns-server dns-servers)
(mezzano.network.dns:add-dns-server dns-server interface))))
(defmethod deconfigure-interface (interface (configuration-type (eql :static)) &key local-ip prefix-length gateway dns-servers)
(let ((local-ip (mezzano.network.ip:make-ipv4-address local-ip)))
(mezzano.network.ip:remove-route
(mezzano.network.ip:address-network local-ip prefix-length)
prefix-length
interface)
(when gateway
(mezzano.network.ip:remove-route "0.0.0.0" 0 interface))
(dolist (dns-server dns-servers)
(mezzano.network.dns:remove-dns-server dns-server interface))
(mezzano.network.ip::ifdown interface)))
(defun nic-added (nic)
;; Do receive work for this nic.
(let ((source (mezzano.sync.dispatch:make-source
(mezzano.driver.network-card:receive-mailbox nic)
(lambda ()
(sys.int::log-and-ignore-errors
(let ((packet (mezzano.sync:mailbox-receive
(mezzano.driver.network-card:receive-mailbox nic)
:wait-p nil)))
(when packet
(mezzano.network.ethernet::receive-ethernet-packet
nic packet)))))
:target *network-serial-queue*)))
(setf (gethash nic *receive-sources*) source))
;; Bring this interface up.
(let ((conf (match-static-configuration nic)))
(cond (conf
(setf (gethash nic *interface-config*) conf)
(apply #'configure-interface nic (first conf) (rest conf)))
(t
(format t "No static configuration available for interface ~A~%" nic)))))
(defun nic-removed (nic)
(let ((conf (gethash nic *interface-config*)))
(when conf
(apply #'deconfigure-interface nic (first conf) (rest conf))
(remhash nic *interface-config*)))
;; Stop trying to receive packets on this interface.
(mezzano.sync.dispatch:cancel (gethash nic *receive-sources*))
(remhash nic *receive-sources*))
(defun network-boot-handler ()
(mezzano.supervisor:with-snapshot-inhibited ()
(mezzano.network.tcp::flush-stale-connections)
(mezzano.sync.dispatch:cancel *boot-source*)
(setf *boot-source* (mezzano.sync.dispatch:make-source
(mezzano.supervisor:current-boot-id)
'network-boot-handler
:target *network-serial-queue*))))
ARP expiration disabled .
;; It's causing the IP layer to drop packets which breaks long-running TCP connections.
(defun initialize-network-stack ()
(setf *network-serial-queue* (mezzano.sync.dispatch:make-queue
:name "Main network stack queue"
:concurrent nil
;; Start suspended so tasks aren't run
;; during initialization.
:suspended t))
Create sources for NIC addition / removal .
(let ((nic-add-mailbox (mezzano.sync:make-mailbox :name "NIC add mailbox"))
(nic-rem-mailbox (mezzano.sync:make-mailbox :name "NIC rem mailbox"))
#+(or)
(arp-expiration-timer (mezzano.supervisor:make-timer :name "ARP expiration timer")))
#+(or)
(setf mezzano.network.arp::*arp-expiration-timer* arp-expiration-timer)
(mezzano.sync.dispatch:make-source
nic-add-mailbox
(lambda ()
(nic-added (mezzano.sync:mailbox-receive nic-add-mailbox)))
:target *network-serial-queue*)
(mezzano.sync.dispatch:make-source
nic-rem-mailbox
(lambda ()
(nic-removed (mezzano.sync:mailbox-receive nic-rem-mailbox)))
:target *network-serial-queue*)
#+(or)
(mezzano.sync.dispatch:make-source
arp-expiration-timer
(lambda ()
(mezzano.network.arp::arp-expiration))
:target *network-serial-queue*)
(mezzano.driver.network-card:add-nic-watchers
nic-add-mailbox nic-rem-mailbox))
(setf *boot-source* (mezzano.sync.dispatch:make-source
(mezzano.supervisor:current-boot-id)
'network-boot-handler
:target *network-serial-queue*))
(setf mezzano.network.ip::*routing-table* '()
mezzano.network.ip::*ipv4-interfaces* '()
mezzano.network.ip::*outstanding-sends* '()
mezzano.network.arp::*arp-table* '()
*hosts* `(("localhost" "127.0.0.1")))
(let ((loopback-interface (make-instance 'loopback-interface)))
(mezzano.network.ip::ifup loopback-interface "127.0.0.1" 8)
(mezzano.network.ip:add-route "127.0.0.0" 8 loopback-interface))
;; All initialzation work complete, now safe to run tasks.
(mezzano.sync.dispatch:resume *network-serial-queue*))
(defvar *network-dispatch-context*
(mezzano.sync.dispatch:make-dispatch-context
:initial-work #'initialize-network-stack
:name "Network stack"))
| null | https://raw.githubusercontent.com/froggey/Mezzano/f0eeb2a3f032098b394e31e3dfd32800f8a51122/net/network-setup.lisp | lisp | Everything in the network stack uses a single serial queue for the moment...
and don't need additional synchronization.
match all interfaces
match all interfaces
running the file-server on non-10.0.2.0 10/8 networks
wildcard configuration
Bring interfaces up.
Add routes.
Local network.
Default route.
Do receive work for this nic.
Bring this interface up.
Stop trying to receive packets on this interface.
It's causing the IP layer to drop packets which breaks long-running TCP connections.
Start suspended so tasks aren't run
during initialization.
All initialzation work complete, now safe to run tasks. | Network initialization and link management
(in-package :mezzano.network)
(defvar *network-serial-queue*)
These three variables are only accessed from the network serial queue
(defvar *receive-sources* (make-hash-table))
(defvar *boot-source* nil)
(defvar *interface-config* (make-hash-table))
(defvar *static-configurations*
This is the old static IP configuration , for use in VirtualBox / qemu .
#+(or)
:static
:local-ip "10.0.2.15"
Use a prefix - length of 24 instead of 8 , so people
:prefix-length 24
:gateway "10.0.2.2"
Use Google DNS , as Virtualbox does not provide a DNS
server within the NAT .
:dns-servers ("8.8.8.8")))
"A list of known INTERFACEs and configurations to use with them.")
(defun match-static-configuration (interface)
(dolist (conf *static-configurations* nil)
(equal (first conf) (mezzano.driver.network-card:mac-address interface)))
(return (rest conf)))))
(defmethod configure-interface (interface (configuration-type (eql :static)) &key local-ip prefix-length gateway dns-servers)
(let ((local-ip (mezzano.network.ip:make-ipv4-address local-ip)))
(mezzano.network.ip::ifup interface local-ip prefix-length)
(mezzano.network.ip:add-route
(mezzano.network.ip:address-network local-ip prefix-length)
prefix-length
interface
interface)
(when gateway
(mezzano.network.ip:add-route
"0.0.0.0" 0
(mezzano.network.ip:make-ipv4-address gateway)
interface))
(dolist (dns-server dns-servers)
(mezzano.network.dns:add-dns-server dns-server interface))))
(defmethod deconfigure-interface (interface (configuration-type (eql :static)) &key local-ip prefix-length gateway dns-servers)
(let ((local-ip (mezzano.network.ip:make-ipv4-address local-ip)))
(mezzano.network.ip:remove-route
(mezzano.network.ip:address-network local-ip prefix-length)
prefix-length
interface)
(when gateway
(mezzano.network.ip:remove-route "0.0.0.0" 0 interface))
(dolist (dns-server dns-servers)
(mezzano.network.dns:remove-dns-server dns-server interface))
(mezzano.network.ip::ifdown interface)))
(defun nic-added (nic)
(let ((source (mezzano.sync.dispatch:make-source
(mezzano.driver.network-card:receive-mailbox nic)
(lambda ()
(sys.int::log-and-ignore-errors
(let ((packet (mezzano.sync:mailbox-receive
(mezzano.driver.network-card:receive-mailbox nic)
:wait-p nil)))
(when packet
(mezzano.network.ethernet::receive-ethernet-packet
nic packet)))))
:target *network-serial-queue*)))
(setf (gethash nic *receive-sources*) source))
(let ((conf (match-static-configuration nic)))
(cond (conf
(setf (gethash nic *interface-config*) conf)
(apply #'configure-interface nic (first conf) (rest conf)))
(t
(format t "No static configuration available for interface ~A~%" nic)))))
(defun nic-removed (nic)
(let ((conf (gethash nic *interface-config*)))
(when conf
(apply #'deconfigure-interface nic (first conf) (rest conf))
(remhash nic *interface-config*)))
(mezzano.sync.dispatch:cancel (gethash nic *receive-sources*))
(remhash nic *receive-sources*))
(defun network-boot-handler ()
(mezzano.supervisor:with-snapshot-inhibited ()
(mezzano.network.tcp::flush-stale-connections)
(mezzano.sync.dispatch:cancel *boot-source*)
(setf *boot-source* (mezzano.sync.dispatch:make-source
(mezzano.supervisor:current-boot-id)
'network-boot-handler
:target *network-serial-queue*))))
ARP expiration disabled .
(defun initialize-network-stack ()
(setf *network-serial-queue* (mezzano.sync.dispatch:make-queue
:name "Main network stack queue"
:concurrent nil
:suspended t))
Create sources for NIC addition / removal .
(let ((nic-add-mailbox (mezzano.sync:make-mailbox :name "NIC add mailbox"))
(nic-rem-mailbox (mezzano.sync:make-mailbox :name "NIC rem mailbox"))
#+(or)
(arp-expiration-timer (mezzano.supervisor:make-timer :name "ARP expiration timer")))
#+(or)
(setf mezzano.network.arp::*arp-expiration-timer* arp-expiration-timer)
(mezzano.sync.dispatch:make-source
nic-add-mailbox
(lambda ()
(nic-added (mezzano.sync:mailbox-receive nic-add-mailbox)))
:target *network-serial-queue*)
(mezzano.sync.dispatch:make-source
nic-rem-mailbox
(lambda ()
(nic-removed (mezzano.sync:mailbox-receive nic-rem-mailbox)))
:target *network-serial-queue*)
#+(or)
(mezzano.sync.dispatch:make-source
arp-expiration-timer
(lambda ()
(mezzano.network.arp::arp-expiration))
:target *network-serial-queue*)
(mezzano.driver.network-card:add-nic-watchers
nic-add-mailbox nic-rem-mailbox))
(setf *boot-source* (mezzano.sync.dispatch:make-source
(mezzano.supervisor:current-boot-id)
'network-boot-handler
:target *network-serial-queue*))
(setf mezzano.network.ip::*routing-table* '()
mezzano.network.ip::*ipv4-interfaces* '()
mezzano.network.ip::*outstanding-sends* '()
mezzano.network.arp::*arp-table* '()
*hosts* `(("localhost" "127.0.0.1")))
(let ((loopback-interface (make-instance 'loopback-interface)))
(mezzano.network.ip::ifup loopback-interface "127.0.0.1" 8)
(mezzano.network.ip:add-route "127.0.0.0" 8 loopback-interface))
(mezzano.sync.dispatch:resume *network-serial-queue*))
(defvar *network-dispatch-context*
(mezzano.sync.dispatch:make-dispatch-context
:initial-work #'initialize-network-stack
:name "Network stack"))
|
f15df5ac686127881466c3ebc8dff0a17e8c78bfe9a1bbf1e3437a174e410655 | tautologico/opfp | exp.ml |
expressoes aritmeticas
Interpretador ,
Linguagem de expressoes aritmeticas
Interpretador, compilador para maquina de pilha
*)
* { 1 }
(** Tipo para expressões *)
type exp =
| Const of int
| Soma of exp * exp
| Sub of exp * exp
| Mult of exp * exp
let rec print e =
match e with
Const n -> string_of_int n
| Soma (e1, e2) ->
Printf.sprintf "(%s + %s)" (print e1) (print e2)
| Sub (e1, e2) ->
Printf.sprintf "(%s - %s)" (print e1) (print e2)
| Mult (e1, e2) ->
Printf.sprintf "(%s * %s)" (print e1) (print e2)
* Interpretador para expressões
let rec eval e =
match e with
Const n -> n
| Soma (e1, e2) -> eval e1 + eval e2
| Sub (e1, e2) -> eval e1 - eval e2
| Mult (e1, e2) -> eval e1 * eval e2
* { 1 Máquina de Pilha }
(** Operações da máquina *)
type operacao = OpSoma | OpSub | OpMult
*
type instrucao =
| Empilha of int
| Oper of operacao
* Um programa é uma lista de instrucoes
type programa = instrucao list
* A pilha da máquina é uma lista
type pilha = int list
(** Obtém dois operandos de uma pilha *)
let operandos p =
match p with
| [] -> None
| _ :: [] -> None
| n1 :: n2 :: r -> Some ((n1, n2), r)
* a função em corresponde a cada operador da máquina
let oper o =
match o with
| OpSoma -> (+)
| OpSub -> (-)
espaços são necessários com comentário
* Executa uma instrução da máquina de pilha .
Dada , a execução .
Dada uma pilha, retorna a pilha resultante apos a execução. *)
let exec_inst p inst =
match inst with
Empilha n -> n :: p
| Oper o ->
match operandos p with
mantem a mesma pilha se deu errado
| Some ((n1, n2), r) ->
let op = oper o in
(op n1 n2) :: r
* Executa um programa , assumindo que a pilha
inicia vazia .
inicia vazia. *)
let rec exec_prog p =
List.fold_left exec_inst [] p
* Executa um programa e o resultado , se houver .
let executa p =
match exec_prog p with
[] -> None
| r :: _ -> Some r
* Compila uma expressão em árvore sintática para um programa da
máquina .
máquina de pilha. *)
let rec compila e =
match e with
| Const n -> [Empilha n]
| Soma (e1, e2) -> (compila e2) @ (compila e1) @ [Oper OpSoma]
| Sub (e1, e2) -> (compila e2) @ (compila e1) @ [Oper OpSub]
| Mult (e1, e2) -> (compila e2) @ (compila e1) @ [Oper OpMult]
Otimizacao
(** Elimina sub-expressões de soma com o valor 0 *)
let rec elimina_soma_0 e =
match e with
| Const _ -> e
| Soma (Const 0, e2) -> elimina_soma_0 e2
| Soma (e1, Const 0) -> elimina_soma_0 e1
| Soma (e1, e2) -> Soma (elimina_soma_0 e1, elimina_soma_0 e2)
| Sub (e1, e2) -> Sub (elimina_soma_0 e1, elimina_soma_0 e2)
| Mult (e1, e2) -> Mult (elimina_soma_0 e1, elimina_soma_0 e2)
* { 1 Opcional : análise sintática }
type lexer = { str: string; }
type token = { str: string; pos_ini: int; pos_prox: int }
let =
let proximo_token tok =
*)
(* TODO traducao para ILasm *)
| null | https://raw.githubusercontent.com/tautologico/opfp/74ef9ed97b0ab6b78c147c3edf7e0b69f2acf9d1/exp/src/exp.ml | ocaml | * Tipo para expressões
* Operações da máquina
* Obtém dois operandos de uma pilha
* Elimina sub-expressões de soma com o valor 0
TODO traducao para ILasm |
expressoes aritmeticas
Interpretador ,
Linguagem de expressoes aritmeticas
Interpretador, compilador para maquina de pilha
*)
* { 1 }
type exp =
| Const of int
| Soma of exp * exp
| Sub of exp * exp
| Mult of exp * exp
let rec print e =
match e with
Const n -> string_of_int n
| Soma (e1, e2) ->
Printf.sprintf "(%s + %s)" (print e1) (print e2)
| Sub (e1, e2) ->
Printf.sprintf "(%s - %s)" (print e1) (print e2)
| Mult (e1, e2) ->
Printf.sprintf "(%s * %s)" (print e1) (print e2)
* Interpretador para expressões
let rec eval e =
match e with
Const n -> n
| Soma (e1, e2) -> eval e1 + eval e2
| Sub (e1, e2) -> eval e1 - eval e2
| Mult (e1, e2) -> eval e1 * eval e2
* { 1 Máquina de Pilha }
type operacao = OpSoma | OpSub | OpMult
*
type instrucao =
| Empilha of int
| Oper of operacao
* Um programa é uma lista de instrucoes
type programa = instrucao list
* A pilha da máquina é uma lista
type pilha = int list
let operandos p =
match p with
| [] -> None
| _ :: [] -> None
| n1 :: n2 :: r -> Some ((n1, n2), r)
* a função em corresponde a cada operador da máquina
let oper o =
match o with
| OpSoma -> (+)
| OpSub -> (-)
espaços são necessários com comentário
* Executa uma instrução da máquina de pilha .
Dada , a execução .
Dada uma pilha, retorna a pilha resultante apos a execução. *)
let exec_inst p inst =
match inst with
Empilha n -> n :: p
| Oper o ->
match operandos p with
mantem a mesma pilha se deu errado
| Some ((n1, n2), r) ->
let op = oper o in
(op n1 n2) :: r
* Executa um programa , assumindo que a pilha
inicia vazia .
inicia vazia. *)
let rec exec_prog p =
List.fold_left exec_inst [] p
* Executa um programa e o resultado , se houver .
let executa p =
match exec_prog p with
[] -> None
| r :: _ -> Some r
* Compila uma expressão em árvore sintática para um programa da
máquina .
máquina de pilha. *)
let rec compila e =
match e with
| Const n -> [Empilha n]
| Soma (e1, e2) -> (compila e2) @ (compila e1) @ [Oper OpSoma]
| Sub (e1, e2) -> (compila e2) @ (compila e1) @ [Oper OpSub]
| Mult (e1, e2) -> (compila e2) @ (compila e1) @ [Oper OpMult]
Otimizacao
let rec elimina_soma_0 e =
match e with
| Const _ -> e
| Soma (Const 0, e2) -> elimina_soma_0 e2
| Soma (e1, Const 0) -> elimina_soma_0 e1
| Soma (e1, e2) -> Soma (elimina_soma_0 e1, elimina_soma_0 e2)
| Sub (e1, e2) -> Sub (elimina_soma_0 e1, elimina_soma_0 e2)
| Mult (e1, e2) -> Mult (elimina_soma_0 e1, elimina_soma_0 e2)
* { 1 Opcional : análise sintática }
type lexer = { str: string; }
type token = { str: string; pos_ini: int; pos_prox: int }
let =
let proximo_token tok =
*)
|
753d0231d3adeed672dc1f06d9787402137e61de7d84c5661304cd4e53b26b26 | mpickering/apply-refact | Bracket16.hs | main = do f; (print x) | null | https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Bracket16.hs | haskell | main = do f; (print x) | |
e4e0c7847798390820c73cdfa0d525f2a03c875c67c8358a75ab55e7aac419fc | ardumont/vinyasa | project.clj | (defproject im.chit/vinyasa "0.2.0"
:description "Utilities to make the development process smoother"
:url ""
:license {:name "The MIT License"
:url ""}
:dependencies [[org.clojure/clojure "1.5.1"]
[com.cemerick/pomegranate "0.3.0"]]
:profiles {:dev {:plugins [[lein-repack "0.1.0"]]}}) | null | https://raw.githubusercontent.com/ardumont/vinyasa/59726febd52f8de792963ea6e61f0522cb3d7404/project.clj | clojure | (defproject im.chit/vinyasa "0.2.0"
:description "Utilities to make the development process smoother"
:url ""
:license {:name "The MIT License"
:url ""}
:dependencies [[org.clojure/clojure "1.5.1"]
[com.cemerick/pomegranate "0.3.0"]]
:profiles {:dev {:plugins [[lein-repack "0.1.0"]]}}) | |
2b14d8f4e79f1758ae1d72528760502be5d58f9a97ef79d04e5d8d88bbc8c389 | HealthSamurai/dojo.clj | storage.cljs | (ns zframes.storage
(:require [re-frame.core :as rf]))
(defn keywordize [x]
(js->clj x :keywordize-keys true))
(defn remove-item
[key]
(.removeItem (.-localStorage js/window) key))
(defn set-item
[key val]
(->> val
clj->js
(.stringify js/JSON)
js/encodeURIComponent
(.setItem (.-localStorage js/window) (name key))))
(defn get-item
[key]
(try (->> key
name
(.getItem (.-localStorage js/window))
js/decodeURIComponent
(.parse js/JSON)
(keywordize))
(catch js/Object e (do (remove-item key) nil))))
(rf/reg-cofx
:storage/get
(fn [coeffects keys]
(reduce (fn [coef k]
(assoc-in coef [:storage k] (get-item k)))
coeffects keys)))
(rf/reg-fx
:storage/set
(fn [items]
(doseq [[k v] items]
(set-item k v))))
(rf/reg-fx
:storage/remove
(fn [keys]
(doseq [k keys]
(remove-item (name k)))))
| null | https://raw.githubusercontent.com/HealthSamurai/dojo.clj/94922640f534897ab2b181c608b54bfbb8351d7b/ui/src/zframes/storage.cljs | clojure | (ns zframes.storage
(:require [re-frame.core :as rf]))
(defn keywordize [x]
(js->clj x :keywordize-keys true))
(defn remove-item
[key]
(.removeItem (.-localStorage js/window) key))
(defn set-item
[key val]
(->> val
clj->js
(.stringify js/JSON)
js/encodeURIComponent
(.setItem (.-localStorage js/window) (name key))))
(defn get-item
[key]
(try (->> key
name
(.getItem (.-localStorage js/window))
js/decodeURIComponent
(.parse js/JSON)
(keywordize))
(catch js/Object e (do (remove-item key) nil))))
(rf/reg-cofx
:storage/get
(fn [coeffects keys]
(reduce (fn [coef k]
(assoc-in coef [:storage k] (get-item k)))
coeffects keys)))
(rf/reg-fx
:storage/set
(fn [items]
(doseq [[k v] items]
(set-item k v))))
(rf/reg-fx
:storage/remove
(fn [keys]
(doseq [k keys]
(remove-item (name k)))))
| |
2aa2f7bd43e73b58c969a0418d017a941bdc1bb93bfd8d3a4fe832de0698c72c | ronxin/stolzen | ex2.73.scm | #lang scheme
(require racket/trace)
(define (variable? e)
(symbol? e)
)
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2))
)
(define (=number? exp num)
(and (number? exp) (= exp num))
)
(define (operator exp)
(car exp)
)
(define (operands exp)
(cdr exp)
)
(define (deriv exp var)
(cond
((number? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0))
(else
((get 'deriv (operator exp)) (operands exp) var))
)
)
(define (put op type item)
true
)
; a
; because number won't contain a type-tag
; same is with same-variable?
; b
(define (make-sum addend augend)
(cond
((=number? addend 0) augend)
((=number? augend 0) addend)
((and (number? addend) (number? augend)) (+ addend augend))
(else
(list '+ addend augend))
)
)
(define (make-product m1 m2)
(cond
((or (=number? m1 0) (=number? m2 0)) 0)
((=number? m1 1) m2)
((=number? m2 1) m1)
((and (number? m1) (number? m2)) (* m1 m2))
(else
(list '* m1 m2))
)
)
(define (add-plus-mult-package)
(define (addend e)
(car e)
)
(define (augend e)
(cadr e)
)
(define (make-sum-deriv operands var)
(make-sum (deriv (addend operands) var)
(deriv (augend operands) var))
)
(put 'deriv '+ make-sum-deriv)
(define (multiplier e)
(car e)
)
(define (multiplicand e)
(cadr e)
)
(define (make-product-deriv operands var)
(make-sum
(make-product (multiplier operands)
(deriv (multiplicand operands) var))
(make-product (deriv (multiplier operands) var)
(multiplicand operands))
)
)
(put 'deriv '* make-product-deriv)
; for checking
(define (get-plus-mult op type)
(if (eq? op 'deriv)
(cond
((eq? type '+) make-sum-deriv)
((eq? type '*) make-product-deriv)
(else false)
)
false
)
)
get-plus-mult
)
; c
(define (add-exp-package)
(define (base e)
(car e)
)
(define (exponent e)
(cadr e)
)
(define (make-exponentiation base exponent)
(cond
((=number? exponent 0) 1)
((=number? exponent 1) base)
((and (number? base) (number? exponent)) (exp base exponent))
(else
(list 'exp base exponent))
)
)
(define (exponent-deriv operands var)
(make-product
(exponent operands)
(make-product
(make-exponentiation (base operands) (- (exponent operands) 1))
(deriv (base operands) var)
)
)
)
; for checking
(define (get-exp op type)
(if (and (eq? op 'deriv) (eq? type 'exp))
exponent-deriv
false
)
)
get-exp
)
; d
; if change to ((get (operator exp) 'deriv) (operands) var), then you'll have to
; change only the get procedure
; get for testing
(define packages (list (add-plus-mult-package) (add-exp-package)))
(define (get op type)
(define (get-inner gets-list)
(if (null? gets-list)
false
(let
((res ((car gets-list) op type)))
(if res
res
(get-inner (cdr gets-list))
)
)
)
)
(get-inner packages)
)
(get 'deriv '+)
(get 'deriv '*)
(get 'deriv 'exp)
(= 2 (deriv '(+ x x) 'x))
(= 1 (deriv '(+ x 3) 'x))
(= 1 (deriv '(+ x y) 'x))
(= 1 (deriv '(+ x y) 'y))
(eq? 'y (deriv '(* x y) 'x))
(equal? '(* 2 x) (deriv '(exp x 2) 'x))
| null | https://raw.githubusercontent.com/ronxin/stolzen/bb13d0a7deea53b65253bb4b61aaf2abe4467f0d/sicp/chapter2/2.4/ex2.73.scm | scheme | a
because number won't contain a type-tag
same is with same-variable?
b
for checking
c
for checking
d
if change to ((get (operator exp) 'deriv) (operands) var), then you'll have to
change only the get procedure
get for testing
| #lang scheme
(require racket/trace)
(define (variable? e)
(symbol? e)
)
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2))
)
(define (=number? exp num)
(and (number? exp) (= exp num))
)
(define (operator exp)
(car exp)
)
(define (operands exp)
(cdr exp)
)
(define (deriv exp var)
(cond
((number? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0))
(else
((get 'deriv (operator exp)) (operands exp) var))
)
)
(define (put op type item)
true
)
(define (make-sum addend augend)
(cond
((=number? addend 0) augend)
((=number? augend 0) addend)
((and (number? addend) (number? augend)) (+ addend augend))
(else
(list '+ addend augend))
)
)
(define (make-product m1 m2)
(cond
((or (=number? m1 0) (=number? m2 0)) 0)
((=number? m1 1) m2)
((=number? m2 1) m1)
((and (number? m1) (number? m2)) (* m1 m2))
(else
(list '* m1 m2))
)
)
(define (add-plus-mult-package)
(define (addend e)
(car e)
)
(define (augend e)
(cadr e)
)
(define (make-sum-deriv operands var)
(make-sum (deriv (addend operands) var)
(deriv (augend operands) var))
)
(put 'deriv '+ make-sum-deriv)
(define (multiplier e)
(car e)
)
(define (multiplicand e)
(cadr e)
)
(define (make-product-deriv operands var)
(make-sum
(make-product (multiplier operands)
(deriv (multiplicand operands) var))
(make-product (deriv (multiplier operands) var)
(multiplicand operands))
)
)
(put 'deriv '* make-product-deriv)
(define (get-plus-mult op type)
(if (eq? op 'deriv)
(cond
((eq? type '+) make-sum-deriv)
((eq? type '*) make-product-deriv)
(else false)
)
false
)
)
get-plus-mult
)
(define (add-exp-package)
(define (base e)
(car e)
)
(define (exponent e)
(cadr e)
)
(define (make-exponentiation base exponent)
(cond
((=number? exponent 0) 1)
((=number? exponent 1) base)
((and (number? base) (number? exponent)) (exp base exponent))
(else
(list 'exp base exponent))
)
)
(define (exponent-deriv operands var)
(make-product
(exponent operands)
(make-product
(make-exponentiation (base operands) (- (exponent operands) 1))
(deriv (base operands) var)
)
)
)
(define (get-exp op type)
(if (and (eq? op 'deriv) (eq? type 'exp))
exponent-deriv
false
)
)
get-exp
)
(define packages (list (add-plus-mult-package) (add-exp-package)))
(define (get op type)
(define (get-inner gets-list)
(if (null? gets-list)
false
(let
((res ((car gets-list) op type)))
(if res
res
(get-inner (cdr gets-list))
)
)
)
)
(get-inner packages)
)
(get 'deriv '+)
(get 'deriv '*)
(get 'deriv 'exp)
(= 2 (deriv '(+ x x) 'x))
(= 1 (deriv '(+ x 3) 'x))
(= 1 (deriv '(+ x y) 'x))
(= 1 (deriv '(+ x y) 'y))
(eq? 'y (deriv '(* x y) 'x))
(equal? '(* 2 x) (deriv '(exp x 2) 'x))
|
119166e7f95d5b6c45d085d62bcc267dc679c739d8fcb073d572fe033881344c | gojek/ziggurat | error_test.clj | (ns ziggurat.util.error-test
(:require [clojure.test :refer :all]
[sentry-clj.async :refer [sentry-report]]
[ziggurat.new-relic :as nr]
[ziggurat.util.error :refer [report-error]]))
(deftest report-error-test
(testing "error gets reported to sentry and new-relic"
(let [sentry-report-called? (atom false)
newrelic-report-error-called? (atom false)]
(with-redefs [nr/report-error (fn [_ _] (reset! newrelic-report-error-called? true))]
(report-error (Exception. "Error") "error")
(is (= false @sentry-report-called?))
(is @newrelic-report-error-called?)))))
| null | https://raw.githubusercontent.com/gojek/ziggurat/7ac8072917aa67cd10b25e940a01bc196d7d8c98/test/ziggurat/util/error_test.clj | clojure | (ns ziggurat.util.error-test
(:require [clojure.test :refer :all]
[sentry-clj.async :refer [sentry-report]]
[ziggurat.new-relic :as nr]
[ziggurat.util.error :refer [report-error]]))
(deftest report-error-test
(testing "error gets reported to sentry and new-relic"
(let [sentry-report-called? (atom false)
newrelic-report-error-called? (atom false)]
(with-redefs [nr/report-error (fn [_ _] (reset! newrelic-report-error-called? true))]
(report-error (Exception. "Error") "error")
(is (= false @sentry-report-called?))
(is @newrelic-report-error-called?)))))
| |
92e8e30ef9aac93115d1af75c81bde430d75943a59bb21ece147a5db67e783b4 | janestreet/core_kernel | enumeration.ml | open! Core
open! Import
type ('a, 'b) t = { all : 'a list }
module type S =
Enumeration_intf.S with type ('a, 'witness) enumeration := ('a, 'witness) t
module type S_fc =
Enumeration_intf.S_fc with type ('a, 'witness) enumeration := ('a, 'witness) t
module Make (T : sig
type t [@@deriving enumerate]
end) =
struct
type enumeration_witness
let enumeration = T.{ all }
end
let make (type t) ~all =
(module struct
type enumerable_t = t
type enumeration_witness
let enumeration = { all }
end : S_fc
with type enumerable_t = t)
;;
| null | https://raw.githubusercontent.com/janestreet/core_kernel/18b2a732657ecac73e075e81e1edd0ef797fcc7d/total_map/src/enumeration.ml | ocaml | open! Core
open! Import
type ('a, 'b) t = { all : 'a list }
module type S =
Enumeration_intf.S with type ('a, 'witness) enumeration := ('a, 'witness) t
module type S_fc =
Enumeration_intf.S_fc with type ('a, 'witness) enumeration := ('a, 'witness) t
module Make (T : sig
type t [@@deriving enumerate]
end) =
struct
type enumeration_witness
let enumeration = T.{ all }
end
let make (type t) ~all =
(module struct
type enumerable_t = t
type enumeration_witness
let enumeration = { all }
end : S_fc
with type enumerable_t = t)
;;
| |
954c9728b7d8480d81caab5c67f2d0cfffadfe3353631856df37352ab1a38d9b | mbutterick/aoc-racket | day12.rkt | #lang scribble/lp2
@(require scribble/manual aoc-racket/helper)
@aoc-title[12]
@defmodule[aoc-racket/day12]
@link[""]{The puzzle}. Our @link-rp["day12-input.txt"]{input} is, unfortunately, a @link["/"]{JSON} file.
@chunk[<day12>
<day12-setup>
<day12-q1>
<day12-q2>
<day12-test>]
@isection{What's the sum of all the numbers in the document?}
I've never liked JavaScript, and spending more time with Racket has only deepened my antipathy. So I apologize if this solution is terse.
We need to parse the JSON file, extract the numbers, and add them.
To parse the file we'll use the @iracket[read-json] function from Racket's @racketmodname[json] library. This function converts the JSON into a JS-expression (see @iracket[jsexpr?]), which is a recursively nested data structure. If we had a simple recursively nested list, we could just @iracket[flatten] it and filter for the numbers. We'll do something similar here — recursively flatten the JS-expression and pull out the numbers.
If you're new to Racket, notice the @italic{recursive descent} pattern used in @racket[flatten-jsexpr] — it's a very common way of handling recursively structured data.
@chunk[<day12-setup>
(require racket rackunit json)
(provide (all-defined-out))
(define (string->jsexpr str)
(read-json (open-input-string str)))
]
@chunk[<day12-q1>
(define (flatten-jsexpr jsexpr)
(flatten
(let loop ([x jsexpr])
(cond
[(list? x)
(map loop x)]
[(hash? x)
(loop (flatten (hash->list x)))]
[else x]))))
(define (q1 input-str)
(define json-items (flatten-jsexpr (string->jsexpr input-str)))
(apply + (filter number? json-items)))]
@section{What's the sum of all the numbers, if hash tables with value @racket{red} are ignored?}
We'll just update our flattening function to skip over hash tables that have @racket{red} among the values.
@chunk[<day12-q2>
(define (flatten-jsexpr-2 jsexpr)
(flatten
(let loop ([x jsexpr])
(cond
[(list? x)
(map loop x)]
[(hash? x)
(if (member "red" (hash-values x))
empty
(loop (flatten (hash->list x))))]
[else x]))))
(define (q2 input-str)
(define json-items (flatten-jsexpr-2 (string->jsexpr input-str)))
(apply + (filter number? json-items))) ]
@section{Testing Day 12}
@chunk[<day12-test>
(module+ test
(define input-str (file->string "day12-input.txt"))
(check-equal? (q1 input-str) 191164)
(check-equal? (q2 input-str) 87842))]
| null | https://raw.githubusercontent.com/mbutterick/aoc-racket/2c6cb2f3ad876a91a82f33ce12844f7758b969d6/day12.rkt | racket | #lang scribble/lp2
@(require scribble/manual aoc-racket/helper)
@aoc-title[12]
@defmodule[aoc-racket/day12]
@link[""]{The puzzle}. Our @link-rp["day12-input.txt"]{input} is, unfortunately, a @link["/"]{JSON} file.
@chunk[<day12>
<day12-setup>
<day12-q1>
<day12-q2>
<day12-test>]
@isection{What's the sum of all the numbers in the document?}
I've never liked JavaScript, and spending more time with Racket has only deepened my antipathy. So I apologize if this solution is terse.
We need to parse the JSON file, extract the numbers, and add them.
To parse the file we'll use the @iracket[read-json] function from Racket's @racketmodname[json] library. This function converts the JSON into a JS-expression (see @iracket[jsexpr?]), which is a recursively nested data structure. If we had a simple recursively nested list, we could just @iracket[flatten] it and filter for the numbers. We'll do something similar here — recursively flatten the JS-expression and pull out the numbers.
If you're new to Racket, notice the @italic{recursive descent} pattern used in @racket[flatten-jsexpr] — it's a very common way of handling recursively structured data.
@chunk[<day12-setup>
(require racket rackunit json)
(provide (all-defined-out))
(define (string->jsexpr str)
(read-json (open-input-string str)))
]
@chunk[<day12-q1>
(define (flatten-jsexpr jsexpr)
(flatten
(let loop ([x jsexpr])
(cond
[(list? x)
(map loop x)]
[(hash? x)
(loop (flatten (hash->list x)))]
[else x]))))
(define (q1 input-str)
(define json-items (flatten-jsexpr (string->jsexpr input-str)))
(apply + (filter number? json-items)))]
@section{What's the sum of all the numbers, if hash tables with value @racket{red} are ignored?}
We'll just update our flattening function to skip over hash tables that have @racket{red} among the values.
@chunk[<day12-q2>
(define (flatten-jsexpr-2 jsexpr)
(flatten
(let loop ([x jsexpr])
(cond
[(list? x)
(map loop x)]
[(hash? x)
(if (member "red" (hash-values x))
empty
(loop (flatten (hash->list x))))]
[else x]))))
(define (q2 input-str)
(define json-items (flatten-jsexpr-2 (string->jsexpr input-str)))
(apply + (filter number? json-items))) ]
@section{Testing Day 12}
@chunk[<day12-test>
(module+ test
(define input-str (file->string "day12-input.txt"))
(check-equal? (q1 input-str) 191164)
(check-equal? (q2 input-str) 87842))]
| |
05ab60f7c86a1bc574f1a5e8951c68ca389a043649d994a98713ffc47d9f70f0 | kmi/irs | load.lisp | Copyright © 2008 The Open University
File created in GNU Emacs
(in-package #:ocml)
(def-ontology math-ontology
"Goals and services for simple mathematics."
:includes (http-grounding mime rfc2616 wsmo)
:type :goal
:namespace-uri "-ontology#"
:namespaces (("math" math-ontology)
("hg" http-grounding)
("mime" mime)
("rfc2616" rfc2616))
:author "dave" :allowed-editors ("dave" "john")
:files ("maths"))
| null | https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/apps/math/ontologies/math-ontology/load.lisp | lisp | Copyright © 2008 The Open University
File created in GNU Emacs
(in-package #:ocml)
(def-ontology math-ontology
"Goals and services for simple mathematics."
:includes (http-grounding mime rfc2616 wsmo)
:type :goal
:namespace-uri "-ontology#"
:namespaces (("math" math-ontology)
("hg" http-grounding)
("mime" mime)
("rfc2616" rfc2616))
:author "dave" :allowed-editors ("dave" "john")
:files ("maths"))
| |
10c4a9324330625460b7f4f66985a36cfa82bfad1c1763cd98300e9cf3603f5f | mfp/obigstore | obs_replication.ml |
* Copyright ( C ) 2011 < >
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* Copyright (C) 2011 Mauricio Fernandez <>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
(** Replication. *)
module type REPLICATION_COMMON =
sig
type db
type raw_dump
type update
end
module type REPLICATION_CLIENT =
sig
include REPLICATION_COMMON
val update_of_string : string -> int -> int -> update option
val apply_update : db -> update -> unit Lwt.t
end
module type REPLICATION_SERVER =
sig
include REPLICATION_COMMON
type update_stream
val get_update_stream : raw_dump -> update_stream Lwt.t
val get_update : update_stream -> update option Lwt.t
val get_updates : update_stream -> update Lwt_stream.t
val ack_update : update -> unit Lwt.t
val nack_update : update -> unit Lwt.t
val is_sync_update : update -> bool Lwt.t
val get_update_data : update -> (string * int * int) Lwt.t
end
| null | https://raw.githubusercontent.com/mfp/obigstore/1b078eeb21e11c8de986717150c7108a94778095/src/core/obs_replication.ml | ocaml | * Replication. |
* Copyright ( C ) 2011 < >
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* Copyright (C) 2011 Mauricio Fernandez <>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
module type REPLICATION_COMMON =
sig
type db
type raw_dump
type update
end
module type REPLICATION_CLIENT =
sig
include REPLICATION_COMMON
val update_of_string : string -> int -> int -> update option
val apply_update : db -> update -> unit Lwt.t
end
module type REPLICATION_SERVER =
sig
include REPLICATION_COMMON
type update_stream
val get_update_stream : raw_dump -> update_stream Lwt.t
val get_update : update_stream -> update option Lwt.t
val get_updates : update_stream -> update Lwt_stream.t
val ack_update : update -> unit Lwt.t
val nack_update : update -> unit Lwt.t
val is_sync_update : update -> bool Lwt.t
val get_update_data : update -> (string * int * int) Lwt.t
end
|
7cbb8f73eadfc2d681ea60e553d1c78e013325915e857292f680298db52c3cc6 | rtoy/ansi-cl-tests | format-justify.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sun Aug 22 18:09:49 2004
;;;; Contains: Tests of the ~< ~> directive
(in-package :cl-test)
(compile-and-load "printer-aux.lsp")
(def-pprint-test format.justify.1
(format nil "~<~>")
"")
(def-pprint-test format.justify.2
(loop for i from 1 to 20
for s1 = (make-string i :initial-element #\x)
for s2 = (format nil "~<~A~>" s1)
unless (string= s1 s2)
collect (list i s1 s2))
nil)
(def-pprint-test format.justify.3
(loop for i from 1 to 20
for s1 = (make-string i :initial-element #\x)
for s2 = (format nil "~<~A~;~A~>" s1 s1)
unless (string= s2 (concatenate 'string s1 s1))
collect (list i s1 s2))
nil)
(def-pprint-test format.justify.4
(loop for i from 1 to 20
for s1 = (make-string i :initial-element #\x)
for expected = (concatenate 'string s1 " " s1)
for s2 = (format nil "~,,1<~A~;~A~>" s1 s1)
unless (string= s2 expected)
collect (list i expected s2))
nil)
(def-pprint-test format.justify.5
(loop for i from 1 to 20
for s1 = (make-string i :initial-element #\x)
for expected = (concatenate 'string s1 "," s1)
for s2 = (format nil "~,,1,',<~A~;~A~>" s1 s1)
unless (string= s2 expected)
collect (list i expected s2))
nil)
(def-pprint-test format.justify.6
(loop for i from 1 to 20
for s1 = (make-string i :initial-element #\x)
for expected = (concatenate 'string s1 " " s1)
for s2 = (format nil "~,,2<~A~;~A~>" s1 s1)
unless (string= s2 expected)
collect (list i expected s2))
nil)
(def-pprint-test format.justify.7
(loop for mincol = (random 50)
for len = (random 50)
for s1 = (make-string len :initial-element #\x)
for s2 = (format nil "~v<~A~>" mincol s1)
for expected = (if (< len mincol)
(concatenate 'string
(make-string (- mincol len) :initial-element #\Space)
s1)
s1)
repeat 100
unless (string= s2 expected)
collect (list mincol len s1 s2 expected))
nil)
(def-pprint-test format.justify.8
(loop for mincol = (random 50)
for minpad = (random 10)
for len = (random 50)
for s1 = (make-string len :initial-element #\x)
for s2 = (format nil "~v,,v<~A~>" mincol minpad s1)
for expected = (if (< len mincol)
(concatenate 'string
(make-string (- mincol len) :initial-element #\Space)
s1)
s1)
repeat 100
unless (string= s2 expected)
collect (list mincol minpad len s1 s2 expected))
nil)
(def-pprint-test format.justify.9
(loop for mincol = (random 50)
for padchar = (random-from-seq +standard-chars+)
for len = (random 50)
for s1 = (make-string len :initial-element #\x)
for s2 = (format nil "~v,,,v<~A~>" mincol padchar s1)
for expected = (if (< len mincol)
(concatenate 'string
(make-string (- mincol len) :initial-element padchar)
s1)
s1)
repeat 100
unless (string= s2 expected)
collect (list mincol padchar len s1 s2 expected))
nil)
(def-pprint-test format.justify.10
(loop for mincol = (random 50)
for padchar = (random-from-seq +standard-chars+)
for len = (random 50)
for s1 = (make-string len :initial-element #\x)
for s2 = (format nil (format nil "~~~d,,,'~c<~~A~~>" mincol padchar) s1)
for expected = (if (< len mincol)
(concatenate 'string
(make-string (- mincol len) :initial-element padchar)
s1)
s1)
repeat 500
unless (string= s2 expected)
collect (list mincol padchar len s1 s2 expected))
nil)
(def-pprint-test format.justify.11
(loop for i = (1+ (random 20))
for colinc = (1+ (random 10))
for s1 = (make-string i :initial-element #\x)
for s2 = (format nil "~,v<~A~>" colinc s1)
for expected-len = (* colinc (ceiling i colinc))
for expected = (concatenate 'string
(make-string (- expected-len i) :initial-element #\Space)
s1)
repeat 10
unless (string= expected s2)
collect (list i colinc expected s2))
nil)
(def-pprint-test format.justify.12
(format nil "~<XXXXXX~^~>")
"")
(def-pprint-test format.justify.13
(format nil "~<XXXXXX~;YYYYYYY~^~>")
"XXXXXX")
(def-pprint-test format.justify.13a
(format nil "~<~<XXXXXX~;YYYYYYY~^~>~>")
"XXXXXX")
(def-pprint-test format.justify.14
(format nil "~<XXXXXX~;YYYYYYY~^~;ZZZZZ~>")
"XXXXXX")
(def-pprint-test format.justify.15
(format nil "~13,,2<aaa~;bbb~;ccc~>")
"aaa bbb ccc")
(def-pprint-test format.justify.16
(format nil "~10@<abcdef~>")
"abcdef ")
(def-pprint-test format.justify.17
(format nil "~10:@<abcdef~>")
" abcdef ")
(def-pprint-test format.justify.18
(format nil "~10:<abcdef~>")
" abcdef")
(def-pprint-test format.justify.19
(format nil "~4@<~>")
" ")
(def-pprint-test format.justify.20
(format nil "~5:@<~>")
" ")
(def-pprint-test format.justify.21
(format nil "~6:<~>")
" ")
(def-pprint-test format.justify.22
(format nil "~v<~A~>" nil "XYZ")
"XYZ")
(def-pprint-test format.justify.23
(format nil "~,v<~A~;~A~>" nil "ABC" "DEF")
"ABCDEF")
(def-pprint-test format.justify.24
(format nil "~,,v<~A~;~A~>" nil "ABC" "DEF")
"ABCDEF")
(def-pprint-test format.justify.25
(format nil "~,,1,v<~A~;~A~>" nil "ABC" "DEF")
"ABC DEF")
(def-pprint-test format.justify.26
(format nil "~,,1,v<~A~;~A~>" #\, "ABC" "DEF")
"ABC,DEF")
(def-pprint-test format.justify.27
(format nil "~6<abc~;def~^~>")
" abc")
(def-pprint-test format.justify.28
(format nil "~6@<abc~;def~^~>")
"abc ")
;;; ~:; tests
(def-pprint-test format.justify.29
(format nil "~%X ~,,1<~%X ~:;AAA~;BBB~;CCC~>")
"
X AAA BBB CCC")
(def-pprint-test format.justify.30
(format nil "~%X ~<~%X ~0,3:;AAA~>~<~%X ~0,3:;BBB~>~<~%X ~0,3:;CCC~>")
"
X
X AAA
X BBB
X CCC")
(def-pprint-test format.justify.31
(format nil "~%X ~<~%X ~0,30:;AAA~>~<~%X ~0,30:;BBB~>~<~%X ~0,30:;CCC~>")
"
X AAABBBCCC")
(def-pprint-test format.justify.32
(format nil "~%X ~<~%X ~0,3:;AAA~>,~<~%X ~0,3:;BBB~>,~<~%X ~0,3:;CCC~>")
"
X
X AAA,
X BBB,
X CCC")
;;; Error cases
See 22.3.5.2
;;; Interaction with ~W
(deftest format.justify.error.w.1
(signals-error-always (format nil "~< ~W ~>" nil) error)
t t)
(deftest format.justify.error.w.2
(signals-error-always (format nil "~<X~:;Y~>~W" nil) error)
t t)
(deftest format.justify.error.w.3
(signals-error-always (format nil "~w~<X~:;Y~>" nil) error)
t t)
;;; Interaction with ~_
(deftest format.justify.error._.1
(signals-error-always (format nil "~< ~_ ~>") error)
t t)
(deftest format.justify.error._.2
(signals-error-always (format nil "~<X~:;Y~>~_") error)
t t)
(deftest format.justify.error._.3
(signals-error-always (format nil "~_~<X~:;Y~>") error)
t t)
;;; Interaction with ~I
(deftest format.justify.error.i.1
(signals-error-always (format nil "~< ~i ~>") error)
t t)
(deftest format.justify.error.i.2
(signals-error-always (format nil "~<X~:;Y~>~I") error)
t t)
(deftest format.justify.error.i.3
(signals-error-always (format nil "~i~<X~:;Y~>") error)
t t)
| null | https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/format-justify.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests of the ~< ~> directive
~:; tests
Error cases
Interaction with ~W
Interaction with ~_
Interaction with ~I | Author :
Created : Sun Aug 22 18:09:49 2004
(in-package :cl-test)
(compile-and-load "printer-aux.lsp")
(def-pprint-test format.justify.1
(format nil "~<~>")
"")
(def-pprint-test format.justify.2
(loop for i from 1 to 20
for s1 = (make-string i :initial-element #\x)
for s2 = (format nil "~<~A~>" s1)
unless (string= s1 s2)
collect (list i s1 s2))
nil)
(def-pprint-test format.justify.3
(loop for i from 1 to 20
for s1 = (make-string i :initial-element #\x)
for s2 = (format nil "~<~A~;~A~>" s1 s1)
unless (string= s2 (concatenate 'string s1 s1))
collect (list i s1 s2))
nil)
(def-pprint-test format.justify.4
(loop for i from 1 to 20
for s1 = (make-string i :initial-element #\x)
for expected = (concatenate 'string s1 " " s1)
for s2 = (format nil "~,,1<~A~;~A~>" s1 s1)
unless (string= s2 expected)
collect (list i expected s2))
nil)
(def-pprint-test format.justify.5
(loop for i from 1 to 20
for s1 = (make-string i :initial-element #\x)
for expected = (concatenate 'string s1 "," s1)
for s2 = (format nil "~,,1,',<~A~;~A~>" s1 s1)
unless (string= s2 expected)
collect (list i expected s2))
nil)
(def-pprint-test format.justify.6
(loop for i from 1 to 20
for s1 = (make-string i :initial-element #\x)
for expected = (concatenate 'string s1 " " s1)
for s2 = (format nil "~,,2<~A~;~A~>" s1 s1)
unless (string= s2 expected)
collect (list i expected s2))
nil)
(def-pprint-test format.justify.7
(loop for mincol = (random 50)
for len = (random 50)
for s1 = (make-string len :initial-element #\x)
for s2 = (format nil "~v<~A~>" mincol s1)
for expected = (if (< len mincol)
(concatenate 'string
(make-string (- mincol len) :initial-element #\Space)
s1)
s1)
repeat 100
unless (string= s2 expected)
collect (list mincol len s1 s2 expected))
nil)
(def-pprint-test format.justify.8
(loop for mincol = (random 50)
for minpad = (random 10)
for len = (random 50)
for s1 = (make-string len :initial-element #\x)
for s2 = (format nil "~v,,v<~A~>" mincol minpad s1)
for expected = (if (< len mincol)
(concatenate 'string
(make-string (- mincol len) :initial-element #\Space)
s1)
s1)
repeat 100
unless (string= s2 expected)
collect (list mincol minpad len s1 s2 expected))
nil)
(def-pprint-test format.justify.9
(loop for mincol = (random 50)
for padchar = (random-from-seq +standard-chars+)
for len = (random 50)
for s1 = (make-string len :initial-element #\x)
for s2 = (format nil "~v,,,v<~A~>" mincol padchar s1)
for expected = (if (< len mincol)
(concatenate 'string
(make-string (- mincol len) :initial-element padchar)
s1)
s1)
repeat 100
unless (string= s2 expected)
collect (list mincol padchar len s1 s2 expected))
nil)
(def-pprint-test format.justify.10
(loop for mincol = (random 50)
for padchar = (random-from-seq +standard-chars+)
for len = (random 50)
for s1 = (make-string len :initial-element #\x)
for s2 = (format nil (format nil "~~~d,,,'~c<~~A~~>" mincol padchar) s1)
for expected = (if (< len mincol)
(concatenate 'string
(make-string (- mincol len) :initial-element padchar)
s1)
s1)
repeat 500
unless (string= s2 expected)
collect (list mincol padchar len s1 s2 expected))
nil)
(def-pprint-test format.justify.11
(loop for i = (1+ (random 20))
for colinc = (1+ (random 10))
for s1 = (make-string i :initial-element #\x)
for s2 = (format nil "~,v<~A~>" colinc s1)
for expected-len = (* colinc (ceiling i colinc))
for expected = (concatenate 'string
(make-string (- expected-len i) :initial-element #\Space)
s1)
repeat 10
unless (string= expected s2)
collect (list i colinc expected s2))
nil)
(def-pprint-test format.justify.12
(format nil "~<XXXXXX~^~>")
"")
(def-pprint-test format.justify.13
(format nil "~<XXXXXX~;YYYYYYY~^~>")
"XXXXXX")
(def-pprint-test format.justify.13a
(format nil "~<~<XXXXXX~;YYYYYYY~^~>~>")
"XXXXXX")
(def-pprint-test format.justify.14
(format nil "~<XXXXXX~;YYYYYYY~^~;ZZZZZ~>")
"XXXXXX")
(def-pprint-test format.justify.15
(format nil "~13,,2<aaa~;bbb~;ccc~>")
"aaa bbb ccc")
(def-pprint-test format.justify.16
(format nil "~10@<abcdef~>")
"abcdef ")
(def-pprint-test format.justify.17
(format nil "~10:@<abcdef~>")
" abcdef ")
(def-pprint-test format.justify.18
(format nil "~10:<abcdef~>")
" abcdef")
(def-pprint-test format.justify.19
(format nil "~4@<~>")
" ")
(def-pprint-test format.justify.20
(format nil "~5:@<~>")
" ")
(def-pprint-test format.justify.21
(format nil "~6:<~>")
" ")
(def-pprint-test format.justify.22
(format nil "~v<~A~>" nil "XYZ")
"XYZ")
(def-pprint-test format.justify.23
(format nil "~,v<~A~;~A~>" nil "ABC" "DEF")
"ABCDEF")
(def-pprint-test format.justify.24
(format nil "~,,v<~A~;~A~>" nil "ABC" "DEF")
"ABCDEF")
(def-pprint-test format.justify.25
(format nil "~,,1,v<~A~;~A~>" nil "ABC" "DEF")
"ABC DEF")
(def-pprint-test format.justify.26
(format nil "~,,1,v<~A~;~A~>" #\, "ABC" "DEF")
"ABC,DEF")
(def-pprint-test format.justify.27
(format nil "~6<abc~;def~^~>")
" abc")
(def-pprint-test format.justify.28
(format nil "~6@<abc~;def~^~>")
"abc ")
(def-pprint-test format.justify.29
(format nil "~%X ~,,1<~%X ~:;AAA~;BBB~;CCC~>")
"
X AAA BBB CCC")
(def-pprint-test format.justify.30
(format nil "~%X ~<~%X ~0,3:;AAA~>~<~%X ~0,3:;BBB~>~<~%X ~0,3:;CCC~>")
"
X
X AAA
X BBB
X CCC")
(def-pprint-test format.justify.31
(format nil "~%X ~<~%X ~0,30:;AAA~>~<~%X ~0,30:;BBB~>~<~%X ~0,30:;CCC~>")
"
X AAABBBCCC")
(def-pprint-test format.justify.32
(format nil "~%X ~<~%X ~0,3:;AAA~>,~<~%X ~0,3:;BBB~>,~<~%X ~0,3:;CCC~>")
"
X
X AAA,
X BBB,
X CCC")
See 22.3.5.2
(deftest format.justify.error.w.1
(signals-error-always (format nil "~< ~W ~>" nil) error)
t t)
(deftest format.justify.error.w.2
(signals-error-always (format nil "~<X~:;Y~>~W" nil) error)
t t)
(deftest format.justify.error.w.3
(signals-error-always (format nil "~w~<X~:;Y~>" nil) error)
t t)
(deftest format.justify.error._.1
(signals-error-always (format nil "~< ~_ ~>") error)
t t)
(deftest format.justify.error._.2
(signals-error-always (format nil "~<X~:;Y~>~_") error)
t t)
(deftest format.justify.error._.3
(signals-error-always (format nil "~_~<X~:;Y~>") error)
t t)
(deftest format.justify.error.i.1
(signals-error-always (format nil "~< ~i ~>") error)
t t)
(deftest format.justify.error.i.2
(signals-error-always (format nil "~<X~:;Y~>~I") error)
t t)
(deftest format.justify.error.i.3
(signals-error-always (format nil "~i~<X~:;Y~>") error)
t t)
|
40c3d6c010b6e9ac1722445d40c0441a515d7f14863e1ffcd95470db39cf1794 | ivanperez-keera/dunai | Yampa.hs | -- |
Copyright : ( c ) , 2019 - 2022
( c ) and , 2016 - 2018
-- License : BSD3
Maintainer :
module FRP.Yampa (module X, SF, FutureSF) where
-- External imports
import Data.Functor.Identity
-- Internal imports
import FRP.BearRiver as X hiding (SF, andThen)
import qualified FRP.BearRiver as BR
-- | Signal function (conceptually, a function between signals that respects
-- causality).
type SF = BR.SF Identity
-- | Future signal function (conceptually, a function between fugure signals
-- that respects causality).
--
-- A future signal is a signal that is only defined for positive times.
type FutureSF = BR.SF Identity
| null | https://raw.githubusercontent.com/ivanperez-keera/dunai/845a4e0dfe8ac060ee65856f035fda2b8168e5ba/dunai-frp-bearriver/src/FRP/Yampa.hs | haskell | |
License : BSD3
External imports
Internal imports
| Signal function (conceptually, a function between signals that respects
causality).
| Future signal function (conceptually, a function between fugure signals
that respects causality).
A future signal is a signal that is only defined for positive times. | Copyright : ( c ) , 2019 - 2022
( c ) and , 2016 - 2018
Maintainer :
module FRP.Yampa (module X, SF, FutureSF) where
import Data.Functor.Identity
import FRP.BearRiver as X hiding (SF, andThen)
import qualified FRP.BearRiver as BR
type SF = BR.SF Identity
type FutureSF = BR.SF Identity
|
e7c9fcc9530be547da963270f61ac3c86cbbb54534ce6ad544aae04728c28bea | admich/Doors | menu.lisp | (in-package :doors)
;; KLUDGE to call menu-choose with :associated-window the graft although it isn't a pane
(defmethod pane-frame ((pane doors-graft))
*wm-application*)
;;; The doors graft don't call tell-window-manager-about-space-reqiurements
(defmethod note-space-requirements-changed :around ((graft doors-graft) pane)
(declare (ignore graft))
nil)
#|
(menu-choose (managed-frames) :associated-window (graft *wm-application*))
|#
| null | https://raw.githubusercontent.com/admich/Doors/322cd234ee97a281832f1fbac72377bbf3341977/menu.lisp | lisp | KLUDGE to call menu-choose with :associated-window the graft although it isn't a pane
The doors graft don't call tell-window-manager-about-space-reqiurements
(menu-choose (managed-frames) :associated-window (graft *wm-application*))
| (in-package :doors)
(defmethod pane-frame ((pane doors-graft))
*wm-application*)
(defmethod note-space-requirements-changed :around ((graft doors-graft) pane)
(declare (ignore graft))
nil)
|
096a76fdfbeedb4d424ffc0833ee39733475105655aa7804fe0004b5c65c0232 | ekmett/dense | Vector.hs | # language RankNTypes #
{-# language TypeFamilies #-}
# language PatternSynonyms #
# language ViewPatterns #
module Dense.Vector where
import Control.Lens
import qualified Linear.V2 as Linear
import qualified Linear.V3 as Linear
type family Elem (t :: *) :: *
class IsV2 t where
_V2 :: Iso' t (Linear.V2 (Elem t))
pattern V2 :: IsV2 t => Elem t -> Elem t -> t
pattern V2 a b <- (view _V2 -> Linear.V2 a b) where
V2 a b = _V2 # Linear.V2 a b
-- {-# complete V2 #-} -- let me write this damn it.
NB : I ca n't make the { - # complete V2 # - } pragma polymorphic and supply it here
-- and i can't supply it on the data type, because it doesn't involve a constructor for the damn type
-- {-# complete #-} pragmas are completely worthless
class IsV3 t where
_V3 :: Iso' t (Linear.V3 (Elem t))
pattern V3 :: IsV3 t => Elem t -> Elem t -> Elem t -> t
pattern V3 a b c <- (view _V3 -> Linear.V3 a b c) where
V3 a b c = _V3 # Linear.V3 a b c
-- {-# complete V3 #-}
| null | https://raw.githubusercontent.com/ekmett/dense/c1ae5d937a1cd64c55310c253eb1745597a9bb9a/lib/dense-common/Dense/Vector.hs | haskell | # language TypeFamilies #
{-# complete V2 #-} -- let me write this damn it.
and i can't supply it on the data type, because it doesn't involve a constructor for the damn type
{-# complete #-} pragmas are completely worthless
{-# complete V3 #-} | # language RankNTypes #
# language PatternSynonyms #
# language ViewPatterns #
module Dense.Vector where
import Control.Lens
import qualified Linear.V2 as Linear
import qualified Linear.V3 as Linear
type family Elem (t :: *) :: *
class IsV2 t where
_V2 :: Iso' t (Linear.V2 (Elem t))
pattern V2 :: IsV2 t => Elem t -> Elem t -> t
pattern V2 a b <- (view _V2 -> Linear.V2 a b) where
V2 a b = _V2 # Linear.V2 a b
NB : I ca n't make the { - # complete V2 # - } pragma polymorphic and supply it here
class IsV3 t where
_V3 :: Iso' t (Linear.V3 (Elem t))
pattern V3 :: IsV3 t => Elem t -> Elem t -> Elem t -> t
pattern V3 a b c <- (view _V3 -> Linear.V3 a b c) where
V3 a b c = _V3 # Linear.V3 a b c
|
f774fdd7da66026e1135cfd803d0633e6f627219f99746432c0191fa551f2e42 | jean-lopes/dfm-to-json | Main.hs | # LANGUAGE CPP #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
module Main where
import qualified AST
import Control.Monad
import Control.Monad.Except
import Data.Aeson
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString.Lazy as ByteString
import Data.Char hiding (Format)
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import Data.Version
import Options.Applicative.Simple
import Parser
import Pipes
import qualified Pipes.Prelude as Pipes
import System.Directory
import System.FilePath
import Text.ParserCombinators.ReadP
data Layout
= Compact
| Format
deriving Show
data Args = Args
{ layout :: Layout
, target :: FilePath
} deriving Show
baseConfig :: Config
baseConfig = defConfig
{ confCompare = keyOrder
[ "file", "code" , "kind" , "name"
, "type", "index", "properties", "objects"
]
}
newConfig :: Layout -> Config
newConfig Compact = baseConfig { confIndent = Spaces 0 }
newConfig Format = baseConfig { confIndent = Spaces 2 }
version :: String
version = $(simpleVersion $ fst . last $ readP_to_S parseVersion CURRENT_PACKAGE_VERSION)
parseOptions :: IO (Args, ())
parseOptions = simpleOptions version empty
"Converts a Delphi Form File (DFM) to JSON"
( Args
<$> flag Format Compact
( long "compact"
<> short 'c'
<> help "Compact JSON output" )
<*> strArgument
( help "FILE or DIRECTORY for conversion"
<> metavar "PATH") )
empty
isExt :: String -> FilePath -> Bool
isExt ext = (=='.':ext) . map toLower . takeExtension
writeJSON :: ToJSON a => Config -> (FilePath, a) -> IO ()
writeJSON cfg (filePath, obj)
= ByteString.writeFile (filePath -<.> "json")
. encodePretty' cfg
. toJSON
$ obj
readDFM :: FilePath -> IO (FilePath, Text)
readDFM p = do
Text.putStrLn . Text.pack $ "Reading: " ++ p
src <- Text.readFile p
return (p, src)
paths :: FilePath -> Producer FilePath IO ()
paths path = do
isFile <- lift $ doesFileExist path
if isFile
then yield path
else do
ps <- lift $ listDirectory path
mapM_ (paths . (path </>)) ps
return ()
parse :: Pipe (FilePath, Text) (FilePath, AST.Object) IO ()
parse = forever $ do
(path, src) <- await
case parseDFM path src of
Left err -> lift $ Text.putStrLn err
Right ast -> yield (path, ast)
process :: FilePath -> Config -> IO ()
process tgt cfg = do
p <- canonicalizePath tgt
setCurrentDirectory p
runEffect
$ paths p
>-> Pipes.filter (isExt "dfm")
>-> Pipes.map (makeRelative p)
>-> Pipes.mapM readDFM
>-> parse
>-> Pipes.mapM_ (writeJSON cfg)
main :: IO ()
main = do
(args, ()) <- parseOptions
let cfg = newConfig . layout $ args
tgt = target args
if isValid tgt
then process tgt cfg
else putStrLn $ "Invalid path: " ++ tgt
| null | https://raw.githubusercontent.com/jean-lopes/dfm-to-json/8c2e51f3e43267c948d307659db9745129578a96/app/Main.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE CPP #
# LANGUAGE TemplateHaskell #
module Main where
import qualified AST
import Control.Monad
import Control.Monad.Except
import Data.Aeson
import Data.Aeson.Encode.Pretty
import qualified Data.ByteString.Lazy as ByteString
import Data.Char hiding (Format)
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import Data.Version
import Options.Applicative.Simple
import Parser
import Pipes
import qualified Pipes.Prelude as Pipes
import System.Directory
import System.FilePath
import Text.ParserCombinators.ReadP
data Layout
= Compact
| Format
deriving Show
data Args = Args
{ layout :: Layout
, target :: FilePath
} deriving Show
baseConfig :: Config
baseConfig = defConfig
{ confCompare = keyOrder
[ "file", "code" , "kind" , "name"
, "type", "index", "properties", "objects"
]
}
newConfig :: Layout -> Config
newConfig Compact = baseConfig { confIndent = Spaces 0 }
newConfig Format = baseConfig { confIndent = Spaces 2 }
version :: String
version = $(simpleVersion $ fst . last $ readP_to_S parseVersion CURRENT_PACKAGE_VERSION)
parseOptions :: IO (Args, ())
parseOptions = simpleOptions version empty
"Converts a Delphi Form File (DFM) to JSON"
( Args
<$> flag Format Compact
( long "compact"
<> short 'c'
<> help "Compact JSON output" )
<*> strArgument
( help "FILE or DIRECTORY for conversion"
<> metavar "PATH") )
empty
isExt :: String -> FilePath -> Bool
isExt ext = (=='.':ext) . map toLower . takeExtension
writeJSON :: ToJSON a => Config -> (FilePath, a) -> IO ()
writeJSON cfg (filePath, obj)
= ByteString.writeFile (filePath -<.> "json")
. encodePretty' cfg
. toJSON
$ obj
readDFM :: FilePath -> IO (FilePath, Text)
readDFM p = do
Text.putStrLn . Text.pack $ "Reading: " ++ p
src <- Text.readFile p
return (p, src)
paths :: FilePath -> Producer FilePath IO ()
paths path = do
isFile <- lift $ doesFileExist path
if isFile
then yield path
else do
ps <- lift $ listDirectory path
mapM_ (paths . (path </>)) ps
return ()
parse :: Pipe (FilePath, Text) (FilePath, AST.Object) IO ()
parse = forever $ do
(path, src) <- await
case parseDFM path src of
Left err -> lift $ Text.putStrLn err
Right ast -> yield (path, ast)
process :: FilePath -> Config -> IO ()
process tgt cfg = do
p <- canonicalizePath tgt
setCurrentDirectory p
runEffect
$ paths p
>-> Pipes.filter (isExt "dfm")
>-> Pipes.map (makeRelative p)
>-> Pipes.mapM readDFM
>-> parse
>-> Pipes.mapM_ (writeJSON cfg)
main :: IO ()
main = do
(args, ()) <- parseOptions
let cfg = newConfig . layout $ args
tgt = target args
if isValid tgt
then process tgt cfg
else putStrLn $ "Invalid path: " ++ tgt
|
e5a42857d8451ca1b0c6271bb2b24b614832342e09d74a55cbd819e69d960a02 | erlang-ls/erlang_ls | rename_usage1.erl | -module(rename_usage1).
-include("rename.hrl").
-behaviour(rename).
-export([rename_me/1]).
-spec rename_me(any()) -> any().
rename_me(x) ->
ok;
rename_me(_) ->
any.
rename_me_macro() ->
{?RENAME_ME, ?RENAME_ME}.
rename_me_parametrized_macro() ->
{?RENAME_ME_PARAMETRIZED(1), ?RENAME_ME_PARAMETRIZED(2)}.
rename_record(R = #rename_rec{rename_field = F}) ->
%% field access
F = R#rename_rec.rename_field,
%% record create
R2 = #rename_rec{rename_field = 12},
%% record update
R2#rename_rec{rename_field = F}.
| null | https://raw.githubusercontent.com/erlang-ls/erlang_ls/b4e2fd4fa5993d608ff547f1798c69ac2ae1c3cd/apps/els_lsp/priv/code_navigation/src/rename_usage1.erl | erlang | field access
record create
record update | -module(rename_usage1).
-include("rename.hrl").
-behaviour(rename).
-export([rename_me/1]).
-spec rename_me(any()) -> any().
rename_me(x) ->
ok;
rename_me(_) ->
any.
rename_me_macro() ->
{?RENAME_ME, ?RENAME_ME}.
rename_me_parametrized_macro() ->
{?RENAME_ME_PARAMETRIZED(1), ?RENAME_ME_PARAMETRIZED(2)}.
rename_record(R = #rename_rec{rename_field = F}) ->
F = R#rename_rec.rename_field,
R2 = #rename_rec{rename_field = 12},
R2#rename_rec{rename_field = F}.
|
5e65204b4f1b577882b891d509e04d4f593054211850e1815c46de4c3a6e08a2 | ocramz/taco-hs | Compiler.hs | # language GADTs #
{-# language PackageImports #-}
module Data.Tensor.Compiler
-- (
-- -- contract
-- -- -- * Tensor types
-- -- , Tensor(..), Sh(..), Dd(..), Sd(..)
-- -- * Syntax
Phoas , eval , var , let _ , let2 _
-- -- -- * Exceptions
-- , ( .. )
-- )
where
import Data . Typeable
import " exceptions " Control . . Catch ( MonadThrow ( .. ) , throwM , MonadCatch ( .. ) , catch )
import Control.Exception (Exception(..))
import Control . Applicative ( liftA2 , ( < | > ) )
( Tensor ( .. ) , Sh ( .. ) , Dd ( .. ) , Sd ( .. ) , tshape , tdata , nnz , rank , dim )
import Data . Tensor . Compiler . PHOAS -- ( Phoas ( .. ) , let _ , let2 _ , var , , lift2 , eval )
-- IN: Tensor reduction syntax (Einstein notation)
-- OUT: stride program (how to read/write memory)
-- taco compiles a tensor expression (e.g. C = A_{ijk}B_{k} ) into a series of nested loops.
-- dimensions : can be either dense or sparse
-- internally, tensor data is stored in /dense/ vectors
" contract A_{ijk}B_{k } over the third index "
-- |
mkVar : : MonadThrow m = > [ Int ] - > Tensor i a - > m ( Phoas ( Tensor i a ) )
mkVar ixs0 t = do
-- ixs <- mkIxs ixs0 (rank t)
-- return $ var t
mkIxs : : MonadThrow m = > [ Int ] - > Int - > m [ Int ]
-- mkIxs ixs mm = go ixs []
-- where
go [ ] acc = pure acc
-- go (i:is) acc | i < 0 =
throwM " Index must be non - negative "
-- | i > mm - 1 =
throwM $ IncompatIx $ unwords [ " Index must be smaller than " , show ]
-- | otherwise = go is (i : acc)
-- | Tensor contraction
--
Inject two ' Tensor ' constant into ' Var 's , while ensuring that all the contraction indices are compatible with those of the tensors .
--
-- Throws a 'CException' if any index is nonnegative or too large for the shape of the given tensor.
-- contract : : MonadThrow m = >
-- -- [Int] -- ^ Tensor contraction indices
-- -- -> Tensor i1 a
-- -- -> Tensor i2 b
-- -- -> ([Int] -> Tensor i1 a -> Tensor i2 b -> Phoas c) -- ^ Contraction function
-- -- -> m (Phoas c)
-- contract ixs0 t1 t2 f = do
-- _ <- mkIxs ixs0 (rank t1)
-- ixs <- mkIxs ixs0 (rank t2)
pure $ let _ ( var ixs ) $ \ixs ' - >
-- let2_ (var t1) (var t2) (f ixs')
| null | https://raw.githubusercontent.com/ocramz/taco-hs/19d208e2ddc628835a816568cd32029fb0b85048/src/Data/Tensor/Compiler.hs | haskell | # language PackageImports #
(
-- contract
-- -- * Tensor types
-- , Tensor(..), Sh(..), Dd(..), Sd(..)
-- * Syntax
-- -- * Exceptions
, ( .. )
)
( Phoas ( .. ) , let _ , let2 _ , var , , lift2 , eval )
IN: Tensor reduction syntax (Einstein notation)
OUT: stride program (how to read/write memory)
taco compiles a tensor expression (e.g. C = A_{ijk}B_{k} ) into a series of nested loops.
dimensions : can be either dense or sparse
internally, tensor data is stored in /dense/ vectors
|
ixs <- mkIxs ixs0 (rank t)
return $ var t
mkIxs ixs mm = go ixs []
where
go (i:is) acc | i < 0 =
| i > mm - 1 =
| otherwise = go is (i : acc)
| Tensor contraction
Throws a 'CException' if any index is nonnegative or too large for the shape of the given tensor.
contract : : MonadThrow m = >
-- [Int] -- ^ Tensor contraction indices
-- -> Tensor i1 a
-- -> Tensor i2 b
-- -> ([Int] -> Tensor i1 a -> Tensor i2 b -> Phoas c) -- ^ Contraction function
-- -> m (Phoas c)
contract ixs0 t1 t2 f = do
_ <- mkIxs ixs0 (rank t1)
ixs <- mkIxs ixs0 (rank t2)
let2_ (var t1) (var t2) (f ixs') | # language GADTs #
module Data.Tensor.Compiler
Phoas , eval , var , let _ , let2 _
where
import Data . Typeable
import " exceptions " Control . . Catch ( MonadThrow ( .. ) , throwM , MonadCatch ( .. ) , catch )
import Control.Exception (Exception(..))
import Control . Applicative ( liftA2 , ( < | > ) )
( Tensor ( .. ) , Sh ( .. ) , Dd ( .. ) , Sd ( .. ) , tshape , tdata , nnz , rank , dim )
" contract A_{ijk}B_{k } over the third index "
mkVar : : MonadThrow m = > [ Int ] - > Tensor i a - > m ( Phoas ( Tensor i a ) )
mkVar ixs0 t = do
mkIxs : : MonadThrow m = > [ Int ] - > Int - > m [ Int ]
go [ ] acc = pure acc
throwM " Index must be non - negative "
throwM $ IncompatIx $ unwords [ " Index must be smaller than " , show ]
Inject two ' Tensor ' constant into ' Var 's , while ensuring that all the contraction indices are compatible with those of the tensors .
pure $ let _ ( var ixs ) $ \ixs ' - >
|
643e5d9b8a3b5575706ea54f06a508aa8e1d1973ac13f9a5073290cf113e3599 | erlang/otp | io.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1996 - 2023 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
-module(io).
-export([put_chars/1,put_chars/2,nl/0,nl/1,
get_chars/2,get_chars/3,get_line/1,get_line/2,
get_password/0, get_password/1,
setopts/1, setopts/2, getopts/0, getopts/1]).
-export([write/1,write/2,read/1,read/2,read/3,read/4]).
-export([columns/0,columns/1,rows/0,rows/1]).
-export([fwrite/1,fwrite/2,fwrite/3,fread/2,fread/3,
format/1,format/2,format/3]).
-export([scan_erl_exprs/1,scan_erl_exprs/2,scan_erl_exprs/3,scan_erl_exprs/4,
scan_erl_form/1,scan_erl_form/2,scan_erl_form/3,scan_erl_form/4,
parse_erl_exprs/1,parse_erl_exprs/2,parse_erl_exprs/3,
parse_erl_exprs/4,parse_erl_form/1,parse_erl_form/2,
parse_erl_form/3,parse_erl_form/4]).
-export([request/1,request/2,requests/1,requests/2]).
%% Implemented in native code
-export([printable_range/0]).
-export_type([device/0, format/0, server_no_data/0]).
%%-------------------------------------------------------------------------
-type device() :: atom() | pid().
-type prompt() :: atom() | unicode:chardata().
ErrorDescription is whatever the I / O - server sends .
-type server_no_data() :: {'error', ErrorDescription :: term()} | 'eof'.
-type location() :: erl_anno:location().
%%-------------------------------------------------------------------------
%% Needs to be inlined for error_info to be correct
-compile({inline,[o_request/2]}).
o_request(Function, OrigArgs) ->
{Io, Request} =
if
Function =:= format; Function =:= fwrite ->
case OrigArgs of
[Format] ->
{default_output(), {format, Format, []}};
[Format, Args] ->
{default_output(), {format, Format, Args}};
[D, Format, Args] ->
{D, {format, Format, Args}}
end;
Function =:= put_chars ->
case OrigArgs of
[Chars] ->
{default_output(), {put_chars, unicode, Chars}};
[D, Chars] ->
{D, {put_chars, unicode, Chars}};
[D, Encoding, Chars] ->
{D, {put_chars, Encoding, Chars}}
end;
Function =:= nl ->
case OrigArgs of
[] ->
{default_output(), nl};
[D] ->
{D, nl}
end;
Function =:= write ->
case OrigArgs of
[Term] ->
{default_output(), {write, Term}};
[D, Term] ->
{D, {write, Term}}
end
end,
ErrorRef = make_ref(),
case request(Io, Request, ErrorRef) of
{ErrorRef, Reason} ->
%% We differentiate between errors that are created by this module
erlang:error(conv_reason(Reason), OrigArgs,
[{error_info,#{cause => {?MODULE, Reason},
module => erl_stdlib_errors}}]);
{error, Reason} ->
%% and the errors we get from the Device
erlang:error(conv_reason(Reason), OrigArgs,
[{error_info,#{cause => {device, Reason},
module => erl_stdlib_errors}}]);
Other ->
Other
end.
%%
%% User interface.
%%
%% Request what the user considers printable characters
-spec printable_range() -> 'unicode' | 'latin1'.
printable_range() ->
erlang:nif_error(undefined).
%% Put chars takes mixed *unicode* list from R13 onwards.
-spec put_chars(CharData) -> 'ok' when
CharData :: unicode:chardata().
put_chars(Chars) ->
o_request(?FUNCTION_NAME, [Chars]).
-spec put_chars(IoDevice, CharData) -> 'ok' when
IoDevice :: device(),
CharData :: unicode:chardata().
put_chars(Io, Chars) ->
o_request(?FUNCTION_NAME, [Io, Chars]).
-spec nl() -> 'ok'.
nl() ->
o_request(?FUNCTION_NAME, []).
-spec nl(IoDevice) -> 'ok' when
IoDevice :: device().
nl(Io) ->
o_request(?FUNCTION_NAME, [Io]).
-spec columns() -> {'ok', pos_integer()} | {'error', 'enotsup'}.
columns() ->
columns(default_output()).
-spec columns(IoDevice) -> {'ok', pos_integer()} | {'error', 'enotsup'} when
IoDevice :: device().
columns(Io) ->
case request(Io, {get_geometry,columns}) of
N when is_integer(N), N > 0 ->
{ok,N};
_ ->
{error,enotsup}
end.
-spec rows() -> {'ok', pos_integer()} | {'error', 'enotsup'}.
rows() ->
rows(default_output()).
-spec rows(IoDevice) -> {'ok', pos_integer()} | {'error', 'enotsup'} when
IoDevice :: device().
rows(Io) ->
case request(Io,{get_geometry,rows}) of
N when is_integer(N), N > 0 ->
{ok,N};
_ ->
{error,enotsup}
end.
-spec get_chars(Prompt, Count) -> Data | server_no_data() when
Prompt :: prompt(),
Count :: non_neg_integer(),
Data :: string() | unicode:unicode_binary().
get_chars(Prompt, N) ->
get_chars(default_input(), Prompt, N).
-spec get_chars(IoDevice, Prompt, Count) -> Data | server_no_data() when
IoDevice :: device(),
Prompt :: prompt(),
Count :: non_neg_integer(),
Data :: string() | unicode:unicode_binary().
get_chars(Io, Prompt, N) when is_integer(N), N >= 0 ->
request(Io, {get_chars,unicode,Prompt,N}).
-spec get_line(Prompt) -> Data | server_no_data() when
Prompt :: prompt(),
Data :: string() | unicode:unicode_binary().
get_line(Prompt) ->
get_line(default_input(), Prompt).
-spec get_line(IoDevice, Prompt) -> Data | server_no_data() when
IoDevice :: device(),
Prompt :: prompt(),
Data :: string() | unicode:unicode_binary().
get_line(Io, Prompt) ->
request(Io, {get_line,unicode,Prompt}).
get_password() ->
get_password(default_input()).
get_password(Io) ->
request(Io, {get_password,unicode}).
-type encoding() :: 'latin1' | 'unicode' | 'utf8' | 'utf16' | 'utf32'
| {'utf16', 'big' | 'little'} | {'utf32','big' | 'little'}.
-type expand_fun() :: fun((string()) -> {'yes'|'no', string(), list()}).
-type opt_pair() :: {'binary', boolean()}
| {'echo', boolean()}
| {'expand_fun', expand_fun()}
| {'encoding', encoding()}
| {atom(), term()}.
-type get_opt_pair() :: opt_pair()
| {'terminal', boolean()}.
-spec getopts() -> [get_opt_pair()] | {'error', Reason} when
Reason :: term().
getopts() ->
getopts(default_input()).
-spec getopts(IoDevice) -> [get_opt_pair()] | {'error', Reason} when
IoDevice :: device(),
Reason :: term().
getopts(Io) ->
request(Io, getopts).
-type setopt() :: 'binary' | 'list' | opt_pair().
-spec setopts(Opts) -> 'ok' | {'error', Reason} when
Opts :: [setopt()],
Reason :: term().
setopts(Opts) ->
setopts(default_input(), Opts).
-spec setopts(IoDevice, Opts) -> 'ok' | {'error', Reason} when
IoDevice :: device(),
Opts :: [setopt()],
Reason :: term().
setopts(Io, Opts) ->
request(Io, {setopts, Opts}).
Writing and reading Erlang terms .
-spec write(Term) -> 'ok' when
Term :: term().
write(Term) ->
o_request(?FUNCTION_NAME, [Term]).
-spec write(IoDevice, Term) -> 'ok' when
IoDevice :: device(),
Term :: term().
write(Io, Term) ->
o_request(?FUNCTION_NAME, [Io, Term]).
-spec read(Prompt) -> Result when
Prompt :: prompt(),
Result :: {'ok', Term :: term()}
| server_no_data()
| {'error', ErrorInfo},
ErrorInfo :: erl_scan:error_info() | erl_parse:error_info().
read(Prompt) ->
read(default_input(), Prompt).
-spec read(IoDevice, Prompt) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
Result :: {'ok', Term :: term()}
| server_no_data()
| {'error', ErrorInfo},
ErrorInfo :: erl_scan:error_info() | erl_parse:error_info().
read(Io, Prompt) ->
case request(Io, {get_until,unicode,Prompt,erl_scan,tokens,[1]}) of
{ok,Toks,_EndLine} ->
erl_parse:parse_term(Toks);
{error,E,_EndLine} ->
{error,E};
{eof,_EndLine} ->
eof;
Other ->
Other
end.
-spec read(IoDevice, Prompt, StartLocation) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Result :: {'ok', Term :: term(), EndLocation :: location()}
| {'eof', EndLocation :: location()}
| server_no_data()
| {'error', ErrorInfo, ErrorLocation :: location()},
ErrorInfo :: erl_scan:error_info() | erl_parse:error_info().
read(Io, Prompt, Pos0) ->
read(Io, Prompt, Pos0, []).
-spec read(IoDevice, Prompt, StartLocation, Options) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Options :: erl_scan:options(),
Result :: {'ok', Term :: term(), EndLocation :: location()}
| {'eof', EndLocation :: location()}
| server_no_data()
| {'error', ErrorInfo, ErrorLocation :: location()},
ErrorInfo :: erl_scan:error_info() | erl_parse:error_info().
read(Io, Prompt, Pos0, Options) ->
Args = [Pos0,Options],
case request(Io, {get_until,unicode,Prompt,erl_scan,tokens,Args}) of
{ok,Toks,EndLocation} ->
case erl_parse:parse_term(Toks) of
{ok,Term} -> {ok,Term,EndLocation};
{error,ErrorInfo} -> {error,ErrorInfo,EndLocation}
end;
{error,_E,_EndLocation} = Error ->
Error;
{eof,_EndLocation} = Eof ->
Eof;
Other ->
Other
end.
%% Formatted writing and reading.
conv_reason(arguments) -> badarg;
conv_reason(terminated) -> terminated;
conv_reason(calling_self) -> calling_self;
conv_reason({no_translation,_,_}) -> no_translation;
conv_reason(_Reason) -> badarg.
-type format() :: atom() | string() | binary().
-spec fwrite(Format) -> 'ok' when
Format :: format().
fwrite(Format) ->
o_request(?FUNCTION_NAME, [Format]).
-spec fwrite(Format, Data) -> 'ok' when
Format :: format(),
Data :: [term()].
fwrite(Format, Args) ->
o_request(?FUNCTION_NAME, [Format, Args]).
-spec fwrite(IoDevice, Format, Data) -> 'ok' when
IoDevice :: device(),
Format :: format(),
Data :: [term()].
fwrite(Io, Format, Args) ->
o_request(?FUNCTION_NAME, [Io, Format, Args]).
-spec fread(Prompt, Format) -> Result when
Prompt :: prompt(),
Format :: format(),
Result :: {'ok', Terms :: [term()]} | 'eof' | {'error', What :: term()}.
fread(Prompt, Format) ->
fread(default_input(), Prompt, Format).
-spec fread(IoDevice, Prompt, Format) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
Format :: format(),
Result :: {'ok', Terms :: [term()]}
| {'error', {'fread', FreadError :: io_lib:fread_error()}}
| server_no_data().
fread(Io, Prompt, Format) ->
request(Io, {fread,Prompt,Format}).
-spec format(Format) -> 'ok' when
Format :: format().
format(Format) ->
o_request(?FUNCTION_NAME, [Format]).
-spec format(Format, Data) -> 'ok' when
Format :: format(),
Data :: [term()].
format(Format, Args) ->
o_request(?FUNCTION_NAME, [Format, Args]).
-spec format(IoDevice, Format, Data) -> 'ok' when
IoDevice :: device(),
Format :: format(),
Data :: [term()].
format(Io, Format, Args) ->
o_request(?FUNCTION_NAME, [Io, Format, Args]).
%% Scanning Erlang code.
-spec scan_erl_exprs(Prompt) -> Result when
Prompt :: prompt(),
Result :: erl_scan:tokens_result() | server_no_data().
scan_erl_exprs(Prompt) ->
scan_erl_exprs(default_input(), Prompt, 1).
-spec scan_erl_exprs(Device, Prompt) -> Result when
Device :: device(),
Prompt :: prompt(),
Result :: erl_scan:tokens_result() | server_no_data().
scan_erl_exprs(Io, Prompt) ->
scan_erl_exprs(Io, Prompt, 1).
-spec scan_erl_exprs(Device, Prompt, StartLocation) -> Result when
Device :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Result :: erl_scan:tokens_result() | server_no_data().
scan_erl_exprs(Io, Prompt, Pos0) ->
scan_erl_exprs(Io, Prompt, Pos0, []).
-spec scan_erl_exprs(Device, Prompt, StartLocation, Options) -> Result when
Device :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Options :: erl_scan:options(),
Result :: erl_scan:tokens_result() | server_no_data().
scan_erl_exprs(Io, Prompt, Pos0, Options) ->
request(Io, {get_until,unicode,Prompt,erl_scan,tokens,[Pos0,Options]}).
-spec scan_erl_form(Prompt) -> Result when
Prompt :: prompt(),
Result :: erl_scan:tokens_result() | server_no_data().
scan_erl_form(Prompt) ->
scan_erl_form(default_input(), Prompt, 1).
-spec scan_erl_form(IoDevice, Prompt) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
Result :: erl_scan:tokens_result() | server_no_data().
scan_erl_form(Io, Prompt) ->
scan_erl_form(Io, Prompt, 1).
-spec scan_erl_form(IoDevice, Prompt, StartLocation) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Result :: erl_scan:tokens_result() | server_no_data().
scan_erl_form(Io, Prompt, Pos0) ->
scan_erl_form(Io, Prompt, Pos0, []).
-spec scan_erl_form(IoDevice, Prompt, StartLocation, Options) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Options :: erl_scan:options(),
Result :: erl_scan:tokens_result() | server_no_data().
scan_erl_form(Io, Prompt, Pos0, Options) ->
request(Io, {get_until,unicode,Prompt,erl_scan,tokens,[Pos0,Options]}).
%% Parsing Erlang code.
-type parse_ret() :: {'ok',
ExprList :: [erl_parse:abstract_expr()],
EndLocation :: location()}
| {'eof', EndLocation :: location()}
| {'error',
ErrorInfo :: erl_scan:error_info()
| erl_parse:error_info(),
ErrorLocation :: location()}
| server_no_data().
-spec parse_erl_exprs(Prompt) -> Result when
Prompt :: prompt(),
Result :: parse_ret().
parse_erl_exprs(Prompt) ->
parse_erl_exprs(default_input(), Prompt, 1).
-spec parse_erl_exprs(IoDevice, Prompt) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
Result :: parse_ret().
parse_erl_exprs(Io, Prompt) ->
parse_erl_exprs(Io, Prompt, 1).
-spec parse_erl_exprs(IoDevice, Prompt, StartLocation) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Result :: parse_ret().
parse_erl_exprs(Io, Prompt, Pos0) ->
parse_erl_exprs(Io, Prompt, Pos0, []).
-spec parse_erl_exprs(IoDevice, Prompt, StartLocation, Options) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Options :: erl_scan:options(),
Result :: parse_ret().
parse_erl_exprs(Io, Prompt, Pos0, Options) ->
case request(Io, {get_until,unicode,Prompt,erl_scan,tokens,[Pos0,Options]}) of
{ok,Toks,EndPos} ->
case erl_parse:parse_exprs(Toks) of
{ok,Exprs} -> {ok,Exprs,EndPos};
{error,E} -> {error,E,EndPos}
end;
Other ->
Other
end.
-type parse_form_ret() :: {'ok',
AbsForm :: erl_parse:abstract_form(),
EndLocation :: location()}
| {'eof', EndLocation :: location()}
| {'error',
ErrorInfo :: erl_scan:error_info()
| erl_parse:error_info(),
ErrorLocation :: location()}
| server_no_data().
-spec parse_erl_form(Prompt) -> Result when
Prompt :: prompt(),
Result :: parse_form_ret().
parse_erl_form(Prompt) ->
parse_erl_form(default_input(), Prompt, 1).
-spec parse_erl_form(IoDevice, Prompt) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
Result :: parse_form_ret().
parse_erl_form(Io, Prompt) ->
parse_erl_form(Io, Prompt, 1).
-spec parse_erl_form(IoDevice, Prompt, StartLocation) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Result :: parse_form_ret().
parse_erl_form(Io, Prompt, Pos0) ->
parse_erl_form(Io, Prompt, Pos0, []).
-spec parse_erl_form(IoDevice, Prompt, StartLocation, Options) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Options :: erl_scan:options(),
Result :: parse_form_ret().
parse_erl_form(Io, Prompt, Pos0, Options) ->
Args = [Pos0, Options],
case request(Io, {get_until,unicode,Prompt,erl_scan,tokens,Args}) of
{ok,Toks,EndPos} ->
case erl_parse:parse_form(Toks) of
{ok,Exprs} -> {ok,Exprs,EndPos};
{error,E} -> {error,E,EndPos}
end;
Other ->
Other
end.
%% Miscellaneous functions.
request(Request) ->
request(default_output(), Request).
request(Name, Request) ->
request(Name, Request, error).
request(standard_io, Request, ErrorTag) ->
request(group_leader(), Request, ErrorTag);
request(Pid, Request, ErrorTag) when is_pid(Pid) ->
execute_request(Pid, io_request(Pid, Request), ErrorTag);
request(Name, Request, ErrorTag) when is_atom(Name) ->
case whereis(Name) of
undefined ->
{ErrorTag, arguments};
Pid ->
request(Pid, Request, ErrorTag)
end.
execute_request(Pid, _Tuple, ErrorTag) when Pid =:= self() ->
{ErrorTag, calling_self};
execute_request(Pid, {Convert,Converted}, ErrorTag) ->
Mref = erlang:monitor(process, Pid),
Pid ! {io_request,self(),Mref,Converted},
receive
{io_reply, Mref, Reply} ->
erlang:demonitor(Mref, [flush]),
if
Convert ->
convert_binaries(Reply);
true ->
Reply
end;
{'DOWN', Mref, _, _, _} ->
receive
{'EXIT', Pid, _What} -> true
after 0 -> true
end,
{ErrorTag,terminated}
end.
requests(Requests) -> %Requests as atomic action
requests(default_output(), Requests).
requests(standard_io, Requests) -> %Requests as atomic action
requests(group_leader(), Requests);
requests(Pid, Requests) when is_pid(Pid) ->
{Convert, Converted} = io_requests(Pid, Requests),
execute_request(Pid,{Convert,{requests,Converted}},error);
requests(Name, Requests) when is_atom(Name) ->
case whereis(Name) of
undefined ->
{error, arguments};
Pid ->
requests(Pid, Requests)
end.
default_input() ->
group_leader().
default_output() ->
group_leader().
%% io_requests(Requests)
%% Transform requests into correct i/o server messages. Only handle the
%% one we KNOW must be changed, others, including incorrect ones, are
%% passed straight through. Perform a flatten on the request list.
io_requests(Pid, Rs) ->
io_requests(Pid, Rs, [], []).
io_requests(Pid, [{requests,Rs1}|Rs], Cont, Tail) ->
io_requests(Pid, Rs1, [Rs|Cont], Tail);
io_requests(Pid, [R], [], _Tail) ->
{Conv,Request} = io_request(Pid, R),
{Conv,[Request]};
io_requests(Pid, [R|Rs], Cont, Tail) ->
{_,Request} = io_request(Pid, R),
{Conv,Requests} = io_requests(Pid, Rs, Cont, Tail),
{Conv,[Request|Requests]};
io_requests(Pid, [], [Rs|Cont], Tail) ->
io_requests(Pid, Rs, Cont, Tail);
io_requests(_Pid, [], [], _Tail) ->
{false,[]}.
bc_req(Pid, Req0, MaybeConvert) ->
case net_kernel:dflag_unicode_io(Pid) of
true ->
%% The most common case. A modern i/o server.
{false,Req0};
false ->
%% Backward compatibility only. Unlikely to ever happen.
case tuple_to_list(Req0) of
[Op,_Enc] ->
{MaybeConvert,Op};
[Op,_Enc|T] ->
Req = list_to_tuple([Op|T]),
{MaybeConvert,Req}
end
end.
io_request(Pid, {write,Term}) ->
bc_req(Pid,{put_chars,unicode,io_lib,write,[Term]},false);
io_request(Pid, {format,Format,Args}) ->
bc_req(Pid,{put_chars,unicode,io_lib,format,[Format,Args]},false);
io_request(Pid, {fwrite,Format,Args}) ->
bc_req(Pid,{put_chars,unicode,io_lib,fwrite,[Format,Args]},false);
io_request(Pid, nl) ->
bc_req(Pid,{put_chars,unicode,io_lib:nl()},false);
io_request(Pid, {put_chars,Enc,Chars}=Request0)
when is_list(Chars), node(Pid) =:= node() ->
%% Convert to binary data if the I/O server is guaranteed to be new
Request =
case catch unicode:characters_to_binary(Chars,Enc) of
Binary when is_binary(Binary) ->
{put_chars,Enc,Binary};
_ ->
Request0
end,
{false,Request};
io_request(Pid, {put_chars,Enc,Chars}=Request0)
when is_list(Chars) ->
case net_kernel:dflag_unicode_io(Pid) of
true ->
case catch unicode:characters_to_binary(Chars,Enc,unicode) of
Binary when is_binary(Binary) ->
{false,{put_chars,unicode,Binary}};
_ ->
{false,Request0}
end;
false ->
%% Convert back to old style put_chars message...
case catch unicode:characters_to_binary(Chars,Enc,latin1) of
Binary when is_binary(Binary) ->
{false,{put_chars,Binary}};
_ ->
{false,{put_chars,Chars}}
end
end;
io_request(Pid, {fread,Prompt,Format}) ->
bc_req(Pid,{get_until,unicode,Prompt,io_lib,fread,[Format]},true);
io_request(Pid, {get_until,Enc,Prompt,M,F,A}) ->
bc_req(Pid,{get_until,Enc,Prompt,M,F,A},true);
io_request(Pid, {get_chars,Enc,Prompt,N}) ->
bc_req(Pid,{get_chars,Enc,Prompt,N},true);
io_request(Pid, {get_line,Enc,Prompt}) ->
bc_req(Pid,{get_line,Enc,Prompt},true);
io_request(Pid, {get_password,Enc}) ->
bc_req(Pid,{get_password, Enc},true);
io_request(_Pid, R) -> %Pass this straight through
{false,R}.
convert_binaries(Bin) when is_binary(Bin) ->
unicode:characters_to_binary(Bin,latin1,unicode);
convert_binaries(Else) ->
Else.
| null | https://raw.githubusercontent.com/erlang/otp/2b397d7e5580480dc32fa9751db95f4b89ff029e/lib/stdlib/src/io.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
Implemented in native code
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Needs to be inlined for error_info to be correct
We differentiate between errors that are created by this module
and the errors we get from the Device
User interface.
Request what the user considers printable characters
Put chars takes mixed *unicode* list from R13 onwards.
Formatted writing and reading.
Scanning Erlang code.
Parsing Erlang code.
Miscellaneous functions.
Requests as atomic action
Requests as atomic action
io_requests(Requests)
Transform requests into correct i/o server messages. Only handle the
one we KNOW must be changed, others, including incorrect ones, are
passed straight through. Perform a flatten on the request list.
The most common case. A modern i/o server.
Backward compatibility only. Unlikely to ever happen.
Convert to binary data if the I/O server is guaranteed to be new
Convert back to old style put_chars message...
Pass this straight through | Copyright Ericsson AB 1996 - 2023 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(io).
-export([put_chars/1,put_chars/2,nl/0,nl/1,
get_chars/2,get_chars/3,get_line/1,get_line/2,
get_password/0, get_password/1,
setopts/1, setopts/2, getopts/0, getopts/1]).
-export([write/1,write/2,read/1,read/2,read/3,read/4]).
-export([columns/0,columns/1,rows/0,rows/1]).
-export([fwrite/1,fwrite/2,fwrite/3,fread/2,fread/3,
format/1,format/2,format/3]).
-export([scan_erl_exprs/1,scan_erl_exprs/2,scan_erl_exprs/3,scan_erl_exprs/4,
scan_erl_form/1,scan_erl_form/2,scan_erl_form/3,scan_erl_form/4,
parse_erl_exprs/1,parse_erl_exprs/2,parse_erl_exprs/3,
parse_erl_exprs/4,parse_erl_form/1,parse_erl_form/2,
parse_erl_form/3,parse_erl_form/4]).
-export([request/1,request/2,requests/1,requests/2]).
-export([printable_range/0]).
-export_type([device/0, format/0, server_no_data/0]).
-type device() :: atom() | pid().
-type prompt() :: atom() | unicode:chardata().
ErrorDescription is whatever the I / O - server sends .
-type server_no_data() :: {'error', ErrorDescription :: term()} | 'eof'.
-type location() :: erl_anno:location().
-compile({inline,[o_request/2]}).
o_request(Function, OrigArgs) ->
{Io, Request} =
if
Function =:= format; Function =:= fwrite ->
case OrigArgs of
[Format] ->
{default_output(), {format, Format, []}};
[Format, Args] ->
{default_output(), {format, Format, Args}};
[D, Format, Args] ->
{D, {format, Format, Args}}
end;
Function =:= put_chars ->
case OrigArgs of
[Chars] ->
{default_output(), {put_chars, unicode, Chars}};
[D, Chars] ->
{D, {put_chars, unicode, Chars}};
[D, Encoding, Chars] ->
{D, {put_chars, Encoding, Chars}}
end;
Function =:= nl ->
case OrigArgs of
[] ->
{default_output(), nl};
[D] ->
{D, nl}
end;
Function =:= write ->
case OrigArgs of
[Term] ->
{default_output(), {write, Term}};
[D, Term] ->
{D, {write, Term}}
end
end,
ErrorRef = make_ref(),
case request(Io, Request, ErrorRef) of
{ErrorRef, Reason} ->
erlang:error(conv_reason(Reason), OrigArgs,
[{error_info,#{cause => {?MODULE, Reason},
module => erl_stdlib_errors}}]);
{error, Reason} ->
erlang:error(conv_reason(Reason), OrigArgs,
[{error_info,#{cause => {device, Reason},
module => erl_stdlib_errors}}]);
Other ->
Other
end.
-spec printable_range() -> 'unicode' | 'latin1'.
printable_range() ->
erlang:nif_error(undefined).
-spec put_chars(CharData) -> 'ok' when
CharData :: unicode:chardata().
put_chars(Chars) ->
o_request(?FUNCTION_NAME, [Chars]).
-spec put_chars(IoDevice, CharData) -> 'ok' when
IoDevice :: device(),
CharData :: unicode:chardata().
put_chars(Io, Chars) ->
o_request(?FUNCTION_NAME, [Io, Chars]).
-spec nl() -> 'ok'.
nl() ->
o_request(?FUNCTION_NAME, []).
-spec nl(IoDevice) -> 'ok' when
IoDevice :: device().
nl(Io) ->
o_request(?FUNCTION_NAME, [Io]).
-spec columns() -> {'ok', pos_integer()} | {'error', 'enotsup'}.
columns() ->
columns(default_output()).
-spec columns(IoDevice) -> {'ok', pos_integer()} | {'error', 'enotsup'} when
IoDevice :: device().
columns(Io) ->
case request(Io, {get_geometry,columns}) of
N when is_integer(N), N > 0 ->
{ok,N};
_ ->
{error,enotsup}
end.
-spec rows() -> {'ok', pos_integer()} | {'error', 'enotsup'}.
rows() ->
rows(default_output()).
-spec rows(IoDevice) -> {'ok', pos_integer()} | {'error', 'enotsup'} when
IoDevice :: device().
rows(Io) ->
case request(Io,{get_geometry,rows}) of
N when is_integer(N), N > 0 ->
{ok,N};
_ ->
{error,enotsup}
end.
-spec get_chars(Prompt, Count) -> Data | server_no_data() when
Prompt :: prompt(),
Count :: non_neg_integer(),
Data :: string() | unicode:unicode_binary().
get_chars(Prompt, N) ->
get_chars(default_input(), Prompt, N).
-spec get_chars(IoDevice, Prompt, Count) -> Data | server_no_data() when
IoDevice :: device(),
Prompt :: prompt(),
Count :: non_neg_integer(),
Data :: string() | unicode:unicode_binary().
get_chars(Io, Prompt, N) when is_integer(N), N >= 0 ->
request(Io, {get_chars,unicode,Prompt,N}).
-spec get_line(Prompt) -> Data | server_no_data() when
Prompt :: prompt(),
Data :: string() | unicode:unicode_binary().
get_line(Prompt) ->
get_line(default_input(), Prompt).
-spec get_line(IoDevice, Prompt) -> Data | server_no_data() when
IoDevice :: device(),
Prompt :: prompt(),
Data :: string() | unicode:unicode_binary().
get_line(Io, Prompt) ->
request(Io, {get_line,unicode,Prompt}).
get_password() ->
get_password(default_input()).
get_password(Io) ->
request(Io, {get_password,unicode}).
-type encoding() :: 'latin1' | 'unicode' | 'utf8' | 'utf16' | 'utf32'
| {'utf16', 'big' | 'little'} | {'utf32','big' | 'little'}.
-type expand_fun() :: fun((string()) -> {'yes'|'no', string(), list()}).
-type opt_pair() :: {'binary', boolean()}
| {'echo', boolean()}
| {'expand_fun', expand_fun()}
| {'encoding', encoding()}
| {atom(), term()}.
-type get_opt_pair() :: opt_pair()
| {'terminal', boolean()}.
-spec getopts() -> [get_opt_pair()] | {'error', Reason} when
Reason :: term().
getopts() ->
getopts(default_input()).
-spec getopts(IoDevice) -> [get_opt_pair()] | {'error', Reason} when
IoDevice :: device(),
Reason :: term().
getopts(Io) ->
request(Io, getopts).
-type setopt() :: 'binary' | 'list' | opt_pair().
-spec setopts(Opts) -> 'ok' | {'error', Reason} when
Opts :: [setopt()],
Reason :: term().
setopts(Opts) ->
setopts(default_input(), Opts).
-spec setopts(IoDevice, Opts) -> 'ok' | {'error', Reason} when
IoDevice :: device(),
Opts :: [setopt()],
Reason :: term().
setopts(Io, Opts) ->
request(Io, {setopts, Opts}).
Writing and reading Erlang terms .
-spec write(Term) -> 'ok' when
Term :: term().
write(Term) ->
o_request(?FUNCTION_NAME, [Term]).
-spec write(IoDevice, Term) -> 'ok' when
IoDevice :: device(),
Term :: term().
write(Io, Term) ->
o_request(?FUNCTION_NAME, [Io, Term]).
-spec read(Prompt) -> Result when
Prompt :: prompt(),
Result :: {'ok', Term :: term()}
| server_no_data()
| {'error', ErrorInfo},
ErrorInfo :: erl_scan:error_info() | erl_parse:error_info().
read(Prompt) ->
read(default_input(), Prompt).
-spec read(IoDevice, Prompt) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
Result :: {'ok', Term :: term()}
| server_no_data()
| {'error', ErrorInfo},
ErrorInfo :: erl_scan:error_info() | erl_parse:error_info().
read(Io, Prompt) ->
case request(Io, {get_until,unicode,Prompt,erl_scan,tokens,[1]}) of
{ok,Toks,_EndLine} ->
erl_parse:parse_term(Toks);
{error,E,_EndLine} ->
{error,E};
{eof,_EndLine} ->
eof;
Other ->
Other
end.
-spec read(IoDevice, Prompt, StartLocation) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Result :: {'ok', Term :: term(), EndLocation :: location()}
| {'eof', EndLocation :: location()}
| server_no_data()
| {'error', ErrorInfo, ErrorLocation :: location()},
ErrorInfo :: erl_scan:error_info() | erl_parse:error_info().
read(Io, Prompt, Pos0) ->
read(Io, Prompt, Pos0, []).
-spec read(IoDevice, Prompt, StartLocation, Options) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Options :: erl_scan:options(),
Result :: {'ok', Term :: term(), EndLocation :: location()}
| {'eof', EndLocation :: location()}
| server_no_data()
| {'error', ErrorInfo, ErrorLocation :: location()},
ErrorInfo :: erl_scan:error_info() | erl_parse:error_info().
read(Io, Prompt, Pos0, Options) ->
Args = [Pos0,Options],
case request(Io, {get_until,unicode,Prompt,erl_scan,tokens,Args}) of
{ok,Toks,EndLocation} ->
case erl_parse:parse_term(Toks) of
{ok,Term} -> {ok,Term,EndLocation};
{error,ErrorInfo} -> {error,ErrorInfo,EndLocation}
end;
{error,_E,_EndLocation} = Error ->
Error;
{eof,_EndLocation} = Eof ->
Eof;
Other ->
Other
end.
conv_reason(arguments) -> badarg;
conv_reason(terminated) -> terminated;
conv_reason(calling_self) -> calling_self;
conv_reason({no_translation,_,_}) -> no_translation;
conv_reason(_Reason) -> badarg.
-type format() :: atom() | string() | binary().
-spec fwrite(Format) -> 'ok' when
Format :: format().
fwrite(Format) ->
o_request(?FUNCTION_NAME, [Format]).
-spec fwrite(Format, Data) -> 'ok' when
Format :: format(),
Data :: [term()].
fwrite(Format, Args) ->
o_request(?FUNCTION_NAME, [Format, Args]).
-spec fwrite(IoDevice, Format, Data) -> 'ok' when
IoDevice :: device(),
Format :: format(),
Data :: [term()].
fwrite(Io, Format, Args) ->
o_request(?FUNCTION_NAME, [Io, Format, Args]).
-spec fread(Prompt, Format) -> Result when
Prompt :: prompt(),
Format :: format(),
Result :: {'ok', Terms :: [term()]} | 'eof' | {'error', What :: term()}.
fread(Prompt, Format) ->
fread(default_input(), Prompt, Format).
-spec fread(IoDevice, Prompt, Format) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
Format :: format(),
Result :: {'ok', Terms :: [term()]}
| {'error', {'fread', FreadError :: io_lib:fread_error()}}
| server_no_data().
fread(Io, Prompt, Format) ->
request(Io, {fread,Prompt,Format}).
-spec format(Format) -> 'ok' when
Format :: format().
format(Format) ->
o_request(?FUNCTION_NAME, [Format]).
-spec format(Format, Data) -> 'ok' when
Format :: format(),
Data :: [term()].
format(Format, Args) ->
o_request(?FUNCTION_NAME, [Format, Args]).
-spec format(IoDevice, Format, Data) -> 'ok' when
IoDevice :: device(),
Format :: format(),
Data :: [term()].
format(Io, Format, Args) ->
o_request(?FUNCTION_NAME, [Io, Format, Args]).
-spec scan_erl_exprs(Prompt) -> Result when
Prompt :: prompt(),
Result :: erl_scan:tokens_result() | server_no_data().
scan_erl_exprs(Prompt) ->
scan_erl_exprs(default_input(), Prompt, 1).
-spec scan_erl_exprs(Device, Prompt) -> Result when
Device :: device(),
Prompt :: prompt(),
Result :: erl_scan:tokens_result() | server_no_data().
scan_erl_exprs(Io, Prompt) ->
scan_erl_exprs(Io, Prompt, 1).
-spec scan_erl_exprs(Device, Prompt, StartLocation) -> Result when
Device :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Result :: erl_scan:tokens_result() | server_no_data().
scan_erl_exprs(Io, Prompt, Pos0) ->
scan_erl_exprs(Io, Prompt, Pos0, []).
-spec scan_erl_exprs(Device, Prompt, StartLocation, Options) -> Result when
Device :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Options :: erl_scan:options(),
Result :: erl_scan:tokens_result() | server_no_data().
scan_erl_exprs(Io, Prompt, Pos0, Options) ->
request(Io, {get_until,unicode,Prompt,erl_scan,tokens,[Pos0,Options]}).
-spec scan_erl_form(Prompt) -> Result when
Prompt :: prompt(),
Result :: erl_scan:tokens_result() | server_no_data().
scan_erl_form(Prompt) ->
scan_erl_form(default_input(), Prompt, 1).
-spec scan_erl_form(IoDevice, Prompt) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
Result :: erl_scan:tokens_result() | server_no_data().
scan_erl_form(Io, Prompt) ->
scan_erl_form(Io, Prompt, 1).
-spec scan_erl_form(IoDevice, Prompt, StartLocation) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Result :: erl_scan:tokens_result() | server_no_data().
scan_erl_form(Io, Prompt, Pos0) ->
scan_erl_form(Io, Prompt, Pos0, []).
-spec scan_erl_form(IoDevice, Prompt, StartLocation, Options) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Options :: erl_scan:options(),
Result :: erl_scan:tokens_result() | server_no_data().
scan_erl_form(Io, Prompt, Pos0, Options) ->
request(Io, {get_until,unicode,Prompt,erl_scan,tokens,[Pos0,Options]}).
-type parse_ret() :: {'ok',
ExprList :: [erl_parse:abstract_expr()],
EndLocation :: location()}
| {'eof', EndLocation :: location()}
| {'error',
ErrorInfo :: erl_scan:error_info()
| erl_parse:error_info(),
ErrorLocation :: location()}
| server_no_data().
-spec parse_erl_exprs(Prompt) -> Result when
Prompt :: prompt(),
Result :: parse_ret().
parse_erl_exprs(Prompt) ->
parse_erl_exprs(default_input(), Prompt, 1).
-spec parse_erl_exprs(IoDevice, Prompt) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
Result :: parse_ret().
parse_erl_exprs(Io, Prompt) ->
parse_erl_exprs(Io, Prompt, 1).
-spec parse_erl_exprs(IoDevice, Prompt, StartLocation) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Result :: parse_ret().
parse_erl_exprs(Io, Prompt, Pos0) ->
parse_erl_exprs(Io, Prompt, Pos0, []).
-spec parse_erl_exprs(IoDevice, Prompt, StartLocation, Options) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Options :: erl_scan:options(),
Result :: parse_ret().
parse_erl_exprs(Io, Prompt, Pos0, Options) ->
case request(Io, {get_until,unicode,Prompt,erl_scan,tokens,[Pos0,Options]}) of
{ok,Toks,EndPos} ->
case erl_parse:parse_exprs(Toks) of
{ok,Exprs} -> {ok,Exprs,EndPos};
{error,E} -> {error,E,EndPos}
end;
Other ->
Other
end.
-type parse_form_ret() :: {'ok',
AbsForm :: erl_parse:abstract_form(),
EndLocation :: location()}
| {'eof', EndLocation :: location()}
| {'error',
ErrorInfo :: erl_scan:error_info()
| erl_parse:error_info(),
ErrorLocation :: location()}
| server_no_data().
-spec parse_erl_form(Prompt) -> Result when
Prompt :: prompt(),
Result :: parse_form_ret().
parse_erl_form(Prompt) ->
parse_erl_form(default_input(), Prompt, 1).
-spec parse_erl_form(IoDevice, Prompt) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
Result :: parse_form_ret().
parse_erl_form(Io, Prompt) ->
parse_erl_form(Io, Prompt, 1).
-spec parse_erl_form(IoDevice, Prompt, StartLocation) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Result :: parse_form_ret().
parse_erl_form(Io, Prompt, Pos0) ->
parse_erl_form(Io, Prompt, Pos0, []).
-spec parse_erl_form(IoDevice, Prompt, StartLocation, Options) -> Result when
IoDevice :: device(),
Prompt :: prompt(),
StartLocation :: location(),
Options :: erl_scan:options(),
Result :: parse_form_ret().
parse_erl_form(Io, Prompt, Pos0, Options) ->
Args = [Pos0, Options],
case request(Io, {get_until,unicode,Prompt,erl_scan,tokens,Args}) of
{ok,Toks,EndPos} ->
case erl_parse:parse_form(Toks) of
{ok,Exprs} -> {ok,Exprs,EndPos};
{error,E} -> {error,E,EndPos}
end;
Other ->
Other
end.
request(Request) ->
request(default_output(), Request).
request(Name, Request) ->
request(Name, Request, error).
request(standard_io, Request, ErrorTag) ->
request(group_leader(), Request, ErrorTag);
request(Pid, Request, ErrorTag) when is_pid(Pid) ->
execute_request(Pid, io_request(Pid, Request), ErrorTag);
request(Name, Request, ErrorTag) when is_atom(Name) ->
case whereis(Name) of
undefined ->
{ErrorTag, arguments};
Pid ->
request(Pid, Request, ErrorTag)
end.
execute_request(Pid, _Tuple, ErrorTag) when Pid =:= self() ->
{ErrorTag, calling_self};
execute_request(Pid, {Convert,Converted}, ErrorTag) ->
Mref = erlang:monitor(process, Pid),
Pid ! {io_request,self(),Mref,Converted},
receive
{io_reply, Mref, Reply} ->
erlang:demonitor(Mref, [flush]),
if
Convert ->
convert_binaries(Reply);
true ->
Reply
end;
{'DOWN', Mref, _, _, _} ->
receive
{'EXIT', Pid, _What} -> true
after 0 -> true
end,
{ErrorTag,terminated}
end.
requests(default_output(), Requests).
requests(group_leader(), Requests);
requests(Pid, Requests) when is_pid(Pid) ->
{Convert, Converted} = io_requests(Pid, Requests),
execute_request(Pid,{Convert,{requests,Converted}},error);
requests(Name, Requests) when is_atom(Name) ->
case whereis(Name) of
undefined ->
{error, arguments};
Pid ->
requests(Pid, Requests)
end.
default_input() ->
group_leader().
default_output() ->
group_leader().
io_requests(Pid, Rs) ->
io_requests(Pid, Rs, [], []).
io_requests(Pid, [{requests,Rs1}|Rs], Cont, Tail) ->
io_requests(Pid, Rs1, [Rs|Cont], Tail);
io_requests(Pid, [R], [], _Tail) ->
{Conv,Request} = io_request(Pid, R),
{Conv,[Request]};
io_requests(Pid, [R|Rs], Cont, Tail) ->
{_,Request} = io_request(Pid, R),
{Conv,Requests} = io_requests(Pid, Rs, Cont, Tail),
{Conv,[Request|Requests]};
io_requests(Pid, [], [Rs|Cont], Tail) ->
io_requests(Pid, Rs, Cont, Tail);
io_requests(_Pid, [], [], _Tail) ->
{false,[]}.
bc_req(Pid, Req0, MaybeConvert) ->
case net_kernel:dflag_unicode_io(Pid) of
true ->
{false,Req0};
false ->
case tuple_to_list(Req0) of
[Op,_Enc] ->
{MaybeConvert,Op};
[Op,_Enc|T] ->
Req = list_to_tuple([Op|T]),
{MaybeConvert,Req}
end
end.
io_request(Pid, {write,Term}) ->
bc_req(Pid,{put_chars,unicode,io_lib,write,[Term]},false);
io_request(Pid, {format,Format,Args}) ->
bc_req(Pid,{put_chars,unicode,io_lib,format,[Format,Args]},false);
io_request(Pid, {fwrite,Format,Args}) ->
bc_req(Pid,{put_chars,unicode,io_lib,fwrite,[Format,Args]},false);
io_request(Pid, nl) ->
bc_req(Pid,{put_chars,unicode,io_lib:nl()},false);
io_request(Pid, {put_chars,Enc,Chars}=Request0)
when is_list(Chars), node(Pid) =:= node() ->
Request =
case catch unicode:characters_to_binary(Chars,Enc) of
Binary when is_binary(Binary) ->
{put_chars,Enc,Binary};
_ ->
Request0
end,
{false,Request};
io_request(Pid, {put_chars,Enc,Chars}=Request0)
when is_list(Chars) ->
case net_kernel:dflag_unicode_io(Pid) of
true ->
case catch unicode:characters_to_binary(Chars,Enc,unicode) of
Binary when is_binary(Binary) ->
{false,{put_chars,unicode,Binary}};
_ ->
{false,Request0}
end;
false ->
case catch unicode:characters_to_binary(Chars,Enc,latin1) of
Binary when is_binary(Binary) ->
{false,{put_chars,Binary}};
_ ->
{false,{put_chars,Chars}}
end
end;
io_request(Pid, {fread,Prompt,Format}) ->
bc_req(Pid,{get_until,unicode,Prompt,io_lib,fread,[Format]},true);
io_request(Pid, {get_until,Enc,Prompt,M,F,A}) ->
bc_req(Pid,{get_until,Enc,Prompt,M,F,A},true);
io_request(Pid, {get_chars,Enc,Prompt,N}) ->
bc_req(Pid,{get_chars,Enc,Prompt,N},true);
io_request(Pid, {get_line,Enc,Prompt}) ->
bc_req(Pid,{get_line,Enc,Prompt},true);
io_request(Pid, {get_password,Enc}) ->
bc_req(Pid,{get_password, Enc},true);
{false,R}.
convert_binaries(Bin) when is_binary(Bin) ->
unicode:characters_to_binary(Bin,latin1,unicode);
convert_binaries(Else) ->
Else.
|
3201420a1653cc0a31c54da61edbc64f7cd5c5dbbc2e039ed2415ff66ee29f9f | vabal/vabal | Glob.hs | --TODO: [code cleanup] plausibly much of this module should be merged with
similar functionality in Cabal .
module Glob
( FilePathGlob(..)
, FilePathRoot(..)
, FilePathGlobRel(..)
, Glob
, GlobPiece(..)
, matchFileGlob
, matchFileGlobRel
, matchGlob
, isTrivialFilePathGlob
, getFilePathRootDirectory
, parseFilePathGlob
, parseFilePathGlobRel
) where
import Distribution.Parsec.Class
import Distribution.Compat.CharParsing
import Control.Applicative
import Distribution.Pretty
import Data.List (stripPrefix)
import Data.Char (toUpper, isAsciiLower, isAsciiUpper)
import Control.Monad (filterM, when)
import Data.Functor (($>))
import qualified Text.PrettyPrint as Disp
import System.FilePath
import System.Directory
-- | A file path specified by globbing
--
data FilePathGlob = FilePathGlob FilePathRoot FilePathGlobRel
deriving (Eq, Show)
data FilePathGlobRel
= GlobDir !Glob !FilePathGlobRel
| GlobFile !Glob
^ trailing dir , a glob ending in @/@
deriving (Eq, Show)
-- | A single directory or file component of a globbed path
type Glob = [GlobPiece]
-- | A piece of a globbing pattern
data GlobPiece = WildCard
| Literal String
| Union [Glob]
deriving (Eq, Show)
data FilePathRoot
= FilePathRelative
| FilePathRoot FilePath -- ^ e.g. @"/"@, @"c:\"@ or result of 'takeDrive'
| FilePathHomeDir
deriving (Eq, Show)
-- | Check if a 'FilePathGlob' doesn't actually make use of any globbing and
is in fact equivalent to a non - glob ' FilePath ' .
--
-- If it is trivial in this sense then the result is the equivalent constant
' FilePath ' . On the other hand if it is not trivial ( so could in principle
match more than one file ) then the result is @Nothing@.
--
isTrivialFilePathGlob :: FilePathGlob -> Maybe FilePath
isTrivialFilePathGlob (FilePathGlob root pathglob) =
case root of
FilePathRelative -> go [] pathglob
FilePathRoot root' -> go [root'] pathglob
FilePathHomeDir -> Nothing
where
go paths (GlobDir [Literal path] globs) = go (path:paths) globs
go paths (GlobFile [Literal path]) = Just (joinPath (reverse (path:paths)))
go paths GlobDirTrailing = Just (addTrailingPathSeparator
(joinPath (reverse paths)))
go _ _ = Nothing
-- | Get the 'FilePath' corresponding to a 'FilePathRoot'.
--
The ' FilePath ' argument is required to supply the path for the
-- 'FilePathRelative' case.
--
getFilePathRootDirectory :: FilePathRoot
-> FilePath -- ^ root for relative paths
-> IO FilePath
getFilePathRootDirectory FilePathRelative root = return root
getFilePathRootDirectory (FilePathRoot root) _ = return root
getFilePathRootDirectory FilePathHomeDir _ = getHomeDirectory
------------------------------------------------------------------------------
-- Matching
--
-- | Match a 'FilePathGlob' against the file system, starting from a given
-- root directory for relative paths. The results of relative globs are
-- relative to the given root. Matches for absolute globs are absolute.
--
matchFileGlob :: FilePath -> FilePathGlob -> IO [FilePath]
matchFileGlob relroot (FilePathGlob globroot glob) = do
root <- getFilePathRootDirectory globroot relroot
matches <- matchFileGlobRel root glob
case globroot of
FilePathRelative -> return matches
_ -> return (map (root </>) matches)
-- | Match a 'FilePathGlobRel' against the file system, starting from a
-- given root directory. The results are all relative to the given root.
--
matchFileGlobRel :: FilePath -> FilePathGlobRel -> IO [FilePath]
matchFileGlobRel root glob0 = go glob0 ""
where
go (GlobFile glob) dir = do
entries <- getDirectoryContents (root </> dir)
let files = filter (matchGlob glob) entries
return (map (dir </>) files)
go (GlobDir glob globPath) dir = do
entries <- getDirectoryContents (root </> dir)
subdirs <- filterM (\subdir -> doesDirectoryExist
(root </> dir </> subdir))
$ filter (matchGlob glob) entries
concat <$> mapM (\subdir -> go globPath (dir </> subdir)) subdirs
go GlobDirTrailing dir = return [dir]
-- | Match a globbing pattern against a file path component
--
matchGlob :: Glob -> String -> Bool
matchGlob = goStart
where
-- From the man page, glob(7):
-- "If a filename starts with a '.', this character must be
-- matched explicitly."
go, goStart :: [GlobPiece] -> String -> Bool
goStart (WildCard:_) ('.':_) = False
goStart (Union globs:rest) cs = any (\glob -> goStart (glob ++ rest) cs)
globs
goStart rest cs = go rest cs
go [] "" = True
go (Literal lit:rest) cs
| Just cs' <- stripPrefix lit cs
= go rest cs'
| otherwise = False
go [WildCard] "" = True
go (WildCard:rest) (c:cs) = go rest (c:cs) || go (WildCard:rest) cs
go (Union globs:rest) cs = any (\glob -> go (glob ++ rest) cs) globs
go [] (_:_) = False
go (_:_) "" = False
------------------------------------------------------------------------------
-- Parsing & printing
--
parseFilePathGlob :: String -> Either String FilePathGlob
parseFilePathGlob = eitherParsec
parseFilePathGlobRel :: String -> Either String FilePathGlobRel
parseFilePathGlobRel = eitherParsec
instance Parsec FilePathGlob where
parsec = do
root <- parsec
(FilePathGlob root <$> parsec) <|> alt2 root
where alt2 root = do
when (root == FilePathRelative) (fail "Unexpected relative path")
return (FilePathGlob root GlobDirTrailing)
instance Pretty FilePathGlob where
pretty (FilePathGlob root pathglob) = pretty root Disp.<> pretty pathglob
instance Parsec FilePathRoot where
parsec = (char '/' $> FilePathRoot "/")
<|> (char '~' *> char '/' $> FilePathHomeDir)
<|> try parseDrive
<|> return FilePathRelative
where isAsciiAlpha c = isAsciiLower c || isAsciiUpper c
parseDrive = do
drive <- satisfy isAsciiAlpha
_ <- char ':'
_ <- char '/' <|> char '\\'
return (FilePathRoot (toUpper drive : ":\\"))
instance Pretty FilePathRoot where
pretty FilePathRelative = Disp.empty
pretty (FilePathRoot root) = Disp.text root
pretty FilePathHomeDir = Disp.char '~' Disp.<> Disp.char '/'
instance Parsec FilePathGlobRel where
parsec = parsePath
where parsePath = do
globpieces <- parseGlob
try (asDir globpieces) <|> try (asTDir globpieces) <|> asFile globpieces
asDir glob = do dirSep
GlobDir glob <$> parsePath
asTDir glob = dirSep $> GlobDir glob GlobDirTrailing
asFile glob = return (GlobFile glob)
dirSep = (char '/' $> ()) <|> notEscapingBackslash
notEscapingBackslash =
char '\\' *> notFollowedBy (satisfy isGlobEscapedChar)
instance Pretty FilePathGlobRel where
pretty (GlobDir glob pathglob) = dispGlob glob
Disp.<> Disp.char '/'
Disp.<> pretty pathglob
pretty (GlobFile glob) = dispGlob glob
pretty GlobDirTrailing = Disp.empty
dispGlob :: Glob -> Disp.Doc
dispGlob = Disp.hcat . map dispPiece
where
dispPiece WildCard = Disp.char '*'
dispPiece (Literal str) = Disp.text (escape str)
dispPiece (Union globs) = Disp.braces
(Disp.hcat (Disp.punctuate
(Disp.char ',')
(map dispGlob globs)))
escape [] = []
escape (c:cs)
| isGlobEscapedChar c = '\\' : c : escape cs
| otherwise = c : escape cs
parseGlob :: CharParsing m => m Glob
parseGlob = some parsePiece
where
parsePiece = literal <|> wildcard <|> union
wildcard = char '*' $> WildCard
union = between (char '{') (char '}') $
fmap Union (sepBy1 parseGlob (char ','))
literal = Literal `fmap` litchars1
litchar = normal <|> escape
normal = satisfy (\c -> not (isGlobEscapedChar c)
&& c /= '/' && c /= '\\')
escape = char '\\' *> satisfy isGlobEscapedChar
litchars1 = liftA2 (:) litchar litchars
litchars = litchars1 <|> pure []
isGlobEscapedChar :: Char -> Bool
isGlobEscapedChar '*' = True
isGlobEscapedChar '{' = True
isGlobEscapedChar '}' = True
isGlobEscapedChar ',' = True
isGlobEscapedChar _ = False
| null | https://raw.githubusercontent.com/vabal/vabal/89bc2ea1cd09e2bf6c6666de1d15f98f840e88fd/vabal/src/Glob.hs | haskell | TODO: [code cleanup] plausibly much of this module should be merged with
| A file path specified by globbing
| A single directory or file component of a globbed path
| A piece of a globbing pattern
^ e.g. @"/"@, @"c:\"@ or result of 'takeDrive'
| Check if a 'FilePathGlob' doesn't actually make use of any globbing and
If it is trivial in this sense then the result is the equivalent constant
| Get the 'FilePath' corresponding to a 'FilePathRoot'.
'FilePathRelative' case.
^ root for relative paths
----------------------------------------------------------------------------
Matching
| Match a 'FilePathGlob' against the file system, starting from a given
root directory for relative paths. The results of relative globs are
relative to the given root. Matches for absolute globs are absolute.
| Match a 'FilePathGlobRel' against the file system, starting from a
given root directory. The results are all relative to the given root.
| Match a globbing pattern against a file path component
From the man page, glob(7):
"If a filename starts with a '.', this character must be
matched explicitly."
----------------------------------------------------------------------------
Parsing & printing
| similar functionality in Cabal .
module Glob
( FilePathGlob(..)
, FilePathRoot(..)
, FilePathGlobRel(..)
, Glob
, GlobPiece(..)
, matchFileGlob
, matchFileGlobRel
, matchGlob
, isTrivialFilePathGlob
, getFilePathRootDirectory
, parseFilePathGlob
, parseFilePathGlobRel
) where
import Distribution.Parsec.Class
import Distribution.Compat.CharParsing
import Control.Applicative
import Distribution.Pretty
import Data.List (stripPrefix)
import Data.Char (toUpper, isAsciiLower, isAsciiUpper)
import Control.Monad (filterM, when)
import Data.Functor (($>))
import qualified Text.PrettyPrint as Disp
import System.FilePath
import System.Directory
data FilePathGlob = FilePathGlob FilePathRoot FilePathGlobRel
deriving (Eq, Show)
data FilePathGlobRel
= GlobDir !Glob !FilePathGlobRel
| GlobFile !Glob
^ trailing dir , a glob ending in @/@
deriving (Eq, Show)
type Glob = [GlobPiece]
data GlobPiece = WildCard
| Literal String
| Union [Glob]
deriving (Eq, Show)
data FilePathRoot
= FilePathRelative
| FilePathHomeDir
deriving (Eq, Show)
is in fact equivalent to a non - glob ' FilePath ' .
' FilePath ' . On the other hand if it is not trivial ( so could in principle
match more than one file ) then the result is @Nothing@.
isTrivialFilePathGlob :: FilePathGlob -> Maybe FilePath
isTrivialFilePathGlob (FilePathGlob root pathglob) =
case root of
FilePathRelative -> go [] pathglob
FilePathRoot root' -> go [root'] pathglob
FilePathHomeDir -> Nothing
where
go paths (GlobDir [Literal path] globs) = go (path:paths) globs
go paths (GlobFile [Literal path]) = Just (joinPath (reverse (path:paths)))
go paths GlobDirTrailing = Just (addTrailingPathSeparator
(joinPath (reverse paths)))
go _ _ = Nothing
The ' FilePath ' argument is required to supply the path for the
getFilePathRootDirectory :: FilePathRoot
-> IO FilePath
getFilePathRootDirectory FilePathRelative root = return root
getFilePathRootDirectory (FilePathRoot root) _ = return root
getFilePathRootDirectory FilePathHomeDir _ = getHomeDirectory
matchFileGlob :: FilePath -> FilePathGlob -> IO [FilePath]
matchFileGlob relroot (FilePathGlob globroot glob) = do
root <- getFilePathRootDirectory globroot relroot
matches <- matchFileGlobRel root glob
case globroot of
FilePathRelative -> return matches
_ -> return (map (root </>) matches)
matchFileGlobRel :: FilePath -> FilePathGlobRel -> IO [FilePath]
matchFileGlobRel root glob0 = go glob0 ""
where
go (GlobFile glob) dir = do
entries <- getDirectoryContents (root </> dir)
let files = filter (matchGlob glob) entries
return (map (dir </>) files)
go (GlobDir glob globPath) dir = do
entries <- getDirectoryContents (root </> dir)
subdirs <- filterM (\subdir -> doesDirectoryExist
(root </> dir </> subdir))
$ filter (matchGlob glob) entries
concat <$> mapM (\subdir -> go globPath (dir </> subdir)) subdirs
go GlobDirTrailing dir = return [dir]
matchGlob :: Glob -> String -> Bool
matchGlob = goStart
where
go, goStart :: [GlobPiece] -> String -> Bool
goStart (WildCard:_) ('.':_) = False
goStart (Union globs:rest) cs = any (\glob -> goStart (glob ++ rest) cs)
globs
goStart rest cs = go rest cs
go [] "" = True
go (Literal lit:rest) cs
| Just cs' <- stripPrefix lit cs
= go rest cs'
| otherwise = False
go [WildCard] "" = True
go (WildCard:rest) (c:cs) = go rest (c:cs) || go (WildCard:rest) cs
go (Union globs:rest) cs = any (\glob -> go (glob ++ rest) cs) globs
go [] (_:_) = False
go (_:_) "" = False
parseFilePathGlob :: String -> Either String FilePathGlob
parseFilePathGlob = eitherParsec
parseFilePathGlobRel :: String -> Either String FilePathGlobRel
parseFilePathGlobRel = eitherParsec
instance Parsec FilePathGlob where
parsec = do
root <- parsec
(FilePathGlob root <$> parsec) <|> alt2 root
where alt2 root = do
when (root == FilePathRelative) (fail "Unexpected relative path")
return (FilePathGlob root GlobDirTrailing)
instance Pretty FilePathGlob where
pretty (FilePathGlob root pathglob) = pretty root Disp.<> pretty pathglob
instance Parsec FilePathRoot where
parsec = (char '/' $> FilePathRoot "/")
<|> (char '~' *> char '/' $> FilePathHomeDir)
<|> try parseDrive
<|> return FilePathRelative
where isAsciiAlpha c = isAsciiLower c || isAsciiUpper c
parseDrive = do
drive <- satisfy isAsciiAlpha
_ <- char ':'
_ <- char '/' <|> char '\\'
return (FilePathRoot (toUpper drive : ":\\"))
instance Pretty FilePathRoot where
pretty FilePathRelative = Disp.empty
pretty (FilePathRoot root) = Disp.text root
pretty FilePathHomeDir = Disp.char '~' Disp.<> Disp.char '/'
instance Parsec FilePathGlobRel where
parsec = parsePath
where parsePath = do
globpieces <- parseGlob
try (asDir globpieces) <|> try (asTDir globpieces) <|> asFile globpieces
asDir glob = do dirSep
GlobDir glob <$> parsePath
asTDir glob = dirSep $> GlobDir glob GlobDirTrailing
asFile glob = return (GlobFile glob)
dirSep = (char '/' $> ()) <|> notEscapingBackslash
notEscapingBackslash =
char '\\' *> notFollowedBy (satisfy isGlobEscapedChar)
instance Pretty FilePathGlobRel where
pretty (GlobDir glob pathglob) = dispGlob glob
Disp.<> Disp.char '/'
Disp.<> pretty pathglob
pretty (GlobFile glob) = dispGlob glob
pretty GlobDirTrailing = Disp.empty
dispGlob :: Glob -> Disp.Doc
dispGlob = Disp.hcat . map dispPiece
where
dispPiece WildCard = Disp.char '*'
dispPiece (Literal str) = Disp.text (escape str)
dispPiece (Union globs) = Disp.braces
(Disp.hcat (Disp.punctuate
(Disp.char ',')
(map dispGlob globs)))
escape [] = []
escape (c:cs)
| isGlobEscapedChar c = '\\' : c : escape cs
| otherwise = c : escape cs
parseGlob :: CharParsing m => m Glob
parseGlob = some parsePiece
where
parsePiece = literal <|> wildcard <|> union
wildcard = char '*' $> WildCard
union = between (char '{') (char '}') $
fmap Union (sepBy1 parseGlob (char ','))
literal = Literal `fmap` litchars1
litchar = normal <|> escape
normal = satisfy (\c -> not (isGlobEscapedChar c)
&& c /= '/' && c /= '\\')
escape = char '\\' *> satisfy isGlobEscapedChar
litchars1 = liftA2 (:) litchar litchars
litchars = litchars1 <|> pure []
isGlobEscapedChar :: Char -> Bool
isGlobEscapedChar '*' = True
isGlobEscapedChar '{' = True
isGlobEscapedChar '}' = True
isGlobEscapedChar ',' = True
isGlobEscapedChar _ = False
|
9590d3f3a1a799e5cb153dbc860f0c108fdf1888bd20bce5c42b4b0db3afcf17 | exoscale/clojure-kubernetes-client | v1_attached_volume.clj | (ns clojure-kubernetes-client.specs.v1-attached-volume
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
)
(:import (java.io File)))
(declare v1-attached-volume-data v1-attached-volume)
(def v1-attached-volume-data
{
(ds/req :devicePath) string?
(ds/req :name) string?
})
(def v1-attached-volume
(ds/spec
{:name ::v1-attached-volume
:spec v1-attached-volume-data}))
| null | https://raw.githubusercontent.com/exoscale/clojure-kubernetes-client/79d84417f28d048c5ac015c17e3926c73e6ac668/src/clojure_kubernetes_client/specs/v1_attached_volume.clj | clojure | (ns clojure-kubernetes-client.specs.v1-attached-volume
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
)
(:import (java.io File)))
(declare v1-attached-volume-data v1-attached-volume)
(def v1-attached-volume-data
{
(ds/req :devicePath) string?
(ds/req :name) string?
})
(def v1-attached-volume
(ds/spec
{:name ::v1-attached-volume
:spec v1-attached-volume-data}))
| |
04a5109040d5640610c673a0cf6325c70c97702668d7047e4dba9c6e39151a96 | MaskRay/OJHaskell | E.hs | # LANGUAGE FlexibleContexts , ScopedTypeVariables #
import Control.Monad
import Data.Array.IArray
import Data.Foldable
import Data.Functor
import Data.List hiding (foldl')
import Data.Maybe
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
int = fst . fromJust . B.readInt
ints = map int . B.words
has :: (Integral i, Ix i, Ord t, IArray a (t, t)) => a i (t, t) -> (t, t) -> Bool
has es (u, v) = not $ i < h && es!i == x
where
x = if u < v then (u, v) else (v, u)
go l h =
if l == h
then l
else
let m = (l+h) `div` 2 in
if es!m < x
then go (m+1) h
else go l m
(l, h) = succ <$> bounds es
i = go l h
dfs es un u =
foldl' (dfs es) (S.difference un vs) vs
where
vs = S.filter (\v -> has es (u, v)) un
main = do
[n, m, k] <- ints <$> B.getLine
es :: Array Int (Int,Int) <- ((listArray (0, m-1) . sort) <$>) . replicateM m $ do
[u, v] <- ints <$> B.getLine
return $ if u < v then (u-1, v-1) else (v-1, u-1)
let deg0 = foldl' (\c (u,v) -> c + fromEnum (u == 0 || v == 0)) 0 es
let (un, ncomp) = foldl' (\(un, ncomp) u ->
if has es (0,u) && S.member u un
then (dfs es un u, ncomp+1)
else (un, ncomp)
) (S.fromList [1..n-1], 0) [1..n-1]
if S.null un && ncomp <= k && k <= n-1-deg0
then putStrLn "possible"
else putStrLn "impossible"
| null | https://raw.githubusercontent.com/MaskRay/OJHaskell/ba24050b2480619f10daa7d37fca558182ba006c/Codeforces/653/E.hs | haskell | # LANGUAGE FlexibleContexts , ScopedTypeVariables #
import Control.Monad
import Data.Array.IArray
import Data.Foldable
import Data.Functor
import Data.List hiding (foldl')
import Data.Maybe
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
int = fst . fromJust . B.readInt
ints = map int . B.words
has :: (Integral i, Ix i, Ord t, IArray a (t, t)) => a i (t, t) -> (t, t) -> Bool
has es (u, v) = not $ i < h && es!i == x
where
x = if u < v then (u, v) else (v, u)
go l h =
if l == h
then l
else
let m = (l+h) `div` 2 in
if es!m < x
then go (m+1) h
else go l m
(l, h) = succ <$> bounds es
i = go l h
dfs es un u =
foldl' (dfs es) (S.difference un vs) vs
where
vs = S.filter (\v -> has es (u, v)) un
main = do
[n, m, k] <- ints <$> B.getLine
es :: Array Int (Int,Int) <- ((listArray (0, m-1) . sort) <$>) . replicateM m $ do
[u, v] <- ints <$> B.getLine
return $ if u < v then (u-1, v-1) else (v-1, u-1)
let deg0 = foldl' (\c (u,v) -> c + fromEnum (u == 0 || v == 0)) 0 es
let (un, ncomp) = foldl' (\(un, ncomp) u ->
if has es (0,u) && S.member u un
then (dfs es un u, ncomp+1)
else (un, ncomp)
) (S.fromList [1..n-1], 0) [1..n-1]
if S.null un && ncomp <= k && k <= n-1-deg0
then putStrLn "possible"
else putStrLn "impossible"
| |
e3729dae86b641915bc18638fba4a94617a55da291c59365536e25473d8fef0e | jeanparpaillon/erlang-dbus | dbus_hex.erl | 2014
@author < >
%% @doc
%%
%% @end
-module(dbus_hex).
%%--------------------------------------------------------------------
%% External exports
%%--------------------------------------------------------------------
-export([encode/1,
decode/1]).
%%====================================================================
%% External functions
%%====================================================================
%% @doc Encode a binary string as hex
%% @end
-spec encode(binary()) -> binary().
encode(Bin) ->
encode(Bin, <<>>).
%% @doc Decode an hex string
%% @end
-spec decode(binary()) -> binary().
decode(Bin) ->
decode(Bin, <<>>).
%%%
%%% Priv
%%%
decode(<<>>, Acc) ->
Acc;
decode(<< $\s, _/binary >>, Acc) ->
Acc;
decode(<< $\r, _/binary >>, Acc) ->
Acc;
decode(<< $\n, _/binary >>, Acc) ->
Acc;
decode(<< H, L, Rest/binary >>, Acc) ->
C = hex_to_int(H) * 16 + hex_to_int(L),
decode(Rest, << Acc/binary, C >>).
hex_to_int(C) when C >= $0, C =< $9 ->
C - $0;
hex_to_int(C) when C >= $a, C =< $f ->
C - $a + 10.
encode(<<>>, Acc) ->
Acc;
encode(<< C:8, Rest/binary >>, Acc) ->
{L, H} = int_to_hex(C),
encode(Rest, << Acc/binary, L, H >>).
int_to_hex(N) when N < 256 ->
{ hex(N div 16), hex(N rem 16) }.
hex(N) when N < 10 ->
$0 + N;
hex(N) when N >= 10, N < 16 ->
$a + (N-10).
| null | https://raw.githubusercontent.com/jeanparpaillon/erlang-dbus/80640bf735badca4a18753f47abbc0072b546c29/src/dbus_hex.erl | erlang | @doc
@end
--------------------------------------------------------------------
External exports
--------------------------------------------------------------------
====================================================================
External functions
====================================================================
@doc Encode a binary string as hex
@end
@doc Decode an hex string
@end
Priv
| 2014
@author < >
-module(dbus_hex).
-export([encode/1,
decode/1]).
-spec encode(binary()) -> binary().
encode(Bin) ->
encode(Bin, <<>>).
-spec decode(binary()) -> binary().
decode(Bin) ->
decode(Bin, <<>>).
decode(<<>>, Acc) ->
Acc;
decode(<< $\s, _/binary >>, Acc) ->
Acc;
decode(<< $\r, _/binary >>, Acc) ->
Acc;
decode(<< $\n, _/binary >>, Acc) ->
Acc;
decode(<< H, L, Rest/binary >>, Acc) ->
C = hex_to_int(H) * 16 + hex_to_int(L),
decode(Rest, << Acc/binary, C >>).
hex_to_int(C) when C >= $0, C =< $9 ->
C - $0;
hex_to_int(C) when C >= $a, C =< $f ->
C - $a + 10.
encode(<<>>, Acc) ->
Acc;
encode(<< C:8, Rest/binary >>, Acc) ->
{L, H} = int_to_hex(C),
encode(Rest, << Acc/binary, L, H >>).
int_to_hex(N) when N < 256 ->
{ hex(N div 16), hex(N rem 16) }.
hex(N) when N < 10 ->
$0 + N;
hex(N) when N >= 10, N < 16 ->
$a + (N-10).
|
86ef228cc345788e2143b48e295b0f395b73191776c08097d5ccfac00c27ff5c | alanb2718/wallingford | integral-numeric-tests.rkt | #lang s-exp rosette
;; unit tests for integral using a numeric solution
These are like integral - symbolic - tests , except for the first one ( integral - in - always ) , which has some additional time advances
;; to exercise that part of the code.
(require rackunit rackunit/text-ui rosette/lib/roseunit)
(require "../core/wallingford.rkt")
(require "../applications/geothings.rkt")
(require "../reactive/reactive.rkt")
(provide integral-numeric-tests)
; helper function to test for approximate equality (pretty coarse for integration tests)
(define (approx-equal? x y)
(or (and (zero? x) (zero? y))
(< (abs (- x y)) 0.01)))
(define (integral-in-always)
(test-case
"test call to integral in an always"
(define tester%
(class reactive-thing%
(inherit milliseconds)
(super-new)
(define-public-symbolic* x y real?)
(always (equal? x (integral 2 #:numeric)))
(always (equal? y (integral (milliseconds) #:numeric)))
))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 4)
(check equal? (send-syncd r milliseconds-syncd) 4)
(check equal? (send r get-x) 8)
(check equal? (send r get-y) 8)
(send-syncd r advance-time-syncd 50)
(check equal? (send-syncd r milliseconds-syncd) 50)
(check equal? (send r get-x) 100)
(check equal? (send r get-y) 1250)
))
(define (integral-in-simple-while-hit-start)
(test-case
"test calls to integral in a simple while that is true for one time interval (and happen to get time when the interval begins)"
(define tester%
(class reactive-thing%
(inherit milliseconds)
(super-new)
(define-public-symbolic* x real?)
(assert (equal? x 0))
(send this solve)
(stay x)
(while (and (>= (milliseconds) 50) (<= (milliseconds) 110))
(assert (equal? x (integral 2 #:numeric))))))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 5)
(check equal? (send r get-x) 0) ; outside of while at this time, so x should have its initial value
(send-syncd r advance-time-syncd 34)
(check equal? (send r get-x) 0) ; still outside of while
(send-syncd r advance-time-syncd 42)
(check equal? (send r get-x) 0) ; still outside of while
(send-syncd r advance-time-syncd 50) ; while should now be active (but just starting)
(check equal? (send r get-x) 0)
(send-syncd r advance-time-syncd 60) ; while still active
(check equal? (send r get-x) 20)
(send-syncd r advance-time-syncd 75)
(check equal? (send r get-x) 50)
while becomes inactive at 110
(check equal? (send r get-x) 120)
(send-syncd r advance-time-syncd 350)
(check equal? (send r get-x) 120)))
(define (integral-in-simple-while-miss-start)
(test-case
"test calls to integral in a simple while that is true for one time interval (but miss the time the interval begins)"
(define tester%
(class reactive-thing%
(inherit milliseconds)
(super-new)
(define-public-symbolic* x real?)
(assert (equal? x 0))
(send this solve)
(stay x)
(while (and (>= (milliseconds) 10) (<= (milliseconds) 100))
(assert (equal? x (integral 2 #:numeric))))))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 5)
(check equal? (send r get-x) 0)
(send-syncd r advance-time-syncd 60)
(check equal? (send r get-x) 100)
(send-syncd r advance-time-syncd 75)
(check equal? (send r get-x) 130)
while becomes inactive at 100
(check equal? (send r get-x) 180)))
(define (integral-in-repeating-while)
(test-case
"test calls to integral in a while that is true for multiple time intervals"
(define tester%
(class reactive-thing%
(inherit milliseconds)
(super-new)
(define-public-symbolic* x real?)
(assert (equal? x 0))
(send this solve)
(stay x)
the while test holds for the first 10 milliseconds of every 100 millisecond interval
(while (<= (remainder (milliseconds) 100) 10)
#:interesting-time (let ([r (remainder (milliseconds) 100)])
(cond [(zero? r) 'first]
[(equal? r 10) 'last]
[else #f]))
(assert (equal? x (integral 2 #:numeric))))))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 5)
(check equal? (send r get-x) 10)
(send-syncd r advance-time-syncd 10)
(check equal? (send r get-x) 20)
(send-syncd r advance-time-syncd 50)
(check equal? (send r get-x) 20)
(send-syncd r advance-time-syncd 100)
(check equal? (send r get-x) 0)
(send-syncd r advance-time-syncd 105)
(check equal? (send r get-x) 10)
(send-syncd r advance-time-syncd 150)
(check equal? (send r get-x) 20)))
(define (integral-with-explict-variable-of-integration)
(test-case
"test call to integral with an explicit variable of integration"
(define tester%
(class reactive-thing%
(inherit milliseconds seconds)
(super-new)
(define-public-symbolic* s x1 x2 y1 y2 z1 z2 real?)
(always (equal? s (* 2 (milliseconds))))
(always (equal? x1 (integral 2 #:var (milliseconds) #:numeric)))
(always (equal? x2 (integral (milliseconds) #:var (milliseconds) #:numeric)))
(always (equal? y1 (integral 2 #:var (seconds) #:numeric)))
(always (equal? y2 (integral (seconds) #:var (seconds) #:numeric)))
(always (equal? z1 (integral 2 #:var s #:numeric)))
(always (equal? z2 (integral s #:var s #:numeric)))))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 100)
(check equal? (send-syncd r milliseconds-syncd) 100)
(check equal? (send r get-x1) 200)
(check equal? (send r get-x2) 5000)
(check-true (approx-equal? (send r get-y1) 0.2))
or this version works too , but not an equal ? test with 0.2 ( since y1 will be an exact number rather than a float )
( check equal ? ( send r get - y1 ) 1/5 )
(check-true (approx-equal? (send r get-y2) 0.005))
(check equal? (send r get-z1) 400)
(check equal? (send r get-z2) 20000)))
(define (integral-sin-milliseconds)
(test-case
"test call to integral with a nonlinear expression: (sin (milliseconds-evaluated))"
(define tester%
(class reactive-thing%
(inherit milliseconds milliseconds-evaluated)
(super-new)
(define-public-symbolic* x real?)
(always (equal? x (integral (sin (milliseconds-evaluated)) #:numeric #:dt 0.1)))
))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 0.6)
(check approx-equal? (send-syncd r milliseconds-syncd) 0.6)
( - ( - ( cos 0.6 ) ) ( - ( cos 0.0 ) ) ) is the symbolic solution
(check approx-equal? (send r get-x) (- (- (cos 0.6)) (- (cos 0.0))))
(send-syncd r advance-time-syncd 3.0)
(check equal? (send-syncd r milliseconds-syncd) 3.0)
(check approx-equal? (send r get-x) (- (- (cos 3.0)) (- (cos 0.0))))
))
(define (integral-sin-milliseconds-one-thousandth)
(test-case
"test call to integral with another nonlinear expression: (sin (* 0.001 (milliseconds-evaluated)))"
(define tester%
(class reactive-thing%
(inherit milliseconds milliseconds-evaluated)
(super-new)
(define-public-symbolic* x real?)
(always (equal? x (integral (sin (* 0.001 (milliseconds-evaluated))))))
))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 500)
(check approx-equal? (send-syncd r milliseconds-syncd) 500)
(check approx-equal? (send r get-x) (- 1000.0 (* 1000.0 (cos 0.5))))
(send-syncd r advance-time-syncd 1000)
(check approx-equal? (send r get-x) (- 1000.0 (* 1000.0 (cos 1.0))))
))
(define (integral-sin-seconds)
(test-case
"test call to integral with another nonlinear expression: (sin (seconds))"
(define tester%
(class reactive-thing%
(inherit milliseconds seconds)
(super-new)
(define-public-symbolic* x real?)
(always (equal? x (integral (sin (seconds)) #:var (seconds))))
))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 500)
(check approx-equal? (send-syncd r milliseconds-syncd) 500)
(check approx-equal? (send r get-x) (- (- (cos 0.5)) (- (cos 0.0))))
(send-syncd r advance-time-syncd 1200)
(check equal? (send-syncd r milliseconds-syncd) 1200)
(check approx-equal? (send r get-x) (- (- (cos 1.2)) (- (cos 0.0))))
))
(define (integral-multiple-dts)
(test-case
"test call to integrals with multiple values for dt"
; this test uses a hack (side effect in the integral expression) to test that we advance to the correct times
(define tester%
(class reactive-thing%
(inherit milliseconds milliseconds-evaluated)
(super-new)
(define-public-symbolic* x y z real?)
(define times (mutable-set))
(define/public (get-times) times)
(always (equal? x (integral (begin (set-add! times (milliseconds-evaluated)) 2) #:numeric #:dt 7)))
(always (equal? y (integral (begin (set-add! times (milliseconds-evaluated)) 3) #:numeric #:dt 13)))
uses default of 10
))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 40)
(check equal? (send-syncd r milliseconds-syncd) 40)
(check equal? (send r get-x) 80)
(check equal? (send r get-y) 120)
(check equal? (send r get-z) 200)
(check equal? (send r get-times) (list->mutable-set '(0 7 14 21 28 35 40)))
))
(define integral-numeric-tests
(test-suite+
"unit tests for integral using a numeric solution"
(integral-in-always)
(integral-in-simple-while-hit-start)
(integral-in-simple-while-miss-start)
(integral-in-repeating-while)
(integral-with-explict-variable-of-integration)
(integral-sin-milliseconds)
(integral-sin-milliseconds-one-thousandth)
(integral-sin-seconds)
(integral-multiple-dts)
))
(time (run-tests integral-numeric-tests))
| null | https://raw.githubusercontent.com/alanb2718/wallingford/9dd436c29f737d210c5b87dc1b86b2924c0c5970/tests/integral-numeric-tests.rkt | racket | unit tests for integral using a numeric solution
to exercise that part of the code.
helper function to test for approximate equality (pretty coarse for integration tests)
outside of while at this time, so x should have its initial value
still outside of while
still outside of while
while should now be active (but just starting)
while still active
this test uses a hack (side effect in the integral expression) to test that we advance to the correct times | #lang s-exp rosette
These are like integral - symbolic - tests , except for the first one ( integral - in - always ) , which has some additional time advances
(require rackunit rackunit/text-ui rosette/lib/roseunit)
(require "../core/wallingford.rkt")
(require "../applications/geothings.rkt")
(require "../reactive/reactive.rkt")
(provide integral-numeric-tests)
(define (approx-equal? x y)
(or (and (zero? x) (zero? y))
(< (abs (- x y)) 0.01)))
(define (integral-in-always)
(test-case
"test call to integral in an always"
(define tester%
(class reactive-thing%
(inherit milliseconds)
(super-new)
(define-public-symbolic* x y real?)
(always (equal? x (integral 2 #:numeric)))
(always (equal? y (integral (milliseconds) #:numeric)))
))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 4)
(check equal? (send-syncd r milliseconds-syncd) 4)
(check equal? (send r get-x) 8)
(check equal? (send r get-y) 8)
(send-syncd r advance-time-syncd 50)
(check equal? (send-syncd r milliseconds-syncd) 50)
(check equal? (send r get-x) 100)
(check equal? (send r get-y) 1250)
))
(define (integral-in-simple-while-hit-start)
(test-case
"test calls to integral in a simple while that is true for one time interval (and happen to get time when the interval begins)"
(define tester%
(class reactive-thing%
(inherit milliseconds)
(super-new)
(define-public-symbolic* x real?)
(assert (equal? x 0))
(send this solve)
(stay x)
(while (and (>= (milliseconds) 50) (<= (milliseconds) 110))
(assert (equal? x (integral 2 #:numeric))))))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 5)
(send-syncd r advance-time-syncd 34)
(send-syncd r advance-time-syncd 42)
(check equal? (send r get-x) 0)
(check equal? (send r get-x) 20)
(send-syncd r advance-time-syncd 75)
(check equal? (send r get-x) 50)
while becomes inactive at 110
(check equal? (send r get-x) 120)
(send-syncd r advance-time-syncd 350)
(check equal? (send r get-x) 120)))
(define (integral-in-simple-while-miss-start)
(test-case
"test calls to integral in a simple while that is true for one time interval (but miss the time the interval begins)"
(define tester%
(class reactive-thing%
(inherit milliseconds)
(super-new)
(define-public-symbolic* x real?)
(assert (equal? x 0))
(send this solve)
(stay x)
(while (and (>= (milliseconds) 10) (<= (milliseconds) 100))
(assert (equal? x (integral 2 #:numeric))))))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 5)
(check equal? (send r get-x) 0)
(send-syncd r advance-time-syncd 60)
(check equal? (send r get-x) 100)
(send-syncd r advance-time-syncd 75)
(check equal? (send r get-x) 130)
while becomes inactive at 100
(check equal? (send r get-x) 180)))
(define (integral-in-repeating-while)
(test-case
"test calls to integral in a while that is true for multiple time intervals"
(define tester%
(class reactive-thing%
(inherit milliseconds)
(super-new)
(define-public-symbolic* x real?)
(assert (equal? x 0))
(send this solve)
(stay x)
the while test holds for the first 10 milliseconds of every 100 millisecond interval
(while (<= (remainder (milliseconds) 100) 10)
#:interesting-time (let ([r (remainder (milliseconds) 100)])
(cond [(zero? r) 'first]
[(equal? r 10) 'last]
[else #f]))
(assert (equal? x (integral 2 #:numeric))))))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 5)
(check equal? (send r get-x) 10)
(send-syncd r advance-time-syncd 10)
(check equal? (send r get-x) 20)
(send-syncd r advance-time-syncd 50)
(check equal? (send r get-x) 20)
(send-syncd r advance-time-syncd 100)
(check equal? (send r get-x) 0)
(send-syncd r advance-time-syncd 105)
(check equal? (send r get-x) 10)
(send-syncd r advance-time-syncd 150)
(check equal? (send r get-x) 20)))
(define (integral-with-explict-variable-of-integration)
(test-case
"test call to integral with an explicit variable of integration"
(define tester%
(class reactive-thing%
(inherit milliseconds seconds)
(super-new)
(define-public-symbolic* s x1 x2 y1 y2 z1 z2 real?)
(always (equal? s (* 2 (milliseconds))))
(always (equal? x1 (integral 2 #:var (milliseconds) #:numeric)))
(always (equal? x2 (integral (milliseconds) #:var (milliseconds) #:numeric)))
(always (equal? y1 (integral 2 #:var (seconds) #:numeric)))
(always (equal? y2 (integral (seconds) #:var (seconds) #:numeric)))
(always (equal? z1 (integral 2 #:var s #:numeric)))
(always (equal? z2 (integral s #:var s #:numeric)))))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 100)
(check equal? (send-syncd r milliseconds-syncd) 100)
(check equal? (send r get-x1) 200)
(check equal? (send r get-x2) 5000)
(check-true (approx-equal? (send r get-y1) 0.2))
or this version works too , but not an equal ? test with 0.2 ( since y1 will be an exact number rather than a float )
( check equal ? ( send r get - y1 ) 1/5 )
(check-true (approx-equal? (send r get-y2) 0.005))
(check equal? (send r get-z1) 400)
(check equal? (send r get-z2) 20000)))
(define (integral-sin-milliseconds)
(test-case
"test call to integral with a nonlinear expression: (sin (milliseconds-evaluated))"
(define tester%
(class reactive-thing%
(inherit milliseconds milliseconds-evaluated)
(super-new)
(define-public-symbolic* x real?)
(always (equal? x (integral (sin (milliseconds-evaluated)) #:numeric #:dt 0.1)))
))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 0.6)
(check approx-equal? (send-syncd r milliseconds-syncd) 0.6)
( - ( - ( cos 0.6 ) ) ( - ( cos 0.0 ) ) ) is the symbolic solution
(check approx-equal? (send r get-x) (- (- (cos 0.6)) (- (cos 0.0))))
(send-syncd r advance-time-syncd 3.0)
(check equal? (send-syncd r milliseconds-syncd) 3.0)
(check approx-equal? (send r get-x) (- (- (cos 3.0)) (- (cos 0.0))))
))
(define (integral-sin-milliseconds-one-thousandth)
(test-case
"test call to integral with another nonlinear expression: (sin (* 0.001 (milliseconds-evaluated)))"
(define tester%
(class reactive-thing%
(inherit milliseconds milliseconds-evaluated)
(super-new)
(define-public-symbolic* x real?)
(always (equal? x (integral (sin (* 0.001 (milliseconds-evaluated))))))
))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 500)
(check approx-equal? (send-syncd r milliseconds-syncd) 500)
(check approx-equal? (send r get-x) (- 1000.0 (* 1000.0 (cos 0.5))))
(send-syncd r advance-time-syncd 1000)
(check approx-equal? (send r get-x) (- 1000.0 (* 1000.0 (cos 1.0))))
))
(define (integral-sin-seconds)
(test-case
"test call to integral with another nonlinear expression: (sin (seconds))"
(define tester%
(class reactive-thing%
(inherit milliseconds seconds)
(super-new)
(define-public-symbolic* x real?)
(always (equal? x (integral (sin (seconds)) #:var (seconds))))
))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 500)
(check approx-equal? (send-syncd r milliseconds-syncd) 500)
(check approx-equal? (send r get-x) (- (- (cos 0.5)) (- (cos 0.0))))
(send-syncd r advance-time-syncd 1200)
(check equal? (send-syncd r milliseconds-syncd) 1200)
(check approx-equal? (send r get-x) (- (- (cos 1.2)) (- (cos 0.0))))
))
(define (integral-multiple-dts)
(test-case
"test call to integrals with multiple values for dt"
(define tester%
(class reactive-thing%
(inherit milliseconds milliseconds-evaluated)
(super-new)
(define-public-symbolic* x y z real?)
(define times (mutable-set))
(define/public (get-times) times)
(always (equal? x (integral (begin (set-add! times (milliseconds-evaluated)) 2) #:numeric #:dt 7)))
(always (equal? y (integral (begin (set-add! times (milliseconds-evaluated)) 3) #:numeric #:dt 13)))
uses default of 10
))
(define r (new tester%))
(send r start)
(send-syncd r advance-time-syncd 40)
(check equal? (send-syncd r milliseconds-syncd) 40)
(check equal? (send r get-x) 80)
(check equal? (send r get-y) 120)
(check equal? (send r get-z) 200)
(check equal? (send r get-times) (list->mutable-set '(0 7 14 21 28 35 40)))
))
(define integral-numeric-tests
(test-suite+
"unit tests for integral using a numeric solution"
(integral-in-always)
(integral-in-simple-while-hit-start)
(integral-in-simple-while-miss-start)
(integral-in-repeating-while)
(integral-with-explict-variable-of-integration)
(integral-sin-milliseconds)
(integral-sin-milliseconds-one-thousandth)
(integral-sin-seconds)
(integral-multiple-dts)
))
(time (run-tests integral-numeric-tests))
|
77f4f39eeb0b05c00f6af06349735e8e414db456238cdc478a3e8d9f084a1bb8 | pirapira/coq2rust | sos.ml | (* ========================================================================= *)
- This code originates from HOL LIGHT 2.30
( see file LICENSE.sos for license , copyright and disclaimer )
- ( ) has isolated the HOL
(* independent bits *)
- ( ) is using it to feed micromega
(* ========================================================================= *)
(* ========================================================================= *)
Nonlinear universal reals procedure using SOS decomposition .
(* ========================================================================= *)
open Num;;
open Sos_types;;
open Sos_lib;;
(*
prioritize_real();;
*)
let debugging = ref false;;
exception Sanity;;
exception Unsolvable;;
(* ------------------------------------------------------------------------- *)
(* Turn a rational into a decimal string with d sig digits. *)
(* ------------------------------------------------------------------------- *)
let decimalize =
let rec normalize y =
if abs_num y </ Int 1 // Int 10 then normalize (Int 10 */ y) - 1
else if abs_num y >=/ Int 1 then normalize (y // Int 10) + 1
else 0 in
fun d x ->
if x =/ Int 0 then "0.0" else
let y = abs_num x in
let e = normalize y in
let z = pow10(-e) */ y +/ Int 1 in
let k = round_num(pow10 d */ z) in
(if x </ Int 0 then "-0." else "0.") ^
implode(List.tl(explode(string_of_num k))) ^
(if e = 0 then "" else "e"^string_of_int e);;
(* ------------------------------------------------------------------------- *)
(* Iterations over numbers, and lists indexed by numbers. *)
(* ------------------------------------------------------------------------- *)
let rec itern k l f a =
match l with
[] -> a
| h::t -> itern (k + 1) t f (f h k a);;
let rec iter (m,n) f a =
if n < m then a
else iter (m+1,n) f (f m a);;
(* ------------------------------------------------------------------------- *)
(* The main types. *)
(* ------------------------------------------------------------------------- *)
type vector = int*(int,num)func;;
type matrix = (int*int)*(int*int,num)func;;
type monomial = (vname,int)func;;
type poly = (monomial,num)func;;
(* ------------------------------------------------------------------------- *)
Assignment avoiding zeros .
(* ------------------------------------------------------------------------- *)
let (|-->) x y a = if y =/ Int 0 then a else (x |-> y) a;;
(* ------------------------------------------------------------------------- *)
(* This can be generic. *)
(* ------------------------------------------------------------------------- *)
let element (d,v) i = tryapplyd v i (Int 0);;
let mapa f (d,v) =
d,foldl (fun a i c -> (i |--> f(c)) a) undefined v;;
let is_zero (d,v) =
match v with
Empty -> true
| _ -> false;;
(* ------------------------------------------------------------------------- *)
Vectors . Conventionally indexed 1 .. n.
(* ------------------------------------------------------------------------- *)
let vector_0 n = (n,undefined:vector);;
let dim (v:vector) = fst v;;
let vector_const c n =
if c =/ Int 0 then vector_0 n
else (n,itlist (fun k -> k |-> c) (1--n) undefined :vector);;
let vector_1 = vector_const (Int 1);;
let vector_cmul c (v:vector) =
let n = dim v in
if c =/ Int 0 then vector_0 n
else n,mapf (fun x -> c */ x) (snd v)
let vector_neg (v:vector) = (fst v,mapf minus_num (snd v) :vector);;
let vector_add (v1:vector) (v2:vector) =
let m = dim v1 and n = dim v2 in
if m <> n then failwith "vector_add: incompatible dimensions" else
(n,combine (+/) (fun x -> x =/ Int 0) (snd v1) (snd v2) :vector);;
let vector_sub v1 v2 = vector_add v1 (vector_neg v2);;
let vector_dot (v1:vector) (v2:vector) =
let m = dim v1 and n = dim v2 in
if m <> n then failwith "vector_add: incompatible dimensions" else
foldl (fun a i x -> x +/ a) (Int 0)
(combine ( */ ) (fun x -> x =/ Int 0) (snd v1) (snd v2));;
let vector_of_list l =
let n = List.length l in
(n,itlist2 (|->) (1--n) l undefined :vector);;
(* ------------------------------------------------------------------------- *)
Matrices ; again rows and columns indexed from 1 .
(* ------------------------------------------------------------------------- *)
let matrix_0 (m,n) = ((m,n),undefined:matrix);;
let dimensions (m:matrix) = fst m;;
let matrix_const c (m,n as mn) =
if m <> n then failwith "matrix_const: needs to be square"
else if c =/ Int 0 then matrix_0 mn
else (mn,itlist (fun k -> (k,k) |-> c) (1--n) undefined :matrix);;
let matrix_1 = matrix_const (Int 1);;
let matrix_cmul c (m:matrix) =
let (i,j) = dimensions m in
if c =/ Int 0 then matrix_0 (i,j)
else (i,j),mapf (fun x -> c */ x) (snd m);;
let matrix_neg (m:matrix) = (dimensions m,mapf minus_num (snd m) :matrix);;
let matrix_add (m1:matrix) (m2:matrix) =
let d1 = dimensions m1 and d2 = dimensions m2 in
if d1 <> d2 then failwith "matrix_add: incompatible dimensions"
else (d1,combine (+/) (fun x -> x =/ Int 0) (snd m1) (snd m2) :matrix);;
let matrix_sub m1 m2 = matrix_add m1 (matrix_neg m2);;
let row k (m:matrix) =
let i,j = dimensions m in
(j,
foldl (fun a (i,j) c -> if i = k then (j |-> c) a else a) undefined (snd m)
: vector);;
let column k (m:matrix) =
let i,j = dimensions m in
(i,
foldl (fun a (i,j) c -> if j = k then (i |-> c) a else a) undefined (snd m)
: vector);;
let transp (m:matrix) =
let i,j = dimensions m in
((j,i),foldl (fun a (i,j) c -> ((j,i) |-> c) a) undefined (snd m) :matrix);;
let diagonal (v:vector) =
let n = dim v in
((n,n),foldl (fun a i c -> ((i,i) |-> c) a) undefined (snd v) : matrix);;
let matrix_of_list l =
let m = List.length l in
if m = 0 then matrix_0 (0,0) else
let n = List.length (List.hd l) in
(m,n),itern 1 l (fun v i -> itern 1 v (fun c j -> (i,j) |-> c)) undefined;;
(* ------------------------------------------------------------------------- *)
(* Monomials. *)
(* ------------------------------------------------------------------------- *)
let monomial_eval assig (m:monomial) =
foldl (fun a x k -> a */ power_num (apply assig x) (Int k))
(Int 1) m;;
let monomial_1 = (undefined:monomial);;
let monomial_var x = (x |=> 1 :monomial);;
let (monomial_mul:monomial->monomial->monomial) =
combine (+) (fun x -> false);;
let monomial_pow (m:monomial) k =
if k = 0 then monomial_1
else mapf (fun x -> k * x) m;;
let monomial_divides (m1:monomial) (m2:monomial) =
foldl (fun a x k -> tryapplyd m2 x 0 >= k && a) true m1;;
let monomial_div (m1:monomial) (m2:monomial) =
let m = combine (+) (fun x -> x = 0) m1 (mapf (fun x -> -x) m2) in
if foldl (fun a x k -> k >= 0 && a) true m then m
else failwith "monomial_div: non-divisible";;
let monomial_degree x (m:monomial) = tryapplyd m x 0;;
let monomial_lcm (m1:monomial) (m2:monomial) =
(itlist (fun x -> x |-> max (monomial_degree x m1) (monomial_degree x m2))
(union (dom m1) (dom m2)) undefined :monomial);;
let monomial_multidegree (m:monomial) = foldl (fun a x k -> k + a) 0 m;;
let monomial_variables m = dom m;;
(* ------------------------------------------------------------------------- *)
(* Polynomials. *)
(* ------------------------------------------------------------------------- *)
let eval assig (p:poly) =
foldl (fun a m c -> a +/ c */ monomial_eval assig m) (Int 0) p;;
let poly_0 = (undefined:poly);;
let poly_isconst (p:poly) = foldl (fun a m c -> m = monomial_1 && a) true p;;
let poly_var x = ((monomial_var x) |=> Int 1 :poly);;
let poly_const c =
if c =/ Int 0 then poly_0 else (monomial_1 |=> c);;
let poly_cmul c (p:poly) =
if c =/ Int 0 then poly_0
else mapf (fun x -> c */ x) p;;
let poly_neg (p:poly) = (mapf minus_num p :poly);;
let poly_add (p1:poly) (p2:poly) =
(combine (+/) (fun x -> x =/ Int 0) p1 p2 :poly);;
let poly_sub p1 p2 = poly_add p1 (poly_neg p2);;
let poly_cmmul (c,m) (p:poly) =
if c =/ Int 0 then poly_0
else if m = monomial_1 then mapf (fun d -> c */ d) p
else foldl (fun a m' d -> (monomial_mul m m' |-> c */ d) a) poly_0 p;;
let poly_mul (p1:poly) (p2:poly) =
foldl (fun a m c -> poly_add (poly_cmmul (c,m) p2) a) poly_0 p1;;
let poly_div (p1:poly) (p2:poly) =
if not(poly_isconst p2) then failwith "poly_div: non-constant" else
let c = eval undefined p2 in
if c =/ Int 0 then failwith "poly_div: division by zero"
else poly_cmul (Int 1 // c) p1;;
let poly_square p = poly_mul p p;;
let rec poly_pow p k =
if k = 0 then poly_const (Int 1)
else if k = 1 then p
else let q = poly_square(poly_pow p (k / 2)) in
if k mod 2 = 1 then poly_mul p q else q;;
let poly_exp p1 p2 =
if not(poly_isconst p2) then failwith "poly_exp: not a constant" else
poly_pow p1 (Num.int_of_num (eval undefined p2));;
let degree x (p:poly) = foldl (fun a m c -> max (monomial_degree x m) a) 0 p;;
let multidegree (p:poly) =
foldl (fun a m c -> max (monomial_multidegree m) a) 0 p;;
let poly_variables (p:poly) =
foldr (fun m c -> union (monomial_variables m)) p [];;
(* ------------------------------------------------------------------------- *)
(* Order monomials for human presentation. *)
(* ------------------------------------------------------------------------- *)
let humanorder_varpow (x1,k1) (x2,k2) = x1 < x2 or x1 = x2 && k1 > k2;;
let humanorder_monomial =
let rec ord l1 l2 = match (l1,l2) with
_,[] -> true
| [],_ -> false
| h1::t1,h2::t2 -> humanorder_varpow h1 h2 or h1 = h2 && ord t1 t2 in
fun m1 m2 -> m1 = m2 or
ord (sort humanorder_varpow (graph m1))
(sort humanorder_varpow (graph m2));;
(* ------------------------------------------------------------------------- *)
(* Conversions to strings. *)
(* ------------------------------------------------------------------------- *)
let string_of_vector min_size max_size (v:vector) =
let n_raw = dim v in
if n_raw = 0 then "[]" else
let n = max min_size (min n_raw max_size) in
let xs = List.map ((o) string_of_num (element v)) (1--n) in
"[" ^ end_itlist (fun s t -> s ^ ", " ^ t) xs ^
(if n_raw > max_size then ", ...]" else "]");;
let string_of_matrix max_size (m:matrix) =
let i_raw,j_raw = dimensions m in
let i = min max_size i_raw and j = min max_size j_raw in
let rstr = List.map (fun k -> string_of_vector j j (row k m)) (1--i) in
"["^end_itlist(fun s t -> s^";\n "^t) rstr ^
(if j > max_size then "\n ...]" else "]");;
let string_of_vname (v:vname): string = (v: string);;
let rec string_of_term t =
match t with
Opp t1 -> "(- " ^ string_of_term t1 ^ ")"
| Add (t1, t2) ->
"(" ^ (string_of_term t1) ^ " + " ^ (string_of_term t2) ^ ")"
| Sub (t1, t2) ->
"(" ^ (string_of_term t1) ^ " - " ^ (string_of_term t2) ^ ")"
| Mul (t1, t2) ->
"(" ^ (string_of_term t1) ^ " * " ^ (string_of_term t2) ^ ")"
| Inv t1 -> "(/ " ^ string_of_term t1 ^ ")"
| Div (t1, t2) ->
"(" ^ (string_of_term t1) ^ " / " ^ (string_of_term t2) ^ ")"
| Pow (t1, n1) ->
"(" ^ (string_of_term t1) ^ " ^ " ^ (string_of_int n1) ^ ")"
| Zero -> "0"
| Var v -> "x" ^ (string_of_vname v)
| Const x -> string_of_num x;;
let string_of_varpow x k =
if k = 1 then string_of_vname x else string_of_vname x^"^"^string_of_int k;;
let string_of_monomial m =
if m = monomial_1 then "1" else
let vps = List.fold_right (fun (x,k) a -> string_of_varpow x k :: a)
(sort humanorder_varpow (graph m)) [] in
end_itlist (fun s t -> s^"*"^t) vps;;
let string_of_cmonomial (c,m) =
if m = monomial_1 then string_of_num c
else if c =/ Int 1 then string_of_monomial m
else string_of_num c ^ "*" ^ string_of_monomial m;;
let string_of_poly (p:poly) =
if p = poly_0 then "<<0>>" else
let cms = sort (fun (m1,_) (m2,_) -> humanorder_monomial m1 m2) (graph p) in
let s =
List.fold_left (fun a (m,c) ->
if c </ Int 0 then a ^ " - " ^ string_of_cmonomial(minus_num c,m)
else a ^ " + " ^ string_of_cmonomial(c,m))
"" cms in
let s1 = String.sub s 0 3
and s2 = String.sub s 3 (String.length s - 3) in
"<<" ^(if s1 = " + " then s2 else "-"^s2)^">>";;
(* ------------------------------------------------------------------------- *)
(* Printers. *)
(* ------------------------------------------------------------------------- *)
let print_vector v = Format.print_string(string_of_vector 0 20 v);;
let print_matrix m = Format.print_string(string_of_matrix 20 m);;
let print_monomial m = Format.print_string(string_of_monomial m);;
let print_poly m = Format.print_string(string_of_poly m);;
(*
#install_printer print_vector;;
#install_printer print_matrix;;
#install_printer print_monomial;;
#install_printer print_poly;;
*)
(* ------------------------------------------------------------------------- *)
(* Conversion from term. *)
(* ------------------------------------------------------------------------- *)
let rec poly_of_term t = match t with
Zero -> poly_0
| Const n -> poly_const n
| Var x -> poly_var x
| Opp t1 -> poly_neg (poly_of_term t1)
| Inv t1 ->
let p = poly_of_term t1 in
if poly_isconst p then poly_const(Int 1 // eval undefined p)
else failwith "poly_of_term: inverse of non-constant polyomial"
| Add (l, r) -> poly_add (poly_of_term l) (poly_of_term r)
| Sub (l, r) -> poly_sub (poly_of_term l) (poly_of_term r)
| Mul (l, r) -> poly_mul (poly_of_term l) (poly_of_term r)
| Div (l, r) ->
let p = poly_of_term l and q = poly_of_term r in
if poly_isconst q then poly_cmul (Int 1 // eval undefined q) p
else failwith "poly_of_term: division by non-constant polynomial"
| Pow (t, n) ->
poly_pow (poly_of_term t) n;;
(* ------------------------------------------------------------------------- *)
(* String of vector (just a list of space-separated numbers). *)
(* ------------------------------------------------------------------------- *)
let sdpa_of_vector (v:vector) =
let n = dim v in
let strs = List.map (o (decimalize 20) (element v)) (1--n) in
end_itlist (fun x y -> x ^ " " ^ y) strs ^ "\n";;
(* ------------------------------------------------------------------------- *)
String for block diagonal matrix numbered
(* ------------------------------------------------------------------------- *)
let sdpa_of_blockdiagonal k m =
let pfx = string_of_int k ^" " in
let ents =
foldl (fun a (b,i,j) c -> if i > j then a else ((b,i,j),c)::a) [] m in
let entss = sort (increasing fst) ents in
itlist (fun ((b,i,j),c) a ->
pfx ^ string_of_int b ^ " " ^ string_of_int i ^ " " ^ string_of_int j ^
" " ^ decimalize 20 c ^ "\n" ^ a) entss "";;
(* ------------------------------------------------------------------------- *)
String for a matrix numbered k , in SDPA sparse format .
(* ------------------------------------------------------------------------- *)
let sdpa_of_matrix k (m:matrix) =
let pfx = string_of_int k ^ " 1 " in
let ms = foldr (fun (i,j) c a -> if i > j then a else ((i,j),c)::a)
(snd m) [] in
let mss = sort (increasing fst) ms in
itlist (fun ((i,j),c) a ->
pfx ^ string_of_int i ^ " " ^ string_of_int j ^
" " ^ decimalize 20 c ^ "\n" ^ a) mss "";;
(* ------------------------------------------------------------------------- *)
String in SDPA sparse format for standard SDP problem :
(* *)
[ M_1 ] + ... + v_m * [ M_m ] - [ M_0 ] must be PSD
Minimize obj_1 * + ... obj_m * v_m
(* ------------------------------------------------------------------------- *)
let sdpa_of_problem comment obj mats =
let m = List.length mats - 1
and n,_ = dimensions (List.hd mats) in
"\"" ^ comment ^ "\"\n" ^
string_of_int m ^ "\n" ^
"1\n" ^
string_of_int n ^ "\n" ^
sdpa_of_vector obj ^
itlist2 (fun k m a -> sdpa_of_matrix (k - 1) m ^ a)
(1--List.length mats) mats "";;
(* ------------------------------------------------------------------------- *)
(* More parser basics. *)
(* ------------------------------------------------------------------------- *)
let word s =
end_itlist (fun p1 p2 -> (p1 ++ p2) >> (fun (s,t) -> s^t))
(List.map a (explode s));;
let token s =
many (some isspace) ++ word s ++ many (some isspace)
>> (fun ((_,t),_) -> t);;
let decimal =
let numeral = some isnum in
let decimalint = atleast 1 numeral >> ((o) Num.num_of_string implode) in
let decimalfrac = atleast 1 numeral
>> (fun s -> Num.num_of_string(implode s) // pow10 (List.length s)) in
let decimalsig =
decimalint ++ possibly (a "." ++ decimalfrac >> snd)
>> (function (h,[x]) -> h +/ x | (h,_) -> h) in
let signed prs =
a "-" ++ prs >> ((o) minus_num snd)
|| a "+" ++ prs >> snd
|| prs in
let exponent = (a "e" || a "E") ++ signed decimalint >> snd in
signed decimalsig ++ possibly exponent
>> (function (h,[x]) -> h */ power_num (Int 10) x | (h,_) -> h);;
let mkparser p s =
let x,rst = p(explode s) in
if rst = [] then x else failwith "mkparser: unparsed input";;
let parse_decimal = mkparser decimal;;
(* ------------------------------------------------------------------------- *)
Parse back a vector .
(* ------------------------------------------------------------------------- *)
let parse_sdpaoutput,parse_csdpoutput =
let vector =
token "{" ++ listof decimal (token ",") "decimal" ++ token "}"
>> (fun ((_,v),_) -> vector_of_list v) in
let rec skipupto dscr prs inp =
(dscr ++ prs >> snd
|| some (fun c -> true) ++ skipupto dscr prs >> snd) inp in
let ignore inp = (),[] in
let sdpaoutput =
skipupto (word "xVec" ++ token "=")
(vector ++ ignore >> fst) in
let csdpoutput =
(decimal ++ many(a " " ++ decimal >> snd) >> (fun (h,t) -> h::t)) ++
(a " " ++ a "\n" ++ ignore) >> ((o) vector_of_list fst) in
mkparser sdpaoutput,mkparser csdpoutput;;
(* ------------------------------------------------------------------------- *)
Also parse the SDPA output to test success ( CSDP yields a return code ) .
(* ------------------------------------------------------------------------- *)
let sdpa_run_succeeded =
let rec skipupto dscr prs inp =
(dscr ++ prs >> snd
|| some (fun c -> true) ++ skipupto dscr prs >> snd) inp in
let prs = skipupto (word "phase.value" ++ token "=")
(possibly (a "p") ++ possibly (a "d") ++
(word "OPT" || word "FEAS")) in
fun s -> try ignore (prs (explode s)); true with Noparse -> false;;
(* ------------------------------------------------------------------------- *)
(* The default parameters. Unfortunately this goes to a fixed file. *)
(* ------------------------------------------------------------------------- *)
let sdpa_default_parameters =
"100 unsigned int maxIteration;\
\n1.0E-7 double 0.0 < epsilonStar;\
\n1.0E2 double 0.0 < lambdaStar;\
\n2.0 double 1.0 < omegaStar;\
\n-1.0E5 double lowerBound;\
\n1.0E5 double upperBound;\
\n0.1 double 0.0 <= betaStar < 1.0;\
\n0.2 double 0.0 <= betaBar < 1.0, betaStar <= betaBar;\
\n0.9 double 0.0 < gammaStar < 1.0;\
\n1.0E-7 double 0.0 < epsilonDash;\
\n";;
(* ------------------------------------------------------------------------- *)
These were suggested by for problems where we are
(* right at the edge of the semidefinite cone, as sometimes happens. *)
(* ------------------------------------------------------------------------- *)
let sdpa_alt_parameters =
"1000 unsigned int maxIteration;\
\n1.0E-7 double 0.0 < epsilonStar;\
\n1.0E4 double 0.0 < lambdaStar;\
\n2.0 double 1.0 < omegaStar;\
\n-1.0E5 double lowerBound;\
\n1.0E5 double upperBound;\
\n0.1 double 0.0 <= betaStar < 1.0;\
\n0.2 double 0.0 <= betaBar < 1.0, betaStar <= betaBar;\
\n0.9 double 0.0 < gammaStar < 1.0;\
\n1.0E-7 double 0.0 < epsilonDash;\
\n";;
let sdpa_params = sdpa_alt_parameters;;
(* ------------------------------------------------------------------------- *)
CSDP parameters ; so far I 'm sticking with the defaults .
(* ------------------------------------------------------------------------- *)
let csdp_default_parameters =
"axtol=1.0e-8\
\natytol=1.0e-8\
\nobjtol=1.0e-8\
\npinftol=1.0e8\
\ndinftol=1.0e8\
\nmaxiter=100\
\nminstepfrac=0.9\
\nmaxstepfrac=0.97\
\nminstepp=1.0e-8\
\nminstepd=1.0e-8\
\nusexzgap=1\
\ntweakgap=0\
\naffine=0\
\nprintlevel=1\
\n";;
let csdp_params = csdp_default_parameters;;
(* ------------------------------------------------------------------------- *)
Now call CSDP on a problem and parse back the output .
(* ------------------------------------------------------------------------- *)
let run_csdp dbg obj mats =
let input_file = Filename.temp_file "sos" ".dat-s" in
let output_file =
String.sub input_file 0 (String.length input_file - 6) ^ ".out"
and params_file = Filename.concat (!temp_path) "param.csdp" in
file_of_string input_file (sdpa_of_problem "" obj mats);
file_of_string params_file csdp_params;
let rv = Sys.command("cd "^(!temp_path)^"; csdp "^input_file ^
" " ^ output_file ^
(if dbg then "" else "> /dev/null")) in
let op = string_of_file output_file in
let res = parse_csdpoutput op in
((if dbg then ()
else (Sys.remove input_file; Sys.remove output_file));
rv,res);;
let csdp obj mats =
let rv,res = run_csdp (!debugging) obj mats in
(if rv = 1 or rv = 2 then failwith "csdp: Problem is infeasible"
else if rv = 3 then ()
Format.print_string " csdp warning : Reduced accuracy " ;
( )
Format.print_newline() *)
else if rv <> 0 then failwith("csdp: error "^string_of_int rv)
else ());
res;;
(* ------------------------------------------------------------------------- *)
Try some apparently sensible scaling first . Note that this is purely to
(* get a cleaner translation to floating-point, and doesn't affect any of *)
(* the results, in principle. In practice it seems a lot better when there *)
(* are extreme numbers in the original problem. *)
(* ------------------------------------------------------------------------- *)
let scale_then =
let common_denominator amat acc =
foldl (fun a m c -> lcm_num (denominator c) a) acc amat
and maximal_element amat acc =
foldl (fun maxa m c -> max_num maxa (abs_num c)) acc amat in
fun solver obj mats ->
let cd1 = itlist common_denominator mats (Int 1)
and cd2 = common_denominator (snd obj) (Int 1) in
let mats' = List.map (mapf (fun x -> cd1 */ x)) mats
and obj' = vector_cmul cd2 obj in
let max1 = itlist maximal_element mats' (Int 0)
and max2 = maximal_element (snd obj') (Int 0) in
let scal1 = pow2 (20-int_of_float(log(float_of_num max1) /. log 2.0))
and scal2 = pow2 (20-int_of_float(log(float_of_num max2) /. log 2.0)) in
let mats'' = List.map (mapf (fun x -> x */ scal1)) mats'
and obj'' = vector_cmul scal2 obj' in
solver obj'' mats'';;
(* ------------------------------------------------------------------------- *)
(* Round a vector to "nice" rationals. *)
(* ------------------------------------------------------------------------- *)
let nice_rational n x = round_num (n */ x) // n;;
let nice_vector n = mapa (nice_rational n);;
(* ------------------------------------------------------------------------- *)
Reduce linear program to SDP ( diagonal matrices ) and test with CSDP . This
one tests A [ -1;x1; .. ;xn ] > = 0 ( i.e. left column is negated constants ) .
(* ------------------------------------------------------------------------- *)
let linear_program_basic a =
let m,n = dimensions a in
let mats = List.map (fun j -> diagonal (column j a)) (1--n)
and obj = vector_const (Int 1) m in
let rv,res = run_csdp false obj mats in
if rv = 1 or rv = 2 then false
else if rv = 0 then true
else failwith "linear_program: An error occurred in the SDP solver";;
(* ------------------------------------------------------------------------- *)
(* Alternative interface testing A x >= b for matrix A, vector b. *)
(* ------------------------------------------------------------------------- *)
let linear_program a b =
let m,n = dimensions a in
if dim b <> m then failwith "linear_program: incompatible dimensions" else
let mats = diagonal b :: List.map (fun j -> diagonal (column j a)) (1--n)
and obj = vector_const (Int 1) m in
let rv,res = run_csdp false obj mats in
if rv = 1 or rv = 2 then false
else if rv = 0 then true
else failwith "linear_program: An error occurred in the SDP solver";;
(* ------------------------------------------------------------------------- *)
(* Test whether a point is in the convex hull of others. Rather than use *)
computational geometry , express as linear inequalities and call CSDP .
(* This is a bit lazy of me, but it's easy and not such a bottleneck so far. *)
(* ------------------------------------------------------------------------- *)
let in_convex_hull pts pt =
let pts1 = (1::pt) :: List.map (fun x -> 1::x) pts in
let pts2 = List.map (fun p -> List.map (fun x -> -x) p @ p) pts1 in
let n = List.length pts + 1
and v = 2 * (List.length pt + 1) in
let m = v + n - 1 in
let mat =
(m,n),
itern 1 pts2 (fun pts j -> itern 1 pts (fun x i -> (i,j) |-> Int x))
(iter (1,n) (fun i -> (v + i,i+1) |-> Int 1) undefined) in
linear_program_basic mat;;
(* ------------------------------------------------------------------------- *)
(* Filter down a set of points to a minimal set with the same convex hull. *)
(* ------------------------------------------------------------------------- *)
let minimal_convex_hull =
let augment1 = function
| [] -> assert false
| (m::ms) -> if in_convex_hull ms m then ms else ms@[m] in
let augment m ms = funpow 3 augment1 (m::ms) in
fun mons ->
let mons' = itlist augment (List.tl mons) [List.hd mons] in
funpow (List.length mons') augment1 mons';;
(* ------------------------------------------------------------------------- *)
Stuff for " equations " ( generic functions ) .
(* ------------------------------------------------------------------------- *)
let equation_cmul c eq =
if c =/ Int 0 then Empty else mapf (fun d -> c */ d) eq;;
let equation_add eq1 eq2 = combine (+/) (fun x -> x =/ Int 0) eq1 eq2;;
let equation_eval assig eq =
let value v = apply assig v in
foldl (fun a v c -> a +/ value(v) */ c) (Int 0) eq;;
(* ------------------------------------------------------------------------- *)
Eliminate among linear equations : return unconstrained variables and
assignments for the others in terms of them . We give one pseudo - variable
(* "one" that's used for a constant term. *)
(* ------------------------------------------------------------------------- *)
let failstore = ref [];;
let eliminate_equations =
let rec extract_first p l =
match l with
[] -> failwith "extract_first"
| h::t -> if p(h) then h,t else
let k,s = extract_first p t in
k,h::s in
let rec eliminate vars dun eqs =
match vars with
[] -> if forall is_undefined eqs then dun
else (failstore := [vars,dun,eqs]; raise Unsolvable)
| v::vs ->
try let eq,oeqs = extract_first (fun e -> defined e v) eqs in
let a = apply eq v in
let eq' = equation_cmul (Int(-1) // a) (undefine v eq) in
let elim e =
let b = tryapplyd e v (Int 0) in
if b =/ Int 0 then e else
equation_add e (equation_cmul (minus_num b // a) eq) in
eliminate vs ((v |-> eq') (mapf elim dun)) (List.map elim oeqs)
with Failure _ -> eliminate vs dun eqs in
fun one vars eqs ->
let assig = eliminate vars undefined eqs in
let vs = foldl (fun a x f -> subtract (dom f) [one] @ a) [] assig in
setify vs,assig;;
(* ------------------------------------------------------------------------- *)
(* Eliminate all variables, in an essentially arbitrary order. *)
(* ------------------------------------------------------------------------- *)
let eliminate_all_equations one =
let choose_variable eq =
let (v,_) = choose eq in
if v = one then
let eq' = undefine v eq in
if is_undefined eq' then failwith "choose_variable" else
let (w,_) = choose eq' in w
else v in
let rec eliminate dun eqs =
match eqs with
[] -> dun
| eq::oeqs ->
if is_undefined eq then eliminate dun oeqs else
let v = choose_variable eq in
let a = apply eq v in
let eq' = equation_cmul (Int(-1) // a) (undefine v eq) in
let elim e =
let b = tryapplyd e v (Int 0) in
if b =/ Int 0 then e else
equation_add e (equation_cmul (minus_num b // a) eq) in
eliminate ((v |-> eq') (mapf elim dun)) (List.map elim oeqs) in
fun eqs ->
let assig = eliminate undefined eqs in
let vs = foldl (fun a x f -> subtract (dom f) [one] @ a) [] assig in
setify vs,assig;;
(* ------------------------------------------------------------------------- *)
(* Solve equations by assigning arbitrary numbers. *)
(* ------------------------------------------------------------------------- *)
let solve_equations one eqs =
let vars,assigs = eliminate_all_equations one eqs in
let vfn = itlist (fun v -> (v |-> Int 0)) vars (one |=> Int(-1)) in
let ass =
combine (+/) (fun c -> false) (mapf (equation_eval vfn) assigs) vfn in
if forall (fun e -> equation_eval ass e =/ Int 0) eqs
then undefine one ass else raise Sanity;;
(* ------------------------------------------------------------------------- *)
(* Hence produce the "relevant" monomials: those whose squares lie in the *)
Newton polytope of the monomials in the input . ( This is enough according
to : " Extremal PSD forms with few terms " , Duke Math . Journal ,
vol 45 , pp . 363 - -374 , 1978 .
(* *)
(* These are ordered in sort of decreasing degree. In particular the *)
(* constant monomial is last; this gives an order in diagonalization of the *)
(* quadratic form that will tend to display constants. *)
(* ------------------------------------------------------------------------- *)
let newton_polytope pol =
let vars = poly_variables pol in
let mons = List.map (fun m -> List.map (fun x -> monomial_degree x m) vars) (dom pol)
and ds = List.map (fun x -> (degree x pol + 1) / 2) vars in
let all = itlist (fun n -> allpairs (fun h t -> h::t) (0--n)) ds [[]]
and mons' = minimal_convex_hull mons in
let all' =
List.filter (fun m -> in_convex_hull mons' (List.map (fun x -> 2 * x) m)) all in
List.map (fun m -> itlist2 (fun v i a -> if i = 0 then a else (v |-> i) a)
vars m monomial_1) (List.rev all');;
(* ------------------------------------------------------------------------- *)
Diagonalize ( Cholesky / LDU ) the matrix corresponding to a quadratic form .
(* ------------------------------------------------------------------------- *)
let diag m =
let nn = dimensions m in
let n = fst nn in
if snd nn <> n then failwith "diagonalize: non-square matrix" else
let rec diagonalize i m =
if is_zero m then [] else
let a11 = element m (i,i) in
if a11 </ Int 0 then failwith "diagonalize: not PSD"
else if a11 =/ Int 0 then
if is_zero(row i m) then diagonalize (i + 1) m
else failwith "diagonalize: not PSD"
else
let v = row i m in
let v' = mapa (fun a1k -> a1k // a11) v in
let m' =
(n,n),
iter (i+1,n) (fun j ->
iter (i+1,n) (fun k ->
((j,k) |--> (element m (j,k) -/ element v j */ element v' k))))
undefined in
(a11,v')::diagonalize (i + 1) m' in
diagonalize 1 m;;
(* ------------------------------------------------------------------------- *)
(* Adjust a diagonalization to collect rationals at the start. *)
(* ------------------------------------------------------------------------- *)
let deration d =
if d = [] then Int 0,d else
let adj(c,l) =
let a = foldl (fun a i c -> lcm_num a (denominator c)) (Int 1) (snd l) //
foldl (fun a i c -> gcd_num a (numerator c)) (Int 0) (snd l) in
(c // (a */ a)),mapa (fun x -> a */ x) l in
let d' = List.map adj d in
let a = itlist ((o) lcm_num ( (o) denominator fst)) d' (Int 1) //
itlist ((o) gcd_num ( (o) numerator fst)) d' (Int 0) in
(Int 1 // a),List.map (fun (c,l) -> (a */ c,l)) d';;
(* ------------------------------------------------------------------------- *)
Enumeration of monomials with given bound .
(* ------------------------------------------------------------------------- *)
let rec enumerate_monomials d vars =
if d < 0 then []
else if d = 0 then [undefined]
else if vars = [] then [monomial_1] else
let alts =
List.map (fun k -> let oths = enumerate_monomials (d - k) (List.tl vars) in
List.map (fun ks -> if k = 0 then ks else (List.hd vars |-> k) ks) oths)
(0--d) in
end_itlist (@) alts;;
(* ------------------------------------------------------------------------- *)
(* Enumerate products of distinct input polys with degree <= d. *)
(* We ignore any constant input polynomials. *)
(* Give the output polynomial and a record of how it was derived. *)
(* ------------------------------------------------------------------------- *)
let rec enumerate_products d pols =
if d = 0 then [poly_const num_1,Rational_lt num_1] else if d < 0 then [] else
match pols with
[] -> [poly_const num_1,Rational_lt num_1]
| (p,b)::ps -> let e = multidegree p in
if e = 0 then enumerate_products d ps else
enumerate_products d ps @
List.map (fun (q,c) -> poly_mul p q,Product(b,c))
(enumerate_products (d - e) ps);;
(* ------------------------------------------------------------------------- *)
(* Multiply equation-parametrized poly by regular poly and add accumulator. *)
(* ------------------------------------------------------------------------- *)
let epoly_pmul p q acc =
foldl (fun a m1 c ->
foldl (fun b m2 e ->
let m = monomial_mul m1 m2 in
let es = tryapplyd b m undefined in
(m |-> equation_add (equation_cmul c e) es) b)
a q) acc p;;
(* ------------------------------------------------------------------------- *)
(* Usual operations on equation-parametrized poly. *)
(* ------------------------------------------------------------------------- *)
let epoly_cmul c l =
if c =/ Int 0 then undefined else mapf (equation_cmul c) l;;
let epoly_neg = epoly_cmul (Int(-1));;
let epoly_add = combine equation_add is_undefined;;
let epoly_sub p q = epoly_add p (epoly_neg q);;
(* ------------------------------------------------------------------------- *)
(* Convert regular polynomial. Note that we treat (0,0,0) as -1. *)
(* ------------------------------------------------------------------------- *)
let epoly_of_poly p =
foldl (fun a m c -> (m |-> ((0,0,0) |=> minus_num c)) a) undefined p;;
(* ------------------------------------------------------------------------- *)
String for block diagonal matrix numbered
(* ------------------------------------------------------------------------- *)
let sdpa_of_blockdiagonal k m =
let pfx = string_of_int k ^" " in
let ents =
foldl (fun a (b,i,j) c -> if i > j then a else ((b,i,j),c)::a) [] m in
let entss = sort (increasing fst) ents in
itlist (fun ((b,i,j),c) a ->
pfx ^ string_of_int b ^ " " ^ string_of_int i ^ " " ^ string_of_int j ^
" " ^ decimalize 20 c ^ "\n" ^ a) entss "";;
(* ------------------------------------------------------------------------- *)
SDPA for problem using block diagonal ( i.e. multiple SDPs )
(* ------------------------------------------------------------------------- *)
let sdpa_of_blockproblem comment nblocks blocksizes obj mats =
let m = List.length mats - 1 in
"\"" ^ comment ^ "\"\n" ^
string_of_int m ^ "\n" ^
string_of_int nblocks ^ "\n" ^
(end_itlist (fun s t -> s^" "^t) (List.map string_of_int blocksizes)) ^
"\n" ^
sdpa_of_vector obj ^
itlist2 (fun k m a -> sdpa_of_blockdiagonal (k - 1) m ^ a)
(1--List.length mats) mats "";;
(* ------------------------------------------------------------------------- *)
Hence run CSDP on a problem in block diagonal form .
(* ------------------------------------------------------------------------- *)
let run_csdp dbg nblocks blocksizes obj mats =
let input_file = Filename.temp_file "sos" ".dat-s" in
let output_file =
String.sub input_file 0 (String.length input_file - 6) ^ ".out"
and params_file = Filename.concat (!temp_path) "param.csdp" in
file_of_string input_file
(sdpa_of_blockproblem "" nblocks blocksizes obj mats);
file_of_string params_file csdp_params;
let rv = Sys.command("cd "^(!temp_path)^"; csdp "^input_file ^
" " ^ output_file ^
(if dbg then "" else "> /dev/null")) in
let op = string_of_file output_file in
let res = parse_csdpoutput op in
((if dbg then ()
else (Sys.remove input_file; Sys.remove output_file));
rv,res);;
let csdp nblocks blocksizes obj mats =
let rv,res = run_csdp (!debugging) nblocks blocksizes obj mats in
(if rv = 1 or rv = 2 then failwith "csdp: Problem is infeasible"
else if rv = 3 then ()
Format.print_string " csdp warning : Reduced accuracy " ;
( )
Format.print_newline() *)
else if rv <> 0 then failwith("csdp: error "^string_of_int rv)
else ());
res;;
(* ------------------------------------------------------------------------- *)
(* 3D versions of matrix operations to consider blocks separately. *)
(* ------------------------------------------------------------------------- *)
let bmatrix_add = combine (+/) (fun x -> x =/ Int 0);;
let bmatrix_cmul c bm =
if c =/ Int 0 then undefined
else mapf (fun x -> c */ x) bm;;
let bmatrix_neg = bmatrix_cmul (Int(-1));;
let bmatrix_sub m1 m2 = bmatrix_add m1 (bmatrix_neg m2);;
(* ------------------------------------------------------------------------- *)
(* Smash a block matrix into components. *)
(* ------------------------------------------------------------------------- *)
let blocks blocksizes bm =
List.map (fun (bs,b0) ->
let m = foldl
(fun a (b,i,j) c -> if b = b0 then ((i,j) |-> c) a else a)
undefined bm in
(((bs,bs),m):matrix))
(zip blocksizes (1--List.length blocksizes));;
(* ------------------------------------------------------------------------- *)
(* Positiv- and Nullstellensatz. Flag "linf" forces a linear representation. *)
(* ------------------------------------------------------------------------- *)
let real_positivnullstellensatz_general linf d eqs leqs pol =
let vars = itlist ((o) union poly_variables) (pol::eqs @ List.map fst leqs) [] in
let monoid =
if linf then
(poly_const num_1,Rational_lt num_1)::
(List.filter (fun (p,c) -> multidegree p <= d) leqs)
else enumerate_products d leqs in
let nblocks = List.length monoid in
let mk_idmultiplier k p =
let e = d - multidegree p in
let mons = enumerate_monomials e vars in
let nons = zip mons (1--List.length mons) in
mons,
itlist (fun (m,n) -> (m |-> ((-k,-n,n) |=> Int 1))) nons undefined in
let mk_sqmultiplier k (p,c) =
let e = (d - multidegree p) / 2 in
let mons = enumerate_monomials e vars in
let nons = zip mons (1--List.length mons) in
mons,
itlist (fun (m1,n1) ->
itlist (fun (m2,n2) a ->
let m = monomial_mul m1 m2 in
if n1 > n2 then a else
let c = if n1 = n2 then Int 1 else Int 2 in
let e = tryapplyd a m undefined in
(m |-> equation_add ((k,n1,n2) |=> c) e) a)
nons)
nons undefined in
let sqmonlist,sqs = unzip(List.map2 mk_sqmultiplier (1--List.length monoid) monoid)
and idmonlist,ids = unzip(List.map2 mk_idmultiplier (1--List.length eqs) eqs) in
let blocksizes = List.map List.length sqmonlist in
let bigsum =
itlist2 (fun p q a -> epoly_pmul p q a) eqs ids
(itlist2 (fun (p,c) s a -> epoly_pmul p s a) monoid sqs
(epoly_of_poly(poly_neg pol))) in
let eqns = foldl (fun a m e -> e::a) [] bigsum in
let pvs,assig = eliminate_all_equations (0,0,0) eqns in
let qvars = (0,0,0)::pvs in
let allassig = itlist (fun v -> (v |-> (v |=> Int 1))) pvs assig in
let mk_matrix v =
foldl (fun m (b,i,j) ass -> if b < 0 then m else
let c = tryapplyd ass v (Int 0) in
if c =/ Int 0 then m else
((b,j,i) |-> c) (((b,i,j) |-> c) m))
undefined allassig in
let diagents = foldl
(fun a (b,i,j) e -> if b > 0 && i = j then equation_add e a else a)
undefined allassig in
let mats = List.map mk_matrix qvars
and obj = List.length pvs,
itern 1 pvs (fun v i -> (i |--> tryapplyd diagents v (Int 0)))
undefined in
let raw_vec = if pvs = [] then vector_0 0
else scale_then (csdp nblocks blocksizes) obj mats in
let find_rounding d =
(if !debugging then
(Format.print_string("Trying rounding with limit "^string_of_num d);
Format.print_newline())
else ());
let vec = nice_vector d raw_vec in
let blockmat = iter (1,dim vec)
(fun i a -> bmatrix_add (bmatrix_cmul (element vec i) (el i mats)) a)
(bmatrix_neg (el 0 mats)) in
let allmats = blocks blocksizes blockmat in
vec,List.map diag allmats in
let vec,ratdias =
if pvs = [] then find_rounding num_1
else tryfind find_rounding (List.map Num.num_of_int (1--31) @
List.map pow2 (5--66)) in
let newassigs =
itlist (fun k -> el (k - 1) pvs |-> element vec k)
(1--dim vec) ((0,0,0) |=> Int(-1)) in
let finalassigs =
foldl (fun a v e -> (v |-> equation_eval newassigs e) a) newassigs
allassig in
let poly_of_epoly p =
foldl (fun a v e -> (v |--> equation_eval finalassigs e) a)
undefined p in
let mk_sos mons =
let mk_sq (c,m) =
c,itlist (fun k a -> (el (k - 1) mons |--> element m k) a)
(1--List.length mons) undefined in
List.map mk_sq in
let sqs = List.map2 mk_sos sqmonlist ratdias
and cfs = List.map poly_of_epoly ids in
let msq = List.filter (fun (a,b) -> b <> []) (List.map2 (fun a b -> a,b) monoid sqs) in
let eval_sq sqs = itlist
(fun (c,q) -> poly_add (poly_cmul c (poly_mul q q))) sqs poly_0 in
let sanity =
itlist (fun ((p,c),s) -> poly_add (poly_mul p (eval_sq s))) msq
(itlist2 (fun p q -> poly_add (poly_mul p q)) cfs eqs
(poly_neg pol)) in
if not(is_undefined sanity) then raise Sanity else
cfs,List.map (fun (a,b) -> snd a,b) msq;;
(* ------------------------------------------------------------------------- *)
(* Iterative deepening. *)
(* ------------------------------------------------------------------------- *)
let rec deepen f n =
try print_string "Searching with depth limit ";
print_int n; print_newline(); f n
with Failure _ -> deepen f (n + 1);;
(* ------------------------------------------------------------------------- *)
The ordering so we can create canonical HOL polynomials .
(* ------------------------------------------------------------------------- *)
let dest_monomial mon = sort (increasing fst) (graph mon);;
let monomial_order =
let rec lexorder l1 l2 =
match (l1,l2) with
[],[] -> true
| vps,[] -> false
| [],vps -> true
| ((x1,n1)::vs1),((x2,n2)::vs2) ->
if x1 < x2 then true
else if x2 < x1 then false
else if n1 < n2 then false
else if n2 < n1 then true
else lexorder vs1 vs2 in
fun m1 m2 ->
if m2 = monomial_1 then true else if m1 = monomial_1 then false else
let mon1 = dest_monomial m1 and mon2 = dest_monomial m2 in
let deg1 = itlist ((o) (+) snd) mon1 0
and deg2 = itlist ((o) (+) snd) mon2 0 in
if deg1 < deg2 then false else if deg1 > deg2 then true
else lexorder mon1 mon2;;
let dest_poly p =
List.map (fun (m,c) -> c,dest_monomial m)
(sort (fun (m1,_) (m2,_) -> monomial_order m1 m2) (graph p));;
(* ------------------------------------------------------------------------- *)
Map back polynomials and their composites to HOL .
(* ------------------------------------------------------------------------- *)
let term_of_varpow =
fun x k ->
if k = 1 then Var x else Pow (Var x, k);;
let term_of_monomial =
fun m -> if m = monomial_1 then Const num_1 else
let m' = dest_monomial m in
let vps = itlist (fun (x,k) a -> term_of_varpow x k :: a) m' [] in
end_itlist (fun s t -> Mul (s,t)) vps;;
let term_of_cmonomial =
fun (m,c) ->
if m = monomial_1 then Const c
else if c =/ num_1 then term_of_monomial m
else Mul (Const c,term_of_monomial m);;
let term_of_poly =
fun p ->
if p = poly_0 then Zero else
let cms = List.map term_of_cmonomial
(sort (fun (m1,_) (m2,_) -> monomial_order m1 m2) (graph p)) in
end_itlist (fun t1 t2 -> Add (t1,t2)) cms;;
let term_of_sqterm (c,p) =
Product(Rational_lt c,Square(term_of_poly p));;
let term_of_sos (pr,sqs) =
if sqs = [] then pr
else Product(pr,end_itlist (fun a b -> Sum(a,b)) (List.map term_of_sqterm sqs));;
(* ------------------------------------------------------------------------- *)
Interface to HOL .
(* ------------------------------------------------------------------------- *)
let REAL_NONLINEAR_PROVER translator ( eqs , les , lts ) =
let eq0 = map ( poly_of_term o lhand o concl ) eqs
and le0 = map ( poly_of_term o lhand o concl ) les
and lt0 = map ( poly_of_term o lhand o concl ) lts in
let eqp0 = map ( fun ( t , i ) - > t , Axiom_eq i ) ( zip eq0 ( 0 - -(length eq0 - 1 ) ) )
and lep0 = map ( fun ( t , i ) - > t , Axiom_le i ) ( zip le0 ( 0 - -(length le0 - 1 ) ) )
and ltp0 = map ( fun ( t , i ) - > t , Axiom_lt i ) ( zip lt0 ( 0 - -(length lt0 - 1 ) ) ) in
let keq , eq = partition ( fun ( p , _ ) - > multidegree p = 0 ) eqp0
and klep , lep = partition ( fun ( p , _ ) - > multidegree p = 0 ) lep0
and kltp , ltp = partition ( fun ( p , _ ) - > multidegree p = 0 ) ltp0 in
let trivial_axiom ( p , ax ) =
match ax with
Axiom_eq n when eval undefined p < > / num_0 - > el n eqs
| Axiom_le n when eval undefined p < / num_0 - > el n les
| Axiom_lt n when eval undefined p < =/ num_0 - > el n lts
| _ - > failwith " not a trivial axiom " in
try let th = tryfind trivial_axiom ( keq @ klep @ kltp ) in
CONV_RULE ( LAND_CONV REAL_POLY_CONV THENC REAL_RAT_RED_CONV ) th
with Failure _ - >
let pol = ( map fst ltp ) ( poly_const num_1 ) in
let leq = lep @ ltp in
let tryall d =
let e = in
let k = if e = 0 then 0 else d / e in
let eq ' = map fst eq in
tryfind ( fun i - > d , i , real_positivnullstellensatz_general false d eq ' leq
( poly_neg(poly_pow pol i ) ) )
( 0 - -k ) in
let d , i,(cert_ideal , cert_cone ) = deepen tryall 0 in
let proofs_ideal =
map2 ( fun q ( p , ax ) - > Eqmul(term_of_poly q , ax ) ) and proofs_cone = map term_of_sos cert_cone
and proof_ne =
if ltp = [ ] then Rational_lt num_1 else
let p = end_itlist ( fun s t - > Product(s , t ) ) ( map snd ltp ) in
funpow i ( fun q - > Product(p , q ) ) ( Rational_lt num_1 ) in
let proof = end_itlist ( fun s t - > Sum(s , t ) )
( proof_ne : : proofs_ideal @ proofs_cone ) in
print_string("Translating proof certificate to HOL " ) ;
print_newline ( ) ;
translator ( eqs , les , lts ) proof ; ;
let REAL_NONLINEAR_PROVER translator (eqs,les,lts) =
let eq0 = map (poly_of_term o lhand o concl) eqs
and le0 = map (poly_of_term o lhand o concl) les
and lt0 = map (poly_of_term o lhand o concl) lts in
let eqp0 = map (fun (t,i) -> t,Axiom_eq i) (zip eq0 (0--(length eq0 - 1)))
and lep0 = map (fun (t,i) -> t,Axiom_le i) (zip le0 (0--(length le0 - 1)))
and ltp0 = map (fun (t,i) -> t,Axiom_lt i) (zip lt0 (0--(length lt0 - 1))) in
let keq,eq = partition (fun (p,_) -> multidegree p = 0) eqp0
and klep,lep = partition (fun (p,_) -> multidegree p = 0) lep0
and kltp,ltp = partition (fun (p,_) -> multidegree p = 0) ltp0 in
let trivial_axiom (p,ax) =
match ax with
Axiom_eq n when eval undefined p <>/ num_0 -> el n eqs
| Axiom_le n when eval undefined p </ num_0 -> el n les
| Axiom_lt n when eval undefined p <=/ num_0 -> el n lts
| _ -> failwith "not a trivial axiom" in
try let th = tryfind trivial_axiom (keq @ klep @ kltp) in
CONV_RULE (LAND_CONV REAL_POLY_CONV THENC REAL_RAT_RED_CONV) th
with Failure _ ->
let pol = itlist poly_mul (map fst ltp) (poly_const num_1) in
let leq = lep @ ltp in
let tryall d =
let e = multidegree pol in
let k = if e = 0 then 0 else d / e in
let eq' = map fst eq in
tryfind (fun i -> d,i,real_positivnullstellensatz_general false d eq' leq
(poly_neg(poly_pow pol i)))
(0--k) in
let d,i,(cert_ideal,cert_cone) = deepen tryall 0 in
let proofs_ideal =
map2 (fun q (p,ax) -> Eqmul(term_of_poly q,ax)) cert_ideal eq
and proofs_cone = map term_of_sos cert_cone
and proof_ne =
if ltp = [] then Rational_lt num_1 else
let p = end_itlist (fun s t -> Product(s,t)) (map snd ltp) in
funpow i (fun q -> Product(p,q)) (Rational_lt num_1) in
let proof = end_itlist (fun s t -> Sum(s,t))
(proof_ne :: proofs_ideal @ proofs_cone) in
print_string("Translating proof certificate to HOL");
print_newline();
translator (eqs,les,lts) proof;;
*)
(* ------------------------------------------------------------------------- *)
A wrapper that tries to substitute away variables first .
(* ------------------------------------------------------------------------- *)
let =
let zero = ` & 0 : real `
and mul_tm = ` ( * ): real->real->real `
and shuffle1 =
CONV_RULE(REWR_CONV(REAL_ARITH ` a + x = ( y : real ) < = > x = y - a ` ) )
and shuffle2 =
CONV_RULE(REWR_CONV(REAL_ARITH ` x + a = ( y : real ) < = > x = y - a ` ) ) in
let rec substitutable_monomial fvs tm =
match tm with
Var(_,Tyapp("real " , [ ] ) ) when not ( mem tm fvs ) - > Int 1,tm
| Comb(Comb(Const("real_mul",_),c),(Var ( _ , _ ) as t ) )
when is_ratconst c & & not ( mem t fvs )
- > rat_of_term c , t
| ) - >
( try substitutable_monomial ( union ( frees t ) fvs ) s
with Failure _ - > substitutable_monomial ( union ( frees s ) fvs ) t )
| _ - > failwith " substitutable_monomial "
and isolate_variable v th =
match lhs(concl th ) with
x when x = v - > th
| Comb(Comb(Const("real_add",_),(Var(_,Tyapp("real " , [ ] ) ) as )
when x = v - > shuffle2 th
| ) - >
isolate_variable v(shuffle1 th ) in
let make_substitution th =
let ( c , v ) = substitutable_monomial [ ] ( lhs(concl th ) ) in
let th1 = AP_TERM ( mk_comb(mul_tm , term_of_rat(Int 1 // c ) ) ) th in
let th2 = CONV_RULE(BINOP_CONV REAL_POLY_MUL_CONV ) th1 in
CONV_RULE ( RAND_CONV REAL_POLY_CONV ) ( isolate_variable v th2 ) in
fun translator - >
let rec substfirst(eqs , les , lts ) =
try let eth = in
let modify =
CONV_RULE(LAND_CONV(SUBS_CONV[eth ] THENC REAL_POLY_CONV ) ) in
substfirst(filter ( fun t - > lhand(concl t ) < > zero ) ( map modify eqs ) ,
map modify les , map modify lts )
with Failure _ - > REAL_NONLINEAR_PROVER translator ( eqs , les , lts ) in
substfirst ; ;
let REAL_NONLINEAR_SUBST_PROVER =
let zero = `&0:real`
and mul_tm = `( * ):real->real->real`
and shuffle1 =
CONV_RULE(REWR_CONV(REAL_ARITH `a + x = (y:real) <=> x = y - a`))
and shuffle2 =
CONV_RULE(REWR_CONV(REAL_ARITH `x + a = (y:real) <=> x = y - a`)) in
let rec substitutable_monomial fvs tm =
match tm with
Var(_,Tyapp("real",[])) when not (mem tm fvs) -> Int 1,tm
| Comb(Comb(Const("real_mul",_),c),(Var(_,_) as t))
when is_ratconst c && not (mem t fvs)
-> rat_of_term c,t
| Comb(Comb(Const("real_add",_),s),t) ->
(try substitutable_monomial (union (frees t) fvs) s
with Failure _ -> substitutable_monomial (union (frees s) fvs) t)
| _ -> failwith "substitutable_monomial"
and isolate_variable v th =
match lhs(concl th) with
x when x = v -> th
| Comb(Comb(Const("real_add",_),(Var(_,Tyapp("real",[])) as x)),t)
when x = v -> shuffle2 th
| Comb(Comb(Const("real_add",_),s),t) ->
isolate_variable v(shuffle1 th) in
let make_substitution th =
let (c,v) = substitutable_monomial [] (lhs(concl th)) in
let th1 = AP_TERM (mk_comb(mul_tm,term_of_rat(Int 1 // c))) th in
let th2 = CONV_RULE(BINOP_CONV REAL_POLY_MUL_CONV) th1 in
CONV_RULE (RAND_CONV REAL_POLY_CONV) (isolate_variable v th2) in
fun translator ->
let rec substfirst(eqs,les,lts) =
try let eth = tryfind make_substitution eqs in
let modify =
CONV_RULE(LAND_CONV(SUBS_CONV[eth] THENC REAL_POLY_CONV)) in
substfirst(filter (fun t -> lhand(concl t) <> zero) (map modify eqs),
map modify les,map modify lts)
with Failure _ -> REAL_NONLINEAR_PROVER translator (eqs,les,lts) in
substfirst;;
*)
(* ------------------------------------------------------------------------- *)
(* Overall function. *)
(* ------------------------------------------------------------------------- *)
let REAL_SOS =
let init = GEN_REWRITE_CONV ONCE_DEPTH_CONV [ DECIMAL ]
and pure = GEN_REAL_ARITH REAL_NONLINEAR_SUBST_PROVER in
fun tm - > let th = init tm in EQ_MP ( SYM th ) ( pure(rand(concl th ) ) ) ; ;
let REAL_SOS =
let init = GEN_REWRITE_CONV ONCE_DEPTH_CONV [DECIMAL]
and pure = GEN_REAL_ARITH REAL_NONLINEAR_SUBST_PROVER in
fun tm -> let th = init tm in EQ_MP (SYM th) (pure(rand(concl th)));;
*)
(* ------------------------------------------------------------------------- *)
(* Add hacks for division. *)
(* ------------------------------------------------------------------------- *)
let let inv_tm = ` inv : real->real ` in
let prenex_conv =
TOP_DEPTH_CONV BETA_CONV THENC
PURE_REWRITE_CONV[FORALL_SIMP ; EXISTS_SIMP ; real_div ;
REAL_INV_INV ; REAL_INV_MUL ; GSYM REAL_POW_INV ] THENC
NNFC_CONV THENC DEPTH_BINOP_CONV ` ( /\ ) ` CONDS_CELIM_CONV THENC
PRENEX_CONV
and THENC WEAK_CNF_CONV THENC CONJ_CANON_CONV
and core_rule t =
try REAL_ARITH t
with Failure _ - > try REAL_RING t
with Failure _ - > REAL_SOS t
and is_inv =
let is_div = is_binop ` ( /):real->real->real ` in
fun tm - > ( is_div tm or ( is_comb tm & & rator tm = inv_tm ) ) & &
not(is_ratconst(rand tm ) ) in
let BASIC_REAL_FIELD tm =
let is_freeinv t = is_inv t & & free_in t tm in
let itms = setify(map rand ( find_terms is_freeinv tm ) ) in
let hyps = map ( fun t - > SPEC t REAL_MUL_RINV ) itms in
let tm ' = itlist ( fun th t - > mk_imp(concl th , t ) ) hyps tm in
let itms ' = map ( curry mk_comb inv_tm ) itms in
let = map ( genvar o type_of ) itms ' in
let tm '' = subst ( zip gvs itms ' ) tm ' in
let th1 = setup_conv tm '' in
let cjs = conjuncts(rand(concl th1 ) ) in
let ths = map core_rule cjs in
let th2 = EQ_MP ( SYM th1 ) ( end_itlist ) in
rev_itlist ( C MP ) hyps ( INST ( zip itms ' ) th2 ) in
fun tm - >
let in
let tm0 = rand(concl ) in
let avs , bod = strip_forall tm0 in
let th1 = setup_conv bod in
let ths = map ( conjuncts(rand(concl th1 ) ) ) in
EQ_MP ( SYM th0 ) ( GENL avs ( EQ_MP ( SYM th1 ) ( end_itlist ) ) ) ; ;
let REAL_SOSFIELD =
let inv_tm = `inv:real->real` in
let prenex_conv =
TOP_DEPTH_CONV BETA_CONV THENC
PURE_REWRITE_CONV[FORALL_SIMP; EXISTS_SIMP; real_div;
REAL_INV_INV; REAL_INV_MUL; GSYM REAL_POW_INV] THENC
NNFC_CONV THENC DEPTH_BINOP_CONV `(/\)` CONDS_CELIM_CONV THENC
PRENEX_CONV
and setup_conv = NNF_CONV THENC WEAK_CNF_CONV THENC CONJ_CANON_CONV
and core_rule t =
try REAL_ARITH t
with Failure _ -> try REAL_RING t
with Failure _ -> REAL_SOS t
and is_inv =
let is_div = is_binop `(/):real->real->real` in
fun tm -> (is_div tm or (is_comb tm && rator tm = inv_tm)) &&
not(is_ratconst(rand tm)) in
let BASIC_REAL_FIELD tm =
let is_freeinv t = is_inv t && free_in t tm in
let itms = setify(map rand (find_terms is_freeinv tm)) in
let hyps = map (fun t -> SPEC t REAL_MUL_RINV) itms in
let tm' = itlist (fun th t -> mk_imp(concl th,t)) hyps tm in
let itms' = map (curry mk_comb inv_tm) itms in
let gvs = map (genvar o type_of) itms' in
let tm'' = subst (zip gvs itms') tm' in
let th1 = setup_conv tm'' in
let cjs = conjuncts(rand(concl th1)) in
let ths = map core_rule cjs in
let th2 = EQ_MP (SYM th1) (end_itlist CONJ ths) in
rev_itlist (C MP) hyps (INST (zip itms' gvs) th2) in
fun tm ->
let th0 = prenex_conv tm in
let tm0 = rand(concl th0) in
let avs,bod = strip_forall tm0 in
let th1 = setup_conv bod in
let ths = map BASIC_REAL_FIELD (conjuncts(rand(concl th1))) in
EQ_MP (SYM th0) (GENL avs (EQ_MP (SYM th1) (end_itlist CONJ ths)));;
*)
(* ------------------------------------------------------------------------- *)
Integer version .
(* ------------------------------------------------------------------------- *)
let INT_SOS =
let atom_CONV =
let pth = prove
( ` ( ~(x < = y ) < = > y + & 1 < = x : int ) /\
( ~(x < y ) < = > y < = x ) /\
( ~(x = y ) < = > x + & 1 < = y \/ y + & 1 < = x ) /\
( x < y < = > x + & 1 < = y ) ` ,
REWRITE_TAC[INT_NOT_LE ; INT_NOT_LT ; INT_NOT_EQ ; INT_LT_DISCRETE ] ) in
GEN_REWRITE_CONV I [ pth ]
and bub_CONV = GEN_REWRITE_CONV TOP_SWEEP_CONV
[ int_eq ; int_le ; int_lt ; int_ge ; int_gt ;
int_of_num_th ; int_neg_th ; int_add_th ; int_mul_th ;
int_sub_th ; int_pow_th ; int_abs_th ; ; int_min_th ] in
let base_CONV = TRY_CONV atom_CONV THENC bub_CONV in
let NNF_NORM_CONV = GEN_NNF_CONV false
( base_CONV , fun t - > base_CONV t , base_CONV(mk_neg t ) ) in
let init_CONV =
GEN_REWRITE_CONV DEPTH_CONV [ FORALL_SIMP ; EXISTS_SIMP ] THENC
GEN_REWRITE_CONV DEPTH_CONV [ INT_GT ; INT_GE ] THENC
CONDS_ELIM_CONV THENC NNF_NORM_CONV in
let p_tm = ` p : bool `
and not_tm = ` ( ~ ) ` in
let pth = TAUT(mk_eq(mk_neg(mk_neg p_tm),p_tm ) ) in
fun tm - >
let = INST [ tm , p_tm ] pth
and th1 = NNF_NORM_CONV(mk_neg tm ) in
let th2 = REAL_SOS(mk_neg(rand(concl th1 ) ) ) in
EQ_MP th0 ( EQ_MP ( AP_TERM not_tm ( SYM th1 ) ) th2 ) ; ;
let INT_SOS =
let atom_CONV =
let pth = prove
(`(~(x <= y) <=> y + &1 <= x:int) /\
(~(x < y) <=> y <= x) /\
(~(x = y) <=> x + &1 <= y \/ y + &1 <= x) /\
(x < y <=> x + &1 <= y)`,
REWRITE_TAC[INT_NOT_LE; INT_NOT_LT; INT_NOT_EQ; INT_LT_DISCRETE]) in
GEN_REWRITE_CONV I [pth]
and bub_CONV = GEN_REWRITE_CONV TOP_SWEEP_CONV
[int_eq; int_le; int_lt; int_ge; int_gt;
int_of_num_th; int_neg_th; int_add_th; int_mul_th;
int_sub_th; int_pow_th; int_abs_th; int_max_th; int_min_th] in
let base_CONV = TRY_CONV atom_CONV THENC bub_CONV in
let NNF_NORM_CONV = GEN_NNF_CONV false
(base_CONV,fun t -> base_CONV t,base_CONV(mk_neg t)) in
let init_CONV =
GEN_REWRITE_CONV DEPTH_CONV [FORALL_SIMP; EXISTS_SIMP] THENC
GEN_REWRITE_CONV DEPTH_CONV [INT_GT; INT_GE] THENC
CONDS_ELIM_CONV THENC NNF_NORM_CONV in
let p_tm = `p:bool`
and not_tm = `(~)` in
let pth = TAUT(mk_eq(mk_neg(mk_neg p_tm),p_tm)) in
fun tm ->
let th0 = INST [tm,p_tm] pth
and th1 = NNF_NORM_CONV(mk_neg tm) in
let th2 = REAL_SOS(mk_neg(rand(concl th1))) in
EQ_MP th0 (EQ_MP (AP_TERM not_tm (SYM th1)) th2);;
*)
(* ------------------------------------------------------------------------- *)
(* Natural number version. *)
(* ------------------------------------------------------------------------- *)
let SOS_RULE tm =
let avs = frees tm in
let tm ' = list_mk_forall(avs , tm ) in
let th1 = NUM_TO_INT_CONV tm ' in
let th2 = INT_SOS ( rand(concl th1 ) ) in
SPECL avs ( EQ_MP ( SYM th1 ) th2 ) ; ;
let SOS_RULE tm =
let avs = frees tm in
let tm' = list_mk_forall(avs,tm) in
let th1 = NUM_TO_INT_CONV tm' in
let th2 = INT_SOS (rand(concl th1)) in
SPECL avs (EQ_MP (SYM th1) th2);;
*)
(* ------------------------------------------------------------------------- *)
(* Now pure SOS stuff. *)
(* ------------------------------------------------------------------------- *)
(*prioritize_real();;*)
(* ------------------------------------------------------------------------- *)
(* Some combinatorial helper functions. *)
(* ------------------------------------------------------------------------- *)
let rec allpermutations l =
if l = [] then [[]] else
itlist (fun h acc -> List.map (fun t -> h::t)
(allpermutations (subtract l [h])) @ acc) l [];;
let allvarorders l =
List.map (fun vlis x -> index x vlis) (allpermutations l);;
let changevariables_monomial zoln (m:monomial) =
foldl (fun a x k -> (List.assoc x zoln |-> k) a) monomial_1 m;;
let changevariables zoln pol =
foldl (fun a m c -> (changevariables_monomial zoln m |-> c) a)
poly_0 pol;;
(* ------------------------------------------------------------------------- *)
(* Return to original non-block matrices. *)
(* ------------------------------------------------------------------------- *)
let sdpa_of_vector (v:vector) =
let n = dim v in
let strs = List.map (o (decimalize 20) (element v)) (1--n) in
end_itlist (fun x y -> x ^ " " ^ y) strs ^ "\n";;
let sdpa_of_blockdiagonal k m =
let pfx = string_of_int k ^" " in
let ents =
foldl (fun a (b,i,j) c -> if i > j then a else ((b,i,j),c)::a) [] m in
let entss = sort (increasing fst) ents in
itlist (fun ((b,i,j),c) a ->
pfx ^ string_of_int b ^ " " ^ string_of_int i ^ " " ^ string_of_int j ^
" " ^ decimalize 20 c ^ "\n" ^ a) entss "";;
let sdpa_of_matrix k (m:matrix) =
let pfx = string_of_int k ^ " 1 " in
let ms = foldr (fun (i,j) c a -> if i > j then a else ((i,j),c)::a)
(snd m) [] in
let mss = sort (increasing fst) ms in
itlist (fun ((i,j),c) a ->
pfx ^ string_of_int i ^ " " ^ string_of_int j ^
" " ^ decimalize 20 c ^ "\n" ^ a) mss "";;
let sdpa_of_problem comment obj mats =
let m = List.length mats - 1
and n,_ = dimensions (List.hd mats) in
"\"" ^ comment ^ "\"\n" ^
string_of_int m ^ "\n" ^
"1\n" ^
string_of_int n ^ "\n" ^
sdpa_of_vector obj ^
itlist2 (fun k m a -> sdpa_of_matrix (k - 1) m ^ a)
(1--List.length mats) mats "";;
let run_csdp dbg obj mats =
let input_file = Filename.temp_file "sos" ".dat-s" in
let output_file =
String.sub input_file 0 (String.length input_file - 6) ^ ".out"
and params_file = Filename.concat (!temp_path) "param.csdp" in
file_of_string input_file (sdpa_of_problem "" obj mats);
file_of_string params_file csdp_params;
let rv = Sys.command("cd "^(!temp_path)^"; csdp "^input_file ^
" " ^ output_file ^
(if dbg then "" else "> /dev/null")) in
let op = string_of_file output_file in
let res = parse_csdpoutput op in
((if dbg then ()
else (Sys.remove input_file; Sys.remove output_file));
rv,res);;
let csdp obj mats =
let rv,res = run_csdp (!debugging) obj mats in
(if rv = 1 or rv = 2 then failwith "csdp: Problem is infeasible"
else if rv = 3 then ()
( Format.print_string " csdp warning : Reduced accuracy " ;
( ) )
Format.print_newline()) *)
else if rv <> 0 then failwith("csdp: error "^string_of_int rv)
else ());
res;;
(* ------------------------------------------------------------------------- *)
(* Sum-of-squares function with some lowbrow symmetry reductions. *)
(* ------------------------------------------------------------------------- *)
let sumofsquares_general_symmetry tool pol =
let vars = poly_variables pol
and lpps = newton_polytope pol in
let n = List.length lpps in
let sym_eqs =
let invariants = List.filter
(fun vars' ->
is_undefined(poly_sub pol (changevariables (zip vars vars') pol)))
(allpermutations vars) in
let lpns = zip lpps (1--List.length lpps) in
let lppcs =
List.filter (fun (m,(n1,n2)) -> n1 <= n2)
(allpairs
(fun (m1,n1) (m2,n2) -> (m1,m2),(n1,n2)) lpns lpns) in
let clppcs = end_itlist (@)
(List.map (fun ((m1,m2),(n1,n2)) ->
List.map (fun vars' ->
(changevariables_monomial (zip vars vars') m1,
changevariables_monomial (zip vars vars') m2),(n1,n2))
invariants)
lppcs) in
let clppcs_dom = setify(List.map fst clppcs) in
let clppcs_cls = List.map (fun d -> List.filter (fun (e,_) -> e = d) clppcs)
clppcs_dom in
let eqvcls = List.map (o setify (List.map snd)) clppcs_cls in
let mk_eq cls acc =
match cls with
[] -> raise Sanity
| [h] -> acc
| h::t -> List.map (fun k -> (k |-> Int(-1)) (h |=> Int 1)) t @ acc in
itlist mk_eq eqvcls [] in
let eqs = foldl (fun a x y -> y::a) []
(itern 1 lpps (fun m1 n1 ->
itern 1 lpps (fun m2 n2 f ->
let m = monomial_mul m1 m2 in
if n1 > n2 then f else
let c = if n1 = n2 then Int 1 else Int 2 in
(m |-> ((n1,n2) |-> c) (tryapplyd f m undefined)) f))
(foldl (fun a m c -> (m |-> ((0,0)|=>c)) a)
undefined pol)) @
sym_eqs in
let pvs,assig = eliminate_all_equations (0,0) eqs in
let allassig = itlist (fun v -> (v |-> (v |=> Int 1))) pvs assig in
let qvars = (0,0)::pvs in
let diagents =
end_itlist equation_add (List.map (fun i -> apply allassig (i,i)) (1--n)) in
let mk_matrix v =
((n,n),
foldl (fun m (i,j) ass -> let c = tryapplyd ass v (Int 0) in
if c =/ Int 0 then m else
((j,i) |-> c) (((i,j) |-> c) m))
undefined allassig :matrix) in
let mats = List.map mk_matrix qvars
and obj = List.length pvs,
itern 1 pvs (fun v i -> (i |--> tryapplyd diagents v (Int 0)))
undefined in
let raw_vec = if pvs = [] then vector_0 0 else tool obj mats in
let find_rounding d =
(if !debugging then
(Format.print_string("Trying rounding with limit "^string_of_num d);
Format.print_newline())
else ());
let vec = nice_vector d raw_vec in
let mat = iter (1,dim vec)
(fun i a -> matrix_add (matrix_cmul (element vec i) (el i mats)) a)
(matrix_neg (el 0 mats)) in
deration(diag mat) in
let rat,dia =
if pvs = [] then
let mat = matrix_neg (el 0 mats) in
deration(diag mat)
else
tryfind find_rounding (List.map Num.num_of_int (1--31) @
List.map pow2 (5--66)) in
let poly_of_lin(d,v) =
d,foldl(fun a i c -> (el (i - 1) lpps |-> c) a) undefined (snd v) in
let lins = List.map poly_of_lin dia in
let sqs = List.map (fun (d,l) -> poly_mul (poly_const d) (poly_pow l 2)) lins in
let sos = poly_cmul rat (end_itlist poly_add sqs) in
if is_undefined(poly_sub sos pol) then rat,lins else raise Sanity;;
let sumofsquares = sumofsquares_general_symmetry csdp;;
(* ------------------------------------------------------------------------- *)
Pure HOL SOS conversion .
(* ------------------------------------------------------------------------- *)
let SOS_CONV =
let mk_square =
let pow_tm = ` ( pow ) ` and two_tm = ` 2 ` in
fun tm - > mk_comb(mk_comb(pow_tm , tm),two_tm )
and mk_prod = mk_binop ` ( * ) `
and mk_sum = mk_binop ` ( + ) ` in
fun tm - >
let k , sos = sumofsquares(poly_of_term tm ) in
let , p ) =
mk_prod ( term_of_rat(k * / c ) ) ( mk_square(term_of_poly p ) ) in
let tm ' = end_itlist mk_sum ( map mk_sqtm sos ) in
let th = REAL_POLY_CONV tm and th ' = REAL_POLY_CONV tm ' in
TRANS th ( SYM th ' ) ; ;
let SOS_CONV =
let mk_square =
let pow_tm = `(pow)` and two_tm = `2` in
fun tm -> mk_comb(mk_comb(pow_tm,tm),two_tm)
and mk_prod = mk_binop `( * )`
and mk_sum = mk_binop `(+)` in
fun tm ->
let k,sos = sumofsquares(poly_of_term tm) in
let mk_sqtm(c,p) =
mk_prod (term_of_rat(k */ c)) (mk_square(term_of_poly p)) in
let tm' = end_itlist mk_sum (map mk_sqtm sos) in
let th = REAL_POLY_CONV tm and th' = REAL_POLY_CONV tm' in
TRANS th (SYM th');;
*)
(* ------------------------------------------------------------------------- *)
Attempt to prove & 0 < = x by direct SOS decomposition .
(* ------------------------------------------------------------------------- *)
let PURE_SOS_TAC =
let tac =
MATCH_ACCEPT_TAC(REWRITE_RULE[GSYM REAL_POW_2 ] REAL_LE_SQUARE ) ORELSE
( MATCH_MP_TAC REAL_LE_ADD THEN ) ORELSE
( MATCH_MP_TAC REAL_LE_MUL THEN ) ORELSE
CONV_TAC(RAND_CONV REAL_RAT_REDUCE_CONV THENC REAL_RAT_LE_CONV ) in
REPEAT GEN_TAC THEN REWRITE_TAC[real_ge ] THEN
I [ GSYM REAL_SUB_LE ] THEN
CONV_TAC(RAND_CONV SOS_CONV ) THEN
REPEAT tac THEN NO_TAC ; ;
let PURE_SOS tm = prove(tm , PURE_SOS_TAC ) ; ;
let PURE_SOS_TAC =
let tac =
MATCH_ACCEPT_TAC(REWRITE_RULE[GSYM REAL_POW_2] REAL_LE_SQUARE) ORELSE
MATCH_ACCEPT_TAC REAL_LE_SQUARE ORELSE
(MATCH_MP_TAC REAL_LE_ADD THEN CONJ_TAC) ORELSE
(MATCH_MP_TAC REAL_LE_MUL THEN CONJ_TAC) ORELSE
CONV_TAC(RAND_CONV REAL_RAT_REDUCE_CONV THENC REAL_RAT_LE_CONV) in
REPEAT GEN_TAC THEN REWRITE_TAC[real_ge] THEN
GEN_REWRITE_TAC I [GSYM REAL_SUB_LE] THEN
CONV_TAC(RAND_CONV SOS_CONV) THEN
REPEAT tac THEN NO_TAC;;
let PURE_SOS tm = prove(tm,PURE_SOS_TAC);;
*)
(* ------------------------------------------------------------------------- *)
(* Examples. *)
(* ------------------------------------------------------------------------- *)
* * * *
time REAL_SOS
` a1 > = & 0 /\ a2 > = & 0 /\
( a1 * a1 + a2 * a2 = b1 * b1 + b2 * b2 + & 2 ) /\
( a1 * b1 + a2 * b2 = & 0 )
= = > a1 * a2 - b1 * b2 > = & 0 ` ; ;
time REAL_SOS ` & 3 * x + & 7 * a < & 4 /\ & 3 < & 2 * x = = > a < & 0 ` ; ;
time REAL_SOS
` b pow 2 < & 4 * a * c = = > ~(a * x pow 2 + b * x + c = & 0 ) ` ; ;
time REAL_SOS
` ( a * x pow 2 + b * x + c = & 0 ) = = > b pow 2 > = & 4 * a * c ` ; ;
time REAL_SOS
` & 0 < = x /\ x < = & 1 /\ & 0 < = y /\ y < = & 1
= = > x pow 2 + y pow 2 < & 1 \/
( x - & 1 ) pow 2 + y pow 2 < & 1 \/
x pow 2 + ( y - & 1 ) pow 2 < & 1 \/
( x - & 1 ) pow 2 + ( y - & 1 ) pow 2 < & 1 ` ; ;
time REAL_SOS
` & 0 < = b /\ & 0 < = c /\ & 0 < = x /\ & 0 < = y /\
( x pow 2 = c ) /\ ( y pow 2 = a pow 2 * c + b )
= = > a * c < = y * x ` ; ;
time REAL_SOS
` & 0 < = x /\ & 0 < = y /\ & 0 < = z /\ x + y + z < = & 3
= = > x * y + x * z + y * z > = & 3 * x * y * z ` ; ;
time REAL_SOS
` ( x pow 2 + y pow 2 + z pow 2 = & 1 ) = = > ( x + y + z ) pow 2 < = & 3 ` ; ;
time REAL_SOS
` ( w pow 2 + x pow 2 + y pow 2 + z pow 2 = & 1 )
= = > ( w + x + y + z ) pow 2 < = & 4 ` ; ;
time REAL_SOS
` x > = & 1 /\ y > = & 1 = = > x * y > = x + y - & 1 ` ; ;
time REAL_SOS
` x > & 1 /\ y > & 1 = = > x * y > x + y - & 1 ` ; ;
time REAL_SOS
` abs(x ) < = & 1
= = > abs(&64 * x pow 7 - & 112 * x pow 5 + & 56 * x pow 3 - & 7 * x ) < = & 1 ` ; ;
time REAL_SOS
` abs(x - z ) < = e /\ abs(y - z ) < = e /\ & 0 < = u /\ & 0 < = v /\ ( u + v = & 1 )
= = > abs((u * x + v * y ) - z ) < = e ` ; ;
( * -------------------------------------------------------------------------
time REAL_SOS
`a1 >= &0 /\ a2 >= &0 /\
(a1 * a1 + a2 * a2 = b1 * b1 + b2 * b2 + &2) /\
(a1 * b1 + a2 * b2 = &0)
==> a1 * a2 - b1 * b2 >= &0`;;
time REAL_SOS `&3 * x + &7 * a < &4 /\ &3 < &2 * x ==> a < &0`;;
time REAL_SOS
`b pow 2 < &4 * a * c ==> ~(a * x pow 2 + b * x + c = &0)`;;
time REAL_SOS
`(a * x pow 2 + b * x + c = &0) ==> b pow 2 >= &4 * a * c`;;
time REAL_SOS
`&0 <= x /\ x <= &1 /\ &0 <= y /\ y <= &1
==> x pow 2 + y pow 2 < &1 \/
(x - &1) pow 2 + y pow 2 < &1 \/
x pow 2 + (y - &1) pow 2 < &1 \/
(x - &1) pow 2 + (y - &1) pow 2 < &1`;;
time REAL_SOS
`&0 <= b /\ &0 <= c /\ &0 <= x /\ &0 <= y /\
(x pow 2 = c) /\ (y pow 2 = a pow 2 * c + b)
==> a * c <= y * x`;;
time REAL_SOS
`&0 <= x /\ &0 <= y /\ &0 <= z /\ x + y + z <= &3
==> x * y + x * z + y * z >= &3 * x * y * z`;;
time REAL_SOS
`(x pow 2 + y pow 2 + z pow 2 = &1) ==> (x + y + z) pow 2 <= &3`;;
time REAL_SOS
`(w pow 2 + x pow 2 + y pow 2 + z pow 2 = &1)
==> (w + x + y + z) pow 2 <= &4`;;
time REAL_SOS
`x >= &1 /\ y >= &1 ==> x * y >= x + y - &1`;;
time REAL_SOS
`x > &1 /\ y > &1 ==> x * y > x + y - &1`;;
time REAL_SOS
`abs(x) <= &1
==> abs(&64 * x pow 7 - &112 * x pow 5 + &56 * x pow 3 - &7 * x) <= &1`;;
time REAL_SOS
`abs(x - z) <= e /\ abs(y - z) <= e /\ &0 <= u /\ &0 <= v /\ (u + v = &1)
==> abs((u * x + v * y) - z) <= e`;;
(* ------------------------------------------------------------------------- *)
One component of denominator in dodecahedral example .
(* ------------------------------------------------------------------------- *)
time REAL_SOS
`&2 <= x /\ x <= &125841 / &50000 /\
&2 <= y /\ y <= &125841 / &50000 /\
&2 <= z /\ z <= &125841 / &50000
==> &2 * (x * z + x * y + y * z) - (x * x + y * y + z * z) >= &0`;;
(* ------------------------------------------------------------------------- *)
(* Over a larger but simpler interval. *)
(* ------------------------------------------------------------------------- *)
time REAL_SOS
`&2 <= x /\ x <= &4 /\ &2 <= y /\ y <= &4 /\ &2 <= z /\ z <= &4
==> &0 <= &2 * (x * z + x * y + y * z) - (x * x + y * y + z * z)`;;
(* ------------------------------------------------------------------------- *)
We can do 12 . I think 12 is a sharp bound ; see PP 's certificate .
(* ------------------------------------------------------------------------- *)
time REAL_SOS
`&2 <= x /\ x <= &4 /\ &2 <= y /\ y <= &4 /\ &2 <= z /\ z <= &4
==> &12 <= &2 * (x * z + x * y + y * z) - (x * x + y * y + z * z)`;;
(* ------------------------------------------------------------------------- *)
Gloptipoly example .
(* ------------------------------------------------------------------------- *)
* * This works but normalization takes minutes
time REAL_SOS
` ( x - y - & 2 * x pow 4 = & 0 ) /\ & 0 < = x /\ x < = & 2 /\ & 0 < = y /\ y < = & 3
= = > y pow 2 - & 7 * y - & 12 * x + & 17 > = & 0 ` ; ;
* *
time REAL_SOS
`(x - y - &2 * x pow 4 = &0) /\ &0 <= x /\ x <= &2 /\ &0 <= y /\ y <= &3
==> y pow 2 - &7 * y - &12 * x + &17 >= &0`;;
***)
(* ------------------------------------------------------------------------- *)
Inequality from sci.math ( see " Leon - Sotelo , por favor " ) .
(* ------------------------------------------------------------------------- *)
time REAL_SOS
`&0 <= x /\ &0 <= y /\ (x * y = &1)
==> x + y <= x pow 2 + y pow 2`;;
time REAL_SOS
`&0 <= x /\ &0 <= y /\ (x * y = &1)
==> x * y * (x + y) <= x pow 2 + y pow 2`;;
time REAL_SOS
`&0 <= x /\ &0 <= y ==> x * y * (x + y) pow 2 <= (x pow 2 + y pow 2) pow 2`;;
(* ------------------------------------------------------------------------- *)
(* Some examples over integers and natural numbers. *)
(* ------------------------------------------------------------------------- *)
time SOS_RULE `!m n. 2 * m + n = (n + m) + m`;;
time SOS_RULE `!n. ~(n = 0) ==> (0 MOD n = 0)`;;
time SOS_RULE `!m n. m < n ==> (m DIV n = 0)`;;
time SOS_RULE `!n:num. n <= n * n`;;
time SOS_RULE `!m n. n * (m DIV n) <= m`;;
time SOS_RULE `!n. ~(n = 0) ==> (0 DIV n = 0)`;;
time SOS_RULE `!m n p. ~(p = 0) /\ m <= n ==> m DIV p <= n DIV p`;;
time SOS_RULE `!a b n. ~(a = 0) ==> (n <= b DIV a <=> a * n <= b)`;;
(* ------------------------------------------------------------------------- *)
(* This is particularly gratifying --- cf hideous manual proof in arith.ml *)
(* ------------------------------------------------------------------------- *)
(*** This doesn't now seem to work as well as it did; what changed?
time SOS_RULE
`!a b c d. ~(b = 0) /\ b * c < (a + 1) * d ==> c DIV d <= a DIV b`;;
***)
(* ------------------------------------------------------------------------- *)
Key lemma for injectivity of Cantor - type pairing functions .
(* ------------------------------------------------------------------------- *)
time SOS_RULE
`!x1 y1 x2 y2. ((x1 + y1) EXP 2 + x1 + 1 = (x2 + y2) EXP 2 + x2 + 1)
==> (x1 + y1 = x2 + y2)`;;
time SOS_RULE
`!x1 y1 x2 y2. ((x1 + y1) EXP 2 + x1 + 1 = (x2 + y2) EXP 2 + x2 + 1) /\
(x1 + y1 = x2 + y2)
==> (x1 = x2) /\ (y1 = y2)`;;
time SOS_RULE
`!x1 y1 x2 y2.
(((x1 + y1) EXP 2 + 3 * x1 + y1) DIV 2 =
((x2 + y2) EXP 2 + 3 * x2 + y2) DIV 2)
==> (x1 + y1 = x2 + y2)`;;
time SOS_RULE
`!x1 y1 x2 y2.
(((x1 + y1) EXP 2 + 3 * x1 + y1) DIV 2 =
((x2 + y2) EXP 2 + 3 * x2 + y2) DIV 2) /\
(x1 + y1 = x2 + y2)
==> (x1 = x2) /\ (y1 = y2)`;;
(* ------------------------------------------------------------------------- *)
Reciprocal multiplication ( actually just ARITH_RULE does these ) .
(* ------------------------------------------------------------------------- *)
time SOS_RULE `x <= 127 ==> ((86 * x) DIV 256 = x DIV 3)`;;
time SOS_RULE `x < 2 EXP 16 ==> ((104858 * x) DIV (2 EXP 20) = x DIV 10)`;;
(* ------------------------------------------------------------------------- *)
(* This is more impressive since it's really nonlinear. See REMAINDER_DECODE *)
(* ------------------------------------------------------------------------- *)
time SOS_RULE `0 < m /\ m < n ==> ((m * ((n * x) DIV m + 1)) DIV n = x)`;;
(* ------------------------------------------------------------------------- *)
(* Some conversion examples. *)
(* ------------------------------------------------------------------------- *)
time SOS_CONV
`&2 * x pow 4 + &2 * x pow 3 * y - x pow 2 * y pow 2 + &5 * y pow 4`;;
time SOS_CONV
`x pow 4 - (&2 * y * z + &1) * x pow 2 +
(y pow 2 * z pow 2 + &2 * y * z + &2)`;;
time SOS_CONV `&4 * x pow 4 +
&4 * x pow 3 * y - &7 * x pow 2 * y pow 2 - &2 * x * y pow 3 +
&10 * y pow 4`;;
time SOS_CONV `&4 * x pow 4 * y pow 6 + x pow 2 - x * y pow 2 + y pow 2`;;
time SOS_CONV
`&4096 * (x pow 4 + x pow 2 + z pow 6 - &3 * x pow 2 * z pow 2) + &729`;;
time SOS_CONV
`&120 * x pow 2 - &63 * x pow 4 + &10 * x pow 6 +
&30 * x * y - &120 * y pow 2 + &120 * y pow 4 + &31`;;
time SOS_CONV
`&9 * x pow 2 * y pow 4 + &9 * x pow 2 * z pow 4 + &36 * x pow 2 * y pow 3 +
&36 * x pow 2 * y pow 2 - &48 * x * y * z pow 2 + &4 * y pow 4 +
&4 * z pow 4 - &16 * y pow 3 + &16 * y pow 2`;;
time SOS_CONV
`(x pow 2 + y pow 2 + z pow 2) *
(x pow 4 * y pow 2 + x pow 2 * y pow 4 +
z pow 6 - &3 * x pow 2 * y pow 2 * z pow 2)`;;
time SOS_CONV
`x pow 4 + y pow 4 + z pow 4 - &4 * x * y * z + x + y + z + &3`;;
(*** I think this will work, but normalization is slow
time SOS_CONV
`&100 * (x pow 4 + y pow 4 + z pow 4 - &4 * x * y * z + x + y + z) + &212`;;
***)
time SOS_CONV
`&100 * ((&2 * x - &2) pow 2 + (x pow 3 - &8 * x - &2) pow 2) - &588`;;
time SOS_CONV
`x pow 2 * (&120 - &63 * x pow 2 + &10 * x pow 4) + &30 * x * y +
&30 * y pow 2 * (&4 * y pow 2 - &4) + &31`;;
(* ------------------------------------------------------------------------- *)
(* Example of basic rule. *)
(* ------------------------------------------------------------------------- *)
time PURE_SOS
`!x. x pow 4 + y pow 4 + z pow 4 - &4 * x * y * z + x + y + z + &3
>= &1 / &7`;;
time PURE_SOS
`&0 <= &98 * x pow 12 +
-- &980 * x pow 10 +
&3038 * x pow 8 +
-- &2968 * x pow 6 +
&1022 * x pow 4 +
-- &84 * x pow 2 +
&2`;;
time PURE_SOS
`!x. &0 <= &2 * x pow 14 +
-- &84 * x pow 12 +
&1022 * x pow 10 +
-- &2968 * x pow 8 +
&3038 * x pow 6 +
-- &980 * x pow 4 +
&98 * x pow 2`;;
(* ------------------------------------------------------------------------- *)
From et al , JSC vol 37 ( 2004 ) , p83 - 99 .
(* All of them work nicely with pure SOS_CONV, except (maybe) the one noted. *)
(* ------------------------------------------------------------------------- *)
PURE_SOS
`x pow 6 + y pow 6 + z pow 6 - &3 * x pow 2 * y pow 2 * z pow 2 >= &0`;;
PURE_SOS `x pow 4 + y pow 4 + z pow 4 + &1 - &4*x*y*z >= &0`;;
PURE_SOS `x pow 4 + &2*x pow 2*z + x pow 2 - &2*x*y*z + &2*y pow 2*z pow 2 +
&2*y*z pow 2 + &2*z pow 2 - &2*x + &2* y*z + &1 >= &0`;;
* * * This is harder . Interestingly , this fails the pure SOS test , it seems .
Yet only on rounding ( ! ? ) Poor polytope optimization or something ?
But REAL_SOS does finally converge on the second run at level 12 !
REAL_SOS
` x pow 4*y pow 4 - & 2*x pow 5*y pow 3*z pow 2 + x pow 6*y pow 2*z pow 4 + & 2*x
pow 2*y pow 3*z - & 4 * x pow 3*y pow 2*z pow 3 + & 2*x pow 4*y*z pow 5 + z pow
2*y pow 2 - & 2*z pow 4*y*x + z pow 6*x pow 2 > = & 0 ` ; ;
* * *
Yet only on rounding(!?) Poor Newton polytope optimization or something?
But REAL_SOS does finally converge on the second run at level 12!
REAL_SOS
`x pow 4*y pow 4 - &2*x pow 5*y pow 3*z pow 2 + x pow 6*y pow 2*z pow 4 + &2*x
pow 2*y pow 3*z - &4* x pow 3*y pow 2*z pow 3 + &2*x pow 4*y*z pow 5 + z pow
2*y pow 2 - &2*z pow 4*y*x + z pow 6*x pow 2 >= &0`;;
****)
PURE_SOS
`x pow 4 + &4*x pow 2*y pow 2 + &2*x*y*z pow 2 + &2*x*y*w pow 2 + y pow 4 + z
pow 4 + w pow 4 + &2*z pow 2*w pow 2 + &2*x pow 2*w + &2*y pow 2*w + &2*x*y +
&3*w pow 2 + &2*z pow 2 + &1 >= &0`;;
PURE_SOS
`w pow 6 + &2*z pow 2*w pow 3 + x pow 4 + y pow 4 + z pow 4 + &2*x pow 2*w +
&2*x pow 2*z + &3*x pow 2 + w pow 2 + &2*z*w + z pow 2 + &2*z + &2*w + &1 >=
&0`;;
*****)
| null | https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/plugins/micromega/sos.ml | ocaml | =========================================================================
independent bits
=========================================================================
=========================================================================
=========================================================================
prioritize_real();;
-------------------------------------------------------------------------
Turn a rational into a decimal string with d sig digits.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Iterations over numbers, and lists indexed by numbers.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
The main types.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
This can be generic.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Monomials.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Polynomials.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Order monomials for human presentation.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Conversions to strings.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Printers.
-------------------------------------------------------------------------
#install_printer print_vector;;
#install_printer print_matrix;;
#install_printer print_monomial;;
#install_printer print_poly;;
-------------------------------------------------------------------------
Conversion from term.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
String of vector (just a list of space-separated numbers).
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
More parser basics.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
The default parameters. Unfortunately this goes to a fixed file.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
right at the edge of the semidefinite cone, as sometimes happens.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
get a cleaner translation to floating-point, and doesn't affect any of
the results, in principle. In practice it seems a lot better when there
are extreme numbers in the original problem.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Round a vector to "nice" rationals.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Alternative interface testing A x >= b for matrix A, vector b.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Test whether a point is in the convex hull of others. Rather than use
This is a bit lazy of me, but it's easy and not such a bottleneck so far.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Filter down a set of points to a minimal set with the same convex hull.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
"one" that's used for a constant term.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Eliminate all variables, in an essentially arbitrary order.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Solve equations by assigning arbitrary numbers.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Hence produce the "relevant" monomials: those whose squares lie in the
These are ordered in sort of decreasing degree. In particular the
constant monomial is last; this gives an order in diagonalization of the
quadratic form that will tend to display constants.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Adjust a diagonalization to collect rationals at the start.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Enumerate products of distinct input polys with degree <= d.
We ignore any constant input polynomials.
Give the output polynomial and a record of how it was derived.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Multiply equation-parametrized poly by regular poly and add accumulator.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Usual operations on equation-parametrized poly.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Convert regular polynomial. Note that we treat (0,0,0) as -1.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
3D versions of matrix operations to consider blocks separately.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Smash a block matrix into components.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Positiv- and Nullstellensatz. Flag "linf" forces a linear representation.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Iterative deepening.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Overall function.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Add hacks for division.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Natural number version.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Now pure SOS stuff.
-------------------------------------------------------------------------
prioritize_real();;
-------------------------------------------------------------------------
Some combinatorial helper functions.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Return to original non-block matrices.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Sum-of-squares function with some lowbrow symmetry reductions.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Examples.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Over a larger but simpler interval.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Some examples over integers and natural numbers.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
This is particularly gratifying --- cf hideous manual proof in arith.ml
-------------------------------------------------------------------------
** This doesn't now seem to work as well as it did; what changed?
time SOS_RULE
`!a b c d. ~(b = 0) /\ b * c < (a + 1) * d ==> c DIV d <= a DIV b`;;
**
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
This is more impressive since it's really nonlinear. See REMAINDER_DECODE
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Some conversion examples.
-------------------------------------------------------------------------
** I think this will work, but normalization is slow
time SOS_CONV
`&100 * (x pow 4 + y pow 4 + z pow 4 - &4 * x * y * z + x + y + z) + &212`;;
**
-------------------------------------------------------------------------
Example of basic rule.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
All of them work nicely with pure SOS_CONV, except (maybe) the one noted.
------------------------------------------------------------------------- | - This code originates from HOL LIGHT 2.30
( see file LICENSE.sos for license , copyright and disclaimer )
- ( ) has isolated the HOL
- ( ) is using it to feed micromega
Nonlinear universal reals procedure using SOS decomposition .
open Num;;
open Sos_types;;
open Sos_lib;;
let debugging = ref false;;
exception Sanity;;
exception Unsolvable;;
let decimalize =
let rec normalize y =
if abs_num y </ Int 1 // Int 10 then normalize (Int 10 */ y) - 1
else if abs_num y >=/ Int 1 then normalize (y // Int 10) + 1
else 0 in
fun d x ->
if x =/ Int 0 then "0.0" else
let y = abs_num x in
let e = normalize y in
let z = pow10(-e) */ y +/ Int 1 in
let k = round_num(pow10 d */ z) in
(if x </ Int 0 then "-0." else "0.") ^
implode(List.tl(explode(string_of_num k))) ^
(if e = 0 then "" else "e"^string_of_int e);;
let rec itern k l f a =
match l with
[] -> a
| h::t -> itern (k + 1) t f (f h k a);;
let rec iter (m,n) f a =
if n < m then a
else iter (m+1,n) f (f m a);;
type vector = int*(int,num)func;;
type matrix = (int*int)*(int*int,num)func;;
type monomial = (vname,int)func;;
type poly = (monomial,num)func;;
Assignment avoiding zeros .
let (|-->) x y a = if y =/ Int 0 then a else (x |-> y) a;;
let element (d,v) i = tryapplyd v i (Int 0);;
let mapa f (d,v) =
d,foldl (fun a i c -> (i |--> f(c)) a) undefined v;;
let is_zero (d,v) =
match v with
Empty -> true
| _ -> false;;
Vectors . Conventionally indexed 1 .. n.
let vector_0 n = (n,undefined:vector);;
let dim (v:vector) = fst v;;
let vector_const c n =
if c =/ Int 0 then vector_0 n
else (n,itlist (fun k -> k |-> c) (1--n) undefined :vector);;
let vector_1 = vector_const (Int 1);;
let vector_cmul c (v:vector) =
let n = dim v in
if c =/ Int 0 then vector_0 n
else n,mapf (fun x -> c */ x) (snd v)
let vector_neg (v:vector) = (fst v,mapf minus_num (snd v) :vector);;
let vector_add (v1:vector) (v2:vector) =
let m = dim v1 and n = dim v2 in
if m <> n then failwith "vector_add: incompatible dimensions" else
(n,combine (+/) (fun x -> x =/ Int 0) (snd v1) (snd v2) :vector);;
let vector_sub v1 v2 = vector_add v1 (vector_neg v2);;
let vector_dot (v1:vector) (v2:vector) =
let m = dim v1 and n = dim v2 in
if m <> n then failwith "vector_add: incompatible dimensions" else
foldl (fun a i x -> x +/ a) (Int 0)
(combine ( */ ) (fun x -> x =/ Int 0) (snd v1) (snd v2));;
let vector_of_list l =
let n = List.length l in
(n,itlist2 (|->) (1--n) l undefined :vector);;
Matrices ; again rows and columns indexed from 1 .
let matrix_0 (m,n) = ((m,n),undefined:matrix);;
let dimensions (m:matrix) = fst m;;
let matrix_const c (m,n as mn) =
if m <> n then failwith "matrix_const: needs to be square"
else if c =/ Int 0 then matrix_0 mn
else (mn,itlist (fun k -> (k,k) |-> c) (1--n) undefined :matrix);;
let matrix_1 = matrix_const (Int 1);;
let matrix_cmul c (m:matrix) =
let (i,j) = dimensions m in
if c =/ Int 0 then matrix_0 (i,j)
else (i,j),mapf (fun x -> c */ x) (snd m);;
let matrix_neg (m:matrix) = (dimensions m,mapf minus_num (snd m) :matrix);;
let matrix_add (m1:matrix) (m2:matrix) =
let d1 = dimensions m1 and d2 = dimensions m2 in
if d1 <> d2 then failwith "matrix_add: incompatible dimensions"
else (d1,combine (+/) (fun x -> x =/ Int 0) (snd m1) (snd m2) :matrix);;
let matrix_sub m1 m2 = matrix_add m1 (matrix_neg m2);;
let row k (m:matrix) =
let i,j = dimensions m in
(j,
foldl (fun a (i,j) c -> if i = k then (j |-> c) a else a) undefined (snd m)
: vector);;
let column k (m:matrix) =
let i,j = dimensions m in
(i,
foldl (fun a (i,j) c -> if j = k then (i |-> c) a else a) undefined (snd m)
: vector);;
let transp (m:matrix) =
let i,j = dimensions m in
((j,i),foldl (fun a (i,j) c -> ((j,i) |-> c) a) undefined (snd m) :matrix);;
let diagonal (v:vector) =
let n = dim v in
((n,n),foldl (fun a i c -> ((i,i) |-> c) a) undefined (snd v) : matrix);;
let matrix_of_list l =
let m = List.length l in
if m = 0 then matrix_0 (0,0) else
let n = List.length (List.hd l) in
(m,n),itern 1 l (fun v i -> itern 1 v (fun c j -> (i,j) |-> c)) undefined;;
let monomial_eval assig (m:monomial) =
foldl (fun a x k -> a */ power_num (apply assig x) (Int k))
(Int 1) m;;
let monomial_1 = (undefined:monomial);;
let monomial_var x = (x |=> 1 :monomial);;
let (monomial_mul:monomial->monomial->monomial) =
combine (+) (fun x -> false);;
let monomial_pow (m:monomial) k =
if k = 0 then monomial_1
else mapf (fun x -> k * x) m;;
let monomial_divides (m1:monomial) (m2:monomial) =
foldl (fun a x k -> tryapplyd m2 x 0 >= k && a) true m1;;
let monomial_div (m1:monomial) (m2:monomial) =
let m = combine (+) (fun x -> x = 0) m1 (mapf (fun x -> -x) m2) in
if foldl (fun a x k -> k >= 0 && a) true m then m
else failwith "monomial_div: non-divisible";;
let monomial_degree x (m:monomial) = tryapplyd m x 0;;
let monomial_lcm (m1:monomial) (m2:monomial) =
(itlist (fun x -> x |-> max (monomial_degree x m1) (monomial_degree x m2))
(union (dom m1) (dom m2)) undefined :monomial);;
let monomial_multidegree (m:monomial) = foldl (fun a x k -> k + a) 0 m;;
let monomial_variables m = dom m;;
let eval assig (p:poly) =
foldl (fun a m c -> a +/ c */ monomial_eval assig m) (Int 0) p;;
let poly_0 = (undefined:poly);;
let poly_isconst (p:poly) = foldl (fun a m c -> m = monomial_1 && a) true p;;
let poly_var x = ((monomial_var x) |=> Int 1 :poly);;
let poly_const c =
if c =/ Int 0 then poly_0 else (monomial_1 |=> c);;
let poly_cmul c (p:poly) =
if c =/ Int 0 then poly_0
else mapf (fun x -> c */ x) p;;
let poly_neg (p:poly) = (mapf minus_num p :poly);;
let poly_add (p1:poly) (p2:poly) =
(combine (+/) (fun x -> x =/ Int 0) p1 p2 :poly);;
let poly_sub p1 p2 = poly_add p1 (poly_neg p2);;
let poly_cmmul (c,m) (p:poly) =
if c =/ Int 0 then poly_0
else if m = monomial_1 then mapf (fun d -> c */ d) p
else foldl (fun a m' d -> (monomial_mul m m' |-> c */ d) a) poly_0 p;;
let poly_mul (p1:poly) (p2:poly) =
foldl (fun a m c -> poly_add (poly_cmmul (c,m) p2) a) poly_0 p1;;
let poly_div (p1:poly) (p2:poly) =
if not(poly_isconst p2) then failwith "poly_div: non-constant" else
let c = eval undefined p2 in
if c =/ Int 0 then failwith "poly_div: division by zero"
else poly_cmul (Int 1 // c) p1;;
let poly_square p = poly_mul p p;;
let rec poly_pow p k =
if k = 0 then poly_const (Int 1)
else if k = 1 then p
else let q = poly_square(poly_pow p (k / 2)) in
if k mod 2 = 1 then poly_mul p q else q;;
let poly_exp p1 p2 =
if not(poly_isconst p2) then failwith "poly_exp: not a constant" else
poly_pow p1 (Num.int_of_num (eval undefined p2));;
let degree x (p:poly) = foldl (fun a m c -> max (monomial_degree x m) a) 0 p;;
let multidegree (p:poly) =
foldl (fun a m c -> max (monomial_multidegree m) a) 0 p;;
let poly_variables (p:poly) =
foldr (fun m c -> union (monomial_variables m)) p [];;
let humanorder_varpow (x1,k1) (x2,k2) = x1 < x2 or x1 = x2 && k1 > k2;;
let humanorder_monomial =
let rec ord l1 l2 = match (l1,l2) with
_,[] -> true
| [],_ -> false
| h1::t1,h2::t2 -> humanorder_varpow h1 h2 or h1 = h2 && ord t1 t2 in
fun m1 m2 -> m1 = m2 or
ord (sort humanorder_varpow (graph m1))
(sort humanorder_varpow (graph m2));;
let string_of_vector min_size max_size (v:vector) =
let n_raw = dim v in
if n_raw = 0 then "[]" else
let n = max min_size (min n_raw max_size) in
let xs = List.map ((o) string_of_num (element v)) (1--n) in
"[" ^ end_itlist (fun s t -> s ^ ", " ^ t) xs ^
(if n_raw > max_size then ", ...]" else "]");;
let string_of_matrix max_size (m:matrix) =
let i_raw,j_raw = dimensions m in
let i = min max_size i_raw and j = min max_size j_raw in
let rstr = List.map (fun k -> string_of_vector j j (row k m)) (1--i) in
"["^end_itlist(fun s t -> s^";\n "^t) rstr ^
(if j > max_size then "\n ...]" else "]");;
let string_of_vname (v:vname): string = (v: string);;
let rec string_of_term t =
match t with
Opp t1 -> "(- " ^ string_of_term t1 ^ ")"
| Add (t1, t2) ->
"(" ^ (string_of_term t1) ^ " + " ^ (string_of_term t2) ^ ")"
| Sub (t1, t2) ->
"(" ^ (string_of_term t1) ^ " - " ^ (string_of_term t2) ^ ")"
| Mul (t1, t2) ->
"(" ^ (string_of_term t1) ^ " * " ^ (string_of_term t2) ^ ")"
| Inv t1 -> "(/ " ^ string_of_term t1 ^ ")"
| Div (t1, t2) ->
"(" ^ (string_of_term t1) ^ " / " ^ (string_of_term t2) ^ ")"
| Pow (t1, n1) ->
"(" ^ (string_of_term t1) ^ " ^ " ^ (string_of_int n1) ^ ")"
| Zero -> "0"
| Var v -> "x" ^ (string_of_vname v)
| Const x -> string_of_num x;;
let string_of_varpow x k =
if k = 1 then string_of_vname x else string_of_vname x^"^"^string_of_int k;;
let string_of_monomial m =
if m = monomial_1 then "1" else
let vps = List.fold_right (fun (x,k) a -> string_of_varpow x k :: a)
(sort humanorder_varpow (graph m)) [] in
end_itlist (fun s t -> s^"*"^t) vps;;
let string_of_cmonomial (c,m) =
if m = monomial_1 then string_of_num c
else if c =/ Int 1 then string_of_monomial m
else string_of_num c ^ "*" ^ string_of_monomial m;;
let string_of_poly (p:poly) =
if p = poly_0 then "<<0>>" else
let cms = sort (fun (m1,_) (m2,_) -> humanorder_monomial m1 m2) (graph p) in
let s =
List.fold_left (fun a (m,c) ->
if c </ Int 0 then a ^ " - " ^ string_of_cmonomial(minus_num c,m)
else a ^ " + " ^ string_of_cmonomial(c,m))
"" cms in
let s1 = String.sub s 0 3
and s2 = String.sub s 3 (String.length s - 3) in
"<<" ^(if s1 = " + " then s2 else "-"^s2)^">>";;
let print_vector v = Format.print_string(string_of_vector 0 20 v);;
let print_matrix m = Format.print_string(string_of_matrix 20 m);;
let print_monomial m = Format.print_string(string_of_monomial m);;
let print_poly m = Format.print_string(string_of_poly m);;
let rec poly_of_term t = match t with
Zero -> poly_0
| Const n -> poly_const n
| Var x -> poly_var x
| Opp t1 -> poly_neg (poly_of_term t1)
| Inv t1 ->
let p = poly_of_term t1 in
if poly_isconst p then poly_const(Int 1 // eval undefined p)
else failwith "poly_of_term: inverse of non-constant polyomial"
| Add (l, r) -> poly_add (poly_of_term l) (poly_of_term r)
| Sub (l, r) -> poly_sub (poly_of_term l) (poly_of_term r)
| Mul (l, r) -> poly_mul (poly_of_term l) (poly_of_term r)
| Div (l, r) ->
let p = poly_of_term l and q = poly_of_term r in
if poly_isconst q then poly_cmul (Int 1 // eval undefined q) p
else failwith "poly_of_term: division by non-constant polynomial"
| Pow (t, n) ->
poly_pow (poly_of_term t) n;;
let sdpa_of_vector (v:vector) =
let n = dim v in
let strs = List.map (o (decimalize 20) (element v)) (1--n) in
end_itlist (fun x y -> x ^ " " ^ y) strs ^ "\n";;
String for block diagonal matrix numbered
let sdpa_of_blockdiagonal k m =
let pfx = string_of_int k ^" " in
let ents =
foldl (fun a (b,i,j) c -> if i > j then a else ((b,i,j),c)::a) [] m in
let entss = sort (increasing fst) ents in
itlist (fun ((b,i,j),c) a ->
pfx ^ string_of_int b ^ " " ^ string_of_int i ^ " " ^ string_of_int j ^
" " ^ decimalize 20 c ^ "\n" ^ a) entss "";;
String for a matrix numbered k , in SDPA sparse format .
let sdpa_of_matrix k (m:matrix) =
let pfx = string_of_int k ^ " 1 " in
let ms = foldr (fun (i,j) c a -> if i > j then a else ((i,j),c)::a)
(snd m) [] in
let mss = sort (increasing fst) ms in
itlist (fun ((i,j),c) a ->
pfx ^ string_of_int i ^ " " ^ string_of_int j ^
" " ^ decimalize 20 c ^ "\n" ^ a) mss "";;
String in SDPA sparse format for standard SDP problem :
[ M_1 ] + ... + v_m * [ M_m ] - [ M_0 ] must be PSD
Minimize obj_1 * + ... obj_m * v_m
let sdpa_of_problem comment obj mats =
let m = List.length mats - 1
and n,_ = dimensions (List.hd mats) in
"\"" ^ comment ^ "\"\n" ^
string_of_int m ^ "\n" ^
"1\n" ^
string_of_int n ^ "\n" ^
sdpa_of_vector obj ^
itlist2 (fun k m a -> sdpa_of_matrix (k - 1) m ^ a)
(1--List.length mats) mats "";;
let word s =
end_itlist (fun p1 p2 -> (p1 ++ p2) >> (fun (s,t) -> s^t))
(List.map a (explode s));;
let token s =
many (some isspace) ++ word s ++ many (some isspace)
>> (fun ((_,t),_) -> t);;
let decimal =
let numeral = some isnum in
let decimalint = atleast 1 numeral >> ((o) Num.num_of_string implode) in
let decimalfrac = atleast 1 numeral
>> (fun s -> Num.num_of_string(implode s) // pow10 (List.length s)) in
let decimalsig =
decimalint ++ possibly (a "." ++ decimalfrac >> snd)
>> (function (h,[x]) -> h +/ x | (h,_) -> h) in
let signed prs =
a "-" ++ prs >> ((o) minus_num snd)
|| a "+" ++ prs >> snd
|| prs in
let exponent = (a "e" || a "E") ++ signed decimalint >> snd in
signed decimalsig ++ possibly exponent
>> (function (h,[x]) -> h */ power_num (Int 10) x | (h,_) -> h);;
let mkparser p s =
let x,rst = p(explode s) in
if rst = [] then x else failwith "mkparser: unparsed input";;
let parse_decimal = mkparser decimal;;
Parse back a vector .
let parse_sdpaoutput,parse_csdpoutput =
let vector =
token "{" ++ listof decimal (token ",") "decimal" ++ token "}"
>> (fun ((_,v),_) -> vector_of_list v) in
let rec skipupto dscr prs inp =
(dscr ++ prs >> snd
|| some (fun c -> true) ++ skipupto dscr prs >> snd) inp in
let ignore inp = (),[] in
let sdpaoutput =
skipupto (word "xVec" ++ token "=")
(vector ++ ignore >> fst) in
let csdpoutput =
(decimal ++ many(a " " ++ decimal >> snd) >> (fun (h,t) -> h::t)) ++
(a " " ++ a "\n" ++ ignore) >> ((o) vector_of_list fst) in
mkparser sdpaoutput,mkparser csdpoutput;;
Also parse the SDPA output to test success ( CSDP yields a return code ) .
let sdpa_run_succeeded =
let rec skipupto dscr prs inp =
(dscr ++ prs >> snd
|| some (fun c -> true) ++ skipupto dscr prs >> snd) inp in
let prs = skipupto (word "phase.value" ++ token "=")
(possibly (a "p") ++ possibly (a "d") ++
(word "OPT" || word "FEAS")) in
fun s -> try ignore (prs (explode s)); true with Noparse -> false;;
let sdpa_default_parameters =
"100 unsigned int maxIteration;\
\n1.0E-7 double 0.0 < epsilonStar;\
\n1.0E2 double 0.0 < lambdaStar;\
\n2.0 double 1.0 < omegaStar;\
\n-1.0E5 double lowerBound;\
\n1.0E5 double upperBound;\
\n0.1 double 0.0 <= betaStar < 1.0;\
\n0.2 double 0.0 <= betaBar < 1.0, betaStar <= betaBar;\
\n0.9 double 0.0 < gammaStar < 1.0;\
\n1.0E-7 double 0.0 < epsilonDash;\
\n";;
These were suggested by for problems where we are
let sdpa_alt_parameters =
"1000 unsigned int maxIteration;\
\n1.0E-7 double 0.0 < epsilonStar;\
\n1.0E4 double 0.0 < lambdaStar;\
\n2.0 double 1.0 < omegaStar;\
\n-1.0E5 double lowerBound;\
\n1.0E5 double upperBound;\
\n0.1 double 0.0 <= betaStar < 1.0;\
\n0.2 double 0.0 <= betaBar < 1.0, betaStar <= betaBar;\
\n0.9 double 0.0 < gammaStar < 1.0;\
\n1.0E-7 double 0.0 < epsilonDash;\
\n";;
let sdpa_params = sdpa_alt_parameters;;
CSDP parameters ; so far I 'm sticking with the defaults .
let csdp_default_parameters =
"axtol=1.0e-8\
\natytol=1.0e-8\
\nobjtol=1.0e-8\
\npinftol=1.0e8\
\ndinftol=1.0e8\
\nmaxiter=100\
\nminstepfrac=0.9\
\nmaxstepfrac=0.97\
\nminstepp=1.0e-8\
\nminstepd=1.0e-8\
\nusexzgap=1\
\ntweakgap=0\
\naffine=0\
\nprintlevel=1\
\n";;
let csdp_params = csdp_default_parameters;;
Now call CSDP on a problem and parse back the output .
let run_csdp dbg obj mats =
let input_file = Filename.temp_file "sos" ".dat-s" in
let output_file =
String.sub input_file 0 (String.length input_file - 6) ^ ".out"
and params_file = Filename.concat (!temp_path) "param.csdp" in
file_of_string input_file (sdpa_of_problem "" obj mats);
file_of_string params_file csdp_params;
let rv = Sys.command("cd "^(!temp_path)^"; csdp "^input_file ^
" " ^ output_file ^
(if dbg then "" else "> /dev/null")) in
let op = string_of_file output_file in
let res = parse_csdpoutput op in
((if dbg then ()
else (Sys.remove input_file; Sys.remove output_file));
rv,res);;
let csdp obj mats =
let rv,res = run_csdp (!debugging) obj mats in
(if rv = 1 or rv = 2 then failwith "csdp: Problem is infeasible"
else if rv = 3 then ()
Format.print_string " csdp warning : Reduced accuracy " ;
( )
Format.print_newline() *)
else if rv <> 0 then failwith("csdp: error "^string_of_int rv)
else ());
res;;
Try some apparently sensible scaling first . Note that this is purely to
let scale_then =
let common_denominator amat acc =
foldl (fun a m c -> lcm_num (denominator c) a) acc amat
and maximal_element amat acc =
foldl (fun maxa m c -> max_num maxa (abs_num c)) acc amat in
fun solver obj mats ->
let cd1 = itlist common_denominator mats (Int 1)
and cd2 = common_denominator (snd obj) (Int 1) in
let mats' = List.map (mapf (fun x -> cd1 */ x)) mats
and obj' = vector_cmul cd2 obj in
let max1 = itlist maximal_element mats' (Int 0)
and max2 = maximal_element (snd obj') (Int 0) in
let scal1 = pow2 (20-int_of_float(log(float_of_num max1) /. log 2.0))
and scal2 = pow2 (20-int_of_float(log(float_of_num max2) /. log 2.0)) in
let mats'' = List.map (mapf (fun x -> x */ scal1)) mats'
and obj'' = vector_cmul scal2 obj' in
solver obj'' mats'';;
let nice_rational n x = round_num (n */ x) // n;;
let nice_vector n = mapa (nice_rational n);;
Reduce linear program to SDP ( diagonal matrices ) and test with CSDP . This
one tests A [ -1;x1; .. ;xn ] > = 0 ( i.e. left column is negated constants ) .
let linear_program_basic a =
let m,n = dimensions a in
let mats = List.map (fun j -> diagonal (column j a)) (1--n)
and obj = vector_const (Int 1) m in
let rv,res = run_csdp false obj mats in
if rv = 1 or rv = 2 then false
else if rv = 0 then true
else failwith "linear_program: An error occurred in the SDP solver";;
let linear_program a b =
let m,n = dimensions a in
if dim b <> m then failwith "linear_program: incompatible dimensions" else
let mats = diagonal b :: List.map (fun j -> diagonal (column j a)) (1--n)
and obj = vector_const (Int 1) m in
let rv,res = run_csdp false obj mats in
if rv = 1 or rv = 2 then false
else if rv = 0 then true
else failwith "linear_program: An error occurred in the SDP solver";;
computational geometry , express as linear inequalities and call CSDP .
let in_convex_hull pts pt =
let pts1 = (1::pt) :: List.map (fun x -> 1::x) pts in
let pts2 = List.map (fun p -> List.map (fun x -> -x) p @ p) pts1 in
let n = List.length pts + 1
and v = 2 * (List.length pt + 1) in
let m = v + n - 1 in
let mat =
(m,n),
itern 1 pts2 (fun pts j -> itern 1 pts (fun x i -> (i,j) |-> Int x))
(iter (1,n) (fun i -> (v + i,i+1) |-> Int 1) undefined) in
linear_program_basic mat;;
let minimal_convex_hull =
let augment1 = function
| [] -> assert false
| (m::ms) -> if in_convex_hull ms m then ms else ms@[m] in
let augment m ms = funpow 3 augment1 (m::ms) in
fun mons ->
let mons' = itlist augment (List.tl mons) [List.hd mons] in
funpow (List.length mons') augment1 mons';;
Stuff for " equations " ( generic functions ) .
let equation_cmul c eq =
if c =/ Int 0 then Empty else mapf (fun d -> c */ d) eq;;
let equation_add eq1 eq2 = combine (+/) (fun x -> x =/ Int 0) eq1 eq2;;
let equation_eval assig eq =
let value v = apply assig v in
foldl (fun a v c -> a +/ value(v) */ c) (Int 0) eq;;
Eliminate among linear equations : return unconstrained variables and
assignments for the others in terms of them . We give one pseudo - variable
let failstore = ref [];;
let eliminate_equations =
let rec extract_first p l =
match l with
[] -> failwith "extract_first"
| h::t -> if p(h) then h,t else
let k,s = extract_first p t in
k,h::s in
let rec eliminate vars dun eqs =
match vars with
[] -> if forall is_undefined eqs then dun
else (failstore := [vars,dun,eqs]; raise Unsolvable)
| v::vs ->
try let eq,oeqs = extract_first (fun e -> defined e v) eqs in
let a = apply eq v in
let eq' = equation_cmul (Int(-1) // a) (undefine v eq) in
let elim e =
let b = tryapplyd e v (Int 0) in
if b =/ Int 0 then e else
equation_add e (equation_cmul (minus_num b // a) eq) in
eliminate vs ((v |-> eq') (mapf elim dun)) (List.map elim oeqs)
with Failure _ -> eliminate vs dun eqs in
fun one vars eqs ->
let assig = eliminate vars undefined eqs in
let vs = foldl (fun a x f -> subtract (dom f) [one] @ a) [] assig in
setify vs,assig;;
let eliminate_all_equations one =
let choose_variable eq =
let (v,_) = choose eq in
if v = one then
let eq' = undefine v eq in
if is_undefined eq' then failwith "choose_variable" else
let (w,_) = choose eq' in w
else v in
let rec eliminate dun eqs =
match eqs with
[] -> dun
| eq::oeqs ->
if is_undefined eq then eliminate dun oeqs else
let v = choose_variable eq in
let a = apply eq v in
let eq' = equation_cmul (Int(-1) // a) (undefine v eq) in
let elim e =
let b = tryapplyd e v (Int 0) in
if b =/ Int 0 then e else
equation_add e (equation_cmul (minus_num b // a) eq) in
eliminate ((v |-> eq') (mapf elim dun)) (List.map elim oeqs) in
fun eqs ->
let assig = eliminate undefined eqs in
let vs = foldl (fun a x f -> subtract (dom f) [one] @ a) [] assig in
setify vs,assig;;
let solve_equations one eqs =
let vars,assigs = eliminate_all_equations one eqs in
let vfn = itlist (fun v -> (v |-> Int 0)) vars (one |=> Int(-1)) in
let ass =
combine (+/) (fun c -> false) (mapf (equation_eval vfn) assigs) vfn in
if forall (fun e -> equation_eval ass e =/ Int 0) eqs
then undefine one ass else raise Sanity;;
Newton polytope of the monomials in the input . ( This is enough according
to : " Extremal PSD forms with few terms " , Duke Math . Journal ,
vol 45 , pp . 363 - -374 , 1978 .
let newton_polytope pol =
let vars = poly_variables pol in
let mons = List.map (fun m -> List.map (fun x -> monomial_degree x m) vars) (dom pol)
and ds = List.map (fun x -> (degree x pol + 1) / 2) vars in
let all = itlist (fun n -> allpairs (fun h t -> h::t) (0--n)) ds [[]]
and mons' = minimal_convex_hull mons in
let all' =
List.filter (fun m -> in_convex_hull mons' (List.map (fun x -> 2 * x) m)) all in
List.map (fun m -> itlist2 (fun v i a -> if i = 0 then a else (v |-> i) a)
vars m monomial_1) (List.rev all');;
Diagonalize ( Cholesky / LDU ) the matrix corresponding to a quadratic form .
let diag m =
let nn = dimensions m in
let n = fst nn in
if snd nn <> n then failwith "diagonalize: non-square matrix" else
let rec diagonalize i m =
if is_zero m then [] else
let a11 = element m (i,i) in
if a11 </ Int 0 then failwith "diagonalize: not PSD"
else if a11 =/ Int 0 then
if is_zero(row i m) then diagonalize (i + 1) m
else failwith "diagonalize: not PSD"
else
let v = row i m in
let v' = mapa (fun a1k -> a1k // a11) v in
let m' =
(n,n),
iter (i+1,n) (fun j ->
iter (i+1,n) (fun k ->
((j,k) |--> (element m (j,k) -/ element v j */ element v' k))))
undefined in
(a11,v')::diagonalize (i + 1) m' in
diagonalize 1 m;;
let deration d =
if d = [] then Int 0,d else
let adj(c,l) =
let a = foldl (fun a i c -> lcm_num a (denominator c)) (Int 1) (snd l) //
foldl (fun a i c -> gcd_num a (numerator c)) (Int 0) (snd l) in
(c // (a */ a)),mapa (fun x -> a */ x) l in
let d' = List.map adj d in
let a = itlist ((o) lcm_num ( (o) denominator fst)) d' (Int 1) //
itlist ((o) gcd_num ( (o) numerator fst)) d' (Int 0) in
(Int 1 // a),List.map (fun (c,l) -> (a */ c,l)) d';;
Enumeration of monomials with given bound .
let rec enumerate_monomials d vars =
if d < 0 then []
else if d = 0 then [undefined]
else if vars = [] then [monomial_1] else
let alts =
List.map (fun k -> let oths = enumerate_monomials (d - k) (List.tl vars) in
List.map (fun ks -> if k = 0 then ks else (List.hd vars |-> k) ks) oths)
(0--d) in
end_itlist (@) alts;;
let rec enumerate_products d pols =
if d = 0 then [poly_const num_1,Rational_lt num_1] else if d < 0 then [] else
match pols with
[] -> [poly_const num_1,Rational_lt num_1]
| (p,b)::ps -> let e = multidegree p in
if e = 0 then enumerate_products d ps else
enumerate_products d ps @
List.map (fun (q,c) -> poly_mul p q,Product(b,c))
(enumerate_products (d - e) ps);;
let epoly_pmul p q acc =
foldl (fun a m1 c ->
foldl (fun b m2 e ->
let m = monomial_mul m1 m2 in
let es = tryapplyd b m undefined in
(m |-> equation_add (equation_cmul c e) es) b)
a q) acc p;;
let epoly_cmul c l =
if c =/ Int 0 then undefined else mapf (equation_cmul c) l;;
let epoly_neg = epoly_cmul (Int(-1));;
let epoly_add = combine equation_add is_undefined;;
let epoly_sub p q = epoly_add p (epoly_neg q);;
let epoly_of_poly p =
foldl (fun a m c -> (m |-> ((0,0,0) |=> minus_num c)) a) undefined p;;
String for block diagonal matrix numbered
let sdpa_of_blockdiagonal k m =
let pfx = string_of_int k ^" " in
let ents =
foldl (fun a (b,i,j) c -> if i > j then a else ((b,i,j),c)::a) [] m in
let entss = sort (increasing fst) ents in
itlist (fun ((b,i,j),c) a ->
pfx ^ string_of_int b ^ " " ^ string_of_int i ^ " " ^ string_of_int j ^
" " ^ decimalize 20 c ^ "\n" ^ a) entss "";;
SDPA for problem using block diagonal ( i.e. multiple SDPs )
let sdpa_of_blockproblem comment nblocks blocksizes obj mats =
let m = List.length mats - 1 in
"\"" ^ comment ^ "\"\n" ^
string_of_int m ^ "\n" ^
string_of_int nblocks ^ "\n" ^
(end_itlist (fun s t -> s^" "^t) (List.map string_of_int blocksizes)) ^
"\n" ^
sdpa_of_vector obj ^
itlist2 (fun k m a -> sdpa_of_blockdiagonal (k - 1) m ^ a)
(1--List.length mats) mats "";;
Hence run CSDP on a problem in block diagonal form .
let run_csdp dbg nblocks blocksizes obj mats =
let input_file = Filename.temp_file "sos" ".dat-s" in
let output_file =
String.sub input_file 0 (String.length input_file - 6) ^ ".out"
and params_file = Filename.concat (!temp_path) "param.csdp" in
file_of_string input_file
(sdpa_of_blockproblem "" nblocks blocksizes obj mats);
file_of_string params_file csdp_params;
let rv = Sys.command("cd "^(!temp_path)^"; csdp "^input_file ^
" " ^ output_file ^
(if dbg then "" else "> /dev/null")) in
let op = string_of_file output_file in
let res = parse_csdpoutput op in
((if dbg then ()
else (Sys.remove input_file; Sys.remove output_file));
rv,res);;
let csdp nblocks blocksizes obj mats =
let rv,res = run_csdp (!debugging) nblocks blocksizes obj mats in
(if rv = 1 or rv = 2 then failwith "csdp: Problem is infeasible"
else if rv = 3 then ()
Format.print_string " csdp warning : Reduced accuracy " ;
( )
Format.print_newline() *)
else if rv <> 0 then failwith("csdp: error "^string_of_int rv)
else ());
res;;
let bmatrix_add = combine (+/) (fun x -> x =/ Int 0);;
let bmatrix_cmul c bm =
if c =/ Int 0 then undefined
else mapf (fun x -> c */ x) bm;;
let bmatrix_neg = bmatrix_cmul (Int(-1));;
let bmatrix_sub m1 m2 = bmatrix_add m1 (bmatrix_neg m2);;
let blocks blocksizes bm =
List.map (fun (bs,b0) ->
let m = foldl
(fun a (b,i,j) c -> if b = b0 then ((i,j) |-> c) a else a)
undefined bm in
(((bs,bs),m):matrix))
(zip blocksizes (1--List.length blocksizes));;
let real_positivnullstellensatz_general linf d eqs leqs pol =
let vars = itlist ((o) union poly_variables) (pol::eqs @ List.map fst leqs) [] in
let monoid =
if linf then
(poly_const num_1,Rational_lt num_1)::
(List.filter (fun (p,c) -> multidegree p <= d) leqs)
else enumerate_products d leqs in
let nblocks = List.length monoid in
let mk_idmultiplier k p =
let e = d - multidegree p in
let mons = enumerate_monomials e vars in
let nons = zip mons (1--List.length mons) in
mons,
itlist (fun (m,n) -> (m |-> ((-k,-n,n) |=> Int 1))) nons undefined in
let mk_sqmultiplier k (p,c) =
let e = (d - multidegree p) / 2 in
let mons = enumerate_monomials e vars in
let nons = zip mons (1--List.length mons) in
mons,
itlist (fun (m1,n1) ->
itlist (fun (m2,n2) a ->
let m = monomial_mul m1 m2 in
if n1 > n2 then a else
let c = if n1 = n2 then Int 1 else Int 2 in
let e = tryapplyd a m undefined in
(m |-> equation_add ((k,n1,n2) |=> c) e) a)
nons)
nons undefined in
let sqmonlist,sqs = unzip(List.map2 mk_sqmultiplier (1--List.length monoid) monoid)
and idmonlist,ids = unzip(List.map2 mk_idmultiplier (1--List.length eqs) eqs) in
let blocksizes = List.map List.length sqmonlist in
let bigsum =
itlist2 (fun p q a -> epoly_pmul p q a) eqs ids
(itlist2 (fun (p,c) s a -> epoly_pmul p s a) monoid sqs
(epoly_of_poly(poly_neg pol))) in
let eqns = foldl (fun a m e -> e::a) [] bigsum in
let pvs,assig = eliminate_all_equations (0,0,0) eqns in
let qvars = (0,0,0)::pvs in
let allassig = itlist (fun v -> (v |-> (v |=> Int 1))) pvs assig in
let mk_matrix v =
foldl (fun m (b,i,j) ass -> if b < 0 then m else
let c = tryapplyd ass v (Int 0) in
if c =/ Int 0 then m else
((b,j,i) |-> c) (((b,i,j) |-> c) m))
undefined allassig in
let diagents = foldl
(fun a (b,i,j) e -> if b > 0 && i = j then equation_add e a else a)
undefined allassig in
let mats = List.map mk_matrix qvars
and obj = List.length pvs,
itern 1 pvs (fun v i -> (i |--> tryapplyd diagents v (Int 0)))
undefined in
let raw_vec = if pvs = [] then vector_0 0
else scale_then (csdp nblocks blocksizes) obj mats in
let find_rounding d =
(if !debugging then
(Format.print_string("Trying rounding with limit "^string_of_num d);
Format.print_newline())
else ());
let vec = nice_vector d raw_vec in
let blockmat = iter (1,dim vec)
(fun i a -> bmatrix_add (bmatrix_cmul (element vec i) (el i mats)) a)
(bmatrix_neg (el 0 mats)) in
let allmats = blocks blocksizes blockmat in
vec,List.map diag allmats in
let vec,ratdias =
if pvs = [] then find_rounding num_1
else tryfind find_rounding (List.map Num.num_of_int (1--31) @
List.map pow2 (5--66)) in
let newassigs =
itlist (fun k -> el (k - 1) pvs |-> element vec k)
(1--dim vec) ((0,0,0) |=> Int(-1)) in
let finalassigs =
foldl (fun a v e -> (v |-> equation_eval newassigs e) a) newassigs
allassig in
let poly_of_epoly p =
foldl (fun a v e -> (v |--> equation_eval finalassigs e) a)
undefined p in
let mk_sos mons =
let mk_sq (c,m) =
c,itlist (fun k a -> (el (k - 1) mons |--> element m k) a)
(1--List.length mons) undefined in
List.map mk_sq in
let sqs = List.map2 mk_sos sqmonlist ratdias
and cfs = List.map poly_of_epoly ids in
let msq = List.filter (fun (a,b) -> b <> []) (List.map2 (fun a b -> a,b) monoid sqs) in
let eval_sq sqs = itlist
(fun (c,q) -> poly_add (poly_cmul c (poly_mul q q))) sqs poly_0 in
let sanity =
itlist (fun ((p,c),s) -> poly_add (poly_mul p (eval_sq s))) msq
(itlist2 (fun p q -> poly_add (poly_mul p q)) cfs eqs
(poly_neg pol)) in
if not(is_undefined sanity) then raise Sanity else
cfs,List.map (fun (a,b) -> snd a,b) msq;;
let rec deepen f n =
try print_string "Searching with depth limit ";
print_int n; print_newline(); f n
with Failure _ -> deepen f (n + 1);;
The ordering so we can create canonical HOL polynomials .
let dest_monomial mon = sort (increasing fst) (graph mon);;
let monomial_order =
let rec lexorder l1 l2 =
match (l1,l2) with
[],[] -> true
| vps,[] -> false
| [],vps -> true
| ((x1,n1)::vs1),((x2,n2)::vs2) ->
if x1 < x2 then true
else if x2 < x1 then false
else if n1 < n2 then false
else if n2 < n1 then true
else lexorder vs1 vs2 in
fun m1 m2 ->
if m2 = monomial_1 then true else if m1 = monomial_1 then false else
let mon1 = dest_monomial m1 and mon2 = dest_monomial m2 in
let deg1 = itlist ((o) (+) snd) mon1 0
and deg2 = itlist ((o) (+) snd) mon2 0 in
if deg1 < deg2 then false else if deg1 > deg2 then true
else lexorder mon1 mon2;;
let dest_poly p =
List.map (fun (m,c) -> c,dest_monomial m)
(sort (fun (m1,_) (m2,_) -> monomial_order m1 m2) (graph p));;
Map back polynomials and their composites to HOL .
let term_of_varpow =
fun x k ->
if k = 1 then Var x else Pow (Var x, k);;
let term_of_monomial =
fun m -> if m = monomial_1 then Const num_1 else
let m' = dest_monomial m in
let vps = itlist (fun (x,k) a -> term_of_varpow x k :: a) m' [] in
end_itlist (fun s t -> Mul (s,t)) vps;;
let term_of_cmonomial =
fun (m,c) ->
if m = monomial_1 then Const c
else if c =/ num_1 then term_of_monomial m
else Mul (Const c,term_of_monomial m);;
let term_of_poly =
fun p ->
if p = poly_0 then Zero else
let cms = List.map term_of_cmonomial
(sort (fun (m1,_) (m2,_) -> monomial_order m1 m2) (graph p)) in
end_itlist (fun t1 t2 -> Add (t1,t2)) cms;;
let term_of_sqterm (c,p) =
Product(Rational_lt c,Square(term_of_poly p));;
let term_of_sos (pr,sqs) =
if sqs = [] then pr
else Product(pr,end_itlist (fun a b -> Sum(a,b)) (List.map term_of_sqterm sqs));;
Interface to HOL .
let REAL_NONLINEAR_PROVER translator ( eqs , les , lts ) =
let eq0 = map ( poly_of_term o lhand o concl ) eqs
and le0 = map ( poly_of_term o lhand o concl ) les
and lt0 = map ( poly_of_term o lhand o concl ) lts in
let eqp0 = map ( fun ( t , i ) - > t , Axiom_eq i ) ( zip eq0 ( 0 - -(length eq0 - 1 ) ) )
and lep0 = map ( fun ( t , i ) - > t , Axiom_le i ) ( zip le0 ( 0 - -(length le0 - 1 ) ) )
and ltp0 = map ( fun ( t , i ) - > t , Axiom_lt i ) ( zip lt0 ( 0 - -(length lt0 - 1 ) ) ) in
let keq , eq = partition ( fun ( p , _ ) - > multidegree p = 0 ) eqp0
and klep , lep = partition ( fun ( p , _ ) - > multidegree p = 0 ) lep0
and kltp , ltp = partition ( fun ( p , _ ) - > multidegree p = 0 ) ltp0 in
let trivial_axiom ( p , ax ) =
match ax with
Axiom_eq n when eval undefined p < > / num_0 - > el n eqs
| Axiom_le n when eval undefined p < / num_0 - > el n les
| Axiom_lt n when eval undefined p < =/ num_0 - > el n lts
| _ - > failwith " not a trivial axiom " in
try let th = tryfind trivial_axiom ( keq @ klep @ kltp ) in
CONV_RULE ( LAND_CONV REAL_POLY_CONV THENC REAL_RAT_RED_CONV ) th
with Failure _ - >
let pol = ( map fst ltp ) ( poly_const num_1 ) in
let leq = lep @ ltp in
let tryall d =
let e = in
let k = if e = 0 then 0 else d / e in
let eq ' = map fst eq in
tryfind ( fun i - > d , i , real_positivnullstellensatz_general false d eq ' leq
( poly_neg(poly_pow pol i ) ) )
( 0 - -k ) in
let d , i,(cert_ideal , cert_cone ) = deepen tryall 0 in
let proofs_ideal =
map2 ( fun q ( p , ax ) - > Eqmul(term_of_poly q , ax ) ) and proofs_cone = map term_of_sos cert_cone
and proof_ne =
if ltp = [ ] then Rational_lt num_1 else
let p = end_itlist ( fun s t - > Product(s , t ) ) ( map snd ltp ) in
funpow i ( fun q - > Product(p , q ) ) ( Rational_lt num_1 ) in
let proof = end_itlist ( fun s t - > Sum(s , t ) )
( proof_ne : : proofs_ideal @ proofs_cone ) in
print_string("Translating proof certificate to HOL " ) ;
print_newline ( ) ;
translator ( eqs , les , lts ) proof ; ;
let REAL_NONLINEAR_PROVER translator (eqs,les,lts) =
let eq0 = map (poly_of_term o lhand o concl) eqs
and le0 = map (poly_of_term o lhand o concl) les
and lt0 = map (poly_of_term o lhand o concl) lts in
let eqp0 = map (fun (t,i) -> t,Axiom_eq i) (zip eq0 (0--(length eq0 - 1)))
and lep0 = map (fun (t,i) -> t,Axiom_le i) (zip le0 (0--(length le0 - 1)))
and ltp0 = map (fun (t,i) -> t,Axiom_lt i) (zip lt0 (0--(length lt0 - 1))) in
let keq,eq = partition (fun (p,_) -> multidegree p = 0) eqp0
and klep,lep = partition (fun (p,_) -> multidegree p = 0) lep0
and kltp,ltp = partition (fun (p,_) -> multidegree p = 0) ltp0 in
let trivial_axiom (p,ax) =
match ax with
Axiom_eq n when eval undefined p <>/ num_0 -> el n eqs
| Axiom_le n when eval undefined p </ num_0 -> el n les
| Axiom_lt n when eval undefined p <=/ num_0 -> el n lts
| _ -> failwith "not a trivial axiom" in
try let th = tryfind trivial_axiom (keq @ klep @ kltp) in
CONV_RULE (LAND_CONV REAL_POLY_CONV THENC REAL_RAT_RED_CONV) th
with Failure _ ->
let pol = itlist poly_mul (map fst ltp) (poly_const num_1) in
let leq = lep @ ltp in
let tryall d =
let e = multidegree pol in
let k = if e = 0 then 0 else d / e in
let eq' = map fst eq in
tryfind (fun i -> d,i,real_positivnullstellensatz_general false d eq' leq
(poly_neg(poly_pow pol i)))
(0--k) in
let d,i,(cert_ideal,cert_cone) = deepen tryall 0 in
let proofs_ideal =
map2 (fun q (p,ax) -> Eqmul(term_of_poly q,ax)) cert_ideal eq
and proofs_cone = map term_of_sos cert_cone
and proof_ne =
if ltp = [] then Rational_lt num_1 else
let p = end_itlist (fun s t -> Product(s,t)) (map snd ltp) in
funpow i (fun q -> Product(p,q)) (Rational_lt num_1) in
let proof = end_itlist (fun s t -> Sum(s,t))
(proof_ne :: proofs_ideal @ proofs_cone) in
print_string("Translating proof certificate to HOL");
print_newline();
translator (eqs,les,lts) proof;;
*)
A wrapper that tries to substitute away variables first .
let =
let zero = ` & 0 : real `
and mul_tm = ` ( * ): real->real->real `
and shuffle1 =
CONV_RULE(REWR_CONV(REAL_ARITH ` a + x = ( y : real ) < = > x = y - a ` ) )
and shuffle2 =
CONV_RULE(REWR_CONV(REAL_ARITH ` x + a = ( y : real ) < = > x = y - a ` ) ) in
let rec substitutable_monomial fvs tm =
match tm with
Var(_,Tyapp("real " , [ ] ) ) when not ( mem tm fvs ) - > Int 1,tm
| Comb(Comb(Const("real_mul",_),c),(Var ( _ , _ ) as t ) )
when is_ratconst c & & not ( mem t fvs )
- > rat_of_term c , t
| ) - >
( try substitutable_monomial ( union ( frees t ) fvs ) s
with Failure _ - > substitutable_monomial ( union ( frees s ) fvs ) t )
| _ - > failwith " substitutable_monomial "
and isolate_variable v th =
match lhs(concl th ) with
x when x = v - > th
| Comb(Comb(Const("real_add",_),(Var(_,Tyapp("real " , [ ] ) ) as )
when x = v - > shuffle2 th
| ) - >
isolate_variable v(shuffle1 th ) in
let make_substitution th =
let ( c , v ) = substitutable_monomial [ ] ( lhs(concl th ) ) in
let th1 = AP_TERM ( mk_comb(mul_tm , term_of_rat(Int 1 // c ) ) ) th in
let th2 = CONV_RULE(BINOP_CONV REAL_POLY_MUL_CONV ) th1 in
CONV_RULE ( RAND_CONV REAL_POLY_CONV ) ( isolate_variable v th2 ) in
fun translator - >
let rec substfirst(eqs , les , lts ) =
try let eth = in
let modify =
CONV_RULE(LAND_CONV(SUBS_CONV[eth ] THENC REAL_POLY_CONV ) ) in
substfirst(filter ( fun t - > lhand(concl t ) < > zero ) ( map modify eqs ) ,
map modify les , map modify lts )
with Failure _ - > REAL_NONLINEAR_PROVER translator ( eqs , les , lts ) in
substfirst ; ;
let REAL_NONLINEAR_SUBST_PROVER =
let zero = `&0:real`
and mul_tm = `( * ):real->real->real`
and shuffle1 =
CONV_RULE(REWR_CONV(REAL_ARITH `a + x = (y:real) <=> x = y - a`))
and shuffle2 =
CONV_RULE(REWR_CONV(REAL_ARITH `x + a = (y:real) <=> x = y - a`)) in
let rec substitutable_monomial fvs tm =
match tm with
Var(_,Tyapp("real",[])) when not (mem tm fvs) -> Int 1,tm
| Comb(Comb(Const("real_mul",_),c),(Var(_,_) as t))
when is_ratconst c && not (mem t fvs)
-> rat_of_term c,t
| Comb(Comb(Const("real_add",_),s),t) ->
(try substitutable_monomial (union (frees t) fvs) s
with Failure _ -> substitutable_monomial (union (frees s) fvs) t)
| _ -> failwith "substitutable_monomial"
and isolate_variable v th =
match lhs(concl th) with
x when x = v -> th
| Comb(Comb(Const("real_add",_),(Var(_,Tyapp("real",[])) as x)),t)
when x = v -> shuffle2 th
| Comb(Comb(Const("real_add",_),s),t) ->
isolate_variable v(shuffle1 th) in
let make_substitution th =
let (c,v) = substitutable_monomial [] (lhs(concl th)) in
let th1 = AP_TERM (mk_comb(mul_tm,term_of_rat(Int 1 // c))) th in
let th2 = CONV_RULE(BINOP_CONV REAL_POLY_MUL_CONV) th1 in
CONV_RULE (RAND_CONV REAL_POLY_CONV) (isolate_variable v th2) in
fun translator ->
let rec substfirst(eqs,les,lts) =
try let eth = tryfind make_substitution eqs in
let modify =
CONV_RULE(LAND_CONV(SUBS_CONV[eth] THENC REAL_POLY_CONV)) in
substfirst(filter (fun t -> lhand(concl t) <> zero) (map modify eqs),
map modify les,map modify lts)
with Failure _ -> REAL_NONLINEAR_PROVER translator (eqs,les,lts) in
substfirst;;
*)
let REAL_SOS =
let init = GEN_REWRITE_CONV ONCE_DEPTH_CONV [ DECIMAL ]
and pure = GEN_REAL_ARITH REAL_NONLINEAR_SUBST_PROVER in
fun tm - > let th = init tm in EQ_MP ( SYM th ) ( pure(rand(concl th ) ) ) ; ;
let REAL_SOS =
let init = GEN_REWRITE_CONV ONCE_DEPTH_CONV [DECIMAL]
and pure = GEN_REAL_ARITH REAL_NONLINEAR_SUBST_PROVER in
fun tm -> let th = init tm in EQ_MP (SYM th) (pure(rand(concl th)));;
*)
let let inv_tm = ` inv : real->real ` in
let prenex_conv =
TOP_DEPTH_CONV BETA_CONV THENC
PURE_REWRITE_CONV[FORALL_SIMP ; EXISTS_SIMP ; real_div ;
REAL_INV_INV ; REAL_INV_MUL ; GSYM REAL_POW_INV ] THENC
NNFC_CONV THENC DEPTH_BINOP_CONV ` ( /\ ) ` CONDS_CELIM_CONV THENC
PRENEX_CONV
and THENC WEAK_CNF_CONV THENC CONJ_CANON_CONV
and core_rule t =
try REAL_ARITH t
with Failure _ - > try REAL_RING t
with Failure _ - > REAL_SOS t
and is_inv =
let is_div = is_binop ` ( /):real->real->real ` in
fun tm - > ( is_div tm or ( is_comb tm & & rator tm = inv_tm ) ) & &
not(is_ratconst(rand tm ) ) in
let BASIC_REAL_FIELD tm =
let is_freeinv t = is_inv t & & free_in t tm in
let itms = setify(map rand ( find_terms is_freeinv tm ) ) in
let hyps = map ( fun t - > SPEC t REAL_MUL_RINV ) itms in
let tm ' = itlist ( fun th t - > mk_imp(concl th , t ) ) hyps tm in
let itms ' = map ( curry mk_comb inv_tm ) itms in
let = map ( genvar o type_of ) itms ' in
let tm '' = subst ( zip gvs itms ' ) tm ' in
let th1 = setup_conv tm '' in
let cjs = conjuncts(rand(concl th1 ) ) in
let ths = map core_rule cjs in
let th2 = EQ_MP ( SYM th1 ) ( end_itlist ) in
rev_itlist ( C MP ) hyps ( INST ( zip itms ' ) th2 ) in
fun tm - >
let in
let tm0 = rand(concl ) in
let avs , bod = strip_forall tm0 in
let th1 = setup_conv bod in
let ths = map ( conjuncts(rand(concl th1 ) ) ) in
EQ_MP ( SYM th0 ) ( GENL avs ( EQ_MP ( SYM th1 ) ( end_itlist ) ) ) ; ;
let REAL_SOSFIELD =
let inv_tm = `inv:real->real` in
let prenex_conv =
TOP_DEPTH_CONV BETA_CONV THENC
PURE_REWRITE_CONV[FORALL_SIMP; EXISTS_SIMP; real_div;
REAL_INV_INV; REAL_INV_MUL; GSYM REAL_POW_INV] THENC
NNFC_CONV THENC DEPTH_BINOP_CONV `(/\)` CONDS_CELIM_CONV THENC
PRENEX_CONV
and setup_conv = NNF_CONV THENC WEAK_CNF_CONV THENC CONJ_CANON_CONV
and core_rule t =
try REAL_ARITH t
with Failure _ -> try REAL_RING t
with Failure _ -> REAL_SOS t
and is_inv =
let is_div = is_binop `(/):real->real->real` in
fun tm -> (is_div tm or (is_comb tm && rator tm = inv_tm)) &&
not(is_ratconst(rand tm)) in
let BASIC_REAL_FIELD tm =
let is_freeinv t = is_inv t && free_in t tm in
let itms = setify(map rand (find_terms is_freeinv tm)) in
let hyps = map (fun t -> SPEC t REAL_MUL_RINV) itms in
let tm' = itlist (fun th t -> mk_imp(concl th,t)) hyps tm in
let itms' = map (curry mk_comb inv_tm) itms in
let gvs = map (genvar o type_of) itms' in
let tm'' = subst (zip gvs itms') tm' in
let th1 = setup_conv tm'' in
let cjs = conjuncts(rand(concl th1)) in
let ths = map core_rule cjs in
let th2 = EQ_MP (SYM th1) (end_itlist CONJ ths) in
rev_itlist (C MP) hyps (INST (zip itms' gvs) th2) in
fun tm ->
let th0 = prenex_conv tm in
let tm0 = rand(concl th0) in
let avs,bod = strip_forall tm0 in
let th1 = setup_conv bod in
let ths = map BASIC_REAL_FIELD (conjuncts(rand(concl th1))) in
EQ_MP (SYM th0) (GENL avs (EQ_MP (SYM th1) (end_itlist CONJ ths)));;
*)
Integer version .
let INT_SOS =
let atom_CONV =
let pth = prove
( ` ( ~(x < = y ) < = > y + & 1 < = x : int ) /\
( ~(x < y ) < = > y < = x ) /\
( ~(x = y ) < = > x + & 1 < = y \/ y + & 1 < = x ) /\
( x < y < = > x + & 1 < = y ) ` ,
REWRITE_TAC[INT_NOT_LE ; INT_NOT_LT ; INT_NOT_EQ ; INT_LT_DISCRETE ] ) in
GEN_REWRITE_CONV I [ pth ]
and bub_CONV = GEN_REWRITE_CONV TOP_SWEEP_CONV
[ int_eq ; int_le ; int_lt ; int_ge ; int_gt ;
int_of_num_th ; int_neg_th ; int_add_th ; int_mul_th ;
int_sub_th ; int_pow_th ; int_abs_th ; ; int_min_th ] in
let base_CONV = TRY_CONV atom_CONV THENC bub_CONV in
let NNF_NORM_CONV = GEN_NNF_CONV false
( base_CONV , fun t - > base_CONV t , base_CONV(mk_neg t ) ) in
let init_CONV =
GEN_REWRITE_CONV DEPTH_CONV [ FORALL_SIMP ; EXISTS_SIMP ] THENC
GEN_REWRITE_CONV DEPTH_CONV [ INT_GT ; INT_GE ] THENC
CONDS_ELIM_CONV THENC NNF_NORM_CONV in
let p_tm = ` p : bool `
and not_tm = ` ( ~ ) ` in
let pth = TAUT(mk_eq(mk_neg(mk_neg p_tm),p_tm ) ) in
fun tm - >
let = INST [ tm , p_tm ] pth
and th1 = NNF_NORM_CONV(mk_neg tm ) in
let th2 = REAL_SOS(mk_neg(rand(concl th1 ) ) ) in
EQ_MP th0 ( EQ_MP ( AP_TERM not_tm ( SYM th1 ) ) th2 ) ; ;
let INT_SOS =
let atom_CONV =
let pth = prove
(`(~(x <= y) <=> y + &1 <= x:int) /\
(~(x < y) <=> y <= x) /\
(~(x = y) <=> x + &1 <= y \/ y + &1 <= x) /\
(x < y <=> x + &1 <= y)`,
REWRITE_TAC[INT_NOT_LE; INT_NOT_LT; INT_NOT_EQ; INT_LT_DISCRETE]) in
GEN_REWRITE_CONV I [pth]
and bub_CONV = GEN_REWRITE_CONV TOP_SWEEP_CONV
[int_eq; int_le; int_lt; int_ge; int_gt;
int_of_num_th; int_neg_th; int_add_th; int_mul_th;
int_sub_th; int_pow_th; int_abs_th; int_max_th; int_min_th] in
let base_CONV = TRY_CONV atom_CONV THENC bub_CONV in
let NNF_NORM_CONV = GEN_NNF_CONV false
(base_CONV,fun t -> base_CONV t,base_CONV(mk_neg t)) in
let init_CONV =
GEN_REWRITE_CONV DEPTH_CONV [FORALL_SIMP; EXISTS_SIMP] THENC
GEN_REWRITE_CONV DEPTH_CONV [INT_GT; INT_GE] THENC
CONDS_ELIM_CONV THENC NNF_NORM_CONV in
let p_tm = `p:bool`
and not_tm = `(~)` in
let pth = TAUT(mk_eq(mk_neg(mk_neg p_tm),p_tm)) in
fun tm ->
let th0 = INST [tm,p_tm] pth
and th1 = NNF_NORM_CONV(mk_neg tm) in
let th2 = REAL_SOS(mk_neg(rand(concl th1))) in
EQ_MP th0 (EQ_MP (AP_TERM not_tm (SYM th1)) th2);;
*)
let SOS_RULE tm =
let avs = frees tm in
let tm ' = list_mk_forall(avs , tm ) in
let th1 = NUM_TO_INT_CONV tm ' in
let th2 = INT_SOS ( rand(concl th1 ) ) in
SPECL avs ( EQ_MP ( SYM th1 ) th2 ) ; ;
let SOS_RULE tm =
let avs = frees tm in
let tm' = list_mk_forall(avs,tm) in
let th1 = NUM_TO_INT_CONV tm' in
let th2 = INT_SOS (rand(concl th1)) in
SPECL avs (EQ_MP (SYM th1) th2);;
*)
let rec allpermutations l =
if l = [] then [[]] else
itlist (fun h acc -> List.map (fun t -> h::t)
(allpermutations (subtract l [h])) @ acc) l [];;
let allvarorders l =
List.map (fun vlis x -> index x vlis) (allpermutations l);;
let changevariables_monomial zoln (m:monomial) =
foldl (fun a x k -> (List.assoc x zoln |-> k) a) monomial_1 m;;
let changevariables zoln pol =
foldl (fun a m c -> (changevariables_monomial zoln m |-> c) a)
poly_0 pol;;
let sdpa_of_vector (v:vector) =
let n = dim v in
let strs = List.map (o (decimalize 20) (element v)) (1--n) in
end_itlist (fun x y -> x ^ " " ^ y) strs ^ "\n";;
let sdpa_of_blockdiagonal k m =
let pfx = string_of_int k ^" " in
let ents =
foldl (fun a (b,i,j) c -> if i > j then a else ((b,i,j),c)::a) [] m in
let entss = sort (increasing fst) ents in
itlist (fun ((b,i,j),c) a ->
pfx ^ string_of_int b ^ " " ^ string_of_int i ^ " " ^ string_of_int j ^
" " ^ decimalize 20 c ^ "\n" ^ a) entss "";;
let sdpa_of_matrix k (m:matrix) =
let pfx = string_of_int k ^ " 1 " in
let ms = foldr (fun (i,j) c a -> if i > j then a else ((i,j),c)::a)
(snd m) [] in
let mss = sort (increasing fst) ms in
itlist (fun ((i,j),c) a ->
pfx ^ string_of_int i ^ " " ^ string_of_int j ^
" " ^ decimalize 20 c ^ "\n" ^ a) mss "";;
let sdpa_of_problem comment obj mats =
let m = List.length mats - 1
and n,_ = dimensions (List.hd mats) in
"\"" ^ comment ^ "\"\n" ^
string_of_int m ^ "\n" ^
"1\n" ^
string_of_int n ^ "\n" ^
sdpa_of_vector obj ^
itlist2 (fun k m a -> sdpa_of_matrix (k - 1) m ^ a)
(1--List.length mats) mats "";;
let run_csdp dbg obj mats =
let input_file = Filename.temp_file "sos" ".dat-s" in
let output_file =
String.sub input_file 0 (String.length input_file - 6) ^ ".out"
and params_file = Filename.concat (!temp_path) "param.csdp" in
file_of_string input_file (sdpa_of_problem "" obj mats);
file_of_string params_file csdp_params;
let rv = Sys.command("cd "^(!temp_path)^"; csdp "^input_file ^
" " ^ output_file ^
(if dbg then "" else "> /dev/null")) in
let op = string_of_file output_file in
let res = parse_csdpoutput op in
((if dbg then ()
else (Sys.remove input_file; Sys.remove output_file));
rv,res);;
let csdp obj mats =
let rv,res = run_csdp (!debugging) obj mats in
(if rv = 1 or rv = 2 then failwith "csdp: Problem is infeasible"
else if rv = 3 then ()
( Format.print_string " csdp warning : Reduced accuracy " ;
( ) )
Format.print_newline()) *)
else if rv <> 0 then failwith("csdp: error "^string_of_int rv)
else ());
res;;
let sumofsquares_general_symmetry tool pol =
let vars = poly_variables pol
and lpps = newton_polytope pol in
let n = List.length lpps in
let sym_eqs =
let invariants = List.filter
(fun vars' ->
is_undefined(poly_sub pol (changevariables (zip vars vars') pol)))
(allpermutations vars) in
let lpns = zip lpps (1--List.length lpps) in
let lppcs =
List.filter (fun (m,(n1,n2)) -> n1 <= n2)
(allpairs
(fun (m1,n1) (m2,n2) -> (m1,m2),(n1,n2)) lpns lpns) in
let clppcs = end_itlist (@)
(List.map (fun ((m1,m2),(n1,n2)) ->
List.map (fun vars' ->
(changevariables_monomial (zip vars vars') m1,
changevariables_monomial (zip vars vars') m2),(n1,n2))
invariants)
lppcs) in
let clppcs_dom = setify(List.map fst clppcs) in
let clppcs_cls = List.map (fun d -> List.filter (fun (e,_) -> e = d) clppcs)
clppcs_dom in
let eqvcls = List.map (o setify (List.map snd)) clppcs_cls in
let mk_eq cls acc =
match cls with
[] -> raise Sanity
| [h] -> acc
| h::t -> List.map (fun k -> (k |-> Int(-1)) (h |=> Int 1)) t @ acc in
itlist mk_eq eqvcls [] in
let eqs = foldl (fun a x y -> y::a) []
(itern 1 lpps (fun m1 n1 ->
itern 1 lpps (fun m2 n2 f ->
let m = monomial_mul m1 m2 in
if n1 > n2 then f else
let c = if n1 = n2 then Int 1 else Int 2 in
(m |-> ((n1,n2) |-> c) (tryapplyd f m undefined)) f))
(foldl (fun a m c -> (m |-> ((0,0)|=>c)) a)
undefined pol)) @
sym_eqs in
let pvs,assig = eliminate_all_equations (0,0) eqs in
let allassig = itlist (fun v -> (v |-> (v |=> Int 1))) pvs assig in
let qvars = (0,0)::pvs in
let diagents =
end_itlist equation_add (List.map (fun i -> apply allassig (i,i)) (1--n)) in
let mk_matrix v =
((n,n),
foldl (fun m (i,j) ass -> let c = tryapplyd ass v (Int 0) in
if c =/ Int 0 then m else
((j,i) |-> c) (((i,j) |-> c) m))
undefined allassig :matrix) in
let mats = List.map mk_matrix qvars
and obj = List.length pvs,
itern 1 pvs (fun v i -> (i |--> tryapplyd diagents v (Int 0)))
undefined in
let raw_vec = if pvs = [] then vector_0 0 else tool obj mats in
let find_rounding d =
(if !debugging then
(Format.print_string("Trying rounding with limit "^string_of_num d);
Format.print_newline())
else ());
let vec = nice_vector d raw_vec in
let mat = iter (1,dim vec)
(fun i a -> matrix_add (matrix_cmul (element vec i) (el i mats)) a)
(matrix_neg (el 0 mats)) in
deration(diag mat) in
let rat,dia =
if pvs = [] then
let mat = matrix_neg (el 0 mats) in
deration(diag mat)
else
tryfind find_rounding (List.map Num.num_of_int (1--31) @
List.map pow2 (5--66)) in
let poly_of_lin(d,v) =
d,foldl(fun a i c -> (el (i - 1) lpps |-> c) a) undefined (snd v) in
let lins = List.map poly_of_lin dia in
let sqs = List.map (fun (d,l) -> poly_mul (poly_const d) (poly_pow l 2)) lins in
let sos = poly_cmul rat (end_itlist poly_add sqs) in
if is_undefined(poly_sub sos pol) then rat,lins else raise Sanity;;
let sumofsquares = sumofsquares_general_symmetry csdp;;
Pure HOL SOS conversion .
let SOS_CONV =
let mk_square =
let pow_tm = ` ( pow ) ` and two_tm = ` 2 ` in
fun tm - > mk_comb(mk_comb(pow_tm , tm),two_tm )
and mk_prod = mk_binop ` ( * ) `
and mk_sum = mk_binop ` ( + ) ` in
fun tm - >
let k , sos = sumofsquares(poly_of_term tm ) in
let , p ) =
mk_prod ( term_of_rat(k * / c ) ) ( mk_square(term_of_poly p ) ) in
let tm ' = end_itlist mk_sum ( map mk_sqtm sos ) in
let th = REAL_POLY_CONV tm and th ' = REAL_POLY_CONV tm ' in
TRANS th ( SYM th ' ) ; ;
let SOS_CONV =
let mk_square =
let pow_tm = `(pow)` and two_tm = `2` in
fun tm -> mk_comb(mk_comb(pow_tm,tm),two_tm)
and mk_prod = mk_binop `( * )`
and mk_sum = mk_binop `(+)` in
fun tm ->
let k,sos = sumofsquares(poly_of_term tm) in
let mk_sqtm(c,p) =
mk_prod (term_of_rat(k */ c)) (mk_square(term_of_poly p)) in
let tm' = end_itlist mk_sum (map mk_sqtm sos) in
let th = REAL_POLY_CONV tm and th' = REAL_POLY_CONV tm' in
TRANS th (SYM th');;
*)
Attempt to prove & 0 < = x by direct SOS decomposition .
let PURE_SOS_TAC =
let tac =
MATCH_ACCEPT_TAC(REWRITE_RULE[GSYM REAL_POW_2 ] REAL_LE_SQUARE ) ORELSE
( MATCH_MP_TAC REAL_LE_ADD THEN ) ORELSE
( MATCH_MP_TAC REAL_LE_MUL THEN ) ORELSE
CONV_TAC(RAND_CONV REAL_RAT_REDUCE_CONV THENC REAL_RAT_LE_CONV ) in
REPEAT GEN_TAC THEN REWRITE_TAC[real_ge ] THEN
I [ GSYM REAL_SUB_LE ] THEN
CONV_TAC(RAND_CONV SOS_CONV ) THEN
REPEAT tac THEN NO_TAC ; ;
let PURE_SOS tm = prove(tm , PURE_SOS_TAC ) ; ;
let PURE_SOS_TAC =
let tac =
MATCH_ACCEPT_TAC(REWRITE_RULE[GSYM REAL_POW_2] REAL_LE_SQUARE) ORELSE
MATCH_ACCEPT_TAC REAL_LE_SQUARE ORELSE
(MATCH_MP_TAC REAL_LE_ADD THEN CONJ_TAC) ORELSE
(MATCH_MP_TAC REAL_LE_MUL THEN CONJ_TAC) ORELSE
CONV_TAC(RAND_CONV REAL_RAT_REDUCE_CONV THENC REAL_RAT_LE_CONV) in
REPEAT GEN_TAC THEN REWRITE_TAC[real_ge] THEN
GEN_REWRITE_TAC I [GSYM REAL_SUB_LE] THEN
CONV_TAC(RAND_CONV SOS_CONV) THEN
REPEAT tac THEN NO_TAC;;
let PURE_SOS tm = prove(tm,PURE_SOS_TAC);;
*)
* * * *
time REAL_SOS
` a1 > = & 0 /\ a2 > = & 0 /\
( a1 * a1 + a2 * a2 = b1 * b1 + b2 * b2 + & 2 ) /\
( a1 * b1 + a2 * b2 = & 0 )
= = > a1 * a2 - b1 * b2 > = & 0 ` ; ;
time REAL_SOS ` & 3 * x + & 7 * a < & 4 /\ & 3 < & 2 * x = = > a < & 0 ` ; ;
time REAL_SOS
` b pow 2 < & 4 * a * c = = > ~(a * x pow 2 + b * x + c = & 0 ) ` ; ;
time REAL_SOS
` ( a * x pow 2 + b * x + c = & 0 ) = = > b pow 2 > = & 4 * a * c ` ; ;
time REAL_SOS
` & 0 < = x /\ x < = & 1 /\ & 0 < = y /\ y < = & 1
= = > x pow 2 + y pow 2 < & 1 \/
( x - & 1 ) pow 2 + y pow 2 < & 1 \/
x pow 2 + ( y - & 1 ) pow 2 < & 1 \/
( x - & 1 ) pow 2 + ( y - & 1 ) pow 2 < & 1 ` ; ;
time REAL_SOS
` & 0 < = b /\ & 0 < = c /\ & 0 < = x /\ & 0 < = y /\
( x pow 2 = c ) /\ ( y pow 2 = a pow 2 * c + b )
= = > a * c < = y * x ` ; ;
time REAL_SOS
` & 0 < = x /\ & 0 < = y /\ & 0 < = z /\ x + y + z < = & 3
= = > x * y + x * z + y * z > = & 3 * x * y * z ` ; ;
time REAL_SOS
` ( x pow 2 + y pow 2 + z pow 2 = & 1 ) = = > ( x + y + z ) pow 2 < = & 3 ` ; ;
time REAL_SOS
` ( w pow 2 + x pow 2 + y pow 2 + z pow 2 = & 1 )
= = > ( w + x + y + z ) pow 2 < = & 4 ` ; ;
time REAL_SOS
` x > = & 1 /\ y > = & 1 = = > x * y > = x + y - & 1 ` ; ;
time REAL_SOS
` x > & 1 /\ y > & 1 = = > x * y > x + y - & 1 ` ; ;
time REAL_SOS
` abs(x ) < = & 1
= = > abs(&64 * x pow 7 - & 112 * x pow 5 + & 56 * x pow 3 - & 7 * x ) < = & 1 ` ; ;
time REAL_SOS
` abs(x - z ) < = e /\ abs(y - z ) < = e /\ & 0 < = u /\ & 0 < = v /\ ( u + v = & 1 )
= = > abs((u * x + v * y ) - z ) < = e ` ; ;
( * -------------------------------------------------------------------------
time REAL_SOS
`a1 >= &0 /\ a2 >= &0 /\
(a1 * a1 + a2 * a2 = b1 * b1 + b2 * b2 + &2) /\
(a1 * b1 + a2 * b2 = &0)
==> a1 * a2 - b1 * b2 >= &0`;;
time REAL_SOS `&3 * x + &7 * a < &4 /\ &3 < &2 * x ==> a < &0`;;
time REAL_SOS
`b pow 2 < &4 * a * c ==> ~(a * x pow 2 + b * x + c = &0)`;;
time REAL_SOS
`(a * x pow 2 + b * x + c = &0) ==> b pow 2 >= &4 * a * c`;;
time REAL_SOS
`&0 <= x /\ x <= &1 /\ &0 <= y /\ y <= &1
==> x pow 2 + y pow 2 < &1 \/
(x - &1) pow 2 + y pow 2 < &1 \/
x pow 2 + (y - &1) pow 2 < &1 \/
(x - &1) pow 2 + (y - &1) pow 2 < &1`;;
time REAL_SOS
`&0 <= b /\ &0 <= c /\ &0 <= x /\ &0 <= y /\
(x pow 2 = c) /\ (y pow 2 = a pow 2 * c + b)
==> a * c <= y * x`;;
time REAL_SOS
`&0 <= x /\ &0 <= y /\ &0 <= z /\ x + y + z <= &3
==> x * y + x * z + y * z >= &3 * x * y * z`;;
time REAL_SOS
`(x pow 2 + y pow 2 + z pow 2 = &1) ==> (x + y + z) pow 2 <= &3`;;
time REAL_SOS
`(w pow 2 + x pow 2 + y pow 2 + z pow 2 = &1)
==> (w + x + y + z) pow 2 <= &4`;;
time REAL_SOS
`x >= &1 /\ y >= &1 ==> x * y >= x + y - &1`;;
time REAL_SOS
`x > &1 /\ y > &1 ==> x * y > x + y - &1`;;
time REAL_SOS
`abs(x) <= &1
==> abs(&64 * x pow 7 - &112 * x pow 5 + &56 * x pow 3 - &7 * x) <= &1`;;
time REAL_SOS
`abs(x - z) <= e /\ abs(y - z) <= e /\ &0 <= u /\ &0 <= v /\ (u + v = &1)
==> abs((u * x + v * y) - z) <= e`;;
One component of denominator in dodecahedral example .
time REAL_SOS
`&2 <= x /\ x <= &125841 / &50000 /\
&2 <= y /\ y <= &125841 / &50000 /\
&2 <= z /\ z <= &125841 / &50000
==> &2 * (x * z + x * y + y * z) - (x * x + y * y + z * z) >= &0`;;
time REAL_SOS
`&2 <= x /\ x <= &4 /\ &2 <= y /\ y <= &4 /\ &2 <= z /\ z <= &4
==> &0 <= &2 * (x * z + x * y + y * z) - (x * x + y * y + z * z)`;;
We can do 12 . I think 12 is a sharp bound ; see PP 's certificate .
time REAL_SOS
`&2 <= x /\ x <= &4 /\ &2 <= y /\ y <= &4 /\ &2 <= z /\ z <= &4
==> &12 <= &2 * (x * z + x * y + y * z) - (x * x + y * y + z * z)`;;
Gloptipoly example .
* * This works but normalization takes minutes
time REAL_SOS
` ( x - y - & 2 * x pow 4 = & 0 ) /\ & 0 < = x /\ x < = & 2 /\ & 0 < = y /\ y < = & 3
= = > y pow 2 - & 7 * y - & 12 * x + & 17 > = & 0 ` ; ;
* *
time REAL_SOS
`(x - y - &2 * x pow 4 = &0) /\ &0 <= x /\ x <= &2 /\ &0 <= y /\ y <= &3
==> y pow 2 - &7 * y - &12 * x + &17 >= &0`;;
***)
Inequality from sci.math ( see " Leon - Sotelo , por favor " ) .
time REAL_SOS
`&0 <= x /\ &0 <= y /\ (x * y = &1)
==> x + y <= x pow 2 + y pow 2`;;
time REAL_SOS
`&0 <= x /\ &0 <= y /\ (x * y = &1)
==> x * y * (x + y) <= x pow 2 + y pow 2`;;
time REAL_SOS
`&0 <= x /\ &0 <= y ==> x * y * (x + y) pow 2 <= (x pow 2 + y pow 2) pow 2`;;
time SOS_RULE `!m n. 2 * m + n = (n + m) + m`;;
time SOS_RULE `!n. ~(n = 0) ==> (0 MOD n = 0)`;;
time SOS_RULE `!m n. m < n ==> (m DIV n = 0)`;;
time SOS_RULE `!n:num. n <= n * n`;;
time SOS_RULE `!m n. n * (m DIV n) <= m`;;
time SOS_RULE `!n. ~(n = 0) ==> (0 DIV n = 0)`;;
time SOS_RULE `!m n p. ~(p = 0) /\ m <= n ==> m DIV p <= n DIV p`;;
time SOS_RULE `!a b n. ~(a = 0) ==> (n <= b DIV a <=> a * n <= b)`;;
Key lemma for injectivity of Cantor - type pairing functions .
time SOS_RULE
`!x1 y1 x2 y2. ((x1 + y1) EXP 2 + x1 + 1 = (x2 + y2) EXP 2 + x2 + 1)
==> (x1 + y1 = x2 + y2)`;;
time SOS_RULE
`!x1 y1 x2 y2. ((x1 + y1) EXP 2 + x1 + 1 = (x2 + y2) EXP 2 + x2 + 1) /\
(x1 + y1 = x2 + y2)
==> (x1 = x2) /\ (y1 = y2)`;;
time SOS_RULE
`!x1 y1 x2 y2.
(((x1 + y1) EXP 2 + 3 * x1 + y1) DIV 2 =
((x2 + y2) EXP 2 + 3 * x2 + y2) DIV 2)
==> (x1 + y1 = x2 + y2)`;;
time SOS_RULE
`!x1 y1 x2 y2.
(((x1 + y1) EXP 2 + 3 * x1 + y1) DIV 2 =
((x2 + y2) EXP 2 + 3 * x2 + y2) DIV 2) /\
(x1 + y1 = x2 + y2)
==> (x1 = x2) /\ (y1 = y2)`;;
Reciprocal multiplication ( actually just ARITH_RULE does these ) .
time SOS_RULE `x <= 127 ==> ((86 * x) DIV 256 = x DIV 3)`;;
time SOS_RULE `x < 2 EXP 16 ==> ((104858 * x) DIV (2 EXP 20) = x DIV 10)`;;
time SOS_RULE `0 < m /\ m < n ==> ((m * ((n * x) DIV m + 1)) DIV n = x)`;;
time SOS_CONV
`&2 * x pow 4 + &2 * x pow 3 * y - x pow 2 * y pow 2 + &5 * y pow 4`;;
time SOS_CONV
`x pow 4 - (&2 * y * z + &1) * x pow 2 +
(y pow 2 * z pow 2 + &2 * y * z + &2)`;;
time SOS_CONV `&4 * x pow 4 +
&4 * x pow 3 * y - &7 * x pow 2 * y pow 2 - &2 * x * y pow 3 +
&10 * y pow 4`;;
time SOS_CONV `&4 * x pow 4 * y pow 6 + x pow 2 - x * y pow 2 + y pow 2`;;
time SOS_CONV
`&4096 * (x pow 4 + x pow 2 + z pow 6 - &3 * x pow 2 * z pow 2) + &729`;;
time SOS_CONV
`&120 * x pow 2 - &63 * x pow 4 + &10 * x pow 6 +
&30 * x * y - &120 * y pow 2 + &120 * y pow 4 + &31`;;
time SOS_CONV
`&9 * x pow 2 * y pow 4 + &9 * x pow 2 * z pow 4 + &36 * x pow 2 * y pow 3 +
&36 * x pow 2 * y pow 2 - &48 * x * y * z pow 2 + &4 * y pow 4 +
&4 * z pow 4 - &16 * y pow 3 + &16 * y pow 2`;;
time SOS_CONV
`(x pow 2 + y pow 2 + z pow 2) *
(x pow 4 * y pow 2 + x pow 2 * y pow 4 +
z pow 6 - &3 * x pow 2 * y pow 2 * z pow 2)`;;
time SOS_CONV
`x pow 4 + y pow 4 + z pow 4 - &4 * x * y * z + x + y + z + &3`;;
time SOS_CONV
`&100 * ((&2 * x - &2) pow 2 + (x pow 3 - &8 * x - &2) pow 2) - &588`;;
time SOS_CONV
`x pow 2 * (&120 - &63 * x pow 2 + &10 * x pow 4) + &30 * x * y +
&30 * y pow 2 * (&4 * y pow 2 - &4) + &31`;;
time PURE_SOS
`!x. x pow 4 + y pow 4 + z pow 4 - &4 * x * y * z + x + y + z + &3
>= &1 / &7`;;
time PURE_SOS
`&0 <= &98 * x pow 12 +
-- &980 * x pow 10 +
&3038 * x pow 8 +
-- &2968 * x pow 6 +
&1022 * x pow 4 +
-- &84 * x pow 2 +
&2`;;
time PURE_SOS
`!x. &0 <= &2 * x pow 14 +
-- &84 * x pow 12 +
&1022 * x pow 10 +
-- &2968 * x pow 8 +
&3038 * x pow 6 +
-- &980 * x pow 4 +
&98 * x pow 2`;;
From et al , JSC vol 37 ( 2004 ) , p83 - 99 .
PURE_SOS
`x pow 6 + y pow 6 + z pow 6 - &3 * x pow 2 * y pow 2 * z pow 2 >= &0`;;
PURE_SOS `x pow 4 + y pow 4 + z pow 4 + &1 - &4*x*y*z >= &0`;;
PURE_SOS `x pow 4 + &2*x pow 2*z + x pow 2 - &2*x*y*z + &2*y pow 2*z pow 2 +
&2*y*z pow 2 + &2*z pow 2 - &2*x + &2* y*z + &1 >= &0`;;
* * * This is harder . Interestingly , this fails the pure SOS test , it seems .
Yet only on rounding ( ! ? ) Poor polytope optimization or something ?
But REAL_SOS does finally converge on the second run at level 12 !
REAL_SOS
` x pow 4*y pow 4 - & 2*x pow 5*y pow 3*z pow 2 + x pow 6*y pow 2*z pow 4 + & 2*x
pow 2*y pow 3*z - & 4 * x pow 3*y pow 2*z pow 3 + & 2*x pow 4*y*z pow 5 + z pow
2*y pow 2 - & 2*z pow 4*y*x + z pow 6*x pow 2 > = & 0 ` ; ;
* * *
Yet only on rounding(!?) Poor Newton polytope optimization or something?
But REAL_SOS does finally converge on the second run at level 12!
REAL_SOS
`x pow 4*y pow 4 - &2*x pow 5*y pow 3*z pow 2 + x pow 6*y pow 2*z pow 4 + &2*x
pow 2*y pow 3*z - &4* x pow 3*y pow 2*z pow 3 + &2*x pow 4*y*z pow 5 + z pow
2*y pow 2 - &2*z pow 4*y*x + z pow 6*x pow 2 >= &0`;;
****)
PURE_SOS
`x pow 4 + &4*x pow 2*y pow 2 + &2*x*y*z pow 2 + &2*x*y*w pow 2 + y pow 4 + z
pow 4 + w pow 4 + &2*z pow 2*w pow 2 + &2*x pow 2*w + &2*y pow 2*w + &2*x*y +
&3*w pow 2 + &2*z pow 2 + &1 >= &0`;;
PURE_SOS
`w pow 6 + &2*z pow 2*w pow 3 + x pow 4 + y pow 4 + z pow 4 + &2*x pow 2*w +
&2*x pow 2*z + &3*x pow 2 + w pow 2 + &2*z*w + z pow 2 + &2*z + &2*w + &1 >=
&0`;;
*****)
|
807b17b87c67a8510fc69b17c0eda3e9de87229b16b7056ab9432b3840ee35dc | discus-lang/salt | Type.hs |
module Salt.Core.Eval.Type where
import Salt.Core.Eval.Error
import Salt.Core.Eval.Base
import Control.Exception
import Control.Monad
---------------------------------------------------------------------------------------------------
-- | Evaluate a type in the given environment.
--
evalType :: EvalType a (Type a) (Type a)
-- (evt-ann) ----------------------------------------------
evalType s _a env (TAnn a' t)
= evalType s a' env t
-- (evt-ref) ----------------------------------------------
evalType _s _a _env tt@TRef{}
= return tt
-- (evt-var) ----------------------------------------------
evalType s a env (TVar u)
= resolveTypeBound (stateModule s) env u
>>= \case
-- Type is bound at top level.
Just (TypeDefDecl t) -> evalType s a env t
-- Type is bound in the local environment.
Just (TypeDefLocal t) -> return t
-- Can't find the binding site for this bound variable.
_ -> throw $ ErrorTypeVarUnbound a u env
-- (evt-abs) ----------------------------------------------
evalType _s _a env (TAbs tps tBody)
= return $ TRef $ TRClo (TypeClosure env tps tBody)
-- (evt-hole) ---------------------------------------------
evalType _s _a _env tt@THole
= return tt
-- (evt-arr) ----------------------------------------------
evalType s a env (TArr ks1 k2)
= do ks1' <- mapM (evalType s a env) ks1
k2' <- evalType s a env k2
return $ TArr ks1' k2'
-- (evt-app) ----------------------------------------------
evalType s a env (TApp tFun tgs)
= do tCloType <- evalType s a env tFun
case tCloType of
-- Reduce applications of primitive types to head normal form.
TRef TRPrm{}
| ts <- takeTGTypes tgs
-> do tsArg <- mapM (evalType s a env) ts
return $ TApp tFun (TGTypes tsArg)
-- Reduce applications of type constructors to head normal form.
TRef TRCon{}
| ts <- takeTGTypes tgs
-> do tsArg <- mapM (evalType s a env) ts
return $ TApp tFun (TGTypes tsArg)
-- Apply type closures.
TRef (TRClo (TypeClosure env' tps tBody))
| bks <- takeTPTypes tps
, ts <- takeTGTypes tgs
-> do let bs = map fst bks
tsArg <- mapM (evalType s a env) ts
when (not $ length tsArg == length bs)
$ throw $ ErrorWrongTypeArity a (length bs) tsArg
let env'' = tenvExtendTypes (zip bs tsArg) env'
evalType s a env'' tBody
_ -> throw $ ErrorAppTypeBadClosure a [tCloType]
-- (evt-fun) ----------------------------------------------
evalType s a env (TFun ts1 ts2)
= do ts1' <- mapM (evalType s a env) ts1
ts2' <- mapM (evalType s a env) ts2
return $ TFun ts1' ts2'
-- (evt-all) ----------------------------------------------
evalType s a env (TForall tps t)
= do let (bs, ks) = unzip $ takeTPTypes tps
ks' <- mapM (evalType s a env) ks
let bks' = zip bs ks'
let env' = tenvExtendTypes bks' env
t' <- evalType s a env' t
return $ TForall (TPTypes bks') t'
-- (evt-ext) ----------------------------------------------
evalType s a env (TExists bks t)
= do let (bs, ks) = unzip $ takeTPTypes bks
ks' <- mapM (evalType s a env) ks
let bks' = zip bs ks'
let env' = tenvExtendTypes bks' env
t' <- evalType s a env' t
return $ TExists (TPTypes bks') t'
-- (evt-rec) ----------------------------------------------
evalType s a env (TRecord ns mgss)
= do mgss' <- mapM (evalTypeArgs s a env) mgss
return $ TRecord ns mgss'
-- (evt-vnt) ----------------------------------------------
evalType s a env (TVariant ns mgss)
= do mgss' <- mapM (evalTypeArgs s a env) mgss
return $ TVariant ns mgss'
-- (evt-susp) ---------------------------------------------
evalType s a env (TSusp tsv te)
= do tsv' <- mapM (evalType s a env) tsv
te' <- evalType s a env te
return $ TSusp tsv' te'
-- (evt-pure) ---------------------------------------------
evalType _s _a _env tt@TPure
= return tt
-- (evt-sync) ---------------------------------------------
evalType _s _a _env tt@TSync
= return tt
-- (evt-sum) ----------------------------------------------
evalType s a env (TSum ts)
= do ts' <- mapM (evalType s a env) ts
return $ TSum ts'
----------------------------------------------------------
-- No match.
evalType _s a _env tt
= throw $ ErrorInvalidType a tt
---------------------------------------------------------------------------------------------------
evalTypeArgs :: EvalType a (TypeArgs a) (TypeArgs a)
evalTypeArgs s a env (TGAnn _ tgs')
= evalTypeArgs s a env tgs'
evalTypeArgs s a env (TGTypes ts)
= do ts' <- mapM (evalType s a env) ts
return $ TGTypes ts'
| null | https://raw.githubusercontent.com/discus-lang/salt/33c14414ac7e238fdbd8161971b8b8ac67fff569/src/salt/Salt/Core/Eval/Type.hs | haskell | -------------------------------------------------------------------------------------------------
| Evaluate a type in the given environment.
(evt-ann) ----------------------------------------------
(evt-ref) ----------------------------------------------
(evt-var) ----------------------------------------------
Type is bound at top level.
Type is bound in the local environment.
Can't find the binding site for this bound variable.
(evt-abs) ----------------------------------------------
(evt-hole) ---------------------------------------------
(evt-arr) ----------------------------------------------
(evt-app) ----------------------------------------------
Reduce applications of primitive types to head normal form.
Reduce applications of type constructors to head normal form.
Apply type closures.
(evt-fun) ----------------------------------------------
(evt-all) ----------------------------------------------
(evt-ext) ----------------------------------------------
(evt-rec) ----------------------------------------------
(evt-vnt) ----------------------------------------------
(evt-susp) ---------------------------------------------
(evt-pure) ---------------------------------------------
(evt-sync) ---------------------------------------------
(evt-sum) ----------------------------------------------
--------------------------------------------------------
No match.
------------------------------------------------------------------------------------------------- |
module Salt.Core.Eval.Type where
import Salt.Core.Eval.Error
import Salt.Core.Eval.Base
import Control.Exception
import Control.Monad
evalType :: EvalType a (Type a) (Type a)
evalType s _a env (TAnn a' t)
= evalType s a' env t
evalType _s _a _env tt@TRef{}
= return tt
evalType s a env (TVar u)
= resolveTypeBound (stateModule s) env u
>>= \case
Just (TypeDefDecl t) -> evalType s a env t
Just (TypeDefLocal t) -> return t
_ -> throw $ ErrorTypeVarUnbound a u env
evalType _s _a env (TAbs tps tBody)
= return $ TRef $ TRClo (TypeClosure env tps tBody)
evalType _s _a _env tt@THole
= return tt
evalType s a env (TArr ks1 k2)
= do ks1' <- mapM (evalType s a env) ks1
k2' <- evalType s a env k2
return $ TArr ks1' k2'
evalType s a env (TApp tFun tgs)
= do tCloType <- evalType s a env tFun
case tCloType of
TRef TRPrm{}
| ts <- takeTGTypes tgs
-> do tsArg <- mapM (evalType s a env) ts
return $ TApp tFun (TGTypes tsArg)
TRef TRCon{}
| ts <- takeTGTypes tgs
-> do tsArg <- mapM (evalType s a env) ts
return $ TApp tFun (TGTypes tsArg)
TRef (TRClo (TypeClosure env' tps tBody))
| bks <- takeTPTypes tps
, ts <- takeTGTypes tgs
-> do let bs = map fst bks
tsArg <- mapM (evalType s a env) ts
when (not $ length tsArg == length bs)
$ throw $ ErrorWrongTypeArity a (length bs) tsArg
let env'' = tenvExtendTypes (zip bs tsArg) env'
evalType s a env'' tBody
_ -> throw $ ErrorAppTypeBadClosure a [tCloType]
evalType s a env (TFun ts1 ts2)
= do ts1' <- mapM (evalType s a env) ts1
ts2' <- mapM (evalType s a env) ts2
return $ TFun ts1' ts2'
evalType s a env (TForall tps t)
= do let (bs, ks) = unzip $ takeTPTypes tps
ks' <- mapM (evalType s a env) ks
let bks' = zip bs ks'
let env' = tenvExtendTypes bks' env
t' <- evalType s a env' t
return $ TForall (TPTypes bks') t'
evalType s a env (TExists bks t)
= do let (bs, ks) = unzip $ takeTPTypes bks
ks' <- mapM (evalType s a env) ks
let bks' = zip bs ks'
let env' = tenvExtendTypes bks' env
t' <- evalType s a env' t
return $ TExists (TPTypes bks') t'
evalType s a env (TRecord ns mgss)
= do mgss' <- mapM (evalTypeArgs s a env) mgss
return $ TRecord ns mgss'
evalType s a env (TVariant ns mgss)
= do mgss' <- mapM (evalTypeArgs s a env) mgss
return $ TVariant ns mgss'
evalType s a env (TSusp tsv te)
= do tsv' <- mapM (evalType s a env) tsv
te' <- evalType s a env te
return $ TSusp tsv' te'
evalType _s _a _env tt@TPure
= return tt
evalType _s _a _env tt@TSync
= return tt
evalType s a env (TSum ts)
= do ts' <- mapM (evalType s a env) ts
return $ TSum ts'
evalType _s a _env tt
= throw $ ErrorInvalidType a tt
evalTypeArgs :: EvalType a (TypeArgs a) (TypeArgs a)
evalTypeArgs s a env (TGAnn _ tgs')
= evalTypeArgs s a env tgs'
evalTypeArgs s a env (TGTypes ts)
= do ts' <- mapM (evalType s a env) ts
return $ TGTypes ts'
|
22ac14274fe8ff5d597dc1172c281d889577ecdf16e19a835843416d681ff7cb | rurban/clisp | ctak.lisp | CTAK -- A version of the TAKeuchi function
;;; that uses the CATCH/THROW facility.
(defun ctak (x y z)
(catch 'ctak (ctak-aux x y z)))
(defun ctak-aux (x y z)
(declare (fixnum x y z))
(cond ((not (< y x))
(throw 'ctak z))
(t (ctak-aux
(catch 'ctak
(ctak-aux (the fixnum (1- x))
y
z))
(catch 'ctak
(ctak-aux (the fixnum (1- y))
z
x))
(catch 'ctak
(ctak-aux (the fixnum (1- z))
x
y))))))
call : ( ctak 18 . 12 . 6 . )
| null | https://raw.githubusercontent.com/rurban/clisp/75ed2995ff8f5364bcc18727cde9438cca4e7c2c/benchmarks/ctak.lisp | lisp | that uses the CATCH/THROW facility. | CTAK -- A version of the TAKeuchi function
(defun ctak (x y z)
(catch 'ctak (ctak-aux x y z)))
(defun ctak-aux (x y z)
(declare (fixnum x y z))
(cond ((not (< y x))
(throw 'ctak z))
(t (ctak-aux
(catch 'ctak
(ctak-aux (the fixnum (1- x))
y
z))
(catch 'ctak
(ctak-aux (the fixnum (1- y))
z
x))
(catch 'ctak
(ctak-aux (the fixnum (1- z))
x
y))))))
call : ( ctak 18 . 12 . 6 . )
|
7a0eafb2ad6177858ddc46e78a7d9a157a0037cf769263ff532fbc11347df7e3 | alexbs01/OCaml | queens.mli |
val all_queens : int -> int list list
" all_queens_sol n " da ( para cada n > = 0 ) una lista con todas las posibles soluciones
al problema de las n reinas de ajedrez en .
solución lista con n enteros ( de 1 a n ) que indica la columna que
ocuparía la dama de cada fila ( ordenadas de la fila 1 a la n ) .
, por ejemplo , la lista [ 2 ; 4 ; 1 ; 3 ] representa , para el tablero 4x4 , la solución
que consiste en colocar las reinas en las casillas ( 1,2 ) , ( 2,4 ) , ( 3,1 ) y ( 4,3 ) .
todas las soluciones posibles y no aparece , no se garantiza
el orden en que apecen las distintas soluciones dentro de la lista .
"all_queens_sol n" da (para cada n >= 0) una lista con todas las posibles soluciones
al problema de las n reinas de ajedrez en el tablero de n x n casillas.
Cada solución se da como una lista con n enteros (de 1 a n) que indica la columna que
ocuparía la dama de cada fila (ordenadas de la fila 1 a la n).
Así, por ejemplo, la lista [2; 4; 1; 3] representa, para el tablero 4x4, la solución
que consiste en colocar las reinas en las casillas (1,2), (2,4), (3,1) y (4,3).
Están todas las soluciones posibles y no aparece ninguna repetida, pero no se garantiza
el orden en que apecen las distintas soluciones dentro de la lista.
*)
| null | https://raw.githubusercontent.com/alexbs01/OCaml/b5f6b2dac761cf3eb99ba55dfe7de85f7e3c4f48/queens/queens.mli | ocaml |
val all_queens : int -> int list list
" all_queens_sol n " da ( para cada n > = 0 ) una lista con todas las posibles soluciones
al problema de las n reinas de ajedrez en .
solución lista con n enteros ( de 1 a n ) que indica la columna que
ocuparía la dama de cada fila ( ordenadas de la fila 1 a la n ) .
, por ejemplo , la lista [ 2 ; 4 ; 1 ; 3 ] representa , para el tablero 4x4 , la solución
que consiste en colocar las reinas en las casillas ( 1,2 ) , ( 2,4 ) , ( 3,1 ) y ( 4,3 ) .
todas las soluciones posibles y no aparece , no se garantiza
el orden en que apecen las distintas soluciones dentro de la lista .
"all_queens_sol n" da (para cada n >= 0) una lista con todas las posibles soluciones
al problema de las n reinas de ajedrez en el tablero de n x n casillas.
Cada solución se da como una lista con n enteros (de 1 a n) que indica la columna que
ocuparía la dama de cada fila (ordenadas de la fila 1 a la n).
Así, por ejemplo, la lista [2; 4; 1; 3] representa, para el tablero 4x4, la solución
que consiste en colocar las reinas en las casillas (1,2), (2,4), (3,1) y (4,3).
Están todas las soluciones posibles y no aparece ninguna repetida, pero no se garantiza
el orden en que apecen las distintas soluciones dentro de la lista.
*)
| |
d2315238337afb29fb7df56544c5fdd50972a1697de0af57fe711e35ce89c6c8 | namachan10777/folivora | key_unit.ml | module M = Scad_ml.Model
open Scad_ml.Util
let keycap_chery_r2 =
( (17.7, 17.9, 4.0)
, M.hull
[ M.cube (11.5, 0.1, 0.1) |>> ((17.7 -. 11.5) /. 2., 17.3, 6.8)
; M.cube (11.5, 0.1, 0.1) |>> ((17.7 -. 11.5) /. 2., 3.3, 7.3)
; M.cube (17.7, 17.9, 0.1) ] )
let keycap_chery_r3 =
( (17.7, 17.9, 4.0)
, M.hull
[ M.cube (11.5, 0.1, 0.1) |>> ((17.7 -. 11.5) /. 2., 17.3, 5.5)
; M.cube (11.5, 0.1, 0.1) |>> ((17.7 -. 11.5) /. 2., 3.3, 7.0)
; M.cube (17.7, 17.9, 0.1) ] )
let keycap_chery_r4 =
( (17.7, 17.9, 4.0)
, M.hull
[ M.cube (11.5, 0.1, 0.1) |>> ((17.7 -. 11.5) /. 2., 17.3, 5.5)
; M.cube (11.5, 0.1, 0.1) |>> ((17.7 -. 11.5) /. 2., 3.3, 8.3)
; M.cube (17.7, 17.9, 0.1) ] )
let keycap_choc =
( (17.7, 17.9, 4.0)
, M.hull
[ M.cube (16.5, 15.5, 0.1)
|>> ((17.7 -. 16.5) /. 2., (16.5 -. 17.5) /. 2., 3.8)
; M.cube (17.5, 16.5, 0.1) ] )
let centering_d (dx, dy) (w, d) (w', d') =
(((w -. w') /. 2.) +. dx, ((d -. d') /. 2.) +. dy, 0.0)
type cap_t = (float * float * float) * M.t
let kailh_box (dx, dy) (w, d, h) cap =
let lump = M.cube (w, d, h) in
let cap =
match cap with
| Some ((cap_w, cap_d, cap_offset), body) ->
[ body
|>> ( centering_d (dx, dy) (w, d) (cap_w, cap_d)
<+> (0., 0., cap_offset +. h) ) ]
| None -> []
in
M.difference
(M.union
( M.difference lump
[ M.cube (16., 16., 1.001)
|>> (((w -. 16.) /. 2.) +. dx, ((d -. 16.) /. 2.) +. dy, h -. 1.)
; M.cube (6., 16., h -. 1.0 -. 1.5 +. 0.001)
|>> (((w -. 6.) /. 2.) +. dx, ((d -. 16.) /. 2.) +. dy, -0.001)
]
:: ( M.cube (16., 10., 1.)
|>> (((w -. 16.) /. 2.) +. dx, ((d -. 10.) /. 2.) +. dy, h -. 1.) )
:: cap ))
[ M.cube (14., 14., h +. 0.02)
|>> (((w -. 14.) /. 2.) +. dx, ((d -. 14.) /. 2.) +. dy, -0.01) ]
let kailh_choc (dx, dy) (w, d, h) cap =
let lump = M.cube (w, d, h) in
let cap =
match cap with
| Some ((cap_w, cap_d, cap_offset), body) ->
[ body
|>> ( centering_d (dx, dy) (w, d) (cap_w, cap_d)
<+> (0., 0., cap_offset +. h) ) ]
| None -> []
in
let cut =
M.difference lump
[ M.cube (14., 14., h +. 0.02)
|>> (((w -. 14.) /. 2.) +. dx, ((d -. 14.) /. 2.) +. dy, -0.01)
; M.cube (16., 16., 1.01)
|>> (((w -. 16.) /. 2.) +. dx, ((d -. 16.) /. 2.) +. dy, h -. 1.)
; M.cube (16., 14., h -. 1.0 -. 1.3 +. 0.001)
|>> (((w -. 16.) /. 2.) +. dx, ((d -. 16.) /. 2.) +. dy, -0.001) ]
in
M.union
[ cut
; M.difference
(M.union
( ( M.cube (16., 10., 1.)
|>> (((w -. 16.) /. 2.) +. dx, ((d -. 10.) /. 2.) +. dy, h -. 1.)
)
:: ( M.cube (16., 3., h)
|>> (((w -. 16.) /. 2.) +. dx, ((d -. 3.) /. 2.) +. dy, 0.) )
:: cap ))
[ M.cube (14., 14., h +. 0.02)
|>> (((w -. 14.) /. 2.) +. dx, ((d -. 14.) /. 2.) +. dy, -0.01) ] ]
let bittradeone_trackball (dx, dy) (w, d, h) =
let lump = M.cube (w, d, h +. 6.) in
M.difference lump
[ M.cube (17., 17., 6. +. 0.001)
|>> (((w -. 17.) /. 2.) +. dx, ((d -. 17.) /. 2.) +. dy, h)
; M.cube (6.35, 1.27, h +. 6. +. 0.02)
|>> ( ((w -. 17.) /. 2.) +. dx +. 7.5
, ((d -. 17.) /. 2.) +. dy +. 1.0
, -0.01 ) ]
let dummy s _ = M.cube s
| null | https://raw.githubusercontent.com/namachan10777/folivora/f752c45f1a4ca1485ebd5488ffef29c704ca06e5/model/lib/key_unit.ml | ocaml | module M = Scad_ml.Model
open Scad_ml.Util
let keycap_chery_r2 =
( (17.7, 17.9, 4.0)
, M.hull
[ M.cube (11.5, 0.1, 0.1) |>> ((17.7 -. 11.5) /. 2., 17.3, 6.8)
; M.cube (11.5, 0.1, 0.1) |>> ((17.7 -. 11.5) /. 2., 3.3, 7.3)
; M.cube (17.7, 17.9, 0.1) ] )
let keycap_chery_r3 =
( (17.7, 17.9, 4.0)
, M.hull
[ M.cube (11.5, 0.1, 0.1) |>> ((17.7 -. 11.5) /. 2., 17.3, 5.5)
; M.cube (11.5, 0.1, 0.1) |>> ((17.7 -. 11.5) /. 2., 3.3, 7.0)
; M.cube (17.7, 17.9, 0.1) ] )
let keycap_chery_r4 =
( (17.7, 17.9, 4.0)
, M.hull
[ M.cube (11.5, 0.1, 0.1) |>> ((17.7 -. 11.5) /. 2., 17.3, 5.5)
; M.cube (11.5, 0.1, 0.1) |>> ((17.7 -. 11.5) /. 2., 3.3, 8.3)
; M.cube (17.7, 17.9, 0.1) ] )
let keycap_choc =
( (17.7, 17.9, 4.0)
, M.hull
[ M.cube (16.5, 15.5, 0.1)
|>> ((17.7 -. 16.5) /. 2., (16.5 -. 17.5) /. 2., 3.8)
; M.cube (17.5, 16.5, 0.1) ] )
let centering_d (dx, dy) (w, d) (w', d') =
(((w -. w') /. 2.) +. dx, ((d -. d') /. 2.) +. dy, 0.0)
type cap_t = (float * float * float) * M.t
let kailh_box (dx, dy) (w, d, h) cap =
let lump = M.cube (w, d, h) in
let cap =
match cap with
| Some ((cap_w, cap_d, cap_offset), body) ->
[ body
|>> ( centering_d (dx, dy) (w, d) (cap_w, cap_d)
<+> (0., 0., cap_offset +. h) ) ]
| None -> []
in
M.difference
(M.union
( M.difference lump
[ M.cube (16., 16., 1.001)
|>> (((w -. 16.) /. 2.) +. dx, ((d -. 16.) /. 2.) +. dy, h -. 1.)
; M.cube (6., 16., h -. 1.0 -. 1.5 +. 0.001)
|>> (((w -. 6.) /. 2.) +. dx, ((d -. 16.) /. 2.) +. dy, -0.001)
]
:: ( M.cube (16., 10., 1.)
|>> (((w -. 16.) /. 2.) +. dx, ((d -. 10.) /. 2.) +. dy, h -. 1.) )
:: cap ))
[ M.cube (14., 14., h +. 0.02)
|>> (((w -. 14.) /. 2.) +. dx, ((d -. 14.) /. 2.) +. dy, -0.01) ]
let kailh_choc (dx, dy) (w, d, h) cap =
let lump = M.cube (w, d, h) in
let cap =
match cap with
| Some ((cap_w, cap_d, cap_offset), body) ->
[ body
|>> ( centering_d (dx, dy) (w, d) (cap_w, cap_d)
<+> (0., 0., cap_offset +. h) ) ]
| None -> []
in
let cut =
M.difference lump
[ M.cube (14., 14., h +. 0.02)
|>> (((w -. 14.) /. 2.) +. dx, ((d -. 14.) /. 2.) +. dy, -0.01)
; M.cube (16., 16., 1.01)
|>> (((w -. 16.) /. 2.) +. dx, ((d -. 16.) /. 2.) +. dy, h -. 1.)
; M.cube (16., 14., h -. 1.0 -. 1.3 +. 0.001)
|>> (((w -. 16.) /. 2.) +. dx, ((d -. 16.) /. 2.) +. dy, -0.001) ]
in
M.union
[ cut
; M.difference
(M.union
( ( M.cube (16., 10., 1.)
|>> (((w -. 16.) /. 2.) +. dx, ((d -. 10.) /. 2.) +. dy, h -. 1.)
)
:: ( M.cube (16., 3., h)
|>> (((w -. 16.) /. 2.) +. dx, ((d -. 3.) /. 2.) +. dy, 0.) )
:: cap ))
[ M.cube (14., 14., h +. 0.02)
|>> (((w -. 14.) /. 2.) +. dx, ((d -. 14.) /. 2.) +. dy, -0.01) ] ]
let bittradeone_trackball (dx, dy) (w, d, h) =
let lump = M.cube (w, d, h +. 6.) in
M.difference lump
[ M.cube (17., 17., 6. +. 0.001)
|>> (((w -. 17.) /. 2.) +. dx, ((d -. 17.) /. 2.) +. dy, h)
; M.cube (6.35, 1.27, h +. 6. +. 0.02)
|>> ( ((w -. 17.) /. 2.) +. dx +. 7.5
, ((d -. 17.) /. 2.) +. dy +. 1.0
, -0.01 ) ]
let dummy s _ = M.cube s
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.