_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
aa37f1694d4a88246927dfdbebd72a328099f29bfc51ded5c1370644394db38e
project-oak/hafnium-verification
androidFramework.mli
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd (** Android lifecycle types and their lifecycle methods that are called by the framework *) val drawable_prefix : string * prefix for fields in generated resources val is_autocloseable : Tenv.t -> Typ.Name.t -> bool val is_view : Tenv.t -> Typ.Name.t -> bool (** return true if [typename] <: android.view.View *) val is_fragment : Tenv.t -> Typ.Name.t -> bool val is_destroy_method : Procname.t -> bool (** return true if [procname] is a special lifecycle cleanup method *)
null
https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/checkers/androidFramework.mli
ocaml
* Android lifecycle types and their lifecycle methods that are called by the framework * return true if [typename] <: android.view.View * return true if [procname] is a special lifecycle cleanup method
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd val drawable_prefix : string * prefix for fields in generated resources val is_autocloseable : Tenv.t -> Typ.Name.t -> bool val is_view : Tenv.t -> Typ.Name.t -> bool val is_fragment : Tenv.t -> Typ.Name.t -> bool val is_destroy_method : Procname.t -> bool
ebe00bab35ed0864dc2cb4069cfbf71987bf93e24fd6a6eb24576d92d6e2ff52
pinterface/burgled-batteries
ffi-callbacks.lisp
(in-package #:python.cffi) #|| We want to expand into a CFFI defcallback, then parse the arguments so we can pretend the Lisp function was defined as (defun fun (positional &key keyword keyword) ...), and /then/ run the &body. ||# (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *callback-types* (make-hash-table)) (defun set-callback-type (lisp-name flags) (setf (gethash lisp-name *callback-types*) flags)) (defun get-callback-type (lisp-name) (or (gethash lisp-name *callback-types*) (error "No such callback ~A" lisp-name))) (defun filter-callback-args (args) (remove '&key args))) (defmacro defpycallback (name return-type (&rest args) &body body) "Defines a Lisp function which is callable from Python. RETURN-TYPE should be either :pointer, in which case type translation will not occur on arguments and you will be working with raw pointers, or a Python type (object, bool, etc.) in which case type translation of arguments will occur." (let ((self-type (if (eql return-type :pointer) :pointer '(object :borrowed))) (args-type (if (eql return-type :pointer) :pointer '(tuple :borrowed))) (dict-type (if (eql return-type :pointer) :pointer '(dict :borrowed)))) `(eval-when (:compile-toplevel :load-toplevel :execute) (defcallback ,name ,return-type ,@(cond ((find '&key args) `(((self ,self-type) (args ,args-type) (dict ,dict-type)) (declare (ignorable self args dict)))) (t `(((self ,self-type) (args ,args-type)) (declare (ignorable self args))))) ,@body) (set-callback-type ',name ,(cond ((zerop (length args)) :no-arguments) ((eql '&key (first args)) :keyword-arguments) ((find '&key args) :mixed-arguments) (t :positional-arguments)))))) SELF is NIL . ARGS is NIL . ( Or a null pointer , if no translation . ) (defpycallback test-no-arguments bool () (format t "arg: self=~A args=~A~%" self args) t) ;; SELF tends to be NIL. ARGS is a list of arguments. (defpycallback test-arguments bool ((arg1 (bool :borrowed))) (format t "arg: self=~A args=~A~%" self args) t) called as test_key_args(a=1 , b=2 , ... ) ;; * SELF is NIL. ARGS is an empty array. DICT is a hashtable of name=value pairs HOWEVER , if called as test_key_args(1 , 2 , a=3 , b=4 , ... ) * SELF is NIL . ARGS is # ( 1 2 ) . DICT is a hashtable { a=3 b=4 } (defpycallback test-key-args bool (&key (arg1 (bool :borrowed))) (format t "key: self=~A args=~A dict=~A~%" self args dict) t) ;; SELF is NIL. ARGS is an array of the positional (non-keyword) parameters. DICT is a hashtable of the keyword parameters . (defpycallback test-pos+key-args bool ((arg1 (bool :borrowed)) &key (arg2 (bool :borrowed))) (format t "key: self=~A args=~A dict=~A~%" self args dict) t) (defpycallback test-no-translation :pointer () (null-pointer)) (defun init-func-def (ptr name flags meth &optional (doc (null-pointer))) (setf (foreign-slot-value ptr 'method-def 'name) name (foreign-slot-value ptr 'method-def 'flags) flags (foreign-slot-value ptr 'method-def 'meth) meth (foreign-slot-value ptr 'method-def 'doc) doc)) (defun make-pytype (&key name c-struct documentation) (let ((ptr (foreign-alloc '%type))) (setf (%object.refcnt ptr) 1 (%object.type* ptr) (null-pointer) ; +Type.Type+? (%var.size ptr) 0 (%type.name ptr) name (%type.basicsize ptr) (foreign-type-size c-struct) (%type.itemsize ptr) 0 (%type.dealloc ptr) (null-pointer) ; FIXME: should point to a C callback or something (%type.print ptr) (null-pointer) (%type.getattr ptr) (null-pointer) (%type.setattr ptr) (null-pointer) (%type.compare ptr) (null-pointer) (%type.repr ptr) (null-pointer) (%type.as-number ptr) (null-pointer) (%type.as-sequence ptr) (null-pointer) (%type.as-mapping ptr) (null-pointer) (%type.hash ptr) (null-pointer) (%type.call ptr) (null-pointer) (%type.str ptr) (null-pointer) (%type.getattro ptr) (null-pointer) (%type.setattro ptr) (null-pointer) (%type.as-buffer ptr) (null-pointer) (%type.flags ptr) '() (%type.doc ptr) (or documentation (null-pointer)) (%type.traverse ptr) (null-pointer) (%type.clear ptr) (null-pointer) (%type.richcompare ptr) (null-pointer) (%type.weaklistoffset ptr) 0 (%type.iter ptr) (null-pointer) (%type.iternext ptr) (null-pointer) FIXME FIXME (%type.getset ptr) (null-pointer) FIXME (%type.dict* ptr) (null-pointer) (%type.descr-get ptr) (null-pointer) (%type.descr-set ptr) (null-pointer) (%type.dictoffset ptr) 0 (%type.init ptr) (null-pointer) (%type.alloc ptr) (null-pointer) (%type.new ptr) (foreign-symbol-pointer "PyType_GenericNew") (%type.free ptr) (null-pointer) (%type.is-gc ptr) (null-pointer) (%type.bases ptr) (null-pointer) (%type.mro ptr) (null-pointer) (%type.cache ptr) (null-pointer) (%type.subclasses ptr) (null-pointer) (%type.weaklist ptr) (null-pointer)) (type.ready ptr))) (defun make-test-module () (let* ((funcs '(("no_args" test-no-arguments) ("args" test-arguments) ("key_args" test-key-args) ("pos_key_args" test-pos+key-args) ("no_trans" test-no-translation))) (ptr (foreign-alloc 'method-def :count (1+ (length funcs))))) (loop :for i :from 0 :for (py lisp) :in funcs :for defptr = (mem-aref ptr 'method-def i) :do (init-func-def defptr py (get-callback-type lisp) (get-callback lisp))) (init-func-def (mem-aref ptr 'method-def (length funcs)) (null-pointer) 0 (null-pointer)) (.init-module* "lisp_test" ptr))) #+(or) (make-test-module) #+(or) (burgled-batteries:import "lisp_test")
null
https://raw.githubusercontent.com/pinterface/burgled-batteries/8ae3815a52fde36e68e54322cd7da2c42ec09f5c/ffi-callbacks.lisp
lisp
We want to expand into a CFFI defcallback, then parse the arguments so we can pretend the Lisp function was defined as (defun fun (positional &key keyword keyword) ...), and /then/ run the &body. SELF tends to be NIL. ARGS is a list of arguments. * SELF is NIL. ARGS is an empty array. DICT is a hashtable of name=value pairs SELF is NIL. ARGS is an array of the positional (non-keyword) parameters. +Type.Type+? FIXME: should point to a C callback or something
(in-package #:python.cffi) (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *callback-types* (make-hash-table)) (defun set-callback-type (lisp-name flags) (setf (gethash lisp-name *callback-types*) flags)) (defun get-callback-type (lisp-name) (or (gethash lisp-name *callback-types*) (error "No such callback ~A" lisp-name))) (defun filter-callback-args (args) (remove '&key args))) (defmacro defpycallback (name return-type (&rest args) &body body) "Defines a Lisp function which is callable from Python. RETURN-TYPE should be either :pointer, in which case type translation will not occur on arguments and you will be working with raw pointers, or a Python type (object, bool, etc.) in which case type translation of arguments will occur." (let ((self-type (if (eql return-type :pointer) :pointer '(object :borrowed))) (args-type (if (eql return-type :pointer) :pointer '(tuple :borrowed))) (dict-type (if (eql return-type :pointer) :pointer '(dict :borrowed)))) `(eval-when (:compile-toplevel :load-toplevel :execute) (defcallback ,name ,return-type ,@(cond ((find '&key args) `(((self ,self-type) (args ,args-type) (dict ,dict-type)) (declare (ignorable self args dict)))) (t `(((self ,self-type) (args ,args-type)) (declare (ignorable self args))))) ,@body) (set-callback-type ',name ,(cond ((zerop (length args)) :no-arguments) ((eql '&key (first args)) :keyword-arguments) ((find '&key args) :mixed-arguments) (t :positional-arguments)))))) SELF is NIL . ARGS is NIL . ( Or a null pointer , if no translation . ) (defpycallback test-no-arguments bool () (format t "arg: self=~A args=~A~%" self args) t) (defpycallback test-arguments bool ((arg1 (bool :borrowed))) (format t "arg: self=~A args=~A~%" self args) t) called as test_key_args(a=1 , b=2 , ... ) HOWEVER , if called as test_key_args(1 , 2 , a=3 , b=4 , ... ) * SELF is NIL . ARGS is # ( 1 2 ) . DICT is a hashtable { a=3 b=4 } (defpycallback test-key-args bool (&key (arg1 (bool :borrowed))) (format t "key: self=~A args=~A dict=~A~%" self args dict) t) DICT is a hashtable of the keyword parameters . (defpycallback test-pos+key-args bool ((arg1 (bool :borrowed)) &key (arg2 (bool :borrowed))) (format t "key: self=~A args=~A dict=~A~%" self args dict) t) (defpycallback test-no-translation :pointer () (null-pointer)) (defun init-func-def (ptr name flags meth &optional (doc (null-pointer))) (setf (foreign-slot-value ptr 'method-def 'name) name (foreign-slot-value ptr 'method-def 'flags) flags (foreign-slot-value ptr 'method-def 'meth) meth (foreign-slot-value ptr 'method-def 'doc) doc)) (defun make-pytype (&key name c-struct documentation) (let ((ptr (foreign-alloc '%type))) (setf (%object.refcnt ptr) 1 (%var.size ptr) 0 (%type.name ptr) name (%type.basicsize ptr) (foreign-type-size c-struct) (%type.itemsize ptr) 0 (%type.print ptr) (null-pointer) (%type.getattr ptr) (null-pointer) (%type.setattr ptr) (null-pointer) (%type.compare ptr) (null-pointer) (%type.repr ptr) (null-pointer) (%type.as-number ptr) (null-pointer) (%type.as-sequence ptr) (null-pointer) (%type.as-mapping ptr) (null-pointer) (%type.hash ptr) (null-pointer) (%type.call ptr) (null-pointer) (%type.str ptr) (null-pointer) (%type.getattro ptr) (null-pointer) (%type.setattro ptr) (null-pointer) (%type.as-buffer ptr) (null-pointer) (%type.flags ptr) '() (%type.doc ptr) (or documentation (null-pointer)) (%type.traverse ptr) (null-pointer) (%type.clear ptr) (null-pointer) (%type.richcompare ptr) (null-pointer) (%type.weaklistoffset ptr) 0 (%type.iter ptr) (null-pointer) (%type.iternext ptr) (null-pointer) FIXME FIXME (%type.getset ptr) (null-pointer) FIXME (%type.dict* ptr) (null-pointer) (%type.descr-get ptr) (null-pointer) (%type.descr-set ptr) (null-pointer) (%type.dictoffset ptr) 0 (%type.init ptr) (null-pointer) (%type.alloc ptr) (null-pointer) (%type.new ptr) (foreign-symbol-pointer "PyType_GenericNew") (%type.free ptr) (null-pointer) (%type.is-gc ptr) (null-pointer) (%type.bases ptr) (null-pointer) (%type.mro ptr) (null-pointer) (%type.cache ptr) (null-pointer) (%type.subclasses ptr) (null-pointer) (%type.weaklist ptr) (null-pointer)) (type.ready ptr))) (defun make-test-module () (let* ((funcs '(("no_args" test-no-arguments) ("args" test-arguments) ("key_args" test-key-args) ("pos_key_args" test-pos+key-args) ("no_trans" test-no-translation))) (ptr (foreign-alloc 'method-def :count (1+ (length funcs))))) (loop :for i :from 0 :for (py lisp) :in funcs :for defptr = (mem-aref ptr 'method-def i) :do (init-func-def defptr py (get-callback-type lisp) (get-callback lisp))) (init-func-def (mem-aref ptr 'method-def (length funcs)) (null-pointer) 0 (null-pointer)) (.init-module* "lisp_test" ptr))) #+(or) (make-test-module) #+(or) (burgled-batteries:import "lisp_test")
f29e0c17acc4366d303d4ff8eadf7041a3fec9cdb467c7edaa504f77d1a4c809
HaskellZhangSong/Introduction_to_Haskell_2ed_source
Person.hs
# LANGUAGE TemplateHaskell # # LANGUAGE ScopedTypeVariables # {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeOperators #-} # LANGUAGE DeriveGeneric # module Person where import System.Exit (exitFailure, exitSuccess) import System.IO (stderr, hPutStrLn) import qualified Data.ByteString.Lazy.Char8 as BSL import System.Environment (getArgs) import Control.Monad (forM_, mzero, join) import Control.Applicative import Data.Aeson.AutoType.Alternative import Data.Aeson(decode, Value(..), FromJSON(..), ToJSON(..), (.:), (.:?), (.=), object) import Data.Text (Text) import GHC.Generics -- | Workaround for . o .:?? val = fmap join (o .:? val) data TopLevel = TopLevel { topLevelAge :: Int, topLevelName :: Text } deriving (Show,Eq,Generic) instance FromJSON TopLevel where parseJSON (Object v) = TopLevel <$> v .: "age" <*> v .: "name" parseJSON _ = mzero instance ToJSON TopLevel where toJSON (TopLevel {..}) = object ["age" .= topLevelAge, "name" .= topLevelName] parse :: FilePath -> IO TopLevel parse filename = do input <- BSL.readFile filename case decode input of Nothing -> fatal $ case (decode input :: Maybe Value) of Nothing -> "Invalid JSON file: " ++ filename Just v -> "Mismatched JSON value from file: " ++ filename Just r -> return (r :: TopLevel) where fatal :: String -> IO a fatal msg = do hPutStrLn stderr msg exitFailure main :: IO () main = do filenames <- getArgs forM_ filenames (\f -> parse f >>= (\p -> p `seq` putStrLn $ "Successfully parsed " ++ f)) exitSuccess
null
https://raw.githubusercontent.com/HaskellZhangSong/Introduction_to_Haskell_2ed_source/140c50fdccfe608fe499ecf2d8a3732f531173f5/C18/Person.hs
haskell
# LANGUAGE RecordWildCards # # LANGUAGE OverloadedStrings # # LANGUAGE TypeOperators # | Workaround for .
# LANGUAGE TemplateHaskell # # LANGUAGE ScopedTypeVariables # # LANGUAGE DeriveGeneric # module Person where import System.Exit (exitFailure, exitSuccess) import System.IO (stderr, hPutStrLn) import qualified Data.ByteString.Lazy.Char8 as BSL import System.Environment (getArgs) import Control.Monad (forM_, mzero, join) import Control.Applicative import Data.Aeson.AutoType.Alternative import Data.Aeson(decode, Value(..), FromJSON(..), ToJSON(..), (.:), (.:?), (.=), object) import Data.Text (Text) import GHC.Generics o .:?? val = fmap join (o .:? val) data TopLevel = TopLevel { topLevelAge :: Int, topLevelName :: Text } deriving (Show,Eq,Generic) instance FromJSON TopLevel where parseJSON (Object v) = TopLevel <$> v .: "age" <*> v .: "name" parseJSON _ = mzero instance ToJSON TopLevel where toJSON (TopLevel {..}) = object ["age" .= topLevelAge, "name" .= topLevelName] parse :: FilePath -> IO TopLevel parse filename = do input <- BSL.readFile filename case decode input of Nothing -> fatal $ case (decode input :: Maybe Value) of Nothing -> "Invalid JSON file: " ++ filename Just v -> "Mismatched JSON value from file: " ++ filename Just r -> return (r :: TopLevel) where fatal :: String -> IO a fatal msg = do hPutStrLn stderr msg exitFailure main :: IO () main = do filenames <- getArgs forM_ filenames (\f -> parse f >>= (\p -> p `seq` putStrLn $ "Successfully parsed " ++ f)) exitSuccess
fb8ae52cb3d4ef34cebf16345e7af1d2dbeddb5d1f54efa9db8addd9ac50d445
dimitri/pgloader
pgsql-create-schema.lisp
;;; ;;; Tools to handle PostgreSQL tables and indexes creations ;;; (in-package #:pgloader.pgsql) ;;; ;;; Table schema support ;;; (defun create-sqltypes (catalog &key if-not-exists include-drop (client-min-messages :notice)) "Create the needed data types for given CATALOG." (let ((sqltype-list (sqltype-list catalog))) (loop :for sqltype :in sqltype-list :when include-drop :count t :do (pgsql-execute (format-drop-sql sqltype :cascade t :if-exists t) :client-min-messages client-min-messages) :do (pgsql-execute (format-create-sql sqltype :if-not-exists if-not-exists) :client-min-messages client-min-messages)))) (defun create-table-sql-list (table-list &key if-not-exists include-drop) "Return the list of CREATE TABLE statements to run against PostgreSQL." (loop :for table :in table-list :when include-drop :collect (format-drop-sql table :cascade t :if-exists t) :collect (format-create-sql table :if-not-exists if-not-exists))) (defun create-table-list (table-list &key if-not-exists include-drop (client-min-messages :notice)) "Create all tables in database dbname in PostgreSQL." (loop :for sql :in (create-table-sql-list table-list :if-not-exists if-not-exists :include-drop include-drop) :count (not (null sql)) :into nb-tables :when sql :do (pgsql-execute sql :client-min-messages client-min-messages) :finally (return nb-tables))) (defun create-schemas (catalog &key include-drop (client-min-messages :notice)) "Create all schemas from the given database CATALOG." (let ((schema-list (list-schemas))) (when include-drop if asked , first DROP the schema CASCADE . (loop :for schema :in (catalog-schema-list catalog) :for schema-name := (schema-name schema) :when (and schema-name (member (ensure-unquoted schema-name) schema-list :test #'string=)) :do (let ((sql (format nil "DROP SCHEMA ~a CASCADE;" schema-name))) (pgsql-execute sql :client-min-messages client-min-messages)))) ;; now create the schemas (again?) (loop :for schema :in (catalog-schema-list catalog) :for schema-name := (schema-name schema) :when (and schema-name (or include-drop (not (member (ensure-unquoted schema-name) schema-list :test #'string=)))) :do (let ((sql (format nil "CREATE SCHEMA ~a;" (schema-name schema)))) (pgsql-execute sql :client-min-messages client-min-messages))))) (defun add-to-search-path (catalog &key label (section :post) (log-level :notice) (client-min-messages :notice)) "Add catalog schemas in the database search_path." (let* ((dbname (get-current-database)) (search-path (list-search-path)) (missing-schemas (loop :for schema :in (catalog-schema-list catalog) :for schema-name := (schema-name schema) :when (and (schema-in-search-path schema) (not (member schema-name search-path :test #'string=))) :collect schema-name))) (when missing-schemas (let ((sql (format nil "ALTER DATABASE ~s SET search_path TO ~{~a~^, ~};" dbname (append search-path missing-schemas)))) (pgsql-execute-with-timing section label sql :log-level log-level :client-min-messages client-min-messages))))) (defun create-extensions (catalog &key if-not-exists include-drop (client-min-messages :notice)) "Create all extensions from the given database CATALOG." (let ((sql (loop :for extension :in (extension-list catalog) :when include-drop :collect (format-drop-sql extension :if-exists t :cascade t) :collect (format-create-sql extension :if-not-exists if-not-exists)))) (pgsql-execute sql :client-min-messages client-min-messages))) (defun create-tables (catalog &key if-not-exists include-drop (client-min-messages :notice)) "Create all tables from the given database CATALOG." (create-table-list (table-list catalog) :if-not-exists if-not-exists :include-drop include-drop :client-min-messages client-min-messages)) (defun create-views (catalog &key if-not-exists include-drop (client-min-messages :notice)) "Create all tables from the given database CATALOG." (create-table-list (view-list catalog) :if-not-exists if-not-exists :include-drop include-drop :client-min-messages client-min-messages)) (defun create-triggers (catalog &key label (section :post) (client-min-messages :notice)) "Create the catalog objects that come after the data has been loaded." (let ((sql-list (loop :for table :in (table-list catalog) :do (process-triggers table) :when (table-trigger-list table) :append (loop :for trigger :in (table-trigger-list table) :collect (format-create-sql (trigger-procedure trigger)) :collect (format-create-sql trigger))))) (pgsql-execute-with-timing section label sql-list :log-level :sql :client-min-messages client-min-messages))) ;;; DDL Utilities : TRUNCATE , ENABLE / DISABLE triggers ;;; (defun truncate-tables (catalog-or-table) "Truncate given TABLE-NAME in database DBNAME. A PostgreSQL connection must already be active when calling that function." (let* ((target-list (mapcar #'format-table-name (etypecase catalog-or-table (catalog (table-list catalog-or-table)) (schema (table-list catalog-or-table)) (table (list catalog-or-table))))) (sql (when target-list (format nil "TRUNCATE ~{~a~^,~};" target-list)))) (if target-list (progn (pgsql-execute sql) return how many tables we just (length target-list)) 0))) (defun disable-triggers (table-name) "Disable triggers on TABLE-NAME. Needs to be called with a PostgreSQL connection already opened." (let ((sql (format nil "ALTER TABLE ~a DISABLE TRIGGER ALL;" (apply-identifier-case table-name)))) (pgsql-execute sql))) (defun enable-triggers (table-name) "Disable triggers on TABLE-NAME. Needs to be called with a PostgreSQL connection already opened." (let ((sql (format nil "ALTER TABLE ~a ENABLE TRIGGER ALL;" (apply-identifier-case table-name)))) (pgsql-execute sql))) (defmacro with-disabled-triggers ((table-name &key disable-triggers) &body forms) "Run FORMS with PostgreSQL triggers disabled for TABLE-NAME if DISABLE-TRIGGERS is T A PostgreSQL connection must be opened already where this macro is used." `(if ,disable-triggers (progn (disable-triggers ,table-name) (unwind-protect (progn ,@forms) (enable-triggers ,table-name))) (progn ,@forms))) ;;; ;;; API for Foreign Keys ;;; (defun drop-pgsql-fkeys (catalog &key (cascade t) (log-level :notice)) "Drop all Foreign Key Definitions given, to prepare for a clean run." (let ((fk-sql-list (loop :for table :in (table-list catalog) :append (loop :for fkey :in (table-fkey-list table) :collect (format-drop-sql fkey :cascade cascade :if-exists t)) ;; also DROP the foreign keys that depend on the indexes we ;; want to DROP :append (loop :for index :in (table-index-list table) :append (loop :for fkey :in (index-fk-deps index) :collect (format-drop-sql fkey :cascade t :if-exists t)))))) (pgsql-execute fk-sql-list :log-level log-level))) (defun create-pgsql-fkeys (catalog &key (section :post) label log-level) "Actually create the Foreign Key References that where declared in the MySQL database" (let ((fk-sql-list (loop :for table :in (table-list catalog) :append (loop :for fkey :in (table-fkey-list table) ;; we might have loaded fkeys referencing tables that ;; have not been included in (or have been excluded ;; from) the load :unless (and (fkey-table fkey) (fkey-foreign-table fkey)) :do (log-message :debug "Skipping foreign key ~a" fkey) :when (and (fkey-table fkey) (fkey-foreign-table fkey)) :collect (format-create-sql fkey)) :append (loop :for index :in (table-index-list table) :do (loop :for fkey :in (index-fk-deps index) :for sql := (format-create-sql fkey) :do (log-message :debug "EXTRA FK DEPS! ~a" sql) :collect sql))))) ;; and now execute our list (pgsql-execute-with-timing section label fk-sql-list :log-level log-level))) ;;; Parallel index building . ;;; (defun create-indexes-in-kernel (pgconn table kernel channel &key (label "Create Indexes")) "Create indexes for given table in dbname, using given lparallel KERNEL and CHANNEL so that the index build happen in concurrently with the data copying." (let* ((lp:*kernel* kernel)) (loop :for index :in (table-index-list table) :for pkey := (multiple-value-bind (sql pkey) ;; we postpone the pkey upgrade of the index for later. (format-create-sql index) (lp:submit-task channel #'pgsql-connect-and-execute-with-timing ;; each thread must have its own connection (clone-connection pgconn) :post label sql) ;; return the pkey "upgrade" statement pkey) :when pkey :collect pkey))) ;;; ;;; Protect from non-unique index names ;;; (defun set-table-oids (catalog &key (variant :pgdg)) "MySQL allows using the same index name against separate tables, which PostgreSQL forbids. To get unicity in index names without running out of characters (we are allowed only 63), we use the table OID instead. This function grabs the table OIDs in the PostgreSQL database and update the definitions with them." (let ((oid-map (list-table-oids catalog :variant variant))) (loop :for table :in (table-list catalog) :for table-name := (format-table-name table) :for table-oid := (gethash table-name oid-map) :unless table-oid :do (error "OID not found for ~s." table-name) :count t :do (setf (table-oid table) table-oid)))) ;;; ;;; Drop indexes before loading ;;; (defun drop-indexes (table-or-catalog &key cascade (log-level :notice)) "Drop indexes in PGSQL-INDEX-LIST. A PostgreSQL connection must already be active when calling that function." (let ((sql-index-list (loop :for index :in (typecase table-or-catalog (table (table-index-list table-or-catalog)) (catalog (loop :for table :in (table-list table-or-catalog) :append (table-index-list table)))) :collect (format-drop-sql index :cascade cascade :if-exists t)))) (pgsql-execute sql-index-list :log-level log-level) ;; return how many indexes we just DROPed (length sql-index-list))) ;;; ;;; Higher level API to care about indexes ;;; (defun maybe-drop-indexes (catalog &key drop-indexes) "Drop the indexes for TABLE-NAME on TARGET PostgreSQL connection, and returns a list of indexes to create again. A PostgreSQL connection must already be active when calling that function." (loop :for table :in (table-list catalog) :do (let ((indexes (table-index-list table)) ;; we get the list of indexes from PostgreSQL catalogs, so don't ;; question their spelling, just quote them. (*identifier-case* :quote)) (cond ((and indexes (not drop-indexes)) (log-message :warning "Target table ~s has ~d indexes defined against it." (format-table-name table) (length indexes)) (log-message :warning "That could impact loading performance badly.") (log-message :warning "Consider the option 'drop indexes'.")) (indexes (drop-indexes table)))))) (defun create-indexes-again (target catalog &key max-parallel-create-index (section :post) drop-indexes) "Create the indexes that we dropped previously." (when (and drop-indexes (< 0 (count-indexes catalog))) (let* ((*preserve-index-names* t) ;; we get the list of indexes from PostgreSQL catalogs, so don't ;; question their spelling, just quote them. (*identifier-case* :quote) (idx-kernel (make-kernel (or max-parallel-create-index (count-indexes catalog)))) (idx-channel (let ((lp:*kernel* idx-kernel)) (lp:make-channel)))) (loop :for table :in (table-list catalog) :when (table-index-list table) :do (let ((pkeys (create-indexes-in-kernel target table idx-kernel idx-channel))) (with-stats-collection ("Index Build Completion" :section section) (loop :repeat (count-indexes table) :do (lp:receive-result idx-channel)) (lp:end-kernel :wait t)) ;; turn unique indexes into pkeys now (pgsql-connect-and-execute-with-timing target section "Constraints" pkeys)))))) ;;; ;;; Sequences ;;; (defun reset-sequences (target catalog &key (section :post)) "Reset all sequences created during this MySQL migration." (log-message :notice "Reset sequences") (with-stats-collection ("Reset Sequences" :use-result-as-read t :use-result-as-rows t :section section) (let ((tables (table-list catalog))) (with-pgsql-connection (target) (set-session-gucs *pg-settings*) (pomo:execute "set client_min_messages to warning;") (pomo:execute "listen seqs") (when tables (pomo:execute (format nil "create temp table reloids(oid) as values ~{('~a'::regclass)~^,~}" (mapcar #'format-table-name tables)))) (handler-case (let ((sql (format nil " DO $$ DECLARE n integer := 0; r record; BEGIN FOR r in SELECT 'select ' || trim(trailing ')' from replace(pg_get_expr(d.adbin, d.adrelid), 'nextval', 'setval')) || ', (select greatest(max(' || quote_ident(a.attname) || '), (select seqmin from pg_sequence where seqrelid = (''' || pg_get_serial_sequence(quote_ident(nspname) || '.' || quote_ident(relname), quote_ident(a.attname)) || ''')::regclass limit 1), 1) from only ' ' as sql FROM pg_class c JOIN pg_namespace n on n.oid = c.relnamespace JOIN pg_attribute a on a.attrelid = c.oid JOIN pg_attrdef d on d.adrelid = a.attrelid and d.adnum = a.attnum and a.atthasdef WHERE relkind = 'r' and a.attnum > 0 and pg_get_expr(d.adbin, d.adrelid) ~~ '^nextval' ~@[and c.oid in (select oid from reloids)~] LOOP n := n + 1; EXECUTE r.sql; END LOOP; PERFORM pg_notify('seqs', n::text); END; $$; " tables))) (pomo:execute sql)) ;; now get the notification signal (cl-postgres:postgresql-notification (c) (parse-integer (cl-postgres:postgresql-notification-payload c)))))))) ;;; ;;; Comments ;;; (defun comment-on-tables-and-columns (catalog &key label (section :post)) "Install comments on tables and columns from CATALOG." (let* ((quote ;; just something improbably found in a table comment, to use as ;; dollar quoting, and generated at random at that. ;; ;; because somehow it appears impossible here to benefit from ;; the usual SQL injection protection offered by the Extended ;; Query Protocol from PostgreSQL. (concatenate 'string (map 'string #'code-char (loop :repeat 5 :collect (+ (random 26) (char-code #\A)))) "_" (map 'string #'code-char (loop :repeat 5 :collect (+ (random 26) (char-code #\A)))))) (sql-list ;; table level comments (loop :for table :in (table-list catalog) :when (table-comment table) :collect (format nil "comment on table ~a is $~a$~a$~a$" (format-table-name table) quote (table-comment table) quote) ;; for each table, append column level comments :append (loop :for column :in (table-column-list table) :when (column-comment column) :collect (format nil "comment on column ~a.~a is $~a$~a$~a$" (format-table-name table) (column-name column) quote (column-comment column) quote))))) (pgsql-execute-with-timing section label sql-list))) ;;; ;;; Citus Disitribution support ;;; (defun create-distributed-table (distribute-rules) (let ((citus-sql (loop :for rule :in distribute-rules :collect (format-create-sql rule)))) (pgsql-execute citus-sql)))
null
https://raw.githubusercontent.com/dimitri/pgloader/644f2617e7e779e93db3bba20ae734f193f6e30c/src/pgsql/pgsql-create-schema.lisp
lisp
Tools to handle PostgreSQL tables and indexes creations Table schema support now create the schemas (again?) API for Foreign Keys also DROP the foreign keys that depend on the indexes we want to DROP we might have loaded fkeys referencing tables that have not been included in (or have been excluded from) the load and now execute our list we postpone the pkey upgrade of the index for later. each thread must have its own connection return the pkey "upgrade" statement Protect from non-unique index names Drop indexes before loading return how many indexes we just DROPed Higher level API to care about indexes we get the list of indexes from PostgreSQL catalogs, so don't question their spelling, just quote them. we get the list of indexes from PostgreSQL catalogs, so don't question their spelling, just quote them. turn unique indexes into pkeys now Sequences " tables))) now get the notification signal Comments just something improbably found in a table comment, to use as dollar quoting, and generated at random at that. because somehow it appears impossible here to benefit from the usual SQL injection protection offered by the Extended Query Protocol from PostgreSQL. table level comments for each table, append column level comments Citus Disitribution support
(in-package #:pgloader.pgsql) (defun create-sqltypes (catalog &key if-not-exists include-drop (client-min-messages :notice)) "Create the needed data types for given CATALOG." (let ((sqltype-list (sqltype-list catalog))) (loop :for sqltype :in sqltype-list :when include-drop :count t :do (pgsql-execute (format-drop-sql sqltype :cascade t :if-exists t) :client-min-messages client-min-messages) :do (pgsql-execute (format-create-sql sqltype :if-not-exists if-not-exists) :client-min-messages client-min-messages)))) (defun create-table-sql-list (table-list &key if-not-exists include-drop) "Return the list of CREATE TABLE statements to run against PostgreSQL." (loop :for table :in table-list :when include-drop :collect (format-drop-sql table :cascade t :if-exists t) :collect (format-create-sql table :if-not-exists if-not-exists))) (defun create-table-list (table-list &key if-not-exists include-drop (client-min-messages :notice)) "Create all tables in database dbname in PostgreSQL." (loop :for sql :in (create-table-sql-list table-list :if-not-exists if-not-exists :include-drop include-drop) :count (not (null sql)) :into nb-tables :when sql :do (pgsql-execute sql :client-min-messages client-min-messages) :finally (return nb-tables))) (defun create-schemas (catalog &key include-drop (client-min-messages :notice)) "Create all schemas from the given database CATALOG." (let ((schema-list (list-schemas))) (when include-drop if asked , first DROP the schema CASCADE . (loop :for schema :in (catalog-schema-list catalog) :for schema-name := (schema-name schema) :when (and schema-name (member (ensure-unquoted schema-name) schema-list :test #'string=)) :do (let ((sql (format nil "DROP SCHEMA ~a CASCADE;" schema-name))) (pgsql-execute sql :client-min-messages client-min-messages)))) (loop :for schema :in (catalog-schema-list catalog) :for schema-name := (schema-name schema) :when (and schema-name (or include-drop (not (member (ensure-unquoted schema-name) schema-list :test #'string=)))) :do (let ((sql (format nil "CREATE SCHEMA ~a;" (schema-name schema)))) (pgsql-execute sql :client-min-messages client-min-messages))))) (defun add-to-search-path (catalog &key label (section :post) (log-level :notice) (client-min-messages :notice)) "Add catalog schemas in the database search_path." (let* ((dbname (get-current-database)) (search-path (list-search-path)) (missing-schemas (loop :for schema :in (catalog-schema-list catalog) :for schema-name := (schema-name schema) :when (and (schema-in-search-path schema) (not (member schema-name search-path :test #'string=))) :collect schema-name))) (when missing-schemas (let ((sql (format nil "ALTER DATABASE ~s SET search_path TO ~{~a~^, ~};" dbname (append search-path missing-schemas)))) (pgsql-execute-with-timing section label sql :log-level log-level :client-min-messages client-min-messages))))) (defun create-extensions (catalog &key if-not-exists include-drop (client-min-messages :notice)) "Create all extensions from the given database CATALOG." (let ((sql (loop :for extension :in (extension-list catalog) :when include-drop :collect (format-drop-sql extension :if-exists t :cascade t) :collect (format-create-sql extension :if-not-exists if-not-exists)))) (pgsql-execute sql :client-min-messages client-min-messages))) (defun create-tables (catalog &key if-not-exists include-drop (client-min-messages :notice)) "Create all tables from the given database CATALOG." (create-table-list (table-list catalog) :if-not-exists if-not-exists :include-drop include-drop :client-min-messages client-min-messages)) (defun create-views (catalog &key if-not-exists include-drop (client-min-messages :notice)) "Create all tables from the given database CATALOG." (create-table-list (view-list catalog) :if-not-exists if-not-exists :include-drop include-drop :client-min-messages client-min-messages)) (defun create-triggers (catalog &key label (section :post) (client-min-messages :notice)) "Create the catalog objects that come after the data has been loaded." (let ((sql-list (loop :for table :in (table-list catalog) :do (process-triggers table) :when (table-trigger-list table) :append (loop :for trigger :in (table-trigger-list table) :collect (format-create-sql (trigger-procedure trigger)) :collect (format-create-sql trigger))))) (pgsql-execute-with-timing section label sql-list :log-level :sql :client-min-messages client-min-messages))) DDL Utilities : TRUNCATE , ENABLE / DISABLE triggers (defun truncate-tables (catalog-or-table) "Truncate given TABLE-NAME in database DBNAME. A PostgreSQL connection must already be active when calling that function." (let* ((target-list (mapcar #'format-table-name (etypecase catalog-or-table (catalog (table-list catalog-or-table)) (schema (table-list catalog-or-table)) (table (list catalog-or-table))))) (sql (when target-list (format nil "TRUNCATE ~{~a~^,~};" target-list)))) (if target-list (progn (pgsql-execute sql) return how many tables we just (length target-list)) 0))) (defun disable-triggers (table-name) "Disable triggers on TABLE-NAME. Needs to be called with a PostgreSQL connection already opened." (let ((sql (format nil "ALTER TABLE ~a DISABLE TRIGGER ALL;" (apply-identifier-case table-name)))) (pgsql-execute sql))) (defun enable-triggers (table-name) "Disable triggers on TABLE-NAME. Needs to be called with a PostgreSQL connection already opened." (let ((sql (format nil "ALTER TABLE ~a ENABLE TRIGGER ALL;" (apply-identifier-case table-name)))) (pgsql-execute sql))) (defmacro with-disabled-triggers ((table-name &key disable-triggers) &body forms) "Run FORMS with PostgreSQL triggers disabled for TABLE-NAME if DISABLE-TRIGGERS is T A PostgreSQL connection must be opened already where this macro is used." `(if ,disable-triggers (progn (disable-triggers ,table-name) (unwind-protect (progn ,@forms) (enable-triggers ,table-name))) (progn ,@forms))) (defun drop-pgsql-fkeys (catalog &key (cascade t) (log-level :notice)) "Drop all Foreign Key Definitions given, to prepare for a clean run." (let ((fk-sql-list (loop :for table :in (table-list catalog) :append (loop :for fkey :in (table-fkey-list table) :collect (format-drop-sql fkey :cascade cascade :if-exists t)) :append (loop :for index :in (table-index-list table) :append (loop :for fkey :in (index-fk-deps index) :collect (format-drop-sql fkey :cascade t :if-exists t)))))) (pgsql-execute fk-sql-list :log-level log-level))) (defun create-pgsql-fkeys (catalog &key (section :post) label log-level) "Actually create the Foreign Key References that where declared in the MySQL database" (let ((fk-sql-list (loop :for table :in (table-list catalog) :append (loop :for fkey :in (table-fkey-list table) :unless (and (fkey-table fkey) (fkey-foreign-table fkey)) :do (log-message :debug "Skipping foreign key ~a" fkey) :when (and (fkey-table fkey) (fkey-foreign-table fkey)) :collect (format-create-sql fkey)) :append (loop :for index :in (table-index-list table) :do (loop :for fkey :in (index-fk-deps index) :for sql := (format-create-sql fkey) :do (log-message :debug "EXTRA FK DEPS! ~a" sql) :collect sql))))) (pgsql-execute-with-timing section label fk-sql-list :log-level log-level))) Parallel index building . (defun create-indexes-in-kernel (pgconn table kernel channel &key (label "Create Indexes")) "Create indexes for given table in dbname, using given lparallel KERNEL and CHANNEL so that the index build happen in concurrently with the data copying." (let* ((lp:*kernel* kernel)) (loop :for index :in (table-index-list table) :for pkey := (multiple-value-bind (sql pkey) (format-create-sql index) (lp:submit-task channel #'pgsql-connect-and-execute-with-timing (clone-connection pgconn) :post label sql) pkey) :when pkey :collect pkey))) (defun set-table-oids (catalog &key (variant :pgdg)) "MySQL allows using the same index name against separate tables, which PostgreSQL forbids. To get unicity in index names without running out of characters (we are allowed only 63), we use the table OID instead. This function grabs the table OIDs in the PostgreSQL database and update the definitions with them." (let ((oid-map (list-table-oids catalog :variant variant))) (loop :for table :in (table-list catalog) :for table-name := (format-table-name table) :for table-oid := (gethash table-name oid-map) :unless table-oid :do (error "OID not found for ~s." table-name) :count t :do (setf (table-oid table) table-oid)))) (defun drop-indexes (table-or-catalog &key cascade (log-level :notice)) "Drop indexes in PGSQL-INDEX-LIST. A PostgreSQL connection must already be active when calling that function." (let ((sql-index-list (loop :for index :in (typecase table-or-catalog (table (table-index-list table-or-catalog)) (catalog (loop :for table :in (table-list table-or-catalog) :append (table-index-list table)))) :collect (format-drop-sql index :cascade cascade :if-exists t)))) (pgsql-execute sql-index-list :log-level log-level) (length sql-index-list))) (defun maybe-drop-indexes (catalog &key drop-indexes) "Drop the indexes for TABLE-NAME on TARGET PostgreSQL connection, and returns a list of indexes to create again. A PostgreSQL connection must already be active when calling that function." (loop :for table :in (table-list catalog) :do (let ((indexes (table-index-list table)) (*identifier-case* :quote)) (cond ((and indexes (not drop-indexes)) (log-message :warning "Target table ~s has ~d indexes defined against it." (format-table-name table) (length indexes)) (log-message :warning "That could impact loading performance badly.") (log-message :warning "Consider the option 'drop indexes'.")) (indexes (drop-indexes table)))))) (defun create-indexes-again (target catalog &key max-parallel-create-index (section :post) drop-indexes) "Create the indexes that we dropped previously." (when (and drop-indexes (< 0 (count-indexes catalog))) (let* ((*preserve-index-names* t) (*identifier-case* :quote) (idx-kernel (make-kernel (or max-parallel-create-index (count-indexes catalog)))) (idx-channel (let ((lp:*kernel* idx-kernel)) (lp:make-channel)))) (loop :for table :in (table-list catalog) :when (table-index-list table) :do (let ((pkeys (create-indexes-in-kernel target table idx-kernel idx-channel))) (with-stats-collection ("Index Build Completion" :section section) (loop :repeat (count-indexes table) :do (lp:receive-result idx-channel)) (lp:end-kernel :wait t)) (pgsql-connect-and-execute-with-timing target section "Constraints" pkeys)))))) (defun reset-sequences (target catalog &key (section :post)) "Reset all sequences created during this MySQL migration." (log-message :notice "Reset sequences") (with-stats-collection ("Reset Sequences" :use-result-as-read t :use-result-as-rows t :section section) (let ((tables (table-list catalog))) (with-pgsql-connection (target) (set-session-gucs *pg-settings*) (pomo:execute "set client_min_messages to warning;") (pomo:execute "listen seqs") (when tables (pomo:execute (format nil "create temp table reloids(oid) as values ~{('~a'::regclass)~^,~}" (mapcar #'format-table-name tables)))) (handler-case (let ((sql (format nil " DO $$ DECLARE BEGIN FOR r in SELECT 'select ' || trim(trailing ')' from replace(pg_get_expr(d.adbin, d.adrelid), 'nextval', 'setval')) || ', (select greatest(max(' || quote_ident(a.attname) || '), (select seqmin from pg_sequence where seqrelid = (''' || pg_get_serial_sequence(quote_ident(nspname) || '.' || quote_ident(relname), quote_ident(a.attname)) || ''')::regclass limit 1), 1) from only ' ' as sql FROM pg_class c JOIN pg_namespace n on n.oid = c.relnamespace JOIN pg_attribute a on a.attrelid = c.oid JOIN pg_attrdef d on d.adrelid = a.attrelid and d.adnum = a.attnum and a.atthasdef WHERE relkind = 'r' and a.attnum > 0 and pg_get_expr(d.adbin, d.adrelid) ~~ '^nextval' ~@[and c.oid in (select oid from reloids)~] LOOP (pomo:execute sql)) (cl-postgres:postgresql-notification (c) (parse-integer (cl-postgres:postgresql-notification-payload c)))))))) (defun comment-on-tables-and-columns (catalog &key label (section :post)) "Install comments on tables and columns from CATALOG." (let* ((quote (concatenate 'string (map 'string #'code-char (loop :repeat 5 :collect (+ (random 26) (char-code #\A)))) "_" (map 'string #'code-char (loop :repeat 5 :collect (+ (random 26) (char-code #\A)))))) (sql-list (loop :for table :in (table-list catalog) :when (table-comment table) :collect (format nil "comment on table ~a is $~a$~a$~a$" (format-table-name table) quote (table-comment table) quote) :append (loop :for column :in (table-column-list table) :when (column-comment column) :collect (format nil "comment on column ~a.~a is $~a$~a$~a$" (format-table-name table) (column-name column) quote (column-comment column) quote))))) (pgsql-execute-with-timing section label sql-list))) (defun create-distributed-table (distribute-rules) (let ((citus-sql (loop :for rule :in distribute-rules :collect (format-create-sql rule)))) (pgsql-execute citus-sql)))
81401977640bdea43adce1a398defe786f6e79a797ff8d4820ade68f77b7fb98
kaizhang/Taiji
Types.hs
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Bio.Data.Experiment.Types ( FileType(..) , File , location , format , tags , emptyFile , FileSet(..) , _Single , _Pair , Replicate , emptyReplicate , files , info , number , Experiment(..) , NGS(..) , IsDNASeq , ChIPSeq , target , control , defaultChIPSeq , ATACSeq , RNASeq , HiC ) where import Bio.Data.Experiment.Types.Internal
null
https://raw.githubusercontent.com/kaizhang/Taiji/f6a050ba0ee6acb6077435566669279455cef350/bio-experiments/src/Bio/Data/Experiment/Types.hs
haskell
# LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE OverloadedStrings # # LANGUAGE TemplateHaskell #
# LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE MultiParamTypeClasses # module Bio.Data.Experiment.Types ( FileType(..) , File , location , format , tags , emptyFile , FileSet(..) , _Single , _Pair , Replicate , emptyReplicate , files , info , number , Experiment(..) , NGS(..) , IsDNASeq , ChIPSeq , target , control , defaultChIPSeq , ATACSeq , RNASeq , HiC ) where import Bio.Data.Experiment.Types.Internal
49122d89d349a0b49c97e3e29a6e8f5825679dfd6f15952d81544ca951747fd0
CryptoKami/cryptokami-core
BlockVersion.hs
-- | Update system-specific functionality related to 'BlockVersion', -- 'BlockVersionData', 'BlockVersionModifier'. module Pos.Update.BlockVersion ( applyBVM ) where import Universum import Pos.Core (BlockVersionData (..)) import Pos.Core.Update (BlockVersionModifier (..)) -- | Apply 'BlockVersionModifier' to 'BlockVersionData'. applyBVM :: BlockVersionModifier -> BlockVersionData -> BlockVersionData applyBVM BlockVersionModifier {..} BlockVersionData {..} = BlockVersionData { bvdScriptVersion = fromMaybe bvdScriptVersion bvmScriptVersion , bvdSlotDuration = fromMaybe bvdSlotDuration bvmSlotDuration , bvdMaxBlockSize = fromMaybe bvdMaxBlockSize bvmMaxBlockSize , bvdMaxHeaderSize = fromMaybe bvdMaxHeaderSize bvmMaxHeaderSize , bvdMaxTxSize = fromMaybe bvdMaxTxSize bvmMaxTxSize , bvdMaxProposalSize = fromMaybe bvdMaxProposalSize bvmMaxProposalSize , bvdMpcThd = fromMaybe bvdMpcThd bvmMpcThd , bvdHeavyDelThd = fromMaybe bvdHeavyDelThd bvmHeavyDelThd , bvdUpdateVoteThd = fromMaybe bvdUpdateVoteThd bvmUpdateVoteThd , bvdUpdateProposalThd = fromMaybe bvdUpdateProposalThd bvmUpdateProposalThd , bvdUpdateImplicit = fromMaybe bvdUpdateImplicit bvmUpdateImplicit , bvdSoftforkRule = fromMaybe bvdSoftforkRule bvmSoftforkRule , bvdTxFeePolicy = fromMaybe bvdTxFeePolicy bvmTxFeePolicy , bvdUnlockStakeEpoch = fromMaybe bvdUnlockStakeEpoch bvmUnlockStakeEpoch }
null
https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/update/Pos/Update/BlockVersion.hs
haskell
| Update system-specific functionality related to 'BlockVersion', 'BlockVersionData', 'BlockVersionModifier'. | Apply 'BlockVersionModifier' to 'BlockVersionData'.
module Pos.Update.BlockVersion ( applyBVM ) where import Universum import Pos.Core (BlockVersionData (..)) import Pos.Core.Update (BlockVersionModifier (..)) applyBVM :: BlockVersionModifier -> BlockVersionData -> BlockVersionData applyBVM BlockVersionModifier {..} BlockVersionData {..} = BlockVersionData { bvdScriptVersion = fromMaybe bvdScriptVersion bvmScriptVersion , bvdSlotDuration = fromMaybe bvdSlotDuration bvmSlotDuration , bvdMaxBlockSize = fromMaybe bvdMaxBlockSize bvmMaxBlockSize , bvdMaxHeaderSize = fromMaybe bvdMaxHeaderSize bvmMaxHeaderSize , bvdMaxTxSize = fromMaybe bvdMaxTxSize bvmMaxTxSize , bvdMaxProposalSize = fromMaybe bvdMaxProposalSize bvmMaxProposalSize , bvdMpcThd = fromMaybe bvdMpcThd bvmMpcThd , bvdHeavyDelThd = fromMaybe bvdHeavyDelThd bvmHeavyDelThd , bvdUpdateVoteThd = fromMaybe bvdUpdateVoteThd bvmUpdateVoteThd , bvdUpdateProposalThd = fromMaybe bvdUpdateProposalThd bvmUpdateProposalThd , bvdUpdateImplicit = fromMaybe bvdUpdateImplicit bvmUpdateImplicit , bvdSoftforkRule = fromMaybe bvdSoftforkRule bvmSoftforkRule , bvdTxFeePolicy = fromMaybe bvdTxFeePolicy bvmTxFeePolicy , bvdUnlockStakeEpoch = fromMaybe bvdUnlockStakeEpoch bvmUnlockStakeEpoch }
c7e0ca34c2dbcbd668d2433b537193e193e1661c4af04df3fd13f734d3b344d8
nubank/midje-nrepl
profiler.clj
(ns midje-nrepl.profiler (:require [midje-nrepl.misc :as misc]) (:import java.text.DecimalFormat java.time.Duration java.util.Locale)) (def ^:private formatter "Instance of java.text.Decimalformat used internally to format decimal values." (let [decimal-format (DecimalFormat/getInstance (Locale/ENGLISH))] (.applyPattern decimal-format "#.##") decimal-format)) (defn- format-duration [value time-unit] (str (.format formatter value) " " (if (= (float value) 1.0) (name time-unit) (str (name time-unit) "s")))) (defn duration->string "Returns a friendly representation of the duration object in question." [duration] (let [millis (.toMillis duration)] (cond (<= millis 999) (format-duration millis :millisecond) (<= millis 59999) (format-duration (float (/ millis 1000)) :second) :else (format-duration (float (/ millis 60000)) :minute)))) (defn- slowest-test-comparator "Compares two test results and determines the slowest one." [x y] (* -1 (.compareTo (:total-time x) (:total-time y)))) (defn top-slowest-tests "Returns the top n slowest tests in the test results." [n test-results] (->> test-results (sort slowest-test-comparator) (take n) (map #(select-keys % [:context :total-time :file :line])))) (defn time-consumption "Returns statistics about the time taken by the supplied test results." [test-results total-time] (let [total-time-of-group (reduce (fn [total {:keys [total-time]}] (.plus total total-time)) (Duration/ZERO) test-results) percent-of-total-time (float (/ (.. total-time-of-group (multipliedBy 100) toMillis) (.toMillis total-time)))] {:total-time total-time-of-group :percent-of-total-time (str (.format formatter percent-of-total-time) "%")})) (defn average "Returns the average time taken by each test in the test suite." [total-time number-of-tests] (if (zero? number-of-tests) (Duration/ZERO) (.dividedBy total-time number-of-tests))) (defn- stats-for-ns [ns test-results total-time-of-suite] (let [number-of-tests (count test-results)] (let [{:keys [total-time] :as time-consumption-data} (time-consumption test-results total-time-of-suite)] (into {:ns ns :number-of-tests number-of-tests :average (average total-time (count test-results))} time-consumption-data)))) (defn stats-per-ns "Returns statistics about each tested namespace." [test-results total-time] (->> test-results (group-by :ns) (map (fn [[ns test-results]] (stats-for-ns ns test-results total-time))) (sort slowest-test-comparator))) (defn distinct-results-with-known-durations [report-map] (->> report-map :results vals flatten (filter #(and (:started-at %) (:finished-at %))) (group-by :id) vals (map last) (map (fn [{:keys [started-at finished-at] :as test-data}] (assoc test-data :total-time (misc/duration-between started-at finished-at)))))) (defn- assoc-stats "Assoc's profiling statistics to the report map and returns it." [report-map options] (let [{:keys [slowest-tests] :or {slowest-tests 5}} options test-results (distinct-results-with-known-durations report-map) total-time (get-in report-map [:summary :finished-in]) number-of-tests (count test-results) top-slowest-tests (top-slowest-tests slowest-tests test-results)] (assoc report-map :profile {:average (average total-time number-of-tests) :total-time total-time :number-of-tests number-of-tests :top-slowest-tests (into {:tests top-slowest-tests} (time-consumption top-slowest-tests total-time)) :namespaces (stats-per-ns test-results total-time)}))) (defn profile "Wraps a runner function by including profiling statistics to the produced report map." [runner] (fn [{:keys [profile?] :as options}] (let [start (misc/now) report-map (runner options) end (misc/now)] (-> report-map (assoc-in [:summary :finished-in] (misc/duration-between start end)) (cond-> (and profile? (not (zero? (get-in report-map [:summary :check])))) (assoc-stats options))))))
null
https://raw.githubusercontent.com/nubank/midje-nrepl/b4d505f346114db88ad5b5c6b3c8f0af4e0136fc/src/midje_nrepl/profiler.clj
clojure
(ns midje-nrepl.profiler (:require [midje-nrepl.misc :as misc]) (:import java.text.DecimalFormat java.time.Duration java.util.Locale)) (def ^:private formatter "Instance of java.text.Decimalformat used internally to format decimal values." (let [decimal-format (DecimalFormat/getInstance (Locale/ENGLISH))] (.applyPattern decimal-format "#.##") decimal-format)) (defn- format-duration [value time-unit] (str (.format formatter value) " " (if (= (float value) 1.0) (name time-unit) (str (name time-unit) "s")))) (defn duration->string "Returns a friendly representation of the duration object in question." [duration] (let [millis (.toMillis duration)] (cond (<= millis 999) (format-duration millis :millisecond) (<= millis 59999) (format-duration (float (/ millis 1000)) :second) :else (format-duration (float (/ millis 60000)) :minute)))) (defn- slowest-test-comparator "Compares two test results and determines the slowest one." [x y] (* -1 (.compareTo (:total-time x) (:total-time y)))) (defn top-slowest-tests "Returns the top n slowest tests in the test results." [n test-results] (->> test-results (sort slowest-test-comparator) (take n) (map #(select-keys % [:context :total-time :file :line])))) (defn time-consumption "Returns statistics about the time taken by the supplied test results." [test-results total-time] (let [total-time-of-group (reduce (fn [total {:keys [total-time]}] (.plus total total-time)) (Duration/ZERO) test-results) percent-of-total-time (float (/ (.. total-time-of-group (multipliedBy 100) toMillis) (.toMillis total-time)))] {:total-time total-time-of-group :percent-of-total-time (str (.format formatter percent-of-total-time) "%")})) (defn average "Returns the average time taken by each test in the test suite." [total-time number-of-tests] (if (zero? number-of-tests) (Duration/ZERO) (.dividedBy total-time number-of-tests))) (defn- stats-for-ns [ns test-results total-time-of-suite] (let [number-of-tests (count test-results)] (let [{:keys [total-time] :as time-consumption-data} (time-consumption test-results total-time-of-suite)] (into {:ns ns :number-of-tests number-of-tests :average (average total-time (count test-results))} time-consumption-data)))) (defn stats-per-ns "Returns statistics about each tested namespace." [test-results total-time] (->> test-results (group-by :ns) (map (fn [[ns test-results]] (stats-for-ns ns test-results total-time))) (sort slowest-test-comparator))) (defn distinct-results-with-known-durations [report-map] (->> report-map :results vals flatten (filter #(and (:started-at %) (:finished-at %))) (group-by :id) vals (map last) (map (fn [{:keys [started-at finished-at] :as test-data}] (assoc test-data :total-time (misc/duration-between started-at finished-at)))))) (defn- assoc-stats "Assoc's profiling statistics to the report map and returns it." [report-map options] (let [{:keys [slowest-tests] :or {slowest-tests 5}} options test-results (distinct-results-with-known-durations report-map) total-time (get-in report-map [:summary :finished-in]) number-of-tests (count test-results) top-slowest-tests (top-slowest-tests slowest-tests test-results)] (assoc report-map :profile {:average (average total-time number-of-tests) :total-time total-time :number-of-tests number-of-tests :top-slowest-tests (into {:tests top-slowest-tests} (time-consumption top-slowest-tests total-time)) :namespaces (stats-per-ns test-results total-time)}))) (defn profile "Wraps a runner function by including profiling statistics to the produced report map." [runner] (fn [{:keys [profile?] :as options}] (let [start (misc/now) report-map (runner options) end (misc/now)] (-> report-map (assoc-in [:summary :finished-in] (misc/duration-between start end)) (cond-> (and profile? (not (zero? (get-in report-map [:summary :check])))) (assoc-stats options))))))
b845979c1a319f2036920feb4a42e4b9677a6776728a29513d56eea98df07831
bsaleil/lc
primes.scm.scm
;;------------------------------------------------------------------------------ Macros (##define-macro (def-macro form . body) `(##define-macro ,form (let () ,@body))) (def-macro (FLOATvector-const . lst) `',(list->f64vector lst)) (def-macro (FLOATvector? x) `(f64vector? ,x)) (def-macro (FLOATvector . lst) `(f64vector ,@lst)) (def-macro (FLOATmake-vector n . init) `(make-f64vector ,n ,@init)) (def-macro (FLOATvector-ref v i) `(f64vector-ref ,v ,i)) (def-macro (FLOATvector-set! v i x) `(f64vector-set! ,v ,i ,x)) (def-macro (FLOATvector-length v) `(f64vector-length ,v)) (def-macro (nuc-const . lst) `',(list->vector (map (lambda (x) (if (vector? x) (list->f64vector (vector->list x)) x)) lst))) (def-macro (FLOAT+ . lst) `(+ ,@lst)) (def-macro (FLOAT- . lst) `(- ,@lst)) (def-macro (FLOAT* . lst) `(* ,@lst)) (def-macro (FLOAT/ . lst) `(/ ,@lst)) (def-macro (FLOAT= . lst) `(= ,@lst)) (def-macro (FLOAT< . lst) `(< ,@lst)) (def-macro (FLOAT<= . lst) `(<= ,@lst)) (def-macro (FLOAT> . lst) `(> ,@lst)) (def-macro (FLOAT>= . lst) `(>= ,@lst)) (def-macro (FLOATnegative? . lst) `(negative? ,@lst)) (def-macro (FLOATpositive? . lst) `(positive? ,@lst)) (def-macro (FLOATzero? . lst) `(zero? ,@lst)) (def-macro (FLOATabs . lst) `(abs ,@lst)) (def-macro (FLOATsin . lst) `(sin ,@lst)) (def-macro (FLOATcos . lst) `(cos ,@lst)) (def-macro (FLOATatan . lst) `(atan ,@lst)) (def-macro (FLOATsqrt . lst) `(sqrt ,@lst)) (def-macro (FLOATmin . lst) `(min ,@lst)) (def-macro (FLOATmax . lst) `(max ,@lst)) (def-macro (FLOATround . lst) `(round ,@lst)) (def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst)) (def-macro (GENERIC+ . lst) `(+ ,@lst)) (def-macro (GENERIC- . lst) `(- ,@lst)) (def-macro (GENERIC* . lst) `(* ,@lst)) (def-macro (GENERIC/ . lst) `(/ ,@lst)) (def-macro (GENERICquotient . lst) `(quotient ,@lst)) (def-macro (GENERICremainder . lst) `(remainder ,@lst)) (def-macro (GENERICmodulo . lst) `(modulo ,@lst)) (def-macro (GENERIC= . lst) `(= ,@lst)) (def-macro (GENERIC< . lst) `(< ,@lst)) (def-macro (GENERIC<= . lst) `(<= ,@lst)) (def-macro (GENERIC> . lst) `(> ,@lst)) (def-macro (GENERIC>= . lst) `(>= ,@lst)) (def-macro (GENERICexpt . lst) `(expt ,@lst)) ;;------------------------------------------------------------------------------ Functions used by LC to get time info (def-macro (##lc-time expr) (let ((sym (gensym))) `(let ((r (##lc-exec-stats (lambda () ,expr)))) (##print-perm-string "CPU time: ") (##print-double (+ (cdr (assoc "User time" (cdr r))) (cdr (assoc "Sys time" (cdr r))))) (##print-perm-string "\n") (##print-perm-string "GC CPU time: ") (##print-double (+ (cdr (assoc "GC user time" (cdr r))) (cdr (assoc "GC sys time" (cdr r))))) (##print-perm-string "\n") (map (lambda (el) (##print-perm-string (car el)) (##print-perm-string ": ") (##print-double (cdr el)) (##print-perm-string "\n")) (cdr r)) r))) (define (##lc-exec-stats thunk) (let* ((at-start (##process-statistics)) (result (thunk)) (at-end (##process-statistics))) (define (get-info msg idx) (cons msg (- (f64vector-ref at-end idx) (f64vector-ref at-start idx)))) (list result (get-info "User time" 0) (get-info "Sys time" 1) (get-info "Real time" 2) (get-info "GC user time" 3) (get-info "GC sys time" 4) (get-info "GC real time" 5) (get-info "Nb gcs" 6)))) ;;------------------------------------------------------------------------------ (define (run-bench name count ok? run) (let loop ((i count) (result '(undefined))) (if (< 0 i) (loop (- i 1) (run)) result))) (define (run-benchmark name count ok? run-maker . args) (let ((run (apply run-maker args))) (let ((result (car (##lc-time (run-bench name count ok? run))))) (if (not (ok? result)) (begin (display "*** wrong result ***") (newline) (display "*** got: ") (write result) (newline)))))) ; Gabriel benchmarks (define boyer-iters 20) (define browse-iters 600) (define cpstak-iters 1000) (define ctak-iters 100) (define dderiv-iters 2000000) (define deriv-iters 2000000) (define destruc-iters 500) (define diviter-iters 1000000) (define divrec-iters 1000000) (define puzzle-iters 100) (define tak-iters 2000) (define takl-iters 300) (define trav1-iters 100) (define trav2-iters 20) (define triangl-iters 10) and benchmarks (define ack-iters 10) (define array1-iters 1) (define cat-iters 1) (define string-iters 10) (define sum1-iters 10) (define sumloop-iters 10) (define tail-iters 1) (define wc-iters 1) ; C benchmarks (define fft-iters 2000) (define fib-iters 5) (define fibfp-iters 2) (define mbrot-iters 100) (define nucleic-iters 5) (define pnpoly-iters 100000) (define sum-iters 20000) (define sumfp-iters 20000) (define tfib-iters 20) ; Other benchmarks (define conform-iters 40) (define dynamic-iters 20) (define earley-iters 200) (define fibc-iters 500) (define graphs-iters 300) (define lattice-iters 1) (define matrix-iters 400) (define maze-iters 4000) (define mazefun-iters 1000) (define nqueens-iters 2000) (define paraffins-iters 1000) (define peval-iters 200) (define pi-iters 2) (define primes-iters 100000) (define ray-iters 5) (define scheme-iters 20000) (define simplex-iters 100000) (define slatex-iters 20) (define perm9-iters 10) (define nboyer-iters 100) (define sboyer-iters 100) (define gcbench-iters 1) (define compiler-iters 300) (define nbody-iters 1) (define fftrad4-iters 4) PRIMES -- Compute primes less than 100 , written by . (define (interval-list m n) (if (> m n) '() (cons m (interval-list (+ 1 m) n)))) (define (sieve l) (letrec ((remove-multiples (lambda (n l) (if (null? l) '() (if (= (modulo (car l) n) 0) (remove-multiples n (cdr l)) (cons (car l) (remove-multiples n (cdr l)))))))) (if (null? l) '() (cons (car l) (sieve (remove-multiples (car l) (cdr l))))))) (define (primes<= n) (sieve (interval-list 2 n))) (define (main) (run-benchmark "primes" primes-iters (lambda (result) (equal? result '(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97))) (lambda (n) (lambda () (primes<= n))) 100)) (main)
null
https://raw.githubusercontent.com/bsaleil/lc/ee7867fd2bdbbe88924300e10b14ea717ee6434b/tools/benchtimes/resultVMIL-lc-gsc-lc/LC5f64/primes.scm.scm
scheme
------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Gabriel benchmarks C benchmarks Other benchmarks
Macros (##define-macro (def-macro form . body) `(##define-macro ,form (let () ,@body))) (def-macro (FLOATvector-const . lst) `',(list->f64vector lst)) (def-macro (FLOATvector? x) `(f64vector? ,x)) (def-macro (FLOATvector . lst) `(f64vector ,@lst)) (def-macro (FLOATmake-vector n . init) `(make-f64vector ,n ,@init)) (def-macro (FLOATvector-ref v i) `(f64vector-ref ,v ,i)) (def-macro (FLOATvector-set! v i x) `(f64vector-set! ,v ,i ,x)) (def-macro (FLOATvector-length v) `(f64vector-length ,v)) (def-macro (nuc-const . lst) `',(list->vector (map (lambda (x) (if (vector? x) (list->f64vector (vector->list x)) x)) lst))) (def-macro (FLOAT+ . lst) `(+ ,@lst)) (def-macro (FLOAT- . lst) `(- ,@lst)) (def-macro (FLOAT* . lst) `(* ,@lst)) (def-macro (FLOAT/ . lst) `(/ ,@lst)) (def-macro (FLOAT= . lst) `(= ,@lst)) (def-macro (FLOAT< . lst) `(< ,@lst)) (def-macro (FLOAT<= . lst) `(<= ,@lst)) (def-macro (FLOAT> . lst) `(> ,@lst)) (def-macro (FLOAT>= . lst) `(>= ,@lst)) (def-macro (FLOATnegative? . lst) `(negative? ,@lst)) (def-macro (FLOATpositive? . lst) `(positive? ,@lst)) (def-macro (FLOATzero? . lst) `(zero? ,@lst)) (def-macro (FLOATabs . lst) `(abs ,@lst)) (def-macro (FLOATsin . lst) `(sin ,@lst)) (def-macro (FLOATcos . lst) `(cos ,@lst)) (def-macro (FLOATatan . lst) `(atan ,@lst)) (def-macro (FLOATsqrt . lst) `(sqrt ,@lst)) (def-macro (FLOATmin . lst) `(min ,@lst)) (def-macro (FLOATmax . lst) `(max ,@lst)) (def-macro (FLOATround . lst) `(round ,@lst)) (def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst)) (def-macro (GENERIC+ . lst) `(+ ,@lst)) (def-macro (GENERIC- . lst) `(- ,@lst)) (def-macro (GENERIC* . lst) `(* ,@lst)) (def-macro (GENERIC/ . lst) `(/ ,@lst)) (def-macro (GENERICquotient . lst) `(quotient ,@lst)) (def-macro (GENERICremainder . lst) `(remainder ,@lst)) (def-macro (GENERICmodulo . lst) `(modulo ,@lst)) (def-macro (GENERIC= . lst) `(= ,@lst)) (def-macro (GENERIC< . lst) `(< ,@lst)) (def-macro (GENERIC<= . lst) `(<= ,@lst)) (def-macro (GENERIC> . lst) `(> ,@lst)) (def-macro (GENERIC>= . lst) `(>= ,@lst)) (def-macro (GENERICexpt . lst) `(expt ,@lst)) Functions used by LC to get time info (def-macro (##lc-time expr) (let ((sym (gensym))) `(let ((r (##lc-exec-stats (lambda () ,expr)))) (##print-perm-string "CPU time: ") (##print-double (+ (cdr (assoc "User time" (cdr r))) (cdr (assoc "Sys time" (cdr r))))) (##print-perm-string "\n") (##print-perm-string "GC CPU time: ") (##print-double (+ (cdr (assoc "GC user time" (cdr r))) (cdr (assoc "GC sys time" (cdr r))))) (##print-perm-string "\n") (map (lambda (el) (##print-perm-string (car el)) (##print-perm-string ": ") (##print-double (cdr el)) (##print-perm-string "\n")) (cdr r)) r))) (define (##lc-exec-stats thunk) (let* ((at-start (##process-statistics)) (result (thunk)) (at-end (##process-statistics))) (define (get-info msg idx) (cons msg (- (f64vector-ref at-end idx) (f64vector-ref at-start idx)))) (list result (get-info "User time" 0) (get-info "Sys time" 1) (get-info "Real time" 2) (get-info "GC user time" 3) (get-info "GC sys time" 4) (get-info "GC real time" 5) (get-info "Nb gcs" 6)))) (define (run-bench name count ok? run) (let loop ((i count) (result '(undefined))) (if (< 0 i) (loop (- i 1) (run)) result))) (define (run-benchmark name count ok? run-maker . args) (let ((run (apply run-maker args))) (let ((result (car (##lc-time (run-bench name count ok? run))))) (if (not (ok? result)) (begin (display "*** wrong result ***") (newline) (display "*** got: ") (write result) (newline)))))) (define boyer-iters 20) (define browse-iters 600) (define cpstak-iters 1000) (define ctak-iters 100) (define dderiv-iters 2000000) (define deriv-iters 2000000) (define destruc-iters 500) (define diviter-iters 1000000) (define divrec-iters 1000000) (define puzzle-iters 100) (define tak-iters 2000) (define takl-iters 300) (define trav1-iters 100) (define trav2-iters 20) (define triangl-iters 10) and benchmarks (define ack-iters 10) (define array1-iters 1) (define cat-iters 1) (define string-iters 10) (define sum1-iters 10) (define sumloop-iters 10) (define tail-iters 1) (define wc-iters 1) (define fft-iters 2000) (define fib-iters 5) (define fibfp-iters 2) (define mbrot-iters 100) (define nucleic-iters 5) (define pnpoly-iters 100000) (define sum-iters 20000) (define sumfp-iters 20000) (define tfib-iters 20) (define conform-iters 40) (define dynamic-iters 20) (define earley-iters 200) (define fibc-iters 500) (define graphs-iters 300) (define lattice-iters 1) (define matrix-iters 400) (define maze-iters 4000) (define mazefun-iters 1000) (define nqueens-iters 2000) (define paraffins-iters 1000) (define peval-iters 200) (define pi-iters 2) (define primes-iters 100000) (define ray-iters 5) (define scheme-iters 20000) (define simplex-iters 100000) (define slatex-iters 20) (define perm9-iters 10) (define nboyer-iters 100) (define sboyer-iters 100) (define gcbench-iters 1) (define compiler-iters 300) (define nbody-iters 1) (define fftrad4-iters 4) PRIMES -- Compute primes less than 100 , written by . (define (interval-list m n) (if (> m n) '() (cons m (interval-list (+ 1 m) n)))) (define (sieve l) (letrec ((remove-multiples (lambda (n l) (if (null? l) '() (if (= (modulo (car l) n) 0) (remove-multiples n (cdr l)) (cons (car l) (remove-multiples n (cdr l)))))))) (if (null? l) '() (cons (car l) (sieve (remove-multiples (car l) (cdr l))))))) (define (primes<= n) (sieve (interval-list 2 n))) (define (main) (run-benchmark "primes" primes-iters (lambda (result) (equal? result '(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97))) (lambda (n) (lambda () (primes<= n))) 100)) (main)
beccb3e64d96ebcd9dc8080612fb7593794260a6fc382933889292bcf2888fcb
ku-fpg/blank-canvas
Path.hs
{-# LANGUAGE OverloadedStrings #-} module Path where import Graphics.Blank ( 578,200 ) main :: IO () main = blankCanvas 3000 $ \ context -> do send context $ do beginPath() moveTo(100, 20) line 1 lineTo(200, 160) -- quadratic curve quadraticCurveTo(230, 200, 250, 120) -- bezier curve bezierCurveTo(290, -40, 300, 200, 400, 150) line 2 lineTo(500, 90) lineWidth 5 strokeStyle "blue" stroke() wiki $ snapShot context "images/Path.png" wiki $ close context
null
https://raw.githubusercontent.com/ku-fpg/blank-canvas/39915c17561106ce06e1e3dcef85cc2e956626e6/wiki-suite/Path.hs
haskell
# LANGUAGE OverloadedStrings # quadratic curve bezier curve
module Path where import Graphics.Blank ( 578,200 ) main :: IO () main = blankCanvas 3000 $ \ context -> do send context $ do beginPath() moveTo(100, 20) line 1 lineTo(200, 160) quadraticCurveTo(230, 200, 250, 120) bezierCurveTo(290, -40, 300, 200, 400, 150) line 2 lineTo(500, 90) lineWidth 5 strokeStyle "blue" stroke() wiki $ snapShot context "images/Path.png" wiki $ close context
0fc3c876b7015f1a198348756b01b025a814e738c7287ceadca34f623abdc312
ghc/ghc
StaticPtrTable.hs
# LANGUAGE ViewPatterns # -- | Code generation for the Static Pointer Table -- ( c ) 2014 I / O Tweag -- -- Each module that uses 'static' keyword declares an initialization function of -- the form hs_spt_init_\<module>() which is emitted into the _stub.c file and -- annotated with __attribute__((constructor)) so that it gets executed at -- startup time. -- -- The function's purpose is to call hs_spt_insert to insert the static pointers of this module in the hashtable of the RTS , and it looks something -- like this: -- -- > static void hs_hpc_init_Main(void) __attribute__((constructor)); -- > static void hs_hpc_init_Main(void) { -- > > static StgWord64 k0[2 ] = { 16252233372134256ULL,7370534374096082ULL } ; -- > extern StgPtr Main_r2wb_closure; -- > hs_spt_insert(k0, &Main_r2wb_closure); -- > > static StgWord64 k1[2 ] = { 12545634534567898ULL,5409674567544151ULL } ; -- > extern StgPtr Main_r2wc_closure; -- > hs_spt_insert(k1, &Main_r2wc_closure); -- > -- > } -- -- where the constants are fingerprints produced from the static forms. -- -- The linker must find the definitions matching the @extern StgPtr <name>@ -- declarations. For this to work, the identifiers of static pointers need to be exported . This is done in ' GHC.Core . Opt . SetLevels.newLvlVar ' . -- -- There is also a finalization function for the time when the module is -- unloaded. -- > static void hs_hpc_fini_Main(void ) _ _ attribute__((destructor ) ) ; -- > static void hs_hpc_fini_Main(void) { -- > > static StgWord64 k0[2 ] = { 16252233372134256ULL,7370534374096082ULL } ; -- > hs_spt_remove(k0); -- > > static StgWord64 k1[2 ] = { 12545634534567898ULL,5409674567544151ULL } ; -- > hs_spt_remove(k1); -- > -- > } -- module GHC.Iface.Tidy.StaticPtrTable ( sptCreateStaticBinds , sptModuleInitCode , StaticPtrOpts (..) ) where Note [ Grand plan for static forms ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Static forms go through the compilation phases as follows . Here is a running example : f x = let k = map toUpper in ... ( static k ) ... * The renamer looks for out - of - scope names in the body of the static form , as always . If all names are in scope , the free variables of the body are stored in AST at the location of the static form . * The typechecker verifies that all free variables occurring in the static form are floatable to top level ( see Note [ Meaning of IdBindingInfo ] in . Types ) . In our example , ' k ' is floatable . Even though it is bound in a nested let , we are fine . * The desugarer replaces the static form with an application of the function ' makeStatic ' ( defined in module GHC.StaticPtr . Internal of base ) . So we get f x = let k = map toUpper in ... fromStaticPtr ( makeStatic location k ) ... * The simplifier runs the FloatOut pass which moves the calls to ' makeStatic ' to the top level . Thus the FloatOut pass is always executed , even when optimizations are disabled . So we get k = map toUpper static_ptr = makeStatic location k f x = ... fromStaticPtr static_ptr ... The FloatOut pass is careful to produce an /exported/ I d for a floated ' makeStatic ' call , so the binding is not removed or inlined by the simplifier . E.g. the code for ` f ` above might look like static_ptr = makeStatic location k f x = ... ( case static_ptr of ... ) ... which might be simplified to f x = ... ( case makeStatic location k of ... ) ... BUT the top - level binding for static_ptr must remain , so that it can be collected to populate the Static Pointer Table . Making the binding exported also has a necessary effect during the CoreTidy pass . * The CoreTidy pass replaces all bindings of the form b = /\ ... - > makeStatic location value with b = /\ ... - > StaticPtr key ( StaticPtrInfo " pkg key " " module " location ) value where a distinct key is generated for each binding . * If we are compiling to object code we insert a C stub ( generated by sptModuleInitCode ) into the final object which runs when the module is loaded , inserting the static forms defined by the module into the RTS 's static pointer table . * If we are compiling for the byte - code interpreter , we instead explicitly add the SPT entries ( recorded in CgGuts ' cg_spt_entries field ) to the interpreter process ' SPT table using the addSptEntry interpreter message . This happens in upsweep after we have compiled the module ( see GHC.Driver.Make.upsweep ' ) . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Static forms go through the compilation phases as follows. Here is a running example: f x = let k = map toUpper in ...(static k)... * The renamer looks for out-of-scope names in the body of the static form, as always. If all names are in scope, the free variables of the body are stored in AST at the location of the static form. * The typechecker verifies that all free variables occurring in the static form are floatable to top level (see Note [Meaning of IdBindingInfo] in GHC.Tc.Types). In our example, 'k' is floatable. Even though it is bound in a nested let, we are fine. * The desugarer replaces the static form with an application of the function 'makeStatic' (defined in module GHC.StaticPtr.Internal of base). So we get f x = let k = map toUpper in ...fromStaticPtr (makeStatic location k)... * The simplifier runs the FloatOut pass which moves the calls to 'makeStatic' to the top level. Thus the FloatOut pass is always executed, even when optimizations are disabled. So we get k = map toUpper static_ptr = makeStatic location k f x = ...fromStaticPtr static_ptr... The FloatOut pass is careful to produce an /exported/ Id for a floated 'makeStatic' call, so the binding is not removed or inlined by the simplifier. E.g. the code for `f` above might look like static_ptr = makeStatic location k f x = ...(case static_ptr of ...)... which might be simplified to f x = ...(case makeStatic location k of ...)... BUT the top-level binding for static_ptr must remain, so that it can be collected to populate the Static Pointer Table. Making the binding exported also has a necessary effect during the CoreTidy pass. * The CoreTidy pass replaces all bindings of the form b = /\ ... -> makeStatic location value with b = /\ ... -> StaticPtr key (StaticPtrInfo "pkg key" "module" location) value where a distinct key is generated for each binding. * If we are compiling to object code we insert a C stub (generated by sptModuleInitCode) into the final object which runs when the module is loaded, inserting the static forms defined by the module into the RTS's static pointer table. * If we are compiling for the byte-code interpreter, we instead explicitly add the SPT entries (recorded in CgGuts' cg_spt_entries field) to the interpreter process' SPT table using the addSptEntry interpreter message. This happens in upsweep after we have compiled the module (see GHC.Driver.Make.upsweep'). -} import GHC.Prelude import GHC.Platform import GHC.Core import GHC.Core.Utils (collectMakeStaticArgs) import GHC.Core.DataCon import GHC.Core.Make (mkStringExprFSWith,MkStringIds(..)) import GHC.Core.Type import GHC.Cmm.CLabel import GHC.Unit.Module import GHC.Utils.Outputable as Outputable import GHC.Linker.Types import GHC.Types.Id import GHC.Types.ForeignStubs import GHC.Data.Maybe import GHC.Data.FastString import Control.Monad.Trans.State.Strict import Data.List (intercalate) import GHC.Fingerprint data StaticPtrOpts = StaticPtrOpts ^ Target platform , opt_gen_cstub :: !Bool -- ^ Generate CStub or not , opt_mk_string :: !MkStringIds -- ^ Ids for `unpackCString[Utf8]#` ^ ` StaticPtrInfo ` datacon ^ ` StaticPtr ` datacon } -- | Replaces all bindings of the form -- -- > b = /\ ... -> makeStatic location value -- -- with -- -- > b = /\ ... -> > StaticPtr key ( StaticPtrInfo " pkg key " " module " location ) value -- -- where a distinct key is generated for each binding. -- -- It also yields the C stub that inserts these bindings into the static -- pointer table. sptCreateStaticBinds :: StaticPtrOpts -> Module -> CoreProgram -> IO ([SptEntry], Maybe CStub, CoreProgram) sptCreateStaticBinds opts this_mod binds = do (fps, binds') <- evalStateT (go [] [] binds) 0 let cstub | opt_gen_cstub opts = Just (sptModuleInitCode (opt_platform opts) this_mod fps) | otherwise = Nothing return (fps, cstub, binds') where go fps bs xs = case xs of [] -> return (reverse fps, reverse bs) bnd : xs' -> do (fps', bnd') <- replaceStaticBind bnd go (reverse fps' ++ fps) (bnd' : bs) xs' Generates keys and replaces ' makeStatic ' with ' StaticPtr ' . -- -- The 'Int' state is used to produce a different key for each binding. replaceStaticBind :: CoreBind -> StateT Int IO ([SptEntry], CoreBind) replaceStaticBind (NonRec b e) = do (mfp, (b', e')) <- replaceStatic b e return (maybeToList mfp, NonRec b' e') replaceStaticBind (Rec rbs) = do (mfps, rbs') <- unzip <$> mapM (uncurry replaceStatic) rbs return (catMaybes mfps, Rec rbs') replaceStatic :: Id -> CoreExpr -> StateT Int IO (Maybe SptEntry, (Id, CoreExpr)) replaceStatic b e@(collectTyBinders -> (tvs, e0)) = case collectMakeStaticArgs e0 of Nothing -> return (Nothing, (b, e)) Just (_, t, info, arg) -> do (fp, e') <- mkStaticBind t info arg return (Just (SptEntry b fp), (b, foldr Lam e' tvs)) mkStaticBind :: Type -> CoreExpr -> CoreExpr -> StateT Int IO (Fingerprint, CoreExpr) mkStaticBind t srcLoc e = do i <- get put (i + 1) let staticPtrInfoDataCon = opt_static_ptr_info_datacon opts let fp@(Fingerprint w0 w1) = mkStaticPtrFingerprint i let mk_string_fs = mkStringExprFSWith (opt_mk_string opts) let info = mkConApp staticPtrInfoDataCon [ mk_string_fs $ unitFS $ moduleUnit this_mod , mk_string_fs $ moduleNameFS $ moduleName this_mod , srcLoc ] let staticPtrDataCon = opt_static_ptr_datacon opts return (fp, mkConApp staticPtrDataCon [ Type t , mkWord64LitWord64 w0 , mkWord64LitWord64 w1 , info , e ]) mkStaticPtrFingerprint :: Int -> Fingerprint mkStaticPtrFingerprint n = fingerprintString $ intercalate ":" [ unitString $ moduleUnit this_mod , moduleNameString $ moduleName this_mod , show n ] -- | @sptModuleInitCode module fps@ is a C stub to insert the static entries -- of @module@ into the static pointer table. -- -- @fps@ is a list associating each binding corresponding to a static entry with -- its fingerprint. sptModuleInitCode :: Platform -> Module -> [SptEntry] -> CStub sptModuleInitCode platform this_mod entries no CStub if there is no entry | [] <- entries = mempty no CStub for the JS backend : it deals with it directly during JS code -- generation | ArchJavaScript <- platformArch platform = mempty | otherwise = initializerCStub platform init_fn_nm empty init_fn_body `mappend` finalizerCStub platform fini_fn_nm empty fini_fn_body where init_fn_nm = mkInitializerStubLabel this_mod (fsLit "spt") init_fn_body = vcat [ text "static StgWord64 k" <> int i <> text "[2] = " <> pprFingerprint fp <> semi $$ text "extern StgPtr " <> (pprCLabel platform $ mkClosureLabel (idName n) (idCafInfo n)) <> semi $$ text "hs_spt_insert" <> parens (hcat $ punctuate comma [ char 'k' <> int i , char '&' <> pprCLabel platform (mkClosureLabel (idName n) (idCafInfo n)) ] ) <> semi | (i, SptEntry n fp) <- zip [0..] entries ] fini_fn_nm = mkFinalizerStubLabel this_mod (fsLit "spt") fini_fn_body = vcat [ text "StgWord64 k" <> int i <> text "[2] = " <> pprFingerprint fp <> semi $$ text "hs_spt_remove" <> parens (char 'k' <> int i) <> semi | (i, (SptEntry _ fp)) <- zip [0..] entries ] pprFingerprint :: Fingerprint -> SDoc pprFingerprint (Fingerprint w1 w2) = braces $ hcat $ punctuate comma [ integer (fromIntegral w1) <> text "ULL" , integer (fromIntegral w2) <> text "ULL" ]
null
https://raw.githubusercontent.com/ghc/ghc/cc25d52e0f65d54c052908c7d91d5946342ab88a/compiler/GHC/Iface/Tidy/StaticPtrTable.hs
haskell
| Code generation for the Static Pointer Table Each module that uses 'static' keyword declares an initialization function of the form hs_spt_init_\<module>() which is emitted into the _stub.c file and annotated with __attribute__((constructor)) so that it gets executed at startup time. The function's purpose is to call hs_spt_insert to insert the static like this: > static void hs_hpc_init_Main(void) __attribute__((constructor)); > static void hs_hpc_init_Main(void) { > > extern StgPtr Main_r2wb_closure; > hs_spt_insert(k0, &Main_r2wb_closure); > > extern StgPtr Main_r2wc_closure; > hs_spt_insert(k1, &Main_r2wc_closure); > > } where the constants are fingerprints produced from the static forms. The linker must find the definitions matching the @extern StgPtr <name>@ declarations. For this to work, the identifiers of static pointers need to be There is also a finalization function for the time when the module is unloaded. > static void hs_hpc_fini_Main(void) { > > hs_spt_remove(k0); > > hs_spt_remove(k1); > > } ^ Generate CStub or not ^ Ids for `unpackCString[Utf8]#` | Replaces all bindings of the form > b = /\ ... -> makeStatic location value with > b = /\ ... -> where a distinct key is generated for each binding. It also yields the C stub that inserts these bindings into the static pointer table. The 'Int' state is used to produce a different key for each binding. | @sptModuleInitCode module fps@ is a C stub to insert the static entries of @module@ into the static pointer table. @fps@ is a list associating each binding corresponding to a static entry with its fingerprint. generation
# LANGUAGE ViewPatterns # ( c ) 2014 I / O Tweag pointers of this module in the hashtable of the RTS , and it looks something > static StgWord64 k0[2 ] = { 16252233372134256ULL,7370534374096082ULL } ; > static StgWord64 k1[2 ] = { 12545634534567898ULL,5409674567544151ULL } ; exported . This is done in ' GHC.Core . Opt . SetLevels.newLvlVar ' . > static void hs_hpc_fini_Main(void ) _ _ attribute__((destructor ) ) ; > static StgWord64 k0[2 ] = { 16252233372134256ULL,7370534374096082ULL } ; > static StgWord64 k1[2 ] = { 12545634534567898ULL,5409674567544151ULL } ; module GHC.Iface.Tidy.StaticPtrTable ( sptCreateStaticBinds , sptModuleInitCode , StaticPtrOpts (..) ) where Note [ Grand plan for static forms ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Static forms go through the compilation phases as follows . Here is a running example : f x = let k = map toUpper in ... ( static k ) ... * The renamer looks for out - of - scope names in the body of the static form , as always . If all names are in scope , the free variables of the body are stored in AST at the location of the static form . * The typechecker verifies that all free variables occurring in the static form are floatable to top level ( see Note [ Meaning of IdBindingInfo ] in . Types ) . In our example , ' k ' is floatable . Even though it is bound in a nested let , we are fine . * The desugarer replaces the static form with an application of the function ' makeStatic ' ( defined in module GHC.StaticPtr . Internal of base ) . So we get f x = let k = map toUpper in ... fromStaticPtr ( makeStatic location k ) ... * The simplifier runs the FloatOut pass which moves the calls to ' makeStatic ' to the top level . Thus the FloatOut pass is always executed , even when optimizations are disabled . So we get k = map toUpper static_ptr = makeStatic location k f x = ... fromStaticPtr static_ptr ... The FloatOut pass is careful to produce an /exported/ I d for a floated ' makeStatic ' call , so the binding is not removed or inlined by the simplifier . E.g. the code for ` f ` above might look like static_ptr = makeStatic location k f x = ... ( case static_ptr of ... ) ... which might be simplified to f x = ... ( case makeStatic location k of ... ) ... BUT the top - level binding for static_ptr must remain , so that it can be collected to populate the Static Pointer Table . Making the binding exported also has a necessary effect during the CoreTidy pass . * The CoreTidy pass replaces all bindings of the form b = /\ ... - > makeStatic location value with b = /\ ... - > StaticPtr key ( StaticPtrInfo " pkg key " " module " location ) value where a distinct key is generated for each binding . * If we are compiling to object code we insert a C stub ( generated by sptModuleInitCode ) into the final object which runs when the module is loaded , inserting the static forms defined by the module into the RTS 's static pointer table . * If we are compiling for the byte - code interpreter , we instead explicitly add the SPT entries ( recorded in CgGuts ' cg_spt_entries field ) to the interpreter process ' SPT table using the addSptEntry interpreter message . This happens in upsweep after we have compiled the module ( see GHC.Driver.Make.upsweep ' ) . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Static forms go through the compilation phases as follows. Here is a running example: f x = let k = map toUpper in ...(static k)... * The renamer looks for out-of-scope names in the body of the static form, as always. If all names are in scope, the free variables of the body are stored in AST at the location of the static form. * The typechecker verifies that all free variables occurring in the static form are floatable to top level (see Note [Meaning of IdBindingInfo] in GHC.Tc.Types). In our example, 'k' is floatable. Even though it is bound in a nested let, we are fine. * The desugarer replaces the static form with an application of the function 'makeStatic' (defined in module GHC.StaticPtr.Internal of base). So we get f x = let k = map toUpper in ...fromStaticPtr (makeStatic location k)... * The simplifier runs the FloatOut pass which moves the calls to 'makeStatic' to the top level. Thus the FloatOut pass is always executed, even when optimizations are disabled. So we get k = map toUpper static_ptr = makeStatic location k f x = ...fromStaticPtr static_ptr... The FloatOut pass is careful to produce an /exported/ Id for a floated 'makeStatic' call, so the binding is not removed or inlined by the simplifier. E.g. the code for `f` above might look like static_ptr = makeStatic location k f x = ...(case static_ptr of ...)... which might be simplified to f x = ...(case makeStatic location k of ...)... BUT the top-level binding for static_ptr must remain, so that it can be collected to populate the Static Pointer Table. Making the binding exported also has a necessary effect during the CoreTidy pass. * The CoreTidy pass replaces all bindings of the form b = /\ ... -> makeStatic location value with b = /\ ... -> StaticPtr key (StaticPtrInfo "pkg key" "module" location) value where a distinct key is generated for each binding. * If we are compiling to object code we insert a C stub (generated by sptModuleInitCode) into the final object which runs when the module is loaded, inserting the static forms defined by the module into the RTS's static pointer table. * If we are compiling for the byte-code interpreter, we instead explicitly add the SPT entries (recorded in CgGuts' cg_spt_entries field) to the interpreter process' SPT table using the addSptEntry interpreter message. This happens in upsweep after we have compiled the module (see GHC.Driver.Make.upsweep'). -} import GHC.Prelude import GHC.Platform import GHC.Core import GHC.Core.Utils (collectMakeStaticArgs) import GHC.Core.DataCon import GHC.Core.Make (mkStringExprFSWith,MkStringIds(..)) import GHC.Core.Type import GHC.Cmm.CLabel import GHC.Unit.Module import GHC.Utils.Outputable as Outputable import GHC.Linker.Types import GHC.Types.Id import GHC.Types.ForeignStubs import GHC.Data.Maybe import GHC.Data.FastString import Control.Monad.Trans.State.Strict import Data.List (intercalate) import GHC.Fingerprint data StaticPtrOpts = StaticPtrOpts ^ Target platform ^ ` StaticPtrInfo ` datacon ^ ` StaticPtr ` datacon } > StaticPtr key ( StaticPtrInfo " pkg key " " module " location ) value sptCreateStaticBinds :: StaticPtrOpts -> Module -> CoreProgram -> IO ([SptEntry], Maybe CStub, CoreProgram) sptCreateStaticBinds opts this_mod binds = do (fps, binds') <- evalStateT (go [] [] binds) 0 let cstub | opt_gen_cstub opts = Just (sptModuleInitCode (opt_platform opts) this_mod fps) | otherwise = Nothing return (fps, cstub, binds') where go fps bs xs = case xs of [] -> return (reverse fps, reverse bs) bnd : xs' -> do (fps', bnd') <- replaceStaticBind bnd go (reverse fps' ++ fps) (bnd' : bs) xs' Generates keys and replaces ' makeStatic ' with ' StaticPtr ' . replaceStaticBind :: CoreBind -> StateT Int IO ([SptEntry], CoreBind) replaceStaticBind (NonRec b e) = do (mfp, (b', e')) <- replaceStatic b e return (maybeToList mfp, NonRec b' e') replaceStaticBind (Rec rbs) = do (mfps, rbs') <- unzip <$> mapM (uncurry replaceStatic) rbs return (catMaybes mfps, Rec rbs') replaceStatic :: Id -> CoreExpr -> StateT Int IO (Maybe SptEntry, (Id, CoreExpr)) replaceStatic b e@(collectTyBinders -> (tvs, e0)) = case collectMakeStaticArgs e0 of Nothing -> return (Nothing, (b, e)) Just (_, t, info, arg) -> do (fp, e') <- mkStaticBind t info arg return (Just (SptEntry b fp), (b, foldr Lam e' tvs)) mkStaticBind :: Type -> CoreExpr -> CoreExpr -> StateT Int IO (Fingerprint, CoreExpr) mkStaticBind t srcLoc e = do i <- get put (i + 1) let staticPtrInfoDataCon = opt_static_ptr_info_datacon opts let fp@(Fingerprint w0 w1) = mkStaticPtrFingerprint i let mk_string_fs = mkStringExprFSWith (opt_mk_string opts) let info = mkConApp staticPtrInfoDataCon [ mk_string_fs $ unitFS $ moduleUnit this_mod , mk_string_fs $ moduleNameFS $ moduleName this_mod , srcLoc ] let staticPtrDataCon = opt_static_ptr_datacon opts return (fp, mkConApp staticPtrDataCon [ Type t , mkWord64LitWord64 w0 , mkWord64LitWord64 w1 , info , e ]) mkStaticPtrFingerprint :: Int -> Fingerprint mkStaticPtrFingerprint n = fingerprintString $ intercalate ":" [ unitString $ moduleUnit this_mod , moduleNameString $ moduleName this_mod , show n ] sptModuleInitCode :: Platform -> Module -> [SptEntry] -> CStub sptModuleInitCode platform this_mod entries no CStub if there is no entry | [] <- entries = mempty no CStub for the JS backend : it deals with it directly during JS code | ArchJavaScript <- platformArch platform = mempty | otherwise = initializerCStub platform init_fn_nm empty init_fn_body `mappend` finalizerCStub platform fini_fn_nm empty fini_fn_body where init_fn_nm = mkInitializerStubLabel this_mod (fsLit "spt") init_fn_body = vcat [ text "static StgWord64 k" <> int i <> text "[2] = " <> pprFingerprint fp <> semi $$ text "extern StgPtr " <> (pprCLabel platform $ mkClosureLabel (idName n) (idCafInfo n)) <> semi $$ text "hs_spt_insert" <> parens (hcat $ punctuate comma [ char 'k' <> int i , char '&' <> pprCLabel platform (mkClosureLabel (idName n) (idCafInfo n)) ] ) <> semi | (i, SptEntry n fp) <- zip [0..] entries ] fini_fn_nm = mkFinalizerStubLabel this_mod (fsLit "spt") fini_fn_body = vcat [ text "StgWord64 k" <> int i <> text "[2] = " <> pprFingerprint fp <> semi $$ text "hs_spt_remove" <> parens (char 'k' <> int i) <> semi | (i, (SptEntry _ fp)) <- zip [0..] entries ] pprFingerprint :: Fingerprint -> SDoc pprFingerprint (Fingerprint w1 w2) = braces $ hcat $ punctuate comma [ integer (fromIntegral w1) <> text "ULL" , integer (fromIntegral w2) <> text "ULL" ]
9da6d1f0d03940bfe64ddd2803561a9468ce43d0bb1f829d6664270e8b073c1e
craigl64/clim-ccl
dep-openmcl.lisp
;;; -*- Mode: Lisp; Package: Xlib; Log: clx.log -*- This file contains some of the system dependent code for CLX ;;; TEXAS INSTRUMENTS INCORPORATED ;;; P.O. BOX 2909 AUSTIN , TEXAS 78769 ;;; Copyright ( C ) 1987 Texas Instruments Incorporated . ;;; ;;; Permission is granted to any individual or institution to use, copy, modify, ;;; and distribute this software, provided that this complete copyright and ;;; permission notice is maintained, intact, in all copies and supporting ;;; documentation. ;;; Texas Instruments Incorporated provides this software " as is " without ;;; express or implied warranty. ;;; (in-package :xlib) (proclaim '(declaration array-register)) The size of the output buffer . Must be a multiple of 4 . (defparameter *output-buffer-size* 8192) ;;; Number of seconds to wait for a reply to a server request (defparameter *reply-timeout* nil) (progn (defconstant +word-0+ 1) (defconstant +word-1+ 0) (defconstant +long-0+ 3) (defconstant +long-1+ 2) (defconstant +long-2+ 1) (defconstant +long-3+ 0)) ;;; Set some compiler-options for often used code (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant +buffer-speed+ #+clx-debugging 1 #-clx-debugging 3 "Speed compiler option for buffer code.") (defconstant +buffer-safety+ #+clx-debugging 3 #-clx-debugging 0 "Safety compiler option for buffer code.") (defconstant +buffer-debug+ #+clx-debugging 2 #-clx-debugging 1 "Debug compiler option for buffer code>") (defun declare-bufmac () `(declare (optimize (speed ,+buffer-speed+) (safety ,+buffer-safety+) (debug ,+buffer-debug+)))) ;; It's my impression that in lucid there's some way to make a ;; declaration called fast-entry or something that causes a function ;; to not do some checking on args. Sadly, we have no lucid manuals ;; here. If such a declaration is available, it would be a good idea to make it here when + buffer - speed+ is 3 and + buffer - safety+ ;; is 0. (defun declare-buffun () `(declare (optimize (speed ,+buffer-speed+) (safety ,+buffer-safety+) (debug ,+buffer-debug+))))) (declaim (inline card8->int8 int8->card8 card16->int16 int16->card16 card32->int32 int32->card32)) (progn (defun card8->int8 (x) (declare (type card8 x)) (declare (clx-values int8)) #.(declare-buffun) (the int8 (if (logbitp 7 x) (the int8 (- x #x100)) x))) (defun int8->card8 (x) (declare (type int8 x)) (declare (clx-values card8)) #.(declare-buffun) (the card8 (ldb (byte 8 0) x))) (defun card16->int16 (x) (declare (type card16 x)) (declare (clx-values int16)) #.(declare-buffun) (the int16 (if (logbitp 15 x) (the int16 (- x #x10000)) x))) (defun int16->card16 (x) (declare (type int16 x)) (declare (clx-values card16)) #.(declare-buffun) (the card16 (ldb (byte 16 0) x))) (defun card32->int32 (x) (declare (type card32 x)) (declare (clx-values int32)) #.(declare-buffun) (the int32 (if (logbitp 31 x) (the int32 (- x #x100000000)) x))) (defun int32->card32 (x) (declare (type int32 x)) (declare (clx-values card32)) #.(declare-buffun) (the card32 (ldb (byte 32 0) x))) ) (declaim (inline aref-card8 aset-card8 aref-int8 aset-int8)) (progn (defun aref-card8 (a i) (declare (type buffer-bytes a) (type array-index i)) (declare (clx-values card8)) #.(declare-buffun) (the card8 (aref a i))) (defun aset-card8 (v a i) (declare (type card8 v) (type buffer-bytes a) (type array-index i)) #.(declare-buffun) (setf (aref a i) v)) (defun aref-int8 (a i) (declare (type buffer-bytes a) (type array-index i)) (declare (clx-values int8)) #.(declare-buffun) (card8->int8 (aref a i))) (defun aset-int8 (v a i) (declare (type int8 v) (type buffer-bytes a) (type array-index i)) #.(declare-buffun) (setf (aref a i) (int8->card8 v))) ) (progn (defun aref-card16 (a i) (declare (type buffer-bytes a) (type array-index i)) (declare (clx-values card16)) #.(declare-buffun) (the card16 (logior (the card16 (ash (the card8 (aref a (index+ i +word-1+))) 8)) (the card8 (aref a (index+ i +word-0+)))))) (defun aset-card16 (v a i) (declare (type card16 v) (type buffer-bytes a) (type array-index i)) #.(declare-buffun) (setf (aref a (index+ i +word-1+)) (the card8 (ldb (byte 8 8) v)) (aref a (index+ i +word-0+)) (the card8 (ldb (byte 8 0) v))) v) (defun aref-int16 (a i) (declare (type buffer-bytes a) (type array-index i)) (declare (clx-values int16)) #.(declare-buffun) (the int16 (logior (the int16 (ash (the int8 (aref-int8 a (index+ i +word-1+))) 8)) (the card8 (aref a (index+ i +word-0+)))))) (defun aset-int16 (v a i) (declare (type int16 v) (type buffer-bytes a) (type array-index i)) #.(declare-buffun) (setf (aref a (index+ i +word-1+)) (the card8 (ldb (byte 8 8) v)) (aref a (index+ i +word-0+)) (the card8 (ldb (byte 8 0) v))) v) (defun aref-card32 (a i) (declare (type buffer-bytes a) (type array-index i)) (declare (clx-values card32)) #.(declare-buffun) (the card32 (logior (the card32 (ash (the card8 (aref a (index+ i +long-3+))) 24)) (the card29 (ash (the card8 (aref a (index+ i +long-2+))) 16)) (the card16 (ash (the card8 (aref a (index+ i +long-1+))) 8)) (the card8 (aref a (index+ i +long-0+)))))) (defun aset-card32 (v a i) (declare (type card32 v) (type buffer-bytes a) (type array-index i)) #.(declare-buffun) (setf (aref a (index+ i +long-3+)) (the card8 (ldb (byte 8 24) v)) (aref a (index+ i +long-2+)) (the card8 (ldb (byte 8 16) v)) (aref a (index+ i +long-1+)) (the card8 (ldb (byte 8 8) v)) (aref a (index+ i +long-0+)) (the card8 (ldb (byte 8 0) v))) v) (defun aref-int32 (a i) (declare (type buffer-bytes a) (type array-index i)) (declare (clx-values int32)) #.(declare-buffun) (the int32 (logior (the int32 (ash (the int8 (aref-int8 a (index+ i +long-3+))) 24)) (the card29 (ash (the card8 (aref a (index+ i +long-2+))) 16)) (the card16 (ash (the card8 (aref a (index+ i +long-1+))) 8)) (the card8 (aref a (index+ i +long-0+)))))) (defun aset-int32 (v a i) (declare (type int32 v) (type buffer-bytes a) (type array-index i)) #.(declare-buffun) (setf (aref a (index+ i +long-3+)) (the card8 (ldb (byte 8 24) v)) (aref a (index+ i +long-2+)) (the card8 (ldb (byte 8 16) v)) (aref a (index+ i +long-1+)) (the card8 (ldb (byte 8 8) v)) (aref a (index+ i +long-0+)) (the card8 (ldb (byte 8 0) v))) v) (defun aref-card29 (a i) (declare (type buffer-bytes a) (type array-index i)) (declare (clx-values card29)) #.(declare-buffun) (the card29 (logior (the card29 (ash (the card8 (aref a (index+ i +long-3+))) 24)) (the card29 (ash (the card8 (aref a (index+ i +long-2+))) 16)) (the card16 (ash (the card8 (aref a (index+ i +long-1+))) 8)) (the card8 (aref a (index+ i +long-0+)))))) (defun aset-card29 (v a i) (declare (type card29 v) (type buffer-bytes a) (type array-index i)) #.(declare-buffun) (setf (aref a (index+ i +long-3+)) (the card8 (ldb (byte 8 24) v)) (aref a (index+ i +long-2+)) (the card8 (ldb (byte 8 16) v)) (aref a (index+ i +long-1+)) (the card8 (ldb (byte 8 8) v)) (aref a (index+ i +long-0+)) (the card8 (ldb (byte 8 0) v))) v) ) (defsetf aref-card8 (a i) (v) `(aset-card8 ,v ,a ,i)) (defsetf aref-int8 (a i) (v) `(aset-int8 ,v ,a ,i)) (defsetf aref-card16 (a i) (v) `(aset-card16 ,v ,a ,i)) (defsetf aref-int16 (a i) (v) `(aset-int16 ,v ,a ,i)) (defsetf aref-card32 (a i) (v) `(aset-card32 ,v ,a ,i)) (defsetf aref-int32 (a i) (v) `(aset-int32 ,v ,a ,i)) (defsetf aref-card29 (a i) (v) `(aset-card29 ,v ,a ,i)) ;;; Other random conversions (defun rgb-val->card16 (value) ;; Short floats are good enough (declare (type rgb-val value)) (declare (clx-values card16)) #.(declare-buffun) ;; Convert VALUE from float to card16 (the card16 (values (round (the rgb-val value) #.(/ 1.0s0 #xffff))))) (defun card16->rgb-val (value) ;; Short floats are good enough (declare (type card16 value)) (declare (clx-values short-float)) #.(declare-buffun) Convert VALUE from card16 to float (the short-float (* (the card16 value) #.(/ 1.0s0 #xffff)))) (defun radians->int16 (value) ;; Short floats are good enough (declare (type angle value)) (declare (clx-values int16)) #.(declare-buffun) (the int16 (values (round (the angle value) #.(float (/ pi 180.0s0 64.0s0) 0.0s0))))) (defun int16->radians (value) ;; Short floats are good enough (declare (type int16 value)) (declare (clx-values short-float)) #.(declare-buffun) (the short-float (* (the int16 value) #.(coerce (/ pi 180.0 64.0) 'short-float)))) ;;----------------------------------------------------------------------------- ;; Character transformation ;;----------------------------------------------------------------------------- ;;; This stuff transforms chars to ascii codes in card8's and back. ;;; You might have to hack it a little to get it to work for your machine. (declaim (inline char->card8 card8->char)) (macrolet ((char-translators () (let ((alist `( ;; The normal ascii codes for the control characters. ,@`((#\Return . 13) (#\Linefeed . 10) (#\Rubout . 127) (#\Page . 12) (#\Tab . 9) (#\Backspace . 8) (#\Newline . 10) (#\Space . 32)) ;; The rest of the common lisp charater set with ;; the normal ascii codes for them. (#\! . 33) (#\" . 34) (#\# . 35) (#\$ . 36) (#\% . 37) (#\& . 38) (#\' . 39) (#\( . 40) (#\) . 41) (#\* . 42) (#\+ . 43) (#\, . 44) (#\- . 45) (#\. . 46) (#\/ . 47) (#\0 . 48) (#\1 . 49) (#\2 . 50) (#\3 . 51) (#\4 . 52) (#\5 . 53) (#\6 . 54) (#\7 . 55) (#\8 . 56) . 59 ) ( # \ < . 60 ) (#\= . 61) (#\> . 62) (#\? . 63) (#\@ . 64) (#\A . 65) (#\B . 66) (#\C . 67) (#\D . 68) (#\E . 69) (#\F . 70) (#\G . 71) (#\H . 72) (#\I . 73) (#\J . 74) (#\K . 75) (#\L . 76) (#\M . 77) (#\N . 78) (#\O . 79) (#\P . 80) (#\Q . 81) (#\R . 82) (#\S . 83) (#\T . 84) (#\U . 85) (#\V . 86) (#\W . 87) (#\X . 88) (#\Y . 89) (#\Z . 90) (#\[ . 91) (#\\ . 92) (#\] . 93) (#\^ . 94) (#\_ . 95) (#\` . 96) (#\a . 97) (#\b . 98) (#\c . 99) (#\d . 100) (#\e . 101) (#\f . 102) (#\g . 103) (#\h . 104) (#\i . 105) (#\j . 106) (#\k . 107) (#\l . 108) (#\m . 109) (#\n . 110) (#\o . 111) (#\p . 112) (#\q . 113) (#\r . 114) (#\s . 115) (#\t . 116) (#\u . 117) (#\v . 118) (#\w . 119) (#\x . 120) (#\y . 121) (#\z . 122) (#\{ . 123) (#\| . 124) (#\} . 125) (#\~ . 126)))) (cond ((dolist (pair alist nil) (when (not (= (char-code (car pair)) (cdr pair))) (return t))) `(progn (defconstant *char-to-card8-translation-table* ',(let ((array (make-array (let ((max-char-code 255)) (dolist (pair alist) (setq max-char-code (max max-char-code (char-code (car pair))))) (1+ max-char-code)) :element-type 'card8))) (dotimes (i (length array)) (setf (aref array i) (mod i 256))) (dolist (pair alist) (setf (aref array (char-code (car pair))) (cdr pair))) array)) (defconstant *card8-to-char-translation-table* ',(let ((array (make-array 256))) (dotimes (i (length array)) (setf (aref array i) (code-char i))) (dolist (pair alist) (setf (aref array (cdr pair)) (car pair))) array)) (progn (defun char->card8 (char) (declare (type base-char char)) #.(declare-buffun) (the card8 (aref (the (simple-array card8 (*)) *char-to-card8-translation-table*) (the array-index (char-code char))))) (defun card8->char (card8) (declare (type card8 card8)) #.(declare-buffun) (the base-char (or (aref (the simple-vector *card8-to-char-translation-table*) card8) (error "Invalid CHAR code ~D." card8)))) ) #+Genera (progn (defun char->card8 (char) (declare lt:(side-effects reader reducible)) (aref *char-to-card8-translation-table* (char-code char))) (defun card8->char (card8) (declare lt:(side-effects reader reducible)) (aref *card8-to-char-translation-table* card8)) ) (dotimes (i 256) (unless (= i (char->card8 (card8->char i))) (warn "The card8->char mapping is not invertible through char->card8. Info:~%~S" (list i (card8->char i) (char->card8 (card8->char i)))) (return nil))) (dotimes (i (length *char-to-card8-translation-table*)) (let ((char (code-char i))) (unless (eql char (card8->char (char->card8 char))) (warn "The char->card8 mapping is not invertible through card8->char. Info:~%~S" (list char (char->card8 char) (card8->char (char->card8 char)))) (return nil)))))) (t `(progn (defun char->card8 (char) (declare (type base-char char)) #.(declare-buffun) (the card8 (char-code char))) (defun card8->char (card8) (declare (type card8 card8)) #.(declare-buffun) (the base-char (code-char card8))) )))))) (char-translators)) ;;----------------------------------------------------------------------------- Process Locking ;; ;; Common-Lisp doesn't provide process locking primitives, so we define our own here , based on primitives . Holding - Lock is very similar to with - lock on The TI Explorer , and a little more efficient ;; than with-process-lock on a Symbolics. ;;----------------------------------------------------------------------------- ;;; MAKE-PROCESS-LOCK: Creating a process lock. (defun make-process-lock (name) (ccl:make-lock name)) ;;; HOLDING-LOCK: Execute a body of code with a lock held. ;;; The holding-lock macro takes a timeout keyword argument. EVENT-LISTEN ;;; passes its timeout to the holding-lock macro, so any timeout you want to ;;; work for event-listen you should do for holding-lock. (defmacro holding-lock ((locator display &optional whostate &key timeout) &body body) (declare (ignore timeout display)) `(ccl:with-lock-grabbed (,locator ,whostate) ,@body)) ;;; WITHOUT-ABORTS ;;; If you can inhibit asynchronous keyboard aborts inside the body of this ;;; macro, then it is a good idea to do this. This macro is wrapped around ;;; request writing and reply reading to ensure that requests are atomically ;;; written and replies are atomically read from the stream. (defmacro without-aborts (&body body) `(ccl:without-interrupts ,@body)) ;;; PROCESS-BLOCK: Wait until a given predicate returns a non-NIL value. Caller guarantees that PROCESS - WAKEUP will be called after the predicate 's ;;; value changes. (defun process-block (whostate predicate &rest predicate-args) #+Ignore (declare (dynamic-extern predicate-args)) (apply #'ccl:process-wait whostate predicate predicate-args)) ;;; PROCESS-WAKEUP: Check some other process' wait function. (declaim (inline process-wakeup)) (defun process-wakeup (process) (declare (ignore process)) nil) ;;; CURRENT-PROCESS: Return the current process object for input locking and for calling PROCESS - WAKEUP . (declaim (inline current-process)) ;;; Default return NIL, which is acceptable even if there is a scheduler. (defun current-process () ccl::*current-process*) ;;; WITHOUT-INTERRUPTS -- provide for atomic operations. (defmacro without-interrupts (&body body) `(ccl:without-interrupts ,@body)) CONDITIONAL - STORE : ;; This should use GET-SETF-METHOD to avoid evaluating subforms multiple times. ;; It doesn't because CLtL doesn't pass the environment to GET-SETF-METHOD. (defvar *conditional-store-lock* (ccl:make-lock "conditional store")) (defmacro conditional-store (place old-value new-value) `(ccl:with-lock-grabbed (*conditional-store-lock*) (cond ((eq ,place ,old-value) (setf ,place ,new-value) t)))) ;;;---------------------------------------------------------------------------- ;;; IO Error Recovery All I / O operations are done within a WRAP - BUF - OUTPUT macro . ;;; It prevents multiple mindless errors when the network craters. ;;; ;;;---------------------------------------------------------------------------- (defmacro wrap-buf-output ((buffer) &body body) ;; Error recovery wrapper `(unless (buffer-dead ,buffer) ,@body)) (defmacro wrap-buf-input ((buffer) &body body) (declare (ignore buffer)) ;; Error recovery wrapper `(progn ,@body)) ;;;---------------------------------------------------------------------------- ;;; System dependent IO primitives ;;; Functions for opening, reading writing forcing-output and closing ;;; the stream to the server. ;;;---------------------------------------------------------------------------- OPEN - X - STREAM - create a stream for communicating to the appropriate X ;;; server (defparameter ccl::*x-server-unix-socket-format-string* "/tmp/.X11-unix/X~d") (defun open-x-stream (host display protocol) (declare (ignore protocol)) (if (or (string= host "") (string= host "unix")) (ccl::make-socket :connect :active :address-family :file :remote-filename (format nil ccl::*x-server-unix-socket-format-string* display)) (ccl::make-socket :connect :active :remote-host host :remote-port (+ 6000 display)))) ;;; BUFFER-READ-DEFAULT - read data from the X stream (defun buffer-read-default (display vector start end timeout) (declare (type display display) (type buffer-bytes vector) (type array-index start end) (type (or null (real 0 *)) timeout)) #.(declare-buffun) (let ((stream (display-input-stream display))) (declare (type (or null stream) stream)) (or (cond ((null stream)) ((listen stream) nil) ((and timeout (= timeout 0)) :timeout) ((buffer-input-wait-default display timeout))) (progn (ccl:stream-read-ivector stream vector start (- end start)) nil)))) ;;; BUFFER-WRITE-DEFAULT - write data to the X stream (defun buffer-write-default (vector display start end) (declare (type buffer-bytes vector) (type display display) (type array-index start end)) #.(declare-buffun) (let ((stream (display-output-stream display))) (declare (type (or null stream) stream)) (unless (null stream) (ccl:stream-write-ivector stream vector start (- end start))) nil)) ;;; buffer-force-output-default - force output to the X stream (defun buffer-force-output-default (display) ;; The default buffer force-output function for use with common-lisp streams (declare (type display display)) (let ((stream (display-output-stream display))) (declare (type (or null stream) stream)) (unless (null stream) (force-output stream)))) BUFFER - CLOSE - DEFAULT - close the X stream (defun buffer-close-default (display &key abort) ;; The default buffer close function for use with common-lisp streams (declare (type display display)) #.(declare-buffun) (let ((stream (display-output-stream display))) (declare (type (or null stream) stream)) (unless (null stream) (close stream :abort abort)))) BUFFER - INPUT - WAIT - DEFAULT - wait for for input to be available for the ;;; buffer. This is called in read-input between requests, so that a process ;;; waiting for input is abortable when between requests. Should return ;;; :TIMEOUT if it times out, NIL otherwise. (defun buffer-input-wait-default (display timeout) (declare (type display display) (type (or null number) timeout)) (let ((stream (display-input-stream display))) (declare (type (or null stream) stream)) (cond ((null stream)) ((listen stream) nil) ((eql timeout 0) :timeout) (t (let* ((fd (ccl::stream-device stream :input)) (ticks (and timeout (floor (* timeout ccl::*ticks-per-second*))))) (if (ccl::process-input-wait fd ticks) nil :timeout)))))) ;;; BUFFER-LISTEN-DEFAULT - returns T if there is input available for the ;;; buffer. This should never block, so it can be called from the scheduler. ;;; The default implementation is to just use listen. (defun buffer-listen-default (display) (declare (type display display)) (let ((stream (display-input-stream display))) (declare (type (or null stream) stream)) (if (null stream) t (listen stream)))) ;;;---------------------------------------------------------------------------- ;;; System dependent speed hacks ;;;---------------------------------------------------------------------------- ;; WITH - STACK - LIST is used by WITH - STATE as a memory saving feature . ;; If your lisp doesn't have stack-lists, and you're worried about ;; consing garbage, you may want to re-write this to allocate and ;; initialize lists from a resource. ;; (defmacro with-stack-list ((var &rest elements) &body body) SYNTAX : ( WITH - STACK - LIST ( var exp1 ... expN ) body ) Equivalent to ( LET ( ( var ( MAPCAR # ' EVAL ' ( exp1 ... expN ) ) ) ) body ) except that the list produced by MAPCAR resides on the stack and therefore DISAPPEARS when WITH - STACK - LIST is exited . `(let ((,var (list ,@elements))) (declare (type cons ,var) #+clx-ansi-common-lisp (dynamic-extent ,var)) ,@body)) (defmacro with-stack-list* ((var &rest elements) &body body) SYNTAX : ( WITH - STACK - LIST * ( var exp1 ... expN ) body ) Equivalent to ( LET ( ( var ( APPLY # ' LIST * ( MAPCAR # ' EVAL ' ( exp1 ... expN ) ) ) ) ) body ) except that the list produced by MAPCAR resides on the stack and therefore DISAPPEARS when WITH - STACK - LIST is exited . `(let ((,var (list* ,@elements))) (declare (type cons ,var) (dynamic-extent ,var)) ,@body)) (declaim (inline buffer-replace)) (defun buffer-replace (buf1 buf2 start1 end1 &optional (start2 0)) (declare (type buffer-bytes buf1 buf2) (type array-index start1 end1 start2)) (replace buf1 buf2 :start1 start1 :end1 end1 :start2 start2)) (defmacro with-gcontext-bindings ((gc saved-state indexes ts-index temp-mask temp-gc) &body body) (let ((local-state (gensym)) (resets nil)) (dolist (index indexes) (push `(setf (svref ,local-state ,index) (svref ,saved-state ,index)) resets)) `(unwind-protect (progn ,@body) (let ((,local-state (gcontext-local-state ,gc))) (declare (type gcontext-state ,local-state)) ,@resets (setf (svref ,local-state ,ts-index) 0)) (when ,temp-gc (restore-gcontext-temp-state ,gc ,temp-mask ,temp-gc)) (deallocate-gcontext-state ,saved-state)))) ;;;---------------------------------------------------------------------------- How much error detection should CLX do ? ;;; Several levels are possible: ;;; 1 . Do the equivalent of check - type on every argument . ;;; 2 . Simply report TYPE - ERROR . This eliminates overhead of all the format ;;; strings generated by check-type. ;;; 3 . Do error checking only on arguments that are likely to have errors ;;; (like keyword names) ;;; 4 . Do error checking only where not doing so may dammage the envirnment ;;; on a non-tagged machine (i.e. when storing into a structure that has ;;; been passed in) ;;; 5 . No extra error detection code . On 's , ASET may barf trying to ;;; store a non-integer into a number array. ;;; ;;; How extensive should the error checking be? For example, if the server expects a CARD16 , is is sufficient for CLX to check for integer , or ;;; should it also check for non-negative and less than 65536? ;;;---------------------------------------------------------------------------- ;; The +TYPE-CHECK?+ constant controls how much error checking is done. ;; Possible values are: ;; NIL - Don't do any error checking t - Do the equivalent of checktype on every argument ;; :minimal - Do error checking only where errors are likely ;;; This controls macro expansion, and isn't changable at run-time You will ;;; probably want to set this to nil if you want good performance at ;;; production time. (defconstant +type-check?+ nil) ;; TYPE? is used to allow the code to do error checking at a different level from ;; the declarations. It also does some optimizations for systems that don't have good compiler support for TYPEP . The definitions for CARD32 , CARD16 , INT16 , etc . ;; include range checks. You can modify TYPE? to do less extensive checking ;; for these types if you desire. ;; # # # This comment is a lie ! TYPE ? is really also used for run - time type ;; dispatching, not just type checking. -- Ram. (defmacro type? (object type) (if (not (constantp type)) `(typep ,object ,type) (progn (setq type (eval type)) (let ((predicate (assoc type '((drawable drawable-p) (window window-p) (pixmap pixmap-p) (cursor cursor-p) (font font-p) (gcontext gcontext-p) (colormap colormap-p) (null null) (integer integerp))))) (cond (predicate `(,(second predicate) ,object)) ((eq type 'generalized-boolean) 't) ; Everything is a generalized-boolean. (+type-check?+ `(locally (declare (optimize safety)) (typep ,object ',type))) (t `(typep ,object ',type))))))) ;; X-TYPE-ERROR is the function called for type errors. ;; If you want lots of checking, but are concerned about code size, ;; this can be made into a macro that ignores some parameters. (defun x-type-error (object type &optional error-string) (x-error 'x-type-error :datum object :expected-type type :type-string error-string)) ;;----------------------------------------------------------------------------- ;; Error handlers Hack up KMP error signaling using zetalisp until the real thing comes ;; along ;;----------------------------------------------------------------------------- (defun default-error-handler (display error-key &rest key-vals &key asynchronous &allow-other-keys) (declare (type generalized-boolean asynchronous) (dynamic-extent key-vals)) ;; The default display-error-handler. ;; It signals the conditions listed in the DISPLAY file. (if asynchronous (apply #'x-cerror "Ignore" error-key :display display :error-key error-key key-vals) (apply #'x-error error-key :display display :error-key error-key key-vals))) (defun x-error (condition &rest keyargs) (declare (dynamic-extent keyargs)) (apply #'error condition keyargs)) (defun x-cerror (proceed-format-string condition &rest keyargs) (declare (dynamic-extent keyargs)) (apply #'cerror proceed-format-string condition keyargs)) version 15 of error handling defines the syntax for define - condition to be : ;; DEFINE-CONDITION name (parent-type) [({slot}*) {option}*] Where option is one of : ( : documentation doc - string ) (: conc - name symbol - or - string ) ;; or (:report exp) (define-condition x-error (error) ()) ;;----------------------------------------------------------------------------- ;; HOST hacking ;;----------------------------------------------------------------------------- (defun host-address (host &optional (family :internet)) ;; Return a list whose car is the family keyword (:internet :DECnet :Chaos) ;; and cdr is a list of network address bytes. (declare (type stringable host) (type (or null (member :internet :decnet :chaos) card8) family)) (declare (clx-values list)) (ecase family ((:internet nil 0) (let* ((addr (ccl::host-as-inet-host host))) (cons :internet (list (ldb (byte 8 24) addr) (ldb (byte 8 16) addr) (ldb (byte 8 8) addr) (ldb (byte 8 0) addr))))))) ;;----------------------------------------------------------------------------- ;; Whether to use closures for requests or not. ;;----------------------------------------------------------------------------- ;;; If this macro expands to non-NIL, then request and locking code is ;;; compiled in a much more compact format, as the common code is shared, and ;;; the specific code is built into a closure that is funcalled by the shared ;;; code. If your compiler makes efficient use of closures then you probably ;;; want to make this expand to T, as it makes the code more compact. (defmacro use-closures () nil) (defun clx-macroexpand (form env) (macroexpand form env)) ;;----------------------------------------------------------------------------- ;; Resource stuff ;;----------------------------------------------------------------------------- Utilities (defun getenv (name) (ccl::getenv name)) (defun get-host-name () "Return the same hostname as gethostname(3) would" (machine-instance)) (defun homedir-file-pathname (name) (merge-pathnames (user-homedir-pathname) (pathname name))) DEFAULT - RESOURCES - PATHNAME - The pathname of the resources file to load if ;;; a resource manager isn't running. (defun default-resources-pathname () (homedir-file-pathname ".Xdefaults")) ;;; RESOURCES-PATHNAME - The pathname of the resources file to load after the ;;; defaults have been loaded. (defun resources-pathname () (or (let ((string (getenv "XENVIRONMENT"))) (and string (pathname string))) (homedir-file-pathname (concatenate 'string ".Xdefaults-" (get-host-name))))) ;;; AUTHORITY-PATHNAME - The pathname of the authority file. (defun authority-pathname () (or (let ((xauthority (getenv "XAUTHORITY"))) (and xauthority (pathname xauthority))) (homedir-file-pathname ".Xauthority"))) this particular defaulting behaviour is typical to most Unices , I think (defun get-default-display (&optional display-name) "Parse the argument DISPLAY-NAME, or the environment variable $DISPLAY if it is NIL. Display names have the format [protocol/] [hostname] : [:] displaynumber [.screennumber] There are two special cases in parsing, to match that done in the Xlib C language bindings - If the hostname is ``unix'' or the empty string, any supplied protocol is ignored and a connection is made using the :local transport. - If a double colon separates hostname from displaynumber, the protocol is assumed to be decnet. Returns a list of (host display-number screen protocol)." (let* ((name (or display-name (getenv "DISPLAY") (error "DISPLAY environment variable is not set"))) (slash-i (or (position #\/ name) -1)) (colon-i (position #\: name :start (1+ slash-i))) (decnet-colon-p (eql (elt name (1+ colon-i)) #\:)) (host (subseq name (1+ slash-i) colon-i)) (dot-i (and colon-i (position #\. name :start colon-i))) (display (when colon-i (parse-integer name :start (if decnet-colon-p (+ colon-i 2) (1+ colon-i)) :end dot-i))) (screen (when dot-i (parse-integer name :start (1+ dot-i)))) (protocol (cond ((or (string= host "") (string-equal host "unix")) :local) (decnet-colon-p :decnet) ((> slash-i -1) (intern (string-upcase (subseq name 0 slash-i)) :keyword)) (t :internet)))) (list host (or display 0) (or screen 0) protocol))) ;;----------------------------------------------------------------------------- GC stuff ;;----------------------------------------------------------------------------- (defun gc-cleanup () (declare (special *event-free-list* *pending-command-free-list* *reply-buffer-free-lists* *gcontext-local-state-cache* *temp-gcontext-cache*)) (setq *event-free-list* nil) (setq *pending-command-free-list* nil) (when (boundp '*reply-buffer-free-lists*) (fill *reply-buffer-free-lists* nil)) (setq *gcontext-local-state-cache* nil) (setq *temp-gcontext-cache* nil) nil) ;;----------------------------------------------------------------------------- ;; DEFAULT-KEYSYM-TRANSLATE ;;----------------------------------------------------------------------------- ;;; If object is a character, char-bits are set from state. ;;; ;;; [the following isn't implemented (should it be?)] ;;; If object is a list, it is an alist with entries: ;;; (base-char [modifiers] [mask-modifiers]) ;;; When MODIFIERS are specified, this character translation ;;; will only take effect when the specified modifiers are pressed. ;;; MASK-MODIFIERS can be used to specify a set of modifiers to ignore. ;;; When MASK-MODIFIERS is missing, all other modifiers are ignored. ;;; In ambiguous cases, the most specific translation is used. (defun default-keysym-translate (display state object) (declare (type display display) (type card16 state) (type t object) (ignore display state) (clx-values t)) object) ;;----------------------------------------------------------------------------- ;; Image stuff ;;----------------------------------------------------------------------------- ;;; Types (deftype pixarray-1-element-type () 'bit) (deftype pixarray-4-element-type () '(unsigned-byte 4)) (deftype pixarray-8-element-type () '(unsigned-byte 8)) (deftype pixarray-16-element-type () '(unsigned-byte 16)) (deftype pixarray-24-element-type () '(unsigned-byte 24)) (deftype pixarray-32-element-type () '(unsigned-byte 32)) (deftype pixarray-1 () '(array pixarray-1-element-type (* *))) (deftype pixarray-4 () '(array pixarray-4-element-type (* *))) (deftype pixarray-8 () '(array pixarray-8-element-type (* *))) (deftype pixarray-16 () '(array pixarray-16-element-type (* *))) (deftype pixarray-24 () '(array pixarray-24-element-type (* *))) (deftype pixarray-32 () '(array pixarray-32-element-type (* *))) (deftype pixarray () '(or pixarray-1 pixarray-4 pixarray-8 pixarray-16 pixarray-24 pixarray-32)) (deftype bitmap () 'pixarray-1) ;;; WITH-UNDERLYING-SIMPLE-VECTOR (defmacro with-underlying-simple-vector ((variable element-type pixarray) &body body) (declare (ignore element-type)) `(let* ((,variable (ccl::array-data-and-offset ,pixarray))) ,@body)) ;;; These are used to read and write pixels from and to CARD8s. READ - IMAGE - LOAD - BYTE is used to extract 1 and 4 bit pixels from CARD8s . (defmacro read-image-load-byte (size position integer) (unless +image-bit-lsb-first-p+ (setq position (- 7 position))) `(the (unsigned-byte ,size) (ldb (byte ,size ,position) (the card8 ,integer)))) READ - IMAGE - ASSEMBLE - BYTES is used to build 16 , 24 and 32 bit pixels from the appropriate number of CARD8s . (defmacro read-image-assemble-bytes (&rest bytes) (unless +image-byte-lsb-first-p+ (setq bytes (reverse bytes))) (let ((it (first bytes)) (count 0)) (dolist (byte (rest bytes)) (setq it `(dpb (the card8 ,byte) (byte 8 ,(incf count 8)) (the (unsigned-byte ,count) ,it)))) `(the (unsigned-byte ,(* (length bytes) 8)) ,it))) WRITE - IMAGE - LOAD - BYTE is used to extract a CARD8 from a 16 , 24 or 32 bit ;;; pixel. (defmacro write-image-load-byte (position integer integer-size) integer-size (unless +image-byte-lsb-first-p+ (setq position (- integer-size 8 position))) `(the card8 (ldb (byte 8 ,position) (the (unsigned-byte ,integer-size) ,integer)))) WRITE - IMAGE - ASSEMBLE - BYTES is used to build a CARD8 from 1 or 4 bit ;;; pixels. (defmacro write-image-assemble-bytes (&rest bytes) (unless +image-bit-lsb-first-p+ (setq bytes (reverse bytes))) (let ((size (floor 8 (length bytes))) (it (first bytes)) (count 0)) (dolist (byte (rest bytes)) (setq it `(dpb (the (unsigned-byte ,size) ,byte) (byte ,size ,(incf count size)) (the (unsigned-byte ,count) ,it)))) `(the card8 ,it))) If you can write fast routines that can read and write pixarrays out of a ;;; buffer-bytes, do it! It makes the image code a lot faster. The ;;; FAST-READ-PIXARRAY, FAST-WRITE-PIXARRAY and FAST-COPY-PIXARRAY routines ;;; return T if they can do it, NIL if they can't. ;;; FAST-READ-PIXARRAY - fill part of a pixarray from a buffer of card8s (defun fast-read-pixarray (bbuf boffset pixarray x y width height padded-bytes-per-line bits-per-pixel unit byte-lsb-first-p bit-lsb-first-p) (declare (ignore bbuf boffset pixarray x y width height padded-bytes-per-line bits-per-pixel unit byte-lsb-first-p bit-lsb-first-p)) nil) ;;; FAST-WRITE-PIXARRAY - copy part of a pixarray into an array of CARD8s (defun fast-write-pixarray (bbuf boffset pixarray x y width height padded-bytes-per-line bits-per-pixel unit byte-lsb-first-p bit-lsb-first-p) (declare (ignore bbuf boffset pixarray x y width height padded-bytes-per-line bits-per-pixel unit byte-lsb-first-p bit-lsb-first-p)) nil) ;;; FAST-COPY-PIXARRAY - copy part of a pixarray into another (defun fast-copy-pixarray (pixarray copy x y width height bits-per-pixel) (declare (ignore pixarray copy x y width height bits-per-pixel)) nil)
null
https://raw.githubusercontent.com/craigl64/clim-ccl/301efbd770745b429f2b00b4e8ca6624de9d9ea9/xlib/dep-openmcl.lisp
lisp
-*- Mode: Lisp; Package: Xlib; Log: clx.log -*- P.O. BOX 2909 Permission is granted to any individual or institution to use, copy, modify, and distribute this software, provided that this complete copyright and permission notice is maintained, intact, in all copies and supporting documentation. express or implied warranty. Number of seconds to wait for a reply to a server request Set some compiler-options for often used code It's my impression that in lucid there's some way to make a declaration called fast-entry or something that causes a function to not do some checking on args. Sadly, we have no lucid manuals here. If such a declaration is available, it would be a good is 0. Other random conversions Short floats are good enough Convert VALUE from float to card16 Short floats are good enough Short floats are good enough Short floats are good enough ----------------------------------------------------------------------------- Character transformation ----------------------------------------------------------------------------- This stuff transforms chars to ascii codes in card8's and back. You might have to hack it a little to get it to work for your machine. The normal ascii codes for the control characters. The rest of the common lisp charater set with the normal ascii codes for them. ----------------------------------------------------------------------------- Common-Lisp doesn't provide process locking primitives, so we define than with-process-lock on a Symbolics. ----------------------------------------------------------------------------- MAKE-PROCESS-LOCK: Creating a process lock. HOLDING-LOCK: Execute a body of code with a lock held. The holding-lock macro takes a timeout keyword argument. EVENT-LISTEN passes its timeout to the holding-lock macro, so any timeout you want to work for event-listen you should do for holding-lock. WITHOUT-ABORTS If you can inhibit asynchronous keyboard aborts inside the body of this macro, then it is a good idea to do this. This macro is wrapped around request writing and reply reading to ensure that requests are atomically written and replies are atomically read from the stream. PROCESS-BLOCK: Wait until a given predicate returns a non-NIL value. value changes. PROCESS-WAKEUP: Check some other process' wait function. CURRENT-PROCESS: Return the current process object for input locking and Default return NIL, which is acceptable even if there is a scheduler. WITHOUT-INTERRUPTS -- provide for atomic operations. This should use GET-SETF-METHOD to avoid evaluating subforms multiple times. It doesn't because CLtL doesn't pass the environment to GET-SETF-METHOD. ---------------------------------------------------------------------------- IO Error Recovery It prevents multiple mindless errors when the network craters. ---------------------------------------------------------------------------- Error recovery wrapper Error recovery wrapper ---------------------------------------------------------------------------- System dependent IO primitives Functions for opening, reading writing forcing-output and closing the stream to the server. ---------------------------------------------------------------------------- server BUFFER-READ-DEFAULT - read data from the X stream BUFFER-WRITE-DEFAULT - write data to the X stream buffer-force-output-default - force output to the X stream The default buffer force-output function for use with common-lisp streams The default buffer close function for use with common-lisp streams buffer. This is called in read-input between requests, so that a process waiting for input is abortable when between requests. Should return :TIMEOUT if it times out, NIL otherwise. BUFFER-LISTEN-DEFAULT - returns T if there is input available for the buffer. This should never block, so it can be called from the scheduler. The default implementation is to just use listen. ---------------------------------------------------------------------------- System dependent speed hacks ---------------------------------------------------------------------------- If your lisp doesn't have stack-lists, and you're worried about consing garbage, you may want to re-write this to allocate and initialize lists from a resource. ---------------------------------------------------------------------------- Several levels are possible: strings generated by check-type. (like keyword names) on a non-tagged machine (i.e. when storing into a structure that has been passed in) store a non-integer into a number array. How extensive should the error checking be? For example, if the server should it also check for non-negative and less than 65536? ---------------------------------------------------------------------------- The +TYPE-CHECK?+ constant controls how much error checking is done. Possible values are: NIL - Don't do any error checking :minimal - Do error checking only where errors are likely This controls macro expansion, and isn't changable at run-time You will probably want to set this to nil if you want good performance at production time. TYPE? is used to allow the code to do error checking at a different level from the declarations. It also does some optimizations for systems that don't have include range checks. You can modify TYPE? to do less extensive checking for these types if you desire. dispatching, not just type checking. -- Ram. Everything is a generalized-boolean. X-TYPE-ERROR is the function called for type errors. If you want lots of checking, but are concerned about code size, this can be made into a macro that ignores some parameters. ----------------------------------------------------------------------------- Error handlers along ----------------------------------------------------------------------------- The default display-error-handler. It signals the conditions listed in the DISPLAY file. DEFINE-CONDITION name (parent-type) [({slot}*) {option}*] or (:report exp) ----------------------------------------------------------------------------- HOST hacking ----------------------------------------------------------------------------- Return a list whose car is the family keyword (:internet :DECnet :Chaos) and cdr is a list of network address bytes. ----------------------------------------------------------------------------- Whether to use closures for requests or not. ----------------------------------------------------------------------------- If this macro expands to non-NIL, then request and locking code is compiled in a much more compact format, as the common code is shared, and the specific code is built into a closure that is funcalled by the shared code. If your compiler makes efficient use of closures then you probably want to make this expand to T, as it makes the code more compact. ----------------------------------------------------------------------------- Resource stuff ----------------------------------------------------------------------------- a resource manager isn't running. RESOURCES-PATHNAME - The pathname of the resources file to load after the defaults have been loaded. AUTHORITY-PATHNAME - The pathname of the authority file. ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- DEFAULT-KEYSYM-TRANSLATE ----------------------------------------------------------------------------- If object is a character, char-bits are set from state. [the following isn't implemented (should it be?)] If object is a list, it is an alist with entries: (base-char [modifiers] [mask-modifiers]) When MODIFIERS are specified, this character translation will only take effect when the specified modifiers are pressed. MASK-MODIFIERS can be used to specify a set of modifiers to ignore. When MASK-MODIFIERS is missing, all other modifiers are ignored. In ambiguous cases, the most specific translation is used. ----------------------------------------------------------------------------- Image stuff ----------------------------------------------------------------------------- Types WITH-UNDERLYING-SIMPLE-VECTOR These are used to read and write pixels from and to CARD8s. pixel. pixels. buffer-bytes, do it! It makes the image code a lot faster. The FAST-READ-PIXARRAY, FAST-WRITE-PIXARRAY and FAST-COPY-PIXARRAY routines return T if they can do it, NIL if they can't. FAST-READ-PIXARRAY - fill part of a pixarray from a buffer of card8s FAST-WRITE-PIXARRAY - copy part of a pixarray into an array of CARD8s FAST-COPY-PIXARRAY - copy part of a pixarray into another
This file contains some of the system dependent code for CLX TEXAS INSTRUMENTS INCORPORATED AUSTIN , TEXAS 78769 Copyright ( C ) 1987 Texas Instruments Incorporated . Texas Instruments Incorporated provides this software " as is " without (in-package :xlib) (proclaim '(declaration array-register)) The size of the output buffer . Must be a multiple of 4 . (defparameter *output-buffer-size* 8192) (defparameter *reply-timeout* nil) (progn (defconstant +word-0+ 1) (defconstant +word-1+ 0) (defconstant +long-0+ 3) (defconstant +long-1+ 2) (defconstant +long-2+ 1) (defconstant +long-3+ 0)) (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant +buffer-speed+ #+clx-debugging 1 #-clx-debugging 3 "Speed compiler option for buffer code.") (defconstant +buffer-safety+ #+clx-debugging 3 #-clx-debugging 0 "Safety compiler option for buffer code.") (defconstant +buffer-debug+ #+clx-debugging 2 #-clx-debugging 1 "Debug compiler option for buffer code>") (defun declare-bufmac () `(declare (optimize (speed ,+buffer-speed+) (safety ,+buffer-safety+) (debug ,+buffer-debug+)))) idea to make it here when + buffer - speed+ is 3 and + buffer - safety+ (defun declare-buffun () `(declare (optimize (speed ,+buffer-speed+) (safety ,+buffer-safety+) (debug ,+buffer-debug+))))) (declaim (inline card8->int8 int8->card8 card16->int16 int16->card16 card32->int32 int32->card32)) (progn (defun card8->int8 (x) (declare (type card8 x)) (declare (clx-values int8)) #.(declare-buffun) (the int8 (if (logbitp 7 x) (the int8 (- x #x100)) x))) (defun int8->card8 (x) (declare (type int8 x)) (declare (clx-values card8)) #.(declare-buffun) (the card8 (ldb (byte 8 0) x))) (defun card16->int16 (x) (declare (type card16 x)) (declare (clx-values int16)) #.(declare-buffun) (the int16 (if (logbitp 15 x) (the int16 (- x #x10000)) x))) (defun int16->card16 (x) (declare (type int16 x)) (declare (clx-values card16)) #.(declare-buffun) (the card16 (ldb (byte 16 0) x))) (defun card32->int32 (x) (declare (type card32 x)) (declare (clx-values int32)) #.(declare-buffun) (the int32 (if (logbitp 31 x) (the int32 (- x #x100000000)) x))) (defun int32->card32 (x) (declare (type int32 x)) (declare (clx-values card32)) #.(declare-buffun) (the card32 (ldb (byte 32 0) x))) ) (declaim (inline aref-card8 aset-card8 aref-int8 aset-int8)) (progn (defun aref-card8 (a i) (declare (type buffer-bytes a) (type array-index i)) (declare (clx-values card8)) #.(declare-buffun) (the card8 (aref a i))) (defun aset-card8 (v a i) (declare (type card8 v) (type buffer-bytes a) (type array-index i)) #.(declare-buffun) (setf (aref a i) v)) (defun aref-int8 (a i) (declare (type buffer-bytes a) (type array-index i)) (declare (clx-values int8)) #.(declare-buffun) (card8->int8 (aref a i))) (defun aset-int8 (v a i) (declare (type int8 v) (type buffer-bytes a) (type array-index i)) #.(declare-buffun) (setf (aref a i) (int8->card8 v))) ) (progn (defun aref-card16 (a i) (declare (type buffer-bytes a) (type array-index i)) (declare (clx-values card16)) #.(declare-buffun) (the card16 (logior (the card16 (ash (the card8 (aref a (index+ i +word-1+))) 8)) (the card8 (aref a (index+ i +word-0+)))))) (defun aset-card16 (v a i) (declare (type card16 v) (type buffer-bytes a) (type array-index i)) #.(declare-buffun) (setf (aref a (index+ i +word-1+)) (the card8 (ldb (byte 8 8) v)) (aref a (index+ i +word-0+)) (the card8 (ldb (byte 8 0) v))) v) (defun aref-int16 (a i) (declare (type buffer-bytes a) (type array-index i)) (declare (clx-values int16)) #.(declare-buffun) (the int16 (logior (the int16 (ash (the int8 (aref-int8 a (index+ i +word-1+))) 8)) (the card8 (aref a (index+ i +word-0+)))))) (defun aset-int16 (v a i) (declare (type int16 v) (type buffer-bytes a) (type array-index i)) #.(declare-buffun) (setf (aref a (index+ i +word-1+)) (the card8 (ldb (byte 8 8) v)) (aref a (index+ i +word-0+)) (the card8 (ldb (byte 8 0) v))) v) (defun aref-card32 (a i) (declare (type buffer-bytes a) (type array-index i)) (declare (clx-values card32)) #.(declare-buffun) (the card32 (logior (the card32 (ash (the card8 (aref a (index+ i +long-3+))) 24)) (the card29 (ash (the card8 (aref a (index+ i +long-2+))) 16)) (the card16 (ash (the card8 (aref a (index+ i +long-1+))) 8)) (the card8 (aref a (index+ i +long-0+)))))) (defun aset-card32 (v a i) (declare (type card32 v) (type buffer-bytes a) (type array-index i)) #.(declare-buffun) (setf (aref a (index+ i +long-3+)) (the card8 (ldb (byte 8 24) v)) (aref a (index+ i +long-2+)) (the card8 (ldb (byte 8 16) v)) (aref a (index+ i +long-1+)) (the card8 (ldb (byte 8 8) v)) (aref a (index+ i +long-0+)) (the card8 (ldb (byte 8 0) v))) v) (defun aref-int32 (a i) (declare (type buffer-bytes a) (type array-index i)) (declare (clx-values int32)) #.(declare-buffun) (the int32 (logior (the int32 (ash (the int8 (aref-int8 a (index+ i +long-3+))) 24)) (the card29 (ash (the card8 (aref a (index+ i +long-2+))) 16)) (the card16 (ash (the card8 (aref a (index+ i +long-1+))) 8)) (the card8 (aref a (index+ i +long-0+)))))) (defun aset-int32 (v a i) (declare (type int32 v) (type buffer-bytes a) (type array-index i)) #.(declare-buffun) (setf (aref a (index+ i +long-3+)) (the card8 (ldb (byte 8 24) v)) (aref a (index+ i +long-2+)) (the card8 (ldb (byte 8 16) v)) (aref a (index+ i +long-1+)) (the card8 (ldb (byte 8 8) v)) (aref a (index+ i +long-0+)) (the card8 (ldb (byte 8 0) v))) v) (defun aref-card29 (a i) (declare (type buffer-bytes a) (type array-index i)) (declare (clx-values card29)) #.(declare-buffun) (the card29 (logior (the card29 (ash (the card8 (aref a (index+ i +long-3+))) 24)) (the card29 (ash (the card8 (aref a (index+ i +long-2+))) 16)) (the card16 (ash (the card8 (aref a (index+ i +long-1+))) 8)) (the card8 (aref a (index+ i +long-0+)))))) (defun aset-card29 (v a i) (declare (type card29 v) (type buffer-bytes a) (type array-index i)) #.(declare-buffun) (setf (aref a (index+ i +long-3+)) (the card8 (ldb (byte 8 24) v)) (aref a (index+ i +long-2+)) (the card8 (ldb (byte 8 16) v)) (aref a (index+ i +long-1+)) (the card8 (ldb (byte 8 8) v)) (aref a (index+ i +long-0+)) (the card8 (ldb (byte 8 0) v))) v) ) (defsetf aref-card8 (a i) (v) `(aset-card8 ,v ,a ,i)) (defsetf aref-int8 (a i) (v) `(aset-int8 ,v ,a ,i)) (defsetf aref-card16 (a i) (v) `(aset-card16 ,v ,a ,i)) (defsetf aref-int16 (a i) (v) `(aset-int16 ,v ,a ,i)) (defsetf aref-card32 (a i) (v) `(aset-card32 ,v ,a ,i)) (defsetf aref-int32 (a i) (v) `(aset-int32 ,v ,a ,i)) (defsetf aref-card29 (a i) (v) `(aset-card29 ,v ,a ,i)) (defun rgb-val->card16 (value) (declare (type rgb-val value)) (declare (clx-values card16)) #.(declare-buffun) (the card16 (values (round (the rgb-val value) #.(/ 1.0s0 #xffff))))) (defun card16->rgb-val (value) (declare (type card16 value)) (declare (clx-values short-float)) #.(declare-buffun) Convert VALUE from card16 to float (the short-float (* (the card16 value) #.(/ 1.0s0 #xffff)))) (defun radians->int16 (value) (declare (type angle value)) (declare (clx-values int16)) #.(declare-buffun) (the int16 (values (round (the angle value) #.(float (/ pi 180.0s0 64.0s0) 0.0s0))))) (defun int16->radians (value) (declare (type int16 value)) (declare (clx-values short-float)) #.(declare-buffun) (the short-float (* (the int16 value) #.(coerce (/ pi 180.0 64.0) 'short-float)))) (declaim (inline char->card8 card8->char)) (macrolet ((char-translators () (let ((alist `( ,@`((#\Return . 13) (#\Linefeed . 10) (#\Rubout . 127) (#\Page . 12) (#\Tab . 9) (#\Backspace . 8) (#\Newline . 10) (#\Space . 32)) (#\! . 33) (#\" . 34) (#\# . 35) (#\$ . 36) (#\% . 37) (#\& . 38) (#\' . 39) (#\( . 40) (#\) . 41) (#\* . 42) (#\+ . 43) (#\, . 44) (#\- . 45) (#\. . 46) (#\/ . 47) (#\0 . 48) (#\1 . 49) (#\2 . 50) (#\3 . 51) (#\4 . 52) (#\5 . 53) (#\6 . 54) (#\7 . 55) (#\8 . 56) . 59 ) ( # \ < . 60 ) (#\= . 61) (#\> . 62) (#\? . 63) (#\@ . 64) (#\A . 65) (#\B . 66) (#\C . 67) (#\D . 68) (#\E . 69) (#\F . 70) (#\G . 71) (#\H . 72) (#\I . 73) (#\J . 74) (#\K . 75) (#\L . 76) (#\M . 77) (#\N . 78) (#\O . 79) (#\P . 80) (#\Q . 81) (#\R . 82) (#\S . 83) (#\T . 84) (#\U . 85) (#\V . 86) (#\W . 87) (#\X . 88) (#\Y . 89) (#\Z . 90) (#\[ . 91) (#\\ . 92) (#\] . 93) (#\^ . 94) (#\_ . 95) (#\` . 96) (#\a . 97) (#\b . 98) (#\c . 99) (#\d . 100) (#\e . 101) (#\f . 102) (#\g . 103) (#\h . 104) (#\i . 105) (#\j . 106) (#\k . 107) (#\l . 108) (#\m . 109) (#\n . 110) (#\o . 111) (#\p . 112) (#\q . 113) (#\r . 114) (#\s . 115) (#\t . 116) (#\u . 117) (#\v . 118) (#\w . 119) (#\x . 120) (#\y . 121) (#\z . 122) (#\{ . 123) (#\| . 124) (#\} . 125) (#\~ . 126)))) (cond ((dolist (pair alist nil) (when (not (= (char-code (car pair)) (cdr pair))) (return t))) `(progn (defconstant *char-to-card8-translation-table* ',(let ((array (make-array (let ((max-char-code 255)) (dolist (pair alist) (setq max-char-code (max max-char-code (char-code (car pair))))) (1+ max-char-code)) :element-type 'card8))) (dotimes (i (length array)) (setf (aref array i) (mod i 256))) (dolist (pair alist) (setf (aref array (char-code (car pair))) (cdr pair))) array)) (defconstant *card8-to-char-translation-table* ',(let ((array (make-array 256))) (dotimes (i (length array)) (setf (aref array i) (code-char i))) (dolist (pair alist) (setf (aref array (cdr pair)) (car pair))) array)) (progn (defun char->card8 (char) (declare (type base-char char)) #.(declare-buffun) (the card8 (aref (the (simple-array card8 (*)) *char-to-card8-translation-table*) (the array-index (char-code char))))) (defun card8->char (card8) (declare (type card8 card8)) #.(declare-buffun) (the base-char (or (aref (the simple-vector *card8-to-char-translation-table*) card8) (error "Invalid CHAR code ~D." card8)))) ) #+Genera (progn (defun char->card8 (char) (declare lt:(side-effects reader reducible)) (aref *char-to-card8-translation-table* (char-code char))) (defun card8->char (card8) (declare lt:(side-effects reader reducible)) (aref *card8-to-char-translation-table* card8)) ) (dotimes (i 256) (unless (= i (char->card8 (card8->char i))) (warn "The card8->char mapping is not invertible through char->card8. Info:~%~S" (list i (card8->char i) (char->card8 (card8->char i)))) (return nil))) (dotimes (i (length *char-to-card8-translation-table*)) (let ((char (code-char i))) (unless (eql char (card8->char (char->card8 char))) (warn "The char->card8 mapping is not invertible through card8->char. Info:~%~S" (list char (char->card8 char) (card8->char (char->card8 char)))) (return nil)))))) (t `(progn (defun char->card8 (char) (declare (type base-char char)) #.(declare-buffun) (the card8 (char-code char))) (defun card8->char (card8) (declare (type card8 card8)) #.(declare-buffun) (the base-char (code-char card8))) )))))) (char-translators)) Process Locking our own here , based on primitives . Holding - Lock is very similar to with - lock on The TI Explorer , and a little more efficient (defun make-process-lock (name) (ccl:make-lock name)) (defmacro holding-lock ((locator display &optional whostate &key timeout) &body body) (declare (ignore timeout display)) `(ccl:with-lock-grabbed (,locator ,whostate) ,@body)) (defmacro without-aborts (&body body) `(ccl:without-interrupts ,@body)) Caller guarantees that PROCESS - WAKEUP will be called after the predicate 's (defun process-block (whostate predicate &rest predicate-args) #+Ignore (declare (dynamic-extern predicate-args)) (apply #'ccl:process-wait whostate predicate predicate-args)) (declaim (inline process-wakeup)) (defun process-wakeup (process) (declare (ignore process)) nil) for calling PROCESS - WAKEUP . (declaim (inline current-process)) (defun current-process () ccl::*current-process*) (defmacro without-interrupts (&body body) `(ccl:without-interrupts ,@body)) CONDITIONAL - STORE : (defvar *conditional-store-lock* (ccl:make-lock "conditional store")) (defmacro conditional-store (place old-value new-value) `(ccl:with-lock-grabbed (*conditional-store-lock*) (cond ((eq ,place ,old-value) (setf ,place ,new-value) t)))) All I / O operations are done within a WRAP - BUF - OUTPUT macro . (defmacro wrap-buf-output ((buffer) &body body) `(unless (buffer-dead ,buffer) ,@body)) (defmacro wrap-buf-input ((buffer) &body body) (declare (ignore buffer)) `(progn ,@body)) OPEN - X - STREAM - create a stream for communicating to the appropriate X (defparameter ccl::*x-server-unix-socket-format-string* "/tmp/.X11-unix/X~d") (defun open-x-stream (host display protocol) (declare (ignore protocol)) (if (or (string= host "") (string= host "unix")) (ccl::make-socket :connect :active :address-family :file :remote-filename (format nil ccl::*x-server-unix-socket-format-string* display)) (ccl::make-socket :connect :active :remote-host host :remote-port (+ 6000 display)))) (defun buffer-read-default (display vector start end timeout) (declare (type display display) (type buffer-bytes vector) (type array-index start end) (type (or null (real 0 *)) timeout)) #.(declare-buffun) (let ((stream (display-input-stream display))) (declare (type (or null stream) stream)) (or (cond ((null stream)) ((listen stream) nil) ((and timeout (= timeout 0)) :timeout) ((buffer-input-wait-default display timeout))) (progn (ccl:stream-read-ivector stream vector start (- end start)) nil)))) (defun buffer-write-default (vector display start end) (declare (type buffer-bytes vector) (type display display) (type array-index start end)) #.(declare-buffun) (let ((stream (display-output-stream display))) (declare (type (or null stream) stream)) (unless (null stream) (ccl:stream-write-ivector stream vector start (- end start))) nil)) (defun buffer-force-output-default (display) (declare (type display display)) (let ((stream (display-output-stream display))) (declare (type (or null stream) stream)) (unless (null stream) (force-output stream)))) BUFFER - CLOSE - DEFAULT - close the X stream (defun buffer-close-default (display &key abort) (declare (type display display)) #.(declare-buffun) (let ((stream (display-output-stream display))) (declare (type (or null stream) stream)) (unless (null stream) (close stream :abort abort)))) BUFFER - INPUT - WAIT - DEFAULT - wait for for input to be available for the (defun buffer-input-wait-default (display timeout) (declare (type display display) (type (or null number) timeout)) (let ((stream (display-input-stream display))) (declare (type (or null stream) stream)) (cond ((null stream)) ((listen stream) nil) ((eql timeout 0) :timeout) (t (let* ((fd (ccl::stream-device stream :input)) (ticks (and timeout (floor (* timeout ccl::*ticks-per-second*))))) (if (ccl::process-input-wait fd ticks) nil :timeout)))))) (defun buffer-listen-default (display) (declare (type display display)) (let ((stream (display-input-stream display))) (declare (type (or null stream) stream)) (if (null stream) t (listen stream)))) WITH - STACK - LIST is used by WITH - STATE as a memory saving feature . (defmacro with-stack-list ((var &rest elements) &body body) SYNTAX : ( WITH - STACK - LIST ( var exp1 ... expN ) body ) Equivalent to ( LET ( ( var ( MAPCAR # ' EVAL ' ( exp1 ... expN ) ) ) ) body ) except that the list produced by MAPCAR resides on the stack and therefore DISAPPEARS when WITH - STACK - LIST is exited . `(let ((,var (list ,@elements))) (declare (type cons ,var) #+clx-ansi-common-lisp (dynamic-extent ,var)) ,@body)) (defmacro with-stack-list* ((var &rest elements) &body body) SYNTAX : ( WITH - STACK - LIST * ( var exp1 ... expN ) body ) Equivalent to ( LET ( ( var ( APPLY # ' LIST * ( MAPCAR # ' EVAL ' ( exp1 ... expN ) ) ) ) ) body ) except that the list produced by MAPCAR resides on the stack and therefore DISAPPEARS when WITH - STACK - LIST is exited . `(let ((,var (list* ,@elements))) (declare (type cons ,var) (dynamic-extent ,var)) ,@body)) (declaim (inline buffer-replace)) (defun buffer-replace (buf1 buf2 start1 end1 &optional (start2 0)) (declare (type buffer-bytes buf1 buf2) (type array-index start1 end1 start2)) (replace buf1 buf2 :start1 start1 :end1 end1 :start2 start2)) (defmacro with-gcontext-bindings ((gc saved-state indexes ts-index temp-mask temp-gc) &body body) (let ((local-state (gensym)) (resets nil)) (dolist (index indexes) (push `(setf (svref ,local-state ,index) (svref ,saved-state ,index)) resets)) `(unwind-protect (progn ,@body) (let ((,local-state (gcontext-local-state ,gc))) (declare (type gcontext-state ,local-state)) ,@resets (setf (svref ,local-state ,ts-index) 0)) (when ,temp-gc (restore-gcontext-temp-state ,gc ,temp-mask ,temp-gc)) (deallocate-gcontext-state ,saved-state)))) How much error detection should CLX do ? 1 . Do the equivalent of check - type on every argument . 2 . Simply report TYPE - ERROR . This eliminates overhead of all the format 3 . Do error checking only on arguments that are likely to have errors 4 . Do error checking only where not doing so may dammage the envirnment 5 . No extra error detection code . On 's , ASET may barf trying to expects a CARD16 , is is sufficient for CLX to check for integer , or t - Do the equivalent of checktype on every argument (defconstant +type-check?+ nil) good compiler support for TYPEP . The definitions for CARD32 , CARD16 , INT16 , etc . # # # This comment is a lie ! TYPE ? is really also used for run - time type (defmacro type? (object type) (if (not (constantp type)) `(typep ,object ,type) (progn (setq type (eval type)) (let ((predicate (assoc type '((drawable drawable-p) (window window-p) (pixmap pixmap-p) (cursor cursor-p) (font font-p) (gcontext gcontext-p) (colormap colormap-p) (null null) (integer integerp))))) (cond (predicate `(,(second predicate) ,object)) ((eq type 'generalized-boolean) (+type-check?+ `(locally (declare (optimize safety)) (typep ,object ',type))) (t `(typep ,object ',type))))))) (defun x-type-error (object type &optional error-string) (x-error 'x-type-error :datum object :expected-type type :type-string error-string)) Hack up KMP error signaling using zetalisp until the real thing comes (defun default-error-handler (display error-key &rest key-vals &key asynchronous &allow-other-keys) (declare (type generalized-boolean asynchronous) (dynamic-extent key-vals)) (if asynchronous (apply #'x-cerror "Ignore" error-key :display display :error-key error-key key-vals) (apply #'x-error error-key :display display :error-key error-key key-vals))) (defun x-error (condition &rest keyargs) (declare (dynamic-extent keyargs)) (apply #'error condition keyargs)) (defun x-cerror (proceed-format-string condition &rest keyargs) (declare (dynamic-extent keyargs)) (apply #'cerror proceed-format-string condition keyargs)) version 15 of error handling defines the syntax for define - condition to be : Where option is one of : ( : documentation doc - string ) (: conc - name symbol - or - string ) (define-condition x-error (error) ()) (defun host-address (host &optional (family :internet)) (declare (type stringable host) (type (or null (member :internet :decnet :chaos) card8) family)) (declare (clx-values list)) (ecase family ((:internet nil 0) (let* ((addr (ccl::host-as-inet-host host))) (cons :internet (list (ldb (byte 8 24) addr) (ldb (byte 8 16) addr) (ldb (byte 8 8) addr) (ldb (byte 8 0) addr))))))) (defmacro use-closures () nil) (defun clx-macroexpand (form env) (macroexpand form env)) Utilities (defun getenv (name) (ccl::getenv name)) (defun get-host-name () "Return the same hostname as gethostname(3) would" (machine-instance)) (defun homedir-file-pathname (name) (merge-pathnames (user-homedir-pathname) (pathname name))) DEFAULT - RESOURCES - PATHNAME - The pathname of the resources file to load if (defun default-resources-pathname () (homedir-file-pathname ".Xdefaults")) (defun resources-pathname () (or (let ((string (getenv "XENVIRONMENT"))) (and string (pathname string))) (homedir-file-pathname (concatenate 'string ".Xdefaults-" (get-host-name))))) (defun authority-pathname () (or (let ((xauthority (getenv "XAUTHORITY"))) (and xauthority (pathname xauthority))) (homedir-file-pathname ".Xauthority"))) this particular defaulting behaviour is typical to most Unices , I think (defun get-default-display (&optional display-name) "Parse the argument DISPLAY-NAME, or the environment variable $DISPLAY if it is NIL. Display names have the format [protocol/] [hostname] : [:] displaynumber [.screennumber] There are two special cases in parsing, to match that done in the Xlib C language bindings - If the hostname is ``unix'' or the empty string, any supplied protocol is ignored and a connection is made using the :local transport. - If a double colon separates hostname from displaynumber, the protocol is assumed to be decnet. Returns a list of (host display-number screen protocol)." (let* ((name (or display-name (getenv "DISPLAY") (error "DISPLAY environment variable is not set"))) (slash-i (or (position #\/ name) -1)) (colon-i (position #\: name :start (1+ slash-i))) (decnet-colon-p (eql (elt name (1+ colon-i)) #\:)) (host (subseq name (1+ slash-i) colon-i)) (dot-i (and colon-i (position #\. name :start colon-i))) (display (when colon-i (parse-integer name :start (if decnet-colon-p (+ colon-i 2) (1+ colon-i)) :end dot-i))) (screen (when dot-i (parse-integer name :start (1+ dot-i)))) (protocol (cond ((or (string= host "") (string-equal host "unix")) :local) (decnet-colon-p :decnet) ((> slash-i -1) (intern (string-upcase (subseq name 0 slash-i)) :keyword)) (t :internet)))) (list host (or display 0) (or screen 0) protocol))) GC stuff (defun gc-cleanup () (declare (special *event-free-list* *pending-command-free-list* *reply-buffer-free-lists* *gcontext-local-state-cache* *temp-gcontext-cache*)) (setq *event-free-list* nil) (setq *pending-command-free-list* nil) (when (boundp '*reply-buffer-free-lists*) (fill *reply-buffer-free-lists* nil)) (setq *gcontext-local-state-cache* nil) (setq *temp-gcontext-cache* nil) nil) (defun default-keysym-translate (display state object) (declare (type display display) (type card16 state) (type t object) (ignore display state) (clx-values t)) object) (deftype pixarray-1-element-type () 'bit) (deftype pixarray-4-element-type () '(unsigned-byte 4)) (deftype pixarray-8-element-type () '(unsigned-byte 8)) (deftype pixarray-16-element-type () '(unsigned-byte 16)) (deftype pixarray-24-element-type () '(unsigned-byte 24)) (deftype pixarray-32-element-type () '(unsigned-byte 32)) (deftype pixarray-1 () '(array pixarray-1-element-type (* *))) (deftype pixarray-4 () '(array pixarray-4-element-type (* *))) (deftype pixarray-8 () '(array pixarray-8-element-type (* *))) (deftype pixarray-16 () '(array pixarray-16-element-type (* *))) (deftype pixarray-24 () '(array pixarray-24-element-type (* *))) (deftype pixarray-32 () '(array pixarray-32-element-type (* *))) (deftype pixarray () '(or pixarray-1 pixarray-4 pixarray-8 pixarray-16 pixarray-24 pixarray-32)) (deftype bitmap () 'pixarray-1) (defmacro with-underlying-simple-vector ((variable element-type pixarray) &body body) (declare (ignore element-type)) `(let* ((,variable (ccl::array-data-and-offset ,pixarray))) ,@body)) READ - IMAGE - LOAD - BYTE is used to extract 1 and 4 bit pixels from CARD8s . (defmacro read-image-load-byte (size position integer) (unless +image-bit-lsb-first-p+ (setq position (- 7 position))) `(the (unsigned-byte ,size) (ldb (byte ,size ,position) (the card8 ,integer)))) READ - IMAGE - ASSEMBLE - BYTES is used to build 16 , 24 and 32 bit pixels from the appropriate number of CARD8s . (defmacro read-image-assemble-bytes (&rest bytes) (unless +image-byte-lsb-first-p+ (setq bytes (reverse bytes))) (let ((it (first bytes)) (count 0)) (dolist (byte (rest bytes)) (setq it `(dpb (the card8 ,byte) (byte 8 ,(incf count 8)) (the (unsigned-byte ,count) ,it)))) `(the (unsigned-byte ,(* (length bytes) 8)) ,it))) WRITE - IMAGE - LOAD - BYTE is used to extract a CARD8 from a 16 , 24 or 32 bit (defmacro write-image-load-byte (position integer integer-size) integer-size (unless +image-byte-lsb-first-p+ (setq position (- integer-size 8 position))) `(the card8 (ldb (byte 8 ,position) (the (unsigned-byte ,integer-size) ,integer)))) WRITE - IMAGE - ASSEMBLE - BYTES is used to build a CARD8 from 1 or 4 bit (defmacro write-image-assemble-bytes (&rest bytes) (unless +image-bit-lsb-first-p+ (setq bytes (reverse bytes))) (let ((size (floor 8 (length bytes))) (it (first bytes)) (count 0)) (dolist (byte (rest bytes)) (setq it `(dpb (the (unsigned-byte ,size) ,byte) (byte ,size ,(incf count size)) (the (unsigned-byte ,count) ,it)))) `(the card8 ,it))) If you can write fast routines that can read and write pixarrays out of a (defun fast-read-pixarray (bbuf boffset pixarray x y width height padded-bytes-per-line bits-per-pixel unit byte-lsb-first-p bit-lsb-first-p) (declare (ignore bbuf boffset pixarray x y width height padded-bytes-per-line bits-per-pixel unit byte-lsb-first-p bit-lsb-first-p)) nil) (defun fast-write-pixarray (bbuf boffset pixarray x y width height padded-bytes-per-line bits-per-pixel unit byte-lsb-first-p bit-lsb-first-p) (declare (ignore bbuf boffset pixarray x y width height padded-bytes-per-line bits-per-pixel unit byte-lsb-first-p bit-lsb-first-p)) nil) (defun fast-copy-pixarray (pixarray copy x y width height bits-per-pixel) (declare (ignore pixarray copy x y width height bits-per-pixel)) nil)
991c6c4bb191a4fafc228a19402d3e7a431c503b40712a40a99d546663453239
NetworkVerification/nv
InterpUtils.ml
open Nv_datastructures open Nv_lang (* Expression and operator interpreters *) (* matches p b is Some env if v matches p and None otherwise; assumes no repeated variables in pattern *) let rec matches p (v : Syntax.value) env : Syntax.value Env.t option = let open Syntax in match p, v.v with | PWild, _ -> Some env | PVar x, _ -> Some (Env.update env x v) | PUnit, VUnit -> Some env | PBool true, VBool true | PBool false, VBool false -> Some env | PInt i1, VInt i2 -> if Nv_datastructures.Integer.equal i1 i2 then Some env else None | PNode n1, VNode n2 -> if n1 = n2 then Some env else None | PEdge (p1, p2), VEdge (n1, n2) -> begin match matches p1 (vnode n1) env with | None -> None | Some env -> matches p2 (vnode n2) env end | PTuple ps, VTuple vs -> (* matches_list ps vs *) (match ps, vs with | [], [] -> Some env | p :: ps, v :: vs -> (match matches p v env with | None -> None | Some env -> matches (PTuple ps) (vtuple vs) env) | _, _ -> None) | POption None, VOption None -> Some env | POption (Some p), VOption (Some v) -> matches p v env | (PUnit | PBool _ | PInt _ | PTuple _ | POption _ | PNode _ | PEdge _), _ -> None | PRecord _, _ -> failwith "Record found during interpretation" ;; let rec match_branches_lst branches v env = match branches with | [] -> None | (p, e) :: branches -> (match matches p v env with | Some env' -> Some (env', e) | None -> match_branches_lst branches v env) ;; let rec val_to_pat v = let open Syntax in match v.v with | VInt i -> PInt i | VBool b -> PBool b | VOption (Some v) -> POption (Some (val_to_pat v)) | VOption None -> POption None | VTuple vs -> PTuple (BatList.map val_to_pat vs) | VRecord map -> PRecord (Collections.StringMap.map val_to_pat map) | VNode n -> PNode n | VEdge (n1, n2) -> PEdge (PNode n1, PNode n2) | VUnit -> PUnit | VMap _ | VClosure _ -> PWild ;; let rec match_branches branches v env = Syntax.iterBranches ( fun ( p , e ) - > Printf.printf " % s\n " ( Printing.pattern_to_string p ) ) branches ; * Printf.printf " val : % s\n " ( Printing.value_to_string v ) ; * Printf.printf "val: %s\n" (Printing.value_to_string v); *) match Syntax.lookUpPat (val_to_pat v) branches with | Found e -> Some (env, e) | Rest ls -> match_branches_lst ls v env ;; let build_env (env : Syntax.env) (free_vars : Nv_datastructures.Var.t BatSet.PSet.t) : Syntax.value BatSet.PSet.t = let base = BatSet.PSet.create Syntax.compare_values in BatSet.PSet.fold (fun v acc -> match Env.lookup_opt env.value v with | Some value -> BatSet.PSet.add value acc | None -> acc) free_vars base ;; let bddfunc_cache : bool Cudd.Mtbdd.t Collections.ExpEnvMap.t ref = ref Collections.ExpEnvMap.empty ;;
null
https://raw.githubusercontent.com/NetworkVerification/nv/aa48abcd1bf9d4b7167cfe83a94b44e446a636e8/src/lib/interpreter/InterpUtils.ml
ocaml
Expression and operator interpreters matches p b is Some env if v matches p and None otherwise; assumes no repeated variables in pattern matches_list ps vs
open Nv_datastructures open Nv_lang let rec matches p (v : Syntax.value) env : Syntax.value Env.t option = let open Syntax in match p, v.v with | PWild, _ -> Some env | PVar x, _ -> Some (Env.update env x v) | PUnit, VUnit -> Some env | PBool true, VBool true | PBool false, VBool false -> Some env | PInt i1, VInt i2 -> if Nv_datastructures.Integer.equal i1 i2 then Some env else None | PNode n1, VNode n2 -> if n1 = n2 then Some env else None | PEdge (p1, p2), VEdge (n1, n2) -> begin match matches p1 (vnode n1) env with | None -> None | Some env -> matches p2 (vnode n2) env end | PTuple ps, VTuple vs -> (match ps, vs with | [], [] -> Some env | p :: ps, v :: vs -> (match matches p v env with | None -> None | Some env -> matches (PTuple ps) (vtuple vs) env) | _, _ -> None) | POption None, VOption None -> Some env | POption (Some p), VOption (Some v) -> matches p v env | (PUnit | PBool _ | PInt _ | PTuple _ | POption _ | PNode _ | PEdge _), _ -> None | PRecord _, _ -> failwith "Record found during interpretation" ;; let rec match_branches_lst branches v env = match branches with | [] -> None | (p, e) :: branches -> (match matches p v env with | Some env' -> Some (env', e) | None -> match_branches_lst branches v env) ;; let rec val_to_pat v = let open Syntax in match v.v with | VInt i -> PInt i | VBool b -> PBool b | VOption (Some v) -> POption (Some (val_to_pat v)) | VOption None -> POption None | VTuple vs -> PTuple (BatList.map val_to_pat vs) | VRecord map -> PRecord (Collections.StringMap.map val_to_pat map) | VNode n -> PNode n | VEdge (n1, n2) -> PEdge (PNode n1, PNode n2) | VUnit -> PUnit | VMap _ | VClosure _ -> PWild ;; let rec match_branches branches v env = Syntax.iterBranches ( fun ( p , e ) - > Printf.printf " % s\n " ( Printing.pattern_to_string p ) ) branches ; * Printf.printf " val : % s\n " ( Printing.value_to_string v ) ; * Printf.printf "val: %s\n" (Printing.value_to_string v); *) match Syntax.lookUpPat (val_to_pat v) branches with | Found e -> Some (env, e) | Rest ls -> match_branches_lst ls v env ;; let build_env (env : Syntax.env) (free_vars : Nv_datastructures.Var.t BatSet.PSet.t) : Syntax.value BatSet.PSet.t = let base = BatSet.PSet.create Syntax.compare_values in BatSet.PSet.fold (fun v acc -> match Env.lookup_opt env.value v with | Some value -> BatSet.PSet.add value acc | None -> acc) free_vars base ;; let bddfunc_cache : bool Cudd.Mtbdd.t Collections.ExpEnvMap.t ref = ref Collections.ExpEnvMap.empty ;;
10c71d941de1c02bb3b3840838ff12b72cb4354d8c36aa6b14049663324a4ecd
robertluo/fun-map
fun_map.cljc
(ns robertluo.fun-map "fun-map Api" (:require [robertluo.fun-map.core :as core] [robertluo.fun-map.wrapper :as wrapper] #?(:clj [robertluo.fun-map.helper :as helper]))) (defn fun-map "Returns a new fun-map. A fun-map is a special map which will automatically *unwrap* a value if it's a wrapper when accessed by key. A wrapper is anything which wrapped a ordinary value inside. Many clojure data structures are wrapper, such as atom, ref, future, delay, agent etc. In fact, anything implements clojure.lang.IDRef interface is a wrapper. FuntionWrapper is another wrapper can be used in a fun-map, which wraps a function, it will be called with the fun-map itself as the argument. Map m is the underlying storage of a fun-map, fun-map does not change its property except accessing values. Options: - ::trace-fn An Effectful function for globally FunctionWrapper calling trace which accept key and value as its argument. Example: (fun-map {:a 35 :b (delay (println \"hello from b!\"))}" [m & {:keys [trace-fn keep-ref]}] (with-meta (core/delegate-map m wrapper/wrapper-entry) {::trace trace-fn ::wrapper/keep-ref keep-ref})) (defn fun-map? "If m is a fun-map" [m] (core/fun-map? m)) (comment (fun-map {:a 1 :b 5 :c (wrapper/fun-wrapper (fn [m _] (let [a (get m :a) b (get m :b)] (+ a b))))}) ) #?(:clj (defmacro fw "Returns a FunctionWrapper of an anonymous function defined by body. Since a FunctionWrapper's function will be called with the map itself as the argument, this macro using a map `arg-map` as its argument. It follows the same syntax of clojure's associative destructure. You may use `:keys`, `:as`, `:or` inside. Special key `:wrappers` specify additional wrappers of function wrapper: - `[]` for naive one, no cache, no trace. - default to specable cached traceable implementation. which supports special keys: - `:focus` A form that will be called to check if the function itself need to be called. It must be pure functional and very effecient. - `:trace` A trace function, if the value updated, it will be called with key and the function's return value. Special option `:par? true` will make dependencies accessing parallel. Example: (fw {:keys [a b] :as m :trace (fn [k v] (println k v)) :focus (select-keys m [:a :b])} (+ a b))" {:style/indent 1} [arg-map & body] (helper/make-fw-wrapper `wrapper/fun-wrapper [:trace :cache] arg-map body))) #?(:clj (defmethod helper/fw-impl :trace [{:keys [f options]}] `(wrapper/trace-wrapper ~f ~(:trace options)))) #?(:clj (defmethod helper/fw-impl :cache [{:keys [f options arg-map]}] (let [focus (when-let [focus (:focus options)] `(fn [~arg-map] ~focus))] `(wrapper/cache-wrapper ~f ~focus)))) #?(:clj (defmacro fnk "A shortcut for `fw` macro. Returns a simple FunctionWrapper which depends on `args` key of the fun-map, it will *focus* on the keys also." {:style/indent 1} [args & body] `(fw {:keys ~args :focus ~args} ~@body))) ;;;;;; life cycle map (defn touch "Forcefully evaluate all entries of a map and returns itself." [m] (doseq [[_ _] m] nil) m) (defprotocol Haltable "Life cycle protocol, signature just like java.io.Closeable, being a protocol gives user ability to extend" (halt! [this])) #?(:clj (extend-protocol Haltable java.io.Closeable (halt! [this] (.close this))) :cljs (extend-protocol Haltable core/DelegatedMap (halt! [this] (when-let [close-fn (some-> this meta ::core/close-fn)] (close-fn this))))) (defn life-cycle-map "returns a fun-map can be shutdown orderly. Any FunctionWrapper supports `Closeable` in this map will be considered as a component, its `close` method will be called in reversed order of its creation when the map itself closing. Notice only accessed components will be shutdown." [m] (let [components (atom []) trace-fn (fn [_ v] (when (satisfies? Haltable v) (swap! components conj v))) sys (fun-map m :trace-fn trace-fn) halt-fn (fn [_] (doseq [component (reverse @components)] (halt! component)))] (vary-meta sys assoc ::core/close-fn halt-fn))) Utilities (deftype CloseableValue [value close-fn] #?(:clj clojure.lang.IDeref :cljs IDeref) #?(:clj (deref [_] value) :cljs (-deref [_] value)) Haltable (halt! [_] (close-fn))) (defn closeable "Returns a wrapped plain value, which implements IDref and Closeable, the close-fn is an effectual function with no argument. When used inside a life cycle map, its close-fn when get called when closing the map." [r close-fn] (->CloseableValue r close-fn)) #?(:clj (defn lookup "Returns a ILookup object for calling f on k" [f] (reify clojure.lang.Associative (entryAt [this k] (clojure.lang.MapEntry. k (.valAt this k))) (valAt [_ k] (f k)) (valAt [this k not-found] (or (.valAt this k) not-found)))))
null
https://raw.githubusercontent.com/robertluo/fun-map/ea2d418dac2b77171f877c4d6fbc4d14d72ea04d/src/robertluo/fun_map.cljc
clojure
life cycle map
(ns robertluo.fun-map "fun-map Api" (:require [robertluo.fun-map.core :as core] [robertluo.fun-map.wrapper :as wrapper] #?(:clj [robertluo.fun-map.helper :as helper]))) (defn fun-map "Returns a new fun-map. A fun-map is a special map which will automatically *unwrap* a value if it's a wrapper when accessed by key. A wrapper is anything which wrapped a ordinary value inside. Many clojure data structures are wrapper, such as atom, ref, future, delay, agent etc. In fact, anything implements clojure.lang.IDRef interface is a wrapper. FuntionWrapper is another wrapper can be used in a fun-map, which wraps a function, it will be called with the fun-map itself as the argument. Map m is the underlying storage of a fun-map, fun-map does not change its property except accessing values. Options: - ::trace-fn An Effectful function for globally FunctionWrapper calling trace which accept key and value as its argument. Example: (fun-map {:a 35 :b (delay (println \"hello from b!\"))}" [m & {:keys [trace-fn keep-ref]}] (with-meta (core/delegate-map m wrapper/wrapper-entry) {::trace trace-fn ::wrapper/keep-ref keep-ref})) (defn fun-map? "If m is a fun-map" [m] (core/fun-map? m)) (comment (fun-map {:a 1 :b 5 :c (wrapper/fun-wrapper (fn [m _] (let [a (get m :a) b (get m :b)] (+ a b))))}) ) #?(:clj (defmacro fw "Returns a FunctionWrapper of an anonymous function defined by body. Since a FunctionWrapper's function will be called with the map itself as the argument, this macro using a map `arg-map` as its argument. It follows the same syntax of clojure's associative destructure. You may use `:keys`, `:as`, `:or` inside. Special key `:wrappers` specify additional wrappers of function wrapper: - `[]` for naive one, no cache, no trace. - default to specable cached traceable implementation. which supports special keys: - `:focus` A form that will be called to check if the function itself need to be called. It must be pure functional and very effecient. - `:trace` A trace function, if the value updated, it will be called with key and the function's return value. Special option `:par? true` will make dependencies accessing parallel. Example: (fw {:keys [a b] :as m :trace (fn [k v] (println k v)) :focus (select-keys m [:a :b])} (+ a b))" {:style/indent 1} [arg-map & body] (helper/make-fw-wrapper `wrapper/fun-wrapper [:trace :cache] arg-map body))) #?(:clj (defmethod helper/fw-impl :trace [{:keys [f options]}] `(wrapper/trace-wrapper ~f ~(:trace options)))) #?(:clj (defmethod helper/fw-impl :cache [{:keys [f options arg-map]}] (let [focus (when-let [focus (:focus options)] `(fn [~arg-map] ~focus))] `(wrapper/cache-wrapper ~f ~focus)))) #?(:clj (defmacro fnk "A shortcut for `fw` macro. Returns a simple FunctionWrapper which depends on `args` key of the fun-map, it will *focus* on the keys also." {:style/indent 1} [args & body] `(fw {:keys ~args :focus ~args} ~@body))) (defn touch "Forcefully evaluate all entries of a map and returns itself." [m] (doseq [[_ _] m] nil) m) (defprotocol Haltable "Life cycle protocol, signature just like java.io.Closeable, being a protocol gives user ability to extend" (halt! [this])) #?(:clj (extend-protocol Haltable java.io.Closeable (halt! [this] (.close this))) :cljs (extend-protocol Haltable core/DelegatedMap (halt! [this] (when-let [close-fn (some-> this meta ::core/close-fn)] (close-fn this))))) (defn life-cycle-map "returns a fun-map can be shutdown orderly. Any FunctionWrapper supports `Closeable` in this map will be considered as a component, its `close` method will be called in reversed order of its creation when the map itself closing. Notice only accessed components will be shutdown." [m] (let [components (atom []) trace-fn (fn [_ v] (when (satisfies? Haltable v) (swap! components conj v))) sys (fun-map m :trace-fn trace-fn) halt-fn (fn [_] (doseq [component (reverse @components)] (halt! component)))] (vary-meta sys assoc ::core/close-fn halt-fn))) Utilities (deftype CloseableValue [value close-fn] #?(:clj clojure.lang.IDeref :cljs IDeref) #?(:clj (deref [_] value) :cljs (-deref [_] value)) Haltable (halt! [_] (close-fn))) (defn closeable "Returns a wrapped plain value, which implements IDref and Closeable, the close-fn is an effectual function with no argument. When used inside a life cycle map, its close-fn when get called when closing the map." [r close-fn] (->CloseableValue r close-fn)) #?(:clj (defn lookup "Returns a ILookup object for calling f on k" [f] (reify clojure.lang.Associative (entryAt [this k] (clojure.lang.MapEntry. k (.valAt this k))) (valAt [_ k] (f k)) (valAt [this k not-found] (or (.valAt this k) not-found)))))
a3114c8dd6352bc08fcfec345d0f48f12e5b9f5069a1e250e9b51279eec14e47
clojure-dus/chess
chessboard.clj
(ns chess.movelogic.bitboard.chessboard (:use [chess.movelogic.bitboard bitoperations file-rank piece-attacks]) (:use [chess.movelogic.protocol :only [read-fen->map]])) (defrecord GameState [board turn rochade ^long r ^long n ^long b ^long q ^long k ^long p ^long R ^long N ^long B ^long Q ^long K ^long P ^long _ ^long whitepieces ^long blackpieces ^long allpieces ^long enpassent]) (def empty-board (map->GameState {:board (vec (repeat 64 :_)) :turn :w :rochade #{:K :Q :k :q } :r 0 :n 0 :b 0 :q 0 :k 0 :p 0 :R 0 :N 0 :B 0 :Q 0 :K 0 :P 0 :_ 0 :whitepieces 0 :blackpieces 0 :allpieces 0 :enpassent 0})) (defmacro thread-it [& [first-expr & rest-expr]] (if (empty? rest-expr) first-expr `(let [~'it ~first-expr] (thread-it ~@rest-expr)))) (defn set-piece [game-state piece dest] (thread-it game-state (update-in it [piece] bit-or (bit-set 0 dest)) (assoc-in it [:board dest] piece) (assoc-in it [:whitepieces] (reduce #(bit-or %1 (%2 it)) 0 [:R :N :B :Q :K :P])) (assoc-in it [:blackpieces] (reduce #(bit-or %1 (%2 it)) 0 [:r :n :b :q :k :p])) (assoc-in it [:allpieces] (bit-or (:whitepieces it) (:blackpieces it))))) (defn promote [game-state square before-piece new-piece] (-> game-state (update-in [before-piece] bit-xor (bit-set 0 square)) (set-piece new-piece square))) (defn move-piece [game-state piece from dest & data] (let [captured (get-in game-state [:board dest]) check-promotion (fn[game-state] (if-let [promotion (first data)] (promote game-state dest piece promotion) game-state))] (-> game-state (assoc-in [:board from] :_) (update-in [piece] bit-xor (bit-set 0 from)) (assoc-in [captured] (bit-xor (captured game-state) (bit-set 0 dest))) (set-piece piece dest) (check-promotion)))) (defn create-board-fn [game-state coll] (reduce #(set-piece %1 (first %2) (second %2)) game-state coll)) (def initial-board (create-board-fn empty-board (list [:r 63] [:n 62] [:b 61] [:q 59] [:k 60] [:b 58] [:n 57] [:r 56] [:p 55] [:p 54] [:p 53] [:p 52] [:p 51] [:p 50] [:p 49] [:p 48] [:P 15] [:P 14] [:P 13] [:P 12] [:P 11] [:P 10] [:P 9] [:P 8] [:R 7] [:N 6] [:B 5] [:K 4] [:Q 3] [:B 2] [:N 1] [:R 0]))) (defn read-fen [fen-str] (let [other (read-fen->map fen-str) squares (flatten (reverse (:board other))) squares (map-indexed vector squares) squares (map reverse squares)] (assoc (create-board-fn empty-board squares) :turn (:turn other) :rochade (:rochade other)))) (defn ^Long pieces-by-turn [game-state] (if (= (:turn game-state) :w) (:whitepieces game-state) (:blackpieces game-state))) (defn print-board [game-state] (println "----- bitmap version -----") (print-board-vector (:board game-state)))
null
https://raw.githubusercontent.com/clojure-dus/chess/7eb0e5bf15290f520f31e7eb3f2b7742c7f27729/src/chess/movelogic/bitboard/chessboard.clj
clojure
(ns chess.movelogic.bitboard.chessboard (:use [chess.movelogic.bitboard bitoperations file-rank piece-attacks]) (:use [chess.movelogic.protocol :only [read-fen->map]])) (defrecord GameState [board turn rochade ^long r ^long n ^long b ^long q ^long k ^long p ^long R ^long N ^long B ^long Q ^long K ^long P ^long _ ^long whitepieces ^long blackpieces ^long allpieces ^long enpassent]) (def empty-board (map->GameState {:board (vec (repeat 64 :_)) :turn :w :rochade #{:K :Q :k :q } :r 0 :n 0 :b 0 :q 0 :k 0 :p 0 :R 0 :N 0 :B 0 :Q 0 :K 0 :P 0 :_ 0 :whitepieces 0 :blackpieces 0 :allpieces 0 :enpassent 0})) (defmacro thread-it [& [first-expr & rest-expr]] (if (empty? rest-expr) first-expr `(let [~'it ~first-expr] (thread-it ~@rest-expr)))) (defn set-piece [game-state piece dest] (thread-it game-state (update-in it [piece] bit-or (bit-set 0 dest)) (assoc-in it [:board dest] piece) (assoc-in it [:whitepieces] (reduce #(bit-or %1 (%2 it)) 0 [:R :N :B :Q :K :P])) (assoc-in it [:blackpieces] (reduce #(bit-or %1 (%2 it)) 0 [:r :n :b :q :k :p])) (assoc-in it [:allpieces] (bit-or (:whitepieces it) (:blackpieces it))))) (defn promote [game-state square before-piece new-piece] (-> game-state (update-in [before-piece] bit-xor (bit-set 0 square)) (set-piece new-piece square))) (defn move-piece [game-state piece from dest & data] (let [captured (get-in game-state [:board dest]) check-promotion (fn[game-state] (if-let [promotion (first data)] (promote game-state dest piece promotion) game-state))] (-> game-state (assoc-in [:board from] :_) (update-in [piece] bit-xor (bit-set 0 from)) (assoc-in [captured] (bit-xor (captured game-state) (bit-set 0 dest))) (set-piece piece dest) (check-promotion)))) (defn create-board-fn [game-state coll] (reduce #(set-piece %1 (first %2) (second %2)) game-state coll)) (def initial-board (create-board-fn empty-board (list [:r 63] [:n 62] [:b 61] [:q 59] [:k 60] [:b 58] [:n 57] [:r 56] [:p 55] [:p 54] [:p 53] [:p 52] [:p 51] [:p 50] [:p 49] [:p 48] [:P 15] [:P 14] [:P 13] [:P 12] [:P 11] [:P 10] [:P 9] [:P 8] [:R 7] [:N 6] [:B 5] [:K 4] [:Q 3] [:B 2] [:N 1] [:R 0]))) (defn read-fen [fen-str] (let [other (read-fen->map fen-str) squares (flatten (reverse (:board other))) squares (map-indexed vector squares) squares (map reverse squares)] (assoc (create-board-fn empty-board squares) :turn (:turn other) :rochade (:rochade other)))) (defn ^Long pieces-by-turn [game-state] (if (= (:turn game-state) :w) (:whitepieces game-state) (:blackpieces game-state))) (defn print-board [game-state] (println "----- bitmap version -----") (print-board-vector (:board game-state)))
e811c771ef08983d51cb27b7c644059db26be77b453c805bb21f22db25523255
clojurewerkz/ogre
branch_test.clj
(ns clojurewerkz.ogre.suite.branch-test (:refer-clojure :exclude [and count drop filter group-by key key identity iterate loop map max min next not or range repeat reverse sort shuffle]) (:require [clojurewerkz.ogre.core :refer :all]) (:import (org.apache.tinkerpop.gremlin.structure Vertex) (org.apache.tinkerpop.gremlin.process.traversal Traverser P) (org.apache.tinkerpop.gremlin.process.traversal.step TraversalOptionParent$Pick))) (defn get_g_V_branchXlabel_eq_person__a_bX_optionXa__ageX_optionXb__langX_optionXb__nameX "g.V().branch(v -> v.get().label().equals('person') ? 'a' : 'b') .option('a', values('age')) .option('b', values('lang')) .option('b', values('name'))" [g] (traverse g (V) (branch (fn [^Vertex v] (if (.equals ^String (.label ^Vertex (.get ^Traverser v)) "person") "a" "b"))) (option "a" (__ (values :age))) (option "b" (__ (values :lang))) (option "b" (__ (values :name))))) (defn get_g_V_branchXlabel_isXpersonX_countX_optionX1__ageX_optionX0__langX_optionX0__nameX "g.V().branch(label().is('person').count()) .option(1L, values('age')) .option(0L, values('lang')) .option(0L, values('name'))" [g] (traverse g (V) (branch (__ (label) (is :person) (count))) (option (long 1) (__ (values :age))) (option (long 0) (__ (values :lang))) (option (long 0) (__ (values :name))))) (defn get_g_V_branchXlabel_isXpersonX_countX_optionX1__ageX_optionX0__langX_optionX0__nameX_optionXany__labelX "g.V().branch(label().is('person').count()) .option(1L, values('age')) .option(0L, values('lang')) .option(0L, values('name')) .option(any, label())" [g] (traverse g (V) (branch (__ (label) (is :person) (count))) (option (long 1) (__ (values :age))) (option (long 0) (__ (values :lang))) (option (long 0) (__ (values :name))) (option (TraversalOptionParent$Pick/any) (__ (label))))) (defn get_g_V_branchXageX_optionXltX30X__youngX_optionXgtX30X__oldX_optionXnone__on_the_edgeX "g.V().hasLabel('person'). branch(values('age')). option(lt(30), constant('young')). option(gt(30), constant('old')). option(none, constant('on the edge'))" [g] 7 (traverse g (V) (has-label :person) (branch (__ (values :age))) (option (P/lt 30) (__ (constant "young"))) (option (P/gt 30) (__ (constant "old"))) (option (TraversalOptionParent$Pick/none) (__ (constant "on the edge"))))) (defn get_g_V_branchXidentityX_optionXhasLabelXsoftwareX__inXcreatedX_name_order_foldX_optionXhasXname_vadasX__ageX_optionXneqX123X__bothE_countX "g.V().branch(identity()). option(hasLabel('software'), __.in('created').values('name').order().fold()). option(has('name','vadas'), values('age')). option(neq(123), bothE().count())" [g] 7 (traverse g (V) (branch (__ (identity))) (option (__ (has-label :software)) (__ (in :created) (values :name) (order) (fold))) (option (__ (has :name "vadas")) (__ (values :age))) (option (P/neq 123) (__ (bothE) (count)))))
null
https://raw.githubusercontent.com/clojurewerkz/ogre/cfc5648881d509a55f8a951e01d7b2a166e71d17/test/clojure/clojurewerkz/ogre/suite/branch_test.clj
clojure
(ns clojurewerkz.ogre.suite.branch-test (:refer-clojure :exclude [and count drop filter group-by key key identity iterate loop map max min next not or range repeat reverse sort shuffle]) (:require [clojurewerkz.ogre.core :refer :all]) (:import (org.apache.tinkerpop.gremlin.structure Vertex) (org.apache.tinkerpop.gremlin.process.traversal Traverser P) (org.apache.tinkerpop.gremlin.process.traversal.step TraversalOptionParent$Pick))) (defn get_g_V_branchXlabel_eq_person__a_bX_optionXa__ageX_optionXb__langX_optionXb__nameX "g.V().branch(v -> v.get().label().equals('person') ? 'a' : 'b') .option('a', values('age')) .option('b', values('lang')) .option('b', values('name'))" [g] (traverse g (V) (branch (fn [^Vertex v] (if (.equals ^String (.label ^Vertex (.get ^Traverser v)) "person") "a" "b"))) (option "a" (__ (values :age))) (option "b" (__ (values :lang))) (option "b" (__ (values :name))))) (defn get_g_V_branchXlabel_isXpersonX_countX_optionX1__ageX_optionX0__langX_optionX0__nameX "g.V().branch(label().is('person').count()) .option(1L, values('age')) .option(0L, values('lang')) .option(0L, values('name'))" [g] (traverse g (V) (branch (__ (label) (is :person) (count))) (option (long 1) (__ (values :age))) (option (long 0) (__ (values :lang))) (option (long 0) (__ (values :name))))) (defn get_g_V_branchXlabel_isXpersonX_countX_optionX1__ageX_optionX0__langX_optionX0__nameX_optionXany__labelX "g.V().branch(label().is('person').count()) .option(1L, values('age')) .option(0L, values('lang')) .option(0L, values('name')) .option(any, label())" [g] (traverse g (V) (branch (__ (label) (is :person) (count))) (option (long 1) (__ (values :age))) (option (long 0) (__ (values :lang))) (option (long 0) (__ (values :name))) (option (TraversalOptionParent$Pick/any) (__ (label))))) (defn get_g_V_branchXageX_optionXltX30X__youngX_optionXgtX30X__oldX_optionXnone__on_the_edgeX "g.V().hasLabel('person'). branch(values('age')). option(lt(30), constant('young')). option(gt(30), constant('old')). option(none, constant('on the edge'))" [g] 7 (traverse g (V) (has-label :person) (branch (__ (values :age))) (option (P/lt 30) (__ (constant "young"))) (option (P/gt 30) (__ (constant "old"))) (option (TraversalOptionParent$Pick/none) (__ (constant "on the edge"))))) (defn get_g_V_branchXidentityX_optionXhasLabelXsoftwareX__inXcreatedX_name_order_foldX_optionXhasXname_vadasX__ageX_optionXneqX123X__bothE_countX "g.V().branch(identity()). option(hasLabel('software'), __.in('created').values('name').order().fold()). option(has('name','vadas'), values('age')). option(neq(123), bothE().count())" [g] 7 (traverse g (V) (branch (__ (identity))) (option (__ (has-label :software)) (__ (in :created) (values :name) (order) (fold))) (option (__ (has :name "vadas")) (__ (values :age))) (option (P/neq 123) (__ (bothE) (count)))))
aeb00f369b5ba92a9d7b6f5fc16478202ed8cb314acd850d70344dc5e5540d9c
project-fifo/vmwebadm
del.cljs
(ns server.keys.del (:use [server.utils :only [clj->js prn-js clj->json transform-keys]]) (:require [server.storage :as storage] [server.http :as http])) (defn handle [resource request response account id] (storage/init) (swap! storage/data update-in [:users account :keys] #(dissoc % id)) (storage/save) (http/ret response {"result" "ok"}))
null
https://raw.githubusercontent.com/project-fifo/vmwebadm/55d83bbc0ac6db8ea1d784c73d91bf4f228fa04a/src/server/keys/del.cljs
clojure
(ns server.keys.del (:use [server.utils :only [clj->js prn-js clj->json transform-keys]]) (:require [server.storage :as storage] [server.http :as http])) (defn handle [resource request response account id] (storage/init) (swap! storage/data update-in [:users account :keys] #(dissoc % id)) (storage/save) (http/ret response {"result" "ok"}))
8d8f299d0b5bfeb771d8992bf6e2ad4d8a98315645ab4c86986549a055e50ac3
sbcl/sbcl
cell.lisp
;;;; the VM definition of various primitive memory access VOPs for the ARM This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB-VM") ;;;; Data object ref/set stuff. (define-vop (slot) (:args (object :scs (descriptor-reg))) (:info name offset lowtag) (:ignore name) (:results (result :scs (descriptor-reg any-reg))) (:generator 1 (loadw result object offset lowtag))) (define-vop (set-slot) (:args (object :scs (descriptor-reg)) (value :scs (descriptor-reg any-reg))) (:info name offset lowtag) (:ignore name) (:results) (:generator 1 (storew value object offset lowtag))) ;;;; Symbol hacking VOPs: ;;; The compiler likes to be able to directly SET symbols. ;;; (define-vop (set cell-set) (:variant symbol-value-slot other-pointer-lowtag)) ;;; Do a cell ref with an error check for being unbound. ;;; (define-vop (checked-cell-ref) (:args (object :scs (descriptor-reg) :target obj-temp)) (:results (value :scs (descriptor-reg any-reg))) (:policy :fast-safe) (:vop-var vop) (:save-p :compute-only) (:temporary (:scs (descriptor-reg) :from (:argument 0)) obj-temp)) With Symbol - Value , we check that the value is n't the trap object . ;;; (define-vop (symbol-value checked-cell-ref) (:translate symbol-value) (:generator 9 (move obj-temp object) (loadw value obj-temp symbol-value-slot other-pointer-lowtag) (let ((err-lab (generate-error-code vop 'unbound-symbol-error obj-temp))) (inst cmp value unbound-marker-widetag) (inst b :eq err-lab)))) ;;; Like CHECKED-CELL-REF, only we are a predicate to see if the cell is bound. (define-vop (boundp) (:args (object :scs (descriptor-reg))) (:conditional) (:info target not-p) (:policy :fast-safe) (:temporary (:scs (descriptor-reg)) value) (:translate boundp) (:generator 9 (loadw value object symbol-value-slot other-pointer-lowtag) (inst cmp value unbound-marker-widetag) (inst b (if not-p :eq :ne) target))) (define-vop (fast-symbol-value cell-ref) (:variant symbol-value-slot other-pointer-lowtag) (:policy :fast) (:translate symbol-value)) (define-vop (symbol-hash) (:policy :fast-safe) (:translate symbol-hash) (:args (symbol :scs (descriptor-reg))) (:temporary (:scs (non-descriptor-reg)) temp) (:results (res :scs (any-reg))) (:result-types positive-fixnum) (:generator 2 The symbol - hash slot of NIL holds NIL because it is also the car slot , so we have to strip off the two low bits to make sure ;; it is a fixnum. The lowtag selection magic that is required to ensure this is explained in the comment in objdef.lisp (loadw temp symbol symbol-hash-slot other-pointer-lowtag) (inst bic res temp fixnum-tag-mask))) ;;; On unithreaded builds these are just copies of the non-global versions. (define-vop (%set-symbol-global-value set)) (define-vop (symbol-global-value symbol-value) (:translate symbol-global-value)) (define-vop (fast-symbol-global-value fast-symbol-value) (:translate symbol-global-value)) ;;;; Fdefinition (fdefn) objects. (define-vop (fdefn-fun cell-ref) (:variant fdefn-fun-slot other-pointer-lowtag)) (define-vop (safe-fdefn-fun) (:translate safe-fdefn-fun) (:policy :fast-safe) (:args (object :scs (descriptor-reg) :target obj-temp)) (:results (value :scs (descriptor-reg any-reg))) (:vop-var vop) (:save-p :compute-only) (:temporary (:scs (descriptor-reg) :from (:argument 0)) obj-temp) (:generator 10 (move obj-temp object) (loadw value obj-temp fdefn-fun-slot other-pointer-lowtag) (inst cmp value null-tn) (let ((err-lab (generate-error-code vop 'undefined-fun-error obj-temp))) (inst b :eq err-lab)))) (define-vop (set-fdefn-fun) (:policy :fast-safe) (:translate (setf fdefn-fun)) (:args (function :scs (descriptor-reg) :target result) (fdefn :scs (descriptor-reg))) (:temporary (:scs (interior-reg)) lip) (:temporary (:scs (non-descriptor-reg)) type) (:results (result :scs (descriptor-reg))) (:generator 38 (let ((closure-tramp-fixup (gen-label))) (assemble (:elsewhere) (emit-label closure-tramp-fixup) (inst word (make-fixup 'closure-tramp :assembly-routine))) (load-type type function (- fun-pointer-lowtag)) (inst cmp type simple-fun-widetag) (inst mov :eq lip function) (inst load-from-label :ne lip lip closure-tramp-fixup) (storew lip fdefn fdefn-raw-addr-slot other-pointer-lowtag) (storew function fdefn fdefn-fun-slot other-pointer-lowtag) (move result function)))) (define-vop (fdefn-makunbound) (:policy :fast-safe) (:translate fdefn-makunbound) (:args (fdefn :scs (descriptor-reg))) (:temporary (:scs (non-descriptor-reg)) temp) (:temporary (:scs (interior-reg)) lip) (:generator 38 (let ((undefined-tramp-fixup (gen-label))) (assemble (:elsewhere) (emit-label undefined-tramp-fixup) (inst word (make-fixup 'undefined-tramp :assembly-routine))) (storew null-tn fdefn fdefn-fun-slot other-pointer-lowtag) (inst load-from-label temp lip undefined-tramp-fixup) (storew temp fdefn fdefn-raw-addr-slot other-pointer-lowtag)))) ;;;; Binding and Unbinding. BIND -- Establish VAL as a binding for SYMBOL . Save the old value and ;;; the symbol on the binding stack and stuff the new value into the ;;; symbol. (define-vop (dynbind) (:args (val :scs (any-reg descriptor-reg)) (symbol :scs (descriptor-reg))) (:temporary (:scs (descriptor-reg)) value-temp) (:temporary (:scs (any-reg)) bsp-temp) (:generator 5 (loadw value-temp symbol symbol-value-slot other-pointer-lowtag) (load-symbol-value bsp-temp *binding-stack-pointer*) (inst add bsp-temp bsp-temp (* 2 n-word-bytes)) (store-symbol-value bsp-temp *binding-stack-pointer*) (storew value-temp bsp-temp (- binding-value-slot binding-size)) (storew symbol bsp-temp (- binding-symbol-slot binding-size)) (storew val symbol symbol-value-slot other-pointer-lowtag))) (define-vop (unbind) (:temporary (:scs (descriptor-reg)) symbol value) (:temporary (:scs (any-reg)) bsp-temp) (:temporary (:scs (any-reg)) zero-temp) (:generator 0 (inst mov zero-temp 0) (load-symbol-value bsp-temp *binding-stack-pointer*) (loadw symbol bsp-temp (- binding-symbol-slot binding-size)) (loadw value bsp-temp (- binding-value-slot binding-size)) (storew value symbol symbol-value-slot other-pointer-lowtag) (storew zero-temp bsp-temp (- binding-symbol-slot binding-size)) (storew zero-temp bsp-temp (- binding-value-slot binding-size)) (inst sub bsp-temp bsp-temp (* 2 n-word-bytes)) (store-symbol-value bsp-temp *binding-stack-pointer*))) (define-vop (unbind-to-here) (:args (arg :scs (descriptor-reg any-reg) :target where)) (:temporary (:scs (any-reg) :from (:argument 0)) where) (:temporary (:scs (descriptor-reg)) symbol value) (:temporary (:scs (any-reg)) bsp-temp zero-temp) (:generator 0 (load-symbol-value bsp-temp *binding-stack-pointer*) (inst mov zero-temp 0) (move where arg) (inst cmp where bsp-temp) (inst b :eq DONE) LOOP (loadw symbol bsp-temp (- binding-symbol-slot binding-size)) (inst cmp symbol 0) (loadw value bsp-temp (- binding-value-slot binding-size) 0 :ne) (storew value symbol symbol-value-slot other-pointer-lowtag :ne) (storew zero-temp bsp-temp (- binding-symbol-slot binding-size) 0 :ne) (storew zero-temp bsp-temp (- binding-value-slot binding-size)) (inst sub bsp-temp bsp-temp (* 2 n-word-bytes)) (inst cmp where bsp-temp) (inst b :ne LOOP) DONE (store-symbol-value bsp-temp *binding-stack-pointer*))) ;;;; Closure indexing. (define-full-reffer closure-index-ref * closure-info-offset fun-pointer-lowtag (descriptor-reg any-reg) * %closure-index-ref) (define-full-setter %closure-index-set * closure-info-offset fun-pointer-lowtag (descriptor-reg any-reg null) * %closure-index-set) (define-full-reffer funcallable-instance-info * funcallable-instance-info-offset fun-pointer-lowtag (descriptor-reg any-reg) * %funcallable-instance-info) (define-vop (closure-ref) (:args (object :scs (descriptor-reg))) (:results (value :scs (descriptor-reg any-reg))) (:info offset) (:generator 4 (loadw value object (+ closure-info-offset offset) fun-pointer-lowtag))) (define-vop (closure-init) (:args (object :scs (descriptor-reg)) (value :scs (descriptor-reg any-reg))) (:info offset) (:generator 4 (storew value object (+ closure-info-offset offset) fun-pointer-lowtag))) (define-vop (closure-init-from-fp) (:args (object :scs (descriptor-reg))) (:info offset) (:generator 4 (storew cfp-tn object (+ closure-info-offset offset) fun-pointer-lowtag))) ;;;; Value Cell hackery. (define-vop (value-cell-ref cell-ref) (:variant value-cell-value-slot other-pointer-lowtag)) (define-vop (value-cell-set cell-set) (:variant value-cell-value-slot other-pointer-lowtag)) ;;;; Instance hackery: (define-vop () (:policy :fast-safe) (:translate %instance-length) (:args (struct :scs (descriptor-reg))) (:results (res :scs (unsigned-reg))) (:result-types positive-fixnum) (:generator 4 (loadw res struct 0 instance-pointer-lowtag) (inst mov res (lsr res instance-length-shift)))) (define-full-reffer instance-index-ref * instance-slots-offset instance-pointer-lowtag (descriptor-reg any-reg) * %instance-ref) (define-full-setter instance-index-set * instance-slots-offset instance-pointer-lowtag (descriptor-reg any-reg null) * %instance-set) ;;;; Code object frobbing. (define-full-reffer code-header-ref * 0 other-pointer-lowtag (descriptor-reg any-reg) * code-header-ref) (define-vop (code-header-set) (:translate code-header-set) (:policy :fast-safe) (:args (object :scs (descriptor-reg)) (index :scs (any-reg)) (value :scs (any-reg descriptor-reg))) (:arg-types * tagged-num *) (:temporary (:scs (non-descriptor-reg)) temp #+gencgc card) #+gencgc (:temporary (:scs (interior-reg)) lip) #+gencgc (:temporary (:sc non-descriptor-reg) pa-flag) (:generator 10 #+cheneygc (progn (inst sub temp index other-pointer-lowtag) (inst str value (@ object temp))) #+gencgc (let ((mask-fixup-label (gen-label)) (table-fixup-label (gen-label))) (inst load-from-label temp lip mask-fixup-label) (inst ldr temp (@ temp)) (inst ldr temp (@ temp)) (pseudo-atomic (pa-flag) ;; Compute card mark index (inst mov card (lsr object gencgc-card-shift)) (inst and card card temp) ;; Load mark table base (inst load-from-label temp lip table-fixup-label) (inst ldr temp (@ temp)) (inst ldr temp (@ temp)) ;; Touch the card mark byte. (inst strb null-tn (@ temp card)) ;; set 'written' flag in the code header If two threads get here at the same time , they 'll write the same byte . (let ((byte (- #+little-endian 3 other-pointer-lowtag))) (inst ldrb temp (@ object byte)) (inst orr temp temp #x40) (inst strb temp (@ object byte))) (inst sub temp index other-pointer-lowtag) (inst str value (@ object temp))) (assemble (:elsewhere) (emit-label mask-fixup-label) (inst word (make-fixup "gc_card_table_mask" :foreign-dataref)) (emit-label table-fixup-label) (inst word (make-fixup "gc_card_mark" :foreign-dataref)))))) ;;;; raw instance slot accessors (macrolet ((define-raw-slot-vops (name ref-inst set-inst value-primtype value-sc &key use-lip (move-macro 'move)) (labels ((emit-generator (instruction move-result) `((inst add offset index (- (* instance-slots-offset n-word-bytes) instance-pointer-lowtag)) ,@(if use-lip `((inst add lip object offset) (inst ,instruction value (@ lip))) `((inst ,instruction value (@ object offset)))) ,@(when move-result `((,move-macro result value)))))) `(progn (define-vop () (:translate ,(symbolicate "%RAW-INSTANCE-REF/" name)) (:policy :fast-safe) (:args (object :scs (descriptor-reg)) (index :scs (any-reg))) (:arg-types * positive-fixnum) (:results (value :scs (,value-sc))) (:result-types ,value-primtype) (:temporary (:scs (non-descriptor-reg)) offset) ,@(when use-lip '((:temporary (:scs (interior-reg)) lip))) (:generator 5 ,@(emit-generator ref-inst nil))) (define-vop () (:translate ,(symbolicate "%RAW-INSTANCE-SET/" name)) (:policy :fast-safe) (:args (object :scs (descriptor-reg)) (index :scs (any-reg)) (value :scs (,value-sc))) (:arg-types * positive-fixnum ,value-primtype) (:temporary (:scs (non-descriptor-reg)) offset) ,@(when use-lip '((:temporary (:scs (interior-reg)) lip))) (:generator 5 ,@(emit-generator set-inst nil))))))) (define-raw-slot-vops word ldr str unsigned-num unsigned-reg) (define-raw-slot-vops signed-word ldr str signed-num signed-reg) (define-raw-slot-vops single flds fsts single-float single-reg :use-lip t :move-macro move-single) (define-raw-slot-vops double fldd fstd double-float double-reg :use-lip t :move-macro move-double) (define-raw-slot-vops complex-single load-complex-single store-complex-single complex-single-float complex-single-reg :use-lip t :move-macro move-complex-single) (define-raw-slot-vops complex-double load-complex-double store-complex-double complex-double-float complex-double-reg :use-lip t :move-macro move-complex-double))
null
https://raw.githubusercontent.com/sbcl/sbcl/dfbd2f7cb1f0fbca276c8db3383d9b147725a49c/src/compiler/arm/cell.lisp
lisp
the VM definition of various primitive memory access VOPs for the more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. Data object ref/set stuff. Symbol hacking VOPs: The compiler likes to be able to directly SET symbols. Do a cell ref with an error check for being unbound. Like CHECKED-CELL-REF, only we are a predicate to see if the cell is bound. it is a fixnum. The lowtag selection magic that is required to On unithreaded builds these are just copies of the non-global versions. Fdefinition (fdefn) objects. Binding and Unbinding. the symbol on the binding stack and stuff the new value into the symbol. Closure indexing. Value Cell hackery. Instance hackery: Code object frobbing. Compute card mark index Load mark table base Touch the card mark byte. set 'written' flag in the code header raw instance slot accessors
ARM This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB-VM") (define-vop (slot) (:args (object :scs (descriptor-reg))) (:info name offset lowtag) (:ignore name) (:results (result :scs (descriptor-reg any-reg))) (:generator 1 (loadw result object offset lowtag))) (define-vop (set-slot) (:args (object :scs (descriptor-reg)) (value :scs (descriptor-reg any-reg))) (:info name offset lowtag) (:ignore name) (:results) (:generator 1 (storew value object offset lowtag))) (define-vop (set cell-set) (:variant symbol-value-slot other-pointer-lowtag)) (define-vop (checked-cell-ref) (:args (object :scs (descriptor-reg) :target obj-temp)) (:results (value :scs (descriptor-reg any-reg))) (:policy :fast-safe) (:vop-var vop) (:save-p :compute-only) (:temporary (:scs (descriptor-reg) :from (:argument 0)) obj-temp)) With Symbol - Value , we check that the value is n't the trap object . (define-vop (symbol-value checked-cell-ref) (:translate symbol-value) (:generator 9 (move obj-temp object) (loadw value obj-temp symbol-value-slot other-pointer-lowtag) (let ((err-lab (generate-error-code vop 'unbound-symbol-error obj-temp))) (inst cmp value unbound-marker-widetag) (inst b :eq err-lab)))) (define-vop (boundp) (:args (object :scs (descriptor-reg))) (:conditional) (:info target not-p) (:policy :fast-safe) (:temporary (:scs (descriptor-reg)) value) (:translate boundp) (:generator 9 (loadw value object symbol-value-slot other-pointer-lowtag) (inst cmp value unbound-marker-widetag) (inst b (if not-p :eq :ne) target))) (define-vop (fast-symbol-value cell-ref) (:variant symbol-value-slot other-pointer-lowtag) (:policy :fast) (:translate symbol-value)) (define-vop (symbol-hash) (:policy :fast-safe) (:translate symbol-hash) (:args (symbol :scs (descriptor-reg))) (:temporary (:scs (non-descriptor-reg)) temp) (:results (res :scs (any-reg))) (:result-types positive-fixnum) (:generator 2 The symbol - hash slot of NIL holds NIL because it is also the car slot , so we have to strip off the two low bits to make sure ensure this is explained in the comment in objdef.lisp (loadw temp symbol symbol-hash-slot other-pointer-lowtag) (inst bic res temp fixnum-tag-mask))) (define-vop (%set-symbol-global-value set)) (define-vop (symbol-global-value symbol-value) (:translate symbol-global-value)) (define-vop (fast-symbol-global-value fast-symbol-value) (:translate symbol-global-value)) (define-vop (fdefn-fun cell-ref) (:variant fdefn-fun-slot other-pointer-lowtag)) (define-vop (safe-fdefn-fun) (:translate safe-fdefn-fun) (:policy :fast-safe) (:args (object :scs (descriptor-reg) :target obj-temp)) (:results (value :scs (descriptor-reg any-reg))) (:vop-var vop) (:save-p :compute-only) (:temporary (:scs (descriptor-reg) :from (:argument 0)) obj-temp) (:generator 10 (move obj-temp object) (loadw value obj-temp fdefn-fun-slot other-pointer-lowtag) (inst cmp value null-tn) (let ((err-lab (generate-error-code vop 'undefined-fun-error obj-temp))) (inst b :eq err-lab)))) (define-vop (set-fdefn-fun) (:policy :fast-safe) (:translate (setf fdefn-fun)) (:args (function :scs (descriptor-reg) :target result) (fdefn :scs (descriptor-reg))) (:temporary (:scs (interior-reg)) lip) (:temporary (:scs (non-descriptor-reg)) type) (:results (result :scs (descriptor-reg))) (:generator 38 (let ((closure-tramp-fixup (gen-label))) (assemble (:elsewhere) (emit-label closure-tramp-fixup) (inst word (make-fixup 'closure-tramp :assembly-routine))) (load-type type function (- fun-pointer-lowtag)) (inst cmp type simple-fun-widetag) (inst mov :eq lip function) (inst load-from-label :ne lip lip closure-tramp-fixup) (storew lip fdefn fdefn-raw-addr-slot other-pointer-lowtag) (storew function fdefn fdefn-fun-slot other-pointer-lowtag) (move result function)))) (define-vop (fdefn-makunbound) (:policy :fast-safe) (:translate fdefn-makunbound) (:args (fdefn :scs (descriptor-reg))) (:temporary (:scs (non-descriptor-reg)) temp) (:temporary (:scs (interior-reg)) lip) (:generator 38 (let ((undefined-tramp-fixup (gen-label))) (assemble (:elsewhere) (emit-label undefined-tramp-fixup) (inst word (make-fixup 'undefined-tramp :assembly-routine))) (storew null-tn fdefn fdefn-fun-slot other-pointer-lowtag) (inst load-from-label temp lip undefined-tramp-fixup) (storew temp fdefn fdefn-raw-addr-slot other-pointer-lowtag)))) BIND -- Establish VAL as a binding for SYMBOL . Save the old value and (define-vop (dynbind) (:args (val :scs (any-reg descriptor-reg)) (symbol :scs (descriptor-reg))) (:temporary (:scs (descriptor-reg)) value-temp) (:temporary (:scs (any-reg)) bsp-temp) (:generator 5 (loadw value-temp symbol symbol-value-slot other-pointer-lowtag) (load-symbol-value bsp-temp *binding-stack-pointer*) (inst add bsp-temp bsp-temp (* 2 n-word-bytes)) (store-symbol-value bsp-temp *binding-stack-pointer*) (storew value-temp bsp-temp (- binding-value-slot binding-size)) (storew symbol bsp-temp (- binding-symbol-slot binding-size)) (storew val symbol symbol-value-slot other-pointer-lowtag))) (define-vop (unbind) (:temporary (:scs (descriptor-reg)) symbol value) (:temporary (:scs (any-reg)) bsp-temp) (:temporary (:scs (any-reg)) zero-temp) (:generator 0 (inst mov zero-temp 0) (load-symbol-value bsp-temp *binding-stack-pointer*) (loadw symbol bsp-temp (- binding-symbol-slot binding-size)) (loadw value bsp-temp (- binding-value-slot binding-size)) (storew value symbol symbol-value-slot other-pointer-lowtag) (storew zero-temp bsp-temp (- binding-symbol-slot binding-size)) (storew zero-temp bsp-temp (- binding-value-slot binding-size)) (inst sub bsp-temp bsp-temp (* 2 n-word-bytes)) (store-symbol-value bsp-temp *binding-stack-pointer*))) (define-vop (unbind-to-here) (:args (arg :scs (descriptor-reg any-reg) :target where)) (:temporary (:scs (any-reg) :from (:argument 0)) where) (:temporary (:scs (descriptor-reg)) symbol value) (:temporary (:scs (any-reg)) bsp-temp zero-temp) (:generator 0 (load-symbol-value bsp-temp *binding-stack-pointer*) (inst mov zero-temp 0) (move where arg) (inst cmp where bsp-temp) (inst b :eq DONE) LOOP (loadw symbol bsp-temp (- binding-symbol-slot binding-size)) (inst cmp symbol 0) (loadw value bsp-temp (- binding-value-slot binding-size) 0 :ne) (storew value symbol symbol-value-slot other-pointer-lowtag :ne) (storew zero-temp bsp-temp (- binding-symbol-slot binding-size) 0 :ne) (storew zero-temp bsp-temp (- binding-value-slot binding-size)) (inst sub bsp-temp bsp-temp (* 2 n-word-bytes)) (inst cmp where bsp-temp) (inst b :ne LOOP) DONE (store-symbol-value bsp-temp *binding-stack-pointer*))) (define-full-reffer closure-index-ref * closure-info-offset fun-pointer-lowtag (descriptor-reg any-reg) * %closure-index-ref) (define-full-setter %closure-index-set * closure-info-offset fun-pointer-lowtag (descriptor-reg any-reg null) * %closure-index-set) (define-full-reffer funcallable-instance-info * funcallable-instance-info-offset fun-pointer-lowtag (descriptor-reg any-reg) * %funcallable-instance-info) (define-vop (closure-ref) (:args (object :scs (descriptor-reg))) (:results (value :scs (descriptor-reg any-reg))) (:info offset) (:generator 4 (loadw value object (+ closure-info-offset offset) fun-pointer-lowtag))) (define-vop (closure-init) (:args (object :scs (descriptor-reg)) (value :scs (descriptor-reg any-reg))) (:info offset) (:generator 4 (storew value object (+ closure-info-offset offset) fun-pointer-lowtag))) (define-vop (closure-init-from-fp) (:args (object :scs (descriptor-reg))) (:info offset) (:generator 4 (storew cfp-tn object (+ closure-info-offset offset) fun-pointer-lowtag))) (define-vop (value-cell-ref cell-ref) (:variant value-cell-value-slot other-pointer-lowtag)) (define-vop (value-cell-set cell-set) (:variant value-cell-value-slot other-pointer-lowtag)) (define-vop () (:policy :fast-safe) (:translate %instance-length) (:args (struct :scs (descriptor-reg))) (:results (res :scs (unsigned-reg))) (:result-types positive-fixnum) (:generator 4 (loadw res struct 0 instance-pointer-lowtag) (inst mov res (lsr res instance-length-shift)))) (define-full-reffer instance-index-ref * instance-slots-offset instance-pointer-lowtag (descriptor-reg any-reg) * %instance-ref) (define-full-setter instance-index-set * instance-slots-offset instance-pointer-lowtag (descriptor-reg any-reg null) * %instance-set) (define-full-reffer code-header-ref * 0 other-pointer-lowtag (descriptor-reg any-reg) * code-header-ref) (define-vop (code-header-set) (:translate code-header-set) (:policy :fast-safe) (:args (object :scs (descriptor-reg)) (index :scs (any-reg)) (value :scs (any-reg descriptor-reg))) (:arg-types * tagged-num *) (:temporary (:scs (non-descriptor-reg)) temp #+gencgc card) #+gencgc (:temporary (:scs (interior-reg)) lip) #+gencgc (:temporary (:sc non-descriptor-reg) pa-flag) (:generator 10 #+cheneygc (progn (inst sub temp index other-pointer-lowtag) (inst str value (@ object temp))) #+gencgc (let ((mask-fixup-label (gen-label)) (table-fixup-label (gen-label))) (inst load-from-label temp lip mask-fixup-label) (inst ldr temp (@ temp)) (inst ldr temp (@ temp)) (pseudo-atomic (pa-flag) (inst mov card (lsr object gencgc-card-shift)) (inst and card card temp) (inst load-from-label temp lip table-fixup-label) (inst ldr temp (@ temp)) (inst ldr temp (@ temp)) (inst strb null-tn (@ temp card)) If two threads get here at the same time , they 'll write the same byte . (let ((byte (- #+little-endian 3 other-pointer-lowtag))) (inst ldrb temp (@ object byte)) (inst orr temp temp #x40) (inst strb temp (@ object byte))) (inst sub temp index other-pointer-lowtag) (inst str value (@ object temp))) (assemble (:elsewhere) (emit-label mask-fixup-label) (inst word (make-fixup "gc_card_table_mask" :foreign-dataref)) (emit-label table-fixup-label) (inst word (make-fixup "gc_card_mark" :foreign-dataref)))))) (macrolet ((define-raw-slot-vops (name ref-inst set-inst value-primtype value-sc &key use-lip (move-macro 'move)) (labels ((emit-generator (instruction move-result) `((inst add offset index (- (* instance-slots-offset n-word-bytes) instance-pointer-lowtag)) ,@(if use-lip `((inst add lip object offset) (inst ,instruction value (@ lip))) `((inst ,instruction value (@ object offset)))) ,@(when move-result `((,move-macro result value)))))) `(progn (define-vop () (:translate ,(symbolicate "%RAW-INSTANCE-REF/" name)) (:policy :fast-safe) (:args (object :scs (descriptor-reg)) (index :scs (any-reg))) (:arg-types * positive-fixnum) (:results (value :scs (,value-sc))) (:result-types ,value-primtype) (:temporary (:scs (non-descriptor-reg)) offset) ,@(when use-lip '((:temporary (:scs (interior-reg)) lip))) (:generator 5 ,@(emit-generator ref-inst nil))) (define-vop () (:translate ,(symbolicate "%RAW-INSTANCE-SET/" name)) (:policy :fast-safe) (:args (object :scs (descriptor-reg)) (index :scs (any-reg)) (value :scs (,value-sc))) (:arg-types * positive-fixnum ,value-primtype) (:temporary (:scs (non-descriptor-reg)) offset) ,@(when use-lip '((:temporary (:scs (interior-reg)) lip))) (:generator 5 ,@(emit-generator set-inst nil))))))) (define-raw-slot-vops word ldr str unsigned-num unsigned-reg) (define-raw-slot-vops signed-word ldr str signed-num signed-reg) (define-raw-slot-vops single flds fsts single-float single-reg :use-lip t :move-macro move-single) (define-raw-slot-vops double fldd fstd double-float double-reg :use-lip t :move-macro move-double) (define-raw-slot-vops complex-single load-complex-single store-complex-single complex-single-float complex-single-reg :use-lip t :move-macro move-complex-single) (define-raw-slot-vops complex-double load-complex-double store-complex-double complex-double-float complex-double-reg :use-lip t :move-macro move-complex-double))
633f40a66dc18b3bb5425f6de0e066b537b15bed7e64c83bcf6f3f3368c0425f
Ptival/chick
Inductive.hs
# LANGUAGE AllowAmbiguousTypes # {-# LANGUAGE OverloadedStrings #-} module Diff.Guess.Inductive ( guess, ) where import Control.Monad (zipWithM) import Data.Function.HT (nest) import qualified Diff.Guess.Atom as ΔGA import qualified Diff.Guess.Constructor as ΔGC import qualified Diff.Guess.Term as ΔGT import qualified Diff.Inductive as ΔI import qualified Diff.List as ΔL import Inductive.Inductive ( Inductive (Inductive), quantifyInductiveIndices, quantifyInductiveParameters, ) import Language (Language (Chick)) import Polysemy (Member, Sem) import Polysemy.Trace (Trace, trace) import PrettyPrinting.PrettyPrintable ( PrettyPrintable (prettyStr), ) import PrettyPrinting.Term () import qualified Term.Raw as Raw import Term.Term (TermX (Var), Variable) import Text.Printf (printf) import Prelude hiding (product) import StandardLibrary guess :: Member Trace r => Inductive Raw.Raw Variable -> Inductive Raw.Raw Variable -> Sem r (ΔI.Diff Raw.Raw) guess i1@(Inductive n1 ips1 iis1 u1 cs1) i2@(Inductive n2 ips2 iis2 u2 cs2) = if i1 == i2 then return ΔI.Same else do δn <- ΔGA.guess n1 n2 To compute δips and δiis , I use a trick : instead of figuring out the permutations from the list itself , I build the telescope term from those and ask the term - diff - guesser to guess a diff for those terms . From this term diff , I extract the information to create the list diff . permutations from the list itself, I build the telescope term from those and ask the term-diff-guesser to guess a diff for those terms. From this term diff, I extract the information to create the list diff. -} let uniqueVar = Var Nothing "__UNIQUE__" let ipsTerm1 = quantifyInductiveParameters ips1 uniqueVar trace $ printf "ipsTerm1: %s" $ prettyStr @'Chick ipsTerm1 let ipsTerm2 = quantifyInductiveParameters ips2 uniqueVar trace $ printf "ipsTerm2: %s" $ prettyStr @'Chick ipsTerm2 δipsType <- ΔGT.guess ipsTerm1 ipsTerm2 let δips = ΔGC.telescopeDiffToListDiffVariable ipsTerm1 δipsType trace "Guess for δips" trace $ show δips let iisTerm1 = quantifyInductiveIndices iis1 uniqueVar let iisTerm2 = quantifyInductiveIndices iis2 uniqueVar δiisType <- ΔGT.guess iisTerm1 iisTerm2 let δiis = ΔGC.telescopeDiffToListDiff iisTerm1 δiisType iisTerm2 trace "Guess for δiis:" trace $ show δiis δu <- ΔGA.guess u1 u2 -- FIXME: for now I cheat and assume: -- - constructors are in the same order -- - if some are missing, they are the last ones -- - if some are introduced, they are the last ones -- Ideally, we'd have some heuristic to match seemingly-related constructors δcsList <- zipWithM ΔGC.guess cs1 cs2 let (l1, l2) = (length cs1, length cs2) let base | l1 == l2 = ΔL.Same | l1 > l2 = nest (l1 - l2) ΔL.Remove ΔL.Same | otherwise = foldr ΔL.Insert ΔL.Same (drop l1 cs2) let δcs = foldr ΔL.Modify base δcsList return $ ΔI.Modify δn δips δiis δu δcs
null
https://raw.githubusercontent.com/Ptival/chick/a5ce39a842ff72348f1c9cea303997d5300163e2/backend/lib/Diff/Guess/Inductive.hs
haskell
# LANGUAGE OverloadedStrings # FIXME: for now I cheat and assume: - constructors are in the same order - if some are missing, they are the last ones - if some are introduced, they are the last ones Ideally, we'd have some heuristic to match seemingly-related constructors
# LANGUAGE AllowAmbiguousTypes # module Diff.Guess.Inductive ( guess, ) where import Control.Monad (zipWithM) import Data.Function.HT (nest) import qualified Diff.Guess.Atom as ΔGA import qualified Diff.Guess.Constructor as ΔGC import qualified Diff.Guess.Term as ΔGT import qualified Diff.Inductive as ΔI import qualified Diff.List as ΔL import Inductive.Inductive ( Inductive (Inductive), quantifyInductiveIndices, quantifyInductiveParameters, ) import Language (Language (Chick)) import Polysemy (Member, Sem) import Polysemy.Trace (Trace, trace) import PrettyPrinting.PrettyPrintable ( PrettyPrintable (prettyStr), ) import PrettyPrinting.Term () import qualified Term.Raw as Raw import Term.Term (TermX (Var), Variable) import Text.Printf (printf) import Prelude hiding (product) import StandardLibrary guess :: Member Trace r => Inductive Raw.Raw Variable -> Inductive Raw.Raw Variable -> Sem r (ΔI.Diff Raw.Raw) guess i1@(Inductive n1 ips1 iis1 u1 cs1) i2@(Inductive n2 ips2 iis2 u2 cs2) = if i1 == i2 then return ΔI.Same else do δn <- ΔGA.guess n1 n2 To compute δips and δiis , I use a trick : instead of figuring out the permutations from the list itself , I build the telescope term from those and ask the term - diff - guesser to guess a diff for those terms . From this term diff , I extract the information to create the list diff . permutations from the list itself, I build the telescope term from those and ask the term-diff-guesser to guess a diff for those terms. From this term diff, I extract the information to create the list diff. -} let uniqueVar = Var Nothing "__UNIQUE__" let ipsTerm1 = quantifyInductiveParameters ips1 uniqueVar trace $ printf "ipsTerm1: %s" $ prettyStr @'Chick ipsTerm1 let ipsTerm2 = quantifyInductiveParameters ips2 uniqueVar trace $ printf "ipsTerm2: %s" $ prettyStr @'Chick ipsTerm2 δipsType <- ΔGT.guess ipsTerm1 ipsTerm2 let δips = ΔGC.telescopeDiffToListDiffVariable ipsTerm1 δipsType trace "Guess for δips" trace $ show δips let iisTerm1 = quantifyInductiveIndices iis1 uniqueVar let iisTerm2 = quantifyInductiveIndices iis2 uniqueVar δiisType <- ΔGT.guess iisTerm1 iisTerm2 let δiis = ΔGC.telescopeDiffToListDiff iisTerm1 δiisType iisTerm2 trace "Guess for δiis:" trace $ show δiis δu <- ΔGA.guess u1 u2 δcsList <- zipWithM ΔGC.guess cs1 cs2 let (l1, l2) = (length cs1, length cs2) let base | l1 == l2 = ΔL.Same | l1 > l2 = nest (l1 - l2) ΔL.Remove ΔL.Same | otherwise = foldr ΔL.Insert ΔL.Same (drop l1 cs2) let δcs = foldr ΔL.Modify base δcsList return $ ΔI.Modify δn δips δiis δu δcs
e1db0eccfc79ece0efde85b50792d71e4ad49a7edbe01c2efac709c26c6a867c
ocaml-toml/To.ml
unicode.ml
For more informations about unicode to utf-8 converting method used see : * ( Page3 , section " 3 . UTF-8 definition " ) * (Page3, section "3. UTF-8 definition") *) decimal conversions of binary used : * 10000000 - > 128 ; 11000000 - > 192 ; 11100000 - > 224 * 10000000 -> 128; 11000000 -> 192; 11100000 -> 224 *) This function convert Unicode escaped XXXX to utf-8 encoded string let to_utf8 u = let dec = int_of_string @@ "0x" ^ u in let update_byte s i mask shift = Char.chr @@ (Char.code (Bytes.get s i) + ((dec lsr shift) land int_of_string mask)) |> Bytes.set s i in if dec > 0xFFFF then failwith ("Invalid escaped unicode \\u" ^ u) else if dec > 0x7FF then ( let s = Bytes.of_string "\224\128\128" in update_byte s 2 "0b00111111" 0; update_byte s 1 "0b00111111" 6; update_byte s 0 "0b00001111" 12; Bytes.to_string s ) else if dec > 0x7F then ( let s = Bytes.of_string "\192\128" in update_byte s 1 "0b00111111" 0; update_byte s 0 "0b00011111" 6; Bytes.to_string s ) else let s = Bytes.of_string "\000" in update_byte s 0 "0b01111111" 0; Bytes.to_string s
null
https://raw.githubusercontent.com/ocaml-toml/To.ml/215922367a2783af22e12e08bd8182e4cd149be0/src/unicode.ml
ocaml
For more informations about unicode to utf-8 converting method used see : * ( Page3 , section " 3 . UTF-8 definition " ) * (Page3, section "3. UTF-8 definition") *) decimal conversions of binary used : * 10000000 - > 128 ; 11000000 - > 192 ; 11100000 - > 224 * 10000000 -> 128; 11000000 -> 192; 11100000 -> 224 *) This function convert Unicode escaped XXXX to utf-8 encoded string let to_utf8 u = let dec = int_of_string @@ "0x" ^ u in let update_byte s i mask shift = Char.chr @@ (Char.code (Bytes.get s i) + ((dec lsr shift) land int_of_string mask)) |> Bytes.set s i in if dec > 0xFFFF then failwith ("Invalid escaped unicode \\u" ^ u) else if dec > 0x7FF then ( let s = Bytes.of_string "\224\128\128" in update_byte s 2 "0b00111111" 0; update_byte s 1 "0b00111111" 6; update_byte s 0 "0b00001111" 12; Bytes.to_string s ) else if dec > 0x7F then ( let s = Bytes.of_string "\192\128" in update_byte s 1 "0b00111111" 0; update_byte s 0 "0b00011111" 6; Bytes.to_string s ) else let s = Bytes.of_string "\000" in update_byte s 0 "0b01111111" 0; Bytes.to_string s
fd61bc9a634bda29a154bb9df8a26d575c33d8563ef5115ee8ab1fccb35556e8
tweag/asterius
arr008.hs
-- !!! Array - out-of-range (index,value) pairs -- supplying a list containing one or more pairs -- with out-of-range index is undefined. -- -- import Data.Array main = let a1 = array (1::Int,0) [] a2 = array (0::Int,1) (zip [0..] ['a'..'z']) in print (a1::Array Int Int) >> print a2
null
https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/test/ghc-testsuite/array/arr008.hs
haskell
!!! Array - out-of-range (index,value) pairs with out-of-range index is undefined.
supplying a list containing one or more pairs import Data.Array main = let a1 = array (1::Int,0) [] a2 = array (0::Int,1) (zip [0..] ['a'..'z']) in print (a1::Array Int Int) >> print a2
2b6957ca5b7457c53ff2b40f3fb4ba348ba27813b353388b472c31e1eba14544
the-dr-lazy/cascade
OffsetDatetime.hs
| Module : Cascade . Api . Data . OffsetDatetime Description : ! ! ! INSERT MODULE SHORT DESCRIPTION ! ! ! Copyright : ( c ) 2020 - 2021 Cascade License : MPL 2.0 Maintainer : < > ( the-dr-lazy.github.io ) Stability : Stable Portability : POSIX ! ! ! INSERT MODULE LONG DESCRIPTION ! ! ! Module : Cascade.Api.Data.OffsetDatetime Description : !!! INSERT MODULE SHORT DESCRIPTION !!! Copyright : (c) 2020-2021 Cascade License : MPL 2.0 Maintainer : Mohammad Hasani <> (the-dr-lazy.github.io) Stability : Stable Portability : POSIX !!! INSERT MODULE LONG DESCRIPTION !!! -} module Cascade.Api.Data.OffsetDatetime ( FormattedOffsetDatetime (..) ) where import qualified Chronos import Chronos.Types import Data.Aeson ( FromJSON (..), ToJSON (..), Value (..) ) import Data.Aeson.Types ( parserThrowError, prependFailure, typeMismatch ) import Data.Attoparsec.Text ( endOfInput, parseOnly ) newtype FormattedOffsetDatetime = FormattedOffsetDatetime { unFormattedOffsetDatetime :: OffsetDatetime } deriving stock (Generic, Show) deriving newtype (Eq) instance FromJSON FormattedOffsetDatetime where parseJSON (String x) = let parser = Chronos.parser_YmdHMSz OffsetFormatColonAuto Chronos.hyphen in case parseOnly (parser <* endOfInput) x of Right r -> pure $ FormattedOffsetDatetime r Left e -> parserThrowError [] ("parsing date failed: " ++ e) parseJSON invalid = prependFailure "parsing date failed, " (typeMismatch "String" invalid) instance ToJSON FormattedOffsetDatetime where toJSON date = String $ Chronos.encode_YmdHMSz OffsetFormatColonAuto SubsecondPrecisionAuto Chronos.hyphen (unFormattedOffsetDatetime date)
null
https://raw.githubusercontent.com/the-dr-lazy/cascade/014a5589a2763ce373e8c84a211cddc479872b44/cascade-api/src/Cascade/Api/Data/OffsetDatetime.hs
haskell
| Module : Cascade . Api . Data . OffsetDatetime Description : ! ! ! INSERT MODULE SHORT DESCRIPTION ! ! ! Copyright : ( c ) 2020 - 2021 Cascade License : MPL 2.0 Maintainer : < > ( the-dr-lazy.github.io ) Stability : Stable Portability : POSIX ! ! ! INSERT MODULE LONG DESCRIPTION ! ! ! Module : Cascade.Api.Data.OffsetDatetime Description : !!! INSERT MODULE SHORT DESCRIPTION !!! Copyright : (c) 2020-2021 Cascade License : MPL 2.0 Maintainer : Mohammad Hasani <> (the-dr-lazy.github.io) Stability : Stable Portability : POSIX !!! INSERT MODULE LONG DESCRIPTION !!! -} module Cascade.Api.Data.OffsetDatetime ( FormattedOffsetDatetime (..) ) where import qualified Chronos import Chronos.Types import Data.Aeson ( FromJSON (..), ToJSON (..), Value (..) ) import Data.Aeson.Types ( parserThrowError, prependFailure, typeMismatch ) import Data.Attoparsec.Text ( endOfInput, parseOnly ) newtype FormattedOffsetDatetime = FormattedOffsetDatetime { unFormattedOffsetDatetime :: OffsetDatetime } deriving stock (Generic, Show) deriving newtype (Eq) instance FromJSON FormattedOffsetDatetime where parseJSON (String x) = let parser = Chronos.parser_YmdHMSz OffsetFormatColonAuto Chronos.hyphen in case parseOnly (parser <* endOfInput) x of Right r -> pure $ FormattedOffsetDatetime r Left e -> parserThrowError [] ("parsing date failed: " ++ e) parseJSON invalid = prependFailure "parsing date failed, " (typeMismatch "String" invalid) instance ToJSON FormattedOffsetDatetime where toJSON date = String $ Chronos.encode_YmdHMSz OffsetFormatColonAuto SubsecondPrecisionAuto Chronos.hyphen (unFormattedOffsetDatetime date)
2aa13fb7bf669b6a89c2e7414948dc9fd4578e92dc9d4cd5aa523c9df4036865
FieryCod/holy-lambda-ring-adapter
codec.clj
(ns fierycod.holy-lambda-ring-adapter.codec "Functions for encoding and decoding data. All credits to @weavejester. -clojure/ring-codec" (:require [clojure.string :as str]) (:import java.util.Map [java.net URLEncoder])) (defn- double-escape [^String x] (.replace (.replace x "\\" "\\\\") "$" "\\$")) (def ^:private string-replace-bug? (= "x" (str/replace "x" #"." (fn [_x] "$0")))) (defmacro ^:no-doc fix-string-replace-bug [x] (if string-replace-bug? `(double-escape ~x) x)) (defn- parse-bytes ^bytes [encoded-bytes] (let [encoded-len (count encoded-bytes) bs (byte-array (/ encoded-len 3))] (loop [encoded-index 1, byte-index 0] (if (< encoded-index encoded-len) (let [encoded-byte (subs encoded-bytes encoded-index (+ encoded-index 2)) b (.byteValue (Integer/valueOf encoded-byte 16))] (aset bs byte-index b) (recur (+ encoded-index 3) (inc byte-index))) bs)))) (defprotocol ^:no-doc FormEncodeable (form-encode* [x encoding])) (extend-protocol FormEncodeable String (form-encode* [^String unencoded ^String encoding] (URLEncoder/encode unencoded encoding)) Map (form-encode* [params encoding] (letfn [(encode [x] (form-encode* x encoding)) (encode-param [k v] (str (encode (name k)) "=" (encode v)))] (->> params (mapcat (fn [[k v]] (cond (sequential? v) (map #(encode-param k %) v) (set? v) (sort (map #(encode-param k %) v)) :else (list (encode-param k v))))) (str/join "&")))) Object (form-encode* [x encoding] (form-encode* (str x) encoding)) nil (form-encode* [_ __] "")) (defn form-encode "Encode the supplied value into www-form-urlencoded format, often used in URL query strings and POST request bodies, using the specified encoding. If the encoding is not specified, it defaults to UTF-8" ([x] (form-encode x "UTF-8")) ([x encoding] (form-encode* x encoding)))
null
https://raw.githubusercontent.com/FieryCod/holy-lambda-ring-adapter/06fb440c6d42c4e1d36108c510cd1b00f21d0b71/src/fierycod/holy_lambda_ring_adapter/codec.clj
clojure
(ns fierycod.holy-lambda-ring-adapter.codec "Functions for encoding and decoding data. All credits to @weavejester. -clojure/ring-codec" (:require [clojure.string :as str]) (:import java.util.Map [java.net URLEncoder])) (defn- double-escape [^String x] (.replace (.replace x "\\" "\\\\") "$" "\\$")) (def ^:private string-replace-bug? (= "x" (str/replace "x" #"." (fn [_x] "$0")))) (defmacro ^:no-doc fix-string-replace-bug [x] (if string-replace-bug? `(double-escape ~x) x)) (defn- parse-bytes ^bytes [encoded-bytes] (let [encoded-len (count encoded-bytes) bs (byte-array (/ encoded-len 3))] (loop [encoded-index 1, byte-index 0] (if (< encoded-index encoded-len) (let [encoded-byte (subs encoded-bytes encoded-index (+ encoded-index 2)) b (.byteValue (Integer/valueOf encoded-byte 16))] (aset bs byte-index b) (recur (+ encoded-index 3) (inc byte-index))) bs)))) (defprotocol ^:no-doc FormEncodeable (form-encode* [x encoding])) (extend-protocol FormEncodeable String (form-encode* [^String unencoded ^String encoding] (URLEncoder/encode unencoded encoding)) Map (form-encode* [params encoding] (letfn [(encode [x] (form-encode* x encoding)) (encode-param [k v] (str (encode (name k)) "=" (encode v)))] (->> params (mapcat (fn [[k v]] (cond (sequential? v) (map #(encode-param k %) v) (set? v) (sort (map #(encode-param k %) v)) :else (list (encode-param k v))))) (str/join "&")))) Object (form-encode* [x encoding] (form-encode* (str x) encoding)) nil (form-encode* [_ __] "")) (defn form-encode "Encode the supplied value into www-form-urlencoded format, often used in URL query strings and POST request bodies, using the specified encoding. If the encoding is not specified, it defaults to UTF-8" ([x] (form-encode x "UTF-8")) ([x encoding] (form-encode* x encoding)))
b5ac0e76d96dbc19687c8de2a15eca0bf4f9ef50ffdcb59926851083bd6db2d7
fused-effects/fused-effects
Writer.hs
# LANGUAGE ExistentialQuantification # {-# LANGUAGE RankNTypes #-} | An effect allowing writes to an accumulated quantity alongside a computed value . A ' Writer ' @w@ effect keeps track of a monoidal datum of type @w@ and strictly appends to that monoidal value with the ' tell ' effect . Writes to that value can be detected and intercepted with the ' listen ' and ' censor ' effects . Predefined carriers : * " Control . Carrier . Writer . Church " * " Control . Carrier . Writer . Strict " . ( A lazy carrier is not provided due to the inherent space leaks associated with lazy writer monads . ) * " Control . . Trans . RWS.CPS " * " Control . . Trans . RWS.Lazy " * " Control . . Trans . RWS.Strict " * " Control . . Trans . Writer . CPS " * " Control . . Trans . Writer . Lazy " * " Control . . Trans . Writer . Strict " * If ' Writer ' @w@ is the last effect in a stack , it can be interpreted to a tuple @(w , a)@ given some result type @a@ and the presence of a ' Monoid ' instance for @w@. @since 0.1.0.0 Predefined carriers: * "Control.Carrier.Writer.Church" * "Control.Carrier.Writer.Strict". (A lazy carrier is not provided due to the inherent space leaks associated with lazy writer monads.) * "Control.Monad.Trans.RWS.CPS" * "Control.Monad.Trans.RWS.Lazy" * "Control.Monad.Trans.RWS.Strict" * "Control.Monad.Trans.Writer.CPS" * "Control.Monad.Trans.Writer.Lazy" * "Control.Monad.Trans.Writer.Strict" * If 'Writer' @w@ is the last effect in a stack, it can be interpreted to a tuple @(w, a)@ given some result type @a@ and the presence of a 'Monoid' instance for @w@. @since 0.1.0.0 -} module Control.Effect.Writer ( -- * Writer effect Writer(..) , tell , listen , listens , censor -- * Re-exports , Algebra , Has , run ) where import Control.Algebra import Control.Effect.Writer.Internal (Writer(..)) import Data.Bifunctor (first) -- | Write a value to the log. -- -- @ ( ' tell ' w ' > > ' m ) = ' Data.Bifunctor.first ' ( ' mappend ' w ) ' < $ > ' m -- @ -- @since 0.1.0.0 tell :: Has (Writer w) sig m => w -> m () tell w = send (Tell w) {-# INLINE tell #-} -- | Run a computation, returning the pair of its output and its result. -- -- @ ( ' listen ' m ) = ' fmap ' ( ' fst ' ' Control . Arrow . & & & ' ' i d ' ) ( ) -- @ -- @since 0.2.0.0 listen :: Has (Writer w) sig m => m a -> m (w, a) listen m = send (Listen m) # INLINE listen # -- | Run a computation, applying a function to its output and returning the pair of the modified output and its result. -- -- @ ' listens ' f m = ' fmap ' ( ' first ' f ) ( ' listen ' m ) -- @ -- @since 0.2.0.0 listens :: Has (Writer w) sig m => (w -> b) -> m a -> m (b, a) listens f = fmap (first f) . listen # INLINE listens # -- | Run a computation, modifying its output with the passed function. -- -- @ ( ' censor ' f m ) = ' fmap ' ( ' Data.Bifunctor.first ' f ) ( ) -- @ -- @since 0.2.0.0 censor :: Has (Writer w) sig m => (w -> w) -> m a -> m a censor f m = send (Censor f m) # INLINE censor #
null
https://raw.githubusercontent.com/fused-effects/fused-effects/9790ed4fb2cbaaf8933ce0eb42d7c55bc38f12ac/src/Control/Effect/Writer.hs
haskell
# LANGUAGE RankNTypes # * Writer effect * Re-exports | Write a value to the log. @ @ # INLINE tell # | Run a computation, returning the pair of its output and its result. @ @ | Run a computation, applying a function to its output and returning the pair of the modified output and its result. @ @ | Run a computation, modifying its output with the passed function. @ @
# LANGUAGE ExistentialQuantification # | An effect allowing writes to an accumulated quantity alongside a computed value . A ' Writer ' @w@ effect keeps track of a monoidal datum of type @w@ and strictly appends to that monoidal value with the ' tell ' effect . Writes to that value can be detected and intercepted with the ' listen ' and ' censor ' effects . Predefined carriers : * " Control . Carrier . Writer . Church " * " Control . Carrier . Writer . Strict " . ( A lazy carrier is not provided due to the inherent space leaks associated with lazy writer monads . ) * " Control . . Trans . RWS.CPS " * " Control . . Trans . RWS.Lazy " * " Control . . Trans . RWS.Strict " * " Control . . Trans . Writer . CPS " * " Control . . Trans . Writer . Lazy " * " Control . . Trans . Writer . Strict " * If ' Writer ' @w@ is the last effect in a stack , it can be interpreted to a tuple @(w , a)@ given some result type @a@ and the presence of a ' Monoid ' instance for @w@. @since 0.1.0.0 Predefined carriers: * "Control.Carrier.Writer.Church" * "Control.Carrier.Writer.Strict". (A lazy carrier is not provided due to the inherent space leaks associated with lazy writer monads.) * "Control.Monad.Trans.RWS.CPS" * "Control.Monad.Trans.RWS.Lazy" * "Control.Monad.Trans.RWS.Strict" * "Control.Monad.Trans.Writer.CPS" * "Control.Monad.Trans.Writer.Lazy" * "Control.Monad.Trans.Writer.Strict" * If 'Writer' @w@ is the last effect in a stack, it can be interpreted to a tuple @(w, a)@ given some result type @a@ and the presence of a 'Monoid' instance for @w@. @since 0.1.0.0 -} module Control.Effect.Writer Writer(..) , tell , listen , listens , censor , Algebra , Has , run ) where import Control.Algebra import Control.Effect.Writer.Internal (Writer(..)) import Data.Bifunctor (first) ( ' tell ' w ' > > ' m ) = ' Data.Bifunctor.first ' ( ' mappend ' w ) ' < $ > ' m @since 0.1.0.0 tell :: Has (Writer w) sig m => w -> m () tell w = send (Tell w) ( ' listen ' m ) = ' fmap ' ( ' fst ' ' Control . Arrow . & & & ' ' i d ' ) ( ) @since 0.2.0.0 listen :: Has (Writer w) sig m => m a -> m (w, a) listen m = send (Listen m) # INLINE listen # ' listens ' f m = ' fmap ' ( ' first ' f ) ( ' listen ' m ) @since 0.2.0.0 listens :: Has (Writer w) sig m => (w -> b) -> m a -> m (b, a) listens f = fmap (first f) . listen # INLINE listens # ( ' censor ' f m ) = ' fmap ' ( ' Data.Bifunctor.first ' f ) ( ) @since 0.2.0.0 censor :: Has (Writer w) sig m => (w -> w) -> m a -> m a censor f m = send (Censor f m) # INLINE censor #
bd11b7adca94fa8bc1d4373090dce3909b4038c38749c1199fe6c2ff81b42fb4
BoeingX/haskell-programming-from-first-principles
GivenATypeWriteTheFunction.hs
module Types.ChapterExercises.GivenATypeWriteTheFunction where Question 1 i :: a -> a -- or i = id i a = a Question 2 c :: a -> b -> a -- or c = const c a _ = a Question 3 c'' :: b -> a -> b c'' = c Question 4 c' :: a -> b -> b c' _ b = b Question 5 r :: [a] -> [a] r = id r' :: [a] -> [a] r' = reverse Question 6 co :: (b -> c) -> (a -> b) -> (a -> c) co f g = f . g Question 7 a :: (a -> c) -> a -> a a _ x = x Question 8 a' :: (a -> b) -> a -> b a' f x = f x
null
https://raw.githubusercontent.com/BoeingX/haskell-programming-from-first-principles/ffb637f536597f552a4e4567fee848ed27f3ba74/src/Types/ChapterExercises/GivenATypeWriteTheFunction.hs
haskell
or i = id or c = const
module Types.ChapterExercises.GivenATypeWriteTheFunction where Question 1 i :: a -> a i a = a Question 2 c :: a -> b -> a c a _ = a Question 3 c'' :: b -> a -> b c'' = c Question 4 c' :: a -> b -> b c' _ b = b Question 5 r :: [a] -> [a] r = id r' :: [a] -> [a] r' = reverse Question 6 co :: (b -> c) -> (a -> b) -> (a -> c) co f g = f . g Question 7 a :: (a -> c) -> a -> a a _ x = x Question 8 a' :: (a -> b) -> a -> b a' f x = f x
c2aa4e09255ff07eb89c188d50794d526c000604aeeacf334f6f85a488316048
lucasdicioccio/deptrack-project
BlockDevice.hs
module Devops.Storage.BlockDevice where data BlockDevice a = BlockDevice { blockDevicePath :: FilePath , partitionPath :: Int -> FilePath }
null
https://raw.githubusercontent.com/lucasdicioccio/deptrack-project/cd3d59a796815af8ae8db32c47b1e1cdc209ac71/deptrack-devops-recipes/src/Devops/Storage/BlockDevice.hs
haskell
module Devops.Storage.BlockDevice where data BlockDevice a = BlockDevice { blockDevicePath :: FilePath , partitionPath :: Int -> FilePath }
53e3dc9442664a3cf34665a5731a8a3d9fbfaa6ffc9fc9a82626868a6574d8b1
viercc/kitchen-sink-hs
Indexed.hs
# LANGUAGE TypeApplications # # LANGUAGE PolyKinds # # LANGUAGE StandaloneKindSignatures # {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE TypeOperators # {-# LANGUAGE GADTs #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE InstanceSigs # # LANGUAGE EmptyCase # | - style Indexed Monad Conor McBride-style Indexed Monad -} module Monad.Indexed( * IxFunctor and IxMonad IxFunctor(..), IxMonad(..), * Relation between Atkey - style At(..), Atkey, ireturn', ibind', WrapAtkey(..), wrap, unwrap, -- * Example: Indexed State monad IxState(..), SomeTup(..), IxState', iget', iput', imodify', runIxState', -- * Example: Free Monad IxFree(..), interpret, -- * Indexed Applicative (Atkey-style) IxApplicative(..), (<<$>>), iap' ) where import Data.Kind (Constraint, Type) -- | Indexed Functor is a Functor from Hask^K to Hask^K, where @K@ stands for the discrete category of types of -- kind @k@. -- That means , to @F@ to be @IxFunctor@ , We do n't assume input -- functor @x@ has any instance of type class (like @Functor@ -- or @Monad@), and don't assure @F x@ to become any instance of -- type class. All data constructors of kind @k -> *@ is already -- an functor from discrete category. type IxFunctor :: ((k -> Type) -> k -> Type) -> Constraint class IxFunctor f where ifmap :: (forall a. x a -> y a) -> f x b -> f y b -- | IxMonad class (IxFunctor m) => IxMonad m where ireturn :: x a -> m x a ijoin :: m (m x) a -> m x a ibind :: m x b -> (forall a. x a -> m y a) -> m y b ibind fxb k = ijoin (ifmap k fxb) data At a i j where V :: a -> At a i i -- | Atkey-style indexed monad type Atkey m i j a = m (At a j) i ireturn' :: (IxMonad m) => a -> Atkey m i i a ireturn' = ireturn . V ibind' :: forall i j k a b m. (IxMonad m) => Atkey m i j a -> (a -> Atkey m j k b) -> Atkey m i k b ibind' m_ij_a f = let f' :: forall z. At a j z -> m (At b k) z f' (V a) = f a in m_ij_a `ibind` f' | Atkey - style to - style type AtkeyIxFunctor :: (k -> k -> Type -> Type) -> Constraint class AtkeyIxFunctor f where ifmap_A :: (a -> b) -> f i j a -> f i j b class AtkeyIxFunctor m => AtkeyIxMonad m where ireturn_A :: a -> m i i a ibind_A :: m i j a -> (a -> m j k b) -> m i k b ibind_A mij k = ijoin_A $ ifmap_A k mij ijoin_A :: m i j (m j k a) -> m i k a ijoin_A mm = ibind_A mm id newtype WrapAtkey m x i = WrapAtkey { runWrapAtkey :: forall __ r. (forall j. x j -> m j __ r) -> m i __ r } wrap :: AtkeyIxMonad m => m i j a -> WrapAtkey m (At a j) i wrap ma = WrapAtkey $ \ret -> ma `ibind_A` \a -> ret (V a) unwrap :: AtkeyIxMonad m => WrapAtkey m (At a j) i -> m i j a unwrap m = runWrapAtkey m (\(V a) -> ireturn_A a) instance IxFunctor (WrapAtkey f) where ifmap phi (WrapAtkey mij) = WrapAtkey (\ret -> mij (ret . phi)) instance IxMonad (WrapAtkey m) where ireturn :: x i -> WrapAtkey m x i ireturn xi = WrapAtkey $ \ret -> ret xi ijoin :: forall x i. WrapAtkey m (WrapAtkey m x) i -> WrapAtkey m x i ijoin (WrapAtkey mm) = WrapAtkey $ \ret -> mm (\m -> runWrapAtkey m ret) | " Free monad " over type IxFree :: ((k -> Type) -> k -> Type) -> (k -> Type) -> k -> Type data IxFree f v a = Wrap (f (IxFree f v) a) | Pure (v a) instance (IxFunctor f) => IxFunctor (IxFree f) where ifmap :: forall g h a. (forall x. g x -> h x) -> IxFree f g a -> IxFree f h a ifmap phi = let go :: forall b. IxFree f g b -> IxFree f h b go (Wrap fpa) = Wrap $ ifmap go fpa go (Pure va) = Pure $ phi va in go instance (IxFunctor f) => IxMonad (IxFree f) where ireturn = Pure ijoin (Wrap fmma) = Wrap $ ifmap ijoin fmma ijoin (Pure ma) = ma interpret :: (IxMonad m) => (forall r a. f r a -> m r a) -> IxFree f x b -> m x b interpret handler (Wrap fpa) = handler fpa `ibind` interpret handler interpret _ (Pure xa) = ireturn xa -- | Indexed State monad -- | ∃t. (t, x t) data SomeTup x = forall t. SomeTup t (x t) -- | IxState x s = s -> ∃t. (t, x t) newtype IxState x s = IxState (s -> SomeTup x) instance IxFunctor IxState where ifmap phi (IxState st) = IxState $ \s -> case st s of SomeTup t xt -> SomeTup t (phi xt) instance IxMonad IxState where ireturn xt = IxState $ \t -> SomeTup t xt ijoin (IxState mmxs) = IxState $ \s -> case mmxs s of SomeTup t (IxState mxt) -> mxt t -- | Atkey-style Indexed State monad type IxState' s t a = Atkey IxState s t a runIxState' :: IxState' s t a -> s -> (t, a) runIxState' (IxState st) s = case st s of SomeTup t (V a) -> (t, a) iget' :: IxState' s s s iget' = IxState $ \s -> SomeTup s (V s) iput' :: t -> IxState' s t () iput' t = IxState $ \_ -> SomeTup t (V ()) imodify' :: (s -> t) -> IxState' s t () imodify' f = IxState $ \s -> SomeTup (f s) (V ()) -- | Atkey-style indexed Applicative class (IxFunctor f) => IxApplicative f where ipure :: a -> Atkey f i i a (<<*>>) :: Atkey f i j (a -> b) -> Atkey f j k a -> Atkey f i k b (<<$>>) :: IxFunctor f => (a -> b) -> Atkey f i j a -> Atkey f i j b f <<$>> fa = ifmap (\(V a) -> V (f a)) fa iap' :: (IxMonad m) => Atkey m i j (a -> b) -> Atkey m j k a -> Atkey m i k b iap' mab ma = ibind' mab (<<$>> ma) instance IxApplicative IxState where ipure = ireturn' (<<*>>) = iap' -- * /= IxApplicative -- -- Monoidal structure of Hask^K : Unit and ( :* :) data Unit ( a : : k ) = Unit deriving ( Show , Read , Eq , Ord ) data ( :* ( a : : k ) = f a :* : g a deriving ( Show , Read , Eq , Ord ) class ( IxFunctor f ) = > f where iunit : : f Unit a iprod : : f x a - > f y a - > f ( x :* : y ) a unit2pure : : ( f ) = > ( forall a. x a ) - > f x b unit2pure xa = ifmap ( const xa ) iunit prod2liftA2 : : forall f x y z. ( f ) = > ( forall a. x a - > y a - > z a ) - > ( forall b. f x b - > f y b - > f z b ) = ifmap ( \(xa :* : ya ) - > phi xa ya ) ( iprod fxb fyb ) -- * IxMonoidal /= IxApplicative -- -- Monoidal structure of Hask^K: Unit and (:*:) data Unit (a :: k) = Unit deriving (Show, Read, Eq, Ord) data (:*:) f g (a :: k) = f a :*: g a deriving (Show, Read, Eq, Ord) class (IxFunctor f) => IxMonoidal f where iunit :: f Unit a iprod :: f x a -> f y a -> f (x :*: y) a unit2pure :: (IxMonoidal f) => (forall a. x a) -> f x b unit2pure xa = ifmap (const xa) iunit prod2liftA2 :: forall f x y z. (IxMonoidal f) => (forall a. x a -> y a -> z a) -> (forall b. f x b -> f y b -> f z b) prod2liftA2 phi fxb fyb = ifmap (\(xa :*: ya) -> phi xa ya) (iprod fxb fyb) -}
null
https://raw.githubusercontent.com/viercc/kitchen-sink-hs/5038b17a39e4e6f19e6fb4779a7c8aaddf64d922/monads-collection/src/Monad/Indexed.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE RankNTypes # # LANGUAGE GADTs # * Example: Indexed State monad * Example: Free Monad * Indexed Applicative (Atkey-style) | Indexed Functor is a Functor from Hask^K to Hask^K, kind @k@. functor @x@ has any instance of type class (like @Functor@ or @Monad@), and don't assure @F x@ to become any instance of type class. All data constructors of kind @k -> *@ is already an functor from discrete category. | IxMonad | Atkey-style indexed monad | Indexed State monad | ∃t. (t, x t) | IxState x s = s -> ∃t. (t, x t) | Atkey-style Indexed State monad | Atkey-style indexed Applicative * /= IxApplicative Monoidal structure of Hask^K : Unit and ( :* :) * IxMonoidal /= IxApplicative Monoidal structure of Hask^K: Unit and (:*:)
# LANGUAGE TypeApplications # # LANGUAGE PolyKinds # # LANGUAGE StandaloneKindSignatures # # LANGUAGE TypeOperators # # LANGUAGE ScopedTypeVariables # # LANGUAGE InstanceSigs # # LANGUAGE EmptyCase # | - style Indexed Monad Conor McBride-style Indexed Monad -} module Monad.Indexed( * IxFunctor and IxMonad IxFunctor(..), IxMonad(..), * Relation between Atkey - style At(..), Atkey, ireturn', ibind', WrapAtkey(..), wrap, unwrap, IxState(..), SomeTup(..), IxState', iget', iput', imodify', runIxState', IxFree(..), interpret, IxApplicative(..), (<<$>>), iap' ) where import Data.Kind (Constraint, Type) where @K@ stands for the discrete category of types of That means , to @F@ to be @IxFunctor@ , We do n't assume input type IxFunctor :: ((k -> Type) -> k -> Type) -> Constraint class IxFunctor f where ifmap :: (forall a. x a -> y a) -> f x b -> f y b class (IxFunctor m) => IxMonad m where ireturn :: x a -> m x a ijoin :: m (m x) a -> m x a ibind :: m x b -> (forall a. x a -> m y a) -> m y b ibind fxb k = ijoin (ifmap k fxb) data At a i j where V :: a -> At a i i type Atkey m i j a = m (At a j) i ireturn' :: (IxMonad m) => a -> Atkey m i i a ireturn' = ireturn . V ibind' :: forall i j k a b m. (IxMonad m) => Atkey m i j a -> (a -> Atkey m j k b) -> Atkey m i k b ibind' m_ij_a f = let f' :: forall z. At a j z -> m (At b k) z f' (V a) = f a in m_ij_a `ibind` f' | Atkey - style to - style type AtkeyIxFunctor :: (k -> k -> Type -> Type) -> Constraint class AtkeyIxFunctor f where ifmap_A :: (a -> b) -> f i j a -> f i j b class AtkeyIxFunctor m => AtkeyIxMonad m where ireturn_A :: a -> m i i a ibind_A :: m i j a -> (a -> m j k b) -> m i k b ibind_A mij k = ijoin_A $ ifmap_A k mij ijoin_A :: m i j (m j k a) -> m i k a ijoin_A mm = ibind_A mm id newtype WrapAtkey m x i = WrapAtkey { runWrapAtkey :: forall __ r. (forall j. x j -> m j __ r) -> m i __ r } wrap :: AtkeyIxMonad m => m i j a -> WrapAtkey m (At a j) i wrap ma = WrapAtkey $ \ret -> ma `ibind_A` \a -> ret (V a) unwrap :: AtkeyIxMonad m => WrapAtkey m (At a j) i -> m i j a unwrap m = runWrapAtkey m (\(V a) -> ireturn_A a) instance IxFunctor (WrapAtkey f) where ifmap phi (WrapAtkey mij) = WrapAtkey (\ret -> mij (ret . phi)) instance IxMonad (WrapAtkey m) where ireturn :: x i -> WrapAtkey m x i ireturn xi = WrapAtkey $ \ret -> ret xi ijoin :: forall x i. WrapAtkey m (WrapAtkey m x) i -> WrapAtkey m x i ijoin (WrapAtkey mm) = WrapAtkey $ \ret -> mm (\m -> runWrapAtkey m ret) | " Free monad " over type IxFree :: ((k -> Type) -> k -> Type) -> (k -> Type) -> k -> Type data IxFree f v a = Wrap (f (IxFree f v) a) | Pure (v a) instance (IxFunctor f) => IxFunctor (IxFree f) where ifmap :: forall g h a. (forall x. g x -> h x) -> IxFree f g a -> IxFree f h a ifmap phi = let go :: forall b. IxFree f g b -> IxFree f h b go (Wrap fpa) = Wrap $ ifmap go fpa go (Pure va) = Pure $ phi va in go instance (IxFunctor f) => IxMonad (IxFree f) where ireturn = Pure ijoin (Wrap fmma) = Wrap $ ifmap ijoin fmma ijoin (Pure ma) = ma interpret :: (IxMonad m) => (forall r a. f r a -> m r a) -> IxFree f x b -> m x b interpret handler (Wrap fpa) = handler fpa `ibind` interpret handler interpret _ (Pure xa) = ireturn xa data SomeTup x = forall t. SomeTup t (x t) newtype IxState x s = IxState (s -> SomeTup x) instance IxFunctor IxState where ifmap phi (IxState st) = IxState $ \s -> case st s of SomeTup t xt -> SomeTup t (phi xt) instance IxMonad IxState where ireturn xt = IxState $ \t -> SomeTup t xt ijoin (IxState mmxs) = IxState $ \s -> case mmxs s of SomeTup t (IxState mxt) -> mxt t type IxState' s t a = Atkey IxState s t a runIxState' :: IxState' s t a -> s -> (t, a) runIxState' (IxState st) s = case st s of SomeTup t (V a) -> (t, a) iget' :: IxState' s s s iget' = IxState $ \s -> SomeTup s (V s) iput' :: t -> IxState' s t () iput' t = IxState $ \_ -> SomeTup t (V ()) imodify' :: (s -> t) -> IxState' s t () imodify' f = IxState $ \s -> SomeTup (f s) (V ()) class (IxFunctor f) => IxApplicative f where ipure :: a -> Atkey f i i a (<<*>>) :: Atkey f i j (a -> b) -> Atkey f j k a -> Atkey f i k b (<<$>>) :: IxFunctor f => (a -> b) -> Atkey f i j a -> Atkey f i j b f <<$>> fa = ifmap (\(V a) -> V (f a)) fa iap' :: (IxMonad m) => Atkey m i j (a -> b) -> Atkey m j k a -> Atkey m i k b iap' mab ma = ibind' mab (<<$>> ma) instance IxApplicative IxState where ipure = ireturn' (<<*>>) = iap' data Unit ( a : : k ) = Unit deriving ( Show , Read , Eq , Ord ) data ( :* ( a : : k ) = f a :* : g a deriving ( Show , Read , Eq , Ord ) class ( IxFunctor f ) = > f where iunit : : f Unit a iprod : : f x a - > f y a - > f ( x :* : y ) a unit2pure : : ( f ) = > ( forall a. x a ) - > f x b unit2pure xa = ifmap ( const xa ) iunit prod2liftA2 : : forall f x y z. ( f ) = > ( forall a. x a - > y a - > z a ) - > ( forall b. f x b - > f y b - > f z b ) = ifmap ( \(xa :* : ya ) - > phi xa ya ) ( iprod fxb fyb ) data Unit (a :: k) = Unit deriving (Show, Read, Eq, Ord) data (:*:) f g (a :: k) = f a :*: g a deriving (Show, Read, Eq, Ord) class (IxFunctor f) => IxMonoidal f where iunit :: f Unit a iprod :: f x a -> f y a -> f (x :*: y) a unit2pure :: (IxMonoidal f) => (forall a. x a) -> f x b unit2pure xa = ifmap (const xa) iunit prod2liftA2 :: forall f x y z. (IxMonoidal f) => (forall a. x a -> y a -> z a) -> (forall b. f x b -> f y b -> f z b) prod2liftA2 phi fxb fyb = ifmap (\(xa :*: ya) -> phi xa ya) (iprod fxb fyb) -}
88b87e3d77f1118182c7ae7a89c1d385670f662aedb248a2002677e81a99ea68
janestreet/incr_dom
main.ml
open! Core open! Incr_dom open! Js_of_ocaml let () = let counters = List.range 0 5 |> List.map ~f:(fun k -> k, Random.int_incl 0 10) |> Int.Map.of_alist_exn in Start_app.start (module Counters) ~bind_to_element_with_id:"app" ~initial_model:(Counters.Model.Fields.create ~counters) ;;
null
https://raw.githubusercontent.com/janestreet/incr_dom/56c04e44d6a8f1cc9b2b841495ec448de4bf61a1/example/svg_graph/main.ml
ocaml
open! Core open! Incr_dom open! Js_of_ocaml let () = let counters = List.range 0 5 |> List.map ~f:(fun k -> k, Random.int_incl 0 10) |> Int.Map.of_alist_exn in Start_app.start (module Counters) ~bind_to_element_with_id:"app" ~initial_model:(Counters.Model.Fields.create ~counters) ;;
22056b1b3220a31b998d1309ac8ee2c6d51b3a5d26f524605051e92554407c2b
jordanthayer/ocaml-search
beam_stack_search.ml
(** Beam Stack Search *) type 'a node = {f : float; g : float; data : 'a; depth : int; mutable pos: int;} let wrap f = (** takes a function to be applied to the data payload such as the goal-test or the domain heuristic and wraps it so that it can be applied to the entire node *) (fun n -> f n.data) let unwrap_sol s = (** Unwraps a solution which is in the form of a search node and presents it in the format the domain expects it, which is domain data followed by cost *) match s with Limit.Nothing -> None | Limit.Incumbent (q,n) -> Some (n.data, n.g) let ordered_p a b = a.f <= b.f let better_p a b = a.g <= b.g (*|| (a.f = b.f && a.g < b.g)*) let make_expand expand h = (** Takes the domain expand function and a heuristic calculator and creates an expand function which returns search nodes. *) (fun n -> let nd = n.depth + 1 in List.map (fun (d, g) -> { data = d; f = g +. (h d); g = g; depth = nd; pos = Dpq.no_position; }) (expand n.data n.g)) let make_sface time sface incumbent = let def_log = Limit.make_default_logger ~silent:true ~time:time (fun n -> n.f) (wrap sface.Search_interface.get_sol_length) in Search_interface.make ~node_expand:(make_expand sface.Search_interface.domain_expand sface.Search_interface.h) ~goal_p:(wrap sface.Search_interface.goal_p) ~key:(wrap sface.Search_interface.key) ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals ~halt_on:sface.Search_interface.halt_on ~incumbent:(Limit.Incumbent (0.,incumbent)) sface.Search_interface.domain {data = sface.Search_interface.initial; f = neg_infinity; g = 0.; depth = 0; pos = Dpq.no_position;} better_p (fun i -> sface.Search_interface.info.Limit.log (Limit.unwrap_info (fun n -> n.data) i); def_log i) cmw 5/18/2010 makes a search interface without a seed ( assumes the best known solution is infinitely far away and infinitely bad ) . Useful if you do n't know what the bound is and do n't really want to try and find a solution becuase finding a solution to use in the first place is not easy . cmw 5/18/2010 makes a search interface without a seed (assumes the best known solution is infinitely far away and infinitely bad). Useful if you don't know what the bound is and don't really want to try and find a solution becuase finding a solution to use in the first place is not easy. *) let make_empty_sface time sface = let def_log = Limit.make_default_logger ~silent:false ~time:time (fun n -> n.f) (wrap sface.Search_interface.get_sol_length) in Search_interface.make ~node_expand:(make_expand sface.Search_interface.domain_expand sface.Search_interface.h) ~goal_p:(wrap sface.Search_interface.goal_p) ~key:(wrap sface.Search_interface.key) ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals ~halt_on:sface.Search_interface.halt_on ~incumbent:(Limit.Nothing) sface.Search_interface.domain {data = sface.Search_interface.initial; f = neg_infinity; g = 0.; depth = 0; pos = Dpq.no_position;} better_p (fun i -> sface.Search_interface.info.Limit.log (Limit.unwrap_info (fun n -> n.data) i); def_log i) let no_dups sface args = let beam_width = Search_args.get_int "Beam_stack_search.no_dups" args 0 in let stime = Sys.time() in match Greedy.no_dups sface [||] with None,x2,x3,x4,x5 -> None,x2,x3,x4,x5 | Some (data, cost),x2,x3,x4,x5 -> Limit.unwrap_sol5 unwrap_sol (let search_interface = make_sface stime sface {f = cost; g = cost; data = data; depth = 0; pos = Dpq.no_position;} in Limit.incr_gen_n search_interface.Search_interface.info x3; Limit.incr_exp_n search_interface.Search_interface.info x2; Limit.incr_prune_n search_interface.Search_interface.info x4; Limit.curr_q search_interface.Search_interface.info x5; Beam_stack.search search_interface beam_width (fun n -> n.f) ordered_p better_p) let dups sface args = let beam_width = Search_args.get_int "Beam_stack_search.dups" args 0 in let stime = Sys.time() in match Greedy.dups sface [||] with None,x2,x3,x4,x5,x6 -> None,x2,x3,x4,x5,x6 | Some (data, cost),x2,x3,x4,x5,x6 -> Verb.pe Verb.always "Starting beam search\n%!"; Limit.unwrap_sol6 unwrap_sol (let search_interface = make_sface stime sface {f = cost; g = cost; data = data; depth = 0; pos = Dpq.no_position;} in Limit.incr_gen_n search_interface.Search_interface.info x3; Limit.incr_exp_n search_interface.Search_interface.info x2; Limit.incr_prune_n search_interface.Search_interface.info x4; Limit.incr_dups_n search_interface.Search_interface.info x6; Limit.curr_q search_interface.Search_interface.info x5; Beam_stack.search_dups search_interface beam_width (fun n -> n.f) (fun n -> n.depth) ordered_p better_p) calls beam stack search without a seed . cmw 5/18/2010 calls beam stack search without a seed. cmw 5/18/2010 *) let no_seed sface args = let beam_width = Search_args.get_int "Beam_stack_search.no_seed" args 0 in let stime = Sys.time() in Limit.unwrap_sol6 unwrap_sol (let search_interface = make_empty_sface stime sface in Beam_stack.search_dups search_interface beam_width (fun n -> n.f) (fun n -> n.depth) ordered_p better_p) let exact_seed sface args = let beam_width = Search_args.get_int "Beam_stack_search.no_seed" args 0 in let node_capacity = Search_args.get_float "Beam_stack_search.dups" args 1 in let depth_bound = node_capacity /. (float_of_int beam_width) in let stime = Sys.time() in Limit.unwrap_sol6 unwrap_sol (let search_interface = make_empty_sface stime sface in Beam_stack.search_dups ~exact_bound:(Some depth_bound) search_interface beam_width (fun n -> n.f) (fun n -> n.depth) ordered_p better_p) EOF
null
https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/search/anytime/beam_stack_search.ml
ocaml
* Beam Stack Search * takes a function to be applied to the data payload such as the goal-test or the domain heuristic and wraps it so that it can be applied to the entire node * Unwraps a solution which is in the form of a search node and presents it in the format the domain expects it, which is domain data followed by cost || (a.f = b.f && a.g < b.g) * Takes the domain expand function and a heuristic calculator and creates an expand function which returns search nodes.
type 'a node = {f : float; g : float; data : 'a; depth : int; mutable pos: int;} let wrap f = (fun n -> f n.data) let unwrap_sol s = match s with Limit.Nothing -> None | Limit.Incumbent (q,n) -> Some (n.data, n.g) let ordered_p a b = a.f <= b.f let better_p a b = let make_expand expand h = (fun n -> let nd = n.depth + 1 in List.map (fun (d, g) -> { data = d; f = g +. (h d); g = g; depth = nd; pos = Dpq.no_position; }) (expand n.data n.g)) let make_sface time sface incumbent = let def_log = Limit.make_default_logger ~silent:true ~time:time (fun n -> n.f) (wrap sface.Search_interface.get_sol_length) in Search_interface.make ~node_expand:(make_expand sface.Search_interface.domain_expand sface.Search_interface.h) ~goal_p:(wrap sface.Search_interface.goal_p) ~key:(wrap sface.Search_interface.key) ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals ~halt_on:sface.Search_interface.halt_on ~incumbent:(Limit.Incumbent (0.,incumbent)) sface.Search_interface.domain {data = sface.Search_interface.initial; f = neg_infinity; g = 0.; depth = 0; pos = Dpq.no_position;} better_p (fun i -> sface.Search_interface.info.Limit.log (Limit.unwrap_info (fun n -> n.data) i); def_log i) cmw 5/18/2010 makes a search interface without a seed ( assumes the best known solution is infinitely far away and infinitely bad ) . Useful if you do n't know what the bound is and do n't really want to try and find a solution becuase finding a solution to use in the first place is not easy . cmw 5/18/2010 makes a search interface without a seed (assumes the best known solution is infinitely far away and infinitely bad). Useful if you don't know what the bound is and don't really want to try and find a solution becuase finding a solution to use in the first place is not easy. *) let make_empty_sface time sface = let def_log = Limit.make_default_logger ~silent:false ~time:time (fun n -> n.f) (wrap sface.Search_interface.get_sol_length) in Search_interface.make ~node_expand:(make_expand sface.Search_interface.domain_expand sface.Search_interface.h) ~goal_p:(wrap sface.Search_interface.goal_p) ~key:(wrap sface.Search_interface.key) ~hash:sface.Search_interface.hash ~equals:sface.Search_interface.equals ~halt_on:sface.Search_interface.halt_on ~incumbent:(Limit.Nothing) sface.Search_interface.domain {data = sface.Search_interface.initial; f = neg_infinity; g = 0.; depth = 0; pos = Dpq.no_position;} better_p (fun i -> sface.Search_interface.info.Limit.log (Limit.unwrap_info (fun n -> n.data) i); def_log i) let no_dups sface args = let beam_width = Search_args.get_int "Beam_stack_search.no_dups" args 0 in let stime = Sys.time() in match Greedy.no_dups sface [||] with None,x2,x3,x4,x5 -> None,x2,x3,x4,x5 | Some (data, cost),x2,x3,x4,x5 -> Limit.unwrap_sol5 unwrap_sol (let search_interface = make_sface stime sface {f = cost; g = cost; data = data; depth = 0; pos = Dpq.no_position;} in Limit.incr_gen_n search_interface.Search_interface.info x3; Limit.incr_exp_n search_interface.Search_interface.info x2; Limit.incr_prune_n search_interface.Search_interface.info x4; Limit.curr_q search_interface.Search_interface.info x5; Beam_stack.search search_interface beam_width (fun n -> n.f) ordered_p better_p) let dups sface args = let beam_width = Search_args.get_int "Beam_stack_search.dups" args 0 in let stime = Sys.time() in match Greedy.dups sface [||] with None,x2,x3,x4,x5,x6 -> None,x2,x3,x4,x5,x6 | Some (data, cost),x2,x3,x4,x5,x6 -> Verb.pe Verb.always "Starting beam search\n%!"; Limit.unwrap_sol6 unwrap_sol (let search_interface = make_sface stime sface {f = cost; g = cost; data = data; depth = 0; pos = Dpq.no_position;} in Limit.incr_gen_n search_interface.Search_interface.info x3; Limit.incr_exp_n search_interface.Search_interface.info x2; Limit.incr_prune_n search_interface.Search_interface.info x4; Limit.incr_dups_n search_interface.Search_interface.info x6; Limit.curr_q search_interface.Search_interface.info x5; Beam_stack.search_dups search_interface beam_width (fun n -> n.f) (fun n -> n.depth) ordered_p better_p) calls beam stack search without a seed . cmw 5/18/2010 calls beam stack search without a seed. cmw 5/18/2010 *) let no_seed sface args = let beam_width = Search_args.get_int "Beam_stack_search.no_seed" args 0 in let stime = Sys.time() in Limit.unwrap_sol6 unwrap_sol (let search_interface = make_empty_sface stime sface in Beam_stack.search_dups search_interface beam_width (fun n -> n.f) (fun n -> n.depth) ordered_p better_p) let exact_seed sface args = let beam_width = Search_args.get_int "Beam_stack_search.no_seed" args 0 in let node_capacity = Search_args.get_float "Beam_stack_search.dups" args 1 in let depth_bound = node_capacity /. (float_of_int beam_width) in let stime = Sys.time() in Limit.unwrap_sol6 unwrap_sol (let search_interface = make_empty_sface stime sface in Beam_stack.search_dups ~exact_bound:(Some depth_bound) search_interface beam_width (fun n -> n.f) (fun n -> n.depth) ordered_p better_p) EOF
816ecb1334d0c9fc98a773737f83c200f48ba6fe9a0c7871de37aa10b4a96ff8
theodormoroianu/SecondYearCourses
HaskellChurch_20210415163937.hs
{-# LANGUAGE RankNTypes #-} module HaskellChurch where A boolean is any way to choose between two alternatives newtype CBool = CBool {cIf :: forall t. t -> t -> t} An instance to show as regular Booleans instance Show CBool where show b = "cBool " <> show (cIf b True False) The boolean constant true always chooses the first alternative cTrue :: CBool cTrue = undefined The boolean constant false always chooses the second alternative cFalse :: CBool cFalse = undefined cBool :: Bool -> CBool cBool True = cTrue cBool False = cFalse --The boolean negation switches the alternatives cNot :: CBool -> CBool cNot = undefined --The boolean conjunction can be built as a conditional (&&:) :: CBool -> CBool -> CBool (&&:) = undefined infixr 3 &&: --The boolean disjunction can be built as a conditional (||:) :: CBool -> CBool -> CBool (||:) = undefined infixr 2 ||: -- a pair is a way to compute something based on the values -- contained within the pair. newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c } An instance to show CPairs as regular pairs . instance (Show a, Show b) => Show (CPair a b) where show p = "cPair " <> show (cOn p (,)) builds a pair out of two values as an object which , when given --a function to be applied on the values, it will apply it on them. cPair :: a -> b -> CPair a b cPair = undefined first projection uses the function selecting first component on a pair cFst :: CPair a b -> a cFst = undefined second projection cSnd :: CPair a b -> b cSnd = undefined -- A natural number is any way to iterate a function s a number of times -- over an initial value z newtype CNat = CNat { cFor :: forall t. (t -> t) -> t -> t } -- An instance to show CNats as regular natural numbers instance Show CNat where show n = show $ cFor n (1 +) (0 :: Integer) --0 will iterate the function s 0 times over z, producing z c0 :: CNat c0 = undefined 1 is the the function s iterated 1 times over z , that is , z c1 :: CNat c1 = undefined --Successor n either - applies s one more time in addition to what n does -- - iterates s n times over (s z) cS :: CNat -> CNat cS = undefined --Addition of m and n is done by iterating s n times over m (+:) :: CNat -> CNat -> CNat (+:) = undefined infixl 6 +: --Multiplication of m and n can be done by composing n and m (*:) :: CNat -> CNat -> CNat (*:) = \n m -> CNat $ cFor n . cFor m infixl 7 *: --Exponentiation of m and n can be done by applying n to m (^:) :: CNat -> CNat -> CNat (^:) = \m n -> CNat $ cFor n (cFor m) infixr 8 ^: --Testing whether a value is 0 can be done through iteration -- using a function constantly false and an initial value true cIs0 :: CNat -> CBool cIs0 = \n -> cFor n (\_ -> cFalse) cTrue Predecessor ( evaluating to 0 for 0 ) can be defined iterating over pairs , starting from an initial value ( 0 , 0 ) cPred :: CNat -> CNat cPred = undefined substraction from m n ( evaluating to 0 if m < n ) is repeated application -- of the predeccesor function (-:) :: CNat -> CNat -> CNat (-:) = \m n -> cFor n cPred m Transform a value into a CNat ( should yield c0 for nums < = 0 ) cNat :: (Ord p, Num p) => p -> CNat cNat n = undefined We can define an instance Num CNat which will allow us to see any integer constant as a CNat ( e.g. 12 : : CNat ) and also use regular -- arithmetic instance Num CNat where (+) = (+:) (*) = (*:) (-) = (-:) abs = id signum n = cIf (cIs0 n) 0 1 fromInteger = cNat -- m is less than (or equal to) n if when substracting n from m we get 0 (<=:) :: CNat -> CNat -> CBool (<=:) = undefined infix 4 <=: (>=:) :: CNat -> CNat -> CBool (>=:) = \m n -> n <=: m infix 4 >=: (<:) :: CNat -> CNat -> CBool (<:) = \m n -> cNot (m >=: n) infix 4 <: (>:) :: CNat -> CNat -> CBool (>:) = \m n -> n <: m infix 4 >: -- equality on naturals can be defined my means of comparisons (==:) :: CNat -> CNat -> CBool (==:) = undefined --Fun with arithmetic and pairs --Define factorial. You can iterate over a pair to contain the current index and so far factorial cFactorial :: CNat -> CNat cFactorial = undefined Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence cFibonacci :: CNat -> CNat cFibonacci = undefined --Given m and n, compute q and r satisfying m = q * n + r. If n is not 0 then r should be less than n. --hint repeated substraction, iterated for at most m times. cDivMod :: CNat -> CNat -> CPair CNat CNat cDivMod = undefined -- a list is a way to aggregate a sequence of elements given an aggregation function and an initial value. newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b } make CList an instance of Foldable instance Foldable CList where --An instance to show CLists as regular lists. instance (Show a) => Show (CList a) where show l = "cList " <> (show $ toList l) -- The empty list is that which when aggregated it will always produce the initial value cNil :: CList a cNil = undefined -- Adding an element to a list means that, when aggregating the list, the newly added -- element will be aggregated with the result obtained by aggregating the remainder of the list (.:) :: a -> CList a -> CList a (.:) = undefined we can obtain a CList from a regular list by folding the list cList :: [a] -> CList a cList = undefined builds a CList of CNats corresponding to a list of Integers cNatList :: [Integer] -> CList CNat cNatList = undefined -- sums the elements in the list cSum :: CList CNat -> CNat cSum = undefined -- checks whether a list is nil (similar to cIs0) cIsNil :: CList a -> CBool cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue -- gets the head of the list (or the default specified value if the list is empty) cHead :: CList a -> a -> a cHead = undefined cTail :: CList a -> CList a cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil) cLength :: CList a -> CNat cLength = \l -> cFoldR l (\_ n -> cS n) 0 fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b) divmod m n = divmod' (0, 0) where divmod' (x, y) | x' <= m = divmod' (x', succ y) | otherwise = (y, m - x) where x' = x + n divmod' m n = if n == 0 then (0, m) else Function.fix (\f p -> (\x' -> if x' > 0 then f ((,) (succ (fst p)) x') else if (<=) n (snd p) then ((,) (succ (fst p)) 0) else p) ((-) (snd p) n)) (0, m) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ) )
null
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/HaskellChurch_20210415163937.hs
haskell
# LANGUAGE RankNTypes # The boolean negation switches the alternatives The boolean conjunction can be built as a conditional The boolean disjunction can be built as a conditional a pair is a way to compute something based on the values contained within the pair. a function to be applied on the values, it will apply it on them. A natural number is any way to iterate a function s a number of times over an initial value z An instance to show CNats as regular natural numbers 0 will iterate the function s 0 times over z, producing z Successor n either - iterates s n times over (s z) Addition of m and n is done by iterating s n times over m Multiplication of m and n can be done by composing n and m Exponentiation of m and n can be done by applying n to m Testing whether a value is 0 can be done through iteration using a function constantly false and an initial value true of the predeccesor function arithmetic m is less than (or equal to) n if when substracting n from m we get 0 equality on naturals can be defined my means of comparisons Fun with arithmetic and pairs Define factorial. You can iterate over a pair to contain the current index and so far factorial Given m and n, compute q and r satisfying m = q * n + r. If n is not 0 then r should be less than n. hint repeated substraction, iterated for at most m times. a list is a way to aggregate a sequence of elements given an aggregation function and an initial value. An instance to show CLists as regular lists. The empty list is that which when aggregated it will always produce the initial value Adding an element to a list means that, when aggregating the list, the newly added element will be aggregated with the result obtained by aggregating the remainder of the list sums the elements in the list checks whether a list is nil (similar to cIs0) gets the head of the list (or the default specified value if the list is empty)
module HaskellChurch where A boolean is any way to choose between two alternatives newtype CBool = CBool {cIf :: forall t. t -> t -> t} An instance to show as regular Booleans instance Show CBool where show b = "cBool " <> show (cIf b True False) The boolean constant true always chooses the first alternative cTrue :: CBool cTrue = undefined The boolean constant false always chooses the second alternative cFalse :: CBool cFalse = undefined cBool :: Bool -> CBool cBool True = cTrue cBool False = cFalse cNot :: CBool -> CBool cNot = undefined (&&:) :: CBool -> CBool -> CBool (&&:) = undefined infixr 3 &&: (||:) :: CBool -> CBool -> CBool (||:) = undefined infixr 2 ||: newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c } An instance to show CPairs as regular pairs . instance (Show a, Show b) => Show (CPair a b) where show p = "cPair " <> show (cOn p (,)) builds a pair out of two values as an object which , when given cPair :: a -> b -> CPair a b cPair = undefined first projection uses the function selecting first component on a pair cFst :: CPair a b -> a cFst = undefined second projection cSnd :: CPair a b -> b cSnd = undefined newtype CNat = CNat { cFor :: forall t. (t -> t) -> t -> t } instance Show CNat where show n = show $ cFor n (1 +) (0 :: Integer) c0 :: CNat c0 = undefined 1 is the the function s iterated 1 times over z , that is , z c1 :: CNat c1 = undefined - applies s one more time in addition to what n does cS :: CNat -> CNat cS = undefined (+:) :: CNat -> CNat -> CNat (+:) = undefined infixl 6 +: (*:) :: CNat -> CNat -> CNat (*:) = \n m -> CNat $ cFor n . cFor m infixl 7 *: (^:) :: CNat -> CNat -> CNat (^:) = \m n -> CNat $ cFor n (cFor m) infixr 8 ^: cIs0 :: CNat -> CBool cIs0 = \n -> cFor n (\_ -> cFalse) cTrue Predecessor ( evaluating to 0 for 0 ) can be defined iterating over pairs , starting from an initial value ( 0 , 0 ) cPred :: CNat -> CNat cPred = undefined substraction from m n ( evaluating to 0 if m < n ) is repeated application (-:) :: CNat -> CNat -> CNat (-:) = \m n -> cFor n cPred m Transform a value into a CNat ( should yield c0 for nums < = 0 ) cNat :: (Ord p, Num p) => p -> CNat cNat n = undefined We can define an instance Num CNat which will allow us to see any integer constant as a CNat ( e.g. 12 : : CNat ) and also use regular instance Num CNat where (+) = (+:) (*) = (*:) (-) = (-:) abs = id signum n = cIf (cIs0 n) 0 1 fromInteger = cNat (<=:) :: CNat -> CNat -> CBool (<=:) = undefined infix 4 <=: (>=:) :: CNat -> CNat -> CBool (>=:) = \m n -> n <=: m infix 4 >=: (<:) :: CNat -> CNat -> CBool (<:) = \m n -> cNot (m >=: n) infix 4 <: (>:) :: CNat -> CNat -> CBool (>:) = \m n -> n <: m infix 4 >: (==:) :: CNat -> CNat -> CBool (==:) = undefined cFactorial :: CNat -> CNat cFactorial = undefined Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence cFibonacci :: CNat -> CNat cFibonacci = undefined cDivMod :: CNat -> CNat -> CPair CNat CNat cDivMod = undefined newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b } make CList an instance of Foldable instance Foldable CList where instance (Show a) => Show (CList a) where show l = "cList " <> (show $ toList l) cNil :: CList a cNil = undefined (.:) :: a -> CList a -> CList a (.:) = undefined we can obtain a CList from a regular list by folding the list cList :: [a] -> CList a cList = undefined builds a CList of CNats corresponding to a list of Integers cNatList :: [Integer] -> CList CNat cNatList = undefined cSum :: CList CNat -> CNat cSum = undefined cIsNil :: CList a -> CBool cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue cHead :: CList a -> a -> a cHead = undefined cTail :: CList a -> CList a cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil) cLength :: CList a -> CNat cLength = \l -> cFoldR l (\_ n -> cS n) 0 fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b) divmod m n = divmod' (0, 0) where divmod' (x, y) | x' <= m = divmod' (x', succ y) | otherwise = (y, m - x) where x' = x + n divmod' m n = if n == 0 then (0, m) else Function.fix (\f p -> (\x' -> if x' > 0 then f ((,) (succ (fst p)) x') else if (<=) n (snd p) then ((,) (succ (fst p)) 0) else p) ((-) (snd p) n)) (0, m) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ) )
5de1103c88327d8bedd2316a2081f0036ff22fbccc7590a33cf1bd638d93501e
petelliott/pscheme
test.scm
(define-library (pscheme test) (import (scheme base) (scheme write) (scheme process-context)) (export assert skip-test run-test define-test finish-tests) (begin (define has-global-fail #f) (define has-local-fail #f) (define (assert b) (unless b (set! has-global-fail #t) (set! has-local-fail #t))) (define red "31") (define green "32") (define yellow "33") (define (bcd color obj) (display "\e[1;") (display color) (display "m") (display obj) (display "\e[0m")) (define (skip-test name) (bcd yellow "SKIP") (display " ") (display name) (newline)) (define (run-test name body) (set! has-local-fail #f) (body) (if has-local-fail (bcd red "FAIL") (bcd green "PASS")) (display " ") (display name) (newline)) (define-syntax define-test (syntax-rules (SKIP) ((_ name SKIP body ...) (skip-test name)) ((_ name body ...) (run-test name (lambda () body ...))))) (define (finish-tests) (exit (not has-global-fail))) ))
null
https://raw.githubusercontent.com/petelliott/pscheme/dcedb1141210308fe1e48a2119f0a209f1dccdf5/scm/pscheme/test.scm
scheme
(define-library (pscheme test) (import (scheme base) (scheme write) (scheme process-context)) (export assert skip-test run-test define-test finish-tests) (begin (define has-global-fail #f) (define has-local-fail #f) (define (assert b) (unless b (set! has-global-fail #t) (set! has-local-fail #t))) (define red "31") (define green "32") (define yellow "33") (define (bcd color obj) (display "\e[1;") (display color) (display "m") (display obj) (display "\e[0m")) (define (skip-test name) (bcd yellow "SKIP") (display " ") (display name) (newline)) (define (run-test name body) (set! has-local-fail #f) (body) (if has-local-fail (bcd red "FAIL") (bcd green "PASS")) (display " ") (display name) (newline)) (define-syntax define-test (syntax-rules (SKIP) ((_ name SKIP body ...) (skip-test name)) ((_ name body ...) (run-test name (lambda () body ...))))) (define (finish-tests) (exit (not has-global-fail))) ))
01b52406331e100fc40423c20b1c8dfdcbae79c378e464821dba876012df48b2
nc6/tabula
Destination.hs
Copyright ( c ) 2014 Genome Research Ltd. Author : < > 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 < / > . Copyright (c) 2014 Genome Research Ltd. Author: Nicholas A. Clarke <> 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 </>. -} # LANGUAGE RankNTypes , FlexibleContexts # module Tabula.Destination where import Control.Applicative import Data.Conduit import Tabula.Record import qualified Text.Parsec as P data Project = UserProject String String | GlobalProject String instance Show Project where show (UserProject user key) = "("++user++") "++key show (GlobalProject key) = "(global) "++key data DestinationProvider = DestinationProvider { listProjects :: IO [Project] , projectDestination :: Project -> Destination , removeProject :: Project -> IO () } data Destination = Destination { recordSink :: Sink Record (ResourceT IO) () -- ^ Sink records to a store , getLastRecord :: IO (Maybe Record) -- ^ Fetch the last ^ Get a stream of all records , first to last } Parser for project names . projectNameParser :: P.Stream s m Char => P.ParsecT s u m String projectNameParser = let (<:>) a b = (:) <$> a <*> b validChar = P.alphaNum <|> P.oneOf "-_." projectName = P.alphaNum <:> P.many1 validChar in projectName
null
https://raw.githubusercontent.com/nc6/tabula/f76524bbe56b45b125707cf1f4f9526817c4e6e8/Tabula/Destination.hs
haskell
^ Sink records to a store ^ Fetch the last
Copyright ( c ) 2014 Genome Research Ltd. Author : < > 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 < / > . Copyright (c) 2014 Genome Research Ltd. Author: Nicholas A. Clarke <> 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 </>. -} # LANGUAGE RankNTypes , FlexibleContexts # module Tabula.Destination where import Control.Applicative import Data.Conduit import Tabula.Record import qualified Text.Parsec as P data Project = UserProject String String | GlobalProject String instance Show Project where show (UserProject user key) = "("++user++") "++key show (GlobalProject key) = "(global) "++key data DestinationProvider = DestinationProvider { listProjects :: IO [Project] , projectDestination :: Project -> Destination , removeProject :: Project -> IO () } data Destination = Destination { ^ Get a stream of all records , first to last } Parser for project names . projectNameParser :: P.Stream s m Char => P.ParsecT s u m String projectNameParser = let (<:>) a b = (:) <$> a <*> b validChar = P.alphaNum <|> P.oneOf "-_." projectName = P.alphaNum <:> P.many1 validChar in projectName
3da9ae635e5152a559c6b9b427182f281d85842370444aaa51e026ddcf4b26e5
gigasquid/libpython-clj-examples
datasets_estimators.clj
(ns gigasquid.sk-learn.datasets-estimators (:require [libpython-clj.require :refer [require-python]] [libpython-clj.python :as py :refer [py. py.. py.-]] [gigasquid.plot :as plot])) (require-python '[sklearn.datasets :as datasets]) (require-python '[matplotlib.pyplot :as pyplot]) (require-python '[matplotlib.pyplot.cm :as pyplot-cm]) ;;;; From -learn.org/stable/tutorial/statistical_inference/settings.html ;;; Taking a look as the standard iris dataset (def iris (datasets/load_iris)) (def data (py.- iris data)) - > ( 150 , 4 ) It is made of 150 observations of irises , each described by 4 features : their sepal and petal length and width ;;; An example of reshaping is with the digits dataset The digits dataset is made of 1797 8x8 images of hand - written digits (def digits (datasets/load_digits)) (def digit-images (py.- digits images)) = > ( 1797 , 8 , 8) (plot/with-show (pyplot/imshow (last digit-images) :cmap pyplot-cm/gray_r)) To use this dataset we transform each 8x8 image to feature vector of length 64 (def data (py. digit-images reshape (first (py.- digit-images shape)) -1)) = > ( 1797 , 64 ) ;;;; Estimator objects ;;An estimator is any object that learns from data ; it may be a classification, regression or clustering algorithm or a transformer that extracts/filters useful features from raw data. ;;All estimator objects expose a fit method that takes a dataset (usually a 2-d array
null
https://raw.githubusercontent.com/gigasquid/libpython-clj-examples/f151c00415c82a144a13959ff7b56f58704ac6f2/src/gigasquid/sk_learn/datasets_estimators.clj
clojure
From -learn.org/stable/tutorial/statistical_inference/settings.html Taking a look as the standard iris dataset An example of reshaping is with the digits dataset Estimator objects An estimator is any object that learns from data it may be a classification, regression or clustering algorithm or a transformer that extracts/filters useful features from raw data. All estimator objects expose a fit method that takes a dataset (usually a 2-d array
(ns gigasquid.sk-learn.datasets-estimators (:require [libpython-clj.require :refer [require-python]] [libpython-clj.python :as py :refer [py. py.. py.-]] [gigasquid.plot :as plot])) (require-python '[sklearn.datasets :as datasets]) (require-python '[matplotlib.pyplot :as pyplot]) (require-python '[matplotlib.pyplot.cm :as pyplot-cm]) (def iris (datasets/load_iris)) (def data (py.- iris data)) - > ( 150 , 4 ) It is made of 150 observations of irises , each described by 4 features : their sepal and petal length and width The digits dataset is made of 1797 8x8 images of hand - written digits (def digits (datasets/load_digits)) (def digit-images (py.- digits images)) = > ( 1797 , 8 , 8) (plot/with-show (pyplot/imshow (last digit-images) :cmap pyplot-cm/gray_r)) To use this dataset we transform each 8x8 image to feature vector of length 64 (def data (py. digit-images reshape (first (py.- digit-images shape)) -1)) = > ( 1797 , 64 )
6731e80464ef464e1cbfafd3e1cf03bbb09efbe99daecd98e61cb1b263e1c9c6
expipiplus1/vulkan
Bracket.hs
module VMA.Bracket ( brackets ) where import Relude hiding ( Handle , Type ) import Data.Vector ( Vector ) import qualified Data.Map as Map import qualified Data.Text.Extra as T import Spec.Name import Bracket import Render.Element import Render.Names import Render.SpecInfo import Error import Marshal.Command import Render.Utils brackets :: forall r . (HasErr r, HasRenderParams r, HasSpecInfo r, HasRenderedNames r) => Vector MarshaledCommand -> Sem r (Vector (CName, CName, RenderElement)) brackets marshaledCommands = context "brackets" $ do let getMarshaledCommand = let mcMap = Map.fromList [ (mcName, m) | m@MarshaledCommand {..} <- toList marshaledCommands ] in \c -> note ("Unable to find marshaled command " <> show c) . (`Map.lookup` mcMap) $ c autoBracket' :: BracketType -> CName -> CName -> CName -> Sem r Bracket autoBracket' bracketType create destroy with = do create' <- getMarshaledCommand create destroy' <- getMarshaledCommand destroy autoBracket bracketType create' destroy' with bs <- sequenceV [ autoBracket' BracketCPS "vmaCreateAllocator" "vmaDestroyAllocator" "vmaWithAllocator" , autoBracket' BracketCPS "vmaCreatePool" "vmaDestroyPool" "vmaWithPool" , autoBracket' BracketCPS "vmaAllocateMemory" "vmaFreeMemory" "vmaWithMemory" , autoBracket' BracketCPS "vmaAllocateMemoryForBuffer" "vmaFreeMemory" "vmaWithMemoryForBuffer" , autoBracket' BracketCPS "vmaAllocateMemoryForImage" "vmaFreeMemory" "vmaWithMemoryForImage" , autoBracket' BracketCPS "vmaAllocateMemoryPages" "vmaFreeMemoryPages" "vmaWithMemoryPages" , autoBracket' BracketCPS "vmaMapMemory" "vmaUnmapMemory" "vmaWithMappedMemory" , autoBracket' BracketCPS "vmaBeginDefragmentation" "vmaEndDefragmentation" "vmaWithDefragmentation" , autoBracket' BracketBookend "vmaBeginDefragmentationPass" "vmaEndDefragmentationPass" "vmaUseDefragmentationPass" , autoBracket' BracketCPS "vmaCreateBuffer" "vmaDestroyBuffer" "vmaWithBuffer" , autoBracket' BracketCPS "vmaCreateImage" "vmaDestroyImage" "vmaWithImage" , autoBracket' BracketCPS "vmaCreateVirtualBlock" "vmaDestroyVirtualBlock" "vmaWithVirtualBlock" , autoBracket' BracketCPS "vmaVirtualAllocate" "vmaVirtualFree" "vmaWithVirtualAllocation" ] fromList <$> traverseV (renderBracket paramName) bs paramName :: Text -> Text paramName = unReservedWord . T.lowerCaseFirst . dropVma dropVma :: Text -> Text dropVma t = if "vma" `T.isPrefixOf` T.toLower t then T.dropWhile (== '_') . T.drop 2 $ t else t
null
https://raw.githubusercontent.com/expipiplus1/vulkan/b1e33d1031779b4740c279c68879d05aee371659/generate-new/vma/VMA/Bracket.hs
haskell
module VMA.Bracket ( brackets ) where import Relude hiding ( Handle , Type ) import Data.Vector ( Vector ) import qualified Data.Map as Map import qualified Data.Text.Extra as T import Spec.Name import Bracket import Render.Element import Render.Names import Render.SpecInfo import Error import Marshal.Command import Render.Utils brackets :: forall r . (HasErr r, HasRenderParams r, HasSpecInfo r, HasRenderedNames r) => Vector MarshaledCommand -> Sem r (Vector (CName, CName, RenderElement)) brackets marshaledCommands = context "brackets" $ do let getMarshaledCommand = let mcMap = Map.fromList [ (mcName, m) | m@MarshaledCommand {..} <- toList marshaledCommands ] in \c -> note ("Unable to find marshaled command " <> show c) . (`Map.lookup` mcMap) $ c autoBracket' :: BracketType -> CName -> CName -> CName -> Sem r Bracket autoBracket' bracketType create destroy with = do create' <- getMarshaledCommand create destroy' <- getMarshaledCommand destroy autoBracket bracketType create' destroy' with bs <- sequenceV [ autoBracket' BracketCPS "vmaCreateAllocator" "vmaDestroyAllocator" "vmaWithAllocator" , autoBracket' BracketCPS "vmaCreatePool" "vmaDestroyPool" "vmaWithPool" , autoBracket' BracketCPS "vmaAllocateMemory" "vmaFreeMemory" "vmaWithMemory" , autoBracket' BracketCPS "vmaAllocateMemoryForBuffer" "vmaFreeMemory" "vmaWithMemoryForBuffer" , autoBracket' BracketCPS "vmaAllocateMemoryForImage" "vmaFreeMemory" "vmaWithMemoryForImage" , autoBracket' BracketCPS "vmaAllocateMemoryPages" "vmaFreeMemoryPages" "vmaWithMemoryPages" , autoBracket' BracketCPS "vmaMapMemory" "vmaUnmapMemory" "vmaWithMappedMemory" , autoBracket' BracketCPS "vmaBeginDefragmentation" "vmaEndDefragmentation" "vmaWithDefragmentation" , autoBracket' BracketBookend "vmaBeginDefragmentationPass" "vmaEndDefragmentationPass" "vmaUseDefragmentationPass" , autoBracket' BracketCPS "vmaCreateBuffer" "vmaDestroyBuffer" "vmaWithBuffer" , autoBracket' BracketCPS "vmaCreateImage" "vmaDestroyImage" "vmaWithImage" , autoBracket' BracketCPS "vmaCreateVirtualBlock" "vmaDestroyVirtualBlock" "vmaWithVirtualBlock" , autoBracket' BracketCPS "vmaVirtualAllocate" "vmaVirtualFree" "vmaWithVirtualAllocation" ] fromList <$> traverseV (renderBracket paramName) bs paramName :: Text -> Text paramName = unReservedWord . T.lowerCaseFirst . dropVma dropVma :: Text -> Text dropVma t = if "vma" `T.isPrefixOf` T.toLower t then T.dropWhile (== '_') . T.drop 2 $ t else t
6821240c6765ae551207e0c3f66526015606364dc66301bc8df973564b72c7bd
dpiponi/Moodler
test_arpeggiator.hs
do restart root <- getRoot let out = "out" let keyboard = "keyboard" let trigger = "trigger" arpeggiator0 <- new' "arpeggiator" arpeggiator1 <- new' "arpeggiator" audio_saw2 <- new' "audio_saw" audio_saw3 <- new' "audio_saw" audio_saw4 <- new' "audio_saw" id10 <- new' "id" id11 <- new' "id" id12 <- new' "id" id13 <- new' "id" id14 <- new' "id" id15 <- new' "id" id16 <- new' "id" id17 <- new' "id" id18 <- new' "id" id19 <- new' "id" id20 <- new' "id" id21 <- new' "id" id22 <- new' "id" id23 <- new' "id" id24 <- new' "id" id25 <- new' "id" id5 <- new' "id" id6 <- new' "id" id7 <- new' "id" id8 <- new' "id" id9 <- new' "id" input176 <- new' "input" input26 <- new' "input" input27 <- new' "input" input28 <- new' "input" input29 <- new' "input" input30 <- new' "input" input31 <- new' "input" input32 <- new' "input" new "input" "keyboard" let keyboard = "keyboard" lfo33 <- new' "lfo" lfo34 <- new' "lfo" string_id35 <- new' "string_id" string_id36 <- new' "string_id" string_input37 <- new' "string_input" string_input38 <- new' "string_input" sum39 <- new' "sum" sum40 <- new' "sum" sum441 <- new' "sum4" new "input" "trigger" let trigger = "trigger" vca175 <- new' "vca" container100 <- container' "panel_knob.png" (-348.0,-84.0) (Inside root) in101 <- plugin' (id22 ! "signal") (-360.0,-84.0) (Outside container100) setColour in101 "#control" hide in101 knob102 <- knob' (input29 ! "result") (-360.0,-84.0) (Outside container100) out103 <- plugout' (id22 ! "result") (-324.0,-84.0) (Outside container100) setColour out103 "#control" container104 <- container' "panel_knob.png" (-348.0,0.0) (Inside root) in105 <- plugin' (id10 ! "signal") (-360.0,0.0) (Outside container104) setColour in105 "#control" hide in105 knob106 <- knob' (input30 ! "result") (-360.0,0.0) (Outside container104) out107 <- plugout' (id10 ! "result") (-324.0,0.0) (Outside container104) setColour out107 "#control" container108 <- container' "panel_knob.png" (-348.0,84.0) (Inside root) in109 <- plugin' (id16 ! "signal") (-360.0,84.0) (Outside container108) setColour in109 "#control" hide in109 knob110 <- knob' (input31 ! "result") (-360.0,84.0) (Outside container108) out111 <- plugout' (id16 ! "result") (-324.0,84.0) (Outside container108) setColour out111 "#control" container112 <- container' "panel_lfo.png" (-192.0,-204.0) (Inside root) in113 <- plugin' (lfo34 ! "sync") (-180.0,-180.0) (Outside container112) setColour in113 "#control" in114 <- plugin' (lfo34 ! "rate") (-195.0,-149.0) (Outside container112) setColour in114 "#control" hide in114 knob115 <- knob' (input32 ! "result") (-180.0,-132.0) (Outside container112) out116 <- plugout' (lfo34 ! "triangle") (-204.0,-324.0) (Outside container112) setColour out116 "#control" out117 <- plugout' (lfo34 ! "saw") (-144.0,-324.0) (Outside container112) setColour out117 "#control" out118 <- plugout' (lfo34 ! "sin_result") (-204.0,-288.0) (Outside container112) setColour out118 "#control" out119 <- plugout' (lfo34 ! "square_result") (-144.0,-288.0) (Outside container112) setColour out119 "#control" container120 <- container' "panel_keyboard.png" (-492.0,-24.0) (Inside root) out121 <- plugout' (keyboard ! "result") (-432.0,0.0) (Outside container120) setColour out121 "#control" out122 <- plugout' (trigger ! "result") (-432.0,-48.0) (Outside container120) setColour out122 "#control" container123 <- container' "panel_lfo.png" (12.0,-192.0) (Inside root) in124 <- plugin' (lfo33 ! "sync") (24.0,-168.0) (Outside container123) setColour in124 "#control" in125 <- plugin' (lfo33 ! "rate") (9.0,-137.0) (Outside container123) setColour in125 "#control" hide in125 knob126 <- knob' (input26 ! "result") (24.0,-120.0) (Outside container123) out127 <- plugout' (lfo33 ! "triangle") (0.0,-312.0) (Outside container123) setColour out127 "#control" out128 <- plugout' (lfo33 ! "saw") (60.0,-312.0) (Outside container123) setColour out128 "#control" out129 <- plugout' (lfo33 ! "sin_result") (0.0,-276.0) (Outside container123) setColour out129 "#control" out130 <- plugout' (lfo33 ! "square_result") (60.0,-276.0) (Outside container123) setColour out130 "#control" container131 <- container' "panel_chord.png" (264.0,-168.0) (Inside root) container132 <- container' "panel_proxy.png" (240.0,-272.0) (Outside container131) hide container132 container133 <- container' "panel_3x1.png" (36.0,72.0) (Inside container132) in134 <- plugin' (audio_saw3 ! "sync") (12.0,36.0) (Outside container133) setColour in134 "#sample" in135 <- plugin' (audio_saw3 ! "freq") (12.0,96.0) (Outside container133) setColour in135 "#control" label136 <- label' "audio_saw" (12.0,144.0) (Outside container133) out137 <- plugout' (audio_saw3 ! "result") (60.0,72.0) (Outside container133) setColour out137 "#sample" container138 <- container' "panel_3x1.png" (-48.0,300.0) (Inside container132) in139 <- plugin' (sum40 ! "signal1") (-72.0,324.0) (Outside container138) setColour in139 "#sample" in140 <- plugin' (sum40 ! "signal2") (-72.0,276.0) (Outside container138) setColour in140 "#sample" label141 <- label' "sum" (-72.0,372.0) (Outside container138) out142 <- plugout' (sum40 ! "result") (-36.0,300.0) (Outside container138) setColour out142 "#sample" container143 <- container' "panel_3x1.png" (-132.0,72.0) (Inside container132) in144 <- plugin' (audio_saw4 ! "freq") (-156.0,96.0) (Outside container143) setColour in144 "#control" in145 <- plugin' (audio_saw4 ! "sync") (-156.0,48.0) (Outside container143) setColour in145 "#sample" label146 <- label' "audio_saw" (-156.0,144.0) (Outside container143) out147 <- plugout' (audio_saw4 ! "result") (-120.0,72.0) (Outside container143) setColour out147 "#sample" container148 <- container' "panel_3x1.png" (36.0,300.0) (Inside container132) in149 <- plugin' (sum39 ! "signal1") (12.0,324.0) (Outside container148) setColour in149 "#sample" in150 <- plugin' (sum39 ! "signal2") (12.0,276.0) (Outside container148) setColour in150 "#sample" label151 <- label' "sum" (12.0,372.0) (Outside container148) out152 <- plugout' (sum39 ! "result") (60.0,300.0) (Outside container148) setColour out152 "#sample" container153 <- container' "panel_4x1.png" (120.0,60.0) (Inside container132) in154 <- plugin' (sum441 ! "signal1") (108.0,132.0) (Outside container153) setColour in154 "#sample" in155 <- plugin' (sum441 ! "signal2") (108.0,84.0) (Outside container153) setColour in155 "#sample" in156 <- plugin' (sum441 ! "signal3") (108.0,36.0) (Outside container153) setColour in156 "#sample" in157 <- plugin' (sum441 ! "signal4") (108.0,-12.0) (Outside container153) setColour in157 "#sample" label158 <- label' "sum4" (96.0,132.0) (Outside container153) out159 <- plugout' (sum441 ! "result") (144.0,60.0) (Outside container153) setColour out159 "#sample" container160 <- container' "panel_3x1.png" (-48.0,72.0) (Inside container132) in161 <- plugin' (audio_saw2 ! "freq") (-60.0,96.0) (Outside container160) setColour in161 "#control" in162 <- plugin' (audio_saw2 ! "sync") (-60.0,48.0) (Outside container160) setColour in162 "#sample" label163 <- label' "audio_saw" (-72.0,144.0) (Outside container160) out164 <- plugout' (audio_saw2 ! "result") (-24.0,72.0) (Outside container160) setColour out164 "#sample" in165 <- plugin' (id21 ! "signal") (192.0,60.0) (Inside container132) setColour in165 "#control" out166 <- plugout' (id9 ! "result") (-228.0,120.0) (Inside container132) setColour out166 "#control" out167 <- plugout' (id19 ! "result") (-228.0,72.0) (Inside container132) setColour out167 "#control" out168 <- plugout' (id20 ! "result") (-228.0,24.0) (Inside container132) setColour out168 "#control" in169 <- plugin' (id9 ! "signal") (312.0,-72.0) (Outside container131) setColour in169 "#control" in170 <- plugin' (id19 ! "signal") (312.0,-120.0) (Outside container131) setColour in170 "#control" hide in170 in171 <- plugin' (id20 ! "signal") (312.0,-168.0) (Outside container131) setColour in171 "#control" hide in171 knob172 <- knob' (input27 ! "result") (312.0,-120.0) (Outside container131) knob173 <- knob' (input28 ! "result") (312.0,-168.0) (Outside container131) out174 <- plugout' (id21 ! "result") (312.0,-264.0) (Outside container131) setColour out174 "#sample" container177 <- container' "panel_gain.png" (468.0,-204.0) (Inside root) in178 <- plugin' (vca175 ! "cv") (444.0,-204.0) (Outside container177) setColour in178 "#control" hide in178 in179 <- plugin' (vca175 ! "signal") (408.0,-204.0) (Outside container177) setColour in179 "#sample" knob180 <- knob' (input176 ! "result") (444.0,-204.0) (Outside container177) out181 <- plugout' (vca175 ! "result") (528.0,-204.0) (Outside container177) setColour out181 "#sample" container42 <- container' "panel_arpeggiator.png" (-24.0,180.0) (Inside root) container43 <- container' "panel_4x1.png" (0.0,300.0) (Inside container42) in44 <- plugin' (arpeggiator0 ! "pattern") (-21.0,425.0) (Outside container43) setColour in44 "(0, 0, 1)" in45 <- plugin' (arpeggiator0 ! "trigger") (-21.0,375.0) (Outside container43) setColour in45 "#control" in46 <- plugin' (arpeggiator0 ! "reset") (-21.0,325.0) (Outside container43) setColour in46 "#control" in47 <- plugin' (arpeggiator0 ! "root") (-21.0,275.0) (Outside container43) setColour in47 "#control" in48 <- plugin' (arpeggiator0 ! "interval1") (-21.0,225.0) (Outside container43) setColour in48 "#control" in49 <- plugin' (arpeggiator0 ! "interval2") (-21.0,175.0) (Outside container43) setColour in49 "#control" label50 <- label' "arpeggiator" (-25.0,375.0) (Outside container43) out51 <- plugout' (arpeggiator0 ! "result") (20.0,325.0) (Outside container43) setColour out51 "#control" out52 <- plugout' (arpeggiator0 ! "gate") (20.0,275.0) (Outside container43) setColour out52 "#control" in53 <- plugin' (id17 ! "signal") (44.0,127.0) (Inside container42) setColour in53 "#control" in54 <- plugin' (id18 ! "signal") (56.0,367.0) (Inside container42) setColour in54 "#control" out55 <- plugout' (id11 ! "result") (-119.0,355.0) (Inside container42) setColour out55 "#control" out56 <- plugout' (id12 ! "result") (-119.0,295.0) (Inside container42) setColour out56 "#control" out57 <- plugout' (id13 ! "result") (-119.0,247.0) (Inside container42) setColour out57 "#control" out58 <- plugout' (id14 ! "result") (-119.0,187.0) (Inside container42) setColour out58 "#control" out59 <- plugout' (id15 ! "result") (-119.0,403.0) (Inside container42) setColour out59 "#control" out60 <- plugout' (string_id36 ! "result") (-118.0,469.0) (Inside container42) setColour out60 "(0, 0, 1)" in61 <- plugin' (id11 ! "signal") (-108.0,204.0) (Outside container42) setColour in61 "#control" in62 <- plugin' (id12 ! "signal") (-108.0,132.0) (Outside container42) setColour in62 "#control" in63 <- plugin' (id13 ! "signal") (-108.0,96.0) (Outside container42) setColour in63 "#control" in64 <- plugin' (id14 ! "signal") (-108.0,60.0) (Outside container42) setColour in64 "#control" in65 <- plugin' (id15 ! "signal") (-108.0,168.0) (Outside container42) setColour in65 "#control" in66 <- plugin' (string_id36 ! "input") (-96.0,240.0) (Outside container42) setColour in66 "(0, 0, 1)" hide in66 out67 <- plugout' (id17 ! "result") (60.0,60.0) (Outside container42) setColour out67 "#control" out68 <- plugout' (id18 ! "result") (60.0,96.0) (Outside container42) setColour out68 "#control" textBox69 <- textBox' (string_input38 ! "result") (-96.0,252.0) (Outside container42) container70 <- container' "panel_arpeggiator.png" (204.0,180.0) (Inside root) container71 <- container' "panel_4x1.png" (0.0,300.0) (Inside container70) in72 <- plugin' (arpeggiator1 ! "pattern") (-21.0,425.0) (Outside container71) setColour in72 "(0, 0, 1)" in73 <- plugin' (arpeggiator1 ! "trigger") (-21.0,375.0) (Outside container71) setColour in73 "#control" in74 <- plugin' (arpeggiator1 ! "reset") (-21.0,325.0) (Outside container71) setColour in74 "#control" in75 <- plugin' (arpeggiator1 ! "root") (-21.0,275.0) (Outside container71) setColour in75 "#control" in76 <- plugin' (arpeggiator1 ! "interval1") (-21.0,225.0) (Outside container71) setColour in76 "#control" in77 <- plugin' (arpeggiator1 ! "interval2") (-21.0,175.0) (Outside container71) setColour in77 "#control" label78 <- label' "arpeggiator" (-25.0,375.0) (Outside container71) out79 <- plugout' (arpeggiator1 ! "result") (20.0,325.0) (Outside container71) setColour out79 "#control" out80 <- plugout' (arpeggiator1 ! "gate") (20.0,275.0) (Outside container71) setColour out80 "#control" in81 <- plugin' (id23 ! "signal") (44.0,127.0) (Inside container70) setColour in81 "#control" in82 <- plugin' (id24 ! "signal") (56.0,367.0) (Inside container70) setColour in82 "#control" out83 <- plugout' (id25 ! "result") (-119.0,355.0) (Inside container70) setColour out83 "#control" out84 <- plugout' (id5 ! "result") (-119.0,295.0) (Inside container70) setColour out84 "#control" out85 <- plugout' (id6 ! "result") (-119.0,247.0) (Inside container70) setColour out85 "#control" out86 <- plugout' (id7 ! "result") (-119.0,187.0) (Inside container70) setColour out86 "#control" out87 <- plugout' (id8 ! "result") (-119.0,403.0) (Inside container70) setColour out87 "#control" out88 <- plugout' (string_id35 ! "result") (-118.0,469.0) (Inside container70) setColour out88 "(0, 0, 1)" in89 <- plugin' (id25 ! "signal") (120.0,204.0) (Outside container70) setColour in89 "#control" in90 <- plugin' (id5 ! "signal") (120.0,132.0) (Outside container70) setColour in90 "#control" in91 <- plugin' (id6 ! "signal") (120.0,96.0) (Outside container70) setColour in91 "#control" in92 <- plugin' (id7 ! "signal") (120.0,60.0) (Outside container70) setColour in92 "#control" in93 <- plugin' (id8 ! "signal") (120.0,168.0) (Outside container70) setColour in93 "#control" in94 <- plugin' (string_id35 ! "input") (132.0,240.0) (Outside container70) setColour in94 "(0, 0, 1)" hide in94 out95 <- plugout' (id23 ! "result") (288.0,60.0) (Outside container70) setColour out95 "#control" out96 <- plugout' (id24 ! "result") (288.0,96.0) (Outside container70) setColour out96 "#control" textBox97 <- textBox' (string_input37 ! "result") (132.0,252.0) (Outside container70) container98 <- container' "panel_out.png" (492.0,-36.0) (Inside root) in99 <- plugin' (out ! "value") (468.0,-36.0) (Outside container98) setOutput in99 setColour in99 "#sample" cable knob102 in101 cable knob106 in105 cable knob110 in109 cable knob115 in114 cable knob126 in125 cable out152 in135 cable out167 in139 cable out166 in140 cable out166 in144 cable out168 in149 cable out166 in150 cable out147 in154 cable out164 in155 cable out137 in156 cable out142 in161 cable out159 in165 cable out95 in169 cable knob172 in170 cable knob173 in171 cable knob180 in178 cable out174 in179 cable out60 in44 cable out59 in45 cable out55 in46 cable out56 in47 cable out57 in48 cable out58 in49 cable out51 in53 cable out52 in54 cable out111 in62 cable out107 in63 cable out103 in64 cable out119 in65 cable textBox69 in66 cable out88 in72 cable out87 in73 cable out83 in74 cable out84 in75 cable out85 in76 cable out86 in77 cable out79 in81 cable out80 in82 cable out67 in90 cable out130 in93 cable textBox97 in94 cable out181 in99 recompile set knob102 (-4.1666664e-2) set knob106 (-6.6666655e-2) set knob110 (-0.1) set knob115 (4.0) set knob126 (8.0) set knob172 (0.1) set knob173 (0.2) set knob180 (0.15619478) setString textBox69 ("3(ace)fe2(dab)") setString textBox97 ("a7(/)a5(/)a7(\\)a") return ()
null
https://raw.githubusercontent.com/dpiponi/Moodler/a0c984c36abae52668d00f25eb3749e97e8936d3/Moodler/saves/test_arpeggiator.hs
haskell
do restart root <- getRoot let out = "out" let keyboard = "keyboard" let trigger = "trigger" arpeggiator0 <- new' "arpeggiator" arpeggiator1 <- new' "arpeggiator" audio_saw2 <- new' "audio_saw" audio_saw3 <- new' "audio_saw" audio_saw4 <- new' "audio_saw" id10 <- new' "id" id11 <- new' "id" id12 <- new' "id" id13 <- new' "id" id14 <- new' "id" id15 <- new' "id" id16 <- new' "id" id17 <- new' "id" id18 <- new' "id" id19 <- new' "id" id20 <- new' "id" id21 <- new' "id" id22 <- new' "id" id23 <- new' "id" id24 <- new' "id" id25 <- new' "id" id5 <- new' "id" id6 <- new' "id" id7 <- new' "id" id8 <- new' "id" id9 <- new' "id" input176 <- new' "input" input26 <- new' "input" input27 <- new' "input" input28 <- new' "input" input29 <- new' "input" input30 <- new' "input" input31 <- new' "input" input32 <- new' "input" new "input" "keyboard" let keyboard = "keyboard" lfo33 <- new' "lfo" lfo34 <- new' "lfo" string_id35 <- new' "string_id" string_id36 <- new' "string_id" string_input37 <- new' "string_input" string_input38 <- new' "string_input" sum39 <- new' "sum" sum40 <- new' "sum" sum441 <- new' "sum4" new "input" "trigger" let trigger = "trigger" vca175 <- new' "vca" container100 <- container' "panel_knob.png" (-348.0,-84.0) (Inside root) in101 <- plugin' (id22 ! "signal") (-360.0,-84.0) (Outside container100) setColour in101 "#control" hide in101 knob102 <- knob' (input29 ! "result") (-360.0,-84.0) (Outside container100) out103 <- plugout' (id22 ! "result") (-324.0,-84.0) (Outside container100) setColour out103 "#control" container104 <- container' "panel_knob.png" (-348.0,0.0) (Inside root) in105 <- plugin' (id10 ! "signal") (-360.0,0.0) (Outside container104) setColour in105 "#control" hide in105 knob106 <- knob' (input30 ! "result") (-360.0,0.0) (Outside container104) out107 <- plugout' (id10 ! "result") (-324.0,0.0) (Outside container104) setColour out107 "#control" container108 <- container' "panel_knob.png" (-348.0,84.0) (Inside root) in109 <- plugin' (id16 ! "signal") (-360.0,84.0) (Outside container108) setColour in109 "#control" hide in109 knob110 <- knob' (input31 ! "result") (-360.0,84.0) (Outside container108) out111 <- plugout' (id16 ! "result") (-324.0,84.0) (Outside container108) setColour out111 "#control" container112 <- container' "panel_lfo.png" (-192.0,-204.0) (Inside root) in113 <- plugin' (lfo34 ! "sync") (-180.0,-180.0) (Outside container112) setColour in113 "#control" in114 <- plugin' (lfo34 ! "rate") (-195.0,-149.0) (Outside container112) setColour in114 "#control" hide in114 knob115 <- knob' (input32 ! "result") (-180.0,-132.0) (Outside container112) out116 <- plugout' (lfo34 ! "triangle") (-204.0,-324.0) (Outside container112) setColour out116 "#control" out117 <- plugout' (lfo34 ! "saw") (-144.0,-324.0) (Outside container112) setColour out117 "#control" out118 <- plugout' (lfo34 ! "sin_result") (-204.0,-288.0) (Outside container112) setColour out118 "#control" out119 <- plugout' (lfo34 ! "square_result") (-144.0,-288.0) (Outside container112) setColour out119 "#control" container120 <- container' "panel_keyboard.png" (-492.0,-24.0) (Inside root) out121 <- plugout' (keyboard ! "result") (-432.0,0.0) (Outside container120) setColour out121 "#control" out122 <- plugout' (trigger ! "result") (-432.0,-48.0) (Outside container120) setColour out122 "#control" container123 <- container' "panel_lfo.png" (12.0,-192.0) (Inside root) in124 <- plugin' (lfo33 ! "sync") (24.0,-168.0) (Outside container123) setColour in124 "#control" in125 <- plugin' (lfo33 ! "rate") (9.0,-137.0) (Outside container123) setColour in125 "#control" hide in125 knob126 <- knob' (input26 ! "result") (24.0,-120.0) (Outside container123) out127 <- plugout' (lfo33 ! "triangle") (0.0,-312.0) (Outside container123) setColour out127 "#control" out128 <- plugout' (lfo33 ! "saw") (60.0,-312.0) (Outside container123) setColour out128 "#control" out129 <- plugout' (lfo33 ! "sin_result") (0.0,-276.0) (Outside container123) setColour out129 "#control" out130 <- plugout' (lfo33 ! "square_result") (60.0,-276.0) (Outside container123) setColour out130 "#control" container131 <- container' "panel_chord.png" (264.0,-168.0) (Inside root) container132 <- container' "panel_proxy.png" (240.0,-272.0) (Outside container131) hide container132 container133 <- container' "panel_3x1.png" (36.0,72.0) (Inside container132) in134 <- plugin' (audio_saw3 ! "sync") (12.0,36.0) (Outside container133) setColour in134 "#sample" in135 <- plugin' (audio_saw3 ! "freq") (12.0,96.0) (Outside container133) setColour in135 "#control" label136 <- label' "audio_saw" (12.0,144.0) (Outside container133) out137 <- plugout' (audio_saw3 ! "result") (60.0,72.0) (Outside container133) setColour out137 "#sample" container138 <- container' "panel_3x1.png" (-48.0,300.0) (Inside container132) in139 <- plugin' (sum40 ! "signal1") (-72.0,324.0) (Outside container138) setColour in139 "#sample" in140 <- plugin' (sum40 ! "signal2") (-72.0,276.0) (Outside container138) setColour in140 "#sample" label141 <- label' "sum" (-72.0,372.0) (Outside container138) out142 <- plugout' (sum40 ! "result") (-36.0,300.0) (Outside container138) setColour out142 "#sample" container143 <- container' "panel_3x1.png" (-132.0,72.0) (Inside container132) in144 <- plugin' (audio_saw4 ! "freq") (-156.0,96.0) (Outside container143) setColour in144 "#control" in145 <- plugin' (audio_saw4 ! "sync") (-156.0,48.0) (Outside container143) setColour in145 "#sample" label146 <- label' "audio_saw" (-156.0,144.0) (Outside container143) out147 <- plugout' (audio_saw4 ! "result") (-120.0,72.0) (Outside container143) setColour out147 "#sample" container148 <- container' "panel_3x1.png" (36.0,300.0) (Inside container132) in149 <- plugin' (sum39 ! "signal1") (12.0,324.0) (Outside container148) setColour in149 "#sample" in150 <- plugin' (sum39 ! "signal2") (12.0,276.0) (Outside container148) setColour in150 "#sample" label151 <- label' "sum" (12.0,372.0) (Outside container148) out152 <- plugout' (sum39 ! "result") (60.0,300.0) (Outside container148) setColour out152 "#sample" container153 <- container' "panel_4x1.png" (120.0,60.0) (Inside container132) in154 <- plugin' (sum441 ! "signal1") (108.0,132.0) (Outside container153) setColour in154 "#sample" in155 <- plugin' (sum441 ! "signal2") (108.0,84.0) (Outside container153) setColour in155 "#sample" in156 <- plugin' (sum441 ! "signal3") (108.0,36.0) (Outside container153) setColour in156 "#sample" in157 <- plugin' (sum441 ! "signal4") (108.0,-12.0) (Outside container153) setColour in157 "#sample" label158 <- label' "sum4" (96.0,132.0) (Outside container153) out159 <- plugout' (sum441 ! "result") (144.0,60.0) (Outside container153) setColour out159 "#sample" container160 <- container' "panel_3x1.png" (-48.0,72.0) (Inside container132) in161 <- plugin' (audio_saw2 ! "freq") (-60.0,96.0) (Outside container160) setColour in161 "#control" in162 <- plugin' (audio_saw2 ! "sync") (-60.0,48.0) (Outside container160) setColour in162 "#sample" label163 <- label' "audio_saw" (-72.0,144.0) (Outside container160) out164 <- plugout' (audio_saw2 ! "result") (-24.0,72.0) (Outside container160) setColour out164 "#sample" in165 <- plugin' (id21 ! "signal") (192.0,60.0) (Inside container132) setColour in165 "#control" out166 <- plugout' (id9 ! "result") (-228.0,120.0) (Inside container132) setColour out166 "#control" out167 <- plugout' (id19 ! "result") (-228.0,72.0) (Inside container132) setColour out167 "#control" out168 <- plugout' (id20 ! "result") (-228.0,24.0) (Inside container132) setColour out168 "#control" in169 <- plugin' (id9 ! "signal") (312.0,-72.0) (Outside container131) setColour in169 "#control" in170 <- plugin' (id19 ! "signal") (312.0,-120.0) (Outside container131) setColour in170 "#control" hide in170 in171 <- plugin' (id20 ! "signal") (312.0,-168.0) (Outside container131) setColour in171 "#control" hide in171 knob172 <- knob' (input27 ! "result") (312.0,-120.0) (Outside container131) knob173 <- knob' (input28 ! "result") (312.0,-168.0) (Outside container131) out174 <- plugout' (id21 ! "result") (312.0,-264.0) (Outside container131) setColour out174 "#sample" container177 <- container' "panel_gain.png" (468.0,-204.0) (Inside root) in178 <- plugin' (vca175 ! "cv") (444.0,-204.0) (Outside container177) setColour in178 "#control" hide in178 in179 <- plugin' (vca175 ! "signal") (408.0,-204.0) (Outside container177) setColour in179 "#sample" knob180 <- knob' (input176 ! "result") (444.0,-204.0) (Outside container177) out181 <- plugout' (vca175 ! "result") (528.0,-204.0) (Outside container177) setColour out181 "#sample" container42 <- container' "panel_arpeggiator.png" (-24.0,180.0) (Inside root) container43 <- container' "panel_4x1.png" (0.0,300.0) (Inside container42) in44 <- plugin' (arpeggiator0 ! "pattern") (-21.0,425.0) (Outside container43) setColour in44 "(0, 0, 1)" in45 <- plugin' (arpeggiator0 ! "trigger") (-21.0,375.0) (Outside container43) setColour in45 "#control" in46 <- plugin' (arpeggiator0 ! "reset") (-21.0,325.0) (Outside container43) setColour in46 "#control" in47 <- plugin' (arpeggiator0 ! "root") (-21.0,275.0) (Outside container43) setColour in47 "#control" in48 <- plugin' (arpeggiator0 ! "interval1") (-21.0,225.0) (Outside container43) setColour in48 "#control" in49 <- plugin' (arpeggiator0 ! "interval2") (-21.0,175.0) (Outside container43) setColour in49 "#control" label50 <- label' "arpeggiator" (-25.0,375.0) (Outside container43) out51 <- plugout' (arpeggiator0 ! "result") (20.0,325.0) (Outside container43) setColour out51 "#control" out52 <- plugout' (arpeggiator0 ! "gate") (20.0,275.0) (Outside container43) setColour out52 "#control" in53 <- plugin' (id17 ! "signal") (44.0,127.0) (Inside container42) setColour in53 "#control" in54 <- plugin' (id18 ! "signal") (56.0,367.0) (Inside container42) setColour in54 "#control" out55 <- plugout' (id11 ! "result") (-119.0,355.0) (Inside container42) setColour out55 "#control" out56 <- plugout' (id12 ! "result") (-119.0,295.0) (Inside container42) setColour out56 "#control" out57 <- plugout' (id13 ! "result") (-119.0,247.0) (Inside container42) setColour out57 "#control" out58 <- plugout' (id14 ! "result") (-119.0,187.0) (Inside container42) setColour out58 "#control" out59 <- plugout' (id15 ! "result") (-119.0,403.0) (Inside container42) setColour out59 "#control" out60 <- plugout' (string_id36 ! "result") (-118.0,469.0) (Inside container42) setColour out60 "(0, 0, 1)" in61 <- plugin' (id11 ! "signal") (-108.0,204.0) (Outside container42) setColour in61 "#control" in62 <- plugin' (id12 ! "signal") (-108.0,132.0) (Outside container42) setColour in62 "#control" in63 <- plugin' (id13 ! "signal") (-108.0,96.0) (Outside container42) setColour in63 "#control" in64 <- plugin' (id14 ! "signal") (-108.0,60.0) (Outside container42) setColour in64 "#control" in65 <- plugin' (id15 ! "signal") (-108.0,168.0) (Outside container42) setColour in65 "#control" in66 <- plugin' (string_id36 ! "input") (-96.0,240.0) (Outside container42) setColour in66 "(0, 0, 1)" hide in66 out67 <- plugout' (id17 ! "result") (60.0,60.0) (Outside container42) setColour out67 "#control" out68 <- plugout' (id18 ! "result") (60.0,96.0) (Outside container42) setColour out68 "#control" textBox69 <- textBox' (string_input38 ! "result") (-96.0,252.0) (Outside container42) container70 <- container' "panel_arpeggiator.png" (204.0,180.0) (Inside root) container71 <- container' "panel_4x1.png" (0.0,300.0) (Inside container70) in72 <- plugin' (arpeggiator1 ! "pattern") (-21.0,425.0) (Outside container71) setColour in72 "(0, 0, 1)" in73 <- plugin' (arpeggiator1 ! "trigger") (-21.0,375.0) (Outside container71) setColour in73 "#control" in74 <- plugin' (arpeggiator1 ! "reset") (-21.0,325.0) (Outside container71) setColour in74 "#control" in75 <- plugin' (arpeggiator1 ! "root") (-21.0,275.0) (Outside container71) setColour in75 "#control" in76 <- plugin' (arpeggiator1 ! "interval1") (-21.0,225.0) (Outside container71) setColour in76 "#control" in77 <- plugin' (arpeggiator1 ! "interval2") (-21.0,175.0) (Outside container71) setColour in77 "#control" label78 <- label' "arpeggiator" (-25.0,375.0) (Outside container71) out79 <- plugout' (arpeggiator1 ! "result") (20.0,325.0) (Outside container71) setColour out79 "#control" out80 <- plugout' (arpeggiator1 ! "gate") (20.0,275.0) (Outside container71) setColour out80 "#control" in81 <- plugin' (id23 ! "signal") (44.0,127.0) (Inside container70) setColour in81 "#control" in82 <- plugin' (id24 ! "signal") (56.0,367.0) (Inside container70) setColour in82 "#control" out83 <- plugout' (id25 ! "result") (-119.0,355.0) (Inside container70) setColour out83 "#control" out84 <- plugout' (id5 ! "result") (-119.0,295.0) (Inside container70) setColour out84 "#control" out85 <- plugout' (id6 ! "result") (-119.0,247.0) (Inside container70) setColour out85 "#control" out86 <- plugout' (id7 ! "result") (-119.0,187.0) (Inside container70) setColour out86 "#control" out87 <- plugout' (id8 ! "result") (-119.0,403.0) (Inside container70) setColour out87 "#control" out88 <- plugout' (string_id35 ! "result") (-118.0,469.0) (Inside container70) setColour out88 "(0, 0, 1)" in89 <- plugin' (id25 ! "signal") (120.0,204.0) (Outside container70) setColour in89 "#control" in90 <- plugin' (id5 ! "signal") (120.0,132.0) (Outside container70) setColour in90 "#control" in91 <- plugin' (id6 ! "signal") (120.0,96.0) (Outside container70) setColour in91 "#control" in92 <- plugin' (id7 ! "signal") (120.0,60.0) (Outside container70) setColour in92 "#control" in93 <- plugin' (id8 ! "signal") (120.0,168.0) (Outside container70) setColour in93 "#control" in94 <- plugin' (string_id35 ! "input") (132.0,240.0) (Outside container70) setColour in94 "(0, 0, 1)" hide in94 out95 <- plugout' (id23 ! "result") (288.0,60.0) (Outside container70) setColour out95 "#control" out96 <- plugout' (id24 ! "result") (288.0,96.0) (Outside container70) setColour out96 "#control" textBox97 <- textBox' (string_input37 ! "result") (132.0,252.0) (Outside container70) container98 <- container' "panel_out.png" (492.0,-36.0) (Inside root) in99 <- plugin' (out ! "value") (468.0,-36.0) (Outside container98) setOutput in99 setColour in99 "#sample" cable knob102 in101 cable knob106 in105 cable knob110 in109 cable knob115 in114 cable knob126 in125 cable out152 in135 cable out167 in139 cable out166 in140 cable out166 in144 cable out168 in149 cable out166 in150 cable out147 in154 cable out164 in155 cable out137 in156 cable out142 in161 cable out159 in165 cable out95 in169 cable knob172 in170 cable knob173 in171 cable knob180 in178 cable out174 in179 cable out60 in44 cable out59 in45 cable out55 in46 cable out56 in47 cable out57 in48 cable out58 in49 cable out51 in53 cable out52 in54 cable out111 in62 cable out107 in63 cable out103 in64 cable out119 in65 cable textBox69 in66 cable out88 in72 cable out87 in73 cable out83 in74 cable out84 in75 cable out85 in76 cable out86 in77 cable out79 in81 cable out80 in82 cable out67 in90 cable out130 in93 cable textBox97 in94 cable out181 in99 recompile set knob102 (-4.1666664e-2) set knob106 (-6.6666655e-2) set knob110 (-0.1) set knob115 (4.0) set knob126 (8.0) set knob172 (0.1) set knob173 (0.2) set knob180 (0.15619478) setString textBox69 ("3(ace)fe2(dab)") setString textBox97 ("a7(/)a5(/)a7(\\)a") return ()
a48b5310b6b50fd9b5af1b8638a24e2b65ef6d72dbe6e96cb859154280b0342e
jordanthayer/ocaml-search
timers.ml
* Basic default timing mechanisms for heuristic searches where nodes need to have values intermittently recalculated . When the timers return true , it is time for the values to be recalculated and the queues will need to be resorted then . need to have values intermittently recalculated. When the timers return true, it is time for the values to be recalculated and the queues will need to be resorted then. *) let reckless = (** Never resort. *) (fun () -> false) let conservative = (** always resort *) (fun () -> true) let fixed_durration d = (** Resort every [d] steps. *) let i = ref 0 in (fun () -> if i > d then (i := 0; true) else (i := !i + 1; false)) let geometric d fact = (** Resorts on a geometrically growing scale *) let i = ref 1. and next = ref d in (fun () -> if !i > !next then (next := !next *. fact; true) else (i := !i +. 1.; false)) let random ?(seed = 314159) p = (** Randomly resorts with probability [p] *) Random.init seed; (fun () -> (Random.float 1.) < p) let one_shot d = (** Resorts once at the [d]th step of the algorithm, and then never again *) let i = ref 0 in (fun () -> i := !i + 1; !i = d) EOF
null
https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/search/timers.ml
ocaml
* Never resort. * always resort * Resort every [d] steps. * Resorts on a geometrically growing scale * Randomly resorts with probability [p] * Resorts once at the [d]th step of the algorithm, and then never again
* Basic default timing mechanisms for heuristic searches where nodes need to have values intermittently recalculated . When the timers return true , it is time for the values to be recalculated and the queues will need to be resorted then . need to have values intermittently recalculated. When the timers return true, it is time for the values to be recalculated and the queues will need to be resorted then. *) let reckless = (fun () -> false) let conservative = (fun () -> true) let fixed_durration d = let i = ref 0 in (fun () -> if i > d then (i := 0; true) else (i := !i + 1; false)) let geometric d fact = let i = ref 1. and next = ref d in (fun () -> if !i > !next then (next := !next *. fact; true) else (i := !i +. 1.; false)) let random ?(seed = 314159) p = Random.init seed; (fun () -> (Random.float 1.) < p) let one_shot d = let i = ref 0 in (fun () -> i := !i + 1; !i = d) EOF
9def0c174bacecfc9f8edbc9e26eb91bd9b287974cfee6ee682bd57b350b4b6c
monadbobo/ocaml-core
pSet_test.ml
open OUnit;; open Core.Std let s1 = Set.Poly.of_list ["a"; "b"; "c"; "d"] let = Map.of_alist [ " a",1 ; " c",-3 ; " d",4 ; " e",5 ] let test = "pSet" >::: [ "sexp" >:: (fun () -> let s = "(a b c d)" in let s1' = Set.Poly.t_of_sexp string_of_sexp (Sexp.of_string s) in "of_sexp1" @? (Set.equal s1' s1); let s_dup = "(a b a d)" in let s_dup = Sexp.of_string s_dup in assert_raises (Sexplib.Conv.Of_sexp_error ( Failure "Set.t_of_sexp: duplicate element in set", (sexp_of_string "a"))) (fun () -> Set.Poly.t_of_sexp string_of_sexp s_dup) ); ]
null
https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/lib_test/pSet_test.ml
ocaml
open OUnit;; open Core.Std let s1 = Set.Poly.of_list ["a"; "b"; "c"; "d"] let = Map.of_alist [ " a",1 ; " c",-3 ; " d",4 ; " e",5 ] let test = "pSet" >::: [ "sexp" >:: (fun () -> let s = "(a b c d)" in let s1' = Set.Poly.t_of_sexp string_of_sexp (Sexp.of_string s) in "of_sexp1" @? (Set.equal s1' s1); let s_dup = "(a b a d)" in let s_dup = Sexp.of_string s_dup in assert_raises (Sexplib.Conv.Of_sexp_error ( Failure "Set.t_of_sexp: duplicate element in set", (sexp_of_string "a"))) (fun () -> Set.Poly.t_of_sexp string_of_sexp s_dup) ); ]
740d048bda7a6f7139f5f4b627351140aadff9d94cf6fa81cb4a46bfedc7e36b
aesiniath/unbeliever
Context.hs
# LANGUAGE DeriveFunctor # # LANGUAGE DeriveGeneric # # LANGUAGE DuplicateRecordFields # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE ImportQualifiedPost # # LANGUAGE InstanceSigs # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE StandaloneDeriving # {-# LANGUAGE StrictData #-} # OPTIONS_GHC -fno - warn - orphans # {-# OPTIONS_HADDOCK hide #-} This is an Internal module , hidden from Haddock module Core.Program.Context ( Datum (..) , emptyDatum , Trace (..) , unTrace , Span (..) , unSpan , Context (..) , handleCommandLine , handleVerbosityLevel , handleTelemetryChoice , Exporter (..) , Forwarder (..) , None (..) , isNone , configure , Verbosity (..) , Program (..) , unProgram , getContext , fmapContext , subProgram ) where import Control.Concurrent (ThreadId) import Control.Concurrent.MVar (MVar, newEmptyMVar, newMVar, putMVar, readMVar) import Control.Concurrent.STM.TQueue (TQueue, newTQueueIO) import Control.Concurrent.STM.TVar (TVar, newTVarIO) import Control.Exception.Safe qualified as Safe (throw) import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow (throwM)) import Control.Monad.IO.Unlift (MonadUnliftIO (withRunInIO)) import Control.Monad.Reader.Class (MonadReader (..)) import Control.Monad.Trans.Reader (ReaderT (..)) import Core.Data.Clock import Core.Data.Structures import Core.Encoding.Json import Core.Program.Arguments import Core.Program.Metadata import Core.System.Base import Core.Text.Rope import Data.Foldable (foldrM) import Data.Int (Int64) import Data.String (IsString) import Prettyprinter (LayoutOptions (..), PageWidth (..), layoutPretty) import Prettyprinter.Render.Text (renderIO) import System.Console.Terminal.Size qualified as Terminal (Window (..), size) import System.Environment (getArgs, getProgName, lookupEnv) import System.Exit (ExitCode (..), exitWith) import System.IO (hIsTerminalDevice) import System.Posix.Process qualified as Posix (exitImmediately) import Prelude hiding (log) | Carrier for spans and events while their data is being accumulated , and later sent down the telemetry channel . There is one of these in the Program monad 's Context . Carrier for spans and events while their data is being accumulated, and later sent down the telemetry channel. There is one of these in the Program monad's Context. -} -- `spanIdentifierFrom` is a Maybe because at startup there is not yet a current span . When the first ( root ) span is formed in ` encloseSpan ` it uses -- this as the parent value - in this case, no parent, which is what we want. data Datum = Datum { spanIdentifierFrom :: Maybe Span , spanNameFrom :: Rope , serviceNameFrom :: Maybe Rope , spanTimeFrom :: Time , traceIdentifierFrom :: Maybe Trace , parentIdentifierFrom :: Maybe Span , durationFrom :: Maybe Int64 , attachedMetadataFrom :: Map JsonKey JsonValue } deriving (Show) emptyDatum :: Datum emptyDatum = Datum { spanIdentifierFrom = Nothing , spanNameFrom = emptyRope , serviceNameFrom = Nothing , spanTimeFrom = epochTime , traceIdentifierFrom = Nothing , parentIdentifierFrom = Nothing , durationFrom = Nothing , attachedMetadataFrom = emptyMap } | Unique identifier for a span . This will be generated by ' Core . Telemetry . Observability.encloseSpan ' but for the case where you are continuing an inherited trace and passed the identifier of the parent span you can specify it using this constructor . Unique identifier for a span. This will be generated by 'Core.Telemetry.Observability.encloseSpan' but for the case where you are continuing an inherited trace and passed the identifier of the parent span you can specify it using this constructor. -} newtype Span = Span Rope deriving (Show, Eq, IsString) unSpan :: Span -> Rope unSpan (Span text) = text | Unique identifier for a trace . If your program is the top of an service stack then you can use ' Core . Telemetry . Observability.beginTrace ' to generate a new idenfifier for this request or iteration . More commonly , however , you will inherit the trace identifier from the application or service which invokes this program or request handler , and you can specify it by using ' Core . Telemetry . Observability.usingTrace ' . Unique identifier for a trace. If your program is the top of an service stack then you can use 'Core.Telemetry.Observability.beginTrace' to generate a new idenfifier for this request or iteration. More commonly, however, you will inherit the trace identifier from the application or service which invokes this program or request handler, and you can specify it by using 'Core.Telemetry.Observability.usingTrace'. -} newtype Trace = Trace Rope deriving (Show, Eq, IsString) unTrace :: Trace -> Rope unTrace (Trace text) = text data Exporter = Exporter { codenameFrom :: Rope , setupConfigFrom :: Config -> Config , setupActionFrom :: forall τ. Context τ -> IO Forwarder } {- | Implementation of a forwarder for structured logging of the telemetry channel. -} data Forwarder = Forwarder { telemetryHandlerFrom :: [Datum] -> IO () } | Internal context for a running program . You access this via actions in the ' Program ' monad . The principal item here is the user - supplied top - level application data of type @τ@ which can be retrieved with ' Core . Program . Execute.getApplicationState ' and updated with ' Core . Program . Execute.setApplicationState ' . Internal context for a running program. You access this via actions in the 'Program' monad. The principal item here is the user-supplied top-level application data of type @τ@ which can be retrieved with 'Core.Program.Execute.getApplicationState' and updated with 'Core.Program.Execute.setApplicationState'. -} -- -- The fieldNameFrom idiom is an experiment. Looks very strange, -- certainly, here in the record type definition and when setting -- fields, but for the common case of getting a value out of the -- record, a call like -- -- fieldNameFrom context -- -- isn't bad at all, and no worse than the leading underscore -- convention. -- -- _fieldName context -- -- (I would argue better, since _ is already so overloaded as the wildcard symbol in Haskell ) . Either way , the point is to avoid a -- bare fieldName because so often you have want to be able to use -- that field name as a local variable name. -- data Context τ = Context { programNameFrom :: MVar Rope , terminalWidthFrom :: Int , terminalColouredFrom :: Bool , versionFrom :: Version , initialConfigFrom :: Config -- only used during initial setup , initialExportersFrom :: [Exporter] , commandLineFrom :: Parameters -- derived at startup , exitSemaphoreFrom :: MVar ExitCode , startTimeFrom :: MVar Time , verbosityLevelFrom :: MVar Verbosity , outputSemaphoreFrom :: MVar () , outputChannelFrom :: TQueue (Maybe Rope) -- communication channels , telemetrySemaphoreFrom :: MVar () , telemetryChannelFrom :: TQueue (Maybe Datum) -- machinery for telemetry , telemetryForwarderFrom :: Maybe Forwarder , currentScopeFrom :: TVar (Set ThreadId) , currentDatumFrom :: MVar Datum , applicationDataFrom :: MVar τ } -- I would happily accept critique as to whether this is safe or not. I think -- so? The only way to get to the underlying top-level application data is through ' getApplicationState ' which is in Program monad so the fact that it is implemented within an MVar should be irrelevant . instance Functor Context where fmap f = unsafePerformIO . fmapContext f {- | Map a function over the underlying user-data inside the 'Context', changing it from type@τ1@ to @τ2@. -} fmapContext :: (τ1 -> τ2) -> Context τ1 -> IO (Context τ2) fmapContext f context = do state <- readMVar (applicationDataFrom context) let state' = f state u <- newMVar state' return (context {applicationDataFrom = u}) | A ' Program ' with no user - supplied state to be threaded throughout the computation . The " Core . Program . Execute " framework makes your top - level application state available at the outer level of your process . While this is a feature that most substantial programs rely on , it is /not/ needed for many simple tasks or when first starting out what will become a larger project . This is effectively the unit type , but this alias is here to clearly signal a user - data type is not a part of the program semantics . A 'Program' with no user-supplied state to be threaded throughout the computation. The "Core.Program.Execute" framework makes your top-level application state available at the outer level of your process. While this is a feature that most substantial programs rely on, it is /not/ needed for many simple tasks or when first starting out what will become a larger project. This is effectively the unit type, but this alias is here to clearly signal a user-data type is not a part of the program semantics. -} -- Bids are open for a better name for this data None = None deriving (Show, Eq) isNone :: None -> Bool isNone _ = True | The verbosity level of the output logging subsystem . You can override the level specified on the command - line by calling ' Core . Program . from within the ' Program ' monad . The verbosity level of the output logging subsystem. You can override the level specified on the command-line by calling 'Core.Program.Execute.setVerbosityLevel' from within the 'Program' monad. -} data Verbosity = Output | -- | @since 0.2.12 Verbose | Debug | @since 0.4.6 Internal deriving (Show) | The type of a top - level program . You would use this by writing : @ module Main where import " Core . Program " main : : ' IO ' ( ) main = ' Core.Program.Execute.execute ' program @ and defining a program that is the top level of your application : @ program : : ' Program ' ' None ' ( ) @ Such actions are combinable ; you can sequence them ( using bind in do - notation ) or run them in parallel , but basically you should need one such object at the top of your application . /Type variables/ A ' Program ' has a user - supplied application state and a return type . The first type variable , @τ@ , is your application 's state . This is an object that will be threaded through the computation and made available to your code in the ' Program ' monad . While this is a common requirement of the outer code layer in large programs , it is often /not/ necessary in small programs or when starting new projects . You can mark that there is no top - level application state required using ' None ' and easily change it later if your needs evolve . The return type , @α@ , is usually unit as this effectively being called directly from @main@ and programs have type @'IO ' ( ) @. That is , they do n't return anything ; I / O having already happened as side effects . /Programs in separate modules/ One of the quirks of is that it is difficult to refer to code in the Main module when you 've got a number of programs kicking around in a project each with a @main@ function . One way of dealing with this is to put your top - level ' Program ' actions in a separate modules so you can refer to them from test suites and example snippets . /Interoperating with the rest of the ecosystem/ The ' Program ' monad is a wrapper over ' IO ' ; at any point when you need to move to another package 's entry point , just use ' liftIO ' . It 's re - exported by " Core . System . Base " for your convenience . Later , you might be interested in unlifting back to Program ; see " Core . Program . Unlift " . The type of a top-level program. You would use this by writing: @ module Main where import "Core.Program" main :: 'IO' () main = 'Core.Program.Execute.execute' program @ and defining a program that is the top level of your application: @ program :: 'Program' 'None' () @ Such actions are combinable; you can sequence them (using bind in do-notation) or run them in parallel, but basically you should need one such object at the top of your application. /Type variables/ A 'Program' has a user-supplied application state and a return type. The first type variable, @τ@, is your application's state. This is an object that will be threaded through the computation and made available to your code in the 'Program' monad. While this is a common requirement of the outer code layer in large programs, it is often /not/ necessary in small programs or when starting new projects. You can mark that there is no top-level application state required using 'None' and easily change it later if your needs evolve. The return type, @α@, is usually unit as this effectively being called directly from @main@ and Haskell programs have type @'IO' ()@. That is, they don't return anything; I/O having already happened as side effects. /Programs in separate modules/ One of the quirks of Haskell is that it is difficult to refer to code in the Main module when you've got a number of programs kicking around in a project each with a @main@ function. One way of dealing with this is to put your top-level 'Program' actions in a separate modules so you can refer to them from test suites and example snippets. /Interoperating with the rest of the Haskell ecosystem/ The 'Program' monad is a wrapper over 'IO'; at any point when you need to move to another package's entry point, just use 'liftIO'. It's re-exported by "Core.System.Base" for your convenience. Later, you might be interested in unlifting back to Program; see "Core.Program.Unlift". -} newtype Program τ α = Program (ReaderT (Context τ) IO α) deriving ( Functor , Applicative , Monad , MonadIO , MonadReader (Context τ) , MonadFail ) unProgram :: Program τ α -> ReaderT (Context τ) IO α unProgram (Program r) = r | Get the internal @Context@ of the running @Program@. There is ordinarily no reason to use this ; to access your top - level application data @τ@ within the @Context@ use ' Core . Program . Execute.getApplicationState ' . Get the internal @Context@ of the running @Program@. There is ordinarily no reason to use this; to access your top-level application data @τ@ within the @Context@ use 'Core.Program.Execute.getApplicationState'. -} getContext :: Program τ (Context τ) getContext = do context <- ask pure context # INLINABLE getContext # {- | Run a subprogram from within a lifted @IO@ block. -} subProgram :: Context τ -> Program τ α -> IO α subProgram context (Program r) = do runReaderT r context -- -- This isn't needed by our packages, but it's a useful instance. This is a copy of what is in Core . Program . Unlift.withContext . I would have put this -- there, but it leaves an orphan. -- instance MonadUnliftIO (Program τ) where # INLINE withRunInIO # withRunInIO action = do context <- getContext liftIO $ do action (subProgram context) This is complicated . The * * safe - exceptions * * library exports a ` throwM ` which is not the ` throwM ` class method from MonadThrow . See -exceptions/issues/31 for discussion . In any event , the re - exports flow back to Control . Monad . Catch from * * exceptions * * and Control . Exceptions in * * base * * . In the execute actions , we need to catch everything ( including asynchronous exceptions ) ; elsewhere we will use and wrap / export * * safe - exceptions * * 's variants of the functions . This is complicated. The **safe-exceptions** library exports a `throwM` which is not the `throwM` class method from MonadThrow. See -exceptions/issues/31 for discussion. In any event, the re-exports flow back to Control.Monad.Catch from **exceptions** and Control.Exceptions in **base**. In the execute actions, we need to catch everything (including asynchronous exceptions); elsewhere we will use and wrap/export **safe-exceptions**'s variants of the functions. -} instance MonadThrow (Program τ) where throwM = liftIO . Safe.throw deriving instance MonadCatch (Program τ) deriving instance MonadMask (Program t) | Initialize the programs 's execution context . This takes care of various administrative actions , including setting up output channels , parsing command - line arguments ( according to the supplied configuration ) , and putting in place various semaphores for internal program communication . See " Core . Program . Arguments " for details . This is also where you specify the initial { blank , empty , default ) value for the top - level user - defined application state , if you have one . Specify ' None ' if you are n't using this feature . Initialize the programs's execution context. This takes care of various administrative actions, including setting up output channels, parsing command-line arguments (according to the supplied configuration), and putting in place various semaphores for internal program communication. See "Core.Program.Arguments" for details. This is also where you specify the initial {blank, empty, default) value for the top-level user-defined application state, if you have one. Specify 'None' if you aren't using this feature. -} configure :: Version -> τ -> Config -> IO (Context τ) configure version t config = do start <- getCurrentTimeNanoseconds arg0 <- getProgName n <- newMVar (intoRope arg0) q <- newEmptyMVar i <- newMVar start columns <- getConsoleWidth coloured <- getConsoleColoured level <- newEmptyMVar vo <- newEmptyMVar vl <- newEmptyMVar out <- newTQueueIO tel <- newTQueueIO scope <- newTVarIO emptySet v <- newMVar emptyDatum u <- newMVar t return $! Context { programNameFrom = n , terminalWidthFrom = columns , terminalColouredFrom = coloured , versionFrom = version , initialConfigFrom = config , initialExportersFrom = [] will be filled in handleCommandLine , exitSemaphoreFrom = q , startTimeFrom = i , verbosityLevelFrom = level -- will be filled in handleVerbosityLevel , outputSemaphoreFrom = vo , outputChannelFrom = out , telemetrySemaphoreFrom = vl , telemetryChannelFrom = tel , telemetryForwarderFrom = Nothing , currentScopeFrom = scope , currentDatumFrom = v , applicationDataFrom = u } -- | Probe the width of the terminal , in characters . If it fails to retrieve , for whatever reason , return a default of 80 characters wide . Probe the width of the terminal, in characters. If it fails to retrieve, for whatever reason, return a default of 80 characters wide. -} getConsoleWidth :: IO (Int) getConsoleWidth = do window <- Terminal.size let columns = case window of Just (Terminal.Window _ w) -> w Nothing -> 80 return columns getConsoleColoured :: IO Bool getConsoleColoured = do terminal <- hIsTerminalDevice stdout pure terminal {- | Process the command line options and arguments. If an invalid option is encountered or a [mandatory] argument is missing, then the program will terminate here. -} We came back here with the error case so we can pass config in to buildUsage ( otherwise we could have done it all in displayException and called that in Core . Program . Arguments ) . And , returning here lets us set up the layout width to match ( one off the ) actual width of console . We came back here with the error case so we can pass config in to buildUsage (otherwise we could have done it all in displayException and called that in Core.Program.Arguments). And, returning here lets us set up the layout width to match (one off the) actual width of console. -} handleCommandLine :: Context τ -> IO (Context τ) handleCommandLine context = do argv <- getArgs let config = initialConfigFrom context version = versionFrom context result = parseCommandLine config argv case result of Right parameters -> do pairs <- lookupEnvironmentVariables config parameters let params = parameters { environmentValuesFrom = pairs } -- update the result of all this and return in let context' = context { commandLineFrom = params } pure context' Left e -> case e of HelpRequest mode -> do render (buildUsage config mode) exitWith (ExitFailure 1) VersionRequest -> do render (buildVersion version) exitWith (ExitFailure 1) _ -> do putStr "error: " putStrLn (displayException e) hFlush stdout exitWith (ExitFailure 1) where render message = do columns <- getConsoleWidth let options = LayoutOptions (AvailablePerLine (columns - 1) 1.0) renderIO stdout (layoutPretty options message) hFlush stdout lookupEnvironmentVariables :: Config -> Parameters -> IO (Map LongName ParameterValue) lookupEnvironmentVariables config params = do let mode = commandNameFrom params let valids = extractValidEnvironments mode config result <- foldrM f emptyMap valids return result where f :: LongName -> (Map LongName ParameterValue) -> IO (Map LongName ParameterValue) f name@(LongName var) acc = do result <- lookupEnv var return $ case result of Just value -> insertKeyValue name (Value value) acc Nothing -> insertKeyValue name Empty acc handleVerbosityLevel :: Context τ -> IO (MVar Verbosity) handleVerbosityLevel context = do let params = commandLineFrom context level = verbosityLevelFrom context result = queryVerbosityLevel params case result of Left exit -> do putStrLn "error: To set logging level use --verbose or --debug; neither take a value." hFlush stdout exitWith exit Right verbosity -> do putMVar level verbosity pure level queryVerbosityLevel :: Parameters -> Either ExitCode Verbosity queryVerbosityLevel params = let debug = lookupKeyValue "debug" (parameterValuesFrom params) verbose = lookupKeyValue "verbose" (parameterValuesFrom params) in case debug of Just value -> case value of Empty -> Right Debug Value "internal" -> Right Internal Value _ -> Left (ExitFailure 2) Nothing -> case verbose of Just value -> case value of Empty -> Right Verbose Value _ -> Left (ExitFailure 2) Nothing -> Right Output handleTelemetryChoice :: Context τ -> IO (Context τ) handleTelemetryChoice context = do let params = commandLineFrom context options = parameterValuesFrom params exporters = initialExportersFrom context case lookupKeyValue "telemetry" options of Nothing -> pure context Just Empty -> do putStrLn "error: Need to supply a value when specifiying --telemetry." Posix.exitImmediately (ExitFailure 99) undefined Just (Value value) -> case lookupExporter (intoRope value) exporters of Nothing -> do putStrLn ("error: supplied value \"" ++ value ++ "\" not a valid telemetry exporter.") Posix.exitImmediately (ExitFailure 99) undefined Just exporter -> do let setupAction = setupActionFrom exporter run the IO action to setup the Forwareder forwarder <- setupAction context -- and return it pure context { telemetryForwarderFrom = Just forwarder } where lookupExporter :: Rope -> [Exporter] -> Maybe Exporter lookupExporter _ [] = Nothing lookupExporter target (exporter : exporters) = case target == codenameFrom exporter of False -> lookupExporter target exporters True -> Just exporter
null
https://raw.githubusercontent.com/aesiniath/unbeliever/723d5073189038428f7ad02b0088152bf309bd40/core-program/lib/Core/Program/Context.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # # LANGUAGE StrictData # # OPTIONS_HADDOCK hide # `spanIdentifierFrom` is a Maybe because at startup there is not yet a this as the parent value - in this case, no parent, which is what we want. | Implementation of a forwarder for structured logging of the telemetry channel. The fieldNameFrom idiom is an experiment. Looks very strange, certainly, here in the record type definition and when setting fields, but for the common case of getting a value out of the record, a call like fieldNameFrom context isn't bad at all, and no worse than the leading underscore convention. _fieldName context (I would argue better, since _ is already so overloaded as the bare fieldName because so often you have want to be able to use that field name as a local variable name. only used during initial setup derived at startup communication channels machinery for telemetry I would happily accept critique as to whether this is safe or not. I think so? The only way to get to the underlying top-level application data is | Map a function over the underlying user-data inside the 'Context', changing it from type@τ1@ to @τ2@. Bids are open for a better name for this | @since 0.2.12 | Run a subprogram from within a lifted @IO@ block. This isn't needed by our packages, but it's a useful instance. This is a there, but it leaves an orphan. will be filled in handleVerbosityLevel | Process the command line options and arguments. If an invalid option is encountered or a [mandatory] argument is missing, then the program will terminate here. update the result of all this and return in and return it
# LANGUAGE DeriveFunctor # # LANGUAGE DeriveGeneric # # LANGUAGE DuplicateRecordFields # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE ImportQualifiedPost # # LANGUAGE InstanceSigs # # LANGUAGE MultiParamTypeClasses # # LANGUAGE StandaloneDeriving # # OPTIONS_GHC -fno - warn - orphans # This is an Internal module , hidden from Haddock module Core.Program.Context ( Datum (..) , emptyDatum , Trace (..) , unTrace , Span (..) , unSpan , Context (..) , handleCommandLine , handleVerbosityLevel , handleTelemetryChoice , Exporter (..) , Forwarder (..) , None (..) , isNone , configure , Verbosity (..) , Program (..) , unProgram , getContext , fmapContext , subProgram ) where import Control.Concurrent (ThreadId) import Control.Concurrent.MVar (MVar, newEmptyMVar, newMVar, putMVar, readMVar) import Control.Concurrent.STM.TQueue (TQueue, newTQueueIO) import Control.Concurrent.STM.TVar (TVar, newTVarIO) import Control.Exception.Safe qualified as Safe (throw) import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow (throwM)) import Control.Monad.IO.Unlift (MonadUnliftIO (withRunInIO)) import Control.Monad.Reader.Class (MonadReader (..)) import Control.Monad.Trans.Reader (ReaderT (..)) import Core.Data.Clock import Core.Data.Structures import Core.Encoding.Json import Core.Program.Arguments import Core.Program.Metadata import Core.System.Base import Core.Text.Rope import Data.Foldable (foldrM) import Data.Int (Int64) import Data.String (IsString) import Prettyprinter (LayoutOptions (..), PageWidth (..), layoutPretty) import Prettyprinter.Render.Text (renderIO) import System.Console.Terminal.Size qualified as Terminal (Window (..), size) import System.Environment (getArgs, getProgName, lookupEnv) import System.Exit (ExitCode (..), exitWith) import System.IO (hIsTerminalDevice) import System.Posix.Process qualified as Posix (exitImmediately) import Prelude hiding (log) | Carrier for spans and events while their data is being accumulated , and later sent down the telemetry channel . There is one of these in the Program monad 's Context . Carrier for spans and events while their data is being accumulated, and later sent down the telemetry channel. There is one of these in the Program monad's Context. -} current span . When the first ( root ) span is formed in ` encloseSpan ` it uses data Datum = Datum { spanIdentifierFrom :: Maybe Span , spanNameFrom :: Rope , serviceNameFrom :: Maybe Rope , spanTimeFrom :: Time , traceIdentifierFrom :: Maybe Trace , parentIdentifierFrom :: Maybe Span , durationFrom :: Maybe Int64 , attachedMetadataFrom :: Map JsonKey JsonValue } deriving (Show) emptyDatum :: Datum emptyDatum = Datum { spanIdentifierFrom = Nothing , spanNameFrom = emptyRope , serviceNameFrom = Nothing , spanTimeFrom = epochTime , traceIdentifierFrom = Nothing , parentIdentifierFrom = Nothing , durationFrom = Nothing , attachedMetadataFrom = emptyMap } | Unique identifier for a span . This will be generated by ' Core . Telemetry . Observability.encloseSpan ' but for the case where you are continuing an inherited trace and passed the identifier of the parent span you can specify it using this constructor . Unique identifier for a span. This will be generated by 'Core.Telemetry.Observability.encloseSpan' but for the case where you are continuing an inherited trace and passed the identifier of the parent span you can specify it using this constructor. -} newtype Span = Span Rope deriving (Show, Eq, IsString) unSpan :: Span -> Rope unSpan (Span text) = text | Unique identifier for a trace . If your program is the top of an service stack then you can use ' Core . Telemetry . Observability.beginTrace ' to generate a new idenfifier for this request or iteration . More commonly , however , you will inherit the trace identifier from the application or service which invokes this program or request handler , and you can specify it by using ' Core . Telemetry . Observability.usingTrace ' . Unique identifier for a trace. If your program is the top of an service stack then you can use 'Core.Telemetry.Observability.beginTrace' to generate a new idenfifier for this request or iteration. More commonly, however, you will inherit the trace identifier from the application or service which invokes this program or request handler, and you can specify it by using 'Core.Telemetry.Observability.usingTrace'. -} newtype Trace = Trace Rope deriving (Show, Eq, IsString) unTrace :: Trace -> Rope unTrace (Trace text) = text data Exporter = Exporter { codenameFrom :: Rope , setupConfigFrom :: Config -> Config , setupActionFrom :: forall τ. Context τ -> IO Forwarder } data Forwarder = Forwarder { telemetryHandlerFrom :: [Datum] -> IO () } | Internal context for a running program . You access this via actions in the ' Program ' monad . The principal item here is the user - supplied top - level application data of type @τ@ which can be retrieved with ' Core . Program . Execute.getApplicationState ' and updated with ' Core . Program . Execute.setApplicationState ' . Internal context for a running program. You access this via actions in the 'Program' monad. The principal item here is the user-supplied top-level application data of type @τ@ which can be retrieved with 'Core.Program.Execute.getApplicationState' and updated with 'Core.Program.Execute.setApplicationState'. -} wildcard symbol in Haskell ) . Either way , the point is to avoid a data Context τ = Context { programNameFrom :: MVar Rope , terminalWidthFrom :: Int , terminalColouredFrom :: Bool , versionFrom :: Version , initialExportersFrom :: [Exporter] , exitSemaphoreFrom :: MVar ExitCode , startTimeFrom :: MVar Time , verbosityLevelFrom :: MVar Verbosity , outputSemaphoreFrom :: MVar () , telemetrySemaphoreFrom :: MVar () , telemetryForwarderFrom :: Maybe Forwarder , currentScopeFrom :: TVar (Set ThreadId) , currentDatumFrom :: MVar Datum , applicationDataFrom :: MVar τ } through ' getApplicationState ' which is in Program monad so the fact that it is implemented within an MVar should be irrelevant . instance Functor Context where fmap f = unsafePerformIO . fmapContext f fmapContext :: (τ1 -> τ2) -> Context τ1 -> IO (Context τ2) fmapContext f context = do state <- readMVar (applicationDataFrom context) let state' = f state u <- newMVar state' return (context {applicationDataFrom = u}) | A ' Program ' with no user - supplied state to be threaded throughout the computation . The " Core . Program . Execute " framework makes your top - level application state available at the outer level of your process . While this is a feature that most substantial programs rely on , it is /not/ needed for many simple tasks or when first starting out what will become a larger project . This is effectively the unit type , but this alias is here to clearly signal a user - data type is not a part of the program semantics . A 'Program' with no user-supplied state to be threaded throughout the computation. The "Core.Program.Execute" framework makes your top-level application state available at the outer level of your process. While this is a feature that most substantial programs rely on, it is /not/ needed for many simple tasks or when first starting out what will become a larger project. This is effectively the unit type, but this alias is here to clearly signal a user-data type is not a part of the program semantics. -} data None = None deriving (Show, Eq) isNone :: None -> Bool isNone _ = True | The verbosity level of the output logging subsystem . You can override the level specified on the command - line by calling ' Core . Program . from within the ' Program ' monad . The verbosity level of the output logging subsystem. You can override the level specified on the command-line by calling 'Core.Program.Execute.setVerbosityLevel' from within the 'Program' monad. -} data Verbosity = Output Verbose | Debug | @since 0.4.6 Internal deriving (Show) | The type of a top - level program . You would use this by writing : @ module Main where import " Core . Program " main : : ' IO ' ( ) main = ' Core.Program.Execute.execute ' program @ and defining a program that is the top level of your application : @ program : : ' Program ' ' None ' ( ) @ Such actions are combinable ; you can sequence them ( using bind in do - notation ) or run them in parallel , but basically you should need one such object at the top of your application . /Type variables/ A ' Program ' has a user - supplied application state and a return type . The first type variable , @τ@ , is your application 's state . This is an object that will be threaded through the computation and made available to your code in the ' Program ' monad . While this is a common requirement of the outer code layer in large programs , it is often /not/ necessary in small programs or when starting new projects . You can mark that there is no top - level application state required using ' None ' and easily change it later if your needs evolve . The return type , @α@ , is usually unit as this effectively being called directly from @main@ and programs have type @'IO ' ( ) @. That is , they do n't return anything ; I / O having already happened as side effects . /Programs in separate modules/ One of the quirks of is that it is difficult to refer to code in the Main module when you 've got a number of programs kicking around in a project each with a @main@ function . One way of dealing with this is to put your top - level ' Program ' actions in a separate modules so you can refer to them from test suites and example snippets . /Interoperating with the rest of the ecosystem/ The ' Program ' monad is a wrapper over ' IO ' ; at any point when you need to move to another package 's entry point , just use ' liftIO ' . It 's re - exported by " Core . System . Base " for your convenience . Later , you might be interested in unlifting back to Program ; see " Core . Program . Unlift " . The type of a top-level program. You would use this by writing: @ module Main where import "Core.Program" main :: 'IO' () main = 'Core.Program.Execute.execute' program @ and defining a program that is the top level of your application: @ program :: 'Program' 'None' () @ Such actions are combinable; you can sequence them (using bind in do-notation) or run them in parallel, but basically you should need one such object at the top of your application. /Type variables/ A 'Program' has a user-supplied application state and a return type. The first type variable, @τ@, is your application's state. This is an object that will be threaded through the computation and made available to your code in the 'Program' monad. While this is a common requirement of the outer code layer in large programs, it is often /not/ necessary in small programs or when starting new projects. You can mark that there is no top-level application state required using 'None' and easily change it later if your needs evolve. The return type, @α@, is usually unit as this effectively being called directly from @main@ and Haskell programs have type @'IO' ()@. That is, they don't return anything; I/O having already happened as side effects. /Programs in separate modules/ One of the quirks of Haskell is that it is difficult to refer to code in the Main module when you've got a number of programs kicking around in a project each with a @main@ function. One way of dealing with this is to put your top-level 'Program' actions in a separate modules so you can refer to them from test suites and example snippets. /Interoperating with the rest of the Haskell ecosystem/ The 'Program' monad is a wrapper over 'IO'; at any point when you need to move to another package's entry point, just use 'liftIO'. It's re-exported by "Core.System.Base" for your convenience. Later, you might be interested in unlifting back to Program; see "Core.Program.Unlift". -} newtype Program τ α = Program (ReaderT (Context τ) IO α) deriving ( Functor , Applicative , Monad , MonadIO , MonadReader (Context τ) , MonadFail ) unProgram :: Program τ α -> ReaderT (Context τ) IO α unProgram (Program r) = r | Get the internal @Context@ of the running @Program@. There is ordinarily no reason to use this ; to access your top - level application data @τ@ within the @Context@ use ' Core . Program . Execute.getApplicationState ' . Get the internal @Context@ of the running @Program@. There is ordinarily no reason to use this; to access your top-level application data @τ@ within the @Context@ use 'Core.Program.Execute.getApplicationState'. -} getContext :: Program τ (Context τ) getContext = do context <- ask pure context # INLINABLE getContext # subProgram :: Context τ -> Program τ α -> IO α subProgram context (Program r) = do runReaderT r context copy of what is in Core . Program . Unlift.withContext . I would have put this instance MonadUnliftIO (Program τ) where # INLINE withRunInIO # withRunInIO action = do context <- getContext liftIO $ do action (subProgram context) This is complicated . The * * safe - exceptions * * library exports a ` throwM ` which is not the ` throwM ` class method from MonadThrow . See -exceptions/issues/31 for discussion . In any event , the re - exports flow back to Control . Monad . Catch from * * exceptions * * and Control . Exceptions in * * base * * . In the execute actions , we need to catch everything ( including asynchronous exceptions ) ; elsewhere we will use and wrap / export * * safe - exceptions * * 's variants of the functions . This is complicated. The **safe-exceptions** library exports a `throwM` which is not the `throwM` class method from MonadThrow. See -exceptions/issues/31 for discussion. In any event, the re-exports flow back to Control.Monad.Catch from **exceptions** and Control.Exceptions in **base**. In the execute actions, we need to catch everything (including asynchronous exceptions); elsewhere we will use and wrap/export **safe-exceptions**'s variants of the functions. -} instance MonadThrow (Program τ) where throwM = liftIO . Safe.throw deriving instance MonadCatch (Program τ) deriving instance MonadMask (Program t) | Initialize the programs 's execution context . This takes care of various administrative actions , including setting up output channels , parsing command - line arguments ( according to the supplied configuration ) , and putting in place various semaphores for internal program communication . See " Core . Program . Arguments " for details . This is also where you specify the initial { blank , empty , default ) value for the top - level user - defined application state , if you have one . Specify ' None ' if you are n't using this feature . Initialize the programs's execution context. This takes care of various administrative actions, including setting up output channels, parsing command-line arguments (according to the supplied configuration), and putting in place various semaphores for internal program communication. See "Core.Program.Arguments" for details. This is also where you specify the initial {blank, empty, default) value for the top-level user-defined application state, if you have one. Specify 'None' if you aren't using this feature. -} configure :: Version -> τ -> Config -> IO (Context τ) configure version t config = do start <- getCurrentTimeNanoseconds arg0 <- getProgName n <- newMVar (intoRope arg0) q <- newEmptyMVar i <- newMVar start columns <- getConsoleWidth coloured <- getConsoleColoured level <- newEmptyMVar vo <- newEmptyMVar vl <- newEmptyMVar out <- newTQueueIO tel <- newTQueueIO scope <- newTVarIO emptySet v <- newMVar emptyDatum u <- newMVar t return $! Context { programNameFrom = n , terminalWidthFrom = columns , terminalColouredFrom = coloured , versionFrom = version , initialConfigFrom = config , initialExportersFrom = [] will be filled in handleCommandLine , exitSemaphoreFrom = q , startTimeFrom = i , outputSemaphoreFrom = vo , outputChannelFrom = out , telemetrySemaphoreFrom = vl , telemetryChannelFrom = tel , telemetryForwarderFrom = Nothing , currentScopeFrom = scope , currentDatumFrom = v , applicationDataFrom = u } | Probe the width of the terminal , in characters . If it fails to retrieve , for whatever reason , return a default of 80 characters wide . Probe the width of the terminal, in characters. If it fails to retrieve, for whatever reason, return a default of 80 characters wide. -} getConsoleWidth :: IO (Int) getConsoleWidth = do window <- Terminal.size let columns = case window of Just (Terminal.Window _ w) -> w Nothing -> 80 return columns getConsoleColoured :: IO Bool getConsoleColoured = do terminal <- hIsTerminalDevice stdout pure terminal We came back here with the error case so we can pass config in to buildUsage ( otherwise we could have done it all in displayException and called that in Core . Program . Arguments ) . And , returning here lets us set up the layout width to match ( one off the ) actual width of console . We came back here with the error case so we can pass config in to buildUsage (otherwise we could have done it all in displayException and called that in Core.Program.Arguments). And, returning here lets us set up the layout width to match (one off the) actual width of console. -} handleCommandLine :: Context τ -> IO (Context τ) handleCommandLine context = do argv <- getArgs let config = initialConfigFrom context version = versionFrom context result = parseCommandLine config argv case result of Right parameters -> do pairs <- lookupEnvironmentVariables config parameters let params = parameters { environmentValuesFrom = pairs } let context' = context { commandLineFrom = params } pure context' Left e -> case e of HelpRequest mode -> do render (buildUsage config mode) exitWith (ExitFailure 1) VersionRequest -> do render (buildVersion version) exitWith (ExitFailure 1) _ -> do putStr "error: " putStrLn (displayException e) hFlush stdout exitWith (ExitFailure 1) where render message = do columns <- getConsoleWidth let options = LayoutOptions (AvailablePerLine (columns - 1) 1.0) renderIO stdout (layoutPretty options message) hFlush stdout lookupEnvironmentVariables :: Config -> Parameters -> IO (Map LongName ParameterValue) lookupEnvironmentVariables config params = do let mode = commandNameFrom params let valids = extractValidEnvironments mode config result <- foldrM f emptyMap valids return result where f :: LongName -> (Map LongName ParameterValue) -> IO (Map LongName ParameterValue) f name@(LongName var) acc = do result <- lookupEnv var return $ case result of Just value -> insertKeyValue name (Value value) acc Nothing -> insertKeyValue name Empty acc handleVerbosityLevel :: Context τ -> IO (MVar Verbosity) handleVerbosityLevel context = do let params = commandLineFrom context level = verbosityLevelFrom context result = queryVerbosityLevel params case result of Left exit -> do putStrLn "error: To set logging level use --verbose or --debug; neither take a value." hFlush stdout exitWith exit Right verbosity -> do putMVar level verbosity pure level queryVerbosityLevel :: Parameters -> Either ExitCode Verbosity queryVerbosityLevel params = let debug = lookupKeyValue "debug" (parameterValuesFrom params) verbose = lookupKeyValue "verbose" (parameterValuesFrom params) in case debug of Just value -> case value of Empty -> Right Debug Value "internal" -> Right Internal Value _ -> Left (ExitFailure 2) Nothing -> case verbose of Just value -> case value of Empty -> Right Verbose Value _ -> Left (ExitFailure 2) Nothing -> Right Output handleTelemetryChoice :: Context τ -> IO (Context τ) handleTelemetryChoice context = do let params = commandLineFrom context options = parameterValuesFrom params exporters = initialExportersFrom context case lookupKeyValue "telemetry" options of Nothing -> pure context Just Empty -> do putStrLn "error: Need to supply a value when specifiying --telemetry." Posix.exitImmediately (ExitFailure 99) undefined Just (Value value) -> case lookupExporter (intoRope value) exporters of Nothing -> do putStrLn ("error: supplied value \"" ++ value ++ "\" not a valid telemetry exporter.") Posix.exitImmediately (ExitFailure 99) undefined Just exporter -> do let setupAction = setupActionFrom exporter run the IO action to setup the Forwareder forwarder <- setupAction context pure context { telemetryForwarderFrom = Just forwarder } where lookupExporter :: Rope -> [Exporter] -> Maybe Exporter lookupExporter _ [] = Nothing lookupExporter target (exporter : exporters) = case target == codenameFrom exporter of False -> lookupExporter target exporters True -> Just exporter
bec8ce6483677bd3ae592ce78cf5d6f1d5691c3bf1978c0580c875731ef7ac6e
vincenthz/hs-hourglass
Internal.hs
-- | -- Module : Data.Hourglass.Internal -- License : BSD-style Maintainer : < > -- Stability : experimental -- Portability : unknown -- -- System lowlevel functions -- # LANGUAGE CPP # module Data.Hourglass.Internal ( dateTimeFromUnixEpochP , dateTimeFromUnixEpoch , systemGetTimezone , systemGetElapsed , systemGetElapsedP ) where #ifdef WINDOWS import Data.Hourglass.Internal.Win #else import Data.Hourglass.Internal.Unix #endif
null
https://raw.githubusercontent.com/vincenthz/hs-hourglass/36bd2e6d5d0eb316532f13285d1c533d6da297ef/Data/Hourglass/Internal.hs
haskell
| Module : Data.Hourglass.Internal License : BSD-style Stability : experimental Portability : unknown System lowlevel functions
Maintainer : < > # LANGUAGE CPP # module Data.Hourglass.Internal ( dateTimeFromUnixEpochP , dateTimeFromUnixEpoch , systemGetTimezone , systemGetElapsed , systemGetElapsedP ) where #ifdef WINDOWS import Data.Hourglass.Internal.Win #else import Data.Hourglass.Internal.Unix #endif
d4160529189b363307e1005a92936e37ff5c4427dc7117ffd1bd638b24ec5e22
clojure-interop/aws-api
ContentManagerBuilder.clj
(ns com.amazonaws.services.workdocs.ContentManagerBuilder "Fluent builder for ContentManager. Use of the builder is required instead of constructors of the client class." (:refer-clojure :only [require comment defn ->]) (:import [com.amazonaws.services.workdocs ContentManagerBuilder])) (defn ->content-manager-builder "Constructor." (^ContentManagerBuilder [] (new ContentManagerBuilder ))) (defn *standard "returns: Create new instance of builder with all defaults set. - `com.amazonaws.services.workdocs.ContentManagerBuilder`" (^com.amazonaws.services.workdocs.ContentManagerBuilder [] (ContentManagerBuilder/standard ))) (defn *default-content-manager "returns: Default client. - `com.amazonaws.services.workdocs.ContentManager`" (^com.amazonaws.services.workdocs.ContentManager [] (ContentManagerBuilder/defaultContentManager ))) (defn with-work-docs-client "Sets the low level client used to make the service calls to Amazon WorkDocs. If no client is specified, a default client will be created. work-docs-client - Client implementation to use. - `com.amazonaws.services.workdocs.AmazonWorkDocs` returns: This object for method chaining. - `com.amazonaws.services.workdocs.ContentManagerBuilder`" (^com.amazonaws.services.workdocs.ContentManagerBuilder [^ContentManagerBuilder this ^com.amazonaws.services.workdocs.AmazonWorkDocs work-docs-client] (-> this (.withWorkDocsClient work-docs-client)))) (defn set-work-docs-client "Sets the low level client used to make the service calls to Amazon WorkDocs. If no client is specified, a default client will be created. work-docs-client - Client implementation to use. - `com.amazonaws.services.workdocs.AmazonWorkDocs`" ([^ContentManagerBuilder this ^com.amazonaws.services.workdocs.AmazonWorkDocs work-docs-client] (-> this (.setWorkDocsClient work-docs-client)))) (defn get-work-docs-client "Gets WorkDocs client. returns: WorkDocs client implementation. - `com.amazonaws.services.workdocs.AmazonWorkDocs`" (^com.amazonaws.services.workdocs.AmazonWorkDocs [^ContentManagerBuilder this] (-> this (.getWorkDocsClient)))) (defn with-authentication-token "Sets authentication token for Amazon WorkDocs calls. This is used only for user-level APIs. authentication-token - Token retrieved by OAuth flow. - `java.lang.String` returns: This object for method chaining. - `com.amazonaws.services.workdocs.ContentManagerBuilder`" (^com.amazonaws.services.workdocs.ContentManagerBuilder [^ContentManagerBuilder this ^java.lang.String authentication-token] (-> this (.withAuthenticationToken authentication-token)))) (defn set-authentication-token "Sets authentication token for Amazon WorkDocs calls. This is used only for user-level APIs. authentication-token - Token retrieved by OAuth flow. - `java.lang.String`" ([^ContentManagerBuilder this ^java.lang.String authentication-token] (-> this (.setAuthenticationToken authentication-token)))) (defn get-authentication-token "Gets authentication token for Amazon WorkDocs calls. returns: Token retrieved by OAuth flow. - `java.lang.String`" (^java.lang.String [^ContentManagerBuilder this] (-> this (.getAuthenticationToken)))) (defn build "Construct ContentManager using the current builder configuration. returns: ContentManager object. - `com.amazonaws.services.workdocs.ContentManager`" (^com.amazonaws.services.workdocs.ContentManager [^ContentManagerBuilder this] (-> this (.build))))
null
https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.workdocs/src/com/amazonaws/services/workdocs/ContentManagerBuilder.clj
clojure
(ns com.amazonaws.services.workdocs.ContentManagerBuilder "Fluent builder for ContentManager. Use of the builder is required instead of constructors of the client class." (:refer-clojure :only [require comment defn ->]) (:import [com.amazonaws.services.workdocs ContentManagerBuilder])) (defn ->content-manager-builder "Constructor." (^ContentManagerBuilder [] (new ContentManagerBuilder ))) (defn *standard "returns: Create new instance of builder with all defaults set. - `com.amazonaws.services.workdocs.ContentManagerBuilder`" (^com.amazonaws.services.workdocs.ContentManagerBuilder [] (ContentManagerBuilder/standard ))) (defn *default-content-manager "returns: Default client. - `com.amazonaws.services.workdocs.ContentManager`" (^com.amazonaws.services.workdocs.ContentManager [] (ContentManagerBuilder/defaultContentManager ))) (defn with-work-docs-client "Sets the low level client used to make the service calls to Amazon WorkDocs. If no client is specified, a default client will be created. work-docs-client - Client implementation to use. - `com.amazonaws.services.workdocs.AmazonWorkDocs` returns: This object for method chaining. - `com.amazonaws.services.workdocs.ContentManagerBuilder`" (^com.amazonaws.services.workdocs.ContentManagerBuilder [^ContentManagerBuilder this ^com.amazonaws.services.workdocs.AmazonWorkDocs work-docs-client] (-> this (.withWorkDocsClient work-docs-client)))) (defn set-work-docs-client "Sets the low level client used to make the service calls to Amazon WorkDocs. If no client is specified, a default client will be created. work-docs-client - Client implementation to use. - `com.amazonaws.services.workdocs.AmazonWorkDocs`" ([^ContentManagerBuilder this ^com.amazonaws.services.workdocs.AmazonWorkDocs work-docs-client] (-> this (.setWorkDocsClient work-docs-client)))) (defn get-work-docs-client "Gets WorkDocs client. returns: WorkDocs client implementation. - `com.amazonaws.services.workdocs.AmazonWorkDocs`" (^com.amazonaws.services.workdocs.AmazonWorkDocs [^ContentManagerBuilder this] (-> this (.getWorkDocsClient)))) (defn with-authentication-token "Sets authentication token for Amazon WorkDocs calls. This is used only for user-level APIs. authentication-token - Token retrieved by OAuth flow. - `java.lang.String` returns: This object for method chaining. - `com.amazonaws.services.workdocs.ContentManagerBuilder`" (^com.amazonaws.services.workdocs.ContentManagerBuilder [^ContentManagerBuilder this ^java.lang.String authentication-token] (-> this (.withAuthenticationToken authentication-token)))) (defn set-authentication-token "Sets authentication token for Amazon WorkDocs calls. This is used only for user-level APIs. authentication-token - Token retrieved by OAuth flow. - `java.lang.String`" ([^ContentManagerBuilder this ^java.lang.String authentication-token] (-> this (.setAuthenticationToken authentication-token)))) (defn get-authentication-token "Gets authentication token for Amazon WorkDocs calls. returns: Token retrieved by OAuth flow. - `java.lang.String`" (^java.lang.String [^ContentManagerBuilder this] (-> this (.getAuthenticationToken)))) (defn build "Construct ContentManager using the current builder configuration. returns: ContentManager object. - `com.amazonaws.services.workdocs.ContentManager`" (^com.amazonaws.services.workdocs.ContentManager [^ContentManagerBuilder this] (-> this (.build))))
1ef92dbf517fe0112ec80fad18d73682a2ee3d44d529dad073a04766fa51a434
mfoemmel/erlang-otp
wxPanel.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2008 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% This file is generated DO NOT EDIT %% @doc See external documentation: <a href="">wxPanel</a>. %% <p>This class is derived (and can use functions) from: %% <br />{@link wxWindow} %% <br />{@link wxEvtHandler} %% </p> %% @type wxPanel(). An object reference, The representation is internal %% and can be changed without notice. It can't be used for comparsion %% stored on disc or distributed for use on other nodes. -module(wxPanel). -include("wxe.hrl"). -export([destroy/1,initDialog/1,new/0,new/1,new/2,new/5,new/6]). %% inherited exports -export([cacheBestSize/2,captureMouse/1,center/1,center/2,centerOnParent/1, centerOnParent/2,centre/1,centre/2,centreOnParent/1,centreOnParent/2, clearBackground/1,clientToScreen/2,clientToScreen/3,close/1,close/2, connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2, destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3, enable/1,enable/2,findWindow/2,fit/1,fitInside/1,freeze/1,getAcceleratorTable/1, getBackgroundColour/1,getBackgroundStyle/1,getBestSize/1,getCaret/1, getCharHeight/1,getCharWidth/1,getChildren/1,getClientSize/1,getContainingSizer/1, getCursor/1,getDropTarget/1,getEventHandler/1,getExtraStyle/1,getFont/1, getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1, getId/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1,getParent/1, getPosition/1,getRect/1,getScreenPosition/1,getScreenRect/1,getScrollPos/2, getScrollRange/2,getScrollThumb/2,getSize/1,getSizer/1,getTextExtent/2, getTextExtent/3,getToolTip/1,getUpdateRegion/1,getVirtualSize/1,getWindowStyleFlag/1, getWindowVariant/1,hasCapture/1,hasScrollbar/2,hasTransparentBackground/1, hide/1,inheritAttributes/1,invalidateBestSize/1,isEnabled/1,isExposed/2, isExposed/3,isExposed/5,isRetained/1,isShown/1,isTopLevel/1,layout/1, lineDown/1,lineUp/1,lower/1,makeModal/1,makeModal/2,move/2,move/3,move/4, moveAfterInTabOrder/2,moveBeforeInTabOrder/2,navigate/1,navigate/2, pageDown/1,pageUp/1,parent_class/1,popEventHandler/1,popEventHandler/2, popupMenu/2,popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2, refreshRect/3,releaseMouse/1,removeChild/2,reparent/2,screenToClient/1, screenToClient/2,scrollLines/2,scrollPages/2,scrollWindow/3,scrollWindow/4, setAcceleratorTable/2,setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2, setCaret/2,setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2, setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,setFont/2, setForegroundColour/2,setHelpText/2,setId/2,setLabel/2,setMaxSize/2, setMinSize/2,setName/2,setOwnBackgroundColour/2,setOwnFont/2,setOwnForegroundColour/2, setPalette/2,setScrollPos/3,setScrollPos/4,setScrollbar/5,setScrollbar/6, setSize/2,setSize/3,setSize/5,setSize/6,setSizeHints/2,setSizeHints/3, setSizeHints/4,setSizer/2,setSizer/3,setSizerAndFit/2,setSizerAndFit/3, setThemeEnabled/2,setToolTip/2,setVirtualSize/2,setVirtualSize/3, setVirtualSizeHints/2,setVirtualSizeHints/3,setVirtualSizeHints/4, setWindowStyle/2,setWindowStyleFlag/2,setWindowVariant/2,shouldInheritColours/1, show/1,show/2,thaw/1,transferDataFromWindow/1,transferDataToWindow/1, update/1,updateWindowUI/1,updateWindowUI/2,validate/1,warpPointer/3]). %% @hidden parent_class(wxWindow) -> true; parent_class(wxEvtHandler) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). ( ) - > wxPanel ( ) %% @doc See <a href="#wxpanelwxpanel">external documentation</a>. new() -> wxe_util:construct(?wxPanel_new_0, <<>>). ( Parent::wxWindow : wxWindow ( ) ) - > wxPanel ( ) %% @equiv new(Parent, []) new(Parent) when is_record(Parent, wx_ref) -> new(Parent, []). ( Parent::wxWindow : wxWindow ( ) , [ Option ] ) - > wxPanel ( ) Option = { winid , integer ( ) } | { pos , { X::integer(),Y::integer ( ) } } | { size , { W::integer(),H::integer ( ) } } | { style , integer ( ) } %% @doc See <a href="#wxpanelwxpanel">external documentation</a>. new(#wx_ref{type=ParentT,ref=ParentRef}, Options) when is_list(Options) -> ?CLASS(ParentT,wxWindow), MOpts = fun({winid, Winid}, Acc) -> [<<1:32/?UI,Winid:32/?UI>>|Acc]; ({pos, {PosX,PosY}}, Acc) -> [<<2:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc]; ({size, {SizeW,SizeH}}, Acc) -> [<<3:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc]; ({style, Style}, Acc) -> [<<4:32/?UI,Style:32/?UI>>|Acc]; (BadOpt, _) -> erlang:error({badoption, BadOpt}) end, BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)), wxe_util:construct(?wxPanel_new_2, <<ParentRef:32/?UI, 0:32,BinOpt/binary>>). ( Parent::wxWindow : wxWindow ( ) , X::integer ( ) , Y::integer ( ) , Width::integer ( ) , Height::integer ( ) ) - > wxPanel ( ) @equiv new(Parent , X , Y , , , [ ] ) new(Parent,X,Y,Width,Height) when is_record(Parent, wx_ref),is_integer(X),is_integer(Y),is_integer(Width),is_integer(Height) -> new(Parent,X,Y,Width,Height, []). ( Parent::wxWindow : wxWindow ( ) , X::integer ( ) , Y::integer ( ) , Width::integer ( ) , Height::integer ( ) , [ Option ] ) - > wxPanel ( ) %% Option = {style, integer()} %% @doc See <a href="#wxpanelwxpanel">external documentation</a>. new(#wx_ref{type=ParentT,ref=ParentRef},X,Y,Width,Height, Options) when is_integer(X),is_integer(Y),is_integer(Width),is_integer(Height),is_list(Options) -> ?CLASS(ParentT,wxWindow), MOpts = fun({style, Style}, Acc) -> [<<1:32/?UI,Style:32/?UI>>|Acc]; (BadOpt, _) -> erlang:error({badoption, BadOpt}) end, BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)), wxe_util:construct(?wxPanel_new_6, <<ParentRef:32/?UI,X:32/?UI,Y:32/?UI,Width:32/?UI,Height:32/?UI, 0:32,BinOpt/binary>>). %% @spec (This::wxPanel()) -> ok %% @doc See <a href="#wxpanelinitdialog">external documentation</a>. initDialog(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxPanel), wxe_util:cast(?wxPanel_InitDialog, <<ThisRef:32/?UI>>). %% @spec (This::wxPanel()) -> ok %% @doc Destroys this object, do not use object again destroy(Obj=#wx_ref{type=Type}) -> ?CLASS(Type,wxPanel), wxe_util:destroy(?DESTROY_OBJECT,Obj), ok. %% From wxWindow %% @hidden warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y). %% @hidden validate(This) -> wxWindow:validate(This). %% @hidden updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options). %% @hidden updateWindowUI(This) -> wxWindow:updateWindowUI(This). %% @hidden update(This) -> wxWindow:update(This). %% @hidden transferDataToWindow(This) -> wxWindow:transferDataToWindow(This). %% @hidden transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This). %% @hidden thaw(This) -> wxWindow:thaw(This). %% @hidden show(This, Options) -> wxWindow:show(This, Options). %% @hidden show(This) -> wxWindow:show(This). %% @hidden shouldInheritColours(This) -> wxWindow:shouldInheritColours(This). %% @hidden setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant). %% @hidden setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style). %% @hidden setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style). %% @hidden setVirtualSizeHints(This,MinW,MinH, Options) -> wxWindow:setVirtualSizeHints(This,MinW,MinH, Options). %% @hidden setVirtualSizeHints(This,MinW,MinH) -> wxWindow:setVirtualSizeHints(This,MinW,MinH). %% @hidden setVirtualSizeHints(This,MinSize) -> wxWindow:setVirtualSizeHints(This,MinSize). %% @hidden setVirtualSize(This,X,Y) -> wxWindow:setVirtualSize(This,X,Y). %% @hidden setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size). %% @hidden setToolTip(This,Tip) -> wxWindow:setToolTip(This,Tip). %% @hidden setThemeEnabled(This,EnableTheme) -> wxWindow:setThemeEnabled(This,EnableTheme). %% @hidden setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options). %% @hidden setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer). %% @hidden setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options). %% @hidden setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer). %% @hidden setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options). %% @hidden setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH). %% @hidden setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize). %% @hidden setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options). %% @hidden setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height). %% @hidden setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height). %% @hidden setSize(This,Rect) -> wxWindow:setSize(This,Rect). %% @hidden setScrollPos(This,Orient,Pos, Options) -> wxWindow:setScrollPos(This,Orient,Pos, Options). %% @hidden setScrollPos(This,Orient,Pos) -> wxWindow:setScrollPos(This,Orient,Pos). %% @hidden setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options). %% @hidden setScrollbar(This,Orient,Pos,ThumbVisible,Range) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range). %% @hidden setPalette(This,Pal) -> wxWindow:setPalette(This,Pal). %% @hidden setName(This,Name) -> wxWindow:setName(This,Name). %% @hidden setLabel(This,Label) -> wxWindow:setLabel(This,Label). %% @hidden setId(This,Winid) -> wxWindow:setId(This,Winid). %% @hidden setHelpText(This,Text) -> wxWindow:setHelpText(This,Text). %% @hidden setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour). %% @hidden setFont(This,Font) -> wxWindow:setFont(This,Font). %% @hidden setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This). %% @hidden setFocus(This) -> wxWindow:setFocus(This). %% @hidden setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle). %% @hidden setDropTarget(This,DropTarget) -> wxWindow:setDropTarget(This,DropTarget). %% @hidden setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour). %% @hidden setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font). %% @hidden setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour). %% @hidden setMinSize(This,MinSize) -> wxWindow:setMinSize(This,MinSize). %% @hidden setMaxSize(This,MaxSize) -> wxWindow:setMaxSize(This,MaxSize). %% @hidden setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor). %% @hidden setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer). %% @hidden setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height). %% @hidden setClientSize(This,Size) -> wxWindow:setClientSize(This,Size). %% @hidden setCaret(This,Caret) -> wxWindow:setCaret(This,Caret). %% @hidden setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style). %% @hidden setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour). %% @hidden setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout). %% @hidden setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel). %% @hidden scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options). %% @hidden scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy). %% @hidden scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages). %% @hidden scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines). %% @hidden screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt). %% @hidden screenToClient(This) -> wxWindow:screenToClient(This). %% @hidden reparent(This,NewParent) -> wxWindow:reparent(This,NewParent). %% @hidden removeChild(This,Child) -> wxWindow:removeChild(This,Child). %% @hidden releaseMouse(This) -> wxWindow:releaseMouse(This). %% @hidden refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options). %% @hidden refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect). %% @hidden refresh(This, Options) -> wxWindow:refresh(This, Options). %% @hidden refresh(This) -> wxWindow:refresh(This). %% @hidden raise(This) -> wxWindow:raise(This). %% @hidden popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y). %% @hidden popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options). %% @hidden popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu). %% @hidden popEventHandler(This, Options) -> wxWindow:popEventHandler(This, Options). %% @hidden popEventHandler(This) -> wxWindow:popEventHandler(This). %% @hidden pageUp(This) -> wxWindow:pageUp(This). %% @hidden pageDown(This) -> wxWindow:pageDown(This). %% @hidden navigate(This, Options) -> wxWindow:navigate(This, Options). %% @hidden navigate(This) -> wxWindow:navigate(This). %% @hidden moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win). %% @hidden moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win). %% @hidden move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options). %% @hidden move(This,X,Y) -> wxWindow:move(This,X,Y). %% @hidden move(This,Pt) -> wxWindow:move(This,Pt). %% @hidden makeModal(This, Options) -> wxWindow:makeModal(This, Options). %% @hidden makeModal(This) -> wxWindow:makeModal(This). %% @hidden lower(This) -> wxWindow:lower(This). %% @hidden lineUp(This) -> wxWindow:lineUp(This). %% @hidden lineDown(This) -> wxWindow:lineDown(This). %% @hidden layout(This) -> wxWindow:layout(This). %% @hidden isTopLevel(This) -> wxWindow:isTopLevel(This). %% @hidden isShown(This) -> wxWindow:isShown(This). %% @hidden isRetained(This) -> wxWindow:isRetained(This). %% @hidden isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H). %% @hidden isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y). %% @hidden isExposed(This,Pt) -> wxWindow:isExposed(This,Pt). %% @hidden isEnabled(This) -> wxWindow:isEnabled(This). %% @hidden invalidateBestSize(This) -> wxWindow:invalidateBestSize(This). %% @hidden inheritAttributes(This) -> wxWindow:inheritAttributes(This). %% @hidden hide(This) -> wxWindow:hide(This). %% @hidden hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This). %% @hidden hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient). %% @hidden hasCapture(This) -> wxWindow:hasCapture(This). %% @hidden getWindowVariant(This) -> wxWindow:getWindowVariant(This). %% @hidden getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This). %% @hidden getVirtualSize(This) -> wxWindow:getVirtualSize(This). %% @hidden getUpdateRegion(This) -> wxWindow:getUpdateRegion(This). %% @hidden getToolTip(This) -> wxWindow:getToolTip(This). %% @hidden getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options). %% @hidden getTextExtent(This,String) -> wxWindow:getTextExtent(This,String). %% @hidden getSizer(This) -> wxWindow:getSizer(This). %% @hidden getSize(This) -> wxWindow:getSize(This). %% @hidden getScrollThumb(This,Orient) -> wxWindow:getScrollThumb(This,Orient). %% @hidden getScrollRange(This,Orient) -> wxWindow:getScrollRange(This,Orient). %% @hidden getScrollPos(This,Orient) -> wxWindow:getScrollPos(This,Orient). %% @hidden getScreenRect(This) -> wxWindow:getScreenRect(This). %% @hidden getScreenPosition(This) -> wxWindow:getScreenPosition(This). %% @hidden getRect(This) -> wxWindow:getRect(This). %% @hidden getPosition(This) -> wxWindow:getPosition(This). %% @hidden getParent(This) -> wxWindow:getParent(This). %% @hidden getName(This) -> wxWindow:getName(This). %% @hidden getMinSize(This) -> wxWindow:getMinSize(This). %% @hidden getMaxSize(This) -> wxWindow:getMaxSize(This). %% @hidden getLabel(This) -> wxWindow:getLabel(This). %% @hidden getId(This) -> wxWindow:getId(This). %% @hidden getHelpText(This) -> wxWindow:getHelpText(This). %% @hidden getHandle(This) -> wxWindow:getHandle(This). %% @hidden getGrandParent(This) -> wxWindow:getGrandParent(This). %% @hidden getForegroundColour(This) -> wxWindow:getForegroundColour(This). %% @hidden getFont(This) -> wxWindow:getFont(This). %% @hidden getExtraStyle(This) -> wxWindow:getExtraStyle(This). %% @hidden getEventHandler(This) -> wxWindow:getEventHandler(This). %% @hidden getDropTarget(This) -> wxWindow:getDropTarget(This). %% @hidden getCursor(This) -> wxWindow:getCursor(This). %% @hidden getContainingSizer(This) -> wxWindow:getContainingSizer(This). %% @hidden getClientSize(This) -> wxWindow:getClientSize(This). %% @hidden getChildren(This) -> wxWindow:getChildren(This). %% @hidden getCharWidth(This) -> wxWindow:getCharWidth(This). %% @hidden getCharHeight(This) -> wxWindow:getCharHeight(This). %% @hidden getCaret(This) -> wxWindow:getCaret(This). %% @hidden getBestSize(This) -> wxWindow:getBestSize(This). %% @hidden getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This). %% @hidden getBackgroundColour(This) -> wxWindow:getBackgroundColour(This). %% @hidden getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This). %% @hidden freeze(This) -> wxWindow:freeze(This). %% @hidden fitInside(This) -> wxWindow:fitInside(This). %% @hidden fit(This) -> wxWindow:fit(This). %% @hidden findWindow(This,Winid) -> wxWindow:findWindow(This,Winid). %% @hidden enable(This, Options) -> wxWindow:enable(This, Options). %% @hidden enable(This) -> wxWindow:enable(This). %% @hidden disable(This) -> wxWindow:disable(This). %% @hidden destroyChildren(This) -> wxWindow:destroyChildren(This). %% @hidden convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz). %% @hidden convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz). %% @hidden close(This, Options) -> wxWindow:close(This, Options). %% @hidden close(This) -> wxWindow:close(This). %% @hidden clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y). %% @hidden clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt). %% @hidden clearBackground(This) -> wxWindow:clearBackground(This). %% @hidden centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options). %% @hidden centreOnParent(This) -> wxWindow:centreOnParent(This). %% @hidden centre(This, Options) -> wxWindow:centre(This, Options). %% @hidden centre(This) -> wxWindow:centre(This). %% @hidden centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options). %% @hidden centerOnParent(This) -> wxWindow:centerOnParent(This). %% @hidden center(This, Options) -> wxWindow:center(This, Options). %% @hidden center(This) -> wxWindow:center(This). %% @hidden captureMouse(This) -> wxWindow:captureMouse(This). %% @hidden cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size). %% From wxEvtHandler %% @hidden disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options). %% @hidden disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType). %% @hidden disconnect(This) -> wxEvtHandler:disconnect(This). %% @hidden connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options). %% @hidden connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
null
https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/wx/src/gen/wxPanel.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% This file is generated DO NOT EDIT @doc See external documentation: <a href="">wxPanel</a>. <p>This class is derived (and can use functions) from: <br />{@link wxWindow} <br />{@link wxEvtHandler} </p> @type wxPanel(). An object reference, The representation is internal and can be changed without notice. It can't be used for comparsion stored on disc or distributed for use on other nodes. inherited exports @hidden @doc See <a href="#wxpanelwxpanel">external documentation</a>. @equiv new(Parent, []) @doc See <a href="#wxpanelwxpanel">external documentation</a>. Option = {style, integer()} @doc See <a href="#wxpanelwxpanel">external documentation</a>. @spec (This::wxPanel()) -> ok @doc See <a href="#wxpanelinitdialog">external documentation</a>. @spec (This::wxPanel()) -> ok @doc Destroys this object, do not use object again From wxWindow @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden From wxEvtHandler @hidden @hidden @hidden @hidden @hidden
Copyright Ericsson AB 2008 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(wxPanel). -include("wxe.hrl"). -export([destroy/1,initDialog/1,new/0,new/1,new/2,new/5,new/6]). -export([cacheBestSize/2,captureMouse/1,center/1,center/2,centerOnParent/1, centerOnParent/2,centre/1,centre/2,centreOnParent/1,centreOnParent/2, clearBackground/1,clientToScreen/2,clientToScreen/3,close/1,close/2, connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2, destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3, enable/1,enable/2,findWindow/2,fit/1,fitInside/1,freeze/1,getAcceleratorTable/1, getBackgroundColour/1,getBackgroundStyle/1,getBestSize/1,getCaret/1, getCharHeight/1,getCharWidth/1,getChildren/1,getClientSize/1,getContainingSizer/1, getCursor/1,getDropTarget/1,getEventHandler/1,getExtraStyle/1,getFont/1, getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1, getId/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1,getParent/1, getPosition/1,getRect/1,getScreenPosition/1,getScreenRect/1,getScrollPos/2, getScrollRange/2,getScrollThumb/2,getSize/1,getSizer/1,getTextExtent/2, getTextExtent/3,getToolTip/1,getUpdateRegion/1,getVirtualSize/1,getWindowStyleFlag/1, getWindowVariant/1,hasCapture/1,hasScrollbar/2,hasTransparentBackground/1, hide/1,inheritAttributes/1,invalidateBestSize/1,isEnabled/1,isExposed/2, isExposed/3,isExposed/5,isRetained/1,isShown/1,isTopLevel/1,layout/1, lineDown/1,lineUp/1,lower/1,makeModal/1,makeModal/2,move/2,move/3,move/4, moveAfterInTabOrder/2,moveBeforeInTabOrder/2,navigate/1,navigate/2, pageDown/1,pageUp/1,parent_class/1,popEventHandler/1,popEventHandler/2, popupMenu/2,popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2, refreshRect/3,releaseMouse/1,removeChild/2,reparent/2,screenToClient/1, screenToClient/2,scrollLines/2,scrollPages/2,scrollWindow/3,scrollWindow/4, setAcceleratorTable/2,setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2, setCaret/2,setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2, setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,setFont/2, setForegroundColour/2,setHelpText/2,setId/2,setLabel/2,setMaxSize/2, setMinSize/2,setName/2,setOwnBackgroundColour/2,setOwnFont/2,setOwnForegroundColour/2, setPalette/2,setScrollPos/3,setScrollPos/4,setScrollbar/5,setScrollbar/6, setSize/2,setSize/3,setSize/5,setSize/6,setSizeHints/2,setSizeHints/3, setSizeHints/4,setSizer/2,setSizer/3,setSizerAndFit/2,setSizerAndFit/3, setThemeEnabled/2,setToolTip/2,setVirtualSize/2,setVirtualSize/3, setVirtualSizeHints/2,setVirtualSizeHints/3,setVirtualSizeHints/4, setWindowStyle/2,setWindowStyleFlag/2,setWindowVariant/2,shouldInheritColours/1, show/1,show/2,thaw/1,transferDataFromWindow/1,transferDataToWindow/1, update/1,updateWindowUI/1,updateWindowUI/2,validate/1,warpPointer/3]). parent_class(wxWindow) -> true; parent_class(wxEvtHandler) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). ( ) - > wxPanel ( ) new() -> wxe_util:construct(?wxPanel_new_0, <<>>). ( Parent::wxWindow : wxWindow ( ) ) - > wxPanel ( ) new(Parent) when is_record(Parent, wx_ref) -> new(Parent, []). ( Parent::wxWindow : wxWindow ( ) , [ Option ] ) - > wxPanel ( ) Option = { winid , integer ( ) } | { pos , { X::integer(),Y::integer ( ) } } | { size , { W::integer(),H::integer ( ) } } | { style , integer ( ) } new(#wx_ref{type=ParentT,ref=ParentRef}, Options) when is_list(Options) -> ?CLASS(ParentT,wxWindow), MOpts = fun({winid, Winid}, Acc) -> [<<1:32/?UI,Winid:32/?UI>>|Acc]; ({pos, {PosX,PosY}}, Acc) -> [<<2:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc]; ({size, {SizeW,SizeH}}, Acc) -> [<<3:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc]; ({style, Style}, Acc) -> [<<4:32/?UI,Style:32/?UI>>|Acc]; (BadOpt, _) -> erlang:error({badoption, BadOpt}) end, BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)), wxe_util:construct(?wxPanel_new_2, <<ParentRef:32/?UI, 0:32,BinOpt/binary>>). ( Parent::wxWindow : wxWindow ( ) , X::integer ( ) , Y::integer ( ) , Width::integer ( ) , Height::integer ( ) ) - > wxPanel ( ) @equiv new(Parent , X , Y , , , [ ] ) new(Parent,X,Y,Width,Height) when is_record(Parent, wx_ref),is_integer(X),is_integer(Y),is_integer(Width),is_integer(Height) -> new(Parent,X,Y,Width,Height, []). ( Parent::wxWindow : wxWindow ( ) , X::integer ( ) , Y::integer ( ) , Width::integer ( ) , Height::integer ( ) , [ Option ] ) - > wxPanel ( ) new(#wx_ref{type=ParentT,ref=ParentRef},X,Y,Width,Height, Options) when is_integer(X),is_integer(Y),is_integer(Width),is_integer(Height),is_list(Options) -> ?CLASS(ParentT,wxWindow), MOpts = fun({style, Style}, Acc) -> [<<1:32/?UI,Style:32/?UI>>|Acc]; (BadOpt, _) -> erlang:error({badoption, BadOpt}) end, BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)), wxe_util:construct(?wxPanel_new_6, <<ParentRef:32/?UI,X:32/?UI,Y:32/?UI,Width:32/?UI,Height:32/?UI, 0:32,BinOpt/binary>>). initDialog(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxPanel), wxe_util:cast(?wxPanel_InitDialog, <<ThisRef:32/?UI>>). destroy(Obj=#wx_ref{type=Type}) -> ?CLASS(Type,wxPanel), wxe_util:destroy(?DESTROY_OBJECT,Obj), ok. warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y). validate(This) -> wxWindow:validate(This). updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options). updateWindowUI(This) -> wxWindow:updateWindowUI(This). update(This) -> wxWindow:update(This). transferDataToWindow(This) -> wxWindow:transferDataToWindow(This). transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This). thaw(This) -> wxWindow:thaw(This). show(This, Options) -> wxWindow:show(This, Options). show(This) -> wxWindow:show(This). shouldInheritColours(This) -> wxWindow:shouldInheritColours(This). setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant). setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style). setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style). setVirtualSizeHints(This,MinW,MinH, Options) -> wxWindow:setVirtualSizeHints(This,MinW,MinH, Options). setVirtualSizeHints(This,MinW,MinH) -> wxWindow:setVirtualSizeHints(This,MinW,MinH). setVirtualSizeHints(This,MinSize) -> wxWindow:setVirtualSizeHints(This,MinSize). setVirtualSize(This,X,Y) -> wxWindow:setVirtualSize(This,X,Y). setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size). setToolTip(This,Tip) -> wxWindow:setToolTip(This,Tip). setThemeEnabled(This,EnableTheme) -> wxWindow:setThemeEnabled(This,EnableTheme). setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options). setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer). setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options). setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer). setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options). setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH). setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize). setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options). setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height). setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height). setSize(This,Rect) -> wxWindow:setSize(This,Rect). setScrollPos(This,Orient,Pos, Options) -> wxWindow:setScrollPos(This,Orient,Pos, Options). setScrollPos(This,Orient,Pos) -> wxWindow:setScrollPos(This,Orient,Pos). setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options). setScrollbar(This,Orient,Pos,ThumbVisible,Range) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range). setPalette(This,Pal) -> wxWindow:setPalette(This,Pal). setName(This,Name) -> wxWindow:setName(This,Name). setLabel(This,Label) -> wxWindow:setLabel(This,Label). setId(This,Winid) -> wxWindow:setId(This,Winid). setHelpText(This,Text) -> wxWindow:setHelpText(This,Text). setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour). setFont(This,Font) -> wxWindow:setFont(This,Font). setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This). setFocus(This) -> wxWindow:setFocus(This). setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle). setDropTarget(This,DropTarget) -> wxWindow:setDropTarget(This,DropTarget). setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour). setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font). setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour). setMinSize(This,MinSize) -> wxWindow:setMinSize(This,MinSize). setMaxSize(This,MaxSize) -> wxWindow:setMaxSize(This,MaxSize). setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor). setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer). setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height). setClientSize(This,Size) -> wxWindow:setClientSize(This,Size). setCaret(This,Caret) -> wxWindow:setCaret(This,Caret). setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style). setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour). setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout). setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel). scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options). scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy). scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages). scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines). screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt). screenToClient(This) -> wxWindow:screenToClient(This). reparent(This,NewParent) -> wxWindow:reparent(This,NewParent). removeChild(This,Child) -> wxWindow:removeChild(This,Child). releaseMouse(This) -> wxWindow:releaseMouse(This). refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options). refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect). refresh(This, Options) -> wxWindow:refresh(This, Options). refresh(This) -> wxWindow:refresh(This). raise(This) -> wxWindow:raise(This). popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y). popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options). popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu). popEventHandler(This, Options) -> wxWindow:popEventHandler(This, Options). popEventHandler(This) -> wxWindow:popEventHandler(This). pageUp(This) -> wxWindow:pageUp(This). pageDown(This) -> wxWindow:pageDown(This). navigate(This, Options) -> wxWindow:navigate(This, Options). navigate(This) -> wxWindow:navigate(This). moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win). moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win). move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options). move(This,X,Y) -> wxWindow:move(This,X,Y). move(This,Pt) -> wxWindow:move(This,Pt). makeModal(This, Options) -> wxWindow:makeModal(This, Options). makeModal(This) -> wxWindow:makeModal(This). lower(This) -> wxWindow:lower(This). lineUp(This) -> wxWindow:lineUp(This). lineDown(This) -> wxWindow:lineDown(This). layout(This) -> wxWindow:layout(This). isTopLevel(This) -> wxWindow:isTopLevel(This). isShown(This) -> wxWindow:isShown(This). isRetained(This) -> wxWindow:isRetained(This). isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H). isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y). isExposed(This,Pt) -> wxWindow:isExposed(This,Pt). isEnabled(This) -> wxWindow:isEnabled(This). invalidateBestSize(This) -> wxWindow:invalidateBestSize(This). inheritAttributes(This) -> wxWindow:inheritAttributes(This). hide(This) -> wxWindow:hide(This). hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This). hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient). hasCapture(This) -> wxWindow:hasCapture(This). getWindowVariant(This) -> wxWindow:getWindowVariant(This). getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This). getVirtualSize(This) -> wxWindow:getVirtualSize(This). getUpdateRegion(This) -> wxWindow:getUpdateRegion(This). getToolTip(This) -> wxWindow:getToolTip(This). getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options). getTextExtent(This,String) -> wxWindow:getTextExtent(This,String). getSizer(This) -> wxWindow:getSizer(This). getSize(This) -> wxWindow:getSize(This). getScrollThumb(This,Orient) -> wxWindow:getScrollThumb(This,Orient). getScrollRange(This,Orient) -> wxWindow:getScrollRange(This,Orient). getScrollPos(This,Orient) -> wxWindow:getScrollPos(This,Orient). getScreenRect(This) -> wxWindow:getScreenRect(This). getScreenPosition(This) -> wxWindow:getScreenPosition(This). getRect(This) -> wxWindow:getRect(This). getPosition(This) -> wxWindow:getPosition(This). getParent(This) -> wxWindow:getParent(This). getName(This) -> wxWindow:getName(This). getMinSize(This) -> wxWindow:getMinSize(This). getMaxSize(This) -> wxWindow:getMaxSize(This). getLabel(This) -> wxWindow:getLabel(This). getId(This) -> wxWindow:getId(This). getHelpText(This) -> wxWindow:getHelpText(This). getHandle(This) -> wxWindow:getHandle(This). getGrandParent(This) -> wxWindow:getGrandParent(This). getForegroundColour(This) -> wxWindow:getForegroundColour(This). getFont(This) -> wxWindow:getFont(This). getExtraStyle(This) -> wxWindow:getExtraStyle(This). getEventHandler(This) -> wxWindow:getEventHandler(This). getDropTarget(This) -> wxWindow:getDropTarget(This). getCursor(This) -> wxWindow:getCursor(This). getContainingSizer(This) -> wxWindow:getContainingSizer(This). getClientSize(This) -> wxWindow:getClientSize(This). getChildren(This) -> wxWindow:getChildren(This). getCharWidth(This) -> wxWindow:getCharWidth(This). getCharHeight(This) -> wxWindow:getCharHeight(This). getCaret(This) -> wxWindow:getCaret(This). getBestSize(This) -> wxWindow:getBestSize(This). getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This). getBackgroundColour(This) -> wxWindow:getBackgroundColour(This). getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This). freeze(This) -> wxWindow:freeze(This). fitInside(This) -> wxWindow:fitInside(This). fit(This) -> wxWindow:fit(This). findWindow(This,Winid) -> wxWindow:findWindow(This,Winid). enable(This, Options) -> wxWindow:enable(This, Options). enable(This) -> wxWindow:enable(This). disable(This) -> wxWindow:disable(This). destroyChildren(This) -> wxWindow:destroyChildren(This). convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz). convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz). close(This, Options) -> wxWindow:close(This, Options). close(This) -> wxWindow:close(This). clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y). clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt). clearBackground(This) -> wxWindow:clearBackground(This). centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options). centreOnParent(This) -> wxWindow:centreOnParent(This). centre(This, Options) -> wxWindow:centre(This, Options). centre(This) -> wxWindow:centre(This). centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options). centerOnParent(This) -> wxWindow:centerOnParent(This). center(This, Options) -> wxWindow:center(This, Options). center(This) -> wxWindow:center(This). captureMouse(This) -> wxWindow:captureMouse(This). cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size). disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options). disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType). disconnect(This) -> wxEvtHandler:disconnect(This). connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options). connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
847173955ea293f8787953dfa3e0aee8d5e49b97ebb7e1d4e5ac57cddb1c96f0
raml-org/api-modeling-framework
raml_types_shapes.cljc
(ns api-modeling-framework.parser.domain.raml-types-shapes (:require [api-modeling-framework.model.vocabulary :as v] [api-modeling-framework.model.domain :as domain] [api-modeling-framework.model.document :as document] [api-modeling-framework.model.syntax :as syntax] [api-modeling-framework.utils :as utils] [instaparse.core :as insta] [clojure.string :as string] [taoensso.timbre :as timbre #?(:clj :refer :cljs :refer-macros) [debug]])) (declare parse-type) (def raml-grammar "TYPE_EXPRESSION = TYPE_NAME | SCALAR_TYPE | <'('> <BS> TYPE_EXPRESSION <BS> <')'> | ARRAY_TYPE | UNION_TYPE SCALAR_TYPE = 'string' | 'number' | 'integer' | 'boolean' | 'date-only' | 'time-only' | 'datetime-only' | 'datetime' | 'file' | 'nil' ARRAY_TYPE = TYPE_EXPRESSION <'[]'> TYPE_NAME = #\"(\\w[\\w\\d]+\\.)*\\w[\\w\\d]+\" UNION_TYPE = TYPE_EXPRESSION <BS> (<'|'> <BS> TYPE_EXPRESSION)+ BS = #\"\\s*\" ") (def raml-type-grammar-analyser (insta/parser raml-grammar)) (defn ast->type [ast] (let [type (filterv #(not= % :TYPE_EXPRESSION) ast)] (if (and (= 1 (count type)) (vector? (first type))) (recur (first type)) (condp = (first type) :UNION_TYPE {:type "union" :anyOf (mapv #(ast->type %) (rest type))} :SCALAR_TYPE {:type (last type)} :ARRAY_TYPE {:type "array" :items (ast->type (last type))} :TYPE_NAME (last type) (throw (new #?(:clj Exception :cljs js/Error) (str "Cannot parse type expression AST " (mapv identity type)))))))) (defn parse-type-expression [exp] (try (ast->type (raml-type-grammar-analyser exp)) (catch #?(:clj Exception :cljs js/Error) ex ;;(println (str "Cannot parse type expression '" exp "': " ex)) nil))) (defn inline-json-schema? [node] (and (string? node) (string/starts-with? node "{"))) (defn parse-generic-keywords [node shape] (->> node (mapv (fn [[p v]] (condp = p :displayName #(assoc % v/sorg:name [{"@value" v}]) :description #(assoc % v/sorg:description [{"@value" v}]) identity))) (reduce (fn [acc p] (p acc)) shape))) (defn parse-type-constraints [node shape] (if (map? node) (->> node (mapv (fn [[p v]] (condp = p :minLength #(assoc % (v/sh-ns "minLength") [{"@value" v}]) :maxLength #(assoc % (v/sh-ns "maxLength") [{"@value" v}]) :pattern #(assoc % (v/sh-ns "pattern") [{"@value" v}]) :format #(assoc % (v/shapes-ns "format") [{"@value" v}]) :additionalProperties #(assoc % (v/sh-ns "closed") [{"@value" (not (utils/->bool v))}]) :uniqueItems #(assoc % (v/shapes-ns "uniqueItems") [{"@value" v}]) :multipleOf #(assoc % (v/shapes-ns "multipleOf") [{"@value" v}]) :minimum #(assoc % (v/sh-ns "minExclusive") [{"@value" v}]) :enum #(assoc % (v/sh-ns "in") (->> v (mapv utils/annotation->jsonld))) identity))) (reduce (fn [acc p] (p acc)) shape) (parse-generic-keywords node)) shape)) (defn required-property? [property-name v] (if (some? (:required v)) (:required v) (if (string/ends-with? property-name "?") false true))) (defn final-property-name [property-name v] (if (some? (:required v)) (utils/safe-str property-name) (string/replace (utils/safe-str property-name) #"\?$" ""))) (defn scalar-shape->property-shape [shape] Object properties vs arrays , only one is allowed if it is an object ( or scalar ) (v/sh-ns "maxCount") [{"@value" 1}] ;; instead of node, we have a datatype here (v/sh-ns "dataType") (get shape (v/sh-ns "dataType"))}) (defn array-shape->property-shape [shape] (let [items (get shape (v/shapes-ns "item")) range (if (= 1 (count items)) (first items) {(v/sh-ns "or") {"@list" items}})] {;; we mark it for our own purposes, for example being able to detect ;; it easily without checking cardinality (v/shapes-ns "ordered") [{"@value" true}] ;; range of the prop (v/sh-ns "node") [range]})) (defn node-shape->property-shape [shape] Object properties vs arrays , only one is allowed if it is an object (v/sh-ns "maxCount") [{"@value" 1}] ;; range of the prop (v/sh-ns "node") [shape]}) (defn parse-shape [node {:keys [parsed-location] :as context}] (let [properties (->> (:properties node []) (mapv (fn [[k v]] (let [property-name (utils/safe-str k) required (required-property? property-name v) property-name (final-property-name property-name v) parsed-location (utils/path-join parsed-location (str "/property/" property-name)) parsed-property-target (parse-type v (assoc context :parsed-location parsed-location)) property-shape (cond (utils/scalar-shape? parsed-property-target) (scalar-shape->property-shape parsed-property-target) (utils/array-shape? parsed-property-target) (array-shape->property-shape parsed-property-target) (utils/nil-shape? parsed-property-target) (utils/nil-shape->property-shape) :else (node-shape->property-shape parsed-property-target)) ;; common properties property-shape (-> property-shape (assoc "@id" parsed-location) (assoc "@type" [(v/sh-ns "PropertyShape") (v/sh-ns "Shape")]) (assoc (v/sh-ns "path") [{"@id" (v/anon-shapes-ns property-name)}]) (assoc (v/shapes-ns "propertyLabel") [{"@value" property-name}]) ;; mandatory prop? (assoc (v/sh-ns "minCount") [(if required {"@value" 1} {"@value" 0})]) utils/clean-nils)] (parse-type-constraints v property-shape))))) open-shape (:additionalProperties node)] (->> {"@type" [(v/sh-ns "NodeShape") (v/sh-ns "Shape")] "@id" parsed-location (v/sh-ns "property") properties (v/sh-ns "closed") (if (some? open-shape) [{"@value" (not open-shape)}] nil)} utils/clean-nils (parse-type-constraints node) ))) (defn parse-file-type [node parse-file-type] (->> {"@type" [(v/shapes-ns "FileUpload") (v/sh-ns "Shape")] (v/shapes-ns "fileType") (utils/map-values node :fileTypes)} utils/clean-nils (parse-type-constraints node))) (defn parse-array [node {:keys [parsed-location] :as context}] (let [is-tuple (some? (get node (keyword "(is-tuple)"))) item-types (if is-tuple (-> node :items :of) [(:items node {:type "any"})]) items (mapv (fn [i item-type] (parse-type item-type (assoc context :parsed-location (str parsed-location "/items/" i)))) (range 0 (count item-types)) item-types)] (->> {"@type" [(v/shapes-ns "Array") (v/sh-ns "Shape")] "@id" parsed-location (v/shapes-ns "item") items} (utils/clean-nils) (parse-type-constraints node)))) (defn parse-scalar [parsed-location scalar-type] (-> {"@id" parsed-location "@type" [(v/shapes-ns "Scalar") (v/sh-ns "Shape")] (v/sh-ns "dataType") (if (= "shapes:any" scalar-type) nil [{"@id" scalar-type}])} utils/clean-nils)) (defn parse-json-node [parsed-location text] {"@id" parsed-location "@type" [(v/shapes-ns "JSONSchema") (v/sh-ns "Shape")] (v/shapes-ns "schemaRaw") [{"@value" text}]}) (defn parse-xml-node [parsed-location text] {"@id" parsed-location "@type" [(v/shapes-ns "XMLSchema") (v/sh-ns "Shape") ] (v/shapes-ns "schemaRaw") [{"@value" text}]}) (defn parse-union "Computes multiple-inheritance references" [node {:keys [parsed-location default-type] :as context}] (let [types (:anyOf node) types (mapv #(parse-type % context) types)] {"@id" parsed-location "@type" [(v/shapes-ns "NodeShape") (v/sh-ns "Shape")] (v/shapes-ns "inherits") types})) (defn check-inheritance [node {:keys [location parsed-location] :as context}] (let [location (utils/path-join location "type") child (cond (some? (:properties node)) (parse-type (assoc node :type "object") context) (some? (:items node)) (parse-type (assoc node :type "array") context) :else {"@id" parsed-location "@type" [(v/shapes-ns "NodeShape") (v/sh-ns "Shape")]}) base-type (parse-type (:type node) (-> context (assoc :parsed-location (utils/path-join parsed-location "type")) (assoc :location location)))] (assoc child (v/shapes-ns "inherits") [base-type]))) (defn check-inclusion [node {:keys [parse-ast parsed-location] :as context}] (let [parsed (parse-ast node context) location (syntax/<-location node)] {"@id" parsed-location "@type" [(v/shapes-ns "NodeShape") (v/sh-ns "Shape")] (v/shapes-ns "inherits") [{"@id" location}]})) (defn check-reference "Checks if a provided string points to one of the types defined at the APIDocumentation level" [type-string {:keys [references parsed-location base-uri] :as context}] (if-let [type-reference (utils/type-reference? type-string references)] (let [label (or (-> type-reference :name) (if (satisfies? domain/Type type-reference) (-> type-reference domain/shape :name) nil) type-string)] (cond (some? (:x-ahead-declaration type-reference)) {"@id" parsed-location "@type" [(v/shapes-ns "NodeShape") (v/sh-ns "Shape")] v/sorg:name [{"@value" label}] (v/shapes-ns "inherits") [{"@id" (:x-ahead-declaration type-reference)}]} (satisfies? document/Includes type-reference) {"@id" parsed-location "@type" [(v/shapes-ns "NodeShape") (v/sh-ns "Shape")] (v/shapes-ns "inherits") [{"@id" (document/target type-reference)}]} :else (let [remote-id (-> type-reference domain/shape (get "@id")) label (or (-> type-reference :name) (-> type-reference domain/shape :name) (last (string/split remote-id #"#")))] {"@id" parsed-location v/sorg:name [{"@value" label}] "@type" [(v/shapes-ns "NodeShape") (v/sh-ns "Shape")] (v/shapes-ns "inherits") [{"@id" remote-id}]}))) ;; we always try to return a reference {"@id" parsed-location "@type" [(v/shapes-ns "NodeShape") (v/sh-ns "Shape")] v/sorg:name [{"@value" (utils/hash-path type-string)}] (v/shapes-ns "inherits") [{"@id" (if (= 0 (string/index-of type-string "#")) (str base-uri type-string) type-string)}]})) (defn ensure-raml-type-expression-info-added [shape with-raml-type-expression] (if (some? @with-raml-type-expression) ;; adding the information using a property from the raml shapes vocabulary ;; we could add source maps, but this is more straight forward. ;; @todo Change this into a source map? (assoc shape (v/shapes-ns "ramlTypeExpression") [{"@value" @with-raml-type-expression}]) shape)) (defn parse-well-known-type-string [type-ref node {:keys [parsed-location] :as context}] (cond ;; scalars (= type-ref "string") (parse-type-constraints node (parse-scalar parsed-location (v/xsd-ns "string"))) (= type-ref "number") (parse-type-constraints node (parse-scalar parsed-location (v/xsd-ns "float"))) (= type-ref "integer") (parse-type-constraints node (parse-scalar parsed-location (v/xsd-ns "integer"))) (= type-ref "float") (parse-type-constraints node (parse-scalar parsed-location (v/xsd-ns "float"))) (= type-ref "boolean") (parse-type-constraints node (parse-scalar parsed-location (v/xsd-ns "boolean"))) (= type-ref "null") (parse-type-constraints node (parse-scalar parsed-location (v/shapes-ns "null"))) (= type-ref "time-only") (parse-type-constraints node (parse-scalar parsed-location (v/xsd-ns "time"))) (= type-ref "datetime") (parse-type-constraints node (parse-scalar parsed-location (v/xsd-ns "dateTime"))) (= type-ref "datetime-only") (parse-type-constraints node (parse-scalar parsed-location (v/shapes-ns "datetime-only"))) (= type-ref "date-only") (parse-type-constraints node (parse-scalar parsed-location (v/xsd-ns "date"))) (= type-ref "any") (parse-type-constraints node (parse-scalar parsed-location (v/shapes-ns "any"))) ;; file type (= type-ref "file") (parse-type-constraints node (parse-file-type node parse-file-type)) ;; nil type (= type-ref "nil") (parse-type-constraints node (utils/parse-nil-value context)) ;; object (= type-ref "object") (parse-shape node context) ;; array (= type-ref "array") (parse-array node context) ;; unions (= type-ref "union") (parse-union node context) ;; json schema (and (string? type-ref) (string/starts-with? type-ref "{")) (parse-json-node parsed-location type-ref) ;; xmls schema (and (string? type-ref) (string/starts-with? type-ref "<")) (parse-xml-node parsed-location type-ref) :else nil)) (defn parse-type-reference-link [type-ref with-raml-type-expression {:keys [parsed-location references] :as context}] (cond ;; links to references (utils/type-link? {:type type-ref} references) (check-reference type-ref context) (some? (syntax/<-data type-ref)) (check-inclusion type-ref context) :else ;; type expressions (let [expanded (parse-type-expression type-ref)] (if (or (nil? expanded) (= expanded type-ref)) nil (do (reset! with-raml-type-expression type-ref) (parse-type expanded context)))))) (defn well-known-type? [type-ref] (or ;; scalars (= type-ref "string") (= type-ref "number") (= type-ref "integer") (= type-ref "float") (= type-ref "boolean") (= type-ref "null") (= type-ref "time-only") (= type-ref "datetime") (= type-ref "datetime-only") (= type-ref "date-only") (= type-ref "any") ;; file type (= type-ref "file") ;; nil (= type-ref "nil") ;; object (= type-ref "object") ;; array (= type-ref "array") ;; unions (= type-ref "union") Careful with the next two , starts - with ? ;; automatically transform maps into strings! ;; json schema (and (string? type-ref) (string/starts-with? type-ref "{")) ;; xmls schema (and (string? type-ref) (string/starts-with? type-ref "<")))) (defn parse-type [node {:keys [parsed-location default-type references] :as context}] (let ;; We need to keep the information about the possible raml-type expression ;; only for the type in node. we cannot pass it in the context in the recursive call, ;; We will store the information as a piece of state in closure [with-raml-type-expression (atom nil)] (-> (cond (nil? node) nil (some? (syntax/<-data node)) (check-inclusion node context) (string? node) (or (parse-well-known-type-string node {:type node} context) (parse-type-reference-link node with-raml-type-expression context)) (map? node) (let [type-ref (or (:type node) (:schema node) (or default-type "object"))] (cond ;; it is scalar, an array, regular object or JSON/XML types (well-known-type? type-ref) (parse-well-known-type-string type-ref node context) ;; it is a link to something that is not a well known type: type expression, referference (utils/link-format? node) (parse-type-reference-link type-ref with-raml-type-expression context) :else ;; inheritance, we have properties in this node a (check-inheritance (utils/ensure-type-property node) context))) :else nil) (ensure-raml-type-expression-info-added with-raml-type-expression))))
null
https://raw.githubusercontent.com/raml-org/api-modeling-framework/34bb3b6c3e3f91b775e27f8e389e04eb2c36beb7/src/api_modeling_framework/parser/domain/raml_types_shapes.cljc
clojure
(println (str "Cannot parse type expression '" exp "': " ex)) instead of node, we have a datatype here we mark it for our own purposes, for example being able to detect it easily without checking cardinality range of the prop range of the prop common properties mandatory prop? we always try to return a reference adding the information using a property from the raml shapes vocabulary we could add source maps, but this is more straight forward. @todo Change this into a source map? scalars file type nil type object array unions json schema xmls schema links to references type expressions scalars file type nil object array unions automatically transform maps into strings! json schema xmls schema We need to keep the information about the possible raml-type expression only for the type in node. we cannot pass it in the context in the recursive call, We will store the information as a piece of state in closure it is scalar, an array, regular object or JSON/XML types it is a link to something that is not a well known type: type expression, referference inheritance, we have properties in this node a
(ns api-modeling-framework.parser.domain.raml-types-shapes (:require [api-modeling-framework.model.vocabulary :as v] [api-modeling-framework.model.domain :as domain] [api-modeling-framework.model.document :as document] [api-modeling-framework.model.syntax :as syntax] [api-modeling-framework.utils :as utils] [instaparse.core :as insta] [clojure.string :as string] [taoensso.timbre :as timbre #?(:clj :refer :cljs :refer-macros) [debug]])) (declare parse-type) (def raml-grammar "TYPE_EXPRESSION = TYPE_NAME | SCALAR_TYPE | <'('> <BS> TYPE_EXPRESSION <BS> <')'> | ARRAY_TYPE | UNION_TYPE SCALAR_TYPE = 'string' | 'number' | 'integer' | 'boolean' | 'date-only' | 'time-only' | 'datetime-only' | 'datetime' | 'file' | 'nil' ARRAY_TYPE = TYPE_EXPRESSION <'[]'> TYPE_NAME = #\"(\\w[\\w\\d]+\\.)*\\w[\\w\\d]+\" UNION_TYPE = TYPE_EXPRESSION <BS> (<'|'> <BS> TYPE_EXPRESSION)+ BS = #\"\\s*\" ") (def raml-type-grammar-analyser (insta/parser raml-grammar)) (defn ast->type [ast] (let [type (filterv #(not= % :TYPE_EXPRESSION) ast)] (if (and (= 1 (count type)) (vector? (first type))) (recur (first type)) (condp = (first type) :UNION_TYPE {:type "union" :anyOf (mapv #(ast->type %) (rest type))} :SCALAR_TYPE {:type (last type)} :ARRAY_TYPE {:type "array" :items (ast->type (last type))} :TYPE_NAME (last type) (throw (new #?(:clj Exception :cljs js/Error) (str "Cannot parse type expression AST " (mapv identity type)))))))) (defn parse-type-expression [exp] (try (ast->type (raml-type-grammar-analyser exp)) (catch #?(:clj Exception :cljs js/Error) ex nil))) (defn inline-json-schema? [node] (and (string? node) (string/starts-with? node "{"))) (defn parse-generic-keywords [node shape] (->> node (mapv (fn [[p v]] (condp = p :displayName #(assoc % v/sorg:name [{"@value" v}]) :description #(assoc % v/sorg:description [{"@value" v}]) identity))) (reduce (fn [acc p] (p acc)) shape))) (defn parse-type-constraints [node shape] (if (map? node) (->> node (mapv (fn [[p v]] (condp = p :minLength #(assoc % (v/sh-ns "minLength") [{"@value" v}]) :maxLength #(assoc % (v/sh-ns "maxLength") [{"@value" v}]) :pattern #(assoc % (v/sh-ns "pattern") [{"@value" v}]) :format #(assoc % (v/shapes-ns "format") [{"@value" v}]) :additionalProperties #(assoc % (v/sh-ns "closed") [{"@value" (not (utils/->bool v))}]) :uniqueItems #(assoc % (v/shapes-ns "uniqueItems") [{"@value" v}]) :multipleOf #(assoc % (v/shapes-ns "multipleOf") [{"@value" v}]) :minimum #(assoc % (v/sh-ns "minExclusive") [{"@value" v}]) :enum #(assoc % (v/sh-ns "in") (->> v (mapv utils/annotation->jsonld))) identity))) (reduce (fn [acc p] (p acc)) shape) (parse-generic-keywords node)) shape)) (defn required-property? [property-name v] (if (some? (:required v)) (:required v) (if (string/ends-with? property-name "?") false true))) (defn final-property-name [property-name v] (if (some? (:required v)) (utils/safe-str property-name) (string/replace (utils/safe-str property-name) #"\?$" ""))) (defn scalar-shape->property-shape [shape] Object properties vs arrays , only one is allowed if it is an object ( or scalar ) (v/sh-ns "maxCount") [{"@value" 1}] (v/sh-ns "dataType") (get shape (v/sh-ns "dataType"))}) (defn array-shape->property-shape [shape] (let [items (get shape (v/shapes-ns "item")) range (if (= 1 (count items)) (first items) {(v/sh-ns "or") {"@list" items}})] (v/shapes-ns "ordered") [{"@value" true}] (v/sh-ns "node") [range]})) (defn node-shape->property-shape [shape] Object properties vs arrays , only one is allowed if it is an object (v/sh-ns "maxCount") [{"@value" 1}] (v/sh-ns "node") [shape]}) (defn parse-shape [node {:keys [parsed-location] :as context}] (let [properties (->> (:properties node []) (mapv (fn [[k v]] (let [property-name (utils/safe-str k) required (required-property? property-name v) property-name (final-property-name property-name v) parsed-location (utils/path-join parsed-location (str "/property/" property-name)) parsed-property-target (parse-type v (assoc context :parsed-location parsed-location)) property-shape (cond (utils/scalar-shape? parsed-property-target) (scalar-shape->property-shape parsed-property-target) (utils/array-shape? parsed-property-target) (array-shape->property-shape parsed-property-target) (utils/nil-shape? parsed-property-target) (utils/nil-shape->property-shape) :else (node-shape->property-shape parsed-property-target)) property-shape (-> property-shape (assoc "@id" parsed-location) (assoc "@type" [(v/sh-ns "PropertyShape") (v/sh-ns "Shape")]) (assoc (v/sh-ns "path") [{"@id" (v/anon-shapes-ns property-name)}]) (assoc (v/shapes-ns "propertyLabel") [{"@value" property-name}]) (assoc (v/sh-ns "minCount") [(if required {"@value" 1} {"@value" 0})]) utils/clean-nils)] (parse-type-constraints v property-shape))))) open-shape (:additionalProperties node)] (->> {"@type" [(v/sh-ns "NodeShape") (v/sh-ns "Shape")] "@id" parsed-location (v/sh-ns "property") properties (v/sh-ns "closed") (if (some? open-shape) [{"@value" (not open-shape)}] nil)} utils/clean-nils (parse-type-constraints node) ))) (defn parse-file-type [node parse-file-type] (->> {"@type" [(v/shapes-ns "FileUpload") (v/sh-ns "Shape")] (v/shapes-ns "fileType") (utils/map-values node :fileTypes)} utils/clean-nils (parse-type-constraints node))) (defn parse-array [node {:keys [parsed-location] :as context}] (let [is-tuple (some? (get node (keyword "(is-tuple)"))) item-types (if is-tuple (-> node :items :of) [(:items node {:type "any"})]) items (mapv (fn [i item-type] (parse-type item-type (assoc context :parsed-location (str parsed-location "/items/" i)))) (range 0 (count item-types)) item-types)] (->> {"@type" [(v/shapes-ns "Array") (v/sh-ns "Shape")] "@id" parsed-location (v/shapes-ns "item") items} (utils/clean-nils) (parse-type-constraints node)))) (defn parse-scalar [parsed-location scalar-type] (-> {"@id" parsed-location "@type" [(v/shapes-ns "Scalar") (v/sh-ns "Shape")] (v/sh-ns "dataType") (if (= "shapes:any" scalar-type) nil [{"@id" scalar-type}])} utils/clean-nils)) (defn parse-json-node [parsed-location text] {"@id" parsed-location "@type" [(v/shapes-ns "JSONSchema") (v/sh-ns "Shape")] (v/shapes-ns "schemaRaw") [{"@value" text}]}) (defn parse-xml-node [parsed-location text] {"@id" parsed-location "@type" [(v/shapes-ns "XMLSchema") (v/sh-ns "Shape") ] (v/shapes-ns "schemaRaw") [{"@value" text}]}) (defn parse-union "Computes multiple-inheritance references" [node {:keys [parsed-location default-type] :as context}] (let [types (:anyOf node) types (mapv #(parse-type % context) types)] {"@id" parsed-location "@type" [(v/shapes-ns "NodeShape") (v/sh-ns "Shape")] (v/shapes-ns "inherits") types})) (defn check-inheritance [node {:keys [location parsed-location] :as context}] (let [location (utils/path-join location "type") child (cond (some? (:properties node)) (parse-type (assoc node :type "object") context) (some? (:items node)) (parse-type (assoc node :type "array") context) :else {"@id" parsed-location "@type" [(v/shapes-ns "NodeShape") (v/sh-ns "Shape")]}) base-type (parse-type (:type node) (-> context (assoc :parsed-location (utils/path-join parsed-location "type")) (assoc :location location)))] (assoc child (v/shapes-ns "inherits") [base-type]))) (defn check-inclusion [node {:keys [parse-ast parsed-location] :as context}] (let [parsed (parse-ast node context) location (syntax/<-location node)] {"@id" parsed-location "@type" [(v/shapes-ns "NodeShape") (v/sh-ns "Shape")] (v/shapes-ns "inherits") [{"@id" location}]})) (defn check-reference "Checks if a provided string points to one of the types defined at the APIDocumentation level" [type-string {:keys [references parsed-location base-uri] :as context}] (if-let [type-reference (utils/type-reference? type-string references)] (let [label (or (-> type-reference :name) (if (satisfies? domain/Type type-reference) (-> type-reference domain/shape :name) nil) type-string)] (cond (some? (:x-ahead-declaration type-reference)) {"@id" parsed-location "@type" [(v/shapes-ns "NodeShape") (v/sh-ns "Shape")] v/sorg:name [{"@value" label}] (v/shapes-ns "inherits") [{"@id" (:x-ahead-declaration type-reference)}]} (satisfies? document/Includes type-reference) {"@id" parsed-location "@type" [(v/shapes-ns "NodeShape") (v/sh-ns "Shape")] (v/shapes-ns "inherits") [{"@id" (document/target type-reference)}]} :else (let [remote-id (-> type-reference domain/shape (get "@id")) label (or (-> type-reference :name) (-> type-reference domain/shape :name) (last (string/split remote-id #"#")))] {"@id" parsed-location v/sorg:name [{"@value" label}] "@type" [(v/shapes-ns "NodeShape") (v/sh-ns "Shape")] (v/shapes-ns "inherits") [{"@id" remote-id}]}))) {"@id" parsed-location "@type" [(v/shapes-ns "NodeShape") (v/sh-ns "Shape")] v/sorg:name [{"@value" (utils/hash-path type-string)}] (v/shapes-ns "inherits") [{"@id" (if (= 0 (string/index-of type-string "#")) (str base-uri type-string) type-string)}]})) (defn ensure-raml-type-expression-info-added [shape with-raml-type-expression] (if (some? @with-raml-type-expression) (assoc shape (v/shapes-ns "ramlTypeExpression") [{"@value" @with-raml-type-expression}]) shape)) (defn parse-well-known-type-string [type-ref node {:keys [parsed-location] :as context}] (cond (= type-ref "string") (parse-type-constraints node (parse-scalar parsed-location (v/xsd-ns "string"))) (= type-ref "number") (parse-type-constraints node (parse-scalar parsed-location (v/xsd-ns "float"))) (= type-ref "integer") (parse-type-constraints node (parse-scalar parsed-location (v/xsd-ns "integer"))) (= type-ref "float") (parse-type-constraints node (parse-scalar parsed-location (v/xsd-ns "float"))) (= type-ref "boolean") (parse-type-constraints node (parse-scalar parsed-location (v/xsd-ns "boolean"))) (= type-ref "null") (parse-type-constraints node (parse-scalar parsed-location (v/shapes-ns "null"))) (= type-ref "time-only") (parse-type-constraints node (parse-scalar parsed-location (v/xsd-ns "time"))) (= type-ref "datetime") (parse-type-constraints node (parse-scalar parsed-location (v/xsd-ns "dateTime"))) (= type-ref "datetime-only") (parse-type-constraints node (parse-scalar parsed-location (v/shapes-ns "datetime-only"))) (= type-ref "date-only") (parse-type-constraints node (parse-scalar parsed-location (v/xsd-ns "date"))) (= type-ref "any") (parse-type-constraints node (parse-scalar parsed-location (v/shapes-ns "any"))) (= type-ref "file") (parse-type-constraints node (parse-file-type node parse-file-type)) (= type-ref "nil") (parse-type-constraints node (utils/parse-nil-value context)) (= type-ref "object") (parse-shape node context) (= type-ref "array") (parse-array node context) (= type-ref "union") (parse-union node context) (and (string? type-ref) (string/starts-with? type-ref "{")) (parse-json-node parsed-location type-ref) (and (string? type-ref) (string/starts-with? type-ref "<")) (parse-xml-node parsed-location type-ref) :else nil)) (defn parse-type-reference-link [type-ref with-raml-type-expression {:keys [parsed-location references] :as context}] (cond (utils/type-link? {:type type-ref} references) (check-reference type-ref context) (some? (syntax/<-data type-ref)) (check-inclusion type-ref context) (let [expanded (parse-type-expression type-ref)] (if (or (nil? expanded) (= expanded type-ref)) nil (do (reset! with-raml-type-expression type-ref) (parse-type expanded context)))))) (defn well-known-type? [type-ref] (or (= type-ref "string") (= type-ref "number") (= type-ref "integer") (= type-ref "float") (= type-ref "boolean") (= type-ref "null") (= type-ref "time-only") (= type-ref "datetime") (= type-ref "datetime-only") (= type-ref "date-only") (= type-ref "any") (= type-ref "file") (= type-ref "nil") (= type-ref "object") (= type-ref "array") (= type-ref "union") Careful with the next two , starts - with ? (and (string? type-ref) (string/starts-with? type-ref "{")) (and (string? type-ref) (string/starts-with? type-ref "<")))) (defn parse-type [node {:keys [parsed-location default-type references] :as context}] (let [with-raml-type-expression (atom nil)] (-> (cond (nil? node) nil (some? (syntax/<-data node)) (check-inclusion node context) (string? node) (or (parse-well-known-type-string node {:type node} context) (parse-type-reference-link node with-raml-type-expression context)) (map? node) (let [type-ref (or (:type node) (:schema node) (or default-type "object"))] (cond (well-known-type? type-ref) (parse-well-known-type-string type-ref node context) (utils/link-format? node) (parse-type-reference-link type-ref with-raml-type-expression context) :else (check-inheritance (utils/ensure-type-property node) context))) :else nil) (ensure-raml-type-expression-info-added with-raml-type-expression))))
5c20322593e0a6d6db61e62a132054bc45c197b8a1d875821e5c32237d39f2d6
expipiplus1/vulkan
ShaderType.hs
module Vulkan.Utils.ShaderQQ.ShaderType ( ShaderType (..) ) where import Data.String (IsString (..)) data ShaderType = GLSL | HLSL instance IsString ShaderType where fromString = \case "glsl" -> GLSL "hlsl" -> HLSL t -> error $ "not support '" ++ t ++ "' shader" instance Show ShaderType where show = \case GLSL -> "glsl" HLSL -> "hlsl"
null
https://raw.githubusercontent.com/expipiplus1/vulkan/b1e33d1031779b4740c279c68879d05aee371659/utils/src/Vulkan/Utils/ShaderQQ/ShaderType.hs
haskell
module Vulkan.Utils.ShaderQQ.ShaderType ( ShaderType (..) ) where import Data.String (IsString (..)) data ShaderType = GLSL | HLSL instance IsString ShaderType where fromString = \case "glsl" -> GLSL "hlsl" -> HLSL t -> error $ "not support '" ++ t ++ "' shader" instance Show ShaderType where show = \case GLSL -> "glsl" HLSL -> "hlsl"
e63b92c3ff0bf6fe0ecc211aea6c0a668f277753201c6094a67b269069581454
dmjio/miso
Main.hs
-- | Haskell language pragma {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE CPP # -- | Haskell module declaration module Main where | Miso framework import import Miso import Miso.String -- | JSAddle import #ifndef __GHCJS__ import Language.Javascript.JSaddle.Warp as JSaddle import qualified Network.Wai.Handler.Warp as Warp import Network.WebSockets #endif import Control.Monad.IO.Class -- | Type synonym for an application model type Model = Int -- | Sum type for application events data Action = AddOne | SubtractOne | NoOp | SayHelloWorld deriving (Show, Eq) #ifndef __GHCJS__ runApp :: JSM () -> IO () runApp f = JSaddle.debugOr 8080 (f >> syncPoint) JSaddle.jsaddleApp #else runApp :: IO () -> IO () runApp app = app #endif -- | Entry point for a miso application main :: IO () main = runApp $ startApp App {..} where initialAction = SayHelloWorld -- initial action to be executed on application load model = 0 -- initial model update = updateModel -- update function view = viewModel -- view function events = defaultEvents -- default delegated events subs = [] -- empty subscription list mountPoint = Nothing -- mount point for application (Nothing defaults to 'body') used during prerendering to see if the VDOM and DOM are in synch ( only used with ` miso ` function ) -- | Updates model, optionally introduces side effects updateModel :: Action -> Model -> Effect Action Model updateModel AddOne m = noEff (m + 1) updateModel SubtractOne m = noEff (m - 1) updateModel NoOp m = noEff m updateModel SayHelloWorld m = m <# do liftIO (putStrLn "Hello World") >> pure NoOp | Constructs a virtual DOM from a model viewModel :: Model -> View Action viewModel x = div_ [] [ button_ [ onClick AddOne ] [ text "+" ] , text (ms x) , button_ [ onClick SubtractOne ] [ text "-" ] ]
null
https://raw.githubusercontent.com/dmjio/miso/4baab9de2a8970c99f7296ba38a4f15ed919d3cd/sample-app-jsaddle/Main.hs
haskell
| Haskell language pragma # LANGUAGE OverloadedStrings # | Haskell module declaration | JSAddle import | Type synonym for an application model | Sum type for application events | Entry point for a miso application initial action to be executed on application load initial model update function view function default delegated events empty subscription list mount point for application (Nothing defaults to 'body') | Updates model, optionally introduces side effects
# LANGUAGE RecordWildCards # # LANGUAGE CPP # module Main where | Miso framework import import Miso import Miso.String #ifndef __GHCJS__ import Language.Javascript.JSaddle.Warp as JSaddle import qualified Network.Wai.Handler.Warp as Warp import Network.WebSockets #endif import Control.Monad.IO.Class type Model = Int data Action = AddOne | SubtractOne | NoOp | SayHelloWorld deriving (Show, Eq) #ifndef __GHCJS__ runApp :: JSM () -> IO () runApp f = JSaddle.debugOr 8080 (f >> syncPoint) JSaddle.jsaddleApp #else runApp :: IO () -> IO () runApp app = app #endif main :: IO () main = runApp $ startApp App {..} where used during prerendering to see if the VDOM and DOM are in synch ( only used with ` miso ` function ) updateModel :: Action -> Model -> Effect Action Model updateModel AddOne m = noEff (m + 1) updateModel SubtractOne m = noEff (m - 1) updateModel NoOp m = noEff m updateModel SayHelloWorld m = m <# do liftIO (putStrLn "Hello World") >> pure NoOp | Constructs a virtual DOM from a model viewModel :: Model -> View Action viewModel x = div_ [] [ button_ [ onClick AddOne ] [ text "+" ] , text (ms x) , button_ [ onClick SubtractOne ] [ text "-" ] ]
5b1941f20c26763856c6e9bd90f4c3d9528962236934fe69cedfa85a68b10a67
janestreet/ppx_typed_fields
typed_deriver_variants.mli
open Base open Ppxlib open Variant_kind_generator_intf * Generates the anonymous records and gives them a concrete name . e.g. ( Also attaches [ @@deriving typed_fields ] if needed . ) { [ type rgb = { r : int ; : int ; b : int } type ' x = { r : int ; : int ; b : int ; x : ' x } [ @@deriving typed_fields ] ] } Generates the anonymous records and gives them a concrete name. e.g. (Also attaches [@@deriving typed_fields] if needed.) {[ type rgb = { r : int; g : int; b: int} type 'x rgbx = { r : int; g : int; b: int; x : 'x} [@@deriving typed_fields] ]} *) val generate_anonymous_records_sig : loc:location -> elements_to_convert:supported_constructor_declaration list -> signature_item list * Generates the anonymous records and gives them a concrete name . e.g. ( Also attaches [ @@deriving typed_fields ] if needed . ) { [ type rgb = { r : int ; : int ; b : int } type ' x = { r : int ; : int ; b : int ; x : ' x } ] } Generates the anonymous records and gives them a concrete name. e.g. (Also attaches [@@deriving typed_fields] if needed.) {[ type rgb = { r : int; g : int; b: int} type 'x rgbx = { r : int; g : int; b: int; x : 'x} ]} *) val generate_anonymous_records_str : loc:location -> elements_to_convert:supported_constructor_declaration list -> structure_item list * Generates the tuples module and gives them a concrete name . e.g. ( Also attaches [ @@deriving typed_fields ] if needed . ) { [ type rgb = ( int * int * string ) type ' x = ' x * float * ' x [ @@deriving typed_fields ] ] } Generates the tuples module and gives them a concrete name. e.g. (Also attaches [@@deriving typed_fields] if needed.) {[ type rgb = (int * int * string) type 'x rgbx = 'x * float * 'x [@@deriving typed_fields] ]} *) val generate_tuples_sig : loc:location -> elements_to_convert:supported_constructor_declaration list -> signature_item list * Generates the tuples module and gives them a concrete name . e.g. ( Also attaches [ @@deriving typed_fields ] if needed . ) { [ type rgb =( int * int * string ) type ' x = ' x * float * ' x [ @@deriving typed_fields ] ] } Generates the tuples module and gives them a concrete name. e.g. (Also attaches [@@deriving typed_fields] if needed.) {[ type rgb =(int * int * string) type 'x rgbx = 'x * float * 'x [@@deriving typed_fields] ]} *) val generate_tuples_str : loc:location -> elements_to_convert:supported_constructor_declaration list -> structure_item list (* Generate a Typed_fields(_t | of_x) structure item given a specific implementation module for how to handle the specific conversions like how the names for the typed_fields constructors are determined and how setter/getter functions work.*) val gen_str : (module Variant_kind_generator_intf.S) -> original_type:core_type option -> original_kind:type_kind -> loc:location -> elements_to_convert:supported_constructor_declaration list -> params:(core_type * (variance * injectivity)) list -> td_case:type_case -> structure_item list (* Generates packed with value type, e.g. type ('a, 'b, 'c, 'd) packed_with_value = | T : ('a, 'b, 'c, 'd, 'r) t * 'r -> ('a, 'b, 'c, 'd) packed_with_value *) val generate_packed_with_value_type : loc:location -> params:(core_type * (variance * injectivity)) list -> core_type_params:core_type list -> unique_parameter_id:label -> type_declaration include Typed_deriver_intf.S
null
https://raw.githubusercontent.com/janestreet/ppx_typed_fields/cf7511db2ccfdbbc0e43601e4d9a0c9d0a36c9e2/src/typed_deriver_variants.mli
ocaml
Generate a Typed_fields(_t | of_x) structure item given a specific implementation module for how to handle the specific conversions like how the names for the typed_fields constructors are determined and how setter/getter functions work. Generates packed with value type, e.g. type ('a, 'b, 'c, 'd) packed_with_value = | T : ('a, 'b, 'c, 'd, 'r) t * 'r -> ('a, 'b, 'c, 'd) packed_with_value
open Base open Ppxlib open Variant_kind_generator_intf * Generates the anonymous records and gives them a concrete name . e.g. ( Also attaches [ @@deriving typed_fields ] if needed . ) { [ type rgb = { r : int ; : int ; b : int } type ' x = { r : int ; : int ; b : int ; x : ' x } [ @@deriving typed_fields ] ] } Generates the anonymous records and gives them a concrete name. e.g. (Also attaches [@@deriving typed_fields] if needed.) {[ type rgb = { r : int; g : int; b: int} type 'x rgbx = { r : int; g : int; b: int; x : 'x} [@@deriving typed_fields] ]} *) val generate_anonymous_records_sig : loc:location -> elements_to_convert:supported_constructor_declaration list -> signature_item list * Generates the anonymous records and gives them a concrete name . e.g. ( Also attaches [ @@deriving typed_fields ] if needed . ) { [ type rgb = { r : int ; : int ; b : int } type ' x = { r : int ; : int ; b : int ; x : ' x } ] } Generates the anonymous records and gives them a concrete name. e.g. (Also attaches [@@deriving typed_fields] if needed.) {[ type rgb = { r : int; g : int; b: int} type 'x rgbx = { r : int; g : int; b: int; x : 'x} ]} *) val generate_anonymous_records_str : loc:location -> elements_to_convert:supported_constructor_declaration list -> structure_item list * Generates the tuples module and gives them a concrete name . e.g. ( Also attaches [ @@deriving typed_fields ] if needed . ) { [ type rgb = ( int * int * string ) type ' x = ' x * float * ' x [ @@deriving typed_fields ] ] } Generates the tuples module and gives them a concrete name. e.g. (Also attaches [@@deriving typed_fields] if needed.) {[ type rgb = (int * int * string) type 'x rgbx = 'x * float * 'x [@@deriving typed_fields] ]} *) val generate_tuples_sig : loc:location -> elements_to_convert:supported_constructor_declaration list -> signature_item list * Generates the tuples module and gives them a concrete name . e.g. ( Also attaches [ @@deriving typed_fields ] if needed . ) { [ type rgb =( int * int * string ) type ' x = ' x * float * ' x [ @@deriving typed_fields ] ] } Generates the tuples module and gives them a concrete name. e.g. (Also attaches [@@deriving typed_fields] if needed.) {[ type rgb =(int * int * string) type 'x rgbx = 'x * float * 'x [@@deriving typed_fields] ]} *) val generate_tuples_str : loc:location -> elements_to_convert:supported_constructor_declaration list -> structure_item list val gen_str : (module Variant_kind_generator_intf.S) -> original_type:core_type option -> original_kind:type_kind -> loc:location -> elements_to_convert:supported_constructor_declaration list -> params:(core_type * (variance * injectivity)) list -> td_case:type_case -> structure_item list val generate_packed_with_value_type : loc:location -> params:(core_type * (variance * injectivity)) list -> core_type_params:core_type list -> unique_parameter_id:label -> type_declaration include Typed_deriver_intf.S
5663fddce86c8c6b5dd0e7acc3b71f73d0e901ec74791e04dd10d857ee2aa2a7
nuprl/gradual-typing-performance
vec.rkt
#lang racket/base (provide v) (define v #'(1 2 3 3 4))
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/tools/summarize/test/higher-order/untyped/vec.rkt
racket
#lang racket/base (provide v) (define v #'(1 2 3 3 4))
1fab81b8b1053af08e59f5926c4a1f8b18a70d94fc5c52bf8b63e4d2cb658f83
cronburg/antlr-haskell
Grammar.hs
# LANGUAGE DeriveAnyClass , DeriveGeneric , TypeFamilies , QuasiQuotes , DataKinds , ScopedTypeVariables , OverloadedStrings , TypeSynonymInstances , FlexibleInstances , UndecidableInstances # , DataKinds, ScopedTypeVariables, OverloadedStrings, TypeSynonymInstances , FlexibleInstances, UndecidableInstances #-} module Language.Chisel.Grammar ( ChiselNTSymbol(..), ChiselTSymbol(..), ChiselAST , lowerID, upperID, prim, int, arrow, lparen, rparen, pound , vertbar, colon, comma, atsymbol, carrot, dot, linecomm, ws , Primitive(..), chiselGrammar, TokenValue(..) , chiselAST, TokenName(..), chiselDFAs, lexeme2value, isWhitespace , ChiselToken(..), list, cons, append ) where import Language.ANTLR4 import Language.Chisel.Syntax as S list a = [a] cons = (:) append = (++) [g4| grammar Chisel; chiselProd : prodSimple | '(' prodSimple ')' ; prodSimple : prodID formals magnitude alignment '->' group -> S.prodFMA | prodID formals '->' group -> S.prodF | prodID magnitude alignment '->' group -> S.prodMA | prodID magnitude '->' group -> S.prodM | LowerID prodID magnitude alignment '->' group -> S.prodNMA ; formals : LowerID formals -> cons | LowerID -> list ; magnitude : '|' '#' sizeArith '|' -> magWild | '|' sizeArith '|' -> magNorm | '|' prodID '|' -> magID ; alignment : '@' '(' sizeArith ')'; group : groupExp1 -> list | '(' groupExp ')' ; groupExp : groupExp1 -> list | groupExp1 ',' groupExp -> cons ; groupExp1 : '#' chiselProd -> gProdWild | '#' sizeArith -> gSizeWild | '(' flags ')' -> GFlags | chiselProd -> gProdNorm | sizeArith -> gSizeNorm | label -> GLabel | arith chiselProd -> gProdArith | arith prodApp -> GProdApp | '(' labels ')' -> GLabels ; flags : prodID -> list | prodID '|' flags -> cons ; labels : label -> list | label '|' labels -> cons ; label : LowerID ':' labelExp -> Label ; labelExp : '#' chiselProd -> lProdWild | '#' prodApp -> lProdAppWild | '#' sizeArith -> lSizeWild | chiselProd -> lProd | prodApp -> lProdApp | sizeArith -> lSize ; prodApp : prodID prodApp -> cons | prodID -> list ; sizeArith : arith Prim -> SizeArith | Prim -> singleArith ; arith : INT -> SizeInt | LowerID -> SizeID | arith '^' arith -> SizeExp ; prodID : UpperID -> id | UpperID '.' prodID -> append ; Prim : ( 'bit' | 'byte' ) 's'? -> Primitive; ArchPrim : ( 'page' | 'word' ) 's'? -> Primitive; UpperID : [A-Z][a-zA-Z0-9_]* -> String; LowerID : [a-z][a-zA-Z0-9_]* -> String; INT : [0-9]+ -> Int; LineComment : '//' (~ '\n')* '\n' -> String; WS : [ \t\n\r\f\v]+ -> String; |] -- Types used to the right of the '->' directive must instance Read isWhitespace T_LineComment = True isWhitespace T_WS = True isWhitespace _ = False Helper functions to construct all the various Tokens from either the desired - ( arbitrary ) lexeme or by looking it up based on the static lexeme it always - matches . - (arbitrary) lexeme or by looking it up based on the static lexeme it always - matches. -} lowerID x = Token T_LowerID (V_LowerID x) (length x) upperID x = Token T_UpperID (V_UpperID x) (length x) prim x = Token T_Prim (V_Prim x) (length $ show x) int x = Token T_INT (V_INT x) (length $ show x) arrow = lookupToken "->" lparen = lookupToken "(" rparen = lookupToken ")" pound = lookupToken "#" vertbar = lookupToken "|" colon = lookupToken ":" comma = lookupToken "," atsymbol = lookupToken "@" carrot = lookupToken "^" dot = lookupToken "." linecomm x = Token T_LineComment (V_LineComment x) (length x) ws x = Token T_WS (V_WS x) (length x)
null
https://raw.githubusercontent.com/cronburg/antlr-haskell/7a9367038eaa58f9764f2ff694269245fbebc155/test/chisel/Language/Chisel/Grammar.hs
haskell
Types used to the right of the '->' directive must instance Read
# LANGUAGE DeriveAnyClass , DeriveGeneric , TypeFamilies , QuasiQuotes , DataKinds , ScopedTypeVariables , OverloadedStrings , TypeSynonymInstances , FlexibleInstances , UndecidableInstances # , DataKinds, ScopedTypeVariables, OverloadedStrings, TypeSynonymInstances , FlexibleInstances, UndecidableInstances #-} module Language.Chisel.Grammar ( ChiselNTSymbol(..), ChiselTSymbol(..), ChiselAST , lowerID, upperID, prim, int, arrow, lparen, rparen, pound , vertbar, colon, comma, atsymbol, carrot, dot, linecomm, ws , Primitive(..), chiselGrammar, TokenValue(..) , chiselAST, TokenName(..), chiselDFAs, lexeme2value, isWhitespace , ChiselToken(..), list, cons, append ) where import Language.ANTLR4 import Language.Chisel.Syntax as S list a = [a] cons = (:) append = (++) [g4| grammar Chisel; chiselProd : prodSimple | '(' prodSimple ')' ; prodSimple : prodID formals magnitude alignment '->' group -> S.prodFMA | prodID formals '->' group -> S.prodF | prodID magnitude alignment '->' group -> S.prodMA | prodID magnitude '->' group -> S.prodM | LowerID prodID magnitude alignment '->' group -> S.prodNMA ; formals : LowerID formals -> cons | LowerID -> list ; magnitude : '|' '#' sizeArith '|' -> magWild | '|' sizeArith '|' -> magNorm | '|' prodID '|' -> magID ; alignment : '@' '(' sizeArith ')'; group : groupExp1 -> list | '(' groupExp ')' ; groupExp : groupExp1 -> list | groupExp1 ',' groupExp -> cons ; groupExp1 : '#' chiselProd -> gProdWild | '#' sizeArith -> gSizeWild | '(' flags ')' -> GFlags | chiselProd -> gProdNorm | sizeArith -> gSizeNorm | label -> GLabel | arith chiselProd -> gProdArith | arith prodApp -> GProdApp | '(' labels ')' -> GLabels ; flags : prodID -> list | prodID '|' flags -> cons ; labels : label -> list | label '|' labels -> cons ; label : LowerID ':' labelExp -> Label ; labelExp : '#' chiselProd -> lProdWild | '#' prodApp -> lProdAppWild | '#' sizeArith -> lSizeWild | chiselProd -> lProd | prodApp -> lProdApp | sizeArith -> lSize ; prodApp : prodID prodApp -> cons | prodID -> list ; sizeArith : arith Prim -> SizeArith | Prim -> singleArith ; arith : INT -> SizeInt | LowerID -> SizeID | arith '^' arith -> SizeExp ; prodID : UpperID -> id | UpperID '.' prodID -> append ; Prim : ( 'bit' | 'byte' ) 's'? -> Primitive; ArchPrim : ( 'page' | 'word' ) 's'? -> Primitive; UpperID : [A-Z][a-zA-Z0-9_]* -> String; LowerID : [a-z][a-zA-Z0-9_]* -> String; INT : [0-9]+ -> Int; LineComment : '//' (~ '\n')* '\n' -> String; WS : [ \t\n\r\f\v]+ -> String; |] isWhitespace T_LineComment = True isWhitespace T_WS = True isWhitespace _ = False Helper functions to construct all the various Tokens from either the desired - ( arbitrary ) lexeme or by looking it up based on the static lexeme it always - matches . - (arbitrary) lexeme or by looking it up based on the static lexeme it always - matches. -} lowerID x = Token T_LowerID (V_LowerID x) (length x) upperID x = Token T_UpperID (V_UpperID x) (length x) prim x = Token T_Prim (V_Prim x) (length $ show x) int x = Token T_INT (V_INT x) (length $ show x) arrow = lookupToken "->" lparen = lookupToken "(" rparen = lookupToken ")" pound = lookupToken "#" vertbar = lookupToken "|" colon = lookupToken ":" comma = lookupToken "," atsymbol = lookupToken "@" carrot = lookupToken "^" dot = lookupToken "." linecomm x = Token T_LineComment (V_LineComment x) (length x) ws x = Token T_WS (V_WS x) (length x)
ded7aa8beab1fef3e245e94f3b95059ffc05461802b9cbdc372da61f68152afa
theodormoroianu/SecondYearCourses
lab13-sol_20210115191705.hs
import Data.Char import Data.List prelStr strin = map toUpper strin ioString = do strin <- getLine putStrLn $ "Intrare\n" ++ strin let strout = prelStr strin putStrLn $ "Iesire\n" ++ strout prelNo noin = sqrt noin ioNumber = do noin <- readLn :: IO Double putStrLn $ "Intrare\n" ++ (show noin) let noout = prelNo noin putStrLn $ "Iesire" print noout inoutFile = do sin <- readFile "Input.txt" putStrLn $ "Intrare\n" ++ sin let sout = prelStr sin putStrLn $ "Iesire\n" ++ sout writeFile "Output.txt" sout readPerson :: IO (String, Int) readPerson = do nume <- getLine varsta <- readLn return (nume, varsta) showPerson :: (String, Int) -> String showPerson (nume, varsta) = nume <> " (" <> show varsta <> " ani)" showPersons :: [(String, Int)] -> String showPersons [] = "" showPersons [p] = "Cel mai in varsta este " <> showPerson p <> "." showPersons ps = "Cei mai in varsta sunt: " <> intercalate ", " (map showPerson ps) <> "." ceiMaiInVarsta :: [(a, Int)] -> [(a, Int)] ceiMaiInVarsta ps = filter ((== m) . snd) ps where m = maximum (map snd ps) ex1 = do n <- readLn :: IO Int persons <- sequence (replicate n readPerson) let ceiMai = ceiMaiInVarsta persons putStrLn (showPersons ceiMai) readPersonComma :: String -> (String, Int) readPersonComma s = (nume, read varsta) where (nume, ',':' ':varsta) = break (== ',') s readPersons :: String -> [(String, Int)] readPersons = map readPersonComma . lines ex2 = do persons <- readPersons <$> readFile "ex2.in" let ceiMai = ceiMaiInVarsta persons putStrLn (showPersons ceiMai) type Input = String type Output = String newtype MyIO a = MyIO { runIO :: Input -> (a, Input, Output)} myGetChar :: MyIO Char myGetChar = MyIO (\(c:sin) -> (c, sin, "")) testMyGetChar :: Bool testMyGetChar = runIO myGetChar "Ana" == ('A', "na", "") myPutChar :: Char -> MyIO () myPutChar c = MyIO (\sin -> ((), sin, [c])) testMyPutChar :: Bool testMyPutChar = runIO (myPutChar 'C') "Ana" == ((), "Ana", "C") instance Functor MyIO where fmap f ioa = MyIO iob where iob sin = (f a, sin', sout') where (a, sin', sout') = runIO ioa sin testFunctorMyIO :: Bool testFunctorMyIO = runIO (fmap toUpper myGetChar) "ana" == ('A', "na", "") instance Applicative MyIO where testPureMyIO :: Bool testPureMyIO = runIO (pure 'C') "Ana" == ('C', "Ana", "") testApMyIO :: Bool testApMyIO = runIO (pure (<) <*> myGetChar <*> myGetChar) "Ana" == (True, "a", "") testApMyIO :: Bool testApMyIO = runIO (myGetChar <* myPutChar "E" <* myPutChar "u") "Ana" == (True, "a", "") instance Monad MyIO where testBindMyIO :: Bool testBindMyIO = runIO (myGetChar >>= myPutChar) "Ana" == ((), "na", "A")
null
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/99185b0e97119135e7301c2c7be0f07ae7258006/Haskell/l/.history/lab13/lab13-sol_20210115191705.hs
haskell
import Data.Char import Data.List prelStr strin = map toUpper strin ioString = do strin <- getLine putStrLn $ "Intrare\n" ++ strin let strout = prelStr strin putStrLn $ "Iesire\n" ++ strout prelNo noin = sqrt noin ioNumber = do noin <- readLn :: IO Double putStrLn $ "Intrare\n" ++ (show noin) let noout = prelNo noin putStrLn $ "Iesire" print noout inoutFile = do sin <- readFile "Input.txt" putStrLn $ "Intrare\n" ++ sin let sout = prelStr sin putStrLn $ "Iesire\n" ++ sout writeFile "Output.txt" sout readPerson :: IO (String, Int) readPerson = do nume <- getLine varsta <- readLn return (nume, varsta) showPerson :: (String, Int) -> String showPerson (nume, varsta) = nume <> " (" <> show varsta <> " ani)" showPersons :: [(String, Int)] -> String showPersons [] = "" showPersons [p] = "Cel mai in varsta este " <> showPerson p <> "." showPersons ps = "Cei mai in varsta sunt: " <> intercalate ", " (map showPerson ps) <> "." ceiMaiInVarsta :: [(a, Int)] -> [(a, Int)] ceiMaiInVarsta ps = filter ((== m) . snd) ps where m = maximum (map snd ps) ex1 = do n <- readLn :: IO Int persons <- sequence (replicate n readPerson) let ceiMai = ceiMaiInVarsta persons putStrLn (showPersons ceiMai) readPersonComma :: String -> (String, Int) readPersonComma s = (nume, read varsta) where (nume, ',':' ':varsta) = break (== ',') s readPersons :: String -> [(String, Int)] readPersons = map readPersonComma . lines ex2 = do persons <- readPersons <$> readFile "ex2.in" let ceiMai = ceiMaiInVarsta persons putStrLn (showPersons ceiMai) type Input = String type Output = String newtype MyIO a = MyIO { runIO :: Input -> (a, Input, Output)} myGetChar :: MyIO Char myGetChar = MyIO (\(c:sin) -> (c, sin, "")) testMyGetChar :: Bool testMyGetChar = runIO myGetChar "Ana" == ('A', "na", "") myPutChar :: Char -> MyIO () myPutChar c = MyIO (\sin -> ((), sin, [c])) testMyPutChar :: Bool testMyPutChar = runIO (myPutChar 'C') "Ana" == ((), "Ana", "C") instance Functor MyIO where fmap f ioa = MyIO iob where iob sin = (f a, sin', sout') where (a, sin', sout') = runIO ioa sin testFunctorMyIO :: Bool testFunctorMyIO = runIO (fmap toUpper myGetChar) "ana" == ('A', "na", "") instance Applicative MyIO where testPureMyIO :: Bool testPureMyIO = runIO (pure 'C') "Ana" == ('C', "Ana", "") testApMyIO :: Bool testApMyIO = runIO (pure (<) <*> myGetChar <*> myGetChar) "Ana" == (True, "a", "") testApMyIO :: Bool testApMyIO = runIO (myGetChar <* myPutChar "E" <* myPutChar "u") "Ana" == (True, "a", "") instance Monad MyIO where testBindMyIO :: Bool testBindMyIO = runIO (myGetChar >>= myPutChar) "Ana" == ((), "na", "A")
e65d8f9763f6b570861b039b2b3287dead4370599c1977b92e157c932aa22ad4
theodormoroianu/SecondYearCourses
HaskellChurch_20210415163124.hs
{-# LANGUAGE RankNTypes #-} module HaskellChurch where A boolean is any way to choose between two alternatives newtype CBool = CBool {cIf :: forall t. t -> t -> t} An instance to show as regular Booleans instance Show CBool where show b = show $ cIf b True False The boolean constant true always chooses the first alternative cTrue :: CBool cTrue = undefined The boolean constant false always chooses the second alternative cFalse :: CBool cFalse = undefined --The boolean negation switches the alternatives cNot :: CBool -> CBool cNot = undefined --The boolean conjunction can be built as a conditional (&&:) :: CBool -> CBool -> CBool (&&:) = undefined infixr 3 &&: --The boolean disjunction can be built as a conditional (||:) :: CBool -> CBool -> CBool (||:) = undefined infixr 2 ||: -- a pair is a way to compute something based on the values -- contained within the pair. newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c } An instance to show CPairs as regular pairs . instance (Show a, Show b) => Show (CPair a b) where show p = show $ cOn p (,) builds a pair out of two values as an object which , when given --a function to be applied on the values, it will apply it on them. cPair :: a -> b -> CPair a b cPair = undefined first projection uses the function selecting first component on a pair cFst :: CPair a b -> a cFst = undefined second projection cSnd :: CPair a b -> b cSnd = undefined -- A natural number is any way to iterate a function s a number of times -- over an initial value z newtype CNat = CNat { cFor :: forall t. (t -> t) -> t -> t } -- An instance to show CNats as regular natural numbers instance Show CNat where show n = show $ cFor n (1 +) (0 :: Integer) --0 will iterate the function s 0 times over z, producing z c0 :: CNat c0 = undefined 1 is the the function s iterated 1 times over z , that is , z c1 :: CNat c1 = undefined --Successor n either - applies s one more time in addition to what n does -- - iterates s n times over (s z) cS :: CNat -> CNat cS = undefined --Addition of m and n is done by iterating s n times over m (+:) :: CNat -> CNat -> CNat (+:) = undefined infixl 6 +: --Multiplication of m and n can be done by composing n and m (*:) :: CNat -> CNat -> CNat (*:) = \n m -> CNat $ cFor n . cFor m infixl 7 *: --Exponentiation of m and n can be done by applying n to m (^:) :: CNat -> CNat -> CNat (^:) = \m n -> CNat $ cFor n (cFor m) infixr 8 ^: --Testing whether a value is 0 can be done through iteration -- using a function constantly false and an initial value true cIs0 :: CNat -> CBool cIs0 = \n -> cFor n (\_ -> cFalse) cTrue Predecessor ( evaluating to 0 for 0 ) can be defined iterating over pairs , starting from an initial value ( 0 , 0 ) cPred :: CNat -> CNat cPred = undefined substraction from m n ( evaluating to 0 if m < n ) is repeated application -- of the predeccesor function (-:) :: CNat -> CNat -> CNat (-:) = \m n -> cFor n cPred m Transform a value into a CNat ( should yield c0 for nums < = 0 ) cNat :: (Ord p, Num p) => p -> CNat cNat n = undefined We can define an instance Num CNat which will allow us to see any integer constant as a CNat ( e.g. 12 : : CNat ) and also use regular -- arithmetic instance Num CNat where (+) = (+:) (*) = (*:) (-) = (-:) abs = id signum n = cIf (cIs0 n) 0 1 fromInteger = cNat -- m is less than (or equal to) n if when substracting n from m we get 0 (<=:) :: CNat -> CNat -> CBool (<=:) = undefined infix 4 <=: (>=:) :: CNat -> CNat -> CBool (>=:) = \m n -> n <=: m infix 4 >=: (<:) :: CNat -> CNat -> CBool (<:) = \m n -> cNot (m >=: n) infix 4 <: (>:) :: CNat -> CNat -> CBool (>:) = \m n -> n <: m infix 4 >: -- equality on naturals can be defined my means of comparisons (==:) :: CNat -> CNat -> CBool (==:) = undefined --Fun with arithmetic and pairs --Define factorial. You can iterate over a pair to contain the current index and so far factorial cFactorial :: CNat -> CNat cFactorial = undefined Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence cFibonacci :: CNat -> CNat cFibonacci = undefined --Given m and n, compute q and r satisfying m = q * n + r. If n is not 0 then r should be less than n. --hint repeated substraction, iterated for at most m times. cDivMod :: CNat -> CNat -> CPair CNat CNat cDivMod = undefined -- a list is a way to aggregate a sequence of elements given an aggregation function and an initial value. newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b } make CList an instance of Foldable instance Foldable CList where --An instance to show CLists as regular lists. instance (Show a) => Show (CList a) where show l = "cList show $ toList l churchNil :: Term churchNil = lams ["agg", "init"] (v "init") cNil :: CList a cNil = CList $ \agg init -> init churchCons :: Term churchCons = lams ["x","l","agg", "init"] (v "agg" $$ v "x" $$ (v "l" $$ v "agg" $$ v "init") ) (.:) :: a -> CList a -> CList a (.:) = \x xs -> CList $ \agg init -> agg x (cFoldR xs agg init) churchList :: [Term] -> Term churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil cList :: [a] -> CList a cList = foldr (.:) cNil churchNatList :: [Integer] -> Term churchNatList = churchList . map churchNat cNatList :: [Integer] -> CList CNat cNatList = cList . map cNat churchSum :: Term churchSum = lam "l" (v "l" $$ churchPlus $$ church0) cSum :: CList CNat -> CNat since CList is an instance of Foldable ; otherwise : \l - > cFoldR l ( + ) 0 churchIsNil :: Term churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue) cIsNil :: CList a -> CBool cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue churchHead :: Term churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default") cHead :: CList a -> a -> a cHead = \l d -> cFoldR l (\x _ -> x) d churchTail :: Term churchTail = lam "l" (churchFst $$ (v "l" $$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ churchNil $$ churchNil) )) cTail :: CList a -> CList a cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil) cLength :: CList a -> CNat cLength = \l -> cFoldR l (\_ n -> cS n) 0 fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b) divmod m n = divmod' (0, 0) where divmod' (x, y) | x' <= m = divmod' (x', succ y) | otherwise = (y, m - x) where x' = x + n divmod' m n = if n == 0 then (0, m) else Function.fix (\f p -> (\x' -> if x' > 0 then f ((,) (succ (fst p)) x') else if (<=) n (snd p) then ((,) (succ (fst p)) 0) else p) ((-) (snd p) n)) (0, m) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ) )
null
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/HaskellChurch_20210415163124.hs
haskell
# LANGUAGE RankNTypes # The boolean negation switches the alternatives The boolean conjunction can be built as a conditional The boolean disjunction can be built as a conditional a pair is a way to compute something based on the values contained within the pair. a function to be applied on the values, it will apply it on them. A natural number is any way to iterate a function s a number of times over an initial value z An instance to show CNats as regular natural numbers 0 will iterate the function s 0 times over z, producing z Successor n either - iterates s n times over (s z) Addition of m and n is done by iterating s n times over m Multiplication of m and n can be done by composing n and m Exponentiation of m and n can be done by applying n to m Testing whether a value is 0 can be done through iteration using a function constantly false and an initial value true of the predeccesor function arithmetic m is less than (or equal to) n if when substracting n from m we get 0 equality on naturals can be defined my means of comparisons Fun with arithmetic and pairs Define factorial. You can iterate over a pair to contain the current index and so far factorial Given m and n, compute q and r satisfying m = q * n + r. If n is not 0 then r should be less than n. hint repeated substraction, iterated for at most m times. a list is a way to aggregate a sequence of elements given an aggregation function and an initial value. An instance to show CLists as regular lists.
module HaskellChurch where A boolean is any way to choose between two alternatives newtype CBool = CBool {cIf :: forall t. t -> t -> t} An instance to show as regular Booleans instance Show CBool where show b = show $ cIf b True False The boolean constant true always chooses the first alternative cTrue :: CBool cTrue = undefined The boolean constant false always chooses the second alternative cFalse :: CBool cFalse = undefined cNot :: CBool -> CBool cNot = undefined (&&:) :: CBool -> CBool -> CBool (&&:) = undefined infixr 3 &&: (||:) :: CBool -> CBool -> CBool (||:) = undefined infixr 2 ||: newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c } An instance to show CPairs as regular pairs . instance (Show a, Show b) => Show (CPair a b) where show p = show $ cOn p (,) builds a pair out of two values as an object which , when given cPair :: a -> b -> CPair a b cPair = undefined first projection uses the function selecting first component on a pair cFst :: CPair a b -> a cFst = undefined second projection cSnd :: CPair a b -> b cSnd = undefined newtype CNat = CNat { cFor :: forall t. (t -> t) -> t -> t } instance Show CNat where show n = show $ cFor n (1 +) (0 :: Integer) c0 :: CNat c0 = undefined 1 is the the function s iterated 1 times over z , that is , z c1 :: CNat c1 = undefined - applies s one more time in addition to what n does cS :: CNat -> CNat cS = undefined (+:) :: CNat -> CNat -> CNat (+:) = undefined infixl 6 +: (*:) :: CNat -> CNat -> CNat (*:) = \n m -> CNat $ cFor n . cFor m infixl 7 *: (^:) :: CNat -> CNat -> CNat (^:) = \m n -> CNat $ cFor n (cFor m) infixr 8 ^: cIs0 :: CNat -> CBool cIs0 = \n -> cFor n (\_ -> cFalse) cTrue Predecessor ( evaluating to 0 for 0 ) can be defined iterating over pairs , starting from an initial value ( 0 , 0 ) cPred :: CNat -> CNat cPred = undefined substraction from m n ( evaluating to 0 if m < n ) is repeated application (-:) :: CNat -> CNat -> CNat (-:) = \m n -> cFor n cPred m Transform a value into a CNat ( should yield c0 for nums < = 0 ) cNat :: (Ord p, Num p) => p -> CNat cNat n = undefined We can define an instance Num CNat which will allow us to see any integer constant as a CNat ( e.g. 12 : : CNat ) and also use regular instance Num CNat where (+) = (+:) (*) = (*:) (-) = (-:) abs = id signum n = cIf (cIs0 n) 0 1 fromInteger = cNat (<=:) :: CNat -> CNat -> CBool (<=:) = undefined infix 4 <=: (>=:) :: CNat -> CNat -> CBool (>=:) = \m n -> n <=: m infix 4 >=: (<:) :: CNat -> CNat -> CBool (<:) = \m n -> cNot (m >=: n) infix 4 <: (>:) :: CNat -> CNat -> CBool (>:) = \m n -> n <: m infix 4 >: (==:) :: CNat -> CNat -> CBool (==:) = undefined cFactorial :: CNat -> CNat cFactorial = undefined Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence cFibonacci :: CNat -> CNat cFibonacci = undefined cDivMod :: CNat -> CNat -> CPair CNat CNat cDivMod = undefined newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b } make CList an instance of Foldable instance Foldable CList where instance (Show a) => Show (CList a) where show l = "cList show $ toList l churchNil :: Term churchNil = lams ["agg", "init"] (v "init") cNil :: CList a cNil = CList $ \agg init -> init churchCons :: Term churchCons = lams ["x","l","agg", "init"] (v "agg" $$ v "x" $$ (v "l" $$ v "agg" $$ v "init") ) (.:) :: a -> CList a -> CList a (.:) = \x xs -> CList $ \agg init -> agg x (cFoldR xs agg init) churchList :: [Term] -> Term churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil cList :: [a] -> CList a cList = foldr (.:) cNil churchNatList :: [Integer] -> Term churchNatList = churchList . map churchNat cNatList :: [Integer] -> CList CNat cNatList = cList . map cNat churchSum :: Term churchSum = lam "l" (v "l" $$ churchPlus $$ church0) cSum :: CList CNat -> CNat since CList is an instance of Foldable ; otherwise : \l - > cFoldR l ( + ) 0 churchIsNil :: Term churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue) cIsNil :: CList a -> CBool cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue churchHead :: Term churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default") cHead :: CList a -> a -> a cHead = \l d -> cFoldR l (\x _ -> x) d churchTail :: Term churchTail = lam "l" (churchFst $$ (v "l" $$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ churchNil $$ churchNil) )) cTail :: CList a -> CList a cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil) cLength :: CList a -> CNat cLength = \l -> cFoldR l (\_ n -> cS n) 0 fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b) divmod m n = divmod' (0, 0) where divmod' (x, y) | x' <= m = divmod' (x', succ y) | otherwise = (y, m - x) where x' = x + n divmod' m n = if n == 0 then (0, m) else Function.fix (\f p -> (\x' -> if x' > 0 then f ((,) (succ (fst p)) x') else if (<=) n (snd p) then ((,) (succ (fst p)) 0) else p) ((-) (snd p) n)) (0, m) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ) )
25ae35ab1467767bb630a54e5e30b8487cf64ffa7d3f9e98f187a4570f29364f
flipstone/haskell-for-beginners
3_where.hs
-- Write a function to tell whether a triangle -- is big or not. A triangle should be called big if its hypoteneuse is longer than 10 . -- (be sure to use where to make your function -- more readable) bigTriangle :: Float -> Float -> Bool bigTriangle length width = hypoteneuse > 10 where hypoteneuse = sqrt (length*length + width*width) -- Write a function that classifies rectangles into at least 5 size categories based their -- area. The pair given is the rectangle's length -- and width. rectSize :: (Integer, Integer) -> String rectSize (length, width) | area > 25 = "Super Sized" | area > 20 = "Large" | area > 15 = "Medium" | area > 10 = "Small" | otherwise = "Why Bother" where area = length*width -- Write a function that constructs a rect from a list of 2 elements , length and width . Assume there will always be exactly 2 elements -- in the list. Use your where and pattern -- matching skills to write the most readable -- function you can. listToRect :: [Integer] -> (Integer, Integer) listToRect list = (length, width) where [length, width] = list -- Write a function that calculates the area of -- each rectangle in a list. areas rects = [ area rect | rect <- rects ] where area (length,width) = length * width
null
https://raw.githubusercontent.com/flipstone/haskell-for-beginners/e586a1f3ef08f21d5181171fe7a7b27057391f0b/answers/chapter_04/3_where.hs
haskell
Write a function to tell whether a triangle is big or not. A triangle should be called (be sure to use where to make your function more readable) Write a function that classifies rectangles area. The pair given is the rectangle's length and width. Write a function that constructs a rect from a in the list. Use your where and pattern matching skills to write the most readable function you can. Write a function that calculates the area of each rectangle in a list.
big if its hypoteneuse is longer than 10 . bigTriangle :: Float -> Float -> Bool bigTriangle length width = hypoteneuse > 10 where hypoteneuse = sqrt (length*length + width*width) into at least 5 size categories based their rectSize :: (Integer, Integer) -> String rectSize (length, width) | area > 25 = "Super Sized" | area > 20 = "Large" | area > 15 = "Medium" | area > 10 = "Small" | otherwise = "Why Bother" where area = length*width list of 2 elements , length and width . Assume there will always be exactly 2 elements listToRect :: [Integer] -> (Integer, Integer) listToRect list = (length, width) where [length, width] = list areas rects = [ area rect | rect <- rects ] where area (length,width) = length * width
054210a9ee13b4b05693da619dccf9b6de675f202ab482bf9e3c1b6416c002e0
oofp/Beseder
STMProducer.hs
# LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # module Beseder.Misc.Prosumers.STMProducer where import Protolude import Beseder.Misc.Prosumers.Producer import Beseder.Misc.Prosumers.AsyncProducer import Beseder.Base.Common stmProducer :: (TaskPoster m, Eq a) => STM a -> m (Producer m a) stmProducer stm_a = initAsyncProducer2 actionFunc where actionFunc a_maybe = do res <- atomically $ do a <- stm_a if (Just a == a_maybe) then retry else return a liftIO $ putStrLn ("stmProducer produced" :: Text) return res
null
https://raw.githubusercontent.com/oofp/Beseder/a0f5c5e3138938b6fa18811d646535ee6df1a4f4/src/Beseder/Misc/Prosumers/STMProducer.hs
haskell
# LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # module Beseder.Misc.Prosumers.STMProducer where import Protolude import Beseder.Misc.Prosumers.Producer import Beseder.Misc.Prosumers.AsyncProducer import Beseder.Base.Common stmProducer :: (TaskPoster m, Eq a) => STM a -> m (Producer m a) stmProducer stm_a = initAsyncProducer2 actionFunc where actionFunc a_maybe = do res <- atomically $ do a <- stm_a if (Just a == a_maybe) then retry else return a liftIO $ putStrLn ("stmProducer produced" :: Text) return res
fc8ad04d654fe25fa6d7b79066b14dc8142e594fa3eb55276b5a5aa8aadc42ea
karamellpelle/grid
Modify.hs
grid is a game written in Haskell Copyright ( C ) 2018 -- -- This file is part of grid. -- -- grid 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. -- -- grid 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 grid. If not, see </>. -- module Game.Modify ( defaultModify, noControlModify, noBeginModify, noUpdateModify, ) where import Game.MEnv defaultModify :: (s -> a -> b -> MEnv' (s, a, b)) -> (s -> a -> b -> MEnv' (s, a, b)) -> (s -> a -> b -> MEnv' (s, a, b)) -> s -> a -> b -> MEnv' (s, a, b) defaultModify beginModify controlModify updateModify = \s a b -> do -- modify world at beginning of step (like clean up) (s', a', b') <- beginModify s a b -- modify world from controls (like input, network) (s'', a'', b'') <- controlModify s' a' b' -- modify world by updating it (s''', a''', b''') <- updateModify s'' a'' b'' return (s''', a''', b''') noControlModify :: s -> a -> b -> MEnv' (s, a, b) noControlModify s a b = return (s, a, b) noBeginModify :: s -> a -> b -> MEnv' (s, a, b) noBeginModify s a b = return (s, a, b) noUpdateModify :: s -> a -> b -> MEnv' (s, a, b) noUpdateModify s a b = return (s, a, b)
null
https://raw.githubusercontent.com/karamellpelle/grid/56729e63ed6404fd6cfd6d11e73fa358f03c386f/designer/source/Game/Modify.hs
haskell
This file is part of grid. grid is free software: you can redistribute it and/or modify (at your option) any later version. grid is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with grid. If not, see </>. modify world at beginning of step (like clean up) modify world from controls (like input, network) modify world by updating it
grid is a game written in Haskell Copyright ( C ) 2018 it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License module Game.Modify ( defaultModify, noControlModify, noBeginModify, noUpdateModify, ) where import Game.MEnv defaultModify :: (s -> a -> b -> MEnv' (s, a, b)) -> (s -> a -> b -> MEnv' (s, a, b)) -> (s -> a -> b -> MEnv' (s, a, b)) -> s -> a -> b -> MEnv' (s, a, b) defaultModify beginModify controlModify updateModify = \s a b -> do (s', a', b') <- beginModify s a b (s'', a'', b'') <- controlModify s' a' b' (s''', a''', b''') <- updateModify s'' a'' b'' return (s''', a''', b''') noControlModify :: s -> a -> b -> MEnv' (s, a, b) noControlModify s a b = return (s, a, b) noBeginModify :: s -> a -> b -> MEnv' (s, a, b) noBeginModify s a b = return (s, a, b) noUpdateModify :: s -> a -> b -> MEnv' (s, a, b) noUpdateModify s a b = return (s, a, b)
ce34d051778ff266ac7bf37163b44e3dc29680d5a132885e1b3f7244030ddc7c
cabol/cross_db
xdb_mnesia_boot_repo.erl
%%%------------------------------------------------------------------- %%% @doc %%% Mnesia bootable repo. %%% @end %%%------------------------------------------------------------------- -module(xdb_mnesia_boot_repo). %% Repo callbacks -export([init/1]). %%%=================================================================== %%% Repo callbacks %%%=================================================================== %% @hidden init(Opts) -> ok = init_mnesia(Opts), {ok, Opts}. %%%=================================================================== Internal functions %%%=================================================================== @private init_mnesia(Opts) -> stopped = mnesia:stop(), ok = mnesia_create_schema(node()), ok = mnesia:start(), ok = create_schemas(Opts), ok. @private mnesia_create_schema(Node) -> case mnesia:create_schema([Node]) of ok -> ok; {error, {Node, {already_exists, Node}}} -> ok end. @private create_schemas(Opts) -> DefaultOpts = parse(Opts), Schemas = xdb_lib:keyfind(schemas, Opts, []), _ = [ok = create_schema(Schema, DefaultOpts) || Schema <- Schemas], ok. @private create_schema(Schema, Opts) -> SchemaSpec = Schema:schema_spec(), Name = xdb_schema_spec:name(SchemaSpec), Fields = xdb_schema_spec:fields(SchemaSpec), Attributes = xdb_schema_spec:field_names(SchemaSpec), Indexes = [FN || {FN, _, FOpts} <- Fields, lists:member(index, FOpts)], TableOpts = [ {attributes, Attributes}, {index, Indexes} | Opts ], case mnesia:create_table(Name, TableOpts) of {atomic, ok} -> ok; {aborted, {already_exists, Name}} -> ok; {aborted, Reason} -> {error, Reason} end. @private parse(Options) -> parse(Options, []). @private parse([], Acc) -> Acc; parse([{disc_copies, local} | Options], Acc) -> parse(Options, [{disc_copies, [node()]} | Acc]); parse([{disc_copies, Nodes} | Options], Acc) -> parse(Options, [{disc_copies, Nodes} | Acc]); parse([{disc_only_copies, local} | Options], Acc) -> parse(Options, [{disc_only_copies, [node()]} | Acc]); parse([{disc_only_copies, Nodes} | Options], Acc) -> parse(Options, [{disc_only_copies, Nodes} | Acc]); parse([{ram_copies, local} | Options], Acc) -> parse(Options, [{ram_copies, [node()]} | Acc]); parse([{ram_copies, Nodes} | Options], Acc) -> parse(Options, [{ram_copies, Nodes} | Acc]); parse([{majority, Flag} | Options], Acc) -> parse(Options, [{majority, Flag} | Acc]); parse([{snmp, SnmpStruct} | Options], Acc) -> parse(Options, [{snmp, SnmpStruct} | Acc]); parse([{storage_properties, Props} | Options], Acc) -> parse(Options, [{storage_properties, Props} | Acc]); parse([{type, Type} | Options], Acc) when Type =:= set; Type =:= ordered_set -> parse(Options, [{type, Type} | Acc]); parse([_IgnoredOption | Options], Acc) -> parse(Options, Acc).
null
https://raw.githubusercontent.com/cabol/cross_db/365bb3b6cffde1b4da7109ed2594a0a3f1a4a949/src/adapters/xdb_mnesia_boot_repo.erl
erlang
------------------------------------------------------------------- @doc Mnesia bootable repo. @end ------------------------------------------------------------------- Repo callbacks =================================================================== Repo callbacks =================================================================== @hidden =================================================================== ===================================================================
-module(xdb_mnesia_boot_repo). -export([init/1]). init(Opts) -> ok = init_mnesia(Opts), {ok, Opts}. Internal functions @private init_mnesia(Opts) -> stopped = mnesia:stop(), ok = mnesia_create_schema(node()), ok = mnesia:start(), ok = create_schemas(Opts), ok. @private mnesia_create_schema(Node) -> case mnesia:create_schema([Node]) of ok -> ok; {error, {Node, {already_exists, Node}}} -> ok end. @private create_schemas(Opts) -> DefaultOpts = parse(Opts), Schemas = xdb_lib:keyfind(schemas, Opts, []), _ = [ok = create_schema(Schema, DefaultOpts) || Schema <- Schemas], ok. @private create_schema(Schema, Opts) -> SchemaSpec = Schema:schema_spec(), Name = xdb_schema_spec:name(SchemaSpec), Fields = xdb_schema_spec:fields(SchemaSpec), Attributes = xdb_schema_spec:field_names(SchemaSpec), Indexes = [FN || {FN, _, FOpts} <- Fields, lists:member(index, FOpts)], TableOpts = [ {attributes, Attributes}, {index, Indexes} | Opts ], case mnesia:create_table(Name, TableOpts) of {atomic, ok} -> ok; {aborted, {already_exists, Name}} -> ok; {aborted, Reason} -> {error, Reason} end. @private parse(Options) -> parse(Options, []). @private parse([], Acc) -> Acc; parse([{disc_copies, local} | Options], Acc) -> parse(Options, [{disc_copies, [node()]} | Acc]); parse([{disc_copies, Nodes} | Options], Acc) -> parse(Options, [{disc_copies, Nodes} | Acc]); parse([{disc_only_copies, local} | Options], Acc) -> parse(Options, [{disc_only_copies, [node()]} | Acc]); parse([{disc_only_copies, Nodes} | Options], Acc) -> parse(Options, [{disc_only_copies, Nodes} | Acc]); parse([{ram_copies, local} | Options], Acc) -> parse(Options, [{ram_copies, [node()]} | Acc]); parse([{ram_copies, Nodes} | Options], Acc) -> parse(Options, [{ram_copies, Nodes} | Acc]); parse([{majority, Flag} | Options], Acc) -> parse(Options, [{majority, Flag} | Acc]); parse([{snmp, SnmpStruct} | Options], Acc) -> parse(Options, [{snmp, SnmpStruct} | Acc]); parse([{storage_properties, Props} | Options], Acc) -> parse(Options, [{storage_properties, Props} | Acc]); parse([{type, Type} | Options], Acc) when Type =:= set; Type =:= ordered_set -> parse(Options, [{type, Type} | Acc]); parse([_IgnoredOption | Options], Acc) -> parse(Options, Acc).
ce8861c5e9b9a4d99e4854b31b684f88c6ec09ae16710e043bacd5a905be5686
Verites/verigraph
Processes.hs
module Processes ( Options , options , execute ) where import Control.Monad import Data.Maybe (fromJust, isJust) import Data.Monoid ((<>)) import Data.Set (toList) import GlobalOptions import Options.Applicative import Abstract.Rewriting.DPO import Abstract.Rewriting.DPO.Process hiding (productions) import Analysis.Processes import Base.Valid import Category.TypedGraphRule import qualified Data.TypedGraph as TG import Data.TypedGraph.Morphism import Rewriting.DPO.TypedGraph.GraphProcess import Rewriting.DPO.TypedGraph.GraphProcess.OccurrenceRelation import qualified XML.GGXReader as XML import qualified XML.GGXWriter as GW newtype Options = Options { outputFile :: String } options :: Parser Options options = Options <$> strOption ( long "output-file" <> short 'o' <> metavar "FILE" <> action "file" <> help "GGX file that will be written, adding the concurrent productions to the original graph grammar") execute :: GlobalOptions -> Options -> IO () execute globalOpts opts = do let dpoConf = morphismsConf globalOpts (gg,gg2,_) <- XML.readGrammar (inputFile globalOpts) (useConstraints globalOpts) dpoConf ggName <- XML.readGGName (inputFile globalOpts) names <- XML.readNames (inputFile globalOpts) sequences <- XML.readSequencesWithObjectFlow gg (inputFile globalOpts) if null sequences then error "input file must have at least a rule sequence" else print "" forM_ sequences $ \sq -> mainFunction opts sq gg2 ggName names sequenceName :: (String, r, o) -> String sequenceName (a,_,_ ) = a mainFunction :: Options -> RuleSequence (TypedGraphMorphism a b) -> Grammar (RuleMorphism a b) -> String -> [(String, String)] -> IO () mainFunction opts sq gg2 ggName names = do let colimit = calculateRulesColimit sq conflictsAndDependencies = findConflictsAndDependencies colimit inducedByNacs = filterInducedByNacs (eliminateSelfConflictsAndDependencies conflictsAndDependencies) sqName = sequenceName sq ogg = generateDoublyTypedGrammar sq sgg = singleTypedGrammar ogg completeOgg = calculateNacRelations ogg inducedByNacs newRules = productions . singleTypedGrammar $ ogg relation = concreteRelation completeOgg rulesRelation = filterRulesOccurrenceRelation relation elementsRelation = filterElementsOccurrenceRelation relation unique = uniqueOrigin newRules (rulesNames, elementsNames) = getElements completeOgg forM_ (zip [sq] newRules) $ \((name, _, _), productions) -> when (null productions) (putStrLn $ "No graph process candidates were found for rule sequence '" ++ name ++ "'") let analysis = "Conflicts and Dependencies: {\n" ++ show (eliminateSelfConflictsAndDependencies conflictsAndDependencies) ++ "\n}\n" ++ "Creation and Deletion Relation: {\n" ++ show (originRelation completeOgg) ++"\n}\n" ++ "Conflicts and dependencies induced by NACs: \n{" ++ show (map (findConcreteTrigger completeOgg) (toList inducedByNacs)) ++ "\n}\n" rulesOrdering = findOrder rulesRelation rulesNames elementsOrdering = findOrder elementsRelation elementsNames testCases = "Rules involved: {\n" ++ show rulesNames ++ "\n}\n" ++ "Concrete Rules Relation: {\n" ++ relationToString rulesRelation ++ "\n}\n" ++ "Elements involved: {\n" ++ show elementsNames ++ "\n}\n" ++ "Elements Relation: {\n" ++ relationToString elementsRelation ++ "\n}\n" ++ "\n\n" ++ "Rules Ordering: {" ++ show rulesOrdering ++ "\n}\n" ++ "Element Ordering: {" ++ show elementsOrdering ++"\n}\n\n" ++ "Set of Category Restrictions: {\n" ++ restrictionToString (restrictRelation completeOgg) ++ "\n}" putStrLn $ "\nTesting Serialization for " ++ sqName ++ ":" if unique then putStrLn "[OK] Unique creations and deletions" else putStrLn "[FAIL] At least one element is created or deleted for more than one rule" if isValid (initialGraph completeOgg) then putStrLn "[OK] Initial graph is valid" else putStrLn $ "[FAIL] Initial graph is not valid: \n" ++ fromJust (errorMessages $ validate $ initialGraph completeOgg) ++ "\n" ++ show (initialGraph completeOgg) if isValid (finalGraph completeOgg) then putStrLn "[OK] Final graph is valid" else putStrLn $ "[FAIL] Final graph is not valid: \n" ++ fromJust (errorMessages $ validate $ finalGraph completeOgg) ++ "\n" ++ show (finalGraph completeOgg) if isJust rulesOrdering then putStrLn "[OK] Concrete occurrence relation is a total order" else putStrLn "[FAIL] Concrete occurrence relation is not a total order" if isJust elementsOrdering then putStrLn "[OK] Concrete elements relation is a total order" else putStrLn "[FAIL] Concrete elements relation is not a total order" if emptyRestrictions completeOgg then putStrLn "[OK] There are no abstract restrictions" else putStrLn "[WARN] There are abstract restrictions" writeFile (outputFile opts ++ "_" ++ sqName ++"_analysis") analysis putStrLn $ "Analysis written in " ++ (outputFile opts ++ "_" ++ sqName ++ "_analysis") writeFile (outputFile opts ++ "_" ++ sqName ++ "_test_cases") testCases putStrLn $ "Test cases written in " ++ (outputFile opts ++ "_" ++ sqName ++ "_test_cases") let newStart = start sgg gg' = addReachableGraphs (reachableGraphs sgg) (grammar newStart [] newRules) GW.writeGrammarFile (gg',gg2) ggName (buildNewNames names (doubleType completeOgg)) (outputFile opts ++ "_" ++ sqName ++ ".ggx") buildNewNames :: [(String,String)] -> TG.TypedGraph a b -> [(String,String)] buildNewNames oldNames tg = newNs ++ newEs where ns = map (\(n,t) -> (n, "I" ++ show t)) (TG.typedNodeIds tg) es = map (\(e,t) -> (e, "I" ++ show t)) (TG.typedEdgeIds tg) newNs = map (\(n,it) -> ("I" ++ show n, rename (show n,it))) ns newEs = map (\(e,it) -> ("I" ++ show e, rename (show e,it))) es rename (z,it) = (\(x,y) -> x ++ "-" ++ z ++ y) (break (=='%') (find it)) find it = fromJust (lookup it oldNames)
null
https://raw.githubusercontent.com/Verites/verigraph/754ec08bf4a55ea7402d8cd0705e58b1d2c9cd67/src/CLI/Processes.hs
haskell
module Processes ( Options , options , execute ) where import Control.Monad import Data.Maybe (fromJust, isJust) import Data.Monoid ((<>)) import Data.Set (toList) import GlobalOptions import Options.Applicative import Abstract.Rewriting.DPO import Abstract.Rewriting.DPO.Process hiding (productions) import Analysis.Processes import Base.Valid import Category.TypedGraphRule import qualified Data.TypedGraph as TG import Data.TypedGraph.Morphism import Rewriting.DPO.TypedGraph.GraphProcess import Rewriting.DPO.TypedGraph.GraphProcess.OccurrenceRelation import qualified XML.GGXReader as XML import qualified XML.GGXWriter as GW newtype Options = Options { outputFile :: String } options :: Parser Options options = Options <$> strOption ( long "output-file" <> short 'o' <> metavar "FILE" <> action "file" <> help "GGX file that will be written, adding the concurrent productions to the original graph grammar") execute :: GlobalOptions -> Options -> IO () execute globalOpts opts = do let dpoConf = morphismsConf globalOpts (gg,gg2,_) <- XML.readGrammar (inputFile globalOpts) (useConstraints globalOpts) dpoConf ggName <- XML.readGGName (inputFile globalOpts) names <- XML.readNames (inputFile globalOpts) sequences <- XML.readSequencesWithObjectFlow gg (inputFile globalOpts) if null sequences then error "input file must have at least a rule sequence" else print "" forM_ sequences $ \sq -> mainFunction opts sq gg2 ggName names sequenceName :: (String, r, o) -> String sequenceName (a,_,_ ) = a mainFunction :: Options -> RuleSequence (TypedGraphMorphism a b) -> Grammar (RuleMorphism a b) -> String -> [(String, String)] -> IO () mainFunction opts sq gg2 ggName names = do let colimit = calculateRulesColimit sq conflictsAndDependencies = findConflictsAndDependencies colimit inducedByNacs = filterInducedByNacs (eliminateSelfConflictsAndDependencies conflictsAndDependencies) sqName = sequenceName sq ogg = generateDoublyTypedGrammar sq sgg = singleTypedGrammar ogg completeOgg = calculateNacRelations ogg inducedByNacs newRules = productions . singleTypedGrammar $ ogg relation = concreteRelation completeOgg rulesRelation = filterRulesOccurrenceRelation relation elementsRelation = filterElementsOccurrenceRelation relation unique = uniqueOrigin newRules (rulesNames, elementsNames) = getElements completeOgg forM_ (zip [sq] newRules) $ \((name, _, _), productions) -> when (null productions) (putStrLn $ "No graph process candidates were found for rule sequence '" ++ name ++ "'") let analysis = "Conflicts and Dependencies: {\n" ++ show (eliminateSelfConflictsAndDependencies conflictsAndDependencies) ++ "\n}\n" ++ "Creation and Deletion Relation: {\n" ++ show (originRelation completeOgg) ++"\n}\n" ++ "Conflicts and dependencies induced by NACs: \n{" ++ show (map (findConcreteTrigger completeOgg) (toList inducedByNacs)) ++ "\n}\n" rulesOrdering = findOrder rulesRelation rulesNames elementsOrdering = findOrder elementsRelation elementsNames testCases = "Rules involved: {\n" ++ show rulesNames ++ "\n}\n" ++ "Concrete Rules Relation: {\n" ++ relationToString rulesRelation ++ "\n}\n" ++ "Elements involved: {\n" ++ show elementsNames ++ "\n}\n" ++ "Elements Relation: {\n" ++ relationToString elementsRelation ++ "\n}\n" ++ "\n\n" ++ "Rules Ordering: {" ++ show rulesOrdering ++ "\n}\n" ++ "Element Ordering: {" ++ show elementsOrdering ++"\n}\n\n" ++ "Set of Category Restrictions: {\n" ++ restrictionToString (restrictRelation completeOgg) ++ "\n}" putStrLn $ "\nTesting Serialization for " ++ sqName ++ ":" if unique then putStrLn "[OK] Unique creations and deletions" else putStrLn "[FAIL] At least one element is created or deleted for more than one rule" if isValid (initialGraph completeOgg) then putStrLn "[OK] Initial graph is valid" else putStrLn $ "[FAIL] Initial graph is not valid: \n" ++ fromJust (errorMessages $ validate $ initialGraph completeOgg) ++ "\n" ++ show (initialGraph completeOgg) if isValid (finalGraph completeOgg) then putStrLn "[OK] Final graph is valid" else putStrLn $ "[FAIL] Final graph is not valid: \n" ++ fromJust (errorMessages $ validate $ finalGraph completeOgg) ++ "\n" ++ show (finalGraph completeOgg) if isJust rulesOrdering then putStrLn "[OK] Concrete occurrence relation is a total order" else putStrLn "[FAIL] Concrete occurrence relation is not a total order" if isJust elementsOrdering then putStrLn "[OK] Concrete elements relation is a total order" else putStrLn "[FAIL] Concrete elements relation is not a total order" if emptyRestrictions completeOgg then putStrLn "[OK] There are no abstract restrictions" else putStrLn "[WARN] There are abstract restrictions" writeFile (outputFile opts ++ "_" ++ sqName ++"_analysis") analysis putStrLn $ "Analysis written in " ++ (outputFile opts ++ "_" ++ sqName ++ "_analysis") writeFile (outputFile opts ++ "_" ++ sqName ++ "_test_cases") testCases putStrLn $ "Test cases written in " ++ (outputFile opts ++ "_" ++ sqName ++ "_test_cases") let newStart = start sgg gg' = addReachableGraphs (reachableGraphs sgg) (grammar newStart [] newRules) GW.writeGrammarFile (gg',gg2) ggName (buildNewNames names (doubleType completeOgg)) (outputFile opts ++ "_" ++ sqName ++ ".ggx") buildNewNames :: [(String,String)] -> TG.TypedGraph a b -> [(String,String)] buildNewNames oldNames tg = newNs ++ newEs where ns = map (\(n,t) -> (n, "I" ++ show t)) (TG.typedNodeIds tg) es = map (\(e,t) -> (e, "I" ++ show t)) (TG.typedEdgeIds tg) newNs = map (\(n,it) -> ("I" ++ show n, rename (show n,it))) ns newEs = map (\(e,it) -> ("I" ++ show e, rename (show e,it))) es rename (z,it) = (\(x,y) -> x ++ "-" ++ z ++ y) (break (=='%') (find it)) find it = fromJust (lookup it oldNames)
f98bb18d813551cf6de474af2e1d09d3bcd7b7243f034c669ee2eb3795c3c8a8
dundalek/liz
compiler.clj
(ns liz.impl.compiler (:refer-clojure :exclude [compile]) (:require [liz.impl.analyzer :as ana] [liz.impl.reader :as reader] [clojure.tools.analyzer.env :as env] [clojure.java.shell :refer [sh]] [liz.impl.emitter :as emitter] [clojure.pprint :refer [pprint]] [clojure.string :as str] [clojure.java.io :as io])) (defn- print-error [file-name form e] (let [{:keys [node]} (ex-data e) line (or (-> e ex-data :line) (-> form meta :line)) column (or (-> e ex-data :column) (-> form meta :column))] (print (str file-name ":" line ":" column ": error: ")) (cond (instance? clojure.lang.ArityException e) (println (ex-message e)) node (do (println (ex-message e)) (println "Please open an issue and include the source code that caused this: ")) (ex-data e) (println (ex-message e)) :else (println e)))) (defn- compile-form [form] (let [ast (ana/analyze form)] (emitter/emit ast))) (defn- compile ([forms] (compile "NO_SOURCE_PATH" forms)) ([file-in forms] (let [!success (atom true)] (env/ensure (ana/global-env) (doseq [form forms] (try (compile-form form) (catch Exception e (reset! !success false) (binding [*out* *err*] (print-error file-in form e)))))) @!success))) (defn compile-file [file-in out-dir] (let [!success (atom true)] (try (let [forms (-> (slurp file-in) (reader/read-all-string)) file-out (str out-dir "/" (str/replace file-in #"\.[^.]+$" ".zig")) parent (-> (io/file file-out) (.getParentFile)) file-out (str/replace file-out #"^\./" "")] (when-not (.isDirectory parent) (.mkdirs parent)) (with-open [writer (io/writer file-out)] (binding [*out* writer] (when-not (compile file-in forms) (reset! !success false)))) (when @!success (let [{:keys [exit err]} (sh "zig" "fmt" file-out)] (when-not (zero? exit) (binding [*out* *err*] (reset! !success false) ;; No need to print extra info since Zig 's error output already includes the file name (print err) (flush)))))) (catch Exception e (reset! !success false) (binding [*out* *err*] (when-not (reader/print-error file-in e) (println file-in ": error: " e))))) @!success)) (defn compile-string [s] (let [!success (atom true)] (try (let [forms (reader/read-all-string s) out (with-out-str (when-not (compile forms) (reset! !success false)))] (when @!success (let [{:keys [exit err out]} (sh "zig" "fmt" "--stdin" :in out)] (if (zero? exit) (print out) (binding [*out* *err*] (reset! !success false) (print err) (flush)))))) (catch Exception e (reset! !success false) (binding [*out* *err*] (when-not (reader/print-error "NO_SOURCE_PATH" e) (println "error: " e))))) @!success)) (comment (let [form (first (reader/read-all-string "(defn a 0)")) _ (binding [*print-meta* true] * print - level * 5 ] (pprint form)) ast (env/ensure (ana/global-env) (ana/analyze form))] (binding [*print-meta* true] * print - level * 5 ] (pprint ast)) (emitter/emit ast)))
null
https://raw.githubusercontent.com/dundalek/liz/158129a160fe68646b164df585cae479a6cde231/src/liz/impl/compiler.clj
clojure
No need to print extra info since
(ns liz.impl.compiler (:refer-clojure :exclude [compile]) (:require [liz.impl.analyzer :as ana] [liz.impl.reader :as reader] [clojure.tools.analyzer.env :as env] [clojure.java.shell :refer [sh]] [liz.impl.emitter :as emitter] [clojure.pprint :refer [pprint]] [clojure.string :as str] [clojure.java.io :as io])) (defn- print-error [file-name form e] (let [{:keys [node]} (ex-data e) line (or (-> e ex-data :line) (-> form meta :line)) column (or (-> e ex-data :column) (-> form meta :column))] (print (str file-name ":" line ":" column ": error: ")) (cond (instance? clojure.lang.ArityException e) (println (ex-message e)) node (do (println (ex-message e)) (println "Please open an issue and include the source code that caused this: ")) (ex-data e) (println (ex-message e)) :else (println e)))) (defn- compile-form [form] (let [ast (ana/analyze form)] (emitter/emit ast))) (defn- compile ([forms] (compile "NO_SOURCE_PATH" forms)) ([file-in forms] (let [!success (atom true)] (env/ensure (ana/global-env) (doseq [form forms] (try (compile-form form) (catch Exception e (reset! !success false) (binding [*out* *err*] (print-error file-in form e)))))) @!success))) (defn compile-file [file-in out-dir] (let [!success (atom true)] (try (let [forms (-> (slurp file-in) (reader/read-all-string)) file-out (str out-dir "/" (str/replace file-in #"\.[^.]+$" ".zig")) parent (-> (io/file file-out) (.getParentFile)) file-out (str/replace file-out #"^\./" "")] (when-not (.isDirectory parent) (.mkdirs parent)) (with-open [writer (io/writer file-out)] (binding [*out* writer] (when-not (compile file-in forms) (reset! !success false)))) (when @!success (let [{:keys [exit err]} (sh "zig" "fmt" file-out)] (when-not (zero? exit) (binding [*out* *err*] (reset! !success false) Zig 's error output already includes the file name (print err) (flush)))))) (catch Exception e (reset! !success false) (binding [*out* *err*] (when-not (reader/print-error file-in e) (println file-in ": error: " e))))) @!success)) (defn compile-string [s] (let [!success (atom true)] (try (let [forms (reader/read-all-string s) out (with-out-str (when-not (compile forms) (reset! !success false)))] (when @!success (let [{:keys [exit err out]} (sh "zig" "fmt" "--stdin" :in out)] (if (zero? exit) (print out) (binding [*out* *err*] (reset! !success false) (print err) (flush)))))) (catch Exception e (reset! !success false) (binding [*out* *err*] (when-not (reader/print-error "NO_SOURCE_PATH" e) (println "error: " e))))) @!success)) (comment (let [form (first (reader/read-all-string "(defn a 0)")) _ (binding [*print-meta* true] * print - level * 5 ] (pprint form)) ast (env/ensure (ana/global-env) (ana/analyze form))] (binding [*print-meta* true] * print - level * 5 ] (pprint ast)) (emitter/emit ast)))
9ab7ac95d163426419759bf75356a12dc23299e85e6482ce1e8346a782b4e623
fizruk/http-api-data
FormUrlEncoded.hs
-- | values to and from @application / xxx - form - urlencoded@ format . module Web.FormUrlEncoded ( -- * Classes ToForm (..), FromForm (..), -- ** Keys for 'Form' entries ToFormKey(..), FromFormKey(..), -- * 'Form' type Form(..), * Encoding and decoding @'Form'@s urlEncodeAsForm, urlEncodeAsFormStable, urlDecodeAsForm, urlEncodeForm, urlEncodeFormStable, urlDecodeForm, * ' Generic 's genericToForm, genericFromForm, -- ** Encoding options FormOptions(..), defaultFormOptions, -- * Helpers toListStable, toEntriesByKey, toEntriesByKeyStable, fromEntriesByKey, lookupAll, lookupMaybe, lookupUnique, parseAll, parseMaybe, parseUnique, urlEncodeParams, urlDecodeParams, ) where import Web.Internal.FormUrlEncoded
null
https://raw.githubusercontent.com/fizruk/http-api-data/b0904171ab4c03898c002151fceb8c56d08216ce/src/Web/FormUrlEncoded.hs
haskell
| * Classes ** Keys for 'Form' entries * 'Form' type ** Encoding options * Helpers
values to and from @application / xxx - form - urlencoded@ format . module Web.FormUrlEncoded ( ToForm (..), FromForm (..), ToFormKey(..), FromFormKey(..), Form(..), * Encoding and decoding @'Form'@s urlEncodeAsForm, urlEncodeAsFormStable, urlDecodeAsForm, urlEncodeForm, urlEncodeFormStable, urlDecodeForm, * ' Generic 's genericToForm, genericFromForm, FormOptions(..), defaultFormOptions, toListStable, toEntriesByKey, toEntriesByKeyStable, fromEntriesByKey, lookupAll, lookupMaybe, lookupUnique, parseAll, parseMaybe, parseUnique, urlEncodeParams, urlDecodeParams, ) where import Web.Internal.FormUrlEncoded
a073fdfa87e3f1f13db3928d4b1b947b843cb53e0238d13c43aeb89123a58815
jlongster/gambit-iphone-example
app3.scm
;;;; "app3" ;;; renders a 3d box, which may bounce around some (declare (block) (standard-bindings) (extended-bindings)) (include "events#.scm") (include "obj-loader2.scm") (include "scene.scm") (include "physics.scm") ;;;;; settings (define %%settings (make-table)) (define (get-config name #!optional default) (table-ref %%settings name default)) (define (set-config name val) (table-set! %%settings name val)) ;;;;; masses (define-type mass constructor: really-make-mass mass position scene-object) (define (make-mass mass pos) (really-make-mass mass pos #f)) (define masses '()) (define (add-mass mass) (set! masses (cons mass masses)) (let ((obj (make-scene-object mass-mesh (make-vec3d 1. 1. 1.) (mass-position mass) (make-vec4d 0.5 0.5 0. (* (random-real) 360.)) 1.5))) (mass-scene-object-set! mass obj) (scene-list-add obj))) (define (mass-apply-gravity) (for-each (lambda (mass) (for-each (lambda (el) (if (and (scene-object-velocity el) (scene-object-radius el)) (let* ((v (vec3d-sub (mass-position mass) (scene-object-position el))) (d (- (vec3d-length v) (scene-object-radius el) (scene-object-radius (mass-scene-object mass)))) (F (* 6.67428e-11 (/ (* (mass-mass mass) OBJECT_MASS) (* d d)))) (accel (vec3d-scalar-mul (vec3d-unit v) (/ F OBJECT_MASS)))) (scene-object-velocity-set! el (vec3d-add (scene-object-velocity el) accel))))) scene-list)) masses)) (define (mass-lighting) (let loop ((i 0)) (if (< i 9) (begin (glDisable (+ GL_LIGHT0 i)) (loop (+ i 1))))) (let loop ((tail masses) (i 0)) (if (and (not (null? tail)) (< i 9)) (let ((pos (mass-position (car tail))) (light (+ GL_LIGHT0 i))) (glEnable light) (glLightf light GL_CONSTANT_ATTENUATION .5) (glLightfv light GL_AMBIENT (vector->GLfloat* (vector .05 .05 .05 1.))) (glLightfv light GL_POSITION (vector->GLfloat* (vector (vec3d-x pos) (vec3d-y pos) (vec3d-z pos) 1.))) (glLightfv light GL_DIFFUSE (vector->GLfloat* (vector 1. 1. 1. 1.))) (loop (cdr tail) (+ i 1)))))) (define OBJECT_MASS 1000.) ;;;;; throwing (define mass-mesh (obj-load (resource "resources/mass") #t)) (define sphere-mesh (obj-load (resource "resources/sphere") #t)) (define collision-mesh (obj-load (resource "resources/collision") #t)) (define (spread-number fl) (- (* fl 2.) 1.)) (define (throw pos vel) (define (random-color) (random-real)) (let ((then (real-time))) (scene-list-add (make-scene-object sphere-mesh (make-vec3d (random-color) (random-color) (random-color)) pos ( make - vec4d 0 . 1 . 0 . -90 . ) #f 1.5 vel #f)))) ;;;;; collisions (define collision-reference (make-table)) (define (reset-table!) (set! collision-reference (make-table))) (define (obj-collided? obj1 obj2) ;; sphere collision (let ((diff (vec3d-sub (scene-object-position obj1) (scene-object-position obj2))) (r1 (scene-object-radius obj1)) (r2 (scene-object-radius obj2))) (and r1 r2 (< (vec3d-length diff) (+ r1 r2 -1.))))) ;; (define (detect-collisions) ;; (reset-table!) ;; (fold ( lambda ( obj1 acc ) ( or acc ;; (fold ;; (lambda (obj2 acc) ( or acc ( and ( not ( table - ref collision - reference ( list obj1 obj2 ) # f ) ) ( not ( eq ? ) ) ;; (obj-collided? obj1 obj2)))) ;; #f ;; scene-list))) ;; #f ;; scene-list)) (define (detect-collisions) (fold (lambda (mass acc) (let ((obj1 (mass-scene-object mass))) (or acc (fold (lambda (obj2 acc) (or acc (and (not (eq? obj1 obj2)) (obj-collided? obj1 obj2)))) #f scene-list)))) #f masses)) ;;;;; controls (define (screen-to-space x y) (let* ((width (UIView-width (current-view))) (height (UIView-height (current-view))) (pers (current-perspective)) (x-width (- (perspective-xmax pers) (perspective-xmin pers))) (y-width (- (perspective-ymax pers) (perspective-ymin pers)))) (vec3d-unit (make-vec3d (- (perspective-xmax pers) (* (/ x width) x-width)) (- (perspective-ymax pers) (* (/ y height) y-width)) (perspective-znear pers))))) (define %%touch-times (make-table)) (define (touch-record-time touch) (table-set! %%touch-times touch (real-time))) (define (touch-pop-life-time touch) (let ((v (table-ref %%touch-times touch))) (table-set! %%touch-times touch) (- (real-time) v))) (define-event-handler (touches-began touches event) (let ((now (real-time))) (for-each (lambda (touch) (touch-record-time touch)) touches))) (define-event-handler (touches-ended touches event) (for-each (lambda (touch) (if (not collided) (let ((loc (UITouch-location touch)) (power (touch-pop-life-time touch))) (user-toss-ball (screen-to-space (car loc) (cdr loc)) power)))) touches)) (define (user-toss-ball dir power) (throw (vec3d-scalar-mul dir (get-config "touch-depth")) (vec3d-scalar-mul (vec3d-unit (vec3d-component-mul dir (get-config "touch-dir"))) (user-force power)))) (define (user-force power) (let ((power (max 0. (min 1. power))) (f (get-config "touch-force"))) (- f (* power power f)))) ;;;;; app (define collided #f) (define reset-camera glLoadIdentity) (define (init) (random-source-randomize! default-random-source) ;; opengl (let* ((fov 40.) (aspect (/ (UIView-width (current-view)) (UIView-height (current-view))))) (glMatrixMode GL_PROJECTION) (glLoadIdentity) (perspective fov aspect 1. 1000.) (lookat (make-vec3d 0. 0. 0.) (make-vec3d 0. 0. 1.) (make-vec3d 0. 1. 0.)) (glMatrixMode GL_MODELVIEW) (glLoadIdentity)) (glEnable GL_DEPTH_TEST) (glDisable GL_CULL_FACE) (glShadeModel GL_SMOOTH) (glEnable GL_RESCALE_NORMAL) (glEnable GL_LIGHTING) (glEnable GL_LIGHT0) (glLightf GL_LIGHT0 GL_CONSTANT_ATTENUATION .6) (glLightfv GL_LIGHT0 GL_AMBIENT (vector->GLfloat* (vector .15 .15 .15 1.))) (glLightfv GL_LIGHT0 GL_POSITION (vector->GLfloat* (vector 25. 25. 0. 1.))) (glLightfv GL_LIGHT0 GL_DIFFUSE (vector->GLfloat* (vector 1. 1. 1. 1.))) (glFogx GL_FOG_MODE GL_EXP2) (glFogfv GL_FOG_COLOR (vector->GLfloat* (vector 0. 0. 0. 1.))) (glFogf GL_FOG_DENSITY .01) (glFogf GL_FOG_START 1.) (glFogf GL_FOG_END 1000.) (glEnable GL_FOG) (current-level) (set! GRAVITY (make-vec3d 0. 0. 0.))) (define (level1) (set-config "touch-force" 19.) (set-config "touch-dir" (make-vec3d 15. 15. 5.)) (set-config "touch-depth" 10.) (add-mass (make-mass 5.3736e11 (make-vec3d 0. 0. 25.)))) (define (level2) (set-config "touch-force" 25.) (set-config "touch-dir" (make-vec3d 15. 15. 5.)) ( add - mass ( make - mass 4.9736e11 ( make - vec3d -10 . 10 . 35 . ) ) ) (add-mass (make-mass 5.3736e13 (make-vec3d 7. -10. 45.))) ( add - mass ( make - mass 1.3736e11 ( make - vec3d -3 . -7 . 35 . ) ) ) (add-mass (make-mass 1.3736e11 (make-vec3d 3. 10. 45.)))) (define (reset-and-add mass) (reset) (add-mass mass)) (define current-level level1) (define (reset #!optional make-level) (set! scene-list '()) (set! masses '()) (set! collided #f) (if make-level (current-level))) (define (run) (if (and (not collided) (detect-collisions)) (let ((now (real-time))) (set! collided (real-time)) (scene-list-add (make-scene-object collision-mesh (make-vec3d .8 .5 .2) (make-vec3d 0. 0. 6.) (make-vec4d 0. 1. 0. 180.) #f (make-vec3d 0. 0. 0.) (make-vec3d 0. 0. 0.) (lambda (el) (if (> (real-time) (+ now 1.)) (begin (scene-object-velocity-set! el #f) (scene-object-acceleration-set! el #f)))))))) (if (and collided (> (real-time) (+ collided 2.))) (begin ( set ! current - level ( if ( eq ? current - level ) level2 ;; level1)) (reset #t))) (mass-apply-gravity) (scene-list-update update-physics)) (define (render) (glClearColor 0. 0. 0. 1.) (glClear (bitwise-ior GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT)) (run) ;(mass-lighting) (run-render-queue (scene-list->render-queue)) (##gc)) (define (get-title) "")
null
https://raw.githubusercontent.com/jlongster/gambit-iphone-example/e55d915180cb6c57312cbb683d81823ea455e14f/lib/apps/app3.scm
scheme
"app3" renders a 3d box, which may bounce around some settings masses throwing collisions sphere collision (define (detect-collisions) (reset-table!) (fold (fold (lambda (obj2 acc) (obj-collided? obj1 obj2)))) #f scene-list))) #f scene-list)) controls app opengl level1)) (mass-lighting)
(declare (block) (standard-bindings) (extended-bindings)) (include "events#.scm") (include "obj-loader2.scm") (include "scene.scm") (include "physics.scm") (define %%settings (make-table)) (define (get-config name #!optional default) (table-ref %%settings name default)) (define (set-config name val) (table-set! %%settings name val)) (define-type mass constructor: really-make-mass mass position scene-object) (define (make-mass mass pos) (really-make-mass mass pos #f)) (define masses '()) (define (add-mass mass) (set! masses (cons mass masses)) (let ((obj (make-scene-object mass-mesh (make-vec3d 1. 1. 1.) (mass-position mass) (make-vec4d 0.5 0.5 0. (* (random-real) 360.)) 1.5))) (mass-scene-object-set! mass obj) (scene-list-add obj))) (define (mass-apply-gravity) (for-each (lambda (mass) (for-each (lambda (el) (if (and (scene-object-velocity el) (scene-object-radius el)) (let* ((v (vec3d-sub (mass-position mass) (scene-object-position el))) (d (- (vec3d-length v) (scene-object-radius el) (scene-object-radius (mass-scene-object mass)))) (F (* 6.67428e-11 (/ (* (mass-mass mass) OBJECT_MASS) (* d d)))) (accel (vec3d-scalar-mul (vec3d-unit v) (/ F OBJECT_MASS)))) (scene-object-velocity-set! el (vec3d-add (scene-object-velocity el) accel))))) scene-list)) masses)) (define (mass-lighting) (let loop ((i 0)) (if (< i 9) (begin (glDisable (+ GL_LIGHT0 i)) (loop (+ i 1))))) (let loop ((tail masses) (i 0)) (if (and (not (null? tail)) (< i 9)) (let ((pos (mass-position (car tail))) (light (+ GL_LIGHT0 i))) (glEnable light) (glLightf light GL_CONSTANT_ATTENUATION .5) (glLightfv light GL_AMBIENT (vector->GLfloat* (vector .05 .05 .05 1.))) (glLightfv light GL_POSITION (vector->GLfloat* (vector (vec3d-x pos) (vec3d-y pos) (vec3d-z pos) 1.))) (glLightfv light GL_DIFFUSE (vector->GLfloat* (vector 1. 1. 1. 1.))) (loop (cdr tail) (+ i 1)))))) (define OBJECT_MASS 1000.) (define mass-mesh (obj-load (resource "resources/mass") #t)) (define sphere-mesh (obj-load (resource "resources/sphere") #t)) (define collision-mesh (obj-load (resource "resources/collision") #t)) (define (spread-number fl) (- (* fl 2.) 1.)) (define (throw pos vel) (define (random-color) (random-real)) (let ((then (real-time))) (scene-list-add (make-scene-object sphere-mesh (make-vec3d (random-color) (random-color) (random-color)) pos ( make - vec4d 0 . 1 . 0 . -90 . ) #f 1.5 vel #f)))) (define collision-reference (make-table)) (define (reset-table!) (set! collision-reference (make-table))) (define (obj-collided? obj1 obj2) (let ((diff (vec3d-sub (scene-object-position obj1) (scene-object-position obj2))) (r1 (scene-object-radius obj1)) (r2 (scene-object-radius obj2))) (and r1 r2 (< (vec3d-length diff) (+ r1 r2 -1.))))) ( lambda ( obj1 acc ) ( or acc ( or acc ( and ( not ( table - ref collision - reference ( list obj1 obj2 ) # f ) ) ( not ( eq ? ) ) (define (detect-collisions) (fold (lambda (mass acc) (let ((obj1 (mass-scene-object mass))) (or acc (fold (lambda (obj2 acc) (or acc (and (not (eq? obj1 obj2)) (obj-collided? obj1 obj2)))) #f scene-list)))) #f masses)) (define (screen-to-space x y) (let* ((width (UIView-width (current-view))) (height (UIView-height (current-view))) (pers (current-perspective)) (x-width (- (perspective-xmax pers) (perspective-xmin pers))) (y-width (- (perspective-ymax pers) (perspective-ymin pers)))) (vec3d-unit (make-vec3d (- (perspective-xmax pers) (* (/ x width) x-width)) (- (perspective-ymax pers) (* (/ y height) y-width)) (perspective-znear pers))))) (define %%touch-times (make-table)) (define (touch-record-time touch) (table-set! %%touch-times touch (real-time))) (define (touch-pop-life-time touch) (let ((v (table-ref %%touch-times touch))) (table-set! %%touch-times touch) (- (real-time) v))) (define-event-handler (touches-began touches event) (let ((now (real-time))) (for-each (lambda (touch) (touch-record-time touch)) touches))) (define-event-handler (touches-ended touches event) (for-each (lambda (touch) (if (not collided) (let ((loc (UITouch-location touch)) (power (touch-pop-life-time touch))) (user-toss-ball (screen-to-space (car loc) (cdr loc)) power)))) touches)) (define (user-toss-ball dir power) (throw (vec3d-scalar-mul dir (get-config "touch-depth")) (vec3d-scalar-mul (vec3d-unit (vec3d-component-mul dir (get-config "touch-dir"))) (user-force power)))) (define (user-force power) (let ((power (max 0. (min 1. power))) (f (get-config "touch-force"))) (- f (* power power f)))) (define collided #f) (define reset-camera glLoadIdentity) (define (init) (random-source-randomize! default-random-source) (let* ((fov 40.) (aspect (/ (UIView-width (current-view)) (UIView-height (current-view))))) (glMatrixMode GL_PROJECTION) (glLoadIdentity) (perspective fov aspect 1. 1000.) (lookat (make-vec3d 0. 0. 0.) (make-vec3d 0. 0. 1.) (make-vec3d 0. 1. 0.)) (glMatrixMode GL_MODELVIEW) (glLoadIdentity)) (glEnable GL_DEPTH_TEST) (glDisable GL_CULL_FACE) (glShadeModel GL_SMOOTH) (glEnable GL_RESCALE_NORMAL) (glEnable GL_LIGHTING) (glEnable GL_LIGHT0) (glLightf GL_LIGHT0 GL_CONSTANT_ATTENUATION .6) (glLightfv GL_LIGHT0 GL_AMBIENT (vector->GLfloat* (vector .15 .15 .15 1.))) (glLightfv GL_LIGHT0 GL_POSITION (vector->GLfloat* (vector 25. 25. 0. 1.))) (glLightfv GL_LIGHT0 GL_DIFFUSE (vector->GLfloat* (vector 1. 1. 1. 1.))) (glFogx GL_FOG_MODE GL_EXP2) (glFogfv GL_FOG_COLOR (vector->GLfloat* (vector 0. 0. 0. 1.))) (glFogf GL_FOG_DENSITY .01) (glFogf GL_FOG_START 1.) (glFogf GL_FOG_END 1000.) (glEnable GL_FOG) (current-level) (set! GRAVITY (make-vec3d 0. 0. 0.))) (define (level1) (set-config "touch-force" 19.) (set-config "touch-dir" (make-vec3d 15. 15. 5.)) (set-config "touch-depth" 10.) (add-mass (make-mass 5.3736e11 (make-vec3d 0. 0. 25.)))) (define (level2) (set-config "touch-force" 25.) (set-config "touch-dir" (make-vec3d 15. 15. 5.)) ( add - mass ( make - mass 4.9736e11 ( make - vec3d -10 . 10 . 35 . ) ) ) (add-mass (make-mass 5.3736e13 (make-vec3d 7. -10. 45.))) ( add - mass ( make - mass 1.3736e11 ( make - vec3d -3 . -7 . 35 . ) ) ) (add-mass (make-mass 1.3736e11 (make-vec3d 3. 10. 45.)))) (define (reset-and-add mass) (reset) (add-mass mass)) (define current-level level1) (define (reset #!optional make-level) (set! scene-list '()) (set! masses '()) (set! collided #f) (if make-level (current-level))) (define (run) (if (and (not collided) (detect-collisions)) (let ((now (real-time))) (set! collided (real-time)) (scene-list-add (make-scene-object collision-mesh (make-vec3d .8 .5 .2) (make-vec3d 0. 0. 6.) (make-vec4d 0. 1. 0. 180.) #f (make-vec3d 0. 0. 0.) (make-vec3d 0. 0. 0.) (lambda (el) (if (> (real-time) (+ now 1.)) (begin (scene-object-velocity-set! el #f) (scene-object-acceleration-set! el #f)))))))) (if (and collided (> (real-time) (+ collided 2.))) (begin ( set ! current - level ( if ( eq ? current - level ) level2 (reset #t))) (mass-apply-gravity) (scene-list-update update-physics)) (define (render) (glClearColor 0. 0. 0. 1.) (glClear (bitwise-ior GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT)) (run) (run-render-queue (scene-list->render-queue)) (##gc)) (define (get-title) "")
3f81cd69c4d89dc77c2b87d77b9c762edad0be5a47d17c4c1d65efaac2b0058a
clojurewerkz/meltdown
consumers.clj
Copyright ( c ) 2013 - 2014 , , and the ClojureWerkz Team . ;; Licensed under the Apache License , Version 2.0 ( the " License " ) ; ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; -2.0 ;; ;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns clojurewerkz.meltdown.consumers "Operations on consumers and registrations" (:require [clojurewerkz.meltdown.events :as ev]) (:import [reactor.function Consumer] reactor.core.Reactor [reactor.event.registry Registration Registry] [clojurewerkz.meltdown IFnConsumer IFnTransformingConsumer] clojure.lang.IFn)) (defn ^Consumer from-fn "Instantiates a transforming Reactor consumer from a Clojure function. The consumer will automatically convert Reactor events to Clojure maps." [^IFn f] (IFnTransformingConsumer. f ev/event->map)) (defn ^Consumer from-fn-raw "Instantiates a reactor consumer from a Clojure function" [^IFn f] (IFnConsumer. f)) (defn ^{:tag 'boolean} paused? [^Registration reg] (.isPaused reg)) (defn ^Registration pause [^Registration reg] (.pause reg)) (defn ^Registration resume [^Registration reg] (.resume reg)) (defn ^{:tag 'boolean} cancelled? [^Registration reg] (.isCancelled reg)) (defn ^Registration cancel [^Registration reg] (.cancel reg)) (defn ^{:tag 'boolean} cancel-after-use? [^Registration reg] (.isCancelAfterUse reg)) (defn ^Registration cancel-after-use [^Registration reg] (.cancelAfterUse reg)) (defn ^Registry consumer-registry-of [^Reactor r] (.getConsumerRegistry r)) (defn consumers-on [^Reactor r] (let [^Registry xs (consumer-registry-of r)] (remove nil? (into [] xs)))) (defn ^{:tag 'long} consumer-count [^Reactor r] (let [^Registry xs (consumer-registry-of r)] (count (remove nil? (into [] xs)))))
null
https://raw.githubusercontent.com/clojurewerkz/meltdown/58d50141bb35b4a5abf59dcb13db9f577b6b3b9f/src/clojure/clojurewerkz/meltdown/consumers.clj
clojure
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright ( c ) 2013 - 2014 , , and the ClojureWerkz Team . distributed under the License is distributed on an " AS IS " BASIS , (ns clojurewerkz.meltdown.consumers "Operations on consumers and registrations" (:require [clojurewerkz.meltdown.events :as ev]) (:import [reactor.function Consumer] reactor.core.Reactor [reactor.event.registry Registration Registry] [clojurewerkz.meltdown IFnConsumer IFnTransformingConsumer] clojure.lang.IFn)) (defn ^Consumer from-fn "Instantiates a transforming Reactor consumer from a Clojure function. The consumer will automatically convert Reactor events to Clojure maps." [^IFn f] (IFnTransformingConsumer. f ev/event->map)) (defn ^Consumer from-fn-raw "Instantiates a reactor consumer from a Clojure function" [^IFn f] (IFnConsumer. f)) (defn ^{:tag 'boolean} paused? [^Registration reg] (.isPaused reg)) (defn ^Registration pause [^Registration reg] (.pause reg)) (defn ^Registration resume [^Registration reg] (.resume reg)) (defn ^{:tag 'boolean} cancelled? [^Registration reg] (.isCancelled reg)) (defn ^Registration cancel [^Registration reg] (.cancel reg)) (defn ^{:tag 'boolean} cancel-after-use? [^Registration reg] (.isCancelAfterUse reg)) (defn ^Registration cancel-after-use [^Registration reg] (.cancelAfterUse reg)) (defn ^Registry consumer-registry-of [^Reactor r] (.getConsumerRegistry r)) (defn consumers-on [^Reactor r] (let [^Registry xs (consumer-registry-of r)] (remove nil? (into [] xs)))) (defn ^{:tag 'long} consumer-count [^Reactor r] (let [^Registry xs (consumer-registry-of r)] (count (remove nil? (into [] xs)))))
3eac79495f81fbe39a672831195b06cf99dbc9371446d76b3a9fde381abaac3a
chebert/schemeish
continuations.lisp
(in-package :schemeish.backend) (install-syntax!) (def (full-ordinary-lambda-list ordinary-lambda-list) "Return a lambda list with optional/keywords fully expanded to their (name default-value provided?) form. If necessary, unique symbols will be generated for provided? names. Aux variables will be (name value)" (append* (map-ordinary-lambda-list (lambda (key parameter) (ecase key ((:positional :rest) (list parameter)) ((:optional :key) (cond ((pair? parameter) (define-destructuring (name &optional default-value provided?) parameter) (list (list name default-value (if provided? provided? (unique-symbol (symbolicate name '-provided?)))))) (t (list (list parameter nil (unique-symbol (symbolicate parameter '-provided?))))))) (:keyword (list parameter)) (:aux (cond ((pair? parameter) (define-destructuring (name &optional default-value) parameter) (list (list name default-value))) (t (list (list parameter nil))))))) ordinary-lambda-list))) (def (full-ordinary-lambda-list->function-argument-list-form full-lambda-list) (let (rest-provided? ;; Required arguments are symbols required-arguments ;; Optional arguments are lists optional-arguments) (map-ordinary-lambda-list (lambda (key parameter) (ecase key (:positional (push parameter required-arguments)) (:optional (define-destructuring (name default-value provided?) parameter) (push `(when ,provided? (list ,name)) optional-arguments)) (:keyword) (:key (unless rest-provided? (define-destructuring (name default-value provided?) parameter) (push `(when ,provided? (list ,(make-keyword name) ,name)) optional-arguments))) (:rest (set! rest-provided? t) (push parameter optional-arguments)) (:aux ()))) full-lambda-list) `(list* ,@(nreverse required-arguments) (nconc ,@(nreverse optional-arguments))))) (assert (equal? (with-readable-symbols (full-ordinary-lambda-list->function-argument-list-form (full-ordinary-lambda-list '(p1 p2 p3 &optional o1 o2 o3 &key k1 k2 k3 &aux aux1 aux2 aux3)))) '(list* P1 P2 P3 (NCONC (WHEN O1-PROVIDED? (LIST O1)) (WHEN O2-PROVIDED? (LIST O2)) (WHEN O3-PROVIDED? (LIST O3)) (WHEN K1-PROVIDED? (LIST :K1 K1)) (WHEN K2-PROVIDED? (LIST :K2 K2)) (WHEN K3-PROVIDED? (LIST :K3 K3)))))) (assert (equal? (with-readable-symbols (full-ordinary-lambda-list->function-argument-list-form (full-ordinary-lambda-list '(p1 p2 p3 &optional o1 o2 o3 &rest rest &key k1 k2 k3 &aux aux1 aux2 aux3)))) '(LIST* P1 P2 P3 (NCONC (WHEN O1-PROVIDED? (LIST O1)) (WHEN O2-PROVIDED? (LIST O2)) (WHEN O3-PROVIDED? (LIST O3)) REST)))) (for-macros (defvar *function->cps-function-table* (make-hash-table :weakness :key))) (defmacro with-lexical-function-names (function-names &body body) `(let ((*lexical-context* (alist-update *lexical-context* :lexical-function-names (lambda (names) (append ,function-names names))))) ,@body)) (def (lexical-function-name? function-name) (member function-name (alist-ref *lexical-context* :lexical-function-names))) (define (function->cps-function function) "Return the cps-function associated with function or the function itself if there is none." (hash-ref *function->cps-function-table* function)) (define (set-cps-function! function cps-function) "Associate the cps-function with the given function." (hash-set! *function->cps-function-table* function cps-function)) (for-macros (defvar *continuation* #'values)) (defmacro with-continuation (form continuation) "Evaluates form with *continuation* bound to the new continuation. Under normal circumstances, this means the values of form will be passed to the lambda-list before evaluating the continuation-body." `(cl:let ((*continuation* ,continuation)) ,form)) (defmacro without-continuation (&body body) "Evaluates body with *CONTINUATION* bound to #'VALUES" `(cl:let ((*continuation* #'values)) ,@body)) (defmacro save-continuation (name &body body) "Binds name to *CONTINUATION* in body" `(let ((,name *continuation*)) ,@body)) (def (continue-with . values) (*continuation* . values)) (def (continue-with* values) (*continuation* . values)) (defmacro continue-with-values (values-form) `(multiple-value-call *continuation* ,values-form)) (for-macros (defvar *transform-cps-special-form-table* (make-hash-table))) (define (register-transform-cps-special-form symbol transform) (hash-set! *transform-cps-special-form-table* symbol transform)) (for-macros (register-transformer 'cps (make-transformer *transform-cps-special-form-table* 'transform-cps-proper-list (lambda (_ expression _) (error "Attempt to compile invalid dotted list: ~S" expression)) (lambda (_ expression _) (error "Attempt to compile invalid cyclic list: ~S" expression)) 'transform-cps-atom))) (define (transform-cps form) (transform 'cps form)) (define (transform-cps* forms) (transform* 'cps forms)) (defmacro cps (expr) "Transforms EXPR into continuation-passing-style." (transform-cps expr)) (defmacro define-transform-cps-special-form (name (expression environment) &body body) "Define a special form transformer for the CPS macro-expansion. Name is the symbol naming the special-form. Expression will be bound to the special form being transformed, and environment will be bound to the current lexical environment for body. Body should evaluate to the transformed form." (let ((transformer (unique-symbol 'transformer))) `(for-macros (register-transform-cps-special-form ',name (cl:lambda (,transformer ,expression ,environment) (cl:declare (ignore ,transformer)) (cl:declare (ignorable ,expression ,environment)) (scm ,@body)))))) (def (atom->cps expression) `(continue-with ,expression)) (def (transform-cps-atom _ expression _) "Return a form that evaluates an atom in CPS." (atom->cps expression)) (defmacro with-return-to-saved-continuation (continuation &body body) "Evaluates from with *CONTINUATION* bound to continuation" `(cl:let ((*continuation* ,continuation)) ,@body)) (defmacro with-primary-value-continuation ((primary-value-name form) &body continuation-body) "Evaluates form with *CONTINUATION* bound to continuation-body. Only the primary-value is passed to continuation body. If no values are passed to the continuation, the primary-value is NIL." (let ((ignored-rest-of-values (unique-symbol 'ignored-rest-of-values))) `(with-continuation ,form (cl:lambda (&optional ,primary-value-name &rest ,ignored-rest-of-values) (declare (ignore ,ignored-rest-of-values)) (declare (ignorable ,primary-value-name)) ,@continuation-body)))) (defmacro with-ignored-values-continuation (form &body continuation-body) "Evaluates form with *CONTINUATION* bound to continuation-body. Ignores values passed to the continuation." (let ((ignored-values (unique-symbol 'ignored-values))) `(with-continuation ,form (cl:lambda (&rest ,ignored-values) (declare (ignore ,ignored-values)) ,@continuation-body)))) (defmacro with-values-continuation ((values-name form) &body continuation-body) "Evaluates form with *CONTINUATION* bound to continuation-body. Binds values passed to the continuation to VALUES-NAME." `(with-continuation ,form (cl:lambda (&rest ,values-name) ,@continuation-body))) (def (eval-arguments->cps-form argument-forms form-proc) "Return a form that evalautes argument-forms from left to right in CPS, before evaluating (form-proc arguments)" (let iterate ((arguments ()) (argument-forms argument-forms)) (cond ((empty? argument-forms) (form-proc (nreverse arguments))) (t (define-destructuring (argument-form . rest-argument-forms) argument-forms) (define-unique-symbols argument) (define eval-rest-of-arguments-form (iterate (cons argument arguments) rest-argument-forms)) `(with-primary-value-continuation (,argument ,(transform-cps argument-form)) ,eval-rest-of-arguments-form))))) (def (apply/cc function-designator arguments) (def function (if (symbol? function-designator) (symbol-function function-designator) function-designator)) (def cps-function (function->cps-function function)) (if cps-function ;; If the function has an associated cps-function, we can just call it. (apply cps-function arguments) ;; If the function is an ordinary function, we need to deliver its returned values ;; to the continuation (multiple-value-call *continuation* (apply function arguments)))) (def (funcall/cc function-designator . arguments) (apply/cc function-designator arguments)) (def (transform-cps-proper-list _ expression _) "Return a form that evaluates function-application in CPS. Special cases currently exist for funcall and apply." (define-destructuring (function-name . argument-forms) expression) (define continue (make-symbol (format nil "CONTINUE-FROM ~S" function-name))) ;; Evaluate all arguments from left to right `(save-continuation ,continue ,(eval-arguments->cps-form argument-forms (cl:lambda (arguments) ;; Set up a catch. If a CPS-FUNCTION is called, it will call the continuation and throw the results ;; Otherwise, it will just return the values (cond ((lexical-function-name? function-name) ;; This is a known cps function, we can call it with continue as the continuation `(with-return-to-saved-continuation ,continue (,function-name ,@arguments))) ;; TODO: Special case higher order functions. funcall/apply/mapcar et. al. ((eq? function-name 'cl:funcall) `(with-return-to-saved-continuation ,continue (funcall/cc ,@arguments))) ((eq? function-name 'cl:apply) `(with-return-to-saved-continuation ,continue (apply/cc ,(first arguments) (list* ,@(rest arguments))))) ((eq? function-name 'dynamic-wind/cc) `(dynamic-wind ,continue ,@arguments)) ((eq? function-name 'run/cc) `(run ,continue ,@arguments)) ;; Special case values ((eq? function-name 'cl:values) `(funcall ,continue ,@arguments)) ;; TODO: Special case: functions which are known to not have CPS-FUNCTIONS (t ;; Otherwise funcall it with continue `(with-return-to-saved-continuation ,continue (funcall/cc ',function-name ,@arguments)))))))) (cps 1) (cps (+ 1 2)) (cps (+ (print 1) (print 2))) (cps (list (list 1 2 t 3))) (define-transform-cps-special-form no-cps (expression environment) (second expression)) (defmacro no-cps (expr) expr) (cps (list (no-cps (funcall *continuation* (list 1 2 t 3))))) (define-transform-cps-special-form cl:quote (expression environment) (atom->cps expression)) (cps (list '(1 2 3))) (def (progn->cps forms) (define-unique-symbols continue-from-progn) (def (progn->cps-iteration forms) ;; (progn . forms) (define-destructuring (cps-form . rest-of-forms) forms) (def form (transform-cps cps-form)) (cond ;; (progn form) => form ((empty? rest-of-forms) `(with-return-to-saved-continuation ,continue-from-progn ,form)) ;; (progn form . rest-of-forms) (t `(with-ignored-values-continuation ,form ,(progn->cps-iteration rest-of-forms))))) (cond ;; (progn) => nil ((empty? forms) (atom->cps nil)) ;; (progn form) => form ((empty? (rest forms)) (transform-cps (first forms))) ;; (progn . forms) (t `(save-continuation ,continue-from-progn ,(progn->cps-iteration forms))))) (define-transform-cps-special-form cl:progn (expression environment) (define forms (rest expression)) (progn->cps forms)) (cps (progn 1 2 3)) (cps (print (progn 1 2 3))) (cps (progn (print 1) (print 2) (print 3))) (define-transform-cps-special-form cl:let (expression environment) (define-destructuring (bindings . body) (rest expression)) (define-values (declarations forms) (parse-declarations body)) (define-unique-symbols continue-from-let) (def binding-names (map let-binding-name bindings)) (def (iterate bindings binding-values) (cond ((empty? bindings) (def new-bindings (map list binding-names (nreverse binding-values))) Establish bindings from name->let - binding - value - name in let `(cl:let ,new-bindings ,@declarations (with-return-to-saved-continuation ,continue-from-let ,(progn->cps forms)))) (t (define-destructuring (binding . rest-of-bindings) bindings) (define value-form (let-binding-value binding)) (define binding-value(unique-symbol (format nil "~S ~S " 'let-binding-value-for (let-binding-name binding)))) ;; Bind value to a unique name `(with-primary-value-continuation (,binding-value ,(transform-cps value-form)) ,(iterate rest-of-bindings (cons binding-value binding-values)))))) `(save-continuation ,continue-from-let ,(iterate bindings ()))) (cps (let ((a (values 1 2 3))) a)) (define-transform-cps-special-form cl:let* (expression environment) (define-destructuring (bindings . body) (rest expression)) (define-values (declarations forms) (parse-declarations body)) (define-unique-symbols continue-from-let*) (def (iterate bindings) (cond ;; Base case: Evaluate body ;; Unfortunately declarations can only apply to the body. ;; This is inevitable, since each binding depends on the previous binding. ((empty? bindings) ;; Unfortunately, using locally will cause most declarations to be out of scope. ;; The only real solution for this is to parse the declarations ourselves, ;; and sort them to be with the definition of the binding they are declaring. `(cl:locally ,@declarations (with-continuation ,(progn->cps forms) ,continue-from-let*))) ;; Iteration case: evaluate value of next binding, and bind it. (t (define-destructuring (binding . rest-of-bindings) bindings) (define name (let-binding-name binding)) (define value (let-binding-value binding)) ;; Evaluate the next binding's value, binding it to name. `(with-primary-value-continuation (,name ,(transform-cps value)) ,(iterate rest-of-bindings))))) `(save-continuation ,continue-from-let* ,(iterate bindings))) (cps (let* ((a (values 1 2 3))) a)) (def (function-binding->cps name full-lambda-list body) (define default-parameter-assignments ()) (define lambda-list (map-ordinary-lambda-list (lambda (key parameter) (ecase key (:positional parameter) ((:optional :key) (push `(unless ,(third parameter) (setq ,(first parameter) ,(second parameter))) default-parameter-assignments) (list (first parameter) nil (third parameter))) (:keyword parameter) (:rest parameter))) full-lambda-list)) (define-values (declarations forms) (parse-declarations body)) `(,name ,lambda-list ,@declarations ,(progn->cps (append (nreverse default-parameter-assignments) forms)))) (def (lambda->cps ordinary-lambda-list body) (define-unique-symbols ordinary-function cps-function) (def full-lambda-list (full-ordinary-lambda-list ordinary-lambda-list)) (def cps-function-form (function-binding->cps 'cl:lambda full-lambda-list body)) (def ordinary-function-form `(cl:lambda ,full-lambda-list ;; Call the underlying cps-function, returning the result to the caller, instead of the continuation. (without-continuation (apply/cc ,cps-function ,(full-ordinary-lambda-list->function-argument-list-form full-lambda-list))))) `(cl:let* ((,cps-function ,cps-function-form) ;; The continuation function curried with #'values as the continuation (,ordinary-function ,ordinary-function-form)) Transform the lambda expression and register it as the CPS - function of the function (set-cps-function! ,ordinary-function ,cps-function) ;; Return an ordinary function. ,ordinary-function)) (define-transform-cps-special-form cl:lambda (expression environment) (define-destructuring (ordinary-lambda-list . body) (rest expression)) `(continue-with ,(lambda->cps ordinary-lambda-list body))) (cps (funcall (cl:lambda (a b c) (values a b c)) :a :b :c)) (funcall (cps (cl:lambda (a b c) (values a b c))) :a :b :c) (define-transform-cps-special-form cl:setq (expression environment) (def pairs (setq-pairs expression)) (define-unique-symbols continue-from-setq) (define (pairs->cps pairs) (define (pair->cps pair rest-of-pairs last-pair?) (define-destructuring (name value-form) pair) (def value-name (unique-symbol (symbolicate name '-value))) `(with-primary-value-continuation (,value-name ,(transform-cps value-form)) (setq ,name ,value-name) ,(if last-pair? ;; If this is the last pair, call the continuation with the value. `(with-return-to-saved-continuation ,continue-from-setq ,(atom->cps value-name)) ;; Otherwise, continue setting pairs. (pairs->cps rest-of-pairs)))) (define-destructuring (pair . rest-of-pairs) pairs) (cond Base case : 1 pair remaining ((empty? rest-of-pairs) (pair->cps pair rest-of-pairs t)) ;; Iteration: (setq pair pairs...) (t (pair->cps pair rest-of-pairs nil)))) (cond ;; (setq) => nil ((empty? pairs) (atom->cps nil)) ( setq pair . pairs ... ) (t `(save-continuation ,continue-from-setq ,(pairs->cps pairs))))) (let (a b c) (list (cps (setq)) (cps (setq a 1)) a (cps (setq b (list a a) c (list b b))) (list a b c))) (define-transform-cps-special-form cl:if (expression environment) (define-destructuring (test-form then-form &optional else-form) (rest expression)) (define-unique-symbols continue-from-if if-test-result) `(save-continuation ,continue-from-if (with-primary-value-continuation (,if-test-result ,(transform-cps test-form)) (with-return-to-saved-continuation ,continue-from-if (cl:if ,if-test-result ,(transform-cps then-form) ,(transform-cps else-form)))))) (cps (if (print nil) (print 1) (print 2))) (define-transform-cps-special-form cl:the (expression environment) (define-destructuring (type-form value-form) (rest expression)) (define-unique-symbols results continue-from-the) `(save-continuation ,continue-from-the (with-values-continuation (,results ,(transform-cps value-form)) (with-return-to-saved-continuation ,continue-from-the (continue-with-values (the ,type-form (values-list ,results))))))) (cps (the (values number &optional) 1)) (cps (the (values number string &optional) (values 1 "string"))) (define-transform-cps-special-form cl:function (expression environment) (def function-name (second expression)) (cond ((lexical-function-name? function-name) ;; If its a lexical function name we need to return an ordinary function, with #'function ;; as an associated cps-function. This means we'll want the full lambda list associated ;; with defining the function. Also, if the ordinary funciton already exists we should ;; grab that. ;; For now though (error "TODO")) ;; Otherwise it's an ordinary atom (t (atom->cps expression)))) (define-transform-cps-special-form cl:multiple-value-call (expression environment) (define-destructuring (function-form . arguments) (rest expression)) (define-unique-symbols continue-from-multiple-value-call multiple-value-call-function) (def (eval-arguments->cps-form argument-forms form-proc) "Return a form that evalautes argument-forms from left to right in CPS, before evaluating (form-proc argument-lists)" (let iterate ((argument-lists ()) (argument-forms argument-forms) (index 0)) (cond ((empty? argument-forms) (form-proc (nreverse argument-lists))) (t (define-destructuring (argument-form . rest-argument-forms) argument-forms) (def argument-list (unique-symbol (format nil "MULTIPLE-VALUE-CALL-ARGUMENT-LIST-~S-" index))) `(with-values-continuation (,argument-list ,(transform-cps argument-form)) ,(iterate (cons argument-list argument-lists) rest-argument-forms (1+ index))))))) `(save-continuation ,continue-from-multiple-value-call ;; evalaute the primary value of function-form and capture it in FUNCTION (with-primary-value-continuation (,multiple-value-call-function ,(transform-cps function-form)) ;; evaluate the arguments... ,(eval-arguments->cps-form arguments (cl:lambda (argument-lists) ;; ...capturing the values of each argument as a list `(with-return-to-saved-continuation ,continue-from-multiple-value-call ;; Apply the function to the appended argument-lists (apply/cc ,multiple-value-call-function (append ,@argument-lists)))))))) (cps (multiple-value-call #'list (values 1 2 3) (values 4 5 6))) (define-transform-cps-special-form cl:eval-when (expression environment) (define-destructuring ((&rest situations) &body body) (rest expression)) if eval - when is called within a CPS form , then it is n't at the top level ;; so :load-toplevel and :compile-toplevel are irrelevant. ;; therefore we only need to handle the :execute case. (cond ((member :execute situations) (progn->cps body)) (t `(continue-with nil)))) (cps (progn (eval-when () (print 'hi)) (print 'after))) (cps (progn (eval-when (:execute) (print 'hi)) (print 'after))) ;; Macrolet (define-transform-cps-special-form cl:macrolet (expression environment) (define-destructuring (definitions &body body) (rest expression)) (define-values (declarations forms) (parse-declarations body)) `(cl:macrolet ,definitions ,@declarations ,(progn->cps body))) ;; symbol-Macrolet (define-transform-cps-special-form cl:symbol-macrolet (expression environment) (define-destructuring (definitions &body body) (rest expression)) (define-values (declarations forms) (parse-declarations body)) `(cl:symbol-macrolet ,definitions ,@declarations ,(progn->cps body))) ;; locally (define-transform-cps-special-form cl:locally (expression environment) (def body (rest expression)) (define-values (declarations forms) (parse-declarations body)) `(cl:locally ,@declarations ,(progn->cps forms))) ;; load-time-value ;; continuation barrier around load-time-value's form, since it is evaluated in a different context (define-transform-cps-special-form cl:load-time-value (expression environment) (define-destructuring (form &optional read-only?) (rest expression)) ;; cl:load-time-value only returns the primary value (atom->cps `(cl:load-time-value (without-continuation ,(transform-cps form)) ,read-only?))) multiple - value - prog1 : why is this a special form ? (define-transform-cps-special-form cl:multiple-value-prog1 (expression environment) (define-destructuring (values-form . forms) (rest expression)) (define-unique-symbols continue-from-multiple-value-prog1 multiple-value-prog1-results) `(save-continuation ,continue-from-multiple-value-prog1 Evaluate the values form first , saving the results (with-values-continuation (,multiple-value-prog1-results ,(transform-cps values-form)) (with-ignored-values-continuation ,(progn->cps forms) (with-return-to-saved-continuation ,continue-from-multiple-value-prog1 (continue-with* ,multiple-value-prog1-results)))))) (define-transform-cps-special-form cl:labels (expression environment) (define-destructuring (definitions &body body) (rest expression)) (define-values (declarations forms) (parse-declarations body)) (define (labels-binding->cps binding) (define-destructuring (name ordinary-lambda-list . body) binding) (def full-lambda-list (full-ordinary-lambda-list ordinary-lambda-list)) (function-binding->cps name full-lambda-list body)) (def function-names (map first definitions)) (with-lexical-function-names function-names `(cl:labels ,(map labels-binding->cps definitions) ,@declarations ,(progn->cps forms)))) (define-transform-cps-special-form cl:flet (expression environment) (define-destructuring (definitions &body body) (rest expression)) (define-values (declarations forms) (parse-declarations body)) (define (flet-binding->cps binding) (define-destructuring (name ordinary-lambda-list . body) binding) (def full-lambda-list (full-ordinary-lambda-list ordinary-lambda-list)) (function-binding->cps name full-lambda-list body)) (def function-names (map first definitions)) `(cl:flet ,(map flet-binding->cps definitions) ,@declarations ,(with-lexical-function-names function-names (progn->cps forms)))) ;; Dynamic forms (define-struct fcontrol-signal (tag value continuation) :opaque) (for-macros (defvar *fcontrol-tag* (unique-symbol "FCONTROL-TAG"))) (for-macros (defvar *prompt-established?* nil)) (def (run continue-from-run tag thunk handler) "Perform THUNK in a dynamic context that catches all tags (cons tag *current-run-tags*). Return the results to continue-from-run. If tag is caught because of (fcontrol tag value), the (handler value rest-of-thunk) is invoked with the rest-of-thunk. If a different tag is caught because of (fcontrol another-tag value), the control is re-signaled with the rest-of-thunk dynamically embedded in the prompt." ;; Execute the thunk, catching fcontrol-signals. (def thunk-result (let ((*prompt-established?* t)) (catch *fcontrol-tag* ;; Call thunk returning results as a list. (multiple-value-list (without-continuation (funcall/cc thunk)))))) (cond ;; If the result is an fcontrol-signal, it means an (FCONTROL value) form was encountered. ((fcontrol-signal? thunk-result) ;; TODO: Destructure structures (define fcontrol-tag (fcontrol-signal-tag thunk-result)) (define value (fcontrol-signal-value thunk-result)) (define rest-of-thunk (fcontrol-signal-continuation thunk-result)) (cond ((eq? tag fcontrol-tag) This is the tag we are trying to catch . Invoke the handler ( which may or may not be in CPS ) . ;; on the signal's value and continuation ;; Return the results to whoever called run. (with-return-to-saved-continuation continue-from-run (funcall/cc handler value rest-of-thunk))) (*prompt-established?* ;; If a prompt is established, then tag may be meant for an outer run. ;; re-throw with setting the prompt up again as part of the continuation (throw *fcontrol-tag* (make-fcontrol-signal fcontrol-tag value ;; Return a modified continuation (lambda arguments ;; When resumed, set up a prompt around the rest-of-thunk. (run continue-from-run tag (lambda () (apply rest-of-thunk arguments)) handler))))) ;; If this is not our tag, and there is no outer prompt established, then we have an error. (t (error "Outermost prompt ~S: No enclosing prompt found for fcontrol signal with tag ~S" tag fcontrol-tag)))) ;; Otherwise, we encountered a normal exit: return the results to whoever called run. (t (apply continue-from-run thunk-result)))) (def (default-prompt-handler value _continuation) value) (defvar *default-prompt-tag* (unique-symbol 'default-prompt-tag)) (defmacro % (expr &key (tag '*default-prompt-tag*) (handler '(function default-prompt-handler))) "Sets up a prompt with the given tag" `(no-cps (cps (run/cc ,tag (cl:lambda () ,expr) ,handler)))) (defmacro catch/cc ((&key (tag '*default-prompt-tag*) (handler '(function default-prompt-handler))) &body body) "Equivalent to (% (progn body...) :tag tag :handler handler)" `(% (progn ,@body) :tag ,tag :handler ,handler)) ;; (fcontrol tag values-form) ;; Evaluates tag, then value. ;; throws to tag with (make-fcontrol-signal tag value current-continuation), aborting the current continuation (define-transform-cps-special-form fcontrol (expression environment) (define-unique-symbols continue-from-fcontrol) (define arguments (rest expression)) `(save-continuation ,continue-from-fcontrol ,(eval-arguments->cps-form arguments (lambda (argument-names) (define-destructuring (tag value) argument-names) `(cond (*prompt-established?* ;; Throw to the nearest established prompt, if one is established (throw *fcontrol-tag* (make-fcontrol-signal ,tag ,value ,continue-from-fcontrol))) (t (error "Attempt to (FCONTROL ~S ~S) without an established prompt. See %, RUN." ,tag ,value))))))) (defmacro fcontrol (tag value) "Evaluates tag, then value, throwing tag, value, and the current continuation to the dynamically nearest established RUN, aborting the current continuation. If FCONTROL is evaluated in a non-CPS function, it issues a warning and evaluates to VALUE." (declare (ignore tag value)) `(error "Attempt to FCONTROL in a non-CPS environment.")) (defmacro throw/cc (&optional value (tag '*default-prompt-tag*)) "Equivalent to (FCONTROL TAG VALUE)." `(fcontrol ,tag ,value)) (define-transform-cps-special-form cl:block (expression environment) (define-destructuring (name . forms) (rest expression)) (define-unique-symbols block-tag) (define lexical-context (alist-update *lexical-context* :block-tag-alist (cut (alist-set _ name block-tag)))) (let ((*lexical-context* lexical-context)) (transform-cps `(run/cc ',block-tag (cl:lambda () ,@forms) (cl:lambda (results k) (declare (ignore k)) (values-list results)))))) (define-transform-cps-special-form cl:return-from (expression environment) (define-destructuring (name &optional values-form) (rest expression)) (define block-tag (alist-ref (alist-ref *lexical-context* :block-tag-alist) name)) (define-unique-symbols return-from-values) (unless block-tag (error "Could not find BLOCK named ~S in the current lexical environment." name)) `(with-values-continuation (,return-from-values ,(transform-cps values-form)) ,(transform-cps `(fcontrol ',block-tag ,return-from-values)))) (define-transform-cps-special-form cl:catch (expression environment) (define-destructuring (tag . forms) (rest expression)) (transform-cps `(run/cc ,tag (cl:lambda () ,@forms) (cl:lambda (results k) (declare (ignore k)) (values-list results))))) (define-transform-cps-special-form cl:throw (expression environment) (define-destructuring (tag-form results-form) (rest expression)) (define-unique-symbols tag results) `(with-primary-value-continuation (,tag ,(transform-cps tag-form)) (with-values-continuation (,results ,(transform-cps results-form)) ;; Return results to the prompt ,(transform-cps `(fcontrol ,tag ,results))))) (def (rethrow-if-fcontrol-signal signal modify-continuation) "If signal is an fcontrol-signal, re-throw it with modify-continuation applied to the signal-continuation." (when (fcontrol-signal? signal) Rethrow it , but with a modified continuation that calls dynamic - wind around the rest - of - thunk (def tag (fcontrol-signal-tag signal)) (def value (fcontrol-signal-value signal)) (def rest-of-thunk (fcontrol-signal-continuation signal)) (throw *fcontrol-tag* (make-fcontrol-signal tag value (modify-continuation rest-of-thunk))))) (def (dynamic-wind continue-from-dynamic-wind before-thunk thunk after-thunk) ;; evaluate before-thunk, ignoring results (with-ignored-values-continuation (funcall/cc before-thunk) ;; A normal-exit occurs when a thunk evaluates without encountering an fcontrol/condition (let (thunk-had-normal-exit? thunk-results after-thunk-had-normal-exit?) (unwind-protect ;; PROTECTED FORM ;; evaluate thunk (let ((result (catch *fcontrol-tag* ;; evaluate thunk, saving the returned values (set! thunk-results (multiple-value-list (without-continuation (funcall/cc thunk))))))) ;; If we caught an fcontrol-tag from within the thunk, rethrow with a modified continuation. (rethrow-if-fcontrol-signal result ;; Modify rest-of-thunk by wrapping it in an identical dynamic-wind (lambda (rest-of-thunk) ;; modified continuation: (cl:lambda (&rest arguments) (dynamic-wind continue-from-dynamic-wind before-thunk ;; Rest of thunk (cl:lambda () (with-return-to-saved-continuation rest-of-thunk (continue-with* arguments))) after-thunk)))) ;; if we made it here, thunk had a normal-exit (set! thunk-had-normal-exit? t)) ;; CLEANUP ;; evaluate after-thunk (let ((result (catch *fcontrol-tag* (without-continuation (funcall/cc after-thunk))))) ;; If we caught an fcontrol-signal in the after-thunk (rethrow-if-fcontrol-signal result ;; modify the rest of the after-thunk ;; return-to rest-of-thunk, before returning-to continue-from-dynamic-wind (lambda (rest-of-after-thunk) ;; Modified continuation: (cl:lambda (&rest arguments) (run (if thunk-had-normal-exit? (lambda _ (apply continue-from-dynamic-wind thunk-results)) values) (unique-symbol 'run) (cl:lambda () (apply rest-of-after-thunk arguments)) default-prompt-handler) ;; Call the rest of thunk with the arguments #; (with-ignored-values-continuation (apply/cc rest-of-after-thunk arguments) ;; If thunk exited normally, we can return the results to whoever called dynamic-wind. (print 'continuing-from-rest-of-after-thunk) (when thunk-had-normal-exit? (print 'thunk-had-normal-exit) ;; IF thunk had a normal-exit ;; then continue from dynamic-wind with the thunk-results (with-return-to-saved-continuation continue-from-dynamic-wind (print 'returning-from-dynamic-wind) (continue-with* thunk-results))) (when (not thunk-had-normal-exit?) (print 'thunk-did-not-have-normal-exit)))))) ;; IF we made it here, after-thunk had a normal-exit (set! after-thunk-had-normal-exit? t))) ;; If we had a normal exit from the thunk and the after-thunk, we need to call the continuation ;; with the thunk-results (when (and thunk-had-normal-exit? after-thunk-had-normal-exit?) (apply continue-from-dynamic-wind thunk-results))))) (define-transform-cps-special-form cl:unwind-protect (expression environment) (define-destructuring (protected &body cleanup) (rest expression)) ;; Don't allow re-entry into protected forms. (transform-cps `(let ((ok? t)) (dynamic-wind/cc (cl:lambda () (if ok? (set! ok? nil) (error "Attempt to re-enter the protected form of an unwind-protect."))) (cl:lambda () ,protected) (cl:lambda () ,@cleanup))))) (defvar *tagbody-go-tag* (unique-symbol 'tagbody-go-tag)) ;; Tagbody: ;; tags have lexical scope and dynamic extent ;; if there is no matching tag visible to go, results are undefined. (define-transform-cps-special-form cl:tagbody (expression environment) (define-destructuring (untagged-statements . tagged-forms) (parse-tagbody (rest expression))) (define-unique-symbols continue-from-tagbody thunk tagbody-prompt-tag tag-thunk) (define tags (map first tagged-forms)) (define (thunk-form statements) "Return a thunk that calls (progn statements...) in continuation-passing style." `(cl:lambda () (without-continuation ,(progn->cps statements)))) (define (tag-thunk-form statements next-tag) "Return a thunk that evaluates a tag's statements before calling the next-tag's thunk." (thunk-form (append statements (list `(funcall ,(tag->function-name next-tag)))))) (define (last-tag-thunk-form statements) "Return a thunk that evaluates a tag's statements." (thunk-form statements)) (define tag->function-name-alist (map (lambda (tag) (cons tag (unique-symbol (symbolicate tag '-function)))) tags)) (define (tag->function-name tag) (alist-ref tag->function-name-alist tag)) (define function-names (map tag->function-name tags)) (define (tag->statements tag) (alist-ref tagged-forms tag)) ;; GO needs to throw to a specific tagbody, and the name of a tag-thunk to throw (define (extend-lexical-context alist) (alist-update alist :tagbody-context-alist (lambda (alist) (append (map (lambda (tag) (cons tag (list tagbody-prompt-tag (tag->function-name tag)))) tags) alist)))) (let* ((*lexical-context* (extend-lexical-context *lexical-context*))) (define untagged-thunk-form (if (empty? tags) (last-tag-thunk-form untagged-statements) (tag-thunk-form untagged-statements (first tags)))) (define function-name-assignments (append (map (lambda (tag next-function-name) `(setq ,(tag->function-name tag) ,(tag-thunk-form (tag->statements tag) next-function-name))) tags (rest tags)) (map (lambda (tag) `(setq ,(tag->function-name tag) ,(last-tag-thunk-form (tag->statements tag)))) (last tags)))) `(let (,@function-names) ,@function-name-assignments (save-continuation ,continue-from-tagbody (let run-tagbody ((,thunk ,untagged-thunk-form)) (let (encountered-go?) (with-primary-value-continuation (,tag-thunk (run *continuation* ',tagbody-prompt-tag ,thunk (cl:lambda (tag-thunk _continue-from-go) (declare (ignore _continue-from-go)) (set! encountered-go? t) tag-thunk))) (if encountered-go? (run-tagbody ,tag-thunk) (with-return-to-saved-continuation ,continue-from-tagbody (continue-with nil)))))))))) (define-transform-cps-special-form cl:go (expression environment) (define-destructuring (tag) (rest expression)) (define tag-data (alist-ref (alist-ref *lexical-context* :tagbody-context-alist) tag)) (cond (tag-data (define-destructuring (tagbody-prompt-tag function-name) tag-data) (transform-cps `(fcontrol ',tagbody-prompt-tag ,function-name))) (t (error "Could not find TAG ~S in lexical-context of GO." tag)))) progv Progv forms can be re - entered , but the dynamic bindings will no longer be in effect . ;; TODO: It might be nice if we could resume with the dynamic bindings intact. ;; The issue is that we need to grab the current bindings right before exiting the continuation. ;; So that we can re-establish when resuming. ;; Since we only get the continuation after exiting the dynamic context, it's too late. ;; we would need to modify FCONTROL within cps progv forms to grab the current dynamic bindings ;; To do this, each fcontrol signal would need to have a list of dynamic bindings, as which ;; prompt they came from. ;; The alternative is to let dynamic bindings go, and instead rely on new forms that ;; establish fluid bindings. ;; It's hard to say which is the right default, but since I don't use progv that often anyways, ;; I don't have a problem with just dropping them for now. (define-transform-cps-special-form cl:progv (expression environment) (define-destructuring (vars-form vals-form &body forms) (rest expression)) (define-unique-symbols continue-from-progv vars vals progv-prompt-tag) `(save-continuation ,continue-from-progv (with-primary-value-continuation (,vars ,(transform-cps vars-form)) (with-primary-value-continuation (,vals ,(transform-cps vals-form)) (with-return-to-saved-continuation ,continue-from-progv ,(transform-cps `(run/cc ',progv-prompt-tag (cl:lambda () (no-cps (progv ,vars ,vals ,(progn->cps forms)))) #'default-prompt-handler))))))) (defmacro cps-form-equal? (form) (let ((results (unique-symbol 'results))) `(let ((,results (multiple-value-list ,form))) (values (equal? (multiple-value-list (cps ,form)) ,results) ,results)))) ;; atoms (assert (cps-form-equal? 1)) (assert (cps-form-equal? (no-cps (values 1 2 3)))) (assert (cps-form-equal? (no-cps (cps (values 1 2 3))))) ;; Function (assert (cps-form-equal? #'+)) ;; Quote (assert (cps-form-equal? '(the quick brown fox))) ;; function application (assert (cps-form-equal? (values 1 2 3 4 5))) (assert (cps-form-equal? (+ (values 1 2) (values 3 4)))) (assert (cps-form-equal? (+ 1 2 (+ 3 4)))) (assert (equal? (scm (let* ((xs ()) (push-v (lambda (x) (push x xs) x))) (list (% (+ ;; Called once (push-v 1) ;; Called each time continue is called. (twice) (push-v (fcontrol :pause :value)) ;; Called each time continue is called. (twice) (push-v 3)) :tag :pause :handler ;; Called once. (lambda (value continue) (: VALUE ( + 1 2 3 ) ( + 1 3 3 ) ) = > (: value 6 7 ) (list value (continue 2) (continue 3)))) (nreverse xs)))) '((:VALUE 6 7) (1 2 3 3 3)))) Progn (assert (cps-form-equal? (progn))) (assert (cps-form-equal? (progn (values 1 2 3)))) (assert (cps-form-equal? (progn 1 2 3 4 (values 1 2 3)))) (assert (equal? (with-output-to-string (s) (assert (equal? (multiple-value-list (cps (progn (format s "c") (format s "b") (format s "a") (values 1 2 3)))) '(1 2 3)))) "cba")) (assert (cps-form-equal? (progn '(the quick brown fox) #'+))) (assert (cps-form-equal? (progn #'+ '(the quick brown fox)))) ;; (progn forms... (fcontrol ...)) (assert (equal? (scm (% (progn (fcontrol :abort :value)) :tag :abort :handler (lambda (v k) (list v (multiple-value-list (k 1 2 3)) (multiple-value-list (k 4 5 6)))))) '(:value (1 2 3) (4 5 6)))) ;; (progn forms... (fcontrol ...) forms...) (assert (equal? (scm (let* ((vs ()) (v (lambda (x) (push x vs) x))) (list (% (progn (v (fcontrol :abort :value)) (v 2) (v 3)) :tag :abort :handler (lambda (v k) ;; vs: (3 2 1) (k 1) vs : ( 3 2 : one 3 2 1 ) (k :one) ;; :value v)) ( 3 2 : one 3 2 1 ) vs))) '(:VALUE (3 2 :ONE 3 2 1)))) ;; Let (assert (cps-form-equal? (let () (values 1 2 3)))) (assert (cps-form-equal? (let ((a 1) (b :steak)) (values a b)))) (assert (cps-form-equal? (let ((a (values 1 2 3)) (b (values :steak :sauce))) (values a b)))) Verifies that names are n't visible , but causes a warning ( assert ( not ( ignore - errors ( cps ( let ( ( a 1 ) ( b a ) ) ( values a b ) ) ) ) ) ) (assert (equal? (scm (% (let () (fcontrol :abort :value)) :tag :abort :handler (lambda (v k) (list v (multiple-value-list (k 1 2 3)))))) '(:value (1 2 3)))) (assert (equal? (scm (define vs ()) (define (v x) (push x vs) x) (list (% (let ((binding1 (v 1)) (binding2 (v (fcontrol :abort :value))) (binding3 (v 3))) (values binding1 binding2 binding3)) :tag :abort :handler (lambda (v k) (list ;; :value v ;; (1 2 3) (multiple-value-list (k 2 :ignored)) ( 1 : two 3 ) (multiple-value-list (k :two :ignored))))) (nreverse vs))) '((:VALUE (1 2 3) (1 :TWO 3)) (1 2 3 :TWO 3)))) ;; LET* (assert (cps-form-equal? (let* () (values 1 2 3)))) (assert (cps-form-equal? (let* ((a 1) (b (1+ a)) (c (1+ b))) c (values a b)))) (assert (cps-form-equal? (let* ((a 1) b (c (1+ a))) b (values a c)))) (assert (equal? (scm (% (let* () (fcontrol :abort :value)) :tag :abort :handler (lambda (v k) (list v (multiple-value-list (k 1 2 3)))))) '(:value (1 2 3)))) (assert (equal? (scm (define vs ()) (define (v x) (push x vs) x) (list (% (let* ((binding1 (v 1)) (binding2 (v (fcontrol :abort :value))) (binding3 (v (+ binding1 binding2)))) (values binding1 binding2 binding3)) :tag :abort :handler (lambda (v k) (list ;; :value v ( 1 2 ( + 1 2 ) ) (multiple-value-list (k 2 :ignored)) ( 1 4 ( + 1 4 ) ) (multiple-value-list (k 4 :ignored))))) (nreverse vs))) '((:VALUE (1 2 3) (1 4 5)) (1 2 3 4 5)))) ;; Lambda (assert (equal? (multiple-value-list (funcall (cps (cl:lambda (a b c) (values a b c))) 1 2 3)) '(1 2 3))) (assert (cps-form-equal? (funcall (cl:lambda (a b c) (values a b c)) 1 2 3))) (assert (equal? (multiple-value-list (funcall (cps (funcall (cl:lambda (f) (cl:lambda (&rest args) (apply f args))) (cl:lambda (&rest args) (apply #'values args)))) 1 2 3)) '(1 2 3))) (assert (equal? (scm (define vs ()) (define (v x) (push x vs) x) (list (% (funcall (cl:lambda (a b c) (values (v a) (v (fcontrol :abort b)) (v c))) 1 :value 3) :tag :abort :handler (lambda (v k) (list ;; :value v ;; (1 2 3) (multiple-value-list (k 2)) ( 1 : two 3 ) (multiple-value-list (k :two))))) (nreverse vs))) '((:VALUE (1 2 3) (1 :TWO 3)) (1 2 3 :TWO 3)))) (assert (equal? (scm (% (funcall (cl:lambda (p1 p2 &optional (o1 (fcontrol :abort :o1)) (o2 (fcontrol :abort :o2))) (list p1 p2 o1 o2)) :p1 :P2 :o1) :tag :abort :handler (cl:lambda (v k) (list v (funcall k :o2) (funcall k :o2-again))))) '(:O2 (:P1 :P2 :O1 :O2) (:P1 :P2 :O1 :O2-AGAIN)))) ;; Setq (assert (cps-form-equal? (setq))) (assert (let (a b c) (cps-form-equal? (setq a 1 b (1+ a) c (1+ b))))) (assert (equal? (scm (define vs ()) (define (v x) (push x vs) x) (let (a b c) (list (% (setq a (v :a) b (v (fcontrol :abort :value)) c (v b)) :tag :abort :handler (lambda (v k) (list v (list a b c) (k :b :ignored) (list a b c) (k :bee :ignored) (list a b c)))) (nreverse vs)))) '((:VALUE (:A NIL NIL) :B (:A :B :B) :BEE (:A :BEE :BEE)) (:A :B :B :BEE :BEE)))) ;; If (assert (cps-form-equal? (if (values t nil nil) (progn 1 2 3) Unreachable (values 4 5 6)))) (assert (cps-form-equal? (if (values nil t nil) (progn 1 2 3) (values 4 5 6)))) (assert (equal? (scm (define vs ()) (define (v x) (push x vs) x) (list (% (if (v (fcontrol :abort :value)) (v :true) (v :false)) :tag :abort :handler (lambda (v k) (list v (k t :ignored) (k nil :ignored)))) (nreverse vs))) '((:value :true :false) (t :true nil :false)))) ;; The (assert (cps-form-equal? (the (values number string &optional) (values 3 "string")))) (assert (equal? (scm (list (% (the (values number string &optional) (fcontrol :abort :value)) :tag :abort :handler (lambda (v k) (list v (multiple-value-list (k 3 "hello"))))))) '((:VALUE (3 "hello"))))) ;; Multiple-value-call (assert (cps-form-equal? (multiple-value-call (values #'list 2 3 4) (values) (values)))) (assert (cps-form-equal? (multiple-value-call (values #'list 2 3 4)))) (assert (cps-form-equal? (multiple-value-call (values #'values 2 3 4) (values 1 2) (values 3 4) (values 5 6)))) (assert (equal? (scm (define vs ()) (define (v x) (push x vs) x) (list (% (multiple-value-call list (values (v 1) (v 2)) (fcontrol :abort :value) (values (v 5) (v 6))) :tag :abort :handler (lambda (v k) (list v (k 3 4) (k :three :four)))) (nreverse vs))) '((:VALUE (1 2 3 4 5 6) (1 2 :THREE :FOUR 5 6)) (1 2 5 6 5 6)))) ;; Block/Return-from (assert (cps-form-equal? (block blah 1))) (assert (cps-form-equal? (block blah (values 1 2 3)))) (assert (cps-form-equal? (block outer (block inner (return-from outer :inner)) (values 1 2 3)))) (assert (cps-form-equal? (block blah (values 1 (return-from blah (values 2 :two :dos)) 3)))) (assert (cps-form-equal? (scm (block name (let ((f (lambda () (return-from name :ok)))) (f)))))) ;;Error block NAME no longer exists, todo: better error message for cps #; (cps (scm ((block name (let ((f (lambda () (return-from name (lambda () :ok))))) f))))) ;;Error: #;(return-from name) #;(cps (return-from name)) (assert (equal? (scm (% (block name (fcontrol :abort :value)) :tag :abort :handler (lambda (value k) (list value (multiple-value-list (k 1 2 3)))))) '(:VALUE (1 2 3)))) (assert (equal? (scm (% (block name (return-from name (fcontrol :abort :value)) (error "unreached")) :tag :abort :handler (lambda (value k) (list value (multiple-value-list (k 1 2 3)))))) '(:VALUE (1 2 3)))) (assert (equal? (scm (% (block name (fcontrol :abort :value) (return-from name (values 1 2 3)) (error "unreached")) :tag :abort :handler (lambda (value k) (list value (multiple-value-list (k)))))) '(:VALUE (1 2 3)))) (assert (equal? (scm (% (block name (let ((f (cl:lambda () (return-from name (values 1 2 3))))) (fcontrol :abort :value) (f) (error "unreached"))) :tag :abort :handler (lambda (value k) (list value (multiple-value-list (k)))))) '(:VALUE (1 2 3)))) (assert (equal? (scm (% (block name (let ((f (cl:lambda () (fcontrol :abort :value) (return-from name (values 1 2 3))))) (f) (error "unreached"))) :tag :abort :handler (lambda (value k) (list value (multiple-value-list (k)))))) '(:VALUE (1 2 3)))) ;; return-from unwinds unwind-protect forms (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (block name (v :start) (unwind-protect (v (return-from name (v :returning))) (v :cleanup)) (v :after)) (nreverse vs))))) ;; Labels ;; FLet (assert (cps-form-equal? (list (labels () :value) :after))) (assert (cps-form-equal? (list (flet () :value) :after))) (assert (equal? (% (labels ((f1 (&optional (o1 (fcontrol :abort :value))) (f2 `(f1 ,o1))) (f2 (p) `(f2 ,p))) (f1)) :tag :abort :handler (lambda (v k) (list v (funcall k :o1)))) '(:VALUE (F2 (F1 :O1))))) (assert (equal? (% (flet ((f1 (&optional (o1 (fcontrol :abort :value))) `(f1 ,o1)) (f2 (v) `(f2 ,v))) (list (f1) (f2 :v))) :tag :abort :handler (lambda (v k) (list v (funcall k :o1)))) '(:VALUE ((F1 :O1) (F2 :V))))) ;; Eval-when Eval - when will never appear as a top - level - form if it is part of a CPS expression ;; Therefore we only test the :execute (assert (cps-form-equal? (list (eval-when (:execute) (list 1 2 3)) 2 3))) (assert (cps-form-equal? (list (eval-when (:compile-toplevel :load-toplevel) (list 1 2 3)) 2 3))) ;; Macrolet (assert (scm (cps-form-equal? (let ((f (cl:lambda (x flag) (macrolet ((fudge (z) `(if flag (list '* ,z ,z) ,z))) `(+ ,x ,(fudge x) ,(fudge `(+ ,x 1))))))) (list (f :x nil) (f :x :flag)))))) ;; symbol-Macrolet (assert (cps-form-equal? (list (symbol-macrolet ((garner `(list :attention))) garner) 'garner))) ;; locally (assert (cps-form-equal? (funcall (cl:lambda (y) (declare (special y)) (let ((y t)) (list y (locally (declare (special y)) y)))) nil))) ;; tagbody/go (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (tagbody (v :u1) (v :u2)) (nreverse vs))))) (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (v 'before) (tagbody (v :ut1) (v :ut2) tag1 (v :t1) (v :t11) tag2 (v :t2) (v :t22)) (v 'after)) (nreverse vs)))) (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (tagbody (v :ut1) (go tag2) (v :ut2) tag1 (v :t1) (go end) (v :t11) tag2 (v :t2) (go tag1) (v :t22) end (v :end)) (nreverse vs))))) (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (tagbody (v :u1) :t1 (v :t1) :t2 (v :t2)) (nreverse vs))))) (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (tagbody (v :u1) (go :t2) :t1 (v :t1) (go :end) :t2 (v :t2) (go :t1) :end (v :end)) (nreverse vs))))) (assert (equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (% (list (v :before) (tagbody (v :u1) (go :t2) :t1 (v :t1) (go :end) :t2 (v :t2) (v (fcontrol :abort :value)) (go :t1) :end (v :end)) (v :after)) :tag :abort :handler (lambda (v k) (list v (k :resume) (k :resume)))) (nreverse vs))) '((:VALUE (:BEFORE NIL :AFTER) (:BEFORE NIL :AFTER)) (:BEFORE :U1 :T2 :RESUME :T1 :END :AFTER :RESUME :T1 :END :AFTER)))) ;; Nested tagbody (assert (equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (% (list (v :before) (tagbody (v :outer-u1) :outer-t1 (v :outer-t1) (tagbody (v :inner-u1) (go :inner-t2) :inner-t1 (v :t1) (go :outer-t2) :inner-t2 (v :t2) (v (fcontrol :abort :value)) (go :inner-t1)) :outer-t2 (v :outer-t2) (go :end) :end (v :end)) (v :after)) :tag :abort :handler (lambda (v k) (list v (k :resume) (k :resume)))) (nreverse vs))) '((:VALUE (:BEFORE NIL :AFTER) (:BEFORE NIL :AFTER)) (:BEFORE :OUTER-U1 :OUTER-T1 :INNER-U1 :T2 :RESUME :T1 :OUTER-T2 :END :AFTER :RESUME :T1 :OUTER-T2 :END :AFTER)))) (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (tagbody (v :start) :tag1 (v :tag1) (unwind-protect (progn (v :inside-protected) (go :tag2)) (v :cleanup)) :tag2 (v :tag2)) (nreverse vs)))) progv (assert (cps-form-equal? (let ((x 3)) (LIST (progv '(x) '(4) (list x (symbol-value 'x))) (list x (boundp 'x)))))) (assert (equal? (scm (% (let ((x 3)) (list (progv '(x) '(4) (list x (symbol-value 'x) (setf (symbol-value 'x) 2) (fcontrol :abort :value) (boundp 'x))) (list x (boundp 'x)))) :tag :abort :handler (lambda (v k) (list v (k :resume))))) '(:VALUE ((3 4 2 :RESUME NIL) (3 NIL))))) ;; unwind-protect (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (unwind-protect (v :protected) (v :cleanup)) (nreverse vs))))) (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (catch :tag (unwind-protect (progn (v :protected) (throw :tag :thrown-value) (v :unreached)) (v :cleanup))) (nreverse vs))))) (def (run-thunk-until-normal-exit thunk) "Run thunk calling (k v) until a normal exit occurs. Useful for testing." (cps (let recurse ((thunk thunk)) (run/cc *default-prompt-tag* thunk (lambda (v k) (recurse (lambda () (k v)))))))) (defvar *vs*) (def (trace-v x) (push x *vs*) x) (defmacro with-v-tracing (&body body) `(let ((*vs* ())) (list ,@body (reverse *vs*)))) ;; Attempt to re-enter a protected form (assert (null (ignore-errors (with-v-tracing (scm (run-thunk-until-normal-exit (cps (lambda () (trace-v :before) (unwind-protect (trace-v (throw/cc (trace-v :protected))) (trace-v :cleanup)) (trace-v :after))))))))) ;; Resume cleanup with abnormal exit (assert (equal? (ignore-errors (with-v-tracing (scm (run-thunk-until-normal-exit (cps (lambda () (trace-v :before) (unwind-protect (error "error") (trace-v (throw/cc :cleanup1)) (trace-v (throw/cc :cleanup2))) (trace-v :after))))))) '(:CLEANUP2 (:BEFORE :CLEANUP1 :CLEANUP2)))) ;; Resume cleanup with normal exit (assert (equal? (with-v-tracing (scm (run-thunk-until-normal-exit (cps (lambda () (trace-v :before) (trace-v (unwind-protect (trace-v :protected) (trace-v (throw/cc :cleanup1)) (trace-v (throw/cc :cleanup2)))) (trace-v :after)))))) '(:AFTER (:BEFORE :PROTECTED :CLEANUP1 :CLEANUP2 :PROTECTED :AFTER)))) (assert (equal? (scm (def vs ()) (def (v x) (push x vs) x) (% (unwind-protect (progn (v 'protected) (values 1 2 3)) (v 'cleanup) (fcontrol :escape-cleanup :value) (v 'resume-cleanup)) :tag :escape-cleanup :handler (lambda (value k) (v 'handler) (list value (multiple-value-list (k)) (multiple-value-list (k)) (nreverse vs))))) '(:VALUE (1 2 3) (1 2 3) (PROTECTED CLEANUP HANDLER RESUME-CLEANUP RESUME-CLEANUP)))) (assert (equal? (scm (def vs ()) (def (v x) (push x vs) x) (ignore-errors (% (unwind-protect (progn (v :protected) (fcontrol :tag :thrown-value) (v :unreached)) (v :cleanup)) :tag :tag :handler (lambda (_ k) (k)))) (nreverse vs)) '(:PROTECTED :CLEANUP))) ;; Error, tried to re-eneter unwind-protect (assert (equal? ;; Conditions unwind unwind-protect (let (cleanup?) (ignore-errors (cps (unwind-protect (error "error") (set! cleanup? t)))) cleanup?) (let (cleanup?) (ignore-errors (unwind-protect (error "error") (set! cleanup? t))) cleanup?))) GO 's unwind (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (tagbody (unwind-protect (progn (v :u1-protected) (go :t2)) (v :u1-cleanup)) :t1 (unwind-protect (progn (v :t1-protected) (go :end)) (v :t1-cleanup)) :t2 (unwind-protect (progn (v :t2-protected) (go :t1)) (v :t2-cleanup)) :end) (nreverse vs)))) ;; catch/throw (assert (cps-form-equal? (catch :tag (throw :tag (values 1 2 3)) (error "unreached")))) (assert (cps-form-equal? (catch :tag (throw (throw :tag (values :one :two :three)) (values 1 2 3)) (error "unreached")))) (assert (cps-form-equal? (catch :tag (catch (throw :tag (values :one :two :three)) (values 1 2 3)) (error "unreached")))) (assert (cps-form-equal? (catch (values :outer :bouter) (catch (values :inner :binner) (throw :outer (values :one :two :three)) (error "unreached")) (error "unreached")))) (assert (equal? (scm (% (progn (catch :tag (fcontrol :abort :value) (print 'throwing) (throw :tag :value)) (values 1 2 3)) :tag :abort :handler (lambda (v k) (print 'catching) (list v (multiple-value-list (k)))))) '(:VALUE (1 2 3)))) (assert (equal? (scm (% (catch :outer (let ((inner-results (multiple-value-list (catch :inner (fcontrol :abort :value) (throw :inner (values 1 2 3)) (error "not reached"))))) (throw :outer inner-results) (error "not reached"))) :tag :abort :handler (lambda (v k) (list v (k))))) '(:VALUE (1 2 3)))) ;; Error throwing to tag #; (cps (progn (catch :tag (throw :tag :value)) (throw :tag :value))) ;; load-time-value (assert (cps (scm (def (rnd) (list (load-time-value (random 17)) 2)) (equal? (rnd) (rnd))))) ;; multiple-value-prog1 (assert (cps-form-equal? (let (temp) (setq temp '(1 2 3)) (list (multiple-value-list (multiple-value-prog1 (values-list temp) (setq temp nil) (values-list temp))) temp)))) (assert (equal? (% (list (fcontrol :abort :one) 2 3) :tag :abort :handler (cl:lambda (value continuation) (list value (funcall continuation 1)))) '(:one (1 2 3)))) ;; Re-establish inner prompts when continuing from an outer prompt: (assert (equal? (% (% (list (fcontrol :outer-abort :one) (fcontrol :inner-abort :two) 3) :tag :inner-abort :handler (cl:lambda (value continuation) (declare (ignore value)) (funcall continuation 2))) :tag :outer-abort :handler (cl:lambda (value continuation) (declare (ignore value)) (funcall continuation 1))) '(1 2 3))) ;; Simple-exit example (def (product . numbers) (% (let recurse ((numbers numbers)) (cond ((empty? numbers) 1) (t (define-destructuring (number . rest-of-numbers) numbers) ;; Short-circut if any number is 0 (cond ((zero? number) (fcontrol :product :zero)) (t (* number (recurse rest-of-numbers))))))) :tag :product :handler (lambda (result _continuation) result))) (assert (= (product 1 2 3 4 5) (* 1 2 3 4 5))) (assert (eq? :zero (product 0 1 2 3 4 5))) ;; Tree matching (def (make-fringe tree) (cps (lambda () (let recurse ((tree tree)) (cond ((pair? tree) (recurse (car tree)) (recurse (cdr tree))) ((empty? tree) :*) (t (fcontrol :yield tree)))) (fcontrol :yield ())))) (def (collect-fringe tree) (define leaves ()) (let recurse ((fringe (make-fringe tree))) (% (fringe) :tag :yield :handler (lambda (leaf rest-of-fringe) (cond ((null? leaf) leaves) (t (push leaf leaves) (recurse rest-of-fringe)))))) leaves) (def (same-fringe? tree1 tree2) (let recurse ((fringe1 (make-fringe tree1)) (fringe2 (make-fringe tree2))) (% (fringe1) :tag :yield :handler (lambda (leaf1 rest-of-fringe1) (% (fringe2) :tag :yield :handler (lambda (leaf2 rest-of-fringe2) (if (eq? leaf1 leaf2) (if (null? leaf1) t (recurse rest-of-fringe1 rest-of-fringe2)) nil))))))) (assert (equal? (collect-fringe '((1 2) ((3 (4 5)) (6 7)))) '(7 6 5 4 3 2 1))) (assert (same-fringe? '((1 2) ((3) (4 5))) '((1 . 2) . ((3 . ()) . (4 . 5))))) (assert (not (same-fringe? '((1 2) ((3) (4 5))) '((1 2) ((3 4) (4 5)))))) ;; TODO: fluid-let ;; TODO: optimize in-place expressions that are known to not signal controls ;; TODO: Special case higher order functions. funcall/apply/mapcar et. al. ;; TODO: special-case no-cps functions ;; An expression N is non-signaling if, cps-expansion, it is a(n): ;; N := atom ;; N := (non-signaling-function arguments...) ;; N := (cl:quote expr) ;; N := (cl:function name) ;; N := (cl:load-time-value expr read-only-p) ;; N := (cl:lambda parameters body) N : = ( cl : ) ;; N := (cl:let bindings declarations... M) ;; N := (cl:let* bindings declarations... M) ;; N := (cl:the value-type N) ;; N := (cl:multiple-value-call non-signaling-function arguments...) ;; N := (cl:setq pairs...) ;; N := (cl:if test N_then N_else) ;; N := (cl:eval-when () body...) | (cl:eval-when (:execute) M) N : = ( cl : macrolet bindings M ) ;; N := (cl:symbol-macrolet bindings M) ;; N := (cl:locally declarations... M) ;; N := (cl:multiple-value-prog1 M) ;; N := (cl:labels bindings M) ;; N := (cl:flet bindings M) ;; N := (cl:block name M) ;; N := (cl:catch tag M) N : = ( cl : unwind - protect N M ) N : = ( cl : M_1 tag1 M_tag1 tag2 M_tag2 ... ) ;; N := (cl:progv variables values M) ;; where M := N_1 N_2 ... N_n ;; Corrollary An expression S signals if, after macro-expansion, it is a(n): ;; S := (fcontrol tag value) ;; S := (signaling-function arguments...) ;; Transformation on output rather than special forms ( with - ignored - values - continuation N body ) = > ( progn N body ) ;; (save-continuation name (with-return-to-saved-continuation name body)) => body ;; (with-primary-value-continuation (name N) body) => (let ((name N)) body) ;; (with-values-continuation (name N) body) => (let ((name (multiple-value-list N))) body) ;; Multi-pass lisp compilation 1st pass : expand all macros with special cases ;; Subsequent pass: code-transformer (hash-keys *transform-cps-special-form-table*) (def (augment-environment-with-macro-bindings bindings environment) (trivial-cltl2:augment-environment environment :macro (map (lambda (binding) (def-destructuring (name lambda-list . body) binding) (list name (trivial-cltl2:enclose (trivial-cltl2:parse-macro name lambda-list body environment) environment))) bindings))) (def (augment-environment-with-symbol-macro-bindings bindings environment) (trivial-cltl2:augment-environment environment :symbol-macro bindings)) (def (macroexpand-progn-forms forms environment) (map (lambda (form) (macroexpand-all-cps form environment)) forms)) (def (macroexpand-body body environment) (def-values (declarations forms) (parse-declarations body)) (append declarations (macroexpand-progn-forms forms environment))) (def (expanded-body body environment) (def-values (declarations forms) (parse-declarations body)) (def expanded-body (macroexpand-body body environment)) (cond ((empty? declarations) (cond ((empty? forms) nil) ((empty? (rest forms)) (first expanded-body)) (t `(progn ,@expanded-body)))) (t `(locally ,@expanded-body)))) (defvar *cps-special-forms* '(NO-CPS FCONTROL cl:QUOTE cl:FUNCTION cl:PROGN COMMON-LISP:LET cl:LET* cl:MACROLET cl:SYMBOL-MACROLET cl:LOCALLY COMMON-LISP:LAMBDA cl:SETQ cl:IF cl:THE cl:MULTIPLE-VALUE-CALL cl:EVAL-WHEN cl:LOAD-TIME-VALUE cl:MULTIPLE-VALUE-PROG1 cl:LABELS cl:FLET cl:BLOCK cl:RETURN-FROM cl:CATCH cl:THROW cl:UNWIND-PROTECT cl:TAGBODY cl:GO cl:PROGV)) (def (macroexpand-all-cps cps-form environment) "Macroexpand-all for CPS-FORM, respecting Common Lisp special forms as well as CPS special forms. See *CPS-SPECIAL-FORMS* for a full list of special forms recognized by CPS. The resulting expansion will not have any macros remaining. Any cl:macrolet and cl:symbol-macrolet will be removed after their expansions have been applied." (cond CPS - FORM is either , NIL , a symbol or a symbol - macro ((symbol? cps-form) (def-values (expanded-cps-form macro?) (macroexpand-1 cps-form environment)) (if macro? ;; If it was a symbol macro, we may need to expand again. (macroexpand-all-cps expanded-cps-form environment) ;; otherwise, we reached a termination point expanded-cps-form)) CPS - FORM is a non - symbol atom ((atom cps-form) cps-form) ;; Otherwise cps-form-is a pair (t (def symbol (first cps-form)) (cond ((member symbol '(cl:quote cl:function)) cps-form) ((eq? symbol 'cl:progn) `(cl:progn ,@(macroexpand-progn-forms (progn-forms cps-form) environment))) ((member symbol '(cl:let cl:let*)) `(,symbol ,(map (lambda (binding) (list (let-binding-name binding) (macroexpand-all-cps (let-binding-value binding) environment))) (let-bindings cps-form)) ,@(macroexpand-body (let-body cps-form) environment))) ;; Macrolets and symbol-macrolets are replaced with locally since the bindings are no longer relevant after expansion ((eq? symbol 'cl:macrolet) (let ((environment (augment-environment-with-macro-bindings (macrolet-bindings cps-form) environment))) (expanded-body (macrolet-body cps-form) environment))) ((eq? symbol 'cl:symbol-macrolet) (let ((environment (augment-environment-with-symbol-macro-bindings (symbol-macrolet-bindings cps-form) environment))) (expanded-body (symbol-macrolet-body cps-form) environment))) ((eq? symbol 'cl:locally) (expanded-body (locally-body cps-form) environment)) ((eq? symbol 'cl:lambda) ;; NOTE: cl-lambda list is a full lambda list after this transformation. kinda nice. `(cl:lambda ,(map-ordinary-lambda-list (lambda (key parameter) (ecase key ((:positional :rest) parameter) (:keyword parameter) ((:optional :key) (cond ((pair? parameter) (define-destructuring (name &optional default-value provided?) parameter) (list name (macroexpand-all-cps default-value environment) (or provided? (unique-symbol (symbolicate name '-provided?))))) (t (list parameter nil (unique-symbol (symbolicate parameter '-provided?)))))) (:aux (cond ((pair? parameter) (define-destructuring (name &optional default-value) parameter) (list name (macroexpand-all-cps default-value environment))) (t (list parameter nil)))))) (lambda-parameters cps-form)) ,@(macroexpand-body (lambda-body cps-form) environment))) ((eq? symbol 'cl:setq) `(cl:setq ,@(append-map (lambda (pair) (def-destructuring (name value) pair) (list name (macroexpand-all-cps value environment))) (setq-pairs cps-form)))) ((eq? symbol 'cl:if) `(cl:if ,(macroexpand-all-cps (if-test cps-form) environment) ,(macroexpand-all-cps (if-then cps-form) environment) ,(macroexpand-all-cps (if-else cps-form) environment))) ((eq? symbol 'cl:the) `(cl:the ,(the-value-type cps-form) ,(macroexpand-all-cps (the-form cps-form) environment))) TODO ((eq? symbol 'cl:multiple-value-call)) ((eq? symbol 'cl:eval-when)) ((eq? symbol 'cl:load-time-value)) ((eq? symbol 'cl:multiple-value-prog1)) ((eq? symbol 'cl:labels)) ((eq? symbol 'cl:flet)) ((eq? symbol 'cl:block)) ((eq? symbol 'cl:return-from)) ((eq? symbol 'cl:catch)) ((eq? symbol 'cl:throw)) ((eq? symbol 'cl:tagbody)) ((eq? symbol 'cl:go)) ((eq? symbol 'cl:progv)) ((eq? symbol 'cl:unwind-protect)) ((eq? symbol 'no-cps)) ((eq? symbol 'fcontrol)) ;; If it isn't a special form, then it's either a function call or a macro expansion. (t (def-values (expanded-cps-form macro?) (macroexpand-1 cps-form environment)) (if macro? (macroexpand-all-cps expanded-cps-form environment) ;; If it's a function call, we need to expand the arguments (progn (def-destructuring (name . arguments) expanded-cps-form) `(,name ,@(map (lambda (form) (macroexpand-all-cps form environment)) arguments))))))))) (macroexpand-all-cps '(symbol-macrolet ((a :a)) 'b (macrolet ((m (a) `(list ,a))) (cl:lambda (&optional a (m (m a))) (locally a (m a)) (if (setq a (m 1)) (the (m 1) (m 2)) (m 3))) a)) nil)
null
https://raw.githubusercontent.com/chebert/schemeish/872ea3dc3f2ea8438388b5e7660acd9446c49948/src/continuations.lisp
lisp
Required arguments are symbols Optional arguments are lists If the function has an associated cps-function, we can just call it. If the function is an ordinary function, we need to deliver its returned values to the continuation Evaluate all arguments from left to right Set up a catch. If a CPS-FUNCTION is called, it will call the continuation and throw the results Otherwise, it will just return the values This is a known cps function, we can call it with continue as the continuation TODO: Special case higher order functions. funcall/apply/mapcar et. al. Special case values TODO: Special case: functions which are known to not have CPS-FUNCTIONS Otherwise funcall it with continue (progn . forms) (progn form) => form (progn form . rest-of-forms) (progn) => nil (progn form) => form (progn . forms) Bind value to a unique name Base case: Evaluate body Unfortunately declarations can only apply to the body. This is inevitable, since each binding depends on the previous binding. Unfortunately, using locally will cause most declarations to be out of scope. The only real solution for this is to parse the declarations ourselves, and sort them to be with the definition of the binding they are declaring. Iteration case: evaluate value of next binding, and bind it. Evaluate the next binding's value, binding it to name. Call the underlying cps-function, returning the result to the caller, instead of the continuation. The continuation function curried with #'values as the continuation Return an ordinary function. If this is the last pair, call the continuation with the value. Otherwise, continue setting pairs. Iteration: (setq pair pairs...) (setq) => nil If its a lexical function name we need to return an ordinary function, with #'function as an associated cps-function. This means we'll want the full lambda list associated with defining the function. Also, if the ordinary funciton already exists we should grab that. For now though Otherwise it's an ordinary atom evalaute the primary value of function-form and capture it in FUNCTION evaluate the arguments... ...capturing the values of each argument as a list Apply the function to the appended argument-lists so :load-toplevel and :compile-toplevel are irrelevant. therefore we only need to handle the :execute case. Macrolet symbol-Macrolet locally load-time-value continuation barrier around load-time-value's form, since it is evaluated in a different context cl:load-time-value only returns the primary value Dynamic forms Execute the thunk, catching fcontrol-signals. Call thunk returning results as a list. If the result is an fcontrol-signal, it means an (FCONTROL value) form was encountered. TODO: Destructure structures on the signal's value and continuation Return the results to whoever called run. If a prompt is established, then tag may be meant for an outer run. re-throw with setting the prompt up again as part of the continuation Return a modified continuation When resumed, set up a prompt around the rest-of-thunk. If this is not our tag, and there is no outer prompt established, then we have an error. Otherwise, we encountered a normal exit: return the results to whoever called run. (fcontrol tag values-form) Evaluates tag, then value. throws to tag with (make-fcontrol-signal tag value current-continuation), aborting the current continuation Throw to the nearest established prompt, if one is established Return results to the prompt evaluate before-thunk, ignoring results A normal-exit occurs when a thunk evaluates without encountering an fcontrol/condition PROTECTED FORM evaluate thunk evaluate thunk, saving the returned values If we caught an fcontrol-tag from within the thunk, rethrow with a modified continuation. Modify rest-of-thunk by wrapping it in an identical dynamic-wind modified continuation: Rest of thunk if we made it here, thunk had a normal-exit CLEANUP evaluate after-thunk If we caught an fcontrol-signal in the after-thunk modify the rest of the after-thunk return-to rest-of-thunk, before returning-to continue-from-dynamic-wind Modified continuation: Call the rest of thunk with the arguments If thunk exited normally, we can return the results to whoever called dynamic-wind. IF thunk had a normal-exit then continue from dynamic-wind with the thunk-results IF we made it here, after-thunk had a normal-exit If we had a normal exit from the thunk and the after-thunk, we need to call the continuation with the thunk-results Don't allow re-entry into protected forms. Tagbody: tags have lexical scope and dynamic extent if there is no matching tag visible to go, results are undefined. GO needs to throw to a specific tagbody, and the name of a tag-thunk to throw TODO: It might be nice if we could resume with the dynamic bindings intact. The issue is that we need to grab the current bindings right before exiting the continuation. So that we can re-establish when resuming. Since we only get the continuation after exiting the dynamic context, it's too late. we would need to modify FCONTROL within cps progv forms to grab the current dynamic bindings To do this, each fcontrol signal would need to have a list of dynamic bindings, as which prompt they came from. The alternative is to let dynamic bindings go, and instead rely on new forms that establish fluid bindings. It's hard to say which is the right default, but since I don't use progv that often anyways, I don't have a problem with just dropping them for now. atoms Function Quote function application Called once Called each time continue is called. (twice) Called each time continue is called. (twice) Called once. (progn forms... (fcontrol ...)) (progn forms... (fcontrol ...) forms...) vs: (3 2 1) :value Let :value (1 2 3) LET* :value Lambda :value (1 2 3) Setq If The Multiple-value-call Block/Return-from Error block NAME no longer exists, todo: better error message for cps Error: (return-from name) (cps (return-from name)) return-from unwinds unwind-protect forms Labels FLet Eval-when Therefore we only test the :execute Macrolet symbol-Macrolet locally tagbody/go Nested tagbody unwind-protect Attempt to re-enter a protected form Resume cleanup with abnormal exit Resume cleanup with normal exit Error, tried to re-eneter unwind-protect Conditions unwind unwind-protect catch/throw Error throwing to tag load-time-value multiple-value-prog1 Re-establish inner prompts when continuing from an outer prompt: Simple-exit example Short-circut if any number is 0 Tree matching TODO: fluid-let TODO: optimize in-place expressions that are known to not signal controls TODO: Special case higher order functions. funcall/apply/mapcar et. al. TODO: special-case no-cps functions An expression N is non-signaling if, cps-expansion, it is a(n): N := atom N := (non-signaling-function arguments...) N := (cl:quote expr) N := (cl:function name) N := (cl:load-time-value expr read-only-p) N := (cl:lambda parameters body) N := (cl:let bindings declarations... M) N := (cl:let* bindings declarations... M) N := (cl:the value-type N) N := (cl:multiple-value-call non-signaling-function arguments...) N := (cl:setq pairs...) N := (cl:if test N_then N_else) N := (cl:eval-when () body...) | (cl:eval-when (:execute) M) N := (cl:symbol-macrolet bindings M) N := (cl:locally declarations... M) N := (cl:multiple-value-prog1 M) N := (cl:labels bindings M) N := (cl:flet bindings M) N := (cl:block name M) N := (cl:catch tag M) N := (cl:progv variables values M) where M := N_1 N_2 ... N_n Corrollary An expression S signals if, after macro-expansion, it is a(n): S := (fcontrol tag value) S := (signaling-function arguments...) Transformation on output rather than special forms (save-continuation name (with-return-to-saved-continuation name body)) => body (with-primary-value-continuation (name N) body) => (let ((name N)) body) (with-values-continuation (name N) body) => (let ((name (multiple-value-list N))) body) Multi-pass lisp compilation Subsequent pass: code-transformer If it was a symbol macro, we may need to expand again. otherwise, we reached a termination point Otherwise cps-form-is a pair Macrolets and symbol-macrolets are replaced with locally since the bindings are no longer relevant after expansion NOTE: cl-lambda list is a full lambda list after this transformation. kinda nice. If it isn't a special form, then it's either a function call or a macro expansion. If it's a function call, we need to expand the arguments
(in-package :schemeish.backend) (install-syntax!) (def (full-ordinary-lambda-list ordinary-lambda-list) "Return a lambda list with optional/keywords fully expanded to their (name default-value provided?) form. If necessary, unique symbols will be generated for provided? names. Aux variables will be (name value)" (append* (map-ordinary-lambda-list (lambda (key parameter) (ecase key ((:positional :rest) (list parameter)) ((:optional :key) (cond ((pair? parameter) (define-destructuring (name &optional default-value provided?) parameter) (list (list name default-value (if provided? provided? (unique-symbol (symbolicate name '-provided?)))))) (t (list (list parameter nil (unique-symbol (symbolicate parameter '-provided?))))))) (:keyword (list parameter)) (:aux (cond ((pair? parameter) (define-destructuring (name &optional default-value) parameter) (list (list name default-value))) (t (list (list parameter nil))))))) ordinary-lambda-list))) (def (full-ordinary-lambda-list->function-argument-list-form full-lambda-list) (let (rest-provided? required-arguments optional-arguments) (map-ordinary-lambda-list (lambda (key parameter) (ecase key (:positional (push parameter required-arguments)) (:optional (define-destructuring (name default-value provided?) parameter) (push `(when ,provided? (list ,name)) optional-arguments)) (:keyword) (:key (unless rest-provided? (define-destructuring (name default-value provided?) parameter) (push `(when ,provided? (list ,(make-keyword name) ,name)) optional-arguments))) (:rest (set! rest-provided? t) (push parameter optional-arguments)) (:aux ()))) full-lambda-list) `(list* ,@(nreverse required-arguments) (nconc ,@(nreverse optional-arguments))))) (assert (equal? (with-readable-symbols (full-ordinary-lambda-list->function-argument-list-form (full-ordinary-lambda-list '(p1 p2 p3 &optional o1 o2 o3 &key k1 k2 k3 &aux aux1 aux2 aux3)))) '(list* P1 P2 P3 (NCONC (WHEN O1-PROVIDED? (LIST O1)) (WHEN O2-PROVIDED? (LIST O2)) (WHEN O3-PROVIDED? (LIST O3)) (WHEN K1-PROVIDED? (LIST :K1 K1)) (WHEN K2-PROVIDED? (LIST :K2 K2)) (WHEN K3-PROVIDED? (LIST :K3 K3)))))) (assert (equal? (with-readable-symbols (full-ordinary-lambda-list->function-argument-list-form (full-ordinary-lambda-list '(p1 p2 p3 &optional o1 o2 o3 &rest rest &key k1 k2 k3 &aux aux1 aux2 aux3)))) '(LIST* P1 P2 P3 (NCONC (WHEN O1-PROVIDED? (LIST O1)) (WHEN O2-PROVIDED? (LIST O2)) (WHEN O3-PROVIDED? (LIST O3)) REST)))) (for-macros (defvar *function->cps-function-table* (make-hash-table :weakness :key))) (defmacro with-lexical-function-names (function-names &body body) `(let ((*lexical-context* (alist-update *lexical-context* :lexical-function-names (lambda (names) (append ,function-names names))))) ,@body)) (def (lexical-function-name? function-name) (member function-name (alist-ref *lexical-context* :lexical-function-names))) (define (function->cps-function function) "Return the cps-function associated with function or the function itself if there is none." (hash-ref *function->cps-function-table* function)) (define (set-cps-function! function cps-function) "Associate the cps-function with the given function." (hash-set! *function->cps-function-table* function cps-function)) (for-macros (defvar *continuation* #'values)) (defmacro with-continuation (form continuation) "Evaluates form with *continuation* bound to the new continuation. Under normal circumstances, this means the values of form will be passed to the lambda-list before evaluating the continuation-body." `(cl:let ((*continuation* ,continuation)) ,form)) (defmacro without-continuation (&body body) "Evaluates body with *CONTINUATION* bound to #'VALUES" `(cl:let ((*continuation* #'values)) ,@body)) (defmacro save-continuation (name &body body) "Binds name to *CONTINUATION* in body" `(let ((,name *continuation*)) ,@body)) (def (continue-with . values) (*continuation* . values)) (def (continue-with* values) (*continuation* . values)) (defmacro continue-with-values (values-form) `(multiple-value-call *continuation* ,values-form)) (for-macros (defvar *transform-cps-special-form-table* (make-hash-table))) (define (register-transform-cps-special-form symbol transform) (hash-set! *transform-cps-special-form-table* symbol transform)) (for-macros (register-transformer 'cps (make-transformer *transform-cps-special-form-table* 'transform-cps-proper-list (lambda (_ expression _) (error "Attempt to compile invalid dotted list: ~S" expression)) (lambda (_ expression _) (error "Attempt to compile invalid cyclic list: ~S" expression)) 'transform-cps-atom))) (define (transform-cps form) (transform 'cps form)) (define (transform-cps* forms) (transform* 'cps forms)) (defmacro cps (expr) "Transforms EXPR into continuation-passing-style." (transform-cps expr)) (defmacro define-transform-cps-special-form (name (expression environment) &body body) "Define a special form transformer for the CPS macro-expansion. Name is the symbol naming the special-form. Expression will be bound to the special form being transformed, and environment will be bound to the current lexical environment for body. Body should evaluate to the transformed form." (let ((transformer (unique-symbol 'transformer))) `(for-macros (register-transform-cps-special-form ',name (cl:lambda (,transformer ,expression ,environment) (cl:declare (ignore ,transformer)) (cl:declare (ignorable ,expression ,environment)) (scm ,@body)))))) (def (atom->cps expression) `(continue-with ,expression)) (def (transform-cps-atom _ expression _) "Return a form that evaluates an atom in CPS." (atom->cps expression)) (defmacro with-return-to-saved-continuation (continuation &body body) "Evaluates from with *CONTINUATION* bound to continuation" `(cl:let ((*continuation* ,continuation)) ,@body)) (defmacro with-primary-value-continuation ((primary-value-name form) &body continuation-body) "Evaluates form with *CONTINUATION* bound to continuation-body. Only the primary-value is passed to continuation body. If no values are passed to the continuation, the primary-value is NIL." (let ((ignored-rest-of-values (unique-symbol 'ignored-rest-of-values))) `(with-continuation ,form (cl:lambda (&optional ,primary-value-name &rest ,ignored-rest-of-values) (declare (ignore ,ignored-rest-of-values)) (declare (ignorable ,primary-value-name)) ,@continuation-body)))) (defmacro with-ignored-values-continuation (form &body continuation-body) "Evaluates form with *CONTINUATION* bound to continuation-body. Ignores values passed to the continuation." (let ((ignored-values (unique-symbol 'ignored-values))) `(with-continuation ,form (cl:lambda (&rest ,ignored-values) (declare (ignore ,ignored-values)) ,@continuation-body)))) (defmacro with-values-continuation ((values-name form) &body continuation-body) "Evaluates form with *CONTINUATION* bound to continuation-body. Binds values passed to the continuation to VALUES-NAME." `(with-continuation ,form (cl:lambda (&rest ,values-name) ,@continuation-body))) (def (eval-arguments->cps-form argument-forms form-proc) "Return a form that evalautes argument-forms from left to right in CPS, before evaluating (form-proc arguments)" (let iterate ((arguments ()) (argument-forms argument-forms)) (cond ((empty? argument-forms) (form-proc (nreverse arguments))) (t (define-destructuring (argument-form . rest-argument-forms) argument-forms) (define-unique-symbols argument) (define eval-rest-of-arguments-form (iterate (cons argument arguments) rest-argument-forms)) `(with-primary-value-continuation (,argument ,(transform-cps argument-form)) ,eval-rest-of-arguments-form))))) (def (apply/cc function-designator arguments) (def function (if (symbol? function-designator) (symbol-function function-designator) function-designator)) (def cps-function (function->cps-function function)) (if cps-function (apply cps-function arguments) (multiple-value-call *continuation* (apply function arguments)))) (def (funcall/cc function-designator . arguments) (apply/cc function-designator arguments)) (def (transform-cps-proper-list _ expression _) "Return a form that evaluates function-application in CPS. Special cases currently exist for funcall and apply." (define-destructuring (function-name . argument-forms) expression) (define continue (make-symbol (format nil "CONTINUE-FROM ~S" function-name))) `(save-continuation ,continue ,(eval-arguments->cps-form argument-forms (cl:lambda (arguments) (cond ((lexical-function-name? function-name) `(with-return-to-saved-continuation ,continue (,function-name ,@arguments))) ((eq? function-name 'cl:funcall) `(with-return-to-saved-continuation ,continue (funcall/cc ,@arguments))) ((eq? function-name 'cl:apply) `(with-return-to-saved-continuation ,continue (apply/cc ,(first arguments) (list* ,@(rest arguments))))) ((eq? function-name 'dynamic-wind/cc) `(dynamic-wind ,continue ,@arguments)) ((eq? function-name 'run/cc) `(run ,continue ,@arguments)) ((eq? function-name 'cl:values) `(funcall ,continue ,@arguments)) (t `(with-return-to-saved-continuation ,continue (funcall/cc ',function-name ,@arguments)))))))) (cps 1) (cps (+ 1 2)) (cps (+ (print 1) (print 2))) (cps (list (list 1 2 t 3))) (define-transform-cps-special-form no-cps (expression environment) (second expression)) (defmacro no-cps (expr) expr) (cps (list (no-cps (funcall *continuation* (list 1 2 t 3))))) (define-transform-cps-special-form cl:quote (expression environment) (atom->cps expression)) (cps (list '(1 2 3))) (def (progn->cps forms) (define-unique-symbols continue-from-progn) (def (progn->cps-iteration forms) (define-destructuring (cps-form . rest-of-forms) forms) (def form (transform-cps cps-form)) (cond ((empty? rest-of-forms) `(with-return-to-saved-continuation ,continue-from-progn ,form)) (t `(with-ignored-values-continuation ,form ,(progn->cps-iteration rest-of-forms))))) (cond ((empty? forms) (atom->cps nil)) ((empty? (rest forms)) (transform-cps (first forms))) (t `(save-continuation ,continue-from-progn ,(progn->cps-iteration forms))))) (define-transform-cps-special-form cl:progn (expression environment) (define forms (rest expression)) (progn->cps forms)) (cps (progn 1 2 3)) (cps (print (progn 1 2 3))) (cps (progn (print 1) (print 2) (print 3))) (define-transform-cps-special-form cl:let (expression environment) (define-destructuring (bindings . body) (rest expression)) (define-values (declarations forms) (parse-declarations body)) (define-unique-symbols continue-from-let) (def binding-names (map let-binding-name bindings)) (def (iterate bindings binding-values) (cond ((empty? bindings) (def new-bindings (map list binding-names (nreverse binding-values))) Establish bindings from name->let - binding - value - name in let `(cl:let ,new-bindings ,@declarations (with-return-to-saved-continuation ,continue-from-let ,(progn->cps forms)))) (t (define-destructuring (binding . rest-of-bindings) bindings) (define value-form (let-binding-value binding)) (define binding-value(unique-symbol (format nil "~S ~S " 'let-binding-value-for (let-binding-name binding)))) `(with-primary-value-continuation (,binding-value ,(transform-cps value-form)) ,(iterate rest-of-bindings (cons binding-value binding-values)))))) `(save-continuation ,continue-from-let ,(iterate bindings ()))) (cps (let ((a (values 1 2 3))) a)) (define-transform-cps-special-form cl:let* (expression environment) (define-destructuring (bindings . body) (rest expression)) (define-values (declarations forms) (parse-declarations body)) (define-unique-symbols continue-from-let*) (def (iterate bindings) (cond ((empty? bindings) `(cl:locally ,@declarations (with-continuation ,(progn->cps forms) ,continue-from-let*))) (t (define-destructuring (binding . rest-of-bindings) bindings) (define name (let-binding-name binding)) (define value (let-binding-value binding)) `(with-primary-value-continuation (,name ,(transform-cps value)) ,(iterate rest-of-bindings))))) `(save-continuation ,continue-from-let* ,(iterate bindings))) (cps (let* ((a (values 1 2 3))) a)) (def (function-binding->cps name full-lambda-list body) (define default-parameter-assignments ()) (define lambda-list (map-ordinary-lambda-list (lambda (key parameter) (ecase key (:positional parameter) ((:optional :key) (push `(unless ,(third parameter) (setq ,(first parameter) ,(second parameter))) default-parameter-assignments) (list (first parameter) nil (third parameter))) (:keyword parameter) (:rest parameter))) full-lambda-list)) (define-values (declarations forms) (parse-declarations body)) `(,name ,lambda-list ,@declarations ,(progn->cps (append (nreverse default-parameter-assignments) forms)))) (def (lambda->cps ordinary-lambda-list body) (define-unique-symbols ordinary-function cps-function) (def full-lambda-list (full-ordinary-lambda-list ordinary-lambda-list)) (def cps-function-form (function-binding->cps 'cl:lambda full-lambda-list body)) (def ordinary-function-form `(cl:lambda ,full-lambda-list (without-continuation (apply/cc ,cps-function ,(full-ordinary-lambda-list->function-argument-list-form full-lambda-list))))) `(cl:let* ((,cps-function ,cps-function-form) (,ordinary-function ,ordinary-function-form)) Transform the lambda expression and register it as the CPS - function of the function (set-cps-function! ,ordinary-function ,cps-function) ,ordinary-function)) (define-transform-cps-special-form cl:lambda (expression environment) (define-destructuring (ordinary-lambda-list . body) (rest expression)) `(continue-with ,(lambda->cps ordinary-lambda-list body))) (cps (funcall (cl:lambda (a b c) (values a b c)) :a :b :c)) (funcall (cps (cl:lambda (a b c) (values a b c))) :a :b :c) (define-transform-cps-special-form cl:setq (expression environment) (def pairs (setq-pairs expression)) (define-unique-symbols continue-from-setq) (define (pairs->cps pairs) (define (pair->cps pair rest-of-pairs last-pair?) (define-destructuring (name value-form) pair) (def value-name (unique-symbol (symbolicate name '-value))) `(with-primary-value-continuation (,value-name ,(transform-cps value-form)) (setq ,name ,value-name) ,(if last-pair? `(with-return-to-saved-continuation ,continue-from-setq ,(atom->cps value-name)) (pairs->cps rest-of-pairs)))) (define-destructuring (pair . rest-of-pairs) pairs) (cond Base case : 1 pair remaining ((empty? rest-of-pairs) (pair->cps pair rest-of-pairs t)) (t (pair->cps pair rest-of-pairs nil)))) (cond ((empty? pairs) (atom->cps nil)) ( setq pair . pairs ... ) (t `(save-continuation ,continue-from-setq ,(pairs->cps pairs))))) (let (a b c) (list (cps (setq)) (cps (setq a 1)) a (cps (setq b (list a a) c (list b b))) (list a b c))) (define-transform-cps-special-form cl:if (expression environment) (define-destructuring (test-form then-form &optional else-form) (rest expression)) (define-unique-symbols continue-from-if if-test-result) `(save-continuation ,continue-from-if (with-primary-value-continuation (,if-test-result ,(transform-cps test-form)) (with-return-to-saved-continuation ,continue-from-if (cl:if ,if-test-result ,(transform-cps then-form) ,(transform-cps else-form)))))) (cps (if (print nil) (print 1) (print 2))) (define-transform-cps-special-form cl:the (expression environment) (define-destructuring (type-form value-form) (rest expression)) (define-unique-symbols results continue-from-the) `(save-continuation ,continue-from-the (with-values-continuation (,results ,(transform-cps value-form)) (with-return-to-saved-continuation ,continue-from-the (continue-with-values (the ,type-form (values-list ,results))))))) (cps (the (values number &optional) 1)) (cps (the (values number string &optional) (values 1 "string"))) (define-transform-cps-special-form cl:function (expression environment) (def function-name (second expression)) (cond ((lexical-function-name? function-name) (error "TODO")) (t (atom->cps expression)))) (define-transform-cps-special-form cl:multiple-value-call (expression environment) (define-destructuring (function-form . arguments) (rest expression)) (define-unique-symbols continue-from-multiple-value-call multiple-value-call-function) (def (eval-arguments->cps-form argument-forms form-proc) "Return a form that evalautes argument-forms from left to right in CPS, before evaluating (form-proc argument-lists)" (let iterate ((argument-lists ()) (argument-forms argument-forms) (index 0)) (cond ((empty? argument-forms) (form-proc (nreverse argument-lists))) (t (define-destructuring (argument-form . rest-argument-forms) argument-forms) (def argument-list (unique-symbol (format nil "MULTIPLE-VALUE-CALL-ARGUMENT-LIST-~S-" index))) `(with-values-continuation (,argument-list ,(transform-cps argument-form)) ,(iterate (cons argument-list argument-lists) rest-argument-forms (1+ index))))))) `(save-continuation ,continue-from-multiple-value-call (with-primary-value-continuation (,multiple-value-call-function ,(transform-cps function-form)) ,(eval-arguments->cps-form arguments (cl:lambda (argument-lists) `(with-return-to-saved-continuation ,continue-from-multiple-value-call (apply/cc ,multiple-value-call-function (append ,@argument-lists)))))))) (cps (multiple-value-call #'list (values 1 2 3) (values 4 5 6))) (define-transform-cps-special-form cl:eval-when (expression environment) (define-destructuring ((&rest situations) &body body) (rest expression)) if eval - when is called within a CPS form , then it is n't at the top level (cond ((member :execute situations) (progn->cps body)) (t `(continue-with nil)))) (cps (progn (eval-when () (print 'hi)) (print 'after))) (cps (progn (eval-when (:execute) (print 'hi)) (print 'after))) (define-transform-cps-special-form cl:macrolet (expression environment) (define-destructuring (definitions &body body) (rest expression)) (define-values (declarations forms) (parse-declarations body)) `(cl:macrolet ,definitions ,@declarations ,(progn->cps body))) (define-transform-cps-special-form cl:symbol-macrolet (expression environment) (define-destructuring (definitions &body body) (rest expression)) (define-values (declarations forms) (parse-declarations body)) `(cl:symbol-macrolet ,definitions ,@declarations ,(progn->cps body))) (define-transform-cps-special-form cl:locally (expression environment) (def body (rest expression)) (define-values (declarations forms) (parse-declarations body)) `(cl:locally ,@declarations ,(progn->cps forms))) (define-transform-cps-special-form cl:load-time-value (expression environment) (define-destructuring (form &optional read-only?) (rest expression)) (atom->cps `(cl:load-time-value (without-continuation ,(transform-cps form)) ,read-only?))) multiple - value - prog1 : why is this a special form ? (define-transform-cps-special-form cl:multiple-value-prog1 (expression environment) (define-destructuring (values-form . forms) (rest expression)) (define-unique-symbols continue-from-multiple-value-prog1 multiple-value-prog1-results) `(save-continuation ,continue-from-multiple-value-prog1 Evaluate the values form first , saving the results (with-values-continuation (,multiple-value-prog1-results ,(transform-cps values-form)) (with-ignored-values-continuation ,(progn->cps forms) (with-return-to-saved-continuation ,continue-from-multiple-value-prog1 (continue-with* ,multiple-value-prog1-results)))))) (define-transform-cps-special-form cl:labels (expression environment) (define-destructuring (definitions &body body) (rest expression)) (define-values (declarations forms) (parse-declarations body)) (define (labels-binding->cps binding) (define-destructuring (name ordinary-lambda-list . body) binding) (def full-lambda-list (full-ordinary-lambda-list ordinary-lambda-list)) (function-binding->cps name full-lambda-list body)) (def function-names (map first definitions)) (with-lexical-function-names function-names `(cl:labels ,(map labels-binding->cps definitions) ,@declarations ,(progn->cps forms)))) (define-transform-cps-special-form cl:flet (expression environment) (define-destructuring (definitions &body body) (rest expression)) (define-values (declarations forms) (parse-declarations body)) (define (flet-binding->cps binding) (define-destructuring (name ordinary-lambda-list . body) binding) (def full-lambda-list (full-ordinary-lambda-list ordinary-lambda-list)) (function-binding->cps name full-lambda-list body)) (def function-names (map first definitions)) `(cl:flet ,(map flet-binding->cps definitions) ,@declarations ,(with-lexical-function-names function-names (progn->cps forms)))) (define-struct fcontrol-signal (tag value continuation) :opaque) (for-macros (defvar *fcontrol-tag* (unique-symbol "FCONTROL-TAG"))) (for-macros (defvar *prompt-established?* nil)) (def (run continue-from-run tag thunk handler) "Perform THUNK in a dynamic context that catches all tags (cons tag *current-run-tags*). Return the results to continue-from-run. If tag is caught because of (fcontrol tag value), the (handler value rest-of-thunk) is invoked with the rest-of-thunk. If a different tag is caught because of (fcontrol another-tag value), the control is re-signaled with the rest-of-thunk dynamically embedded in the prompt." (def thunk-result (let ((*prompt-established?* t)) (catch *fcontrol-tag* (multiple-value-list (without-continuation (funcall/cc thunk)))))) (cond ((fcontrol-signal? thunk-result) (define fcontrol-tag (fcontrol-signal-tag thunk-result)) (define value (fcontrol-signal-value thunk-result)) (define rest-of-thunk (fcontrol-signal-continuation thunk-result)) (cond ((eq? tag fcontrol-tag) This is the tag we are trying to catch . Invoke the handler ( which may or may not be in CPS ) . (with-return-to-saved-continuation continue-from-run (funcall/cc handler value rest-of-thunk))) (*prompt-established?* (throw *fcontrol-tag* (make-fcontrol-signal fcontrol-tag value (lambda arguments (run continue-from-run tag (lambda () (apply rest-of-thunk arguments)) handler))))) (t (error "Outermost prompt ~S: No enclosing prompt found for fcontrol signal with tag ~S" tag fcontrol-tag)))) (t (apply continue-from-run thunk-result)))) (def (default-prompt-handler value _continuation) value) (defvar *default-prompt-tag* (unique-symbol 'default-prompt-tag)) (defmacro % (expr &key (tag '*default-prompt-tag*) (handler '(function default-prompt-handler))) "Sets up a prompt with the given tag" `(no-cps (cps (run/cc ,tag (cl:lambda () ,expr) ,handler)))) (defmacro catch/cc ((&key (tag '*default-prompt-tag*) (handler '(function default-prompt-handler))) &body body) "Equivalent to (% (progn body...) :tag tag :handler handler)" `(% (progn ,@body) :tag ,tag :handler ,handler)) (define-transform-cps-special-form fcontrol (expression environment) (define-unique-symbols continue-from-fcontrol) (define arguments (rest expression)) `(save-continuation ,continue-from-fcontrol ,(eval-arguments->cps-form arguments (lambda (argument-names) (define-destructuring (tag value) argument-names) `(cond (*prompt-established?* (throw *fcontrol-tag* (make-fcontrol-signal ,tag ,value ,continue-from-fcontrol))) (t (error "Attempt to (FCONTROL ~S ~S) without an established prompt. See %, RUN." ,tag ,value))))))) (defmacro fcontrol (tag value) "Evaluates tag, then value, throwing tag, value, and the current continuation to the dynamically nearest established RUN, aborting the current continuation. If FCONTROL is evaluated in a non-CPS function, it issues a warning and evaluates to VALUE." (declare (ignore tag value)) `(error "Attempt to FCONTROL in a non-CPS environment.")) (defmacro throw/cc (&optional value (tag '*default-prompt-tag*)) "Equivalent to (FCONTROL TAG VALUE)." `(fcontrol ,tag ,value)) (define-transform-cps-special-form cl:block (expression environment) (define-destructuring (name . forms) (rest expression)) (define-unique-symbols block-tag) (define lexical-context (alist-update *lexical-context* :block-tag-alist (cut (alist-set _ name block-tag)))) (let ((*lexical-context* lexical-context)) (transform-cps `(run/cc ',block-tag (cl:lambda () ,@forms) (cl:lambda (results k) (declare (ignore k)) (values-list results)))))) (define-transform-cps-special-form cl:return-from (expression environment) (define-destructuring (name &optional values-form) (rest expression)) (define block-tag (alist-ref (alist-ref *lexical-context* :block-tag-alist) name)) (define-unique-symbols return-from-values) (unless block-tag (error "Could not find BLOCK named ~S in the current lexical environment." name)) `(with-values-continuation (,return-from-values ,(transform-cps values-form)) ,(transform-cps `(fcontrol ',block-tag ,return-from-values)))) (define-transform-cps-special-form cl:catch (expression environment) (define-destructuring (tag . forms) (rest expression)) (transform-cps `(run/cc ,tag (cl:lambda () ,@forms) (cl:lambda (results k) (declare (ignore k)) (values-list results))))) (define-transform-cps-special-form cl:throw (expression environment) (define-destructuring (tag-form results-form) (rest expression)) (define-unique-symbols tag results) `(with-primary-value-continuation (,tag ,(transform-cps tag-form)) (with-values-continuation (,results ,(transform-cps results-form)) ,(transform-cps `(fcontrol ,tag ,results))))) (def (rethrow-if-fcontrol-signal signal modify-continuation) "If signal is an fcontrol-signal, re-throw it with modify-continuation applied to the signal-continuation." (when (fcontrol-signal? signal) Rethrow it , but with a modified continuation that calls dynamic - wind around the rest - of - thunk (def tag (fcontrol-signal-tag signal)) (def value (fcontrol-signal-value signal)) (def rest-of-thunk (fcontrol-signal-continuation signal)) (throw *fcontrol-tag* (make-fcontrol-signal tag value (modify-continuation rest-of-thunk))))) (def (dynamic-wind continue-from-dynamic-wind before-thunk thunk after-thunk) (with-ignored-values-continuation (funcall/cc before-thunk) (let (thunk-had-normal-exit? thunk-results after-thunk-had-normal-exit?) (unwind-protect (let ((result (catch *fcontrol-tag* (set! thunk-results (multiple-value-list (without-continuation (funcall/cc thunk))))))) (rethrow-if-fcontrol-signal result (lambda (rest-of-thunk) (cl:lambda (&rest arguments) (dynamic-wind continue-from-dynamic-wind before-thunk (cl:lambda () (with-return-to-saved-continuation rest-of-thunk (continue-with* arguments))) after-thunk)))) (set! thunk-had-normal-exit? t)) (let ((result (catch *fcontrol-tag* (without-continuation (funcall/cc after-thunk))))) (rethrow-if-fcontrol-signal result (lambda (rest-of-after-thunk) (cl:lambda (&rest arguments) (run (if thunk-had-normal-exit? (lambda _ (apply continue-from-dynamic-wind thunk-results)) values) (unique-symbol 'run) (cl:lambda () (apply rest-of-after-thunk arguments)) default-prompt-handler) (with-ignored-values-continuation (apply/cc rest-of-after-thunk arguments) (print 'continuing-from-rest-of-after-thunk) (when thunk-had-normal-exit? (print 'thunk-had-normal-exit) (with-return-to-saved-continuation continue-from-dynamic-wind (print 'returning-from-dynamic-wind) (continue-with* thunk-results))) (when (not thunk-had-normal-exit?) (print 'thunk-did-not-have-normal-exit)))))) (set! after-thunk-had-normal-exit? t))) (when (and thunk-had-normal-exit? after-thunk-had-normal-exit?) (apply continue-from-dynamic-wind thunk-results))))) (define-transform-cps-special-form cl:unwind-protect (expression environment) (define-destructuring (protected &body cleanup) (rest expression)) (transform-cps `(let ((ok? t)) (dynamic-wind/cc (cl:lambda () (if ok? (set! ok? nil) (error "Attempt to re-enter the protected form of an unwind-protect."))) (cl:lambda () ,protected) (cl:lambda () ,@cleanup))))) (defvar *tagbody-go-tag* (unique-symbol 'tagbody-go-tag)) (define-transform-cps-special-form cl:tagbody (expression environment) (define-destructuring (untagged-statements . tagged-forms) (parse-tagbody (rest expression))) (define-unique-symbols continue-from-tagbody thunk tagbody-prompt-tag tag-thunk) (define tags (map first tagged-forms)) (define (thunk-form statements) "Return a thunk that calls (progn statements...) in continuation-passing style." `(cl:lambda () (without-continuation ,(progn->cps statements)))) (define (tag-thunk-form statements next-tag) "Return a thunk that evaluates a tag's statements before calling the next-tag's thunk." (thunk-form (append statements (list `(funcall ,(tag->function-name next-tag)))))) (define (last-tag-thunk-form statements) "Return a thunk that evaluates a tag's statements." (thunk-form statements)) (define tag->function-name-alist (map (lambda (tag) (cons tag (unique-symbol (symbolicate tag '-function)))) tags)) (define (tag->function-name tag) (alist-ref tag->function-name-alist tag)) (define function-names (map tag->function-name tags)) (define (tag->statements tag) (alist-ref tagged-forms tag)) (define (extend-lexical-context alist) (alist-update alist :tagbody-context-alist (lambda (alist) (append (map (lambda (tag) (cons tag (list tagbody-prompt-tag (tag->function-name tag)))) tags) alist)))) (let* ((*lexical-context* (extend-lexical-context *lexical-context*))) (define untagged-thunk-form (if (empty? tags) (last-tag-thunk-form untagged-statements) (tag-thunk-form untagged-statements (first tags)))) (define function-name-assignments (append (map (lambda (tag next-function-name) `(setq ,(tag->function-name tag) ,(tag-thunk-form (tag->statements tag) next-function-name))) tags (rest tags)) (map (lambda (tag) `(setq ,(tag->function-name tag) ,(last-tag-thunk-form (tag->statements tag)))) (last tags)))) `(let (,@function-names) ,@function-name-assignments (save-continuation ,continue-from-tagbody (let run-tagbody ((,thunk ,untagged-thunk-form)) (let (encountered-go?) (with-primary-value-continuation (,tag-thunk (run *continuation* ',tagbody-prompt-tag ,thunk (cl:lambda (tag-thunk _continue-from-go) (declare (ignore _continue-from-go)) (set! encountered-go? t) tag-thunk))) (if encountered-go? (run-tagbody ,tag-thunk) (with-return-to-saved-continuation ,continue-from-tagbody (continue-with nil)))))))))) (define-transform-cps-special-form cl:go (expression environment) (define-destructuring (tag) (rest expression)) (define tag-data (alist-ref (alist-ref *lexical-context* :tagbody-context-alist) tag)) (cond (tag-data (define-destructuring (tagbody-prompt-tag function-name) tag-data) (transform-cps `(fcontrol ',tagbody-prompt-tag ,function-name))) (t (error "Could not find TAG ~S in lexical-context of GO." tag)))) progv Progv forms can be re - entered , but the dynamic bindings will no longer be in effect . (define-transform-cps-special-form cl:progv (expression environment) (define-destructuring (vars-form vals-form &body forms) (rest expression)) (define-unique-symbols continue-from-progv vars vals progv-prompt-tag) `(save-continuation ,continue-from-progv (with-primary-value-continuation (,vars ,(transform-cps vars-form)) (with-primary-value-continuation (,vals ,(transform-cps vals-form)) (with-return-to-saved-continuation ,continue-from-progv ,(transform-cps `(run/cc ',progv-prompt-tag (cl:lambda () (no-cps (progv ,vars ,vals ,(progn->cps forms)))) #'default-prompt-handler))))))) (defmacro cps-form-equal? (form) (let ((results (unique-symbol 'results))) `(let ((,results (multiple-value-list ,form))) (values (equal? (multiple-value-list (cps ,form)) ,results) ,results)))) (assert (cps-form-equal? 1)) (assert (cps-form-equal? (no-cps (values 1 2 3)))) (assert (cps-form-equal? (no-cps (cps (values 1 2 3))))) (assert (cps-form-equal? #'+)) (assert (cps-form-equal? '(the quick brown fox))) (assert (cps-form-equal? (values 1 2 3 4 5))) (assert (cps-form-equal? (+ (values 1 2) (values 3 4)))) (assert (cps-form-equal? (+ 1 2 (+ 3 4)))) (assert (equal? (scm (let* ((xs ()) (push-v (lambda (x) (push x xs) x))) (list (% (+ (push-v 1) (push-v (fcontrol :pause :value)) (push-v 3)) :tag :pause :handler (lambda (value continue) (: VALUE ( + 1 2 3 ) ( + 1 3 3 ) ) = > (: value 6 7 ) (list value (continue 2) (continue 3)))) (nreverse xs)))) '((:VALUE 6 7) (1 2 3 3 3)))) Progn (assert (cps-form-equal? (progn))) (assert (cps-form-equal? (progn (values 1 2 3)))) (assert (cps-form-equal? (progn 1 2 3 4 (values 1 2 3)))) (assert (equal? (with-output-to-string (s) (assert (equal? (multiple-value-list (cps (progn (format s "c") (format s "b") (format s "a") (values 1 2 3)))) '(1 2 3)))) "cba")) (assert (cps-form-equal? (progn '(the quick brown fox) #'+))) (assert (cps-form-equal? (progn #'+ '(the quick brown fox)))) (assert (equal? (scm (% (progn (fcontrol :abort :value)) :tag :abort :handler (lambda (v k) (list v (multiple-value-list (k 1 2 3)) (multiple-value-list (k 4 5 6)))))) '(:value (1 2 3) (4 5 6)))) (assert (equal? (scm (let* ((vs ()) (v (lambda (x) (push x vs) x))) (list (% (progn (v (fcontrol :abort :value)) (v 2) (v 3)) :tag :abort :handler (lambda (v k) (k 1) vs : ( 3 2 : one 3 2 1 ) (k :one) v)) ( 3 2 : one 3 2 1 ) vs))) '(:VALUE (3 2 :ONE 3 2 1)))) (assert (cps-form-equal? (let () (values 1 2 3)))) (assert (cps-form-equal? (let ((a 1) (b :steak)) (values a b)))) (assert (cps-form-equal? (let ((a (values 1 2 3)) (b (values :steak :sauce))) (values a b)))) Verifies that names are n't visible , but causes a warning ( assert ( not ( ignore - errors ( cps ( let ( ( a 1 ) ( b a ) ) ( values a b ) ) ) ) ) ) (assert (equal? (scm (% (let () (fcontrol :abort :value)) :tag :abort :handler (lambda (v k) (list v (multiple-value-list (k 1 2 3)))))) '(:value (1 2 3)))) (assert (equal? (scm (define vs ()) (define (v x) (push x vs) x) (list (% (let ((binding1 (v 1)) (binding2 (v (fcontrol :abort :value))) (binding3 (v 3))) (values binding1 binding2 binding3)) :tag :abort :handler (lambda (v k) (list v (multiple-value-list (k 2 :ignored)) ( 1 : two 3 ) (multiple-value-list (k :two :ignored))))) (nreverse vs))) '((:VALUE (1 2 3) (1 :TWO 3)) (1 2 3 :TWO 3)))) (assert (cps-form-equal? (let* () (values 1 2 3)))) (assert (cps-form-equal? (let* ((a 1) (b (1+ a)) (c (1+ b))) c (values a b)))) (assert (cps-form-equal? (let* ((a 1) b (c (1+ a))) b (values a c)))) (assert (equal? (scm (% (let* () (fcontrol :abort :value)) :tag :abort :handler (lambda (v k) (list v (multiple-value-list (k 1 2 3)))))) '(:value (1 2 3)))) (assert (equal? (scm (define vs ()) (define (v x) (push x vs) x) (list (% (let* ((binding1 (v 1)) (binding2 (v (fcontrol :abort :value))) (binding3 (v (+ binding1 binding2)))) (values binding1 binding2 binding3)) :tag :abort :handler (lambda (v k) (list v ( 1 2 ( + 1 2 ) ) (multiple-value-list (k 2 :ignored)) ( 1 4 ( + 1 4 ) ) (multiple-value-list (k 4 :ignored))))) (nreverse vs))) '((:VALUE (1 2 3) (1 4 5)) (1 2 3 4 5)))) (assert (equal? (multiple-value-list (funcall (cps (cl:lambda (a b c) (values a b c))) 1 2 3)) '(1 2 3))) (assert (cps-form-equal? (funcall (cl:lambda (a b c) (values a b c)) 1 2 3))) (assert (equal? (multiple-value-list (funcall (cps (funcall (cl:lambda (f) (cl:lambda (&rest args) (apply f args))) (cl:lambda (&rest args) (apply #'values args)))) 1 2 3)) '(1 2 3))) (assert (equal? (scm (define vs ()) (define (v x) (push x vs) x) (list (% (funcall (cl:lambda (a b c) (values (v a) (v (fcontrol :abort b)) (v c))) 1 :value 3) :tag :abort :handler (lambda (v k) (list v (multiple-value-list (k 2)) ( 1 : two 3 ) (multiple-value-list (k :two))))) (nreverse vs))) '((:VALUE (1 2 3) (1 :TWO 3)) (1 2 3 :TWO 3)))) (assert (equal? (scm (% (funcall (cl:lambda (p1 p2 &optional (o1 (fcontrol :abort :o1)) (o2 (fcontrol :abort :o2))) (list p1 p2 o1 o2)) :p1 :P2 :o1) :tag :abort :handler (cl:lambda (v k) (list v (funcall k :o2) (funcall k :o2-again))))) '(:O2 (:P1 :P2 :O1 :O2) (:P1 :P2 :O1 :O2-AGAIN)))) (assert (cps-form-equal? (setq))) (assert (let (a b c) (cps-form-equal? (setq a 1 b (1+ a) c (1+ b))))) (assert (equal? (scm (define vs ()) (define (v x) (push x vs) x) (let (a b c) (list (% (setq a (v :a) b (v (fcontrol :abort :value)) c (v b)) :tag :abort :handler (lambda (v k) (list v (list a b c) (k :b :ignored) (list a b c) (k :bee :ignored) (list a b c)))) (nreverse vs)))) '((:VALUE (:A NIL NIL) :B (:A :B :B) :BEE (:A :BEE :BEE)) (:A :B :B :BEE :BEE)))) (assert (cps-form-equal? (if (values t nil nil) (progn 1 2 3) Unreachable (values 4 5 6)))) (assert (cps-form-equal? (if (values nil t nil) (progn 1 2 3) (values 4 5 6)))) (assert (equal? (scm (define vs ()) (define (v x) (push x vs) x) (list (% (if (v (fcontrol :abort :value)) (v :true) (v :false)) :tag :abort :handler (lambda (v k) (list v (k t :ignored) (k nil :ignored)))) (nreverse vs))) '((:value :true :false) (t :true nil :false)))) (assert (cps-form-equal? (the (values number string &optional) (values 3 "string")))) (assert (equal? (scm (list (% (the (values number string &optional) (fcontrol :abort :value)) :tag :abort :handler (lambda (v k) (list v (multiple-value-list (k 3 "hello"))))))) '((:VALUE (3 "hello"))))) (assert (cps-form-equal? (multiple-value-call (values #'list 2 3 4) (values) (values)))) (assert (cps-form-equal? (multiple-value-call (values #'list 2 3 4)))) (assert (cps-form-equal? (multiple-value-call (values #'values 2 3 4) (values 1 2) (values 3 4) (values 5 6)))) (assert (equal? (scm (define vs ()) (define (v x) (push x vs) x) (list (% (multiple-value-call list (values (v 1) (v 2)) (fcontrol :abort :value) (values (v 5) (v 6))) :tag :abort :handler (lambda (v k) (list v (k 3 4) (k :three :four)))) (nreverse vs))) '((:VALUE (1 2 3 4 5 6) (1 2 :THREE :FOUR 5 6)) (1 2 5 6 5 6)))) (assert (cps-form-equal? (block blah 1))) (assert (cps-form-equal? (block blah (values 1 2 3)))) (assert (cps-form-equal? (block outer (block inner (return-from outer :inner)) (values 1 2 3)))) (assert (cps-form-equal? (block blah (values 1 (return-from blah (values 2 :two :dos)) 3)))) (assert (cps-form-equal? (scm (block name (let ((f (lambda () (return-from name :ok)))) (f)))))) (cps (scm ((block name (let ((f (lambda () (return-from name (lambda () :ok))))) f))))) (assert (equal? (scm (% (block name (fcontrol :abort :value)) :tag :abort :handler (lambda (value k) (list value (multiple-value-list (k 1 2 3)))))) '(:VALUE (1 2 3)))) (assert (equal? (scm (% (block name (return-from name (fcontrol :abort :value)) (error "unreached")) :tag :abort :handler (lambda (value k) (list value (multiple-value-list (k 1 2 3)))))) '(:VALUE (1 2 3)))) (assert (equal? (scm (% (block name (fcontrol :abort :value) (return-from name (values 1 2 3)) (error "unreached")) :tag :abort :handler (lambda (value k) (list value (multiple-value-list (k)))))) '(:VALUE (1 2 3)))) (assert (equal? (scm (% (block name (let ((f (cl:lambda () (return-from name (values 1 2 3))))) (fcontrol :abort :value) (f) (error "unreached"))) :tag :abort :handler (lambda (value k) (list value (multiple-value-list (k)))))) '(:VALUE (1 2 3)))) (assert (equal? (scm (% (block name (let ((f (cl:lambda () (fcontrol :abort :value) (return-from name (values 1 2 3))))) (f) (error "unreached"))) :tag :abort :handler (lambda (value k) (list value (multiple-value-list (k)))))) '(:VALUE (1 2 3)))) (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (block name (v :start) (unwind-protect (v (return-from name (v :returning))) (v :cleanup)) (v :after)) (nreverse vs))))) (assert (cps-form-equal? (list (labels () :value) :after))) (assert (cps-form-equal? (list (flet () :value) :after))) (assert (equal? (% (labels ((f1 (&optional (o1 (fcontrol :abort :value))) (f2 `(f1 ,o1))) (f2 (p) `(f2 ,p))) (f1)) :tag :abort :handler (lambda (v k) (list v (funcall k :o1)))) '(:VALUE (F2 (F1 :O1))))) (assert (equal? (% (flet ((f1 (&optional (o1 (fcontrol :abort :value))) `(f1 ,o1)) (f2 (v) `(f2 ,v))) (list (f1) (f2 :v))) :tag :abort :handler (lambda (v k) (list v (funcall k :o1)))) '(:VALUE ((F1 :O1) (F2 :V))))) Eval - when will never appear as a top - level - form if it is part of a CPS expression (assert (cps-form-equal? (list (eval-when (:execute) (list 1 2 3)) 2 3))) (assert (cps-form-equal? (list (eval-when (:compile-toplevel :load-toplevel) (list 1 2 3)) 2 3))) (assert (scm (cps-form-equal? (let ((f (cl:lambda (x flag) (macrolet ((fudge (z) `(if flag (list '* ,z ,z) ,z))) `(+ ,x ,(fudge x) ,(fudge `(+ ,x 1))))))) (list (f :x nil) (f :x :flag)))))) (assert (cps-form-equal? (list (symbol-macrolet ((garner `(list :attention))) garner) 'garner))) (assert (cps-form-equal? (funcall (cl:lambda (y) (declare (special y)) (let ((y t)) (list y (locally (declare (special y)) y)))) nil))) (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (tagbody (v :u1) (v :u2)) (nreverse vs))))) (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (v 'before) (tagbody (v :ut1) (v :ut2) tag1 (v :t1) (v :t11) tag2 (v :t2) (v :t22)) (v 'after)) (nreverse vs)))) (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (tagbody (v :ut1) (go tag2) (v :ut2) tag1 (v :t1) (go end) (v :t11) tag2 (v :t2) (go tag1) (v :t22) end (v :end)) (nreverse vs))))) (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (tagbody (v :u1) :t1 (v :t1) :t2 (v :t2)) (nreverse vs))))) (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (tagbody (v :u1) (go :t2) :t1 (v :t1) (go :end) :t2 (v :t2) (go :t1) :end (v :end)) (nreverse vs))))) (assert (equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (% (list (v :before) (tagbody (v :u1) (go :t2) :t1 (v :t1) (go :end) :t2 (v :t2) (v (fcontrol :abort :value)) (go :t1) :end (v :end)) (v :after)) :tag :abort :handler (lambda (v k) (list v (k :resume) (k :resume)))) (nreverse vs))) '((:VALUE (:BEFORE NIL :AFTER) (:BEFORE NIL :AFTER)) (:BEFORE :U1 :T2 :RESUME :T1 :END :AFTER :RESUME :T1 :END :AFTER)))) (assert (equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (% (list (v :before) (tagbody (v :outer-u1) :outer-t1 (v :outer-t1) (tagbody (v :inner-u1) (go :inner-t2) :inner-t1 (v :t1) (go :outer-t2) :inner-t2 (v :t2) (v (fcontrol :abort :value)) (go :inner-t1)) :outer-t2 (v :outer-t2) (go :end) :end (v :end)) (v :after)) :tag :abort :handler (lambda (v k) (list v (k :resume) (k :resume)))) (nreverse vs))) '((:VALUE (:BEFORE NIL :AFTER) (:BEFORE NIL :AFTER)) (:BEFORE :OUTER-U1 :OUTER-T1 :INNER-U1 :T2 :RESUME :T1 :OUTER-T2 :END :AFTER :RESUME :T1 :OUTER-T2 :END :AFTER)))) (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (tagbody (v :start) :tag1 (v :tag1) (unwind-protect (progn (v :inside-protected) (go :tag2)) (v :cleanup)) :tag2 (v :tag2)) (nreverse vs)))) progv (assert (cps-form-equal? (let ((x 3)) (LIST (progv '(x) '(4) (list x (symbol-value 'x))) (list x (boundp 'x)))))) (assert (equal? (scm (% (let ((x 3)) (list (progv '(x) '(4) (list x (symbol-value 'x) (setf (symbol-value 'x) 2) (fcontrol :abort :value) (boundp 'x))) (list x (boundp 'x)))) :tag :abort :handler (lambda (v k) (list v (k :resume))))) '(:VALUE ((3 4 2 :RESUME NIL) (3 NIL))))) (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (unwind-protect (v :protected) (v :cleanup)) (nreverse vs))))) (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (list (catch :tag (unwind-protect (progn (v :protected) (throw :tag :thrown-value) (v :unreached)) (v :cleanup))) (nreverse vs))))) (def (run-thunk-until-normal-exit thunk) "Run thunk calling (k v) until a normal exit occurs. Useful for testing." (cps (let recurse ((thunk thunk)) (run/cc *default-prompt-tag* thunk (lambda (v k) (recurse (lambda () (k v)))))))) (defvar *vs*) (def (trace-v x) (push x *vs*) x) (defmacro with-v-tracing (&body body) `(let ((*vs* ())) (list ,@body (reverse *vs*)))) (assert (null (ignore-errors (with-v-tracing (scm (run-thunk-until-normal-exit (cps (lambda () (trace-v :before) (unwind-protect (trace-v (throw/cc (trace-v :protected))) (trace-v :cleanup)) (trace-v :after))))))))) (assert (equal? (ignore-errors (with-v-tracing (scm (run-thunk-until-normal-exit (cps (lambda () (trace-v :before) (unwind-protect (error "error") (trace-v (throw/cc :cleanup1)) (trace-v (throw/cc :cleanup2))) (trace-v :after))))))) '(:CLEANUP2 (:BEFORE :CLEANUP1 :CLEANUP2)))) (assert (equal? (with-v-tracing (scm (run-thunk-until-normal-exit (cps (lambda () (trace-v :before) (trace-v (unwind-protect (trace-v :protected) (trace-v (throw/cc :cleanup1)) (trace-v (throw/cc :cleanup2)))) (trace-v :after)))))) '(:AFTER (:BEFORE :PROTECTED :CLEANUP1 :CLEANUP2 :PROTECTED :AFTER)))) (assert (equal? (scm (def vs ()) (def (v x) (push x vs) x) (% (unwind-protect (progn (v 'protected) (values 1 2 3)) (v 'cleanup) (fcontrol :escape-cleanup :value) (v 'resume-cleanup)) :tag :escape-cleanup :handler (lambda (value k) (v 'handler) (list value (multiple-value-list (k)) (multiple-value-list (k)) (nreverse vs))))) '(:VALUE (1 2 3) (1 2 3) (PROTECTED CLEANUP HANDLER RESUME-CLEANUP RESUME-CLEANUP)))) (assert (equal? (scm (def vs ()) (def (v x) (push x vs) x) (ignore-errors (% (unwind-protect (progn (v :protected) (fcontrol :tag :thrown-value) (v :unreached)) (v :cleanup)) :tag :tag :handler (lambda (_ k) (k)))) (nreverse vs)) '(:PROTECTED :CLEANUP))) (assert (equal? (let (cleanup?) (ignore-errors (cps (unwind-protect (error "error") (set! cleanup? t)))) cleanup?) (let (cleanup?) (ignore-errors (unwind-protect (error "error") (set! cleanup? t))) cleanup?))) GO 's unwind (assert (cps-form-equal? (scm (def vs ()) (def (v x) (push x vs) x) (tagbody (unwind-protect (progn (v :u1-protected) (go :t2)) (v :u1-cleanup)) :t1 (unwind-protect (progn (v :t1-protected) (go :end)) (v :t1-cleanup)) :t2 (unwind-protect (progn (v :t2-protected) (go :t1)) (v :t2-cleanup)) :end) (nreverse vs)))) (assert (cps-form-equal? (catch :tag (throw :tag (values 1 2 3)) (error "unreached")))) (assert (cps-form-equal? (catch :tag (throw (throw :tag (values :one :two :three)) (values 1 2 3)) (error "unreached")))) (assert (cps-form-equal? (catch :tag (catch (throw :tag (values :one :two :three)) (values 1 2 3)) (error "unreached")))) (assert (cps-form-equal? (catch (values :outer :bouter) (catch (values :inner :binner) (throw :outer (values :one :two :three)) (error "unreached")) (error "unreached")))) (assert (equal? (scm (% (progn (catch :tag (fcontrol :abort :value) (print 'throwing) (throw :tag :value)) (values 1 2 3)) :tag :abort :handler (lambda (v k) (print 'catching) (list v (multiple-value-list (k)))))) '(:VALUE (1 2 3)))) (assert (equal? (scm (% (catch :outer (let ((inner-results (multiple-value-list (catch :inner (fcontrol :abort :value) (throw :inner (values 1 2 3)) (error "not reached"))))) (throw :outer inner-results) (error "not reached"))) :tag :abort :handler (lambda (v k) (list v (k))))) '(:VALUE (1 2 3)))) (cps (progn (catch :tag (throw :tag :value)) (throw :tag :value))) (assert (cps (scm (def (rnd) (list (load-time-value (random 17)) 2)) (equal? (rnd) (rnd))))) (assert (cps-form-equal? (let (temp) (setq temp '(1 2 3)) (list (multiple-value-list (multiple-value-prog1 (values-list temp) (setq temp nil) (values-list temp))) temp)))) (assert (equal? (% (list (fcontrol :abort :one) 2 3) :tag :abort :handler (cl:lambda (value continuation) (list value (funcall continuation 1)))) '(:one (1 2 3)))) (assert (equal? (% (% (list (fcontrol :outer-abort :one) (fcontrol :inner-abort :two) 3) :tag :inner-abort :handler (cl:lambda (value continuation) (declare (ignore value)) (funcall continuation 2))) :tag :outer-abort :handler (cl:lambda (value continuation) (declare (ignore value)) (funcall continuation 1))) '(1 2 3))) (def (product . numbers) (% (let recurse ((numbers numbers)) (cond ((empty? numbers) 1) (t (define-destructuring (number . rest-of-numbers) numbers) (cond ((zero? number) (fcontrol :product :zero)) (t (* number (recurse rest-of-numbers))))))) :tag :product :handler (lambda (result _continuation) result))) (assert (= (product 1 2 3 4 5) (* 1 2 3 4 5))) (assert (eq? :zero (product 0 1 2 3 4 5))) (def (make-fringe tree) (cps (lambda () (let recurse ((tree tree)) (cond ((pair? tree) (recurse (car tree)) (recurse (cdr tree))) ((empty? tree) :*) (t (fcontrol :yield tree)))) (fcontrol :yield ())))) (def (collect-fringe tree) (define leaves ()) (let recurse ((fringe (make-fringe tree))) (% (fringe) :tag :yield :handler (lambda (leaf rest-of-fringe) (cond ((null? leaf) leaves) (t (push leaf leaves) (recurse rest-of-fringe)))))) leaves) (def (same-fringe? tree1 tree2) (let recurse ((fringe1 (make-fringe tree1)) (fringe2 (make-fringe tree2))) (% (fringe1) :tag :yield :handler (lambda (leaf1 rest-of-fringe1) (% (fringe2) :tag :yield :handler (lambda (leaf2 rest-of-fringe2) (if (eq? leaf1 leaf2) (if (null? leaf1) t (recurse rest-of-fringe1 rest-of-fringe2)) nil))))))) (assert (equal? (collect-fringe '((1 2) ((3 (4 5)) (6 7)))) '(7 6 5 4 3 2 1))) (assert (same-fringe? '((1 2) ((3) (4 5))) '((1 . 2) . ((3 . ()) . (4 . 5))))) (assert (not (same-fringe? '((1 2) ((3) (4 5))) '((1 2) ((3 4) (4 5)))))) N : = ( cl : ) N : = ( cl : macrolet bindings M ) N : = ( cl : unwind - protect N M ) N : = ( cl : M_1 tag1 M_tag1 tag2 M_tag2 ... ) ( with - ignored - values - continuation N body ) = > ( progn N body ) 1st pass : expand all macros with special cases (hash-keys *transform-cps-special-form-table*) (def (augment-environment-with-macro-bindings bindings environment) (trivial-cltl2:augment-environment environment :macro (map (lambda (binding) (def-destructuring (name lambda-list . body) binding) (list name (trivial-cltl2:enclose (trivial-cltl2:parse-macro name lambda-list body environment) environment))) bindings))) (def (augment-environment-with-symbol-macro-bindings bindings environment) (trivial-cltl2:augment-environment environment :symbol-macro bindings)) (def (macroexpand-progn-forms forms environment) (map (lambda (form) (macroexpand-all-cps form environment)) forms)) (def (macroexpand-body body environment) (def-values (declarations forms) (parse-declarations body)) (append declarations (macroexpand-progn-forms forms environment))) (def (expanded-body body environment) (def-values (declarations forms) (parse-declarations body)) (def expanded-body (macroexpand-body body environment)) (cond ((empty? declarations) (cond ((empty? forms) nil) ((empty? (rest forms)) (first expanded-body)) (t `(progn ,@expanded-body)))) (t `(locally ,@expanded-body)))) (defvar *cps-special-forms* '(NO-CPS FCONTROL cl:QUOTE cl:FUNCTION cl:PROGN COMMON-LISP:LET cl:LET* cl:MACROLET cl:SYMBOL-MACROLET cl:LOCALLY COMMON-LISP:LAMBDA cl:SETQ cl:IF cl:THE cl:MULTIPLE-VALUE-CALL cl:EVAL-WHEN cl:LOAD-TIME-VALUE cl:MULTIPLE-VALUE-PROG1 cl:LABELS cl:FLET cl:BLOCK cl:RETURN-FROM cl:CATCH cl:THROW cl:UNWIND-PROTECT cl:TAGBODY cl:GO cl:PROGV)) (def (macroexpand-all-cps cps-form environment) "Macroexpand-all for CPS-FORM, respecting Common Lisp special forms as well as CPS special forms. See *CPS-SPECIAL-FORMS* for a full list of special forms recognized by CPS. The resulting expansion will not have any macros remaining. Any cl:macrolet and cl:symbol-macrolet will be removed after their expansions have been applied." (cond CPS - FORM is either , NIL , a symbol or a symbol - macro ((symbol? cps-form) (def-values (expanded-cps-form macro?) (macroexpand-1 cps-form environment)) (if macro? (macroexpand-all-cps expanded-cps-form environment) expanded-cps-form)) CPS - FORM is a non - symbol atom ((atom cps-form) cps-form) (t (def symbol (first cps-form)) (cond ((member symbol '(cl:quote cl:function)) cps-form) ((eq? symbol 'cl:progn) `(cl:progn ,@(macroexpand-progn-forms (progn-forms cps-form) environment))) ((member symbol '(cl:let cl:let*)) `(,symbol ,(map (lambda (binding) (list (let-binding-name binding) (macroexpand-all-cps (let-binding-value binding) environment))) (let-bindings cps-form)) ,@(macroexpand-body (let-body cps-form) environment))) ((eq? symbol 'cl:macrolet) (let ((environment (augment-environment-with-macro-bindings (macrolet-bindings cps-form) environment))) (expanded-body (macrolet-body cps-form) environment))) ((eq? symbol 'cl:symbol-macrolet) (let ((environment (augment-environment-with-symbol-macro-bindings (symbol-macrolet-bindings cps-form) environment))) (expanded-body (symbol-macrolet-body cps-form) environment))) ((eq? symbol 'cl:locally) (expanded-body (locally-body cps-form) environment)) ((eq? symbol 'cl:lambda) `(cl:lambda ,(map-ordinary-lambda-list (lambda (key parameter) (ecase key ((:positional :rest) parameter) (:keyword parameter) ((:optional :key) (cond ((pair? parameter) (define-destructuring (name &optional default-value provided?) parameter) (list name (macroexpand-all-cps default-value environment) (or provided? (unique-symbol (symbolicate name '-provided?))))) (t (list parameter nil (unique-symbol (symbolicate parameter '-provided?)))))) (:aux (cond ((pair? parameter) (define-destructuring (name &optional default-value) parameter) (list name (macroexpand-all-cps default-value environment))) (t (list parameter nil)))))) (lambda-parameters cps-form)) ,@(macroexpand-body (lambda-body cps-form) environment))) ((eq? symbol 'cl:setq) `(cl:setq ,@(append-map (lambda (pair) (def-destructuring (name value) pair) (list name (macroexpand-all-cps value environment))) (setq-pairs cps-form)))) ((eq? symbol 'cl:if) `(cl:if ,(macroexpand-all-cps (if-test cps-form) environment) ,(macroexpand-all-cps (if-then cps-form) environment) ,(macroexpand-all-cps (if-else cps-form) environment))) ((eq? symbol 'cl:the) `(cl:the ,(the-value-type cps-form) ,(macroexpand-all-cps (the-form cps-form) environment))) TODO ((eq? symbol 'cl:multiple-value-call)) ((eq? symbol 'cl:eval-when)) ((eq? symbol 'cl:load-time-value)) ((eq? symbol 'cl:multiple-value-prog1)) ((eq? symbol 'cl:labels)) ((eq? symbol 'cl:flet)) ((eq? symbol 'cl:block)) ((eq? symbol 'cl:return-from)) ((eq? symbol 'cl:catch)) ((eq? symbol 'cl:throw)) ((eq? symbol 'cl:tagbody)) ((eq? symbol 'cl:go)) ((eq? symbol 'cl:progv)) ((eq? symbol 'cl:unwind-protect)) ((eq? symbol 'no-cps)) ((eq? symbol 'fcontrol)) (t (def-values (expanded-cps-form macro?) (macroexpand-1 cps-form environment)) (if macro? (macroexpand-all-cps expanded-cps-form environment) (progn (def-destructuring (name . arguments) expanded-cps-form) `(,name ,@(map (lambda (form) (macroexpand-all-cps form environment)) arguments))))))))) (macroexpand-all-cps '(symbol-macrolet ((a :a)) 'b (macrolet ((m (a) `(list ,a))) (cl:lambda (&optional a (m (m a))) (locally a (m a)) (if (setq a (m 1)) (the (m 1) (m 2)) (m 3))) a)) nil)
10c8275b48b9937497f919e7d20659de006fce27d2bb7bef3c9209c4c168aeba
haskell-github/github
GitLog.hs
module GitLog where import qualified Github.Repos.Commits as Github import Data.List main = do possibleCommits <- Github.commitsFor "thoughtbot" "paperclip" case possibleCommits of (Left error) -> putStrLn $ "Error: " ++ (show error) (Right commits) -> putStrLn $ intercalate "\n\n" $ map formatCommit commits formatCommit :: Github.Commit -> String formatCommit commit = "commit " ++ (Github.commitSha commit) ++ "\nAuthor: " ++ (formatAuthor author) ++ "\nDate: " ++ (show $ Github.fromDate $ Github.gitUserDate author) ++ "\n\n\t" ++ (Github.gitCommitMessage gitCommit) where author = Github.gitCommitAuthor gitCommit gitCommit = Github.commitGitCommit commit formatAuthor :: Github.GitUser -> String formatAuthor author = (Github.gitUserName author) ++ " <" ++ (Github.gitUserEmail author) ++ ">"
null
https://raw.githubusercontent.com/haskell-github/github/81d9b658c33a706f18418211a78d2690752518a4/samples/Repos/Commits/GitLog.hs
haskell
module GitLog where import qualified Github.Repos.Commits as Github import Data.List main = do possibleCommits <- Github.commitsFor "thoughtbot" "paperclip" case possibleCommits of (Left error) -> putStrLn $ "Error: " ++ (show error) (Right commits) -> putStrLn $ intercalate "\n\n" $ map formatCommit commits formatCommit :: Github.Commit -> String formatCommit commit = "commit " ++ (Github.commitSha commit) ++ "\nAuthor: " ++ (formatAuthor author) ++ "\nDate: " ++ (show $ Github.fromDate $ Github.gitUserDate author) ++ "\n\n\t" ++ (Github.gitCommitMessage gitCommit) where author = Github.gitCommitAuthor gitCommit gitCommit = Github.commitGitCommit commit formatAuthor :: Github.GitUser -> String formatAuthor author = (Github.gitUserName author) ++ " <" ++ (Github.gitUserEmail author) ++ ">"
0916c18cc0705a85711dd53576360b2b2007cfa44c13132528c5966a9b93ac25
nikomatsakis/a-mir-formality
test-solution.rkt
#lang racket (require redex/reduction-semantics "../../util.rkt" "../../logic/env-inequalities.rkt" "../../logic/substitution.rkt" "../../logic/instantiate.rkt" "../../logic/solution.rkt" "../grammar.rkt" "../user-ty.rkt" "hook.rkt" ) (module+ test (redex-let* formality-ty [(Env_0 (term (env-with-clauses-invariants-and-generics [] [] []))) ; Model a canonical query (?A ?B) that has an answer ?A = Vec<?C>, ?C <: ?B ; Create placeholder T and inference variables ?A and ?B ; that are meant to be part of the "canonical query" ((Env_1 () (Ty_T)) (term (instantiate-quantified EmptyEnv (∀ ((type T)) ())))) ((Env_2 () (Ty_A Ty_B)) (term (instantiate-quantified Env_1 (∃ ((type A) (type B)) ())))) ; Create the "solution" constraints: ; * there exists a C... ((Env_3 () (Ty_C)) (term (instantiate-quantified Env_2 (∃ ((type C)) ())))) ; * where C <: B (Env_4 (term (env-with-var-related-to-parameter Env_3 Ty_C <= Ty_B))) * and A = = > (Env_5 (term (env-with-var-mapped-to Env_4 Ty_A (user-ty (Vec < Ty_C >))))) (Env_N (term Env_5)) ] (test-match-terms formality-ty (extract-solution Env_N (Ty_A Ty_B)) (:- ((VarId_C type ∃ (universe 1))) (((Ty_A (rigid-ty Vec (VarId_C)))) ((VarId_C <= Ty_B))))) ) )
null
https://raw.githubusercontent.com/nikomatsakis/a-mir-formality/bc951e21bff2bae1ccab8cc05b2b39cfb6365bfd/racket-src/ty/test/test-solution.rkt
racket
Model a canonical query (?A ?B) that has an answer ?A = Vec<?C>, ?C <: ?B Create placeholder T and inference variables ?A and ?B that are meant to be part of the "canonical query" Create the "solution" constraints: * there exists a C... * where C <: B
#lang racket (require redex/reduction-semantics "../../util.rkt" "../../logic/env-inequalities.rkt" "../../logic/substitution.rkt" "../../logic/instantiate.rkt" "../../logic/solution.rkt" "../grammar.rkt" "../user-ty.rkt" "hook.rkt" ) (module+ test (redex-let* formality-ty [(Env_0 (term (env-with-clauses-invariants-and-generics [] [] []))) ((Env_1 () (Ty_T)) (term (instantiate-quantified EmptyEnv (∀ ((type T)) ())))) ((Env_2 () (Ty_A Ty_B)) (term (instantiate-quantified Env_1 (∃ ((type A) (type B)) ())))) ((Env_3 () (Ty_C)) (term (instantiate-quantified Env_2 (∃ ((type C)) ())))) (Env_4 (term (env-with-var-related-to-parameter Env_3 Ty_C <= Ty_B))) * and A = = > (Env_5 (term (env-with-var-mapped-to Env_4 Ty_A (user-ty (Vec < Ty_C >))))) (Env_N (term Env_5)) ] (test-match-terms formality-ty (extract-solution Env_N (Ty_A Ty_B)) (:- ((VarId_C type ∃ (universe 1))) (((Ty_A (rigid-ty Vec (VarId_C)))) ((VarId_C <= Ty_B))))) ) )
0a7764ef1108233f66dd75cb87b6b9a8274a0c4781eabaaea4a70bbcf164ad32
LimitEpsilon/reanalyze-ropas
PrintSE.ml
open SetExpression let string_of_arithop : arithop -> string = function | INT x | INT32 x | INT64 x | FLOAT x | NATURALINT x -> ( match x with | ADD -> "+" | SUB -> "-" | DIV -> "÷" | MUL -> "×" | NEG -> "~-" | ABS -> "abs" | MOD -> "mod" | AND -> "&&" | OR -> "||" | NOT -> "not" | XOR -> "xor" | LSL -> "lsl" | LSR -> "lsr" | ASR -> "asr" | SUCC -> "++" | PRED -> "--") let string_of_relop : relop -> string = function | GEN x -> ( match x with | EQ -> "==" | NE -> "<>" | LT -> "<" | LE -> "<=" | GT -> ">" | GE -> ">=") module Loc = struct type t = loc let compare = compare end module LocSet = Set.Make (Loc) let to_be_explained = ref LocSet.empty let print_code_loc loc = CL.Location.print_loc Format.str_formatter loc; prerr_string (Format.flush_str_formatter ()) let print_loc = function | Expr_loc e -> print_code_loc e.exp_loc | Mod_loc m -> print_code_loc m.mod_loc | Bop_loc t -> print_code_loc t.val_loc let print_param = function | None -> () | Some (x, _) -> prerr_string (CL.Ident.name x) let print_expr : type k. k expr -> unit = function | Expr_var (p, _) -> prerr_string "Expr_var ("; prerr_string (CL.Ident.name p); prerr_string ")" | Expr loc -> prerr_string "Expr ("; print_loc loc; prerr_string ")" let print_tagged_expr : type k. k tagged_expr -> unit = function | Val v -> prerr_string "Val ("; print_expr v; prerr_string ")" | Packet p -> prerr_string "Packet ("; print_expr p; prerr_string ")" let rec print_se : value se -> unit = function | Top -> prerr_string "⊤" | Const c -> prerr_string (CL.Printpat.pretty_const c) | Fn (p, list) -> prerr_string "λ"; print_param p; prerr_string "."; print_expr_list_with_separator list ";" | Prim {prim_name} -> prerr_string ("Prim (" ^ prim_name ^ ")") | Var e -> prerr_string "X ("; print_tagged_expr e; prerr_string ")" | App_V (se, list) -> prerr_string "AppV ("; print_se se; prerr_string ", "; print_option_list_with_separator list ";"; prerr_string ")" | App_P (se, list) -> prerr_string "AppP ("; print_se se; prerr_string ", "; print_option_list_with_separator list ";"; prerr_string ")" | Ctor (k, Static arr) -> prerr_string "Ctor ("; (match k with None -> prerr_string " " | Some s -> prerr_string s); prerr_string ", "; print_arr_with_separator arr ";"; prerr_string ")" | Ctor (k, Dynamic (i, _)) -> prerr_string "Ctor ("; (match k with None -> prerr_string " " | Some s -> prerr_string s); prerr_string "malloc "; prerr_string (string_of_int i); prerr_string ")" | Fld (se, lbl) -> prerr_string "Fld ("; print_se se; prerr_string ", ("; (match lbl with | None, Some i -> prerr_string " , "; prerr_int i | Some s, Some i -> prerr_string s; prerr_string ", "; prerr_int i | _, None -> prerr_string " , "); prerr_string "))" | Arith (op, xs) -> Printf.eprintf "( %s ) " (string_of_arithop op); print_ses xs | Rel (rel, xs) -> Printf.eprintf "( %s ) " (string_of_relop rel); print_ses xs | Diff (x, y) -> prerr_string "("; print_se x; prerr_string ")-("; print_pattern y; prerr_string ")" | _ -> () and print_pattern : pattern se -> unit = function | Top -> prerr_string "⊤" | Const c -> prerr_string (CL.Printpat.pretty_const c) | Var e -> prerr_string "X ("; print_tagged_expr e; prerr_string ")" | Ctor_pat (k, arr) -> prerr_string "Ctor ("; (match k with None -> prerr_string " " | Some s -> prerr_string s); prerr_string ", "; print_pattern_arr_with_separator arr ";"; prerr_string ")" | Loc ((i, name), p) -> prerr_string "("; prerr_int i; prerr_string ", "; (match p with | Some p -> print_pattern p | _ -> to_be_explained := LocSet.add (i, name) !to_be_explained); prerr_string ")" | _ -> () and print_ses (xs : value se list) = prerr_string "["; List.iter print_se xs; prerr_string "]" and print_se_list_with_separator l sep = let l' = ref l in prerr_string "["; while !l' <> [] do match !l' with | hd :: tl -> prerr_string "("; print_se hd; prerr_string ")"; if tl <> [] then prerr_string sep; l' := tl | _ -> assert false done; prerr_string "]" and print_pattern_arr_with_separator arr sep = let len = Array.length arr in let i = ref 0 in prerr_string "["; while !i < len do print_pattern arr.(!i); if !i < len - 1 then prerr_string sep; incr i done; prerr_string "]" and print_expr_list_with_separator l sep = let l' = ref l in prerr_string "["; while !l' <> [] do match !l' with | hd :: tl -> prerr_string "("; print_expr hd; prerr_string ")"; if tl <> [] then prerr_string sep; l' := tl | _ -> assert false done; prerr_string "]" and print_option_list_with_separator l sep = let l' = ref l in prerr_string "["; while !l' <> [] do match !l' with | Some hd :: tl -> prerr_string "("; print_se hd; prerr_string ")"; if tl <> [] then prerr_string sep; l' := tl | None :: tl -> if tl <> [] then prerr_string sep; l' := tl | _ -> assert false done; prerr_string "]" and print_arr_with_separator arr sep = let len = Array.length arr in let i = ref 0 in prerr_string "["; while !i < len do prerr_int (fst arr.(!i)); if !i < len - 1 then prerr_string sep; incr i done; prerr_string "]" let show_env_map ( env_map : globalenv ) = (* Hashtbl.iter *) (* (fun param loc_tagged_expr -> *) (* prerr_string "Globalenv :\n param = "; *) ; (* prerr_string "\n code_loc tagged_expr = "; *) (* print_tagged_expr loc_tagged_expr; *) (* prerr_newline ()) *) (* env_map *) let show_se_with_separator set sep = SESet.iter (fun x -> prerr_string sep; print_se x; prerr_newline ()) set let show_pattern_with_separator set sep = GESet.iter (fun x -> prerr_string sep; print_pattern x; prerr_newline ()) set let show_var_se_tbl (var_to_se : var_se_tbl) = Hashtbl.iter (fun x se -> prerr_string "var_to_se :\n ident = "; prerr_string (CL.Ident.unique_name x); prerr_string "\n se = "; prerr_newline (); show_se_with_separator se "\t"; prerr_newline ()) var_to_se let show_mem (mem : (loc, SESet.t) Hashtbl.t) = Hashtbl.iter (fun (key, _) data -> if SESet.is_empty data then () else ( prerr_string "mem :\n"; prerr_int key; prerr_newline (); show_se_with_separator data "\t"; prerr_newline ())) mem let show_sc_tbl (tbl : (value se, SESet.t) Hashtbl.t) = Hashtbl.iter (fun key data -> if SESet.is_empty data then () else ( prerr_string "sc :\n"; print_se key; (match key with | Fld (_, _) -> prerr_string " <- " | _ -> prerr_string " = "); prerr_newline (); show_se_with_separator data "\t"; prerr_newline ())) tbl let show_grammar (g : (pattern se, GESet.t) Hashtbl.t) = Hashtbl.iter (fun key data -> if GESet.is_empty data then () else ( prerr_string "grammar :\n"; print_pattern key; prerr_string " = "; prerr_newline (); show_pattern_with_separator data "\t"; prerr_newline ())) g let show_abs_mem (a : (loc, GESet.t) Hashtbl.t) = Hashtbl.iter (fun (key, _) data -> if GESet.is_empty data then () else ( prerr_string "abs_mem :\n"; prerr_int key; prerr_string " = "; prerr_newline (); show_pattern_with_separator data "\t"; prerr_newline ())) a let show_exn_of_file (tbl : (string, value se list) Hashtbl.t) = Hashtbl.iter (fun key data -> prerr_string "exceptions in file "; prerr_string key; prerr_newline (); List.iter (function | Var x -> let set = try Hashtbl.find grammar (Var x) with _ -> GESet.empty in if GESet.is_empty set then () else ( prerr_string "\tfrom "; print_tagged_expr x; prerr_endline ":"; show_pattern_with_separator set "\t\t"; prerr_newline ()) | _ -> ()) data) tbl let show_closure_analysis tbl = prerr_endline "Closure analysis:"; Hashtbl.iter (fun key data -> let set = SESet.filter (fun x -> match x with | App_V (_, _) | Fn (_, _) | Prim _ -> true | _ -> false) data in if SESet.is_empty set then () else ( print_se key; prerr_newline (); show_se_with_separator set "\t"; prerr_newline ())) tbl let explain_abs_mem () = prerr_endline "where abstract locations contain:"; LocSet.iter (fun (i, name) -> let set = try Hashtbl.find abs_mem (i, name) with _ -> GESet.empty in prerr_string "\tlocation "; prerr_int i; prerr_newline (); show_pattern_with_separator set "\t\t"; prerr_newline ()) !to_be_explained; to_be_explained := LocSet.empty let print_sc_info () = show_mem mem; show_var_se_tbl var_to_se; show_sc_tbl sc let print_grammar () = show_abs_mem abs_mem; show_grammar grammar let print_exa () = Format.flush_str_formatter () |> ignore; show_exn_of_file exn_of_file; explain_abs_mem () let print_closure () = Format.flush_str_formatter () |> ignore; show_closure_analysis sc
null
https://raw.githubusercontent.com/LimitEpsilon/reanalyze-ropas/0db54b5fa4b85467a0ca7495bba8fc693da72a59/src/PrintSE.ml
ocaml
Hashtbl.iter (fun param loc_tagged_expr -> prerr_string "Globalenv :\n param = "; prerr_string "\n code_loc tagged_expr = "; print_tagged_expr loc_tagged_expr; prerr_newline ()) env_map
open SetExpression let string_of_arithop : arithop -> string = function | INT x | INT32 x | INT64 x | FLOAT x | NATURALINT x -> ( match x with | ADD -> "+" | SUB -> "-" | DIV -> "÷" | MUL -> "×" | NEG -> "~-" | ABS -> "abs" | MOD -> "mod" | AND -> "&&" | OR -> "||" | NOT -> "not" | XOR -> "xor" | LSL -> "lsl" | LSR -> "lsr" | ASR -> "asr" | SUCC -> "++" | PRED -> "--") let string_of_relop : relop -> string = function | GEN x -> ( match x with | EQ -> "==" | NE -> "<>" | LT -> "<" | LE -> "<=" | GT -> ">" | GE -> ">=") module Loc = struct type t = loc let compare = compare end module LocSet = Set.Make (Loc) let to_be_explained = ref LocSet.empty let print_code_loc loc = CL.Location.print_loc Format.str_formatter loc; prerr_string (Format.flush_str_formatter ()) let print_loc = function | Expr_loc e -> print_code_loc e.exp_loc | Mod_loc m -> print_code_loc m.mod_loc | Bop_loc t -> print_code_loc t.val_loc let print_param = function | None -> () | Some (x, _) -> prerr_string (CL.Ident.name x) let print_expr : type k. k expr -> unit = function | Expr_var (p, _) -> prerr_string "Expr_var ("; prerr_string (CL.Ident.name p); prerr_string ")" | Expr loc -> prerr_string "Expr ("; print_loc loc; prerr_string ")" let print_tagged_expr : type k. k tagged_expr -> unit = function | Val v -> prerr_string "Val ("; print_expr v; prerr_string ")" | Packet p -> prerr_string "Packet ("; print_expr p; prerr_string ")" let rec print_se : value se -> unit = function | Top -> prerr_string "⊤" | Const c -> prerr_string (CL.Printpat.pretty_const c) | Fn (p, list) -> prerr_string "λ"; print_param p; prerr_string "."; print_expr_list_with_separator list ";" | Prim {prim_name} -> prerr_string ("Prim (" ^ prim_name ^ ")") | Var e -> prerr_string "X ("; print_tagged_expr e; prerr_string ")" | App_V (se, list) -> prerr_string "AppV ("; print_se se; prerr_string ", "; print_option_list_with_separator list ";"; prerr_string ")" | App_P (se, list) -> prerr_string "AppP ("; print_se se; prerr_string ", "; print_option_list_with_separator list ";"; prerr_string ")" | Ctor (k, Static arr) -> prerr_string "Ctor ("; (match k with None -> prerr_string " " | Some s -> prerr_string s); prerr_string ", "; print_arr_with_separator arr ";"; prerr_string ")" | Ctor (k, Dynamic (i, _)) -> prerr_string "Ctor ("; (match k with None -> prerr_string " " | Some s -> prerr_string s); prerr_string "malloc "; prerr_string (string_of_int i); prerr_string ")" | Fld (se, lbl) -> prerr_string "Fld ("; print_se se; prerr_string ", ("; (match lbl with | None, Some i -> prerr_string " , "; prerr_int i | Some s, Some i -> prerr_string s; prerr_string ", "; prerr_int i | _, None -> prerr_string " , "); prerr_string "))" | Arith (op, xs) -> Printf.eprintf "( %s ) " (string_of_arithop op); print_ses xs | Rel (rel, xs) -> Printf.eprintf "( %s ) " (string_of_relop rel); print_ses xs | Diff (x, y) -> prerr_string "("; print_se x; prerr_string ")-("; print_pattern y; prerr_string ")" | _ -> () and print_pattern : pattern se -> unit = function | Top -> prerr_string "⊤" | Const c -> prerr_string (CL.Printpat.pretty_const c) | Var e -> prerr_string "X ("; print_tagged_expr e; prerr_string ")" | Ctor_pat (k, arr) -> prerr_string "Ctor ("; (match k with None -> prerr_string " " | Some s -> prerr_string s); prerr_string ", "; print_pattern_arr_with_separator arr ";"; prerr_string ")" | Loc ((i, name), p) -> prerr_string "("; prerr_int i; prerr_string ", "; (match p with | Some p -> print_pattern p | _ -> to_be_explained := LocSet.add (i, name) !to_be_explained); prerr_string ")" | _ -> () and print_ses (xs : value se list) = prerr_string "["; List.iter print_se xs; prerr_string "]" and print_se_list_with_separator l sep = let l' = ref l in prerr_string "["; while !l' <> [] do match !l' with | hd :: tl -> prerr_string "("; print_se hd; prerr_string ")"; if tl <> [] then prerr_string sep; l' := tl | _ -> assert false done; prerr_string "]" and print_pattern_arr_with_separator arr sep = let len = Array.length arr in let i = ref 0 in prerr_string "["; while !i < len do print_pattern arr.(!i); if !i < len - 1 then prerr_string sep; incr i done; prerr_string "]" and print_expr_list_with_separator l sep = let l' = ref l in prerr_string "["; while !l' <> [] do match !l' with | hd :: tl -> prerr_string "("; print_expr hd; prerr_string ")"; if tl <> [] then prerr_string sep; l' := tl | _ -> assert false done; prerr_string "]" and print_option_list_with_separator l sep = let l' = ref l in prerr_string "["; while !l' <> [] do match !l' with | Some hd :: tl -> prerr_string "("; print_se hd; prerr_string ")"; if tl <> [] then prerr_string sep; l' := tl | None :: tl -> if tl <> [] then prerr_string sep; l' := tl | _ -> assert false done; prerr_string "]" and print_arr_with_separator arr sep = let len = Array.length arr in let i = ref 0 in prerr_string "["; while !i < len do prerr_int (fst arr.(!i)); if !i < len - 1 then prerr_string sep; incr i done; prerr_string "]" let show_env_map ( env_map : globalenv ) = ; let show_se_with_separator set sep = SESet.iter (fun x -> prerr_string sep; print_se x; prerr_newline ()) set let show_pattern_with_separator set sep = GESet.iter (fun x -> prerr_string sep; print_pattern x; prerr_newline ()) set let show_var_se_tbl (var_to_se : var_se_tbl) = Hashtbl.iter (fun x se -> prerr_string "var_to_se :\n ident = "; prerr_string (CL.Ident.unique_name x); prerr_string "\n se = "; prerr_newline (); show_se_with_separator se "\t"; prerr_newline ()) var_to_se let show_mem (mem : (loc, SESet.t) Hashtbl.t) = Hashtbl.iter (fun (key, _) data -> if SESet.is_empty data then () else ( prerr_string "mem :\n"; prerr_int key; prerr_newline (); show_se_with_separator data "\t"; prerr_newline ())) mem let show_sc_tbl (tbl : (value se, SESet.t) Hashtbl.t) = Hashtbl.iter (fun key data -> if SESet.is_empty data then () else ( prerr_string "sc :\n"; print_se key; (match key with | Fld (_, _) -> prerr_string " <- " | _ -> prerr_string " = "); prerr_newline (); show_se_with_separator data "\t"; prerr_newline ())) tbl let show_grammar (g : (pattern se, GESet.t) Hashtbl.t) = Hashtbl.iter (fun key data -> if GESet.is_empty data then () else ( prerr_string "grammar :\n"; print_pattern key; prerr_string " = "; prerr_newline (); show_pattern_with_separator data "\t"; prerr_newline ())) g let show_abs_mem (a : (loc, GESet.t) Hashtbl.t) = Hashtbl.iter (fun (key, _) data -> if GESet.is_empty data then () else ( prerr_string "abs_mem :\n"; prerr_int key; prerr_string " = "; prerr_newline (); show_pattern_with_separator data "\t"; prerr_newline ())) a let show_exn_of_file (tbl : (string, value se list) Hashtbl.t) = Hashtbl.iter (fun key data -> prerr_string "exceptions in file "; prerr_string key; prerr_newline (); List.iter (function | Var x -> let set = try Hashtbl.find grammar (Var x) with _ -> GESet.empty in if GESet.is_empty set then () else ( prerr_string "\tfrom "; print_tagged_expr x; prerr_endline ":"; show_pattern_with_separator set "\t\t"; prerr_newline ()) | _ -> ()) data) tbl let show_closure_analysis tbl = prerr_endline "Closure analysis:"; Hashtbl.iter (fun key data -> let set = SESet.filter (fun x -> match x with | App_V (_, _) | Fn (_, _) | Prim _ -> true | _ -> false) data in if SESet.is_empty set then () else ( print_se key; prerr_newline (); show_se_with_separator set "\t"; prerr_newline ())) tbl let explain_abs_mem () = prerr_endline "where abstract locations contain:"; LocSet.iter (fun (i, name) -> let set = try Hashtbl.find abs_mem (i, name) with _ -> GESet.empty in prerr_string "\tlocation "; prerr_int i; prerr_newline (); show_pattern_with_separator set "\t\t"; prerr_newline ()) !to_be_explained; to_be_explained := LocSet.empty let print_sc_info () = show_mem mem; show_var_se_tbl var_to_se; show_sc_tbl sc let print_grammar () = show_abs_mem abs_mem; show_grammar grammar let print_exa () = Format.flush_str_formatter () |> ignore; show_exn_of_file exn_of_file; explain_abs_mem () let print_closure () = Format.flush_str_formatter () |> ignore; show_closure_analysis sc
ab15f0e05108f5d7c602c4a86882df78423c4aedf3b35fa875f84b0b37b3d6b3
ChrisKuklewicz/SafeSemaphore
SSem.hs
----------------------------------------------------------------------------- -- | -- Module : Control.Concurrent.STM.SSem Copyright : ( c ) , 2012 -- License : BSD-style -- -- Maintainer : -- Stability : experimental -- Portability : non-portable (concurrency) -- -- Very simple quantity semaphore. -- ----------------------------------------------------------------------------- module Control.Concurrent.STM.SSem(SSem, new, wait, signal, tryWait , waitN, signalN, tryWaitN , getValue) where import Control.Monad.STM(STM,retry) import Control.Concurrent.STM.TVar(newTVar,readTVar,writeTVar) import Control.Concurrent.STM.SSemInternals(SSem(SSem)) -- | Create a new semaphore with the given argument as the initially available quantity. This allows new semaphores to start with a negative , zero , or positive quantity . new :: Int -> STM SSem new = fmap SSem . newTVar -- | Try to take a unit of value from the semaphore. This succeeds when the current quantity is positive , and then reduces the quantity by one . Otherwise this will ' retry ' . This will never result in a negative quantity . If several threads are retying then which one succeeds next is -- undefined -- an unlucky thread might starve. wait :: SSem -> STM () wait = flip waitN 1 -- | Try to take the given value from the semaphore. This succeeds when the quantity is greater or -- equal to the given value, and then subtracts the given value from the quantity. Otherwise this -- will 'retry'. This will never result in a negative quantity. If several threads are retrying -- then which one succeeds next is undefined -- an unlucky thread might starve. waitN :: SSem -> Int -> STM () waitN (SSem s) i = do v <- readTVar s if v >= i then writeTVar s $! v-i else retry -- | Signal that single unit of the semaphore is available. This increases the available quantity -- by one. signal :: SSem -> STM () signal = flip signalN 1 -- | Signal that many units of the semaphore are available. This changes the available quantity by -- adding the passed size. signalN :: SSem -> Int -> STM () signalN (SSem s) i = do v <- readTVar s writeTVar s $! v+i -- | Non-retrying version of 'wait'. `tryWait s` is defined as `tryN s 1` tryWait :: SSem -> STM (Maybe Int) tryWait = flip tryWaitN 1 | Non - retrying version of waitN. It either takes the quantity from the semaphore like -- waitN and returns `Just value taken` or finds insufficient quantity to take and returns -- Nothing tryWaitN :: SSem -> Int -> STM (Maybe Int) tryWaitN (SSem s) i = do v <- readTVar s if v >= i then do writeTVar s $! v-i return (Just i) else return Nothing | Return the current quantity in the semaphore . This is potentially useful in a larger STM -- transaciton and less useful as `atomically getValueSem :: IO Int` due to race conditions. getValue :: SSem -> STM Int getValue (SSem s) = readTVar s
null
https://raw.githubusercontent.com/ChrisKuklewicz/SafeSemaphore/c05e7aaea6dfcf1713a0c8eb3214cb832c9356f3/src/Control/Concurrent/STM/SSem.hs
haskell
--------------------------------------------------------------------------- | Module : Control.Concurrent.STM.SSem License : BSD-style Maintainer : Stability : experimental Portability : non-portable (concurrency) Very simple quantity semaphore. --------------------------------------------------------------------------- | Create a new semaphore with the given argument as the initially available quantity. This | Try to take a unit of value from the semaphore. This succeeds when the current quantity is undefined -- an unlucky thread might starve. | Try to take the given value from the semaphore. This succeeds when the quantity is greater or equal to the given value, and then subtracts the given value from the quantity. Otherwise this will 'retry'. This will never result in a negative quantity. If several threads are retrying then which one succeeds next is undefined -- an unlucky thread might starve. | Signal that single unit of the semaphore is available. This increases the available quantity by one. | Signal that many units of the semaphore are available. This changes the available quantity by adding the passed size. | Non-retrying version of 'wait'. `tryWait s` is defined as `tryN s 1` waitN and returns `Just value taken` or finds insufficient quantity to take and returns Nothing transaciton and less useful as `atomically getValueSem :: IO Int` due to race conditions.
Copyright : ( c ) , 2012 module Control.Concurrent.STM.SSem(SSem, new, wait, signal, tryWait , waitN, signalN, tryWaitN , getValue) where import Control.Monad.STM(STM,retry) import Control.Concurrent.STM.TVar(newTVar,readTVar,writeTVar) import Control.Concurrent.STM.SSemInternals(SSem(SSem)) allows new semaphores to start with a negative , zero , or positive quantity . new :: Int -> STM SSem new = fmap SSem . newTVar positive , and then reduces the quantity by one . Otherwise this will ' retry ' . This will never result in a negative quantity . If several threads are retying then which one succeeds next is wait :: SSem -> STM () wait = flip waitN 1 waitN :: SSem -> Int -> STM () waitN (SSem s) i = do v <- readTVar s if v >= i then writeTVar s $! v-i else retry signal :: SSem -> STM () signal = flip signalN 1 signalN :: SSem -> Int -> STM () signalN (SSem s) i = do v <- readTVar s writeTVar s $! v+i tryWait :: SSem -> STM (Maybe Int) tryWait = flip tryWaitN 1 | Non - retrying version of waitN. It either takes the quantity from the semaphore like tryWaitN :: SSem -> Int -> STM (Maybe Int) tryWaitN (SSem s) i = do v <- readTVar s if v >= i then do writeTVar s $! v-i return (Just i) else return Nothing | Return the current quantity in the semaphore . This is potentially useful in a larger STM getValue :: SSem -> STM Int getValue (SSem s) = readTVar s
f3e4f1e6b9047a0e37a59a70e0673ad8231e528bdfcf324296879c008dec2f8b
unclebob/spacewar
direction_selector.cljc
(ns spacewar.ui.widgets.direction-selector (:require [quil.core :as q #?@(:cljs [:include-macros true])] [spacewar.ui.protocols :as p] [spacewar.geometry :as geo] [spacewar.ui.config :as uic] [spacewar.vector :as vector])) (defn degree-tick [radius angle] (let [tick-length (if (zero? (rem angle 30)) 10 5) tick-radius (- radius tick-length) radians (geo/->radians angle) sin-r (Math/sin radians) cos-r (Math/cos radians)] (map #(geo/round %) [(* sin-r radius) (* cos-r radius) (* sin-r tick-radius) (* cos-r tick-radius)]))) (defn draw-bezel-ring [[cx cy radius] ring-color fill-color] (apply q/fill fill-color) (q/stroke-weight 2) (apply q/stroke ring-color) (q/ellipse-mode :radius) (q/ellipse cx cy radius radius)) (defn draw-ticks [[x y radius]] (apply q/stroke uic/black) (doseq [angle-tenth (range 36)] (q/with-translation [x y] (apply q/line (degree-tick radius (* 10 angle-tenth)))))) (defn draw-labels [[x y _] radius] (doseq [angle-thirtieth (range 12)] (let [angle-tenth (* 3 angle-thirtieth) angle (* 10 angle-tenth) radians (geo/->radians angle) [label-x label-y] (vector/from-angular radius radians)] (q/with-translation [x y] (apply q/fill uic/black) (q/text-align :center :center) (q/text-font (:lcars-small (q/state :fonts)) 12) (q/text (str angle-tenth) label-x label-y))))) (defn draw-pointer [x y length direction color] (let [radians (geo/->radians direction) [tip-x tip-y] (vector/from-angular length radians) base-width (geo/->radians 10) base-offset 15 [xb1 yb1] (vector/from-angular base-offset (- radians base-width)) [xb2 yb2] (vector/from-angular base-offset (+ radians base-width))] (q/no-stroke) (apply q/fill color) (q/with-translation [x y] (q/triangle tip-x tip-y xb1 yb1 xb2 yb2) ))) (defn draw-direction-text [text cx cy dial-color text-color] (q/rect-mode :center) (q/no-stroke) (apply q/fill dial-color) (q/rect cx cy 20 20) (apply q/fill text-color) (q/text-align :center :center) (q/text-font (:lcars-small (q/state :fonts)) 12) (q/text text cx cy)) (defn- ->circle [x y diameter] (let [radius (/ diameter 2) center-x (+ x radius) center-y (+ y radius)] [center-x center-y radius])) (deftype direction-selector [state] p/Drawable (get-state [_] state) (clone [_ clone-state] (direction-selector. clone-state)) (draw [_] (let [{:keys [x y diameter direction color mouse-in left-down mouse-pos pointer2]} state circle (->circle x y diameter) [cx cy radius] circle label-radius (- radius 18) pointer-length (- radius 25) ring-color (if mouse-in uic/white color) mouse-angle (if left-down (geo/angle-degrees [cx cy] mouse-pos) 0) direction-text (str (geo/round (if left-down mouse-angle direction))) text-color (if left-down uic/grey uic/black)] (draw-bezel-ring circle ring-color color) (when mouse-in (draw-ticks circle) (draw-labels circle label-radius)) (when pointer2 (draw-pointer cx cy pointer-length pointer2 uic/light-grey)) (draw-pointer cx cy pointer-length direction uic/black) (when left-down (draw-pointer cx cy pointer-length mouse-angle uic/grey)) (draw-direction-text direction-text cx cy color text-color))) (setup [_] (direction-selector. (assoc state :mouse-pos [0 0]))) (update-state [_ _] (let [{:keys [x y diameter]} state last-left-down (:left-down state) [cx cy _ :as circle] (->circle x y diameter) mouse-pos [(q/mouse-x) (q/mouse-y)] mouse-in (geo/inside-circle circle mouse-pos) left-down (and mouse-in (q/mouse-pressed?) (= :left (q/mouse-button))) left-up (and (not left-down) last-left-down mouse-in) event (if left-up (assoc (:left-up-event state) :angle (geo/round (geo/angle-degrees [cx cy] mouse-pos))) nil) new-state (assoc state :mouse-pos mouse-pos :mouse-in mouse-in :left-down left-down)] (p/pack-update (direction-selector. new-state) event))))
null
https://raw.githubusercontent.com/unclebob/spacewar/71c3195b050c4fdb7e643f53556ab580d70f27ba/src/spacewar/ui/widgets/direction_selector.cljc
clojure
(ns spacewar.ui.widgets.direction-selector (:require [quil.core :as q #?@(:cljs [:include-macros true])] [spacewar.ui.protocols :as p] [spacewar.geometry :as geo] [spacewar.ui.config :as uic] [spacewar.vector :as vector])) (defn degree-tick [radius angle] (let [tick-length (if (zero? (rem angle 30)) 10 5) tick-radius (- radius tick-length) radians (geo/->radians angle) sin-r (Math/sin radians) cos-r (Math/cos radians)] (map #(geo/round %) [(* sin-r radius) (* cos-r radius) (* sin-r tick-radius) (* cos-r tick-radius)]))) (defn draw-bezel-ring [[cx cy radius] ring-color fill-color] (apply q/fill fill-color) (q/stroke-weight 2) (apply q/stroke ring-color) (q/ellipse-mode :radius) (q/ellipse cx cy radius radius)) (defn draw-ticks [[x y radius]] (apply q/stroke uic/black) (doseq [angle-tenth (range 36)] (q/with-translation [x y] (apply q/line (degree-tick radius (* 10 angle-tenth)))))) (defn draw-labels [[x y _] radius] (doseq [angle-thirtieth (range 12)] (let [angle-tenth (* 3 angle-thirtieth) angle (* 10 angle-tenth) radians (geo/->radians angle) [label-x label-y] (vector/from-angular radius radians)] (q/with-translation [x y] (apply q/fill uic/black) (q/text-align :center :center) (q/text-font (:lcars-small (q/state :fonts)) 12) (q/text (str angle-tenth) label-x label-y))))) (defn draw-pointer [x y length direction color] (let [radians (geo/->radians direction) [tip-x tip-y] (vector/from-angular length radians) base-width (geo/->radians 10) base-offset 15 [xb1 yb1] (vector/from-angular base-offset (- radians base-width)) [xb2 yb2] (vector/from-angular base-offset (+ radians base-width))] (q/no-stroke) (apply q/fill color) (q/with-translation [x y] (q/triangle tip-x tip-y xb1 yb1 xb2 yb2) ))) (defn draw-direction-text [text cx cy dial-color text-color] (q/rect-mode :center) (q/no-stroke) (apply q/fill dial-color) (q/rect cx cy 20 20) (apply q/fill text-color) (q/text-align :center :center) (q/text-font (:lcars-small (q/state :fonts)) 12) (q/text text cx cy)) (defn- ->circle [x y diameter] (let [radius (/ diameter 2) center-x (+ x radius) center-y (+ y radius)] [center-x center-y radius])) (deftype direction-selector [state] p/Drawable (get-state [_] state) (clone [_ clone-state] (direction-selector. clone-state)) (draw [_] (let [{:keys [x y diameter direction color mouse-in left-down mouse-pos pointer2]} state circle (->circle x y diameter) [cx cy radius] circle label-radius (- radius 18) pointer-length (- radius 25) ring-color (if mouse-in uic/white color) mouse-angle (if left-down (geo/angle-degrees [cx cy] mouse-pos) 0) direction-text (str (geo/round (if left-down mouse-angle direction))) text-color (if left-down uic/grey uic/black)] (draw-bezel-ring circle ring-color color) (when mouse-in (draw-ticks circle) (draw-labels circle label-radius)) (when pointer2 (draw-pointer cx cy pointer-length pointer2 uic/light-grey)) (draw-pointer cx cy pointer-length direction uic/black) (when left-down (draw-pointer cx cy pointer-length mouse-angle uic/grey)) (draw-direction-text direction-text cx cy color text-color))) (setup [_] (direction-selector. (assoc state :mouse-pos [0 0]))) (update-state [_ _] (let [{:keys [x y diameter]} state last-left-down (:left-down state) [cx cy _ :as circle] (->circle x y diameter) mouse-pos [(q/mouse-x) (q/mouse-y)] mouse-in (geo/inside-circle circle mouse-pos) left-down (and mouse-in (q/mouse-pressed?) (= :left (q/mouse-button))) left-up (and (not left-down) last-left-down mouse-in) event (if left-up (assoc (:left-up-event state) :angle (geo/round (geo/angle-degrees [cx cy] mouse-pos))) nil) new-state (assoc state :mouse-pos mouse-pos :mouse-in mouse-in :left-down left-down)] (p/pack-update (direction-selector. new-state) event))))
55406f6b1b8f5ec4e02c6ea7a26eec71f9c340a6f2f5d480cb2611ef2f9cecf6
whalliburton/language
packages.lisp
packages.lisp (defpackage language (:use common-lisp drakma anaphora split-sequence iterate typeset) (:import-from alexandria when-let with-input-from-file with-output-to-file shuffle) (:import-from cl-fad list-directory) (:import-from json decode-json-from-string) (:import-from sb-ext run-program process-status octets-to-string string-to-octets) (:import-from flexi-streams with-output-to-sequence) (:import-from dict with-dict-client define) (:export quiz-keys quiz-typing translate quiz done))
null
https://raw.githubusercontent.com/whalliburton/language/d16ddf05c2b7e067f6f9ce74416c73f0b64b63c4/packages.lisp
lisp
packages.lisp (defpackage language (:use common-lisp drakma anaphora split-sequence iterate typeset) (:import-from alexandria when-let with-input-from-file with-output-to-file shuffle) (:import-from cl-fad list-directory) (:import-from json decode-json-from-string) (:import-from sb-ext run-program process-status octets-to-string string-to-octets) (:import-from flexi-streams with-output-to-sequence) (:import-from dict with-dict-client define) (:export quiz-keys quiz-typing translate quiz done))
cc53b280b149aad6ec4aa833ee94ff607b25ec7b6bdfcbe22f6139673fd908a4
janestreet/merlin-jst
mpipeline.ml
open Std let {Logger. log} = Logger.for_section "Pipeline" let time_shift = ref 0.0 let timed_lazy r x = lazy ( let start = Misc.time_spent () in let time_shift0 = !time_shift in let update () = let delta = Misc.time_spent () -. start in let shift = !time_shift -. time_shift0 in time_shift := time_shift0 +. delta; r := !r +. delta -. shift; in match Lazy.force x with | x -> update (); x | exception exn -> update (); Std.reraise exn ) module Cache = struct let cache = ref [] (* Values from configuration that are used as a key for the cache. These values should: - allow to maximize reuse; associating a single typechecker instance to a filename and directory is natural, but keying also based on verbosity makes no sense - prevent reuse in different environments (if there is a change in loadpath, a new typechecker should be produced). It would be better to guarantee that the typechecker was well-behaved when the loadpath changes (so that we can reusing the same instance, and let the typechecker figure which part of its internal state should be invalidated). However we already had many bug related to that. There are subtle changes in the type checker behavior across the different versions of OCaml. It is simpler to create new instances upfront. *) let key config = Mconfig.( config.query.filename, config.query.directory, config.ocaml, {config.merlin with log_file = None; log_sections = []} ) let get config = let title = "pop_cache" in let key = key config in match List.assoc key !cache with | state -> cache := (key, state) :: List.remove_assoc key !cache; log ~title "found entry for this configuration"; state | exception Not_found -> log ~title "nothing cached for this configuration"; let state = Mocaml.new_state () in cache := (key, state) :: List.take_n 5 !cache; state end module Typer = struct type t = { errors : exn list lazy_t; result : Mtyper.result; } end module Ppx = struct type t = { config : Mconfig.t; errors : exn list; parsetree : Mreader.parsetree; } end type t = { config : Mconfig.t; state : Mocaml.typer_state; raw_source : Msource.t; source : (Msource.t * Mreader.parsetree option) lazy_t; reader : (Mreader.result * Mconfig.t) lazy_t; ppx : Ppx.t lazy_t; typer : Typer.t lazy_t; pp_time : float ref; reader_time : float ref; ppx_time : float ref; typer_time : float ref; error_time : float ref; } let raw_source t = t.raw_source let input_config t = t.config let input_source t = fst (Lazy.force t.source) let with_pipeline t f = Mocaml.with_state t.state @@ fun () -> Mreader.with_ambient_reader t.config (input_source t) f let get_lexing_pos t pos = Msource.get_lexing_pos (input_source t) ~filename:(Mconfig.filename t.config) pos let reader t = Lazy.force t.reader let ppx t = Lazy.force t.ppx let typer t = Lazy.force t.typer let reader_config t = (snd (reader t)) let reader_parsetree t = (fst (reader t)).Mreader.parsetree let reader_comments t = (fst (reader t)).Mreader.comments let reader_lexer_keywords t = (fst (reader t)).Mreader.lexer_keywords let reader_lexer_errors t = (fst (reader t)).Mreader.lexer_errors let reader_parser_errors t = (fst (reader t)).Mreader.parser_errors let reader_no_labels_for_completion t = (fst (reader t)).Mreader.no_labels_for_completion let ppx_parsetree t = (ppx t).Ppx.parsetree let ppx_errors t = (ppx t).Ppx.errors let final_config t = (ppx t).Ppx.config let typer_result t = (typer t).Typer.result let typer_errors t = Lazy.force (typer t).Typer.errors let process ?state ?(pp_time=ref 0.0) ?(reader_time=ref 0.0) ?(ppx_time=ref 0.0) ?(typer_time=ref 0.0) ?(error_time=ref 0.0) ?for_completion config raw_source = let state = match state with | None -> Cache.get config | Some state -> state in let source = timed_lazy pp_time (lazy ( match Mconfig.(config.ocaml.pp) with | None -> raw_source, None | Some { workdir; workval } -> let source = Msource.text raw_source in match Pparse.apply_pp ~workdir ~filename:Mconfig.(config.query.filename) ~source ~pp:workval with | `Source source -> Msource.make source, None | (`Interface _ | `Implementation _) as ast -> raw_source, Some ast )) in let reader = timed_lazy reader_time (lazy ( let lazy source = source in let config = Mconfig.normalize config in Mocaml.setup_reader_config config; let result = Mreader.parse ?for_completion config source in result, config )) in let ppx = timed_lazy ppx_time (lazy ( let lazy ({Mreader.parsetree; _}, config) = reader in let caught = ref [] in Msupport.catch_errors Mconfig.(config.ocaml.warnings) caught @@ fun () -> let parsetree = Mppx.rewrite config parsetree in { Ppx. config; parsetree; errors = !caught } )) in let typer = timed_lazy typer_time (lazy ( let lazy { Ppx. config; parsetree; _ } = ppx in Mocaml.setup_typer_config config; let result = Mtyper.run config parsetree in let errors = timed_lazy error_time (lazy (Mtyper.get_errors result)) in { Typer. errors; result } )) in { config; state; raw_source; source; reader; ppx; typer; pp_time; reader_time; ppx_time; typer_time; error_time } let make config source = process (Mconfig.normalize config) source let for_completion position {config; state; raw_source; pp_time; reader_time; ppx_time; typer_time; error_time; _} = process config raw_source ~for_completion:position ~state ~pp_time ~reader_time ~ppx_time ~typer_time ~error_time let timing_information t = [ "pp" , !(t.pp_time); "reader" , !(t.reader_time); "ppx" , !(t.ppx_time); "typer" , !(t.typer_time); "error" , !(t.error_time); ]
null
https://raw.githubusercontent.com/janestreet/merlin-jst/980b574405617fa0dfb0b79a84a66536b46cd71b/src/kernel/mpipeline.ml
ocaml
Values from configuration that are used as a key for the cache. These values should: - allow to maximize reuse; associating a single typechecker instance to a filename and directory is natural, but keying also based on verbosity makes no sense - prevent reuse in different environments (if there is a change in loadpath, a new typechecker should be produced). It would be better to guarantee that the typechecker was well-behaved when the loadpath changes (so that we can reusing the same instance, and let the typechecker figure which part of its internal state should be invalidated). However we already had many bug related to that. There are subtle changes in the type checker behavior across the different versions of OCaml. It is simpler to create new instances upfront.
open Std let {Logger. log} = Logger.for_section "Pipeline" let time_shift = ref 0.0 let timed_lazy r x = lazy ( let start = Misc.time_spent () in let time_shift0 = !time_shift in let update () = let delta = Misc.time_spent () -. start in let shift = !time_shift -. time_shift0 in time_shift := time_shift0 +. delta; r := !r +. delta -. shift; in match Lazy.force x with | x -> update (); x | exception exn -> update (); Std.reraise exn ) module Cache = struct let cache = ref [] let key config = Mconfig.( config.query.filename, config.query.directory, config.ocaml, {config.merlin with log_file = None; log_sections = []} ) let get config = let title = "pop_cache" in let key = key config in match List.assoc key !cache with | state -> cache := (key, state) :: List.remove_assoc key !cache; log ~title "found entry for this configuration"; state | exception Not_found -> log ~title "nothing cached for this configuration"; let state = Mocaml.new_state () in cache := (key, state) :: List.take_n 5 !cache; state end module Typer = struct type t = { errors : exn list lazy_t; result : Mtyper.result; } end module Ppx = struct type t = { config : Mconfig.t; errors : exn list; parsetree : Mreader.parsetree; } end type t = { config : Mconfig.t; state : Mocaml.typer_state; raw_source : Msource.t; source : (Msource.t * Mreader.parsetree option) lazy_t; reader : (Mreader.result * Mconfig.t) lazy_t; ppx : Ppx.t lazy_t; typer : Typer.t lazy_t; pp_time : float ref; reader_time : float ref; ppx_time : float ref; typer_time : float ref; error_time : float ref; } let raw_source t = t.raw_source let input_config t = t.config let input_source t = fst (Lazy.force t.source) let with_pipeline t f = Mocaml.with_state t.state @@ fun () -> Mreader.with_ambient_reader t.config (input_source t) f let get_lexing_pos t pos = Msource.get_lexing_pos (input_source t) ~filename:(Mconfig.filename t.config) pos let reader t = Lazy.force t.reader let ppx t = Lazy.force t.ppx let typer t = Lazy.force t.typer let reader_config t = (snd (reader t)) let reader_parsetree t = (fst (reader t)).Mreader.parsetree let reader_comments t = (fst (reader t)).Mreader.comments let reader_lexer_keywords t = (fst (reader t)).Mreader.lexer_keywords let reader_lexer_errors t = (fst (reader t)).Mreader.lexer_errors let reader_parser_errors t = (fst (reader t)).Mreader.parser_errors let reader_no_labels_for_completion t = (fst (reader t)).Mreader.no_labels_for_completion let ppx_parsetree t = (ppx t).Ppx.parsetree let ppx_errors t = (ppx t).Ppx.errors let final_config t = (ppx t).Ppx.config let typer_result t = (typer t).Typer.result let typer_errors t = Lazy.force (typer t).Typer.errors let process ?state ?(pp_time=ref 0.0) ?(reader_time=ref 0.0) ?(ppx_time=ref 0.0) ?(typer_time=ref 0.0) ?(error_time=ref 0.0) ?for_completion config raw_source = let state = match state with | None -> Cache.get config | Some state -> state in let source = timed_lazy pp_time (lazy ( match Mconfig.(config.ocaml.pp) with | None -> raw_source, None | Some { workdir; workval } -> let source = Msource.text raw_source in match Pparse.apply_pp ~workdir ~filename:Mconfig.(config.query.filename) ~source ~pp:workval with | `Source source -> Msource.make source, None | (`Interface _ | `Implementation _) as ast -> raw_source, Some ast )) in let reader = timed_lazy reader_time (lazy ( let lazy source = source in let config = Mconfig.normalize config in Mocaml.setup_reader_config config; let result = Mreader.parse ?for_completion config source in result, config )) in let ppx = timed_lazy ppx_time (lazy ( let lazy ({Mreader.parsetree; _}, config) = reader in let caught = ref [] in Msupport.catch_errors Mconfig.(config.ocaml.warnings) caught @@ fun () -> let parsetree = Mppx.rewrite config parsetree in { Ppx. config; parsetree; errors = !caught } )) in let typer = timed_lazy typer_time (lazy ( let lazy { Ppx. config; parsetree; _ } = ppx in Mocaml.setup_typer_config config; let result = Mtyper.run config parsetree in let errors = timed_lazy error_time (lazy (Mtyper.get_errors result)) in { Typer. errors; result } )) in { config; state; raw_source; source; reader; ppx; typer; pp_time; reader_time; ppx_time; typer_time; error_time } let make config source = process (Mconfig.normalize config) source let for_completion position {config; state; raw_source; pp_time; reader_time; ppx_time; typer_time; error_time; _} = process config raw_source ~for_completion:position ~state ~pp_time ~reader_time ~ppx_time ~typer_time ~error_time let timing_information t = [ "pp" , !(t.pp_time); "reader" , !(t.reader_time); "ppx" , !(t.ppx_time); "typer" , !(t.typer_time); "error" , !(t.error_time); ]
1fbc378c32d28cdf2231a06e54df544164f4ac48ff2f3e9f9fc2f3df7e8f5e14
snoyberg/conduit
Unqualified.hs
# OPTIONS_HADDOCK not - home # # LANGUAGE CPP # # LANGUAGE FlexibleContexts # {-# LANGUAGE RankNTypes #-} {-# LANGUAGE GADTs #-} # LANGUAGE MultiParamTypeClasses # # LANGUAGE NoImplicitPrelude # # LANGUAGE NoMonomorphismRestriction # module Data.Conduit.Combinators.Unqualified ( -- ** Producers -- *** Pure CC.yieldMany , unfoldC , enumFromToC , iterateC , repeatC , replicateC , CC.sourceLazy * * * , repeatMC , repeatWhileMC , replicateMC -- *** I\/O , CC.sourceFile , CC.sourceFileBS , CC.sourceHandle , CC.sourceHandleUnsafe , CC.sourceIOHandle , stdinC , CC.withSourceFile -- *** Filesystem , CC.sourceDirectory , CC.sourceDirectoryDeep -- ** Consumers -- *** Pure , dropC , dropCE , dropWhileC , dropWhileCE , foldC , foldCE , foldlC , foldlCE , foldMapC , foldMapCE , allC , allCE , anyC , anyCE , andC , andCE , orC , orCE , asumC , elemC , elemCE , notElemC , notElemCE , CC.sinkLazy , CC.sinkList , CC.sinkVector , CC.sinkVectorN , CC.sinkLazyBuilder , CC.sinkNull , CC.awaitNonNull , headC , headDefC , headCE , peekC , peekCE , lastC , lastDefC , lastCE , lengthC , lengthCE , lengthIfC , lengthIfCE , maximumC , maximumCE , minimumC , minimumCE , nullC , nullCE , sumC , sumCE , productC , productCE , findC * * * , mapM_C , mapM_CE , foldMC , foldMCE , foldMapMC , foldMapMCE -- *** I\/O , CC.sinkFile , CC.sinkFileCautious , CC.sinkTempFile , CC.sinkSystemTempFile , CC.sinkFileBS , CC.sinkHandle , CC.sinkIOHandle , printC , stdoutC , stderrC , CC.withSinkFile , CC.withSinkFileBuilder , CC.withSinkFileCautious , CC.sinkHandleBuilder , CC.sinkHandleFlush -- ** Transformers -- *** Pure , mapC , mapCE , omapCE , concatMapC , concatMapCE , takeC , takeCE , takeWhileC , takeWhileCE , takeExactlyC , takeExactlyCE , concatC , filterC , filterCE , mapWhileC , conduitVector , scanlC , mapAccumWhileC , concatMapAccumC , intersperseC , slidingWindowC , chunksOfCE , chunksOfExactlyCE * * * , mapMC , mapMCE , omapMCE , concatMapMC , filterMC , filterMCE , iterMC , scanlMC , mapAccumWhileMC , concatMapAccumMC -- *** Textual , encodeUtf8C , decodeUtf8C , decodeUtf8LenientC , lineC , lineAsciiC , unlinesC , unlinesAsciiC , linesUnboundedC , linesUnboundedAsciiC -- ** Builders , CC.builderToByteString , CC.unsafeBuilderToByteString , CC.builderToByteStringWith , CC.builderToByteStringFlush , CC.builderToByteStringWithFlush , CC.BufferAllocStrategy , CC.allNewBuffersStrategy , CC.reuseBufferStrategy -- ** Special , vectorBuilderC , CC.mapAccumS , CC.peekForever , CC.peekForeverE ) where -- BEGIN IMPORTS import qualified Data.Conduit.Combinators as CC -- BEGIN IMPORTS import qualified Data.Traversable import Control.Applicative (Alternative) import Control.Monad.IO.Class (MonadIO (..)) import Control.Monad.Primitive (PrimMonad, PrimState) import Control.Monad.Trans.Resource (MonadThrow) import Data.Conduit import Data.Monoid (Monoid (..)) import Data.MonoTraversable import qualified Data.Sequences as Seq import qualified Data.Vector.Generic as V import Prelude (Bool (..), Eq (..), Int, Maybe (..), Monad (..), Num (..), Ord (..), Functor (..), Either (..), Enum, Show, Char) import Data.Word (Word8) import Data.ByteString (ByteString) import Data.Text (Text) import qualified Data.Sequences as DTE -- END IMPORTS -- | Generate a producer from a seed value. -- -- @since 1.3.0 unfoldC :: Monad m => (b -> Maybe (a, b)) -> b -> ConduitT i a m () unfoldC = CC.unfold # INLINE unfoldC # -- | Enumerate from a value to a final value, inclusive, via 'succ'. -- This is generally more efficient than using @Prelude@\ 's @enumFromTo@ and -- combining with @sourceList@ since this avoids any intermediate data -- structures. -- -- @since 1.3.0 enumFromToC :: (Monad m, Enum a, Ord a) => a -> a -> ConduitT i a m () enumFromToC = CC.enumFromTo # INLINE enumFromToC # -- | Produces an infinite stream of repeated applications of f to x. -- -- @since 1.3.0 iterateC :: Monad m => (a -> a) -> a -> ConduitT i a m () iterateC = CC.iterate # INLINE iterateC # -- | Produce an infinite stream consisting entirely of the given value. -- -- @since 1.3.0 repeatC :: Monad m => a -> ConduitT i a m () repeatC = CC.repeat # INLINE repeatC # -- | Produce a finite stream consisting of n copies of the given value. -- -- @since 1.3.0 replicateC :: Monad m => Int -> a -> ConduitT i a m () replicateC = CC.replicate # INLINE replicateC # -- | Repeatedly run the given action and yield all values it produces. -- -- @since 1.3.0 repeatMC :: Monad m => m a -> ConduitT i a m () repeatMC = CC.repeatM # INLINE repeatMC # -- | Repeatedly run the given action and yield all values it produces, until the provided predicate returns -- -- @since 1.3.0 repeatWhileMC :: Monad m => m a -> (a -> Bool) -> ConduitT i a m () repeatWhileMC = CC.repeatWhileM # INLINE repeatWhileMC # -- | Perform the given action n times, yielding each result. -- -- @since 1.3.0 replicateMC :: Monad m => Int -> m a -> ConduitT i a m () replicateMC = CC.replicateM # INLINE replicateMC # | @sourceHandle@ applied to @stdin@. -- -- @since 1.3.0 stdinC :: MonadIO m => ConduitT i ByteString m () stdinC = CC.stdin # INLINE stdinC # -- | Ignore a certain number of values in the stream. -- -- Note: since this function doesn't produce anything, you probably want to -- use it with ('>>') instead of directly plugging it into a pipeline: -- > > > runConduit $ yieldMany [ 1 .. 5 ] .| dropC 2 .| sinkList -- [] > > > runConduit $ yieldMany [ 1 .. 5 ] .| ( dropC 2 > > sinkList ) [ 3,4,5 ] -- -- @since 1.3.0 dropC :: Monad m => Int -> ConduitT a o m () dropC = CC.drop # INLINE dropC # -- | Drop a certain number of elements from a chunked stream. -- -- Note: you likely want to use it with monadic composition. See the docs -- for 'dropC'. -- -- @since 1.3.0 dropCE :: (Monad m, Seq.IsSequence seq) => Seq.Index seq -> ConduitT seq o m () dropCE = CC.dropE # INLINE dropCE # -- | Drop all values which match the given predicate. -- -- Note: you likely want to use it with monadic composition. See the docs -- for 'dropC'. -- -- @since 1.3.0 dropWhileC :: Monad m => (a -> Bool) -> ConduitT a o m () dropWhileC = CC.dropWhile # INLINE dropWhileC # -- | Drop all elements in the chunked stream which match the given predicate. -- -- Note: you likely want to use it with monadic composition. See the docs -- for 'dropC'. -- -- @since 1.3.0 dropWhileCE :: (Monad m, Seq.IsSequence seq) => (Element seq -> Bool) -> ConduitT seq o m () dropWhileCE = CC.dropWhileE # INLINE dropWhileCE # | combine all values in the stream . -- -- @since 1.3.0 foldC :: (Monad m, Monoid a) => ConduitT a o m a foldC = CC.fold # INLINE foldC # | combine all elements in the chunked stream . -- -- @since 1.3.0 foldCE :: (Monad m, MonoFoldable mono, Monoid (Element mono)) => ConduitT mono o m (Element mono) foldCE = CC.foldE # INLINE foldCE # -- | A strict left fold. -- -- @since 1.3.0 foldlC :: Monad m => (a -> b -> a) -> a -> ConduitT b o m a foldlC = CC.foldl # INLINE foldlC # -- | A strict left fold on a chunked stream. -- -- @since 1.3.0 foldlCE :: (Monad m, MonoFoldable mono) => (a -> Element mono -> a) -> a -> ConduitT mono o m a foldlCE = CC.foldlE # INLINE foldlCE # -- | Apply the provided mapping function and monoidal combine all values. -- -- @since 1.3.0 foldMapC :: (Monad m, Monoid b) => (a -> b) -> ConduitT a o m b foldMapC = CC.foldMap # INLINE foldMapC # -- | Apply the provided mapping function and monoidal combine all elements of the chunked stream. -- -- @since 1.3.0 foldMapCE :: (Monad m, MonoFoldable mono, Monoid w) => (Element mono -> w) -> ConduitT mono o m w foldMapCE = CC.foldMapE # INLINE foldMapCE # -- | Check that all values in the stream return True. -- Subject to shortcut logic : at the first False , consumption of the stream -- will stop. -- -- @since 1.3.0 allC :: Monad m => (a -> Bool) -> ConduitT a o m Bool allC = CC.all # INLINE allC # -- | Check that all elements in the chunked stream return True. -- Subject to shortcut logic : at the first False , consumption of the stream -- will stop. -- -- @since 1.3.0 allCE :: (Monad m, MonoFoldable mono) => (Element mono -> Bool) -> ConduitT mono o m Bool allCE = CC.allE # INLINE allCE # | Check that at least one value in the stream returns True . -- Subject to shortcut logic : at the first True , consumption of the stream -- will stop. -- -- @since 1.3.0 anyC :: Monad m => (a -> Bool) -> ConduitT a o m Bool anyC = CC.any # INLINE anyC # | Check that at least one element in the chunked stream returns True . -- Subject to shortcut logic : at the first True , consumption of the stream -- will stop. -- -- @since 1.3.0 anyCE :: (Monad m, MonoFoldable mono) => (Element mono -> Bool) -> ConduitT mono o m Bool anyCE = CC.anyE # INLINE anyCE # -- | Are all values in the stream True? -- Consumption stops once the first False is encountered . -- -- @since 1.3.0 andC :: Monad m => ConduitT Bool o m Bool andC = CC.and # INLINE andC # -- | Are all elements in the chunked stream True? -- Consumption stops once the first False is encountered . -- -- @since 1.3.0 andCE :: (Monad m, MonoFoldable mono, Element mono ~ Bool) => ConduitT mono o m Bool andCE = CC.andE # INLINE andCE # -- | Are any values in the stream True? -- Consumption stops once the first True is encountered . -- -- @since 1.3.0 orC :: Monad m => ConduitT Bool o m Bool orC = CC.or # INLINE orC # -- | Are any elements in the chunked stream True? -- Consumption stops once the first True is encountered . -- -- @since 1.3.0 orCE :: (Monad m, MonoFoldable mono, Element mono ~ Bool) => ConduitT mono o m Bool orCE = CC.orE # INLINE orCE # | ' Alternative'ly combine all values in the stream . -- -- @since 1.3.0 asumC :: (Monad m, Alternative f) => ConduitT (f a) o m (f a) asumC = CC.asum -- | Are any values in the stream equal to the given value? -- -- Stops consuming as soon as a match is found. -- -- @since 1.3.0 elemC :: (Monad m, Eq a) => a -> ConduitT a o m Bool elemC = CC.elem # INLINE elemC # -- | Are any elements in the chunked stream equal to the given element? -- -- Stops consuming as soon as a match is found. -- -- @since 1.3.0 #if MIN_VERSION_mono_traversable(1,0,0) elemCE :: (Monad m, Seq.IsSequence seq, Eq (Element seq)) #else elemCE :: (Monad m, Seq.EqSequence seq) #endif => Element seq -> ConduitT seq o m Bool elemCE = CC.elemE # INLINE elemCE # -- | Are no values in the stream equal to the given value? -- -- Stops consuming as soon as a match is found. -- -- @since 1.3.0 notElemC :: (Monad m, Eq a) => a -> ConduitT a o m Bool notElemC = CC.notElem # INLINE notElemC # -- | Are no elements in the chunked stream equal to the given element? -- -- Stops consuming as soon as a match is found. -- -- @since 1.3.0 #if MIN_VERSION_mono_traversable(1,0,0) notElemCE :: (Monad m, Seq.IsSequence seq, Eq (Element seq)) #else notElemCE :: (Monad m, Seq.EqSequence seq) #endif => Element seq -> ConduitT seq o m Bool notElemCE = CC.notElemE # INLINE notElemCE # -- | Take a single value from the stream, if available. -- -- @since 1.3.0 headC :: Monad m => ConduitT a o m (Maybe a) headC = CC.head -- | Same as 'headC', but returns a default value if none are available from the stream. -- -- @since 1.3.0 headDefC :: Monad m => a -> ConduitT a o m a headDefC = CC.headDef -- | Get the next element in the chunked stream. -- -- @since 1.3.0 headCE :: (Monad m, Seq.IsSequence seq) => ConduitT seq o m (Maybe (Element seq)) headCE = CC.headE # INLINE headCE # -- | View the next value in the stream without consuming it. -- -- @since 1.3.0 peekC :: Monad m => ConduitT a o m (Maybe a) peekC = CC.peek # INLINE peekC # -- | View the next element in the chunked stream without consuming it. -- -- @since 1.3.0 peekCE :: (Monad m, MonoFoldable mono) => ConduitT mono o m (Maybe (Element mono)) peekCE = CC.peekE # INLINE peekCE # -- | Retrieve the last value in the stream, if present. -- -- @since 1.3.0 lastC :: Monad m => ConduitT a o m (Maybe a) lastC = CC.last # INLINE lastC # -- | Same as 'lastC', but returns a default value if none are available from the stream. -- -- @since 1.3.0 lastDefC :: Monad m => a -> ConduitT a o m a lastDefC = CC.lastDef -- | Retrieve the last element in the chunked stream, if present. -- -- @since 1.3.0 lastCE :: (Monad m, Seq.IsSequence seq) => ConduitT seq o m (Maybe (Element seq)) lastCE = CC.lastE # INLINE lastCE # -- | Count how many values are in the stream. -- -- @since 1.3.0 lengthC :: (Monad m, Num len) => ConduitT a o m len lengthC = CC.length # INLINE lengthC # -- | Count how many elements are in the chunked stream. -- -- @since 1.3.0 lengthCE :: (Monad m, Num len, MonoFoldable mono) => ConduitT mono o m len lengthCE = CC.lengthE # INLINE lengthCE # -- | Count how many values in the stream pass the given predicate. -- -- @since 1.3.0 lengthIfC :: (Monad m, Num len) => (a -> Bool) -> ConduitT a o m len lengthIfC = CC.lengthIf # INLINE lengthIfC # -- | Count how many elements in the chunked stream pass the given predicate. -- -- @since 1.3.0 lengthIfCE :: (Monad m, Num len, MonoFoldable mono) => (Element mono -> Bool) -> ConduitT mono o m len lengthIfCE = CC.lengthIfE # INLINE lengthIfCE # -- | Get the largest value in the stream, if present. -- -- @since 1.3.0 maximumC :: (Monad m, Ord a) => ConduitT a o m (Maybe a) maximumC = CC.maximum # INLINE maximumC # -- | Get the largest element in the chunked stream, if present. -- -- @since 1.3.0 #if MIN_VERSION_mono_traversable(1,0,0) maximumCE :: (Monad m, Seq.IsSequence seq, Ord (Element seq)) => ConduitT seq o m (Maybe (Element seq)) #else maximumCE :: (Monad m, Seq.OrdSequence seq) => ConduitT seq o m (Maybe (Element seq)) #endif maximumCE = CC.maximumE # INLINE maximumCE # -- | Get the smallest value in the stream, if present. -- -- @since 1.3.0 minimumC :: (Monad m, Ord a) => ConduitT a o m (Maybe a) minimumC = CC.minimum # INLINE minimumC # -- | Get the smallest element in the chunked stream, if present. -- -- @since 1.3.0 #if MIN_VERSION_mono_traversable(1,0,0) minimumCE :: (Monad m, Seq.IsSequence seq, Ord (Element seq)) => ConduitT seq o m (Maybe (Element seq)) #else minimumCE :: (Monad m, Seq.OrdSequence seq) => ConduitT seq o m (Maybe (Element seq)) #endif minimumCE = CC.minimumE # INLINE minimumCE # -- | True if there are no values in the stream. -- -- This function does not modify the stream. -- -- @since 1.3.0 nullC :: Monad m => ConduitT a o m Bool nullC = CC.null # INLINE nullC # -- | True if there are no elements in the chunked stream. -- -- This function may remove empty leading chunks from the stream, but otherwise -- will not modify it. -- -- @since 1.3.0 nullCE :: (Monad m, MonoFoldable mono) => ConduitT mono o m Bool nullCE = CC.nullE # INLINE nullCE # -- | Get the sum of all values in the stream. -- -- @since 1.3.0 sumC :: (Monad m, Num a) => ConduitT a o m a sumC = CC.sum # INLINE sumC # -- | Get the sum of all elements in the chunked stream. -- -- @since 1.3.0 sumCE :: (Monad m, MonoFoldable mono, Num (Element mono)) => ConduitT mono o m (Element mono) sumCE = CC.sumE {-# INLINE sumCE #-} -- | Get the product of all values in the stream. -- -- @since 1.3.0 productC :: (Monad m, Num a) => ConduitT a o m a productC = CC.product # INLINE productC # -- | Get the product of all elements in the chunked stream. -- -- @since 1.3.0 productCE :: (Monad m, MonoFoldable mono, Num (Element mono)) => ConduitT mono o m (Element mono) productCE = CC.productE # INLINE productCE # | Find the first matching value . -- -- @since 1.3.0 findC :: Monad m => (a -> Bool) -> ConduitT a o m (Maybe a) findC = CC.find # INLINE findC # -- | Apply the action to all values in the stream. -- -- Note: if you want to /pass/ the values instead of /consuming/ them, use -- 'iterM' instead. -- -- @since 1.3.0 mapM_C :: Monad m => (a -> m ()) -> ConduitT a o m () mapM_C = CC.mapM_ # INLINE mapM_C # -- | Apply the action to all elements in the chunked stream. -- -- Note: the same caveat as with 'mapM_C' applies. If you don't want to -- consume the values, you can use 'iterM': -- -- > iterM (omapM_ f) -- -- @since 1.3.0 mapM_CE :: (Monad m, MonoFoldable mono) => (Element mono -> m ()) -> ConduitT mono o m () mapM_CE = CC.mapM_E # INLINE mapM_CE # -- | A monadic strict left fold. -- -- @since 1.3.0 foldMC :: Monad m => (a -> b -> m a) -> a -> ConduitT b o m a foldMC = CC.foldM # INLINE foldMC # -- | A monadic strict left fold on a chunked stream. -- -- @since 1.3.0 foldMCE :: (Monad m, MonoFoldable mono) => (a -> Element mono -> m a) -> a -> ConduitT mono o m a foldMCE = CC.foldME # INLINE foldMCE # -- | Apply the provided monadic mapping function and monoidal combine all values. -- -- @since 1.3.0 foldMapMC :: (Monad m, Monoid w) => (a -> m w) -> ConduitT a o m w foldMapMC = CC.foldMapM # INLINE foldMapMC # -- | Apply the provided monadic mapping function and monoidal combine all -- elements in the chunked stream. -- -- @since 1.3.0 foldMapMCE :: (Monad m, MonoFoldable mono, Monoid w) => (Element mono -> m w) -> ConduitT mono o m w foldMapMCE = CC.foldMapME # INLINE foldMapMCE # -- | Print all incoming values to stdout. -- -- @since 1.3.0 printC :: (Show a, MonadIO m) => ConduitT a o m () printC = CC.print # INLINE printC # -- | @sinkHandle@ applied to @stdout@. -- -- @since 1.3.0 stdoutC :: MonadIO m => ConduitT ByteString o m () stdoutC = CC.stdout # INLINE stdoutC # -- | @sinkHandle@ applied to @stderr@. -- -- @since 1.3.0 stderrC :: MonadIO m => ConduitT ByteString o m () stderrC = CC.stderr # INLINE stderrC # -- | Apply a transformation to all values in a stream. -- -- @since 1.3.0 mapC :: Monad m => (a -> b) -> ConduitT a b m () mapC = CC.map # INLINE mapC # -- | Apply a transformation to all elements in a chunked stream. -- -- @since 1.3.0 mapCE :: (Monad m, Functor f) => (a -> b) -> ConduitT (f a) (f b) m () mapCE = CC.mapE # INLINE mapCE # -- | Apply a monomorphic transformation to all elements in a chunked stream. -- Unlike @mapE@ , this will work on types like @ByteString@ and @Text@ which -- are @MonoFunctor@ but not @Functor@. -- -- @since 1.3.0 omapCE :: (Monad m, MonoFunctor mono) => (Element mono -> Element mono) -> ConduitT mono mono m () omapCE = CC.omapE # INLINE omapCE # -- | Apply the function to each value in the stream, resulting in a foldable -- value (e.g., a list). Then yield each of the individual values in that -- foldable value separately. -- Generalizes concatMap , mapMaybe , and mapFoldable . -- -- @since 1.3.0 concatMapC :: (Monad m, MonoFoldable mono) => (a -> mono) -> ConduitT a (Element mono) m () concatMapC = CC.concatMap # INLINE concatMapC # -- | Apply the function to each element in the chunked stream, resulting in a -- foldable value (e.g., a list). Then yield each of the individual values in -- that foldable value separately. -- Generalizes concatMap , mapMaybe , and mapFoldable . -- -- @since 1.3.0 concatMapCE :: (Monad m, MonoFoldable mono, Monoid w) => (Element mono -> w) -> ConduitT mono w m () concatMapCE = CC.concatMapE # INLINE concatMapCE # -- | Stream up to n number of values downstream. -- -- Note that, if downstream terminates early, not all values will be consumed. -- If you want to force /exactly/ the given number of values to be consumed, -- see 'takeExactly'. -- -- @since 1.3.0 takeC :: Monad m => Int -> ConduitT a a m () takeC = CC.take # INLINE takeC # -- | Stream up to n number of elements downstream in a chunked stream. -- -- Note that, if downstream terminates early, not all values will be consumed. -- If you want to force /exactly/ the given number of values to be consumed, -- see 'takeExactlyE'. -- -- @since 1.3.0 takeCE :: (Monad m, Seq.IsSequence seq) => Seq.Index seq -> ConduitT seq seq m () takeCE = CC.takeE # INLINE takeCE # -- | Stream all values downstream that match the given predicate. -- -- Same caveats regarding downstream termination apply as with 'take'. -- -- @since 1.3.0 takeWhileC :: Monad m => (a -> Bool) -> ConduitT a a m () takeWhileC = CC.takeWhile # INLINE takeWhileC # -- | Stream all elements downstream that match the given predicate in a chunked stream. -- -- Same caveats regarding downstream termination apply as with 'takeE'. -- -- @since 1.3.0 takeWhileCE :: (Monad m, Seq.IsSequence seq) => (Element seq -> Bool) -> ConduitT seq seq m () takeWhileCE = CC.takeWhileE {-# INLINE takeWhileCE #-} -- | Consume precisely the given number of values and feed them downstream. -- -- This function is in contrast to 'take', which will only consume up to the -- given number of values, and will terminate early if downstream terminates -- early. This function will discard any additional values in the stream if -- they are unconsumed. -- -- Note that this function takes a downstream @ConduitT@ as a parameter, as -- opposed to working with normal fusion. For more information, see -- <-flaw-pipes-conduit>, the section -- titled \"pipes and conduit: isolate\". -- -- @since 1.3.0 takeExactlyC :: Monad m => Int -> ConduitT a b m r -> ConduitT a b m r takeExactlyC = CC.takeExactly # INLINE takeExactlyC # -- | Same as 'takeExactly', but for chunked streams. -- -- @since 1.3.0 takeExactlyCE :: (Monad m, Seq.IsSequence a) => Seq.Index a -> ConduitT a b m r -> ConduitT a b m r takeExactlyCE = CC.takeExactlyE # INLINE takeExactlyCE # -- | Flatten out a stream by yielding the values contained in an incoming -- @MonoFoldable@ as individually yielded values. -- -- @since 1.3.0 concatC :: (Monad m, MonoFoldable mono) => ConduitT mono (Element mono) m () concatC = CC.concat # INLINE concatC # -- | Keep only values in the stream passing a given predicate. -- -- @since 1.3.0 filterC :: Monad m => (a -> Bool) -> ConduitT a a m () filterC = CC.filter # INLINE filterC # -- | Keep only elements in the chunked stream passing a given predicate. -- -- @since 1.3.0 filterCE :: (Seq.IsSequence seq, Monad m) => (Element seq -> Bool) -> ConduitT seq seq m () filterCE = CC.filterE # INLINE filterCE # -- | Map values as long as the result is @Just@. -- -- @since 1.3.0 mapWhileC :: Monad m => (a -> Maybe b) -> ConduitT a b m () mapWhileC = CC.mapWhile # INLINE mapWhileC # -- | Break up a stream of values into vectors of size n. The final vector may -- be smaller than n if the total number of values is not a strict multiple of -- n. No empty vectors will be yielded. -- -- @since 1.3.0 conduitVector :: (V.Vector v a, PrimMonad m) => Int -- ^ maximum allowed size -> ConduitT a (v a) m () conduitVector = CC.conduitVector # INLINE conduitVector # -- | Analog of 'Prelude.scanl' for lists. -- -- @since 1.3.0 scanlC :: Monad m => (a -> b -> a) -> a -> ConduitT b a m () scanlC = CC.scanl # INLINE scanlC # | ' ' with a break condition dependent on a strict accumulator . -- Equivalently, 'CL.mapAccum' as long as the result is @Right@. Instead of -- producing a leftover, the breaking input determines the resulting -- accumulator via @Left@. mapAccumWhileC :: Monad m => (a -> s -> Either s (s, b)) -> s -> ConduitT a b m s mapAccumWhileC = CC.mapAccumWhile # INLINE mapAccumWhileC # -- | 'concatMap' with an accumulator. -- -- @since 1.3.0 concatMapAccumC :: Monad m => (a -> accum -> (accum, [b])) -> accum -> ConduitT a b m () concatMapAccumC = CC.concatMapAccum # INLINE concatMapAccumC # | Insert the given value between each two values in the stream . -- -- @since 1.3.0 intersperseC :: Monad m => a -> ConduitT a a m () intersperseC = CC.intersperse # INLINE intersperseC # -- | Sliding window of values 1,2,3,4,5 with window size 2 gives [ 1,2],[2,3],[3,4],[4,5 ] -- -- Best used with structures that support O(1) snoc. -- -- @since 1.3.0 slidingWindowC :: (Monad m, Seq.IsSequence seq, Element seq ~ a) => Int -> ConduitT a seq m () slidingWindowC = CC.slidingWindow # INLINE slidingWindowC # -- | Split input into chunk of size 'chunkSize' -- -- The last element may be smaller than the 'chunkSize' (see also -- 'chunksOfExactlyE' which will not yield this last element) -- -- @since 1.3.0 chunksOfCE :: (Monad m, Seq.IsSequence seq) => Seq.Index seq -> ConduitT seq seq m () chunksOfCE = CC.chunksOfE # INLINE chunksOfCE # -- | Split input into chunk of size 'chunkSize' -- -- If the input does not split into chunks exactly, the remainder will be -- leftover (see also 'chunksOfE') -- -- @since 1.3.0 chunksOfExactlyCE :: (Monad m, Seq.IsSequence seq) => Seq.Index seq -> ConduitT seq seq m () chunksOfExactlyCE = CC.chunksOfExactlyE # INLINE chunksOfExactlyCE # -- | Apply a monadic transformation to all values in a stream. -- -- If you do not need the transformed values, and instead just want the monadic -- side-effects of running the action, see 'mapM_'. -- -- @since 1.3.0 mapMC :: Monad m => (a -> m b) -> ConduitT a b m () mapMC = CC.mapM # INLINE mapMC # -- | Apply a monadic transformation to all elements in a chunked stream. -- -- @since 1.3.0 mapMCE :: (Monad m, Data.Traversable.Traversable f) => (a -> m b) -> ConduitT (f a) (f b) m () mapMCE = CC.mapME # INLINE mapMCE # -- | Apply a monadic monomorphic transformation to all elements in a chunked stream. -- -- Unlike @mapME@, this will work on types like @ByteString@ and @Text@ which -- are @MonoFunctor@ but not @Functor@. -- -- @since 1.3.0 omapMCE :: (Monad m, MonoTraversable mono) => (Element mono -> m (Element mono)) -> ConduitT mono mono m () omapMCE = CC.omapME # INLINE omapMCE # -- | Apply the monadic function to each value in the stream, resulting in a -- foldable value (e.g., a list). Then yield each of the individual values in -- that foldable value separately. -- -- Generalizes concatMapM, mapMaybeM, and mapFoldableM. -- -- @since 1.3.0 concatMapMC :: (Monad m, MonoFoldable mono) => (a -> m mono) -> ConduitT a (Element mono) m () concatMapMC = CC.concatMapM # INLINE concatMapMC # -- | Keep only values in the stream passing a given monadic predicate. -- -- @since 1.3.0 filterMC :: Monad m => (a -> m Bool) -> ConduitT a a m () filterMC = CC.filterM # INLINE filterMC # -- | Keep only elements in the chunked stream passing a given monadic predicate. -- -- @since 1.3.0 filterMCE :: (Monad m, Seq.IsSequence seq) => (Element seq -> m Bool) -> ConduitT seq seq m () filterMCE = CC.filterME # INLINE filterMCE # -- | Apply a monadic action on all values in a stream. -- -- This @Conduit@ can be used to perform a monadic side-effect for every -- value, whilst passing the value through the @Conduit@ as-is. -- > iterM f = mapM ( \a - > f a > > = \ ( ) - > return a ) -- -- @since 1.3.0 iterMC :: Monad m => (a -> m ()) -> ConduitT a a m () iterMC = CC.iterM # INLINE iterMC # -- | Analog of 'Prelude.scanl' for lists, monadic. -- -- @since 1.3.0 scanlMC :: Monad m => (a -> b -> m a) -> a -> ConduitT b a m () scanlMC = CC.scanlM # INLINE scanlMC # | Monadic ` mapAccumWhileC ` . mapAccumWhileMC :: Monad m => (a -> s -> m (Either s (s, b))) -> s -> ConduitT a b m s mapAccumWhileMC = CC.mapAccumWhileM # INLINE mapAccumWhileMC # -- | 'concatMapM' with an accumulator. -- -- @since 1.3.0 concatMapAccumMC :: Monad m => (a -> accum -> m (accum, [b])) -> accum -> ConduitT a b m () concatMapAccumMC = CC.concatMapAccumM # INLINE concatMapAccumMC # -- | Encode a stream of text as UTF8. -- -- @since 1.3.0 encodeUtf8C :: (Monad m, DTE.Utf8 text binary) => ConduitT text binary m () encodeUtf8C = CC.encodeUtf8 # INLINE encodeUtf8C # -- | Decode a stream of binary data as UTF8. -- -- @since 1.3.0 decodeUtf8C :: MonadThrow m => ConduitT ByteString Text m () decodeUtf8C = CC.decodeUtf8 # INLINE decodeUtf8C # -- | Decode a stream of binary data as UTF8, replacing any invalid bytes with the Unicode replacement character . -- -- @since 1.3.0 decodeUtf8LenientC :: Monad m => ConduitT ByteString Text m () decodeUtf8LenientC = CC.decodeUtf8Lenient # INLINE decodeUtf8LenientC # -- | Stream in the entirety of a single line. -- -- Like @takeExactly@, this will consume the entirety of the line regardless of the behavior of the inner Conduit . -- -- @since 1.3.0 lineC :: (Monad m, Seq.IsSequence seq, Element seq ~ Char) => ConduitT seq o m r -> ConduitT seq o m r lineC = CC.line # INLINE lineC # -- | Same as 'line', but operates on ASCII/binary data. -- -- @since 1.3.0 lineAsciiC :: (Monad m, Seq.IsSequence seq, Element seq ~ Word8) => ConduitT seq o m r -> ConduitT seq o m r lineAsciiC = CC.lineAscii # INLINE lineAsciiC # -- | Insert a newline character after each incoming chunk of data. -- -- @since 1.3.0 unlinesC :: (Monad m, Seq.IsSequence seq, Element seq ~ Char) => ConduitT seq seq m () unlinesC = CC.unlines # INLINE unlinesC # -- | Same as 'unlines', but operates on ASCII/binary data. -- -- @since 1.3.0 unlinesAsciiC :: (Monad m, Seq.IsSequence seq, Element seq ~ Word8) => ConduitT seq seq m () unlinesAsciiC = CC.unlinesAscii # INLINE unlinesAsciiC # -- | Convert a stream of arbitrarily-chunked textual data into a stream of data -- where each chunk represents a single line. Note that, if you have -- unknown/untrusted input, this function is /unsafe/, since it would allow an -- attacker to form lines of massive length and exhaust memory. -- -- @since 1.3.0 linesUnboundedC :: (Monad m, Seq.IsSequence seq, Element seq ~ Char) => ConduitT seq seq m () linesUnboundedC = CC.linesUnbounded # INLINE linesUnboundedC # -- | Same as 'linesUnbounded', but for ASCII/binary data. -- -- @since 1.3.0 linesUnboundedAsciiC :: (Monad m, Seq.IsSequence seq, Element seq ~ Word8) => ConduitT seq seq m () linesUnboundedAsciiC = CC.linesUnboundedAscii # INLINE linesUnboundedAsciiC # | Generally speaking , yielding values from inside a Conduit requires -- some allocation for constructors. This can introduce an overhead, -- similar to the overhead needed to represent a list of values instead of -- a vector. This overhead is even more severe when talking about unboxed -- values. -- -- This combinator allows you to overcome this overhead, and efficiently fill up vectors . It takes two parameters . The first is the size of each mutable vector to be allocated . The second is a function . The function -- takes an argument which will yield the next value into a mutable -- vector. -- -- Under the surface, this function uses a number of tricks to get high -- performance. For more information on both usage and implementation, -- please see: -- <-documentation/vectorbuilder> -- -- @since 1.3.0 vectorBuilderC :: (PrimMonad m, V.Vector v e, PrimMonad n, PrimState m ~ PrimState n) => Int -- ^ size -> ((e -> n ()) -> ConduitT i Void m r) -> ConduitT i (v e) m r vectorBuilderC = CC.vectorBuilder # INLINE vectorBuilderC #
null
https://raw.githubusercontent.com/snoyberg/conduit/1771780ff4b606296924a28bf5d4433ae6a916f3/conduit/src/Data/Conduit/Combinators/Unqualified.hs
haskell
# LANGUAGE RankNTypes # # LANGUAGE GADTs # ** Producers *** Pure *** I\/O *** Filesystem ** Consumers *** Pure *** I\/O ** Transformers *** Pure *** Textual ** Builders ** Special BEGIN IMPORTS BEGIN IMPORTS END IMPORTS | Generate a producer from a seed value. @since 1.3.0 | Enumerate from a value to a final value, inclusive, via 'succ'. combining with @sourceList@ since this avoids any intermediate data structures. @since 1.3.0 | Produces an infinite stream of repeated applications of f to x. @since 1.3.0 | Produce an infinite stream consisting entirely of the given value. @since 1.3.0 | Produce a finite stream consisting of n copies of the given value. @since 1.3.0 | Repeatedly run the given action and yield all values it produces. @since 1.3.0 | Repeatedly run the given action and yield all values it produces, until @since 1.3.0 | Perform the given action n times, yielding each result. @since 1.3.0 @since 1.3.0 | Ignore a certain number of values in the stream. Note: since this function doesn't produce anything, you probably want to use it with ('>>') instead of directly plugging it into a pipeline: [] @since 1.3.0 | Drop a certain number of elements from a chunked stream. Note: you likely want to use it with monadic composition. See the docs for 'dropC'. @since 1.3.0 | Drop all values which match the given predicate. Note: you likely want to use it with monadic composition. See the docs for 'dropC'. @since 1.3.0 | Drop all elements in the chunked stream which match the given predicate. Note: you likely want to use it with monadic composition. See the docs for 'dropC'. @since 1.3.0 @since 1.3.0 @since 1.3.0 | A strict left fold. @since 1.3.0 | A strict left fold on a chunked stream. @since 1.3.0 | Apply the provided mapping function and monoidal combine all values. @since 1.3.0 | Apply the provided mapping function and monoidal combine all elements of the chunked stream. @since 1.3.0 | Check that all values in the stream return True. will stop. @since 1.3.0 | Check that all elements in the chunked stream return True. will stop. @since 1.3.0 will stop. @since 1.3.0 will stop. @since 1.3.0 | Are all values in the stream True? @since 1.3.0 | Are all elements in the chunked stream True? @since 1.3.0 | Are any values in the stream True? @since 1.3.0 | Are any elements in the chunked stream True? @since 1.3.0 @since 1.3.0 | Are any values in the stream equal to the given value? Stops consuming as soon as a match is found. @since 1.3.0 | Are any elements in the chunked stream equal to the given element? Stops consuming as soon as a match is found. @since 1.3.0 | Are no values in the stream equal to the given value? Stops consuming as soon as a match is found. @since 1.3.0 | Are no elements in the chunked stream equal to the given element? Stops consuming as soon as a match is found. @since 1.3.0 | Take a single value from the stream, if available. @since 1.3.0 | Same as 'headC', but returns a default value if none are available from the stream. @since 1.3.0 | Get the next element in the chunked stream. @since 1.3.0 | View the next value in the stream without consuming it. @since 1.3.0 | View the next element in the chunked stream without consuming it. @since 1.3.0 | Retrieve the last value in the stream, if present. @since 1.3.0 | Same as 'lastC', but returns a default value if none are available from the stream. @since 1.3.0 | Retrieve the last element in the chunked stream, if present. @since 1.3.0 | Count how many values are in the stream. @since 1.3.0 | Count how many elements are in the chunked stream. @since 1.3.0 | Count how many values in the stream pass the given predicate. @since 1.3.0 | Count how many elements in the chunked stream pass the given predicate. @since 1.3.0 | Get the largest value in the stream, if present. @since 1.3.0 | Get the largest element in the chunked stream, if present. @since 1.3.0 | Get the smallest value in the stream, if present. @since 1.3.0 | Get the smallest element in the chunked stream, if present. @since 1.3.0 | True if there are no values in the stream. This function does not modify the stream. @since 1.3.0 | True if there are no elements in the chunked stream. This function may remove empty leading chunks from the stream, but otherwise will not modify it. @since 1.3.0 | Get the sum of all values in the stream. @since 1.3.0 | Get the sum of all elements in the chunked stream. @since 1.3.0 # INLINE sumCE # | Get the product of all values in the stream. @since 1.3.0 | Get the product of all elements in the chunked stream. @since 1.3.0 @since 1.3.0 | Apply the action to all values in the stream. Note: if you want to /pass/ the values instead of /consuming/ them, use 'iterM' instead. @since 1.3.0 | Apply the action to all elements in the chunked stream. Note: the same caveat as with 'mapM_C' applies. If you don't want to consume the values, you can use 'iterM': > iterM (omapM_ f) @since 1.3.0 | A monadic strict left fold. @since 1.3.0 | A monadic strict left fold on a chunked stream. @since 1.3.0 | Apply the provided monadic mapping function and monoidal combine all values. @since 1.3.0 | Apply the provided monadic mapping function and monoidal combine all elements in the chunked stream. @since 1.3.0 | Print all incoming values to stdout. @since 1.3.0 | @sinkHandle@ applied to @stdout@. @since 1.3.0 | @sinkHandle@ applied to @stderr@. @since 1.3.0 | Apply a transformation to all values in a stream. @since 1.3.0 | Apply a transformation to all elements in a chunked stream. @since 1.3.0 | Apply a monomorphic transformation to all elements in a chunked stream. are @MonoFunctor@ but not @Functor@. @since 1.3.0 | Apply the function to each value in the stream, resulting in a foldable value (e.g., a list). Then yield each of the individual values in that foldable value separately. @since 1.3.0 | Apply the function to each element in the chunked stream, resulting in a foldable value (e.g., a list). Then yield each of the individual values in that foldable value separately. @since 1.3.0 | Stream up to n number of values downstream. Note that, if downstream terminates early, not all values will be consumed. If you want to force /exactly/ the given number of values to be consumed, see 'takeExactly'. @since 1.3.0 | Stream up to n number of elements downstream in a chunked stream. Note that, if downstream terminates early, not all values will be consumed. If you want to force /exactly/ the given number of values to be consumed, see 'takeExactlyE'. @since 1.3.0 | Stream all values downstream that match the given predicate. Same caveats regarding downstream termination apply as with 'take'. @since 1.3.0 | Stream all elements downstream that match the given predicate in a chunked stream. Same caveats regarding downstream termination apply as with 'takeE'. @since 1.3.0 # INLINE takeWhileCE # | Consume precisely the given number of values and feed them downstream. This function is in contrast to 'take', which will only consume up to the given number of values, and will terminate early if downstream terminates early. This function will discard any additional values in the stream if they are unconsumed. Note that this function takes a downstream @ConduitT@ as a parameter, as opposed to working with normal fusion. For more information, see <-flaw-pipes-conduit>, the section titled \"pipes and conduit: isolate\". @since 1.3.0 | Same as 'takeExactly', but for chunked streams. @since 1.3.0 | Flatten out a stream by yielding the values contained in an incoming @MonoFoldable@ as individually yielded values. @since 1.3.0 | Keep only values in the stream passing a given predicate. @since 1.3.0 | Keep only elements in the chunked stream passing a given predicate. @since 1.3.0 | Map values as long as the result is @Just@. @since 1.3.0 | Break up a stream of values into vectors of size n. The final vector may be smaller than n if the total number of values is not a strict multiple of n. No empty vectors will be yielded. @since 1.3.0 ^ maximum allowed size | Analog of 'Prelude.scanl' for lists. @since 1.3.0 Equivalently, 'CL.mapAccum' as long as the result is @Right@. Instead of producing a leftover, the breaking input determines the resulting accumulator via @Left@. | 'concatMap' with an accumulator. @since 1.3.0 @since 1.3.0 | Sliding window of values Best used with structures that support O(1) snoc. @since 1.3.0 | Split input into chunk of size 'chunkSize' The last element may be smaller than the 'chunkSize' (see also 'chunksOfExactlyE' which will not yield this last element) @since 1.3.0 | Split input into chunk of size 'chunkSize' If the input does not split into chunks exactly, the remainder will be leftover (see also 'chunksOfE') @since 1.3.0 | Apply a monadic transformation to all values in a stream. If you do not need the transformed values, and instead just want the monadic side-effects of running the action, see 'mapM_'. @since 1.3.0 | Apply a monadic transformation to all elements in a chunked stream. @since 1.3.0 | Apply a monadic monomorphic transformation to all elements in a chunked stream. Unlike @mapME@, this will work on types like @ByteString@ and @Text@ which are @MonoFunctor@ but not @Functor@. @since 1.3.0 | Apply the monadic function to each value in the stream, resulting in a foldable value (e.g., a list). Then yield each of the individual values in that foldable value separately. Generalizes concatMapM, mapMaybeM, and mapFoldableM. @since 1.3.0 | Keep only values in the stream passing a given monadic predicate. @since 1.3.0 | Keep only elements in the chunked stream passing a given monadic predicate. @since 1.3.0 | Apply a monadic action on all values in a stream. This @Conduit@ can be used to perform a monadic side-effect for every value, whilst passing the value through the @Conduit@ as-is. @since 1.3.0 | Analog of 'Prelude.scanl' for lists, monadic. @since 1.3.0 | 'concatMapM' with an accumulator. @since 1.3.0 | Encode a stream of text as UTF8. @since 1.3.0 | Decode a stream of binary data as UTF8. @since 1.3.0 | Decode a stream of binary data as UTF8, replacing any invalid bytes with @since 1.3.0 | Stream in the entirety of a single line. Like @takeExactly@, this will consume the entirety of the line regardless of @since 1.3.0 | Same as 'line', but operates on ASCII/binary data. @since 1.3.0 | Insert a newline character after each incoming chunk of data. @since 1.3.0 | Same as 'unlines', but operates on ASCII/binary data. @since 1.3.0 | Convert a stream of arbitrarily-chunked textual data into a stream of data where each chunk represents a single line. Note that, if you have unknown/untrusted input, this function is /unsafe/, since it would allow an attacker to form lines of massive length and exhaust memory. @since 1.3.0 | Same as 'linesUnbounded', but for ASCII/binary data. @since 1.3.0 some allocation for constructors. This can introduce an overhead, similar to the overhead needed to represent a list of values instead of a vector. This overhead is even more severe when talking about unboxed values. This combinator allows you to overcome this overhead, and efficiently takes an argument which will yield the next value into a mutable vector. Under the surface, this function uses a number of tricks to get high performance. For more information on both usage and implementation, please see: <-documentation/vectorbuilder> @since 1.3.0 ^ size
# OPTIONS_HADDOCK not - home # # LANGUAGE CPP # # LANGUAGE FlexibleContexts # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NoImplicitPrelude # # LANGUAGE NoMonomorphismRestriction # module Data.Conduit.Combinators.Unqualified CC.yieldMany , unfoldC , enumFromToC , iterateC , repeatC , replicateC , CC.sourceLazy * * * , repeatMC , repeatWhileMC , replicateMC , CC.sourceFile , CC.sourceFileBS , CC.sourceHandle , CC.sourceHandleUnsafe , CC.sourceIOHandle , stdinC , CC.withSourceFile , CC.sourceDirectory , CC.sourceDirectoryDeep , dropC , dropCE , dropWhileC , dropWhileCE , foldC , foldCE , foldlC , foldlCE , foldMapC , foldMapCE , allC , allCE , anyC , anyCE , andC , andCE , orC , orCE , asumC , elemC , elemCE , notElemC , notElemCE , CC.sinkLazy , CC.sinkList , CC.sinkVector , CC.sinkVectorN , CC.sinkLazyBuilder , CC.sinkNull , CC.awaitNonNull , headC , headDefC , headCE , peekC , peekCE , lastC , lastDefC , lastCE , lengthC , lengthCE , lengthIfC , lengthIfCE , maximumC , maximumCE , minimumC , minimumCE , nullC , nullCE , sumC , sumCE , productC , productCE , findC * * * , mapM_C , mapM_CE , foldMC , foldMCE , foldMapMC , foldMapMCE , CC.sinkFile , CC.sinkFileCautious , CC.sinkTempFile , CC.sinkSystemTempFile , CC.sinkFileBS , CC.sinkHandle , CC.sinkIOHandle , printC , stdoutC , stderrC , CC.withSinkFile , CC.withSinkFileBuilder , CC.withSinkFileCautious , CC.sinkHandleBuilder , CC.sinkHandleFlush , mapC , mapCE , omapCE , concatMapC , concatMapCE , takeC , takeCE , takeWhileC , takeWhileCE , takeExactlyC , takeExactlyCE , concatC , filterC , filterCE , mapWhileC , conduitVector , scanlC , mapAccumWhileC , concatMapAccumC , intersperseC , slidingWindowC , chunksOfCE , chunksOfExactlyCE * * * , mapMC , mapMCE , omapMCE , concatMapMC , filterMC , filterMCE , iterMC , scanlMC , mapAccumWhileMC , concatMapAccumMC , encodeUtf8C , decodeUtf8C , decodeUtf8LenientC , lineC , lineAsciiC , unlinesC , unlinesAsciiC , linesUnboundedC , linesUnboundedAsciiC , CC.builderToByteString , CC.unsafeBuilderToByteString , CC.builderToByteStringWith , CC.builderToByteStringFlush , CC.builderToByteStringWithFlush , CC.BufferAllocStrategy , CC.allNewBuffersStrategy , CC.reuseBufferStrategy , vectorBuilderC , CC.mapAccumS , CC.peekForever , CC.peekForeverE ) where import qualified Data.Conduit.Combinators as CC import qualified Data.Traversable import Control.Applicative (Alternative) import Control.Monad.IO.Class (MonadIO (..)) import Control.Monad.Primitive (PrimMonad, PrimState) import Control.Monad.Trans.Resource (MonadThrow) import Data.Conduit import Data.Monoid (Monoid (..)) import Data.MonoTraversable import qualified Data.Sequences as Seq import qualified Data.Vector.Generic as V import Prelude (Bool (..), Eq (..), Int, Maybe (..), Monad (..), Num (..), Ord (..), Functor (..), Either (..), Enum, Show, Char) import Data.Word (Word8) import Data.ByteString (ByteString) import Data.Text (Text) import qualified Data.Sequences as DTE unfoldC :: Monad m => (b -> Maybe (a, b)) -> b -> ConduitT i a m () unfoldC = CC.unfold # INLINE unfoldC # This is generally more efficient than using @Prelude@\ 's @enumFromTo@ and enumFromToC :: (Monad m, Enum a, Ord a) => a -> a -> ConduitT i a m () enumFromToC = CC.enumFromTo # INLINE enumFromToC # iterateC :: Monad m => (a -> a) -> a -> ConduitT i a m () iterateC = CC.iterate # INLINE iterateC # repeatC :: Monad m => a -> ConduitT i a m () repeatC = CC.repeat # INLINE repeatC # replicateC :: Monad m => Int -> a -> ConduitT i a m () replicateC = CC.replicate # INLINE replicateC # repeatMC :: Monad m => m a -> ConduitT i a m () repeatMC = CC.repeatM # INLINE repeatMC # the provided predicate returns repeatWhileMC :: Monad m => m a -> (a -> Bool) -> ConduitT i a m () repeatWhileMC = CC.repeatWhileM # INLINE repeatWhileMC # replicateMC :: Monad m => Int -> m a -> ConduitT i a m () replicateMC = CC.replicateM # INLINE replicateMC # | @sourceHandle@ applied to @stdin@. stdinC :: MonadIO m => ConduitT i ByteString m () stdinC = CC.stdin # INLINE stdinC # > > > runConduit $ yieldMany [ 1 .. 5 ] .| dropC 2 .| sinkList > > > runConduit $ yieldMany [ 1 .. 5 ] .| ( dropC 2 > > sinkList ) [ 3,4,5 ] dropC :: Monad m => Int -> ConduitT a o m () dropC = CC.drop # INLINE dropC # dropCE :: (Monad m, Seq.IsSequence seq) => Seq.Index seq -> ConduitT seq o m () dropCE = CC.dropE # INLINE dropCE # dropWhileC :: Monad m => (a -> Bool) -> ConduitT a o m () dropWhileC = CC.dropWhile # INLINE dropWhileC # dropWhileCE :: (Monad m, Seq.IsSequence seq) => (Element seq -> Bool) -> ConduitT seq o m () dropWhileCE = CC.dropWhileE # INLINE dropWhileCE # | combine all values in the stream . foldC :: (Monad m, Monoid a) => ConduitT a o m a foldC = CC.fold # INLINE foldC # | combine all elements in the chunked stream . foldCE :: (Monad m, MonoFoldable mono, Monoid (Element mono)) => ConduitT mono o m (Element mono) foldCE = CC.foldE # INLINE foldCE # foldlC :: Monad m => (a -> b -> a) -> a -> ConduitT b o m a foldlC = CC.foldl # INLINE foldlC # foldlCE :: (Monad m, MonoFoldable mono) => (a -> Element mono -> a) -> a -> ConduitT mono o m a foldlCE = CC.foldlE # INLINE foldlCE # foldMapC :: (Monad m, Monoid b) => (a -> b) -> ConduitT a o m b foldMapC = CC.foldMap # INLINE foldMapC # foldMapCE :: (Monad m, MonoFoldable mono, Monoid w) => (Element mono -> w) -> ConduitT mono o m w foldMapCE = CC.foldMapE # INLINE foldMapCE # Subject to shortcut logic : at the first False , consumption of the stream allC :: Monad m => (a -> Bool) -> ConduitT a o m Bool allC = CC.all # INLINE allC # Subject to shortcut logic : at the first False , consumption of the stream allCE :: (Monad m, MonoFoldable mono) => (Element mono -> Bool) -> ConduitT mono o m Bool allCE = CC.allE # INLINE allCE # | Check that at least one value in the stream returns True . Subject to shortcut logic : at the first True , consumption of the stream anyC :: Monad m => (a -> Bool) -> ConduitT a o m Bool anyC = CC.any # INLINE anyC # | Check that at least one element in the chunked stream returns True . Subject to shortcut logic : at the first True , consumption of the stream anyCE :: (Monad m, MonoFoldable mono) => (Element mono -> Bool) -> ConduitT mono o m Bool anyCE = CC.anyE # INLINE anyCE # Consumption stops once the first False is encountered . andC :: Monad m => ConduitT Bool o m Bool andC = CC.and # INLINE andC # Consumption stops once the first False is encountered . andCE :: (Monad m, MonoFoldable mono, Element mono ~ Bool) => ConduitT mono o m Bool andCE = CC.andE # INLINE andCE # Consumption stops once the first True is encountered . orC :: Monad m => ConduitT Bool o m Bool orC = CC.or # INLINE orC # Consumption stops once the first True is encountered . orCE :: (Monad m, MonoFoldable mono, Element mono ~ Bool) => ConduitT mono o m Bool orCE = CC.orE # INLINE orCE # | ' Alternative'ly combine all values in the stream . asumC :: (Monad m, Alternative f) => ConduitT (f a) o m (f a) asumC = CC.asum elemC :: (Monad m, Eq a) => a -> ConduitT a o m Bool elemC = CC.elem # INLINE elemC # #if MIN_VERSION_mono_traversable(1,0,0) elemCE :: (Monad m, Seq.IsSequence seq, Eq (Element seq)) #else elemCE :: (Monad m, Seq.EqSequence seq) #endif => Element seq -> ConduitT seq o m Bool elemCE = CC.elemE # INLINE elemCE # notElemC :: (Monad m, Eq a) => a -> ConduitT a o m Bool notElemC = CC.notElem # INLINE notElemC # #if MIN_VERSION_mono_traversable(1,0,0) notElemCE :: (Monad m, Seq.IsSequence seq, Eq (Element seq)) #else notElemCE :: (Monad m, Seq.EqSequence seq) #endif => Element seq -> ConduitT seq o m Bool notElemCE = CC.notElemE # INLINE notElemCE # headC :: Monad m => ConduitT a o m (Maybe a) headC = CC.head headDefC :: Monad m => a -> ConduitT a o m a headDefC = CC.headDef headCE :: (Monad m, Seq.IsSequence seq) => ConduitT seq o m (Maybe (Element seq)) headCE = CC.headE # INLINE headCE # peekC :: Monad m => ConduitT a o m (Maybe a) peekC = CC.peek # INLINE peekC # peekCE :: (Monad m, MonoFoldable mono) => ConduitT mono o m (Maybe (Element mono)) peekCE = CC.peekE # INLINE peekCE # lastC :: Monad m => ConduitT a o m (Maybe a) lastC = CC.last # INLINE lastC # lastDefC :: Monad m => a -> ConduitT a o m a lastDefC = CC.lastDef lastCE :: (Monad m, Seq.IsSequence seq) => ConduitT seq o m (Maybe (Element seq)) lastCE = CC.lastE # INLINE lastCE # lengthC :: (Monad m, Num len) => ConduitT a o m len lengthC = CC.length # INLINE lengthC # lengthCE :: (Monad m, Num len, MonoFoldable mono) => ConduitT mono o m len lengthCE = CC.lengthE # INLINE lengthCE # lengthIfC :: (Monad m, Num len) => (a -> Bool) -> ConduitT a o m len lengthIfC = CC.lengthIf # INLINE lengthIfC # lengthIfCE :: (Monad m, Num len, MonoFoldable mono) => (Element mono -> Bool) -> ConduitT mono o m len lengthIfCE = CC.lengthIfE # INLINE lengthIfCE # maximumC :: (Monad m, Ord a) => ConduitT a o m (Maybe a) maximumC = CC.maximum # INLINE maximumC # #if MIN_VERSION_mono_traversable(1,0,0) maximumCE :: (Monad m, Seq.IsSequence seq, Ord (Element seq)) => ConduitT seq o m (Maybe (Element seq)) #else maximumCE :: (Monad m, Seq.OrdSequence seq) => ConduitT seq o m (Maybe (Element seq)) #endif maximumCE = CC.maximumE # INLINE maximumCE # minimumC :: (Monad m, Ord a) => ConduitT a o m (Maybe a) minimumC = CC.minimum # INLINE minimumC # #if MIN_VERSION_mono_traversable(1,0,0) minimumCE :: (Monad m, Seq.IsSequence seq, Ord (Element seq)) => ConduitT seq o m (Maybe (Element seq)) #else minimumCE :: (Monad m, Seq.OrdSequence seq) => ConduitT seq o m (Maybe (Element seq)) #endif minimumCE = CC.minimumE # INLINE minimumCE # nullC :: Monad m => ConduitT a o m Bool nullC = CC.null # INLINE nullC # nullCE :: (Monad m, MonoFoldable mono) => ConduitT mono o m Bool nullCE = CC.nullE # INLINE nullCE # sumC :: (Monad m, Num a) => ConduitT a o m a sumC = CC.sum # INLINE sumC # sumCE :: (Monad m, MonoFoldable mono, Num (Element mono)) => ConduitT mono o m (Element mono) sumCE = CC.sumE productC :: (Monad m, Num a) => ConduitT a o m a productC = CC.product # INLINE productC # productCE :: (Monad m, MonoFoldable mono, Num (Element mono)) => ConduitT mono o m (Element mono) productCE = CC.productE # INLINE productCE # | Find the first matching value . findC :: Monad m => (a -> Bool) -> ConduitT a o m (Maybe a) findC = CC.find # INLINE findC # mapM_C :: Monad m => (a -> m ()) -> ConduitT a o m () mapM_C = CC.mapM_ # INLINE mapM_C # mapM_CE :: (Monad m, MonoFoldable mono) => (Element mono -> m ()) -> ConduitT mono o m () mapM_CE = CC.mapM_E # INLINE mapM_CE # foldMC :: Monad m => (a -> b -> m a) -> a -> ConduitT b o m a foldMC = CC.foldM # INLINE foldMC # foldMCE :: (Monad m, MonoFoldable mono) => (a -> Element mono -> m a) -> a -> ConduitT mono o m a foldMCE = CC.foldME # INLINE foldMCE # foldMapMC :: (Monad m, Monoid w) => (a -> m w) -> ConduitT a o m w foldMapMC = CC.foldMapM # INLINE foldMapMC # foldMapMCE :: (Monad m, MonoFoldable mono, Monoid w) => (Element mono -> m w) -> ConduitT mono o m w foldMapMCE = CC.foldMapME # INLINE foldMapMCE # printC :: (Show a, MonadIO m) => ConduitT a o m () printC = CC.print # INLINE printC # stdoutC :: MonadIO m => ConduitT ByteString o m () stdoutC = CC.stdout # INLINE stdoutC # stderrC :: MonadIO m => ConduitT ByteString o m () stderrC = CC.stderr # INLINE stderrC # mapC :: Monad m => (a -> b) -> ConduitT a b m () mapC = CC.map # INLINE mapC # mapCE :: (Monad m, Functor f) => (a -> b) -> ConduitT (f a) (f b) m () mapCE = CC.mapE # INLINE mapCE # Unlike @mapE@ , this will work on types like @ByteString@ and @Text@ which omapCE :: (Monad m, MonoFunctor mono) => (Element mono -> Element mono) -> ConduitT mono mono m () omapCE = CC.omapE # INLINE omapCE # Generalizes concatMap , mapMaybe , and mapFoldable . concatMapC :: (Monad m, MonoFoldable mono) => (a -> mono) -> ConduitT a (Element mono) m () concatMapC = CC.concatMap # INLINE concatMapC # Generalizes concatMap , mapMaybe , and mapFoldable . concatMapCE :: (Monad m, MonoFoldable mono, Monoid w) => (Element mono -> w) -> ConduitT mono w m () concatMapCE = CC.concatMapE # INLINE concatMapCE # takeC :: Monad m => Int -> ConduitT a a m () takeC = CC.take # INLINE takeC # takeCE :: (Monad m, Seq.IsSequence seq) => Seq.Index seq -> ConduitT seq seq m () takeCE = CC.takeE # INLINE takeCE # takeWhileC :: Monad m => (a -> Bool) -> ConduitT a a m () takeWhileC = CC.takeWhile # INLINE takeWhileC # takeWhileCE :: (Monad m, Seq.IsSequence seq) => (Element seq -> Bool) -> ConduitT seq seq m () takeWhileCE = CC.takeWhileE takeExactlyC :: Monad m => Int -> ConduitT a b m r -> ConduitT a b m r takeExactlyC = CC.takeExactly # INLINE takeExactlyC # takeExactlyCE :: (Monad m, Seq.IsSequence a) => Seq.Index a -> ConduitT a b m r -> ConduitT a b m r takeExactlyCE = CC.takeExactlyE # INLINE takeExactlyCE # concatC :: (Monad m, MonoFoldable mono) => ConduitT mono (Element mono) m () concatC = CC.concat # INLINE concatC # filterC :: Monad m => (a -> Bool) -> ConduitT a a m () filterC = CC.filter # INLINE filterC # filterCE :: (Seq.IsSequence seq, Monad m) => (Element seq -> Bool) -> ConduitT seq seq m () filterCE = CC.filterE # INLINE filterCE # mapWhileC :: Monad m => (a -> Maybe b) -> ConduitT a b m () mapWhileC = CC.mapWhile # INLINE mapWhileC # conduitVector :: (V.Vector v a, PrimMonad m) -> ConduitT a (v a) m () conduitVector = CC.conduitVector # INLINE conduitVector # scanlC :: Monad m => (a -> b -> a) -> a -> ConduitT b a m () scanlC = CC.scanl # INLINE scanlC # | ' ' with a break condition dependent on a strict accumulator . mapAccumWhileC :: Monad m => (a -> s -> Either s (s, b)) -> s -> ConduitT a b m s mapAccumWhileC = CC.mapAccumWhile # INLINE mapAccumWhileC # concatMapAccumC :: Monad m => (a -> accum -> (accum, [b])) -> accum -> ConduitT a b m () concatMapAccumC = CC.concatMapAccum # INLINE concatMapAccumC # | Insert the given value between each two values in the stream . intersperseC :: Monad m => a -> ConduitT a a m () intersperseC = CC.intersperse # INLINE intersperseC # 1,2,3,4,5 with window size 2 gives [ 1,2],[2,3],[3,4],[4,5 ] slidingWindowC :: (Monad m, Seq.IsSequence seq, Element seq ~ a) => Int -> ConduitT a seq m () slidingWindowC = CC.slidingWindow # INLINE slidingWindowC # chunksOfCE :: (Monad m, Seq.IsSequence seq) => Seq.Index seq -> ConduitT seq seq m () chunksOfCE = CC.chunksOfE # INLINE chunksOfCE # chunksOfExactlyCE :: (Monad m, Seq.IsSequence seq) => Seq.Index seq -> ConduitT seq seq m () chunksOfExactlyCE = CC.chunksOfExactlyE # INLINE chunksOfExactlyCE # mapMC :: Monad m => (a -> m b) -> ConduitT a b m () mapMC = CC.mapM # INLINE mapMC # mapMCE :: (Monad m, Data.Traversable.Traversable f) => (a -> m b) -> ConduitT (f a) (f b) m () mapMCE = CC.mapME # INLINE mapMCE # omapMCE :: (Monad m, MonoTraversable mono) => (Element mono -> m (Element mono)) -> ConduitT mono mono m () omapMCE = CC.omapME # INLINE omapMCE # concatMapMC :: (Monad m, MonoFoldable mono) => (a -> m mono) -> ConduitT a (Element mono) m () concatMapMC = CC.concatMapM # INLINE concatMapMC # filterMC :: Monad m => (a -> m Bool) -> ConduitT a a m () filterMC = CC.filterM # INLINE filterMC # filterMCE :: (Monad m, Seq.IsSequence seq) => (Element seq -> m Bool) -> ConduitT seq seq m () filterMCE = CC.filterME # INLINE filterMCE # > iterM f = mapM ( \a - > f a > > = \ ( ) - > return a ) iterMC :: Monad m => (a -> m ()) -> ConduitT a a m () iterMC = CC.iterM # INLINE iterMC # scanlMC :: Monad m => (a -> b -> m a) -> a -> ConduitT b a m () scanlMC = CC.scanlM # INLINE scanlMC # | Monadic ` mapAccumWhileC ` . mapAccumWhileMC :: Monad m => (a -> s -> m (Either s (s, b))) -> s -> ConduitT a b m s mapAccumWhileMC = CC.mapAccumWhileM # INLINE mapAccumWhileMC # concatMapAccumMC :: Monad m => (a -> accum -> m (accum, [b])) -> accum -> ConduitT a b m () concatMapAccumMC = CC.concatMapAccumM # INLINE concatMapAccumMC # encodeUtf8C :: (Monad m, DTE.Utf8 text binary) => ConduitT text binary m () encodeUtf8C = CC.encodeUtf8 # INLINE encodeUtf8C # decodeUtf8C :: MonadThrow m => ConduitT ByteString Text m () decodeUtf8C = CC.decodeUtf8 # INLINE decodeUtf8C # the Unicode replacement character . decodeUtf8LenientC :: Monad m => ConduitT ByteString Text m () decodeUtf8LenientC = CC.decodeUtf8Lenient # INLINE decodeUtf8LenientC # the behavior of the inner Conduit . lineC :: (Monad m, Seq.IsSequence seq, Element seq ~ Char) => ConduitT seq o m r -> ConduitT seq o m r lineC = CC.line # INLINE lineC # lineAsciiC :: (Monad m, Seq.IsSequence seq, Element seq ~ Word8) => ConduitT seq o m r -> ConduitT seq o m r lineAsciiC = CC.lineAscii # INLINE lineAsciiC # unlinesC :: (Monad m, Seq.IsSequence seq, Element seq ~ Char) => ConduitT seq seq m () unlinesC = CC.unlines # INLINE unlinesC # unlinesAsciiC :: (Monad m, Seq.IsSequence seq, Element seq ~ Word8) => ConduitT seq seq m () unlinesAsciiC = CC.unlinesAscii # INLINE unlinesAsciiC # linesUnboundedC :: (Monad m, Seq.IsSequence seq, Element seq ~ Char) => ConduitT seq seq m () linesUnboundedC = CC.linesUnbounded # INLINE linesUnboundedC # linesUnboundedAsciiC :: (Monad m, Seq.IsSequence seq, Element seq ~ Word8) => ConduitT seq seq m () linesUnboundedAsciiC = CC.linesUnboundedAscii # INLINE linesUnboundedAsciiC # | Generally speaking , yielding values from inside a Conduit requires fill up vectors . It takes two parameters . The first is the size of each mutable vector to be allocated . The second is a function . The function vectorBuilderC :: (PrimMonad m, V.Vector v e, PrimMonad n, PrimState m ~ PrimState n) -> ((e -> n ()) -> ConduitT i Void m r) -> ConduitT i (v e) m r vectorBuilderC = CC.vectorBuilder # INLINE vectorBuilderC #
196543a659f13d21b50d45bf654a63da748fe4dd610a9c554b3166b015307a4c
initc3/SaUCy
TypeError.hs
{-# OPTIONS_GHC -Wall #-} -------------------------------------------------------------------------------- -- | -- Module : Language.ILC.TypeError Copyright : ( C ) 2018 -- License : BSD-style (see LICENSE) Maintainer : ( ) -- Stability : experimental -- -- Describes type errors and implements error messages. -- -------------------------------------------------------------------------------- module Language.ILC.TypeError ( TypeError(..) ) where import Text.PrettyPrint.ANSI.Leijen import Language.ILC.Syntax import Language.ILC.Type data TypeError = UnificationFail Type Type | InfiniteType TVar Type | UnboundVariable Name | WrTokenInChoice | WrTokenInRd | NoWrTok | Ambiguous [(Type, Type)] | UnificationMismatch [Type] [Type] | TypeFail String | LinearFail Name instance Show TypeError where show = show . pretty instance Pretty TypeError where pretty (UnificationFail a b) = hsep [ text "Cannot unify types:\n\t" , pretty a , text "\nwith\n\t" , pretty b ] pretty (InfiniteType (TV a) b) = hsep [ text "Cannot construct the infinite type:" , pretty a , text "=" , pretty b ] pretty (Ambiguous cs) = hsep [ hsep [ text "Cannot match expected type:" , text "'" <> pretty a <> text "'" , text "with actual type:" , text "'" <> pretty b <> text "'\n" ] | (a, b) <- cs ] pretty (UnboundVariable a) = text "Not in scope:" <+> pretty a pretty (WrTokenInChoice) = text "Write token cannot be present in choice expression" pretty (WrTokenInRd) = text "Write token cannot be present in read expression" pretty (NoWrTok) = text "Write expression requires write token" pretty (TypeFail s) = text s pretty (LinearFail x) = text "Linear read channel violation on variable" <+> text x pretty _ = text "Unimplemented error message"
null
https://raw.githubusercontent.com/initc3/SaUCy/199154c1f488af4561e4bf1f7f5f3ef8876dfa6b/src/Language/ILC/TypeError.hs
haskell
# OPTIONS_GHC -Wall # ------------------------------------------------------------------------------ | Module : Language.ILC.TypeError License : BSD-style (see LICENSE) Stability : experimental Describes type errors and implements error messages. ------------------------------------------------------------------------------
Copyright : ( C ) 2018 Maintainer : ( ) module Language.ILC.TypeError ( TypeError(..) ) where import Text.PrettyPrint.ANSI.Leijen import Language.ILC.Syntax import Language.ILC.Type data TypeError = UnificationFail Type Type | InfiniteType TVar Type | UnboundVariable Name | WrTokenInChoice | WrTokenInRd | NoWrTok | Ambiguous [(Type, Type)] | UnificationMismatch [Type] [Type] | TypeFail String | LinearFail Name instance Show TypeError where show = show . pretty instance Pretty TypeError where pretty (UnificationFail a b) = hsep [ text "Cannot unify types:\n\t" , pretty a , text "\nwith\n\t" , pretty b ] pretty (InfiniteType (TV a) b) = hsep [ text "Cannot construct the infinite type:" , pretty a , text "=" , pretty b ] pretty (Ambiguous cs) = hsep [ hsep [ text "Cannot match expected type:" , text "'" <> pretty a <> text "'" , text "with actual type:" , text "'" <> pretty b <> text "'\n" ] | (a, b) <- cs ] pretty (UnboundVariable a) = text "Not in scope:" <+> pretty a pretty (WrTokenInChoice) = text "Write token cannot be present in choice expression" pretty (WrTokenInRd) = text "Write token cannot be present in read expression" pretty (NoWrTok) = text "Write expression requires write token" pretty (TypeFail s) = text s pretty (LinearFail x) = text "Linear read channel violation on variable" <+> text x pretty _ = text "Unimplemented error message"
847b1da7f7e5c0e13bb06a707121666099eed25e5b78965e51f13ef2b01f7163
jackfirth/point-free
info.rkt
#lang info (define collection 'multi) (define deps '("base" "rackunit-lib" "doc-coverage")) (define build-deps '("cover" "doc-coverage" "scribble-lib" "rackunit-lib" "racket-doc"))
null
https://raw.githubusercontent.com/jackfirth/point-free/d294a342466d5071dd2c8f16ba9e50f9006b54af/info.rkt
racket
#lang info (define collection 'multi) (define deps '("base" "rackunit-lib" "doc-coverage")) (define build-deps '("cover" "doc-coverage" "scribble-lib" "rackunit-lib" "racket-doc"))
f31e57df8138543872ca73d76bfd8f8923ad98de1041dace9a3f093e24981a0f
ctford/Idris-Elba-Dev
Chaser.hs
module Idris.Chaser(buildTree, getModuleFiles, ModuleTree(..)) where import Idris.Parser import Idris.AbsSyntax import Idris.Imports import Idris.Unlit import Idris.Error import Idris.IBC import System.FilePath import System.Directory import Data.Time.Clock import Control.Monad.Trans import Control.Monad.State import Data.List import Debug.Trace data ModuleTree = MTree { mod_path :: IFileType, mod_needsRecheck :: Bool, mod_time :: UTCTime, mod_deps :: [ModuleTree] } deriving Show latest :: UTCTime -> [ModuleTree] -> UTCTime latest tm [] = tm latest tm (m : ms) = latest (max tm (mod_time m)) (ms ++ mod_deps m) -- Given a module tree, return the list of files to be loaded. If any -- module has a descendent which needs reloading, return its source, otherwise return the IBC getModuleFiles :: [ModuleTree] -> [IFileType] getModuleFiles ts = nub $ execState (modList ts) [] where modList :: [ModuleTree] -> State [IFileType] () modList [] = return () modList (m : ms) = do modTree [] m; modList ms modTree path (MTree p rechk tm deps) = do let file = chkReload rechk p -- Needs rechecking if 'rechk' is true, or if any of the modification times in ' ' are later than tm let depMod = latest tm deps let needsRechk = rechk || depMod > tm st <- get if needsRechk then put $ nub (getSrc file : updateToSrc path st) else put $ nub (file : st) -- when (not (ibc p) || rechk) $ mapM_ (modTree (getSrc p : path)) deps ibc (IBC _ _) = True ibc _ = False chkReload False p = p chkReload True (IBC fn src) = chkReload True src chkReload True p = p getSrc (IBC fn src) = getSrc src getSrc f = f updateToSrc path [] = [] updateToSrc path (x : xs) = if getSrc x `elem` path then getSrc x : updateToSrc path xs else x : updateToSrc path xs getIModTime (IBC i _) = getModificationTime i getIModTime (IDR i) = getModificationTime i getIModTime (LIDR i) = getModificationTime i buildTree :: [FilePath] -> -- already guaranteed built FilePath -> Idris [ModuleTree] buildTree built fp = btree [] fp -- = idrisCatch (btree [] fp) -- (\e -> do now <- runIO $ getCurrentTime -- iputStrLn (show e) -- return [MTree (IDR fp) True now []]) where btree done f = do i <- getIState let file = takeWhile (/= ' ') f iLOG $ "CHASING " ++ show file ibcsd <- valIBCSubDir i ids <- allImportDirs fp <- runIO $ findImport ids ibcsd file iLOG $ "Found " ++ show fp mt <- runIO $ getIModTime fp if (file `elem` built) then return [MTree fp False mt []] else if file `elem` done then return [] else mkChildren fp where mkChildren (LIDR fn) = do ms <- children True fn (f:done) mt <- runIO $ getModificationTime fn return [MTree (LIDR fn) True mt ms] mkChildren (IDR fn) = do ms <- children False fn (f:done) mt <- runIO $ getModificationTime fn return [MTree (IDR fn) True mt ms] mkChildren (IBC fn src) = do srcexist <- runIO $ doesFileExist (getSrcFile src) ms <- if srcexist then do [MTree _ _ _ ms'] <- mkChildren src return ms' else return [] mt <- idrisCatch (runIO $ getModificationTime fn) (\c -> runIO $ getIModTime src) ok <- checkIBCUpToDate fn src return [MTree (IBC fn src) ok mt ms] getSrcFile (IBC _ src) = getSrcFile src getSrcFile (LIDR src) = src getSrcFile (IDR src) = src -- FIXME: It's also not up to date if anything it imports has been modified since its own ibc has . checkIBCUpToDate fn (LIDR src) = older fn src checkIBCUpToDate fn (IDR src) = older fn src older ibc src = do exist <- runIO $ doesFileExist src if exist then do ibct <- runIO $ getModificationTime ibc srct <- runIO $ getModificationTime src return (srct > ibct) else return False children :: Bool -> FilePath -> [FilePath] -> Idris [ModuleTree] children lit f done = -- idrisCatch do exist <- runIO $ doesFileExist f if exist then do file_in <- runIO $ readFile f file <- if lit then tclift $ unlit f file_in else return file_in (_, modules, _) <- parseImports f file ms <- mapM (btree done) [realName | (realName, alias, fc) <- modules] return (concat ms) IBC with no source available ( - > return [ ] ) -- error , ca n't chase modules here
null
https://raw.githubusercontent.com/ctford/Idris-Elba-Dev/e915e1d6b7a5921ba43d2572a9ad9b980619b8ee/src/Idris/Chaser.hs
haskell
Given a module tree, return the list of files to be loaded. If any module has a descendent which needs reloading, return its source, otherwise Needs rechecking if 'rechk' is true, or if any of the when (not (ibc p) || rechk) $ already guaranteed built = idrisCatch (btree [] fp) (\e -> do now <- runIO $ getCurrentTime iputStrLn (show e) return [MTree (IDR fp) True now []]) FIXME: It's also not up to date if anything it imports has idrisCatch error , ca n't chase modules here
module Idris.Chaser(buildTree, getModuleFiles, ModuleTree(..)) where import Idris.Parser import Idris.AbsSyntax import Idris.Imports import Idris.Unlit import Idris.Error import Idris.IBC import System.FilePath import System.Directory import Data.Time.Clock import Control.Monad.Trans import Control.Monad.State import Data.List import Debug.Trace data ModuleTree = MTree { mod_path :: IFileType, mod_needsRecheck :: Bool, mod_time :: UTCTime, mod_deps :: [ModuleTree] } deriving Show latest :: UTCTime -> [ModuleTree] -> UTCTime latest tm [] = tm latest tm (m : ms) = latest (max tm (mod_time m)) (ms ++ mod_deps m) return the IBC getModuleFiles :: [ModuleTree] -> [IFileType] getModuleFiles ts = nub $ execState (modList ts) [] where modList :: [ModuleTree] -> State [IFileType] () modList [] = return () modList (m : ms) = do modTree [] m; modList ms modTree path (MTree p rechk tm deps) = do let file = chkReload rechk p modification times in ' ' are later than tm let depMod = latest tm deps let needsRechk = rechk || depMod > tm st <- get if needsRechk then put $ nub (getSrc file : updateToSrc path st) else put $ nub (file : st) mapM_ (modTree (getSrc p : path)) deps ibc (IBC _ _) = True ibc _ = False chkReload False p = p chkReload True (IBC fn src) = chkReload True src chkReload True p = p getSrc (IBC fn src) = getSrc src getSrc f = f updateToSrc path [] = [] updateToSrc path (x : xs) = if getSrc x `elem` path then getSrc x : updateToSrc path xs else x : updateToSrc path xs getIModTime (IBC i _) = getModificationTime i getIModTime (IDR i) = getModificationTime i getIModTime (LIDR i) = getModificationTime i FilePath -> Idris [ModuleTree] buildTree built fp = btree [] fp where btree done f = do i <- getIState let file = takeWhile (/= ' ') f iLOG $ "CHASING " ++ show file ibcsd <- valIBCSubDir i ids <- allImportDirs fp <- runIO $ findImport ids ibcsd file iLOG $ "Found " ++ show fp mt <- runIO $ getIModTime fp if (file `elem` built) then return [MTree fp False mt []] else if file `elem` done then return [] else mkChildren fp where mkChildren (LIDR fn) = do ms <- children True fn (f:done) mt <- runIO $ getModificationTime fn return [MTree (LIDR fn) True mt ms] mkChildren (IDR fn) = do ms <- children False fn (f:done) mt <- runIO $ getModificationTime fn return [MTree (IDR fn) True mt ms] mkChildren (IBC fn src) = do srcexist <- runIO $ doesFileExist (getSrcFile src) ms <- if srcexist then do [MTree _ _ _ ms'] <- mkChildren src return ms' else return [] mt <- idrisCatch (runIO $ getModificationTime fn) (\c -> runIO $ getIModTime src) ok <- checkIBCUpToDate fn src return [MTree (IBC fn src) ok mt ms] getSrcFile (IBC _ src) = getSrcFile src getSrcFile (LIDR src) = src getSrcFile (IDR src) = src been modified since its own ibc has . checkIBCUpToDate fn (LIDR src) = older fn src checkIBCUpToDate fn (IDR src) = older fn src older ibc src = do exist <- runIO $ doesFileExist src if exist then do ibct <- runIO $ getModificationTime ibc srct <- runIO $ getModificationTime src return (srct > ibct) else return False children :: Bool -> FilePath -> [FilePath] -> Idris [ModuleTree] do exist <- runIO $ doesFileExist f if exist then do file_in <- runIO $ readFile f file <- if lit then tclift $ unlit f file_in else return file_in (_, modules, _) <- parseImports f file ms <- mapM (btree done) [realName | (realName, alias, fc) <- modules] return (concat ms) IBC with no source available
f4a3ba459c3c4884fb353de635f5ef18b116dfc3c27a7ba550dbf761a35cf953
typedclojure/typedclojure
repl_new.clj
(ns clojure.core.typed.test.repl-new (:require [typed.clojure :as t] [clojure.test :refer :all] [typed.clj.checker.test-utils :refer :all])) (deftest apropos-test (is-tc-e #(apropos "clojure") [-> (t/Seq t/Sym)] :requires [[clojure.repl :refer [apropos]]]) (is-tc-e #(apropos #"") [-> (t/Seq t/Sym)] :requires [[clojure.repl :refer [apropos]]]) (is-tc-err #(apropos "clojure") [-> (t/Seq t/Str)] :requires [[clojure.repl :refer [apropos]]]) (is-tc-err #(apropos 'clojure) [-> (t/Seq t/Str)] :requires [[clojure.repl :refer [apropos]]])) (deftest demunge-test (is-tc-e #(demunge "clojure.repl$demunge") [-> t/Str] :requires [[clojure.repl :refer [demunge]]]) (is-tc-err #(demunge "clojure.repl$demunge") [-> (t/Vec t/Any)] :requires [[clojure.repl :refer [demunge]]]) (is-tc-err #(demunge 'clojure.repl$demunge) [-> t/Str] :requires [[clojure.repl :refer [demunge]]])) (deftest source-fn-test (is-tc-e #(source-fn 'source) [-> (t/U nil t/Str)] :requires [[clojure.repl :refer [source-fn]]]) (is-tc-err #(source-fn 'source) [-> (t/Vec t/Any)] :requires [[clojure.repl :refer [source-fn]]]) (is-tc-err #(source-fn "source") [-> t/Str] :requires [[clojure.repl :refer [source-fn]]]))
null
https://raw.githubusercontent.com/typedclojure/typedclojure/5fd7cdf7941c6e7d1dd5df88bf44474fa35e1fca/typed/clj.checker/test/clojure/core/typed/test/repl_new.clj
clojure
(ns clojure.core.typed.test.repl-new (:require [typed.clojure :as t] [clojure.test :refer :all] [typed.clj.checker.test-utils :refer :all])) (deftest apropos-test (is-tc-e #(apropos "clojure") [-> (t/Seq t/Sym)] :requires [[clojure.repl :refer [apropos]]]) (is-tc-e #(apropos #"") [-> (t/Seq t/Sym)] :requires [[clojure.repl :refer [apropos]]]) (is-tc-err #(apropos "clojure") [-> (t/Seq t/Str)] :requires [[clojure.repl :refer [apropos]]]) (is-tc-err #(apropos 'clojure) [-> (t/Seq t/Str)] :requires [[clojure.repl :refer [apropos]]])) (deftest demunge-test (is-tc-e #(demunge "clojure.repl$demunge") [-> t/Str] :requires [[clojure.repl :refer [demunge]]]) (is-tc-err #(demunge "clojure.repl$demunge") [-> (t/Vec t/Any)] :requires [[clojure.repl :refer [demunge]]]) (is-tc-err #(demunge 'clojure.repl$demunge) [-> t/Str] :requires [[clojure.repl :refer [demunge]]])) (deftest source-fn-test (is-tc-e #(source-fn 'source) [-> (t/U nil t/Str)] :requires [[clojure.repl :refer [source-fn]]]) (is-tc-err #(source-fn 'source) [-> (t/Vec t/Any)] :requires [[clojure.repl :refer [source-fn]]]) (is-tc-err #(source-fn "source") [-> t/Str] :requires [[clojure.repl :refer [source-fn]]]))
7351e73baf5f0e13953004c3846539a5c8b710f7fc2d0593971501ab55af2d30
lambda-study-group/sicp
anabastos.clj
(defn p [] p) (defn test [x y] (if (> x 0) 0 y)) (test 0 (p)) The expression ( test 0 ( p ) ) will end in a infinite loop if the programming language evaluates in applicative - order ; In normal order evaluation the expression is evaluated outside in, terminating the execution.
null
https://raw.githubusercontent.com/lambda-study-group/sicp/70819ea6156dfc4e49a2d174dff62c6527c8f024/1.1-TheElementsOfProgramming/ex-1.5/anabastos.clj
clojure
In normal order evaluation the expression is evaluated outside in, terminating the execution.
(defn p [] p) (defn test [x y] (if (> x 0) 0 y)) (test 0 (p)) The expression ( test 0 ( p ) ) will end in a infinite loop if the programming language evaluates in applicative - order
b7160626a6f41bbb8b9a3df1528e062b4ad22cf783284778220c02933c152cff
eslick/cl-langutils
reference.lisp
-*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Base : 10 ; Package : utils -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: reference ;;;; Purpose: A wrapper around vector representations of text ;;;; Programmer : Date Started : October 2004 ;;;; (in-package :langutils) ;; --------------------------- ;; Document wrapper (defclass vector-document () ((text ;; text vector :accessor document-text :initarg :text :type (array fixnum)) (tags ;; tag vector :accessor document-tags :initarg :tags :type (array symbol)) (annotations :accessor document-annotations :initarg :annotations :initform nil :type list))) (defmethod length-of ((doc vector-document)) (length (document-text doc))) (defun make-vector-document (text &optional tags) (make-instance 'vector-document :text text :tags tags)) ;; Document accessors (defmethod get-token-id ((doc vector-document) offset) (aref (document-text doc) offset)) (defmethod get-tag ((doc vector-document) offset) (aref (document-tags doc) offset)) (defmethod get-annotation ((doc vector-document) key) "First returned value is the association value or null if none. The second is true if the key exists, nil otherwise" (aif (assoc key (document-annotations doc)) (values (cdr it) t) (values nil nil))) (defmethod set-annotation ((doc vector-document) key value &key (method :override)) "Add an annotation to object using method :override, :push, :duplicate-key" (flet ((set-on-empty () (assoc-setf (document-annotations doc) key value 'eq))) (case method (:override (aif (assoc key (document-annotations doc)) (rplacd it value) (set-on-empty))) (:push (aif (assoc key (document-annotations doc)) (push value (cdr it)) (set-on-empty))) (:duplicate-key (setf (document-annotations doc) (acons key value (document-annotations doc)))) (t (error "Invalid method ~A for add-annotation" method))) t)) (defmethod unset-annotation ((doc vector-document) key) (remove key (document-annotations doc) :key #'car)) ;; Create a vector document from a file or text (defun vector-document (input) (typecase input (string (vector-tag input)) (pathname (read-vector-document input)) (vector-document input) (t (error "No handler for input type: ~A" (type-of input))))) ;; Documents to/from strings (defun string-tag ( string &optional (stream t)) "Tokenizes and tags the string returning a standard tagged string using '/' as a separator" (string-tag-tokenized (mvretn 3 (tokenize-string string)) stream)) (defun string-tag-tokenized ( string &optional (stream t)) (print-vector-document (vector-tag string) :stream stream)) (defmethod vector-document-string ( (doc vector-document) &key (with-tags nil) (with-newline nil) ) (with-output-to-string (stream) (print-vector-document doc :stream stream :with-tags with-tags :with-newline with-newline))) (defmethod print-vector-document ( (doc vector-document) &key (stream t) (with-tags t) (with-newline t) ) (with-slots (text tags) doc (loop for token fixnum across (document-text doc) and tag symbol across (document-tags doc) do (if with-tags (format stream "~A/~A " (token-for-id token) tag) (format stream "~A " (token-for-id token)))) (when with-newline (format stream "~%")))) (defmethod vector-document-words ( (doc vector-document) ) (token-array->words (document-text doc))) ;; Documents to/from files in native form (defmethod vector-doc-as-ids ( (doc vector-document) ) "Converts the word array to ids with shared structure for the other elements; keeps the data 'in the family' so the source or destination documents should be short lived" (let* ((word-array (document-text doc)) (id-array (make-array (length word-array) :element-type 'fixnum))) (make-instance 'vector-document :text (map-into id-array #'id-for-token word-array) :tags (document-tags doc) :annotations (document-annotations doc)))) (defmethod vector-doc-as-words ( (doc vector-document) ) (let* ((id-array (document-text doc)) (word-array (make-array (length id-array) :element-type 'string))) (make-instance 'vector-document :text (map-into word-array #'token-for-id id-array) :tags (document-tags doc) :annotations (document-annotations doc)))) (defmethod write-vector-document ((doc vector-document) filename &key (with-tags t) (if-exists :supersede)) (with-open-file (s filename :direction :output :if-exists if-exists) (print-vector-document doc :stream s :with-tags with-tags))) (defmethod read-vector-document (filename) (vector-tag (read-file-to-string filename))) (defmethod read-vector-document-to-string ((doc vector-document) &key (with-tags t)) (with-output-to-string (s) (print-vector-document doc :with-tags with-tags :stream s))) (defmethod document-window-as-string (document start end) (apply #'concatenate 'string (shuffle (mapcar #'token-for-id (subseq (document-text document) start end)) (repeat " " (- end start))))) ;; ======================================================== ;; Phrase wrapper ;; ======================================================== (defclass+ phrase () ((type nil) ;; phrase type (document nil) ;; pointer or id if in registry (start nil) ;; offset in doc (end nil) ;; end in doc (annotations nil)) (:prefix "phrase-")) (defmethod print-object ((p phrase) stream) (let ((pstr (make-string-output-stream))) (print-phrase p :stream pstr :with-tags nil :newline nil) (format stream "#<~A:~A \"~A\">" (class-name (class-of p)) (phrase-type p) (get-output-stream-string pstr)))) (defun make-phrase-from-sentence (tok-string &optional tag-array) (let ((words (extract-words tok-string))) (make-phrase (map-into (make-array (length words)) #'id-for-token words) tag-array))) (defun make-phrase (text-array tag-array &optional type) "Take two arrays of test and tags and create a phrase that points at a vdoc created from the two arrays" (make-phrase-from-vdoc (vector-doc-as-ids (make-vector-document text-array tag-array)) 0 (length text-array) type)) (defparameter *temp-phrase* nil) (defun temp-phrase () (unless *temp-phrase* (setf *temp-phrase* (make-phrase nil nil nil))) *temp-phrase*) (defmethod find-phrase ((p phrase) (doc vector-document) &key (match :all) (start 0) (ignore-start nil) (ignore-end nil) (lemma nil) (concept-terms nil)) "Find the specified phrase starting at start, matching text and/or tags according to match. The lemma parameter indicates whether the phrases match under the lemma operator and ignore-start and ignore-end causes the search to not match a region within the document" (declare (optimize (speed 3) (safety 1) (space 0)) (type fixnum start)) (if (eq (phrase-document p) doc) (values (phrase-start p) (phrase-end p)) (let ((ptext (document-text (phrase-document p))) (dtext (document-text doc)) (ptags (document-tags (phrase-document p))) (dtags (document-tags doc))) (declare (type (array fixnum *) dtext) (type (array symbol *) ptext)) (labels ((match-tokens (doc-offset phrase-offset) (declare (type fixnum doc-offset phrase-offset)) (if (and ignore-start ignore-end (>= doc-offset ignore-start) (<= doc-offset ignore-end)) nil (case match (:all (and (match-text doc-offset phrase-offset) (match-tags doc-offset phrase-offset))) (:words (match-text doc-offset phrase-offset)) (:pos (match-tags doc-offset phrase-offset)) (t nil)))) (match-text (d p) (declare (type fixnum d p)) (cond ((and concept-terms (eq (aref ptext p) (id-for-token "person"))) (member (aref dtext d) (mapcar #'id-for-token '("I" "him" "her" "they" "them" "me" "you" "us")))) ((and concept-terms (eq (aref ptext p) (id-for-token "something"))) (eq (aref dtext d) (id-for-token "it"))) (lemma (eq (get-lemma (aref ptext p)) (get-lemma (aref dtext d)))) (t (eq (aref ptext p) (aref dtext d))))) (match-tags (d p) (declare (type fixnum d p)) (eq (aref ptags p) (aref dtags d)))) (loop for offset fixnum from start upto (1- (length dtext)) finally (return nil) do (when (match-tokens offset 0) (when (loop for pindex from 0 for dindex from offset while (and (< pindex (length ptext)) (< dindex (length dtext))) finally (return t) do (unless (match-tokens dindex pindex) (return nil))) (return (values offset (+ offset (1- (length ptext)))))))))))) (defmethod find-phrase-intervals ((p phrase) (doc vector-document) &key (match :all) (start 0) (lemma nil) (concept-terms nil) &aux results) "Find all phrase intervals in the vector document" (loop while (< start (1- (length-of doc))) do (mvbind (front back) (find-phrase p doc :match match :start start :lemma lemma :concept-terms concept-terms) (if (and front back) (progn (push (cons front back) results) (setf start (1+ back))) (return)))) (nreverse results)) (defmethod find-phrase-intervals ((p array) (doc vector-document) &key (match :words) (start 0) (lemma nil) (concept-terms nil) &aux results) "Find all phrase intervals in the vector document" (declare (ignore match) (optimize (speed 3) (space 0) (safety 1)) (type fixnum start) (type list results)) ;; (labels ((expand-if-person () ;; (let ((offset (person-token-offset p))) ;; (when (> offset -1) ( setf results ; (mapcan #'(lambda ( (loop while (< start (1- (length-of doc))) do (mvbind (front back) (find-phrase (make-phrase p nil) doc :match :words :start start :lemma lemma :concept-terms concept-terms) (declare (type (or fixnum nil) front back)) (if (and front back) (progn (push (cons front back) results) (setf start (1+ back))) (return)))) (nreverse results)) (defun person-token-offset (array) (let ((person (id-for-token "person"))) (loop for token across array for offset from 0 do (when (eq token person) (return-from person-token-offset t))))) (defmethod get-annotation ((p phrase) key) "First returned value is the association value or null if none. The second is true if the key exists, nil otherwise" (aif (assoc key (phrase-annotations p)) (values (cdr it) t) (values nil nil))) (defmethod set-annotation ((p phrase) key value &key (method :override)) "Add an annotation to object using method :override, :push, :duplicate-key" (flet ((set-on-empty () (setf (phrase-annotations p) (acons key value nil)))) (case method (:override (aif (assoc key (phrase-annotations p)) (rplacd it value) (set-on-empty))) (:push (aif (assoc key (phrase-annotations p)) (push value (cdr it)) (set-on-empty))) (:duplicate-key (setf (phrase-annotations p) (acons key value (phrase-annotations p)))) (t (error "Invalid method ~A for add-annotation" method))) t)) (defmethod unset-annotation ((p phrase) key) (remove key (phrase-annotations p) :key #'car)) (defun make-phrase-from-vdoc (doc start len &optional (type nil)) (make-instance 'phrase :type type :document doc :start start :end (+ start len (- 1)))) (defmethod get-token-id ((p phrase) offset) (get-token-id (phrase-document p) (+ (phrase-start p) offset))) (defmethod get-tag ((p phrase) offset) (get-tag (phrase-document p) (+ (phrase-start p) offset))) (defmethod phrase-length ((p phrase)) (with-slots (end start) p (- end start -1))) (defun print-token-array (tokens start stop &key pos pos-start stream with-tags newline) (let ((offset (- pos-start start))) (loop for index from start upto stop do (if with-tags (format stream "~A/~A " (string-downcase (token-for-id (aref tokens index))) (aref pos (+ index offset))) (format stream "~A " (string-downcase (token-for-id (aref tokens index)))))) (when newline (format stream "~%")))) (defmethod print-phrase ((p phrase) &key (stream t) (with-tags t) (with-info nil) (newline t)) (with-slots (text tags) (phrase-document p) (when with-info (format stream "~A phrase: " (phrase-type p))) (print-token-array text (phrase-start p) (phrase-end p) :pos (if with-tags tags nil) :pos-start (if with-tags (phrase-start p) 0) :with-tags with-tags :stream stream :newline newline))) (defmethod phrase->string ((p phrase) &key (with-tags nil) (with-info nil) (newline nil)) (with-output-to-string (stream) (print-phrase p :stream stream :with-tags with-tags :with-info with-info :newline newline))) (defmethod phrase->token-array ((p phrase)) "Used in conceptnet to index into a node data structure NOTE: could be faster with direct, declared array copy" (make-array (phrase-length p) :element-type 'fixnum :initial-contents (phrase-words p) :adjustable nil)) (defmethod print-window ((p phrase) wsize &key (stream t) (with-tags t) (with-info nil) (newline t)) (with-slots (text tags) (phrase-document p) (let ((start (limit-min 0 (- (phrase-start p) wsize))) (end (limit-max (1- (length-of (phrase-document p))) (+ (phrase-end p) wsize)))) (loop for index from start upto end do (when with-info (format stream "~A phrase: " (phrase-type p))) (if with-tags (format stream "~A/~A " (token-for-id (aref text index)) (aref tags index)) (format stream "~A " (token-for-id (aref text index))))) (when newline (format stream "~%"))))) (defun token-array->words (tokens) (let ((words nil)) (map-across (lambda (word) (push word words)) tokens ) (nreverse words))) ;; (on-array (cons it rec) nil tokens)) (defun phrase-words (phrase &optional index) (assert phrase) (cond ((null index) (phrase-words phrase (phrase-start phrase))) ((>= index (1+ (phrase-end phrase))) nil) (t (cons (aref (document-text (phrase-document phrase)) index) (phrase-words phrase (1+ index)))))) ;; Phrase operations (defmethod copy-phrase ((p phrase) &optional (annotations t)) (make-instance 'phrase :type (phrase-type p) :document (phrase-document p) :start (phrase-start p) :end (phrase-end p) :annotations (when annotations (copy-list (phrase-annotations p))))) (defmethod phrase-distance ((p1 phrase) (p2 phrase)) "Distance between the nearest end of two phrases" (let* ((p1-start (slot-value p1 'start)) (p1-end (slot-value p1 'end)) (p2-start (slot-value p2 'start)) (p2-end (slot-value p2 'end))) (cond ((> p2-start p1-end) (- p2-start p1-end)) ((> p1-start p2-end) (- p1-start p2-end)) ((or (> p2-end p1-start) (> p1-end p2-start)) 0) (t (error "I didn't consider a case in phrase-distance"))))) (defmethod phrase-overlap ((ph1 phrase) (ph2 phrase)) (not (or (< (slot-value ph1 'end) (slot-value ph2 'start)) (< (slot-value ph2 'end) (slot-value ph2 'start))))) (defmethod phrase-equal ((ph1 phrase) (ph2 phrase)) (declare (optimize (speed 3) (safety 1) (debug 0))) (and (eq (phrase-length ph1) (phrase-length ph2)) (loop with text1 = (document-text (phrase-document ph1)) and text2 = (document-text (phrase-document ph2)) for i from (phrase-start ph1) upto (phrase-end ph1) for j from (phrase-start ph2) upto (phrase-end ph2) finally (return t) do (when (neq (aref text1 i) (aref text2 j)) (return nil))))) (defmethod phrase-lemmas ((ph phrase)) "Returns the lemmatized phrase represented by the underlying phrase" (mapcar #'get-lemma-for-id (phrase-words ph))) (defmethod print-phrase-lemmas ((ph phrase)) (apply #'concatenate (cons 'string (shuffle (mapcar #'token-for-id (phrase-lemmas ph)) (repeat " " (1- (phrase-length ph))))))) ;; ========================================================= ;; Altered phrase - keep doc refs, but change active content ;; ========================================================= ;; Allows us to lemma the original phrase but still ;; perform ops on it as phrases; means lots of generic ;; functions though... (defclass+ altered-phrase (phrase) ((custom-document nil)) (:prefix "altered-phrase-")) (defmethod get-token-id ((phrase altered-phrase) index) (get-token-id (altered-phrase-custom-document phrase) index)) (defmethod get-tag ((phrase altered-phrase) index) (get-tag (altered-phrase-custom-document phrase) index)) (defmethod make-document-from-phrase ((p phrase)) "Copy referenced phrase data into it's own document" (let ((start (phrase-start p)) (end (phrase-end p)) (text (document-text (phrase-document p))) (tags (document-tags (phrase-document p)))) (make-instance 'vector-document :text (subseq text start (1+ end)) :tags (subseq tags start (1+ end)) :annotations nil))) (defmethod make-alterable-phrase ((p phrase)) (change-class (copy-phrase p) 'altered-phrase :custom-document (make-document-from-phrase p))) Spoof the altered document as the original for most calls (defmethod phrase-document ((p altered-phrase)) (altered-phrase-custom-document p)) (defmethod phrase-start ((p altered-phrase)) 0) (defmethod phrase-end ((p altered-phrase)) (1- (length-of (altered-phrase-custom-document p)))) (defmethod phrase-length ((p altered-phrase)) (length-of (altered-phrase-custom-document p))) ;; Mutate the 'phrase' data (defmethod change-word ((p phrase) index new-token &optional new-pos) (change-word (change-class p 'altered-phrase :custom-document (make-document-from-phrase p)) index new-token new-pos)) (defmethod remove-word ((p phrase) index) (remove-word (change-class p 'altered-phrase :custom-document (make-document-from-phrase p)) index)) (defmethod change-word ((p altered-phrase) index new-token &optional new-pos) (let ((text (document-text (altered-phrase-custom-document p))) (tags (document-tags (altered-phrase-custom-document p)))) (setf (aref text index) new-token) (when new-pos (setf (aref tags index) new-pos)) p)) (defmethod remove-word ((p altered-phrase) index) (setf (document-text (phrase-document p)) (vector-1d-lshift (document-text (phrase-document p)) index 1)) (setf (document-tags (phrase-document p)) (vector-1d-lshift (document-tags (phrase-document p)) index 1))) (defmethod add-word ((p altered-phrase) index word tag) (setf (document-text (phrase-document p)) (vector-1d-rshift (document-text (phrase-document p)) index 1 :filler word)) (setf (document-tags (phrase-document p)) (vector-1d-rshift (document-tags (phrase-document p)) index 1 :filler tag))) ;; ================================= ;; Handle destructive lemmatization ;; ================================= (defmethod lemmatize-phrase ((p phrase) &optional (offset 0)) "Destructive lemmatization of a phrase" (let ((doc (phrase-document p)) (start (phrase-start p))) (when (<= offset (phrase-end p)) (loop for idx from (+ offset start) upto (phrase-end p) do (let ((token (get-token-id doc idx))) (awhen2 (get-lemma-for-id token :pos (get-tag doc idx) :noun nil) (when (not (eq it token)) (return (lemmatize-phrase (change-word p (- idx start) it) (1+ (- idx start)))))))))) p) (defparameter *test* nil) (defmethod lemmatize-phrase ((p altered-phrase) &optional (offset 0)) "Destructive lemmatization of a phrase" (let ((doc (phrase-document p))) (setf *test* p) (when (<= offset (phrase-end p)) (loop for idx from (+ offset (phrase-start p)) upto (phrase-end p) do (let ((token (get-token-id doc idx))) (awhen2 (get-lemma-for-id token :pos (get-tag doc idx) :noun nil) (when (not (eq it token)) (change-word p idx it))))))) p)
null
https://raw.githubusercontent.com/eslick/cl-langutils/38beec7a82eeb35b0bfb0824a41d13ed94fc648b/src/reference.lisp
lisp
Syntax : ANSI - Common - Lisp ; Base : 10 ; Package : utils -*- ************************************************************************* FILE IDENTIFICATION Name: reference Purpose: A wrapper around vector representations of text --------------------------- Document wrapper text vector tag vector Document accessors Create a vector document from a file or text Documents to/from strings Documents to/from files in native form keeps the data 'in the family' ======================================================== Phrase wrapper ======================================================== phrase type pointer or id if in registry offset in doc end in doc (labels ((expand-if-person () (let ((offset (person-token-offset p))) (when (> offset -1) (mapcan #'(lambda ( (on-array (cons it rec) nil tokens)) Phrase operations ========================================================= Altered phrase - keep doc refs, but change active content ========================================================= Allows us to lemma the original phrase but still perform ops on it as phrases; means lots of generic functions though... Mutate the 'phrase' data ================================= Handle destructive lemmatization =================================
Programmer : Date Started : October 2004 (in-package :langutils) (defclass vector-document () :accessor document-text :initarg :text :type (array fixnum)) :accessor document-tags :initarg :tags :type (array symbol)) (annotations :accessor document-annotations :initarg :annotations :initform nil :type list))) (defmethod length-of ((doc vector-document)) (length (document-text doc))) (defun make-vector-document (text &optional tags) (make-instance 'vector-document :text text :tags tags)) (defmethod get-token-id ((doc vector-document) offset) (aref (document-text doc) offset)) (defmethod get-tag ((doc vector-document) offset) (aref (document-tags doc) offset)) (defmethod get-annotation ((doc vector-document) key) "First returned value is the association value or null if none. The second is true if the key exists, nil otherwise" (aif (assoc key (document-annotations doc)) (values (cdr it) t) (values nil nil))) (defmethod set-annotation ((doc vector-document) key value &key (method :override)) "Add an annotation to object using method :override, :push, :duplicate-key" (flet ((set-on-empty () (assoc-setf (document-annotations doc) key value 'eq))) (case method (:override (aif (assoc key (document-annotations doc)) (rplacd it value) (set-on-empty))) (:push (aif (assoc key (document-annotations doc)) (push value (cdr it)) (set-on-empty))) (:duplicate-key (setf (document-annotations doc) (acons key value (document-annotations doc)))) (t (error "Invalid method ~A for add-annotation" method))) t)) (defmethod unset-annotation ((doc vector-document) key) (remove key (document-annotations doc) :key #'car)) (defun vector-document (input) (typecase input (string (vector-tag input)) (pathname (read-vector-document input)) (vector-document input) (t (error "No handler for input type: ~A" (type-of input))))) (defun string-tag ( string &optional (stream t)) "Tokenizes and tags the string returning a standard tagged string using '/' as a separator" (string-tag-tokenized (mvretn 3 (tokenize-string string)) stream)) (defun string-tag-tokenized ( string &optional (stream t)) (print-vector-document (vector-tag string) :stream stream)) (defmethod vector-document-string ( (doc vector-document) &key (with-tags nil) (with-newline nil) ) (with-output-to-string (stream) (print-vector-document doc :stream stream :with-tags with-tags :with-newline with-newline))) (defmethod print-vector-document ( (doc vector-document) &key (stream t) (with-tags t) (with-newline t) ) (with-slots (text tags) doc (loop for token fixnum across (document-text doc) and tag symbol across (document-tags doc) do (if with-tags (format stream "~A/~A " (token-for-id token) tag) (format stream "~A " (token-for-id token)))) (when with-newline (format stream "~%")))) (defmethod vector-document-words ( (doc vector-document) ) (token-array->words (document-text doc))) (defmethod vector-doc-as-ids ( (doc vector-document) ) "Converts the word array to ids with shared structure so the source or destination documents should be short lived" (let* ((word-array (document-text doc)) (id-array (make-array (length word-array) :element-type 'fixnum))) (make-instance 'vector-document :text (map-into id-array #'id-for-token word-array) :tags (document-tags doc) :annotations (document-annotations doc)))) (defmethod vector-doc-as-words ( (doc vector-document) ) (let* ((id-array (document-text doc)) (word-array (make-array (length id-array) :element-type 'string))) (make-instance 'vector-document :text (map-into word-array #'token-for-id id-array) :tags (document-tags doc) :annotations (document-annotations doc)))) (defmethod write-vector-document ((doc vector-document) filename &key (with-tags t) (if-exists :supersede)) (with-open-file (s filename :direction :output :if-exists if-exists) (print-vector-document doc :stream s :with-tags with-tags))) (defmethod read-vector-document (filename) (vector-tag (read-file-to-string filename))) (defmethod read-vector-document-to-string ((doc vector-document) &key (with-tags t)) (with-output-to-string (s) (print-vector-document doc :with-tags with-tags :stream s))) (defmethod document-window-as-string (document start end) (apply #'concatenate 'string (shuffle (mapcar #'token-for-id (subseq (document-text document) start end)) (repeat " " (- end start))))) (defclass+ phrase () (annotations nil)) (:prefix "phrase-")) (defmethod print-object ((p phrase) stream) (let ((pstr (make-string-output-stream))) (print-phrase p :stream pstr :with-tags nil :newline nil) (format stream "#<~A:~A \"~A\">" (class-name (class-of p)) (phrase-type p) (get-output-stream-string pstr)))) (defun make-phrase-from-sentence (tok-string &optional tag-array) (let ((words (extract-words tok-string))) (make-phrase (map-into (make-array (length words)) #'id-for-token words) tag-array))) (defun make-phrase (text-array tag-array &optional type) "Take two arrays of test and tags and create a phrase that points at a vdoc created from the two arrays" (make-phrase-from-vdoc (vector-doc-as-ids (make-vector-document text-array tag-array)) 0 (length text-array) type)) (defparameter *temp-phrase* nil) (defun temp-phrase () (unless *temp-phrase* (setf *temp-phrase* (make-phrase nil nil nil))) *temp-phrase*) (defmethod find-phrase ((p phrase) (doc vector-document) &key (match :all) (start 0) (ignore-start nil) (ignore-end nil) (lemma nil) (concept-terms nil)) "Find the specified phrase starting at start, matching text and/or tags according to match. The lemma parameter indicates whether the phrases match under the lemma operator and ignore-start and ignore-end causes the search to not match a region within the document" (declare (optimize (speed 3) (safety 1) (space 0)) (type fixnum start)) (if (eq (phrase-document p) doc) (values (phrase-start p) (phrase-end p)) (let ((ptext (document-text (phrase-document p))) (dtext (document-text doc)) (ptags (document-tags (phrase-document p))) (dtags (document-tags doc))) (declare (type (array fixnum *) dtext) (type (array symbol *) ptext)) (labels ((match-tokens (doc-offset phrase-offset) (declare (type fixnum doc-offset phrase-offset)) (if (and ignore-start ignore-end (>= doc-offset ignore-start) (<= doc-offset ignore-end)) nil (case match (:all (and (match-text doc-offset phrase-offset) (match-tags doc-offset phrase-offset))) (:words (match-text doc-offset phrase-offset)) (:pos (match-tags doc-offset phrase-offset)) (t nil)))) (match-text (d p) (declare (type fixnum d p)) (cond ((and concept-terms (eq (aref ptext p) (id-for-token "person"))) (member (aref dtext d) (mapcar #'id-for-token '("I" "him" "her" "they" "them" "me" "you" "us")))) ((and concept-terms (eq (aref ptext p) (id-for-token "something"))) (eq (aref dtext d) (id-for-token "it"))) (lemma (eq (get-lemma (aref ptext p)) (get-lemma (aref dtext d)))) (t (eq (aref ptext p) (aref dtext d))))) (match-tags (d p) (declare (type fixnum d p)) (eq (aref ptags p) (aref dtags d)))) (loop for offset fixnum from start upto (1- (length dtext)) finally (return nil) do (when (match-tokens offset 0) (when (loop for pindex from 0 for dindex from offset while (and (< pindex (length ptext)) (< dindex (length dtext))) finally (return t) do (unless (match-tokens dindex pindex) (return nil))) (return (values offset (+ offset (1- (length ptext)))))))))))) (defmethod find-phrase-intervals ((p phrase) (doc vector-document) &key (match :all) (start 0) (lemma nil) (concept-terms nil) &aux results) "Find all phrase intervals in the vector document" (loop while (< start (1- (length-of doc))) do (mvbind (front back) (find-phrase p doc :match match :start start :lemma lemma :concept-terms concept-terms) (if (and front back) (progn (push (cons front back) results) (setf start (1+ back))) (return)))) (nreverse results)) (defmethod find-phrase-intervals ((p array) (doc vector-document) &key (match :words) (start 0) (lemma nil) (concept-terms nil) &aux results) "Find all phrase intervals in the vector document" (declare (ignore match) (optimize (speed 3) (space 0) (safety 1)) (type fixnum start) (type list results)) ( setf results (loop while (< start (1- (length-of doc))) do (mvbind (front back) (find-phrase (make-phrase p nil) doc :match :words :start start :lemma lemma :concept-terms concept-terms) (declare (type (or fixnum nil) front back)) (if (and front back) (progn (push (cons front back) results) (setf start (1+ back))) (return)))) (nreverse results)) (defun person-token-offset (array) (let ((person (id-for-token "person"))) (loop for token across array for offset from 0 do (when (eq token person) (return-from person-token-offset t))))) (defmethod get-annotation ((p phrase) key) "First returned value is the association value or null if none. The second is true if the key exists, nil otherwise" (aif (assoc key (phrase-annotations p)) (values (cdr it) t) (values nil nil))) (defmethod set-annotation ((p phrase) key value &key (method :override)) "Add an annotation to object using method :override, :push, :duplicate-key" (flet ((set-on-empty () (setf (phrase-annotations p) (acons key value nil)))) (case method (:override (aif (assoc key (phrase-annotations p)) (rplacd it value) (set-on-empty))) (:push (aif (assoc key (phrase-annotations p)) (push value (cdr it)) (set-on-empty))) (:duplicate-key (setf (phrase-annotations p) (acons key value (phrase-annotations p)))) (t (error "Invalid method ~A for add-annotation" method))) t)) (defmethod unset-annotation ((p phrase) key) (remove key (phrase-annotations p) :key #'car)) (defun make-phrase-from-vdoc (doc start len &optional (type nil)) (make-instance 'phrase :type type :document doc :start start :end (+ start len (- 1)))) (defmethod get-token-id ((p phrase) offset) (get-token-id (phrase-document p) (+ (phrase-start p) offset))) (defmethod get-tag ((p phrase) offset) (get-tag (phrase-document p) (+ (phrase-start p) offset))) (defmethod phrase-length ((p phrase)) (with-slots (end start) p (- end start -1))) (defun print-token-array (tokens start stop &key pos pos-start stream with-tags newline) (let ((offset (- pos-start start))) (loop for index from start upto stop do (if with-tags (format stream "~A/~A " (string-downcase (token-for-id (aref tokens index))) (aref pos (+ index offset))) (format stream "~A " (string-downcase (token-for-id (aref tokens index)))))) (when newline (format stream "~%")))) (defmethod print-phrase ((p phrase) &key (stream t) (with-tags t) (with-info nil) (newline t)) (with-slots (text tags) (phrase-document p) (when with-info (format stream "~A phrase: " (phrase-type p))) (print-token-array text (phrase-start p) (phrase-end p) :pos (if with-tags tags nil) :pos-start (if with-tags (phrase-start p) 0) :with-tags with-tags :stream stream :newline newline))) (defmethod phrase->string ((p phrase) &key (with-tags nil) (with-info nil) (newline nil)) (with-output-to-string (stream) (print-phrase p :stream stream :with-tags with-tags :with-info with-info :newline newline))) (defmethod phrase->token-array ((p phrase)) "Used in conceptnet to index into a node data structure NOTE: could be faster with direct, declared array copy" (make-array (phrase-length p) :element-type 'fixnum :initial-contents (phrase-words p) :adjustable nil)) (defmethod print-window ((p phrase) wsize &key (stream t) (with-tags t) (with-info nil) (newline t)) (with-slots (text tags) (phrase-document p) (let ((start (limit-min 0 (- (phrase-start p) wsize))) (end (limit-max (1- (length-of (phrase-document p))) (+ (phrase-end p) wsize)))) (loop for index from start upto end do (when with-info (format stream "~A phrase: " (phrase-type p))) (if with-tags (format stream "~A/~A " (token-for-id (aref text index)) (aref tags index)) (format stream "~A " (token-for-id (aref text index))))) (when newline (format stream "~%"))))) (defun token-array->words (tokens) (let ((words nil)) (map-across (lambda (word) (push word words)) tokens ) (nreverse words))) (defun phrase-words (phrase &optional index) (assert phrase) (cond ((null index) (phrase-words phrase (phrase-start phrase))) ((>= index (1+ (phrase-end phrase))) nil) (t (cons (aref (document-text (phrase-document phrase)) index) (phrase-words phrase (1+ index)))))) (defmethod copy-phrase ((p phrase) &optional (annotations t)) (make-instance 'phrase :type (phrase-type p) :document (phrase-document p) :start (phrase-start p) :end (phrase-end p) :annotations (when annotations (copy-list (phrase-annotations p))))) (defmethod phrase-distance ((p1 phrase) (p2 phrase)) "Distance between the nearest end of two phrases" (let* ((p1-start (slot-value p1 'start)) (p1-end (slot-value p1 'end)) (p2-start (slot-value p2 'start)) (p2-end (slot-value p2 'end))) (cond ((> p2-start p1-end) (- p2-start p1-end)) ((> p1-start p2-end) (- p1-start p2-end)) ((or (> p2-end p1-start) (> p1-end p2-start)) 0) (t (error "I didn't consider a case in phrase-distance"))))) (defmethod phrase-overlap ((ph1 phrase) (ph2 phrase)) (not (or (< (slot-value ph1 'end) (slot-value ph2 'start)) (< (slot-value ph2 'end) (slot-value ph2 'start))))) (defmethod phrase-equal ((ph1 phrase) (ph2 phrase)) (declare (optimize (speed 3) (safety 1) (debug 0))) (and (eq (phrase-length ph1) (phrase-length ph2)) (loop with text1 = (document-text (phrase-document ph1)) and text2 = (document-text (phrase-document ph2)) for i from (phrase-start ph1) upto (phrase-end ph1) for j from (phrase-start ph2) upto (phrase-end ph2) finally (return t) do (when (neq (aref text1 i) (aref text2 j)) (return nil))))) (defmethod phrase-lemmas ((ph phrase)) "Returns the lemmatized phrase represented by the underlying phrase" (mapcar #'get-lemma-for-id (phrase-words ph))) (defmethod print-phrase-lemmas ((ph phrase)) (apply #'concatenate (cons 'string (shuffle (mapcar #'token-for-id (phrase-lemmas ph)) (repeat " " (1- (phrase-length ph))))))) (defclass+ altered-phrase (phrase) ((custom-document nil)) (:prefix "altered-phrase-")) (defmethod get-token-id ((phrase altered-phrase) index) (get-token-id (altered-phrase-custom-document phrase) index)) (defmethod get-tag ((phrase altered-phrase) index) (get-tag (altered-phrase-custom-document phrase) index)) (defmethod make-document-from-phrase ((p phrase)) "Copy referenced phrase data into it's own document" (let ((start (phrase-start p)) (end (phrase-end p)) (text (document-text (phrase-document p))) (tags (document-tags (phrase-document p)))) (make-instance 'vector-document :text (subseq text start (1+ end)) :tags (subseq tags start (1+ end)) :annotations nil))) (defmethod make-alterable-phrase ((p phrase)) (change-class (copy-phrase p) 'altered-phrase :custom-document (make-document-from-phrase p))) Spoof the altered document as the original for most calls (defmethod phrase-document ((p altered-phrase)) (altered-phrase-custom-document p)) (defmethod phrase-start ((p altered-phrase)) 0) (defmethod phrase-end ((p altered-phrase)) (1- (length-of (altered-phrase-custom-document p)))) (defmethod phrase-length ((p altered-phrase)) (length-of (altered-phrase-custom-document p))) (defmethod change-word ((p phrase) index new-token &optional new-pos) (change-word (change-class p 'altered-phrase :custom-document (make-document-from-phrase p)) index new-token new-pos)) (defmethod remove-word ((p phrase) index) (remove-word (change-class p 'altered-phrase :custom-document (make-document-from-phrase p)) index)) (defmethod change-word ((p altered-phrase) index new-token &optional new-pos) (let ((text (document-text (altered-phrase-custom-document p))) (tags (document-tags (altered-phrase-custom-document p)))) (setf (aref text index) new-token) (when new-pos (setf (aref tags index) new-pos)) p)) (defmethod remove-word ((p altered-phrase) index) (setf (document-text (phrase-document p)) (vector-1d-lshift (document-text (phrase-document p)) index 1)) (setf (document-tags (phrase-document p)) (vector-1d-lshift (document-tags (phrase-document p)) index 1))) (defmethod add-word ((p altered-phrase) index word tag) (setf (document-text (phrase-document p)) (vector-1d-rshift (document-text (phrase-document p)) index 1 :filler word)) (setf (document-tags (phrase-document p)) (vector-1d-rshift (document-tags (phrase-document p)) index 1 :filler tag))) (defmethod lemmatize-phrase ((p phrase) &optional (offset 0)) "Destructive lemmatization of a phrase" (let ((doc (phrase-document p)) (start (phrase-start p))) (when (<= offset (phrase-end p)) (loop for idx from (+ offset start) upto (phrase-end p) do (let ((token (get-token-id doc idx))) (awhen2 (get-lemma-for-id token :pos (get-tag doc idx) :noun nil) (when (not (eq it token)) (return (lemmatize-phrase (change-word p (- idx start) it) (1+ (- idx start)))))))))) p) (defparameter *test* nil) (defmethod lemmatize-phrase ((p altered-phrase) &optional (offset 0)) "Destructive lemmatization of a phrase" (let ((doc (phrase-document p))) (setf *test* p) (when (<= offset (phrase-end p)) (loop for idx from (+ offset (phrase-start p)) upto (phrase-end p) do (let ((token (get-token-id doc idx))) (awhen2 (get-lemma-for-id token :pos (get-tag doc idx) :noun nil) (when (not (eq it token)) (change-word p idx it))))))) p)
6ee5809e65d2a1135c2eed0c184e20d43995c28b241e38b748818cb84ea5e8b8
juliannagele/ebso
evm_stack.ml
Copyright 2019 and under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) open Core open Z3util module PC = Program_counter module SI = Stack_index type t = { el : Z3.Expr.expr -> Z3.Expr.expr -> Z3.Expr.expr; decl : Z3.FuncDecl.func_decl; ctr_decl : Z3.FuncDecl.func_decl; ctr : Z3.Expr.expr -> Z3.Expr.expr; } let mk ea idx = let mk_vars_sorts vs = List.map vs ~f:(fun _ -> !Word.sort) in let vars_sorts = mk_vars_sorts (Enc_consts.forall_vars ea) in let sk = func_decl ("stack" ^ idx) (vars_sorts @ [PC.sort; !SI.sort]) !Word.sort in let c = func_decl ("sc" ^ idx) [PC.sort] !SI.sort in { (* stack(x0 ... x(sd-1), j, n) = nth word on stack after j instructions starting from a stack that contained words x0 ... x(sd-1) *) el = (fun j n -> sk <@@> (Enc_consts.forall_vars ea @ [j; n])); decl = sk; sc(j ) = index of the next free slot on the stack after j instructions ctr_decl = c; ctr = (fun j -> c <@@> [j]); } let init sk skd xs = let open Z3Ops in set stack counter to skd (sk.ctr PC.init == SI.enc skd) (* set inital words on stack *) && conj (List.mapi xs ~f:(fun i x -> sk.el PC.init (SI.enc i) == x)) let enc_equiv_at sks skt js jt = let open Z3Ops in let n = SI.const "n" in (* source and target stack counter are equal *) sks.ctr js == skt.ctr jt && (* source and target stack are equal below the stack counter; note that it doesn't matter which stack counter is used, they are equal *) (forall n ((n < skt.ctr jt) ==> ((sks.el js n) == (skt.el jt n)))) (* get the top d elements of the stack *) let enc_top_d sk j d = let open Z3Ops in let pos l = (sk.ctr j) - SI.enc (Int.succ l) in List.init d ~f:(fun l -> sk.el j (pos l)) let enc_push a sk j x = let open Z3Ops in (* the stack after the PUSH *) let sk' n = sk.el (j + one) n in (* the stack counter before the PUSH *) let sc = sk.ctr j in (* the new top word will be x *) sk' sc == Pusharg.enc a j x (* the only effect of POP is to change the stack counter *) let enc_pop _ _ = top let enc_unaryop sk j op = let open Z3Ops in let sc = sk.ctr j and sc'= sk.ctr (j + one) in (sk.el (j + one) (sc' - SI.enc 1) == op (sk.el j (sc - SI.enc 1))) let enc_binop sk j op = let open Z3Ops in let sc = sk.ctr j and sc'= sk.ctr (j + one) in the new top word is the result of applying op to the previous two (sk.el (j + one) (sc' - SI.enc 1) == op (sk.el j (sc - SI.enc 1)) (sk.el j (sc - SI.enc 2))) let enc_ternaryop sk j op = let open Z3Ops in let sc = sk.ctr j and sc'= sk.ctr (j + one) in let w3 = sk.el j (sc - SI.enc 3) and w2 = sk.el j (sc - SI.enc 2) and w1 = sk.el j (sc - SI.enc 1) in sk.el (j + one) (sc' - SI.enc 1) == op w1 w2 w3 let enc_swap sk j idx = let sc_idx = SI.enc (idx + 1) in let open Z3Ops in let sc = sk.ctr j and sc'= sk.ctr (j + one) in the new top word is the 1+idx'th from the old stack (sk.el (j + one) (sc' - SI.enc 1) == sk.el j (sc - sc_idx)) && the new 1+idx'th word is the top from the old stack (sk.el (j + one) (sc' - sc_idx) == sk.el j (sc - SI.enc 1)) && the words between top and are not touched conj (List.init (Int.pred idx) ~f:(fun i -> let sc_iidx = SI.enc (Int.(-) idx i) in (sk.el (j + one) (sc' - sc_iidx) == sk.el j (sc - sc_iidx)))) let enc_dup sk j idx = let sc_idx = SI.enc idx in let open Z3Ops in let sc = sk.ctr j and sc'= sk.ctr (j + one) in (* the new top word is the idx'th from the old stack *) (sk.el (j + one) (sc' - SI.enc 1) == sk.el j (sc - sc_idx)) && (* all words down to idx are not touched *) conj (List.init idx ~f:(fun i -> let sc_iidx = SI.enc (Int.(-) idx i) in (sk.el (j + one) (sc - sc_iidx) == sk.el j (sc - sc_iidx)))) let pres is sk j = let open Z3Ops in let (d, _) = Instruction.delta_alpha is in let n = SI.const "n" in let sc = sk.ctr j in (* all words below d stay the same *) (forall n ((n < sc - SI.enc d) ==> (sk.el (j + one) n == sk.el j n))) let enc_stack_ctr is sk j = let (d, a) = Instruction.delta_alpha is in let diff = (a - d) in let open Z3Ops in sk.ctr (j + one) == (sk.ctr j + SI.enc diff)
null
https://raw.githubusercontent.com/juliannagele/ebso/8e516036fcb98074b6be14fc81ae020f76977712/lib/evm_stack.ml
ocaml
stack(x0 ... x(sd-1), j, n) = nth word on stack after j instructions starting from a stack that contained words x0 ... x(sd-1) set inital words on stack source and target stack counter are equal source and target stack are equal below the stack counter; note that it doesn't matter which stack counter is used, they are equal get the top d elements of the stack the stack after the PUSH the stack counter before the PUSH the new top word will be x the only effect of POP is to change the stack counter the new top word is the idx'th from the old stack all words down to idx are not touched all words below d stay the same
Copyright 2019 and under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) open Core open Z3util module PC = Program_counter module SI = Stack_index type t = { el : Z3.Expr.expr -> Z3.Expr.expr -> Z3.Expr.expr; decl : Z3.FuncDecl.func_decl; ctr_decl : Z3.FuncDecl.func_decl; ctr : Z3.Expr.expr -> Z3.Expr.expr; } let mk ea idx = let mk_vars_sorts vs = List.map vs ~f:(fun _ -> !Word.sort) in let vars_sorts = mk_vars_sorts (Enc_consts.forall_vars ea) in let sk = func_decl ("stack" ^ idx) (vars_sorts @ [PC.sort; !SI.sort]) !Word.sort in let c = func_decl ("sc" ^ idx) [PC.sort] !SI.sort in { el = (fun j n -> sk <@@> (Enc_consts.forall_vars ea @ [j; n])); decl = sk; sc(j ) = index of the next free slot on the stack after j instructions ctr_decl = c; ctr = (fun j -> c <@@> [j]); } let init sk skd xs = let open Z3Ops in set stack counter to skd (sk.ctr PC.init == SI.enc skd) && conj (List.mapi xs ~f:(fun i x -> sk.el PC.init (SI.enc i) == x)) let enc_equiv_at sks skt js jt = let open Z3Ops in let n = SI.const "n" in sks.ctr js == skt.ctr jt && (forall n ((n < skt.ctr jt) ==> ((sks.el js n) == (skt.el jt n)))) let enc_top_d sk j d = let open Z3Ops in let pos l = (sk.ctr j) - SI.enc (Int.succ l) in List.init d ~f:(fun l -> sk.el j (pos l)) let enc_push a sk j x = let open Z3Ops in let sk' n = sk.el (j + one) n in let sc = sk.ctr j in sk' sc == Pusharg.enc a j x let enc_pop _ _ = top let enc_unaryop sk j op = let open Z3Ops in let sc = sk.ctr j and sc'= sk.ctr (j + one) in (sk.el (j + one) (sc' - SI.enc 1) == op (sk.el j (sc - SI.enc 1))) let enc_binop sk j op = let open Z3Ops in let sc = sk.ctr j and sc'= sk.ctr (j + one) in the new top word is the result of applying op to the previous two (sk.el (j + one) (sc' - SI.enc 1) == op (sk.el j (sc - SI.enc 1)) (sk.el j (sc - SI.enc 2))) let enc_ternaryop sk j op = let open Z3Ops in let sc = sk.ctr j and sc'= sk.ctr (j + one) in let w3 = sk.el j (sc - SI.enc 3) and w2 = sk.el j (sc - SI.enc 2) and w1 = sk.el j (sc - SI.enc 1) in sk.el (j + one) (sc' - SI.enc 1) == op w1 w2 w3 let enc_swap sk j idx = let sc_idx = SI.enc (idx + 1) in let open Z3Ops in let sc = sk.ctr j and sc'= sk.ctr (j + one) in the new top word is the 1+idx'th from the old stack (sk.el (j + one) (sc' - SI.enc 1) == sk.el j (sc - sc_idx)) && the new 1+idx'th word is the top from the old stack (sk.el (j + one) (sc' - sc_idx) == sk.el j (sc - SI.enc 1)) && the words between top and are not touched conj (List.init (Int.pred idx) ~f:(fun i -> let sc_iidx = SI.enc (Int.(-) idx i) in (sk.el (j + one) (sc' - sc_iidx) == sk.el j (sc - sc_iidx)))) let enc_dup sk j idx = let sc_idx = SI.enc idx in let open Z3Ops in let sc = sk.ctr j and sc'= sk.ctr (j + one) in (sk.el (j + one) (sc' - SI.enc 1) == sk.el j (sc - sc_idx)) && conj (List.init idx ~f:(fun i -> let sc_iidx = SI.enc (Int.(-) idx i) in (sk.el (j + one) (sc - sc_iidx) == sk.el j (sc - sc_iidx)))) let pres is sk j = let open Z3Ops in let (d, _) = Instruction.delta_alpha is in let n = SI.const "n" in let sc = sk.ctr j in (forall n ((n < sc - SI.enc d) ==> (sk.el (j + one) n == sk.el j n))) let enc_stack_ctr is sk j = let (d, a) = Instruction.delta_alpha is in let diff = (a - d) in let open Z3Ops in sk.ctr (j + one) == (sk.ctr j + SI.enc diff)
d6057f0035cd757905e86f3d0c457c82069872d19ae0b8607559f6f54618cbf2
evturn/haskellbook
21.12-traversable-instances.hs
import Test.QuickCheck import Test.QuickCheck.Checkers import Test.QuickCheck.Classes type IIIs = (Int, Int, [Int]) ----------------------------------------------------------------------------- -- Identity -- newtype Identity a = Identity a deriving (Eq, Ord, Show) instance Functor Identity where fmap f (Identity x) = Identity (f x) instance Foldable Identity where foldr f z (Identity y) = f y z instance Traversable Identity where traverse f (Identity x) = Identity <$> f x instance Arbitrary a => Arbitrary (Identity a) where arbitrary = do x <- arbitrary return $ Identity x instance Eq a => EqProp (Identity a) where (=-=) = eq identityTraversable :: Identity IIIs identityTraversable = undefined ----------------------------------------------------------------------------- -- Constant -- newtype Constant a b = Constant { getConstant :: a } deriving (Eq, Show) instance Functor (Constant a) where fmap _ (Constant y) = Constant y instance Foldable (Constant a) where foldr _ z _ = z instance Traversable (Constant a) where traverse f (Constant x) = pure $ Constant x instance (Arbitrary a, Arbitrary b) => Arbitrary (Constant a b) where arbitrary = do x <- arbitrary return $ Constant x instance (Eq a, Eq b) => EqProp (Constant a b) where (=-=) = eq constantTraversable :: Constant Int IIIs constantTraversable = undefined ----------------------------------------------------------------------------- -- Maybe -- data Optional a = Nada | Yep a deriving (Eq, Show) instance Functor Optional where fmap _ Nada = Nada fmap f (Yep x) = Yep (f x) instance Foldable Optional where foldMap _ Nada = mempty foldMap f (Yep x) = f x instance Traversable Optional where traverse _ Nada = pure Nada traverse f (Yep x) = Yep <$> f x instance Arbitrary a => Arbitrary (Optional a) where arbitrary = do x <- arbitrary elements [ Nada , Yep x ] instance Eq a => EqProp (Optional a) where (=-=) = eq maybeTraversable :: Optional IIIs maybeTraversable = undefined ----------------------------------------------------------------------------- -- List data List a = Nil | Cons a (List a) deriving (Eq, Show) instance Functor List where fmap _ Nil = Nil fmap f (Cons x y) = Cons (f x) (fmap f y) instance Foldable List where foldMap _ Nil = mempty foldMap f (Cons x y) = f x `mappend` foldMap f y instance Traversable List where traverse _ Nil = pure Nil traverse f (Cons x y) = Cons <$> f x <*> traverse f y instance Arbitrary a => Arbitrary (List a) where arbitrary = do x <- arbitrary return $ Cons x Nil instance Eq a => EqProp (List a) where (=-=) = eq listTraversable :: List IIIs listTraversable = undefined ----------------------------------------------------------------------------- Three data Three a b c = Three a b c deriving (Eq, Show) instance Functor (Three a b) where fmap f (Three x y z) = Three x y (f z) instance Foldable (Three a b) where foldMap f (Three _ _ z) = f z instance Traversable (Three a b) where traverse f (Three x y z) = Three x y <$> f z instance ( Arbitrary a , Arbitrary b , Arbitrary c ) => Arbitrary (Three a b c) where arbitrary = do x <- arbitrary y <- arbitrary z <- arbitrary return $ Three x y z instance (Eq a, Eq b, Eq c) => EqProp (Three a b c) where (=-=) = eq threeTraversable :: Three Int Int IIIs threeTraversable = undefined ----------------------------------------------------------------------------- -- Pair data Pair a b = Pair a b deriving (Eq, Show) instance Functor (Pair a) where fmap f (Pair x y) = Pair x (f y) instance Foldable (Pair a) where foldMap f (Pair _ y) = f y instance Traversable (Pair a) where traverse f (Pair x y) = Pair x <$> f y instance (Arbitrary a, Arbitrary b) => Arbitrary (Pair a b) where arbitrary = do x <- arbitrary y <- arbitrary return $ Pair x y instance (Eq a, Eq b) => EqProp (Pair a b) where (=-=) = eq pairTraversable :: Pair Int IIIs pairTraversable = undefined ----------------------------------------------------------------------------- -- Big data Big a b = Big a b b deriving (Eq, Show) instance Functor (Big a) where fmap f (Big x y y') = Big x (f y) (f y') instance Foldable (Big a) where foldMap f (Big _ y y') = f y `mappend` f y' instance Traversable (Big a) where traverse f (Big x y y') = Big x <$> f y <*> f y' instance (Arbitrary a, Arbitrary b) => Arbitrary (Big a b) where arbitrary = do x <- arbitrary y <- arbitrary return $ Big x y y instance (Eq a, Eq b) => EqProp (Big a b) where (=-=) = eq bigTraversable :: Big Int IIIs bigTraversable = undefined ----------------------------------------------------------------------------- -- Bigger data Bigger a b = Bigger a b b b deriving (Eq, Show) instance Functor (Bigger a) where fmap f (Bigger x y y' y'') = Bigger x (f y) (f y') (f y'') instance Foldable (Bigger a) where foldMap f (Bigger _ y y' y'') = f y `mappend` f y' `mappend` f y'' instance Traversable (Bigger a) where traverse f (Bigger x y y' y'')= Bigger x <$> f y <*> f y' <*> f y'' instance (Arbitrary a, Arbitrary b) => Arbitrary (Bigger a b) where arbitrary = do x <- arbitrary y <- arbitrary return $ Bigger x y y y instance (Eq a, Eq b) => EqProp (Bigger a b) where (=-=) = eq biggerTraversable :: Bigger Int IIIs biggerTraversable = undefined ----------------------------------------------------------------------------- main :: IO () main = do putStrLn "\n-- Identity" quickBatch $ functor identityTraversable quickBatch $ traversable identityTraversable putStrLn "\n-- Constant" quickBatch $ functor constantTraversable quickBatch $ traversable constantTraversable putStrLn "\n-- Maybe" quickBatch $ functor maybeTraversable quickBatch $ traversable maybeTraversable putStrLn "\n-- List" quickBatch $ functor listTraversable quickBatch $ traversable listTraversable putStrLn "\n-- Three" quickBatch $ functor threeTraversable putStrLn "\n-- Pair" quickBatch $ functor pairTraversable quickBatch $ traversable pairTraversable putStrLn "\n-- Big" quickBatch $ functor bigTraversable quickBatch $ traversable bigTraversable putStrLn "\n-- Bigger" quickBatch $ functor biggerTraversable quickBatch $ traversable biggerTraversable
null
https://raw.githubusercontent.com/evturn/haskellbook/3d310d0ddd4221ffc5b9fd7ec6476b2a0731274a/21/21.12-traversable-instances.hs
haskell
--------------------------------------------------------------------------- Identity --------------------------------------------------------------------------- Constant --------------------------------------------------------------------------- Maybe --------------------------------------------------------------------------- List --------------------------------------------------------------------------- --------------------------------------------------------------------------- Pair --------------------------------------------------------------------------- Big --------------------------------------------------------------------------- Bigger ---------------------------------------------------------------------------
import Test.QuickCheck import Test.QuickCheck.Checkers import Test.QuickCheck.Classes type IIIs = (Int, Int, [Int]) newtype Identity a = Identity a deriving (Eq, Ord, Show) instance Functor Identity where fmap f (Identity x) = Identity (f x) instance Foldable Identity where foldr f z (Identity y) = f y z instance Traversable Identity where traverse f (Identity x) = Identity <$> f x instance Arbitrary a => Arbitrary (Identity a) where arbitrary = do x <- arbitrary return $ Identity x instance Eq a => EqProp (Identity a) where (=-=) = eq identityTraversable :: Identity IIIs identityTraversable = undefined newtype Constant a b = Constant { getConstant :: a } deriving (Eq, Show) instance Functor (Constant a) where fmap _ (Constant y) = Constant y instance Foldable (Constant a) where foldr _ z _ = z instance Traversable (Constant a) where traverse f (Constant x) = pure $ Constant x instance (Arbitrary a, Arbitrary b) => Arbitrary (Constant a b) where arbitrary = do x <- arbitrary return $ Constant x instance (Eq a, Eq b) => EqProp (Constant a b) where (=-=) = eq constantTraversable :: Constant Int IIIs constantTraversable = undefined data Optional a = Nada | Yep a deriving (Eq, Show) instance Functor Optional where fmap _ Nada = Nada fmap f (Yep x) = Yep (f x) instance Foldable Optional where foldMap _ Nada = mempty foldMap f (Yep x) = f x instance Traversable Optional where traverse _ Nada = pure Nada traverse f (Yep x) = Yep <$> f x instance Arbitrary a => Arbitrary (Optional a) where arbitrary = do x <- arbitrary elements [ Nada , Yep x ] instance Eq a => EqProp (Optional a) where (=-=) = eq maybeTraversable :: Optional IIIs maybeTraversable = undefined data List a = Nil | Cons a (List a) deriving (Eq, Show) instance Functor List where fmap _ Nil = Nil fmap f (Cons x y) = Cons (f x) (fmap f y) instance Foldable List where foldMap _ Nil = mempty foldMap f (Cons x y) = f x `mappend` foldMap f y instance Traversable List where traverse _ Nil = pure Nil traverse f (Cons x y) = Cons <$> f x <*> traverse f y instance Arbitrary a => Arbitrary (List a) where arbitrary = do x <- arbitrary return $ Cons x Nil instance Eq a => EqProp (List a) where (=-=) = eq listTraversable :: List IIIs listTraversable = undefined Three data Three a b c = Three a b c deriving (Eq, Show) instance Functor (Three a b) where fmap f (Three x y z) = Three x y (f z) instance Foldable (Three a b) where foldMap f (Three _ _ z) = f z instance Traversable (Three a b) where traverse f (Three x y z) = Three x y <$> f z instance ( Arbitrary a , Arbitrary b , Arbitrary c ) => Arbitrary (Three a b c) where arbitrary = do x <- arbitrary y <- arbitrary z <- arbitrary return $ Three x y z instance (Eq a, Eq b, Eq c) => EqProp (Three a b c) where (=-=) = eq threeTraversable :: Three Int Int IIIs threeTraversable = undefined data Pair a b = Pair a b deriving (Eq, Show) instance Functor (Pair a) where fmap f (Pair x y) = Pair x (f y) instance Foldable (Pair a) where foldMap f (Pair _ y) = f y instance Traversable (Pair a) where traverse f (Pair x y) = Pair x <$> f y instance (Arbitrary a, Arbitrary b) => Arbitrary (Pair a b) where arbitrary = do x <- arbitrary y <- arbitrary return $ Pair x y instance (Eq a, Eq b) => EqProp (Pair a b) where (=-=) = eq pairTraversable :: Pair Int IIIs pairTraversable = undefined data Big a b = Big a b b deriving (Eq, Show) instance Functor (Big a) where fmap f (Big x y y') = Big x (f y) (f y') instance Foldable (Big a) where foldMap f (Big _ y y') = f y `mappend` f y' instance Traversable (Big a) where traverse f (Big x y y') = Big x <$> f y <*> f y' instance (Arbitrary a, Arbitrary b) => Arbitrary (Big a b) where arbitrary = do x <- arbitrary y <- arbitrary return $ Big x y y instance (Eq a, Eq b) => EqProp (Big a b) where (=-=) = eq bigTraversable :: Big Int IIIs bigTraversable = undefined data Bigger a b = Bigger a b b b deriving (Eq, Show) instance Functor (Bigger a) where fmap f (Bigger x y y' y'') = Bigger x (f y) (f y') (f y'') instance Foldable (Bigger a) where foldMap f (Bigger _ y y' y'') = f y `mappend` f y' `mappend` f y'' instance Traversable (Bigger a) where traverse f (Bigger x y y' y'')= Bigger x <$> f y <*> f y' <*> f y'' instance (Arbitrary a, Arbitrary b) => Arbitrary (Bigger a b) where arbitrary = do x <- arbitrary y <- arbitrary return $ Bigger x y y y instance (Eq a, Eq b) => EqProp (Bigger a b) where (=-=) = eq biggerTraversable :: Bigger Int IIIs biggerTraversable = undefined main :: IO () main = do putStrLn "\n-- Identity" quickBatch $ functor identityTraversable quickBatch $ traversable identityTraversable putStrLn "\n-- Constant" quickBatch $ functor constantTraversable quickBatch $ traversable constantTraversable putStrLn "\n-- Maybe" quickBatch $ functor maybeTraversable quickBatch $ traversable maybeTraversable putStrLn "\n-- List" quickBatch $ functor listTraversable quickBatch $ traversable listTraversable putStrLn "\n-- Three" quickBatch $ functor threeTraversable putStrLn "\n-- Pair" quickBatch $ functor pairTraversable quickBatch $ traversable pairTraversable putStrLn "\n-- Big" quickBatch $ functor bigTraversable quickBatch $ traversable bigTraversable putStrLn "\n-- Bigger" quickBatch $ functor biggerTraversable quickBatch $ traversable biggerTraversable
321472fadd7afaee389dfdfb74dde594dae86bd4ecce557facb6e9d4e9bac995
Liqwid-Labs/plutus-extra
Natural.hs
module Compare.Natural (tests) where import Functions.Integer qualified as I import Functions.Natural qualified as Nat import Plutus.V1.Ledger.Scripts (fromCompiledCode) import Test.Tasty (TestTree, testGroup) import Test.Tasty.ExpectedFailure (expectFailBecause) import Test.Tasty.Plutus.Size (fitsUnder) import Prelude hiding (Rational, divMod, (/)) tests :: [TestTree] tests = [ testGroup "Eq" [ fitsUnder "==" (fromCompiledCode Nat.natEq) (fromCompiledCode I.iEq) , fitsUnder "/=" (fromCompiledCode Nat.natNeq) (fromCompiledCode I.iNeq) ] , testGroup "Ord" [ fitsUnder "compare" (fromCompiledCode Nat.natCompare) (fromCompiledCode I.iCompare) , fitsUnder "<=" (fromCompiledCode Nat.natLE) (fromCompiledCode I.iLE) , fitsUnder ">=" (fromCompiledCode Nat.natGE) (fromCompiledCode I.iGE) , fitsUnder "<" (fromCompiledCode Nat.natLT) (fromCompiledCode I.iLT) , fitsUnder ">" (fromCompiledCode Nat.natGT) (fromCompiledCode I.iGT) , fitsUnder "min" (fromCompiledCode Nat.natMin) (fromCompiledCode I.iMin) , fitsUnder "max" (fromCompiledCode Nat.natMax) (fromCompiledCode I.iMax) ] , testGroup "Additive" [ fitsUnder "+" (fromCompiledCode Nat.natPlus) (fromCompiledCode I.iPlus) , fitsUnder "zero" (fromCompiledCode Nat.natZero) (fromCompiledCode I.iZero) , fitsUnder "semiscale" (fromCompiledCode Nat.natSemiscale) (fromCompiledCode I.iSemiscale) , expectFailBecause "monus requires more checks" . fitsUnder "^- vs -" (fromCompiledCode Nat.natMonus) . fromCompiledCode $ I.iMinus ] , testGroup "Multiplicative" [ fitsUnder "*" (fromCompiledCode Nat.natTimes) (fromCompiledCode I.iTimes) , fitsUnder "one" (fromCompiledCode Nat.natOne) (fromCompiledCode I.iOne) , fitsUnder "powNat" (fromCompiledCode Nat.natPowNat) (fromCompiledCode I.iPowNat) ] , testGroup "EuclideanClosed" [ fitsUnder "divMod" (fromCompiledCode Nat.natDivMod) (fromCompiledCode I.iDivMod) ] , testGroup "Serialization" [ fitsUnder "toBuiltinData" (fromCompiledCode Nat.natToBuiltinData) (fromCompiledCode I.iToBuiltinData) , expectFailBecause "Natural requires more checks" . fitsUnder "fromBuiltinData" (fromCompiledCode Nat.natFromBuiltinData) . fromCompiledCode $ I.iFromBuiltinData , expectFailBecause "Natural requires more checks" . fitsUnder "unsafeFromBuiltinData" (fromCompiledCode Nat.natUnsafeFromBuiltinData) . fromCompiledCode $ I.iUnsafeFromBuiltinData ] ]
null
https://raw.githubusercontent.com/Liqwid-Labs/plutus-extra/19c03bf6f66fadef4465c3eff849472d4ac8bc05/plutus-numeric/test/size/Compare/Natural.hs
haskell
module Compare.Natural (tests) where import Functions.Integer qualified as I import Functions.Natural qualified as Nat import Plutus.V1.Ledger.Scripts (fromCompiledCode) import Test.Tasty (TestTree, testGroup) import Test.Tasty.ExpectedFailure (expectFailBecause) import Test.Tasty.Plutus.Size (fitsUnder) import Prelude hiding (Rational, divMod, (/)) tests :: [TestTree] tests = [ testGroup "Eq" [ fitsUnder "==" (fromCompiledCode Nat.natEq) (fromCompiledCode I.iEq) , fitsUnder "/=" (fromCompiledCode Nat.natNeq) (fromCompiledCode I.iNeq) ] , testGroup "Ord" [ fitsUnder "compare" (fromCompiledCode Nat.natCompare) (fromCompiledCode I.iCompare) , fitsUnder "<=" (fromCompiledCode Nat.natLE) (fromCompiledCode I.iLE) , fitsUnder ">=" (fromCompiledCode Nat.natGE) (fromCompiledCode I.iGE) , fitsUnder "<" (fromCompiledCode Nat.natLT) (fromCompiledCode I.iLT) , fitsUnder ">" (fromCompiledCode Nat.natGT) (fromCompiledCode I.iGT) , fitsUnder "min" (fromCompiledCode Nat.natMin) (fromCompiledCode I.iMin) , fitsUnder "max" (fromCompiledCode Nat.natMax) (fromCompiledCode I.iMax) ] , testGroup "Additive" [ fitsUnder "+" (fromCompiledCode Nat.natPlus) (fromCompiledCode I.iPlus) , fitsUnder "zero" (fromCompiledCode Nat.natZero) (fromCompiledCode I.iZero) , fitsUnder "semiscale" (fromCompiledCode Nat.natSemiscale) (fromCompiledCode I.iSemiscale) , expectFailBecause "monus requires more checks" . fitsUnder "^- vs -" (fromCompiledCode Nat.natMonus) . fromCompiledCode $ I.iMinus ] , testGroup "Multiplicative" [ fitsUnder "*" (fromCompiledCode Nat.natTimes) (fromCompiledCode I.iTimes) , fitsUnder "one" (fromCompiledCode Nat.natOne) (fromCompiledCode I.iOne) , fitsUnder "powNat" (fromCompiledCode Nat.natPowNat) (fromCompiledCode I.iPowNat) ] , testGroup "EuclideanClosed" [ fitsUnder "divMod" (fromCompiledCode Nat.natDivMod) (fromCompiledCode I.iDivMod) ] , testGroup "Serialization" [ fitsUnder "toBuiltinData" (fromCompiledCode Nat.natToBuiltinData) (fromCompiledCode I.iToBuiltinData) , expectFailBecause "Natural requires more checks" . fitsUnder "fromBuiltinData" (fromCompiledCode Nat.natFromBuiltinData) . fromCompiledCode $ I.iFromBuiltinData , expectFailBecause "Natural requires more checks" . fitsUnder "unsafeFromBuiltinData" (fromCompiledCode Nat.natUnsafeFromBuiltinData) . fromCompiledCode $ I.iUnsafeFromBuiltinData ] ]
c66138578ba3b366d2f97efdd24b0293b896dc777ff8bd937d2a4c1b30ec0fa8
herbelin/coq-hh
cbytegen.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 *) (************************************************************************) Author : as part of the bytecode - based virtual reduction machine , Oct 2004 machine, Oct 2004 *) Extension : ( support for native arithmetic ) , May 2005 open Util open Names open Cbytecodes open Cemitcodes open Term open Declarations open Pre_env (* Compilation of variables + computing free variables *) (* The virtual machine doesn't distinguish closures and their environment *) (* Representation of function environments : *) (* [clos_t | code | fv1 | fv2 | ... | fvn ] *) (* ^ *) The offset for accessing free variables is 1 ( we must skip the code (* pointer). *) (* While compiling, free variables are stored in [in_env] in order *) (* opposite to machine representation, so we can add new free variables *) (* easily (i.e. without changing the position of previous variables) *) (* Function arguments are on the stack in the same order as the *) application : f arg1 ... (* - the stack is then : *) (* arg1 : ... argn : extra args : return addr : ... *) In the function body [ arg1 ] is represented by [ n ] , and [ argn ] by [ 1 ] (* Representation of environements of mutual fixpoints : *) (* [t1|C1| ... |tc|Cc| ... |t(nbr)|C(nbr)| fv1 | fv2 | .... | fvn | type] *) (* ^<----------offset---------> *) (* type = [Ct1 | .... | Ctn] *) (* Ci is the code pointer of the i-th body *) (* At runtime, a fixpoint environment (which is the same as the fixpoint *) (* itself) is a pointer to the field holding its code pointer. *) In each fixpoint body , [ nbr ] represents the first fixpoint and [ 1 ] the last one . (* Access to these variables is performed by the [Koffsetclosure n] *) (* instruction that shifts the environment pointer of [n] fields. *) This allows to represent mutual fixpoints in just one block . (* [Ct1 | ... | Ctn] is an array holding code pointers of the fixpoint *) (* types. They are used in conversion tests (which requires that *) (* fixpoint types must be convertible). Their environment is the one of *) (* the last fixpoint : *) (* [t1|C1| ... |tc|Cc| ... |t(nbr)|C(nbr)| fv1 | fv2 | .... | fvn | type] *) (* ^ *) (* Representation of mutual cofix : *) (* a1 = [A_t | accumulate | [Cfx_t | fcofix1 ] ] *) (* ... *) anbr = [ A_t | accumulate | [ Cfx_t | fcofixnbr ] ] (* *) fcofix1 = [ clos_t | code1 | a1 | ... | anbr | fv1 | ... | fvn | type ] (* ^ *) (* ... *) (* fcofixnbr = [clos_t | codenbr | a1 |...| anbr | fv1 |...| fvn | type] *) (* ^ *) (* The [ai] blocks are functions that accumulate their arguments: *) (* ai arg1 argp ---> *) (* ai' = [A_t | accumulate | [Cfx_t | fcofixi] | arg1 | ... | argp ] *) (* If such a block is matched against, we have to force evaluation, *) (* function [fcofixi] is then applied to [ai'] [arg1] ... [argp] *) (* Once evaluation is completed [ai'] is updated with the result: *) (* ai' <-- *) (* [A_t | accumulate | [Cfxe_t |fcofixi|result] | arg1 | ... | argp ] *) (* This representation is nice because the application of the cofix is *) (* evaluated only once (it simulates a lazy evaluation) *) Moreover , when do n't have arguments , it is possible to create (* a cycle, e.g.: *) (* cofix one := cons 1 one *) (* a1 = [A_t | accumulate | [Cfx_t|fcofix1] ] *) (* fcofix1 = [clos_t | code | a1] *) (* The result of evaluating [a1] is [cons_t | 1 | a1]. *) (* When [a1] is updated : *) (* a1 = [A_t | accumulate | [Cfxe_t | fcofix1 | [cons_t | 1 | a1]] ] *) (* The cycle is created ... *) (* *) In Cfxe_t accumulators , we need to store [ fcofixi ] for testing conversion of ( which is intentional ) . let empty_fv = { size= 0; fv_rev = [] } let fv r = !(r.in_env) let empty_comp_env ()= { nb_stack = 0; in_stack = []; nb_rec = 0; pos_rec = []; offset = 0; in_env = ref empty_fv; } (*i Creation functions for comp_env *) let rec add_param n sz l = if n = 0 then l else add_param (n - 1) sz (n+sz::l) let comp_env_fun arity = { nb_stack = arity; in_stack = add_param arity 0 []; nb_rec = 0; pos_rec = []; offset = 1; in_env = ref empty_fv } let comp_env_fix_type rfv = { nb_stack = 0; in_stack = []; nb_rec = 0; pos_rec = []; offset = 1; in_env = rfv } let comp_env_fix ndef curr_pos arity rfv = let prec = ref [] in for i = ndef downto 1 do prec := Koffsetclosure (2 * (ndef - curr_pos - i)) :: !prec done; { nb_stack = arity; in_stack = add_param arity 0 []; nb_rec = ndef; pos_rec = !prec; offset = 2 * (ndef - curr_pos - 1)+1; in_env = rfv } let comp_env_cofix_type ndef rfv = { nb_stack = 0; in_stack = []; nb_rec = 0; pos_rec = []; offset = 1+ndef; in_env = rfv } let comp_env_cofix ndef arity rfv = let prec = ref [] in for i = 1 to ndef do prec := Kenvacc i :: !prec done; { nb_stack = arity; in_stack = add_param arity 0 []; nb_rec = ndef; pos_rec = !prec; offset = ndef+1; in_env = rfv } (* [push_param ] add function parameters on the stack *) let push_param n sz r = { r with nb_stack = r.nb_stack + n; in_stack = add_param n sz r.in_stack } (* [push_local sz r] add a new variable on the stack at position [sz] *) let push_local sz r = { r with nb_stack = r.nb_stack + 1; in_stack = (sz + 1) :: r.in_stack } (*i Compilation of variables *) let find_at el l = let rec aux n = function | [] -> raise Not_found | hd :: tl -> if hd = el then n else aux (n+1) tl in aux 1 l let pos_named id r = let env = !(r.in_env) in let cid = FVnamed id in try Kenvacc(r.offset + env.size - (find_at cid env.fv_rev)) with Not_found -> let pos = env.size in r.in_env := { size = pos+1; fv_rev = cid:: env.fv_rev}; Kenvacc (r.offset + pos) let pos_rel i r sz = if i <= r.nb_stack then Kacc(sz - (List.nth r.in_stack (i-1))) else let i = i - r.nb_stack in if i <= r.nb_rec then try List.nth r.pos_rec (i-1) with (Failure _|Invalid_argument _) -> assert false else let i = i - r.nb_rec in let db = FVrel(i) in let env = !(r.in_env) in try Kenvacc(r.offset + env.size - (find_at db env.fv_rev)) with Not_found -> let pos = env.size in r.in_env := { size = pos+1; fv_rev = db:: env.fv_rev}; Kenvacc(r.offset + pos) (*i Examination of the continuation *) (* Discard all instructions up to the next label. *) (* This function is to be applied to the continuation before adding a *) (* non-terminating instruction (branch, raise, return, appterm) *) (* in front of it. *) let rec discard_dead_code cont = cont function [ ] - > [ ] | ( Klabel _ | Krestart ) : : _ as cont - > cont | _ : : cont - > discard_dead_code cont [] -> [] | (Klabel _ | Krestart ) :: _ as cont -> cont | _ :: cont -> discard_dead_code cont *) (* Return a label to the beginning of the given continuation. *) (* If the sequence starts with a branch, use the target of that branch *) (* as the label, thus avoiding a jump to a jump. *) let label_code = function | Klabel lbl :: _ as cont -> (lbl, cont) | Kbranch lbl :: _ as cont -> (lbl, cont) | cont -> let lbl = Label.create() in (lbl, Klabel lbl :: cont) (* Return a branch to the continuation. That is, an instruction that, when executed, branches to the continuation or performs what the continuation performs. We avoid generating branches to returns. *) spiwack : make_branch was only used once . Changed it back to the ZAM one to match the appropriate semantics ( old one avoided the introduction of an unconditional branch operation , which seemed appropriate for the 31 - bit integers ' code ) . As a memory , I leave the former version in this comment . let make_branch cont = match cont with | ( Kreturn _ as return ) : : cont ' - > return , cont ' | Klabel lbl as b : : _ - > b , cont | _ - > let b = ( ) ) in b , b::cont one to match the appropriate semantics (old one avoided the introduction of an unconditional branch operation, which seemed appropriate for the 31-bit integers' code). As a memory, I leave the former version in this comment. let make_branch cont = match cont with | (Kreturn _ as return) :: cont' -> return, cont' | Klabel lbl as b :: _ -> b, cont | _ -> let b = Klabel(Label.create()) in b,b::cont *) let rec make_branch_2 lbl n cont = function Kreturn m :: _ -> (Kreturn (n + m), cont) | Klabel _ :: c -> make_branch_2 lbl n cont c | Kpop m :: c -> make_branch_2 lbl (n + m) cont c | _ -> match lbl with Some lbl -> (Kbranch lbl, cont) | None -> let lbl = Label.create() in (Kbranch lbl, Klabel lbl :: cont) let make_branch cont = match cont with (Kbranch _ as branch) :: _ -> (branch, cont) | (Kreturn _ as return) :: _ -> (return, cont) | Klabel lbl :: _ -> make_branch_2 (Some lbl) 0 cont cont | _ -> make_branch_2 (None) 0 cont cont (* Check if we're in tailcall position *) let rec is_tailcall = function | Kreturn k :: _ -> Some k | Klabel _ :: c -> is_tailcall c | _ -> None (* Extention of the continuation *) (* Add a Kpop n instruction in front of a continuation *) let rec add_pop n = function | Kpop m :: cont -> add_pop (n+m) cont | Kreturn m:: cont -> Kreturn (n+m) ::cont | cont -> if n = 0 then cont else Kpop n :: cont let add_grab arity lbl cont = if arity = 1 then Klabel lbl :: cont else Krestart :: Klabel lbl :: Kgrab (arity - 1) :: cont let add_grabrec rec_arg arity lbl cont = if arity = 1 then Klabel lbl :: Kgrabrec 0 :: Krestart :: cont else Krestart :: Klabel lbl :: Kgrabrec rec_arg :: Krestart :: Kgrab (arity - 1) :: cont continuation of a cofix let cont_cofix arity = (* accu = res *) (* stk = ai::args::ra::... *) (* ai = [At|accumulate|[Cfx_t|fcofix]|args] *) [ Kpush; Kpush; (* stk = res::res::ai::args::ra::... *) Kacc 2; Kfield 1; Kfield 0; Kmakeblock(2, cofix_evaluated_tag); stk = [ Cfxe_t|fcofix|res]::res::ai::args::ra : : ... Kacc 2; Ksetfield 1; (* ai = [At|accumulate|[Cfxe_t|fcofix|res]|args] *) (* stk = res::ai::args::ra::... *) Kacc 0; (* accu = res *) Kreturn (arity+2) ] (*i Global environment *) let global_env = ref empty_env let set_global_env env = global_env := env (* Code of closures *) let fun_code = ref [] let init_fun_code () = fun_code := [] (* Compilation of constructors and inductive types *) Inv : + arity > 0 let code_construct tag nparams arity cont = let f_cont = add_pop nparams (if arity = 0 then [Kconst (Const_b0 tag); Kreturn 0] else [Kacc 0; Kpop 1; Kmakeblock(arity, tag); Kreturn 0]) in let lbl = Label.create() in fun_code := [Ksequence (add_grab (nparams+arity) lbl f_cont,!fun_code)]; Kclosure(lbl,0) :: cont let get_strcst = function | Bstrconst sc -> sc | _ -> raise Not_found let rec str_const c = match kind_of_term c with | Sort s -> Bstrconst (Const_sorts s) | Cast(c,_,_) -> str_const c | App(f,args) -> begin match kind_of_term f with | Construct((kn,j),i) -> begin let oib = lookup_mind kn !global_env in let oip = oib.mind_packets.(j) in let num,arity = oip.mind_reloc_tbl.(i-1) in let nparams = oib.mind_nparams in if nparams + arity = Array.length args then (* spiwack: *) 1/ tries to compile the constructor in an optimal way , it is supposed to work only if the arguments are all fully constructed , fails with Cbytecodes . NotClosed . it can also raise Not_found when there is no special treatment for this constructor for instance : tries to to compile an integer of the form I31 D1 D2 ... D31 to [ D1D2 ... D31 ] as a processor number ( a caml number actually ) it is supposed to work only if the arguments are all fully constructed, fails with Cbytecodes.NotClosed. it can also raise Not_found when there is no special treatment for this constructor for instance: tries to to compile an integer of the form I31 D1 D2 ... D31 to [D1D2...D31] as a processor number (a caml number actually) *) try try Bstrconst (Retroknowledge.get_vm_constant_static_info (!global_env).retroknowledge (kind_of_term f) args) with NotClosed -> 2/ if the arguments are not all closed ( this is expectingly ( and it is currently the case ) the only reason why this exception is raised ) tries to give a clever , run - time behavior to the constructor . Raises Not_found if there is no special treatment for this integer . this is done in a lazy fashion , using the constructor Bspecial because it needs to know the continuation and such , which ca n't be done at this time . for instance , for int31 : if one of the digit is not closed , it 's not impossible that the number gets fully instanciated at run - time , thus to ensure uniqueness of the representation in the vm it is necessary to try and build a caml integer during the execution expectingly (and it is currently the case) the only reason why this exception is raised) tries to give a clever, run-time behavior to the constructor. Raises Not_found if there is no special treatment for this integer. this is done in a lazy fashion, using the constructor Bspecial because it needs to know the continuation and such, which can't be done at this time. for instance, for int31: if one of the digit is not closed, it's not impossible that the number gets fully instanciated at run-time, thus to ensure uniqueness of the representation in the vm it is necessary to try and build a caml integer during the execution *) let rargs = Array.sub args nparams arity in let b_args = Array.map str_const rargs in Bspecial ((Retroknowledge.get_vm_constant_dynamic_info (!global_env).retroknowledge (kind_of_term f)), b_args) with Not_found -> 3/ if no special behavior is available , then the compiler falls back to the normal behavior falls back to the normal behavior *) if arity = 0 then Bstrconst(Const_b0 num) else let rargs = Array.sub args nparams arity in let b_args = Array.map str_const rargs in try let sc_args = Array.map get_strcst b_args in Bstrconst(Const_bn(num, sc_args)) with Not_found -> Bmakeblock(num,b_args) else let b_args = Array.map str_const args in spiwack : tries first to apply the run - time compilation behavior of the constructor , as in 2/ above behavior of the constructor, as in 2/ above *) try Bspecial ((Retroknowledge.get_vm_constant_dynamic_info (!global_env).retroknowledge (kind_of_term f)), b_args) with Not_found -> Bconstruct_app(num, nparams, arity, b_args) end | _ -> Bconstr c end | Ind ind -> Bstrconst (Const_ind ind) | Construct ((kn,j),i) -> begin spiwack : tries first to apply the run - time compilation behavior of the constructor , as in 2/ above behavior of the constructor, as in 2/ above *) try Bspecial ((Retroknowledge.get_vm_constant_dynamic_info (!global_env).retroknowledge (kind_of_term c)), [| |]) with Not_found -> let oib = lookup_mind kn !global_env in let oip = oib.mind_packets.(j) in let num,arity = oip.mind_reloc_tbl.(i-1) in let nparams = oib.mind_nparams in if nparams + arity = 0 then Bstrconst(Const_b0 num) else Bconstruct_app(num,nparams,arity,[||]) end | _ -> Bconstr c (* compiling application *) let comp_args comp_expr reloc args sz cont = let nargs_m_1 = Array.length args - 1 in let c = ref (comp_expr reloc args.(0) (sz + nargs_m_1) cont) in for i = 1 to nargs_m_1 do c := comp_expr reloc args.(i) (sz + nargs_m_1 - i) (Kpush :: !c) done; !c let comp_app comp_fun comp_arg reloc f args sz cont = let nargs = Array.length args in match is_tailcall cont with | Some k -> comp_args comp_arg reloc args sz (Kpush :: comp_fun reloc f (sz + nargs) (Kappterm(nargs, k + nargs) :: (discard_dead_code cont))) | None -> if nargs < 4 then comp_args comp_arg reloc args sz (Kpush :: (comp_fun reloc f (sz+nargs) (Kapply nargs :: cont))) else let lbl,cont1 = label_code cont in Kpush_retaddr lbl :: (comp_args comp_arg reloc args (sz + 3) (Kpush :: (comp_fun reloc f (sz+3+nargs) (Kapply nargs :: cont1)))) (* Compiling free variables *) let compile_fv_elem reloc fv sz cont = match fv with | FVrel i -> pos_rel i reloc sz :: cont | FVnamed id -> pos_named id reloc :: cont let rec compile_fv reloc l sz cont = match l with | [] -> cont | [fvn] -> compile_fv_elem reloc fvn sz cont | fvn :: tl -> compile_fv_elem reloc fvn sz (Kpush :: compile_fv reloc tl (sz + 1) cont) (* Compiling constants *) let rec get_allias env kn = let tps = (lookup_constant kn env).const_body_code in match Cemitcodes.force tps with | BCallias kn' -> get_allias env kn' | _ -> kn (* Compiling expressions *) let rec compile_constr reloc c sz cont = match kind_of_term c with | Meta _ -> raise (Invalid_argument "Cbytegen.compile_constr : Meta") | Evar _ -> raise (Invalid_argument "Cbytegen.compile_constr : Evar") | Cast(c,_,_) -> compile_constr reloc c sz cont | Rel i -> pos_rel i reloc sz :: cont | Var id -> pos_named id reloc :: cont | Const kn -> compile_const reloc kn [||] sz cont | Sort _ | Ind _ | Construct _ -> compile_str_cst reloc (str_const c) sz cont | LetIn(_,xb,_,body) -> compile_constr reloc xb sz (Kpush :: (compile_constr (push_local sz reloc) body (sz+1) (add_pop 1 cont))) | Prod(id,dom,codom) -> let cont1 = Kpush :: compile_constr reloc dom (sz+1) (Kmakeprod :: cont) in compile_constr reloc (mkLambda(id,dom,codom)) sz cont1 | Lambda _ -> let params, body = decompose_lam c in let arity = List.length params in let r_fun = comp_env_fun arity in let lbl_fun = Label.create() in let cont_fun = compile_constr r_fun body arity [Kreturn arity] in fun_code := [Ksequence(add_grab arity lbl_fun cont_fun,!fun_code)]; let fv = fv r_fun in compile_fv reloc fv.fv_rev sz (Kclosure(lbl_fun,fv.size) :: cont) | App(f,args) -> begin match kind_of_term f with | Construct _ -> compile_str_cst reloc (str_const c) sz cont | Const kn -> compile_const reloc kn args sz cont | _ -> comp_app compile_constr compile_constr reloc f args sz cont end | Fix ((rec_args,init),(_,type_bodies,rec_bodies)) -> let ndef = Array.length type_bodies in let rfv = ref empty_fv in let lbl_types = Array.create ndef Label.no in let lbl_bodies = Array.create ndef Label.no in (* Compilation des types *) let env_type = comp_env_fix_type rfv in for i = 0 to ndef - 1 do let lbl,fcode = label_code (compile_constr env_type type_bodies.(i) 0 [Kstop]) in lbl_types.(i) <- lbl; fun_code := [Ksequence(fcode,!fun_code)] done; (* Compiling bodies *) for i = 0 to ndef - 1 do let params,body = decompose_lam rec_bodies.(i) in let arity = List.length params in let env_body = comp_env_fix ndef i arity rfv in let cont1 = compile_constr env_body body arity [Kreturn arity] in let lbl = Label.create () in lbl_bodies.(i) <- lbl; let fcode = add_grabrec rec_args.(i) arity lbl cont1 in fun_code := [Ksequence(fcode,!fun_code)] done; let fv = !rfv in compile_fv reloc fv.fv_rev sz (Kclosurerec(fv.size,init,lbl_types,lbl_bodies) :: cont) | CoFix(init,(_,type_bodies,rec_bodies)) -> let ndef = Array.length type_bodies in let lbl_types = Array.create ndef Label.no in let lbl_bodies = Array.create ndef Label.no in (* Compiling types *) let rfv = ref empty_fv in let env_type = comp_env_cofix_type ndef rfv in for i = 0 to ndef - 1 do let lbl,fcode = label_code (compile_constr env_type type_bodies.(i) 0 [Kstop]) in lbl_types.(i) <- lbl; fun_code := [Ksequence(fcode,!fun_code)] done; (* Compiling bodies *) for i = 0 to ndef - 1 do let params,body = decompose_lam rec_bodies.(i) in let arity = List.length params in let env_body = comp_env_cofix ndef arity rfv in let lbl = Label.create () in let cont1 = compile_constr env_body body (arity+1) (cont_cofix arity) in let cont2 = add_grab (arity+1) lbl cont1 in lbl_bodies.(i) <- lbl; fun_code := [Ksequence(cont2,!fun_code)]; done; let fv = !rfv in compile_fv reloc fv.fv_rev sz (Kclosurecofix(fv.size, init, lbl_types, lbl_bodies) :: cont) | Case(ci,t,a,branchs) -> let ind = ci.ci_ind in let mib = lookup_mind (fst ind) !global_env in let oib = mib.mind_packets.(snd ind) in let tbl = oib.mind_reloc_tbl in let lbl_consts = Array.create oib.mind_nb_constant Label.no in let lbl_blocks = Array.create (oib.mind_nb_args+1) Label.no in let branch1,cont = make_branch cont in (* Compiling return type *) let lbl_typ,fcode = label_code (compile_constr reloc t sz [Kpop sz; Kstop]) in fun_code := [Ksequence(fcode,!fun_code)]; (* Compiling branches *) let lbl_sw = Label.create () in let sz_b,branch,is_tailcall = match branch1 with | Kreturn k -> assert (k = sz); sz, branch1, true | _ -> sz+3, Kjump, false in let annot = {ci = ci; rtbl = tbl; tailcall = is_tailcall} in (* Compiling branch for accumulators *) let lbl_accu, code_accu = label_code(Kmakeswitchblock(lbl_typ,lbl_sw,annot,sz) :: branch::cont) in lbl_blocks.(0) <- lbl_accu; let c = ref code_accu in (* Compiling regular constructor branches *) for i = 0 to Array.length tbl - 1 do let tag, arity = tbl.(i) in if arity = 0 then let lbl_b,code_b = label_code(compile_constr reloc branchs.(i) sz_b (branch :: !c)) in lbl_consts.(tag) <- lbl_b; c := code_b else let args, body = decompose_lam branchs.(i) in let nargs = List.length args in let lbl_b,code_b = label_code( if nargs = arity then Kpushfields arity :: compile_constr (push_param arity sz_b reloc) body (sz_b+arity) (add_pop arity (branch :: !c)) else let sz_appterm = if is_tailcall then sz_b + arity else arity in Kpushfields arity :: compile_constr reloc branchs.(i) (sz_b+arity) (Kappterm(arity,sz_appterm) :: !c)) in lbl_blocks.(tag) <- lbl_b; c := code_b done; c := Klabel lbl_sw :: Kswitch(lbl_consts,lbl_blocks) :: !c; let code_sw = match branch1 with spiwack : ca n't be a lbl anymore it 's a Branch instead | Kpush_retaddr lbl : : ! c | Klabel lbl -> Kpush_retaddr lbl :: !c *) | Kbranch lbl -> Kpush_retaddr lbl :: !c | _ -> !c in compile_constr reloc a sz (try let entry = Term.Ind ind in Retroknowledge.get_vm_before_match_info (!global_env).retroknowledge entry code_sw with Not_found -> code_sw) and compile_str_cst reloc sc sz cont = match sc with | Bconstr c -> compile_constr reloc c sz cont | Bstrconst sc -> Kconst sc :: cont | Bmakeblock(tag,args) -> let nargs = Array.length args in comp_args compile_str_cst reloc args sz (Kmakeblock(nargs,tag) :: cont) | Bconstruct_app(tag,nparams,arity,args) -> if Array.length args = 0 then code_construct tag nparams arity cont else comp_app (fun _ _ _ cont -> code_construct tag nparams arity cont) compile_str_cst reloc () args sz cont | Bspecial (comp_fx, args) -> comp_fx reloc args sz cont spiwack : compilation of constants with their arguments . Makes a special treatment with 31 - bit integer addition Makes a special treatment with 31-bit integer addition *) and compile_const = fun reloc-> fun kn -> fun args -> fun sz -> fun cont -> let nargs = Array.length args in (* spiwack: checks if there is a specific way to compile the constant if there is not, Not_found is raised, and the function falls back on its normal behavior *) try Retroknowledge.get_vm_compiling_info (!global_env).retroknowledge (kind_of_term (mkConst kn)) reloc args sz cont with Not_found -> if nargs = 0 then Kgetglobal (get_allias !global_env kn) :: cont else comp_app (fun _ _ _ cont -> Kgetglobal (get_allias !global_env kn) :: cont) compile_constr reloc () args sz cont let compile env c = set_global_env env; init_fun_code (); Label.reset_label_counter (); let reloc = empty_comp_env () in let init_code = compile_constr reloc c 0 [Kstop] in let fv = List.rev (!(reloc.in_env).fv_rev) in draw_instr init_code ; draw_instr ! fun_code ; Format.print_string " fv = " ; List.iter ( fun v - > match v with | FVnamed i d - > Format.print_string ( ( string_of_id id)^ " ; " ) | FVrel i - > Format.print_string ( ( string_of_int i)^ " ; " ) ) fv ; Format .print_string " \n " ; Format.print_flush ( ) ; draw_instr !fun_code; Format.print_string "fv = "; List.iter (fun v -> match v with | FVnamed id -> Format.print_string ((string_of_id id)^"; ") | FVrel i -> Format.print_string ((string_of_int i)^"; ")) fv; Format .print_string "\n"; Format.print_flush(); *) init_code,!fun_code, Array.of_list fv let compile_constant_body env body opaque boxed = if opaque then BCconstant else match body with | None -> BCconstant | Some sb -> let body = Declarations.force sb in if boxed then let res = compile env body in let to_patch = to_memory res in BCdefined(true, to_patch) else match kind_of_term body with | Const kn' -> (* we use the canonical name of the constant*) let con= constant_of_kn (canonical_con kn') in BCallias (get_allias env con) | _ -> let res = compile env body in let to_patch = to_memory res in BCdefined (false, to_patch) spiwack : additional function which allow different part of compilation of the 31 - bit integers 31-bit integers *) let make_areconst n else_lbl cont = if n <=0 then cont else Kareconst (n, else_lbl)::cont (* try to compile int31 as a const_b0. Succeed if all the arguments are closed fails otherwise by raising NotClosed*) let compile_structured_int31 fc args = if not fc then raise Not_found else Const_b0 (Array.fold_left (fun temp_i -> fun t -> match kind_of_term t with | Construct (_,d) -> 2*temp_i+d-1 | _ -> raise NotClosed) 0 args ) this function is used for the compilation of the constructor of the int31 , it is used when it appears not fully applied , or applied to at least one non - closed digit the int31, it is used when it appears not fully applied, or applied to at least one non-closed digit *) let dynamic_int31_compilation fc reloc args sz cont = if not fc then raise Not_found else let nargs = Array.length args in if nargs = 31 then let (escape,labeled_cont) = make_branch cont in let else_lbl = Label.create() in comp_args compile_str_cst reloc args sz ( Kisconst else_lbl::Kareconst(30,else_lbl)::Kcompint31::escape::Klabel else_lbl::Kmakeblock(31, 1)::labeled_cont) else let code_construct cont = (* spiwack: variant of the global code_construct which handles dynamic compilation of integers *) let f_cont = let else_lbl = Label.create () in [Kacc 0; Kpop 1; Kisconst else_lbl; Kareconst(30,else_lbl); Kcompint31; Kreturn 0; Klabel else_lbl; Kmakeblock(31, 1); Kreturn 0] in let lbl = Label.create() in fun_code := [Ksequence (add_grab 31 lbl f_cont,!fun_code)]; Kclosure(lbl,0) :: cont in if nargs = 0 then code_construct cont else comp_app (fun _ _ _ cont -> code_construct cont) compile_str_cst reloc () args sz cont ( * template compilation for 2ary operation , it probably possible to make a generic such function with arity abstracted to make a generic such function with arity abstracted *) let op2_compilation op = let code_construct normal cont = (*kn cont =*) let f_cont = let else_lbl = Label.create () in Kareconst(2, else_lbl):: Kacc 0:: Kpop 1:: op:: Kreturn 0:: Klabel else_lbl:: works as comp_app with and tailcall cont [ Kreturn 0 ] ( get_allias ! global_env kn ): : normal:: Kappterm(2, 2):: [] (* = discard_dead_code [Kreturn 0] *) in let lbl = Label.create () in fun_code := [Ksequence (add_grab 2 lbl f_cont, !fun_code)]; Kclosure(lbl, 0)::cont in fun normal fc _ reloc args sz cont -> if not fc then raise Not_found else let nargs = Array.length args in if nargs=2 then (*if it is a fully applied addition*) let (escape, labeled_cont) = make_branch cont in let else_lbl = Label.create () in comp_args compile_constr reloc args sz (Kisconst else_lbl::(make_areconst 1 else_lbl (*Kaddint31::escape::Klabel else_lbl::Kpush::*) (op::escape::Klabel else_lbl::Kpush:: works as comp_app with and non - tailcall cont ( get_allias ! global_env kn ): : normal:: Kapply 2::labeled_cont))) else if nargs=0 then code_construct normal cont else comp_app (fun _ _ _ cont -> code_construct normal cont) compile_constr reloc () args sz cont *) template for n - ary operation , invariant : n>=1 , the operations does the following : 1/ checks if all the arguments are constants ( i.e. non - block values ) 2/ if they are , uses the " op " instruction to execute 3/ if at least one is not , branches to the normal behavior : ( get_allias ! ) the operations does the following : 1/ checks if all the arguments are constants (i.e. non-block values) 2/ if they are, uses the "op" instruction to execute 3/ if at least one is not, branches to the normal behavior: Kgetglobal (get_allias !global_env kn) *) let op_compilation n op = let code_construct kn cont = let f_cont = let else_lbl = Label.create () in Kareconst(n, else_lbl):: Kacc 0:: Kpop 1:: op:: Kreturn 0:: Klabel else_lbl:: works as comp_app with nargs = n and tailcall cont [ Kreturn 0 ] Kgetglobal (get_allias !global_env kn):: Kappterm(n, n):: [] (* = discard_dead_code [Kreturn 0] *) in let lbl = Label.create () in fun_code := [Ksequence (add_grab n lbl f_cont, !fun_code)]; Kclosure(lbl, 0)::cont in fun kn fc reloc args sz cont -> if not fc then raise Not_found else let nargs = Array.length args in if nargs=n then (*if it is a fully applied addition*) let (escape, labeled_cont) = make_branch cont in let else_lbl = Label.create () in comp_args compile_constr reloc args sz (Kisconst else_lbl::(make_areconst (n-1) else_lbl (*Kaddint31::escape::Klabel else_lbl::Kpush::*) (op::escape::Klabel else_lbl::Kpush:: works as comp_app with nargs = n and non - tailcall cont Kgetglobal (get_allias !global_env kn):: Kapply n::labeled_cont))) else if nargs=0 then code_construct kn cont else comp_app (fun _ _ _ cont -> code_construct kn cont) compile_constr reloc () args sz cont let int31_escape_before_match fc cont = if not fc then raise Not_found else let escape_lbl, labeled_cont = label_code cont in (Kisconst escape_lbl)::Kdecompint31::labeled_cont
null
https://raw.githubusercontent.com/herbelin/coq-hh/296d03d5049fea661e8bdbaf305ed4bf6d2001d2/kernel/cbytegen.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** Compilation of variables + computing free variables The virtual machine doesn't distinguish closures and their environment Representation of function environments : [clos_t | code | fv1 | fv2 | ... | fvn ] ^ pointer). While compiling, free variables are stored in [in_env] in order opposite to machine representation, so we can add new free variables easily (i.e. without changing the position of previous variables) Function arguments are on the stack in the same order as the - the stack is then : arg1 : ... argn : extra args : return addr : ... Representation of environements of mutual fixpoints : [t1|C1| ... |tc|Cc| ... |t(nbr)|C(nbr)| fv1 | fv2 | .... | fvn | type] ^<----------offset---------> type = [Ct1 | .... | Ctn] Ci is the code pointer of the i-th body At runtime, a fixpoint environment (which is the same as the fixpoint itself) is a pointer to the field holding its code pointer. Access to these variables is performed by the [Koffsetclosure n] instruction that shifts the environment pointer of [n] fields. [Ct1 | ... | Ctn] is an array holding code pointers of the fixpoint types. They are used in conversion tests (which requires that fixpoint types must be convertible). Their environment is the one of the last fixpoint : [t1|C1| ... |tc|Cc| ... |t(nbr)|C(nbr)| fv1 | fv2 | .... | fvn | type] ^ Representation of mutual cofix : a1 = [A_t | accumulate | [Cfx_t | fcofix1 ] ] ... ^ ... fcofixnbr = [clos_t | codenbr | a1 |...| anbr | fv1 |...| fvn | type] ^ The [ai] blocks are functions that accumulate their arguments: ai arg1 argp ---> ai' = [A_t | accumulate | [Cfx_t | fcofixi] | arg1 | ... | argp ] If such a block is matched against, we have to force evaluation, function [fcofixi] is then applied to [ai'] [arg1] ... [argp] Once evaluation is completed [ai'] is updated with the result: ai' <-- [A_t | accumulate | [Cfxe_t |fcofixi|result] | arg1 | ... | argp ] This representation is nice because the application of the cofix is evaluated only once (it simulates a lazy evaluation) a cycle, e.g.: cofix one := cons 1 one a1 = [A_t | accumulate | [Cfx_t|fcofix1] ] fcofix1 = [clos_t | code | a1] The result of evaluating [a1] is [cons_t | 1 | a1]. When [a1] is updated : a1 = [A_t | accumulate | [Cfxe_t | fcofix1 | [cons_t | 1 | a1]] ] The cycle is created ... i Creation functions for comp_env [push_param ] add function parameters on the stack [push_local sz r] add a new variable on the stack at position [sz] i Compilation of variables i Examination of the continuation Discard all instructions up to the next label. This function is to be applied to the continuation before adding a non-terminating instruction (branch, raise, return, appterm) in front of it. Return a label to the beginning of the given continuation. If the sequence starts with a branch, use the target of that branch as the label, thus avoiding a jump to a jump. Return a branch to the continuation. That is, an instruction that, when executed, branches to the continuation or performs what the continuation performs. We avoid generating branches to returns. Check if we're in tailcall position Extention of the continuation Add a Kpop n instruction in front of a continuation accu = res stk = ai::args::ra::... ai = [At|accumulate|[Cfx_t|fcofix]|args] stk = res::res::ai::args::ra::... ai = [At|accumulate|[Cfxe_t|fcofix|res]|args] stk = res::ai::args::ra::... accu = res i Global environment Code of closures Compilation of constructors and inductive types spiwack: compiling application Compiling free variables Compiling constants Compiling expressions Compilation des types Compiling bodies Compiling types Compiling bodies Compiling return type Compiling branches Compiling branch for accumulators Compiling regular constructor branches spiwack: checks if there is a specific way to compile the constant if there is not, Not_found is raised, and the function falls back on its normal behavior we use the canonical name of the constant try to compile int31 as a const_b0. Succeed if all the arguments are closed fails otherwise by raising NotClosed spiwack: variant of the global code_construct which handles dynamic compilation of integers kn cont = = discard_dead_code [Kreturn 0] if it is a fully applied addition Kaddint31::escape::Klabel else_lbl::Kpush:: = discard_dead_code [Kreturn 0] if it is a fully applied addition Kaddint31::escape::Klabel else_lbl::Kpush::
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author : as part of the bytecode - based virtual reduction machine , Oct 2004 machine, Oct 2004 *) Extension : ( support for native arithmetic ) , May 2005 open Util open Names open Cbytecodes open Cemitcodes open Term open Declarations open Pre_env The offset for accessing free variables is 1 ( we must skip the code application : f arg1 ... In the function body [ arg1 ] is represented by [ n ] , and [ argn ] by [ 1 ] In each fixpoint body , [ nbr ] represents the first fixpoint and [ 1 ] the last one . This allows to represent mutual fixpoints in just one block . anbr = [ A_t | accumulate | [ Cfx_t | fcofixnbr ] ] fcofix1 = [ clos_t | code1 | a1 | ... | anbr | fv1 | ... | fvn | type ] Moreover , when do n't have arguments , it is possible to create In Cfxe_t accumulators , we need to store [ fcofixi ] for testing conversion of ( which is intentional ) . let empty_fv = { size= 0; fv_rev = [] } let fv r = !(r.in_env) let empty_comp_env ()= { nb_stack = 0; in_stack = []; nb_rec = 0; pos_rec = []; offset = 0; in_env = ref empty_fv; } let rec add_param n sz l = if n = 0 then l else add_param (n - 1) sz (n+sz::l) let comp_env_fun arity = { nb_stack = arity; in_stack = add_param arity 0 []; nb_rec = 0; pos_rec = []; offset = 1; in_env = ref empty_fv } let comp_env_fix_type rfv = { nb_stack = 0; in_stack = []; nb_rec = 0; pos_rec = []; offset = 1; in_env = rfv } let comp_env_fix ndef curr_pos arity rfv = let prec = ref [] in for i = ndef downto 1 do prec := Koffsetclosure (2 * (ndef - curr_pos - i)) :: !prec done; { nb_stack = arity; in_stack = add_param arity 0 []; nb_rec = ndef; pos_rec = !prec; offset = 2 * (ndef - curr_pos - 1)+1; in_env = rfv } let comp_env_cofix_type ndef rfv = { nb_stack = 0; in_stack = []; nb_rec = 0; pos_rec = []; offset = 1+ndef; in_env = rfv } let comp_env_cofix ndef arity rfv = let prec = ref [] in for i = 1 to ndef do prec := Kenvacc i :: !prec done; { nb_stack = arity; in_stack = add_param arity 0 []; nb_rec = ndef; pos_rec = !prec; offset = ndef+1; in_env = rfv } let push_param n sz r = { r with nb_stack = r.nb_stack + n; in_stack = add_param n sz r.in_stack } let push_local sz r = { r with nb_stack = r.nb_stack + 1; in_stack = (sz + 1) :: r.in_stack } let find_at el l = let rec aux n = function | [] -> raise Not_found | hd :: tl -> if hd = el then n else aux (n+1) tl in aux 1 l let pos_named id r = let env = !(r.in_env) in let cid = FVnamed id in try Kenvacc(r.offset + env.size - (find_at cid env.fv_rev)) with Not_found -> let pos = env.size in r.in_env := { size = pos+1; fv_rev = cid:: env.fv_rev}; Kenvacc (r.offset + pos) let pos_rel i r sz = if i <= r.nb_stack then Kacc(sz - (List.nth r.in_stack (i-1))) else let i = i - r.nb_stack in if i <= r.nb_rec then try List.nth r.pos_rec (i-1) with (Failure _|Invalid_argument _) -> assert false else let i = i - r.nb_rec in let db = FVrel(i) in let env = !(r.in_env) in try Kenvacc(r.offset + env.size - (find_at db env.fv_rev)) with Not_found -> let pos = env.size in r.in_env := { size = pos+1; fv_rev = db:: env.fv_rev}; Kenvacc(r.offset + pos) let rec discard_dead_code cont = cont function [ ] - > [ ] | ( Klabel _ | Krestart ) : : _ as cont - > cont | _ : : cont - > discard_dead_code cont [] -> [] | (Klabel _ | Krestart ) :: _ as cont -> cont | _ :: cont -> discard_dead_code cont *) let label_code = function | Klabel lbl :: _ as cont -> (lbl, cont) | Kbranch lbl :: _ as cont -> (lbl, cont) | cont -> let lbl = Label.create() in (lbl, Klabel lbl :: cont) spiwack : make_branch was only used once . Changed it back to the ZAM one to match the appropriate semantics ( old one avoided the introduction of an unconditional branch operation , which seemed appropriate for the 31 - bit integers ' code ) . As a memory , I leave the former version in this comment . let make_branch cont = match cont with | ( Kreturn _ as return ) : : cont ' - > return , cont ' | Klabel lbl as b : : _ - > b , cont | _ - > let b = ( ) ) in b , b::cont one to match the appropriate semantics (old one avoided the introduction of an unconditional branch operation, which seemed appropriate for the 31-bit integers' code). As a memory, I leave the former version in this comment. let make_branch cont = match cont with | (Kreturn _ as return) :: cont' -> return, cont' | Klabel lbl as b :: _ -> b, cont | _ -> let b = Klabel(Label.create()) in b,b::cont *) let rec make_branch_2 lbl n cont = function Kreturn m :: _ -> (Kreturn (n + m), cont) | Klabel _ :: c -> make_branch_2 lbl n cont c | Kpop m :: c -> make_branch_2 lbl (n + m) cont c | _ -> match lbl with Some lbl -> (Kbranch lbl, cont) | None -> let lbl = Label.create() in (Kbranch lbl, Klabel lbl :: cont) let make_branch cont = match cont with (Kbranch _ as branch) :: _ -> (branch, cont) | (Kreturn _ as return) :: _ -> (return, cont) | Klabel lbl :: _ -> make_branch_2 (Some lbl) 0 cont cont | _ -> make_branch_2 (None) 0 cont cont let rec is_tailcall = function | Kreturn k :: _ -> Some k | Klabel _ :: c -> is_tailcall c | _ -> None let rec add_pop n = function | Kpop m :: cont -> add_pop (n+m) cont | Kreturn m:: cont -> Kreturn (n+m) ::cont | cont -> if n = 0 then cont else Kpop n :: cont let add_grab arity lbl cont = if arity = 1 then Klabel lbl :: cont else Krestart :: Klabel lbl :: Kgrab (arity - 1) :: cont let add_grabrec rec_arg arity lbl cont = if arity = 1 then Klabel lbl :: Kgrabrec 0 :: Krestart :: cont else Krestart :: Klabel lbl :: Kgrabrec rec_arg :: Krestart :: Kgrab (arity - 1) :: cont continuation of a cofix let cont_cofix arity = [ Kpush; Kacc 2; Kfield 1; Kfield 0; Kmakeblock(2, cofix_evaluated_tag); stk = [ Cfxe_t|fcofix|res]::res::ai::args::ra : : ... Kacc 2; Kreturn (arity+2) ] let global_env = ref empty_env let set_global_env env = global_env := env let fun_code = ref [] let init_fun_code () = fun_code := [] Inv : + arity > 0 let code_construct tag nparams arity cont = let f_cont = add_pop nparams (if arity = 0 then [Kconst (Const_b0 tag); Kreturn 0] else [Kacc 0; Kpop 1; Kmakeblock(arity, tag); Kreturn 0]) in let lbl = Label.create() in fun_code := [Ksequence (add_grab (nparams+arity) lbl f_cont,!fun_code)]; Kclosure(lbl,0) :: cont let get_strcst = function | Bstrconst sc -> sc | _ -> raise Not_found let rec str_const c = match kind_of_term c with | Sort s -> Bstrconst (Const_sorts s) | Cast(c,_,_) -> str_const c | App(f,args) -> begin match kind_of_term f with | Construct((kn,j),i) -> begin let oib = lookup_mind kn !global_env in let oip = oib.mind_packets.(j) in let num,arity = oip.mind_reloc_tbl.(i-1) in let nparams = oib.mind_nparams in if nparams + arity = Array.length args then 1/ tries to compile the constructor in an optimal way , it is supposed to work only if the arguments are all fully constructed , fails with Cbytecodes . NotClosed . it can also raise Not_found when there is no special treatment for this constructor for instance : tries to to compile an integer of the form I31 D1 D2 ... D31 to [ D1D2 ... D31 ] as a processor number ( a caml number actually ) it is supposed to work only if the arguments are all fully constructed, fails with Cbytecodes.NotClosed. it can also raise Not_found when there is no special treatment for this constructor for instance: tries to to compile an integer of the form I31 D1 D2 ... D31 to [D1D2...D31] as a processor number (a caml number actually) *) try try Bstrconst (Retroknowledge.get_vm_constant_static_info (!global_env).retroknowledge (kind_of_term f) args) with NotClosed -> 2/ if the arguments are not all closed ( this is expectingly ( and it is currently the case ) the only reason why this exception is raised ) tries to give a clever , run - time behavior to the constructor . Raises Not_found if there is no special treatment for this integer . this is done in a lazy fashion , using the constructor Bspecial because it needs to know the continuation and such , which ca n't be done at this time . for instance , for int31 : if one of the digit is not closed , it 's not impossible that the number gets fully instanciated at run - time , thus to ensure uniqueness of the representation in the vm it is necessary to try and build a caml integer during the execution expectingly (and it is currently the case) the only reason why this exception is raised) tries to give a clever, run-time behavior to the constructor. Raises Not_found if there is no special treatment for this integer. this is done in a lazy fashion, using the constructor Bspecial because it needs to know the continuation and such, which can't be done at this time. for instance, for int31: if one of the digit is not closed, it's not impossible that the number gets fully instanciated at run-time, thus to ensure uniqueness of the representation in the vm it is necessary to try and build a caml integer during the execution *) let rargs = Array.sub args nparams arity in let b_args = Array.map str_const rargs in Bspecial ((Retroknowledge.get_vm_constant_dynamic_info (!global_env).retroknowledge (kind_of_term f)), b_args) with Not_found -> 3/ if no special behavior is available , then the compiler falls back to the normal behavior falls back to the normal behavior *) if arity = 0 then Bstrconst(Const_b0 num) else let rargs = Array.sub args nparams arity in let b_args = Array.map str_const rargs in try let sc_args = Array.map get_strcst b_args in Bstrconst(Const_bn(num, sc_args)) with Not_found -> Bmakeblock(num,b_args) else let b_args = Array.map str_const args in spiwack : tries first to apply the run - time compilation behavior of the constructor , as in 2/ above behavior of the constructor, as in 2/ above *) try Bspecial ((Retroknowledge.get_vm_constant_dynamic_info (!global_env).retroknowledge (kind_of_term f)), b_args) with Not_found -> Bconstruct_app(num, nparams, arity, b_args) end | _ -> Bconstr c end | Ind ind -> Bstrconst (Const_ind ind) | Construct ((kn,j),i) -> begin spiwack : tries first to apply the run - time compilation behavior of the constructor , as in 2/ above behavior of the constructor, as in 2/ above *) try Bspecial ((Retroknowledge.get_vm_constant_dynamic_info (!global_env).retroknowledge (kind_of_term c)), [| |]) with Not_found -> let oib = lookup_mind kn !global_env in let oip = oib.mind_packets.(j) in let num,arity = oip.mind_reloc_tbl.(i-1) in let nparams = oib.mind_nparams in if nparams + arity = 0 then Bstrconst(Const_b0 num) else Bconstruct_app(num,nparams,arity,[||]) end | _ -> Bconstr c let comp_args comp_expr reloc args sz cont = let nargs_m_1 = Array.length args - 1 in let c = ref (comp_expr reloc args.(0) (sz + nargs_m_1) cont) in for i = 1 to nargs_m_1 do c := comp_expr reloc args.(i) (sz + nargs_m_1 - i) (Kpush :: !c) done; !c let comp_app comp_fun comp_arg reloc f args sz cont = let nargs = Array.length args in match is_tailcall cont with | Some k -> comp_args comp_arg reloc args sz (Kpush :: comp_fun reloc f (sz + nargs) (Kappterm(nargs, k + nargs) :: (discard_dead_code cont))) | None -> if nargs < 4 then comp_args comp_arg reloc args sz (Kpush :: (comp_fun reloc f (sz+nargs) (Kapply nargs :: cont))) else let lbl,cont1 = label_code cont in Kpush_retaddr lbl :: (comp_args comp_arg reloc args (sz + 3) (Kpush :: (comp_fun reloc f (sz+3+nargs) (Kapply nargs :: cont1)))) let compile_fv_elem reloc fv sz cont = match fv with | FVrel i -> pos_rel i reloc sz :: cont | FVnamed id -> pos_named id reloc :: cont let rec compile_fv reloc l sz cont = match l with | [] -> cont | [fvn] -> compile_fv_elem reloc fvn sz cont | fvn :: tl -> compile_fv_elem reloc fvn sz (Kpush :: compile_fv reloc tl (sz + 1) cont) let rec get_allias env kn = let tps = (lookup_constant kn env).const_body_code in match Cemitcodes.force tps with | BCallias kn' -> get_allias env kn' | _ -> kn let rec compile_constr reloc c sz cont = match kind_of_term c with | Meta _ -> raise (Invalid_argument "Cbytegen.compile_constr : Meta") | Evar _ -> raise (Invalid_argument "Cbytegen.compile_constr : Evar") | Cast(c,_,_) -> compile_constr reloc c sz cont | Rel i -> pos_rel i reloc sz :: cont | Var id -> pos_named id reloc :: cont | Const kn -> compile_const reloc kn [||] sz cont | Sort _ | Ind _ | Construct _ -> compile_str_cst reloc (str_const c) sz cont | LetIn(_,xb,_,body) -> compile_constr reloc xb sz (Kpush :: (compile_constr (push_local sz reloc) body (sz+1) (add_pop 1 cont))) | Prod(id,dom,codom) -> let cont1 = Kpush :: compile_constr reloc dom (sz+1) (Kmakeprod :: cont) in compile_constr reloc (mkLambda(id,dom,codom)) sz cont1 | Lambda _ -> let params, body = decompose_lam c in let arity = List.length params in let r_fun = comp_env_fun arity in let lbl_fun = Label.create() in let cont_fun = compile_constr r_fun body arity [Kreturn arity] in fun_code := [Ksequence(add_grab arity lbl_fun cont_fun,!fun_code)]; let fv = fv r_fun in compile_fv reloc fv.fv_rev sz (Kclosure(lbl_fun,fv.size) :: cont) | App(f,args) -> begin match kind_of_term f with | Construct _ -> compile_str_cst reloc (str_const c) sz cont | Const kn -> compile_const reloc kn args sz cont | _ -> comp_app compile_constr compile_constr reloc f args sz cont end | Fix ((rec_args,init),(_,type_bodies,rec_bodies)) -> let ndef = Array.length type_bodies in let rfv = ref empty_fv in let lbl_types = Array.create ndef Label.no in let lbl_bodies = Array.create ndef Label.no in let env_type = comp_env_fix_type rfv in for i = 0 to ndef - 1 do let lbl,fcode = label_code (compile_constr env_type type_bodies.(i) 0 [Kstop]) in lbl_types.(i) <- lbl; fun_code := [Ksequence(fcode,!fun_code)] done; for i = 0 to ndef - 1 do let params,body = decompose_lam rec_bodies.(i) in let arity = List.length params in let env_body = comp_env_fix ndef i arity rfv in let cont1 = compile_constr env_body body arity [Kreturn arity] in let lbl = Label.create () in lbl_bodies.(i) <- lbl; let fcode = add_grabrec rec_args.(i) arity lbl cont1 in fun_code := [Ksequence(fcode,!fun_code)] done; let fv = !rfv in compile_fv reloc fv.fv_rev sz (Kclosurerec(fv.size,init,lbl_types,lbl_bodies) :: cont) | CoFix(init,(_,type_bodies,rec_bodies)) -> let ndef = Array.length type_bodies in let lbl_types = Array.create ndef Label.no in let lbl_bodies = Array.create ndef Label.no in let rfv = ref empty_fv in let env_type = comp_env_cofix_type ndef rfv in for i = 0 to ndef - 1 do let lbl,fcode = label_code (compile_constr env_type type_bodies.(i) 0 [Kstop]) in lbl_types.(i) <- lbl; fun_code := [Ksequence(fcode,!fun_code)] done; for i = 0 to ndef - 1 do let params,body = decompose_lam rec_bodies.(i) in let arity = List.length params in let env_body = comp_env_cofix ndef arity rfv in let lbl = Label.create () in let cont1 = compile_constr env_body body (arity+1) (cont_cofix arity) in let cont2 = add_grab (arity+1) lbl cont1 in lbl_bodies.(i) <- lbl; fun_code := [Ksequence(cont2,!fun_code)]; done; let fv = !rfv in compile_fv reloc fv.fv_rev sz (Kclosurecofix(fv.size, init, lbl_types, lbl_bodies) :: cont) | Case(ci,t,a,branchs) -> let ind = ci.ci_ind in let mib = lookup_mind (fst ind) !global_env in let oib = mib.mind_packets.(snd ind) in let tbl = oib.mind_reloc_tbl in let lbl_consts = Array.create oib.mind_nb_constant Label.no in let lbl_blocks = Array.create (oib.mind_nb_args+1) Label.no in let branch1,cont = make_branch cont in let lbl_typ,fcode = label_code (compile_constr reloc t sz [Kpop sz; Kstop]) in fun_code := [Ksequence(fcode,!fun_code)]; let lbl_sw = Label.create () in let sz_b,branch,is_tailcall = match branch1 with | Kreturn k -> assert (k = sz); sz, branch1, true | _ -> sz+3, Kjump, false in let annot = {ci = ci; rtbl = tbl; tailcall = is_tailcall} in let lbl_accu, code_accu = label_code(Kmakeswitchblock(lbl_typ,lbl_sw,annot,sz) :: branch::cont) in lbl_blocks.(0) <- lbl_accu; let c = ref code_accu in for i = 0 to Array.length tbl - 1 do let tag, arity = tbl.(i) in if arity = 0 then let lbl_b,code_b = label_code(compile_constr reloc branchs.(i) sz_b (branch :: !c)) in lbl_consts.(tag) <- lbl_b; c := code_b else let args, body = decompose_lam branchs.(i) in let nargs = List.length args in let lbl_b,code_b = label_code( if nargs = arity then Kpushfields arity :: compile_constr (push_param arity sz_b reloc) body (sz_b+arity) (add_pop arity (branch :: !c)) else let sz_appterm = if is_tailcall then sz_b + arity else arity in Kpushfields arity :: compile_constr reloc branchs.(i) (sz_b+arity) (Kappterm(arity,sz_appterm) :: !c)) in lbl_blocks.(tag) <- lbl_b; c := code_b done; c := Klabel lbl_sw :: Kswitch(lbl_consts,lbl_blocks) :: !c; let code_sw = match branch1 with spiwack : ca n't be a lbl anymore it 's a Branch instead | Kpush_retaddr lbl : : ! c | Klabel lbl -> Kpush_retaddr lbl :: !c *) | Kbranch lbl -> Kpush_retaddr lbl :: !c | _ -> !c in compile_constr reloc a sz (try let entry = Term.Ind ind in Retroknowledge.get_vm_before_match_info (!global_env).retroknowledge entry code_sw with Not_found -> code_sw) and compile_str_cst reloc sc sz cont = match sc with | Bconstr c -> compile_constr reloc c sz cont | Bstrconst sc -> Kconst sc :: cont | Bmakeblock(tag,args) -> let nargs = Array.length args in comp_args compile_str_cst reloc args sz (Kmakeblock(nargs,tag) :: cont) | Bconstruct_app(tag,nparams,arity,args) -> if Array.length args = 0 then code_construct tag nparams arity cont else comp_app (fun _ _ _ cont -> code_construct tag nparams arity cont) compile_str_cst reloc () args sz cont | Bspecial (comp_fx, args) -> comp_fx reloc args sz cont spiwack : compilation of constants with their arguments . Makes a special treatment with 31 - bit integer addition Makes a special treatment with 31-bit integer addition *) and compile_const = fun reloc-> fun kn -> fun args -> fun sz -> fun cont -> let nargs = Array.length args in try Retroknowledge.get_vm_compiling_info (!global_env).retroknowledge (kind_of_term (mkConst kn)) reloc args sz cont with Not_found -> if nargs = 0 then Kgetglobal (get_allias !global_env kn) :: cont else comp_app (fun _ _ _ cont -> Kgetglobal (get_allias !global_env kn) :: cont) compile_constr reloc () args sz cont let compile env c = set_global_env env; init_fun_code (); Label.reset_label_counter (); let reloc = empty_comp_env () in let init_code = compile_constr reloc c 0 [Kstop] in let fv = List.rev (!(reloc.in_env).fv_rev) in draw_instr init_code ; draw_instr ! fun_code ; Format.print_string " fv = " ; List.iter ( fun v - > match v with | FVnamed i d - > Format.print_string ( ( string_of_id id)^ " ; " ) | FVrel i - > Format.print_string ( ( string_of_int i)^ " ; " ) ) fv ; Format .print_string " \n " ; Format.print_flush ( ) ; draw_instr !fun_code; Format.print_string "fv = "; List.iter (fun v -> match v with | FVnamed id -> Format.print_string ((string_of_id id)^"; ") | FVrel i -> Format.print_string ((string_of_int i)^"; ")) fv; Format .print_string "\n"; Format.print_flush(); *) init_code,!fun_code, Array.of_list fv let compile_constant_body env body opaque boxed = if opaque then BCconstant else match body with | None -> BCconstant | Some sb -> let body = Declarations.force sb in if boxed then let res = compile env body in let to_patch = to_memory res in BCdefined(true, to_patch) else match kind_of_term body with | Const kn' -> let con= constant_of_kn (canonical_con kn') in BCallias (get_allias env con) | _ -> let res = compile env body in let to_patch = to_memory res in BCdefined (false, to_patch) spiwack : additional function which allow different part of compilation of the 31 - bit integers 31-bit integers *) let make_areconst n else_lbl cont = if n <=0 then cont else Kareconst (n, else_lbl)::cont let compile_structured_int31 fc args = if not fc then raise Not_found else Const_b0 (Array.fold_left (fun temp_i -> fun t -> match kind_of_term t with | Construct (_,d) -> 2*temp_i+d-1 | _ -> raise NotClosed) 0 args ) this function is used for the compilation of the constructor of the int31 , it is used when it appears not fully applied , or applied to at least one non - closed digit the int31, it is used when it appears not fully applied, or applied to at least one non-closed digit *) let dynamic_int31_compilation fc reloc args sz cont = if not fc then raise Not_found else let nargs = Array.length args in if nargs = 31 then let (escape,labeled_cont) = make_branch cont in let else_lbl = Label.create() in comp_args compile_str_cst reloc args sz ( Kisconst else_lbl::Kareconst(30,else_lbl)::Kcompint31::escape::Klabel else_lbl::Kmakeblock(31, 1)::labeled_cont) else let f_cont = let else_lbl = Label.create () in [Kacc 0; Kpop 1; Kisconst else_lbl; Kareconst(30,else_lbl); Kcompint31; Kreturn 0; Klabel else_lbl; Kmakeblock(31, 1); Kreturn 0] in let lbl = Label.create() in fun_code := [Ksequence (add_grab 31 lbl f_cont,!fun_code)]; Kclosure(lbl,0) :: cont in if nargs = 0 then code_construct cont else comp_app (fun _ _ _ cont -> code_construct cont) compile_str_cst reloc () args sz cont ( * template compilation for 2ary operation , it probably possible to make a generic such function with arity abstracted to make a generic such function with arity abstracted *) let op2_compilation op = let f_cont = let else_lbl = Label.create () in Kareconst(2, else_lbl):: Kacc 0:: Kpop 1:: op:: Kreturn 0:: Klabel else_lbl:: works as comp_app with and tailcall cont [ Kreturn 0 ] ( get_allias ! global_env kn ): : normal:: in let lbl = Label.create () in fun_code := [Ksequence (add_grab 2 lbl f_cont, !fun_code)]; Kclosure(lbl, 0)::cont in fun normal fc _ reloc args sz cont -> if not fc then raise Not_found else let nargs = Array.length args in let (escape, labeled_cont) = make_branch cont in let else_lbl = Label.create () in comp_args compile_constr reloc args sz (Kisconst else_lbl::(make_areconst 1 else_lbl (op::escape::Klabel else_lbl::Kpush:: works as comp_app with and non - tailcall cont ( get_allias ! global_env kn ): : normal:: Kapply 2::labeled_cont))) else if nargs=0 then code_construct normal cont else comp_app (fun _ _ _ cont -> code_construct normal cont) compile_constr reloc () args sz cont *) template for n - ary operation , invariant : n>=1 , the operations does the following : 1/ checks if all the arguments are constants ( i.e. non - block values ) 2/ if they are , uses the " op " instruction to execute 3/ if at least one is not , branches to the normal behavior : ( get_allias ! ) the operations does the following : 1/ checks if all the arguments are constants (i.e. non-block values) 2/ if they are, uses the "op" instruction to execute 3/ if at least one is not, branches to the normal behavior: Kgetglobal (get_allias !global_env kn) *) let op_compilation n op = let code_construct kn cont = let f_cont = let else_lbl = Label.create () in Kareconst(n, else_lbl):: Kacc 0:: Kpop 1:: op:: Kreturn 0:: Klabel else_lbl:: works as comp_app with nargs = n and tailcall cont [ Kreturn 0 ] Kgetglobal (get_allias !global_env kn):: in let lbl = Label.create () in fun_code := [Ksequence (add_grab n lbl f_cont, !fun_code)]; Kclosure(lbl, 0)::cont in fun kn fc reloc args sz cont -> if not fc then raise Not_found else let nargs = Array.length args in let (escape, labeled_cont) = make_branch cont in let else_lbl = Label.create () in comp_args compile_constr reloc args sz (Kisconst else_lbl::(make_areconst (n-1) else_lbl (op::escape::Klabel else_lbl::Kpush:: works as comp_app with nargs = n and non - tailcall cont Kgetglobal (get_allias !global_env kn):: Kapply n::labeled_cont))) else if nargs=0 then code_construct kn cont else comp_app (fun _ _ _ cont -> code_construct kn cont) compile_constr reloc () args sz cont let int31_escape_before_match fc cont = if not fc then raise Not_found else let escape_lbl, labeled_cont = label_code cont in (Kisconst escape_lbl)::Kdecompint31::labeled_cont
dd48b66230b7d03194c543369a3f2eb208a9aecc261faca1cbd9b0f7d1a9eabc
katox/neanderthal-stick
nippy_ext.clj
Copyright ( c ) . All rights reserved . ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 2.0 (-2.0) or later ;; which can be found in the file LICENSE at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns neanderthal-stick.nippy-ext (:require [taoensso.nippy :as nippy] [uncomplicate.commons.core :refer [info let-release release with-release]] [uncomplicate.commons.utils :refer [dragan-says-ex]] [uncomplicate.neanderthal.core :refer [transfer!]] [uncomplicate.neanderthal.internal.api :as api] [neanderthal-stick.core :refer [describe create]] [neanderthal-stick.internal.common :as common])) (def ^{:dynamic true :doc "Dynamically bound factory that is used in Neanderthal vector and matrix constructors."} *neanderthal-factory* nil) (defmacro with-real-factory "Create a bind to use the `factory` during Neanderthal real vector and matrix construction. ``` (clojurecuda/with-default (with-open [in (DataInputStream. (io/input-stream (io/file \"/tmp/my_matrix.bin\")))] (with-neanderthal-factory (cuda-double (current-context) default-stream) (nippy/thaw-from-in! in))) ``` " [factory & body] `(binding [*neanderthal-factory* ~factory] ~@body)) (defn- freeze-to-out! "Freeze ContainerInfo `x` and its contents to the `data-output` stream." [data-output x] (nippy/freeze-to-out! data-output (describe x)) (transfer! x data-output) nil) (defn- freeze-through-native! "Freeze `x` to `data-output` by using a temp copy in host memory if needed." [data-output x] (let [native-x (api/native x)] (try (nippy/freeze-to-out! data-output native-x) (finally (when-not (identical? native-x x) (release native-x)))))) (defn- thaw-from-in! "Thaw a previously frozen descriptor from the `data-input to a new Neanderthal structure." [data-input] (let [factory *neanderthal-factory* descriptor (nippy/thaw-from-in! data-input) ext-options (:ext-options descriptor) input (when-not (common/options-omit-data? ext-options) data-input)] (if (and factory input (not (common/native-factory? factory))) (let [native-x (create descriptor)] (let-release [x (api/raw native-x factory)] (try (transfer! input x) (finally (release native-x))))) (let-release [x (create factory descriptor)] (if input (transfer! input x) x))))) ;; =================== Extend Neanderthal Types with Nippy Protocols =================== (nippy/extend-freeze uncomplicate.neanderthal.internal.host.buffer_block.RealBlockVector :uncomplicate.neanderthal/RealBlockVector [x data-output] (freeze-to-out! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/RealBlockVector [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.host.buffer_block.IntegerBlockVector :uncomplicate.neanderthal/IntegerBlockVector [x data-output] (freeze-to-out! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/IntegerBlockVector [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.host.buffer_block.RealGEMatrix :uncomplicate.neanderthal/RealGEMatrix [x data-output] (freeze-to-out! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/RealGEMatrix [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.host.buffer_block.RealUploMatrix :uncomplicate.neanderthal/RealUploMatrix [x data-output] (freeze-to-out! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/RealUploMatrix [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.host.buffer_block.RealBandedMatrix :uncomplicate.neanderthal/RealBandedMatrix [x data-output] (freeze-to-out! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/RealBandedMatrix [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.host.buffer_block.RealPackedMatrix :uncomplicate.neanderthal/RealPackedMatrix [x data-output] (freeze-to-out! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/RealPackedMatrix [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.host.buffer_block.RealDiagonalMatrix :uncomplicate.neanderthal/RealDiagonalMatrix [x data-output] (freeze-to-out! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/RealDiagonalMatrix [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.api.CUVector :uncomplicate.neanderthal/CUVector [x data-output] (freeze-through-native! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/CUVector [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.api.CUMatrix :uncomplicate.neanderthal/CUMatrix [x data-output] (freeze-through-native! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/CUMatrix [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.api.CLVector :uncomplicate.neanderthal/CLVector [x data-output] (freeze-through-native! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/CLVector [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.api.CLMatrix :uncomplicate.neanderthal/CLMatrix [x data-output] (freeze-through-native! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/CLMatrix [data-input] (thaw-from-in! data-input))
null
https://raw.githubusercontent.com/katox/neanderthal-stick/b8f92e46327a54c065232a1fb0f0bebef38c4b40/src/neanderthal_stick/nippy_ext.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 2.0 (-2.0) or later which can be found in the file LICENSE 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. =================== Extend Neanderthal Types with Nippy Protocols ===================
Copyright ( c ) . All rights reserved . (ns neanderthal-stick.nippy-ext (:require [taoensso.nippy :as nippy] [uncomplicate.commons.core :refer [info let-release release with-release]] [uncomplicate.commons.utils :refer [dragan-says-ex]] [uncomplicate.neanderthal.core :refer [transfer!]] [uncomplicate.neanderthal.internal.api :as api] [neanderthal-stick.core :refer [describe create]] [neanderthal-stick.internal.common :as common])) (def ^{:dynamic true :doc "Dynamically bound factory that is used in Neanderthal vector and matrix constructors."} *neanderthal-factory* nil) (defmacro with-real-factory "Create a bind to use the `factory` during Neanderthal real vector and matrix construction. ``` (clojurecuda/with-default (with-open [in (DataInputStream. (io/input-stream (io/file \"/tmp/my_matrix.bin\")))] (with-neanderthal-factory (cuda-double (current-context) default-stream) (nippy/thaw-from-in! in))) ``` " [factory & body] `(binding [*neanderthal-factory* ~factory] ~@body)) (defn- freeze-to-out! "Freeze ContainerInfo `x` and its contents to the `data-output` stream." [data-output x] (nippy/freeze-to-out! data-output (describe x)) (transfer! x data-output) nil) (defn- freeze-through-native! "Freeze `x` to `data-output` by using a temp copy in host memory if needed." [data-output x] (let [native-x (api/native x)] (try (nippy/freeze-to-out! data-output native-x) (finally (when-not (identical? native-x x) (release native-x)))))) (defn- thaw-from-in! "Thaw a previously frozen descriptor from the `data-input to a new Neanderthal structure." [data-input] (let [factory *neanderthal-factory* descriptor (nippy/thaw-from-in! data-input) ext-options (:ext-options descriptor) input (when-not (common/options-omit-data? ext-options) data-input)] (if (and factory input (not (common/native-factory? factory))) (let [native-x (create descriptor)] (let-release [x (api/raw native-x factory)] (try (transfer! input x) (finally (release native-x))))) (let-release [x (create factory descriptor)] (if input (transfer! input x) x))))) (nippy/extend-freeze uncomplicate.neanderthal.internal.host.buffer_block.RealBlockVector :uncomplicate.neanderthal/RealBlockVector [x data-output] (freeze-to-out! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/RealBlockVector [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.host.buffer_block.IntegerBlockVector :uncomplicate.neanderthal/IntegerBlockVector [x data-output] (freeze-to-out! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/IntegerBlockVector [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.host.buffer_block.RealGEMatrix :uncomplicate.neanderthal/RealGEMatrix [x data-output] (freeze-to-out! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/RealGEMatrix [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.host.buffer_block.RealUploMatrix :uncomplicate.neanderthal/RealUploMatrix [x data-output] (freeze-to-out! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/RealUploMatrix [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.host.buffer_block.RealBandedMatrix :uncomplicate.neanderthal/RealBandedMatrix [x data-output] (freeze-to-out! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/RealBandedMatrix [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.host.buffer_block.RealPackedMatrix :uncomplicate.neanderthal/RealPackedMatrix [x data-output] (freeze-to-out! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/RealPackedMatrix [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.host.buffer_block.RealDiagonalMatrix :uncomplicate.neanderthal/RealDiagonalMatrix [x data-output] (freeze-to-out! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/RealDiagonalMatrix [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.api.CUVector :uncomplicate.neanderthal/CUVector [x data-output] (freeze-through-native! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/CUVector [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.api.CUMatrix :uncomplicate.neanderthal/CUMatrix [x data-output] (freeze-through-native! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/CUMatrix [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.api.CLVector :uncomplicate.neanderthal/CLVector [x data-output] (freeze-through-native! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/CLVector [data-input] (thaw-from-in! data-input)) (nippy/extend-freeze uncomplicate.neanderthal.internal.api.CLMatrix :uncomplicate.neanderthal/CLMatrix [x data-output] (freeze-through-native! data-output x)) (nippy/extend-thaw :uncomplicate.neanderthal/CLMatrix [data-input] (thaw-from-in! data-input))
02ffd50dbaa4ed3fa059cbc156ebee50f3de3e48c99e60c8c321069708223c4b
PacktPublishing/Haskell-High-Performance-Programming
th-names.hs
# LANGUAGE TemplateHaskell # import Language.Haskell.TH n = 5 main = print $(fmap VarE (newName "n")) where n = 1
null
https://raw.githubusercontent.com/PacktPublishing/Haskell-High-Performance-Programming/2b1bfdb8102129be41e8d79c7e9caf12100c5556/Chapter09/th-names.hs
haskell
# LANGUAGE TemplateHaskell # import Language.Haskell.TH n = 5 main = print $(fmap VarE (newName "n")) where n = 1
fc721dcb67104cb325b6e3eddc49f207bed55fda96690c6deed911fddafb837b
jaylevitt/gibak
ometastore.ml
Copyright ( C ) 2008 < > http//eigenclass.org * See README.txt and LICENSE for the redistribution and modification terms * See README.txt and LICENSE for the redistribution and modification terms *) open Printf open Unix open Folddir open Util open FileUtil.StrUtil let debug = ref false let verbose = ref false let use_mtime = ref false let use_xattrs = ref false let magic = "Ometastore" let version = "1.1.0" type xattr = { name : string; value : string } type entry = { path : string; owner : string; group : string; mode : int; mtime : float; kind : Unix.file_kind; xattrs : xattr list; } type whatsnew = Added of entry | Deleted of entry | Diff of entry * entry external utime : string -> nativeint -> unit = "perform_utime" external llistxattr : string -> string list = "perform_llistxattr" external lgetxattr : string -> string -> string = "perform_lgetxattr" external lsetxattr : string -> string -> string -> unit = "perform_lsetxattr" external lremovexattr : string -> string -> unit = "perform_lremovexattr" let user_name = memoized (fun uid -> try (getpwuid uid).pw_name with Not_found -> try (getpwuid (getuid ())).pw_name with Not_found -> Sys.getenv("USER")) let group_name = memoized (fun gid -> try (getgrgid gid).gr_name with Not_found -> try (getgrgid (getgid ())).gr_name with Not_found -> Sys.getenv("USER")) let int_of_file_kind = function S_REG -> 0 | S_DIR -> 1 | S_CHR -> 2 | S_BLK -> 3 | S_LNK -> 4 | S_FIFO -> 5 | S_SOCK -> 6 let kind_of_int = function 0 -> S_REG | 1 -> S_DIR | 2 -> S_CHR | 3 -> S_BLK | 4 -> S_LNK | 5 -> S_FIFO | 6 -> S_SOCK | _ -> invalid_arg "kind_of_int" let entry_of_path path = let s = lstat path in let user = user_name s.st_uid in let group = group_name s.st_gid in let xattrs = List.map (fun attr -> { name = attr; value = lgetxattr path attr; }) (List.sort compare (llistxattr path)) in { path = path; owner = user; group = group; mode = s.st_perm; kind = s.st_kind; mtime = s.st_mtime; xattrs = xattrs } module Entries(F : Folddir.S) = struct let get_entries ?(debug=false) ?(sorted=false) path = let aux l name stat = let fullname = join path name in let entry = { (entry_of_path fullname) with path = name } in match stat.st_kind with | S_DIR -> begin try access (join fullname ".git") [F_OK]; Prune (entry :: l) with Unix_error _ -> Continue (entry :: l) end | _ -> Continue (entry :: l) in List.rev (F.fold_directory ~debug ~sorted aux [] path "") end let write_int os bytes n = for i = bytes - 1 downto 0 do output_char os (Char.chr ((n lsr (i lsl 3)) land 0xFF)) done let read_int is bytes = let r = ref 0 in for i = 0 to bytes - 1 do r := !r lsl 8 + Char.code (input_char is) done; !r let write_xstring os s = write_int os 4 (String.length s); output_string os s let read_xstring is = let len = read_int is 4 in let s = String.create len in really_input is s 0 len; s let common_prefix_chars s1 s2 = let rec loop s1 s2 i max = if s1.[i] = s2.[i] then if i < max then loop s1 s2 (i+1) max else i + 1 else i in if String.length s1 = 0 || String.length s2 = 0 then 0 else loop s1 s2 0 (min (String.length s1 - 1) (String.length s2 -1)) let dump_entries ?(verbose=false) ?(sorted=false) l fname = let dump_entry os prev e = if verbose then printf "%s\n" e.path; let pref = common_prefix_chars prev e.path in write_int os 2 pref; write_xstring os (String.sub e.path pref (String.length e.path - pref)); write_xstring os e.owner; write_xstring os e.group; write_xstring os (string_of_float e.mtime); write_int os 2 e.mode; write_int os 1 (int_of_file_kind e.kind); write_int os 2 (List.length e.xattrs); List.iter (fun t -> write_xstring os t.name; write_xstring os t.value) e.xattrs; e.path in do_finally (open_out_bin fname) close_out begin fun os -> output_string os (magic ^ "\n"); output_string os (version ^ "\n"); let l = if sorted then List.sort compare l else l in ignore (List.fold_left (dump_entry os) "" l) end let read_entries fname = let read_entry is prev = let pref = read_int is 2 in let path = String.sub prev 0 pref ^ read_xstring is in let owner = read_xstring is in let group = read_xstring is in let mtime = float_of_string (read_xstring is) in let mode = read_int is 2 in let kind = kind_of_int (read_int is 1) in let nattrs = read_int is 2 in let attrs = ref [] in for i = 1 to nattrs do let name = read_xstring is in let value = read_xstring is in attrs := { name = name; value = value } :: !attrs done; { path = path; owner = owner; group = group; mtime = mtime; mode = mode; kind = kind; xattrs = List.rev !attrs } in do_finally (open_in_bin fname) close_in begin fun is -> if magic <> input_line is then failwith "Invalid file: bad magic"; let _ = input_line is (* version *) in let entries = ref [] in let prev = ref "" in try while true do let e = read_entry is !prev in entries := e :: !entries; prev := e.path done; assert false with End_of_file -> !entries end module SMap = Map.Make(struct type t = string let compare = compare end) let compare_entries l1 l2 = let to_map l = List.fold_left (fun m e -> SMap.add e.path e m) SMap.empty l in let m1 = to_map l1 in let m2 = to_map l2 in let changes = List.fold_left (fun changes e2 -> try let e1 = SMap.find e2.path m1 in if e1 = e2 then changes else Diff (e1, e2) :: changes with Not_found -> Added e2 :: changes) [] l2 in let deletions = List.fold_left (fun dels e1 -> if SMap.mem e1.path m2 then dels else Deleted e1 :: dels) [] l1 in List.rev (List.rev_append deletions changes) let print_changes ?(sorted=false) l = List.iter (function Added e -> printf "Added: %s\n" e.path | Deleted e -> printf "Deleted: %s\n" e.path | Diff (e1, e2) -> let test name f s = if f e1 <> f e2 then name :: s else s in let (++) x f = f x in let diffs = test "owner" (fun x -> x.owner) [] ++ test "group" (fun x -> x.group) ++ test "mode" (fun x -> x.mode) ++ test "kind" (fun x -> x.kind) ++ test "mtime" (if !use_mtime then (fun x -> x.mtime) else (fun _ -> 0.)) ++ test "xattr" (if !use_xattrs then (fun x -> x.xattrs) else (fun _ -> [])) in match List.rev diffs with [] -> () | l -> printf "Changed %s: %s\n" e1.path (String.concat " " l)) (if sorted then List.sort compare l else l) let print_deleted ?(sorted=false) separator l = List.iter (function Deleted e -> printf "%s%s" e.path separator | Added _ | Diff _ -> ()) (if sorted then List.sort compare l else l) let out s = if !verbose then Printf.fprintf Pervasives.stdout s else Printf.ifprintf Pervasives.stdout s let fix_usergroup e = try out "%s: set owner/group to %S %S\n" e.path e.owner e.group; chown e.path (getpwnam e.owner).pw_uid (getgrnam e.group).gr_gid; with Unix_error _ -> ( out "chown failed: %s\n" e.path ) let fix_xattrs src dst = out "%s: fixing xattrs (" src.path; let to_map l = List.fold_left (fun m e -> SMap.add e.name e.value m) SMap.empty l in let set_attr name value = out "+%S, " name; try lsetxattr src.path name value with Failure _ -> () in let del_attr name = out "-%S, " name; try lremovexattr src.path name with Failure _ -> () in let src = to_map src.xattrs in let dst = to_map dst.xattrs in SMap.iter (fun name value -> try if SMap.find name dst <> SMap.find name src then set_attr name value with Not_found -> set_attr name value) dst; remove deleted SMap.iter (fun name _ -> if not (SMap.mem name dst) then del_attr name) src; out ")\n" let apply_change = function | Added e when e.kind = S_DIR -> out "%s: mkdir (mode %04o)\n" e.path e.mode; mkdir ~parent:true e.path; chmod e.path e.mode; fix_usergroup e | Deleted _ | Added _ -> () | Diff (e1, e2) -> if e1.owner <> e2.owner || e1.group <> e2.group then fix_usergroup e2; if e1.mode <> e2.mode then begin out "%s: chmod %04o\n" e2.path e2.mode; chmod e2.path e2.mode; end; if e1.kind <> e2.kind then printf "%s: file type of changed (nothing done)\n" e1.path; if !use_mtime && e1.mtime <> e2.mtime then begin out "%s: mtime set to %.0f\n" e1.path e2.mtime; try utime e2.path (Nativeint.of_float e2.mtime) with Failure _ -> ( out "utime failed: %s\n" e1.path ) end; if !use_xattrs && e1.xattrs <> e2.xattrs then fix_xattrs e1 e2 let apply_changes path l = List.iter apply_change (List.rev (List.rev_map (function Added _ | Deleted _ as x -> x | Diff (e1, e2) -> Diff ({ e1 with path = join path e1.path}, { e2 with path = join path e2.path})) l) ) module Allentries = Entries(Folddir.Make(Folddir.Ignore_none)) module Gitignored = Entries(Folddir.Make(Folddir.Gitignore)) let main () = let usage = "Usage: ometastore COMMAND [options]\n\ where COMMAND is -c, -d, -s or -a.\n" in let mode = ref `Unset in let file = ref ".ometastore" in let path = ref "." in let get_entries = ref Allentries.get_entries in let sep = ref "\n" in let sorted = ref false in let specs = [ "-c", Arg.Unit (fun () -> mode := `Compare), "show all differences between stored and real metadata"; "-d", Arg.Unit (fun () -> mode := `Show_deleted), "show only files deleted or newly ignored"; "-s", Arg.Unit (fun () -> mode := `Save), "save metadata"; "-a", Arg.Unit (fun () -> mode := `Apply), "apply current metadata"; "-i", Arg.Unit (fun () -> get_entries := Gitignored.get_entries), "mimic git semantics (honor .gitignore, don't scan git submodules)"; "-m", Arg.Set use_mtime, "consider mtime for diff and apply"; "-x", Arg.Set use_xattrs, "consider extended attributes for diff and apply"; "-z", Arg.Unit (fun () -> sep := "\000"), "use \\0 to separate filenames"; "--sort", Arg.Set sorted, "sort output by filename"; "-v", Arg.Set verbose, "verbose mode"; "--debug", Arg.Set debug, "debug mode"; "--version", Arg.Unit (fun () -> printf "ometastore version %s\n" version; exit 0), "show version info"; ] in Arg.parse specs ignore usage; match !mode with | `Unset -> Arg.usage specs usage | `Save -> dump_entries ~sorted:!sorted ~verbose:!verbose (!get_entries !path) !file | `Show_deleted | `Compare | `Apply as mode -> let stored = read_entries !file in let actual = !get_entries ~debug:!debug !path in match mode with `Compare -> print_changes ~sorted:!sorted (compare_entries stored actual) | `Apply -> apply_changes !path (compare_entries actual stored) | `Show_deleted -> print_deleted ~sorted:!sorted !sep (compare_entries stored actual) let () = main ()
null
https://raw.githubusercontent.com/jaylevitt/gibak/4fa77cda38c3a61af5e1bf9ead0a63c6824fd6ce/ometastore.ml
ocaml
version
Copyright ( C ) 2008 < > http//eigenclass.org * See README.txt and LICENSE for the redistribution and modification terms * See README.txt and LICENSE for the redistribution and modification terms *) open Printf open Unix open Folddir open Util open FileUtil.StrUtil let debug = ref false let verbose = ref false let use_mtime = ref false let use_xattrs = ref false let magic = "Ometastore" let version = "1.1.0" type xattr = { name : string; value : string } type entry = { path : string; owner : string; group : string; mode : int; mtime : float; kind : Unix.file_kind; xattrs : xattr list; } type whatsnew = Added of entry | Deleted of entry | Diff of entry * entry external utime : string -> nativeint -> unit = "perform_utime" external llistxattr : string -> string list = "perform_llistxattr" external lgetxattr : string -> string -> string = "perform_lgetxattr" external lsetxattr : string -> string -> string -> unit = "perform_lsetxattr" external lremovexattr : string -> string -> unit = "perform_lremovexattr" let user_name = memoized (fun uid -> try (getpwuid uid).pw_name with Not_found -> try (getpwuid (getuid ())).pw_name with Not_found -> Sys.getenv("USER")) let group_name = memoized (fun gid -> try (getgrgid gid).gr_name with Not_found -> try (getgrgid (getgid ())).gr_name with Not_found -> Sys.getenv("USER")) let int_of_file_kind = function S_REG -> 0 | S_DIR -> 1 | S_CHR -> 2 | S_BLK -> 3 | S_LNK -> 4 | S_FIFO -> 5 | S_SOCK -> 6 let kind_of_int = function 0 -> S_REG | 1 -> S_DIR | 2 -> S_CHR | 3 -> S_BLK | 4 -> S_LNK | 5 -> S_FIFO | 6 -> S_SOCK | _ -> invalid_arg "kind_of_int" let entry_of_path path = let s = lstat path in let user = user_name s.st_uid in let group = group_name s.st_gid in let xattrs = List.map (fun attr -> { name = attr; value = lgetxattr path attr; }) (List.sort compare (llistxattr path)) in { path = path; owner = user; group = group; mode = s.st_perm; kind = s.st_kind; mtime = s.st_mtime; xattrs = xattrs } module Entries(F : Folddir.S) = struct let get_entries ?(debug=false) ?(sorted=false) path = let aux l name stat = let fullname = join path name in let entry = { (entry_of_path fullname) with path = name } in match stat.st_kind with | S_DIR -> begin try access (join fullname ".git") [F_OK]; Prune (entry :: l) with Unix_error _ -> Continue (entry :: l) end | _ -> Continue (entry :: l) in List.rev (F.fold_directory ~debug ~sorted aux [] path "") end let write_int os bytes n = for i = bytes - 1 downto 0 do output_char os (Char.chr ((n lsr (i lsl 3)) land 0xFF)) done let read_int is bytes = let r = ref 0 in for i = 0 to bytes - 1 do r := !r lsl 8 + Char.code (input_char is) done; !r let write_xstring os s = write_int os 4 (String.length s); output_string os s let read_xstring is = let len = read_int is 4 in let s = String.create len in really_input is s 0 len; s let common_prefix_chars s1 s2 = let rec loop s1 s2 i max = if s1.[i] = s2.[i] then if i < max then loop s1 s2 (i+1) max else i + 1 else i in if String.length s1 = 0 || String.length s2 = 0 then 0 else loop s1 s2 0 (min (String.length s1 - 1) (String.length s2 -1)) let dump_entries ?(verbose=false) ?(sorted=false) l fname = let dump_entry os prev e = if verbose then printf "%s\n" e.path; let pref = common_prefix_chars prev e.path in write_int os 2 pref; write_xstring os (String.sub e.path pref (String.length e.path - pref)); write_xstring os e.owner; write_xstring os e.group; write_xstring os (string_of_float e.mtime); write_int os 2 e.mode; write_int os 1 (int_of_file_kind e.kind); write_int os 2 (List.length e.xattrs); List.iter (fun t -> write_xstring os t.name; write_xstring os t.value) e.xattrs; e.path in do_finally (open_out_bin fname) close_out begin fun os -> output_string os (magic ^ "\n"); output_string os (version ^ "\n"); let l = if sorted then List.sort compare l else l in ignore (List.fold_left (dump_entry os) "" l) end let read_entries fname = let read_entry is prev = let pref = read_int is 2 in let path = String.sub prev 0 pref ^ read_xstring is in let owner = read_xstring is in let group = read_xstring is in let mtime = float_of_string (read_xstring is) in let mode = read_int is 2 in let kind = kind_of_int (read_int is 1) in let nattrs = read_int is 2 in let attrs = ref [] in for i = 1 to nattrs do let name = read_xstring is in let value = read_xstring is in attrs := { name = name; value = value } :: !attrs done; { path = path; owner = owner; group = group; mtime = mtime; mode = mode; kind = kind; xattrs = List.rev !attrs } in do_finally (open_in_bin fname) close_in begin fun is -> if magic <> input_line is then failwith "Invalid file: bad magic"; let entries = ref [] in let prev = ref "" in try while true do let e = read_entry is !prev in entries := e :: !entries; prev := e.path done; assert false with End_of_file -> !entries end module SMap = Map.Make(struct type t = string let compare = compare end) let compare_entries l1 l2 = let to_map l = List.fold_left (fun m e -> SMap.add e.path e m) SMap.empty l in let m1 = to_map l1 in let m2 = to_map l2 in let changes = List.fold_left (fun changes e2 -> try let e1 = SMap.find e2.path m1 in if e1 = e2 then changes else Diff (e1, e2) :: changes with Not_found -> Added e2 :: changes) [] l2 in let deletions = List.fold_left (fun dels e1 -> if SMap.mem e1.path m2 then dels else Deleted e1 :: dels) [] l1 in List.rev (List.rev_append deletions changes) let print_changes ?(sorted=false) l = List.iter (function Added e -> printf "Added: %s\n" e.path | Deleted e -> printf "Deleted: %s\n" e.path | Diff (e1, e2) -> let test name f s = if f e1 <> f e2 then name :: s else s in let (++) x f = f x in let diffs = test "owner" (fun x -> x.owner) [] ++ test "group" (fun x -> x.group) ++ test "mode" (fun x -> x.mode) ++ test "kind" (fun x -> x.kind) ++ test "mtime" (if !use_mtime then (fun x -> x.mtime) else (fun _ -> 0.)) ++ test "xattr" (if !use_xattrs then (fun x -> x.xattrs) else (fun _ -> [])) in match List.rev diffs with [] -> () | l -> printf "Changed %s: %s\n" e1.path (String.concat " " l)) (if sorted then List.sort compare l else l) let print_deleted ?(sorted=false) separator l = List.iter (function Deleted e -> printf "%s%s" e.path separator | Added _ | Diff _ -> ()) (if sorted then List.sort compare l else l) let out s = if !verbose then Printf.fprintf Pervasives.stdout s else Printf.ifprintf Pervasives.stdout s let fix_usergroup e = try out "%s: set owner/group to %S %S\n" e.path e.owner e.group; chown e.path (getpwnam e.owner).pw_uid (getgrnam e.group).gr_gid; with Unix_error _ -> ( out "chown failed: %s\n" e.path ) let fix_xattrs src dst = out "%s: fixing xattrs (" src.path; let to_map l = List.fold_left (fun m e -> SMap.add e.name e.value m) SMap.empty l in let set_attr name value = out "+%S, " name; try lsetxattr src.path name value with Failure _ -> () in let del_attr name = out "-%S, " name; try lremovexattr src.path name with Failure _ -> () in let src = to_map src.xattrs in let dst = to_map dst.xattrs in SMap.iter (fun name value -> try if SMap.find name dst <> SMap.find name src then set_attr name value with Not_found -> set_attr name value) dst; remove deleted SMap.iter (fun name _ -> if not (SMap.mem name dst) then del_attr name) src; out ")\n" let apply_change = function | Added e when e.kind = S_DIR -> out "%s: mkdir (mode %04o)\n" e.path e.mode; mkdir ~parent:true e.path; chmod e.path e.mode; fix_usergroup e | Deleted _ | Added _ -> () | Diff (e1, e2) -> if e1.owner <> e2.owner || e1.group <> e2.group then fix_usergroup e2; if e1.mode <> e2.mode then begin out "%s: chmod %04o\n" e2.path e2.mode; chmod e2.path e2.mode; end; if e1.kind <> e2.kind then printf "%s: file type of changed (nothing done)\n" e1.path; if !use_mtime && e1.mtime <> e2.mtime then begin out "%s: mtime set to %.0f\n" e1.path e2.mtime; try utime e2.path (Nativeint.of_float e2.mtime) with Failure _ -> ( out "utime failed: %s\n" e1.path ) end; if !use_xattrs && e1.xattrs <> e2.xattrs then fix_xattrs e1 e2 let apply_changes path l = List.iter apply_change (List.rev (List.rev_map (function Added _ | Deleted _ as x -> x | Diff (e1, e2) -> Diff ({ e1 with path = join path e1.path}, { e2 with path = join path e2.path})) l) ) module Allentries = Entries(Folddir.Make(Folddir.Ignore_none)) module Gitignored = Entries(Folddir.Make(Folddir.Gitignore)) let main () = let usage = "Usage: ometastore COMMAND [options]\n\ where COMMAND is -c, -d, -s or -a.\n" in let mode = ref `Unset in let file = ref ".ometastore" in let path = ref "." in let get_entries = ref Allentries.get_entries in let sep = ref "\n" in let sorted = ref false in let specs = [ "-c", Arg.Unit (fun () -> mode := `Compare), "show all differences between stored and real metadata"; "-d", Arg.Unit (fun () -> mode := `Show_deleted), "show only files deleted or newly ignored"; "-s", Arg.Unit (fun () -> mode := `Save), "save metadata"; "-a", Arg.Unit (fun () -> mode := `Apply), "apply current metadata"; "-i", Arg.Unit (fun () -> get_entries := Gitignored.get_entries), "mimic git semantics (honor .gitignore, don't scan git submodules)"; "-m", Arg.Set use_mtime, "consider mtime for diff and apply"; "-x", Arg.Set use_xattrs, "consider extended attributes for diff and apply"; "-z", Arg.Unit (fun () -> sep := "\000"), "use \\0 to separate filenames"; "--sort", Arg.Set sorted, "sort output by filename"; "-v", Arg.Set verbose, "verbose mode"; "--debug", Arg.Set debug, "debug mode"; "--version", Arg.Unit (fun () -> printf "ometastore version %s\n" version; exit 0), "show version info"; ] in Arg.parse specs ignore usage; match !mode with | `Unset -> Arg.usage specs usage | `Save -> dump_entries ~sorted:!sorted ~verbose:!verbose (!get_entries !path) !file | `Show_deleted | `Compare | `Apply as mode -> let stored = read_entries !file in let actual = !get_entries ~debug:!debug !path in match mode with `Compare -> print_changes ~sorted:!sorted (compare_entries stored actual) | `Apply -> apply_changes !path (compare_entries actual stored) | `Show_deleted -> print_deleted ~sorted:!sorted !sep (compare_entries stored actual) let () = main ()
9ae6e47b43d746226bcfbd9941947939847485573ed71ec5e1089885d763cb86
dccsillag/dotfiles
Scratchpads.hs
module XMonad.Csillag.Scratchpads where import Data.List import XMonad import qualified XMonad.StackSet as W import XMonad.Util.NamedScratchpad import XMonad.Csillag.Externals -- Scratchpads: myScratchpads = [ NS { name = "sysmon" , cmd = termRun' "sysmon" systemMonitor , query = className =? "sysmon" , hook = floatingScratchpad } , NS { name = "whatsapp" , cmd = "brave --app=/" , query = className =? "Brave-browser" <&&> appName =? "web.whatsapp.com" , hook = floatingScratchpad } , NS { name = "telegram" , cmd = "telegram-desktop" , query = className =? "TelegramDesktop" , hook = floatingScratchpad } , NS { name = "terminal" , cmd = termSpawn' "scratchterm" , query = className =? "scratchterm" , hook = floatingScratchpad } , NS { name = "calculator" , cmd = termRun' "calculator" "insect" , query = className =? "calculator" , hook = floatingScratchpad } , NS { name = "audio" , cmd = termRun' "audiomanage" "pulsemixer" , query = className =? "audiomanage" , hook = floatingScratchpad } , NS { name = "deezer" , cmd = browserOpen "" , query = isSuffixOf "Deezer - qutebrowser" <$> title , hook = floatingScratchpad } , NS { name = "slack" , cmd = "slack -s" , query = className =? "Slack" , hook = floatingScratchpad } , NS { name = "discord" , cmd = "discord" , query = className =? "discord" , hook = floatingScratchpad } , NS { name = "mail" , cmd = "geary" , query = className =? "Geary" , hook = floatingScratchpad } , NS { name = "element" , cmd = "element-desktop" , query = className =? "Element" , hook = floatingScratchpad } ] where floatingScratchpad = customFloating $ W.RationalRect 0.05 0.05 0.9 0.9
null
https://raw.githubusercontent.com/dccsillag/dotfiles/1a8aa69b19c560ce7355990d15e28eb05eacfc65/.xmonad/lib/XMonad/Csillag/Scratchpads.hs
haskell
Scratchpads:
module XMonad.Csillag.Scratchpads where import Data.List import XMonad import qualified XMonad.StackSet as W import XMonad.Util.NamedScratchpad import XMonad.Csillag.Externals myScratchpads = [ NS { name = "sysmon" , cmd = termRun' "sysmon" systemMonitor , query = className =? "sysmon" , hook = floatingScratchpad } , NS { name = "whatsapp" , cmd = "brave --app=/" , query = className =? "Brave-browser" <&&> appName =? "web.whatsapp.com" , hook = floatingScratchpad } , NS { name = "telegram" , cmd = "telegram-desktop" , query = className =? "TelegramDesktop" , hook = floatingScratchpad } , NS { name = "terminal" , cmd = termSpawn' "scratchterm" , query = className =? "scratchterm" , hook = floatingScratchpad } , NS { name = "calculator" , cmd = termRun' "calculator" "insect" , query = className =? "calculator" , hook = floatingScratchpad } , NS { name = "audio" , cmd = termRun' "audiomanage" "pulsemixer" , query = className =? "audiomanage" , hook = floatingScratchpad } , NS { name = "deezer" , cmd = browserOpen "" , query = isSuffixOf "Deezer - qutebrowser" <$> title , hook = floatingScratchpad } , NS { name = "slack" , cmd = "slack -s" , query = className =? "Slack" , hook = floatingScratchpad } , NS { name = "discord" , cmd = "discord" , query = className =? "discord" , hook = floatingScratchpad } , NS { name = "mail" , cmd = "geary" , query = className =? "Geary" , hook = floatingScratchpad } , NS { name = "element" , cmd = "element-desktop" , query = className =? "Element" , hook = floatingScratchpad } ] where floatingScratchpad = customFloating $ W.RationalRect 0.05 0.05 0.9 0.9
ceef4aa6b074fcaeb8720cc0be46172c6bb4184cc2d01281abdbf80f4fa47a87
softlab-ntua/bencherl
client_db.erl
%%%-------------------------------------------------------------------- %%% CLIENT_DB MODULE %%% @author : upon a design by ( C ) 2014 , RELEASE project %%% @doc %%% Client_DB module for the Distributed Erlang instant messenger ( IM ) application developed as a real benchmark for the Scalable Distributed Erlang extension of the Erlang / OTP language . %%% %%% This module implementes the functionality for the database that %%% stores the cients that are loggen in at a given time in a system similar to the system described in the Section 2 of the document " Instant Messenger Architectures Design Proposal " . %%% @end Created : 1 Jul 2014 by %%%-------------------------------------------------------------------- -module(client_db). -export([start/1, stop/1, start_local/1, stop_local/1, client_db/1]). %%%==================================================================== %%% API %%%==================================================================== %%--------------------------------------------------------------------- %% @doc %% Starts the clients database. %% @spec start(DB_Name ) %% @end %%--------------------------------------------------------------------- start(DB_Name) -> global:register_name(DB_Name, spawn_link(fun() -> client_db(DB_Name) end)). %%-------------------------------------------------------------------- %% @doc %% Stops the client database. %% %% @spec stop(DB_Name) %% @end %%-------------------------------------------------------------------- stop(DB_Name) -> destroy(DB_Name), global:unregister_name(DB_Name). %%--------------------------------------------------------------------- %% Starts the clients database, and registers it locally. %% @spec start_local(DB_Name ) %% @end %%--------------------------------------------------------------------- start_local(DB_Name) -> Pid = spawn_link(fun() -> client_db(DB_Name) end), register(DB_Name, Pid). %%-------------------------------------------------------------------- %% @doc %% Stops a client database that has been started locally. %% stop_local(DB_Name ) %% @end %%-------------------------------------------------------------------- stop_local(DB_Name) -> destroy(DB_Name), unregister(DB_Name). %%-------------------------------------------------------------------- %% @doc %% client_db is first stage of the database process. It creates an ets %% table after the atom specified as the parameter DB_Name. %% %% @spec client_db(DB_Name) %% @end %%-------------------------------------------------------------------- client_db(DB_Name) -> case ets:info(DB_Name) of undefined -> create(DB_Name), client_db_loop(DB_Name); _ -> client_db_loop(DB_Name) end. %%-------------------------------------------------------------------- %% @doc %% client_db_loop constitutes the database process, and offers an inter- %% face to interact with the ets table, allowing the input or retrieval %% of information concerning the clients logged in the system. %% @spec client_db_loop(DB_Name ) %% @end %%-------------------------------------------------------------------- client_db_loop(DB_Name) -> receive {From, add, Client_Name, Client_Pid, Client_Monitor_Pid} -> add_client(DB_Name, Client_Name, Client_Pid, Client_Monitor_Pid), case From of undefined -> ok; _ -> From ! {client_added, ok} end, client_db_loop(DB_Name); {From, remove, Client_Name} -> remove_client(DB_Name, Client_Name), case From of undefined -> ok; _ -> From ! {client_removed, ok} end, client_db_loop(DB_Name); {From, full_db} -> A = retrieve_db(DB_Name), case From of undefined -> ok; _ -> From ! A end, client_db_loop(DB_Name); {From, update_pid, Client_Name, Client_Pid} -> Answer = update_client_pid(DB_Name, Client_Name, Client_Pid), case From of undefined -> ok; _ -> From ! Answer end, client_db_loop(DB_Name); {From, update_monitor_pid, Client_Name, Client_Monitor_Pid} -> Answer = update_client_monitor_pid(DB_Name, Client_Name, Client_Monitor_Pid), case From of undefined -> ok; _ -> From ! Answer end, client_db_loop(DB_Name); {From, peak, Client_Name} -> C = peak_client(DB_Name, Client_Name), case From of undefined -> ok; _ -> From ! C end, client_db_loop(DB_Name); {From, peak_by_client_monitor, Client_Monitor_Pid} -> C = peak_client_monitor(DB_Name, Client_Monitor_Pid), case From of undefined -> ok; _ -> From ! C end, client_db_loop(DB_Name); {From, retrieve, Client_Name} -> C = retrieve_client(DB_Name, Client_Name), case From of undefined -> ok; _ -> From ! C end, client_db_loop(DB_Name); {From, client_pid, Client_Name} -> Pid = client_pid(DB_Name, Client_Name), case From of undefined -> ok; _ -> From ! Pid end, client_db_loop(DB_Name); {From, client_monitor_pid, Client_Name} -> Pid = client_monitor_pid(DB_Name, Client_Name), case From of undefined -> ok; _ -> From ! Pid end, client_db_loop(DB_Name); {From, recover, Target_DB_Name, Source_DB_Name} -> recover_db(Target_DB_Name, Source_DB_Name), case From of undefined -> ok; _ -> From ! {recovered, ok} end, client_db_loop(DB_Name); {From, stop} -> stop(DB_Name), case From of undefined -> ok; _ -> From ! {client_db_destroyed, ok} end end. %%--------------------------------------------------------------------- %% @doc Creates a new ets table -named Table_Name- to store the different %% clients active in the system. %% %% @spec create(Table_Name) -> Table_Name | {error, Error} %% @end %%--------------------------------------------------------------------- create(Table_Name) -> ets:new(Table_Name, [set, named_table]). %%--------------------------------------------------------------------- %% @doc Destroys ets table named . %% ) - > Table_Name | { error , Error } %% @end %%--------------------------------------------------------------------- destroy(Table_Name) -> ets:delete(Table_Name). %%--------------------------------------------------------------------- %% @doc %% Adds a client to the clients database. %% add_client(Table_Name , Client_name , Client_Pid , %% Client_Monitor_Pid) -> true | {error, Error} %% @end %%--------------------------------------------------------------------- add_client(Table_Name, Client_Name, Client_Pid, Client_Monitor_Pid) -> ets:insert(Table_Name, {Client_Name, Client_Pid, Client_Monitor_Pid}). %%--------------------------------------------------------------------- %% @doc %% Removes a client from the clients database. %% @spec remove_session(Table_Name , Client_name ) - > true | { error , Error } %% @end %%--------------------------------------------------------------------- remove_client(Table_Name, Client_Name) -> ets:delete(Table_Name, Client_Name). %%--------------------------------------------------------------------- %% @doc Updates a client 's Pid . %% , Client_Monitor_Pid ) - > %% true | {error, Error} %% @end %%--------------------------------------------------------------------- update_client_pid(Table_Name, Client_Name, New_Pid) -> ets:update_element(Table_Name, Client_Name, {2, New_Pid}). %%--------------------------------------------------------------------- %% @doc Updates a client 's monitor Pid . %% , Client_Monitor_Pid ) - > %% true | {error, Error} %% @end %%--------------------------------------------------------------------- update_client_monitor_pid(Table_Name, Client_Name, New_Monitor_Pid) -> ets:update_element(Table_Name, Client_Name, {3, New_Monitor_Pid}). %%--------------------------------------------------------------------- %% @doc %% Returns the contents of the whole database as a list of lists, where each of the nested lists is one client . ( Not in use , only for debug %% purposes %% retrieve_db(Table_Name ) - > [ [ Client1 ] , ... , [ ClientK ] ] | { error , Error } %% @end %%--------------------------------------------------------------------- retrieve_db(Table_Name) -> ets:match(Table_Name, {'$0', '$1', '$2'}). %%--------------------------------------------------------------------- %% @doc %% Returns a list containing the data of the client passed as argument. %% It does not delete the client from the db. %% peak_client(Table_Name , Client_Monitor_Pid ) - > [ Client_Name , Client_Monitor_Pid , Client ] | [ ] %% @end %%--------------------------------------------------------------------- peak_client(Table_Name, Client_Name) -> L = ets:select(Table_Name, [{{'$0', '$1', '$2'}, [{'==', '$0', Client_Name}], [['$0', '$1', '$2']]}]), case L == [] of true -> L; false -> lists:last(L) end. %%--------------------------------------------------------------------- %% @doc %% Returns a list containing the data of the client monitored by the %% monitor that has the pid passed as argument. %% It does not delete the client from the db. %% @spec peak_client_monitor(Table_Name , Client_Monitor_Pid ) - > [ Client_Name , Client_Monitor_Pid , Client ] | [ ] %% @end %%--------------------------------------------------------------------- peak_client_monitor(Table_Name, Client_Monitor_Pid) -> L = ets:select(Table_Name, [{{'$0', '$1', '$2'}, [{'==', '$2', Client_Monitor_Pid}], [['$0', '$1', '$2']]}]), case L == [] of true -> L; false -> lists:last(L) end. %%--------------------------------------------------------------------- %% @doc %% Deletes the client passed as argument from the database and returns %% a list containing the data of the said client. %% retrieve_client(Table_Name , Client_Monitor_Pid ) - > [ Client_Monitor_Pid , Client ] | { error , Error } %% @end %%--------------------------------------------------------------------- retrieve_client(Table_Name, Client_Name) -> C = peak_client(Table_Name, Client_Name), remove_client(Table_Name, Client_Name), C. %%-------------------------------------------------------------------- %% @doc Returns the Pid of the client passed as argument . %% , Session_Name ) - > Client_Pid | [ ] %% @end %%-------------------------------------------------------------------- client_pid(Table_Name, Client_Name) -> L = ets:select(Table_Name, [{{'$0', '$1', '$2'}, [{'==', '$0', Client_Name}], [['$1']]}]), case L == [] of true -> L; false -> lists:last(lists:last(L)) end. %%--------------------------------------------------------------------- %% @doc Returns the Pid of the client monitor for a given client passed as %% argument. %% @spec client_monitor_pid(Table_Name , Session_Name ) - > %% Client_Monitor_Pid | [] %% @end %%--------------------------------------------------------------------- client_monitor_pid(Table_Name, Client_Name)-> L = ets:select(Table_Name, [{{'$0', '$1', '$2'}, [{'==', '$0', Client_Name}], [['$2']]}]), case L == [] of true -> L; false -> lists:last(lists:last(L)) end. %%--------------------------------------------------------------------- %% @doc %% Replicates the clients table specified as the Source argument, in a new table with name . %% @spec retrieve_server(Table_Name , Client_Monitor_Pid ) - > %% true | {error, Error} %% @end %%--------------------------------------------------------------------- recover_db(Destination, Source) -> ets:safe_fixtable(Source, true), replicate(Source, Destination, ets:first(Source)), ets:safe_fixtable(Source, false). %%--------------------------------------------------------------------- %% @doc %% Auxiliary function to the recover_db(Table_Name, Source) function. This %% function traverses the source table specified in Source, and feeds the %% data in the destination table. %% @spec retrieve_server(Table_Name , Session_Pid ) - > true | { error , Error } %% @end %%--------------------------------------------------------------------- replicate(Source, Destination, Key) -> case Key of '$end_of_table' -> true; _ -> S = peak_client(Source, Key), global:whereis_name(Destination) ! {undefined ,add, lists:nth(1, S), lists:nth(2, S), lists:nth(3, S)}, replicate(Source, Destination, ets:next(Source, Key)) end.
null
https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/IM/src/client_db.erl
erlang
-------------------------------------------------------------------- CLIENT_DB MODULE @doc Client_DB module for the Distributed Erlang instant messenger This module implementes the functionality for the database that stores the cients that are loggen in at a given time in a system @end -------------------------------------------------------------------- ==================================================================== API ==================================================================== --------------------------------------------------------------------- @doc Starts the clients database. @end --------------------------------------------------------------------- -------------------------------------------------------------------- @doc Stops the client database. @spec stop(DB_Name) @end -------------------------------------------------------------------- --------------------------------------------------------------------- Starts the clients database, and registers it locally. @end --------------------------------------------------------------------- -------------------------------------------------------------------- @doc Stops a client database that has been started locally. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc client_db is first stage of the database process. It creates an ets table after the atom specified as the parameter DB_Name. @spec client_db(DB_Name) @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc client_db_loop constitutes the database process, and offers an inter- face to interact with the ets table, allowing the input or retrieval of information concerning the clients logged in the system. @end -------------------------------------------------------------------- --------------------------------------------------------------------- @doc clients active in the system. @spec create(Table_Name) -> Table_Name | {error, Error} @end --------------------------------------------------------------------- --------------------------------------------------------------------- @doc @end --------------------------------------------------------------------- --------------------------------------------------------------------- @doc Adds a client to the clients database. Client_Monitor_Pid) -> true | {error, Error} @end --------------------------------------------------------------------- --------------------------------------------------------------------- @doc Removes a client from the clients database. @end --------------------------------------------------------------------- --------------------------------------------------------------------- @doc true | {error, Error} @end --------------------------------------------------------------------- --------------------------------------------------------------------- @doc true | {error, Error} @end --------------------------------------------------------------------- --------------------------------------------------------------------- @doc Returns the contents of the whole database as a list of lists, where purposes @end --------------------------------------------------------------------- --------------------------------------------------------------------- @doc Returns a list containing the data of the client passed as argument. It does not delete the client from the db. @end --------------------------------------------------------------------- --------------------------------------------------------------------- @doc Returns a list containing the data of the client monitored by the monitor that has the pid passed as argument. It does not delete the client from the db. @end --------------------------------------------------------------------- --------------------------------------------------------------------- @doc Deletes the client passed as argument from the database and returns a list containing the data of the said client. @end --------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- --------------------------------------------------------------------- @doc argument. Client_Monitor_Pid | [] @end --------------------------------------------------------------------- --------------------------------------------------------------------- @doc Replicates the clients table specified as the Source argument, in a true | {error, Error} @end --------------------------------------------------------------------- --------------------------------------------------------------------- @doc Auxiliary function to the recover_db(Table_Name, Source) function. This function traverses the source table specified in Source, and feeds the data in the destination table. @end ---------------------------------------------------------------------
@author : upon a design by ( C ) 2014 , RELEASE project ( IM ) application developed as a real benchmark for the Scalable Distributed Erlang extension of the Erlang / OTP language . similar to the system described in the Section 2 of the document " Instant Messenger Architectures Design Proposal " . Created : 1 Jul 2014 by -module(client_db). -export([start/1, stop/1, start_local/1, stop_local/1, client_db/1]). @spec start(DB_Name ) start(DB_Name) -> global:register_name(DB_Name, spawn_link(fun() -> client_db(DB_Name) end)). stop(DB_Name) -> destroy(DB_Name), global:unregister_name(DB_Name). @spec start_local(DB_Name ) start_local(DB_Name) -> Pid = spawn_link(fun() -> client_db(DB_Name) end), register(DB_Name, Pid). stop_local(DB_Name ) stop_local(DB_Name) -> destroy(DB_Name), unregister(DB_Name). client_db(DB_Name) -> case ets:info(DB_Name) of undefined -> create(DB_Name), client_db_loop(DB_Name); _ -> client_db_loop(DB_Name) end. @spec client_db_loop(DB_Name ) client_db_loop(DB_Name) -> receive {From, add, Client_Name, Client_Pid, Client_Monitor_Pid} -> add_client(DB_Name, Client_Name, Client_Pid, Client_Monitor_Pid), case From of undefined -> ok; _ -> From ! {client_added, ok} end, client_db_loop(DB_Name); {From, remove, Client_Name} -> remove_client(DB_Name, Client_Name), case From of undefined -> ok; _ -> From ! {client_removed, ok} end, client_db_loop(DB_Name); {From, full_db} -> A = retrieve_db(DB_Name), case From of undefined -> ok; _ -> From ! A end, client_db_loop(DB_Name); {From, update_pid, Client_Name, Client_Pid} -> Answer = update_client_pid(DB_Name, Client_Name, Client_Pid), case From of undefined -> ok; _ -> From ! Answer end, client_db_loop(DB_Name); {From, update_monitor_pid, Client_Name, Client_Monitor_Pid} -> Answer = update_client_monitor_pid(DB_Name, Client_Name, Client_Monitor_Pid), case From of undefined -> ok; _ -> From ! Answer end, client_db_loop(DB_Name); {From, peak, Client_Name} -> C = peak_client(DB_Name, Client_Name), case From of undefined -> ok; _ -> From ! C end, client_db_loop(DB_Name); {From, peak_by_client_monitor, Client_Monitor_Pid} -> C = peak_client_monitor(DB_Name, Client_Monitor_Pid), case From of undefined -> ok; _ -> From ! C end, client_db_loop(DB_Name); {From, retrieve, Client_Name} -> C = retrieve_client(DB_Name, Client_Name), case From of undefined -> ok; _ -> From ! C end, client_db_loop(DB_Name); {From, client_pid, Client_Name} -> Pid = client_pid(DB_Name, Client_Name), case From of undefined -> ok; _ -> From ! Pid end, client_db_loop(DB_Name); {From, client_monitor_pid, Client_Name} -> Pid = client_monitor_pid(DB_Name, Client_Name), case From of undefined -> ok; _ -> From ! Pid end, client_db_loop(DB_Name); {From, recover, Target_DB_Name, Source_DB_Name} -> recover_db(Target_DB_Name, Source_DB_Name), case From of undefined -> ok; _ -> From ! {recovered, ok} end, client_db_loop(DB_Name); {From, stop} -> stop(DB_Name), case From of undefined -> ok; _ -> From ! {client_db_destroyed, ok} end end. Creates a new ets table -named Table_Name- to store the different create(Table_Name) -> ets:new(Table_Name, [set, named_table]). Destroys ets table named . ) - > Table_Name | { error , Error } destroy(Table_Name) -> ets:delete(Table_Name). add_client(Table_Name , Client_name , Client_Pid , add_client(Table_Name, Client_Name, Client_Pid, Client_Monitor_Pid) -> ets:insert(Table_Name, {Client_Name, Client_Pid, Client_Monitor_Pid}). @spec remove_session(Table_Name , Client_name ) - > true | { error , Error } remove_client(Table_Name, Client_Name) -> ets:delete(Table_Name, Client_Name). Updates a client 's Pid . , Client_Monitor_Pid ) - > update_client_pid(Table_Name, Client_Name, New_Pid) -> ets:update_element(Table_Name, Client_Name, {2, New_Pid}). Updates a client 's monitor Pid . , Client_Monitor_Pid ) - > update_client_monitor_pid(Table_Name, Client_Name, New_Monitor_Pid) -> ets:update_element(Table_Name, Client_Name, {3, New_Monitor_Pid}). each of the nested lists is one client . ( Not in use , only for debug retrieve_db(Table_Name ) - > [ [ Client1 ] , ... , [ ClientK ] ] | { error , Error } retrieve_db(Table_Name) -> ets:match(Table_Name, {'$0', '$1', '$2'}). peak_client(Table_Name , Client_Monitor_Pid ) - > [ Client_Name , Client_Monitor_Pid , Client ] | [ ] peak_client(Table_Name, Client_Name) -> L = ets:select(Table_Name, [{{'$0', '$1', '$2'}, [{'==', '$0', Client_Name}], [['$0', '$1', '$2']]}]), case L == [] of true -> L; false -> lists:last(L) end. @spec peak_client_monitor(Table_Name , Client_Monitor_Pid ) - > [ Client_Name , Client_Monitor_Pid , Client ] | [ ] peak_client_monitor(Table_Name, Client_Monitor_Pid) -> L = ets:select(Table_Name, [{{'$0', '$1', '$2'}, [{'==', '$2', Client_Monitor_Pid}], [['$0', '$1', '$2']]}]), case L == [] of true -> L; false -> lists:last(L) end. retrieve_client(Table_Name , Client_Monitor_Pid ) - > [ Client_Monitor_Pid , Client ] | { error , Error } retrieve_client(Table_Name, Client_Name) -> C = peak_client(Table_Name, Client_Name), remove_client(Table_Name, Client_Name), C. Returns the Pid of the client passed as argument . , Session_Name ) - > Client_Pid | [ ] client_pid(Table_Name, Client_Name) -> L = ets:select(Table_Name, [{{'$0', '$1', '$2'}, [{'==', '$0', Client_Name}], [['$1']]}]), case L == [] of true -> L; false -> lists:last(lists:last(L)) end. Returns the Pid of the client monitor for a given client passed as @spec client_monitor_pid(Table_Name , Session_Name ) - > client_monitor_pid(Table_Name, Client_Name)-> L = ets:select(Table_Name, [{{'$0', '$1', '$2'}, [{'==', '$0', Client_Name}], [['$2']]}]), case L == [] of true -> L; false -> lists:last(lists:last(L)) end. new table with name . @spec retrieve_server(Table_Name , Client_Monitor_Pid ) - > recover_db(Destination, Source) -> ets:safe_fixtable(Source, true), replicate(Source, Destination, ets:first(Source)), ets:safe_fixtable(Source, false). @spec retrieve_server(Table_Name , Session_Pid ) - > true | { error , Error } replicate(Source, Destination, Key) -> case Key of '$end_of_table' -> true; _ -> S = peak_client(Source, Key), global:whereis_name(Destination) ! {undefined ,add, lists:nth(1, S), lists:nth(2, S), lists:nth(3, S)}, replicate(Source, Destination, ets:next(Source, Key)) end.
3197df022549f1664601b75ba1bdb64372933c6f0a5a0f12307c5c018ceceeeb
mbenke/zpf2013
Simpl2.hs
# LANGUAGE QuasiQuotes # import ExprQuote2 import Expr2 simpl :: Exp -> Exp simpl [expr|0 + $x|] = x main = print $ simpl [expr|0+2|]
null
https://raw.githubusercontent.com/mbenke/zpf2013/85f32747e17f07a74e1c3cb064b1d6acaca3f2f0/Code/TH/QQ/Simpl2.hs
haskell
# LANGUAGE QuasiQuotes # import ExprQuote2 import Expr2 simpl :: Exp -> Exp simpl [expr|0 + $x|] = x main = print $ simpl [expr|0+2|]
f4244ece2b0c18fc2ed44a673279898ede5369df99d991e0de7cbbd179a172ee
gebi/jungerl
ibrowse.erl
%%%------------------------------------------------------------------- %%% File : ibrowse.erl Author : > %%% Description : Load balancer process for HTTP client connections. %%% Created : 11 Oct 2003 by > %%%------------------------------------------------------------------- @author at gmail dot com > 2005 - 2009 %% @version 1.5.2 @doc The ibrowse application implements an HTTP 1.1 client . This %% module implements the API of the HTTP client. There is one named process called ' ibrowse ' which assists in load balancing and maintaining configuration . There is one load balancing process per unique webserver . There is one process to handle one TCP connection to a webserver %% (implemented in the module ibrowse_http_client). Multiple connections to a %% webserver are setup based on the settings for each webserver. The %% ibrowse process also determines which connection to pipeline a certain request on . The functions to call are send_req/3 , send_req/4 , send_req/5 , send_req/6 . %% %% <p>Here are a few sample invocations.</p> %% %% <code> %% ibrowse:send_req("/", [], get). %% <br/><br/> %% %% ibrowse:send_req("/", [], get, [], %% [{proxy_user, "XXXXX"}, %% {proxy_password, "XXXXX"}, %% {proxy_host, "proxy"}, { proxy_port , 8080 } ] , 1000 ) . %% <br/><br/> %% ibrowse : send_req(" / download / otp_src_R10B-3.tar.gz " , [ ] , get , [ ] , %% [{proxy_user, "XXXXX"}, %% {proxy_password, "XXXXX"}, %% {proxy_host, "proxy"}, { proxy_port , 8080 } , { save_response_to_file , true } ] , 1000 ) . %% <br/><br/> %% %% ibrowse:send_req("", [], head). %% %% <br/><br/> ibrowse : send_req(" " , [ ] , options ) . %% %% <br/><br/> %% ibrowse:send_req("", [], trace). %% %% <br/><br/> %% ibrowse:send_req("", [], get, [], %% [{stream_to, self()}]). %% </code> %% %% <p>A driver exists which implements URL encoding in C, but the %% speed achieved using only erlang has been good enough, so the %% driver isn't actually used.</p> -module(ibrowse). -vsn('$Id: ibrowse.erl,v 1.11 2009/09/06 20:04:02 chandrusf Exp $ '). -behaviour(gen_server). %%-------------------------------------------------------------------- %% Include files %%-------------------------------------------------------------------- %%-------------------------------------------------------------------- %% External exports -export([start_link/0, start/0, stop/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %% API interface -export([ rescan_config/0, rescan_config/1, get_config_value/1, get_config_value/2, spawn_worker_process/2, spawn_link_worker_process/2, stop_worker_process/1, send_req/3, send_req/4, send_req/5, send_req/6, send_req_direct/4, send_req_direct/5, send_req_direct/6, send_req_direct/7, stream_next/1, set_max_sessions/3, set_max_pipeline_size/3, set_dest/3, trace_on/0, trace_off/0, trace_on/2, trace_off/2, all_trace_off/0, show_dest_status/0, show_dest_status/2 ]). -ifdef(debug). -compile(export_all). -endif. -import(ibrowse_lib, [ parse_url/1, get_value/3, do_trace/2 ]). -record(state, {trace = false}). -include("ibrowse.hrl"). -include_lib("stdlib/include/ms_transform.hrl"). -define(DEF_MAX_SESSIONS,10). -define(DEF_MAX_PIPELINE_SIZE,10). %%==================================================================== %% External functions %%==================================================================== %%-------------------------------------------------------------------- Function : start_link/0 %% Description: Starts the server %%-------------------------------------------------------------------- %% @doc Starts the ibrowse process linked to the calling process. Usually invoked by the supervisor ibrowse_sup ( ) - > { ok , pid ( ) } start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). %% @doc Starts the ibrowse process without linking. Useful when testing using the shell start() -> gen_server:start({local, ?MODULE}, ?MODULE, [], [{debug, []}]). %% @doc Stop the ibrowse process. Useful when testing using the shell. stop() -> catch gen_server:call(ibrowse, stop). %% @doc This is the basic function to send a HTTP request. %% The Status return value indicates the HTTP status code returned by the webserver send_req(Url::string ( ) , Headers::headerList ( ) , Method::method ( ) ) - > response ( ) %% headerList() = [{header(), value()}] %% header() = atom() | string() %% value() = term() method ( ) = get | post | head | options | put | delete | trace | mkcol | propfind | proppatch | lock | unlock | move | copy %% Status = string() %% ResponseHeaders = [respHeader()] respHeader ( ) = { headerName ( ) , headerValue ( ) } %% headerName() = string() %% headerValue() = string() response ( ) = { ok , Status , ResponseHeaders , ResponseBody } | { ibrowse_req_id , req_id ( ) } | { error , Reason } %% req_id() = term() %% ResponseBody = string() | {file, Filename} %% Reason = term() send_req(Url, Headers, Method) -> send_req(Url, Headers, Method, [], []). @doc Same as send_req/3 . If a list is specified for the body it has to be a flat list . The body can also be a fun/0 or a . < br/ > If fun/0 , the connection handling process will repeatdely call the fun until it returns an error or eof . < pre > Fun ( ) = { ok , Data } | eof</pre><br/ > If , the connection handling process will repeatedly call the fun with the supplied state until it returns an error or eof . < pre > Fun(State ) = { ok , Data } | { ok , Data , NewState } | eof</pre > @spec send_req(Url , Headers , Method::method ( ) , ( ) ) - > response ( ) %% body() = [] | string() | binary() | fun_arity_0() | {fun_arity_1(), initial_state()} %% initial_state() = term() send_req(Url, Headers, Method, Body) -> send_req(Url, Headers, Method, Body, []). @doc Same as send_req/4 . For a description of SSL Options , look in the < a href=" / doc / apps / ssl / index.html">ssl</a > manpage . If the HTTP Version to use is not specified , the default is 1.1 . %% <br/> < p > The < code > host_header</code > option is useful in the case where ibrowse is %% connecting to a component such as <a %% href="">stunnel</a> which then sets up a %% secure connection to a webserver. In this case, the URL supplied to ibrowse must have the stunnel host / port details , but that wo n't %% make sense to the destination webserver. This option can then be %% used to specify what should go in the <code>Host</code> header in %% the request.</p> %% <ul> %% <li>The <code>stream_to</code> option can be used to have the HTTP %% response streamed to a process as messages as data arrives on the %% socket. If the calling process wishes to control the rate at which %% data is received from the server, the option <code>{stream_to, %% {process(), once}}</code> can be specified. The calling process %% will have to invoke <code>ibrowse:stream_next(Request_id)</code> to %% receive the next packet.</li> %% %% <li>When both the options <code>save_response_to_file</code> and <code>stream_to</code> %% are specified, the former takes precedence.</li> %% %% <li>For the <code>save_response_to_file</code> option, the response body is saved to file only if the status code is in the 200 - 299 range . If not , the response body is returned %% as a string.</li> < li > Whenever an error occurs in the processing of a request , ibrowse will return as much %% information as it has, such as HTTP Status Code and HTTP Headers. When this happens, the response is of the form < code>{error , { Reason , { stat_code , } , HTTP_headers}}</code></li > %% %% <li>The <code>inactivity_timeout</code> option is useful when %% dealing with large response bodies and/or slow links. In these %% cases, it might be hard to estimate how long a request will take to %% complete. In such cases, the client might want to timeout if no data has been received on the link for a certain time interval.</li > %% %% <li> %% The <code>connect_timeout</code> option is to specify how long the %% client process should wait for connection establishment. This is %% useful in scenarios where connections to servers are usually setup %% very fast, but responses might take much longer compared to %% connection setup. In such cases, it is better for the calling %% process to timeout faster if there is a problem (DNS lookup %% delays/failures, network routing issues, etc). The total timeout %% value specified for the request will enforced. To illustrate using %% an example: %% <code> ibrowse : send_req(" / cgi - bin / request " , [ ] , get , [ ] , [ { connect_timeout , 100 } ] , 1000 ) . %% </code> %% In the above invocation, if the connection isn't established within %% 100 milliseconds, the request will fail with %% <code>{error, conn_failed}</code>.<br/> %% If connection setup succeeds, the total time allowed for the request to complete will be 1000 milliseconds minus the time taken %% for connection setup. %% </li> %% </ul> %% %% <li> The <code>socket_options</code> option can be used to set %% specific options on the socket. The <code>{active, true | false | once}</code> and < code>{packet_type , Packet_type}</code > will be filtered out by ibrowse . < /li > %% send_req(Url::string ( ) , Headers::headerList ( ) , Method::method ( ) , ( ) , Options::optionList ( ) ) - > response ( ) %% optionList() = [option()] option ( ) = , integer ( ) } | %% {response_format,response_format()}| %% {stream_chunk_size, integer()} | %% {max_pipeline_size, integer()} | %% {trace, boolean()} | %% {is_ssl, boolean()} | %% {ssl_options, [SSLOpt]} | %% {pool_name, atom()} | %% {proxy_host, string()} | %% {proxy_port, integer()} | %% {proxy_user, string()} | , string ( ) } | %% {use_absolute_uri, boolean()} | { basic_auth , { username ( ) , password ( ) } } | %% {cookie, string()} | { content_length , integer ( ) } | %% {content_type, string()} | %% {save_response_to_file, srtf()} | ( ) } | { http_vsn , { MajorVsn , MinorVsn } } | %% {host_header, string()} | %% {inactivity_timeout, integer()} | %% {connect_timeout, integer()} | %% {socket_options, Sock_opts} | { transfer_encoding , { chunked , ChunkSize } } %% %% stream_to() = process() | {process(), once} %% process() = pid() | atom() %% username() = string() %% password() = string() %% SSLOpt = term() %% Sock_opts = [Sock_opt] Sock_opt = term ( ) ChunkSize = integer ( ) %% srtf() = boolean() | filename() %% filename() = string() %% response_format() = list | binary send_req(Url, Headers, Method, Body, Options) -> send_req(Url, Headers, Method, Body, Options, 30000). %% @doc Same as send_req/5. %% All timeout values are in milliseconds. @spec send_req(Url , Headers::headerList ( ) , Method::method ( ) , ( ) , Options::optionList ( ) , Timeout ) - > response ( ) Timeout = integer ( ) | infinity send_req(Url, Headers, Method, Body, Options, Timeout) -> case catch parse_url(Url) of #url{host = Host, port = Port, protocol = Protocol} = Parsed_url -> Lb_pid = case ets:lookup(ibrowse_lb, {Host, Port}) of [] -> get_lb_pid(Parsed_url); [#lb_pid{pid = Lb_pid_1}] -> Lb_pid_1 end, Max_sessions = get_max_sessions(Host, Port, Options), Max_pipeline_size = get_max_pipeline_size(Host, Port, Options), Options_1 = merge_options(Host, Port, Options), {SSLOptions, IsSSL} = case (Protocol == https) orelse get_value(is_ssl, Options_1, false) of false -> {[], false}; true -> {get_value(ssl_options, Options_1, []), true} end, case ibrowse_lb:spawn_connection(Lb_pid, Parsed_url, Max_sessions, Max_pipeline_size, {SSLOptions, IsSSL}) of {ok, Conn_Pid} -> do_send_req(Conn_Pid, Parsed_url, Headers, Method, Body, Options_1, Timeout); Err -> Err end; Err -> {error, {url_parsing_failed, Err}} end. merge_options(Host, Port, Options) -> Config_options = get_config_value({options, Host, Port}, []), lists:foldl( fun({Key, Val}, Acc) -> case lists:keysearch(Key, 1, Options) of false -> [{Key, Val} | Acc]; _ -> Acc end end, Options, Config_options). get_lb_pid(Url) -> gen_server:call(?MODULE, {get_lb_pid, Url}). get_max_sessions(Host, Port, Options) -> get_value(max_sessions, Options, get_config_value({max_sessions, Host, Port}, ?DEF_MAX_SESSIONS)). get_max_pipeline_size(Host, Port, Options) -> get_value(max_pipeline_size, Options, get_config_value({max_pipeline_size, Host, Port}, ?DEF_MAX_PIPELINE_SIZE)). %% @doc Deprecated. Use set_max_sessions/3 and set_max_pipeline_size/3 %% for achieving the same effect. set_dest(Host, Port, [{max_sessions, Max} | T]) -> set_max_sessions(Host, Port, Max), set_dest(Host, Port, T); set_dest(Host, Port, [{max_pipeline_size, Max} | T]) -> set_max_pipeline_size(Host, Port, Max), set_dest(Host, Port, T); set_dest(Host, Port, [{trace, Bool} | T]) when Bool == true; Bool == false -> ibrowse ! {trace, true, Host, Port}, set_dest(Host, Port, T); set_dest(_Host, _Port, [H | _]) -> exit({invalid_option, H}); set_dest(_, _, []) -> ok. %% @doc Set the maximum number of connections allowed to a specific Host:Port. ( ) , Port::integer ( ) , Max::integer ( ) ) - > ok set_max_sessions(Host, Port, Max) when is_integer(Max), Max > 0 -> gen_server:call(?MODULE, {set_config_value, {max_sessions, Host, Port}, Max}). %% @doc Set the maximum pipeline size for each connection to a specific Host:Port. ( ) , Port::integer ( ) , Max::integer ( ) ) - > ok set_max_pipeline_size(Host, Port, Max) when is_integer(Max), Max > 0 -> gen_server:call(?MODULE, {set_config_value, {max_pipeline_size, Host, Port}, Max}). do_send_req(Conn_Pid, Parsed_url, Headers, Method, Body, Options, Timeout) -> case catch ibrowse_http_client:send_req(Conn_Pid, Parsed_url, Headers, Method, ensure_bin(Body), Options, Timeout) of {'EXIT', {timeout, _}} -> {error, req_timedout}; {'EXIT', Reason} -> {error, {'EXIT', Reason}}; {ok, St_code, Headers, Body} = Ret when is_binary(Body) -> case get_value(response_format, Options, list) of list -> {ok, St_code, Headers, binary_to_list(Body)}; binary -> Ret end; Ret -> Ret end. ensure_bin(L) when is_list(L) -> list_to_binary(L); ensure_bin(B) when is_binary(B) -> B; ensure_bin(Fun) when is_function(Fun) -> Fun; ensure_bin({Fun}) when is_function(Fun) -> Fun; ensure_bin({Fun, _} = Body) when is_function(Fun) -> Body. %% @doc Creates a HTTP client process to the specified Host:Port which %% is not part of the load balancing pool. This is useful in cases %% where some requests to a webserver might take a long time whereas %% some might take a very short time. To avoid getting these quick %% requests stuck in the pipeline behind time consuming requests, use %% this function to get a handle to a connection process. <br/> %% <b>Note:</b> Calling this function only creates a worker process. No connection is setup . The connection attempt is made only when the first request is sent via any of the send_req_direct/4,5,6,7 functions.<br/ > %% <b>Note:</b> It is the responsibility of the calling process to control %% pipeline size on such connections. %% ( ) , Port::integer ( ) ) - > { ok , pid ( ) } spawn_worker_process(Host, Port) -> ibrowse_http_client:start({Host, Port}). %% @doc Same as spawn_worker_process/2 except the the calling process %% is linked to the worker process which is spawned. spawn_link_worker_process(Host, Port) -> ibrowse_http_client:start_link({Host, Port}). %% @doc Terminate a worker process spawned using spawn_worker_process/2 or spawn_link_worker_process/2 . Requests in %% progress will get the error response <pre>{error, closing_on_request}</pre> stop_worker_process(Conn_pid::pid ( ) ) - > ok stop_worker_process(Conn_pid) -> ibrowse_http_client:stop(Conn_pid). @doc Same as send_req/3 except that the first argument is the PID returned by spawn_worker_process/2 or spawn_link_worker_process/2 send_req_direct(Conn_pid, Url, Headers, Method) -> send_req_direct(Conn_pid, Url, Headers, Method, [], []). @doc Same as send_req/4 except that the first argument is the PID returned by spawn_worker_process/2 or spawn_link_worker_process/2 send_req_direct(Conn_pid, Url, Headers, Method, Body) -> send_req_direct(Conn_pid, Url, Headers, Method, Body, []). @doc Same as send_req/5 except that the first argument is the PID returned by spawn_worker_process/2 or spawn_link_worker_process/2 send_req_direct(Conn_pid, Url, Headers, Method, Body, Options) -> send_req_direct(Conn_pid, Url, Headers, Method, Body, Options, 30000). @doc Same as send_req/6 except that the first argument is the PID returned by spawn_worker_process/2 or spawn_link_worker_process/2 send_req_direct(Conn_pid, Url, Headers, Method, Body, Options, Timeout) -> case catch parse_url(Url) of #url{host = Host, port = Port} = Parsed_url -> Options_1 = merge_options(Host, Port, Options), case do_send_req(Conn_pid, Parsed_url, Headers, Method, Body, Options_1, Timeout) of {error, {'EXIT', {noproc, _}}} -> {error, worker_is_dead}; Ret -> Ret end; Err -> {error, {url_parsing_failed, Err}} end. %% @doc Tell ibrowse to stream the next chunk of data to the %% caller. Should be used in conjunction with the %% <code>stream_to</code> option stream_next(Req_id : : req_id ( ) ) - > ok | { error , unknown_req_id } stream_next(Req_id) -> case ets:lookup(ibrowse_stream, {req_id_pid, Req_id}) of [] -> {error, unknown_req_id}; [{_, Pid}] -> catch Pid ! {stream_next, Req_id}, ok end. %% @doc Turn tracing on for the ibrowse process trace_on() -> ibrowse ! {trace, true}. %% @doc Turn tracing off for the ibrowse process trace_off() -> ibrowse ! {trace, false}. %% @doc Turn tracing on for all connections to the specified HTTP %% server. Host is whatever is specified as the domain name in the URL ) - > ok %% Host = string() %% Port = integer() trace_on(Host, Port) -> ibrowse ! {trace, true, Host, Port}, ok. %% @doc Turn tracing OFF for all connections to the specified HTTP %% server. Port ) - > ok trace_off(Host, Port) -> ibrowse ! {trace, false, Host, Port}, ok. %% @doc Turn Off ALL tracing ( ) - > ok all_trace_off() -> ibrowse ! all_trace_off, ok. show_dest_status() -> Dests = lists:filter(fun({lb_pid, {Host, Port}, _}) when is_list(Host), is_integer(Port) -> true; (_) -> false end, ets:tab2list(ibrowse_lb)), All_ets = ets:all(), io:format("~-40.40s | ~-5.5s | ~-10.10s | ~s~n", ["Server:port", "ETS", "Num conns", "LB Pid"]), io:format("~80.80.=s~n", [""]), lists:foreach(fun({lb_pid, {Host, Port}, Lb_pid}) -> case lists:dropwhile( fun(Tid) -> ets:info(Tid, owner) /= Lb_pid end, All_ets) of [] -> io:format("~40.40s | ~-5.5s | ~-5.5s | ~s~n", [Host ++ ":" ++ integer_to_list(Port), "", "", io_lib:format("~p", [Lb_pid])] ); [Tid | _] -> catch ( begin Size = ets:info(Tid, size), io:format("~40.40s | ~-5.5s | ~-5.5s | ~s~n", [Host ++ ":" ++ integer_to_list(Port), integer_to_list(Tid), integer_to_list(Size), io_lib:format("~p", [Lb_pid])] ) end ) end end, Dests). %% @doc Shows some internal information about load balancing to a specified Host : Port . Info about workers spawned using spawn_worker_process/2 or spawn_link_worker_process/2 is not %% included. show_dest_status(Host, Port) -> case ets:lookup(ibrowse_lb, {Host, Port}) of [] -> no_active_processes; [#lb_pid{pid = Lb_pid}] -> io:format("Load Balancer Pid : ~p~n", [Lb_pid]), io:format("LB process msg q size : ~p~n", [(catch process_info(Lb_pid, message_queue_len))]), case lists:dropwhile( fun(Tid) -> ets:info(Tid, owner) /= Lb_pid end, ets:all()) of [] -> io:format("Couldn't locate ETS table for ~p~n", [Lb_pid]); [Tid | _] -> First = ets:first(Tid), Last = ets:last(Tid), Size = ets:info(Tid, size), io:format("LB ETS table id : ~p~n", [Tid]), io:format("Num Connections : ~p~n", [Size]), case Size of 0 -> ok; _ -> {First_p_sz, _} = First, {Last_p_sz, _} = Last, io:format("Smallest pipeline : ~1000.p~n", [First_p_sz]), io:format("Largest pipeline : ~1000.p~n", [Last_p_sz]) end end end. %% @doc Clear current configuration for ibrowse and load from the file ibrowse.conf in the IBROWSE_EBIN/ .. /priv directory . Current %% configuration is cleared only if the ibrowse.conf file is readable %% using file:consult/1 rescan_config() -> gen_server:call(?MODULE, rescan_config). %% Clear current configuration for ibrowse and load from the specified %% file. Current configuration is cleared only if the specified %% file is readable using file:consult/1 rescan_config(File) when is_list(File) -> gen_server:call(?MODULE, {rescan_config, File}). %%==================================================================== %% Server functions %%==================================================================== %%-------------------------------------------------------------------- %% Function: init/1 %% Description: Initiates the server %% Returns: {ok, State} | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %%-------------------------------------------------------------------- init(_) -> process_flag(trap_exit, true), State = #state{}, put(my_trace_flag, State#state.trace), put(ibrowse_trace_token, "ibrowse"), ets:new(ibrowse_lb, [named_table, public, {keypos, 2}]), ets:new(ibrowse_conf, [named_table, protected, {keypos, 2}]), ets:new(ibrowse_stream, [named_table, public]), import_config(), {ok, #state{}}. import_config() -> case code:priv_dir(ibrowse) of {error, _} = Err -> Err; PrivDir -> Filename = filename:join(PrivDir, "ibrowse.conf"), import_config(Filename) end. import_config(Filename) -> case file:consult(Filename) of {ok, Terms} -> ets:delete_all_objects(ibrowse_conf), Fun = fun({dest, Host, Port, MaxSess, MaxPipe, Options}) when is_list(Host), is_integer(Port), is_integer(MaxSess), MaxSess > 0, is_integer(MaxPipe), MaxPipe > 0, is_list(Options) -> I = [{{max_sessions, Host, Port}, MaxSess}, {{max_pipeline_size, Host, Port}, MaxPipe}, {{options, Host, Port}, Options}], lists:foreach( fun({X, Y}) -> ets:insert(ibrowse_conf, #ibrowse_conf{key = X, value = Y}) end, I); ({K, V}) -> ets:insert(ibrowse_conf, #ibrowse_conf{key = K, value = V}); (X) -> io:format("Skipping unrecognised term: ~p~n", [X]) end, lists:foreach(Fun, Terms); Err -> Err end. %% @doc Internal export get_config_value(Key) -> [#ibrowse_conf{value = V}] = ets:lookup(ibrowse_conf, Key), V. %% @doc Internal export get_config_value(Key, DefVal) -> case ets:lookup(ibrowse_conf, Key) of [] -> DefVal; [#ibrowse_conf{value = V}] -> V end. set_config_value(Key, Val) -> ets:insert(ibrowse_conf, #ibrowse_conf{key = Key, value = Val}). %%-------------------------------------------------------------------- Function : handle_call/3 %% Description: Handling call messages %% Returns: {reply, Reply, State} | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | (terminate/2 is called) %% {stop, Reason, State} (terminate/2 is called) %%-------------------------------------------------------------------- handle_call({get_lb_pid, #url{host = Host, port = Port} = Url}, _From, State) -> Pid = do_get_connection(Url, ets:lookup(ibrowse_lb, {Host, Port})), {reply, Pid, State}; handle_call(stop, _From, State) -> do_trace("IBROWSE shutting down~n", []), {stop, normal, ok, State}; handle_call({set_config_value, Key, Val}, _From, State) -> set_config_value(Key, Val), {reply, ok, State}; handle_call(rescan_config, _From, State) -> Ret = (catch import_config()), {reply, Ret, State}; handle_call({rescan_config, File}, _From, State) -> Ret = (catch import_config(File)), {reply, Ret, State}; handle_call(Request, _From, State) -> Reply = {unknown_request, Request}, {reply, Reply, State}. %%-------------------------------------------------------------------- %% Function: handle_cast/2 %% Description: Handling cast messages Returns : { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} (terminate/2 is called) %%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% Function: handle_info/2 %% Description: Handling all non call/cast messages Returns : { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} (terminate/2 is called) %%-------------------------------------------------------------------- handle_info(all_trace_off, State) -> Mspec = [{{ibrowse_conf,{trace,'$1','$2'},true},[],[{{'$1','$2'}}]}], Trace_on_dests = ets:select(ibrowse_conf, Mspec), Fun = fun(#lb_pid{host_port = {H, P}, pid = Pid}, _) -> case lists:member({H, P}, Trace_on_dests) of false -> ok; true -> catch Pid ! {trace, false} end; (_, Acc) -> Acc end, ets:foldl(Fun, undefined, ibrowse_lb), ets:select_delete(ibrowse_conf, [{{ibrowse_conf,{trace,'$1','$2'},true},[],['true']}]), {noreply, State}; handle_info({trace, Bool}, State) -> put(my_trace_flag, Bool), {noreply, State}; handle_info({trace, Bool, Host, Port}, State) -> Fun = fun(#lb_pid{host_port = {H, P}, pid = Pid}, _) when H == Host, P == Port -> catch Pid ! {trace, Bool}; (_, Acc) -> Acc end, ets:foldl(Fun, undefined, ibrowse_lb), ets:insert(ibrowse_conf, #ibrowse_conf{key = {trace, Host, Port}, value = Bool}), {noreply, State}; handle_info(_Info, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% Function: terminate/2 %% Description: Shutdown the server %% Returns: any (ignored by gen_server) %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- %% Func: code_change/3 %% Purpose: Convert process state when code is changed %% Returns: {ok, NewState} %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- do_get_connection(#url{host = Host, port = Port}, []) -> {ok, Pid} = ibrowse_lb:start_link([Host, Port]), ets:insert(ibrowse_lb, #lb_pid{host_port = {Host, Port}, pid = Pid}), Pid; do_get_connection(_Url, [#lb_pid{pid = Pid}]) -> Pid.
null
https://raw.githubusercontent.com/gebi/jungerl/8f5c102295dbe903f47d79fd64714b7de17026ec/lib/ibrowse/src/ibrowse.erl
erlang
------------------------------------------------------------------- File : ibrowse.erl Description : Load balancer process for HTTP client connections. ------------------------------------------------------------------- @version 1.5.2 module implements the API of the HTTP client. There is one named (implemented in the module ibrowse_http_client). Multiple connections to a webserver are setup based on the settings for each webserver. The ibrowse process also determines which connection to pipeline a <p>Here are a few sample invocations.</p> <code> ibrowse:send_req("/", [], get). <br/><br/> ibrowse:send_req("/", [], get, [], [{proxy_user, "XXXXX"}, {proxy_password, "XXXXX"}, {proxy_host, "proxy"}, <br/><br/> [{proxy_user, "XXXXX"}, {proxy_password, "XXXXX"}, {proxy_host, "proxy"}, <br/><br/> ibrowse:send_req("", [], head). <br/><br/> <br/><br/> ibrowse:send_req("", [], trace). <br/><br/> ibrowse:send_req("", [], get, [], [{stream_to, self()}]). </code> <p>A driver exists which implements URL encoding in C, but the speed achieved using only erlang has been good enough, so the driver isn't actually used.</p> -------------------------------------------------------------------- Include files -------------------------------------------------------------------- -------------------------------------------------------------------- External exports gen_server callbacks API interface ==================================================================== External functions ==================================================================== -------------------------------------------------------------------- Description: Starts the server -------------------------------------------------------------------- @doc Starts the ibrowse process linked to the calling process. Usually invoked by the supervisor ibrowse_sup @doc Starts the ibrowse process without linking. Useful when testing using the shell @doc Stop the ibrowse process. Useful when testing using the shell. @doc This is the basic function to send a HTTP request. The Status return value indicates the HTTP status code returned by the webserver headerList() = [{header(), value()}] header() = atom() | string() value() = term() Status = string() ResponseHeaders = [respHeader()] headerName() = string() headerValue() = string() req_id() = term() ResponseBody = string() | {file, Filename} Reason = term() body() = [] | string() | binary() | fun_arity_0() | {fun_arity_1(), initial_state()} initial_state() = term() <br/> connecting to a component such as <a href="">stunnel</a> which then sets up a secure connection to a webserver. In this case, the URL supplied to make sense to the destination webserver. This option can then be used to specify what should go in the <code>Host</code> header in the request.</p> <ul> <li>The <code>stream_to</code> option can be used to have the HTTP response streamed to a process as messages as data arrives on the socket. If the calling process wishes to control the rate at which data is received from the server, the option <code>{stream_to, {process(), once}}</code> can be specified. The calling process will have to invoke <code>ibrowse:stream_next(Request_id)</code> to receive the next packet.</li> <li>When both the options <code>save_response_to_file</code> and <code>stream_to</code> are specified, the former takes precedence.</li> <li>For the <code>save_response_to_file</code> option, the response body is saved to as a string.</li> information as it has, such as HTTP Status Code and HTTP Headers. When this happens, the response <li>The <code>inactivity_timeout</code> option is useful when dealing with large response bodies and/or slow links. In these cases, it might be hard to estimate how long a request will take to complete. In such cases, the client might want to timeout if no <li> The <code>connect_timeout</code> option is to specify how long the client process should wait for connection establishment. This is useful in scenarios where connections to servers are usually setup very fast, but responses might take much longer compared to connection setup. In such cases, it is better for the calling process to timeout faster if there is a problem (DNS lookup delays/failures, network routing issues, etc). The total timeout value specified for the request will enforced. To illustrate using an example: <code> </code> In the above invocation, if the connection isn't established within 100 milliseconds, the request will fail with <code>{error, conn_failed}</code>.<br/> If connection setup succeeds, the total time allowed for the for connection setup. </li> </ul> <li> The <code>socket_options</code> option can be used to set specific options on the socket. The <code>{active, true | false | once}</code> optionList() = [option()] {response_format,response_format()}| {stream_chunk_size, integer()} | {max_pipeline_size, integer()} | {trace, boolean()} | {is_ssl, boolean()} | {ssl_options, [SSLOpt]} | {pool_name, atom()} | {proxy_host, string()} | {proxy_port, integer()} | {proxy_user, string()} | {use_absolute_uri, boolean()} | {cookie, string()} | {content_type, string()} | {save_response_to_file, srtf()} | {host_header, string()} | {inactivity_timeout, integer()} | {connect_timeout, integer()} | {socket_options, Sock_opts} | stream_to() = process() | {process(), once} process() = pid() | atom() username() = string() password() = string() SSLOpt = term() Sock_opts = [Sock_opt] srtf() = boolean() | filename() filename() = string() response_format() = list | binary @doc Same as send_req/5. All timeout values are in milliseconds. @doc Deprecated. Use set_max_sessions/3 and set_max_pipeline_size/3 for achieving the same effect. @doc Set the maximum number of connections allowed to a specific Host:Port. @doc Set the maximum pipeline size for each connection to a specific Host:Port. @doc Creates a HTTP client process to the specified Host:Port which is not part of the load balancing pool. This is useful in cases where some requests to a webserver might take a long time whereas some might take a very short time. To avoid getting these quick requests stuck in the pipeline behind time consuming requests, use this function to get a handle to a connection process. <br/> <b>Note:</b> Calling this function only creates a worker process. No connection <b>Note:</b> It is the responsibility of the calling process to control pipeline size on such connections. @doc Same as spawn_worker_process/2 except the the calling process is linked to the worker process which is spawned. @doc Terminate a worker process spawned using progress will get the error response <pre>{error, closing_on_request}</pre> @doc Tell ibrowse to stream the next chunk of data to the caller. Should be used in conjunction with the <code>stream_to</code> option @doc Turn tracing on for the ibrowse process @doc Turn tracing off for the ibrowse process @doc Turn tracing on for all connections to the specified HTTP server. Host is whatever is specified as the domain name in the URL Host = string() Port = integer() @doc Turn tracing OFF for all connections to the specified HTTP server. @doc Turn Off ALL tracing @doc Shows some internal information about load balancing to a included. @doc Clear current configuration for ibrowse and load from the file configuration is cleared only if the ibrowse.conf file is readable using file:consult/1 Clear current configuration for ibrowse and load from the specified file. Current configuration is cleared only if the specified file is readable using file:consult/1 ==================================================================== Server functions ==================================================================== -------------------------------------------------------------------- Function: init/1 Description: Initiates the server Returns: {ok, State} | ignore | {stop, Reason} -------------------------------------------------------------------- @doc Internal export @doc Internal export -------------------------------------------------------------------- Description: Handling call messages Returns: {reply, Reply, State} | {stop, Reason, Reply, State} | (terminate/2 is called) {stop, Reason, State} (terminate/2 is called) -------------------------------------------------------------------- -------------------------------------------------------------------- Function: handle_cast/2 Description: Handling cast messages {stop, Reason, State} (terminate/2 is called) -------------------------------------------------------------------- -------------------------------------------------------------------- Function: handle_info/2 Description: Handling all non call/cast messages {stop, Reason, State} (terminate/2 is called) -------------------------------------------------------------------- -------------------------------------------------------------------- Function: terminate/2 Description: Shutdown the server Returns: any (ignored by gen_server) -------------------------------------------------------------------- -------------------------------------------------------------------- Func: code_change/3 Purpose: Convert process state when code is changed Returns: {ok, NewState} -------------------------------------------------------------------- -------------------------------------------------------------------- --------------------------------------------------------------------
Author : > Created : 11 Oct 2003 by > @author at gmail dot com > 2005 - 2009 @doc The ibrowse application implements an HTTP 1.1 client . This process called ' ibrowse ' which assists in load balancing and maintaining configuration . There is one load balancing process per unique webserver . There is one process to handle one TCP connection to a webserver certain request on . The functions to call are send_req/3 , send_req/4 , send_req/5 , send_req/6 . { proxy_port , 8080 } ] , 1000 ) . ibrowse : send_req(" / download / otp_src_R10B-3.tar.gz " , [ ] , get , [ ] , { proxy_port , 8080 } , { save_response_to_file , true } ] , 1000 ) . ibrowse : send_req(" " , [ ] , options ) . -module(ibrowse). -vsn('$Id: ibrowse.erl,v 1.11 2009/09/06 20:04:02 chandrusf Exp $ '). -behaviour(gen_server). -export([start_link/0, start/0, stop/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([ rescan_config/0, rescan_config/1, get_config_value/1, get_config_value/2, spawn_worker_process/2, spawn_link_worker_process/2, stop_worker_process/1, send_req/3, send_req/4, send_req/5, send_req/6, send_req_direct/4, send_req_direct/5, send_req_direct/6, send_req_direct/7, stream_next/1, set_max_sessions/3, set_max_pipeline_size/3, set_dest/3, trace_on/0, trace_off/0, trace_on/2, trace_off/2, all_trace_off/0, show_dest_status/0, show_dest_status/2 ]). -ifdef(debug). -compile(export_all). -endif. -import(ibrowse_lib, [ parse_url/1, get_value/3, do_trace/2 ]). -record(state, {trace = false}). -include("ibrowse.hrl"). -include_lib("stdlib/include/ms_transform.hrl"). -define(DEF_MAX_SESSIONS,10). -define(DEF_MAX_PIPELINE_SIZE,10). Function : start_link/0 ( ) - > { ok , pid ( ) } start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). start() -> gen_server:start({local, ?MODULE}, ?MODULE, [], [{debug, []}]). stop() -> catch gen_server:call(ibrowse, stop). send_req(Url::string ( ) , Headers::headerList ( ) , Method::method ( ) ) - > response ( ) method ( ) = get | post | head | options | put | delete | trace | mkcol | propfind | proppatch | lock | unlock | move | copy respHeader ( ) = { headerName ( ) , headerValue ( ) } response ( ) = { ok , Status , ResponseHeaders , ResponseBody } | { ibrowse_req_id , req_id ( ) } | { error , Reason } send_req(Url, Headers, Method) -> send_req(Url, Headers, Method, [], []). @doc Same as send_req/3 . If a list is specified for the body it has to be a flat list . The body can also be a fun/0 or a . < br/ > If fun/0 , the connection handling process will repeatdely call the fun until it returns an error or eof . < pre > Fun ( ) = { ok , Data } | eof</pre><br/ > If , the connection handling process will repeatedly call the fun with the supplied state until it returns an error or eof . < pre > Fun(State ) = { ok , Data } | { ok , Data , NewState } | eof</pre > @spec send_req(Url , Headers , Method::method ( ) , ( ) ) - > response ( ) send_req(Url, Headers, Method, Body) -> send_req(Url, Headers, Method, Body, []). @doc Same as send_req/4 . For a description of SSL Options , look in the < a href=" / doc / apps / ssl / index.html">ssl</a > manpage . If the HTTP Version to use is not specified , the default is 1.1 . < p > The < code > host_header</code > option is useful in the case where ibrowse is ibrowse must have the stunnel host / port details , but that wo n't file only if the status code is in the 200 - 299 range . If not , the response body is returned < li > Whenever an error occurs in the processing of a request , ibrowse will return as much is of the form < code>{error , { Reason , { stat_code , } , HTTP_headers}}</code></li > data has been received on the link for a certain time interval.</li > ibrowse : send_req(" / cgi - bin / request " , [ ] , get , [ ] , [ { connect_timeout , 100 } ] , 1000 ) . request to complete will be 1000 milliseconds minus the time taken and < code>{packet_type , Packet_type}</code > will be filtered out by ibrowse . < /li > send_req(Url::string ( ) , Headers::headerList ( ) , Method::method ( ) , ( ) , Options::optionList ( ) ) - > response ( ) option ( ) = , integer ( ) } | , string ( ) } | { basic_auth , { username ( ) , password ( ) } } | { content_length , integer ( ) } | ( ) } | { http_vsn , { MajorVsn , MinorVsn } } | { transfer_encoding , { chunked , ChunkSize } } Sock_opt = term ( ) ChunkSize = integer ( ) send_req(Url, Headers, Method, Body, Options) -> send_req(Url, Headers, Method, Body, Options, 30000). @spec send_req(Url , Headers::headerList ( ) , Method::method ( ) , ( ) , Options::optionList ( ) , Timeout ) - > response ( ) Timeout = integer ( ) | infinity send_req(Url, Headers, Method, Body, Options, Timeout) -> case catch parse_url(Url) of #url{host = Host, port = Port, protocol = Protocol} = Parsed_url -> Lb_pid = case ets:lookup(ibrowse_lb, {Host, Port}) of [] -> get_lb_pid(Parsed_url); [#lb_pid{pid = Lb_pid_1}] -> Lb_pid_1 end, Max_sessions = get_max_sessions(Host, Port, Options), Max_pipeline_size = get_max_pipeline_size(Host, Port, Options), Options_1 = merge_options(Host, Port, Options), {SSLOptions, IsSSL} = case (Protocol == https) orelse get_value(is_ssl, Options_1, false) of false -> {[], false}; true -> {get_value(ssl_options, Options_1, []), true} end, case ibrowse_lb:spawn_connection(Lb_pid, Parsed_url, Max_sessions, Max_pipeline_size, {SSLOptions, IsSSL}) of {ok, Conn_Pid} -> do_send_req(Conn_Pid, Parsed_url, Headers, Method, Body, Options_1, Timeout); Err -> Err end; Err -> {error, {url_parsing_failed, Err}} end. merge_options(Host, Port, Options) -> Config_options = get_config_value({options, Host, Port}, []), lists:foldl( fun({Key, Val}, Acc) -> case lists:keysearch(Key, 1, Options) of false -> [{Key, Val} | Acc]; _ -> Acc end end, Options, Config_options). get_lb_pid(Url) -> gen_server:call(?MODULE, {get_lb_pid, Url}). get_max_sessions(Host, Port, Options) -> get_value(max_sessions, Options, get_config_value({max_sessions, Host, Port}, ?DEF_MAX_SESSIONS)). get_max_pipeline_size(Host, Port, Options) -> get_value(max_pipeline_size, Options, get_config_value({max_pipeline_size, Host, Port}, ?DEF_MAX_PIPELINE_SIZE)). set_dest(Host, Port, [{max_sessions, Max} | T]) -> set_max_sessions(Host, Port, Max), set_dest(Host, Port, T); set_dest(Host, Port, [{max_pipeline_size, Max} | T]) -> set_max_pipeline_size(Host, Port, Max), set_dest(Host, Port, T); set_dest(Host, Port, [{trace, Bool} | T]) when Bool == true; Bool == false -> ibrowse ! {trace, true, Host, Port}, set_dest(Host, Port, T); set_dest(_Host, _Port, [H | _]) -> exit({invalid_option, H}); set_dest(_, _, []) -> ok. ( ) , Port::integer ( ) , Max::integer ( ) ) - > ok set_max_sessions(Host, Port, Max) when is_integer(Max), Max > 0 -> gen_server:call(?MODULE, {set_config_value, {max_sessions, Host, Port}, Max}). ( ) , Port::integer ( ) , Max::integer ( ) ) - > ok set_max_pipeline_size(Host, Port, Max) when is_integer(Max), Max > 0 -> gen_server:call(?MODULE, {set_config_value, {max_pipeline_size, Host, Port}, Max}). do_send_req(Conn_Pid, Parsed_url, Headers, Method, Body, Options, Timeout) -> case catch ibrowse_http_client:send_req(Conn_Pid, Parsed_url, Headers, Method, ensure_bin(Body), Options, Timeout) of {'EXIT', {timeout, _}} -> {error, req_timedout}; {'EXIT', Reason} -> {error, {'EXIT', Reason}}; {ok, St_code, Headers, Body} = Ret when is_binary(Body) -> case get_value(response_format, Options, list) of list -> {ok, St_code, Headers, binary_to_list(Body)}; binary -> Ret end; Ret -> Ret end. ensure_bin(L) when is_list(L) -> list_to_binary(L); ensure_bin(B) when is_binary(B) -> B; ensure_bin(Fun) when is_function(Fun) -> Fun; ensure_bin({Fun}) when is_function(Fun) -> Fun; ensure_bin({Fun, _} = Body) when is_function(Fun) -> Body. is setup . The connection attempt is made only when the first request is sent via any of the send_req_direct/4,5,6,7 functions.<br/ > ( ) , Port::integer ( ) ) - > { ok , pid ( ) } spawn_worker_process(Host, Port) -> ibrowse_http_client:start({Host, Port}). spawn_link_worker_process(Host, Port) -> ibrowse_http_client:start_link({Host, Port}). spawn_worker_process/2 or spawn_link_worker_process/2 . Requests in stop_worker_process(Conn_pid::pid ( ) ) - > ok stop_worker_process(Conn_pid) -> ibrowse_http_client:stop(Conn_pid). @doc Same as send_req/3 except that the first argument is the PID returned by spawn_worker_process/2 or spawn_link_worker_process/2 send_req_direct(Conn_pid, Url, Headers, Method) -> send_req_direct(Conn_pid, Url, Headers, Method, [], []). @doc Same as send_req/4 except that the first argument is the PID returned by spawn_worker_process/2 or spawn_link_worker_process/2 send_req_direct(Conn_pid, Url, Headers, Method, Body) -> send_req_direct(Conn_pid, Url, Headers, Method, Body, []). @doc Same as send_req/5 except that the first argument is the PID returned by spawn_worker_process/2 or spawn_link_worker_process/2 send_req_direct(Conn_pid, Url, Headers, Method, Body, Options) -> send_req_direct(Conn_pid, Url, Headers, Method, Body, Options, 30000). @doc Same as send_req/6 except that the first argument is the PID returned by spawn_worker_process/2 or spawn_link_worker_process/2 send_req_direct(Conn_pid, Url, Headers, Method, Body, Options, Timeout) -> case catch parse_url(Url) of #url{host = Host, port = Port} = Parsed_url -> Options_1 = merge_options(Host, Port, Options), case do_send_req(Conn_pid, Parsed_url, Headers, Method, Body, Options_1, Timeout) of {error, {'EXIT', {noproc, _}}} -> {error, worker_is_dead}; Ret -> Ret end; Err -> {error, {url_parsing_failed, Err}} end. stream_next(Req_id : : req_id ( ) ) - > ok | { error , unknown_req_id } stream_next(Req_id) -> case ets:lookup(ibrowse_stream, {req_id_pid, Req_id}) of [] -> {error, unknown_req_id}; [{_, Pid}] -> catch Pid ! {stream_next, Req_id}, ok end. trace_on() -> ibrowse ! {trace, true}. trace_off() -> ibrowse ! {trace, false}. ) - > ok trace_on(Host, Port) -> ibrowse ! {trace, true, Host, Port}, ok. Port ) - > ok trace_off(Host, Port) -> ibrowse ! {trace, false, Host, Port}, ok. ( ) - > ok all_trace_off() -> ibrowse ! all_trace_off, ok. show_dest_status() -> Dests = lists:filter(fun({lb_pid, {Host, Port}, _}) when is_list(Host), is_integer(Port) -> true; (_) -> false end, ets:tab2list(ibrowse_lb)), All_ets = ets:all(), io:format("~-40.40s | ~-5.5s | ~-10.10s | ~s~n", ["Server:port", "ETS", "Num conns", "LB Pid"]), io:format("~80.80.=s~n", [""]), lists:foreach(fun({lb_pid, {Host, Port}, Lb_pid}) -> case lists:dropwhile( fun(Tid) -> ets:info(Tid, owner) /= Lb_pid end, All_ets) of [] -> io:format("~40.40s | ~-5.5s | ~-5.5s | ~s~n", [Host ++ ":" ++ integer_to_list(Port), "", "", io_lib:format("~p", [Lb_pid])] ); [Tid | _] -> catch ( begin Size = ets:info(Tid, size), io:format("~40.40s | ~-5.5s | ~-5.5s | ~s~n", [Host ++ ":" ++ integer_to_list(Port), integer_to_list(Tid), integer_to_list(Size), io_lib:format("~p", [Lb_pid])] ) end ) end end, Dests). specified Host : Port . Info about workers spawned using spawn_worker_process/2 or spawn_link_worker_process/2 is not show_dest_status(Host, Port) -> case ets:lookup(ibrowse_lb, {Host, Port}) of [] -> no_active_processes; [#lb_pid{pid = Lb_pid}] -> io:format("Load Balancer Pid : ~p~n", [Lb_pid]), io:format("LB process msg q size : ~p~n", [(catch process_info(Lb_pid, message_queue_len))]), case lists:dropwhile( fun(Tid) -> ets:info(Tid, owner) /= Lb_pid end, ets:all()) of [] -> io:format("Couldn't locate ETS table for ~p~n", [Lb_pid]); [Tid | _] -> First = ets:first(Tid), Last = ets:last(Tid), Size = ets:info(Tid, size), io:format("LB ETS table id : ~p~n", [Tid]), io:format("Num Connections : ~p~n", [Size]), case Size of 0 -> ok; _ -> {First_p_sz, _} = First, {Last_p_sz, _} = Last, io:format("Smallest pipeline : ~1000.p~n", [First_p_sz]), io:format("Largest pipeline : ~1000.p~n", [Last_p_sz]) end end end. ibrowse.conf in the IBROWSE_EBIN/ .. /priv directory . Current rescan_config() -> gen_server:call(?MODULE, rescan_config). rescan_config(File) when is_list(File) -> gen_server:call(?MODULE, {rescan_config, File}). { ok , State , Timeout } | init(_) -> process_flag(trap_exit, true), State = #state{}, put(my_trace_flag, State#state.trace), put(ibrowse_trace_token, "ibrowse"), ets:new(ibrowse_lb, [named_table, public, {keypos, 2}]), ets:new(ibrowse_conf, [named_table, protected, {keypos, 2}]), ets:new(ibrowse_stream, [named_table, public]), import_config(), {ok, #state{}}. import_config() -> case code:priv_dir(ibrowse) of {error, _} = Err -> Err; PrivDir -> Filename = filename:join(PrivDir, "ibrowse.conf"), import_config(Filename) end. import_config(Filename) -> case file:consult(Filename) of {ok, Terms} -> ets:delete_all_objects(ibrowse_conf), Fun = fun({dest, Host, Port, MaxSess, MaxPipe, Options}) when is_list(Host), is_integer(Port), is_integer(MaxSess), MaxSess > 0, is_integer(MaxPipe), MaxPipe > 0, is_list(Options) -> I = [{{max_sessions, Host, Port}, MaxSess}, {{max_pipeline_size, Host, Port}, MaxPipe}, {{options, Host, Port}, Options}], lists:foreach( fun({X, Y}) -> ets:insert(ibrowse_conf, #ibrowse_conf{key = X, value = Y}) end, I); ({K, V}) -> ets:insert(ibrowse_conf, #ibrowse_conf{key = K, value = V}); (X) -> io:format("Skipping unrecognised term: ~p~n", [X]) end, lists:foreach(Fun, Terms); Err -> Err end. get_config_value(Key) -> [#ibrowse_conf{value = V}] = ets:lookup(ibrowse_conf, Key), V. get_config_value(Key, DefVal) -> case ets:lookup(ibrowse_conf, Key) of [] -> DefVal; [#ibrowse_conf{value = V}] -> V end. set_config_value(Key, Val) -> ets:insert(ibrowse_conf, #ibrowse_conf{key = Key, value = Val}). Function : handle_call/3 { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call({get_lb_pid, #url{host = Host, port = Port} = Url}, _From, State) -> Pid = do_get_connection(Url, ets:lookup(ibrowse_lb, {Host, Port})), {reply, Pid, State}; handle_call(stop, _From, State) -> do_trace("IBROWSE shutting down~n", []), {stop, normal, ok, State}; handle_call({set_config_value, Key, Val}, _From, State) -> set_config_value(Key, Val), {reply, ok, State}; handle_call(rescan_config, _From, State) -> Ret = (catch import_config()), {reply, Ret, State}; handle_call({rescan_config, File}, _From, State) -> Ret = (catch import_config(File)), {reply, Ret, State}; handle_call(Request, _From, State) -> Reply = {unknown_request, Request}, {reply, Reply, State}. Returns : { noreply , State } | { noreply , State , Timeout } | handle_cast(_Msg, State) -> {noreply, State}. Returns : { noreply , State } | { noreply , State , Timeout } | handle_info(all_trace_off, State) -> Mspec = [{{ibrowse_conf,{trace,'$1','$2'},true},[],[{{'$1','$2'}}]}], Trace_on_dests = ets:select(ibrowse_conf, Mspec), Fun = fun(#lb_pid{host_port = {H, P}, pid = Pid}, _) -> case lists:member({H, P}, Trace_on_dests) of false -> ok; true -> catch Pid ! {trace, false} end; (_, Acc) -> Acc end, ets:foldl(Fun, undefined, ibrowse_lb), ets:select_delete(ibrowse_conf, [{{ibrowse_conf,{trace,'$1','$2'},true},[],['true']}]), {noreply, State}; handle_info({trace, Bool}, State) -> put(my_trace_flag, Bool), {noreply, State}; handle_info({trace, Bool, Host, Port}, State) -> Fun = fun(#lb_pid{host_port = {H, P}, pid = Pid}, _) when H == Host, P == Port -> catch Pid ! {trace, Bool}; (_, Acc) -> Acc end, ets:foldl(Fun, undefined, ibrowse_lb), ets:insert(ibrowse_conf, #ibrowse_conf{key = {trace, Host, Port}, value = Bool}), {noreply, State}; handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions do_get_connection(#url{host = Host, port = Port}, []) -> {ok, Pid} = ibrowse_lb:start_link([Host, Port]), ets:insert(ibrowse_lb, #lb_pid{host_port = {Host, Port}, pid = Pid}), Pid; do_get_connection(_Url, [#lb_pid{pid = Pid}]) -> Pid.
8d9494b3bf33bca77b8e0db7456d3718dde167d71103ea497a826d692813f46c
plum-umd/fundamentals
yo-client2.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-intermediate-lambda-reader.ss" "lang")((modname yo-client2) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; The Yo App - exchange "yo" messages with users online ;; Use (run '!) to start a demo. ;; How to use the client: ;; - Numeric keys open chat window for designated user. ;; - Enter key sends "yo" in current chat window. (require 2htdp/universe) (require 2htdp/image) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Data Definitions A World is a ( make - world Name [ Maybe Name ] ( ) ( Listof History ) ) (define-struct world (you them users history)) ;; A History is a (make-history Name [Listof Chat]) (define-struct history (user chats)) A Chat is one of : ;; - (make-in String) ;; - (make-out String) (define-struct in (msg)) (define-struct out (msg)) ;; A Name is a String A Message is one of : - ( list " users " ( ) ) ; List of users on server - ( list " from " Name String ) ; Message from Name ;; - (list "username?") ; What's your name? ;; Interp: a valid message from the server ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Yo Client ;; yo-client : Name -> World ;; Start a yo client with the given username (define (yo-client username) (big-bang (make-world username #false '() '()) [name username] [register LOCALHOST] [on-receive handle-receive] [on-key handle-key] [to-draw draw-world])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Example : run 3 clients ( assumes server is already running ) (define (run _) (launch-many-worlds (yo-client "DVH") (yo-client "AB") (yo-client "RZ"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Constants (define FONT-SIZE 12) (define LINE-HEIGHT (* 1.4 FONT-SIZE)) (define WIDTH 200) (define LINE (rectangle WIDTH LINE-HEIGHT "solid" "white")) (define HLINE (rectangle WIDTH LINE-HEIGHT "solid" "yellow")) (define USR-WINDOW-HEIGHT 100) (define MSG-WINDOW-HEIGHT 300) (define SCENE-HEIGHT (+ USR-WINDOW-HEIGHT MSG-WINDOW-HEIGHT)) (define OUT-COLOR "plum") (define IN-COLOR "light blue") (define H0 '()) (define H1 (make-history "You" (list (make-out "yo")))) (define H2 (make-history "You" (list (make-in "yo") (make-out "yo")))) (define W0 (make-world "Me" #false (list "You") '())) (define W1 (make-world "Me" "You" (list "You") '())) (define W2 (make-world "Me" "You" (list "You") (list (make-history "You" (list (make-out "yo")))))) (define W3 (make-world "Me" "You" (list "You") (list (make-history "You" (list (make-out "yo") (make-in "yo")))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Event Handlers ;; handle-receive : World SExpr -> HandlerResult ;; Receive a message from the server (check-expect (handle-receive W0 (list "users" (list "A" "B" "C"))) (receive-users W0 (list "A" "B" "C"))) (check-expect (handle-receive W0 (list "from" "You" "yo")) (receive-chat W0 "You" "yo")) (check-expect (handle-receive W0 (list "username?")) (make-package W0 (list "username" "Me"))) (check-expect (handle-receive W0 "bogus") W0) (define (handle-receive w msg) (if (valid-message? msg) (handle-message w msg) w)) ;; handle-message : World Message -> HandlerResult ;; Receive a valid message from the server (define (handle-message w m) (local [(define tag (first m))] (cond [(string=? tag "users") (receive-users w (second m))] [(string=? tag "from") (receive-chat w (second m) (third m))] [(string=? tag "username?") (make-package w (list "username" (world-you w)))]))) handle - key : World KeyEvent - > HandlerResult ;; Handle key events; numeric keys select user, enter key tries to send yo (check-expect (handle-key W0 "1") W1) (check-expect (handle-key W0 "\r") W0) (check-expect (handle-key W1 "\r") (send-yo W1)) (check-expect (handle-key W0 "a") W0) (define (handle-key w ke) (cond [(number? (string->number ke)) (select-user w (string->number ke))] [(key=? "\r" ke) (send-yo w)] [else w])) ;; draw-world : World -> Image ;; Draw list of users above history of currently select user (define (draw-world w) (place-image/align (above (show-users (world-them w) (world-users w)) (above (line WIDTH 0 (pen "red" 1 "long-dash" "round" "bevel")) (show-chats (select-chats (world-them w) (world-history w))))) 1 1 "left" "top" (empty-scene (+ 2 WIDTH) (+ 3 SCENE-HEIGHT)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Message receivers ;; receive-users : World [Listof String] -> World ;; Receive list of users online (define (receive-users w us) (make-world (world-you w) (world-them w) ; don't include yourself in user list (filter (λ (n) (not (string=? n (world-you w)))) us) (world-history w))) ;; receive-chat : World Name String -> World ;; Receive a chat message (content) from given user (define (receive-chat w from content) (make-world (world-you w) (world-them w) (world-users w) (update-history from content (world-history w) make-in))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Message validity checking ;; valid-message? : SExpr -> Boolean Determe if message is one of : ;; - (list "username?") - ( list " users " [ ] ) - ( list " from " String String ) (check-expect (valid-message? (list "username?")) #true) (check-expect (valid-message? (list "from" "DVH" "yo")) #true) (check-expect (valid-message? (list "users" (list "DVH" "AB"))) #true) (check-expect (valid-message? #false) #false) (check-expect (valid-message? (list "username?" "blah")) #false) (check-expect (valid-message? (list "from")) #false) (check-expect (valid-message? (list "users")) #false) (check-expect (valid-message? (list "users" (list #false))) #false) (define (valid-message? msg) (and (cons? msg) (string? (first msg)) (if (empty? (rest msg)) (string=? (first msg) "username?") (cond [(string=? (first msg) "users") (and (list? (second msg)) (andmap string? (second msg)))] [(string=? (first msg) "from") (and (cons? (rest msg)) (cons? (rest (rest msg))) (empty? (rest (rest (rest msg)))) (string? (second msg)) (string? (third msg)))] [else #false])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; select-user : World Digit -> World Select user in list of users counting from 1 ; invalid selection does nothing (check-expect (select-user W0 1) W1) (check-expect (select-user W0 2) W0) (define (select-user w n) (cond [(< 0 n (add1 (length (world-users w)))) (make-world (world-you w) (list-ref (world-users w) (sub1 n)) (world-users w) (world-history w))] [else w])) ;; send-yo : World -> HandlerResult ;; Send yo message to selected user (if there is one; update chat-history (check-expect (send-yo W0) W0) (check-expect (send-yo W1) (make-package (yo-history W1) (list "message" "You" "yo"))) (define (send-yo w) (cond [(false? (world-them w)) w] [else (make-package (yo-history w) (list "message" (world-them w) "yo"))])) yo - history : World - > World ;; Add sent "yo" to the chat history with current user ;; Assume: there is a user selected (check-expect (yo-history W1) W2) (define (yo-history w) (make-world (world-you w) (world-them w) (world-users w) (update-history (world-them w) "yo" (world-history w) make-out))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; GUI show - users : [ Maybe Name ] [ Name ] - > Image ;; Render list of users, highlighting the selected one (if exists) (check-expect (show-users #false (list "A" "B")) (crop/align "left" "top" WIDTH USR-WINDOW-HEIGHT (above (show-user 1 "A" LINE) (show-user 2 "B" LINE)))) (check-expect (show-users "B" (list "A" "B")) (crop/align "left" "top" WIDTH USR-WINDOW-HEIGHT (above (show-user 1 "A" LINE) (show-user 2 "B" HLINE)))) (define (show-users selected users) (local [;; show-user/select : Number Name -> Image ;; Show user, highlight if selected (define (show-user/select n u) (show-user n u (if (and (string? selected) (string=? selected u)) HLINE LINE)))] (crop/align "left" "top" WIDTH USR-WINDOW-HEIGHT (foldr above empty-image (map show-user/select (build-list (length users) add1) users))))) ;; show-user : Number Name Image -> Image ;; Show numbered user on background of given color (check-expect (show-user 5 "DVH" LINE) (overlay/align "left" "middle" (text " 5: DVH" FONT-SIZE "black") LINE)) (define (show-user n name line) (overlay/align "left" "middle" (text (string-append " " (number->string n) ": " name) FONT-SIZE "black") line)) show - chats : [ Chat ] - > Image ;; Render all of the chats (check-expect (show-chats '()) (crop/align "left" "bottom" WIDTH MSG-WINDOW-HEIGHT empty-image)) (check-expect (show-chats (list (make-out "yo"))) (crop/align "left" "bottom" WIDTH MSG-WINDOW-HEIGHT (show-chat (make-out "yo")))) (define (show-chats chats) (crop/align "left" "bottom" WIDTH MSG-WINDOW-HEIGHT (foldl above empty-image (map show-chat chats)))) ;; show-chat : Chat -> Image ;; Render a single chat (check-expect (show-chat (make-in "yo")) (left-line (show-txt "yo" IN-COLOR))) (check-expect (show-chat (make-out "yo")) (right-line (show-txt "yo" OUT-COLOR))) (define (show-chat c) (cond [(in? c) (left-line (show-txt (in-msg c) IN-COLOR))] [(out? c) (right-line (show-txt (out-msg c) OUT-COLOR))])) ;; left-line : Image -> Image ;; Put image on left of LINE (define (left-line img) (overlay/align "left" "middle" img LINE)) ;; right-line : Image ->Image ;; Put image on right of LINE (define (right-line img) (overlay/align "right" "middle" img LINE)) show - txt : String Color - > Image ;; Render a string on given color background (define (show-txt s c) (local [(define txt (text s FONT-SIZE "black"))] (overlay txt (rectangle (* 1.5 (image-width txt)) LINE-HEIGHT "solid" c)))) select - chats : [ Maybe Name ] [ History ] - > [ Chats ] ;; Select all of the chats from the given user (check-expect (select-chats "You" '()) '()) (check-expect (select-chats "You" (list H2)) (list (make-in "yo") (make-out "yo"))) (check-expect (select-chats "Other" (list H2)) '()) (define (select-chats name h) (cond [(false? name) '()] [(empty? h) '()] [(cons? h) (if (string=? (history-user (first h)) name) (history-chats (first h)) (select-chats name (rest h)))])) update - history : Name String [ History ] [ String - > Chat ] - > [ History ] (check-expect (update-history "You" "yo" '() make-out) (list H1)) (check-expect (update-history "You" "yo" (list H1) make-in) (list H2)) (check-expect (update-history "Other" "yo" (list H1) make-out) (list H1 (make-history "Other" (list (make-out "yo"))))) (define (update-history from content h in/out) (cond [(empty? h) (list (make-history from (list (in/out content))))] [(cons? h) (if (string=? (history-user (first h)) from) (cons (make-history from (cons (in/out content) (history-chats (first h)))) (rest h)) (cons (first h) (update-history from content (rest h) in/out)))]))
null
https://raw.githubusercontent.com/plum-umd/fundamentals/eb01ac528d42855be53649991a17d19c025a97ad/1/www/code/yo-client2.rkt
racket
about the language level of this file in a form that our tools can easily process. The Yo App - exchange "yo" messages with users online Use (run '!) to start a demo. How to use the client: - Numeric keys open chat window for designated user. - Enter key sends "yo" in current chat window. Data Definitions A History is a (make-history Name [Listof Chat]) - (make-in String) - (make-out String) A Name is a String List of users on server Message from Name - (list "username?") ; What's your name? Interp: a valid message from the server Yo Client yo-client : Name -> World Start a yo client with the given username Constants Event Handlers handle-receive : World SExpr -> HandlerResult Receive a message from the server handle-message : World Message -> HandlerResult Receive a valid message from the server Handle key events; numeric keys select user, enter key tries to send yo draw-world : World -> Image Draw list of users above history of currently select user Message receivers receive-users : World [Listof String] -> World Receive list of users online don't include yourself in user list receive-chat : World Name String -> World Receive a chat message (content) from given user Message validity checking valid-message? : SExpr -> Boolean - (list "username?") select-user : World Digit -> World invalid selection does nothing send-yo : World -> HandlerResult Send yo message to selected user (if there is one; update chat-history Add sent "yo" to the chat history with current user Assume: there is a user selected GUI Render list of users, highlighting the selected one (if exists) show-user/select : Number Name -> Image Show user, highlight if selected show-user : Number Name Image -> Image Show numbered user on background of given color Render all of the chats show-chat : Chat -> Image Render a single chat left-line : Image -> Image Put image on left of LINE right-line : Image ->Image Put image on right of LINE Render a string on given color background Select all of the chats from the given user
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname yo-client2) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/universe) (require 2htdp/image) A World is a ( make - world Name [ Maybe Name ] ( ) ( Listof History ) ) (define-struct world (you them users history)) (define-struct history (user chats)) A Chat is one of : (define-struct in (msg)) (define-struct out (msg)) A Message is one of : (define (yo-client username) (big-bang (make-world username #false '() '()) [name username] [register LOCALHOST] [on-receive handle-receive] [on-key handle-key] [to-draw draw-world])) Example : run 3 clients ( assumes server is already running ) (define (run _) (launch-many-worlds (yo-client "DVH") (yo-client "AB") (yo-client "RZ"))) (define FONT-SIZE 12) (define LINE-HEIGHT (* 1.4 FONT-SIZE)) (define WIDTH 200) (define LINE (rectangle WIDTH LINE-HEIGHT "solid" "white")) (define HLINE (rectangle WIDTH LINE-HEIGHT "solid" "yellow")) (define USR-WINDOW-HEIGHT 100) (define MSG-WINDOW-HEIGHT 300) (define SCENE-HEIGHT (+ USR-WINDOW-HEIGHT MSG-WINDOW-HEIGHT)) (define OUT-COLOR "plum") (define IN-COLOR "light blue") (define H0 '()) (define H1 (make-history "You" (list (make-out "yo")))) (define H2 (make-history "You" (list (make-in "yo") (make-out "yo")))) (define W0 (make-world "Me" #false (list "You") '())) (define W1 (make-world "Me" "You" (list "You") '())) (define W2 (make-world "Me" "You" (list "You") (list (make-history "You" (list (make-out "yo")))))) (define W3 (make-world "Me" "You" (list "You") (list (make-history "You" (list (make-out "yo") (make-in "yo")))))) (check-expect (handle-receive W0 (list "users" (list "A" "B" "C"))) (receive-users W0 (list "A" "B" "C"))) (check-expect (handle-receive W0 (list "from" "You" "yo")) (receive-chat W0 "You" "yo")) (check-expect (handle-receive W0 (list "username?")) (make-package W0 (list "username" "Me"))) (check-expect (handle-receive W0 "bogus") W0) (define (handle-receive w msg) (if (valid-message? msg) (handle-message w msg) w)) (define (handle-message w m) (local [(define tag (first m))] (cond [(string=? tag "users") (receive-users w (second m))] [(string=? tag "from") (receive-chat w (second m) (third m))] [(string=? tag "username?") (make-package w (list "username" (world-you w)))]))) handle - key : World KeyEvent - > HandlerResult (check-expect (handle-key W0 "1") W1) (check-expect (handle-key W0 "\r") W0) (check-expect (handle-key W1 "\r") (send-yo W1)) (check-expect (handle-key W0 "a") W0) (define (handle-key w ke) (cond [(number? (string->number ke)) (select-user w (string->number ke))] [(key=? "\r" ke) (send-yo w)] [else w])) (define (draw-world w) (place-image/align (above (show-users (world-them w) (world-users w)) (above (line WIDTH 0 (pen "red" 1 "long-dash" "round" "bevel")) (show-chats (select-chats (world-them w) (world-history w))))) 1 1 "left" "top" (empty-scene (+ 2 WIDTH) (+ 3 SCENE-HEIGHT)))) (define (receive-users w us) (make-world (world-you w) (world-them w) (filter (λ (n) (not (string=? n (world-you w)))) us) (world-history w))) (define (receive-chat w from content) (make-world (world-you w) (world-them w) (world-users w) (update-history from content (world-history w) make-in))) Determe if message is one of : - ( list " users " [ ] ) - ( list " from " String String ) (check-expect (valid-message? (list "username?")) #true) (check-expect (valid-message? (list "from" "DVH" "yo")) #true) (check-expect (valid-message? (list "users" (list "DVH" "AB"))) #true) (check-expect (valid-message? #false) #false) (check-expect (valid-message? (list "username?" "blah")) #false) (check-expect (valid-message? (list "from")) #false) (check-expect (valid-message? (list "users")) #false) (check-expect (valid-message? (list "users" (list #false))) #false) (define (valid-message? msg) (and (cons? msg) (string? (first msg)) (if (empty? (rest msg)) (string=? (first msg) "username?") (cond [(string=? (first msg) "users") (and (list? (second msg)) (andmap string? (second msg)))] [(string=? (first msg) "from") (and (cons? (rest msg)) (cons? (rest (rest msg))) (empty? (rest (rest (rest msg)))) (string? (second msg)) (string? (third msg)))] [else #false])))) (check-expect (select-user W0 1) W1) (check-expect (select-user W0 2) W0) (define (select-user w n) (cond [(< 0 n (add1 (length (world-users w)))) (make-world (world-you w) (list-ref (world-users w) (sub1 n)) (world-users w) (world-history w))] [else w])) (check-expect (send-yo W0) W0) (check-expect (send-yo W1) (make-package (yo-history W1) (list "message" "You" "yo"))) (define (send-yo w) (cond [(false? (world-them w)) w] [else (make-package (yo-history w) (list "message" (world-them w) "yo"))])) yo - history : World - > World (check-expect (yo-history W1) W2) (define (yo-history w) (make-world (world-you w) (world-them w) (world-users w) (update-history (world-them w) "yo" (world-history w) make-out))) show - users : [ Maybe Name ] [ Name ] - > Image (check-expect (show-users #false (list "A" "B")) (crop/align "left" "top" WIDTH USR-WINDOW-HEIGHT (above (show-user 1 "A" LINE) (show-user 2 "B" LINE)))) (check-expect (show-users "B" (list "A" "B")) (crop/align "left" "top" WIDTH USR-WINDOW-HEIGHT (above (show-user 1 "A" LINE) (show-user 2 "B" HLINE)))) (define (show-users selected users) (define (show-user/select n u) (show-user n u (if (and (string? selected) (string=? selected u)) HLINE LINE)))] (crop/align "left" "top" WIDTH USR-WINDOW-HEIGHT (foldr above empty-image (map show-user/select (build-list (length users) add1) users))))) (check-expect (show-user 5 "DVH" LINE) (overlay/align "left" "middle" (text " 5: DVH" FONT-SIZE "black") LINE)) (define (show-user n name line) (overlay/align "left" "middle" (text (string-append " " (number->string n) ": " name) FONT-SIZE "black") line)) show - chats : [ Chat ] - > Image (check-expect (show-chats '()) (crop/align "left" "bottom" WIDTH MSG-WINDOW-HEIGHT empty-image)) (check-expect (show-chats (list (make-out "yo"))) (crop/align "left" "bottom" WIDTH MSG-WINDOW-HEIGHT (show-chat (make-out "yo")))) (define (show-chats chats) (crop/align "left" "bottom" WIDTH MSG-WINDOW-HEIGHT (foldl above empty-image (map show-chat chats)))) (check-expect (show-chat (make-in "yo")) (left-line (show-txt "yo" IN-COLOR))) (check-expect (show-chat (make-out "yo")) (right-line (show-txt "yo" OUT-COLOR))) (define (show-chat c) (cond [(in? c) (left-line (show-txt (in-msg c) IN-COLOR))] [(out? c) (right-line (show-txt (out-msg c) OUT-COLOR))])) (define (left-line img) (overlay/align "left" "middle" img LINE)) (define (right-line img) (overlay/align "right" "middle" img LINE)) show - txt : String Color - > Image (define (show-txt s c) (local [(define txt (text s FONT-SIZE "black"))] (overlay txt (rectangle (* 1.5 (image-width txt)) LINE-HEIGHT "solid" c)))) select - chats : [ Maybe Name ] [ History ] - > [ Chats ] (check-expect (select-chats "You" '()) '()) (check-expect (select-chats "You" (list H2)) (list (make-in "yo") (make-out "yo"))) (check-expect (select-chats "Other" (list H2)) '()) (define (select-chats name h) (cond [(false? name) '()] [(empty? h) '()] [(cons? h) (if (string=? (history-user (first h)) name) (history-chats (first h)) (select-chats name (rest h)))])) update - history : Name String [ History ] [ String - > Chat ] - > [ History ] (check-expect (update-history "You" "yo" '() make-out) (list H1)) (check-expect (update-history "You" "yo" (list H1) make-in) (list H2)) (check-expect (update-history "Other" "yo" (list H1) make-out) (list H1 (make-history "Other" (list (make-out "yo"))))) (define (update-history from content h in/out) (cond [(empty? h) (list (make-history from (list (in/out content))))] [(cons? h) (if (string=? (history-user (first h)) from) (cons (make-history from (cons (in/out content) (history-chats (first h)))) (rest h)) (cons (first h) (update-history from content (rest h) in/out)))]))
5a0c98f45d60eb2cfed8868fbced08646ce817512eb124d8f5ebdbbe1281864c
larcenists/larceny
esc3.scm
(text (begin (push $eip) (push $win) (push $lose)) (seq (push $eip) (push $win) (push $lose) (nop))) 00000000 6805000000 push dword 0x5 00000005 680A000000 push dword 0xa 0000000A 680F000000 push dword 0xf 0000000F 6814000000 push dword 0x14 00000014 6819000000 push dword 0x19 00000019 681F000000 push dword 0x1f 0000001E 90 nop
null
https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/src/Lib/Sassy/tests/prims/esc3.scm
scheme
(text (begin (push $eip) (push $win) (push $lose)) (seq (push $eip) (push $win) (push $lose) (nop))) 00000000 6805000000 push dword 0x5 00000005 680A000000 push dword 0xa 0000000A 680F000000 push dword 0xf 0000000F 6814000000 push dword 0x14 00000014 6819000000 push dword 0x19 00000019 681F000000 push dword 0x1f 0000001E 90 nop
61a798128cf3075ae81a620305aab6a535cd13a6ab05aeab5a28448b318ec282
may-liu/qtalk
ejabberd_ldap_sup.erl
-module(ejabberd_ldap_sup). %% API -export([start_link/1, init/1]). -export([add_pid/1, remove_pid/1, get_pids/0, get_random_pid/0]). -export([ login/2, get_dep/0]). -define(POOLSIZE, 5). start_link(Option) -> ets:new(ldap_server_pid, [named_table, bag, public]), supervisor:start_link({local,?MODULE}, ?MODULE, [Option]). init([Option]) -> PoolSize = proplists:get_value("poolsize", Option, ?POOLSIZE), {ok, {{one_for_one, 1000, 1}, lists:map(fun(I) -> {I, {ejabberd_ldap_server, start_link, [Option]}, transient, 2000, worker, [?MODULE]} end, lists:seq(1, PoolSize)) }}. get_pids() -> case ets:tab2list(ldap_server_pid) of [] -> []; Pids when is_list(Pids) -> Pids; _ -> [] end. get_random_pid() -> case get_pids() of [] -> undefined; Pids -> {Pid} = lists:nth(erlang:phash(os:timestamp(), length(Pids)), Pids), Pid end. add_pid(Pid) -> ets:insert(ldap_server_pid,{Pid}). remove_pid(Pid) -> ets:delete_object(ldap_server_pid,{Pid}). login(User, Passwd) -> case get_random_pid() of undefined -> error; Pid -> ejabberd_ldap_server:login(Pid, User, Passwd) end. %% ejabberd_ldap_sup:get_dep(). get_dep() -> case get_random_pid() of undefined -> []; Pid -> ejabberd_ldap_server:get_dep(Pid) end.
null
https://raw.githubusercontent.com/may-liu/qtalk/f5431e5a7123975e9656e7ab239e674ce33713cd/qtalk_opensource/src/ejabberd_ldap_sup.erl
erlang
API ejabberd_ldap_sup:get_dep().
-module(ejabberd_ldap_sup). -export([start_link/1, init/1]). -export([add_pid/1, remove_pid/1, get_pids/0, get_random_pid/0]). -export([ login/2, get_dep/0]). -define(POOLSIZE, 5). start_link(Option) -> ets:new(ldap_server_pid, [named_table, bag, public]), supervisor:start_link({local,?MODULE}, ?MODULE, [Option]). init([Option]) -> PoolSize = proplists:get_value("poolsize", Option, ?POOLSIZE), {ok, {{one_for_one, 1000, 1}, lists:map(fun(I) -> {I, {ejabberd_ldap_server, start_link, [Option]}, transient, 2000, worker, [?MODULE]} end, lists:seq(1, PoolSize)) }}. get_pids() -> case ets:tab2list(ldap_server_pid) of [] -> []; Pids when is_list(Pids) -> Pids; _ -> [] end. get_random_pid() -> case get_pids() of [] -> undefined; Pids -> {Pid} = lists:nth(erlang:phash(os:timestamp(), length(Pids)), Pids), Pid end. add_pid(Pid) -> ets:insert(ldap_server_pid,{Pid}). remove_pid(Pid) -> ets:delete_object(ldap_server_pid,{Pid}). login(User, Passwd) -> case get_random_pid() of undefined -> error; Pid -> ejabberd_ldap_server:login(Pid, User, Passwd) end. get_dep() -> case get_random_pid() of undefined -> []; Pid -> ejabberd_ldap_server:get_dep(Pid) end.
391e045e4ab76f659fadf2fdc47385ec93c944eaa39c9da0c884042454337e2b
nvim-treesitter/nvim-treesitter
locals.scm
(class_definition body: (_) @scope) (block) @scope (try_statement) @scope (catch_clause) @scope (finally_clause) @scope
null
https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/ddc0f1b606472b6a1ab85ee9becfd4877507627d/queries/dart/locals.scm
scheme
(class_definition body: (_) @scope) (block) @scope (try_statement) @scope (catch_clause) @scope (finally_clause) @scope
4627a1126e4d5eeaa9d10411f01946959cbfcd83cecc38f5c23478bb028a2c26
ckirkendall/fresnel
runner.cljs
(ns fresnel.runner (:require [cljs.test :as t :include-macros true :refer [report]] [doo.runner :include-macros true :refer [doo-all-tests]] [fresnel.lenses-test])) (doo-all-tests #"fresnel.*test")
null
https://raw.githubusercontent.com/ckirkendall/fresnel/aba1102220b0aac50061557d3969ce3bb54bac24/test/fresnel/runner.cljs
clojure
(ns fresnel.runner (:require [cljs.test :as t :include-macros true :refer [report]] [doo.runner :include-macros true :refer [doo-all-tests]] [fresnel.lenses-test])) (doo-all-tests #"fresnel.*test")
79b567b4598f632f83ec4054a16fee81c1a86140b0549ab68f08d14079402860
paurkedal/ocaml-caqti
test_mariadb.ml
Copyright ( C ) 2021 < > * * This library is free software ; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version , with the LGPL-3.0 Linking Exception . * * This library is distributed in the hope that it will be useful , but WITHOUT * ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library . If not , see * < / > and < > , respectively . * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version, with the LGPL-3.0 Linking Exception. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library. If not, see * </> and <>, respectively. *) open Testlib open Testlib_blocking module Req = struct include Caqti_type.Std include Caqti_request.Infix end let bad_select_req = Req.(unit -->! unit @:- "SELECT not_defined") let test_error (module C : Caqti_blocking.CONNECTION) = (match C.find bad_select_req () with | Ok () -> Alcotest.fail "unexpected ok from bad_select" | Error (`Request_failed {msg = Caqti_driver_mariadb.Error_msg {errno; error = _}; _}) -> Alcotest.(check int) "errno" 1054 errno | Error err -> Alcotest.failf "unexpected error from bad_select: %a" Caqti_error.pp err) let test_cases_on_connection = [ "test_error", `Quick, test_error; ] let mk_test (name, pool) = let pass_conn (name, speed, f) = let f' () = Caqti_blocking.Pool.use (fun c -> Ok (f c)) pool |> function | Ok () -> () | Error err -> Alcotest.failf "%a" Caqti_error.pp err in (name, speed, f') in let test_cases = List.map pass_conn test_cases_on_connection in (name, test_cases) let mk_tests {uris; tweaks_version} = let connect_pool uri = (match Caqti_blocking.connect_pool uri ~max_size:1 ?tweaks_version with | Ok pool -> (test_name_of_uri uri, pool) | Error err -> raise (Caqti_error.Exn err)) in let is_mariadb uri = Uri.scheme uri = Some "mariadb" in let pools = List.map connect_pool (List.filter is_mariadb uris) in List.map mk_test pools let () = Alcotest_cli.run_with_args_dependency "test_mariadb" common_args mk_tests
null
https://raw.githubusercontent.com/paurkedal/ocaml-caqti/8fa70f082461dd9772d94daf080e48ee69abfef4/caqti-driver-mariadb/test/test_mariadb.ml
ocaml
Copyright ( C ) 2021 < > * * This library is free software ; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version , with the LGPL-3.0 Linking Exception . * * This library is distributed in the hope that it will be useful , but WITHOUT * ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library . If not , see * < / > and < > , respectively . * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version, with the LGPL-3.0 Linking Exception. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library. If not, see * </> and <>, respectively. *) open Testlib open Testlib_blocking module Req = struct include Caqti_type.Std include Caqti_request.Infix end let bad_select_req = Req.(unit -->! unit @:- "SELECT not_defined") let test_error (module C : Caqti_blocking.CONNECTION) = (match C.find bad_select_req () with | Ok () -> Alcotest.fail "unexpected ok from bad_select" | Error (`Request_failed {msg = Caqti_driver_mariadb.Error_msg {errno; error = _}; _}) -> Alcotest.(check int) "errno" 1054 errno | Error err -> Alcotest.failf "unexpected error from bad_select: %a" Caqti_error.pp err) let test_cases_on_connection = [ "test_error", `Quick, test_error; ] let mk_test (name, pool) = let pass_conn (name, speed, f) = let f' () = Caqti_blocking.Pool.use (fun c -> Ok (f c)) pool |> function | Ok () -> () | Error err -> Alcotest.failf "%a" Caqti_error.pp err in (name, speed, f') in let test_cases = List.map pass_conn test_cases_on_connection in (name, test_cases) let mk_tests {uris; tweaks_version} = let connect_pool uri = (match Caqti_blocking.connect_pool uri ~max_size:1 ?tweaks_version with | Ok pool -> (test_name_of_uri uri, pool) | Error err -> raise (Caqti_error.Exn err)) in let is_mariadb uri = Uri.scheme uri = Some "mariadb" in let pools = List.map connect_pool (List.filter is_mariadb uris) in List.map mk_test pools let () = Alcotest_cli.run_with_args_dependency "test_mariadb" common_args mk_tests
496a66a4705163451b4bf0de63fb09f1d240d315ee4463e2572b685afac0e545
caradoc-org/caradoc
typesgraphic.ml
(*****************************************************************************) (* Caradoc: a PDF parser and validator *) Copyright ( C ) 2015 ANSSI Copyright ( C ) 2015 - 2017 (* *) (* This program is free software; you can redistribute it and/or modify *) it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation . (* *) (* This program is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU General Public License for more details. *) (* *) You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . (*****************************************************************************) open Type.Type open Util open Boundedint let register_graphic ctxt = (***********************) PDF reference 8.4.5 (***********************) register_class ~strict:false ctxt.pool "graphic_state" [ "Type", entry_name_exact ~allow_ind:false ~optional:true "ExtGState" ; (* TODO : check allowed values *) "LW", entry_alias ~optional:true "number" ; (* TODO : check allowed values *) "LC", make_entry_type ~optional:true Int ; (* TODO : check allowed values *) "LJ", make_entry_type ~optional:true Int ; "ML", entry_alias ~optional:true "number" ; "D", entry_alias ~optional:true "dash_pattern" ; (* TODO : check allowed values *) "RI", make_entry_type ~optional:true Name ; "OP", make_entry_type ~optional:true Bool ; "op", make_entry_type ~optional:true Bool ; (* TODO : check allowed values *) "OPM", make_entry_type ~optional:true Int ; (* TODO : check allowed values *) "Font", entry_tuple ~optional:true [| type_alias "font" ; type_alias "numpositive" |] ; "BG", entry_alias ~optional:true "function" ; "BG2", entry_variant ~optional:true [Alias "function" ; NameExact "Default"] ; "UCR", entry_alias ~optional:true "function" ; "UCR2", entry_variant ~optional:true [Alias "function" ; NameExact "Default"] ; "TR", entry_variant ~optional:true [Alias "function" ; ArraySized (type_alias "function", 4) ; NameExact "Identity"] ; "TR2", entry_variant ~optional:true [Alias "function" ; ArraySized (type_alias "function", 4) ; kind_name_in ["Identity" ; "Default"]] ; "HT", entry_variant ~optional:true [Alias "halftone" ; NameExact "Default"] ; (* TODO : check allowed values *) "FL", entry_alias ~optional:true "number" ; (* TODO : check allowed values *) "SM", entry_alias ~optional:true "number" ; "SA", make_entry_type ~optional:true Bool ; "BM", entry_alias ~optional:true "blend_mode" ; "SMask", entry_alias ~optional:true "soft_mask" ; (* TODO : check allowed values *) "CA", entry_alias ~optional:true "number" ; (* TODO : check allowed values *) "ca", entry_alias ~optional:true "number" ; "AIS", make_entry_type ~optional:true Bool ; "TK", make_entry_type ~optional:true Bool ; ]; TODO register_alias ctxt.pool "halftone" Any; register_alias ctxt.pool "blend_mode" Any; register_alias ctxt.pool "soft_mask" Any; (*********************) PDF reference 8.7 (*********************) register_alias ctxt.pool "pattern" (Variant [ Stream "tiling_pattern" ; Class "shading_pattern" ; ]); register_class ctxt.pool "pattern_base" [ "Type", entry_name_exact ~allow_ind:false ~optional:true "Pattern" ; "Matrix", entry_alias ~optional:true "matrix6" ; ]; register_class ctxt.pool "tiling_pattern" ~includes:[ "stream_base" ; "pattern_base" ; ] [ "PatternType", entry_int_exact ~optional:false 1 ; "PaintType", make_entry_type ~optional:false Int ; "TilingType", make_entry_type ~optional:false Int ; "BBox", entry_alias ~optional:false "rectangle" ; "XStep", entry_alias ~optional:false "numnonzero" ; "YStep", entry_alias ~optional:false "numnonzero" ; "Resources", entry_class ~optional:false "resources" ; ]; register_class ctxt.pool "shading_pattern" ~includes:[ "pattern_base" ; ] [ "PatternType", entry_int_exact ~optional:false 2 ; "Shading", entry_alias ~optional:false "shading" ; "ExtGState", entry_class ~optional:true "graphic_state" ; ]; (*************************) (* PDF reference 8.7.4.3 *) (*************************) register_alias ctxt.pool "shading" (Variant [ Class "shading_1" ; Class "shading_2" ; Class "shading_3" ; Stream "shading_4" ; Stream "shading_5" ; Stream "shading_6" ; Stream "shading_7" ; ]); register_class ctxt.pool "shading_base" [ "ColorSpace", entry_alias ~optional:false "color_space" ; (* TODO : background *) "Background", entry_array ~optional:true (make_type Any) ; "BBox", entry_alias ~optional:true "rectangle" ; "AntiAlias", make_entry_type ~optional:true Bool ; ]; register_class ctxt.pool "shading_1" ~includes:[ "shading_base" ; ] [ "ShadingType", entry_int_exact ~allow_ind:false ~optional:false 1 ; "Domain", entry_alias ~optional:true "rectangle" ; "Matrix", entry_alias ~optional:true "matrix6" ; "Function", entry_alias ~optional:false "function" ; ]; register_class ctxt.pool "shading_2" ~includes:[ "shading_base" ; ] [ "ShadingType", entry_int_exact ~allow_ind:false ~optional:false 2 ; "Coords", entry_sized_array ~optional:false 4 (type_alias "number") ; "Domain", entry_sized_array ~optional:true 2 (type_alias "number") ; "Function", entry_alias ~optional:false "function" ; "Extend", entry_sized_array ~optional:true 2 (make_type Bool) ; ]; register_class ctxt.pool "shading_3" ~includes:[ "shading_base" ; ] [ "ShadingType", entry_int_exact ~allow_ind:false ~optional:false 3 ; "Coords", entry_sized_array ~optional:false 6 (type_alias "number") ; "Domain", entry_sized_array ~optional:true 2 (type_alias "number") ; "Function", entry_alias ~optional:false "function" ; "Extend", entry_sized_array ~optional:true 2 (make_type Bool) ; ]; register_class ctxt.pool "shading_stream_base" ~includes:[ "shading_base" ; "stream_base" ; ] [ "BitsPerCoordinate", entry_int_in ~optional:false [| 1 ; 2 ; 4 ; 8 ; 12 ; 16 ; 24 ; 32 |] ; "BitsPerComponent", entry_int_in ~optional:false [| 1 ; 2 ; 4 ; 8 ; 12 ; 16 |] ; "Decode", entry_array_tuples ~optional:false [| type_alias "number" ; type_alias "number" |] ; "Function", entry_alias ~optional:true "function" ; ]; register_class ctxt.pool "shading_467" ~includes:[ "shading_stream_base" ; ] [ "BitsPerFlag", entry_int_in ~optional:false [| 2 ; 4 ; 8 |] ; ]; register_class ctxt.pool "shading_4" ~includes:[ "shading_467" ; ] [ "ShadingType", entry_int_exact ~allow_ind:false ~optional:false 4 ; ]; register_class ctxt.pool "shading_5" ~includes:[ "shading_stream_base" ; ] [ "ShadingType", entry_int_exact ~allow_ind:false ~optional:false 5 ; "VerticesPerRow", make_entry_type ~optional:false (IntRange (Some ~:2, None)) ; ]; register_class ctxt.pool "shading_6" ~includes:[ "shading_467" ; ] [ "ShadingType", entry_int_exact ~allow_ind:false ~optional:false 6 ; ]; register_class ctxt.pool "shading_7" ~includes:[ "shading_467" ; ] [ "ShadingType", entry_int_exact ~allow_ind:false ~optional:false 7 ; ];
null
https://raw.githubusercontent.com/caradoc-org/caradoc/100f53bc55ef682049e10fabf24869bc019dc6ce/src/type/pdf/typesgraphic.ml
ocaml
*************************************************************************** Caradoc: a PDF parser and validator This program is free software; you can redistribute it and/or modify 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. *************************************************************************** ********************* ********************* TODO : check allowed values TODO : check allowed values TODO : check allowed values TODO : check allowed values TODO : check allowed values TODO : check allowed values TODO : check allowed values TODO : check allowed values TODO : check allowed values TODO : check allowed values ******************* ******************* *********************** PDF reference 8.7.4.3 *********************** TODO : background
Copyright ( C ) 2015 ANSSI Copyright ( C ) 2015 - 2017 it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . open Type.Type open Util open Boundedint let register_graphic ctxt = PDF reference 8.4.5 register_class ~strict:false ctxt.pool "graphic_state" [ "Type", entry_name_exact ~allow_ind:false ~optional:true "ExtGState" ; "LW", entry_alias ~optional:true "number" ; "LC", make_entry_type ~optional:true Int ; "LJ", make_entry_type ~optional:true Int ; "ML", entry_alias ~optional:true "number" ; "D", entry_alias ~optional:true "dash_pattern" ; "RI", make_entry_type ~optional:true Name ; "OP", make_entry_type ~optional:true Bool ; "op", make_entry_type ~optional:true Bool ; "OPM", make_entry_type ~optional:true Int ; "Font", entry_tuple ~optional:true [| type_alias "font" ; type_alias "numpositive" |] ; "BG", entry_alias ~optional:true "function" ; "BG2", entry_variant ~optional:true [Alias "function" ; NameExact "Default"] ; "UCR", entry_alias ~optional:true "function" ; "UCR2", entry_variant ~optional:true [Alias "function" ; NameExact "Default"] ; "TR", entry_variant ~optional:true [Alias "function" ; ArraySized (type_alias "function", 4) ; NameExact "Identity"] ; "TR2", entry_variant ~optional:true [Alias "function" ; ArraySized (type_alias "function", 4) ; kind_name_in ["Identity" ; "Default"]] ; "HT", entry_variant ~optional:true [Alias "halftone" ; NameExact "Default"] ; "FL", entry_alias ~optional:true "number" ; "SM", entry_alias ~optional:true "number" ; "SA", make_entry_type ~optional:true Bool ; "BM", entry_alias ~optional:true "blend_mode" ; "SMask", entry_alias ~optional:true "soft_mask" ; "CA", entry_alias ~optional:true "number" ; "ca", entry_alias ~optional:true "number" ; "AIS", make_entry_type ~optional:true Bool ; "TK", make_entry_type ~optional:true Bool ; ]; TODO register_alias ctxt.pool "halftone" Any; register_alias ctxt.pool "blend_mode" Any; register_alias ctxt.pool "soft_mask" Any; PDF reference 8.7 register_alias ctxt.pool "pattern" (Variant [ Stream "tiling_pattern" ; Class "shading_pattern" ; ]); register_class ctxt.pool "pattern_base" [ "Type", entry_name_exact ~allow_ind:false ~optional:true "Pattern" ; "Matrix", entry_alias ~optional:true "matrix6" ; ]; register_class ctxt.pool "tiling_pattern" ~includes:[ "stream_base" ; "pattern_base" ; ] [ "PatternType", entry_int_exact ~optional:false 1 ; "PaintType", make_entry_type ~optional:false Int ; "TilingType", make_entry_type ~optional:false Int ; "BBox", entry_alias ~optional:false "rectangle" ; "XStep", entry_alias ~optional:false "numnonzero" ; "YStep", entry_alias ~optional:false "numnonzero" ; "Resources", entry_class ~optional:false "resources" ; ]; register_class ctxt.pool "shading_pattern" ~includes:[ "pattern_base" ; ] [ "PatternType", entry_int_exact ~optional:false 2 ; "Shading", entry_alias ~optional:false "shading" ; "ExtGState", entry_class ~optional:true "graphic_state" ; ]; register_alias ctxt.pool "shading" (Variant [ Class "shading_1" ; Class "shading_2" ; Class "shading_3" ; Stream "shading_4" ; Stream "shading_5" ; Stream "shading_6" ; Stream "shading_7" ; ]); register_class ctxt.pool "shading_base" [ "ColorSpace", entry_alias ~optional:false "color_space" ; "Background", entry_array ~optional:true (make_type Any) ; "BBox", entry_alias ~optional:true "rectangle" ; "AntiAlias", make_entry_type ~optional:true Bool ; ]; register_class ctxt.pool "shading_1" ~includes:[ "shading_base" ; ] [ "ShadingType", entry_int_exact ~allow_ind:false ~optional:false 1 ; "Domain", entry_alias ~optional:true "rectangle" ; "Matrix", entry_alias ~optional:true "matrix6" ; "Function", entry_alias ~optional:false "function" ; ]; register_class ctxt.pool "shading_2" ~includes:[ "shading_base" ; ] [ "ShadingType", entry_int_exact ~allow_ind:false ~optional:false 2 ; "Coords", entry_sized_array ~optional:false 4 (type_alias "number") ; "Domain", entry_sized_array ~optional:true 2 (type_alias "number") ; "Function", entry_alias ~optional:false "function" ; "Extend", entry_sized_array ~optional:true 2 (make_type Bool) ; ]; register_class ctxt.pool "shading_3" ~includes:[ "shading_base" ; ] [ "ShadingType", entry_int_exact ~allow_ind:false ~optional:false 3 ; "Coords", entry_sized_array ~optional:false 6 (type_alias "number") ; "Domain", entry_sized_array ~optional:true 2 (type_alias "number") ; "Function", entry_alias ~optional:false "function" ; "Extend", entry_sized_array ~optional:true 2 (make_type Bool) ; ]; register_class ctxt.pool "shading_stream_base" ~includes:[ "shading_base" ; "stream_base" ; ] [ "BitsPerCoordinate", entry_int_in ~optional:false [| 1 ; 2 ; 4 ; 8 ; 12 ; 16 ; 24 ; 32 |] ; "BitsPerComponent", entry_int_in ~optional:false [| 1 ; 2 ; 4 ; 8 ; 12 ; 16 |] ; "Decode", entry_array_tuples ~optional:false [| type_alias "number" ; type_alias "number" |] ; "Function", entry_alias ~optional:true "function" ; ]; register_class ctxt.pool "shading_467" ~includes:[ "shading_stream_base" ; ] [ "BitsPerFlag", entry_int_in ~optional:false [| 2 ; 4 ; 8 |] ; ]; register_class ctxt.pool "shading_4" ~includes:[ "shading_467" ; ] [ "ShadingType", entry_int_exact ~allow_ind:false ~optional:false 4 ; ]; register_class ctxt.pool "shading_5" ~includes:[ "shading_stream_base" ; ] [ "ShadingType", entry_int_exact ~allow_ind:false ~optional:false 5 ; "VerticesPerRow", make_entry_type ~optional:false (IntRange (Some ~:2, None)) ; ]; register_class ctxt.pool "shading_6" ~includes:[ "shading_467" ; ] [ "ShadingType", entry_int_exact ~allow_ind:false ~optional:false 6 ; ]; register_class ctxt.pool "shading_7" ~includes:[ "shading_467" ; ] [ "ShadingType", entry_int_exact ~allow_ind:false ~optional:false 7 ; ];
b4456f303af124e4f8de08bfa05866ad9e9c08ade163c1f78f777fad560d0e49
erlang/otp
erl_distribution_SUITE.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 1997 - 2022 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% -module(erl_distribution_SUITE). -include_lib("common_test/include/ct.hrl"). -include_lib("kernel/include/dist.hrl"). -include_lib("stdlib/include/assert.hrl"). -include_lib("kernel/include/file.hrl"). -export([all/0, suite/0,groups/0,init_per_suite/1, end_per_suite/1, init_per_group/2,end_per_group/2]). -export([tick/1, tick_intensity/1, tick_change/1, connect_node/1, nodenames/1, hostnames/1, illegal_nodenames/1, hidden_node/1, dyn_node_name/1, epmd_reconnect/1, setopts/1, table_waste/1, net_setuptime/1, inet_dist_options_options/1, net_ticker_spawn_options/1, monitor_nodes_nodedown_reason/1, monitor_nodes_complex_nodedown_reason/1, monitor_nodes_node_type/1, monitor_nodes_misc/1, monitor_nodes_otp_6481/1, monitor_nodes_errors/1, monitor_nodes_combinations/1, monitor_nodes_cleanup/1, monitor_nodes_many/1, monitor_nodes_down_up/1, dist_ctrl_proc_smoke/1, dist_ctrl_proc_reject/1, erl_uds_dist_smoke_test/1, erl_1424/1, net_kernel_start/1, differing_cookies/1, cmdline_setcookie_2/1, connection_cookie/1, dyn_differing_cookies/1, xdg_cookie/1]). %% Performs the test at another node. -export([get_socket_priorities/0, get_net_ticker_fullsweep_option/1, tick_cli_test/3, tick_cli_test1/3, tick_serv_test/2, tick_serv_test1/1, run_remote_test/1, dyn_node_name_do/2, epmd_reconnect_do/2, setopts_do/2, setopts_deadlock_test/2, keep_conn/1, time_ping/1, ddc_remote_run/2]). -export([net_kernel_start_do_test/1]). -export([init_per_testcase/2, end_per_testcase/2]). -export([dist_cntrlr_output_test_size/2]). -export([pinger/1]). -export([start_uds_rpc_server/1]). -define(DUMMY_NODE,dummy@test01). -define(ALT_EPMD_PORT, "12321"). -define(ALT_EPMD_CMD, "epmd -port "++?ALT_EPMD_PORT). %%----------------------------------------------------------------- %% The distribution is mainly tested in the big old test_suite. %% This test only tests the net_ticktime configuration flag. %% Should be started in a CC view with: %% erl -sname master -rsh ctrsh %%----------------------------------------------------------------- suite() -> [{ct_hooks,[ts_install_cth]}, {timetrap,{minutes,12}}]. all() -> [dist_ctrl_proc_smoke, dist_ctrl_proc_reject, tick, tick_intensity, tick_change, nodenames, hostnames, illegal_nodenames, connect_node, dyn_node_name, epmd_reconnect, hidden_node, setopts, table_waste, net_setuptime, inet_dist_options_options, net_ticker_spawn_options, {group, monitor_nodes}, erl_uds_dist_smoke_test, erl_1424, net_kernel_start, {group, differing_cookies}]. groups() -> [{monitor_nodes, [], [monitor_nodes_nodedown_reason, monitor_nodes_complex_nodedown_reason, monitor_nodes_node_type, monitor_nodes_misc, monitor_nodes_otp_6481, monitor_nodes_errors, monitor_nodes_combinations, monitor_nodes_cleanup, monitor_nodes_many, monitor_nodes_down_up]}, {differing_cookies, [], [differing_cookies, cmdline_setcookie_2, connection_cookie, dyn_differing_cookies, xdg_cookie]}]. init_per_suite(Config) -> start_gen_tcp_dist_test_type_server(), Config. end_per_suite(_Config) -> [slave:stop(N) || N <- nodes()], kill_gen_tcp_dist_test_type_server(), ok. init_per_group(_GroupName, Config) -> Config. end_per_group(_GroupName, Config) -> Config. init_per_testcase(TC, Config) when TC == hostnames; TC == nodenames -> file:make_dir("hostnames_nodedir"), file:write_file("hostnames_nodedir/ignore_core_files",""), Config; init_per_testcase(epmd_reconnect, Config) -> [] = os:cmd(?ALT_EPMD_CMD++" -relaxed_command_check -daemon"), Config; init_per_testcase(Func, Config) when is_atom(Func), is_list(Config) -> Config. end_per_testcase(epmd_reconnect, _Config) -> os:cmd(?ALT_EPMD_CMD++" -kill"), ok; end_per_testcase(_Func, _Config) -> ok. connect_node(Config) when is_list(Config) -> Connected = nodes(connected), true = net_kernel:connect_node(node()), Connected = nodes(connected), ok. tick(Config) when is_list(Config) -> run_dist_configs(fun tick/2, Config). tick(DCfg, Config) -> tick_test(DCfg, Config, false). tick_intensity(Config) when is_list(Config) -> run_dist_configs(fun tick_intensity/2, Config). tick_intensity(DCfg, Config) -> tick_test(DCfg, Config, true). tick_test(DCfg, _Config, CheckIntensityArg) -> %% %% This test case use disabled "connect all" so that %% global wont interfere... %% [Name1, Name2] = get_nodenames(2, dist_test), {ok, Node} = start_node(DCfg, Name1), case CheckIntensityArg of true -> %% Not for intensity test... ok; false -> First check that the normal case is OK ! rpc:call(Node, erl_distribution_SUITE, tick_cli_test, [node(), 8000, 16000]), erlang:monitor_node(Node, true), receive {nodedown, Node} -> ct:fail("nodedown from other node") after 30000 -> erlang:monitor_node(Node, false) end, ok end, stop_node(Node), Now , set the net_ticktime for the other node to 12 secs . %% After the sleep(2sec) and cast the other node shall destroy %% the connection as it has not received anything on the connection. The nodedown message should arrive within 8 < T < 16 secs . We must have two slave nodes as the slave mechanism otherwise %% halts the client node after tick timeout (the connection is down %% and the slave node decides to halt !! Set the ticktime on the server node to 100 secs so the server %% node doesn't tick the client node within the interval ... {ok, ServNode} = start_node(DCfg, Name2, "-kernel net_ticktime 100 -connect_all false"), rpc:call(ServNode, erl_distribution_SUITE, tick_serv_test, [Node, node()]), We set min / max a second lower / higher than expected since it takes %% time for termination of the dist controller, delivery of messages, scheduling of the process receiving nodedown , etc ... {IArg, Min, Max} = case CheckIntensityArg of false -> {"", 7000, 17000}; true -> {" -kernel net_tickintensity 24", 10500, 13500} end, {ok, Node} = start_node(DCfg, Name1, "-kernel net_ticktime 12 -connect_all false" ++ IArg), rpc:call(Node, erl_distribution_SUITE, tick_cli_test, [ServNode, Min, Max]), spawn_link(erl_distribution_SUITE, keep_conn, [Node]), {tick_serv, ServNode} ! {i_want_the_result, self()}, monitor_node(ServNode, true), monitor_node(Node, true), receive {tick_test, T} when is_integer(T) -> stop_node(ServNode), stop_node(Node), io:format("Result: ~p~n", [T]), T; {tick_test, Error} -> stop_node(ServNode), stop_node(Node), ct:fail(Error); {nodedown, Node} -> stop_node(ServNode), ct:fail("client node died"); {nodedown, ServNode} -> stop_node(Node), ct:fail("server node died") end, ok. %% Checks that pinging nonexistyent nodes does not waste space in distribution table. table_waste(Config) when is_list(Config) -> run_dist_configs(fun table_waste/2, Config). table_waste(DCfg, _Config) -> {ok, HName} = inet:gethostname(), F = fun(0,_F) -> []; (N,F) -> Name = list_to_atom("erl_distribution_"++integer_to_list(N)++ "@"++HName), pang = net_adm:ping(Name), F(N-1,F) end, F(256,F), {ok, N} = start_node(DCfg, erl_distribution_300), stop_node(N), ok. %% Test that starting nodes with different legal name part works, and that illegal %% ones are filtered nodenames(Config) when is_list(Config) -> legal("a1@b"), legal("a-1@b"), legal("a_1@b"), Test that giving two -sname works as it should started = test_node("a_1@b", false, long_or_short() ++ "a_0@b"), illegal("cdé@a"), illegal("te欢st@a"). %% Test that starting nodes with different legal host part works, and that illegal %% ones are filtered hostnames(Config) when is_list(Config) -> Host = gethostname(), legal([$a,$@|atom_to_list(Host)]), legal("1@b1"), legal("b@b1-c"), legal("c@b1_c"), legal("d@b1#c"), legal("f@::1"), legal("g@1:bc3:4e3f:f20:0:1"), case file:native_name_encoding() of latin1 -> ignore; _ -> legal("e@b1é") end, long_hostnames(net_kernel:longnames()), illegal("h@testالع"), illegal("i@языtest"), illegal("j@te欢st"). long_hostnames(true) -> legal(""), legal(""), legal("_c.d"), legal("[email protected]"), legal("[email protected]"); long_hostnames(false) -> illegal(""). legal(Name) -> case test_node(Name) of started -> ok; not_started -> ct:fail("no ~p node started", [Name]) end. illegal(Name) -> case test_node(Name, true) of not_started -> ok; started -> ct:fail("~p node started with illegal name", [Name]) end. test_node(Name) -> test_node(Name, false). test_node(Name, Illegal) -> test_node(Name, Illegal, ""). test_node(Name, Illegal, ExtraArgs) -> ProgName = ct:get_progname(), Command = ProgName ++ " -noinput " ++ long_or_short() ++ Name ++ ExtraArgs ++ " -eval \"net_adm:ping('" ++ atom_to_list(node()) ++ "')\"" ++ case Illegal of true -> " -eval \"timer:sleep(10000),init:stop().\""; false -> "" end, net_kernel:monitor_nodes(true), BinCommand = unicode:characters_to_binary(Command, utf8), _Prt = open_port({spawn, BinCommand}, [stream,{cd,"hostnames_nodedir"}]), Node = list_to_atom(Name), receive {nodeup, Node} -> net_kernel:monitor_nodes(false), slave:stop(Node), started after 5000 -> net_kernel:monitor_nodes(false), not_started end. long_or_short() -> case net_kernel:longnames() of true -> " -name "; false -> " -sname " end. % get the localhost's name, depending on the using name policy gethostname() -> Hostname = case net_kernel:longnames() of true-> net_adm:localhost(); _-> {ok, Name}=inet:gethostname(), Name end, list_to_atom(Hostname). %% Test that pinging an illegal nodename does not kill the node. illegal_nodenames(Config) when is_list(Config) -> run_dist_configs(fun illegal_nodenames/2, Config). illegal_nodenames(DCfg, _Config) -> {ok, Node}=start_node(DCfg, illegal_nodenames), monitor_node(Node, true), RPid=rpc:call(Node, erlang, spawn, [?MODULE, pinger, [self()]]), receive {RPid, pinged} -> monitor_node(Node, false), ok; {nodedown, Node} -> ct:fail("Remote node died.") end, stop_node(Node), ok. pinger(Starter) -> io:format("Starter:~p~n",[Starter]), net_adm:ping(a@b@c), Starter ! {self(), pinged}, ok. Test that you can set the net_setuptime properly . net_setuptime(Config) when is_list(Config) -> run_dist_configs(fun net_setuptime/2, Config). net_setuptime(DCfg, _Config) -> %% In this test case, we reluctantly accept shorter times than the given %% setup time, because the connection attempt can end in a %% "Host unreachable" error before the timeout fires. Res0 = do_test_setuptime(DCfg, "2"), io:format("Res0 = ~p", [Res0]), true = (Res0 =< 4000), Res1 = do_test_setuptime(DCfg, "0.3"), io:format("Res1 = ~p", [Res1]), true = (Res1 =< 500), ok. do_test_setuptime(DCfg, Setuptime) when is_list(Setuptime) -> {ok, Node} = start_node(DCfg, dist_setuptime_test, "-kernel net_setuptime " ++ Setuptime), Res = rpc:call(Node,?MODULE,time_ping,[?DUMMY_NODE]), stop_node(Node), Res. time_ping(Node) -> T0 = erlang:monotonic_time(), pang = net_adm:ping(Node), T1 = erlang:monotonic_time(), erlang:convert_time_unit(T1 - T0, native, millisecond). %% Keep the connection with the client node up. %% This is necessary as the client node runs with much shorter %% tick time !! keep_conn(Node) -> sleep(1), rpc:cast(Node, erlang, time, []), keep_conn(Node). tick_serv_test(Node, MasterNode) -> spawn(erl_distribution_SUITE, keep_conn, [MasterNode]), spawn(erl_distribution_SUITE, tick_serv_test1, [Node]). tick_serv_test1(Node) -> register(tick_serv, self()), TestServer = receive {i_want_the_result, TS} -> TS end, monitor_node(Node, true), receive {nodedown, Node} -> net_adm:ping(Node), %% Set up the connection again !! {tick_test, Node} ! {whats_the_result, self()}, receive {tick_test, Res} -> TestServer ! {tick_test, Res} end end. tick_cli_test(Node, Min, Max) -> spawn(erl_distribution_SUITE, tick_cli_test1, [Node, Min, Max]). tick_cli_test1(Node, Min, Max) -> register(tick_test, self()), erlang:monitor_node(Node, true), sleep(2), rpc:call(Node, erlang, time, []), %% simulate action on the connection T1 = erlang:monotonic_time(), receive {nodedown, Node} -> T2 = erlang:monotonic_time(), receive {whats_the_result, From} -> Diff = erlang:convert_time_unit(T2-T1, native, millisecond), case Diff of T when Min =< T, T =< Max -> From ! {tick_test, T}; T -> From ! {tick_test, {"T not in interval " ++ integer_to_list(Min) ++ " =< T =< " ++ integer_to_list(Max), T}} end end end. epmd_reconnect(Config) when is_list(Config) -> NodeNames = [N1,N2,N3] = get_nodenames(3, ?FUNCTION_NAME), Nodes = [atom_to_list(full_node_name(NN)) || NN <- NodeNames], DCfg = "-epmd_port "++?ALT_EPMD_PORT, {_N1F,Port1} = start_node_unconnected(DCfg, N1, ?MODULE, run_remote_test, ["epmd_reconnect_do", atom_to_list(node()), "1" | Nodes]), {_N2F,Port2} = start_node_unconnected(DCfg, N2, ?MODULE, run_remote_test, ["epmd_reconnect_do", atom_to_list(node()), "2" | Nodes]), {_N3F,Port3} = start_node_unconnected(DCfg, N3, ?MODULE, run_remote_test, ["epmd_reconnect_do", atom_to_list(node()), "3" | Nodes]), Ports = [Port1, Port2, Port3], ok = reap_ports(Ports), ok. reap_ports([]) -> ok; reap_ports(Ports) -> case (receive M -> M end) of {Port, Message} -> case lists:member(Port, Ports) andalso Message of {data,String} -> io:format("~p: ~s\n", [Port, String]), reap_ports(Ports); {exit_status,0} -> reap_ports(Ports -- [Port]) end end. epmd_reconnect_do(_Node, ["1", Node1, Node2, Node3]) -> Names = [Name || Name <- [hd(string:tokens(Node, "@")) || Node <- [Node1, Node2, Node3]]], %% wait until all nodes are registered ok = wait_for_names(Names), "Killed" ++_ = os:cmd(?ALT_EPMD_CMD++" -kill"), open_port({spawn, ?ALT_EPMD_CMD}, []), %% check that all nodes reregister with epmd ok = wait_for_names(Names), lists:foreach(fun(Node) -> ANode = list_to_atom(Node), pong = net_adm:ping(ANode), {epmd_reconnect_do, ANode} ! {stop, Node1, Node} end, [Node2, Node3]), ok; epmd_reconnect_do(_Node, ["2", Node1, Node2, _Node3]) -> register(epmd_reconnect_do, self()), receive {stop, Node1, Node2} -> ok after 7000 -> exit(timeout) end; epmd_reconnect_do(_Node, ["3", Node1, _Node2, Node3]) -> register(epmd_reconnect_do, self()), receive {stop, Node1, Node3} -> ok after 7000 -> exit(timeout) end. wait_for_names(Names) -> wait for up to 3 seconds ( the current retry timer in erl_epmd is 2s ) wait_for_names(lists:sort(Names), 30, 100). wait_for_names(Names, N, Wait) when N > 0 -> try {ok, Info} = erl_epmd:names(), Names = lists:sort([Name || {Name, _Port} <- Info]), ok catch error:{badmatch, _} -> timer:sleep(Wait), wait_for_names(Names, N-1, Wait) end. dyn_node_name(Config) when is_list(Config) -> run_dist_configs(fun dyn_node_name/2, Config). dyn_node_name(DCfg, _Config) -> NameDomain = case net_kernel:get_state() of #{name_domain := shortnames} -> "shortnames"; #{name_domain := longnames} -> "longnames" end, {_N1F,Port1} = start_node_unconnected(DCfg, undefined, ?MODULE, run_remote_test, ["dyn_node_name_do", atom_to_list(node()), NameDomain]), 0 = wait_for_port_exit(Port1), ok. dyn_node_name_do(TestNode, [NameDomainStr]) -> nonode@nohost = node(), [] = nodes(), [] = nodes(hidden), NameDomain = list_to_atom(NameDomainStr), #{started := static, name_type := dynamic, name := undefined, name_domain := NameDomain} = net_kernel:get_state(), net_kernel:monitor_nodes(true, [{node_type,all}]), net_kernel:connect_node(TestNode), [] = nodes(), [TestNode] = nodes(hidden), MyName = node(), false = (MyName =:= undefined), false = (MyName =:= nonode@nohost), #{started := static, name_type := dynamic, name := MyName, name_domain := NameDomain} = net_kernel:get_state(), check([MyName], rpc:call(TestNode, erlang, nodes, [hidden])), {nodeup, MyName, [{node_type, visible}]} = receive_any(), {nodeup, TestNode, [{node_type, hidden}]} = receive_any(), true = net_kernel:disconnect(TestNode), We do n't know the order of these nodedown messages . Often nodedown from the connection comes first , but not always ... NodedownMsgsA = lists:sort([{nodedown, TestNode, [{node_type, hidden}]}, {nodedown, MyName, [{node_type, visible}]}]), NodedownMsgA1 = receive_any(), NodedownMsgA2 = receive_any(), NodedownMsgsA = lists:sort([NodedownMsgA1, NodedownMsgA2]), [] = nodes(hidden), nonode@nohost = node(), #{started := static, name_type := dynamic, name := undefined, name_domain := NameDomain} = net_kernel:get_state(), net_kernel:connect_node(TestNode), [] = nodes(), [TestNode] = nodes(hidden), MyName = node(), #{started := static, name_type := dynamic, name := MyName, name_domain := NameDomain} = net_kernel:get_state(), check([MyName], rpc:call(TestNode, erlang, nodes, [hidden])), {nodeup, MyName, [{node_type, visible}]} = receive_any(), {nodeup, TestNode, [{node_type, hidden}]} = receive_any(), true = rpc:cast(TestNode, net_kernel, disconnect, [MyName]), We do n't know the order of these nodedown messages . Often nodedown from the connection comes first , but not always ... NodedownMsgsB = lists:sort([{nodedown, TestNode, [{node_type, hidden}]}, {nodedown, MyName, [{node_type, visible}]}]), NodedownMsgB1 = receive_any(), NodedownMsgB2 = receive_any(), NodedownMsgsB = lists:sort([NodedownMsgB1, NodedownMsgB2]), [] = nodes(hidden), nonode@nohost = node(), #{started := static, name_type := dynamic, name := undefined, name_domain := NameDomain} = net_kernel:get_state(), ok. check(X, X) -> ok. setopts(Config) when is_list(Config) -> run_dist_configs(fun setopts/2, Config). setopts(DCfg, _Config) -> register(setopts_regname, self()), [N1,N2,N3,N4,N5] = get_nodenames(5, setopts), {_N1F,Port1} = start_node_unconnected(DCfg, N1, ?MODULE, run_remote_test, ["setopts_do", atom_to_list(node()), "1", "ping"]), 0 = wait_for_port_exit(Port1), {_N2F,Port2} = start_node_unconnected(DCfg, N2, ?MODULE, run_remote_test, ["setopts_do", atom_to_list(node()), "2", "ping"]), 0 = wait_for_port_exit(Port2), {ok, LSock} = gen_tcp:listen(0, [{packet,2}, {active,false}]), {ok, LTcpPort} = inet:port(LSock), {N3F,Port3} = start_node_unconnected(DCfg, N3, ?MODULE, run_remote_test, ["setopts_do", atom_to_list(node()), "1", integer_to_list(LTcpPort)]), wait_and_connect(LSock, N3F, Port3), 0 = wait_for_port_exit(Port3), {N4F,Port4} = start_node_unconnected(DCfg, N4, ?MODULE, run_remote_test, ["setopts_do", atom_to_list(node()), "2", integer_to_list(LTcpPort)]), wait_and_connect(LSock, N4F, Port4), 0 = wait_for_port_exit(Port4), net_kernel : setopts(new , _ ) used to be able to produce a deadlock in net_kernel . / OTP-18198 {N5F,Port5} = start_node_unconnected(DCfg, N5, ?MODULE, run_remote_test, ["setopts_deadlock_test", atom_to_list(node()), integer_to_list(LTcpPort)]), wait_and_connect(LSock, N5F, Port5), repeat(fun () -> receive after 10 -> ok end, erlang:disconnect_node(N5F), WD = spawn_link(fun () -> receive after 2000 -> ok end, exit({net_kernel_probably_deadlocked, N5F}) end), pong = net_adm:ping(N5F), unlink(WD), exit(WD, kill), false = is_process_alive(WD) end, 200), try erpc:call(N5F, erlang, halt, []) catch error:{erpc,noconnection} -> ok end, 0 = wait_for_port_exit(Port5), unregister(setopts_regname), ok. wait_and_connect(LSock, NodeName, NodePort) -> {ok, Sock} = gen_tcp:accept(LSock), {ok, "Connect please"} = gen_tcp:recv(Sock, 0), flush_from_port(NodePort), pong = net_adm:ping(NodeName), gen_tcp:send(Sock, "Connect done"), gen_tcp:close(Sock). flush_from_port(Port) -> flush_from_port(Port, 10). flush_from_port(Port, Timeout) -> receive {Port,{data,String}} -> io:format("~p: ~s\n", [Port, String]), flush_from_port(Port, Timeout) after Timeout -> timeout end. wait_for_port_exit(Port) -> case (receive M -> M end) of {Port,{exit_status,Status}} -> Status; {Port,{data,String}} -> io:format("~p: ~s\n", [Port, String]), wait_for_port_exit(Port) end. run_remote_test([FuncStr, TestNodeStr | Args]) -> Status = try io:format("Node ~p started~n", [node()]), TestNode = list_to_atom(TestNodeStr), io:format("Node ~p spawning function ~p~n", [node(), FuncStr]), {Pid,Ref} = spawn_monitor(?MODULE, list_to_atom(FuncStr), [TestNode, Args]), io:format("Node ~p waiting for function ~p~n", [node(), FuncStr]), receive {'DOWN', Ref, process, Pid, normal} -> 0; Other -> io:format("Node ~p got unexpected msg: ~p\n",[node(), Other]), 1 end catch C:E:S -> io:format("Node ~p got EXCEPTION ~p:~p\nat ~p\n", [node(), C, E, S]), 2 end, io:format("Node ~p doing halt(~p).\n",[node(), Status]), erlang:halt(Status). % Do the actual test on the remote node setopts_do(TestNode, [OptNr, ConnectData]) -> [] = nodes(), {Opt, Val} = opt_from_nr(OptNr), ok = net_kernel:setopts(new, [{Opt, Val}]), [] = nodes(), {error, noconnection} = net_kernel:getopts(TestNode, [Opt]), case ConnectData of "ping" -> % We connect net_adm:ping(TestNode); TcpPort -> % Other connect {ok, Sock} = gen_tcp:connect("localhost", list_to_integer(TcpPort), [{active,false},{packet,2}]), ok = gen_tcp:send(Sock, "Connect please"), {ok, "Connect done"} = gen_tcp:recv(Sock, 0), gen_tcp:close(Sock) end, [TestNode] = nodes(), {ok, [{Opt,Val}]} = net_kernel:getopts(TestNode, [Opt]), {error, noconnection} = net_kernel:getopts('pixie@fairyland', [Opt]), NewVal = change_val(Val), ok = net_kernel:setopts(TestNode, [{Opt, NewVal}]), {ok, [{Opt,NewVal}]} = net_kernel:getopts(TestNode, [Opt]), ok = net_kernel:setopts(TestNode, [{Opt, Val}]), {ok, [{Opt,Val}]} = net_kernel:getopts(TestNode, [Opt]), ok. setopts_deadlock_test(_TestNode, [TcpPort]) -> {ok, Sock} = gen_tcp:connect("localhost", list_to_integer(TcpPort), [{active,false},{packet,2}]), ok = gen_tcp:send(Sock, "Connect please"), {ok, "Connect done"} = gen_tcp:recv(Sock, 0), gen_tcp:close(Sock), setopts_new_loop(). setopts_new_loop() -> ok = net_kernel:setopts(new, [{nodelay, true}]), receive after 10 -> ok end, setopts_new_loop(). opt_from_nr("1") -> {nodelay, true}; opt_from_nr("2") -> {nodelay, false}. change_val(true) -> false; change_val(false) -> true. start_node_unconnected(DCfg, Name, Mod, Func, Args) -> start_node_unconnected(DCfg, Name, erlang:get_cookie(), Mod, Func, Args). start_node_unconnected(DCfg, Name, Cookie, Mod, Func, Args) -> FullName = full_node_name(Name), CmdLine = mk_node_cmdline(DCfg, Name, Cookie, Mod, Func, Args), io:format("Starting node ~p: ~s~n", [FullName, CmdLine]), case open_port({spawn, CmdLine}, [exit_status]) of Port when is_port(Port) -> {FullName, Port}; Error -> exit({failed_to_start_node, FullName, Error}) end. full_node_name(PreName) when is_atom(PreName) -> full_node_name(atom_to_list(PreName)); full_node_name(PreNameL) when is_list(PreNameL) -> HostSuffix = lists:dropwhile(fun ($@) -> false; (_) -> true end, atom_to_list(node())), list_to_atom(PreNameL ++ HostSuffix). mk_node_cmdline(DCfg, Name, Cookie, Mod, Func, Args) -> Static = "-noinput", Pa = filename:dirname(code:which(?MODULE)), Prog = case catch init:get_argument(progname) of {ok,[[P]]} -> P; _ -> exit(no_progname_argument_found) end, NameSw = case net_kernel:longnames() of false -> "-sname "; true -> "-name "; _ -> exit(not_distributed_node) end, {ok, Pwd} = file:get_cwd(), NameStr = atom_to_list(Name), Prog ++ " " ++ Static ++ " " ++ NameSw ++ " " ++ NameStr ++ " " ++ DCfg ++ " -pa " ++ Pa ++ " -env ERL_CRASH_DUMP " ++ Pwd ++ "/erl_crash_dump." ++ NameStr ++ " -setcookie " ++ atom_to_list(Cookie) ++ " -run " ++ atom_to_list(Mod) ++ " " ++ atom_to_list(Func) ++ " " ++ string:join(Args, " "). %% OTP-4255. tick_change(Config) when is_list(Config) -> run_dist_configs(fun tick_change/2, Config). tick_change(DCfg, _Config) -> %% %% This test case use disabled "connect all" so that %% global wont interfere... %% [BN, CN] = get_nodenames(2, tick_change), DefaultTT = net_kernel:get_net_ticktime(), unchanged = net_kernel:set_net_ticktime(DefaultTT, 60), case DefaultTT of I when is_integer(I) -> ok; _ -> ct:fail(DefaultTT) end, %% In case other nodes are connected case nodes(connected) of [] -> net_kernel:set_net_ticktime(10, 0); _ -> rpc:multicall(nodes([this, connected]), net_kernel, set_net_ticktime, [10, 5]) end, wait_until(fun () -> 10 == net_kernel:get_net_ticktime() end), {ok, B} = start_node(DCfg, BN, "-kernel net_ticktime 10 -connect_all false"), {ok, C} = start_node(DCfg, CN, "-kernel net_ticktime 10 -hidden"), OTE = process_flag(trap_exit, true), case catch begin run_tick_change_test(DCfg, B, C, 10, 1), run_tick_change_test(DCfg, B, C, 1, 10) end of {'EXIT', Reason} -> stop_node(B), stop_node(C), %% In case other nodes are connected case nodes(connected) of [] -> net_kernel:set_net_ticktime(DefaultTT, 0); _ -> rpc:multicall(nodes([this, connected]), net_kernel, set_net_ticktime, [DefaultTT, 10]) end, wait_until(fun () -> DefaultTT == net_kernel:get_net_ticktime() end), process_flag(trap_exit, OTE), ct:fail(Reason); _ -> ok end, process_flag(trap_exit, OTE), stop_node(B), stop_node(C), %% In case other nodes are connected case nodes(connected) of [] -> net_kernel:set_net_ticktime(DefaultTT, 0); _ -> rpc:multicall(nodes([this, connected]), net_kernel, set_net_ticktime, [DefaultTT, 5]) end, wait_until(fun () -> DefaultTT == net_kernel:get_net_ticktime() end), ok. wait_for_nodedowns(Tester, Ref) -> receive {nodedown, Node} -> io:format("~p~n", [{node(), {nodedown, Node}}]), Tester ! {Ref, {node(), {nodedown, Node}}} end, wait_for_nodedowns(Tester, Ref). run_tick_change_test(DCfg, B, C, PrevTT, TT) -> [DN, EN] = get_nodenames(2, tick_change), Tester = self(), Ref = make_ref(), MonitorNodes = fun (Nodes) -> lists:foreach( fun (N) -> monitor_node(N,true) end, Nodes), wait_for_nodedowns(Tester, Ref) end, {ok, D} = start_node(DCfg, DN, "-connect_all false -kernel net_ticktime " ++ integer_to_list(PrevTT)), NMA = spawn_link(fun () -> MonitorNodes([B, C, D]) end), NMB = spawn_link(B, fun () -> MonitorNodes([node(), C, D]) end), NMC = spawn_link(C, fun () -> MonitorNodes([node(), B, D]) end), MaxTT = case PrevTT > TT of true -> PrevTT; false -> TT end, CheckResult = make_ref(), spawn_link(fun () -> receive after (25 + MaxTT)*1000 -> Tester ! CheckResult end end), %% In case other nodes than these are connected case nodes(connected) -- [B, C, D] of [] -> ok; OtherNodes -> rpc:multicall(OtherNodes, net_kernel, set_net_ticktime, [TT, 20]) end, change_initiated = net_kernel:set_net_ticktime(TT,20), {ongoing_change_to,_} = net_kernel:set_net_ticktime(TT,20), sleep(3), change_initiated = rpc:call(B,net_kernel,set_net_ticktime,[TT,15]), sleep(7), change_initiated = rpc:call(C,net_kernel,set_net_ticktime,[TT,10]), {ok, E} = start_node(DCfg, EN, "-connect_all false -kernel net_ticktime " ++ integer_to_list(TT)), NME = spawn_link(E, fun () -> MonitorNodes([node(), B, C, D]) end), NMA2 = spawn_link(fun () -> MonitorNodes([E]) end), NMB2 = spawn_link(B, fun () -> MonitorNodes([E]) end), NMC2 = spawn_link(C, fun () -> MonitorNodes([E]) end), receive CheckResult -> ok end, unlink(NMA), exit(NMA, kill), unlink(NMB), exit(NMB, kill), unlink(NMC), exit(NMC, kill), unlink(NME), exit(NME, kill), unlink(NMA2), exit(NMA2, kill), unlink(NMB2), exit(NMB2, kill), unlink(NMC2), exit(NMC2, kill), %% The node not changing ticktime should have been disconnected from the %% other nodes receive {Ref, {Node, {nodedown, D}}} when Node == node() -> ok after 0 -> exit({?LINE, no_nodedown}) end, receive {Ref, {B, {nodedown, D}}} -> ok after 0 -> exit({?LINE, no_nodedown}) end, receive {Ref, {C, {nodedown, D}}} -> ok after 0 -> exit({?LINE, no_nodedown}) end, receive {Ref, {E, {nodedown, D}}} -> ok after 0 -> exit({?LINE, no_nodedown}) end, %% No other connections should have been broken receive {Ref, Reason} -> stop_node(E), exit({?LINE, Reason}); {'EXIT', Pid, Reason} when Pid == NMA; Pid == NMB; Pid == NMC; Pid == NME; Pid == NMA2; Pid == NMB2; Pid == NMC2 -> stop_node(E), exit({?LINE, {node(Pid), Reason}}) after 0 -> TT = net_kernel:get_net_ticktime(), TT = rpc:call(B, net_kernel, get_net_ticktime, []), TT = rpc:call(C, net_kernel, get_net_ticktime, []), TT = rpc:call(E, net_kernel, get_net_ticktime, []), stop_node(E), ok end. %% %% Basic tests of hidden node. %% %% Basic test of hidden node. hidden_node(Config) when is_list(Config) -> run_dist_configs(fun hidden_node/2, Config). hidden_node(DCfg, Config) -> hidden_node(DCfg, "-hidden", Config), hidden_node(DCfg, "-hidden -hidden", Config), hidden_node(DCfg, "-hidden true -hidden true", Config), ok. hidden_node(DCfg, HArgs, _Config) -> ct:pal("--- Hidden argument(s): ~s~n", [HArgs]), {ok, V} = start_node(DCfg, visible_node), VMN = start_monitor_nodes_proc(V), {ok, H} = start_node(DCfg, hidden_node, HArgs), Connect visible_node - > hidden_node connect_nodes(V, H), test_nodes(V, H), stop_node(H), sleep(5), check_monitor_nodes_res(VMN, H), stop_node(V), {ok, H} = start_node(DCfg, hidden_node, HArgs), HMN = start_monitor_nodes_proc(H), {ok, V} = start_node(DCfg, visible_node), Connect hidden_node - > visible_node connect_nodes(H, V), test_nodes(V, H), stop_node(V), sleep(5), check_monitor_nodes_res(HMN, V), stop_node(H), ok. connect_nodes(A, B) -> %% Check that they haven't already connected. false = lists:member(A, rpc:call(B, erlang, nodes, [connected])), false = lists:member(B, rpc:call(A, erlang, nodes, [connected])), Connect them . pong = rpc:call(A, net_adm, ping, [B]). test_nodes(V, H) -> %% No nodes should be visible on hidden_node [] = rpc:call(H, erlang, nodes, []), %% visible_node should be hidden on hidden_node true = lists:member(V, rpc:call(H, erlang, nodes, [hidden])), %% hidden_node node shouldn't be visible on visible_node false = lists:member(H, rpc:call(V, erlang, nodes, [])), %% hidden_node should be hidden on visible_node true = lists:member(H, rpc:call(V, erlang, nodes, [hidden])). mn_loop(MNs) -> receive {nodeup, N} -> mn_loop([{nodeup, N}|MNs]); {nodedown, N} -> mn_loop([{nodedown, N}|MNs]); {monitor_nodes_result, Ref, From} -> From ! {Ref, MNs}; _ -> mn_loop(MNs) end. start_monitor_nodes_proc(Node) -> Ref = make_ref(), Starter = self(), Pid = spawn(Node, fun() -> net_kernel:monitor_nodes(true), Starter ! Ref, mn_loop([]) end), receive Ref -> ok end, Pid. check_monitor_nodes_res(Pid, Node) -> Ref = make_ref(), Pid ! {monitor_nodes_result, Ref, self()}, receive {Ref, MNs} -> false = lists:keysearch(Node, 2, MNs) end. %% Check the kernel inet_dist_{listen,connect}_options options. inet_dist_options_options(Config) when is_list(Config) -> Prio = 1, case gen_udp:open(0, [{priority,Prio}]) of {ok,Socket} -> case inet:getopts(Socket, [priority]) of {ok,[{priority,Prio}]} -> ok = gen_udp:close(Socket), do_inet_dist_options_options(Prio); _ -> ok = gen_udp:close(Socket), {skip, "Can not set priority "++integer_to_list(Prio)++ " on socket"} end; {error,_} -> {skip, "Can not set priority on socket"} end. do_inet_dist_options_options(Prio) -> PriorityString0 = "[{priority,"++integer_to_list(Prio)++"}]", PriorityString = case os:cmd("echo [{a,1}]") of "[{a,1}]"++_ -> PriorityString0; _ -> %% Some shells need quoting of [{}] "'"++PriorityString0++"'" end, InetDistOptions = "-hidden " "-kernel inet_dist_connect_options "++PriorityString++" " "-kernel inet_dist_listen_options "++PriorityString, {ok,Node1} = start_node("", inet_dist_options_1, InetDistOptions), {ok,Node2} = start_node("", inet_dist_options_2, InetDistOptions), %% pong = rpc:call(Node1, net_adm, ping, [Node2]), PrioritiesNode1 = rpc:call(Node1, ?MODULE, get_socket_priorities, []), PrioritiesNode2 = rpc:call(Node2, ?MODULE, get_socket_priorities, []), io:format("PrioritiesNode1 = ~p", [PrioritiesNode1]), io:format("PrioritiesNode2 = ~p", [PrioritiesNode2]), Elevated = [P || P <- PrioritiesNode1, P =:= Prio], Elevated = [P || P <- PrioritiesNode2, P =:= Prio], [_|_] = Elevated, %% stop_node(Node2), stop_node(Node1), ok. get_socket_priorities() -> [Priority || {ok,[{priority,Priority}]} <- [inet:getopts(Port, [priority]) || Port <- erlang:ports(), element(2, erlang:port_info(Port, name)) =:= "tcp_inet"]]. %% check net_ticker_spawn_options net_ticker_spawn_options(Config) when is_list(Config) -> run_dist_configs(fun net_ticker_spawn_options/2, Config). net_ticker_spawn_options(DCfg, Config) when is_list(Config) -> FullsweepString0 = "[{fullsweep_after,0}]", FullsweepString = case os:cmd("echo [{a,1}]") of "[{a,1}]"++_ -> FullsweepString0; _ -> %% Some shells need quoting of [{}] "'"++FullsweepString0++"'" end, InetDistOptions = "-hidden " "-kernel net_ticker_spawn_options "++FullsweepString, {ok,Node1} = start_node(DCfg, net_ticker_spawn_options_1, InetDistOptions), {ok,Node2} = start_node(DCfg, net_ticker_spawn_options_2, InetDistOptions), %% pong = erpc:call(Node1, net_adm, ping, [Node2]), FullsweepOptionNode1 = erpc:call(Node1, ?MODULE, get_net_ticker_fullsweep_option, [Node2]), FullsweepOptionNode2 = erpc:call(Node2, ?MODULE, get_net_ticker_fullsweep_option, [Node1]), io:format("FullsweepOptionNode1 = ~p", [FullsweepOptionNode1]), io:format("FullsweepOptionNode2 = ~p", [FullsweepOptionNode2]), 0 = FullsweepOptionNode1, 0 = FullsweepOptionNode2, %% stop_node(Node2), stop_node(Node1), ok. get_net_ticker_fullsweep_option(Node) -> Links = case proplists:get_value(Node, erlang:system_info(dist_ctrl)) of DistCtrl when is_port(DistCtrl) -> {links, Ls} = erlang:port_info(DistCtrl, links), Ls; DistCtrl when is_pid(DistCtrl) -> {links, Ls} = process_info(DistCtrl, links), Ls end, Ticker = try lists:foreach( fun (Pid) when is_pid(Pid) -> {current_stacktrace, Stk} = process_info(Pid, current_stacktrace), lists:foreach( fun ({dist_util, con_loop, _, _}) -> throw(Pid); (_) -> ok end, Stk); (_) -> ok end, Links), error(no_ticker_found) catch throw:Pid when is_pid(Pid) -> Pid end, {garbage_collection, GCOpts} = erlang:process_info(Ticker, garbage_collection), proplists:get_value(fullsweep_after, GCOpts). %% : monitor_nodes_nodedown_reason %% monitor_nodes_nodedown_reason(Config) when is_list(Config) -> run_dist_configs(fun monitor_nodes_nodedown_reason/2, Config). monitor_nodes_nodedown_reason(DCfg, _Config) -> MonNodeState = monitor_node_state(), ok = net_kernel:monitor_nodes(true), ok = net_kernel:monitor_nodes(true, [nodedown_reason]), Names = get_numbered_nodenames(5, node), [NN1, NN2, NN3, NN4, NN5] = Names, {ok, N1} = start_node(DCfg, NN1, "-connect_all false"), {ok, N2} = start_node(DCfg, NN2, "-connect_all false"), {ok, N3} = start_node(DCfg, NN3, "-connect_all false"), {ok, N4} = start_node(DCfg, NN4, "-hidden"), receive {nodeup, N1} -> ok end, receive {nodeup, N2} -> ok end, receive {nodeup, N3} -> ok end, receive {nodeup, N1, []} -> ok end, receive {nodeup, N2, []} -> ok end, receive {nodeup, N3, []} -> ok end, stop_node(N1), stop_node(N4), true = net_kernel:disconnect(N2), TickTime = net_kernel:get_net_ticktime(), SleepTime = TickTime + (TickTime div 2), spawn(N3, fun () -> block_emu(SleepTime*1000), halt() end), receive {nodedown, N1} -> ok end, receive {nodedown, N2} -> ok end, receive {nodedown, N3} -> ok end, receive {nodedown, N1, [{nodedown_reason, R1}]} -> connection_closed = R1 end, receive {nodedown, N2, [{nodedown_reason, R2}]} -> disconnect = R2 end, receive {nodedown, N3, [{nodedown_reason, R3}]} -> net_tick_timeout = R3 end, ok = net_kernel:monitor_nodes(false, [nodedown_reason]), {ok, N5} = start_node(DCfg, NN5), stop_node(N5), receive {nodeup, N5} -> ok end, receive {nodedown, N5} -> ok end, print_my_messages(), ok = check_no_nodedown_nodeup(1000), ok = net_kernel:monitor_nodes(false), MonNodeState = monitor_node_state(), ok. monitor_nodes_complex_nodedown_reason(Config) when is_list(Config) -> run_dist_configs(fun monitor_nodes_complex_nodedown_reason/2, Config). monitor_nodes_complex_nodedown_reason(DCfg, _Config) -> MonNodeState = monitor_node_state(), Me = self(), ok = net_kernel:monitor_nodes(true, [nodedown_reason]), [Name] = get_nodenames(1, monitor_nodes_complex_nodedown_reason), {ok, Node} = start_node(DCfg, Name, ""), Pid = spawn(Node, fun() -> Me ! {stuff, self(), [make_ref(), {processes(), erlang:ports()}]} end), receive {nodeup, Node, []} -> ok end, {ok, NodeInfo} = net_kernel:node_info(Node), {value,{owner, Owner}} = lists:keysearch(owner, 1, NodeInfo), ComplexTerm = receive {stuff, Pid, _} = Msg -> {Msg, term_to_binary(Msg)} end, exit(Owner, ComplexTerm), receive {nodedown, Node, [{nodedown_reason, NodeDownReason}]} -> ok end, %% If the complex nodedown_reason messed something up garbage collections %% are likely to dump core garbage_collect(), garbage_collect(), garbage_collect(), ComplexTerm = NodeDownReason, ok = net_kernel:monitor_nodes(false, [nodedown_reason]), no_msgs(), MonNodeState = monitor_node_state(), ok. %% : %% monitor_nodes_node_type %% monitor_nodes_node_type(Config) when is_list(Config) -> run_dist_configs(fun monitor_nodes_node_type/2, Config). monitor_nodes_node_type(DCfg, _Config) -> MonNodeState = monitor_node_state(), ok = net_kernel:monitor_nodes(true), ok = net_kernel:monitor_nodes(true, [{node_type, all}]), Names = get_numbered_nodenames(9, node), [NN1, NN2, NN3, NN4, NN5, NN6, NN7, NN8, NN9] = Names, {ok, N1} = start_node(DCfg, NN1), {ok, N2} = start_node(DCfg, NN2), {ok, N3} = start_node(DCfg, NN3, "-hidden"), {ok, N4} = start_node(DCfg, NN4, "-hidden"), receive {nodeup, N1} -> ok end, receive {nodeup, N2} -> ok end, receive {nodeup, N1, [{node_type, visible}]} -> ok end, receive {nodeup, N2, [{node_type, visible}]} -> ok end, receive {nodeup, N3, [{node_type, hidden}]} -> ok end, receive {nodeup, N4, [{node_type, hidden}]} -> ok end, stop_node(N1), stop_node(N2), stop_node(N3), stop_node(N4), receive {nodedown, N1} -> ok end, receive {nodedown, N2} -> ok end, receive {nodedown, N1, [{node_type, visible}]} -> ok end, receive {nodedown, N2, [{node_type, visible}]} -> ok end, receive {nodedown, N3, [{node_type, hidden}]} -> ok end, receive {nodedown, N4, [{node_type, hidden}]} -> ok end, ok = net_kernel:monitor_nodes(false, [{node_type, all}]), {ok, N5} = start_node(DCfg, NN5), receive {nodeup, N5} -> ok end, stop_node(N5), receive {nodedown, N5} -> ok end, ok = net_kernel:monitor_nodes(true, [{node_type, hidden}]), {ok, N6} = start_node(DCfg, NN6), {ok, N7} = start_node(DCfg, NN7, "-hidden"), receive {nodeup, N6} -> ok end, receive {nodeup, N7, [{node_type, hidden}]} -> ok end, stop_node(N6), stop_node(N7), receive {nodedown, N6} -> ok end, receive {nodedown, N7, [{node_type, hidden}]} -> ok end, ok = net_kernel:monitor_nodes(true, [{node_type, visible}]), ok = net_kernel:monitor_nodes(false, [{node_type, hidden}]), ok = net_kernel:monitor_nodes(false), {ok, N8} = start_node(DCfg, NN8), {ok, N9} = start_node(DCfg, NN9, "-hidden"), receive {nodeup, N8, [{node_type, visible}]} -> ok end, stop_node(N8), stop_node(N9), receive {nodedown, N8, [{node_type, visible}]} -> ok end, print_my_messages(), ok = check_no_nodedown_nodeup(1000), ok = net_kernel:monitor_nodes(false, [{node_type, visible}]), MonNodeState = monitor_node_state(), ok. %% : %% monitor_nodes %% monitor_nodes_misc(Config) when is_list(Config) -> run_dist_configs(fun monitor_nodes_misc/2, Config). monitor_nodes_misc(DCfg, _Config) -> MonNodeState = monitor_node_state(), ok = net_kernel:monitor_nodes(true), ok = net_kernel:monitor_nodes(true, [{node_type, all}, nodedown_reason]), ok = net_kernel:monitor_nodes(true, [nodedown_reason, {node_type, all}, connection_id]), ok = net_kernel:monitor_nodes(true, #{node_type => all, nodedown_reason => true}), ok = net_kernel:monitor_nodes(true, #{node_type => all, nodedown_reason => true, connection_id => true}), Names = get_numbered_nodenames(3, node), [NN1, NN2, NN3] = Names, {ok, N1} = start_node(DCfg, NN1), {ok, N2} = start_node(DCfg, NN2, "-hidden"), receive {nodeup, N1} -> ok end, receive {nodeup, N1, #{node_type := visible}} -> ok end, receive {nodeup, N2, #{node_type := hidden}} -> ok end, receive {nodeup, N1, [{node_type, visible}]} -> ok end, receive {nodeup, N2, [{node_type, hidden}]} -> ok end, NodesInfo = erlang:nodes(connected, #{connection_id => true}), {N1, #{connection_id := N1CId}} = lists:keyfind(N1, 1, NodesInfo), {N2, #{connection_id := N2CId}} = lists:keyfind(N2, 1, NodesInfo), ct:pal("N1: ~p ~p~n", [N1, N1CId]), ct:pal("N2: ~p ~p~n", [N2, N2CId]), receive {nodeup, N1, #{node_type := visible, connection_id := N1CId}} -> ok end, receive {nodeup, N2, #{node_type := hidden, connection_id := N2CId}} -> ok end, N1UpInfoSorted = lists:sort([{node_type, visible},{connection_id, N1CId}]), N2UpInfoSorted = lists:sort([{node_type, hidden},{connection_id, N2CId}]), receive {nodeup, N1, UpN1Info} -> N1UpInfoSorted = lists:sort(UpN1Info) end, receive {nodeup, N2, UpN2Info} -> N2UpInfoSorted = lists:sort(UpN2Info) end, stop_node(N1), stop_node(N2), receive {nodedown, N1} -> ok end, receive {nodedown, N1, #{node_type := visible, nodedown_reason := connection_closed}} -> ok end, receive {nodedown, N1, #{node_type := visible, nodedown_reason := connection_closed, connection_id := N1CId}} -> ok end, receive {nodedown, N2, #{node_type := hidden, nodedown_reason := connection_closed}} -> ok end, receive {nodedown, N2, #{node_type := hidden, nodedown_reason := connection_closed, connection_id := N2CId}} -> ok end, N1ADownInfoSorted = lists:sort([{node_type, visible}, {nodedown_reason, connection_closed}]), N1BDownInfoSorted = lists:sort([{node_type, visible}, {nodedown_reason, connection_closed}, {connection_id, N1CId}]), N2ADownInfoSorted = lists:sort([{node_type, hidden}, {nodedown_reason, connection_closed}]), N2BDownInfoSorted = lists:sort([{node_type, hidden}, {nodedown_reason, connection_closed}, {connection_id, N2CId}]), receive {nodedown, N1, N1Info1} -> case lists:sort(N1Info1) of N1ADownInfoSorted -> receive {nodedown, N1, N1Info2} -> N1BDownInfoSorted = lists:sort(N1Info2) end; N1BDownInfoSorted -> receive {nodedown, N1, N1Info2} -> N1ADownInfoSorted = lists:sort(N1Info2) end end end, receive {nodedown, N2, N2Info1} -> case lists:sort(N2Info1) of N2ADownInfoSorted -> receive {nodedown, N2, N2Info2} -> N2BDownInfoSorted = lists:sort(N2Info2) end; N2BDownInfoSorted -> receive {nodedown, N2, N2Info2} -> N2ADownInfoSorted = lists:sort(N2Info2) end end end, ok = net_kernel:monitor_nodes(false, [{node_type, all}, nodedown_reason]), ok = net_kernel:monitor_nodes(false, [nodedown_reason, {node_type, all}, connection_id]), ok = net_kernel:monitor_nodes(false, #{node_type => all, nodedown_reason => true}), ok = net_kernel:monitor_nodes(false, #{node_type => all, nodedown_reason => true, connection_id => true}), {ok, N3} = start_node(DCfg, NN3), receive {nodeup, N3} -> ok end, stop_node(N3), receive {nodedown, N3} -> ok end, print_my_messages(), ok = check_no_nodedown_nodeup(1000), ok = net_kernel:monitor_nodes(false), MonNodeState = monitor_node_state(), ok. %% Tests that {nodeup, Node} messages are received before messages from and that { nodedown , Node } messages are received after messages from Node . monitor_nodes_otp_6481(Config) when is_list(Config) -> run_dist_configs(fun monitor_nodes_otp_6481/2, Config). monitor_nodes_otp_6481(DCfg, Config) -> io:format("Testing nodedown...~n"), monitor_nodes_otp_6481_test(DCfg, Config, nodedown), io:format("ok~n"), io:format("Testing nodeup...~n"), monitor_nodes_otp_6481_test(DCfg, Config, nodeup), io:format("ok~n"), ok. monitor_nodes_otp_6481_test(DCfg, Config, TestType) when is_list(Config) -> MonNodeState = monitor_node_state(), NodeMsg = make_ref(), Me = self(), [Name] = get_nodenames(1, monitor_nodes_otp_6481), case TestType of nodedown -> ok = net_kernel:monitor_nodes(true); nodeup -> ok end, Seq = lists:seq(1,10000), MN = spawn_link( fun () -> lists:foreach( fun (_) -> ok = net_kernel:monitor_nodes(true) end, Seq), Me ! {mon_set, self()}, receive after infinity -> ok end end), receive {mon_set, MN} -> ok end, case TestType of nodedown -> ok; nodeup -> ok = net_kernel:monitor_nodes(true) end, %% Whitebox: nodedown test : Since this process was the first one monitoring nodes this process will be the first one notified on nodedown . %% nodeup test: Since this process was the last one monitoring %% nodes this process will be the last one notified %% on nodeup %% Verify the monitor_nodes order expected TestMonNodeState = monitor_node_state(), %% io:format("~p~n", [TestMonNodeState]), TestMonNodeState = case TestType of nodedown -> []; nodeup -> [{self(), []}] end ++ lists:map(fun (_) -> {MN, []} end, Seq) ++ case TestType of nodedown -> [{self(), []}]; nodeup -> [] end ++ MonNodeState, {ok, Node} = start_node(DCfg, Name, "", this), receive {nodeup, Node} -> ok end, RemotePid = spawn(Node, fun () -> receive after 1500 -> ok end, infinite loop of msgs %% we want an endless stream of messages and the kill %% the node mercilessly. We then want to ensure that the nodedown message arrives %% last ... without garbage after it. _ = spawn(fun() -> node_loop_send(Me, NodeMsg, 1) end), receive {Me, kill_it} -> ok end, halt() end), net_kernel:disconnect(Node), receive {nodedown, Node} -> ok end, Verify that ' { nodeup , } ' comes before ' { NodeMsg , 1 } ' ( the message %% bringing up the connection). {nodeup, Node} = receive Msg1 -> Msg1 end, {NodeMsg, N} = receive Msg2 -> Msg2 end, %% msg stream has begun, kill the node RemotePid ! {self(), kill_it}, Verify that ' { nodedown , Node } ' comes after the last ' { NodeMsg , N } ' %% message. {nodedown, Node} = flush_node_msgs(NodeMsg, N+1), no_msgs(500), Mon = erlang:monitor(process, MN), unlink(MN), exit(MN, bang), receive {'DOWN', Mon, process, MN, bang} -> ok end, ok = net_kernel:monitor_nodes(false), MonNodeState = monitor_node_state(), ok. flush_node_msgs(NodeMsg, No) -> case receive Msg -> Msg end of {NodeMsg, N} when N >= No -> flush_node_msgs(NodeMsg, N+1); OtherMsg -> OtherMsg end. node_loop_send(Pid, Msg, No) -> Pid ! {Msg, No}, node_loop_send(Pid, Msg, No + 1). monitor_nodes_errors(Config) when is_list(Config) -> MonNodeState = monitor_node_state(), error = net_kernel:monitor_nodes(asdf), {error, {unknown_options, [gurka]}} = net_kernel:monitor_nodes(true, [gurka]), {error, {unknown_options, #{gurka := true}}} = net_kernel:monitor_nodes(true, #{gurka => true}), {error, {invalid_options, gurka}} = net_kernel:monitor_nodes(true, gurka), {error, {option_value_mismatch, [{node_type,visible}, {node_type,hidden}]}} = net_kernel:monitor_nodes(true, [{node_type,hidden}, {node_type,visible}]), {error, {option_value_mismatch, [{node_type,visible}, {node_type,all}]}} = net_kernel:monitor_nodes(true, [{node_type,all}, {node_type,visible}]), {error, {bad_option_value, {node_type, blaha}}} = net_kernel:monitor_nodes(true, [{node_type, blaha}]), {error, {bad_option_value, #{node_type := blaha}}} = net_kernel:monitor_nodes(true, #{node_type => blaha}), MonNodeState = monitor_node_state(), ok. monitor_nodes_combinations(Config) when is_list(Config) -> run_dist_configs(fun monitor_nodes_combinations/2, Config). monitor_nodes_combinations(DCfg, _Config) -> MonNodeState = monitor_node_state(), monitor_nodes_all_comb(true), [VisibleName, HiddenName] = get_nodenames(2, monitor_nodes_combinations), {ok, Visible} = start_node(DCfg, VisibleName, ""), receive_all_comb_nodeup_msgs(visible, Visible), no_msgs(), stop_node(Visible), receive_all_comb_nodedown_msgs(visible, Visible, connection_closed), no_msgs(), {ok, Hidden} = start_node(DCfg, HiddenName, "-hidden"), receive_all_comb_nodeup_msgs(hidden, Hidden), no_msgs(), stop_node(Hidden), receive_all_comb_nodedown_msgs(hidden, Hidden, connection_closed), no_msgs(), monitor_nodes_all_comb(false), MonNodeState = monitor_node_state(), no_msgs(), ok. monitor_nodes_all_comb(Flag) -> ok = net_kernel:monitor_nodes(Flag), ok = net_kernel:monitor_nodes(Flag, [nodedown_reason]), ok = net_kernel:monitor_nodes(Flag, [{node_type, hidden}]), ok = net_kernel:monitor_nodes(Flag, [{node_type, visible}]), ok = net_kernel:monitor_nodes(Flag, [{node_type, all}]), ok = net_kernel:monitor_nodes(Flag, [nodedown_reason, {node_type, hidden}]), ok = net_kernel:monitor_nodes(Flag, [nodedown_reason, {node_type, visible}]), ok = net_kernel:monitor_nodes(Flag, [nodedown_reason, {node_type, all}]), There currently are 8 different combinations 8. receive_all_comb_nodeup_msgs(visible, Node) -> io:format("Receive nodeup visible...~n"), Exp = [{nodeup, Node}, {nodeup, Node, []}] ++ mk_exp_mn_all_comb_nodeup_msgs_common(visible, Node), receive_mn_msgs(Exp), io:format("ok~n"), ok; receive_all_comb_nodeup_msgs(hidden, Node) -> io:format("Receive nodeup hidden...~n"), Exp = mk_exp_mn_all_comb_nodeup_msgs_common(hidden, Node), receive_mn_msgs(Exp), io:format("ok~n"), ok. mk_exp_mn_all_comb_nodeup_msgs_common(Type, Node) -> InfoNt = [{node_type, Type}], [{nodeup, Node, InfoNt}, {nodeup, Node, InfoNt}, {nodeup, Node, InfoNt}, {nodeup, Node, InfoNt}]. receive_all_comb_nodedown_msgs(visible, Node, Reason) -> io:format("Receive nodedown visible...~n"), Exp = [{nodedown, Node}, {nodedown, Node, [{nodedown_reason, Reason}]}] ++ mk_exp_mn_all_comb_nodedown_msgs_common(visible, Node, Reason), receive_mn_msgs(Exp), io:format("ok~n"), ok; receive_all_comb_nodedown_msgs(hidden, Node, Reason) -> io:format("Receive nodedown hidden...~n"), Exp = mk_exp_mn_all_comb_nodedown_msgs_common(hidden, Node, Reason), receive_mn_msgs(Exp), io:format("ok~n"), ok. mk_exp_mn_all_comb_nodedown_msgs_common(Type, Node, Reason) -> InfoNt = [{node_type, Type}], InfoNdrNt = lists:sort([{nodedown_reason, Reason}]++InfoNt), [{nodedown, Node, InfoNt}, {nodedown, Node, InfoNt}, {nodedown, Node, InfoNdrNt}, {nodedown, Node, InfoNdrNt}]. receive_mn_msgs([]) -> ok; receive_mn_msgs(Msgs) -> io:format("Expecting msgs: ~p~n", [Msgs]), receive {_Dir, _Node} = Msg -> io:format("received ~p~n", [Msg]), case lists:member(Msg, Msgs) of true -> receive_mn_msgs(lists:delete(Msg, Msgs)); false -> ct:fail({unexpected_message, Msg, expected_messages, Msgs}) end; {Dir, Node, Info} -> Msg = {Dir, Node, lists:sort(Info)}, io:format("received ~p~n", [Msg]), case lists:member(Msg, Msgs) of true -> receive_mn_msgs(lists:delete(Msg, Msgs)); false -> ct:fail({unexpected_message, Msg, expected_messages, Msgs}) end; Msg -> io:format("received ~p~n", [Msg]), ct:fail({unexpected_message, Msg, expected_messages, Msgs}) end. monitor_nodes_cleanup(Config) when is_list(Config) -> MonNodeState = monitor_node_state(), Me = self(), No = monitor_nodes_all_comb(true), Inf = spawn(fun () -> monitor_nodes_all_comb(true), Me ! {mons_set, self()}, receive after infinity -> ok end end), TO = spawn(fun () -> monitor_nodes_all_comb(true), Me ! {mons_set, self()}, receive after 500 -> ok end end), receive {mons_set, Inf} -> ok end, receive {mons_set, TO} -> ok end, MNLen = length(MonNodeState) + No*3, MNLen = length(monitor_node_state()), MonInf = erlang:monitor(process, Inf), MonTO = erlang:monitor(process, TO), exit(Inf, bang), No = monitor_nodes_all_comb(false), receive {'DOWN', MonInf, process, Inf, bang} -> ok end, receive {'DOWN', MonTO, process, TO, normal} -> ok end, MonNodeState = monitor_node_state(), no_msgs(), ok. monitor_nodes_many(Config) when is_list(Config) -> run_dist_configs(fun monitor_nodes_many/2, Config). monitor_nodes_many(DCfg, _Config) -> MonNodeState = monitor_node_state(), [Name] = get_nodenames(1, monitor_nodes_many), We want to perform more than 2 ^ 16 net_kernel : monitor_nodes %% since this will wrap an internal counter No = (1 bsl 16) + 17, repeat(fun () -> ok = net_kernel:monitor_nodes(true) end, No), No = length(monitor_node_state()) - length(MonNodeState), {ok, Node} = start_node(DCfg, Name), repeat(fun () -> receive {nodeup, Node} -> ok end end, No), stop_node(Node), repeat(fun () -> receive {nodedown, Node} -> ok end end, No), ok = net_kernel:monitor_nodes(false), no_msgs(10), MonNodeState = monitor_node_state(), ok. Test order of messages nodedown and nodeup . monitor_nodes_down_up(Config) when is_list(Config) -> {ok, Peer, Node} = ?CT_PEER(#{connection => 0}), true = net_kernel:connect_node(Node), monitor_nodes_yoyo(Node), peer:stop(Peer). monitor_nodes_yoyo(A) -> net_kernel:monitor_nodes(true), Papa = self(), Spawn lots of processes doing one erlang : monitor_node(A , true ) each %% just to get lots of other monitors to fire when connection goes down %% and thereby give time for {nodeup,A} to race before {nodedown,A}. NodeMonCnt = 10000, NodeMons = [my_spawn_opt(fun F() -> monitor_node = receive_any(), monitor_node(A, true), Papa ! ready, {nodedown, A} = receive_any(), F() end, [link, monitor, {priority, low}]) || _ <- lists:seq(1, NodeMonCnt)], %% Spawn message spamming process to trigger new connection setups %% as quick as possible. Spammer = my_spawn_opt(fun F() -> {dummy, A} ! trigger_auto_connect, F() end, [link, monitor]), %% Now bring connection down and verify we get {nodedown,A} before {nodeup,A}. Yoyos = 20, [begin [P ! monitor_node || P <- NodeMons], [receive ready -> ok end || _ <- NodeMons], Owner = get_conn_owner(A), exit(Owner, kill), {nodedown, A} = receive_any(), {nodeup, A} = receive_any() end || _ <- lists:seq(1,Yoyos)], unlink(Spammer), exit(Spammer, die), receive {'DOWN',_,process,Spammer,_} -> ok end, [begin unlink(P), exit(P, die) end || P <- NodeMons], [receive {'DOWN',_,process,P,_} -> ok end || P <- NodeMons], net_kernel:monitor_nodes(false), ok. receive_any() -> receive_any(infinity). receive_any(Timeout) -> receive M -> M after Timeout -> timeout end. my_spawn_opt(Fun, Opts) -> case spawn_opt(Fun, Opts) of {Pid, _Mref} -> Pid; Pid -> Pid end. get_conn_owner(Node) -> {ok, NodeInfo} = net_kernel:node_info(Node), {value,{owner, Owner}} = lists:keysearch(owner, 1, NodeInfo), Owner. dist_ctrl_proc_smoke(Config) when is_list(Config) -> dist_ctrl_proc_test(get_nodenames(2, ?FUNCTION_NAME)). dist_ctrl_proc_reject(Config) when is_list(Config) -> ToReject = combinations(dist_util:rejectable_flags()), lists:map(fun(Flags) -> ct:log("Try to reject ~p",[Flags]), dist_ctrl_proc_test(get_nodenames(2, ?FUNCTION_NAME), "-gen_tcp_dist_reject_flags " ++ integer_to_list(Flags)) end, ToReject). combinations([H | T]) -> lists:flatten([[(1 bsl H) bor C || C <- combinations(T)] | combinations(T)]); combinations([]) -> [0]; combinations(BitField) -> lists:sort(combinations(bits(BitField, 0))). bits(0, _) -> []; bits(BitField, Cnt) when BitField band 1 == 1 -> [Cnt | bits(BitField bsr 1, Cnt + 1)]; bits(BitField, Cnt) -> bits(BitField bsr 1, Cnt + 1). dist_ctrl_proc_test(Nodes) -> dist_ctrl_proc_test(Nodes,""). dist_ctrl_proc_test([Name1,Name2], Extra) -> ThisNode = node(), GenTcpOptProlog = "-proto_dist gen_tcp " "-gen_tcp_dist_output_loop " ++ atom_to_list(?MODULE) ++ " " ++ "dist_cntrlr_output_test_size " ++ Extra, {ok, Node1} = start_node("", Name1, "-proto_dist gen_tcp"), {ok, Node2} = start_node("", Name2, GenTcpOptProlog), NL = lists:sort([ThisNode, Node1, Node2]), wait_until(fun () -> NL == lists:sort([node()|nodes()]) end), wait_until(fun () -> NL == lists:sort([rpc:call(Node1,erlang, node, []) | rpc:call(Node1, erlang, nodes, [])]) end), wait_until(fun () -> NL == lists:sort([rpc:call(Node2,erlang, node, []) | rpc:call(Node2, erlang, nodes, [])]) end), smoke_communicate(Node1, gen_tcp_dist, dist_cntrlr_output_loop), smoke_communicate(Node2, erl_distribution_SUITE, dist_cntrlr_output_loop_size), stop_node(Node1), stop_node(Node2), ok. smoke_communicate(Node, OLoopMod, OLoopFun) -> %% Verify that we actually are executing the distribution %% module we expect and also massage message passing over %% the connection a bit... Ps = rpc:call(Node, erlang, processes, []), try lists:foreach( fun (P) -> case rpc:call(Node, erlang, process_info, [P, current_stacktrace]) of undefined -> ok; {current_stacktrace, StkTrace} -> lists:foreach(fun ({Mod, Fun, 2, _}) when Mod == OLoopMod, Fun == OLoopFun -> io:format("~p ~p~n", [P, StkTrace]), throw(found_it); (_) -> ok end, StkTrace) end end, Ps), exit({missing, {OLoopMod, OLoopFun}}) catch throw:found_it -> ok end, Bin = list_to_binary(lists:duplicate(1000,100)), BitStr = <<0:7999>>, List = [[Bin], atom, [BitStr|Bin], make_ref(), [[[BitStr|"hopp"]]], 4711, 111122222211111111111111,"hej", fun () -> ok end, BitStr, self(), fun erlang:node/1], Pid = spawn_link(Node, fun () -> receive {From1, Msg1} -> From1 ! Msg1 end, receive {From2, Msg2} -> From2 ! Msg2 end end), R = make_ref(), Pid ! {self(), [R, List]}, receive [R, L1] -> List = L1 end, %% Send a huge message in order to trigger message fragmentation if enabled FragBin = <<0:(2*(1024*64*8))>>, Pid ! {self(), [R, List, FragBin]}, receive [R, L2, B] -> List = L2, FragBin = B end, unlink(Pid), exit(Pid, kill), ok. erl_uds_dist_smoke_test(Config) when is_list(Config) -> case os:type() of {win32,_} -> {skipped, "Not on Windows"}; _ -> do_erl_uds_dist_smoke_test() end. do_erl_uds_dist_smoke_test() -> [Node1, Node2] = lists:map(fun (Name) -> list_to_atom(atom_to_list(Name) ++ "@localhost") end, get_nodenames(2, erl_uds_dist_smoke_test)), {LPort, Acceptor} = uds_listen(), start_uds_node(Node1, LPort), start_uds_node(Node2, LPort), receive {uds_nodeup, N1} -> io:format("~p is up~n", [N1]) end, receive {uds_nodeup, N2} -> io:format("~p is up~n", [N2]) end, io:format("Testing ping net_adm:ping(~p) on ~p~n", [Node2, Node1]), Node1 ! {self(), {net_adm, ping, [Node2]}}, receive {Node1, PingRes} -> io:format("~p~n", [PingRes]), pong = PingRes end, io:format("Testing nodes() on ~p~n", [Node1]), Node1 ! {self(), {erlang, nodes, []}}, receive {Node1, N1List} -> io:format("~p~n", [N1List]), [Node2] = N1List end, io:format("Testing nodes() on ~p~n", [Node2]), Node2 ! {self(), {erlang, nodes, []}}, receive {Node2, N2List} -> io:format("~p~n", [N2List]), [Node1] = N2List end, io:format("Shutting down~n", []), Node1 ! {self(), close}, Node2 ! {self(), close}, receive {Node1, C1} -> ok = C1 end, receive {Node2, C2} -> ok = C2 end, unlink(Acceptor), exit(Acceptor, kill), io:format("ok~n", []), ok. %% Helpers for testing the erl_uds_dist example uds_listen() -> Me = self(), {ok, LSock} = gen_tcp:listen(0, [binary, {packet, 4}, {active, false}]), {ok, LPort} = inet:port(LSock), {LPort, spawn_link(fun () -> uds_accept_loop(LSock, Me) end)}. uds_accept_loop(LSock, TestProc) -> {ok, Sock} = gen_tcp:accept(LSock), _ = spawn_link(fun () -> uds_rpc_client_init(Sock, TestProc) end), uds_accept_loop(LSock, TestProc). uds_rpc(Sock, MFA) -> ok = gen_tcp:send(Sock, term_to_binary(MFA)), case gen_tcp:recv(Sock, 0) of {error, Reason} -> error({recv_failed, Reason}); {ok, Packet} -> binary_to_term(Packet) end. uds_rpc_client_init(Sock, TestProc) -> case uds_rpc(Sock, {erlang, node, []}) of nonode@nohost -> %% Wait for distribution to come up... receive after 100 -> ok end, uds_rpc_client_init(Sock, TestProc); Node when is_atom(Node) -> register(Node, self()), TestProc ! {uds_nodeup, Node}, uds_rpc_client_loop(Sock, Node) end. uds_rpc_client_loop(Sock, Node) -> receive {From, close} -> ok = gen_tcp:send(Sock, term_to_binary(close)), From ! {Node, gen_tcp:close(Sock)}, exit(normal); {From, ApplyData} -> From ! {Node, uds_rpc(Sock, ApplyData)}, uds_rpc_client_loop(Sock, Node) end. uds_rpc_server_loop(Sock) -> case gen_tcp:recv(Sock, 0) of {error, Reason} -> error({recv_failed, Reason}); {ok, Packet} -> case binary_to_term(Packet) of {M, F, A} when is_atom(M), is_atom(F), is_list(A) -> ok = gen_tcp:send(Sock, term_to_binary(apply(M, F, A))); {F, A} when is_function(F), is_list(A) -> ok = gen_tcp:send(Sock, term_to_binary(apply(F, A))); close -> ok = gen_tcp:close(Sock), exit(normal); Other -> error({unexpected_data, Other}) end end, uds_rpc_server_loop(Sock). start_uds_rpc_server([PortString]) -> Port = list_to_integer(PortString), {Pid, Mon} = spawn_monitor(fun () -> {ok, Sock} = gen_tcp:connect({127,0,0,1}, Port, [binary, {packet, 4}, {active, false}]), uds_rpc_server_loop(Sock) end), receive {'DOWN', Mon, process, Pid, Reason} -> if Reason == normal -> halt(); true -> EStr = lists:flatten(io_lib:format("uds rpc server crashed: ~p", [Reason])), (catch file:write_file("uds_rpc_server_crash."++os:getpid(), EStr)), halt(EStr) end end. start_uds_node(NodeName, LPort) -> Static = "-detached -noinput -proto_dist erl_uds", Pa = filename:dirname(code:which(?MODULE)), Prog = case catch init:get_argument(progname) of {ok,[[P]]} -> P; _ -> error(no_progname_argument_found) end, {ok, Pwd} = file:get_cwd(), NameStr = atom_to_list(NodeName), CmdLine = Prog ++ " " ++ Static ++ " -sname " ++ NameStr ++ " -pa " ++ Pa ++ " -env ERL_CRASH_DUMP " ++ Pwd ++ "/erl_crash_dump." ++ NameStr ++ " -setcookie " ++ atom_to_list(erlang:get_cookie()) ++ " -run " ++ atom_to_list(?MODULE) ++ " start_uds_rpc_server " ++ integer_to_list(LPort), io:format("Starting: ~p~n", [CmdLine]), case open_port({spawn, CmdLine}, []) of Port when is_port(Port) -> unlink(Port), erlang:port_close(Port); Error -> error({open_port_failed, Error}) end, ok. erl_1424(Config) when is_list(Config) -> {error, Reason} = erl_epmd:names("."), {comment, lists:flatten(io_lib:format("Reason: ~p", [Reason]))}. net_kernel_start(Config) when is_list(Config) -> MyName = net_kernel_start_tester, register(MyName, self()), net_kernel_start_test(MyName, 120, 8, true, false), net_kernel_start_test(MyName, 120, 8, false, false), net_kernel_start_test(MyName, 120, 8, true, true), net_kernel_start_test(MyName, undefined, undefined, undefined, undefined). net_kernel_start_test(MyName, NetTickTime, NetTickIntesity, DistListen, Hidden) -> TestNameStr = "net_kernel_start_test_node-" ++ integer_to_list(erlang:system_time(seconds)) ++ "-" ++ integer_to_list(erlang:unique_integer([monotonic,positive])), TestNode = list_to_atom(TestNameStr ++ "@" ++ atom_to_list(gethostname())), CmdLine = net_kernel_start_cmdline(MyName, list_to_atom(TestNameStr), NetTickTime, NetTickIntesity, DistListen, Hidden), io:format("Starting test node ~p: ~s~n", [TestNode, CmdLine]), case open_port({spawn, CmdLine}, []) of Port when is_port(Port) -> case DistListen == false of false -> ok; true -> receive after 1500 -> ok end, pang = net_adm:ping(TestNode), ok end, receive {i_am_alive, Pid, Node, NTT} = Msg -> IsHidden = lists:member(TestNode, nodes(hidden)), IsVisible = lists:member(TestNode, nodes(visible)), io:format("IsVisible = ~p~nIsHidden = ~p~n", [IsVisible, IsHidden]), io:format("Response from ~p: ~p~n", [Node, Msg]), rpc:cast(Node, erlang, halt, []), catch erlang:port_close(Port), TestNode = node(Pid), TestNode = Node, case NetTickTime == undefined of true -> {ok, DefNTT} = application:get_env(kernel, net_ticktime), DefNTT = NTT; false -> NetTickTime = NTT end, case DistListen == false orelse Hidden == true of true -> true = IsHidden, false = IsVisible; false -> false = IsHidden, true = IsVisible end end, ok; Error -> error({open_port_failed, TestNode, Error}) end. net_kernel_start_cmdline(TestName, Name, NetTickTime, NetTickIntensity, DistListen, Hidden) -> Pa = filename:dirname(code:which(?MODULE)), Prog = case catch init:get_argument(progname) of {ok, [[Prg]]} -> Prg; _ -> error(missing_progname) end, NameDomain = case net_kernel:longnames() of false -> "shortnames"; true -> "longnames" end, {ok, Pwd} = file:get_cwd(), NameStr = atom_to_list(Name), Prog ++ " -noinput -noshell -detached -pa " ++ Pa ++ " -env ERL_CRASH_DUMP " ++ Pwd ++ "/erl_crash_dump." ++ NameStr ++ " -setcookie " ++ atom_to_list(erlang:get_cookie()) ++ " -run " ++ atom_to_list(?MODULE) ++ " net_kernel_start_do_test " ++ atom_to_list(TestName) ++ " " ++ atom_to_list(node()) ++ " " ++ NameStr ++ " " ++ NameDomain ++ case NetTickTime == undefined of true -> ""; false -> " " ++ integer_to_list(NetTickTime) ++ " " ++ integer_to_list(NetTickIntensity) end ++ case DistListen == undefined of true -> ""; false -> " " ++ atom_to_list(DistListen) end ++ case Hidden == undefined of true -> ""; false -> " " ++ atom_to_list(Hidden) end. net_kernel_start_do_test([TestName, TestNode, Name, NameDomain]) -> net_kernel_start_do_test(TestName, TestNode, list_to_atom(Name), #{name_domain => list_to_atom(NameDomain)}); net_kernel_start_do_test([TestName, TestNode, Name, NameDomain, NetTickTime, NetTickIntensity, DistListen, Hidden]) -> net_kernel_start_do_test(TestName, TestNode, list_to_atom(Name), #{net_ticktime => list_to_integer(NetTickTime), name_domain => list_to_atom(NameDomain), net_tickintensity => list_to_integer(NetTickIntensity), dist_listen => list_to_atom(DistListen), hidden => list_to_atom(Hidden)}). net_kernel_start_do_test(TestName, TestNode, Name, Options) -> case net_kernel:start(Name, Options) of {ok, _Pid} -> case maps:get(dist_listen, Options, true) of false -> receive after 3000 -> ok end; true -> ok end, Tester = {list_to_atom(TestName), list_to_atom(TestNode)}, Tester ! {i_am_alive, self(), node(), net_kernel:get_net_ticktime()}, receive after 60000 -> ok end, erlang:halt(); Error -> erlang:halt(lists:flatten(io_lib:format("~p", [Error]))) end. differing_cookies(Config) when is_list(Config) -> test_server:timetrap({minutes, 1}), Node = node(), true = Node =/= nonode@nohost, [] = nodes(), BaseName = atom_to_list(?FUNCTION_NAME), %% Use -hidden nodes to avoid global connecting all nodes %% Start node A with different cookie NodeAName = BaseName++"_nodeA", NodeA = full_node_name(NodeAName), NodeACookieL = BaseName++"_cookieA", NodeACookie = list_to_atom(NodeACookieL), true = erlang:set_cookie( NodeA, NodeACookie ), { ok, NodeA } = start_node( "-hidden", NodeAName, "-setcookie "++NodeACookieL ), try %% Verify the cluster [ NodeA ] = nodes(hidden), [ Node ] = rpc:call( NodeA, erlang, nodes, [hidden] ), %% Start node B with another different cookie NodeBName = BaseName++"_nodeB", NodeB = full_node_name(NodeBName), NodeBCookieL = BaseName++"_cookieB", NodeBCookie = list_to_atom(NodeBCookieL), true = erlang:set_cookie( NodeB, NodeBCookie ), { ok, NodeB } = start_node( "-hidden", NodeBName, "-setcookie "++NodeBCookieL ), try %% Verify the cluster equal_sets( [NodeA, NodeB], nodes(hidden) ), [ Node ] = rpc:call( NodeA, erlang, nodes, [hidden] ), [ Node ] = rpc:call( NodeB, erlang, nodes, [hidden] ), %% Verify that the nodes can not connect %% before correcting the cookie configuration pang = rpc:call( NodeA, net_adm, ping, [NodeB] ), pang = rpc:call( NodeB, net_adm, ping, [NodeA] ), %% Configure cookie and connect node A -> B true = rpc:call( NodeA, erlang, set_cookie, [NodeB, NodeBCookie] ), pong = rpc:call( NodeA, net_adm, ping, [NodeB] ), %% Verify the cluster NodeACookie = rpc:call( NodeA, erlang, get_cookie, []), NodeBCookie = rpc:call( NodeB, erlang, get_cookie, []), equal_sets( [NodeA, NodeB], nodes(hidden) ), equal_sets( [Node, NodeB], rpc:call( NodeA, erlang, nodes, [hidden] )), equal_sets( [Node, NodeA], rpc:call( NodeB, erlang, nodes, [hidden] )), %% Disconnect node A from B true = rpc:call( NodeB, net_kernel, disconnect, [NodeA] ), %% Verify the cluster equal_sets( [NodeA, NodeB], nodes(hidden) ), [ Node ] = rpc:call( NodeA, erlang, nodes, [hidden] ), [ Node ] = rpc:call( NodeB, erlang, nodes, [hidden] ), Reconnect , now node B - > A pong = rpc:call( NodeB, net_adm, ping, [NodeA] ), %% Verify the cluster equal_sets( [NodeA, NodeB], nodes(hidden) ), equal_sets( [Node, NodeB], rpc:call( NodeA, erlang, nodes, [hidden] )), equal_sets( [Node, NodeA], rpc:call( NodeB, erlang, nodes, [hidden] )) after _ = stop_node(NodeB) end after _ = stop_node(NodeA) end, [] = nodes(hidden), ok. cmdline_setcookie_2(Config) when is_list(Config) -> test_server:timetrap({minutes, 1}), Node = node(), true = Node =/= nonode@nohost, [] = nodes(), NodeL = atom_to_list(Node), BaseName = atom_to_list(?FUNCTION_NAME), NodeCookie = erlang:get_cookie(), NodeCookieL = atom_to_list(NodeCookie), %% Use -hidden nodes to avoid global connecting all nodes %% Start node A with different cookie %% and cookie configuration of mother node NodeAName = BaseName++"_nodeA", NodeA = full_node_name(NodeAName), NodeACookieL = BaseName++"_cookieA", NodeACookie = list_to_atom(NodeACookieL), { ok, NodeA } = start_node( "-hidden", NodeAName, "-setcookie "++NodeL++" "++NodeCookieL ), try %% Verify the cluster [ NodeA ] = nodes(hidden), [ Node ] = rpc:call( NodeA, erlang, nodes, [hidden] ), NodeCookie = rpc:call( NodeA, erlang, get_cookie, []), true = rpc:call( NodeA, erlang, set_cookie, [NodeACookie] ), %% Start node B with different cookie %% and cookie configuration of mother node and node A NodeBName = BaseName++"_nodeB", NodeB = full_node_name(NodeBName), NodeBCookieL = BaseName++"_cookieB", NodeBCookie = list_to_atom(NodeBCookieL), { ok, NodeB } = start_node( "-hidden", NodeBName, "-setcookie "++NodeBCookieL++" " "-setcookie "++NodeL++" "++NodeCookieL++" " "-setcookie "++atom_to_list(NodeA)++" "++NodeACookieL ), try %% Verify the cluster NodeACookie = rpc:call( NodeA, erlang, get_cookie, []), NodeBCookie = rpc:call( NodeB, erlang, get_cookie, []), equal_sets( [NodeA, NodeB], nodes(hidden) ), [ Node ] = rpc:call( NodeA, erlang, nodes, [hidden] ), [ Node ] = rpc:call( NodeB, erlang, nodes, [hidden] ), Connect the nodes pong = rpc:call( NodeA, net_adm, ping, [NodeB] ), %% Verify the cluster NodeACookie = rpc:call( NodeA, erlang, get_cookie, []), NodeBCookie = rpc:call( NodeB, erlang, get_cookie, []), equal_sets( [NodeA, NodeB], nodes(hidden) ), equal_sets( [Node, NodeB], rpc:call( NodeA, erlang, nodes, [hidden] )), equal_sets( [Node, NodeA], rpc:call( NodeB, erlang, nodes, [hidden] )) after _ = stop_node(NodeB) end after _ = stop_node(NodeA) end, [] = nodes(hidden), ok. connection_cookie(Config) when is_list(Config) -> test_server:timetrap({minutes, 1}), Node = node(), true = Node =/= nonode@nohost, [] = nodes(), NodeL = atom_to_list(Node), BaseName = atom_to_list(?FUNCTION_NAME), %% Start node A with dedicated connection cookie NodeAName = BaseName++"_nodeA", NodeA = full_node_name(NodeAName), NodeACookieL = BaseName++"_cookieA", NodeACookie = list_to_atom(NodeACookieL), true = NodeACookie =/= erlang:get_cookie(), ConnectionCookieL = BaseName++"_connectionCookie", ConnectionCookie = list_to_atom(ConnectionCookieL), true = erlang:set_cookie( NodeA, ConnectionCookie ), { ok, NodeA } = start_node( "", NodeAName, "-setcookie "++NodeACookieL++" " "-setcookie "++NodeL++" "++ConnectionCookieL ), try %% Verify the cluster [ NodeA ] = nodes(), [ Node ] = rpc:call( NodeA, erlang, nodes, [] ), NodeACookie = rpc:call( NodeA, erlang, get_cookie, []), ConnectionCookie = rpc:call( NodeA, auth, get_cookie, [Node]), ConnectionCookie = erlang:get_cookie( NodeA ) after _ = stop_node(NodeA) end, [] = nodes(), ok. dyn_differing_cookies(Config) when is_list(Config) -> test_server:timetrap({minutes, 1}), MotherNode = node(), true = MotherNode =/= nonode@nohost, [] = nodes(hidden), MotherNodeL = atom_to_list(MotherNode), BaseName = atom_to_list(?FUNCTION_NAME), MotherNodeCookie = erlang:get_cookie(), MotherNodeCookieL = atom_to_list(MotherNodeCookie), register(?FUNCTION_NAME, self()), %% Start node A with different cookie %% and cookie configuration of mother node DynNodeCookieL = BaseName++"_cookieA", DynNodeCookie = list_to_atom(DynNodeCookieL), {_NF1, Port1} = start_node_unconnected( "-setcookie "++MotherNodeL++" "++MotherNodeCookieL, undefined, DynNodeCookie, ?MODULE, run_remote_test, ["ddc_remote_run", MotherNodeL, "cmdline", MotherNodeCookieL] ), dyn_differing_cookies(MotherNode, MotherNodeCookie, DynNodeCookie, Port1), Same again , but use : set_cookie/2 to set MotherNodeCookie {_NF2, Port2} = start_node_unconnected( "", undefined, DynNodeCookie, ?MODULE, run_remote_test, ["ddc_remote_run", MotherNodeL, "set_cookie", MotherNodeCookieL] ), dyn_differing_cookies(MotherNode, MotherNodeCookie, DynNodeCookie, Port2). dyn_differing_cookies(MotherNode, MotherNodeCookie, DynNodeCookie, Port) -> receive { MotherNode, MotherNodeCookie, DynNodeCookie, DynNode } -> [ DynNode ] = nodes(hidden), [ MotherNode ] = rpc:call( DynNode, erlang, nodes, [hidden] ), DynNodeCookie = rpc:call( DynNode, erlang, get_cookie, [] ), MotherNodeCookie = rpc:call( DynNode, erlang, get_cookie, [MotherNode] ), {ddc_remote_run, DynNode} ! {MotherNode, MotherNodeCookie, DynNode}, 0 = wait_for_port_exit(Port), [] = nodes(hidden), ok; {Port, {data, Data}} -> io:format("~p: ~s", [Port, Data]), dyn_differing_cookies( MotherNode, MotherNodeCookie, DynNodeCookie, Port); Other -> error({unexpected, Other}) end. ddc_remote_run(MotherNode, [SetCookie, MotherNodeCookieL]) -> nonode@nohost = node(), [] = nodes(hidden), MotherNodeCookie = list_to_atom(MotherNodeCookieL), case SetCookie of "set_cookie" -> erlang:set_cookie(MotherNode, MotherNodeCookie); "cmdline" -> ok end, MotherNodeCookie = erlang:get_cookie(MotherNode), true = net_kernel:connect_node( MotherNode ), [ MotherNode ] = nodes(hidden), DynNode = node(), [ DynNode ] = rpc:call( MotherNode, erlang, nodes, [hidden] ), MotherNodeCookie = erlang:get_cookie( MotherNode ), MotherNodeCookie = rpc:call( MotherNode, erlang, get_cookie, [] ), %% Here we get the mother node's default cookie MotherNodeCookie = rpc:call( MotherNode, erlang, get_cookie, [DynNode] ), DynNodeCookie = erlang:get_cookie(), register(ddc_remote_run, self() ), {dyn_differing_cookies, MotherNode} ! {MotherNode, MotherNodeCookie, DynNodeCookie, DynNode}, receive { MotherNode, MotherNodeCookie, DynNode } -> true = disconnect_node( MotherNode ), [] = nodes(hidden), ok; Other -> error({unexpected, Other}) end. xdg_cookie(Config) when is_list(Config) -> PrivDir = proplists:get_value(priv_dir, Config), TestHome = filename:join(PrivDir, ?FUNCTION_NAME), ok = file:make_dir(TestHome), HomeEnv = case os:type() of {win32, _} -> [Drive | Path] = filename:split(TestHome), [{"APPDATA", filename:join(TestHome,"AppData")}, {"HOMEDRIVE", Drive}, {"HOMEPATH", filename:join(Path)}]; _ -> [{"HOME", TestHome}] end, NodeOpts = #{ env => HomeEnv ++ [{"ERL_CRASH_DUMP", filename:join([TestHome,"erl_crash.dump"])}], connection => 0 }, Test that a default .erlang.cookie file is created {ok, CreatorPeer, _} = peer:start_link(NodeOpts#{ name => peer:random_name(?FUNCTION_NAME) }), UserConfig = peer:call(CreatorPeer, filename, basedir, [user_config,"erlang"]), ?assert(peer:call(CreatorPeer, filelib, is_regular, [filename:join(TestHome, ".erlang.cookie")])), OrigCookie = peer:call(CreatorPeer, erlang, get_cookie, []), peer:stop(CreatorPeer), Test that the $ HOME/.erlang.cookie file takes precedence over XDG XDGCookie = filename:join([UserConfig, ".erlang.cookie"]), ok = filelib:ensure_dir(XDGCookie), ok = file:write_file(XDGCookie, "Me want cookie!"), {ok, XDGFI} = file:read_file_info(XDGCookie), ok = file:write_file_info(XDGCookie, XDGFI#file_info{ mode = 8#600 }), {ok, Peer, _} = peer:start_link(NodeOpts#{ name => peer:random_name(?FUNCTION_NAME) }), ?assertEqual(OrigCookie, peer:call(Peer, erlang, get_cookie, [])), peer:stop(Peer), Check that XDG cookie works after we delete the $ HOME cookie HomeCookie = filename:join(TestHome, ".erlang.cookie"), {ok, HomeFI} = file:read_file_info(HomeCookie), ok = file:write_file_info(HomeCookie, HomeFI#file_info{ mode = 8#777 }), ok = file:delete(HomeCookie), {ok, Peer2, _} = peer:start_link(NodeOpts#{ name => peer:random_name(?FUNCTION_NAME) }), ?assertEqual('Me want cookie!', peer:call(Peer2, erlang, get_cookie, [])), peer:stop(Peer2), ok. %% Misc. functions equal_sets(A, B) -> S = lists:sort(A), case lists:sort(B) of S -> ok; _ -> erlang:error({not_equal_sets, A, B}) end. run_dist_configs(Func, Config) -> GetOptProlog = "-proto_dist gen_tcp -gen_tcp_dist_output_loop " ++ atom_to_list(?MODULE) ++ " ", GenTcpDistTest = case get_gen_tcp_dist_test_type() of default -> {"gen_tcp_dist", "-proto_dist gen_tcp"}; size -> {"gen_tcp_dist (get_size)", GetOptProlog ++ "dist_cntrlr_output_test_size"} end, lists:map(fun ({DCfgName, DCfg}) -> io:format("~n~n=== Running ~s configuration ===~n~n", [DCfgName]), Func(DCfg, Config) end, [{"default", ""}, GenTcpDistTest]). start_gen_tcp_dist_test_type_server() -> Me = self(), Go = make_ref(), io:format("STARTING: gen_tcp_dist_test_type_server~n",[]), {P, M} = spawn_monitor(fun () -> register(gen_tcp_dist_test_type_server, self()), Me ! Go, gen_tcp_dist_test_type_server() end), receive Go -> ok; {'DOWN', M, process, P, _} -> start_gen_tcp_dist_test_type_server() end. kill_gen_tcp_dist_test_type_server() -> case whereis(gen_tcp_dist_test_type_server) of undefined -> ok; Pid -> exit(Pid,kill), Sync death , before continuing ... false = erlang:is_process_alive(Pid) end. gen_tcp_dist_test_type_server() -> Type = case abs(erlang:monotonic_time(second)) rem 2 of 0 -> default; 1 -> size end, gen_tcp_dist_test_type_server(Type). gen_tcp_dist_test_type_server(Type) -> receive {From, Ref} -> From ! {Ref, Type}, NewType = case Type of default -> size; size -> default end, gen_tcp_dist_test_type_server(NewType) end. get_gen_tcp_dist_test_type() -> Ref = make_ref(), try gen_tcp_dist_test_type_server ! {self(), Ref}, receive {Ref, Type} -> Type end catch error:badarg -> start_gen_tcp_dist_test_type_server(), get_gen_tcp_dist_test_type() end. dist_cntrlr_output_test_size(DHandle, Socket) -> false = erlang:dist_ctrl_get_opt(DHandle, get_size), false = erlang:dist_ctrl_set_opt(DHandle, get_size, true), true = erlang:dist_ctrl_get_opt(DHandle, get_size), true = erlang:dist_ctrl_set_opt(DHandle, get_size, false), false = erlang:dist_ctrl_get_opt(DHandle, get_size), false = erlang:dist_ctrl_set_opt(DHandle, get_size, true), true = erlang:dist_ctrl_get_opt(DHandle, get_size), dist_cntrlr_output_loop_size(DHandle, Socket). dist_cntrlr_output_loop_size(DHandle, Socket) -> receive dist_data -> %% Outgoing data from this node... dist_cntrlr_send_data_size(DHandle, Socket); _ -> ok %% Drop garbage message... end, dist_cntrlr_output_loop_size(DHandle, Socket). dist_cntrlr_send_data_size(DHandle, Socket) -> case erlang:dist_ctrl_get_data(DHandle) of none -> erlang:dist_ctrl_get_data_notification(DHandle); {Size, Data} -> ok = ensure_iovec(Data), Size = erlang:iolist_size(Data), ok = gen_tcp:send(Socket, Data), dist_cntrlr_send_data_size(DHandle, Socket) end. ensure_iovec([]) -> ok; ensure_iovec([X|Y]) when is_binary(X) -> ensure_iovec(Y). monitor_node_state() -> erts_debug:set_internal_state(available_internal_state, true), MonitoringNodes = erts_debug:get_internal_state(monitoring_nodes), erts_debug:set_internal_state(available_internal_state, false), MonitoringNodes. check_no_nodedown_nodeup(TimeOut) -> receive {nodeup, _, _} = Msg -> ct:fail({unexpected_nodeup, Msg}); {nodeup, _} = Msg -> ct:fail({unexpected_nodeup, Msg}); {nodedown, _, _} = Msg -> ct:fail({unexpected_nodedown, Msg}); {nodedown, _} = Msg -> ct:fail({unexpected_nodedown, Msg}) after TimeOut -> ok end. print_my_messages() -> {messages, Messages} = process_info(self(), messages), io:format("Messages: ~p~n", [Messages]), ok. sleep(T) -> receive after T * 1000 -> ok end. start_node(_DCfg, Name, Param, this) -> NewParam = Param ++ " -pa " ++ filename:dirname(code:which(?MODULE)), test_server:start_node(Name, peer, [{args, NewParam}, {erl, [this]}]); start_node(DCfg, Name, Param, "this") -> NewParam = Param ++ " -pa " ++ filename:dirname(code:which(?MODULE)) ++ " " ++ DCfg, test_server:start_node(Name, peer, [{args, NewParam}, {erl, [this]}]); start_node(DCfg, Name, Param, Rel) when is_atom(Rel) -> NewParam = Param ++ " -pa " ++ filename:dirname(code:which(?MODULE)) ++ " " ++ DCfg, test_server:start_node(Name, peer, [{args, NewParam}, {erl, [{release, atom_to_list(Rel)}]}]); start_node(DCfg, Name, Param, Rel) when is_list(Rel) -> NewParam = Param ++ " -pa " ++ filename:dirname(code:which(?MODULE)) ++ " " ++ DCfg, test_server:start_node(Name, peer, [{args, NewParam}, {erl, [{release, Rel}]}]). start_node(DCfg, Name, Param) -> NewParam = Param ++ " -pa " ++ filename:dirname(code:which(?MODULE)) ++ " " ++ DCfg, test_server:start_node(Name, slave, [{args, NewParam}]). start_node(DCfg, Name) -> start_node(DCfg, Name, ""). stop_node(Node) -> test_server:stop_node(Node). get_nodenames(N, T) -> get_nodenames(N, T, []). get_nodenames(0, _, Acc) -> Acc; get_nodenames(N, T, Acc) -> U = erlang:unique_integer([positive]), get_nodenames(N-1, T, [list_to_atom(atom_to_list(T) ++ "-" ++ ?MODULE_STRING ++ "-" ++ integer_to_list(U)) | Acc]). get_numbered_nodenames(N, T) -> get_numbered_nodenames(N, T, []). get_numbered_nodenames(0, _, Acc) -> Acc; get_numbered_nodenames(N, T, Acc) -> U = erlang:unique_integer([positive]), NL = [list_to_atom(atom_to_list(T) ++ integer_to_list(N) ++ "-" ++ ?MODULE_STRING ++ "-" ++ integer_to_list(U)) | Acc], get_numbered_nodenames(N-1, T, NL). wait_until(Fun) -> case Fun() of true -> ok; _ -> receive after 100 -> wait_until(Fun) end end. repeat(Fun, 0) when is_function(Fun) -> ok; repeat(Fun, N) when is_function(Fun), is_integer(N), N > 0 -> Fun(), repeat(Fun, N-1). no_msgs(Wait) -> receive after Wait -> no_msgs() end. no_msgs() -> {messages, []} = process_info(self(), messages). block_emu(Ms) -> erts_debug:set_internal_state(available_internal_state, true), Res = erts_debug:set_internal_state(block, Ms), erts_debug:set_internal_state(available_internal_state, false), Res.
null
https://raw.githubusercontent.com/erlang/otp/9ce9c59aa7f97d694da6307e2e52dc1378393a99/lib/kernel/test/erl_distribution_SUITE.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% Performs the test at another node. ----------------------------------------------------------------- The distribution is mainly tested in the big old test_suite. This test only tests the net_ticktime configuration flag. Should be started in a CC view with: erl -sname master -rsh ctrsh ----------------------------------------------------------------- This test case use disabled "connect all" so that global wont interfere... Not for intensity test... After the sleep(2sec) and cast the other node shall destroy the connection as it has not received anything on the connection. halts the client node after tick timeout (the connection is down and the slave node decides to halt !! node doesn't tick the client node within the interval ... time for termination of the dist controller, delivery of messages, Checks that pinging nonexistyent nodes does not waste space in distribution table. Test that starting nodes with different legal name part works, and that illegal ones are filtered Test that starting nodes with different legal host part works, and that illegal ones are filtered get the localhost's name, depending on the using name policy Test that pinging an illegal nodename does not kill the node. In this test case, we reluctantly accept shorter times than the given setup time, because the connection attempt can end in a "Host unreachable" error before the timeout fires. Keep the connection with the client node up. This is necessary as the client node runs with much shorter tick time !! Set up the connection again !! simulate action on the connection wait until all nodes are registered check that all nodes reregister with epmd Do the actual test on the remote node We connect Other connect OTP-4255. This test case use disabled "connect all" so that global wont interfere... In case other nodes are connected In case other nodes are connected In case other nodes are connected In case other nodes than these are connected The node not changing ticktime should have been disconnected from the other nodes No other connections should have been broken Basic tests of hidden node. Basic test of hidden node. Check that they haven't already connected. No nodes should be visible on hidden_node visible_node should be hidden on hidden_node hidden_node node shouldn't be visible on visible_node hidden_node should be hidden on visible_node Check the kernel inet_dist_{listen,connect}_options options. Some shells need quoting of [{}] check net_ticker_spawn_options Some shells need quoting of [{}] If the complex nodedown_reason messed something up garbage collections are likely to dump core monitor_nodes_node_type monitor_nodes Tests that {nodeup, Node} messages are received before Whitebox: nodeup test: Since this process was the last one monitoring nodes this process will be the last one notified on nodeup Verify the monitor_nodes order expected io:format("~p~n", [TestMonNodeState]), we want an endless stream of messages and the kill the node mercilessly. last ... without garbage after it. bringing up the connection). msg stream has begun, kill the node message. since this will wrap an internal counter just to get lots of other monitors to fire when connection goes down and thereby give time for {nodeup,A} to race before {nodedown,A}. Spawn message spamming process to trigger new connection setups as quick as possible. Now bring connection down and verify we get {nodedown,A} before {nodeup,A}. Verify that we actually are executing the distribution module we expect and also massage message passing over the connection a bit... Send a huge message in order to trigger message fragmentation if enabled Helpers for testing the erl_uds_dist example Wait for distribution to come up... Use -hidden nodes to avoid global connecting all nodes Start node A with different cookie Verify the cluster Start node B with another different cookie Verify the cluster Verify that the nodes can not connect before correcting the cookie configuration Configure cookie and connect node A -> B Verify the cluster Disconnect node A from B Verify the cluster Verify the cluster Use -hidden nodes to avoid global connecting all nodes Start node A with different cookie and cookie configuration of mother node Verify the cluster Start node B with different cookie and cookie configuration of mother node and node A Verify the cluster Verify the cluster Start node A with dedicated connection cookie Verify the cluster Start node A with different cookie and cookie configuration of mother node Here we get the mother node's default cookie Misc. functions Outgoing data from this node... Drop garbage message...
Copyright Ericsson AB 1997 - 2022 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(erl_distribution_SUITE). -include_lib("common_test/include/ct.hrl"). -include_lib("kernel/include/dist.hrl"). -include_lib("stdlib/include/assert.hrl"). -include_lib("kernel/include/file.hrl"). -export([all/0, suite/0,groups/0,init_per_suite/1, end_per_suite/1, init_per_group/2,end_per_group/2]). -export([tick/1, tick_intensity/1, tick_change/1, connect_node/1, nodenames/1, hostnames/1, illegal_nodenames/1, hidden_node/1, dyn_node_name/1, epmd_reconnect/1, setopts/1, table_waste/1, net_setuptime/1, inet_dist_options_options/1, net_ticker_spawn_options/1, monitor_nodes_nodedown_reason/1, monitor_nodes_complex_nodedown_reason/1, monitor_nodes_node_type/1, monitor_nodes_misc/1, monitor_nodes_otp_6481/1, monitor_nodes_errors/1, monitor_nodes_combinations/1, monitor_nodes_cleanup/1, monitor_nodes_many/1, monitor_nodes_down_up/1, dist_ctrl_proc_smoke/1, dist_ctrl_proc_reject/1, erl_uds_dist_smoke_test/1, erl_1424/1, net_kernel_start/1, differing_cookies/1, cmdline_setcookie_2/1, connection_cookie/1, dyn_differing_cookies/1, xdg_cookie/1]). -export([get_socket_priorities/0, get_net_ticker_fullsweep_option/1, tick_cli_test/3, tick_cli_test1/3, tick_serv_test/2, tick_serv_test1/1, run_remote_test/1, dyn_node_name_do/2, epmd_reconnect_do/2, setopts_do/2, setopts_deadlock_test/2, keep_conn/1, time_ping/1, ddc_remote_run/2]). -export([net_kernel_start_do_test/1]). -export([init_per_testcase/2, end_per_testcase/2]). -export([dist_cntrlr_output_test_size/2]). -export([pinger/1]). -export([start_uds_rpc_server/1]). -define(DUMMY_NODE,dummy@test01). -define(ALT_EPMD_PORT, "12321"). -define(ALT_EPMD_CMD, "epmd -port "++?ALT_EPMD_PORT). suite() -> [{ct_hooks,[ts_install_cth]}, {timetrap,{minutes,12}}]. all() -> [dist_ctrl_proc_smoke, dist_ctrl_proc_reject, tick, tick_intensity, tick_change, nodenames, hostnames, illegal_nodenames, connect_node, dyn_node_name, epmd_reconnect, hidden_node, setopts, table_waste, net_setuptime, inet_dist_options_options, net_ticker_spawn_options, {group, monitor_nodes}, erl_uds_dist_smoke_test, erl_1424, net_kernel_start, {group, differing_cookies}]. groups() -> [{monitor_nodes, [], [monitor_nodes_nodedown_reason, monitor_nodes_complex_nodedown_reason, monitor_nodes_node_type, monitor_nodes_misc, monitor_nodes_otp_6481, monitor_nodes_errors, monitor_nodes_combinations, monitor_nodes_cleanup, monitor_nodes_many, monitor_nodes_down_up]}, {differing_cookies, [], [differing_cookies, cmdline_setcookie_2, connection_cookie, dyn_differing_cookies, xdg_cookie]}]. init_per_suite(Config) -> start_gen_tcp_dist_test_type_server(), Config. end_per_suite(_Config) -> [slave:stop(N) || N <- nodes()], kill_gen_tcp_dist_test_type_server(), ok. init_per_group(_GroupName, Config) -> Config. end_per_group(_GroupName, Config) -> Config. init_per_testcase(TC, Config) when TC == hostnames; TC == nodenames -> file:make_dir("hostnames_nodedir"), file:write_file("hostnames_nodedir/ignore_core_files",""), Config; init_per_testcase(epmd_reconnect, Config) -> [] = os:cmd(?ALT_EPMD_CMD++" -relaxed_command_check -daemon"), Config; init_per_testcase(Func, Config) when is_atom(Func), is_list(Config) -> Config. end_per_testcase(epmd_reconnect, _Config) -> os:cmd(?ALT_EPMD_CMD++" -kill"), ok; end_per_testcase(_Func, _Config) -> ok. connect_node(Config) when is_list(Config) -> Connected = nodes(connected), true = net_kernel:connect_node(node()), Connected = nodes(connected), ok. tick(Config) when is_list(Config) -> run_dist_configs(fun tick/2, Config). tick(DCfg, Config) -> tick_test(DCfg, Config, false). tick_intensity(Config) when is_list(Config) -> run_dist_configs(fun tick_intensity/2, Config). tick_intensity(DCfg, Config) -> tick_test(DCfg, Config, true). tick_test(DCfg, _Config, CheckIntensityArg) -> [Name1, Name2] = get_nodenames(2, dist_test), {ok, Node} = start_node(DCfg, Name1), case CheckIntensityArg of true -> ok; false -> First check that the normal case is OK ! rpc:call(Node, erl_distribution_SUITE, tick_cli_test, [node(), 8000, 16000]), erlang:monitor_node(Node, true), receive {nodedown, Node} -> ct:fail("nodedown from other node") after 30000 -> erlang:monitor_node(Node, false) end, ok end, stop_node(Node), Now , set the net_ticktime for the other node to 12 secs . The nodedown message should arrive within 8 < T < 16 secs . We must have two slave nodes as the slave mechanism otherwise Set the ticktime on the server node to 100 secs so the server {ok, ServNode} = start_node(DCfg, Name2, "-kernel net_ticktime 100 -connect_all false"), rpc:call(ServNode, erl_distribution_SUITE, tick_serv_test, [Node, node()]), We set min / max a second lower / higher than expected since it takes scheduling of the process receiving nodedown , etc ... {IArg, Min, Max} = case CheckIntensityArg of false -> {"", 7000, 17000}; true -> {" -kernel net_tickintensity 24", 10500, 13500} end, {ok, Node} = start_node(DCfg, Name1, "-kernel net_ticktime 12 -connect_all false" ++ IArg), rpc:call(Node, erl_distribution_SUITE, tick_cli_test, [ServNode, Min, Max]), spawn_link(erl_distribution_SUITE, keep_conn, [Node]), {tick_serv, ServNode} ! {i_want_the_result, self()}, monitor_node(ServNode, true), monitor_node(Node, true), receive {tick_test, T} when is_integer(T) -> stop_node(ServNode), stop_node(Node), io:format("Result: ~p~n", [T]), T; {tick_test, Error} -> stop_node(ServNode), stop_node(Node), ct:fail(Error); {nodedown, Node} -> stop_node(ServNode), ct:fail("client node died"); {nodedown, ServNode} -> stop_node(Node), ct:fail("server node died") end, ok. table_waste(Config) when is_list(Config) -> run_dist_configs(fun table_waste/2, Config). table_waste(DCfg, _Config) -> {ok, HName} = inet:gethostname(), F = fun(0,_F) -> []; (N,F) -> Name = list_to_atom("erl_distribution_"++integer_to_list(N)++ "@"++HName), pang = net_adm:ping(Name), F(N-1,F) end, F(256,F), {ok, N} = start_node(DCfg, erl_distribution_300), stop_node(N), ok. nodenames(Config) when is_list(Config) -> legal("a1@b"), legal("a-1@b"), legal("a_1@b"), Test that giving two -sname works as it should started = test_node("a_1@b", false, long_or_short() ++ "a_0@b"), illegal("cdé@a"), illegal("te欢st@a"). hostnames(Config) when is_list(Config) -> Host = gethostname(), legal([$a,$@|atom_to_list(Host)]), legal("1@b1"), legal("b@b1-c"), legal("c@b1_c"), legal("d@b1#c"), legal("f@::1"), legal("g@1:bc3:4e3f:f20:0:1"), case file:native_name_encoding() of latin1 -> ignore; _ -> legal("e@b1é") end, long_hostnames(net_kernel:longnames()), illegal("h@testالع"), illegal("i@языtest"), illegal("j@te欢st"). long_hostnames(true) -> legal(""), legal(""), legal("_c.d"), legal("[email protected]"), legal("[email protected]"); long_hostnames(false) -> illegal(""). legal(Name) -> case test_node(Name) of started -> ok; not_started -> ct:fail("no ~p node started", [Name]) end. illegal(Name) -> case test_node(Name, true) of not_started -> ok; started -> ct:fail("~p node started with illegal name", [Name]) end. test_node(Name) -> test_node(Name, false). test_node(Name, Illegal) -> test_node(Name, Illegal, ""). test_node(Name, Illegal, ExtraArgs) -> ProgName = ct:get_progname(), Command = ProgName ++ " -noinput " ++ long_or_short() ++ Name ++ ExtraArgs ++ " -eval \"net_adm:ping('" ++ atom_to_list(node()) ++ "')\"" ++ case Illegal of true -> " -eval \"timer:sleep(10000),init:stop().\""; false -> "" end, net_kernel:monitor_nodes(true), BinCommand = unicode:characters_to_binary(Command, utf8), _Prt = open_port({spawn, BinCommand}, [stream,{cd,"hostnames_nodedir"}]), Node = list_to_atom(Name), receive {nodeup, Node} -> net_kernel:monitor_nodes(false), slave:stop(Node), started after 5000 -> net_kernel:monitor_nodes(false), not_started end. long_or_short() -> case net_kernel:longnames() of true -> " -name "; false -> " -sname " end. gethostname() -> Hostname = case net_kernel:longnames() of true-> net_adm:localhost(); _-> {ok, Name}=inet:gethostname(), Name end, list_to_atom(Hostname). illegal_nodenames(Config) when is_list(Config) -> run_dist_configs(fun illegal_nodenames/2, Config). illegal_nodenames(DCfg, _Config) -> {ok, Node}=start_node(DCfg, illegal_nodenames), monitor_node(Node, true), RPid=rpc:call(Node, erlang, spawn, [?MODULE, pinger, [self()]]), receive {RPid, pinged} -> monitor_node(Node, false), ok; {nodedown, Node} -> ct:fail("Remote node died.") end, stop_node(Node), ok. pinger(Starter) -> io:format("Starter:~p~n",[Starter]), net_adm:ping(a@b@c), Starter ! {self(), pinged}, ok. Test that you can set the net_setuptime properly . net_setuptime(Config) when is_list(Config) -> run_dist_configs(fun net_setuptime/2, Config). net_setuptime(DCfg, _Config) -> Res0 = do_test_setuptime(DCfg, "2"), io:format("Res0 = ~p", [Res0]), true = (Res0 =< 4000), Res1 = do_test_setuptime(DCfg, "0.3"), io:format("Res1 = ~p", [Res1]), true = (Res1 =< 500), ok. do_test_setuptime(DCfg, Setuptime) when is_list(Setuptime) -> {ok, Node} = start_node(DCfg, dist_setuptime_test, "-kernel net_setuptime " ++ Setuptime), Res = rpc:call(Node,?MODULE,time_ping,[?DUMMY_NODE]), stop_node(Node), Res. time_ping(Node) -> T0 = erlang:monotonic_time(), pang = net_adm:ping(Node), T1 = erlang:monotonic_time(), erlang:convert_time_unit(T1 - T0, native, millisecond). keep_conn(Node) -> sleep(1), rpc:cast(Node, erlang, time, []), keep_conn(Node). tick_serv_test(Node, MasterNode) -> spawn(erl_distribution_SUITE, keep_conn, [MasterNode]), spawn(erl_distribution_SUITE, tick_serv_test1, [Node]). tick_serv_test1(Node) -> register(tick_serv, self()), TestServer = receive {i_want_the_result, TS} -> TS end, monitor_node(Node, true), receive {nodedown, Node} -> {tick_test, Node} ! {whats_the_result, self()}, receive {tick_test, Res} -> TestServer ! {tick_test, Res} end end. tick_cli_test(Node, Min, Max) -> spawn(erl_distribution_SUITE, tick_cli_test1, [Node, Min, Max]). tick_cli_test1(Node, Min, Max) -> register(tick_test, self()), erlang:monitor_node(Node, true), sleep(2), T1 = erlang:monotonic_time(), receive {nodedown, Node} -> T2 = erlang:monotonic_time(), receive {whats_the_result, From} -> Diff = erlang:convert_time_unit(T2-T1, native, millisecond), case Diff of T when Min =< T, T =< Max -> From ! {tick_test, T}; T -> From ! {tick_test, {"T not in interval " ++ integer_to_list(Min) ++ " =< T =< " ++ integer_to_list(Max), T}} end end end. epmd_reconnect(Config) when is_list(Config) -> NodeNames = [N1,N2,N3] = get_nodenames(3, ?FUNCTION_NAME), Nodes = [atom_to_list(full_node_name(NN)) || NN <- NodeNames], DCfg = "-epmd_port "++?ALT_EPMD_PORT, {_N1F,Port1} = start_node_unconnected(DCfg, N1, ?MODULE, run_remote_test, ["epmd_reconnect_do", atom_to_list(node()), "1" | Nodes]), {_N2F,Port2} = start_node_unconnected(DCfg, N2, ?MODULE, run_remote_test, ["epmd_reconnect_do", atom_to_list(node()), "2" | Nodes]), {_N3F,Port3} = start_node_unconnected(DCfg, N3, ?MODULE, run_remote_test, ["epmd_reconnect_do", atom_to_list(node()), "3" | Nodes]), Ports = [Port1, Port2, Port3], ok = reap_ports(Ports), ok. reap_ports([]) -> ok; reap_ports(Ports) -> case (receive M -> M end) of {Port, Message} -> case lists:member(Port, Ports) andalso Message of {data,String} -> io:format("~p: ~s\n", [Port, String]), reap_ports(Ports); {exit_status,0} -> reap_ports(Ports -- [Port]) end end. epmd_reconnect_do(_Node, ["1", Node1, Node2, Node3]) -> Names = [Name || Name <- [hd(string:tokens(Node, "@")) || Node <- [Node1, Node2, Node3]]], ok = wait_for_names(Names), "Killed" ++_ = os:cmd(?ALT_EPMD_CMD++" -kill"), open_port({spawn, ?ALT_EPMD_CMD}, []), ok = wait_for_names(Names), lists:foreach(fun(Node) -> ANode = list_to_atom(Node), pong = net_adm:ping(ANode), {epmd_reconnect_do, ANode} ! {stop, Node1, Node} end, [Node2, Node3]), ok; epmd_reconnect_do(_Node, ["2", Node1, Node2, _Node3]) -> register(epmd_reconnect_do, self()), receive {stop, Node1, Node2} -> ok after 7000 -> exit(timeout) end; epmd_reconnect_do(_Node, ["3", Node1, _Node2, Node3]) -> register(epmd_reconnect_do, self()), receive {stop, Node1, Node3} -> ok after 7000 -> exit(timeout) end. wait_for_names(Names) -> wait for up to 3 seconds ( the current retry timer in erl_epmd is 2s ) wait_for_names(lists:sort(Names), 30, 100). wait_for_names(Names, N, Wait) when N > 0 -> try {ok, Info} = erl_epmd:names(), Names = lists:sort([Name || {Name, _Port} <- Info]), ok catch error:{badmatch, _} -> timer:sleep(Wait), wait_for_names(Names, N-1, Wait) end. dyn_node_name(Config) when is_list(Config) -> run_dist_configs(fun dyn_node_name/2, Config). dyn_node_name(DCfg, _Config) -> NameDomain = case net_kernel:get_state() of #{name_domain := shortnames} -> "shortnames"; #{name_domain := longnames} -> "longnames" end, {_N1F,Port1} = start_node_unconnected(DCfg, undefined, ?MODULE, run_remote_test, ["dyn_node_name_do", atom_to_list(node()), NameDomain]), 0 = wait_for_port_exit(Port1), ok. dyn_node_name_do(TestNode, [NameDomainStr]) -> nonode@nohost = node(), [] = nodes(), [] = nodes(hidden), NameDomain = list_to_atom(NameDomainStr), #{started := static, name_type := dynamic, name := undefined, name_domain := NameDomain} = net_kernel:get_state(), net_kernel:monitor_nodes(true, [{node_type,all}]), net_kernel:connect_node(TestNode), [] = nodes(), [TestNode] = nodes(hidden), MyName = node(), false = (MyName =:= undefined), false = (MyName =:= nonode@nohost), #{started := static, name_type := dynamic, name := MyName, name_domain := NameDomain} = net_kernel:get_state(), check([MyName], rpc:call(TestNode, erlang, nodes, [hidden])), {nodeup, MyName, [{node_type, visible}]} = receive_any(), {nodeup, TestNode, [{node_type, hidden}]} = receive_any(), true = net_kernel:disconnect(TestNode), We do n't know the order of these nodedown messages . Often nodedown from the connection comes first , but not always ... NodedownMsgsA = lists:sort([{nodedown, TestNode, [{node_type, hidden}]}, {nodedown, MyName, [{node_type, visible}]}]), NodedownMsgA1 = receive_any(), NodedownMsgA2 = receive_any(), NodedownMsgsA = lists:sort([NodedownMsgA1, NodedownMsgA2]), [] = nodes(hidden), nonode@nohost = node(), #{started := static, name_type := dynamic, name := undefined, name_domain := NameDomain} = net_kernel:get_state(), net_kernel:connect_node(TestNode), [] = nodes(), [TestNode] = nodes(hidden), MyName = node(), #{started := static, name_type := dynamic, name := MyName, name_domain := NameDomain} = net_kernel:get_state(), check([MyName], rpc:call(TestNode, erlang, nodes, [hidden])), {nodeup, MyName, [{node_type, visible}]} = receive_any(), {nodeup, TestNode, [{node_type, hidden}]} = receive_any(), true = rpc:cast(TestNode, net_kernel, disconnect, [MyName]), We do n't know the order of these nodedown messages . Often nodedown from the connection comes first , but not always ... NodedownMsgsB = lists:sort([{nodedown, TestNode, [{node_type, hidden}]}, {nodedown, MyName, [{node_type, visible}]}]), NodedownMsgB1 = receive_any(), NodedownMsgB2 = receive_any(), NodedownMsgsB = lists:sort([NodedownMsgB1, NodedownMsgB2]), [] = nodes(hidden), nonode@nohost = node(), #{started := static, name_type := dynamic, name := undefined, name_domain := NameDomain} = net_kernel:get_state(), ok. check(X, X) -> ok. setopts(Config) when is_list(Config) -> run_dist_configs(fun setopts/2, Config). setopts(DCfg, _Config) -> register(setopts_regname, self()), [N1,N2,N3,N4,N5] = get_nodenames(5, setopts), {_N1F,Port1} = start_node_unconnected(DCfg, N1, ?MODULE, run_remote_test, ["setopts_do", atom_to_list(node()), "1", "ping"]), 0 = wait_for_port_exit(Port1), {_N2F,Port2} = start_node_unconnected(DCfg, N2, ?MODULE, run_remote_test, ["setopts_do", atom_to_list(node()), "2", "ping"]), 0 = wait_for_port_exit(Port2), {ok, LSock} = gen_tcp:listen(0, [{packet,2}, {active,false}]), {ok, LTcpPort} = inet:port(LSock), {N3F,Port3} = start_node_unconnected(DCfg, N3, ?MODULE, run_remote_test, ["setopts_do", atom_to_list(node()), "1", integer_to_list(LTcpPort)]), wait_and_connect(LSock, N3F, Port3), 0 = wait_for_port_exit(Port3), {N4F,Port4} = start_node_unconnected(DCfg, N4, ?MODULE, run_remote_test, ["setopts_do", atom_to_list(node()), "2", integer_to_list(LTcpPort)]), wait_and_connect(LSock, N4F, Port4), 0 = wait_for_port_exit(Port4), net_kernel : setopts(new , _ ) used to be able to produce a deadlock in net_kernel . / OTP-18198 {N5F,Port5} = start_node_unconnected(DCfg, N5, ?MODULE, run_remote_test, ["setopts_deadlock_test", atom_to_list(node()), integer_to_list(LTcpPort)]), wait_and_connect(LSock, N5F, Port5), repeat(fun () -> receive after 10 -> ok end, erlang:disconnect_node(N5F), WD = spawn_link(fun () -> receive after 2000 -> ok end, exit({net_kernel_probably_deadlocked, N5F}) end), pong = net_adm:ping(N5F), unlink(WD), exit(WD, kill), false = is_process_alive(WD) end, 200), try erpc:call(N5F, erlang, halt, []) catch error:{erpc,noconnection} -> ok end, 0 = wait_for_port_exit(Port5), unregister(setopts_regname), ok. wait_and_connect(LSock, NodeName, NodePort) -> {ok, Sock} = gen_tcp:accept(LSock), {ok, "Connect please"} = gen_tcp:recv(Sock, 0), flush_from_port(NodePort), pong = net_adm:ping(NodeName), gen_tcp:send(Sock, "Connect done"), gen_tcp:close(Sock). flush_from_port(Port) -> flush_from_port(Port, 10). flush_from_port(Port, Timeout) -> receive {Port,{data,String}} -> io:format("~p: ~s\n", [Port, String]), flush_from_port(Port, Timeout) after Timeout -> timeout end. wait_for_port_exit(Port) -> case (receive M -> M end) of {Port,{exit_status,Status}} -> Status; {Port,{data,String}} -> io:format("~p: ~s\n", [Port, String]), wait_for_port_exit(Port) end. run_remote_test([FuncStr, TestNodeStr | Args]) -> Status = try io:format("Node ~p started~n", [node()]), TestNode = list_to_atom(TestNodeStr), io:format("Node ~p spawning function ~p~n", [node(), FuncStr]), {Pid,Ref} = spawn_monitor(?MODULE, list_to_atom(FuncStr), [TestNode, Args]), io:format("Node ~p waiting for function ~p~n", [node(), FuncStr]), receive {'DOWN', Ref, process, Pid, normal} -> 0; Other -> io:format("Node ~p got unexpected msg: ~p\n",[node(), Other]), 1 end catch C:E:S -> io:format("Node ~p got EXCEPTION ~p:~p\nat ~p\n", [node(), C, E, S]), 2 end, io:format("Node ~p doing halt(~p).\n",[node(), Status]), erlang:halt(Status). setopts_do(TestNode, [OptNr, ConnectData]) -> [] = nodes(), {Opt, Val} = opt_from_nr(OptNr), ok = net_kernel:setopts(new, [{Opt, Val}]), [] = nodes(), {error, noconnection} = net_kernel:getopts(TestNode, [Opt]), case ConnectData of net_adm:ping(TestNode); {ok, Sock} = gen_tcp:connect("localhost", list_to_integer(TcpPort), [{active,false},{packet,2}]), ok = gen_tcp:send(Sock, "Connect please"), {ok, "Connect done"} = gen_tcp:recv(Sock, 0), gen_tcp:close(Sock) end, [TestNode] = nodes(), {ok, [{Opt,Val}]} = net_kernel:getopts(TestNode, [Opt]), {error, noconnection} = net_kernel:getopts('pixie@fairyland', [Opt]), NewVal = change_val(Val), ok = net_kernel:setopts(TestNode, [{Opt, NewVal}]), {ok, [{Opt,NewVal}]} = net_kernel:getopts(TestNode, [Opt]), ok = net_kernel:setopts(TestNode, [{Opt, Val}]), {ok, [{Opt,Val}]} = net_kernel:getopts(TestNode, [Opt]), ok. setopts_deadlock_test(_TestNode, [TcpPort]) -> {ok, Sock} = gen_tcp:connect("localhost", list_to_integer(TcpPort), [{active,false},{packet,2}]), ok = gen_tcp:send(Sock, "Connect please"), {ok, "Connect done"} = gen_tcp:recv(Sock, 0), gen_tcp:close(Sock), setopts_new_loop(). setopts_new_loop() -> ok = net_kernel:setopts(new, [{nodelay, true}]), receive after 10 -> ok end, setopts_new_loop(). opt_from_nr("1") -> {nodelay, true}; opt_from_nr("2") -> {nodelay, false}. change_val(true) -> false; change_val(false) -> true. start_node_unconnected(DCfg, Name, Mod, Func, Args) -> start_node_unconnected(DCfg, Name, erlang:get_cookie(), Mod, Func, Args). start_node_unconnected(DCfg, Name, Cookie, Mod, Func, Args) -> FullName = full_node_name(Name), CmdLine = mk_node_cmdline(DCfg, Name, Cookie, Mod, Func, Args), io:format("Starting node ~p: ~s~n", [FullName, CmdLine]), case open_port({spawn, CmdLine}, [exit_status]) of Port when is_port(Port) -> {FullName, Port}; Error -> exit({failed_to_start_node, FullName, Error}) end. full_node_name(PreName) when is_atom(PreName) -> full_node_name(atom_to_list(PreName)); full_node_name(PreNameL) when is_list(PreNameL) -> HostSuffix = lists:dropwhile(fun ($@) -> false; (_) -> true end, atom_to_list(node())), list_to_atom(PreNameL ++ HostSuffix). mk_node_cmdline(DCfg, Name, Cookie, Mod, Func, Args) -> Static = "-noinput", Pa = filename:dirname(code:which(?MODULE)), Prog = case catch init:get_argument(progname) of {ok,[[P]]} -> P; _ -> exit(no_progname_argument_found) end, NameSw = case net_kernel:longnames() of false -> "-sname "; true -> "-name "; _ -> exit(not_distributed_node) end, {ok, Pwd} = file:get_cwd(), NameStr = atom_to_list(Name), Prog ++ " " ++ Static ++ " " ++ NameSw ++ " " ++ NameStr ++ " " ++ DCfg ++ " -pa " ++ Pa ++ " -env ERL_CRASH_DUMP " ++ Pwd ++ "/erl_crash_dump." ++ NameStr ++ " -setcookie " ++ atom_to_list(Cookie) ++ " -run " ++ atom_to_list(Mod) ++ " " ++ atom_to_list(Func) ++ " " ++ string:join(Args, " "). tick_change(Config) when is_list(Config) -> run_dist_configs(fun tick_change/2, Config). tick_change(DCfg, _Config) -> [BN, CN] = get_nodenames(2, tick_change), DefaultTT = net_kernel:get_net_ticktime(), unchanged = net_kernel:set_net_ticktime(DefaultTT, 60), case DefaultTT of I when is_integer(I) -> ok; _ -> ct:fail(DefaultTT) end, case nodes(connected) of [] -> net_kernel:set_net_ticktime(10, 0); _ -> rpc:multicall(nodes([this, connected]), net_kernel, set_net_ticktime, [10, 5]) end, wait_until(fun () -> 10 == net_kernel:get_net_ticktime() end), {ok, B} = start_node(DCfg, BN, "-kernel net_ticktime 10 -connect_all false"), {ok, C} = start_node(DCfg, CN, "-kernel net_ticktime 10 -hidden"), OTE = process_flag(trap_exit, true), case catch begin run_tick_change_test(DCfg, B, C, 10, 1), run_tick_change_test(DCfg, B, C, 1, 10) end of {'EXIT', Reason} -> stop_node(B), stop_node(C), case nodes(connected) of [] -> net_kernel:set_net_ticktime(DefaultTT, 0); _ -> rpc:multicall(nodes([this, connected]), net_kernel, set_net_ticktime, [DefaultTT, 10]) end, wait_until(fun () -> DefaultTT == net_kernel:get_net_ticktime() end), process_flag(trap_exit, OTE), ct:fail(Reason); _ -> ok end, process_flag(trap_exit, OTE), stop_node(B), stop_node(C), case nodes(connected) of [] -> net_kernel:set_net_ticktime(DefaultTT, 0); _ -> rpc:multicall(nodes([this, connected]), net_kernel, set_net_ticktime, [DefaultTT, 5]) end, wait_until(fun () -> DefaultTT == net_kernel:get_net_ticktime() end), ok. wait_for_nodedowns(Tester, Ref) -> receive {nodedown, Node} -> io:format("~p~n", [{node(), {nodedown, Node}}]), Tester ! {Ref, {node(), {nodedown, Node}}} end, wait_for_nodedowns(Tester, Ref). run_tick_change_test(DCfg, B, C, PrevTT, TT) -> [DN, EN] = get_nodenames(2, tick_change), Tester = self(), Ref = make_ref(), MonitorNodes = fun (Nodes) -> lists:foreach( fun (N) -> monitor_node(N,true) end, Nodes), wait_for_nodedowns(Tester, Ref) end, {ok, D} = start_node(DCfg, DN, "-connect_all false -kernel net_ticktime " ++ integer_to_list(PrevTT)), NMA = spawn_link(fun () -> MonitorNodes([B, C, D]) end), NMB = spawn_link(B, fun () -> MonitorNodes([node(), C, D]) end), NMC = spawn_link(C, fun () -> MonitorNodes([node(), B, D]) end), MaxTT = case PrevTT > TT of true -> PrevTT; false -> TT end, CheckResult = make_ref(), spawn_link(fun () -> receive after (25 + MaxTT)*1000 -> Tester ! CheckResult end end), case nodes(connected) -- [B, C, D] of [] -> ok; OtherNodes -> rpc:multicall(OtherNodes, net_kernel, set_net_ticktime, [TT, 20]) end, change_initiated = net_kernel:set_net_ticktime(TT,20), {ongoing_change_to,_} = net_kernel:set_net_ticktime(TT,20), sleep(3), change_initiated = rpc:call(B,net_kernel,set_net_ticktime,[TT,15]), sleep(7), change_initiated = rpc:call(C,net_kernel,set_net_ticktime,[TT,10]), {ok, E} = start_node(DCfg, EN, "-connect_all false -kernel net_ticktime " ++ integer_to_list(TT)), NME = spawn_link(E, fun () -> MonitorNodes([node(), B, C, D]) end), NMA2 = spawn_link(fun () -> MonitorNodes([E]) end), NMB2 = spawn_link(B, fun () -> MonitorNodes([E]) end), NMC2 = spawn_link(C, fun () -> MonitorNodes([E]) end), receive CheckResult -> ok end, unlink(NMA), exit(NMA, kill), unlink(NMB), exit(NMB, kill), unlink(NMC), exit(NMC, kill), unlink(NME), exit(NME, kill), unlink(NMA2), exit(NMA2, kill), unlink(NMB2), exit(NMB2, kill), unlink(NMC2), exit(NMC2, kill), receive {Ref, {Node, {nodedown, D}}} when Node == node() -> ok after 0 -> exit({?LINE, no_nodedown}) end, receive {Ref, {B, {nodedown, D}}} -> ok after 0 -> exit({?LINE, no_nodedown}) end, receive {Ref, {C, {nodedown, D}}} -> ok after 0 -> exit({?LINE, no_nodedown}) end, receive {Ref, {E, {nodedown, D}}} -> ok after 0 -> exit({?LINE, no_nodedown}) end, receive {Ref, Reason} -> stop_node(E), exit({?LINE, Reason}); {'EXIT', Pid, Reason} when Pid == NMA; Pid == NMB; Pid == NMC; Pid == NME; Pid == NMA2; Pid == NMB2; Pid == NMC2 -> stop_node(E), exit({?LINE, {node(Pid), Reason}}) after 0 -> TT = net_kernel:get_net_ticktime(), TT = rpc:call(B, net_kernel, get_net_ticktime, []), TT = rpc:call(C, net_kernel, get_net_ticktime, []), TT = rpc:call(E, net_kernel, get_net_ticktime, []), stop_node(E), ok end. hidden_node(Config) when is_list(Config) -> run_dist_configs(fun hidden_node/2, Config). hidden_node(DCfg, Config) -> hidden_node(DCfg, "-hidden", Config), hidden_node(DCfg, "-hidden -hidden", Config), hidden_node(DCfg, "-hidden true -hidden true", Config), ok. hidden_node(DCfg, HArgs, _Config) -> ct:pal("--- Hidden argument(s): ~s~n", [HArgs]), {ok, V} = start_node(DCfg, visible_node), VMN = start_monitor_nodes_proc(V), {ok, H} = start_node(DCfg, hidden_node, HArgs), Connect visible_node - > hidden_node connect_nodes(V, H), test_nodes(V, H), stop_node(H), sleep(5), check_monitor_nodes_res(VMN, H), stop_node(V), {ok, H} = start_node(DCfg, hidden_node, HArgs), HMN = start_monitor_nodes_proc(H), {ok, V} = start_node(DCfg, visible_node), Connect hidden_node - > visible_node connect_nodes(H, V), test_nodes(V, H), stop_node(V), sleep(5), check_monitor_nodes_res(HMN, V), stop_node(H), ok. connect_nodes(A, B) -> false = lists:member(A, rpc:call(B, erlang, nodes, [connected])), false = lists:member(B, rpc:call(A, erlang, nodes, [connected])), Connect them . pong = rpc:call(A, net_adm, ping, [B]). test_nodes(V, H) -> [] = rpc:call(H, erlang, nodes, []), true = lists:member(V, rpc:call(H, erlang, nodes, [hidden])), false = lists:member(H, rpc:call(V, erlang, nodes, [])), true = lists:member(H, rpc:call(V, erlang, nodes, [hidden])). mn_loop(MNs) -> receive {nodeup, N} -> mn_loop([{nodeup, N}|MNs]); {nodedown, N} -> mn_loop([{nodedown, N}|MNs]); {monitor_nodes_result, Ref, From} -> From ! {Ref, MNs}; _ -> mn_loop(MNs) end. start_monitor_nodes_proc(Node) -> Ref = make_ref(), Starter = self(), Pid = spawn(Node, fun() -> net_kernel:monitor_nodes(true), Starter ! Ref, mn_loop([]) end), receive Ref -> ok end, Pid. check_monitor_nodes_res(Pid, Node) -> Ref = make_ref(), Pid ! {monitor_nodes_result, Ref, self()}, receive {Ref, MNs} -> false = lists:keysearch(Node, 2, MNs) end. inet_dist_options_options(Config) when is_list(Config) -> Prio = 1, case gen_udp:open(0, [{priority,Prio}]) of {ok,Socket} -> case inet:getopts(Socket, [priority]) of {ok,[{priority,Prio}]} -> ok = gen_udp:close(Socket), do_inet_dist_options_options(Prio); _ -> ok = gen_udp:close(Socket), {skip, "Can not set priority "++integer_to_list(Prio)++ " on socket"} end; {error,_} -> {skip, "Can not set priority on socket"} end. do_inet_dist_options_options(Prio) -> PriorityString0 = "[{priority,"++integer_to_list(Prio)++"}]", PriorityString = case os:cmd("echo [{a,1}]") of "[{a,1}]"++_ -> PriorityString0; _ -> "'"++PriorityString0++"'" end, InetDistOptions = "-hidden " "-kernel inet_dist_connect_options "++PriorityString++" " "-kernel inet_dist_listen_options "++PriorityString, {ok,Node1} = start_node("", inet_dist_options_1, InetDistOptions), {ok,Node2} = start_node("", inet_dist_options_2, InetDistOptions), pong = rpc:call(Node1, net_adm, ping, [Node2]), PrioritiesNode1 = rpc:call(Node1, ?MODULE, get_socket_priorities, []), PrioritiesNode2 = rpc:call(Node2, ?MODULE, get_socket_priorities, []), io:format("PrioritiesNode1 = ~p", [PrioritiesNode1]), io:format("PrioritiesNode2 = ~p", [PrioritiesNode2]), Elevated = [P || P <- PrioritiesNode1, P =:= Prio], Elevated = [P || P <- PrioritiesNode2, P =:= Prio], [_|_] = Elevated, stop_node(Node2), stop_node(Node1), ok. get_socket_priorities() -> [Priority || {ok,[{priority,Priority}]} <- [inet:getopts(Port, [priority]) || Port <- erlang:ports(), element(2, erlang:port_info(Port, name)) =:= "tcp_inet"]]. net_ticker_spawn_options(Config) when is_list(Config) -> run_dist_configs(fun net_ticker_spawn_options/2, Config). net_ticker_spawn_options(DCfg, Config) when is_list(Config) -> FullsweepString0 = "[{fullsweep_after,0}]", FullsweepString = case os:cmd("echo [{a,1}]") of "[{a,1}]"++_ -> FullsweepString0; _ -> "'"++FullsweepString0++"'" end, InetDistOptions = "-hidden " "-kernel net_ticker_spawn_options "++FullsweepString, {ok,Node1} = start_node(DCfg, net_ticker_spawn_options_1, InetDistOptions), {ok,Node2} = start_node(DCfg, net_ticker_spawn_options_2, InetDistOptions), pong = erpc:call(Node1, net_adm, ping, [Node2]), FullsweepOptionNode1 = erpc:call(Node1, ?MODULE, get_net_ticker_fullsweep_option, [Node2]), FullsweepOptionNode2 = erpc:call(Node2, ?MODULE, get_net_ticker_fullsweep_option, [Node1]), io:format("FullsweepOptionNode1 = ~p", [FullsweepOptionNode1]), io:format("FullsweepOptionNode2 = ~p", [FullsweepOptionNode2]), 0 = FullsweepOptionNode1, 0 = FullsweepOptionNode2, stop_node(Node2), stop_node(Node1), ok. get_net_ticker_fullsweep_option(Node) -> Links = case proplists:get_value(Node, erlang:system_info(dist_ctrl)) of DistCtrl when is_port(DistCtrl) -> {links, Ls} = erlang:port_info(DistCtrl, links), Ls; DistCtrl when is_pid(DistCtrl) -> {links, Ls} = process_info(DistCtrl, links), Ls end, Ticker = try lists:foreach( fun (Pid) when is_pid(Pid) -> {current_stacktrace, Stk} = process_info(Pid, current_stacktrace), lists:foreach( fun ({dist_util, con_loop, _, _}) -> throw(Pid); (_) -> ok end, Stk); (_) -> ok end, Links), error(no_ticker_found) catch throw:Pid when is_pid(Pid) -> Pid end, {garbage_collection, GCOpts} = erlang:process_info(Ticker, garbage_collection), proplists:get_value(fullsweep_after, GCOpts). : monitor_nodes_nodedown_reason monitor_nodes_nodedown_reason(Config) when is_list(Config) -> run_dist_configs(fun monitor_nodes_nodedown_reason/2, Config). monitor_nodes_nodedown_reason(DCfg, _Config) -> MonNodeState = monitor_node_state(), ok = net_kernel:monitor_nodes(true), ok = net_kernel:monitor_nodes(true, [nodedown_reason]), Names = get_numbered_nodenames(5, node), [NN1, NN2, NN3, NN4, NN5] = Names, {ok, N1} = start_node(DCfg, NN1, "-connect_all false"), {ok, N2} = start_node(DCfg, NN2, "-connect_all false"), {ok, N3} = start_node(DCfg, NN3, "-connect_all false"), {ok, N4} = start_node(DCfg, NN4, "-hidden"), receive {nodeup, N1} -> ok end, receive {nodeup, N2} -> ok end, receive {nodeup, N3} -> ok end, receive {nodeup, N1, []} -> ok end, receive {nodeup, N2, []} -> ok end, receive {nodeup, N3, []} -> ok end, stop_node(N1), stop_node(N4), true = net_kernel:disconnect(N2), TickTime = net_kernel:get_net_ticktime(), SleepTime = TickTime + (TickTime div 2), spawn(N3, fun () -> block_emu(SleepTime*1000), halt() end), receive {nodedown, N1} -> ok end, receive {nodedown, N2} -> ok end, receive {nodedown, N3} -> ok end, receive {nodedown, N1, [{nodedown_reason, R1}]} -> connection_closed = R1 end, receive {nodedown, N2, [{nodedown_reason, R2}]} -> disconnect = R2 end, receive {nodedown, N3, [{nodedown_reason, R3}]} -> net_tick_timeout = R3 end, ok = net_kernel:monitor_nodes(false, [nodedown_reason]), {ok, N5} = start_node(DCfg, NN5), stop_node(N5), receive {nodeup, N5} -> ok end, receive {nodedown, N5} -> ok end, print_my_messages(), ok = check_no_nodedown_nodeup(1000), ok = net_kernel:monitor_nodes(false), MonNodeState = monitor_node_state(), ok. monitor_nodes_complex_nodedown_reason(Config) when is_list(Config) -> run_dist_configs(fun monitor_nodes_complex_nodedown_reason/2, Config). monitor_nodes_complex_nodedown_reason(DCfg, _Config) -> MonNodeState = monitor_node_state(), Me = self(), ok = net_kernel:monitor_nodes(true, [nodedown_reason]), [Name] = get_nodenames(1, monitor_nodes_complex_nodedown_reason), {ok, Node} = start_node(DCfg, Name, ""), Pid = spawn(Node, fun() -> Me ! {stuff, self(), [make_ref(), {processes(), erlang:ports()}]} end), receive {nodeup, Node, []} -> ok end, {ok, NodeInfo} = net_kernel:node_info(Node), {value,{owner, Owner}} = lists:keysearch(owner, 1, NodeInfo), ComplexTerm = receive {stuff, Pid, _} = Msg -> {Msg, term_to_binary(Msg)} end, exit(Owner, ComplexTerm), receive {nodedown, Node, [{nodedown_reason, NodeDownReason}]} -> ok end, garbage_collect(), garbage_collect(), garbage_collect(), ComplexTerm = NodeDownReason, ok = net_kernel:monitor_nodes(false, [nodedown_reason]), no_msgs(), MonNodeState = monitor_node_state(), ok. : monitor_nodes_node_type(Config) when is_list(Config) -> run_dist_configs(fun monitor_nodes_node_type/2, Config). monitor_nodes_node_type(DCfg, _Config) -> MonNodeState = monitor_node_state(), ok = net_kernel:monitor_nodes(true), ok = net_kernel:monitor_nodes(true, [{node_type, all}]), Names = get_numbered_nodenames(9, node), [NN1, NN2, NN3, NN4, NN5, NN6, NN7, NN8, NN9] = Names, {ok, N1} = start_node(DCfg, NN1), {ok, N2} = start_node(DCfg, NN2), {ok, N3} = start_node(DCfg, NN3, "-hidden"), {ok, N4} = start_node(DCfg, NN4, "-hidden"), receive {nodeup, N1} -> ok end, receive {nodeup, N2} -> ok end, receive {nodeup, N1, [{node_type, visible}]} -> ok end, receive {nodeup, N2, [{node_type, visible}]} -> ok end, receive {nodeup, N3, [{node_type, hidden}]} -> ok end, receive {nodeup, N4, [{node_type, hidden}]} -> ok end, stop_node(N1), stop_node(N2), stop_node(N3), stop_node(N4), receive {nodedown, N1} -> ok end, receive {nodedown, N2} -> ok end, receive {nodedown, N1, [{node_type, visible}]} -> ok end, receive {nodedown, N2, [{node_type, visible}]} -> ok end, receive {nodedown, N3, [{node_type, hidden}]} -> ok end, receive {nodedown, N4, [{node_type, hidden}]} -> ok end, ok = net_kernel:monitor_nodes(false, [{node_type, all}]), {ok, N5} = start_node(DCfg, NN5), receive {nodeup, N5} -> ok end, stop_node(N5), receive {nodedown, N5} -> ok end, ok = net_kernel:monitor_nodes(true, [{node_type, hidden}]), {ok, N6} = start_node(DCfg, NN6), {ok, N7} = start_node(DCfg, NN7, "-hidden"), receive {nodeup, N6} -> ok end, receive {nodeup, N7, [{node_type, hidden}]} -> ok end, stop_node(N6), stop_node(N7), receive {nodedown, N6} -> ok end, receive {nodedown, N7, [{node_type, hidden}]} -> ok end, ok = net_kernel:monitor_nodes(true, [{node_type, visible}]), ok = net_kernel:monitor_nodes(false, [{node_type, hidden}]), ok = net_kernel:monitor_nodes(false), {ok, N8} = start_node(DCfg, NN8), {ok, N9} = start_node(DCfg, NN9, "-hidden"), receive {nodeup, N8, [{node_type, visible}]} -> ok end, stop_node(N8), stop_node(N9), receive {nodedown, N8, [{node_type, visible}]} -> ok end, print_my_messages(), ok = check_no_nodedown_nodeup(1000), ok = net_kernel:monitor_nodes(false, [{node_type, visible}]), MonNodeState = monitor_node_state(), ok. : monitor_nodes_misc(Config) when is_list(Config) -> run_dist_configs(fun monitor_nodes_misc/2, Config). monitor_nodes_misc(DCfg, _Config) -> MonNodeState = monitor_node_state(), ok = net_kernel:monitor_nodes(true), ok = net_kernel:monitor_nodes(true, [{node_type, all}, nodedown_reason]), ok = net_kernel:monitor_nodes(true, [nodedown_reason, {node_type, all}, connection_id]), ok = net_kernel:monitor_nodes(true, #{node_type => all, nodedown_reason => true}), ok = net_kernel:monitor_nodes(true, #{node_type => all, nodedown_reason => true, connection_id => true}), Names = get_numbered_nodenames(3, node), [NN1, NN2, NN3] = Names, {ok, N1} = start_node(DCfg, NN1), {ok, N2} = start_node(DCfg, NN2, "-hidden"), receive {nodeup, N1} -> ok end, receive {nodeup, N1, #{node_type := visible}} -> ok end, receive {nodeup, N2, #{node_type := hidden}} -> ok end, receive {nodeup, N1, [{node_type, visible}]} -> ok end, receive {nodeup, N2, [{node_type, hidden}]} -> ok end, NodesInfo = erlang:nodes(connected, #{connection_id => true}), {N1, #{connection_id := N1CId}} = lists:keyfind(N1, 1, NodesInfo), {N2, #{connection_id := N2CId}} = lists:keyfind(N2, 1, NodesInfo), ct:pal("N1: ~p ~p~n", [N1, N1CId]), ct:pal("N2: ~p ~p~n", [N2, N2CId]), receive {nodeup, N1, #{node_type := visible, connection_id := N1CId}} -> ok end, receive {nodeup, N2, #{node_type := hidden, connection_id := N2CId}} -> ok end, N1UpInfoSorted = lists:sort([{node_type, visible},{connection_id, N1CId}]), N2UpInfoSorted = lists:sort([{node_type, hidden},{connection_id, N2CId}]), receive {nodeup, N1, UpN1Info} -> N1UpInfoSorted = lists:sort(UpN1Info) end, receive {nodeup, N2, UpN2Info} -> N2UpInfoSorted = lists:sort(UpN2Info) end, stop_node(N1), stop_node(N2), receive {nodedown, N1} -> ok end, receive {nodedown, N1, #{node_type := visible, nodedown_reason := connection_closed}} -> ok end, receive {nodedown, N1, #{node_type := visible, nodedown_reason := connection_closed, connection_id := N1CId}} -> ok end, receive {nodedown, N2, #{node_type := hidden, nodedown_reason := connection_closed}} -> ok end, receive {nodedown, N2, #{node_type := hidden, nodedown_reason := connection_closed, connection_id := N2CId}} -> ok end, N1ADownInfoSorted = lists:sort([{node_type, visible}, {nodedown_reason, connection_closed}]), N1BDownInfoSorted = lists:sort([{node_type, visible}, {nodedown_reason, connection_closed}, {connection_id, N1CId}]), N2ADownInfoSorted = lists:sort([{node_type, hidden}, {nodedown_reason, connection_closed}]), N2BDownInfoSorted = lists:sort([{node_type, hidden}, {nodedown_reason, connection_closed}, {connection_id, N2CId}]), receive {nodedown, N1, N1Info1} -> case lists:sort(N1Info1) of N1ADownInfoSorted -> receive {nodedown, N1, N1Info2} -> N1BDownInfoSorted = lists:sort(N1Info2) end; N1BDownInfoSorted -> receive {nodedown, N1, N1Info2} -> N1ADownInfoSorted = lists:sort(N1Info2) end end end, receive {nodedown, N2, N2Info1} -> case lists:sort(N2Info1) of N2ADownInfoSorted -> receive {nodedown, N2, N2Info2} -> N2BDownInfoSorted = lists:sort(N2Info2) end; N2BDownInfoSorted -> receive {nodedown, N2, N2Info2} -> N2ADownInfoSorted = lists:sort(N2Info2) end end end, ok = net_kernel:monitor_nodes(false, [{node_type, all}, nodedown_reason]), ok = net_kernel:monitor_nodes(false, [nodedown_reason, {node_type, all}, connection_id]), ok = net_kernel:monitor_nodes(false, #{node_type => all, nodedown_reason => true}), ok = net_kernel:monitor_nodes(false, #{node_type => all, nodedown_reason => true, connection_id => true}), {ok, N3} = start_node(DCfg, NN3), receive {nodeup, N3} -> ok end, stop_node(N3), receive {nodedown, N3} -> ok end, print_my_messages(), ok = check_no_nodedown_nodeup(1000), ok = net_kernel:monitor_nodes(false), MonNodeState = monitor_node_state(), ok. messages from and that { nodedown , Node } messages are received after messages from Node . monitor_nodes_otp_6481(Config) when is_list(Config) -> run_dist_configs(fun monitor_nodes_otp_6481/2, Config). monitor_nodes_otp_6481(DCfg, Config) -> io:format("Testing nodedown...~n"), monitor_nodes_otp_6481_test(DCfg, Config, nodedown), io:format("ok~n"), io:format("Testing nodeup...~n"), monitor_nodes_otp_6481_test(DCfg, Config, nodeup), io:format("ok~n"), ok. monitor_nodes_otp_6481_test(DCfg, Config, TestType) when is_list(Config) -> MonNodeState = monitor_node_state(), NodeMsg = make_ref(), Me = self(), [Name] = get_nodenames(1, monitor_nodes_otp_6481), case TestType of nodedown -> ok = net_kernel:monitor_nodes(true); nodeup -> ok end, Seq = lists:seq(1,10000), MN = spawn_link( fun () -> lists:foreach( fun (_) -> ok = net_kernel:monitor_nodes(true) end, Seq), Me ! {mon_set, self()}, receive after infinity -> ok end end), receive {mon_set, MN} -> ok end, case TestType of nodedown -> ok; nodeup -> ok = net_kernel:monitor_nodes(true) end, nodedown test : Since this process was the first one monitoring nodes this process will be the first one notified on nodedown . TestMonNodeState = monitor_node_state(), TestMonNodeState = case TestType of nodedown -> []; nodeup -> [{self(), []}] end ++ lists:map(fun (_) -> {MN, []} end, Seq) ++ case TestType of nodedown -> [{self(), []}]; nodeup -> [] end ++ MonNodeState, {ok, Node} = start_node(DCfg, Name, "", this), receive {nodeup, Node} -> ok end, RemotePid = spawn(Node, fun () -> receive after 1500 -> ok end, infinite loop of msgs We then want to ensure that the nodedown message arrives _ = spawn(fun() -> node_loop_send(Me, NodeMsg, 1) end), receive {Me, kill_it} -> ok end, halt() end), net_kernel:disconnect(Node), receive {nodedown, Node} -> ok end, Verify that ' { nodeup , } ' comes before ' { NodeMsg , 1 } ' ( the message {nodeup, Node} = receive Msg1 -> Msg1 end, {NodeMsg, N} = receive Msg2 -> Msg2 end, RemotePid ! {self(), kill_it}, Verify that ' { nodedown , Node } ' comes after the last ' { NodeMsg , N } ' {nodedown, Node} = flush_node_msgs(NodeMsg, N+1), no_msgs(500), Mon = erlang:monitor(process, MN), unlink(MN), exit(MN, bang), receive {'DOWN', Mon, process, MN, bang} -> ok end, ok = net_kernel:monitor_nodes(false), MonNodeState = monitor_node_state(), ok. flush_node_msgs(NodeMsg, No) -> case receive Msg -> Msg end of {NodeMsg, N} when N >= No -> flush_node_msgs(NodeMsg, N+1); OtherMsg -> OtherMsg end. node_loop_send(Pid, Msg, No) -> Pid ! {Msg, No}, node_loop_send(Pid, Msg, No + 1). monitor_nodes_errors(Config) when is_list(Config) -> MonNodeState = monitor_node_state(), error = net_kernel:monitor_nodes(asdf), {error, {unknown_options, [gurka]}} = net_kernel:monitor_nodes(true, [gurka]), {error, {unknown_options, #{gurka := true}}} = net_kernel:monitor_nodes(true, #{gurka => true}), {error, {invalid_options, gurka}} = net_kernel:monitor_nodes(true, gurka), {error, {option_value_mismatch, [{node_type,visible}, {node_type,hidden}]}} = net_kernel:monitor_nodes(true, [{node_type,hidden}, {node_type,visible}]), {error, {option_value_mismatch, [{node_type,visible}, {node_type,all}]}} = net_kernel:monitor_nodes(true, [{node_type,all}, {node_type,visible}]), {error, {bad_option_value, {node_type, blaha}}} = net_kernel:monitor_nodes(true, [{node_type, blaha}]), {error, {bad_option_value, #{node_type := blaha}}} = net_kernel:monitor_nodes(true, #{node_type => blaha}), MonNodeState = monitor_node_state(), ok. monitor_nodes_combinations(Config) when is_list(Config) -> run_dist_configs(fun monitor_nodes_combinations/2, Config). monitor_nodes_combinations(DCfg, _Config) -> MonNodeState = monitor_node_state(), monitor_nodes_all_comb(true), [VisibleName, HiddenName] = get_nodenames(2, monitor_nodes_combinations), {ok, Visible} = start_node(DCfg, VisibleName, ""), receive_all_comb_nodeup_msgs(visible, Visible), no_msgs(), stop_node(Visible), receive_all_comb_nodedown_msgs(visible, Visible, connection_closed), no_msgs(), {ok, Hidden} = start_node(DCfg, HiddenName, "-hidden"), receive_all_comb_nodeup_msgs(hidden, Hidden), no_msgs(), stop_node(Hidden), receive_all_comb_nodedown_msgs(hidden, Hidden, connection_closed), no_msgs(), monitor_nodes_all_comb(false), MonNodeState = monitor_node_state(), no_msgs(), ok. monitor_nodes_all_comb(Flag) -> ok = net_kernel:monitor_nodes(Flag), ok = net_kernel:monitor_nodes(Flag, [nodedown_reason]), ok = net_kernel:monitor_nodes(Flag, [{node_type, hidden}]), ok = net_kernel:monitor_nodes(Flag, [{node_type, visible}]), ok = net_kernel:monitor_nodes(Flag, [{node_type, all}]), ok = net_kernel:monitor_nodes(Flag, [nodedown_reason, {node_type, hidden}]), ok = net_kernel:monitor_nodes(Flag, [nodedown_reason, {node_type, visible}]), ok = net_kernel:monitor_nodes(Flag, [nodedown_reason, {node_type, all}]), There currently are 8 different combinations 8. receive_all_comb_nodeup_msgs(visible, Node) -> io:format("Receive nodeup visible...~n"), Exp = [{nodeup, Node}, {nodeup, Node, []}] ++ mk_exp_mn_all_comb_nodeup_msgs_common(visible, Node), receive_mn_msgs(Exp), io:format("ok~n"), ok; receive_all_comb_nodeup_msgs(hidden, Node) -> io:format("Receive nodeup hidden...~n"), Exp = mk_exp_mn_all_comb_nodeup_msgs_common(hidden, Node), receive_mn_msgs(Exp), io:format("ok~n"), ok. mk_exp_mn_all_comb_nodeup_msgs_common(Type, Node) -> InfoNt = [{node_type, Type}], [{nodeup, Node, InfoNt}, {nodeup, Node, InfoNt}, {nodeup, Node, InfoNt}, {nodeup, Node, InfoNt}]. receive_all_comb_nodedown_msgs(visible, Node, Reason) -> io:format("Receive nodedown visible...~n"), Exp = [{nodedown, Node}, {nodedown, Node, [{nodedown_reason, Reason}]}] ++ mk_exp_mn_all_comb_nodedown_msgs_common(visible, Node, Reason), receive_mn_msgs(Exp), io:format("ok~n"), ok; receive_all_comb_nodedown_msgs(hidden, Node, Reason) -> io:format("Receive nodedown hidden...~n"), Exp = mk_exp_mn_all_comb_nodedown_msgs_common(hidden, Node, Reason), receive_mn_msgs(Exp), io:format("ok~n"), ok. mk_exp_mn_all_comb_nodedown_msgs_common(Type, Node, Reason) -> InfoNt = [{node_type, Type}], InfoNdrNt = lists:sort([{nodedown_reason, Reason}]++InfoNt), [{nodedown, Node, InfoNt}, {nodedown, Node, InfoNt}, {nodedown, Node, InfoNdrNt}, {nodedown, Node, InfoNdrNt}]. receive_mn_msgs([]) -> ok; receive_mn_msgs(Msgs) -> io:format("Expecting msgs: ~p~n", [Msgs]), receive {_Dir, _Node} = Msg -> io:format("received ~p~n", [Msg]), case lists:member(Msg, Msgs) of true -> receive_mn_msgs(lists:delete(Msg, Msgs)); false -> ct:fail({unexpected_message, Msg, expected_messages, Msgs}) end; {Dir, Node, Info} -> Msg = {Dir, Node, lists:sort(Info)}, io:format("received ~p~n", [Msg]), case lists:member(Msg, Msgs) of true -> receive_mn_msgs(lists:delete(Msg, Msgs)); false -> ct:fail({unexpected_message, Msg, expected_messages, Msgs}) end; Msg -> io:format("received ~p~n", [Msg]), ct:fail({unexpected_message, Msg, expected_messages, Msgs}) end. monitor_nodes_cleanup(Config) when is_list(Config) -> MonNodeState = monitor_node_state(), Me = self(), No = monitor_nodes_all_comb(true), Inf = spawn(fun () -> monitor_nodes_all_comb(true), Me ! {mons_set, self()}, receive after infinity -> ok end end), TO = spawn(fun () -> monitor_nodes_all_comb(true), Me ! {mons_set, self()}, receive after 500 -> ok end end), receive {mons_set, Inf} -> ok end, receive {mons_set, TO} -> ok end, MNLen = length(MonNodeState) + No*3, MNLen = length(monitor_node_state()), MonInf = erlang:monitor(process, Inf), MonTO = erlang:monitor(process, TO), exit(Inf, bang), No = monitor_nodes_all_comb(false), receive {'DOWN', MonInf, process, Inf, bang} -> ok end, receive {'DOWN', MonTO, process, TO, normal} -> ok end, MonNodeState = monitor_node_state(), no_msgs(), ok. monitor_nodes_many(Config) when is_list(Config) -> run_dist_configs(fun monitor_nodes_many/2, Config). monitor_nodes_many(DCfg, _Config) -> MonNodeState = monitor_node_state(), [Name] = get_nodenames(1, monitor_nodes_many), We want to perform more than 2 ^ 16 net_kernel : monitor_nodes No = (1 bsl 16) + 17, repeat(fun () -> ok = net_kernel:monitor_nodes(true) end, No), No = length(monitor_node_state()) - length(MonNodeState), {ok, Node} = start_node(DCfg, Name), repeat(fun () -> receive {nodeup, Node} -> ok end end, No), stop_node(Node), repeat(fun () -> receive {nodedown, Node} -> ok end end, No), ok = net_kernel:monitor_nodes(false), no_msgs(10), MonNodeState = monitor_node_state(), ok. Test order of messages nodedown and nodeup . monitor_nodes_down_up(Config) when is_list(Config) -> {ok, Peer, Node} = ?CT_PEER(#{connection => 0}), true = net_kernel:connect_node(Node), monitor_nodes_yoyo(Node), peer:stop(Peer). monitor_nodes_yoyo(A) -> net_kernel:monitor_nodes(true), Papa = self(), Spawn lots of processes doing one erlang : monitor_node(A , true ) each NodeMonCnt = 10000, NodeMons = [my_spawn_opt(fun F() -> monitor_node = receive_any(), monitor_node(A, true), Papa ! ready, {nodedown, A} = receive_any(), F() end, [link, monitor, {priority, low}]) || _ <- lists:seq(1, NodeMonCnt)], Spammer = my_spawn_opt(fun F() -> {dummy, A} ! trigger_auto_connect, F() end, [link, monitor]), Yoyos = 20, [begin [P ! monitor_node || P <- NodeMons], [receive ready -> ok end || _ <- NodeMons], Owner = get_conn_owner(A), exit(Owner, kill), {nodedown, A} = receive_any(), {nodeup, A} = receive_any() end || _ <- lists:seq(1,Yoyos)], unlink(Spammer), exit(Spammer, die), receive {'DOWN',_,process,Spammer,_} -> ok end, [begin unlink(P), exit(P, die) end || P <- NodeMons], [receive {'DOWN',_,process,P,_} -> ok end || P <- NodeMons], net_kernel:monitor_nodes(false), ok. receive_any() -> receive_any(infinity). receive_any(Timeout) -> receive M -> M after Timeout -> timeout end. my_spawn_opt(Fun, Opts) -> case spawn_opt(Fun, Opts) of {Pid, _Mref} -> Pid; Pid -> Pid end. get_conn_owner(Node) -> {ok, NodeInfo} = net_kernel:node_info(Node), {value,{owner, Owner}} = lists:keysearch(owner, 1, NodeInfo), Owner. dist_ctrl_proc_smoke(Config) when is_list(Config) -> dist_ctrl_proc_test(get_nodenames(2, ?FUNCTION_NAME)). dist_ctrl_proc_reject(Config) when is_list(Config) -> ToReject = combinations(dist_util:rejectable_flags()), lists:map(fun(Flags) -> ct:log("Try to reject ~p",[Flags]), dist_ctrl_proc_test(get_nodenames(2, ?FUNCTION_NAME), "-gen_tcp_dist_reject_flags " ++ integer_to_list(Flags)) end, ToReject). combinations([H | T]) -> lists:flatten([[(1 bsl H) bor C || C <- combinations(T)] | combinations(T)]); combinations([]) -> [0]; combinations(BitField) -> lists:sort(combinations(bits(BitField, 0))). bits(0, _) -> []; bits(BitField, Cnt) when BitField band 1 == 1 -> [Cnt | bits(BitField bsr 1, Cnt + 1)]; bits(BitField, Cnt) -> bits(BitField bsr 1, Cnt + 1). dist_ctrl_proc_test(Nodes) -> dist_ctrl_proc_test(Nodes,""). dist_ctrl_proc_test([Name1,Name2], Extra) -> ThisNode = node(), GenTcpOptProlog = "-proto_dist gen_tcp " "-gen_tcp_dist_output_loop " ++ atom_to_list(?MODULE) ++ " " ++ "dist_cntrlr_output_test_size " ++ Extra, {ok, Node1} = start_node("", Name1, "-proto_dist gen_tcp"), {ok, Node2} = start_node("", Name2, GenTcpOptProlog), NL = lists:sort([ThisNode, Node1, Node2]), wait_until(fun () -> NL == lists:sort([node()|nodes()]) end), wait_until(fun () -> NL == lists:sort([rpc:call(Node1,erlang, node, []) | rpc:call(Node1, erlang, nodes, [])]) end), wait_until(fun () -> NL == lists:sort([rpc:call(Node2,erlang, node, []) | rpc:call(Node2, erlang, nodes, [])]) end), smoke_communicate(Node1, gen_tcp_dist, dist_cntrlr_output_loop), smoke_communicate(Node2, erl_distribution_SUITE, dist_cntrlr_output_loop_size), stop_node(Node1), stop_node(Node2), ok. smoke_communicate(Node, OLoopMod, OLoopFun) -> Ps = rpc:call(Node, erlang, processes, []), try lists:foreach( fun (P) -> case rpc:call(Node, erlang, process_info, [P, current_stacktrace]) of undefined -> ok; {current_stacktrace, StkTrace} -> lists:foreach(fun ({Mod, Fun, 2, _}) when Mod == OLoopMod, Fun == OLoopFun -> io:format("~p ~p~n", [P, StkTrace]), throw(found_it); (_) -> ok end, StkTrace) end end, Ps), exit({missing, {OLoopMod, OLoopFun}}) catch throw:found_it -> ok end, Bin = list_to_binary(lists:duplicate(1000,100)), BitStr = <<0:7999>>, List = [[Bin], atom, [BitStr|Bin], make_ref(), [[[BitStr|"hopp"]]], 4711, 111122222211111111111111,"hej", fun () -> ok end, BitStr, self(), fun erlang:node/1], Pid = spawn_link(Node, fun () -> receive {From1, Msg1} -> From1 ! Msg1 end, receive {From2, Msg2} -> From2 ! Msg2 end end), R = make_ref(), Pid ! {self(), [R, List]}, receive [R, L1] -> List = L1 end, FragBin = <<0:(2*(1024*64*8))>>, Pid ! {self(), [R, List, FragBin]}, receive [R, L2, B] -> List = L2, FragBin = B end, unlink(Pid), exit(Pid, kill), ok. erl_uds_dist_smoke_test(Config) when is_list(Config) -> case os:type() of {win32,_} -> {skipped, "Not on Windows"}; _ -> do_erl_uds_dist_smoke_test() end. do_erl_uds_dist_smoke_test() -> [Node1, Node2] = lists:map(fun (Name) -> list_to_atom(atom_to_list(Name) ++ "@localhost") end, get_nodenames(2, erl_uds_dist_smoke_test)), {LPort, Acceptor} = uds_listen(), start_uds_node(Node1, LPort), start_uds_node(Node2, LPort), receive {uds_nodeup, N1} -> io:format("~p is up~n", [N1]) end, receive {uds_nodeup, N2} -> io:format("~p is up~n", [N2]) end, io:format("Testing ping net_adm:ping(~p) on ~p~n", [Node2, Node1]), Node1 ! {self(), {net_adm, ping, [Node2]}}, receive {Node1, PingRes} -> io:format("~p~n", [PingRes]), pong = PingRes end, io:format("Testing nodes() on ~p~n", [Node1]), Node1 ! {self(), {erlang, nodes, []}}, receive {Node1, N1List} -> io:format("~p~n", [N1List]), [Node2] = N1List end, io:format("Testing nodes() on ~p~n", [Node2]), Node2 ! {self(), {erlang, nodes, []}}, receive {Node2, N2List} -> io:format("~p~n", [N2List]), [Node1] = N2List end, io:format("Shutting down~n", []), Node1 ! {self(), close}, Node2 ! {self(), close}, receive {Node1, C1} -> ok = C1 end, receive {Node2, C2} -> ok = C2 end, unlink(Acceptor), exit(Acceptor, kill), io:format("ok~n", []), ok. uds_listen() -> Me = self(), {ok, LSock} = gen_tcp:listen(0, [binary, {packet, 4}, {active, false}]), {ok, LPort} = inet:port(LSock), {LPort, spawn_link(fun () -> uds_accept_loop(LSock, Me) end)}. uds_accept_loop(LSock, TestProc) -> {ok, Sock} = gen_tcp:accept(LSock), _ = spawn_link(fun () -> uds_rpc_client_init(Sock, TestProc) end), uds_accept_loop(LSock, TestProc). uds_rpc(Sock, MFA) -> ok = gen_tcp:send(Sock, term_to_binary(MFA)), case gen_tcp:recv(Sock, 0) of {error, Reason} -> error({recv_failed, Reason}); {ok, Packet} -> binary_to_term(Packet) end. uds_rpc_client_init(Sock, TestProc) -> case uds_rpc(Sock, {erlang, node, []}) of nonode@nohost -> receive after 100 -> ok end, uds_rpc_client_init(Sock, TestProc); Node when is_atom(Node) -> register(Node, self()), TestProc ! {uds_nodeup, Node}, uds_rpc_client_loop(Sock, Node) end. uds_rpc_client_loop(Sock, Node) -> receive {From, close} -> ok = gen_tcp:send(Sock, term_to_binary(close)), From ! {Node, gen_tcp:close(Sock)}, exit(normal); {From, ApplyData} -> From ! {Node, uds_rpc(Sock, ApplyData)}, uds_rpc_client_loop(Sock, Node) end. uds_rpc_server_loop(Sock) -> case gen_tcp:recv(Sock, 0) of {error, Reason} -> error({recv_failed, Reason}); {ok, Packet} -> case binary_to_term(Packet) of {M, F, A} when is_atom(M), is_atom(F), is_list(A) -> ok = gen_tcp:send(Sock, term_to_binary(apply(M, F, A))); {F, A} when is_function(F), is_list(A) -> ok = gen_tcp:send(Sock, term_to_binary(apply(F, A))); close -> ok = gen_tcp:close(Sock), exit(normal); Other -> error({unexpected_data, Other}) end end, uds_rpc_server_loop(Sock). start_uds_rpc_server([PortString]) -> Port = list_to_integer(PortString), {Pid, Mon} = spawn_monitor(fun () -> {ok, Sock} = gen_tcp:connect({127,0,0,1}, Port, [binary, {packet, 4}, {active, false}]), uds_rpc_server_loop(Sock) end), receive {'DOWN', Mon, process, Pid, Reason} -> if Reason == normal -> halt(); true -> EStr = lists:flatten(io_lib:format("uds rpc server crashed: ~p", [Reason])), (catch file:write_file("uds_rpc_server_crash."++os:getpid(), EStr)), halt(EStr) end end. start_uds_node(NodeName, LPort) -> Static = "-detached -noinput -proto_dist erl_uds", Pa = filename:dirname(code:which(?MODULE)), Prog = case catch init:get_argument(progname) of {ok,[[P]]} -> P; _ -> error(no_progname_argument_found) end, {ok, Pwd} = file:get_cwd(), NameStr = atom_to_list(NodeName), CmdLine = Prog ++ " " ++ Static ++ " -sname " ++ NameStr ++ " -pa " ++ Pa ++ " -env ERL_CRASH_DUMP " ++ Pwd ++ "/erl_crash_dump." ++ NameStr ++ " -setcookie " ++ atom_to_list(erlang:get_cookie()) ++ " -run " ++ atom_to_list(?MODULE) ++ " start_uds_rpc_server " ++ integer_to_list(LPort), io:format("Starting: ~p~n", [CmdLine]), case open_port({spawn, CmdLine}, []) of Port when is_port(Port) -> unlink(Port), erlang:port_close(Port); Error -> error({open_port_failed, Error}) end, ok. erl_1424(Config) when is_list(Config) -> {error, Reason} = erl_epmd:names("."), {comment, lists:flatten(io_lib:format("Reason: ~p", [Reason]))}. net_kernel_start(Config) when is_list(Config) -> MyName = net_kernel_start_tester, register(MyName, self()), net_kernel_start_test(MyName, 120, 8, true, false), net_kernel_start_test(MyName, 120, 8, false, false), net_kernel_start_test(MyName, 120, 8, true, true), net_kernel_start_test(MyName, undefined, undefined, undefined, undefined). net_kernel_start_test(MyName, NetTickTime, NetTickIntesity, DistListen, Hidden) -> TestNameStr = "net_kernel_start_test_node-" ++ integer_to_list(erlang:system_time(seconds)) ++ "-" ++ integer_to_list(erlang:unique_integer([monotonic,positive])), TestNode = list_to_atom(TestNameStr ++ "@" ++ atom_to_list(gethostname())), CmdLine = net_kernel_start_cmdline(MyName, list_to_atom(TestNameStr), NetTickTime, NetTickIntesity, DistListen, Hidden), io:format("Starting test node ~p: ~s~n", [TestNode, CmdLine]), case open_port({spawn, CmdLine}, []) of Port when is_port(Port) -> case DistListen == false of false -> ok; true -> receive after 1500 -> ok end, pang = net_adm:ping(TestNode), ok end, receive {i_am_alive, Pid, Node, NTT} = Msg -> IsHidden = lists:member(TestNode, nodes(hidden)), IsVisible = lists:member(TestNode, nodes(visible)), io:format("IsVisible = ~p~nIsHidden = ~p~n", [IsVisible, IsHidden]), io:format("Response from ~p: ~p~n", [Node, Msg]), rpc:cast(Node, erlang, halt, []), catch erlang:port_close(Port), TestNode = node(Pid), TestNode = Node, case NetTickTime == undefined of true -> {ok, DefNTT} = application:get_env(kernel, net_ticktime), DefNTT = NTT; false -> NetTickTime = NTT end, case DistListen == false orelse Hidden == true of true -> true = IsHidden, false = IsVisible; false -> false = IsHidden, true = IsVisible end end, ok; Error -> error({open_port_failed, TestNode, Error}) end. net_kernel_start_cmdline(TestName, Name, NetTickTime, NetTickIntensity, DistListen, Hidden) -> Pa = filename:dirname(code:which(?MODULE)), Prog = case catch init:get_argument(progname) of {ok, [[Prg]]} -> Prg; _ -> error(missing_progname) end, NameDomain = case net_kernel:longnames() of false -> "shortnames"; true -> "longnames" end, {ok, Pwd} = file:get_cwd(), NameStr = atom_to_list(Name), Prog ++ " -noinput -noshell -detached -pa " ++ Pa ++ " -env ERL_CRASH_DUMP " ++ Pwd ++ "/erl_crash_dump." ++ NameStr ++ " -setcookie " ++ atom_to_list(erlang:get_cookie()) ++ " -run " ++ atom_to_list(?MODULE) ++ " net_kernel_start_do_test " ++ atom_to_list(TestName) ++ " " ++ atom_to_list(node()) ++ " " ++ NameStr ++ " " ++ NameDomain ++ case NetTickTime == undefined of true -> ""; false -> " " ++ integer_to_list(NetTickTime) ++ " " ++ integer_to_list(NetTickIntensity) end ++ case DistListen == undefined of true -> ""; false -> " " ++ atom_to_list(DistListen) end ++ case Hidden == undefined of true -> ""; false -> " " ++ atom_to_list(Hidden) end. net_kernel_start_do_test([TestName, TestNode, Name, NameDomain]) -> net_kernel_start_do_test(TestName, TestNode, list_to_atom(Name), #{name_domain => list_to_atom(NameDomain)}); net_kernel_start_do_test([TestName, TestNode, Name, NameDomain, NetTickTime, NetTickIntensity, DistListen, Hidden]) -> net_kernel_start_do_test(TestName, TestNode, list_to_atom(Name), #{net_ticktime => list_to_integer(NetTickTime), name_domain => list_to_atom(NameDomain), net_tickintensity => list_to_integer(NetTickIntensity), dist_listen => list_to_atom(DistListen), hidden => list_to_atom(Hidden)}). net_kernel_start_do_test(TestName, TestNode, Name, Options) -> case net_kernel:start(Name, Options) of {ok, _Pid} -> case maps:get(dist_listen, Options, true) of false -> receive after 3000 -> ok end; true -> ok end, Tester = {list_to_atom(TestName), list_to_atom(TestNode)}, Tester ! {i_am_alive, self(), node(), net_kernel:get_net_ticktime()}, receive after 60000 -> ok end, erlang:halt(); Error -> erlang:halt(lists:flatten(io_lib:format("~p", [Error]))) end. differing_cookies(Config) when is_list(Config) -> test_server:timetrap({minutes, 1}), Node = node(), true = Node =/= nonode@nohost, [] = nodes(), BaseName = atom_to_list(?FUNCTION_NAME), NodeAName = BaseName++"_nodeA", NodeA = full_node_name(NodeAName), NodeACookieL = BaseName++"_cookieA", NodeACookie = list_to_atom(NodeACookieL), true = erlang:set_cookie( NodeA, NodeACookie ), { ok, NodeA } = start_node( "-hidden", NodeAName, "-setcookie "++NodeACookieL ), try [ NodeA ] = nodes(hidden), [ Node ] = rpc:call( NodeA, erlang, nodes, [hidden] ), NodeBName = BaseName++"_nodeB", NodeB = full_node_name(NodeBName), NodeBCookieL = BaseName++"_cookieB", NodeBCookie = list_to_atom(NodeBCookieL), true = erlang:set_cookie( NodeB, NodeBCookie ), { ok, NodeB } = start_node( "-hidden", NodeBName, "-setcookie "++NodeBCookieL ), try equal_sets( [NodeA, NodeB], nodes(hidden) ), [ Node ] = rpc:call( NodeA, erlang, nodes, [hidden] ), [ Node ] = rpc:call( NodeB, erlang, nodes, [hidden] ), pang = rpc:call( NodeA, net_adm, ping, [NodeB] ), pang = rpc:call( NodeB, net_adm, ping, [NodeA] ), true = rpc:call( NodeA, erlang, set_cookie, [NodeB, NodeBCookie] ), pong = rpc:call( NodeA, net_adm, ping, [NodeB] ), NodeACookie = rpc:call( NodeA, erlang, get_cookie, []), NodeBCookie = rpc:call( NodeB, erlang, get_cookie, []), equal_sets( [NodeA, NodeB], nodes(hidden) ), equal_sets( [Node, NodeB], rpc:call( NodeA, erlang, nodes, [hidden] )), equal_sets( [Node, NodeA], rpc:call( NodeB, erlang, nodes, [hidden] )), true = rpc:call( NodeB, net_kernel, disconnect, [NodeA] ), equal_sets( [NodeA, NodeB], nodes(hidden) ), [ Node ] = rpc:call( NodeA, erlang, nodes, [hidden] ), [ Node ] = rpc:call( NodeB, erlang, nodes, [hidden] ), Reconnect , now node B - > A pong = rpc:call( NodeB, net_adm, ping, [NodeA] ), equal_sets( [NodeA, NodeB], nodes(hidden) ), equal_sets( [Node, NodeB], rpc:call( NodeA, erlang, nodes, [hidden] )), equal_sets( [Node, NodeA], rpc:call( NodeB, erlang, nodes, [hidden] )) after _ = stop_node(NodeB) end after _ = stop_node(NodeA) end, [] = nodes(hidden), ok. cmdline_setcookie_2(Config) when is_list(Config) -> test_server:timetrap({minutes, 1}), Node = node(), true = Node =/= nonode@nohost, [] = nodes(), NodeL = atom_to_list(Node), BaseName = atom_to_list(?FUNCTION_NAME), NodeCookie = erlang:get_cookie(), NodeCookieL = atom_to_list(NodeCookie), NodeAName = BaseName++"_nodeA", NodeA = full_node_name(NodeAName), NodeACookieL = BaseName++"_cookieA", NodeACookie = list_to_atom(NodeACookieL), { ok, NodeA } = start_node( "-hidden", NodeAName, "-setcookie "++NodeL++" "++NodeCookieL ), try [ NodeA ] = nodes(hidden), [ Node ] = rpc:call( NodeA, erlang, nodes, [hidden] ), NodeCookie = rpc:call( NodeA, erlang, get_cookie, []), true = rpc:call( NodeA, erlang, set_cookie, [NodeACookie] ), NodeBName = BaseName++"_nodeB", NodeB = full_node_name(NodeBName), NodeBCookieL = BaseName++"_cookieB", NodeBCookie = list_to_atom(NodeBCookieL), { ok, NodeB } = start_node( "-hidden", NodeBName, "-setcookie "++NodeBCookieL++" " "-setcookie "++NodeL++" "++NodeCookieL++" " "-setcookie "++atom_to_list(NodeA)++" "++NodeACookieL ), try NodeACookie = rpc:call( NodeA, erlang, get_cookie, []), NodeBCookie = rpc:call( NodeB, erlang, get_cookie, []), equal_sets( [NodeA, NodeB], nodes(hidden) ), [ Node ] = rpc:call( NodeA, erlang, nodes, [hidden] ), [ Node ] = rpc:call( NodeB, erlang, nodes, [hidden] ), Connect the nodes pong = rpc:call( NodeA, net_adm, ping, [NodeB] ), NodeACookie = rpc:call( NodeA, erlang, get_cookie, []), NodeBCookie = rpc:call( NodeB, erlang, get_cookie, []), equal_sets( [NodeA, NodeB], nodes(hidden) ), equal_sets( [Node, NodeB], rpc:call( NodeA, erlang, nodes, [hidden] )), equal_sets( [Node, NodeA], rpc:call( NodeB, erlang, nodes, [hidden] )) after _ = stop_node(NodeB) end after _ = stop_node(NodeA) end, [] = nodes(hidden), ok. connection_cookie(Config) when is_list(Config) -> test_server:timetrap({minutes, 1}), Node = node(), true = Node =/= nonode@nohost, [] = nodes(), NodeL = atom_to_list(Node), BaseName = atom_to_list(?FUNCTION_NAME), NodeAName = BaseName++"_nodeA", NodeA = full_node_name(NodeAName), NodeACookieL = BaseName++"_cookieA", NodeACookie = list_to_atom(NodeACookieL), true = NodeACookie =/= erlang:get_cookie(), ConnectionCookieL = BaseName++"_connectionCookie", ConnectionCookie = list_to_atom(ConnectionCookieL), true = erlang:set_cookie( NodeA, ConnectionCookie ), { ok, NodeA } = start_node( "", NodeAName, "-setcookie "++NodeACookieL++" " "-setcookie "++NodeL++" "++ConnectionCookieL ), try [ NodeA ] = nodes(), [ Node ] = rpc:call( NodeA, erlang, nodes, [] ), NodeACookie = rpc:call( NodeA, erlang, get_cookie, []), ConnectionCookie = rpc:call( NodeA, auth, get_cookie, [Node]), ConnectionCookie = erlang:get_cookie( NodeA ) after _ = stop_node(NodeA) end, [] = nodes(), ok. dyn_differing_cookies(Config) when is_list(Config) -> test_server:timetrap({minutes, 1}), MotherNode = node(), true = MotherNode =/= nonode@nohost, [] = nodes(hidden), MotherNodeL = atom_to_list(MotherNode), BaseName = atom_to_list(?FUNCTION_NAME), MotherNodeCookie = erlang:get_cookie(), MotherNodeCookieL = atom_to_list(MotherNodeCookie), register(?FUNCTION_NAME, self()), DynNodeCookieL = BaseName++"_cookieA", DynNodeCookie = list_to_atom(DynNodeCookieL), {_NF1, Port1} = start_node_unconnected( "-setcookie "++MotherNodeL++" "++MotherNodeCookieL, undefined, DynNodeCookie, ?MODULE, run_remote_test, ["ddc_remote_run", MotherNodeL, "cmdline", MotherNodeCookieL] ), dyn_differing_cookies(MotherNode, MotherNodeCookie, DynNodeCookie, Port1), Same again , but use : set_cookie/2 to set MotherNodeCookie {_NF2, Port2} = start_node_unconnected( "", undefined, DynNodeCookie, ?MODULE, run_remote_test, ["ddc_remote_run", MotherNodeL, "set_cookie", MotherNodeCookieL] ), dyn_differing_cookies(MotherNode, MotherNodeCookie, DynNodeCookie, Port2). dyn_differing_cookies(MotherNode, MotherNodeCookie, DynNodeCookie, Port) -> receive { MotherNode, MotherNodeCookie, DynNodeCookie, DynNode } -> [ DynNode ] = nodes(hidden), [ MotherNode ] = rpc:call( DynNode, erlang, nodes, [hidden] ), DynNodeCookie = rpc:call( DynNode, erlang, get_cookie, [] ), MotherNodeCookie = rpc:call( DynNode, erlang, get_cookie, [MotherNode] ), {ddc_remote_run, DynNode} ! {MotherNode, MotherNodeCookie, DynNode}, 0 = wait_for_port_exit(Port), [] = nodes(hidden), ok; {Port, {data, Data}} -> io:format("~p: ~s", [Port, Data]), dyn_differing_cookies( MotherNode, MotherNodeCookie, DynNodeCookie, Port); Other -> error({unexpected, Other}) end. ddc_remote_run(MotherNode, [SetCookie, MotherNodeCookieL]) -> nonode@nohost = node(), [] = nodes(hidden), MotherNodeCookie = list_to_atom(MotherNodeCookieL), case SetCookie of "set_cookie" -> erlang:set_cookie(MotherNode, MotherNodeCookie); "cmdline" -> ok end, MotherNodeCookie = erlang:get_cookie(MotherNode), true = net_kernel:connect_node( MotherNode ), [ MotherNode ] = nodes(hidden), DynNode = node(), [ DynNode ] = rpc:call( MotherNode, erlang, nodes, [hidden] ), MotherNodeCookie = erlang:get_cookie( MotherNode ), MotherNodeCookie = rpc:call( MotherNode, erlang, get_cookie, [] ), MotherNodeCookie = rpc:call( MotherNode, erlang, get_cookie, [DynNode] ), DynNodeCookie = erlang:get_cookie(), register(ddc_remote_run, self() ), {dyn_differing_cookies, MotherNode} ! {MotherNode, MotherNodeCookie, DynNodeCookie, DynNode}, receive { MotherNode, MotherNodeCookie, DynNode } -> true = disconnect_node( MotherNode ), [] = nodes(hidden), ok; Other -> error({unexpected, Other}) end. xdg_cookie(Config) when is_list(Config) -> PrivDir = proplists:get_value(priv_dir, Config), TestHome = filename:join(PrivDir, ?FUNCTION_NAME), ok = file:make_dir(TestHome), HomeEnv = case os:type() of {win32, _} -> [Drive | Path] = filename:split(TestHome), [{"APPDATA", filename:join(TestHome,"AppData")}, {"HOMEDRIVE", Drive}, {"HOMEPATH", filename:join(Path)}]; _ -> [{"HOME", TestHome}] end, NodeOpts = #{ env => HomeEnv ++ [{"ERL_CRASH_DUMP", filename:join([TestHome,"erl_crash.dump"])}], connection => 0 }, Test that a default .erlang.cookie file is created {ok, CreatorPeer, _} = peer:start_link(NodeOpts#{ name => peer:random_name(?FUNCTION_NAME) }), UserConfig = peer:call(CreatorPeer, filename, basedir, [user_config,"erlang"]), ?assert(peer:call(CreatorPeer, filelib, is_regular, [filename:join(TestHome, ".erlang.cookie")])), OrigCookie = peer:call(CreatorPeer, erlang, get_cookie, []), peer:stop(CreatorPeer), Test that the $ HOME/.erlang.cookie file takes precedence over XDG XDGCookie = filename:join([UserConfig, ".erlang.cookie"]), ok = filelib:ensure_dir(XDGCookie), ok = file:write_file(XDGCookie, "Me want cookie!"), {ok, XDGFI} = file:read_file_info(XDGCookie), ok = file:write_file_info(XDGCookie, XDGFI#file_info{ mode = 8#600 }), {ok, Peer, _} = peer:start_link(NodeOpts#{ name => peer:random_name(?FUNCTION_NAME) }), ?assertEqual(OrigCookie, peer:call(Peer, erlang, get_cookie, [])), peer:stop(Peer), Check that XDG cookie works after we delete the $ HOME cookie HomeCookie = filename:join(TestHome, ".erlang.cookie"), {ok, HomeFI} = file:read_file_info(HomeCookie), ok = file:write_file_info(HomeCookie, HomeFI#file_info{ mode = 8#777 }), ok = file:delete(HomeCookie), {ok, Peer2, _} = peer:start_link(NodeOpts#{ name => peer:random_name(?FUNCTION_NAME) }), ?assertEqual('Me want cookie!', peer:call(Peer2, erlang, get_cookie, [])), peer:stop(Peer2), ok. equal_sets(A, B) -> S = lists:sort(A), case lists:sort(B) of S -> ok; _ -> erlang:error({not_equal_sets, A, B}) end. run_dist_configs(Func, Config) -> GetOptProlog = "-proto_dist gen_tcp -gen_tcp_dist_output_loop " ++ atom_to_list(?MODULE) ++ " ", GenTcpDistTest = case get_gen_tcp_dist_test_type() of default -> {"gen_tcp_dist", "-proto_dist gen_tcp"}; size -> {"gen_tcp_dist (get_size)", GetOptProlog ++ "dist_cntrlr_output_test_size"} end, lists:map(fun ({DCfgName, DCfg}) -> io:format("~n~n=== Running ~s configuration ===~n~n", [DCfgName]), Func(DCfg, Config) end, [{"default", ""}, GenTcpDistTest]). start_gen_tcp_dist_test_type_server() -> Me = self(), Go = make_ref(), io:format("STARTING: gen_tcp_dist_test_type_server~n",[]), {P, M} = spawn_monitor(fun () -> register(gen_tcp_dist_test_type_server, self()), Me ! Go, gen_tcp_dist_test_type_server() end), receive Go -> ok; {'DOWN', M, process, P, _} -> start_gen_tcp_dist_test_type_server() end. kill_gen_tcp_dist_test_type_server() -> case whereis(gen_tcp_dist_test_type_server) of undefined -> ok; Pid -> exit(Pid,kill), Sync death , before continuing ... false = erlang:is_process_alive(Pid) end. gen_tcp_dist_test_type_server() -> Type = case abs(erlang:monotonic_time(second)) rem 2 of 0 -> default; 1 -> size end, gen_tcp_dist_test_type_server(Type). gen_tcp_dist_test_type_server(Type) -> receive {From, Ref} -> From ! {Ref, Type}, NewType = case Type of default -> size; size -> default end, gen_tcp_dist_test_type_server(NewType) end. get_gen_tcp_dist_test_type() -> Ref = make_ref(), try gen_tcp_dist_test_type_server ! {self(), Ref}, receive {Ref, Type} -> Type end catch error:badarg -> start_gen_tcp_dist_test_type_server(), get_gen_tcp_dist_test_type() end. dist_cntrlr_output_test_size(DHandle, Socket) -> false = erlang:dist_ctrl_get_opt(DHandle, get_size), false = erlang:dist_ctrl_set_opt(DHandle, get_size, true), true = erlang:dist_ctrl_get_opt(DHandle, get_size), true = erlang:dist_ctrl_set_opt(DHandle, get_size, false), false = erlang:dist_ctrl_get_opt(DHandle, get_size), false = erlang:dist_ctrl_set_opt(DHandle, get_size, true), true = erlang:dist_ctrl_get_opt(DHandle, get_size), dist_cntrlr_output_loop_size(DHandle, Socket). dist_cntrlr_output_loop_size(DHandle, Socket) -> receive dist_data -> dist_cntrlr_send_data_size(DHandle, Socket); _ -> end, dist_cntrlr_output_loop_size(DHandle, Socket). dist_cntrlr_send_data_size(DHandle, Socket) -> case erlang:dist_ctrl_get_data(DHandle) of none -> erlang:dist_ctrl_get_data_notification(DHandle); {Size, Data} -> ok = ensure_iovec(Data), Size = erlang:iolist_size(Data), ok = gen_tcp:send(Socket, Data), dist_cntrlr_send_data_size(DHandle, Socket) end. ensure_iovec([]) -> ok; ensure_iovec([X|Y]) when is_binary(X) -> ensure_iovec(Y). monitor_node_state() -> erts_debug:set_internal_state(available_internal_state, true), MonitoringNodes = erts_debug:get_internal_state(monitoring_nodes), erts_debug:set_internal_state(available_internal_state, false), MonitoringNodes. check_no_nodedown_nodeup(TimeOut) -> receive {nodeup, _, _} = Msg -> ct:fail({unexpected_nodeup, Msg}); {nodeup, _} = Msg -> ct:fail({unexpected_nodeup, Msg}); {nodedown, _, _} = Msg -> ct:fail({unexpected_nodedown, Msg}); {nodedown, _} = Msg -> ct:fail({unexpected_nodedown, Msg}) after TimeOut -> ok end. print_my_messages() -> {messages, Messages} = process_info(self(), messages), io:format("Messages: ~p~n", [Messages]), ok. sleep(T) -> receive after T * 1000 -> ok end. start_node(_DCfg, Name, Param, this) -> NewParam = Param ++ " -pa " ++ filename:dirname(code:which(?MODULE)), test_server:start_node(Name, peer, [{args, NewParam}, {erl, [this]}]); start_node(DCfg, Name, Param, "this") -> NewParam = Param ++ " -pa " ++ filename:dirname(code:which(?MODULE)) ++ " " ++ DCfg, test_server:start_node(Name, peer, [{args, NewParam}, {erl, [this]}]); start_node(DCfg, Name, Param, Rel) when is_atom(Rel) -> NewParam = Param ++ " -pa " ++ filename:dirname(code:which(?MODULE)) ++ " " ++ DCfg, test_server:start_node(Name, peer, [{args, NewParam}, {erl, [{release, atom_to_list(Rel)}]}]); start_node(DCfg, Name, Param, Rel) when is_list(Rel) -> NewParam = Param ++ " -pa " ++ filename:dirname(code:which(?MODULE)) ++ " " ++ DCfg, test_server:start_node(Name, peer, [{args, NewParam}, {erl, [{release, Rel}]}]). start_node(DCfg, Name, Param) -> NewParam = Param ++ " -pa " ++ filename:dirname(code:which(?MODULE)) ++ " " ++ DCfg, test_server:start_node(Name, slave, [{args, NewParam}]). start_node(DCfg, Name) -> start_node(DCfg, Name, ""). stop_node(Node) -> test_server:stop_node(Node). get_nodenames(N, T) -> get_nodenames(N, T, []). get_nodenames(0, _, Acc) -> Acc; get_nodenames(N, T, Acc) -> U = erlang:unique_integer([positive]), get_nodenames(N-1, T, [list_to_atom(atom_to_list(T) ++ "-" ++ ?MODULE_STRING ++ "-" ++ integer_to_list(U)) | Acc]). get_numbered_nodenames(N, T) -> get_numbered_nodenames(N, T, []). get_numbered_nodenames(0, _, Acc) -> Acc; get_numbered_nodenames(N, T, Acc) -> U = erlang:unique_integer([positive]), NL = [list_to_atom(atom_to_list(T) ++ integer_to_list(N) ++ "-" ++ ?MODULE_STRING ++ "-" ++ integer_to_list(U)) | Acc], get_numbered_nodenames(N-1, T, NL). wait_until(Fun) -> case Fun() of true -> ok; _ -> receive after 100 -> wait_until(Fun) end end. repeat(Fun, 0) when is_function(Fun) -> ok; repeat(Fun, N) when is_function(Fun), is_integer(N), N > 0 -> Fun(), repeat(Fun, N-1). no_msgs(Wait) -> receive after Wait -> no_msgs() end. no_msgs() -> {messages, []} = process_info(self(), messages). block_emu(Ms) -> erts_debug:set_internal_state(available_internal_state, true), Res = erts_debug:set_internal_state(block, Ms), erts_debug:set_internal_state(available_internal_state, false), Res.
73858a87bb999b97efcf9f20de8a29f676f8b158a0457290eb12ede872237ea2
ijvcms/chuanqi_dev
dynamic_compile.erl
Copyright ( c ) 2007 Mats < > < > < > %% %% 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. %%%------------------------------------------------------------------- %%% File : dynamic_compile.erl %%% Description : Authors : Mats < > < > < > %%% - add support for limit include-file depth (and prevent circular references) prevent circular macro expansion set FILE correctly when -module ( ) is found -include_lib support $ ENVVAR in include filenames %%% substitute-stringize (??MACRO) %%% -undef/-ifdef/-ifndef/-else/-endif %%% -file(File, Line) %%%------------------------------------------------------------------- -module(dynamic_compile). %% API -export([from_string/1, from_string/2]). -import(lists, [reverse/1, keyreplace/4]). %%==================================================================== %% API %%==================================================================== %%-------------------------------------------------------------------- %% Function: %% Description: %% Returns a binary that can be used with code : load_binary(Module , ModuleFilenameForInternalRecords , Binary ) . %%-------------------------------------------------------------------- from_string(CodeStr) -> from_string(CodeStr, []). % takes Options as for compile:forms/2 from_string(CodeStr, CompileFormsOptions) -> Initialise the macro dictionary with the default predefined macros , %% (adapted from epp.erl:predef_macros/1 Filename = "compiled_from_string", %%Machine = list_to_atom(erlang:system_info(machine)), Ms0 = dict:new(), Ms1 = dict : store('FILE ' , { [ ] , " compiled_from_string " } , Ms0 ) , Ms2 = dict : store('LINE ' , { [ ] , 1 } , Ms1 ) , % actually we might add special code for this % Ms3 = dict:store('MODULE', {[], undefined}, Ms2), % Ms4 = dict:store('MODULE_STRING', {[], undefined}, Ms3), % Ms5 = dict:store('MACHINE', {[], Machine}, Ms4), % InitMD = dict:store(Machine, {[], true}, Ms5), InitMD = Ms0, %% From the docs for compile:forms: When encountering an -include or directive , the compiler searches for header files in the following directories : %% 1. ".", the current working directory of the file server; 2 . the base name of the compiled file ; 3 . the directories specified using the i option . The directory specified last is searched first . In this case , # 2 is meaningless . IncludeSearchPath = ["." | reverse([Dir || {i, Dir} <- CompileFormsOptions])], {RevForms, _OutMacroDict} = scan_and_parse(CodeStr, Filename, 1, [], InitMD, IncludeSearchPath), Forms = reverse(RevForms), %% note: 'binary' is forced as an implicit option, whether it is provided or not. case compile:forms(Forms, CompileFormsOptions) of {ok, ModuleName, CompiledCodeBinary} when is_binary(CompiledCodeBinary) -> {ModuleName, CompiledCodeBinary}; {ok, ModuleName, CompiledCodeBinary, []} when is_binary(CompiledCodeBinary) -> % empty warnings list {ModuleName, CompiledCodeBinary}; {ok, _ModuleName, _CompiledCodeBinary, Warnings} -> throw({?MODULE, warnings, Warnings}); Other -> throw({?MODULE, compile_forms, Other}) end. %%==================================================================== Internal functions %%==================================================================== Code from Mats %%% See -questions/2007-March/025507.html %%%## 'scan_and_parse' %%% basically we call the OTP scanner and parser ( erl_scan and %%% erl_parse) line-by-line, but check each scanned line for (or %%% definitions of) macros before parsing. %% returns {ReverseForms, FinalMacroDict} scan_and_parse([], _CurrFilename, _CurrLine, RevForms, MacroDict, _IncludeSearchPath) -> {RevForms, MacroDict}; scan_and_parse(RemainingText, CurrFilename, CurrLine, RevForms, MacroDict, IncludeSearchPath) -> case scanner(RemainingText, CurrLine, MacroDict) of {tokens, NLine, NRemainingText, Toks} -> {ok, Form} = erl_parse:parse_form(Toks), scan_and_parse(NRemainingText, CurrFilename, NLine, [Form | RevForms], MacroDict, IncludeSearchPath); {macro, NLine, NRemainingText, NMacroDict} -> scan_and_parse(NRemainingText, CurrFilename, NLine, RevForms, NMacroDict, IncludeSearchPath); {include, NLine, NRemainingText, IncludeFilename} -> IncludeFileRemainingTextents = read_include_file(IncludeFilename, IncludeSearchPath), io : format("include file ~p contents : ~n ~ p ~ nRemainingText = ~p ~ n " , [ IncludeFilename , IncludeFileRemainingTextents , RemainingText ] ) , Modify the FILE macro to reflect the filename IncludeMacroDict = dict : store('FILE ' , { [ ] , } , MacroDict ) , IncludeMacroDict = MacroDict, %% Process the header file (inc. any nested header files) {RevIncludeForms, IncludedMacroDict} = scan_and_parse(IncludeFileRemainingTextents, IncludeFilename, 1, [], IncludeMacroDict, IncludeSearchPath), %io:format("include file results = ~p~n", [R]), Restore the FILE macro in the NEW MacroDict ( so we keep any macros defined in the header file ) NMacroDict = dict : store('FILE ' , { [ ] , CurrFilename } , IncludedMacroDict ) , NMacroDict = IncludedMacroDict, %% Continue with the original file scan_and_parse(NRemainingText, CurrFilename, NLine, RevIncludeForms ++ RevForms, NMacroDict, IncludeSearchPath); done -> scan_and_parse([], CurrFilename, CurrLine, RevForms, MacroDict, IncludeSearchPath) end. scanner(Text, Line, MacroDict) -> case erl_scan:tokens([], Text, Line) of {done, {ok, Toks, NLine}, LeftOverChars} -> case pre_proc(Toks, MacroDict) of {tokens, NToks} -> {tokens, NLine, LeftOverChars, NToks}; {macro, NMacroDict} -> {macro, NLine, LeftOverChars, NMacroDict}; {include, Filename} -> {include, NLine, LeftOverChars, Filename} end; {more, _Continuation} -> %% This is supposed to mean "term is not yet complete" (i.e. a '.' has %% not been reached yet). %% However, for some bizarre reason we also get this if there is a comment after the final '.' in a file. %% So we check to see if Text only consists of comments. case is_only_comments(Text) of true -> done; false -> throw({incomplete_term, Text, Line}) end end. is_only_comments(Text) -> is_only_comments(Text, not_in_comment). is_only_comments([], _) -> true; is_only_comments([$ | T], not_in_comment) -> skipping whitspace outside of comment is_only_comments([$\t | T], not_in_comment) -> skipping whitspace outside of comment is_only_comments([$\n | T], not_in_comment) -> skipping whitspace outside of comment is_only_comments([$% | T], not_in_comment) -> is_only_comments(T, in_comment); % found start of a comment is_only_comments(_, not_in_comment) -> false; % found any significant char NOT in a comment is_only_comments([$\n | T], in_comment) -> is_only_comments(T, not_in_comment); % found end of a comment is_only_comments([_ | T], in_comment) -> is_only_comments(T, in_comment). % skipping over in-comment chars %%%## 'pre-proc' %%% %%% have to implement a subset of the pre-processor, since epp insists %%% on running on a file. only handles 2 cases ; %% -define(MACRO, something). -define(MACRO(VAR1,VARN),{stuff , VAR1,more , stuff , VARN , extra , stuff } ) . pre_proc([{'-', _}, {atom, _, define}, {'(', _}, {_, _, Name} | DefToks], MacroDict) -> false = dict:is_key(Name, MacroDict), case DefToks of [{',', _} | Macro] -> {macro, dict:store(Name, {[], macro_body_def(Macro, [])}, MacroDict)}; [{'(', _} | Macro] -> {macro, dict:store(Name, macro_params_body_def(Macro, []), MacroDict)} end; pre_proc([{'-', _}, {atom, _, include}, {'(', _}, {string, _, Filename}, {')', _}, {dot, _}], _MacroDict) -> {include, Filename}; pre_proc(Toks, MacroDict) -> {tokens, subst_macros(Toks, MacroDict)}. macro_params_body_def([{')', _}, {',', _} | Toks], RevParams) -> {reverse(RevParams), macro_body_def(Toks, [])}; macro_params_body_def([{var, _, Param} | Toks], RevParams) -> macro_params_body_def(Toks, [Param | RevParams]); macro_params_body_def([{',', _}, {var, _, Param} | Toks], RevParams) -> macro_params_body_def(Toks, [Param | RevParams]). macro_body_def([{')', _}, {dot, _}], RevMacroBodyToks) -> reverse(RevMacroBodyToks); macro_body_def([Tok | Toks], RevMacroBodyToks) -> macro_body_def(Toks, [Tok | RevMacroBodyToks]). subst_macros(Toks, MacroDict) -> reverse(subst_macros_rev(Toks, MacroDict, [])). %% returns a reversed list of tokes subst_macros_rev([{'?', _}, {_, LineNum, 'LINE'} | Toks], MacroDict, RevOutToks) -> special - case for ? LINE , to avoid creating a new MacroDict for every line in the source file subst_macros_rev(Toks, MacroDict, [{integer, LineNum, LineNum}] ++ RevOutToks); subst_macros_rev([{'?', _}, {_, _, Name}, {'(', _} = Paren | Toks], MacroDict, RevOutToks) -> case dict:fetch(Name, MacroDict) of {[], MacroValue} -> %% This macro does not have any vars, so ignore the fact that the invocation is followed by "(...stuff" %% Recursively expand any macro calls inside this macro's value %% TODO: avoid infinite expansion due to circular references (even indirect ones) RevExpandedOtherMacrosToks = subst_macros_rev(MacroValue, MacroDict, []), subst_macros_rev([Paren | Toks], MacroDict, RevExpandedOtherMacrosToks ++ RevOutToks); ParamsAndBody -> %% This macro does have vars. %% Collect all of the passe arguments, in an ordered list {NToks, Arguments} = subst_macros_get_args(Toks, []), Expand the varibles ExpandedParamsToks = subst_macros_subst_args_for_vars(ParamsAndBody, Arguments), %% Recursively expand any macro calls inside this macro's value %% TODO: avoid infinite expansion due to circular references (even indirect ones) RevExpandedOtherMacrosToks = subst_macros_rev(ExpandedParamsToks, MacroDict, []), subst_macros_rev(NToks, MacroDict, RevExpandedOtherMacrosToks ++ RevOutToks) end; subst_macros_rev([{'?', _}, {_, _, Name} | Toks], MacroDict, RevOutToks) -> %% This macro invocation does not have arguments. %% Therefore the definition should not have parameters {[], MacroValue} = dict:fetch(Name, MacroDict), %% Recursively expand any macro calls inside this macro's value %% TODO: avoid infinite expansion due to circular references (even indirect ones) RevExpandedOtherMacrosToks = subst_macros_rev(MacroValue, MacroDict, []), subst_macros_rev(Toks, MacroDict, RevExpandedOtherMacrosToks ++ RevOutToks); subst_macros_rev([Tok | Toks], MacroDict, RevOutToks) -> subst_macros_rev(Toks, MacroDict, [Tok | RevOutToks]); subst_macros_rev([], _MacroDict, RevOutToks) -> RevOutToks. subst_macros_get_args([{')', _} | Toks], RevArgs) -> {Toks, reverse(RevArgs)}; subst_macros_get_args([{',', _}, {var, _, ArgName} | Toks], RevArgs) -> subst_macros_get_args(Toks, [ArgName | RevArgs]); subst_macros_get_args([{var, _, ArgName} | Toks], RevArgs) -> subst_macros_get_args(Toks, [ArgName | RevArgs]). subst_macros_subst_args_for_vars({[], BodyToks}, []) -> BodyToks; subst_macros_subst_args_for_vars({[Param | Params], BodyToks}, [Arg | Args]) -> NBodyToks = keyreplace(Param, 3, BodyToks, {var, 1, Arg}), subst_macros_subst_args_for_vars({Params, NBodyToks}, Args). read_include_file(Filename, IncludeSearchPath) -> case file:path_open(IncludeSearchPath, Filename, [read, raw, binary]) of {ok, IoDevice, FullName} -> {ok, Data} = file:read(IoDevice, filelib:file_size(FullName)), file:close(IoDevice), binary_to_list(Data); {error, Reason} -> throw({failed_to_read_include_file, Reason, Filename, IncludeSearchPath}) end.
null
https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/system/misc/dynamic_compile.erl
erlang
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be 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. ------------------------------------------------------------------- File : dynamic_compile.erl Description : - add support for limit include-file depth (and prevent circular references) substitute-stringize (??MACRO) -undef/-ifdef/-ifndef/-else/-endif -file(File, Line) ------------------------------------------------------------------- API ==================================================================== API ==================================================================== -------------------------------------------------------------------- Function: Description: Returns a binary that can be used with -------------------------------------------------------------------- takes Options as for compile:forms/2 (adapted from epp.erl:predef_macros/1 Machine = list_to_atom(erlang:system_info(machine)), actually we might add special code for this Ms3 = dict:store('MODULE', {[], undefined}, Ms2), Ms4 = dict:store('MODULE_STRING', {[], undefined}, Ms3), Ms5 = dict:store('MACHINE', {[], Machine}, Ms4), InitMD = dict:store(Machine, {[], true}, Ms5), From the docs for compile:forms: 1. ".", the current working directory of the file server; note: 'binary' is forced as an implicit option, whether it is provided or not. empty warnings list ==================================================================== ==================================================================== See -questions/2007-March/025507.html ## 'scan_and_parse' erl_parse) line-by-line, but check each scanned line for (or definitions of) macros before parsing. returns {ReverseForms, FinalMacroDict} Process the header file (inc. any nested header files) io:format("include file results = ~p~n", [R]), Continue with the original file This is supposed to mean "term is not yet complete" (i.e. a '.' has not been reached yet). However, for some bizarre reason we also get this if there is a comment after the final '.' in a file. So we check to see if Text only consists of comments. | T], not_in_comment) -> is_only_comments(T, in_comment); % found start of a comment found any significant char NOT in a comment found end of a comment skipping over in-comment chars ## 'pre-proc' have to implement a subset of the pre-processor, since epp insists on running on a file. -define(MACRO, something). returns a reversed list of tokes This macro does not have any vars, so ignore the fact that the invocation is followed by "(...stuff" Recursively expand any macro calls inside this macro's value TODO: avoid infinite expansion due to circular references (even indirect ones) This macro does have vars. Collect all of the passe arguments, in an ordered list Recursively expand any macro calls inside this macro's value TODO: avoid infinite expansion due to circular references (even indirect ones) This macro invocation does not have arguments. Therefore the definition should not have parameters Recursively expand any macro calls inside this macro's value TODO: avoid infinite expansion due to circular references (even indirect ones)
Copyright ( c ) 2007 Mats < > < > < > files ( the " Software " ) , to deal in the Software without copies of the Software , and to permit persons to whom the included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , Authors : Mats < > < > < > prevent circular macro expansion set FILE correctly when -module ( ) is found -include_lib support $ ENVVAR in include filenames -module(dynamic_compile). -export([from_string/1, from_string/2]). -import(lists, [reverse/1, keyreplace/4]). code : load_binary(Module , ModuleFilenameForInternalRecords , Binary ) . from_string(CodeStr) -> from_string(CodeStr, []). from_string(CodeStr, CompileFormsOptions) -> Initialise the macro dictionary with the default predefined macros , Filename = "compiled_from_string", Ms0 = dict:new(), Ms1 = dict : store('FILE ' , { [ ] , " compiled_from_string " } , Ms0 ) , InitMD = Ms0, When encountering an -include or directive , the compiler searches for header files in the following directories : 2 . the base name of the compiled file ; 3 . the directories specified using the i option . The directory specified last is searched first . In this case , # 2 is meaningless . IncludeSearchPath = ["." | reverse([Dir || {i, Dir} <- CompileFormsOptions])], {RevForms, _OutMacroDict} = scan_and_parse(CodeStr, Filename, 1, [], InitMD, IncludeSearchPath), Forms = reverse(RevForms), case compile:forms(Forms, CompileFormsOptions) of {ok, ModuleName, CompiledCodeBinary} when is_binary(CompiledCodeBinary) -> {ModuleName, CompiledCodeBinary}; {ModuleName, CompiledCodeBinary}; {ok, _ModuleName, _CompiledCodeBinary, Warnings} -> throw({?MODULE, warnings, Warnings}); Other -> throw({?MODULE, compile_forms, Other}) end. Internal functions Code from Mats basically we call the OTP scanner and parser ( erl_scan and scan_and_parse([], _CurrFilename, _CurrLine, RevForms, MacroDict, _IncludeSearchPath) -> {RevForms, MacroDict}; scan_and_parse(RemainingText, CurrFilename, CurrLine, RevForms, MacroDict, IncludeSearchPath) -> case scanner(RemainingText, CurrLine, MacroDict) of {tokens, NLine, NRemainingText, Toks} -> {ok, Form} = erl_parse:parse_form(Toks), scan_and_parse(NRemainingText, CurrFilename, NLine, [Form | RevForms], MacroDict, IncludeSearchPath); {macro, NLine, NRemainingText, NMacroDict} -> scan_and_parse(NRemainingText, CurrFilename, NLine, RevForms, NMacroDict, IncludeSearchPath); {include, NLine, NRemainingText, IncludeFilename} -> IncludeFileRemainingTextents = read_include_file(IncludeFilename, IncludeSearchPath), io : format("include file ~p contents : ~n ~ p ~ nRemainingText = ~p ~ n " , [ IncludeFilename , IncludeFileRemainingTextents , RemainingText ] ) , Modify the FILE macro to reflect the filename IncludeMacroDict = dict : store('FILE ' , { [ ] , } , MacroDict ) , IncludeMacroDict = MacroDict, {RevIncludeForms, IncludedMacroDict} = scan_and_parse(IncludeFileRemainingTextents, IncludeFilename, 1, [], IncludeMacroDict, IncludeSearchPath), Restore the FILE macro in the NEW MacroDict ( so we keep any macros defined in the header file ) NMacroDict = dict : store('FILE ' , { [ ] , CurrFilename } , IncludedMacroDict ) , NMacroDict = IncludedMacroDict, scan_and_parse(NRemainingText, CurrFilename, NLine, RevIncludeForms ++ RevForms, NMacroDict, IncludeSearchPath); done -> scan_and_parse([], CurrFilename, CurrLine, RevForms, MacroDict, IncludeSearchPath) end. scanner(Text, Line, MacroDict) -> case erl_scan:tokens([], Text, Line) of {done, {ok, Toks, NLine}, LeftOverChars} -> case pre_proc(Toks, MacroDict) of {tokens, NToks} -> {tokens, NLine, LeftOverChars, NToks}; {macro, NMacroDict} -> {macro, NLine, LeftOverChars, NMacroDict}; {include, Filename} -> {include, NLine, LeftOverChars, Filename} end; {more, _Continuation} -> case is_only_comments(Text) of true -> done; false -> throw({incomplete_term, Text, Line}) end end. is_only_comments(Text) -> is_only_comments(Text, not_in_comment). is_only_comments([], _) -> true; is_only_comments([$ | T], not_in_comment) -> skipping whitspace outside of comment is_only_comments([$\t | T], not_in_comment) -> skipping whitspace outside of comment is_only_comments([$\n | T], not_in_comment) -> skipping whitspace outside of comment is_only_comments(_, not_in_comment) -> false; only handles 2 cases ; -define(MACRO(VAR1,VARN),{stuff , VAR1,more , stuff , VARN , extra , stuff } ) . pre_proc([{'-', _}, {atom, _, define}, {'(', _}, {_, _, Name} | DefToks], MacroDict) -> false = dict:is_key(Name, MacroDict), case DefToks of [{',', _} | Macro] -> {macro, dict:store(Name, {[], macro_body_def(Macro, [])}, MacroDict)}; [{'(', _} | Macro] -> {macro, dict:store(Name, macro_params_body_def(Macro, []), MacroDict)} end; pre_proc([{'-', _}, {atom, _, include}, {'(', _}, {string, _, Filename}, {')', _}, {dot, _}], _MacroDict) -> {include, Filename}; pre_proc(Toks, MacroDict) -> {tokens, subst_macros(Toks, MacroDict)}. macro_params_body_def([{')', _}, {',', _} | Toks], RevParams) -> {reverse(RevParams), macro_body_def(Toks, [])}; macro_params_body_def([{var, _, Param} | Toks], RevParams) -> macro_params_body_def(Toks, [Param | RevParams]); macro_params_body_def([{',', _}, {var, _, Param} | Toks], RevParams) -> macro_params_body_def(Toks, [Param | RevParams]). macro_body_def([{')', _}, {dot, _}], RevMacroBodyToks) -> reverse(RevMacroBodyToks); macro_body_def([Tok | Toks], RevMacroBodyToks) -> macro_body_def(Toks, [Tok | RevMacroBodyToks]). subst_macros(Toks, MacroDict) -> reverse(subst_macros_rev(Toks, MacroDict, [])). subst_macros_rev([{'?', _}, {_, LineNum, 'LINE'} | Toks], MacroDict, RevOutToks) -> special - case for ? LINE , to avoid creating a new MacroDict for every line in the source file subst_macros_rev(Toks, MacroDict, [{integer, LineNum, LineNum}] ++ RevOutToks); subst_macros_rev([{'?', _}, {_, _, Name}, {'(', _} = Paren | Toks], MacroDict, RevOutToks) -> case dict:fetch(Name, MacroDict) of {[], MacroValue} -> RevExpandedOtherMacrosToks = subst_macros_rev(MacroValue, MacroDict, []), subst_macros_rev([Paren | Toks], MacroDict, RevExpandedOtherMacrosToks ++ RevOutToks); ParamsAndBody -> {NToks, Arguments} = subst_macros_get_args(Toks, []), Expand the varibles ExpandedParamsToks = subst_macros_subst_args_for_vars(ParamsAndBody, Arguments), RevExpandedOtherMacrosToks = subst_macros_rev(ExpandedParamsToks, MacroDict, []), subst_macros_rev(NToks, MacroDict, RevExpandedOtherMacrosToks ++ RevOutToks) end; subst_macros_rev([{'?', _}, {_, _, Name} | Toks], MacroDict, RevOutToks) -> {[], MacroValue} = dict:fetch(Name, MacroDict), RevExpandedOtherMacrosToks = subst_macros_rev(MacroValue, MacroDict, []), subst_macros_rev(Toks, MacroDict, RevExpandedOtherMacrosToks ++ RevOutToks); subst_macros_rev([Tok | Toks], MacroDict, RevOutToks) -> subst_macros_rev(Toks, MacroDict, [Tok | RevOutToks]); subst_macros_rev([], _MacroDict, RevOutToks) -> RevOutToks. subst_macros_get_args([{')', _} | Toks], RevArgs) -> {Toks, reverse(RevArgs)}; subst_macros_get_args([{',', _}, {var, _, ArgName} | Toks], RevArgs) -> subst_macros_get_args(Toks, [ArgName | RevArgs]); subst_macros_get_args([{var, _, ArgName} | Toks], RevArgs) -> subst_macros_get_args(Toks, [ArgName | RevArgs]). subst_macros_subst_args_for_vars({[], BodyToks}, []) -> BodyToks; subst_macros_subst_args_for_vars({[Param | Params], BodyToks}, [Arg | Args]) -> NBodyToks = keyreplace(Param, 3, BodyToks, {var, 1, Arg}), subst_macros_subst_args_for_vars({Params, NBodyToks}, Args). read_include_file(Filename, IncludeSearchPath) -> case file:path_open(IncludeSearchPath, Filename, [read, raw, binary]) of {ok, IoDevice, FullName} -> {ok, Data} = file:read(IoDevice, filelib:file_size(FullName)), file:close(IoDevice), binary_to_list(Data); {error, Reason} -> throw({failed_to_read_include_file, Reason, Filename, IncludeSearchPath}) end.
e067c850cc747b1310c46cb7839c28b7f301b8de8c615032f3b51c7df0182a2b
geneweb/geneweb
notes.mli
val path_of_fnotes : string -> string val commit_notes : Config.config -> Gwdb.base -> string -> string -> unit val notes_links_db : Config.config -> Gwdb.base -> bool -> (Mutil.StrSet.elt * (Gwdb.iper, Gwdb.ifam) Def.NLDB.page list) list val update_notes_links_db : Gwdb.base -> (Gwdb.iper, Gwdb.ifam) Def.NLDB.page -> string -> unit val file_path : Config.config -> Gwdb.base -> string -> string val read_notes : Gwdb.base -> string -> (string * string) list * string val merge_possible_aliases : Config.config -> (('a, 'b) Def.NLDB.page * (string list * 'c list)) list -> (('a, 'b) Def.NLDB.page * (string list * 'c list)) list val source : Config.config -> Gwdb.base -> string -> Adef.safe_string * [ source conf base str ] Interprets wiki syntax in a " source " context : - supposed to be one line - no < p > surrounding tag Interprets wiki syntax in a "source" context: - supposed to be one line - no <p> surrounding tag *) val note : Config.config -> Gwdb.base -> (char * (unit -> string)) list -> string -> Adef.safe_string (** [note conf base env str] Interprets wiki syntax in a "note" context: - [env] is available during [str] interpretation *) val person_note : Config.config -> Gwdb.base -> Gwdb.person -> string -> Adef.safe_string (** [person_note conf base person str] Interprets wiki syntax in a "note" context: - env is available during [str] interpretation with [i] variable bound to person image *) val source_note : Config.config -> Gwdb.base -> Gwdb.person -> string -> Adef.safe_string (** [source_note conf base person str] Interprets wiki syntax in a "source" context: - env is available during [str] interpretation with [i] variable bound to person image *) val source_note_with_env : Config.config -> Gwdb.base -> (char * (unit -> string)) list -> string -> Adef.safe_string (** [source_note_with_env conf base env str] Interprets wiki syntax in a "source" context with a predefined env. *)
null
https://raw.githubusercontent.com/geneweb/geneweb/747f43da396a706bd1da60d34c04493a190edf0f/lib/notes.mli
ocaml
* [note conf base env str] Interprets wiki syntax in a "note" context: - [env] is available during [str] interpretation * [person_note conf base person str] Interprets wiki syntax in a "note" context: - env is available during [str] interpretation with [i] variable bound to person image * [source_note conf base person str] Interprets wiki syntax in a "source" context: - env is available during [str] interpretation with [i] variable bound to person image * [source_note_with_env conf base env str] Interprets wiki syntax in a "source" context with a predefined env.
val path_of_fnotes : string -> string val commit_notes : Config.config -> Gwdb.base -> string -> string -> unit val notes_links_db : Config.config -> Gwdb.base -> bool -> (Mutil.StrSet.elt * (Gwdb.iper, Gwdb.ifam) Def.NLDB.page list) list val update_notes_links_db : Gwdb.base -> (Gwdb.iper, Gwdb.ifam) Def.NLDB.page -> string -> unit val file_path : Config.config -> Gwdb.base -> string -> string val read_notes : Gwdb.base -> string -> (string * string) list * string val merge_possible_aliases : Config.config -> (('a, 'b) Def.NLDB.page * (string list * 'c list)) list -> (('a, 'b) Def.NLDB.page * (string list * 'c list)) list val source : Config.config -> Gwdb.base -> string -> Adef.safe_string * [ source conf base str ] Interprets wiki syntax in a " source " context : - supposed to be one line - no < p > surrounding tag Interprets wiki syntax in a "source" context: - supposed to be one line - no <p> surrounding tag *) val note : Config.config -> Gwdb.base -> (char * (unit -> string)) list -> string -> Adef.safe_string val person_note : Config.config -> Gwdb.base -> Gwdb.person -> string -> Adef.safe_string val source_note : Config.config -> Gwdb.base -> Gwdb.person -> string -> Adef.safe_string val source_note_with_env : Config.config -> Gwdb.base -> (char * (unit -> string)) list -> string -> Adef.safe_string
cf43f2efb680f832701645a7486a4db3ebf534a79f51020f028734d2313b3394
facebookarchive/pfff
model_codemap.ml
* * Copyright ( C ) 2013 Facebook * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation , with the * special exception on linking described in file license.txt . * * This library is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file * license.txt for more details . * * Copyright (C) 2013 Facebook * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation, with the * special exception on linking described in file license.txt. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * license.txt for more details. *) open Common open Common2.ArithFloatInfix module F = Figures module T = Treemap (*****************************************************************************) (* Prelude *) (*****************************************************************************) TODO : factorize with pfff / code_map / model2.ml ? (*****************************************************************************) (* Types *) (*****************************************************************************) type world_client = { project: string; (* readable path *) path: string; size: string; rects: Treemap.treemap_rendering; (* to show labels without leading path *) root: Common.dirname; (* viewport, device coordinates *) width: int; height: int; } type fileinfo_client = { nblines: float; (* more convenient than int *) style: file_rendering_style; } and file_rendering_style = | Regular of string list (* lines *) | Fancy of (lines * Highlight_code.category option * Common2.filepos) list | Nothing and lines = (string, unit) Common2.either list (*****************************************************************************) (* Coordinate system *) (*****************************************************************************) in treemap.ml : xy_ratio = 1.71 (*****************************************************************************) (* Misc *) (*****************************************************************************) type context = Dom_html.canvasRenderingContext2D Js.t (*****************************************************************************) (* Point -> treemap info *) (*****************************************************************************) alt : could use Cairo_bigarray and the pixel trick if * it takes too long to detect which rectangle is under the cursor . * also sort the rectangles ... or have some kind of BSP . * it takes too long to detect which rectangle is under the cursor. * coud also sort the rectangles ... or have some kind of BSP. *) let find_rectangle_at_user_point w user = let rects = w.rects in if List.length rects = 1 then we are fully zommed , this treemap will have tr_depth = 1 but we return * it * it *) let x = List.hd rects in Some (x, [], x) else let matching_rects = rects +> List.filter (fun r -> F.point_is_in_rectangle user r.T.tr_rect && r.T.tr_depth > 1 ) +> List.map (fun r -> r, r.T.tr_depth) +> Common.sort_by_val_highfirst +> List.map fst in match matching_rects with | [] -> None | [x] -> Some (x, [], x) | _ -> Some (Common2.head_middle_tail matching_rects)
null
https://raw.githubusercontent.com/facebookarchive/pfff/ec21095ab7d445559576513a63314e794378c367/web/code_map/model_codemap.ml
ocaml
*************************************************************************** Prelude *************************************************************************** *************************************************************************** Types *************************************************************************** readable path to show labels without leading path viewport, device coordinates more convenient than int lines *************************************************************************** Coordinate system *************************************************************************** *************************************************************************** Misc *************************************************************************** *************************************************************************** Point -> treemap info ***************************************************************************
* * Copyright ( C ) 2013 Facebook * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation , with the * special exception on linking described in file license.txt . * * This library is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file * license.txt for more details . * * Copyright (C) 2013 Facebook * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation, with the * special exception on linking described in file license.txt. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * license.txt for more details. *) open Common open Common2.ArithFloatInfix module F = Figures module T = Treemap TODO : factorize with pfff / code_map / model2.ml ? type world_client = { project: string; path: string; size: string; rects: Treemap.treemap_rendering; root: Common.dirname; width: int; height: int; } type fileinfo_client = { style: file_rendering_style; } and file_rendering_style = | Fancy of (lines * Highlight_code.category option * Common2.filepos) list | Nothing and lines = (string, unit) Common2.either list in treemap.ml : xy_ratio = 1.71 type context = Dom_html.canvasRenderingContext2D Js.t alt : could use Cairo_bigarray and the pixel trick if * it takes too long to detect which rectangle is under the cursor . * also sort the rectangles ... or have some kind of BSP . * it takes too long to detect which rectangle is under the cursor. * coud also sort the rectangles ... or have some kind of BSP. *) let find_rectangle_at_user_point w user = let rects = w.rects in if List.length rects = 1 then we are fully zommed , this treemap will have tr_depth = 1 but we return * it * it *) let x = List.hd rects in Some (x, [], x) else let matching_rects = rects +> List.filter (fun r -> F.point_is_in_rectangle user r.T.tr_rect && r.T.tr_depth > 1 ) +> List.map (fun r -> r, r.T.tr_depth) +> Common.sort_by_val_highfirst +> List.map fst in match matching_rects with | [] -> None | [x] -> Some (x, [], x) | _ -> Some (Common2.head_middle_tail matching_rects)
76b8e41fed56160e1630b9cd18c5659f2764965713e733339d1de5efb376d1ff
bennn/dissertation
main.rkt
#lang typed/racket/base AKA quick-test.rkt ;; ----------------------------------------------------------------------------- (require require-typed-check "../base/core-types.rkt" "../base/quad-types.rkt" (only-in typed/racket/class new send) ) (require/typed/check "world.rkt" [world:allow-hyphenated-last-word-in-paragraph Boolean] [world:quality-default (Parameterof Index)] [world:draft-quality Index]) (require/typed/check "quad-main.rkt" [typeset (-> Quad DocQuad)]) (require/typed/check "quick-sample.rkt" [quick-sample (-> Quad)]) (require/typed/check "render.rkt" [pdf-renderer% (Class [render-to-file (Quad Path-String -> Void)] [render-element (Quad -> Any)] [render-page ((Listof Quad) -> Void)] [render-word (Quad -> Any)] [render (-> Quad Any)] [finalize (-> Any Any)] [setup (-> Quad Quad)] )]) ;; ============================================================================= (parameterize ([world:quality-default world:draft-quality]) (time (begin (define to (typeset (quick-sample))) (send (new pdf-renderer%) render-to-file to "./output.pdf") (void))))
null
https://raw.githubusercontent.com/bennn/dissertation/779bfe6f8fee19092849b7e2cfc476df33e9357b/dissertation/scrbl/jfp-2019/benchmarks/quadT/typed/main.rkt
racket
----------------------------------------------------------------------------- =============================================================================
#lang typed/racket/base AKA quick-test.rkt (require require-typed-check "../base/core-types.rkt" "../base/quad-types.rkt" (only-in typed/racket/class new send) ) (require/typed/check "world.rkt" [world:allow-hyphenated-last-word-in-paragraph Boolean] [world:quality-default (Parameterof Index)] [world:draft-quality Index]) (require/typed/check "quad-main.rkt" [typeset (-> Quad DocQuad)]) (require/typed/check "quick-sample.rkt" [quick-sample (-> Quad)]) (require/typed/check "render.rkt" [pdf-renderer% (Class [render-to-file (Quad Path-String -> Void)] [render-element (Quad -> Any)] [render-page ((Listof Quad) -> Void)] [render-word (Quad -> Any)] [render (-> Quad Any)] [finalize (-> Any Any)] [setup (-> Quad Quad)] )]) (parameterize ([world:quality-default world:draft-quality]) (time (begin (define to (typeset (quick-sample))) (send (new pdf-renderer%) render-to-file to "./output.pdf") (void))))
d056f28ba5b8570e3b282e62649aa82320ed9d86cd0cd2d477909e258420895d
pkamenarsky/replica
Render.hs
{-# LANGUAGE OverloadedStrings #-} module Replica.VDOM.Render where import qualified Data.Text as T import qualified Data.Text.Lazy.Builder as TB import qualified Data.Map as M import Replica.VDOM.Types (HTML, VDOM(VNode,VLeaf,VText,VRawText), Attrs, Attr(AText,ABool,AEvent,AMap)) renderHTML :: HTML -> TB.Builder renderHTML = mconcat . map renderVDOM renderVDOM :: VDOM -> TB.Builder renderVDOM vdom = case vdom of VNode name attrs _mNamespace children -> mconcat [ tag $ TB.fromText name <> renderAttrs attrs , mconcat $ map renderVDOM children , tag $ sl <> TB.fromText name ] VLeaf name attrs _mNamespace -> tag $ TB.fromText name <> renderAttrs attrs VText txt -> renderEscapedString txt VRawText txt -> TB.fromText txt where tag a = TB.singleton '<' <> a <> TB.singleton '>' sl = TB.singleton '/' renderAttrs :: Attrs -> TB.Builder renderAttrs = foldMap (TB.singleton ' ' <>) . _renderAttrs where dq = TB.singleton '"' eq = TB.singleton '=' _renderAttrs :: Attrs -> [TB.Builder] _renderAttrs = foldMap (uncurry _renderAttr) . M.toList _renderAttr :: T.Text -> Attr -> [TB.Builder] _renderAttr name value = case value of AText txt -> [TB.fromText name <> eq <> dq <> renderEscapedString txt <> dq] ABool True -> [TB.fromText name] ABool False -> [] AEvent _ _ -> [] AMap attrs -> _renderAttrs attrs renderEscapedString :: T.Text -> TB.Builder renderEscapedString = TB.fromText . T.concatMap escape where escape :: Char -> T.Text escape '<' = "&lt;" escape '>' = "&gt;" escape '&' = "&amp;" escape '"' = "&quot;" escape '\'' = "&#39;" escape c = T.singleton c
null
https://raw.githubusercontent.com/pkamenarsky/replica/f01bbfb77c9536a1ea6ab011fb38351d91cb0217/src/Replica/VDOM/Render.hs
haskell
# LANGUAGE OverloadedStrings #
module Replica.VDOM.Render where import qualified Data.Text as T import qualified Data.Text.Lazy.Builder as TB import qualified Data.Map as M import Replica.VDOM.Types (HTML, VDOM(VNode,VLeaf,VText,VRawText), Attrs, Attr(AText,ABool,AEvent,AMap)) renderHTML :: HTML -> TB.Builder renderHTML = mconcat . map renderVDOM renderVDOM :: VDOM -> TB.Builder renderVDOM vdom = case vdom of VNode name attrs _mNamespace children -> mconcat [ tag $ TB.fromText name <> renderAttrs attrs , mconcat $ map renderVDOM children , tag $ sl <> TB.fromText name ] VLeaf name attrs _mNamespace -> tag $ TB.fromText name <> renderAttrs attrs VText txt -> renderEscapedString txt VRawText txt -> TB.fromText txt where tag a = TB.singleton '<' <> a <> TB.singleton '>' sl = TB.singleton '/' renderAttrs :: Attrs -> TB.Builder renderAttrs = foldMap (TB.singleton ' ' <>) . _renderAttrs where dq = TB.singleton '"' eq = TB.singleton '=' _renderAttrs :: Attrs -> [TB.Builder] _renderAttrs = foldMap (uncurry _renderAttr) . M.toList _renderAttr :: T.Text -> Attr -> [TB.Builder] _renderAttr name value = case value of AText txt -> [TB.fromText name <> eq <> dq <> renderEscapedString txt <> dq] ABool True -> [TB.fromText name] ABool False -> [] AEvent _ _ -> [] AMap attrs -> _renderAttrs attrs renderEscapedString :: T.Text -> TB.Builder renderEscapedString = TB.fromText . T.concatMap escape where escape :: Char -> T.Text escape '<' = "&lt;" escape '>' = "&gt;" escape '&' = "&amp;" escape '"' = "&quot;" escape '\'' = "&#39;" escape c = T.singleton c
2e814c2b741f71b8078b255eebd59006cbd7d4bd393db371ecd356424b01a1d9
michiakig/sicp
ex-1.09.scm
;;;; Structure and Interpretation of Computer Programs Chapter 1 Section 2 Procedures and the Processes They Generate Exercise 1.09 illustrate iterative and recursive procedures (define (+ a b) (if (= a 0) b (inc (+ (dec a) b)))) ;; (+ 4 5) ;; (inc (+ 3 5)) ;; (inc (inc (+ 2 5))) ;; (inc (inc (inc (+ 1 5)))) ;; (inc (inc (inc (inc (+ 0 5))))) ;; (inc (inc (inc (inc 5)))) ;; (inc (inc (inc 6))) ;; (inc (inc 7)) ;; (inc 8) 9 ;; This is clearly a recursive process. (define (+ a b) (if (= a 0) b (+ (dec a) (inc b)))) ;; (+ 4 5) ;; (+ 3 6) ;; (+ 2 7) ;; (+ 1 8) ;; (+ 0 9) 9 ;; This clearly is an iterative process.
null
https://raw.githubusercontent.com/michiakig/sicp/1aa445f00b7895dbfaa29cf6984b825b4e5af492/ch1/ex-1.09.scm
scheme
Structure and Interpretation of Computer Programs (+ 4 5) (inc (+ 3 5)) (inc (inc (+ 2 5))) (inc (inc (inc (+ 1 5)))) (inc (inc (inc (inc (+ 0 5))))) (inc (inc (inc (inc 5)))) (inc (inc (inc 6))) (inc (inc 7)) (inc 8) This is clearly a recursive process. (+ 4 5) (+ 3 6) (+ 2 7) (+ 1 8) (+ 0 9) This clearly is an iterative process.
Chapter 1 Section 2 Procedures and the Processes They Generate Exercise 1.09 illustrate iterative and recursive procedures (define (+ a b) (if (= a 0) b (inc (+ (dec a) b)))) 9 (define (+ a b) (if (= a 0) b (+ (dec a) (inc b)))) 9
558e02a49af7a0ce5664ce7b8cca73e6cdbaf47e6d861a8eff40d359f96eae4b
dada-lang/dada-model
opsem.rkt
#lang racket (require "opsem/lang.rkt" "opsem/small-step.rkt") (provide Dada Dada-reduction)
null
https://raw.githubusercontent.com/dada-lang/dada-model/7833849ebb10e8c458d168c597bcc289569dc707/racket/opsem.rkt
racket
#lang racket (require "opsem/lang.rkt" "opsem/small-step.rkt") (provide Dada Dada-reduction)
3d1afd55a3fca350b84390ef09dde2dfe5f0439b6de3242f14ce90fb67ba84dc
basho/clique
clique_app.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2014 - 2017 Basho Technologies , Inc. %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% ------------------------------------------------------------------- -module(clique_app). -behaviour(application). %% Application callbacks -export([start/2, stop/1]). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. %% =================================================================== %% Application callbacks %% =================================================================== start(_StartType, _StartArgs) -> clique_sup:start_link(). stop(_State) -> ok. %% =================================================================== %% Tests %% =================================================================== -ifdef(TEST). start_stop_test_() -> {setup, fun() -> LogDir = clique:create_test_dir(), ConLog = filename:join(LogDir, "console.log"), ErrLog = filename:join(LogDir, "error.log"), CrashLog = filename:join(LogDir, "crash.log"), application:load(sasl), application:set_env(sasl, errlog_type, error), application:load(lager), application:set_env(lager, crash_log, CrashLog), application:set_env(lager, handlers, [ {lager_console_backend, warn}, {lager_file_backend, [{file, ErrLog}, {level, warn}]}, {lager_file_backend, [{file, ConLog}, {level, debug}]}]), _ = clique:ensure_stopped(), LogDir end, fun clique:delete_test_dir/1, fun() -> Ret = application:ensure_all_started(clique), ?assertMatch({ok, _}, Ret), {_, Started} = Ret, lists:foreach(fun(App) -> ?assertEqual(ok, application:stop(App)) end, lists:reverse(Started)) end}. -endif. % TEST
null
https://raw.githubusercontent.com/basho/clique/4014357e4e677164b890fdad08a45cfa54b3e8f3/src/clique_app.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- Application callbacks =================================================================== Application callbacks =================================================================== =================================================================== Tests =================================================================== TEST
Copyright ( c ) 2014 - 2017 Basho Technologies , Inc. This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(clique_app). -behaviour(application). -export([start/2, stop/1]). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. start(_StartType, _StartArgs) -> clique_sup:start_link(). stop(_State) -> ok. -ifdef(TEST). start_stop_test_() -> {setup, fun() -> LogDir = clique:create_test_dir(), ConLog = filename:join(LogDir, "console.log"), ErrLog = filename:join(LogDir, "error.log"), CrashLog = filename:join(LogDir, "crash.log"), application:load(sasl), application:set_env(sasl, errlog_type, error), application:load(lager), application:set_env(lager, crash_log, CrashLog), application:set_env(lager, handlers, [ {lager_console_backend, warn}, {lager_file_backend, [{file, ErrLog}, {level, warn}]}, {lager_file_backend, [{file, ConLog}, {level, debug}]}]), _ = clique:ensure_stopped(), LogDir end, fun clique:delete_test_dir/1, fun() -> Ret = application:ensure_all_started(clique), ?assertMatch({ok, _}, Ret), {_, Started} = Ret, lists:foreach(fun(App) -> ?assertEqual(ok, application:stop(App)) end, lists:reverse(Started)) end}.
3aaae8ee69d767df10868ca48323d29fa309e93e3bc7ca4860a2ddd30ee66957
BranchTaken/Hemlock
test_union.ml
open! Basis.Rudiments open! Basis open MapTest open Map let test () = let test ks0 ks1 = begin let map0 = of_klist ks0 in let map1 = of_klist ks1 in let map = union ~f:merge map0 map1 in let kvs = to_alist map in List.iter ks0 ~f:(fun k -> assert ((mem k map) && (mem k map0))); List.iter ks1 ~f:(fun k -> assert ((mem k map) && (mem k map1))); List.iter kvs ~f:(fun (k, _) -> assert ((mem k map0) || (mem k map1))); end in let test_disjoint ks0 ks1 = begin let map0 = of_klist ks0 in let map1 = of_klist ks1 in let map = union ~f:merge map0 map1 in assert ((length map) = (length map0) + (length map1)); end in let test_lists = [ []; [0L]; [0L; 1L]; [0L; 1L; 2L]; [0L; 1L; 66L]; [0L; 1L; 66L; 91L]; [42L; 420L]; [42L; 420L; 421L]; [42L; 420L; 4200L]; ] in let test_disjoint_list_pairs = [ ([], [0L]); ([0L], [1L]); ([0L], [1L; 2L]); ([0L; 1L], [2L; 3L]); ([0L; 1L], [2L; 3L; 4L]); ([0L; 1L; 2L], [3L; 4L; 5L]) ] in List.iteri test_lists ~f:(fun i ks0 -> List.iteri test_lists ~f:(fun j ks1 -> if i <= j then begin test ks0 ks1; test ks1 ks0 end ) ); List.iter test_disjoint_list_pairs ~f:(fun (ks0, ks1) -> test_disjoint ks0 ks1; test_disjoint ks0 (List.rev ks1); test_disjoint (List.rev ks0) ks1; test_disjoint (List.rev ks0) (List.rev ks1); ) let _ = test ()
null
https://raw.githubusercontent.com/BranchTaken/Hemlock/07922d4658ca6ecf37dfd46f5aca31c8b58e06e4/bootstrap/test/basis/map/test_union.ml
ocaml
open! Basis.Rudiments open! Basis open MapTest open Map let test () = let test ks0 ks1 = begin let map0 = of_klist ks0 in let map1 = of_klist ks1 in let map = union ~f:merge map0 map1 in let kvs = to_alist map in List.iter ks0 ~f:(fun k -> assert ((mem k map) && (mem k map0))); List.iter ks1 ~f:(fun k -> assert ((mem k map) && (mem k map1))); List.iter kvs ~f:(fun (k, _) -> assert ((mem k map0) || (mem k map1))); end in let test_disjoint ks0 ks1 = begin let map0 = of_klist ks0 in let map1 = of_klist ks1 in let map = union ~f:merge map0 map1 in assert ((length map) = (length map0) + (length map1)); end in let test_lists = [ []; [0L]; [0L; 1L]; [0L; 1L; 2L]; [0L; 1L; 66L]; [0L; 1L; 66L; 91L]; [42L; 420L]; [42L; 420L; 421L]; [42L; 420L; 4200L]; ] in let test_disjoint_list_pairs = [ ([], [0L]); ([0L], [1L]); ([0L], [1L; 2L]); ([0L; 1L], [2L; 3L]); ([0L; 1L], [2L; 3L; 4L]); ([0L; 1L; 2L], [3L; 4L; 5L]) ] in List.iteri test_lists ~f:(fun i ks0 -> List.iteri test_lists ~f:(fun j ks1 -> if i <= j then begin test ks0 ks1; test ks1 ks0 end ) ); List.iter test_disjoint_list_pairs ~f:(fun (ks0, ks1) -> test_disjoint ks0 ks1; test_disjoint ks0 (List.rev ks1); test_disjoint (List.rev ks0) ks1; test_disjoint (List.rev ks0) (List.rev ks1); ) let _ = test ()