_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
a0df894dc74d14d6b1805ac64a0b734fcbf5f17d89df506d16bff5dc62519d03
dbmcclain/vmath
simplex.lisp
(in-package :vm) (defun #1=simplex (errfn v &key nmax (tol 1d-6)) (let* ((dim (length v)) (verts (cons v (loop for ix from 0 below dim collect (let* ((vx (copy-seq v))) (setf (aref vx ix) (* 1.1 (aref vx ix))) vx)))) (errs (mapcar errfn verts)) (converged (um:rcurry #'< tol)) (count 0)) (um:nlet iter ((verts verts) (errs errs)) (incf count) (when (zerop (mod count 100)) (format t "~%Count ~d err = ~f" count (reduce #'min errs))) (when (and nmax (> count nmax)) (return-from #1# (values (first verts) (first errs) count))) order vertices err(x_1 ) < = ) < = ... < = err(x_n+1 ) (let* ((pairs (sort (um:zip errs verts) #'< :key #'first)) (verts (mapcar #'second pairs)) (errs (mapcar #'first pairs))) ;; check for convergence (if (every converged (mapcar (um:compose #'abs (um:curry #'- (first errs))) (rest errs))) (values (first verts) (first errs) count) ;; compute centroid of vertices and reflect the worst vertex in the opposite ;; direction from there, starting from the centroid position (let* ((x0 (vops:vscale (/ dim) (apply #'vops:vadd (butlast verts)))) (xr (vops:vadd x0 (vops:vsub x0 (um:last1 verts)))) (errr (funcall errfn xr))) (cond ((and (<= (first errs) errr) (< errr (um:last1 (butlast errs)))) (go-iter (cons xr (butlast verts)) (cons errr (butlast errs)))) ((< errr (first errs)) ;; reflection is better so expand in same direction (let* ((xe (vops:vadd x0 (vops:vscale 2 (vops:vsub xr x0)))) (erre (funcall errfn xe))) (if (< erre errr) ;; is better? (go-iter (cons xe (butlast verts)) (cons erre (butlast errs))) (go-iter (cons xr (butlast verts)) (cons errr (butlast errs)))) )) (t ;; contract in from centroid toward worst vertex (let* ((xc (vops:vadd x0 (vops:vscale 0.5 (vops:vsub (um:last1 verts) x0)))) (errc (funcall errfn xc))) (if (< errc (um:last1 errs)) ;; is better than worst? (go-iter (cons xc (butlast verts)) (cons errc (butlast errs))) ;; shrink the simplex about the best vertex and try again (let* ((x1 (first verts)) (e1 (first errs)) (xs (loop for x in (rest verts) collect (vops:vadd x1 (vops:vscale 0.5 (vops:vsub x x1))))) (errxs (mapcar errfn xs))) (go-iter (cons x1 xs) (cons e1 errxs)) )) )) )) ))) ))
null
https://raw.githubusercontent.com/dbmcclain/vmath/4f811af1a5ae80d864fbe9505054498d29f90e7a/simplex.lisp
lisp
check for convergence compute centroid of vertices and reflect the worst vertex in the opposite direction from there, starting from the centroid position reflection is better so expand in same direction is better? contract in from centroid toward worst vertex is better than worst? shrink the simplex about the best vertex and try again
(in-package :vm) (defun #1=simplex (errfn v &key nmax (tol 1d-6)) (let* ((dim (length v)) (verts (cons v (loop for ix from 0 below dim collect (let* ((vx (copy-seq v))) (setf (aref vx ix) (* 1.1 (aref vx ix))) vx)))) (errs (mapcar errfn verts)) (converged (um:rcurry #'< tol)) (count 0)) (um:nlet iter ((verts verts) (errs errs)) (incf count) (when (zerop (mod count 100)) (format t "~%Count ~d err = ~f" count (reduce #'min errs))) (when (and nmax (> count nmax)) (return-from #1# (values (first verts) (first errs) count))) order vertices err(x_1 ) < = ) < = ... < = err(x_n+1 ) (let* ((pairs (sort (um:zip errs verts) #'< :key #'first)) (verts (mapcar #'second pairs)) (errs (mapcar #'first pairs))) (if (every converged (mapcar (um:compose #'abs (um:curry #'- (first errs))) (rest errs))) (values (first verts) (first errs) count) (let* ((x0 (vops:vscale (/ dim) (apply #'vops:vadd (butlast verts)))) (xr (vops:vadd x0 (vops:vsub x0 (um:last1 verts)))) (errr (funcall errfn xr))) (cond ((and (<= (first errs) errr) (< errr (um:last1 (butlast errs)))) (go-iter (cons xr (butlast verts)) (cons errr (butlast errs)))) ((< errr (first errs)) (let* ((xe (vops:vadd x0 (vops:vscale 2 (vops:vsub xr x0)))) (erre (funcall errfn xe))) (go-iter (cons xe (butlast verts)) (cons erre (butlast errs))) (go-iter (cons xr (butlast verts)) (cons errr (butlast errs)))) )) (t (let* ((xc (vops:vadd x0 (vops:vscale 0.5 (vops:vsub (um:last1 verts) x0)))) (errc (funcall errfn xc))) (go-iter (cons xc (butlast verts)) (cons errc (butlast errs))) (let* ((x1 (first verts)) (e1 (first errs)) (xs (loop for x in (rest verts) collect (vops:vadd x1 (vops:vscale 0.5 (vops:vsub x x1))))) (errxs (mapcar errfn xs))) (go-iter (cons x1 xs) (cons e1 errxs)) )) )) )) ))) ))
7b7663bd12688a4f9cba432456bbe295fed08faf270c7ce7ba82f43ce8374171
progman1/genprintlib
input_handling.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt OCaml port by and (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (**************************** Input control ****************************) open Unix open Primitives (*** Actives files. ***) (* List of the actives files. *) let active_files = ref ([] : (file_descr * ((io_channel -> unit) * io_channel)) list) (* Add a file to the list of actives files. *) let add_file file controller = active_files := (file.io_fd, (controller, file))::!active_files (* Remove a file from the list of actives files. *) let remove_file file = active_files := List.remove_assoc file.io_fd !active_files (* Change the controller for the given file. *) let change_controller file controller = remove_file file; add_file file controller (* Return the controller currently attached to the given file. *) let current_controller file = fst (List.assoc file.io_fd !active_files) (* Execute a function with `controller' attached to `file'. *) # # # controller file funct let execute_with_other_controller controller file funct = let old_controller = current_controller file in change_controller file controller; try let result = funct () in change_controller file old_controller; result with x -> change_controller file old_controller; raise x (*** The "Main Loop" ***) let continue_main_loop = ref true let exit_main_loop _ = continue_main_loop := false (* Handle active files until `continue_main_loop' is false. *) let main_loop () = let old_state = !continue_main_loop in try continue_main_loop := true; while !continue_main_loop do try let (input, _, _) = select (List.map fst !active_files) [] [] (-1.) in List.iter (function fd -> let (funct, iochan) = (List.assoc fd !active_files) in funct iochan) input with Unix_error (EINTR, _, _) -> () done; continue_main_loop := old_state with x -> continue_main_loop := old_state; raise x (*** Managing user inputs ***) (* Are we in interactive mode ? *) let interactif = ref true let current_prompt = ref "" (* Where the user input come from. *) let user_channel = ref std_io let read_user_input buffer length = main_loop (); input !user_channel.io_in buffer 0 length (* Stop reading user input. *) let stop_user_input () = remove_file !user_channel (* Resume reading user input. *) let resume_user_input () = if not (List.mem_assoc !user_channel.io_fd !active_files) then begin if !interactif && !Parameters.prompt then begin print_string !current_prompt; flush Pervasives.stdout end; add_file !user_channel exit_main_loop end
null
https://raw.githubusercontent.com/progman1/genprintlib/acc1e5cc46b9ce6191d0306f51337581c93ffe94/debugger/4.07.1/input_handling.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. ************************************************************************ *************************** Input control *************************** ** Actives files. ** List of the actives files. Add a file to the list of actives files. Remove a file from the list of actives files. Change the controller for the given file. Return the controller currently attached to the given file. Execute a function with `controller' attached to `file'. ** The "Main Loop" ** Handle active files until `continue_main_loop' is false. ** Managing user inputs ** Are we in interactive mode ? Where the user input come from. Stop reading user input. Resume reading user input.
, projet Cristal , INRIA Rocquencourt OCaml port by and Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Unix open Primitives let active_files = ref ([] : (file_descr * ((io_channel -> unit) * io_channel)) list) let add_file file controller = active_files := (file.io_fd, (controller, file))::!active_files let remove_file file = active_files := List.remove_assoc file.io_fd !active_files let change_controller file controller = remove_file file; add_file file controller let current_controller file = fst (List.assoc file.io_fd !active_files) # # # controller file funct let execute_with_other_controller controller file funct = let old_controller = current_controller file in change_controller file controller; try let result = funct () in change_controller file old_controller; result with x -> change_controller file old_controller; raise x let continue_main_loop = ref true let exit_main_loop _ = continue_main_loop := false let main_loop () = let old_state = !continue_main_loop in try continue_main_loop := true; while !continue_main_loop do try let (input, _, _) = select (List.map fst !active_files) [] [] (-1.) in List.iter (function fd -> let (funct, iochan) = (List.assoc fd !active_files) in funct iochan) input with Unix_error (EINTR, _, _) -> () done; continue_main_loop := old_state with x -> continue_main_loop := old_state; raise x let interactif = ref true let current_prompt = ref "" let user_channel = ref std_io let read_user_input buffer length = main_loop (); input !user_channel.io_in buffer 0 length let stop_user_input () = remove_file !user_channel let resume_user_input () = if not (List.mem_assoc !user_channel.io_fd !active_files) then begin if !interactif && !Parameters.prompt then begin print_string !current_prompt; flush Pervasives.stdout end; add_file !user_channel exit_main_loop end
48295926bb7c84bf71d0fe4333ccc67b9834542b1e48f0516b9be3bbbcf1534a
mark-watson/Clojure-AI-Book-Code
project.clj
(defproject python_interop_deeplearning "0.1.0-SNAPSHOT" :description "Example using libpython-clj with the Python spaCy NLP library" :url "-clj-examples" :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0" :url "-2.0/"} :jvm-opts ["-Djdk.attach.allowAttachSelf" "-XX:+UnlockDiagnosticVMOptions" "-XX:+DebugNonSafepoints"] :plugins [[lein-tools-deps "0.4.5"]] :middleware [lein-tools-deps.plugin/resolve-dependencies-with-deps-edn] :lein-tools-deps/config {:config-files [:project] :resolve-aliases []} :mvn/repos {"central" {:url "/"} "clojars" {:url ""}} :dependencies [[org.clojure/clojure "1.10.1"] [clj-python/libpython-clj "1.37"] [clj-http "3.10.3"] [com.cemerick/url "0.1.1"] [org.clojure/data.csv "1.0.0"] [org.clojure/data.json "1.0.0"]] :main ^:skip-aot nlp-libpython-spacy.core :target-path "target/%s" :profiles {:uberjar {:aot :all :jvm-opts ["-Dclojure.compiler.direct-linking=true"]}})
null
https://raw.githubusercontent.com/mark-watson/Clojure-AI-Book-Code/c68c71f671fc2bf75d95616348a9e04303d0da75/nlp_libpython/project.clj
clojure
(defproject python_interop_deeplearning "0.1.0-SNAPSHOT" :description "Example using libpython-clj with the Python spaCy NLP library" :url "-clj-examples" :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0" :url "-2.0/"} :jvm-opts ["-Djdk.attach.allowAttachSelf" "-XX:+UnlockDiagnosticVMOptions" "-XX:+DebugNonSafepoints"] :plugins [[lein-tools-deps "0.4.5"]] :middleware [lein-tools-deps.plugin/resolve-dependencies-with-deps-edn] :lein-tools-deps/config {:config-files [:project] :resolve-aliases []} :mvn/repos {"central" {:url "/"} "clojars" {:url ""}} :dependencies [[org.clojure/clojure "1.10.1"] [clj-python/libpython-clj "1.37"] [clj-http "3.10.3"] [com.cemerick/url "0.1.1"] [org.clojure/data.csv "1.0.0"] [org.clojure/data.json "1.0.0"]] :main ^:skip-aot nlp-libpython-spacy.core :target-path "target/%s" :profiles {:uberjar {:aot :all :jvm-opts ["-Dclojure.compiler.direct-linking=true"]}})
a3b1e6badcaf40f3fc3661a4aa94a641210a6c2d2476c24ffde4b61f50e5283e
turquoise-hexagon/euler
solution.scm
(import (chicken fixnum) (chicken sort) (srfi 1) (srfi 69)) (define-constant limit #e1e9) (define (generate limit proc) (let loop ((i 1) (acc '())) (let ((_ (proc i))) (if (fx> _ limit) acc (loop (fx+ i 1) (cons _ acc)))))) (define (palindrome? n) (let loop ((i n) (acc 0)) (if (fx= i 0) (fx= n acc) (loop (fx/ i 10) (fx+ (fx* acc 10) (fxmod i 10)))))) (define (compute limit) (let ((acc (make-hash-table)) (a (generate limit (lambda (n) (fx* n n)))) (b (generate limit (lambda (n) (fx* n (fx* n n)))))) (for-each (lambda (a) (for-each (lambda (b) (let ((_ (fx+ a b))) (when (palindrome? _) (hash-table-update!/default acc _ (lambda (_) (fx+ _ 1)) 0)))) b)) a) acc)) (define (solve nb-numbers nb-ways) (let ((acc (compute limit))) (foldl fx+ 0 (take (sort (filter (lambda (i) (fx= (hash-table-ref acc i) nb-ways)) (hash-table-keys acc)) fx<) nb-numbers)))) (let ((_ (solve 5 4))) (print _) (assert (= _ 1004195061)))
null
https://raw.githubusercontent.com/turquoise-hexagon/euler/55706a88df2869038d3b910d29f135776c7e3da7/src/spoilers/348/solution.scm
scheme
(import (chicken fixnum) (chicken sort) (srfi 1) (srfi 69)) (define-constant limit #e1e9) (define (generate limit proc) (let loop ((i 1) (acc '())) (let ((_ (proc i))) (if (fx> _ limit) acc (loop (fx+ i 1) (cons _ acc)))))) (define (palindrome? n) (let loop ((i n) (acc 0)) (if (fx= i 0) (fx= n acc) (loop (fx/ i 10) (fx+ (fx* acc 10) (fxmod i 10)))))) (define (compute limit) (let ((acc (make-hash-table)) (a (generate limit (lambda (n) (fx* n n)))) (b (generate limit (lambda (n) (fx* n (fx* n n)))))) (for-each (lambda (a) (for-each (lambda (b) (let ((_ (fx+ a b))) (when (palindrome? _) (hash-table-update!/default acc _ (lambda (_) (fx+ _ 1)) 0)))) b)) a) acc)) (define (solve nb-numbers nb-ways) (let ((acc (compute limit))) (foldl fx+ 0 (take (sort (filter (lambda (i) (fx= (hash-table-ref acc i) nb-ways)) (hash-table-keys acc)) fx<) nb-numbers)))) (let ((_ (solve 5 4))) (print _) (assert (= _ 1004195061)))
04c2ae0e3b9c20ff5fab01875b560b9a6ab6a01b20957f7590de0b1bbcde83bc
HugoPeters1024/hs-sleuth
Pure.hs
-- | Benchmarks various pure functions from the Text library -- -- Tested in this benchmark: -- -- * Most pure functions defined the string types -- # LANGUAGE BangPatterns , CPP , GADTs , MagicHash # # LANGUAGE DeriveGeneric , RecordWildCards # # OPTIONS_GHC -fno - warn - orphans # module Benchmarks.Pure ( initEnv , benchmark ) where import Control.DeepSeq (NFData (..)) import Control.Exception (evaluate) import Test.Tasty.Bench (Benchmark, bgroup, bench, nf) import GHC.Base (Char (..), Int (..), chr#, ord#, (+#)) import GHC.Generics (Generic) import GHC.Int (Int64) import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy.Char8 as BL import qualified Data.List as L import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Builder as TB import qualified Data.Text.Lazy.Encoding as TL data Env = Env { bsa :: !BS.ByteString , ta :: !T.Text , tb :: !T.Text , tla :: !TL.Text , tlb :: !TL.Text , bla :: !BL.ByteString , bsa_len :: !Int , ta_len :: !Int , bla_len :: !Int64 , tla_len :: !Int64 , tl :: [T.Text] , tll :: [TL.Text] } deriving (Generic) instance NFData Env initEnv :: FilePath -> IO Env initEnv fp = do -- Evaluate stuff before actually running the benchmark, we don't want to -- count it here. -- ByteString A bsa <- BS.readFile fp Text A / B , LazyText A / B ta <- evaluate $ T.decodeUtf8 bsa tb <- evaluate $ T.toUpper ta tla <- evaluate $ TL.fromChunks (T.chunksOf 16376 ta) tlb <- evaluate $ TL.fromChunks (T.chunksOf 16376 tb) bla <- evaluate $ BL.fromChunks (chunksOf 16376 bsa) -- Lengths bsa_len <- evaluate $ BS.length bsa ta_len <- evaluate $ T.length ta bla_len <- evaluate $ BL.length bla tla_len <- evaluate $ TL.length tla -- Lines tl <- evaluate $ T.lines ta tll <- evaluate $ TL.lines tla return Env{..} benchmark :: String -> Env -> Benchmark benchmark kind ~Env{..} = bgroup kind [ bgroup "append" [ benchT $ nf (T.append tb) ta , benchTL $ nf (TL.append tlb) tla ] , bgroup "concat" [ benchT $ nf T.concat tl , benchTL $ nf TL.concat tll ] , bgroup "cons" [ benchT $ nf (T.cons c) ta , benchTL $ nf (TL.cons c) tla ] concatMap exceeds 4 G heap size on current test data -- , bgroup "concatMap" [ benchT $ nf ( ( T.replicate 3 . T.singleton ) ) ta , benchTL $ nf ( TL.concatMap ( TL.replicate 3 . TL.singleton ) ) tla -- ] , bgroup "decode" [ benchT $ nf T.decodeUtf8 bsa , benchTL $ nf TL.decodeUtf8 bla ] , bgroup "decode'" [ benchT $ nf T.decodeUtf8' bsa , benchTL $ nf TL.decodeUtf8' bla ] , bgroup "drop" [ benchT $ nf (T.drop (ta_len `div` 3)) ta , benchTL $ nf (TL.drop (tla_len `div` 3)) tla ] , bgroup "encode" [ benchT $ nf T.encodeUtf8 ta , benchTL $ nf TL.encodeUtf8 tla ] , bgroup "filter" [ benchT $ nf (T.filter p0) ta , benchTL $ nf (TL.filter p0) tla ] , bgroup "filter.filter" [ benchT $ nf (T.filter p1 . T.filter p0) ta , benchTL $ nf (TL.filter p1 . TL.filter p0) tla ] , bgroup "foldl'" [ benchT $ nf (T.foldl' len 0) ta , benchTL $ nf (TL.foldl' len 0) tla ] , bgroup "foldr" [ benchT $ nf (L.length . T.foldr (:) []) ta , benchTL $ nf (L.length . TL.foldr (:) []) tla ] , bgroup "head" [ benchT $ nf T.head ta , benchTL $ nf TL.head tla ] , bgroup "init" [ benchT $ nf T.init ta , benchTL $ nf TL.init tla ] , bgroup "intercalate" [ benchT $ nf (T.intercalate tsw) tl , benchTL $ nf (TL.intercalate tlw) tll ] , bgroup "intersperse" [ benchT $ nf (T.intersperse c) ta , benchTL $ nf (TL.intersperse c) tla ] , bgroup "isInfixOf" [ benchT $ nf (T.isInfixOf tsw) ta , benchTL $ nf (TL.isInfixOf tlw) tla ] , bgroup "last" [ benchT $ nf T.last ta , benchTL $ nf TL.last tla ] , bgroup "map" [ benchT $ nf (T.map f) ta , benchTL $ nf (TL.map f) tla ] , bgroup "mapAccumL" [ benchT $ nf (T.mapAccumL g 0) ta , benchTL $ nf (TL.mapAccumL g 0) tla ] , bgroup "mapAccumR" [ benchT $ nf (T.mapAccumR g 0) ta , benchTL $ nf (TL.mapAccumR g 0) tla ] , bgroup "map.map" [ benchT $ nf (T.map f . T.map f) ta , benchTL $ nf (TL.map f . TL.map f) tla ] , bgroup "replicate char" [ benchT $ nf (T.replicate bsa_len) (T.singleton c) , benchTL $ nf (TL.replicate (fromIntegral bsa_len)) (TL.singleton c) ] , bgroup "replicate string" [ benchT $ nf (T.replicate (bsa_len `div` T.length tsw)) tsw , benchTL $ nf (TL.replicate (fromIntegral bsa_len `div` TL.length tlw)) tlw ] , bgroup "reverse" [ benchT $ nf T.reverse ta , benchTL $ nf TL.reverse tla ] , bgroup "take" [ benchT $ nf (T.take (ta_len `div` 3)) ta , benchTL $ nf (TL.take (tla_len `div` 3)) tla ] , bgroup "tail" [ benchT $ nf T.tail ta , benchTL $ nf TL.tail tla ] , bgroup "toLower" [ benchT $ nf T.toLower ta , benchTL $ nf TL.toLower tla ] , bgroup "toUpper" [ benchT $ nf T.toUpper ta , benchTL $ nf TL.toUpper tla ] , bgroup "uncons" [ benchT $ nf T.uncons ta , benchTL $ nf TL.uncons tla ] , bgroup "words" [ benchT $ nf T.words ta , benchTL $ nf TL.words tla ] , bgroup "zipWith" [ benchT $ nf (T.zipWith min tb) ta , benchTL $ nf (TL.zipWith min tlb) tla ] , bgroup "length" [ bgroup "cons" [ benchT $ nf (T.length . T.cons c) ta , benchTL $ nf (TL.length . TL.cons c) tla ] , bgroup "decode" [ benchT $ nf (T.length . T.decodeUtf8) bsa , benchTL $ nf (TL.length . TL.decodeUtf8) bla ] , bgroup "drop" [ benchT $ nf (T.length . T.drop (ta_len `div` 3)) ta , benchTL $ nf (TL.length . TL.drop (tla_len `div` 3)) tla ] , bgroup "filter" [ benchT $ nf (T.length . T.filter p0) ta , benchTL $ nf (TL.length . TL.filter p0) tla ] , bgroup "filter.filter" [ benchT $ nf (T.length . T.filter p1 . T.filter p0) ta , benchTL $ nf (TL.length . TL.filter p1 . TL.filter p0) tla ] , bgroup "init" [ benchT $ nf (T.length . T.init) ta , benchTL $ nf (TL.length . TL.init) tla ] , bgroup "intercalate" [ benchT $ nf (T.length . T.intercalate tsw) tl , benchTL $ nf (TL.length . TL.intercalate tlw) tll ] , bgroup "intersperse" [ benchT $ nf (T.length . T.intersperse c) ta , benchTL $ nf (TL.length . TL.intersperse c) tla ] , bgroup "map" [ benchT $ nf (T.length . T.map f) ta , benchTL $ nf (TL.length . TL.map f) tla ] , bgroup "map.map" [ benchT $ nf (T.length . T.map f . T.map f) ta , benchTL $ nf (TL.length . TL.map f . TL.map f) tla ] , bgroup "replicate char" [ benchT $ nf (T.length . T.replicate bsa_len) (T.singleton c) , benchTL $ nf (TL.length . TL.replicate (fromIntegral bsa_len)) (TL.singleton c) ] , bgroup "replicate string" [ benchT $ nf (T.length . T.replicate (bsa_len `div` T.length tsw)) tsw , benchTL $ nf (TL.length . TL.replicate (fromIntegral bsa_len `div` TL.length tlw)) tlw ] , bgroup "take" [ benchT $ nf (T.length . T.take (ta_len `div` 3)) ta , benchTL $ nf (TL.length . TL.take (tla_len `div` 3)) tla ] , bgroup "tail" [ benchT $ nf (T.length . T.tail) ta , benchTL $ nf (TL.length . TL.tail) tla ] , bgroup "toLower" [ benchT $ nf (T.length . T.toLower) ta , benchTL $ nf (TL.length . TL.toLower) tla ] , bgroup "toUpper" [ benchT $ nf (T.length . T.toUpper) ta , benchTL $ nf (TL.length . TL.toUpper) tla ] , bgroup "words" [ benchT $ nf (L.length . T.words) ta , benchTL $ nf (L.length . TL.words) tla ] , bgroup "zipWith" [ benchT $ nf (T.length . T.zipWith min tb) ta , benchTL $ nf (TL.length . TL.zipWith min tlb) tla ] ] , bgroup "Builder" [ bench "mappend char" $ nf (TL.length . TB.toLazyText . mappendNChar 'a') 10000 , bench "mappend 8 char" $ nf (TL.length . TB.toLazyText . mappend8Char) 'a' , bench "mappend text" $ nf (TL.length . TB.toLazyText . mappendNText short) 10000 ] ] where benchT = bench "Text" benchTL = bench "LazyText" c = 'й' p0 = (== c) p1 = (/= 'д') lw = "право" tsw = T.pack lw tlw = TL.fromChunks [tsw] f (C# c#) = C# (chr# (ord# c# +# 1#)) g (I# i#) (C# c#) = (I# (i# +# 1#), C# (chr# (ord# c# +# i#))) len l _ = l + (1::Int) short = T.pack "short" data B where B :: NFData a => a -> B instance NFData B where rnf (B b) = rnf b -- | Split a bytestring in chunks -- chunksOf :: Int -> BS.ByteString -> [BS.ByteString] chunksOf k = go where go t = case BS.splitAt k t of (a,b) | BS.null a -> [] | otherwise -> a : go b -- | Append a character n times -- mappendNChar :: Char -> Int -> TB.Builder mappendNChar c n = go 0 where go i | i < n = TB.singleton c `mappend` go (i+1) | otherwise = mempty -- | Gives more opportunity for inlining and elimination of unnecesary -- bounds checks. -- mappend8Char :: Char -> TB.Builder mappend8Char c = TB.singleton c `mappend` TB.singleton c `mappend` TB.singleton c `mappend` TB.singleton c `mappend` TB.singleton c `mappend` TB.singleton c `mappend` TB.singleton c `mappend` TB.singleton c -- | Append a text N times -- mappendNText :: T.Text -> Int -> TB.Builder mappendNText t n = go 0 where go i | i < n = TB.fromText t `mappend` go (i+1) | otherwise = mempty
null
https://raw.githubusercontent.com/HugoPeters1024/hs-sleuth/91aa2806ea71b7a26add3801383b3133200971a5/test-project/text-nofusion/benchmarks/haskell/Benchmarks/Pure.hs
haskell
| Benchmarks various pure functions from the Text library Tested in this benchmark: * Most pure functions defined the string types Evaluate stuff before actually running the benchmark, we don't want to count it here. ByteString A Lengths Lines , bgroup "concatMap" ] | Split a bytestring in chunks | Append a character n times | Gives more opportunity for inlining and elimination of unnecesary bounds checks. | Append a text N times
# LANGUAGE BangPatterns , CPP , GADTs , MagicHash # # LANGUAGE DeriveGeneric , RecordWildCards # # OPTIONS_GHC -fno - warn - orphans # module Benchmarks.Pure ( initEnv , benchmark ) where import Control.DeepSeq (NFData (..)) import Control.Exception (evaluate) import Test.Tasty.Bench (Benchmark, bgroup, bench, nf) import GHC.Base (Char (..), Int (..), chr#, ord#, (+#)) import GHC.Generics (Generic) import GHC.Int (Int64) import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy.Char8 as BL import qualified Data.List as L import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Builder as TB import qualified Data.Text.Lazy.Encoding as TL data Env = Env { bsa :: !BS.ByteString , ta :: !T.Text , tb :: !T.Text , tla :: !TL.Text , tlb :: !TL.Text , bla :: !BL.ByteString , bsa_len :: !Int , ta_len :: !Int , bla_len :: !Int64 , tla_len :: !Int64 , tl :: [T.Text] , tll :: [TL.Text] } deriving (Generic) instance NFData Env initEnv :: FilePath -> IO Env initEnv fp = do bsa <- BS.readFile fp Text A / B , LazyText A / B ta <- evaluate $ T.decodeUtf8 bsa tb <- evaluate $ T.toUpper ta tla <- evaluate $ TL.fromChunks (T.chunksOf 16376 ta) tlb <- evaluate $ TL.fromChunks (T.chunksOf 16376 tb) bla <- evaluate $ BL.fromChunks (chunksOf 16376 bsa) bsa_len <- evaluate $ BS.length bsa ta_len <- evaluate $ T.length ta bla_len <- evaluate $ BL.length bla tla_len <- evaluate $ TL.length tla tl <- evaluate $ T.lines ta tll <- evaluate $ TL.lines tla return Env{..} benchmark :: String -> Env -> Benchmark benchmark kind ~Env{..} = bgroup kind [ bgroup "append" [ benchT $ nf (T.append tb) ta , benchTL $ nf (TL.append tlb) tla ] , bgroup "concat" [ benchT $ nf T.concat tl , benchTL $ nf TL.concat tll ] , bgroup "cons" [ benchT $ nf (T.cons c) ta , benchTL $ nf (TL.cons c) tla ] concatMap exceeds 4 G heap size on current test data [ benchT $ nf ( ( T.replicate 3 . T.singleton ) ) ta , benchTL $ nf ( TL.concatMap ( TL.replicate 3 . TL.singleton ) ) tla , bgroup "decode" [ benchT $ nf T.decodeUtf8 bsa , benchTL $ nf TL.decodeUtf8 bla ] , bgroup "decode'" [ benchT $ nf T.decodeUtf8' bsa , benchTL $ nf TL.decodeUtf8' bla ] , bgroup "drop" [ benchT $ nf (T.drop (ta_len `div` 3)) ta , benchTL $ nf (TL.drop (tla_len `div` 3)) tla ] , bgroup "encode" [ benchT $ nf T.encodeUtf8 ta , benchTL $ nf TL.encodeUtf8 tla ] , bgroup "filter" [ benchT $ nf (T.filter p0) ta , benchTL $ nf (TL.filter p0) tla ] , bgroup "filter.filter" [ benchT $ nf (T.filter p1 . T.filter p0) ta , benchTL $ nf (TL.filter p1 . TL.filter p0) tla ] , bgroup "foldl'" [ benchT $ nf (T.foldl' len 0) ta , benchTL $ nf (TL.foldl' len 0) tla ] , bgroup "foldr" [ benchT $ nf (L.length . T.foldr (:) []) ta , benchTL $ nf (L.length . TL.foldr (:) []) tla ] , bgroup "head" [ benchT $ nf T.head ta , benchTL $ nf TL.head tla ] , bgroup "init" [ benchT $ nf T.init ta , benchTL $ nf TL.init tla ] , bgroup "intercalate" [ benchT $ nf (T.intercalate tsw) tl , benchTL $ nf (TL.intercalate tlw) tll ] , bgroup "intersperse" [ benchT $ nf (T.intersperse c) ta , benchTL $ nf (TL.intersperse c) tla ] , bgroup "isInfixOf" [ benchT $ nf (T.isInfixOf tsw) ta , benchTL $ nf (TL.isInfixOf tlw) tla ] , bgroup "last" [ benchT $ nf T.last ta , benchTL $ nf TL.last tla ] , bgroup "map" [ benchT $ nf (T.map f) ta , benchTL $ nf (TL.map f) tla ] , bgroup "mapAccumL" [ benchT $ nf (T.mapAccumL g 0) ta , benchTL $ nf (TL.mapAccumL g 0) tla ] , bgroup "mapAccumR" [ benchT $ nf (T.mapAccumR g 0) ta , benchTL $ nf (TL.mapAccumR g 0) tla ] , bgroup "map.map" [ benchT $ nf (T.map f . T.map f) ta , benchTL $ nf (TL.map f . TL.map f) tla ] , bgroup "replicate char" [ benchT $ nf (T.replicate bsa_len) (T.singleton c) , benchTL $ nf (TL.replicate (fromIntegral bsa_len)) (TL.singleton c) ] , bgroup "replicate string" [ benchT $ nf (T.replicate (bsa_len `div` T.length tsw)) tsw , benchTL $ nf (TL.replicate (fromIntegral bsa_len `div` TL.length tlw)) tlw ] , bgroup "reverse" [ benchT $ nf T.reverse ta , benchTL $ nf TL.reverse tla ] , bgroup "take" [ benchT $ nf (T.take (ta_len `div` 3)) ta , benchTL $ nf (TL.take (tla_len `div` 3)) tla ] , bgroup "tail" [ benchT $ nf T.tail ta , benchTL $ nf TL.tail tla ] , bgroup "toLower" [ benchT $ nf T.toLower ta , benchTL $ nf TL.toLower tla ] , bgroup "toUpper" [ benchT $ nf T.toUpper ta , benchTL $ nf TL.toUpper tla ] , bgroup "uncons" [ benchT $ nf T.uncons ta , benchTL $ nf TL.uncons tla ] , bgroup "words" [ benchT $ nf T.words ta , benchTL $ nf TL.words tla ] , bgroup "zipWith" [ benchT $ nf (T.zipWith min tb) ta , benchTL $ nf (TL.zipWith min tlb) tla ] , bgroup "length" [ bgroup "cons" [ benchT $ nf (T.length . T.cons c) ta , benchTL $ nf (TL.length . TL.cons c) tla ] , bgroup "decode" [ benchT $ nf (T.length . T.decodeUtf8) bsa , benchTL $ nf (TL.length . TL.decodeUtf8) bla ] , bgroup "drop" [ benchT $ nf (T.length . T.drop (ta_len `div` 3)) ta , benchTL $ nf (TL.length . TL.drop (tla_len `div` 3)) tla ] , bgroup "filter" [ benchT $ nf (T.length . T.filter p0) ta , benchTL $ nf (TL.length . TL.filter p0) tla ] , bgroup "filter.filter" [ benchT $ nf (T.length . T.filter p1 . T.filter p0) ta , benchTL $ nf (TL.length . TL.filter p1 . TL.filter p0) tla ] , bgroup "init" [ benchT $ nf (T.length . T.init) ta , benchTL $ nf (TL.length . TL.init) tla ] , bgroup "intercalate" [ benchT $ nf (T.length . T.intercalate tsw) tl , benchTL $ nf (TL.length . TL.intercalate tlw) tll ] , bgroup "intersperse" [ benchT $ nf (T.length . T.intersperse c) ta , benchTL $ nf (TL.length . TL.intersperse c) tla ] , bgroup "map" [ benchT $ nf (T.length . T.map f) ta , benchTL $ nf (TL.length . TL.map f) tla ] , bgroup "map.map" [ benchT $ nf (T.length . T.map f . T.map f) ta , benchTL $ nf (TL.length . TL.map f . TL.map f) tla ] , bgroup "replicate char" [ benchT $ nf (T.length . T.replicate bsa_len) (T.singleton c) , benchTL $ nf (TL.length . TL.replicate (fromIntegral bsa_len)) (TL.singleton c) ] , bgroup "replicate string" [ benchT $ nf (T.length . T.replicate (bsa_len `div` T.length tsw)) tsw , benchTL $ nf (TL.length . TL.replicate (fromIntegral bsa_len `div` TL.length tlw)) tlw ] , bgroup "take" [ benchT $ nf (T.length . T.take (ta_len `div` 3)) ta , benchTL $ nf (TL.length . TL.take (tla_len `div` 3)) tla ] , bgroup "tail" [ benchT $ nf (T.length . T.tail) ta , benchTL $ nf (TL.length . TL.tail) tla ] , bgroup "toLower" [ benchT $ nf (T.length . T.toLower) ta , benchTL $ nf (TL.length . TL.toLower) tla ] , bgroup "toUpper" [ benchT $ nf (T.length . T.toUpper) ta , benchTL $ nf (TL.length . TL.toUpper) tla ] , bgroup "words" [ benchT $ nf (L.length . T.words) ta , benchTL $ nf (L.length . TL.words) tla ] , bgroup "zipWith" [ benchT $ nf (T.length . T.zipWith min tb) ta , benchTL $ nf (TL.length . TL.zipWith min tlb) tla ] ] , bgroup "Builder" [ bench "mappend char" $ nf (TL.length . TB.toLazyText . mappendNChar 'a') 10000 , bench "mappend 8 char" $ nf (TL.length . TB.toLazyText . mappend8Char) 'a' , bench "mappend text" $ nf (TL.length . TB.toLazyText . mappendNText short) 10000 ] ] where benchT = bench "Text" benchTL = bench "LazyText" c = 'й' p0 = (== c) p1 = (/= 'д') lw = "право" tsw = T.pack lw tlw = TL.fromChunks [tsw] f (C# c#) = C# (chr# (ord# c# +# 1#)) g (I# i#) (C# c#) = (I# (i# +# 1#), C# (chr# (ord# c# +# i#))) len l _ = l + (1::Int) short = T.pack "short" data B where B :: NFData a => a -> B instance NFData B where rnf (B b) = rnf b chunksOf :: Int -> BS.ByteString -> [BS.ByteString] chunksOf k = go where go t = case BS.splitAt k t of (a,b) | BS.null a -> [] | otherwise -> a : go b mappendNChar :: Char -> Int -> TB.Builder mappendNChar c n = go 0 where go i | i < n = TB.singleton c `mappend` go (i+1) | otherwise = mempty mappend8Char :: Char -> TB.Builder mappend8Char c = TB.singleton c `mappend` TB.singleton c `mappend` TB.singleton c `mappend` TB.singleton c `mappend` TB.singleton c `mappend` TB.singleton c `mappend` TB.singleton c `mappend` TB.singleton c mappendNText :: T.Text -> Int -> TB.Builder mappendNText t n = go 0 where go i | i < n = TB.fromText t `mappend` go (i+1) | otherwise = mempty
cd34cd9e9651859aa9f2f6cab139582d6d670e310e69b80cbaa67e6d7b4d91cd
jackfirth/rebellion
definition-macro.rkt
#lang racket/base (provide define-tuple-type) (require (for-syntax racket/base racket/sequence rebellion/type/private/naming (submod rebellion/type/tuple/binding private-constructor) rebellion/type/tuple/base syntax/transformer) racket/match rebellion/type/tuple/base rebellion/type/tuple/descriptor syntax/parse/define) (module+ test (require (submod "..") rackunit rebellion/private/static-name)) ;@------------------------------------------------------------------------------ (define-simple-macro (define-tuple-type id:id (field:id ...) (~alt (~optional (~and #:omit-root-binding omit-root-binding-kw)) (~optional (~seq #:descriptor-name descriptor:id) #:defaults ([descriptor (default-descriptor-identifier #'id)]) #:name "#:descriptor-name option") (~optional (~seq #:predicate-name predicate:id) #:defaults ([predicate (default-predicate-identifier #'id)]) #:name "#:predicate-name option") (~optional (~seq #:constructor-name constructor:id) #:defaults ([constructor (default-constructor-identifier #'id)]) #:name "#:constructor-name option") (~optional (~seq #:accessor-name accessor:id) #:defaults ([accessor (default-accessor-identifier #'id)]) #:name "#:accessor-name option") (~optional (~seq #:pattern-name pattern:id) #:defaults ([pattern (default-pattern-identifier #'id)]) #:name "#:pattern-name option") (~optional (~seq #:inspector inspector:expr) #:name "#:inspector option" #:defaults ([inspector #'(current-inspector)])) (~optional (~seq #:property-maker property-maker:expr) #:defaults ([property-maker #'default-tuple-properties]) #:name "#:property-maker option")) ...) #:do [(define size (length (syntax->list #'(field ...))))] #:with (field-accessor ...) (for/list ([field-id (in-syntax #'(field ...))]) (default-field-accessor-identifier #'id field-id)) #:with (field-position ...) (build-list size (λ (n) #`(quote #,n))) #:with root-binding (if (attribute omit-root-binding-kw) #'(begin) #'(define-syntax id (tuple-binding #:type (tuple-type 'id (list 'field ...) #:predicate-name 'predicate #:accessor-name 'accessor #:constructor-name 'constructor) #:descriptor #'descriptor #:predicate #'predicate #:constructor #'constructor #:accessor #'accessor #:fields (list #'field ...) #:field-accessors (list #'field-accessor ...) #:pattern #'pattern #:macro (make-variable-like-transformer #'constructor)))) (begin (define descriptor (make-tuple-implementation (tuple-type 'id (list 'field ...) #:predicate-name 'predicate #:accessor-name 'accessor #:constructor-name 'constructor) #:inspector inspector #:property-maker property-maker)) (define constructor (tuple-descriptor-constructor descriptor)) (define predicate (tuple-descriptor-predicate descriptor)) (define accessor (tuple-descriptor-accessor descriptor)) (define field-accessor (make-tuple-field-accessor descriptor field-position)) ... (define-match-expander pattern (syntax-parser [(_ field ...) #'(? predicate (app field-accessor field) ...)])) root-binding)) (module+ test (test-case (name-string define-tuple-type) (define-tuple-type point (x y)) (check-pred point? (point 1 2)) (check-equal? (point-x (point 1 2)) 1) (check-equal? (point-y (point 1 2)) 2) (check-equal? (point 1 2) (point 1 2)) (check-pred point? (apply point (list 1 2))) (check-match (point 1 2) (point x _) (equal? x 1)) (check-match (point 1 2) (point _ y) (equal? y 2)) (test-case "should allow omitting the root binding" (define-tuple-type point (x y) #:omit-root-binding) (check-match (constructor:point 1 2) (pattern:point x y) (and (equal? x 1) (equal? y 2))) (check-pred point? (apply constructor:point (list 1 2))))))
null
https://raw.githubusercontent.com/jackfirth/rebellion/64f8f82ac3343fe632388bfcbb9e537759ac1ac2/type/tuple/private/definition-macro.rkt
racket
@------------------------------------------------------------------------------
#lang racket/base (provide define-tuple-type) (require (for-syntax racket/base racket/sequence rebellion/type/private/naming (submod rebellion/type/tuple/binding private-constructor) rebellion/type/tuple/base syntax/transformer) racket/match rebellion/type/tuple/base rebellion/type/tuple/descriptor syntax/parse/define) (module+ test (require (submod "..") rackunit rebellion/private/static-name)) (define-simple-macro (define-tuple-type id:id (field:id ...) (~alt (~optional (~and #:omit-root-binding omit-root-binding-kw)) (~optional (~seq #:descriptor-name descriptor:id) #:defaults ([descriptor (default-descriptor-identifier #'id)]) #:name "#:descriptor-name option") (~optional (~seq #:predicate-name predicate:id) #:defaults ([predicate (default-predicate-identifier #'id)]) #:name "#:predicate-name option") (~optional (~seq #:constructor-name constructor:id) #:defaults ([constructor (default-constructor-identifier #'id)]) #:name "#:constructor-name option") (~optional (~seq #:accessor-name accessor:id) #:defaults ([accessor (default-accessor-identifier #'id)]) #:name "#:accessor-name option") (~optional (~seq #:pattern-name pattern:id) #:defaults ([pattern (default-pattern-identifier #'id)]) #:name "#:pattern-name option") (~optional (~seq #:inspector inspector:expr) #:name "#:inspector option" #:defaults ([inspector #'(current-inspector)])) (~optional (~seq #:property-maker property-maker:expr) #:defaults ([property-maker #'default-tuple-properties]) #:name "#:property-maker option")) ...) #:do [(define size (length (syntax->list #'(field ...))))] #:with (field-accessor ...) (for/list ([field-id (in-syntax #'(field ...))]) (default-field-accessor-identifier #'id field-id)) #:with (field-position ...) (build-list size (λ (n) #`(quote #,n))) #:with root-binding (if (attribute omit-root-binding-kw) #'(begin) #'(define-syntax id (tuple-binding #:type (tuple-type 'id (list 'field ...) #:predicate-name 'predicate #:accessor-name 'accessor #:constructor-name 'constructor) #:descriptor #'descriptor #:predicate #'predicate #:constructor #'constructor #:accessor #'accessor #:fields (list #'field ...) #:field-accessors (list #'field-accessor ...) #:pattern #'pattern #:macro (make-variable-like-transformer #'constructor)))) (begin (define descriptor (make-tuple-implementation (tuple-type 'id (list 'field ...) #:predicate-name 'predicate #:accessor-name 'accessor #:constructor-name 'constructor) #:inspector inspector #:property-maker property-maker)) (define constructor (tuple-descriptor-constructor descriptor)) (define predicate (tuple-descriptor-predicate descriptor)) (define accessor (tuple-descriptor-accessor descriptor)) (define field-accessor (make-tuple-field-accessor descriptor field-position)) ... (define-match-expander pattern (syntax-parser [(_ field ...) #'(? predicate (app field-accessor field) ...)])) root-binding)) (module+ test (test-case (name-string define-tuple-type) (define-tuple-type point (x y)) (check-pred point? (point 1 2)) (check-equal? (point-x (point 1 2)) 1) (check-equal? (point-y (point 1 2)) 2) (check-equal? (point 1 2) (point 1 2)) (check-pred point? (apply point (list 1 2))) (check-match (point 1 2) (point x _) (equal? x 1)) (check-match (point 1 2) (point _ y) (equal? y 2)) (test-case "should allow omitting the root binding" (define-tuple-type point (x y) #:omit-root-binding) (check-match (constructor:point 1 2) (pattern:point x y) (and (equal? x 1) (equal? y 2))) (check-pred point? (apply constructor:point (list 1 2))))))
028dea0d27a2326c7f944e3bb277172d8c5865f6c6f47ac15b08dd6785c5e74c
ezrakilty/narc
Common.hs
module Database.Narc.Common where type Tabname = String type Field = String
null
https://raw.githubusercontent.com/ezrakilty/narc/76310e6ac528fe038d8bdd4aa78fa8c555501fad/Database/Narc/Common.hs
haskell
module Database.Narc.Common where type Tabname = String type Field = String
55e87d4c22188e02077e0bcb76c12575f1ba39dcd29a3c981188ff4dad94bb6f
fulcro-legacy/semantic-ui-wrapper
ui_portal.cljs
(ns fulcrologic.semantic-ui.addons.portal.ui-portal (:require [fulcrologic.semantic-ui.factory-helpers :as h] ["semantic-ui-react/dist/commonjs/addons/Portal/Portal" :default Portal])) (def ui-portal "A component that allows you to render children outside their parent. Props: - children (node): Primary content. - closeOnDocumentClick (bool): Controls whether or not the portal should close when the document is clicked. - closeOnEscape (bool): Controls whether or not the portal should close when escape is pressed is displayed. - closeOnPortalMouseLeave (bool): Controls whether or not the portal should close when mousing out of the portal. - closeOnTriggerBlur (bool): Controls whether or not the portal should close on blur of the trigger. - closeOnTriggerClick (bool): Controls whether or not the portal should close on click of the trigger. - closeOnTriggerMouseLeave (bool): Controls whether or not the portal should close when mousing out of the trigger. - defaultOpen (bool): Initial value of open. - eventPool (string): Event pool namespace that is used to handle component events - mountNode (any): The node where the portal should mount. - mouseEnterDelay (number): Milliseconds to wait before opening on mouse over - mouseLeaveDelay (number): Milliseconds to wait before closing on mouse leave - onClose (func): Called when a close event happens - onMount (func): Called when the portal is mounted on the DOM. - onOpen (func): Called when an open event happens - onUnmount (func): Called when the portal is unmounted from the DOM. - open (bool): Controls whether or not the portal is displayed. - openOnTriggerClick (bool): Controls whether or not the portal should open when the trigger is clicked. - openOnTriggerFocus (bool): Controls whether or not the portal should open on focus of the trigger. - openOnTriggerMouseEnter (bool): Controls whether or not the portal should open when mousing over the trigger. - trigger (node): Element to be rendered in-place where the portal is defined. - triggerRef (func|object): Called with a ref to the trigger node. ()" (h/factory-apply Portal))
null
https://raw.githubusercontent.com/fulcro-legacy/semantic-ui-wrapper/b0473480ddfff18496df086bf506099ac897f18f/semantic-ui-wrappers-shadow/src/main/fulcrologic/semantic_ui/addons/portal/ui_portal.cljs
clojure
(ns fulcrologic.semantic-ui.addons.portal.ui-portal (:require [fulcrologic.semantic-ui.factory-helpers :as h] ["semantic-ui-react/dist/commonjs/addons/Portal/Portal" :default Portal])) (def ui-portal "A component that allows you to render children outside their parent. Props: - children (node): Primary content. - closeOnDocumentClick (bool): Controls whether or not the portal should close when the document is clicked. - closeOnEscape (bool): Controls whether or not the portal should close when escape is pressed is displayed. - closeOnPortalMouseLeave (bool): Controls whether or not the portal should close when mousing out of the portal. - closeOnTriggerBlur (bool): Controls whether or not the portal should close on blur of the trigger. - closeOnTriggerClick (bool): Controls whether or not the portal should close on click of the trigger. - closeOnTriggerMouseLeave (bool): Controls whether or not the portal should close when mousing out of the trigger. - defaultOpen (bool): Initial value of open. - eventPool (string): Event pool namespace that is used to handle component events - mountNode (any): The node where the portal should mount. - mouseEnterDelay (number): Milliseconds to wait before opening on mouse over - mouseLeaveDelay (number): Milliseconds to wait before closing on mouse leave - onClose (func): Called when a close event happens - onMount (func): Called when the portal is mounted on the DOM. - onOpen (func): Called when an open event happens - onUnmount (func): Called when the portal is unmounted from the DOM. - open (bool): Controls whether or not the portal is displayed. - openOnTriggerClick (bool): Controls whether or not the portal should open when the trigger is clicked. - openOnTriggerFocus (bool): Controls whether or not the portal should open on focus of the trigger. - openOnTriggerMouseEnter (bool): Controls whether or not the portal should open when mousing over the trigger. - trigger (node): Element to be rendered in-place where the portal is defined. - triggerRef (func|object): Called with a ref to the trigger node. ()" (h/factory-apply Portal))
8a3f22cb591b0555df5244971ba231cd3090ad47eb9bf3d5af4157ae3a266fe0
parapluu/Concuerror
readers.erl
-module(readers). -export([scenarios/0,test/0]). scenarios() -> [{test, B, dpor} || B <- [0, 1, 2, 3, 4, 5, 6, 7]]. test() -> readers(6). readers(N) -> ets:new(tab, [public, named_table]), Writer = fun() -> ets:insert(tab, {x, 42}) end, Reader = fun(I) -> ets:lookup(tab, I), ets:lookup(tab, x) end, spawn(Writer), [spawn(fun() -> Reader(I) end) || I <- lists:seq(1, N)], receive after infinity -> deadlock end.
null
https://raw.githubusercontent.com/parapluu/Concuerror/152a5ccee0b6e97d8c3329c2167166435329d261/tests/suites/bounding_tests/src/readers.erl
erlang
-module(readers). -export([scenarios/0,test/0]). scenarios() -> [{test, B, dpor} || B <- [0, 1, 2, 3, 4, 5, 6, 7]]. test() -> readers(6). readers(N) -> ets:new(tab, [public, named_table]), Writer = fun() -> ets:insert(tab, {x, 42}) end, Reader = fun(I) -> ets:lookup(tab, I), ets:lookup(tab, x) end, spawn(Writer), [spawn(fun() -> Reader(I) end) || I <- lists:seq(1, N)], receive after infinity -> deadlock end.
f37391a52c5d2b84fe1ff01b3a6351bfffc65606d935cbe212d6fafc7c237855
morpheusgraphql/morpheus-graphql
API.hs
module Operation.API where import Operation.Mutation () import Operation.Query () import Operation.Subscription ()
null
https://raw.githubusercontent.com/morpheusgraphql/morpheus-graphql/1d3ab7e3bc723e29ef8bd2a0c818a03ae82ce8ad/examples/code-gen/src/Operation/API.hs
haskell
module Operation.API where import Operation.Mutation () import Operation.Query () import Operation.Subscription ()
784b8310524aa1acc98424e5f2ebc202418fcb00b6e3f50198c0479fe2139938
Perry961002/SICP
exe4.16.scm
; a) (define (lookup-variable-value var env) (define (env-loop env) (define (scan vars vals) (cond ((null? vars) (env-loop (enclosing-environment env))) ((eq? var (car vars)) (if (eq? '*unassigned* (car vals)) (error "Can't use unassigned variable" var) (car vals))) (else (scan (cdr vars) (cdr vals))))) (if (eq? env the-empty-environment) (error "Unbound variable" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))) (env-loop env)) ; b) ;以一个过程体为参数,返回不包括内部定义的等价表达式 (define (scan-out-defines body) ;设置特殊符号'*unassigned* (define (make-unassigned defines) (map (lambda (def) (list (definition-variable def) '*unassigned*)) defines)) ;对特殊变量赋值 (define (set-value defines) (map (lambda (def) (list 'set! (definition-variable def) (definition-value def))) defines)) ;改成写let形式 ;exps是所有的表达式,defines是内部定义式,rest-exps是其他表达式 (define (defines->let exps defines rest-exps) (cond ((null? exps) (if (null? defines) rest-exps (list (list 'let (make-unassigned defines) (make-begin (append (set-value defines) rest-exps)))))) ((definition? (car exps)) (defines->let (cdr exps) (cons (car exps) defines) rest-exps)) (else (defines->let (cdr exps) defines (cons rest-exps (car exps)))))) (defines->let body '() '())) ; c) ;在 make-procedure 里面添加相当于在定义时就处理好内部定义了 在 procedure - body 里面添加相当于在应用时再处理内部定义 ;具体采用哪种形式的定义,可以根据语言的使用场景来,如果 lambda 定义多而应用少,那么可以在 procedure-body 里面添加, ;反之,可以在 make-procedure 里添加。
null
https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/Chap4/exercise/exe4.16.scm
scheme
a) b) 以一个过程体为参数,返回不包括内部定义的等价表达式 设置特殊符号'*unassigned* 对特殊变量赋值 改成写let形式 exps是所有的表达式,defines是内部定义式,rest-exps是其他表达式 c) 在 make-procedure 里面添加相当于在定义时就处理好内部定义了 具体采用哪种形式的定义,可以根据语言的使用场景来,如果 lambda 定义多而应用少,那么可以在 procedure-body 里面添加, 反之,可以在 make-procedure 里添加。
(define (lookup-variable-value var env) (define (env-loop env) (define (scan vars vals) (cond ((null? vars) (env-loop (enclosing-environment env))) ((eq? var (car vars)) (if (eq? '*unassigned* (car vals)) (error "Can't use unassigned variable" var) (car vals))) (else (scan (cdr vars) (cdr vals))))) (if (eq? env the-empty-environment) (error "Unbound variable" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))) (env-loop env)) (define (scan-out-defines body) (define (make-unassigned defines) (map (lambda (def) (list (definition-variable def) '*unassigned*)) defines)) (define (set-value defines) (map (lambda (def) (list 'set! (definition-variable def) (definition-value def))) defines)) (define (defines->let exps defines rest-exps) (cond ((null? exps) (if (null? defines) rest-exps (list (list 'let (make-unassigned defines) (make-begin (append (set-value defines) rest-exps)))))) ((definition? (car exps)) (defines->let (cdr exps) (cons (car exps) defines) rest-exps)) (else (defines->let (cdr exps) defines (cons rest-exps (car exps)))))) (defines->let body '() '())) 在 procedure - body 里面添加相当于在应用时再处理内部定义
4ffe740a9a52c1d47dda337701415458cd63cfdee03966c25abda407c08ace47
ppaml-op3/insomnia
InsomniaStages.hs
{-# LANGUAGE OverloadedStrings #-} module Insomnia.Main.InsomniaStages where import Control.Monad.Reader import Data.Monoid (Monoid(..), (<>)) import qualified Data.Format as F import qualified Pipes import Insomnia.Main.Config import Insomnia.Main.Monad import Insomnia.Main.Stage import Insomnia.Toplevel (Toplevel) import Insomnia.Typecheck as TC import Insomnia.Pretty import qualified Insomnia.IReturn as IReturn import qualified Insomnia.ToF as ToF import qualified FOmega.Syntax as FOmega import qualified FOmega.Check as FCheck import qualified FOmega.Eval as FOmega import qualified Gambling.FromF as ToGamble import qualified Gambling.Emit as EmitGamble import qualified Gambling.Racket import Insomnia.Main.ParsingStage (parsingStage) import Insomnia.Main.SaveFinalProductStage (saveFinalProductStage) parseAndCheck' :: Stage FilePath FOmega.Command parseAndCheck' = parsingStage ->->- desugaring ->->- checking ->->- toFOmega ->->- checkFOmega ->->- conditionalStage (asks ismCfgEvaluateFOmega) runFOmega parseAndCheck :: FilePath -> InsomniaMain () parseAndCheck fp = Pipes.runEffect $ startingFrom fp $ parseAndCheck' ->->- compilerDone parseAndCheckAndGamble :: FilePath -> InsomniaMain () parseAndCheckAndGamble fp = Pipes.runEffect $ startingFrom fp $ parseAndCheck' ->->- translateToGamble ->->- prettyPrintGamble ->->- (saveFinalProductStage "Gamble code") ->->- compilerDone desugaring :: Stage Toplevel Toplevel desugaring = Stage { bannerStage = "Desugaring" , performStage = do t <- Pipes.await let t' = IReturn.toplevel t Pipes.yield t' , formatStage = F.format . ppDefault } checking :: Stage Toplevel Toplevel checking = Stage { bannerStage = "Typechecking" , performStage = do ast <- Pipes.await let tc = TC.runTC $ TC.checkToplevel ast (elab, unifState) <- Pipes.lift $ case tc of Left err -> showErrorAndDie "typechecking" err Right ((elab, _tsum), unifState) -> return (elab, unifState) Pipes.lift $ do putDebugStrLn "Typechecked OK." putDebugStrLn "Unification state:" putDebugDoc (F.format (ppDefault unifState) <> F.newline) Pipes.yield elab , formatStage = F.format . ppDefault } toFOmega :: Stage Toplevel FOmega.Command toFOmega = Stage { bannerStage = "Convert to FΩ" , performStage = do pgm <- Pipes.await let (_sigSummary, tm) = ToF.runToFM $ ToF.toplevel pgm Pipes.yield tm , formatStage = F.format . ppDefault } checkFOmega :: Stage FOmega.Command FOmega.Command checkFOmega = Stage { bannerStage = "Typechecking FΩ" , performStage = do m <- Pipes.await mty <- Pipes.lift $ FCheck.runTC (FCheck.inferCmdTy m) Pipes.lift $ case mty of Left err -> showErrorAndDie "typechecking FOmega" (show err) Right ty -> do putDebugStrLn "FOmega type is: " putDebugDoc (F.format $ ppDefault ty) putDebugStrLn "\n" Pipes.yield m , formatStage = const mempty } runFOmega :: Stage FOmega.Command FOmega.Command runFOmega = Stage { bannerStage = "Running FΩ" , performStage = do m <- Pipes.await mv <- Pipes.lift $ FOmega.runEvalCommand m Pipes.lift $ case mv of Left err -> showErrorAndDie "running FOmega" (show err) Right v -> do putDebugDoc (F.format $ ppDefault v) Pipes.yield m , formatStage = const mempty } translateToGamble :: Stage FOmega.Command Gambling.Racket.Module translateToGamble = Stage { bannerStage = "Translating to Gamble" , performStage = do c <- Pipes.await Pipes.yield $ ToGamble.fomegaToGamble "<unnamed>" c , formatStage = const mempty } prettyPrintGamble :: Stage Gambling.Racket.Module F.Doc prettyPrintGamble = Stage { bannerStage = "Pretty-printing Gamble code" , performStage = do m <- Pipes.await Pipes.yield $ EmitGamble.emitIt m , formatStage = id }
null
https://raw.githubusercontent.com/ppaml-op3/insomnia/5fc6eb1d554e8853d2fc929a957c7edce9e8867d/src/Insomnia/Main/InsomniaStages.hs
haskell
# LANGUAGE OverloadedStrings #
module Insomnia.Main.InsomniaStages where import Control.Monad.Reader import Data.Monoid (Monoid(..), (<>)) import qualified Data.Format as F import qualified Pipes import Insomnia.Main.Config import Insomnia.Main.Monad import Insomnia.Main.Stage import Insomnia.Toplevel (Toplevel) import Insomnia.Typecheck as TC import Insomnia.Pretty import qualified Insomnia.IReturn as IReturn import qualified Insomnia.ToF as ToF import qualified FOmega.Syntax as FOmega import qualified FOmega.Check as FCheck import qualified FOmega.Eval as FOmega import qualified Gambling.FromF as ToGamble import qualified Gambling.Emit as EmitGamble import qualified Gambling.Racket import Insomnia.Main.ParsingStage (parsingStage) import Insomnia.Main.SaveFinalProductStage (saveFinalProductStage) parseAndCheck' :: Stage FilePath FOmega.Command parseAndCheck' = parsingStage ->->- desugaring ->->- checking ->->- toFOmega ->->- checkFOmega ->->- conditionalStage (asks ismCfgEvaluateFOmega) runFOmega parseAndCheck :: FilePath -> InsomniaMain () parseAndCheck fp = Pipes.runEffect $ startingFrom fp $ parseAndCheck' ->->- compilerDone parseAndCheckAndGamble :: FilePath -> InsomniaMain () parseAndCheckAndGamble fp = Pipes.runEffect $ startingFrom fp $ parseAndCheck' ->->- translateToGamble ->->- prettyPrintGamble ->->- (saveFinalProductStage "Gamble code") ->->- compilerDone desugaring :: Stage Toplevel Toplevel desugaring = Stage { bannerStage = "Desugaring" , performStage = do t <- Pipes.await let t' = IReturn.toplevel t Pipes.yield t' , formatStage = F.format . ppDefault } checking :: Stage Toplevel Toplevel checking = Stage { bannerStage = "Typechecking" , performStage = do ast <- Pipes.await let tc = TC.runTC $ TC.checkToplevel ast (elab, unifState) <- Pipes.lift $ case tc of Left err -> showErrorAndDie "typechecking" err Right ((elab, _tsum), unifState) -> return (elab, unifState) Pipes.lift $ do putDebugStrLn "Typechecked OK." putDebugStrLn "Unification state:" putDebugDoc (F.format (ppDefault unifState) <> F.newline) Pipes.yield elab , formatStage = F.format . ppDefault } toFOmega :: Stage Toplevel FOmega.Command toFOmega = Stage { bannerStage = "Convert to FΩ" , performStage = do pgm <- Pipes.await let (_sigSummary, tm) = ToF.runToFM $ ToF.toplevel pgm Pipes.yield tm , formatStage = F.format . ppDefault } checkFOmega :: Stage FOmega.Command FOmega.Command checkFOmega = Stage { bannerStage = "Typechecking FΩ" , performStage = do m <- Pipes.await mty <- Pipes.lift $ FCheck.runTC (FCheck.inferCmdTy m) Pipes.lift $ case mty of Left err -> showErrorAndDie "typechecking FOmega" (show err) Right ty -> do putDebugStrLn "FOmega type is: " putDebugDoc (F.format $ ppDefault ty) putDebugStrLn "\n" Pipes.yield m , formatStage = const mempty } runFOmega :: Stage FOmega.Command FOmega.Command runFOmega = Stage { bannerStage = "Running FΩ" , performStage = do m <- Pipes.await mv <- Pipes.lift $ FOmega.runEvalCommand m Pipes.lift $ case mv of Left err -> showErrorAndDie "running FOmega" (show err) Right v -> do putDebugDoc (F.format $ ppDefault v) Pipes.yield m , formatStage = const mempty } translateToGamble :: Stage FOmega.Command Gambling.Racket.Module translateToGamble = Stage { bannerStage = "Translating to Gamble" , performStage = do c <- Pipes.await Pipes.yield $ ToGamble.fomegaToGamble "<unnamed>" c , formatStage = const mempty } prettyPrintGamble :: Stage Gambling.Racket.Module F.Doc prettyPrintGamble = Stage { bannerStage = "Pretty-printing Gamble code" , performStage = do m <- Pipes.await Pipes.yield $ EmitGamble.emitIt m , formatStage = id }
f94f36336aef0159a84c28da75b9c3ea416353557b4a7cb77855c31bb006d55d
Misterio77/aoc2022
Shape.hs
module Shape where data Shape = Rock | Paper | Scissors deriving (Eq) toScore :: Shape -> Int toScore Rock = 1 toScore Paper = 2 toScore Scissors = 3 fromChar :: Char -> Shape fromChar 'A' = Rock fromChar 'B' = Paper fromChar 'C' = Scissors fromChar 'X' = Rock fromChar 'Y' = Paper fromChar 'Z' = Scissors fromChar x = error $ "Invalid shape: " ++ show x winsFrom :: Shape -> Shape winsFrom Rock = Paper winsFrom Paper = Scissors winsFrom Scissors = Rock losesTo :: Shape -> Shape losesTo Rock = Scissors losesTo Paper = Rock losesTo Scissors = Paper
null
https://raw.githubusercontent.com/Misterio77/aoc2022/eec09d01ba1e0fa921a737d5a2eb81dd602fadfd/src/day2/Shape.hs
haskell
module Shape where data Shape = Rock | Paper | Scissors deriving (Eq) toScore :: Shape -> Int toScore Rock = 1 toScore Paper = 2 toScore Scissors = 3 fromChar :: Char -> Shape fromChar 'A' = Rock fromChar 'B' = Paper fromChar 'C' = Scissors fromChar 'X' = Rock fromChar 'Y' = Paper fromChar 'Z' = Scissors fromChar x = error $ "Invalid shape: " ++ show x winsFrom :: Shape -> Shape winsFrom Rock = Paper winsFrom Paper = Scissors winsFrom Scissors = Rock losesTo :: Shape -> Shape losesTo Rock = Scissors losesTo Paper = Rock losesTo Scissors = Paper
aae38189aa183282322367bb77fb83621e9eca812978963332fde82789bac6e3
input-output-hk/ouroboros-network
Degenerate.hs
{-# LANGUAGE DataKinds #-} # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ScopedTypeVariables #-} # LANGUAGE TypeApplications # # LANGUAGE UndecidableInstances # # LANGUAGE ViewPatterns # # OPTIONS_GHC -Wno - orphans # module Ouroboros.Consensus.HardFork.Combinator.Degenerate ( -- * Pattern synonyms BlockConfig (DegenBlockConfig) , BlockQuery (DegenQuery) , CodecConfig (DegenCodecConfig) , ConsensusConfig (DegenConsensusConfig) , Either (DegenQueryResult) , GenTx (DegenGenTx) , HardForkApplyTxErr (DegenApplyTxErr) , HardForkBlock (DegenBlock) , HardForkEnvelopeErr (DegenOtherHeaderEnvelopeError) , HardForkLedgerConfig (DegenLedgerConfig) , HardForkLedgerError (DegenLedgerError) , Header (DegenHeader) , LedgerState (DegenLedgerState) , OneEraTipInfo (DegenTipInfo) , TopLevelConfig (DegenTopLevelConfig) , TxId (DegenGenTxId) ) where import Data.SOP.Strict import Ouroboros.Consensus.Block.Abstract import Ouroboros.Consensus.Config import Ouroboros.Consensus.HeaderValidation import Ouroboros.Consensus.Ledger.Abstract import Ouroboros.Consensus.Ledger.SupportsMempool import Ouroboros.Consensus.TypeFamilyWrappers import Ouroboros.Consensus.HardFork.Combinator.Abstract.NoHardForks import Ouroboros.Consensus.HardFork.Combinator.AcrossEras import Ouroboros.Consensus.HardFork.Combinator.Basics import Ouroboros.Consensus.HardFork.Combinator.Embed.Unary import Ouroboros.Consensus.HardFork.Combinator.Ledger import Ouroboros.Consensus.HardFork.Combinator.Ledger.CommonProtocolParams () import Ouroboros.Consensus.HardFork.Combinator.Ledger.Query import Ouroboros.Consensus.HardFork.Combinator.Mempool import Ouroboros.Consensus.HardFork.Combinator.Node () import Ouroboros.Consensus.HardFork.Combinator.PartialConfig import Ouroboros.Consensus.HardFork.Combinator.Serialisation.SerialiseDisk () import Ouroboros.Consensus.HardFork.Combinator.Serialisation.SerialiseNodeToClient () import Ouroboros.Consensus.HardFork.Combinator.Serialisation.SerialiseNodeToNode () {------------------------------------------------------------------------------- Simple patterns -------------------------------------------------------------------------------} {-# COMPLETE DegenApplyTxErr #-} {-# COMPLETE DegenBlock #-} {-# COMPLETE DegenBlockConfig #-} {-# COMPLETE DegenCodecConfig #-} {-# COMPLETE DegenGenTx #-} {-# COMPLETE DegenGenTxId #-} {-# COMPLETE DegenHeader #-} {-# COMPLETE DegenLedgerError #-} {-# COMPLETE DegenLedgerState #-} # COMPLETE DegenOtherHeaderEnvelopeError # {-# COMPLETE DegenQuery #-} {-# COMPLETE DegenQueryResult #-} {-# COMPLETE DegenTipInfo #-} pattern DegenBlock :: forall b. NoHardForks b => b -> HardForkBlock '[b] pattern DegenBlock x <- (project' (Proxy @(I b)) -> x) where DegenBlock x = inject' (Proxy @(I b)) x pattern DegenHeader :: NoHardForks b => Header b -> Header (HardForkBlock '[b]) pattern DegenHeader x <- (project -> x) where DegenHeader x = inject x pattern DegenGenTx :: NoHardForks b => GenTx b -> GenTx (HardForkBlock '[b]) pattern DegenGenTx x <- (project -> x) where DegenGenTx x = inject x pattern DegenGenTxId :: forall b. NoHardForks b => GenTxId b -> GenTxId (HardForkBlock '[b]) pattern DegenGenTxId x <- (project' (Proxy @(WrapGenTxId b)) -> x) where DegenGenTxId x = inject' (Proxy @(WrapGenTxId b)) x pattern DegenApplyTxErr :: forall b. NoHardForks b => ApplyTxErr b -> HardForkApplyTxErr '[b] -- ApplyTxErr (HardForkBlock '[b]) pattern DegenApplyTxErr x <- (project' (Proxy @(WrapApplyTxErr b)) -> x) where DegenApplyTxErr x = inject' (Proxy @(WrapApplyTxErr b)) x pattern DegenLedgerError :: forall b. NoHardForks b => LedgerError b LedgerError ( HardForkBlock ' [ b ] ) pattern DegenLedgerError x <- (project' (Proxy @(WrapLedgerErr b)) -> x) where DegenLedgerError x = inject' (Proxy @(WrapLedgerErr b)) x pattern DegenOtherHeaderEnvelopeError :: forall b. NoHardForks b => OtherHeaderEnvelopeError b -> HardForkEnvelopeErr '[b] -- OtherHeaderEnvelopeError (HardForkBlock '[b]) pattern DegenOtherHeaderEnvelopeError x <- (project' (Proxy @(WrapEnvelopeErr b)) -> x) where DegenOtherHeaderEnvelopeError x = inject' (Proxy @(WrapEnvelopeErr b)) x pattern DegenTipInfo :: forall b. NoHardForks b => TipInfo b TipInfo ( HardForkBlock ' [ b ] ) pattern DegenTipInfo x <- (project' (Proxy @(WrapTipInfo b)) -> x) where DegenTipInfo x = inject' (Proxy @(WrapTipInfo b)) x pattern DegenQuery :: () => HardForkQueryResult '[b] result ~ a => BlockQuery b result -> BlockQuery (HardForkBlock '[b]) a pattern DegenQuery x <- (projQuery' -> ProjHardForkQuery x) where DegenQuery x = injQuery x pattern DegenQueryResult :: result -> HardForkQueryResult '[b] result pattern DegenQueryResult x <- (projQueryResult -> x) where DegenQueryResult x = injQueryResult x pattern DegenCodecConfig :: NoHardForks b => CodecConfig b -> CodecConfig (HardForkBlock '[b]) pattern DegenCodecConfig x <- (project -> x) where DegenCodecConfig x = inject x pattern DegenBlockConfig :: NoHardForks b => BlockConfig b -> BlockConfig (HardForkBlock '[b]) pattern DegenBlockConfig x <- (project -> x) where DegenBlockConfig x = inject x pattern DegenLedgerState :: NoHardForks b => LedgerState b -> LedgerState (HardForkBlock '[b]) pattern DegenLedgerState x <- (project -> x) where DegenLedgerState x = inject x ------------------------------------------------------------------------------ Dealing with the config NOTE : The pattern synonyms for ' ConsensusConfig ' and ' LedgerConfig ' give you a /partial/ config . The pattern synonym for the ' TopLevelConfig ' /does/ give you a full config . ------------------------------------------------------------------------------ Dealing with the config NOTE: The pattern synonyms for 'ConsensusConfig' and 'LedgerConfig' give you a /partial/ config. The pattern synonym for the 'TopLevelConfig' /does/ give you a full config. -------------------------------------------------------------------------------} {-# COMPLETE DegenConsensusConfig #-} # COMPLETE DegenLedgerConfig # {-# COMPLETE DegenTopLevelConfig #-} pattern DegenConsensusConfig :: PartialConsensusConfig (BlockProtocol b) -> ConsensusConfig (BlockProtocol (HardForkBlock '[b])) pattern DegenConsensusConfig x <- HardForkConsensusConfig { hardForkConsensusConfigPerEra = PerEraConsensusConfig ( WrapPartialConsensusConfig x :* Nil ) } pattern DegenLedgerConfig :: PartialLedgerConfig b LedgerConfig ( HardForkBlock ' [ b ] ) pattern DegenLedgerConfig x <- HardForkLedgerConfig { hardForkLedgerConfigPerEra = PerEraLedgerConfig ( WrapPartialLedgerConfig x :* Nil ) } pattern DegenTopLevelConfig :: NoHardForks b => TopLevelConfig b -> TopLevelConfig (HardForkBlock '[b]) pattern DegenTopLevelConfig x <- (project -> x) where DegenTopLevelConfig x = inject x
null
https://raw.githubusercontent.com/input-output-hk/ouroboros-network/437d7160079c83c4632fe0a42c596e5105c59a4d/ouroboros-consensus/src/Ouroboros/Consensus/HardFork/Combinator/Degenerate.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE GADTs # # LANGUAGE PatternSynonyms # # LANGUAGE ScopedTypeVariables # * Pattern synonyms ------------------------------------------------------------------------------ Simple patterns ------------------------------------------------------------------------------ # COMPLETE DegenApplyTxErr # # COMPLETE DegenBlock # # COMPLETE DegenBlockConfig # # COMPLETE DegenCodecConfig # # COMPLETE DegenGenTx # # COMPLETE DegenGenTxId # # COMPLETE DegenHeader # # COMPLETE DegenLedgerError # # COMPLETE DegenLedgerState # # COMPLETE DegenQuery # # COMPLETE DegenQueryResult # # COMPLETE DegenTipInfo # ApplyTxErr (HardForkBlock '[b]) OtherHeaderEnvelopeError (HardForkBlock '[b]) ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -----------------------------------------------------------------------------} # COMPLETE DegenConsensusConfig # # COMPLETE DegenTopLevelConfig #
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE TypeApplications # # LANGUAGE UndecidableInstances # # LANGUAGE ViewPatterns # # OPTIONS_GHC -Wno - orphans # module Ouroboros.Consensus.HardFork.Combinator.Degenerate ( BlockConfig (DegenBlockConfig) , BlockQuery (DegenQuery) , CodecConfig (DegenCodecConfig) , ConsensusConfig (DegenConsensusConfig) , Either (DegenQueryResult) , GenTx (DegenGenTx) , HardForkApplyTxErr (DegenApplyTxErr) , HardForkBlock (DegenBlock) , HardForkEnvelopeErr (DegenOtherHeaderEnvelopeError) , HardForkLedgerConfig (DegenLedgerConfig) , HardForkLedgerError (DegenLedgerError) , Header (DegenHeader) , LedgerState (DegenLedgerState) , OneEraTipInfo (DegenTipInfo) , TopLevelConfig (DegenTopLevelConfig) , TxId (DegenGenTxId) ) where import Data.SOP.Strict import Ouroboros.Consensus.Block.Abstract import Ouroboros.Consensus.Config import Ouroboros.Consensus.HeaderValidation import Ouroboros.Consensus.Ledger.Abstract import Ouroboros.Consensus.Ledger.SupportsMempool import Ouroboros.Consensus.TypeFamilyWrappers import Ouroboros.Consensus.HardFork.Combinator.Abstract.NoHardForks import Ouroboros.Consensus.HardFork.Combinator.AcrossEras import Ouroboros.Consensus.HardFork.Combinator.Basics import Ouroboros.Consensus.HardFork.Combinator.Embed.Unary import Ouroboros.Consensus.HardFork.Combinator.Ledger import Ouroboros.Consensus.HardFork.Combinator.Ledger.CommonProtocolParams () import Ouroboros.Consensus.HardFork.Combinator.Ledger.Query import Ouroboros.Consensus.HardFork.Combinator.Mempool import Ouroboros.Consensus.HardFork.Combinator.Node () import Ouroboros.Consensus.HardFork.Combinator.PartialConfig import Ouroboros.Consensus.HardFork.Combinator.Serialisation.SerialiseDisk () import Ouroboros.Consensus.HardFork.Combinator.Serialisation.SerialiseNodeToClient () import Ouroboros.Consensus.HardFork.Combinator.Serialisation.SerialiseNodeToNode () # COMPLETE DegenOtherHeaderEnvelopeError # pattern DegenBlock :: forall b. NoHardForks b => b -> HardForkBlock '[b] pattern DegenBlock x <- (project' (Proxy @(I b)) -> x) where DegenBlock x = inject' (Proxy @(I b)) x pattern DegenHeader :: NoHardForks b => Header b -> Header (HardForkBlock '[b]) pattern DegenHeader x <- (project -> x) where DegenHeader x = inject x pattern DegenGenTx :: NoHardForks b => GenTx b -> GenTx (HardForkBlock '[b]) pattern DegenGenTx x <- (project -> x) where DegenGenTx x = inject x pattern DegenGenTxId :: forall b. NoHardForks b => GenTxId b -> GenTxId (HardForkBlock '[b]) pattern DegenGenTxId x <- (project' (Proxy @(WrapGenTxId b)) -> x) where DegenGenTxId x = inject' (Proxy @(WrapGenTxId b)) x pattern DegenApplyTxErr :: forall b. NoHardForks b => ApplyTxErr b pattern DegenApplyTxErr x <- (project' (Proxy @(WrapApplyTxErr b)) -> x) where DegenApplyTxErr x = inject' (Proxy @(WrapApplyTxErr b)) x pattern DegenLedgerError :: forall b. NoHardForks b => LedgerError b LedgerError ( HardForkBlock ' [ b ] ) pattern DegenLedgerError x <- (project' (Proxy @(WrapLedgerErr b)) -> x) where DegenLedgerError x = inject' (Proxy @(WrapLedgerErr b)) x pattern DegenOtherHeaderEnvelopeError :: forall b. NoHardForks b => OtherHeaderEnvelopeError b pattern DegenOtherHeaderEnvelopeError x <- (project' (Proxy @(WrapEnvelopeErr b)) -> x) where DegenOtherHeaderEnvelopeError x = inject' (Proxy @(WrapEnvelopeErr b)) x pattern DegenTipInfo :: forall b. NoHardForks b => TipInfo b TipInfo ( HardForkBlock ' [ b ] ) pattern DegenTipInfo x <- (project' (Proxy @(WrapTipInfo b)) -> x) where DegenTipInfo x = inject' (Proxy @(WrapTipInfo b)) x pattern DegenQuery :: () => HardForkQueryResult '[b] result ~ a => BlockQuery b result -> BlockQuery (HardForkBlock '[b]) a pattern DegenQuery x <- (projQuery' -> ProjHardForkQuery x) where DegenQuery x = injQuery x pattern DegenQueryResult :: result -> HardForkQueryResult '[b] result pattern DegenQueryResult x <- (projQueryResult -> x) where DegenQueryResult x = injQueryResult x pattern DegenCodecConfig :: NoHardForks b => CodecConfig b -> CodecConfig (HardForkBlock '[b]) pattern DegenCodecConfig x <- (project -> x) where DegenCodecConfig x = inject x pattern DegenBlockConfig :: NoHardForks b => BlockConfig b -> BlockConfig (HardForkBlock '[b]) pattern DegenBlockConfig x <- (project -> x) where DegenBlockConfig x = inject x pattern DegenLedgerState :: NoHardForks b => LedgerState b -> LedgerState (HardForkBlock '[b]) pattern DegenLedgerState x <- (project -> x) where DegenLedgerState x = inject x Dealing with the config NOTE : The pattern synonyms for ' ConsensusConfig ' and ' LedgerConfig ' give you a /partial/ config . The pattern synonym for the ' TopLevelConfig ' /does/ give you a full config . Dealing with the config NOTE: The pattern synonyms for 'ConsensusConfig' and 'LedgerConfig' give you a /partial/ config. The pattern synonym for the 'TopLevelConfig' /does/ give you a full config. # COMPLETE DegenLedgerConfig # pattern DegenConsensusConfig :: PartialConsensusConfig (BlockProtocol b) -> ConsensusConfig (BlockProtocol (HardForkBlock '[b])) pattern DegenConsensusConfig x <- HardForkConsensusConfig { hardForkConsensusConfigPerEra = PerEraConsensusConfig ( WrapPartialConsensusConfig x :* Nil ) } pattern DegenLedgerConfig :: PartialLedgerConfig b LedgerConfig ( HardForkBlock ' [ b ] ) pattern DegenLedgerConfig x <- HardForkLedgerConfig { hardForkLedgerConfigPerEra = PerEraLedgerConfig ( WrapPartialLedgerConfig x :* Nil ) } pattern DegenTopLevelConfig :: NoHardForks b => TopLevelConfig b -> TopLevelConfig (HardForkBlock '[b]) pattern DegenTopLevelConfig x <- (project -> x) where DegenTopLevelConfig x = inject x
a8cd7c0b814f74939a8f6044b21577b64116b977e4bac98292dfc72ef2b7592f
mbj/stratosphere
Rec709SettingsProperty.hs
module Stratosphere.MediaLive.Channel.Rec709SettingsProperty ( Rec709SettingsProperty(..), mkRec709SettingsProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.ResourceProperties data Rec709SettingsProperty = Rec709SettingsProperty {} mkRec709SettingsProperty :: Rec709SettingsProperty mkRec709SettingsProperty = Rec709SettingsProperty {} instance ToResourceProperties Rec709SettingsProperty where toResourceProperties Rec709SettingsProperty {} = ResourceProperties {awsType = "AWS::MediaLive::Channel.Rec709Settings", supportsTags = Prelude.False, properties = []} instance JSON.ToJSON Rec709SettingsProperty where toJSON Rec709SettingsProperty {} = JSON.object []
null
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/medialive/gen/Stratosphere/MediaLive/Channel/Rec709SettingsProperty.hs
haskell
module Stratosphere.MediaLive.Channel.Rec709SettingsProperty ( Rec709SettingsProperty(..), mkRec709SettingsProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.ResourceProperties data Rec709SettingsProperty = Rec709SettingsProperty {} mkRec709SettingsProperty :: Rec709SettingsProperty mkRec709SettingsProperty = Rec709SettingsProperty {} instance ToResourceProperties Rec709SettingsProperty where toResourceProperties Rec709SettingsProperty {} = ResourceProperties {awsType = "AWS::MediaLive::Channel.Rec709Settings", supportsTags = Prelude.False, properties = []} instance JSON.ToJSON Rec709SettingsProperty where toJSON Rec709SettingsProperty {} = JSON.object []
88ce963fbc5e0113f3e8534676c6816ae295ec01a19d1b047654daa8fd1654f9
namenu/tfjs-cljs
macros.clj
(ns tfjs-cljs.macros) (defn ->camelCase [s] (let [s (clojure.string/split s #"-")] (transduce (map clojure.string/capitalize) str (first s) (next s)))) (defmacro deftf [name] (let [params (gensym) cname (symbol "js" (->camelCase (str "tf." name)))] `(defn ~name [& ~params] (apply ~cname ~params)))) (defmacro defconst [n keywords] (let [const-map (mapv (comp ->camelCase name) keywords)] `(def ~n (zipmap ~keywords ~const-map))))
null
https://raw.githubusercontent.com/namenu/tfjs-cljs/24d1b22c0be58c38d723dafad9734283d526564d/src/tfjs_cljs/macros.clj
clojure
(ns tfjs-cljs.macros) (defn ->camelCase [s] (let [s (clojure.string/split s #"-")] (transduce (map clojure.string/capitalize) str (first s) (next s)))) (defmacro deftf [name] (let [params (gensym) cname (symbol "js" (->camelCase (str "tf." name)))] `(defn ~name [& ~params] (apply ~cname ~params)))) (defmacro defconst [n keywords] (let [const-map (mapv (comp ->camelCase name) keywords)] `(def ~n (zipmap ~keywords ~const-map))))
8aa8610c32a5c6336e3276abf0ebc2e23d735c8d265a2e36268af5b44e70582b
qkrgud55/ocamlmulti
rawwidget.ml
(***********************************************************************) (* *) MLTk , Tcl / Tk interface of OCaml (* *) , , and projet Cristal , INRIA Rocquencourt , Kyoto University RIMS (* *) Copyright 2002 Institut National de Recherche en Informatique et en Automatique and Kyoto University . 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 found in the OCaml source tree. *) (* *) (***********************************************************************) $ I d : rawwidget.ml 11156 2011 - 07 - 27 14:17:02Z doligez $ open Support (* * Widgets *) exception IllegalWidgetType of string (* Raised when widget command applied illegally*) (***************************************************) (* Widgets *) (* This 'a raw_widget will be 'a Widget.widget *) (***************************************************) type 'a raw_widget = Untyped of string | Typed of string * string type raw_any (* will be Widget.any *) and button and canvas and checkbutton and entry and frame and label and listbox and menu and menubutton and message and radiobutton and scale and scrollbar and text and toplevel let forget_type w = (Obj.magic (w : 'a raw_widget) : raw_any raw_widget) let coe = forget_type (* table of widgets *) let table = (Hashtbl.create 401 : (string, raw_any raw_widget) Hashtbl.t) let name = function Untyped s -> s | Typed (s,_) -> s (* Normally all widgets are known *) (* this is a provision for send commands to external tk processes *) let known_class = function Untyped _ -> "unknown" | Typed (_,c) -> c (* This one is always created by opentk *) let default_toplevel = let wname = "." in let w = Typed (wname, "toplevel") in Hashtbl.add table wname w; w (* Dummy widget to which global callbacks are associated *) (* also passed around by camltotkoption when no widget in context *) let dummy = Untyped "dummy" let remove w = Hashtbl.remove table (name w) Retype widgets returned from Tk JPF report : sometime s is " " , see Protocol.cTKtoCAMLwidget let get_atom s = try Hashtbl.find table s with Not_found -> Untyped s let naming_scheme = [ "button", "b"; "canvas", "ca"; "checkbutton", "cb"; "entry", "en"; "frame", "f"; "label", "l"; "listbox", "li"; "menu", "me"; "menubutton", "mb"; "message", "ms"; "radiobutton", "rb"; "scale", "sc"; "scrollbar", "sb"; "text", "t"; "toplevel", "top" ] let widget_any_table = List.map fst naming_scheme (* subtypes *) let widget_button_table = [ "button" ] and widget_canvas_table = [ "canvas" ] and widget_checkbutton_table = [ "checkbutton" ] and widget_entry_table = [ "entry" ] and widget_frame_table = [ "frame" ] and widget_label_table = [ "label" ] and widget_listbox_table = [ "listbox" ] and widget_menu_table = [ "menu" ] and widget_menubutton_table = [ "menubutton" ] and widget_message_table = [ "message" ] and widget_radiobutton_table = [ "radiobutton" ] and widget_scale_table = [ "scale" ] and widget_scrollbar_table = [ "scrollbar" ] and widget_text_table = [ "text" ] and widget_toplevel_table = [ "toplevel" ] let new_suffix clas n = try (List.assoc clas naming_scheme) ^ (string_of_int n) with Not_found -> "w" ^ (string_of_int n) (* The function called by generic creation *) let counter = ref 0 let new_atom ~parent ?name:nom clas = let parentpath = name parent in let path = match nom with None -> incr counter; if parentpath = "." then "." ^ (new_suffix clas !counter) else parentpath ^ "." ^ (new_suffix clas !counter) | Some name -> if parentpath = "." then "." ^ name else parentpath ^ "." ^ name in let w = Typed(path,clas) in Hashtbl.add table path w; w (* Just create a path. Only to check existence of widgets *) (* Use with care *) let atom ~parent ~name:pathcomp = let parentpath = name parent in let path = if parentpath = "." then "." ^ pathcomp else parentpath ^ "." ^ pathcomp in Untyped path (* LablTk: Redundant with subtyping of Widget, backward compatibility *) let check_class w clas = match w with Untyped _ -> () (* assume run-time check by tk*) | Typed(_,c) -> if List.mem c clas then () else raise (IllegalWidgetType c) (* Checking membership of constructor in subtype table *) let chk_sub errname table c = if List.mem c table then () else raise (Invalid_argument errname)
null
https://raw.githubusercontent.com/qkrgud55/ocamlmulti/74fe84df0ce7be5ee03fb4ac0520fb3e9f4b6d1f/otherlibs/labltk/support/rawwidget.ml
ocaml
********************************************************************* described in file LICENSE found in the OCaml source tree. ********************************************************************* * Widgets Raised when widget command applied illegally ************************************************* Widgets This 'a raw_widget will be 'a Widget.widget ************************************************* will be Widget.any table of widgets Normally all widgets are known this is a provision for send commands to external tk processes This one is always created by opentk Dummy widget to which global callbacks are associated also passed around by camltotkoption when no widget in context subtypes The function called by generic creation Just create a path. Only to check existence of widgets Use with care LablTk: Redundant with subtyping of Widget, backward compatibility assume run-time check by tk Checking membership of constructor in subtype table
MLTk , Tcl / Tk interface of OCaml , , and projet Cristal , INRIA Rocquencourt , Kyoto University RIMS Copyright 2002 Institut National de Recherche en Informatique et en Automatique and Kyoto University . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with the special exception on linking $ I d : rawwidget.ml 11156 2011 - 07 - 27 14:17:02Z doligez $ open Support exception IllegalWidgetType of string type 'a raw_widget = Untyped of string | Typed of string * string and button and canvas and checkbutton and entry and frame and label and listbox and menu and menubutton and message and radiobutton and scale and scrollbar and text and toplevel let forget_type w = (Obj.magic (w : 'a raw_widget) : raw_any raw_widget) let coe = forget_type let table = (Hashtbl.create 401 : (string, raw_any raw_widget) Hashtbl.t) let name = function Untyped s -> s | Typed (s,_) -> s let known_class = function Untyped _ -> "unknown" | Typed (_,c) -> c let default_toplevel = let wname = "." in let w = Typed (wname, "toplevel") in Hashtbl.add table wname w; w let dummy = Untyped "dummy" let remove w = Hashtbl.remove table (name w) Retype widgets returned from Tk JPF report : sometime s is " " , see Protocol.cTKtoCAMLwidget let get_atom s = try Hashtbl.find table s with Not_found -> Untyped s let naming_scheme = [ "button", "b"; "canvas", "ca"; "checkbutton", "cb"; "entry", "en"; "frame", "f"; "label", "l"; "listbox", "li"; "menu", "me"; "menubutton", "mb"; "message", "ms"; "radiobutton", "rb"; "scale", "sc"; "scrollbar", "sb"; "text", "t"; "toplevel", "top" ] let widget_any_table = List.map fst naming_scheme let widget_button_table = [ "button" ] and widget_canvas_table = [ "canvas" ] and widget_checkbutton_table = [ "checkbutton" ] and widget_entry_table = [ "entry" ] and widget_frame_table = [ "frame" ] and widget_label_table = [ "label" ] and widget_listbox_table = [ "listbox" ] and widget_menu_table = [ "menu" ] and widget_menubutton_table = [ "menubutton" ] and widget_message_table = [ "message" ] and widget_radiobutton_table = [ "radiobutton" ] and widget_scale_table = [ "scale" ] and widget_scrollbar_table = [ "scrollbar" ] and widget_text_table = [ "text" ] and widget_toplevel_table = [ "toplevel" ] let new_suffix clas n = try (List.assoc clas naming_scheme) ^ (string_of_int n) with Not_found -> "w" ^ (string_of_int n) let counter = ref 0 let new_atom ~parent ?name:nom clas = let parentpath = name parent in let path = match nom with None -> incr counter; if parentpath = "." then "." ^ (new_suffix clas !counter) else parentpath ^ "." ^ (new_suffix clas !counter) | Some name -> if parentpath = "." then "." ^ name else parentpath ^ "." ^ name in let w = Typed(path,clas) in Hashtbl.add table path w; w let atom ~parent ~name:pathcomp = let parentpath = name parent in let path = if parentpath = "." then "." ^ pathcomp else parentpath ^ "." ^ pathcomp in Untyped path let check_class w clas = match w with | Typed(_,c) -> if List.mem c clas then () else raise (IllegalWidgetType c) let chk_sub errname table c = if List.mem c table then () else raise (Invalid_argument errname)
1487b6362aebecd95428925027831c6c5dd64aa4312a3a068400572947f2ca5c
tek/polysemy-hasql
ExistingColumn.hs
module Polysemy.Hasql.Data.ExistingColumn where import Polysemy.Hasql.Data.DbType (Name) data ExistingColumn = ExistingColumn { name :: Name, ctype :: Text } deriving stock (Eq, Show, Ord)
null
https://raw.githubusercontent.com/tek/polysemy-hasql/443ccf348bb8af0ec0543981d58af8aa26fc4c10/packages/hasql/lib/Polysemy/Hasql/Data/ExistingColumn.hs
haskell
module Polysemy.Hasql.Data.ExistingColumn where import Polysemy.Hasql.Data.DbType (Name) data ExistingColumn = ExistingColumn { name :: Name, ctype :: Text } deriving stock (Eq, Show, Ord)
7868074f5d7220ebaa0a7ceef78661c8c67763ce3fceec57010d0c98f568fdac
brendanhay/terrafomo
Provider.hs
-- This module is auto-generated. # LANGUAGE NoImplicitPrelude # # LANGUAGE RecordWildCards # # LANGUAGE StrictData # # OPTIONS_GHC -fno - warn - unused - imports # -- | Module : . NewRelic . Provider Copyright : ( c ) 2017 - 2018 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) -- module Terrafomo.NewRelic.Provider ( -- * NewRelic Specific Aliases Provider , DataSource , Resource -- * NewRelic Configuration , currentVersion , newProvider , NewRelic (..) , NewRelic_Required (..) ) where import Data.Function ((&)) import Data.Functor ((<$>)) import Data.Semigroup ((<>)) import Data.Version (Version, makeVersion, showVersion) import GHC.Base (($)) import Terrafomo.NewRelic.Settings import qualified Data.Functor.Const as P import qualified Data.List.NonEmpty as P import qualified Data.Map.Strict as P import qualified Data.Maybe as P import qualified Data.Text.Lazy as P import qualified Prelude as P import qualified Terrafomo.HCL as TF import qualified Terrafomo.Lens as Lens import qualified Terrafomo.NewRelic.Types as P import qualified Terrafomo.Schema as TF type Provider = TF.Provider NewRelic type DataSource = TF.Resource NewRelic TF.Ignored type Resource = TF.Resource NewRelic TF.Meta type instance TF.ProviderName NewRelic = "newrelic" currentVersion :: Version currentVersion = makeVersion [1, 0, 1] | The @newrelic@ Terraform provider configuration . data NewRelic = NewRelic_Internal { api_key :: P.Text -- ^ @api_key@ -- - (Required) , api_url :: P.Maybe P.Text ^ -- - (Optional) , infra_api_url :: P.Maybe P.Text -- ^ @infra_api_url@ -- - (Optional) } deriving (P.Show) | Specify a new NewRelic provider configuration . See the < terraform documentation > for more information . See the < terraform documentation> for more information. -} newProvider :: NewRelic_Required -- ^ The minimal/required arguments. -> Provider newProvider x = TF.Provider { TF.providerVersion = P.Just ("~> " P.++ showVersion currentVersion) , TF.providerConfig = (let NewRelic{..} = x in NewRelic_Internal { api_key = api_key , api_url = P.Nothing , infra_api_url = P.Nothing }) , TF.providerEncoder = (\NewRelic_Internal{..} -> P.mempty <> TF.pair "api_key" api_key <> P.maybe P.mempty (TF.pair "api_url") api_url <> P.maybe P.mempty (TF.pair "infra_api_url") infra_api_url ) } -- | The required arguments for 'newProvider'. data NewRelic_Required = NewRelic { api_key :: P.Text -- ^ (Required) } deriving (P.Show) instance Lens.HasField "api_key" f Provider (P.Text) where field = Lens.providerLens P.. Lens.lens' (api_key :: NewRelic -> P.Text) (\s a -> s { api_key = a } :: NewRelic) instance Lens.HasField "api_url" f Provider (P.Maybe P.Text) where field = Lens.providerLens P.. Lens.lens' (api_url :: NewRelic -> P.Maybe P.Text) (\s a -> s { api_url = a } :: NewRelic) instance Lens.HasField "infra_api_url" f Provider (P.Maybe P.Text) where field = Lens.providerLens P.. Lens.lens' (infra_api_url :: NewRelic -> P.Maybe P.Text) (\s a -> s { infra_api_url = a } :: NewRelic)
null
https://raw.githubusercontent.com/brendanhay/terrafomo/387a0e9341fb9cd5543ef8332dea126f50f1070e/provider/terrafomo-newrelic/gen/Terrafomo/NewRelic/Provider.hs
haskell
This module is auto-generated. | Stability : auto-generated * NewRelic Specific Aliases * NewRelic Configuration ^ @api_key@ - (Required) - (Optional) ^ @infra_api_url@ - (Optional) ^ The minimal/required arguments. | The required arguments for 'newProvider'. ^ (Required)
# LANGUAGE NoImplicitPrelude # # LANGUAGE RecordWildCards # # LANGUAGE StrictData # # OPTIONS_GHC -fno - warn - unused - imports # Module : . NewRelic . Provider Copyright : ( c ) 2017 - 2018 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Terrafomo.NewRelic.Provider ( Provider , DataSource , Resource , currentVersion , newProvider , NewRelic (..) , NewRelic_Required (..) ) where import Data.Function ((&)) import Data.Functor ((<$>)) import Data.Semigroup ((<>)) import Data.Version (Version, makeVersion, showVersion) import GHC.Base (($)) import Terrafomo.NewRelic.Settings import qualified Data.Functor.Const as P import qualified Data.List.NonEmpty as P import qualified Data.Map.Strict as P import qualified Data.Maybe as P import qualified Data.Text.Lazy as P import qualified Prelude as P import qualified Terrafomo.HCL as TF import qualified Terrafomo.Lens as Lens import qualified Terrafomo.NewRelic.Types as P import qualified Terrafomo.Schema as TF type Provider = TF.Provider NewRelic type DataSource = TF.Resource NewRelic TF.Ignored type Resource = TF.Resource NewRelic TF.Meta type instance TF.ProviderName NewRelic = "newrelic" currentVersion :: Version currentVersion = makeVersion [1, 0, 1] | The @newrelic@ Terraform provider configuration . data NewRelic = NewRelic_Internal { api_key :: P.Text , api_url :: P.Maybe P.Text ^ , infra_api_url :: P.Maybe P.Text } deriving (P.Show) | Specify a new NewRelic provider configuration . See the < terraform documentation > for more information . See the < terraform documentation> for more information. -} newProvider -> Provider newProvider x = TF.Provider { TF.providerVersion = P.Just ("~> " P.++ showVersion currentVersion) , TF.providerConfig = (let NewRelic{..} = x in NewRelic_Internal { api_key = api_key , api_url = P.Nothing , infra_api_url = P.Nothing }) , TF.providerEncoder = (\NewRelic_Internal{..} -> P.mempty <> TF.pair "api_key" api_key <> P.maybe P.mempty (TF.pair "api_url") api_url <> P.maybe P.mempty (TF.pair "infra_api_url") infra_api_url ) } data NewRelic_Required = NewRelic { api_key :: P.Text } deriving (P.Show) instance Lens.HasField "api_key" f Provider (P.Text) where field = Lens.providerLens P.. Lens.lens' (api_key :: NewRelic -> P.Text) (\s a -> s { api_key = a } :: NewRelic) instance Lens.HasField "api_url" f Provider (P.Maybe P.Text) where field = Lens.providerLens P.. Lens.lens' (api_url :: NewRelic -> P.Maybe P.Text) (\s a -> s { api_url = a } :: NewRelic) instance Lens.HasField "infra_api_url" f Provider (P.Maybe P.Text) where field = Lens.providerLens P.. Lens.lens' (infra_api_url :: NewRelic -> P.Maybe P.Text) (\s a -> s { infra_api_url = a } :: NewRelic)
1dcc694d91c2169aafd469b19a414c02bb726c6b987c96cb4bc8bc8ad34b6672
zippy/anansi
commands.clj
(ns anansi.test.receptor.host-interface.commands (:use [anansi.receptor.host-interface.commands] :reload) (:use [anansi.ceptr]) (:use [anansi.receptor.host] [anansi.receptor.scape]) (:use [midje.sweet]) (:use [clojure.test] [clojure.contrib.io :only [writer]])) (def some-interface-def (receptor-def "some-interface")) (deftest commands (let [h (make-receptor host-def nil {}) i (make-receptor some-interface-def h {})] (binding [*err* (java.io.PrintWriter. (writer "/dev/null"))] (testing "execute" (is (= {:status :error :result "authentication failed for user: eric"} (execute h i "authenticate" {:user "eric"})) ))) (testing "authenticate" (is (thrown-with-msg? RuntimeException #"authentication failed for user: eric" (authenticate h i {:user "eric"})))) (let [n-addr (new-user h i {:user "eric"})] (testing "new-user" (is (= n-addr (resolve-name h "eric")))) (testing "send" (let [{session :session creator :creator} (authenticate h i {:user "eric"})] (fact creator => []) (is (re-find #"^[0-9a-f]+$" session)) (let [new-user-addr (send-signal h i {:signal "host-user" :aspect "self" :prefix "receptor.host" :session session :to 0 :params "boink"})] (fact new-user-addr => (resolve-name h "boink")) (testing "get-state" (is (= {:name "eric", :fingerprint :anansi.receptor.user.user, :address n-addr, :changes 0} (get-state h i {:receptor n-addr}))) ) (fact (authenticate h i {:user "eric"}) => (contains {:creator [new-user-addr]}))) )) )) )
null
https://raw.githubusercontent.com/zippy/anansi/881aa279e5e7836f3002fc2ef7623f2ee1860c9a/test/anansi/test/receptor/host_interface/commands.clj
clojure
(ns anansi.test.receptor.host-interface.commands (:use [anansi.receptor.host-interface.commands] :reload) (:use [anansi.ceptr]) (:use [anansi.receptor.host] [anansi.receptor.scape]) (:use [midje.sweet]) (:use [clojure.test] [clojure.contrib.io :only [writer]])) (def some-interface-def (receptor-def "some-interface")) (deftest commands (let [h (make-receptor host-def nil {}) i (make-receptor some-interface-def h {})] (binding [*err* (java.io.PrintWriter. (writer "/dev/null"))] (testing "execute" (is (= {:status :error :result "authentication failed for user: eric"} (execute h i "authenticate" {:user "eric"})) ))) (testing "authenticate" (is (thrown-with-msg? RuntimeException #"authentication failed for user: eric" (authenticate h i {:user "eric"})))) (let [n-addr (new-user h i {:user "eric"})] (testing "new-user" (is (= n-addr (resolve-name h "eric")))) (testing "send" (let [{session :session creator :creator} (authenticate h i {:user "eric"})] (fact creator => []) (is (re-find #"^[0-9a-f]+$" session)) (let [new-user-addr (send-signal h i {:signal "host-user" :aspect "self" :prefix "receptor.host" :session session :to 0 :params "boink"})] (fact new-user-addr => (resolve-name h "boink")) (testing "get-state" (is (= {:name "eric", :fingerprint :anansi.receptor.user.user, :address n-addr, :changes 0} (get-state h i {:receptor n-addr}))) ) (fact (authenticate h i {:user "eric"}) => (contains {:creator [new-user-addr]}))) )) )) )
190e40bf67623c5be0e71df4c97ab3dd3a88ada474febc1c53d69ee308cda1d1
polyfy/polylith
m201_mismatching_parameters_test.clj
(ns polylith.clj.core.validator.m201-mismatching-parameters-test (:require [clojure.test :refer :all] [polylith.clj.core.util.interface.color :as color] [polylith.clj.core.validator.m201-mismatching-parameters :as m201])) (def interfaces [{:name "auth" :definitions [{:name "add-two", :type "function", :parameters [{:name "x"}]}] :implementing-components ["auth"]} {:name "invoice" :type "interface" :definitions [{:name "abc" :type "data"} {:name "func1", :type "function", :parameters [{:name "a"}]} {:name "func1", :type "function", :parameters [{:name "b"}]} {:name "func1", :type "function", :parameters [{:name "a"} {:name "b"}]} {:name "func1", :type "function", :parameters [{:name "x"} {:name "y"}]}] :implementing-components ["invoice" "invoice2"]} {:name "payment" :definitions [{:name "pay", :type "function", :parameters [{:name "a"}]} {:name "pay", :type "function", :parameters [{:name "b"}]}] :implementing-components ["payment"]} {:name "user" :type "interface" :definitions [{:name "func1", :type "function", :parameters []} {:name "func2", :type "function", :parameters [{:name "a"} {:name "b"}]} {:name "func2", :type "function", :parameters [{:name "x"} {:name "y"}]} {:name "func3", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"}]} {:name "func3", :type "function", :parameters [{:name "x"} {:name "y"} {:name "z"}]} {:name "func4", :type "function", :parameters []} {:name "func5", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"} {:name "d"}]}] :implementing-components ["user1" "user2"]}]) (def components [{:name "auth" :type "component" :namespaces {:src [{:name "auth/interface.clj", :imports ["auth.core"]} {:name "auth/core.clj", :imports []}]} :interface {:name "auth", :definitions [{:name "add-two", :type "function", :parameters [{:name "x"}]}]} :interface-deps {}} {:name "invoice" :type "component" :namespaces {:src [{:name "invoice/interface.clj", :imports []} {:name "invoice/core.clj", :imports ["user.interface"]}]} :interface {:name "invoice" :definitions [{:name "abc" :type "data"} {:name "func1", :type "function", :parameters [{:name "a"}]} {:name "func1", :type "function", :parameters [{:name "a"} {:name "b"}]}]} :interface-deps {:src ["user"]}} {:name "invoice2" :type "component" :namespaces {:src [{:name "invoice/interface.clj", :imports []} {:name "invoice/core.clj", :imports []}]} :interface {:name "invoice" :definitions [{:name "func1", :type "function", :parameters [{:name "b"}]} {:name "func1", :type "function", :parameters [{:name "x"} {:name "y"}]}]} :interface-deps {}} {:name "payment" :type "component" :namespaces {:src [{:name "payment/interface.clj", :imports ["payment.core"]} {:name "payment/core.clj", :imports ["invoice.interface"]}]} :interface {:name "payment" :definitions [{:name "pay", :type "function", :parameters [{:name "a"}]} {:name "pay", :type "function", :parameters [{:name "b"}]}]} :interface-deps {:src ["invoice"]}} {:name "user1" :type "component" :namespaces {:src [{:name "user/interface.clj", :imports []} {:name "user/core.clj", :imports ["payment.interface"]}]} :interface {:name "user" :definitions [{:name "func1", :type "function", :parameters []} {:name "func2", :type "function", :parameters [{:name "a"} {:name "b"}]} {:name "func3", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"}]} {:name "func4", :type "function2", :parameters []} {:name "func5", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"} {:name "d"}]}]} :interface-deps {:src ["payment"]}} {:name "user2" :type "component" :namespaces {:src [{:name "user/interface.clj", :imports []} {:name "user/core.clj", :imports ["auth.interface"]}]} :interface {:name "user" :definitions [{:name "func2", :type "function", :parameters [{:name "x"} {:name "y"}]} {:name "func3", :type "function", :parameters [{:name "x"} {:name "y"} {:name "z"}]} {:name "func5", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"} {:name "d"}]}]} :interface-deps {:src ["auth"]}}]) (def interfaces2 [{:name "auth", :definitions [{:name "add-two", :type "function", :parameters [{:name "x"}]}] :implementing-components ["auth"]} {:name "invoice", :type "interface" :definitions [{:name "abc" :type "data"} {:name "macro1", :type "macro", :parameters [{:name "a"}]} {:name "macro1", :type "macro", :parameters [{:name "b"}]} {:name "func1", :type "function", :parameters [{:name "a"} {:name "b"}]} {:name "func1", :type "function", :parameters [{:name "x"} {:name "y"}]}] :implementing-components ["invoice" "invoice2"]} {:name "payment" :definitions [{:name "pay", :type "function", :parameters [{:name "a"}]} {:name "pay", :type "function", :parameters [{:name "b"}]}] :implementing-components ["payment"]} {:name "user" :type "interface" :definitions [{:name "func1", :type "function", :parameters []} {:name "func2", :type "function", :parameters [{:name "a"} {:name "b"}]} {:name "func2", :type "function", :parameters [{:name "x"} {:name "y"}]} {:name "func3", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"}]} {:name "func3", :type "function", :parameters [{:name "x"} {:name "y"} {:name "z"}]} {:name "func4", :type "function", :parameters []} {:name "func5", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"} {:name "d"}]}] :implementing-components ["user1" "user2"]}]) (def components2 [{:name "auth" :type "component" :namespaces {:src [{:name "auth/interface.clj", :imports ["auth.core"]} {:name "auth/core.clj", :imports []}]} :interface {:name "auth" :definitions [{:name "add-two", :type "function", :parameters [{:name "x"}]}]} :interface-deps {}} {:name "invoice" :type "component" :namespaces {:src [{:name "invoice/interface.clj", :imports []} {:name "invoice/core.clj", :imports ["user.interface"]}]} :interface {:name "invoice" :definitions [{:name "abc" :type "data"} {:name "macro1", :type "macro", :parameters [{:name "a"}] :sub-ns "sub"} {:name "func1", :type "function", :parameters [{:name "a"} {:name "b"}]}]} :interface-deps {:src ["user"]}} {:name "invoice2" :type "component" :namespaces {:src [{:name "invoice/interface.clj", :imports []} {:name "invoice/core.clj", :imports []}]} :interface {:name "invoice" :definitions [{:name "macro1", :type "macro", :parameters [{:name "b"}] :sub-ns "sub"} {:name "func1", :type "function", :parameters [{:name "x"} {:name "y"}]}]} :interface-deps {}} {:name "payment", :type "component" :namespaces {:src [{:name "payment/interface.clj", :imports ["payment.core"]} {:name "payment/core.clj", :imports ["invoice.interface"]}]} :interface {:name "payment" :definitions [{:name "pay", :type "function", :parameters [{:name "a"}]} {:name "pay", :type "function", :parameters [{:name "b"}]}]} :interface-deps {:src ["invoice"]}} {:name "user1" :type "component" :namespaces {:src [{:name "user/interface.clj", :imports []} {:name "user/core.clj", :imports ["payment.interface"]}]} :interface {:name "user" :definitions [{:name "macro1", :type "macro", :parameters []} {:name "func2", :type "function", :parameters [{:name "a"} {:name "b"}]} {:name "func3", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"}]} {:name "func4", :type "function", :parameters []} {:name "func5", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"} {:name "d"}]}]} :interface-deps {:src ["payment"]}} {:name "user2" :type "component" :namespaces {:src [{:name "user/interface.clj", :imports []} {:name "user/core.clj", :imports ["auth.interface"]}]} :interface {:name "user" :definitions [{:name "func2", :type "function", :parameters [{:name "x"} {:name "y"}]} {:name "func3", :type "function", :parameters [{:name "x"} {:name "y"} {:name "z"}]} {:name "func5", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"} {:name "d"}]}]} :interface-deps {:src ["auth"]}}]) (def interfaces3 [{:name "auth", :definitions [{:name "hello", :type "function", :parameters [{:name "x"}]}] :implementing-components ["auth1" "auth2"]}]) (def components3 [{:name "auth1" :type "component" :interface {:name "auth" :definitions [{:name "hello", :type "function", :parameters [{:name "x"}]}]} :interface-deps {}} {:name "auth2" :type "component" :interface {:name "auth" :definitions [{:name "hello", :type "function", :parameters [{:name "x", :type "^String"}]}]} :interface-deps {}}]) (deftest warnings--when-having-functions-with-the-same-arity-but-with-different-parameter-lists--return-warnings (is (= [{:type "warning" :code 201 :colorized-message "Function in the invoice component is also defined in invoice2 but with a different parameter list: func1[a b], func1[x y]" :message "Function in the invoice component is also defined in invoice2 but with a different parameter list: func1[a b], func1[x y]" :components ["invoice" "invoice2"]} {:type "warning" :code 201 :colorized-message "Function in the invoice component is also defined in invoice2 but with a different parameter list: func1[a], func1[b]" :message "Function in the invoice component is also defined in invoice2 but with a different parameter list: func1[a], func1[b]" :components ["invoice" "invoice2"]} {:type "warning" :code 201 :colorized-message "Function in the user1 component is also defined in user2 but with a different parameter list: func2[a b], func2[x y]" :message "Function in the user1 component is also defined in user2 but with a different parameter list: func2[a b], func2[x y]" :components ["user1" "user2"]} {:type "warning" :code 201 :colorized-message "Function in the user1 component is also defined in user2 but with a different parameter list: func3[a b c], func3[x y z]" :message "Function in the user1 component is also defined in user2 but with a different parameter list: func3[a b c], func3[x y z]" :components ["user1" "user2"]}] (sort-by :message (m201/warnings interfaces components color/none))))) (deftest warnings--when-having-macros-with-the-same-arity-but-with-different-parameter-lists--return-warnings (is (= [{:type "warning" :code 201 :colorized-message "Function in the invoice component is also defined in invoice2 but with a different parameter list: func1[a b], func1[x y]" :message "Function in the invoice component is also defined in invoice2 but with a different parameter list: func1[a b], func1[x y]" :components ["invoice" "invoice2"]} {:type "warning" :code 201 :colorized-message "Function in the user1 component is also defined in user2 but with a different parameter list: func2[a b], func2[x y]" :message "Function in the user1 component is also defined in user2 but with a different parameter list: func2[a b], func2[x y]" :components ["user1" "user2"]} {:type "warning" :code 201 :colorized-message "Function in the user1 component is also defined in user2 but with a different parameter list: func3[a b c], func3[x y z]" :message "Function in the user1 component is also defined in user2 but with a different parameter list: func3[a b c], func3[x y z]" :components ["user1" "user2"]} {:type "warning" :code 201 :colorized-message "Macro in the invoice component is also defined in invoice2 but with a different parameter list: sub.macro1[a], sub.macro1[b]" :message "Macro in the invoice component is also defined in invoice2 but with a different parameter list: sub.macro1[a], sub.macro1[b]" :components ["invoice" "invoice2"]}] (sort-by :message (m201/warnings interfaces2 components2 color/none))))) (deftest warnings--when-having-functions-with-the-same-arity-but-with-a-type-hint-in-only-one-of-the-parameter-lists--return-warning (is (= [{:type "warning" :code 201 :colorized-message "Function in the auth1 component is also defined in auth2 but with a different parameter list: hello[^String x], hello[x]" :message "Function in the auth1 component is also defined in auth2 but with a different parameter list: hello[^String x], hello[x]" :components ["auth1" "auth2"]}] (sort-by :message (m201/warnings interfaces3 components3 color/none)))))
null
https://raw.githubusercontent.com/polyfy/polylith/febea3d8a9b30a60397594dda3cb0f25154b8d8d/components/validator/test/polylith/clj/core/validator/m201_mismatching_parameters_test.clj
clojure
(ns polylith.clj.core.validator.m201-mismatching-parameters-test (:require [clojure.test :refer :all] [polylith.clj.core.util.interface.color :as color] [polylith.clj.core.validator.m201-mismatching-parameters :as m201])) (def interfaces [{:name "auth" :definitions [{:name "add-two", :type "function", :parameters [{:name "x"}]}] :implementing-components ["auth"]} {:name "invoice" :type "interface" :definitions [{:name "abc" :type "data"} {:name "func1", :type "function", :parameters [{:name "a"}]} {:name "func1", :type "function", :parameters [{:name "b"}]} {:name "func1", :type "function", :parameters [{:name "a"} {:name "b"}]} {:name "func1", :type "function", :parameters [{:name "x"} {:name "y"}]}] :implementing-components ["invoice" "invoice2"]} {:name "payment" :definitions [{:name "pay", :type "function", :parameters [{:name "a"}]} {:name "pay", :type "function", :parameters [{:name "b"}]}] :implementing-components ["payment"]} {:name "user" :type "interface" :definitions [{:name "func1", :type "function", :parameters []} {:name "func2", :type "function", :parameters [{:name "a"} {:name "b"}]} {:name "func2", :type "function", :parameters [{:name "x"} {:name "y"}]} {:name "func3", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"}]} {:name "func3", :type "function", :parameters [{:name "x"} {:name "y"} {:name "z"}]} {:name "func4", :type "function", :parameters []} {:name "func5", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"} {:name "d"}]}] :implementing-components ["user1" "user2"]}]) (def components [{:name "auth" :type "component" :namespaces {:src [{:name "auth/interface.clj", :imports ["auth.core"]} {:name "auth/core.clj", :imports []}]} :interface {:name "auth", :definitions [{:name "add-two", :type "function", :parameters [{:name "x"}]}]} :interface-deps {}} {:name "invoice" :type "component" :namespaces {:src [{:name "invoice/interface.clj", :imports []} {:name "invoice/core.clj", :imports ["user.interface"]}]} :interface {:name "invoice" :definitions [{:name "abc" :type "data"} {:name "func1", :type "function", :parameters [{:name "a"}]} {:name "func1", :type "function", :parameters [{:name "a"} {:name "b"}]}]} :interface-deps {:src ["user"]}} {:name "invoice2" :type "component" :namespaces {:src [{:name "invoice/interface.clj", :imports []} {:name "invoice/core.clj", :imports []}]} :interface {:name "invoice" :definitions [{:name "func1", :type "function", :parameters [{:name "b"}]} {:name "func1", :type "function", :parameters [{:name "x"} {:name "y"}]}]} :interface-deps {}} {:name "payment" :type "component" :namespaces {:src [{:name "payment/interface.clj", :imports ["payment.core"]} {:name "payment/core.clj", :imports ["invoice.interface"]}]} :interface {:name "payment" :definitions [{:name "pay", :type "function", :parameters [{:name "a"}]} {:name "pay", :type "function", :parameters [{:name "b"}]}]} :interface-deps {:src ["invoice"]}} {:name "user1" :type "component" :namespaces {:src [{:name "user/interface.clj", :imports []} {:name "user/core.clj", :imports ["payment.interface"]}]} :interface {:name "user" :definitions [{:name "func1", :type "function", :parameters []} {:name "func2", :type "function", :parameters [{:name "a"} {:name "b"}]} {:name "func3", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"}]} {:name "func4", :type "function2", :parameters []} {:name "func5", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"} {:name "d"}]}]} :interface-deps {:src ["payment"]}} {:name "user2" :type "component" :namespaces {:src [{:name "user/interface.clj", :imports []} {:name "user/core.clj", :imports ["auth.interface"]}]} :interface {:name "user" :definitions [{:name "func2", :type "function", :parameters [{:name "x"} {:name "y"}]} {:name "func3", :type "function", :parameters [{:name "x"} {:name "y"} {:name "z"}]} {:name "func5", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"} {:name "d"}]}]} :interface-deps {:src ["auth"]}}]) (def interfaces2 [{:name "auth", :definitions [{:name "add-two", :type "function", :parameters [{:name "x"}]}] :implementing-components ["auth"]} {:name "invoice", :type "interface" :definitions [{:name "abc" :type "data"} {:name "macro1", :type "macro", :parameters [{:name "a"}]} {:name "macro1", :type "macro", :parameters [{:name "b"}]} {:name "func1", :type "function", :parameters [{:name "a"} {:name "b"}]} {:name "func1", :type "function", :parameters [{:name "x"} {:name "y"}]}] :implementing-components ["invoice" "invoice2"]} {:name "payment" :definitions [{:name "pay", :type "function", :parameters [{:name "a"}]} {:name "pay", :type "function", :parameters [{:name "b"}]}] :implementing-components ["payment"]} {:name "user" :type "interface" :definitions [{:name "func1", :type "function", :parameters []} {:name "func2", :type "function", :parameters [{:name "a"} {:name "b"}]} {:name "func2", :type "function", :parameters [{:name "x"} {:name "y"}]} {:name "func3", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"}]} {:name "func3", :type "function", :parameters [{:name "x"} {:name "y"} {:name "z"}]} {:name "func4", :type "function", :parameters []} {:name "func5", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"} {:name "d"}]}] :implementing-components ["user1" "user2"]}]) (def components2 [{:name "auth" :type "component" :namespaces {:src [{:name "auth/interface.clj", :imports ["auth.core"]} {:name "auth/core.clj", :imports []}]} :interface {:name "auth" :definitions [{:name "add-two", :type "function", :parameters [{:name "x"}]}]} :interface-deps {}} {:name "invoice" :type "component" :namespaces {:src [{:name "invoice/interface.clj", :imports []} {:name "invoice/core.clj", :imports ["user.interface"]}]} :interface {:name "invoice" :definitions [{:name "abc" :type "data"} {:name "macro1", :type "macro", :parameters [{:name "a"}] :sub-ns "sub"} {:name "func1", :type "function", :parameters [{:name "a"} {:name "b"}]}]} :interface-deps {:src ["user"]}} {:name "invoice2" :type "component" :namespaces {:src [{:name "invoice/interface.clj", :imports []} {:name "invoice/core.clj", :imports []}]} :interface {:name "invoice" :definitions [{:name "macro1", :type "macro", :parameters [{:name "b"}] :sub-ns "sub"} {:name "func1", :type "function", :parameters [{:name "x"} {:name "y"}]}]} :interface-deps {}} {:name "payment", :type "component" :namespaces {:src [{:name "payment/interface.clj", :imports ["payment.core"]} {:name "payment/core.clj", :imports ["invoice.interface"]}]} :interface {:name "payment" :definitions [{:name "pay", :type "function", :parameters [{:name "a"}]} {:name "pay", :type "function", :parameters [{:name "b"}]}]} :interface-deps {:src ["invoice"]}} {:name "user1" :type "component" :namespaces {:src [{:name "user/interface.clj", :imports []} {:name "user/core.clj", :imports ["payment.interface"]}]} :interface {:name "user" :definitions [{:name "macro1", :type "macro", :parameters []} {:name "func2", :type "function", :parameters [{:name "a"} {:name "b"}]} {:name "func3", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"}]} {:name "func4", :type "function", :parameters []} {:name "func5", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"} {:name "d"}]}]} :interface-deps {:src ["payment"]}} {:name "user2" :type "component" :namespaces {:src [{:name "user/interface.clj", :imports []} {:name "user/core.clj", :imports ["auth.interface"]}]} :interface {:name "user" :definitions [{:name "func2", :type "function", :parameters [{:name "x"} {:name "y"}]} {:name "func3", :type "function", :parameters [{:name "x"} {:name "y"} {:name "z"}]} {:name "func5", :type "function", :parameters [{:name "a"} {:name "b"} {:name "c"} {:name "d"}]}]} :interface-deps {:src ["auth"]}}]) (def interfaces3 [{:name "auth", :definitions [{:name "hello", :type "function", :parameters [{:name "x"}]}] :implementing-components ["auth1" "auth2"]}]) (def components3 [{:name "auth1" :type "component" :interface {:name "auth" :definitions [{:name "hello", :type "function", :parameters [{:name "x"}]}]} :interface-deps {}} {:name "auth2" :type "component" :interface {:name "auth" :definitions [{:name "hello", :type "function", :parameters [{:name "x", :type "^String"}]}]} :interface-deps {}}]) (deftest warnings--when-having-functions-with-the-same-arity-but-with-different-parameter-lists--return-warnings (is (= [{:type "warning" :code 201 :colorized-message "Function in the invoice component is also defined in invoice2 but with a different parameter list: func1[a b], func1[x y]" :message "Function in the invoice component is also defined in invoice2 but with a different parameter list: func1[a b], func1[x y]" :components ["invoice" "invoice2"]} {:type "warning" :code 201 :colorized-message "Function in the invoice component is also defined in invoice2 but with a different parameter list: func1[a], func1[b]" :message "Function in the invoice component is also defined in invoice2 but with a different parameter list: func1[a], func1[b]" :components ["invoice" "invoice2"]} {:type "warning" :code 201 :colorized-message "Function in the user1 component is also defined in user2 but with a different parameter list: func2[a b], func2[x y]" :message "Function in the user1 component is also defined in user2 but with a different parameter list: func2[a b], func2[x y]" :components ["user1" "user2"]} {:type "warning" :code 201 :colorized-message "Function in the user1 component is also defined in user2 but with a different parameter list: func3[a b c], func3[x y z]" :message "Function in the user1 component is also defined in user2 but with a different parameter list: func3[a b c], func3[x y z]" :components ["user1" "user2"]}] (sort-by :message (m201/warnings interfaces components color/none))))) (deftest warnings--when-having-macros-with-the-same-arity-but-with-different-parameter-lists--return-warnings (is (= [{:type "warning" :code 201 :colorized-message "Function in the invoice component is also defined in invoice2 but with a different parameter list: func1[a b], func1[x y]" :message "Function in the invoice component is also defined in invoice2 but with a different parameter list: func1[a b], func1[x y]" :components ["invoice" "invoice2"]} {:type "warning" :code 201 :colorized-message "Function in the user1 component is also defined in user2 but with a different parameter list: func2[a b], func2[x y]" :message "Function in the user1 component is also defined in user2 but with a different parameter list: func2[a b], func2[x y]" :components ["user1" "user2"]} {:type "warning" :code 201 :colorized-message "Function in the user1 component is also defined in user2 but with a different parameter list: func3[a b c], func3[x y z]" :message "Function in the user1 component is also defined in user2 but with a different parameter list: func3[a b c], func3[x y z]" :components ["user1" "user2"]} {:type "warning" :code 201 :colorized-message "Macro in the invoice component is also defined in invoice2 but with a different parameter list: sub.macro1[a], sub.macro1[b]" :message "Macro in the invoice component is also defined in invoice2 but with a different parameter list: sub.macro1[a], sub.macro1[b]" :components ["invoice" "invoice2"]}] (sort-by :message (m201/warnings interfaces2 components2 color/none))))) (deftest warnings--when-having-functions-with-the-same-arity-but-with-a-type-hint-in-only-one-of-the-parameter-lists--return-warning (is (= [{:type "warning" :code 201 :colorized-message "Function in the auth1 component is also defined in auth2 but with a different parameter list: hello[^String x], hello[x]" :message "Function in the auth1 component is also defined in auth2 but with a different parameter list: hello[^String x], hello[x]" :components ["auth1" "auth2"]}] (sort-by :message (m201/warnings interfaces3 components3 color/none)))))
80926029fb4c39c43d02db6c32d7fd6f54dedea4f2b0f3876603b43fd3bbfdda
lspitzner/brittany
Test509.hs
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft } func = [ (thing, take 10 alts) --TODO: select best ones | (thing, _got, alts@(_ : _)) <- nosuchFooThing , gast <- award ]
null
https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test509.hs
haskell
brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft } TODO: select best ones
func = | (thing, _got, alts@(_ : _)) <- nosuchFooThing , gast <- award ]
c74c9374610bd1fa5cd9012bc8012a11f23daecf867967c00daadc0a9d3d62dd
sneeuwballen/zipperposition
Ind_cst.ml
* { 1 Inductive Constants and Cases } Skolem constants of an inductive type , coversets , etc . required for inductive reasoning . Skolem constants of an inductive type, coversets, etc. required for inductive reasoning. *) open Logtk module T = Term exception InvalidDecl of string exception NotAnInductiveConstant of ID.t let () = let spf = CCFormat.sprintf in Printexc.register_printer (function | InvalidDecl msg -> Some (spf "@[<2>invalid declaration:@ %s@]" msg) | NotAnInductiveConstant id -> Some (spf "%a is not an inductive constant" ID.pp id) | _ -> None) let invalid_decl m = raise (InvalidDecl m) let invalid_declf m = CCFormat.ksprintf m ~f:invalid_decl type t = { cst_id: ID.t; cst_args: Type.t list; [ cst_ty = cst_id ] cst_ity: Ind_ty.t; (* the corresponding inductive type *) cst_is_sub: bool; (* sub-constant? *) cst_depth: int; (* how many induction lead to this one? *) } exception Payload_cst of t * { 5 Inductive Constants } let to_term c = Term.const ~ty:c.cst_ty c.cst_id let id c = c.cst_id let ty c = c.cst_ty let equal a b = ID.equal a.cst_id b.cst_id let compare a b = ID.compare a.cst_id b.cst_id let hash a = ID.hash a.cst_id module Cst_set = CCSet.Make(struct type t_ = t type t = t_ let compare = compare end) let depth c = c.cst_depth let same_type c1 c2 = Type.equal c1.cst_ty c2.cst_ty let pp out c = ID.pp out c.cst_id let on_new_cst = Signal.create() let id_as_cst id = ID.payload_find id ~f:(function | Payload_cst c -> Some c | _ -> None) let id_as_cst_exn id = match id_as_cst id with | None -> raise (NotAnInductiveConstant id) | Some c -> c let id_is_cst id = match id_as_cst id with Some _ -> true | _ -> false let is_sub c = c.cst_is_sub let id_is_sub id = id_as_cst id |> CCOpt.map_or ~default:false is_sub * { 5 Creation of Coverset and Cst } let n_ = ref 0 let make_skolem ty : ID.t = let c = ID.makef "#%s_%d" (Type.mangle ty) !n_ in incr n_; (* declare as a skolem *) let k = if Ind_ty.is_inductive_type ty then ID.K_ind else ID.K_normal in ID.set_payload c (ID.Attr_skolem k); c (* declare new constant *) let declare ~depth ~is_sub id ty = Util.debugf ~section:Ind_ty.section 2 "@[<2>declare new inductive symbol@ `@[%a : %a@]`@ :depth %d :is_sub %B@]" (fun k->k ID.pp id Type.pp ty depth is_sub); assert (not (id_is_cst id)); assert (Type.is_ground ty); (* constant --> not polymorphic *) let ity, args = match Ind_ty.as_inductive_type ty with | Some (t,l) -> t,l | None -> invalid_declf "cannot declare a constant of type %a" Type.pp ty in (* build coverset and constant, mutually recursive *) let cst = { cst_id=id; cst_ty=ty; cst_depth=depth; cst_ity=ity; cst_args=args; cst_is_sub=is_sub; } in ID.set_payload id (Payload_cst cst) ~can_erase:(function | ID.Attr_skolem ID.K_ind -> true (* special case: promotion from skolem to inductive const *) | _ -> false); (* return *) Signal.send on_new_cst cst; cst let make ?(depth=0) ~is_sub (ty:Type.t): t = let id = make_skolem ty in declare ~depth ~is_sub id ty let dominates (c1:t)(c2:t): bool = c1.cst_depth < c2.cst_depth * { 2 Inductive Skolems } type ind_skolem = ID.t * Type.t let ind_skolem_compare = CCOrd.pair ID.compare Type.compare let ind_skolem_equal a b = ind_skolem_compare a b = 0 let id_is_ind_skolem (id:ID.t) (ty:Type.t): bool = let n_tyvars, ty_args, ty_ret = Type.open_poly_fun ty in n_tyvars=0 && ty_args=[] (* constant *) && Ind_ty.is_inductive_type ty_ret && Ind_ty.is_recursive (Ind_ty.as_inductive_type_exn ty_ret |> fst) && Type.is_ground ty && (id_is_cst id || (not (Ind_ty.is_constructor id) && not (Rewrite.is_defined_cst id))) let ind_skolem_depth (id:ID.t): int = match id_as_cst id with | None -> 0 | Some c -> depth c (* find inductive constant candidates in terms *) let find_ind_skolems t : ind_skolem Iter.t = T.Seq.subterms t |> Iter.filter_map (fun t -> match T.view t with | T.Const id -> let ty = T.ty t in if id_is_ind_skolem id ty then ( let n_tyvars, ty_args, _ = Type.open_poly_fun ty in assert (n_tyvars=0 && ty_args=[]); Some (id, ty) ) else None | _ -> None)
null
https://raw.githubusercontent.com/sneeuwballen/zipperposition/7f1455fbe2e7509907f927649c288141b1a3a247/src/prover/Ind_cst.ml
ocaml
the corresponding inductive type sub-constant? how many induction lead to this one? declare as a skolem declare new constant constant --> not polymorphic build coverset and constant, mutually recursive special case: promotion from skolem to inductive const return constant find inductive constant candidates in terms
* { 1 Inductive Constants and Cases } Skolem constants of an inductive type , coversets , etc . required for inductive reasoning . Skolem constants of an inductive type, coversets, etc. required for inductive reasoning. *) open Logtk module T = Term exception InvalidDecl of string exception NotAnInductiveConstant of ID.t let () = let spf = CCFormat.sprintf in Printexc.register_printer (function | InvalidDecl msg -> Some (spf "@[<2>invalid declaration:@ %s@]" msg) | NotAnInductiveConstant id -> Some (spf "%a is not an inductive constant" ID.pp id) | _ -> None) let invalid_decl m = raise (InvalidDecl m) let invalid_declf m = CCFormat.ksprintf m ~f:invalid_decl type t = { cst_id: ID.t; cst_args: Type.t list; [ cst_ty = cst_id ] } exception Payload_cst of t * { 5 Inductive Constants } let to_term c = Term.const ~ty:c.cst_ty c.cst_id let id c = c.cst_id let ty c = c.cst_ty let equal a b = ID.equal a.cst_id b.cst_id let compare a b = ID.compare a.cst_id b.cst_id let hash a = ID.hash a.cst_id module Cst_set = CCSet.Make(struct type t_ = t type t = t_ let compare = compare end) let depth c = c.cst_depth let same_type c1 c2 = Type.equal c1.cst_ty c2.cst_ty let pp out c = ID.pp out c.cst_id let on_new_cst = Signal.create() let id_as_cst id = ID.payload_find id ~f:(function | Payload_cst c -> Some c | _ -> None) let id_as_cst_exn id = match id_as_cst id with | None -> raise (NotAnInductiveConstant id) | Some c -> c let id_is_cst id = match id_as_cst id with Some _ -> true | _ -> false let is_sub c = c.cst_is_sub let id_is_sub id = id_as_cst id |> CCOpt.map_or ~default:false is_sub * { 5 Creation of Coverset and Cst } let n_ = ref 0 let make_skolem ty : ID.t = let c = ID.makef "#%s_%d" (Type.mangle ty) !n_ in incr n_; let k = if Ind_ty.is_inductive_type ty then ID.K_ind else ID.K_normal in ID.set_payload c (ID.Attr_skolem k); c let declare ~depth ~is_sub id ty = Util.debugf ~section:Ind_ty.section 2 "@[<2>declare new inductive symbol@ `@[%a : %a@]`@ :depth %d :is_sub %B@]" (fun k->k ID.pp id Type.pp ty depth is_sub); assert (not (id_is_cst id)); let ity, args = match Ind_ty.as_inductive_type ty with | Some (t,l) -> t,l | None -> invalid_declf "cannot declare a constant of type %a" Type.pp ty in let cst = { cst_id=id; cst_ty=ty; cst_depth=depth; cst_ity=ity; cst_args=args; cst_is_sub=is_sub; } in ID.set_payload id (Payload_cst cst) ~can_erase:(function | ID.Attr_skolem ID.K_ind -> | _ -> false); Signal.send on_new_cst cst; cst let make ?(depth=0) ~is_sub (ty:Type.t): t = let id = make_skolem ty in declare ~depth ~is_sub id ty let dominates (c1:t)(c2:t): bool = c1.cst_depth < c2.cst_depth * { 2 Inductive Skolems } type ind_skolem = ID.t * Type.t let ind_skolem_compare = CCOrd.pair ID.compare Type.compare let ind_skolem_equal a b = ind_skolem_compare a b = 0 let id_is_ind_skolem (id:ID.t) (ty:Type.t): bool = let n_tyvars, ty_args, ty_ret = Type.open_poly_fun ty in n_tyvars=0 && Ind_ty.is_inductive_type ty_ret && Ind_ty.is_recursive (Ind_ty.as_inductive_type_exn ty_ret |> fst) && Type.is_ground ty && (id_is_cst id || (not (Ind_ty.is_constructor id) && not (Rewrite.is_defined_cst id))) let ind_skolem_depth (id:ID.t): int = match id_as_cst id with | None -> 0 | Some c -> depth c let find_ind_skolems t : ind_skolem Iter.t = T.Seq.subterms t |> Iter.filter_map (fun t -> match T.view t with | T.Const id -> let ty = T.ty t in if id_is_ind_skolem id ty then ( let n_tyvars, ty_args, _ = Type.open_poly_fun ty in assert (n_tyvars=0 && ty_args=[]); Some (id, ty) ) else None | _ -> None)
fb7406b482e9830338148b16c81038f09b7bc2cfaa73210b964e30748803be2e
amnh/PCG
NonNegativeAverage.hs
----------------------------------------------------------------------------- -- | Module : Numeric . Copyright : ( c ) 2015 - 2021 Ward Wheeler -- License : BSD-style -- -- Maintainer : -- Stability : provisional -- Portability : portable -- ----------------------------------------------------------------------------- {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # {-# LANGUAGE Safe #-} module Numeric.NonNegativeAverage ( NonNegativeAverage() , fromNonNegativeAverage , fromNonNegativeValue ) where import Control.DeepSeq import Data.Binary import Data.Data import Data.Hashable import GHC.Generics import Test.QuickCheck -- | -- Defines an average of non-negative numbers. -- -- This is a newtyped 'Ratio Word' for efficiency purposes. -- -- Use 'fromNonNegativeValue' to create a single average value. -- Use the ` Semigroup ` operator ' ( < > ) ' to combine two ' ' values . -- -- Use 'fromNonNegativeAverage' when you are done accumulating values to average -- to compute the /possibly/ non-integer average as a 'Fractional' value. -- -- All instance operations are /O(1)/. data NonNegativeAverage = Avg !Word !Word deriving stock (Data, Eq, Generic, Ord) deriving anyclass (Binary, NFData) instance Arbitrary NonNegativeAverage where arbitrary = do num <- arbitrary den <- arbitrary pure . Avg num $ getPositive den instance Bounded NonNegativeAverage where maxBound = Avg maxBound 1 minBound = Avg 0 1 instance Hashable NonNegativeAverage where hashWithSalt salt (Avg d n) = hashWithSalt salt (d, n) instance Semigroup NonNegativeAverage where (Avg n d) <> (Avg n' d') = Avg (n + n') (d + d') instance Show NonNegativeAverage where show = show . (fromNonNegativeAverage :: NonNegativeAverage -> Rational) -- | Safely construct a ' ' from a ' Word ' . # INLINE fromNonNegativeValue # fromNonNegativeValue :: Word -> NonNegativeAverage fromNonNegativeValue x = Avg x 1 -- | Safely convert a ' ' to a ' Fractional ' representation . fromNonNegativeAverage :: Fractional r => NonNegativeAverage -> r fromNonNegativeAverage (Avg n d) = num / den where num = fromIntegral n den = fromIntegral d
null
https://raw.githubusercontent.com/amnh/PCG/9341efe0ec2053302c22b4466157d0a24ed18154/lib/utility/src/Numeric/NonNegativeAverage.hs
haskell
--------------------------------------------------------------------------- | License : BSD-style Maintainer : Stability : provisional Portability : portable --------------------------------------------------------------------------- # LANGUAGE DeriveAnyClass # # LANGUAGE DeriveDataTypeable # # LANGUAGE Safe # | Defines an average of non-negative numbers. This is a newtyped 'Ratio Word' for efficiency purposes. Use 'fromNonNegativeValue' to create a single average value. Use 'fromNonNegativeAverage' when you are done accumulating values to average to compute the /possibly/ non-integer average as a 'Fractional' value. All instance operations are /O(1)/. | |
Module : Numeric . Copyright : ( c ) 2015 - 2021 Ward Wheeler # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # module Numeric.NonNegativeAverage ( NonNegativeAverage() , fromNonNegativeAverage , fromNonNegativeValue ) where import Control.DeepSeq import Data.Binary import Data.Data import Data.Hashable import GHC.Generics import Test.QuickCheck Use the ` Semigroup ` operator ' ( < > ) ' to combine two ' ' values . data NonNegativeAverage = Avg !Word !Word deriving stock (Data, Eq, Generic, Ord) deriving anyclass (Binary, NFData) instance Arbitrary NonNegativeAverage where arbitrary = do num <- arbitrary den <- arbitrary pure . Avg num $ getPositive den instance Bounded NonNegativeAverage where maxBound = Avg maxBound 1 minBound = Avg 0 1 instance Hashable NonNegativeAverage where hashWithSalt salt (Avg d n) = hashWithSalt salt (d, n) instance Semigroup NonNegativeAverage where (Avg n d) <> (Avg n' d') = Avg (n + n') (d + d') instance Show NonNegativeAverage where show = show . (fromNonNegativeAverage :: NonNegativeAverage -> Rational) Safely construct a ' ' from a ' Word ' . # INLINE fromNonNegativeValue # fromNonNegativeValue :: Word -> NonNegativeAverage fromNonNegativeValue x = Avg x 1 Safely convert a ' ' to a ' Fractional ' representation . fromNonNegativeAverage :: Fractional r => NonNegativeAverage -> r fromNonNegativeAverage (Avg n d) = num / den where num = fromIntegral n den = fromIntegral d
35e62afdbb61d1a4d6566ec464c93b2b079e75130849aa4fa894387ba7d17462
softwarelanguageslab/maf
R5RS_rosetta_easter-4.scm
; Changes: * removed : 0 * added : 0 * swaps : 0 * negated predicates : 1 ; * swapped branches: 0 ; * calls to id fun: 0 (letrec ((easter (lambda (year) (let* ((a (remainder year 19)) (b (quotient year 100)) (c (remainder year 100)) (d (quotient b 4)) (e (remainder b 4)) (f (quotient (+ b 8) 25)) (g (quotient (+ 1 (- b f)) 3)) (h (remainder (+ (* 19 a) (- b d g) 15) 30)) (i (quotient c 4)) (k (remainder c 4)) (l (remainder (+ e e i i (- 32 h k)) 7)) (m (quotient (+ a (* 11 h) (* 22 l)) 451)) (n (+ h l (- 114 (* 7 m))))) (list (quotient n 31) (+ 1 (remainder n 31))))))) (if (equal? (easter 2017) (__toplevel_cons 4 (__toplevel_cons 16 ()))) (if (equal? (easter 1027) (__toplevel_cons 4 (__toplevel_cons 1 ()))) (if (<change> (equal? (easter 2016) (__toplevel_cons 3 (__toplevel_cons 27 ()))) (not (equal? (easter 2016) (__toplevel_cons 3 (__toplevel_cons 27 ()))))) (equal? (easter 172) (__toplevel_cons 3 (__toplevel_cons 29 ()))) #f) #f) #f))
null
https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_rosetta_easter-4.scm
scheme
Changes: * swapped branches: 0 * calls to id fun: 0
* removed : 0 * added : 0 * swaps : 0 * negated predicates : 1 (letrec ((easter (lambda (year) (let* ((a (remainder year 19)) (b (quotient year 100)) (c (remainder year 100)) (d (quotient b 4)) (e (remainder b 4)) (f (quotient (+ b 8) 25)) (g (quotient (+ 1 (- b f)) 3)) (h (remainder (+ (* 19 a) (- b d g) 15) 30)) (i (quotient c 4)) (k (remainder c 4)) (l (remainder (+ e e i i (- 32 h k)) 7)) (m (quotient (+ a (* 11 h) (* 22 l)) 451)) (n (+ h l (- 114 (* 7 m))))) (list (quotient n 31) (+ 1 (remainder n 31))))))) (if (equal? (easter 2017) (__toplevel_cons 4 (__toplevel_cons 16 ()))) (if (equal? (easter 1027) (__toplevel_cons 4 (__toplevel_cons 1 ()))) (if (<change> (equal? (easter 2016) (__toplevel_cons 3 (__toplevel_cons 27 ()))) (not (equal? (easter 2016) (__toplevel_cons 3 (__toplevel_cons 27 ()))))) (equal? (easter 172) (__toplevel_cons 3 (__toplevel_cons 29 ()))) #f) #f) #f))
0fd109deeaab5286cb2f67ca3c80df0745738a338ac95119ec87608c6a51673f
madnificent/jsown
packages.lisp
(defpackage :jsown-tests (:use :common-lisp :jsown :fiveam) (:export :test-all :test-readers :test-writers :test-accessors)) (in-package :jsown-tests) (def-suite test-all :description "All tests made for jsown")
null
https://raw.githubusercontent.com/madnificent/jsown/744c4407bef58dfa876d9da0b5c0205d869e7977/tests/packages.lisp
lisp
(defpackage :jsown-tests (:use :common-lisp :jsown :fiveam) (:export :test-all :test-readers :test-writers :test-accessors)) (in-package :jsown-tests) (def-suite test-all :description "All tests made for jsown")
bd142cc73b40290a42ccb100bd8b30763891289950b85e9e5b84f817442b32bb
DataHaskell/dh-core
Gapminder.hs
# LANGUAGE DeriveGeneric , OverloadedStrings , # OPTIONS_GHC -fno - warn - unused - imports # | Gapminder dataset - Life expectancy , GDP , population every five years per country Source : < > More information : -project.org/web/packages/gapminder/gapminder.pdf Gapminder dataset - Life expectancy, GDP, population every five years per country Source: <> More information: -project.org/web/packages/gapminder/gapminder.pdf -} module Numeric.Datasets.Gapminder where import Numeric.Datasets import Data.Csv import GHC.Generics import Control.Applicative import Data.Text (Text) import Network.HTTP.Req ((/:), https, Scheme(..)) data Gapminder = Gapminder { country :: Text , year :: Int , pop :: Integer , continent :: Text , lifeExp :: Double , gdpPercap :: Double } deriving (Show, Read, Generic) instance FromNamedRecord Gapminder where parseNamedRecord m = Gapminder <$> m .: "country" <*> m .: "year" <*> (roundIt <$> m .: "pop") <*> m .: "continent" <*> m .: "lifeExp" <*> m .: "gdpPercap" where roundIt :: Double -> Integer roundIt = round gapminder :: Dataset Gapminder gapminder = csvHdrDataset $ URL $ https "raw.githubusercontent.com" /: "plotly" /: "datasets" /: "master" /: "gapminderDataFiveYear.csv"
null
https://raw.githubusercontent.com/DataHaskell/dh-core/2beb8740f27fa9683db70eb8d8424ee6c75d3e91/datasets/src/Numeric/Datasets/Gapminder.hs
haskell
# LANGUAGE DeriveGeneric , OverloadedStrings , # OPTIONS_GHC -fno - warn - unused - imports # | Gapminder dataset - Life expectancy , GDP , population every five years per country Source : < > More information : -project.org/web/packages/gapminder/gapminder.pdf Gapminder dataset - Life expectancy, GDP, population every five years per country Source: <> More information: -project.org/web/packages/gapminder/gapminder.pdf -} module Numeric.Datasets.Gapminder where import Numeric.Datasets import Data.Csv import GHC.Generics import Control.Applicative import Data.Text (Text) import Network.HTTP.Req ((/:), https, Scheme(..)) data Gapminder = Gapminder { country :: Text , year :: Int , pop :: Integer , continent :: Text , lifeExp :: Double , gdpPercap :: Double } deriving (Show, Read, Generic) instance FromNamedRecord Gapminder where parseNamedRecord m = Gapminder <$> m .: "country" <*> m .: "year" <*> (roundIt <$> m .: "pop") <*> m .: "continent" <*> m .: "lifeExp" <*> m .: "gdpPercap" where roundIt :: Double -> Integer roundIt = round gapminder :: Dataset Gapminder gapminder = csvHdrDataset $ URL $ https "raw.githubusercontent.com" /: "plotly" /: "datasets" /: "master" /: "gapminderDataFiveYear.csv"
a944b16351f2120c6d88fd9c5e0ab23de5c47c5b9bf2ffa596adcdf80c5183da
rubenbarroso/EOPL
2-unify.scm
(let ((time-stamp "Time-stamp: <2000-12-11 17:01:55 wand>")) (eopl:printf "2-unify.scm: terms, substitutions, unification ~a~%" (substring time-stamp 13 29))) ;;;;;;;;;;;;;;;; syntax ;;;;;;;;;;;;;;;; (define-datatype term term? (var-term (id symbol?)) (constant-term (datum constant?)) (app-term (terms (list-of term?)))) ;;;;;;;;;;;;;;;; substitutions ;;;;;;;;;;;;;;;; ;;; basic interface ;; represent substs as fcns id -> term (define empty-subst (lambda () (lambda (id) (var-term id)))) (define apply-subst (lambda (subst id) (subst id))) (define unit-subst (lambda (id new-term) (lambda (id2) (if (eq? id2 id) new-term (var-term id2))))) (define compose-substs (lambda (s1 s2) (lambda (id) (subst-in-term (apply-subst s1 id) s2)))) ;;; next level (define subst-in-term (lambda (t subst) (cases term t (var-term (id) (apply-subst subst id)) (constant-term (datum) (constant-term datum)) (app-term (ts) (app-term (subst-in-terms ts subst)))))) (define subst-in-terms (lambda (ts subst) (map (lambda (t) (subst-in-term t subst)) ts))) ;;; auxiliaries for unifier: (define all-ids (lambda (t) (cases term t (var-term (id) (list id)) (constant-term (datum) '()) (app-term (ts) (all-ids-terms ts))))) (define all-ids-terms (lambda (ts) (map-union all-ids ts))) ;;;;;;;;;;;;;;;; unification ;;;;;;;;;;;;;;;; (define var-term? (lambda (t) (cases term t (var-term (id) #t) (else #f)))) ;; the unifier (define unify-term (lambda (t u) (cases term t (var-term (tid) (if (or (var-term? u) (not (memv tid (all-ids u)))) (unit-subst tid u) #f)) (else (cases term u (var-term (uid) (unify-term u t)) (constant-term (udatum) (cases term t (constant-term (tdatum) (if (equal? tdatum udatum) (empty-subst) #f)) (else #f))) (app-term (us) (cases term t (app-term (ts) (unify-terms ts us)) (else #f)))))))) (define unify-terms (lambda (ts us) (cond ((and (null? ts) (null? us)) (empty-subst)) ((or (null? ts) (null? us)) #f) (else (let ((subst-car (unify-term (car ts) (car us)))) (if (not subst-car) #f (let ((new-ts (subst-in-terms (cdr ts) subst-car)) (new-us (subst-in-terms (cdr us) subst-car))) (let ((subst-cdr (unify-terms new-ts new-us))) (if (not subst-cdr) #f (compose-substs subst-car subst-cdr)))))))))) ;;;; -------------------- Junk below the line ------------------- (define variable (lambda (x) (gensym))) (define union (lambda (set1 set2) (cond ((null? set1) set2) ((memv (car set1) set2) (union (cdr set1) set2)) (else (cons (car set1) (union (cdr set1) set2)))))) (define map-union (lambda (f ls) (cond ((null? ls) '()) (else (union (f (car ls)) (map-union f (cdr ls))))))) (define parse-term (lambda (exp) (cond ((symbol? exp) (var-term exp)) ((list? exp) (app-term (map parse-term exp))) ((constant? exp) (constant-term exp)) (else (eopl:error 'parse-term "Invalid term:~s" exp))))) (define unparse-term (lambda (t) (cases term t (var-term (id) id) (constant-term (datum) datum) (app-term (ts) (unparse-terms ts))))) (define unparse-terms (lambda (ts) (map unparse-term ts))) (define constant? (lambda (x) (or (boolean? x) (number? x) (string? x) (null? x))))
null
https://raw.githubusercontent.com/rubenbarroso/EOPL/f9b3c03c2fcbaddf64694ee3243d54be95bfe31d/src/interps/2-unify.scm
scheme
syntax ;;;;;;;;;;;;;;;; substitutions ;;;;;;;;;;;;;;;; basic interface represent substs as fcns id -> term next level auxiliaries for unifier: unification ;;;;;;;;;;;;;;;; the unifier -------------------- Junk below the line -------------------
(let ((time-stamp "Time-stamp: <2000-12-11 17:01:55 wand>")) (eopl:printf "2-unify.scm: terms, substitutions, unification ~a~%" (substring time-stamp 13 29))) (define-datatype term term? (var-term (id symbol?)) (constant-term (datum constant?)) (app-term (terms (list-of term?)))) (define empty-subst (lambda () (lambda (id) (var-term id)))) (define apply-subst (lambda (subst id) (subst id))) (define unit-subst (lambda (id new-term) (lambda (id2) (if (eq? id2 id) new-term (var-term id2))))) (define compose-substs (lambda (s1 s2) (lambda (id) (subst-in-term (apply-subst s1 id) s2)))) (define subst-in-term (lambda (t subst) (cases term t (var-term (id) (apply-subst subst id)) (constant-term (datum) (constant-term datum)) (app-term (ts) (app-term (subst-in-terms ts subst)))))) (define subst-in-terms (lambda (ts subst) (map (lambda (t) (subst-in-term t subst)) ts))) (define all-ids (lambda (t) (cases term t (var-term (id) (list id)) (constant-term (datum) '()) (app-term (ts) (all-ids-terms ts))))) (define all-ids-terms (lambda (ts) (map-union all-ids ts))) (define var-term? (lambda (t) (cases term t (var-term (id) #t) (else #f)))) (define unify-term (lambda (t u) (cases term t (var-term (tid) (if (or (var-term? u) (not (memv tid (all-ids u)))) (unit-subst tid u) #f)) (else (cases term u (var-term (uid) (unify-term u t)) (constant-term (udatum) (cases term t (constant-term (tdatum) (if (equal? tdatum udatum) (empty-subst) #f)) (else #f))) (app-term (us) (cases term t (app-term (ts) (unify-terms ts us)) (else #f)))))))) (define unify-terms (lambda (ts us) (cond ((and (null? ts) (null? us)) (empty-subst)) ((or (null? ts) (null? us)) #f) (else (let ((subst-car (unify-term (car ts) (car us)))) (if (not subst-car) #f (let ((new-ts (subst-in-terms (cdr ts) subst-car)) (new-us (subst-in-terms (cdr us) subst-car))) (let ((subst-cdr (unify-terms new-ts new-us))) (if (not subst-cdr) #f (compose-substs subst-car subst-cdr)))))))))) (define variable (lambda (x) (gensym))) (define union (lambda (set1 set2) (cond ((null? set1) set2) ((memv (car set1) set2) (union (cdr set1) set2)) (else (cons (car set1) (union (cdr set1) set2)))))) (define map-union (lambda (f ls) (cond ((null? ls) '()) (else (union (f (car ls)) (map-union f (cdr ls))))))) (define parse-term (lambda (exp) (cond ((symbol? exp) (var-term exp)) ((list? exp) (app-term (map parse-term exp))) ((constant? exp) (constant-term exp)) (else (eopl:error 'parse-term "Invalid term:~s" exp))))) (define unparse-term (lambda (t) (cases term t (var-term (id) id) (constant-term (datum) datum) (app-term (ts) (unparse-terms ts))))) (define unparse-terms (lambda (ts) (map unparse-term ts))) (define constant? (lambda (x) (or (boolean? x) (number? x) (string? x) (null? x))))
b1613df2de59883dc7d6162323cb049e410dda27995f91421569bc6b82a87e94
lambdaisland/deep-diff2
color.cljc
(ns lambdaisland.deep-diff2.puget.color "Coloring multimethods to format text by adding markup. #### Color Options `:print-color` When true, ouptut colored text from print functions. `:color-markup` - `:ansi` for color terminal text (default) - `:html-inline` for inline-styled html - `:html-classes` for html with semantic classes `:color-scheme` Map of syntax element keywords to color codes. ") ;; ## Coloring Multimethods (defn dispatch "Dispatches to coloring multimethods. Element should be a key from the color-scheme map." [options element text] (when (:print-color options) (:color-markup options))) (defmulti document "Constructs a pretty print document, which may be colored if `:print-color` is true." #'dispatch) (defmulti text "Produces text colored according to the active color scheme. This is mostly useful to clients which want to produce output which matches data printed by Puget, but which is not directly printed by the library. Note that this function still obeys the `:print-color` option." #'dispatch) # # Default Markup ;; The default transformation when there's no markup specified is to return the ;; text unaltered. (defmethod document nil [options element text] text) (defmethod text nil [options element text] text)
null
https://raw.githubusercontent.com/lambdaisland/deep-diff2/2ef429227ac9986024e6c8f63ded9a88eb3fe9c2/src/lambdaisland/deep_diff2/puget/color.cljc
clojure
## Coloring Multimethods The default transformation when there's no markup specified is to return the text unaltered.
(ns lambdaisland.deep-diff2.puget.color "Coloring multimethods to format text by adding markup. #### Color Options `:print-color` When true, ouptut colored text from print functions. `:color-markup` - `:ansi` for color terminal text (default) - `:html-inline` for inline-styled html - `:html-classes` for html with semantic classes `:color-scheme` Map of syntax element keywords to color codes. ") (defn dispatch "Dispatches to coloring multimethods. Element should be a key from the color-scheme map." [options element text] (when (:print-color options) (:color-markup options))) (defmulti document "Constructs a pretty print document, which may be colored if `:print-color` is true." #'dispatch) (defmulti text "Produces text colored according to the active color scheme. This is mostly useful to clients which want to produce output which matches data printed by Puget, but which is not directly printed by the library. Note that this function still obeys the `:print-color` option." #'dispatch) # # Default Markup (defmethod document nil [options element text] text) (defmethod text nil [options element text] text)
0773a1c44196366bc6e0b9e9dbbf92c430c1ed79062ffd4a88c61e8f4cac0361
ekmett/haskell
Type.hs
# language PatternSynonyms # {-# language ExplicitNamespaces #-} # language TemplateHaskell # # language StandaloneKindSignatures # # language FlexibleInstances # # language DataKinds # # language TypeApplications # # language PolyKinds # # language RoleAnnotations # # language ViewPatterns # # language GADTs # # language MagicHash # # OPTIONS_GHC -Wno - orphans # -- | Copyright : ( c ) 2020 License : BSD-2 - Clause OR Apache-2.0 Maintainer : < > -- Stability : experimental -- Portability: non-portable module Data.Type ( -- * Singleton types and reflection from singletons type Sing , SingT(Sing, the) , SingI(..) , makeSing , withSing -- * Reflection , reify , reflect -- * Singular types , Singular , me , Me -- makeMe -- ** 'Type' , type Type , pattern Type , pattern SType -- ** 'Constraint' , type Constraint , pattern Constraint , pattern SConstraint * * ' ' , Nat , toNat, fromNat , pattern Nat -- ** 'Symbol' , Symbol , pattern Symbol , toSymbol , fromSymbol -- * Lifting numerics , Nice(..) , pattern Z , pattern S , type Z , type S , pattern SZ , pattern SS, pattern SS' * * ' ' , MkChar -- ** @'Ptr' a@ , MkPtr , pattern SMkPtr -- ** @'StablePtr' a@ , MkStablePtr , pattern SMkStablePtr -- * Singletons -- ** '(,)' , pattern SUnit , pattern STuple2 -- (,) , pattern STuple3 -- (,,) , pattern STuple4 -- (,,,) , pattern STuple5 -- (,,,,) , pattern STuple6 -- (,,,,,) , pattern STuple7 -- (,,,,,,) , pattern STuple8 -- (,,,,,,,) , pattern STuple9 -- (,,,,,,,,) -- ** 'Either' , pattern SLeft, pattern SRight -- Either -- ** 'Maybe' , pattern SJust, pattern SNothing -- Maybe -- ** 'List' , pattern SNil, pattern (:#) -- List * * ' NonEmpty ' NonEmpty * * ' ' , pattern STrue, pattern SFalse -- Bool -- ** 'Ordering' , pattern SLT, pattern SEQ, pattern SGT -- Ordering -- ** 'Const' , pattern SConst -- ** 'Identity' , pattern SIdentity -- ** 'Compose' , pattern SCompose -- ** 'Proxy' , pattern SProxy -- ** '(:~:)' , pattern SRefl -- ** '(:~~:)' , pattern SHRefl -- ** Dict p , type MkDict , pattern SDict -- ** p :- q , type MkImpl , pattern SImpl --, MkSubDict ) where import Data.Type.Internal import Data.Type.Internal.Instances import Data.Type.Internal.TH import GHC.Types (Constraint, Type, Nat, Symbol)
null
https://raw.githubusercontent.com/ekmett/haskell/37ad048531f5a3a13c6dfbf4772ee4325f0e4458/types/src/Data/Type.hs
haskell
# language ExplicitNamespaces # | Stability : experimental Portability: non-portable * Singleton types and reflection from singletons * Reflection * Singular types makeMe ** 'Type' ** 'Constraint' ** 'Symbol' * Lifting numerics ** @'Ptr' a@ ** @'StablePtr' a@ * Singletons ** '(,)' (,) (,,) (,,,) (,,,,) (,,,,,) (,,,,,,) (,,,,,,,) (,,,,,,,,) ** 'Either' Either ** 'Maybe' Maybe ** 'List' List Bool ** 'Ordering' Ordering ** 'Const' ** 'Identity' ** 'Compose' ** 'Proxy' ** '(:~:)' ** '(:~~:)' ** Dict p ** p :- q , MkSubDict
# language PatternSynonyms # # language TemplateHaskell # # language StandaloneKindSignatures # # language FlexibleInstances # # language DataKinds # # language TypeApplications # # language PolyKinds # # language RoleAnnotations # # language ViewPatterns # # language GADTs # # language MagicHash # # OPTIONS_GHC -Wno - orphans # Copyright : ( c ) 2020 License : BSD-2 - Clause OR Apache-2.0 Maintainer : < > module Data.Type ( type Sing , SingT(Sing, the) , SingI(..) , makeSing , withSing , reify , reflect , Singular , me , Me , type Type , pattern Type , pattern SType , type Constraint , pattern Constraint , pattern SConstraint * * ' ' , Nat , toNat, fromNat , pattern Nat , Symbol , pattern Symbol , toSymbol , fromSymbol , Nice(..) , pattern Z , pattern S , type Z , type S , pattern SZ , pattern SS, pattern SS' * * ' ' , MkChar , MkPtr , pattern SMkPtr , MkStablePtr , pattern SMkStablePtr , pattern SUnit * * ' NonEmpty ' NonEmpty * * ' ' , pattern SConst , pattern SIdentity , pattern SCompose , pattern SProxy , pattern SRefl , pattern SHRefl , type MkDict , pattern SDict , type MkImpl , pattern SImpl ) where import Data.Type.Internal import Data.Type.Internal.Instances import Data.Type.Internal.TH import GHC.Types (Constraint, Type, Nat, Symbol)
58884bf975e0725a5a2b7b5bab46571a0f527ea14de77a114dc172a44321ca85
kcsongor/generic-lens
Internal.hs
----------------------------------------------------------------------------- -- | -- Module : Data.GenericLens.Internal Copyright : ( C ) 2020 -- License : BSD3 Maintainer : < > -- Stability : experimental -- Portability : non-portable -- -- The library internals are exposed through this module. Please keep -- in mind that everything here is subject to change irrespective of -- the the version numbers. ----------------------------------------------------------------------------- module Data.GenericLens.Internal ( module Data.Generics.Internal.Families , module Data.Generics.Internal.Families.Changing , module Data.Generics.Internal.Families.Collect , module Data.Generics.Internal.Families.Has , module Data.Generics.Internal.Void , module Data.Generics.Internal.Errors , module Data.Generics.Internal.GenericN -- * Profunctor optics , module Data.Generics.Internal.Profunctor.Iso , module Data.Generics.Internal.Profunctor.Lens , module Data.Generics.Internal.Profunctor.Prism , module Data.Generics.Product.Internal.Subtype ) where import Data.Generics.Internal.Families import Data.Generics.Internal.Families.Changing import Data.Generics.Internal.Families.Collect import Data.Generics.Internal.Families.Has import Data.Generics.Internal.Void import Data.Generics.Internal.Errors import Data.Generics.Internal.GenericN import Data.Generics.Internal.Profunctor.Iso import Data.Generics.Internal.Profunctor.Lens import Data.Generics.Internal.Profunctor.Prism import Data.Generics.Product.Internal.Subtype
null
https://raw.githubusercontent.com/kcsongor/generic-lens/8e1fc7dcf444332c474fca17110d4bc554db08c8/generic-lens-core/src/Data/GenericLens/Internal.hs
haskell
--------------------------------------------------------------------------- | Module : Data.GenericLens.Internal License : BSD3 Stability : experimental Portability : non-portable The library internals are exposed through this module. Please keep in mind that everything here is subject to change irrespective of the the version numbers. --------------------------------------------------------------------------- * Profunctor optics
Copyright : ( C ) 2020 Maintainer : < > module Data.GenericLens.Internal ( module Data.Generics.Internal.Families , module Data.Generics.Internal.Families.Changing , module Data.Generics.Internal.Families.Collect , module Data.Generics.Internal.Families.Has , module Data.Generics.Internal.Void , module Data.Generics.Internal.Errors , module Data.Generics.Internal.GenericN , module Data.Generics.Internal.Profunctor.Iso , module Data.Generics.Internal.Profunctor.Lens , module Data.Generics.Internal.Profunctor.Prism , module Data.Generics.Product.Internal.Subtype ) where import Data.Generics.Internal.Families import Data.Generics.Internal.Families.Changing import Data.Generics.Internal.Families.Collect import Data.Generics.Internal.Families.Has import Data.Generics.Internal.Void import Data.Generics.Internal.Errors import Data.Generics.Internal.GenericN import Data.Generics.Internal.Profunctor.Iso import Data.Generics.Internal.Profunctor.Lens import Data.Generics.Internal.Profunctor.Prism import Data.Generics.Product.Internal.Subtype
6caf29aab00279862a15bb2561e44b1a311bb7fe77019741dfe5fcabb740863d
kframework/semantic-approaches
SmallStep.hs
module Language.Imp.Semantics.SmallStep ( runImpTrace -- , execPgm -- ) where import Language.Imp.Syntax.Abstract import Language.Imp.State import SemanticModel.SmallStep type ImpTrace = Trace ImpEnv runImpTrace :: ImpTrace syntax -> [(syntax, ImpEnv)] runImpTrace impTrace = runTrace emptyEnv impTrace -------------- -- Programs -- The rule for programs is special . For the sake of consistency every rule should have to follow through a top level program rule , but for practicality sake ( the Pgm construct can be erased after the first application ) we simply use it to build the initial state . every rule should have to follow through a top level program rule, but for practicality sake (the Pgm construct can be erased after the first application) we simply use it to build the initial state. -} pgmRule :: Pgm -> ImpTrace Stmt pgmRule (Pgm ids stmt) = put (initialEnv ids) >> return stmt execPgm :: Pgm -> ImpTrace Stmt execPgm pgm = manyStep $ pgmRule pgm ---------------- -- Arithmetic -- aexpRules = [ lookupRule , addRule, addLRule, addRRule , divRule, divLRule, divRRule ] instance Transition ImpEnv (Exp Integer) where isLiteral (Lit _) = True isLiteral _ = False rules = aexpRules -- lookup lookupRule :: Exp Integer -> ImpTrace (Exp Integer) lookupRule (Var v) = do { mi <- gets $ lookupEnv v ; case mi of Nothing -> mzero Just i -> return $ Lit i } lookupRule _ = mzero -- addition addRule :: Exp Integer -> ImpTrace (Exp Integer) addRule (Lit i1 :+: Lit i2) = return $ Lit $ i1 + i2 addRule _ = mzero addLRule :: Exp Integer -> ImpTrace (Exp Integer) addLRule (aexp1 :+: aexp2) | isNotLiteral aexp1 = do { aexp1' <- o aexp1 ; return $ aexp1' :+: aexp2 } addLRule _ = mzero addRRule :: Exp Integer -> ImpTrace (Exp Integer) addRRule (aexp1 :+: aexp2) | isNotLiteral aexp2 = do { aexp2' <- o aexp2 ; return $ aexp1 :+: aexp2' } addRRule _ = mzero -- division divRule :: Exp Integer -> ImpTrace (Exp Integer) divRule (Lit i1 :/: Lit 0) = mzero divRule (Lit i1 :/: Lit i2) = return $ Lit $ i1 `div` i2 divRule _ = mzero divLRule :: Exp Integer -> ImpTrace (Exp Integer) divLRule (aexp1 :/: aexp2) | isNotLiteral aexp1 = do { aexp1' <- o aexp1 ; return $ aexp1' :/: aexp2 } divLRule _ = mzero divRRule :: Exp Integer -> ImpTrace (Exp Integer) divRRule (aexp1 :/: aexp2) | isNotLiteral aexp2 = do { aexp2' <- o aexp2 ; return $ aexp1 :/: aexp2' } divRRule _ = mzero ----------- -- Logic -- bexpRules = [ leqRule, leqLRule, leqRRule , andRule, andLRule , notRule, not'Rule ] instance Transition ImpEnv (Exp Bool) where isLiteral (Lit _) = True isLiteral _ = False rules = bexpRules -- less than or equal to leqRule :: Exp Bool -> ImpTrace (Exp Bool) leqRule (Lit i1 :<=: Lit i2) = return $ Lit $ i1 <= i2 leqRule _ = mzero leqLRule :: Exp Bool -> ImpTrace (Exp Bool) leqLRule (aexp1 :<=: aexp2) | isNotLiteral aexp1 = do { aexp1' <- o aexp1 ; return $ aexp1' :<=: aexp2 } leqLRule _ = mzero leqRRule :: Exp Bool -> ImpTrace (Exp Bool) leqRRule (Lit i :<=: aexp2) | isNotLiteral aexp2 = do { aexp2' <- o aexp2 ; return $ Lit i :<=: aexp2' } leqRRule _ = mzero -- and andRule :: Exp Bool -> ImpTrace (Exp Bool) andRule (Lit True :&&: bexp) = return $ bexp andRule (Lit False :&&: _) = return $ Lit False andRule _ = mzero andLRule :: Exp Bool -> ImpTrace (Exp Bool) andLRule (bexp1 :&&: bexp2) | isNotLiteral bexp1 = do { bexp1' <- o bexp1 ; return $ bexp1' :&&: bexp2 } andLRule _ = mzero -- not notRule :: Exp Bool -> ImpTrace (Exp Bool) notRule (Not (Lit True)) = return $ Lit False notRule (Not (Lit False)) = return $ Lit True notRule _ = mzero not'Rule :: Exp Bool -> ImpTrace (Exp Bool) not'Rule (Not bexp) = do { bexp' <- o bexp ; return $ Not bexp' } not'Rule _ = mzero ---------------- -- Statements -- stmtRules = [ assignRule, assign'Rule , seqRule, seq'Rule , ifRule, if'Rule , whileRule ] instance Transition ImpEnv Stmt where isLiteral Empty = True isLiteral _ = False rules = stmtRules -- assignment assignRule :: Stmt -> ImpTrace Stmt assignRule (x := Lit i) = do { mi <- gets $ lookupEnv x ; case mi of Nothing -> mzero _ -> (modify $ insertEnv x i) >> pure Empty } assignRule _ = mzero assign'Rule :: Stmt -> ImpTrace Stmt assign'Rule (x := aexp) | isNotLiteral aexp = do { aexp' <- o aexp ; return $ x := aexp' } assign'Rule _ = mzero -- sequence seqRule :: Stmt -> ImpTrace Stmt seqRule (Seq Empty s2) = return s2 seqRule _ = mzero seq'Rule :: Stmt -> ImpTrace Stmt seq'Rule (Seq s1 s2) | isNotLiteral s1 = do { s1' <- o s1 ; return $ Seq s1' s2 } seq'Rule _ = mzero -- if then else ifRule :: Stmt -> ImpTrace Stmt ifRule (IfElse (Lit True) s1 _) = return s1 ifRule (IfElse (Lit False) _ s2) = return s2 ifRule _ = mzero if'Rule :: Stmt -> ImpTrace Stmt if'Rule (IfElse bexp s1 s2) | isNotLiteral bexp = do bexp' <- o bexp return $ IfElse bexp' s1 s2 if'Rule _ = mzero -- while whileRule :: Stmt -> ImpTrace Stmt whileRule while@(While bexp s) = return $ IfElse bexp (Seq s while) Empty whileRule _ = mzero
null
https://raw.githubusercontent.com/kframework/semantic-approaches/6f64eac09e005fe4eae7141e3c0e0f5711da0647/haskell/semantic-styles/src/Language/Imp/Semantics/SmallStep.hs
haskell
, execPgm ) ------------ Programs -- -------------- Arithmetic -- lookup addition division --------- Logic -- less than or equal to and not -------------- Statements -- assignment sequence if then else while
module Language.Imp.Semantics.SmallStep ( runImpTrace where import Language.Imp.Syntax.Abstract import Language.Imp.State import SemanticModel.SmallStep type ImpTrace = Trace ImpEnv runImpTrace :: ImpTrace syntax -> [(syntax, ImpEnv)] runImpTrace impTrace = runTrace emptyEnv impTrace The rule for programs is special . For the sake of consistency every rule should have to follow through a top level program rule , but for practicality sake ( the Pgm construct can be erased after the first application ) we simply use it to build the initial state . every rule should have to follow through a top level program rule, but for practicality sake (the Pgm construct can be erased after the first application) we simply use it to build the initial state. -} pgmRule :: Pgm -> ImpTrace Stmt pgmRule (Pgm ids stmt) = put (initialEnv ids) >> return stmt execPgm :: Pgm -> ImpTrace Stmt execPgm pgm = manyStep $ pgmRule pgm aexpRules = [ lookupRule , addRule, addLRule, addRRule , divRule, divLRule, divRRule ] instance Transition ImpEnv (Exp Integer) where isLiteral (Lit _) = True isLiteral _ = False rules = aexpRules lookupRule :: Exp Integer -> ImpTrace (Exp Integer) lookupRule (Var v) = do { mi <- gets $ lookupEnv v ; case mi of Nothing -> mzero Just i -> return $ Lit i } lookupRule _ = mzero addRule :: Exp Integer -> ImpTrace (Exp Integer) addRule (Lit i1 :+: Lit i2) = return $ Lit $ i1 + i2 addRule _ = mzero addLRule :: Exp Integer -> ImpTrace (Exp Integer) addLRule (aexp1 :+: aexp2) | isNotLiteral aexp1 = do { aexp1' <- o aexp1 ; return $ aexp1' :+: aexp2 } addLRule _ = mzero addRRule :: Exp Integer -> ImpTrace (Exp Integer) addRRule (aexp1 :+: aexp2) | isNotLiteral aexp2 = do { aexp2' <- o aexp2 ; return $ aexp1 :+: aexp2' } addRRule _ = mzero divRule :: Exp Integer -> ImpTrace (Exp Integer) divRule (Lit i1 :/: Lit 0) = mzero divRule (Lit i1 :/: Lit i2) = return $ Lit $ i1 `div` i2 divRule _ = mzero divLRule :: Exp Integer -> ImpTrace (Exp Integer) divLRule (aexp1 :/: aexp2) | isNotLiteral aexp1 = do { aexp1' <- o aexp1 ; return $ aexp1' :/: aexp2 } divLRule _ = mzero divRRule :: Exp Integer -> ImpTrace (Exp Integer) divRRule (aexp1 :/: aexp2) | isNotLiteral aexp2 = do { aexp2' <- o aexp2 ; return $ aexp1 :/: aexp2' } divRRule _ = mzero bexpRules = [ leqRule, leqLRule, leqRRule , andRule, andLRule , notRule, not'Rule ] instance Transition ImpEnv (Exp Bool) where isLiteral (Lit _) = True isLiteral _ = False rules = bexpRules leqRule :: Exp Bool -> ImpTrace (Exp Bool) leqRule (Lit i1 :<=: Lit i2) = return $ Lit $ i1 <= i2 leqRule _ = mzero leqLRule :: Exp Bool -> ImpTrace (Exp Bool) leqLRule (aexp1 :<=: aexp2) | isNotLiteral aexp1 = do { aexp1' <- o aexp1 ; return $ aexp1' :<=: aexp2 } leqLRule _ = mzero leqRRule :: Exp Bool -> ImpTrace (Exp Bool) leqRRule (Lit i :<=: aexp2) | isNotLiteral aexp2 = do { aexp2' <- o aexp2 ; return $ Lit i :<=: aexp2' } leqRRule _ = mzero andRule :: Exp Bool -> ImpTrace (Exp Bool) andRule (Lit True :&&: bexp) = return $ bexp andRule (Lit False :&&: _) = return $ Lit False andRule _ = mzero andLRule :: Exp Bool -> ImpTrace (Exp Bool) andLRule (bexp1 :&&: bexp2) | isNotLiteral bexp1 = do { bexp1' <- o bexp1 ; return $ bexp1' :&&: bexp2 } andLRule _ = mzero notRule :: Exp Bool -> ImpTrace (Exp Bool) notRule (Not (Lit True)) = return $ Lit False notRule (Not (Lit False)) = return $ Lit True notRule _ = mzero not'Rule :: Exp Bool -> ImpTrace (Exp Bool) not'Rule (Not bexp) = do { bexp' <- o bexp ; return $ Not bexp' } not'Rule _ = mzero stmtRules = [ assignRule, assign'Rule , seqRule, seq'Rule , ifRule, if'Rule , whileRule ] instance Transition ImpEnv Stmt where isLiteral Empty = True isLiteral _ = False rules = stmtRules assignRule :: Stmt -> ImpTrace Stmt assignRule (x := Lit i) = do { mi <- gets $ lookupEnv x ; case mi of Nothing -> mzero _ -> (modify $ insertEnv x i) >> pure Empty } assignRule _ = mzero assign'Rule :: Stmt -> ImpTrace Stmt assign'Rule (x := aexp) | isNotLiteral aexp = do { aexp' <- o aexp ; return $ x := aexp' } assign'Rule _ = mzero seqRule :: Stmt -> ImpTrace Stmt seqRule (Seq Empty s2) = return s2 seqRule _ = mzero seq'Rule :: Stmt -> ImpTrace Stmt seq'Rule (Seq s1 s2) | isNotLiteral s1 = do { s1' <- o s1 ; return $ Seq s1' s2 } seq'Rule _ = mzero ifRule :: Stmt -> ImpTrace Stmt ifRule (IfElse (Lit True) s1 _) = return s1 ifRule (IfElse (Lit False) _ s2) = return s2 ifRule _ = mzero if'Rule :: Stmt -> ImpTrace Stmt if'Rule (IfElse bexp s1 s2) | isNotLiteral bexp = do bexp' <- o bexp return $ IfElse bexp' s1 s2 if'Rule _ = mzero whileRule :: Stmt -> ImpTrace Stmt whileRule while@(While bexp s) = return $ IfElse bexp (Seq s while) Empty whileRule _ = mzero
a9d378309c2f581d480162455bc0ecc936b224c108cf150ee858c8162ebceed6
modular-macros/ocaml-macros
ocamldep.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1999 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 Compenv open Parsetree module StringMap = Depend.StringMap let ppf = Format.err_formatter (* Print the dependencies *) type file_kind = ML | MLI;; let load_path = ref ([] : (string * string array) list) let ml_synonyms = ref [".ml"] let mli_synonyms = ref [".mli"] let native_only = ref false let bytecode_only = ref false let error_occurred = ref false let raw_dependencies = ref false let sort_files = ref false let all_dependencies = ref false let one_line = ref false let files = ref [] let allow_approximation = ref false let map_files = ref [] let module_map = ref StringMap.empty let debug = ref false Fix path to use ' / ' as directory separator instead of ' \ ' . Only under Windows . Only under Windows. *) let fix_slash s = if Sys.os_type = "Unix" then s else begin String.map (function '\\' -> '/' | c -> c) s end Since we reinitialize load_path after reading OCAMLCOMP , we must use a cache instead of calling Sys.readdir too often . we must use a cache instead of calling Sys.readdir too often. *) let dirs = ref StringMap.empty let readdir dir = try StringMap.find dir !dirs with Not_found -> let contents = try Sys.readdir dir with Sys_error msg -> Format.fprintf Format.err_formatter "@[Bad -I option: %s@]@." msg; error_occurred := true; [||] in dirs := StringMap.add dir contents !dirs; contents let add_to_list li s = li := s :: !li let add_to_load_path dir = try let dir = Misc.expand_directory Config.standard_library dir in let contents = readdir dir in add_to_list load_path (dir, contents) with Sys_error msg -> Format.fprintf Format.err_formatter "@[Bad -I option: %s@]@." msg; error_occurred := true let add_to_synonym_list synonyms suffix = if (String.length suffix) > 1 && suffix.[0] = '.' then add_to_list synonyms suffix else begin Format.fprintf Format.err_formatter "@[Bad suffix: '%s'@]@." suffix; error_occurred := true end (* Find file 'name' (capitalized) in search path *) let find_file name = let uname = String.uncapitalize_ascii name in let rec find_in_array a pos = if pos >= Array.length a then None else begin let s = a.(pos) in if s = name || s = uname then Some s else find_in_array a (pos + 1) end in let rec find_in_path = function [] -> raise Not_found | (dir, contents) :: rem -> match find_in_array contents 0 with Some truename -> if dir = "." then truename else Filename.concat dir truename | None -> find_in_path rem in find_in_path !load_path let rec find_file_in_list = function [] -> raise Not_found | x :: rem -> try find_file x with Not_found -> find_file_in_list rem let find_dependency target_kind modname (byt_deps, opt_deps) = try let candidates = List.map ((^) modname) !mli_synonyms in let filename = find_file_in_list candidates in let basename = Filename.chop_extension filename in let cmi_file = basename ^ ".cmi" in let cmx_file = basename ^ ".cmx" in let ml_exists = List.exists (fun ext -> Sys.file_exists (basename ^ ext)) !ml_synonyms in let new_opt_dep = if !all_dependencies then match target_kind with | MLI -> [ cmi_file ] | ML -> cmi_file :: (if ml_exists then [ cmx_file ] else []) else this is a make - specific hack that makes .cmx to be a ' proxy ' target that would force the dependency on via transitivity target that would force the dependency on .cmi via transitivity *) if ml_exists then [ cmx_file ] else [ cmi_file ] in ( cmi_file :: byt_deps, new_opt_dep @ opt_deps) with Not_found -> try " just .ml " case let candidates = List.map ((^) modname) !ml_synonyms in let filename = find_file_in_list candidates in let basename = Filename.chop_extension filename in let cmi_file = basename ^ ".cmi" in let cmx_file = basename ^ ".cmx" in let bytenames = if !all_dependencies then match target_kind with | MLI -> [ cmi_file ] | ML -> [ cmi_file ] else (* again, make-specific hack *) [basename ^ (if !native_only then ".cmx" else ".cmo")] in let optnames = if !all_dependencies then match target_kind with | MLI -> [ cmi_file ] | ML -> [ cmi_file; cmx_file ] else [ cmx_file ] in (bytenames @ byt_deps, optnames @ opt_deps) with Not_found -> (byt_deps, opt_deps) let (depends_on, escaped_eol) = (":", " \\\n ") let print_filename s = let s = if !Clflags.force_slash then fix_slash s else s in if not (String.contains s ' ') then begin print_string s; end else begin let rec count n i = if i >= String.length s then n else if s.[i] = ' ' then count (n+1) (i+1) else count n (i+1) in let spaces = count 0 0 in let result = Bytes.create (String.length s + spaces) in let rec loop i j = if i >= String.length s then () else if s.[i] = ' ' then begin Bytes.set result j '\\'; Bytes.set result (j+1) ' '; loop (i+1) (j+2); end else begin Bytes.set result j s.[i]; loop (i+1) (j+1); end in loop 0 0; print_bytes result; end ;; let print_dependencies target_files deps = let rec print_items pos = function [] -> print_string "\n" | dep :: rem -> if !one_line || (pos + 1 + String.length dep <= 77) then begin if pos <> 0 then print_string " "; print_filename dep; print_items (pos + String.length dep + 1) rem end else begin print_string escaped_eol; print_filename dep; print_items (String.length dep + 4) rem end in print_items 0 (target_files @ [depends_on] @ deps) let print_raw_dependencies source_file deps = print_filename source_file; print_string depends_on; Depend.StringSet.iter (fun dep -> (* filter out "*predef*" *) if (String.length dep > 0) && (match dep.[0] with | 'A'..'Z' | '\128'..'\255' -> true | _ -> false) then begin print_char ' '; print_string dep end) deps; print_char '\n' (* Process one file *) let report_err exn = error_occurred := true; match exn with | Sys_error msg -> Format.fprintf Format.err_formatter "@[I/O error:@ %s@]@." msg | x -> match Location.error_of_exn x with | Some err -> Format.fprintf Format.err_formatter "@[%a@]@." Location.report_error err | None -> raise x let tool_name = "ocamldep" let rec lexical_approximation lexbuf = (* Approximation when a file can't be parsed. Heuristic: - first component of any path starting with an uppercase character is a dependency. - always skip the token after a dot, unless dot is preceded by a lower-case identifier - always skip the token after a backquote *) try let rec process after_lident lexbuf = match Lexer.token lexbuf with | Parser.UIDENT name -> Depend.free_structure_names := Depend.StringSet.add name !Depend.free_structure_names; process false lexbuf | Parser.LIDENT _ -> process true lexbuf | Parser.DOT when after_lident -> process false lexbuf | Parser.DOT | Parser.BACKQUOTE -> skip_one lexbuf | Parser.EOF -> () | _ -> process false lexbuf and skip_one lexbuf = match Lexer.token lexbuf with | Parser.DOT | Parser.BACKQUOTE -> skip_one lexbuf | Parser.EOF -> () | _ -> process false lexbuf in process false lexbuf with Lexer.Error _ -> lexical_approximation lexbuf let read_and_approximate inputfile = error_occurred := false; Depend.free_structure_names := Depend.StringSet.empty; let ic = open_in_bin inputfile in try seek_in ic 0; Location.input_name := inputfile; let lexbuf = Lexing.from_channel ic in Location.init lexbuf inputfile; lexical_approximation lexbuf; close_in ic; !Depend.free_structure_names with exn -> close_in ic; report_err exn; !Depend.free_structure_names let read_parse_and_extract parse_function extract_function def ast_kind source_file = Depend.free_structure_names := Depend.StringSet.empty; try let input_file = Pparse.preprocess source_file in begin try let ast = Pparse.file ~tool_name Format.err_formatter input_file parse_function ast_kind in let bound_vars = List.fold_left (fun bv modname -> Depend.open_module bv (Longident.Lident modname)) PR#7248 in let r = extract_function bound_vars ast in Pparse.remove_preprocessed input_file; (!Depend.free_structure_names, r) with x -> Pparse.remove_preprocessed input_file; raise x end with x -> begin report_err x; if not !allow_approximation then (Depend.StringSet.empty, def) else (read_and_approximate source_file, def) end let print_ml_dependencies source_file extracted_deps = let basename = Filename.chop_extension source_file in let byte_targets = [ basename ^ ".cmo" ] in let native_targets = if !all_dependencies then [ basename ^ ".cmx"; basename ^ ".o" ] else [ basename ^ ".cmx" ] in let init_deps = if !all_dependencies then [source_file] else [] in let cmi_name = basename ^ ".cmi" in let init_deps, extra_targets = if List.exists (fun ext -> Sys.file_exists (basename ^ ext)) !mli_synonyms then (cmi_name :: init_deps, cmi_name :: init_deps), [] else (init_deps, init_deps), (if !all_dependencies then [cmi_name] else []) in let (byt_deps, native_deps) = Depend.StringSet.fold (find_dependency ML) extracted_deps init_deps in if not !native_only then print_dependencies (byte_targets @ extra_targets) byt_deps; if not !bytecode_only then print_dependencies (native_targets @ extra_targets) native_deps let print_mli_dependencies source_file extracted_deps = let basename = Filename.chop_extension source_file in let (byt_deps, _opt_deps) = Depend.StringSet.fold (find_dependency MLI) extracted_deps ([], []) in print_dependencies [basename ^ ".cmi"] byt_deps let print_file_dependencies (source_file, kind, extracted_deps) = if !raw_dependencies then begin print_raw_dependencies source_file extracted_deps end else match kind with | ML -> print_ml_dependencies source_file extracted_deps | MLI -> print_mli_dependencies source_file extracted_deps let ml_file_dependencies source_file = let parse_use_file_as_impl lexbuf = let f x = match x with | Ptop_stat_eval _ -> [] (* macros: probably wrong *) | Ptop_def s -> s | Ptop_dir _ -> [] in List.flatten (List.map f (Parse.use_file lexbuf)) in let (extracted_deps, ()) = read_parse_and_extract parse_use_file_as_impl Depend.add_implementation () Pparse.Structure source_file in files := (source_file, ML, extracted_deps) :: !files let mli_file_dependencies source_file = let (extracted_deps, ()) = read_parse_and_extract Parse.interface Depend.add_signature () Pparse.Signature source_file in files := (source_file, MLI, extracted_deps) :: !files let process_file_as process_fun def source_file = Compenv.readenv ppf (Before_compile source_file); load_path := []; List.iter add_to_load_path ( (!Compenv.last_include_dirs @ !Clflags.include_dirs @ !Compenv.first_include_dirs )); Location.input_name := source_file; try if Sys.file_exists source_file then process_fun source_file else def with x -> report_err x; def let process_file source_file ~ml_file ~mli_file ~def = if List.exists (Filename.check_suffix source_file) !ml_synonyms then process_file_as ml_file def source_file else if List.exists (Filename.check_suffix source_file) !mli_synonyms then process_file_as mli_file def source_file else def let file_dependencies source_file = process_file source_file ~def:() ~ml_file:ml_file_dependencies ~mli_file:mli_file_dependencies let file_dependencies_as kind = match kind with | ML -> process_file_as ml_file_dependencies () | MLI -> process_file_as mli_file_dependencies () let sort_files_by_dependencies files = let h = Hashtbl.create 31 in let worklist = ref [] in (* Init Hashtbl with all defined modules *) let files = List.map (fun (file, file_kind, deps) -> let modname = String.capitalize_ascii (Filename.chop_extension (Filename.basename file)) in let key = (modname, file_kind) in let new_deps = ref [] in Hashtbl.add h key (file, new_deps); worklist := key :: !worklist; (modname, file_kind, deps, new_deps) ) files in (* Keep only dependencies to defined modules *) List.iter (fun (modname, file_kind, deps, new_deps) -> let add_dep modname kind = new_deps := (modname, kind) :: !new_deps; in Depend.StringSet.iter (fun modname -> match file_kind with ML depends both on ML and MLI if Hashtbl.mem h (modname, MLI) then add_dep modname MLI; if Hashtbl.mem h (modname, ML) then add_dep modname ML MLI depends on MLI if exists , or ML otherwise if Hashtbl.mem h (modname, MLI) then add_dep modname MLI else if Hashtbl.mem h (modname, ML) then add_dep modname ML ) deps; add dep from .ml to .mli if Hashtbl.mem h (modname, MLI) then add_dep modname MLI ) files; (* Print and remove all files with no remaining dependency. Iterate until all files have been removed (worklist is empty) or no file was removed during a turn (cycle). *) let printed = ref true in while !printed && !worklist <> [] do let files = !worklist in worklist := []; printed := false; List.iter (fun key -> let (file, deps) = Hashtbl.find h key in let set = !deps in deps := []; List.iter (fun key -> if Hashtbl.mem h key then deps := key :: !deps ) set; if !deps = [] then begin printed := true; Printf.printf "%s " file; Hashtbl.remove h key; end else worklist := key :: !worklist ) files done; if !worklist <> [] then begin Format.fprintf Format.err_formatter "@[Warning: cycle in dependencies. End of list is not sorted.@]@."; let sorted_deps = let li = ref [] in Hashtbl.iter (fun _ file_deps -> li := file_deps :: !li) h; List.sort (fun (file1, _) (file2, _) -> String.compare file1 file2) !li in List.iter (fun (file, deps) -> Format.fprintf Format.err_formatter "\t@[%s: " file; List.iter (fun (modname, kind) -> Format.fprintf Format.err_formatter "%s.%s " modname (if kind=ML then "ml" else "mli"); ) !deps; Format.fprintf Format.err_formatter "@]@."; Printf.printf "%s " file) sorted_deps; end; Printf.printf "\n%!"; () (* Map *) let rec dump_map s0 ppf m = let open Depend in StringMap.iter (fun key (Node(s1,m')) -> let s = StringSet.diff s1 s0 in if StringSet.is_empty s then Format.fprintf ppf "@ @[<hv2>module %s : sig%a@;<1 -2>end@]" key (dump_map (StringSet.union s1 s0)) m' else Format.fprintf ppf "@ module %s = %s" key (StringSet.choose s)) m let process_ml_map = read_parse_and_extract Parse.implementation Depend.add_implementation_binding StringMap.empty Pparse.Structure let process_mli_map = read_parse_and_extract Parse.interface Depend.add_signature_binding StringMap.empty Pparse.Signature let parse_map fname = map_files := fname :: !map_files ; let old_transp = !Clflags.transparent_modules in Clflags.transparent_modules := true; let (deps, m) = process_file fname ~def:(Depend.StringSet.empty, StringMap.empty) ~ml_file:process_ml_map ~mli_file:process_mli_map in Clflags.transparent_modules := old_transp; let modname = String.capitalize_ascii (Filename.basename (Filename.chop_extension fname)) in if StringMap.is_empty m then report_err (Failure (fname ^ " : empty map file or parse error")); let mm = Depend.make_node m in if !debug then begin Format.printf "@[<v>%s:%t%a@]@." fname (fun ppf -> Depend.StringSet.iter (Format.fprintf ppf " %s") deps) (dump_map deps) (StringMap.add modname mm StringMap.empty) end; let mm = Depend.(weaken_map (StringSet.singleton modname) mm) in module_map := StringMap.add modname mm !module_map ;; (* Entry point *) let usage = "Usage: ocamldep [options] <source files>\nOptions are:" let print_version () = Format.printf "ocamldep, version %s@." Sys.ocaml_version; exit 0; ;; let print_version_num () = Format.printf "%s@." Sys.ocaml_version; exit 0; ;; let _ = Clflags.classic := false; add_to_list first_include_dirs Filename.current_dir_name; Compenv.readenv ppf Before_args; Arg.parse [ "-absname", Arg.Set Location.absname, " Show absolute filenames in error messages"; "-all", Arg.Set all_dependencies, " Generate dependencies on all files"; "-allow-approx", Arg.Set allow_approximation, " Fallback to a lexer-based approximation on unparseable files"; "-as-map", Arg.Set Clflags.transparent_modules, " Omit delayed dependencies for module aliases (-no-alias-deps -w -49)"; (* "compiler uses -no-alias-deps, and no module is coerced"; *) "-debug-map", Arg.Set debug, " Dump the delayed dependency map for each map file"; "-I", Arg.String (add_to_list Clflags.include_dirs), "<dir> Add <dir> to the list of include directories"; "-impl", Arg.String (file_dependencies_as ML), "<f> Process <f> as a .ml file"; "-intf", Arg.String (file_dependencies_as MLI), "<f> Process <f> as a .mli file"; "-map", Arg.String parse_map, "<f> Read <f> and propagate delayed dependencies to following files"; "-ml-synonym", Arg.String(add_to_synonym_list ml_synonyms), "<e> Consider <e> as a synonym of the .ml extension"; "-mli-synonym", Arg.String(add_to_synonym_list mli_synonyms), "<e> Consider <e> as a synonym of the .mli extension"; "-modules", Arg.Set raw_dependencies, " Print module dependencies in raw form (not suitable for make)"; "-native", Arg.Set native_only, " Generate dependencies for native-code only (no .cmo files)"; "-bytecode", Arg.Set bytecode_only, " Generate dependencies for bytecode-code only (no .cmx files)"; "-one-line", Arg.Set one_line, " Output one line per file, regardless of the length"; "-open", Arg.String (add_to_list Clflags.open_modules), "<module> Opens the module <module> before typing"; "-pp", Arg.String(fun s -> Clflags.preprocessor := Some s), "<cmd> Pipe sources through preprocessor <cmd>"; "-ppx", Arg.String (add_to_list first_ppx), "<cmd> Pipe abstract syntax trees through preprocessor <cmd>"; "-slash", Arg.Set Clflags.force_slash, " (Windows) Use forward slash / instead of backslash \\ in file paths"; "-sort", Arg.Set sort_files, " Sort files according to their dependencies"; "-version", Arg.Unit print_version, " Print version and exit"; "-vnum", Arg.Unit print_version_num, " Print version number and exit"; ] file_dependencies usage; Compenv.readenv ppf Before_link; if !sort_files then sort_files_by_dependencies !files else List.iter print_file_dependencies (List.sort compare !files); exit (if !error_occurred then 2 else 0)
null
https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/tools/ocamldep.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. ************************************************************************ Print the dependencies Find file 'name' (capitalized) in search path again, make-specific hack filter out "*predef*" Process one file Approximation when a file can't be parsed. Heuristic: - first component of any path starting with an uppercase character is a dependency. - always skip the token after a dot, unless dot is preceded by a lower-case identifier - always skip the token after a backquote macros: probably wrong Init Hashtbl with all defined modules Keep only dependencies to defined modules Print and remove all files with no remaining dependency. Iterate until all files have been removed (worklist is empty) or no file was removed during a turn (cycle). Map Entry point "compiler uses -no-alias-deps, and no module is coerced";
, projet Cristal , INRIA Rocquencourt Copyright 1999 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Compenv open Parsetree module StringMap = Depend.StringMap let ppf = Format.err_formatter type file_kind = ML | MLI;; let load_path = ref ([] : (string * string array) list) let ml_synonyms = ref [".ml"] let mli_synonyms = ref [".mli"] let native_only = ref false let bytecode_only = ref false let error_occurred = ref false let raw_dependencies = ref false let sort_files = ref false let all_dependencies = ref false let one_line = ref false let files = ref [] let allow_approximation = ref false let map_files = ref [] let module_map = ref StringMap.empty let debug = ref false Fix path to use ' / ' as directory separator instead of ' \ ' . Only under Windows . Only under Windows. *) let fix_slash s = if Sys.os_type = "Unix" then s else begin String.map (function '\\' -> '/' | c -> c) s end Since we reinitialize load_path after reading OCAMLCOMP , we must use a cache instead of calling Sys.readdir too often . we must use a cache instead of calling Sys.readdir too often. *) let dirs = ref StringMap.empty let readdir dir = try StringMap.find dir !dirs with Not_found -> let contents = try Sys.readdir dir with Sys_error msg -> Format.fprintf Format.err_formatter "@[Bad -I option: %s@]@." msg; error_occurred := true; [||] in dirs := StringMap.add dir contents !dirs; contents let add_to_list li s = li := s :: !li let add_to_load_path dir = try let dir = Misc.expand_directory Config.standard_library dir in let contents = readdir dir in add_to_list load_path (dir, contents) with Sys_error msg -> Format.fprintf Format.err_formatter "@[Bad -I option: %s@]@." msg; error_occurred := true let add_to_synonym_list synonyms suffix = if (String.length suffix) > 1 && suffix.[0] = '.' then add_to_list synonyms suffix else begin Format.fprintf Format.err_formatter "@[Bad suffix: '%s'@]@." suffix; error_occurred := true end let find_file name = let uname = String.uncapitalize_ascii name in let rec find_in_array a pos = if pos >= Array.length a then None else begin let s = a.(pos) in if s = name || s = uname then Some s else find_in_array a (pos + 1) end in let rec find_in_path = function [] -> raise Not_found | (dir, contents) :: rem -> match find_in_array contents 0 with Some truename -> if dir = "." then truename else Filename.concat dir truename | None -> find_in_path rem in find_in_path !load_path let rec find_file_in_list = function [] -> raise Not_found | x :: rem -> try find_file x with Not_found -> find_file_in_list rem let find_dependency target_kind modname (byt_deps, opt_deps) = try let candidates = List.map ((^) modname) !mli_synonyms in let filename = find_file_in_list candidates in let basename = Filename.chop_extension filename in let cmi_file = basename ^ ".cmi" in let cmx_file = basename ^ ".cmx" in let ml_exists = List.exists (fun ext -> Sys.file_exists (basename ^ ext)) !ml_synonyms in let new_opt_dep = if !all_dependencies then match target_kind with | MLI -> [ cmi_file ] | ML -> cmi_file :: (if ml_exists then [ cmx_file ] else []) else this is a make - specific hack that makes .cmx to be a ' proxy ' target that would force the dependency on via transitivity target that would force the dependency on .cmi via transitivity *) if ml_exists then [ cmx_file ] else [ cmi_file ] in ( cmi_file :: byt_deps, new_opt_dep @ opt_deps) with Not_found -> try " just .ml " case let candidates = List.map ((^) modname) !ml_synonyms in let filename = find_file_in_list candidates in let basename = Filename.chop_extension filename in let cmi_file = basename ^ ".cmi" in let cmx_file = basename ^ ".cmx" in let bytenames = if !all_dependencies then match target_kind with | MLI -> [ cmi_file ] | ML -> [ cmi_file ] else [basename ^ (if !native_only then ".cmx" else ".cmo")] in let optnames = if !all_dependencies then match target_kind with | MLI -> [ cmi_file ] | ML -> [ cmi_file; cmx_file ] else [ cmx_file ] in (bytenames @ byt_deps, optnames @ opt_deps) with Not_found -> (byt_deps, opt_deps) let (depends_on, escaped_eol) = (":", " \\\n ") let print_filename s = let s = if !Clflags.force_slash then fix_slash s else s in if not (String.contains s ' ') then begin print_string s; end else begin let rec count n i = if i >= String.length s then n else if s.[i] = ' ' then count (n+1) (i+1) else count n (i+1) in let spaces = count 0 0 in let result = Bytes.create (String.length s + spaces) in let rec loop i j = if i >= String.length s then () else if s.[i] = ' ' then begin Bytes.set result j '\\'; Bytes.set result (j+1) ' '; loop (i+1) (j+2); end else begin Bytes.set result j s.[i]; loop (i+1) (j+1); end in loop 0 0; print_bytes result; end ;; let print_dependencies target_files deps = let rec print_items pos = function [] -> print_string "\n" | dep :: rem -> if !one_line || (pos + 1 + String.length dep <= 77) then begin if pos <> 0 then print_string " "; print_filename dep; print_items (pos + String.length dep + 1) rem end else begin print_string escaped_eol; print_filename dep; print_items (String.length dep + 4) rem end in print_items 0 (target_files @ [depends_on] @ deps) let print_raw_dependencies source_file deps = print_filename source_file; print_string depends_on; Depend.StringSet.iter (fun dep -> if (String.length dep > 0) && (match dep.[0] with | 'A'..'Z' | '\128'..'\255' -> true | _ -> false) then begin print_char ' '; print_string dep end) deps; print_char '\n' let report_err exn = error_occurred := true; match exn with | Sys_error msg -> Format.fprintf Format.err_formatter "@[I/O error:@ %s@]@." msg | x -> match Location.error_of_exn x with | Some err -> Format.fprintf Format.err_formatter "@[%a@]@." Location.report_error err | None -> raise x let tool_name = "ocamldep" let rec lexical_approximation lexbuf = try let rec process after_lident lexbuf = match Lexer.token lexbuf with | Parser.UIDENT name -> Depend.free_structure_names := Depend.StringSet.add name !Depend.free_structure_names; process false lexbuf | Parser.LIDENT _ -> process true lexbuf | Parser.DOT when after_lident -> process false lexbuf | Parser.DOT | Parser.BACKQUOTE -> skip_one lexbuf | Parser.EOF -> () | _ -> process false lexbuf and skip_one lexbuf = match Lexer.token lexbuf with | Parser.DOT | Parser.BACKQUOTE -> skip_one lexbuf | Parser.EOF -> () | _ -> process false lexbuf in process false lexbuf with Lexer.Error _ -> lexical_approximation lexbuf let read_and_approximate inputfile = error_occurred := false; Depend.free_structure_names := Depend.StringSet.empty; let ic = open_in_bin inputfile in try seek_in ic 0; Location.input_name := inputfile; let lexbuf = Lexing.from_channel ic in Location.init lexbuf inputfile; lexical_approximation lexbuf; close_in ic; !Depend.free_structure_names with exn -> close_in ic; report_err exn; !Depend.free_structure_names let read_parse_and_extract parse_function extract_function def ast_kind source_file = Depend.free_structure_names := Depend.StringSet.empty; try let input_file = Pparse.preprocess source_file in begin try let ast = Pparse.file ~tool_name Format.err_formatter input_file parse_function ast_kind in let bound_vars = List.fold_left (fun bv modname -> Depend.open_module bv (Longident.Lident modname)) PR#7248 in let r = extract_function bound_vars ast in Pparse.remove_preprocessed input_file; (!Depend.free_structure_names, r) with x -> Pparse.remove_preprocessed input_file; raise x end with x -> begin report_err x; if not !allow_approximation then (Depend.StringSet.empty, def) else (read_and_approximate source_file, def) end let print_ml_dependencies source_file extracted_deps = let basename = Filename.chop_extension source_file in let byte_targets = [ basename ^ ".cmo" ] in let native_targets = if !all_dependencies then [ basename ^ ".cmx"; basename ^ ".o" ] else [ basename ^ ".cmx" ] in let init_deps = if !all_dependencies then [source_file] else [] in let cmi_name = basename ^ ".cmi" in let init_deps, extra_targets = if List.exists (fun ext -> Sys.file_exists (basename ^ ext)) !mli_synonyms then (cmi_name :: init_deps, cmi_name :: init_deps), [] else (init_deps, init_deps), (if !all_dependencies then [cmi_name] else []) in let (byt_deps, native_deps) = Depend.StringSet.fold (find_dependency ML) extracted_deps init_deps in if not !native_only then print_dependencies (byte_targets @ extra_targets) byt_deps; if not !bytecode_only then print_dependencies (native_targets @ extra_targets) native_deps let print_mli_dependencies source_file extracted_deps = let basename = Filename.chop_extension source_file in let (byt_deps, _opt_deps) = Depend.StringSet.fold (find_dependency MLI) extracted_deps ([], []) in print_dependencies [basename ^ ".cmi"] byt_deps let print_file_dependencies (source_file, kind, extracted_deps) = if !raw_dependencies then begin print_raw_dependencies source_file extracted_deps end else match kind with | ML -> print_ml_dependencies source_file extracted_deps | MLI -> print_mli_dependencies source_file extracted_deps let ml_file_dependencies source_file = let parse_use_file_as_impl lexbuf = let f x = match x with | Ptop_def s -> s | Ptop_dir _ -> [] in List.flatten (List.map f (Parse.use_file lexbuf)) in let (extracted_deps, ()) = read_parse_and_extract parse_use_file_as_impl Depend.add_implementation () Pparse.Structure source_file in files := (source_file, ML, extracted_deps) :: !files let mli_file_dependencies source_file = let (extracted_deps, ()) = read_parse_and_extract Parse.interface Depend.add_signature () Pparse.Signature source_file in files := (source_file, MLI, extracted_deps) :: !files let process_file_as process_fun def source_file = Compenv.readenv ppf (Before_compile source_file); load_path := []; List.iter add_to_load_path ( (!Compenv.last_include_dirs @ !Clflags.include_dirs @ !Compenv.first_include_dirs )); Location.input_name := source_file; try if Sys.file_exists source_file then process_fun source_file else def with x -> report_err x; def let process_file source_file ~ml_file ~mli_file ~def = if List.exists (Filename.check_suffix source_file) !ml_synonyms then process_file_as ml_file def source_file else if List.exists (Filename.check_suffix source_file) !mli_synonyms then process_file_as mli_file def source_file else def let file_dependencies source_file = process_file source_file ~def:() ~ml_file:ml_file_dependencies ~mli_file:mli_file_dependencies let file_dependencies_as kind = match kind with | ML -> process_file_as ml_file_dependencies () | MLI -> process_file_as mli_file_dependencies () let sort_files_by_dependencies files = let h = Hashtbl.create 31 in let worklist = ref [] in let files = List.map (fun (file, file_kind, deps) -> let modname = String.capitalize_ascii (Filename.chop_extension (Filename.basename file)) in let key = (modname, file_kind) in let new_deps = ref [] in Hashtbl.add h key (file, new_deps); worklist := key :: !worklist; (modname, file_kind, deps, new_deps) ) files in List.iter (fun (modname, file_kind, deps, new_deps) -> let add_dep modname kind = new_deps := (modname, kind) :: !new_deps; in Depend.StringSet.iter (fun modname -> match file_kind with ML depends both on ML and MLI if Hashtbl.mem h (modname, MLI) then add_dep modname MLI; if Hashtbl.mem h (modname, ML) then add_dep modname ML MLI depends on MLI if exists , or ML otherwise if Hashtbl.mem h (modname, MLI) then add_dep modname MLI else if Hashtbl.mem h (modname, ML) then add_dep modname ML ) deps; add dep from .ml to .mli if Hashtbl.mem h (modname, MLI) then add_dep modname MLI ) files; let printed = ref true in while !printed && !worklist <> [] do let files = !worklist in worklist := []; printed := false; List.iter (fun key -> let (file, deps) = Hashtbl.find h key in let set = !deps in deps := []; List.iter (fun key -> if Hashtbl.mem h key then deps := key :: !deps ) set; if !deps = [] then begin printed := true; Printf.printf "%s " file; Hashtbl.remove h key; end else worklist := key :: !worklist ) files done; if !worklist <> [] then begin Format.fprintf Format.err_formatter "@[Warning: cycle in dependencies. End of list is not sorted.@]@."; let sorted_deps = let li = ref [] in Hashtbl.iter (fun _ file_deps -> li := file_deps :: !li) h; List.sort (fun (file1, _) (file2, _) -> String.compare file1 file2) !li in List.iter (fun (file, deps) -> Format.fprintf Format.err_formatter "\t@[%s: " file; List.iter (fun (modname, kind) -> Format.fprintf Format.err_formatter "%s.%s " modname (if kind=ML then "ml" else "mli"); ) !deps; Format.fprintf Format.err_formatter "@]@."; Printf.printf "%s " file) sorted_deps; end; Printf.printf "\n%!"; () let rec dump_map s0 ppf m = let open Depend in StringMap.iter (fun key (Node(s1,m')) -> let s = StringSet.diff s1 s0 in if StringSet.is_empty s then Format.fprintf ppf "@ @[<hv2>module %s : sig%a@;<1 -2>end@]" key (dump_map (StringSet.union s1 s0)) m' else Format.fprintf ppf "@ module %s = %s" key (StringSet.choose s)) m let process_ml_map = read_parse_and_extract Parse.implementation Depend.add_implementation_binding StringMap.empty Pparse.Structure let process_mli_map = read_parse_and_extract Parse.interface Depend.add_signature_binding StringMap.empty Pparse.Signature let parse_map fname = map_files := fname :: !map_files ; let old_transp = !Clflags.transparent_modules in Clflags.transparent_modules := true; let (deps, m) = process_file fname ~def:(Depend.StringSet.empty, StringMap.empty) ~ml_file:process_ml_map ~mli_file:process_mli_map in Clflags.transparent_modules := old_transp; let modname = String.capitalize_ascii (Filename.basename (Filename.chop_extension fname)) in if StringMap.is_empty m then report_err (Failure (fname ^ " : empty map file or parse error")); let mm = Depend.make_node m in if !debug then begin Format.printf "@[<v>%s:%t%a@]@." fname (fun ppf -> Depend.StringSet.iter (Format.fprintf ppf " %s") deps) (dump_map deps) (StringMap.add modname mm StringMap.empty) end; let mm = Depend.(weaken_map (StringSet.singleton modname) mm) in module_map := StringMap.add modname mm !module_map ;; let usage = "Usage: ocamldep [options] <source files>\nOptions are:" let print_version () = Format.printf "ocamldep, version %s@." Sys.ocaml_version; exit 0; ;; let print_version_num () = Format.printf "%s@." Sys.ocaml_version; exit 0; ;; let _ = Clflags.classic := false; add_to_list first_include_dirs Filename.current_dir_name; Compenv.readenv ppf Before_args; Arg.parse [ "-absname", Arg.Set Location.absname, " Show absolute filenames in error messages"; "-all", Arg.Set all_dependencies, " Generate dependencies on all files"; "-allow-approx", Arg.Set allow_approximation, " Fallback to a lexer-based approximation on unparseable files"; "-as-map", Arg.Set Clflags.transparent_modules, " Omit delayed dependencies for module aliases (-no-alias-deps -w -49)"; "-debug-map", Arg.Set debug, " Dump the delayed dependency map for each map file"; "-I", Arg.String (add_to_list Clflags.include_dirs), "<dir> Add <dir> to the list of include directories"; "-impl", Arg.String (file_dependencies_as ML), "<f> Process <f> as a .ml file"; "-intf", Arg.String (file_dependencies_as MLI), "<f> Process <f> as a .mli file"; "-map", Arg.String parse_map, "<f> Read <f> and propagate delayed dependencies to following files"; "-ml-synonym", Arg.String(add_to_synonym_list ml_synonyms), "<e> Consider <e> as a synonym of the .ml extension"; "-mli-synonym", Arg.String(add_to_synonym_list mli_synonyms), "<e> Consider <e> as a synonym of the .mli extension"; "-modules", Arg.Set raw_dependencies, " Print module dependencies in raw form (not suitable for make)"; "-native", Arg.Set native_only, " Generate dependencies for native-code only (no .cmo files)"; "-bytecode", Arg.Set bytecode_only, " Generate dependencies for bytecode-code only (no .cmx files)"; "-one-line", Arg.Set one_line, " Output one line per file, regardless of the length"; "-open", Arg.String (add_to_list Clflags.open_modules), "<module> Opens the module <module> before typing"; "-pp", Arg.String(fun s -> Clflags.preprocessor := Some s), "<cmd> Pipe sources through preprocessor <cmd>"; "-ppx", Arg.String (add_to_list first_ppx), "<cmd> Pipe abstract syntax trees through preprocessor <cmd>"; "-slash", Arg.Set Clflags.force_slash, " (Windows) Use forward slash / instead of backslash \\ in file paths"; "-sort", Arg.Set sort_files, " Sort files according to their dependencies"; "-version", Arg.Unit print_version, " Print version and exit"; "-vnum", Arg.Unit print_version_num, " Print version number and exit"; ] file_dependencies usage; Compenv.readenv ppf Before_link; if !sort_files then sort_files_by_dependencies !files else List.iter print_file_dependencies (List.sort compare !files); exit (if !error_occurred then 2 else 0)
c12f0817faea7685e361d8213805f9d4c33bd2f6a826fed7f0aa68c2ed8503a2
songyahui/AlgebraicEffect
build_path_prefix_map.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet , INRIA Saclay (* *) Copyright 2017 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. *) (* *) (**************************************************************************) type path = string type path_prefix = string type error_message = string let errorf fmt = Printf.ksprintf (fun err -> Error err) fmt let encode_prefix str = let buf = Buffer.create (String.length str) in let push_char = function | '%' -> Buffer.add_string buf "%#" | '=' -> Buffer.add_string buf "%+" | ':' -> Buffer.add_string buf "%." | c -> Buffer.add_char buf c in String.iter push_char str; Buffer.contents buf let decode_prefix str = let buf = Buffer.create (String.length str) in let rec loop i = if i >= String.length str then Ok (Buffer.contents buf) else match str.[i] with | ('=' | ':') as c -> errorf "invalid character '%c' in key or value" c | '%' -> let push c = Buffer.add_char buf c; loop (i + 2) in if i + 1 = String.length str then errorf "invalid encoded string %S (trailing '%%')" str else begin match str.[i + 1] with | '#' -> push '%' | '+' -> push '=' | '.' -> push ':' | c -> errorf "invalid %%-escaped character '%c'" c end | c -> Buffer.add_char buf c; loop (i + 1) in loop 0 type pair = { target: path_prefix; source : path_prefix } let encode_pair { target; source } = String.concat "=" [encode_prefix target; encode_prefix source] let decode_pair str = match String.index str '=' with | exception Not_found -> errorf "invalid key/value pair %S, no '=' separator" str | equal_pos -> let encoded_target = String.sub str 0 equal_pos in let encoded_source = String.sub str (equal_pos + 1) (String.length str - equal_pos - 1) in match decode_prefix encoded_target, decode_prefix encoded_source with | Ok target, Ok source -> Ok { target; source } | ((Error _ as err), _) | (_, (Error _ as err)) -> err type map = pair option list let encode_map map = let encode_elem = function | None -> "" | Some pair -> encode_pair pair in List.map encode_elem map |> String.concat ":" let decode_map str = let exception Shortcut of error_message in let decode_or_empty = function | "" -> None | pair -> begin match decode_pair pair with | Ok str -> Some str | Error err -> raise (Shortcut err) end in let pairs = String.split_on_char ':' str in match List.map decode_or_empty pairs with | exception (Shortcut err) -> Error err | map -> Ok map let rewrite_opt prefix_map path = let is_prefix = function | None -> false | Some { target = _; source } -> String.length source <= String.length path && String.equal source (String.sub path 0 (String.length source)) in match List.find is_prefix (* read key/value pairs from right to left, as the spec demands *) (List.rev prefix_map) with | exception Not_found -> None | None -> None | Some { source; target } -> Some (target ^ (String.sub path (String.length source) (String.length path - String.length source))) let rewrite prefix_map path = match rewrite_opt prefix_map path with | None -> path | Some path -> path
null
https://raw.githubusercontent.com/songyahui/AlgebraicEffect/421afc58ed355f2ce1ada7e77733d7642c328815/parsing/build_path_prefix_map.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. ************************************************************************ read key/value pairs from right to left, as the spec demands
, projet , INRIA Saclay Copyright 2017 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the type path = string type path_prefix = string type error_message = string let errorf fmt = Printf.ksprintf (fun err -> Error err) fmt let encode_prefix str = let buf = Buffer.create (String.length str) in let push_char = function | '%' -> Buffer.add_string buf "%#" | '=' -> Buffer.add_string buf "%+" | ':' -> Buffer.add_string buf "%." | c -> Buffer.add_char buf c in String.iter push_char str; Buffer.contents buf let decode_prefix str = let buf = Buffer.create (String.length str) in let rec loop i = if i >= String.length str then Ok (Buffer.contents buf) else match str.[i] with | ('=' | ':') as c -> errorf "invalid character '%c' in key or value" c | '%' -> let push c = Buffer.add_char buf c; loop (i + 2) in if i + 1 = String.length str then errorf "invalid encoded string %S (trailing '%%')" str else begin match str.[i + 1] with | '#' -> push '%' | '+' -> push '=' | '.' -> push ':' | c -> errorf "invalid %%-escaped character '%c'" c end | c -> Buffer.add_char buf c; loop (i + 1) in loop 0 type pair = { target: path_prefix; source : path_prefix } let encode_pair { target; source } = String.concat "=" [encode_prefix target; encode_prefix source] let decode_pair str = match String.index str '=' with | exception Not_found -> errorf "invalid key/value pair %S, no '=' separator" str | equal_pos -> let encoded_target = String.sub str 0 equal_pos in let encoded_source = String.sub str (equal_pos + 1) (String.length str - equal_pos - 1) in match decode_prefix encoded_target, decode_prefix encoded_source with | Ok target, Ok source -> Ok { target; source } | ((Error _ as err), _) | (_, (Error _ as err)) -> err type map = pair option list let encode_map map = let encode_elem = function | None -> "" | Some pair -> encode_pair pair in List.map encode_elem map |> String.concat ":" let decode_map str = let exception Shortcut of error_message in let decode_or_empty = function | "" -> None | pair -> begin match decode_pair pair with | Ok str -> Some str | Error err -> raise (Shortcut err) end in let pairs = String.split_on_char ':' str in match List.map decode_or_empty pairs with | exception (Shortcut err) -> Error err | map -> Ok map let rewrite_opt prefix_map path = let is_prefix = function | None -> false | Some { target = _; source } -> String.length source <= String.length path && String.equal source (String.sub path 0 (String.length source)) in match List.find is_prefix (List.rev prefix_map) with | exception Not_found -> None | None -> None | Some { source; target } -> Some (target ^ (String.sub path (String.length source) (String.length path - String.length source))) let rewrite prefix_map path = match rewrite_opt prefix_map path with | None -> path | Some path -> path
3f6563af34eb676a95c59ac6714b2a7e6b30d69956846350312dad22dcb5da89
hjcapple/reading-sicp
exercise_3_61.scm
#lang racket P232 - [ 练习 3.61 ] (require "stream.scm") (require "infinite_stream.scm") (require "exercise_3_59.scm") ; for cosine-series、exp-series for mul - series (provide invert-unit-series) (define (neg-stream s) (scale-stream s -1)) (define (invert-unit-series s) (cons-stream 1 (neg-stream (mul-series (stream-cdr s) (invert-unit-series s))))) ;;;;;;;;;;;;;;;;; (module* main #f (define a (invert-unit-series cosine-series)) (stream-head->list (mul-series a cosine-series) 20) ; (1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) (define b (invert-unit-series exp-series)) (stream-head->list (mul-series b exp-series) 20) ; (1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) )
null
https://raw.githubusercontent.com/hjcapple/reading-sicp/7051d55dde841c06cf9326dc865d33d656702ecc/chapter_3/exercise_3_61.scm
scheme
for cosine-series、exp-series (1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) (1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
#lang racket P232 - [ 练习 3.61 ] (require "stream.scm") (require "infinite_stream.scm") for mul - series (provide invert-unit-series) (define (neg-stream s) (scale-stream s -1)) (define (invert-unit-series s) (cons-stream 1 (neg-stream (mul-series (stream-cdr s) (invert-unit-series s))))) (module* main #f (define a (invert-unit-series cosine-series)) (define b (invert-unit-series exp-series)) )
f6c760b6c01ccf0a49bd47d6b7e1cf95cfc2dcd26f8ec470694a0db04fb856af
vaclavsvejcar/headroom
TemplateRef.hs
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE FlexibleContexts # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # {-# LANGUAGE StrictData #-} # LANGUAGE TypeApplications # # LANGUAGE ViewPatterns # # LANGUAGE NoImplicitPrelude # -- | -- Module : Headroom.Template.TemplateRef -- Description : Representation of reference to template file Copyright : ( c ) 2019 - 2022 -- License : BSD-3-Clause -- Maintainer : -- Stability : experimental -- Portability : POSIX -- -- 'TemplateRef' data type represents reference to template file, either local or -- remote, which can be later opened/downloaded and parsed into template. module Headroom.Template.TemplateRef ( -- * Data Types TemplateRef (..) -- * Constructor Functions , mkTemplateRef -- * Public Functions , renderRef -- * Error Types , TemplateRefError (..) ) where import Data.Aeson ( FromJSON (..) , Value (String) ) import Data.String.Interpolate ( i , iii ) import Headroom.Data.EnumExtra (textToEnum) import Headroom.Data.Regex ( match , re ) import Headroom.FileType.Types (FileType (..)) import Headroom.Types ( LicenseType , fromHeadroomError , toHeadroomError ) import RIO import qualified RIO.Text as T import Text.URI ( URI (..) , mkURI ) import qualified Text.URI as URI --------------------------------- DATA TYPES --------------------------------- | Reference to the template ( e.g. local file , URI address ) . data TemplateRef = InlineRef Text | -- | template path on local file system LocalTemplateRef FilePath | remote template URI adress UriTemplateRef URI | BuiltInRef LicenseType FileType deriving (Eq, Ord, Show) instance FromJSON TemplateRef where parseJSON = \case String s -> maybe (error $ T.unpack s) pure (mkTemplateRef s) other -> error $ "Invalid value for template reference: " <> show other ------------------------------ PUBLIC FUNCTIONS ------------------------------ -- | Creates a 'TemplateRef' from given text. If the raw text appears to be valid URL with either @http@ or as protocol , it considers it as -- 'UriTemplateRef', otherwise it creates 'LocalTemplateRef'. -- > > > mkTemplateRef " /path / to / haskell.mustache " : : Maybe -- Just (LocalTemplateRef "/path/to/haskell.mustache") -- > > > mkTemplateRef " " : : Maybe -- Just (UriTemplateRef (URI {uriScheme = Just "https", uriAuthority = Right (Authority {authUserInfo = Nothing, authHost = "foo.bar", authPort = Nothing}), uriPath = Just (False,"haskell.mustache" :| []), uriQuery = [], uriFragment = Nothing})) mkTemplateRef :: MonadThrow m => Text -- ^ input text -> m TemplateRef -- ^ created 'TemplateRef' (or error) mkTemplateRef raw = case match [re|(^\w+):\/\/|] raw of Just (_ : p : _) | p `elem` ["http", "https"] -> uriTemplateRef | otherwise -> throwM $ UnsupportedUriProtocol p raw _ -> pure . LocalTemplateRef . T.unpack $ raw where uriTemplateRef = extractFileType >> UriTemplateRef <$> mkURI raw extractFileType = case match [re|(\w+)\.(\w+)$|] raw of Just (_ : (textToEnum @FileType -> (Just ft)) : _ : _) -> pure ft _ -> throwM $ UnrecognizedTemplateName raw ------------------------------ PUBLIC FUNCTIONS ------------------------------ -- | Renders given 'TemplateRef' into human-friendly text. renderRef :: TemplateRef -- ^ 'TemplateRef' to render -> Text -- ^ rendered text renderRef (InlineRef content) = [i|<inline template '#{content}'>|] renderRef (LocalTemplateRef path) = T.pack path renderRef (UriTemplateRef uri) = URI.render uri renderRef (BuiltInRef lt ft) = [i|<built-in template #{lt}/#{ft}>|] --------------------------------- ERROR TYPES -------------------------------- -- | Error related to template references. data TemplateRefError = -- | not a valid format for template name UnrecognizedTemplateName Text | -- | URI protocol not supported UnsupportedUriProtocol Text Text deriving (Eq, Show) instance Exception TemplateRefError where displayException = displayException' toException = toHeadroomError fromException = fromHeadroomError displayException' :: TemplateRefError -> String displayException' = \case UnrecognizedTemplateName raw -> [iii| Cannot extract file type and template type from path #{raw}. Please make sure that the path ends with '<FILE_TYPE>.<TEMPLATE_TYPE>', for example '/path/to/haskell.mustache'. |] UnsupportedUriProtocol protocol raw -> [iii| Protocol '#{protocol}' of in URI '#{raw}' is not supported. Make sure that you use either HTTP or HTTPS URIs. |]
null
https://raw.githubusercontent.com/vaclavsvejcar/headroom/3b20a89568248259d59f83f274f60f6e13d16f93/src/Headroom/Template/TemplateRef.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Module : Headroom.Template.TemplateRef Description : Representation of reference to template file License : BSD-3-Clause Maintainer : Stability : experimental Portability : POSIX 'TemplateRef' data type represents reference to template file, either local or remote, which can be later opened/downloaded and parsed into template. * Data Types * Constructor Functions * Public Functions * Error Types ------------------------------- DATA TYPES --------------------------------- | template path on local file system ---------------------------- PUBLIC FUNCTIONS ------------------------------ | Creates a 'TemplateRef' from given text. If the raw text appears to be 'UriTemplateRef', otherwise it creates 'LocalTemplateRef'. Just (LocalTemplateRef "/path/to/haskell.mustache") Just (UriTemplateRef (URI {uriScheme = Just "https", uriAuthority = Right (Authority {authUserInfo = Nothing, authHost = "foo.bar", authPort = Nothing}), uriPath = Just (False,"haskell.mustache" :| []), uriQuery = [], uriFragment = Nothing})) ^ input text ^ created 'TemplateRef' (or error) ---------------------------- PUBLIC FUNCTIONS ------------------------------ | Renders given 'TemplateRef' into human-friendly text. ^ 'TemplateRef' to render ^ rendered text ------------------------------- ERROR TYPES -------------------------------- | Error related to template references. | not a valid format for template name | URI protocol not supported
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE FlexibleContexts # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # # LANGUAGE TypeApplications # # LANGUAGE ViewPatterns # # LANGUAGE NoImplicitPrelude # Copyright : ( c ) 2019 - 2022 module Headroom.Template.TemplateRef TemplateRef (..) , mkTemplateRef , renderRef , TemplateRefError (..) ) where import Data.Aeson ( FromJSON (..) , Value (String) ) import Data.String.Interpolate ( i , iii ) import Headroom.Data.EnumExtra (textToEnum) import Headroom.Data.Regex ( match , re ) import Headroom.FileType.Types (FileType (..)) import Headroom.Types ( LicenseType , fromHeadroomError , toHeadroomError ) import RIO import qualified RIO.Text as T import Text.URI ( URI (..) , mkURI ) import qualified Text.URI as URI | Reference to the template ( e.g. local file , URI address ) . data TemplateRef = InlineRef Text LocalTemplateRef FilePath | remote template URI adress UriTemplateRef URI | BuiltInRef LicenseType FileType deriving (Eq, Ord, Show) instance FromJSON TemplateRef where parseJSON = \case String s -> maybe (error $ T.unpack s) pure (mkTemplateRef s) other -> error $ "Invalid value for template reference: " <> show other valid URL with either @http@ or as protocol , it considers it as > > > mkTemplateRef " /path / to / haskell.mustache " : : Maybe > > > mkTemplateRef " " : : Maybe mkTemplateRef :: MonadThrow m => Text -> m TemplateRef mkTemplateRef raw = case match [re|(^\w+):\/\/|] raw of Just (_ : p : _) | p `elem` ["http", "https"] -> uriTemplateRef | otherwise -> throwM $ UnsupportedUriProtocol p raw _ -> pure . LocalTemplateRef . T.unpack $ raw where uriTemplateRef = extractFileType >> UriTemplateRef <$> mkURI raw extractFileType = case match [re|(\w+)\.(\w+)$|] raw of Just (_ : (textToEnum @FileType -> (Just ft)) : _ : _) -> pure ft _ -> throwM $ UnrecognizedTemplateName raw renderRef :: TemplateRef -> Text renderRef (InlineRef content) = [i|<inline template '#{content}'>|] renderRef (LocalTemplateRef path) = T.pack path renderRef (UriTemplateRef uri) = URI.render uri renderRef (BuiltInRef lt ft) = [i|<built-in template #{lt}/#{ft}>|] data TemplateRefError UnrecognizedTemplateName Text UnsupportedUriProtocol Text Text deriving (Eq, Show) instance Exception TemplateRefError where displayException = displayException' toException = toHeadroomError fromException = fromHeadroomError displayException' :: TemplateRefError -> String displayException' = \case UnrecognizedTemplateName raw -> [iii| Cannot extract file type and template type from path #{raw}. Please make sure that the path ends with '<FILE_TYPE>.<TEMPLATE_TYPE>', for example '/path/to/haskell.mustache'. |] UnsupportedUriProtocol protocol raw -> [iii| Protocol '#{protocol}' of in URI '#{raw}' is not supported. Make sure that you use either HTTP or HTTPS URIs. |]
960ccf4b086f1aaeca54d1a381e530ed500fcb68793491b6fde17fdc112c3878
WormBase/wormbase_rest
core.clj
(ns rest-api.classes.phenotype.core (:require [clojure.string :as str] [datomic.api :as d] [pseudoace.utils :as pace-utils] [rest-api.classes.paper.core :as paper-core] [rest-api.formatters.object :as obj] [rest-api.formatters.object :as obj :refer [pack-obj]])) (defn- create-pato-term [id label entity-term entity-type pato-term] (let [pato-id (str/join "_" [id label pato-term])] {pato-id {:pato_evidence {:entity_term entity-term :entity_type label :pato_term pato-term} :key pato-id}})) (defn get-pato-from-holder [holder] (let [sot (for [eq-annotations {"anatomy-term" "anatomy-term" "life-stage" "life-stage" "go-term" "go-term" "molecule-affected" "molecule"} :let [[eq-key label] eq-annotations]] (for [eq-term ((keyword "phenotype-info" eq-key) holder)] (let [make-pi-kw (partial keyword (str "phenotype-info." eq-key)) pato-term-kw (make-pi-kw "pato-term") label-kw (make-pi-kw label) eq-kw (make-pi-kw eq-key) pato-names (:pato-term/name (-> eq-term (pato-term-kw))) pato-name (first pato-names) id ((keyword eq-key "id") (-> eq-term (eq-kw))) entity-term (pack-obj label (-> eq-term (label-kw))) pato-term (if (nil? pato-name) "abnormal" pato-name)] (if (pace-utils/not-nil? id) (create-pato-term id label entity-term (str/capitalize (str/replace eq-key #"-" "_")) pato-term))))) var-combo (into {} (for [x sot] (apply merge x)))] (if (> (count var-combo) 0) {(str/join "_" (sort (keys var-combo))) (vals var-combo)}))) (defn get-pato-combinations [db pid phenos] (if-let [tp (phenos pid)] (let [patos (for [t tp :let [holder (d/entity db t)]] (get-pato-from-holder holder))] (apply merge patos)))) (defn get-evidence [holder entity pheno] (pace-utils/vmap :Person_evidence (seq (for [person (:phenotype-info/person-evidence holder)] {:class "person" :id (:person/id person) :label (:person/standard-name person) :taxonomy "all"})) :Curator (seq (for [person (:phenotype-info/curator-confirmed holder)] {:class "person" :id (:person/id person) :label (:person/standard-name person) :taxonomy "all"})) :Paper_evidence (seq (for [paper (:phenotype-info/paper-evidence holder)] (paper-core/evidence paper))) :Remark (seq (map :phenotype-info.remark/text (:phenotype-info/remark holder))) :Recessive (if (contains? holder :phenotype-info/recessive) "") :Quantity_description (seq (map :phenotype-info.quantity-description/text (:phenotype-info/quantity-description holder))) :Dominant (if (contains? holder :phenotype-info/dominant) "") :Semi_dominant (if (contains? holder :phenotype-info/semi-dominant) (let [sd (:phenotype-info/semi-dominant holder)] (remove nil? [(if (contains? sd :evidence/person-evidence) (obj/tag-obj "Person_evidence")) (if (contains? sd :evidence/curator-confirmed) (obj/tag-obj "Curator_confirmed")) (if (contains? sd :evidence/paper-evidence) (obj/tag-obj "Paper_evidence"))]))) :Penetrance (first (remove nil? (flatten (conj (if (contains? holder :phenotype-info/low) (for [low-holder (:phenotype-info/low holder) :let [text (:phenotype-info.low/text low-holder)]] (if (not= text "") text))) (if (contains? holder :phenotype-info/high) (for [high-holder (:phenotype-info/high holder) :let [text (:phenotype-info.high/text high-holder)]] (if (not= text "") text))) (if (contains? holder :phenotype-info/complete) (for [complete-holder (:phenotype-info/complete holder) :let [text (:phenotype-info.complete/text complete-holder)]] (if (not= text "") text))))))) :Penetrance-range (if (pace-utils/not-nil? (:phenotype-info/range holder)) (let [range-holder (:phenotype-info/range holder)] (if (contains? range-holder :phenotype-info.range/int-b) (let [range (str/join "-" [(str (:phenotype-info.range/int-a range-holder)) (str (:phenotype-info.range/int-b range-holder))])] (if (= range "100-100") "100%" range)) (:phenotype-info.range/int-a range-holder)))) :Maternal (if (contains? holder :phenotype-info/maternal) (obj/tag-obj (obj/humanize-ident (:phenotype-info.maternal/value (:phenotype-info/maternal holder))))) :Paternal (if (contains? holder :phenotype-info/paternal) (obj/tag-obj (obj/humanize-ident (:phenotype-info.paternal/value (:phenotype-info/paternal holder))))) :Haplo_insufficient (if (contains? holder :phenotype-info/haplo-insufficient) (obj/tag-obj (obj/humanize-ident (:phenotype-info.paternal/value (:phenotype-info/haplo-insufficient holder))))) :Variation_effect (if (contains? holder :phenotype-info/variation-effect) (first ;; we should actually display all of them but catalyst template ;; not displaying nested array (for [ve (:phenotype-info/variation-effect holder)] (remove nil? [(obj/tag-obj (obj/humanize-ident (:phenotype-info.variation-effect/value ve))) (if (contains? ve :evidence/person-evidence) (obj/tag-obj "Person_evidence")) (if (contains? ve :evidence/curator-confirmed) (obj/tag-obj "Curator_confirmed")) (if (contains? ve :evidence/paper-evidence) (obj/tag-obj "Paper_evidence"))])))) :Affected_by_molecule (if (contains? holder :phenotype-info/molecule) (for [m (:phenotype-info/molecule holder)] (pack-obj (:phenotype-info.molecule/molecule m)))) :Affected_by_pathogen (if (contains? holder :phenotype-info/pathogen) (for [m (:phenotype-info/pathogen holder)] (pack-obj (:phenotype-info.molecule/species m)))) :Ease_of_scoring (if (contains? holder :phenotype-info/ease-of-scoring) (obj/tag-obj (obj/humanize-ident (:phenotype-info.ease-of-scoring/value (:phenotype-info/ease-of-scoring holder))))) :Caused_by_gene (if (contains? holder :phenotype-info/caused-by-gene) (let [cbgs (:phenotype-info/caused-by-gene holder)] (for [cbg cbgs] (pack-obj (:phenotype-info.caused-by-gene/gene cbg))))) :Phenotype_assay (if (contains? holder :phenotype-info/strain) (obj/tag-obj "Strain")) :Male_mating_efficiency (if (contains? entity :variation/male-mating-efficiency) (obj/humanize-ident (:variation.male-mating-efficiency/value (:variation/male-mating-efficiency entity)))) :Temperature_sensitive (if (or (contains? holder :phenotype-info/heat-sensitive) (contains? holder :phenotype-info/cold-sensitive)) (conj (if (contains? holder :phenotype-info/heat-sensitive) (obj/tag-obj "Heat-sensitive")) (if (contains? holder :phenotype-info/cold-sensitive) (obj/tag-obj "Cold-sensitive")))) :Treatment (if (contains? holder :phenotype-info/treatment) (first (for [treatment-holder (:phenotype-info/treatment holder) :let [text (:phenotype-info.treatment/text treatment-holder)]] (if-not (str/blank? text) text)))) :Temperature (if (contains? holder :phenotype-info/temperature) (first (for [temp-holder (:phenotype-info/temperature holder) :let [text (:phenotype-info.temperature/text temp-holder)]] (if-not (str/blank? text) text)))) :Ease_of_scoring nil))
null
https://raw.githubusercontent.com/WormBase/wormbase_rest/e51026f35b87d96260b62ddb5458a81ee911bf3a/src/rest_api/classes/phenotype/core.clj
clojure
we should actually display all of them but catalyst template not displaying nested array
(ns rest-api.classes.phenotype.core (:require [clojure.string :as str] [datomic.api :as d] [pseudoace.utils :as pace-utils] [rest-api.classes.paper.core :as paper-core] [rest-api.formatters.object :as obj] [rest-api.formatters.object :as obj :refer [pack-obj]])) (defn- create-pato-term [id label entity-term entity-type pato-term] (let [pato-id (str/join "_" [id label pato-term])] {pato-id {:pato_evidence {:entity_term entity-term :entity_type label :pato_term pato-term} :key pato-id}})) (defn get-pato-from-holder [holder] (let [sot (for [eq-annotations {"anatomy-term" "anatomy-term" "life-stage" "life-stage" "go-term" "go-term" "molecule-affected" "molecule"} :let [[eq-key label] eq-annotations]] (for [eq-term ((keyword "phenotype-info" eq-key) holder)] (let [make-pi-kw (partial keyword (str "phenotype-info." eq-key)) pato-term-kw (make-pi-kw "pato-term") label-kw (make-pi-kw label) eq-kw (make-pi-kw eq-key) pato-names (:pato-term/name (-> eq-term (pato-term-kw))) pato-name (first pato-names) id ((keyword eq-key "id") (-> eq-term (eq-kw))) entity-term (pack-obj label (-> eq-term (label-kw))) pato-term (if (nil? pato-name) "abnormal" pato-name)] (if (pace-utils/not-nil? id) (create-pato-term id label entity-term (str/capitalize (str/replace eq-key #"-" "_")) pato-term))))) var-combo (into {} (for [x sot] (apply merge x)))] (if (> (count var-combo) 0) {(str/join "_" (sort (keys var-combo))) (vals var-combo)}))) (defn get-pato-combinations [db pid phenos] (if-let [tp (phenos pid)] (let [patos (for [t tp :let [holder (d/entity db t)]] (get-pato-from-holder holder))] (apply merge patos)))) (defn get-evidence [holder entity pheno] (pace-utils/vmap :Person_evidence (seq (for [person (:phenotype-info/person-evidence holder)] {:class "person" :id (:person/id person) :label (:person/standard-name person) :taxonomy "all"})) :Curator (seq (for [person (:phenotype-info/curator-confirmed holder)] {:class "person" :id (:person/id person) :label (:person/standard-name person) :taxonomy "all"})) :Paper_evidence (seq (for [paper (:phenotype-info/paper-evidence holder)] (paper-core/evidence paper))) :Remark (seq (map :phenotype-info.remark/text (:phenotype-info/remark holder))) :Recessive (if (contains? holder :phenotype-info/recessive) "") :Quantity_description (seq (map :phenotype-info.quantity-description/text (:phenotype-info/quantity-description holder))) :Dominant (if (contains? holder :phenotype-info/dominant) "") :Semi_dominant (if (contains? holder :phenotype-info/semi-dominant) (let [sd (:phenotype-info/semi-dominant holder)] (remove nil? [(if (contains? sd :evidence/person-evidence) (obj/tag-obj "Person_evidence")) (if (contains? sd :evidence/curator-confirmed) (obj/tag-obj "Curator_confirmed")) (if (contains? sd :evidence/paper-evidence) (obj/tag-obj "Paper_evidence"))]))) :Penetrance (first (remove nil? (flatten (conj (if (contains? holder :phenotype-info/low) (for [low-holder (:phenotype-info/low holder) :let [text (:phenotype-info.low/text low-holder)]] (if (not= text "") text))) (if (contains? holder :phenotype-info/high) (for [high-holder (:phenotype-info/high holder) :let [text (:phenotype-info.high/text high-holder)]] (if (not= text "") text))) (if (contains? holder :phenotype-info/complete) (for [complete-holder (:phenotype-info/complete holder) :let [text (:phenotype-info.complete/text complete-holder)]] (if (not= text "") text))))))) :Penetrance-range (if (pace-utils/not-nil? (:phenotype-info/range holder)) (let [range-holder (:phenotype-info/range holder)] (if (contains? range-holder :phenotype-info.range/int-b) (let [range (str/join "-" [(str (:phenotype-info.range/int-a range-holder)) (str (:phenotype-info.range/int-b range-holder))])] (if (= range "100-100") "100%" range)) (:phenotype-info.range/int-a range-holder)))) :Maternal (if (contains? holder :phenotype-info/maternal) (obj/tag-obj (obj/humanize-ident (:phenotype-info.maternal/value (:phenotype-info/maternal holder))))) :Paternal (if (contains? holder :phenotype-info/paternal) (obj/tag-obj (obj/humanize-ident (:phenotype-info.paternal/value (:phenotype-info/paternal holder))))) :Haplo_insufficient (if (contains? holder :phenotype-info/haplo-insufficient) (obj/tag-obj (obj/humanize-ident (:phenotype-info.paternal/value (:phenotype-info/haplo-insufficient holder))))) :Variation_effect (if (contains? holder :phenotype-info/variation-effect) (first (for [ve (:phenotype-info/variation-effect holder)] (remove nil? [(obj/tag-obj (obj/humanize-ident (:phenotype-info.variation-effect/value ve))) (if (contains? ve :evidence/person-evidence) (obj/tag-obj "Person_evidence")) (if (contains? ve :evidence/curator-confirmed) (obj/tag-obj "Curator_confirmed")) (if (contains? ve :evidence/paper-evidence) (obj/tag-obj "Paper_evidence"))])))) :Affected_by_molecule (if (contains? holder :phenotype-info/molecule) (for [m (:phenotype-info/molecule holder)] (pack-obj (:phenotype-info.molecule/molecule m)))) :Affected_by_pathogen (if (contains? holder :phenotype-info/pathogen) (for [m (:phenotype-info/pathogen holder)] (pack-obj (:phenotype-info.molecule/species m)))) :Ease_of_scoring (if (contains? holder :phenotype-info/ease-of-scoring) (obj/tag-obj (obj/humanize-ident (:phenotype-info.ease-of-scoring/value (:phenotype-info/ease-of-scoring holder))))) :Caused_by_gene (if (contains? holder :phenotype-info/caused-by-gene) (let [cbgs (:phenotype-info/caused-by-gene holder)] (for [cbg cbgs] (pack-obj (:phenotype-info.caused-by-gene/gene cbg))))) :Phenotype_assay (if (contains? holder :phenotype-info/strain) (obj/tag-obj "Strain")) :Male_mating_efficiency (if (contains? entity :variation/male-mating-efficiency) (obj/humanize-ident (:variation.male-mating-efficiency/value (:variation/male-mating-efficiency entity)))) :Temperature_sensitive (if (or (contains? holder :phenotype-info/heat-sensitive) (contains? holder :phenotype-info/cold-sensitive)) (conj (if (contains? holder :phenotype-info/heat-sensitive) (obj/tag-obj "Heat-sensitive")) (if (contains? holder :phenotype-info/cold-sensitive) (obj/tag-obj "Cold-sensitive")))) :Treatment (if (contains? holder :phenotype-info/treatment) (first (for [treatment-holder (:phenotype-info/treatment holder) :let [text (:phenotype-info.treatment/text treatment-holder)]] (if-not (str/blank? text) text)))) :Temperature (if (contains? holder :phenotype-info/temperature) (first (for [temp-holder (:phenotype-info/temperature holder) :let [text (:phenotype-info.temperature/text temp-holder)]] (if-not (str/blank? text) text)))) :Ease_of_scoring nil))
dfe4610299beee39c72be966444d806c813739bbfe59f4ad4efdc49100a16fa3
alvatar/spheres
concurrency-termite.scm
(load (spheres/util test)) ;;------------------------------------------------------------------------------- ;; Multiple-instance tests Node 2 (define (spawn-gambit code #!key (flags-string #f) (verbose #f)) ;; This is a hack transforming all ' into ` since they work in all cases and makes ;; life easier when passed as a string with ' delimiters to bash (let ((quotes->semiquotes (lambda (string) (let ((length (string-length string)) (transformed (string-copy string))) (let recur ((n 0)) (if (< n length) (begin (if (eq? #\' (string-ref string n)) (string-set! transformed n #\`)) (recur (+ n 1))) transformed)))))) (let ((code-string (quotes->semiquotes (object->string (cons 'begin code))))) (and verbose (begin (println "gambit-eval-here input code: ") (pp code) (println "gambit-eval-here string: ") (print code-string))) (open-process (list path: "gsi" arguments: (if flags-string (list flags-string "-e" code-string) (list "-e" code-string)) stdout-redirection: #f))))) (spawn-gambit '((load (spheres/concurrency termite)) (define node1 (make-node "localhost" 3001)) (define node2 (make-node "localhost" 3002)) (node-init node2) (thread-sleep! 6))) Wait to make sure is up and running (thread-sleep! 1) Node 1 (load (spheres/concurrency termite)) (define node1 (make-node "localhost" 3001)) (define node2 (make-node "localhost" 3002)) (node-init node1) ;;(debug (current-node)) (on node2 (lambda () (write 'success) (newline) (println "Termite task migration test successful!"))) (define pid (spawn (lambda () (migrate-task node2) (termite-info 'migration-ok!)))) ;;------------------------------------------------------------------------------- ;; Single-instance tests (test-begin "termite" 1) (test-equal "single instance messaging" (let () (define (worker) (let* ((msg (?)) (pid (car msg)) (fun (cadr msg)) (arg (caddr msg))) (! pid (fun arg)))) (define (pmap fun lst) ;; spawn workers (for-each (lambda (x) (let ((p (spawn worker))) (! p (list (self) fun x)))) lst) ;; collect results (let loop ((i (length lst)) (result '())) (if (= 0 i) (reverse result) (loop (- i 1) (cons (?) result))))) (define (f x) (thread-sleep! x) x) (pmap f (list 1 2 3 2 1))) '(1 1 2 2 3)) (test-end)
null
https://raw.githubusercontent.com/alvatar/spheres/568836f234a469ef70c69f4a2d9b56d41c3fc5bd/test/concurrency-termite.scm
scheme
------------------------------------------------------------------------------- Multiple-instance tests This is a hack transforming all ' into ` since they work in all cases and makes life easier when passed as a string with ' delimiters to bash (debug (current-node)) ------------------------------------------------------------------------------- Single-instance tests spawn workers collect results
(load (spheres/util test)) Node 2 (define (spawn-gambit code #!key (flags-string #f) (verbose #f)) (let ((quotes->semiquotes (lambda (string) (let ((length (string-length string)) (transformed (string-copy string))) (let recur ((n 0)) (if (< n length) (begin (if (eq? #\' (string-ref string n)) (string-set! transformed n #\`)) (recur (+ n 1))) transformed)))))) (let ((code-string (quotes->semiquotes (object->string (cons 'begin code))))) (and verbose (begin (println "gambit-eval-here input code: ") (pp code) (println "gambit-eval-here string: ") (print code-string))) (open-process (list path: "gsi" arguments: (if flags-string (list flags-string "-e" code-string) (list "-e" code-string)) stdout-redirection: #f))))) (spawn-gambit '((load (spheres/concurrency termite)) (define node1 (make-node "localhost" 3001)) (define node2 (make-node "localhost" 3002)) (node-init node2) (thread-sleep! 6))) Wait to make sure is up and running (thread-sleep! 1) Node 1 (load (spheres/concurrency termite)) (define node1 (make-node "localhost" 3001)) (define node2 (make-node "localhost" 3002)) (node-init node1) (on node2 (lambda () (write 'success) (newline) (println "Termite task migration test successful!"))) (define pid (spawn (lambda () (migrate-task node2) (termite-info 'migration-ok!)))) (test-begin "termite" 1) (test-equal "single instance messaging" (let () (define (worker) (let* ((msg (?)) (pid (car msg)) (fun (cadr msg)) (arg (caddr msg))) (! pid (fun arg)))) (define (pmap fun lst) (for-each (lambda (x) (let ((p (spawn worker))) (! p (list (self) fun x)))) lst) (let loop ((i (length lst)) (result '())) (if (= 0 i) (reverse result) (loop (- i 1) (cons (?) result))))) (define (f x) (thread-sleep! x) x) (pmap f (list 1 2 3 2 1))) '(1 1 2 2 3)) (test-end)
27275183e5bc7e74df9610d1613079d7734ee5681e24c8f4f0681a6050e11e2f
bootstrapworld/curr
NW6.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname NWComplete) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) (require "Teachpacks/bootstrap-teachpack.rkt") ;; DATA: The World is the x position of the dog , x position of the ruby , and y position of the cat (define-struct world (dogX rubyX catY)) ;; STARTING WORLD (define START (make-world 0 600 240)) (define NEXT (make-world 10 595 240)) (define BACKGROUND (bitmap "Teachpacks/teachpack-images/bg.jpg")) (define DANGER (bitmap "Teachpacks/teachpack-images/dog.png")) (define TARGET (scale .3 (bitmap "Teachpacks/teachpack-images/ruby.png"))) (define PLAYER (bitmap "Teachpacks/teachpack-images/ninja.png")) (define CLOUD (bitmap "Teachpacks/teachpack-images/clouds.png")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; GRAPHICS FUNCTIONS: ;; draw-world: world -> Image place DANGER , TARGET , CLOUD and PLAYER onto BACKGROUND at the right coordinates (define (draw-world w) (put-image PLAYER 320 (world-catY w) (put-image TARGET (world-rubyX w) 300 (put-image CLOUD 500 400 (put-image DANGER (world-dogX w) 400 BACKGROUND))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; UPDATING FUNCTIONS: ;; update-world: world -> world increase dogX by 10 , decrease rubyX by 5 (define (update-world w) (cond [(collide? 320 (world-catY w) (world-dogX w) 400) (make-world -50 (world-rubyX w) (world-catY w))] [(collide? 320 (world-catY w) (world-rubyX w) 300) (make-world (world-dogX w) 650 (world-catY w))] [(off-left? (world-rubyX w)) (make-world (world-dogX w) 700 (world-catY w))] [(off-right? (world-dogX w)) (make-world -100 (world-rubyX w) (world-catY w))] [else (make-world (+ (world-dogX w) 10) (- (world-rubyX w) 5) (world-catY w))])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; KEY EVENTS: ;; keypress: world string -> world ;; make catY respond to key events (define (keypress w key) (cond [(string=? key "up") (make-world (world-dogX w) (world-rubyX w) (+ (world-catY w) 10))] [(string=? key "down") (make-world (world-dogX w) (world-rubyX w) (- (world-catY w) 10))] [else (make-world (world-dogX w) (world-rubyX w) (world-catY w))])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TESTS FOR COND: ;; off-left? : number -> boolean ;; Checks whether an object has gone off the left side of the screen (define (off-left? x) (< x 0)) ;; off-right? : number -> boolean ;; Checks whether an object has gone off the right side of the screen (define (off-right? x) (> x 640)) ;; line-length : number number -> number ;; Finds 1D distance (define (line-length a b) (cond [(< a b) (- b a)] [else (- a b)])) ;; distance : number number number number -> number Finds the 2D distance between two points (define (distance x1 y1 x2 y2) (sqrt (+ (sq (line-length x1 x2)) (sq (line-length y1 y2))))) ;; collide? : number number number number -> boolean determines whether two objects are within 50 pixels of eachother (define (collide? x1 y1 x2 y2) (< (distance x1 y1 x2 y2) 50)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; big - bang using the START world ;; on a tick-event, use update-world ;; on a draw-event, use draw-world ;; on a key-event, use keypress (big-bang START (on-tick update-world) (to-draw draw-world) (on-key keypress) )
null
https://raw.githubusercontent.com/bootstrapworld/curr/443015255eacc1c902a29978df0e3e8e8f3b9430/courses/reactive/resources/source-files/NW6.rkt
racket
about the language level of this file in a form that our tools can easily process. DATA: STARTING WORLD GRAPHICS FUNCTIONS: draw-world: world -> Image UPDATING FUNCTIONS: update-world: world -> world KEY EVENTS: keypress: world string -> world make catY respond to key events TESTS FOR COND: off-left? : number -> boolean Checks whether an object has gone off the left side of the screen off-right? : number -> boolean Checks whether an object has gone off the right side of the screen line-length : number number -> number Finds 1D distance distance : number number number number -> number collide? : number number number number -> boolean on a tick-event, use update-world on a draw-event, use draw-world on a key-event, use keypress
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname NWComplete) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) (require "Teachpacks/bootstrap-teachpack.rkt") The World is the x position of the dog , x position of the ruby , and y position of the cat (define-struct world (dogX rubyX catY)) (define START (make-world 0 600 240)) (define NEXT (make-world 10 595 240)) (define BACKGROUND (bitmap "Teachpacks/teachpack-images/bg.jpg")) (define DANGER (bitmap "Teachpacks/teachpack-images/dog.png")) (define TARGET (scale .3 (bitmap "Teachpacks/teachpack-images/ruby.png"))) (define PLAYER (bitmap "Teachpacks/teachpack-images/ninja.png")) (define CLOUD (bitmap "Teachpacks/teachpack-images/clouds.png")) place DANGER , TARGET , CLOUD and PLAYER onto BACKGROUND at the right coordinates (define (draw-world w) (put-image PLAYER 320 (world-catY w) (put-image TARGET (world-rubyX w) 300 (put-image CLOUD 500 400 (put-image DANGER (world-dogX w) 400 BACKGROUND))))) increase dogX by 10 , decrease rubyX by 5 (define (update-world w) (cond [(collide? 320 (world-catY w) (world-dogX w) 400) (make-world -50 (world-rubyX w) (world-catY w))] [(collide? 320 (world-catY w) (world-rubyX w) 300) (make-world (world-dogX w) 650 (world-catY w))] [(off-left? (world-rubyX w)) (make-world (world-dogX w) 700 (world-catY w))] [(off-right? (world-dogX w)) (make-world -100 (world-rubyX w) (world-catY w))] [else (make-world (+ (world-dogX w) 10) (- (world-rubyX w) 5) (world-catY w))])) (define (keypress w key) (cond [(string=? key "up") (make-world (world-dogX w) (world-rubyX w) (+ (world-catY w) 10))] [(string=? key "down") (make-world (world-dogX w) (world-rubyX w) (- (world-catY w) 10))] [else (make-world (world-dogX w) (world-rubyX w) (world-catY w))])) (define (off-left? x) (< x 0)) (define (off-right? x) (> x 640)) (define (line-length a b) (cond [(< a b) (- b a)] [else (- a b)])) Finds the 2D distance between two points (define (distance x1 y1 x2 y2) (sqrt (+ (sq (line-length x1 x2)) (sq (line-length y1 y2))))) determines whether two objects are within 50 pixels of eachother (define (collide? x1 y1 x2 y2) (< (distance x1 y1 x2 y2) 50)) big - bang using the START world (big-bang START (on-tick update-world) (to-draw draw-world) (on-key keypress) )
5c36b0cbd3e8061ed4d96cee60b3babbb6410eb251b76bea690fb7b6d0ca6f78
ocaml-multicore/tezos
lqt_fa12_repr.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2021 Nomadic Labs < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) open Protocol open Alpha_context open Expr_common module Parameter = struct (* // ============================================================================= * // Entrypoints * // ============================================================================= *) (* Note: in the lqt_fa12 contract, [value] is a nat. Hence, it should always be positive *) type approve = {spender : Contract.t; value : Z.t} type mintOrBurn = {quantity : Z.t; target : Contract.t} Note : this wrapper does not implement a reprensentation for the entrypoints transfer , getAllowance , getBalance , getTotalSupply , as they are not used as of yet . entrypoints transfer, getAllowance, getBalance, getTotalSupply, as they are not used as of yet. *) type t = Approve of approve | MintOrBurn of mintOrBurn let approve p = assert (Z.lt Z.zero p.value || Z.equal Z.zero p.value) ; Approve p let mintOrBurn p = MintOrBurn p let approve_to_string {spender; value} = Format.asprintf "{ spender: %a; value: %a }" Contract.pp spender Z.pp_print value let mint_or_burn_to_string {quantity; target} = Format.asprintf "{ quantity: %a; target: %a }" Z.pp_print quantity Contract.pp target let to_string : t -> string = function | Approve p -> Format.asprintf "Approve %s" (approve_to_string p) | MintOrBurn p -> Format.asprintf "MintOrBurn %s" (mint_or_burn_to_string p) let entrypoint_of_parameter : t -> string = function | Approve _ -> "approve" | MintOrBurn _ -> "mintOrBurn" let pp fmt s = Format.fprintf fmt "%s" (to_string s) let eq s s' = s = s' let to_expr_rooted : loc:'a -> t -> ('a, Michelson_v1_primitives.prim) Tezos_micheline.Micheline.node = fun ~loc -> function | MintOrBurn {quantity; target} -> comb ~loc [int ~loc quantity; address_string ~loc target] | Approve {spender; value} -> comb ~loc [address_string ~loc spender; int ~loc value] let to_expr : loc:'a -> t -> ('a, Michelson_v1_primitives.prim) Tezos_micheline.Micheline.node = fun ~loc p -> let rooted = to_expr_rooted ~loc p in match p with | MintOrBurn _ -> right ~loc @@ left ~loc rooted | Approve _ -> left ~loc @@ left ~loc @@ left ~loc rooted let to_michelson_string e = let e = to_expr ~loc:0 e in Format.asprintf "%a" Michelson_v1_printer.print_expr (Micheline.strip_locations e) end (* // ============================================================================= * // Storage * // ============================================================================= *) module Storage = struct let pp_big_map_id fmt v = Z.pp_print fmt (Big_map.Id.unparse_to_z v) type t = { tokens : Big_map.Id.t; allowances : Big_map.Id.t; admin : Contract.t; totalSupply : Z.t; } let pp {tokens; allowances; admin; totalSupply} = Format.asprintf "{ tokens: %a; allowances: %a; admin: %a; totalSupply: %a}" Z.pp_print (Big_map.Id.unparse_to_z tokens) Z.pp_print (Big_map.Id.unparse_to_z allowances) Contract.pp admin Z.pp_print totalSupply let null : t = { tokens = Big_map.Id.parse_z Z.zero; allowances = Big_map.Id.parse_z Z.one; admin = Contract.implicit_contract Signature.Public_key_hash.zero; totalSupply = Z.zero; } let eq s s' = s = s' let to_expr : loc:'a -> t -> ('a, Michelson_v1_primitives.prim) Tezos_micheline.Micheline.node = fun ~loc {tokens; allowances; admin; totalSupply} -> comb ~loc [ big_map_id ~loc tokens; big_map_id ~loc allowances; address_string ~loc admin; int ~loc totalSupply; ] let to_michelson_string e = let e = to_expr ~loc:0 e in Format.asprintf "%a" Michelson_v1_printer.print_expr (Micheline.strip_locations e) type exn += Invalid_storage_expr of string (** Note: parses a storage unparsed in readable mode (as e.g. returned by [Alpha_services.Contract.storage]), so that contracts are represented by strings. *) let of_expr_exn : ('a, Michelson_v1_primitives.prim) Tezos_micheline.Micheline.node -> t = function | Tezos_micheline.Micheline.Prim ( _, Script.D_Pair, [ Tezos_micheline.Micheline.Int (_, tokens); Tezos_micheline.Micheline.Int (_, allowances); Tezos_micheline.Micheline.String (_, admin); Tezos_micheline.Micheline.Int (_, totalSupply); ], [] ) -> let tokens = Big_map.Id.parse_z tokens in let allowances = Big_map.Id.parse_z allowances in let admin = address_of_string_exn admin in {tokens; allowances; admin; totalSupply} | e -> let canonical = Micheline.strip_locations e in let msg = Format.asprintf "Not a valid LQT_FA1.2 storage: %s /// %a" (try Michelson_v1_printer.micheline_string_of_expression ~zero_loc:true canonical with Z.Overflow -> "Cannot represent as micheline due to overflowing Z -> int") Michelson_v1_printer.print_expr canonical in raise (Invalid_storage_expr msg) let get (ctxt : Context.t) ~(contract : Contract.t) : t tzresult Lwt.t = Context.Contract.storage ctxt contract >|=? Micheline.root >|=? of_expr_exn let get_alpha_context (ctxt : Context.t) : Alpha_context.t tzresult Lwt.t = (match ctxt with | B b -> (* can perhaps be retrieved through Raw_context.prepare ? *) Incremental.begin_construction b | I i -> return i) >|=? Incremental.alpha_ctxt let getBalance_opt (ctxt : Context.t) ~(contract : Contract.t) (owner : Script_typed_ir.address) = get ctxt ~contract >>=? fun storage -> let tokens = storage.tokens in get_alpha_context ctxt >>=? fun ctxt -> Script_ir_translator.hash_data ctxt Script_typed_ir.(address_t ~annot:None) owner >|= Environment.wrap_tzresult >>=? fun (address_hash, ctxt) -> Big_map.get_opt ctxt tokens address_hash >|= Environment.wrap_tzresult >>=? function | (_, Some canonical) -> ( match Tezos_micheline.Micheline.root canonical with | Tezos_micheline.Micheline.Int (_, amount) -> return @@ Some amount | _ -> assert false) | (_, None) -> return @@ None let getBalance (ctxt : Context.t) ~(contract : Contract.t) (owner : Script_typed_ir.address) = getBalance_opt ctxt ~contract owner >|=? Option.value ~default:Z.zero end let transaction (ctxt : Context.t) ~(contract : Contract.t) ~(src : Contract.t) ?(amount = Tez.zero) (parameters : Parameter.t) = let entrypoint = Parameter.entrypoint_of_parameter parameters in let rooted_param_lazy = parameters |> Parameter.to_expr_rooted ~loc:0 |> Micheline.strip_locations |> Alpha_context.Script.lazy_expr in Op.transaction ctxt src contract amount ~entrypoint ~parameters:rooted_param_lazy
null
https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_012_Psithaca/lib_protocol/test/helpers/lqt_fa12_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. *************************************************************************** // ============================================================================= * // Entrypoints * // ============================================================================= Note: in the lqt_fa12 contract, [value] is a nat. Hence, it should always be positive // ============================================================================= * // Storage * // ============================================================================= * Note: parses a storage unparsed in readable mode (as e.g. returned by [Alpha_services.Contract.storage]), so that contracts are represented by strings. can perhaps be retrieved through Raw_context.prepare ?
Copyright ( c ) 2021 Nomadic Labs < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING open Protocol open Alpha_context open Expr_common module Parameter = struct type approve = {spender : Contract.t; value : Z.t} type mintOrBurn = {quantity : Z.t; target : Contract.t} Note : this wrapper does not implement a reprensentation for the entrypoints transfer , getAllowance , getBalance , getTotalSupply , as they are not used as of yet . entrypoints transfer, getAllowance, getBalance, getTotalSupply, as they are not used as of yet. *) type t = Approve of approve | MintOrBurn of mintOrBurn let approve p = assert (Z.lt Z.zero p.value || Z.equal Z.zero p.value) ; Approve p let mintOrBurn p = MintOrBurn p let approve_to_string {spender; value} = Format.asprintf "{ spender: %a; value: %a }" Contract.pp spender Z.pp_print value let mint_or_burn_to_string {quantity; target} = Format.asprintf "{ quantity: %a; target: %a }" Z.pp_print quantity Contract.pp target let to_string : t -> string = function | Approve p -> Format.asprintf "Approve %s" (approve_to_string p) | MintOrBurn p -> Format.asprintf "MintOrBurn %s" (mint_or_burn_to_string p) let entrypoint_of_parameter : t -> string = function | Approve _ -> "approve" | MintOrBurn _ -> "mintOrBurn" let pp fmt s = Format.fprintf fmt "%s" (to_string s) let eq s s' = s = s' let to_expr_rooted : loc:'a -> t -> ('a, Michelson_v1_primitives.prim) Tezos_micheline.Micheline.node = fun ~loc -> function | MintOrBurn {quantity; target} -> comb ~loc [int ~loc quantity; address_string ~loc target] | Approve {spender; value} -> comb ~loc [address_string ~loc spender; int ~loc value] let to_expr : loc:'a -> t -> ('a, Michelson_v1_primitives.prim) Tezos_micheline.Micheline.node = fun ~loc p -> let rooted = to_expr_rooted ~loc p in match p with | MintOrBurn _ -> right ~loc @@ left ~loc rooted | Approve _ -> left ~loc @@ left ~loc @@ left ~loc rooted let to_michelson_string e = let e = to_expr ~loc:0 e in Format.asprintf "%a" Michelson_v1_printer.print_expr (Micheline.strip_locations e) end module Storage = struct let pp_big_map_id fmt v = Z.pp_print fmt (Big_map.Id.unparse_to_z v) type t = { tokens : Big_map.Id.t; allowances : Big_map.Id.t; admin : Contract.t; totalSupply : Z.t; } let pp {tokens; allowances; admin; totalSupply} = Format.asprintf "{ tokens: %a; allowances: %a; admin: %a; totalSupply: %a}" Z.pp_print (Big_map.Id.unparse_to_z tokens) Z.pp_print (Big_map.Id.unparse_to_z allowances) Contract.pp admin Z.pp_print totalSupply let null : t = { tokens = Big_map.Id.parse_z Z.zero; allowances = Big_map.Id.parse_z Z.one; admin = Contract.implicit_contract Signature.Public_key_hash.zero; totalSupply = Z.zero; } let eq s s' = s = s' let to_expr : loc:'a -> t -> ('a, Michelson_v1_primitives.prim) Tezos_micheline.Micheline.node = fun ~loc {tokens; allowances; admin; totalSupply} -> comb ~loc [ big_map_id ~loc tokens; big_map_id ~loc allowances; address_string ~loc admin; int ~loc totalSupply; ] let to_michelson_string e = let e = to_expr ~loc:0 e in Format.asprintf "%a" Michelson_v1_printer.print_expr (Micheline.strip_locations e) type exn += Invalid_storage_expr of string let of_expr_exn : ('a, Michelson_v1_primitives.prim) Tezos_micheline.Micheline.node -> t = function | Tezos_micheline.Micheline.Prim ( _, Script.D_Pair, [ Tezos_micheline.Micheline.Int (_, tokens); Tezos_micheline.Micheline.Int (_, allowances); Tezos_micheline.Micheline.String (_, admin); Tezos_micheline.Micheline.Int (_, totalSupply); ], [] ) -> let tokens = Big_map.Id.parse_z tokens in let allowances = Big_map.Id.parse_z allowances in let admin = address_of_string_exn admin in {tokens; allowances; admin; totalSupply} | e -> let canonical = Micheline.strip_locations e in let msg = Format.asprintf "Not a valid LQT_FA1.2 storage: %s /// %a" (try Michelson_v1_printer.micheline_string_of_expression ~zero_loc:true canonical with Z.Overflow -> "Cannot represent as micheline due to overflowing Z -> int") Michelson_v1_printer.print_expr canonical in raise (Invalid_storage_expr msg) let get (ctxt : Context.t) ~(contract : Contract.t) : t tzresult Lwt.t = Context.Contract.storage ctxt contract >|=? Micheline.root >|=? of_expr_exn let get_alpha_context (ctxt : Context.t) : Alpha_context.t tzresult Lwt.t = (match ctxt with | B b -> Incremental.begin_construction b | I i -> return i) >|=? Incremental.alpha_ctxt let getBalance_opt (ctxt : Context.t) ~(contract : Contract.t) (owner : Script_typed_ir.address) = get ctxt ~contract >>=? fun storage -> let tokens = storage.tokens in get_alpha_context ctxt >>=? fun ctxt -> Script_ir_translator.hash_data ctxt Script_typed_ir.(address_t ~annot:None) owner >|= Environment.wrap_tzresult >>=? fun (address_hash, ctxt) -> Big_map.get_opt ctxt tokens address_hash >|= Environment.wrap_tzresult >>=? function | (_, Some canonical) -> ( match Tezos_micheline.Micheline.root canonical with | Tezos_micheline.Micheline.Int (_, amount) -> return @@ Some amount | _ -> assert false) | (_, None) -> return @@ None let getBalance (ctxt : Context.t) ~(contract : Contract.t) (owner : Script_typed_ir.address) = getBalance_opt ctxt ~contract owner >|=? Option.value ~default:Z.zero end let transaction (ctxt : Context.t) ~(contract : Contract.t) ~(src : Contract.t) ?(amount = Tez.zero) (parameters : Parameter.t) = let entrypoint = Parameter.entrypoint_of_parameter parameters in let rooted_param_lazy = parameters |> Parameter.to_expr_rooted ~loc:0 |> Micheline.strip_locations |> Alpha_context.Script.lazy_expr in Op.transaction ctxt src contract amount ~entrypoint ~parameters:rooted_param_lazy
60a9df88078993a8ad14320090e27185955d72148ec500004808b31181b356f9
pirapira/coq2rust
cases.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) open Pp open Errors open Util open Names open Nameops open Term open Vars open Context open Termops open Namegen open Declarations open Inductiveops open Environ open Reductionops open Type_errors open Glob_term open Glob_ops open Retyping open Pretype_errors open Evarutil open Evarsolve open Evarconv open Evd (* Pattern-matching errors *) type pattern_matching_error = | BadPattern of constructor * constr | BadConstructor of constructor * inductive | WrongNumargConstructor of constructor * int | WrongNumargInductive of inductive * int | UnusedClause of cases_pattern list | NonExhaustive of cases_pattern list | CannotInferPredicate of (constr * types) array exception PatternMatchingError of env * evar_map * pattern_matching_error let raise_pattern_matching_error (loc,env,sigma,te) = Loc.raise loc (PatternMatchingError(env,sigma,te)) let error_bad_pattern_loc loc env sigma cstr ind = raise_pattern_matching_error (loc, env, sigma, BadPattern (cstr,ind)) let error_bad_constructor_loc loc env cstr ind = raise_pattern_matching_error (loc, env, Evd.empty, BadConstructor (cstr,ind)) let error_wrong_numarg_constructor_loc loc env c n = raise_pattern_matching_error (loc, env, Evd.empty, WrongNumargConstructor(c,n)) let error_wrong_numarg_inductive_loc loc env c n = raise_pattern_matching_error (loc, env, Evd.empty, WrongNumargInductive(c,n)) let rec list_try_compile f = function | [a] -> f a | [] -> anomaly (str "try_find_f") | h::t -> try f h with UserError _ | TypeError _ | PretypeError _ | PatternMatchingError _ -> list_try_compile f t let force_name = let nx = Name default_dependent_ident in function Anonymous -> nx | na -> na (************************************************************************) (* Pattern-matching compilation (Cases) *) (************************************************************************) (************************************************************************) (* Configuration, errors and warnings *) open Pp let msg_may_need_inversion () = strbrk "Found a matching with no clauses on a term unknown to have an empty inductive type." Utils let make_anonymous_patvars n = List.make n (PatVar (Loc.ghost,Anonymous)) We have x1 : t1 ... xn : , xi':ti , y1 .. yk |- c and re - generalize over xi : ti to get x1 : t1 ... xn : , xi':ti , y1 .. yk |- c[xi:=xi ' ] over xi:ti to get x1:t1...xn:tn,xi':ti,y1..yk |- c[xi:=xi'] *) let relocate_rel n1 n2 k j = if Int.equal j (n1 + k) then n2+k else j let rec relocate_index n1 n2 k t = match kind_of_term t with | Rel j when Int.equal j (n1 + k) -> mkRel (n2+k) | Rel j when j < n1+k -> t | Rel j when j > n1+k -> t | _ -> map_constr_with_binders succ (relocate_index n1 n2) k t (**********************************************************************) (* Structures used in compiling pattern-matching *) type 'a rhs = { rhs_env : env; rhs_vars : Id.t list; avoid_ids : Id.t list; it : 'a option} type 'a equation = { patterns : cases_pattern list; rhs : 'a rhs; alias_stack : Name.t list; eqn_loc : Loc.t; used : bool ref } type 'a matrix = 'a equation list 1st argument of IsInd is the original before extracting the summary type tomatch_type = | IsInd of types * inductive_type * Name.t list | NotInd of constr option * types spiwack : The first argument of [ Pushed ] is [ true ] for initial Pushed and [ false ] otherwise . Used to decide whether the term being matched on must be aliased in the variable case ( only initial Pushed need to be aliased ) . The first argument of [ ] is [ true ] if the alias was introduced by an initial pushed and [ false ] otherwise . Pushed and [false] otherwise. Used to decide whether the term being matched on must be aliased in the variable case (only initial Pushed need to be aliased). The first argument of [Alias] is [true] if the alias was introduced by an initial pushed and [false] otherwise.*) type tomatch_status = | Pushed of (bool*((constr * tomatch_type) * int list * Name.t)) | Alias of (bool*(Name.t * constr * (constr * types))) | NonDepAlias | Abstract of int * rel_declaration type tomatch_stack = tomatch_status list (* We keep a constr for aliases and a cases_pattern for error message *) type pattern_history = | Top | MakeConstructor of constructor * pattern_continuation and pattern_continuation = | Continuation of int * cases_pattern list * pattern_history | Result of cases_pattern list let start_history n = Continuation (n, [], Top) let feed_history arg = function | Continuation (n, l, h) when n>=1 -> Continuation (n-1, arg :: l, h) | Continuation (n, _, _) -> anomaly (str "Bad number of expected remaining patterns: " ++ int n) | Result _ -> anomaly (Pp.str "Exhausted pattern history") (* This is for non exhaustive error message *) let rec glob_pattern_of_partial_history args2 = function | Continuation (n, args1, h) -> let args3 = make_anonymous_patvars (n - (List.length args2)) in build_glob_pattern (List.rev_append args1 (args2@args3)) h | Result pl -> pl and build_glob_pattern args = function | Top -> args | MakeConstructor (pci, rh) -> glob_pattern_of_partial_history [PatCstr (Loc.ghost, pci, args, Anonymous)] rh let complete_history = glob_pattern_of_partial_history [] (* This is to build glued pattern-matching history and alias bodies *) let pop_history_pattern = function | Continuation (0, l, Top) -> Result (List.rev l) | Continuation (0, l, MakeConstructor (pci, rh)) -> feed_history (PatCstr (Loc.ghost,pci,List.rev l,Anonymous)) rh | _ -> anomaly (Pp.str "Constructor not yet filled with its arguments") let pop_history h = feed_history (PatVar (Loc.ghost, Anonymous)) h (* Builds a continuation expecting [n] arguments and building [ci] applied to this [n] arguments *) let push_history_pattern n pci cont = Continuation (n, [], MakeConstructor (pci, cont)) A pattern - matching problem has the following form : env , evd |- match terms_to_tomatch return pred with mat end where is some sequence of " instructions " ( t1 ... tp ) and mat is some matrix ( p11 ... p1n - > rhs1 ) ( ... ) ( pm1 ... pmn - > rhsm ) Terms to match : there are 3 kinds of instructions - " Pushed " terms to match are typed in [ env ] ; these are usually just Rel(n ) except for the initial terms given by user ; in Pushed ( ( c , tm),deps , na ) , [ c ] is the reference to the term ( which is a Rel or an initial term ) , [ tm ] is its type ( telling whether we know if it is an inductive type or not ) , [ ] is the list of terms to abstract before matching on [ c ] ( these are rels too ) - " Abstract " instructions mean that an abstraction has to be inserted in the current branch to build ( this means a pattern has been detected dependent in another one and a generalization is necessary to ensure well - typing ) Abstract instructions extend the [ env ] in which the other instructions are typed - " " instructions mean an alias has to be inserted ( this alias is usually removed at the end , except when its type is not the same as the type of the matched term from which it comes - typically because the inductive types are " real " parameters ) - " " instructions mean the completion of a matching over a term to match as for but without inserting this alias because there is no dependency in it Right - hand sides : They consist of a raw term to type in an environment specific to the clause they belong to : the names of declarations are those of the variables present in the patterns . Therefore , they come with their own [ rhs_env ] ( actually it is the same as [ env ] except for the names of variables ) . env, evd |- match terms_to_tomatch return pred with mat end where terms_to_match is some sequence of "instructions" (t1 ... tp) and mat is some matrix (p11 ... p1n -> rhs1) ( ... ) (pm1 ... pmn -> rhsm) Terms to match: there are 3 kinds of instructions - "Pushed" terms to match are typed in [env]; these are usually just Rel(n) except for the initial terms given by user; in Pushed ((c,tm),deps,na), [c] is the reference to the term (which is a Rel or an initial term), [tm] is its type (telling whether we know if it is an inductive type or not), [deps] is the list of terms to abstract before matching on [c] (these are rels too) - "Abstract" instructions mean that an abstraction has to be inserted in the current branch to build (this means a pattern has been detected dependent in another one and a generalization is necessary to ensure well-typing) Abstract instructions extend the [env] in which the other instructions are typed - "Alias" instructions mean an alias has to be inserted (this alias is usually removed at the end, except when its type is not the same as the type of the matched term from which it comes - typically because the inductive types are "real" parameters) - "NonDepAlias" instructions mean the completion of a matching over a term to match as for Alias but without inserting this alias because there is no dependency in it Right-hand sides: They consist of a raw term to type in an environment specific to the clause they belong to: the names of declarations are those of the variables present in the patterns. Therefore, they come with their own [rhs_env] (actually it is the same as [env] except for the names of variables). *) type 'a pattern_matching_problem = { env : env; evdref : evar_map ref; pred : constr; tomatch : tomatch_stack; history : pattern_continuation; mat : 'a matrix; caseloc : Loc.t; casestyle : case_style; typing_function: type_constraint -> env -> evar_map ref -> 'a option -> unsafe_judgment } -------------------------------------------------------------------------- * * A few functions to infer the inductive type from the patterns instead of * * checking that the patterns correspond to the ind . type of the * * destructurated object . Allows type inference of examples like * * match n with O = > true | _ = > false end * * match x in I with C = > true | _ = > false end * * -------------------------------------------------------------------------- * A few functions to infer the inductive type from the patterns instead of * * checking that the patterns correspond to the ind. type of the * * destructurated object. Allows type inference of examples like * * match n with O => true | _ => false end * * match x in I with C => true | _ => false end * *--------------------------------------------------------------------------*) (* Computing the inductive type from the matrix of patterns *) (* We use the "in I" clause to coerce the terms to match and otherwise use the constructor to know in which type is the matching problem Note that insertion of coercions inside nested patterns is done each time the matrix is expanded *) let rec find_row_ind = function [] -> None | PatVar _ :: l -> find_row_ind l | PatCstr(loc,c,_,_) :: _ -> Some (loc,c) let inductive_template evdref env tmloc ind = let indu = evd_comb1 (Evd.fresh_inductive_instance env) evdref ind in let arsign = inductive_alldecls_env env indu in let hole_source = match tmloc with | Some loc -> fun i -> (loc, Evar_kinds.TomatchTypeParameter (ind,i)) | None -> fun _ -> (Loc.ghost, Evar_kinds.InternalHole) in let (_,evarl,_) = List.fold_right (fun (na,b,ty) (subst,evarl,n) -> match b with | None -> let ty' = substl subst ty in let e = e_new_evar env evdref ~src:(hole_source n) ty' in (e::subst,e::evarl,n+1) | Some b -> (substl subst b::subst,evarl,n+1)) arsign ([],[],1) in applist (mkIndU indu,List.rev evarl) let try_find_ind env sigma typ realnames = let (IndType(_,realargs) as ind) = find_rectype env sigma typ in let names = match realnames with | Some names -> names | None -> List.make (List.length realargs) Anonymous in IsInd (typ,ind,names) let inh_coerce_to_ind evdref env loc ty tyi = let sigma = !evdref in let expected_typ = inductive_template evdref env loc tyi in (* Try to refine the type with inductive information coming from the constructor and renounce if not able to give more information *) devrait être indifférent d'exiger leq ou pas puisque pour un inductif cela doit être égal *) if not (e_cumul env evdref expected_typ ty) then evdref := sigma let binding_vars_of_inductive = function | NotInd _ -> [] | IsInd (_,IndType(_,realargs),_) -> List.filter isRel realargs let extract_inductive_data env sigma (_,b,t) = match b with | None -> let tmtyp = try try_find_ind env sigma t None with Not_found -> NotInd (None,t) in let tmtypvars = binding_vars_of_inductive tmtyp in (tmtyp,tmtypvars) | Some _ -> (NotInd (None, t), []) let unify_tomatch_with_patterns evdref env loc typ pats realnames = match find_row_ind pats with | None -> NotInd (None,typ) | Some (_,(ind,_)) -> inh_coerce_to_ind evdref env loc typ ind; try try_find_ind env !evdref typ realnames with Not_found -> NotInd (None,typ) let find_tomatch_tycon evdref env loc = function (* Try if some 'in I ...' is present and can be used as a constraint *) | Some (_,ind,realnal) -> mk_tycon (inductive_template evdref env loc ind),Some (List.rev realnal) | None -> empty_tycon,None let coerce_row typing_fun evdref env pats (tomatch,(_,indopt)) = let loc = Some (loc_of_glob_constr tomatch) in let tycon,realnames = find_tomatch_tycon evdref env loc indopt in let j = typing_fun tycon env evdref tomatch in let evd, j = Coercion.inh_coerce_to_base (loc_of_glob_constr tomatch) env !evdref j in evdref := evd; let typ = nf_evar !evdref j.uj_type in let t = try try_find_ind env !evdref typ realnames with Not_found -> unify_tomatch_with_patterns evdref env loc typ pats realnames in (j.uj_val,t) let coerce_to_indtype typing_fun evdref env matx tomatchl = let pats = List.map (fun r -> r.patterns) matx in let matx' = match matrix_transpose pats with | [] -> List.map (fun _ -> []) tomatchl (* no patterns at all *) | m -> m in List.map2 (coerce_row typing_fun evdref env) matx' tomatchl (************************************************************************) Utils let mkExistential env ?(src=(Loc.ghost,Evar_kinds.InternalHole)) evdref = let e, u = e_new_type_evar env evdref univ_flexible_alg ~src:src in e let evd_comb2 f evdref x y = let (evd',y) = f !evdref x y in evdref := evd'; y let adjust_tomatch_to_pattern pb ((current,typ),deps,dep) = (* Ideally, we could find a common inductive type to which both the term to match and the patterns coerce *) In practice , we coerce the term to match if it is not already an inductive type and it is not dependent ; moreover , we use only the first pattern type and forget about the others inductive type and it is not dependent; moreover, we use only the first pattern type and forget about the others *) let typ,names = match typ with IsInd(t,_,names) -> t,Some names | NotInd(_,t) -> t,None in let tmtyp = try try_find_ind pb.env !(pb.evdref) typ names with Not_found -> NotInd (None,typ) in match tmtyp with | NotInd (None,typ) -> let tm1 = List.map (fun eqn -> List.hd eqn.patterns) pb.mat in (match find_row_ind tm1 with | None -> (current,tmtyp) | Some (_,(ind,_)) -> let indt = inductive_template pb.evdref pb.env None ind in let current = if List.is_empty deps && isEvar typ then (* Don't insert coercions if dependent; only solve evars *) let _ = e_cumul pb.env pb.evdref indt typ in current else (evd_comb2 (Coercion.inh_conv_coerce_to true Loc.ghost pb.env) pb.evdref (make_judge current typ) indt).uj_val in let sigma = !(pb.evdref) in (current,try_find_ind pb.env sigma indt names)) | _ -> (current,tmtyp) let type_of_tomatch = function | IsInd (t,_,_) -> t | NotInd (_,t) -> t let map_tomatch_type f = function | IsInd (t,ind,names) -> IsInd (f t,map_inductive_type f ind,names) | NotInd (c,t) -> NotInd (Option.map f c, f t) let liftn_tomatch_type n depth = map_tomatch_type (liftn n depth) let lift_tomatch_type n = liftn_tomatch_type n 1 (**********************************************************************) Utilities on patterns let current_pattern eqn = match eqn.patterns with | pat::_ -> pat | [] -> anomaly (Pp.str "Empty list of patterns") let alias_of_pat = function | PatVar (_,name) -> name | PatCstr(_,_,_,name) -> name let remove_current_pattern eqn = match eqn.patterns with | pat::pats -> { eqn with patterns = pats; alias_stack = alias_of_pat pat :: eqn.alias_stack } | [] -> anomaly (Pp.str "Empty list of patterns") let push_current_pattern (cur,ty) eqn = match eqn.patterns with | pat::pats -> let rhs_env = push_rel (alias_of_pat pat,Some cur,ty) eqn.rhs.rhs_env in { eqn with rhs = { eqn.rhs with rhs_env = rhs_env }; patterns = pats } | [] -> anomaly (Pp.str "Empty list of patterns") (* spiwack: like [push_current_pattern] but does not introduce an alias in rhs_env. Aliasing binders are only useful for variables at the root of a pattern matching problem (initial push), so we distinguish the cases. *) let push_noalias_current_pattern eqn = match eqn.patterns with | _::pats -> { eqn with patterns = pats } | [] -> anomaly (Pp.str "push_noalias_current_pattern: Empty list of patterns") let prepend_pattern tms eqn = {eqn with patterns = } (**********************************************************************) (* Well-formedness tests *) (* Partial check on patterns *) exception NotAdjustable let rec adjust_local_defs loc = function | (pat :: pats, (_,None,_) :: decls) -> pat :: adjust_local_defs loc (pats,decls) | (pats, (_,Some _,_) :: decls) -> PatVar (loc, Anonymous) :: adjust_local_defs loc (pats,decls) | [], [] -> [] | _ -> raise NotAdjustable let check_and_adjust_constructor env ind cstrs = function | PatVar _ as pat -> pat | PatCstr (loc,((_,i) as cstr),args,alias) as pat -> (* Check it is constructor of the right type *) let ind' = inductive_of_constructor cstr in if eq_ind ind' ind then (* Check the constructor has the right number of args *) let ci = cstrs.(i-1) in let nb_args_constr = ci.cs_nargs in if Int.equal (List.length args) nb_args_constr then pat else try let args' = adjust_local_defs loc (args, List.rev ci.cs_args) in PatCstr (loc, cstr, args', alias) with NotAdjustable -> error_wrong_numarg_constructor_loc loc env cstr nb_args_constr else (* Try to insert a coercion *) try Coercion.inh_pattern_coerce_to loc env pat ind' ind with Not_found -> error_bad_constructor_loc loc env cstr ind let check_all_variables env sigma typ mat = List.iter (fun eqn -> match current_pattern eqn with | PatVar (_,id) -> () | PatCstr (loc,cstr_sp,_,_) -> error_bad_pattern_loc loc env sigma cstr_sp typ) mat let check_unused_pattern env eqn = if not !(eqn.used) then raise_pattern_matching_error (eqn.eqn_loc, env, Evd.empty, UnusedClause eqn.patterns) let set_used_pattern eqn = eqn.used := true let extract_rhs pb = match pb.mat with | [] -> errorlabstrm "build_leaf" (msg_may_need_inversion()) | eqn::_ -> set_used_pattern eqn; eqn.rhs (**********************************************************************) (* Functions to deal with matrix factorization *) let occur_in_rhs na rhs = match na with | Anonymous -> false | Name id -> Id.List.mem id rhs.rhs_vars let is_dep_patt_in eqn = function | PatVar (_,name) -> Flags.is_program_mode () || occur_in_rhs name eqn.rhs | PatCstr _ -> true let mk_dep_patt_row (pats,_,eqn) = List.map (is_dep_patt_in eqn) pats let dependencies_in_pure_rhs nargs eqns = if List.is_empty eqns then List.make nargs (not (Flags.is_program_mode ())) (* Only "_" patts *) else let deps_rows = List.map mk_dep_patt_row eqns in let deps_columns = matrix_transpose deps_rows in List.map (List.exists (fun x -> x)) deps_columns let dependent_decl a = function | (na,None,t) -> dependent a t | (na,Some c,t) -> dependent a t || dependent a c let rec dep_in_tomatch n = function | (Pushed _ | Alias _ | NonDepAlias) :: l -> dep_in_tomatch n l | Abstract (_,d) :: l -> dependent_decl (mkRel n) d || dep_in_tomatch (n+1) l | [] -> false let dependencies_in_rhs nargs current tms eqns = match kind_of_term current with | Rel n when dep_in_tomatch n tms -> List.make nargs true | _ -> dependencies_in_pure_rhs nargs eqns (* Computing the matrix of dependencies *) [ find_dependency_list tmi [ d(i+1); ... ;dn ] ] computes in which declarations [ d(i+1); ... ;dn ] the term [ tmi ] is dependent in . [ find_dependencies_signature ( used1, ... ,usedn ) ( ( tm1,d1), ... ,(tmn , dn ) ) ] returns [ ( deps1, ... ,depsn ) ] where [ depsi ] is a subset of n, .. ,i+1 denoting in which of the d(i+1) ... dn , the term tmi is dependent . Dependencies are expressed by index , e.g. in dependency list [ n-2;1 ] , [ 1 ] points to [ dn ] and [ n-2 ] to [ d3 ] declarations [d(i+1);...;dn] the term [tmi] is dependent in. [find_dependencies_signature (used1,...,usedn) ((tm1,d1),...,(tmn,dn))] returns [(deps1,...,depsn)] where [depsi] is a subset of n,..,i+1 denoting in which of the d(i+1)...dn, the term tmi is dependent. Dependencies are expressed by index, e.g. in dependency list [n-2;1], [1] points to [dn] and [n-2] to [d3] *) let rec find_dependency_list tmblock = function | [] -> [] | (used,tdeps,d)::rest -> let deps = find_dependency_list tmblock rest in if used && List.exists (fun x -> dependent_decl x d) tmblock then List.add_set Int.equal (List.length rest + 1) (List.union Int.equal deps tdeps) else deps let find_dependencies is_dep_or_cstr_in_rhs (tm,(_,tmtypleaves),d) nextlist = let deps = find_dependency_list (tm::tmtypleaves) nextlist in if is_dep_or_cstr_in_rhs || not (List.is_empty deps) then ((true ,deps,d)::nextlist) else ((false,[] ,d)::nextlist) let find_dependencies_signature deps_in_rhs typs = let l = List.fold_right2 find_dependencies deps_in_rhs typs [] in List.map (fun (_,deps,_) -> deps) l Assume we had terms t1 .. tq to match in a context xp : Tp, ... ,x1 : T1 |- and xn : Tn has just been regeneralized into x : Tn so that the terms to match are now to be considered in the context xp : Tp, ... ,x1 : T1,x : Tn |- . [ relocate_index_tomatch n 1 tomatch ] updates t1 .. tq so that former references to are now references to x. Note that t1 .. tq are already adjusted to the context xp : Tp, ... ,x1 : T1,x : Tn |- . [ relocate_index_tomatch 1 n tomatch ] will go the way back . and xn:Tn has just been regeneralized into x:Tn so that the terms to match are now to be considered in the context xp:Tp,...,x1:T1,x:Tn |-. [relocate_index_tomatch n 1 tomatch] updates t1..tq so that former references to xn1 are now references to x. Note that t1..tq are already adjusted to the context xp:Tp,...,x1:T1,x:Tn |-. [relocate_index_tomatch 1 n tomatch] will go the way back. *) let relocate_index_tomatch n1 n2 = let rec genrec depth = function | [] -> [] | Pushed (b,((c,tm),l,na)) :: rest -> let c = relocate_index n1 n2 depth c in let tm = map_tomatch_type (relocate_index n1 n2 depth) tm in let l = List.map (relocate_rel n1 n2 depth) l in Pushed (b,((c,tm),l,na)) :: genrec depth rest | Alias (initial,(na,c,d)) :: rest -> (* [c] is out of relocation scope *) Alias (initial,(na,c,map_pair (relocate_index n1 n2 depth) d)) :: genrec depth rest | NonDepAlias :: rest -> NonDepAlias :: genrec depth rest | Abstract (i,d) :: rest -> let i = relocate_rel n1 n2 depth i in Abstract (i,map_rel_declaration (relocate_index n1 n2 depth) d) :: genrec (depth+1) rest in genrec 0 [ replace_tomatch n c tomatch ] replaces [ Rel n ] by [ c ] in [ tomatch ] let rec replace_term n c k t = if isRel t && Int.equal (destRel t) (n + k) then lift k c else map_constr_with_binders succ (replace_term n c) k t let length_of_tomatch_type_sign na t = let l = match na with | Anonymous -> 0 | Name _ -> 1 in match t with | NotInd _ -> l | IsInd (_, _, names) -> List.length names + l let replace_tomatch n c = let rec replrec depth = function | [] -> [] | Pushed (initial,((b,tm),l,na)) :: rest -> let b = replace_term n c depth b in let tm = map_tomatch_type (replace_term n c depth) tm in List.iter (fun i -> if Int.equal i (n + depth) then anomaly (Pp.str "replace_tomatch")) l; Pushed (initial,((b,tm),l,na)) :: replrec depth rest | Alias (initial,(na,b,d)) :: rest -> (* [b] is out of replacement scope *) Alias (initial,(na,b,map_pair (replace_term n c depth) d)) :: replrec depth rest | NonDepAlias :: rest -> NonDepAlias :: replrec depth rest | Abstract (i,d) :: rest -> Abstract (i,map_rel_declaration (replace_term n c depth) d) :: replrec (depth+1) rest in replrec 0 (* [liftn_tomatch_stack]: a term to match has just been substituted by some constructor t = (ci x1...xn) and the terms x1 ... xn have been added to match; all pushed terms to match must be lifted by n (knowing that [Abstract] introduces a binder in the list of pushed terms to match). *) let rec liftn_tomatch_stack n depth = function | [] -> [] | Pushed (initial,((c,tm),l,na))::rest -> let c = liftn n depth c in let tm = liftn_tomatch_type n depth tm in let l = List.map (fun i -> if i<depth then i else i+n) l in Pushed (initial,((c,tm),l,na))::(liftn_tomatch_stack n depth rest) | Alias (initial,(na,c,d))::rest -> Alias (initial,(na,liftn n depth c,map_pair (liftn n depth) d)) ::(liftn_tomatch_stack n depth rest) | NonDepAlias :: rest -> NonDepAlias :: liftn_tomatch_stack n depth rest | Abstract (i,d)::rest -> let i = if i<depth then i else i+n in Abstract (i,map_rel_declaration (liftn n depth) d) ::(liftn_tomatch_stack n (depth+1) rest) let lift_tomatch_stack n = liftn_tomatch_stack n 1 if [ current ] has type [ I(p1 ... pn u1 ... um ) ] and we consider the case of constructor [ ci ] of type [ I(p1 ... pn u'1 ... ) ] , then the default variable [ name ] is expected to have which type ? Rem : [ current ] is [ ( Rel i ) ] except perhaps for initial terms to match of constructor [ci] of type [I(p1...pn u'1...u'm)], then the default variable [name] is expected to have which type? Rem: [current] is [(Rel i)] except perhaps for initial terms to match *) (************************************************************************) (* Some heuristics to get names for variables pushed in pb environment *) Typical requirement : [ match y with ( S ( S x ) ) = > x | x = > x end ] should be compiled into [ match y with O = > y | ( S n ) = > match n with O = > y | ( S x ) = > x end end ] and [ match y with ( S ( S n ) ) = > n | n = > n end ] into [ match y with O = > y | ( S n0 ) = > match n0 with O = > y | ( S n ) = > n end end ] i.e. user names should be preserved and created names should not interfere with user names The exact names here are not important for typing ( because they are put in pb.env and not in the rhs.rhs_env of branches . However , whether a name is or not may have an effect on whether a generalization is done or not . [match y with (S (S x)) => x | x => x end] should be compiled into [match y with O => y | (S n) => match n with O => y | (S x) => x end end] and [match y with (S (S n)) => n | n => n end] into [match y with O => y | (S n0) => match n0 with O => y | (S n) => n end end] i.e. user names should be preserved and created names should not interfere with user names The exact names here are not important for typing (because they are put in pb.env and not in the rhs.rhs_env of branches. However, whether a name is Anonymous or not may have an effect on whether a generalization is done or not. *) let merge_name get_name obj = function | Anonymous -> get_name obj | na -> na let merge_names get_name = List.map2 (merge_name get_name) let get_names env sign eqns = let names1 = List.make (List.length sign) Anonymous in (* If any, we prefer names used in pats, from top to bottom *) let names2,aliasname = List.fold_right (fun (pats,pat_alias,eqn) (names,aliasname) -> (merge_names alias_of_pat pats names, merge_name (fun x -> x) pat_alias aliasname)) eqns (names1,Anonymous) in (* Otherwise, we take names from the parameters of the constructor but avoiding conflicts with user ids *) let allvars = List.fold_left (fun l (_,_,eqn) -> List.union Id.equal l eqn.rhs.avoid_ids) [] eqns in let names3,_ = List.fold_left2 (fun (l,avoid) d na -> let na = merge_name (fun (na,_,t) -> Name (next_name_away (named_hd env t na) avoid)) d na in (na::l,(out_name na)::avoid)) ([],allvars) (List.rev sign) names2 in names3,aliasname (*****************************************************************) (* Recovering names for variables pushed to the rhs' environment *) (* We just factorized a match over a matrix of equations *) (* "C xi1 .. xin as xi" as a single match over "C y1 .. yn as y" *) (* We now replace the names y1 .. yn y by the actual names *) xi1 .. to be found in the i - th clause of the matrix let set_declaration_name x (_,c,t) = (x,c,t) let recover_initial_subpattern_names = List.map2 set_declaration_name let recover_alias_names get_name = List.map2 (fun x (_,c,t) ->(get_name x,c,t)) let push_rels_eqn sign eqn = {eqn with rhs = {eqn.rhs with rhs_env = push_rel_context sign eqn.rhs.rhs_env} } let push_rels_eqn_with_names sign eqn = let subpats = List.rev (List.firstn (List.length sign) eqn.patterns) in let subpatnames = List.map alias_of_pat subpats in let sign = recover_initial_subpattern_names subpatnames sign in push_rels_eqn sign eqn let push_generalized_decl_eqn env n (na,c,t) eqn = let na = match na with | Anonymous -> Anonymous | Name id -> pi1 (Environ.lookup_rel n eqn.rhs.rhs_env) in push_rels_eqn [(na,c,t)] eqn let drop_alias_eqn eqn = { eqn with alias_stack = List.tl eqn.alias_stack } let push_alias_eqn alias eqn = let aliasname = List.hd eqn.alias_stack in let eqn = drop_alias_eqn eqn in let alias = set_declaration_name aliasname alias in push_rels_eqn [alias] eqn (**********************************************************************) (* Functions to deal with elimination predicate *) (* Infering the predicate *) The problem to solve is the following : We match Gamma |- t : I(u01 .. u0q ) against the following constructors : Gamma , x11 ... x1p1 |- C1(x11 .. x1p1 ) : I(u11 .. u1q ) ... Gamma , xn1 ... |- Cn(xn1 .. xnp1 ) : I(un1 .. unq ) Assume the types in the branches are the following Gamma , x11 ... x1p1 |- : T1 ... Gamma , xn1 ... |- branchn : Tn Assume the type of the global case expression is Gamma |- T The predicate has the form = [ y1 .. yq][z : I(y1 .. yq)]psi and it has to satisfy the following n+1 equations : Gamma , x11 ... x1p1 |- ( phi u11 .. u1q ( C1 x11 .. x1p1 ) ) = T1 ... Gamma , xn1 ... ( phi un1 .. unq ( Cn xn1 .. xnpn ) ) = Tn Gamma |- ( phi u01 .. u0q t ) = T Some hints : - Clearly , if xij occurs in Ti , then , a " match z with ( ) = > ... end " or a " psi(yk ) " , with psi extracting xij from uik , should be inserted somewhere in Ti . - If T is undefined , an easy solution is to insert a " match z with ( Ci xi1 .. ) = > ... end " in front of each Ti - Otherwise , T1 .. Tn and T must be step by step unified , if some of them diverge , then try to replace the diverging subterm by one of y1 .. yq or main problem is what to do when an existential variables is encountered The problem to solve is the following: We match Gamma |- t : I(u01..u0q) against the following constructors: Gamma, x11...x1p1 |- C1(x11..x1p1) : I(u11..u1q) ... Gamma, xn1...xnpn |- Cn(xn1..xnp1) : I(un1..unq) Assume the types in the branches are the following Gamma, x11...x1p1 |- branch1 : T1 ... Gamma, xn1...xnpn |- branchn : Tn Assume the type of the global case expression is Gamma |- T The predicate has the form phi = [y1..yq][z:I(y1..yq)]psi and it has to satisfy the following n+1 equations: Gamma, x11...x1p1 |- (phi u11..u1q (C1 x11..x1p1)) = T1 ... Gamma, xn1...xnpn |- (phi un1..unq (Cn xn1..xnpn)) = Tn Gamma |- (phi u01..u0q t) = T Some hints: - Clearly, if xij occurs in Ti, then, a "match z with (Ci xi1..xipi) => ... end" or a "psi(yk)", with psi extracting xij from uik, should be inserted somewhere in Ti. - If T is undefined, an easy solution is to insert a "match z with (Ci xi1..xipi) => ... end" in front of each Ti - Otherwise, T1..Tn and T must be step by step unified, if some of them diverge, then try to replace the diverging subterm by one of y1..yq or z. - The main problem is what to do when an existential variables is encountered *) (* Propagation of user-provided predicate through compilation steps *) let rec map_predicate f k ccl = function | [] -> f k ccl | Pushed (_,((_,tm),_,na)) :: rest -> let k' = length_of_tomatch_type_sign na tm in map_predicate f (k+k') ccl rest | (Alias _ | NonDepAlias) :: rest -> map_predicate f k ccl rest | Abstract _ :: rest -> map_predicate f (k+1) ccl rest let noccur_predicate_between n = map_predicate (noccur_between n) let liftn_predicate n = map_predicate (liftn n) let lift_predicate n = liftn_predicate n 1 let regeneralize_index_predicate n = map_predicate (relocate_index n 1) 0 let substnl_predicate sigma = map_predicate (substnl sigma) (* This is parallel bindings *) let subst_predicate (args,copt) ccl tms = let sigma = match copt with | None -> List.rev args | Some c -> c::(List.rev args) in substnl_predicate sigma 0 ccl tms let specialize_predicate_var (cur,typ,dep) tms ccl = let c = match dep with | Anonymous -> None | Name _ -> Some cur in let l = match typ with | IsInd (_, IndType (_, _), []) -> [] | IsInd (_, IndType (_, realargs), names) -> realargs | NotInd _ -> [] in subst_predicate (l,c) ccl tms (*****************************************************************************) We have pred = [ X:=realargs;x:=c]P typed in Gamma1 , x : I(realargs ) , Gamma2 and we want to abstract P over y : ) typed in the same context to get (* *) (* pred' = [X:=realargs;x':=c](y':t(x'))P[y:=y'] *) (* *) We first need to lift ) it is typed in Gamma , X:=rargs , x ' then we have to replace x by x ' in ) and y by y ' in P (*****************************************************************************) let generalize_predicate (names,na) ny d tms ccl = let () = match na with | Anonymous -> anomaly (Pp.str "Undetected dependency") | _ -> () in let p = List.length names + 1 in let ccl = lift_predicate 1 ccl tms in regeneralize_index_predicate (ny+p+1) ccl tms (*****************************************************************************) (* We just matched over cur:ind(realargs) in the following matching problem *) (* *) (* env |- match cur tms return ccl with ... end *) (* *) (* and we want to build the predicate corresponding to the individual *) (* matching over cur *) (* *) (* pred = fun X:realargstyps x:ind(X)] PI tms.ccl *) (* *) where pred is computed by abstract_predicate and PI tms.ccl by (* extract_predicate *) (*****************************************************************************) let rec extract_predicate ccl = function | (Alias _ | NonDepAlias)::tms -> (* substitution already done in build_branch *) extract_predicate ccl tms | Abstract (i,d)::tms -> mkProd_wo_LetIn d (extract_predicate ccl tms) | Pushed (_,((cur,NotInd _),_,na))::tms -> begin match na with | Anonymous -> extract_predicate ccl tms | Name _ -> let tms = lift_tomatch_stack 1 tms in let pred = extract_predicate ccl tms in subst1 cur pred end | Pushed (_,((cur,IsInd (_,IndType(_,realargs),_)),_,na))::tms -> let realargs = List.rev realargs in let k, nrealargs = match na with | Anonymous -> 0, realargs | Name _ -> 1, (cur :: realargs) in let tms = lift_tomatch_stack (List.length realargs + k) tms in let pred = extract_predicate ccl tms in substl nrealargs pred | [] -> ccl let abstract_predicate env sigma indf cur realargs (names,na) tms ccl = let sign = make_arity_signature env true indf in (* n is the number of real args + 1 (+ possible let-ins in sign) *) let n = List.length sign in (* Before abstracting we generalize over cur and on those realargs *) (* that are rels, consistently with the specialization made in *) (* build_branch *) let tms = List.fold_right2 (fun par arg tomatch -> match kind_of_term par with | Rel i -> relocate_index_tomatch (i+n) (destRel arg) tomatch | _ -> tomatch) (realargs@[cur]) (extended_rel_list 0 sign) (lift_tomatch_stack n tms) in (* Pred is already dependent in the current term to match (if *) (* (na<>Anonymous) and its realargs; we just need to adjust it to *) (* full sign if dep in cur is not taken into account *) let ccl = match na with | Anonymous -> lift_predicate 1 ccl tms | Name _ -> ccl in let pred = extract_predicate ccl tms in (* Build the predicate properly speaking *) let sign = List.map2 set_declaration_name (na::names) sign in it_mkLambda_or_LetIn_name env pred sign [ expand_arg ] is used by [ specialize_predicate ] if Yk denotes [ Xk;xk ] or [ Xk ] , it replaces gamma , x1 ... xn , x1 ... xk Yk+1 ... Yn |- pred by gamma , x1 ... xn , x1 ... xk-1 [ Xk;xk ] Yk+1 ... Yn |- pred ( if dep ) or by gamma , x1 ... xn , x1 ... xk-1 [ Xk ] Yk+1 ... Yn |- pred ( if not dep ) if Yk denotes [Xk;xk] or [Xk], it replaces gamma, x1...xn, x1...xk Yk+1...Yn |- pred by gamma, x1...xn, x1...xk-1 [Xk;xk] Yk+1...Yn |- pred (if dep) or by gamma, x1...xn, x1...xk-1 [Xk] Yk+1...Yn |- pred (if not dep) *) let expand_arg tms (p,ccl) ((_,t),_,na) = let k = length_of_tomatch_type_sign na t in (p+k,liftn_predicate (k-1) (p+1) ccl tms) let use_unit_judge evd = let j, ctx = coq_unit_judge () in let evd' = Evd.merge_context_set Evd.univ_flexible_alg evd ctx in evd', j let add_assert_false_case pb tomatch = let pats = List.map (fun _ -> PatVar (Loc.ghost,Anonymous)) tomatch in let aliasnames = List.map_filter (function Alias _ | NonDepAlias -> Some Anonymous | _ -> None) tomatch in [ { patterns = pats; rhs = { rhs_env = pb.env; rhs_vars = []; avoid_ids = []; it = None }; alias_stack = Anonymous::aliasnames; eqn_loc = Loc.ghost; used = ref false } ] let adjust_impossible_cases pb pred tomatch submat = match submat with | [] -> begin match kind_of_term pred with | Evar (evk,_) when snd (evar_source evk !(pb.evdref)) == Evar_kinds.ImpossibleCase -> if not (Evd.is_defined !(pb.evdref) evk) then begin let evd, default = use_unit_judge !(pb.evdref) in pb.evdref := Evd.define evk default.uj_type evd end; add_assert_false_case pb tomatch | _ -> submat end | _ -> submat (*****************************************************************************) (* Let pred = PI [X;x:I(X)]. PI tms. P be a typing predicate for the *) (* following pattern-matching problem: *) (* *) Gamma |- match Pushed(c : I(V ) ) as x in I(X ) , tms return pred with ... end (* *) where the branch with constructor : T1) ... (xn : ) is considered . Assume each Ti is some Ii(argsi ) with Ti : PI Ui . sort_i (* We let subst = X:=realargsi;x:=Ci(x1,...,xn) and replace pred by *) (* *) pred ' = PI [ X1 : Ui;x1 : I1(X1)] ... [Xn : Un;xn : In(Xn ) ] . ( PI tms . P)[subst ] (* *) (* s.t. the following well-typed sub-pattern-matching problem is obtained *) (* *) Gamma , x'1 .. x'n |- (* match *) (* Pushed(x'1) as x1 in I(X1), *) (* .., *) (* Pushed(x'n) as xn in I(Xn), *) (* tms *) (* return pred' *) (* with .. end *) (* *) (*****************************************************************************) let specialize_predicate newtomatchs (names,depna) arsign cs tms ccl = Assume some gamma st : gamma |- PI [ X , x : I(X ) ] . PI tms . ccl let nrealargs = List.length names in let l = match depna with Anonymous -> 0 | Name _ -> 1 in let k = nrealargs + l in (* We adjust pred st: gamma, x1..xn |- PI [X,x:I(X)]. PI tms. ccl' *) (* so that x can later be instantiated by Ci(x1..xn) *) and X by the realargs for let n = cs.cs_nargs in let ccl' = liftn_predicate n (k+1) ccl tms in (* We prepare the substitution of X and x:I(X) *) let realargsi = if not (Int.equal nrealargs 0) then adjust_subst_to_rel_context arsign (Array.to_list cs.cs_concl_realargs) else [] in let copti = match depna with | Anonymous -> None | Name _ -> Some (build_dependent_constructor cs) in The substituends realargsi , copti are all defined in gamma , x1 ... xn (* We need _parallel_ bindings to get gamma, x1...xn |- PI tms. ccl'' *) Note : applying the substitution in tms is not important ( is it sure ? ) let ccl'' = whd_betaiota Evd.empty (subst_predicate (realargsi, copti) ccl' tms) in (* We adjust ccl st: gamma, x'1..x'n, x1..xn, tms |- ccl'' *) let ccl''' = liftn_predicate n (n+1) ccl'' tms in We finally get gamma , x'1 .. x'n , x |- [ X1;x1 : I(X1)] .. : I(Xn)]pred '' ' snd (List.fold_left (expand_arg tms) (1,ccl''') newtomatchs) let find_predicate loc env evdref p current (IndType (indf,realargs)) dep tms = let pred = abstract_predicate env !evdref indf current realargs dep tms p in (pred, whd_betaiota !evdref (applist (pred, realargs@[current]))) (* Take into account that a type has been discovered to be inductive, leading to more dependencies in the predicate if the type has indices *) let adjust_predicate_from_tomatch tomatch (current,typ as ct) pb = let ((_,oldtyp),deps,na) = tomatch in match typ, oldtyp with | IsInd (_,_,names), NotInd _ -> let k = match na with | Anonymous -> 1 | Name _ -> 2 in let n = List.length names in { pb with pred = liftn_predicate n k pb.pred pb.tomatch }, (ct,List.map (fun i -> if i >= k then i+n else i) deps,na) | _ -> pb, (ct,deps,na) (* Remove commutative cuts that turn out to be non-dependent after some evars have been instantiated *) let rec ungeneralize n ng body = match kind_of_term body with | Lambda (_,_,c) when Int.equal ng 0 -> subst1 (mkRel n) c | Lambda (na,t,c) -> (* We traverse an inner generalization *) mkLambda (na,t,ungeneralize (n+1) (ng-1) c) | LetIn (na,b,t,c) -> (* We traverse an alias *) mkLetIn (na,b,t,ungeneralize (n+1) ng c) | Case (ci,p,c,brs) -> (* We traverse a split *) let p = let sign,p = decompose_lam_assum p in let sign2,p = decompose_prod_n_assum ng p in let p = prod_applist p [mkRel (n+List.length sign+ng)] in it_mkLambda_or_LetIn (it_mkProd_or_LetIn p sign2) sign in mkCase (ci,p,c,Array.map2 (fun q c -> let sign,b = decompose_lam_n_assum q c in it_mkLambda_or_LetIn (ungeneralize (n+q) ng b) sign) ci.ci_cstr_ndecls brs) | App (f,args) -> (* We traverse an inner generalization *) assert (isCase f); mkApp (ungeneralize n (ng+Array.length args) f,args) | _ -> assert false let ungeneralize_branch n k (sign,body) cs = (sign,ungeneralize (n+cs.cs_nargs) k body) let rec is_dependent_generalization ng body = match kind_of_term body with | Lambda (_,_,c) when Int.equal ng 0 -> dependent (mkRel 1) c | Lambda (na,t,c) -> (* We traverse an inner generalization *) is_dependent_generalization (ng-1) c | LetIn (na,b,t,c) -> (* We traverse an alias *) is_dependent_generalization ng c | Case (ci,p,c,brs) -> (* We traverse a split *) Array.exists2 (fun q c -> let _,b = decompose_lam_n_assum q c in is_dependent_generalization ng b) ci.ci_cstr_ndecls brs | App (g,args) -> (* We traverse an inner generalization *) assert (isCase g); is_dependent_generalization (ng+Array.length args) g | _ -> assert false let is_dependent_branch k (_,br) = is_dependent_generalization k br let postprocess_dependencies evd tocheck brs tomatch pred deps cs = let rec aux k brs tomatch pred tocheck deps = match deps, tomatch with | [], _ -> brs,tomatch,pred,[] | n::deps, Abstract (i,d) :: tomatch -> let d = map_rel_declaration (nf_evar evd) d in let is_d = match d with (_, None, _) -> false | _ -> true in if is_d || List.exists (fun c -> dependent_decl (lift k c) d) tocheck && Array.exists (is_dependent_branch k) brs then (* Dependency in the current term to match and its dependencies is real *) let brs,tomatch,pred,inst = aux (k+1) brs tomatch pred (mkRel n::tocheck) deps in let inst = match d with | (_, None, _) -> mkRel n :: inst | _ -> inst in brs, Abstract (i,d) :: tomatch, pred, inst else (* Finally, no dependency remains, so, we can replace the generalized *) (* terms by its actual value in both the remaining terms to match and *) (* the bodies of the Case *) let pred = lift_predicate (-1) pred tomatch in let tomatch = relocate_index_tomatch 1 (n+1) tomatch in let tomatch = lift_tomatch_stack (-1) tomatch in let brs = Array.map2 (ungeneralize_branch n k) brs cs in aux k brs tomatch pred tocheck deps | _ -> assert false in aux 0 brs tomatch pred tocheck deps (************************************************************************) (* Sorting equations by constructor *) let rec irrefutable env = function | PatVar (_,name) -> true | PatCstr (_,cstr,args,_) -> let ind = inductive_of_constructor cstr in let (_,mip) = Inductive.lookup_mind_specif env ind in let one_constr = Int.equal (Array.length mip.mind_user_lc) 1 in one_constr && List.for_all (irrefutable env) args let first_clause_irrefutable env = function | eqn::mat -> List.for_all (irrefutable env) eqn.patterns | _ -> false let group_equations pb ind current cstrs mat = let mat = if first_clause_irrefutable pb.env mat then [List.hd mat] else mat in let brs = Array.make (Array.length cstrs) [] in let only_default = ref None in let _ = List.fold_right (* To be sure it's from bottom to top *) (fun eqn () -> let rest = remove_current_pattern eqn in let pat = current_pattern eqn in match check_and_adjust_constructor pb.env ind cstrs pat with | PatVar (_,name) -> (* This is a default clause that we expand *) for i=1 to Array.length cstrs do let args = make_anonymous_patvars cstrs.(i-1).cs_nargs in brs.(i-1) <- (args, name, rest) :: brs.(i-1) done; if !only_default == None then only_default := Some true | PatCstr (loc,((_,i)),args,name) -> (* This is a regular clause *) only_default := Some false; brs.(i-1) <- (args, name, rest) :: brs.(i-1)) mat () in (brs,Option.default false !only_default) (************************************************************************) (* Here starts the pattern-matching compilation algorithm *) (* Abstracting over dependent subterms to match *) let rec generalize_problem names pb = function | [] -> pb, [] | i::l -> let (na,b,t as d) = map_rel_declaration (lift i) (Environ.lookup_rel i pb.env) in let pb',deps = generalize_problem names pb l in begin match (na, b) with | Anonymous, Some _ -> pb', deps | _ -> let d = on_pi3 (whd_betaiota !(pb.evdref)) d in (* for better rendering *) let tomatch = lift_tomatch_stack 1 pb'.tomatch in let tomatch = relocate_index_tomatch (i+1) 1 tomatch in { pb' with tomatch = Abstract (i,d) :: tomatch; pred = generalize_predicate names i d pb'.tomatch pb'.pred }, i::deps end (* No more patterns: typing the right-hand side of equations *) let build_leaf pb = let rhs = extract_rhs pb in let j = pb.typing_function (mk_tycon pb.pred) rhs.rhs_env pb.evdref rhs.it in j_nf_evar !(pb.evdref) j (* Build the sub-pattern-matching problem for a given branch "C x1..xn as x" *) (* spiwack: the [initial] argument keeps track whether the branch is a toplevel branch ([true]) or a deep one ([false]). *) let build_branch initial current realargs deps (realnames,curname) pb arsign eqns const_info = (* We remember that we descend through constructor C *) let history = push_history_pattern const_info.cs_nargs (fst const_info.cs_cstr) pb.history in (* We prepare the matching on x1:T1 .. xn:Tn using some heuristic to *) (* build the name x1..xn from the names present in the equations *) (* that had matched constructor C *) let cs_args = const_info.cs_args in let names,aliasname = get_names pb.env cs_args eqns in let typs = List.map2 (fun (_,c,t) na -> (na,c,t)) cs_args names in (* We build the matrix obtained by expanding the matching on *) (* "C x1..xn as x" followed by a residual matching on eqn into *) (* a matching on "x1 .. xn eqn" *) let submat = List.map (fun (tms,_,eqn) -> prepend_pattern tms eqn) eqns in (* We adjust the terms to match in the context they will be once the *) (* context [x1:T1,..,xn:Tn] will have been pushed on the current env *) let typs' = List.map_i (fun i d -> (mkRel i,map_rel_declaration (lift i) d)) 1 typs in let extenv = push_rel_context typs pb.env in let typs' = List.map (fun (c,d) -> (c,extract_inductive_data extenv !(pb.evdref) d,d)) typs' in We compute over which of x(i+1) .. xn and x matching on xi will need a (* generalization *) let dep_sign = find_dependencies_signature (dependencies_in_rhs const_info.cs_nargs current pb.tomatch eqns) (List.rev typs') in (* The dependent term to subst in the types of the remaining UnPushed terms is relative to the current context enriched by topushs *) let ci = build_dependent_constructor const_info in Current context Gamma has the form Gamma1;cur : I(realargs);Gamma2 (* We go from Gamma |- PI tms. pred to *) (* Gamma;x1..xn;curalias:I(x1..xn) |- PI tms'. pred' *) (* where, in tms and pred, those realargs that are vars are *) (* replaced by the corresponding xi and cur replaced by curalias *) let cirealargs = Array.to_list const_info.cs_concl_realargs in (* Do the specialization for terms to match *) let tomatch = List.fold_right2 (fun par arg tomatch -> match kind_of_term par with | Rel i -> replace_tomatch (i+const_info.cs_nargs) arg tomatch | _ -> tomatch) (current::realargs) (ci::cirealargs) (lift_tomatch_stack const_info.cs_nargs pb.tomatch) in let pred_is_not_dep = noccur_predicate_between 1 (List.length realnames + 1) pb.pred tomatch in let typs' = List.map2 (fun (tm,(tmtyp,_),(na,_,_)) deps -> let na = match curname, na with | Name _, Anonymous -> curname | Name _, Name _ -> na | Anonymous, _ -> if List.is_empty deps && pred_is_not_dep then Anonymous else force_name na in ((tm,tmtyp),deps,na)) typs' (List.rev dep_sign) in (* Do the specialization for the predicate *) let pred = specialize_predicate typs' (realnames,curname) arsign const_info tomatch pb.pred in let currents = List.map (fun x -> Pushed (false,x)) typs' in let alias = match aliasname with | Anonymous -> NonDepAlias | Name _ -> let cur_alias = lift const_info.cs_nargs current in let ind = appvect ( applist (mkIndU (inductive_of_constructor (fst const_info.cs_cstr), snd const_info.cs_cstr), List.map (lift const_info.cs_nargs) const_info.cs_params), const_info.cs_concl_realargs) in Alias (initial,(aliasname,cur_alias,(ci,ind))) in let tomatch = List.rev_append (alias :: currents) tomatch in let submat = adjust_impossible_cases pb pred tomatch submat in let () = match submat with | [] -> raise_pattern_matching_error (Loc.ghost, pb.env, Evd.empty, NonExhaustive (complete_history history)) | _ -> () in typs, { pb with env = extenv; tomatch = tomatch; pred = pred; history = history; mat = List.map (push_rels_eqn_with_names typs) submat } * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * INVARIANT : pb = { env , pred , tomatch , mat , ... } tomatch = list of Pushed ( c : T ) , Abstract ( na : T ) , ( c : T ) or all terms and types in Pushed , Abstract and are relative to env enriched by the Abstract coming before INVARIANT: pb = { env, pred, tomatch, mat, ...} tomatch = list of Pushed (c:T), Abstract (na:T), Alias (c:T) or NonDepAlias all terms and types in Pushed, Abstract and Alias are relative to env enriched by the Abstract coming before *) let mk_case pb (ci,pred,c,brs) = let mib = lookup_mind (fst ci.ci_ind) pb.env in match mib.mind_record with | Some (Some (_, cs, pbs)) -> Reduction.beta_appvect brs.(0) (Array.map (fun p -> mkProj (Projection.make p true, c)) cs) | _ -> mkCase (ci,pred,c,brs) (**********************************************************************) (* Main compiling descent *) let rec compile pb = match pb.tomatch with | Pushed cur :: rest -> match_current { pb with tomatch = rest } cur | Alias (initial,x) :: rest -> compile_alias initial pb x rest | NonDepAlias :: rest -> compile_non_dep_alias pb rest | Abstract (i,d) :: rest -> compile_generalization pb i d rest | [] -> build_leaf pb (* Case splitting *) and match_current pb (initial,tomatch) = let tm = adjust_tomatch_to_pattern pb tomatch in let pb,tomatch = adjust_predicate_from_tomatch tomatch tm pb in let ((current,typ),deps,dep) = tomatch in match typ with | NotInd (_,typ) -> check_all_variables pb.env !(pb.evdref) typ pb.mat; compile_all_variables initial tomatch pb | IsInd (_,(IndType(indf,realargs) as indt),names) -> let mind,_ = dest_ind_family indf in let mind = Tacred.check_privacy pb.env mind in let cstrs = get_constructors pb.env indf in let arsign, _ = get_arity pb.env indf in let eqns,onlydflt = group_equations pb (fst mind) current cstrs pb.mat in let no_cstr = Int.equal (Array.length cstrs) 0 in if (not no_cstr || not (List.is_empty pb.mat)) && onlydflt then compile_all_variables initial tomatch pb else (* We generalize over terms depending on current term to match *) let pb,deps = generalize_problem (names,dep) pb deps in (* We compile branches *) let brvals = Array.map2 (compile_branch initial current realargs (names,dep) deps pb arsign) eqns cstrs in (* We build the (elementary) case analysis *) let depstocheck = current::binding_vars_of_inductive typ in let brvals,tomatch,pred,inst = postprocess_dependencies !(pb.evdref) depstocheck brvals pb.tomatch pb.pred deps cstrs in let brvals = Array.map (fun (sign,body) -> it_mkLambda_or_LetIn body sign) brvals in let (pred,typ) = find_predicate pb.caseloc pb.env pb.evdref pred current indt (names,dep) tomatch in let ci = make_case_info pb.env (fst mind) pb.casestyle in let pred = nf_betaiota !(pb.evdref) pred in let case = mk_case pb (ci,pred,current,brvals) in Typing.check_allowed_sort pb.env !(pb.evdref) mind current pred; { uj_val = applist (case, inst); uj_type = prod_applist typ inst } (* Building the sub-problem when all patterns are variables. Case where [current] is an intially pushed term. *) and shift_problem ((current,t),_,na) pb = let ty = type_of_tomatch t in let tomatch = lift_tomatch_stack 1 pb.tomatch in let pred = specialize_predicate_var (current,t,na) pb.tomatch pb.pred in let pb = { pb with env = push_rel (na,Some current,ty) pb.env; tomatch = tomatch; pred = lift_predicate 1 pred tomatch; history = pop_history pb.history; mat = List.map (push_current_pattern (current,ty)) pb.mat } in let j = compile pb in { uj_val = subst1 current j.uj_val; uj_type = subst1 current j.uj_type } (* Building the sub-problem when all patterns are variables, non-initial case. Variables which appear as subterms of constructor are already introduced in the context, we avoid creating aliases to themselves by treating this case specially. *) and pop_problem ((current,t),_,na) pb = let pred = specialize_predicate_var (current,t,na) pb.tomatch pb.pred in let pb = { pb with pred = pred; history = pop_history pb.history; mat = List.map push_noalias_current_pattern pb.mat } in compile pb (* Building the sub-problem when all patterns are variables. *) and compile_all_variables initial cur pb = if initial then shift_problem cur pb else pop_problem cur pb (* Building the sub-problem when all patterns are variables *) and compile_branch initial current realargs names deps pb arsign eqns cstr = let sign, pb = build_branch initial current realargs deps names pb arsign eqns cstr in sign, (compile pb).uj_val (* Abstract over a declaration before continuing splitting *) and compile_generalization pb i d rest = let pb = { pb with env = push_rel d pb.env; tomatch = rest; mat = List.map (push_generalized_decl_eqn pb.env i d) pb.mat } in let j = compile pb in { uj_val = mkLambda_or_LetIn d j.uj_val; uj_type = mkProd_wo_LetIn d j.uj_type } (* spiwack: the [initial] argument keeps track whether the alias has been introduced by a toplevel branch ([true]) or a deep one ([false]). *) and compile_alias initial pb (na,orig,(expanded,expanded_typ)) rest = let f c t = let alias = (na,Some c,t) in let pb = { pb with env = push_rel alias pb.env; tomatch = lift_tomatch_stack 1 rest; pred = lift_predicate 1 pb.pred pb.tomatch; history = pop_history_pattern pb.history; mat = List.map (push_alias_eqn alias) pb.mat } in let j = compile pb in { uj_val = if isRel c || isVar c || count_occurrences (mkRel 1) j.uj_val <= 1 then subst1 c j.uj_val else mkLetIn (na,c,t,j.uj_val); uj_type = subst1 c j.uj_type } in (* spiwack: when an alias appears on a deep branch, its non-expanded form is automatically a variable of the same name. We avoid introducing such superfluous aliases so that refines are elegant. *) let just_pop () = let pb = { pb with tomatch = rest; history = pop_history_pattern pb.history; mat = List.map drop_alias_eqn pb.mat } in compile pb in let sigma = !(pb.evdref) in if not (Flags.is_program_mode ()) && (isRel orig || isVar orig) then Try to compile first using non expanded alias try if initial then f orig (Retyping.get_type_of pb.env !(pb.evdref) orig) else just_pop () with e when precatchable_exception e -> (* Try then to compile using expanded alias *) pb.evdref := sigma; f expanded expanded_typ else Try to compile first using expanded alias try f expanded expanded_typ with e when precatchable_exception e -> (* Try then to compile using non expanded alias *) pb.evdref := sigma; if initial then f orig (Retyping.get_type_of pb.env !(pb.evdref) orig) else just_pop () (* Remember that a non-trivial pattern has been consumed *) and compile_non_dep_alias pb rest = let pb = { pb with tomatch = rest; history = pop_history_pattern pb.history; mat = List.map drop_alias_eqn pb.mat } in compile pb pour les alias , enrichir les env de ce qu'il faut et substituer après par les initiaux substituer après par les initiaux *) (**************************************************************************) (* Preparation of the pattern-matching problem *) builds the matrix of equations testing that each eqn has n patterns * and linearizing the _ patterns . * Syntactic correctness has already been done in astterm * and linearizing the _ patterns. * Syntactic correctness has already been done in astterm *) let matx_of_eqns env eqns = let build_eqn (loc,ids,lpat,rhs) = let initial_lpat,initial_rhs = lpat,rhs in let initial_rhs = rhs in let rhs = { rhs_env = env; rhs_vars = free_glob_vars initial_rhs; avoid_ids = ids@(ids_of_named_context (named_context env)); it = Some initial_rhs } in { patterns = initial_lpat; alias_stack = []; eqn_loc = loc; used = ref false; rhs = rhs } in List.map build_eqn eqns (***************** Building an inversion predicate ************************) Let " match t1 in I1 u11 .. u1n_1 ... tm in I m um1 .. umn_m with ... end : T " be a pattern - matching problem . We assume that each uij can be decomposed under the form pij(vij1 .. vijq_ij ) where .. aijq_ij ) is a pattern depending on some variables aijk and the vijk are instances of these variables . We also assume that each ti has the form of a pattern qi(wi1 .. wiq_i ) where qi(bi1 .. ) is a pattern depending on some variables bik and the wik are instances of these variables ( in practice , there is no reason that ti is already constructed and the qi will be degenerated ) . We then look for a type U( .. a1jk .. b1 .. .. ) so that T = U( .. v1jk .. t1 .. .. vmjk .. tm ) . This a higher - order matching problem with a priori different solutions ( one of them if T itself ! ) . We finally invert the uij and the ti and build the return clause phi(x11 .. x1n_1y1 .. xm1 .. xmn_mym ) = match x11 .. x1n_1 y1 .. xm1 .. xmn_m ym with | p11 .. p1n_1 q1 .. pm1 .. pmn_m qm = > U( .. a1jk .. b1 .. .. ) | _ .. _ _ .. _ .. _ _ = > True end so that " phi(u11 .. u1n_1t1 .. um1 .. umn_mtm ) = T " ( note that the clause returning True never happens and any inhabited type can be put instead ) . be a pattern-matching problem. We assume that each uij can be decomposed under the form pij(vij1..vijq_ij) where pij(aij1..aijq_ij) is a pattern depending on some variables aijk and the vijk are instances of these variables. We also assume that each ti has the form of a pattern qi(wi1..wiq_i) where qi(bi1..biq_i) is a pattern depending on some variables bik and the wik are instances of these variables (in practice, there is no reason that ti is already constructed and the qi will be degenerated). We then look for a type U(..a1jk..b1 .. ..amjk..bm) so that T = U(..v1jk..t1 .. ..vmjk..tm). This a higher-order matching problem with a priori different solutions (one of them if T itself!). We finally invert the uij and the ti and build the return clause phi(x11..x1n_1y1..xm1..xmn_mym) = match x11..x1n_1 y1 .. xm1..xmn_m ym with | p11..p1n_1 q1 .. pm1..pmn_m qm => U(..a1jk..b1 .. ..amjk..bm) | _ .. _ _ .. _ .. _ _ => True end so that "phi(u11..u1n_1t1..um1..umn_mtm) = T" (note that the clause returning True never happens and any inhabited type can be put instead). *) let adjust_to_extended_env_and_remove_deps env extenv subst t = let n = rel_context_length (rel_context env) in let n' = rel_context_length (rel_context extenv) in We first remove the bindings that are dependently typed ( they are difficult to manage and it is not sure these are so useful in practice ) ; Notes : - [ subst ] is made of pairs [ ( id , u ) ] where i d is a name in [ extenv ] and [ u ] a term typed in [ env ] ; - [ subst0 ] is made of items [ ( p , u,(u , ty ) ) ] where [ ty ] is the type of [ u ] and both are adjusted to [ extenv ] while [ p ] is the index of [ i d ] in [ extenv ] ( after expansion of the aliases ) difficult to manage and it is not sure these are so useful in practice); Notes: - [subst] is made of pairs [(id,u)] where id is a name in [extenv] and [u] a term typed in [env]; - [subst0] is made of items [(p,u,(u,ty))] where [ty] is the type of [u] and both are adjusted to [extenv] while [p] is the index of [id] in [extenv] (after expansion of the aliases) *) let map (x, u) = (* d1 ... dn dn+1 ... dn'-p+1 ... dn' *) (* \--env-/ (= x:ty) *) (* \--------------extenv------------/ *) let (p, _, _) = lookup_rel_id x (rel_context extenv) in let rec traverse_local_defs p = match pi2 (lookup_rel p extenv) with | Some c -> assert (isRel c); traverse_local_defs (p + destRel c) | None -> p in let p = traverse_local_defs p in let u = lift (n' - n) u in try Some (p, u, expand_vars_in_term extenv u) (* pedrot: does this really happen to raise [Failure _]? *) with Failure _ -> None in let subst0 = List.map_filter map subst in let t0 = lift (n' - n) t in (subst0, t0) let push_binder d (k,env,subst) = (k+1,push_rel d env,List.map (fun (na,u,d) -> (na,lift 1 u,d)) subst) let rec list_assoc_in_triple x = function [] -> raise Not_found | (a, b, _)::l -> if Int.equal a x then b else list_assoc_in_triple x l Let vijk and be a set of dependent terms and T a type , all * defined in some environment env . The vijk and ti are supposed to be * instances for variables aijk and bi . * * [ abstract_tycon Gamma0 Sigma subst T Gamma ] looks for U( .. v1jk .. t1 .. .. vmjk .. tm ) * defined in some extended context * " Gamma0 , .. a1jk : V1jk .. b1 : W1 .. .. amjk : Vmjk .. bm : Wm " * such that env |- T = U( .. v1jk .. t1 .. .. vmjk .. tm ) . To not commit to * a particular solution , we replace each subterm t in T that unifies with * a subset u1 .. ul of the vijk and ti by a special evar * ? id(x = t;c1:=c1, .. ,cl = cl ) defined in context Gamma0,x , ... ,cl |- ? i d * ( where the c1 .. cl are the aijk and bi matching the u1 .. ul ) , and * similarly for each ti . * defined in some environment env. The vijk and ti are supposed to be * instances for variables aijk and bi. * * [abstract_tycon Gamma0 Sigma subst T Gamma] looks for U(..v1jk..t1 .. ..vmjk..tm) * defined in some extended context * "Gamma0, ..a1jk:V1jk.. b1:W1 .. ..amjk:Vmjk.. bm:Wm" * such that env |- T = U(..v1jk..t1 .. ..vmjk..tm). To not commit to * a particular solution, we replace each subterm t in T that unifies with * a subset u1..ul of the vijk and ti by a special evar * ?id(x=t;c1:=c1,..,cl=cl) defined in context Gamma0,x,c1,...,cl |- ?id * (where the c1..cl are the aijk and bi matching the u1..ul), and * similarly for each ti. *) let abstract_tycon loc env evdref subst tycon extenv t = let t = nf_betaiota !evdref t in (* it helps in some cases to remove K-redex*) let src = match kind_of_term t with | Evar (evk,_) -> (loc,Evar_kinds.SubEvar evk) | _ -> (loc,Evar_kinds.CasesType true) in let subst0,t0 = adjust_to_extended_env_and_remove_deps env extenv subst t in We traverse the type T of the original problem looking for subterms that match the non - constructor part of the constraints ( this part is in subst ) ; these subterms are the " good " subterms and we replace them by an evar that may depend ( and only depend ) on the corresponding convertible subterms of the substitution that match the non-constructor part of the constraints (this part is in subst); these subterms are the "good" subterms and we replace them by an evar that may depend (and only depend) on the corresponding convertible subterms of the substitution *) let rec aux (k,env,subst as x) t = let t = whd_evar !evdref t in match kind_of_term t with | Rel n when pi2 (lookup_rel n env) != None -> t | Evar ev -> let ty = get_type_of env !evdref t in let ty = Evarutil.evd_comb1 (refresh_universes (Some false) env) evdref ty in let inst = List.map_i (fun i _ -> try list_assoc_in_triple i subst0 with Not_found -> mkRel i) 1 (rel_context env) in let ev' = e_new_evar env evdref ~src ty in begin match solve_simple_eqn (evar_conv_x full_transparent_state) env !evdref (None,ev,substl inst ev') with | Success evd -> evdref := evd | UnifFailure _ -> assert false end; ev' | _ -> let good = List.filter (fun (_,u,_) -> is_conv_leq env !evdref t u) subst in match good with | [] -> map_constr_with_full_binders push_binder aux x t u is in extenv let vl = List.map pi1 good in let ty = let ty = get_type_of env !evdref t in Evarutil.evd_comb1 (refresh_universes (Some false) env) evdref ty in let ty = lift (-k) (aux x ty) in let depvl = free_rels ty in let inst = List.map_i (fun i _ -> if Int.List.mem i vl then u else mkRel i) 1 (rel_context extenv) in let rel_filter = List.map (fun a -> not (isRel a) || dependent a u || Int.Set.mem (destRel a) depvl) inst in let named_filter = List.map (fun (id,_,_) -> dependent (mkVar id) u) (named_context extenv) in let filter = Filter.make (rel_filter @ named_filter) in let candidates = u :: List.map mkRel vl in let ev = e_new_evar extenv evdref ~src ~filter ~candidates ty in lift k ev in aux (0,extenv,subst0) t0 let build_tycon loc env tycon_env subst tycon extenv evdref t = let t,tt = match t with | None -> (* This is the situation we are building a return predicate and we are in an impossible branch *) let n = rel_context_length (rel_context env) in let n' = rel_context_length (rel_context tycon_env) in let impossible_case_type, u = e_new_type_evar (reset_context env) evdref univ_flexible_alg ~src:(loc,Evar_kinds.ImpossibleCase) in (lift (n'-n) impossible_case_type, mkSort u) | Some t -> let t = abstract_tycon loc tycon_env evdref subst tycon extenv t in let evd,tt = Typing.e_type_of extenv !evdref t in evdref := evd; (t,tt) in { uj_val = t; uj_type = tt } For a multiple pattern - matching problem on t1 .. tn with return * type T , [ build_inversion_problem Gamma Sigma ( t1 .. tn ) T ] builds a return * predicate for that is itself made by an auxiliary * pattern - matching problem of which the first clause reveals the * pattern structure of the constraints on the inductive types of the t1 .. tn , * and the second clause is a wildcard clause for catching the * impossible cases . See above " Building an inversion predicate " for * further explanations * type T, [build_inversion_problem Gamma Sigma (t1..tn) T] builds a return * predicate for Xi that is itself made by an auxiliary * pattern-matching problem of which the first clause reveals the * pattern structure of the constraints on the inductive types of the t1..tn, * and the second clause is a wildcard clause for catching the * impossible cases. See above "Building an inversion predicate" for * further explanations *) let build_inversion_problem loc env sigma tms t = let make_patvar t (subst,avoid) = let id = next_name_away (named_hd env t Anonymous) avoid in PatVar (Loc.ghost,Name id), ((id,t)::subst, id::avoid) in let rec reveal_pattern t (subst,avoid as acc) = match kind_of_term (whd_betadeltaiota env sigma t) with | Construct (cstr,u) -> PatCstr (Loc.ghost,cstr,[],Anonymous), acc | App (f,v) when isConstruct f -> let cstr,u = destConstruct f in let n = constructor_nrealargs_env env cstr in let l = List.lastn n (Array.to_list v) in let l,acc = List.fold_map' reveal_pattern l acc in PatCstr (Loc.ghost,cstr,l,Anonymous), acc | _ -> make_patvar t acc in let rec aux n env acc_sign tms acc = match tms with | [] -> [], acc_sign, acc | (t, IsInd (_,IndType(indf,realargs),_)) :: tms -> let patl,acc = List.fold_map' reveal_pattern realargs acc in let pat,acc = make_patvar t acc in let indf' = lift_inductive_family n indf in let sign = make_arity_signature env true indf' in let sign = recover_alias_names alias_of_pat (pat :: List.rev patl) sign in let p = List.length realargs in let env' = push_rel_context sign env in let patl',acc_sign,acc = aux (n+p+1) env' (sign@acc_sign) tms acc in patl@pat::patl',acc_sign,acc | (t, NotInd (bo,typ)) :: tms -> let pat,acc = make_patvar t acc in let d = (alias_of_pat pat,None,typ) in let patl,acc_sign,acc = aux (n+1) (push_rel d env) (d::acc_sign) tms acc in pat::patl,acc_sign,acc in let avoid0 = ids_of_context env in [ patl ] is a list of patterns revealing the substructure of constructors present in the constraints on the type of the multiple terms t1 .. tn that are matched in the original problem ; [ subst ] is the substitution of the free pattern variables in [ patl ] that returns the non - constructor parts of the constraints . Especially , if the ti has type I ui1 .. uin_i , and the patterns associated to ti are pi1 .. pin_i , then subst(pij ) is uij ; the substitution is useful to recognize which subterms of the whole type T of the original problem have to be abstracted constructors present in the constraints on the type of the multiple terms t1..tn that are matched in the original problem; [subst] is the substitution of the free pattern variables in [patl] that returns the non-constructor parts of the constraints. Especially, if the ti has type I ui1..uin_i, and the patterns associated to ti are pi1..pin_i, then subst(pij) is uij; the substitution is useful to recognize which subterms of the whole type T of the original problem have to be abstracted *) let patl,sign,(subst,avoid) = aux 0 env [] tms ([],avoid0) in let n = List.length sign in let decls = List.map_i (fun i d -> (mkRel i,map_rel_declaration (lift i) d)) 1 sign in let pb_env = push_rel_context sign env in let decls = List.map (fun (c,d) -> (c,extract_inductive_data pb_env sigma d,d)) decls in let decls = List.rev decls in let dep_sign = find_dependencies_signature (List.make n true) decls in let sub_tms = List.map2 (fun deps (tm,(tmtyp,_),(na,b,t)) -> let na = if List.is_empty deps then Anonymous else force_name na in Pushed (true,((tm,tmtyp),deps,na))) dep_sign decls in let subst = List.map (fun (na,t) -> (na,lift n t)) subst in [ eqn1 ] is the first clause of the auxiliary pattern - matching that serves as skeleton for the return type : [ patl ] is the substructure of constructors extracted from the list of constraints on the inductive types of the multiple terms matched in the original pattern - matching problem serves as skeleton for the return type: [patl] is the substructure of constructors extracted from the list of constraints on the inductive types of the multiple terms matched in the original pattern-matching problem Xi *) let eqn1 = { patterns = patl; alias_stack = []; eqn_loc = Loc.ghost; used = ref false; rhs = { rhs_env = pb_env; we assume all vars are used ; in practice we discard dependent vars so that the field rhs_vars is normally not used vars so that the field rhs_vars is normally not used *) rhs_vars = List.map fst subst; avoid_ids = avoid; it = Some (lift n t) } } in [ eqn2 ] is the default clause of the auxiliary pattern - matching : it will catch the clauses of the original pattern - matching problem whose type constraints are incompatible with the constraints on the inductive types of the multiple terms matched in catch the clauses of the original pattern-matching problem Xi whose type constraints are incompatible with the constraints on the inductive types of the multiple terms matched in Xi *) let eqn2 = { patterns = List.map (fun _ -> PatVar (Loc.ghost,Anonymous)) patl; alias_stack = []; eqn_loc = Loc.ghost; used = ref false; rhs = { rhs_env = pb_env; rhs_vars = []; avoid_ids = avoid0; it = None } } in [ pb ] is the auxiliary pattern - matching serving as skeleton for the return type of the original problem return type of the original problem Xi *) let sigma , s = sigma in (*FIXME TRY *) let sigma , s = sigma in let s' = Retyping.get_sort_of env sigma t in let sigma, s = Evd.new_sort_variable univ_flexible_alg sigma in let sigma = Evd.set_leq_sort env sigma s' s in let evdref = ref sigma in (* let ty = evd_comb1 (refresh_universes false) evdref ty in *) let pb = { env = pb_env; evdref = evdref; pred = (*ty *) mkSort s; tomatch = sub_tms; history = start_history n; mat = [eqn1;eqn2]; caseloc = loc; casestyle = RegularStyle; typing_function = build_tycon loc env pb_env subst} in let pred = (compile pb).uj_val in (!evdref,pred) (* Here, [pred] is assumed to be in the context built from all *) (* realargs and terms to match *) let build_initial_predicate arsign pred = let rec buildrec n pred tmnames = function | [] -> List.rev tmnames,pred | ((na,c,t)::realdecls)::lnames -> let n' = n + List.length realdecls in buildrec (n'+1) pred (force_name na::tmnames) lnames | _ -> assert false in buildrec 0 pred [] (List.rev arsign) let extract_arity_signature ?(dolift=true) env0 tomatchl tmsign = let lift = if dolift then lift else fun n t -> t in let get_one_sign n tm (na,t) = match tm with | NotInd (bo,typ) -> (match t with | None -> [na,Option.map (lift n) bo,lift n typ] | Some (loc,_,_) -> user_err_loc (loc,"", str"Unexpected type annotation for a term of non inductive type.")) | IsInd (term,IndType(indf,realargs),_) -> let indf' = if dolift then lift_inductive_family n indf else indf in let ((ind,u),_) = dest_ind_family indf' in let nrealargs_ctxt = inductive_nrealdecls_env env0 ind in let arsign = fst (get_arity env0 indf') in let realnal = match t with | Some (loc,ind',realnal) -> if not (eq_ind ind ind') then user_err_loc (loc,"",str "Wrong inductive type."); if not (Int.equal nrealargs_ctxt (List.length realnal)) then anomaly (Pp.str "Ill-formed 'in' clause in cases"); List.rev realnal | None -> List.make nrealargs_ctxt Anonymous in (na,None,build_dependent_inductive env0 indf') ::(List.map2 (fun x (_,c,t) ->(x,c,t)) realnal arsign) in let rec buildrec n = function | [],[] -> [] | (_,tm)::ltm, (_,x)::tmsign -> let l = get_one_sign n tm x in l :: buildrec (n + List.length l) (ltm,tmsign) | _ -> assert false in List.rev (buildrec 0 (tomatchl,tmsign)) let inh_conv_coerce_to_tycon loc env evdref j tycon = match tycon with | Some p -> let (evd',j) = Coercion.inh_conv_coerce_to true loc env !evdref j p in evdref := evd'; j | None -> j (* We put the tycon inside the arity signature, possibly discovering dependencies. *) let prepare_predicate_from_arsign_tycon loc tomatchs arsign c = let nar = List.fold_left (fun n sign -> List.length sign + n) 0 arsign in let subst, len = List.fold_left2 (fun (subst, len) (tm, tmtype) sign -> let signlen = List.length sign in match kind_of_term tm with | Rel n when dependent tm c && Int.equal signlen 1 (* The term to match is not of a dependent type itself *) -> ((n, len) :: subst, len - signlen) | Rel n when signlen > 1 (* The term is of a dependent type, maybe some variable in its type appears in the tycon. *) -> (match tmtype with NotInd _ -> (subst, len - signlen) | IsInd (_, IndType(indf,realargs),_) -> let subst = if dependent tm c && List.for_all isRel realargs then (n, 1) :: subst else subst in List.fold_left (fun (subst, len) arg -> match kind_of_term arg with | Rel n when dependent arg c -> ((n, len) :: subst, pred len) | _ -> (subst, pred len)) (subst, len) realargs) | _ -> (subst, len - signlen)) ([], nar) tomatchs arsign in let rec predicate lift c = match kind_of_term c with | Rel n when n > lift -> (try (* Make the predicate dependent on the matched variable *) let idx = Int.List.assoc (n - lift) subst in mkRel (idx + lift) with Not_found -> (* A variable that is not matched, lift over the arsign. *) mkRel (n + nar)) | _ -> map_constr_with_binders succ predicate lift c in predicate 0 c Builds the predicate . If the predicate is dependent , its context is * made of 1+nrealargs assumptions for each matched term in an inductive * type and 1 assumption for each term not _ syntactically _ in an * inductive type . * Each matched terms are independently considered dependent or not . * A type constraint but no annotation case : we try to specialize the * tycon to make the predicate if it is not closed . * made of 1+nrealargs assumptions for each matched term in an inductive * type and 1 assumption for each term not _syntactically_ in an * inductive type. * Each matched terms are independently considered dependent or not. * A type constraint but no annotation case: we try to specialize the * tycon to make the predicate if it is not closed. *) let prepare_predicate loc typing_fun env sigma tomatchs arsign tycon pred = let preds = match pred, tycon with (* No type annotation *) | None, Some t when not (noccur_with_meta 0 max_int t) -> (* If the tycon is not closed w.r.t real variables, we try *) two different strategies First strategy : we abstract the tycon wrt to the dependencies let pred1 = prepare_predicate_from_arsign_tycon loc tomatchs arsign t in Second strategy : we build an " inversion " predicate let sigma2,pred2 = build_inversion_problem loc env sigma tomatchs t in [sigma, pred1; sigma2, pred2] | None, _ -> (* No dependent type constraint, or no constraints at all: *) we use two strategies let sigma,t = match tycon with | Some t -> sigma,t | None -> let sigma, (t, _) = new_type_evar env sigma univ_flexible_alg ~src:(loc, Evar_kinds.CasesType false) in sigma, t in First strategy : we build an " inversion " predicate let sigma1,pred1 = build_inversion_problem loc env sigma tomatchs t in Second strategy : we directly use the evar as a non dependent pred let pred2 = lift (List.length (List.flatten arsign)) t in [sigma1, pred1; sigma, pred2] (* Some type annotation *) | Some rtntyp, _ -> (* We extract the signature of the arity *) let envar = List.fold_right push_rel_context arsign env in let sigma, newt = new_sort_variable univ_flexible_alg sigma in let evdref = ref sigma in let predcclj = typing_fun (mk_tycon (mkSort newt)) envar evdref rtntyp in let sigma = !evdref in (* let sigma = Option.cata (fun tycon -> *) (* let na = Name (Id.of_string "x") in *) let tms = List.map ( fun tm - > Pushed(tm,[],na ) ) tomatchs in (* let predinst = extract_predicate predcclj.uj_val tms in *) Coercion.inh_conv_coerce_to loc env ! ) ! in let predccl = (j_nf_evar sigma predcclj).uj_val in [sigma, predccl] in List.map (fun (sigma,pred) -> let (nal,pred) = build_initial_predicate arsign pred in sigma,nal,pred) preds (** Program cases *) open Program let ($) f x = f x let string_of_name name = match name with | Anonymous -> "anonymous" | Name n -> Id.to_string n let make_prime_id name = let str = string_of_name name in Id.of_string str, Id.of_string (str ^ "'") let prime avoid name = let previd, id = make_prime_id name in previd, next_ident_away id avoid let make_prime avoid prevname = let previd, id = prime !avoid prevname in avoid := id :: !avoid; previd, id let eq_id avoid id = let hid = Id.of_string ("Heq_" ^ Id.to_string id) in let hid' = next_ident_away hid avoid in hid' let mk_eq evdref typ x y = papp evdref coq_eq_ind [| typ; x ; y |] let mk_eq_refl evdref typ x = papp evdref coq_eq_refl [| typ; x |] let mk_JMeq evdref typ x typ' y = papp evdref coq_JMeq_ind [| typ; x ; typ'; y |] let mk_JMeq_refl evdref typ x = papp evdref coq_JMeq_refl [| typ; x |] let hole = GHole (Loc.ghost, Evar_kinds.QuestionMark (Evar_kinds.Define true), Misctypes.IntroAnonymous, None) let constr_of_pat env evdref arsign pat avoid = let rec typ env (ty, realargs) pat avoid = match pat with | PatVar (l,name) -> let name, avoid = match name with Name n -> name, avoid | Anonymous -> let previd, id = prime avoid (Name (Id.of_string "wildcard")) in Name id, id :: avoid in (PatVar (l, name), [name, None, ty] @ realargs, mkRel 1, ty, (List.map (fun x -> mkRel 1) realargs), 1, avoid) | PatCstr (l,((_, i) as cstr),args,alias) -> let cind = inductive_of_constructor cstr in let IndType (indf, _) = try find_rectype env ( !evdref) (lift (-(List.length realargs)) ty) with Not_found -> error_case_not_inductive env {uj_val = ty; uj_type = Typing.type_of env !evdref ty} in let (ind,u), params = dest_ind_family indf in if not (eq_ind ind cind) then error_bad_constructor_loc l env cstr ind; let cstrs = get_constructors env indf in let ci = cstrs.(i-1) in let nb_args_constr = ci.cs_nargs in assert (Int.equal nb_args_constr (List.length args)); let patargs, args, sign, env, n, m, avoid = List.fold_right2 (fun (na, c, t) ua (patargs, args, sign, env, n, m, avoid) -> let pat', sign', arg', typ', argtypargs, n', avoid = let liftt = liftn (List.length sign) (succ (List.length args)) t in typ env (substl args liftt, []) ua avoid in let args' = arg' :: List.map (lift n') args in let env' = push_rel_context sign' env in (pat' :: patargs, args', sign' @ sign, env', n' + n, succ m, avoid)) ci.cs_args (List.rev args) ([], [], [], env, 0, 0, avoid) in let args = List.rev args in let patargs = List.rev patargs in let pat' = PatCstr (l, cstr, patargs, alias) in let cstr = mkConstructU ci.cs_cstr in let app = applistc cstr (List.map (lift (List.length sign)) params) in let app = applistc app args in let apptype = Retyping.get_type_of env ( !evdref) app in let IndType (indf, realargs) = find_rectype env ( !evdref) apptype in match alias with Anonymous -> pat', sign, app, apptype, realargs, n, avoid | Name id -> let sign = (alias, None, lift m ty) :: sign in let avoid = id :: avoid in let sign, i, avoid = try let env = push_rel_context sign env in evdref := the_conv_x_leq (push_rel_context sign env) (lift (succ m) ty) (lift 1 apptype) !evdref; let eq_t = mk_eq evdref (lift (succ m) ty) (mkRel 1) (* alias *) (lift 1 app) (* aliased term *) in let neq = eq_id avoid id in (Name neq, Some (mkRel 0), eq_t) :: sign, 2, neq :: avoid with Reduction.NotConvertible -> sign, 1, avoid in (* Mark the equality as a hole *) pat', sign, lift i app, lift i apptype, realargs, n + i, avoid in let pat', sign, patc, patty, args, z, avoid = typ env (pi3 (List.hd arsign), List.tl arsign) pat avoid in pat', (sign, patc, (pi3 (List.hd arsign), args), pat'), avoid (* shadows functional version *) let eq_id avoid id = let hid = Id.of_string ("Heq_" ^ Id.to_string id) in let hid' = next_ident_away hid !avoid in avoid := hid' :: !avoid; hid' let is_topvar t = match kind_of_term t with | Rel 0 -> true | _ -> false let rels_of_patsign l = List.map (fun ((na, b, t) as x) -> match b with | Some t' when is_topvar t' -> (na, None, t) | _ -> x) l let vars_of_ctx ctx = let _, y = List.fold_right (fun (na, b, t) (prev, vars) -> match b with | Some t' when is_topvar t' -> prev, (GApp (Loc.ghost, (GRef (Loc.ghost, delayed_force coq_eq_refl_ref, None)), [hole; GVar (Loc.ghost, prev)])) :: vars | _ -> match na with Anonymous -> invalid_arg "vars_of_ctx" | Name n -> n, GVar (Loc.ghost, n) :: vars) ctx (Id.of_string "vars_of_ctx_error", []) in List.rev y let rec is_included x y = match x, y with | PatVar _, _ -> true | _, PatVar _ -> true | PatCstr (l, (_, i), args, alias), PatCstr (l', (_, i'), args', alias') -> if Int.equal i i' then List.for_all2 is_included args args' else false liftsign is the current pattern 's complete signature length . Hence pats is already typed in its full signature . However prevpatterns are in the original one signature per pattern form . Hence pats is already typed in its full signature. However prevpatterns are in the original one signature per pattern form. *) let build_ineqs evdref prevpatterns pats liftsign = let _tomatchs = List.length pats in let diffs = List.fold_left (fun c eqnpats -> let acc = List.fold_left2 ppat is the pattern we are discriminating against , curpat is the current one . (fun acc (ppat_sign, ppat_c, (ppat_ty, ppat_tyargs), ppat) (curpat_sign, curpat_c, (curpat_ty, curpat_tyargs), curpat) -> match acc with None -> None | Some (sign, len, n, c) -> (* FixMe: do not work with ppat_args *) if is_included curpat ppat then (* Length of previous pattern's signature *) let lens = List.length ppat_sign in (* Accumulated length of previous pattern's signatures *) let len' = lens + len in let acc = Jump over previous prevpat signs lift_rel_context len ppat_sign @ sign, len', succ n, (* nth pattern *) (papp evdref coq_eq_ind [| lift (len' + liftsign) curpat_ty; liftn (len + liftsign) (succ lens) ppat_c ; lift len' curpat_c |]) :: Jump over this prevpat signature in Some acc else None) (Some ([], 0, 0, [])) eqnpats pats in match acc with None -> c | Some (sign, len, _, c') -> let conj = it_mkProd_or_LetIn (mk_coq_not (mk_coq_and c')) (lift_rel_context liftsign sign) in conj :: c) [] prevpatterns in match diffs with [] -> None | _ -> Some (mk_coq_and diffs) let constrs_of_pats typing_fun env evdref eqns tomatchs sign neqs arity = let i = ref 0 in let (x, y, z) = List.fold_left (fun (branches, eqns, prevpatterns) eqn -> let _, newpatterns, pats = List.fold_left2 (fun (idents, newpatterns, pats) pat arsign -> let pat', cpat, idents = constr_of_pat env evdref arsign pat idents in (idents, pat' :: newpatterns, cpat :: pats)) ([], [], []) eqn.patterns sign in let newpatterns = List.rev newpatterns and opats = List.rev pats in let rhs_rels, pats, signlen = List.fold_left (fun (renv, pats, n) (sign,c, (s, args), p) -> Recombine signatures and terms of all of the row 's patterns let sign' = lift_rel_context n sign in let len = List.length sign' in (sign' @ renv, (* lift to get outside of previous pattern's signatures. *) (sign', liftn n (succ len) c, (s, List.map (liftn n (succ len)) args), p) :: pats, len + n)) ([], [], 0) opats in let pats, _ = List.fold_left (* lift to get outside of past patterns to get terms in the combined environment. *) (fun (pats, n) (sign, c, (s, args), p) -> let len = List.length sign in ((rels_of_patsign sign, lift n c, (s, List.map (lift n) args), p) :: pats, len + n)) ([], 0) pats in let ineqs = build_ineqs evdref prevpatterns pats signlen in let rhs_rels' = rels_of_patsign rhs_rels in let _signenv = push_rel_context rhs_rels' env in let arity = let args, nargs = List.fold_right (fun (sign, c, (_, args), _) (allargs,n) -> (args @ c :: allargs, List.length args + succ n)) pats ([], 0) in let args = List.rev args in substl args (liftn signlen (succ nargs) arity) in let rhs_rels', tycon = let neqs_rels, arity = match ineqs with | None -> [], arity | Some ineqs -> [Anonymous, None, ineqs], lift 1 arity in let eqs_rels, arity = decompose_prod_n_assum neqs arity in eqs_rels @ neqs_rels @ rhs_rels', arity in let rhs_env = push_rel_context rhs_rels' env in let j = typing_fun (mk_tycon tycon) rhs_env eqn.rhs.it in let bbody = it_mkLambda_or_LetIn j.uj_val rhs_rels' and btype = it_mkProd_or_LetIn j.uj_type rhs_rels' in let _btype = evd_comb1 (Typing.e_type_of env) evdref bbody in let branch_name = Id.of_string ("program_branch_" ^ (string_of_int !i)) in let branch_decl = (Name branch_name, Some (lift !i bbody), (lift !i btype)) in let branch = let bref = GVar (Loc.ghost, branch_name) in match vars_of_ctx rhs_rels with [] -> bref | l -> GApp (Loc.ghost, bref, l) in let branch = match ineqs with Some _ -> GApp (Loc.ghost, branch, [ hole ]) | None -> branch in incr i; let rhs = { eqn.rhs with it = Some branch } in (branch_decl :: branches, { eqn with patterns = newpatterns; rhs = rhs } :: eqns, opats :: prevpatterns)) ([], [], []) eqns in x, y Builds the predicate . If the predicate is dependent , its context is * made of 1+nrealargs assumptions for each matched term in an inductive * type and 1 assumption for each term not _ syntactically _ in an * inductive type . * Each matched terms are independently considered dependent or not . * A type constraint but no annotation case : it is assumed non dependent . * made of 1+nrealargs assumptions for each matched term in an inductive * type and 1 assumption for each term not _syntactically_ in an * inductive type. * Each matched terms are independently considered dependent or not. * A type constraint but no annotation case: it is assumed non dependent. *) let lift_ctx n ctx = let ctx', _ = List.fold_right (fun (c, t) (ctx, n') -> (liftn n n' c, liftn_tomatch_type n n' t) :: ctx, succ n') ctx ([], 0) in ctx' (* Turn matched terms into variables. *) let abstract_tomatch env tomatchs tycon = let prev, ctx, names, tycon = List.fold_left (fun (prev, ctx, names, tycon) (c, t) -> let lenctx = List.length ctx in match kind_of_term c with Rel n -> (lift lenctx c, lift_tomatch_type lenctx t) :: prev, ctx, names, tycon | _ -> let tycon = Option.map (fun t -> subst_term (lift 1 c) (lift 1 t)) tycon in let name = next_ident_away (Id.of_string "filtered_var") names in (mkRel 1, lift_tomatch_type (succ lenctx) t) :: lift_ctx 1 prev, (Name name, Some (lift lenctx c), lift lenctx $ type_of_tomatch t) :: ctx, name :: names, tycon) ([], [], [], tycon) tomatchs in List.rev prev, ctx, tycon let build_dependent_signature env evdref avoid tomatchs arsign = let avoid = ref avoid in let arsign = List.rev arsign in let allnames = List.rev_map (List.map pi1) arsign in let nar = List.fold_left (fun n names -> List.length names + n) 0 allnames in let eqs, neqs, refls, slift, arsign' = List.fold_left2 (fun (eqs, neqs, refl_args, slift, arsigns) (tm, ty) arsign -> The accumulator : previous eqs , number of previous eqs , lift to get outside eqs and in the introduced variables ( ' as ' and ' in ' ) , new arity signatures previous eqs, number of previous eqs, lift to get outside eqs and in the introduced variables ('as' and 'in'), new arity signatures *) match ty with | IsInd (ty, IndType (indf, args), _) when List.length args > 0 -> (* Build the arity signature following the names in matched terms as much as possible *) let argsign = List.tl arsign in (* arguments in inverse application order *) let (appn, appb, appt) as _appsign = List.hd arsign in (* The matched argument *) let argsign = List.rev argsign in (* arguments in application order *) let env', nargeqs, argeqs, refl_args, slift, argsign' = List.fold_left2 (fun (env, nargeqs, argeqs, refl_args, slift, argsign') arg (name, b, t) -> let argt = Retyping.get_type_of env !evdref arg in let eq, refl_arg = if Reductionops.is_conv env !evdref argt t then (mk_eq evdref (lift (nargeqs + slift) argt) (mkRel (nargeqs + slift)) (lift (nargeqs + nar) arg), mk_eq_refl evdref argt arg) else (mk_JMeq evdref (lift (nargeqs + slift) t) (mkRel (nargeqs + slift)) (lift (nargeqs + nar) argt) (lift (nargeqs + nar) arg), mk_JMeq_refl evdref argt arg) in let previd, id = let name = match kind_of_term arg with Rel n -> pi1 (lookup_rel n env) | _ -> name in make_prime avoid name in (env, succ nargeqs, (Name (eq_id avoid previd), None, eq) :: argeqs, refl_arg :: refl_args, pred slift, (Name id, b, t) :: argsign')) (env, neqs, [], [], slift, []) args argsign in let eq = mk_JMeq evdref (lift (nargeqs + slift) appt) (mkRel (nargeqs + slift)) (lift (nargeqs + nar) ty) (lift (nargeqs + nar) tm) in let refl_eq = mk_JMeq_refl evdref ty tm in let previd, id = make_prime avoid appn in (((Name (eq_id avoid previd), None, eq) :: argeqs) :: eqs, succ nargeqs, refl_eq :: refl_args, pred slift, (((Name id, appb, appt) :: argsign') :: arsigns)) | _ -> (* Non dependent inductive or not inductive, just use a regular equality *) let (name, b, typ) = match arsign with [x] -> x | _ -> assert(false) in let previd, id = make_prime avoid name in let arsign' = (Name id, b, typ) in let tomatch_ty = type_of_tomatch ty in let eq = mk_eq evdref (lift nar tomatch_ty) (mkRel slift) (lift nar tm) in ([(Name (eq_id avoid previd), None, eq)] :: eqs, succ neqs, (mk_eq_refl evdref tomatch_ty tm) :: refl_args, pred slift, (arsign' :: []) :: arsigns)) ([], 0, [], nar, []) tomatchs arsign in let arsign'' = List.rev arsign' in assert(Int.equal slift 0); (* we must have folded over all elements of the arity signature *) arsign'', allnames, nar, eqs, neqs, refls let context_of_arsign l = let (x, _) = List.fold_right (fun c (x, n) -> (lift_rel_context n c @ x, List.length c + n)) l ([], 0) in x let compile_program_cases loc style (typing_function, evdref) tycon env (predopt, tomatchl, eqns) = let typing_fun tycon env = function | Some t -> typing_function tycon env evdref t | None -> Evarutil.evd_comb0 use_unit_judge evdref in (* We build the matrix of patterns and right-hand side *) let matx = matx_of_eqns env eqns in (* We build the vector of terms to match consistently with the *) (* constructors found in patterns *) let tomatchs = coerce_to_indtype typing_function evdref env matx tomatchl in let tycon = valcon_of_tycon tycon in let tomatchs, tomatchs_lets, tycon' = abstract_tomatch env tomatchs tycon in let env = push_rel_context tomatchs_lets env in let len = List.length eqns in let sign, allnames, signlen, eqs, neqs, args = (* The arity signature *) let arsign = extract_arity_signature ~dolift:false env tomatchs tomatchl in Build the dependent arity signature , the equalities which makes the first part of the predicate and their instantiations . the first part of the predicate and their instantiations. *) let avoid = [] in build_dependent_signature env evdref avoid tomatchs arsign in let tycon, arity = match tycon' with | None -> let ev = mkExistential env evdref in ev, ev | Some t -> let pred = try let pred = prepare_predicate_from_arsign_tycon loc tomatchs sign t in (* The tycon may be ill-typed after abstraction. *) let env' = push_rel_context (context_of_arsign sign) env in ignore(Typing.sort_of env' evdref pred); pred with e when Errors.noncritical e -> let nar = List.fold_left (fun n sign -> List.length sign + n) 0 sign in lift nar t in Option.get tycon, pred in let neqs, arity = let ctx = context_of_arsign eqs in let neqs = List.length ctx in neqs, it_mkProd_or_LetIn (lift neqs arity) ctx in let lets, matx = (* Type the rhs under the assumption of equations *) constrs_of_pats typing_fun env evdref matx tomatchs sign neqs arity in let matx = List.rev matx in let _ = assert (Int.equal len (List.length lets)) in let env = push_rel_context lets env in let matx = List.map (fun eqn -> { eqn with rhs = { eqn.rhs with rhs_env = env } }) matx in let tomatchs = List.map (fun (x, y) -> lift len x, lift_tomatch_type len y) tomatchs in let args = List.rev_map (lift len) args in let pred = liftn len (succ signlen) arity in let nal, pred = build_initial_predicate sign pred in (* We push the initial terms to match and push their alias to rhs' envs *) (* names of aliases will be recovered from patterns (hence Anonymous here) *) let out_tmt na = function NotInd (c,t) -> (na,c,t) | IsInd (typ,_,_) -> (na,None,typ) in let typs = List.map2 (fun na (tm,tmt) -> (tm,out_tmt na tmt)) nal tomatchs in let typs = List.map (fun (c,d) -> (c,extract_inductive_data env !evdref d,d)) typs in let dep_sign = find_dependencies_signature (List.make (List.length typs) true) typs in let typs' = List.map3 (fun (tm,tmt) deps na -> let deps = if not (isRel tm) then [] else deps in ((tm,tmt),deps,na)) tomatchs dep_sign nal in let initial_pushed = List.map (fun x -> Pushed (true,x)) typs' in let typing_function tycon env evdref = function | Some t -> typing_function tycon env evdref t | None -> evd_comb0 use_unit_judge evdref in let pb = { env = env; evdref = evdref; pred = pred; tomatch = initial_pushed; history = start_history (List.length initial_pushed); mat = matx; caseloc = loc; casestyle= style; typing_function = typing_function } in let j = compile pb in (* We check for unused patterns *) List.iter (check_unused_pattern env) matx; let body = it_mkLambda_or_LetIn (applistc j.uj_val args) lets in let j = { uj_val = it_mkLambda_or_LetIn body tomatchs_lets; uj_type = nf_evar !evdref tycon; } in j (**************************************************************************) (* Main entry of the matching compilation *) let compile_cases loc style (typing_fun, evdref) tycon env (predopt, tomatchl, eqns) = if predopt == None && Flags.is_program_mode () then compile_program_cases loc style (typing_fun, evdref) tycon env (predopt, tomatchl, eqns) else (* We build the matrix of patterns and right-hand side *) let matx = matx_of_eqns env eqns in (* We build the vector of terms to match consistently with the *) (* constructors found in patterns *) let tomatchs = coerce_to_indtype typing_fun evdref env matx tomatchl in (* If an elimination predicate is provided, we check it is compatible with the type of arguments to match; if none is provided, we build alternative possible predicates *) let arsign = extract_arity_signature env tomatchs tomatchl in let preds = prepare_predicate loc typing_fun env !evdref tomatchs arsign tycon predopt in let compile_for_one_predicate (sigma,nal,pred) = (* We push the initial terms to match and push their alias to rhs' envs *) names of aliases will be recovered from patterns ( hence (* here) *) let out_tmt na = function NotInd (c,t) -> (na,c,t) | IsInd (typ,_,_) -> (na,None,typ) in let typs = List.map2 (fun na (tm,tmt) -> (tm,out_tmt na tmt)) nal tomatchs in let typs = List.map (fun (c,d) -> (c,extract_inductive_data env sigma d,d)) typs in let dep_sign = find_dependencies_signature (List.make (List.length typs) true) typs in let typs' = List.map3 (fun (tm,tmt) deps na -> let deps = if not (isRel tm) then [] else deps in ((tm,tmt),deps,na)) tomatchs dep_sign nal in let initial_pushed = List.map (fun x -> Pushed (true,x)) typs' in (* A typing function that provides with a canonical term for absurd cases*) let typing_fun tycon env evdref = function | Some t -> typing_fun tycon env evdref t | None -> evd_comb0 use_unit_judge evdref in let myevdref = ref sigma in let pb = { env = env; evdref = myevdref; pred = pred; tomatch = initial_pushed; history = start_history (List.length initial_pushed); mat = matx; caseloc = loc; casestyle = style; typing_function = typing_fun } in let j = compile pb in evdref := !myevdref; j in Return the term compiled with the first possible elimination (* predicate for which the compilation succeeds *) let j = list_try_compile compile_for_one_predicate preds in (* We check for unused patterns *) List.iter (check_unused_pattern env) matx; We coerce to the ( if an elim predicate was provided ) inh_conv_coerce_to_tycon loc env evdref j tycon
null
https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/pretyping/cases.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** Pattern-matching errors ********************************************************************** Pattern-matching compilation (Cases) ********************************************************************** ********************************************************************** Configuration, errors and warnings ******************************************************************** Structures used in compiling pattern-matching We keep a constr for aliases and a cases_pattern for error message This is for non exhaustive error message This is to build glued pattern-matching history and alias bodies Builds a continuation expecting [n] arguments and building [ci] applied to this [n] arguments Computing the inductive type from the matrix of patterns We use the "in I" clause to coerce the terms to match and otherwise use the constructor to know in which type is the matching problem Note that insertion of coercions inside nested patterns is done each time the matrix is expanded Try to refine the type with inductive information coming from the constructor and renounce if not able to give more information Try if some 'in I ...' is present and can be used as a constraint no patterns at all ********************************************************************** Ideally, we could find a common inductive type to which both the term to match and the patterns coerce Don't insert coercions if dependent; only solve evars ******************************************************************** spiwack: like [push_current_pattern] but does not introduce an alias in rhs_env. Aliasing binders are only useful for variables at the root of a pattern matching problem (initial push), so we distinguish the cases. ******************************************************************** Well-formedness tests Partial check on patterns Check it is constructor of the right type Check the constructor has the right number of args Try to insert a coercion ******************************************************************** Functions to deal with matrix factorization Only "_" patts Computing the matrix of dependencies [c] is out of relocation scope [b] is out of replacement scope [liftn_tomatch_stack]: a term to match has just been substituted by some constructor t = (ci x1...xn) and the terms x1 ... xn have been added to match; all pushed terms to match must be lifted by n (knowing that [Abstract] introduces a binder in the list of pushed terms to match). ********************************************************************** Some heuristics to get names for variables pushed in pb environment If any, we prefer names used in pats, from top to bottom Otherwise, we take names from the parameters of the constructor but avoiding conflicts with user ids *************************************************************** Recovering names for variables pushed to the rhs' environment We just factorized a match over a matrix of equations "C xi1 .. xin as xi" as a single match over "C y1 .. yn as y" We now replace the names y1 .. yn y by the actual names ******************************************************************** Functions to deal with elimination predicate Infering the predicate Propagation of user-provided predicate through compilation steps This is parallel bindings *************************************************************************** pred' = [X:=realargs;x':=c](y':t(x'))P[y:=y'] *************************************************************************** *************************************************************************** We just matched over cur:ind(realargs) in the following matching problem env |- match cur tms return ccl with ... end and we want to build the predicate corresponding to the individual matching over cur pred = fun X:realargstyps x:ind(X)] PI tms.ccl extract_predicate *************************************************************************** substitution already done in build_branch n is the number of real args + 1 (+ possible let-ins in sign) Before abstracting we generalize over cur and on those realargs that are rels, consistently with the specialization made in build_branch Pred is already dependent in the current term to match (if (na<>Anonymous) and its realargs; we just need to adjust it to full sign if dep in cur is not taken into account Build the predicate properly speaking *************************************************************************** Let pred = PI [X;x:I(X)]. PI tms. P be a typing predicate for the following pattern-matching problem: We let subst = X:=realargsi;x:=Ci(x1,...,xn) and replace pred by s.t. the following well-typed sub-pattern-matching problem is obtained match Pushed(x'1) as x1 in I(X1), .., Pushed(x'n) as xn in I(Xn), tms return pred' with .. end *************************************************************************** We adjust pred st: gamma, x1..xn |- PI [X,x:I(X)]. PI tms. ccl' so that x can later be instantiated by Ci(x1..xn) We prepare the substitution of X and x:I(X) We need _parallel_ bindings to get gamma, x1...xn |- PI tms. ccl'' We adjust ccl st: gamma, x'1..x'n, x1..xn, tms |- ccl'' Take into account that a type has been discovered to be inductive, leading to more dependencies in the predicate if the type has indices Remove commutative cuts that turn out to be non-dependent after some evars have been instantiated We traverse an inner generalization We traverse an alias We traverse a split We traverse an inner generalization We traverse an inner generalization We traverse an alias We traverse a split We traverse an inner generalization Dependency in the current term to match and its dependencies is real Finally, no dependency remains, so, we can replace the generalized terms by its actual value in both the remaining terms to match and the bodies of the Case ********************************************************************** Sorting equations by constructor To be sure it's from bottom to top This is a default clause that we expand This is a regular clause ********************************************************************** Here starts the pattern-matching compilation algorithm Abstracting over dependent subterms to match for better rendering No more patterns: typing the right-hand side of equations Build the sub-pattern-matching problem for a given branch "C x1..xn as x" spiwack: the [initial] argument keeps track whether the branch is a toplevel branch ([true]) or a deep one ([false]). We remember that we descend through constructor C We prepare the matching on x1:T1 .. xn:Tn using some heuristic to build the name x1..xn from the names present in the equations that had matched constructor C We build the matrix obtained by expanding the matching on "C x1..xn as x" followed by a residual matching on eqn into a matching on "x1 .. xn eqn" We adjust the terms to match in the context they will be once the context [x1:T1,..,xn:Tn] will have been pushed on the current env generalization The dependent term to subst in the types of the remaining UnPushed terms is relative to the current context enriched by topushs We go from Gamma |- PI tms. pred to Gamma;x1..xn;curalias:I(x1..xn) |- PI tms'. pred' where, in tms and pred, those realargs that are vars are replaced by the corresponding xi and cur replaced by curalias Do the specialization for terms to match Do the specialization for the predicate ******************************************************************** Main compiling descent Case splitting We generalize over terms depending on current term to match We compile branches We build the (elementary) case analysis Building the sub-problem when all patterns are variables. Case where [current] is an intially pushed term. Building the sub-problem when all patterns are variables, non-initial case. Variables which appear as subterms of constructor are already introduced in the context, we avoid creating aliases to themselves by treating this case specially. Building the sub-problem when all patterns are variables. Building the sub-problem when all patterns are variables Abstract over a declaration before continuing splitting spiwack: the [initial] argument keeps track whether the alias has been introduced by a toplevel branch ([true]) or a deep one ([false]). spiwack: when an alias appears on a deep branch, its non-expanded form is automatically a variable of the same name. We avoid introducing such superfluous aliases so that refines are elegant. Try then to compile using expanded alias Try then to compile using non expanded alias Remember that a non-trivial pattern has been consumed ************************************************************************ Preparation of the pattern-matching problem **************** Building an inversion predicate *********************** d1 ... dn dn+1 ... dn'-p+1 ... dn' \--env-/ (= x:ty) \--------------extenv------------/ pedrot: does this really happen to raise [Failure _]? it helps in some cases to remove K-redex This is the situation we are building a return predicate and we are in an impossible branch FIXME TRY let ty = evd_comb1 (refresh_universes false) evdref ty in ty Here, [pred] is assumed to be in the context built from all realargs and terms to match We put the tycon inside the arity signature, possibly discovering dependencies. The term to match is not of a dependent type itself The term is of a dependent type, maybe some variable in its type appears in the tycon. Make the predicate dependent on the matched variable A variable that is not matched, lift over the arsign. No type annotation If the tycon is not closed w.r.t real variables, we try No dependent type constraint, or no constraints at all: Some type annotation We extract the signature of the arity let sigma = Option.cata (fun tycon -> let na = Name (Id.of_string "x") in let predinst = extract_predicate predcclj.uj_val tms in * Program cases alias aliased term Mark the equality as a hole shadows functional version FixMe: do not work with ppat_args Length of previous pattern's signature Accumulated length of previous pattern's signatures nth pattern lift to get outside of previous pattern's signatures. lift to get outside of past patterns to get terms in the combined environment. Turn matched terms into variables. Build the arity signature following the names in matched terms as much as possible arguments in inverse application order The matched argument arguments in application order Non dependent inductive or not inductive, just use a regular equality we must have folded over all elements of the arity signature We build the matrix of patterns and right-hand side We build the vector of terms to match consistently with the constructors found in patterns The arity signature The tycon may be ill-typed after abstraction. Type the rhs under the assumption of equations We push the initial terms to match and push their alias to rhs' envs names of aliases will be recovered from patterns (hence Anonymous here) We check for unused patterns ************************************************************************ Main entry of the matching compilation We build the matrix of patterns and right-hand side We build the vector of terms to match consistently with the constructors found in patterns If an elimination predicate is provided, we check it is compatible with the type of arguments to match; if none is provided, we build alternative possible predicates We push the initial terms to match and push their alias to rhs' envs here) A typing function that provides with a canonical term for absurd cases predicate for which the compilation succeeds We check for unused patterns
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Pp open Errors open Util open Names open Nameops open Term open Vars open Context open Termops open Namegen open Declarations open Inductiveops open Environ open Reductionops open Type_errors open Glob_term open Glob_ops open Retyping open Pretype_errors open Evarutil open Evarsolve open Evarconv open Evd type pattern_matching_error = | BadPattern of constructor * constr | BadConstructor of constructor * inductive | WrongNumargConstructor of constructor * int | WrongNumargInductive of inductive * int | UnusedClause of cases_pattern list | NonExhaustive of cases_pattern list | CannotInferPredicate of (constr * types) array exception PatternMatchingError of env * evar_map * pattern_matching_error let raise_pattern_matching_error (loc,env,sigma,te) = Loc.raise loc (PatternMatchingError(env,sigma,te)) let error_bad_pattern_loc loc env sigma cstr ind = raise_pattern_matching_error (loc, env, sigma, BadPattern (cstr,ind)) let error_bad_constructor_loc loc env cstr ind = raise_pattern_matching_error (loc, env, Evd.empty, BadConstructor (cstr,ind)) let error_wrong_numarg_constructor_loc loc env c n = raise_pattern_matching_error (loc, env, Evd.empty, WrongNumargConstructor(c,n)) let error_wrong_numarg_inductive_loc loc env c n = raise_pattern_matching_error (loc, env, Evd.empty, WrongNumargInductive(c,n)) let rec list_try_compile f = function | [a] -> f a | [] -> anomaly (str "try_find_f") | h::t -> try f h with UserError _ | TypeError _ | PretypeError _ | PatternMatchingError _ -> list_try_compile f t let force_name = let nx = Name default_dependent_ident in function Anonymous -> nx | na -> na open Pp let msg_may_need_inversion () = strbrk "Found a matching with no clauses on a term unknown to have an empty inductive type." Utils let make_anonymous_patvars n = List.make n (PatVar (Loc.ghost,Anonymous)) We have x1 : t1 ... xn : , xi':ti , y1 .. yk |- c and re - generalize over xi : ti to get x1 : t1 ... xn : , xi':ti , y1 .. yk |- c[xi:=xi ' ] over xi:ti to get x1:t1...xn:tn,xi':ti,y1..yk |- c[xi:=xi'] *) let relocate_rel n1 n2 k j = if Int.equal j (n1 + k) then n2+k else j let rec relocate_index n1 n2 k t = match kind_of_term t with | Rel j when Int.equal j (n1 + k) -> mkRel (n2+k) | Rel j when j < n1+k -> t | Rel j when j > n1+k -> t | _ -> map_constr_with_binders succ (relocate_index n1 n2) k t type 'a rhs = { rhs_env : env; rhs_vars : Id.t list; avoid_ids : Id.t list; it : 'a option} type 'a equation = { patterns : cases_pattern list; rhs : 'a rhs; alias_stack : Name.t list; eqn_loc : Loc.t; used : bool ref } type 'a matrix = 'a equation list 1st argument of IsInd is the original before extracting the summary type tomatch_type = | IsInd of types * inductive_type * Name.t list | NotInd of constr option * types spiwack : The first argument of [ Pushed ] is [ true ] for initial Pushed and [ false ] otherwise . Used to decide whether the term being matched on must be aliased in the variable case ( only initial Pushed need to be aliased ) . The first argument of [ ] is [ true ] if the alias was introduced by an initial pushed and [ false ] otherwise . Pushed and [false] otherwise. Used to decide whether the term being matched on must be aliased in the variable case (only initial Pushed need to be aliased). The first argument of [Alias] is [true] if the alias was introduced by an initial pushed and [false] otherwise.*) type tomatch_status = | Pushed of (bool*((constr * tomatch_type) * int list * Name.t)) | Alias of (bool*(Name.t * constr * (constr * types))) | NonDepAlias | Abstract of int * rel_declaration type tomatch_stack = tomatch_status list type pattern_history = | Top | MakeConstructor of constructor * pattern_continuation and pattern_continuation = | Continuation of int * cases_pattern list * pattern_history | Result of cases_pattern list let start_history n = Continuation (n, [], Top) let feed_history arg = function | Continuation (n, l, h) when n>=1 -> Continuation (n-1, arg :: l, h) | Continuation (n, _, _) -> anomaly (str "Bad number of expected remaining patterns: " ++ int n) | Result _ -> anomaly (Pp.str "Exhausted pattern history") let rec glob_pattern_of_partial_history args2 = function | Continuation (n, args1, h) -> let args3 = make_anonymous_patvars (n - (List.length args2)) in build_glob_pattern (List.rev_append args1 (args2@args3)) h | Result pl -> pl and build_glob_pattern args = function | Top -> args | MakeConstructor (pci, rh) -> glob_pattern_of_partial_history [PatCstr (Loc.ghost, pci, args, Anonymous)] rh let complete_history = glob_pattern_of_partial_history [] let pop_history_pattern = function | Continuation (0, l, Top) -> Result (List.rev l) | Continuation (0, l, MakeConstructor (pci, rh)) -> feed_history (PatCstr (Loc.ghost,pci,List.rev l,Anonymous)) rh | _ -> anomaly (Pp.str "Constructor not yet filled with its arguments") let pop_history h = feed_history (PatVar (Loc.ghost, Anonymous)) h let push_history_pattern n pci cont = Continuation (n, [], MakeConstructor (pci, cont)) A pattern - matching problem has the following form : env , evd |- match terms_to_tomatch return pred with mat end where is some sequence of " instructions " ( t1 ... tp ) and mat is some matrix ( p11 ... p1n - > rhs1 ) ( ... ) ( pm1 ... pmn - > rhsm ) Terms to match : there are 3 kinds of instructions - " Pushed " terms to match are typed in [ env ] ; these are usually just Rel(n ) except for the initial terms given by user ; in Pushed ( ( c , tm),deps , na ) , [ c ] is the reference to the term ( which is a Rel or an initial term ) , [ tm ] is its type ( telling whether we know if it is an inductive type or not ) , [ ] is the list of terms to abstract before matching on [ c ] ( these are rels too ) - " Abstract " instructions mean that an abstraction has to be inserted in the current branch to build ( this means a pattern has been detected dependent in another one and a generalization is necessary to ensure well - typing ) Abstract instructions extend the [ env ] in which the other instructions are typed - " " instructions mean an alias has to be inserted ( this alias is usually removed at the end , except when its type is not the same as the type of the matched term from which it comes - typically because the inductive types are " real " parameters ) - " " instructions mean the completion of a matching over a term to match as for but without inserting this alias because there is no dependency in it Right - hand sides : They consist of a raw term to type in an environment specific to the clause they belong to : the names of declarations are those of the variables present in the patterns . Therefore , they come with their own [ rhs_env ] ( actually it is the same as [ env ] except for the names of variables ) . env, evd |- match terms_to_tomatch return pred with mat end where terms_to_match is some sequence of "instructions" (t1 ... tp) and mat is some matrix (p11 ... p1n -> rhs1) ( ... ) (pm1 ... pmn -> rhsm) Terms to match: there are 3 kinds of instructions - "Pushed" terms to match are typed in [env]; these are usually just Rel(n) except for the initial terms given by user; in Pushed ((c,tm),deps,na), [c] is the reference to the term (which is a Rel or an initial term), [tm] is its type (telling whether we know if it is an inductive type or not), [deps] is the list of terms to abstract before matching on [c] (these are rels too) - "Abstract" instructions mean that an abstraction has to be inserted in the current branch to build (this means a pattern has been detected dependent in another one and a generalization is necessary to ensure well-typing) Abstract instructions extend the [env] in which the other instructions are typed - "Alias" instructions mean an alias has to be inserted (this alias is usually removed at the end, except when its type is not the same as the type of the matched term from which it comes - typically because the inductive types are "real" parameters) - "NonDepAlias" instructions mean the completion of a matching over a term to match as for Alias but without inserting this alias because there is no dependency in it Right-hand sides: They consist of a raw term to type in an environment specific to the clause they belong to: the names of declarations are those of the variables present in the patterns. Therefore, they come with their own [rhs_env] (actually it is the same as [env] except for the names of variables). *) type 'a pattern_matching_problem = { env : env; evdref : evar_map ref; pred : constr; tomatch : tomatch_stack; history : pattern_continuation; mat : 'a matrix; caseloc : Loc.t; casestyle : case_style; typing_function: type_constraint -> env -> evar_map ref -> 'a option -> unsafe_judgment } -------------------------------------------------------------------------- * * A few functions to infer the inductive type from the patterns instead of * * checking that the patterns correspond to the ind . type of the * * destructurated object . Allows type inference of examples like * * match n with O = > true | _ = > false end * * match x in I with C = > true | _ = > false end * * -------------------------------------------------------------------------- * A few functions to infer the inductive type from the patterns instead of * * checking that the patterns correspond to the ind. type of the * * destructurated object. Allows type inference of examples like * * match n with O => true | _ => false end * * match x in I with C => true | _ => false end * *--------------------------------------------------------------------------*) let rec find_row_ind = function [] -> None | PatVar _ :: l -> find_row_ind l | PatCstr(loc,c,_,_) :: _ -> Some (loc,c) let inductive_template evdref env tmloc ind = let indu = evd_comb1 (Evd.fresh_inductive_instance env) evdref ind in let arsign = inductive_alldecls_env env indu in let hole_source = match tmloc with | Some loc -> fun i -> (loc, Evar_kinds.TomatchTypeParameter (ind,i)) | None -> fun _ -> (Loc.ghost, Evar_kinds.InternalHole) in let (_,evarl,_) = List.fold_right (fun (na,b,ty) (subst,evarl,n) -> match b with | None -> let ty' = substl subst ty in let e = e_new_evar env evdref ~src:(hole_source n) ty' in (e::subst,e::evarl,n+1) | Some b -> (substl subst b::subst,evarl,n+1)) arsign ([],[],1) in applist (mkIndU indu,List.rev evarl) let try_find_ind env sigma typ realnames = let (IndType(_,realargs) as ind) = find_rectype env sigma typ in let names = match realnames with | Some names -> names | None -> List.make (List.length realargs) Anonymous in IsInd (typ,ind,names) let inh_coerce_to_ind evdref env loc ty tyi = let sigma = !evdref in let expected_typ = inductive_template evdref env loc tyi in devrait être indifférent d'exiger leq ou pas puisque pour un inductif cela doit être égal *) if not (e_cumul env evdref expected_typ ty) then evdref := sigma let binding_vars_of_inductive = function | NotInd _ -> [] | IsInd (_,IndType(_,realargs),_) -> List.filter isRel realargs let extract_inductive_data env sigma (_,b,t) = match b with | None -> let tmtyp = try try_find_ind env sigma t None with Not_found -> NotInd (None,t) in let tmtypvars = binding_vars_of_inductive tmtyp in (tmtyp,tmtypvars) | Some _ -> (NotInd (None, t), []) let unify_tomatch_with_patterns evdref env loc typ pats realnames = match find_row_ind pats with | None -> NotInd (None,typ) | Some (_,(ind,_)) -> inh_coerce_to_ind evdref env loc typ ind; try try_find_ind env !evdref typ realnames with Not_found -> NotInd (None,typ) let find_tomatch_tycon evdref env loc = function | Some (_,ind,realnal) -> mk_tycon (inductive_template evdref env loc ind),Some (List.rev realnal) | None -> empty_tycon,None let coerce_row typing_fun evdref env pats (tomatch,(_,indopt)) = let loc = Some (loc_of_glob_constr tomatch) in let tycon,realnames = find_tomatch_tycon evdref env loc indopt in let j = typing_fun tycon env evdref tomatch in let evd, j = Coercion.inh_coerce_to_base (loc_of_glob_constr tomatch) env !evdref j in evdref := evd; let typ = nf_evar !evdref j.uj_type in let t = try try_find_ind env !evdref typ realnames with Not_found -> unify_tomatch_with_patterns evdref env loc typ pats realnames in (j.uj_val,t) let coerce_to_indtype typing_fun evdref env matx tomatchl = let pats = List.map (fun r -> r.patterns) matx in let matx' = match matrix_transpose pats with | m -> m in List.map2 (coerce_row typing_fun evdref env) matx' tomatchl Utils let mkExistential env ?(src=(Loc.ghost,Evar_kinds.InternalHole)) evdref = let e, u = e_new_type_evar env evdref univ_flexible_alg ~src:src in e let evd_comb2 f evdref x y = let (evd',y) = f !evdref x y in evdref := evd'; y let adjust_tomatch_to_pattern pb ((current,typ),deps,dep) = In practice , we coerce the term to match if it is not already an inductive type and it is not dependent ; moreover , we use only the first pattern type and forget about the others inductive type and it is not dependent; moreover, we use only the first pattern type and forget about the others *) let typ,names = match typ with IsInd(t,_,names) -> t,Some names | NotInd(_,t) -> t,None in let tmtyp = try try_find_ind pb.env !(pb.evdref) typ names with Not_found -> NotInd (None,typ) in match tmtyp with | NotInd (None,typ) -> let tm1 = List.map (fun eqn -> List.hd eqn.patterns) pb.mat in (match find_row_ind tm1 with | None -> (current,tmtyp) | Some (_,(ind,_)) -> let indt = inductive_template pb.evdref pb.env None ind in let current = if List.is_empty deps && isEvar typ then let _ = e_cumul pb.env pb.evdref indt typ in current else (evd_comb2 (Coercion.inh_conv_coerce_to true Loc.ghost pb.env) pb.evdref (make_judge current typ) indt).uj_val in let sigma = !(pb.evdref) in (current,try_find_ind pb.env sigma indt names)) | _ -> (current,tmtyp) let type_of_tomatch = function | IsInd (t,_,_) -> t | NotInd (_,t) -> t let map_tomatch_type f = function | IsInd (t,ind,names) -> IsInd (f t,map_inductive_type f ind,names) | NotInd (c,t) -> NotInd (Option.map f c, f t) let liftn_tomatch_type n depth = map_tomatch_type (liftn n depth) let lift_tomatch_type n = liftn_tomatch_type n 1 Utilities on patterns let current_pattern eqn = match eqn.patterns with | pat::_ -> pat | [] -> anomaly (Pp.str "Empty list of patterns") let alias_of_pat = function | PatVar (_,name) -> name | PatCstr(_,_,_,name) -> name let remove_current_pattern eqn = match eqn.patterns with | pat::pats -> { eqn with patterns = pats; alias_stack = alias_of_pat pat :: eqn.alias_stack } | [] -> anomaly (Pp.str "Empty list of patterns") let push_current_pattern (cur,ty) eqn = match eqn.patterns with | pat::pats -> let rhs_env = push_rel (alias_of_pat pat,Some cur,ty) eqn.rhs.rhs_env in { eqn with rhs = { eqn.rhs with rhs_env = rhs_env }; patterns = pats } | [] -> anomaly (Pp.str "Empty list of patterns") let push_noalias_current_pattern eqn = match eqn.patterns with | _::pats -> { eqn with patterns = pats } | [] -> anomaly (Pp.str "push_noalias_current_pattern: Empty list of patterns") let prepend_pattern tms eqn = {eqn with patterns = } exception NotAdjustable let rec adjust_local_defs loc = function | (pat :: pats, (_,None,_) :: decls) -> pat :: adjust_local_defs loc (pats,decls) | (pats, (_,Some _,_) :: decls) -> PatVar (loc, Anonymous) :: adjust_local_defs loc (pats,decls) | [], [] -> [] | _ -> raise NotAdjustable let check_and_adjust_constructor env ind cstrs = function | PatVar _ as pat -> pat | PatCstr (loc,((_,i) as cstr),args,alias) as pat -> let ind' = inductive_of_constructor cstr in if eq_ind ind' ind then let ci = cstrs.(i-1) in let nb_args_constr = ci.cs_nargs in if Int.equal (List.length args) nb_args_constr then pat else try let args' = adjust_local_defs loc (args, List.rev ci.cs_args) in PatCstr (loc, cstr, args', alias) with NotAdjustable -> error_wrong_numarg_constructor_loc loc env cstr nb_args_constr else try Coercion.inh_pattern_coerce_to loc env pat ind' ind with Not_found -> error_bad_constructor_loc loc env cstr ind let check_all_variables env sigma typ mat = List.iter (fun eqn -> match current_pattern eqn with | PatVar (_,id) -> () | PatCstr (loc,cstr_sp,_,_) -> error_bad_pattern_loc loc env sigma cstr_sp typ) mat let check_unused_pattern env eqn = if not !(eqn.used) then raise_pattern_matching_error (eqn.eqn_loc, env, Evd.empty, UnusedClause eqn.patterns) let set_used_pattern eqn = eqn.used := true let extract_rhs pb = match pb.mat with | [] -> errorlabstrm "build_leaf" (msg_may_need_inversion()) | eqn::_ -> set_used_pattern eqn; eqn.rhs let occur_in_rhs na rhs = match na with | Anonymous -> false | Name id -> Id.List.mem id rhs.rhs_vars let is_dep_patt_in eqn = function | PatVar (_,name) -> Flags.is_program_mode () || occur_in_rhs name eqn.rhs | PatCstr _ -> true let mk_dep_patt_row (pats,_,eqn) = List.map (is_dep_patt_in eqn) pats let dependencies_in_pure_rhs nargs eqns = if List.is_empty eqns then let deps_rows = List.map mk_dep_patt_row eqns in let deps_columns = matrix_transpose deps_rows in List.map (List.exists (fun x -> x)) deps_columns let dependent_decl a = function | (na,None,t) -> dependent a t | (na,Some c,t) -> dependent a t || dependent a c let rec dep_in_tomatch n = function | (Pushed _ | Alias _ | NonDepAlias) :: l -> dep_in_tomatch n l | Abstract (_,d) :: l -> dependent_decl (mkRel n) d || dep_in_tomatch (n+1) l | [] -> false let dependencies_in_rhs nargs current tms eqns = match kind_of_term current with | Rel n when dep_in_tomatch n tms -> List.make nargs true | _ -> dependencies_in_pure_rhs nargs eqns [ find_dependency_list tmi [ d(i+1); ... ;dn ] ] computes in which declarations [ d(i+1); ... ;dn ] the term [ tmi ] is dependent in . [ find_dependencies_signature ( used1, ... ,usedn ) ( ( tm1,d1), ... ,(tmn , dn ) ) ] returns [ ( deps1, ... ,depsn ) ] where [ depsi ] is a subset of n, .. ,i+1 denoting in which of the d(i+1) ... dn , the term tmi is dependent . Dependencies are expressed by index , e.g. in dependency list [ n-2;1 ] , [ 1 ] points to [ dn ] and [ n-2 ] to [ d3 ] declarations [d(i+1);...;dn] the term [tmi] is dependent in. [find_dependencies_signature (used1,...,usedn) ((tm1,d1),...,(tmn,dn))] returns [(deps1,...,depsn)] where [depsi] is a subset of n,..,i+1 denoting in which of the d(i+1)...dn, the term tmi is dependent. Dependencies are expressed by index, e.g. in dependency list [n-2;1], [1] points to [dn] and [n-2] to [d3] *) let rec find_dependency_list tmblock = function | [] -> [] | (used,tdeps,d)::rest -> let deps = find_dependency_list tmblock rest in if used && List.exists (fun x -> dependent_decl x d) tmblock then List.add_set Int.equal (List.length rest + 1) (List.union Int.equal deps tdeps) else deps let find_dependencies is_dep_or_cstr_in_rhs (tm,(_,tmtypleaves),d) nextlist = let deps = find_dependency_list (tm::tmtypleaves) nextlist in if is_dep_or_cstr_in_rhs || not (List.is_empty deps) then ((true ,deps,d)::nextlist) else ((false,[] ,d)::nextlist) let find_dependencies_signature deps_in_rhs typs = let l = List.fold_right2 find_dependencies deps_in_rhs typs [] in List.map (fun (_,deps,_) -> deps) l Assume we had terms t1 .. tq to match in a context xp : Tp, ... ,x1 : T1 |- and xn : Tn has just been regeneralized into x : Tn so that the terms to match are now to be considered in the context xp : Tp, ... ,x1 : T1,x : Tn |- . [ relocate_index_tomatch n 1 tomatch ] updates t1 .. tq so that former references to are now references to x. Note that t1 .. tq are already adjusted to the context xp : Tp, ... ,x1 : T1,x : Tn |- . [ relocate_index_tomatch 1 n tomatch ] will go the way back . and xn:Tn has just been regeneralized into x:Tn so that the terms to match are now to be considered in the context xp:Tp,...,x1:T1,x:Tn |-. [relocate_index_tomatch n 1 tomatch] updates t1..tq so that former references to xn1 are now references to x. Note that t1..tq are already adjusted to the context xp:Tp,...,x1:T1,x:Tn |-. [relocate_index_tomatch 1 n tomatch] will go the way back. *) let relocate_index_tomatch n1 n2 = let rec genrec depth = function | [] -> [] | Pushed (b,((c,tm),l,na)) :: rest -> let c = relocate_index n1 n2 depth c in let tm = map_tomatch_type (relocate_index n1 n2 depth) tm in let l = List.map (relocate_rel n1 n2 depth) l in Pushed (b,((c,tm),l,na)) :: genrec depth rest | Alias (initial,(na,c,d)) :: rest -> Alias (initial,(na,c,map_pair (relocate_index n1 n2 depth) d)) :: genrec depth rest | NonDepAlias :: rest -> NonDepAlias :: genrec depth rest | Abstract (i,d) :: rest -> let i = relocate_rel n1 n2 depth i in Abstract (i,map_rel_declaration (relocate_index n1 n2 depth) d) :: genrec (depth+1) rest in genrec 0 [ replace_tomatch n c tomatch ] replaces [ Rel n ] by [ c ] in [ tomatch ] let rec replace_term n c k t = if isRel t && Int.equal (destRel t) (n + k) then lift k c else map_constr_with_binders succ (replace_term n c) k t let length_of_tomatch_type_sign na t = let l = match na with | Anonymous -> 0 | Name _ -> 1 in match t with | NotInd _ -> l | IsInd (_, _, names) -> List.length names + l let replace_tomatch n c = let rec replrec depth = function | [] -> [] | Pushed (initial,((b,tm),l,na)) :: rest -> let b = replace_term n c depth b in let tm = map_tomatch_type (replace_term n c depth) tm in List.iter (fun i -> if Int.equal i (n + depth) then anomaly (Pp.str "replace_tomatch")) l; Pushed (initial,((b,tm),l,na)) :: replrec depth rest | Alias (initial,(na,b,d)) :: rest -> Alias (initial,(na,b,map_pair (replace_term n c depth) d)) :: replrec depth rest | NonDepAlias :: rest -> NonDepAlias :: replrec depth rest | Abstract (i,d) :: rest -> Abstract (i,map_rel_declaration (replace_term n c depth) d) :: replrec (depth+1) rest in replrec 0 let rec liftn_tomatch_stack n depth = function | [] -> [] | Pushed (initial,((c,tm),l,na))::rest -> let c = liftn n depth c in let tm = liftn_tomatch_type n depth tm in let l = List.map (fun i -> if i<depth then i else i+n) l in Pushed (initial,((c,tm),l,na))::(liftn_tomatch_stack n depth rest) | Alias (initial,(na,c,d))::rest -> Alias (initial,(na,liftn n depth c,map_pair (liftn n depth) d)) ::(liftn_tomatch_stack n depth rest) | NonDepAlias :: rest -> NonDepAlias :: liftn_tomatch_stack n depth rest | Abstract (i,d)::rest -> let i = if i<depth then i else i+n in Abstract (i,map_rel_declaration (liftn n depth) d) ::(liftn_tomatch_stack n (depth+1) rest) let lift_tomatch_stack n = liftn_tomatch_stack n 1 if [ current ] has type [ I(p1 ... pn u1 ... um ) ] and we consider the case of constructor [ ci ] of type [ I(p1 ... pn u'1 ... ) ] , then the default variable [ name ] is expected to have which type ? Rem : [ current ] is [ ( Rel i ) ] except perhaps for initial terms to match of constructor [ci] of type [I(p1...pn u'1...u'm)], then the default variable [name] is expected to have which type? Rem: [current] is [(Rel i)] except perhaps for initial terms to match *) Typical requirement : [ match y with ( S ( S x ) ) = > x | x = > x end ] should be compiled into [ match y with O = > y | ( S n ) = > match n with O = > y | ( S x ) = > x end end ] and [ match y with ( S ( S n ) ) = > n | n = > n end ] into [ match y with O = > y | ( S n0 ) = > match n0 with O = > y | ( S n ) = > n end end ] i.e. user names should be preserved and created names should not interfere with user names The exact names here are not important for typing ( because they are put in pb.env and not in the rhs.rhs_env of branches . However , whether a name is or not may have an effect on whether a generalization is done or not . [match y with (S (S x)) => x | x => x end] should be compiled into [match y with O => y | (S n) => match n with O => y | (S x) => x end end] and [match y with (S (S n)) => n | n => n end] into [match y with O => y | (S n0) => match n0 with O => y | (S n) => n end end] i.e. user names should be preserved and created names should not interfere with user names The exact names here are not important for typing (because they are put in pb.env and not in the rhs.rhs_env of branches. However, whether a name is Anonymous or not may have an effect on whether a generalization is done or not. *) let merge_name get_name obj = function | Anonymous -> get_name obj | na -> na let merge_names get_name = List.map2 (merge_name get_name) let get_names env sign eqns = let names1 = List.make (List.length sign) Anonymous in let names2,aliasname = List.fold_right (fun (pats,pat_alias,eqn) (names,aliasname) -> (merge_names alias_of_pat pats names, merge_name (fun x -> x) pat_alias aliasname)) eqns (names1,Anonymous) in let allvars = List.fold_left (fun l (_,_,eqn) -> List.union Id.equal l eqn.rhs.avoid_ids) [] eqns in let names3,_ = List.fold_left2 (fun (l,avoid) d na -> let na = merge_name (fun (na,_,t) -> Name (next_name_away (named_hd env t na) avoid)) d na in (na::l,(out_name na)::avoid)) ([],allvars) (List.rev sign) names2 in names3,aliasname xi1 .. to be found in the i - th clause of the matrix let set_declaration_name x (_,c,t) = (x,c,t) let recover_initial_subpattern_names = List.map2 set_declaration_name let recover_alias_names get_name = List.map2 (fun x (_,c,t) ->(get_name x,c,t)) let push_rels_eqn sign eqn = {eqn with rhs = {eqn.rhs with rhs_env = push_rel_context sign eqn.rhs.rhs_env} } let push_rels_eqn_with_names sign eqn = let subpats = List.rev (List.firstn (List.length sign) eqn.patterns) in let subpatnames = List.map alias_of_pat subpats in let sign = recover_initial_subpattern_names subpatnames sign in push_rels_eqn sign eqn let push_generalized_decl_eqn env n (na,c,t) eqn = let na = match na with | Anonymous -> Anonymous | Name id -> pi1 (Environ.lookup_rel n eqn.rhs.rhs_env) in push_rels_eqn [(na,c,t)] eqn let drop_alias_eqn eqn = { eqn with alias_stack = List.tl eqn.alias_stack } let push_alias_eqn alias eqn = let aliasname = List.hd eqn.alias_stack in let eqn = drop_alias_eqn eqn in let alias = set_declaration_name aliasname alias in push_rels_eqn [alias] eqn The problem to solve is the following : We match Gamma |- t : I(u01 .. u0q ) against the following constructors : Gamma , x11 ... x1p1 |- C1(x11 .. x1p1 ) : I(u11 .. u1q ) ... Gamma , xn1 ... |- Cn(xn1 .. xnp1 ) : I(un1 .. unq ) Assume the types in the branches are the following Gamma , x11 ... x1p1 |- : T1 ... Gamma , xn1 ... |- branchn : Tn Assume the type of the global case expression is Gamma |- T The predicate has the form = [ y1 .. yq][z : I(y1 .. yq)]psi and it has to satisfy the following n+1 equations : Gamma , x11 ... x1p1 |- ( phi u11 .. u1q ( C1 x11 .. x1p1 ) ) = T1 ... Gamma , xn1 ... ( phi un1 .. unq ( Cn xn1 .. xnpn ) ) = Tn Gamma |- ( phi u01 .. u0q t ) = T Some hints : - Clearly , if xij occurs in Ti , then , a " match z with ( ) = > ... end " or a " psi(yk ) " , with psi extracting xij from uik , should be inserted somewhere in Ti . - If T is undefined , an easy solution is to insert a " match z with ( Ci xi1 .. ) = > ... end " in front of each Ti - Otherwise , T1 .. Tn and T must be step by step unified , if some of them diverge , then try to replace the diverging subterm by one of y1 .. yq or main problem is what to do when an existential variables is encountered The problem to solve is the following: We match Gamma |- t : I(u01..u0q) against the following constructors: Gamma, x11...x1p1 |- C1(x11..x1p1) : I(u11..u1q) ... Gamma, xn1...xnpn |- Cn(xn1..xnp1) : I(un1..unq) Assume the types in the branches are the following Gamma, x11...x1p1 |- branch1 : T1 ... Gamma, xn1...xnpn |- branchn : Tn Assume the type of the global case expression is Gamma |- T The predicate has the form phi = [y1..yq][z:I(y1..yq)]psi and it has to satisfy the following n+1 equations: Gamma, x11...x1p1 |- (phi u11..u1q (C1 x11..x1p1)) = T1 ... Gamma, xn1...xnpn |- (phi un1..unq (Cn xn1..xnpn)) = Tn Gamma |- (phi u01..u0q t) = T Some hints: - Clearly, if xij occurs in Ti, then, a "match z with (Ci xi1..xipi) => ... end" or a "psi(yk)", with psi extracting xij from uik, should be inserted somewhere in Ti. - If T is undefined, an easy solution is to insert a "match z with (Ci xi1..xipi) => ... end" in front of each Ti - Otherwise, T1..Tn and T must be step by step unified, if some of them diverge, then try to replace the diverging subterm by one of y1..yq or z. - The main problem is what to do when an existential variables is encountered *) let rec map_predicate f k ccl = function | [] -> f k ccl | Pushed (_,((_,tm),_,na)) :: rest -> let k' = length_of_tomatch_type_sign na tm in map_predicate f (k+k') ccl rest | (Alias _ | NonDepAlias) :: rest -> map_predicate f k ccl rest | Abstract _ :: rest -> map_predicate f (k+1) ccl rest let noccur_predicate_between n = map_predicate (noccur_between n) let liftn_predicate n = map_predicate (liftn n) let lift_predicate n = liftn_predicate n 1 let regeneralize_index_predicate n = map_predicate (relocate_index n 1) 0 let substnl_predicate sigma = map_predicate (substnl sigma) let subst_predicate (args,copt) ccl tms = let sigma = match copt with | None -> List.rev args | Some c -> c::(List.rev args) in substnl_predicate sigma 0 ccl tms let specialize_predicate_var (cur,typ,dep) tms ccl = let c = match dep with | Anonymous -> None | Name _ -> Some cur in let l = match typ with | IsInd (_, IndType (_, _), []) -> [] | IsInd (_, IndType (_, realargs), names) -> realargs | NotInd _ -> [] in subst_predicate (l,c) ccl tms We have pred = [ X:=realargs;x:=c]P typed in Gamma1 , x : I(realargs ) , Gamma2 and we want to abstract P over y : ) typed in the same context to get We first need to lift ) it is typed in Gamma , X:=rargs , x ' then we have to replace x by x ' in ) and y by y ' in P let generalize_predicate (names,na) ny d tms ccl = let () = match na with | Anonymous -> anomaly (Pp.str "Undetected dependency") | _ -> () in let p = List.length names + 1 in let ccl = lift_predicate 1 ccl tms in regeneralize_index_predicate (ny+p+1) ccl tms where pred is computed by abstract_predicate and PI tms.ccl by let rec extract_predicate ccl = function | (Alias _ | NonDepAlias)::tms -> extract_predicate ccl tms | Abstract (i,d)::tms -> mkProd_wo_LetIn d (extract_predicate ccl tms) | Pushed (_,((cur,NotInd _),_,na))::tms -> begin match na with | Anonymous -> extract_predicate ccl tms | Name _ -> let tms = lift_tomatch_stack 1 tms in let pred = extract_predicate ccl tms in subst1 cur pred end | Pushed (_,((cur,IsInd (_,IndType(_,realargs),_)),_,na))::tms -> let realargs = List.rev realargs in let k, nrealargs = match na with | Anonymous -> 0, realargs | Name _ -> 1, (cur :: realargs) in let tms = lift_tomatch_stack (List.length realargs + k) tms in let pred = extract_predicate ccl tms in substl nrealargs pred | [] -> ccl let abstract_predicate env sigma indf cur realargs (names,na) tms ccl = let sign = make_arity_signature env true indf in let n = List.length sign in let tms = List.fold_right2 (fun par arg tomatch -> match kind_of_term par with | Rel i -> relocate_index_tomatch (i+n) (destRel arg) tomatch | _ -> tomatch) (realargs@[cur]) (extended_rel_list 0 sign) (lift_tomatch_stack n tms) in let ccl = match na with | Anonymous -> lift_predicate 1 ccl tms | Name _ -> ccl in let pred = extract_predicate ccl tms in let sign = List.map2 set_declaration_name (na::names) sign in it_mkLambda_or_LetIn_name env pred sign [ expand_arg ] is used by [ specialize_predicate ] if Yk denotes [ Xk;xk ] or [ Xk ] , it replaces gamma , x1 ... xn , x1 ... xk Yk+1 ... Yn |- pred by gamma , x1 ... xn , x1 ... xk-1 [ Xk;xk ] Yk+1 ... Yn |- pred ( if dep ) or by gamma , x1 ... xn , x1 ... xk-1 [ Xk ] Yk+1 ... Yn |- pred ( if not dep ) if Yk denotes [Xk;xk] or [Xk], it replaces gamma, x1...xn, x1...xk Yk+1...Yn |- pred by gamma, x1...xn, x1...xk-1 [Xk;xk] Yk+1...Yn |- pred (if dep) or by gamma, x1...xn, x1...xk-1 [Xk] Yk+1...Yn |- pred (if not dep) *) let expand_arg tms (p,ccl) ((_,t),_,na) = let k = length_of_tomatch_type_sign na t in (p+k,liftn_predicate (k-1) (p+1) ccl tms) let use_unit_judge evd = let j, ctx = coq_unit_judge () in let evd' = Evd.merge_context_set Evd.univ_flexible_alg evd ctx in evd', j let add_assert_false_case pb tomatch = let pats = List.map (fun _ -> PatVar (Loc.ghost,Anonymous)) tomatch in let aliasnames = List.map_filter (function Alias _ | NonDepAlias -> Some Anonymous | _ -> None) tomatch in [ { patterns = pats; rhs = { rhs_env = pb.env; rhs_vars = []; avoid_ids = []; it = None }; alias_stack = Anonymous::aliasnames; eqn_loc = Loc.ghost; used = ref false } ] let adjust_impossible_cases pb pred tomatch submat = match submat with | [] -> begin match kind_of_term pred with | Evar (evk,_) when snd (evar_source evk !(pb.evdref)) == Evar_kinds.ImpossibleCase -> if not (Evd.is_defined !(pb.evdref) evk) then begin let evd, default = use_unit_judge !(pb.evdref) in pb.evdref := Evd.define evk default.uj_type evd end; add_assert_false_case pb tomatch | _ -> submat end | _ -> submat Gamma |- match Pushed(c : I(V ) ) as x in I(X ) , tms return pred with ... end where the branch with constructor : T1) ... (xn : ) is considered . Assume each Ti is some Ii(argsi ) with Ti : PI Ui . sort_i pred ' = PI [ X1 : Ui;x1 : I1(X1)] ... [Xn : Un;xn : In(Xn ) ] . ( PI tms . P)[subst ] Gamma , x'1 .. x'n |- let specialize_predicate newtomatchs (names,depna) arsign cs tms ccl = Assume some gamma st : gamma |- PI [ X , x : I(X ) ] . PI tms . ccl let nrealargs = List.length names in let l = match depna with Anonymous -> 0 | Name _ -> 1 in let k = nrealargs + l in and X by the realargs for let n = cs.cs_nargs in let ccl' = liftn_predicate n (k+1) ccl tms in let realargsi = if not (Int.equal nrealargs 0) then adjust_subst_to_rel_context arsign (Array.to_list cs.cs_concl_realargs) else [] in let copti = match depna with | Anonymous -> None | Name _ -> Some (build_dependent_constructor cs) in The substituends realargsi , copti are all defined in gamma , x1 ... xn Note : applying the substitution in tms is not important ( is it sure ? ) let ccl'' = whd_betaiota Evd.empty (subst_predicate (realargsi, copti) ccl' tms) in let ccl''' = liftn_predicate n (n+1) ccl'' tms in We finally get gamma , x'1 .. x'n , x |- [ X1;x1 : I(X1)] .. : I(Xn)]pred '' ' snd (List.fold_left (expand_arg tms) (1,ccl''') newtomatchs) let find_predicate loc env evdref p current (IndType (indf,realargs)) dep tms = let pred = abstract_predicate env !evdref indf current realargs dep tms p in (pred, whd_betaiota !evdref (applist (pred, realargs@[current]))) let adjust_predicate_from_tomatch tomatch (current,typ as ct) pb = let ((_,oldtyp),deps,na) = tomatch in match typ, oldtyp with | IsInd (_,_,names), NotInd _ -> let k = match na with | Anonymous -> 1 | Name _ -> 2 in let n = List.length names in { pb with pred = liftn_predicate n k pb.pred pb.tomatch }, (ct,List.map (fun i -> if i >= k then i+n else i) deps,na) | _ -> pb, (ct,deps,na) let rec ungeneralize n ng body = match kind_of_term body with | Lambda (_,_,c) when Int.equal ng 0 -> subst1 (mkRel n) c | Lambda (na,t,c) -> mkLambda (na,t,ungeneralize (n+1) (ng-1) c) | LetIn (na,b,t,c) -> mkLetIn (na,b,t,ungeneralize (n+1) ng c) | Case (ci,p,c,brs) -> let p = let sign,p = decompose_lam_assum p in let sign2,p = decompose_prod_n_assum ng p in let p = prod_applist p [mkRel (n+List.length sign+ng)] in it_mkLambda_or_LetIn (it_mkProd_or_LetIn p sign2) sign in mkCase (ci,p,c,Array.map2 (fun q c -> let sign,b = decompose_lam_n_assum q c in it_mkLambda_or_LetIn (ungeneralize (n+q) ng b) sign) ci.ci_cstr_ndecls brs) | App (f,args) -> assert (isCase f); mkApp (ungeneralize n (ng+Array.length args) f,args) | _ -> assert false let ungeneralize_branch n k (sign,body) cs = (sign,ungeneralize (n+cs.cs_nargs) k body) let rec is_dependent_generalization ng body = match kind_of_term body with | Lambda (_,_,c) when Int.equal ng 0 -> dependent (mkRel 1) c | Lambda (na,t,c) -> is_dependent_generalization (ng-1) c | LetIn (na,b,t,c) -> is_dependent_generalization ng c | Case (ci,p,c,brs) -> Array.exists2 (fun q c -> let _,b = decompose_lam_n_assum q c in is_dependent_generalization ng b) ci.ci_cstr_ndecls brs | App (g,args) -> assert (isCase g); is_dependent_generalization (ng+Array.length args) g | _ -> assert false let is_dependent_branch k (_,br) = is_dependent_generalization k br let postprocess_dependencies evd tocheck brs tomatch pred deps cs = let rec aux k brs tomatch pred tocheck deps = match deps, tomatch with | [], _ -> brs,tomatch,pred,[] | n::deps, Abstract (i,d) :: tomatch -> let d = map_rel_declaration (nf_evar evd) d in let is_d = match d with (_, None, _) -> false | _ -> true in if is_d || List.exists (fun c -> dependent_decl (lift k c) d) tocheck && Array.exists (is_dependent_branch k) brs then let brs,tomatch,pred,inst = aux (k+1) brs tomatch pred (mkRel n::tocheck) deps in let inst = match d with | (_, None, _) -> mkRel n :: inst | _ -> inst in brs, Abstract (i,d) :: tomatch, pred, inst else let pred = lift_predicate (-1) pred tomatch in let tomatch = relocate_index_tomatch 1 (n+1) tomatch in let tomatch = lift_tomatch_stack (-1) tomatch in let brs = Array.map2 (ungeneralize_branch n k) brs cs in aux k brs tomatch pred tocheck deps | _ -> assert false in aux 0 brs tomatch pred tocheck deps let rec irrefutable env = function | PatVar (_,name) -> true | PatCstr (_,cstr,args,_) -> let ind = inductive_of_constructor cstr in let (_,mip) = Inductive.lookup_mind_specif env ind in let one_constr = Int.equal (Array.length mip.mind_user_lc) 1 in one_constr && List.for_all (irrefutable env) args let first_clause_irrefutable env = function | eqn::mat -> List.for_all (irrefutable env) eqn.patterns | _ -> false let group_equations pb ind current cstrs mat = let mat = if first_clause_irrefutable pb.env mat then [List.hd mat] else mat in let brs = Array.make (Array.length cstrs) [] in let only_default = ref None in let _ = (fun eqn () -> let rest = remove_current_pattern eqn in let pat = current_pattern eqn in match check_and_adjust_constructor pb.env ind cstrs pat with | PatVar (_,name) -> for i=1 to Array.length cstrs do let args = make_anonymous_patvars cstrs.(i-1).cs_nargs in brs.(i-1) <- (args, name, rest) :: brs.(i-1) done; if !only_default == None then only_default := Some true | PatCstr (loc,((_,i)),args,name) -> only_default := Some false; brs.(i-1) <- (args, name, rest) :: brs.(i-1)) mat () in (brs,Option.default false !only_default) let rec generalize_problem names pb = function | [] -> pb, [] | i::l -> let (na,b,t as d) = map_rel_declaration (lift i) (Environ.lookup_rel i pb.env) in let pb',deps = generalize_problem names pb l in begin match (na, b) with | Anonymous, Some _ -> pb', deps | _ -> let tomatch = lift_tomatch_stack 1 pb'.tomatch in let tomatch = relocate_index_tomatch (i+1) 1 tomatch in { pb' with tomatch = Abstract (i,d) :: tomatch; pred = generalize_predicate names i d pb'.tomatch pb'.pred }, i::deps end let build_leaf pb = let rhs = extract_rhs pb in let j = pb.typing_function (mk_tycon pb.pred) rhs.rhs_env pb.evdref rhs.it in j_nf_evar !(pb.evdref) j let build_branch initial current realargs deps (realnames,curname) pb arsign eqns const_info = let history = push_history_pattern const_info.cs_nargs (fst const_info.cs_cstr) pb.history in let cs_args = const_info.cs_args in let names,aliasname = get_names pb.env cs_args eqns in let typs = List.map2 (fun (_,c,t) na -> (na,c,t)) cs_args names in let submat = List.map (fun (tms,_,eqn) -> prepend_pattern tms eqn) eqns in let typs' = List.map_i (fun i d -> (mkRel i,map_rel_declaration (lift i) d)) 1 typs in let extenv = push_rel_context typs pb.env in let typs' = List.map (fun (c,d) -> (c,extract_inductive_data extenv !(pb.evdref) d,d)) typs' in We compute over which of x(i+1) .. xn and x matching on xi will need a let dep_sign = find_dependencies_signature (dependencies_in_rhs const_info.cs_nargs current pb.tomatch eqns) (List.rev typs') in let ci = build_dependent_constructor const_info in Current context Gamma has the form Gamma1;cur : I(realargs);Gamma2 let cirealargs = Array.to_list const_info.cs_concl_realargs in let tomatch = List.fold_right2 (fun par arg tomatch -> match kind_of_term par with | Rel i -> replace_tomatch (i+const_info.cs_nargs) arg tomatch | _ -> tomatch) (current::realargs) (ci::cirealargs) (lift_tomatch_stack const_info.cs_nargs pb.tomatch) in let pred_is_not_dep = noccur_predicate_between 1 (List.length realnames + 1) pb.pred tomatch in let typs' = List.map2 (fun (tm,(tmtyp,_),(na,_,_)) deps -> let na = match curname, na with | Name _, Anonymous -> curname | Name _, Name _ -> na | Anonymous, _ -> if List.is_empty deps && pred_is_not_dep then Anonymous else force_name na in ((tm,tmtyp),deps,na)) typs' (List.rev dep_sign) in let pred = specialize_predicate typs' (realnames,curname) arsign const_info tomatch pb.pred in let currents = List.map (fun x -> Pushed (false,x)) typs' in let alias = match aliasname with | Anonymous -> NonDepAlias | Name _ -> let cur_alias = lift const_info.cs_nargs current in let ind = appvect ( applist (mkIndU (inductive_of_constructor (fst const_info.cs_cstr), snd const_info.cs_cstr), List.map (lift const_info.cs_nargs) const_info.cs_params), const_info.cs_concl_realargs) in Alias (initial,(aliasname,cur_alias,(ci,ind))) in let tomatch = List.rev_append (alias :: currents) tomatch in let submat = adjust_impossible_cases pb pred tomatch submat in let () = match submat with | [] -> raise_pattern_matching_error (Loc.ghost, pb.env, Evd.empty, NonExhaustive (complete_history history)) | _ -> () in typs, { pb with env = extenv; tomatch = tomatch; pred = pred; history = history; mat = List.map (push_rels_eqn_with_names typs) submat } * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * INVARIANT : pb = { env , pred , tomatch , mat , ... } tomatch = list of Pushed ( c : T ) , Abstract ( na : T ) , ( c : T ) or all terms and types in Pushed , Abstract and are relative to env enriched by the Abstract coming before INVARIANT: pb = { env, pred, tomatch, mat, ...} tomatch = list of Pushed (c:T), Abstract (na:T), Alias (c:T) or NonDepAlias all terms and types in Pushed, Abstract and Alias are relative to env enriched by the Abstract coming before *) let mk_case pb (ci,pred,c,brs) = let mib = lookup_mind (fst ci.ci_ind) pb.env in match mib.mind_record with | Some (Some (_, cs, pbs)) -> Reduction.beta_appvect brs.(0) (Array.map (fun p -> mkProj (Projection.make p true, c)) cs) | _ -> mkCase (ci,pred,c,brs) let rec compile pb = match pb.tomatch with | Pushed cur :: rest -> match_current { pb with tomatch = rest } cur | Alias (initial,x) :: rest -> compile_alias initial pb x rest | NonDepAlias :: rest -> compile_non_dep_alias pb rest | Abstract (i,d) :: rest -> compile_generalization pb i d rest | [] -> build_leaf pb and match_current pb (initial,tomatch) = let tm = adjust_tomatch_to_pattern pb tomatch in let pb,tomatch = adjust_predicate_from_tomatch tomatch tm pb in let ((current,typ),deps,dep) = tomatch in match typ with | NotInd (_,typ) -> check_all_variables pb.env !(pb.evdref) typ pb.mat; compile_all_variables initial tomatch pb | IsInd (_,(IndType(indf,realargs) as indt),names) -> let mind,_ = dest_ind_family indf in let mind = Tacred.check_privacy pb.env mind in let cstrs = get_constructors pb.env indf in let arsign, _ = get_arity pb.env indf in let eqns,onlydflt = group_equations pb (fst mind) current cstrs pb.mat in let no_cstr = Int.equal (Array.length cstrs) 0 in if (not no_cstr || not (List.is_empty pb.mat)) && onlydflt then compile_all_variables initial tomatch pb else let pb,deps = generalize_problem (names,dep) pb deps in let brvals = Array.map2 (compile_branch initial current realargs (names,dep) deps pb arsign) eqns cstrs in let depstocheck = current::binding_vars_of_inductive typ in let brvals,tomatch,pred,inst = postprocess_dependencies !(pb.evdref) depstocheck brvals pb.tomatch pb.pred deps cstrs in let brvals = Array.map (fun (sign,body) -> it_mkLambda_or_LetIn body sign) brvals in let (pred,typ) = find_predicate pb.caseloc pb.env pb.evdref pred current indt (names,dep) tomatch in let ci = make_case_info pb.env (fst mind) pb.casestyle in let pred = nf_betaiota !(pb.evdref) pred in let case = mk_case pb (ci,pred,current,brvals) in Typing.check_allowed_sort pb.env !(pb.evdref) mind current pred; { uj_val = applist (case, inst); uj_type = prod_applist typ inst } and shift_problem ((current,t),_,na) pb = let ty = type_of_tomatch t in let tomatch = lift_tomatch_stack 1 pb.tomatch in let pred = specialize_predicate_var (current,t,na) pb.tomatch pb.pred in let pb = { pb with env = push_rel (na,Some current,ty) pb.env; tomatch = tomatch; pred = lift_predicate 1 pred tomatch; history = pop_history pb.history; mat = List.map (push_current_pattern (current,ty)) pb.mat } in let j = compile pb in { uj_val = subst1 current j.uj_val; uj_type = subst1 current j.uj_type } and pop_problem ((current,t),_,na) pb = let pred = specialize_predicate_var (current,t,na) pb.tomatch pb.pred in let pb = { pb with pred = pred; history = pop_history pb.history; mat = List.map push_noalias_current_pattern pb.mat } in compile pb and compile_all_variables initial cur pb = if initial then shift_problem cur pb else pop_problem cur pb and compile_branch initial current realargs names deps pb arsign eqns cstr = let sign, pb = build_branch initial current realargs deps names pb arsign eqns cstr in sign, (compile pb).uj_val and compile_generalization pb i d rest = let pb = { pb with env = push_rel d pb.env; tomatch = rest; mat = List.map (push_generalized_decl_eqn pb.env i d) pb.mat } in let j = compile pb in { uj_val = mkLambda_or_LetIn d j.uj_val; uj_type = mkProd_wo_LetIn d j.uj_type } and compile_alias initial pb (na,orig,(expanded,expanded_typ)) rest = let f c t = let alias = (na,Some c,t) in let pb = { pb with env = push_rel alias pb.env; tomatch = lift_tomatch_stack 1 rest; pred = lift_predicate 1 pb.pred pb.tomatch; history = pop_history_pattern pb.history; mat = List.map (push_alias_eqn alias) pb.mat } in let j = compile pb in { uj_val = if isRel c || isVar c || count_occurrences (mkRel 1) j.uj_val <= 1 then subst1 c j.uj_val else mkLetIn (na,c,t,j.uj_val); uj_type = subst1 c j.uj_type } in let just_pop () = let pb = { pb with tomatch = rest; history = pop_history_pattern pb.history; mat = List.map drop_alias_eqn pb.mat } in compile pb in let sigma = !(pb.evdref) in if not (Flags.is_program_mode ()) && (isRel orig || isVar orig) then Try to compile first using non expanded alias try if initial then f orig (Retyping.get_type_of pb.env !(pb.evdref) orig) else just_pop () with e when precatchable_exception e -> pb.evdref := sigma; f expanded expanded_typ else Try to compile first using expanded alias try f expanded expanded_typ with e when precatchable_exception e -> pb.evdref := sigma; if initial then f orig (Retyping.get_type_of pb.env !(pb.evdref) orig) else just_pop () and compile_non_dep_alias pb rest = let pb = { pb with tomatch = rest; history = pop_history_pattern pb.history; mat = List.map drop_alias_eqn pb.mat } in compile pb pour les alias , enrichir les env de ce qu'il faut et substituer après par les initiaux substituer après par les initiaux *) builds the matrix of equations testing that each eqn has n patterns * and linearizing the _ patterns . * Syntactic correctness has already been done in astterm * and linearizing the _ patterns. * Syntactic correctness has already been done in astterm *) let matx_of_eqns env eqns = let build_eqn (loc,ids,lpat,rhs) = let initial_lpat,initial_rhs = lpat,rhs in let initial_rhs = rhs in let rhs = { rhs_env = env; rhs_vars = free_glob_vars initial_rhs; avoid_ids = ids@(ids_of_named_context (named_context env)); it = Some initial_rhs } in { patterns = initial_lpat; alias_stack = []; eqn_loc = loc; used = ref false; rhs = rhs } in List.map build_eqn eqns Let " match t1 in I1 u11 .. u1n_1 ... tm in I m um1 .. umn_m with ... end : T " be a pattern - matching problem . We assume that each uij can be decomposed under the form pij(vij1 .. vijq_ij ) where .. aijq_ij ) is a pattern depending on some variables aijk and the vijk are instances of these variables . We also assume that each ti has the form of a pattern qi(wi1 .. wiq_i ) where qi(bi1 .. ) is a pattern depending on some variables bik and the wik are instances of these variables ( in practice , there is no reason that ti is already constructed and the qi will be degenerated ) . We then look for a type U( .. a1jk .. b1 .. .. ) so that T = U( .. v1jk .. t1 .. .. vmjk .. tm ) . This a higher - order matching problem with a priori different solutions ( one of them if T itself ! ) . We finally invert the uij and the ti and build the return clause phi(x11 .. x1n_1y1 .. xm1 .. xmn_mym ) = match x11 .. x1n_1 y1 .. xm1 .. xmn_m ym with | p11 .. p1n_1 q1 .. pm1 .. pmn_m qm = > U( .. a1jk .. b1 .. .. ) | _ .. _ _ .. _ .. _ _ = > True end so that " phi(u11 .. u1n_1t1 .. um1 .. umn_mtm ) = T " ( note that the clause returning True never happens and any inhabited type can be put instead ) . be a pattern-matching problem. We assume that each uij can be decomposed under the form pij(vij1..vijq_ij) where pij(aij1..aijq_ij) is a pattern depending on some variables aijk and the vijk are instances of these variables. We also assume that each ti has the form of a pattern qi(wi1..wiq_i) where qi(bi1..biq_i) is a pattern depending on some variables bik and the wik are instances of these variables (in practice, there is no reason that ti is already constructed and the qi will be degenerated). We then look for a type U(..a1jk..b1 .. ..amjk..bm) so that T = U(..v1jk..t1 .. ..vmjk..tm). This a higher-order matching problem with a priori different solutions (one of them if T itself!). We finally invert the uij and the ti and build the return clause phi(x11..x1n_1y1..xm1..xmn_mym) = match x11..x1n_1 y1 .. xm1..xmn_m ym with | p11..p1n_1 q1 .. pm1..pmn_m qm => U(..a1jk..b1 .. ..amjk..bm) | _ .. _ _ .. _ .. _ _ => True end so that "phi(u11..u1n_1t1..um1..umn_mtm) = T" (note that the clause returning True never happens and any inhabited type can be put instead). *) let adjust_to_extended_env_and_remove_deps env extenv subst t = let n = rel_context_length (rel_context env) in let n' = rel_context_length (rel_context extenv) in We first remove the bindings that are dependently typed ( they are difficult to manage and it is not sure these are so useful in practice ) ; Notes : - [ subst ] is made of pairs [ ( id , u ) ] where i d is a name in [ extenv ] and [ u ] a term typed in [ env ] ; - [ subst0 ] is made of items [ ( p , u,(u , ty ) ) ] where [ ty ] is the type of [ u ] and both are adjusted to [ extenv ] while [ p ] is the index of [ i d ] in [ extenv ] ( after expansion of the aliases ) difficult to manage and it is not sure these are so useful in practice); Notes: - [subst] is made of pairs [(id,u)] where id is a name in [extenv] and [u] a term typed in [env]; - [subst0] is made of items [(p,u,(u,ty))] where [ty] is the type of [u] and both are adjusted to [extenv] while [p] is the index of [id] in [extenv] (after expansion of the aliases) *) let map (x, u) = let (p, _, _) = lookup_rel_id x (rel_context extenv) in let rec traverse_local_defs p = match pi2 (lookup_rel p extenv) with | Some c -> assert (isRel c); traverse_local_defs (p + destRel c) | None -> p in let p = traverse_local_defs p in let u = lift (n' - n) u in try Some (p, u, expand_vars_in_term extenv u) with Failure _ -> None in let subst0 = List.map_filter map subst in let t0 = lift (n' - n) t in (subst0, t0) let push_binder d (k,env,subst) = (k+1,push_rel d env,List.map (fun (na,u,d) -> (na,lift 1 u,d)) subst) let rec list_assoc_in_triple x = function [] -> raise Not_found | (a, b, _)::l -> if Int.equal a x then b else list_assoc_in_triple x l Let vijk and be a set of dependent terms and T a type , all * defined in some environment env . The vijk and ti are supposed to be * instances for variables aijk and bi . * * [ abstract_tycon Gamma0 Sigma subst T Gamma ] looks for U( .. v1jk .. t1 .. .. vmjk .. tm ) * defined in some extended context * " Gamma0 , .. a1jk : V1jk .. b1 : W1 .. .. amjk : Vmjk .. bm : Wm " * such that env |- T = U( .. v1jk .. t1 .. .. vmjk .. tm ) . To not commit to * a particular solution , we replace each subterm t in T that unifies with * a subset u1 .. ul of the vijk and ti by a special evar * ? id(x = t;c1:=c1, .. ,cl = cl ) defined in context Gamma0,x , ... ,cl |- ? i d * ( where the c1 .. cl are the aijk and bi matching the u1 .. ul ) , and * similarly for each ti . * defined in some environment env. The vijk and ti are supposed to be * instances for variables aijk and bi. * * [abstract_tycon Gamma0 Sigma subst T Gamma] looks for U(..v1jk..t1 .. ..vmjk..tm) * defined in some extended context * "Gamma0, ..a1jk:V1jk.. b1:W1 .. ..amjk:Vmjk.. bm:Wm" * such that env |- T = U(..v1jk..t1 .. ..vmjk..tm). To not commit to * a particular solution, we replace each subterm t in T that unifies with * a subset u1..ul of the vijk and ti by a special evar * ?id(x=t;c1:=c1,..,cl=cl) defined in context Gamma0,x,c1,...,cl |- ?id * (where the c1..cl are the aijk and bi matching the u1..ul), and * similarly for each ti. *) let abstract_tycon loc env evdref subst tycon extenv t = let src = match kind_of_term t with | Evar (evk,_) -> (loc,Evar_kinds.SubEvar evk) | _ -> (loc,Evar_kinds.CasesType true) in let subst0,t0 = adjust_to_extended_env_and_remove_deps env extenv subst t in We traverse the type T of the original problem looking for subterms that match the non - constructor part of the constraints ( this part is in subst ) ; these subterms are the " good " subterms and we replace them by an evar that may depend ( and only depend ) on the corresponding convertible subterms of the substitution that match the non-constructor part of the constraints (this part is in subst); these subterms are the "good" subterms and we replace them by an evar that may depend (and only depend) on the corresponding convertible subterms of the substitution *) let rec aux (k,env,subst as x) t = let t = whd_evar !evdref t in match kind_of_term t with | Rel n when pi2 (lookup_rel n env) != None -> t | Evar ev -> let ty = get_type_of env !evdref t in let ty = Evarutil.evd_comb1 (refresh_universes (Some false) env) evdref ty in let inst = List.map_i (fun i _ -> try list_assoc_in_triple i subst0 with Not_found -> mkRel i) 1 (rel_context env) in let ev' = e_new_evar env evdref ~src ty in begin match solve_simple_eqn (evar_conv_x full_transparent_state) env !evdref (None,ev,substl inst ev') with | Success evd -> evdref := evd | UnifFailure _ -> assert false end; ev' | _ -> let good = List.filter (fun (_,u,_) -> is_conv_leq env !evdref t u) subst in match good with | [] -> map_constr_with_full_binders push_binder aux x t u is in extenv let vl = List.map pi1 good in let ty = let ty = get_type_of env !evdref t in Evarutil.evd_comb1 (refresh_universes (Some false) env) evdref ty in let ty = lift (-k) (aux x ty) in let depvl = free_rels ty in let inst = List.map_i (fun i _ -> if Int.List.mem i vl then u else mkRel i) 1 (rel_context extenv) in let rel_filter = List.map (fun a -> not (isRel a) || dependent a u || Int.Set.mem (destRel a) depvl) inst in let named_filter = List.map (fun (id,_,_) -> dependent (mkVar id) u) (named_context extenv) in let filter = Filter.make (rel_filter @ named_filter) in let candidates = u :: List.map mkRel vl in let ev = e_new_evar extenv evdref ~src ~filter ~candidates ty in lift k ev in aux (0,extenv,subst0) t0 let build_tycon loc env tycon_env subst tycon extenv evdref t = let t,tt = match t with | None -> let n = rel_context_length (rel_context env) in let n' = rel_context_length (rel_context tycon_env) in let impossible_case_type, u = e_new_type_evar (reset_context env) evdref univ_flexible_alg ~src:(loc,Evar_kinds.ImpossibleCase) in (lift (n'-n) impossible_case_type, mkSort u) | Some t -> let t = abstract_tycon loc tycon_env evdref subst tycon extenv t in let evd,tt = Typing.e_type_of extenv !evdref t in evdref := evd; (t,tt) in { uj_val = t; uj_type = tt } For a multiple pattern - matching problem on t1 .. tn with return * type T , [ build_inversion_problem Gamma Sigma ( t1 .. tn ) T ] builds a return * predicate for that is itself made by an auxiliary * pattern - matching problem of which the first clause reveals the * pattern structure of the constraints on the inductive types of the t1 .. tn , * and the second clause is a wildcard clause for catching the * impossible cases . See above " Building an inversion predicate " for * further explanations * type T, [build_inversion_problem Gamma Sigma (t1..tn) T] builds a return * predicate for Xi that is itself made by an auxiliary * pattern-matching problem of which the first clause reveals the * pattern structure of the constraints on the inductive types of the t1..tn, * and the second clause is a wildcard clause for catching the * impossible cases. See above "Building an inversion predicate" for * further explanations *) let build_inversion_problem loc env sigma tms t = let make_patvar t (subst,avoid) = let id = next_name_away (named_hd env t Anonymous) avoid in PatVar (Loc.ghost,Name id), ((id,t)::subst, id::avoid) in let rec reveal_pattern t (subst,avoid as acc) = match kind_of_term (whd_betadeltaiota env sigma t) with | Construct (cstr,u) -> PatCstr (Loc.ghost,cstr,[],Anonymous), acc | App (f,v) when isConstruct f -> let cstr,u = destConstruct f in let n = constructor_nrealargs_env env cstr in let l = List.lastn n (Array.to_list v) in let l,acc = List.fold_map' reveal_pattern l acc in PatCstr (Loc.ghost,cstr,l,Anonymous), acc | _ -> make_patvar t acc in let rec aux n env acc_sign tms acc = match tms with | [] -> [], acc_sign, acc | (t, IsInd (_,IndType(indf,realargs),_)) :: tms -> let patl,acc = List.fold_map' reveal_pattern realargs acc in let pat,acc = make_patvar t acc in let indf' = lift_inductive_family n indf in let sign = make_arity_signature env true indf' in let sign = recover_alias_names alias_of_pat (pat :: List.rev patl) sign in let p = List.length realargs in let env' = push_rel_context sign env in let patl',acc_sign,acc = aux (n+p+1) env' (sign@acc_sign) tms acc in patl@pat::patl',acc_sign,acc | (t, NotInd (bo,typ)) :: tms -> let pat,acc = make_patvar t acc in let d = (alias_of_pat pat,None,typ) in let patl,acc_sign,acc = aux (n+1) (push_rel d env) (d::acc_sign) tms acc in pat::patl,acc_sign,acc in let avoid0 = ids_of_context env in [ patl ] is a list of patterns revealing the substructure of constructors present in the constraints on the type of the multiple terms t1 .. tn that are matched in the original problem ; [ subst ] is the substitution of the free pattern variables in [ patl ] that returns the non - constructor parts of the constraints . Especially , if the ti has type I ui1 .. uin_i , and the patterns associated to ti are pi1 .. pin_i , then subst(pij ) is uij ; the substitution is useful to recognize which subterms of the whole type T of the original problem have to be abstracted constructors present in the constraints on the type of the multiple terms t1..tn that are matched in the original problem; [subst] is the substitution of the free pattern variables in [patl] that returns the non-constructor parts of the constraints. Especially, if the ti has type I ui1..uin_i, and the patterns associated to ti are pi1..pin_i, then subst(pij) is uij; the substitution is useful to recognize which subterms of the whole type T of the original problem have to be abstracted *) let patl,sign,(subst,avoid) = aux 0 env [] tms ([],avoid0) in let n = List.length sign in let decls = List.map_i (fun i d -> (mkRel i,map_rel_declaration (lift i) d)) 1 sign in let pb_env = push_rel_context sign env in let decls = List.map (fun (c,d) -> (c,extract_inductive_data pb_env sigma d,d)) decls in let decls = List.rev decls in let dep_sign = find_dependencies_signature (List.make n true) decls in let sub_tms = List.map2 (fun deps (tm,(tmtyp,_),(na,b,t)) -> let na = if List.is_empty deps then Anonymous else force_name na in Pushed (true,((tm,tmtyp),deps,na))) dep_sign decls in let subst = List.map (fun (na,t) -> (na,lift n t)) subst in [ eqn1 ] is the first clause of the auxiliary pattern - matching that serves as skeleton for the return type : [ patl ] is the substructure of constructors extracted from the list of constraints on the inductive types of the multiple terms matched in the original pattern - matching problem serves as skeleton for the return type: [patl] is the substructure of constructors extracted from the list of constraints on the inductive types of the multiple terms matched in the original pattern-matching problem Xi *) let eqn1 = { patterns = patl; alias_stack = []; eqn_loc = Loc.ghost; used = ref false; rhs = { rhs_env = pb_env; we assume all vars are used ; in practice we discard dependent vars so that the field rhs_vars is normally not used vars so that the field rhs_vars is normally not used *) rhs_vars = List.map fst subst; avoid_ids = avoid; it = Some (lift n t) } } in [ eqn2 ] is the default clause of the auxiliary pattern - matching : it will catch the clauses of the original pattern - matching problem whose type constraints are incompatible with the constraints on the inductive types of the multiple terms matched in catch the clauses of the original pattern-matching problem Xi whose type constraints are incompatible with the constraints on the inductive types of the multiple terms matched in Xi *) let eqn2 = { patterns = List.map (fun _ -> PatVar (Loc.ghost,Anonymous)) patl; alias_stack = []; eqn_loc = Loc.ghost; used = ref false; rhs = { rhs_env = pb_env; rhs_vars = []; avoid_ids = avoid0; it = None } } in [ pb ] is the auxiliary pattern - matching serving as skeleton for the return type of the original problem return type of the original problem Xi *) let sigma , s = sigma in let sigma , s = sigma in let s' = Retyping.get_sort_of env sigma t in let sigma, s = Evd.new_sort_variable univ_flexible_alg sigma in let sigma = Evd.set_leq_sort env sigma s' s in let evdref = ref sigma in let pb = { env = pb_env; evdref = evdref; tomatch = sub_tms; history = start_history n; mat = [eqn1;eqn2]; caseloc = loc; casestyle = RegularStyle; typing_function = build_tycon loc env pb_env subst} in let pred = (compile pb).uj_val in (!evdref,pred) let build_initial_predicate arsign pred = let rec buildrec n pred tmnames = function | [] -> List.rev tmnames,pred | ((na,c,t)::realdecls)::lnames -> let n' = n + List.length realdecls in buildrec (n'+1) pred (force_name na::tmnames) lnames | _ -> assert false in buildrec 0 pred [] (List.rev arsign) let extract_arity_signature ?(dolift=true) env0 tomatchl tmsign = let lift = if dolift then lift else fun n t -> t in let get_one_sign n tm (na,t) = match tm with | NotInd (bo,typ) -> (match t with | None -> [na,Option.map (lift n) bo,lift n typ] | Some (loc,_,_) -> user_err_loc (loc,"", str"Unexpected type annotation for a term of non inductive type.")) | IsInd (term,IndType(indf,realargs),_) -> let indf' = if dolift then lift_inductive_family n indf else indf in let ((ind,u),_) = dest_ind_family indf' in let nrealargs_ctxt = inductive_nrealdecls_env env0 ind in let arsign = fst (get_arity env0 indf') in let realnal = match t with | Some (loc,ind',realnal) -> if not (eq_ind ind ind') then user_err_loc (loc,"",str "Wrong inductive type."); if not (Int.equal nrealargs_ctxt (List.length realnal)) then anomaly (Pp.str "Ill-formed 'in' clause in cases"); List.rev realnal | None -> List.make nrealargs_ctxt Anonymous in (na,None,build_dependent_inductive env0 indf') ::(List.map2 (fun x (_,c,t) ->(x,c,t)) realnal arsign) in let rec buildrec n = function | [],[] -> [] | (_,tm)::ltm, (_,x)::tmsign -> let l = get_one_sign n tm x in l :: buildrec (n + List.length l) (ltm,tmsign) | _ -> assert false in List.rev (buildrec 0 (tomatchl,tmsign)) let inh_conv_coerce_to_tycon loc env evdref j tycon = match tycon with | Some p -> let (evd',j) = Coercion.inh_conv_coerce_to true loc env !evdref j p in evdref := evd'; j | None -> j let prepare_predicate_from_arsign_tycon loc tomatchs arsign c = let nar = List.fold_left (fun n sign -> List.length sign + n) 0 arsign in let subst, len = List.fold_left2 (fun (subst, len) (tm, tmtype) sign -> let signlen = List.length sign in match kind_of_term tm with | Rel n when dependent tm c ((n, len) :: subst, len - signlen) (match tmtype with NotInd _ -> (subst, len - signlen) | IsInd (_, IndType(indf,realargs),_) -> let subst = if dependent tm c && List.for_all isRel realargs then (n, 1) :: subst else subst in List.fold_left (fun (subst, len) arg -> match kind_of_term arg with | Rel n when dependent arg c -> ((n, len) :: subst, pred len) | _ -> (subst, pred len)) (subst, len) realargs) | _ -> (subst, len - signlen)) ([], nar) tomatchs arsign in let rec predicate lift c = match kind_of_term c with | Rel n when n > lift -> (try let idx = Int.List.assoc (n - lift) subst in mkRel (idx + lift) with Not_found -> mkRel (n + nar)) | _ -> map_constr_with_binders succ predicate lift c in predicate 0 c Builds the predicate . If the predicate is dependent , its context is * made of 1+nrealargs assumptions for each matched term in an inductive * type and 1 assumption for each term not _ syntactically _ in an * inductive type . * Each matched terms are independently considered dependent or not . * A type constraint but no annotation case : we try to specialize the * tycon to make the predicate if it is not closed . * made of 1+nrealargs assumptions for each matched term in an inductive * type and 1 assumption for each term not _syntactically_ in an * inductive type. * Each matched terms are independently considered dependent or not. * A type constraint but no annotation case: we try to specialize the * tycon to make the predicate if it is not closed. *) let prepare_predicate loc typing_fun env sigma tomatchs arsign tycon pred = let preds = match pred, tycon with | None, Some t when not (noccur_with_meta 0 max_int t) -> two different strategies First strategy : we abstract the tycon wrt to the dependencies let pred1 = prepare_predicate_from_arsign_tycon loc tomatchs arsign t in Second strategy : we build an " inversion " predicate let sigma2,pred2 = build_inversion_problem loc env sigma tomatchs t in [sigma, pred1; sigma2, pred2] | None, _ -> we use two strategies let sigma,t = match tycon with | Some t -> sigma,t | None -> let sigma, (t, _) = new_type_evar env sigma univ_flexible_alg ~src:(loc, Evar_kinds.CasesType false) in sigma, t in First strategy : we build an " inversion " predicate let sigma1,pred1 = build_inversion_problem loc env sigma tomatchs t in Second strategy : we directly use the evar as a non dependent pred let pred2 = lift (List.length (List.flatten arsign)) t in [sigma1, pred1; sigma, pred2] | Some rtntyp, _ -> let envar = List.fold_right push_rel_context arsign env in let sigma, newt = new_sort_variable univ_flexible_alg sigma in let evdref = ref sigma in let predcclj = typing_fun (mk_tycon (mkSort newt)) envar evdref rtntyp in let sigma = !evdref in let tms = List.map ( fun tm - > Pushed(tm,[],na ) ) tomatchs in Coercion.inh_conv_coerce_to loc env ! ) ! in let predccl = (j_nf_evar sigma predcclj).uj_val in [sigma, predccl] in List.map (fun (sigma,pred) -> let (nal,pred) = build_initial_predicate arsign pred in sigma,nal,pred) preds open Program let ($) f x = f x let string_of_name name = match name with | Anonymous -> "anonymous" | Name n -> Id.to_string n let make_prime_id name = let str = string_of_name name in Id.of_string str, Id.of_string (str ^ "'") let prime avoid name = let previd, id = make_prime_id name in previd, next_ident_away id avoid let make_prime avoid prevname = let previd, id = prime !avoid prevname in avoid := id :: !avoid; previd, id let eq_id avoid id = let hid = Id.of_string ("Heq_" ^ Id.to_string id) in let hid' = next_ident_away hid avoid in hid' let mk_eq evdref typ x y = papp evdref coq_eq_ind [| typ; x ; y |] let mk_eq_refl evdref typ x = papp evdref coq_eq_refl [| typ; x |] let mk_JMeq evdref typ x typ' y = papp evdref coq_JMeq_ind [| typ; x ; typ'; y |] let mk_JMeq_refl evdref typ x = papp evdref coq_JMeq_refl [| typ; x |] let hole = GHole (Loc.ghost, Evar_kinds.QuestionMark (Evar_kinds.Define true), Misctypes.IntroAnonymous, None) let constr_of_pat env evdref arsign pat avoid = let rec typ env (ty, realargs) pat avoid = match pat with | PatVar (l,name) -> let name, avoid = match name with Name n -> name, avoid | Anonymous -> let previd, id = prime avoid (Name (Id.of_string "wildcard")) in Name id, id :: avoid in (PatVar (l, name), [name, None, ty] @ realargs, mkRel 1, ty, (List.map (fun x -> mkRel 1) realargs), 1, avoid) | PatCstr (l,((_, i) as cstr),args,alias) -> let cind = inductive_of_constructor cstr in let IndType (indf, _) = try find_rectype env ( !evdref) (lift (-(List.length realargs)) ty) with Not_found -> error_case_not_inductive env {uj_val = ty; uj_type = Typing.type_of env !evdref ty} in let (ind,u), params = dest_ind_family indf in if not (eq_ind ind cind) then error_bad_constructor_loc l env cstr ind; let cstrs = get_constructors env indf in let ci = cstrs.(i-1) in let nb_args_constr = ci.cs_nargs in assert (Int.equal nb_args_constr (List.length args)); let patargs, args, sign, env, n, m, avoid = List.fold_right2 (fun (na, c, t) ua (patargs, args, sign, env, n, m, avoid) -> let pat', sign', arg', typ', argtypargs, n', avoid = let liftt = liftn (List.length sign) (succ (List.length args)) t in typ env (substl args liftt, []) ua avoid in let args' = arg' :: List.map (lift n') args in let env' = push_rel_context sign' env in (pat' :: patargs, args', sign' @ sign, env', n' + n, succ m, avoid)) ci.cs_args (List.rev args) ([], [], [], env, 0, 0, avoid) in let args = List.rev args in let patargs = List.rev patargs in let pat' = PatCstr (l, cstr, patargs, alias) in let cstr = mkConstructU ci.cs_cstr in let app = applistc cstr (List.map (lift (List.length sign)) params) in let app = applistc app args in let apptype = Retyping.get_type_of env ( !evdref) app in let IndType (indf, realargs) = find_rectype env ( !evdref) apptype in match alias with Anonymous -> pat', sign, app, apptype, realargs, n, avoid | Name id -> let sign = (alias, None, lift m ty) :: sign in let avoid = id :: avoid in let sign, i, avoid = try let env = push_rel_context sign env in evdref := the_conv_x_leq (push_rel_context sign env) (lift (succ m) ty) (lift 1 apptype) !evdref; let eq_t = mk_eq evdref (lift (succ m) ty) in let neq = eq_id avoid id in (Name neq, Some (mkRel 0), eq_t) :: sign, 2, neq :: avoid with Reduction.NotConvertible -> sign, 1, avoid in pat', sign, lift i app, lift i apptype, realargs, n + i, avoid in let pat', sign, patc, patty, args, z, avoid = typ env (pi3 (List.hd arsign), List.tl arsign) pat avoid in pat', (sign, patc, (pi3 (List.hd arsign), args), pat'), avoid let eq_id avoid id = let hid = Id.of_string ("Heq_" ^ Id.to_string id) in let hid' = next_ident_away hid !avoid in avoid := hid' :: !avoid; hid' let is_topvar t = match kind_of_term t with | Rel 0 -> true | _ -> false let rels_of_patsign l = List.map (fun ((na, b, t) as x) -> match b with | Some t' when is_topvar t' -> (na, None, t) | _ -> x) l let vars_of_ctx ctx = let _, y = List.fold_right (fun (na, b, t) (prev, vars) -> match b with | Some t' when is_topvar t' -> prev, (GApp (Loc.ghost, (GRef (Loc.ghost, delayed_force coq_eq_refl_ref, None)), [hole; GVar (Loc.ghost, prev)])) :: vars | _ -> match na with Anonymous -> invalid_arg "vars_of_ctx" | Name n -> n, GVar (Loc.ghost, n) :: vars) ctx (Id.of_string "vars_of_ctx_error", []) in List.rev y let rec is_included x y = match x, y with | PatVar _, _ -> true | _, PatVar _ -> true | PatCstr (l, (_, i), args, alias), PatCstr (l', (_, i'), args', alias') -> if Int.equal i i' then List.for_all2 is_included args args' else false liftsign is the current pattern 's complete signature length . Hence pats is already typed in its full signature . However prevpatterns are in the original one signature per pattern form . Hence pats is already typed in its full signature. However prevpatterns are in the original one signature per pattern form. *) let build_ineqs evdref prevpatterns pats liftsign = let _tomatchs = List.length pats in let diffs = List.fold_left (fun c eqnpats -> let acc = List.fold_left2 ppat is the pattern we are discriminating against , curpat is the current one . (fun acc (ppat_sign, ppat_c, (ppat_ty, ppat_tyargs), ppat) (curpat_sign, curpat_c, (curpat_ty, curpat_tyargs), curpat) -> match acc with None -> None if is_included curpat ppat then let lens = List.length ppat_sign in let len' = lens + len in let acc = Jump over previous prevpat signs lift_rel_context len ppat_sign @ sign, len', (papp evdref coq_eq_ind [| lift (len' + liftsign) curpat_ty; liftn (len + liftsign) (succ lens) ppat_c ; lift len' curpat_c |]) :: Jump over this prevpat signature in Some acc else None) (Some ([], 0, 0, [])) eqnpats pats in match acc with None -> c | Some (sign, len, _, c') -> let conj = it_mkProd_or_LetIn (mk_coq_not (mk_coq_and c')) (lift_rel_context liftsign sign) in conj :: c) [] prevpatterns in match diffs with [] -> None | _ -> Some (mk_coq_and diffs) let constrs_of_pats typing_fun env evdref eqns tomatchs sign neqs arity = let i = ref 0 in let (x, y, z) = List.fold_left (fun (branches, eqns, prevpatterns) eqn -> let _, newpatterns, pats = List.fold_left2 (fun (idents, newpatterns, pats) pat arsign -> let pat', cpat, idents = constr_of_pat env evdref arsign pat idents in (idents, pat' :: newpatterns, cpat :: pats)) ([], [], []) eqn.patterns sign in let newpatterns = List.rev newpatterns and opats = List.rev pats in let rhs_rels, pats, signlen = List.fold_left (fun (renv, pats, n) (sign,c, (s, args), p) -> Recombine signatures and terms of all of the row 's patterns let sign' = lift_rel_context n sign in let len = List.length sign' in (sign' @ renv, (sign', liftn n (succ len) c, (s, List.map (liftn n (succ len)) args), p) :: pats, len + n)) ([], [], 0) opats in let pats, _ = List.fold_left (fun (pats, n) (sign, c, (s, args), p) -> let len = List.length sign in ((rels_of_patsign sign, lift n c, (s, List.map (lift n) args), p) :: pats, len + n)) ([], 0) pats in let ineqs = build_ineqs evdref prevpatterns pats signlen in let rhs_rels' = rels_of_patsign rhs_rels in let _signenv = push_rel_context rhs_rels' env in let arity = let args, nargs = List.fold_right (fun (sign, c, (_, args), _) (allargs,n) -> (args @ c :: allargs, List.length args + succ n)) pats ([], 0) in let args = List.rev args in substl args (liftn signlen (succ nargs) arity) in let rhs_rels', tycon = let neqs_rels, arity = match ineqs with | None -> [], arity | Some ineqs -> [Anonymous, None, ineqs], lift 1 arity in let eqs_rels, arity = decompose_prod_n_assum neqs arity in eqs_rels @ neqs_rels @ rhs_rels', arity in let rhs_env = push_rel_context rhs_rels' env in let j = typing_fun (mk_tycon tycon) rhs_env eqn.rhs.it in let bbody = it_mkLambda_or_LetIn j.uj_val rhs_rels' and btype = it_mkProd_or_LetIn j.uj_type rhs_rels' in let _btype = evd_comb1 (Typing.e_type_of env) evdref bbody in let branch_name = Id.of_string ("program_branch_" ^ (string_of_int !i)) in let branch_decl = (Name branch_name, Some (lift !i bbody), (lift !i btype)) in let branch = let bref = GVar (Loc.ghost, branch_name) in match vars_of_ctx rhs_rels with [] -> bref | l -> GApp (Loc.ghost, bref, l) in let branch = match ineqs with Some _ -> GApp (Loc.ghost, branch, [ hole ]) | None -> branch in incr i; let rhs = { eqn.rhs with it = Some branch } in (branch_decl :: branches, { eqn with patterns = newpatterns; rhs = rhs } :: eqns, opats :: prevpatterns)) ([], [], []) eqns in x, y Builds the predicate . If the predicate is dependent , its context is * made of 1+nrealargs assumptions for each matched term in an inductive * type and 1 assumption for each term not _ syntactically _ in an * inductive type . * Each matched terms are independently considered dependent or not . * A type constraint but no annotation case : it is assumed non dependent . * made of 1+nrealargs assumptions for each matched term in an inductive * type and 1 assumption for each term not _syntactically_ in an * inductive type. * Each matched terms are independently considered dependent or not. * A type constraint but no annotation case: it is assumed non dependent. *) let lift_ctx n ctx = let ctx', _ = List.fold_right (fun (c, t) (ctx, n') -> (liftn n n' c, liftn_tomatch_type n n' t) :: ctx, succ n') ctx ([], 0) in ctx' let abstract_tomatch env tomatchs tycon = let prev, ctx, names, tycon = List.fold_left (fun (prev, ctx, names, tycon) (c, t) -> let lenctx = List.length ctx in match kind_of_term c with Rel n -> (lift lenctx c, lift_tomatch_type lenctx t) :: prev, ctx, names, tycon | _ -> let tycon = Option.map (fun t -> subst_term (lift 1 c) (lift 1 t)) tycon in let name = next_ident_away (Id.of_string "filtered_var") names in (mkRel 1, lift_tomatch_type (succ lenctx) t) :: lift_ctx 1 prev, (Name name, Some (lift lenctx c), lift lenctx $ type_of_tomatch t) :: ctx, name :: names, tycon) ([], [], [], tycon) tomatchs in List.rev prev, ctx, tycon let build_dependent_signature env evdref avoid tomatchs arsign = let avoid = ref avoid in let arsign = List.rev arsign in let allnames = List.rev_map (List.map pi1) arsign in let nar = List.fold_left (fun n names -> List.length names + n) 0 allnames in let eqs, neqs, refls, slift, arsign' = List.fold_left2 (fun (eqs, neqs, refl_args, slift, arsigns) (tm, ty) arsign -> The accumulator : previous eqs , number of previous eqs , lift to get outside eqs and in the introduced variables ( ' as ' and ' in ' ) , new arity signatures previous eqs, number of previous eqs, lift to get outside eqs and in the introduced variables ('as' and 'in'), new arity signatures *) match ty with | IsInd (ty, IndType (indf, args), _) when List.length args > 0 -> let env', nargeqs, argeqs, refl_args, slift, argsign' = List.fold_left2 (fun (env, nargeqs, argeqs, refl_args, slift, argsign') arg (name, b, t) -> let argt = Retyping.get_type_of env !evdref arg in let eq, refl_arg = if Reductionops.is_conv env !evdref argt t then (mk_eq evdref (lift (nargeqs + slift) argt) (mkRel (nargeqs + slift)) (lift (nargeqs + nar) arg), mk_eq_refl evdref argt arg) else (mk_JMeq evdref (lift (nargeqs + slift) t) (mkRel (nargeqs + slift)) (lift (nargeqs + nar) argt) (lift (nargeqs + nar) arg), mk_JMeq_refl evdref argt arg) in let previd, id = let name = match kind_of_term arg with Rel n -> pi1 (lookup_rel n env) | _ -> name in make_prime avoid name in (env, succ nargeqs, (Name (eq_id avoid previd), None, eq) :: argeqs, refl_arg :: refl_args, pred slift, (Name id, b, t) :: argsign')) (env, neqs, [], [], slift, []) args argsign in let eq = mk_JMeq evdref (lift (nargeqs + slift) appt) (mkRel (nargeqs + slift)) (lift (nargeqs + nar) ty) (lift (nargeqs + nar) tm) in let refl_eq = mk_JMeq_refl evdref ty tm in let previd, id = make_prime avoid appn in (((Name (eq_id avoid previd), None, eq) :: argeqs) :: eqs, succ nargeqs, refl_eq :: refl_args, pred slift, (((Name id, appb, appt) :: argsign') :: arsigns)) let (name, b, typ) = match arsign with [x] -> x | _ -> assert(false) in let previd, id = make_prime avoid name in let arsign' = (Name id, b, typ) in let tomatch_ty = type_of_tomatch ty in let eq = mk_eq evdref (lift nar tomatch_ty) (mkRel slift) (lift nar tm) in ([(Name (eq_id avoid previd), None, eq)] :: eqs, succ neqs, (mk_eq_refl evdref tomatch_ty tm) :: refl_args, pred slift, (arsign' :: []) :: arsigns)) ([], 0, [], nar, []) tomatchs arsign in let arsign'' = List.rev arsign' in arsign'', allnames, nar, eqs, neqs, refls let context_of_arsign l = let (x, _) = List.fold_right (fun c (x, n) -> (lift_rel_context n c @ x, List.length c + n)) l ([], 0) in x let compile_program_cases loc style (typing_function, evdref) tycon env (predopt, tomatchl, eqns) = let typing_fun tycon env = function | Some t -> typing_function tycon env evdref t | None -> Evarutil.evd_comb0 use_unit_judge evdref in let matx = matx_of_eqns env eqns in let tomatchs = coerce_to_indtype typing_function evdref env matx tomatchl in let tycon = valcon_of_tycon tycon in let tomatchs, tomatchs_lets, tycon' = abstract_tomatch env tomatchs tycon in let env = push_rel_context tomatchs_lets env in let len = List.length eqns in let sign, allnames, signlen, eqs, neqs, args = let arsign = extract_arity_signature ~dolift:false env tomatchs tomatchl in Build the dependent arity signature , the equalities which makes the first part of the predicate and their instantiations . the first part of the predicate and their instantiations. *) let avoid = [] in build_dependent_signature env evdref avoid tomatchs arsign in let tycon, arity = match tycon' with | None -> let ev = mkExistential env evdref in ev, ev | Some t -> let pred = try let pred = prepare_predicate_from_arsign_tycon loc tomatchs sign t in let env' = push_rel_context (context_of_arsign sign) env in ignore(Typing.sort_of env' evdref pred); pred with e when Errors.noncritical e -> let nar = List.fold_left (fun n sign -> List.length sign + n) 0 sign in lift nar t in Option.get tycon, pred in let neqs, arity = let ctx = context_of_arsign eqs in let neqs = List.length ctx in neqs, it_mkProd_or_LetIn (lift neqs arity) ctx in let lets, matx = constrs_of_pats typing_fun env evdref matx tomatchs sign neqs arity in let matx = List.rev matx in let _ = assert (Int.equal len (List.length lets)) in let env = push_rel_context lets env in let matx = List.map (fun eqn -> { eqn with rhs = { eqn.rhs with rhs_env = env } }) matx in let tomatchs = List.map (fun (x, y) -> lift len x, lift_tomatch_type len y) tomatchs in let args = List.rev_map (lift len) args in let pred = liftn len (succ signlen) arity in let nal, pred = build_initial_predicate sign pred in let out_tmt na = function NotInd (c,t) -> (na,c,t) | IsInd (typ,_,_) -> (na,None,typ) in let typs = List.map2 (fun na (tm,tmt) -> (tm,out_tmt na tmt)) nal tomatchs in let typs = List.map (fun (c,d) -> (c,extract_inductive_data env !evdref d,d)) typs in let dep_sign = find_dependencies_signature (List.make (List.length typs) true) typs in let typs' = List.map3 (fun (tm,tmt) deps na -> let deps = if not (isRel tm) then [] else deps in ((tm,tmt),deps,na)) tomatchs dep_sign nal in let initial_pushed = List.map (fun x -> Pushed (true,x)) typs' in let typing_function tycon env evdref = function | Some t -> typing_function tycon env evdref t | None -> evd_comb0 use_unit_judge evdref in let pb = { env = env; evdref = evdref; pred = pred; tomatch = initial_pushed; history = start_history (List.length initial_pushed); mat = matx; caseloc = loc; casestyle= style; typing_function = typing_function } in let j = compile pb in List.iter (check_unused_pattern env) matx; let body = it_mkLambda_or_LetIn (applistc j.uj_val args) lets in let j = { uj_val = it_mkLambda_or_LetIn body tomatchs_lets; uj_type = nf_evar !evdref tycon; } in j let compile_cases loc style (typing_fun, evdref) tycon env (predopt, tomatchl, eqns) = if predopt == None && Flags.is_program_mode () then compile_program_cases loc style (typing_fun, evdref) tycon env (predopt, tomatchl, eqns) else let matx = matx_of_eqns env eqns in let tomatchs = coerce_to_indtype typing_fun evdref env matx tomatchl in let arsign = extract_arity_signature env tomatchs tomatchl in let preds = prepare_predicate loc typing_fun env !evdref tomatchs arsign tycon predopt in let compile_for_one_predicate (sigma,nal,pred) = names of aliases will be recovered from patterns ( hence let out_tmt na = function NotInd (c,t) -> (na,c,t) | IsInd (typ,_,_) -> (na,None,typ) in let typs = List.map2 (fun na (tm,tmt) -> (tm,out_tmt na tmt)) nal tomatchs in let typs = List.map (fun (c,d) -> (c,extract_inductive_data env sigma d,d)) typs in let dep_sign = find_dependencies_signature (List.make (List.length typs) true) typs in let typs' = List.map3 (fun (tm,tmt) deps na -> let deps = if not (isRel tm) then [] else deps in ((tm,tmt),deps,na)) tomatchs dep_sign nal in let initial_pushed = List.map (fun x -> Pushed (true,x)) typs' in let typing_fun tycon env evdref = function | Some t -> typing_fun tycon env evdref t | None -> evd_comb0 use_unit_judge evdref in let myevdref = ref sigma in let pb = { env = env; evdref = myevdref; pred = pred; tomatch = initial_pushed; history = start_history (List.length initial_pushed); mat = matx; caseloc = loc; casestyle = style; typing_function = typing_fun } in let j = compile pb in evdref := !myevdref; j in Return the term compiled with the first possible elimination let j = list_try_compile compile_for_one_predicate preds in List.iter (check_unused_pattern env) matx; We coerce to the ( if an elim predicate was provided ) inh_conv_coerce_to_tycon loc env evdref j tycon
afbd0fe348d85770444c32814081f3287b6629110a391a67dc0bd9fa9e77ef54
inaka/elvis_core
pass_private_data_types.erl
-module(pass_private_data_types). -record(my_rec, {a :: integer(), b :: integer(), c :: integer()}). -opaque my_rec() :: #my_rec{}. -export_type([my_rec/0]). -export([hello/0]). -spec hello() -> ok. hello() -> my_fun(#my_rec{a = 1, b = 2, c = 3}). -spec my_fun(my_rec()) -> ok. my_fun(_Rec) -> ok.
null
https://raw.githubusercontent.com/inaka/elvis_core/c0993efbc9e2007ca0028232312753009862b2ac/test/examples/pass_private_data_types.erl
erlang
-module(pass_private_data_types). -record(my_rec, {a :: integer(), b :: integer(), c :: integer()}). -opaque my_rec() :: #my_rec{}. -export_type([my_rec/0]). -export([hello/0]). -spec hello() -> ok. hello() -> my_fun(#my_rec{a = 1, b = 2, c = 3}). -spec my_fun(my_rec()) -> ok. my_fun(_Rec) -> ok.
e6fa33f1cd040f8fd7e5eb774ecf0c7e09e21ce9a46b25afe62d138bd54c5359
metabase/metabase
dashboard_detail.clj
(ns metabase-enterprise.audit-app.pages.dashboard-detail "Detail page for a single dashboard." (:require [metabase-enterprise.audit-app.interface :as audit.i] [metabase-enterprise.audit-app.pages.common :as common] [metabase-enterprise.audit-app.pages.common.card-and-dashboard-detail :as card-and-dash-detail] [metabase-enterprise.audit-app.pages.common.cards :as cards] [metabase.models.dashboard :refer [Dashboard]] [metabase.util.schema :as su] [schema.core :as s])) ;; Get views of a Dashboard broken out by a time `unit`, e.g. `day` or `day-of-week`. (s/defmethod audit.i/internal-query ::views-by-time [_ dashboard-id :- su/IntGreaterThanZero datetime-unit :- common/DateTimeUnitStr] (card-and-dash-detail/views-by-time "dashboard" dashboard-id datetime-unit)) ;; Revision history for a specific Dashboard. (s/defmethod audit.i/internal-query ::revision-history [_ dashboard-id :- su/IntGreaterThanZero] (card-and-dash-detail/revision-history Dashboard dashboard-id)) ;; View log for a specific Dashboard. (s/defmethod audit.i/internal-query ::audit-log [_ dashboard-id :- su/IntGreaterThanZero] (card-and-dash-detail/audit-log "dashboard" dashboard-id)) ;; Information about the Saved Questions (Cards) in this instance. (s/defmethod audit.i/internal-query ::cards [_ dashboard-id :- su/IntGreaterThanZero] {:metadata [[:card_id {:display_name "Card ID", :base_type :type/Integer, :remapped_to :card_name}] [:card_name {:display_name "Title", :base_type :type/Name, :remapped_from :card_id}] [:collection_id {:display_name "Collection ID", :base_type :type/Integer, :remapped_to :collection_name}] [:collection_name {:display_name "Collection", :base_type :type/Text, :remapped_from :collection_id}] [:created_at {:display_name "Created At", :base_type :type/DateTime}] [:database_id {:display_name "Database ID", :base_type :type/Integer, :remapped_to :database_name}] [:database_name {:display_name "Database", :base_type :type/Text, :remapped_from :database_id}] [:table_id {:display_name "Table ID", :base_type :type/Integer, :remapped_to :table_name}] [:table_name {:display_name "Table", :base_type :type/Text, :remapped_from :table_id}] [:avg_running_time_ms {:display_name "Avg. exec. time (ms)", :base_type :type/Number}] [:cache_ttl {:display_name "Cache Duration", :base_type :type/Number}] [:public_link {:display_name "Public Link", :base_type :type/URL}] [:total_views {:display_name "Total Views", :base_type :type/Integer}]] :results (common/reducible-query {:with [[:card {:select [:card.* [:dc.created_at :dashcard_created_at]] :from [[:report_dashboardcard :dc]] :join [[:report_card :card] [:= :card.id :dc.card_id]] :where [:= :dc.dashboard_id dashboard-id]}] cards/avg-exec-time cards/views] :select [[:card.id :card_id] [:card.name :card_name] [:coll.id :collection_id] [:coll.name :collection_name] [:card.dashcard_created_at :created_at] :card.database_id [:db.name :database_name] :card.table_id [:t.name :table_name] :avg_exec_time.avg_running_time_ms [(common/card-public-url :card.public_uuid) :public_link] :card.cache_ttl [:card_views.count :total_views]] :from [:card] :left-join [:avg_exec_time [:= :card.id :avg_exec_time.card_id] [:metabase_database :db] [:= :card.database_id :db.id] [:metabase_table :t] [:= :card.table_id :t.id] [:collection :coll] [:= :card.collection_id :coll.id] :card_views [:= :card.id :card_views.card_id]] :order-by [[[:lower :card.name] :asc]]})})
null
https://raw.githubusercontent.com/metabase/metabase/79b08ee8627ad2b3d4d7703e9aeb1a48db5d3493/enterprise/backend/src/metabase_enterprise/audit_app/pages/dashboard_detail.clj
clojure
Get views of a Dashboard broken out by a time `unit`, e.g. `day` or `day-of-week`. Revision history for a specific Dashboard. View log for a specific Dashboard. Information about the Saved Questions (Cards) in this instance.
(ns metabase-enterprise.audit-app.pages.dashboard-detail "Detail page for a single dashboard." (:require [metabase-enterprise.audit-app.interface :as audit.i] [metabase-enterprise.audit-app.pages.common :as common] [metabase-enterprise.audit-app.pages.common.card-and-dashboard-detail :as card-and-dash-detail] [metabase-enterprise.audit-app.pages.common.cards :as cards] [metabase.models.dashboard :refer [Dashboard]] [metabase.util.schema :as su] [schema.core :as s])) (s/defmethod audit.i/internal-query ::views-by-time [_ dashboard-id :- su/IntGreaterThanZero datetime-unit :- common/DateTimeUnitStr] (card-and-dash-detail/views-by-time "dashboard" dashboard-id datetime-unit)) (s/defmethod audit.i/internal-query ::revision-history [_ dashboard-id :- su/IntGreaterThanZero] (card-and-dash-detail/revision-history Dashboard dashboard-id)) (s/defmethod audit.i/internal-query ::audit-log [_ dashboard-id :- su/IntGreaterThanZero] (card-and-dash-detail/audit-log "dashboard" dashboard-id)) (s/defmethod audit.i/internal-query ::cards [_ dashboard-id :- su/IntGreaterThanZero] {:metadata [[:card_id {:display_name "Card ID", :base_type :type/Integer, :remapped_to :card_name}] [:card_name {:display_name "Title", :base_type :type/Name, :remapped_from :card_id}] [:collection_id {:display_name "Collection ID", :base_type :type/Integer, :remapped_to :collection_name}] [:collection_name {:display_name "Collection", :base_type :type/Text, :remapped_from :collection_id}] [:created_at {:display_name "Created At", :base_type :type/DateTime}] [:database_id {:display_name "Database ID", :base_type :type/Integer, :remapped_to :database_name}] [:database_name {:display_name "Database", :base_type :type/Text, :remapped_from :database_id}] [:table_id {:display_name "Table ID", :base_type :type/Integer, :remapped_to :table_name}] [:table_name {:display_name "Table", :base_type :type/Text, :remapped_from :table_id}] [:avg_running_time_ms {:display_name "Avg. exec. time (ms)", :base_type :type/Number}] [:cache_ttl {:display_name "Cache Duration", :base_type :type/Number}] [:public_link {:display_name "Public Link", :base_type :type/URL}] [:total_views {:display_name "Total Views", :base_type :type/Integer}]] :results (common/reducible-query {:with [[:card {:select [:card.* [:dc.created_at :dashcard_created_at]] :from [[:report_dashboardcard :dc]] :join [[:report_card :card] [:= :card.id :dc.card_id]] :where [:= :dc.dashboard_id dashboard-id]}] cards/avg-exec-time cards/views] :select [[:card.id :card_id] [:card.name :card_name] [:coll.id :collection_id] [:coll.name :collection_name] [:card.dashcard_created_at :created_at] :card.database_id [:db.name :database_name] :card.table_id [:t.name :table_name] :avg_exec_time.avg_running_time_ms [(common/card-public-url :card.public_uuid) :public_link] :card.cache_ttl [:card_views.count :total_views]] :from [:card] :left-join [:avg_exec_time [:= :card.id :avg_exec_time.card_id] [:metabase_database :db] [:= :card.database_id :db.id] [:metabase_table :t] [:= :card.table_id :t.id] [:collection :coll] [:= :card.collection_id :coll.id] :card_views [:= :card.id :card_views.card_id]] :order-by [[[:lower :card.name] :asc]]})})
9a99aa30a0d9635ddfc51f1a412d5f23b61f672c67f709873037c461c84f2047
jordanthayer/ocaml-search
three_queue_search_rev.ml
* Three queud search with reverse heuristics Jordan - August 2009 Jordan - August 2009 *) type 'a node = { mutable est_f : float; h : float; d : float; g : float; depth : int; rev_h : float; rev_d : float; mutable q_pos : int; mutable fh_pos : int; mutable geqe : 'a node; data : 'a; } (**** Utility functions ****) let set_qpos n i = n.q_pos <- i let get_qpos n = n.q_pos let set_fhpos n i = n.fh_pos <- i let get_fhpos n = n.fh_pos let set_geqe n e = n.geqe <- e let get_geqe n = n.geqe let wrap f = (fun n -> f n.data) let get_f n = n.g +. n.h let get_estf n = n.est_f let make_child s g h d rh rd est_f geqe depth = { est_f = est_f; h = h; d = d; g = g; depth = depth; rev_h = rh; rev_d = rd; q_pos = Dpq.no_position; fh_pos = Dpq.no_position; geqe = geqe; data = s; } let wrap_incumbent i = match i with None -> Limit.Nothing | Some (n) -> Limit.Incumbent (0., n) let make_initial initial hd = let h, d = hd initial in let rec n = { est_f = h; h = h; d = d; g = 0.; depth = 0; rev_h = 0.; rev_d = 0.; q_pos = Dpq.no_position; fh_pos = Dpq.no_position; geqe = n; data = initial; } in n let est_f_then_d_then_g a b = (a.est_f < b.est_f) || (* sort by fhat *) ((a.est_f = b.est_f) && ((a.g >= b.g) || (* break ties on low d *) ((a.g == b.g) && (a.d <= b.d)))) (* break ties on high g *) let d_then_f_then_g a b = (** convenience ordering predicate *) let af = a.g +. a.h and bf = b.g +. b.h in (a.d < b.d) || ((a.d = b.d) && ((af < bf) || ((af = bf) && (a.g >= b.g)))) let better_p a b = (a.g +. a.h) <= (b.g +. b.h) let f_order a b = let af = a.g +. a.h and bf = b.g +. b.h in af < bf || (af = bf && a.g > b.g) || (af = bf && a.g = b.g && a.d < b.d) let make_close_enough bound = (fun a b -> (b.est_f <= (a.est_f *. bound))) let unwrap_sol s = match s with Limit.Incumbent (q, n) -> Some (n.data, n.g) | _ -> None let get_node bound f_q geq i = let best_f = Dpq.peek_first f_q and best_fh = Safe_geq.peek_doset geq and best_d = Safe_geq.peek_best geq in let wf = (best_f.g +. best_f.h) *. bound in if best_d.est_f <= wf then best_d else (if best_fh.est_f <= wf then best_fh else best_f) let no_d_getnode bound fq geq i = let best_f = Dpq.peek_first fq and best_fh = Safe_geq.peek_doset geq in let wf = (best_f.g +. best_f.h) *. bound in if best_fh.est_f <= wf then ((*Verb.pe Verb.debug "Got Best fh\n";*) best_fh) else ((*Verb.pe Verb.debug "Got Best f\n";*) best_f) let no_fh_getnode bound fq geq i = let best_f = Dpq.peek_first fq and best_d = Safe_geq.peek_best geq in let wf = (best_f.g +. best_f.h) *. bound in if best_d.est_f <= wf then ((*Verb.pe Verb.debug "Got Best d\n";*) best_d) else ((*Verb.pe Verb.debug "Got Best f\n";*) best_f) let make_expand init expand hd rev_hd timer calc_h_data f_calc = (fun n -> let best_f = ref infinity and best_child = ref n and reorder = timer() in let children = (List.map (fun (s, g) -> let h, d = hd s and rh, rd = rev_hd s in let f = g +. h in let c = (make_child s g h d rh rd 0. init (n.depth + 1)) in if f < !best_f then (best_child := c; best_f := f) else if f = !best_f then (if d < !best_child.d then (best_child := c; best_f := f)); c) (expand n.data n.g)) in if not ((List.length children) = 0) then (calc_h_data n !best_child children; List.iter (fun c -> c.est_f <- f_calc c) children); reorder,children) let make_update fcalc = (fun n -> n.est_f <- fcalc n) (****************************** Search *************************************) let no_dups ?(node_get = get_node) sface bound timer calc_h_data f_calc = let i_node = make_initial sface.Search_interface.initial sface.Search_interface.hd in let search_interface = Search_interface.make ~resort_expand:(make_expand i_node sface.Search_interface.domain_expand sface.Search_interface.hd sface.Search_interface.rev_hd timer calc_h_data f_calc) ~goal_p:(wrap sface.Search_interface.goal_p) ~halt_on:sface.Search_interface.halt_on ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals sface.Search_interface.domain i_node f_order (Limit.make_default_logger (fun n -> n.g +. n.h) (wrap sface.Search_interface.get_sol_length)) in Limit.unwrap_sol5 unwrap_sol (Three_queue.no_dups search_interface f_order d_then_f_then_g est_f_then_d_then_g (make_close_enough bound) f_order set_qpos get_qpos set_fhpos get_fhpos set_geqe get_geqe (node_get bound) (make_update f_calc)) let dups ?(node_get = get_node) sface bound timer calc_h_data f_calc = let i_node = make_initial sface.Search_interface.initial sface.Search_interface.hd in let search_interface = Search_interface.make ~resort_expand:(make_expand i_node sface.Search_interface.domain_expand sface.Search_interface.hd sface.Search_interface.rev_hd timer calc_h_data f_calc) ~goal_p:(wrap sface.Search_interface.goal_p) ~halt_on:sface.Search_interface.halt_on ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals ~key:(wrap sface.Search_interface.key) sface.Search_interface.domain i_node f_order (Limit.make_default_logger (fun n -> n.g +. n.h) (wrap sface.Search_interface.get_sol_length)) in Limit.unwrap_sol6 unwrap_sol (Three_queue.dups search_interface f_order d_then_f_then_g est_f_then_d_then_g (make_close_enough bound) f_order set_qpos get_qpos set_fhpos get_fhpos set_geqe get_geqe (node_get bound) (make_update f_calc)) EOF
null
https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/search/optimistic/three_queue_search_rev.ml
ocaml
*** Utility functions *** sort by fhat break ties on low d break ties on high g * convenience ordering predicate Verb.pe Verb.debug "Got Best fh\n"; Verb.pe Verb.debug "Got Best f\n"; Verb.pe Verb.debug "Got Best d\n"; Verb.pe Verb.debug "Got Best f\n"; ***************************** Search ************************************
* Three queud search with reverse heuristics Jordan - August 2009 Jordan - August 2009 *) type 'a node = { mutable est_f : float; h : float; d : float; g : float; depth : int; rev_h : float; rev_d : float; mutable q_pos : int; mutable fh_pos : int; mutable geqe : 'a node; data : 'a; } let set_qpos n i = n.q_pos <- i let get_qpos n = n.q_pos let set_fhpos n i = n.fh_pos <- i let get_fhpos n = n.fh_pos let set_geqe n e = n.geqe <- e let get_geqe n = n.geqe let wrap f = (fun n -> f n.data) let get_f n = n.g +. n.h let get_estf n = n.est_f let make_child s g h d rh rd est_f geqe depth = { est_f = est_f; h = h; d = d; g = g; depth = depth; rev_h = rh; rev_d = rd; q_pos = Dpq.no_position; fh_pos = Dpq.no_position; geqe = geqe; data = s; } let wrap_incumbent i = match i with None -> Limit.Nothing | Some (n) -> Limit.Incumbent (0., n) let make_initial initial hd = let h, d = hd initial in let rec n = { est_f = h; h = h; d = d; g = 0.; depth = 0; rev_h = 0.; rev_d = 0.; q_pos = Dpq.no_position; fh_pos = Dpq.no_position; geqe = n; data = initial; } in n let est_f_then_d_then_g a b = ((a.est_f = b.est_f) && ((a.g >= b.g) ((a.g == b.g) && let d_then_f_then_g a b = let af = a.g +. a.h and bf = b.g +. b.h in (a.d < b.d) || ((a.d = b.d) && ((af < bf) || ((af = bf) && (a.g >= b.g)))) let better_p a b = (a.g +. a.h) <= (b.g +. b.h) let f_order a b = let af = a.g +. a.h and bf = b.g +. b.h in af < bf || (af = bf && a.g > b.g) || (af = bf && a.g = b.g && a.d < b.d) let make_close_enough bound = (fun a b -> (b.est_f <= (a.est_f *. bound))) let unwrap_sol s = match s with Limit.Incumbent (q, n) -> Some (n.data, n.g) | _ -> None let get_node bound f_q geq i = let best_f = Dpq.peek_first f_q and best_fh = Safe_geq.peek_doset geq and best_d = Safe_geq.peek_best geq in let wf = (best_f.g +. best_f.h) *. bound in if best_d.est_f <= wf then best_d else (if best_fh.est_f <= wf then best_fh else best_f) let no_d_getnode bound fq geq i = let best_f = Dpq.peek_first fq and best_fh = Safe_geq.peek_doset geq in let wf = (best_f.g +. best_f.h) *. bound in if best_fh.est_f <= wf let no_fh_getnode bound fq geq i = let best_f = Dpq.peek_first fq and best_d = Safe_geq.peek_best geq in let wf = (best_f.g +. best_f.h) *. bound in if best_d.est_f <= wf let make_expand init expand hd rev_hd timer calc_h_data f_calc = (fun n -> let best_f = ref infinity and best_child = ref n and reorder = timer() in let children = (List.map (fun (s, g) -> let h, d = hd s and rh, rd = rev_hd s in let f = g +. h in let c = (make_child s g h d rh rd 0. init (n.depth + 1)) in if f < !best_f then (best_child := c; best_f := f) else if f = !best_f then (if d < !best_child.d then (best_child := c; best_f := f)); c) (expand n.data n.g)) in if not ((List.length children) = 0) then (calc_h_data n !best_child children; List.iter (fun c -> c.est_f <- f_calc c) children); reorder,children) let make_update fcalc = (fun n -> n.est_f <- fcalc n) let no_dups ?(node_get = get_node) sface bound timer calc_h_data f_calc = let i_node = make_initial sface.Search_interface.initial sface.Search_interface.hd in let search_interface = Search_interface.make ~resort_expand:(make_expand i_node sface.Search_interface.domain_expand sface.Search_interface.hd sface.Search_interface.rev_hd timer calc_h_data f_calc) ~goal_p:(wrap sface.Search_interface.goal_p) ~halt_on:sface.Search_interface.halt_on ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals sface.Search_interface.domain i_node f_order (Limit.make_default_logger (fun n -> n.g +. n.h) (wrap sface.Search_interface.get_sol_length)) in Limit.unwrap_sol5 unwrap_sol (Three_queue.no_dups search_interface f_order d_then_f_then_g est_f_then_d_then_g (make_close_enough bound) f_order set_qpos get_qpos set_fhpos get_fhpos set_geqe get_geqe (node_get bound) (make_update f_calc)) let dups ?(node_get = get_node) sface bound timer calc_h_data f_calc = let i_node = make_initial sface.Search_interface.initial sface.Search_interface.hd in let search_interface = Search_interface.make ~resort_expand:(make_expand i_node sface.Search_interface.domain_expand sface.Search_interface.hd sface.Search_interface.rev_hd timer calc_h_data f_calc) ~goal_p:(wrap sface.Search_interface.goal_p) ~halt_on:sface.Search_interface.halt_on ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals ~key:(wrap sface.Search_interface.key) sface.Search_interface.domain i_node f_order (Limit.make_default_logger (fun n -> n.g +. n.h) (wrap sface.Search_interface.get_sol_length)) in Limit.unwrap_sol6 unwrap_sol (Three_queue.dups search_interface f_order d_then_f_then_g est_f_then_d_then_g (make_close_enough bound) f_order set_qpos get_qpos set_fhpos get_fhpos set_geqe get_geqe (node_get bound) (make_update f_calc)) EOF
9c7f396f59c0769b3897b15aac45baff017e2181aff71497917f33611c3ed288
mathematical-systems/clml
classes.lisp
(in-package #:metabang-bind-test) (defclass metabang-bind-class-1 () ((a :initarg :a :accessor a) (b :initarg :b :accessor b) (c :initarg :c :accessor c))) (defclass metabang-bind-class-2 (metabang-bind-class-1) ((d :initarg :d :accessor the-d) (e :initarg :e :accessor e))) (deftestsuite test-classes (metabang-bind-test) ()) (addtest (test-classes) basic-slots (ensure-same (bind (((:slots-read-only a c) (make-instance 'metabang-bind-class-1 :a 1 :b 2 :c 3))) (list a c)) '(1 3) :test 'equal)) (addtest (test-classes) slots-new-variable-names (ensure-same (bind (((:slots-read-only a (my-c c) (the-b b)) (make-instance 'metabang-bind-class-1 :a 1 :b 2 :c 3))) (list a the-b my-c)) '(1 2 3) :test 'equal)) (addtest (test-classes) writable-slots (ensure-same (bind ((instance (make-instance 'metabang-bind-class-1 :a 1 :b 2 :c 3)) ((:slots a (my-c c) (the-b b)) instance)) (setf a :changed) (list (slot-value instance 'a) the-b my-c)) '(:changed 2 3) :test 'equal)) (addtest (test-classes) basic-accessors-r/o-1 (ensure-same (bind (((:accessors-read-only a c e) (make-instance 'metabang-bind-class-2 :a 1 :b 2 :c 3 :d 4 :e 5))) (list e c a)) '(5 3 1) :test 'equal)) (addtest (test-classes) basic-accessors-r/o-2 (bind ((obj (make-instance 'metabang-bind-class-2 :a 1 :b 2 :c 3 :d 4 :e 5)) ((:accessors-read-only a c e) obj)) (setf a :a c :c) (ensure-same (list a c e) '(:a :c 5) :test 'equal) (ensure-same (list (e obj) (c obj) (a obj)) '(5 3 1) :test 'equal))) (addtest (test-classes) accessors-new-variable-names-r/o (ensure-same (bind (((:accessors-r/o (my-a a) (my-c c) (d the-d)) (make-instance 'metabang-bind-class-2 :a 1 :b 2 :c 3 :d 4 :e 5))) (list d my-c my-a)) '(4 3 1) :test 'equal)) (addtest (test-classes) basic-accessors-1 (ensure-same (bind ((obj (make-instance 'metabang-bind-class-2 :a 1 :b 2 :c 3 :d 4 :e 5)) ((:accessors a c e) obj)) (setf a :a c :c) (list (e obj) (c obj) (a obj))) '(5 :c :a) :test 'equal)) (addtest (test-classes) accessors-new-variable-names (ensure-same (bind ((obj (make-instance 'metabang-bind-class-2 :a 1 :b 2 :c 3 :d 4 :e 5)) ((:writable-accessors (my-a a) (my-c c) (d the-d)) obj)) (setf my-a 42) (list d my-c my-a (a obj))) '(4 3 42 42) :test 'equal))
null
https://raw.githubusercontent.com/mathematical-systems/clml/918e41e67ee2a8102c55a84b4e6e85bbdde933f5/addons/metabang-bind/unit-tests/classes.lisp
lisp
(in-package #:metabang-bind-test) (defclass metabang-bind-class-1 () ((a :initarg :a :accessor a) (b :initarg :b :accessor b) (c :initarg :c :accessor c))) (defclass metabang-bind-class-2 (metabang-bind-class-1) ((d :initarg :d :accessor the-d) (e :initarg :e :accessor e))) (deftestsuite test-classes (metabang-bind-test) ()) (addtest (test-classes) basic-slots (ensure-same (bind (((:slots-read-only a c) (make-instance 'metabang-bind-class-1 :a 1 :b 2 :c 3))) (list a c)) '(1 3) :test 'equal)) (addtest (test-classes) slots-new-variable-names (ensure-same (bind (((:slots-read-only a (my-c c) (the-b b)) (make-instance 'metabang-bind-class-1 :a 1 :b 2 :c 3))) (list a the-b my-c)) '(1 2 3) :test 'equal)) (addtest (test-classes) writable-slots (ensure-same (bind ((instance (make-instance 'metabang-bind-class-1 :a 1 :b 2 :c 3)) ((:slots a (my-c c) (the-b b)) instance)) (setf a :changed) (list (slot-value instance 'a) the-b my-c)) '(:changed 2 3) :test 'equal)) (addtest (test-classes) basic-accessors-r/o-1 (ensure-same (bind (((:accessors-read-only a c e) (make-instance 'metabang-bind-class-2 :a 1 :b 2 :c 3 :d 4 :e 5))) (list e c a)) '(5 3 1) :test 'equal)) (addtest (test-classes) basic-accessors-r/o-2 (bind ((obj (make-instance 'metabang-bind-class-2 :a 1 :b 2 :c 3 :d 4 :e 5)) ((:accessors-read-only a c e) obj)) (setf a :a c :c) (ensure-same (list a c e) '(:a :c 5) :test 'equal) (ensure-same (list (e obj) (c obj) (a obj)) '(5 3 1) :test 'equal))) (addtest (test-classes) accessors-new-variable-names-r/o (ensure-same (bind (((:accessors-r/o (my-a a) (my-c c) (d the-d)) (make-instance 'metabang-bind-class-2 :a 1 :b 2 :c 3 :d 4 :e 5))) (list d my-c my-a)) '(4 3 1) :test 'equal)) (addtest (test-classes) basic-accessors-1 (ensure-same (bind ((obj (make-instance 'metabang-bind-class-2 :a 1 :b 2 :c 3 :d 4 :e 5)) ((:accessors a c e) obj)) (setf a :a c :c) (list (e obj) (c obj) (a obj))) '(5 :c :a) :test 'equal)) (addtest (test-classes) accessors-new-variable-names (ensure-same (bind ((obj (make-instance 'metabang-bind-class-2 :a 1 :b 2 :c 3 :d 4 :e 5)) ((:writable-accessors (my-a a) (my-c c) (d the-d)) obj)) (setf my-a 42) (list d my-c my-a (a obj))) '(4 3 42 42) :test 'equal))
4742550ca00c2c7af7628157e5c9261f8b88594db83158788815e0ed8a7a48a8
finnishtransportagency/harja
liikennetapahtumat.clj
(ns harja.kyselyt.kanavat.liikennetapahtumat (:require [clojure.java.jdbc :as jdbc] [clojure.spec.alpha :as s] [clojure.set :as set] [jeesql.core :refer [defqueries]] [specql.core :as specql] [specql.op :as op] [specql.rel :as rel] [taoensso.timbre :as log] [jeesql.core :refer [defqueries]] [harja.id :refer [id-olemassa?]] [harja.pvm :as pvm] [harja.kyselyt.kanavat.kohteet :as kohteet-q] [harja.domain.urakka :as ur] [harja.domain.sopimus :as sop] [harja.domain.muokkaustiedot :as m] [harja.domain.kanavat.liikennetapahtuma :as lt] [harja.domain.kanavat.lt-alus :as lt-alus] [harja.domain.kanavat.lt-toiminto :as toiminto] [harja.domain.kanavat.lt-ketjutus :as ketjutus] [harja.domain.kanavat.kohde :as kohde] [clojure.string :as str] [clojure.core :as c])) (defn- liita-kohteen-urakkatiedot [kohteiden-haku tapahtumat] (let [kohteet (group-by ::kohde/id (kohteiden-haku (map ::lt/kohde tapahtumat)))] (into [] (map #(update % ::lt/kohde (fn [kohde] (if-let [kohteen-urakat (-> kohde ::kohde/id kohteet first ::kohde/urakat)] (assoc kohde ::kohde/urakat kohteen-urakat) (assoc kohde ::kohde/urakat [])))) tapahtumat)))) (defn- urakat-idlla [urakka-idt tapahtuma] (update-in tapahtuma [::lt/kohde ::kohde/urakat] (fn [urakat] (keep #(when (urakka-idt (::ur/id %)) %) urakat)))) (defn- suodata-liikennetapahtuma-toimenpidetyypillä [tiedot tapahtumat] (filter #(let [toimenpidetyypit (::toiminto/toimenpiteet tiedot)] (if (empty? toimenpidetyypit) true (some toimenpidetyypit (map ::toiminto/toimenpide (::lt/toiminnot %))))) tapahtumat)) (defn- suodata-liikennetapahtuma-aluksen-nimella [tiedot tapahtumat] (filter (fn [tapahtuma] (let [alus-nimi (::lt-alus/nimi tiedot)] (if (empty? alus-nimi) ;; Voi olla nil tai "" true , alkaa annetulla nimellä (not (empty? (lt-alus/suodata-alukset-nimen-alulla (::lt/alukset tapahtuma) alus-nimi)))))) tapahtumat)) (defn- hae-liikennetapahtumat* [tiedot tapahtumat urakkatiedot-fn urakka-idt] (->> tapahtumat (suodata-liikennetapahtuma-toimenpidetyypillä tiedot) (suodata-liikennetapahtuma-aluksen-nimella tiedot) (liita-kohteen-urakkatiedot urakkatiedot-fn) (map (partial urakat-idlla urakka-idt)) (remove (comp empty? ::kohde/urakat ::lt/kohde)))) (def ilman-poistettuja-aluksia (map #(update % ::lt/alukset (partial remove ::m/poistettu?)))) (def vain-uittoniput (keep (fn [t] (let [t (update t ::lt/alukset (partial remove (comp #(or (nil? %) (zero? %)) ::lt-alus/nippulkm)))] (when-not (empty? (::lt/alukset t)) t))))) (defn- hae-tapahtumien-palvelumuodot* [osien-tiedot tapahtumat] (let [id-ja-osat (->> osien-tiedot (group-by ::lt/id) (map (fn [[id osat]] [id (get-in osat [0 ::lt/toiminnot])])) (into {}))] (map (fn [tapahtuma] (assoc tapahtuma ::lt/toiminnot (id-ja-osat (::lt/id tapahtuma)))) tapahtumat))) (defn hae-tapahtumien-palvelumuodot [db tapahtumat] (hae-tapahtumien-palvelumuodot* (specql/fetch db ::lt/liikennetapahtuma (set/union lt/perustiedot lt/toimintojen-tiedot) {::lt/id (op/in (map ::lt/id tapahtumat))}) tapahtumat)) (defn- hae-tapahtumien-kohdetiedot* [kohdetiedot tapahtumat] (let [id-ja-kohde (->> kohdetiedot (group-by ::kohde/id))] (map (fn [tapahtuma] (assoc tapahtuma ::lt/kohde (first (id-ja-kohde (::lt/kohde-id tapahtuma))))) tapahtumat))) (defn hae-tapahtumien-kohdetiedot [db tapahtumat] (hae-tapahtumien-kohdetiedot* (specql/fetch db ::kohde/kohde (set/union kohde/perustiedot kohde/kohteenosat) {::kohde/id (op/in (map ::lt/kohde-id tapahtumat)) ::m/poistettu? false}) tapahtumat)) (defn- hae-tapahtumien-perustiedot* [tapahtumat {:keys [niput?]}] (into [] (apply comp (remove nil? [(when niput? vain-uittoniput) otetaan pois poistetut alukset , niin ei palaudu tapahtumat , joiden kaikki . ilman-poistettuja-aluksia])) tapahtumat)) (defn hae-tapahtumien-perustiedot [db {:keys [aikavali] :as tiedot}] (let [urakka-idt (:urakka-idt tiedot) kohde-id (get-in tiedot [::lt/kohde ::kohde/id]) aluslajit (::lt-alus/aluslajit tiedot) suunta (::lt-alus/suunta tiedot) [alku loppu] aikavali] (hae-tapahtumien-perustiedot* (specql/fetch db ::lt/liikennetapahtuma (set/union lt/perustiedot lt/kuittaajan-tiedot lt/sopimuksen-tiedot lt/alusten-tiedot kohde JA kohteenosat , bugittaa eikä . erikseen . #{::lt/kohde-id}) (op/and (when (and alku loppu) {::lt/aika (op/between alku loppu)}) (when kohde-id {::lt/kohde-id kohde-id}) (op/and {::m/poistettu? false ::lt/urakka-id (op/in urakka-idt)} (when (or suunta aluslajit) {::lt/alukset (op/and (when suunta {::lt-alus/suunta suunta}) {::lt-alus/laji (if (empty? aluslajit) (op/in (map name lt-alus/aluslajit)) (op/in (map name aluslajit)))})})))) tiedot))) (defn hae-liikennetapahtumat [db user tiedot] (hae-liikennetapahtumat* tiedot (->> (hae-tapahtumien-perustiedot db tiedot) (hae-tapahtumien-palvelumuodot db) (hae-tapahtumien-kohdetiedot db)) (partial kohteet-q/hae-kohteiden-urakkatiedot db user) (:urakka-idt tiedot))) (defn- hae-kohteen-edellinen-tapahtuma* [tulokset] (first (sort-by ::lt/aika pvm/jalkeen? tulokset))) (defn- hae-kohteen-edellinen-tapahtuma [db tapahtuma] (let [urakka-id (::lt/urakka-id tapahtuma) sopimus-id (::lt/sopimus-id tapahtuma) kohde-id (::lt/kohde-id tapahtuma)] (assert (and urakka-id sopimus-id kohde-id) "Urakka-, sopimus-, tai kohde-id puuttuu, ei voida hakea edellistä tapahtumaa.") (hae-kohteen-edellinen-tapahtuma* (specql/fetch db ::lt/liikennetapahtuma (set/union lt/perustiedot) {::lt/kohde-id kohde-id ::lt/urakka-id urakka-id ::lt/sopimus-id sopimus-id})))) (defn- hae-kuittaamattomat-alukset* [tulokset] (into {} (map (fn [[suunta tapahtumat]] [suunta (when-let [edelliset (map (fn [[kohde ketjut]] (assoc kohde :edelliset-alukset (map (fn [k] (merge (dissoc k ::ketjutus/tapahtumasta ::ketjutus/kohteelta ::ketjutus/alus) (apply merge (map val (select-keys k [::ketjutus/tapahtumasta ::ketjutus/kohteelta ::ketjutus/alus]))))) ketjut))) (group-by ::ketjutus/kohteelta tapahtumat))] (assert (= 1 (count edelliset)) Ketjutus menee , joten edellisiä kohteita voi samasta suunnasta olla vain yksi "Liikennetapahtumien ketjutuksessa virhe. Kohteelle saapuu aluksia samasta suunnasta, monesta kohteesta.") (first edelliset))]) (group-by (comp ::lt-alus/suunta ::ketjutus/alus) tulokset)))) (defn- hae-kuittaamattomat-alukset [db tapahtuma] (let [urakka-id (::lt/urakka-id tapahtuma) sopimus-id (::lt/sopimus-id tapahtuma) kohde-id (::lt/kohde-id tapahtuma)] (assert (and urakka-id sopimus-id kohde-id) "Urakka-, sopimus-, tai kohde-id puuttuu, ei voida hakea ketjutustietoja.") (hae-kuittaamattomat-alukset* (specql/fetch db ::ketjutus/liikennetapahtuman-ketjutus (set/union ketjutus/perustiedot ketjutus/aluksen-tiedot ketjutus/kohteelta-tiedot ketjutus/tapahtumasta-tiedot) {::ketjutus/kohteelle-id kohde-id ::ketjutus/urakka-id urakka-id ::ketjutus/sopimus-id sopimus-id ::ketjutus/tapahtumaan-id op/null?})))) (defn hae-edelliset-tapahtumat [db tiedot] (let [{:keys [ylos alas]} (hae-kuittaamattomat-alukset db tiedot) kohde (hae-kohteen-edellinen-tapahtuma db tiedot)] {:ylos ylos :alas alas :edellinen kohde})) (defn- alus-kuuluu-tapahtumaan? [db alus tapahtuma] (some? (first (specql/fetch db ::lt-alus/liikennetapahtuman-alus #{::lt-alus/id} {::lt-alus/liikennetapahtuma-id (::lt/id tapahtuma) ::lt-alus/id (::lt-alus/id alus)})))) (defn vaadi-alus-kuuluu-tapahtumaan! [db alus tapahtuma] (assert (alus-kuuluu-tapahtumaan? db alus tapahtuma) "Alus ei kuulu tapahtumaan!")) (defn ketjutus-kuuluu-urakkaan? [db alus-id urakka-id] (let [tapahtuma-id (first (map ::ketjutus/tapahtumasta-id (specql/fetch db ::ketjutus/liikennetapahtuman-ketjutus #{::ketjutus/tapahtumasta-id} {::ketjutus/alus-id alus-id})))] (boolean (when tapahtuma-id (not-empty (specql/fetch db ::lt/liikennetapahtuma #{::lt/urakka-id ::lt/id} {::lt/id tapahtuma-id ::lt/urakka-id urakka-id})))))) (defn poista-ketjutus! [db alus-id urakka-id] (when (ketjutus-kuuluu-urakkaan? db alus-id urakka-id) (specql/delete! db ::ketjutus/liikennetapahtuman-ketjutus {::ketjutus/alus-id alus-id ::ketjutus/tapahtumaan-id op/null?}))) (defn vapauta-ketjutus! [db tapahtuma-id] (specql/update! db ::ketjutus/liikennetapahtuman-ketjutus {::ketjutus/tapahtumaan-id nil} {::ketjutus/tapahtumaan-id tapahtuma-id})) (defn poista-alus! [db user alus tapahtuma] (vaadi-alus-kuuluu-tapahtumaan! db alus tapahtuma) (specql/update! db ::lt-alus/liikennetapahtuman-alus (merge {::m/poistaja-id (:id user) ::m/poistettu? true ::m/muokattu (pvm/nyt)} alus) {::lt-alus/id (::lt-alus/id alus)}) (poista-ketjutus! db (::lt-alus/id alus) (::lt/urakka-id tapahtuma))) (defn tallenna-alus-tapahtumaan! [db user alus tapahtuma] (let [olemassa? (id-olemassa? (::lt-alus/id alus)) alus (assoc alus ::lt-alus/liikennetapahtuma-id (::lt/id tapahtuma))] (if (and olemassa? (::m/poistettu? alus)) (poista-alus! db user alus tapahtuma) (if (and olemassa? (alus-kuuluu-tapahtumaan? db alus tapahtuma)) (do (specql/update! db ::lt-alus/liikennetapahtuman-alus (merge {::m/muokkaaja-id (:id user) ::m/muokattu (pvm/nyt)} alus) {::lt-alus/id (::lt-alus/id alus)}) ;; Palauta luotu alus alus) tallennettu ollenkaan ( ) , älä inserttaa sitä tietokantaan Me ei tätä tietoa tarvita (when-not (::m/poistettu? alus) (specql/insert! db ::lt-alus/liikennetapahtuman-alus (merge {::m/luoja-id (:id user)} (-> (->> (keys alus) (filter #(= (namespace %) "harja.domain.kanavat.lt-alus")) (select-keys alus)) (dissoc ::lt-alus/id))))))))) (defn- osa-kuuluu-tapahtumaan? [db osa tapahtuma] (some? (first (specql/fetch db ::toiminto/liikennetapahtuman-toiminto #{::toiminto/id} {::toiminto/liikennetapahtuma-id (::lt/id tapahtuma) ::toiminto/id (::toiminto/id osa)})))) (defn vaadi-osa-kuuluu-tapahtumaan! [db osa tapahtuma] (assert (osa-kuuluu-tapahtumaan? db osa tapahtuma) "Alus ei kuulu tapahtumaan!")) (defn tallenna-osa-tapahtumaan! [db user osa tapahtuma] (let [olemassa? (id-olemassa? (::toiminto/id osa)) osa (assoc osa ::toiminto/liikennetapahtuma-id (::lt/id tapahtuma) ::toiminto/kohde-id (::lt/kohde-id tapahtuma))] (if olemassa? (do (vaadi-osa-kuuluu-tapahtumaan! db osa tapahtuma) (specql/update! db ::toiminto/liikennetapahtuman-toiminto (merge (if (::m/poistettu? osa) {::m/poistaja-id (:id user) ::m/muokattu (pvm/nyt)} {::m/muokkaaja-id (:id user) ::m/muokattu (pvm/nyt)}) (into {} (filter (comp some? val) osa))) {::toiminto/id (::toiminto/id osa)})) (specql/insert! db ::toiminto/liikennetapahtuman-toiminto (merge {::m/luoja-id (:id user)} on nil , specql ei tykännyt (into {} (filter (comp some? val) osa))))))) (defn tapahtuma-kuuluu-urakkaan? [db tapahtuma] (some? (first (specql/fetch db ::lt/liikennetapahtuma #{::lt/id} {::lt/id (::lt/id tapahtuma) ::lt/urakka-id (::lt/urakka-id tapahtuma)})))) (defn vaadi-tapahtuma-kuuluu-urakkaan! [db tapahtuma] (assert (tapahtuma-kuuluu-urakkaan? db tapahtuma) "Tapahtuma ei kuulu urakkaan!")) (defn kuittaa-vanhat-ketjutukset! [db tapahtuma] (specql/update! db ::ketjutus/liikennetapahtuman-ketjutus {::ketjutus/tapahtumaan-id (::lt/id tapahtuma)} {::ketjutus/alus-id (op/in (map ::lt-alus/id (::lt/alukset tapahtuma))) ::ketjutus/kohteelle-id (::lt/kohde-id tapahtuma)})) (defn ketjutus-olemassa? [db alus] (not-empty (specql/fetch db ::ketjutus/liikennetapahtuman-ketjutus #{::ketjutus/alus-id} {::ketjutus/alus-id (::lt-alus/id alus)}))) (defn- hae-seuraavat-kohteet* [kohteet] (mapcat vals kohteet)) (defn hae-seuraavat-kohteet [db kohteelta-id suunta] (hae-seuraavat-kohteet* (specql/fetch db ::kohde/kohde (if (= suunta :ylos) #{::kohde/ylos-id} #{::kohde/alas-id}) {::kohde/id kohteelta-id}))) specql : n insert , insertoidaan , niiden : : suunta on . vertailu on , funktion turvatakseni tulevaisuutta - voi , että myös inserttien paluuarvoihin . (defn- sama-suunta? "Vertailee kahta suuntaa. Suunnat voivat olla keywordejä tai merkkijonoja." [a b] (cond (and (keyword? a) (keyword? b)) (= a b) (and (string? a) (string? b)) (= a b) (and (keyword? a) (string? b)) (= (name a) b) (and (string? a) (keyword? b)) (= (keyword a) b) :else false)) (defn luo-uusi-ketjutus! [db tapahtuma] (let [alukset (::lt/alukset tapahtuma) kohteelta-id (::lt/kohde-id tapahtuma) palautuu insertistä , suunta on suunnat (into #{} (map (comp keyword ::lt-alus/suunta) alukset))] (doseq [suunta suunnat] (doseq [kohteelle-id (hae-seuraavat-kohteet db kohteelta-id suunta)] (doseq [alus (filter (comp (partial sama-suunta? suunta) ::lt-alus/suunta) alukset)] (specql/upsert! db ::ketjutus/liikennetapahtuman-ketjutus #{::ketjutus/alus-id} {::ketjutus/kohteelle-id kohteelle-id ::ketjutus/kohteelta-id kohteelta-id ::ketjutus/alus-id (::lt-alus/id alus) ::ketjutus/tapahtumasta-id (::lt/id tapahtuma) ::ketjutus/urakka-id (::lt/urakka-id tapahtuma) ::ketjutus/sopimus-id (::lt/sopimus-id tapahtuma)})))))) (defn poista-toiminto! [db user toiminto] (specql/update! db ::toiminto/liikennetapahtuman-toiminto {::m/poistaja-id (:id user) ::m/muokattu (pvm/nyt) ::m/poistettu? true} {::toiminto/id (::toiminto/id toiminto)})) (defn poista-tapahtuma! [db user tapahtuma] (specql/update! db ::lt/liikennetapahtuma (merge {::m/poistaja-id (:id user) ::m/poistettu? true ::m/muokattu (pvm/nyt)} (dissoc tapahtuma ::lt/alukset ::lt/toiminnot)) {::lt/id (::lt/id tapahtuma)}) (vapauta-ketjutus! db (::lt/id tapahtuma)) (doseq [alus (::lt/alukset tapahtuma)] (poista-alus! db user alus tapahtuma)) (doseq [toiminto (::lt/toiminnot tapahtuma)] (poista-toiminto! db user toiminto))) (defn tallenna-liikennetapahtuma! [db user tapahtuma] (jdbc/with-db-transaction [db db] (jdbc/execute! db ["SET CONSTRAINTS ALL DEFERRED"]) (if (::m/poistettu? tapahtuma) (poista-tapahtuma! db user tapahtuma) (let [olemassa? (id-olemassa? (::lt/id tapahtuma)) uusi-tapahtuma (if olemassa? (do (vaadi-tapahtuma-kuuluu-urakkaan! db tapahtuma) (specql/update! db ::lt/liikennetapahtuma (merge {::m/muokkaaja-id (:id user) ::m/muokattu (pvm/nyt)} (-> tapahtuma (update ::lt/vesipinta-alaraja #(when-not (nil? %) (bigdec %))) (update ::lt/vesipinta-ylaraja #(when-not (nil? %) (bigdec %))) (dissoc ::lt/alukset ::lt/toiminnot))) {::lt/id (::lt/id tapahtuma)}) , koska update palauttaa vain ykkösen . Ei haeta kannasta uudelleen , koska se on turhaa . tapahtuma) (specql/insert! db ::lt/liikennetapahtuma (merge {::m/luoja-id (:id user)} (dissoc tapahtuma ::lt/id ::lt/alukset ::lt/toiminnot))))] (doseq [osa (::lt/toiminnot tapahtuma)] (tallenna-osa-tapahtumaan! db user osa uusi-tapahtuma)) (kuittaa-vanhat-ketjutukset! db (assoc tapahtuma ::lt/id (::lt/id uusi-tapahtuma))) (let [alukset (doall (for [alus (::lt/alukset tapahtuma)] (tallenna-alus-tapahtumaan! db user alus uusi-tapahtuma)))] (luo-uusi-ketjutus! db (assoc tapahtuma ::lt/alukset (remove ::m/poistettu? alukset) ::lt/id (::lt/id uusi-tapahtuma))))))))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/40b3f90850b60b6add49b25a4ee7da4c71e963ff/src/clj/harja/kyselyt/kanavat/liikennetapahtumat.clj
clojure
Voi olla nil tai "" Palauta luotu alus
(ns harja.kyselyt.kanavat.liikennetapahtumat (:require [clojure.java.jdbc :as jdbc] [clojure.spec.alpha :as s] [clojure.set :as set] [jeesql.core :refer [defqueries]] [specql.core :as specql] [specql.op :as op] [specql.rel :as rel] [taoensso.timbre :as log] [jeesql.core :refer [defqueries]] [harja.id :refer [id-olemassa?]] [harja.pvm :as pvm] [harja.kyselyt.kanavat.kohteet :as kohteet-q] [harja.domain.urakka :as ur] [harja.domain.sopimus :as sop] [harja.domain.muokkaustiedot :as m] [harja.domain.kanavat.liikennetapahtuma :as lt] [harja.domain.kanavat.lt-alus :as lt-alus] [harja.domain.kanavat.lt-toiminto :as toiminto] [harja.domain.kanavat.lt-ketjutus :as ketjutus] [harja.domain.kanavat.kohde :as kohde] [clojure.string :as str] [clojure.core :as c])) (defn- liita-kohteen-urakkatiedot [kohteiden-haku tapahtumat] (let [kohteet (group-by ::kohde/id (kohteiden-haku (map ::lt/kohde tapahtumat)))] (into [] (map #(update % ::lt/kohde (fn [kohde] (if-let [kohteen-urakat (-> kohde ::kohde/id kohteet first ::kohde/urakat)] (assoc kohde ::kohde/urakat kohteen-urakat) (assoc kohde ::kohde/urakat [])))) tapahtumat)))) (defn- urakat-idlla [urakka-idt tapahtuma] (update-in tapahtuma [::lt/kohde ::kohde/urakat] (fn [urakat] (keep #(when (urakka-idt (::ur/id %)) %) urakat)))) (defn- suodata-liikennetapahtuma-toimenpidetyypillä [tiedot tapahtumat] (filter #(let [toimenpidetyypit (::toiminto/toimenpiteet tiedot)] (if (empty? toimenpidetyypit) true (some toimenpidetyypit (map ::toiminto/toimenpide (::lt/toiminnot %))))) tapahtumat)) (defn- suodata-liikennetapahtuma-aluksen-nimella [tiedot tapahtumat] (filter (fn [tapahtuma] (let [alus-nimi (::lt-alus/nimi tiedot)] true , alkaa annetulla nimellä (not (empty? (lt-alus/suodata-alukset-nimen-alulla (::lt/alukset tapahtuma) alus-nimi)))))) tapahtumat)) (defn- hae-liikennetapahtumat* [tiedot tapahtumat urakkatiedot-fn urakka-idt] (->> tapahtumat (suodata-liikennetapahtuma-toimenpidetyypillä tiedot) (suodata-liikennetapahtuma-aluksen-nimella tiedot) (liita-kohteen-urakkatiedot urakkatiedot-fn) (map (partial urakat-idlla urakka-idt)) (remove (comp empty? ::kohde/urakat ::lt/kohde)))) (def ilman-poistettuja-aluksia (map #(update % ::lt/alukset (partial remove ::m/poistettu?)))) (def vain-uittoniput (keep (fn [t] (let [t (update t ::lt/alukset (partial remove (comp #(or (nil? %) (zero? %)) ::lt-alus/nippulkm)))] (when-not (empty? (::lt/alukset t)) t))))) (defn- hae-tapahtumien-palvelumuodot* [osien-tiedot tapahtumat] (let [id-ja-osat (->> osien-tiedot (group-by ::lt/id) (map (fn [[id osat]] [id (get-in osat [0 ::lt/toiminnot])])) (into {}))] (map (fn [tapahtuma] (assoc tapahtuma ::lt/toiminnot (id-ja-osat (::lt/id tapahtuma)))) tapahtumat))) (defn hae-tapahtumien-palvelumuodot [db tapahtumat] (hae-tapahtumien-palvelumuodot* (specql/fetch db ::lt/liikennetapahtuma (set/union lt/perustiedot lt/toimintojen-tiedot) {::lt/id (op/in (map ::lt/id tapahtumat))}) tapahtumat)) (defn- hae-tapahtumien-kohdetiedot* [kohdetiedot tapahtumat] (let [id-ja-kohde (->> kohdetiedot (group-by ::kohde/id))] (map (fn [tapahtuma] (assoc tapahtuma ::lt/kohde (first (id-ja-kohde (::lt/kohde-id tapahtuma))))) tapahtumat))) (defn hae-tapahtumien-kohdetiedot [db tapahtumat] (hae-tapahtumien-kohdetiedot* (specql/fetch db ::kohde/kohde (set/union kohde/perustiedot kohde/kohteenosat) {::kohde/id (op/in (map ::lt/kohde-id tapahtumat)) ::m/poistettu? false}) tapahtumat)) (defn- hae-tapahtumien-perustiedot* [tapahtumat {:keys [niput?]}] (into [] (apply comp (remove nil? [(when niput? vain-uittoniput) otetaan pois poistetut alukset , niin ei palaudu tapahtumat , joiden kaikki . ilman-poistettuja-aluksia])) tapahtumat)) (defn hae-tapahtumien-perustiedot [db {:keys [aikavali] :as tiedot}] (let [urakka-idt (:urakka-idt tiedot) kohde-id (get-in tiedot [::lt/kohde ::kohde/id]) aluslajit (::lt-alus/aluslajit tiedot) suunta (::lt-alus/suunta tiedot) [alku loppu] aikavali] (hae-tapahtumien-perustiedot* (specql/fetch db ::lt/liikennetapahtuma (set/union lt/perustiedot lt/kuittaajan-tiedot lt/sopimuksen-tiedot lt/alusten-tiedot kohde JA kohteenosat , bugittaa eikä . erikseen . #{::lt/kohde-id}) (op/and (when (and alku loppu) {::lt/aika (op/between alku loppu)}) (when kohde-id {::lt/kohde-id kohde-id}) (op/and {::m/poistettu? false ::lt/urakka-id (op/in urakka-idt)} (when (or suunta aluslajit) {::lt/alukset (op/and (when suunta {::lt-alus/suunta suunta}) {::lt-alus/laji (if (empty? aluslajit) (op/in (map name lt-alus/aluslajit)) (op/in (map name aluslajit)))})})))) tiedot))) (defn hae-liikennetapahtumat [db user tiedot] (hae-liikennetapahtumat* tiedot (->> (hae-tapahtumien-perustiedot db tiedot) (hae-tapahtumien-palvelumuodot db) (hae-tapahtumien-kohdetiedot db)) (partial kohteet-q/hae-kohteiden-urakkatiedot db user) (:urakka-idt tiedot))) (defn- hae-kohteen-edellinen-tapahtuma* [tulokset] (first (sort-by ::lt/aika pvm/jalkeen? tulokset))) (defn- hae-kohteen-edellinen-tapahtuma [db tapahtuma] (let [urakka-id (::lt/urakka-id tapahtuma) sopimus-id (::lt/sopimus-id tapahtuma) kohde-id (::lt/kohde-id tapahtuma)] (assert (and urakka-id sopimus-id kohde-id) "Urakka-, sopimus-, tai kohde-id puuttuu, ei voida hakea edellistä tapahtumaa.") (hae-kohteen-edellinen-tapahtuma* (specql/fetch db ::lt/liikennetapahtuma (set/union lt/perustiedot) {::lt/kohde-id kohde-id ::lt/urakka-id urakka-id ::lt/sopimus-id sopimus-id})))) (defn- hae-kuittaamattomat-alukset* [tulokset] (into {} (map (fn [[suunta tapahtumat]] [suunta (when-let [edelliset (map (fn [[kohde ketjut]] (assoc kohde :edelliset-alukset (map (fn [k] (merge (dissoc k ::ketjutus/tapahtumasta ::ketjutus/kohteelta ::ketjutus/alus) (apply merge (map val (select-keys k [::ketjutus/tapahtumasta ::ketjutus/kohteelta ::ketjutus/alus]))))) ketjut))) (group-by ::ketjutus/kohteelta tapahtumat))] (assert (= 1 (count edelliset)) Ketjutus menee , joten edellisiä kohteita voi samasta suunnasta olla vain yksi "Liikennetapahtumien ketjutuksessa virhe. Kohteelle saapuu aluksia samasta suunnasta, monesta kohteesta.") (first edelliset))]) (group-by (comp ::lt-alus/suunta ::ketjutus/alus) tulokset)))) (defn- hae-kuittaamattomat-alukset [db tapahtuma] (let [urakka-id (::lt/urakka-id tapahtuma) sopimus-id (::lt/sopimus-id tapahtuma) kohde-id (::lt/kohde-id tapahtuma)] (assert (and urakka-id sopimus-id kohde-id) "Urakka-, sopimus-, tai kohde-id puuttuu, ei voida hakea ketjutustietoja.") (hae-kuittaamattomat-alukset* (specql/fetch db ::ketjutus/liikennetapahtuman-ketjutus (set/union ketjutus/perustiedot ketjutus/aluksen-tiedot ketjutus/kohteelta-tiedot ketjutus/tapahtumasta-tiedot) {::ketjutus/kohteelle-id kohde-id ::ketjutus/urakka-id urakka-id ::ketjutus/sopimus-id sopimus-id ::ketjutus/tapahtumaan-id op/null?})))) (defn hae-edelliset-tapahtumat [db tiedot] (let [{:keys [ylos alas]} (hae-kuittaamattomat-alukset db tiedot) kohde (hae-kohteen-edellinen-tapahtuma db tiedot)] {:ylos ylos :alas alas :edellinen kohde})) (defn- alus-kuuluu-tapahtumaan? [db alus tapahtuma] (some? (first (specql/fetch db ::lt-alus/liikennetapahtuman-alus #{::lt-alus/id} {::lt-alus/liikennetapahtuma-id (::lt/id tapahtuma) ::lt-alus/id (::lt-alus/id alus)})))) (defn vaadi-alus-kuuluu-tapahtumaan! [db alus tapahtuma] (assert (alus-kuuluu-tapahtumaan? db alus tapahtuma) "Alus ei kuulu tapahtumaan!")) (defn ketjutus-kuuluu-urakkaan? [db alus-id urakka-id] (let [tapahtuma-id (first (map ::ketjutus/tapahtumasta-id (specql/fetch db ::ketjutus/liikennetapahtuman-ketjutus #{::ketjutus/tapahtumasta-id} {::ketjutus/alus-id alus-id})))] (boolean (when tapahtuma-id (not-empty (specql/fetch db ::lt/liikennetapahtuma #{::lt/urakka-id ::lt/id} {::lt/id tapahtuma-id ::lt/urakka-id urakka-id})))))) (defn poista-ketjutus! [db alus-id urakka-id] (when (ketjutus-kuuluu-urakkaan? db alus-id urakka-id) (specql/delete! db ::ketjutus/liikennetapahtuman-ketjutus {::ketjutus/alus-id alus-id ::ketjutus/tapahtumaan-id op/null?}))) (defn vapauta-ketjutus! [db tapahtuma-id] (specql/update! db ::ketjutus/liikennetapahtuman-ketjutus {::ketjutus/tapahtumaan-id nil} {::ketjutus/tapahtumaan-id tapahtuma-id})) (defn poista-alus! [db user alus tapahtuma] (vaadi-alus-kuuluu-tapahtumaan! db alus tapahtuma) (specql/update! db ::lt-alus/liikennetapahtuman-alus (merge {::m/poistaja-id (:id user) ::m/poistettu? true ::m/muokattu (pvm/nyt)} alus) {::lt-alus/id (::lt-alus/id alus)}) (poista-ketjutus! db (::lt-alus/id alus) (::lt/urakka-id tapahtuma))) (defn tallenna-alus-tapahtumaan! [db user alus tapahtuma] (let [olemassa? (id-olemassa? (::lt-alus/id alus)) alus (assoc alus ::lt-alus/liikennetapahtuma-id (::lt/id tapahtuma))] (if (and olemassa? (::m/poistettu? alus)) (poista-alus! db user alus tapahtuma) (if (and olemassa? (alus-kuuluu-tapahtumaan? db alus tapahtuma)) (do (specql/update! db ::lt-alus/liikennetapahtuman-alus (merge {::m/muokkaaja-id (:id user) ::m/muokattu (pvm/nyt)} alus) {::lt-alus/id (::lt-alus/id alus)}) alus) tallennettu ollenkaan ( ) , älä inserttaa sitä tietokantaan Me ei tätä tietoa tarvita (when-not (::m/poistettu? alus) (specql/insert! db ::lt-alus/liikennetapahtuman-alus (merge {::m/luoja-id (:id user)} (-> (->> (keys alus) (filter #(= (namespace %) "harja.domain.kanavat.lt-alus")) (select-keys alus)) (dissoc ::lt-alus/id))))))))) (defn- osa-kuuluu-tapahtumaan? [db osa tapahtuma] (some? (first (specql/fetch db ::toiminto/liikennetapahtuman-toiminto #{::toiminto/id} {::toiminto/liikennetapahtuma-id (::lt/id tapahtuma) ::toiminto/id (::toiminto/id osa)})))) (defn vaadi-osa-kuuluu-tapahtumaan! [db osa tapahtuma] (assert (osa-kuuluu-tapahtumaan? db osa tapahtuma) "Alus ei kuulu tapahtumaan!")) (defn tallenna-osa-tapahtumaan! [db user osa tapahtuma] (let [olemassa? (id-olemassa? (::toiminto/id osa)) osa (assoc osa ::toiminto/liikennetapahtuma-id (::lt/id tapahtuma) ::toiminto/kohde-id (::lt/kohde-id tapahtuma))] (if olemassa? (do (vaadi-osa-kuuluu-tapahtumaan! db osa tapahtuma) (specql/update! db ::toiminto/liikennetapahtuman-toiminto (merge (if (::m/poistettu? osa) {::m/poistaja-id (:id user) ::m/muokattu (pvm/nyt)} {::m/muokkaaja-id (:id user) ::m/muokattu (pvm/nyt)}) (into {} (filter (comp some? val) osa))) {::toiminto/id (::toiminto/id osa)})) (specql/insert! db ::toiminto/liikennetapahtuman-toiminto (merge {::m/luoja-id (:id user)} on nil , specql ei tykännyt (into {} (filter (comp some? val) osa))))))) (defn tapahtuma-kuuluu-urakkaan? [db tapahtuma] (some? (first (specql/fetch db ::lt/liikennetapahtuma #{::lt/id} {::lt/id (::lt/id tapahtuma) ::lt/urakka-id (::lt/urakka-id tapahtuma)})))) (defn vaadi-tapahtuma-kuuluu-urakkaan! [db tapahtuma] (assert (tapahtuma-kuuluu-urakkaan? db tapahtuma) "Tapahtuma ei kuulu urakkaan!")) (defn kuittaa-vanhat-ketjutukset! [db tapahtuma] (specql/update! db ::ketjutus/liikennetapahtuman-ketjutus {::ketjutus/tapahtumaan-id (::lt/id tapahtuma)} {::ketjutus/alus-id (op/in (map ::lt-alus/id (::lt/alukset tapahtuma))) ::ketjutus/kohteelle-id (::lt/kohde-id tapahtuma)})) (defn ketjutus-olemassa? [db alus] (not-empty (specql/fetch db ::ketjutus/liikennetapahtuman-ketjutus #{::ketjutus/alus-id} {::ketjutus/alus-id (::lt-alus/id alus)}))) (defn- hae-seuraavat-kohteet* [kohteet] (mapcat vals kohteet)) (defn hae-seuraavat-kohteet [db kohteelta-id suunta] (hae-seuraavat-kohteet* (specql/fetch db ::kohde/kohde (if (= suunta :ylos) #{::kohde/ylos-id} #{::kohde/alas-id}) {::kohde/id kohteelta-id}))) specql : n insert , insertoidaan , niiden : : suunta on . vertailu on , funktion turvatakseni tulevaisuutta - voi , että myös inserttien paluuarvoihin . (defn- sama-suunta? "Vertailee kahta suuntaa. Suunnat voivat olla keywordejä tai merkkijonoja." [a b] (cond (and (keyword? a) (keyword? b)) (= a b) (and (string? a) (string? b)) (= a b) (and (keyword? a) (string? b)) (= (name a) b) (and (string? a) (keyword? b)) (= (keyword a) b) :else false)) (defn luo-uusi-ketjutus! [db tapahtuma] (let [alukset (::lt/alukset tapahtuma) kohteelta-id (::lt/kohde-id tapahtuma) palautuu insertistä , suunta on suunnat (into #{} (map (comp keyword ::lt-alus/suunta) alukset))] (doseq [suunta suunnat] (doseq [kohteelle-id (hae-seuraavat-kohteet db kohteelta-id suunta)] (doseq [alus (filter (comp (partial sama-suunta? suunta) ::lt-alus/suunta) alukset)] (specql/upsert! db ::ketjutus/liikennetapahtuman-ketjutus #{::ketjutus/alus-id} {::ketjutus/kohteelle-id kohteelle-id ::ketjutus/kohteelta-id kohteelta-id ::ketjutus/alus-id (::lt-alus/id alus) ::ketjutus/tapahtumasta-id (::lt/id tapahtuma) ::ketjutus/urakka-id (::lt/urakka-id tapahtuma) ::ketjutus/sopimus-id (::lt/sopimus-id tapahtuma)})))))) (defn poista-toiminto! [db user toiminto] (specql/update! db ::toiminto/liikennetapahtuman-toiminto {::m/poistaja-id (:id user) ::m/muokattu (pvm/nyt) ::m/poistettu? true} {::toiminto/id (::toiminto/id toiminto)})) (defn poista-tapahtuma! [db user tapahtuma] (specql/update! db ::lt/liikennetapahtuma (merge {::m/poistaja-id (:id user) ::m/poistettu? true ::m/muokattu (pvm/nyt)} (dissoc tapahtuma ::lt/alukset ::lt/toiminnot)) {::lt/id (::lt/id tapahtuma)}) (vapauta-ketjutus! db (::lt/id tapahtuma)) (doseq [alus (::lt/alukset tapahtuma)] (poista-alus! db user alus tapahtuma)) (doseq [toiminto (::lt/toiminnot tapahtuma)] (poista-toiminto! db user toiminto))) (defn tallenna-liikennetapahtuma! [db user tapahtuma] (jdbc/with-db-transaction [db db] (jdbc/execute! db ["SET CONSTRAINTS ALL DEFERRED"]) (if (::m/poistettu? tapahtuma) (poista-tapahtuma! db user tapahtuma) (let [olemassa? (id-olemassa? (::lt/id tapahtuma)) uusi-tapahtuma (if olemassa? (do (vaadi-tapahtuma-kuuluu-urakkaan! db tapahtuma) (specql/update! db ::lt/liikennetapahtuma (merge {::m/muokkaaja-id (:id user) ::m/muokattu (pvm/nyt)} (-> tapahtuma (update ::lt/vesipinta-alaraja #(when-not (nil? %) (bigdec %))) (update ::lt/vesipinta-ylaraja #(when-not (nil? %) (bigdec %))) (dissoc ::lt/alukset ::lt/toiminnot))) {::lt/id (::lt/id tapahtuma)}) , koska update palauttaa vain ykkösen . Ei haeta kannasta uudelleen , koska se on turhaa . tapahtuma) (specql/insert! db ::lt/liikennetapahtuma (merge {::m/luoja-id (:id user)} (dissoc tapahtuma ::lt/id ::lt/alukset ::lt/toiminnot))))] (doseq [osa (::lt/toiminnot tapahtuma)] (tallenna-osa-tapahtumaan! db user osa uusi-tapahtuma)) (kuittaa-vanhat-ketjutukset! db (assoc tapahtuma ::lt/id (::lt/id uusi-tapahtuma))) (let [alukset (doall (for [alus (::lt/alukset tapahtuma)] (tallenna-alus-tapahtumaan! db user alus uusi-tapahtuma)))] (luo-uusi-ketjutus! db (assoc tapahtuma ::lt/alukset (remove ::m/poistettu? alukset) ::lt/id (::lt/id uusi-tapahtuma))))))))
7ec8f848e1a6f194b036aa2e815ca2da78d274067abf1d5768f1d8abf5eb4ea3
cyppan/grape
restricts_fields.clj
(ns grape.hooks.restricts-fields (:require [grape.schema :refer :all]) (:import (grape.schema Hidden))) (def hooks {:pre-read (fn [deps resource request query] (let [query-fields (map keyword (vec (:fields query []))) resource-fields (when-let [fields (:fields resource)] (into #{} fields)) schema-fields (->> (get-schema-keyseqs (:schema resource) :skip-hidden? true) (map #(filter (partial not= []) %)) (map #(keyword (clojure.string/join "." (map name %)))) (into #{})) default-fields (->> (get-schema-keyseqs (:schema resource) :skip-hidden? true) (filter #(= (count %) 1)) (map first) (into #{})) fields (if (seq query-fields) (into [] (filter (or resource-fields schema-fields) query-fields)) (into [] (or resource-fields default-fields)))] (when (empty? fields) (throw (ex-info "there is no field to fetch for your resource" {:type :restrict-fields}))) (assoc-in query [:fields] fields)))})
null
https://raw.githubusercontent.com/cyppan/grape/62488a335542fc58fc9126b8d5ff7fccdd16f1d7/src/grape/hooks/restricts_fields.clj
clojure
(ns grape.hooks.restricts-fields (:require [grape.schema :refer :all]) (:import (grape.schema Hidden))) (def hooks {:pre-read (fn [deps resource request query] (let [query-fields (map keyword (vec (:fields query []))) resource-fields (when-let [fields (:fields resource)] (into #{} fields)) schema-fields (->> (get-schema-keyseqs (:schema resource) :skip-hidden? true) (map #(filter (partial not= []) %)) (map #(keyword (clojure.string/join "." (map name %)))) (into #{})) default-fields (->> (get-schema-keyseqs (:schema resource) :skip-hidden? true) (filter #(= (count %) 1)) (map first) (into #{})) fields (if (seq query-fields) (into [] (filter (or resource-fields schema-fields) query-fields)) (into [] (or resource-fields default-fields)))] (when (empty? fields) (throw (ex-info "there is no field to fetch for your resource" {:type :restrict-fields}))) (assoc-in query [:fields] fields)))})
7ab429217ec90f16cee30202492582985ad942d4edf4e30079a9303b24d18668
Datomic/day-of-datomic
find_specification_examples.clj
Copyright ( c ) Cognitect , Inc. All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (require '[datomic.api :as d] '[datomic.samples.repl :as repl]) ;; The examples below parallel #find-specifications (def conn (repl/scratch-conn)) (def db (d/db conn)) ;; relation find spec (d/q '[:find ?e ?v :where [?e :db/ident ?v]] db) ;; collection find spec (d/q '[:find [?v ...] :where [_ :db/ident ?v]] db) ;; single tuple find spec (d/q '[:find [?e ?ident] :where [?e :db/ident ?ident]] db) ;; single scalar find spec (d/q '[:find ?v . :where [0 :db/ident ?v]] db) ;; Sample examples as above, using map forms. ;; relation find spec (d/q '{:find [?e ?v] :where [[?e :db/ident ?v]]} db) ;; collection find spec (d/q '{:find [[?v ...]] :where [[_ :db/ident ?v]]} db) ;; single tuple find spec (d/q '{:find [[?e ?ident]] :where [[?e :db/ident ?ident]]} db) ;; single scalar find spec (d/q '{:find [?v .] :where [[0 :db/ident ?v]]} db) (d/release conn)
null
https://raw.githubusercontent.com/Datomic/day-of-datomic/20c02d26fd2a12481903dd5347589456c74f8eeb/tutorial/find_specification_examples.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. The examples below parallel #find-specifications relation find spec collection find spec single tuple find spec single scalar find spec Sample examples as above, using map forms. relation find spec collection find spec single tuple find spec single scalar find spec
Copyright ( c ) Cognitect , Inc. All rights reserved . (require '[datomic.api :as d] '[datomic.samples.repl :as repl]) (def conn (repl/scratch-conn)) (def db (d/db conn)) (d/q '[:find ?e ?v :where [?e :db/ident ?v]] db) (d/q '[:find [?v ...] :where [_ :db/ident ?v]] db) (d/q '[:find [?e ?ident] :where [?e :db/ident ?ident]] db) (d/q '[:find ?v . :where [0 :db/ident ?v]] db) (d/q '{:find [?e ?v] :where [[?e :db/ident ?v]]} db) (d/q '{:find [[?v ...]] :where [[_ :db/ident ?v]]} db) (d/q '{:find [[?e ?ident]] :where [[?e :db/ident ?ident]]} db) (d/q '{:find [?v .] :where [[0 :db/ident ?v]]} db) (d/release conn)
3a93ed185501bfb06e4e230082452e8bff6063be779d931fd81fad74367c9f19
mfikes/fifth-postulate
ns372.cljs
(ns fifth-postulate.ns372) (defn solve-for01 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for02 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for03 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for04 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for05 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for06 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for07 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for08 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for09 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for10 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for11 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for12 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for13 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for14 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for15 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for16 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for17 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for18 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for19 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
null
https://raw.githubusercontent.com/mfikes/fifth-postulate/22cfd5f8c2b4a2dead1c15a96295bfeb4dba235e/src/fifth_postulate/ns372.cljs
clojure
(ns fifth-postulate.ns372) (defn solve-for01 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for02 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for03 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for04 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for05 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for06 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for07 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for08 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for09 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for10 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for11 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for12 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for13 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for14 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for15 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for16 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for17 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for18 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for19 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
99e5a683f0258975145a17da20b7e5eaadf01d8fc02aaf4167a194f8ce11bfb3
huangz1990/SICP-answers
26-tree.scm
26-tree.scm ; constructor (define (make-tree key value left-branch right-branch) (list key value left-branch right-branch)) ; selector (define (tree-key tree) (car tree)) (define (tree-value tree) (cadr tree)) (define (tree-left-branch tree) (caddr tree)) (define (tree-right-branch tree) (cadddr tree)) (define (tree-empty? tree) (null? tree)) ; setter (define (tree-set-key! new-key tree) (set-car! tree new-key)) (define (tree-set-value! new-value tree) (set-car! (cdr tree) new-value)) (define (tree-set-left-branch! new-left-branch tree) (set-car! (cddr tree) new-left-branch)) (define (tree-set-right-branch! new-right-branch tree) (set-car! (cdddr tree) new-right-branch)) ; operator (define (tree-insert! tree given-key value compare) (if (tree-empty? tree) (make-tree given-key value '() '()) (let ((compare-result (compare given-key (tree-key tree)))) (cond ((= 0 compare-result) (tree-set-value! value tree) tree) ((= 1 compare-result) (tree-set-right-branch! (tree-insert! (tree-right-branch tree) given-key value compare) tree) tree) ((= -1 compare-result) (tree-set-left-branch! (tree-insert! (tree-left-branch tree) given-key value compare) tree) tree))))) (define (tree-search tree given-key compare) (if (tree-empty? tree) '() (let ((compare-result (compare given-key (tree-key tree)))) (cond ((= 0 compare-result) tree) ((= 1 compare-result) (tree-search (tree-right-branch tree) given-key compare)) ((= -1 compare-result) (tree-search (tree-left-branch tree) given-key compare)))))) ; comparer (define (compare-string x y) (cond ((string=? x y) 0) ((string>? x y) 1) ((string<? x y) -1))) (define (compare-symbol x y) (compare-string (symbol->string x) (symbol->string y))) (define (compare-number x y) (cond ((= x y) 0) ((> x y) 1) ((< x y) -1)))
null
https://raw.githubusercontent.com/huangz1990/SICP-answers/15e3475003ef10eb738cf93c1932277bc56bacbe/chp3/code/26-tree.scm
scheme
constructor selector setter operator comparer
26-tree.scm (define (make-tree key value left-branch right-branch) (list key value left-branch right-branch)) (define (tree-key tree) (car tree)) (define (tree-value tree) (cadr tree)) (define (tree-left-branch tree) (caddr tree)) (define (tree-right-branch tree) (cadddr tree)) (define (tree-empty? tree) (null? tree)) (define (tree-set-key! new-key tree) (set-car! tree new-key)) (define (tree-set-value! new-value tree) (set-car! (cdr tree) new-value)) (define (tree-set-left-branch! new-left-branch tree) (set-car! (cddr tree) new-left-branch)) (define (tree-set-right-branch! new-right-branch tree) (set-car! (cdddr tree) new-right-branch)) (define (tree-insert! tree given-key value compare) (if (tree-empty? tree) (make-tree given-key value '() '()) (let ((compare-result (compare given-key (tree-key tree)))) (cond ((= 0 compare-result) (tree-set-value! value tree) tree) ((= 1 compare-result) (tree-set-right-branch! (tree-insert! (tree-right-branch tree) given-key value compare) tree) tree) ((= -1 compare-result) (tree-set-left-branch! (tree-insert! (tree-left-branch tree) given-key value compare) tree) tree))))) (define (tree-search tree given-key compare) (if (tree-empty? tree) '() (let ((compare-result (compare given-key (tree-key tree)))) (cond ((= 0 compare-result) tree) ((= 1 compare-result) (tree-search (tree-right-branch tree) given-key compare)) ((= -1 compare-result) (tree-search (tree-left-branch tree) given-key compare)))))) (define (compare-string x y) (cond ((string=? x y) 0) ((string>? x y) 1) ((string<? x y) -1))) (define (compare-symbol x y) (compare-string (symbol->string x) (symbol->string y))) (define (compare-number x y) (cond ((= x y) 0) ((> x y) 1) ((< x y) -1)))
1bef7fa6aaae902ed9a2a970acb4a098939d9aa74823795719022b064b8ba61f
atlas-engineer/closure
dep-acl.lisp
;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: GLISP; -*- ;;; --------------------------------------------------------------------------- Title : ACL-4.3 dependent stuff + fixups Created : 1999 - 05 - 25 22:33 Author : < > License : MIT style ( see below ) ;;; --------------------------------------------------------------------------- ( c ) copyright 1998,1999 by ;;; 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. (defun glisp::read-byte-sequence (&rest ap) (apply #'read-sequence ap)) (defun glisp::read-char-sequence (&rest ap) (apply #'read-sequence ap)) (defmacro glisp::with-timeout ((&rest options) &body body) `(mp:with-timeout ,options . ,body)) (defun glisp::g/make-string (length &rest options) (apply #'make-array length :element-type 'base-char options)) (defun glisp:run-unix-shell-command (cmd) (excl:shell cmd)) (defun glisp::getenv (string) (sys:getenv string))
null
https://raw.githubusercontent.com/atlas-engineer/closure/539ce81dbcb5fb46e19818a9bb35eeaf86042219/src/glisp/dep-acl.lisp
lisp
-*- Mode: Lisp; Syntax: Common-Lisp; Package: GLISP; -*- --------------------------------------------------------------------------- --------------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the without limitation the rights to use, copy, modify, merge, publish, the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Title : ACL-4.3 dependent stuff + fixups Created : 1999 - 05 - 25 22:33 Author : < > License : MIT style ( see below ) ( c ) copyright 1998,1999 by " Software " ) , to deal in the Software without restriction , including distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , (defun glisp::read-byte-sequence (&rest ap) (apply #'read-sequence ap)) (defun glisp::read-char-sequence (&rest ap) (apply #'read-sequence ap)) (defmacro glisp::with-timeout ((&rest options) &body body) `(mp:with-timeout ,options . ,body)) (defun glisp::g/make-string (length &rest options) (apply #'make-array length :element-type 'base-char options)) (defun glisp:run-unix-shell-command (cmd) (excl:shell cmd)) (defun glisp::getenv (string) (sys:getenv string))
b859694d90a94ecc1a7a48e45a3724792e55ed81810f7c2236800995c1080046
khasm-lang/khasmc
hash.ml
let main_tbl : (int, Ast.typesig) Hashtbl.t = Hashtbl.create ~random:true 100 let add_typ id typ = Hashtbl.add main_tbl id typ let get_typ id = Hashtbl.find main_tbl id let print_table () = Hashtbl.iter (fun x y -> print_string (string_of_int x); print_string ": "; print_endline (Ast.pshow_typesig y)) main_tbl
null
https://raw.githubusercontent.com/khasm-lang/khasmc/e190cad60ba66e701ad0ae9d288ddb9a55e63a12/lib/frontend/hash.ml
ocaml
let main_tbl : (int, Ast.typesig) Hashtbl.t = Hashtbl.create ~random:true 100 let add_typ id typ = Hashtbl.add main_tbl id typ let get_typ id = Hashtbl.find main_tbl id let print_table () = Hashtbl.iter (fun x y -> print_string (string_of_int x); print_string ": "; print_endline (Ast.pshow_typesig y)) main_tbl
8daf6dba5615ae7290cf5829bfcdd945a85a712b19b75407f18bc9efb4a1dda7
gfngfn/SATySFi
pageInfo.ml
open HorzBox -- ' embed_page_info pbinfo imhblst ' associates ' ImHorzHookPageBreak ( ... ) ' in ' imhblst ' with ' pbinfo ' , and returns footnotes in ' imhblst ' -- 'embed_page_info pbinfo imhblst' associates 'ImHorzHookPageBreak(...)' in 'imhblst' with 'pbinfo', and returns footnotes in 'imhblst' -- *) let rec embed_page_info (pbinfo : page_break_info) (imhblst : intermediate_horz_box list) : evaled_horz_box list * (intermediate_vert_box list) list = let iter = embed_page_info pbinfo in let (evhbacc, footnoteacc) = imhblst |> List.fold_left (fun (evhbacc, footnoteacc) imhb -> let extH = Alist.extend evhbacc in let appendF = Alist.append footnoteacc in let ext evhb = (extH evhb, footnoteacc) in match imhb with | ImHorz(evhb) -> ext evhb | ImHorzRising(wid, hgt, dpt, lenrising, imhblst) -> let (evhblst, footnotelst) = iter imhblst in let evhb = (wid, EvHorzRising(hgt, dpt, lenrising, evhblst)) in (extH evhb, appendF footnotelst) | ImHorzFrame(ratios, wid, hgt, dpt, deco, imhbs) -> let (evhbs, footnotelst) = iter imhbs in let evhb = (wid, EvHorzFrame(ratios, hgt, dpt, deco, evhbs)) in (extH evhb, appendF footnotelst) | ImHorzInlineTabular(wid, hgt, dpt, imtabular, widlst, lenlst, rulesf) -> let (evrowlst, footnotelst) = embed_page_info_to_tabular pbinfo imtabular in ext (wid, EvHorzInlineTabular(hgt, dpt, evrowlst, widlst, lenlst, rulesf)) | ImHorzEmbeddedVert(wid, hgt, dpt, imvblst) -> let (evvblst, footnotelst) = embed_page_info_vert pbinfo imvblst in let evhb = (wid, EvHorzEmbeddedVert(hgt, dpt, evvblst)) in (extH evhb, appendF footnotelst) | ImHorzHookPageBreak(hookf) -> ext (Length.zero, EvHorzHookPageBreak(pbinfo, hookf)) | ImHorzInlineGraphics(wid, hgt, dpt, graphics) -> ext (wid, EvHorzInlineGraphics(hgt, dpt, graphics)) | ImHorzFootnote(imvblst) -> (evhbacc, Alist.extend footnoteacc imvblst) ) (Alist.empty, Alist.empty) in (Alist.to_list evhbacc, Alist.to_list footnoteacc) and embed_page_info_to_tabular (pbinfo : page_break_info) (imtabular : intermediate_row list) : evaled_row list * (intermediate_vert_box list) list = let (evrowacc, footnoteacc) = imtabular |> List.fold_left (fun (evrowacc, footnoteacc) (widtotal, imcelllst) -> let (evcellacc, footnoteacc) = imcelllst |> List.fold_left (fun (evcellacc, footnoteacc) imcell -> let extC = Alist.extend evcellacc in let appendF = Alist.append footnoteacc in match imcell with | ImEmptyCell(len) -> (extC (EvEmptyCell(len)), footnoteacc) | ImNormalCell(ratios, info, imhblst) -> let (evhblst, footnotelst) = embed_page_info pbinfo imhblst in let evcell = EvNormalCell(ratios, info, evhblst) in (extC evcell, appendF footnotelst) | ImMultiCell(ratios, info, imhblst) -> let (evhblst, footnotelst) = embed_page_info pbinfo imhblst in let evcell = EvMultiCell(ratios, info, evhblst) in (extC evcell, appendF footnotelst) ) (Alist.empty, footnoteacc) in (Alist.extend evrowacc (widtotal, Alist.to_list evcellacc), footnoteacc) ) (Alist.empty, Alist.empty) in (Alist.to_list evrowacc, Alist.to_list footnoteacc) and embed_page_info_vert (pbinfo : page_break_info) (imvblst : intermediate_vert_box list) : evaled_vert_box list * (intermediate_vert_box list) list = let (evvbacc, footnoteacc) = imvblst |> List.fold_left (fun (evvbacc, footnoteacc) imvb -> let extV = Alist.extend evvbacc in let appendF = Alist.append footnoteacc in match imvb with | ImVertLine(ratios, hgt, dpt, imhbs) -> let (imvbs, footnotelst) = embed_page_info pbinfo imhbs in let evvb = EvVertLine(ratios, hgt, dpt, imvbs) in (extV evvb, appendF footnotelst) | ImVertFixedEmpty(debug_margins, vskip) -> (extV (EvVertFixedEmpty(debug_margins, vskip)), footnoteacc) | ImVertFrame(pads, deco, wid, imvblst) -> let (evvblst, footnotelst) = embed_page_info_vert pbinfo imvblst in let evvb = EvVertFrame(pads, pbinfo, deco, wid, evvblst) in (extV evvb, appendF footnotelst) | ImVertHookPageBreak(hookf) -> let evvb = EvVertHookPageBreak(hookf) in (extV evvb, footnoteacc) ) (Alist.empty, Alist.empty) in (Alist.to_list evvbacc, Alist.to_list footnoteacc)
null
https://raw.githubusercontent.com/gfngfn/SATySFi/9dbd61df0ab05943b3394830c371e927df45251a/src/backend/pageInfo.ml
ocaml
open HorzBox -- ' embed_page_info pbinfo imhblst ' associates ' ImHorzHookPageBreak ( ... ) ' in ' imhblst ' with ' pbinfo ' , and returns footnotes in ' imhblst ' -- 'embed_page_info pbinfo imhblst' associates 'ImHorzHookPageBreak(...)' in 'imhblst' with 'pbinfo', and returns footnotes in 'imhblst' -- *) let rec embed_page_info (pbinfo : page_break_info) (imhblst : intermediate_horz_box list) : evaled_horz_box list * (intermediate_vert_box list) list = let iter = embed_page_info pbinfo in let (evhbacc, footnoteacc) = imhblst |> List.fold_left (fun (evhbacc, footnoteacc) imhb -> let extH = Alist.extend evhbacc in let appendF = Alist.append footnoteacc in let ext evhb = (extH evhb, footnoteacc) in match imhb with | ImHorz(evhb) -> ext evhb | ImHorzRising(wid, hgt, dpt, lenrising, imhblst) -> let (evhblst, footnotelst) = iter imhblst in let evhb = (wid, EvHorzRising(hgt, dpt, lenrising, evhblst)) in (extH evhb, appendF footnotelst) | ImHorzFrame(ratios, wid, hgt, dpt, deco, imhbs) -> let (evhbs, footnotelst) = iter imhbs in let evhb = (wid, EvHorzFrame(ratios, hgt, dpt, deco, evhbs)) in (extH evhb, appendF footnotelst) | ImHorzInlineTabular(wid, hgt, dpt, imtabular, widlst, lenlst, rulesf) -> let (evrowlst, footnotelst) = embed_page_info_to_tabular pbinfo imtabular in ext (wid, EvHorzInlineTabular(hgt, dpt, evrowlst, widlst, lenlst, rulesf)) | ImHorzEmbeddedVert(wid, hgt, dpt, imvblst) -> let (evvblst, footnotelst) = embed_page_info_vert pbinfo imvblst in let evhb = (wid, EvHorzEmbeddedVert(hgt, dpt, evvblst)) in (extH evhb, appendF footnotelst) | ImHorzHookPageBreak(hookf) -> ext (Length.zero, EvHorzHookPageBreak(pbinfo, hookf)) | ImHorzInlineGraphics(wid, hgt, dpt, graphics) -> ext (wid, EvHorzInlineGraphics(hgt, dpt, graphics)) | ImHorzFootnote(imvblst) -> (evhbacc, Alist.extend footnoteacc imvblst) ) (Alist.empty, Alist.empty) in (Alist.to_list evhbacc, Alist.to_list footnoteacc) and embed_page_info_to_tabular (pbinfo : page_break_info) (imtabular : intermediate_row list) : evaled_row list * (intermediate_vert_box list) list = let (evrowacc, footnoteacc) = imtabular |> List.fold_left (fun (evrowacc, footnoteacc) (widtotal, imcelllst) -> let (evcellacc, footnoteacc) = imcelllst |> List.fold_left (fun (evcellacc, footnoteacc) imcell -> let extC = Alist.extend evcellacc in let appendF = Alist.append footnoteacc in match imcell with | ImEmptyCell(len) -> (extC (EvEmptyCell(len)), footnoteacc) | ImNormalCell(ratios, info, imhblst) -> let (evhblst, footnotelst) = embed_page_info pbinfo imhblst in let evcell = EvNormalCell(ratios, info, evhblst) in (extC evcell, appendF footnotelst) | ImMultiCell(ratios, info, imhblst) -> let (evhblst, footnotelst) = embed_page_info pbinfo imhblst in let evcell = EvMultiCell(ratios, info, evhblst) in (extC evcell, appendF footnotelst) ) (Alist.empty, footnoteacc) in (Alist.extend evrowacc (widtotal, Alist.to_list evcellacc), footnoteacc) ) (Alist.empty, Alist.empty) in (Alist.to_list evrowacc, Alist.to_list footnoteacc) and embed_page_info_vert (pbinfo : page_break_info) (imvblst : intermediate_vert_box list) : evaled_vert_box list * (intermediate_vert_box list) list = let (evvbacc, footnoteacc) = imvblst |> List.fold_left (fun (evvbacc, footnoteacc) imvb -> let extV = Alist.extend evvbacc in let appendF = Alist.append footnoteacc in match imvb with | ImVertLine(ratios, hgt, dpt, imhbs) -> let (imvbs, footnotelst) = embed_page_info pbinfo imhbs in let evvb = EvVertLine(ratios, hgt, dpt, imvbs) in (extV evvb, appendF footnotelst) | ImVertFixedEmpty(debug_margins, vskip) -> (extV (EvVertFixedEmpty(debug_margins, vskip)), footnoteacc) | ImVertFrame(pads, deco, wid, imvblst) -> let (evvblst, footnotelst) = embed_page_info_vert pbinfo imvblst in let evvb = EvVertFrame(pads, pbinfo, deco, wid, evvblst) in (extV evvb, appendF footnotelst) | ImVertHookPageBreak(hookf) -> let evvb = EvVertHookPageBreak(hookf) in (extV evvb, footnoteacc) ) (Alist.empty, Alist.empty) in (Alist.to_list evvbacc, Alist.to_list footnoteacc)
74b334491580df9db2aaac513416673baac7081c155aaafdb65672ddb5e59335
biocad/servant-openapi3
Todo.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} # LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeOperators #-} module Todo where import Control.Lens import Data.Aeson import Data.Aeson.Encode.Pretty (encodePretty) import qualified Data.ByteString.Lazy.Char8 as BL8 import Data.OpenApi hiding (Server) import Data.Proxy import Data.Text (Text) import Data.Time (UTCTime (..), fromGregorian) import Data.Typeable (Typeable) import GHC.Generics import Servant import Servant.OpenApi todoAPI :: Proxy TodoAPI todoAPI = Proxy -- | The API of a Todo service. type TodoAPI = "todo" :> Get '[JSON] [Todo] :<|> "todo" :> ReqBody '[JSON] Todo :> Post '[JSON] TodoId :<|> "todo" :> Capture "id" TodoId :> Get '[JSON] Todo :<|> "todo" :> Capture "id" TodoId :> ReqBody '[JSON] Todo :> Put '[JSON] TodoId -- | API for serving @swagger.json@. type SwaggerAPI = "swagger.json" :> Get '[JSON] OpenApi -- | Combined API of a Todo service with Swagger documentation. type API = SwaggerAPI :<|> TodoAPI | A single Todo entry . data Todo = Todo { created :: UTCTime -- ^ Creation datetime. , summary :: Text -- ^ Task summary. } deriving (Show, Generic, Typeable) | A unique Todo entry ID . newtype TodoId = TodoId Int deriving (Show, Generic, Typeable, ToJSON, FromHttpApiData) instance ToJSON Todo instance FromJSON Todo instance ToSchema Todo where declareNamedSchema proxy = genericDeclareNamedSchema defaultSchemaOptions proxy & mapped.schema.description ?~ "This is some real Todo right here" & mapped.schema.example ?~ toJSON (Todo (UTCTime (fromGregorian 2015 12 31) 0) "get milk") instance ToParamSchema TodoId instance ToSchema TodoId | Swagger spec for Todo API . todoSwagger :: OpenApi todoSwagger = toOpenApi todoAPI & info.title .~ "Todo API" & info.version .~ "1.0" & info.description ?~ "This is an API that tests swagger integration" & info.license ?~ ("MIT" & url ?~ URL "") | Combined server of a service with Swagger documentation . server :: Server API server = return todoSwagger :<|> error "not implemented" | Output generated @swagger.json@ file for the @'TodoAPI'@. writeSwaggerJSON :: IO () writeSwaggerJSON = BL8.writeFile "example/swagger.json" (encodePretty todoSwagger)
null
https://raw.githubusercontent.com/biocad/servant-openapi3/5eec55e6d0b091f8267060900d25ddcfad5df7a3/example/src/Todo.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE DeriveDataTypeable # # LANGUAGE DeriveGeneric # # LANGUAGE OverloadedStrings # # LANGUAGE TypeOperators # | The API of a Todo service. | API for serving @swagger.json@. | Combined API of a Todo service with Swagger documentation. ^ Creation datetime. ^ Task summary.
# LANGUAGE GeneralizedNewtypeDeriving # module Todo where import Control.Lens import Data.Aeson import Data.Aeson.Encode.Pretty (encodePretty) import qualified Data.ByteString.Lazy.Char8 as BL8 import Data.OpenApi hiding (Server) import Data.Proxy import Data.Text (Text) import Data.Time (UTCTime (..), fromGregorian) import Data.Typeable (Typeable) import GHC.Generics import Servant import Servant.OpenApi todoAPI :: Proxy TodoAPI todoAPI = Proxy type TodoAPI = "todo" :> Get '[JSON] [Todo] :<|> "todo" :> ReqBody '[JSON] Todo :> Post '[JSON] TodoId :<|> "todo" :> Capture "id" TodoId :> Get '[JSON] Todo :<|> "todo" :> Capture "id" TodoId :> ReqBody '[JSON] Todo :> Put '[JSON] TodoId type SwaggerAPI = "swagger.json" :> Get '[JSON] OpenApi type API = SwaggerAPI :<|> TodoAPI | A single Todo entry . data Todo = Todo } deriving (Show, Generic, Typeable) | A unique Todo entry ID . newtype TodoId = TodoId Int deriving (Show, Generic, Typeable, ToJSON, FromHttpApiData) instance ToJSON Todo instance FromJSON Todo instance ToSchema Todo where declareNamedSchema proxy = genericDeclareNamedSchema defaultSchemaOptions proxy & mapped.schema.description ?~ "This is some real Todo right here" & mapped.schema.example ?~ toJSON (Todo (UTCTime (fromGregorian 2015 12 31) 0) "get milk") instance ToParamSchema TodoId instance ToSchema TodoId | Swagger spec for Todo API . todoSwagger :: OpenApi todoSwagger = toOpenApi todoAPI & info.title .~ "Todo API" & info.version .~ "1.0" & info.description ?~ "This is an API that tests swagger integration" & info.license ?~ ("MIT" & url ?~ URL "") | Combined server of a service with Swagger documentation . server :: Server API server = return todoSwagger :<|> error "not implemented" | Output generated @swagger.json@ file for the @'TodoAPI'@. writeSwaggerJSON :: IO () writeSwaggerJSON = BL8.writeFile "example/swagger.json" (encodePretty todoSwagger)
cfb074f3cb61de5e6b39689668389f05d37afe74cd8668aa9ad352dec1104a3d
2600hz/kazoo
pqc_cb_phone_numbers.erl
%%%----------------------------------------------------------------------------- ( C ) 2010 - 2020 , 2600Hz %%% @doc @author %%% This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %%% %%% @end %%%----------------------------------------------------------------------------- -module(pqc_cb_phone_numbers). -behaviour(proper_statem). Crossbar API test functions -export([summary/2 ,list_number/3 ,cleanup_numbers/2 ,add_number/3 ,activate_number/3 ,remove_number/3 ]). -export([command/1 ,initial_state/0 ,next_state/3 ,postcondition/3 ,precondition/2 ,correct/0 ,correct_parallel/0 ]). -export([seq/0 ,cleanup/0 ]). -include_lib("proper/include/proper.hrl"). -include("kazoo_proper.hrl"). -define(ACCOUNT_NAMES, [<<"accountone">>]). -define(PHONE_NUMBERS, [<<"+12345678901">>]). -spec cleanup_numbers(pqc_cb_api:state(), kz_term:ne_binaries()) -> 'ok'. cleanup_numbers(_API, Numbers) -> _ = knm_ops:delete(Numbers, [{'auth_by', <<"system">>}]), 'ok'. -spec summary(pqc_cb_api:state(), kz_term:ne_binary()) -> pqc_cb_api:response(). summary(API, AccountId) -> pqc_cb_crud:summary(API, numbers_url(AccountId)). -spec list_number(pqc_cb_api:state(), kz_term:api_ne_binary(), kz_term:ne_binary()) -> pqc_cb_api:response(). list_number(_API, 'undefined', _Number) -> ?FAILED_RESPONSE; list_number(API, AccountId, Number) -> URL = number_url(AccountId, Number), RequestHeaders = pqc_cb_api:request_headers(API), Expectations = [#expectation{response_codes = [200, 404]}], pqc_cb_api:make_request(Expectations ,fun kz_http:get/2 ,URL ,RequestHeaders ). -spec add_number(pqc_cb_api:state(), kz_term:api_ne_binary(), kz_term:ne_binary()) -> pqc_cb_api:response(). add_number(_API, 'undefined', _Number) -> ?FAILED_RESPONSE; add_number(API, AccountId, Number) -> add_number(API, AccountId, Number, kz_json:new()). -spec add_number(pqc_cb_api:state(), kz_term:api_ne_binary(), kz_term:ne_binary(), kz_json:object()) -> pqc_cb_api:response(). add_number(API, AccountId, Number, RequestData) -> URL = number_url(AccountId, Number), RequestHeaders = pqc_cb_api:request_headers(API), RequestEnvelope = pqc_cb_api:create_envelope(RequestData ,kz_json:from_list([{<<"accept_charges">>, 'true'}]) ), Expectations = [#expectation{response_codes = [201, 404, 409]}], pqc_cb_api:make_request(Expectations ,fun kz_http:put/3 ,URL ,RequestHeaders ,kz_json:encode(RequestEnvelope) ). -spec remove_number(pqc_cb_api:state(), kz_term:api_ne_binary(), kz_term:ne_binary()) -> pqc_cb_api:response(). remove_number(_API, 'undefined', _Number) -> ?FAILED_RESPONSE; remove_number(API, AccountId, Number) -> URL = number_url(AccountId, Number), RequestHeaders = pqc_cb_api:request_headers(API), Expectations = [#expectation{response_codes = [200, 404]}], pqc_cb_api:make_request(Expectations ,fun kz_http:delete/2 ,URL ,RequestHeaders ). -spec activate_number(pqc_cb_api:state(), kz_term:api_ne_binary(), kz_term:ne_binary()) -> pqc_cb_api:response(). activate_number(_API, 'undefined', _Number) -> ?FAILED_RESPONSE; activate_number(API, AccountId, Number) -> URL = number_url(AccountId, Number, "activate"), RequestHeaders = pqc_cb_api:request_headers(API), RequestEnvelope = pqc_cb_api:create_envelope(kz_json:new(), kz_json:from_list([{<<"accept_charges">>, 'true'}])), Expectations = [#expectation{response_codes = [201, 404, 500]}], pqc_cb_api:make_request(Expectations ,fun kz_http:put/3 ,URL ,RequestHeaders ,kz_json:encode(RequestEnvelope) ). -spec numbers_url(kz_term:ne_binary()) -> string(). numbers_url(AccountId) -> string:join([pqc_cb_accounts:account_url(AccountId), "phone_numbers"] ,"/" ). -spec number_url(kz_term:ne_binary(), kz_term:ne_binary()) -> string(). number_url(AccountId, Number) -> string:join([pqc_cb_accounts:account_url(AccountId) ,"phone_numbers", kz_term:to_list(kz_http_util:urlencode(Number)) ] ,"/" ). -spec number_url(kz_term:ne_binary(), kz_term:ne_binary(), string()) -> string(). number_url(AccountId, Number, PathToken) -> string:join([pqc_cb_accounts:account_url(AccountId) ,"phone_numbers", kz_term:to_list(kz_http_util:urlencode(Number)) ,PathToken ] ,"/" ). -spec correct() -> any(). correct() -> ?FORALL(Cmds ,commands(?MODULE) ,?TRAPEXIT( begin timer:sleep(1000), {History, Model, Result} = run_commands(?MODULE, Cmds), pqc_cb_accounts:cleanup_accounts(pqc_kazoo_model:api(Model), ?ACCOUNT_NAMES), ?WHENFAIL(io:format("Final Model : ~p~nFailing Cmds: ~p~n" ,[pqc_kazoo_model:pp(Model), zip(Cmds, History)] ) ,aggregate(command_names(Cmds), Result =:= 'ok') ) end ) ). -spec correct_parallel() -> any(). correct_parallel() -> ?FORALL(Cmds ,parallel_commands(?MODULE) ,?TRAPEXIT( begin {Sequential, Parallel, Result} = run_parallel_commands(?MODULE, Cmds), pqc_cb_accounts:cleanup_accounts(?ACCOUNT_NAMES), ?WHENFAIL(io:format("S: ~p~nP: ~p~n", [Sequential, Parallel]) ,aggregate(command_names(Cmds), Result =:= 'ok') ) end ) ). -spec initial_state() -> pqc_kazoo_model:model(). initial_state() -> API = pqc_cb_api:authenticate(), pqc_cb_accounts:cleanup_accounts(API, ?ACCOUNT_NAMES), pqc_kazoo_model:new(API). -spec command(any()) -> proper_types:type(). command(Model) -> command(Model, pqc_kazoo_model:has_accounts(Model)). -spec command(any(), boolean()) -> proper_types:type(). command(Model, 'false') -> pqc_cb_accounts:command(Model, name()); command(Model, 'true') -> API = pqc_kazoo_model:api(Model), AccountId = pqc_cb_accounts:symbolic_account_id(Model, name()), oneof([{'call', ?MODULE, 'list_number', [API, AccountId, phone_number()]} ,{'call', ?MODULE, 'add_number', [API, AccountId, phone_number()]} ,{'call', ?MODULE, 'activate_number', [API, AccountId, phone_number()]} ,{'call', ?MODULE, 'remove_number', [API, AccountId, phone_number()]} ,pqc_cb_accounts:command(Model, name()) %% ,{'call', ?MODULE, 'reserve_number', [API, name(), phone_number()]} ]). name() -> elements(?ACCOUNT_NAMES). phone_number() -> elements(?PHONE_NUMBERS). -spec next_state(pqc_kazoo_model:model(), any(), any()) -> pqc_kazoo_model:model(). next_state(Model, APIResp, {'call', _, 'create_account', _Args}=Call) -> pqc_cb_accounts:next_state(Model, APIResp, Call); next_state(Model ,APIResp ,{'call', _, 'add_number', [_API, AccountId, Number]} ) -> pqc_util:transition_if(Model ,[{fun pqc_kazoo_model:does_account_exist/2, [AccountId]} ,{fun pqc_kazoo_model:is_number_missing_in_account/3, [AccountId, Number]} ,{fun pqc_kazoo_model:add_number_to_account/4, [AccountId, Number, APIResp]} ] ); next_state(Model ,_APIResp ,{'call', _, 'remove_number', [_API, AccountId, Number]} ) -> pqc_util:transition_if(Model ,[{fun pqc_kazoo_model:does_account_exist/2, [AccountId]} ,{fun pqc_kazoo_model:is_number_in_account/3, [AccountId, Number]} ,{fun pqc_kazoo_model:remove_number_from_account/2, [Number]} ] ); next_state(Model ,APIResp ,{'call', _, 'activate_number', [_API, AccountId, Number]} ) -> pqc_util:transition_if(Model ,[{fun pqc_kazoo_model:does_account_exist/2, [AccountId]} ,{fun pqc_kazoo_model:is_number_in_account/3, [AccountId, Number]} ,{fun pqc_kazoo_model:transition_number_state/3, [Number, APIResp]} ] ); next_state(Model ,_APIResp ,{'call', _, 'list_number', [_API, _AccountId, _Number]} ) -> Model. -spec postcondition(pqc_kazoo_model:model(), any(), any()) -> boolean(). postcondition(Model ,{'call', _, 'create_account', [_API, _Name]}=Call ,APIResult ) -> pqc_cb_accounts:postcondition(Model, Call, APIResult); postcondition(Model ,{'call', _, 'list_number', [_API, AccountId, Number]} ,APIResult ) -> case pqc_kazoo_model:does_account_exist(Model, AccountId) of 'false' -> ?FAILED_RESPONSE =:= APIResult; 'true' -> case pqc_kazoo_model:number_data(Model, Number) of 'undefined' -> 404 =:= pqc_cb_response:error_code(APIResult); #{'number_state' := NumberState ,'account_id' := AccountId } -> NumberState =:= pqc_cb_response:number_state(APIResult); _N -> 404 =:= pqc_cb_response:error_code(APIResult) end end; postcondition(Model ,{'call', _, 'add_number', [_API, AccountId, Number]} ,APIResult ) -> case pqc_kazoo_model:does_account_exist(Model, AccountId) of 'false' -> ?FAILED_RESPONSE =:= APIResult; 'true' -> case pqc_kazoo_model:number_data(Model, Number) of #{'account_id' := AccountId ,'number_state' := _CurrentState } -> 409 =:= pqc_cb_response:error_code(APIResult) andalso <<"number_exists">> =:= pqc_cb_response:message(APIResult); #{} -> %% if in another account 409 =:= pqc_cb_response:error_code(APIResult); 'undefined' -> case <<"success">> =:= pqc_cb_response:status(APIResult) of 'true' -> 'reserved' =:= pqc_cb_response:number_state(APIResult); 'false' -> 500 =:= pqc_cb_response:error_code(APIResult) end end end; postcondition(Model ,{'call', _, 'remove_number', [_API, AccountId, Number]} ,APIResult ) -> case pqc_kazoo_model:does_account_exist(Model, AccountId) of 'false' -> ?FAILED_RESPONSE =:= APIResult; 'true' -> case pqc_kazoo_model:number_data(Model, Number) of #{'account_id' := AccountId} -> <<"success">> =:= pqc_cb_response:status(APIResult) andalso 'deleted' =:= pqc_cb_response:number_state(APIResult); #{} -> 404 =:= pqc_cb_response:error_code(APIResult); 'undefined' -> 404 =:= pqc_cb_response:error_code(APIResult) end end; postcondition(Model ,{'call', _, 'activate_number', [_API, AccountId, Number]} ,APIResult ) -> case pqc_kazoo_model:does_account_exist(Model, AccountId) of 'false' -> ?FAILED_RESPONSE =:= APIResult; 'true' -> case pqc_kazoo_model:number_data(Model, Number) of #{'number_state' := NumberState ,'account_id' := AccountId } when 'reserved' =:= NumberState orelse 'in_service' =:= NumberState -> 'in_service' =:= pqc_cb_response:number_state(APIResult); #{} -> <<"error">> =:= pqc_cb_response:status(APIResult); 'undefined' -> 404 =:= pqc_cb_response:error_code(APIResult) end end. -spec precondition(pqc_kazoo_model:model(), any()) -> boolean(). precondition(_Model, _Call) -> 'true'. -spec seq() -> 'ok'. seq() -> _ = init(), seq_kzoo_41(). seq_kzoo_41() -> Model = initial_state(), API = pqc_kazoo_model:api(Model), AccountResp = pqc_cb_accounts:create_account(API, hd(?ACCOUNT_NAMES)), AccountId = kz_json:get_value([<<"data">>, <<"id">>], kz_json:decode(AccountResp)), lager:info("created account ~s", [AccountId]), EmptySummaryResp = summary(API, AccountId), lager:info("empty summary: ~s", [EmptySummaryResp]), 'true' = kz_json:is_empty(kz_json:get_json_value([<<"data">>, <<"numbers">>], kz_json:decode(EmptySummaryResp))), PhoneNumber = hd(?PHONE_NUMBERS), CreateResp = add_number(API, AccountId, PhoneNumber, kz_json:from_list([{<<"carrier_name">>, <<"knm_other">>}])), lager:info("create resp ~p", [CreateResp]), NumberDoc = kz_json:get_json_value(<<"data">>, kz_json:decode(CreateResp)), <<PhoneNumber/binary>> = kz_doc:id(NumberDoc), SummaryResp = summary(API, AccountId), lager:info("summary resp: ~s", [SummaryResp]), SummaryJObj = kz_json:get_json_value([<<"data">>, <<"numbers">>, PhoneNumber], kz_json:decode(SummaryResp)), 'false' = kz_json:is_empty(SummaryJObj), RemoveResp = remove_number(API, AccountId, PhoneNumber), lager:info("removed resp: ~s", [RemoveResp]), EmptyAgainResp = summary(API, AccountId), lager:info("empty again: ~s", [EmptyAgainResp]), EmptyData = kz_json:get_json_value([<<"data">>, <<"numbers">>], kz_json:decode(EmptyAgainResp)), 'true' = kz_json:is_empty(EmptyData), cleanup(API). init() -> _ = kz_data_tracing:clear_all_traces(), _ = [kapps_controller:start_app(App) || App <- ['crossbar'] ], _ = [crossbar_maintenance:start_module(Mod) || Mod <- ['cb_phone_numbers_v2'] ], lager:info("INIT FINISHED"). -spec cleanup() -> any(). cleanup() -> lager:info("CLEANUP ALL THE THINGS"), kz_data_tracing:clear_all_traces(), cleanup(pqc_cb_api:authenticate()). -spec cleanup(pqc_cb_api:state()) -> any(). cleanup(API) -> lager:info("CLEANUP TIME, EVERYBODY HELPS"), lager:info("~p", [API]), _ = pqc_cb_accounts:cleanup_accounts(API, ?ACCOUNT_NAMES), _D = knm_numbers:delete(?PHONE_NUMBERS, [{'auth_by', pqc_cb_api:auth_account_id(API)}]), lager:info("deleted numbers ~p", [_D]), _ = pqc_cb_api:cleanup(API), 'ok'.
null
https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_proper/src/pqc_cb_phone_numbers.erl
erlang
----------------------------------------------------------------------------- @doc @end ----------------------------------------------------------------------------- ,{'call', ?MODULE, 'reserve_number', [API, name(), phone_number()]} if in another account
( C ) 2010 - 2020 , 2600Hz @author This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. -module(pqc_cb_phone_numbers). -behaviour(proper_statem). Crossbar API test functions -export([summary/2 ,list_number/3 ,cleanup_numbers/2 ,add_number/3 ,activate_number/3 ,remove_number/3 ]). -export([command/1 ,initial_state/0 ,next_state/3 ,postcondition/3 ,precondition/2 ,correct/0 ,correct_parallel/0 ]). -export([seq/0 ,cleanup/0 ]). -include_lib("proper/include/proper.hrl"). -include("kazoo_proper.hrl"). -define(ACCOUNT_NAMES, [<<"accountone">>]). -define(PHONE_NUMBERS, [<<"+12345678901">>]). -spec cleanup_numbers(pqc_cb_api:state(), kz_term:ne_binaries()) -> 'ok'. cleanup_numbers(_API, Numbers) -> _ = knm_ops:delete(Numbers, [{'auth_by', <<"system">>}]), 'ok'. -spec summary(pqc_cb_api:state(), kz_term:ne_binary()) -> pqc_cb_api:response(). summary(API, AccountId) -> pqc_cb_crud:summary(API, numbers_url(AccountId)). -spec list_number(pqc_cb_api:state(), kz_term:api_ne_binary(), kz_term:ne_binary()) -> pqc_cb_api:response(). list_number(_API, 'undefined', _Number) -> ?FAILED_RESPONSE; list_number(API, AccountId, Number) -> URL = number_url(AccountId, Number), RequestHeaders = pqc_cb_api:request_headers(API), Expectations = [#expectation{response_codes = [200, 404]}], pqc_cb_api:make_request(Expectations ,fun kz_http:get/2 ,URL ,RequestHeaders ). -spec add_number(pqc_cb_api:state(), kz_term:api_ne_binary(), kz_term:ne_binary()) -> pqc_cb_api:response(). add_number(_API, 'undefined', _Number) -> ?FAILED_RESPONSE; add_number(API, AccountId, Number) -> add_number(API, AccountId, Number, kz_json:new()). -spec add_number(pqc_cb_api:state(), kz_term:api_ne_binary(), kz_term:ne_binary(), kz_json:object()) -> pqc_cb_api:response(). add_number(API, AccountId, Number, RequestData) -> URL = number_url(AccountId, Number), RequestHeaders = pqc_cb_api:request_headers(API), RequestEnvelope = pqc_cb_api:create_envelope(RequestData ,kz_json:from_list([{<<"accept_charges">>, 'true'}]) ), Expectations = [#expectation{response_codes = [201, 404, 409]}], pqc_cb_api:make_request(Expectations ,fun kz_http:put/3 ,URL ,RequestHeaders ,kz_json:encode(RequestEnvelope) ). -spec remove_number(pqc_cb_api:state(), kz_term:api_ne_binary(), kz_term:ne_binary()) -> pqc_cb_api:response(). remove_number(_API, 'undefined', _Number) -> ?FAILED_RESPONSE; remove_number(API, AccountId, Number) -> URL = number_url(AccountId, Number), RequestHeaders = pqc_cb_api:request_headers(API), Expectations = [#expectation{response_codes = [200, 404]}], pqc_cb_api:make_request(Expectations ,fun kz_http:delete/2 ,URL ,RequestHeaders ). -spec activate_number(pqc_cb_api:state(), kz_term:api_ne_binary(), kz_term:ne_binary()) -> pqc_cb_api:response(). activate_number(_API, 'undefined', _Number) -> ?FAILED_RESPONSE; activate_number(API, AccountId, Number) -> URL = number_url(AccountId, Number, "activate"), RequestHeaders = pqc_cb_api:request_headers(API), RequestEnvelope = pqc_cb_api:create_envelope(kz_json:new(), kz_json:from_list([{<<"accept_charges">>, 'true'}])), Expectations = [#expectation{response_codes = [201, 404, 500]}], pqc_cb_api:make_request(Expectations ,fun kz_http:put/3 ,URL ,RequestHeaders ,kz_json:encode(RequestEnvelope) ). -spec numbers_url(kz_term:ne_binary()) -> string(). numbers_url(AccountId) -> string:join([pqc_cb_accounts:account_url(AccountId), "phone_numbers"] ,"/" ). -spec number_url(kz_term:ne_binary(), kz_term:ne_binary()) -> string(). number_url(AccountId, Number) -> string:join([pqc_cb_accounts:account_url(AccountId) ,"phone_numbers", kz_term:to_list(kz_http_util:urlencode(Number)) ] ,"/" ). -spec number_url(kz_term:ne_binary(), kz_term:ne_binary(), string()) -> string(). number_url(AccountId, Number, PathToken) -> string:join([pqc_cb_accounts:account_url(AccountId) ,"phone_numbers", kz_term:to_list(kz_http_util:urlencode(Number)) ,PathToken ] ,"/" ). -spec correct() -> any(). correct() -> ?FORALL(Cmds ,commands(?MODULE) ,?TRAPEXIT( begin timer:sleep(1000), {History, Model, Result} = run_commands(?MODULE, Cmds), pqc_cb_accounts:cleanup_accounts(pqc_kazoo_model:api(Model), ?ACCOUNT_NAMES), ?WHENFAIL(io:format("Final Model : ~p~nFailing Cmds: ~p~n" ,[pqc_kazoo_model:pp(Model), zip(Cmds, History)] ) ,aggregate(command_names(Cmds), Result =:= 'ok') ) end ) ). -spec correct_parallel() -> any(). correct_parallel() -> ?FORALL(Cmds ,parallel_commands(?MODULE) ,?TRAPEXIT( begin {Sequential, Parallel, Result} = run_parallel_commands(?MODULE, Cmds), pqc_cb_accounts:cleanup_accounts(?ACCOUNT_NAMES), ?WHENFAIL(io:format("S: ~p~nP: ~p~n", [Sequential, Parallel]) ,aggregate(command_names(Cmds), Result =:= 'ok') ) end ) ). -spec initial_state() -> pqc_kazoo_model:model(). initial_state() -> API = pqc_cb_api:authenticate(), pqc_cb_accounts:cleanup_accounts(API, ?ACCOUNT_NAMES), pqc_kazoo_model:new(API). -spec command(any()) -> proper_types:type(). command(Model) -> command(Model, pqc_kazoo_model:has_accounts(Model)). -spec command(any(), boolean()) -> proper_types:type(). command(Model, 'false') -> pqc_cb_accounts:command(Model, name()); command(Model, 'true') -> API = pqc_kazoo_model:api(Model), AccountId = pqc_cb_accounts:symbolic_account_id(Model, name()), oneof([{'call', ?MODULE, 'list_number', [API, AccountId, phone_number()]} ,{'call', ?MODULE, 'add_number', [API, AccountId, phone_number()]} ,{'call', ?MODULE, 'activate_number', [API, AccountId, phone_number()]} ,{'call', ?MODULE, 'remove_number', [API, AccountId, phone_number()]} ,pqc_cb_accounts:command(Model, name()) ]). name() -> elements(?ACCOUNT_NAMES). phone_number() -> elements(?PHONE_NUMBERS). -spec next_state(pqc_kazoo_model:model(), any(), any()) -> pqc_kazoo_model:model(). next_state(Model, APIResp, {'call', _, 'create_account', _Args}=Call) -> pqc_cb_accounts:next_state(Model, APIResp, Call); next_state(Model ,APIResp ,{'call', _, 'add_number', [_API, AccountId, Number]} ) -> pqc_util:transition_if(Model ,[{fun pqc_kazoo_model:does_account_exist/2, [AccountId]} ,{fun pqc_kazoo_model:is_number_missing_in_account/3, [AccountId, Number]} ,{fun pqc_kazoo_model:add_number_to_account/4, [AccountId, Number, APIResp]} ] ); next_state(Model ,_APIResp ,{'call', _, 'remove_number', [_API, AccountId, Number]} ) -> pqc_util:transition_if(Model ,[{fun pqc_kazoo_model:does_account_exist/2, [AccountId]} ,{fun pqc_kazoo_model:is_number_in_account/3, [AccountId, Number]} ,{fun pqc_kazoo_model:remove_number_from_account/2, [Number]} ] ); next_state(Model ,APIResp ,{'call', _, 'activate_number', [_API, AccountId, Number]} ) -> pqc_util:transition_if(Model ,[{fun pqc_kazoo_model:does_account_exist/2, [AccountId]} ,{fun pqc_kazoo_model:is_number_in_account/3, [AccountId, Number]} ,{fun pqc_kazoo_model:transition_number_state/3, [Number, APIResp]} ] ); next_state(Model ,_APIResp ,{'call', _, 'list_number', [_API, _AccountId, _Number]} ) -> Model. -spec postcondition(pqc_kazoo_model:model(), any(), any()) -> boolean(). postcondition(Model ,{'call', _, 'create_account', [_API, _Name]}=Call ,APIResult ) -> pqc_cb_accounts:postcondition(Model, Call, APIResult); postcondition(Model ,{'call', _, 'list_number', [_API, AccountId, Number]} ,APIResult ) -> case pqc_kazoo_model:does_account_exist(Model, AccountId) of 'false' -> ?FAILED_RESPONSE =:= APIResult; 'true' -> case pqc_kazoo_model:number_data(Model, Number) of 'undefined' -> 404 =:= pqc_cb_response:error_code(APIResult); #{'number_state' := NumberState ,'account_id' := AccountId } -> NumberState =:= pqc_cb_response:number_state(APIResult); _N -> 404 =:= pqc_cb_response:error_code(APIResult) end end; postcondition(Model ,{'call', _, 'add_number', [_API, AccountId, Number]} ,APIResult ) -> case pqc_kazoo_model:does_account_exist(Model, AccountId) of 'false' -> ?FAILED_RESPONSE =:= APIResult; 'true' -> case pqc_kazoo_model:number_data(Model, Number) of #{'account_id' := AccountId ,'number_state' := _CurrentState } -> 409 =:= pqc_cb_response:error_code(APIResult) andalso <<"number_exists">> =:= pqc_cb_response:message(APIResult); #{} -> 409 =:= pqc_cb_response:error_code(APIResult); 'undefined' -> case <<"success">> =:= pqc_cb_response:status(APIResult) of 'true' -> 'reserved' =:= pqc_cb_response:number_state(APIResult); 'false' -> 500 =:= pqc_cb_response:error_code(APIResult) end end end; postcondition(Model ,{'call', _, 'remove_number', [_API, AccountId, Number]} ,APIResult ) -> case pqc_kazoo_model:does_account_exist(Model, AccountId) of 'false' -> ?FAILED_RESPONSE =:= APIResult; 'true' -> case pqc_kazoo_model:number_data(Model, Number) of #{'account_id' := AccountId} -> <<"success">> =:= pqc_cb_response:status(APIResult) andalso 'deleted' =:= pqc_cb_response:number_state(APIResult); #{} -> 404 =:= pqc_cb_response:error_code(APIResult); 'undefined' -> 404 =:= pqc_cb_response:error_code(APIResult) end end; postcondition(Model ,{'call', _, 'activate_number', [_API, AccountId, Number]} ,APIResult ) -> case pqc_kazoo_model:does_account_exist(Model, AccountId) of 'false' -> ?FAILED_RESPONSE =:= APIResult; 'true' -> case pqc_kazoo_model:number_data(Model, Number) of #{'number_state' := NumberState ,'account_id' := AccountId } when 'reserved' =:= NumberState orelse 'in_service' =:= NumberState -> 'in_service' =:= pqc_cb_response:number_state(APIResult); #{} -> <<"error">> =:= pqc_cb_response:status(APIResult); 'undefined' -> 404 =:= pqc_cb_response:error_code(APIResult) end end. -spec precondition(pqc_kazoo_model:model(), any()) -> boolean(). precondition(_Model, _Call) -> 'true'. -spec seq() -> 'ok'. seq() -> _ = init(), seq_kzoo_41(). seq_kzoo_41() -> Model = initial_state(), API = pqc_kazoo_model:api(Model), AccountResp = pqc_cb_accounts:create_account(API, hd(?ACCOUNT_NAMES)), AccountId = kz_json:get_value([<<"data">>, <<"id">>], kz_json:decode(AccountResp)), lager:info("created account ~s", [AccountId]), EmptySummaryResp = summary(API, AccountId), lager:info("empty summary: ~s", [EmptySummaryResp]), 'true' = kz_json:is_empty(kz_json:get_json_value([<<"data">>, <<"numbers">>], kz_json:decode(EmptySummaryResp))), PhoneNumber = hd(?PHONE_NUMBERS), CreateResp = add_number(API, AccountId, PhoneNumber, kz_json:from_list([{<<"carrier_name">>, <<"knm_other">>}])), lager:info("create resp ~p", [CreateResp]), NumberDoc = kz_json:get_json_value(<<"data">>, kz_json:decode(CreateResp)), <<PhoneNumber/binary>> = kz_doc:id(NumberDoc), SummaryResp = summary(API, AccountId), lager:info("summary resp: ~s", [SummaryResp]), SummaryJObj = kz_json:get_json_value([<<"data">>, <<"numbers">>, PhoneNumber], kz_json:decode(SummaryResp)), 'false' = kz_json:is_empty(SummaryJObj), RemoveResp = remove_number(API, AccountId, PhoneNumber), lager:info("removed resp: ~s", [RemoveResp]), EmptyAgainResp = summary(API, AccountId), lager:info("empty again: ~s", [EmptyAgainResp]), EmptyData = kz_json:get_json_value([<<"data">>, <<"numbers">>], kz_json:decode(EmptyAgainResp)), 'true' = kz_json:is_empty(EmptyData), cleanup(API). init() -> _ = kz_data_tracing:clear_all_traces(), _ = [kapps_controller:start_app(App) || App <- ['crossbar'] ], _ = [crossbar_maintenance:start_module(Mod) || Mod <- ['cb_phone_numbers_v2'] ], lager:info("INIT FINISHED"). -spec cleanup() -> any(). cleanup() -> lager:info("CLEANUP ALL THE THINGS"), kz_data_tracing:clear_all_traces(), cleanup(pqc_cb_api:authenticate()). -spec cleanup(pqc_cb_api:state()) -> any(). cleanup(API) -> lager:info("CLEANUP TIME, EVERYBODY HELPS"), lager:info("~p", [API]), _ = pqc_cb_accounts:cleanup_accounts(API, ?ACCOUNT_NAMES), _D = knm_numbers:delete(?PHONE_NUMBERS, [{'auth_by', pqc_cb_api:auth_account_id(API)}]), lager:info("deleted numbers ~p", [_D]), _ = pqc_cb_api:cleanup(API), 'ok'.
02178aba6dbd6dc3e0b1e39e1c883d9c45685a0a6d68be0e9a8c75e2b7bd9864
melisgl/planet-wars
proxy-bot.lisp
(in-package :pw-proxy-bot) (defun connection-refused (&optional arg) (declare (ignore arg)) (pw-util:logmsg "Connection refused. Aborting...~%") (pw-util:exit :status 111)) (defun proxy () (pw-util:with-reckless-exit (pw-util:with-errors-logged (:exit-on-error-p t) (setq pw-util:*verbose* t) (setq pw-util:*log-filename* "proxy-bot.log") (pw-util:logmsg "* ProxyBot started at ~A~%" (pw-util:current-date-time-string)) (pw-util:logmsg "Connecting to real bot at 127.0.0.1:41807...~%") (handler-bind ((connection-refused-error #'connection-refused)) (let ((socket (usocket:socket-connect #+sbcl #(127 0 0 1) #+allegro "localhost" 41807))) (handler-bind ((error (lambda (e) (pw-util:logmsg "ERROR: ~A~%~A~%" e (with-output-to-string (s) (pw-util:backtrace-to-stream s))) (pw-util:exit :recklessly-p t)))) (unwind-protect (loop with stream = (usocket:socket-stream socket) while (peek-char nil *standard-input* nil) for turn from 1 do (pw-util:logmsg "** turn: ~S~%" turn) (pw-util:logmsg "Sending game state...~%") (loop for line = (read-line *standard-input* nil) do (write-line line stream) until (equal line "go") finally (force-output stream)) (pw-util:logmsg "Receiving bot response...~%") (loop for line = (read-line stream nil nil) do (write-line line *standard-output*) until (equal line "go") finally (force-output *standard-output*))) (ignore-errors (usocket:socket-close socket)))))))))
null
https://raw.githubusercontent.com/melisgl/planet-wars/499742d5fb46edeb114f2996b01b0343cf42b76a/src/proxy-bot/proxy-bot.lisp
lisp
(in-package :pw-proxy-bot) (defun connection-refused (&optional arg) (declare (ignore arg)) (pw-util:logmsg "Connection refused. Aborting...~%") (pw-util:exit :status 111)) (defun proxy () (pw-util:with-reckless-exit (pw-util:with-errors-logged (:exit-on-error-p t) (setq pw-util:*verbose* t) (setq pw-util:*log-filename* "proxy-bot.log") (pw-util:logmsg "* ProxyBot started at ~A~%" (pw-util:current-date-time-string)) (pw-util:logmsg "Connecting to real bot at 127.0.0.1:41807...~%") (handler-bind ((connection-refused-error #'connection-refused)) (let ((socket (usocket:socket-connect #+sbcl #(127 0 0 1) #+allegro "localhost" 41807))) (handler-bind ((error (lambda (e) (pw-util:logmsg "ERROR: ~A~%~A~%" e (with-output-to-string (s) (pw-util:backtrace-to-stream s))) (pw-util:exit :recklessly-p t)))) (unwind-protect (loop with stream = (usocket:socket-stream socket) while (peek-char nil *standard-input* nil) for turn from 1 do (pw-util:logmsg "** turn: ~S~%" turn) (pw-util:logmsg "Sending game state...~%") (loop for line = (read-line *standard-input* nil) do (write-line line stream) until (equal line "go") finally (force-output stream)) (pw-util:logmsg "Receiving bot response...~%") (loop for line = (read-line stream nil nil) do (write-line line *standard-output*) until (equal line "go") finally (force-output *standard-output*))) (ignore-errors (usocket:socket-close socket)))))))))
0be524f0511f17e49b592d8c9ad07467565532a3dadc09122c698c5ff5b9d0d4
3b/3bgl-shader
compiler.lisp
(in-package #:3bgl-shaders) ;;; passes ;;; +base pass (expand macros, symbol macros, etc) ;; (possibly combined with next pass, since it probably inherits from ;; walker that does expansion already) ;;; +extract top-level definitions ;;; +inline local functions? ;; has to happen after alpha conversion, since free variables ;; in the local function bodies need to refer to bindings in the ;; scope when the function was defined, as opposed to when it was ;; called ;;; alpha conversion? ;;; (including resolving conflicts between fn/var/etc namespaces?) ;; if possible, it would be nice to leave names unchanged, and ;; rely on on {} for shadowing lexical scopes, but if so, we need ;; to watch out for inlined local closures ;;; convert into some less-cl form? ;;; tree of objects (or just plists)? ;;; constant folding? ;;; (partial) type inference for secondary functions ;; for anything that isn't the main function, we allow parameters ;; and return types to be not fully determined, and later try to ;; generate overloads for any variants actually used after tree shaker ;;; type inference on main function ;;; +tree shaker ;; possibly before any type inference? depends on if we are keeping ;; secondary functions around for multiple compiles (which we probably want to do , for libs and such ) ;;; generate specialized versions of any partially types functions ;;; generate code first pass : expand macros , extract function definitions into environments ;;; (should basically just leave variable definitions/initialization?) (defclass extract-functions (3bgl-glsl::glsl-walker) ()) ;;; list of new functions (used to tell which functions were just ;;; defined and need things like dependencies added and type ;;; inference by later passes) (defvar *new-function-definitions*) (defvar *new-type-definitions*) (defvar *new-global-definitions*) (defvar *function-stages*) (defwalker extract-functions (defun name lambda-list &body body+d) (multiple-value-bind (body declare doc) (alexandria:parse-body body+d :documentation t) (let* ((3bgl-glsl::*current-function* (process-type-declarations-for-scope (add-function name lambda-list nil :declarations declare :docs doc))) (*function-stages* (valid-stages 3bgl-glsl::*current-function*))) (clrhash (bindings-used-by 3bgl-glsl::*current-function*)) (when (boundp '*new-function-definitions*) (pushnew 3bgl-glsl::*current-function* *new-function-definitions*)) (setf (body 3bgl-glsl::*current-function*) (with-lambda-list-vars (3bgl-glsl::*current-function*) (@@ body))) ;; if *function-stages* is NIL, we got bindings that only exist ;; in disjoint sets of stages... (assert *function-stages*) (setf (valid-stages 3bgl-glsl::*current-function*) (alexandria:ensure-list *function-stages*))) nil)) (macrolet ((track-globals (&rest forms) `(progn ,@(loop for form in forms collect `(defwalker extract-functions (,form name &rest rest) (declare (ignore rest)) (prog1 (call-next-method) (when (boundp '*new-global-definitions*) (when (consp name) (setf name (car name))) (assert (get-variable-binding name)) (pushnew (list name (get-variable-binding name)) *new-global-definitions*)))))))) (track-globals defconstant defparameter 3bgl-glsl:defconstant 3bgl-glsl::%defconstant 3bgl-glsl:attribute 3bgl-glsl:uniform 3bgl-glsl:input 3bgl-glsl:output 3bgl-glsl:bind-interface)) (macrolet ((track-types (&rest forms) `(progn ,@(loop for form in forms collect `(defwalker extract-functions (,form name &rest rest) (declare (ignore rest)) (prog1 (call-next-method) (when (boundp '*new-type-definitions*) (pushnew (list name (get-type-binding name)) *new-type-definitions*)))))))) (track-types defstruct)) (defmethod check-stages (interface-binding) (let ((types (loop for (nil sb) on (stage-bindings interface-binding) by #'cddr ;; don't check for conflicts in IN/OUT for now for .iq = (interface-qualifier sb) for iq = (if (consp .iq) (remove-if (lambda (a) (member a '(:in :out))) .iq) (if (member .iq '(:in :out)) nil .iq)) when iq collect (binding sb)))) (unless (or (every (lambda (a) (typep a 'interface-type)) types) (every (lambda (a) (eq a (car types))) (cdr types))) (error "conflicting types for interface binding ~s : ~{~s~^ ~}" (name interface-binding) (remove-duplicates(mapcar 'name types)))))) (defmethod check-slot-stages (slot-access) (labels ((get-interface-bindings (x) (etypecase x ((or slot-access variable-read variable-write array-access) (get-interface-bindings (binding x))) (interface-binding x) (local-variable (return-from check-slot-stages t))))) (let* ((interface-bindings (get-interface-bindings slot-access)) (types (loop for (nil sb) on (stage-bindings interface-bindings) by #'cddr for b = (binding sb) for st = (if (typep b 'interface-type) (find (field slot-access) (bindings b) :key #'name) b) when st collect (value-type st)))) (unless (every (lambda (a) (eq a (car types))) (cdr types)) (error "conflicting types for slot ~s.~s : ~{~s~^ ~}" (name interface-bindings) (field slot-access) (remove-duplicates(mapcar 'name types))))))) (defmethod walk :around (form (walker extract-functions)) (let ((r (call-next-method))) (when (typep r 'slot-access) (check-slot-stages r)) (when (or (typep r 'variable-read) (typep r 'variable-write)) (when (typep (binding r) 'interface-binding) (check-stages (binding r)) (let ((stage-bindings (stage-bindings (binding r)))) (unless (getf stage-bindings t) (let ((stages (loop for s in stage-bindings by #'cddr collect s))) (if (or (eq t *function-stages*) (equalp '(t) *function-stages*)) (setf *function-stages* stages) (setf *function-stages* (intersection *function-stages* stages)))))))) r)) ;;;; tree-shaker ;;; given an entry point, return a list of all functions called by that ;;; entry point, in reverse dependency order (so main entry point last) ;; ;; we also need to declare any aggregate types we use, so we need to ;; mark variable usage, then map those back to structure/interface ;; types and dump those as well ;(defparameter *tree-shaker-live* nil) ;(defparameter *tree-shaker-depth* 0) ;(defparameter *tree-shaker-roots* nil) (defparameter *tree-shaker-hook* (lambda (&rest r) (declare (ignore r)))) (defparameter *tree-shaker-type-hook* (lambda (&rest r) (declare (ignore r)))) (defparameter *tree-shaker-current-object* nil) ;; fixme: rename this stuff, since tree-shaker doesn't use it anymore (defclass tree-shaker () ()) (defmethod walk ((form cons) (walker tree-shaker)) (flet ((w (x) (walk x walker))) (map nil #'w form))) (defmethod walk ((form function-call) (walker tree-shaker)) (when (or (typep (called-function form) 'global-function) (typep (called-function form) 'unknown-function-binding)) (funcall *tree-shaker-hook* (called-function form))) (call-next-method)) (defmethod walk ((form (eql t)) (walker tree-shaker)) ;; for unspecified declared types form) (defmethod walk ((form (eql :*)) (walker tree-shaker)) ;; for unspecified array size form) (defmethod walk ((form concrete-type) (walker tree-shaker)) form) (defmethod walk ((form slot-access) (walker tree-shaker)) (walk (binding form) walker) (call-next-method)) (defmethod walk ((form variable-read) (walker tree-shaker)) (walk (binding form) walker) (call-next-method)) (defmethod walk ((form variable-write) (walker tree-shaker)) (walk (binding form) walker) (call-next-method)) (defmethod walk ((form swizzle-access) (walker tree-shaker)) (walk (binding form) walker) (call-next-method)) (defmethod walk ((form local-variable) (walker tree-shaker)) (walk (value-type form) walker) (walk (declared-type form) walker) (call-next-method)) (defmethod walk ((form binding) (walker tree-shaker)) (walk (declared-type form) walker) (walk (value-type form) walker) (call-next-method)) (defmethod walk ((form constant-binding) (walker tree-shaker)) (funcall *tree-shaker-type-hook* form) (call-next-method)) (defmethod walk ((form interface-binding) (walker tree-shaker)) (funcall *tree-shaker-type-hook* form) (let ((*tree-shaker-current-object* form)) (walk (stage-binding form) walker)) (call-next-method)) (defmethod walk ((form interface-stage-binding) (walker tree-shaker)) (walk (binding form) walker) (call-next-method)) (defmethod walk ((form struct-type) (walker tree-shaker)) (funcall *tree-shaker-type-hook* form) (let ((*tree-shaker-current-object* form)) (walk (bindings form) walker))) (defmethod walk ((form array-type) (walker tree-shaker)) (walk (base-type form) walker) (walk (array-size form) walker)) (defmethod walk ((form for-loop) (walker tree-shaker)) (walk (condition-forms form) walker) (walk (step-forms form) walker) (call-next-method)) ;; todo: rewrite this to use pregenerated dependencies? (defun tree-shaker (root) ;; we assume local functions have been inlined or extracted, and ;; names have been alpha converted as needed, etc already... (let* ((root (get-function-binding root))) (assert root) (reverse (topo-sort-dependencies root #'bindings-used-by)))) ;; add dependencies to specified function-binding-function ;; also add function as a dependent to any functions it depends on? (defun update-dependencies (form) ;; reuse tree-shaker walker, find all functions called and add to list ;; (assert (not (symbolp form))) (let* ((*tree-shaker-current-object* form) (*tree-shaker-hook* (lambda (f) (when (and (not (eq f *tree-shaker-current-object*)) (typep f 'binding-with-dependencies)) (setf (gethash f (bindings-used-by *tree-shaker-current-object*)) f) (setf (gethash *tree-shaker-current-object* (bindings-using f)) *tree-shaker-current-object*)))) (*tree-shaker-type-hook* (lambda (f) (when (and (not (eq f *tree-shaker-current-object*)) (typep f 'binding-with-dependencies)) (setf (gethash f (bindings-used-by *tree-shaker-current-object*)) f) (setf (gethash *tree-shaker-current-object* (bindings-using f)) *tree-shaker-current-object*))))) (walk *tree-shaker-current-object* (make-instance 'tree-shaker)))) (defclass update-calls (3bgl-glsl::glsl-walker) ((modified :initarg :modified :reader modified))) (defmethod walk ((form function-call) (walker update-calls)) (let ((*environment* (argument-environment form))) (setf (arguments form) (mapcar (lambda (x) (walk x walker)) (funcall (expander (called-function form)) (raw-arguments form))))) (call-next-method)) #++ (multiple-value-list (compile-block '((defun foo (a1 b1) (+ a (* 3 (/ b)) 2))) 'foo :vertex)) #++ (multiple-value-list (compile-block '((input position :vec4 :location 0) (defun foo (a1 b1) (+ a (* 3 (/ b)) 2))) 'foo :vertex)) #++ (multiple-value-list (compile-block '((defun foo (a b) (+ a (* 3 (/ b)) 2)) (defparameter *foo-bar* (+ 123 4)) (defconstant +hoge-piyo+ 45) (defmacro bar (c d) `(- ,c ,(+ d 10))) (defun not-called (g) (foo 1 2)) (defun calls-foo (a b) (foo a b)) (defun complicated (a &optional (b 1.0) &key (c 2 cp) (d 3)) (if cp (+ a b c) (+ a b))) (defun main () "do baz stuff" #++(flet ((a (b) (+ 1 b))) (a 2)) (let ((e) (f 1)) (when e (foo 1 2) (bar 2 3)) (if e (calls-foo (foo e 1) (bar f 9)) (complicated (if f (3bgl-glsl::<< f 1) (3bgl-glsl::>> e 1)) (3bgl-glsl::<< 4 +hoge-piyo+) :d 4))))) 'main :vertex)) #++ (multiple-value-list (compile-block '((defun a () (let ((aa 1.0)) (+ aa (b aa) (b 1) (c) (d)))) (defun a2 (a) (+ (b a) (c))) (defun b (bb) (+ (e) (f) bb)) (defun c () (b 2)) (defun d () (f)) (defun e () (d)) (defun f () (+ (g) (h))) (defun g () 1) (defun h () 2)) 'a :vertex)) #++ (3bgl-glsl::generate-stage :fragment 'skybox-shaders::fragment) #++ (print (3bgl-glsl::generate-stage :fragment '3bgl-mesh-shaders::fragment)) #++ (print (3bgl-glsl::generate-stage :geometry '3bgl-mesh-shaders::tsd-geometry))
null
https://raw.githubusercontent.com/3b/3bgl-shader/5dd0207ef2d468e7caca2dd6df07b87fe839df88/compiler.lisp
lisp
passes +base pass (expand macros, symbol macros, etc) (possibly combined with next pass, since it probably inherits from walker that does expansion already) +extract top-level definitions +inline local functions? has to happen after alpha conversion, since free variables in the local function bodies need to refer to bindings in the scope when the function was defined, as opposed to when it was called alpha conversion? (including resolving conflicts between fn/var/etc namespaces?) if possible, it would be nice to leave names unchanged, and rely on on {} for shadowing lexical scopes, but if so, we need to watch out for inlined local closures convert into some less-cl form? tree of objects (or just plists)? constant folding? (partial) type inference for secondary functions for anything that isn't the main function, we allow parameters and return types to be not fully determined, and later try to generate overloads for any variants actually used after tree shaker type inference on main function +tree shaker possibly before any type inference? depends on if we are keeping secondary functions around for multiple compiles (which we probably generate specialized versions of any partially types functions generate code (should basically just leave variable definitions/initialization?) list of new functions (used to tell which functions were just defined and need things like dependencies added and type inference by later passes) if *function-stages* is NIL, we got bindings that only exist in disjoint sets of stages... don't check for conflicts in IN/OUT for now tree-shaker given an entry point, return a list of all functions called by that entry point, in reverse dependency order (so main entry point last) we also need to declare any aggregate types we use, so we need to mark variable usage, then map those back to structure/interface types and dump those as well (defparameter *tree-shaker-live* nil) (defparameter *tree-shaker-depth* 0) (defparameter *tree-shaker-roots* nil) fixme: rename this stuff, since tree-shaker doesn't use it anymore for unspecified declared types for unspecified array size todo: rewrite this to use pregenerated dependencies? we assume local functions have been inlined or extracted, and names have been alpha converted as needed, etc already... add dependencies to specified function-binding-function also add function as a dependent to any functions it depends on? reuse tree-shaker walker, find all functions called and add to list
(in-package #:3bgl-shaders) want to do , for libs and such ) first pass : expand macros , extract function definitions into environments (defclass extract-functions (3bgl-glsl::glsl-walker) ()) (defvar *new-function-definitions*) (defvar *new-type-definitions*) (defvar *new-global-definitions*) (defvar *function-stages*) (defwalker extract-functions (defun name lambda-list &body body+d) (multiple-value-bind (body declare doc) (alexandria:parse-body body+d :documentation t) (let* ((3bgl-glsl::*current-function* (process-type-declarations-for-scope (add-function name lambda-list nil :declarations declare :docs doc))) (*function-stages* (valid-stages 3bgl-glsl::*current-function*))) (clrhash (bindings-used-by 3bgl-glsl::*current-function*)) (when (boundp '*new-function-definitions*) (pushnew 3bgl-glsl::*current-function* *new-function-definitions*)) (setf (body 3bgl-glsl::*current-function*) (with-lambda-list-vars (3bgl-glsl::*current-function*) (@@ body))) (assert *function-stages*) (setf (valid-stages 3bgl-glsl::*current-function*) (alexandria:ensure-list *function-stages*))) nil)) (macrolet ((track-globals (&rest forms) `(progn ,@(loop for form in forms collect `(defwalker extract-functions (,form name &rest rest) (declare (ignore rest)) (prog1 (call-next-method) (when (boundp '*new-global-definitions*) (when (consp name) (setf name (car name))) (assert (get-variable-binding name)) (pushnew (list name (get-variable-binding name)) *new-global-definitions*)))))))) (track-globals defconstant defparameter 3bgl-glsl:defconstant 3bgl-glsl::%defconstant 3bgl-glsl:attribute 3bgl-glsl:uniform 3bgl-glsl:input 3bgl-glsl:output 3bgl-glsl:bind-interface)) (macrolet ((track-types (&rest forms) `(progn ,@(loop for form in forms collect `(defwalker extract-functions (,form name &rest rest) (declare (ignore rest)) (prog1 (call-next-method) (when (boundp '*new-type-definitions*) (pushnew (list name (get-type-binding name)) *new-type-definitions*)))))))) (track-types defstruct)) (defmethod check-stages (interface-binding) (let ((types (loop for (nil sb) on (stage-bindings interface-binding) by #'cddr for .iq = (interface-qualifier sb) for iq = (if (consp .iq) (remove-if (lambda (a) (member a '(:in :out))) .iq) (if (member .iq '(:in :out)) nil .iq)) when iq collect (binding sb)))) (unless (or (every (lambda (a) (typep a 'interface-type)) types) (every (lambda (a) (eq a (car types))) (cdr types))) (error "conflicting types for interface binding ~s : ~{~s~^ ~}" (name interface-binding) (remove-duplicates(mapcar 'name types)))))) (defmethod check-slot-stages (slot-access) (labels ((get-interface-bindings (x) (etypecase x ((or slot-access variable-read variable-write array-access) (get-interface-bindings (binding x))) (interface-binding x) (local-variable (return-from check-slot-stages t))))) (let* ((interface-bindings (get-interface-bindings slot-access)) (types (loop for (nil sb) on (stage-bindings interface-bindings) by #'cddr for b = (binding sb) for st = (if (typep b 'interface-type) (find (field slot-access) (bindings b) :key #'name) b) when st collect (value-type st)))) (unless (every (lambda (a) (eq a (car types))) (cdr types)) (error "conflicting types for slot ~s.~s : ~{~s~^ ~}" (name interface-bindings) (field slot-access) (remove-duplicates(mapcar 'name types))))))) (defmethod walk :around (form (walker extract-functions)) (let ((r (call-next-method))) (when (typep r 'slot-access) (check-slot-stages r)) (when (or (typep r 'variable-read) (typep r 'variable-write)) (when (typep (binding r) 'interface-binding) (check-stages (binding r)) (let ((stage-bindings (stage-bindings (binding r)))) (unless (getf stage-bindings t) (let ((stages (loop for s in stage-bindings by #'cddr collect s))) (if (or (eq t *function-stages*) (equalp '(t) *function-stages*)) (setf *function-stages* stages) (setf *function-stages* (intersection *function-stages* stages)))))))) r)) (defparameter *tree-shaker-hook* (lambda (&rest r) (declare (ignore r)))) (defparameter *tree-shaker-type-hook* (lambda (&rest r) (declare (ignore r)))) (defparameter *tree-shaker-current-object* nil) (defclass tree-shaker () ()) (defmethod walk ((form cons) (walker tree-shaker)) (flet ((w (x) (walk x walker))) (map nil #'w form))) (defmethod walk ((form function-call) (walker tree-shaker)) (when (or (typep (called-function form) 'global-function) (typep (called-function form) 'unknown-function-binding)) (funcall *tree-shaker-hook* (called-function form))) (call-next-method)) (defmethod walk ((form (eql t)) (walker tree-shaker)) form) (defmethod walk ((form (eql :*)) (walker tree-shaker)) form) (defmethod walk ((form concrete-type) (walker tree-shaker)) form) (defmethod walk ((form slot-access) (walker tree-shaker)) (walk (binding form) walker) (call-next-method)) (defmethod walk ((form variable-read) (walker tree-shaker)) (walk (binding form) walker) (call-next-method)) (defmethod walk ((form variable-write) (walker tree-shaker)) (walk (binding form) walker) (call-next-method)) (defmethod walk ((form swizzle-access) (walker tree-shaker)) (walk (binding form) walker) (call-next-method)) (defmethod walk ((form local-variable) (walker tree-shaker)) (walk (value-type form) walker) (walk (declared-type form) walker) (call-next-method)) (defmethod walk ((form binding) (walker tree-shaker)) (walk (declared-type form) walker) (walk (value-type form) walker) (call-next-method)) (defmethod walk ((form constant-binding) (walker tree-shaker)) (funcall *tree-shaker-type-hook* form) (call-next-method)) (defmethod walk ((form interface-binding) (walker tree-shaker)) (funcall *tree-shaker-type-hook* form) (let ((*tree-shaker-current-object* form)) (walk (stage-binding form) walker)) (call-next-method)) (defmethod walk ((form interface-stage-binding) (walker tree-shaker)) (walk (binding form) walker) (call-next-method)) (defmethod walk ((form struct-type) (walker tree-shaker)) (funcall *tree-shaker-type-hook* form) (let ((*tree-shaker-current-object* form)) (walk (bindings form) walker))) (defmethod walk ((form array-type) (walker tree-shaker)) (walk (base-type form) walker) (walk (array-size form) walker)) (defmethod walk ((form for-loop) (walker tree-shaker)) (walk (condition-forms form) walker) (walk (step-forms form) walker) (call-next-method)) (defun tree-shaker (root) (let* ((root (get-function-binding root))) (assert root) (reverse (topo-sort-dependencies root #'bindings-used-by)))) (defun update-dependencies (form) (assert (not (symbolp form))) (let* ((*tree-shaker-current-object* form) (*tree-shaker-hook* (lambda (f) (when (and (not (eq f *tree-shaker-current-object*)) (typep f 'binding-with-dependencies)) (setf (gethash f (bindings-used-by *tree-shaker-current-object*)) f) (setf (gethash *tree-shaker-current-object* (bindings-using f)) *tree-shaker-current-object*)))) (*tree-shaker-type-hook* (lambda (f) (when (and (not (eq f *tree-shaker-current-object*)) (typep f 'binding-with-dependencies)) (setf (gethash f (bindings-used-by *tree-shaker-current-object*)) f) (setf (gethash *tree-shaker-current-object* (bindings-using f)) *tree-shaker-current-object*))))) (walk *tree-shaker-current-object* (make-instance 'tree-shaker)))) (defclass update-calls (3bgl-glsl::glsl-walker) ((modified :initarg :modified :reader modified))) (defmethod walk ((form function-call) (walker update-calls)) (let ((*environment* (argument-environment form))) (setf (arguments form) (mapcar (lambda (x) (walk x walker)) (funcall (expander (called-function form)) (raw-arguments form))))) (call-next-method)) #++ (multiple-value-list (compile-block '((defun foo (a1 b1) (+ a (* 3 (/ b)) 2))) 'foo :vertex)) #++ (multiple-value-list (compile-block '((input position :vec4 :location 0) (defun foo (a1 b1) (+ a (* 3 (/ b)) 2))) 'foo :vertex)) #++ (multiple-value-list (compile-block '((defun foo (a b) (+ a (* 3 (/ b)) 2)) (defparameter *foo-bar* (+ 123 4)) (defconstant +hoge-piyo+ 45) (defmacro bar (c d) `(- ,c ,(+ d 10))) (defun not-called (g) (foo 1 2)) (defun calls-foo (a b) (foo a b)) (defun complicated (a &optional (b 1.0) &key (c 2 cp) (d 3)) (if cp (+ a b c) (+ a b))) (defun main () "do baz stuff" #++(flet ((a (b) (+ 1 b))) (a 2)) (let ((e) (f 1)) (when e (foo 1 2) (bar 2 3)) (if e (calls-foo (foo e 1) (bar f 9)) (complicated (if f (3bgl-glsl::<< f 1) (3bgl-glsl::>> e 1)) (3bgl-glsl::<< 4 +hoge-piyo+) :d 4))))) 'main :vertex)) #++ (multiple-value-list (compile-block '((defun a () (let ((aa 1.0)) (+ aa (b aa) (b 1) (c) (d)))) (defun a2 (a) (+ (b a) (c))) (defun b (bb) (+ (e) (f) bb)) (defun c () (b 2)) (defun d () (f)) (defun e () (d)) (defun f () (+ (g) (h))) (defun g () 1) (defun h () 2)) 'a :vertex)) #++ (3bgl-glsl::generate-stage :fragment 'skybox-shaders::fragment) #++ (print (3bgl-glsl::generate-stage :fragment '3bgl-mesh-shaders::fragment)) #++ (print (3bgl-glsl::generate-stage :geometry '3bgl-mesh-shaders::tsd-geometry))
d2704d40a757921f21497d6b963c925cbe49b1951f2430c2591651f43a9279a7
bitblaze-fuzzball/fuzzball
exec_influence.ml
Copyright ( C ) BitBlaze , 2009 - 2013 , and copyright ( C ) 2010 Ensighta Security Inc. All rights reserved . Copyright (C) BitBlaze, 2009-2013, and copyright (C) 2010 Ensighta Security Inc. All rights reserved. *) module V = Vine open Exec_options open Exec_exceptions open Query_engine open Options_solver open Stpvc_engine open Formula_manager open Fragment_machine open Sym_path_frag_machine let collect_let_vars e = let rec loop e = match e with | V.BinOp(_, e1, e2) -> (loop e1) @ (loop e2) | V.FBinOp(_, _, e1, e2) -> (loop e1) @ (loop e2) | V.UnOp(_, e1) -> loop e1 | V.FUnOp(_, _, e1) -> loop e1 | V.Constant(_) -> [] | V.Lval(_) -> [] | V.Name(_) -> [] | V.Cast(_, _, e1) -> loop e1 | V.FCast(_, _, _, e1) -> loop e1 | V.Unknown(_) -> [] | V.Let(V.Mem(_, _, _), _, _) -> failwith "Let-mem unsupported in collect_let_vars" | V.Let(V.Temp(var), e1, e2) -> var :: (loop e1) @ (loop e2) | V.Ite(ce, te, fe) -> (loop ce) @ (loop te) @ (loop fe) in loop e let log2_of_int i = (log (float_of_int i)) /. (log 2.0) let log2_of_uint64 i64 = let f = Vine_util.int64_u_to_float i64 in (log f) /. (log 2.0) let sx ty v = let bits = 64 - V.bits_of_width ty in Int64.shift_right (Int64.shift_left v bits) bits let zx ty v = let bits = 64 - V.bits_of_width ty in Int64.shift_right_logical (Int64.shift_left v bits) bits let diff_to_range_i diff = if diff = Int64.max_int then 64.0 else log2_of_uint64 (Int64.succ diff) let random_xor_constraint ty target_e num_terms = ( out & ( 1 < < k ) ) < > 0 , k random in [ 0 , bits(out)-1 ] let random_term () = let k = Random.int (V.bits_of_width ty) in let mask = V.Constant(V.Int(ty, (Int64.shift_left 1L k))) in V.BinOp(V.NEQ, V.BinOp(V.BITAND, target_e, mask), V.Constant(V.Int(ty, 0L))) in let rec random_terms k = match k with | 1 -> random_term () | _ -> V.BinOp(V.XOR, random_term (), random_terms (k - 1)) in let parity = V.Constant(V.Int(V.REG_1, Random.int64 2L)) and terms = random_terms num_terms in V.BinOp(V.EQ, terms, parity) let random_xor_constraints ty target_e num_terms k = let rec loop k = match k with | 1 -> random_xor_constraint ty target_e num_terms | _ -> V.BinOp(V.BITAND, (random_xor_constraint ty target_e num_terms), loop (k - 1)) in loop k let opt_influence_details = ref false module InfluenceManagerFunctor = functor (D : Exec_domain.DOMAIN) -> struct class influence_manager (fm : SymPathFragMachineFunctor(D).sym_path_frag_machine) = object(self) val form_man = fm#get_form_man (* This class is currently constructed before the command line options that relate to the choice of solver are parsed. So we want to delay constructing the query engine until it's needed. Using a dummy object will satisfy OCaml's type system so that we don't need a cumbersome option type. *) val mutable qe = new Query_engine.dummy_query_engine val mutable qe_ready = false val measured_values = Hashtbl.create 30 method private take_measure key e = let old = (try Hashtbl.find measured_values key with Not_found -> []) in Hashtbl.replace measured_values key ((fm#get_path_cond, e) :: old) method take_measure_eip e = let eip = fm#get_eip in let str = Printf.sprintf "eip 0x%08Lx" eip in self#take_measure str e method take_measure_expr key_expr e = let str = Printf.sprintf "expr %s" (V.exp_to_string key_expr) in self#take_measure str e method private check_sat target_eq cond = qe#push; qe#start_query; let (result, ce) = qe#query (V.BinOp(V.BITAND, target_eq, cond)) in match result with | Some false -> if !opt_influence_details then (Printf.printf "Yup, condition is satisfiable, by\n"; print_ce ce); qe#after_query !opt_influence_details; qe#pop; let v = ref 0L in ce_iter ce (fun s i64 -> if s = "influence_target" then v := i64); It 's intentional here that v will be set to zero if the variable does n't appear in the counterexample , since some of the solvers do that . the variable doesn't appear in the counterexample, since some of the solvers do that. *) if !opt_influence_details then Printf.printf "Satisfying value is 0x%Lx\n" !v; Some !v | Some true -> if !opt_influence_details then Printf.printf "No, condition is unsat\n"; qe#after_query false; qe#pop; None | None -> qe#after_query true; qe#pop; raise SolverFailure method private check_valid target_eq cond = qe#push; qe#start_query; let (result, ce) = qe#query (V.BinOp(V.BITAND, target_eq, V.UnOp(V.NOT, cond))) in match result with | Some false -> if !opt_influence_details then (Printf.printf "No, condition is invalid; counterexample:\n"; print_ce ce); qe#after_query !opt_influence_details; qe#pop; false | Some true -> if !opt_influence_details then Printf.printf "Yes, condition is valid\n"; qe#after_query false; qe#pop; true | None -> qe#after_query true; qe#pop; raise SolverFailure method private find_bound target_eq target_e is_signed is_max = let ty = Vine_typecheck.infer_type None target_e in let le_op = if is_signed then V.SLE else V.LE in let midpoint a b = let half_rounded x = let half = Int64.shift_right_logical x 1 in if Int64.logand x 1L = 0L then half else Int64.add half (if is_max then 0L else 1L) in if is_signed then let (a', b') = ((sx ty a), (sx ty b)) in let sz = Int64.sub b' a' in let hf_sz = half_rounded sz in let mid = Int64.add a' hf_sz in assert(a' <= mid); assert(mid <= b'); zx ty mid else let sz = Int64.sub b a in let hf_sz = half_rounded sz in let mid = Int64.add a hf_sz in assert(Vine_util.int64_ucompare a mid <= 0); assert(Vine_util.int64_ucompare mid b <= 0); mid in let rec loop min max = if !opt_influence_details then Printf.printf "Binary search in [0x%Lx, 0x%Lx]\n" min max; assert(is_signed || Vine_util.int64_ucompare min max <= 0); if min = max then min else let mid = midpoint min max in let mid_e = V.Constant(V.Int(ty, mid)) in if is_max then let cond_e = V.BinOp(le_op, target_e, mid_e) in let in_bounds = self#check_valid target_eq cond_e in if in_bounds then loop min mid else loop (zx ty (Int64.succ mid)) max else let cond_e = V.BinOp(le_op, mid_e, target_e) in let in_bounds = self#check_valid target_eq cond_e in if in_bounds then loop mid max else loop min (zx ty (Int64.pred mid)) in let wd = V.bits_of_width ty in let (min_limit, max_limit) = if is_signed then (sx ty (Int64.shift_left 1L (wd - 1)), Int64.shift_right_logical (-1L) (64-wd+1)) else (0L, Int64.shift_right_logical (-1L) (64-wd)) in let limit = loop min_limit max_limit in limit method private pointwise_enum target_eq target_e conds max_vals = let ty = Vine_typecheck.infer_type None target_e in let neq_exp v = V.BinOp(V.NEQ, target_e, V.Constant(V.Int(ty, v))) in let rec loop vals n = if n = 0 then vals else let not_old = conjoin (conds @ (List.map neq_exp vals)) in match self#check_sat target_eq not_old with | None -> vals | Some v -> loop (v :: vals) (n - 1) in loop [] max_vals method private random_sample target_eq target_e num_samples = let ty = Vine_typecheck.infer_type None target_e in let rand_val () = match ty with | V.REG_1 -> if Random.bool () then 1L else 0L | V.REG_8 -> Int64.of_int (Random.int 256) | V.REG_16 -> Int64.of_int (Random.int 65536) | V.REG_32 -> Int64.of_int32 (Random.int32 Int32.max_int) | V.REG_64 -> Random.int64 Int64.max_int | _ -> failwith "Unexpected type in rand_val" in let num_hits = ref 0 in for i = 1 to num_samples do let v = rand_val () in let cond = V.BinOp(V.EQ, target_e, V.Constant(V.Int(ty, v))) in match self#check_sat target_eq cond with | None -> () | Some v' -> assert(v = v'); num_hits := !num_hits + 1 done; !num_hits This is basically the # SAT algorithm used in the PLAS'09 paper . paper. *) method private xor_walk_simple target_eq target_e count = let ty = Vine_typecheck.infer_type None target_e in let start = float ((V.bits_of_width ty) / 2) in let num_terms = (V.bits_of_width ty) / 4 in let rec loop guess i = if i >= count then guess else let experiment hypo = let cond = random_xor_constraints ty target_e num_terms hypo in assert(hypo > 0); match self#check_sat target_eq cond with | None -> false | Some(_) -> true in let delta = 2.0 /. (1.0 +. (float i) /. 5.0) and fexp = experiment (int_of_float (floor (guess -. 0.5))) and cexp = experiment (int_of_float (ceil (guess -. 0.5))) in let new_guess = match (fexp, cexp) with | (true, true ) -> guess +. delta | (false, false) -> guess -. delta | _ -> guess in if !opt_influence_details then Printf.printf "XOR iteration %d estimate is %f +- %f\n" i new_guess delta; loop new_guess (i + 1) in loop start 0 The general idea of using enumeration to get more precision , embodied in this function , seems like a good one . This particular approach also sometimes does well when the other constraints are well - structured . But after thiking about it more I believe generating only one set of XOR constraints is n't enough to get a precise and accurate result , because the factor by which any one set of constraints shrink the solution space has high variance . -SMcC embodied in this function, seems like a good one. This particular approach also sometimes does well when the other constraints are well-structured. But after thiking about it more I believe generating only one set of XOR constraints isn't enough to get a precise and accurate result, because the factor by which any one set of constraints shrink the solution space has high variance. -SMcC *) method private xor_then_enum target_eq target_e count = let ty = Vine_typecheck.infer_type None target_e in let num_terms = (V.bits_of_width ty) / 4 in let infty = match ty with | V.REG_1 -> 3 | V.REG_8 -> 257 | V.REG_16 -> 65537 | _ -> 0x3ffffffe in let rec add_xors_loop k = if !opt_influence_details then Printf.printf "Trying with %d constraints\n" k; let cond = random_xor_constraints ty target_e num_terms k in match self#check_sat target_eq cond with | None -> k | Some(_) -> add_xors_loop (k + 1) in let rec rm_xors_loop k = let cond = random_xor_constraints ty target_e num_terms k in let vals = self#pointwise_enum target_eq target_e [cond] infty in let n = List.length vals in if !opt_influence_details then Printf.printf "With %d constraints got %d solutions\n" k n; if n < count then rm_xors_loop (k - 1) else (float k) +. log2_of_int n in let num_xors = add_xors_loop 1 in Printf.printf "Reached unsat after %d constraints\n" num_xors; rm_xors_loop num_xors method private influence_strategies target_eq target_e ty = (let unsign_min = self#find_bound target_eq target_e false false and unsign_max = self#find_bound target_eq target_e false true and signed_min = self#find_bound target_eq target_e true false and signed_max = self#find_bound target_eq target_e true true in let unsign_range_i = (diff_to_range_i (Int64.sub unsign_max unsign_min)) and signed_range_i = (diff_to_range_i (Int64.sub (sx ty signed_max) (sx ty signed_min))) in Printf.printf "Upper bound from unsigned range [0x%Lx, 0x%Lx]: %f\n" unsign_min unsign_max unsign_range_i; Printf.printf "Upper bound from signed range [0x%Lx, 0x%Lx]: %f\n" signed_min signed_max signed_range_i); let points_bits = 6 in let points_max = (1 lsl points_bits) + 1 in let points = self#pointwise_enum target_eq target_e [] points_max in let num_points = List.length points in let points_i = log2_of_int num_points in if num_points < points_max then (Printf.printf "Exact influence from %d points is %f\n" num_points points_i; points_i) else (Printf.printf "Lower bound from %d points is %f\n" num_points points_i; let num_samples = 20 in let num_hits = self#random_sample target_eq target_e num_samples in Printf.printf "Random sampling: %d hits out of %d samples\n" num_hits num_samples; if num_hits > 1 then let frac = (float_of_int num_hits) /. (float_of_int num_samples) in let log_frac = (log frac) /. (log 2.0) and max_bits = float_of_int (V.bits_of_width ty) in let sampled_i = log_frac +. max_bits in Printf.printf "Samples influence is %f\n" sampled_i; sampled_i else (* Here's where we need XOR-streamlining *) self#xor_walk_simple target_eq target_e 50 self#xor_then_enum target_eq target_e 50 ) method measure_influence_common decls assigns cond_e target_e = Printf.printf "In measure_influence_common\n"; if not qe_ready then (qe <- construct_solver "-influence"; qe_ready <- true); let ty = Vine_typecheck.infer_type None target_e in let temp_vars = List.map (fun (var, e) -> var) assigns in let let_vars = (collect_let_vars target_e) @ List.concat (List.map (fun (var, e) -> collect_let_vars e) assigns) in let target_var = V.newvar "influence_target" ty in let free_decls = target_var :: Vine_util.list_difference (Vine_util.list_difference decls temp_vars) let_vars in let target_eq = V.BinOp(V.EQ, V.Lval(V.Temp(target_var)), target_e) in let target_e' = V.Lval(V.Temp(target_var)) in Printf.printf "Free variables are"; List.iter (fun v -> Printf.printf " %s" (V.var_to_string v)) free_decls; Printf.printf "\n"; List.iter (fun v -> qe#add_decl (InputVar(v))) free_decls; Printf.printf "Temp assignments are:\n"; List.iter (fun (v, exp) -> Printf.printf " %s = %s\n" (V.var_to_string v) (V.exp_to_string exp)) assigns; List.iter (fun (v, exp) -> qe#add_decl (TempVar(v, exp))) assigns; Printf.printf "Conditional expr is %s\n" (V.exp_to_string cond_e); qe#add_condition cond_e; Printf.printf "Target expr is %s\n" (V.exp_to_string target_e); flush stdout; assert(self#check_sat target_eq V.exp_true <> None); let i = self#influence_strategies target_eq target_e' ty in qe#reset; i method measure_influence (target_expr : V.exp) = let (decls, assigns, cond_e, target_e, inputs_influencing) = form_man#collect_for_solving [] fm#get_path_cond target_expr in let i = self#measure_influence_common decls assigns cond_e target_e in Printf.printf "Estimated influence on %s is %f\n" (V.exp_to_string target_expr) i; Printf.printf "Inputs contributing to this target expression: %s\n" (List.fold_left (fun a varble -> a ^ ", " ^ (V.var_to_string varble)) "" inputs_influencing); i method compute_multipath_influence loc = let fresh_cond_var = let counter = ref 0 in fun () -> counter := !counter + 1; V.newvar ("cond_" ^ (string_of_int !counter)) V.REG_1 in A note about the List.rev here : in the nested if - then - else we construct below , it 's important to check more specific conditions before more general ones , otherwise the more specific ones will be shadowed . As we collect path conditions along a single path , later PCs will be more specific than earlier ones . So we 're OK if we put them first , i.e. check the PCs in the reverse order that they are collected . The list is reversed once because it 's collected by pushing elements onto a list , and once in the fold_left below , so to make the total number of reversals odd we reverse it one more time here . construct below, it's important to check more specific conditions before more general ones, otherwise the more specific ones will be shadowed. As we collect path conditions along a single path, later PCs will be more specific than earlier ones. So we're OK if we put them first, i.e. check the PCs in the reverse order that they are collected. The list is reversed once because it's collected by pushing elements onto a list, and once in the fold_left below, so to make the total number of reversals odd we reverse it one more time here. *) let measurements = List.rev (try Hashtbl.find measured_values loc with Not_found -> []) in let vtype = match measurements with | (_, e) :: rest -> Vine_typecheck.infer_type None e | _ -> V.REG_32 in let conjoined = List.map (fun (pc, e) -> (fresh_cond_var (), conjoin pc, e)) measurements in let cond_assigns = List.map (fun (lhs, rhs, _) -> (lhs, rhs)) conjoined in let cond_vars = List.map (fun (v, _) -> v) cond_assigns in let cond_var_exps = List.map (fun v -> V.Lval(V.Temp(v))) cond_vars in let cond = disjoin cond_var_exps in let expr = List.fold_left (fun e (cond_v, _, v_e) -> V.exp_ite (V.Lval(V.Temp(cond_v))) vtype v_e e) (V.Constant(V.Int(vtype, 0L))) conjoined in let (free_decls, t_assigns, cond_e, target_e, inputs_influencing) = form_man#collect_for_solving cond_assigns [cond] expr in if measurements = [] then Printf.printf "No influence measurements at %s\n" loc else let i = (self#measure_influence_common free_decls t_assigns cond_e target_e) in Printf.printf "Estimated multipath influence at %s is %f\n" loc i; Printf.printf "Inputs contributing to this target expression: %s\n" (List.fold_left (fun a varble -> a ^ ", " ^ (V.var_to_string varble)) "" inputs_influencing); method compute_all_multipath_influence = Hashtbl.iter (fun eip _ -> self#compute_multipath_influence eip) measured_values val mutable periodic_influence_exprs = [] method store_symbolic_byte_influence addr varname = let v = form_man#fresh_symbolic_8 varname in fm#store_byte addr v; periodic_influence_exprs <- (D.to_symbolic_8 v) :: periodic_influence_exprs method store_symbolic_short_influence addr varname = let v = form_man#fresh_symbolic_16 varname in fm#store_short addr v; periodic_influence_exprs <- (D.to_symbolic_16 v) :: periodic_influence_exprs method store_symbolic_word_influence addr varname = let v = form_man#fresh_symbolic_32 varname in fm#store_word addr v; periodic_influence_exprs <- (D.to_symbolic_32 v) :: periodic_influence_exprs method store_symbolic_long_influence addr varname = let v = form_man#fresh_symbolic_64 varname in fm#store_long addr v; periodic_influence_exprs <- (D.to_symbolic_64 v) :: periodic_influence_exprs method maybe_periodic_influence = match !opt_periodic_influence with | None -> () | Some period when fm#get_depth >= !next_periodic_influence -> next_periodic_influence := fm#get_depth + period; let num_bounded = ref 0 in List.iter (fun e -> let i = self#measure_influence e in if i <= !opt_influence_bound then incr num_bounded) periodic_influence_exprs; if !num_bounded = List.length periodic_influence_exprs then raise ReachedInfluenceBound | Some _ -> () method path_end_influence = List.iter (fun e -> self#take_measure_expr e e) periodic_influence_exprs val unique_measurements = Hashtbl.create 30 method measure_point_influence name e = let eip = fm#get_eip in let loc = Printf.sprintf "%s %s:%08Lx:%Ld" name (fm#get_hist_str) eip fm#get_loop_cnt in if Hashtbl.mem unique_measurements loc then (if !opt_trace_sym_addrs then Printf.printf "Skipping redundant influence measurement at %s\n" loc) else (Hashtbl.replace unique_measurements loc (); self#take_measure_eip e; if !opt_trace_sym_addrs then Printf.printf "Took influence measurement at %s\n" loc; if not !opt_multipath_influence_only then ignore(self#measure_influence e)) method maybe_measure_influence_deref e = let eip = fm#get_eip in match !opt_measure_deref_influence_at with | Some addr when addr = eip -> self#take_measure_eip e; if !opt_trace_sym_addrs then Printf.printf "Took influence measurement at eip %08Lx\n" eip; if not !opt_multipath_influence_only then ignore(self#measure_influence e); if !opt_stop_at_measurement then raise ReachedMeasurePoint | _ -> if !opt_measure_influence_derefs then self#measure_point_influence "deref" e method measure_influence_rep = assert(!opt_arch = X86); let count = fm#get_word_var_d R_ECX in try ignore(D.to_concrete_32 count) with NotConcrete _ -> self#measure_point_influence "reploop" (D.to_symbolic_32 count) method measure_influence_expr expr = let (v, ty) = fm#eval_int_exp_ty expr in let e = match ty with | V.REG_1 -> D.to_symbolic_1 v | V.REG_8 -> D.to_symbolic_8 v | V.REG_16 -> D.to_symbolic_16 v | V.REG_32 -> D.to_symbolic_32 v | V.REG_64 -> D.to_symbolic_64 v | _ -> failwith "Bad type in measure_influence_expr" in self#measure_point_influence "expr" e val mutable qualified = true method disqualify_path = qualified <- false method eip_hook eip = if List.mem eip !opt_disqualify_addrs then (self#disqualify_path; fm#unfinish_fuzz "Disqualified path"; raise DisqualifiedPath); (if !opt_measure_influence_reploops then let prefix = fm#load_byte_conc eip in match prefix with | 0xf2 | 0xf3 -> self#measure_influence_rep | _ -> ()); (match !opt_measure_expr_influence_at with | Some (eip', expr) when eip' = eip -> self#measure_influence_expr expr; if !opt_stop_at_measurement then raise ReachedMeasurePoint | _ -> ()); method finish_path = if qualified then self#path_end_influence method reset = qualified <- true method after_exploration = match (!opt_measure_deref_influence_at, !opt_measure_expr_influence_at) with | (Some eip, _) -> self#compute_multipath_influence (Printf.sprintf "eip 0x%08Lx" eip) | (_, Some (eip, expr)) -> self#compute_multipath_influence (Printf.sprintf "eip 0x%08Lx" eip) | _ -> self#compute_all_multipath_influence end end
null
https://raw.githubusercontent.com/bitblaze-fuzzball/fuzzball/b9a617b45e68fa732f1357fedc08a2a10f87a62c/execution/exec_influence.ml
ocaml
This class is currently constructed before the command line options that relate to the choice of solver are parsed. So we want to delay constructing the query engine until it's needed. Using a dummy object will satisfy OCaml's type system so that we don't need a cumbersome option type. Here's where we need XOR-streamlining
Copyright ( C ) BitBlaze , 2009 - 2013 , and copyright ( C ) 2010 Ensighta Security Inc. All rights reserved . Copyright (C) BitBlaze, 2009-2013, and copyright (C) 2010 Ensighta Security Inc. All rights reserved. *) module V = Vine open Exec_options open Exec_exceptions open Query_engine open Options_solver open Stpvc_engine open Formula_manager open Fragment_machine open Sym_path_frag_machine let collect_let_vars e = let rec loop e = match e with | V.BinOp(_, e1, e2) -> (loop e1) @ (loop e2) | V.FBinOp(_, _, e1, e2) -> (loop e1) @ (loop e2) | V.UnOp(_, e1) -> loop e1 | V.FUnOp(_, _, e1) -> loop e1 | V.Constant(_) -> [] | V.Lval(_) -> [] | V.Name(_) -> [] | V.Cast(_, _, e1) -> loop e1 | V.FCast(_, _, _, e1) -> loop e1 | V.Unknown(_) -> [] | V.Let(V.Mem(_, _, _), _, _) -> failwith "Let-mem unsupported in collect_let_vars" | V.Let(V.Temp(var), e1, e2) -> var :: (loop e1) @ (loop e2) | V.Ite(ce, te, fe) -> (loop ce) @ (loop te) @ (loop fe) in loop e let log2_of_int i = (log (float_of_int i)) /. (log 2.0) let log2_of_uint64 i64 = let f = Vine_util.int64_u_to_float i64 in (log f) /. (log 2.0) let sx ty v = let bits = 64 - V.bits_of_width ty in Int64.shift_right (Int64.shift_left v bits) bits let zx ty v = let bits = 64 - V.bits_of_width ty in Int64.shift_right_logical (Int64.shift_left v bits) bits let diff_to_range_i diff = if diff = Int64.max_int then 64.0 else log2_of_uint64 (Int64.succ diff) let random_xor_constraint ty target_e num_terms = ( out & ( 1 < < k ) ) < > 0 , k random in [ 0 , bits(out)-1 ] let random_term () = let k = Random.int (V.bits_of_width ty) in let mask = V.Constant(V.Int(ty, (Int64.shift_left 1L k))) in V.BinOp(V.NEQ, V.BinOp(V.BITAND, target_e, mask), V.Constant(V.Int(ty, 0L))) in let rec random_terms k = match k with | 1 -> random_term () | _ -> V.BinOp(V.XOR, random_term (), random_terms (k - 1)) in let parity = V.Constant(V.Int(V.REG_1, Random.int64 2L)) and terms = random_terms num_terms in V.BinOp(V.EQ, terms, parity) let random_xor_constraints ty target_e num_terms k = let rec loop k = match k with | 1 -> random_xor_constraint ty target_e num_terms | _ -> V.BinOp(V.BITAND, (random_xor_constraint ty target_e num_terms), loop (k - 1)) in loop k let opt_influence_details = ref false module InfluenceManagerFunctor = functor (D : Exec_domain.DOMAIN) -> struct class influence_manager (fm : SymPathFragMachineFunctor(D).sym_path_frag_machine) = object(self) val form_man = fm#get_form_man val mutable qe = new Query_engine.dummy_query_engine val mutable qe_ready = false val measured_values = Hashtbl.create 30 method private take_measure key e = let old = (try Hashtbl.find measured_values key with Not_found -> []) in Hashtbl.replace measured_values key ((fm#get_path_cond, e) :: old) method take_measure_eip e = let eip = fm#get_eip in let str = Printf.sprintf "eip 0x%08Lx" eip in self#take_measure str e method take_measure_expr key_expr e = let str = Printf.sprintf "expr %s" (V.exp_to_string key_expr) in self#take_measure str e method private check_sat target_eq cond = qe#push; qe#start_query; let (result, ce) = qe#query (V.BinOp(V.BITAND, target_eq, cond)) in match result with | Some false -> if !opt_influence_details then (Printf.printf "Yup, condition is satisfiable, by\n"; print_ce ce); qe#after_query !opt_influence_details; qe#pop; let v = ref 0L in ce_iter ce (fun s i64 -> if s = "influence_target" then v := i64); It 's intentional here that v will be set to zero if the variable does n't appear in the counterexample , since some of the solvers do that . the variable doesn't appear in the counterexample, since some of the solvers do that. *) if !opt_influence_details then Printf.printf "Satisfying value is 0x%Lx\n" !v; Some !v | Some true -> if !opt_influence_details then Printf.printf "No, condition is unsat\n"; qe#after_query false; qe#pop; None | None -> qe#after_query true; qe#pop; raise SolverFailure method private check_valid target_eq cond = qe#push; qe#start_query; let (result, ce) = qe#query (V.BinOp(V.BITAND, target_eq, V.UnOp(V.NOT, cond))) in match result with | Some false -> if !opt_influence_details then (Printf.printf "No, condition is invalid; counterexample:\n"; print_ce ce); qe#after_query !opt_influence_details; qe#pop; false | Some true -> if !opt_influence_details then Printf.printf "Yes, condition is valid\n"; qe#after_query false; qe#pop; true | None -> qe#after_query true; qe#pop; raise SolverFailure method private find_bound target_eq target_e is_signed is_max = let ty = Vine_typecheck.infer_type None target_e in let le_op = if is_signed then V.SLE else V.LE in let midpoint a b = let half_rounded x = let half = Int64.shift_right_logical x 1 in if Int64.logand x 1L = 0L then half else Int64.add half (if is_max then 0L else 1L) in if is_signed then let (a', b') = ((sx ty a), (sx ty b)) in let sz = Int64.sub b' a' in let hf_sz = half_rounded sz in let mid = Int64.add a' hf_sz in assert(a' <= mid); assert(mid <= b'); zx ty mid else let sz = Int64.sub b a in let hf_sz = half_rounded sz in let mid = Int64.add a hf_sz in assert(Vine_util.int64_ucompare a mid <= 0); assert(Vine_util.int64_ucompare mid b <= 0); mid in let rec loop min max = if !opt_influence_details then Printf.printf "Binary search in [0x%Lx, 0x%Lx]\n" min max; assert(is_signed || Vine_util.int64_ucompare min max <= 0); if min = max then min else let mid = midpoint min max in let mid_e = V.Constant(V.Int(ty, mid)) in if is_max then let cond_e = V.BinOp(le_op, target_e, mid_e) in let in_bounds = self#check_valid target_eq cond_e in if in_bounds then loop min mid else loop (zx ty (Int64.succ mid)) max else let cond_e = V.BinOp(le_op, mid_e, target_e) in let in_bounds = self#check_valid target_eq cond_e in if in_bounds then loop mid max else loop min (zx ty (Int64.pred mid)) in let wd = V.bits_of_width ty in let (min_limit, max_limit) = if is_signed then (sx ty (Int64.shift_left 1L (wd - 1)), Int64.shift_right_logical (-1L) (64-wd+1)) else (0L, Int64.shift_right_logical (-1L) (64-wd)) in let limit = loop min_limit max_limit in limit method private pointwise_enum target_eq target_e conds max_vals = let ty = Vine_typecheck.infer_type None target_e in let neq_exp v = V.BinOp(V.NEQ, target_e, V.Constant(V.Int(ty, v))) in let rec loop vals n = if n = 0 then vals else let not_old = conjoin (conds @ (List.map neq_exp vals)) in match self#check_sat target_eq not_old with | None -> vals | Some v -> loop (v :: vals) (n - 1) in loop [] max_vals method private random_sample target_eq target_e num_samples = let ty = Vine_typecheck.infer_type None target_e in let rand_val () = match ty with | V.REG_1 -> if Random.bool () then 1L else 0L | V.REG_8 -> Int64.of_int (Random.int 256) | V.REG_16 -> Int64.of_int (Random.int 65536) | V.REG_32 -> Int64.of_int32 (Random.int32 Int32.max_int) | V.REG_64 -> Random.int64 Int64.max_int | _ -> failwith "Unexpected type in rand_val" in let num_hits = ref 0 in for i = 1 to num_samples do let v = rand_val () in let cond = V.BinOp(V.EQ, target_e, V.Constant(V.Int(ty, v))) in match self#check_sat target_eq cond with | None -> () | Some v' -> assert(v = v'); num_hits := !num_hits + 1 done; !num_hits This is basically the # SAT algorithm used in the PLAS'09 paper . paper. *) method private xor_walk_simple target_eq target_e count = let ty = Vine_typecheck.infer_type None target_e in let start = float ((V.bits_of_width ty) / 2) in let num_terms = (V.bits_of_width ty) / 4 in let rec loop guess i = if i >= count then guess else let experiment hypo = let cond = random_xor_constraints ty target_e num_terms hypo in assert(hypo > 0); match self#check_sat target_eq cond with | None -> false | Some(_) -> true in let delta = 2.0 /. (1.0 +. (float i) /. 5.0) and fexp = experiment (int_of_float (floor (guess -. 0.5))) and cexp = experiment (int_of_float (ceil (guess -. 0.5))) in let new_guess = match (fexp, cexp) with | (true, true ) -> guess +. delta | (false, false) -> guess -. delta | _ -> guess in if !opt_influence_details then Printf.printf "XOR iteration %d estimate is %f +- %f\n" i new_guess delta; loop new_guess (i + 1) in loop start 0 The general idea of using enumeration to get more precision , embodied in this function , seems like a good one . This particular approach also sometimes does well when the other constraints are well - structured . But after thiking about it more I believe generating only one set of XOR constraints is n't enough to get a precise and accurate result , because the factor by which any one set of constraints shrink the solution space has high variance . -SMcC embodied in this function, seems like a good one. This particular approach also sometimes does well when the other constraints are well-structured. But after thiking about it more I believe generating only one set of XOR constraints isn't enough to get a precise and accurate result, because the factor by which any one set of constraints shrink the solution space has high variance. -SMcC *) method private xor_then_enum target_eq target_e count = let ty = Vine_typecheck.infer_type None target_e in let num_terms = (V.bits_of_width ty) / 4 in let infty = match ty with | V.REG_1 -> 3 | V.REG_8 -> 257 | V.REG_16 -> 65537 | _ -> 0x3ffffffe in let rec add_xors_loop k = if !opt_influence_details then Printf.printf "Trying with %d constraints\n" k; let cond = random_xor_constraints ty target_e num_terms k in match self#check_sat target_eq cond with | None -> k | Some(_) -> add_xors_loop (k + 1) in let rec rm_xors_loop k = let cond = random_xor_constraints ty target_e num_terms k in let vals = self#pointwise_enum target_eq target_e [cond] infty in let n = List.length vals in if !opt_influence_details then Printf.printf "With %d constraints got %d solutions\n" k n; if n < count then rm_xors_loop (k - 1) else (float k) +. log2_of_int n in let num_xors = add_xors_loop 1 in Printf.printf "Reached unsat after %d constraints\n" num_xors; rm_xors_loop num_xors method private influence_strategies target_eq target_e ty = (let unsign_min = self#find_bound target_eq target_e false false and unsign_max = self#find_bound target_eq target_e false true and signed_min = self#find_bound target_eq target_e true false and signed_max = self#find_bound target_eq target_e true true in let unsign_range_i = (diff_to_range_i (Int64.sub unsign_max unsign_min)) and signed_range_i = (diff_to_range_i (Int64.sub (sx ty signed_max) (sx ty signed_min))) in Printf.printf "Upper bound from unsigned range [0x%Lx, 0x%Lx]: %f\n" unsign_min unsign_max unsign_range_i; Printf.printf "Upper bound from signed range [0x%Lx, 0x%Lx]: %f\n" signed_min signed_max signed_range_i); let points_bits = 6 in let points_max = (1 lsl points_bits) + 1 in let points = self#pointwise_enum target_eq target_e [] points_max in let num_points = List.length points in let points_i = log2_of_int num_points in if num_points < points_max then (Printf.printf "Exact influence from %d points is %f\n" num_points points_i; points_i) else (Printf.printf "Lower bound from %d points is %f\n" num_points points_i; let num_samples = 20 in let num_hits = self#random_sample target_eq target_e num_samples in Printf.printf "Random sampling: %d hits out of %d samples\n" num_hits num_samples; if num_hits > 1 then let frac = (float_of_int num_hits) /. (float_of_int num_samples) in let log_frac = (log frac) /. (log 2.0) and max_bits = float_of_int (V.bits_of_width ty) in let sampled_i = log_frac +. max_bits in Printf.printf "Samples influence is %f\n" sampled_i; sampled_i else self#xor_walk_simple target_eq target_e 50 self#xor_then_enum target_eq target_e 50 ) method measure_influence_common decls assigns cond_e target_e = Printf.printf "In measure_influence_common\n"; if not qe_ready then (qe <- construct_solver "-influence"; qe_ready <- true); let ty = Vine_typecheck.infer_type None target_e in let temp_vars = List.map (fun (var, e) -> var) assigns in let let_vars = (collect_let_vars target_e) @ List.concat (List.map (fun (var, e) -> collect_let_vars e) assigns) in let target_var = V.newvar "influence_target" ty in let free_decls = target_var :: Vine_util.list_difference (Vine_util.list_difference decls temp_vars) let_vars in let target_eq = V.BinOp(V.EQ, V.Lval(V.Temp(target_var)), target_e) in let target_e' = V.Lval(V.Temp(target_var)) in Printf.printf "Free variables are"; List.iter (fun v -> Printf.printf " %s" (V.var_to_string v)) free_decls; Printf.printf "\n"; List.iter (fun v -> qe#add_decl (InputVar(v))) free_decls; Printf.printf "Temp assignments are:\n"; List.iter (fun (v, exp) -> Printf.printf " %s = %s\n" (V.var_to_string v) (V.exp_to_string exp)) assigns; List.iter (fun (v, exp) -> qe#add_decl (TempVar(v, exp))) assigns; Printf.printf "Conditional expr is %s\n" (V.exp_to_string cond_e); qe#add_condition cond_e; Printf.printf "Target expr is %s\n" (V.exp_to_string target_e); flush stdout; assert(self#check_sat target_eq V.exp_true <> None); let i = self#influence_strategies target_eq target_e' ty in qe#reset; i method measure_influence (target_expr : V.exp) = let (decls, assigns, cond_e, target_e, inputs_influencing) = form_man#collect_for_solving [] fm#get_path_cond target_expr in let i = self#measure_influence_common decls assigns cond_e target_e in Printf.printf "Estimated influence on %s is %f\n" (V.exp_to_string target_expr) i; Printf.printf "Inputs contributing to this target expression: %s\n" (List.fold_left (fun a varble -> a ^ ", " ^ (V.var_to_string varble)) "" inputs_influencing); i method compute_multipath_influence loc = let fresh_cond_var = let counter = ref 0 in fun () -> counter := !counter + 1; V.newvar ("cond_" ^ (string_of_int !counter)) V.REG_1 in A note about the List.rev here : in the nested if - then - else we construct below , it 's important to check more specific conditions before more general ones , otherwise the more specific ones will be shadowed . As we collect path conditions along a single path , later PCs will be more specific than earlier ones . So we 're OK if we put them first , i.e. check the PCs in the reverse order that they are collected . The list is reversed once because it 's collected by pushing elements onto a list , and once in the fold_left below , so to make the total number of reversals odd we reverse it one more time here . construct below, it's important to check more specific conditions before more general ones, otherwise the more specific ones will be shadowed. As we collect path conditions along a single path, later PCs will be more specific than earlier ones. So we're OK if we put them first, i.e. check the PCs in the reverse order that they are collected. The list is reversed once because it's collected by pushing elements onto a list, and once in the fold_left below, so to make the total number of reversals odd we reverse it one more time here. *) let measurements = List.rev (try Hashtbl.find measured_values loc with Not_found -> []) in let vtype = match measurements with | (_, e) :: rest -> Vine_typecheck.infer_type None e | _ -> V.REG_32 in let conjoined = List.map (fun (pc, e) -> (fresh_cond_var (), conjoin pc, e)) measurements in let cond_assigns = List.map (fun (lhs, rhs, _) -> (lhs, rhs)) conjoined in let cond_vars = List.map (fun (v, _) -> v) cond_assigns in let cond_var_exps = List.map (fun v -> V.Lval(V.Temp(v))) cond_vars in let cond = disjoin cond_var_exps in let expr = List.fold_left (fun e (cond_v, _, v_e) -> V.exp_ite (V.Lval(V.Temp(cond_v))) vtype v_e e) (V.Constant(V.Int(vtype, 0L))) conjoined in let (free_decls, t_assigns, cond_e, target_e, inputs_influencing) = form_man#collect_for_solving cond_assigns [cond] expr in if measurements = [] then Printf.printf "No influence measurements at %s\n" loc else let i = (self#measure_influence_common free_decls t_assigns cond_e target_e) in Printf.printf "Estimated multipath influence at %s is %f\n" loc i; Printf.printf "Inputs contributing to this target expression: %s\n" (List.fold_left (fun a varble -> a ^ ", " ^ (V.var_to_string varble)) "" inputs_influencing); method compute_all_multipath_influence = Hashtbl.iter (fun eip _ -> self#compute_multipath_influence eip) measured_values val mutable periodic_influence_exprs = [] method store_symbolic_byte_influence addr varname = let v = form_man#fresh_symbolic_8 varname in fm#store_byte addr v; periodic_influence_exprs <- (D.to_symbolic_8 v) :: periodic_influence_exprs method store_symbolic_short_influence addr varname = let v = form_man#fresh_symbolic_16 varname in fm#store_short addr v; periodic_influence_exprs <- (D.to_symbolic_16 v) :: periodic_influence_exprs method store_symbolic_word_influence addr varname = let v = form_man#fresh_symbolic_32 varname in fm#store_word addr v; periodic_influence_exprs <- (D.to_symbolic_32 v) :: periodic_influence_exprs method store_symbolic_long_influence addr varname = let v = form_man#fresh_symbolic_64 varname in fm#store_long addr v; periodic_influence_exprs <- (D.to_symbolic_64 v) :: periodic_influence_exprs method maybe_periodic_influence = match !opt_periodic_influence with | None -> () | Some period when fm#get_depth >= !next_periodic_influence -> next_periodic_influence := fm#get_depth + period; let num_bounded = ref 0 in List.iter (fun e -> let i = self#measure_influence e in if i <= !opt_influence_bound then incr num_bounded) periodic_influence_exprs; if !num_bounded = List.length periodic_influence_exprs then raise ReachedInfluenceBound | Some _ -> () method path_end_influence = List.iter (fun e -> self#take_measure_expr e e) periodic_influence_exprs val unique_measurements = Hashtbl.create 30 method measure_point_influence name e = let eip = fm#get_eip in let loc = Printf.sprintf "%s %s:%08Lx:%Ld" name (fm#get_hist_str) eip fm#get_loop_cnt in if Hashtbl.mem unique_measurements loc then (if !opt_trace_sym_addrs then Printf.printf "Skipping redundant influence measurement at %s\n" loc) else (Hashtbl.replace unique_measurements loc (); self#take_measure_eip e; if !opt_trace_sym_addrs then Printf.printf "Took influence measurement at %s\n" loc; if not !opt_multipath_influence_only then ignore(self#measure_influence e)) method maybe_measure_influence_deref e = let eip = fm#get_eip in match !opt_measure_deref_influence_at with | Some addr when addr = eip -> self#take_measure_eip e; if !opt_trace_sym_addrs then Printf.printf "Took influence measurement at eip %08Lx\n" eip; if not !opt_multipath_influence_only then ignore(self#measure_influence e); if !opt_stop_at_measurement then raise ReachedMeasurePoint | _ -> if !opt_measure_influence_derefs then self#measure_point_influence "deref" e method measure_influence_rep = assert(!opt_arch = X86); let count = fm#get_word_var_d R_ECX in try ignore(D.to_concrete_32 count) with NotConcrete _ -> self#measure_point_influence "reploop" (D.to_symbolic_32 count) method measure_influence_expr expr = let (v, ty) = fm#eval_int_exp_ty expr in let e = match ty with | V.REG_1 -> D.to_symbolic_1 v | V.REG_8 -> D.to_symbolic_8 v | V.REG_16 -> D.to_symbolic_16 v | V.REG_32 -> D.to_symbolic_32 v | V.REG_64 -> D.to_symbolic_64 v | _ -> failwith "Bad type in measure_influence_expr" in self#measure_point_influence "expr" e val mutable qualified = true method disqualify_path = qualified <- false method eip_hook eip = if List.mem eip !opt_disqualify_addrs then (self#disqualify_path; fm#unfinish_fuzz "Disqualified path"; raise DisqualifiedPath); (if !opt_measure_influence_reploops then let prefix = fm#load_byte_conc eip in match prefix with | 0xf2 | 0xf3 -> self#measure_influence_rep | _ -> ()); (match !opt_measure_expr_influence_at with | Some (eip', expr) when eip' = eip -> self#measure_influence_expr expr; if !opt_stop_at_measurement then raise ReachedMeasurePoint | _ -> ()); method finish_path = if qualified then self#path_end_influence method reset = qualified <- true method after_exploration = match (!opt_measure_deref_influence_at, !opt_measure_expr_influence_at) with | (Some eip, _) -> self#compute_multipath_influence (Printf.sprintf "eip 0x%08Lx" eip) | (_, Some (eip, expr)) -> self#compute_multipath_influence (Printf.sprintf "eip 0x%08Lx" eip) | _ -> self#compute_all_multipath_influence end end
c9ab518b588333e1343aeb1cefc462797bb23e32997fffe607a7fb025f24b621
monadbobo/ocaml-core
pre_sexp.ml
Sexp : Module for handling S - expressions ( I / O , etc . ) open Format open Bigarray include Type exception Of_sexp_error of exn * t type bigstring = (char, int8_unsigned_elt, c_layout) Array1.t (* Default indentation level for human-readable conversions *) let default_indent = ref 1 (* Escaping of strings used as atoms in S-expressions *) let must_escape str = let len = String.length str in len = 0 || let rec loop ix = match str.[ix] with | '"' | '(' | ')' | ';' | '\\' -> true | '|' -> ix > 0 && let next = ix - 1 in str.[next] = '#' || loop next | '#' -> ix > 0 && let next = ix - 1 in str.[next] = '|' || loop next | c -> c <= ' ' || ix > 0 && loop (ix - 1) in loop (len - 1) let maybe_esc_str str = if must_escape str then let estr = String.escaped str in let elen = String.length estr in let res = String.create (elen + 2) in String.blit estr 0 res 1 elen; res.[0] <- '"'; res.[elen + 1] <- '"'; res else str let pp_maybe_esc_str ppf str = pp_print_string ppf (maybe_esc_str str) (* Output of S-expressions to formatters *) let rec pp_hum_indent indent ppf = function | Atom str -> pp_maybe_esc_str ppf str | List (h :: t) -> pp_open_box ppf indent; pp_print_string ppf "("; pp_hum_indent indent ppf h; pp_hum_rest indent ppf t | List [] -> pp_print_string ppf "()" and pp_hum_rest indent ppf = function | h :: t -> pp_print_space ppf (); pp_hum_indent indent ppf h; pp_hum_rest indent ppf t | [] -> pp_print_string ppf ")"; pp_close_box ppf () let rec pp_mach_internal may_need_space ppf = function | Atom str -> let str' = maybe_esc_str str in let new_may_need_space = str' == str in if may_need_space && new_may_need_space then pp_print_string ppf " "; pp_print_string ppf str'; new_may_need_space | List (h :: t) -> pp_print_string ppf "("; let may_need_space = pp_mach_internal false ppf h in pp_mach_rest may_need_space ppf t; false | List [] -> pp_print_string ppf "()"; false and pp_mach_rest may_need_space ppf = function | h :: t -> let may_need_space = pp_mach_internal may_need_space ppf h in pp_mach_rest may_need_space ppf t | [] -> pp_print_string ppf ")" let pp_hum ppf sexp = pp_hum_indent !default_indent ppf sexp let pp_mach ppf sexp = ignore (pp_mach_internal false ppf sexp) let pp = pp_mach Sexp size let rec size_loop (v, c as acc) = function | Atom str -> v + 1, c + String.length str | List lst -> List.fold_left size_loop acc lst let size sexp = size_loop (0, 0) sexp (* Buffer conversions *) let to_buffer_hum ~buf ?(indent = !default_indent) sexp = Format.bprintf buf "%a@?" (pp_hum_indent indent) sexp let to_buffer_mach ~buf sexp = let rec loop may_need_space = function | Atom str -> let str' = maybe_esc_str str in let new_may_need_space = str' == str in if may_need_space && new_may_need_space then Buffer.add_char buf ' '; Buffer.add_string buf str'; new_may_need_space | List (h :: t) -> Buffer.add_char buf '('; let may_need_space = loop false h in loop_rest may_need_space t; false | List [] -> Buffer.add_string buf "()"; false and loop_rest may_need_space = function | h :: t -> let may_need_space = loop may_need_space h in loop_rest may_need_space t | [] -> Buffer.add_char buf ')' in ignore (loop false sexp) let to_buffer = to_buffer_mach let to_buffer_gen ~buf ~add_char ~add_string sexp = let rec loop may_need_space = function | Atom str -> let str' = maybe_esc_str str in let new_may_need_space = str' == str in if may_need_space && new_may_need_space then add_char buf ' '; add_string buf str'; new_may_need_space | List (h :: t) -> add_char buf '('; let may_need_space = loop false h in loop_rest may_need_space t; false | List [] -> add_string buf "()"; false and loop_rest may_need_space = function | h :: t -> let may_need_space = loop may_need_space h in loop_rest may_need_space t | [] -> add_char buf ')' in ignore (loop false sexp) (* Output of S-expressions to I/O-channels *) The maximum size of a thing on the minor heap is 256 words . Previously , this size of the returned buffer here was 4096 bytes , which caused the Buffer to be allocated on the * major * heap every time . According to a simple benchmark by , we can improve performance for small s - expressions by a factor of ~4 if we only allocate 1024 bytes ( 128 words + some small overhead ) worth of buffer initially . And one can argue that if it 's free to allocate strings smaller than 256 words , large s - expressions requiring larger expensive buffers wo n't notice the extra two doublings from 1024 bytes to 2048 and 4096 . And especially performance - sensitive applications to always pass in a larger buffer to use . Previously, this size of the returned buffer here was 4096 bytes, which caused the Buffer to be allocated on the *major* heap every time. According to a simple benchmark by Ron, we can improve performance for small s-expressions by a factor of ~4 if we only allocate 1024 bytes (128 words + some small overhead) worth of buffer initially. And one can argue that if it's free to allocate strings smaller than 256 words, large s-expressions requiring larger expensive buffers won't notice the extra two doublings from 1024 bytes to 2048 and 4096. And especially performance-sensitive applications to always pass in a larger buffer to use. *) let buffer () = Buffer.create 1024 let with_new_buffer oc f = let buf = buffer () in f buf; Buffer.output_buffer oc buf let output_hum oc sexp = with_new_buffer oc (fun buf -> to_buffer_hum sexp ~buf) let output_hum_indent indent oc sexp = with_new_buffer oc (fun buf -> to_buffer_hum ~indent sexp ~buf) let output_mach oc sexp = with_new_buffer oc (fun buf -> to_buffer_mach sexp ~buf) let output = output_mach (* Output of S-expressions to file *) (* The temp file functions in the OCaml Filename module do not support permissions. But opening a file with given permissions is different from opening it and chmoding it to these permissions, because the umask is taken in account. Under Unix there's no easy way to get the umask in a thread-safe way. *) module Tmp_file = struct let prng = ref None let temp_file_name prefix suffix = let rand_state = match !prng with | Some v -> v | None -> let ret = Random.State.make_self_init () in prng := Some ret; ret in let rnd = (Random.State.bits rand_state) land 0xFFFFFF in Printf.sprintf "%s%06x%s" prefix rnd suffix let open_temp_file ?(perm = 0o600) prefix suffix = let rec try_name counter = let name = temp_file_name prefix suffix in try let oc = open_out_gen [Open_wronly; Open_creat; Open_excl; Open_text] perm name in name, oc with Sys_error _ as e -> if counter >= 1000 then raise e else try_name (counter + 1) in try_name 0 end let save_of_output ?perm output_function file sexp = let tmp_name, oc = Tmp_file.open_temp_file ?perm file "tmp" in begin try output_function oc sexp; close_out oc; with e -> close_out_noerr oc; begin try Sys.remove tmp_name with _ -> () end; raise e end; Sys.rename tmp_name file let output_sexp_nl do_output oc sexp = do_output oc sexp; output_string oc "\n" let save_hum ?perm file sexp = save_of_output ?perm (output_sexp_nl output_hum) file sexp let save_mach ?perm file sexp = save_of_output ?perm output_mach file sexp let save = save_mach let output_sexps_nl do_output oc sexps = List.iter (output_sexp_nl do_output oc) sexps let save_sexps_hum ?perm file sexps = save_of_output ?perm (output_sexps_nl output_hum) file sexps let save_sexps_mach ?perm file sexps = save_of_output ?perm (output_sexps_nl output_mach) file sexps let save_sexps = save_sexps_mach (* String conversions *) let to_string_hum ?indent = function | Atom str -> maybe_esc_str str | sexp -> let buf = buffer () in to_buffer_hum ?indent sexp ~buf; Buffer.contents buf let to_string_mach = function | Atom str -> maybe_esc_str str | sexp -> let buf = buffer () in to_buffer_mach sexp ~buf; Buffer.contents buf let to_string = to_string_mach (* Scan functions *) let scan_sexp ?buf lexbuf = Parser.sexp (Lexer.main ?buf) lexbuf let scan_sexps ?buf lexbuf = Parser.sexps (Lexer.main ?buf) lexbuf let get_main_buf buf = let buf = match buf with | None -> Buffer.create 128 | Some buf -> buf in Lexer.main ~buf let scan_fold_sexps ?buf ~f ~init lexbuf = let main = get_main_buf buf in let rec loop acc = match Parser.sexp_opt main lexbuf with | None -> acc | Some sexp -> loop (f acc sexp) in loop init let scan_iter_sexps ?buf ~f lexbuf = scan_fold_sexps ?buf lexbuf ~init:() ~f:(fun () sexp -> f sexp) let scan_sexps_conv ?buf ~f lexbuf = let coll acc sexp = f sexp :: acc in List.rev (scan_fold_sexps ?buf ~f:coll ~init:[] lexbuf) (* Partial parsing *) module Annot = struct type pos = { line : int; col : int; offset : int } type range = { start_pos : pos; end_pos : pos } type t = Atom of range * Type.t | List of range * t list * Type.t type 'a conv = [ `Result of 'a | `Error of exn * t ] exception Conv_exn of string * exn type stack = { mutable positions : pos list; mutable stack : t list list; } let get_sexp = function Atom (_, sexp) | List (_, _, sexp) -> sexp let get_range = function Atom (range, _) | List (range, _, _) -> range exception Annot_sexp of t let find_sexp annot_sexp sexp = let rec loop annot_sexp = match annot_sexp with | Atom (_, sub_sexp) | List (_, _, sub_sexp) when sexp == sub_sexp -> raise (Annot_sexp annot_sexp) | List (_, annots, _) -> List.iter loop annots | Atom _ -> () in try loop annot_sexp; None with Annot_sexp res -> Some res end module Parse_pos = struct type t = { mutable text_line : int; mutable text_char : int; mutable global_offset : int; mutable buf_pos : int; } let create ?(text_line = 1) ?(text_char = 0) ?(buf_pos = 0) ?(global_offset = 0) () = let fail msg = failwith ("Sexplib.Sexp.Parse_pos.create: " ^ msg) in if text_line < 1 then fail "text_line < 1" else if text_char < 0 then fail "text_char < 0" else if global_offset < 0 then fail "global_offset < 0" else if buf_pos < 0 then fail "buf_pos < 0" else { text_line; text_char; global_offset; buf_pos } let with_buf_pos t buf_pos = { t with buf_pos } end module Cont_state = struct type t = | Parsing_whitespace | Parsing_atom | Parsing_list | Parsing_sexp_comment | Parsing_block_comment let to_string = function | Parsing_whitespace -> "Parsing_whitespace" | Parsing_atom -> "Parsing_atom" | Parsing_list -> "Parsing_list" | Parsing_sexp_comment -> "Parsing_sexp_comment" | Parsing_block_comment -> "Parsing_block_comment" end type ('a, 't) parse_result = | Done of 't * Parse_pos.t | Cont of Cont_state.t * ('a, 't) parse_fun and ('a, 't) parse_fun = pos : int -> len : int -> 'a -> ('a, 't) parse_result type 't parse_state = { parse_pos : Parse_pos.t; mutable pstack : 't; pbuf : Buffer.t; } type parse_error = { location : string; err_msg : string; parse_state : [ | `Sexp of t list list parse_state | `Annot of Annot.stack parse_state ] } exception Parse_error of parse_error let bump_text_line { parse_pos; _ } = parse_pos.Parse_pos.text_line <- parse_pos.Parse_pos.text_line + 1; parse_pos.Parse_pos.text_char <- 0 let bump_text_pos { parse_pos; _ } = parse_pos.Parse_pos.text_char <- parse_pos.Parse_pos.text_char + 1 let bump_pos_cont state str ~max_pos ~pos cont = bump_text_pos state; cont state str ~max_pos ~pos:(pos + 1) let bump_line_cont state str ~max_pos ~pos cont = bump_text_line state; cont state str ~max_pos ~pos:(pos + 1) let add_bump bump state str ~max_pos ~pos c cont = Buffer.add_char state.pbuf c; bump state; cont state str ~max_pos ~pos:(pos + 1) let add_bump_pos state str ~max_pos ~pos c cont = add_bump bump_text_pos state str ~max_pos ~pos c cont let add_bump_line state str ~max_pos ~pos c cont = add_bump bump_text_line state str ~max_pos ~pos c cont let set_parse_pos parse_pos buf_pos = let len = buf_pos - parse_pos.Parse_pos.buf_pos in parse_pos.Parse_pos.buf_pos <- buf_pos; parse_pos.Parse_pos.global_offset <- parse_pos.Parse_pos.global_offset + len let mk_parse_pos { parse_pos; _ } buf_pos = set_parse_pos parse_pos buf_pos; parse_pos let raise_parse_error parse_state location buf_pos err_msg = match parse_state with | `Sexp { parse_pos; _ } | `Annot { parse_pos; _ } -> set_parse_pos parse_pos buf_pos; let parse_error = { location; err_msg; parse_state } in raise (Parse_error parse_error) let raise_unexpected_char parse_state location buf_pos c = let err_msg = sprintf "unexpected character: '%c'" c in raise_parse_error parse_state location buf_pos err_msg let mk_cont_parser cont_parse = (); fun _state str ~max_pos ~pos -> let len = max_pos - pos + 1 in cont_parse ~pos ~len str Macro for generating parsers #define MK_PARSER( \ TYPE, GET_LEN, PARSE, GET_CHAR, \ GET_PSTACK, SET_PSTACK, \ REGISTER_POS, REGISTER_POS1, \ MK_ATOM, MK_LIST, INIT_PSTACK, MK_PARSE_STATE) \ let bump_found_atom bump state str ~max_pos ~pos cont = \ let pbuf = state.pbuf in \ let pbuf_str = Buffer.contents pbuf in \ let atom = MK_ATOM in \ match GET_PSTACK with \ | [] -> Done (atom, mk_parse_pos state pos) \ | rev_sexp_lst :: sexp_stack -> \ Buffer.clear pbuf; \ let pstack = (atom :: rev_sexp_lst) :: sexp_stack in \ SET_PSTACK; \ bump state; \ cont state str ~max_pos ~pos:(pos + 1) \ \ let check_str_bounds loc ~pos ~len (str : TYPE) = \ if pos < 0 then invalid_arg (loc ^ ": pos < 0"); \ if len < 0 then invalid_arg (loc ^ ": len < 0"); \ let str_len = GET_LEN str in \ let pos_len = pos + len in \ if pos_len > str_len then invalid_arg (loc ^ ": pos + len > str_len"); \ pos_len - 1 \ \ let mk_cont_state name cont state ~cont_state = \ let parse_fun = \ let used_ref = ref false in \ fun ~pos ~len str -> \ if !used_ref then \ failwith "Sexplib.Sexp: parser continuation called twice" \ else begin \ used_ref := true; \ let max_pos = check_str_bounds name ~pos ~len str in \ cont state str ~max_pos ~pos \ end \ in \ Cont (cont_state, parse_fun) \ \ let mk_cont name cont state = \ let cont_state = \ match GET_PSTACK = [], Buffer.length state.pbuf = 0 with \ | true, true -> Cont_state.Parsing_whitespace \ | false, true -> Cont_state.Parsing_list \ | _, false -> Cont_state.Parsing_atom \ in \ mk_cont_state name cont state ~cont_state \ \ let rec PARSE state str ~max_pos ~pos = \ if pos > max_pos then mk_cont "parse" PARSE state \ else \ match GET_CHAR with \ | '(' -> \ REGISTER_POS \ let pstack = [] :: GET_PSTACK in \ SET_PSTACK; \ bump_pos_cont state str ~max_pos ~pos PARSE \ | ')' as c -> \ (match GET_PSTACK with \ | [] -> raise_unexpected_char (MK_PARSE_STATE state) "parse" pos c \ | rev_sexp_lst :: sexp_stack -> \ let sexp_lst = List.rev rev_sexp_lst in \ let sexp = MK_LIST in \ match sexp_stack with \ | [] -> Done (sexp, mk_parse_pos state (pos + 1)) \ | higher_rev_sexp_lst :: higher_sexp_stack -> \ let pstack = \ (sexp :: higher_rev_sexp_lst) :: higher_sexp_stack \ in \ SET_PSTACK; \ bump_pos_cont state str ~max_pos ~pos PARSE) \ | ' ' | '\009' | '\012' -> bump_pos_cont state str ~max_pos ~pos PARSE \ | '\010' -> bump_line_cont state str ~max_pos ~pos PARSE \ | '\013' -> bump_pos_cont state str ~max_pos ~pos parse_nl \ | ';' -> bump_pos_cont state str ~max_pos ~pos parse_comment \ | '"' -> \ REGISTER_POS1 \ bump_pos_cont state str ~max_pos ~pos parse_quoted \ | c -> \ REGISTER_POS \ let parse = \ match c with \ | '#' -> maybe_parse_comment \ | '|' -> maybe_parse_close_comment \ | _ -> parse_atom \ in \ add_bump_pos state str ~max_pos ~pos c parse \ \ and parse_nl state str ~max_pos ~pos = \ if pos > max_pos then mk_cont "parse_nl" parse_nl state \ else \ let c = GET_CHAR in \ if c = '\010' then bump_line_cont state str ~max_pos ~pos PARSE \ else raise_unexpected_char (MK_PARSE_STATE state) "parse_nl" pos c \ \ and parse_comment state str ~max_pos ~pos = \ if pos > max_pos then mk_cont "parse_comment" parse_comment state \ else \ match GET_CHAR with \ | '\010' -> bump_line_cont state str ~max_pos ~pos PARSE \ | '\013' -> bump_pos_cont state str ~max_pos ~pos parse_nl \ | _ -> bump_pos_cont state str ~max_pos ~pos parse_comment \ \ and maybe_parse_comment state str ~max_pos ~pos = \ if pos > max_pos then \ mk_cont "maybe_parse_comment" maybe_parse_comment state \ else \ match GET_CHAR with \ | ';' -> bump_pos_cont state str ~max_pos ~pos parse_sexp_comment \ | '|' -> bump_pos_cont state str ~max_pos ~pos parse_block_comment \ | _ -> parse_atom state str ~max_pos ~pos \ \ and maybe_parse_close_comment state str ~max_pos ~pos = \ if pos > max_pos then \ mk_cont "maybe_parse_close_comment" maybe_parse_close_comment state \ else \ if GET_CHAR <> '#' then parse_atom state str ~max_pos ~pos \ else \ let err_msg = "end of block comment without start" in \ raise_parse_error (MK_PARSE_STATE state) \ "maybe_parse_close_comment" pos err_msg \ \ and parse_sexp_comment state str ~max_pos ~pos = \ let pbuf_str = "" in \ ignore (MK_ATOM); \ let old_pstack = GET_PSTACK in \ let pstack = [] in \ SET_PSTACK; \ let rec loop parse state str ~max_pos ~pos = \ Buffer.clear state.pbuf; \ match parse state str ~max_pos ~pos with \ | Done (_sexp, { Parse_pos.buf_pos = pos; _ }) -> \ Buffer.clear state.pbuf; \ let pstack = old_pstack in \ SET_PSTACK; \ PARSE state str ~max_pos ~pos \ | Cont (_, cont_parse) -> \ let parse = mk_cont_parser cont_parse in \ mk_cont_state "parse_sexp_comment" (loop parse) state \ ~cont_state:Cont_state.Parsing_sexp_comment \ in \ loop PARSE state str ~max_pos ~pos \ \ and parse_block_comment ({ pbuf; _ } as state) str ~max_pos ~pos = \ let pbuf_str = "" in \ ignore (MK_ATOM); \ Buffer.clear pbuf; \ let rec loop depth state str ~max_pos ~pos = \ let rec parse_block_depth state str ~max_pos ~pos = \ if pos > max_pos then \ mk_cont "parse_block_depth" parse_block_depth state \ else \ match GET_CHAR with \ | '\010' -> bump_line_cont state str ~max_pos ~pos parse_block_depth \ | '"' -> \ let rec parse_block_quote parse state str ~max_pos ~pos = \ match parse state str ~max_pos ~pos with \ | Done (_sexp, { Parse_pos.buf_pos = pos; _ }) -> \ Buffer.clear pbuf; \ parse_block_depth state str ~max_pos ~pos \ | Cont (_, cont_parse) -> \ let parse = mk_cont_parser cont_parse in \ mk_cont_state "parse_block_quote" \ (parse_block_quote parse) state \ ~cont_state:Cont_state.Parsing_block_comment \ in \ bump_pos_cont state str ~max_pos ~pos \ (parse_block_quote parse_quoted) \ | '#' -> bump_pos_cont state str ~max_pos ~pos parse_open_block \ | '|' -> bump_pos_cont state str ~max_pos ~pos parse_close_block \ | _ -> bump_pos_cont state str ~max_pos ~pos parse_block_depth \ and parse_open_block state str ~max_pos ~pos = \ if pos > max_pos then \ mk_cont "parse_open_block" parse_open_block state \ else \ if GET_CHAR = '|' then \ bump_pos_cont state str ~max_pos ~pos (loop (depth + 1)) \ else parse_block_depth state str ~max_pos ~pos \ and parse_close_block state str ~max_pos ~pos = \ if pos > max_pos then \ mk_cont "parse_close_block" parse_close_block state \ else \ if GET_CHAR = '#' then \ let parse = if depth = 1 then PARSE else loop (depth - 1) in \ bump_pos_cont state str ~max_pos ~pos parse \ else parse_block_depth state str ~max_pos ~pos \ in \ parse_block_depth state str ~max_pos ~pos \ in \ loop 1 state str ~max_pos ~pos \ \ and parse_atom state str ~max_pos ~pos = \ if pos > max_pos then mk_cont "parse_atom" parse_atom state \ else \ match GET_CHAR with \ | ' ' | '\009' | '\012' -> \ bump_found_atom bump_text_pos state str ~max_pos ~pos PARSE \ | '#' as c -> \ add_bump_pos state str ~max_pos ~pos c maybe_parse_bad_atom_hash \ | '|' as c -> \ add_bump_pos state str ~max_pos ~pos c maybe_parse_bad_atom_pipe \ | '(' -> \ let pbuf = state.pbuf in \ let pbuf_str = Buffer.contents pbuf in \ let atom = MK_ATOM in \ (match GET_PSTACK with \ | [] -> Done (atom, mk_parse_pos state pos) \ | rev_sexp_lst :: sexp_stack -> \ REGISTER_POS \ Buffer.clear pbuf; \ let pstack = [] :: (atom :: rev_sexp_lst) :: sexp_stack in \ SET_PSTACK; \ bump_pos_cont state str ~max_pos ~pos PARSE) \ | ')' -> \ let pbuf = state.pbuf in \ let pbuf_str = Buffer.contents pbuf in \ let atom = MK_ATOM in \ (match GET_PSTACK with \ | [] -> Done (atom, mk_parse_pos state pos) \ | rev_sexp_lst :: sexp_stack -> \ let sexp_lst = List.rev_append rev_sexp_lst [atom] in \ let sexp = MK_LIST in \ match sexp_stack with \ | [] -> Done (sexp, mk_parse_pos state (pos + 1)) \ | higher_rev_sexp_lst :: higher_sexp_stack -> \ Buffer.clear pbuf; \ let pstack = \ (sexp :: higher_rev_sexp_lst) :: higher_sexp_stack \ in \ SET_PSTACK; \ bump_pos_cont state str ~max_pos ~pos PARSE) \ | '\010' -> bump_found_atom bump_text_line state str ~max_pos ~pos PARSE \ | '\013' -> \ bump_found_atom bump_text_pos state str ~max_pos ~pos parse_nl \ | ';' -> \ bump_found_atom bump_text_pos state str ~max_pos ~pos parse_comment \ | '"' -> \ bump_found_atom \ bump_text_pos state str ~max_pos ~pos reg_parse_quoted \ | c -> add_bump_pos state str ~max_pos ~pos c parse_atom \ \ and maybe_parse_bad_atom_pipe state str ~max_pos ~pos = \ if pos > max_pos then \ mk_cont "maybe_parse_bad_atom_pipe" maybe_parse_bad_atom_pipe state \ else \ match GET_CHAR with \ | '#' -> \ let err_msg = "illegal end of block comment in unquoted atom" in \ raise_parse_error (MK_PARSE_STATE state) "maybe_parse_bad_atom_pipe" \ pos err_msg \ | _ -> parse_atom state str ~max_pos ~pos \ \ and maybe_parse_bad_atom_hash state str ~max_pos ~pos = \ if pos > max_pos then \ mk_cont "maybe_parse_bad_atom_hash" maybe_parse_bad_atom_hash state \ else \ match GET_CHAR with \ | '|' -> \ let err_msg = "illegal start of block comment in unquoted atom" in \ raise_parse_error (MK_PARSE_STATE state) "maybe_parse_bad_atom_hash" \ pos err_msg \ | _ -> parse_atom state str ~max_pos ~pos \ \ and reg_parse_quoted state str ~max_pos ~pos = \ REGISTER_POS \ parse_quoted state str ~max_pos ~pos \ \ and parse_quoted state str ~max_pos ~pos = \ if pos > max_pos then mk_cont "parse_quoted" parse_quoted state \ else \ match GET_CHAR with \ | '"' -> \ let pbuf = state.pbuf in \ let pbuf_str = Buffer.contents pbuf in \ let atom = MK_ATOM in \ (match GET_PSTACK with \ | [] -> Done (atom, mk_parse_pos state (pos + 1)) \ | rev_sexp_lst :: sexp_stack -> \ Buffer.clear pbuf; \ let pstack = (atom :: rev_sexp_lst) :: sexp_stack in \ SET_PSTACK; \ bump_pos_cont state str ~max_pos ~pos PARSE) \ | '\\' -> bump_pos_cont state str ~max_pos ~pos parse_escaped \ | '\010' as c -> add_bump_line state str ~max_pos ~pos c parse_quoted \ | c -> add_bump_pos state str ~max_pos ~pos c parse_quoted \ \ and parse_escaped state str ~max_pos ~pos = \ if pos > max_pos then mk_cont "parse_escaped" parse_escaped state \ else \ match GET_CHAR with \ | '\010' -> bump_line_cont state str ~max_pos ~pos parse_skip_ws \ | '\013' -> bump_pos_cont state str ~max_pos ~pos parse_skip_ws_nl \ | '0' .. '9' as c -> \ bump_text_pos state; \ let d = Char.code c - 48 in \ parse_dec state str ~max_pos ~pos:(pos + 1) ~count:2 ~d \ | 'x' -> \ bump_text_pos state; \ parse_hex state str ~max_pos ~pos:(pos + 1) ~count:2 ~d:0 \ | ('\\' | '"' | '\'' ) as c -> \ add_bump_pos state str ~max_pos ~pos c parse_quoted \ | 'n' -> add_bump_pos state str ~max_pos ~pos '\n' parse_quoted \ | 't' -> add_bump_pos state str ~max_pos ~pos '\t' parse_quoted \ | 'b' -> add_bump_pos state str ~max_pos ~pos '\b' parse_quoted \ | 'r' -> add_bump_pos state str ~max_pos ~pos '\r' parse_quoted \ | c -> \ Buffer.add_char state.pbuf '\\'; \ add_bump_pos state str ~max_pos ~pos c parse_quoted \ \ and parse_skip_ws state str ~max_pos ~pos = \ if pos > max_pos then mk_cont "parse_skip_ws" parse_skip_ws state \ else \ match GET_CHAR with \ | ' ' | '\009' -> bump_pos_cont state str ~max_pos ~pos parse_skip_ws \ | _ -> parse_quoted state str ~max_pos ~pos \ \ and parse_skip_ws_nl state str ~max_pos ~pos = \ if pos > max_pos then mk_cont "parse_skip_ws_nl" parse_skip_ws_nl state \ else \ if GET_CHAR = '\010' then \ bump_line_cont state str ~max_pos ~pos parse_skip_ws \ else begin \ Buffer.add_char state.pbuf '\013'; \ parse_quoted state str ~max_pos ~pos \ end \ \ and parse_dec state str ~max_pos ~pos ~count ~d = \ if pos > max_pos then mk_cont "parse_dec" (parse_dec ~count ~d) state \ else \ match GET_CHAR with \ | '0' .. '9' as c -> \ let d = 10 * d + Char.code c - 48 in \ if count = 1 then \ if d > 255 then \ let err_msg = sprintf "illegal decimal escape: \\%d" d in \ raise_parse_error (MK_PARSE_STATE state) "parse_dec" pos err_msg \ else \ add_bump_pos state str ~max_pos ~pos (Char.chr d) parse_quoted \ else ( \ bump_text_pos state; \ parse_dec state str ~max_pos ~pos:(pos + 1) ~count:(count - 1) ~d) \ | c -> raise_unexpected_char (MK_PARSE_STATE state) "parse_dec" pos c \ \ and parse_hex state str ~max_pos ~pos ~count ~d = \ if pos > max_pos then mk_cont "parse_hex" (parse_hex ~count ~d) state \ else \ match GET_CHAR with \ | '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' as c -> \ let corr = \ if c >= 'a' then 87 \ else if c >= 'A' then 55 \ else 48 \ in \ let d = 16 * d + Char.code c - corr in \ if count = 1 then \ if d > 255 then \ let err_msg = sprintf "illegal hexadecimal escape: \\%x" d in \ raise_parse_error (MK_PARSE_STATE state) "parse_hex" pos err_msg \ else \ add_bump_pos state str ~max_pos ~pos (Char.chr d) parse_quoted \ else ( \ bump_text_pos state; \ parse_hex state str ~max_pos ~pos:(pos + 1) ~count:(count - 1) ~d) \ | c -> raise_unexpected_char (MK_PARSE_STATE state) "parse_hex" pos c \ \ let PARSE ?(parse_pos = Parse_pos.create ()) ?len str = \ let pos = parse_pos.Parse_pos.buf_pos in \ let len = \ match len with \ | Some len -> len \ | None -> GET_LEN str - pos \ in \ let max_pos = check_str_bounds "parse" ~pos ~len str in \ let state = \ { \ parse_pos; \ pstack = INIT_PSTACK; \ pbuf = Buffer.create 128; \ } \ in \ PARSE state str ~max_pos ~pos MK_PARSER( string, String.length, parse_str, str.[pos], state.pstack, state.pstack <- pstack, ,, Atom pbuf_str, List sexp_lst, [], `Sexp ) let parse = parse_str (* Annot parsers *) let get_glob_ofs parse_pos pos = parse_pos.Parse_pos.global_offset + pos - parse_pos.Parse_pos.buf_pos let mk_annot_pos ({ Parse_pos.text_line = line; text_char = col; _ } as parse_pos) pos = { Annot.line; col; offset = get_glob_ofs parse_pos pos } let mk_annot_pos1 ({ Parse_pos.text_line = line; text_char = col; _ } as parse_pos) pos = { Annot.line; col = col + 1; offset = get_glob_ofs parse_pos pos } let add_annot_pos { parse_pos; pstack; _ } pos = pstack.Annot.positions <- mk_annot_pos parse_pos pos :: pstack.Annot.positions let add_annot_pos1 { parse_pos; pstack; _ } pos = pstack.Annot.positions <- mk_annot_pos1 parse_pos pos :: pstack.Annot.positions let get_annot_range { parse_pos; pstack; _ } pos = let start_pos = match pstack.Annot.positions with | [] -> assert false (* impossible *) | h :: t -> pstack.Annot.positions <- t; h in let end_pos = { Annot. line = parse_pos.Parse_pos.text_line; col = parse_pos.Parse_pos.text_char; offset = get_glob_ofs parse_pos pos; } in { Annot.start_pos; end_pos } let mk_annot_atom parse_state str pos = Annot.Atom (get_annot_range parse_state pos, Atom str) let mk_annot_list parse_state annot_lst pos = let range = get_annot_range parse_state pos in let sexp = List (List.rev (List.rev_map Annot.get_sexp annot_lst)) in Annot.List (range, annot_lst, sexp) let init_annot_pstate () = { Annot.positions = []; stack = [] } MK_PARSER( string, String.length, parse_str_annot, str.[pos], state.pstack.Annot.stack, state.pstack.Annot.stack <- pstack, add_annot_pos state pos;,add_annot_pos1 state pos;, mk_annot_atom state pbuf_str pos, mk_annot_list state sexp_lst pos, init_annot_pstate (), `Annot ) Partial parsing from bigstrings (* NOTE: this is really an awful duplication of the code for parsing strings, but since OCaml does not inline higher-order functions known at compile, other solutions would sacrifice a lot of efficiency. *) MK_PARSER( bigstring, Array1.dim, parse_bigstring, str.{pos}, state.pstack, state.pstack <- pstack, ,, Atom pbuf_str, List sexp_lst, [], `Sexp ) MK_PARSER( bigstring, Array1.dim, parse_bigstring_annot, str.{pos}, state.pstack.Annot.stack, state.pstack.Annot.stack <- pstack, add_annot_pos state pos;,add_annot_pos1 state pos;, mk_annot_atom state pbuf_str pos, mk_annot_list state sexp_lst pos, init_annot_pstate (), `Annot ) (* Input functions *) let mk_this_parse ?parse_pos my_parse = (); fun ~pos ~len str -> let parse_pos = match parse_pos with | None -> Parse_pos.create ~buf_pos:pos () | Some parse_pos -> parse_pos.Parse_pos.buf_pos <- pos; parse_pos in my_parse ?parse_pos:(Some parse_pos) ?len:(Some len) str let gen_input_sexp my_parse ?parse_pos ic = let buf = String.create 1 in let rec loop this_parse = let c = input_char ic in buf.[0] <- c; match this_parse ~pos:0 ~len:1 buf with | Done (sexp, _) -> sexp | Cont (_, this_parse) -> loop this_parse in loop (mk_this_parse ?parse_pos my_parse) let input_sexp ?parse_pos ic = gen_input_sexp parse ?parse_pos ic let gen_input_rev_sexps my_parse ?parse_pos ?(buf = String.create 8192) ic = let rev_sexps_ref = ref [] in let buf_len = String.length buf in let rec loop this_parse ~pos ~len ~cont_state = if len > 0 then match this_parse ~pos ~len buf with | Done (sexp, ({ Parse_pos.buf_pos; _ } as parse_pos)) -> rev_sexps_ref := sexp :: !rev_sexps_ref; let n_parsed = buf_pos - pos in let this_parse = mk_this_parse ~parse_pos my_parse in let cont_state = Cont_state.Parsing_whitespace in if n_parsed = len then let new_len = input ic buf 0 buf_len in loop this_parse ~pos:0 ~len:new_len ~cont_state else loop this_parse ~pos:buf_pos ~len:(len - n_parsed) ~cont_state | Cont (cont_state, this_parse) -> loop this_parse ~pos:0 ~len:(input ic buf 0 buf_len) ~cont_state else if cont_state = Cont_state.Parsing_whitespace then !rev_sexps_ref else failwith ( "Sexplib.Sexp.input_rev_sexps: reached EOF while in state " ^ Cont_state.to_string cont_state) in let len = input ic buf 0 buf_len in let this_parse = mk_this_parse ?parse_pos my_parse in loop this_parse ~pos:0 ~len ~cont_state:Cont_state.Parsing_whitespace let input_rev_sexps ?parse_pos ?buf ic = gen_input_rev_sexps parse ?parse_pos ?buf ic let input_sexps ?parse_pos ?buf ic = List.rev (input_rev_sexps ?parse_pos ?buf ic) of_string and let of_string_bigstring loc this_parse ws_buf get_len get_sub str = match this_parse str with | Done (_, { Parse_pos.buf_pos; _ }) when buf_pos <> get_len str -> let prefix_len = min (get_len str - buf_pos) 20 in let prefix = get_sub str buf_pos prefix_len in let msg = sprintf "Sexplib.Sexp.%s: S-expression followed by data at position %d: %S..." loc buf_pos prefix in failwith msg | Done (sexp, _) -> sexp | Cont (_, this_parse) -> When parsing atoms , the incremental parser can not tell whether it is at the end until it hits whitespace . We therefore feed it one space to determine whether it is finished . it is at the end until it hits whitespace. We therefore feed it one space to determine whether it is finished. *) match this_parse ~pos:0 ~len:1 ws_buf with | Done (sexp, _) -> sexp | Cont (cont_state, _) -> let cont_state_str = Cont_state.to_string cont_state in failwith ( sprintf "Sexplib.Sexp.%s: incomplete S-expression while in state %s: %s" loc cont_state_str (get_sub str 0 (get_len str))) let of_string str = of_string_bigstring "of_string" parse " " String.length String.sub str let get_bstr_sub_str bstr pos len = let str = String.create len in for i = 0 to len - 1 do str.[i] <- bstr.{pos + i} done; str let bstr_ws_buf = Array1.create char c_layout 1 let () = bstr_ws_buf.{0} <- ' ' let of_bigstring bstr = of_string_bigstring "of_bigstring" parse_bigstring bstr_ws_buf Array1.dim get_bstr_sub_str bstr (* Loading *) let gen_load_rev_sexps input_rev_sexps ?buf file = let ic = open_in file in try let sexps = input_rev_sexps ?parse_pos:None ?buf ic in close_in ic; sexps with exc -> close_in_noerr ic; raise exc let load_rev_sexps ?buf file = gen_load_rev_sexps input_rev_sexps ?buf file let load_sexps ?buf file = List.rev (load_rev_sexps ?buf file) let gen_load_sexp my_parse ?(strict = true) ?(buf = String.create 8192) file = let buf_len = String.length buf in let ic = open_in file in let rec loop this_parse ~cont_state = let len = input ic buf 0 buf_len in if len = 0 then failwith ( sprintf "Sexplib.Sexp.gen_load_sexp: EOF in %s while in state %s" file (Cont_state.to_string cont_state)) else match this_parse ~pos:0 ~len buf with | Done (sexp, ({ Parse_pos.buf_pos; _ } as parse_pos)) when strict -> let rec strict_loop this_parse ~pos ~len = match this_parse ~pos ~len buf with | Done _ -> failwith ( sprintf "Sexplib.Sexp.gen_load_sexp: \ more than one S-expression in file %s" file) | Cont (cont_state, this_parse) -> let len = input ic buf 0 buf_len in if len > 0 then strict_loop this_parse ~pos:0 ~len else if cont_state = Cont_state.Parsing_whitespace then sexp else failwith ( sprintf "Sexplib.Sexp.gen_load_sexp: \ additional incomplete data in state %s loading file %s" (Cont_state.to_string cont_state) file) in let this_parse = mk_this_parse ~parse_pos my_parse in strict_loop this_parse ~pos:buf_pos ~len:(len - buf_pos) | Done (sexp, _) -> sexp | Cont (cont_state, this_parse) -> loop this_parse ~cont_state in try let sexp = loop (mk_this_parse my_parse) ~cont_state:Cont_state.Parsing_whitespace in close_in ic; sexp with exc -> close_in_noerr ic; raise exc let load_sexp ?strict ?buf file = gen_load_sexp parse ?strict ?buf file module Annotated = struct include Annot let parse = parse_str_annot let parse_bigstring = parse_bigstring_annot let input_rev_sexps ?parse_pos ?buf ic = gen_input_rev_sexps parse ?parse_pos ?buf ic let input_sexp ?parse_pos ic = gen_input_sexp parse ?parse_pos ic let input_sexps ?parse_pos ?buf ic = List.rev (input_rev_sexps ?parse_pos ?buf ic) let of_string str = of_string_bigstring "Annotated.of_string" parse " " String.length String.sub str let of_bigstring bstr = of_string_bigstring "Annotated.of_bigstring" parse_bigstring bstr_ws_buf Array1.dim get_bstr_sub_str bstr let load_rev_sexps ?buf file = gen_load_rev_sexps input_rev_sexps ?buf file let load_sexps ?buf file = List.rev (load_rev_sexps ?buf file) let load_sexp ?strict ?buf file = gen_load_sexp parse ?strict ?buf file let conv f annot_sexp = let sexp = get_sexp annot_sexp in try `Result (f sexp) with Of_sexp_error (exc, bad_sexp) as e -> match find_sexp annot_sexp bad_sexp with | None -> raise e | Some bad_annot_sexp -> `Error (exc, bad_annot_sexp) let get_conv_exn ~file ~exc annot_sexp = let range = get_range annot_sexp in let { start_pos = { line; col; _ }; _ } = range in let loc = sprintf "%s:%d:%d" file line col in Of_sexp_error (Annot.Conv_exn (loc, exc), get_sexp annot_sexp) end let load_sexp_conv ?(strict = true) ?(buf = String.create 8192) file f = let sexp = load_sexp ~strict ~buf file in try `Result (f sexp) with Of_sexp_error _ -> Annotated.conv f (Annotated.load_sexp ~strict ~buf file) let raise_conv_exn ~file = function | `Result res -> res | `Error (exc, annot_sexp) -> raise (Annotated.get_conv_exn ~file ~exc annot_sexp) let load_sexp_conv_exn ?strict ?buf file f = raise_conv_exn ~file (load_sexp_conv ?strict ?buf file f) let load_sexps_conv ?(buf = String.create 8192) file f = let rev_sexps = load_rev_sexps ~buf file in try List.rev_map (fun sexp -> `Result (f sexp)) rev_sexps with Of_sexp_error _ as e -> match Annotated.load_rev_sexps ~buf file with | [] -> (* File is now empty - perhaps it was a temporary file handle? *) raise e | rev_annot_sexps -> List.rev_map (fun annot_sexp -> Annotated.conv f annot_sexp) rev_annot_sexps let load_sexps_conv_exn ?(buf = String.create 8192) file f = let rev_sexps = load_rev_sexps ~buf file in try List.rev_map f rev_sexps with Of_sexp_error _ as e -> match Annotated.load_rev_sexps ~buf file with | [] -> (* File is now empty - perhaps it was a temporary file handle? *) raise e | rev_annot_sexps -> List.rev_map (fun annot_sexp -> raise_conv_exn ~file (Annotated.conv f annot_sexp)) rev_annot_sexps let gen_of_string_conv of_string annot_of_string str f = let sexp = of_string str in try `Result (f sexp) with Of_sexp_error _ -> Annotated.conv f (annot_of_string str) let of_string_conv str f = gen_of_string_conv of_string Annotated.of_string str f let of_bigstring_conv bstr f = gen_of_string_conv of_bigstring Annotated.of_bigstring bstr f module Of_string_conv_exn = struct type t = { exc : exn; sexp : Type.t; sub_sexp : Type.t } exception E of t end let gen_of_string_conv_exn of_string str f = let sexp = of_string str in try f sexp with Of_sexp_error (exc, sub_sexp) -> raise (Of_string_conv_exn.E { Of_string_conv_exn.exc; sexp; sub_sexp }) let of_string_conv_exn str f = gen_of_string_conv_exn of_string str f let of_bigstring_conv_exn bstr f = gen_of_string_conv_exn of_bigstring bstr f Utilities for automated type conversions let unit = List [] external sexp_of_t : t -> t = "%identity" external t_of_sexp : t -> t = "%identity" Utilities for conversion error handling type found = [ `Found | `Pos of int * found ] type search_result = [ `Not_found | found ] let rec search_physical sexp ~contained = if sexp == contained then `Found else match sexp with | Atom _ -> `Not_found | List lst -> let rec loop i = function | [] -> `Not_found | h :: t -> let res = search_physical h ~contained in match res with | `Not_found -> loop (i + 1) t | #found as found -> `Pos (i, found) in loop 0 lst let rec subst_found sexp ~subst = function | `Found -> subst | `Pos (pos, found) -> match sexp with | Atom _ -> failwith "Sexplib.Sexp.subst_search_result: atom when position requested" | List lst -> let rec loop acc pos = function | [] -> failwith "Sexplib.Sexp.subst_search_result: \ short list when position requested" | h :: t when pos <> 0 -> loop (h :: acc) (pos - 1) t | h :: t -> List (List.rev_append acc (subst_found h ~subst found :: t)) in loop [] pos lst
null
https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/sexplib/lib/pre_sexp.ml
ocaml
Default indentation level for human-readable conversions Escaping of strings used as atoms in S-expressions Output of S-expressions to formatters Buffer conversions Output of S-expressions to I/O-channels Output of S-expressions to file The temp file functions in the OCaml Filename module do not support permissions. But opening a file with given permissions is different from opening it and chmoding it to these permissions, because the umask is taken in account. Under Unix there's no easy way to get the umask in a thread-safe way. String conversions Scan functions Partial parsing Annot parsers impossible NOTE: this is really an awful duplication of the code for parsing strings, but since OCaml does not inline higher-order functions known at compile, other solutions would sacrifice a lot of efficiency. Input functions Loading File is now empty - perhaps it was a temporary file handle? File is now empty - perhaps it was a temporary file handle?
Sexp : Module for handling S - expressions ( I / O , etc . ) open Format open Bigarray include Type exception Of_sexp_error of exn * t type bigstring = (char, int8_unsigned_elt, c_layout) Array1.t let default_indent = ref 1 let must_escape str = let len = String.length str in len = 0 || let rec loop ix = match str.[ix] with | '"' | '(' | ')' | ';' | '\\' -> true | '|' -> ix > 0 && let next = ix - 1 in str.[next] = '#' || loop next | '#' -> ix > 0 && let next = ix - 1 in str.[next] = '|' || loop next | c -> c <= ' ' || ix > 0 && loop (ix - 1) in loop (len - 1) let maybe_esc_str str = if must_escape str then let estr = String.escaped str in let elen = String.length estr in let res = String.create (elen + 2) in String.blit estr 0 res 1 elen; res.[0] <- '"'; res.[elen + 1] <- '"'; res else str let pp_maybe_esc_str ppf str = pp_print_string ppf (maybe_esc_str str) let rec pp_hum_indent indent ppf = function | Atom str -> pp_maybe_esc_str ppf str | List (h :: t) -> pp_open_box ppf indent; pp_print_string ppf "("; pp_hum_indent indent ppf h; pp_hum_rest indent ppf t | List [] -> pp_print_string ppf "()" and pp_hum_rest indent ppf = function | h :: t -> pp_print_space ppf (); pp_hum_indent indent ppf h; pp_hum_rest indent ppf t | [] -> pp_print_string ppf ")"; pp_close_box ppf () let rec pp_mach_internal may_need_space ppf = function | Atom str -> let str' = maybe_esc_str str in let new_may_need_space = str' == str in if may_need_space && new_may_need_space then pp_print_string ppf " "; pp_print_string ppf str'; new_may_need_space | List (h :: t) -> pp_print_string ppf "("; let may_need_space = pp_mach_internal false ppf h in pp_mach_rest may_need_space ppf t; false | List [] -> pp_print_string ppf "()"; false and pp_mach_rest may_need_space ppf = function | h :: t -> let may_need_space = pp_mach_internal may_need_space ppf h in pp_mach_rest may_need_space ppf t | [] -> pp_print_string ppf ")" let pp_hum ppf sexp = pp_hum_indent !default_indent ppf sexp let pp_mach ppf sexp = ignore (pp_mach_internal false ppf sexp) let pp = pp_mach Sexp size let rec size_loop (v, c as acc) = function | Atom str -> v + 1, c + String.length str | List lst -> List.fold_left size_loop acc lst let size sexp = size_loop (0, 0) sexp let to_buffer_hum ~buf ?(indent = !default_indent) sexp = Format.bprintf buf "%a@?" (pp_hum_indent indent) sexp let to_buffer_mach ~buf sexp = let rec loop may_need_space = function | Atom str -> let str' = maybe_esc_str str in let new_may_need_space = str' == str in if may_need_space && new_may_need_space then Buffer.add_char buf ' '; Buffer.add_string buf str'; new_may_need_space | List (h :: t) -> Buffer.add_char buf '('; let may_need_space = loop false h in loop_rest may_need_space t; false | List [] -> Buffer.add_string buf "()"; false and loop_rest may_need_space = function | h :: t -> let may_need_space = loop may_need_space h in loop_rest may_need_space t | [] -> Buffer.add_char buf ')' in ignore (loop false sexp) let to_buffer = to_buffer_mach let to_buffer_gen ~buf ~add_char ~add_string sexp = let rec loop may_need_space = function | Atom str -> let str' = maybe_esc_str str in let new_may_need_space = str' == str in if may_need_space && new_may_need_space then add_char buf ' '; add_string buf str'; new_may_need_space | List (h :: t) -> add_char buf '('; let may_need_space = loop false h in loop_rest may_need_space t; false | List [] -> add_string buf "()"; false and loop_rest may_need_space = function | h :: t -> let may_need_space = loop may_need_space h in loop_rest may_need_space t | [] -> add_char buf ')' in ignore (loop false sexp) The maximum size of a thing on the minor heap is 256 words . Previously , this size of the returned buffer here was 4096 bytes , which caused the Buffer to be allocated on the * major * heap every time . According to a simple benchmark by , we can improve performance for small s - expressions by a factor of ~4 if we only allocate 1024 bytes ( 128 words + some small overhead ) worth of buffer initially . And one can argue that if it 's free to allocate strings smaller than 256 words , large s - expressions requiring larger expensive buffers wo n't notice the extra two doublings from 1024 bytes to 2048 and 4096 . And especially performance - sensitive applications to always pass in a larger buffer to use . Previously, this size of the returned buffer here was 4096 bytes, which caused the Buffer to be allocated on the *major* heap every time. According to a simple benchmark by Ron, we can improve performance for small s-expressions by a factor of ~4 if we only allocate 1024 bytes (128 words + some small overhead) worth of buffer initially. And one can argue that if it's free to allocate strings smaller than 256 words, large s-expressions requiring larger expensive buffers won't notice the extra two doublings from 1024 bytes to 2048 and 4096. And especially performance-sensitive applications to always pass in a larger buffer to use. *) let buffer () = Buffer.create 1024 let with_new_buffer oc f = let buf = buffer () in f buf; Buffer.output_buffer oc buf let output_hum oc sexp = with_new_buffer oc (fun buf -> to_buffer_hum sexp ~buf) let output_hum_indent indent oc sexp = with_new_buffer oc (fun buf -> to_buffer_hum ~indent sexp ~buf) let output_mach oc sexp = with_new_buffer oc (fun buf -> to_buffer_mach sexp ~buf) let output = output_mach module Tmp_file = struct let prng = ref None let temp_file_name prefix suffix = let rand_state = match !prng with | Some v -> v | None -> let ret = Random.State.make_self_init () in prng := Some ret; ret in let rnd = (Random.State.bits rand_state) land 0xFFFFFF in Printf.sprintf "%s%06x%s" prefix rnd suffix let open_temp_file ?(perm = 0o600) prefix suffix = let rec try_name counter = let name = temp_file_name prefix suffix in try let oc = open_out_gen [Open_wronly; Open_creat; Open_excl; Open_text] perm name in name, oc with Sys_error _ as e -> if counter >= 1000 then raise e else try_name (counter + 1) in try_name 0 end let save_of_output ?perm output_function file sexp = let tmp_name, oc = Tmp_file.open_temp_file ?perm file "tmp" in begin try output_function oc sexp; close_out oc; with e -> close_out_noerr oc; begin try Sys.remove tmp_name with _ -> () end; raise e end; Sys.rename tmp_name file let output_sexp_nl do_output oc sexp = do_output oc sexp; output_string oc "\n" let save_hum ?perm file sexp = save_of_output ?perm (output_sexp_nl output_hum) file sexp let save_mach ?perm file sexp = save_of_output ?perm output_mach file sexp let save = save_mach let output_sexps_nl do_output oc sexps = List.iter (output_sexp_nl do_output oc) sexps let save_sexps_hum ?perm file sexps = save_of_output ?perm (output_sexps_nl output_hum) file sexps let save_sexps_mach ?perm file sexps = save_of_output ?perm (output_sexps_nl output_mach) file sexps let save_sexps = save_sexps_mach let to_string_hum ?indent = function | Atom str -> maybe_esc_str str | sexp -> let buf = buffer () in to_buffer_hum ?indent sexp ~buf; Buffer.contents buf let to_string_mach = function | Atom str -> maybe_esc_str str | sexp -> let buf = buffer () in to_buffer_mach sexp ~buf; Buffer.contents buf let to_string = to_string_mach let scan_sexp ?buf lexbuf = Parser.sexp (Lexer.main ?buf) lexbuf let scan_sexps ?buf lexbuf = Parser.sexps (Lexer.main ?buf) lexbuf let get_main_buf buf = let buf = match buf with | None -> Buffer.create 128 | Some buf -> buf in Lexer.main ~buf let scan_fold_sexps ?buf ~f ~init lexbuf = let main = get_main_buf buf in let rec loop acc = match Parser.sexp_opt main lexbuf with | None -> acc | Some sexp -> loop (f acc sexp) in loop init let scan_iter_sexps ?buf ~f lexbuf = scan_fold_sexps ?buf lexbuf ~init:() ~f:(fun () sexp -> f sexp) let scan_sexps_conv ?buf ~f lexbuf = let coll acc sexp = f sexp :: acc in List.rev (scan_fold_sexps ?buf ~f:coll ~init:[] lexbuf) module Annot = struct type pos = { line : int; col : int; offset : int } type range = { start_pos : pos; end_pos : pos } type t = Atom of range * Type.t | List of range * t list * Type.t type 'a conv = [ `Result of 'a | `Error of exn * t ] exception Conv_exn of string * exn type stack = { mutable positions : pos list; mutable stack : t list list; } let get_sexp = function Atom (_, sexp) | List (_, _, sexp) -> sexp let get_range = function Atom (range, _) | List (range, _, _) -> range exception Annot_sexp of t let find_sexp annot_sexp sexp = let rec loop annot_sexp = match annot_sexp with | Atom (_, sub_sexp) | List (_, _, sub_sexp) when sexp == sub_sexp -> raise (Annot_sexp annot_sexp) | List (_, annots, _) -> List.iter loop annots | Atom _ -> () in try loop annot_sexp; None with Annot_sexp res -> Some res end module Parse_pos = struct type t = { mutable text_line : int; mutable text_char : int; mutable global_offset : int; mutable buf_pos : int; } let create ?(text_line = 1) ?(text_char = 0) ?(buf_pos = 0) ?(global_offset = 0) () = let fail msg = failwith ("Sexplib.Sexp.Parse_pos.create: " ^ msg) in if text_line < 1 then fail "text_line < 1" else if text_char < 0 then fail "text_char < 0" else if global_offset < 0 then fail "global_offset < 0" else if buf_pos < 0 then fail "buf_pos < 0" else { text_line; text_char; global_offset; buf_pos } let with_buf_pos t buf_pos = { t with buf_pos } end module Cont_state = struct type t = | Parsing_whitespace | Parsing_atom | Parsing_list | Parsing_sexp_comment | Parsing_block_comment let to_string = function | Parsing_whitespace -> "Parsing_whitespace" | Parsing_atom -> "Parsing_atom" | Parsing_list -> "Parsing_list" | Parsing_sexp_comment -> "Parsing_sexp_comment" | Parsing_block_comment -> "Parsing_block_comment" end type ('a, 't) parse_result = | Done of 't * Parse_pos.t | Cont of Cont_state.t * ('a, 't) parse_fun and ('a, 't) parse_fun = pos : int -> len : int -> 'a -> ('a, 't) parse_result type 't parse_state = { parse_pos : Parse_pos.t; mutable pstack : 't; pbuf : Buffer.t; } type parse_error = { location : string; err_msg : string; parse_state : [ | `Sexp of t list list parse_state | `Annot of Annot.stack parse_state ] } exception Parse_error of parse_error let bump_text_line { parse_pos; _ } = parse_pos.Parse_pos.text_line <- parse_pos.Parse_pos.text_line + 1; parse_pos.Parse_pos.text_char <- 0 let bump_text_pos { parse_pos; _ } = parse_pos.Parse_pos.text_char <- parse_pos.Parse_pos.text_char + 1 let bump_pos_cont state str ~max_pos ~pos cont = bump_text_pos state; cont state str ~max_pos ~pos:(pos + 1) let bump_line_cont state str ~max_pos ~pos cont = bump_text_line state; cont state str ~max_pos ~pos:(pos + 1) let add_bump bump state str ~max_pos ~pos c cont = Buffer.add_char state.pbuf c; bump state; cont state str ~max_pos ~pos:(pos + 1) let add_bump_pos state str ~max_pos ~pos c cont = add_bump bump_text_pos state str ~max_pos ~pos c cont let add_bump_line state str ~max_pos ~pos c cont = add_bump bump_text_line state str ~max_pos ~pos c cont let set_parse_pos parse_pos buf_pos = let len = buf_pos - parse_pos.Parse_pos.buf_pos in parse_pos.Parse_pos.buf_pos <- buf_pos; parse_pos.Parse_pos.global_offset <- parse_pos.Parse_pos.global_offset + len let mk_parse_pos { parse_pos; _ } buf_pos = set_parse_pos parse_pos buf_pos; parse_pos let raise_parse_error parse_state location buf_pos err_msg = match parse_state with | `Sexp { parse_pos; _ } | `Annot { parse_pos; _ } -> set_parse_pos parse_pos buf_pos; let parse_error = { location; err_msg; parse_state } in raise (Parse_error parse_error) let raise_unexpected_char parse_state location buf_pos c = let err_msg = sprintf "unexpected character: '%c'" c in raise_parse_error parse_state location buf_pos err_msg let mk_cont_parser cont_parse = (); fun _state str ~max_pos ~pos -> let len = max_pos - pos + 1 in cont_parse ~pos ~len str Macro for generating parsers #define MK_PARSER( \ TYPE, GET_LEN, PARSE, GET_CHAR, \ GET_PSTACK, SET_PSTACK, \ REGISTER_POS, REGISTER_POS1, \ MK_ATOM, MK_LIST, INIT_PSTACK, MK_PARSE_STATE) \ let bump_found_atom bump state str ~max_pos ~pos cont = \ let pbuf = state.pbuf in \ let pbuf_str = Buffer.contents pbuf in \ let atom = MK_ATOM in \ match GET_PSTACK with \ | [] -> Done (atom, mk_parse_pos state pos) \ | rev_sexp_lst :: sexp_stack -> \ Buffer.clear pbuf; \ let pstack = (atom :: rev_sexp_lst) :: sexp_stack in \ SET_PSTACK; \ bump state; \ cont state str ~max_pos ~pos:(pos + 1) \ \ let check_str_bounds loc ~pos ~len (str : TYPE) = \ if pos < 0 then invalid_arg (loc ^ ": pos < 0"); \ if len < 0 then invalid_arg (loc ^ ": len < 0"); \ let str_len = GET_LEN str in \ let pos_len = pos + len in \ if pos_len > str_len then invalid_arg (loc ^ ": pos + len > str_len"); \ pos_len - 1 \ \ let mk_cont_state name cont state ~cont_state = \ let parse_fun = \ let used_ref = ref false in \ fun ~pos ~len str -> \ if !used_ref then \ failwith "Sexplib.Sexp: parser continuation called twice" \ else begin \ used_ref := true; \ let max_pos = check_str_bounds name ~pos ~len str in \ cont state str ~max_pos ~pos \ end \ in \ Cont (cont_state, parse_fun) \ \ let mk_cont name cont state = \ let cont_state = \ match GET_PSTACK = [], Buffer.length state.pbuf = 0 with \ | true, true -> Cont_state.Parsing_whitespace \ | false, true -> Cont_state.Parsing_list \ | _, false -> Cont_state.Parsing_atom \ in \ mk_cont_state name cont state ~cont_state \ \ let rec PARSE state str ~max_pos ~pos = \ if pos > max_pos then mk_cont "parse" PARSE state \ else \ match GET_CHAR with \ | '(' -> \ REGISTER_POS \ let pstack = [] :: GET_PSTACK in \ SET_PSTACK; \ bump_pos_cont state str ~max_pos ~pos PARSE \ | ')' as c -> \ (match GET_PSTACK with \ | [] -> raise_unexpected_char (MK_PARSE_STATE state) "parse" pos c \ | rev_sexp_lst :: sexp_stack -> \ let sexp_lst = List.rev rev_sexp_lst in \ let sexp = MK_LIST in \ match sexp_stack with \ | [] -> Done (sexp, mk_parse_pos state (pos + 1)) \ | higher_rev_sexp_lst :: higher_sexp_stack -> \ let pstack = \ (sexp :: higher_rev_sexp_lst) :: higher_sexp_stack \ in \ SET_PSTACK; \ bump_pos_cont state str ~max_pos ~pos PARSE) \ | ' ' | '\009' | '\012' -> bump_pos_cont state str ~max_pos ~pos PARSE \ | '\010' -> bump_line_cont state str ~max_pos ~pos PARSE \ | '\013' -> bump_pos_cont state str ~max_pos ~pos parse_nl \ | ';' -> bump_pos_cont state str ~max_pos ~pos parse_comment \ | '"' -> \ REGISTER_POS1 \ bump_pos_cont state str ~max_pos ~pos parse_quoted \ | c -> \ REGISTER_POS \ let parse = \ match c with \ | '#' -> maybe_parse_comment \ | '|' -> maybe_parse_close_comment \ | _ -> parse_atom \ in \ add_bump_pos state str ~max_pos ~pos c parse \ \ and parse_nl state str ~max_pos ~pos = \ if pos > max_pos then mk_cont "parse_nl" parse_nl state \ else \ let c = GET_CHAR in \ if c = '\010' then bump_line_cont state str ~max_pos ~pos PARSE \ else raise_unexpected_char (MK_PARSE_STATE state) "parse_nl" pos c \ \ and parse_comment state str ~max_pos ~pos = \ if pos > max_pos then mk_cont "parse_comment" parse_comment state \ else \ match GET_CHAR with \ | '\010' -> bump_line_cont state str ~max_pos ~pos PARSE \ | '\013' -> bump_pos_cont state str ~max_pos ~pos parse_nl \ | _ -> bump_pos_cont state str ~max_pos ~pos parse_comment \ \ and maybe_parse_comment state str ~max_pos ~pos = \ if pos > max_pos then \ mk_cont "maybe_parse_comment" maybe_parse_comment state \ else \ match GET_CHAR with \ | ';' -> bump_pos_cont state str ~max_pos ~pos parse_sexp_comment \ | '|' -> bump_pos_cont state str ~max_pos ~pos parse_block_comment \ | _ -> parse_atom state str ~max_pos ~pos \ \ and maybe_parse_close_comment state str ~max_pos ~pos = \ if pos > max_pos then \ mk_cont "maybe_parse_close_comment" maybe_parse_close_comment state \ else \ if GET_CHAR <> '#' then parse_atom state str ~max_pos ~pos \ else \ let err_msg = "end of block comment without start" in \ raise_parse_error (MK_PARSE_STATE state) \ "maybe_parse_close_comment" pos err_msg \ \ and parse_sexp_comment state str ~max_pos ~pos = \ let pbuf_str = "" in \ ignore (MK_ATOM); \ let old_pstack = GET_PSTACK in \ let pstack = [] in \ SET_PSTACK; \ let rec loop parse state str ~max_pos ~pos = \ Buffer.clear state.pbuf; \ match parse state str ~max_pos ~pos with \ | Done (_sexp, { Parse_pos.buf_pos = pos; _ }) -> \ Buffer.clear state.pbuf; \ let pstack = old_pstack in \ SET_PSTACK; \ PARSE state str ~max_pos ~pos \ | Cont (_, cont_parse) -> \ let parse = mk_cont_parser cont_parse in \ mk_cont_state "parse_sexp_comment" (loop parse) state \ ~cont_state:Cont_state.Parsing_sexp_comment \ in \ loop PARSE state str ~max_pos ~pos \ \ and parse_block_comment ({ pbuf; _ } as state) str ~max_pos ~pos = \ let pbuf_str = "" in \ ignore (MK_ATOM); \ Buffer.clear pbuf; \ let rec loop depth state str ~max_pos ~pos = \ let rec parse_block_depth state str ~max_pos ~pos = \ if pos > max_pos then \ mk_cont "parse_block_depth" parse_block_depth state \ else \ match GET_CHAR with \ | '\010' -> bump_line_cont state str ~max_pos ~pos parse_block_depth \ | '"' -> \ let rec parse_block_quote parse state str ~max_pos ~pos = \ match parse state str ~max_pos ~pos with \ | Done (_sexp, { Parse_pos.buf_pos = pos; _ }) -> \ Buffer.clear pbuf; \ parse_block_depth state str ~max_pos ~pos \ | Cont (_, cont_parse) -> \ let parse = mk_cont_parser cont_parse in \ mk_cont_state "parse_block_quote" \ (parse_block_quote parse) state \ ~cont_state:Cont_state.Parsing_block_comment \ in \ bump_pos_cont state str ~max_pos ~pos \ (parse_block_quote parse_quoted) \ | '#' -> bump_pos_cont state str ~max_pos ~pos parse_open_block \ | '|' -> bump_pos_cont state str ~max_pos ~pos parse_close_block \ | _ -> bump_pos_cont state str ~max_pos ~pos parse_block_depth \ and parse_open_block state str ~max_pos ~pos = \ if pos > max_pos then \ mk_cont "parse_open_block" parse_open_block state \ else \ if GET_CHAR = '|' then \ bump_pos_cont state str ~max_pos ~pos (loop (depth + 1)) \ else parse_block_depth state str ~max_pos ~pos \ and parse_close_block state str ~max_pos ~pos = \ if pos > max_pos then \ mk_cont "parse_close_block" parse_close_block state \ else \ if GET_CHAR = '#' then \ let parse = if depth = 1 then PARSE else loop (depth - 1) in \ bump_pos_cont state str ~max_pos ~pos parse \ else parse_block_depth state str ~max_pos ~pos \ in \ parse_block_depth state str ~max_pos ~pos \ in \ loop 1 state str ~max_pos ~pos \ \ and parse_atom state str ~max_pos ~pos = \ if pos > max_pos then mk_cont "parse_atom" parse_atom state \ else \ match GET_CHAR with \ | ' ' | '\009' | '\012' -> \ bump_found_atom bump_text_pos state str ~max_pos ~pos PARSE \ | '#' as c -> \ add_bump_pos state str ~max_pos ~pos c maybe_parse_bad_atom_hash \ | '|' as c -> \ add_bump_pos state str ~max_pos ~pos c maybe_parse_bad_atom_pipe \ | '(' -> \ let pbuf = state.pbuf in \ let pbuf_str = Buffer.contents pbuf in \ let atom = MK_ATOM in \ (match GET_PSTACK with \ | [] -> Done (atom, mk_parse_pos state pos) \ | rev_sexp_lst :: sexp_stack -> \ REGISTER_POS \ Buffer.clear pbuf; \ let pstack = [] :: (atom :: rev_sexp_lst) :: sexp_stack in \ SET_PSTACK; \ bump_pos_cont state str ~max_pos ~pos PARSE) \ | ')' -> \ let pbuf = state.pbuf in \ let pbuf_str = Buffer.contents pbuf in \ let atom = MK_ATOM in \ (match GET_PSTACK with \ | [] -> Done (atom, mk_parse_pos state pos) \ | rev_sexp_lst :: sexp_stack -> \ let sexp_lst = List.rev_append rev_sexp_lst [atom] in \ let sexp = MK_LIST in \ match sexp_stack with \ | [] -> Done (sexp, mk_parse_pos state (pos + 1)) \ | higher_rev_sexp_lst :: higher_sexp_stack -> \ Buffer.clear pbuf; \ let pstack = \ (sexp :: higher_rev_sexp_lst) :: higher_sexp_stack \ in \ SET_PSTACK; \ bump_pos_cont state str ~max_pos ~pos PARSE) \ | '\010' -> bump_found_atom bump_text_line state str ~max_pos ~pos PARSE \ | '\013' -> \ bump_found_atom bump_text_pos state str ~max_pos ~pos parse_nl \ | ';' -> \ bump_found_atom bump_text_pos state str ~max_pos ~pos parse_comment \ | '"' -> \ bump_found_atom \ bump_text_pos state str ~max_pos ~pos reg_parse_quoted \ | c -> add_bump_pos state str ~max_pos ~pos c parse_atom \ \ and maybe_parse_bad_atom_pipe state str ~max_pos ~pos = \ if pos > max_pos then \ mk_cont "maybe_parse_bad_atom_pipe" maybe_parse_bad_atom_pipe state \ else \ match GET_CHAR with \ | '#' -> \ let err_msg = "illegal end of block comment in unquoted atom" in \ raise_parse_error (MK_PARSE_STATE state) "maybe_parse_bad_atom_pipe" \ pos err_msg \ | _ -> parse_atom state str ~max_pos ~pos \ \ and maybe_parse_bad_atom_hash state str ~max_pos ~pos = \ if pos > max_pos then \ mk_cont "maybe_parse_bad_atom_hash" maybe_parse_bad_atom_hash state \ else \ match GET_CHAR with \ | '|' -> \ let err_msg = "illegal start of block comment in unquoted atom" in \ raise_parse_error (MK_PARSE_STATE state) "maybe_parse_bad_atom_hash" \ pos err_msg \ | _ -> parse_atom state str ~max_pos ~pos \ \ and reg_parse_quoted state str ~max_pos ~pos = \ REGISTER_POS \ parse_quoted state str ~max_pos ~pos \ \ and parse_quoted state str ~max_pos ~pos = \ if pos > max_pos then mk_cont "parse_quoted" parse_quoted state \ else \ match GET_CHAR with \ | '"' -> \ let pbuf = state.pbuf in \ let pbuf_str = Buffer.contents pbuf in \ let atom = MK_ATOM in \ (match GET_PSTACK with \ | [] -> Done (atom, mk_parse_pos state (pos + 1)) \ | rev_sexp_lst :: sexp_stack -> \ Buffer.clear pbuf; \ let pstack = (atom :: rev_sexp_lst) :: sexp_stack in \ SET_PSTACK; \ bump_pos_cont state str ~max_pos ~pos PARSE) \ | '\\' -> bump_pos_cont state str ~max_pos ~pos parse_escaped \ | '\010' as c -> add_bump_line state str ~max_pos ~pos c parse_quoted \ | c -> add_bump_pos state str ~max_pos ~pos c parse_quoted \ \ and parse_escaped state str ~max_pos ~pos = \ if pos > max_pos then mk_cont "parse_escaped" parse_escaped state \ else \ match GET_CHAR with \ | '\010' -> bump_line_cont state str ~max_pos ~pos parse_skip_ws \ | '\013' -> bump_pos_cont state str ~max_pos ~pos parse_skip_ws_nl \ | '0' .. '9' as c -> \ bump_text_pos state; \ let d = Char.code c - 48 in \ parse_dec state str ~max_pos ~pos:(pos + 1) ~count:2 ~d \ | 'x' -> \ bump_text_pos state; \ parse_hex state str ~max_pos ~pos:(pos + 1) ~count:2 ~d:0 \ | ('\\' | '"' | '\'' ) as c -> \ add_bump_pos state str ~max_pos ~pos c parse_quoted \ | 'n' -> add_bump_pos state str ~max_pos ~pos '\n' parse_quoted \ | 't' -> add_bump_pos state str ~max_pos ~pos '\t' parse_quoted \ | 'b' -> add_bump_pos state str ~max_pos ~pos '\b' parse_quoted \ | 'r' -> add_bump_pos state str ~max_pos ~pos '\r' parse_quoted \ | c -> \ Buffer.add_char state.pbuf '\\'; \ add_bump_pos state str ~max_pos ~pos c parse_quoted \ \ and parse_skip_ws state str ~max_pos ~pos = \ if pos > max_pos then mk_cont "parse_skip_ws" parse_skip_ws state \ else \ match GET_CHAR with \ | ' ' | '\009' -> bump_pos_cont state str ~max_pos ~pos parse_skip_ws \ | _ -> parse_quoted state str ~max_pos ~pos \ \ and parse_skip_ws_nl state str ~max_pos ~pos = \ if pos > max_pos then mk_cont "parse_skip_ws_nl" parse_skip_ws_nl state \ else \ if GET_CHAR = '\010' then \ bump_line_cont state str ~max_pos ~pos parse_skip_ws \ else begin \ Buffer.add_char state.pbuf '\013'; \ parse_quoted state str ~max_pos ~pos \ end \ \ and parse_dec state str ~max_pos ~pos ~count ~d = \ if pos > max_pos then mk_cont "parse_dec" (parse_dec ~count ~d) state \ else \ match GET_CHAR with \ | '0' .. '9' as c -> \ let d = 10 * d + Char.code c - 48 in \ if count = 1 then \ if d > 255 then \ let err_msg = sprintf "illegal decimal escape: \\%d" d in \ raise_parse_error (MK_PARSE_STATE state) "parse_dec" pos err_msg \ else \ add_bump_pos state str ~max_pos ~pos (Char.chr d) parse_quoted \ else ( \ bump_text_pos state; \ parse_dec state str ~max_pos ~pos:(pos + 1) ~count:(count - 1) ~d) \ | c -> raise_unexpected_char (MK_PARSE_STATE state) "parse_dec" pos c \ \ and parse_hex state str ~max_pos ~pos ~count ~d = \ if pos > max_pos then mk_cont "parse_hex" (parse_hex ~count ~d) state \ else \ match GET_CHAR with \ | '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' as c -> \ let corr = \ if c >= 'a' then 87 \ else if c >= 'A' then 55 \ else 48 \ in \ let d = 16 * d + Char.code c - corr in \ if count = 1 then \ if d > 255 then \ let err_msg = sprintf "illegal hexadecimal escape: \\%x" d in \ raise_parse_error (MK_PARSE_STATE state) "parse_hex" pos err_msg \ else \ add_bump_pos state str ~max_pos ~pos (Char.chr d) parse_quoted \ else ( \ bump_text_pos state; \ parse_hex state str ~max_pos ~pos:(pos + 1) ~count:(count - 1) ~d) \ | c -> raise_unexpected_char (MK_PARSE_STATE state) "parse_hex" pos c \ \ let PARSE ?(parse_pos = Parse_pos.create ()) ?len str = \ let pos = parse_pos.Parse_pos.buf_pos in \ let len = \ match len with \ | Some len -> len \ | None -> GET_LEN str - pos \ in \ let max_pos = check_str_bounds "parse" ~pos ~len str in \ let state = \ { \ parse_pos; \ pstack = INIT_PSTACK; \ pbuf = Buffer.create 128; \ } \ in \ PARSE state str ~max_pos ~pos MK_PARSER( string, String.length, parse_str, str.[pos], state.pstack, state.pstack <- pstack, ,, Atom pbuf_str, List sexp_lst, [], `Sexp ) let parse = parse_str let get_glob_ofs parse_pos pos = parse_pos.Parse_pos.global_offset + pos - parse_pos.Parse_pos.buf_pos let mk_annot_pos ({ Parse_pos.text_line = line; text_char = col; _ } as parse_pos) pos = { Annot.line; col; offset = get_glob_ofs parse_pos pos } let mk_annot_pos1 ({ Parse_pos.text_line = line; text_char = col; _ } as parse_pos) pos = { Annot.line; col = col + 1; offset = get_glob_ofs parse_pos pos } let add_annot_pos { parse_pos; pstack; _ } pos = pstack.Annot.positions <- mk_annot_pos parse_pos pos :: pstack.Annot.positions let add_annot_pos1 { parse_pos; pstack; _ } pos = pstack.Annot.positions <- mk_annot_pos1 parse_pos pos :: pstack.Annot.positions let get_annot_range { parse_pos; pstack; _ } pos = let start_pos = match pstack.Annot.positions with | h :: t -> pstack.Annot.positions <- t; h in let end_pos = { Annot. line = parse_pos.Parse_pos.text_line; col = parse_pos.Parse_pos.text_char; offset = get_glob_ofs parse_pos pos; } in { Annot.start_pos; end_pos } let mk_annot_atom parse_state str pos = Annot.Atom (get_annot_range parse_state pos, Atom str) let mk_annot_list parse_state annot_lst pos = let range = get_annot_range parse_state pos in let sexp = List (List.rev (List.rev_map Annot.get_sexp annot_lst)) in Annot.List (range, annot_lst, sexp) let init_annot_pstate () = { Annot.positions = []; stack = [] } MK_PARSER( string, String.length, parse_str_annot, str.[pos], state.pstack.Annot.stack, state.pstack.Annot.stack <- pstack, add_annot_pos state pos;,add_annot_pos1 state pos;, mk_annot_atom state pbuf_str pos, mk_annot_list state sexp_lst pos, init_annot_pstate (), `Annot ) Partial parsing from bigstrings MK_PARSER( bigstring, Array1.dim, parse_bigstring, str.{pos}, state.pstack, state.pstack <- pstack, ,, Atom pbuf_str, List sexp_lst, [], `Sexp ) MK_PARSER( bigstring, Array1.dim, parse_bigstring_annot, str.{pos}, state.pstack.Annot.stack, state.pstack.Annot.stack <- pstack, add_annot_pos state pos;,add_annot_pos1 state pos;, mk_annot_atom state pbuf_str pos, mk_annot_list state sexp_lst pos, init_annot_pstate (), `Annot ) let mk_this_parse ?parse_pos my_parse = (); fun ~pos ~len str -> let parse_pos = match parse_pos with | None -> Parse_pos.create ~buf_pos:pos () | Some parse_pos -> parse_pos.Parse_pos.buf_pos <- pos; parse_pos in my_parse ?parse_pos:(Some parse_pos) ?len:(Some len) str let gen_input_sexp my_parse ?parse_pos ic = let buf = String.create 1 in let rec loop this_parse = let c = input_char ic in buf.[0] <- c; match this_parse ~pos:0 ~len:1 buf with | Done (sexp, _) -> sexp | Cont (_, this_parse) -> loop this_parse in loop (mk_this_parse ?parse_pos my_parse) let input_sexp ?parse_pos ic = gen_input_sexp parse ?parse_pos ic let gen_input_rev_sexps my_parse ?parse_pos ?(buf = String.create 8192) ic = let rev_sexps_ref = ref [] in let buf_len = String.length buf in let rec loop this_parse ~pos ~len ~cont_state = if len > 0 then match this_parse ~pos ~len buf with | Done (sexp, ({ Parse_pos.buf_pos; _ } as parse_pos)) -> rev_sexps_ref := sexp :: !rev_sexps_ref; let n_parsed = buf_pos - pos in let this_parse = mk_this_parse ~parse_pos my_parse in let cont_state = Cont_state.Parsing_whitespace in if n_parsed = len then let new_len = input ic buf 0 buf_len in loop this_parse ~pos:0 ~len:new_len ~cont_state else loop this_parse ~pos:buf_pos ~len:(len - n_parsed) ~cont_state | Cont (cont_state, this_parse) -> loop this_parse ~pos:0 ~len:(input ic buf 0 buf_len) ~cont_state else if cont_state = Cont_state.Parsing_whitespace then !rev_sexps_ref else failwith ( "Sexplib.Sexp.input_rev_sexps: reached EOF while in state " ^ Cont_state.to_string cont_state) in let len = input ic buf 0 buf_len in let this_parse = mk_this_parse ?parse_pos my_parse in loop this_parse ~pos:0 ~len ~cont_state:Cont_state.Parsing_whitespace let input_rev_sexps ?parse_pos ?buf ic = gen_input_rev_sexps parse ?parse_pos ?buf ic let input_sexps ?parse_pos ?buf ic = List.rev (input_rev_sexps ?parse_pos ?buf ic) of_string and let of_string_bigstring loc this_parse ws_buf get_len get_sub str = match this_parse str with | Done (_, { Parse_pos.buf_pos; _ }) when buf_pos <> get_len str -> let prefix_len = min (get_len str - buf_pos) 20 in let prefix = get_sub str buf_pos prefix_len in let msg = sprintf "Sexplib.Sexp.%s: S-expression followed by data at position %d: %S..." loc buf_pos prefix in failwith msg | Done (sexp, _) -> sexp | Cont (_, this_parse) -> When parsing atoms , the incremental parser can not tell whether it is at the end until it hits whitespace . We therefore feed it one space to determine whether it is finished . it is at the end until it hits whitespace. We therefore feed it one space to determine whether it is finished. *) match this_parse ~pos:0 ~len:1 ws_buf with | Done (sexp, _) -> sexp | Cont (cont_state, _) -> let cont_state_str = Cont_state.to_string cont_state in failwith ( sprintf "Sexplib.Sexp.%s: incomplete S-expression while in state %s: %s" loc cont_state_str (get_sub str 0 (get_len str))) let of_string str = of_string_bigstring "of_string" parse " " String.length String.sub str let get_bstr_sub_str bstr pos len = let str = String.create len in for i = 0 to len - 1 do str.[i] <- bstr.{pos + i} done; str let bstr_ws_buf = Array1.create char c_layout 1 let () = bstr_ws_buf.{0} <- ' ' let of_bigstring bstr = of_string_bigstring "of_bigstring" parse_bigstring bstr_ws_buf Array1.dim get_bstr_sub_str bstr let gen_load_rev_sexps input_rev_sexps ?buf file = let ic = open_in file in try let sexps = input_rev_sexps ?parse_pos:None ?buf ic in close_in ic; sexps with exc -> close_in_noerr ic; raise exc let load_rev_sexps ?buf file = gen_load_rev_sexps input_rev_sexps ?buf file let load_sexps ?buf file = List.rev (load_rev_sexps ?buf file) let gen_load_sexp my_parse ?(strict = true) ?(buf = String.create 8192) file = let buf_len = String.length buf in let ic = open_in file in let rec loop this_parse ~cont_state = let len = input ic buf 0 buf_len in if len = 0 then failwith ( sprintf "Sexplib.Sexp.gen_load_sexp: EOF in %s while in state %s" file (Cont_state.to_string cont_state)) else match this_parse ~pos:0 ~len buf with | Done (sexp, ({ Parse_pos.buf_pos; _ } as parse_pos)) when strict -> let rec strict_loop this_parse ~pos ~len = match this_parse ~pos ~len buf with | Done _ -> failwith ( sprintf "Sexplib.Sexp.gen_load_sexp: \ more than one S-expression in file %s" file) | Cont (cont_state, this_parse) -> let len = input ic buf 0 buf_len in if len > 0 then strict_loop this_parse ~pos:0 ~len else if cont_state = Cont_state.Parsing_whitespace then sexp else failwith ( sprintf "Sexplib.Sexp.gen_load_sexp: \ additional incomplete data in state %s loading file %s" (Cont_state.to_string cont_state) file) in let this_parse = mk_this_parse ~parse_pos my_parse in strict_loop this_parse ~pos:buf_pos ~len:(len - buf_pos) | Done (sexp, _) -> sexp | Cont (cont_state, this_parse) -> loop this_parse ~cont_state in try let sexp = loop (mk_this_parse my_parse) ~cont_state:Cont_state.Parsing_whitespace in close_in ic; sexp with exc -> close_in_noerr ic; raise exc let load_sexp ?strict ?buf file = gen_load_sexp parse ?strict ?buf file module Annotated = struct include Annot let parse = parse_str_annot let parse_bigstring = parse_bigstring_annot let input_rev_sexps ?parse_pos ?buf ic = gen_input_rev_sexps parse ?parse_pos ?buf ic let input_sexp ?parse_pos ic = gen_input_sexp parse ?parse_pos ic let input_sexps ?parse_pos ?buf ic = List.rev (input_rev_sexps ?parse_pos ?buf ic) let of_string str = of_string_bigstring "Annotated.of_string" parse " " String.length String.sub str let of_bigstring bstr = of_string_bigstring "Annotated.of_bigstring" parse_bigstring bstr_ws_buf Array1.dim get_bstr_sub_str bstr let load_rev_sexps ?buf file = gen_load_rev_sexps input_rev_sexps ?buf file let load_sexps ?buf file = List.rev (load_rev_sexps ?buf file) let load_sexp ?strict ?buf file = gen_load_sexp parse ?strict ?buf file let conv f annot_sexp = let sexp = get_sexp annot_sexp in try `Result (f sexp) with Of_sexp_error (exc, bad_sexp) as e -> match find_sexp annot_sexp bad_sexp with | None -> raise e | Some bad_annot_sexp -> `Error (exc, bad_annot_sexp) let get_conv_exn ~file ~exc annot_sexp = let range = get_range annot_sexp in let { start_pos = { line; col; _ }; _ } = range in let loc = sprintf "%s:%d:%d" file line col in Of_sexp_error (Annot.Conv_exn (loc, exc), get_sexp annot_sexp) end let load_sexp_conv ?(strict = true) ?(buf = String.create 8192) file f = let sexp = load_sexp ~strict ~buf file in try `Result (f sexp) with Of_sexp_error _ -> Annotated.conv f (Annotated.load_sexp ~strict ~buf file) let raise_conv_exn ~file = function | `Result res -> res | `Error (exc, annot_sexp) -> raise (Annotated.get_conv_exn ~file ~exc annot_sexp) let load_sexp_conv_exn ?strict ?buf file f = raise_conv_exn ~file (load_sexp_conv ?strict ?buf file f) let load_sexps_conv ?(buf = String.create 8192) file f = let rev_sexps = load_rev_sexps ~buf file in try List.rev_map (fun sexp -> `Result (f sexp)) rev_sexps with Of_sexp_error _ as e -> match Annotated.load_rev_sexps ~buf file with | [] -> raise e | rev_annot_sexps -> List.rev_map (fun annot_sexp -> Annotated.conv f annot_sexp) rev_annot_sexps let load_sexps_conv_exn ?(buf = String.create 8192) file f = let rev_sexps = load_rev_sexps ~buf file in try List.rev_map f rev_sexps with Of_sexp_error _ as e -> match Annotated.load_rev_sexps ~buf file with | [] -> raise e | rev_annot_sexps -> List.rev_map (fun annot_sexp -> raise_conv_exn ~file (Annotated.conv f annot_sexp)) rev_annot_sexps let gen_of_string_conv of_string annot_of_string str f = let sexp = of_string str in try `Result (f sexp) with Of_sexp_error _ -> Annotated.conv f (annot_of_string str) let of_string_conv str f = gen_of_string_conv of_string Annotated.of_string str f let of_bigstring_conv bstr f = gen_of_string_conv of_bigstring Annotated.of_bigstring bstr f module Of_string_conv_exn = struct type t = { exc : exn; sexp : Type.t; sub_sexp : Type.t } exception E of t end let gen_of_string_conv_exn of_string str f = let sexp = of_string str in try f sexp with Of_sexp_error (exc, sub_sexp) -> raise (Of_string_conv_exn.E { Of_string_conv_exn.exc; sexp; sub_sexp }) let of_string_conv_exn str f = gen_of_string_conv_exn of_string str f let of_bigstring_conv_exn bstr f = gen_of_string_conv_exn of_bigstring bstr f Utilities for automated type conversions let unit = List [] external sexp_of_t : t -> t = "%identity" external t_of_sexp : t -> t = "%identity" Utilities for conversion error handling type found = [ `Found | `Pos of int * found ] type search_result = [ `Not_found | found ] let rec search_physical sexp ~contained = if sexp == contained then `Found else match sexp with | Atom _ -> `Not_found | List lst -> let rec loop i = function | [] -> `Not_found | h :: t -> let res = search_physical h ~contained in match res with | `Not_found -> loop (i + 1) t | #found as found -> `Pos (i, found) in loop 0 lst let rec subst_found sexp ~subst = function | `Found -> subst | `Pos (pos, found) -> match sexp with | Atom _ -> failwith "Sexplib.Sexp.subst_search_result: atom when position requested" | List lst -> let rec loop acc pos = function | [] -> failwith "Sexplib.Sexp.subst_search_result: \ short list when position requested" | h :: t when pos <> 0 -> loop (h :: acc) (pos - 1) t | h :: t -> List (List.rev_append acc (subst_found h ~subst found :: t)) in loop [] pos lst
da768cc5757bf6a335ddc3f8e44d8b7675e0fe5aa92e4b2f9c9466aba499e3a9
threatgrid/ctim
valid_time_test.clj
(ns ctim.schemas.valid-time-test (:require [clj-momo.lib.clj-time.core :as time] [clojure.spec.alpha :as s] [clojure.test :refer [deftest is testing use-fixtures]] [ctim.schemas.judgement :as j] [ctim.test-helpers.core :as th] [ctim.examples.judgements :as e] [flanders.spec :as fs])) (use-fixtures :once th/fixture-spec-validation (th/fixture-spec j/Judgement "test.judgement")) (deftest test-judgement-valid-time-spec-validation (testing "valid valid_time" (is (s/valid? :test.judgement/map (assoc e/judgement-minimal :valid_time {}))) (is (s/valid? :test.judgement/map (assoc e/judgement-minimal :valid_time {:start_time (time/internal-date 2017 10 1)}))) (is (s/valid? :test.judgement/map (assoc e/judgement-minimal :valid_time {:end_time (time/internal-date 2017 10 1)}))) (is (s/valid? :test.judgement/map (assoc e/judgement-minimal :valid_time {:start_time (time/internal-date 2017 10 1) :end_time (time/internal-date 2017 10 2)}))) (is (s/valid? :test.judgement/map (assoc e/judgement-minimal :valid_time {:start_time (time/internal-date 2017 10 1) :end_time (time/internal-date 2017 10 1)})))) (testing "invalid valid_time" (is ((complement s/valid?) :test.judgement/map (assoc e/judgement-minimal :valid_time {:start_time (time/internal-date 2017 10 2) :end_time (time/internal-date 2017 10 1)})))))
null
https://raw.githubusercontent.com/threatgrid/ctim/2ecae70682e69495cc3a12fd58a474d4ea57ae9c/test/ctim/schemas/valid_time_test.clj
clojure
(ns ctim.schemas.valid-time-test (:require [clj-momo.lib.clj-time.core :as time] [clojure.spec.alpha :as s] [clojure.test :refer [deftest is testing use-fixtures]] [ctim.schemas.judgement :as j] [ctim.test-helpers.core :as th] [ctim.examples.judgements :as e] [flanders.spec :as fs])) (use-fixtures :once th/fixture-spec-validation (th/fixture-spec j/Judgement "test.judgement")) (deftest test-judgement-valid-time-spec-validation (testing "valid valid_time" (is (s/valid? :test.judgement/map (assoc e/judgement-minimal :valid_time {}))) (is (s/valid? :test.judgement/map (assoc e/judgement-minimal :valid_time {:start_time (time/internal-date 2017 10 1)}))) (is (s/valid? :test.judgement/map (assoc e/judgement-minimal :valid_time {:end_time (time/internal-date 2017 10 1)}))) (is (s/valid? :test.judgement/map (assoc e/judgement-minimal :valid_time {:start_time (time/internal-date 2017 10 1) :end_time (time/internal-date 2017 10 2)}))) (is (s/valid? :test.judgement/map (assoc e/judgement-minimal :valid_time {:start_time (time/internal-date 2017 10 1) :end_time (time/internal-date 2017 10 1)})))) (testing "invalid valid_time" (is ((complement s/valid?) :test.judgement/map (assoc e/judgement-minimal :valid_time {:start_time (time/internal-date 2017 10 2) :end_time (time/internal-date 2017 10 1)})))))
adda98bab8a055f9f40315230b639bd5fe124e547c0e7a9847ae8e97997860a8
MinaProtocol/mina
js_util.ml
-- types and transformers for Javascript open Js_of_ocaml open Snark_params.Tick open Mina_base module Global_slot = Mina_numbers.Global_slot module Memo = Signed_command_memo let raise_js_error s = Js_error.(raise_ @@ of_error (new%js Js.error_constr (Js.string s))) type string_js = Js.js_string Js.t type keypair_js = < privateKey : string_js Js.readonly_prop ; publicKey : string_js Js.readonly_prop > Js.t type payload_common_js = < fee : string_js Js.prop ; feePayer : string_js Js.prop ; nonce : string_js Js.prop ; validUntil : string_js Js.prop ; memo : string_js Js.prop > Js.t type payload_fee_payer_js = < fee : string_js Js.prop ; feePayer : string_js Js.prop ; nonce : string_js Js.prop ; memo : string_js Js.prop > Js.t let payload_of_fee_payer_js (fee_payer_js : payload_fee_payer_js) : Account_update.Fee_payer.t = let fee_payer_pk = fee_payer_js##.feePayer |> Js.to_string |> Signature_lib.Public_key.of_base58_check_decompress_exn in let fee = fee_payer_js##.fee |> Js.to_string |> Currency.Fee.of_string in let nonce = fee_payer_js##.nonce |> Js.to_string |> Mina_numbers.Account_nonce.of_string in { Account_update.Fee_payer.body = { public_key = fee_payer_pk; fee; valid_until = None; nonce } ; authorization = Signature.dummy } let payload_common_of_js (payload_common_js : payload_common_js) = let fee_js = payload_common_js##.fee in let fee = Js.to_string fee_js |> Currency.Fee.of_string in let fee_payer_pk = payload_common_js##.feePayer |> Js.to_string |> Signature_lib.Public_key.of_base58_check_decompress_exn in let nonce_js = payload_common_js##.nonce in let nonce = Js.to_string nonce_js |> Mina_numbers.Account_nonce.of_string in let valid_until_js = payload_common_js##.validUntil in let valid_until = Js.to_string valid_until_js |> Global_slot.of_string in let memo_js = payload_common_js##.memo in let memo = Js.to_string memo_js |> Memo.create_from_string_exn in Signed_command_payload.Common.Poly. { fee; fee_payer_pk; nonce; valid_until; memo } type payment_payload_js = < source : string_js Js.prop ; receiver : string_js Js.prop ; amount : string_js Js.prop > Js.t type payment_js = < common : payload_common_js Js.prop ; paymentPayload : payment_payload_js Js.prop > Js.t let payment_body_of_js payment_payload = let source_pk = payment_payload##.source |> Js.to_string |> Signature_lib.Public_key.of_base58_check_decompress_exn in let receiver_pk = payment_payload##.receiver |> Js.to_string |> Signature_lib.Public_key.of_base58_check_decompress_exn in let amount = payment_payload##.amount |> Js.to_string |> Currency.Amount.of_string in Signed_command_payload.Body.Payment Payment_payload.Poly.{ source_pk; receiver_pk; amount } let payload_of_payment_js payment_js : Signed_command_payload.t = let common = payload_common_of_js payment_js##.common in let body = payment_body_of_js payment_js##.paymentPayload in Signed_command_payload.Poly.{ common; body } type stake_delegation_payload_js = < delegator : string_js Js.prop ; newDelegate : string_js Js.prop > Js.t type stake_delegation_js = < common : payload_common_js Js.prop ; delegationPayload : stake_delegation_payload_js Js.prop > Js.t let stake_delegation_body_of_js delegation_payload = let delegator = Js.to_string delegation_payload##.delegator |> Signature_lib.Public_key.of_base58_check_decompress_exn in let new_delegate = Js.to_string delegation_payload##.newDelegate |> Signature_lib.Public_key.of_base58_check_decompress_exn in Signed_command_payload.Body.Stake_delegation (Set_delegate { delegator; new_delegate }) let payload_of_stake_delegation_js payment_js : Signed_command_payload.t = let common = payload_common_of_js payment_js##.common in let body = stake_delegation_body_of_js payment_js##.delegationPayload in Signed_command_payload.Poly.{ common; body } type signature_js = < field : string_js Js.readonly_prop ; scalar : string_js Js.readonly_prop > Js.t let signature_to_js_object ((field, scalar) : Signature.t) = object%js val field = Field.to_string field |> Js.string val scalar = Inner_curve.Scalar.to_string scalar |> Js.string end let signature_of_js_object (signature_js : signature_js) : Signature.t = let field = signature_js##.field |> Js.to_string |> Field.of_string in let scalar = signature_js##.scalar |> Js.to_string |> Inner_curve.Scalar.of_string in (field, scalar) type signed_string = < string : string_js Js.readonly_prop ; signer : string_js Js.readonly_prop ; signature : signature_js Js.readonly_prop > Js.t type signed_payment = < payment : payment_js Js.readonly_prop ; sender : string_js Js.readonly_prop ; signature : signature_js Js.readonly_prop > Js.t type signed_stake_delegation = < stakeDelegation : stake_delegation_js Js.readonly_prop ; sender : string_js Js.readonly_prop ; signature : signature_js Js.readonly_prop > Js.t let signature_kind_of_string_js network_js fname : Mina_signature_kind.t = match Js.to_string network_js |> Base.String.lowercase with | "mainnet" -> Mainnet | "testnet" -> Testnet | s -> raise_js_error (Core_kernel.sprintf "%s: expected network to be mainnet or testnet, got: %s" fname s )
null
https://raw.githubusercontent.com/MinaProtocol/mina/778f499316fe439a7a843f91cd3c6e05484b3f7d/src/app/client_sdk/js_util.ml
ocaml
-- types and transformers for Javascript open Js_of_ocaml open Snark_params.Tick open Mina_base module Global_slot = Mina_numbers.Global_slot module Memo = Signed_command_memo let raise_js_error s = Js_error.(raise_ @@ of_error (new%js Js.error_constr (Js.string s))) type string_js = Js.js_string Js.t type keypair_js = < privateKey : string_js Js.readonly_prop ; publicKey : string_js Js.readonly_prop > Js.t type payload_common_js = < fee : string_js Js.prop ; feePayer : string_js Js.prop ; nonce : string_js Js.prop ; validUntil : string_js Js.prop ; memo : string_js Js.prop > Js.t type payload_fee_payer_js = < fee : string_js Js.prop ; feePayer : string_js Js.prop ; nonce : string_js Js.prop ; memo : string_js Js.prop > Js.t let payload_of_fee_payer_js (fee_payer_js : payload_fee_payer_js) : Account_update.Fee_payer.t = let fee_payer_pk = fee_payer_js##.feePayer |> Js.to_string |> Signature_lib.Public_key.of_base58_check_decompress_exn in let fee = fee_payer_js##.fee |> Js.to_string |> Currency.Fee.of_string in let nonce = fee_payer_js##.nonce |> Js.to_string |> Mina_numbers.Account_nonce.of_string in { Account_update.Fee_payer.body = { public_key = fee_payer_pk; fee; valid_until = None; nonce } ; authorization = Signature.dummy } let payload_common_of_js (payload_common_js : payload_common_js) = let fee_js = payload_common_js##.fee in let fee = Js.to_string fee_js |> Currency.Fee.of_string in let fee_payer_pk = payload_common_js##.feePayer |> Js.to_string |> Signature_lib.Public_key.of_base58_check_decompress_exn in let nonce_js = payload_common_js##.nonce in let nonce = Js.to_string nonce_js |> Mina_numbers.Account_nonce.of_string in let valid_until_js = payload_common_js##.validUntil in let valid_until = Js.to_string valid_until_js |> Global_slot.of_string in let memo_js = payload_common_js##.memo in let memo = Js.to_string memo_js |> Memo.create_from_string_exn in Signed_command_payload.Common.Poly. { fee; fee_payer_pk; nonce; valid_until; memo } type payment_payload_js = < source : string_js Js.prop ; receiver : string_js Js.prop ; amount : string_js Js.prop > Js.t type payment_js = < common : payload_common_js Js.prop ; paymentPayload : payment_payload_js Js.prop > Js.t let payment_body_of_js payment_payload = let source_pk = payment_payload##.source |> Js.to_string |> Signature_lib.Public_key.of_base58_check_decompress_exn in let receiver_pk = payment_payload##.receiver |> Js.to_string |> Signature_lib.Public_key.of_base58_check_decompress_exn in let amount = payment_payload##.amount |> Js.to_string |> Currency.Amount.of_string in Signed_command_payload.Body.Payment Payment_payload.Poly.{ source_pk; receiver_pk; amount } let payload_of_payment_js payment_js : Signed_command_payload.t = let common = payload_common_of_js payment_js##.common in let body = payment_body_of_js payment_js##.paymentPayload in Signed_command_payload.Poly.{ common; body } type stake_delegation_payload_js = < delegator : string_js Js.prop ; newDelegate : string_js Js.prop > Js.t type stake_delegation_js = < common : payload_common_js Js.prop ; delegationPayload : stake_delegation_payload_js Js.prop > Js.t let stake_delegation_body_of_js delegation_payload = let delegator = Js.to_string delegation_payload##.delegator |> Signature_lib.Public_key.of_base58_check_decompress_exn in let new_delegate = Js.to_string delegation_payload##.newDelegate |> Signature_lib.Public_key.of_base58_check_decompress_exn in Signed_command_payload.Body.Stake_delegation (Set_delegate { delegator; new_delegate }) let payload_of_stake_delegation_js payment_js : Signed_command_payload.t = let common = payload_common_of_js payment_js##.common in let body = stake_delegation_body_of_js payment_js##.delegationPayload in Signed_command_payload.Poly.{ common; body } type signature_js = < field : string_js Js.readonly_prop ; scalar : string_js Js.readonly_prop > Js.t let signature_to_js_object ((field, scalar) : Signature.t) = object%js val field = Field.to_string field |> Js.string val scalar = Inner_curve.Scalar.to_string scalar |> Js.string end let signature_of_js_object (signature_js : signature_js) : Signature.t = let field = signature_js##.field |> Js.to_string |> Field.of_string in let scalar = signature_js##.scalar |> Js.to_string |> Inner_curve.Scalar.of_string in (field, scalar) type signed_string = < string : string_js Js.readonly_prop ; signer : string_js Js.readonly_prop ; signature : signature_js Js.readonly_prop > Js.t type signed_payment = < payment : payment_js Js.readonly_prop ; sender : string_js Js.readonly_prop ; signature : signature_js Js.readonly_prop > Js.t type signed_stake_delegation = < stakeDelegation : stake_delegation_js Js.readonly_prop ; sender : string_js Js.readonly_prop ; signature : signature_js Js.readonly_prop > Js.t let signature_kind_of_string_js network_js fname : Mina_signature_kind.t = match Js.to_string network_js |> Base.String.lowercase with | "mainnet" -> Mainnet | "testnet" -> Testnet | s -> raise_js_error (Core_kernel.sprintf "%s: expected network to be mainnet or testnet, got: %s" fname s )
fe412d0063c68bc40d4c87f62d7c3ba315318e17697b855e213a2b4c11fb2e2f
e-bigmoon/haskell-blog
Quiz12.hs
#!/usr/bin/env stack -- stack script --resolver lts-11.17 import Conduit main:: IO () main = runConduit $ yieldMany [1..10] .| iterMC print .| sinkNull
null
https://raw.githubusercontent.com/e-bigmoon/haskell-blog/5c9e7c25f31ea6856c5d333e8e991dbceab21c56/quiz/Quiz12/Quiz12.hs
haskell
stack script --resolver lts-11.17
#!/usr/bin/env stack import Conduit main:: IO () main = runConduit $ yieldMany [1..10] .| iterMC print .| sinkNull
e5ffa22931525566ccc6d419bda47aba9bbba274227c595111d1a26f3c764b6e
gafiatulin/codewars
MakeUpper.hs
MakeUpperCase module MakeUpper where import Data.Char (toUpper) makeUpperCase :: String -> String makeUpperCase = map toUpper
null
https://raw.githubusercontent.com/gafiatulin/codewars/535db608333e854be93ecfc165686a2162264fef/src/8%20kyu/MakeUpper.hs
haskell
MakeUpperCase module MakeUpper where import Data.Char (toUpper) makeUpperCase :: String -> String makeUpperCase = map toUpper
e904462197026c101703ea900650c80ae64190dee114e89d2fcfb43d19308dd6
goncalotomas/FMKe
fmke_gen_http_handler.erl
%% Default behaviour for a generic HTTP handler. -module (fmke_gen_http_handler). -include ("fmke_http.hrl"). -export ([init/3, handle_req/5, handle_reply/5]). -callback init(Req::cowboy_req:req(), State::any()) -> {ok, cowboy_req:req(), any()}. -callback handle_req(Method::binary(), HasBody::boolean(), Req::cowboy_req:req()) -> cowboy_req:req(). -callback perform_operation(Method::binary(), Req::cowboy_req:req(), UrlParamsFound::list({atom(), binary()}), BodyParamsFound::list({atom(), any()})) -> cowboy_req:req(). %% Every requests starts being processed at the init function, and processing is %% identical throughout all modules that implement this behaviour, so this function %% reduces code duplication. init(Mod, Req, State) -> try Method = cowboy_req:method(Req), HasBody = cowboy_req:has_body(Req), Req1 = Mod:handle_req(Method, HasBody, Req), {ok, Req1, State} catch Class:Reason -> lager:error(io_lib:format("Error ~p:~p in request from ~p~n", [Class, Reason, Mod])), Req2 = handle_reply(Mod, Req, {error, internal}, false, Reason), {ok, Req2, State} end. %% Processing any request has a pattern that involves acquiring necessary parameters %% from the URL and/or HTTP body, executing an operation on the `fmke` module and %% replying back with an answer. -spec handle_req(Mod::atom(), Method::binary(), Req::cowboy_req:req(), UrlParams::list(atom()), BodyParams::list({atom(), integer | string})) -> cowboy_req:req(). handle_req(Mod, <<"GET">>, Req, UrlParams, _) -> try Bindings = cowboy_req:bindings(Req), UrlParamsFound = lists:foldl(fun(Param, Accum) -> case maps:get(Param, Bindings, undefined) of undefined -> Accum; Val -> [{Param, Val} | Accum] end end, [], UrlParams), Mod:perform_operation(<<"GET">>, Req, lists:reverse(UrlParamsFound), []) catch error:ErrReason -> handle_reply(Mod, Req, {error, internal}, false, ErrReason); _:ExReason -> handle_reply(Mod, Req, {error, internal}, false, ExReason) end; handle_req(Mod, Method, Req, UrlParams, BodyParams) -> try {ok, Body, Req1} = cowboy_req:read_body(Req), Bindings = cowboy_req:bindings(Req1), UrlParamsFound = lists:foldl(fun(Param, Accum) -> case maps:get(Param, Bindings, undefined) of undefined -> Accum; Val -> lists:append(Accum, [{Param, Val}]) end end, [], UrlParams), BodyParamsFound = fmke_http_utils:parse_body(BodyParams, Body), case BodyParamsFound of [] -> handle_reply(Mod, Req, {error, bad_req}, false, ?ERR_MISSING_BODY); _List -> case proplists:get_keys(BodyParamsFound) =:= proplists:get_keys(BodyParams) of true -> %% All body params that were requested have been found Mod:perform_operation(Method, Req1, UrlParamsFound, BodyParamsFound); false -> Some body parameters are missing , let decide what to do Mod:perform_operation(Method, Req1, UrlParamsFound, {incomplete, BodyParamsFound}) end end catch error:ErrReason -> handle_reply(Mod, Req, {error, internal}, false, ErrReason); _:ExReason -> handle_reply(Mod, Req, {error, internal}, false, ExReason) end. handle_reply(_Mod, Req, ok, Success, Result) -> cowboy_req:reply(200, ?CONT_TYPE_JSON, ?ENCODE_RESPONSE(Success, Result), Req); handle_reply(_Mod, Req, {error, bad_req}, false, Result) -> cowboy_req:reply(400, ?CONT_TYPE_JSON, ?ENCODE_FAIL(Result), Req); handle_reply(Mod, Req, {error, internal}, false, Reason) -> Method = binary_to_list(cowboy_req:method(Req)), Uri = binary_to_list(cowboy_req:path(Req)), lager:error(io_lib:format("Internal error in ~p for operation ~p ~p: ~p~n", [Mod, Method, Uri, Reason])), cowboy_req:reply(500, ?CONT_TYPE_JSON, ?ENCODE_SRV_ERR, Req).
null
https://raw.githubusercontent.com/goncalotomas/FMKe/654d3211ef57d841540e58033a397ce0f3dee0f7/src/fmke_gen_http_handler.erl
erlang
Default behaviour for a generic HTTP handler. Every requests starts being processed at the init function, and processing is identical throughout all modules that implement this behaviour, so this function reduces code duplication. Processing any request has a pattern that involves acquiring necessary parameters from the URL and/or HTTP body, executing an operation on the `fmke` module and replying back with an answer. All body params that were requested have been found
-module (fmke_gen_http_handler). -include ("fmke_http.hrl"). -export ([init/3, handle_req/5, handle_reply/5]). -callback init(Req::cowboy_req:req(), State::any()) -> {ok, cowboy_req:req(), any()}. -callback handle_req(Method::binary(), HasBody::boolean(), Req::cowboy_req:req()) -> cowboy_req:req(). -callback perform_operation(Method::binary(), Req::cowboy_req:req(), UrlParamsFound::list({atom(), binary()}), BodyParamsFound::list({atom(), any()})) -> cowboy_req:req(). init(Mod, Req, State) -> try Method = cowboy_req:method(Req), HasBody = cowboy_req:has_body(Req), Req1 = Mod:handle_req(Method, HasBody, Req), {ok, Req1, State} catch Class:Reason -> lager:error(io_lib:format("Error ~p:~p in request from ~p~n", [Class, Reason, Mod])), Req2 = handle_reply(Mod, Req, {error, internal}, false, Reason), {ok, Req2, State} end. -spec handle_req(Mod::atom(), Method::binary(), Req::cowboy_req:req(), UrlParams::list(atom()), BodyParams::list({atom(), integer | string})) -> cowboy_req:req(). handle_req(Mod, <<"GET">>, Req, UrlParams, _) -> try Bindings = cowboy_req:bindings(Req), UrlParamsFound = lists:foldl(fun(Param, Accum) -> case maps:get(Param, Bindings, undefined) of undefined -> Accum; Val -> [{Param, Val} | Accum] end end, [], UrlParams), Mod:perform_operation(<<"GET">>, Req, lists:reverse(UrlParamsFound), []) catch error:ErrReason -> handle_reply(Mod, Req, {error, internal}, false, ErrReason); _:ExReason -> handle_reply(Mod, Req, {error, internal}, false, ExReason) end; handle_req(Mod, Method, Req, UrlParams, BodyParams) -> try {ok, Body, Req1} = cowboy_req:read_body(Req), Bindings = cowboy_req:bindings(Req1), UrlParamsFound = lists:foldl(fun(Param, Accum) -> case maps:get(Param, Bindings, undefined) of undefined -> Accum; Val -> lists:append(Accum, [{Param, Val}]) end end, [], UrlParams), BodyParamsFound = fmke_http_utils:parse_body(BodyParams, Body), case BodyParamsFound of [] -> handle_reply(Mod, Req, {error, bad_req}, false, ?ERR_MISSING_BODY); _List -> case proplists:get_keys(BodyParamsFound) =:= proplists:get_keys(BodyParams) of true -> Mod:perform_operation(Method, Req1, UrlParamsFound, BodyParamsFound); false -> Some body parameters are missing , let decide what to do Mod:perform_operation(Method, Req1, UrlParamsFound, {incomplete, BodyParamsFound}) end end catch error:ErrReason -> handle_reply(Mod, Req, {error, internal}, false, ErrReason); _:ExReason -> handle_reply(Mod, Req, {error, internal}, false, ExReason) end. handle_reply(_Mod, Req, ok, Success, Result) -> cowboy_req:reply(200, ?CONT_TYPE_JSON, ?ENCODE_RESPONSE(Success, Result), Req); handle_reply(_Mod, Req, {error, bad_req}, false, Result) -> cowboy_req:reply(400, ?CONT_TYPE_JSON, ?ENCODE_FAIL(Result), Req); handle_reply(Mod, Req, {error, internal}, false, Reason) -> Method = binary_to_list(cowboy_req:method(Req)), Uri = binary_to_list(cowboy_req:path(Req)), lager:error(io_lib:format("Internal error in ~p for operation ~p ~p: ~p~n", [Mod, Method, Uri, Reason])), cowboy_req:reply(500, ?CONT_TYPE_JSON, ?ENCODE_SRV_ERR, Req).
b9f70ad1b4863cfd91c833c914cd405ccebcaa26b1aa2d4629014d644e185e5a
brendanhay/terrafomo
Types.hs
-- This module was auto-generated. If it is modified, it will not be overwritten. -- | Module : . Spotinst . Types Copyright : ( c ) 2017 - 2018 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) -- module Terrafomo.Spotinst.Types where import Data . Text ( Text ) import Terrafomo -- import Formatting (Format, (%)) import Terrafomo . Spotinst . Lens import qualified Terrafomo . Attribute as TF import qualified Terrafomo . HCL as TF import qualified Terrafomo . Name as TF import qualified Terrafomo . Provider as TF import qualified Terrafomo . Schema as TF
null
https://raw.githubusercontent.com/brendanhay/terrafomo/387a0e9341fb9cd5543ef8332dea126f50f1070e/provider/terrafomo-spotinst/src/Terrafomo/Spotinst/Types.hs
haskell
This module was auto-generated. If it is modified, it will not be overwritten. | Stability : auto-generated import Formatting (Format, (%))
Module : . Spotinst . Types Copyright : ( c ) 2017 - 2018 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Terrafomo.Spotinst.Types where import Data . Text ( Text ) import Terrafomo import Terrafomo . Spotinst . Lens import qualified Terrafomo . Attribute as TF import qualified Terrafomo . HCL as TF import qualified Terrafomo . Name as TF import qualified Terrafomo . Provider as TF import qualified Terrafomo . Schema as TF
d1988f251eb49b516ab29d5eead6b4072ba7048a9293f664cb2b11be90051e6c
haskell-jp/makeMistakesToLearnHaskell
no-main.hs
input <- getContents putStr (unlines (reverse (lines input)))
null
https://raw.githubusercontent.com/haskell-jp/makeMistakesToLearnHaskell/1174d5c6bb82e57622be8033607a4d049e30ae7e/test/assets/4/no-main.hs
haskell
input <- getContents putStr (unlines (reverse (lines input)))
38585783ee8e53029872b0b755b08e4d2ea840c9c08b21dbae2c59d24d040efa
geremih/xcljb
xtest.clj
This file is automatically generated . DO NOT MODIFY . (clojure.core/ns xcljb.gen.xtest (:require xcljb.conn-ext xcljb.gen.xtest-types)) (def -XCLJB {:minor-version 1, :major-version 2, :header "xtest", :extension-multiword false, :extension-name "Test", :extension-xname "XTEST"}) (def CURSOR {:current 1, :none 0}) (clojure.core/defn get-version [conn major-version minor-version] (clojure.core/let [request (clojure.core/zipmap [:major-version :minor-version] [major-version minor-version])] (xcljb.conn-ext/send conn "XTEST" xcljb.gen.xtest-types/GetVersionRequest request))) (clojure.core/defn compare-cursor [conn window cursor] (clojure.core/let [request (clojure.core/zipmap [:window :cursor] [window cursor])] (xcljb.conn-ext/send conn "XTEST" xcljb.gen.xtest-types/CompareCursorRequest request))) (clojure.core/defn fake-input [conn type detail time root root-x root-y deviceid] (clojure.core/let [request (clojure.core/zipmap [:type :detail :time :root :root-x :root-y :deviceid] [type detail time root root-x root-y deviceid])] (xcljb.conn-ext/send conn "XTEST" xcljb.gen.xtest-types/FakeInputRequest request))) (clojure.core/defn grab-control [conn impervious] (clojure.core/let [request (clojure.core/zipmap [:impervious] [impervious])] (xcljb.conn-ext/send conn "XTEST" xcljb.gen.xtest-types/GrabControlRequest request))) ;;; Manually written.
null
https://raw.githubusercontent.com/geremih/xcljb/59e9ff795bf00595a3d46231a7bb4ec976852396/src/xcljb/gen/xtest.clj
clojure
Manually written.
This file is automatically generated . DO NOT MODIFY . (clojure.core/ns xcljb.gen.xtest (:require xcljb.conn-ext xcljb.gen.xtest-types)) (def -XCLJB {:minor-version 1, :major-version 2, :header "xtest", :extension-multiword false, :extension-name "Test", :extension-xname "XTEST"}) (def CURSOR {:current 1, :none 0}) (clojure.core/defn get-version [conn major-version minor-version] (clojure.core/let [request (clojure.core/zipmap [:major-version :minor-version] [major-version minor-version])] (xcljb.conn-ext/send conn "XTEST" xcljb.gen.xtest-types/GetVersionRequest request))) (clojure.core/defn compare-cursor [conn window cursor] (clojure.core/let [request (clojure.core/zipmap [:window :cursor] [window cursor])] (xcljb.conn-ext/send conn "XTEST" xcljb.gen.xtest-types/CompareCursorRequest request))) (clojure.core/defn fake-input [conn type detail time root root-x root-y deviceid] (clojure.core/let [request (clojure.core/zipmap [:type :detail :time :root :root-x :root-y :deviceid] [type detail time root root-x root-y deviceid])] (xcljb.conn-ext/send conn "XTEST" xcljb.gen.xtest-types/FakeInputRequest request))) (clojure.core/defn grab-control [conn impervious] (clojure.core/let [request (clojure.core/zipmap [:impervious] [impervious])] (xcljb.conn-ext/send conn "XTEST" xcljb.gen.xtest-types/GrabControlRequest request)))
5b42d9cfc8691693cbed516e0dd92193587b405507466d26a70c94da65a59045
cognitect-labs/vase
descriptor_test.clj
(ns com.cognitect.vase.descriptor-test (:require [clojure.test :refer :all] [io.pedestal.test :refer :all] [com.cognitect.vase.test-helper :as helper] [com.cognitect.vase.service-route-table :as srt] [com.cognitect.vase.util :as util] [com.cognitect.vase :as vase])) (deftest exercise-descriptored-service (helper/with-service (srt/service-map) (let [post-response (helper/post-json "/api/example/v1/user" {:payload [{:user/userId 42 :user/userEmail ""}]}) get-response (helper/GET "/api/example/v1/fogus") get-response2 (helper/GET "/api/example/v1/users/42") delete-response (helper/json-request :delete "/api/example/v1/user" In Datomic 5544 , lookup - ids no longer automatically get prepended with ` : ` ;; Use a string instead...VV {:payload [{:db/id [":user/userId" 42]}]}) get-response3 (helper/GET "/api/example/v1/fogus")] (is (= 200 (:status post-response))) (is (= 200 (:status get-response))) (is (= 200 (:status get-response2))) ( is (= 200 (: status delete - response ) ) ) (is (= 200 (:status get-response3))) (is (string? (get-in get-response [:headers "vaserequest-id"]))) (is (seq (helper/response-data post-response))) (is (= (seq (helper/response-data get-response)) (seq (helper/response-data get-response2)))) (is (empty? (helper/response-data get-response3)))))) (deftest exercise-constant-and-parameter-action (helper/with-service (srt/service-map) (let [post1 (helper/post-json "/api/example/v1/user" {:payload [{:user/userEmail ""}]}) post2 (helper/post-json "/api/example/v1/user" {:payload [{:user/userEmail ""}]}) special-get (helper/GET "/api/example/v1/fogus-and-someone?someone=")] (are [x] (= (:status x) 200) post1 post2 special-get) (is (seq (helper/response-data special-get))) (is (= (count (helper/response-data special-get)) 2))))) (deftest exercise-version-interceptor-chains (helper/with-service (srt/service-map) (let [hello-resp (helper/GET "/api/example/v2/hello") hello-body (util/read-transit-json (:body hello-resp))] (is (= hello-body {:just-a-key "Another Hello World Route"}))))) (deftest exercise-per-route-interceptor-chains (helper/with-service (srt/service-map) (let [hello-resp (helper/GET "/api/example/v2/intercept") hello-body (helper/response-data hello-resp)] (is (= hello-body {:one 1}))))) (deftest multiple-api-specs (let [one-spec (srt/test-spec) datomic-uri (:datomic-uri one-spec) specs (conj (mapv (fn [[path v]] (assoc-in {:descriptor {} :datomic-uri datomic-uri} path v)) {[:descriptor :vase/norms] {:example/animal-schema {:vase.norm/txes [#vase/schema-tx [[:animal/type :one :string :identity "The type of animal"] [:animal/pack-name :one :string "The word for a 'pack' of the animal"]]]}} [:descriptor :vase/apis] {:example/vnew {:vase.api/routes {"/something-new" {:get #vase/respond {:name :example.vnew/something-new :body "This is new"}}}}}}) one-spec)] (testing "norms merge cleanly" (let [merged-norms (vase/ensure-schema specs)] (is (= (set (keys (get-in merged-norms [datomic-uri :norms]))) #{:example/user-schema :example/animal-schema :example/base-schema :example/loan-schema})))) (testing "routes merge cleanly; Only activated routes are included" (let [routes (vase/routes "/api" specs) paths (map (fn [[path verb]] [path verb]) routes) more-routes (vase/routes "/api" (assoc-in specs [1 :activated-apis] [:example/vnew])) more-paths (map (fn [[path verb]] [path verb]) more-routes)] (is (= (count (set paths)) (count paths))) (is (= (set paths) #{["/api/example/v1/user" :delete] ["/api/example/v2" :get] ["/api" :get] ["/api/example/v1/fogus-and-paul" :get] ["/api/example/v1/redirect-to-google" :get] ["/api/example/v1/users" :get] ["/api/example/v1/validate" :post] ["/api/example/v2/intercept" :get] ["/api/example/v1/db" :get] ["/api/example/v1/users/:id" :get] ["/api/example/v1/fogus-and-someone" :get] ["/api/example/v1/fogus" :get] ["/api/example/v1" :get] ["/api/example/v1/user" :get] ["/api/example/v1/redirect-to-param" :get] ["/api/example/v1/hello" :get] ["/api/example/v1/user" :post] ["/api/example/v1/capture-s/:url-thing" :get] ["/api/example/v2/hello" :get]})) (is (= (count (set more-paths)) (count more-paths))) (is (> (count more-paths) (count paths))) (is (= (set more-paths) #{["/api/example/v1/user" :delete] ["/api/example/v2" :get] ["/api" :get] ["/api/example/v1/fogus-and-paul" :get] ["/api/example/v1/redirect-to-google" :get] ["/api/example/v1/users" :get] ["/api/example/v1/validate" :post] ["/api/example/v2/intercept" :get] ["/api/example/v1/db" :get] ["/api/example/v1/users/:id" :get] ["/api/example/v1/fogus-and-someone" :get] ["/api/example/v1/fogus" :get] ["/api/example/v1" :get] ["/api/example/v1/user" :get] ["/api/example/v1/redirect-to-param" :get] ["/api/example/v1/hello" :get] ["/api/example/v1/user" :post] ["/api/example/v1/capture-s/:url-thing" :get] ["/api/example/vnew" :get] ["/api/example/vnew/something-new" :get] ["/api/example/v2/hello" :get]}))))))
null
https://raw.githubusercontent.com/cognitect-labs/vase/d882bc8f28e8af2077b55c80e069aa2238f646b7/test/com/cognitect/vase/descriptor_test.clj
clojure
Use a string instead...VV
(ns com.cognitect.vase.descriptor-test (:require [clojure.test :refer :all] [io.pedestal.test :refer :all] [com.cognitect.vase.test-helper :as helper] [com.cognitect.vase.service-route-table :as srt] [com.cognitect.vase.util :as util] [com.cognitect.vase :as vase])) (deftest exercise-descriptored-service (helper/with-service (srt/service-map) (let [post-response (helper/post-json "/api/example/v1/user" {:payload [{:user/userId 42 :user/userEmail ""}]}) get-response (helper/GET "/api/example/v1/fogus") get-response2 (helper/GET "/api/example/v1/users/42") delete-response (helper/json-request :delete "/api/example/v1/user" In Datomic 5544 , lookup - ids no longer automatically get prepended with ` : ` {:payload [{:db/id [":user/userId" 42]}]}) get-response3 (helper/GET "/api/example/v1/fogus")] (is (= 200 (:status post-response))) (is (= 200 (:status get-response))) (is (= 200 (:status get-response2))) ( is (= 200 (: status delete - response ) ) ) (is (= 200 (:status get-response3))) (is (string? (get-in get-response [:headers "vaserequest-id"]))) (is (seq (helper/response-data post-response))) (is (= (seq (helper/response-data get-response)) (seq (helper/response-data get-response2)))) (is (empty? (helper/response-data get-response3)))))) (deftest exercise-constant-and-parameter-action (helper/with-service (srt/service-map) (let [post1 (helper/post-json "/api/example/v1/user" {:payload [{:user/userEmail ""}]}) post2 (helper/post-json "/api/example/v1/user" {:payload [{:user/userEmail ""}]}) special-get (helper/GET "/api/example/v1/fogus-and-someone?someone=")] (are [x] (= (:status x) 200) post1 post2 special-get) (is (seq (helper/response-data special-get))) (is (= (count (helper/response-data special-get)) 2))))) (deftest exercise-version-interceptor-chains (helper/with-service (srt/service-map) (let [hello-resp (helper/GET "/api/example/v2/hello") hello-body (util/read-transit-json (:body hello-resp))] (is (= hello-body {:just-a-key "Another Hello World Route"}))))) (deftest exercise-per-route-interceptor-chains (helper/with-service (srt/service-map) (let [hello-resp (helper/GET "/api/example/v2/intercept") hello-body (helper/response-data hello-resp)] (is (= hello-body {:one 1}))))) (deftest multiple-api-specs (let [one-spec (srt/test-spec) datomic-uri (:datomic-uri one-spec) specs (conj (mapv (fn [[path v]] (assoc-in {:descriptor {} :datomic-uri datomic-uri} path v)) {[:descriptor :vase/norms] {:example/animal-schema {:vase.norm/txes [#vase/schema-tx [[:animal/type :one :string :identity "The type of animal"] [:animal/pack-name :one :string "The word for a 'pack' of the animal"]]]}} [:descriptor :vase/apis] {:example/vnew {:vase.api/routes {"/something-new" {:get #vase/respond {:name :example.vnew/something-new :body "This is new"}}}}}}) one-spec)] (testing "norms merge cleanly" (let [merged-norms (vase/ensure-schema specs)] (is (= (set (keys (get-in merged-norms [datomic-uri :norms]))) #{:example/user-schema :example/animal-schema :example/base-schema :example/loan-schema})))) (testing "routes merge cleanly; Only activated routes are included" (let [routes (vase/routes "/api" specs) paths (map (fn [[path verb]] [path verb]) routes) more-routes (vase/routes "/api" (assoc-in specs [1 :activated-apis] [:example/vnew])) more-paths (map (fn [[path verb]] [path verb]) more-routes)] (is (= (count (set paths)) (count paths))) (is (= (set paths) #{["/api/example/v1/user" :delete] ["/api/example/v2" :get] ["/api" :get] ["/api/example/v1/fogus-and-paul" :get] ["/api/example/v1/redirect-to-google" :get] ["/api/example/v1/users" :get] ["/api/example/v1/validate" :post] ["/api/example/v2/intercept" :get] ["/api/example/v1/db" :get] ["/api/example/v1/users/:id" :get] ["/api/example/v1/fogus-and-someone" :get] ["/api/example/v1/fogus" :get] ["/api/example/v1" :get] ["/api/example/v1/user" :get] ["/api/example/v1/redirect-to-param" :get] ["/api/example/v1/hello" :get] ["/api/example/v1/user" :post] ["/api/example/v1/capture-s/:url-thing" :get] ["/api/example/v2/hello" :get]})) (is (= (count (set more-paths)) (count more-paths))) (is (> (count more-paths) (count paths))) (is (= (set more-paths) #{["/api/example/v1/user" :delete] ["/api/example/v2" :get] ["/api" :get] ["/api/example/v1/fogus-and-paul" :get] ["/api/example/v1/redirect-to-google" :get] ["/api/example/v1/users" :get] ["/api/example/v1/validate" :post] ["/api/example/v2/intercept" :get] ["/api/example/v1/db" :get] ["/api/example/v1/users/:id" :get] ["/api/example/v1/fogus-and-someone" :get] ["/api/example/v1/fogus" :get] ["/api/example/v1" :get] ["/api/example/v1/user" :get] ["/api/example/v1/redirect-to-param" :get] ["/api/example/v1/hello" :get] ["/api/example/v1/user" :post] ["/api/example/v1/capture-s/:url-thing" :get] ["/api/example/vnew" :get] ["/api/example/vnew/something-new" :get] ["/api/example/v2/hello" :get]}))))))
91b9a34421b66bb5d98fb585c402390ccf69df097762b6936a5bf43d942dff62
kazu-yamamoto/cab
Utils.hs
# LANGUAGE CPP # module Distribution.Cab.Utils where import Data.List import Distribution.InstalledPackageInfo (InstalledPackageInfo) import Distribution.Package (PackageName) import Distribution.PackageDescription (GenericPackageDescription) import Distribution.Simple.PackageIndex (PackageIndex) import Distribution.Verbosity (Verbosity) #if MIN_VERSION_Cabal(1,21,0) && !(MIN_VERSION_Cabal(1,23,0)) import Distribution.Package (PackageInstalled) #endif #if MIN_VERSION_Cabal(1,23,0) import qualified Distribution.InstalledPackageInfo as Cabal (installedUnitId) import qualified Distribution.Package as Cabal (UnitId) import qualified Distribution.Simple.PackageIndex as Cabal (lookupUnitId) #else import qualified Distribution.InstalledPackageInfo as Cabal (installedPackageId) import qualified Distribution.Package as Cabal (InstalledPackageId) import qualified Distribution.Simple.PackageIndex as Cabal (lookupInstalledPackageId) #endif #if MIN_VERSION_Cabal(2,0,0) import qualified Distribution.Package as Cabal (mkPackageName, unPackageName) #else import qualified Distribution.Package as Cabal (PackageName(..)) #endif #if MIN_VERSION_Cabal(3,8,0) import qualified Distribution.Simple.PackageDescription as Cabal (readGenericPackageDescription) #elif MIN_VERSION_Cabal(2,2,0) import qualified Distribution.PackageDescription.Parsec as Cabal (readGenericPackageDescription) #elif MIN_VERSION_Cabal(2,0,0) import qualified Distribution.PackageDescription.Parse as Cabal (readGenericPackageDescription) #else import qualified Distribution.PackageDescription.Parse as Cabal (readPackageDescription) #endif -- | -- >>> fromDotted "1.2.3" -- [1,2,3] fromDotted :: String -> [Int] fromDotted [] = [] fromDotted xs = case break (=='.') xs of (x,"") -> [read x :: Int] (x,_:ys) -> (read x :: Int) : fromDotted ys -- | -- >>> toDotted [1,2,3] -- "1.2.3" toDotted :: [Int] -> String toDotted = intercalate "." . map show UnitIds #if MIN_VERSION_Cabal(1,23,0) type UnitId = Cabal.UnitId #else type UnitId = Cabal.InstalledPackageId #endif installedUnitId :: InstalledPackageInfo -> UnitId #if MIN_VERSION_Cabal(1,23,0) installedUnitId = Cabal.installedUnitId #else installedUnitId = Cabal.installedPackageId #endif #if MIN_VERSION_Cabal(1,23,0) lookupUnitId :: PackageIndex a -> UnitId -> Maybe a lookupUnitId = Cabal.lookupUnitId #elif MIN_VERSION_Cabal(1,21,0) lookupUnitId :: PackageInstalled a => PackageIndex a -> UnitId -> Maybe a lookupUnitId = Cabal.lookupInstalledPackageId #else lookupUnitId :: PackageIndex -> UnitId -> Maybe InstalledPackageInfo lookupUnitId = Cabal.lookupInstalledPackageId #endif PackageNames mkPackageName :: String -> PackageName #if MIN_VERSION_Cabal(2,0,0) mkPackageName = Cabal.mkPackageName #else mkPackageName = Cabal.PackageName #endif unPackageName :: PackageName -> String #if MIN_VERSION_Cabal(2,0,0) unPackageName = Cabal.unPackageName #else unPackageName (Cabal.PackageName s) = s #endif -- GenericPackageDescription readGenericPackageDescription :: Verbosity -> FilePath -> IO GenericPackageDescription #if MIN_VERSION_Cabal(2,0,0) readGenericPackageDescription = Cabal.readGenericPackageDescription #else readGenericPackageDescription = Cabal.readPackageDescription #endif
null
https://raw.githubusercontent.com/kazu-yamamoto/cab/1480e1eb3dc057908e63359d32f5ae3fc951ef5c/Distribution/Cab/Utils.hs
haskell
| >>> fromDotted "1.2.3" [1,2,3] | >>> toDotted [1,2,3] "1.2.3" GenericPackageDescription
# LANGUAGE CPP # module Distribution.Cab.Utils where import Data.List import Distribution.InstalledPackageInfo (InstalledPackageInfo) import Distribution.Package (PackageName) import Distribution.PackageDescription (GenericPackageDescription) import Distribution.Simple.PackageIndex (PackageIndex) import Distribution.Verbosity (Verbosity) #if MIN_VERSION_Cabal(1,21,0) && !(MIN_VERSION_Cabal(1,23,0)) import Distribution.Package (PackageInstalled) #endif #if MIN_VERSION_Cabal(1,23,0) import qualified Distribution.InstalledPackageInfo as Cabal (installedUnitId) import qualified Distribution.Package as Cabal (UnitId) import qualified Distribution.Simple.PackageIndex as Cabal (lookupUnitId) #else import qualified Distribution.InstalledPackageInfo as Cabal (installedPackageId) import qualified Distribution.Package as Cabal (InstalledPackageId) import qualified Distribution.Simple.PackageIndex as Cabal (lookupInstalledPackageId) #endif #if MIN_VERSION_Cabal(2,0,0) import qualified Distribution.Package as Cabal (mkPackageName, unPackageName) #else import qualified Distribution.Package as Cabal (PackageName(..)) #endif #if MIN_VERSION_Cabal(3,8,0) import qualified Distribution.Simple.PackageDescription as Cabal (readGenericPackageDescription) #elif MIN_VERSION_Cabal(2,2,0) import qualified Distribution.PackageDescription.Parsec as Cabal (readGenericPackageDescription) #elif MIN_VERSION_Cabal(2,0,0) import qualified Distribution.PackageDescription.Parse as Cabal (readGenericPackageDescription) #else import qualified Distribution.PackageDescription.Parse as Cabal (readPackageDescription) #endif fromDotted :: String -> [Int] fromDotted [] = [] fromDotted xs = case break (=='.') xs of (x,"") -> [read x :: Int] (x,_:ys) -> (read x :: Int) : fromDotted ys toDotted :: [Int] -> String toDotted = intercalate "." . map show UnitIds #if MIN_VERSION_Cabal(1,23,0) type UnitId = Cabal.UnitId #else type UnitId = Cabal.InstalledPackageId #endif installedUnitId :: InstalledPackageInfo -> UnitId #if MIN_VERSION_Cabal(1,23,0) installedUnitId = Cabal.installedUnitId #else installedUnitId = Cabal.installedPackageId #endif #if MIN_VERSION_Cabal(1,23,0) lookupUnitId :: PackageIndex a -> UnitId -> Maybe a lookupUnitId = Cabal.lookupUnitId #elif MIN_VERSION_Cabal(1,21,0) lookupUnitId :: PackageInstalled a => PackageIndex a -> UnitId -> Maybe a lookupUnitId = Cabal.lookupInstalledPackageId #else lookupUnitId :: PackageIndex -> UnitId -> Maybe InstalledPackageInfo lookupUnitId = Cabal.lookupInstalledPackageId #endif PackageNames mkPackageName :: String -> PackageName #if MIN_VERSION_Cabal(2,0,0) mkPackageName = Cabal.mkPackageName #else mkPackageName = Cabal.PackageName #endif unPackageName :: PackageName -> String #if MIN_VERSION_Cabal(2,0,0) unPackageName = Cabal.unPackageName #else unPackageName (Cabal.PackageName s) = s #endif readGenericPackageDescription :: Verbosity -> FilePath -> IO GenericPackageDescription #if MIN_VERSION_Cabal(2,0,0) readGenericPackageDescription = Cabal.readGenericPackageDescription #else readGenericPackageDescription = Cabal.readPackageDescription #endif
5eb83c545700b6e2281153e9bbd23ae4072d3b4cd645b05def24a56947c4fa67
well-typed-lightbulbs/ocaml-esp32
threadsigmask.ml
(* TEST * hassysthreads include systhreads ** not-windows *** bytecode *** native *) let stopped = ref false (* This function is purposed to do some computations which allocate, so that the corresponding thread is likely to handle signals if it is allowed to. *) let rec loop () = let rec generate_list n = let rec aux acc = function | 0 -> acc | n -> aux (float n :: acc) (n-1) in aux [] n in let long_list = generate_list 100000 in let res = List.length (List.rev_map sin long_list) in ignore (Sys.opaque_identity res) let thread s = ignore (Thread.sigmask Unix.SIG_UNBLOCK [s]); while not !stopped do loop () done let handler tid_exp cnt signal = incr cnt; if Thread.id (Thread.self ()) != !tid_exp then Printf.printf "Signal received in an unexpected thread !\n" let _ = ignore (Thread.sigmask Unix.SIG_BLOCK [Sys.sigusr1; Sys.sigusr2]); (* Install the signal handlers *) let (tid1, tid2) = (ref 0, ref 0) in let (cnt1, cnt2) = (ref 0, ref 0) in Sys.set_signal Sys.sigusr1 (Sys.Signal_handle (handler tid1 cnt1)); Sys.set_signal Sys.sigusr2 (Sys.Signal_handle (handler tid2 cnt2)); Spawn the other thread and unblock in the main thread let t1 = Thread.create thread Sys.sigusr1 in let t2 = Thread.self () in ignore (Thread.sigmask Unix.SIG_UNBLOCK [Sys.sigusr2]); tid1 := Thread.id t1; tid2 := Thread.id t2; (* Send signals to the current process. They should be received by the correct respective threads. *) let pid = Unix.getpid () in let cntsent = ref 0 in We loop until each thread has received at least 5 signals and we have sent more than 100 signals in total . We do not check that all signals get handled , because they could be missed because of the lack of fairness of the scheduler . have sent more than 100 signals in total. We do not check that all signals get handled, because they could be missed because of the lack of fairness of the scheduler. *) while !cntsent < 100 || !cnt1 < 5 || !cnt2 < 5 do Unix.kill pid Sys.sigusr1; Unix.kill pid Sys.sigusr2; incr cntsent; Thread.delay 0.07; (* Still, if too many signals have been sent, we interrupt the test to avoid a timeout. *) if !cntsent > 2000 then begin stopped := true; Thread.join t1; Printf.printf "A thread does not receive signals. %d %d %d\n" !cnt1 !cnt2 !cntsent; exit 0 end done; (* Join worker thread *) stopped := true; Thread.join t1; Printf.printf "OK\n"
null
https://raw.githubusercontent.com/well-typed-lightbulbs/ocaml-esp32/c24fcbfbee0e3aa6bb71c9b467c60c6bac326cc7/testsuite/tests/lib-systhreads/threadsigmask.ml
ocaml
TEST * hassysthreads include systhreads ** not-windows *** bytecode *** native This function is purposed to do some computations which allocate, so that the corresponding thread is likely to handle signals if it is allowed to. Install the signal handlers Send signals to the current process. They should be received by the correct respective threads. Still, if too many signals have been sent, we interrupt the test to avoid a timeout. Join worker thread
let stopped = ref false let rec loop () = let rec generate_list n = let rec aux acc = function | 0 -> acc | n -> aux (float n :: acc) (n-1) in aux [] n in let long_list = generate_list 100000 in let res = List.length (List.rev_map sin long_list) in ignore (Sys.opaque_identity res) let thread s = ignore (Thread.sigmask Unix.SIG_UNBLOCK [s]); while not !stopped do loop () done let handler tid_exp cnt signal = incr cnt; if Thread.id (Thread.self ()) != !tid_exp then Printf.printf "Signal received in an unexpected thread !\n" let _ = ignore (Thread.sigmask Unix.SIG_BLOCK [Sys.sigusr1; Sys.sigusr2]); let (tid1, tid2) = (ref 0, ref 0) in let (cnt1, cnt2) = (ref 0, ref 0) in Sys.set_signal Sys.sigusr1 (Sys.Signal_handle (handler tid1 cnt1)); Sys.set_signal Sys.sigusr2 (Sys.Signal_handle (handler tid2 cnt2)); Spawn the other thread and unblock in the main thread let t1 = Thread.create thread Sys.sigusr1 in let t2 = Thread.self () in ignore (Thread.sigmask Unix.SIG_UNBLOCK [Sys.sigusr2]); tid1 := Thread.id t1; tid2 := Thread.id t2; let pid = Unix.getpid () in let cntsent = ref 0 in We loop until each thread has received at least 5 signals and we have sent more than 100 signals in total . We do not check that all signals get handled , because they could be missed because of the lack of fairness of the scheduler . have sent more than 100 signals in total. We do not check that all signals get handled, because they could be missed because of the lack of fairness of the scheduler. *) while !cntsent < 100 || !cnt1 < 5 || !cnt2 < 5 do Unix.kill pid Sys.sigusr1; Unix.kill pid Sys.sigusr2; incr cntsent; Thread.delay 0.07; if !cntsent > 2000 then begin stopped := true; Thread.join t1; Printf.printf "A thread does not receive signals. %d %d %d\n" !cnt1 !cnt2 !cntsent; exit 0 end done; stopped := true; Thread.join t1; Printf.printf "OK\n"
55b7d71837f45b0450ed83768d3158b8390db1bd4f77d1e635665278539c818b
mzp/coq-ide-for-ios
envars.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) This file gathers environment variables needed by Coq to run ( such as coqlib ) as coqlib) *) let coqbin () = if !Flags.boot || Coq_config.local then Filename.concat Coq_config.coqsrc "bin" else System.canonical_path_name (Filename.dirname Sys.executable_name) (* On win32, we add coqbin to the PATH at launch-time (this used to be done in a .bat script). *) let _ = if Coq_config.arch = "win32" then Unix.putenv "PATH" (coqbin() ^ ";" ^ System.getenv_else "PATH" "") let guess_coqlib () = let file = "states/initial.coq" in if Sys.file_exists (Filename.concat Coq_config.coqlib file) then Coq_config.coqlib else let coqbin = System.canonical_path_name (Filename.dirname Sys.executable_name) in let prefix = Filename.dirname coqbin in let rpath = if Coq_config.local then [] else (if Coq_config.arch = "win32" then ["lib"] else ["lib";"coq"]) in let coqlib = List.fold_left Filename.concat prefix rpath in if Sys.file_exists (Filename.concat coqlib file) then coqlib else Util.error "cannot guess a path for Coq libraries; please use -coqlib option" let coqlib () = if !Flags.coqlib_spec then !Flags.coqlib else (if !Flags.boot then Coq_config.coqsrc else guess_coqlib ()) let path_to_list p = let sep = if Sys.os_type = "Win32" then ';' else ':' in Util.split_string_at sep p let rec which l f = match l with | [] -> raise Not_found | p :: tl -> if Sys.file_exists (Filename.concat p f) then p else which tl f let guess_camlbin () = let path = try Sys.getenv "PATH" with _ -> raise Not_found in let lpath = path_to_list path in which lpath "ocamlc" let guess_camlp4bin () = let path = try Sys.getenv "PATH" with _ -> raise Not_found in let lpath = path_to_list path in which lpath Coq_config.camlp4 let camlbin () = if !Flags.camlbin_spec then !Flags.camlbin else if !Flags.boot then Coq_config.camlbin else try guess_camlbin () with _ -> Coq_config.camlbin let camllib () = if !Flags.boot then Coq_config.camllib else let camlbin = camlbin () in let com = (Filename.concat camlbin "ocamlc") ^ " -where" in let _,res = System.run_command (fun x -> x) (fun _ -> ()) com in Util.strip res TODO : essayer let camlp4bin () = if !Flags.camlp4bin_spec then !Flags.camlp4bin else if !Flags.boot then Coq_config.camlp4bin else try guess_camlp4bin () with _ -> Coq_config.camlp4bin let camlp4lib () = if !Flags.boot then Coq_config.camlp4lib else let camlp4bin = camlp4bin () in let com = (Filename.concat camlp4bin Coq_config.camlp4) ^ " -where" in let _,res = System.run_command (fun x -> x) (fun _ -> ()) com in Util.strip res
null
https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/coqlib/lib/envars.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** On win32, we add coqbin to the PATH at launch-time (this used to be done in a .bat script).
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This file gathers environment variables needed by Coq to run ( such as coqlib ) as coqlib) *) let coqbin () = if !Flags.boot || Coq_config.local then Filename.concat Coq_config.coqsrc "bin" else System.canonical_path_name (Filename.dirname Sys.executable_name) let _ = if Coq_config.arch = "win32" then Unix.putenv "PATH" (coqbin() ^ ";" ^ System.getenv_else "PATH" "") let guess_coqlib () = let file = "states/initial.coq" in if Sys.file_exists (Filename.concat Coq_config.coqlib file) then Coq_config.coqlib else let coqbin = System.canonical_path_name (Filename.dirname Sys.executable_name) in let prefix = Filename.dirname coqbin in let rpath = if Coq_config.local then [] else (if Coq_config.arch = "win32" then ["lib"] else ["lib";"coq"]) in let coqlib = List.fold_left Filename.concat prefix rpath in if Sys.file_exists (Filename.concat coqlib file) then coqlib else Util.error "cannot guess a path for Coq libraries; please use -coqlib option" let coqlib () = if !Flags.coqlib_spec then !Flags.coqlib else (if !Flags.boot then Coq_config.coqsrc else guess_coqlib ()) let path_to_list p = let sep = if Sys.os_type = "Win32" then ';' else ':' in Util.split_string_at sep p let rec which l f = match l with | [] -> raise Not_found | p :: tl -> if Sys.file_exists (Filename.concat p f) then p else which tl f let guess_camlbin () = let path = try Sys.getenv "PATH" with _ -> raise Not_found in let lpath = path_to_list path in which lpath "ocamlc" let guess_camlp4bin () = let path = try Sys.getenv "PATH" with _ -> raise Not_found in let lpath = path_to_list path in which lpath Coq_config.camlp4 let camlbin () = if !Flags.camlbin_spec then !Flags.camlbin else if !Flags.boot then Coq_config.camlbin else try guess_camlbin () with _ -> Coq_config.camlbin let camllib () = if !Flags.boot then Coq_config.camllib else let camlbin = camlbin () in let com = (Filename.concat camlbin "ocamlc") ^ " -where" in let _,res = System.run_command (fun x -> x) (fun _ -> ()) com in Util.strip res TODO : essayer let camlp4bin () = if !Flags.camlp4bin_spec then !Flags.camlp4bin else if !Flags.boot then Coq_config.camlp4bin else try guess_camlp4bin () with _ -> Coq_config.camlp4bin let camlp4lib () = if !Flags.boot then Coq_config.camlp4lib else let camlp4bin = camlp4bin () in let com = (Filename.concat camlp4bin Coq_config.camlp4) ^ " -where" in let _,res = System.run_command (fun x -> x) (fun _ -> ()) com in Util.strip res
a00b963df19d68ae820dcdd65b8a905ffe7d4bb82286a576f8844ab06c880b76
alanzplus/EOPL
explicit-refs-read-print-ast.rkt
#lang eopl (require "explicit-refs-spec.rkt") (read-print-ast)
null
https://raw.githubusercontent.com/alanzplus/EOPL/d7b06392d26d93df851d0ca66d9edc681a06693c/EOPL/ch4/explicit-refs-read-print-ast.rkt
racket
#lang eopl (require "explicit-refs-spec.rkt") (read-print-ast)
a37e5744674f3a5c958f77aeb49f44ebb512043ea38d60680afdb2cacda1aa6c
clash-lang/clash-compiler
BlockRam.hs
| Copyright : ( C ) 2013 - 2016 , University of Twente , 2016 - 2017 , Myrtle Software Ltd , 2017 , Google Inc. , 2021 - 2022 , QBayLogic B.V. , 2022 , Google Inc. , License : BSD2 ( see the file LICENSE ) Maintainer : QBayLogic B.V. < > Block RAM primitives = Using RAMs # usingrams # We will show a rather elaborate example on how you can , and why you might want to use block RAMs . We will build a \"small\ " CPU + Memory + Program ROM where we will slowly evolve to using block RAMs . Note that the code is /not/ meant as a de - facto standard on how to do CPU design in Clash . We start with the definition of the Instructions , Register names and machine codes : @ { \-\ # LANGUAGE RecordWildCards , TupleSections , DeriveAnyClass \#-\ } module CPU where import Clash . Explicit . Prelude type InstrAddr = Unsigned 8 type = Unsigned 5 type Value = Signed 8 data Instruction = Compute Operator | Branch Reg Value | Jump Value | Load | Store Reg MemAddr | Nop deriving ( Eq , Show , Generic , ) data = Zero | PC | RegA | RegB | RegC | RegD | deriving ( Eq , Show , , Generic , ) data Operator = Add | Sub | Incr | Imm | CmpGt deriving ( Eq , Show , Generic , ) data MachCode = MachCode { inputX : : , inputY : : , result : : , aluCode : : Operator , ldReg : : , rdAddr : : , wrAddrM : : Maybe , jmpM : : Maybe Value } nullCode = MachCode { inputX = Zero , inputY = Zero , result = Zero , aluCode = Imm , ldReg = Zero , rdAddr = 0 , wrAddrM = Nothing , jmpM = Nothing } @ Next we define the CPU and its ALU : @ cpu : : -- ^ Register bank - > ( Value , Instruction ) -- ^ ( Memory output , Current instruction ) - > ( Vec 7 Value , ( , Maybe ( , Value ) , InstrAddr ) ) cpu regbank ( memOut , instr ) = ( regbank ' , ( rdAddr , ( , aluOut ) ' < $ > ' wrAddrM , bitCoerce ipntr ) ) where -- Current instruction pointer ipntr = regbank ' Clash . Sized . Vector . ! ! ' PC -- Decoder ( MachCode { .. } ) = case instr of Compute op rx nullCode { inputX = rx , inputY = ry , result = res , aluCode = op } Branch cr a - > nullCode { inputX = cr , jmpM = Just a } Jump a - > nullCode { aluCode = Incr , jmpM = Just a } Load a r - > nullCode { ldReg = r , } Store r a - > nullCode { inputX = r , wrAddrM = Just a } Nop - > nullCode -- ALU regX = regbank ' Clash . Sized . Vector . ! ! ' inputX regY = regbank ' Clash . Sized . Vector . ! ! ' inputY aluOut = alu aluCode regX regY -- next instruction nextPC = case jmpM of Just a | aluOut /= 0 - > ipntr + a _ - > ipntr + 1 -- update registers regbank ' = ' Clash.Sized.Vector.replace ' Zero 0 $ ' Clash.Sized.Vector.replace ' PC nextPC $ ' Clash.Sized.Vector.replace ' result aluOut $ ' Clash.Sized.Vector.replace ' ldReg memOut $ regbank alu Add x y = x + y alu Sub x y = x - y alu _ = x + 1 alu Imm x _ = x alu CmpGt x y = if x > y then 1 else 0 @ We initially create a memory out of simple registers : @ dataMem : : KnownDomain dom = > Clock dom - > Reset dom - > Enable dom - > Signal dom -- ^ Read address - > Signal dom ( Maybe ( , Value ) ) -- ^ ( write address , data in ) - > Signal dom Value -- ^ data out dataMem clk rst en rd wrM = ' Clash.Explicit.Mealy.mealy ' clk rst en dataMemT ( ' Clash.Sized.Vector.replicate ' d32 0 ) ( bundle ( rd , wrM ) ) where dataMemT mem ( rd , wrM ) = ( mem',dout ) where dout = mem ' Clash . Sized . Vector . ! ! ' rd mem ' = case wrM of Just ( wr , din ) - > ' Clash.Sized.Vector.replace ' - > mem @ And then connect everything : @ system : : ( KnownDomain dom , KnownNat n ) = > n Instruction - > Clock dom - > Reset dom - > Enable dom - > Signal dom Value system instrs clk rst en = memOut where memOut = dataMem clk rst en ( rdAddr , dout , ipntr ) = ' Clash . Explicit . Mealy.mealyB ' clk rst en cpu ( ' Clash.Sized.Vector.replicate ' d7 0 ) ( memOut , instr ) instr = ' Clash . Explicit . Prelude.asyncRom ' instrs ' < $ > ' ipntr @ Create a simple program that calculates the GCD of 4 and 6 : @ -- Compute GCD of 4 and 6 prog = -- 0 : = 4 Compute Incr Zero RegA RegA :> replicate d3 ( Compute Incr RegA Zero RegA ) + + Store RegA 0 :> -- 1 : = 6 Compute Incr Zero RegA RegA :> replicate d5 ( Compute Incr RegA Zero RegA ) + + Store RegA 1 :> -- A : = 4 Load 0 RegA :> -- B : = 6 Load 1 RegB :> -- start Compute CmpGt RegA RegB RegC :> Branch RegC 4 :> Compute CmpGt RegB RegA RegC :> Branch RegC 4 :> Jump 5 :> -- ( a > b ) Compute Sub RegA RegB RegA :> Jump ( -6 ) :> -- ( b > a ) Compute Sub RegB RegA RegB :> Jump (-8 ) :> -- end Store RegA 2 :> Load 2 RegC :> Nil @ And test our system : @ > > > sampleN 32 $ system prog systemClockGen resetGen enableGen [ 0,0,0,0,0,0,4,4,4,4,4,4,4,4,6,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2 ] @ to see that our system indeed calculates that the GCD of 6 and 4 is 2 . = = = Improvement 1 : using @asyncRam@ As you can see , it 's fairly straightforward to build a memory using registers and read ( ' Clash . Sized . Vector . ! ! ' ) and write ( ' Clash.Sized.Vector.replace ' ) logic . This might however not result in the most efficient hardware structure , especially when building an ASIC . Instead it is preferable to use the ' Clash . Prelude . RAM.asyncRam ' function which has the potential to be translated to a more efficient structure : @ : : ( KnownDomain dom , KnownNat n ) = > n Instruction - > Clock dom - > Reset dom - > Enable dom - > Signal dom Value rst en = memOut where memOut = ' Clash . Explicit . RAM.asyncRam ' clk clk en d32 ( rdAddr , dout , ipntr ) = ' Clash . Explicit . Prelude.mealyB ' clk rst en cpu ( ' Clash.Sized.Vector.replicate ' d7 0 ) ( memOut , instr ) instr = ' Clash . Prelude . ROM.asyncRom ' instrs ' < $ > ' ipntr @ Again , we can simulate our system and see that it works . This time however , we need to disregard the first few output samples , because the initial content of an ' Clash . Prelude . RAM.asyncRam ' is /undefined/ , and consequently , the first few output samples are also /undefined/. We use the utility function ' Clash . XException.printX ' to conveniently filter out the undefinedness and replace it with the string @\"undefined\"@ in the first few leading outputs . @ > > > printX $ sampleN 32 $ system2 prog systemClockGen resetGen enableGen [ undefined , undefined , undefined , undefined , undefined , = = Improvement 2 : using @blockRam@ Finally we get to using ' blockRam ' . On FPGAs , ' Clash . Prelude . RAM.asyncRam ' will be implemented in terms of LUTs , and therefore take up logic resources . FPGAs also have large(r ) memory structures called /block RAMs/ , which are preferred , especially as the memories we need for our application get bigger . The ' blockRam ' function will be translated to such a /block RAM/. One important aspect of block RAMs is that they have a /synchronous/ read port , meaning unlike an ' Clash . Prelude . RAM.asyncRam ' , the result of a read command given at time @t@ is output at time @t + 1@. For us that means we need to change the design of our CPU . Right now , upon a load instruction we generate a read address for the memory , and the value at that read address is immediately available to be put in the register bank . We will be using a block RAM , so the value is delayed until the next cycle . Thus , we will also need to delay the register address to which the memory address is loaded : @ cpu2 : : ( Vec 7 Value , ) -- ^ ( Register bank , Load reg addr ) - > ( Value , Instruction ) -- ^ ( Memory output , Current instruction ) - > ( ( Vec 7 Value , ) , ( , Maybe ( , Value ) , InstrAddr ) ) cpu2 ( regbank , ldRegD ) ( memOut , instr ) = ( ( regbank ' , ldRegD ' ) , ( rdAddr , ( , aluOut ) ' < $ > ' wrAddrM , bitCoerce ipntr ) ) where -- Current instruction pointer ipntr = regbank ' Clash . Sized . Vector . ! ! ' PC -- Decoder ( MachCode { .. } ) = case instr of Compute op rx nullCode { inputX = rx , inputY = ry , result = res , aluCode = op } Branch cr a - > nullCode { inputX = cr , jmpM = Just a } Jump a - > nullCode { aluCode = Incr , jmpM = Just a } Load a r - > nullCode { ldReg = r , } Store r a - > nullCode { inputX = r , wrAddrM = Just a } Nop - > nullCode -- ALU regX = regbank ' Clash . Sized . Vector . ! ! ' inputX regY = regbank ' Clash . Sized . Vector . ! ! ' inputY aluOut = alu aluCode regX regY -- next instruction nextPC = case jmpM of Just a | aluOut /= 0 - > ipntr + a _ - > ipntr + 1 -- update registers ldRegD ' = ldReg -- Delay the ldReg by 1 cycle regbank ' = ' Clash.Sized.Vector.replace ' Zero 0 $ ' Clash.Sized.Vector.replace ' PC nextPC $ ' Clash.Sized.Vector.replace ' result aluOut $ ' Clash.Sized.Vector.replace ' ldRegD memOut $ regbank @ We can now finally instantiate our system with a ' blockRam ' : @ : : ( KnownDomain dom , KnownNat n ) = > n Instruction - > Clock dom - > Reset dom - > Enable dom - > Signal dom Value clk rst en = memOut where memOut = ' blockRam ' clk en ( replicate d32 0 ) ( rdAddr , dout , ipntr ) = ' Clash . Explicit . Prelude.mealyB ' clk rst en cpu2 ( ( ' Clash.Sized.Vector.replicate ' d7 0),Zero ) ( memOut , instr ) instr = ' Clash . Explicit . Prelude.asyncRom ' instrs ' < $ > ' ipntr @ We are , however , not done . We will also need to update our program . The reason being that values that we try to load in our registers wo n't be loaded into the register until the next cycle . This is a problem when the next instruction immediately depends on this memory value . In our example , this was only the case when we loaded the value , which was stored at address @1@ , into @RegB@. Our updated program is thus : @ prog2 = -- 0 : = 4 Compute Incr Zero RegA RegA :> replicate d3 ( Compute Incr RegA Zero RegA ) + + Store RegA 0 :> -- 1 : = 6 Compute Incr Zero RegA RegA :> replicate d5 ( Compute Incr RegA Zero RegA ) + + Store RegA 1 :> -- A : = 4 Load 0 RegA :> -- B : = 6 Load 1 RegB :> Nop :> -- Extra NOP -- start Compute CmpGt RegA RegB RegC :> Branch RegC 4 :> Compute CmpGt RegB RegA RegC :> Branch RegC 4 :> Jump 5 :> -- ( a > b ) Compute Sub RegA RegB RegA :> Jump ( -6 ) :> -- ( b > a ) Compute Sub RegB RegA RegB :> Jump (-8 ) :> -- end Store RegA 2 :> Load 2 RegC :> Nil @ When we simulate our system we see that it works . This time again , we need to disregard the first sample , because the initial output of a ' blockRam ' is /undefined/. We use the utility function ' Clash . XException.printX ' to conveniently filter out the undefinedness and replace it with the string @\"undefined\"@. @ > > > printX $ sampleN 34 $ [ undefined,0,0,0,0,0,0,4,4,4,4,4,4,4,4,6,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2 ] @ This concludes the short introduction to using ' blockRam ' . Copyright : (C) 2013-2016, University of Twente, 2016-2017, Myrtle Software Ltd, 2017 , Google Inc., 2021-2022, QBayLogic B.V., 2022 , Google Inc., License : BSD2 (see the file LICENSE) Maintainer : QBayLogic B.V. <> Block RAM primitives = Using RAMs #usingrams# We will show a rather elaborate example on how you can, and why you might want to use block RAMs. We will build a \"small\" CPU + Memory + Program ROM where we will slowly evolve to using block RAMs. Note that the code is /not/ meant as a de-facto standard on how to do CPU design in Clash. We start with the definition of the Instructions, Register names and machine codes: @ {\-\# LANGUAGE RecordWildCards, TupleSections, DeriveAnyClass \#-\} module CPU where import Clash.Explicit.Prelude type InstrAddr = Unsigned 8 type MemAddr = Unsigned 5 type Value = Signed 8 data Instruction = Compute Operator Reg Reg Reg | Branch Reg Value | Jump Value | Load MemAddr Reg | Store Reg MemAddr | Nop deriving (Eq, Show, Generic, NFDataX) data Reg = Zero | PC | RegA | RegB | RegC | RegD | RegE deriving (Eq, Show, Enum, Generic, NFDataX) data Operator = Add | Sub | Incr | Imm | CmpGt deriving (Eq, Show, Generic, NFDataX) data MachCode = MachCode { inputX :: Reg , inputY :: Reg , result :: Reg , aluCode :: Operator , ldReg :: Reg , rdAddr :: MemAddr , wrAddrM :: Maybe MemAddr , jmpM :: Maybe Value } nullCode = MachCode { inputX = Zero , inputY = Zero , result = Zero , aluCode = Imm , ldReg = Zero , rdAddr = 0 , wrAddrM = Nothing , jmpM = Nothing } @ Next we define the CPU and its ALU: @ cpu :: Vec 7 Value -- ^ Register bank -> (Value,Instruction) -- ^ (Memory output, Current instruction) -> ( Vec 7 Value , (MemAddr, Maybe (MemAddr,Value), InstrAddr) ) cpu regbank (memOut, instr) = (regbank', (rdAddr, (,aluOut) '<$>' wrAddrM, bitCoerce ipntr)) where -- Current instruction pointer ipntr = regbank 'Clash.Sized.Vector.!!' PC -- Decoder (MachCode {..}) = case instr of Compute op rx ry res -> nullCode {inputX=rx,inputY=ry,result=res,aluCode=op} Branch cr a -> nullCode {inputX=cr,jmpM=Just a} Jump a -> nullCode {aluCode=Incr,jmpM=Just a} Load a r -> nullCode {ldReg=r,rdAddr=a} Store r a -> nullCode {inputX=r,wrAddrM=Just a} Nop -> nullCode -- ALU regX = regbank 'Clash.Sized.Vector.!!' inputX regY = regbank 'Clash.Sized.Vector.!!' inputY aluOut = alu aluCode regX regY -- next instruction nextPC = case jmpM of Just a | aluOut /= 0 -> ipntr + a _ -> ipntr + 1 -- update registers regbank' = 'Clash.Sized.Vector.replace' Zero 0 $ 'Clash.Sized.Vector.replace' PC nextPC $ 'Clash.Sized.Vector.replace' result aluOut $ 'Clash.Sized.Vector.replace' ldReg memOut $ regbank alu Add x y = x + y alu Sub x y = x - y alu Incr x _ = x + 1 alu Imm x _ = x alu CmpGt x y = if x > y then 1 else 0 @ We initially create a memory out of simple registers: @ dataMem :: KnownDomain dom => Clock dom -> Reset dom -> Enable dom -> Signal dom MemAddr -- ^ Read address -> Signal dom (Maybe (MemAddr,Value)) -- ^ (write address, data in) -> Signal dom Value -- ^ data out dataMem clk rst en rd wrM = 'Clash.Explicit.Mealy.mealy' clk rst en dataMemT ('Clash.Sized.Vector.replicate' d32 0) (bundle (rd,wrM)) where dataMemT mem (rd,wrM) = (mem',dout) where dout = mem 'Clash.Sized.Vector.!!' rd mem' = case wrM of Just (wr,din) -> 'Clash.Sized.Vector.replace' wr din mem _ -> mem @ And then connect everything: @ system :: ( KnownDomain dom , KnownNat n ) => Vec n Instruction -> Clock dom -> Reset dom -> Enable dom -> Signal dom Value system instrs clk rst en = memOut where memOut = dataMem clk rst en rdAddr dout (rdAddr,dout,ipntr) = 'Clash.Explicit.Mealy.mealyB' clk rst en cpu ('Clash.Sized.Vector.replicate' d7 0) (memOut,instr) instr = 'Clash.Explicit.Prelude.asyncRom' instrs '<$>' ipntr @ Create a simple program that calculates the GCD of 4 and 6: @ -- Compute GCD of 4 and 6 prog = -- 0 := 4 Compute Incr Zero RegA RegA :> replicate d3 (Compute Incr RegA Zero RegA) ++ Store RegA 0 :> -- 1 := 6 Compute Incr Zero RegA RegA :> replicate d5 (Compute Incr RegA Zero RegA) ++ Store RegA 1 :> -- A := 4 Load 0 RegA :> -- B := 6 Load 1 RegB :> -- start Compute CmpGt RegA RegB RegC :> Branch RegC 4 :> Compute CmpGt RegB RegA RegC :> Branch RegC 4 :> Jump 5 :> -- (a > b) Compute Sub RegA RegB RegA :> Jump (-6) :> -- (b > a) Compute Sub RegB RegA RegB :> Jump (-8) :> -- end Store RegA 2 :> Load 2 RegC :> Nil @ And test our system: @ >>> sampleN 32 $ system prog systemClockGen resetGen enableGen [0,0,0,0,0,0,4,4,4,4,4,4,4,4,6,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2] @ to see that our system indeed calculates that the GCD of 6 and 4 is 2. === Improvement 1: using @asyncRam@ As you can see, it's fairly straightforward to build a memory using registers and read ('Clash.Sized.Vector.!!') and write ('Clash.Sized.Vector.replace') logic. This might however not result in the most efficient hardware structure, especially when building an ASIC. Instead it is preferable to use the 'Clash.Prelude.RAM.asyncRam' function which has the potential to be translated to a more efficient structure: @ system2 :: ( KnownDomain dom , KnownNat n ) => Vec n Instruction -> Clock dom -> Reset dom -> Enable dom -> Signal dom Value system2 instrs clk rst en = memOut where memOut = 'Clash.Explicit.RAM.asyncRam' clk clk en d32 rdAddr dout (rdAddr,dout,ipntr) = 'Clash.Explicit.Prelude.mealyB' clk rst en cpu ('Clash.Sized.Vector.replicate' d7 0) (memOut,instr) instr = 'Clash.Prelude.ROM.asyncRom' instrs '<$>' ipntr @ Again, we can simulate our system and see that it works. This time however, we need to disregard the first few output samples, because the initial content of an 'Clash.Prelude.RAM.asyncRam' is /undefined/, and consequently, the first few output samples are also /undefined/. We use the utility function 'Clash.XException.printX' to conveniently filter out the undefinedness and replace it with the string @\"undefined\"@ in the first few leading outputs. @ >>> printX $ sampleN 32 $ system2 prog systemClockGen resetGen enableGen [undefined,undefined,undefined,undefined,undefined,undefined,4,4,4,4,4,4,4,4,6,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2] @ === Improvement 2: using @blockRam@ Finally we get to using 'blockRam'. On FPGAs, 'Clash.Prelude.RAM.asyncRam' will be implemented in terms of LUTs, and therefore take up logic resources. FPGAs also have large(r) memory structures called /block RAMs/, which are preferred, especially as the memories we need for our application get bigger. The 'blockRam' function will be translated to such a /block RAM/. One important aspect of block RAMs is that they have a /synchronous/ read port, meaning unlike an 'Clash.Prelude.RAM.asyncRam', the result of a read command given at time @t@ is output at time @t + 1@. For us that means we need to change the design of our CPU. Right now, upon a load instruction we generate a read address for the memory, and the value at that read address is immediately available to be put in the register bank. We will be using a block RAM, so the value is delayed until the next cycle. Thus, we will also need to delay the register address to which the memory address is loaded: @ cpu2 :: (Vec 7 Value,Reg) -- ^ (Register bank, Load reg addr) -> (Value,Instruction) -- ^ (Memory output, Current instruction) -> ( (Vec 7 Value, Reg) , (MemAddr, Maybe (MemAddr,Value), InstrAddr) ) cpu2 (regbank, ldRegD) (memOut, instr) = ((regbank', ldRegD'), (rdAddr, (,aluOut) '<$>' wrAddrM, bitCoerce ipntr)) where -- Current instruction pointer ipntr = regbank 'Clash.Sized.Vector.!!' PC -- Decoder (MachCode {..}) = case instr of Compute op rx ry res -> nullCode {inputX=rx,inputY=ry,result=res,aluCode=op} Branch cr a -> nullCode {inputX=cr,jmpM=Just a} Jump a -> nullCode {aluCode=Incr,jmpM=Just a} Load a r -> nullCode {ldReg=r,rdAddr=a} Store r a -> nullCode {inputX=r,wrAddrM=Just a} Nop -> nullCode -- ALU regX = regbank 'Clash.Sized.Vector.!!' inputX regY = regbank 'Clash.Sized.Vector.!!' inputY aluOut = alu aluCode regX regY -- next instruction nextPC = case jmpM of Just a | aluOut /= 0 -> ipntr + a _ -> ipntr + 1 -- update registers ldRegD' = ldReg -- Delay the ldReg by 1 cycle regbank' = 'Clash.Sized.Vector.replace' Zero 0 $ 'Clash.Sized.Vector.replace' PC nextPC $ 'Clash.Sized.Vector.replace' result aluOut $ 'Clash.Sized.Vector.replace' ldRegD memOut $ regbank @ We can now finally instantiate our system with a 'blockRam': @ system3 :: ( KnownDomain dom , KnownNat n ) => Vec n Instruction -> Clock dom -> Reset dom -> Enable dom -> Signal dom Value system3 instrs clk rst en = memOut where memOut = 'blockRam' clk en (replicate d32 0) rdAddr dout (rdAddr,dout,ipntr) = 'Clash.Explicit.Prelude.mealyB' clk rst en cpu2 (('Clash.Sized.Vector.replicate' d7 0),Zero) (memOut,instr) instr = 'Clash.Explicit.Prelude.asyncRom' instrs '<$>' ipntr @ We are, however, not done. We will also need to update our program. The reason being that values that we try to load in our registers won't be loaded into the register until the next cycle. This is a problem when the next instruction immediately depends on this memory value. In our example, this was only the case when we loaded the value @6@, which was stored at address @1@, into @RegB@. Our updated program is thus: @ prog2 = -- 0 := 4 Compute Incr Zero RegA RegA :> replicate d3 (Compute Incr RegA Zero RegA) ++ Store RegA 0 :> -- 1 := 6 Compute Incr Zero RegA RegA :> replicate d5 (Compute Incr RegA Zero RegA) ++ Store RegA 1 :> -- A := 4 Load 0 RegA :> -- B := 6 Load 1 RegB :> Nop :> -- Extra NOP -- start Compute CmpGt RegA RegB RegC :> Branch RegC 4 :> Compute CmpGt RegB RegA RegC :> Branch RegC 4 :> Jump 5 :> -- (a > b) Compute Sub RegA RegB RegA :> Jump (-6) :> -- (b > a) Compute Sub RegB RegA RegB :> Jump (-8) :> -- end Store RegA 2 :> Load 2 RegC :> Nil @ When we simulate our system we see that it works. This time again, we need to disregard the first sample, because the initial output of a 'blockRam' is /undefined/. We use the utility function 'Clash.XException.printX' to conveniently filter out the undefinedness and replace it with the string @\"undefined\"@. @ >>> printX $ sampleN 34 $ system3 prog2 systemClockGen resetGen enableGen [undefined,0,0,0,0,0,0,4,4,4,4,4,4,4,4,6,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2] @ This concludes the short introduction to using 'blockRam'. -} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE GADTs #-} # LANGUAGE NoImplicitPrelude # # LANGUAGE Trustworthy # # OPTIONS_GHC -fplugin GHC.TypeLits . KnownNat . Solver # {-# OPTIONS_HADDOCK show-extensions #-} -- See [Note: eta port names for trueDualPortBlockRam] # OPTIONS_GHC -fno - do - lambda - eta - expansion # -- See: -lang/clash-compiler/commit/721fcfa9198925661cd836668705f817bddaae3c -- as to why we need this. # OPTIONS_GHC -fno - cpr - anal # module Clash.Explicit.BlockRam ( -- * Block RAM synchronized to an arbitrary clock blockRam , blockRamPow2 , blockRamU , blockRam1 , ResetStrategy(..) -- ** Read/write conflict resolution , readNew * True dual - port block RAM $ tdpbram , trueDualPortBlockRam , RamOp(..) -- * Internal , blockRam# , blockRamU# , blockRam1# , trueDualPortBlockRam# ) where import Clash.HaskellPrelude import Control.Exception (catch, throw) import Control.Monad (forM_) import Control.Monad.ST (ST, runST) import Control.Monad.ST.Unsafe (unsafeInterleaveST, unsafeIOToST, unsafeSTToIO) import Data.Array.MArray (newListArray) import qualified Data.List as L import Data.Maybe (isJust, fromMaybe) import GHC.Arr (STArray, unsafeReadSTArray, unsafeWriteSTArray) import qualified Data.Sequence as Seq import Data.Sequence (Seq) import Data.Tuple (swap) import GHC.Generics (Generic) import GHC.Stack (HasCallStack, withFrozenCallStack) import GHC.TypeLits (KnownNat, type (^), type (<=)) import Unsafe.Coerce (unsafeCoerce) import Clash.Annotations.Primitive (hasBlackBox) import Clash.Class.Num (SaturationMode(SatBound), satSucc) import Clash.Explicit.Signal (KnownDomain, Enable, register, fromEnable) import Clash.Signal.Internal (Clock(..), Reset, Signal (..), ClockAB (..), invertReset, (.&&.), mux, clockTicks) import Clash.Promoted.Nat (SNat(..), snatToNum, natToNum) import Clash.Signal.Bundle (unbundle, bundle) import Clash.Signal.Internal.Ambiguous (clockPeriod) import Clash.Sized.Unsigned (Unsigned) import Clash.Sized.Index (Index) import Clash.Sized.Vector (Vec, replicate, iterateI) import qualified Clash.Sized.Vector as CV import Clash.XException (maybeIsX, NFDataX(deepErrorX), defaultSeqX, fromJustX, undefined, XException (..), seqX, isX, errorX) $ tdpbram A true dual - port block RAM has two fully independent , fully functional access ports : port A and port B. Either port can do both RAM reads and writes . These two ports can even be on distinct clock domains , but the memory itself is shared between the ports . This also makes a true dual - port block RAM suitable as a component in a domain crossing circuit ( but it needs additional logic for it to be safe , see e.g. ' Clash . Explicit . Synchronizer.asyncFIFOSynchronizer ' ) . A version with implicit clocks can be found in " Clash . Prelude . BlockRam " . A true dual-port block RAM has two fully independent, fully functional access ports: port A and port B. Either port can do both RAM reads and writes. These two ports can even be on distinct clock domains, but the memory itself is shared between the ports. This also makes a true dual-port block RAM suitable as a component in a domain crossing circuit (but it needs additional logic for it to be safe, see e.g. 'Clash.Explicit.Synchronizer.asyncFIFOSynchronizer'). A version with implicit clocks can be found in "Clash.Prelude.BlockRam". -} -- start benchmark only import ( listArray , unsafeThawSTArray ) -- end benchmark only $ setup > > > import Clash . Explicit . Prelude as C > > > import qualified Data . List as L > > > : set -XDataKinds -XRecordWildCards -XTupleSections -XDeriveAnyClass -XDeriveGeneric > > > type InstrAddr = Unsigned 8 > > > type = Unsigned 5 > > > type Value = Signed 8 > > > : { data = Zero | PC | RegA | RegB | RegC | RegD | deriving ( Eq , Show , , C.Generic , ) :} > > > : { data Operator = Add | Sub | Incr | Imm | CmpGt deriving ( Eq , Show , Generic , ) :} > > > : { data Instruction = Compute Operator | Branch Reg Value | Jump Value | Load | Store Reg MemAddr | Nop deriving ( Eq , Show , Generic , ) :} > > > : { data MachCode = MachCode { inputX : : , inputY : : , result : : , aluCode : : Operator , ldReg : : , rdAddr : : , wrAddrM : : Maybe , jmpM : : Maybe Value } :} > > > : { nullCode = MachCode { inputX = Zero , inputY = Zero , result = Zero , aluCode = , ldReg = Zero , rdAddr = 0 , wrAddrM = Nothing , jmpM = Nothing } :} > > > : { alu Add x y = x + y alu Sub x y = x - y alu _ = x + 1 alu Imm x _ = x alu CmpGt x y = if x > y then 1 else 0 :} > > > : { let cpu : : -- ^ Register bank - > ( Value , Instruction ) -- ^ ( Memory output , Current instruction ) - > ( Vec 7 Value , ( , Maybe ( , Value),InstrAddr ) ) cpu regbank ( memOut , instr ) = ( regbank',(rdAddr,(,aluOut ) < $ > wrAddrM , bitCoerce ipntr ) ) where -- Current instruction pointer ipntr = regbank C. ! ! PC -- Decoder ( MachCode { .. } ) = case instr of Compute op rx ry res - > nullCode { inputX = rx , inputY = ry , result = res , aluCode = op } Branch cr a - > nullCode { inputX = cr , jmpM = Just a } Jump a - > nullCode { aluCode = Incr , jmpM = Just a } Load a r - > nullCode { ldReg = r , } Store r a - > nullCode { inputX = r , wrAddrM = Just a } nullCode -- ALU regX = regbank C. ! ! inputX regY = regbank C. ! ! inputY aluOut = alu aluCode regX regY -- next instruction nextPC = case jmpM of Just a | aluOut /= 0 - > ipntr + a _ - > ipntr + 1 -- update registers regbank ' = replace Zero 0 $ replace PC nextPC $ replace result aluOut $ replace ldReg memOut $ regbank :} > > > : { let dataMem : : = > Clock dom - > Reset dom - > Enable dom - > Signal dom > Signal dom ( Maybe ( , Value ) ) - > Signal dom Value dataMem clk rst en rd wrM = mealy clk rst en dataMemT ( C.replicate d32 0 ) ( bundle ( rd , wrM ) ) where dataMemT mem ( rd , wrM ) = ( mem',dout ) where dout = mem C. ! ! = case wrM of Just ( wr , din ) - > replace Nothing - > mem :} > > > : { let system : : ( KnownDomain dom , KnownNat n ) = > - > Clock dom - > Reset dom - > Enable dom - > Signal dom Value system instrs clk rst en = memOut where memOut = dataMem clk rst en ( rdAddr , dout , ipntr ) = mealyB clk rst en cpu ( C.replicate d7 0 ) ( memOut , instr ) instr = asyncRom instrs < $ > ipntr :} > > > : { -- Compute GCD of 4 and 6 prog = -- 0 : = 4 Compute Incr Zero RegA RegA :> C.replicate d3 ( Compute Incr RegA Zero RegA ) C.++ Store RegA 0 :> -- 1 : = 6 Compute Incr Zero RegA RegA :> C.replicate d5 ( Compute Incr RegA Zero RegA ) C.++ Store RegA 1 :> -- A : = 4 Load 0 RegA :> -- B : = 6 Load 1 RegB :> -- start Compute CmpGt RegA RegB RegC :> Branch RegC 4 :> Compute CmpGt RegB RegA RegC :> Branch RegC 4 :> Jump 5 :> -- ( a > b ) Compute Sub RegA RegB RegA :> Jump ( -6 ) :> -- ( b > a ) Compute Sub RegB RegA RegB :> Jump (-8 ) :> -- end Store RegA 2 :> Load 2 RegC :> Nil :} > > > : { let : : ( KnownDomain dom , KnownNat n ) = > - > Clock dom - > Reset dom - > Enable dom - > Signal dom Value rst en = memOut where memOut = asyncRam clk clk en ( rdAddr , dout , ipntr ) = mealyB clk rst en cpu ( C.replicate d7 0 ) ( memOut , instr ) instr = asyncRom instrs < $ > ipntr :} > > > : { let cpu2 : : ( Vec 7 Value , ) -- ^ ( Register bank , Load reg addr ) - > ( Value , Instruction ) -- ^ ( Memory output , Current instruction ) - > ( ( Vec 7 Value , ) , ( , Maybe ( , Value),InstrAddr ) ) cpu2 ( regbank , ldRegD ) ( memOut , instr ) = ( ( regbank',ldRegD'),(rdAddr,(,aluOut ) < $ > wrAddrM , bitCoerce ipntr ) ) where -- Current instruction pointer ipntr = regbank C. ! ! PC -- Decoder ( MachCode { .. } ) = case instr of Compute op rx ry res - > nullCode { inputX = rx , inputY = ry , result = res , aluCode = op } Branch cr a - > nullCode { inputX = cr , jmpM = Just a } Jump a - > nullCode { aluCode = Incr , jmpM = Just a } Load a r - > nullCode { ldReg = r , } Store r a - > nullCode { inputX = r , wrAddrM = Just a } nullCode -- ALU regX = regbank C. ! ! inputX regY = regbank C. ! ! inputY aluOut = alu aluCode regX regY -- next instruction nextPC = case jmpM of Just a | aluOut /= 0 - > ipntr + a _ - > ipntr + 1 -- update registers ldRegD ' = ldReg -- Delay the ldReg by 1 cycle regbank ' = replace Zero 0 $ replace PC nextPC $ replace result aluOut $ replace ldRegD memOut $ regbank :} > > > : { let : : ( KnownDomain dom , KnownNat n ) = > - > Clock dom - > Reset dom - > Enable dom - > Signal dom Value rst en = memOut where memOut = blockRam clk en ( C.replicate d32 0 ) ( rdAddr , dout , ipntr ) = mealyB clk rst en cpu2 ( ( C.replicate d7 0),Zero ) ( memOut , instr ) instr = asyncRom instrs < $ > ipntr :} > > > : { prog2 = -- 0 : = 4 Compute Incr Zero RegA RegA :> C.replicate d3 ( Compute Incr RegA Zero RegA ) C.++ Store RegA 0 :> -- 1 : = 6 Compute Incr Zero RegA RegA :> C.replicate d5 ( Compute Incr RegA Zero RegA ) C.++ Store RegA 1 :> -- A : = 4 Load 0 RegA :> -- B : = 6 Load 1 RegB :> Nop :> -- Extra NOP -- start Compute CmpGt RegA RegB RegC :> Branch RegC 4 :> Compute CmpGt RegB RegA RegC :> Branch RegC 4 :> Jump 5 :> -- ( a > b ) Compute Sub RegA RegB RegA :> Jump ( -6 ) :> -- ( b > a ) Compute Sub RegB RegA RegB :> Jump (-8 ) :> -- end Store RegA 2 :> Load 2 RegC :> Nil :} >>> import Clash.Explicit.Prelude as C >>> import qualified Data.List as L >>> :set -XDataKinds -XRecordWildCards -XTupleSections -XDeriveAnyClass -XDeriveGeneric >>> type InstrAddr = Unsigned 8 >>> type MemAddr = Unsigned 5 >>> type Value = Signed 8 >>> :{ data Reg = Zero | PC | RegA | RegB | RegC | RegD | RegE deriving (Eq,Show,Enum,C.Generic,NFDataX) :} >>> :{ data Operator = Add | Sub | Incr | Imm | CmpGt deriving (Eq, Show, Generic, NFDataX) :} >>> :{ data Instruction = Compute Operator Reg Reg Reg | Branch Reg Value | Jump Value | Load MemAddr Reg | Store Reg MemAddr | Nop deriving (Eq, Show, Generic, NFDataX) :} >>> :{ data MachCode = MachCode { inputX :: Reg , inputY :: Reg , result :: Reg , aluCode :: Operator , ldReg :: Reg , rdAddr :: MemAddr , wrAddrM :: Maybe MemAddr , jmpM :: Maybe Value } :} >>> :{ nullCode = MachCode { inputX = Zero, inputY = Zero, result = Zero, aluCode = Imm , ldReg = Zero, rdAddr = 0, wrAddrM = Nothing , jmpM = Nothing } :} >>> :{ alu Add x y = x + y alu Sub x y = x - y alu Incr x _ = x + 1 alu Imm x _ = x alu CmpGt x y = if x > y then 1 else 0 :} >>> :{ let cpu :: Vec 7 Value -- ^ Register bank -> (Value,Instruction) -- ^ (Memory output, Current instruction) -> ( Vec 7 Value , (MemAddr,Maybe (MemAddr,Value),InstrAddr) ) cpu regbank (memOut,instr) = (regbank',(rdAddr,(,aluOut) <$> wrAddrM,bitCoerce ipntr)) where -- Current instruction pointer ipntr = regbank C.!! PC -- Decoder (MachCode {..}) = case instr of Compute op rx ry res -> nullCode {inputX=rx,inputY=ry,result=res,aluCode=op} Branch cr a -> nullCode {inputX=cr,jmpM=Just a} Jump a -> nullCode {aluCode=Incr,jmpM=Just a} Load a r -> nullCode {ldReg=r,rdAddr=a} Store r a -> nullCode {inputX=r,wrAddrM=Just a} Nop -> nullCode -- ALU regX = regbank C.!! inputX regY = regbank C.!! inputY aluOut = alu aluCode regX regY -- next instruction nextPC = case jmpM of Just a | aluOut /= 0 -> ipntr + a _ -> ipntr + 1 -- update registers regbank' = replace Zero 0 $ replace PC nextPC $ replace result aluOut $ replace ldReg memOut $ regbank :} >>> :{ let dataMem :: KnownDomain dom => Clock dom -> Reset dom -> Enable dom -> Signal dom MemAddr -> Signal dom (Maybe (MemAddr,Value)) -> Signal dom Value dataMem clk rst en rd wrM = mealy clk rst en dataMemT (C.replicate d32 0) (bundle (rd,wrM)) where dataMemT mem (rd,wrM) = (mem',dout) where dout = mem C.!! rd mem' = case wrM of Just (wr,din) -> replace wr din mem Nothing -> mem :} >>> :{ let system :: ( KnownDomain dom , KnownNat n ) => Vec n Instruction -> Clock dom -> Reset dom -> Enable dom -> Signal dom Value system instrs clk rst en = memOut where memOut = dataMem clk rst en rdAddr dout (rdAddr,dout,ipntr) = mealyB clk rst en cpu (C.replicate d7 0) (memOut,instr) instr = asyncRom instrs <$> ipntr :} >>> :{ -- Compute GCD of 4 and 6 prog = -- 0 := 4 Compute Incr Zero RegA RegA :> C.replicate d3 (Compute Incr RegA Zero RegA) C.++ Store RegA 0 :> -- 1 := 6 Compute Incr Zero RegA RegA :> C.replicate d5 (Compute Incr RegA Zero RegA) C.++ Store RegA 1 :> -- A := 4 Load 0 RegA :> -- B := 6 Load 1 RegB :> -- start Compute CmpGt RegA RegB RegC :> Branch RegC 4 :> Compute CmpGt RegB RegA RegC :> Branch RegC 4 :> Jump 5 :> -- (a > b) Compute Sub RegA RegB RegA :> Jump (-6) :> -- (b > a) Compute Sub RegB RegA RegB :> Jump (-8) :> -- end Store RegA 2 :> Load 2 RegC :> Nil :} >>> :{ let system2 :: ( KnownDomain dom , KnownNat n ) => Vec n Instruction -> Clock dom -> Reset dom -> Enable dom -> Signal dom Value system2 instrs clk rst en = memOut where memOut = asyncRam clk clk en d32 rdAddr dout (rdAddr,dout,ipntr) = mealyB clk rst en cpu (C.replicate d7 0) (memOut,instr) instr = asyncRom instrs <$> ipntr :} >>> :{ let cpu2 :: (Vec 7 Value,Reg) -- ^ (Register bank, Load reg addr) -> (Value,Instruction) -- ^ (Memory output, Current instruction) -> ( (Vec 7 Value,Reg) , (MemAddr,Maybe (MemAddr,Value),InstrAddr) ) cpu2 (regbank,ldRegD) (memOut,instr) = ((regbank',ldRegD'),(rdAddr,(,aluOut) <$> wrAddrM,bitCoerce ipntr)) where -- Current instruction pointer ipntr = regbank C.!! PC -- Decoder (MachCode {..}) = case instr of Compute op rx ry res -> nullCode {inputX=rx,inputY=ry,result=res,aluCode=op} Branch cr a -> nullCode {inputX=cr,jmpM=Just a} Jump a -> nullCode {aluCode=Incr,jmpM=Just a} Load a r -> nullCode {ldReg=r,rdAddr=a} Store r a -> nullCode {inputX=r,wrAddrM=Just a} Nop -> nullCode -- ALU regX = regbank C.!! inputX regY = regbank C.!! inputY aluOut = alu aluCode regX regY -- next instruction nextPC = case jmpM of Just a | aluOut /= 0 -> ipntr + a _ -> ipntr + 1 -- update registers ldRegD' = ldReg -- Delay the ldReg by 1 cycle regbank' = replace Zero 0 $ replace PC nextPC $ replace result aluOut $ replace ldRegD memOut $ regbank :} >>> :{ let system3 :: ( KnownDomain dom , KnownNat n ) => Vec n Instruction -> Clock dom -> Reset dom -> Enable dom -> Signal dom Value system3 instrs clk rst en = memOut where memOut = blockRam clk en (C.replicate d32 0) rdAddr dout (rdAddr,dout,ipntr) = mealyB clk rst en cpu2 ((C.replicate d7 0),Zero) (memOut,instr) instr = asyncRom instrs <$> ipntr :} >>> :{ prog2 = -- 0 := 4 Compute Incr Zero RegA RegA :> C.replicate d3 (Compute Incr RegA Zero RegA) C.++ Store RegA 0 :> -- 1 := 6 Compute Incr Zero RegA RegA :> C.replicate d5 (Compute Incr RegA Zero RegA) C.++ Store RegA 1 :> -- A := 4 Load 0 RegA :> -- B := 6 Load 1 RegB :> Nop :> -- Extra NOP -- start Compute CmpGt RegA RegB RegC :> Branch RegC 4 :> Compute CmpGt RegB RegA RegC :> Branch RegC 4 :> Jump 5 :> -- (a > b) Compute Sub RegA RegB RegA :> Jump (-6) :> -- (b > a) Compute Sub RegB RegA RegB :> Jump (-8) :> -- end Store RegA 2 :> Load 2 RegC :> Nil :} -} | Create a block RAM with space for @n@ elements -- * _ _ NB _ _ : Read value is delayed by 1 cycle -- * __NB__: Initial output value is /undefined/, reading it will throw an -- 'XException' -- -- === See also: -- -- * See "Clash.Explicit.BlockRam#usingrams" for more information on how to use a block RAM . -- * Use the adapter 'readNew' for obtaining write-before-read semantics like -- this: @'readNew' clk rst en ('blockRam' clk inits) rd wrM@. * A large ' ' for the initial content may be too inefficient , depending on how it is constructed . See ' Clash . Explicit . BlockRam . File.blockRamFile ' and ' Clash . Explicit . BlockRam . ' for different approaches that -- scale well. -- -- === __Example__ -- @ bram40 -- :: 'Clock' dom -- -> 'Enable' dom - > ' Signal ' dom ( ' Unsigned ' 6 ) -- -> 'Signal' dom (Maybe ('Unsigned' 6, 'Clash.Sized.BitVector.Bit')) -- -> 'Signal' dom 'Clash.Sized.BitVector.Bit' bram40 clk en = ' blockRam ' clk en ( ' Clash.Sized.Vector.replicate ' d40 1 ) -- @ blockRam :: ( KnownDomain dom , HasCallStack , NFDataX a , Enum addr , NFDataX addr ) => Clock dom -- ^ 'Clock' to synchronize to -> Enable dom -- ^ 'Enable' line -> Vec n a ^ Initial content of the , also determines the size , @n@ , of the -- -- __NB__: __MUST__ be a constant -> Signal dom addr -- ^ Read address @r@ -> Signal dom (Maybe (addr, a)) -- ^ (write address @w@, value to write) -> Signal dom a ^ Value of the at address @r@ from the previous clock cycle blockRam = \clk gen content rd wrM -> let en = isJust <$> wrM (wr,din) = unbundle (fromJustX <$> wrM) in withFrozenCallStack (blockRam# clk gen content (fromEnum <$> rd) en (fromEnum <$> wr) din) # INLINE blockRam # | Create a block RAM with space for 2^@n@ elements -- * _ _ NB _ _ : Read value is delayed by 1 cycle -- * __NB__: Initial output value is /undefined/, reading it will throw an -- 'XException' -- -- === See also: -- -- * See "Clash.Prelude.BlockRam#usingrams" for more information on how to use a block RAM . -- * Use the adapter 'readNew' for obtaining write-before-read semantics like -- this: @'readNew' clk rst en ('blockRamPow2' clk inits) rd wrM@. * A large ' ' for the initial content may be too inefficient , depending on how it is constructed . See ' Clash . Explicit . BlockRam . File.blockRamFilePow2 ' and ' Clash . Explicit . BlockRam . Blob.blockRamBlobPow2 ' for different approaches -- that scale well. -- -- === __Example__ -- @ -- bram32 -- :: 'Clock' dom -- -> 'Enable' dom - > ' Signal ' dom ( ' Unsigned ' 5 ) -- -> 'Signal' dom (Maybe ('Unsigned' 5, 'Clash.Sized.BitVector.Bit')) -- -> 'Signal' dom 'Clash.Sized.BitVector.Bit' bram32 clk en = ' blockRamPow2 ' clk en ( ' Clash.Sized.Vector.replicate ' d32 1 ) -- @ blockRamPow2 :: ( KnownDomain dom , HasCallStack , NFDataX a , KnownNat n ) => Clock dom -- ^ 'Clock' to synchronize to -> Enable dom -- ^ 'Enable' line -> Vec (2^n) a ^ Initial content of the -- -- __NB__: __MUST__ be a constant -> Signal dom (Unsigned n) -- ^ Read address @r@ -> Signal dom (Maybe (Unsigned n, a)) -- ^ (Write address @w@, value to write) -> Signal dom a ^ Value of the at address @r@ from the previous clock cycle blockRamPow2 = \clk en cnt rd wrM -> withFrozenCallStack (blockRam clk en cnt rd wrM) # INLINE blockRamPow2 # data ResetStrategy (r :: Bool) where ClearOnReset :: ResetStrategy 'True NoClearOnReset :: ResetStrategy 'False | A version of ' blockRam ' that has no default values set . May be cleared to -- an arbitrary state using a reset function. blockRamU :: forall n dom a r addr . ( KnownDomain dom , HasCallStack , NFDataX a , Enum addr , NFDataX addr , 1 <= n ) => Clock dom -- ^ 'Clock' to synchronize to -> Reset dom -- ^ 'Reset' line. This needs to be asserted for at least /n/ cycles in order for the to be reset to its initial state . -> Enable dom -- ^ 'Enable' line -> ResetStrategy r ^ Whether to clear on asserted reset ( ' ClearOnReset ' ) or -- not ('NoClearOnReset'). The reset needs to be asserted for at least /n/ cycles to clear the . -> SNat n ^ Number of elements in -> (Index n -> a) ^ If applicable ( see ' ResetStrategy ' argument ) , reset using this function -> Signal dom addr -- ^ Read address @r@ -> Signal dom (Maybe (addr, a)) -- ^ (write address @w@, value to write) -> Signal dom a ^ Value of the at address @r@ from the previous clock cycle blockRamU clk rst0 en rstStrategy n@SNat initF rd0 mw0 = case rstStrategy of ClearOnReset -> -- Use reset infrastructure blockRamU# clk en n rd1 we1 wa1 w1 NoClearOnReset -> -- Ignore reset infrastructure, pass values unchanged blockRamU# clk en n (fromEnum <$> rd0) we0 (fromEnum <$> wa0) w0 where rstBool = register clk rst0 en True (pure False) rstInv = invertReset rst0 waCounter :: Signal dom (Index n) waCounter = register clk rstInv en 0 (satSucc SatBound <$> waCounter) wa0 = fst . fromJustX <$> mw0 w0 = snd . fromJustX <$> mw0 we0 = isJust <$> mw0 rd1 = mux rstBool 0 (fromEnum <$> rd0) we1 = mux rstBool (pure True) we0 wa1 = mux rstBool (fromInteger . toInteger <$> waCounter) (fromEnum <$> wa0) w1 = mux rstBool (initF <$> waCounter) w0 -- | blockRAMU primitive blockRamU# :: forall n dom a . ( KnownDomain dom , HasCallStack , NFDataX a ) => Clock dom -- ^ 'Clock' to synchronize to -> Enable dom -- ^ 'Enable' line -> SNat n ^ Number of elements in -> Signal dom Int -- ^ Read address @r@ -> Signal dom Bool -- ^ Write enable -> Signal dom Int -- ^ Write address @w@ -> Signal dom a -- ^ Value to write (at address @w@) -> Signal dom a ^ Value of the at address @r@ from the previous clock cycle blockRamU# clk en SNat = TODO : to single BRAM primitive taking an initialization function blockRam# clk en (CV.map (\i -> deepErrorX $ "Initial value at index " <> show i <> " undefined.") (iterateI @n succ (0 :: Int))) # NOINLINE blockRamU # # {-# ANN blockRamU# hasBlackBox #-} -- | A version of 'blockRam' that is initialized with the same value on all -- memory positions blockRam1 :: forall n dom a r addr . ( KnownDomain dom , HasCallStack , NFDataX a , Enum addr , NFDataX addr , 1 <= n ) => Clock dom -- ^ 'Clock' to synchronize to -> Reset dom -- ^ 'Reset' line. This needs to be asserted for at least /n/ cycles in order for the to be reset to its initial state . -> Enable dom -- ^ 'Enable' line -> ResetStrategy r ^ Whether to clear on asserted reset ( ' ClearOnReset ' ) or -- not ('NoClearOnReset'). The reset needs to be asserted for at least /n/ cycles to clear the . -> SNat n ^ Number of elements in -> a ^ Initial content of the ( replicated /n/ times ) -> Signal dom addr -- ^ Read address @r@ -> Signal dom (Maybe (addr, a)) -- ^ (write address @w@, value to write) -> Signal dom a ^ Value of the at address @r@ from the previous clock cycle blockRam1 clk rst0 en rstStrategy n@SNat a rd0 mw0 = case rstStrategy of ClearOnReset -> -- Use reset infrastructure blockRam1# clk en n a rd1 we1 wa1 w1 NoClearOnReset -> -- Ignore reset infrastructure, pass values unchanged blockRam1# clk en n a (fromEnum <$> rd0) we0 (fromEnum <$> wa0) w0 where rstBool = register clk rst0 en True (pure False) rstInv = invertReset rst0 waCounter :: Signal dom (Index n) waCounter = register clk rstInv en 0 (satSucc SatBound <$> waCounter) wa0 = fst . fromJustX <$> mw0 w0 = snd . fromJustX <$> mw0 we0 = isJust <$> mw0 rd1 = mux rstBool 0 (fromEnum <$> rd0) we1 = mux rstBool (pure True) we0 wa1 = mux rstBool (fromInteger . toInteger <$> waCounter) (fromEnum <$> wa0) w1 = mux rstBool (pure a) w0 -- | blockRAM1 primitive blockRam1# :: forall n dom a . ( KnownDomain dom , HasCallStack , NFDataX a ) => Clock dom -- ^ 'Clock' to synchronize to -> Enable dom -- ^ 'Enable' line -> SNat n ^ Number of elements in -> a ^ Initial content of the ( replicated /n/ times ) -> Signal dom Int -- ^ Read address @r@ -> Signal dom Bool -- ^ Write enable -> Signal dom Int -- ^ Write address @w@ -> Signal dom a -- ^ Value to write (at address @w@) -> Signal dom a ^ Value of the at address @r@ from the previous clock cycle blockRam1# clk en n a = TODO : to single BRAM primitive taking an initialization function blockRam# clk en (replicate n a) # NOINLINE blockRam1 # # {-# ANN blockRam1# hasBlackBox #-} -- | blockRAM primitive blockRam# :: forall dom a n . ( KnownDomain dom , HasCallStack , NFDataX a ) => Clock dom -- ^ 'Clock' to synchronize to -> Enable dom -- ^ 'Enable' line -> Vec n a ^ Initial content of the , also determines the size , @n@ , of the -- -- __NB__: __MUST__ be a constant -> Signal dom Int -- ^ Read address @r@ -> Signal dom Bool -- ^ Write enable -> Signal dom Int -- ^ Write address @w@ -> Signal dom a -- ^ Value to write (at address @w@) -> Signal dom a ^ Value of the at address @r@ from the previous clock cycle blockRam# (Clock _ Nothing) gen content = \rd wen waS wd -> runST $ do ramStart <- newListArray (0,szI-1) contentL -- start benchmark only < - unsafeThawSTArray ramArr -- end benchmark only go ramStart (withFrozenCallStack (deepErrorX "blockRam: intial value undefined")) (fromEnable gen) rd (fromEnable gen .&&. wen) waS wd where contentL = unsafeCoerce content :: [a] szI = L.length contentL -- start benchmark only ramArr = listArray ( 0,szI-1 ) contentL -- end benchmark only go :: STArray s Int a -> a -> Signal dom Bool -> Signal dom Int -> Signal dom Bool -> Signal dom Int -> Signal dom a -> ST s (Signal dom a) go !ram o ret@(~(re :- res)) rt@(~(r :- rs)) et@(~(e :- en)) wt@(~(w :- wr)) dt@(~(d :- din)) = do o `seqX` (o :-) <$> (ret `seq` rt `seq` et `seq` wt `seq` dt `seq` unsafeInterleaveST (do o' <- unsafeIOToST (catch (if re then unsafeSTToIO (ram `safeAt` r) else pure o) (\err@XException {} -> pure (throw err))) d `defaultSeqX` upd ram e (fromEnum w) d go ram o' res rs en wr din)) upd :: STArray s Int a -> Bool -> Int -> a -> ST s () upd ram we waddr d = case maybeIsX we of Nothing -> case maybeIsX waddr of Nothing -> -- Put the XException from `waddr` as the value in all -- locations of `ram`. forM_ [0..(szI-1)] (\i -> unsafeWriteSTArray ram i (seq waddr d)) Just wa -> -- Put the XException from `we` as the value at address -- `waddr`. safeUpdate wa (seq we d) ram Just True -> case maybeIsX waddr of Nothing -> -- Put the XException from `waddr` as the value in all -- locations of `ram`. forM_ [0..(szI-1)] (\i -> unsafeWriteSTArray ram i (seq waddr d)) Just wa -> safeUpdate wa d ram _ -> return () safeAt :: HasCallStack => STArray s Int a -> Int -> ST s a safeAt s i = if (0 <= i) && (i < szI) then unsafeReadSTArray s i else pure $ withFrozenCallStack (deepErrorX ("blockRam: read address " <> show i <> " not in range [0.." <> show szI <> ")")) # INLINE safeAt # safeUpdate :: HasCallStack => Int -> a -> STArray s Int a -> ST s () safeUpdate i a s = if (0 <= i) && (i < szI) then unsafeWriteSTArray s i a else let d = withFrozenCallStack (deepErrorX ("blockRam: write address " <> show i <> " not in range [0.." <> show szI <> ")")) in forM_ [0..(szI-1)] (\j -> unsafeWriteSTArray s j d) # INLINE safeUpdate # blockRam# _ _ _ = error "blockRam#: dynamic clocks not supported" {-# ANN blockRam# hasBlackBox #-} # NOINLINE blockRam # # | Create a read - after - write block RAM from a read - before - write one readNew :: ( KnownDomain dom , NFDataX a , Eq addr ) => Clock dom -> Reset dom -> Enable dom -> (Signal dom addr -> Signal dom (Maybe (addr, a)) -> Signal dom a) ^ The component -> Signal dom addr -- ^ Read address @r@ -> Signal dom (Maybe (addr, a)) -- ^ (Write address @w@, value to write) -> Signal dom a ^ Value of the at address @r@ from the previous clock cycle readNew clk rst en ram rdAddr wrM = mux wasSame wasWritten $ ram rdAddr wrM where readNewT rd (Just (wr, wrdata)) = (wr == rd, wrdata) readNewT _ Nothing = (False , undefined) (wasSame,wasWritten) = unbundle (register clk rst en (False, undefined) (readNewT <$> rdAddr <*> wrM)) -- | Port operation data RamOp n a = RamRead (Index n) -- ^ Read from address | RamWrite (Index n) a -- ^ Write data to address | RamNoOp -- ^ No operation deriving (Generic, NFDataX, Show) ramOpAddr :: RamOp n a -> Index n ramOpAddr (RamRead addr) = addr ramOpAddr (RamWrite addr _) = addr ramOpAddr RamNoOp = errorX "Address for No operation undefined" isRamWrite :: RamOp n a -> Bool isRamWrite (RamWrite {}) = True isRamWrite _ = False ramOpWriteVal :: RamOp n a -> Maybe a ramOpWriteVal (RamWrite _ val) = Just val ramOpWriteVal _ = Nothing isOp :: RamOp n a -> Bool isOp RamNoOp = False isOp _ = True -- | Produces vendor-agnostic HDL that will be inferred as a true dual-port block RAM -- -- Any value that is being written on a particular port is also the -- value that will be read on that port, i.e. the same-port read/write behavior is : WriteFirst . For mixed - port read / write , when port A writes to the address -- port B reads from, the output of port B is undefined, and vice versa. trueDualPortBlockRam :: forall nAddrs domA domB a . ( HasCallStack , KnownNat nAddrs , KnownDomain domA , KnownDomain domB , NFDataX a ) => Clock domA -- ^ Clock for port A -> Clock domB -- ^ Clock for port B -> Signal domA (RamOp nAddrs a) -- ^ RAM operation for port A -> Signal domB (RamOp nAddrs a) -- ^ RAM operation for port B -> (Signal domA a, Signal domB a) -- ^ Outputs data on /next/ cycle. When writing, the data written -- will be echoed. When reading, the read data is returned. # INLINE trueDualPortBlockRam # trueDualPortBlockRam = \clkA clkB opA opB -> trueDualPortBlockRamWrapper clkA (isOp <$> opA) (isRamWrite <$> opA) (ramOpAddr <$> opA) (fromJustX . ramOpWriteVal <$> opA) clkB (isOp <$> opB) (isRamWrite <$> opB) (ramOpAddr <$> opB) (fromJustX . ramOpWriteVal <$> opB) toMaybeX :: a -> MaybeX a toMaybeX a = case isX a of Left _ -> IsX Right _ -> IsDefined a data MaybeX a = IsX | IsDefined !a data Conflict = Conflict { cfRWA :: !(MaybeX Bool) -- ^ Read/Write conflict for output A , cfRWB :: !(MaybeX Bool) -- ^ Read/Write conflict for output B , cfWW :: !(MaybeX Bool) -- ^ Write/Write conflict , cfAddress :: !(MaybeX Int) } -- [Note: eta port names for trueDualPortBlockRam] -- By naming all the arguments and setting the -fno - do - lambda - eta - expansion GHC -- option for this module, the generated HDL also contains names based on the -- argument names used here. This greatly improves readability of the HDL. -- [Note: true dual-port blockRAM separate architecture] -- A multi - clock true dual - port block RAM is only inferred from the generated HDL when it lives in its own Verilog module / VHDL architecture . Add any other -- logic to the module / architecture, and synthesis will no longer infer a multi - clock true dual - port block RAM . This wrapper pushes the primitive out -- into its own module / architecture. trueDualPortBlockRamWrapper clkA enA weA addrA datA clkB enB weB addrB datB = trueDualPortBlockRam# clkA enA weA addrA datA clkB enB weB addrB datB # NOINLINE trueDualPortBlockRamWrapper # -- | Primitive of 'trueDualPortBlockRam'. trueDualPortBlockRam#, trueDualPortBlockRamWrapper :: forall nAddrs domA domB a . ( HasCallStack , KnownNat nAddrs , KnownDomain domA , KnownDomain domB , NFDataX a ) => Clock domA -- ^ Clock for port A -> Signal domA Bool -- ^ Enable for port A -> Signal domA Bool -- ^ Write enable for port A -> Signal domA (Index nAddrs) -- ^ Address to read from or write to on port A -> Signal domA a -- ^ Data in for port A; ignored when /write enable/ is @False@ -> Clock domB -- ^ Clock for port B -> Signal domB Bool -- ^ Enable for port B -> Signal domB Bool -- ^ Write enable for port B -> Signal domB (Index nAddrs) -- ^ Address to read from or write to on port B -> Signal domB a -- ^ Data in for port B; ignored when /write enable/ is @False@ -> (Signal domA a, Signal domB a) ^ Outputs data on /next/ cycle . If write enable is @True@ , the data written -- will be echoed. If write enable is @False@, the read data is returned. If -- port enable is @False@, it is /undefined/. trueDualPortBlockRam# clkA enA weA addrA datA clkB enB weB addrB datB | snatToNum @Int (clockPeriod @domA) < snatToNum @Int (clockPeriod @domB) = swap (trueDualPortBlockRamModel labelB clkB enB weB addrB datB labelA clkA enA weA addrA datA) | otherwise = trueDualPortBlockRamModel labelA clkA enA weA addrA datA labelB clkB enB weB addrB datB where labelA = "Port A" labelB = "Port B" # NOINLINE trueDualPortBlockRam # # # ANN trueDualPortBlockRam # hasBlackBox # -- | Haskell model for the primitive 'trueDualPortBlockRam#'. -- Warning : this model only works if @domFast@ 's clock is faster than ( or equal -- to) @domSlow@'s clock. trueDualPortBlockRamModel :: forall nAddrs domFast domSlow a . ( HasCallStack , KnownNat nAddrs , KnownDomain domSlow , KnownDomain domFast , NFDataX a ) => String -> Clock domSlow -> Signal domSlow Bool -> Signal domSlow Bool -> Signal domSlow (Index nAddrs) -> Signal domSlow a -> String -> Clock domFast -> Signal domFast Bool -> Signal domFast Bool -> Signal domFast (Index nAddrs) -> Signal domFast a -> (Signal domSlow a, Signal domFast a) trueDualPortBlockRamModel labelA clkA enA weA addrA datA labelB clkB enB weB addrB datB = ( startA :- outA , startB :- outB ) where (outA, outB) = go (Seq.fromFunction (natToNum @nAddrs) initElement) ensure ' go ' hits ' goFast ' first for 1 cycle , then execute ' goBoth ' -- once, followed by the regular cadence of either 'ceil(tA / tB)' or ' floor(tA / tB ) ' cycles for the fast clock followed by 1 cycle of the -- slow clock (ClockB : clockTicks clkA clkB) (bundle (enA, weA, fromIntegral <$> addrA, datA)) (bundle (enB, weB, fromIntegral <$> addrB, datB)) startA startB startA = deepErrorX $ "trueDualPortBlockRam: " <> labelA <> ": First value undefined" startB = deepErrorX $ "trueDualPortBlockRam: " <> labelB <> ": First value undefined" initElement :: Int -> a initElement n = deepErrorX ("Unknown initial element; position " <> show n) unknownEnableAndAddr :: String -> String -> Int -> a unknownEnableAndAddr enaMsg addrMsg n = deepErrorX ("Write enable and address unknown; position " <> show n <> "\nWrite enable error message: " <> enaMsg <> "\nAddress error message: " <> addrMsg) unknownAddr :: String -> Int -> a unknownAddr msg n = deepErrorX ("Write enabled, but address unknown; position " <> show n <> "\nAddress error message: " <> msg) getConflict :: Bool -> Bool -> Bool -> Int -> Bool -> Int -> Maybe Conflict getConflict enA_ enB_ wenA addrA_ wenB addrB_ = -- If port A or port B is writing on (potentially!) the same address, -- there's a conflict if sameAddr then Just conflict else Nothing where wenAX = toMaybeX wenA wenBX = toMaybeX wenB mergeX IsX b = b mergeX a IsX = a mergeX (IsDefined a) (IsDefined b) = IsDefined (a && b) conflict = Conflict { cfRWA = if enB_ then wenBX else IsDefined False , cfRWB = if enA_ then wenAX else IsDefined False , cfWW = if enA_ && enB_ then mergeX wenAX wenBX else IsDefined False , cfAddress = toMaybeX addrA_ } sameAddr = case (isX addrA_, isX addrB_) of (Left _, _) -> True (_, Left _) -> True _ -> addrA_ == addrB_ writeRam :: Bool -> Int -> a -> Seq a -> (Maybe a, Seq a) writeRam enable addr dat mem | Left enaMsg <- enableUndefined , Left addrMsg <- addrUndefined = let msg = "Unknown enable and address" <> "\nWrite enable error message: " <> enaMsg <> "\nAddress error message: " <> addrMsg in ( Just (deepErrorX msg) , Seq.fromFunction (natToNum @nAddrs) (unknownEnableAndAddr enaMsg addrMsg) ) | Left enaMsg <- enableUndefined = let msg = "Write enable unknown; position" <> show addr <> "\nWrite enable error message: " <> enaMsg in writeRam True addr (deepErrorX msg) mem | enable , Left addrMsg <- addrUndefined = ( Just (deepErrorX "Unknown address") , Seq.fromFunction (natToNum @nAddrs) (unknownAddr addrMsg) ) | enable = (Just dat, Seq.update addr dat mem) | otherwise = (Nothing, mem) where enableUndefined = isX enable addrUndefined = isX addr go :: Seq a -> [ClockAB] -> Signal domSlow (Bool, Bool, Int, a) -> Signal domFast (Bool, Bool, Int, a) -> a -> a -> (Signal domSlow a, Signal domFast a) go _ [] _ _ = error "trueDualPortBlockRamModel.go: `ticks` should have been an infinite list" go ram0 (tick:ticks) as0 bs0 = case tick of ClockA -> goSlow ClockB -> goFast ClockAB -> goBoth where (enA_, weA_, addrA_, datA_) :- as1 = as0 (enB_, weB_, addrB_, datB_) :- bs1 = bs0 goBoth prevA prevB = outA2 `seqX` outB2 `seqX` (outA2 :- as2, outB2 :- bs2) where conflict = getConflict enA_ enB_ weA_ addrA_ weB_ addrB_ (datA1_,datB1_) = case conflict of Just Conflict{cfWW=IsDefined True} -> ( deepErrorX "trueDualPortBlockRam: conflicting write/write queries" , deepErrorX "trueDualPortBlockRam: conflicting write/write queries" ) Just Conflict{cfWW=IsX} -> ( deepErrorX "trueDualPortBlockRam: conflicting write/write queries" , deepErrorX "trueDualPortBlockRam: conflicting write/write queries" ) _ -> (datA_,datB_) (wroteA,ram1) = writeRam weA_ addrA_ datA1_ ram0 (wroteB,ram2) = writeRam weB_ addrB_ datB1_ ram1 outA1 = case conflict of Just Conflict{cfRWA=IsDefined True} -> deepErrorX "trueDualPortBlockRam: conflicting read/write queries" Just Conflict{cfRWA=IsX} -> deepErrorX "trueDualPortBlockRam: conflicting read/write queries" _ -> fromMaybe (ram0 `Seq.index` addrA_) wroteA outB1 = case conflict of Just Conflict{cfRWB=IsDefined True} -> deepErrorX "trueDualPortBlockRam: conflicting read/write queries" Just Conflict{cfRWB=IsX} -> deepErrorX "trueDualPortBlockRam: conflicting read/write queries" _ -> fromMaybe (ram0 `Seq.index` addrB_) wroteB outA2 = if enA_ then outA1 else prevA outB2 = if enB_ then outB1 else prevB (as2,bs2) = go ram2 ticks as1 bs1 outA2 outB2 1 iteration here , as this is the slow clock . goSlow _ prevB | enA_ = out0 `seqX` (out0 :- as2, bs2) where (wrote, !ram1) = writeRam weA_ addrA_ datA_ ram0 out0 = fromMaybe (ram1 `Seq.index` addrA_) wrote (as2, bs2) = go ram1 ticks as1 bs0 out0 prevB goSlow prevA prevB = (prevA :- as2, bs2) where (as2,bs2) = go ram0 ticks as1 bs0 prevA prevB 1 or more iterations here , as this is the fast clock . First iteration -- happens here. goFast prevA _ | enB_ = out0 `seqX` (as2, out0 :- bs2) where (wrote, !ram1) = writeRam weB_ addrB_ datB_ ram0 out0 = fromMaybe (ram1 `Seq.index` addrB_) wrote (as2, bs2) = go ram1 ticks as0 bs1 prevA out0 goFast prevA prevB = (as2, prevB :- bs2) where (as2,bs2) = go ram0 ticks as0 bs1 prevA prevB
null
https://raw.githubusercontent.com/clash-lang/clash-compiler/53d32a6b063f17c8f3e637582624d3804c95a7cd/clash-prelude/src/Clash/Explicit/BlockRam.hs
haskell
^ Register bank ^ ( Memory output , Current instruction ) Current instruction pointer Decoder ALU next instruction update registers ^ Read address ^ ( write address , data in ) ^ data out Compute GCD of 4 and 6 0 : = 4 1 : = 6 A : = 4 B : = 6 start ( a > b ) ( b > a ) end ^ ( Register bank , Load reg addr ) ^ ( Memory output , Current instruction ) Current instruction pointer Decoder ALU next instruction update registers Delay the ldReg by 1 cycle 0 : = 4 1 : = 6 A : = 4 B : = 6 Extra NOP start ( a > b ) ( b > a ) end ^ Register bank ^ (Memory output, Current instruction) Current instruction pointer Decoder ALU next instruction update registers ^ Read address ^ (write address, data in) ^ data out Compute GCD of 4 and 6 0 := 4 1 := 6 A := 4 B := 6 start (a > b) (b > a) end ^ (Register bank, Load reg addr) ^ (Memory output, Current instruction) Current instruction pointer Decoder ALU next instruction update registers Delay the ldReg by 1 cycle 0 := 4 1 := 6 A := 4 B := 6 Extra NOP start (a > b) (b > a) end # LANGUAGE DeriveAnyClass # # LANGUAGE GADTs # # OPTIONS_HADDOCK show-extensions # See [Note: eta port names for trueDualPortBlockRam] See: -lang/clash-compiler/commit/721fcfa9198925661cd836668705f817bddaae3c as to why we need this. * Block RAM synchronized to an arbitrary clock ** Read/write conflict resolution * Internal start benchmark only end benchmark only ^ Register bank ^ ( Memory output , Current instruction ) Current instruction pointer Decoder ALU next instruction update registers Compute GCD of 4 and 6 0 : = 4 1 : = 6 A : = 4 B : = 6 start ( a > b ) ( b > a ) end ^ ( Register bank , Load reg addr ) ^ ( Memory output , Current instruction ) Current instruction pointer Decoder ALU next instruction update registers Delay the ldReg by 1 cycle 0 : = 4 1 : = 6 A : = 4 B : = 6 Extra NOP start ( a > b ) ( b > a ) end ^ Register bank ^ (Memory output, Current instruction) Current instruction pointer Decoder ALU next instruction update registers Compute GCD of 4 and 6 0 := 4 1 := 6 A := 4 B := 6 start (a > b) (b > a) end ^ (Register bank, Load reg addr) ^ (Memory output, Current instruction) Current instruction pointer Decoder ALU next instruction update registers Delay the ldReg by 1 cycle 0 := 4 1 := 6 A := 4 B := 6 Extra NOP start (a > b) (b > a) end * __NB__: Initial output value is /undefined/, reading it will throw an 'XException' === See also: * See "Clash.Explicit.BlockRam#usingrams" for more information on how to use a * Use the adapter 'readNew' for obtaining write-before-read semantics like this: @'readNew' clk rst en ('blockRam' clk inits) rd wrM@. scale well. === __Example__ @ :: 'Clock' dom -> 'Enable' dom -> 'Signal' dom (Maybe ('Unsigned' 6, 'Clash.Sized.BitVector.Bit')) -> 'Signal' dom 'Clash.Sized.BitVector.Bit' @ ^ 'Clock' to synchronize to ^ 'Enable' line __NB__: __MUST__ be a constant ^ Read address @r@ ^ (write address @w@, value to write) * __NB__: Initial output value is /undefined/, reading it will throw an 'XException' === See also: * See "Clash.Prelude.BlockRam#usingrams" for more information on how to use a * Use the adapter 'readNew' for obtaining write-before-read semantics like this: @'readNew' clk rst en ('blockRamPow2' clk inits) rd wrM@. that scale well. === __Example__ @ bram32 :: 'Clock' dom -> 'Enable' dom -> 'Signal' dom (Maybe ('Unsigned' 5, 'Clash.Sized.BitVector.Bit')) -> 'Signal' dom 'Clash.Sized.BitVector.Bit' @ ^ 'Clock' to synchronize to ^ 'Enable' line __NB__: __MUST__ be a constant ^ Read address @r@ ^ (Write address @w@, value to write) an arbitrary state using a reset function. ^ 'Clock' to synchronize to ^ 'Reset' line. This needs to be asserted for at least /n/ cycles in order ^ 'Enable' line not ('NoClearOnReset'). The reset needs to be asserted for at least /n/ ^ Read address @r@ ^ (write address @w@, value to write) Use reset infrastructure Ignore reset infrastructure, pass values unchanged | blockRAMU primitive ^ 'Clock' to synchronize to ^ 'Enable' line ^ Read address @r@ ^ Write enable ^ Write address @w@ ^ Value to write (at address @w@) # ANN blockRamU# hasBlackBox # | A version of 'blockRam' that is initialized with the same value on all memory positions ^ 'Clock' to synchronize to ^ 'Reset' line. This needs to be asserted for at least /n/ cycles in order ^ 'Enable' line not ('NoClearOnReset'). The reset needs to be asserted for at least /n/ ^ Read address @r@ ^ (write address @w@, value to write) Use reset infrastructure Ignore reset infrastructure, pass values unchanged | blockRAM1 primitive ^ 'Clock' to synchronize to ^ 'Enable' line ^ Read address @r@ ^ Write enable ^ Write address @w@ ^ Value to write (at address @w@) # ANN blockRam1# hasBlackBox # | blockRAM primitive ^ 'Clock' to synchronize to ^ 'Enable' line __NB__: __MUST__ be a constant ^ Read address @r@ ^ Write enable ^ Write address @w@ ^ Value to write (at address @w@) start benchmark only end benchmark only start benchmark only end benchmark only Put the XException from `waddr` as the value in all locations of `ram`. Put the XException from `we` as the value at address `waddr`. Put the XException from `waddr` as the value in all locations of `ram`. # ANN blockRam# hasBlackBox # ^ Read address @r@ ^ (Write address @w@, value to write) | Port operation ^ Read from address ^ Write data to address ^ No operation | Produces vendor-agnostic HDL that will be inferred as a true dual-port Any value that is being written on a particular port is also the value that will be read on that port, i.e. the same-port read/write behavior port B reads from, the output of port B is undefined, and vice versa. ^ Clock for port A ^ Clock for port B ^ RAM operation for port A ^ RAM operation for port B ^ Outputs data on /next/ cycle. When writing, the data written will be echoed. When reading, the read data is returned. ^ Read/Write conflict for output A ^ Read/Write conflict for output B ^ Write/Write conflict [Note: eta port names for trueDualPortBlockRam] option for this module, the generated HDL also contains names based on the argument names used here. This greatly improves readability of the HDL. [Note: true dual-port blockRAM separate architecture] logic to the module / architecture, and synthesis will no longer infer a into its own module / architecture. | Primitive of 'trueDualPortBlockRam'. ^ Clock for port A ^ Enable for port A ^ Write enable for port A ^ Address to read from or write to on port A ^ Data in for port A; ignored when /write enable/ is @False@ ^ Clock for port B ^ Enable for port B ^ Write enable for port B ^ Address to read from or write to on port B ^ Data in for port B; ignored when /write enable/ is @False@ will be echoed. If write enable is @False@, the read data is returned. If port enable is @False@, it is /undefined/. | Haskell model for the primitive 'trueDualPortBlockRam#'. to) @domSlow@'s clock. once, followed by the regular cadence of either 'ceil(tA / tB)' or slow clock If port A or port B is writing on (potentially!) the same address, there's a conflict happens here.
| Copyright : ( C ) 2013 - 2016 , University of Twente , 2016 - 2017 , Myrtle Software Ltd , 2017 , Google Inc. , 2021 - 2022 , QBayLogic B.V. , 2022 , Google Inc. , License : BSD2 ( see the file LICENSE ) Maintainer : QBayLogic B.V. < > Block RAM primitives = Using RAMs # usingrams # We will show a rather elaborate example on how you can , and why you might want to use block RAMs . We will build a \"small\ " CPU + Memory + Program ROM where we will slowly evolve to using block RAMs . Note that the code is /not/ meant as a de - facto standard on how to do CPU design in Clash . We start with the definition of the Instructions , Register names and machine codes : @ { \-\ # LANGUAGE RecordWildCards , TupleSections , DeriveAnyClass \#-\ } module CPU where import Clash . Explicit . Prelude type InstrAddr = Unsigned 8 type = Unsigned 5 type Value = Signed 8 data Instruction = Compute Operator | Branch Reg Value | Jump Value | Load | Store Reg MemAddr | Nop deriving ( Eq , Show , Generic , ) data = Zero | PC | RegA | RegB | RegC | RegD | deriving ( Eq , Show , , Generic , ) data Operator = Add | Sub | Incr | Imm | CmpGt deriving ( Eq , Show , Generic , ) data MachCode = MachCode { inputX : : , inputY : : , result : : , aluCode : : Operator , ldReg : : , rdAddr : : , wrAddrM : : Maybe , jmpM : : Maybe Value } nullCode = MachCode { inputX = Zero , inputY = Zero , result = Zero , aluCode = Imm , ldReg = Zero , rdAddr = 0 , wrAddrM = Nothing , jmpM = Nothing } @ Next we define the CPU and its ALU : @ cpu - > ( Vec 7 Value , ( , Maybe ( , Value ) , InstrAddr ) ) cpu regbank ( memOut , instr ) = ( regbank ' , ( rdAddr , ( , aluOut ) ' < $ > ' wrAddrM , bitCoerce ipntr ) ) where ipntr = regbank ' Clash . Sized . Vector . ! ! ' PC ( MachCode { .. } ) = case instr of Compute op rx nullCode { inputX = rx , inputY = ry , result = res , aluCode = op } Branch cr a - > nullCode { inputX = cr , jmpM = Just a } Jump a - > nullCode { aluCode = Incr , jmpM = Just a } Load a r - > nullCode { ldReg = r , } Store r a - > nullCode { inputX = r , wrAddrM = Just a } Nop - > nullCode regX = regbank ' Clash . Sized . Vector . ! ! ' inputX regY = regbank ' Clash . Sized . Vector . ! ! ' inputY aluOut = alu aluCode regX regY nextPC = case jmpM of Just a | aluOut /= 0 - > ipntr + a _ - > ipntr + 1 regbank ' = ' Clash.Sized.Vector.replace ' Zero 0 $ ' Clash.Sized.Vector.replace ' PC nextPC $ ' Clash.Sized.Vector.replace ' result aluOut $ ' Clash.Sized.Vector.replace ' ldReg memOut $ regbank alu Add x y = x + y alu Sub x y = x - y alu _ = x + 1 alu Imm x _ = x alu CmpGt x y = if x > y then 1 else 0 @ We initially create a memory out of simple registers : @ dataMem : : KnownDomain dom = > Clock dom - > Reset dom - > Enable dom - > Signal dom ( Maybe ( , Value ) ) - > Signal dom Value dataMem clk rst en rd wrM = ' Clash.Explicit.Mealy.mealy ' clk rst en dataMemT ( ' Clash.Sized.Vector.replicate ' d32 0 ) ( bundle ( rd , wrM ) ) where dataMemT mem ( rd , wrM ) = ( mem',dout ) where dout = mem ' Clash . Sized . Vector . ! ! ' rd mem ' = case wrM of Just ( wr , din ) - > ' Clash.Sized.Vector.replace ' - > mem @ And then connect everything : @ system : : ( KnownDomain dom , KnownNat n ) = > n Instruction - > Clock dom - > Reset dom - > Enable dom - > Signal dom Value system instrs clk rst en = memOut where memOut = dataMem clk rst en ( rdAddr , dout , ipntr ) = ' Clash . Explicit . Mealy.mealyB ' clk rst en cpu ( ' Clash.Sized.Vector.replicate ' d7 0 ) ( memOut , instr ) instr = ' Clash . Explicit . Prelude.asyncRom ' instrs ' < $ > ' ipntr @ Create a simple program that calculates the GCD of 4 and 6 : @ Compute Incr Zero RegA RegA :> replicate d3 ( Compute Incr RegA Zero RegA ) + + Store RegA 0 :> Compute Incr Zero RegA RegA :> replicate d5 ( Compute Incr RegA Zero RegA ) + + Store RegA 1 :> Load 0 RegA :> Load 1 RegB :> Compute CmpGt RegA RegB RegC :> Branch RegC 4 :> Compute CmpGt RegB RegA RegC :> Branch RegC 4 :> Jump 5 :> Compute Sub RegA RegB RegA :> Jump ( -6 ) :> Compute Sub RegB RegA RegB :> Jump (-8 ) :> Store RegA 2 :> Load 2 RegC :> Nil @ And test our system : @ > > > sampleN 32 $ system prog systemClockGen resetGen enableGen [ 0,0,0,0,0,0,4,4,4,4,4,4,4,4,6,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2 ] @ to see that our system indeed calculates that the GCD of 6 and 4 is 2 . = = = Improvement 1 : using @asyncRam@ As you can see , it 's fairly straightforward to build a memory using registers and read ( ' Clash . Sized . Vector . ! ! ' ) and write ( ' Clash.Sized.Vector.replace ' ) logic . This might however not result in the most efficient hardware structure , especially when building an ASIC . Instead it is preferable to use the ' Clash . Prelude . RAM.asyncRam ' function which has the potential to be translated to a more efficient structure : @ : : ( KnownDomain dom , KnownNat n ) = > n Instruction - > Clock dom - > Reset dom - > Enable dom - > Signal dom Value rst en = memOut where memOut = ' Clash . Explicit . RAM.asyncRam ' clk clk en d32 ( rdAddr , dout , ipntr ) = ' Clash . Explicit . Prelude.mealyB ' clk rst en cpu ( ' Clash.Sized.Vector.replicate ' d7 0 ) ( memOut , instr ) instr = ' Clash . Prelude . ROM.asyncRom ' instrs ' < $ > ' ipntr @ Again , we can simulate our system and see that it works . This time however , we need to disregard the first few output samples , because the initial content of an ' Clash . Prelude . RAM.asyncRam ' is /undefined/ , and consequently , the first few output samples are also /undefined/. We use the utility function ' Clash . XException.printX ' to conveniently filter out the undefinedness and replace it with the string @\"undefined\"@ in the first few leading outputs . @ > > > printX $ sampleN 32 $ system2 prog systemClockGen resetGen enableGen [ undefined , undefined , undefined , undefined , undefined , = = Improvement 2 : using @blockRam@ Finally we get to using ' blockRam ' . On FPGAs , ' Clash . Prelude . RAM.asyncRam ' will be implemented in terms of LUTs , and therefore take up logic resources . FPGAs also have large(r ) memory structures called /block RAMs/ , which are preferred , especially as the memories we need for our application get bigger . The ' blockRam ' function will be translated to such a /block RAM/. One important aspect of block RAMs is that they have a /synchronous/ read port , meaning unlike an ' Clash . Prelude . RAM.asyncRam ' , the result of a read command given at time @t@ is output at time @t + 1@. For us that means we need to change the design of our CPU . Right now , upon a load instruction we generate a read address for the memory , and the value at that read address is immediately available to be put in the register bank . We will be using a block RAM , so the value is delayed until the next cycle . Thus , we will also need to delay the register address to which the memory address is loaded : @ cpu2 - > ( ( Vec 7 Value , ) , ( , Maybe ( , Value ) , InstrAddr ) ) cpu2 ( regbank , ldRegD ) ( memOut , instr ) = ( ( regbank ' , ldRegD ' ) , ( rdAddr , ( , aluOut ) ' < $ > ' wrAddrM , bitCoerce ipntr ) ) where ipntr = regbank ' Clash . Sized . Vector . ! ! ' PC ( MachCode { .. } ) = case instr of Compute op rx nullCode { inputX = rx , inputY = ry , result = res , aluCode = op } Branch cr a - > nullCode { inputX = cr , jmpM = Just a } Jump a - > nullCode { aluCode = Incr , jmpM = Just a } Load a r - > nullCode { ldReg = r , } Store r a - > nullCode { inputX = r , wrAddrM = Just a } Nop - > nullCode regX = regbank ' Clash . Sized . Vector . ! ! ' inputX regY = regbank ' Clash . Sized . Vector . ! ! ' inputY aluOut = alu aluCode regX regY nextPC = case jmpM of Just a | aluOut /= 0 - > ipntr + a _ - > ipntr + 1 regbank ' = ' Clash.Sized.Vector.replace ' Zero 0 $ ' Clash.Sized.Vector.replace ' PC nextPC $ ' Clash.Sized.Vector.replace ' result aluOut $ ' Clash.Sized.Vector.replace ' ldRegD memOut $ regbank @ We can now finally instantiate our system with a ' blockRam ' : @ : : ( KnownDomain dom , KnownNat n ) = > n Instruction - > Clock dom - > Reset dom - > Enable dom - > Signal dom Value clk rst en = memOut where memOut = ' blockRam ' clk en ( replicate d32 0 ) ( rdAddr , dout , ipntr ) = ' Clash . Explicit . Prelude.mealyB ' clk rst en cpu2 ( ( ' Clash.Sized.Vector.replicate ' d7 0),Zero ) ( memOut , instr ) instr = ' Clash . Explicit . Prelude.asyncRom ' instrs ' < $ > ' ipntr @ We are , however , not done . We will also need to update our program . The reason being that values that we try to load in our registers wo n't be loaded into the register until the next cycle . This is a problem when the next instruction immediately depends on this memory value . In our example , this was only the case when we loaded the value , which was stored at address @1@ , into @RegB@. Our updated program is thus : @ Compute Incr Zero RegA RegA :> replicate d3 ( Compute Incr RegA Zero RegA ) + + Store RegA 0 :> Compute Incr Zero RegA RegA :> replicate d5 ( Compute Incr RegA Zero RegA ) + + Store RegA 1 :> Load 0 RegA :> Load 1 RegB :> Compute CmpGt RegA RegB RegC :> Branch RegC 4 :> Compute CmpGt RegB RegA RegC :> Branch RegC 4 :> Jump 5 :> Compute Sub RegA RegB RegA :> Jump ( -6 ) :> Compute Sub RegB RegA RegB :> Jump (-8 ) :> Store RegA 2 :> Load 2 RegC :> Nil @ When we simulate our system we see that it works . This time again , we need to disregard the first sample , because the initial output of a ' blockRam ' is /undefined/. We use the utility function ' Clash . XException.printX ' to conveniently filter out the undefinedness and replace it with the string @\"undefined\"@. @ > > > printX $ sampleN 34 $ [ undefined,0,0,0,0,0,0,4,4,4,4,4,4,4,4,6,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2 ] @ This concludes the short introduction to using ' blockRam ' . Copyright : (C) 2013-2016, University of Twente, 2016-2017, Myrtle Software Ltd, 2017 , Google Inc., 2021-2022, QBayLogic B.V., 2022 , Google Inc., License : BSD2 (see the file LICENSE) Maintainer : QBayLogic B.V. <> Block RAM primitives = Using RAMs #usingrams# We will show a rather elaborate example on how you can, and why you might want to use block RAMs. We will build a \"small\" CPU + Memory + Program ROM where we will slowly evolve to using block RAMs. Note that the code is /not/ meant as a de-facto standard on how to do CPU design in Clash. We start with the definition of the Instructions, Register names and machine codes: @ {\-\# LANGUAGE RecordWildCards, TupleSections, DeriveAnyClass \#-\} module CPU where import Clash.Explicit.Prelude type InstrAddr = Unsigned 8 type MemAddr = Unsigned 5 type Value = Signed 8 data Instruction = Compute Operator Reg Reg Reg | Branch Reg Value | Jump Value | Load MemAddr Reg | Store Reg MemAddr | Nop deriving (Eq, Show, Generic, NFDataX) data Reg = Zero | PC | RegA | RegB | RegC | RegD | RegE deriving (Eq, Show, Enum, Generic, NFDataX) data Operator = Add | Sub | Incr | Imm | CmpGt deriving (Eq, Show, Generic, NFDataX) data MachCode = MachCode { inputX :: Reg , inputY :: Reg , result :: Reg , aluCode :: Operator , ldReg :: Reg , rdAddr :: MemAddr , wrAddrM :: Maybe MemAddr , jmpM :: Maybe Value } nullCode = MachCode { inputX = Zero , inputY = Zero , result = Zero , aluCode = Imm , ldReg = Zero , rdAddr = 0 , wrAddrM = Nothing , jmpM = Nothing } @ Next we define the CPU and its ALU: @ cpu -> ( Vec 7 Value , (MemAddr, Maybe (MemAddr,Value), InstrAddr) ) cpu regbank (memOut, instr) = (regbank', (rdAddr, (,aluOut) '<$>' wrAddrM, bitCoerce ipntr)) where ipntr = regbank 'Clash.Sized.Vector.!!' PC (MachCode {..}) = case instr of Compute op rx ry res -> nullCode {inputX=rx,inputY=ry,result=res,aluCode=op} Branch cr a -> nullCode {inputX=cr,jmpM=Just a} Jump a -> nullCode {aluCode=Incr,jmpM=Just a} Load a r -> nullCode {ldReg=r,rdAddr=a} Store r a -> nullCode {inputX=r,wrAddrM=Just a} Nop -> nullCode regX = regbank 'Clash.Sized.Vector.!!' inputX regY = regbank 'Clash.Sized.Vector.!!' inputY aluOut = alu aluCode regX regY nextPC = case jmpM of Just a | aluOut /= 0 -> ipntr + a _ -> ipntr + 1 regbank' = 'Clash.Sized.Vector.replace' Zero 0 $ 'Clash.Sized.Vector.replace' PC nextPC $ 'Clash.Sized.Vector.replace' result aluOut $ 'Clash.Sized.Vector.replace' ldReg memOut $ regbank alu Add x y = x + y alu Sub x y = x - y alu Incr x _ = x + 1 alu Imm x _ = x alu CmpGt x y = if x > y then 1 else 0 @ We initially create a memory out of simple registers: @ dataMem :: KnownDomain dom => Clock dom -> Reset dom -> Enable dom -> Signal dom MemAddr -> Signal dom (Maybe (MemAddr,Value)) -> Signal dom Value dataMem clk rst en rd wrM = 'Clash.Explicit.Mealy.mealy' clk rst en dataMemT ('Clash.Sized.Vector.replicate' d32 0) (bundle (rd,wrM)) where dataMemT mem (rd,wrM) = (mem',dout) where dout = mem 'Clash.Sized.Vector.!!' rd mem' = case wrM of Just (wr,din) -> 'Clash.Sized.Vector.replace' wr din mem _ -> mem @ And then connect everything: @ system :: ( KnownDomain dom , KnownNat n ) => Vec n Instruction -> Clock dom -> Reset dom -> Enable dom -> Signal dom Value system instrs clk rst en = memOut where memOut = dataMem clk rst en rdAddr dout (rdAddr,dout,ipntr) = 'Clash.Explicit.Mealy.mealyB' clk rst en cpu ('Clash.Sized.Vector.replicate' d7 0) (memOut,instr) instr = 'Clash.Explicit.Prelude.asyncRom' instrs '<$>' ipntr @ Create a simple program that calculates the GCD of 4 and 6: @ Compute Incr Zero RegA RegA :> replicate d3 (Compute Incr RegA Zero RegA) ++ Store RegA 0 :> Compute Incr Zero RegA RegA :> replicate d5 (Compute Incr RegA Zero RegA) ++ Store RegA 1 :> Load 0 RegA :> Load 1 RegB :> Compute CmpGt RegA RegB RegC :> Branch RegC 4 :> Compute CmpGt RegB RegA RegC :> Branch RegC 4 :> Jump 5 :> Compute Sub RegA RegB RegA :> Jump (-6) :> Compute Sub RegB RegA RegB :> Jump (-8) :> Store RegA 2 :> Load 2 RegC :> Nil @ And test our system: @ >>> sampleN 32 $ system prog systemClockGen resetGen enableGen [0,0,0,0,0,0,4,4,4,4,4,4,4,4,6,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2] @ to see that our system indeed calculates that the GCD of 6 and 4 is 2. === Improvement 1: using @asyncRam@ As you can see, it's fairly straightforward to build a memory using registers and read ('Clash.Sized.Vector.!!') and write ('Clash.Sized.Vector.replace') logic. This might however not result in the most efficient hardware structure, especially when building an ASIC. Instead it is preferable to use the 'Clash.Prelude.RAM.asyncRam' function which has the potential to be translated to a more efficient structure: @ system2 :: ( KnownDomain dom , KnownNat n ) => Vec n Instruction -> Clock dom -> Reset dom -> Enable dom -> Signal dom Value system2 instrs clk rst en = memOut where memOut = 'Clash.Explicit.RAM.asyncRam' clk clk en d32 rdAddr dout (rdAddr,dout,ipntr) = 'Clash.Explicit.Prelude.mealyB' clk rst en cpu ('Clash.Sized.Vector.replicate' d7 0) (memOut,instr) instr = 'Clash.Prelude.ROM.asyncRom' instrs '<$>' ipntr @ Again, we can simulate our system and see that it works. This time however, we need to disregard the first few output samples, because the initial content of an 'Clash.Prelude.RAM.asyncRam' is /undefined/, and consequently, the first few output samples are also /undefined/. We use the utility function 'Clash.XException.printX' to conveniently filter out the undefinedness and replace it with the string @\"undefined\"@ in the first few leading outputs. @ >>> printX $ sampleN 32 $ system2 prog systemClockGen resetGen enableGen [undefined,undefined,undefined,undefined,undefined,undefined,4,4,4,4,4,4,4,4,6,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2] @ === Improvement 2: using @blockRam@ Finally we get to using 'blockRam'. On FPGAs, 'Clash.Prelude.RAM.asyncRam' will be implemented in terms of LUTs, and therefore take up logic resources. FPGAs also have large(r) memory structures called /block RAMs/, which are preferred, especially as the memories we need for our application get bigger. The 'blockRam' function will be translated to such a /block RAM/. One important aspect of block RAMs is that they have a /synchronous/ read port, meaning unlike an 'Clash.Prelude.RAM.asyncRam', the result of a read command given at time @t@ is output at time @t + 1@. For us that means we need to change the design of our CPU. Right now, upon a load instruction we generate a read address for the memory, and the value at that read address is immediately available to be put in the register bank. We will be using a block RAM, so the value is delayed until the next cycle. Thus, we will also need to delay the register address to which the memory address is loaded: @ cpu2 -> ( (Vec 7 Value, Reg) , (MemAddr, Maybe (MemAddr,Value), InstrAddr) ) cpu2 (regbank, ldRegD) (memOut, instr) = ((regbank', ldRegD'), (rdAddr, (,aluOut) '<$>' wrAddrM, bitCoerce ipntr)) where ipntr = regbank 'Clash.Sized.Vector.!!' PC (MachCode {..}) = case instr of Compute op rx ry res -> nullCode {inputX=rx,inputY=ry,result=res,aluCode=op} Branch cr a -> nullCode {inputX=cr,jmpM=Just a} Jump a -> nullCode {aluCode=Incr,jmpM=Just a} Load a r -> nullCode {ldReg=r,rdAddr=a} Store r a -> nullCode {inputX=r,wrAddrM=Just a} Nop -> nullCode regX = regbank 'Clash.Sized.Vector.!!' inputX regY = regbank 'Clash.Sized.Vector.!!' inputY aluOut = alu aluCode regX regY nextPC = case jmpM of Just a | aluOut /= 0 -> ipntr + a _ -> ipntr + 1 regbank' = 'Clash.Sized.Vector.replace' Zero 0 $ 'Clash.Sized.Vector.replace' PC nextPC $ 'Clash.Sized.Vector.replace' result aluOut $ 'Clash.Sized.Vector.replace' ldRegD memOut $ regbank @ We can now finally instantiate our system with a 'blockRam': @ system3 :: ( KnownDomain dom , KnownNat n ) => Vec n Instruction -> Clock dom -> Reset dom -> Enable dom -> Signal dom Value system3 instrs clk rst en = memOut where memOut = 'blockRam' clk en (replicate d32 0) rdAddr dout (rdAddr,dout,ipntr) = 'Clash.Explicit.Prelude.mealyB' clk rst en cpu2 (('Clash.Sized.Vector.replicate' d7 0),Zero) (memOut,instr) instr = 'Clash.Explicit.Prelude.asyncRom' instrs '<$>' ipntr @ We are, however, not done. We will also need to update our program. The reason being that values that we try to load in our registers won't be loaded into the register until the next cycle. This is a problem when the next instruction immediately depends on this memory value. In our example, this was only the case when we loaded the value @6@, which was stored at address @1@, into @RegB@. Our updated program is thus: @ Compute Incr Zero RegA RegA :> replicate d3 (Compute Incr RegA Zero RegA) ++ Store RegA 0 :> Compute Incr Zero RegA RegA :> replicate d5 (Compute Incr RegA Zero RegA) ++ Store RegA 1 :> Load 0 RegA :> Load 1 RegB :> Compute CmpGt RegA RegB RegC :> Branch RegC 4 :> Compute CmpGt RegB RegA RegC :> Branch RegC 4 :> Jump 5 :> Compute Sub RegA RegB RegA :> Jump (-6) :> Compute Sub RegB RegA RegB :> Jump (-8) :> Store RegA 2 :> Load 2 RegC :> Nil @ When we simulate our system we see that it works. This time again, we need to disregard the first sample, because the initial output of a 'blockRam' is /undefined/. We use the utility function 'Clash.XException.printX' to conveniently filter out the undefinedness and replace it with the string @\"undefined\"@. @ >>> printX $ sampleN 34 $ system3 prog2 systemClockGen resetGen enableGen [undefined,0,0,0,0,0,0,4,4,4,4,4,4,4,4,6,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2] @ This concludes the short introduction to using 'blockRam'. -} # LANGUAGE NoImplicitPrelude # # LANGUAGE Trustworthy # # OPTIONS_GHC -fplugin GHC.TypeLits . KnownNat . Solver # # OPTIONS_GHC -fno - do - lambda - eta - expansion # # OPTIONS_GHC -fno - cpr - anal # module Clash.Explicit.BlockRam blockRam , blockRamPow2 , blockRamU , blockRam1 , ResetStrategy(..) , readNew * True dual - port block RAM $ tdpbram , trueDualPortBlockRam , RamOp(..) , blockRam# , blockRamU# , blockRam1# , trueDualPortBlockRam# ) where import Clash.HaskellPrelude import Control.Exception (catch, throw) import Control.Monad (forM_) import Control.Monad.ST (ST, runST) import Control.Monad.ST.Unsafe (unsafeInterleaveST, unsafeIOToST, unsafeSTToIO) import Data.Array.MArray (newListArray) import qualified Data.List as L import Data.Maybe (isJust, fromMaybe) import GHC.Arr (STArray, unsafeReadSTArray, unsafeWriteSTArray) import qualified Data.Sequence as Seq import Data.Sequence (Seq) import Data.Tuple (swap) import GHC.Generics (Generic) import GHC.Stack (HasCallStack, withFrozenCallStack) import GHC.TypeLits (KnownNat, type (^), type (<=)) import Unsafe.Coerce (unsafeCoerce) import Clash.Annotations.Primitive (hasBlackBox) import Clash.Class.Num (SaturationMode(SatBound), satSucc) import Clash.Explicit.Signal (KnownDomain, Enable, register, fromEnable) import Clash.Signal.Internal (Clock(..), Reset, Signal (..), ClockAB (..), invertReset, (.&&.), mux, clockTicks) import Clash.Promoted.Nat (SNat(..), snatToNum, natToNum) import Clash.Signal.Bundle (unbundle, bundle) import Clash.Signal.Internal.Ambiguous (clockPeriod) import Clash.Sized.Unsigned (Unsigned) import Clash.Sized.Index (Index) import Clash.Sized.Vector (Vec, replicate, iterateI) import qualified Clash.Sized.Vector as CV import Clash.XException (maybeIsX, NFDataX(deepErrorX), defaultSeqX, fromJustX, undefined, XException (..), seqX, isX, errorX) $ tdpbram A true dual - port block RAM has two fully independent , fully functional access ports : port A and port B. Either port can do both RAM reads and writes . These two ports can even be on distinct clock domains , but the memory itself is shared between the ports . This also makes a true dual - port block RAM suitable as a component in a domain crossing circuit ( but it needs additional logic for it to be safe , see e.g. ' Clash . Explicit . Synchronizer.asyncFIFOSynchronizer ' ) . A version with implicit clocks can be found in " Clash . Prelude . BlockRam " . A true dual-port block RAM has two fully independent, fully functional access ports: port A and port B. Either port can do both RAM reads and writes. These two ports can even be on distinct clock domains, but the memory itself is shared between the ports. This also makes a true dual-port block RAM suitable as a component in a domain crossing circuit (but it needs additional logic for it to be safe, see e.g. 'Clash.Explicit.Synchronizer.asyncFIFOSynchronizer'). A version with implicit clocks can be found in "Clash.Prelude.BlockRam". -} import ( listArray , unsafeThawSTArray ) $ setup > > > import Clash . Explicit . Prelude as C > > > import qualified Data . List as L > > > : set -XDataKinds -XRecordWildCards -XTupleSections -XDeriveAnyClass -XDeriveGeneric > > > type InstrAddr = Unsigned 8 > > > type = Unsigned 5 > > > type Value = Signed 8 > > > : { data = Zero | PC | RegA | RegB | RegC | RegD | deriving ( Eq , Show , , C.Generic , ) :} > > > : { data Operator = Add | Sub | Incr | Imm | CmpGt deriving ( Eq , Show , Generic , ) :} > > > : { data Instruction = Compute Operator | Branch Reg Value | Jump Value | Load | Store Reg MemAddr | Nop deriving ( Eq , Show , Generic , ) :} > > > : { data MachCode = MachCode { inputX : : , inputY : : , result : : , aluCode : : Operator , ldReg : : , rdAddr : : , wrAddrM : : Maybe , jmpM : : Maybe Value } :} > > > : { nullCode = MachCode { inputX = Zero , inputY = Zero , result = Zero , aluCode = , ldReg = Zero , rdAddr = 0 , wrAddrM = Nothing , jmpM = Nothing } :} > > > : { alu Add x y = x + y alu Sub x y = x - y alu _ = x + 1 alu Imm x _ = x alu CmpGt x y = if x > y then 1 else 0 :} > > > : { - > ( Vec 7 Value , ( , Maybe ( , Value),InstrAddr ) ) cpu regbank ( memOut , instr ) = ( regbank',(rdAddr,(,aluOut ) < $ > wrAddrM , bitCoerce ipntr ) ) where ipntr = regbank C. ! ! PC ( MachCode { .. } ) = case instr of Compute op rx ry res - > nullCode { inputX = rx , inputY = ry , result = res , aluCode = op } Branch cr a - > nullCode { inputX = cr , jmpM = Just a } Jump a - > nullCode { aluCode = Incr , jmpM = Just a } Load a r - > nullCode { ldReg = r , } Store r a - > nullCode { inputX = r , wrAddrM = Just a } nullCode regX = regbank C. ! ! inputX regY = regbank C. ! ! inputY aluOut = alu aluCode regX regY nextPC = case jmpM of Just a | aluOut /= 0 - > ipntr + a _ - > ipntr + 1 regbank ' = replace Zero 0 $ replace PC nextPC $ replace result aluOut $ replace ldReg memOut $ regbank :} > > > : { let dataMem : : = > Clock dom - > Reset dom - > Enable dom - > Signal dom > Signal dom ( Maybe ( , Value ) ) - > Signal dom Value dataMem clk rst en rd wrM = mealy clk rst en dataMemT ( C.replicate d32 0 ) ( bundle ( rd , wrM ) ) where dataMemT mem ( rd , wrM ) = ( mem',dout ) where dout = mem C. ! ! = case wrM of Just ( wr , din ) - > replace Nothing - > mem :} > > > : { let system : : ( KnownDomain dom , KnownNat n ) = > - > Clock dom - > Reset dom - > Enable dom - > Signal dom Value system instrs clk rst en = memOut where memOut = dataMem clk rst en ( rdAddr , dout , ipntr ) = mealyB clk rst en cpu ( C.replicate d7 0 ) ( memOut , instr ) instr = asyncRom instrs < $ > ipntr :} > > > : { Compute Incr Zero RegA RegA :> C.replicate d3 ( Compute Incr RegA Zero RegA ) C.++ Store RegA 0 :> Compute Incr Zero RegA RegA :> C.replicate d5 ( Compute Incr RegA Zero RegA ) C.++ Store RegA 1 :> Load 0 RegA :> Load 1 RegB :> Compute CmpGt RegA RegB RegC :> Branch RegC 4 :> Compute CmpGt RegB RegA RegC :> Branch RegC 4 :> Jump 5 :> Compute Sub RegA RegB RegA :> Jump ( -6 ) :> Compute Sub RegB RegA RegB :> Jump (-8 ) :> Store RegA 2 :> Load 2 RegC :> Nil :} > > > : { let : : ( KnownDomain dom , KnownNat n ) = > - > Clock dom - > Reset dom - > Enable dom - > Signal dom Value rst en = memOut where memOut = asyncRam clk clk en ( rdAddr , dout , ipntr ) = mealyB clk rst en cpu ( C.replicate d7 0 ) ( memOut , instr ) instr = asyncRom instrs < $ > ipntr :} > > > : { - > ( ( Vec 7 Value , ) , ( , Maybe ( , Value),InstrAddr ) ) cpu2 ( regbank , ldRegD ) ( memOut , instr ) = ( ( regbank',ldRegD'),(rdAddr,(,aluOut ) < $ > wrAddrM , bitCoerce ipntr ) ) where ipntr = regbank C. ! ! PC ( MachCode { .. } ) = case instr of Compute op rx ry res - > nullCode { inputX = rx , inputY = ry , result = res , aluCode = op } Branch cr a - > nullCode { inputX = cr , jmpM = Just a } Jump a - > nullCode { aluCode = Incr , jmpM = Just a } Load a r - > nullCode { ldReg = r , } Store r a - > nullCode { inputX = r , wrAddrM = Just a } nullCode regX = regbank C. ! ! inputX regY = regbank C. ! ! inputY aluOut = alu aluCode regX regY nextPC = case jmpM of Just a | aluOut /= 0 - > ipntr + a _ - > ipntr + 1 regbank ' = replace Zero 0 $ replace PC nextPC $ replace result aluOut $ replace ldRegD memOut $ regbank :} > > > : { let : : ( KnownDomain dom , KnownNat n ) = > - > Clock dom - > Reset dom - > Enable dom - > Signal dom Value rst en = memOut where memOut = blockRam clk en ( C.replicate d32 0 ) ( rdAddr , dout , ipntr ) = mealyB clk rst en cpu2 ( ( C.replicate d7 0),Zero ) ( memOut , instr ) instr = asyncRom instrs < $ > ipntr :} > > > : { Compute Incr Zero RegA RegA :> C.replicate d3 ( Compute Incr RegA Zero RegA ) C.++ Store RegA 0 :> Compute Incr Zero RegA RegA :> C.replicate d5 ( Compute Incr RegA Zero RegA ) C.++ Store RegA 1 :> Load 0 RegA :> Load 1 RegB :> Compute CmpGt RegA RegB RegC :> Branch RegC 4 :> Compute CmpGt RegB RegA RegC :> Branch RegC 4 :> Jump 5 :> Compute Sub RegA RegB RegA :> Jump ( -6 ) :> Compute Sub RegB RegA RegB :> Jump (-8 ) :> Store RegA 2 :> Load 2 RegC :> Nil :} >>> import Clash.Explicit.Prelude as C >>> import qualified Data.List as L >>> :set -XDataKinds -XRecordWildCards -XTupleSections -XDeriveAnyClass -XDeriveGeneric >>> type InstrAddr = Unsigned 8 >>> type MemAddr = Unsigned 5 >>> type Value = Signed 8 >>> :{ data Reg = Zero | PC | RegA | RegB | RegC | RegD | RegE deriving (Eq,Show,Enum,C.Generic,NFDataX) :} >>> :{ data Operator = Add | Sub | Incr | Imm | CmpGt deriving (Eq, Show, Generic, NFDataX) :} >>> :{ data Instruction = Compute Operator Reg Reg Reg | Branch Reg Value | Jump Value | Load MemAddr Reg | Store Reg MemAddr | Nop deriving (Eq, Show, Generic, NFDataX) :} >>> :{ data MachCode = MachCode { inputX :: Reg , inputY :: Reg , result :: Reg , aluCode :: Operator , ldReg :: Reg , rdAddr :: MemAddr , wrAddrM :: Maybe MemAddr , jmpM :: Maybe Value } :} >>> :{ nullCode = MachCode { inputX = Zero, inputY = Zero, result = Zero, aluCode = Imm , ldReg = Zero, rdAddr = 0, wrAddrM = Nothing , jmpM = Nothing } :} >>> :{ alu Add x y = x + y alu Sub x y = x - y alu Incr x _ = x + 1 alu Imm x _ = x alu CmpGt x y = if x > y then 1 else 0 :} >>> :{ -> ( Vec 7 Value , (MemAddr,Maybe (MemAddr,Value),InstrAddr) ) cpu regbank (memOut,instr) = (regbank',(rdAddr,(,aluOut) <$> wrAddrM,bitCoerce ipntr)) where ipntr = regbank C.!! PC (MachCode {..}) = case instr of Compute op rx ry res -> nullCode {inputX=rx,inputY=ry,result=res,aluCode=op} Branch cr a -> nullCode {inputX=cr,jmpM=Just a} Jump a -> nullCode {aluCode=Incr,jmpM=Just a} Load a r -> nullCode {ldReg=r,rdAddr=a} Store r a -> nullCode {inputX=r,wrAddrM=Just a} Nop -> nullCode regX = regbank C.!! inputX regY = regbank C.!! inputY aluOut = alu aluCode regX regY nextPC = case jmpM of Just a | aluOut /= 0 -> ipntr + a _ -> ipntr + 1 regbank' = replace Zero 0 $ replace PC nextPC $ replace result aluOut $ replace ldReg memOut $ regbank :} >>> :{ let dataMem :: KnownDomain dom => Clock dom -> Reset dom -> Enable dom -> Signal dom MemAddr -> Signal dom (Maybe (MemAddr,Value)) -> Signal dom Value dataMem clk rst en rd wrM = mealy clk rst en dataMemT (C.replicate d32 0) (bundle (rd,wrM)) where dataMemT mem (rd,wrM) = (mem',dout) where dout = mem C.!! rd mem' = case wrM of Just (wr,din) -> replace wr din mem Nothing -> mem :} >>> :{ let system :: ( KnownDomain dom , KnownNat n ) => Vec n Instruction -> Clock dom -> Reset dom -> Enable dom -> Signal dom Value system instrs clk rst en = memOut where memOut = dataMem clk rst en rdAddr dout (rdAddr,dout,ipntr) = mealyB clk rst en cpu (C.replicate d7 0) (memOut,instr) instr = asyncRom instrs <$> ipntr :} >>> :{ Compute Incr Zero RegA RegA :> C.replicate d3 (Compute Incr RegA Zero RegA) C.++ Store RegA 0 :> Compute Incr Zero RegA RegA :> C.replicate d5 (Compute Incr RegA Zero RegA) C.++ Store RegA 1 :> Load 0 RegA :> Load 1 RegB :> Compute CmpGt RegA RegB RegC :> Branch RegC 4 :> Compute CmpGt RegB RegA RegC :> Branch RegC 4 :> Jump 5 :> Compute Sub RegA RegB RegA :> Jump (-6) :> Compute Sub RegB RegA RegB :> Jump (-8) :> Store RegA 2 :> Load 2 RegC :> Nil :} >>> :{ let system2 :: ( KnownDomain dom , KnownNat n ) => Vec n Instruction -> Clock dom -> Reset dom -> Enable dom -> Signal dom Value system2 instrs clk rst en = memOut where memOut = asyncRam clk clk en d32 rdAddr dout (rdAddr,dout,ipntr) = mealyB clk rst en cpu (C.replicate d7 0) (memOut,instr) instr = asyncRom instrs <$> ipntr :} >>> :{ -> ( (Vec 7 Value,Reg) , (MemAddr,Maybe (MemAddr,Value),InstrAddr) ) cpu2 (regbank,ldRegD) (memOut,instr) = ((regbank',ldRegD'),(rdAddr,(,aluOut) <$> wrAddrM,bitCoerce ipntr)) where ipntr = regbank C.!! PC (MachCode {..}) = case instr of Compute op rx ry res -> nullCode {inputX=rx,inputY=ry,result=res,aluCode=op} Branch cr a -> nullCode {inputX=cr,jmpM=Just a} Jump a -> nullCode {aluCode=Incr,jmpM=Just a} Load a r -> nullCode {ldReg=r,rdAddr=a} Store r a -> nullCode {inputX=r,wrAddrM=Just a} Nop -> nullCode regX = regbank C.!! inputX regY = regbank C.!! inputY aluOut = alu aluCode regX regY nextPC = case jmpM of Just a | aluOut /= 0 -> ipntr + a _ -> ipntr + 1 regbank' = replace Zero 0 $ replace PC nextPC $ replace result aluOut $ replace ldRegD memOut $ regbank :} >>> :{ let system3 :: ( KnownDomain dom , KnownNat n ) => Vec n Instruction -> Clock dom -> Reset dom -> Enable dom -> Signal dom Value system3 instrs clk rst en = memOut where memOut = blockRam clk en (C.replicate d32 0) rdAddr dout (rdAddr,dout,ipntr) = mealyB clk rst en cpu2 ((C.replicate d7 0),Zero) (memOut,instr) instr = asyncRom instrs <$> ipntr :} >>> :{ Compute Incr Zero RegA RegA :> C.replicate d3 (Compute Incr RegA Zero RegA) C.++ Store RegA 0 :> Compute Incr Zero RegA RegA :> C.replicate d5 (Compute Incr RegA Zero RegA) C.++ Store RegA 1 :> Load 0 RegA :> Load 1 RegB :> Compute CmpGt RegA RegB RegC :> Branch RegC 4 :> Compute CmpGt RegB RegA RegC :> Branch RegC 4 :> Jump 5 :> Compute Sub RegA RegB RegA :> Jump (-6) :> Compute Sub RegB RegA RegB :> Jump (-8) :> Store RegA 2 :> Load 2 RegC :> Nil :} -} | Create a block RAM with space for @n@ elements * _ _ NB _ _ : Read value is delayed by 1 cycle block RAM . * A large ' ' for the initial content may be too inefficient , depending on how it is constructed . See ' Clash . Explicit . BlockRam . File.blockRamFile ' and ' Clash . Explicit . BlockRam . ' for different approaches that bram40 - > ' Signal ' dom ( ' Unsigned ' 6 ) bram40 clk en = ' blockRam ' clk en ( ' Clash.Sized.Vector.replicate ' d40 1 ) blockRam :: ( KnownDomain dom , HasCallStack , NFDataX a , Enum addr , NFDataX addr ) => Clock dom -> Enable dom -> Vec n a ^ Initial content of the , also determines the size , @n@ , of the -> Signal dom addr -> Signal dom (Maybe (addr, a)) -> Signal dom a ^ Value of the at address @r@ from the previous clock cycle blockRam = \clk gen content rd wrM -> let en = isJust <$> wrM (wr,din) = unbundle (fromJustX <$> wrM) in withFrozenCallStack (blockRam# clk gen content (fromEnum <$> rd) en (fromEnum <$> wr) din) # INLINE blockRam # | Create a block RAM with space for 2^@n@ elements * _ _ NB _ _ : Read value is delayed by 1 cycle block RAM . * A large ' ' for the initial content may be too inefficient , depending on how it is constructed . See ' Clash . Explicit . BlockRam . File.blockRamFilePow2 ' and ' Clash . Explicit . BlockRam . Blob.blockRamBlobPow2 ' for different approaches - > ' Signal ' dom ( ' Unsigned ' 5 ) bram32 clk en = ' blockRamPow2 ' clk en ( ' Clash.Sized.Vector.replicate ' d32 1 ) blockRamPow2 :: ( KnownDomain dom , HasCallStack , NFDataX a , KnownNat n ) => Clock dom -> Enable dom -> Vec (2^n) a ^ Initial content of the -> Signal dom (Unsigned n) -> Signal dom (Maybe (Unsigned n, a)) -> Signal dom a ^ Value of the at address @r@ from the previous clock cycle blockRamPow2 = \clk en cnt rd wrM -> withFrozenCallStack (blockRam clk en cnt rd wrM) # INLINE blockRamPow2 # data ResetStrategy (r :: Bool) where ClearOnReset :: ResetStrategy 'True NoClearOnReset :: ResetStrategy 'False | A version of ' blockRam ' that has no default values set . May be cleared to blockRamU :: forall n dom a r addr . ( KnownDomain dom , HasCallStack , NFDataX a , Enum addr , NFDataX addr , 1 <= n ) => Clock dom -> Reset dom for the to be reset to its initial state . -> Enable dom -> ResetStrategy r ^ Whether to clear on asserted reset ( ' ClearOnReset ' ) or cycles to clear the . -> SNat n ^ Number of elements in -> (Index n -> a) ^ If applicable ( see ' ResetStrategy ' argument ) , reset using this function -> Signal dom addr -> Signal dom (Maybe (addr, a)) -> Signal dom a ^ Value of the at address @r@ from the previous clock cycle blockRamU clk rst0 en rstStrategy n@SNat initF rd0 mw0 = case rstStrategy of ClearOnReset -> blockRamU# clk en n rd1 we1 wa1 w1 NoClearOnReset -> blockRamU# clk en n (fromEnum <$> rd0) we0 (fromEnum <$> wa0) w0 where rstBool = register clk rst0 en True (pure False) rstInv = invertReset rst0 waCounter :: Signal dom (Index n) waCounter = register clk rstInv en 0 (satSucc SatBound <$> waCounter) wa0 = fst . fromJustX <$> mw0 w0 = snd . fromJustX <$> mw0 we0 = isJust <$> mw0 rd1 = mux rstBool 0 (fromEnum <$> rd0) we1 = mux rstBool (pure True) we0 wa1 = mux rstBool (fromInteger . toInteger <$> waCounter) (fromEnum <$> wa0) w1 = mux rstBool (initF <$> waCounter) w0 blockRamU# :: forall n dom a . ( KnownDomain dom , HasCallStack , NFDataX a ) => Clock dom -> Enable dom -> SNat n ^ Number of elements in -> Signal dom Int -> Signal dom Bool -> Signal dom Int -> Signal dom a -> Signal dom a ^ Value of the at address @r@ from the previous clock cycle blockRamU# clk en SNat = TODO : to single BRAM primitive taking an initialization function blockRam# clk en (CV.map (\i -> deepErrorX $ "Initial value at index " <> show i <> " undefined.") (iterateI @n succ (0 :: Int))) # NOINLINE blockRamU # # blockRam1 :: forall n dom a r addr . ( KnownDomain dom , HasCallStack , NFDataX a , Enum addr , NFDataX addr , 1 <= n ) => Clock dom -> Reset dom for the to be reset to its initial state . -> Enable dom -> ResetStrategy r ^ Whether to clear on asserted reset ( ' ClearOnReset ' ) or cycles to clear the . -> SNat n ^ Number of elements in -> a ^ Initial content of the ( replicated /n/ times ) -> Signal dom addr -> Signal dom (Maybe (addr, a)) -> Signal dom a ^ Value of the at address @r@ from the previous clock cycle blockRam1 clk rst0 en rstStrategy n@SNat a rd0 mw0 = case rstStrategy of ClearOnReset -> blockRam1# clk en n a rd1 we1 wa1 w1 NoClearOnReset -> blockRam1# clk en n a (fromEnum <$> rd0) we0 (fromEnum <$> wa0) w0 where rstBool = register clk rst0 en True (pure False) rstInv = invertReset rst0 waCounter :: Signal dom (Index n) waCounter = register clk rstInv en 0 (satSucc SatBound <$> waCounter) wa0 = fst . fromJustX <$> mw0 w0 = snd . fromJustX <$> mw0 we0 = isJust <$> mw0 rd1 = mux rstBool 0 (fromEnum <$> rd0) we1 = mux rstBool (pure True) we0 wa1 = mux rstBool (fromInteger . toInteger <$> waCounter) (fromEnum <$> wa0) w1 = mux rstBool (pure a) w0 blockRam1# :: forall n dom a . ( KnownDomain dom , HasCallStack , NFDataX a ) => Clock dom -> Enable dom -> SNat n ^ Number of elements in -> a ^ Initial content of the ( replicated /n/ times ) -> Signal dom Int -> Signal dom Bool -> Signal dom Int -> Signal dom a -> Signal dom a ^ Value of the at address @r@ from the previous clock cycle blockRam1# clk en n a = TODO : to single BRAM primitive taking an initialization function blockRam# clk en (replicate n a) # NOINLINE blockRam1 # # blockRam# :: forall dom a n . ( KnownDomain dom , HasCallStack , NFDataX a ) => Clock dom -> Enable dom -> Vec n a ^ Initial content of the , also determines the size , @n@ , of the -> Signal dom Int -> Signal dom Bool -> Signal dom Int -> Signal dom a -> Signal dom a ^ Value of the at address @r@ from the previous clock cycle blockRam# (Clock _ Nothing) gen content = \rd wen waS wd -> runST $ do ramStart <- newListArray (0,szI-1) contentL < - unsafeThawSTArray ramArr go ramStart (withFrozenCallStack (deepErrorX "blockRam: intial value undefined")) (fromEnable gen) rd (fromEnable gen .&&. wen) waS wd where contentL = unsafeCoerce content :: [a] szI = L.length contentL ramArr = listArray ( 0,szI-1 ) contentL go :: STArray s Int a -> a -> Signal dom Bool -> Signal dom Int -> Signal dom Bool -> Signal dom Int -> Signal dom a -> ST s (Signal dom a) go !ram o ret@(~(re :- res)) rt@(~(r :- rs)) et@(~(e :- en)) wt@(~(w :- wr)) dt@(~(d :- din)) = do o `seqX` (o :-) <$> (ret `seq` rt `seq` et `seq` wt `seq` dt `seq` unsafeInterleaveST (do o' <- unsafeIOToST (catch (if re then unsafeSTToIO (ram `safeAt` r) else pure o) (\err@XException {} -> pure (throw err))) d `defaultSeqX` upd ram e (fromEnum w) d go ram o' res rs en wr din)) upd :: STArray s Int a -> Bool -> Int -> a -> ST s () upd ram we waddr d = case maybeIsX we of Nothing -> case maybeIsX waddr of forM_ [0..(szI-1)] (\i -> unsafeWriteSTArray ram i (seq waddr d)) safeUpdate wa (seq we d) ram Just True -> case maybeIsX waddr of forM_ [0..(szI-1)] (\i -> unsafeWriteSTArray ram i (seq waddr d)) Just wa -> safeUpdate wa d ram _ -> return () safeAt :: HasCallStack => STArray s Int a -> Int -> ST s a safeAt s i = if (0 <= i) && (i < szI) then unsafeReadSTArray s i else pure $ withFrozenCallStack (deepErrorX ("blockRam: read address " <> show i <> " not in range [0.." <> show szI <> ")")) # INLINE safeAt # safeUpdate :: HasCallStack => Int -> a -> STArray s Int a -> ST s () safeUpdate i a s = if (0 <= i) && (i < szI) then unsafeWriteSTArray s i a else let d = withFrozenCallStack (deepErrorX ("blockRam: write address " <> show i <> " not in range [0.." <> show szI <> ")")) in forM_ [0..(szI-1)] (\j -> unsafeWriteSTArray s j d) # INLINE safeUpdate # blockRam# _ _ _ = error "blockRam#: dynamic clocks not supported" # NOINLINE blockRam # # | Create a read - after - write block RAM from a read - before - write one readNew :: ( KnownDomain dom , NFDataX a , Eq addr ) => Clock dom -> Reset dom -> Enable dom -> (Signal dom addr -> Signal dom (Maybe (addr, a)) -> Signal dom a) ^ The component -> Signal dom addr -> Signal dom (Maybe (addr, a)) -> Signal dom a ^ Value of the at address @r@ from the previous clock cycle readNew clk rst en ram rdAddr wrM = mux wasSame wasWritten $ ram rdAddr wrM where readNewT rd (Just (wr, wrdata)) = (wr == rd, wrdata) readNewT _ Nothing = (False , undefined) (wasSame,wasWritten) = unbundle (register clk rst en (False, undefined) (readNewT <$> rdAddr <*> wrM)) data RamOp n a = RamRead (Index n) | RamWrite (Index n) a | RamNoOp deriving (Generic, NFDataX, Show) ramOpAddr :: RamOp n a -> Index n ramOpAddr (RamRead addr) = addr ramOpAddr (RamWrite addr _) = addr ramOpAddr RamNoOp = errorX "Address for No operation undefined" isRamWrite :: RamOp n a -> Bool isRamWrite (RamWrite {}) = True isRamWrite _ = False ramOpWriteVal :: RamOp n a -> Maybe a ramOpWriteVal (RamWrite _ val) = Just val ramOpWriteVal _ = Nothing isOp :: RamOp n a -> Bool isOp RamNoOp = False isOp _ = True block RAM is : WriteFirst . For mixed - port read / write , when port A writes to the address trueDualPortBlockRam :: forall nAddrs domA domB a . ( HasCallStack , KnownNat nAddrs , KnownDomain domA , KnownDomain domB , NFDataX a ) => Clock domA -> Clock domB -> Signal domA (RamOp nAddrs a) -> Signal domB (RamOp nAddrs a) -> (Signal domA a, Signal domB a) # INLINE trueDualPortBlockRam # trueDualPortBlockRam = \clkA clkB opA opB -> trueDualPortBlockRamWrapper clkA (isOp <$> opA) (isRamWrite <$> opA) (ramOpAddr <$> opA) (fromJustX . ramOpWriteVal <$> opA) clkB (isOp <$> opB) (isRamWrite <$> opB) (ramOpAddr <$> opB) (fromJustX . ramOpWriteVal <$> opB) toMaybeX :: a -> MaybeX a toMaybeX a = case isX a of Left _ -> IsX Right _ -> IsDefined a data MaybeX a = IsX | IsDefined !a data Conflict = Conflict , cfAddress :: !(MaybeX Int) } By naming all the arguments and setting the -fno - do - lambda - eta - expansion GHC A multi - clock true dual - port block RAM is only inferred from the generated HDL when it lives in its own Verilog module / VHDL architecture . Add any other multi - clock true dual - port block RAM . This wrapper pushes the primitive out trueDualPortBlockRamWrapper clkA enA weA addrA datA clkB enB weB addrB datB = trueDualPortBlockRam# clkA enA weA addrA datA clkB enB weB addrB datB # NOINLINE trueDualPortBlockRamWrapper # trueDualPortBlockRam#, trueDualPortBlockRamWrapper :: forall nAddrs domA domB a . ( HasCallStack , KnownNat nAddrs , KnownDomain domA , KnownDomain domB , NFDataX a ) => Clock domA -> Signal domA Bool -> Signal domA Bool -> Signal domA (Index nAddrs) -> Signal domA a -> Clock domB -> Signal domB Bool -> Signal domB Bool -> Signal domB (Index nAddrs) -> Signal domB a -> (Signal domA a, Signal domB a) ^ Outputs data on /next/ cycle . If write enable is @True@ , the data written trueDualPortBlockRam# clkA enA weA addrA datA clkB enB weB addrB datB | snatToNum @Int (clockPeriod @domA) < snatToNum @Int (clockPeriod @domB) = swap (trueDualPortBlockRamModel labelB clkB enB weB addrB datB labelA clkA enA weA addrA datA) | otherwise = trueDualPortBlockRamModel labelA clkA enA weA addrA datA labelB clkB enB weB addrB datB where labelA = "Port A" labelB = "Port B" # NOINLINE trueDualPortBlockRam # # # ANN trueDualPortBlockRam # hasBlackBox # Warning : this model only works if @domFast@ 's clock is faster than ( or equal trueDualPortBlockRamModel :: forall nAddrs domFast domSlow a . ( HasCallStack , KnownNat nAddrs , KnownDomain domSlow , KnownDomain domFast , NFDataX a ) => String -> Clock domSlow -> Signal domSlow Bool -> Signal domSlow Bool -> Signal domSlow (Index nAddrs) -> Signal domSlow a -> String -> Clock domFast -> Signal domFast Bool -> Signal domFast Bool -> Signal domFast (Index nAddrs) -> Signal domFast a -> (Signal domSlow a, Signal domFast a) trueDualPortBlockRamModel labelA clkA enA weA addrA datA labelB clkB enB weB addrB datB = ( startA :- outA , startB :- outB ) where (outA, outB) = go (Seq.fromFunction (natToNum @nAddrs) initElement) ensure ' go ' hits ' goFast ' first for 1 cycle , then execute ' goBoth ' ' floor(tA / tB ) ' cycles for the fast clock followed by 1 cycle of the (ClockB : clockTicks clkA clkB) (bundle (enA, weA, fromIntegral <$> addrA, datA)) (bundle (enB, weB, fromIntegral <$> addrB, datB)) startA startB startA = deepErrorX $ "trueDualPortBlockRam: " <> labelA <> ": First value undefined" startB = deepErrorX $ "trueDualPortBlockRam: " <> labelB <> ": First value undefined" initElement :: Int -> a initElement n = deepErrorX ("Unknown initial element; position " <> show n) unknownEnableAndAddr :: String -> String -> Int -> a unknownEnableAndAddr enaMsg addrMsg n = deepErrorX ("Write enable and address unknown; position " <> show n <> "\nWrite enable error message: " <> enaMsg <> "\nAddress error message: " <> addrMsg) unknownAddr :: String -> Int -> a unknownAddr msg n = deepErrorX ("Write enabled, but address unknown; position " <> show n <> "\nAddress error message: " <> msg) getConflict :: Bool -> Bool -> Bool -> Int -> Bool -> Int -> Maybe Conflict getConflict enA_ enB_ wenA addrA_ wenB addrB_ = if sameAddr then Just conflict else Nothing where wenAX = toMaybeX wenA wenBX = toMaybeX wenB mergeX IsX b = b mergeX a IsX = a mergeX (IsDefined a) (IsDefined b) = IsDefined (a && b) conflict = Conflict { cfRWA = if enB_ then wenBX else IsDefined False , cfRWB = if enA_ then wenAX else IsDefined False , cfWW = if enA_ && enB_ then mergeX wenAX wenBX else IsDefined False , cfAddress = toMaybeX addrA_ } sameAddr = case (isX addrA_, isX addrB_) of (Left _, _) -> True (_, Left _) -> True _ -> addrA_ == addrB_ writeRam :: Bool -> Int -> a -> Seq a -> (Maybe a, Seq a) writeRam enable addr dat mem | Left enaMsg <- enableUndefined , Left addrMsg <- addrUndefined = let msg = "Unknown enable and address" <> "\nWrite enable error message: " <> enaMsg <> "\nAddress error message: " <> addrMsg in ( Just (deepErrorX msg) , Seq.fromFunction (natToNum @nAddrs) (unknownEnableAndAddr enaMsg addrMsg) ) | Left enaMsg <- enableUndefined = let msg = "Write enable unknown; position" <> show addr <> "\nWrite enable error message: " <> enaMsg in writeRam True addr (deepErrorX msg) mem | enable , Left addrMsg <- addrUndefined = ( Just (deepErrorX "Unknown address") , Seq.fromFunction (natToNum @nAddrs) (unknownAddr addrMsg) ) | enable = (Just dat, Seq.update addr dat mem) | otherwise = (Nothing, mem) where enableUndefined = isX enable addrUndefined = isX addr go :: Seq a -> [ClockAB] -> Signal domSlow (Bool, Bool, Int, a) -> Signal domFast (Bool, Bool, Int, a) -> a -> a -> (Signal domSlow a, Signal domFast a) go _ [] _ _ = error "trueDualPortBlockRamModel.go: `ticks` should have been an infinite list" go ram0 (tick:ticks) as0 bs0 = case tick of ClockA -> goSlow ClockB -> goFast ClockAB -> goBoth where (enA_, weA_, addrA_, datA_) :- as1 = as0 (enB_, weB_, addrB_, datB_) :- bs1 = bs0 goBoth prevA prevB = outA2 `seqX` outB2 `seqX` (outA2 :- as2, outB2 :- bs2) where conflict = getConflict enA_ enB_ weA_ addrA_ weB_ addrB_ (datA1_,datB1_) = case conflict of Just Conflict{cfWW=IsDefined True} -> ( deepErrorX "trueDualPortBlockRam: conflicting write/write queries" , deepErrorX "trueDualPortBlockRam: conflicting write/write queries" ) Just Conflict{cfWW=IsX} -> ( deepErrorX "trueDualPortBlockRam: conflicting write/write queries" , deepErrorX "trueDualPortBlockRam: conflicting write/write queries" ) _ -> (datA_,datB_) (wroteA,ram1) = writeRam weA_ addrA_ datA1_ ram0 (wroteB,ram2) = writeRam weB_ addrB_ datB1_ ram1 outA1 = case conflict of Just Conflict{cfRWA=IsDefined True} -> deepErrorX "trueDualPortBlockRam: conflicting read/write queries" Just Conflict{cfRWA=IsX} -> deepErrorX "trueDualPortBlockRam: conflicting read/write queries" _ -> fromMaybe (ram0 `Seq.index` addrA_) wroteA outB1 = case conflict of Just Conflict{cfRWB=IsDefined True} -> deepErrorX "trueDualPortBlockRam: conflicting read/write queries" Just Conflict{cfRWB=IsX} -> deepErrorX "trueDualPortBlockRam: conflicting read/write queries" _ -> fromMaybe (ram0 `Seq.index` addrB_) wroteB outA2 = if enA_ then outA1 else prevA outB2 = if enB_ then outB1 else prevB (as2,bs2) = go ram2 ticks as1 bs1 outA2 outB2 1 iteration here , as this is the slow clock . goSlow _ prevB | enA_ = out0 `seqX` (out0 :- as2, bs2) where (wrote, !ram1) = writeRam weA_ addrA_ datA_ ram0 out0 = fromMaybe (ram1 `Seq.index` addrA_) wrote (as2, bs2) = go ram1 ticks as1 bs0 out0 prevB goSlow prevA prevB = (prevA :- as2, bs2) where (as2,bs2) = go ram0 ticks as1 bs0 prevA prevB 1 or more iterations here , as this is the fast clock . First iteration goFast prevA _ | enB_ = out0 `seqX` (as2, out0 :- bs2) where (wrote, !ram1) = writeRam weB_ addrB_ datB_ ram0 out0 = fromMaybe (ram1 `Seq.index` addrB_) wrote (as2, bs2) = go ram1 ticks as0 bs1 prevA out0 goFast prevA prevB = (as2, prevB :- bs2) where (as2,bs2) = go ram0 ticks as0 bs1 prevA prevB
182d4c5544db2c80fb38b1aeeea24f33ec8058afc375788da5e68e0b4018eaea
restyled-io/restyled.io
ProfileSpec.hs
module Restyled.Handlers.ProfileSpec ( spec ) where import Restyled.Test import qualified Database.Persist as P import qualified GitHub.Data as GH import Restyled.Authorization (authRepoCacheKey) import Restyled.GitHubOrg import Restyled.Test.Graphula spec :: Spec spec = withApp $ do describe "/profile" $ do it "requires authentication" $ do get ProfileR `shouldRedirectTo` "/auth/login" it "shows user repositories" $ graph $ do void $ node @Repo () $ edit $ (fieldLens RepoOwner .~ "pbrisbin") . (fieldLens RepoName .~ "foo") void $ node @Repo () $ edit $ (fieldLens RepoOwner .~ "pbrisbin") . (fieldLens RepoName .~ "bar") user <- genUser "" $ (fieldLens UserGithubUserId ?~ 123) . (fieldLens UserGithubUsername ?~ "pbrisbin") lift $ do authenticateAs user get ProfileR statusIs 200 htmlAnyContain ".profile-repo" "pbrisbin/foo" htmlAnyContain ".profile-repo" "pbrisbin/bar" it "shows org repositories" $ graph $ do void $ node @Repo () $ edit $ (fieldLens RepoOwner .~ "freckle") . (fieldLens RepoName .~ "foo") void $ node @Repo () $ edit $ (fieldLens RepoOwner .~ "yesodweb") . (fieldLens RepoName .~ "bar") user <- genUser "" $ (fieldLens UserGithubUserId ?~ 123) . (fieldLens UserGithubUsername ?~ "pbrisbin") lift $ do authenticateAs user cacheGitHubOrgs "pbrisbin" ["freckle", "restyled-io", "yesodweb"] get ProfileR statusIs 200 htmlAnyContain ".profile-repo" "freckle/foo" htmlAnyContain ".profile-repo" "yesodweb/bar" it "supports enable/disable for private repo plans (User)" $ graph $ do repo <- node @Repo () $ edit $ (fieldLens RepoOwner .~ "pbrisbin") . (fieldLens RepoName .~ "private") . (fieldLens RepoIsPrivate .~ True) plan <- node @MarketplacePlan () $ edit $ setPlanLimited 1 account <- genAccount repo plan setAccountUnexpired user <- genUser "" $ (fieldLens UserGithubUserId ?~ 123) . (fieldLens UserGithubUsername ?~ "pbrisbin") lift $ do authenticateAs user cacheCallaboratorCanRead (entityKey repo) "pbrisbin" True cacheGitHubOrgs "pbrisbin" [] get ProfileR statusIs 200 htmlAnyContain ".profile-repo" "pbrisbin/private" htmlAnyContain ".profile-repo" "Enable" clickOn $ " .profile - repo- " < > ( entityKey repo ) < > " .enable " post $ RepoP "pbrisbin" "private" $ RepoMarketplaceP RepoMarketplaceClaimR followRedirect htmlAnyContain ".profile-repo" "pbrisbin/private" htmlAnyContain ".profile-repo" "Disable" enabled <- runDB $ getBy $ UniqueMarketplaceEnabledRepo (entityKey plan) (entityKey account) (entityKey repo) void enabled `shouldBe` Just () it "supports enable/disable for private repo plans (Org)" $ graph $ do repo <- node @Repo () $ edit $ (fieldLens RepoOwner .~ "yesodweb") . (fieldLens RepoName .~ "yesod") . (fieldLens RepoIsPrivate .~ True) plan <- node @MarketplacePlan () $ edit $ setPlanLimited 1 account <- genAccount repo plan setAccountUnexpired user <- genUser "" $ (fieldLens UserGithubUserId ?~ 123) . (fieldLens UserGithubUsername ?~ "pbrisbin") lift $ do authenticateAs user cacheCallaboratorCanRead (entityKey repo) "pbrisbin" True cacheGitHubOrgs "pbrisbin" ["yesodweb"] get ProfileR statusIs 200 htmlAnyContain ".profile-repo" "yesodweb/yesod" htmlAnyContain ".profile-repo" "Enable" clickOn $ " .profile - repo- " < > repoId < > " .enable " post $ RepoP "yesodweb" "yesod" $ RepoMarketplaceP RepoMarketplaceClaimR followRedirect htmlAnyContain ".profile-repo" "yesodweb/yesod" htmlAnyContain ".profile-repo" "Disable" enabled <- runDB $ getBy $ UniqueMarketplaceEnabledRepo (entityKey plan) (entityKey account) (entityKey repo) void enabled `shouldBe` Just () cacheCallaboratorCanRead :: RepoId -> GitHubUserName -> Bool -> YesodExample App () cacheCallaboratorCanRead repoId user canRead = do Just repo <- runDB $ P.get repoId setCache (cacheKey $ authRepoCacheKey repo user) canRead cacheGitHubOrgs :: MonadCache m => GH.Name GH.User -> [GH.Name GH.Organization] -> m () cacheGitHubOrgs user = setCache (cacheKey $ githubOrgsCacheKey user) . map toGitHubOrg where toGitHubOrg login = GitHubOrg GH.SimpleOrganization { GH.simpleOrganizationId = 99 , GH.simpleOrganizationLogin = login , GH.simpleOrganizationUrl = GH.URL "" , GH.simpleOrganizationAvatarUrl = GH.URL "" }
null
https://raw.githubusercontent.com/restyled-io/restyled.io/134019dffb54f84bddb905e8e21131b4e33f7850/test/Restyled/Handlers/ProfileSpec.hs
haskell
module Restyled.Handlers.ProfileSpec ( spec ) where import Restyled.Test import qualified Database.Persist as P import qualified GitHub.Data as GH import Restyled.Authorization (authRepoCacheKey) import Restyled.GitHubOrg import Restyled.Test.Graphula spec :: Spec spec = withApp $ do describe "/profile" $ do it "requires authentication" $ do get ProfileR `shouldRedirectTo` "/auth/login" it "shows user repositories" $ graph $ do void $ node @Repo () $ edit $ (fieldLens RepoOwner .~ "pbrisbin") . (fieldLens RepoName .~ "foo") void $ node @Repo () $ edit $ (fieldLens RepoOwner .~ "pbrisbin") . (fieldLens RepoName .~ "bar") user <- genUser "" $ (fieldLens UserGithubUserId ?~ 123) . (fieldLens UserGithubUsername ?~ "pbrisbin") lift $ do authenticateAs user get ProfileR statusIs 200 htmlAnyContain ".profile-repo" "pbrisbin/foo" htmlAnyContain ".profile-repo" "pbrisbin/bar" it "shows org repositories" $ graph $ do void $ node @Repo () $ edit $ (fieldLens RepoOwner .~ "freckle") . (fieldLens RepoName .~ "foo") void $ node @Repo () $ edit $ (fieldLens RepoOwner .~ "yesodweb") . (fieldLens RepoName .~ "bar") user <- genUser "" $ (fieldLens UserGithubUserId ?~ 123) . (fieldLens UserGithubUsername ?~ "pbrisbin") lift $ do authenticateAs user cacheGitHubOrgs "pbrisbin" ["freckle", "restyled-io", "yesodweb"] get ProfileR statusIs 200 htmlAnyContain ".profile-repo" "freckle/foo" htmlAnyContain ".profile-repo" "yesodweb/bar" it "supports enable/disable for private repo plans (User)" $ graph $ do repo <- node @Repo () $ edit $ (fieldLens RepoOwner .~ "pbrisbin") . (fieldLens RepoName .~ "private") . (fieldLens RepoIsPrivate .~ True) plan <- node @MarketplacePlan () $ edit $ setPlanLimited 1 account <- genAccount repo plan setAccountUnexpired user <- genUser "" $ (fieldLens UserGithubUserId ?~ 123) . (fieldLens UserGithubUsername ?~ "pbrisbin") lift $ do authenticateAs user cacheCallaboratorCanRead (entityKey repo) "pbrisbin" True cacheGitHubOrgs "pbrisbin" [] get ProfileR statusIs 200 htmlAnyContain ".profile-repo" "pbrisbin/private" htmlAnyContain ".profile-repo" "Enable" clickOn $ " .profile - repo- " < > ( entityKey repo ) < > " .enable " post $ RepoP "pbrisbin" "private" $ RepoMarketplaceP RepoMarketplaceClaimR followRedirect htmlAnyContain ".profile-repo" "pbrisbin/private" htmlAnyContain ".profile-repo" "Disable" enabled <- runDB $ getBy $ UniqueMarketplaceEnabledRepo (entityKey plan) (entityKey account) (entityKey repo) void enabled `shouldBe` Just () it "supports enable/disable for private repo plans (Org)" $ graph $ do repo <- node @Repo () $ edit $ (fieldLens RepoOwner .~ "yesodweb") . (fieldLens RepoName .~ "yesod") . (fieldLens RepoIsPrivate .~ True) plan <- node @MarketplacePlan () $ edit $ setPlanLimited 1 account <- genAccount repo plan setAccountUnexpired user <- genUser "" $ (fieldLens UserGithubUserId ?~ 123) . (fieldLens UserGithubUsername ?~ "pbrisbin") lift $ do authenticateAs user cacheCallaboratorCanRead (entityKey repo) "pbrisbin" True cacheGitHubOrgs "pbrisbin" ["yesodweb"] get ProfileR statusIs 200 htmlAnyContain ".profile-repo" "yesodweb/yesod" htmlAnyContain ".profile-repo" "Enable" clickOn $ " .profile - repo- " < > repoId < > " .enable " post $ RepoP "yesodweb" "yesod" $ RepoMarketplaceP RepoMarketplaceClaimR followRedirect htmlAnyContain ".profile-repo" "yesodweb/yesod" htmlAnyContain ".profile-repo" "Disable" enabled <- runDB $ getBy $ UniqueMarketplaceEnabledRepo (entityKey plan) (entityKey account) (entityKey repo) void enabled `shouldBe` Just () cacheCallaboratorCanRead :: RepoId -> GitHubUserName -> Bool -> YesodExample App () cacheCallaboratorCanRead repoId user canRead = do Just repo <- runDB $ P.get repoId setCache (cacheKey $ authRepoCacheKey repo user) canRead cacheGitHubOrgs :: MonadCache m => GH.Name GH.User -> [GH.Name GH.Organization] -> m () cacheGitHubOrgs user = setCache (cacheKey $ githubOrgsCacheKey user) . map toGitHubOrg where toGitHubOrg login = GitHubOrg GH.SimpleOrganization { GH.simpleOrganizationId = 99 , GH.simpleOrganizationLogin = login , GH.simpleOrganizationUrl = GH.URL "" , GH.simpleOrganizationAvatarUrl = GH.URL "" }
a92641a14b8bcf72b2bdd2462894d640be6c5e89504ed8314ea972746d2a010f
qfpl/propagator-examples
Sudoku4.hs
module Data.Propagator.Example.Sudoku4 where import Control.Monad.ST (ST) import Data.Foldable (toList, traverse_) import Data.List (intercalate) import Data.Propagator import Data.Set (Set, (\\)) import qualified Data.Set as Set data Number = One | Two | Three | Four deriving (Eq, Ord, Show) newtype Square = Square { possibilities :: Set Number } instance Propagated Square where merge (Square p) (Square q) = let overlap = Set.intersection p q in if Set.null overlap then Contradiction mempty "Impossible square" else Change (p /= overlap) (Square overlap) data V4 a = V4 { _1 :: a , _2 :: a , _3 :: a , _4 :: a } deriving (Eq, Ord) instance Show a => Show (V4 a) where show = show . toList newtype Grid s = Grid { ungrid :: V4 (V4 (Cell s Square)) } newtype SudokuResult = Result { unresult :: V4 (V4 (Maybe Number))} instance Show SudokuResult where show (Result vvmn) = intercalate "\n" . toList $ fmap (fmap showMN . toList) vvmn where showMN :: Maybe Number -> Char showMN Nothing = '?' showMN (Just n) = case n of One -> '1' Two -> '2' Three -> '3' Four -> '4' instance Functor V4 where fmap f (V4 a b c d) = V4 (f a) (f b) (f c) (f d) instance Foldable V4 where foldMap f (V4 a b c d) = f a <> f b <> f c <> f d instance Traversable V4 where traverse f (V4 a b c d) = V4 <$> f a <*> f b <*> f c <*> f d instance Applicative V4 where pure a = V4 a a a a V4 fa fb fc fd <*> V4 a b c d = V4 (fa a) (fb b) (fc c) (fd d) sudokuExample :: ST s SudokuResult sudokuExample = do grid <- initialGrid traverse_ allDifferent (rows grid) traverse_ allDifferent (columns grid) traverse_ allDifferent (blocks grid) setup grid collect grid This is naive . There are papers on making the allDifferent constraint fast allDifferent :: V4 (Cell s Square) -> ST s () allDifferent = go . toList where go [] = pure () go (x:xs) = traverse_ (different x) xs *> go xs initialGrid :: ST s (Grid s) initialGrid = Grid <$> traverse sequenceA (pure (pure cell)) setup :: Grid s -> ST s () setup grid = do -- ??3? -- ?4?? -- ??2? ? ? ? 1 write' (_3._1) Three write' (_2._2) Four write' (_3._3) Two write' (_4._4) One where write' path n = write (path (ungrid grid)) (sq n) sq = Square . Set.singleton different :: Cell s Square -> Cell s Square -> ST s () different s1 s2 = do lift1 diff s1 s2 lift1 diff s2 s1 where universe = Set.fromList[One,Two,Three,Four] diff s = Square $ case demand s of Nothing -> universe Just x -> universe \\ Set.singleton x collect :: Grid s -> ST s SudokuResult collect = fmap Result . (traverse.traverse) readSquare . ungrid where readSquare :: Cell s Square -> ST s (Maybe Number) readSquare c = (>>= demand) <$> content c demand :: Square -> Maybe Number demand square = case Set.toList (possibilities square) of [] -> Nothing _:_:_ -> Nothing x:[] -> Just x rows :: Grid s -> V4 (V4 (Cell s Square)) rows = ungrid columns :: Grid s -> V4 (V4 (Cell s Square)) columns = sequenceA . ungrid blocks :: Grid s -> V4 (V4 (Cell s Square)) blocks grid = (fmap.fmap) select (V4 tl tr bl br) where select = ($ ungrid grid) tl = V4 (_1._1) (_1._2) (_2._1) (_2._2) tr = V4 (_1._3) (_1._4) (_2._3) (_2._4) bl = V4 (_3._1) (_3._2) (_4._1) (_4._2) br = V4 (_3._3) (_3._4) (_4._3) (_4._4)
null
https://raw.githubusercontent.com/qfpl/propagator-examples/93dbabdac1b06c8acee65c6e815c854bde07301e/src/Data/Propagator/Example/Sudoku4.hs
haskell
??3? ?4?? ??2?
module Data.Propagator.Example.Sudoku4 where import Control.Monad.ST (ST) import Data.Foldable (toList, traverse_) import Data.List (intercalate) import Data.Propagator import Data.Set (Set, (\\)) import qualified Data.Set as Set data Number = One | Two | Three | Four deriving (Eq, Ord, Show) newtype Square = Square { possibilities :: Set Number } instance Propagated Square where merge (Square p) (Square q) = let overlap = Set.intersection p q in if Set.null overlap then Contradiction mempty "Impossible square" else Change (p /= overlap) (Square overlap) data V4 a = V4 { _1 :: a , _2 :: a , _3 :: a , _4 :: a } deriving (Eq, Ord) instance Show a => Show (V4 a) where show = show . toList newtype Grid s = Grid { ungrid :: V4 (V4 (Cell s Square)) } newtype SudokuResult = Result { unresult :: V4 (V4 (Maybe Number))} instance Show SudokuResult where show (Result vvmn) = intercalate "\n" . toList $ fmap (fmap showMN . toList) vvmn where showMN :: Maybe Number -> Char showMN Nothing = '?' showMN (Just n) = case n of One -> '1' Two -> '2' Three -> '3' Four -> '4' instance Functor V4 where fmap f (V4 a b c d) = V4 (f a) (f b) (f c) (f d) instance Foldable V4 where foldMap f (V4 a b c d) = f a <> f b <> f c <> f d instance Traversable V4 where traverse f (V4 a b c d) = V4 <$> f a <*> f b <*> f c <*> f d instance Applicative V4 where pure a = V4 a a a a V4 fa fb fc fd <*> V4 a b c d = V4 (fa a) (fb b) (fc c) (fd d) sudokuExample :: ST s SudokuResult sudokuExample = do grid <- initialGrid traverse_ allDifferent (rows grid) traverse_ allDifferent (columns grid) traverse_ allDifferent (blocks grid) setup grid collect grid This is naive . There are papers on making the allDifferent constraint fast allDifferent :: V4 (Cell s Square) -> ST s () allDifferent = go . toList where go [] = pure () go (x:xs) = traverse_ (different x) xs *> go xs initialGrid :: ST s (Grid s) initialGrid = Grid <$> traverse sequenceA (pure (pure cell)) setup :: Grid s -> ST s () setup grid = do ? ? ? 1 write' (_3._1) Three write' (_2._2) Four write' (_3._3) Two write' (_4._4) One where write' path n = write (path (ungrid grid)) (sq n) sq = Square . Set.singleton different :: Cell s Square -> Cell s Square -> ST s () different s1 s2 = do lift1 diff s1 s2 lift1 diff s2 s1 where universe = Set.fromList[One,Two,Three,Four] diff s = Square $ case demand s of Nothing -> universe Just x -> universe \\ Set.singleton x collect :: Grid s -> ST s SudokuResult collect = fmap Result . (traverse.traverse) readSquare . ungrid where readSquare :: Cell s Square -> ST s (Maybe Number) readSquare c = (>>= demand) <$> content c demand :: Square -> Maybe Number demand square = case Set.toList (possibilities square) of [] -> Nothing _:_:_ -> Nothing x:[] -> Just x rows :: Grid s -> V4 (V4 (Cell s Square)) rows = ungrid columns :: Grid s -> V4 (V4 (Cell s Square)) columns = sequenceA . ungrid blocks :: Grid s -> V4 (V4 (Cell s Square)) blocks grid = (fmap.fmap) select (V4 tl tr bl br) where select = ($ ungrid grid) tl = V4 (_1._1) (_1._2) (_2._1) (_2._2) tr = V4 (_1._3) (_1._4) (_2._3) (_2._4) bl = V4 (_3._1) (_3._2) (_4._1) (_4._2) br = V4 (_3._3) (_3._4) (_4._3) (_4._4)
268897a05b558d5212217396937c7fc0d513e7ded1a5ee4d18e1b13d68c2f030
kawasima/darzana
project.clj
(defproject net.unit8.darzana/darzana "1.0.0-SNAPSHOT" :description "A Backends for Frontends Tool" :url "" :license {:name "Eclipse Public License - v 1.0" :url "-v10.html" :distribution :repo :comments "same as Clojure"} :min-lein-version "2.0.0" :dependencies [[org.clojure/clojure "1.9.0"] [org.clojure/spec.alpha "0.1.143"] [org.clojure/core.async "0.4.474"] [org.clojure/java.data "0.1.1"] [cheshire "5.8.0"] ;; json [bidi "2.1.3"] [duct/core "0.6.2"] [duct/module.logging "0.3.1"] [duct/logger "0.2.1"] [duct/server.http.jetty "0.2.0"] [ring/ring-core "1.6.3"] [ring/ring-devel "1.6.3"] [ring/ring-defaults "0.3.1"] [ring-webjars "0.2.0"] [javax.cache/cache-api "1.0.0"] [io.swagger.parser.v3/swagger-parser-v3 "2.0.0-rc3"] [com.github.jknack/handlebars "4.0.6"] [org.freemarker/freemarker "2.3.27-incubating"] [com.squareup.okhttp3/okhttp "3.9.1"] [org.hibernate.validator/hibernate-validator "6.0.7.Final"] [org.glassfish/javax.el "3.0.1-b08"] [org.slf4j/slf4j-simple "1.7.25"] [integrant/repl "0.3.0"]] :plugins [[duct/lein-duct "0.10.6"]] :main ^:skip-aot darzana.main :target-path "target/%s/" :resource-paths ["resources"] :prep-tasks ["javac" "compile"] :profiles {:dev [:project/dev :profiles/dev] :repl {:prep-tasks ^:replace [["javac"] ["compile"]] :resource-paths ^:replace ["resources" "dev/resources"] :repl-options {:init-ns user}} :uberjar {:aot :all} :profiles/dev {} :project/dev {:dependencies [[integrant/repl "0.3.1"] [org.jsr107.ri/cache-ri-impl "1.0.0"] [eftest "0.5.0"] [org.clojure/test.check "0.9.0"] [kerodon "0.9.0"]] :source-paths ["dev/src"] :java-source-paths ["dev/src"] :resource-paths ["dev/resources"] :env {:port "3000"}}})
null
https://raw.githubusercontent.com/kawasima/darzana/4b37c8556f74219b707d23cb2d6dce70509a0c1b/project.clj
clojure
json
(defproject net.unit8.darzana/darzana "1.0.0-SNAPSHOT" :description "A Backends for Frontends Tool" :url "" :license {:name "Eclipse Public License - v 1.0" :url "-v10.html" :distribution :repo :comments "same as Clojure"} :min-lein-version "2.0.0" :dependencies [[org.clojure/clojure "1.9.0"] [org.clojure/spec.alpha "0.1.143"] [org.clojure/core.async "0.4.474"] [org.clojure/java.data "0.1.1"] [bidi "2.1.3"] [duct/core "0.6.2"] [duct/module.logging "0.3.1"] [duct/logger "0.2.1"] [duct/server.http.jetty "0.2.0"] [ring/ring-core "1.6.3"] [ring/ring-devel "1.6.3"] [ring/ring-defaults "0.3.1"] [ring-webjars "0.2.0"] [javax.cache/cache-api "1.0.0"] [io.swagger.parser.v3/swagger-parser-v3 "2.0.0-rc3"] [com.github.jknack/handlebars "4.0.6"] [org.freemarker/freemarker "2.3.27-incubating"] [com.squareup.okhttp3/okhttp "3.9.1"] [org.hibernate.validator/hibernate-validator "6.0.7.Final"] [org.glassfish/javax.el "3.0.1-b08"] [org.slf4j/slf4j-simple "1.7.25"] [integrant/repl "0.3.0"]] :plugins [[duct/lein-duct "0.10.6"]] :main ^:skip-aot darzana.main :target-path "target/%s/" :resource-paths ["resources"] :prep-tasks ["javac" "compile"] :profiles {:dev [:project/dev :profiles/dev] :repl {:prep-tasks ^:replace [["javac"] ["compile"]] :resource-paths ^:replace ["resources" "dev/resources"] :repl-options {:init-ns user}} :uberjar {:aot :all} :profiles/dev {} :project/dev {:dependencies [[integrant/repl "0.3.1"] [org.jsr107.ri/cache-ri-impl "1.0.0"] [eftest "0.5.0"] [org.clojure/test.check "0.9.0"] [kerodon "0.9.0"]] :source-paths ["dev/src"] :java-source-paths ["dev/src"] :resource-paths ["dev/resources"] :env {:port "3000"}}})
f25937d71afbd5f7ecf5a782f5a35cfbefb09086babe7f53c45b2cdf406a5aed
rethab/h-gpgme
Gpgme.hs
-- | Module : Crypto . Gpgme Copyright : ( c ) Reto Hablützel 2015 License : MIT -- -- Maintainer : -- Stability : experimental -- Portability : untested -- -- High Level Binding for GnuPG Made Easy (gpgme) -- Most of these functions are a one - to - one translation from GnuPG API with some to make -- the API more convenient. -- -- See the GnuPG manual for more information: <> -- -- -- == Example (from the tests): -- > let alice_pub_fpr = " EAACEB8A " -- > -- >Just enc <- withCtx "test/bob" "C" OpenPGP $ \bCtx -> runMaybeT $ do > aPubKey < - MaybeT $ getKey bCtx alice_pub_fpr NoSecret -- > fromRight $ encrypt bCtx [aPubKey] NoFlag plain -- > -- >-- decrypt -- >dec <- withCtx "test/alice" "C" OpenPGP $ \aCtx -> > decrypt aCtx enc -- > -- module Crypto.Gpgme ( -- * Context Ctx , newCtx , freeCtx , withCtx , setArmor , setKeyListingMode * * Passphrase callbacks , isPassphraseCbSupported , PassphraseCb , setPassphraseCallback -- ** Progress callbacks , progressCb , setProgressCallback -- * Keys , Key , importKeyFromFile , getKey , listKeys , removeKey , RemoveKeyFlags(..) , searchKeys -- * Information about keys , Validity (..) , PubKeyAlgo (..) , KeySignature (..) , UserId (..) , KeyUserId (..) , keyUserIds , keyUserIds' , SubKey (..) , keySubKeys , keySubKeys' -- * Encryption , Signature , SignatureSummary(..) , VerificationResult , encrypt , encryptSign , encryptFd , encryptSignFd , encrypt' , encryptSign' , decrypt , decryptFd , decryptVerifyFd , decrypt' , decryptVerify , decryptVerify' , verify , verify' , verifyDetached , verifyDetached' , verifyPlain , verifyPlain' , sign -- * Error handling , GpgmeError , errorString , sourceString -- * Other Types , KeyListingMode(..) , SignMode(..) , Fpr , Encrypted , Plain , Protocol(..) , InvalidKey , IncludeSecret(..) , Flag(..) , DecryptError(..) , HgpgmeException(..) ) where import Crypto.Gpgme.Ctx import Crypto.Gpgme.Crypto import Crypto.Gpgme.Types import Crypto.Gpgme.Key
null
https://raw.githubusercontent.com/rethab/h-gpgme/6af2391258cbf9c6b24afed78ecaad6ce4d5e04d/src/Crypto/Gpgme.hs
haskell
| Maintainer : Stability : experimental Portability : untested High Level Binding for GnuPG Made Easy (gpgme) the API more convenient. See the GnuPG manual for more information: <> == Example (from the tests): > >Just enc <- withCtx "test/bob" "C" OpenPGP $ \bCtx -> runMaybeT $ do > fromRight $ encrypt bCtx [aPubKey] NoFlag plain > >-- decrypt >dec <- withCtx "test/alice" "C" OpenPGP $ \aCtx -> > * Context ** Progress callbacks * Keys * Information about keys * Encryption * Error handling * Other Types
Module : Crypto . Gpgme Copyright : ( c ) Reto Hablützel 2015 License : MIT Most of these functions are a one - to - one translation from GnuPG API with some to make > let alice_pub_fpr = " EAACEB8A " > aPubKey < - MaybeT $ getKey bCtx alice_pub_fpr NoSecret > decrypt aCtx enc module Crypto.Gpgme ( Ctx , newCtx , freeCtx , withCtx , setArmor , setKeyListingMode * * Passphrase callbacks , isPassphraseCbSupported , PassphraseCb , setPassphraseCallback , progressCb , setProgressCallback , Key , importKeyFromFile , getKey , listKeys , removeKey , RemoveKeyFlags(..) , searchKeys , Validity (..) , PubKeyAlgo (..) , KeySignature (..) , UserId (..) , KeyUserId (..) , keyUserIds , keyUserIds' , SubKey (..) , keySubKeys , keySubKeys' , Signature , SignatureSummary(..) , VerificationResult , encrypt , encryptSign , encryptFd , encryptSignFd , encrypt' , encryptSign' , decrypt , decryptFd , decryptVerifyFd , decrypt' , decryptVerify , decryptVerify' , verify , verify' , verifyDetached , verifyDetached' , verifyPlain , verifyPlain' , sign , GpgmeError , errorString , sourceString , KeyListingMode(..) , SignMode(..) , Fpr , Encrypted , Plain , Protocol(..) , InvalidKey , IncludeSecret(..) , Flag(..) , DecryptError(..) , HgpgmeException(..) ) where import Crypto.Gpgme.Ctx import Crypto.Gpgme.Crypto import Crypto.Gpgme.Types import Crypto.Gpgme.Key
763b0ea82e2190fb0c5403164e6ab344cc14772135b4d80dcdce665d60c03d5e
behrica/casagemas
setup.clj
(ns org.scicloj.casagemas.setup (:require [nextjournal.clerk :as clerk] [nextjournal.clerk.tap] [org.scicloj.casagemas] [org.scicloj.casagemas.dataset] [org.scicloj.casagemas.kroki] [nextjournal.clerk.viewer :as v])) (defn start-clerk! [] (println "Start Clerk") (future (clerk/serve! {:browse? true})) (Thread/sleep 10000) (println "Show tap inspecor") (clerk/show! 'nextjournal.clerk.tap) (println "Configure Clerk viewers") (nextjournal.clerk.viewer/reset-viewers! ;; :default (find-ns 'nextjournal.clerk.tap) (-> nextjournal.clerk.viewer/default-viewers (nextjournal.clerk.viewer/add-viewers [nextjournal.clerk.tap/tap-viewer]) (nextjournal.clerk.viewer/add-viewers (concat (org.scicloj.casagemas/viewers) (org.scicloj.casagemas.dataset/viewers) (org.scicloj.casagemas.kroki/viewers))))))
null
https://raw.githubusercontent.com/behrica/casagemas/ba57339fda376943a673fa456b01f761e7d1d6da/src/org/scicloj/casagemas/setup.clj
clojure
:default
(ns org.scicloj.casagemas.setup (:require [nextjournal.clerk :as clerk] [nextjournal.clerk.tap] [org.scicloj.casagemas] [org.scicloj.casagemas.dataset] [org.scicloj.casagemas.kroki] [nextjournal.clerk.viewer :as v])) (defn start-clerk! [] (println "Start Clerk") (future (clerk/serve! {:browse? true})) (Thread/sleep 10000) (println "Show tap inspecor") (clerk/show! 'nextjournal.clerk.tap) (println "Configure Clerk viewers") (nextjournal.clerk.viewer/reset-viewers! (find-ns 'nextjournal.clerk.tap) (-> nextjournal.clerk.viewer/default-viewers (nextjournal.clerk.viewer/add-viewers [nextjournal.clerk.tap/tap-viewer]) (nextjournal.clerk.viewer/add-viewers (concat (org.scicloj.casagemas/viewers) (org.scicloj.casagemas.dataset/viewers) (org.scicloj.casagemas.kroki/viewers))))))
88fe6cb570415aa8d76afe3c71922d345ef88e2cefa213f21460a4a8cdac9d70
code-iai/ros_emacs_utils
mezzano.lisp
;;;;; -*- indent-tabs-mode: nil -*- ;;; swank-mezzano.lisp --- SLIME backend for Mezzano ;;; ;;; This code has been placed in the Public Domain. All warranties are ;;; disclaimed. ;;; Administrivia (defpackage swank/mezzano (:use cl swank/backend)) (in-package swank/mezzano) ;;; swank-mop (import-swank-mop-symbols :mezzano.clos '(:class-default-initargs :class-direct-default-initargs :specializer-direct-methods :generic-function-declarations)) (defun swank-mop:specializer-direct-methods (obj) (declare (ignore obj)) '()) (defun swank-mop:generic-function-declarations (gf) (declare (ignore gf)) '()) (defimplementation gray-package-name () "MEZZANO.GRAY") ;;;; TCP server (defclass listen-socket () ((%host :initarg :host) (%port :initarg :port) (%connection-fifo :initarg :connections) (%callback :initarg :callback))) (defimplementation create-socket (host port &key backlog) (let* ((connections (mezzano.supervisor:make-fifo (or backlog 10))) (sock (make-instance 'listen-socket :host host :port port :connections connections :callback (lambda (conn) (do-connection conn connections)))) (listen-fn (slot-value sock '%callback))) (when (find port mezzano.network.tcp::*server-alist* :key #'first) (error "Server already listening on port ~D" port)) (push (list port listen-fn) mezzano.network.tcp::*server-alist*) sock)) (defun do-connection (conn connections) (when (not (mezzano.supervisor:fifo-push (make-instance 'mezzano.network.tcp::tcp-stream :connection conn) connections nil)) ;; Drop connections when they can't be handled. (close conn))) (defimplementation local-port (socket) (slot-value socket '%port)) (defimplementation close-socket (socket) (setf mezzano.network.tcp::*server-alist* (remove (slot-value socket '%callback) mezzano.network.tcp::*server-alist* :key #'second)) (let ((fifo (slot-value socket '%connection-fifo))) (loop (let ((conn (mezzano.supervisor:fifo-pop fifo nil))) (when (not conn) (return)) (close conn)))) (setf (slot-value socket '%connection-fifo) nil)) (defimplementation accept-connection (socket &key external-format buffering timeout) (declare (ignore external-format buffering timeout)) (loop (let ((value (mezzano.supervisor:fifo-pop (slot-value socket '%connection-fifo) nil))) (when value (return value))) ;; Poke standard-input every now and then to keep the console alive. (listen) (sleep 0.05))) (defimplementation preferred-communication-style () :spawn) ;;;; Unix signals ;;;; ???? (defimplementation getpid () 0) ;;;; Compilation (defun signal-compiler-condition (condition severity) (signal 'compiler-condition :original-condition condition :severity severity :message (format nil "~A" condition) :location nil)) (defimplementation call-with-compilation-hooks (func) (handler-bind ((error (lambda (c) (signal-compiler-condition c :error))) (warning (lambda (c) (signal-compiler-condition c :warning))) (style-warning (lambda (c) (signal-compiler-condition c :style-warning)))) (funcall func))) (defimplementation swank-compile-string (string &key buffer position filename policy) (declare (ignore buffer policy)) (let* ((*load-pathname* (ignore-errors (pathname filename))) (*load-truename* (when *load-pathname* (ignore-errors (truename *load-pathname*)))) (sys.int::*top-level-form-number* `(:position ,position))) (with-compilation-hooks () (eval (read-from-string (concatenate 'string "(progn " string " )"))))) t) (defimplementation swank-compile-file (input-file output-file load-p external-format &key policy) (with-compilation-hooks () (multiple-value-prog1 (compile-file input-file :output-file output-file :external-format external-format) (when load-p (load output-file))))) (defimplementation find-external-format (coding-system) (if (or (equal coding-system "utf-8") (equal coding-system "utf-8-unix")) :default nil)) ;;;; Debugging ;; Definitely don't allow this. (defimplementation install-debugger-globally (function) (declare (ignore function)) nil) (defvar *current-backtrace*) (defimplementation call-with-debugging-environment (debugger-loop-fn) (let ((*current-backtrace* '())) (let ((prev-fp nil)) (sys.int::map-backtrace (lambda (i fp) (push (list (1- i) fp prev-fp) *current-backtrace*) (setf prev-fp fp)))) (setf *current-backtrace* (reverse *current-backtrace*)) ;; Drop the topmost frame, which is finished call to MAP-BACKTRACE. (pop *current-backtrace*) ;; And the next one for good measure. (pop *current-backtrace*) (funcall debugger-loop-fn))) (defimplementation compute-backtrace (start end) (subseq *current-backtrace* start end)) (defimplementation print-frame (frame stream) (format stream "~S" (sys.int::function-from-frame frame))) (defimplementation frame-source-location (frame-number) (let* ((frame (nth frame-number *current-backtrace*)) (fn (sys.int::function-from-frame frame))) (function-location fn))) (defimplementation frame-locals (frame-number) (loop with frame = (nth frame-number *current-backtrace*) for (name id location repr) in (sys.int::frame-locals frame) collect (list :name name :id id :value (sys.int::read-frame-slot frame location repr)))) (defimplementation frame-var-value (frame-number var-id) (let* ((frame (nth frame-number *current-backtrace*)) (locals (sys.int::frame-locals frame)) (info (nth var-id locals))) (if info (destructuring-bind (name id location repr) info (declare (ignore id)) (values (sys.int::read-frame-slot frame location repr) name)) (error "Invalid variable id ~D for frame number ~D." var-id frame-number)))) ;;;; Definition finding (defun top-level-form-position (pathname tlf) (ignore-errors (with-open-file (s pathname) (loop repeat tlf do (with-standard-io-syntax (let ((*read-suppress* t) (*read-eval* nil)) (read s nil)))) (let ((default (make-pathname :host (pathname-host s)))) (make-location `(:file ,(enough-namestring s default)) `(:position ,(1+ (file-position s)))))))) (defun function-location (function) "Return a location object for FUNCTION." (let* ((info (sys.int::function-debug-info function)) (pathname (sys.int::debug-info-source-pathname info)) (tlf (sys.int::debug-info-source-top-level-form-number info))) (cond ((and (consp tlf) (eql (first tlf) :position)) (let ((default (make-pathname :host (pathname-host pathname)))) (make-location `(:file ,(enough-namestring pathname default)) `(:position ,(second tlf))))) (t (top-level-form-position pathname tlf))))) (defun method-definition-name (name method) `(defmethod ,name ,@(mezzano.clos:method-qualifiers method) ,(mapcar (lambda (x) (typecase x (mezzano.clos:class (mezzano.clos:class-name x)) (mezzano.clos:eql-specializer `(eql ,(mezzano.clos:eql-specializer-object x))) (t x))) (mezzano.clos:method-specializers method)))) (defimplementation find-definitions (name) (let ((result '())) (labels ((frob-fn (dspec fn) (let ((loc (function-location fn))) (when loc (push (list dspec loc) result)))) (try-fn (name) (when (valid-function-name-p name) (when (and (fboundp name) (not (and (symbolp name) (or (special-operator-p name) (macro-function name))))) (let ((fn (fdefinition name))) (cond ((typep fn 'mezzano.clos:standard-generic-function) (dolist (m (mezzano.clos:generic-function-methods fn)) (frob-fn (method-definition-name name m) (mezzano.clos:method-function m)))) (t (frob-fn `(defun ,name) fn))))) (when (compiler-macro-function name) (frob-fn `(define-compiler-macro ,name) (compiler-macro-function name)))))) (try-fn name) (try-fn `(setf name)) (try-fn `(sys.int::cas name)) (when (and (symbolp name) (get name 'sys.int::setf-expander)) (frob-fn `(define-setf-expander ,name) (get name 'sys.int::setf-expander))) (when (and (symbolp name) (macro-function name)) (frob-fn `(defmacro ,name) (macro-function name)))) result)) ;;;; XREF ;;; Simpler variants. (defun find-all-frefs () (let ((frefs (make-array 500 :adjustable t :fill-pointer 0)) (keep-going t)) (loop (when (not keep-going) (return)) (adjust-array frefs (* (array-dimension frefs 0) 2)) (setf keep-going nil (fill-pointer frefs) 0) ;; Walk the wired area looking for FREFs. (sys.int::walk-area :wired (lambda (object address size) (when (sys.int::function-reference-p object) (when (not (vector-push object frefs)) (setf keep-going t)))))) (remove-duplicates (coerce frefs 'list)))) (defimplementation list-callers (function-name) (let ((fref-for-fn (sys.int::function-reference function-name)) (callers '())) (loop for fref in (find-all-frefs) for fn = (sys.int::function-reference-function fref) for name = (sys.int::function-reference-name fref) when fn do (cond ((typep fn 'standard-generic-function) (dolist (m (mezzano.clos:generic-function-methods fn)) (let* ((mf (mezzano.clos:method-function m)) (mf-frefs (get-all-frefs-in-function mf))) (when (member fref-for-fn mf-frefs) (push `((defmethod ,name ,@(mezzano.clos:method-qualifiers m) ,(mapcar #'specializer-name (mezzano.clos:method-specializers m))) ,(function-location mf)) callers))))) ((member fref-for-fn (get-all-frefs-in-function fn)) (push `((defun ,name) ,(function-location fn)) callers)))) callers)) (defun specializer-name (specializer) (if (typep specializer 'standard-class) (mezzano.clos:class-name specializer) specializer)) (defun get-all-frefs-in-function (function) (when (sys.int::funcallable-std-instance-p function) (setf function (sys.int::funcallable-std-instance-function function))) (when (sys.int::closure-p function) (setf function (sys.int::%closure-function function))) (loop for i below (sys.int::function-pool-size function) for entry = (sys.int::function-pool-object function i) when (sys.int::function-reference-p entry) collect entry when (compiled-function-p entry) ; closures append (get-all-frefs-in-function entry))) (defimplementation list-callees (function-name) (let* ((fn (fdefinition function-name)) ;; Grovel around in the function's constant pool looking for ;; function-references. These may be for #', but they're ;; probably going to be for normal calls. ;; TODO: This doesn't work well on interpreted functions or ;; funcallable instances. (callees (remove-duplicates (get-all-frefs-in-function fn)))) (loop for fref in callees for name = (sys.int::function-reference-name fref) for fn = (sys.int::function-reference-function fref) when fn collect `((defun ,name) ,(function-location fn))))) ;;;; Documentation (defimplementation arglist (name) (let ((macro (when (symbolp name) (macro-function name))) (fn (if (functionp name) name (ignore-errors (fdefinition name))))) (cond (macro (get name 'sys.int::macro-lambda-list)) (fn (cond ((typep fn 'mezzano.clos:standard-generic-function) (mezzano.clos:generic-function-lambda-list fn)) (t (function-lambda-list fn)))) (t :not-available)))) (defun function-lambda-list (function) (sys.int::debug-info-lambda-list (sys.int::function-debug-info function))) (defimplementation type-specifier-p (symbol) (cond ((or (get symbol 'sys.int::type-expander) (get symbol 'sys.int::compound-type) (get symbol 'sys.int::type-symbol)) t) (t :not-available))) (defimplementation function-name (function) (sys.int::function-name function)) (defimplementation valid-function-name-p (form) "Is FORM syntactically valid to name a function? If true, FBOUNDP should not signal a type-error for FORM." (flet ((length=2 (list) (and (not (null (cdr list))) (null (cddr list))))) (or (symbolp form) (and (consp form) (length=2 form) (or (eq (first form) 'setf) (eq (first form) 'sys.int::cas)) (symbolp (second form)))))) (defimplementation describe-symbol-for-emacs (symbol) (let ((result '())) (when (boundp symbol) (setf (getf result :variable) nil)) (when (and (fboundp symbol) (not (macro-function symbol))) (setf (getf result :function) (function-docstring symbol))) (when (fboundp `(setf ,symbol)) (setf (getf result :setf) (function-docstring `(setf ,symbol)))) (when (get symbol 'sys.int::setf-expander) (setf (getf result :setf) nil)) (when (special-operator-p symbol) (setf (getf result :special-operator) nil)) (when (macro-function symbol) (setf (getf result :macro) nil)) (when (compiler-macro-function symbol) (setf (getf result :compiler-macro) nil)) (when (type-specifier-p symbol) (setf (getf result :type) nil)) (when (find-class symbol nil) (setf (getf result :class) nil)) result)) (defun function-docstring (function-name) (let* ((definition (fdefinition function-name)) (debug-info (sys.int::function-debug-info definition))) (sys.int::debug-info-docstring debug-info))) ;;;; Multithreading ;; FIXME: This should be a weak table. (defvar *thread-ids-for-emacs* (make-hash-table)) (defvar *next-thread-id-for-emacs* 0) (defvar *thread-id-for-emacs-lock* (mezzano.supervisor:make-mutex "SWANK thread ID table")) (defimplementation spawn (fn &key name) (mezzano.supervisor:make-thread fn :name name)) (defimplementation thread-id (thread) (mezzano.supervisor:with-mutex (*thread-id-for-emacs-lock*) (let ((id (gethash thread *thread-ids-for-emacs*))) (when (null id) (setf id (incf *next-thread-id-for-emacs*) (gethash thread *thread-ids-for-emacs*) id (gethash id *thread-ids-for-emacs*) thread)) id))) (defimplementation find-thread (id) (mezzano.supervisor:with-mutex (*thread-id-for-emacs-lock*) (gethash id *thread-ids-for-emacs*))) (defimplementation thread-name (thread) (mezzano.supervisor:thread-name thread)) (defimplementation thread-status (thread) (format nil "~:(~A~)" (mezzano.supervisor:thread-state thread))) (defimplementation current-thread () (mezzano.supervisor:current-thread)) (defimplementation all-threads () (mezzano.supervisor:all-threads)) (defimplementation thread-alive-p (thread) (not (eql (mezzano.supervisor:thread-state thread) :dead))) (defimplementation interrupt-thread (thread fn) (mezzano.supervisor:establish-thread-foothold thread fn)) (defimplementation kill-thread (thread) ;; Documentation says not to execute unwind-protected sections, but there's ;; no way to do that. ;; And killing threads at arbitrary points without unwinding them is a good ;; way to hose the system. (mezzano.supervisor:terminate-thread thread)) (defvar *mailbox-lock* (mezzano.supervisor:make-mutex "mailbox lock")) (defvar *mailboxes* (list)) (defstruct (mailbox (:conc-name mailbox.)) thread (mutex (mezzano.supervisor:make-mutex)) (queue '() :type list)) (defun mailbox (thread) "Return THREAD's mailbox." ;; Use weak pointers to avoid holding on to dead threads forever. (mezzano.supervisor:with-mutex (*mailbox-lock*) ;; Flush forgotten threads. (setf *mailboxes* (remove-if-not #'sys.int::weak-pointer-value *mailboxes*)) (loop for entry in *mailboxes* do (multiple-value-bind (key value livep) (sys.int::weak-pointer-pair entry) (when (eql key thread) (return value))) finally (let ((mb (make-mailbox :thread thread))) (push (sys.int::make-weak-pointer thread mb) *mailboxes*) (return mb))))) (defimplementation send (thread message) (let* ((mbox (mailbox thread)) (mutex (mailbox.mutex mbox))) (mezzano.supervisor:with-mutex (mutex) (setf (mailbox.queue mbox) (nconc (mailbox.queue mbox) (list message)))))) (defvar *receive-if-sleep-time* 0.02) (defimplementation receive-if (test &optional timeout) (let* ((mbox (mailbox (current-thread))) (mutex (mailbox.mutex mbox))) (assert (or (not timeout) (eq timeout t))) (loop (check-slime-interrupts) (mezzano.supervisor:with-mutex (mutex) (let* ((q (mailbox.queue mbox)) (tail (member-if test q))) (when tail (setf (mailbox.queue mbox) (nconc (ldiff q tail) (cdr tail))) (return (car tail)))) (when (eq timeout t) (return (values nil t)))) (sleep *receive-if-sleep-time*)))) (defvar *registered-threads* (make-hash-table)) (defvar *registered-threads-lock* (mezzano.supervisor:make-mutex "registered threads lock")) (defimplementation register-thread (name thread) (declare (type symbol name)) (mezzano.supervisor:with-mutex (*registered-threads-lock*) (etypecase thread (null (remhash name *registered-threads*)) (mezzano.supervisor:thread (setf (gethash name *registered-threads*) thread)))) nil) (defimplementation find-registered (name) (mezzano.supervisor:with-mutex (*registered-threads-lock*) (values (gethash name *registered-threads*)))) (defimplementation wait-for-input (streams &optional timeout) (loop (let ((ready '())) (dolist (s streams) (when (or (listen s) (and (typep s 'mezzano.network.tcp::tcp-stream) (mezzano.network.tcp::tcp-connection-closed-p s))) (push s ready))) (when ready (return ready)) (when (check-slime-interrupts) (return :interrupt)) (when timeout (return '())) (sleep 1) (when (numberp timeout) (decf timeout 1) (when (not (plusp timeout)) (return '())))))) ;;;; Locks (defstruct recursive-lock mutex (depth 0)) (defimplementation make-lock (&key name) (make-recursive-lock :mutex (mezzano.supervisor:make-mutex name))) (defimplementation call-with-lock-held (lock function) (cond ((mezzano.supervisor:mutex-held-p (recursive-lock-mutex lock)) (unwind-protect (progn (incf (recursive-lock-depth lock)) (funcall function)) (decf (recursive-lock-depth lock)))) (t (mezzano.supervisor:with-mutex ((recursive-lock-mutex lock)) (multiple-value-prog1 (funcall function) (assert (eql (recursive-lock-depth lock) 0))))))) ;;;; Character names (defimplementation character-completion-set (prefix matchp) ;; TODO: Unicode characters too. (loop for names in sys.int::*char-name-alist* append (loop for name in (rest names) when (funcall matchp prefix name) collect name))) ;;;; Inspector (defmethod emacs-inspect ((o function)) (case (sys.int::%object-tag o) (#.sys.int::+object-tag-function+ (label-value-line* (:name (sys.int::function-name o)) (:arglist (arglist o)) (:debug-info (sys.int::function-debug-info o)))) (#.sys.int::+object-tag-closure+ (append (label-value-line :function (sys.int::%closure-function o)) `("Closed over values:" (:newline)) (loop for i below (sys.int::%closure-length o) append (label-value-line i (sys.int::%closure-value o i))))) (t (call-next-method)))) (defmethod emacs-inspect ((o sys.int::weak-pointer)) (label-value-line* (:key (sys.int::weak-pointer-key o)) (:value (sys.int::weak-pointer-value o)))) (defmethod emacs-inspect ((o sys.int::function-reference)) (label-value-line* (:name (sys.int::function-reference-name o)) (:function (sys.int::function-reference-function o)))) (defmethod emacs-inspect ((object structure-object)) (let ((class (class-of object))) `("Class: " (:value ,class) (:newline) ,@(swank::all-slots-for-inspector object)))) (in-package :swank) (defmethod all-slots-for-inspector ((object structure-object)) (let* ((class (class-of object)) (direct-slots (swank-mop:class-direct-slots class)) (effective-slots (swank-mop:class-slots class)) (longest-slot-name-length (loop for slot :in effective-slots maximize (length (symbol-name (swank-mop:slot-definition-name slot))))) (checklist (reinitialize-checklist (ensure-istate-metadata object :checklist (make-checklist (length effective-slots))))) (grouping-kind ;; We box the value so we can re-set it. (ensure-istate-metadata object :grouping-kind (box *inspector-slots-default-grouping*))) (sort-order (ensure-istate-metadata object :sort-order (box *inspector-slots-default-order*))) (sort-predicate (ecase (ref sort-order) (:alphabetically #'string<) (:unsorted (constantly nil)))) (sorted-slots (sort (copy-seq effective-slots) sort-predicate :key #'swank-mop:slot-definition-name)) (effective-slots (ecase (ref grouping-kind) (:all sorted-slots) (:inheritance (stable-sort-by-inheritance sorted-slots class sort-predicate))))) `("--------------------" (:newline) " Group slots by inheritance " (:action ,(ecase (ref grouping-kind) (:all "[ ]") (:inheritance "[X]")) ,(lambda () ;; We have to do this as the order of slots will ;; be sorted differently. (fill (checklist.buttons checklist) nil) (setf (ref grouping-kind) (ecase (ref grouping-kind) (:all :inheritance) (:inheritance :all)))) :refreshp t) (:newline) " Sort slots alphabetically " (:action ,(ecase (ref sort-order) (:unsorted "[ ]") (:alphabetically "[X]")) ,(lambda () (fill (checklist.buttons checklist) nil) (setf (ref sort-order) (ecase (ref sort-order) (:unsorted :alphabetically) (:alphabetically :unsorted)))) :refreshp t) (:newline) ,@ (case (ref grouping-kind) (:all `((:newline) "All Slots:" (:newline) ,@(make-slot-listing checklist object class effective-slots direct-slots longest-slot-name-length))) (:inheritance (list-all-slots-by-inheritance checklist object class effective-slots direct-slots longest-slot-name-length))) (:newline) (:action "[set value]" ,(lambda () (do-checklist (idx checklist) (query-and-set-slot class object (nth idx effective-slots)))) :refreshp t) " " (:action "[make unbound]" ,(lambda () (do-checklist (idx checklist) (swank-mop:slot-makunbound-using-class class object (nth idx effective-slots)))) :refreshp t) (:newline))))
null
https://raw.githubusercontent.com/code-iai/ros_emacs_utils/ab5cea686d582020c75881583beca7402fa9e7b8/slime_wrapper/slime/swank/mezzano.lisp
lisp
-*- indent-tabs-mode: nil -*- This code has been placed in the Public Domain. All warranties are disclaimed. swank-mop TCP server Drop connections when they can't be handled. Poke standard-input every now and then to keep the console alive. Unix signals ???? Compilation Debugging Definitely don't allow this. Drop the topmost frame, which is finished call to MAP-BACKTRACE. And the next one for good measure. Definition finding XREF Simpler variants. Walk the wired area looking for FREFs. closures Grovel around in the function's constant pool looking for function-references. These may be for #', but they're probably going to be for normal calls. TODO: This doesn't work well on interpreted functions or funcallable instances. Documentation Multithreading FIXME: This should be a weak table. Documentation says not to execute unwind-protected sections, but there's no way to do that. And killing threads at arbitrary points without unwinding them is a good way to hose the system. Use weak pointers to avoid holding on to dead threads forever. Flush forgotten threads. Locks Character names TODO: Unicode characters too. Inspector We box the value so we can re-set it. We have to do this as the order of slots will be sorted differently.
swank-mezzano.lisp --- SLIME backend for Mezzano Administrivia (defpackage swank/mezzano (:use cl swank/backend)) (in-package swank/mezzano) (import-swank-mop-symbols :mezzano.clos '(:class-default-initargs :class-direct-default-initargs :specializer-direct-methods :generic-function-declarations)) (defun swank-mop:specializer-direct-methods (obj) (declare (ignore obj)) '()) (defun swank-mop:generic-function-declarations (gf) (declare (ignore gf)) '()) (defimplementation gray-package-name () "MEZZANO.GRAY") (defclass listen-socket () ((%host :initarg :host) (%port :initarg :port) (%connection-fifo :initarg :connections) (%callback :initarg :callback))) (defimplementation create-socket (host port &key backlog) (let* ((connections (mezzano.supervisor:make-fifo (or backlog 10))) (sock (make-instance 'listen-socket :host host :port port :connections connections :callback (lambda (conn) (do-connection conn connections)))) (listen-fn (slot-value sock '%callback))) (when (find port mezzano.network.tcp::*server-alist* :key #'first) (error "Server already listening on port ~D" port)) (push (list port listen-fn) mezzano.network.tcp::*server-alist*) sock)) (defun do-connection (conn connections) (when (not (mezzano.supervisor:fifo-push (make-instance 'mezzano.network.tcp::tcp-stream :connection conn) connections nil)) (close conn))) (defimplementation local-port (socket) (slot-value socket '%port)) (defimplementation close-socket (socket) (setf mezzano.network.tcp::*server-alist* (remove (slot-value socket '%callback) mezzano.network.tcp::*server-alist* :key #'second)) (let ((fifo (slot-value socket '%connection-fifo))) (loop (let ((conn (mezzano.supervisor:fifo-pop fifo nil))) (when (not conn) (return)) (close conn)))) (setf (slot-value socket '%connection-fifo) nil)) (defimplementation accept-connection (socket &key external-format buffering timeout) (declare (ignore external-format buffering timeout)) (loop (let ((value (mezzano.supervisor:fifo-pop (slot-value socket '%connection-fifo) nil))) (when value (return value))) (listen) (sleep 0.05))) (defimplementation preferred-communication-style () :spawn) (defimplementation getpid () 0) (defun signal-compiler-condition (condition severity) (signal 'compiler-condition :original-condition condition :severity severity :message (format nil "~A" condition) :location nil)) (defimplementation call-with-compilation-hooks (func) (handler-bind ((error (lambda (c) (signal-compiler-condition c :error))) (warning (lambda (c) (signal-compiler-condition c :warning))) (style-warning (lambda (c) (signal-compiler-condition c :style-warning)))) (funcall func))) (defimplementation swank-compile-string (string &key buffer position filename policy) (declare (ignore buffer policy)) (let* ((*load-pathname* (ignore-errors (pathname filename))) (*load-truename* (when *load-pathname* (ignore-errors (truename *load-pathname*)))) (sys.int::*top-level-form-number* `(:position ,position))) (with-compilation-hooks () (eval (read-from-string (concatenate 'string "(progn " string " )"))))) t) (defimplementation swank-compile-file (input-file output-file load-p external-format &key policy) (with-compilation-hooks () (multiple-value-prog1 (compile-file input-file :output-file output-file :external-format external-format) (when load-p (load output-file))))) (defimplementation find-external-format (coding-system) (if (or (equal coding-system "utf-8") (equal coding-system "utf-8-unix")) :default nil)) (defimplementation install-debugger-globally (function) (declare (ignore function)) nil) (defvar *current-backtrace*) (defimplementation call-with-debugging-environment (debugger-loop-fn) (let ((*current-backtrace* '())) (let ((prev-fp nil)) (sys.int::map-backtrace (lambda (i fp) (push (list (1- i) fp prev-fp) *current-backtrace*) (setf prev-fp fp)))) (setf *current-backtrace* (reverse *current-backtrace*)) (pop *current-backtrace*) (pop *current-backtrace*) (funcall debugger-loop-fn))) (defimplementation compute-backtrace (start end) (subseq *current-backtrace* start end)) (defimplementation print-frame (frame stream) (format stream "~S" (sys.int::function-from-frame frame))) (defimplementation frame-source-location (frame-number) (let* ((frame (nth frame-number *current-backtrace*)) (fn (sys.int::function-from-frame frame))) (function-location fn))) (defimplementation frame-locals (frame-number) (loop with frame = (nth frame-number *current-backtrace*) for (name id location repr) in (sys.int::frame-locals frame) collect (list :name name :id id :value (sys.int::read-frame-slot frame location repr)))) (defimplementation frame-var-value (frame-number var-id) (let* ((frame (nth frame-number *current-backtrace*)) (locals (sys.int::frame-locals frame)) (info (nth var-id locals))) (if info (destructuring-bind (name id location repr) info (declare (ignore id)) (values (sys.int::read-frame-slot frame location repr) name)) (error "Invalid variable id ~D for frame number ~D." var-id frame-number)))) (defun top-level-form-position (pathname tlf) (ignore-errors (with-open-file (s pathname) (loop repeat tlf do (with-standard-io-syntax (let ((*read-suppress* t) (*read-eval* nil)) (read s nil)))) (let ((default (make-pathname :host (pathname-host s)))) (make-location `(:file ,(enough-namestring s default)) `(:position ,(1+ (file-position s)))))))) (defun function-location (function) "Return a location object for FUNCTION." (let* ((info (sys.int::function-debug-info function)) (pathname (sys.int::debug-info-source-pathname info)) (tlf (sys.int::debug-info-source-top-level-form-number info))) (cond ((and (consp tlf) (eql (first tlf) :position)) (let ((default (make-pathname :host (pathname-host pathname)))) (make-location `(:file ,(enough-namestring pathname default)) `(:position ,(second tlf))))) (t (top-level-form-position pathname tlf))))) (defun method-definition-name (name method) `(defmethod ,name ,@(mezzano.clos:method-qualifiers method) ,(mapcar (lambda (x) (typecase x (mezzano.clos:class (mezzano.clos:class-name x)) (mezzano.clos:eql-specializer `(eql ,(mezzano.clos:eql-specializer-object x))) (t x))) (mezzano.clos:method-specializers method)))) (defimplementation find-definitions (name) (let ((result '())) (labels ((frob-fn (dspec fn) (let ((loc (function-location fn))) (when loc (push (list dspec loc) result)))) (try-fn (name) (when (valid-function-name-p name) (when (and (fboundp name) (not (and (symbolp name) (or (special-operator-p name) (macro-function name))))) (let ((fn (fdefinition name))) (cond ((typep fn 'mezzano.clos:standard-generic-function) (dolist (m (mezzano.clos:generic-function-methods fn)) (frob-fn (method-definition-name name m) (mezzano.clos:method-function m)))) (t (frob-fn `(defun ,name) fn))))) (when (compiler-macro-function name) (frob-fn `(define-compiler-macro ,name) (compiler-macro-function name)))))) (try-fn name) (try-fn `(setf name)) (try-fn `(sys.int::cas name)) (when (and (symbolp name) (get name 'sys.int::setf-expander)) (frob-fn `(define-setf-expander ,name) (get name 'sys.int::setf-expander))) (when (and (symbolp name) (macro-function name)) (frob-fn `(defmacro ,name) (macro-function name)))) result)) (defun find-all-frefs () (let ((frefs (make-array 500 :adjustable t :fill-pointer 0)) (keep-going t)) (loop (when (not keep-going) (return)) (adjust-array frefs (* (array-dimension frefs 0) 2)) (setf keep-going nil (fill-pointer frefs) 0) (sys.int::walk-area :wired (lambda (object address size) (when (sys.int::function-reference-p object) (when (not (vector-push object frefs)) (setf keep-going t)))))) (remove-duplicates (coerce frefs 'list)))) (defimplementation list-callers (function-name) (let ((fref-for-fn (sys.int::function-reference function-name)) (callers '())) (loop for fref in (find-all-frefs) for fn = (sys.int::function-reference-function fref) for name = (sys.int::function-reference-name fref) when fn do (cond ((typep fn 'standard-generic-function) (dolist (m (mezzano.clos:generic-function-methods fn)) (let* ((mf (mezzano.clos:method-function m)) (mf-frefs (get-all-frefs-in-function mf))) (when (member fref-for-fn mf-frefs) (push `((defmethod ,name ,@(mezzano.clos:method-qualifiers m) ,(mapcar #'specializer-name (mezzano.clos:method-specializers m))) ,(function-location mf)) callers))))) ((member fref-for-fn (get-all-frefs-in-function fn)) (push `((defun ,name) ,(function-location fn)) callers)))) callers)) (defun specializer-name (specializer) (if (typep specializer 'standard-class) (mezzano.clos:class-name specializer) specializer)) (defun get-all-frefs-in-function (function) (when (sys.int::funcallable-std-instance-p function) (setf function (sys.int::funcallable-std-instance-function function))) (when (sys.int::closure-p function) (setf function (sys.int::%closure-function function))) (loop for i below (sys.int::function-pool-size function) for entry = (sys.int::function-pool-object function i) when (sys.int::function-reference-p entry) collect entry append (get-all-frefs-in-function entry))) (defimplementation list-callees (function-name) (let* ((fn (fdefinition function-name)) (callees (remove-duplicates (get-all-frefs-in-function fn)))) (loop for fref in callees for name = (sys.int::function-reference-name fref) for fn = (sys.int::function-reference-function fref) when fn collect `((defun ,name) ,(function-location fn))))) (defimplementation arglist (name) (let ((macro (when (symbolp name) (macro-function name))) (fn (if (functionp name) name (ignore-errors (fdefinition name))))) (cond (macro (get name 'sys.int::macro-lambda-list)) (fn (cond ((typep fn 'mezzano.clos:standard-generic-function) (mezzano.clos:generic-function-lambda-list fn)) (t (function-lambda-list fn)))) (t :not-available)))) (defun function-lambda-list (function) (sys.int::debug-info-lambda-list (sys.int::function-debug-info function))) (defimplementation type-specifier-p (symbol) (cond ((or (get symbol 'sys.int::type-expander) (get symbol 'sys.int::compound-type) (get symbol 'sys.int::type-symbol)) t) (t :not-available))) (defimplementation function-name (function) (sys.int::function-name function)) (defimplementation valid-function-name-p (form) "Is FORM syntactically valid to name a function? If true, FBOUNDP should not signal a type-error for FORM." (flet ((length=2 (list) (and (not (null (cdr list))) (null (cddr list))))) (or (symbolp form) (and (consp form) (length=2 form) (or (eq (first form) 'setf) (eq (first form) 'sys.int::cas)) (symbolp (second form)))))) (defimplementation describe-symbol-for-emacs (symbol) (let ((result '())) (when (boundp symbol) (setf (getf result :variable) nil)) (when (and (fboundp symbol) (not (macro-function symbol))) (setf (getf result :function) (function-docstring symbol))) (when (fboundp `(setf ,symbol)) (setf (getf result :setf) (function-docstring `(setf ,symbol)))) (when (get symbol 'sys.int::setf-expander) (setf (getf result :setf) nil)) (when (special-operator-p symbol) (setf (getf result :special-operator) nil)) (when (macro-function symbol) (setf (getf result :macro) nil)) (when (compiler-macro-function symbol) (setf (getf result :compiler-macro) nil)) (when (type-specifier-p symbol) (setf (getf result :type) nil)) (when (find-class symbol nil) (setf (getf result :class) nil)) result)) (defun function-docstring (function-name) (let* ((definition (fdefinition function-name)) (debug-info (sys.int::function-debug-info definition))) (sys.int::debug-info-docstring debug-info))) (defvar *thread-ids-for-emacs* (make-hash-table)) (defvar *next-thread-id-for-emacs* 0) (defvar *thread-id-for-emacs-lock* (mezzano.supervisor:make-mutex "SWANK thread ID table")) (defimplementation spawn (fn &key name) (mezzano.supervisor:make-thread fn :name name)) (defimplementation thread-id (thread) (mezzano.supervisor:with-mutex (*thread-id-for-emacs-lock*) (let ((id (gethash thread *thread-ids-for-emacs*))) (when (null id) (setf id (incf *next-thread-id-for-emacs*) (gethash thread *thread-ids-for-emacs*) id (gethash id *thread-ids-for-emacs*) thread)) id))) (defimplementation find-thread (id) (mezzano.supervisor:with-mutex (*thread-id-for-emacs-lock*) (gethash id *thread-ids-for-emacs*))) (defimplementation thread-name (thread) (mezzano.supervisor:thread-name thread)) (defimplementation thread-status (thread) (format nil "~:(~A~)" (mezzano.supervisor:thread-state thread))) (defimplementation current-thread () (mezzano.supervisor:current-thread)) (defimplementation all-threads () (mezzano.supervisor:all-threads)) (defimplementation thread-alive-p (thread) (not (eql (mezzano.supervisor:thread-state thread) :dead))) (defimplementation interrupt-thread (thread fn) (mezzano.supervisor:establish-thread-foothold thread fn)) (defimplementation kill-thread (thread) (mezzano.supervisor:terminate-thread thread)) (defvar *mailbox-lock* (mezzano.supervisor:make-mutex "mailbox lock")) (defvar *mailboxes* (list)) (defstruct (mailbox (:conc-name mailbox.)) thread (mutex (mezzano.supervisor:make-mutex)) (queue '() :type list)) (defun mailbox (thread) "Return THREAD's mailbox." (mezzano.supervisor:with-mutex (*mailbox-lock*) (setf *mailboxes* (remove-if-not #'sys.int::weak-pointer-value *mailboxes*)) (loop for entry in *mailboxes* do (multiple-value-bind (key value livep) (sys.int::weak-pointer-pair entry) (when (eql key thread) (return value))) finally (let ((mb (make-mailbox :thread thread))) (push (sys.int::make-weak-pointer thread mb) *mailboxes*) (return mb))))) (defimplementation send (thread message) (let* ((mbox (mailbox thread)) (mutex (mailbox.mutex mbox))) (mezzano.supervisor:with-mutex (mutex) (setf (mailbox.queue mbox) (nconc (mailbox.queue mbox) (list message)))))) (defvar *receive-if-sleep-time* 0.02) (defimplementation receive-if (test &optional timeout) (let* ((mbox (mailbox (current-thread))) (mutex (mailbox.mutex mbox))) (assert (or (not timeout) (eq timeout t))) (loop (check-slime-interrupts) (mezzano.supervisor:with-mutex (mutex) (let* ((q (mailbox.queue mbox)) (tail (member-if test q))) (when tail (setf (mailbox.queue mbox) (nconc (ldiff q tail) (cdr tail))) (return (car tail)))) (when (eq timeout t) (return (values nil t)))) (sleep *receive-if-sleep-time*)))) (defvar *registered-threads* (make-hash-table)) (defvar *registered-threads-lock* (mezzano.supervisor:make-mutex "registered threads lock")) (defimplementation register-thread (name thread) (declare (type symbol name)) (mezzano.supervisor:with-mutex (*registered-threads-lock*) (etypecase thread (null (remhash name *registered-threads*)) (mezzano.supervisor:thread (setf (gethash name *registered-threads*) thread)))) nil) (defimplementation find-registered (name) (mezzano.supervisor:with-mutex (*registered-threads-lock*) (values (gethash name *registered-threads*)))) (defimplementation wait-for-input (streams &optional timeout) (loop (let ((ready '())) (dolist (s streams) (when (or (listen s) (and (typep s 'mezzano.network.tcp::tcp-stream) (mezzano.network.tcp::tcp-connection-closed-p s))) (push s ready))) (when ready (return ready)) (when (check-slime-interrupts) (return :interrupt)) (when timeout (return '())) (sleep 1) (when (numberp timeout) (decf timeout 1) (when (not (plusp timeout)) (return '())))))) (defstruct recursive-lock mutex (depth 0)) (defimplementation make-lock (&key name) (make-recursive-lock :mutex (mezzano.supervisor:make-mutex name))) (defimplementation call-with-lock-held (lock function) (cond ((mezzano.supervisor:mutex-held-p (recursive-lock-mutex lock)) (unwind-protect (progn (incf (recursive-lock-depth lock)) (funcall function)) (decf (recursive-lock-depth lock)))) (t (mezzano.supervisor:with-mutex ((recursive-lock-mutex lock)) (multiple-value-prog1 (funcall function) (assert (eql (recursive-lock-depth lock) 0))))))) (defimplementation character-completion-set (prefix matchp) (loop for names in sys.int::*char-name-alist* append (loop for name in (rest names) when (funcall matchp prefix name) collect name))) (defmethod emacs-inspect ((o function)) (case (sys.int::%object-tag o) (#.sys.int::+object-tag-function+ (label-value-line* (:name (sys.int::function-name o)) (:arglist (arglist o)) (:debug-info (sys.int::function-debug-info o)))) (#.sys.int::+object-tag-closure+ (append (label-value-line :function (sys.int::%closure-function o)) `("Closed over values:" (:newline)) (loop for i below (sys.int::%closure-length o) append (label-value-line i (sys.int::%closure-value o i))))) (t (call-next-method)))) (defmethod emacs-inspect ((o sys.int::weak-pointer)) (label-value-line* (:key (sys.int::weak-pointer-key o)) (:value (sys.int::weak-pointer-value o)))) (defmethod emacs-inspect ((o sys.int::function-reference)) (label-value-line* (:name (sys.int::function-reference-name o)) (:function (sys.int::function-reference-function o)))) (defmethod emacs-inspect ((object structure-object)) (let ((class (class-of object))) `("Class: " (:value ,class) (:newline) ,@(swank::all-slots-for-inspector object)))) (in-package :swank) (defmethod all-slots-for-inspector ((object structure-object)) (let* ((class (class-of object)) (direct-slots (swank-mop:class-direct-slots class)) (effective-slots (swank-mop:class-slots class)) (longest-slot-name-length (loop for slot :in effective-slots maximize (length (symbol-name (swank-mop:slot-definition-name slot))))) (checklist (reinitialize-checklist (ensure-istate-metadata object :checklist (make-checklist (length effective-slots))))) (grouping-kind (ensure-istate-metadata object :grouping-kind (box *inspector-slots-default-grouping*))) (sort-order (ensure-istate-metadata object :sort-order (box *inspector-slots-default-order*))) (sort-predicate (ecase (ref sort-order) (:alphabetically #'string<) (:unsorted (constantly nil)))) (sorted-slots (sort (copy-seq effective-slots) sort-predicate :key #'swank-mop:slot-definition-name)) (effective-slots (ecase (ref grouping-kind) (:all sorted-slots) (:inheritance (stable-sort-by-inheritance sorted-slots class sort-predicate))))) `("--------------------" (:newline) " Group slots by inheritance " (:action ,(ecase (ref grouping-kind) (:all "[ ]") (:inheritance "[X]")) ,(lambda () (fill (checklist.buttons checklist) nil) (setf (ref grouping-kind) (ecase (ref grouping-kind) (:all :inheritance) (:inheritance :all)))) :refreshp t) (:newline) " Sort slots alphabetically " (:action ,(ecase (ref sort-order) (:unsorted "[ ]") (:alphabetically "[X]")) ,(lambda () (fill (checklist.buttons checklist) nil) (setf (ref sort-order) (ecase (ref sort-order) (:unsorted :alphabetically) (:alphabetically :unsorted)))) :refreshp t) (:newline) ,@ (case (ref grouping-kind) (:all `((:newline) "All Slots:" (:newline) ,@(make-slot-listing checklist object class effective-slots direct-slots longest-slot-name-length))) (:inheritance (list-all-slots-by-inheritance checklist object class effective-slots direct-slots longest-slot-name-length))) (:newline) (:action "[set value]" ,(lambda () (do-checklist (idx checklist) (query-and-set-slot class object (nth idx effective-slots)))) :refreshp t) " " (:action "[make unbound]" ,(lambda () (do-checklist (idx checklist) (swank-mop:slot-makunbound-using-class class object (nth idx effective-slots)))) :refreshp t) (:newline))))
0058789d4032363a24c843122bf1d010b517f53d7e57ca0fc4984b131ef65f01
LPCIC/matita
content.mli
Copyright ( C ) 2000 , HELM Team . * * This file is part of HELM , an Hypertextual , Electronic * Library of Mathematics , developed at the Computer Science * Department , University of Bologna , Italy . * * is free software ; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation ; either version 2 * of the License , or ( at your option ) any later version . * * 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 HELM ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , * MA 02111 - 1307 , USA . * * For details , see the HELM World - Wide - Web page , * /. * * This file is part of HELM, an Hypertextual, Electronic * Library of Mathematics, developed at the Computer Science * Department, University of Bologna, Italy. * * HELM is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * HELM 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 HELM; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. * * For details, see the HELM World-Wide-Web page, * /. *) type id = string;; type joint_recursion_kind = [ `Recursive of int list (* decreasing arguments *) | `CoRecursive | `Inductive of int (* paramsno *) | `CoInductive of int (* paramsno *) ] ;; type var_or_const = Var | Const;; type 'term declaration = { dec_name : string option; dec_id : id ; dec_inductive : bool; dec_aref : string; dec_type : 'term } ;; type 'term definition = { def_name : string option; def_id : id ; def_aref : string ; def_term : 'term ; def_type : 'term } ;; type 'term inductive = { inductive_id : id ; inductive_name : string; inductive_kind : bool; inductive_type : 'term; inductive_constructors : 'term declaration list } ;; type 'term decl_context_element = [ `Declaration of 'term declaration | `Hypothesis of 'term declaration ] ;; type ('term,'proof) def_context_element = [ `Proof of 'proof | `Definition of 'term definition ] ;; type ('term,'proof) in_joint_context_element = [ `Inductive of 'term inductive | 'term decl_context_element | ('term,'proof) def_context_element ] ;; type ('term,'proof) joint = { joint_id : id ; joint_kind : joint_recursion_kind ; joint_defs : ('term,'proof) in_joint_context_element list } ;; type ('term,'proof) joint_context_element = [ `Joint of ('term,'proof) joint ] ;; type 'term proof = { proof_name : string option; proof_id : id ; proof_context : 'term in_proof_context_element list ; proof_apply_context: 'term proof list; proof_conclude : 'term conclude_item } and 'term in_proof_context_element = [ 'term decl_context_element | ('term,'term proof) def_context_element | ('term,'term proof) joint_context_element ] and 'term conclude_item = { conclude_id : id; conclude_aref : string; conclude_method : string; conclude_args : ('term arg) list ; conclude_conclusion : 'term option } and 'term arg = Aux of string | Premise of premise | Lemma of lemma | Term of bool * 'term (* inferrable, term *) | ArgProof of 'term proof | ArgMethod of string (* ???? *) and premise = { premise_id: id; premise_xref : string ; premise_binder : string option; premise_n : int option; } and lemma = { lemma_id: id; lemma_name : string; lemma_uri: string } ;; type 'term conjecture = id * int * 'term context * 'term and 'term context = 'term hypothesis list and 'term hypothesis = ['term decl_context_element | ('term,'term proof) def_context_element ] option ;; type 'term in_object_context_element = [ `Decl of var_or_const * 'term decl_context_element | `Def of var_or_const * 'term * ('term,'term proof) def_context_element | ('term,'term proof) joint_context_element ] ;; type 'term cobj = id * (* id *) 'term conjecture list option * (* optional metasenv *) 'term in_object_context_element (* actual object *) ;;
null
https://raw.githubusercontent.com/LPCIC/matita/794ed25e6e608b2136ce7fa2963bca4115c7e175/matita/components/content/content.mli
ocaml
decreasing arguments paramsno paramsno inferrable, term ???? id optional metasenv actual object
Copyright ( C ) 2000 , HELM Team . * * This file is part of HELM , an Hypertextual , Electronic * Library of Mathematics , developed at the Computer Science * Department , University of Bologna , Italy . * * is free software ; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation ; either version 2 * of the License , or ( at your option ) any later version . * * 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 HELM ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , * MA 02111 - 1307 , USA . * * For details , see the HELM World - Wide - Web page , * /. * * This file is part of HELM, an Hypertextual, Electronic * Library of Mathematics, developed at the Computer Science * Department, University of Bologna, Italy. * * HELM is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * HELM 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 HELM; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. * * For details, see the HELM World-Wide-Web page, * /. *) type id = string;; type joint_recursion_kind = | `CoRecursive ] ;; type var_or_const = Var | Const;; type 'term declaration = { dec_name : string option; dec_id : id ; dec_inductive : bool; dec_aref : string; dec_type : 'term } ;; type 'term definition = { def_name : string option; def_id : id ; def_aref : string ; def_term : 'term ; def_type : 'term } ;; type 'term inductive = { inductive_id : id ; inductive_name : string; inductive_kind : bool; inductive_type : 'term; inductive_constructors : 'term declaration list } ;; type 'term decl_context_element = [ `Declaration of 'term declaration | `Hypothesis of 'term declaration ] ;; type ('term,'proof) def_context_element = [ `Proof of 'proof | `Definition of 'term definition ] ;; type ('term,'proof) in_joint_context_element = [ `Inductive of 'term inductive | 'term decl_context_element | ('term,'proof) def_context_element ] ;; type ('term,'proof) joint = { joint_id : id ; joint_kind : joint_recursion_kind ; joint_defs : ('term,'proof) in_joint_context_element list } ;; type ('term,'proof) joint_context_element = [ `Joint of ('term,'proof) joint ] ;; type 'term proof = { proof_name : string option; proof_id : id ; proof_context : 'term in_proof_context_element list ; proof_apply_context: 'term proof list; proof_conclude : 'term conclude_item } and 'term in_proof_context_element = [ 'term decl_context_element | ('term,'term proof) def_context_element | ('term,'term proof) joint_context_element ] and 'term conclude_item = { conclude_id : id; conclude_aref : string; conclude_method : string; conclude_args : ('term arg) list ; conclude_conclusion : 'term option } and 'term arg = Aux of string | Premise of premise | Lemma of lemma | ArgProof of 'term proof and premise = { premise_id: id; premise_xref : string ; premise_binder : string option; premise_n : int option; } and lemma = { lemma_id: id; lemma_name : string; lemma_uri: string } ;; type 'term conjecture = id * int * 'term context * 'term and 'term context = 'term hypothesis list and 'term hypothesis = ['term decl_context_element | ('term,'term proof) def_context_element ] option ;; type 'term in_object_context_element = [ `Decl of var_or_const * 'term decl_context_element | `Def of var_or_const * 'term * ('term,'term proof) def_context_element | ('term,'term proof) joint_context_element ] ;; type 'term cobj = ;;
b809c0b17f29f4c368b23878612f542402ed1faca5deb4083442bab394234cfa
ghc/nofib
Match.hs
----------------------------------------------------------------------------- MATCHING This module provides a ` match ' function which implements the famous unification algorithm . It takes a pair of ` patterns ' , ie structures with variables in them , matches them against each other , and extracts information about the values which variables must have in order for the match to be successful . For example , if ` X has stripes ' is matched against ` Y has Z ' then the match is successful , and the information X = Y and Z = stripes is gleaned . The information about variables is stored using the ` Environment ' type ; a table which maps variable names to phrases . The exports from this module are the ` Environment ' type and the ` match ' function . ----------------------------------------------------------------------------- MATCHING This module provides a `match' function which implements the famous unification algorithm. It takes a pair of `patterns', ie structures with variables in them, matches them against each other, and extracts information about the values which variables must have in order for the match to be successful. For example, if `X has stripes' is matched against `Y has Z' then the match is successful, and the information X=Y and Z=stripes is gleaned. The information about variables is stored using the `Environment' type; a table which maps variable names to phrases. The exports from this module are the `Environment' type and the `match' function. ------------------------------------------------------------------------------} module Match where import Result import Table import Knowledge The ` Environment ' type stores information about variables . The ` subst ' -- function is used whenever a phrase contains variables about which -- information may be known. The variables in the phrase are (recursively) -- substituted by their values in the given environment. type Environment = Table String Phrase subst env (Term x ps) = Term x [subst env p | p<-ps] subst env (Var x) = if fails lookup then (Var x) else subst env (answer lookup) where lookup = find env x -- The `match' function substitutes any known information about the variables -- in its argument patterns before comparing them with `compear'. The -- `matchList' function deals with a list of pairs of patterns which need to be -- matched. The information gleaned from each pair is used in matching the -- next, and the final result contains all the information. match env p1 p2 = compear env (subst env p1) (subst env p2) matchList env [] = success env matchList env ((p1,p2):pairs) = if fails res then res else matchList (answer res) pairs where res = match env p1 p2 The ` compear ' function is the heart of the algorithm . It compares two -- phrases and updates the given environment accordingly. For normal terms, it -- compares the joining words. If these are equal, then it compares corresponding pairs of subphrases . If one or other of the phrases is a -- variable, then it makes a suitable entry in the environment. compear env (Term x1 ps1) (Term x2 ps2) | x1 == x2 = matchList env (zip ps1 ps2) | otherwise = failure "no match" compear env (Var x) (Var y) | x /= y = success (update env x (Var y)) | otherwise = success env compear env (Var x) p | not (occurs (Var x) p) = success (update env x p) | otherwise = failure "occurs check failed" compear env p (Var x) = compear env (Var x) p -- The `occurs' check makes sure that a variable does not itself occur in the -- phrase which it is being set equal to. For example, if X were being set -- equal to `the animal eats X', then there would be no solution for X, -- indicating some sort of logical error. occurs v (Term x ps) = or [occurs v p | p<-ps] occurs (Var y) (Var x) = y == x occurs p (Var x) = False
null
https://raw.githubusercontent.com/ghc/nofib/f34b90b5a6ce46284693119a06d1133908b11856/spectral/expert/Match.hs
haskell
--------------------------------------------------------------------------- --------------------------------------------------------------------------- ----------------------------------------------------------------------------} function is used whenever a phrase contains variables about which information may be known. The variables in the phrase are (recursively) substituted by their values in the given environment. The `match' function substitutes any known information about the variables in its argument patterns before comparing them with `compear'. The `matchList' function deals with a list of pairs of patterns which need to be matched. The information gleaned from each pair is used in matching the next, and the final result contains all the information. phrases and updates the given environment accordingly. For normal terms, it compares the joining words. If these are equal, then it compares variable, then it makes a suitable entry in the environment. The `occurs' check makes sure that a variable does not itself occur in the phrase which it is being set equal to. For example, if X were being set equal to `the animal eats X', then there would be no solution for X, indicating some sort of logical error.
MATCHING This module provides a ` match ' function which implements the famous unification algorithm . It takes a pair of ` patterns ' , ie structures with variables in them , matches them against each other , and extracts information about the values which variables must have in order for the match to be successful . For example , if ` X has stripes ' is matched against ` Y has Z ' then the match is successful , and the information X = Y and Z = stripes is gleaned . The information about variables is stored using the ` Environment ' type ; a table which maps variable names to phrases . The exports from this module are the ` Environment ' type and the ` match ' function . MATCHING This module provides a `match' function which implements the famous unification algorithm. It takes a pair of `patterns', ie structures with variables in them, matches them against each other, and extracts information about the values which variables must have in order for the match to be successful. For example, if `X has stripes' is matched against `Y has Z' then the match is successful, and the information X=Y and Z=stripes is gleaned. The information about variables is stored using the `Environment' type; a table which maps variable names to phrases. The exports from this module are the `Environment' type and the `match' function. module Match where import Result import Table import Knowledge The ` Environment ' type stores information about variables . The ` subst ' type Environment = Table String Phrase subst env (Term x ps) = Term x [subst env p | p<-ps] subst env (Var x) = if fails lookup then (Var x) else subst env (answer lookup) where lookup = find env x match env p1 p2 = compear env (subst env p1) (subst env p2) matchList env [] = success env matchList env ((p1,p2):pairs) = if fails res then res else matchList (answer res) pairs where res = match env p1 p2 The ` compear ' function is the heart of the algorithm . It compares two corresponding pairs of subphrases . If one or other of the phrases is a compear env (Term x1 ps1) (Term x2 ps2) | x1 == x2 = matchList env (zip ps1 ps2) | otherwise = failure "no match" compear env (Var x) (Var y) | x /= y = success (update env x (Var y)) | otherwise = success env compear env (Var x) p | not (occurs (Var x) p) = success (update env x p) | otherwise = failure "occurs check failed" compear env p (Var x) = compear env (Var x) p occurs v (Term x ps) = or [occurs v p | p<-ps] occurs (Var y) (Var x) = y == x occurs p (Var x) = False
8c20d7c2e8daf7927f4d6c3c6550d6b0069ee7f16f8934d319e8066af6e7914b
hoplon/demos
contacts.clj
(ns app.contacts (:require [app.handler :as handler])) (def app handler/routes) (def my-contacts (atom #{{:first "Ben" :last "Bitdiddle" :email ""} {:first "Alyssa" :middle-initial "P" :last "Hacker" :email ""} {:first "Eva" :middle "Lu" :last "Ator" :email ""} {:first "Louis" :last "Reasoner" :email ""} {:first "Cy" :middle-initial "D" :last "Effect" :email ""} {:first "Lem" :middle-initial "E" :last "Tweakit" :email ""}})) (defmethod handler/event-msg-handler :contacts/get-contacts [{:as ev-msg :keys [event id ?data ring-req ?reply-fn send-fn]}] (handler/chsk-send! (:client-id ev-msg) [(:resp-id ?data) @my-contacts])) (defmethod handler/event-msg-handler :contacts/delete [{:as ev-msg :keys [event id ?data ring-req ?reply-fn send-fn]}] (let [contact (:contact ?data)] (swap! my-contacts disj contact) (handler/broadcast :contacts/deleted contact))) (defmethod handler/event-msg-handler :contacts/add [{:as ev-msg :keys [event id ?data ring-req ?reply-fn send-fn]}] (let [contact (:contact ?data)] (swap! my-contacts conj contact) (handler/broadcast :contacts/added contact)))
null
https://raw.githubusercontent.com/hoplon/demos/50d613892db0624a4f0326c1427d82f5b8e2390f/ws-contacts/src/app/contacts.clj
clojure
(ns app.contacts (:require [app.handler :as handler])) (def app handler/routes) (def my-contacts (atom #{{:first "Ben" :last "Bitdiddle" :email ""} {:first "Alyssa" :middle-initial "P" :last "Hacker" :email ""} {:first "Eva" :middle "Lu" :last "Ator" :email ""} {:first "Louis" :last "Reasoner" :email ""} {:first "Cy" :middle-initial "D" :last "Effect" :email ""} {:first "Lem" :middle-initial "E" :last "Tweakit" :email ""}})) (defmethod handler/event-msg-handler :contacts/get-contacts [{:as ev-msg :keys [event id ?data ring-req ?reply-fn send-fn]}] (handler/chsk-send! (:client-id ev-msg) [(:resp-id ?data) @my-contacts])) (defmethod handler/event-msg-handler :contacts/delete [{:as ev-msg :keys [event id ?data ring-req ?reply-fn send-fn]}] (let [contact (:contact ?data)] (swap! my-contacts disj contact) (handler/broadcast :contacts/deleted contact))) (defmethod handler/event-msg-handler :contacts/add [{:as ev-msg :keys [event id ?data ring-req ?reply-fn send-fn]}] (let [contact (:contact ?data)] (swap! my-contacts conj contact) (handler/broadcast :contacts/added contact)))
8d72e74a5f0ae8ac34fce4f2593e26aa609bcf5fed01185a5a32ce11451e8cea
furkan3ayraktar/clojure-polylith-realworld-example-app
store.clj
(ns clojure.realworld.user.store (:require [clojure.java.jdbc :as jdbc] [clojure.realworld.database.interface :as database] [clojure.realworld.user.spec :as spec] [clojure.spec.alpha :as s] [honey.sql :as sql])) (defn find-by [key value] (let [query {:select [:*] :from [:user] :where [:= key value]} results (jdbc/query (database/db) (sql/format query))] (first results))) (defn find-by-email [email] (find-by :email email)) (defn find-by-username [username] (find-by :username username)) (defn find-by-id [id] (find-by :id id)) (defn find-by-username-or-id [username-or-id] (if (s/valid? spec/id username-or-id) (find-by-id username-or-id) (find-by-username username-or-id))) (defn insert-user! [user-input] (jdbc/insert! (database/db) :user user-input)) (defn update-user! [id user-input] (let [query {:update :user :set user-input :where [:= :id id]}] (jdbc/execute! (database/db) (sql/format query))))
null
https://raw.githubusercontent.com/furkan3ayraktar/clojure-polylith-realworld-example-app/7703ee7af93887ea600d1c05e400255303a6ed47/components/user/src/clojure/realworld/user/store.clj
clojure
(ns clojure.realworld.user.store (:require [clojure.java.jdbc :as jdbc] [clojure.realworld.database.interface :as database] [clojure.realworld.user.spec :as spec] [clojure.spec.alpha :as s] [honey.sql :as sql])) (defn find-by [key value] (let [query {:select [:*] :from [:user] :where [:= key value]} results (jdbc/query (database/db) (sql/format query))] (first results))) (defn find-by-email [email] (find-by :email email)) (defn find-by-username [username] (find-by :username username)) (defn find-by-id [id] (find-by :id id)) (defn find-by-username-or-id [username-or-id] (if (s/valid? spec/id username-or-id) (find-by-id username-or-id) (find-by-username username-or-id))) (defn insert-user! [user-input] (jdbc/insert! (database/db) :user user-input)) (defn update-user! [id user-input] (let [query {:update :user :set user-input :where [:= :id id]}] (jdbc/execute! (database/db) (sql/format query))))
c36a482691c710b63e206a5234f0cd09e3f02d6375c1572fc96bbae36ecdd779
acl2/acl2
(INTERSECTION-EQUAL-OF-CONS-IFF (2068 6 (:DEFINITION SUBSETP-EQUAL)) (1638 18 (:REWRITE SUBSEQUENCEP-EQUAL-EQUAL-LEN)) (1158 101 (:REWRITE CONSP-FROM-LEN-CHEAP)) (1104 48 (:REWRITE NODE-LIST-P-TRUE-LISTP1)) (1044 24 (:DEFINITION TRUE-LISTP)) (654 54 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (470 18 (:REWRITE SUBLISTP-NOT-PREFIXP)) (355 51 (:REWRITE LEN-OF-CDR)) (346 6 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR-RIGHT)) (258 48 (:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP)) (258 36 (:REWRITE SUBLISTP-WHEN-ATOM-LEFT)) (216 24 (:REWRITE NODE-LIST-P-OF-CDR)) (204 30 (:REWRITE TRUE-LISTP-OF-CDR-0)) (184 36 (:REWRITE SUBLISTP-WHEN-ATOM-RIGHT)) (138 138 (:TYPE-PRESCRIPTION TRUE-LISTP)) (126 42 (:REWRITE SUFFIXP-SUBLISTP)) (124 124 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (123 63 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (119 69 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (108 108 (:TYPE-PRESCRIPTION NODE-LIST-P)) (107 107 (:REWRITE DEFAULT-CDR)) (101 101 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (97 97 (:REWRITE CONSP-WHEN-LEN-GREATER)) (96 6 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (95 51 (:REWRITE DEFAULT-<-2)) (91 61 (:REWRITE DEFAULT-+-2)) (84 84 (:TYPE-PRESCRIPTION SUFFIXP)) (82 36 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (69 69 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (69 69 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (69 69 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (66 66 (:REWRITE DEFAULT-CAR)) (66 33 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (66 33 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (64 64 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (64 64 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (64 64 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (64 64 (:LINEAR LEN-WHEN-PREFIXP)) (63 63 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (63 63 (:REWRITE SUFFIXP$-TRANSITIVE)) (63 63 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (61 61 (:REWRITE DEFAULT-+-1)) (60 60 (:TYPE-PRESCRIPTION SET::SETP-TYPE)) (60 30 (:REWRITE OMAP::SETP-WHEN-MAPP)) (60 30 (:REWRITE SET::NONEMPTY-MEANS-SET)) (60 18 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-LEFT)) (59 59 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (57 57 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (54 54 (:REWRITE USE-ALL-NODE-LIST-P-2)) (54 54 (:REWRITE USE-ALL-NODE-LIST-P)) (54 54 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (54 54 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (54 54 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (51 51 (:REWRITE DEFAULT-<-1)) (50 18 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-RIGHT)) (48 48 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (47 47 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (47 47 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (47 47 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (42 42 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (42 42 (:REWRITE SUBLISTP-TRANSITIVE)) (36 36 (:REWRITE SUBLISTP-COMPLETE)) (36 18 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR)) (36 10 (:REWRITE FOLD-CONSTS-IN-+)) (30 30 (:TYPE-PRESCRIPTION OMAP::MAPP)) (30 30 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE)) (30 30 (:REWRITE SET::IN-SET)) (30 6 (:REWRITE SUFFIXP$-OF-CDR-AND-CDR)) (27 27 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (27 27 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (24 24 (:REWRITE EQUAL-OF-LEN-AND-0)) (18 18 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-OF-CDR-OF-MEMBER-EQUAL)) (18 18 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-SUFFIXP$)) (18 18 (:REWRITE SUBSEQUENCEP-EQUAL-TRANSITIVE)) (10 10 (:REWRITE LEN-OF-CDDR-WHEN-EQUAL-OF-LEN)) (2 2 (:REWRITE MEMBERP-OF-CONS-IRREL-STRONG)) ) (DRONE-ID-P) (BOOLEANP-OF-DRONE-ID-P) (DRONE-ID-P-ZERO) (DRONE-ID-FIX (1 1 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) ) (DRONE-ID-P-DRONE-ID-FIX (26 26 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) (3 3 (:REWRITE DEFAULT-<-2)) (3 3 (:REWRITE DEFAULT-<-1)) ) (DRONE-ID-P-DRONE-ID-FIX-ID (1 1 (:REWRITE DEFAULT-<-2)) (1 1 (:REWRITE DEFAULT-<-1)) ) (DRONE-ID-EQUIV (10 10 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) ) (DRONE-ID-EQUIV-IS-AN-EQUIVALENCE (6 6 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) ) (__DEFFIXTYPE-DRONE-ID-EQUIV-MEANS-EQUAL-OF-DRONE-ID-FIX (6 6 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) ) (DRONE-ID-LIST-P) (STD::DEFLIST-LOCAL-BOOLEANP-ELEMENT-THM) (DRONE-ID-LIST-P-OF-CONS) (DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P) (DRONE-ID-LIST-P-WHEN-NOT-CONSP) (DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P) (TRUE-LISTP-WHEN-DRONE-ID-LIST-P) (DRONE-ID-LIST-P-OF-LIST-FIX) (DRONE-ID-LIST-P-OF-REV) (DRONE-ID-LIST-FIX$INLINE (1 1 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) ) (DRONE-ID-LIST-P-OF-DRONE-ID-LIST-FIX (15 1 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (12 2 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (9 5 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (9 1 (:DEFINITION DRONE-ID-LIST-P)) (4 4 (:TYPE-PRESCRIPTION DRONE-ID-P)) (2 1 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) ) (DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P (17 4 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (9 3 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) ) (DRONE-ID-LIST-FIX$INLINE (4 4 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (4 1 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (4 1 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) ) (FTY::TMP-DEFFIXTYPE-IDEMPOTENT (1 1 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) ) (DRONE-ID-LIST-EQUIV$INLINE) (DRONE-ID-LIST-EQUIV-IS-AN-EQUIVALENCE) (DRONE-ID-LIST-EQUIV-IMPLIES-EQUAL-DRONE-ID-LIST-FIX-1) (DRONE-ID-LIST-FIX-UNDER-DRONE-ID-LIST-EQUIV) (EQUAL-OF-DRONE-ID-LIST-FIX-1-FORWARD-TO-DRONE-ID-LIST-EQUIV) (EQUAL-OF-DRONE-ID-LIST-FIX-2-FORWARD-TO-DRONE-ID-LIST-EQUIV) (DRONE-ID-LIST-EQUIV-OF-DRONE-ID-LIST-FIX-1-FORWARD) (DRONE-ID-LIST-EQUIV-OF-DRONE-ID-LIST-FIX-2-FORWARD) (CAR-OF-DRONE-ID-LIST-FIX-X-UNDER-DRONE-ID-EQUIV (112 8 (:REWRITE INTEGERP-OF-CAR-WHEN-INTEGER-LISTP)) (96 4 (:DEFINITION INTEGER-LISTP)) (61 4 (:REWRITE NATP-OF-CAR-WHEN-NAT-LISTP)) (60 8 (:REWRITE INTEGER-LISTP-WHEN-NOT-CONSP)) (59 6 (:REWRITE CONSP-FROM-LEN-CHEAP)) (55 1 (:DEFINITION NAT-LISTP)) (45 45 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) (28 28 (:TYPE-PRESCRIPTION INTEGER-LISTP)) (25 5 (:REWRITE LEN-OF-CDR)) (18 6 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (15 2 (:REWRITE NAT-LISTP-WHEN-NOT-CONSP)) (14 14 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (12 12 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (12 2 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (11 10 (:REWRITE DEFAULT-<-2)) (10 10 (:REWRITE DEFAULT-<-1)) (8 4 (:REWRITE INTEGER-LISTP-OF-CDR-WHEN-INTEGER-LISTP)) (7 7 (:TYPE-PRESCRIPTION NAT-LISTP)) (7 7 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (6 6 (:REWRITE CONSP-WHEN-LEN-GREATER)) (6 6 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (5 5 (:REWRITE DEFAULT-CDR)) (5 5 (:REWRITE DEFAULT-+-2)) (5 5 (:REWRITE DEFAULT-+-1)) (5 5 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (4 1 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (3 3 (:TYPE-PRESCRIPTION DRONE-ID-LIST-FIX$INLINE)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (2 2 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (2 2 (:LINEAR LEN-WHEN-PREFIXP)) (2 1 (:REWRITE NAT-LISTP-OF-CDR-WHEN-NAT-LISTP)) (2 1 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) ) (CAR-DRONE-ID-LIST-EQUIV-CONGRUENCE-ON-X-UNDER-DRONE-ID-EQUIV) (CDR-OF-DRONE-ID-LIST-FIX-X-UNDER-DRONE-ID-LIST-EQUIV (29 3 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (14 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (8 2 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (4 4 (:TYPE-PRESCRIPTION DRONE-ID-P)) ) (CDR-DRONE-ID-LIST-EQUIV-CONGRUENCE-ON-X-UNDER-DRONE-ID-LIST-EQUIV) (CONS-OF-DRONE-ID-FIX-X-UNDER-DRONE-ID-LIST-EQUIV (20 4 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (9 2 (:REWRITE DRONE-ID-LIST-P-OF-CONS)) (6 6 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (5 5 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) ) (CONS-DRONE-ID-EQUIV-CONGRUENCE-ON-X-UNDER-DRONE-ID-LIST-EQUIV) (CONS-OF-DRONE-ID-LIST-FIX-Y-UNDER-DRONE-ID-LIST-EQUIV (12 2 (:REWRITE DRONE-ID-LIST-P-OF-CONS)) (8 8 (:TYPE-PRESCRIPTION DRONE-ID-P)) (5 4 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (4 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) ) (CONS-DRONE-ID-LIST-EQUIV-CONGRUENCE-ON-Y-UNDER-DRONE-ID-LIST-EQUIV) (CONSP-OF-DRONE-ID-LIST-FIX (12 2 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (8 8 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (7 1 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (4 4 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (4 1 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (4 1 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (2 2 (:TYPE-PRESCRIPTION DRONE-ID-P)) ) (DRONE-ID-LIST-FIX-UNDER-IFF (12 2 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (8 8 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (7 1 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (4 4 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (4 1 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (4 1 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (2 2 (:TYPE-PRESCRIPTION DRONE-ID-P)) ) (DRONE-ID-LIST-FIX-OF-CONS (13 3 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (5 1 (:REWRITE DRONE-ID-LIST-P-OF-CONS)) (4 4 (:TYPE-PRESCRIPTION DRONE-ID-P)) (4 4 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (4 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (3 3 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) ) (LEN-OF-DRONE-ID-LIST-FIX (23 4 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (13 13 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (8 2 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (7 7 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (7 1 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (4 1 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (2 2 (:TYPE-PRESCRIPTION DRONE-ID-P)) (1 1 (:REWRITE FTY::EQUAL-OF-LEN)) ) (DRONE-ID-LIST-FIX-OF-APPEND (56 10 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (23 23 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (18 12 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (8 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (8 2 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (4 1 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (2 2 (:TYPE-PRESCRIPTION DRONE-ID-P)) ) (DRONE-ID-LIST-FIX-OF-REPEAT (20 2 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (10 4 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (8 2 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (6 6 (:TYPE-PRESCRIPTION DRONE-ID-P)) (4 4 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (1 1 (:REWRITE-QUOTED-CONSTANT DRONE-ID-LIST-FIX-UNDER-DRONE-ID-LIST-EQUIV)) ) (LIST-EQUIV-REFINES-DRONE-ID-LIST-EQUIV (98 14 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (72 8 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (70 70 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (60 18 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (48 8 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (36 36 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (16 16 (:TYPE-PRESCRIPTION DRONE-ID-P)) ) (NTH-OF-DRONE-ID-LIST-FIX (219 24 (:REWRITE CONSP-FROM-LEN-CHEAP)) (135 16 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (93 24 (:REWRITE DEFAULT-CDR)) (76 7 (:REWRITE DEFAULT-CAR)) (71 71 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (63 63 (:REWRITE DEFAULT-+-2)) (63 63 (:REWRITE DEFAULT-+-1)) (59 35 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (50 13 (:REWRITE CONSP-OF-DRONE-ID-LIST-FIX)) (48 45 (:REWRITE DEFAULT-<-2)) (48 12 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (45 45 (:REWRITE DEFAULT-<-1)) (31 10 (:REWRITE ZP-OPEN)) (28 7 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (24 24 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (20 2 (:LINEAR LEN-OF-CDR-LINEAR-STRONG)) (19 1 (:REWRITE NOT-EQUAL-NTH-WHEN-NOT-MEMBERP-CHEAP)) (16 2 (:LINEAR LEN-OF-CDR-LINEAR)) (10 10 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (10 10 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (10 10 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (10 10 (:LINEAR LEN-WHEN-PREFIXP)) (8 5 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (7 7 (:REWRITE NTH-WHEN-PREFIXP)) (5 5 (:REWRITE CONSP-WHEN-LEN-GREATER)) (4 4 (:TYPE-PRESCRIPTION MEMBERP)) (4 4 (:LINEAR LISTPOS-COMPLETE)) (2 2 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (2 1 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (2 1 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (2 1 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (2 1 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (2 1 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (2 1 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (1 1 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (1 1 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (1 1 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (1 1 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (1 1 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (1 1 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (1 1 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) ) (DRONE-ID-LIST-EQUIV-IMPLIES-DRONE-ID-LIST-EQUIV-APPEND-1 (181 32 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (131 17 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (126 126 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (80 17 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (79 22 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (64 64 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (34 34 (:TYPE-PRESCRIPTION DRONE-ID-P)) ) (DRONE-ID-LIST-EQUIV-IMPLIES-DRONE-ID-LIST-EQUIV-APPEND-2 (267 46 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (206 26 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (189 189 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (138 39 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (128 26 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (95 95 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (52 52 (:TYPE-PRESCRIPTION DRONE-ID-P)) (4 4 (:REWRITE CONSP-OF-DRONE-ID-LIST-FIX)) ) (DRONE-ID-LIST-EQUIV-IMPLIES-DRONE-ID-LIST-EQUIV-NTHCDR-2 (249 39 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (175 175 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (174 22 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (117 33 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (108 22 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (88 88 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (44 44 (:TYPE-PRESCRIPTION DRONE-ID-P)) ) (DRONE-ID-LIST-EQUIV-IMPLIES-DRONE-ID-LIST-EQUIV-TAKE-2 (326 38 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (222 28 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (190 190 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (149 39 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (140 26 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (119 95 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (54 54 (:TYPE-PRESCRIPTION DRONE-ID-P)) (40 40 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) (6 6 (:REWRITE-QUOTED-CONSTANT DRONE-ID-LIST-FIX-UNDER-DRONE-ID-LIST-EQUIV)) ) (COORD-ID-P) (GET-ASSOC) (NO-DUPLICATE-ALIST-P) (BOOLEANP-OF-NO-DUPLICATE-ALIST-P) (NO-DUPLICATE-ALIST-CDR (2751 18 (:DEFINITION NO-DUPLICATESP-EQUAL)) (2360 54 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NO-DUPLICATESP-EQUAL-OF-CDR)) (977 61 (:REWRITE CONSP-FROM-LEN-CHEAP)) (796 36 (:REWRITE NO-DUPLICATESP-EQUAL-OF-CDR)) (715 19 (:REWRITE MEMBER-EQUAL-BECOMES-MEMBERP)) (601 30 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (415 24 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (284 5 (:DEFINITION HONS-ASSOC-EQUAL)) (246 246 (:TYPE-PRESCRIPTION TRUE-LISTP-OF-ALIST-KEYS)) (221 18 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (206 16 (:REWRITE LEN-OF-CDR)) (162 162 (:TYPE-PRESCRIPTION MEMBER-EQUAL)) (147 147 (:TYPE-PRESCRIPTION MEMBERP)) (120 85 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (120 60 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (120 60 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (89 41 (:REWRITE DEFAULT-<-2)) (86 43 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (86 43 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (86 43 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (80 16 (:REWRITE EQUAL-OF-LEN-AND-0)) (75 54 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NOT-CONSP-CHEAP)) (70 36 (:REWRITE MEMBER-EQUAL-OF-CAR-SAME)) (67 60 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (61 61 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (60 60 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (60 60 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (60 60 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (58 58 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (58 58 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (58 58 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (58 58 (:LINEAR LEN-WHEN-PREFIXP)) (54 54 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL)) (52 43 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (51 51 (:REWRITE CONSP-WHEN-LEN-GREATER)) (43 43 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (43 43 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (43 43 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (43 43 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (43 43 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (43 43 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (43 43 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (41 41 (:REWRITE DEFAULT-<-1)) (39 39 (:REWRITE DEFAULT-CAR)) (34 17 (:REWRITE DEFAULT-+-2)) (30 30 (:TYPE-PRESCRIPTION HONS-ASSOC-EQUAL)) (19 19 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (18 18 (:REWRITE MEMBERP-OF-CAR-SAME)) (17 17 (:REWRITE DEFAULT-+-1)) (16 16 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (10 10 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (10 5 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (10 5 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (5 5 (:DEFINITION HONS-EQUAL)) ) (NO-DUPLICATE-ALIST-ACONS (13870 324 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NO-DUPLICATESP-EQUAL-OF-CDR)) (6631 440 (:REWRITE CONSP-FROM-LEN-CHEAP)) (3303 187 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (2601 149 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (2096 431 (:REWRITE DEFAULT-CDR)) (1578 6 (:DEFINITION SUBSETP-EQUAL)) (1390 111 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (1193 121 (:REWRITE LEN-OF-CDR)) (1003 734 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (942 18 (:REWRITE SUBSEQUENCEP-EQUAL-EQUAL-LEN)) (770 385 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (770 385 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (619 307 (:REWRITE DEFAULT-<-2)) (583 293 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (572 572 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (572 572 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (572 572 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (572 572 (:LINEAR LEN-WHEN-PREFIXP)) (572 286 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (572 286 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (501 222 (:REWRITE MEMBER-EQUAL-OF-CAR-SAME)) (462 6 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR-RIGHT)) (440 440 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (426 379 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (426 320 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NOT-CONSP-CHEAP)) (385 385 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (385 385 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (385 385 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (365 365 (:REWRITE CONSP-WHEN-LEN-GREATER)) (354 286 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (340 88 (:REWRITE EQUAL-OF-LEN-AND-0)) (328 328 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL)) (309 307 (:REWRITE DEFAULT-<-1)) (293 293 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (293 293 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (293 293 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (293 293 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (288 18 (:REWRITE SUBLISTP-WHEN-ATOM-LEFT)) (286 286 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (233 133 (:REWRITE DEFAULT-+-2)) (229 4 (:REWRITE NO-DUPLICATESP-EQUAL-OF-CONS-NO-SPLIT)) (194 8 (:REWRITE PREFIXP-WHEN-EQUAL-LENGTHS)) (165 8 (:REWRITE PREFIXP-WHEN-PREFIXP)) (148 2 (:REWRITE SUBLISTP-NOT-PREFIXP)) (133 133 (:REWRITE DEFAULT-+-1)) (126 18 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-LEFT)) (124 124 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (124 62 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (118 109 (:REWRITE MEMBERP-OF-CAR-SAME)) (115 115 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (111 111 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (106 53 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (102 18 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-RIGHT)) (102 18 (:REWRITE SUBLISTP-WHEN-ATOM-RIGHT)) (84 28 (:REWRITE SUFFIXP-SUBLISTP)) (75 4 (:REWRITE LIST-EQUIV-WHEN-ATOM-RIGHT)) (56 56 (:TYPE-PRESCRIPTION SUFFIXP)) (50 10 (:REWRITE SUFFIXP$-OF-CDR)) (38 38 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (38 38 (:REWRITE SUFFIXP$-TRANSITIVE)) (36 18 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR)) (28 28 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (28 28 (:REWRITE SUBLISTP-TRANSITIVE)) (19 19 (:REWRITE SUBLISTP-COMPLETE)) (18 18 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-OF-CDR-OF-MEMBER-EQUAL)) (18 18 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-SUFFIXP$)) (18 18 (:REWRITE SUBSEQUENCEP-EQUAL-TRANSITIVE)) (15 3 (:REWRITE PREFIXP-WHEN-NOT-CONSP-LEFT)) (8 8 (:REWRITE PREFIXP-TRANSITIVE-1)) (8 8 (:REWRITE PREFIXP-TRANSITIVE . 2)) (8 8 (:REWRITE PREFIXP-TRANSITIVE . 1)) (8 8 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 2)) (8 8 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 1)) (5 4 (:REWRITE LIST-EQUIV-WHEN-ATOM-LEFT)) (4 4 (:TYPE-PRESCRIPTION LIST-EQUIV)) (3 3 (:REWRITE PREFIXP-WHEN-NOT-CONSP-RIGHT)) ) (NO-DUPLICATE-ALIST-CONS (1735 27 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NO-DUPLICATESP-EQUAL-OF-CDR)) (657 69 (:REWRITE CONSP-FROM-LEN-CHEAP)) (605 24 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (371 19 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (221 14 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (211 45 (:REWRITE DEFAULT-CDR)) (186 28 (:REWRITE MEMBER-EQUAL-OF-CAR-SAME)) (148 2 (:REWRITE SUBLISTP-NOT-PREFIXP)) (98 49 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (98 49 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (88 48 (:REWRITE DEFAULT-CAR)) (86 71 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (84 12 (:REWRITE LEN-OF-CDR)) (79 34 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (72 4 (:REWRITE PREFIXP-WHEN-EQUAL-LENGTHS)) (69 69 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (66 4 (:REWRITE PREFIXP-WHEN-PREFIXP)) (65 34 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (60 60 (:REWRITE CONSP-WHEN-LEN-GREATER)) (60 30 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (60 30 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (58 49 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (56 30 (:REWRITE DEFAULT-<-2)) (50 50 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (50 50 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (50 50 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (50 50 (:LINEAR LEN-WHEN-PREFIXP)) (49 49 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (49 49 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (49 49 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (42 6 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (39 34 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (36 30 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (34 34 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (34 34 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (34 34 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (34 34 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (34 12 (:REWRITE MEMBERP-OF-CAR-SAME)) (30 30 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (30 30 (:REWRITE DEFAULT-<-1)) (29 29 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL)) (28 28 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (28 2 (:REWRITE LIST-EQUIV-WHEN-ATOM-RIGHT)) (22 16 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NOT-CONSP-CHEAP)) (20 4 (:REWRITE SUFFIXP$-OF-CDR)) (18 6 (:REWRITE SUFFIXP-SUBLISTP)) (17 12 (:REWRITE DEFAULT-+-2)) (16 16 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (16 8 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (16 8 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (14 14 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (12 12 (:TYPE-PRESCRIPTION SUFFIXP)) (12 12 (:REWRITE DEFAULT-+-1)) (12 5 (:REWRITE EQUAL-OF-LEN-AND-0)) (10 10 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (10 10 (:REWRITE SUFFIXP$-TRANSITIVE)) (10 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-LEFT)) (8 8 (:TYPE-PRESCRIPTION PREFIXP)) (6 6 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (6 6 (:REWRITE SUBLISTP-TRANSITIVE)) (4 4 (:REWRITE PREFIXP-TRANSITIVE-1)) (4 4 (:REWRITE PREFIXP-TRANSITIVE . 2)) (4 4 (:REWRITE PREFIXP-TRANSITIVE . 1)) (4 4 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 2)) (4 4 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 1)) (2 2 (:TYPE-PRESCRIPTION LIST-EQUIV)) (2 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-RIGHT)) (2 2 (:REWRITE LIST-EQUIV-WHEN-ATOM-LEFT)) ) (NO-DUPLICATE-ALIST-CAAR-ALIST-KEYS-CDR (834 6 (:DEFINITION NO-DUPLICATESP-EQUAL)) (702 18 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NO-DUPLICATESP-EQUAL-OF-CDR)) (355 25 (:REWRITE CONSP-FROM-LEN-CHEAP)) (264 12 (:REWRITE NO-DUPLICATESP-EQUAL-OF-CDR)) (232 6 (:REWRITE MEMBER-EQUAL-BECOMES-MEMBERP)) (138 8 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (124 10 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (118 28 (:REWRITE DEFAULT-CDR)) (74 6 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (60 6 (:REWRITE LEN-OF-CDR)) (52 1 (:REWRITE NO-DUPLICATESP-EQUAL-OF-CONS-NO-SPLIT)) (49 39 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (48 48 (:TYPE-PRESCRIPTION MEMBERP)) (44 22 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (44 22 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (38 19 (:REWRITE DEFAULT-<-2)) (37 37 (:REWRITE DEFAULT-CAR)) (36 36 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (36 36 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (36 36 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (36 36 (:LINEAR LEN-WHEN-PREFIXP)) (28 14 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (28 14 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (28 14 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (26 22 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (25 25 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (24 18 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NOT-CONSP-CHEAP)) (24 12 (:REWRITE MEMBER-EQUAL-OF-CAR-SAME)) (23 23 (:REWRITE CONSP-WHEN-LEN-GREATER)) (22 22 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (22 22 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (22 22 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (19 19 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL)) (19 19 (:REWRITE DEFAULT-<-1)) (18 4 (:REWRITE EQUAL-OF-LEN-AND-0)) (16 14 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (15 4 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (14 14 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (14 14 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (14 14 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (14 14 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (14 14 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (14 14 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (14 14 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (14 8 (:REWRITE DEFAULT-+-2)) (12 12 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (12 6 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (12 6 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (8 8 (:REWRITE DEFAULT-+-1)) (6 6 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (6 6 (:REWRITE MEMBERP-OF-CAR-SAME)) (6 6 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (DISJOINT-ALISTS-P) (BOOLEANP-OF-DISJOINT-ALISTS-P) (DISJOINT-ALISTS-P-ACONS-CAAR (3327 72 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NO-DUPLICATESP-EQUAL-OF-CDR)) (1652 114 (:REWRITE CONSP-FROM-LEN-CHEAP)) (820 45 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (651 36 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (473 112 (:REWRITE DEFAULT-CDR)) (353 27 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (218 22 (:REWRITE LEN-OF-CDR)) (209 164 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (196 98 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (196 98 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (165 54 (:REWRITE MEMBER-EQUAL-OF-CAR-SAME)) (156 77 (:REWRITE DEFAULT-<-2)) (148 2 (:REWRITE SUBLISTP-NOT-PREFIXP)) (146 126 (:REWRITE DEFAULT-CAR)) (142 142 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (142 142 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (142 142 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (142 142 (:LINEAR LEN-WHEN-PREFIXP)) (123 63 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (123 22 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (118 59 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (118 59 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (115 98 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (114 114 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (98 98 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (98 98 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (98 98 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (95 95 (:REWRITE CONSP-WHEN-LEN-GREATER)) (90 68 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NOT-CONSP-CHEAP)) (77 77 (:REWRITE DEFAULT-<-1)) (73 73 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL)) (72 4 (:REWRITE PREFIXP-WHEN-EQUAL-LENGTHS)) (70 1 (:REWRITE NO-DUPLICATESP-EQUAL-OF-CONS-NO-SPLIT)) (68 59 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (66 4 (:REWRITE PREFIXP-WHEN-PREFIXP)) (65 63 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (64 15 (:REWRITE EQUAL-OF-LEN-AND-0)) (63 63 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (63 63 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (63 63 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (63 63 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (59 59 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (41 24 (:REWRITE DEFAULT-+-2)) (38 19 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (37 37 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (36 18 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (34 25 (:REWRITE MEMBERP-OF-CAR-SAME)) (28 2 (:REWRITE LIST-EQUIV-WHEN-ATOM-RIGHT)) (27 27 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (26 26 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (24 24 (:REWRITE DEFAULT-+-1)) (20 4 (:REWRITE SUFFIXP$-OF-CDR)) (18 6 (:REWRITE SUFFIXP-SUBLISTP)) (12 12 (:TYPE-PRESCRIPTION SUFFIXP)) (10 10 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (10 10 (:REWRITE SUFFIXP$-TRANSITIVE)) (10 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-LEFT)) (9 9 (:REWRITE INTERSECTION-EQUAL-WHEN-MEMBERP-AND-MEMBERP-SAME-IFF)) (8 8 (:TYPE-PRESCRIPTION PREFIXP)) (6 6 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (6 6 (:REWRITE SUBLISTP-TRANSITIVE)) (4 4 (:REWRITE PREFIXP-TRANSITIVE-1)) (4 4 (:REWRITE PREFIXP-TRANSITIVE . 2)) (4 4 (:REWRITE PREFIXP-TRANSITIVE . 1)) (4 4 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 2)) (4 4 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 1)) (2 2 (:TYPE-PRESCRIPTION LIST-EQUIV)) (2 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-RIGHT)) (2 2 (:REWRITE LIST-EQUIV-WHEN-ATOM-LEFT)) ) (NOT-ASSOC-EQUAL-LEMMA (1659 128 (:REWRITE CONSP-FROM-LEN-CHEAP)) (601 17 (:DEFINITION HONS-ASSOC-EQUAL)) (596 2 (:DEFINITION SUBSETP-EQUAL)) (410 50 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (314 6 (:REWRITE SUBSEQUENCEP-EQUAL-EQUAL-LEN)) (278 236 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (221 17 (:REWRITE OMAP::ALISTP-WHEN-MAPP)) (203 149 (:REWRITE DEFAULT-CAR)) (194 194 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (194 194 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (194 194 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (194 194 (:LINEAR LEN-WHEN-PREFIXP)) (154 2 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR-RIGHT)) (148 80 (:REWRITE DEFAULT-<-2)) (128 128 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (96 6 (:REWRITE SUBLISTP-WHEN-ATOM-LEFT)) (92 16 (:REWRITE LEN-OF-CDR)) (85 17 (:REWRITE OMAP::MFIX-IMPLIES-MAPP)) (85 17 (:REWRITE OMAP::MAPP-WHEN-NOT-EMPTY)) (82 82 (:REWRITE DEFAULT-CDR)) (82 82 (:REWRITE CONSP-WHEN-LEN-GREATER)) (80 80 (:REWRITE DEFAULT-<-1)) (68 68 (:TYPE-PRESCRIPTION OMAP::MAPP)) (56 28 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (50 50 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (44 22 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (42 6 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-LEFT)) (36 36 (:TYPE-PRESCRIPTION MEMBER-EQUAL)) (36 18 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (36 18 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (34 34 (:TYPE-PRESCRIPTION OMAP::MFIX)) (34 34 (:TYPE-PRESCRIPTION OMAP::EMPTY)) (34 17 (:REWRITE OMAP::MFIX-WHEN-MAPP)) (34 17 (:REWRITE OMAP::MAPP-NON-NIL-IMPLIES-NON-EMPTY)) (34 6 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-RIGHT)) (34 6 (:REWRITE SUBLISTP-WHEN-ATOM-RIGHT)) (32 16 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (32 16 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (31 16 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (30 30 (:REWRITE INTERSECTION-EQUAL-WHEN-MEMBERP-AND-MEMBERP-SAME-IFF)) (28 20 (:REWRITE DEFAULT-+-2)) (28 14 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (28 14 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (28 14 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (24 8 (:REWRITE SUFFIXP-SUBLISTP)) (20 20 (:REWRITE DEFAULT-+-1)) (18 18 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (18 18 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (18 18 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (17 17 (:DEFINITION HONS-EQUAL)) (16 16 (:TYPE-PRESCRIPTION SUFFIXP)) (16 16 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (16 16 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (16 16 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (16 16 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (16 16 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (14 14 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (12 6 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR)) (10 10 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (10 10 (:REWRITE SUFFIXP$-TRANSITIVE)) (10 2 (:REWRITE SUFFIXP$-OF-CDR)) (8 8 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (8 8 (:REWRITE SUBLISTP-TRANSITIVE)) (6 6 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-OF-CDR-OF-MEMBER-EQUAL)) (6 6 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-SUFFIXP$)) (6 6 (:REWRITE SUBSEQUENCEP-EQUAL-TRANSITIVE)) (6 6 (:REWRITE SUBLISTP-COMPLETE)) (4 4 (:REWRITE EQUAL-OF-LEN-AND-0)) ) (DISJOINT-ALISTS-P-OF-CONS-ARG2 (324 24 (:REWRITE CONSP-FROM-LEN-CHEAP)) (208 4 (:DEFINITION HONS-ASSOC-EQUAL)) (88 16 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (63 1 (:REWRITE MEMBER-EQUAL-OF-CONS-NON-CONSTANT)) (48 24 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (40 36 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (32 32 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (32 32 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (32 32 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (32 32 (:LINEAR LEN-WHEN-PREFIXP)) (32 16 (:REWRITE DEFAULT-<-2)) (29 29 (:REWRITE DEFAULT-CAR)) (24 24 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (16 16 (:REWRITE DEFAULT-CDR)) (16 16 (:REWRITE DEFAULT-<-1)) (16 16 (:REWRITE CONSP-WHEN-LEN-GREATER)) (8 8 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (8 8 (:TYPE-PRESCRIPTION MEMBER-EQUAL)) (8 4 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (8 4 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (8 4 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (8 4 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (8 4 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (8 4 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (8 4 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (6 3 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (6 3 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (6 3 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (5 5 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (5 5 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (5 5 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (4 4 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (4 4 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (4 4 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (4 4 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (4 4 (:REWRITE INTERSECTION-EQUAL-WHEN-MEMBERP-AND-MEMBERP-SAME-IFF)) (4 4 (:DEFINITION HONS-EQUAL)) (3 3 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (3 1 (:REWRITE SUFFIXP-SUBLISTP)) (2 2 (:TYPE-PRESCRIPTION SUFFIXP)) (1 1 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (1 1 (:REWRITE SUFFIXP$-TRANSITIVE)) (1 1 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (1 1 (:REWRITE SUBLISTP-TRANSITIVE)) ) (PATH-MAP-P0) (BOOLEANP-OF-DRONE-ID-P-FOR-PATH-MAP-P0-KEY-LEMMA) (BOOLEANP-OF-NODE-LIST-P-FOR-PATH-MAP-P0-VAL-LEMMA) (BOOLEANP-OF-DRONE-ID-P-FOR-PATH-MAP-P0-KEY) (BOOLEANP-OF-NODE-LIST-P-FOR-PATH-MAP-P0-VAL) (PATH-MAP-P0-OF-REV) (PATH-MAP-P0-OF-LIST-FIX) (TRUE-LISTP-WHEN-PATH-MAP-P0) (PATH-MAP-P0-WHEN-NOT-CONSP) (PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0) (PATH-MAP-P0-OF-CONS) (PATH-MAP-P0-OF-REMOVE-ASSOC (56 10 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (16 16 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) ) (PATH-MAP-P0-OF-PUT-ASSOC) (PATH-MAP-P0-OF-FAST-ALIST-CLEAN) (PATH-MAP-P0-OF-HONS-SHRINK-ALIST) (PATH-MAP-P0-OF-HONS-ACONS) (NODE-LIST-P-OF-CDR-OF-HONS-ASSOC-EQUAL-WHEN-PATH-MAP-P0) (ALISTP-WHEN-PATH-MAP-P0-REWRITE) (ALISTP-WHEN-PATH-MAP-P0) (NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0) (DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0) (PATH-MAP-FIX$INLINE (2 2 (:TYPE-PRESCRIPTION NODE-LIST-FIX)) (1 1 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) ) (PATH-MAP-P0-OF-PATH-MAP-FIX (349 24 (:REWRITE CONSP-FROM-LEN-CHEAP)) (314 7 (:REWRITE NODE-LIST-FIX-NODE-LIST-P)) (233 7 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (201 8 (:DEFINITION PATH-MAP-P0)) (199 15 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0)) (176 12 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (146 12 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (119 40 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (102 6 (:REWRITE NODE-LIST-P-OF-CDR)) (77 15 (:REWRITE NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0)) (56 48 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (52 8 (:REWRITE LEN-OF-CDR)) (48 6 (:REWRITE USE-ALL-NODE-LIST-P-FOR-CAR)) (42 42 (:TYPE-PRESCRIPTION NODE-LIST-P)) (36 20 (:REWRITE DEFAULT-<-2)) (34 34 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (34 34 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (34 34 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (34 34 (:LINEAR LEN-WHEN-PREFIXP)) (32 32 (:REWRITE DEFAULT-CAR)) (30 30 (:TYPE-PRESCRIPTION DRONE-ID-P)) (26 26 (:REWRITE DEFAULT-CDR)) (24 24 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (24 6 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (20 20 (:REWRITE DEFAULT-<-1)) (20 20 (:REWRITE CONSP-WHEN-LEN-GREATER)) (16 16 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (14 9 (:REWRITE DEFAULT-+-2)) (12 12 (:REWRITE USE-ALL-NODE-LIST-P-2)) (12 12 (:REWRITE USE-ALL-NODE-LIST-P)) (12 12 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (12 12 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (12 12 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (12 6 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (12 2 (:REWRITE ALL-NODE-LIST-P-OF-CDR)) (9 9 (:REWRITE DEFAULT-+-1)) (8 8 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (8 8 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (8 8 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (8 8 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (6 6 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (6 6 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (4 4 (:REWRITE EQUAL-OF-LEN-AND-0)) (2 2 (:TYPE-PRESCRIPTION NODE-LIST-FIX)) ) (PATH-MAP-FIX-WHEN-PATH-MAP-P0 (331 29 (:REWRITE NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0)) (313 29 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0)) (313 26 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (278 28 (:REWRITE CONSP-FROM-LEN-CHEAP)) (192 26 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (141 15 (:REWRITE NODE-LIST-P-OF-CDR)) (90 18 (:REWRITE LEN-OF-CDR)) (74 70 (:REWRITE DEFAULT-CAR)) (57 57 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (54 9 (:REWRITE USE-ALL-NODE-LIST-P-FOR-CAR)) (49 45 (:REWRITE DEFAULT-CDR)) (42 15 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (36 27 (:REWRITE DEFAULT-<-2)) (28 28 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (27 27 (:REWRITE DEFAULT-<-1)) (27 27 (:REWRITE CONSP-WHEN-LEN-GREATER)) (26 26 (:REWRITE USE-ALL-NODE-LIST-P-2)) (26 26 (:REWRITE USE-ALL-NODE-LIST-P)) (26 26 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (26 26 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (26 26 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (22 22 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (22 22 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (22 22 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (22 22 (:LINEAR LEN-WHEN-PREFIXP)) (22 20 (:REWRITE DEFAULT-+-2)) (20 20 (:REWRITE DEFAULT-+-1)) (18 18 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (18 18 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (9 9 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (9 9 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (9 9 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (9 9 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (6 3 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (3 3 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) ) (PATH-MAP-FIX$INLINE (5 5 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (4 1 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (4 1 (:REWRITE NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0)) (4 1 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0)) ) (FTY::TMP-DEFFIXTYPE-IDEMPOTENT (1 1 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) ) (PATH-MAP-EQUIV$INLINE) (PATH-MAP-EQUIV-IS-AN-EQUIVALENCE) (PATH-MAP-EQUIV-IMPLIES-EQUAL-PATH-MAP-FIX-1) (PATH-MAP-FIX-UNDER-PATH-MAP-EQUIV) (EQUAL-OF-PATH-MAP-FIX-1-FORWARD-TO-PATH-MAP-EQUIV) (EQUAL-OF-PATH-MAP-FIX-2-FORWARD-TO-PATH-MAP-EQUIV) (PATH-MAP-EQUIV-OF-PATH-MAP-FIX-1-FORWARD) (PATH-MAP-EQUIV-OF-PATH-MAP-FIX-2-FORWARD) (CONS-OF-DRONE-ID-FIX-K-UNDER-PATH-MAP-EQUIV (27 4 (:REWRITE PATH-MAP-FIX-WHEN-PATH-MAP-P0)) (18 2 (:REWRITE PATH-MAP-P0-OF-CONS)) (6 6 (:TYPE-PRESCRIPTION PATH-MAP-P0)) (6 6 (:TYPE-PRESCRIPTION NODE-LIST-P)) (4 2 (:REWRITE NODE-LIST-FIX-NODE-LIST-P)) (3 3 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) ) (CONS-DRONE-ID-EQUIV-CONGRUENCE-ON-K-UNDER-PATH-MAP-EQUIV) (CONS-OF-NODE-LIST-FIX-V-UNDER-PATH-MAP-EQUIV (31 4 (:REWRITE PATH-MAP-FIX-WHEN-PATH-MAP-P0)) (22 2 (:REWRITE PATH-MAP-P0-OF-CONS)) (10 10 (:TYPE-PRESCRIPTION DRONE-ID-P)) (6 6 (:TYPE-PRESCRIPTION PATH-MAP-P0)) (4 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (3 3 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (2 2 (:TYPE-PRESCRIPTION NODE-LIST-FIX)) ) (CONS-NODE-LIST-EQUIV-CONGRUENCE-ON-V-UNDER-PATH-MAP-EQUIV) (CONS-OF-PATH-MAP-FIX-Y-UNDER-PATH-MAP-EQUIV (18 2 (:REWRITE PATH-MAP-P0-OF-CONS)) (11 11 (:TYPE-PRESCRIPTION DRONE-ID-P)) (9 9 (:TYPE-PRESCRIPTION NODE-LIST-P)) (6 2 (:REWRITE NODE-LIST-FIX-NODE-LIST-P)) (6 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (4 4 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) ) (CONS-PATH-MAP-EQUIV-CONGRUENCE-ON-Y-UNDER-PATH-MAP-EQUIV) (PATH-MAP-FIX-OF-ACONS (17 3 (:REWRITE PATH-MAP-FIX-WHEN-PATH-MAP-P0)) (10 1 (:REWRITE PATH-MAP-P0-OF-CONS)) (5 5 (:TYPE-PRESCRIPTION DRONE-ID-P)) (4 4 (:TYPE-PRESCRIPTION PATH-MAP-P0)) (4 4 (:TYPE-PRESCRIPTION NODE-LIST-P)) (4 2 (:REWRITE NODE-LIST-FIX-NODE-LIST-P)) (4 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (2 2 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) ) (PATH-MAP-FIX-OF-APPEND (143 19 (:REWRITE PATH-MAP-FIX-WHEN-PATH-MAP-P0)) (61 61 (:TYPE-PRESCRIPTION PATH-MAP-P0)) (49 31 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (22 4 (:REWRITE NODE-LIST-FIX-NODE-LIST-P)) (22 4 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (21 1 (:REWRITE PATH-MAP-P0-OF-CONS)) (20 5 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (16 4 (:REWRITE NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0)) (16 4 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0)) (9 9 (:TYPE-PRESCRIPTION DRONE-ID-P)) (8 8 (:TYPE-PRESCRIPTION NODE-LIST-P)) ) (CONSP-CAR-OF-PATH-MAP-FIX (50 10 (:REWRITE PATH-MAP-FIX-WHEN-PATH-MAP-P0)) (31 31 (:TYPE-PRESCRIPTION PATH-MAP-P0)) (20 5 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (16 16 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (14 2 (:REWRITE NODE-LIST-FIX-NODE-LIST-P)) (14 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (8 2 (:REWRITE NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0)) (8 2 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0)) (4 4 (:TYPE-PRESCRIPTION NODE-LIST-P)) (4 4 (:TYPE-PRESCRIPTION DRONE-ID-P)) (1 1 (:TYPE-PRESCRIPTION NODE-LIST-FIX)) ) (PATH-MAP-P) (BOOLEANP-OF-PATH-MAP-P) (PATH-MAP-PAIR-P) (BOOLEANP-OF-PATH-MAP-PAIR-P) (DRONE-ID-LIST-P-ALIST-KEYS-PATH-MAP (3319 81 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NO-DUPLICATESP-EQUAL-OF-CDR)) (2084 130 (:REWRITE CONSP-FROM-LEN-CHEAP)) (1060 4 (:REWRITE NO-DUPLICATESP-EQUAL-OF-CONS-NO-SPLIT)) (953 57 (:REWRITE NO-DUPLICATESP-EQUAL-OF-CDR)) (936 6 (:REWRITE NO-DUPLICATE-ALIST-CAAR-ALIST-KEYS-CDR)) (830 43 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (794 16 (:DEFINITION HONS-ASSOC-EQUAL)) (639 37 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (561 116 (:REWRITE DEFAULT-CDR)) (369 42 (:REWRITE LEN-OF-CDR)) (312 27 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (304 20 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (270 211 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (248 248 (:TYPE-PRESCRIPTION MEMBER-EQUAL)) (187 98 (:REWRITE DEFAULT-<-2)) (182 91 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (182 91 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (148 148 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (148 148 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (148 148 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (148 148 (:LINEAR LEN-WHEN-PREFIXP)) (130 130 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (128 64 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (128 64 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (128 64 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (127 127 (:REWRITE DEFAULT-CAR)) (108 108 (:REWRITE CONSP-WHEN-LEN-GREATER)) (108 81 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NOT-CONSP-CHEAP)) (105 91 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (100 50 (:REWRITE MEMBER-EQUAL-OF-CAR-SAME)) (98 98 (:REWRITE DEFAULT-<-1)) (91 91 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (91 91 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (91 91 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (90 7 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (88 28 (:REWRITE EQUAL-OF-LEN-AND-0)) (85 85 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL)) (74 64 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (70 42 (:REWRITE DEFAULT-+-2)) (64 64 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (64 64 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (64 64 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (64 64 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (64 64 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (64 64 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (64 64 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (52 26 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (42 42 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (42 42 (:REWRITE DEFAULT-+-1)) (42 42 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (32 16 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (27 27 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (27 27 (:REWRITE MEMBERP-OF-CAR-SAME)) (16 16 (:DEFINITION HONS-EQUAL)) (4 4 (:TYPE-PRESCRIPTION NO-DUPLICATE-ALIST-P)) ) (PATH-MAP-P-ALIST) (PATH-MAP-NON-EMPTY-PATHS-P0) (BOOLEANP-OF-PATH-MAP-NON-EMPTY-PATHS-P0) (PATH-MAP-NON-EMPTY-PATHS-P) (BOOLEANP-OF-PATH-MAP-NON-EMPTY-PATHS-P) (PLAN-MAP-PAIR-P) (BOOLEANP-OF-PLAN-MAP-PAIR-P) (TMP-DEFTYPES-ALL-NODE-LIST-P-OF-ALL-NODE-LIST-FIX (71 3 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (56 3 (:REWRITE CONSP-FROM-LEN-CHEAP)) (15 15 (:TYPE-PRESCRIPTION LEN)) (6 6 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (6 6 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (6 6 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (6 6 (:LINEAR LEN-WHEN-PREFIXP)) (6 3 (:REWRITE DEFAULT-<-2)) (4 3 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (4 3 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (4 3 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (3 3 (:REWRITE DEFAULT-<-1)) (3 3 (:REWRITE CONSP-WHEN-LEN-GREATER)) (3 3 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (3 3 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) ) (TMP-DEFTYPES-ALL-NODE-LIST-FIX-WHEN-ALL-NODE-LIST-P (42 2 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (36 2 (:REWRITE CONSP-FROM-LEN-CHEAP)) (19 19 (:TYPE-PRESCRIPTION ALL-NODE-LIST-FIX)) (10 10 (:TYPE-PRESCRIPTION LEN)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (4 4 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (4 4 (:LINEAR LEN-WHEN-PREFIXP)) (4 2 (:REWRITE DEFAULT-<-2)) (2 2 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (2 2 (:REWRITE DEFAULT-<-1)) (2 2 (:REWRITE CONSP-WHEN-LEN-GREATER)) (2 2 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (2 2 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (2 2 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (2 2 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) ) (PLAN-MAP-P0) (BOOLEANP-OF-DRONE-ID-P-FOR-PLAN-MAP-P0-KEY-LEMMA) (BOOLEANP-OF-ALL-NODE-LIST-P-FOR-PLAN-MAP-P0-VAL-LEMMA) (BOOLEANP-OF-DRONE-ID-P-FOR-PLAN-MAP-P0-KEY) (BOOLEANP-OF-ALL-NODE-LIST-P-FOR-PLAN-MAP-P0-VAL) (PLAN-MAP-P0-OF-REV) (PLAN-MAP-P0-OF-LIST-FIX) (TRUE-LISTP-WHEN-PLAN-MAP-P0) (PLAN-MAP-P0-WHEN-NOT-CONSP) (PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0) (PLAN-MAP-P0-OF-CONS) (PLAN-MAP-P0-OF-REMOVE-ASSOC (56 10 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (16 16 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) ) (PLAN-MAP-P0-OF-PUT-ASSOC) (PLAN-MAP-P0-OF-FAST-ALIST-CLEAN) (PLAN-MAP-P0-OF-HONS-SHRINK-ALIST) (PLAN-MAP-P0-OF-HONS-ACONS) (ALL-NODE-LIST-P-OF-CDR-OF-HONS-ASSOC-EQUAL-WHEN-PLAN-MAP-P0) (ALISTP-WHEN-PLAN-MAP-P0-REWRITE) (ALISTP-WHEN-PLAN-MAP-P0) (ALL-NODE-LIST-P-OF-CDAR-WHEN-PLAN-MAP-P0) (DRONE-ID-P-OF-CAAR-WHEN-PLAN-MAP-P0) (PLAN-MAP-FIX$INLINE (2 2 (:TYPE-PRESCRIPTION ALL-NODE-LIST-FIX)) (1 1 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) ) (PLAN-MAP-P0-OF-PLAN-MAP-FIX (349 24 (:REWRITE CONSP-FROM-LEN-CHEAP)) (254 7 (:REWRITE TMP-DEFTYPES-ALL-NODE-LIST-FIX-WHEN-ALL-NODE-LIST-P)) (241 7 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (185 8 (:DEFINITION PLAN-MAP-P0)) (183 15 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PLAN-MAP-P0)) (180 16 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (130 12 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (119 40 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (81 19 (:REWRITE ALL-NODE-LIST-P-OF-CDAR-WHEN-PLAN-MAP-P0)) (56 48 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (52 8 (:REWRITE LEN-OF-CDR)) (46 46 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (40 10 (:REWRITE ALL-NODE-LIST-P-OF-CDR)) (36 20 (:REWRITE DEFAULT-<-2)) (34 34 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (34 34 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (34 34 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (34 34 (:LINEAR LEN-WHEN-PREFIXP)) (32 32 (:REWRITE DEFAULT-CAR)) (32 6 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0)) (30 30 (:TYPE-PRESCRIPTION DRONE-ID-P)) (28 4 (:DEFINITION ALL-NODE-LIST-FIX)) (26 26 (:REWRITE DEFAULT-CDR)) (24 24 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (24 6 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (20 20 (:REWRITE DEFAULT-<-1)) (20 20 (:REWRITE CONSP-WHEN-LEN-GREATER)) (16 16 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (16 16 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (14 9 (:REWRITE DEFAULT-+-2)) (12 6 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (9 9 (:REWRITE DEFAULT-+-1)) (8 8 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (8 8 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (8 2 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (6 6 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (6 6 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (4 4 (:REWRITE EQUAL-OF-LEN-AND-0)) (2 2 (:TYPE-PRESCRIPTION ALL-NODE-LIST-FIX)) ) (PLAN-MAP-FIX-WHEN-PLAN-MAP-P0 (298 29 (:REWRITE ALL-NODE-LIST-P-OF-CDAR-WHEN-PLAN-MAP-P0)) (292 29 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PLAN-MAP-P0)) (289 26 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (278 28 (:REWRITE CONSP-FROM-LEN-CHEAP)) (192 26 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (90 18 (:REWRITE LEN-OF-CDR)) (74 70 (:REWRITE DEFAULT-CAR)) (60 15 (:REWRITE ALL-NODE-LIST-P-OF-CDR)) (57 57 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (49 45 (:REWRITE DEFAULT-CDR)) (42 15 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (42 15 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0)) (36 27 (:REWRITE DEFAULT-<-2)) (28 28 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (27 27 (:REWRITE DEFAULT-<-1)) (27 27 (:REWRITE CONSP-WHEN-LEN-GREATER)) (26 26 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (26 26 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (22 22 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (22 22 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (22 22 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (22 22 (:LINEAR LEN-WHEN-PREFIXP)) (22 20 (:REWRITE DEFAULT-+-2)) (20 20 (:REWRITE DEFAULT-+-1)) (18 18 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (9 9 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (9 9 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (6 3 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (3 3 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) ) (PLAN-MAP-FIX$INLINE (5 5 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (4 1 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (4 1 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PLAN-MAP-P0)) (4 1 (:REWRITE ALL-NODE-LIST-P-OF-CDAR-WHEN-PLAN-MAP-P0)) ) (FTY::TMP-DEFFIXTYPE-IDEMPOTENT (1 1 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) ) (PLAN-MAP-EQUIV$INLINE) (PLAN-MAP-EQUIV-IS-AN-EQUIVALENCE) (PLAN-MAP-EQUIV-IMPLIES-EQUAL-PLAN-MAP-FIX-1) (PLAN-MAP-FIX-UNDER-PLAN-MAP-EQUIV) (EQUAL-OF-PLAN-MAP-FIX-1-FORWARD-TO-PLAN-MAP-EQUIV) (EQUAL-OF-PLAN-MAP-FIX-2-FORWARD-TO-PLAN-MAP-EQUIV) (PLAN-MAP-EQUIV-OF-PLAN-MAP-FIX-1-FORWARD) (PLAN-MAP-EQUIV-OF-PLAN-MAP-FIX-2-FORWARD) (CONS-OF-DRONE-ID-FIX-K-UNDER-PLAN-MAP-EQUIV (27 4 (:REWRITE PLAN-MAP-FIX-WHEN-PLAN-MAP-P0)) (18 2 (:REWRITE PLAN-MAP-P0-OF-CONS)) (6 6 (:TYPE-PRESCRIPTION PLAN-MAP-P0)) (6 6 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (4 2 (:REWRITE TMP-DEFTYPES-ALL-NODE-LIST-FIX-WHEN-ALL-NODE-LIST-P)) (3 3 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) ) (CONS-DRONE-ID-EQUIV-CONGRUENCE-ON-K-UNDER-PLAN-MAP-EQUIV) (CONS-OF-ALL-NODE-LIST-FIX-V-UNDER-PLAN-MAP-EQUIV (31 4 (:REWRITE PLAN-MAP-FIX-WHEN-PLAN-MAP-P0)) (22 2 (:REWRITE PLAN-MAP-P0-OF-CONS)) (10 10 (:TYPE-PRESCRIPTION DRONE-ID-P)) (6 6 (:TYPE-PRESCRIPTION PLAN-MAP-P0)) (4 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (3 3 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (2 2 (:TYPE-PRESCRIPTION ALL-NODE-LIST-FIX)) ) (CONS-ALL-NODE-LIST-EQUIV-CONGRUENCE-ON-V-UNDER-PLAN-MAP-EQUIV) (CONS-OF-PLAN-MAP-FIX-Y-UNDER-PLAN-MAP-EQUIV (18 2 (:REWRITE PLAN-MAP-P0-OF-CONS)) (11 11 (:TYPE-PRESCRIPTION DRONE-ID-P)) (9 9 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (6 2 (:REWRITE TMP-DEFTYPES-ALL-NODE-LIST-FIX-WHEN-ALL-NODE-LIST-P)) (6 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (4 4 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) ) (CONS-PLAN-MAP-EQUIV-CONGRUENCE-ON-Y-UNDER-PLAN-MAP-EQUIV) (PLAN-MAP-FIX-OF-ACONS (17 3 (:REWRITE PLAN-MAP-FIX-WHEN-PLAN-MAP-P0)) (10 1 (:REWRITE PLAN-MAP-P0-OF-CONS)) (5 5 (:TYPE-PRESCRIPTION DRONE-ID-P)) (4 4 (:TYPE-PRESCRIPTION PLAN-MAP-P0)) (4 4 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (4 2 (:REWRITE TMP-DEFTYPES-ALL-NODE-LIST-FIX-WHEN-ALL-NODE-LIST-P)) (4 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (2 2 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) ) (PLAN-MAP-FIX-OF-APPEND (143 19 (:REWRITE PLAN-MAP-FIX-WHEN-PLAN-MAP-P0)) (61 61 (:TYPE-PRESCRIPTION PLAN-MAP-P0)) (49 31 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (22 4 (:REWRITE TMP-DEFTYPES-ALL-NODE-LIST-FIX-WHEN-ALL-NODE-LIST-P)) (22 4 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (21 1 (:REWRITE PLAN-MAP-P0-OF-CONS)) (20 5 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (16 4 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PLAN-MAP-P0)) (16 4 (:REWRITE ALL-NODE-LIST-P-OF-CDAR-WHEN-PLAN-MAP-P0)) (9 9 (:TYPE-PRESCRIPTION DRONE-ID-P)) (8 8 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) ) (CONSP-CAR-OF-PLAN-MAP-FIX (50 10 (:REWRITE PLAN-MAP-FIX-WHEN-PLAN-MAP-P0)) (31 31 (:TYPE-PRESCRIPTION PLAN-MAP-P0)) (20 5 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (16 16 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (14 2 (:REWRITE TMP-DEFTYPES-ALL-NODE-LIST-FIX-WHEN-ALL-NODE-LIST-P)) (14 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (8 2 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PLAN-MAP-P0)) (8 2 (:REWRITE ALL-NODE-LIST-P-OF-CDAR-WHEN-PLAN-MAP-P0)) (4 4 (:TYPE-PRESCRIPTION DRONE-ID-P)) (4 4 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (1 1 (:TYPE-PRESCRIPTION ALL-NODE-LIST-FIX)) ) (PLAN-MAP-P0-ALIST) (PLAN-MAP-P) (PLAN-MAP-P-CDR (24 3 (:REWRITE CONSP-FROM-LEN-CHEAP)) (20 2 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (12 12 (:TYPE-PRESCRIPTION LEN)) (10 1 (:REWRITE DEFAULT-CDR)) (9 3 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (6 6 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (3 3 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) ) (PLAN-MAP-P-ALIST) (NON-TRIVIAL-PLAN-MAP-P (255 20 (:REWRITE CONSP-FROM-LEN-CHEAP)) (41 12 (:REWRITE DEFAULT-CAR)) (32 5 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (31 16 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (30 2 (:REWRITE LEN-OF-CDR)) (28 28 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (22 11 (:REWRITE DEFAULT-<-2)) (21 3 (:REWRITE DEFAULT-CDR)) (20 20 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (18 18 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (18 18 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (18 18 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (18 18 (:LINEAR LEN-WHEN-PREFIXP)) (16 2 (:REWRITE EQUAL-OF-LEN-AND-0)) (14 7 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (13 13 (:REWRITE CONSP-WHEN-LEN-GREATER)) (11 11 (:REWRITE DEFAULT-<-1)) (10 10 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (6 3 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (4 2 (:REWRITE DEFAULT-+-2)) (2 2 (:REWRITE DEFAULT-+-1)) (2 2 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (NON-TRIVIAL-PLAN-MAP-P-CONS (58 5 (:REWRITE CONSP-FROM-LEN-CHEAP)) (15 1 (:REWRITE LEN-OF-CDR)) (12 3 (:REWRITE DEFAULT-CDR)) (8 1 (:REWRITE EQUAL-OF-LEN-AND-0)) (7 7 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (6 3 (:REWRITE DEFAULT-<-2)) (6 3 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (5 5 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (4 4 (:REWRITE CONSP-WHEN-LEN-GREATER)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (4 4 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (4 4 (:LINEAR LEN-WHEN-PREFIXP)) (3 3 (:REWRITE DEFAULT-<-1)) (2 2 (:REWRITE DEFAULT-CAR)) (2 1 (:REWRITE DEFAULT-+-2)) (2 1 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (1 1 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (1 1 (:REWRITE USE-ALL-NODE-LIST-P-2)) (1 1 (:REWRITE USE-ALL-NODE-LIST-P)) (1 1 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (1 1 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (1 1 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (1 1 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (DRONE-ID-LIST-P-ALIST-KEYS-PLAN-MAP-P (401 29 (:REWRITE CONSP-FROM-LEN-CHEAP)) (150 8 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (144 6 (:REWRITE DRONE-ID-LIST-P-ALIST-KEYS-PATH-MAP)) (132 6 (:DEFINITION PATH-MAP-P)) (90 7 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (86 16 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (68 56 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (52 8 (:REWRITE LEN-OF-CDR)) (30 17 (:REWRITE DEFAULT-<-2)) (29 29 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (26 26 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (26 26 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (26 26 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (26 26 (:LINEAR LEN-WHEN-PREFIXP)) (20 8 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (17 17 (:REWRITE DEFAULT-<-1)) (17 17 (:REWRITE CONSP-WHEN-LEN-GREATER)) (12 12 (:REWRITE DEFAULT-CAR)) (12 8 (:REWRITE DEFAULT-+-2)) (8 8 (:REWRITE DEFAULT-+-1)) (8 8 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (8 4 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (6 6 (:TYPE-PRESCRIPTION PATH-MAP-P)) (4 4 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (4 4 (:REWRITE NO-DUPLICATE-ALIST-CDR)) (4 4 (:REWRITE EQUAL-OF-LEN-AND-0)) (4 4 (:REWRITE DEFAULT-CDR)) ) (PLAN-FOR-ID-EQUAL-P) (BOOLEANP-OF-PLAN-FOR-ID-EQUAL-P) (PLAN-FOR-ID-EQUAL-P-REFLEXIVE) (PLAN-FOR-ID-SUBSET-P (6852 39 (:DEFINITION TRUE-LISTP)) (6545 105 (:REWRITE NODE-LIST-P-TRUE-LISTP1)) (5127 73 (:REWRITE TRUE-LISTP-OF-CDR-0)) (4792 319 (:REWRITE CONSP-FROM-LEN-CHEAP)) (4581 164 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (1950 86 (:REWRITE NODE-LIST-P-OF-CDR)) (999 114 (:REWRITE LEN-OF-CDR)) (902 105 (:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP)) (491 431 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (436 219 (:REWRITE DEFAULT-<-2)) (434 12 (:REWRITE TRUE-LISTP-OF-CAR-WHEN-TRUE-LIST-LISTP)) (410 6 (:DEFINITION TRUE-LIST-LISTP)) (405 265 (:REWRITE DEFAULT-CDR)) (392 48 (:REWRITE NODE-LIST-P-OF-CDR-OF-HONS-ASSOC-EQUAL-WHEN-PATH-MAP-P0)) (338 338 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (338 338 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (338 338 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (338 338 (:LINEAR LEN-WHEN-PREFIXP)) (328 328 (:TYPE-PRESCRIPTION NODE-LIST-P)) (319 319 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (284 284 (:REWRITE CONSP-WHEN-LEN-GREATER)) (280 280 (:REWRITE DEFAULT-CAR)) (248 164 (:REWRITE USE-ALL-NODE-LIST-P)) (244 60 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (219 219 (:REWRITE DEFAULT-<-1)) (210 58 (:REWRITE EQUAL-OF-LEN-AND-0)) (204 164 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (199 131 (:REWRITE DEFAULT-+-2)) (190 190 (:TYPE-PRESCRIPTION SET::SETP-TYPE)) (190 95 (:REWRITE OMAP::SETP-WHEN-MAPP)) (190 95 (:REWRITE SET::NONEMPTY-MEANS-SET)) (164 164 (:REWRITE USE-ALL-NODE-LIST-P-2)) (164 164 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (164 164 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (131 131 (:REWRITE DEFAULT-+-1)) (130 65 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (95 95 (:TYPE-PRESCRIPTION OMAP::MAPP)) (95 95 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE)) (95 95 (:REWRITE SET::IN-SET)) (91 91 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (90 12 (:REWRITE TRUE-LIST-LISTP-WHEN-NOT-CONSP)) (66 16 (:REWRITE USE-ALL-NODE-LIST-P-FOR-CAR)) (65 65 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (53 15 (:REWRITE FOLD-CONSTS-IN-+)) (43 13 (:REWRITE NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0)) (43 12 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (40 10 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (24 24 (:TYPE-PRESCRIPTION MEMBERP)) (23 23 (:REWRITE LEN-OF-CDDR-WHEN-EQUAL-OF-LEN)) (12 12 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (12 12 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (12 6 (:REWRITE TRUE-LIST-LISTP-OF-CDR-WHEN-TRUE-LIST-LISTP)) (12 6 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (12 6 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (12 6 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (6 6 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (6 6 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (6 6 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (6 6 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (6 6 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (6 6 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (6 2 (:REWRITE NO-DUPLICATE-ALIST-CONS)) ) (BOOLEANP-OF-PLAN-FOR-ID-SUBSET-P) (PLAN-FOR-ID-SUBSET-P-REFLEXIVE (177 1 (:REWRITE SUBLISTP-NOT-PREFIXP)) (135 12 (:REWRITE CONSP-FROM-LEN-CHEAP)) (105 2 (:REWRITE PREFIXP-WHEN-PREFIXP)) (100 2 (:DEFINITION HONS-ASSOC-EQUAL)) (87 2 (:REWRITE PREFIXP-WHEN-EQUAL-LENGTHS)) (67 3 (:REWRITE LEN-OF-CDR)) (58 58 (:TYPE-PRESCRIPTION LEN)) (42 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-RIGHT)) (40 3 (:REWRITE EQUAL-OF-LEN-AND-0)) (23 15 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (20 6 (:REWRITE DEFAULT-CDR)) (18 8 (:REWRITE DEFAULT-<-2)) (15 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-LEFT)) (12 12 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (11 11 (:REWRITE CONSP-WHEN-LEN-GREATER)) (11 8 (:REWRITE DEFAULT-<-1)) (11 6 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (10 10 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (10 10 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (10 10 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (10 10 (:LINEAR LEN-WHEN-PREFIXP)) (8 8 (:REWRITE DEFAULT-CAR)) (6 3 (:REWRITE DEFAULT-+-2)) (6 3 (:DEFINITION NOT)) (6 2 (:REWRITE SUFFIXP-SUBLISTP)) (5 5 (:TYPE-PRESCRIPTION PREFIXP)) (5 1 (:REWRITE SUFFIXP$-OF-CDR)) (4 4 (:TYPE-PRESCRIPTION SUFFIXP)) (4 2 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (3 3 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (3 3 (:REWRITE SUFFIXP$-TRANSITIVE)) (3 3 (:REWRITE DEFAULT-+-1)) (2 2 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (2 2 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (2 2 (:REWRITE SUBLISTP-TRANSITIVE)) (2 2 (:REWRITE PREFIXP-TRANSITIVE-1)) (2 2 (:REWRITE PREFIXP-TRANSITIVE . 2)) (2 2 (:REWRITE PREFIXP-TRANSITIVE . 1)) (2 2 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 2)) (2 2 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 1)) (2 2 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (2 2 (:DEFINITION HONS-EQUAL)) ) (SUBSET-FOR-MAP-ELTS (60 7 (:REWRITE CONSP-FROM-LEN-CHEAP)) (40 4 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (17 4 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (16 6 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (14 14 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (7 7 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (5 3 (:REWRITE DEFAULT-<-2)) (5 1 (:REWRITE LEN-OF-CDR)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (4 4 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (4 4 (:LINEAR LEN-WHEN-PREFIXP)) (3 3 (:REWRITE DEFAULT-<-1)) (3 3 (:REWRITE CONSP-WHEN-LEN-GREATER)) (2 2 (:REWRITE DEFAULT-CAR)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-+-2)) (1 1 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (SUBSET-FOR-MAP-ELTS-OF-CONS) (USE-SUBSET-FOR-MAP-ELTS-FOR-CAR) (USE-SUBSET-FOR-MAP-ELTS-FOR-CAR-OF-LAST) (SUBSET-FOR-MAP-ELTS-OF-APPEND) (SUBSET-FOR-MAP-ELTS-OF-UNION-EQUAL) (SUBSET-FOR-MAP-ELTS-WHEN-NOT-CONSP) (SUBSET-FOR-MAP-ELTS-WHEN-NOT-CONSP-CHEAP) (SUBSET-FOR-MAP-ELTS-OF-REVAPPEND) (SUBSET-FOR-MAP-ELTS-OF-CDR) (SUBSET-FOR-MAP-ELTS-OF-NTHCDR) (SUBSET-FOR-MAP-ELTS-OF-FIRSTN) (SUBSET-FOR-MAP-ELTS-OF-REMOVE1-EQUAL) (SUBSET-FOR-MAP-ELTS-OF-REMOVE-EQUAL) (SUBSET-FOR-MAP-ELTS-OF-LAST) (SUBSET-FOR-MAP-ELTS-OF-TAKE) (TRUE-LISTP-WHEN-SUBSET-FOR-MAP-ELTS) (TRUE-LISTP-WHEN-SUBSET-FOR-MAP-ELTS-FORWARD) (SUBSET-FOR-MAP-ELTS-WHEN-PERM) (SUBSET-FOR-MAP-ELTS-OF-TRUE-LIST-FIX) (USE-SUBSET-FOR-MAP-ELTS) (USE-SUBSET-FOR-MAP-ELTS-2) (SUBSET-FOR-MAP-ELTS-OF-ADD-TO-SET-EQUAL) (SUBSET-FOR-MAP-ELTS-REFL (156 12 (:REWRITE CONSP-FROM-LEN-CHEAP)) (114 10 (:REWRITE SUBSET-FOR-MAP-ELTS-WHEN-NOT-CONSP)) (21 9 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (21 3 (:REWRITE LEN-OF-CDR)) (19 19 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (18 4 (:REWRITE USE-SUBSET-FOR-MAP-ELTS)) (15 8 (:REWRITE DEFAULT-<-2)) (14 14 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (14 14 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (14 14 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (14 14 (:LINEAR LEN-WHEN-PREFIXP)) (12 12 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (12 2 (:REWRITE SUBSET-FOR-MAP-ELTS-OF-CDR)) (10 10 (:REWRITE CONSP-WHEN-LEN-GREATER)) (8 8 (:REWRITE DEFAULT-<-1)) (5 5 (:REWRITE DEFAULT-CDR)) (5 3 (:REWRITE DEFAULT-+-2)) (4 4 (:TYPE-PRESCRIPTION MEMBERP)) (4 4 (:REWRITE USE-SUBSET-FOR-MAP-ELTS-2)) (4 4 (:REWRITE DEFAULT-CAR)) (3 3 (:REWRITE DEFAULT-+-1)) (3 3 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (2 2 (:REWRITE EQUAL-OF-LEN-AND-0)) (2 1 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (2 1 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (2 1 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (1 1 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (1 1 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (1 1 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (1 1 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (1 1 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (1 1 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) ) (SUB-PLAN-MAP-P) (BOOLEANP-OF-SUB-PLAN-MAP-P) (SUB-PLAN-MAP-P-REFLEXIVE (24 3 (:REWRITE CONSP-FROM-LEN-CHEAP)) (20 2 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (12 12 (:TYPE-PRESCRIPTION LEN)) (10 1 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (9 3 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (6 6 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (3 3 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) ) (SUB-PLAN-MAP-P-HYPS) (SUB-PLAN-MAP-P-SUB) (SUB-PLAN-MAP-P-SUPER) (SUB-PLAN-MAP-P-MEMBERSHIP-CONSTRAINT) (SUB-PLAN-MAP-P-BADGUY-AUX (60 7 (:REWRITE CONSP-FROM-LEN-CHEAP)) (40 4 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (17 4 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (16 6 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (14 14 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (7 7 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (5 3 (:REWRITE DEFAULT-<-2)) (5 1 (:REWRITE USE-SUBSET-FOR-MAP-ELTS-FOR-CAR)) (5 1 (:REWRITE LEN-OF-CDR)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (4 4 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (4 4 (:LINEAR LEN-WHEN-PREFIXP)) (3 3 (:REWRITE DEFAULT-<-1)) (3 3 (:REWRITE CONSP-WHEN-LEN-GREATER)) (2 2 (:TYPE-PRESCRIPTION SUBSET-FOR-MAP-ELTS)) (2 2 (:REWRITE DEFAULT-CAR)) (1 1 (:REWRITE USE-SUBSET-FOR-MAP-ELTS-2)) (1 1 (:REWRITE USE-SUBSET-FOR-MAP-ELTS)) (1 1 (:REWRITE SUBSET-FOR-MAP-ELTS-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE SUBSET-FOR-MAP-ELTS-WHEN-NOT-CONSP)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-+-2)) (1 1 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (SUB-PLAN-MAP-P-BADGUY-AUX-WITNESS (269 18 (:REWRITE CONSP-FROM-LEN-CHEAP)) (210 10 (:REWRITE NODE-LIST-P-TRUE-LISTP1)) (121 17 (:REWRITE SUBSET-FOR-MAP-ELTS-WHEN-NOT-CONSP)) (115 11 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (80 10 (:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP)) (51 23 (:REWRITE USE-SUBSET-FOR-MAP-ELTS)) (42 2 (:REWRITE TRUE-LISTP-OF-CDR-0)) (32 4 (:REWRITE LEN-OF-CDR)) (29 14 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (28 28 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (28 28 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (28 28 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (28 28 (:LINEAR LEN-WHEN-PREFIXP)) (28 14 (:REWRITE DEFAULT-<-2)) (25 25 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (23 23 (:TYPE-PRESCRIPTION NODE-LIST-P)) (23 23 (:REWRITE USE-SUBSET-FOR-MAP-ELTS-2)) (21 21 (:REWRITE DEFAULT-CAR)) (20 20 (:TYPE-PRESCRIPTION SET::SETP-TYPE)) (20 10 (:REWRITE OMAP::SETP-WHEN-MAPP)) (20 10 (:REWRITE SET::NONEMPTY-MEANS-SET)) (18 18 (:REWRITE CONSP-WHEN-LEN-GREATER)) (18 18 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (18 2 (:REWRITE NODE-LIST-P-OF-CDR)) (14 14 (:REWRITE DEFAULT-<-1)) (12 12 (:REWRITE USE-ALL-NODE-LIST-P-2)) (12 12 (:REWRITE USE-ALL-NODE-LIST-P)) (12 12 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (12 12 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (12 12 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (12 2 (:REWRITE SUBSET-FOR-MAP-ELTS-OF-CDR)) (10 10 (:TYPE-PRESCRIPTION OMAP::MAPP)) (10 10 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE)) (10 10 (:REWRITE SET::IN-SET)) (10 10 (:REWRITE DEFAULT-CDR)) (8 8 (:TYPE-PRESCRIPTION MEMBERP)) (8 4 (:REWRITE DEFAULT-+-2)) (4 4 (:REWRITE EQUAL-OF-LEN-AND-0)) (4 4 (:REWRITE DEFAULT-+-1)) (4 4 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (4 2 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (4 2 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (4 2 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (2 2 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (2 2 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (2 2 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (2 2 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (2 2 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (2 2 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) ) (SUB-PLAN-MAP-P-BADGUY) (SUB-PLAN-MAP-P-BADGUY-WITNESS (36 3 (:REWRITE CONSP-FROM-LEN-CHEAP)) (27 1 (:REWRITE SUBSET-FOR-MAP-ELTS-WHEN-NOT-CONSP)) (21 3 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (13 13 (:TYPE-PRESCRIPTION LEN)) (8 3 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (6 5 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (3 3 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (2 2 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (2 2 (:LINEAR LEN-WHEN-PREFIXP)) (2 1 (:REWRITE SUBSET-FOR-MAP-ELTS-WHEN-NOT-CONSP-CHEAP)) (2 1 (:REWRITE DEFAULT-<-2)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:REWRITE CONSP-WHEN-LEN-GREATER)) ) (SUB-PLAN-MAP-P-BY-MEMBERSHIP-DRIVER) (ADVISER-SUB-PLAN-MAP-P-TRIGGER) (SUB-PLAN-MAP-P-BY-MEMBERSHIP-ANY) (SUB-PLAN-MAP-P-BY-MEMBERSHIP) (TRUE-ALISTP) (BOOLEANP-OF-TRUE-ALISTP) (TRUE-ALISTP-IMPLIES-CONS-OR-NIL) (TRUE-ALISTP-CDR (508 7 (:REWRITE TRUE-LISTP-OF-CDR-0)) (433 8 (:REWRITE TRUE-LISTP-OF-CAR-WHEN-TRUE-LIST-LISTP)) (427 4 (:DEFINITION TRUE-LIST-LISTP)) (422 5 (:DEFINITION TRUE-LISTP)) (342 15 (:REWRITE NODE-LIST-P-TRUE-LISTP1)) (234 16 (:REWRITE CONSP-FROM-LEN-CHEAP)) (171 12 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (108 8 (:REWRITE TRUE-LIST-LISTP-WHEN-NOT-CONSP)) (99 15 (:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP)) (93 15 (:REWRITE LEN-OF-CDR)) (65 5 (:REWRITE NODE-LIST-P-OF-CDR)) (50 7 (:REWRITE USE-ALL-NODE-LIST-P-FOR-CAR)) (33 33 (:TYPE-PRESCRIPTION TRUE-LISTP)) (30 30 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (24 24 (:TYPE-PRESCRIPTION SET::SETP-TYPE)) (24 24 (:TYPE-PRESCRIPTION NODE-LIST-P)) (24 12 (:REWRITE OMAP::SETP-WHEN-MAPP)) (24 12 (:REWRITE SET::NONEMPTY-MEANS-SET)) (23 18 (:REWRITE DEFAULT-+-2)) (20 20 (:REWRITE DEFAULT-CDR)) (19 12 (:REWRITE DEFAULT-<-2)) (18 18 (:REWRITE DEFAULT-+-1)) (18 3 (:REWRITE ALL-NODE-LIST-P-OF-CDR)) (17 4 (:REWRITE NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0)) (16 16 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (16 16 (:REWRITE CONSP-WHEN-LEN-GREATER)) (16 16 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (13 13 (:REWRITE DEFAULT-CAR)) (13 6 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (12 12 (:TYPE-PRESCRIPTION OMAP::MAPP)) (12 12 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE)) (12 12 (:REWRITE USE-ALL-NODE-LIST-P-2)) (12 12 (:REWRITE USE-ALL-NODE-LIST-P)) (12 12 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (12 12 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (12 12 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (12 12 (:REWRITE SET::IN-SET)) (12 12 (:REWRITE DEFAULT-<-1)) (12 12 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (12 12 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (12 12 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (12 12 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (12 12 (:LINEAR LEN-WHEN-PREFIXP)) (12 6 (:REWRITE TRUE-LIST-LISTP-OF-CDR-WHEN-TRUE-LIST-LISTP)) (10 3 (:REWRITE FOLD-CONSTS-IN-+)) (8 8 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (8 8 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (8 8 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (8 4 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (4 4 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (4 4 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (4 4 (:REWRITE EQUAL-OF-LEN-AND-0)) (4 1 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (3 3 (:REWRITE LEN-OF-CDDR-WHEN-EQUAL-OF-LEN)) ) (TRUE-ALISTP-CAR (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (2 2 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (2 2 (:LINEAR LEN-WHEN-PREFIXP)) (2 1 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (1 1 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE DEFAULT-CAR)) ) (TRUE-ALISTP-CDAR (18 1 (:REWRITE CONSP-FROM-LEN-CHEAP)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (4 4 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (4 4 (:LINEAR LEN-WHEN-PREFIXP)) (4 1 (:REWRITE TRUE-ALISTP-CAR)) (3 2 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (2 2 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (2 2 (:REWRITE DEFAULT-CAR)) (2 1 (:REWRITE DEFAULT-<-2)) (2 1 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (1 1 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:REWRITE CONSP-WHEN-LEN-GREATER)) (1 1 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) ) (COLLECT-LOCS (22 5 (:REWRITE CONSP-FROM-LEN-CHEAP)) (5 5 (:TYPE-PRESCRIPTION LEN)) (5 5 (:REWRITE CONSP-WHEN-LEN-GREATER)) (5 5 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (3 3 (:REWRITE DEFAULT-CAR)) (3 2 (:REWRITE DEFAULT-CDR)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (2 2 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (2 2 (:LINEAR LEN-WHEN-PREFIXP)) (2 1 (:REWRITE DEFAULT-<-2)) (1 1 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) ) (MAX-PLAN-LENGTH (24 7 (:REWRITE CONSP-FROM-LEN-CHEAP)) (7 7 (:REWRITE CONSP-WHEN-LEN-GREATER)) (7 7 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (5 5 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (5 5 (:REWRITE DEFAULT-CAR)) (5 3 (:REWRITE DEFAULT-CDR)) (4 3 (:REWRITE DEFAULT-<-2)) (4 3 (:REWRITE DEFAULT-<-1)) (4 2 (:REWRITE DEFAULT-+-2)) (2 2 (:REWRITE DEFAULT-+-1)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (2 2 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (2 2 (:LINEAR LEN-WHEN-PREFIXP)) (1 1 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) ) (NATP-OF-MAX-PLAN-LENGTH (258 197 (:REWRITE DEFAULT-<-2)) (225 197 (:REWRITE DEFAULT-<-1)) (164 164 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (142 142 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (142 142 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (142 142 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (142 142 (:LINEAR LEN-WHEN-PREFIXP)) (95 83 (:REWRITE DEFAULT-CDR)) (85 31 (:REWRITE TRUE-ALISTP-CAR)) (74 74 (:REWRITE DEFAULT-CAR)) (69 69 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (68 41 (:REWRITE DEFAULT-+-2)) (61 61 (:REWRITE CONSP-WHEN-LEN-GREATER)) (54 54 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (46 23 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (41 41 (:REWRITE DEFAULT-+-1)) (23 23 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (15 15 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) ) (PRINT-PLAN-STATS (96 1 (:DEFINITION REMOVE-DUPLICATES-EQUAL)) (32 1 (:REWRITE MEMBER-EQUAL-BECOMES-MEMBERP)) (20 1 (:REWRITE CONSP-FROM-LEN-CHEAP)) (17 1 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (16 8 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (12 1 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (12 1 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (8 8 (:TYPE-PRESCRIPTION MEMBER-EQUAL)) (6 6 (:TYPE-PRESCRIPTION MEMBERP)) (6 3 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (6 3 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (4 2 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (4 2 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (4 2 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (4 2 (:REWRITE MEMBER-EQUAL-OF-CAR-SAME)) (4 2 (:REWRITE DEFAULT-UNARY-MINUS)) (3 3 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (3 3 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (3 3 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (3 3 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (3 3 (:REWRITE DEFAULT-CDR)) (2 2 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (2 2 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (2 2 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (2 2 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (2 2 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (2 2 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (2 2 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (2 2 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (2 2 (:REWRITE DEFAULT-CAR)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (2 2 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (2 2 (:LINEAR LEN-WHEN-PREFIXP)) (2 1 (:REWRITE DEFAULT-<-2)) (2 1 (:REWRITE DEFAULT-+-2)) (2 1 (:REWRITE DEFAULT-+-1)) (2 1 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (1 1 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (1 1 (:REWRITE MEMBERP-OF-CAR-SAME)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:REWRITE CONSP-WHEN-LEN-GREATER)) (1 1 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) ) (NODEP-CAR-LAST-NODE-LIST) (DESTINATION-OF-PATH (72 4 (:REWRITE CONSP-FROM-LEN-CHEAP)) (21 1 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (20 20 (:TYPE-PRESCRIPTION LEN)) (8 8 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (8 8 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (8 8 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (8 8 (:LINEAR LEN-WHEN-PREFIXP)) (8 4 (:REWRITE DEFAULT-<-2)) (4 4 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (4 4 (:REWRITE DEFAULT-<-1)) (4 4 (:REWRITE CONSP-WHEN-LEN-GREATER)) (4 4 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (4 4 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (2 2 (:REWRITE USE-ALL-NODE-LIST-P-2)) (2 2 (:REWRITE USE-ALL-NODE-LIST-P)) (2 2 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (2 2 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) ) (NODEP-OF-DESTINATION-OF-PATH (66 3 (:REWRITE CONSP-FROM-LEN-CHEAP)) (34 1 (:DEFINITION LAST)) (29 1 (:REWRITE NODE-LIST-FIX-NODE-LIST-P)) (21 1 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (19 19 (:TYPE-PRESCRIPTION LEN)) (8 8 (:TYPE-PRESCRIPTION NODE-LIST-FIX)) (8 1 (:REWRITE LEN-OF-CDR)) (7 3 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (6 6 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (6 6 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (6 6 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (6 6 (:LINEAR LEN-WHEN-PREFIXP)) (6 5 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (6 3 (:REWRITE DEFAULT-<-2)) (4 4 (:TYPE-PRESCRIPTION NODE-LIST-P)) (4 2 (:TYPE-PRESCRIPTION NODEP-CAR-LAST-NODE-LIST)) (3 3 (:REWRITE DEFAULT-<-1)) (3 3 (:REWRITE CONSP-WHEN-LEN-GREATER)) (3 3 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (2 2 (:REWRITE DEFAULT-CDR)) (2 1 (:REWRITE DEFAULT-CAR)) (2 1 (:REWRITE DEFAULT-+-2)) (1 1 (:REWRITE USE-NODE-LIST-P-2)) (1 1 (:REWRITE USE-NODE-LIST-P)) (1 1 (:REWRITE USE-ALL-NODE-LIST-P-2)) (1 1 (:REWRITE USE-ALL-NODE-LIST-P)) (1 1 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (1 1 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (1 1 (:REWRITE NODE-OF-DGRAPH-P-NODEP)) (1 1 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE EQUAL-OF-LEN-AND-0)) (1 1 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (DESTINATIONS-OF-PATHS (108 6 (:REWRITE CONSP-FROM-LEN-CHEAP)) (31 31 (:TYPE-PRESCRIPTION LEN)) (23 3 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (12 12 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (12 12 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (12 12 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (12 12 (:LINEAR LEN-WHEN-PREFIXP)) (12 6 (:REWRITE DEFAULT-<-2)) (6 6 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (6 6 (:REWRITE DEFAULT-<-1)) (6 6 (:REWRITE CONSP-WHEN-LEN-GREATER)) (6 6 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (6 6 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (5 5 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (2 1 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (2 1 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (2 1 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (1 1 (:REWRITE USE-ALL-NODE-LIST-P-2)) (1 1 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (1 1 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (1 1 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (1 1 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (1 1 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (1 1 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (1 1 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (1 1 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-CAR)) ) (NODE-LIST-P-OF-DESTINATIONS-OF-PATHS (252 15 (:REWRITE CONSP-FROM-LEN-CHEAP)) (211 9 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (30 15 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (29 19 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (28 28 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (28 28 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (28 28 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (28 28 (:LINEAR LEN-WHEN-PREFIXP)) (28 14 (:REWRITE DEFAULT-<-2)) (18 9 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (15 15 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (15 1 (:REWRITE DEFAULT-CAR)) (14 14 (:REWRITE DEFAULT-<-1)) (14 14 (:REWRITE CONSP-WHEN-LEN-GREATER)) (9 9 (:REWRITE USE-ALL-NODE-LIST-P-2)) (9 9 (:REWRITE USE-ALL-NODE-LIST-P)) (9 9 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (9 9 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (2 2 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (1 1 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) ) (FILTER-UNPRODUCTIVE-PLANS (229 17 (:REWRITE CONSP-FROM-LEN-CHEAP)) (105 5 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (38 9 (:REWRITE DEFAULT-CAR)) (30 17 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (25 25 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (24 24 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (24 24 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (24 24 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (24 24 (:LINEAR LEN-WHEN-PREFIXP)) (24 12 (:REWRITE DEFAULT-<-2)) (23 5 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (17 17 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (15 5 (:REWRITE TRUE-ALISTP-CAR)) (13 1 (:REWRITE DEFAULT-CDR)) (12 12 (:REWRITE DEFAULT-<-1)) (12 12 (:REWRITE CONSP-WHEN-LEN-GREATER)) (10 10 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (8 4 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (7 7 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (6 3 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (5 5 (:REWRITE USE-ALL-NODE-LIST-P-2)) (5 5 (:REWRITE USE-ALL-NODE-LIST-P)) (5 5 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (5 5 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (5 5 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) ) (FILTER-UNPRODUCTIVE-PLANS-OF-NIL) (FILTER-UNPRODUCTIVE-PLANS-OF-CONS) (FILTER-UNPRODUCTIVE-PLANS-OF-TRUE-LIST-FIX) (FILTER-UNPRODUCTIVE-PLANS-OPENER) (FILTER-UNPRODUCTIVE-PLANS-OF-APPEND) (CAR-OF-FILTER-UNPRODUCTIVE-PLANS) (CDR-OF-FILTER-UNPRODUCTIVE-PLANS) (LEN-OF-FILTER-UNPRODUCTIVE-PLANS) (CONSP-OF-FILTER-UNPRODUCTIVE-PLANS) (FILTER-UNPRODUCTIVE-PLANS-IFF) (TRUE-LISTP-OF-FILTER-UNPRODUCTIVE-PLANS) (FIRSTN-OF-FILTER-UNPRODUCTIVE-PLANS) (TAKE-OF-FILTER-UNPRODUCTIVE-PLANS) (NTH-OF-FILTER-UNPRODUCTIVE-PLANS) (NTHCDR-OF-FILTER-UNPRODUCTIVE-PLANS) (FILTER-UNPRODUCTIVE-PLANS-PRESERVES-ALIST-KEYS (2421 234 (:REWRITE CONSP-FROM-LEN-CHEAP)) (1130 43 (:REWRITE PATHS-NOT-ENDING-IN-SET-WHEN-NOT-CONSP)) (778 72 (:REWRITE LEN-OF-CDR)) (664 148 (:REWRITE DEFAULT-CAR)) (502 52 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (353 119 (:REWRITE TRUE-ALISTP-CAR)) (342 38 (:REWRITE EQUAL-OF-LEN-AND-0)) (335 335 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (261 17 (:REWRITE CONSP-OF-FILTER-UNPRODUCTIVE-PLANS)) (234 234 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (210 122 (:REWRITE DEFAULT-<-2)) (198 198 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (174 174 (:REWRITE CONSP-WHEN-LEN-GREATER)) (122 122 (:REWRITE DEFAULT-<-1)) (122 61 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (118 76 (:REWRITE DEFAULT-+-2)) (108 36 (:REWRITE TRUE-ALISTP-CDR)) (92 92 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (92 92 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (92 92 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (92 92 (:LINEAR LEN-WHEN-PREFIXP)) (82 82 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (76 76 (:REWRITE DEFAULT-+-1)) (61 61 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (36 36 (:TYPE-PRESCRIPTION FILTER-UNPRODUCTIVE-PLANS)) (24 2 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (6 2 (:REWRITE NO-DUPLICATE-ALIST-CONS)) (2 2 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (2 2 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) ) (NON-TRIVIAL-PLAN-MAP-P-FILTER-UNPRODUCTIVE-PLANS (1838 142 (:REWRITE CONSP-FROM-LEN-CHEAP)) (823 6 (:REWRITE CDR-OF-FILTER-UNPRODUCTIVE-PLANS)) (677 148 (:REWRITE DEFAULT-CAR)) (564 164 (:REWRITE DEFAULT-CDR)) (436 6 (:REWRITE CAR-OF-FILTER-UNPRODUCTIVE-PLANS)) (354 94 (:REWRITE TRUE-ALISTP-CAR)) (348 41 (:REWRITE LEN-OF-CDR)) (263 257 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (212 212 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (144 48 (:REWRITE TRUE-ALISTP-CDR)) (142 142 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (129 68 (:REWRITE DEFAULT-<-2)) (108 36 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (108 6 (:REWRITE CONSP-OF-FILTER-UNPRODUCTIVE-PLANS)) (90 90 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (90 90 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (90 90 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (90 90 (:LINEAR LEN-WHEN-PREFIXP)) (84 24 (:REWRITE EQUAL-OF-LEN-AND-0)) (76 76 (:REWRITE CONSP-WHEN-LEN-GREATER)) (70 45 (:REWRITE DEFAULT-+-2)) (68 68 (:REWRITE DEFAULT-<-1)) (60 30 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (45 45 (:REWRITE DEFAULT-+-1)) (34 34 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (30 30 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (13 4 (:REWRITE FOLD-CONSTS-IN-+)) (4 4 (:REWRITE LEN-OF-CDDR-WHEN-EQUAL-OF-LEN)) ) (FILTER-UNPRODUCTIVE-PLANS-PLAN-FOR-ID-SUBSET-P (165186 70 (:REWRITE SUBSEQUENCEP-EQUAL-EQUAL-LEN)) (135980 156 (:DEFINITION TRUE-LISTP)) (113502 312 (:REWRITE NODE-LIST-P-TRUE-LISTP1)) (107752 9420 (:REWRITE CONSP-FROM-LEN-CHEAP)) (105235 532 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (71253 2800 (:REWRITE PATHS-NOT-ENDING-IN-SET-WHEN-NOT-CONSP)) (60590 858 (:REWRITE CAR-OF-FILTER-UNPRODUCTIVE-PLANS)) (55341 42 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR-RIGHT)) (54116 256 (:REWRITE TRUE-LISTP-OF-CDR-0)) (50907 3901 (:REWRITE LEN-OF-CDR)) (49664 286 (:REWRITE CDR-OF-FILTER-UNPRODUCTIVE-PLANS)) (30801 314 (:REWRITE NODE-LIST-P-OF-CDR)) (24870 2823 (:REWRITE EQUAL-OF-LEN-AND-0)) (17188 5187 (:REWRITE TRUE-ALISTP-CAR)) (12639 12277 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (9651 9651 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (9420 9420 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (7428 3896 (:REWRITE DEFAULT-<-2)) (7238 7238 (:REWRITE CONSP-WHEN-LEN-GREATER)) (7050 2350 (:REWRITE TRUE-ALISTP-CDR)) (7048 4181 (:REWRITE DEFAULT-+-2)) (6098 3049 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (4768 440 (:REWRITE CONSP-OF-FILTER-UNPRODUCTIVE-PLANS)) (4181 4181 (:REWRITE DEFAULT-+-1)) (4155 205 (:REWRITE NODE-LIST-P-OF-CDR-OF-HONS-ASSOC-EQUAL-WHEN-PATH-MAP-P0)) (3896 3896 (:REWRITE DEFAULT-<-1)) (3670 3670 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (3177 72 (:REWRITE SUBLISTP-NOT-PREFIXP)) (3049 3049 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (3004 170 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (2484 312 (:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP)) (1592 1592 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (1592 1592 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (1592 1592 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (1592 1592 (:LINEAR LEN-WHEN-PREFIXP)) (1299 142 (:REWRITE SUBLISTP-WHEN-ATOM-RIGHT)) (884 280 (:REWRITE FOLD-CONSTS-IN-+)) (834 834 (:TYPE-PRESCRIPTION TRUE-LISTP)) (630 532 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (537 127 (:REWRITE SUFFIXP$-OF-CDR)) (532 532 (:REWRITE USE-ALL-NODE-LIST-P-2)) (532 532 (:REWRITE USE-ALL-NODE-LIST-P)) (532 532 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (532 532 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (484 484 (:TYPE-PRESCRIPTION SET::SETP-TYPE)) (484 242 (:REWRITE OMAP::SETP-WHEN-MAPP)) (484 242 (:REWRITE SET::NONEMPTY-MEANS-SET)) (432 144 (:REWRITE SUFFIXP-SUBLISTP)) (416 14 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (416 14 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (392 70 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-LEFT)) (350 350 (:REWRITE LEN-OF-CDDR-WHEN-EQUAL-OF-LEN)) (288 288 (:TYPE-PRESCRIPTION SUFFIXP)) (271 271 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (271 271 (:REWRITE SUFFIXP$-TRANSITIVE)) (263 14 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (260 70 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-RIGHT)) (242 242 (:TYPE-PRESCRIPTION OMAP::MAPP)) (242 242 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE)) (242 242 (:REWRITE SET::IN-SET)) (238 56 (:REWRITE SUFFIXP$-OF-CDR-AND-CDR)) (144 144 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (144 144 (:REWRITE SUBLISTP-TRANSITIVE)) (142 142 (:REWRITE SUBLISTP-COMPLETE)) (140 70 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR)) (119 61 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (116 58 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (116 58 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (115 61 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (102 53 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (94 4 (:REWRITE PREFIXP-WHEN-EQUAL-LENGTHS)) (84 42 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (84 42 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (81 42 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (79 4 (:REWRITE PREFIXP-WHEN-PREFIXP)) (70 70 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-OF-CDR-OF-MEMBER-EQUAL)) (70 70 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-SUFFIXP$)) (70 70 (:REWRITE SUBSEQUENCEP-EQUAL-TRANSITIVE)) (61 61 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (61 61 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (61 61 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (61 61 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (56 56 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (42 42 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (42 42 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (42 42 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (42 42 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (30 1 (:REWRITE LIST-EQUIV-OF-NIL-RIGHT)) (28 28 (:REWRITE NOT-SUBSETP-EQUAL-WHEN-MEMBERP)) (14 1 (:REWRITE LIST-EQUIV-WHEN-ATOM-RIGHT)) (8 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-RIGHT)) (7 7 (:TYPE-PRESCRIPTION PREFIXP)) (6 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-LEFT)) (6 1 (:REWRITE USE-ALL-PREFIXED-P-FOR-CAR)) (5 1 (:REWRITE USE-ALL-PREFIXES-P-FOR-CAR)) (4 4 (:REWRITE PREFIXP-TRANSITIVE-1)) (4 4 (:REWRITE PREFIXP-TRANSITIVE . 2)) (4 4 (:REWRITE PREFIXP-TRANSITIVE . 1)) (4 4 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 2)) (4 4 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 1)) (2 2 (:TYPE-PRESCRIPTION ALL-PREFIXES-P)) (2 2 (:TYPE-PRESCRIPTION ALL-PREFIXED-P)) (1 1 (:TYPE-PRESCRIPTION LIST-EQUIV)) (1 1 (:REWRITE LIST-EQUIV-WHEN-ATOM-LEFT)) (1 1 (:REWRITE ALL-PREFIXES-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE ALL-PREFIXES-P-WHEN-NOT-CONSP)) (1 1 (:REWRITE ALL-PREFIXED-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE ALL-PREFIXED-P-WHEN-NOT-CONSP)) (1 1 (:REWRITE ALL-PREFIXED-P-TRANSITIVE)) ) (FILTER-UNPRODUCTIVE-PLANS-SUB-PLAN-MAP-P (138 11 (:REWRITE CONSP-FROM-LEN-CHEAP)) (105 5 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (60 6 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (49 49 (:TYPE-PRESCRIPTION LEN)) (23 11 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (17 17 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (11 11 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (10 10 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (10 10 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (10 10 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (10 10 (:LINEAR LEN-WHEN-PREFIXP)) (10 5 (:REWRITE DEFAULT-<-2)) (5 5 (:REWRITE USE-ALL-NODE-LIST-P-2)) (5 5 (:REWRITE USE-ALL-NODE-LIST-P)) (5 5 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (5 5 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (5 5 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (5 5 (:REWRITE DEFAULT-<-1)) (5 5 (:REWRITE CONSP-WHEN-LEN-GREATER)) ) (FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX (34 4 (:REWRITE CONSP-FROM-LEN-CHEAP)) (30 3 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (14 12 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (11 4 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (4 4 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (3 2 (:REWRITE DEFAULT-<-2)) (2 2 (:REWRITE DEFAULT-<-1)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (2 2 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (2 2 (:LINEAR LEN-WHEN-PREFIXP)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-+-2)) (1 1 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE CONSP-WHEN-LEN-GREATER)) ) (PLAN-MAP-P0-OF-FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX (1202 83 (:REWRITE CONSP-FROM-LEN-CHEAP)) (515 45 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (418 14 (:REWRITE PATHS-NOT-ENDING-IN-SET-WHEN-NOT-CONSP)) (387 69 (:REWRITE PLAN-MAP-FIX-WHEN-PLAN-MAP-P0)) (253 13 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (216 82 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (195 149 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (177 16 (:REWRITE LEN-OF-CDR)) (151 30 (:REWRITE DEFAULT-CAR)) (98 27 (:REWRITE DEFAULT-CDR)) (83 83 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (76 76 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (76 76 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (76 76 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (76 76 (:LINEAR LEN-WHEN-PREFIXP)) (76 38 (:REWRITE DEFAULT-<-2)) (66 35 (:REWRITE TRUE-ALISTP-CAR)) (65 16 (:REWRITE EQUAL-OF-LEN-AND-0)) (39 39 (:REWRITE CONSP-WHEN-LEN-GREATER)) (38 38 (:REWRITE DEFAULT-<-1)) (32 16 (:REWRITE DEFAULT-+-2)) (31 31 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (17 17 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (16 16 (:REWRITE DEFAULT-+-1)) (13 13 (:REWRITE USE-ALL-NODE-LIST-P-2)) (13 13 (:REWRITE USE-ALL-NODE-LIST-P)) (13 13 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (13 13 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (13 13 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) ) (ALISTP-OF-FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX (1014 66 (:REWRITE CONSP-FROM-LEN-CHEAP)) (617 10 (:REWRITE PATH-MAP-P-ALIST)) (597 10 (:DEFINITION PATH-MAP-P)) (508 18 (:REWRITE PATHS-NOT-ENDING-IN-SET-WHEN-NOT-CONSP)) (287 3 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (240 21 (:REWRITE LEN-OF-CDR)) (215 39 (:REWRITE DEFAULT-CAR)) (206 50 (:REWRITE PLAN-MAP-FIX-WHEN-PLAN-MAP-P0)) (177 14 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (145 53 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (144 10 (:REWRITE OMAP::ALISTP-WHEN-MAPP)) (141 110 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (114 15 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (101 2 (:REWRITE PATH-MAP-P0-OF-CONS)) (97 19 (:REWRITE EQUAL-OF-LEN-AND-0)) (82 44 (:REWRITE TRUE-ALISTP-CAR)) (74 28 (:REWRITE DEFAULT-CDR)) (66 66 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (64 33 (:REWRITE DEFAULT-<-2)) (64 10 (:REWRITE OMAP::MFIX-IMPLIES-MAPP)) (54 54 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (54 54 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (54 54 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (54 54 (:LINEAR LEN-WHEN-PREFIXP)) (50 10 (:REWRITE OMAP::MAPP-WHEN-NOT-EMPTY)) (40 40 (:TYPE-PRESCRIPTION OMAP::MAPP)) (40 40 (:REWRITE CONSP-WHEN-LEN-GREATER)) (40 21 (:REWRITE DEFAULT-+-2)) (36 36 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (34 20 (:TYPE-PRESCRIPTION OMAP::MFIX)) (33 33 (:REWRITE DEFAULT-<-1)) (24 24 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (21 21 (:REWRITE DEFAULT-+-1)) (20 20 (:TYPE-PRESCRIPTION OMAP::EMPTY)) (20 10 (:REWRITE OMAP::MFIX-WHEN-MAPP)) (20 10 (:REWRITE OMAP::MAPP-NON-NIL-IMPLIES-NON-EMPTY)) (20 1 (:REWRITE NODE-LIST-P-OF-CDR)) (19 19 (:TYPE-PRESCRIPTION NO-DUPLICATE-ALIST-P)) (15 3 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (14 7 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (10 10 (:TYPE-PRESCRIPTION PATH-MAP-P)) (9 3 (:REWRITE NO-DUPLICATE-ALIST-CDR)) (8 8 (:TYPE-PRESCRIPTION NODE-LIST-P)) (8 2 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (7 7 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (6 2 (:REWRITE TRUE-ALISTP-CDR)) (6 2 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PLAN-MAP-P0)) (6 1 (:REWRITE USE-ALL-NODE-LIST-P-FOR-CAR)) (5 1 (:REWRITE NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0)) (4 4 (:REWRITE PLAN-MAP-P0-OF-PLAN-MAP-FIX)) (3 3 (:REWRITE USE-ALL-NODE-LIST-P-2)) (3 3 (:REWRITE USE-ALL-NODE-LIST-P)) (3 3 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (3 3 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (3 3 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (3 1 (:REWRITE NO-DUPLICATE-ALIST-CONS)) (2 2 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (1 1 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (1 1 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) ) (FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX (1189 89 (:REWRITE CONSP-FROM-LEN-CHEAP)) (475 49 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (425 21 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (382 67 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (375 30 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PLAN-MAP-P0)) (315 23 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (276 48 (:REWRITE LEN-OF-CDR)) (276 22 (:REWRITE USE-ALL-NODE-LIST-P)) (230 158 (:REWRITE DEFAULT-CAR)) (206 13 (:REWRITE PATHS-NOT-ENDING-IN-SET-WHEN-NOT-CONSP)) (164 159 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (137 31 (:REWRITE ALL-NODE-LIST-P-OF-CDR)) (120 78 (:REWRITE DEFAULT-<-2)) (99 91 (:REWRITE DEFAULT-CDR)) (96 96 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (96 96 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (96 96 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (96 96 (:LINEAR LEN-WHEN-PREFIXP)) (94 30 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (90 30 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0)) (87 87 (:REWRITE CONSP-WHEN-LEN-GREATER)) (78 78 (:REWRITE DEFAULT-<-1)) (67 67 (:TYPE-PRESCRIPTION MEMBERP)) (62 49 (:REWRITE DEFAULT-+-2)) (57 57 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (55 20 (:REWRITE TRUE-ALISTP-CAR)) (53 53 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (49 49 (:REWRITE DEFAULT-+-1)) (34 17 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (34 17 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (34 17 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (32 32 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (24 20 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (23 21 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (22 22 (:REWRITE USE-ALL-NODE-LIST-P-2)) (22 22 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (22 22 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (20 20 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (19 19 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (18 9 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (17 17 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (17 17 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (17 17 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (17 17 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (17 17 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (15 3 (:REWRITE MEMBERP-OF-CAR-SAME)) (12 12 (:REWRITE EQUAL-OF-LEN-AND-0)) (9 9 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (9 3 (:REWRITE TRUE-ALISTP-CDR)) ) (FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX-PRESERVES-ALIST-KEYS (3076 284 (:REWRITE CONSP-FROM-LEN-CHEAP)) (1553 59 (:REWRITE PATHS-NOT-ENDING-IN-SET-WHEN-NOT-CONSP)) (1059 87 (:REWRITE LEN-OF-CDR)) (623 58 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (516 446 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (512 56 (:REWRITE EQUAL-OF-LEN-AND-0)) (284 284 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (253 118 (:REWRITE TRUE-ALISTP-CAR)) (231 131 (:REWRITE DEFAULT-<-2)) (186 186 (:REWRITE CONSP-WHEN-LEN-GREATER)) (159 95 (:REWRITE DEFAULT-+-2)) (131 131 (:REWRITE DEFAULT-<-1)) (124 124 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (120 60 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (95 95 (:REWRITE DEFAULT-+-1)) (87 87 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (85 85 (:TYPE-PRESCRIPTION FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX)) (84 84 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (84 84 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (84 84 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (84 84 (:LINEAR LEN-WHEN-PREFIXP)) (60 60 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (36 1 (:DEFINITION LAST)) (33 11 (:REWRITE TRUE-ALISTP-CDR)) (24 2 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (21 1 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (21 1 (:REWRITE CONSP-LAST)) (15 1 (:REWRITE USE-ALL-NODE-LIST-P)) (9 3 (:REWRITE NO-DUPLICATE-ALIST-CONS)) (4 2 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (4 2 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (4 2 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (4 1 (:REWRITE FOLD-CONSTS-IN-+)) (3 3 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (2 2 (:TYPE-PRESCRIPTION LAST)) (2 2 (:TYPE-PRESCRIPTION ACONS)) (2 2 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (2 2 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (2 2 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (2 2 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (2 2 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (2 2 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (1 1 (:REWRITE USE-PATHS-NOT-ENDING-IN-SET)) (1 1 (:REWRITE USE-ALL-NODE-LIST-P-2)) (1 1 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (1 1 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (1 1 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (1 1 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) ) (NON-TRIVIAL-PLAN-MAP-P-FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX (3172 280 (:REWRITE CONSP-FROM-LEN-CHEAP)) (1089 48 (:REWRITE PATHS-NOT-ENDING-IN-SET-WHEN-NOT-CONSP)) (883 127 (:REWRITE DEFAULT-CDR)) (652 121 (:REWRITE DEFAULT-CAR)) (460 410 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (349 160 (:REWRITE TRUE-ALISTP-CAR)) (280 280 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (217 112 (:REWRITE DEFAULT-<-2)) (184 184 (:REWRITE CONSP-WHEN-LEN-GREATER)) (175 175 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (161 87 (:REWRITE DEFAULT-+-2)) (158 79 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (112 112 (:REWRITE DEFAULT-<-1)) (87 87 (:REWRITE DEFAULT-+-1)) (84 84 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (80 80 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (80 80 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (80 80 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (80 80 (:LINEAR LEN-WHEN-PREFIXP)) (79 79 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (54 54 (:TYPE-PRESCRIPTION ACONS)) (42 14 (:REWRITE TRUE-ALISTP-CDR)) (22 2 (:LINEAR LEN-OF-CDR-LINEAR-STRONG)) ) (FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX-PLAN-FOR-ID-SUBSET-P (47344 60 (:REWRITE SUBSEQUENCEP-EQUAL-EQUAL-LEN)) (40166 216 (:REWRITE NODE-LIST-P-TRUE-LISTP1)) (36702 342 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (34225 2670 (:REWRITE CONSP-FROM-LEN-CHEAP)) (33925 108 (:DEFINITION TRUE-LISTP)) (26248 12 (:DEFINITION SUBSETP-EQUAL)) (14298 192 (:REWRITE NODE-LIST-P-OF-CDR)) (13224 477 (:REWRITE PATHS-NOT-ENDING-IN-SET-WHEN-NOT-CONSP)) (12397 888 (:REWRITE LEN-OF-CDR)) (11023 36 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR-RIGHT)) (9851 168 (:REWRITE TRUE-LISTP-OF-CDR-0)) (5937 713 (:REWRITE EQUAL-OF-LEN-AND-0)) (4241 3347 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (2789 62 (:REWRITE SUBLISTP-NOT-PREFIXP)) (2670 2670 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (2507 1242 (:REWRITE DEFAULT-<-2)) (2471 1040 (:REWRITE TRUE-ALISTP-CAR)) (2099 2099 (:REWRITE CONSP-WHEN-LEN-GREATER)) (1625 900 (:REWRITE DEFAULT-+-2)) (1624 216 (:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP)) (1394 697 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (1309 1309 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (1242 1242 (:REWRITE DEFAULT-<-1)) (1232 122 (:REWRITE SUBLISTP-WHEN-ATOM-RIGHT)) (1140 1140 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (1140 1140 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (1140 1140 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (1140 1140 (:LINEAR LEN-WHEN-PREFIXP)) (900 900 (:REWRITE DEFAULT-+-1)) (894 114 (:REWRITE NODE-LIST-P-OF-CDR-OF-HONS-ASSOC-EQUAL-WHEN-PATH-MAP-P0)) (880 36 (:REWRITE MEMBER-EQUAL-BECOMES-MEMBERP)) (847 847 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (697 697 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (612 612 (:TYPE-PRESCRIPTION TRUE-LISTP)) (461 109 (:REWRITE SUFFIXP$-OF-CDR)) (426 342 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (372 124 (:REWRITE SUFFIXP-SUBLISTP)) (366 122 (:REWRITE TRUE-ALISTP-CDR)) (366 12 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (366 12 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (352 60 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-LEFT)) (342 342 (:REWRITE USE-ALL-NODE-LIST-P-2)) (342 342 (:REWRITE USE-ALL-NODE-LIST-P)) (342 342 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (342 342 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (312 312 (:TYPE-PRESCRIPTION SET::SETP-TYPE)) (312 156 (:REWRITE OMAP::SETP-WHEN-MAPP)) (312 156 (:REWRITE SET::NONEMPTY-MEANS-SET)) (248 248 (:TYPE-PRESCRIPTION SUFFIXP)) (242 98 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (240 60 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-RIGHT)) (233 233 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (233 233 (:REWRITE SUFFIXP$-TRANSITIVE)) (232 12 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (204 48 (:REWRITE SUFFIXP$-OF-CDR-AND-CDR)) (156 156 (:TYPE-PRESCRIPTION MEMBERP)) (156 156 (:TYPE-PRESCRIPTION OMAP::MAPP)) (156 156 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE)) (156 156 (:REWRITE SET::IN-SET)) (124 124 (:TYPE-PRESCRIPTION ACONS)) (124 124 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (124 124 (:REWRITE SUBLISTP-TRANSITIVE)) (122 122 (:REWRITE SUBLISTP-COMPLETE)) (120 60 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR)) (104 48 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (104 48 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (96 48 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (96 48 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (96 48 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (94 4 (:REWRITE PREFIXP-WHEN-EQUAL-LENGTHS)) (79 4 (:REWRITE PREFIXP-WHEN-PREFIXP)) (78 36 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (76 76 (:REWRITE LEN-OF-CDDR-WHEN-EQUAL-OF-LEN)) (72 36 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (72 36 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (60 60 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-OF-CDR-OF-MEMBER-EQUAL)) (60 60 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-SUFFIXP$)) (60 60 (:REWRITE SUBSEQUENCEP-EQUAL-TRANSITIVE)) (48 48 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (48 48 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (48 48 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (48 48 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (48 48 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (48 48 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (48 12 (:REWRITE FOLD-CONSTS-IN-+)) (36 36 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (36 36 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (36 36 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (36 36 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (30 1 (:REWRITE LIST-EQUIV-OF-NIL-RIGHT)) (24 24 (:REWRITE NOT-SUBSETP-EQUAL-WHEN-MEMBERP)) (14 1 (:REWRITE LIST-EQUIV-WHEN-ATOM-RIGHT)) (8 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-RIGHT)) (7 7 (:TYPE-PRESCRIPTION PREFIXP)) (6 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-LEFT)) (6 1 (:REWRITE USE-ALL-PREFIXED-P-FOR-CAR)) (5 1 (:REWRITE USE-ALL-PREFIXES-P-FOR-CAR)) (4 4 (:REWRITE PREFIXP-TRANSITIVE-1)) (4 4 (:REWRITE PREFIXP-TRANSITIVE . 2)) (4 4 (:REWRITE PREFIXP-TRANSITIVE . 1)) (4 4 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 2)) (4 4 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 1)) (2 2 (:TYPE-PRESCRIPTION ALL-PREFIXES-P)) (2 2 (:TYPE-PRESCRIPTION ALL-PREFIXED-P)) (1 1 (:TYPE-PRESCRIPTION LIST-EQUIV)) (1 1 (:REWRITE LIST-EQUIV-WHEN-ATOM-LEFT)) (1 1 (:REWRITE ALL-PREFIXES-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE ALL-PREFIXES-P-WHEN-NOT-CONSP)) (1 1 (:REWRITE ALL-PREFIXED-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE ALL-PREFIXED-P-WHEN-NOT-CONSP)) (1 1 (:REWRITE ALL-PREFIXED-P-TRANSITIVE)) ) (FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX-SUB-PLAN-MAP-P (138 11 (:REWRITE CONSP-FROM-LEN-CHEAP)) (105 5 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (60 6 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (49 49 (:TYPE-PRESCRIPTION LEN)) (23 11 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (17 17 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (11 11 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (10 10 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (10 10 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (10 10 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (10 10 (:LINEAR LEN-WHEN-PREFIXP)) (10 5 (:REWRITE DEFAULT-<-2)) (5 5 (:REWRITE USE-ALL-NODE-LIST-P-2)) (5 5 (:REWRITE USE-ALL-NODE-LIST-P)) (5 5 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (5 5 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (5 5 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (5 5 (:REWRITE DEFAULT-<-1)) (5 5 (:REWRITE CONSP-WHEN-LEN-GREATER)) ) (FILTER-REDUNDANT-DESTINATION-PLANS-1) (PLAN-MAP-P0-OF-FILTER-REDUNDANT-DESTINATION-PLANS-1) (NON-TRIVIAL-PLAN-MAP-P-FILTER-REDUNDANT-DESTINATION-PLANS-1) (FILTER-REDUNDANT-DESTINATION-PLANS-1-SUB-PLAN-MAP-P (108 1 (:DEFINITION FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX)) (92 8 (:REWRITE CONSP-FROM-LEN-CHEAP)) (42 3 (:REWRITE DEFAULT-CAR)) (34 34 (:TYPE-PRESCRIPTION LEN)) (25 1 (:DEFINITION ACONS)) (24 1 (:REWRITE CONS-CAR-CDR)) (20 2 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (16 1 (:REWRITE LEN-OF-CDR)) (14 6 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (13 3 (:REWRITE DEFAULT-CDR)) (12 12 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (9 1 (:REWRITE EQUAL-OF-LEN-AND-0)) (8 8 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (6 4 (:REWRITE TRUE-ALISTP-CAR)) (6 3 (:REWRITE DEFAULT-<-2)) (6 2 (:REWRITE PATHS-NOT-ENDING-IN-SET-ID)) (4 4 (:REWRITE CONSP-WHEN-LEN-GREATER)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (4 4 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (4 4 (:LINEAR LEN-WHEN-PREFIXP)) (4 2 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (3 3 (:REWRITE DEFAULT-<-1)) (2 2 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (2 2 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (2 2 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (2 2 (:REWRITE ALL-NODE-LIST-P-OF-CDAR-WHEN-PLAN-MAP-P0)) (2 1 (:REWRITE DEFAULT-+-2)) (1 1 (:REWRITE PLAN-MAP-FIX-WHEN-PLAN-MAP-P0)) (1 1 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) )
null
https://raw.githubusercontent.com/acl2/acl2/f64742cc6d41c35f9d3f94e154cd5fd409105d34/books/workshops/2020/coglio-westfold/drone-plan/.sys/plans%40useless-runes.lsp
lisp
(INTERSECTION-EQUAL-OF-CONS-IFF (2068 6 (:DEFINITION SUBSETP-EQUAL)) (1638 18 (:REWRITE SUBSEQUENCEP-EQUAL-EQUAL-LEN)) (1158 101 (:REWRITE CONSP-FROM-LEN-CHEAP)) (1104 48 (:REWRITE NODE-LIST-P-TRUE-LISTP1)) (1044 24 (:DEFINITION TRUE-LISTP)) (654 54 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (470 18 (:REWRITE SUBLISTP-NOT-PREFIXP)) (355 51 (:REWRITE LEN-OF-CDR)) (346 6 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR-RIGHT)) (258 48 (:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP)) (258 36 (:REWRITE SUBLISTP-WHEN-ATOM-LEFT)) (216 24 (:REWRITE NODE-LIST-P-OF-CDR)) (204 30 (:REWRITE TRUE-LISTP-OF-CDR-0)) (184 36 (:REWRITE SUBLISTP-WHEN-ATOM-RIGHT)) (138 138 (:TYPE-PRESCRIPTION TRUE-LISTP)) (126 42 (:REWRITE SUFFIXP-SUBLISTP)) (124 124 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (123 63 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (119 69 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (108 108 (:TYPE-PRESCRIPTION NODE-LIST-P)) (107 107 (:REWRITE DEFAULT-CDR)) (101 101 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (97 97 (:REWRITE CONSP-WHEN-LEN-GREATER)) (96 6 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (95 51 (:REWRITE DEFAULT-<-2)) (91 61 (:REWRITE DEFAULT-+-2)) (84 84 (:TYPE-PRESCRIPTION SUFFIXP)) (82 36 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (69 69 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (69 69 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (69 69 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (66 66 (:REWRITE DEFAULT-CAR)) (66 33 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (66 33 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (64 64 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (64 64 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (64 64 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (64 64 (:LINEAR LEN-WHEN-PREFIXP)) (63 63 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (63 63 (:REWRITE SUFFIXP$-TRANSITIVE)) (63 63 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (61 61 (:REWRITE DEFAULT-+-1)) (60 60 (:TYPE-PRESCRIPTION SET::SETP-TYPE)) (60 30 (:REWRITE OMAP::SETP-WHEN-MAPP)) (60 30 (:REWRITE SET::NONEMPTY-MEANS-SET)) (60 18 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-LEFT)) (59 59 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (57 57 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (54 54 (:REWRITE USE-ALL-NODE-LIST-P-2)) (54 54 (:REWRITE USE-ALL-NODE-LIST-P)) (54 54 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (54 54 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (54 54 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (51 51 (:REWRITE DEFAULT-<-1)) (50 18 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-RIGHT)) (48 48 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (47 47 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (47 47 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (47 47 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (42 42 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (42 42 (:REWRITE SUBLISTP-TRANSITIVE)) (36 36 (:REWRITE SUBLISTP-COMPLETE)) (36 18 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR)) (36 10 (:REWRITE FOLD-CONSTS-IN-+)) (30 30 (:TYPE-PRESCRIPTION OMAP::MAPP)) (30 30 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE)) (30 30 (:REWRITE SET::IN-SET)) (30 6 (:REWRITE SUFFIXP$-OF-CDR-AND-CDR)) (27 27 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (27 27 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (24 24 (:REWRITE EQUAL-OF-LEN-AND-0)) (18 18 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-OF-CDR-OF-MEMBER-EQUAL)) (18 18 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-SUFFIXP$)) (18 18 (:REWRITE SUBSEQUENCEP-EQUAL-TRANSITIVE)) (10 10 (:REWRITE LEN-OF-CDDR-WHEN-EQUAL-OF-LEN)) (2 2 (:REWRITE MEMBERP-OF-CONS-IRREL-STRONG)) ) (DRONE-ID-P) (BOOLEANP-OF-DRONE-ID-P) (DRONE-ID-P-ZERO) (DRONE-ID-FIX (1 1 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) ) (DRONE-ID-P-DRONE-ID-FIX (26 26 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) (3 3 (:REWRITE DEFAULT-<-2)) (3 3 (:REWRITE DEFAULT-<-1)) ) (DRONE-ID-P-DRONE-ID-FIX-ID (1 1 (:REWRITE DEFAULT-<-2)) (1 1 (:REWRITE DEFAULT-<-1)) ) (DRONE-ID-EQUIV (10 10 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) ) (DRONE-ID-EQUIV-IS-AN-EQUIVALENCE (6 6 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) ) (__DEFFIXTYPE-DRONE-ID-EQUIV-MEANS-EQUAL-OF-DRONE-ID-FIX (6 6 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) ) (DRONE-ID-LIST-P) (STD::DEFLIST-LOCAL-BOOLEANP-ELEMENT-THM) (DRONE-ID-LIST-P-OF-CONS) (DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P) (DRONE-ID-LIST-P-WHEN-NOT-CONSP) (DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P) (TRUE-LISTP-WHEN-DRONE-ID-LIST-P) (DRONE-ID-LIST-P-OF-LIST-FIX) (DRONE-ID-LIST-P-OF-REV) (DRONE-ID-LIST-FIX$INLINE (1 1 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) ) (DRONE-ID-LIST-P-OF-DRONE-ID-LIST-FIX (15 1 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (12 2 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (9 5 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (9 1 (:DEFINITION DRONE-ID-LIST-P)) (4 4 (:TYPE-PRESCRIPTION DRONE-ID-P)) (2 1 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) ) (DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P (17 4 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (9 3 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) ) (DRONE-ID-LIST-FIX$INLINE (4 4 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (4 1 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (4 1 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) ) (FTY::TMP-DEFFIXTYPE-IDEMPOTENT (1 1 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) ) (DRONE-ID-LIST-EQUIV$INLINE) (DRONE-ID-LIST-EQUIV-IS-AN-EQUIVALENCE) (DRONE-ID-LIST-EQUIV-IMPLIES-EQUAL-DRONE-ID-LIST-FIX-1) (DRONE-ID-LIST-FIX-UNDER-DRONE-ID-LIST-EQUIV) (EQUAL-OF-DRONE-ID-LIST-FIX-1-FORWARD-TO-DRONE-ID-LIST-EQUIV) (EQUAL-OF-DRONE-ID-LIST-FIX-2-FORWARD-TO-DRONE-ID-LIST-EQUIV) (DRONE-ID-LIST-EQUIV-OF-DRONE-ID-LIST-FIX-1-FORWARD) (DRONE-ID-LIST-EQUIV-OF-DRONE-ID-LIST-FIX-2-FORWARD) (CAR-OF-DRONE-ID-LIST-FIX-X-UNDER-DRONE-ID-EQUIV (112 8 (:REWRITE INTEGERP-OF-CAR-WHEN-INTEGER-LISTP)) (96 4 (:DEFINITION INTEGER-LISTP)) (61 4 (:REWRITE NATP-OF-CAR-WHEN-NAT-LISTP)) (60 8 (:REWRITE INTEGER-LISTP-WHEN-NOT-CONSP)) (59 6 (:REWRITE CONSP-FROM-LEN-CHEAP)) (55 1 (:DEFINITION NAT-LISTP)) (45 45 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) (28 28 (:TYPE-PRESCRIPTION INTEGER-LISTP)) (25 5 (:REWRITE LEN-OF-CDR)) (18 6 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (15 2 (:REWRITE NAT-LISTP-WHEN-NOT-CONSP)) (14 14 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (12 12 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (12 2 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (11 10 (:REWRITE DEFAULT-<-2)) (10 10 (:REWRITE DEFAULT-<-1)) (8 4 (:REWRITE INTEGER-LISTP-OF-CDR-WHEN-INTEGER-LISTP)) (7 7 (:TYPE-PRESCRIPTION NAT-LISTP)) (7 7 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (6 6 (:REWRITE CONSP-WHEN-LEN-GREATER)) (6 6 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (5 5 (:REWRITE DEFAULT-CDR)) (5 5 (:REWRITE DEFAULT-+-2)) (5 5 (:REWRITE DEFAULT-+-1)) (5 5 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (4 1 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (3 3 (:TYPE-PRESCRIPTION DRONE-ID-LIST-FIX$INLINE)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (2 2 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (2 2 (:LINEAR LEN-WHEN-PREFIXP)) (2 1 (:REWRITE NAT-LISTP-OF-CDR-WHEN-NAT-LISTP)) (2 1 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) ) (CAR-DRONE-ID-LIST-EQUIV-CONGRUENCE-ON-X-UNDER-DRONE-ID-EQUIV) (CDR-OF-DRONE-ID-LIST-FIX-X-UNDER-DRONE-ID-LIST-EQUIV (29 3 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (14 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (8 2 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (4 4 (:TYPE-PRESCRIPTION DRONE-ID-P)) ) (CDR-DRONE-ID-LIST-EQUIV-CONGRUENCE-ON-X-UNDER-DRONE-ID-LIST-EQUIV) (CONS-OF-DRONE-ID-FIX-X-UNDER-DRONE-ID-LIST-EQUIV (20 4 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (9 2 (:REWRITE DRONE-ID-LIST-P-OF-CONS)) (6 6 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (5 5 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) ) (CONS-DRONE-ID-EQUIV-CONGRUENCE-ON-X-UNDER-DRONE-ID-LIST-EQUIV) (CONS-OF-DRONE-ID-LIST-FIX-Y-UNDER-DRONE-ID-LIST-EQUIV (12 2 (:REWRITE DRONE-ID-LIST-P-OF-CONS)) (8 8 (:TYPE-PRESCRIPTION DRONE-ID-P)) (5 4 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (4 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) ) (CONS-DRONE-ID-LIST-EQUIV-CONGRUENCE-ON-Y-UNDER-DRONE-ID-LIST-EQUIV) (CONSP-OF-DRONE-ID-LIST-FIX (12 2 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (8 8 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (7 1 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (4 4 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (4 1 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (4 1 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (2 2 (:TYPE-PRESCRIPTION DRONE-ID-P)) ) (DRONE-ID-LIST-FIX-UNDER-IFF (12 2 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (8 8 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (7 1 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (4 4 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (4 1 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (4 1 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (2 2 (:TYPE-PRESCRIPTION DRONE-ID-P)) ) (DRONE-ID-LIST-FIX-OF-CONS (13 3 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (5 1 (:REWRITE DRONE-ID-LIST-P-OF-CONS)) (4 4 (:TYPE-PRESCRIPTION DRONE-ID-P)) (4 4 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (4 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (3 3 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) ) (LEN-OF-DRONE-ID-LIST-FIX (23 4 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (13 13 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (8 2 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (7 7 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (7 1 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (4 1 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (2 2 (:TYPE-PRESCRIPTION DRONE-ID-P)) (1 1 (:REWRITE FTY::EQUAL-OF-LEN)) ) (DRONE-ID-LIST-FIX-OF-APPEND (56 10 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (23 23 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (18 12 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (8 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (8 2 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (4 1 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (2 2 (:TYPE-PRESCRIPTION DRONE-ID-P)) ) (DRONE-ID-LIST-FIX-OF-REPEAT (20 2 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (10 4 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (8 2 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (6 6 (:TYPE-PRESCRIPTION DRONE-ID-P)) (4 4 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (1 1 (:REWRITE-QUOTED-CONSTANT DRONE-ID-LIST-FIX-UNDER-DRONE-ID-LIST-EQUIV)) ) (LIST-EQUIV-REFINES-DRONE-ID-LIST-EQUIV (98 14 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (72 8 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (70 70 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (60 18 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (48 8 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (36 36 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (16 16 (:TYPE-PRESCRIPTION DRONE-ID-P)) ) (NTH-OF-DRONE-ID-LIST-FIX (219 24 (:REWRITE CONSP-FROM-LEN-CHEAP)) (135 16 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (93 24 (:REWRITE DEFAULT-CDR)) (76 7 (:REWRITE DEFAULT-CAR)) (71 71 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (63 63 (:REWRITE DEFAULT-+-2)) (63 63 (:REWRITE DEFAULT-+-1)) (59 35 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (50 13 (:REWRITE CONSP-OF-DRONE-ID-LIST-FIX)) (48 45 (:REWRITE DEFAULT-<-2)) (48 12 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (45 45 (:REWRITE DEFAULT-<-1)) (31 10 (:REWRITE ZP-OPEN)) (28 7 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (24 24 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (20 2 (:LINEAR LEN-OF-CDR-LINEAR-STRONG)) (19 1 (:REWRITE NOT-EQUAL-NTH-WHEN-NOT-MEMBERP-CHEAP)) (16 2 (:LINEAR LEN-OF-CDR-LINEAR)) (10 10 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (10 10 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (10 10 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (10 10 (:LINEAR LEN-WHEN-PREFIXP)) (8 5 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (7 7 (:REWRITE NTH-WHEN-PREFIXP)) (5 5 (:REWRITE CONSP-WHEN-LEN-GREATER)) (4 4 (:TYPE-PRESCRIPTION MEMBERP)) (4 4 (:LINEAR LISTPOS-COMPLETE)) (2 2 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (2 1 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (2 1 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (2 1 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (2 1 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (2 1 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (2 1 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (1 1 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (1 1 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (1 1 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (1 1 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (1 1 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (1 1 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (1 1 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) ) (DRONE-ID-LIST-EQUIV-IMPLIES-DRONE-ID-LIST-EQUIV-APPEND-1 (181 32 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (131 17 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (126 126 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (80 17 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (79 22 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (64 64 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (34 34 (:TYPE-PRESCRIPTION DRONE-ID-P)) ) (DRONE-ID-LIST-EQUIV-IMPLIES-DRONE-ID-LIST-EQUIV-APPEND-2 (267 46 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (206 26 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (189 189 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (138 39 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (128 26 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (95 95 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (52 52 (:TYPE-PRESCRIPTION DRONE-ID-P)) (4 4 (:REWRITE CONSP-OF-DRONE-ID-LIST-FIX)) ) (DRONE-ID-LIST-EQUIV-IMPLIES-DRONE-ID-LIST-EQUIV-NTHCDR-2 (249 39 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (175 175 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (174 22 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (117 33 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (108 22 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (88 88 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (44 44 (:TYPE-PRESCRIPTION DRONE-ID-P)) ) (DRONE-ID-LIST-EQUIV-IMPLIES-DRONE-ID-LIST-EQUIV-TAKE-2 (326 38 (:REWRITE DRONE-ID-LIST-FIX-WHEN-DRONE-ID-LIST-P)) (222 28 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (190 190 (:TYPE-PRESCRIPTION DRONE-ID-LIST-P)) (149 39 (:REWRITE DRONE-ID-LIST-P-OF-CDR-WHEN-DRONE-ID-LIST-P)) (140 26 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (119 95 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (54 54 (:TYPE-PRESCRIPTION DRONE-ID-P)) (40 40 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) (6 6 (:REWRITE-QUOTED-CONSTANT DRONE-ID-LIST-FIX-UNDER-DRONE-ID-LIST-EQUIV)) ) (COORD-ID-P) (GET-ASSOC) (NO-DUPLICATE-ALIST-P) (BOOLEANP-OF-NO-DUPLICATE-ALIST-P) (NO-DUPLICATE-ALIST-CDR (2751 18 (:DEFINITION NO-DUPLICATESP-EQUAL)) (2360 54 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NO-DUPLICATESP-EQUAL-OF-CDR)) (977 61 (:REWRITE CONSP-FROM-LEN-CHEAP)) (796 36 (:REWRITE NO-DUPLICATESP-EQUAL-OF-CDR)) (715 19 (:REWRITE MEMBER-EQUAL-BECOMES-MEMBERP)) (601 30 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (415 24 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (284 5 (:DEFINITION HONS-ASSOC-EQUAL)) (246 246 (:TYPE-PRESCRIPTION TRUE-LISTP-OF-ALIST-KEYS)) (221 18 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (206 16 (:REWRITE LEN-OF-CDR)) (162 162 (:TYPE-PRESCRIPTION MEMBER-EQUAL)) (147 147 (:TYPE-PRESCRIPTION MEMBERP)) (120 85 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (120 60 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (120 60 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (89 41 (:REWRITE DEFAULT-<-2)) (86 43 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (86 43 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (86 43 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (80 16 (:REWRITE EQUAL-OF-LEN-AND-0)) (75 54 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NOT-CONSP-CHEAP)) (70 36 (:REWRITE MEMBER-EQUAL-OF-CAR-SAME)) (67 60 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (61 61 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (60 60 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (60 60 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (60 60 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (58 58 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (58 58 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (58 58 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (58 58 (:LINEAR LEN-WHEN-PREFIXP)) (54 54 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL)) (52 43 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (51 51 (:REWRITE CONSP-WHEN-LEN-GREATER)) (43 43 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (43 43 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (43 43 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (43 43 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (43 43 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (43 43 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (43 43 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (41 41 (:REWRITE DEFAULT-<-1)) (39 39 (:REWRITE DEFAULT-CAR)) (34 17 (:REWRITE DEFAULT-+-2)) (30 30 (:TYPE-PRESCRIPTION HONS-ASSOC-EQUAL)) (19 19 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (18 18 (:REWRITE MEMBERP-OF-CAR-SAME)) (17 17 (:REWRITE DEFAULT-+-1)) (16 16 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (10 10 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (10 5 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (10 5 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (5 5 (:DEFINITION HONS-EQUAL)) ) (NO-DUPLICATE-ALIST-ACONS (13870 324 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NO-DUPLICATESP-EQUAL-OF-CDR)) (6631 440 (:REWRITE CONSP-FROM-LEN-CHEAP)) (3303 187 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (2601 149 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (2096 431 (:REWRITE DEFAULT-CDR)) (1578 6 (:DEFINITION SUBSETP-EQUAL)) (1390 111 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (1193 121 (:REWRITE LEN-OF-CDR)) (1003 734 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (942 18 (:REWRITE SUBSEQUENCEP-EQUAL-EQUAL-LEN)) (770 385 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (770 385 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (619 307 (:REWRITE DEFAULT-<-2)) (583 293 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (572 572 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (572 572 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (572 572 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (572 572 (:LINEAR LEN-WHEN-PREFIXP)) (572 286 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (572 286 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (501 222 (:REWRITE MEMBER-EQUAL-OF-CAR-SAME)) (462 6 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR-RIGHT)) (440 440 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (426 379 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (426 320 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NOT-CONSP-CHEAP)) (385 385 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (385 385 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (385 385 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (365 365 (:REWRITE CONSP-WHEN-LEN-GREATER)) (354 286 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (340 88 (:REWRITE EQUAL-OF-LEN-AND-0)) (328 328 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL)) (309 307 (:REWRITE DEFAULT-<-1)) (293 293 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (293 293 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (293 293 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (293 293 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (288 18 (:REWRITE SUBLISTP-WHEN-ATOM-LEFT)) (286 286 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (233 133 (:REWRITE DEFAULT-+-2)) (229 4 (:REWRITE NO-DUPLICATESP-EQUAL-OF-CONS-NO-SPLIT)) (194 8 (:REWRITE PREFIXP-WHEN-EQUAL-LENGTHS)) (165 8 (:REWRITE PREFIXP-WHEN-PREFIXP)) (148 2 (:REWRITE SUBLISTP-NOT-PREFIXP)) (133 133 (:REWRITE DEFAULT-+-1)) (126 18 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-LEFT)) (124 124 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (124 62 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (118 109 (:REWRITE MEMBERP-OF-CAR-SAME)) (115 115 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (111 111 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (106 53 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (102 18 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-RIGHT)) (102 18 (:REWRITE SUBLISTP-WHEN-ATOM-RIGHT)) (84 28 (:REWRITE SUFFIXP-SUBLISTP)) (75 4 (:REWRITE LIST-EQUIV-WHEN-ATOM-RIGHT)) (56 56 (:TYPE-PRESCRIPTION SUFFIXP)) (50 10 (:REWRITE SUFFIXP$-OF-CDR)) (38 38 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (38 38 (:REWRITE SUFFIXP$-TRANSITIVE)) (36 18 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR)) (28 28 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (28 28 (:REWRITE SUBLISTP-TRANSITIVE)) (19 19 (:REWRITE SUBLISTP-COMPLETE)) (18 18 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-OF-CDR-OF-MEMBER-EQUAL)) (18 18 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-SUFFIXP$)) (18 18 (:REWRITE SUBSEQUENCEP-EQUAL-TRANSITIVE)) (15 3 (:REWRITE PREFIXP-WHEN-NOT-CONSP-LEFT)) (8 8 (:REWRITE PREFIXP-TRANSITIVE-1)) (8 8 (:REWRITE PREFIXP-TRANSITIVE . 2)) (8 8 (:REWRITE PREFIXP-TRANSITIVE . 1)) (8 8 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 2)) (8 8 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 1)) (5 4 (:REWRITE LIST-EQUIV-WHEN-ATOM-LEFT)) (4 4 (:TYPE-PRESCRIPTION LIST-EQUIV)) (3 3 (:REWRITE PREFIXP-WHEN-NOT-CONSP-RIGHT)) ) (NO-DUPLICATE-ALIST-CONS (1735 27 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NO-DUPLICATESP-EQUAL-OF-CDR)) (657 69 (:REWRITE CONSP-FROM-LEN-CHEAP)) (605 24 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (371 19 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (221 14 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (211 45 (:REWRITE DEFAULT-CDR)) (186 28 (:REWRITE MEMBER-EQUAL-OF-CAR-SAME)) (148 2 (:REWRITE SUBLISTP-NOT-PREFIXP)) (98 49 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (98 49 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (88 48 (:REWRITE DEFAULT-CAR)) (86 71 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (84 12 (:REWRITE LEN-OF-CDR)) (79 34 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (72 4 (:REWRITE PREFIXP-WHEN-EQUAL-LENGTHS)) (69 69 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (66 4 (:REWRITE PREFIXP-WHEN-PREFIXP)) (65 34 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (60 60 (:REWRITE CONSP-WHEN-LEN-GREATER)) (60 30 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (60 30 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (58 49 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (56 30 (:REWRITE DEFAULT-<-2)) (50 50 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (50 50 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (50 50 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (50 50 (:LINEAR LEN-WHEN-PREFIXP)) (49 49 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (49 49 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (49 49 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (42 6 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (39 34 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (36 30 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (34 34 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (34 34 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (34 34 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (34 34 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (34 12 (:REWRITE MEMBERP-OF-CAR-SAME)) (30 30 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (30 30 (:REWRITE DEFAULT-<-1)) (29 29 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL)) (28 28 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (28 2 (:REWRITE LIST-EQUIV-WHEN-ATOM-RIGHT)) (22 16 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NOT-CONSP-CHEAP)) (20 4 (:REWRITE SUFFIXP$-OF-CDR)) (18 6 (:REWRITE SUFFIXP-SUBLISTP)) (17 12 (:REWRITE DEFAULT-+-2)) (16 16 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (16 8 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (16 8 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (14 14 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (12 12 (:TYPE-PRESCRIPTION SUFFIXP)) (12 12 (:REWRITE DEFAULT-+-1)) (12 5 (:REWRITE EQUAL-OF-LEN-AND-0)) (10 10 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (10 10 (:REWRITE SUFFIXP$-TRANSITIVE)) (10 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-LEFT)) (8 8 (:TYPE-PRESCRIPTION PREFIXP)) (6 6 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (6 6 (:REWRITE SUBLISTP-TRANSITIVE)) (4 4 (:REWRITE PREFIXP-TRANSITIVE-1)) (4 4 (:REWRITE PREFIXP-TRANSITIVE . 2)) (4 4 (:REWRITE PREFIXP-TRANSITIVE . 1)) (4 4 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 2)) (4 4 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 1)) (2 2 (:TYPE-PRESCRIPTION LIST-EQUIV)) (2 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-RIGHT)) (2 2 (:REWRITE LIST-EQUIV-WHEN-ATOM-LEFT)) ) (NO-DUPLICATE-ALIST-CAAR-ALIST-KEYS-CDR (834 6 (:DEFINITION NO-DUPLICATESP-EQUAL)) (702 18 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NO-DUPLICATESP-EQUAL-OF-CDR)) (355 25 (:REWRITE CONSP-FROM-LEN-CHEAP)) (264 12 (:REWRITE NO-DUPLICATESP-EQUAL-OF-CDR)) (232 6 (:REWRITE MEMBER-EQUAL-BECOMES-MEMBERP)) (138 8 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (124 10 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (118 28 (:REWRITE DEFAULT-CDR)) (74 6 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (60 6 (:REWRITE LEN-OF-CDR)) (52 1 (:REWRITE NO-DUPLICATESP-EQUAL-OF-CONS-NO-SPLIT)) (49 39 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (48 48 (:TYPE-PRESCRIPTION MEMBERP)) (44 22 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (44 22 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (38 19 (:REWRITE DEFAULT-<-2)) (37 37 (:REWRITE DEFAULT-CAR)) (36 36 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (36 36 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (36 36 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (36 36 (:LINEAR LEN-WHEN-PREFIXP)) (28 14 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (28 14 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (28 14 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (26 22 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (25 25 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (24 18 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NOT-CONSP-CHEAP)) (24 12 (:REWRITE MEMBER-EQUAL-OF-CAR-SAME)) (23 23 (:REWRITE CONSP-WHEN-LEN-GREATER)) (22 22 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (22 22 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (22 22 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (19 19 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL)) (19 19 (:REWRITE DEFAULT-<-1)) (18 4 (:REWRITE EQUAL-OF-LEN-AND-0)) (16 14 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (15 4 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (14 14 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (14 14 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (14 14 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (14 14 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (14 14 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (14 14 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (14 14 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (14 8 (:REWRITE DEFAULT-+-2)) (12 12 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (12 6 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (12 6 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (8 8 (:REWRITE DEFAULT-+-1)) (6 6 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (6 6 (:REWRITE MEMBERP-OF-CAR-SAME)) (6 6 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (DISJOINT-ALISTS-P) (BOOLEANP-OF-DISJOINT-ALISTS-P) (DISJOINT-ALISTS-P-ACONS-CAAR (3327 72 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NO-DUPLICATESP-EQUAL-OF-CDR)) (1652 114 (:REWRITE CONSP-FROM-LEN-CHEAP)) (820 45 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (651 36 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (473 112 (:REWRITE DEFAULT-CDR)) (353 27 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (218 22 (:REWRITE LEN-OF-CDR)) (209 164 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (196 98 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (196 98 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (165 54 (:REWRITE MEMBER-EQUAL-OF-CAR-SAME)) (156 77 (:REWRITE DEFAULT-<-2)) (148 2 (:REWRITE SUBLISTP-NOT-PREFIXP)) (146 126 (:REWRITE DEFAULT-CAR)) (142 142 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (142 142 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (142 142 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (142 142 (:LINEAR LEN-WHEN-PREFIXP)) (123 63 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (123 22 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (118 59 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (118 59 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (115 98 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (114 114 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (98 98 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (98 98 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (98 98 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (95 95 (:REWRITE CONSP-WHEN-LEN-GREATER)) (90 68 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NOT-CONSP-CHEAP)) (77 77 (:REWRITE DEFAULT-<-1)) (73 73 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL)) (72 4 (:REWRITE PREFIXP-WHEN-EQUAL-LENGTHS)) (70 1 (:REWRITE NO-DUPLICATESP-EQUAL-OF-CONS-NO-SPLIT)) (68 59 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (66 4 (:REWRITE PREFIXP-WHEN-PREFIXP)) (65 63 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (64 15 (:REWRITE EQUAL-OF-LEN-AND-0)) (63 63 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (63 63 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (63 63 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (63 63 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (59 59 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (41 24 (:REWRITE DEFAULT-+-2)) (38 19 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (37 37 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (36 18 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (34 25 (:REWRITE MEMBERP-OF-CAR-SAME)) (28 2 (:REWRITE LIST-EQUIV-WHEN-ATOM-RIGHT)) (27 27 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (26 26 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (24 24 (:REWRITE DEFAULT-+-1)) (20 4 (:REWRITE SUFFIXP$-OF-CDR)) (18 6 (:REWRITE SUFFIXP-SUBLISTP)) (12 12 (:TYPE-PRESCRIPTION SUFFIXP)) (10 10 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (10 10 (:REWRITE SUFFIXP$-TRANSITIVE)) (10 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-LEFT)) (9 9 (:REWRITE INTERSECTION-EQUAL-WHEN-MEMBERP-AND-MEMBERP-SAME-IFF)) (8 8 (:TYPE-PRESCRIPTION PREFIXP)) (6 6 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (6 6 (:REWRITE SUBLISTP-TRANSITIVE)) (4 4 (:REWRITE PREFIXP-TRANSITIVE-1)) (4 4 (:REWRITE PREFIXP-TRANSITIVE . 2)) (4 4 (:REWRITE PREFIXP-TRANSITIVE . 1)) (4 4 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 2)) (4 4 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 1)) (2 2 (:TYPE-PRESCRIPTION LIST-EQUIV)) (2 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-RIGHT)) (2 2 (:REWRITE LIST-EQUIV-WHEN-ATOM-LEFT)) ) (NOT-ASSOC-EQUAL-LEMMA (1659 128 (:REWRITE CONSP-FROM-LEN-CHEAP)) (601 17 (:DEFINITION HONS-ASSOC-EQUAL)) (596 2 (:DEFINITION SUBSETP-EQUAL)) (410 50 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (314 6 (:REWRITE SUBSEQUENCEP-EQUAL-EQUAL-LEN)) (278 236 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (221 17 (:REWRITE OMAP::ALISTP-WHEN-MAPP)) (203 149 (:REWRITE DEFAULT-CAR)) (194 194 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (194 194 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (194 194 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (194 194 (:LINEAR LEN-WHEN-PREFIXP)) (154 2 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR-RIGHT)) (148 80 (:REWRITE DEFAULT-<-2)) (128 128 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (96 6 (:REWRITE SUBLISTP-WHEN-ATOM-LEFT)) (92 16 (:REWRITE LEN-OF-CDR)) (85 17 (:REWRITE OMAP::MFIX-IMPLIES-MAPP)) (85 17 (:REWRITE OMAP::MAPP-WHEN-NOT-EMPTY)) (82 82 (:REWRITE DEFAULT-CDR)) (82 82 (:REWRITE CONSP-WHEN-LEN-GREATER)) (80 80 (:REWRITE DEFAULT-<-1)) (68 68 (:TYPE-PRESCRIPTION OMAP::MAPP)) (56 28 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (50 50 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (44 22 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (42 6 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-LEFT)) (36 36 (:TYPE-PRESCRIPTION MEMBER-EQUAL)) (36 18 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (36 18 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (34 34 (:TYPE-PRESCRIPTION OMAP::MFIX)) (34 34 (:TYPE-PRESCRIPTION OMAP::EMPTY)) (34 17 (:REWRITE OMAP::MFIX-WHEN-MAPP)) (34 17 (:REWRITE OMAP::MAPP-NON-NIL-IMPLIES-NON-EMPTY)) (34 6 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-RIGHT)) (34 6 (:REWRITE SUBLISTP-WHEN-ATOM-RIGHT)) (32 16 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (32 16 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (31 16 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (30 30 (:REWRITE INTERSECTION-EQUAL-WHEN-MEMBERP-AND-MEMBERP-SAME-IFF)) (28 20 (:REWRITE DEFAULT-+-2)) (28 14 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (28 14 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (28 14 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (24 8 (:REWRITE SUFFIXP-SUBLISTP)) (20 20 (:REWRITE DEFAULT-+-1)) (18 18 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (18 18 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (18 18 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (17 17 (:DEFINITION HONS-EQUAL)) (16 16 (:TYPE-PRESCRIPTION SUFFIXP)) (16 16 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (16 16 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (16 16 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (16 16 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (16 16 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (14 14 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (12 6 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR)) (10 10 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (10 10 (:REWRITE SUFFIXP$-TRANSITIVE)) (10 2 (:REWRITE SUFFIXP$-OF-CDR)) (8 8 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (8 8 (:REWRITE SUBLISTP-TRANSITIVE)) (6 6 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-OF-CDR-OF-MEMBER-EQUAL)) (6 6 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-SUFFIXP$)) (6 6 (:REWRITE SUBSEQUENCEP-EQUAL-TRANSITIVE)) (6 6 (:REWRITE SUBLISTP-COMPLETE)) (4 4 (:REWRITE EQUAL-OF-LEN-AND-0)) ) (DISJOINT-ALISTS-P-OF-CONS-ARG2 (324 24 (:REWRITE CONSP-FROM-LEN-CHEAP)) (208 4 (:DEFINITION HONS-ASSOC-EQUAL)) (88 16 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (63 1 (:REWRITE MEMBER-EQUAL-OF-CONS-NON-CONSTANT)) (48 24 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (40 36 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (32 32 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (32 32 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (32 32 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (32 32 (:LINEAR LEN-WHEN-PREFIXP)) (32 16 (:REWRITE DEFAULT-<-2)) (29 29 (:REWRITE DEFAULT-CAR)) (24 24 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (16 16 (:REWRITE DEFAULT-CDR)) (16 16 (:REWRITE DEFAULT-<-1)) (16 16 (:REWRITE CONSP-WHEN-LEN-GREATER)) (8 8 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (8 8 (:TYPE-PRESCRIPTION MEMBER-EQUAL)) (8 4 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (8 4 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (8 4 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (8 4 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (8 4 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (8 4 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (8 4 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (6 3 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (6 3 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (6 3 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (5 5 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (5 5 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (5 5 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (4 4 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (4 4 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (4 4 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (4 4 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (4 4 (:REWRITE INTERSECTION-EQUAL-WHEN-MEMBERP-AND-MEMBERP-SAME-IFF)) (4 4 (:DEFINITION HONS-EQUAL)) (3 3 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (3 1 (:REWRITE SUFFIXP-SUBLISTP)) (2 2 (:TYPE-PRESCRIPTION SUFFIXP)) (1 1 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (1 1 (:REWRITE SUFFIXP$-TRANSITIVE)) (1 1 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (1 1 (:REWRITE SUBLISTP-TRANSITIVE)) ) (PATH-MAP-P0) (BOOLEANP-OF-DRONE-ID-P-FOR-PATH-MAP-P0-KEY-LEMMA) (BOOLEANP-OF-NODE-LIST-P-FOR-PATH-MAP-P0-VAL-LEMMA) (BOOLEANP-OF-DRONE-ID-P-FOR-PATH-MAP-P0-KEY) (BOOLEANP-OF-NODE-LIST-P-FOR-PATH-MAP-P0-VAL) (PATH-MAP-P0-OF-REV) (PATH-MAP-P0-OF-LIST-FIX) (TRUE-LISTP-WHEN-PATH-MAP-P0) (PATH-MAP-P0-WHEN-NOT-CONSP) (PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0) (PATH-MAP-P0-OF-CONS) (PATH-MAP-P0-OF-REMOVE-ASSOC (56 10 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (16 16 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) ) (PATH-MAP-P0-OF-PUT-ASSOC) (PATH-MAP-P0-OF-FAST-ALIST-CLEAN) (PATH-MAP-P0-OF-HONS-SHRINK-ALIST) (PATH-MAP-P0-OF-HONS-ACONS) (NODE-LIST-P-OF-CDR-OF-HONS-ASSOC-EQUAL-WHEN-PATH-MAP-P0) (ALISTP-WHEN-PATH-MAP-P0-REWRITE) (ALISTP-WHEN-PATH-MAP-P0) (NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0) (DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0) (PATH-MAP-FIX$INLINE (2 2 (:TYPE-PRESCRIPTION NODE-LIST-FIX)) (1 1 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) ) (PATH-MAP-P0-OF-PATH-MAP-FIX (349 24 (:REWRITE CONSP-FROM-LEN-CHEAP)) (314 7 (:REWRITE NODE-LIST-FIX-NODE-LIST-P)) (233 7 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (201 8 (:DEFINITION PATH-MAP-P0)) (199 15 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0)) (176 12 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (146 12 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (119 40 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (102 6 (:REWRITE NODE-LIST-P-OF-CDR)) (77 15 (:REWRITE NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0)) (56 48 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (52 8 (:REWRITE LEN-OF-CDR)) (48 6 (:REWRITE USE-ALL-NODE-LIST-P-FOR-CAR)) (42 42 (:TYPE-PRESCRIPTION NODE-LIST-P)) (36 20 (:REWRITE DEFAULT-<-2)) (34 34 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (34 34 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (34 34 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (34 34 (:LINEAR LEN-WHEN-PREFIXP)) (32 32 (:REWRITE DEFAULT-CAR)) (30 30 (:TYPE-PRESCRIPTION DRONE-ID-P)) (26 26 (:REWRITE DEFAULT-CDR)) (24 24 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (24 6 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (20 20 (:REWRITE DEFAULT-<-1)) (20 20 (:REWRITE CONSP-WHEN-LEN-GREATER)) (16 16 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (14 9 (:REWRITE DEFAULT-+-2)) (12 12 (:REWRITE USE-ALL-NODE-LIST-P-2)) (12 12 (:REWRITE USE-ALL-NODE-LIST-P)) (12 12 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (12 12 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (12 12 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (12 6 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (12 2 (:REWRITE ALL-NODE-LIST-P-OF-CDR)) (9 9 (:REWRITE DEFAULT-+-1)) (8 8 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (8 8 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (8 8 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (8 8 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (6 6 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (6 6 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (4 4 (:REWRITE EQUAL-OF-LEN-AND-0)) (2 2 (:TYPE-PRESCRIPTION NODE-LIST-FIX)) ) (PATH-MAP-FIX-WHEN-PATH-MAP-P0 (331 29 (:REWRITE NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0)) (313 29 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0)) (313 26 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (278 28 (:REWRITE CONSP-FROM-LEN-CHEAP)) (192 26 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (141 15 (:REWRITE NODE-LIST-P-OF-CDR)) (90 18 (:REWRITE LEN-OF-CDR)) (74 70 (:REWRITE DEFAULT-CAR)) (57 57 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (54 9 (:REWRITE USE-ALL-NODE-LIST-P-FOR-CAR)) (49 45 (:REWRITE DEFAULT-CDR)) (42 15 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (36 27 (:REWRITE DEFAULT-<-2)) (28 28 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (27 27 (:REWRITE DEFAULT-<-1)) (27 27 (:REWRITE CONSP-WHEN-LEN-GREATER)) (26 26 (:REWRITE USE-ALL-NODE-LIST-P-2)) (26 26 (:REWRITE USE-ALL-NODE-LIST-P)) (26 26 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (26 26 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (26 26 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (22 22 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (22 22 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (22 22 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (22 22 (:LINEAR LEN-WHEN-PREFIXP)) (22 20 (:REWRITE DEFAULT-+-2)) (20 20 (:REWRITE DEFAULT-+-1)) (18 18 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (18 18 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (9 9 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (9 9 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (9 9 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (9 9 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (6 3 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (3 3 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) ) (PATH-MAP-FIX$INLINE (5 5 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (4 1 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (4 1 (:REWRITE NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0)) (4 1 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0)) ) (FTY::TMP-DEFFIXTYPE-IDEMPOTENT (1 1 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) ) (PATH-MAP-EQUIV$INLINE) (PATH-MAP-EQUIV-IS-AN-EQUIVALENCE) (PATH-MAP-EQUIV-IMPLIES-EQUAL-PATH-MAP-FIX-1) (PATH-MAP-FIX-UNDER-PATH-MAP-EQUIV) (EQUAL-OF-PATH-MAP-FIX-1-FORWARD-TO-PATH-MAP-EQUIV) (EQUAL-OF-PATH-MAP-FIX-2-FORWARD-TO-PATH-MAP-EQUIV) (PATH-MAP-EQUIV-OF-PATH-MAP-FIX-1-FORWARD) (PATH-MAP-EQUIV-OF-PATH-MAP-FIX-2-FORWARD) (CONS-OF-DRONE-ID-FIX-K-UNDER-PATH-MAP-EQUIV (27 4 (:REWRITE PATH-MAP-FIX-WHEN-PATH-MAP-P0)) (18 2 (:REWRITE PATH-MAP-P0-OF-CONS)) (6 6 (:TYPE-PRESCRIPTION PATH-MAP-P0)) (6 6 (:TYPE-PRESCRIPTION NODE-LIST-P)) (4 2 (:REWRITE NODE-LIST-FIX-NODE-LIST-P)) (3 3 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) ) (CONS-DRONE-ID-EQUIV-CONGRUENCE-ON-K-UNDER-PATH-MAP-EQUIV) (CONS-OF-NODE-LIST-FIX-V-UNDER-PATH-MAP-EQUIV (31 4 (:REWRITE PATH-MAP-FIX-WHEN-PATH-MAP-P0)) (22 2 (:REWRITE PATH-MAP-P0-OF-CONS)) (10 10 (:TYPE-PRESCRIPTION DRONE-ID-P)) (6 6 (:TYPE-PRESCRIPTION PATH-MAP-P0)) (4 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (3 3 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (2 2 (:TYPE-PRESCRIPTION NODE-LIST-FIX)) ) (CONS-NODE-LIST-EQUIV-CONGRUENCE-ON-V-UNDER-PATH-MAP-EQUIV) (CONS-OF-PATH-MAP-FIX-Y-UNDER-PATH-MAP-EQUIV (18 2 (:REWRITE PATH-MAP-P0-OF-CONS)) (11 11 (:TYPE-PRESCRIPTION DRONE-ID-P)) (9 9 (:TYPE-PRESCRIPTION NODE-LIST-P)) (6 2 (:REWRITE NODE-LIST-FIX-NODE-LIST-P)) (6 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (4 4 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) ) (CONS-PATH-MAP-EQUIV-CONGRUENCE-ON-Y-UNDER-PATH-MAP-EQUIV) (PATH-MAP-FIX-OF-ACONS (17 3 (:REWRITE PATH-MAP-FIX-WHEN-PATH-MAP-P0)) (10 1 (:REWRITE PATH-MAP-P0-OF-CONS)) (5 5 (:TYPE-PRESCRIPTION DRONE-ID-P)) (4 4 (:TYPE-PRESCRIPTION PATH-MAP-P0)) (4 4 (:TYPE-PRESCRIPTION NODE-LIST-P)) (4 2 (:REWRITE NODE-LIST-FIX-NODE-LIST-P)) (4 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (2 2 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) ) (PATH-MAP-FIX-OF-APPEND (143 19 (:REWRITE PATH-MAP-FIX-WHEN-PATH-MAP-P0)) (61 61 (:TYPE-PRESCRIPTION PATH-MAP-P0)) (49 31 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (22 4 (:REWRITE NODE-LIST-FIX-NODE-LIST-P)) (22 4 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (21 1 (:REWRITE PATH-MAP-P0-OF-CONS)) (20 5 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (16 4 (:REWRITE NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0)) (16 4 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0)) (9 9 (:TYPE-PRESCRIPTION DRONE-ID-P)) (8 8 (:TYPE-PRESCRIPTION NODE-LIST-P)) ) (CONSP-CAR-OF-PATH-MAP-FIX (50 10 (:REWRITE PATH-MAP-FIX-WHEN-PATH-MAP-P0)) (31 31 (:TYPE-PRESCRIPTION PATH-MAP-P0)) (20 5 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (16 16 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (14 2 (:REWRITE NODE-LIST-FIX-NODE-LIST-P)) (14 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (8 2 (:REWRITE NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0)) (8 2 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0)) (4 4 (:TYPE-PRESCRIPTION NODE-LIST-P)) (4 4 (:TYPE-PRESCRIPTION DRONE-ID-P)) (1 1 (:TYPE-PRESCRIPTION NODE-LIST-FIX)) ) (PATH-MAP-P) (BOOLEANP-OF-PATH-MAP-P) (PATH-MAP-PAIR-P) (BOOLEANP-OF-PATH-MAP-PAIR-P) (DRONE-ID-LIST-P-ALIST-KEYS-PATH-MAP (3319 81 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NO-DUPLICATESP-EQUAL-OF-CDR)) (2084 130 (:REWRITE CONSP-FROM-LEN-CHEAP)) (1060 4 (:REWRITE NO-DUPLICATESP-EQUAL-OF-CONS-NO-SPLIT)) (953 57 (:REWRITE NO-DUPLICATESP-EQUAL-OF-CDR)) (936 6 (:REWRITE NO-DUPLICATE-ALIST-CAAR-ALIST-KEYS-CDR)) (830 43 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (794 16 (:DEFINITION HONS-ASSOC-EQUAL)) (639 37 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (561 116 (:REWRITE DEFAULT-CDR)) (369 42 (:REWRITE LEN-OF-CDR)) (312 27 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (304 20 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (270 211 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (248 248 (:TYPE-PRESCRIPTION MEMBER-EQUAL)) (187 98 (:REWRITE DEFAULT-<-2)) (182 91 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (182 91 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (148 148 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (148 148 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (148 148 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (148 148 (:LINEAR LEN-WHEN-PREFIXP)) (130 130 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (128 64 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (128 64 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (128 64 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (127 127 (:REWRITE DEFAULT-CAR)) (108 108 (:REWRITE CONSP-WHEN-LEN-GREATER)) (108 81 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-NOT-CONSP-CHEAP)) (105 91 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (100 50 (:REWRITE MEMBER-EQUAL-OF-CAR-SAME)) (98 98 (:REWRITE DEFAULT-<-1)) (91 91 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (91 91 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (91 91 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (90 7 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (88 28 (:REWRITE EQUAL-OF-LEN-AND-0)) (85 85 (:REWRITE NO-DUPLICATESP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL)) (74 64 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (70 42 (:REWRITE DEFAULT-+-2)) (64 64 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (64 64 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (64 64 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (64 64 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (64 64 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (64 64 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (64 64 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (52 26 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (42 42 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (42 42 (:REWRITE DEFAULT-+-1)) (42 42 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (32 16 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (27 27 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (27 27 (:REWRITE MEMBERP-OF-CAR-SAME)) (16 16 (:DEFINITION HONS-EQUAL)) (4 4 (:TYPE-PRESCRIPTION NO-DUPLICATE-ALIST-P)) ) (PATH-MAP-P-ALIST) (PATH-MAP-NON-EMPTY-PATHS-P0) (BOOLEANP-OF-PATH-MAP-NON-EMPTY-PATHS-P0) (PATH-MAP-NON-EMPTY-PATHS-P) (BOOLEANP-OF-PATH-MAP-NON-EMPTY-PATHS-P) (PLAN-MAP-PAIR-P) (BOOLEANP-OF-PLAN-MAP-PAIR-P) (TMP-DEFTYPES-ALL-NODE-LIST-P-OF-ALL-NODE-LIST-FIX (71 3 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (56 3 (:REWRITE CONSP-FROM-LEN-CHEAP)) (15 15 (:TYPE-PRESCRIPTION LEN)) (6 6 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (6 6 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (6 6 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (6 6 (:LINEAR LEN-WHEN-PREFIXP)) (6 3 (:REWRITE DEFAULT-<-2)) (4 3 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (4 3 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (4 3 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (3 3 (:REWRITE DEFAULT-<-1)) (3 3 (:REWRITE CONSP-WHEN-LEN-GREATER)) (3 3 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (3 3 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) ) (TMP-DEFTYPES-ALL-NODE-LIST-FIX-WHEN-ALL-NODE-LIST-P (42 2 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (36 2 (:REWRITE CONSP-FROM-LEN-CHEAP)) (19 19 (:TYPE-PRESCRIPTION ALL-NODE-LIST-FIX)) (10 10 (:TYPE-PRESCRIPTION LEN)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (4 4 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (4 4 (:LINEAR LEN-WHEN-PREFIXP)) (4 2 (:REWRITE DEFAULT-<-2)) (2 2 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (2 2 (:REWRITE DEFAULT-<-1)) (2 2 (:REWRITE CONSP-WHEN-LEN-GREATER)) (2 2 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (2 2 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (2 2 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (2 2 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) ) (PLAN-MAP-P0) (BOOLEANP-OF-DRONE-ID-P-FOR-PLAN-MAP-P0-KEY-LEMMA) (BOOLEANP-OF-ALL-NODE-LIST-P-FOR-PLAN-MAP-P0-VAL-LEMMA) (BOOLEANP-OF-DRONE-ID-P-FOR-PLAN-MAP-P0-KEY) (BOOLEANP-OF-ALL-NODE-LIST-P-FOR-PLAN-MAP-P0-VAL) (PLAN-MAP-P0-OF-REV) (PLAN-MAP-P0-OF-LIST-FIX) (TRUE-LISTP-WHEN-PLAN-MAP-P0) (PLAN-MAP-P0-WHEN-NOT-CONSP) (PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0) (PLAN-MAP-P0-OF-CONS) (PLAN-MAP-P0-OF-REMOVE-ASSOC (56 10 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (16 16 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) ) (PLAN-MAP-P0-OF-PUT-ASSOC) (PLAN-MAP-P0-OF-FAST-ALIST-CLEAN) (PLAN-MAP-P0-OF-HONS-SHRINK-ALIST) (PLAN-MAP-P0-OF-HONS-ACONS) (ALL-NODE-LIST-P-OF-CDR-OF-HONS-ASSOC-EQUAL-WHEN-PLAN-MAP-P0) (ALISTP-WHEN-PLAN-MAP-P0-REWRITE) (ALISTP-WHEN-PLAN-MAP-P0) (ALL-NODE-LIST-P-OF-CDAR-WHEN-PLAN-MAP-P0) (DRONE-ID-P-OF-CAAR-WHEN-PLAN-MAP-P0) (PLAN-MAP-FIX$INLINE (2 2 (:TYPE-PRESCRIPTION ALL-NODE-LIST-FIX)) (1 1 (:TYPE-PRESCRIPTION DRONE-ID-FIX)) ) (PLAN-MAP-P0-OF-PLAN-MAP-FIX (349 24 (:REWRITE CONSP-FROM-LEN-CHEAP)) (254 7 (:REWRITE TMP-DEFTYPES-ALL-NODE-LIST-FIX-WHEN-ALL-NODE-LIST-P)) (241 7 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (185 8 (:DEFINITION PLAN-MAP-P0)) (183 15 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PLAN-MAP-P0)) (180 16 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (130 12 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (119 40 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (81 19 (:REWRITE ALL-NODE-LIST-P-OF-CDAR-WHEN-PLAN-MAP-P0)) (56 48 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (52 8 (:REWRITE LEN-OF-CDR)) (46 46 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (40 10 (:REWRITE ALL-NODE-LIST-P-OF-CDR)) (36 20 (:REWRITE DEFAULT-<-2)) (34 34 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (34 34 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (34 34 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (34 34 (:LINEAR LEN-WHEN-PREFIXP)) (32 32 (:REWRITE DEFAULT-CAR)) (32 6 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0)) (30 30 (:TYPE-PRESCRIPTION DRONE-ID-P)) (28 4 (:DEFINITION ALL-NODE-LIST-FIX)) (26 26 (:REWRITE DEFAULT-CDR)) (24 24 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (24 6 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (20 20 (:REWRITE DEFAULT-<-1)) (20 20 (:REWRITE CONSP-WHEN-LEN-GREATER)) (16 16 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (16 16 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (14 9 (:REWRITE DEFAULT-+-2)) (12 6 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (9 9 (:REWRITE DEFAULT-+-1)) (8 8 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (8 8 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (8 2 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (6 6 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (6 6 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (4 4 (:REWRITE EQUAL-OF-LEN-AND-0)) (2 2 (:TYPE-PRESCRIPTION ALL-NODE-LIST-FIX)) ) (PLAN-MAP-FIX-WHEN-PLAN-MAP-P0 (298 29 (:REWRITE ALL-NODE-LIST-P-OF-CDAR-WHEN-PLAN-MAP-P0)) (292 29 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PLAN-MAP-P0)) (289 26 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (278 28 (:REWRITE CONSP-FROM-LEN-CHEAP)) (192 26 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (90 18 (:REWRITE LEN-OF-CDR)) (74 70 (:REWRITE DEFAULT-CAR)) (60 15 (:REWRITE ALL-NODE-LIST-P-OF-CDR)) (57 57 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (49 45 (:REWRITE DEFAULT-CDR)) (42 15 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (42 15 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0)) (36 27 (:REWRITE DEFAULT-<-2)) (28 28 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (27 27 (:REWRITE DEFAULT-<-1)) (27 27 (:REWRITE CONSP-WHEN-LEN-GREATER)) (26 26 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (26 26 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (22 22 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (22 22 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (22 22 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (22 22 (:LINEAR LEN-WHEN-PREFIXP)) (22 20 (:REWRITE DEFAULT-+-2)) (20 20 (:REWRITE DEFAULT-+-1)) (18 18 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (9 9 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (9 9 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (6 3 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (3 3 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) ) (PLAN-MAP-FIX$INLINE (5 5 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (4 1 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (4 1 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PLAN-MAP-P0)) (4 1 (:REWRITE ALL-NODE-LIST-P-OF-CDAR-WHEN-PLAN-MAP-P0)) ) (FTY::TMP-DEFFIXTYPE-IDEMPOTENT (1 1 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) ) (PLAN-MAP-EQUIV$INLINE) (PLAN-MAP-EQUIV-IS-AN-EQUIVALENCE) (PLAN-MAP-EQUIV-IMPLIES-EQUAL-PLAN-MAP-FIX-1) (PLAN-MAP-FIX-UNDER-PLAN-MAP-EQUIV) (EQUAL-OF-PLAN-MAP-FIX-1-FORWARD-TO-PLAN-MAP-EQUIV) (EQUAL-OF-PLAN-MAP-FIX-2-FORWARD-TO-PLAN-MAP-EQUIV) (PLAN-MAP-EQUIV-OF-PLAN-MAP-FIX-1-FORWARD) (PLAN-MAP-EQUIV-OF-PLAN-MAP-FIX-2-FORWARD) (CONS-OF-DRONE-ID-FIX-K-UNDER-PLAN-MAP-EQUIV (27 4 (:REWRITE PLAN-MAP-FIX-WHEN-PLAN-MAP-P0)) (18 2 (:REWRITE PLAN-MAP-P0-OF-CONS)) (6 6 (:TYPE-PRESCRIPTION PLAN-MAP-P0)) (6 6 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (4 2 (:REWRITE TMP-DEFTYPES-ALL-NODE-LIST-FIX-WHEN-ALL-NODE-LIST-P)) (3 3 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) ) (CONS-DRONE-ID-EQUIV-CONGRUENCE-ON-K-UNDER-PLAN-MAP-EQUIV) (CONS-OF-ALL-NODE-LIST-FIX-V-UNDER-PLAN-MAP-EQUIV (31 4 (:REWRITE PLAN-MAP-FIX-WHEN-PLAN-MAP-P0)) (22 2 (:REWRITE PLAN-MAP-P0-OF-CONS)) (10 10 (:TYPE-PRESCRIPTION DRONE-ID-P)) (6 6 (:TYPE-PRESCRIPTION PLAN-MAP-P0)) (4 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (3 3 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (2 2 (:TYPE-PRESCRIPTION ALL-NODE-LIST-FIX)) ) (CONS-ALL-NODE-LIST-EQUIV-CONGRUENCE-ON-V-UNDER-PLAN-MAP-EQUIV) (CONS-OF-PLAN-MAP-FIX-Y-UNDER-PLAN-MAP-EQUIV (18 2 (:REWRITE PLAN-MAP-P0-OF-CONS)) (11 11 (:TYPE-PRESCRIPTION DRONE-ID-P)) (9 9 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (6 2 (:REWRITE TMP-DEFTYPES-ALL-NODE-LIST-FIX-WHEN-ALL-NODE-LIST-P)) (6 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (4 4 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) ) (CONS-PLAN-MAP-EQUIV-CONGRUENCE-ON-Y-UNDER-PLAN-MAP-EQUIV) (PLAN-MAP-FIX-OF-ACONS (17 3 (:REWRITE PLAN-MAP-FIX-WHEN-PLAN-MAP-P0)) (10 1 (:REWRITE PLAN-MAP-P0-OF-CONS)) (5 5 (:TYPE-PRESCRIPTION DRONE-ID-P)) (4 4 (:TYPE-PRESCRIPTION PLAN-MAP-P0)) (4 4 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (4 2 (:REWRITE TMP-DEFTYPES-ALL-NODE-LIST-FIX-WHEN-ALL-NODE-LIST-P)) (4 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (2 2 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) ) (PLAN-MAP-FIX-OF-APPEND (143 19 (:REWRITE PLAN-MAP-FIX-WHEN-PLAN-MAP-P0)) (61 61 (:TYPE-PRESCRIPTION PLAN-MAP-P0)) (49 31 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (22 4 (:REWRITE TMP-DEFTYPES-ALL-NODE-LIST-FIX-WHEN-ALL-NODE-LIST-P)) (22 4 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (21 1 (:REWRITE PLAN-MAP-P0-OF-CONS)) (20 5 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (16 4 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PLAN-MAP-P0)) (16 4 (:REWRITE ALL-NODE-LIST-P-OF-CDAR-WHEN-PLAN-MAP-P0)) (9 9 (:TYPE-PRESCRIPTION DRONE-ID-P)) (8 8 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) ) (CONSP-CAR-OF-PLAN-MAP-FIX (50 10 (:REWRITE PLAN-MAP-FIX-WHEN-PLAN-MAP-P0)) (31 31 (:TYPE-PRESCRIPTION PLAN-MAP-P0)) (20 5 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (16 16 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (14 2 (:REWRITE TMP-DEFTYPES-ALL-NODE-LIST-FIX-WHEN-ALL-NODE-LIST-P)) (14 2 (:REWRITE DRONE-ID-P-DRONE-ID-FIX-ID)) (8 2 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PLAN-MAP-P0)) (8 2 (:REWRITE ALL-NODE-LIST-P-OF-CDAR-WHEN-PLAN-MAP-P0)) (4 4 (:TYPE-PRESCRIPTION DRONE-ID-P)) (4 4 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (1 1 (:TYPE-PRESCRIPTION ALL-NODE-LIST-FIX)) ) (PLAN-MAP-P0-ALIST) (PLAN-MAP-P) (PLAN-MAP-P-CDR (24 3 (:REWRITE CONSP-FROM-LEN-CHEAP)) (20 2 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (12 12 (:TYPE-PRESCRIPTION LEN)) (10 1 (:REWRITE DEFAULT-CDR)) (9 3 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (6 6 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (3 3 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) ) (PLAN-MAP-P-ALIST) (NON-TRIVIAL-PLAN-MAP-P (255 20 (:REWRITE CONSP-FROM-LEN-CHEAP)) (41 12 (:REWRITE DEFAULT-CAR)) (32 5 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (31 16 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (30 2 (:REWRITE LEN-OF-CDR)) (28 28 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (22 11 (:REWRITE DEFAULT-<-2)) (21 3 (:REWRITE DEFAULT-CDR)) (20 20 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (18 18 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (18 18 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (18 18 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (18 18 (:LINEAR LEN-WHEN-PREFIXP)) (16 2 (:REWRITE EQUAL-OF-LEN-AND-0)) (14 7 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (13 13 (:REWRITE CONSP-WHEN-LEN-GREATER)) (11 11 (:REWRITE DEFAULT-<-1)) (10 10 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (6 3 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (4 2 (:REWRITE DEFAULT-+-2)) (2 2 (:REWRITE DEFAULT-+-1)) (2 2 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (NON-TRIVIAL-PLAN-MAP-P-CONS (58 5 (:REWRITE CONSP-FROM-LEN-CHEAP)) (15 1 (:REWRITE LEN-OF-CDR)) (12 3 (:REWRITE DEFAULT-CDR)) (8 1 (:REWRITE EQUAL-OF-LEN-AND-0)) (7 7 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (6 3 (:REWRITE DEFAULT-<-2)) (6 3 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (5 5 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (4 4 (:REWRITE CONSP-WHEN-LEN-GREATER)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (4 4 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (4 4 (:LINEAR LEN-WHEN-PREFIXP)) (3 3 (:REWRITE DEFAULT-<-1)) (2 2 (:REWRITE DEFAULT-CAR)) (2 1 (:REWRITE DEFAULT-+-2)) (2 1 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (1 1 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (1 1 (:REWRITE USE-ALL-NODE-LIST-P-2)) (1 1 (:REWRITE USE-ALL-NODE-LIST-P)) (1 1 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (1 1 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (1 1 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (1 1 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (DRONE-ID-LIST-P-ALIST-KEYS-PLAN-MAP-P (401 29 (:REWRITE CONSP-FROM-LEN-CHEAP)) (150 8 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (144 6 (:REWRITE DRONE-ID-LIST-P-ALIST-KEYS-PATH-MAP)) (132 6 (:DEFINITION PATH-MAP-P)) (90 7 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (86 16 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (68 56 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (52 8 (:REWRITE LEN-OF-CDR)) (30 17 (:REWRITE DEFAULT-<-2)) (29 29 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (26 26 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (26 26 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (26 26 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (26 26 (:LINEAR LEN-WHEN-PREFIXP)) (20 8 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (17 17 (:REWRITE DEFAULT-<-1)) (17 17 (:REWRITE CONSP-WHEN-LEN-GREATER)) (12 12 (:REWRITE DEFAULT-CAR)) (12 8 (:REWRITE DEFAULT-+-2)) (8 8 (:REWRITE DEFAULT-+-1)) (8 8 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (8 4 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (6 6 (:TYPE-PRESCRIPTION PATH-MAP-P)) (4 4 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (4 4 (:REWRITE NO-DUPLICATE-ALIST-CDR)) (4 4 (:REWRITE EQUAL-OF-LEN-AND-0)) (4 4 (:REWRITE DEFAULT-CDR)) ) (PLAN-FOR-ID-EQUAL-P) (BOOLEANP-OF-PLAN-FOR-ID-EQUAL-P) (PLAN-FOR-ID-EQUAL-P-REFLEXIVE) (PLAN-FOR-ID-SUBSET-P (6852 39 (:DEFINITION TRUE-LISTP)) (6545 105 (:REWRITE NODE-LIST-P-TRUE-LISTP1)) (5127 73 (:REWRITE TRUE-LISTP-OF-CDR-0)) (4792 319 (:REWRITE CONSP-FROM-LEN-CHEAP)) (4581 164 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (1950 86 (:REWRITE NODE-LIST-P-OF-CDR)) (999 114 (:REWRITE LEN-OF-CDR)) (902 105 (:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP)) (491 431 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (436 219 (:REWRITE DEFAULT-<-2)) (434 12 (:REWRITE TRUE-LISTP-OF-CAR-WHEN-TRUE-LIST-LISTP)) (410 6 (:DEFINITION TRUE-LIST-LISTP)) (405 265 (:REWRITE DEFAULT-CDR)) (392 48 (:REWRITE NODE-LIST-P-OF-CDR-OF-HONS-ASSOC-EQUAL-WHEN-PATH-MAP-P0)) (338 338 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (338 338 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (338 338 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (338 338 (:LINEAR LEN-WHEN-PREFIXP)) (328 328 (:TYPE-PRESCRIPTION NODE-LIST-P)) (319 319 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (284 284 (:REWRITE CONSP-WHEN-LEN-GREATER)) (280 280 (:REWRITE DEFAULT-CAR)) (248 164 (:REWRITE USE-ALL-NODE-LIST-P)) (244 60 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (219 219 (:REWRITE DEFAULT-<-1)) (210 58 (:REWRITE EQUAL-OF-LEN-AND-0)) (204 164 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (199 131 (:REWRITE DEFAULT-+-2)) (190 190 (:TYPE-PRESCRIPTION SET::SETP-TYPE)) (190 95 (:REWRITE OMAP::SETP-WHEN-MAPP)) (190 95 (:REWRITE SET::NONEMPTY-MEANS-SET)) (164 164 (:REWRITE USE-ALL-NODE-LIST-P-2)) (164 164 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (164 164 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (131 131 (:REWRITE DEFAULT-+-1)) (130 65 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (95 95 (:TYPE-PRESCRIPTION OMAP::MAPP)) (95 95 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE)) (95 95 (:REWRITE SET::IN-SET)) (91 91 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (90 12 (:REWRITE TRUE-LIST-LISTP-WHEN-NOT-CONSP)) (66 16 (:REWRITE USE-ALL-NODE-LIST-P-FOR-CAR)) (65 65 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (53 15 (:REWRITE FOLD-CONSTS-IN-+)) (43 13 (:REWRITE NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0)) (43 12 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (40 10 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (24 24 (:TYPE-PRESCRIPTION MEMBERP)) (23 23 (:REWRITE LEN-OF-CDDR-WHEN-EQUAL-OF-LEN)) (12 12 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (12 12 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (12 6 (:REWRITE TRUE-LIST-LISTP-OF-CDR-WHEN-TRUE-LIST-LISTP)) (12 6 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (12 6 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (12 6 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (6 6 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (6 6 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (6 6 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (6 6 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (6 6 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (6 6 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (6 2 (:REWRITE NO-DUPLICATE-ALIST-CONS)) ) (BOOLEANP-OF-PLAN-FOR-ID-SUBSET-P) (PLAN-FOR-ID-SUBSET-P-REFLEXIVE (177 1 (:REWRITE SUBLISTP-NOT-PREFIXP)) (135 12 (:REWRITE CONSP-FROM-LEN-CHEAP)) (105 2 (:REWRITE PREFIXP-WHEN-PREFIXP)) (100 2 (:DEFINITION HONS-ASSOC-EQUAL)) (87 2 (:REWRITE PREFIXP-WHEN-EQUAL-LENGTHS)) (67 3 (:REWRITE LEN-OF-CDR)) (58 58 (:TYPE-PRESCRIPTION LEN)) (42 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-RIGHT)) (40 3 (:REWRITE EQUAL-OF-LEN-AND-0)) (23 15 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (20 6 (:REWRITE DEFAULT-CDR)) (18 8 (:REWRITE DEFAULT-<-2)) (15 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-LEFT)) (12 12 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (11 11 (:REWRITE CONSP-WHEN-LEN-GREATER)) (11 8 (:REWRITE DEFAULT-<-1)) (11 6 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (10 10 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (10 10 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (10 10 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (10 10 (:LINEAR LEN-WHEN-PREFIXP)) (8 8 (:REWRITE DEFAULT-CAR)) (6 3 (:REWRITE DEFAULT-+-2)) (6 3 (:DEFINITION NOT)) (6 2 (:REWRITE SUFFIXP-SUBLISTP)) (5 5 (:TYPE-PRESCRIPTION PREFIXP)) (5 1 (:REWRITE SUFFIXP$-OF-CDR)) (4 4 (:TYPE-PRESCRIPTION SUFFIXP)) (4 2 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (3 3 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (3 3 (:REWRITE SUFFIXP$-TRANSITIVE)) (3 3 (:REWRITE DEFAULT-+-1)) (2 2 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (2 2 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (2 2 (:REWRITE SUBLISTP-TRANSITIVE)) (2 2 (:REWRITE PREFIXP-TRANSITIVE-1)) (2 2 (:REWRITE PREFIXP-TRANSITIVE . 2)) (2 2 (:REWRITE PREFIXP-TRANSITIVE . 1)) (2 2 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 2)) (2 2 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 1)) (2 2 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (2 2 (:DEFINITION HONS-EQUAL)) ) (SUBSET-FOR-MAP-ELTS (60 7 (:REWRITE CONSP-FROM-LEN-CHEAP)) (40 4 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (17 4 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (16 6 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (14 14 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (7 7 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (5 3 (:REWRITE DEFAULT-<-2)) (5 1 (:REWRITE LEN-OF-CDR)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (4 4 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (4 4 (:LINEAR LEN-WHEN-PREFIXP)) (3 3 (:REWRITE DEFAULT-<-1)) (3 3 (:REWRITE CONSP-WHEN-LEN-GREATER)) (2 2 (:REWRITE DEFAULT-CAR)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-+-2)) (1 1 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (SUBSET-FOR-MAP-ELTS-OF-CONS) (USE-SUBSET-FOR-MAP-ELTS-FOR-CAR) (USE-SUBSET-FOR-MAP-ELTS-FOR-CAR-OF-LAST) (SUBSET-FOR-MAP-ELTS-OF-APPEND) (SUBSET-FOR-MAP-ELTS-OF-UNION-EQUAL) (SUBSET-FOR-MAP-ELTS-WHEN-NOT-CONSP) (SUBSET-FOR-MAP-ELTS-WHEN-NOT-CONSP-CHEAP) (SUBSET-FOR-MAP-ELTS-OF-REVAPPEND) (SUBSET-FOR-MAP-ELTS-OF-CDR) (SUBSET-FOR-MAP-ELTS-OF-NTHCDR) (SUBSET-FOR-MAP-ELTS-OF-FIRSTN) (SUBSET-FOR-MAP-ELTS-OF-REMOVE1-EQUAL) (SUBSET-FOR-MAP-ELTS-OF-REMOVE-EQUAL) (SUBSET-FOR-MAP-ELTS-OF-LAST) (SUBSET-FOR-MAP-ELTS-OF-TAKE) (TRUE-LISTP-WHEN-SUBSET-FOR-MAP-ELTS) (TRUE-LISTP-WHEN-SUBSET-FOR-MAP-ELTS-FORWARD) (SUBSET-FOR-MAP-ELTS-WHEN-PERM) (SUBSET-FOR-MAP-ELTS-OF-TRUE-LIST-FIX) (USE-SUBSET-FOR-MAP-ELTS) (USE-SUBSET-FOR-MAP-ELTS-2) (SUBSET-FOR-MAP-ELTS-OF-ADD-TO-SET-EQUAL) (SUBSET-FOR-MAP-ELTS-REFL (156 12 (:REWRITE CONSP-FROM-LEN-CHEAP)) (114 10 (:REWRITE SUBSET-FOR-MAP-ELTS-WHEN-NOT-CONSP)) (21 9 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (21 3 (:REWRITE LEN-OF-CDR)) (19 19 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (18 4 (:REWRITE USE-SUBSET-FOR-MAP-ELTS)) (15 8 (:REWRITE DEFAULT-<-2)) (14 14 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (14 14 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (14 14 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (14 14 (:LINEAR LEN-WHEN-PREFIXP)) (12 12 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (12 2 (:REWRITE SUBSET-FOR-MAP-ELTS-OF-CDR)) (10 10 (:REWRITE CONSP-WHEN-LEN-GREATER)) (8 8 (:REWRITE DEFAULT-<-1)) (5 5 (:REWRITE DEFAULT-CDR)) (5 3 (:REWRITE DEFAULT-+-2)) (4 4 (:TYPE-PRESCRIPTION MEMBERP)) (4 4 (:REWRITE USE-SUBSET-FOR-MAP-ELTS-2)) (4 4 (:REWRITE DEFAULT-CAR)) (3 3 (:REWRITE DEFAULT-+-1)) (3 3 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (2 2 (:REWRITE EQUAL-OF-LEN-AND-0)) (2 1 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (2 1 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (2 1 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (1 1 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (1 1 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (1 1 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (1 1 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (1 1 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (1 1 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) ) (SUB-PLAN-MAP-P) (BOOLEANP-OF-SUB-PLAN-MAP-P) (SUB-PLAN-MAP-P-REFLEXIVE (24 3 (:REWRITE CONSP-FROM-LEN-CHEAP)) (20 2 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (12 12 (:TYPE-PRESCRIPTION LEN)) (10 1 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (9 3 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (6 6 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (3 3 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) ) (SUB-PLAN-MAP-P-HYPS) (SUB-PLAN-MAP-P-SUB) (SUB-PLAN-MAP-P-SUPER) (SUB-PLAN-MAP-P-MEMBERSHIP-CONSTRAINT) (SUB-PLAN-MAP-P-BADGUY-AUX (60 7 (:REWRITE CONSP-FROM-LEN-CHEAP)) (40 4 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (17 4 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (16 6 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (14 14 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (7 7 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (5 3 (:REWRITE DEFAULT-<-2)) (5 1 (:REWRITE USE-SUBSET-FOR-MAP-ELTS-FOR-CAR)) (5 1 (:REWRITE LEN-OF-CDR)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (4 4 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (4 4 (:LINEAR LEN-WHEN-PREFIXP)) (3 3 (:REWRITE DEFAULT-<-1)) (3 3 (:REWRITE CONSP-WHEN-LEN-GREATER)) (2 2 (:TYPE-PRESCRIPTION SUBSET-FOR-MAP-ELTS)) (2 2 (:REWRITE DEFAULT-CAR)) (1 1 (:REWRITE USE-SUBSET-FOR-MAP-ELTS-2)) (1 1 (:REWRITE USE-SUBSET-FOR-MAP-ELTS)) (1 1 (:REWRITE SUBSET-FOR-MAP-ELTS-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE SUBSET-FOR-MAP-ELTS-WHEN-NOT-CONSP)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-+-2)) (1 1 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (SUB-PLAN-MAP-P-BADGUY-AUX-WITNESS (269 18 (:REWRITE CONSP-FROM-LEN-CHEAP)) (210 10 (:REWRITE NODE-LIST-P-TRUE-LISTP1)) (121 17 (:REWRITE SUBSET-FOR-MAP-ELTS-WHEN-NOT-CONSP)) (115 11 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (80 10 (:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP)) (51 23 (:REWRITE USE-SUBSET-FOR-MAP-ELTS)) (42 2 (:REWRITE TRUE-LISTP-OF-CDR-0)) (32 4 (:REWRITE LEN-OF-CDR)) (29 14 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (28 28 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (28 28 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (28 28 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (28 28 (:LINEAR LEN-WHEN-PREFIXP)) (28 14 (:REWRITE DEFAULT-<-2)) (25 25 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (23 23 (:TYPE-PRESCRIPTION NODE-LIST-P)) (23 23 (:REWRITE USE-SUBSET-FOR-MAP-ELTS-2)) (21 21 (:REWRITE DEFAULT-CAR)) (20 20 (:TYPE-PRESCRIPTION SET::SETP-TYPE)) (20 10 (:REWRITE OMAP::SETP-WHEN-MAPP)) (20 10 (:REWRITE SET::NONEMPTY-MEANS-SET)) (18 18 (:REWRITE CONSP-WHEN-LEN-GREATER)) (18 18 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (18 2 (:REWRITE NODE-LIST-P-OF-CDR)) (14 14 (:REWRITE DEFAULT-<-1)) (12 12 (:REWRITE USE-ALL-NODE-LIST-P-2)) (12 12 (:REWRITE USE-ALL-NODE-LIST-P)) (12 12 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (12 12 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (12 12 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (12 2 (:REWRITE SUBSET-FOR-MAP-ELTS-OF-CDR)) (10 10 (:TYPE-PRESCRIPTION OMAP::MAPP)) (10 10 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE)) (10 10 (:REWRITE SET::IN-SET)) (10 10 (:REWRITE DEFAULT-CDR)) (8 8 (:TYPE-PRESCRIPTION MEMBERP)) (8 4 (:REWRITE DEFAULT-+-2)) (4 4 (:REWRITE EQUAL-OF-LEN-AND-0)) (4 4 (:REWRITE DEFAULT-+-1)) (4 4 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (4 2 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (4 2 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (4 2 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (2 2 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (2 2 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (2 2 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (2 2 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (2 2 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (2 2 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) ) (SUB-PLAN-MAP-P-BADGUY) (SUB-PLAN-MAP-P-BADGUY-WITNESS (36 3 (:REWRITE CONSP-FROM-LEN-CHEAP)) (27 1 (:REWRITE SUBSET-FOR-MAP-ELTS-WHEN-NOT-CONSP)) (21 3 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (13 13 (:TYPE-PRESCRIPTION LEN)) (8 3 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (6 5 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (3 3 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (2 2 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (2 2 (:LINEAR LEN-WHEN-PREFIXP)) (2 1 (:REWRITE SUBSET-FOR-MAP-ELTS-WHEN-NOT-CONSP-CHEAP)) (2 1 (:REWRITE DEFAULT-<-2)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:REWRITE CONSP-WHEN-LEN-GREATER)) ) (SUB-PLAN-MAP-P-BY-MEMBERSHIP-DRIVER) (ADVISER-SUB-PLAN-MAP-P-TRIGGER) (SUB-PLAN-MAP-P-BY-MEMBERSHIP-ANY) (SUB-PLAN-MAP-P-BY-MEMBERSHIP) (TRUE-ALISTP) (BOOLEANP-OF-TRUE-ALISTP) (TRUE-ALISTP-IMPLIES-CONS-OR-NIL) (TRUE-ALISTP-CDR (508 7 (:REWRITE TRUE-LISTP-OF-CDR-0)) (433 8 (:REWRITE TRUE-LISTP-OF-CAR-WHEN-TRUE-LIST-LISTP)) (427 4 (:DEFINITION TRUE-LIST-LISTP)) (422 5 (:DEFINITION TRUE-LISTP)) (342 15 (:REWRITE NODE-LIST-P-TRUE-LISTP1)) (234 16 (:REWRITE CONSP-FROM-LEN-CHEAP)) (171 12 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (108 8 (:REWRITE TRUE-LIST-LISTP-WHEN-NOT-CONSP)) (99 15 (:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP)) (93 15 (:REWRITE LEN-OF-CDR)) (65 5 (:REWRITE NODE-LIST-P-OF-CDR)) (50 7 (:REWRITE USE-ALL-NODE-LIST-P-FOR-CAR)) (33 33 (:TYPE-PRESCRIPTION TRUE-LISTP)) (30 30 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (24 24 (:TYPE-PRESCRIPTION SET::SETP-TYPE)) (24 24 (:TYPE-PRESCRIPTION NODE-LIST-P)) (24 12 (:REWRITE OMAP::SETP-WHEN-MAPP)) (24 12 (:REWRITE SET::NONEMPTY-MEANS-SET)) (23 18 (:REWRITE DEFAULT-+-2)) (20 20 (:REWRITE DEFAULT-CDR)) (19 12 (:REWRITE DEFAULT-<-2)) (18 18 (:REWRITE DEFAULT-+-1)) (18 3 (:REWRITE ALL-NODE-LIST-P-OF-CDR)) (17 4 (:REWRITE NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0)) (16 16 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (16 16 (:REWRITE CONSP-WHEN-LEN-GREATER)) (16 16 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (13 13 (:REWRITE DEFAULT-CAR)) (13 6 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (12 12 (:TYPE-PRESCRIPTION OMAP::MAPP)) (12 12 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE)) (12 12 (:REWRITE USE-ALL-NODE-LIST-P-2)) (12 12 (:REWRITE USE-ALL-NODE-LIST-P)) (12 12 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (12 12 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (12 12 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (12 12 (:REWRITE SET::IN-SET)) (12 12 (:REWRITE DEFAULT-<-1)) (12 12 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (12 12 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (12 12 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (12 12 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (12 12 (:LINEAR LEN-WHEN-PREFIXP)) (12 6 (:REWRITE TRUE-LIST-LISTP-OF-CDR-WHEN-TRUE-LIST-LISTP)) (10 3 (:REWRITE FOLD-CONSTS-IN-+)) (8 8 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (8 8 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (8 8 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (8 4 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (4 4 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (4 4 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (4 4 (:REWRITE EQUAL-OF-LEN-AND-0)) (4 1 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (3 3 (:REWRITE LEN-OF-CDDR-WHEN-EQUAL-OF-LEN)) ) (TRUE-ALISTP-CAR (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (2 2 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (2 2 (:LINEAR LEN-WHEN-PREFIXP)) (2 1 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (1 1 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE DEFAULT-CAR)) ) (TRUE-ALISTP-CDAR (18 1 (:REWRITE CONSP-FROM-LEN-CHEAP)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (4 4 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (4 4 (:LINEAR LEN-WHEN-PREFIXP)) (4 1 (:REWRITE TRUE-ALISTP-CAR)) (3 2 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (2 2 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (2 2 (:REWRITE DEFAULT-CAR)) (2 1 (:REWRITE DEFAULT-<-2)) (2 1 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (1 1 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:REWRITE CONSP-WHEN-LEN-GREATER)) (1 1 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) ) (COLLECT-LOCS (22 5 (:REWRITE CONSP-FROM-LEN-CHEAP)) (5 5 (:TYPE-PRESCRIPTION LEN)) (5 5 (:REWRITE CONSP-WHEN-LEN-GREATER)) (5 5 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (3 3 (:REWRITE DEFAULT-CAR)) (3 2 (:REWRITE DEFAULT-CDR)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (2 2 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (2 2 (:LINEAR LEN-WHEN-PREFIXP)) (2 1 (:REWRITE DEFAULT-<-2)) (1 1 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) ) (MAX-PLAN-LENGTH (24 7 (:REWRITE CONSP-FROM-LEN-CHEAP)) (7 7 (:REWRITE CONSP-WHEN-LEN-GREATER)) (7 7 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (5 5 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (5 5 (:REWRITE DEFAULT-CAR)) (5 3 (:REWRITE DEFAULT-CDR)) (4 3 (:REWRITE DEFAULT-<-2)) (4 3 (:REWRITE DEFAULT-<-1)) (4 2 (:REWRITE DEFAULT-+-2)) (2 2 (:REWRITE DEFAULT-+-1)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (2 2 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (2 2 (:LINEAR LEN-WHEN-PREFIXP)) (1 1 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) ) (NATP-OF-MAX-PLAN-LENGTH (258 197 (:REWRITE DEFAULT-<-2)) (225 197 (:REWRITE DEFAULT-<-1)) (164 164 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (142 142 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (142 142 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (142 142 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (142 142 (:LINEAR LEN-WHEN-PREFIXP)) (95 83 (:REWRITE DEFAULT-CDR)) (85 31 (:REWRITE TRUE-ALISTP-CAR)) (74 74 (:REWRITE DEFAULT-CAR)) (69 69 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (68 41 (:REWRITE DEFAULT-+-2)) (61 61 (:REWRITE CONSP-WHEN-LEN-GREATER)) (54 54 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (46 23 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (41 41 (:REWRITE DEFAULT-+-1)) (23 23 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (15 15 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) ) (PRINT-PLAN-STATS (96 1 (:DEFINITION REMOVE-DUPLICATES-EQUAL)) (32 1 (:REWRITE MEMBER-EQUAL-BECOMES-MEMBERP)) (20 1 (:REWRITE CONSP-FROM-LEN-CHEAP)) (17 1 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (16 8 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (12 1 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (12 1 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (8 8 (:TYPE-PRESCRIPTION MEMBER-EQUAL)) (6 6 (:TYPE-PRESCRIPTION MEMBERP)) (6 3 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (6 3 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (4 2 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (4 2 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (4 2 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (4 2 (:REWRITE MEMBER-EQUAL-OF-CAR-SAME)) (4 2 (:REWRITE DEFAULT-UNARY-MINUS)) (3 3 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (3 3 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (3 3 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (3 3 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (3 3 (:REWRITE DEFAULT-CDR)) (2 2 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (2 2 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (2 2 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (2 2 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (2 2 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (2 2 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (2 2 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (2 2 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (2 2 (:REWRITE DEFAULT-CAR)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (2 2 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (2 2 (:LINEAR LEN-WHEN-PREFIXP)) (2 1 (:REWRITE DEFAULT-<-2)) (2 1 (:REWRITE DEFAULT-+-2)) (2 1 (:REWRITE DEFAULT-+-1)) (2 1 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (1 1 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (1 1 (:REWRITE MEMBERP-OF-CAR-SAME)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:REWRITE CONSP-WHEN-LEN-GREATER)) (1 1 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) ) (NODEP-CAR-LAST-NODE-LIST) (DESTINATION-OF-PATH (72 4 (:REWRITE CONSP-FROM-LEN-CHEAP)) (21 1 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (20 20 (:TYPE-PRESCRIPTION LEN)) (8 8 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (8 8 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (8 8 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (8 8 (:LINEAR LEN-WHEN-PREFIXP)) (8 4 (:REWRITE DEFAULT-<-2)) (4 4 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (4 4 (:REWRITE DEFAULT-<-1)) (4 4 (:REWRITE CONSP-WHEN-LEN-GREATER)) (4 4 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (4 4 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (2 2 (:REWRITE USE-ALL-NODE-LIST-P-2)) (2 2 (:REWRITE USE-ALL-NODE-LIST-P)) (2 2 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (2 2 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) ) (NODEP-OF-DESTINATION-OF-PATH (66 3 (:REWRITE CONSP-FROM-LEN-CHEAP)) (34 1 (:DEFINITION LAST)) (29 1 (:REWRITE NODE-LIST-FIX-NODE-LIST-P)) (21 1 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (19 19 (:TYPE-PRESCRIPTION LEN)) (8 8 (:TYPE-PRESCRIPTION NODE-LIST-FIX)) (8 1 (:REWRITE LEN-OF-CDR)) (7 3 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (6 6 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (6 6 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (6 6 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (6 6 (:LINEAR LEN-WHEN-PREFIXP)) (6 5 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (6 3 (:REWRITE DEFAULT-<-2)) (4 4 (:TYPE-PRESCRIPTION NODE-LIST-P)) (4 2 (:TYPE-PRESCRIPTION NODEP-CAR-LAST-NODE-LIST)) (3 3 (:REWRITE DEFAULT-<-1)) (3 3 (:REWRITE CONSP-WHEN-LEN-GREATER)) (3 3 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (2 2 (:REWRITE DEFAULT-CDR)) (2 1 (:REWRITE DEFAULT-CAR)) (2 1 (:REWRITE DEFAULT-+-2)) (1 1 (:REWRITE USE-NODE-LIST-P-2)) (1 1 (:REWRITE USE-NODE-LIST-P)) (1 1 (:REWRITE USE-ALL-NODE-LIST-P-2)) (1 1 (:REWRITE USE-ALL-NODE-LIST-P)) (1 1 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (1 1 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (1 1 (:REWRITE NODE-OF-DGRAPH-P-NODEP)) (1 1 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE EQUAL-OF-LEN-AND-0)) (1 1 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (DESTINATIONS-OF-PATHS (108 6 (:REWRITE CONSP-FROM-LEN-CHEAP)) (31 31 (:TYPE-PRESCRIPTION LEN)) (23 3 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (12 12 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (12 12 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (12 12 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (12 12 (:LINEAR LEN-WHEN-PREFIXP)) (12 6 (:REWRITE DEFAULT-<-2)) (6 6 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (6 6 (:REWRITE DEFAULT-<-1)) (6 6 (:REWRITE CONSP-WHEN-LEN-GREATER)) (6 6 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (6 6 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (5 5 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (2 1 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (2 1 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (2 1 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (1 1 (:REWRITE USE-ALL-NODE-LIST-P-2)) (1 1 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (1 1 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (1 1 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (1 1 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (1 1 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (1 1 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (1 1 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (1 1 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-CAR)) ) (NODE-LIST-P-OF-DESTINATIONS-OF-PATHS (252 15 (:REWRITE CONSP-FROM-LEN-CHEAP)) (211 9 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (30 15 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (29 19 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (28 28 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (28 28 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (28 28 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (28 28 (:LINEAR LEN-WHEN-PREFIXP)) (28 14 (:REWRITE DEFAULT-<-2)) (18 9 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (15 15 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (15 1 (:REWRITE DEFAULT-CAR)) (14 14 (:REWRITE DEFAULT-<-1)) (14 14 (:REWRITE CONSP-WHEN-LEN-GREATER)) (9 9 (:REWRITE USE-ALL-NODE-LIST-P-2)) (9 9 (:REWRITE USE-ALL-NODE-LIST-P)) (9 9 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (9 9 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (2 2 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (1 1 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) ) (FILTER-UNPRODUCTIVE-PLANS (229 17 (:REWRITE CONSP-FROM-LEN-CHEAP)) (105 5 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (38 9 (:REWRITE DEFAULT-CAR)) (30 17 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (25 25 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (24 24 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (24 24 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (24 24 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (24 24 (:LINEAR LEN-WHEN-PREFIXP)) (24 12 (:REWRITE DEFAULT-<-2)) (23 5 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (17 17 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (15 5 (:REWRITE TRUE-ALISTP-CAR)) (13 1 (:REWRITE DEFAULT-CDR)) (12 12 (:REWRITE DEFAULT-<-1)) (12 12 (:REWRITE CONSP-WHEN-LEN-GREATER)) (10 10 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (8 4 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (7 7 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (6 3 (:REWRITE IFF-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (5 5 (:REWRITE USE-ALL-NODE-LIST-P-2)) (5 5 (:REWRITE USE-ALL-NODE-LIST-P)) (5 5 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (5 5 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (5 5 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) ) (FILTER-UNPRODUCTIVE-PLANS-OF-NIL) (FILTER-UNPRODUCTIVE-PLANS-OF-CONS) (FILTER-UNPRODUCTIVE-PLANS-OF-TRUE-LIST-FIX) (FILTER-UNPRODUCTIVE-PLANS-OPENER) (FILTER-UNPRODUCTIVE-PLANS-OF-APPEND) (CAR-OF-FILTER-UNPRODUCTIVE-PLANS) (CDR-OF-FILTER-UNPRODUCTIVE-PLANS) (LEN-OF-FILTER-UNPRODUCTIVE-PLANS) (CONSP-OF-FILTER-UNPRODUCTIVE-PLANS) (FILTER-UNPRODUCTIVE-PLANS-IFF) (TRUE-LISTP-OF-FILTER-UNPRODUCTIVE-PLANS) (FIRSTN-OF-FILTER-UNPRODUCTIVE-PLANS) (TAKE-OF-FILTER-UNPRODUCTIVE-PLANS) (NTH-OF-FILTER-UNPRODUCTIVE-PLANS) (NTHCDR-OF-FILTER-UNPRODUCTIVE-PLANS) (FILTER-UNPRODUCTIVE-PLANS-PRESERVES-ALIST-KEYS (2421 234 (:REWRITE CONSP-FROM-LEN-CHEAP)) (1130 43 (:REWRITE PATHS-NOT-ENDING-IN-SET-WHEN-NOT-CONSP)) (778 72 (:REWRITE LEN-OF-CDR)) (664 148 (:REWRITE DEFAULT-CAR)) (502 52 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (353 119 (:REWRITE TRUE-ALISTP-CAR)) (342 38 (:REWRITE EQUAL-OF-LEN-AND-0)) (335 335 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (261 17 (:REWRITE CONSP-OF-FILTER-UNPRODUCTIVE-PLANS)) (234 234 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (210 122 (:REWRITE DEFAULT-<-2)) (198 198 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (174 174 (:REWRITE CONSP-WHEN-LEN-GREATER)) (122 122 (:REWRITE DEFAULT-<-1)) (122 61 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (118 76 (:REWRITE DEFAULT-+-2)) (108 36 (:REWRITE TRUE-ALISTP-CDR)) (92 92 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (92 92 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (92 92 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (92 92 (:LINEAR LEN-WHEN-PREFIXP)) (82 82 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (76 76 (:REWRITE DEFAULT-+-1)) (61 61 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (36 36 (:TYPE-PRESCRIPTION FILTER-UNPRODUCTIVE-PLANS)) (24 2 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (6 2 (:REWRITE NO-DUPLICATE-ALIST-CONS)) (2 2 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (2 2 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) ) (NON-TRIVIAL-PLAN-MAP-P-FILTER-UNPRODUCTIVE-PLANS (1838 142 (:REWRITE CONSP-FROM-LEN-CHEAP)) (823 6 (:REWRITE CDR-OF-FILTER-UNPRODUCTIVE-PLANS)) (677 148 (:REWRITE DEFAULT-CAR)) (564 164 (:REWRITE DEFAULT-CDR)) (436 6 (:REWRITE CAR-OF-FILTER-UNPRODUCTIVE-PLANS)) (354 94 (:REWRITE TRUE-ALISTP-CAR)) (348 41 (:REWRITE LEN-OF-CDR)) (263 257 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (212 212 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (144 48 (:REWRITE TRUE-ALISTP-CDR)) (142 142 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (129 68 (:REWRITE DEFAULT-<-2)) (108 36 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (108 6 (:REWRITE CONSP-OF-FILTER-UNPRODUCTIVE-PLANS)) (90 90 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (90 90 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (90 90 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (90 90 (:LINEAR LEN-WHEN-PREFIXP)) (84 24 (:REWRITE EQUAL-OF-LEN-AND-0)) (76 76 (:REWRITE CONSP-WHEN-LEN-GREATER)) (70 45 (:REWRITE DEFAULT-+-2)) (68 68 (:REWRITE DEFAULT-<-1)) (60 30 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (45 45 (:REWRITE DEFAULT-+-1)) (34 34 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (30 30 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (13 4 (:REWRITE FOLD-CONSTS-IN-+)) (4 4 (:REWRITE LEN-OF-CDDR-WHEN-EQUAL-OF-LEN)) ) (FILTER-UNPRODUCTIVE-PLANS-PLAN-FOR-ID-SUBSET-P (165186 70 (:REWRITE SUBSEQUENCEP-EQUAL-EQUAL-LEN)) (135980 156 (:DEFINITION TRUE-LISTP)) (113502 312 (:REWRITE NODE-LIST-P-TRUE-LISTP1)) (107752 9420 (:REWRITE CONSP-FROM-LEN-CHEAP)) (105235 532 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (71253 2800 (:REWRITE PATHS-NOT-ENDING-IN-SET-WHEN-NOT-CONSP)) (60590 858 (:REWRITE CAR-OF-FILTER-UNPRODUCTIVE-PLANS)) (55341 42 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR-RIGHT)) (54116 256 (:REWRITE TRUE-LISTP-OF-CDR-0)) (50907 3901 (:REWRITE LEN-OF-CDR)) (49664 286 (:REWRITE CDR-OF-FILTER-UNPRODUCTIVE-PLANS)) (30801 314 (:REWRITE NODE-LIST-P-OF-CDR)) (24870 2823 (:REWRITE EQUAL-OF-LEN-AND-0)) (17188 5187 (:REWRITE TRUE-ALISTP-CAR)) (12639 12277 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (9651 9651 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (9420 9420 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (7428 3896 (:REWRITE DEFAULT-<-2)) (7238 7238 (:REWRITE CONSP-WHEN-LEN-GREATER)) (7050 2350 (:REWRITE TRUE-ALISTP-CDR)) (7048 4181 (:REWRITE DEFAULT-+-2)) (6098 3049 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (4768 440 (:REWRITE CONSP-OF-FILTER-UNPRODUCTIVE-PLANS)) (4181 4181 (:REWRITE DEFAULT-+-1)) (4155 205 (:REWRITE NODE-LIST-P-OF-CDR-OF-HONS-ASSOC-EQUAL-WHEN-PATH-MAP-P0)) (3896 3896 (:REWRITE DEFAULT-<-1)) (3670 3670 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (3177 72 (:REWRITE SUBLISTP-NOT-PREFIXP)) (3049 3049 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (3004 170 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (2484 312 (:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP)) (1592 1592 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (1592 1592 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (1592 1592 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (1592 1592 (:LINEAR LEN-WHEN-PREFIXP)) (1299 142 (:REWRITE SUBLISTP-WHEN-ATOM-RIGHT)) (884 280 (:REWRITE FOLD-CONSTS-IN-+)) (834 834 (:TYPE-PRESCRIPTION TRUE-LISTP)) (630 532 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (537 127 (:REWRITE SUFFIXP$-OF-CDR)) (532 532 (:REWRITE USE-ALL-NODE-LIST-P-2)) (532 532 (:REWRITE USE-ALL-NODE-LIST-P)) (532 532 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (532 532 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (484 484 (:TYPE-PRESCRIPTION SET::SETP-TYPE)) (484 242 (:REWRITE OMAP::SETP-WHEN-MAPP)) (484 242 (:REWRITE SET::NONEMPTY-MEANS-SET)) (432 144 (:REWRITE SUFFIXP-SUBLISTP)) (416 14 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (416 14 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (392 70 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-LEFT)) (350 350 (:REWRITE LEN-OF-CDDR-WHEN-EQUAL-OF-LEN)) (288 288 (:TYPE-PRESCRIPTION SUFFIXP)) (271 271 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (271 271 (:REWRITE SUFFIXP$-TRANSITIVE)) (263 14 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (260 70 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-RIGHT)) (242 242 (:TYPE-PRESCRIPTION OMAP::MAPP)) (242 242 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE)) (242 242 (:REWRITE SET::IN-SET)) (238 56 (:REWRITE SUFFIXP$-OF-CDR-AND-CDR)) (144 144 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (144 144 (:REWRITE SUBLISTP-TRANSITIVE)) (142 142 (:REWRITE SUBLISTP-COMPLETE)) (140 70 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR)) (119 61 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (116 58 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (116 58 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (115 61 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (102 53 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (94 4 (:REWRITE PREFIXP-WHEN-EQUAL-LENGTHS)) (84 42 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (84 42 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (81 42 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (79 4 (:REWRITE PREFIXP-WHEN-PREFIXP)) (70 70 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-OF-CDR-OF-MEMBER-EQUAL)) (70 70 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-SUFFIXP$)) (70 70 (:REWRITE SUBSEQUENCEP-EQUAL-TRANSITIVE)) (61 61 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (61 61 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (61 61 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (61 61 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (56 56 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (42 42 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (42 42 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (42 42 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (42 42 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (30 1 (:REWRITE LIST-EQUIV-OF-NIL-RIGHT)) (28 28 (:REWRITE NOT-SUBSETP-EQUAL-WHEN-MEMBERP)) (14 1 (:REWRITE LIST-EQUIV-WHEN-ATOM-RIGHT)) (8 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-RIGHT)) (7 7 (:TYPE-PRESCRIPTION PREFIXP)) (6 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-LEFT)) (6 1 (:REWRITE USE-ALL-PREFIXED-P-FOR-CAR)) (5 1 (:REWRITE USE-ALL-PREFIXES-P-FOR-CAR)) (4 4 (:REWRITE PREFIXP-TRANSITIVE-1)) (4 4 (:REWRITE PREFIXP-TRANSITIVE . 2)) (4 4 (:REWRITE PREFIXP-TRANSITIVE . 1)) (4 4 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 2)) (4 4 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 1)) (2 2 (:TYPE-PRESCRIPTION ALL-PREFIXES-P)) (2 2 (:TYPE-PRESCRIPTION ALL-PREFIXED-P)) (1 1 (:TYPE-PRESCRIPTION LIST-EQUIV)) (1 1 (:REWRITE LIST-EQUIV-WHEN-ATOM-LEFT)) (1 1 (:REWRITE ALL-PREFIXES-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE ALL-PREFIXES-P-WHEN-NOT-CONSP)) (1 1 (:REWRITE ALL-PREFIXED-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE ALL-PREFIXED-P-WHEN-NOT-CONSP)) (1 1 (:REWRITE ALL-PREFIXED-P-TRANSITIVE)) ) (FILTER-UNPRODUCTIVE-PLANS-SUB-PLAN-MAP-P (138 11 (:REWRITE CONSP-FROM-LEN-CHEAP)) (105 5 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (60 6 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (49 49 (:TYPE-PRESCRIPTION LEN)) (23 11 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (17 17 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (11 11 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (10 10 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (10 10 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (10 10 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (10 10 (:LINEAR LEN-WHEN-PREFIXP)) (10 5 (:REWRITE DEFAULT-<-2)) (5 5 (:REWRITE USE-ALL-NODE-LIST-P-2)) (5 5 (:REWRITE USE-ALL-NODE-LIST-P)) (5 5 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (5 5 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (5 5 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (5 5 (:REWRITE DEFAULT-<-1)) (5 5 (:REWRITE CONSP-WHEN-LEN-GREATER)) ) (FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX (34 4 (:REWRITE CONSP-FROM-LEN-CHEAP)) (30 3 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (14 12 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (11 4 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (4 4 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (3 2 (:REWRITE DEFAULT-<-2)) (2 2 (:REWRITE DEFAULT-<-1)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (2 2 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (2 2 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (2 2 (:LINEAR LEN-WHEN-PREFIXP)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-+-2)) (1 1 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE CONSP-WHEN-LEN-GREATER)) ) (PLAN-MAP-P0-OF-FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX (1202 83 (:REWRITE CONSP-FROM-LEN-CHEAP)) (515 45 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (418 14 (:REWRITE PATHS-NOT-ENDING-IN-SET-WHEN-NOT-CONSP)) (387 69 (:REWRITE PLAN-MAP-FIX-WHEN-PLAN-MAP-P0)) (253 13 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (216 82 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (195 149 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (177 16 (:REWRITE LEN-OF-CDR)) (151 30 (:REWRITE DEFAULT-CAR)) (98 27 (:REWRITE DEFAULT-CDR)) (83 83 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (76 76 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (76 76 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (76 76 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (76 76 (:LINEAR LEN-WHEN-PREFIXP)) (76 38 (:REWRITE DEFAULT-<-2)) (66 35 (:REWRITE TRUE-ALISTP-CAR)) (65 16 (:REWRITE EQUAL-OF-LEN-AND-0)) (39 39 (:REWRITE CONSP-WHEN-LEN-GREATER)) (38 38 (:REWRITE DEFAULT-<-1)) (32 16 (:REWRITE DEFAULT-+-2)) (31 31 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (17 17 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (16 16 (:REWRITE DEFAULT-+-1)) (13 13 (:REWRITE USE-ALL-NODE-LIST-P-2)) (13 13 (:REWRITE USE-ALL-NODE-LIST-P)) (13 13 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (13 13 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (13 13 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) ) (ALISTP-OF-FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX (1014 66 (:REWRITE CONSP-FROM-LEN-CHEAP)) (617 10 (:REWRITE PATH-MAP-P-ALIST)) (597 10 (:DEFINITION PATH-MAP-P)) (508 18 (:REWRITE PATHS-NOT-ENDING-IN-SET-WHEN-NOT-CONSP)) (287 3 (:REWRITE PATH-MAP-P0-OF-CDR-WHEN-PATH-MAP-P0)) (240 21 (:REWRITE LEN-OF-CDR)) (215 39 (:REWRITE DEFAULT-CAR)) (206 50 (:REWRITE PLAN-MAP-FIX-WHEN-PLAN-MAP-P0)) (177 14 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (145 53 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (144 10 (:REWRITE OMAP::ALISTP-WHEN-MAPP)) (141 110 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (114 15 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (101 2 (:REWRITE PATH-MAP-P0-OF-CONS)) (97 19 (:REWRITE EQUAL-OF-LEN-AND-0)) (82 44 (:REWRITE TRUE-ALISTP-CAR)) (74 28 (:REWRITE DEFAULT-CDR)) (66 66 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (64 33 (:REWRITE DEFAULT-<-2)) (64 10 (:REWRITE OMAP::MFIX-IMPLIES-MAPP)) (54 54 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (54 54 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (54 54 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (54 54 (:LINEAR LEN-WHEN-PREFIXP)) (50 10 (:REWRITE OMAP::MAPP-WHEN-NOT-EMPTY)) (40 40 (:TYPE-PRESCRIPTION OMAP::MAPP)) (40 40 (:REWRITE CONSP-WHEN-LEN-GREATER)) (40 21 (:REWRITE DEFAULT-+-2)) (36 36 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (34 20 (:TYPE-PRESCRIPTION OMAP::MFIX)) (33 33 (:REWRITE DEFAULT-<-1)) (24 24 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (21 21 (:REWRITE DEFAULT-+-1)) (20 20 (:TYPE-PRESCRIPTION OMAP::EMPTY)) (20 10 (:REWRITE OMAP::MFIX-WHEN-MAPP)) (20 10 (:REWRITE OMAP::MAPP-NON-NIL-IMPLIES-NON-EMPTY)) (20 1 (:REWRITE NODE-LIST-P-OF-CDR)) (19 19 (:TYPE-PRESCRIPTION NO-DUPLICATE-ALIST-P)) (15 3 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (14 7 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (10 10 (:TYPE-PRESCRIPTION PATH-MAP-P)) (9 3 (:REWRITE NO-DUPLICATE-ALIST-CDR)) (8 8 (:TYPE-PRESCRIPTION NODE-LIST-P)) (8 2 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (7 7 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (6 2 (:REWRITE TRUE-ALISTP-CDR)) (6 2 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PLAN-MAP-P0)) (6 1 (:REWRITE USE-ALL-NODE-LIST-P-FOR-CAR)) (5 1 (:REWRITE NODE-LIST-P-OF-CDAR-WHEN-PATH-MAP-P0)) (4 4 (:REWRITE PLAN-MAP-P0-OF-PLAN-MAP-FIX)) (3 3 (:REWRITE USE-ALL-NODE-LIST-P-2)) (3 3 (:REWRITE USE-ALL-NODE-LIST-P)) (3 3 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (3 3 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (3 3 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (3 1 (:REWRITE NO-DUPLICATE-ALIST-CONS)) (2 2 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (1 1 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (1 1 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) ) (FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX (1189 89 (:REWRITE CONSP-FROM-LEN-CHEAP)) (475 49 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (425 21 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (382 67 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (375 30 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PLAN-MAP-P0)) (315 23 (:REWRITE PLAN-MAP-P0-OF-CDR-WHEN-PLAN-MAP-P0)) (276 48 (:REWRITE LEN-OF-CDR)) (276 22 (:REWRITE USE-ALL-NODE-LIST-P)) (230 158 (:REWRITE DEFAULT-CAR)) (206 13 (:REWRITE PATHS-NOT-ENDING-IN-SET-WHEN-NOT-CONSP)) (164 159 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (137 31 (:REWRITE ALL-NODE-LIST-P-OF-CDR)) (120 78 (:REWRITE DEFAULT-<-2)) (99 91 (:REWRITE DEFAULT-CDR)) (96 96 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (96 96 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (96 96 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (96 96 (:LINEAR LEN-WHEN-PREFIXP)) (94 30 (:REWRITE DRONE-ID-P-OF-CAR-WHEN-DRONE-ID-LIST-P)) (90 30 (:REWRITE DRONE-ID-P-OF-CAAR-WHEN-PATH-MAP-P0)) (87 87 (:REWRITE CONSP-WHEN-LEN-GREATER)) (78 78 (:REWRITE DEFAULT-<-1)) (67 67 (:TYPE-PRESCRIPTION MEMBERP)) (62 49 (:REWRITE DEFAULT-+-2)) (57 57 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (55 20 (:REWRITE TRUE-ALISTP-CAR)) (53 53 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (49 49 (:REWRITE DEFAULT-+-1)) (34 17 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (34 17 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (34 17 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (32 32 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (24 20 (:REWRITE DRONE-ID-LIST-P-WHEN-NOT-CONSP)) (23 21 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (22 22 (:REWRITE USE-ALL-NODE-LIST-P-2)) (22 22 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (22 22 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (20 20 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (19 19 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (18 9 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (17 17 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (17 17 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (17 17 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (17 17 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (17 17 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (15 3 (:REWRITE MEMBERP-OF-CAR-SAME)) (12 12 (:REWRITE EQUAL-OF-LEN-AND-0)) (9 9 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (9 3 (:REWRITE TRUE-ALISTP-CDR)) ) (FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX-PRESERVES-ALIST-KEYS (3076 284 (:REWRITE CONSP-FROM-LEN-CHEAP)) (1553 59 (:REWRITE PATHS-NOT-ENDING-IN-SET-WHEN-NOT-CONSP)) (1059 87 (:REWRITE LEN-OF-CDR)) (623 58 (:REWRITE ALIST-KEYS-WHEN-ATOM)) (516 446 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (512 56 (:REWRITE EQUAL-OF-LEN-AND-0)) (284 284 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (253 118 (:REWRITE TRUE-ALISTP-CAR)) (231 131 (:REWRITE DEFAULT-<-2)) (186 186 (:REWRITE CONSP-WHEN-LEN-GREATER)) (159 95 (:REWRITE DEFAULT-+-2)) (131 131 (:REWRITE DEFAULT-<-1)) (124 124 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (120 60 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (95 95 (:REWRITE DEFAULT-+-1)) (87 87 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (85 85 (:TYPE-PRESCRIPTION FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX)) (84 84 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (84 84 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (84 84 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (84 84 (:LINEAR LEN-WHEN-PREFIXP)) (60 60 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (36 1 (:DEFINITION LAST)) (33 11 (:REWRITE TRUE-ALISTP-CDR)) (24 2 (:REWRITE ALL-NODE-LIST-P-WHEN-NOT-CONSP)) (21 1 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (21 1 (:REWRITE CONSP-LAST)) (15 1 (:REWRITE USE-ALL-NODE-LIST-P)) (9 3 (:REWRITE NO-DUPLICATE-ALIST-CONS)) (4 2 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (4 2 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (4 2 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (4 1 (:REWRITE FOLD-CONSTS-IN-+)) (3 3 (:REWRITE ALL-NODE-PATH-P-ALL-NODE-LIST-P)) (2 2 (:TYPE-PRESCRIPTION LAST)) (2 2 (:TYPE-PRESCRIPTION ACONS)) (2 2 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (2 2 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (2 2 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (2 2 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (2 2 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (2 2 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (1 1 (:REWRITE USE-PATHS-NOT-ENDING-IN-SET)) (1 1 (:REWRITE USE-ALL-NODE-LIST-P-2)) (1 1 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (1 1 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (1 1 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (1 1 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) ) (NON-TRIVIAL-PLAN-MAP-P-FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX (3172 280 (:REWRITE CONSP-FROM-LEN-CHEAP)) (1089 48 (:REWRITE PATHS-NOT-ENDING-IN-SET-WHEN-NOT-CONSP)) (883 127 (:REWRITE DEFAULT-CDR)) (652 121 (:REWRITE DEFAULT-CAR)) (460 410 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (349 160 (:REWRITE TRUE-ALISTP-CAR)) (280 280 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (217 112 (:REWRITE DEFAULT-<-2)) (184 184 (:REWRITE CONSP-WHEN-LEN-GREATER)) (175 175 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (161 87 (:REWRITE DEFAULT-+-2)) (158 79 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (112 112 (:REWRITE DEFAULT-<-1)) (87 87 (:REWRITE DEFAULT-+-1)) (84 84 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (80 80 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (80 80 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (80 80 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (80 80 (:LINEAR LEN-WHEN-PREFIXP)) (79 79 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (54 54 (:TYPE-PRESCRIPTION ACONS)) (42 14 (:REWRITE TRUE-ALISTP-CDR)) (22 2 (:LINEAR LEN-OF-CDR-LINEAR-STRONG)) ) (FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX-PLAN-FOR-ID-SUBSET-P (47344 60 (:REWRITE SUBSEQUENCEP-EQUAL-EQUAL-LEN)) (40166 216 (:REWRITE NODE-LIST-P-TRUE-LISTP1)) (36702 342 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (34225 2670 (:REWRITE CONSP-FROM-LEN-CHEAP)) (33925 108 (:DEFINITION TRUE-LISTP)) (26248 12 (:DEFINITION SUBSETP-EQUAL)) (14298 192 (:REWRITE NODE-LIST-P-OF-CDR)) (13224 477 (:REWRITE PATHS-NOT-ENDING-IN-SET-WHEN-NOT-CONSP)) (12397 888 (:REWRITE LEN-OF-CDR)) (11023 36 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR-RIGHT)) (9851 168 (:REWRITE TRUE-LISTP-OF-CDR-0)) (5937 713 (:REWRITE EQUAL-OF-LEN-AND-0)) (4241 3347 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (2789 62 (:REWRITE SUBLISTP-NOT-PREFIXP)) (2670 2670 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (2507 1242 (:REWRITE DEFAULT-<-2)) (2471 1040 (:REWRITE TRUE-ALISTP-CAR)) (2099 2099 (:REWRITE CONSP-WHEN-LEN-GREATER)) (1625 900 (:REWRITE DEFAULT-+-2)) (1624 216 (:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP)) (1394 697 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (1309 1309 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (1242 1242 (:REWRITE DEFAULT-<-1)) (1232 122 (:REWRITE SUBLISTP-WHEN-ATOM-RIGHT)) (1140 1140 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (1140 1140 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (1140 1140 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (1140 1140 (:LINEAR LEN-WHEN-PREFIXP)) (900 900 (:REWRITE DEFAULT-+-1)) (894 114 (:REWRITE NODE-LIST-P-OF-CDR-OF-HONS-ASSOC-EQUAL-WHEN-PATH-MAP-P0)) (880 36 (:REWRITE MEMBER-EQUAL-BECOMES-MEMBERP)) (847 847 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (697 697 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (612 612 (:TYPE-PRESCRIPTION TRUE-LISTP)) (461 109 (:REWRITE SUFFIXP$-OF-CDR)) (426 342 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (372 124 (:REWRITE SUFFIXP-SUBLISTP)) (366 122 (:REWRITE TRUE-ALISTP-CDR)) (366 12 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR-WHEN-NOT-MEMBER-EQUAL)) (366 12 (:REWRITE NOT-MEMBER-EQUAL-OF-CDR)) (352 60 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-LEFT)) (342 342 (:REWRITE USE-ALL-NODE-LIST-P-2)) (342 342 (:REWRITE USE-ALL-NODE-LIST-P)) (342 342 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (342 342 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (312 312 (:TYPE-PRESCRIPTION SET::SETP-TYPE)) (312 156 (:REWRITE OMAP::SETP-WHEN-MAPP)) (312 156 (:REWRITE SET::NONEMPTY-MEANS-SET)) (248 248 (:TYPE-PRESCRIPTION SUFFIXP)) (242 98 (:REWRITE PATH-MAP-P0-WHEN-NOT-CONSP)) (240 60 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-ATOM-RIGHT)) (233 233 (:REWRITE SUFFIXP$-TRANSITIVE-2)) (233 233 (:REWRITE SUFFIXP$-TRANSITIVE)) (232 12 (:REWRITE MEMBERP-OF-CDR-WHEN-NOT-MEMBERP)) (204 48 (:REWRITE SUFFIXP$-OF-CDR-AND-CDR)) (156 156 (:TYPE-PRESCRIPTION MEMBERP)) (156 156 (:TYPE-PRESCRIPTION OMAP::MAPP)) (156 156 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE)) (156 156 (:REWRITE SET::IN-SET)) (124 124 (:TYPE-PRESCRIPTION ACONS)) (124 124 (:REWRITE SUBLISTP-WHEN-SUBLISTP-AND-PREFIXP)) (124 124 (:REWRITE SUBLISTP-TRANSITIVE)) (122 122 (:REWRITE SUBLISTP-COMPLETE)) (120 60 (:REWRITE SUBSEQUENCEP-EQUAL-OF-CDR)) (104 48 (:REWRITE MEMBERP-WHEN-NOT-CONSP-CHEAP)) (104 48 (:REWRITE MEMBERP-WHEN-NOT-CONS-OF-CDR-CHEAP)) (96 48 (:REWRITE MEMBERP-WHEN-SINGLETON-CHEAP)) (96 48 (:REWRITE MEMBERP-WHEN-NOT-MEMBERP-OF-CDR-CHEAP)) (96 48 (:REWRITE MEMBERP-WHEN-MEMBERP-OF-CDR-CHEAP)) (94 4 (:REWRITE PREFIXP-WHEN-EQUAL-LENGTHS)) (79 4 (:REWRITE PREFIXP-WHEN-PREFIXP)) (78 36 (:REWRITE MEMBER-EQUAL-WHEN-NOT-CONSP-CHEAP)) (76 76 (:REWRITE LEN-OF-CDDR-WHEN-EQUAL-OF-LEN)) (72 36 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP)) (72 36 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP)) (60 60 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-OF-CDR-OF-MEMBER-EQUAL)) (60 60 (:REWRITE SUBSEQUENCEP-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-SUFFIXP$)) (60 60 (:REWRITE SUBSEQUENCEP-EQUAL-TRANSITIVE)) (48 48 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-OF-TAKE)) (48 48 (:REWRITE NOT-MEMBERP-WHEN-MEMBERP-AND-NOT-INTERSECTION-EQUAL-CHEAP)) (48 48 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-2)) (48 48 (:REWRITE MEMBERP-WHEN-SUBSETP-EQUAL-1)) (48 48 (:REWRITE MEMBERP-WHEN-NOT-EQUAL-OF-CAR-CHEAP)) (48 48 (:REWRITE MEMBERP-OF-CONSTANT-WHEN-NOT-MEMBER-OF-CONSTANT)) (48 12 (:REWRITE FOLD-CONSTS-IN-+)) (36 36 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL)) (36 36 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL)) (36 36 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR)) (36 36 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM)) (30 1 (:REWRITE LIST-EQUIV-OF-NIL-RIGHT)) (24 24 (:REWRITE NOT-SUBSETP-EQUAL-WHEN-MEMBERP)) (14 1 (:REWRITE LIST-EQUIV-WHEN-ATOM-RIGHT)) (8 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-RIGHT)) (7 7 (:TYPE-PRESCRIPTION PREFIXP)) (6 2 (:REWRITE PREFIXP-WHEN-NOT-CONSP-LEFT)) (6 1 (:REWRITE USE-ALL-PREFIXED-P-FOR-CAR)) (5 1 (:REWRITE USE-ALL-PREFIXES-P-FOR-CAR)) (4 4 (:REWRITE PREFIXP-TRANSITIVE-1)) (4 4 (:REWRITE PREFIXP-TRANSITIVE . 2)) (4 4 (:REWRITE PREFIXP-TRANSITIVE . 1)) (4 4 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 2)) (4 4 (:REWRITE PREFIXP-ONE-WAY-OR-ANOTHER . 1)) (2 2 (:TYPE-PRESCRIPTION ALL-PREFIXES-P)) (2 2 (:TYPE-PRESCRIPTION ALL-PREFIXED-P)) (1 1 (:TYPE-PRESCRIPTION LIST-EQUIV)) (1 1 (:REWRITE LIST-EQUIV-WHEN-ATOM-LEFT)) (1 1 (:REWRITE ALL-PREFIXES-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE ALL-PREFIXES-P-WHEN-NOT-CONSP)) (1 1 (:REWRITE ALL-PREFIXED-P-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE ALL-PREFIXED-P-WHEN-NOT-CONSP)) (1 1 (:REWRITE ALL-PREFIXED-P-TRANSITIVE)) ) (FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX-SUB-PLAN-MAP-P (138 11 (:REWRITE CONSP-FROM-LEN-CHEAP)) (105 5 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP)) (60 6 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (49 49 (:TYPE-PRESCRIPTION LEN)) (23 11 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (17 17 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (11 11 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (10 10 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (10 10 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (10 10 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (10 10 (:LINEAR LEN-WHEN-PREFIXP)) (10 5 (:REWRITE DEFAULT-<-2)) (5 5 (:REWRITE USE-ALL-NODE-LIST-P-2)) (5 5 (:REWRITE USE-ALL-NODE-LIST-P)) (5 5 (:REWRITE NODE-PATH-P-NODE-LIST-P)) (5 5 (:REWRITE NODE-PATH-FROM-P-IMPLIES-NODE-LIST-P)) (5 5 (:REWRITE NODE-LIST-P-WHEN-NOT-CONSP-CHEAP)) (5 5 (:REWRITE DEFAULT-<-1)) (5 5 (:REWRITE CONSP-WHEN-LEN-GREATER)) ) (FILTER-REDUNDANT-DESTINATION-PLANS-1) (PLAN-MAP-P0-OF-FILTER-REDUNDANT-DESTINATION-PLANS-1) (NON-TRIVIAL-PLAN-MAP-P-FILTER-REDUNDANT-DESTINATION-PLANS-1) (FILTER-REDUNDANT-DESTINATION-PLANS-1-SUB-PLAN-MAP-P (108 1 (:DEFINITION FILTER-REDUNDANT-DESTINATION-PLANS-1-AUX)) (92 8 (:REWRITE CONSP-FROM-LEN-CHEAP)) (42 3 (:REWRITE DEFAULT-CAR)) (34 34 (:TYPE-PRESCRIPTION LEN)) (25 1 (:DEFINITION ACONS)) (24 1 (:REWRITE CONS-CAR-CDR)) (20 2 (:REWRITE PLAN-MAP-P0-WHEN-NOT-CONSP)) (16 1 (:REWRITE LEN-OF-CDR)) (14 6 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (13 3 (:REWRITE DEFAULT-CDR)) (12 12 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (9 1 (:REWRITE EQUAL-OF-LEN-AND-0)) (8 8 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (6 4 (:REWRITE TRUE-ALISTP-CAR)) (6 3 (:REWRITE DEFAULT-<-2)) (6 2 (:REWRITE PATHS-NOT-ENDING-IN-SET-ID)) (4 4 (:REWRITE CONSP-WHEN-LEN-GREATER)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL)) (4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP)) (4 4 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2)) (4 4 (:LINEAR LEN-WHEN-PREFIXP)) (4 2 (:REWRITE CONSP-OF-CAR-WHEN-SYMBOL-TERM-ALISTP-CHEAP)) (3 3 (:REWRITE DEFAULT-<-1)) (2 2 (:TYPE-PRESCRIPTION TRUE-ALISTP)) (2 2 (:TYPE-PRESCRIPTION SYMBOL-TERM-ALISTP)) (2 2 (:TYPE-PRESCRIPTION ALL-NODE-LIST-P)) (2 2 (:REWRITE ALL-NODE-LIST-P-OF-CDAR-WHEN-PLAN-MAP-P0)) (2 1 (:REWRITE DEFAULT-+-2)) (1 1 (:REWRITE PLAN-MAP-FIX-WHEN-PLAN-MAP-P0)) (1 1 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) )
e08df341273c25acbe47fe4003a247af413c7577a3c4f890da374f7129c3104f
coinmetrics/haskell-tools
JsonRpc.hs
# LANGUAGE OverloadedLists , OverloadedStrings # module CoinMetrics.JsonRpc ( JsonRpc() , newJsonRpc , jsonRpcRequest , nonJsonRpcRequest ) where import qualified Data.Aeson as J import qualified Data.Aeson.Types as J import qualified Data.ByteString as B import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Network.HTTP.Client as H import CoinMetrics.Util data JsonRpc = JsonRpc { jsonRpc_httpManager :: !H.Manager , jsonRpc_httpRequest :: !H.Request } newJsonRpc :: H.Manager -> H.Request -> Maybe (T.Text, T.Text) -> JsonRpc newJsonRpc httpManager httpRequest maybeCredentials = JsonRpc { jsonRpc_httpManager = httpManager , jsonRpc_httpRequest = maybe id (\(authName, authPass) -> H.applyBasicAuth (T.encodeUtf8 authName) (T.encodeUtf8 authPass)) maybeCredentials httpRequest { H.method = "POST" , H.requestHeaders = ("Content-Type", "application/json") : H.requestHeaders httpRequest } } jsonRpcRequest :: (J.FromJSON r, J.ToJSON p) => JsonRpc -> T.Text -> p -> IO r jsonRpcRequest JsonRpc { jsonRpc_httpManager = httpManager , jsonRpc_httpRequest = httpRequest } method params = do body <- H.responseBody <$> tryWithRepeat (H.httpLbs httpRequest { H.requestBody = H.RequestBodyLBS $ J.encode $ J.Object [ ("jsonrpc", "2.0") , ("method", J.String method) , ("params", J.toJSON params) , ("id", J.String "1") ] } httpManager) case J.eitherDecode' body of Right obj -> case J.parse (J..: "result") obj of J.Success result -> return result J.Error err -> fail err Left err -> fail err nonJsonRpcRequest :: (J.FromJSON r, J.ToJSON p) => JsonRpc -> B.ByteString -> p -> IO r nonJsonRpcRequest JsonRpc { jsonRpc_httpManager = httpManager , jsonRpc_httpRequest = httpRequest } path params = do body <- H.responseBody <$> tryWithRepeat (H.httpLbs httpRequest { H.requestBody = H.RequestBodyLBS $ J.encode $ J.toJSON params , H.path = path } httpManager) either fail return $ J.eitherDecode' body
null
https://raw.githubusercontent.com/coinmetrics/haskell-tools/94d59497b6c4d829dd680df82c71fe607877ae76/coinmetrics/CoinMetrics/JsonRpc.hs
haskell
# LANGUAGE OverloadedLists , OverloadedStrings # module CoinMetrics.JsonRpc ( JsonRpc() , newJsonRpc , jsonRpcRequest , nonJsonRpcRequest ) where import qualified Data.Aeson as J import qualified Data.Aeson.Types as J import qualified Data.ByteString as B import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Network.HTTP.Client as H import CoinMetrics.Util data JsonRpc = JsonRpc { jsonRpc_httpManager :: !H.Manager , jsonRpc_httpRequest :: !H.Request } newJsonRpc :: H.Manager -> H.Request -> Maybe (T.Text, T.Text) -> JsonRpc newJsonRpc httpManager httpRequest maybeCredentials = JsonRpc { jsonRpc_httpManager = httpManager , jsonRpc_httpRequest = maybe id (\(authName, authPass) -> H.applyBasicAuth (T.encodeUtf8 authName) (T.encodeUtf8 authPass)) maybeCredentials httpRequest { H.method = "POST" , H.requestHeaders = ("Content-Type", "application/json") : H.requestHeaders httpRequest } } jsonRpcRequest :: (J.FromJSON r, J.ToJSON p) => JsonRpc -> T.Text -> p -> IO r jsonRpcRequest JsonRpc { jsonRpc_httpManager = httpManager , jsonRpc_httpRequest = httpRequest } method params = do body <- H.responseBody <$> tryWithRepeat (H.httpLbs httpRequest { H.requestBody = H.RequestBodyLBS $ J.encode $ J.Object [ ("jsonrpc", "2.0") , ("method", J.String method) , ("params", J.toJSON params) , ("id", J.String "1") ] } httpManager) case J.eitherDecode' body of Right obj -> case J.parse (J..: "result") obj of J.Success result -> return result J.Error err -> fail err Left err -> fail err nonJsonRpcRequest :: (J.FromJSON r, J.ToJSON p) => JsonRpc -> B.ByteString -> p -> IO r nonJsonRpcRequest JsonRpc { jsonRpc_httpManager = httpManager , jsonRpc_httpRequest = httpRequest } path params = do body <- H.responseBody <$> tryWithRepeat (H.httpLbs httpRequest { H.requestBody = H.RequestBodyLBS $ J.encode $ J.toJSON params , H.path = path } httpManager) either fail return $ J.eitherDecode' body
09b2eef5be5730e0cabc5ef4c45d54ab4e7fbea3735c3e70a5905eeb4cca5af3
Opetushallitus/ataru
autosave.cljs
(ns ataru.virkailija.autosave (:require-macros [cljs.core.async.macros :refer [go go-loop]]) (:require [re-frame.core :refer [subscribe]] [ataru.cljs-util :refer [debounce]] [cljs.core.match :refer-macros [match]] [cljs.core.async :as a :refer [chan <! >! close! alts! timeout sliding-buffer]] [taoensso.timbre :as log])) (defn stop-autosave! [stop-fn] (when stop-fn (stop-fn))) (defn interval-loop [{:keys [interval-ms subscribe-path handler ; extra predicate for changing whether a change should be ; propagated to the db changed-predicate last-autosaved-form] :or {interval-ms 2000 changed-predicate not=}}] {:pre [(integer? interval-ms) (vector? subscribe-path)]} (let [value-to-watch (subscribe [:state-query subscribe-path]) previous (atom (or last-autosaved-form @value-to-watch)) change (chan (sliding-buffer 1)) watch (fn [_ _ old new] (do (reset! previous old) (go (>! change [old new])))) stop? (atom false) stop-fn (fn [] (do (reset! stop? true) (close! change)) true) bounce (debounce handler) when-changed-save (fn [save-fn current prev] (when (changed-predicate current prev) (save-fn current prev)))] (do (-add-watch value-to-watch :autosave watch) (go-loop [] (<! (timeout 500)) (if (and @value-to-watch (not @stop?)) (recur) (log/info "Stopping autosave at" subscribe-path))) (go-loop [] (when-let [[prev current] (<! change)] (when-changed-save bounce current prev) (recur)) ; save right before exiting loop (when-let [current @value-to-watch] (when-changed-save handler current @previous))) (when (some? last-autosaved-form) (go (>! change [last-autosaved-form @value-to-watch])))) stop-fn))
null
https://raw.githubusercontent.com/Opetushallitus/ataru/2d8ef1d3f972621e301a3818567d4e11219d2e82/src/cljs/ataru/virkailija/autosave.cljs
clojure
extra predicate for changing whether a change should be propagated to the db save right before exiting loop
(ns ataru.virkailija.autosave (:require-macros [cljs.core.async.macros :refer [go go-loop]]) (:require [re-frame.core :refer [subscribe]] [ataru.cljs-util :refer [debounce]] [cljs.core.match :refer-macros [match]] [cljs.core.async :as a :refer [chan <! >! close! alts! timeout sliding-buffer]] [taoensso.timbre :as log])) (defn stop-autosave! [stop-fn] (when stop-fn (stop-fn))) (defn interval-loop [{:keys [interval-ms subscribe-path handler changed-predicate last-autosaved-form] :or {interval-ms 2000 changed-predicate not=}}] {:pre [(integer? interval-ms) (vector? subscribe-path)]} (let [value-to-watch (subscribe [:state-query subscribe-path]) previous (atom (or last-autosaved-form @value-to-watch)) change (chan (sliding-buffer 1)) watch (fn [_ _ old new] (do (reset! previous old) (go (>! change [old new])))) stop? (atom false) stop-fn (fn [] (do (reset! stop? true) (close! change)) true) bounce (debounce handler) when-changed-save (fn [save-fn current prev] (when (changed-predicate current prev) (save-fn current prev)))] (do (-add-watch value-to-watch :autosave watch) (go-loop [] (<! (timeout 500)) (if (and @value-to-watch (not @stop?)) (recur) (log/info "Stopping autosave at" subscribe-path))) (go-loop [] (when-let [[prev current] (<! change)] (when-changed-save bounce current prev) (recur)) (when-let [current @value-to-watch] (when-changed-save handler current @previous))) (when (some? last-autosaved-form) (go (>! change [last-autosaved-form @value-to-watch])))) stop-fn))
9d6f5773cd6936ca1acefe7b311136dc237b1d326576dbe9a675d9d4f63cc6b0
Convex-Dev/convex.cljc
key_pair.clj
(ns convex.recipe.key-pair "Key pairs are essential, they are used by clients to sign transactions and by peers to sign blocks of transactions. This example shows how to create a key pair and store it securely in a PFX file. Storing key pairs is always a sensitive topic. A PFX file allows storing one or several key pairs where each is given a alias and protected by a dedicated password. The file itself can be protected by a password as well. Creating and handling Ed25519 key pairs is done using namespace [[convex.sign]]. Creating and handling PFX iles is done using namespace [[convex.pfx]]. More information about public-key cryptography: -key_cryptography" {:author "Adam Helinski"} (:require [convex.key-pair :as $.key-pair] [convex.pfx :as $.pfx])) One plausible example (defn retrieve "Tries to load the key pair from file 'keystore.pfx' in given `dir`. When not found, generates a new key pair and saves it in a new file. A real application might require more sophisticated error handling. Returns the key pair." [dir] (let [file-key-store (str dir "/keystore.pfx")] (try (-> ($.pfx/load file-key-store) ($.pfx/key-pair-get "my-key-pair" "my-password")) (catch Throwable _ex (let [key-pair ($.key-pair/ed25519)] (-> ($.pfx/create file-key-store) ($.pfx/key-pair-set "my-key-pair" key-pair "my-password") ($.pfx/save file-key-store)) key-pair))))) ;;;;;;;;;; (comment ;; Example directory where key pair will be stored. ;; (def dir "private/recipe/key-pair/") The first time , the key pair is generated and stored in a PFX file . ;; ;; Each subsequent time, the key pair is always retrieved from that file. ;; ;; Deleting that 'keystore.pfx' file in this directory will lose it forever. ;; (retrieve dir) ;; ;; Let us inspect the core ideas in `retrieve`. ;; ;; Generating a key pair. ;; (def key-pair ($.key-pair/ed25519)) ;; File for storing our "key store" capable of securely hosting one or several key pairs. ;; (def file (str dir "/keystore.pfx")) ;; We create a file for our "key store" capable of securely hosting one or several key pairs, ;; our key pair under an alias and protected by a password. Lastly, the updated key store is ;; saved to the file. ;; (-> ($.pfx/create file) ($.pfx/key-pair-set "my-key-pair" key-pair "my-password") ($.pfx/save file)) ;; At any later time, we can load that file and retrieve our key pair by providing its alias and ;; its password. ;; (= key-pair (-> ($.pfx/load file) ($.pfx/key-pair-get "my-key-pair" "my-password"))) ;; ;; Although not mandatory, it is a good idea also specifying a password for the key store itself ;; when using [[$.pfx/create]], [[$.pfx/save]], and [[$.pfx/load]]. ;; )
null
https://raw.githubusercontent.com/Convex-Dev/convex.cljc/effce7127933c0733a7ef00f4ede8fc83277ab28/module/recipe/src/main/clj/convex/recipe/key_pair.clj
clojure
Example directory where key pair will be stored. Each subsequent time, the key pair is always retrieved from that file. Deleting that 'keystore.pfx' file in this directory will lose it forever. Let us inspect the core ideas in `retrieve`. Generating a key pair. File for storing our "key store" capable of securely hosting one or several key pairs. We create a file for our "key store" capable of securely hosting one or several key pairs, our key pair under an alias and protected by a password. Lastly, the updated key store is saved to the file. At any later time, we can load that file and retrieve our key pair by providing its alias and its password. Although not mandatory, it is a good idea also specifying a password for the key store itself when using [[$.pfx/create]], [[$.pfx/save]], and [[$.pfx/load]].
(ns convex.recipe.key-pair "Key pairs are essential, they are used by clients to sign transactions and by peers to sign blocks of transactions. This example shows how to create a key pair and store it securely in a PFX file. Storing key pairs is always a sensitive topic. A PFX file allows storing one or several key pairs where each is given a alias and protected by a dedicated password. The file itself can be protected by a password as well. Creating and handling Ed25519 key pairs is done using namespace [[convex.sign]]. Creating and handling PFX iles is done using namespace [[convex.pfx]]. More information about public-key cryptography: -key_cryptography" {:author "Adam Helinski"} (:require [convex.key-pair :as $.key-pair] [convex.pfx :as $.pfx])) One plausible example (defn retrieve "Tries to load the key pair from file 'keystore.pfx' in given `dir`. When not found, generates a new key pair and saves it in a new file. A real application might require more sophisticated error handling. Returns the key pair." [dir] (let [file-key-store (str dir "/keystore.pfx")] (try (-> ($.pfx/load file-key-store) ($.pfx/key-pair-get "my-key-pair" "my-password")) (catch Throwable _ex (let [key-pair ($.key-pair/ed25519)] (-> ($.pfx/create file-key-store) ($.pfx/key-pair-set "my-key-pair" key-pair "my-password") ($.pfx/save file-key-store)) key-pair))))) (comment (def dir "private/recipe/key-pair/") The first time , the key pair is generated and stored in a PFX file . (retrieve dir) (def key-pair ($.key-pair/ed25519)) (def file (str dir "/keystore.pfx")) (-> ($.pfx/create file) ($.pfx/key-pair-set "my-key-pair" key-pair "my-password") ($.pfx/save file)) (= key-pair (-> ($.pfx/load file) ($.pfx/key-pair-get "my-key-pair" "my-password"))) )
c7f1edd29e4a80b1e8e87615a5947a4c910f3fe2153d1539514f698dcbfa3c67
JacquesCarette/Drasil
TableOfAbbAndAcronyms.hs
-- | Standard code to make a table of abbreviations and acronyms. module Drasil.Sections.TableOfAbbAndAcronyms (tableAbbAccGen, tableAbbAccRef) where import Language.Drasil import Data.Drasil.Concepts.Documentation (abbreviation, fullForm, abbAcc) import Control.Lens ((^.)) import Data.List (sortBy) import Data.Function (on) -- | Helper function that gets the acronym out of an 'Idea'. select :: (Idea s) => [s] -> [(String, s)] select [] = [] select (x:xs) = case getA x of Nothing -> select xs Just y -> (y, x) : select xs -- | The actual table creation function. tableAbbAccGen :: (Idea s) => [s] -> LabelledContent tableAbbAccGen ls = let chunks = sortBy (compare `on` fst) $ select ls in llcc tableAbbAccRef $ Table (map titleize [abbreviation, fullForm]) (mkTable [\(a,_) -> S a, \(_,b) -> titleize b] chunks) (titleize' abbAcc) True -- | Table of abbreviations and acronyms reference. tableAbbAccRef :: Reference tableAbbAccRef = makeTabRef' $ abbAcc ^. uid
null
https://raw.githubusercontent.com/JacquesCarette/Drasil/92dddf7a545ba5029f99ad5c5eddcd8dad56a2d8/code/drasil-docLang/lib/Drasil/Sections/TableOfAbbAndAcronyms.hs
haskell
| Standard code to make a table of abbreviations and acronyms. | Helper function that gets the acronym out of an 'Idea'. | The actual table creation function. | Table of abbreviations and acronyms reference.
module Drasil.Sections.TableOfAbbAndAcronyms (tableAbbAccGen, tableAbbAccRef) where import Language.Drasil import Data.Drasil.Concepts.Documentation (abbreviation, fullForm, abbAcc) import Control.Lens ((^.)) import Data.List (sortBy) import Data.Function (on) select :: (Idea s) => [s] -> [(String, s)] select [] = [] select (x:xs) = case getA x of Nothing -> select xs Just y -> (y, x) : select xs tableAbbAccGen :: (Idea s) => [s] -> LabelledContent tableAbbAccGen ls = let chunks = sortBy (compare `on` fst) $ select ls in llcc tableAbbAccRef $ Table (map titleize [abbreviation, fullForm]) (mkTable [\(a,_) -> S a, \(_,b) -> titleize b] chunks) (titleize' abbAcc) True tableAbbAccRef :: Reference tableAbbAccRef = makeTabRef' $ abbAcc ^. uid
a26d4869a01e2281a947c6e448ad90f9fb5b17c1119680a0b5ae542bc76430f2
votinginfoproject/data-processor
sqlite_test.clj
(ns vip.data-processor.db.sqlite-test (:require [vip.data-processor.db.sqlite :as sqlite] [clojure.test :refer :all] [vip.data-processor.validation.data-spec.v3-0 :as v3-0])) (deftest column-names-test (let [db (sqlite/temp-db "column-names-test" "3.0")] (is (= ["state_id" "early_vote_site_id"] (sqlite/column-names (-> db :tables :state-early-vote-sites))))))
null
https://raw.githubusercontent.com/votinginfoproject/data-processor/b4baf334b3a6219d12125af8e8c1e3de93ba1dc9/test/vip/data_processor/db/sqlite_test.clj
clojure
(ns vip.data-processor.db.sqlite-test (:require [vip.data-processor.db.sqlite :as sqlite] [clojure.test :refer :all] [vip.data-processor.validation.data-spec.v3-0 :as v3-0])) (deftest column-names-test (let [db (sqlite/temp-db "column-names-test" "3.0")] (is (= ["state_id" "early_vote_site_id"] (sqlite/column-names (-> db :tables :state-early-vote-sites))))))
ba8f2a00fa7ddba0b33d1641e91368a2374e64b8735997a02376920c41ffb013
haskellari/some
Church.hs
{-# LANGUAGE CPP #-} {-# LANGUAGE Safe #-} module Data.Some.Church ( Some(..), mkSome, mapSome, withSomeM, foldSome, traverseSome, ) where import Data.GADT.Internal
null
https://raw.githubusercontent.com/haskellari/some/00e42322da777cba81a1afdbb701fe8bbe263f58/src/Data/Some/Church.hs
haskell
# LANGUAGE CPP # # LANGUAGE Safe #
module Data.Some.Church ( Some(..), mkSome, mapSome, withSomeM, foldSome, traverseSome, ) where import Data.GADT.Internal
9533ef085d64f6b8e1c758e673e5756255ea8a0a3734fd7db883d380ce6e1933
pashatsyganenko/main
24022021.ml
let re = Str.regexp "[2-7]\\(0\\|2\\|4\\|6\\|8\\)$" ;; let re = Str.regexp "[0-9]+\\.[0-9]+$" ;; let re = Str.regexp "\\(\\(0\\.[0-9]+\\)\\|\\([1-9][0-9]*\\.[0-9+]\\)\\)$" ;; let re = Str.regexp "\\(\\(0\\.[0-9]*[1-9]\\)\\|\\([1-9][0-9]*\\.[0-9]*[1-9]\\)\\)$" ;; let re = Str.regexp "\\(\\(0\\.0\\)\\|\\([1-9][0-9]*\\.0\\)\\|\\(0\\.[0-9]*[1-9]\\)\\|\\([1-9][0-9]*\\.[0-9]*[1-9]\\)\\)$" ;; let re = Str.regexp "\\(\\(0\\.0\\)\\|\\(-?[1-9][0-9]*\\.0\\)\\|\\(-?\\.[0-9]*[1-9]\\)\\|\\(-?[1-9][0-9]*\\.\\)\\|\\(-?0\\.[0-9]*[1-9]\\)\\|\\(-?[1-9][0-9]*\\.[0-9]*[1-9]\\)\\)$" ;; let re = Str.regexp "\\(\\([0-9]\\|[1-9][0-9]\\|1[0-9][0-9]\\|2[0-4][0-9]\\|25[0-5]\\)\\.\\([0-9]\\|[1-9][0-9]\\|1[0-9][0-9]\\|2[0-4][0-9]\\|25[0-5]\\)\\.\\([0-9]\\|[1-9][0-9]\\|1[0-9][0-9]\\|2[0-4][0-9]\\|25[0-5]\\)\\.\\([0-9]\\|[1-9][0-9]\\|1[0-9][0-9]\\|2[0-4][0-9]\\|25[0-5]\\)\\)$" ;; let s = "" ;; if Str.string_match re s 0 then print_string "Matched!\n" else print_string "Match failed!\n" ;;
null
https://raw.githubusercontent.com/pashatsyganenko/main/3903ec183f62ead548de51086e7fa3ac4553587c/2021-10/24022021.ml
ocaml
let re = Str.regexp "[2-7]\\(0\\|2\\|4\\|6\\|8\\)$" ;; let re = Str.regexp "[0-9]+\\.[0-9]+$" ;; let re = Str.regexp "\\(\\(0\\.[0-9]+\\)\\|\\([1-9][0-9]*\\.[0-9+]\\)\\)$" ;; let re = Str.regexp "\\(\\(0\\.[0-9]*[1-9]\\)\\|\\([1-9][0-9]*\\.[0-9]*[1-9]\\)\\)$" ;; let re = Str.regexp "\\(\\(0\\.0\\)\\|\\([1-9][0-9]*\\.0\\)\\|\\(0\\.[0-9]*[1-9]\\)\\|\\([1-9][0-9]*\\.[0-9]*[1-9]\\)\\)$" ;; let re = Str.regexp "\\(\\(0\\.0\\)\\|\\(-?[1-9][0-9]*\\.0\\)\\|\\(-?\\.[0-9]*[1-9]\\)\\|\\(-?[1-9][0-9]*\\.\\)\\|\\(-?0\\.[0-9]*[1-9]\\)\\|\\(-?[1-9][0-9]*\\.[0-9]*[1-9]\\)\\)$" ;; let re = Str.regexp "\\(\\([0-9]\\|[1-9][0-9]\\|1[0-9][0-9]\\|2[0-4][0-9]\\|25[0-5]\\)\\.\\([0-9]\\|[1-9][0-9]\\|1[0-9][0-9]\\|2[0-4][0-9]\\|25[0-5]\\)\\.\\([0-9]\\|[1-9][0-9]\\|1[0-9][0-9]\\|2[0-4][0-9]\\|25[0-5]\\)\\.\\([0-9]\\|[1-9][0-9]\\|1[0-9][0-9]\\|2[0-4][0-9]\\|25[0-5]\\)\\)$" ;; let s = "" ;; if Str.string_match re s 0 then print_string "Matched!\n" else print_string "Match failed!\n" ;;
ff17b7f41a13753caa0126b2c5a6d20e98be109e10d2d0bc41b1739ede603264
whamtet/ctmx
command.cljc
(ns ctmx.render.command) ;; when the hx-* endpoint is of the form endpoint:command ;; we shall split on the colon and add command to hx-vals (defn- assoc-command [m verb] (if-let [endpoint (m verb)] (let [[endpoint command] (.split endpoint ":")] (if command (-> m (update :hx-vals #(if (string? %) % (assoc % :command command))) (assoc verb endpoint)) m)) m)) (defn assoc-commands [m] (reduce assoc-command m [:hx-get :hx-post :hx-put :hx-patch :hx-delete]))
null
https://raw.githubusercontent.com/whamtet/ctmx/45a635ecd5781a68d17bdc5c5e3905fbac32e81f/src/ctmx/render/command.cljc
clojure
when the hx-* endpoint is of the form endpoint:command we shall split on the colon and add command to hx-vals
(ns ctmx.render.command) (defn- assoc-command [m verb] (if-let [endpoint (m verb)] (let [[endpoint command] (.split endpoint ":")] (if command (-> m (update :hx-vals #(if (string? %) % (assoc % :command command))) (assoc verb endpoint)) m)) m)) (defn assoc-commands [m] (reduce assoc-command m [:hx-get :hx-post :hx-put :hx-patch :hx-delete]))
c2a0ebac3639b1fc0651a16d244d4e23a0e717ddb72a902f07965e5bbfa5e38b
juxt/grab
eql_compile_test.clj
(ns juxt.grab.eql-compile-test (:require [clojure.test :refer [deftest is]] [juxt.grab.alpha.schema :as schema] [juxt.grab.alpha.document :as doc] [juxt.grab.alpha.parser :refer [parse]] [juxt.grab.alpha.compile :refer [compile-root]] [clojure.java.io :as io])) (defn expected-errors [{::doc/keys [errors]} regexes] (is (= (count errors) (count regexes)) "Count of errors doesn't equal expected count") (doall (map (fn [error regex] (when regex (is (re-matches regex (:message error))))) errors regexes))) (defn example-schema [] (schema/compile-schema (parse (slurp (io/resource "juxt/grab/examples/example-90.graphql"))))) (deftest simple-query-test (is (= (-> (parse "{ dog { name }}") (doc/compile-document* (example-schema)) (compile-root)) [{:dog [:name]}]))) (deftest join-test-1 (is (= (-> (parse " query getOwnerName { dog { name owner { name } } } ") (doc/compile-document* (example-schema)) (compile-root)) [{:dog [:name {:owner [:name]}]}]))) (deftest arguments-test-1 (is (= (-> (parse "query WithBarkVolume { dog(barkVolume: 12) { name } }") (doc/compile-document* (example-schema)) (compile-root)) [{'(:dog {:barkVolume 12}) [:name]}]))) (deftest fragments-test-1 (is (= (-> (parse "{ dog { ...fragmentOne ...fragmentTwo } } fragment fragmentOne on Dog { name } fragment fragmentTwo on Dog { owner { name } } ") (doc/compile-document* (example-schema)) (compile-root)) [{:dog [:name {:owner [:name]}]}])))
null
https://raw.githubusercontent.com/juxt/grab/63ca3fd6542705151ff6ef7127a79478cae12b2b/test/juxt/grab/eql_compile_test.clj
clojure
(ns juxt.grab.eql-compile-test (:require [clojure.test :refer [deftest is]] [juxt.grab.alpha.schema :as schema] [juxt.grab.alpha.document :as doc] [juxt.grab.alpha.parser :refer [parse]] [juxt.grab.alpha.compile :refer [compile-root]] [clojure.java.io :as io])) (defn expected-errors [{::doc/keys [errors]} regexes] (is (= (count errors) (count regexes)) "Count of errors doesn't equal expected count") (doall (map (fn [error regex] (when regex (is (re-matches regex (:message error))))) errors regexes))) (defn example-schema [] (schema/compile-schema (parse (slurp (io/resource "juxt/grab/examples/example-90.graphql"))))) (deftest simple-query-test (is (= (-> (parse "{ dog { name }}") (doc/compile-document* (example-schema)) (compile-root)) [{:dog [:name]}]))) (deftest join-test-1 (is (= (-> (parse " query getOwnerName { dog { name owner { name } } } ") (doc/compile-document* (example-schema)) (compile-root)) [{:dog [:name {:owner [:name]}]}]))) (deftest arguments-test-1 (is (= (-> (parse "query WithBarkVolume { dog(barkVolume: 12) { name } }") (doc/compile-document* (example-schema)) (compile-root)) [{'(:dog {:barkVolume 12}) [:name]}]))) (deftest fragments-test-1 (is (= (-> (parse "{ dog { ...fragmentOne ...fragmentTwo } } fragment fragmentOne on Dog { name } fragment fragmentTwo on Dog { owner { name } } ") (doc/compile-document* (example-schema)) (compile-root)) [{:dog [:name {:owner [:name]}]}])))
8d93e32eecd091f61f647e298cccd7bf74001f21f320bbbd0d82ae67dd243b8e
jasonjckn/snake3d
gen.clj
(ns gen) (defn gen-cube [] (let [sq (fn [m z] [{:vertex (m 1 1 z)} {:vertex (m -1 1 z)} {:vertex (m -1 -1 z)} {:vertex (m 1 -1 z)}]) twosq (fn [m] (for [z [-1 1]] (sq m z)))] (flatten (for [f [#(vec [%1 %2 %3]) #(vec [%3 %2 %1]) #(vec [%2 %3 %1])]] (twosq f))))) #_ (spit "cube.vertex" (vec x))
null
https://raw.githubusercontent.com/jasonjckn/snake3d/e2bd88fbdec8f98c2ba16ead3b55011d55aae9b4/src/gen.clj
clojure
(ns gen) (defn gen-cube [] (let [sq (fn [m z] [{:vertex (m 1 1 z)} {:vertex (m -1 1 z)} {:vertex (m -1 -1 z)} {:vertex (m 1 -1 z)}]) twosq (fn [m] (for [z [-1 1]] (sq m z)))] (flatten (for [f [#(vec [%1 %2 %3]) #(vec [%3 %2 %1]) #(vec [%2 %3 %1])]] (twosq f))))) #_ (spit "cube.vertex" (vec x))
9363e722ac0f393eabb3edf9b2bd496803cad0a23bf05ae1a100e49234770f0d
pallet/pallet
lift.clj
(ns pallet.task.lift "Apply configuration." (:require [clojure.pprint :refer [print-table]] [clojure.stacktrace :refer [print-cause-trace]] [clojure.tools.logging :as logging] [pallet.algo.fsmop :refer [complete? wait-for]] [pallet.api :as api] [pallet.api :refer [print-targets]] [pallet.core.primitives :refer [phase-errors]] [pallet.task :refer [abort maybe-resolve-symbol-string]] [pallet.task-utils :refer [pallet-project project-groups]])) (defn- build-args [args] (loop [args args prefix nil m nil phases []] (if-let [^String a (first args)] (let [v (maybe-resolve-symbol-string a)] (cond non symbol as first arg (and (nil? m) (not v)) (recur (next args) a m phases) ;; a symbol (not (.startsWith a ":")) (if v (recur (next args) prefix (conj (or m []) v) phases) (abort (str "Could not locate node definition for " a))) ;; a phase :else (recur (next args) prefix m (conj phases (read-string a))))) (concat [(set m)] [:phase phases])))) (defn lift "Apply configuration. eg. pallet lift mynodes/my-node The node-types should be namespace qualified." [{:keys [compute project] :as request} & args] (let [[spec & args] (build-args args) spec (or (seq spec) (project-groups (pallet-project project) compute nil nil nil)) _ (logging/debugf "lift %s" (pr-str spec)) op (apply api/lift spec :async true (concat args (apply concat (-> request (dissoc :config :project) (assoc :environment (or (:environment request) (-> request :project :environment)))))))] (wait-for op) (if (complete? op) (print-targets @op) (binding [*out* *err*] (println "An error occured") (when-let [e (seq (phase-errors op))] (print-table (->> e (map :error) (map #(dissoc % :type))))) (when-let [e (:exception @op)] (print-cause-trace e) (throw (ex-info "pallet up failed" {} e))) (println "See logs for further details")))))
null
https://raw.githubusercontent.com/pallet/pallet/30226008d243c1072dcfa1f27150173d6d71c36d/src/pallet/task/lift.clj
clojure
a symbol a phase
(ns pallet.task.lift "Apply configuration." (:require [clojure.pprint :refer [print-table]] [clojure.stacktrace :refer [print-cause-trace]] [clojure.tools.logging :as logging] [pallet.algo.fsmop :refer [complete? wait-for]] [pallet.api :as api] [pallet.api :refer [print-targets]] [pallet.core.primitives :refer [phase-errors]] [pallet.task :refer [abort maybe-resolve-symbol-string]] [pallet.task-utils :refer [pallet-project project-groups]])) (defn- build-args [args] (loop [args args prefix nil m nil phases []] (if-let [^String a (first args)] (let [v (maybe-resolve-symbol-string a)] (cond non symbol as first arg (and (nil? m) (not v)) (recur (next args) a m phases) (not (.startsWith a ":")) (if v (recur (next args) prefix (conj (or m []) v) phases) (abort (str "Could not locate node definition for " a))) :else (recur (next args) prefix m (conj phases (read-string a))))) (concat [(set m)] [:phase phases])))) (defn lift "Apply configuration. eg. pallet lift mynodes/my-node The node-types should be namespace qualified." [{:keys [compute project] :as request} & args] (let [[spec & args] (build-args args) spec (or (seq spec) (project-groups (pallet-project project) compute nil nil nil)) _ (logging/debugf "lift %s" (pr-str spec)) op (apply api/lift spec :async true (concat args (apply concat (-> request (dissoc :config :project) (assoc :environment (or (:environment request) (-> request :project :environment)))))))] (wait-for op) (if (complete? op) (print-targets @op) (binding [*out* *err*] (println "An error occured") (when-let [e (seq (phase-errors op))] (print-table (->> e (map :error) (map #(dissoc % :type))))) (when-let [e (:exception @op)] (print-cause-trace e) (throw (ex-info "pallet up failed" {} e))) (println "See logs for further details")))))
9bc13d454b3ee7f4901fe1e2a5bbd782252fb4a6257c2b28f7c423449ee35fae
helium/erlang-dkg
dkg_worker.erl
-module(dkg_worker). -behaviour(gen_server). -export([ start_link/5, start_round/1, is_done/1, dkg_status/1, get_pubkey/1, sign_share/2, dec_share/2, verify_signature_share/3, combine_signature_shares/2, verify_decryption_share/3, combine_decryption_shares/3 ]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2]). -record(state, { n :: pos_integer(), f :: pos_integer(), t :: pos_integer(), id :: pos_integer(), dkg :: dkg_hybriddkg:dkg(), round :: binary(), key_share :: undefined | tc_key_share:tc_key_share(), commitment_cache_fun }). start_round(Pid) -> gen_server:cast(Pid, start_round). is_done(Pid) -> gen_server:call(Pid, is_done, infinity). dkg_status(Pid) -> gen_server:call(Pid, dkg_status, infinity). get_pubkey(Pid) -> gen_server:call(Pid, get_pubkey, infinity). sign_share(Pid, Msg) -> gen_server:call(Pid, {sign_share, Msg}, infinity). dec_share(Pid, Share) -> gen_server:call(Pid, {dec_share, Share}, infinity). verify_signature_share(Pid, Share, Msg) -> gen_server:call(Pid, {verify_signature_share, Share, Msg}, infinity). combine_signature_shares(Pid, Shares) -> gen_server:call(Pid, {combine_signature_shares, Shares}, infinity). verify_decryption_share(Pid, Share, CipherText) -> gen_server:call(Pid, {verify_decryption_share, Share, CipherText}, infinity). combine_decryption_shares(Pid, Shares, CipherText) -> gen_server:call(Pid, {combine_decryption_shares, Shares, CipherText}, infinity). start_link(Id, N, F, T, Round) -> gen_server:start_link({global, name(Id)}, ?MODULE, [Id, N, F, T, Round], []). init([Id, N, F, T, Round]) -> CCacheFun = dkg_util:commitment_cache_fun(), DKG = dkg_hybriddkg:init(Id, N, F, T, Round, [ {signfun, fun(_) -> <<"lol">> end}, {verifyfun, fun(_, _, _) -> true end}, {commitment_cache_fun, CCacheFun} ]), {ok, #state{ n = N, f = F, t = T, id = Id, round = Round, dkg = DKG, commitment_cache_fun = CCacheFun }}. handle_call(is_done, _From, State) -> {reply, State#state.key_share /= undefined, State}; handle_call(dkg_status, _From, #state{dkg = DKG} = State) -> {reply, dkg_hybriddkg:status(DKG), State}; handle_call(get_pubkey, _From, State) -> {reply, tc_key_share:public_key(State#state.key_share), State}; handle_call({sign_share, MessageToSign}, _From, State) -> {reply, tc_key_share:sign_share(State#state.key_share, MessageToSign), State}; handle_call({dec_share, CipherText}, _From, State) -> {reply, tc_key_share:decrypt_share(State#state.key_share, CipherText), State}; handle_call({combine_signature_shares, Shares}, _From, State) -> {reply, tc_key_share:combine_signature_shares(State#state.key_share, Shares), State}; handle_call({verify_signature_share, Share, Msg}, _From, State) -> {reply, tc_key_share:verify_signature_share(State#state.key_share, Share, Msg), State}; handle_call({combine_decryption_shares, Shares, CipherText}, _From, State) -> {reply, tc_key_share:combine_decryption_shares(State#state.key_share, Shares, CipherText), State}; handle_call({verify_decryption_share, Share, CipherText}, _From, State) -> {reply, tc_key_share:verify_decryption_share(State#state.key_share, Share, CipherText), State}; handle_call(Msg, _From, State) -> io:format("unhandled msg ~p~n", [Msg]), {reply, ok, State}. handle_cast(start_round, State) -> NewState = dispatch(dkg_hybriddkg:start(State#state.dkg), State), {noreply, NewState}; handle_cast({dkg, PeerID, Msg}, State = #state{dkg = DKG}) -> NewState = dispatch(dkg_hybriddkg:handle_msg(DKG, PeerID, Msg), State), {noreply, NewState}; handle_cast(Msg, State) -> io:format("unhandled msg ~p~n", [Msg]), {noreply, State}. handle_info(Msg, State) -> io:format("unhandled msg ~p~n", [Msg]), {noreply, State}. dispatch({NewDKG, {result, KeyShare}}, State) -> update_dkg(NewDKG, State#state{key_share = KeyShare}); dispatch({NewDKG, {send, ToSend}}, State) -> do_send(ToSend, State), update_dkg(NewDKG, State); dispatch({NewDKG, ok}, State) -> update_dkg(NewDKG, State); dispatch({NewDKG, Other}, State) -> io:format("UNHANDLED ~p~n", [Other]), State#state{dkg = NewDKG}; dispatch(Other, State) -> io:format("UNHANDLED2 ~p~n", [Other]), State. do_send([], _) -> ok; do_send([{unicast, Dest, Msg} | T], State) -> gen_server:cast({global, name(Dest)}, {dkg, State#state.id, Msg}), do_send(T, State); do_send([{multicast, Msg} | T], State) -> io : format("~p multicasting ~p to ~p ~ n " , [ State#state.id , Msg , [ global : whereis_name(name(Dest ) ) || Dest < - lists : seq(1 , State#state.n ) ] ] ) , [ gen_server:cast({global, name(Dest)}, {dkg, State#state.id, Msg}) || Dest <- lists:seq(1, State#state.n) ], do_send(T, State). %% helper functions update_dkg(DKG, State) -> NewDKG = dkg_hybriddkg:deserialize( dkg_hybriddkg:serialize(DKG), fun(_) -> <<"lol">> end, fun(_, _, _) -> true end, State#state.commitment_cache_fun ), State#state{dkg = NewDKG}. name(N) -> list_to_atom(lists:flatten(["dkg_worker_", integer_to_list(N)])).
null
https://raw.githubusercontent.com/helium/erlang-dkg/a22b841ae6cb31b17e547a6f208e93fa35f04b7f/test/dkg_worker.erl
erlang
helper functions
-module(dkg_worker). -behaviour(gen_server). -export([ start_link/5, start_round/1, is_done/1, dkg_status/1, get_pubkey/1, sign_share/2, dec_share/2, verify_signature_share/3, combine_signature_shares/2, verify_decryption_share/3, combine_decryption_shares/3 ]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2]). -record(state, { n :: pos_integer(), f :: pos_integer(), t :: pos_integer(), id :: pos_integer(), dkg :: dkg_hybriddkg:dkg(), round :: binary(), key_share :: undefined | tc_key_share:tc_key_share(), commitment_cache_fun }). start_round(Pid) -> gen_server:cast(Pid, start_round). is_done(Pid) -> gen_server:call(Pid, is_done, infinity). dkg_status(Pid) -> gen_server:call(Pid, dkg_status, infinity). get_pubkey(Pid) -> gen_server:call(Pid, get_pubkey, infinity). sign_share(Pid, Msg) -> gen_server:call(Pid, {sign_share, Msg}, infinity). dec_share(Pid, Share) -> gen_server:call(Pid, {dec_share, Share}, infinity). verify_signature_share(Pid, Share, Msg) -> gen_server:call(Pid, {verify_signature_share, Share, Msg}, infinity). combine_signature_shares(Pid, Shares) -> gen_server:call(Pid, {combine_signature_shares, Shares}, infinity). verify_decryption_share(Pid, Share, CipherText) -> gen_server:call(Pid, {verify_decryption_share, Share, CipherText}, infinity). combine_decryption_shares(Pid, Shares, CipherText) -> gen_server:call(Pid, {combine_decryption_shares, Shares, CipherText}, infinity). start_link(Id, N, F, T, Round) -> gen_server:start_link({global, name(Id)}, ?MODULE, [Id, N, F, T, Round], []). init([Id, N, F, T, Round]) -> CCacheFun = dkg_util:commitment_cache_fun(), DKG = dkg_hybriddkg:init(Id, N, F, T, Round, [ {signfun, fun(_) -> <<"lol">> end}, {verifyfun, fun(_, _, _) -> true end}, {commitment_cache_fun, CCacheFun} ]), {ok, #state{ n = N, f = F, t = T, id = Id, round = Round, dkg = DKG, commitment_cache_fun = CCacheFun }}. handle_call(is_done, _From, State) -> {reply, State#state.key_share /= undefined, State}; handle_call(dkg_status, _From, #state{dkg = DKG} = State) -> {reply, dkg_hybriddkg:status(DKG), State}; handle_call(get_pubkey, _From, State) -> {reply, tc_key_share:public_key(State#state.key_share), State}; handle_call({sign_share, MessageToSign}, _From, State) -> {reply, tc_key_share:sign_share(State#state.key_share, MessageToSign), State}; handle_call({dec_share, CipherText}, _From, State) -> {reply, tc_key_share:decrypt_share(State#state.key_share, CipherText), State}; handle_call({combine_signature_shares, Shares}, _From, State) -> {reply, tc_key_share:combine_signature_shares(State#state.key_share, Shares), State}; handle_call({verify_signature_share, Share, Msg}, _From, State) -> {reply, tc_key_share:verify_signature_share(State#state.key_share, Share, Msg), State}; handle_call({combine_decryption_shares, Shares, CipherText}, _From, State) -> {reply, tc_key_share:combine_decryption_shares(State#state.key_share, Shares, CipherText), State}; handle_call({verify_decryption_share, Share, CipherText}, _From, State) -> {reply, tc_key_share:verify_decryption_share(State#state.key_share, Share, CipherText), State}; handle_call(Msg, _From, State) -> io:format("unhandled msg ~p~n", [Msg]), {reply, ok, State}. handle_cast(start_round, State) -> NewState = dispatch(dkg_hybriddkg:start(State#state.dkg), State), {noreply, NewState}; handle_cast({dkg, PeerID, Msg}, State = #state{dkg = DKG}) -> NewState = dispatch(dkg_hybriddkg:handle_msg(DKG, PeerID, Msg), State), {noreply, NewState}; handle_cast(Msg, State) -> io:format("unhandled msg ~p~n", [Msg]), {noreply, State}. handle_info(Msg, State) -> io:format("unhandled msg ~p~n", [Msg]), {noreply, State}. dispatch({NewDKG, {result, KeyShare}}, State) -> update_dkg(NewDKG, State#state{key_share = KeyShare}); dispatch({NewDKG, {send, ToSend}}, State) -> do_send(ToSend, State), update_dkg(NewDKG, State); dispatch({NewDKG, ok}, State) -> update_dkg(NewDKG, State); dispatch({NewDKG, Other}, State) -> io:format("UNHANDLED ~p~n", [Other]), State#state{dkg = NewDKG}; dispatch(Other, State) -> io:format("UNHANDLED2 ~p~n", [Other]), State. do_send([], _) -> ok; do_send([{unicast, Dest, Msg} | T], State) -> gen_server:cast({global, name(Dest)}, {dkg, State#state.id, Msg}), do_send(T, State); do_send([{multicast, Msg} | T], State) -> io : format("~p multicasting ~p to ~p ~ n " , [ State#state.id , Msg , [ global : whereis_name(name(Dest ) ) || Dest < - lists : seq(1 , State#state.n ) ] ] ) , [ gen_server:cast({global, name(Dest)}, {dkg, State#state.id, Msg}) || Dest <- lists:seq(1, State#state.n) ], do_send(T, State). update_dkg(DKG, State) -> NewDKG = dkg_hybriddkg:deserialize( dkg_hybriddkg:serialize(DKG), fun(_) -> <<"lol">> end, fun(_, _, _) -> true end, State#state.commitment_cache_fun ), State#state{dkg = NewDKG}. name(N) -> list_to_atom(lists:flatten(["dkg_worker_", integer_to_list(N)])).
6d5088e164d241c4ec0316944cb975338de2e20b83b5bf7804525dabfe19dbf8
geremih/xcljb
xc_misc.clj
This file is automatically generated . DO NOT MODIFY . (clojure.core/ns xcljb.gen.xc-misc (:require xcljb.conn-ext xcljb.gen.xc-misc-types)) (def -XCLJB {:minor-version 1, :major-version 1, :header "xc_misc", :extension-multiword true, :extension-name "XCMisc", :extension-xname "XC-MISC"}) (clojure.core/defn get-version [conn client-major-version client-minor-version] (clojure.core/let [request (clojure.core/zipmap [:client-major-version :client-minor-version] [client-major-version client-minor-version])] (xcljb.conn-ext/send conn "XC-MISC" xcljb.gen.xc-misc-types/GetVersionRequest request))) (clojure.core/defn get-xid-range [conn] (clojure.core/let [request (clojure.core/zipmap [] [])] (xcljb.conn-ext/send conn "XC-MISC" xcljb.gen.xc-misc-types/GetXIDRangeRequest request))) (clojure.core/defn get-xid-list [conn count] (clojure.core/let [request (clojure.core/zipmap [:count] [count])] (xcljb.conn-ext/send conn "XC-MISC" xcljb.gen.xc-misc-types/GetXIDListRequest request))) ;;; Manually written.
null
https://raw.githubusercontent.com/geremih/xcljb/59e9ff795bf00595a3d46231a7bb4ec976852396/src/xcljb/gen/xc_misc.clj
clojure
Manually written.
This file is automatically generated . DO NOT MODIFY . (clojure.core/ns xcljb.gen.xc-misc (:require xcljb.conn-ext xcljb.gen.xc-misc-types)) (def -XCLJB {:minor-version 1, :major-version 1, :header "xc_misc", :extension-multiword true, :extension-name "XCMisc", :extension-xname "XC-MISC"}) (clojure.core/defn get-version [conn client-major-version client-minor-version] (clojure.core/let [request (clojure.core/zipmap [:client-major-version :client-minor-version] [client-major-version client-minor-version])] (xcljb.conn-ext/send conn "XC-MISC" xcljb.gen.xc-misc-types/GetVersionRequest request))) (clojure.core/defn get-xid-range [conn] (clojure.core/let [request (clojure.core/zipmap [] [])] (xcljb.conn-ext/send conn "XC-MISC" xcljb.gen.xc-misc-types/GetXIDRangeRequest request))) (clojure.core/defn get-xid-list [conn count] (clojure.core/let [request (clojure.core/zipmap [:count] [count])] (xcljb.conn-ext/send conn "XC-MISC" xcljb.gen.xc-misc-types/GetXIDListRequest request)))
39895acf45542cd66dedf3309c8a095bc718781d5b86c318cff587483d82cbf8
carl-eastlund/dracula
debug.rkt
#lang scheme (provide debug dprintf begin/debug define/debug define/private/debug define/public/debug define/override/debug define/augment/debug let/debug let*/debug letrec/debug let-values/debug let*-values/debug letrec-values/debug with-syntax/debug with-syntax*/debug parameterize/debug with-debugging) (require "syntax.ss" (for-syntax scheme/match syntax/parse "syntax.ss")) (define-syntax (let/debug stx) (syntax-parse stx [(_ (~optional loop:id) ... ([lhs:id rhs:expr] ...) body:expr ... last:expr) #`(with-debugging #:name '#,(if (attribute loop) #'loop #'let/debug) #:source (quote-srcloc #,stx) (let #,@(if (attribute loop) (list #'loop) null) ([lhs (with-debugging #:name 'lhs rhs)] ...) (debug body) ... (debug last)))])) (define-syntaxes [ let*/debug letrec/debug let-values/debug let*-values/debug letrec-values/debug with-syntax/debug with-syntax*/debug parameterize/debug ] (let () (define ((expander binder-id) stx) (with-syntax ([binder binder-id]) (syntax-parse stx [(binder/debug:id ([lhs rhs:expr] ...) body:expr ... last:expr) #`(with-debugging #:name 'binder/debug #:source (quote-srcloc #,stx) (binder ([lhs (with-debugging #:name 'lhs rhs)] ...) (debug body) ... (debug last)))]))) (values (expander #'let*) (expander #'letrec) (expander #'let-values) (expander #'let*-values) (expander #'letrec-values) (expander #'with-syntax) (expander #'with-syntax*) (expander #'parameterize)))) (define-syntaxes [ define/debug define/private/debug define/public/debug define/override/debug define/augment/debug ] (let () (define-syntax-class header #:attributes [name] (pattern (name:id . _)) (pattern (inner:header . _) #:attr name (attribute inner.name))) (define ((expander definer-id) stx) (with-syntax ([definer definer-id]) (syntax-parse stx [(definer/debug:id name:id body:expr) #`(definer name (with-debugging #:name 'name #:source (quote-srcloc #,stx) body))] [(definer/debug:id spec:header body:expr ... last:expr) #`(definer spec (with-debugging #:name 'spec.name #:source (quote-srcloc #,stx) (let () body ... last)))]))) (values (expander #'define) (expander #'define/private) (expander #'define/public) (expander #'define/override) (expander #'define/augment)))) (define-syntax (begin/debug stx) (syntax-parse stx [(_ term:expr ...) #`(with-debugging #:name 'begin/debug #:source (quote-srcloc #,stx) (begin (debug term) ...))])) (define-syntax (debug stx) (syntax-parse stx [(_ term:expr) (syntax (with-debugging term))])) (define-syntax (with-debugging stx) (syntax-parse stx [(_ (~or (~optional (~seq #:name name:expr)) (~optional (~seq #:source source:expr))) ... body:expr) (with-syntax* ([name (or (attribute name) #'(quote body))] [source (or (attribute source) #'(quote-srcloc body))]) #'(with-debugging/proc name source (quote body) (lambda () (#%expression body))))])) (define (srcloc->string src) (match src [(struct srcloc [source line col pos span]) (format "~a~a" (or source "") (if line (if col (format ":~a.~a" line col) (format ":~a" line)) (if pos (if span (format "::~a-~a" pos (+ pos span)) (format "::~a" pos)) "")))])) (define (srcloc->prefix src) (let* ([str (srcloc->string src)]) (if (string=? str "") "" (string-append str ": ")))) (define (with-debugging/proc name source term thunk) (let* ([src (srcloc->prefix (src->srcloc source))]) (begin (dprintf ">> ~a~s" src name) (begin0 (parameterize ([current-debug-depth (add1 (current-debug-depth))]) (call-with-values thunk (lambda results (match results [(list v) (dprintf "~s" v)] [(list vs ...) (dprintf "(values~a)" (apply string-append (for/list ([v (in-list vs)]) (format " ~s" v))))]) (apply values results)))) (dprintf "<< ~a~s" src name))))) (define (dprintf fmt . args) (let* ([message (apply format fmt args)] [prefix (make-string (* debug-indent (current-debug-depth)) #\space)] [indented (string-append prefix (regexp-replace* "\n" message (string-append "\n" prefix)))]) (log-debug indented))) (define current-debug-depth (make-parameter 0)) (define debug-indent 2)
null
https://raw.githubusercontent.com/carl-eastlund/dracula/a937f4b40463779246e3544e4021c53744a33847/private/scheme/debug.rkt
racket
#lang scheme (provide debug dprintf begin/debug define/debug define/private/debug define/public/debug define/override/debug define/augment/debug let/debug let*/debug letrec/debug let-values/debug let*-values/debug letrec-values/debug with-syntax/debug with-syntax*/debug parameterize/debug with-debugging) (require "syntax.ss" (for-syntax scheme/match syntax/parse "syntax.ss")) (define-syntax (let/debug stx) (syntax-parse stx [(_ (~optional loop:id) ... ([lhs:id rhs:expr] ...) body:expr ... last:expr) #`(with-debugging #:name '#,(if (attribute loop) #'loop #'let/debug) #:source (quote-srcloc #,stx) (let #,@(if (attribute loop) (list #'loop) null) ([lhs (with-debugging #:name 'lhs rhs)] ...) (debug body) ... (debug last)))])) (define-syntaxes [ let*/debug letrec/debug let-values/debug let*-values/debug letrec-values/debug with-syntax/debug with-syntax*/debug parameterize/debug ] (let () (define ((expander binder-id) stx) (with-syntax ([binder binder-id]) (syntax-parse stx [(binder/debug:id ([lhs rhs:expr] ...) body:expr ... last:expr) #`(with-debugging #:name 'binder/debug #:source (quote-srcloc #,stx) (binder ([lhs (with-debugging #:name 'lhs rhs)] ...) (debug body) ... (debug last)))]))) (values (expander #'let*) (expander #'letrec) (expander #'let-values) (expander #'let*-values) (expander #'letrec-values) (expander #'with-syntax) (expander #'with-syntax*) (expander #'parameterize)))) (define-syntaxes [ define/debug define/private/debug define/public/debug define/override/debug define/augment/debug ] (let () (define-syntax-class header #:attributes [name] (pattern (name:id . _)) (pattern (inner:header . _) #:attr name (attribute inner.name))) (define ((expander definer-id) stx) (with-syntax ([definer definer-id]) (syntax-parse stx [(definer/debug:id name:id body:expr) #`(definer name (with-debugging #:name 'name #:source (quote-srcloc #,stx) body))] [(definer/debug:id spec:header body:expr ... last:expr) #`(definer spec (with-debugging #:name 'spec.name #:source (quote-srcloc #,stx) (let () body ... last)))]))) (values (expander #'define) (expander #'define/private) (expander #'define/public) (expander #'define/override) (expander #'define/augment)))) (define-syntax (begin/debug stx) (syntax-parse stx [(_ term:expr ...) #`(with-debugging #:name 'begin/debug #:source (quote-srcloc #,stx) (begin (debug term) ...))])) (define-syntax (debug stx) (syntax-parse stx [(_ term:expr) (syntax (with-debugging term))])) (define-syntax (with-debugging stx) (syntax-parse stx [(_ (~or (~optional (~seq #:name name:expr)) (~optional (~seq #:source source:expr))) ... body:expr) (with-syntax* ([name (or (attribute name) #'(quote body))] [source (or (attribute source) #'(quote-srcloc body))]) #'(with-debugging/proc name source (quote body) (lambda () (#%expression body))))])) (define (srcloc->string src) (match src [(struct srcloc [source line col pos span]) (format "~a~a" (or source "") (if line (if col (format ":~a.~a" line col) (format ":~a" line)) (if pos (if span (format "::~a-~a" pos (+ pos span)) (format "::~a" pos)) "")))])) (define (srcloc->prefix src) (let* ([str (srcloc->string src)]) (if (string=? str "") "" (string-append str ": ")))) (define (with-debugging/proc name source term thunk) (let* ([src (srcloc->prefix (src->srcloc source))]) (begin (dprintf ">> ~a~s" src name) (begin0 (parameterize ([current-debug-depth (add1 (current-debug-depth))]) (call-with-values thunk (lambda results (match results [(list v) (dprintf "~s" v)] [(list vs ...) (dprintf "(values~a)" (apply string-append (for/list ([v (in-list vs)]) (format " ~s" v))))]) (apply values results)))) (dprintf "<< ~a~s" src name))))) (define (dprintf fmt . args) (let* ([message (apply format fmt args)] [prefix (make-string (* debug-indent (current-debug-depth)) #\space)] [indented (string-append prefix (regexp-replace* "\n" message (string-append "\n" prefix)))]) (log-debug indented))) (define current-debug-depth (make-parameter 0)) (define debug-indent 2)
e6a6b11453c2b51baae0f9305ff5418ea24e922f96cdcc9bf68d8b4644f9415e
cblp/notifaika
X.hs
Notifaika reposts notifications from different feeds to chats . Copyright ( C ) 2015 This program is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program . If not , see < / > . Notifaika reposts notifications from different feeds to Gitter chats. Copyright (C) 2015 Yuriy Syrovetskiy This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see </>. -} module Data.Aeson.X (module Data.Aeson, module Data.Aeson.X) where import Data.Aeson import Data.ByteString.Lazy as ByteString import Data.Monoid decodeFile :: FromJSON a => FilePath -> IO a decodeFile filepath = do bytes <- ByteString.readFile filepath let decodeResult = eitherDecode bytes case decodeResult of Left decodeError -> error ("Cannot decode file \"" <> filepath <> "\": " <> decodeError) Right value -> return value
null
https://raw.githubusercontent.com/cblp/notifaika/db8f9b69d3417db337bce7fb44b2da8e0337a466/src/Data/Aeson/X.hs
haskell
Notifaika reposts notifications from different feeds to chats . Copyright ( C ) 2015 This program is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program . If not , see < / > . Notifaika reposts notifications from different feeds to Gitter chats. Copyright (C) 2015 Yuriy Syrovetskiy This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see </>. -} module Data.Aeson.X (module Data.Aeson, module Data.Aeson.X) where import Data.Aeson import Data.ByteString.Lazy as ByteString import Data.Monoid decodeFile :: FromJSON a => FilePath -> IO a decodeFile filepath = do bytes <- ByteString.readFile filepath let decodeResult = eitherDecode bytes case decodeResult of Left decodeError -> error ("Cannot decode file \"" <> filepath <> "\": " <> decodeError) Right value -> return value
f92019a772130b6e97142d55ab70eff70f4f5038d42d27e36afb62b3a2a147bc
ku-fpg/hermit
GHC.hs
| Output the raw constructors . Helpful for writing pattern matching rewrites . module HERMIT.PrettyPrinter.GHC * GHC 's standard Pretty - Printer for GHC Core externals , pretty , ppCoreTC , ppModGuts , ppCoreProg , ppCoreBind , ppCoreExpr , ppCoreAlt , ppKindOrType , ppCoercion ) where import Control.Arrow hiding ((<+>)) import Data.Char (isSpace) import Data.Default.Class import HERMIT.Core import HERMIT.External import HERMIT.GHC hiding ((<+>), (<>), char, text, parens, hsep, empty) import HERMIT.Kure import HERMIT.PrettyPrinter.Common import Text.PrettyPrint.MarkedHughesPJ as PP --------------------------------------------------------------------------- externals :: [External] externals = [ external "ghc" pretty ["GHC pretty printer."] ] pretty :: PrettyPrinter TODO , pOptions = def , pTag = "ghc" } | This pretty printer is just a reflection of GHC 's standard pretty printer . ppCoreTC :: PrettyH CoreTC ppCoreTC = promoteExprT ppCoreExpr <+ promoteProgT ppCoreProg <+ promoteBindT ppCoreBind <+ promoteDefT ppCoreDef <+ promoteModGutsT ppModGuts <+ promoteAltT ppCoreAlt <+ promoteTypeT ppKindOrType <+ promoteCoercionT ppCoercion Use for any GHC structure . ppSDoc :: Outputable a => PrettyH a ppSDoc = do dynFlags <- constT getDynFlags arr (toDoc . showPpr dynFlags) where toDoc s | any isSpace s = parens (text s) | otherwise = text s ppModGuts :: PrettyH ModGuts ppModGuts = mg_binds ^>> ppSDoc ppCoreProg :: PrettyH CoreProg ppCoreProg = progToBinds ^>> ppSDoc ppCoreExpr :: PrettyH CoreExpr ppCoreExpr = ppSDoc ppCoreBind :: PrettyH CoreBind ppCoreBind = ppSDoc ppCoreAlt :: PrettyH CoreAlt ppCoreAlt = ppSDoc ppCoreDef :: PrettyH CoreDef ppCoreDef = defT ppSDoc ppCoreExpr $ \ i e -> i <+> char '=' <+> e ppKindOrType :: PrettyH Type ppKindOrType = ppSDoc ppCoercion :: PrettyH Coercion ppCoercion = ppSDoc TODO : lemma pp for GHC - style ppForallQuantification : : PrettyH [ Var ] ppForallQuantification = do vs ppSDoc if null vs then return empty else return $ text " forall " < + > vs < > text " . " ppForallQuantification :: PrettyH [Var] ppForallQuantification = do vs <- mapT ppSDoc if null vs then return empty else return $ text "forall" <+> hsep vs <> text "." -} ---------------------------------------------------------------------------
null
https://raw.githubusercontent.com/ku-fpg/hermit/3e7be430fae74a9e3860b8b574f36efbf9648dec/src/HERMIT/PrettyPrinter/GHC.hs
haskell
------------------------------------------------------------------------- -------------------------------------------------------------------------
| Output the raw constructors . Helpful for writing pattern matching rewrites . module HERMIT.PrettyPrinter.GHC * GHC 's standard Pretty - Printer for GHC Core externals , pretty , ppCoreTC , ppModGuts , ppCoreProg , ppCoreBind , ppCoreExpr , ppCoreAlt , ppKindOrType , ppCoercion ) where import Control.Arrow hiding ((<+>)) import Data.Char (isSpace) import Data.Default.Class import HERMIT.Core import HERMIT.External import HERMIT.GHC hiding ((<+>), (<>), char, text, parens, hsep, empty) import HERMIT.Kure import HERMIT.PrettyPrinter.Common import Text.PrettyPrint.MarkedHughesPJ as PP externals :: [External] externals = [ external "ghc" pretty ["GHC pretty printer."] ] pretty :: PrettyPrinter TODO , pOptions = def , pTag = "ghc" } | This pretty printer is just a reflection of GHC 's standard pretty printer . ppCoreTC :: PrettyH CoreTC ppCoreTC = promoteExprT ppCoreExpr <+ promoteProgT ppCoreProg <+ promoteBindT ppCoreBind <+ promoteDefT ppCoreDef <+ promoteModGutsT ppModGuts <+ promoteAltT ppCoreAlt <+ promoteTypeT ppKindOrType <+ promoteCoercionT ppCoercion Use for any GHC structure . ppSDoc :: Outputable a => PrettyH a ppSDoc = do dynFlags <- constT getDynFlags arr (toDoc . showPpr dynFlags) where toDoc s | any isSpace s = parens (text s) | otherwise = text s ppModGuts :: PrettyH ModGuts ppModGuts = mg_binds ^>> ppSDoc ppCoreProg :: PrettyH CoreProg ppCoreProg = progToBinds ^>> ppSDoc ppCoreExpr :: PrettyH CoreExpr ppCoreExpr = ppSDoc ppCoreBind :: PrettyH CoreBind ppCoreBind = ppSDoc ppCoreAlt :: PrettyH CoreAlt ppCoreAlt = ppSDoc ppCoreDef :: PrettyH CoreDef ppCoreDef = defT ppSDoc ppCoreExpr $ \ i e -> i <+> char '=' <+> e ppKindOrType :: PrettyH Type ppKindOrType = ppSDoc ppCoercion :: PrettyH Coercion ppCoercion = ppSDoc TODO : lemma pp for GHC - style ppForallQuantification : : PrettyH [ Var ] ppForallQuantification = do vs ppSDoc if null vs then return empty else return $ text " forall " < + > vs < > text " . " ppForallQuantification :: PrettyH [Var] ppForallQuantification = do vs <- mapT ppSDoc if null vs then return empty else return $ text "forall" <+> hsep vs <> text "." -}