_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 |
|---|---|---|---|---|---|---|---|---|
f43375e3d82f8f251acd7b906a75bd0fb3958148446a13f0e7db3349bd3feab2 | haskellari/postgresql-simple | SqlQQ.hs | # LANGUAGE CPP #
#if __GLASGOW_HASKELL__ >= 800
{-# LANGUAGE TemplateHaskellQuotes #-}
#else
# LANGUAGE TemplateHaskell #
#endif
------------------------------------------------------------------------------
-- |
-- Module: Database.PostgreSQL.Simple.SqlQQ
Copyright : ( c ) 2011 - 2012
License : BSD3
Maintainer : < >
-- Stability: experimental
--
------------------------------------------------------------------------------
module Database.PostgreSQL.Simple.SqlQQ (sql) where
import Database.PostgreSQL.Simple.Types (Query)
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import Data.Char
import Data.String
-- | 'sql' is a quasiquoter that eases the syntactic burden
of writing big sql statements in Haskell source code . For example :
--
-- > {-# LANGUAGE QuasiQuotes #-}
-- >
-- > query conn [sql| SELECT column_a, column_b
> FROM table1 NATURAL JOIN
-- > WHERE ? <= time AND time < ?
-- > AND name LIKE ?
-- > ORDER BY size DESC
> LIMIT 100 | ]
-- > (beginTime,endTime,string)
--
-- This quasiquoter returns a literal string expression of type 'Query',
-- and attempts to minimize whitespace; otherwise the above query would
consist of approximately half whitespace when sent to the database
-- backend. It also recognizes and strips out standard sql comments "--".
--
-- The implementation of the whitespace reducer is currently incomplete.
-- Thus it can mess up your syntax in cases where whitespace should be
-- preserved as-is. It does preserve whitespace inside standard SQL string
-- literals. But it can get confused by the non-standard PostgreSQL string
literal syntax ( which is the default setting in PostgreSQL 8 and below ) ,
-- the extended escape string syntax, quoted identifiers, and other similar
-- constructs.
--
-- Of course, this caveat only applies to text written inside the SQL
-- quasiquoter; whitespace reduction is a compile-time computation and
-- thus will not touch the @string@ parameter above, which is a run-time
-- value.
--
-- Also note that this will not work if the substring @|]@ is contained
-- in the query.
sql :: QuasiQuoter
sql = QuasiQuoter
{ quotePat = error "Database.PostgreSQL.Simple.SqlQQ.sql: quasiquoter used in pattern context"
, quoteType = error "Database.PostgreSQL.Simple.SqlQQ.sql: quasiquoter used in type context"
, quoteExp = sqlExp
, quoteDec = error "Database.PostgreSQL.Simple.SqlQQ.sql: quasiquoter used in declaration context"
}
sqlExp :: String -> Q Exp
sqlExp = appE [| fromString :: String -> Query |] . stringE . minimizeSpace
minimizeSpace :: String -> String
minimizeSpace = drop 1 . reduceSpace
where
needsReduced [] = False
needsReduced ('-':'-':_) = True
needsReduced (x:_) = isSpace x
reduceSpace xs =
case dropWhile isSpace xs of
[] -> []
('-':'-':ys) -> reduceSpace (dropWhile (/= '\n') ys)
ys -> ' ' : insql ys
insql ('\'':xs) = '\'' : instring xs
insql xs | needsReduced xs = reduceSpace xs
insql (x:xs) = x : insql xs
insql [] = []
instring ('\'':'\'':xs) = '\'':'\'': instring xs
instring ('\'':xs) = '\'': insql xs
instring (x:xs) = x : instring xs
instring [] = error "Database.PostgreSQL.Simple.SqlQQ.sql: string literal not terminated"
| null | https://raw.githubusercontent.com/haskellari/postgresql-simple/6cabb13959310f32a15285f8e41c2d053403d687/src/Database/PostgreSQL/Simple/SqlQQ.hs | haskell | # LANGUAGE TemplateHaskellQuotes #
----------------------------------------------------------------------------
|
Module: Database.PostgreSQL.Simple.SqlQQ
Stability: experimental
----------------------------------------------------------------------------
| 'sql' is a quasiquoter that eases the syntactic burden
> {-# LANGUAGE QuasiQuotes #-}
>
> query conn [sql| SELECT column_a, column_b
> WHERE ? <= time AND time < ?
> AND name LIKE ?
> ORDER BY size DESC
> (beginTime,endTime,string)
This quasiquoter returns a literal string expression of type 'Query',
and attempts to minimize whitespace; otherwise the above query would
backend. It also recognizes and strips out standard sql comments "--".
The implementation of the whitespace reducer is currently incomplete.
Thus it can mess up your syntax in cases where whitespace should be
preserved as-is. It does preserve whitespace inside standard SQL string
literals. But it can get confused by the non-standard PostgreSQL string
the extended escape string syntax, quoted identifiers, and other similar
constructs.
Of course, this caveat only applies to text written inside the SQL
quasiquoter; whitespace reduction is a compile-time computation and
thus will not touch the @string@ parameter above, which is a run-time
value.
Also note that this will not work if the substring @|]@ is contained
in the query. | # LANGUAGE CPP #
#if __GLASGOW_HASKELL__ >= 800
#else
# LANGUAGE TemplateHaskell #
#endif
Copyright : ( c ) 2011 - 2012
License : BSD3
Maintainer : < >
module Database.PostgreSQL.Simple.SqlQQ (sql) where
import Database.PostgreSQL.Simple.Types (Query)
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import Data.Char
import Data.String
of writing big sql statements in Haskell source code . For example :
> FROM table1 NATURAL JOIN
> LIMIT 100 | ]
consist of approximately half whitespace when sent to the database
literal syntax ( which is the default setting in PostgreSQL 8 and below ) ,
sql :: QuasiQuoter
sql = QuasiQuoter
{ quotePat = error "Database.PostgreSQL.Simple.SqlQQ.sql: quasiquoter used in pattern context"
, quoteType = error "Database.PostgreSQL.Simple.SqlQQ.sql: quasiquoter used in type context"
, quoteExp = sqlExp
, quoteDec = error "Database.PostgreSQL.Simple.SqlQQ.sql: quasiquoter used in declaration context"
}
sqlExp :: String -> Q Exp
sqlExp = appE [| fromString :: String -> Query |] . stringE . minimizeSpace
minimizeSpace :: String -> String
minimizeSpace = drop 1 . reduceSpace
where
needsReduced [] = False
needsReduced ('-':'-':_) = True
needsReduced (x:_) = isSpace x
reduceSpace xs =
case dropWhile isSpace xs of
[] -> []
('-':'-':ys) -> reduceSpace (dropWhile (/= '\n') ys)
ys -> ' ' : insql ys
insql ('\'':xs) = '\'' : instring xs
insql xs | needsReduced xs = reduceSpace xs
insql (x:xs) = x : insql xs
insql [] = []
instring ('\'':'\'':xs) = '\'':'\'': instring xs
instring ('\'':xs) = '\'': insql xs
instring (x:xs) = x : instring xs
instring [] = error "Database.PostgreSQL.Simple.SqlQQ.sql: string literal not terminated"
|
7513811424cb5ba480c67100159cc2f8e2da68225bcb0b14ed9c18a3444b303a | simonmar/parconc-examples | Infer.hs | --
-- Adapted from the program "infer", believed to have been originally
authored by , and used in the nofib benchmark suite
since at least the late 90s .
--
module Infer (inferTerm,inferTop) where
import Data.List(nub)
import MyList (minus)
import Type (TVarId, MonoType (..), PolyType (All),
arrow, intType, freeTVarMono)
import Term
import Substitution (Sub, applySub, lookupSub, makeSub)
import Environment
import InferMonad
import Control.Monad.Par.Scheds.Trace
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Maybe
import Control.Monad
specialiseI :: PolyType -> Infer MonoType
specialiseI (All xxs tt) = freshesI (length xxs) `thenI` (\yys ->
returnI (applySubs xxs yys tt))
applySubs :: [TVarId] -> [MonoType] -> MonoType -> MonoType
applySubs xxs yys tt = applySub (makeSub (zip xxs yys)) tt
generaliseI :: Env -> MonoType -> Infer PolyType
generaliseI aa tt = getSubI `thenI` (\s ->
let aaVars = nub (freeTVarSubEnv s aa) in
let ttVars = nub (freeTVarMono tt) in
let xxs = ttVars `minus` aaVars in
returnI (All xxs tt)
)
freeTVarSubEnv :: Sub -> Env -> [TVarId]
freeTVarSubEnv s aa = concat (map (freeTVarMono . lookupSub s)
(freeTVarEnv aa))
inferTerm :: Env -> Term -> Infer MonoType
inferTerm _ (Int _) = returnI intType
inferTerm aa (Var x) =
(x `elem` domEnv aa) `guardI` (
let ss = lookupEnv aa x in
specialiseI ss `thenI` (\tt ->
substituteI tt `thenI` (\uu ->
returnI uu)))
inferTerm aa (Abs x v) =
freshI `thenI` (\xx ->
inferTerm (extendLocal aa x xx) v `thenI` (\vv ->
substituteI xx `thenI` (\uu ->
returnI (uu `arrow` vv))))
inferTerm aa (App t u) =
inferTerm aa t `thenI` (\tt ->
inferTerm aa u `thenI` (\uu ->
freshI `thenI` (\xx ->
unifyI tt (uu `arrow` xx) `thenI` (\() ->
substituteI xx `thenI` (\vv ->
returnI vv)))))
inferTerm aa (Let x u v) = do
ss <- inferRhs aa u
inferTerm (extendGlobal aa x ss) v
inferRhs :: Env -> Term -> Infer PolyType
inferRhs aa u = do
uu <- inferTerm aa u
generaliseI aa uu
inferTopRhs :: Env -> Term -> PolyType
inferTopRhs aa u = useI (error "type error") $ do
uu <- inferTerm aa u
generaliseI aa uu
type TopEnv = Map VarId (IVar PolyType)
-- <<inferTop
inferTop :: TopEnv -> [(VarId,Term)] -> Par [(VarId,PolyType)]
inferTop topenv0 binds = do
< 1 >
< 2 >
-- >>
-- <<inferBind
inferBind :: TopEnv -> (VarId,Term) -> Par TopEnv
inferBind topenv (x,u) = do
< 1 >
< 2 >
let fu = Set.toList (freeVars u) -- <3>
< 4 >
< 5 >
< 6 >
< 7 >
-- >>
| null | https://raw.githubusercontent.com/simonmar/parconc-examples/840a3f508f9bb6e03961e1b90311a1edd945adba/parinfer/Infer.hs | haskell |
Adapted from the program "infer", believed to have been originally
<<inferTop
>>
<<inferBind
<3>
>> | authored by , and used in the nofib benchmark suite
since at least the late 90s .
module Infer (inferTerm,inferTop) where
import Data.List(nub)
import MyList (minus)
import Type (TVarId, MonoType (..), PolyType (All),
arrow, intType, freeTVarMono)
import Term
import Substitution (Sub, applySub, lookupSub, makeSub)
import Environment
import InferMonad
import Control.Monad.Par.Scheds.Trace
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Maybe
import Control.Monad
specialiseI :: PolyType -> Infer MonoType
specialiseI (All xxs tt) = freshesI (length xxs) `thenI` (\yys ->
returnI (applySubs xxs yys tt))
applySubs :: [TVarId] -> [MonoType] -> MonoType -> MonoType
applySubs xxs yys tt = applySub (makeSub (zip xxs yys)) tt
generaliseI :: Env -> MonoType -> Infer PolyType
generaliseI aa tt = getSubI `thenI` (\s ->
let aaVars = nub (freeTVarSubEnv s aa) in
let ttVars = nub (freeTVarMono tt) in
let xxs = ttVars `minus` aaVars in
returnI (All xxs tt)
)
freeTVarSubEnv :: Sub -> Env -> [TVarId]
freeTVarSubEnv s aa = concat (map (freeTVarMono . lookupSub s)
(freeTVarEnv aa))
inferTerm :: Env -> Term -> Infer MonoType
inferTerm _ (Int _) = returnI intType
inferTerm aa (Var x) =
(x `elem` domEnv aa) `guardI` (
let ss = lookupEnv aa x in
specialiseI ss `thenI` (\tt ->
substituteI tt `thenI` (\uu ->
returnI uu)))
inferTerm aa (Abs x v) =
freshI `thenI` (\xx ->
inferTerm (extendLocal aa x xx) v `thenI` (\vv ->
substituteI xx `thenI` (\uu ->
returnI (uu `arrow` vv))))
inferTerm aa (App t u) =
inferTerm aa t `thenI` (\tt ->
inferTerm aa u `thenI` (\uu ->
freshI `thenI` (\xx ->
unifyI tt (uu `arrow` xx) `thenI` (\() ->
substituteI xx `thenI` (\vv ->
returnI vv)))))
inferTerm aa (Let x u v) = do
ss <- inferRhs aa u
inferTerm (extendGlobal aa x ss) v
inferRhs :: Env -> Term -> Infer PolyType
inferRhs aa u = do
uu <- inferTerm aa u
generaliseI aa uu
inferTopRhs :: Env -> Term -> PolyType
inferTopRhs aa u = useI (error "type error") $ do
uu <- inferTerm aa u
generaliseI aa uu
type TopEnv = Map VarId (IVar PolyType)
inferTop :: TopEnv -> [(VarId,Term)] -> Par [(VarId,PolyType)]
inferTop topenv0 binds = do
< 1 >
< 2 >
inferBind :: TopEnv -> (VarId,Term) -> Par TopEnv
inferBind topenv (x,u) = do
< 1 >
< 2 >
< 4 >
< 5 >
< 6 >
< 7 >
|
f16eff309409de5871fb91a319e4ed64fe215081749ab49a1ab6fe777e4da290 | jimpil/duratom | error_handling_test.clj | (ns duratom.error-handling-test
(:require [clojure.test :refer :all]
[clojure.java.io :as io]
[duratom.core :as core]
[duratom.backends :as storage]
[duratom.utils :as ut])
(:import (java.util.concurrent.atomic AtomicLong)
(java.io IOException)
(java.nio.file Files)))
(defn- persist-exceptions-common*
[duratom errors async?]
(with-open [dura duratom]
(with-redefs [storage/save-to-file!
(fn [_ _ _]
(throw (IllegalStateException. "whatever")))]
(swap! dura update :x inc)
(when async?
(Thread/sleep 60))
(swap! dura update :y inc)
(is (= [2 3] ((juxt :x :y) @dura)))
(when async?
(Thread/sleep 60))
(is (= 2 (count @errors)))
(is (every? (partial instance? IllegalStateException) @errors)))))
(deftest persist-errors
(testing "asynchronous error handler"
(let [rel-path "data_temp1.txt"
_ (when (.exists (io/file rel-path))
(io/delete-file rel-path)) ;; proper cleanup before testing
init {:x 1 :y 2}
errors (atom [])]
(persist-exceptions-common*
(core/duratom :local-file
:file-path rel-path
:init init
:rw (assoc core/default-file-rw
:error-handler
(fn [e _]
(println "Error while saving asynchronously to file!")
(swap! errors conj e))))
errors
true)))
(testing "synchronous error handler"
(let [rel-path "data_temp2.txt"
_ (when (.exists (io/file rel-path))
(io/delete-file rel-path)) ;; proper cleanup before testing
init {:x 1 :y 2}
errors (atom [])]
(persist-exceptions-common*
(core/duratom :local-file
:file-path rel-path
:init init
:rw (assoc core/default-file-rw
:commit-mode :sync
:error-handler
(fn [e _]
(println "Error while saving synchronously to file!")
(swap! errors conj e))))
errors
false)))
)
(defn- recommit-common
[duratom async?]
(let [errors (atom 0)]
(with-open [dura duratom]
(with-redefs [ut/move-file!
(let [al (AtomicLong. 0)]
(fn [s t]
;; the guts of `move-file!`
(let [normal-flow #(Files/move (.toPath (io/file s))
(.toPath (io/file t))
ut/move-opts)
i (.incrementAndGet al)]
(case i
1 (do (swap! errors inc)
(throw (IOException. "whatever")))
3 (do (swap! errors inc)
(throw (IOException. "whatever")))
(normal-flow)))))]
(swap! dura update :x inc) ;; fails once, but the error-handler recommits successfully
(when async?
(Thread/sleep 100))
(swap! dura update :y inc) ;; fails once, but the error-handler recommits successfully
(when async?
(Thread/sleep 100))
(is (= [2 3] ((juxt :x :y) @dura))) ;; as if nothing failed
(is (= 2 @errors))))))
(deftest recommit-tests
(testing "asynchronous recommits"
(let [rel-path "data_temp3.txt"
_ (when (.exists (io/file rel-path))
(io/delete-file rel-path)) ;; proper cleanup before testing
init {:x 1 :y 2}]
(recommit-common
(core/duratom :local-file
:file-path rel-path
:init init
:rw (assoc core/default-file-rw
:error-handler
(fn [_ recommit]
(println "Error while saving asynchronously to file! Recommitting...")
(recommit))))
true)))
(testing "synchronous recommits"
(let [rel-path "data_temp4.txt"
_ (when (.exists (io/file rel-path))
(io/delete-file rel-path)) ;; proper cleanup before testing
init {:x 1 :y 2}]
(recommit-common
(core/duratom :local-file
:file-path rel-path
:init init
:rw (assoc core/default-file-rw
:commit-mode :sync
:error-handler
(fn [_ recommit]
(println "Error while saving synchronously to file! Recommitting...")
(recommit))))
false)))
)
| null | https://raw.githubusercontent.com/jimpil/duratom/3633f1c709ed18d75491eef6919899ee3dda8939/test/duratom/error_handling_test.clj | clojure | proper cleanup before testing
proper cleanup before testing
the guts of `move-file!`
fails once, but the error-handler recommits successfully
fails once, but the error-handler recommits successfully
as if nothing failed
proper cleanup before testing
proper cleanup before testing | (ns duratom.error-handling-test
(:require [clojure.test :refer :all]
[clojure.java.io :as io]
[duratom.core :as core]
[duratom.backends :as storage]
[duratom.utils :as ut])
(:import (java.util.concurrent.atomic AtomicLong)
(java.io IOException)
(java.nio.file Files)))
(defn- persist-exceptions-common*
[duratom errors async?]
(with-open [dura duratom]
(with-redefs [storage/save-to-file!
(fn [_ _ _]
(throw (IllegalStateException. "whatever")))]
(swap! dura update :x inc)
(when async?
(Thread/sleep 60))
(swap! dura update :y inc)
(is (= [2 3] ((juxt :x :y) @dura)))
(when async?
(Thread/sleep 60))
(is (= 2 (count @errors)))
(is (every? (partial instance? IllegalStateException) @errors)))))
(deftest persist-errors
(testing "asynchronous error handler"
(let [rel-path "data_temp1.txt"
_ (when (.exists (io/file rel-path))
init {:x 1 :y 2}
errors (atom [])]
(persist-exceptions-common*
(core/duratom :local-file
:file-path rel-path
:init init
:rw (assoc core/default-file-rw
:error-handler
(fn [e _]
(println "Error while saving asynchronously to file!")
(swap! errors conj e))))
errors
true)))
(testing "synchronous error handler"
(let [rel-path "data_temp2.txt"
_ (when (.exists (io/file rel-path))
init {:x 1 :y 2}
errors (atom [])]
(persist-exceptions-common*
(core/duratom :local-file
:file-path rel-path
:init init
:rw (assoc core/default-file-rw
:commit-mode :sync
:error-handler
(fn [e _]
(println "Error while saving synchronously to file!")
(swap! errors conj e))))
errors
false)))
)
(defn- recommit-common
[duratom async?]
(let [errors (atom 0)]
(with-open [dura duratom]
(with-redefs [ut/move-file!
(let [al (AtomicLong. 0)]
(fn [s t]
(let [normal-flow #(Files/move (.toPath (io/file s))
(.toPath (io/file t))
ut/move-opts)
i (.incrementAndGet al)]
(case i
1 (do (swap! errors inc)
(throw (IOException. "whatever")))
3 (do (swap! errors inc)
(throw (IOException. "whatever")))
(normal-flow)))))]
(when async?
(Thread/sleep 100))
(when async?
(Thread/sleep 100))
(is (= 2 @errors))))))
(deftest recommit-tests
(testing "asynchronous recommits"
(let [rel-path "data_temp3.txt"
_ (when (.exists (io/file rel-path))
init {:x 1 :y 2}]
(recommit-common
(core/duratom :local-file
:file-path rel-path
:init init
:rw (assoc core/default-file-rw
:error-handler
(fn [_ recommit]
(println "Error while saving asynchronously to file! Recommitting...")
(recommit))))
true)))
(testing "synchronous recommits"
(let [rel-path "data_temp4.txt"
_ (when (.exists (io/file rel-path))
init {:x 1 :y 2}]
(recommit-common
(core/duratom :local-file
:file-path rel-path
:init init
:rw (assoc core/default-file-rw
:commit-mode :sync
:error-handler
(fn [_ recommit]
(println "Error while saving synchronously to file! Recommitting...")
(recommit))))
false)))
)
|
ced836ba9a129691b9e243f462f43b8c330572999e8dce86dbe8abf7a47904b0 | ejgallego/coq-lsp | jLang.mli | (************************************************************************)
(* Coq Language Server Protocol *)
Copyright 2019 MINES ParisTech -- LGPL 2.1 +
Copyright 2019 - 2023 Inria -- LGPL 2.1 +
Written by :
(************************************************************************)
module Point : sig
type t = Lang.Point.t [@@deriving yojson]
end
module Range : sig
type t = Lang.Range.t [@@deriving yojson]
end
module LUri : sig
module File : sig
type t = Lang.LUri.File.t [@@deriving yojson]
end
end
module Diagnostic : sig
type t = Lang.Diagnostic.t [@@deriving to_yojson]
end
val mk_diagnostics :
uri:Lang.LUri.File.t -> version:int -> Lang.Diagnostic.t list -> Yojson.Safe.t
| null | https://raw.githubusercontent.com/ejgallego/coq-lsp/dbc7b1f3966834f562eda76060c9848679ebf928/lsp/jLang.mli | ocaml | **********************************************************************
Coq Language Server Protocol
********************************************************************** | Copyright 2019 MINES ParisTech -- LGPL 2.1 +
Copyright 2019 - 2023 Inria -- LGPL 2.1 +
Written by :
module Point : sig
type t = Lang.Point.t [@@deriving yojson]
end
module Range : sig
type t = Lang.Range.t [@@deriving yojson]
end
module LUri : sig
module File : sig
type t = Lang.LUri.File.t [@@deriving yojson]
end
end
module Diagnostic : sig
type t = Lang.Diagnostic.t [@@deriving to_yojson]
end
val mk_diagnostics :
uri:Lang.LUri.File.t -> version:int -> Lang.Diagnostic.t list -> Yojson.Safe.t
|
0ab6b6e45fe201e01c0180c13fe07df46bf0a28f831aaed74f59798a7aaf0180 | jeffshrager/biobike | javascript-filecompiler.lisp | ;;
Copyright ( c ) 2005 , Gigamonkeys Consulting All rights reserved .
;;
(in-package :com.gigamonkeys.foo.javascript)
(defmacro define-javascript-module (name &body names)
`(setf (get ',name 'javascript-module) ',names))
(define-javascript-module com.gigamonkeys.foo.javascript.special-ops
array object @ ref new ++ -- ? progn prog block var if
do-while while for continue break return with switch label
throw try function
Unary ops
delete void typeof ~ !
;; Simple binary ops
* / % + - << >> >>> < > <= >= instanceof in
== != === !=== & ^ \| && \|\|)
(define-javascript-module com.gigamonkeys.foo.javascript.built-in-macros
defun defmethod defvar debug lambda let let* if when unless cond case switch
dolist dotimes dokids return array autoref autorefset setf defcallback
destructure html define-builder)
(defvar *mappings*)
(defun add-mappings (mappings name)
(dolist (sym (get name 'javascript-module))
(add-mapping sym mappings)))
(defun add-mapping (symbol mappings)
(let ((name (intern (string-downcase symbol) :com.gigamonkeys.foo.javascript.tokens)))
(let ((existing (gethash name mappings)))
(if existing
(unless (eql existing symbol)
(error "Already a mapping for ~a to ~a" name existing))
(setf (gethash name mappings) symbol)))))
(defparameter *default-initial-mappings* (make-hash-table))
(progn
(add-mappings *default-initial-mappings* 'com.gigamonkeys.foo.javascript.special-ops)
(add-mappings *default-initial-mappings* 'com.gigamonkeys.foo.javascript.built-in-macros))
(defun resolve-names (thing mappings)
(cond
((null thing) nil)
((symbolp thing) (or (gethash thing mappings) thing))
((atom thing) thing)
(t (cons (resolve-names (car thing) mappings) (resolve-names (cdr thing) mappings)))))
(defun js (string)
(process-javascript (get-pretty-printer) (read-js-from-string string) :expression))
(defmacro with-javascript-input (&body body)
`(let ((*readtable* (copy-readtable))
(*package* (find-package :com.gigamonkeys.foo.javascript.tokens))
(*mappings* (make-hash-table)))
(maphash #'(lambda (k v) (setf (gethash k *mappings*) v)) *default-initial-mappings*)
(setf (readtable-case *readtable*) :preserve)
,@body))
(defun read-js-from-string (string)
(with-javascript-input
(resolve-names (read-from-string string) *mappings*)))
(defun emit-javascript (in out)
(with-javascript-input
(with-html-output (out :pretty t)
(loop with processor = (get-pretty-printer)
for form = (read in nil in)
while (not (eql form in)) do
(process-javascript processor (resolve-names form *mappings*) :statement)
(newline processor)))))
(defun compile-javascript (input &key (output (make-pathname :type "js" :defaults input)))
(assert (not (equal (pathname input) (pathname output))))
(let ((*counter* 0))
(with-open-file (in input)
(with-open-file (out output :direction :output :if-exists :supersede)
(format out "// Generated at ~a from ~a.~2%" (format-iso-8601-time (get-universal-time)) (truename in))
(emit-javascript in out))))) | null | https://raw.githubusercontent.com/jeffshrager/biobike/5313ec1fe8e82c21430d645e848ecc0386436f57/BioLisp/ThirdParty/monkeylib/foo/javascript/javascript-filecompiler.lisp | lisp |
Simple binary ops | Copyright ( c ) 2005 , Gigamonkeys Consulting All rights reserved .
(in-package :com.gigamonkeys.foo.javascript)
(defmacro define-javascript-module (name &body names)
`(setf (get ',name 'javascript-module) ',names))
(define-javascript-module com.gigamonkeys.foo.javascript.special-ops
array object @ ref new ++ -- ? progn prog block var if
do-while while for continue break return with switch label
throw try function
Unary ops
delete void typeof ~ !
* / % + - << >> >>> < > <= >= instanceof in
== != === !=== & ^ \| && \|\|)
(define-javascript-module com.gigamonkeys.foo.javascript.built-in-macros
defun defmethod defvar debug lambda let let* if when unless cond case switch
dolist dotimes dokids return array autoref autorefset setf defcallback
destructure html define-builder)
(defvar *mappings*)
(defun add-mappings (mappings name)
(dolist (sym (get name 'javascript-module))
(add-mapping sym mappings)))
(defun add-mapping (symbol mappings)
(let ((name (intern (string-downcase symbol) :com.gigamonkeys.foo.javascript.tokens)))
(let ((existing (gethash name mappings)))
(if existing
(unless (eql existing symbol)
(error "Already a mapping for ~a to ~a" name existing))
(setf (gethash name mappings) symbol)))))
(defparameter *default-initial-mappings* (make-hash-table))
(progn
(add-mappings *default-initial-mappings* 'com.gigamonkeys.foo.javascript.special-ops)
(add-mappings *default-initial-mappings* 'com.gigamonkeys.foo.javascript.built-in-macros))
(defun resolve-names (thing mappings)
(cond
((null thing) nil)
((symbolp thing) (or (gethash thing mappings) thing))
((atom thing) thing)
(t (cons (resolve-names (car thing) mappings) (resolve-names (cdr thing) mappings)))))
(defun js (string)
(process-javascript (get-pretty-printer) (read-js-from-string string) :expression))
(defmacro with-javascript-input (&body body)
`(let ((*readtable* (copy-readtable))
(*package* (find-package :com.gigamonkeys.foo.javascript.tokens))
(*mappings* (make-hash-table)))
(maphash #'(lambda (k v) (setf (gethash k *mappings*) v)) *default-initial-mappings*)
(setf (readtable-case *readtable*) :preserve)
,@body))
(defun read-js-from-string (string)
(with-javascript-input
(resolve-names (read-from-string string) *mappings*)))
(defun emit-javascript (in out)
(with-javascript-input
(with-html-output (out :pretty t)
(loop with processor = (get-pretty-printer)
for form = (read in nil in)
while (not (eql form in)) do
(process-javascript processor (resolve-names form *mappings*) :statement)
(newline processor)))))
(defun compile-javascript (input &key (output (make-pathname :type "js" :defaults input)))
(assert (not (equal (pathname input) (pathname output))))
(let ((*counter* 0))
(with-open-file (in input)
(with-open-file (out output :direction :output :if-exists :supersede)
(format out "// Generated at ~a from ~a.~2%" (format-iso-8601-time (get-universal-time)) (truename in))
(emit-javascript in out))))) |
5738095fe7250063cf65bf8cffb3da36e3d5c6ae714608fc7862c93bc55fc5a7 | SonarQubeCommunity/sonar-erlang | branchesofrecursion.erl | -module(a).
quicksort([H|T]) ->
{Smaller_Ones,Larger_Ones} = a:split(H,T,{[],[]}),
lists:append( quicksort(Smaller_Ones),
[H | quicksort(Larger_Ones)]
);
quicksort([]) -> [].
split(Pivot, [H|T], {Acc_S, Acc_L}) ->
if Pivot > H -> New_Acc = { [H|Acc_S] , Acc_L };
true -> New_Acc = { Acc_S , [H|Acc_L] }
end,
split(Pivot,T,New_Acc);
split(_,[],Acc) -> Acc.
acc_multipart(V) ->
acc_multipart((parser(<<"boundary">>))(V), []).
acc_multipart({headers, Headers, Cont}, Acc) ->
acc_multipart(Cont(), [{Headers, []}|Acc]);
acc_multipart({body, Body, Cont}, [{Headers, BodyAcc}|Acc]) ->
acc_multipart(Cont(), [{Headers, [Body|BodyAcc]}|Acc]);
acc_multipart({end_of_part, Cont}, [{Headers, BodyAcc}|Acc]) ->
Body = list_to_binary(lists:reverse(BodyAcc)),
acc_multipart(Cont(), [{Headers, Body}|Acc]);
acc_multipart(eof, Acc) ->
lists:reverse(Acc).
| null | https://raw.githubusercontent.com/SonarQubeCommunity/sonar-erlang/279eb7ccd84787c1c0cfd34b9a07981eb20183e3/erlang-checks/src/test/resources/checks/branchesofrecursion.erl | erlang | -module(a).
quicksort([H|T]) ->
{Smaller_Ones,Larger_Ones} = a:split(H,T,{[],[]}),
lists:append( quicksort(Smaller_Ones),
[H | quicksort(Larger_Ones)]
);
quicksort([]) -> [].
split(Pivot, [H|T], {Acc_S, Acc_L}) ->
if Pivot > H -> New_Acc = { [H|Acc_S] , Acc_L };
true -> New_Acc = { Acc_S , [H|Acc_L] }
end,
split(Pivot,T,New_Acc);
split(_,[],Acc) -> Acc.
acc_multipart(V) ->
acc_multipart((parser(<<"boundary">>))(V), []).
acc_multipart({headers, Headers, Cont}, Acc) ->
acc_multipart(Cont(), [{Headers, []}|Acc]);
acc_multipart({body, Body, Cont}, [{Headers, BodyAcc}|Acc]) ->
acc_multipart(Cont(), [{Headers, [Body|BodyAcc]}|Acc]);
acc_multipart({end_of_part, Cont}, [{Headers, BodyAcc}|Acc]) ->
Body = list_to_binary(lists:reverse(BodyAcc)),
acc_multipart(Cont(), [{Headers, Body}|Acc]);
acc_multipart(eof, Acc) ->
lists:reverse(Acc).
| |
ac3d610d924b57c4ff82743ccb2c63b2db535e212a48ce68b5ccdbcfb94df182 | tomjkidd/web-whiteboard | core.cljs | (ns web-whiteboard.client.core
"Code to support creating the web-whiteboard client app"
(:require [web-whiteboard.client.state :as state]
[web-whiteboard.client.ui :as ui]
[web-whiteboard.client.handlers.websocket :as hws]))
(defn ^:export run
"The main function to run the client app"
[]
(let [app-state (state/create-app-state state/ws-url)]
(hws/listen-to-websocket-to-chan app-state)
(ui/create-ui app-state)))
| null | https://raw.githubusercontent.com/tomjkidd/web-whiteboard/6bc508703b14c136be0def8bb6839f2784a3ae9b/src/web_whiteboard/client/core.cljs | clojure | (ns web-whiteboard.client.core
"Code to support creating the web-whiteboard client app"
(:require [web-whiteboard.client.state :as state]
[web-whiteboard.client.ui :as ui]
[web-whiteboard.client.handlers.websocket :as hws]))
(defn ^:export run
"The main function to run the client app"
[]
(let [app-state (state/create-app-state state/ws-url)]
(hws/listen-to-websocket-to-chan app-state)
(ui/create-ui app-state)))
| |
404cf62ebdf6e46cd6b9a7dfa2dd2c23568ce51dcc61bccdaa0d923defa74abf | airalab/hs-web3 | Config.hs | {-# LANGUAGE OverloadedStrings #-}
-- |
Module : Network . . Api . Config
Copyright : 2016 - 2021
-- License : Apache-2.0
--
-- Maintainer :
-- Stability : experimental
-- Portability : unknown
--
-- Api calls with `config` prefix.
--
module Network.Ipfs.Api.Config where
import Control.Monad.IO.Class (MonadIO)
import Data.Text (Text)
import Network.HTTP.Client (responseStatus)
import Network.HTTP.Types (Status (..))
import Network.Ipfs.Api.Internal (_configGet, _configSet)
import Network.Ipfs.Api.Internal.Call (call, multipartCall)
import Network.Ipfs.Api.Types (ConfigObj)
import Network.Ipfs.Client (IpfsT)
-- | Get ipfs config values.
get :: MonadIO m => Text -> IpfsT m ConfigObj
get = call . _configGet
-- | Set ipfs config values.
set :: MonadIO m => Text -> Maybe Text -> IpfsT m ConfigObj
set key = call . _configSet key
-- | Replace the config with the file at <filePath>.
replace :: MonadIO m => Text -> IpfsT m Bool
replace = fmap isSuccess . multipartCall "config/replace"
where
isSuccess = (== 200) . statusCode . responseStatus
| null | https://raw.githubusercontent.com/airalab/hs-web3/c03b86eb621f963886a78c39ee18bcec753f17ac/packages/ipfs/src/Network/Ipfs/Api/Config.hs | haskell | # LANGUAGE OverloadedStrings #
|
License : Apache-2.0
Maintainer :
Stability : experimental
Portability : unknown
Api calls with `config` prefix.
| Get ipfs config values.
| Set ipfs config values.
| Replace the config with the file at <filePath>. |
Module : Network . . Api . Config
Copyright : 2016 - 2021
module Network.Ipfs.Api.Config where
import Control.Monad.IO.Class (MonadIO)
import Data.Text (Text)
import Network.HTTP.Client (responseStatus)
import Network.HTTP.Types (Status (..))
import Network.Ipfs.Api.Internal (_configGet, _configSet)
import Network.Ipfs.Api.Internal.Call (call, multipartCall)
import Network.Ipfs.Api.Types (ConfigObj)
import Network.Ipfs.Client (IpfsT)
get :: MonadIO m => Text -> IpfsT m ConfigObj
get = call . _configGet
set :: MonadIO m => Text -> Maybe Text -> IpfsT m ConfigObj
set key = call . _configSet key
replace :: MonadIO m => Text -> IpfsT m Bool
replace = fmap isSuccess . multipartCall "config/replace"
where
isSuccess = (== 200) . statusCode . responseStatus
|
90eb42c267750ae0d3cfd42454f1fae1d69e57f78411270ff4248e568a498d4c | mwand/eopl3 | tests.scm | (module tests mzscheme
(provide test-list)
;;;;;;;;;;;;;;;; tests ;;;;;;;;;;;;;;;;
(define test-list
'(
;; simple arithmetic
(positive-const "11" 11)
(negative-const "-33" -33)
(simple-arith-1 "-(44,33)" 11)
;; nested arithmetic
(nested-arith-left "-(-(44,33),22)" -11)
(nested-arith-right "-(55, -(22,11))" 44)
;; simple variables
(test-var-1 "x" 10)
(test-var-2 "-(x,1)" 9)
(test-var-3 "-(1,x)" -9)
;; simple unbound variables
(test-unbound-var-1 "foo" error)
(test-unbound-var-2 "-(x,foo)" error)
;; simple conditionals
(if-true "if zero?(0) then 3 else 4" 3)
(if-false "if zero?(1) then 3 else 4" 4)
;; test dynamic typechecking
(no-bool-to-diff-1 "-(zero?(0),1)" error)
(no-bool-to-diff-2 "-(1,zero?(0))" error)
(no-int-to-if "if 1 then 2 else 3" error)
;; make sure that the test and both arms get evaluated
;; properly.
(if-eval-test-true "if zero?(-(11,11)) then 3 else 4" 3)
(if-eval-test-false "if zero?(-(11, 12)) then 3 else 4" 4)
;; and make sure the other arm doesn't get evaluated.
(if-eval-test-true-2 "if zero?(-(11, 11)) then 3 else foo" 3)
(if-eval-test-false-2 "if zero?(-(11,12)) then foo else 4" 4)
;; simple let
(simple-let-1 "let x = 3 in x" 3)
make sure the body and rhs get evaluated
(eval-let-body "let x = 3 in -(x,1)" 2)
(eval-let-rhs "let x = -(4,1) in -(x,1)" 2)
;; check nested let and shadowing
(simple-nested-let "let x = 3 in let y = 4 in -(x,y)" -1)
(check-shadowing-in-body "let x = 3 in let x = 4 in x" 4)
(check-shadowing-in-rhs "let x = 3 in let x = -(x,1) in x" 2)
;; simple applications
(apply-proc-in-rator-pos "(proc(x) -(x,1) 30)" 29)
(apply-simple-proc "let f = proc (x) -(x,1) in (f 30)" 29)
(let-to-proc-1 "(proc(f)(f 30) proc(x)-(x,1))" 29)
(nested-procs "((proc (x) proc (y) -(x,y) 5) 6)" -1)
(nested-procs2 "let f = proc(x) proc (y) -(x,y) in ((f -(10,5)) 6)"
-1)
(y-combinator-1 "
let fix = proc (f)
let d = proc (x) proc (z) ((f (x x)) z)
in proc (n) ((f (d d)) n)
in let
t4m = proc (f) proc(x) if zero?(x) then 0 else -((f -(x,1)),-4)
in let times4 = (fix t4m)
in (times4 3)" 12)
;; simple letrecs
(simple-letrec-1 "letrec f(x) = -(x,1) in (f 33)" 32)
(simple-letrec-2
"letrec f(x) = if zero?(x) then 0 else -((f -(x,1)), -2) in (f 4)"
8)
(simple-letrec-3
"let m = -5
in letrec f(x) = if zero?(x) then 0 else -((f -(x,1)), m) in (f 4)"
20)
; (fact-of-6 "letrec
fact(x ) = if ) then 1 else * ( x , ( fact ) ) )
in ( fact 6 ) "
720 )
(HO-nested-letrecs
"letrec even(odd) = proc(x) if zero?(x) then 1 else (odd -(x,1))
in letrec odd(x) = if zero?(x) then 0 else ((even odd) -(x,1))
in (odd 13)" 1)
(begin-test-1
"begin 1; 2; 3 end"
3)
(gensym-test-1
"let g = let counter = newref(0)
in proc (dummy) let d = setref(counter, -(deref(counter),-1))
in deref(counter)
in -((g 11),(g 22))"
-1)
(simple-store-test-1 "let x = newref(17) in deref(x)" 17)
(assignment-test-1 "let x = newref(17)
in begin setref(x,27); deref(x) end"
27)
(gensym-test-2
"let g = let counter = newref(0)
in proc (dummy) begin
setref(counter, -(deref(counter),-1));
deref(counter)
end
in -((g 11),(g 22))"
-1)
(even-odd-via-set-1 "
let x = newref(0)
in letrec even(d) = if zero?(deref(x))
then 1
else let d = setref(x, -(deref(x),1))
in (odd d)
odd(d) = if zero?(deref(x))
then 0
else let d = setref(x, -(deref(x),1))
in (even d)
in let d = setref(x,13) in (odd -100)" 1)
(even-odd-via-set-1 "
let x = newref(0)
in letrec even(d) = if zero?(deref(x))
then 1
else let d = setref(x, -(deref(x),1))
in (odd d)
odd(d) = if zero?(deref(x))
then 0
else let d = setref(x, -(deref(x),1))
in (even d)
in let d = setref(x,13) in (odd -100)" 1)
(show-allocation-1 "
let x = newref(22)
in let f = proc (z) let zz = newref(-(z,deref(x))) in deref(zz)
in -((f 66), (f 55))"
11)
(chains-1 "
let x = newref(newref(0))
in begin
setref(deref(x), 11);
deref(deref(x))
end"
11)
))
) | null | https://raw.githubusercontent.com/mwand/eopl3/b50e015be7f021d94c1af5f0e3a05d40dd2b0cbf/chapter4/explicit-refs/tests.scm | scheme | tests ;;;;;;;;;;;;;;;;
simple arithmetic
nested arithmetic
simple variables
simple unbound variables
simple conditionals
test dynamic typechecking
make sure that the test and both arms get evaluated
properly.
and make sure the other arm doesn't get evaluated.
simple let
check nested let and shadowing
simple applications
simple letrecs
(fact-of-6 "letrec
deref(x) end"
| (module tests mzscheme
(provide test-list)
(define test-list
'(
(positive-const "11" 11)
(negative-const "-33" -33)
(simple-arith-1 "-(44,33)" 11)
(nested-arith-left "-(-(44,33),22)" -11)
(nested-arith-right "-(55, -(22,11))" 44)
(test-var-1 "x" 10)
(test-var-2 "-(x,1)" 9)
(test-var-3 "-(1,x)" -9)
(test-unbound-var-1 "foo" error)
(test-unbound-var-2 "-(x,foo)" error)
(if-true "if zero?(0) then 3 else 4" 3)
(if-false "if zero?(1) then 3 else 4" 4)
(no-bool-to-diff-1 "-(zero?(0),1)" error)
(no-bool-to-diff-2 "-(1,zero?(0))" error)
(no-int-to-if "if 1 then 2 else 3" error)
(if-eval-test-true "if zero?(-(11,11)) then 3 else 4" 3)
(if-eval-test-false "if zero?(-(11, 12)) then 3 else 4" 4)
(if-eval-test-true-2 "if zero?(-(11, 11)) then 3 else foo" 3)
(if-eval-test-false-2 "if zero?(-(11,12)) then foo else 4" 4)
(simple-let-1 "let x = 3 in x" 3)
make sure the body and rhs get evaluated
(eval-let-body "let x = 3 in -(x,1)" 2)
(eval-let-rhs "let x = -(4,1) in -(x,1)" 2)
(simple-nested-let "let x = 3 in let y = 4 in -(x,y)" -1)
(check-shadowing-in-body "let x = 3 in let x = 4 in x" 4)
(check-shadowing-in-rhs "let x = 3 in let x = -(x,1) in x" 2)
(apply-proc-in-rator-pos "(proc(x) -(x,1) 30)" 29)
(apply-simple-proc "let f = proc (x) -(x,1) in (f 30)" 29)
(let-to-proc-1 "(proc(f)(f 30) proc(x)-(x,1))" 29)
(nested-procs "((proc (x) proc (y) -(x,y) 5) 6)" -1)
(nested-procs2 "let f = proc(x) proc (y) -(x,y) in ((f -(10,5)) 6)"
-1)
(y-combinator-1 "
let fix = proc (f)
let d = proc (x) proc (z) ((f (x x)) z)
in proc (n) ((f (d d)) n)
in let
t4m = proc (f) proc(x) if zero?(x) then 0 else -((f -(x,1)),-4)
in let times4 = (fix t4m)
in (times4 3)" 12)
(simple-letrec-1 "letrec f(x) = -(x,1) in (f 33)" 32)
(simple-letrec-2
"letrec f(x) = if zero?(x) then 0 else -((f -(x,1)), -2) in (f 4)"
8)
(simple-letrec-3
"let m = -5
in letrec f(x) = if zero?(x) then 0 else -((f -(x,1)), m) in (f 4)"
20)
fact(x ) = if ) then 1 else * ( x , ( fact ) ) )
in ( fact 6 ) "
720 )
(HO-nested-letrecs
"letrec even(odd) = proc(x) if zero?(x) then 1 else (odd -(x,1))
in letrec odd(x) = if zero?(x) then 0 else ((even odd) -(x,1))
in (odd 13)" 1)
(begin-test-1
"begin 1; 2; 3 end"
3)
(gensym-test-1
"let g = let counter = newref(0)
in proc (dummy) let d = setref(counter, -(deref(counter),-1))
in deref(counter)
in -((g 11),(g 22))"
-1)
(simple-store-test-1 "let x = newref(17) in deref(x)" 17)
(assignment-test-1 "let x = newref(17)
27)
(gensym-test-2
"let g = let counter = newref(0)
in proc (dummy) begin
deref(counter)
end
in -((g 11),(g 22))"
-1)
(even-odd-via-set-1 "
let x = newref(0)
in letrec even(d) = if zero?(deref(x))
then 1
else let d = setref(x, -(deref(x),1))
in (odd d)
odd(d) = if zero?(deref(x))
then 0
else let d = setref(x, -(deref(x),1))
in (even d)
in let d = setref(x,13) in (odd -100)" 1)
(even-odd-via-set-1 "
let x = newref(0)
in letrec even(d) = if zero?(deref(x))
then 1
else let d = setref(x, -(deref(x),1))
in (odd d)
odd(d) = if zero?(deref(x))
then 0
else let d = setref(x, -(deref(x),1))
in (even d)
in let d = setref(x,13) in (odd -100)" 1)
(show-allocation-1 "
let x = newref(22)
in let f = proc (z) let zz = newref(-(z,deref(x))) in deref(zz)
in -((f 66), (f 55))"
11)
(chains-1 "
let x = newref(newref(0))
in begin
deref(deref(x))
end"
11)
))
) |
cf6775f9a496219165ce2c03fe7beff93bbed3a7a52555f0fe84d826eb29e375 | dalaing/little-languages | SmallStep.hs | |
Copyright : ( c ) , 2016
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) Dave Laing, 2016
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Component.Term.Int.Eval.SmallStep (
smallStepInput
) where
import Control.Lens (preview, review)
import Component.Term.Eval.SmallStep (SmallStepRule(..), SmallStepInput(..))
import Component.Term.Int (AsIntTerm(..), WithIntTerm)
-- |
eAddIntInt :: WithIntTerm tm
=> tm nTy nTm a -- ^
-> Maybe (tm nTy nTm a) -- ^
eAddIntInt tm = do
(tm1, tm2) <- preview _TmAdd tm
i1 <- preview _TmIntLit tm1
i2 <- preview _TmIntLit tm2
return $ review _TmIntLit (i1 + i2)
-- |
eAdd1 :: WithIntTerm tm
=> (tm nTy nTm a -> Maybe (tm nTy nTm a))
-> tm nTy nTm a -- ^
-> Maybe (tm nTy nTm a) -- ^
eAdd1 step tm = do
(tm1, tm2) <- preview _TmAdd tm
tm1' <- step tm1
return $ review _TmAdd (tm1', tm2)
-- |
eAdd2 :: WithIntTerm tm
=> (tm nTy nTm a -> Maybe (tm nTy nTm a)) -- ^
-> (tm nTy nTm a -> Maybe (tm nTy nTm a)) -- ^
-> tm nTy nTm a -- ^
-> Maybe (tm nTy nTm a) -- ^
eAdd2 value step tm = do
(tm1, tm2) <- preview _TmAdd tm
_ <- value tm1
tm2' <- step tm2
return $ review _TmAdd (tm1, tm2')
-- |
eSubIntInt :: WithIntTerm tm
=> tm nTy nTm a -- ^
-> Maybe (tm nTy nTm a) -- ^
eSubIntInt tm = do
(tm1, tm2) <- preview _TmSub tm
i1 <- preview _TmIntLit tm1
i2 <- preview _TmIntLit tm2
return $ review _TmIntLit (i1 - i2)
-- |
eSub1 :: WithIntTerm tm
=> (tm nTy nTm a -> Maybe (tm nTy nTm a))
-> tm nTy nTm a -- ^
-> Maybe (tm nTy nTm a) -- ^
eSub1 step tm = do
(tm1, tm2) <- preview _TmSub tm
tm1' <- step tm1
return $ review _TmSub (tm1', tm2)
-- |
eSub2 :: WithIntTerm tm
=> (tm nTy nTm a -> Maybe (tm nTy nTm a)) -- ^
-> (tm nTy nTm a -> Maybe (tm nTy nTm a)) -- ^
-> tm nTy nTm a -- ^
-> Maybe (tm nTy nTm a) -- ^
eSub2 value step tm = do
(tm1, tm2) <- preview _TmSub tm
_ <- value tm1
tm2' <- step tm2
return $ review _TmSub (tm1, tm2')
-- |
eMulIntInt :: WithIntTerm tm
=> tm nTy nTm a -- ^
-> Maybe (tm nTy nTm a) -- ^
eMulIntInt tm = do
(tm1, tm2) <- preview _TmMul tm
i1 <- preview _TmIntLit tm1
i2 <- preview _TmIntLit tm2
return $ review _TmIntLit (i1 * i2)
-- |
eMul1 :: WithIntTerm tm
=> (tm nTy nTm a -> Maybe (tm nTy nTm a))
-> tm nTy nTm a -- ^
-> Maybe (tm nTy nTm a) -- ^
eMul1 step tm = do
(tm1, tm2) <- preview _TmMul tm
tm1' <- step tm1
return $ review _TmMul (tm1', tm2)
-- |
eMul2 :: WithIntTerm tm
=> (tm nTy nTm a -> Maybe (tm nTy nTm a)) -- ^
-> (tm nTy nTm a -> Maybe (tm nTy nTm a)) -- ^
-> tm nTy nTm a -- ^
-> Maybe (tm nTy nTm a) -- ^
eMul2 value step tm = do
(tm1, tm2) <- preview _TmMul tm
_ <- value tm1
tm2' <- step tm2
return $ review _TmMul (tm1, tm2')
-- |
eExpIntInt :: WithIntTerm tm
=> tm nTy nTm a -- ^
-> Maybe (tm nTy nTm a) -- ^
eExpIntInt tm = do
(tm1, tm2) <- preview _TmExp tm
i1 <- preview _TmIntLit tm1
i2 <- preview _TmIntLit tm2
return . review _TmIntLit $
if i2 < 0
then 0
else i1 ^ i2
-- |
eExp1 :: WithIntTerm tm
=> (tm nTy nTm a -> Maybe (tm nTy nTm a))
-> tm nTy nTm a -- ^
-> Maybe (tm nTy nTm a) -- ^
eExp1 step tm = do
(tm1, tm2) <- preview _TmExp tm
tm1' <- step tm1
return $ review _TmExp (tm1', tm2)
-- |
eExp2 :: WithIntTerm tm
=> (tm nTy nTm a -> Maybe (tm nTy nTm a)) -- ^
-> (tm nTy nTm a -> Maybe (tm nTy nTm a)) -- ^
-> tm nTy nTm a -- ^
-> Maybe (tm nTy nTm a) -- ^
eExp2 value step tm = do
(tm1, tm2) <- preview _TmExp tm
_ <- value tm1
tm2' <- step tm2
return $ review _TmExp (tm1, tm2')
-- |
smallStepInput :: WithIntTerm tm
=> SmallStepInput tm
smallStepInput =
SmallStepInput
[ SmallStepBase eAddIntInt
, SmallStepRecurse eAdd1
, SmallStepValueRecurse eAdd2
, SmallStepBase eSubIntInt
, SmallStepRecurse eSub1
, SmallStepValueRecurse eSub2
, SmallStepBase eMulIntInt
, SmallStepRecurse eMul1
, SmallStepValueRecurse eMul2
, SmallStepBase eExpIntInt
, SmallStepRecurse eExp1
, SmallStepValueRecurse eExp2
]
| null | https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/old/modular/i-lang/src/Component/Term/Int/Eval/SmallStep.hs | haskell | |
^
^
|
^
^
|
^
^
^
^
|
^
^
|
^
^
|
^
^
^
^
|
^
^
|
^
^
|
^
^
^
^
|
^
^
|
^
^
|
^
^
^
^
| | |
Copyright : ( c ) , 2016
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) Dave Laing, 2016
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Component.Term.Int.Eval.SmallStep (
smallStepInput
) where
import Control.Lens (preview, review)
import Component.Term.Eval.SmallStep (SmallStepRule(..), SmallStepInput(..))
import Component.Term.Int (AsIntTerm(..), WithIntTerm)
eAddIntInt :: WithIntTerm tm
eAddIntInt tm = do
(tm1, tm2) <- preview _TmAdd tm
i1 <- preview _TmIntLit tm1
i2 <- preview _TmIntLit tm2
return $ review _TmIntLit (i1 + i2)
eAdd1 :: WithIntTerm tm
=> (tm nTy nTm a -> Maybe (tm nTy nTm a))
eAdd1 step tm = do
(tm1, tm2) <- preview _TmAdd tm
tm1' <- step tm1
return $ review _TmAdd (tm1', tm2)
eAdd2 :: WithIntTerm tm
eAdd2 value step tm = do
(tm1, tm2) <- preview _TmAdd tm
_ <- value tm1
tm2' <- step tm2
return $ review _TmAdd (tm1, tm2')
eSubIntInt :: WithIntTerm tm
eSubIntInt tm = do
(tm1, tm2) <- preview _TmSub tm
i1 <- preview _TmIntLit tm1
i2 <- preview _TmIntLit tm2
return $ review _TmIntLit (i1 - i2)
eSub1 :: WithIntTerm tm
=> (tm nTy nTm a -> Maybe (tm nTy nTm a))
eSub1 step tm = do
(tm1, tm2) <- preview _TmSub tm
tm1' <- step tm1
return $ review _TmSub (tm1', tm2)
eSub2 :: WithIntTerm tm
eSub2 value step tm = do
(tm1, tm2) <- preview _TmSub tm
_ <- value tm1
tm2' <- step tm2
return $ review _TmSub (tm1, tm2')
eMulIntInt :: WithIntTerm tm
eMulIntInt tm = do
(tm1, tm2) <- preview _TmMul tm
i1 <- preview _TmIntLit tm1
i2 <- preview _TmIntLit tm2
return $ review _TmIntLit (i1 * i2)
eMul1 :: WithIntTerm tm
=> (tm nTy nTm a -> Maybe (tm nTy nTm a))
eMul1 step tm = do
(tm1, tm2) <- preview _TmMul tm
tm1' <- step tm1
return $ review _TmMul (tm1', tm2)
eMul2 :: WithIntTerm tm
eMul2 value step tm = do
(tm1, tm2) <- preview _TmMul tm
_ <- value tm1
tm2' <- step tm2
return $ review _TmMul (tm1, tm2')
eExpIntInt :: WithIntTerm tm
eExpIntInt tm = do
(tm1, tm2) <- preview _TmExp tm
i1 <- preview _TmIntLit tm1
i2 <- preview _TmIntLit tm2
return . review _TmIntLit $
if i2 < 0
then 0
else i1 ^ i2
eExp1 :: WithIntTerm tm
=> (tm nTy nTm a -> Maybe (tm nTy nTm a))
eExp1 step tm = do
(tm1, tm2) <- preview _TmExp tm
tm1' <- step tm1
return $ review _TmExp (tm1', tm2)
eExp2 :: WithIntTerm tm
eExp2 value step tm = do
(tm1, tm2) <- preview _TmExp tm
_ <- value tm1
tm2' <- step tm2
return $ review _TmExp (tm1, tm2')
smallStepInput :: WithIntTerm tm
=> SmallStepInput tm
smallStepInput =
SmallStepInput
[ SmallStepBase eAddIntInt
, SmallStepRecurse eAdd1
, SmallStepValueRecurse eAdd2
, SmallStepBase eSubIntInt
, SmallStepRecurse eSub1
, SmallStepValueRecurse eSub2
, SmallStepBase eMulIntInt
, SmallStepRecurse eMul1
, SmallStepValueRecurse eMul2
, SmallStepBase eExpIntInt
, SmallStepRecurse eExp1
, SmallStepValueRecurse eExp2
]
|
f6d5c52e83607d3af3f4447462f021a8a20c69fdcc27ba6deb278d7a180d6514 | fossas/fossa-cli | Container.hs | module App.Fossa.Container (
containerSubCommand,
) where
import App.Docs (fossaContainerScannerUrl)
import App.Fossa.Config.Container (
ContainerAnalyzeConfig (usesExperimentalScanner),
ContainerCommand,
ContainerScanConfig (..),
)
import App.Fossa.Config.Container qualified as Config
import App.Fossa.Container.AnalyzeNative qualified as AnalyzeNative
import App.Fossa.Container.ListTargets (listTargets)
import App.Fossa.Container.Test qualified as Test
import App.Fossa.Subcommand (SubCommand)
import App.Support (supportUrl)
import Control.Effect.Diagnostics (
Diagnostics,
Has,
)
import Control.Effect.Lift (Lift)
import Control.Effect.Telemetry (Telemetry)
import Effect.Exec (Exec)
import Effect.Logger (
Logger,
Pretty (pretty),
indent,
logWarn,
vsep,
)
import Effect.ReadFS (ReadFS)
containerSubCommand :: SubCommand ContainerCommand ContainerScanConfig
containerSubCommand = Config.mkSubCommand dispatch
dispatch ::
( Has Diagnostics sig m
, Has Exec sig m
, Has (Lift IO) sig m
, Has Logger sig m
, Has ReadFS sig m
, Has Telemetry sig m
) =>
ContainerScanConfig ->
m ()
dispatch = \case
AnalyzeCfg cfg -> do
if (usesExperimentalScanner cfg)
then
logWarn $
vsep
[ "DEPRECATION NOTICE"
, ""
, "The 'experimental' container scanner is now the only available scanner, and is enabled automatically."
, ""
, "The --experimental-scanner flag is now deprecated, and has no effect."
, "In the future, using this flag will cause a fatal error."
, "To avoid these errors, remove the flag from your fossa commands."
, ""
]
else
logWarn $
vsep
[ "NOTICE"
, ""
, "FOSSA CLI is using new native container scanner, which scans for application"
, "dependencies in the container image by default. To only scan for system"
, "dependencies, provide `--only-system-deps` flag."
, ""
, "To learn more,"
, indent 4 $ pretty fossaContainerScannerUrl
, ""
, "In future release of FOSSA CLI, this notice will not be displayed."
, ""
, "If you are running into a performance issue or poor results on image analysis"
, "with new scanner, please contact FOSSA support at:"
, indent 4 $ pretty supportUrl
]
AnalyzeNative.analyzeExperimental cfg
TestCfg cfg -> Test.test cfg
ListTargetsCfg cfg -> listTargets cfg
| null | https://raw.githubusercontent.com/fossas/fossa-cli/62c25adda99bab2c80ef78ee78206a14ad0ab0fa/src/App/Fossa/Container.hs | haskell | module App.Fossa.Container (
containerSubCommand,
) where
import App.Docs (fossaContainerScannerUrl)
import App.Fossa.Config.Container (
ContainerAnalyzeConfig (usesExperimentalScanner),
ContainerCommand,
ContainerScanConfig (..),
)
import App.Fossa.Config.Container qualified as Config
import App.Fossa.Container.AnalyzeNative qualified as AnalyzeNative
import App.Fossa.Container.ListTargets (listTargets)
import App.Fossa.Container.Test qualified as Test
import App.Fossa.Subcommand (SubCommand)
import App.Support (supportUrl)
import Control.Effect.Diagnostics (
Diagnostics,
Has,
)
import Control.Effect.Lift (Lift)
import Control.Effect.Telemetry (Telemetry)
import Effect.Exec (Exec)
import Effect.Logger (
Logger,
Pretty (pretty),
indent,
logWarn,
vsep,
)
import Effect.ReadFS (ReadFS)
containerSubCommand :: SubCommand ContainerCommand ContainerScanConfig
containerSubCommand = Config.mkSubCommand dispatch
dispatch ::
( Has Diagnostics sig m
, Has Exec sig m
, Has (Lift IO) sig m
, Has Logger sig m
, Has ReadFS sig m
, Has Telemetry sig m
) =>
ContainerScanConfig ->
m ()
dispatch = \case
AnalyzeCfg cfg -> do
if (usesExperimentalScanner cfg)
then
logWarn $
vsep
[ "DEPRECATION NOTICE"
, ""
, "The 'experimental' container scanner is now the only available scanner, and is enabled automatically."
, ""
, "The --experimental-scanner flag is now deprecated, and has no effect."
, "In the future, using this flag will cause a fatal error."
, "To avoid these errors, remove the flag from your fossa commands."
, ""
]
else
logWarn $
vsep
[ "NOTICE"
, ""
, "FOSSA CLI is using new native container scanner, which scans for application"
, "dependencies in the container image by default. To only scan for system"
, "dependencies, provide `--only-system-deps` flag."
, ""
, "To learn more,"
, indent 4 $ pretty fossaContainerScannerUrl
, ""
, "In future release of FOSSA CLI, this notice will not be displayed."
, ""
, "If you are running into a performance issue or poor results on image analysis"
, "with new scanner, please contact FOSSA support at:"
, indent 4 $ pretty supportUrl
]
AnalyzeNative.analyzeExperimental cfg
TestCfg cfg -> Test.test cfg
ListTargetsCfg cfg -> listTargets cfg
| |
eb691c9e87c9344e8ea14ed354119b71d04208dd00e13ff0b696177b0d40e0d0 | karlhof26/gimp-scheme | bates-layers-delete.scm | ;
; The GIMP -- an image manipulation program
Copyright ( C ) 1995 and
;
Mass delete layers script for GIMP 2.4
Created by
;
; Tags: public domain, layers, delete
;
; Author statement:
;
; Script designed to mass delete layers from current image
; User uses numbers to denote start and end point of deletion
;
; --------------------------------------------------------------------
Distributed by Gimp FX Foundry project
; --------------------------------------------------------------------
; - Changelog -
;
; --------------------------------------------------------------------
;
; This script is released into the public domain.
; You may redistribute and/or modify this script or extract segments without prior consent.
; This script is distributed in the hope of being useful
; but without warranty, explicit or otherwise.
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Define Script
(define (script-fu-delete-layers theImage theDraw theLayer1 theLayer2)
; Define Variables
(let* (
(theNumber 0)
(theRepeat 0)
(theLayerRef 0)
)
; If the end layer is set below the start layer create an error message and terminate
(if (> theLayer1 theLayer2)
(begin
(set! theLayerRef (car (gimp-message-get-handler)))
(gimp-message-set-handler 0)
(gimp-message "Error: End layer number must be set higher than start layer number!")
(gimp-message-set-handler theLayerRef)
)
(begin
; Begin an undo group
(gimp-undo-push-group-start theImage)
; Get the number of layers in an image and set to a variable
(set! theNumber (car (gimp-image-get-layers theImage)))
; If layer2 is set above total layers change layer2 value to the total number of layers
(if (> theLayer2 theNumber)
(set! theLayer2 theNumber)
)
; Set the repeat variable by subtracting the user input values from the total number of layers
(set! theRepeat (+ (- theLayer2 theLayer1) 1))
Begin loop and continue while repeat is higher than zero
(while (> theRepeat 0)
; Set up variable for setting active layers and attributes
(set! theLayerRef (cadr (gimp-image-get-layers theImage)))
Alter theNumber for use in setting active layers and attributes
(set! theNumber (car (gimp-image-get-layers theImage)))
(set! theNumber (- theNumber (- theLayer1 1)))
; Set the layer to be editted as the active layer
( set ! ( gimp - image - set - active - layer theImage ( aref theLayerRef ( - theNumber 1 ) ) ) )
; Delete the specified layer
(gimp-image-remove-layer theImage (aref theLayerRef (- theNumber 1)))
Alter repeat variable ready for checking for next layer , if applicable
(set! theRepeat (- theRepeat 1))
)
; Update visual display
(gimp-displays-flush)
; End undo group
(gimp-undo-push-group-end theImage)
)
)
)
)
Register script
(script-fu-register "script-fu-delete-layers"
"<Toolbox>/Script-Fu/Photo/Multi-Layer Tools/Delete Layers..."
"Deletes layers within the specified range. \nfile:bates-layers-delete.scm"
"Daniel Bates"
"Daniel Bates"
"Dec 2007"
"*"
SF-IMAGE "SF-IMAGE" 0
SF-DRAWABLE "SF-DRAWABLE" 0
SF-ADJUSTMENT _"Start at which layer?" '(1 1 2000 1 5 0 1)
SF-ADJUSTMENT _"End at which layer?" '(2 1 2000 1 5 0 1)
)
; end of script
| null | https://raw.githubusercontent.com/karlhof26/gimp-scheme/2b6798888592a834b7736e1321aa9a0931fc0b2b/bates-layers-delete.scm | scheme |
The GIMP -- an image manipulation program
Tags: public domain, layers, delete
Author statement:
Script designed to mass delete layers from current image
User uses numbers to denote start and end point of deletion
--------------------------------------------------------------------
--------------------------------------------------------------------
- Changelog -
--------------------------------------------------------------------
This script is released into the public domain.
You may redistribute and/or modify this script or extract segments without prior consent.
This script is distributed in the hope of being useful
but without warranty, explicit or otherwise.
Define Script
Define Variables
If the end layer is set below the start layer create an error message and terminate
Begin an undo group
Get the number of layers in an image and set to a variable
If layer2 is set above total layers change layer2 value to the total number of layers
Set the repeat variable by subtracting the user input values from the total number of layers
Set up variable for setting active layers and attributes
Set the layer to be editted as the active layer
Delete the specified layer
Update visual display
End undo group
end of script | Copyright ( C ) 1995 and
Mass delete layers script for GIMP 2.4
Created by
Distributed by Gimp FX Foundry project
(define (script-fu-delete-layers theImage theDraw theLayer1 theLayer2)
(let* (
(theNumber 0)
(theRepeat 0)
(theLayerRef 0)
)
(if (> theLayer1 theLayer2)
(begin
(set! theLayerRef (car (gimp-message-get-handler)))
(gimp-message-set-handler 0)
(gimp-message "Error: End layer number must be set higher than start layer number!")
(gimp-message-set-handler theLayerRef)
)
(begin
(gimp-undo-push-group-start theImage)
(set! theNumber (car (gimp-image-get-layers theImage)))
(if (> theLayer2 theNumber)
(set! theLayer2 theNumber)
)
(set! theRepeat (+ (- theLayer2 theLayer1) 1))
Begin loop and continue while repeat is higher than zero
(while (> theRepeat 0)
(set! theLayerRef (cadr (gimp-image-get-layers theImage)))
Alter theNumber for use in setting active layers and attributes
(set! theNumber (car (gimp-image-get-layers theImage)))
(set! theNumber (- theNumber (- theLayer1 1)))
( set ! ( gimp - image - set - active - layer theImage ( aref theLayerRef ( - theNumber 1 ) ) ) )
(gimp-image-remove-layer theImage (aref theLayerRef (- theNumber 1)))
Alter repeat variable ready for checking for next layer , if applicable
(set! theRepeat (- theRepeat 1))
)
(gimp-displays-flush)
(gimp-undo-push-group-end theImage)
)
)
)
)
Register script
(script-fu-register "script-fu-delete-layers"
"<Toolbox>/Script-Fu/Photo/Multi-Layer Tools/Delete Layers..."
"Deletes layers within the specified range. \nfile:bates-layers-delete.scm"
"Daniel Bates"
"Daniel Bates"
"Dec 2007"
"*"
SF-IMAGE "SF-IMAGE" 0
SF-DRAWABLE "SF-DRAWABLE" 0
SF-ADJUSTMENT _"Start at which layer?" '(1 1 2000 1 5 0 1)
SF-ADJUSTMENT _"End at which layer?" '(2 1 2000 1 5 0 1)
)
|
4f31206bc8e272ca216957e9f9694545ac5657446cae028334ce10efb01db22b | ocaml-obuild/obuild | a.ml | let foo = "B.A.foo"
| null | https://raw.githubusercontent.com/ocaml-obuild/obuild/28252e8cee836448e85bfbc9e09a44e7674dae39/tests/full/autopack2/src/b/a.ml | ocaml | let foo = "B.A.foo"
| |
caf1ab122bc522ad7b0d1ec940923ac414e4d7ede549da6360d1a212a2a3e48a | 5HT/ant | Types.mli |
open XNum;
open Runtime;
open Unicode.Types;
open Unicode.SymbolTable;
exception Syntax_error of UCStream.location and uc_string;
exception Runtime_error of uc_string;
value runtime_error : string -> 'a;
(*
type compare = [ Equal | Less | LessEqual | Greater | GreaterEqual | Inequal ];
type relation = unit; (* FIX *)
*)
type unknown = ref partial_value
and partial_value =
[ Unbound
| Constraint of list unknown
| Bool of bool
| Number of num
| Char of uc_char
| Symbol of symbol
| LinForm of LinForm.lin_form unknown
| Primitive1 of unknown -> partial_value
| Primitive2 of unknown -> unknown -> partial_value
| PrimitiveN of int and (list unknown -> partial_value)
| Function of environment and int and array bytecode
| Chain of environment and array bytecode
aritiy , local variables , and equations
| Application of partial_value and int and list unknown
| Nil
| List of unknown and unknown
| Tuple of array unknown
| Dictionary of SymbolMap.t unknown
| Opaque of Opaque.opaque unknown
]
and bytecode =
[ BDup
| BPop
| BPopN of int
| BConst of partial_value
| BGlobal of unknown
| BVariable of int and int
| BFunction of int and array bytecode
| BDictionary of array symbol
| BPair
| BTuple of int
| BSet of int and int
| BApply of int
| BReturn
| BCondJump of int
| BJump of int
| BLocal of int
| BEndLocal
| BMatch1 of list pattern_check and int and int and int
| BMatchN of array (list pattern_check) and int and int and int
| BUnify
| BRaise of string
]
and pattern_check =
[ PCAnything
| PCVariable of int
| PCNumber of num
| PCChar of uc_char
| PCSymbol of symbol
| PCTuple of int
| PCNil
| PCConsList
| PCAssign of int
]
and environment = list (array unknown);
value identical : unknown -> unknown -> bool;
value compare_unknowns : unknown -> unknown -> LinForm.compare_result;
value create_unbound : 'a -> unknown;
value create_unknown : partial_value -> unknown;
value add_constraint : unknown -> list unknown -> list unknown;
value merge_constraints : list unknown -> list unknown -> list unknown;
value type_name : partial_value -> string;
| null | https://raw.githubusercontent.com/5HT/ant/6acf51f4c4ebcc06c52c595776e0293cfa2f1da4/VM/Types.mli | ocaml |
type compare = [ Equal | Less | LessEqual | Greater | GreaterEqual | Inequal ];
type relation = unit; (* FIX |
open XNum;
open Runtime;
open Unicode.Types;
open Unicode.SymbolTable;
exception Syntax_error of UCStream.location and uc_string;
exception Runtime_error of uc_string;
value runtime_error : string -> 'a;
*)
type unknown = ref partial_value
and partial_value =
[ Unbound
| Constraint of list unknown
| Bool of bool
| Number of num
| Char of uc_char
| Symbol of symbol
| LinForm of LinForm.lin_form unknown
| Primitive1 of unknown -> partial_value
| Primitive2 of unknown -> unknown -> partial_value
| PrimitiveN of int and (list unknown -> partial_value)
| Function of environment and int and array bytecode
| Chain of environment and array bytecode
aritiy , local variables , and equations
| Application of partial_value and int and list unknown
| Nil
| List of unknown and unknown
| Tuple of array unknown
| Dictionary of SymbolMap.t unknown
| Opaque of Opaque.opaque unknown
]
and bytecode =
[ BDup
| BPop
| BPopN of int
| BConst of partial_value
| BGlobal of unknown
| BVariable of int and int
| BFunction of int and array bytecode
| BDictionary of array symbol
| BPair
| BTuple of int
| BSet of int and int
| BApply of int
| BReturn
| BCondJump of int
| BJump of int
| BLocal of int
| BEndLocal
| BMatch1 of list pattern_check and int and int and int
| BMatchN of array (list pattern_check) and int and int and int
| BUnify
| BRaise of string
]
and pattern_check =
[ PCAnything
| PCVariable of int
| PCNumber of num
| PCChar of uc_char
| PCSymbol of symbol
| PCTuple of int
| PCNil
| PCConsList
| PCAssign of int
]
and environment = list (array unknown);
value identical : unknown -> unknown -> bool;
value compare_unknowns : unknown -> unknown -> LinForm.compare_result;
value create_unbound : 'a -> unknown;
value create_unknown : partial_value -> unknown;
value add_constraint : unknown -> list unknown -> list unknown;
value merge_constraints : list unknown -> list unknown -> list unknown;
value type_name : partial_value -> string;
|
1318fcea1640e607dc99317953905825c118ae350555788b4ce77d4749a65780 | fujita-y/digamma | syncase.scm | Copyright ( c ) 2004 - 2022 Yoshikatsu Fujita / LittleWing Company Limited .
;;; See LICENSE file for terms and conditions of use.
;; memo:
;; (lookup-lexical-name)
;; local macro bound to unique symbol generated by (generate-local-macro-symbol). It may used for lexical name.
;; (unrename-syntax)
;; apply unrename-syntax to literals, patterns, and templates. It make expanded code free from environment.
;; (datum->syntax)
;; if call (datum->syntax ...) on macro expansion, (syntax-object-renames template-id) should be nil.
;; if call (datum->syntax ...) on transformer evaluation, (syntax-object-renames template-id) should be alist.
(set-top-level-value! '|.vars| #f)
(define make-syntax-object (lambda (form renames lexname) (tuple 'type:syntax form renames lexname)))
(define syntax-object-expr (lambda (obj) (tuple-ref obj 1)))
(define syntax-object-renames (lambda (obj) (tuple-ref obj 2)))
(define syntax-object-lexname (lambda (obj) (tuple-ref obj 3)))
(define wrapped-syntax-object?
(lambda (datum)
(eq? (tuple-ref datum 0) 'type:syntax)))
(define ensure-output-is-syntax-object
(lambda (form)
(let loop ((obj form))
(cond ((pair? obj)
(loop (car obj))
(loop (cdr obj)))
((vector? obj)
(map loop (vector->list obj)))
((symbol? obj)
(or (uninterned-symbol? obj)
(assertion-violation "transformation procedure" (format "output contains raw symbol ~s" obj) form)))))))
(define ensure-input-is-syntax-object
(lambda (form)
(let loop ((obj form))
(cond ((pair? obj)
(loop (car obj))
(loop (cdr obj)))
((vector? obj)
(map loop (vector->list obj)))
((symbol? obj)
(or (uninterned-symbol? obj)
(assertion-violation "transformation procedure" (format "input contains raw symbol ~s" obj) form)))))))
(set-top-level-value!
'|.flatten-syntax|
(lambda (expr)
(ensure-output-is-syntax-object expr)
(let ((ht (make-core-hashtable)))
(let ((expr
(let loop ((lst expr))
(cond ((pair? lst)
(let ((a (loop (car lst))) (d (loop (cdr lst))))
(cond ((and (eq? a (car lst)) (eq? d (cdr lst))) lst) (else (cons a d)))))
((vector? lst) (list->vector (map loop (vector->list lst))))
((identifier? lst)
(let ((rename (syntax-object-renames lst)))
(or (null? rename)
(or (core-hashtable-contains? ht (car rename))
(core-hashtable-set! ht (car rename) (cdr rename)))))
(syntax-object-expr lst))
((wrapped-syntax-object? lst)
(for-each
(lambda (a)
(or (core-hashtable-contains? ht (car a)) (core-hashtable-set! ht (car a) (cdr a))))
(syntax-object-renames lst))
(loop (syntax-object-expr lst)))
(else lst)))))
(values expr (core-hashtable->alist ht))))))
(set-top-level-value!
'|.syntax-dispatch|
(lambda (patvars form lites . lst)
(define match (lambda (form pat) (and (match-pattern? form pat lites) (bind-pattern form pat lites '()))))
(and patvars (ensure-input-is-syntax-object form))
(let ((form (unwrap-syntax form)) (patvars (or patvars '())))
(let loop ((lst lst))
(if (null? lst)
(syntax-violation (and (pair? form) (car form)) "invalid syntax" form)
(let ((clause (car lst)))
(let ((pat (car clause)) (fender (cadr clause)) (expr (caddr clause)))
(let ((vars (match form pat)))
(if (and vars (or (not fender) (fender (append vars patvars))))
(expr (append vars patvars))
(loop (cdr lst)))))))))))
(set-top-level-value!
'|.transformer-thunk|
(lambda (code)
(let ((thunk
(lambda (x)
(call-with-values
(lambda () (code x))
(lambda (obj . env) (if (null? env) (|.flatten-syntax| obj) (values obj (car env))))))))
(cond ((procedure? code)
(let-values (((nargs opt) (closure-arity code))) (and nargs opt (= nargs 1) (= opt 0) thunk)))
((variable-transformer-token? code) (set! code (tuple-ref code 1)) (make-variable-transformer-token thunk))
(else code)))))
(define expand-syntax-case
(lambda (form env)
(define rewrite
(lambda (form aliases)
(let loop ((lst form))
(cond ((pair? lst) (cons (loop (car lst)) (loop (cdr lst))))
((and (symbol? lst) (assq lst aliases)) => cdr)
((vector? lst) (list->vector (map loop (vector->list lst))))
(else lst)))))
(destructuring-match form
((_ expr lites clauses ...)
(let ((lites (unrename-syntax lites env)))
(or (and (list? lites) (every1 symbol? lites)) (syntax-violation 'syntax-case "invalid literals" form lites))
(or (unique-id-list? lites) (syntax-violation 'syntax-case "duplicate literals" form lites))
(and (memq '_ lites) (syntax-violation 'syntax-case "_ in literals" form lites))
(and (memq '... lites) (syntax-violation 'syntax-case "... in literals" form lites))
(let ((renames (map (lambda (id) (cons id (lookup-lexical-name id env))) lites)))
(let ((lites (rewrite lites renames)))
(define parse-pattern
(lambda (lst)
(let ((pattern (rewrite (unrename-syntax lst env) renames)))
(annotate pattern lst)
(check-pattern pattern lites)
(values
pattern
(extend-env
(map (lambda (a) (cons (car a) (make-pattern-variable (cdr a))))
(collect-vars-ranks pattern lites 0 '()))
env)))))
(annotate
`(|.syntax-dispatch|
,(expand-form '|.vars| env)
,(expand-form expr env)
',lites
,@(map (lambda (clause)
(destructuring-match clause
((p expr)
(let-values (((pattern env) (parse-pattern p)))
`(|.list| ',pattern #f ,(expand-form `(|.lambda| (|.vars|) ,expr) env))))
((p fender expr)
(let-values (((pattern env) (parse-pattern p)))
`(|.list|
',pattern
,(expand-form `(|.lambda| (|.vars|) ,fender) env)
,(expand-form `(|.lambda| (|.vars|) ,expr) env))))))
clauses))
expr)))))
(_ (syntax-violation 'syntax-case "invalid syntax" form)))))
(define expand-syntax
(lambda (form env)
(destructuring-match form
((_ tmpl)
(let ((template (unrename-syntax tmpl env)) (patvar (expand-form '|.vars| env)))
(let ((ids (collect-unique-macro-ids template)))
(let ((ranks
(filter
values
(map (lambda (id)
(let ((deno (env-lookup env id))) (and (pattern-variable? deno) (cons id (cdr deno)))))
ids))))
(check-template template ranks)
(let ((template-env
(cond ((current-template-environment)
=>
(lambda (alist)
(filter
values
(map (lambda (id)
(cond ((assq id ranks) #f)
((assq id alist) => (lambda (b) (cons id (cdr b))))
(else #f)))
ids))))
(else '()))))
(if (symbol? template)
(let ((identifier-lexname (lookup-lexical-name tmpl env)))
(if (eq? template identifier-lexname)
(if (null? ranks)
(if (null? template-env)
(annotate `(|.syntax/i0n| ,patvar ',template) form)
(annotate `(|.syntax/i0e| ,patvar ',template ',template-env) form))
(if (null? template-env)
(annotate `(|.syntax/i1n| ,patvar ',template) form)
(annotate `(|.syntax/i1e| ,patvar ',template ',template-env) form)))
(if (null? ranks)
(if (null? template-env)
(annotate `(|.syntax/i2n| ,patvar ',template ',identifier-lexname) form)
(annotate
`(|.syntax/i2e| ,patvar ',template ',template-env ',identifier-lexname)
form))
(if (null? template-env)
(annotate `(|.syntax/i3n| ,patvar ',template ',identifier-lexname) form)
(annotate
`(|.syntax/i3e| ,patvar ',template ',template-env ',identifier-lexname)
form)))))
(let ((lexname-check-list
(filter
values
(map (lambda (id)
(let ((lexname (lookup-lexical-name id env)))
(and (or (renamed-id? lexname) (local-macro-symbol? lexname))
(cond ((eq? id lexname) #f) (else (cons id lexname))))))
(collect-rename-ids template ranks)))))
(if (null? lexname-check-list)
(if (null? ranks)
(if (null? template-env)
(annotate `(|.syntax/c0n| ,patvar ',template) form)
(annotate `(|.syntax/c0e| ,patvar ',template ',template-env) form))
(if (null? template-env)
(annotate `(|.syntax/c1n| ,patvar ',template ',ranks) form)
(annotate `(|.syntax/c1e| ,patvar ',template ',template-env ',ranks) form)))
(if (null? ranks)
(if (null? template-env)
(annotate `(|.syntax/c2n| ,patvar ',template ',lexname-check-list) form)
(annotate
`(|.syntax/c2e| ,patvar ',template ',template-env ',lexname-check-list)
form))
(if (null? template-env)
(annotate `(|.syntax/c3n| ,patvar ',template ',ranks ',lexname-check-list) form)
(annotate
`(|.syntax/c3e| ,patvar ',template ',template-env ',ranks ',lexname-check-list)
form)))))))))))
(_ (syntax-violation 'syntax "expected exactly one datum" form)))))
(define syntax->datum
(lambda (expr)
(strip-rename-suffix
(let loop ((lst expr))
(cond ((pair? lst)
(let ((a (loop (car lst))) (d (loop (cdr lst))))
(cond ((and (eq? a (car lst)) (eq? d (cdr lst))) lst) (else (cons a d)))))
((vector? lst) (list->vector (map loop (vector->list lst))))
((wrapped-syntax-object? lst) (loop (syntax-object-expr lst)))
(else lst))))))
(define datum->syntax
(lambda (template-id datum)
(or (identifier? template-id)
(assertion-violation 'datum->syntax (format "expected identifier, but got ~r" template-id)))
(and (pair? (syntax-object-renames template-id))
(import? (cdr (syntax-object-renames template-id)))
(assertion-violation 'datum->syntax (format "identifer ~u out of context" (syntax-object-expr template-id))))
(let ((suffix (retrieve-rename-suffix (syntax-object-expr template-id)))
(env
(if (null? (syntax-object-renames template-id))
(current-expansion-environment)
(current-transformer-environment)))
(ht1 (make-core-hashtable))
(ht2 (make-core-hashtable)))
(let ((obj
(let loop ((lst datum))
(cond ((pair? lst) (cons (loop (car lst)) (loop (cdr lst))))
((vector? lst) (list->vector (map loop (vector->list lst))))
((symbol? lst)
(cond ((core-hashtable-ref ht1 lst #f))
(else
(let ((new
(if (or (uninterned-symbol? lst) (not (string=? suffix "")))
(compose-id lst suffix)
(string->symbol (format "~a~a" lst suffix)))))
(core-hashtable-set! ht1 lst new)
(let ((deno-trans (env-lookup env new)))
(cond ((eq? deno-trans new) (core-hashtable-set! ht2 new (env-lookup env lst)))
(else (core-hashtable-set! ht2 new deno-trans))))
new))))
(else lst)))))
(if (symbol? obj)
(make-syntax-object obj (or (assq obj (core-hashtable->alist ht2)) '()) #f)
(make-syntax-object obj (core-hashtable->alist ht2) #f))))))
(define identifier?
(lambda (datum)
(and (wrapped-syntax-object? datum)
(symbol? (syntax-object-expr datum)))))
(define bound-identifier=?
(lambda (id1 id2)
(or (identifier? id1)
(assertion-violation 'bound-identifier=? (format "expected identifier, but got ~r" id1)))
(or (identifier? id2)
(assertion-violation 'bound-identifier=? (format "expected identifier, but got ~r" id2)))
(string=? (symbol->string (syntax-object-expr id1))
(symbol->string (syntax-object-expr id2)))))
(define free-identifier=?
(lambda (id1 id2)
(or (identifier? id1) (assertion-violation 'free-identifier=? (format "expected identifier, but got ~r" id1)))
(or (identifier? id2) (assertion-violation 'free-identifier=? (format "expected identifier, but got ~r" id2)))
(let ((env-use (current-expansion-environment)) (env-def (current-transformer-environment)))
(let ((n1a (syntax-object-lexname id1)) (n2a (syntax-object-lexname id2)))
(let ((n1b (or n1a (lookup-lexical-name (syntax-object-expr id1) env-use)))
(n2b (or n2a (lookup-lexical-name (syntax-object-expr id2) env-use))))
(cond ((and n1a n2a) (eq? n1a n2a))
((eq? n1b n2b) (eq? (lookup-topmost-subst n1b env-def) (lookup-topmost-subst n2b env-use)))
(else
(let ((ren1 (syntax-object-renames id1)) (ren2 (syntax-object-renames id2)))
(if (and (pair? ren1) (pair? ren2))
(eq? (cdr ren1) (cdr ren2))
(eq? (lookup-topmost-subst n1b env-def) (lookup-topmost-subst n2b env-def)))))))))))
(define generate-temporaries
(lambda (obj)
(or (list? obj)
(assertion-violation 'generate-temporaries (format "expected list, but got ~r" obj)))
(map (lambda (n) (make-syntax-object (generate-temporary-symbol) '() #f)) obj)))
(define make-variable-transformer
(lambda (proc)
(make-variable-transformer-token
(lambda (x) (proc (if (wrapped-syntax-object? x) x (make-syntax-object x '() #f)))))))
(define make-variable-transformer-token
(lambda (datum)
(tuple 'type:variable-transformer-token datum)))
(define variable-transformer-token?
(lambda (obj)
(eq? (tuple-ref obj 0) 'type:variable-transformer-token)))
(define wrap-transformer-input
(lambda (form)
(cond ((wrapped-syntax-object? form) form)
((symbol? form) (make-syntax-object form form #f))
(else (make-syntax-object form '() #f)))))
(define unwrap-syntax
(lambda (expr)
(define contain-non-id-wrapped-syntax-object?
(lambda (lst)
(let loop ((lst lst))
(cond ((pair? lst) (or (loop (car lst)) (loop (cdr lst))))
((vector? lst)
(let loop2 ((i (- (vector-length lst) 1)))
(and (>= i 0) (or (loop (vector-ref lst i)) (loop2 (- i 1))))))
((identifier? lst) #f)
(else (wrapped-syntax-object? lst))))))
(cond ((contain-non-id-wrapped-syntax-object? expr)
(let ((renames
(let ((ht (make-core-hashtable)))
(let loop ((lst expr))
(cond ((pair? lst) (loop (car lst)) (loop (cdr lst)))
((vector? lst) (for-each loop (vector->list lst)))
((identifier? lst)
(let ((rename (syntax-object-renames lst)))
(or (null? rename)
(core-hashtable-contains? ht (car rename))
(core-hashtable-set! ht (car rename) (cdr rename)))))
((wrapped-syntax-object? lst)
(for-each
(lambda (a)
(or (core-hashtable-contains? ht (car a)) (core-hashtable-set! ht (car a) (cdr a))))
(syntax-object-renames lst))
(loop (syntax-object-expr lst)))))
(core-hashtable->alist ht))))
(let loop ((lst expr))
(cond ((pair? lst)
(let ((a (loop (car lst))) (d (loop (cdr lst))))
(cond ((and (eq? a (car lst)) (eq? d (cdr lst))) lst) (else (cons a d)))))
((symbol? lst) (make-syntax-object lst (or (assq lst renames) '()) #f))
((wrapped-syntax-object? lst)
(cond ((identifier? lst) lst) (else (loop (syntax-object-expr lst)))))
((vector? lst) (list->vector (map loop (vector->list lst))))
(else lst)))))
(else expr))))
(define syntax-transcribe
(lambda (vars template template-env ranks identifier-lexname lexname-check-list)
(define emit
(lambda (datum)
(cond ((wrapped-syntax-object? datum) datum)
(else (make-syntax-object datum '() #f)))))
(define contain-wrapped-syntax-object?
(lambda (lst)
(let loop ((lst lst))
(cond ((pair? lst) (or (null? (car lst)) (loop (car lst)) (loop (cdr lst))))
((vector? lst)
(let loop2 ((i (- (vector-length lst) 1)))
(and (>= i 0) (or (loop (vector-ref lst i)) (loop2 (- i 1))))))
(else (wrapped-syntax-object? lst))))))
(define rewrite-nil
(lambda (lst)
(let loop ((lst lst))
(cond ((pair? lst)
(let ((a (loop (car lst))) (d (loop (cdr lst))))
(cond ((and (eq? (car lst) a) (eq? (cdr lst) d)) lst) (else (cons a d)))))
((vector? lst) (list->vector (loop (vector->list lst))))
((eq? lst '|.&NIL|) '())
(else lst)))))
(define wrap-renamed-id
(lambda (lst renames)
(let loop ((lst lst))
(cond ((pair? lst)
(let ((a (loop (car lst))) (d (loop (cdr lst))))
(cond ((and (eq? (car lst) a) (eq? (cdr lst) d)) lst) (else (cons a d)))))
((vector? lst) (list->vector (loop (vector->list lst))))
((renamed-id? lst) (make-syntax-object lst (or (assq lst renames) '()) #f))
(else lst)))))
(define partial-wrap-syntax-object
(lambda (lst renames)
(let loop ((lst lst))
(cond ((contain-wrapped-syntax-object? lst)
(cond ((pair? lst)
(let ((a (loop (car lst))) (d (loop (cdr lst))))
(cond ((and (eq? (car lst) a) (eq? (cdr lst) d)) lst) (else (cons a d)))))
(else lst)))
((eq? lst '|.&NIL|) (make-syntax-object '() '() #f))
((symbol? lst) (make-syntax-object lst (or (assq lst renames) '()) #f))
((vector? lst) (make-syntax-object (rewrite-nil lst) renames #f))
((pair? lst) (make-syntax-object (rewrite-nil lst) renames #f))
((null? lst) '())
(else (make-syntax-object lst '() #f))))))
(if (null? template)
(make-syntax-object '() '() #f)
(let* ((env-use (current-expansion-environment))
(env-def (current-transformer-environment))
(suffix (current-rename-count))
(aliases (map (lambda (id) (cons id (rename-id id suffix))) (collect-rename-ids template ranks)))
(renames
(if (null? template-env)
(map (lambda (lst) (cons (cdr lst) (env-lookup env-def (car lst)))) aliases)
(map (lambda (lst)
(cond ((assq (car lst) template-env) => (lambda (e) (cons (cdr lst) (cdr e))))
(else (cons (cdr lst) (env-lookup env-def (car lst))))))
aliases)))
(out-of-context
(cond ((null? lexname-check-list) '())
((null? env-def) '())
(else
(filter
values
(map (lambda (a)
(let ((id (car a)))
(cond ((assq id lexname-check-list)
=>
(lambda (e)
(if (or (eq? (lookup-lexical-name id env-def) (cdr e))
(and (local-macro-symbol? (cdr e))
(let ((lexname-use (lookup-lexical-name (car e) env-use)))
(and (local-macro-symbol? lexname-use)
(eq?
lexname-use
(lookup-lexical-name (car e) env-def))))))
#f
(cons (cdr a) (make-out-of-context template)))))
(else #f))))
aliases))))))
(let ((vars (or vars '())))
(if (null? env-use)
(let ((form (transcribe-template template ranks vars aliases #f)))
(if (renamed-id? form)
(make-syntax-object form (or (assq form renames) '()) identifier-lexname)
(wrap-renamed-id form renames)))
(let ((form (transcribe-template template ranks vars aliases emit)))
(cond ((null? form) '())
((wrapped-syntax-object? form) form)
((eq? form '|.&NIL|) (make-syntax-object '() '() #f))
((symbol? form)
(make-syntax-object
form
(or (assq form out-of-context) (assq form renames) '())
identifier-lexname))
(else (partial-wrap-syntax-object form (extend-env out-of-context renames)))))))))))
;; shorthands without template environment
(set-top-level-value! '|.syntax/i0n| ; identifier: no-rank no-lexname
(lambda (vars template)
(syntax-transcribe vars template '() '() template '())))
(set-top-level-value! '|.syntax/i1n| ; identifier: rank-0 no-lexname
(lambda (vars template)
(syntax-transcribe vars template '() (list (cons template 0)) template '())))
(set-top-level-value! '|.syntax/i2n| ; identifier: no-rank has-lexname
(lambda (vars template identifier-lexname)
(syntax-transcribe vars template '() '() identifier-lexname '())))
(set-top-level-value! '|.syntax/i3n| ; identifier: rank-0 has-lexname
(lambda (vars template identifier-lexname)
(syntax-transcribe vars template '() (list (cons template 0)) identifier-lexname '())))
(set-top-level-value! '|.syntax/c0n| ; subtemplate: no-ranks no-lexname-check-list
(lambda (vars template)
(syntax-transcribe vars template '() '() #f '())))
(set-top-level-value! '|.syntax/c1n| ; subtemplate: has-ranks no-lexname-check-list
(lambda (vars template ranks)
(syntax-transcribe vars template '() ranks #f '())))
(set-top-level-value! '|.syntax/c2n| ; subtemplate: no-ranks has-lexname-check-list
(lambda (vars template lexname-check-list)
(syntax-transcribe vars template '() '() #f lexname-check-list)))
(set-top-level-value! '|.syntax/c3n| ; subtemplate: has-ranks has-lexname-check-list
(lambda (vars template ranks lexname-check-list)
(syntax-transcribe vars template '() ranks #f lexname-check-list)))
;; shorthands with template environment
(set-top-level-value! '|.syntax/i0e| ; identifier: no-rank no-lexname
(lambda (vars template env)
(syntax-transcribe vars template env '() template '())))
(set-top-level-value! '|.syntax/i1e| ; identifier: rank-0 no-lexname
(lambda (vars template env)
(syntax-transcribe vars template env (list (cons template 0)) template '())))
(set-top-level-value! '|.syntax/i2e| ; identifier: no-rank has-lexname
(lambda (vars template env identifier-lexname)
(syntax-transcribe vars template env '() identifier-lexname '())))
(set-top-level-value! '|.syntax/i3e| ; identifier: rank-0 has-lexname
(lambda (vars template env identifier-lexname)
(syntax-transcribe vars template env (list (cons template 0)) identifier-lexname '())))
(set-top-level-value! '|.syntax/c0e| ; subtemplate: no-ranks no-lexname-check-list
(lambda (vars template env)
(syntax-transcribe vars template env '() #f '())))
(set-top-level-value! '|.syntax/c1e| ; subtemplate: has-ranks no-lexname-check-list
(lambda (vars template env ranks)
(syntax-transcribe vars template env ranks #f '())))
(set-top-level-value! '|.syntax/c2e| ; subtemplate: no-ranks has-lexname-check-list
(lambda (vars template env lexname-check-list)
(syntax-transcribe vars template env '() #f lexname-check-list)))
(set-top-level-value! '|.syntax/c3e| ; subtemplate: has-ranks has-lexname-check-list
(lambda (vars template env ranks lexname-check-list)
(syntax-transcribe vars template env ranks #f lexname-check-list)))
| null | https://raw.githubusercontent.com/fujita-y/digamma/58cccd77bd2c208ec58d3cd634cbe65e32b3c7ec/heap/boot/macro/syncase.scm | scheme | See LICENSE file for terms and conditions of use.
memo:
(lookup-lexical-name)
local macro bound to unique symbol generated by (generate-local-macro-symbol). It may used for lexical name.
(unrename-syntax)
apply unrename-syntax to literals, patterns, and templates. It make expanded code free from environment.
(datum->syntax)
if call (datum->syntax ...) on macro expansion, (syntax-object-renames template-id) should be nil.
if call (datum->syntax ...) on transformer evaluation, (syntax-object-renames template-id) should be alist.
shorthands without template environment
identifier: no-rank no-lexname
identifier: rank-0 no-lexname
identifier: no-rank has-lexname
identifier: rank-0 has-lexname
subtemplate: no-ranks no-lexname-check-list
subtemplate: has-ranks no-lexname-check-list
subtemplate: no-ranks has-lexname-check-list
subtemplate: has-ranks has-lexname-check-list
shorthands with template environment
identifier: no-rank no-lexname
identifier: rank-0 no-lexname
identifier: no-rank has-lexname
identifier: rank-0 has-lexname
subtemplate: no-ranks no-lexname-check-list
subtemplate: has-ranks no-lexname-check-list
subtemplate: no-ranks has-lexname-check-list
subtemplate: has-ranks has-lexname-check-list | Copyright ( c ) 2004 - 2022 Yoshikatsu Fujita / LittleWing Company Limited .
(set-top-level-value! '|.vars| #f)
(define make-syntax-object (lambda (form renames lexname) (tuple 'type:syntax form renames lexname)))
(define syntax-object-expr (lambda (obj) (tuple-ref obj 1)))
(define syntax-object-renames (lambda (obj) (tuple-ref obj 2)))
(define syntax-object-lexname (lambda (obj) (tuple-ref obj 3)))
(define wrapped-syntax-object?
(lambda (datum)
(eq? (tuple-ref datum 0) 'type:syntax)))
(define ensure-output-is-syntax-object
(lambda (form)
(let loop ((obj form))
(cond ((pair? obj)
(loop (car obj))
(loop (cdr obj)))
((vector? obj)
(map loop (vector->list obj)))
((symbol? obj)
(or (uninterned-symbol? obj)
(assertion-violation "transformation procedure" (format "output contains raw symbol ~s" obj) form)))))))
(define ensure-input-is-syntax-object
(lambda (form)
(let loop ((obj form))
(cond ((pair? obj)
(loop (car obj))
(loop (cdr obj)))
((vector? obj)
(map loop (vector->list obj)))
((symbol? obj)
(or (uninterned-symbol? obj)
(assertion-violation "transformation procedure" (format "input contains raw symbol ~s" obj) form)))))))
(set-top-level-value!
'|.flatten-syntax|
(lambda (expr)
(ensure-output-is-syntax-object expr)
(let ((ht (make-core-hashtable)))
(let ((expr
(let loop ((lst expr))
(cond ((pair? lst)
(let ((a (loop (car lst))) (d (loop (cdr lst))))
(cond ((and (eq? a (car lst)) (eq? d (cdr lst))) lst) (else (cons a d)))))
((vector? lst) (list->vector (map loop (vector->list lst))))
((identifier? lst)
(let ((rename (syntax-object-renames lst)))
(or (null? rename)
(or (core-hashtable-contains? ht (car rename))
(core-hashtable-set! ht (car rename) (cdr rename)))))
(syntax-object-expr lst))
((wrapped-syntax-object? lst)
(for-each
(lambda (a)
(or (core-hashtable-contains? ht (car a)) (core-hashtable-set! ht (car a) (cdr a))))
(syntax-object-renames lst))
(loop (syntax-object-expr lst)))
(else lst)))))
(values expr (core-hashtable->alist ht))))))
(set-top-level-value!
'|.syntax-dispatch|
(lambda (patvars form lites . lst)
(define match (lambda (form pat) (and (match-pattern? form pat lites) (bind-pattern form pat lites '()))))
(and patvars (ensure-input-is-syntax-object form))
(let ((form (unwrap-syntax form)) (patvars (or patvars '())))
(let loop ((lst lst))
(if (null? lst)
(syntax-violation (and (pair? form) (car form)) "invalid syntax" form)
(let ((clause (car lst)))
(let ((pat (car clause)) (fender (cadr clause)) (expr (caddr clause)))
(let ((vars (match form pat)))
(if (and vars (or (not fender) (fender (append vars patvars))))
(expr (append vars patvars))
(loop (cdr lst)))))))))))
(set-top-level-value!
'|.transformer-thunk|
(lambda (code)
(let ((thunk
(lambda (x)
(call-with-values
(lambda () (code x))
(lambda (obj . env) (if (null? env) (|.flatten-syntax| obj) (values obj (car env))))))))
(cond ((procedure? code)
(let-values (((nargs opt) (closure-arity code))) (and nargs opt (= nargs 1) (= opt 0) thunk)))
((variable-transformer-token? code) (set! code (tuple-ref code 1)) (make-variable-transformer-token thunk))
(else code)))))
(define expand-syntax-case
(lambda (form env)
(define rewrite
(lambda (form aliases)
(let loop ((lst form))
(cond ((pair? lst) (cons (loop (car lst)) (loop (cdr lst))))
((and (symbol? lst) (assq lst aliases)) => cdr)
((vector? lst) (list->vector (map loop (vector->list lst))))
(else lst)))))
(destructuring-match form
((_ expr lites clauses ...)
(let ((lites (unrename-syntax lites env)))
(or (and (list? lites) (every1 symbol? lites)) (syntax-violation 'syntax-case "invalid literals" form lites))
(or (unique-id-list? lites) (syntax-violation 'syntax-case "duplicate literals" form lites))
(and (memq '_ lites) (syntax-violation 'syntax-case "_ in literals" form lites))
(and (memq '... lites) (syntax-violation 'syntax-case "... in literals" form lites))
(let ((renames (map (lambda (id) (cons id (lookup-lexical-name id env))) lites)))
(let ((lites (rewrite lites renames)))
(define parse-pattern
(lambda (lst)
(let ((pattern (rewrite (unrename-syntax lst env) renames)))
(annotate pattern lst)
(check-pattern pattern lites)
(values
pattern
(extend-env
(map (lambda (a) (cons (car a) (make-pattern-variable (cdr a))))
(collect-vars-ranks pattern lites 0 '()))
env)))))
(annotate
`(|.syntax-dispatch|
,(expand-form '|.vars| env)
,(expand-form expr env)
',lites
,@(map (lambda (clause)
(destructuring-match clause
((p expr)
(let-values (((pattern env) (parse-pattern p)))
`(|.list| ',pattern #f ,(expand-form `(|.lambda| (|.vars|) ,expr) env))))
((p fender expr)
(let-values (((pattern env) (parse-pattern p)))
`(|.list|
',pattern
,(expand-form `(|.lambda| (|.vars|) ,fender) env)
,(expand-form `(|.lambda| (|.vars|) ,expr) env))))))
clauses))
expr)))))
(_ (syntax-violation 'syntax-case "invalid syntax" form)))))
(define expand-syntax
(lambda (form env)
(destructuring-match form
((_ tmpl)
(let ((template (unrename-syntax tmpl env)) (patvar (expand-form '|.vars| env)))
(let ((ids (collect-unique-macro-ids template)))
(let ((ranks
(filter
values
(map (lambda (id)
(let ((deno (env-lookup env id))) (and (pattern-variable? deno) (cons id (cdr deno)))))
ids))))
(check-template template ranks)
(let ((template-env
(cond ((current-template-environment)
=>
(lambda (alist)
(filter
values
(map (lambda (id)
(cond ((assq id ranks) #f)
((assq id alist) => (lambda (b) (cons id (cdr b))))
(else #f)))
ids))))
(else '()))))
(if (symbol? template)
(let ((identifier-lexname (lookup-lexical-name tmpl env)))
(if (eq? template identifier-lexname)
(if (null? ranks)
(if (null? template-env)
(annotate `(|.syntax/i0n| ,patvar ',template) form)
(annotate `(|.syntax/i0e| ,patvar ',template ',template-env) form))
(if (null? template-env)
(annotate `(|.syntax/i1n| ,patvar ',template) form)
(annotate `(|.syntax/i1e| ,patvar ',template ',template-env) form)))
(if (null? ranks)
(if (null? template-env)
(annotate `(|.syntax/i2n| ,patvar ',template ',identifier-lexname) form)
(annotate
`(|.syntax/i2e| ,patvar ',template ',template-env ',identifier-lexname)
form))
(if (null? template-env)
(annotate `(|.syntax/i3n| ,patvar ',template ',identifier-lexname) form)
(annotate
`(|.syntax/i3e| ,patvar ',template ',template-env ',identifier-lexname)
form)))))
(let ((lexname-check-list
(filter
values
(map (lambda (id)
(let ((lexname (lookup-lexical-name id env)))
(and (or (renamed-id? lexname) (local-macro-symbol? lexname))
(cond ((eq? id lexname) #f) (else (cons id lexname))))))
(collect-rename-ids template ranks)))))
(if (null? lexname-check-list)
(if (null? ranks)
(if (null? template-env)
(annotate `(|.syntax/c0n| ,patvar ',template) form)
(annotate `(|.syntax/c0e| ,patvar ',template ',template-env) form))
(if (null? template-env)
(annotate `(|.syntax/c1n| ,patvar ',template ',ranks) form)
(annotate `(|.syntax/c1e| ,patvar ',template ',template-env ',ranks) form)))
(if (null? ranks)
(if (null? template-env)
(annotate `(|.syntax/c2n| ,patvar ',template ',lexname-check-list) form)
(annotate
`(|.syntax/c2e| ,patvar ',template ',template-env ',lexname-check-list)
form))
(if (null? template-env)
(annotate `(|.syntax/c3n| ,patvar ',template ',ranks ',lexname-check-list) form)
(annotate
`(|.syntax/c3e| ,patvar ',template ',template-env ',ranks ',lexname-check-list)
form)))))))))))
(_ (syntax-violation 'syntax "expected exactly one datum" form)))))
(define syntax->datum
(lambda (expr)
(strip-rename-suffix
(let loop ((lst expr))
(cond ((pair? lst)
(let ((a (loop (car lst))) (d (loop (cdr lst))))
(cond ((and (eq? a (car lst)) (eq? d (cdr lst))) lst) (else (cons a d)))))
((vector? lst) (list->vector (map loop (vector->list lst))))
((wrapped-syntax-object? lst) (loop (syntax-object-expr lst)))
(else lst))))))
(define datum->syntax
(lambda (template-id datum)
(or (identifier? template-id)
(assertion-violation 'datum->syntax (format "expected identifier, but got ~r" template-id)))
(and (pair? (syntax-object-renames template-id))
(import? (cdr (syntax-object-renames template-id)))
(assertion-violation 'datum->syntax (format "identifer ~u out of context" (syntax-object-expr template-id))))
(let ((suffix (retrieve-rename-suffix (syntax-object-expr template-id)))
(env
(if (null? (syntax-object-renames template-id))
(current-expansion-environment)
(current-transformer-environment)))
(ht1 (make-core-hashtable))
(ht2 (make-core-hashtable)))
(let ((obj
(let loop ((lst datum))
(cond ((pair? lst) (cons (loop (car lst)) (loop (cdr lst))))
((vector? lst) (list->vector (map loop (vector->list lst))))
((symbol? lst)
(cond ((core-hashtable-ref ht1 lst #f))
(else
(let ((new
(if (or (uninterned-symbol? lst) (not (string=? suffix "")))
(compose-id lst suffix)
(string->symbol (format "~a~a" lst suffix)))))
(core-hashtable-set! ht1 lst new)
(let ((deno-trans (env-lookup env new)))
(cond ((eq? deno-trans new) (core-hashtable-set! ht2 new (env-lookup env lst)))
(else (core-hashtable-set! ht2 new deno-trans))))
new))))
(else lst)))))
(if (symbol? obj)
(make-syntax-object obj (or (assq obj (core-hashtable->alist ht2)) '()) #f)
(make-syntax-object obj (core-hashtable->alist ht2) #f))))))
(define identifier?
(lambda (datum)
(and (wrapped-syntax-object? datum)
(symbol? (syntax-object-expr datum)))))
(define bound-identifier=?
(lambda (id1 id2)
(or (identifier? id1)
(assertion-violation 'bound-identifier=? (format "expected identifier, but got ~r" id1)))
(or (identifier? id2)
(assertion-violation 'bound-identifier=? (format "expected identifier, but got ~r" id2)))
(string=? (symbol->string (syntax-object-expr id1))
(symbol->string (syntax-object-expr id2)))))
(define free-identifier=?
(lambda (id1 id2)
(or (identifier? id1) (assertion-violation 'free-identifier=? (format "expected identifier, but got ~r" id1)))
(or (identifier? id2) (assertion-violation 'free-identifier=? (format "expected identifier, but got ~r" id2)))
(let ((env-use (current-expansion-environment)) (env-def (current-transformer-environment)))
(let ((n1a (syntax-object-lexname id1)) (n2a (syntax-object-lexname id2)))
(let ((n1b (or n1a (lookup-lexical-name (syntax-object-expr id1) env-use)))
(n2b (or n2a (lookup-lexical-name (syntax-object-expr id2) env-use))))
(cond ((and n1a n2a) (eq? n1a n2a))
((eq? n1b n2b) (eq? (lookup-topmost-subst n1b env-def) (lookup-topmost-subst n2b env-use)))
(else
(let ((ren1 (syntax-object-renames id1)) (ren2 (syntax-object-renames id2)))
(if (and (pair? ren1) (pair? ren2))
(eq? (cdr ren1) (cdr ren2))
(eq? (lookup-topmost-subst n1b env-def) (lookup-topmost-subst n2b env-def)))))))))))
(define generate-temporaries
(lambda (obj)
(or (list? obj)
(assertion-violation 'generate-temporaries (format "expected list, but got ~r" obj)))
(map (lambda (n) (make-syntax-object (generate-temporary-symbol) '() #f)) obj)))
(define make-variable-transformer
(lambda (proc)
(make-variable-transformer-token
(lambda (x) (proc (if (wrapped-syntax-object? x) x (make-syntax-object x '() #f)))))))
(define make-variable-transformer-token
(lambda (datum)
(tuple 'type:variable-transformer-token datum)))
(define variable-transformer-token?
(lambda (obj)
(eq? (tuple-ref obj 0) 'type:variable-transformer-token)))
(define wrap-transformer-input
(lambda (form)
(cond ((wrapped-syntax-object? form) form)
((symbol? form) (make-syntax-object form form #f))
(else (make-syntax-object form '() #f)))))
(define unwrap-syntax
(lambda (expr)
(define contain-non-id-wrapped-syntax-object?
(lambda (lst)
(let loop ((lst lst))
(cond ((pair? lst) (or (loop (car lst)) (loop (cdr lst))))
((vector? lst)
(let loop2 ((i (- (vector-length lst) 1)))
(and (>= i 0) (or (loop (vector-ref lst i)) (loop2 (- i 1))))))
((identifier? lst) #f)
(else (wrapped-syntax-object? lst))))))
(cond ((contain-non-id-wrapped-syntax-object? expr)
(let ((renames
(let ((ht (make-core-hashtable)))
(let loop ((lst expr))
(cond ((pair? lst) (loop (car lst)) (loop (cdr lst)))
((vector? lst) (for-each loop (vector->list lst)))
((identifier? lst)
(let ((rename (syntax-object-renames lst)))
(or (null? rename)
(core-hashtable-contains? ht (car rename))
(core-hashtable-set! ht (car rename) (cdr rename)))))
((wrapped-syntax-object? lst)
(for-each
(lambda (a)
(or (core-hashtable-contains? ht (car a)) (core-hashtable-set! ht (car a) (cdr a))))
(syntax-object-renames lst))
(loop (syntax-object-expr lst)))))
(core-hashtable->alist ht))))
(let loop ((lst expr))
(cond ((pair? lst)
(let ((a (loop (car lst))) (d (loop (cdr lst))))
(cond ((and (eq? a (car lst)) (eq? d (cdr lst))) lst) (else (cons a d)))))
((symbol? lst) (make-syntax-object lst (or (assq lst renames) '()) #f))
((wrapped-syntax-object? lst)
(cond ((identifier? lst) lst) (else (loop (syntax-object-expr lst)))))
((vector? lst) (list->vector (map loop (vector->list lst))))
(else lst)))))
(else expr))))
(define syntax-transcribe
(lambda (vars template template-env ranks identifier-lexname lexname-check-list)
(define emit
(lambda (datum)
(cond ((wrapped-syntax-object? datum) datum)
(else (make-syntax-object datum '() #f)))))
(define contain-wrapped-syntax-object?
(lambda (lst)
(let loop ((lst lst))
(cond ((pair? lst) (or (null? (car lst)) (loop (car lst)) (loop (cdr lst))))
((vector? lst)
(let loop2 ((i (- (vector-length lst) 1)))
(and (>= i 0) (or (loop (vector-ref lst i)) (loop2 (- i 1))))))
(else (wrapped-syntax-object? lst))))))
(define rewrite-nil
(lambda (lst)
(let loop ((lst lst))
(cond ((pair? lst)
(let ((a (loop (car lst))) (d (loop (cdr lst))))
(cond ((and (eq? (car lst) a) (eq? (cdr lst) d)) lst) (else (cons a d)))))
((vector? lst) (list->vector (loop (vector->list lst))))
((eq? lst '|.&NIL|) '())
(else lst)))))
(define wrap-renamed-id
(lambda (lst renames)
(let loop ((lst lst))
(cond ((pair? lst)
(let ((a (loop (car lst))) (d (loop (cdr lst))))
(cond ((and (eq? (car lst) a) (eq? (cdr lst) d)) lst) (else (cons a d)))))
((vector? lst) (list->vector (loop (vector->list lst))))
((renamed-id? lst) (make-syntax-object lst (or (assq lst renames) '()) #f))
(else lst)))))
(define partial-wrap-syntax-object
(lambda (lst renames)
(let loop ((lst lst))
(cond ((contain-wrapped-syntax-object? lst)
(cond ((pair? lst)
(let ((a (loop (car lst))) (d (loop (cdr lst))))
(cond ((and (eq? (car lst) a) (eq? (cdr lst) d)) lst) (else (cons a d)))))
(else lst)))
((eq? lst '|.&NIL|) (make-syntax-object '() '() #f))
((symbol? lst) (make-syntax-object lst (or (assq lst renames) '()) #f))
((vector? lst) (make-syntax-object (rewrite-nil lst) renames #f))
((pair? lst) (make-syntax-object (rewrite-nil lst) renames #f))
((null? lst) '())
(else (make-syntax-object lst '() #f))))))
(if (null? template)
(make-syntax-object '() '() #f)
(let* ((env-use (current-expansion-environment))
(env-def (current-transformer-environment))
(suffix (current-rename-count))
(aliases (map (lambda (id) (cons id (rename-id id suffix))) (collect-rename-ids template ranks)))
(renames
(if (null? template-env)
(map (lambda (lst) (cons (cdr lst) (env-lookup env-def (car lst)))) aliases)
(map (lambda (lst)
(cond ((assq (car lst) template-env) => (lambda (e) (cons (cdr lst) (cdr e))))
(else (cons (cdr lst) (env-lookup env-def (car lst))))))
aliases)))
(out-of-context
(cond ((null? lexname-check-list) '())
((null? env-def) '())
(else
(filter
values
(map (lambda (a)
(let ((id (car a)))
(cond ((assq id lexname-check-list)
=>
(lambda (e)
(if (or (eq? (lookup-lexical-name id env-def) (cdr e))
(and (local-macro-symbol? (cdr e))
(let ((lexname-use (lookup-lexical-name (car e) env-use)))
(and (local-macro-symbol? lexname-use)
(eq?
lexname-use
(lookup-lexical-name (car e) env-def))))))
#f
(cons (cdr a) (make-out-of-context template)))))
(else #f))))
aliases))))))
(let ((vars (or vars '())))
(if (null? env-use)
(let ((form (transcribe-template template ranks vars aliases #f)))
(if (renamed-id? form)
(make-syntax-object form (or (assq form renames) '()) identifier-lexname)
(wrap-renamed-id form renames)))
(let ((form (transcribe-template template ranks vars aliases emit)))
(cond ((null? form) '())
((wrapped-syntax-object? form) form)
((eq? form '|.&NIL|) (make-syntax-object '() '() #f))
((symbol? form)
(make-syntax-object
form
(or (assq form out-of-context) (assq form renames) '())
identifier-lexname))
(else (partial-wrap-syntax-object form (extend-env out-of-context renames)))))))))))
(lambda (vars template)
(syntax-transcribe vars template '() '() template '())))
(lambda (vars template)
(syntax-transcribe vars template '() (list (cons template 0)) template '())))
(lambda (vars template identifier-lexname)
(syntax-transcribe vars template '() '() identifier-lexname '())))
(lambda (vars template identifier-lexname)
(syntax-transcribe vars template '() (list (cons template 0)) identifier-lexname '())))
(lambda (vars template)
(syntax-transcribe vars template '() '() #f '())))
(lambda (vars template ranks)
(syntax-transcribe vars template '() ranks #f '())))
(lambda (vars template lexname-check-list)
(syntax-transcribe vars template '() '() #f lexname-check-list)))
(lambda (vars template ranks lexname-check-list)
(syntax-transcribe vars template '() ranks #f lexname-check-list)))
(lambda (vars template env)
(syntax-transcribe vars template env '() template '())))
(lambda (vars template env)
(syntax-transcribe vars template env (list (cons template 0)) template '())))
(lambda (vars template env identifier-lexname)
(syntax-transcribe vars template env '() identifier-lexname '())))
(lambda (vars template env identifier-lexname)
(syntax-transcribe vars template env (list (cons template 0)) identifier-lexname '())))
(lambda (vars template env)
(syntax-transcribe vars template env '() #f '())))
(lambda (vars template env ranks)
(syntax-transcribe vars template env ranks #f '())))
(lambda (vars template env lexname-check-list)
(syntax-transcribe vars template env '() #f lexname-check-list)))
(lambda (vars template env ranks lexname-check-list)
(syntax-transcribe vars template env ranks #f lexname-check-list)))
|
cc5294eaf12f8fb07d397cae4b26b5884679d9156054e312fc95c232c2da285f | scicloj/notespace | view.clj | (ns scicloj.notespace.v4.view
(:require [clojure.string :as string]
[gorilla-notes.core :as gn]
[scicloj.notespace.v4.log :as v4.log]
[scicloj.notespace.v4.note :as v4.note]
[scicloj.notespace.v4.config :as v4.config]))
(defn summary->hiccup [{:keys [current-path
current-notes
counts]
:as details}]
[:div
[:p [:big [:big [:p/code (pr-str {:notespace current-path})]]]]
[:p/code
(->> counts
(merge {:notes (count current-notes)})
pr-str)]])
(defn comment-source->hiccup [source]
[:div.container-fluid
[:p/markdown
(-> source
(string/split #"\n")
(->> (map #(string/replace % #"^\s*;*" ""))
(string/join "\n")))]])
(defn note->hiccup [[part {:keys [source gen status value comment?] :as note}]]
(let [{:keys [render-src? value->hiccup]} (v4.note/behaviour note)
source-view (fn []
(if comment?
(comment-source->hiccup source)
;; else
(when (and (not comment?)
render-src?)
[:div.bg-light.pt-4.pb-2
[:div.container-fluid [:p/code {:code source}]]])))
state-view (fn []
(if comment?
""
(if status
[:div #_{:style {:background "floralwhite"}}
[:div.container-fluid
(case status
:evaluating "evaluating ..."
:failed "failed"
:evaluated (value->hiccup value))]]
[:div.mb-3])))
both-view (fn []
[:div
[:div {:style {:display :inline-block
:vertical-align :top
:width "50%"}}
(source-view)]
[:div {:style {:display :inline-block
:vertical-align :top
:width "50%"}}
(state-view)]
[:br]
[:br]])]
[:div
(case part
:view/source (source-view)
:view/state (state-view)
:view/both (both-view))]))
(defn ->header [{:keys [current-path]
:as details}]
[:div
[:br]
[:p
{:style {:margin "0 10px"
;; :font-family "'Fira Code'"
}}
current-path]]
;; (let [{:keys [messages? summary?]} @v4.config/*config]
;; [:div.bg-light
;; [:p ""]
;; (when summary?
;; (summary->hiccup details))])
)
| null | https://raw.githubusercontent.com/scicloj/notespace/1929f4d2b69c9e52f4ddb5581d10ecaaa29b3c69/src/scicloj/notespace/v4/view.clj | clojure | else
:font-family "'Fira Code'"
(let [{:keys [messages? summary?]} @v4.config/*config]
[:div.bg-light
[:p ""]
(when summary?
(summary->hiccup details))]) | (ns scicloj.notespace.v4.view
(:require [clojure.string :as string]
[gorilla-notes.core :as gn]
[scicloj.notespace.v4.log :as v4.log]
[scicloj.notespace.v4.note :as v4.note]
[scicloj.notespace.v4.config :as v4.config]))
(defn summary->hiccup [{:keys [current-path
current-notes
counts]
:as details}]
[:div
[:p [:big [:big [:p/code (pr-str {:notespace current-path})]]]]
[:p/code
(->> counts
(merge {:notes (count current-notes)})
pr-str)]])
(defn comment-source->hiccup [source]
[:div.container-fluid
[:p/markdown
(-> source
(string/split #"\n")
(->> (map #(string/replace % #"^\s*;*" ""))
(string/join "\n")))]])
(defn note->hiccup [[part {:keys [source gen status value comment?] :as note}]]
(let [{:keys [render-src? value->hiccup]} (v4.note/behaviour note)
source-view (fn []
(if comment?
(comment-source->hiccup source)
(when (and (not comment?)
render-src?)
[:div.bg-light.pt-4.pb-2
[:div.container-fluid [:p/code {:code source}]]])))
state-view (fn []
(if comment?
""
(if status
[:div #_{:style {:background "floralwhite"}}
[:div.container-fluid
(case status
:evaluating "evaluating ..."
:failed "failed"
:evaluated (value->hiccup value))]]
[:div.mb-3])))
both-view (fn []
[:div
[:div {:style {:display :inline-block
:vertical-align :top
:width "50%"}}
(source-view)]
[:div {:style {:display :inline-block
:vertical-align :top
:width "50%"}}
(state-view)]
[:br]
[:br]])]
[:div
(case part
:view/source (source-view)
:view/state (state-view)
:view/both (both-view))]))
(defn ->header [{:keys [current-path]
:as details}]
[:div
[:br]
[:p
{:style {:margin "0 10px"
}}
current-path]]
)
|
9b3725b2e542e550482fe5d10f025e20c67110aed8cb5fe19024fd0d2dcd9370 | mirage/arp | arp_handler.ml |
type 'a entry =
| Static of Macaddr.t * bool
| Dynamic of Macaddr.t * int
| Pending of 'a * int
module M = Map.Make(Ipaddr.V4)
type 'a t = {
cache : 'a entry M.t ;
mac : Macaddr.t ;
ip : Ipaddr.V4.t ;
timeout : int ;
retries : int ;
epoch : int ;
logsrc : Logs.src
}
let ips t =
M.fold (fun ip entry acc -> match entry with
| Static (_, true) -> ip :: acc
| _ -> acc)
t.cache []
let mac t = t.mac
let[@coverage off] pp_entry now k pp =
function
| Static (m, adv) ->
let adv = if adv then " advertising" else "" in
Format.fprintf pp "%a at %a (static%s)" Ipaddr.V4.pp k Macaddr.pp m adv
| Dynamic (m, t) ->
Format.fprintf pp "%a at %a (timeout in %d)" Ipaddr.V4.pp k
Macaddr.pp m (t - now)
| Pending (_, retries) ->
Format.fprintf pp "%a (incomplete, %d retries left)"
Ipaddr.V4.pp k (retries - now)
let[@coverage off] pp pp t =
Format.fprintf pp "mac %a ip %a entries %d timeout %d retries %d@."
Macaddr.pp t.mac
Ipaddr.V4.pp t.ip
(M.cardinal t.cache)
t.timeout t.retries ;
M.iter (fun k v -> pp_entry t.epoch k pp v ; Format.pp_print_space pp ()) t.cache
let pending t ip =
match M.find ip t.cache with
| exception Not_found -> None
| Pending (a, _) -> Some a
| _ -> None
let mac0 = Macaddr.of_octets_exn (Cstruct.to_string (Cstruct.create 6))
let alias t ip =
let cache = M.add ip (Static (t.mac, true)) t.cache in
see RFC5227 Section 3 why we send out an ARP request
let garp = Arp_packet.({
operation = Request ;
source_mac = t.mac ;
target_mac = mac0 ;
source_ip = ip ; target_ip = ip })
in
Logs.info ~src:t.logsrc
(fun pp -> pp "Sending gratuitous ARP for %a (%a)"
Ipaddr.V4.pp ip Macaddr.pp t.mac) ;
{ t with cache }, (garp, Macaddr.broadcast), pending t ip
let create ?(timeout = 800) ?(retries = 5)
?(logsrc = Logs.Src.create "arp" ~doc:"ARP handler")
?ipaddr
mac =
if timeout <= 0 then
invalid_arg "timeout must be strictly positive" ;
if retries < 0 then
invalid_arg "retries must be positive" ;
let cache = M.empty in
let ip = match ipaddr with None -> Ipaddr.V4.any | Some x -> x in
let t = { cache ; mac ; ip ; timeout ; retries ; epoch = 0 ; logsrc } in
match ipaddr with
| None -> t, None
| Some ip ->
let t, garp, _ = alias t ip in
t, Some garp
let static t ip mac =
let cache = M.add ip (Static (mac, false)) t.cache in
{ t with cache }, pending t ip
let remove t ip =
let cache = M.remove ip t.cache in
{ t with cache }
let in_cache t ip =
match M.find ip t.cache with
| exception Not_found -> None
| Pending _ -> None
| Static (m, _) -> Some m
| Dynamic (m, _) -> Some m
let request t ip =
let target = Macaddr.broadcast in
let request = {
Arp_packet.operation = Arp_packet.Request ;
source_mac = t.mac ; source_ip = t.ip ;
target_mac = target ; target_ip = ip
}
in
request, target
let reply arp m =
let reply = {
Arp_packet.operation = Arp_packet.Reply ;
source_mac = m ; source_ip = arp.Arp_packet.target_ip ;
target_mac = arp.Arp_packet.source_mac ; target_ip = arp.Arp_packet.source_ip ;
} in
reply, arp.Arp_packet.source_mac
let tick t =
let epoch = t.epoch in
let entry k v (cache, acc, r) = match v with
| Dynamic (m, tick) when tick = epoch ->
Logs.debug ~src:t.logsrc
(fun pp -> pp "removing ARP entry %a (mac %a)"
Ipaddr.V4.pp k Macaddr.pp m) ;
M.remove k cache, acc, r
| Dynamic (_, tick) when tick = succ epoch ->
cache, request t k :: acc, r
| Pending (a, retry) when retry = epoch ->
Logs.info ~src:t.logsrc
(fun pp -> pp "ARP timeout after %d retries for %a"
t.retries Ipaddr.V4.pp k) ;
M.remove k cache, acc, a :: r
| Pending _ -> cache, request t k :: acc, r
| _ -> cache, acc, r
in
let cache, outs, r = M.fold entry t.cache (t.cache, [], []) in
{ t with cache ; epoch = succ epoch }, outs, r
let handle_reply t source mac =
let extcache =
let cache = M.add source (Dynamic (mac, t.epoch + t.timeout)) t.cache in
{ t with cache }
in
match M.find source t.cache with
| exception Not_found ->
t, None, None
| Static (_, adv) ->
if adv && Macaddr.compare mac mac0 = 0 then
Logs.info ~src:t.logsrc
(fun pp ->
pp "ignoring gratuitous ARP from %a using my IP address %a"
Macaddr.pp mac Ipaddr.V4.pp source)[@coverage off]
else
Logs.info ~src:t.logsrc
(fun pp ->
pp "ignoring ARP reply for %a (static %sarp entry in cache)"
Ipaddr.V4.pp source (if adv then "advertised " else ""))
[@coverage off] ;
t, None, None
| Dynamic (m, _) ->
if Macaddr.compare mac m <> 0 then
Logs.warn ~src:t.logsrc
(fun pp -> pp "ARP for %a moved from %a to %a"
Ipaddr.V4.pp source
Macaddr.pp m
Macaddr.pp mac) ;
extcache, None, None
| Pending (xs, _) -> extcache, None, Some (mac, xs)
let handle_request t arp =
let dest = arp.Arp_packet.target_ip
and source = arp.Arp_packet.source_ip
in
match M.find dest t.cache with
| exception Not_found ->
Logs.debug ~src:t.logsrc
(fun pp -> pp "ignoring ARP request for %a from %a (mac %a)"
Ipaddr.V4.pp dest
Ipaddr.V4.pp source
Macaddr.pp arp.Arp_packet.source_mac) ;
t, None, None
| Static (m, true) ->
Logs.debug ~src:t.logsrc
(fun pp -> pp "replying to ARP request for %a from %a (mac %a)"
Ipaddr.V4.pp dest
Ipaddr.V4.pp source
Macaddr.pp arp.Arp_packet.source_mac) ;
t, Some (reply arp m), None
| _ ->
Logs.debug ~src:t.logsrc
(fun pp -> pp "ignoring ARP request for %a from %a (mac %a)"
Ipaddr.V4.pp dest
Ipaddr.V4.pp source
Macaddr.pp arp.Arp_packet.source_mac)
[@coverage off] ;
t, None, None
let input t buf =
match Arp_packet.decode buf with
| Error e ->
Logs.info ~src:t.logsrc
(fun pp -> pp "Failed to parse ARP frame %a" Arp_packet.pp_error e) ;
t, None, None
| Ok arp ->
if
Ipaddr.V4.compare arp.Arp_packet.source_ip arp.Arp_packet.target_ip = 0 ||
arp.Arp_packet.operation = Arp_packet.Reply
then
let mac = arp.Arp_packet.source_mac
and source = arp.Arp_packet.source_ip
in
handle_reply t source mac
else (* must be a request *)
handle_request t arp
type 'a qres =
| Mac of Macaddr.t
| Wait of 'a
| RequestWait of (Arp_packet.t * Macaddr.t) * 'a
let query t ip a =
match M.find ip t.cache with
| exception Not_found ->
let a = a None in
let cache = M.add ip (Pending (a, t.epoch + t.retries)) t.cache in
{ t with cache }, RequestWait (request t ip, a)
| Pending (x, r) ->
let a = a (Some x) in
let cache = M.add ip (Pending (a, r)) t.cache in
{ t with cache }, Wait a
| Static (m, _) -> t, Mac m
| Dynamic (m, _) -> t, Mac m
| null | https://raw.githubusercontent.com/mirage/arp/498237d01401ad94011a1703fec831e9cf715973/src/arp_handler.ml | ocaml | must be a request |
type 'a entry =
| Static of Macaddr.t * bool
| Dynamic of Macaddr.t * int
| Pending of 'a * int
module M = Map.Make(Ipaddr.V4)
type 'a t = {
cache : 'a entry M.t ;
mac : Macaddr.t ;
ip : Ipaddr.V4.t ;
timeout : int ;
retries : int ;
epoch : int ;
logsrc : Logs.src
}
let ips t =
M.fold (fun ip entry acc -> match entry with
| Static (_, true) -> ip :: acc
| _ -> acc)
t.cache []
let mac t = t.mac
let[@coverage off] pp_entry now k pp =
function
| Static (m, adv) ->
let adv = if adv then " advertising" else "" in
Format.fprintf pp "%a at %a (static%s)" Ipaddr.V4.pp k Macaddr.pp m adv
| Dynamic (m, t) ->
Format.fprintf pp "%a at %a (timeout in %d)" Ipaddr.V4.pp k
Macaddr.pp m (t - now)
| Pending (_, retries) ->
Format.fprintf pp "%a (incomplete, %d retries left)"
Ipaddr.V4.pp k (retries - now)
let[@coverage off] pp pp t =
Format.fprintf pp "mac %a ip %a entries %d timeout %d retries %d@."
Macaddr.pp t.mac
Ipaddr.V4.pp t.ip
(M.cardinal t.cache)
t.timeout t.retries ;
M.iter (fun k v -> pp_entry t.epoch k pp v ; Format.pp_print_space pp ()) t.cache
let pending t ip =
match M.find ip t.cache with
| exception Not_found -> None
| Pending (a, _) -> Some a
| _ -> None
let mac0 = Macaddr.of_octets_exn (Cstruct.to_string (Cstruct.create 6))
let alias t ip =
let cache = M.add ip (Static (t.mac, true)) t.cache in
see RFC5227 Section 3 why we send out an ARP request
let garp = Arp_packet.({
operation = Request ;
source_mac = t.mac ;
target_mac = mac0 ;
source_ip = ip ; target_ip = ip })
in
Logs.info ~src:t.logsrc
(fun pp -> pp "Sending gratuitous ARP for %a (%a)"
Ipaddr.V4.pp ip Macaddr.pp t.mac) ;
{ t with cache }, (garp, Macaddr.broadcast), pending t ip
let create ?(timeout = 800) ?(retries = 5)
?(logsrc = Logs.Src.create "arp" ~doc:"ARP handler")
?ipaddr
mac =
if timeout <= 0 then
invalid_arg "timeout must be strictly positive" ;
if retries < 0 then
invalid_arg "retries must be positive" ;
let cache = M.empty in
let ip = match ipaddr with None -> Ipaddr.V4.any | Some x -> x in
let t = { cache ; mac ; ip ; timeout ; retries ; epoch = 0 ; logsrc } in
match ipaddr with
| None -> t, None
| Some ip ->
let t, garp, _ = alias t ip in
t, Some garp
let static t ip mac =
let cache = M.add ip (Static (mac, false)) t.cache in
{ t with cache }, pending t ip
let remove t ip =
let cache = M.remove ip t.cache in
{ t with cache }
let in_cache t ip =
match M.find ip t.cache with
| exception Not_found -> None
| Pending _ -> None
| Static (m, _) -> Some m
| Dynamic (m, _) -> Some m
let request t ip =
let target = Macaddr.broadcast in
let request = {
Arp_packet.operation = Arp_packet.Request ;
source_mac = t.mac ; source_ip = t.ip ;
target_mac = target ; target_ip = ip
}
in
request, target
let reply arp m =
let reply = {
Arp_packet.operation = Arp_packet.Reply ;
source_mac = m ; source_ip = arp.Arp_packet.target_ip ;
target_mac = arp.Arp_packet.source_mac ; target_ip = arp.Arp_packet.source_ip ;
} in
reply, arp.Arp_packet.source_mac
let tick t =
let epoch = t.epoch in
let entry k v (cache, acc, r) = match v with
| Dynamic (m, tick) when tick = epoch ->
Logs.debug ~src:t.logsrc
(fun pp -> pp "removing ARP entry %a (mac %a)"
Ipaddr.V4.pp k Macaddr.pp m) ;
M.remove k cache, acc, r
| Dynamic (_, tick) when tick = succ epoch ->
cache, request t k :: acc, r
| Pending (a, retry) when retry = epoch ->
Logs.info ~src:t.logsrc
(fun pp -> pp "ARP timeout after %d retries for %a"
t.retries Ipaddr.V4.pp k) ;
M.remove k cache, acc, a :: r
| Pending _ -> cache, request t k :: acc, r
| _ -> cache, acc, r
in
let cache, outs, r = M.fold entry t.cache (t.cache, [], []) in
{ t with cache ; epoch = succ epoch }, outs, r
let handle_reply t source mac =
let extcache =
let cache = M.add source (Dynamic (mac, t.epoch + t.timeout)) t.cache in
{ t with cache }
in
match M.find source t.cache with
| exception Not_found ->
t, None, None
| Static (_, adv) ->
if adv && Macaddr.compare mac mac0 = 0 then
Logs.info ~src:t.logsrc
(fun pp ->
pp "ignoring gratuitous ARP from %a using my IP address %a"
Macaddr.pp mac Ipaddr.V4.pp source)[@coverage off]
else
Logs.info ~src:t.logsrc
(fun pp ->
pp "ignoring ARP reply for %a (static %sarp entry in cache)"
Ipaddr.V4.pp source (if adv then "advertised " else ""))
[@coverage off] ;
t, None, None
| Dynamic (m, _) ->
if Macaddr.compare mac m <> 0 then
Logs.warn ~src:t.logsrc
(fun pp -> pp "ARP for %a moved from %a to %a"
Ipaddr.V4.pp source
Macaddr.pp m
Macaddr.pp mac) ;
extcache, None, None
| Pending (xs, _) -> extcache, None, Some (mac, xs)
let handle_request t arp =
let dest = arp.Arp_packet.target_ip
and source = arp.Arp_packet.source_ip
in
match M.find dest t.cache with
| exception Not_found ->
Logs.debug ~src:t.logsrc
(fun pp -> pp "ignoring ARP request for %a from %a (mac %a)"
Ipaddr.V4.pp dest
Ipaddr.V4.pp source
Macaddr.pp arp.Arp_packet.source_mac) ;
t, None, None
| Static (m, true) ->
Logs.debug ~src:t.logsrc
(fun pp -> pp "replying to ARP request for %a from %a (mac %a)"
Ipaddr.V4.pp dest
Ipaddr.V4.pp source
Macaddr.pp arp.Arp_packet.source_mac) ;
t, Some (reply arp m), None
| _ ->
Logs.debug ~src:t.logsrc
(fun pp -> pp "ignoring ARP request for %a from %a (mac %a)"
Ipaddr.V4.pp dest
Ipaddr.V4.pp source
Macaddr.pp arp.Arp_packet.source_mac)
[@coverage off] ;
t, None, None
let input t buf =
match Arp_packet.decode buf with
| Error e ->
Logs.info ~src:t.logsrc
(fun pp -> pp "Failed to parse ARP frame %a" Arp_packet.pp_error e) ;
t, None, None
| Ok arp ->
if
Ipaddr.V4.compare arp.Arp_packet.source_ip arp.Arp_packet.target_ip = 0 ||
arp.Arp_packet.operation = Arp_packet.Reply
then
let mac = arp.Arp_packet.source_mac
and source = arp.Arp_packet.source_ip
in
handle_reply t source mac
handle_request t arp
type 'a qres =
| Mac of Macaddr.t
| Wait of 'a
| RequestWait of (Arp_packet.t * Macaddr.t) * 'a
let query t ip a =
match M.find ip t.cache with
| exception Not_found ->
let a = a None in
let cache = M.add ip (Pending (a, t.epoch + t.retries)) t.cache in
{ t with cache }, RequestWait (request t ip, a)
| Pending (x, r) ->
let a = a (Some x) in
let cache = M.add ip (Pending (a, r)) t.cache in
{ t with cache }, Wait a
| Static (m, _) -> t, Mac m
| Dynamic (m, _) -> t, Mac m
|
f7f92fe8d5c5910d202e2fe346aad09f4a3372f62554717db80b0989d54791da | offby1/rudybot | clearenv.rkt | #lang racket
(require ffi/unsafe)
(provide clearenv)
(module+ test (require rackunit rackunit/text-ui))
The ' clearenv ' function does n't exist on some systems ( notably
;; OS X), so we use 'unsetenv' in a loop instead.
(define (clearenv)
(let ([unsetenv (get-ffi-obj 'unsetenv #f (_fun _bytes -> _int))])
(let loop ()
(match
I 've seen this ptr - ref fail , too ( on
;; Macbook); no idea why.
(ptr-ref (get-ffi-obj 'environ #f _pointer) _bytes)
[(regexp #rx"^(.*?)=(.*)$" (list _ k v))
(unsetenv k)
(loop)]
[#f (void)]))))
(module+ test
(define hmm-tests
(test-suite
"loop"
(test-case
"dunno"
(clearenv)
(for ([v '("FOO" "HOME" "PATH" "EDITOR" "SNICKERDOODLE")])
(check-false (getenv v) v)))))
(run-tests hmm-tests))
| null | https://raw.githubusercontent.com/offby1/rudybot/74773ce9c1224813ee963f4d5d8a7748197f6963/clearenv.rkt | racket | OS X), so we use 'unsetenv' in a loop instead.
Macbook); no idea why. | #lang racket
(require ffi/unsafe)
(provide clearenv)
(module+ test (require rackunit rackunit/text-ui))
The ' clearenv ' function does n't exist on some systems ( notably
(define (clearenv)
(let ([unsetenv (get-ffi-obj 'unsetenv #f (_fun _bytes -> _int))])
(let loop ()
(match
I 've seen this ptr - ref fail , too ( on
(ptr-ref (get-ffi-obj 'environ #f _pointer) _bytes)
[(regexp #rx"^(.*?)=(.*)$" (list _ k v))
(unsetenv k)
(loop)]
[#f (void)]))))
(module+ test
(define hmm-tests
(test-suite
"loop"
(test-case
"dunno"
(clearenv)
(for ([v '("FOO" "HOME" "PATH" "EDITOR" "SNICKERDOODLE")])
(check-false (getenv v) v)))))
(run-tests hmm-tests))
|
dd07e0f9977b0c3bdd60d9dba0cba4ff6c8e96131a23c2130c61c3a5206d0e2c | lyrm/ocaml-httpadapter | method.ml | { { { Copyright ( C ) < 2020 > < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
} } }
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
}}}*)
module M = Httpaf.Method
type t =
[ `GET
| `HEAD
| `POST
| `PUT
| `DELETE
| `CONNECT
| `OPTIONS
| `TRACE
| `Other of string
| `PATCH ]
let to_local : t -> M.t = function
| `GET -> `GET
| `HEAD -> `HEAD
| `POST -> `POST
| `PUT -> `PUT
| `DELETE -> `DELETE
| `CONNECT -> `CONNECT
| `OPTIONS -> `OPTIONS
| `TRACE -> `TRACE
| `Other str -> `Other str
| `PATCH -> `Other "patch"
let from_local : M.t -> t = function
| `GET -> `GET
| `HEAD -> `HEAD
| `POST -> `POST
| `PUT -> `PUT
| `DELETE -> `DELETE
| `CONNECT -> `CONNECT
| `OPTIONS -> `OPTIONS
| `TRACE -> `TRACE
| `Other "patch" -> `PATCH
| `Other str -> `Other str
let to_string meth = to_local meth |> M.to_string
let compare a b = compare (to_string a) (to_string b)
| null | https://raw.githubusercontent.com/lyrm/ocaml-httpadapter/01926ba6a1e3ab607fc8a33a40fb13682b6711a5/src-httpaf/method.ml | ocaml | { { { Copyright ( C ) < 2020 > < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
} } }
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
}}}*)
module M = Httpaf.Method
type t =
[ `GET
| `HEAD
| `POST
| `PUT
| `DELETE
| `CONNECT
| `OPTIONS
| `TRACE
| `Other of string
| `PATCH ]
let to_local : t -> M.t = function
| `GET -> `GET
| `HEAD -> `HEAD
| `POST -> `POST
| `PUT -> `PUT
| `DELETE -> `DELETE
| `CONNECT -> `CONNECT
| `OPTIONS -> `OPTIONS
| `TRACE -> `TRACE
| `Other str -> `Other str
| `PATCH -> `Other "patch"
let from_local : M.t -> t = function
| `GET -> `GET
| `HEAD -> `HEAD
| `POST -> `POST
| `PUT -> `PUT
| `DELETE -> `DELETE
| `CONNECT -> `CONNECT
| `OPTIONS -> `OPTIONS
| `TRACE -> `TRACE
| `Other "patch" -> `PATCH
| `Other str -> `Other str
let to_string meth = to_local meth |> M.to_string
let compare a b = compare (to_string a) (to_string b)
| |
e3e1df0abd537c2bed30dc799ca4b0872a5bd65ea73f0181181e02b82ce7fac2 | lingnand/VIMonad | Gnome.hs | # OPTIONS_GHC -fno - warn - missing - signatures #
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Config.Gnome
Copyright : ( c ) < >
-- License : BSD
--
Maintainer : < >
-- Stability : unstable
-- Portability : unportable
--
-- This module provides a config suitable for use with the GNOME desktop
-- environment.
module XMonad.Config.Gnome (
-- * Usage
-- $usage
gnomeConfig,
gnomeRun,
gnomeRegister
) where
import XMonad
import XMonad.Config.Desktop
import XMonad.Util.Run (safeSpawn)
import qualified Data.Map as M
import System.Environment (getEnvironment)
-- $usage
-- To use this module, start with the following @~\/.xmonad\/xmonad.hs@:
--
> import XMonad
> import XMonad . Config . Gnome
-- >
> main = xmonad gnomeConfig
--
-- For examples of how to further customize @gnomeConfig@ see "XMonad.Config.Desktop".
gnomeConfig = desktopConfig
{ terminal = "gnome-terminal"
, keys = gnomeKeys <+> keys desktopConfig
, startupHook = gnomeRegister >> startupHook desktopConfig }
gnomeKeys (XConfig {modMask = modm}) = M.fromList $
[ ((modm, xK_p), gnomeRun)
, ((modm .|. shiftMask, xK_q), spawn "gnome-session-save --kill") ]
-- | Launch the "Run Application" dialog. gnome-panel must be running for this
-- to work.
gnomeRun :: X ()
gnomeRun = withDisplay $ \dpy -> do
rw <- asks theRoot
gnome_panel <- getAtom "_GNOME_PANEL_ACTION"
panel_run <- getAtom "_GNOME_PANEL_ACTION_RUN_DIALOG"
io $ allocaXEvent $ \e -> do
setEventType e clientMessage
setClientMessageEvent e rw gnome_panel 32 panel_run 0
sendEvent dpy rw False structureNotifyMask e
sync dpy False
-- | Register xmonad with gnome. 'dbus-send' must be in the $PATH with which
xmonad is started .
--
-- This action reduces a delay on startup only only if you have configured
-- gnome-session>=2.26: to start xmonad with a command as such:
--
> gconftool-2 -s /desktop / gnome / session / required_components / windowmanager xmonad --type string
gnomeRegister :: MonadIO m => m ()
gnomeRegister = io $ do
x <- lookup "DESKTOP_AUTOSTART_ID" `fmap` getEnvironment
whenJust x $ \sessionId -> safeSpawn "dbus-send"
["--session"
,"--print-reply=literal"
,"--dest=org.gnome.SessionManager"
,"/org/gnome/SessionManager"
,"org.gnome.SessionManager.RegisterClient"
,"string:xmonad"
,"string:"++sessionId]
| null | https://raw.githubusercontent.com/lingnand/VIMonad/048e419fc4ef57a5235dbaeef8890faf6956b574/XMonadContrib/XMonad/Config/Gnome.hs | haskell | ---------------------------------------------------------------------------
|
Module : XMonad.Config.Gnome
License : BSD
Stability : unstable
Portability : unportable
This module provides a config suitable for use with the GNOME desktop
environment.
* Usage
$usage
$usage
To use this module, start with the following @~\/.xmonad\/xmonad.hs@:
>
For examples of how to further customize @gnomeConfig@ see "XMonad.Config.Desktop".
| Launch the "Run Application" dialog. gnome-panel must be running for this
to work.
| Register xmonad with gnome. 'dbus-send' must be in the $PATH with which
This action reduces a delay on startup only only if you have configured
gnome-session>=2.26: to start xmonad with a command as such:
type string | # OPTIONS_GHC -fno - warn - missing - signatures #
Copyright : ( c ) < >
Maintainer : < >
module XMonad.Config.Gnome (
gnomeConfig,
gnomeRun,
gnomeRegister
) where
import XMonad
import XMonad.Config.Desktop
import XMonad.Util.Run (safeSpawn)
import qualified Data.Map as M
import System.Environment (getEnvironment)
> import XMonad
> import XMonad . Config . Gnome
> main = xmonad gnomeConfig
gnomeConfig = desktopConfig
{ terminal = "gnome-terminal"
, keys = gnomeKeys <+> keys desktopConfig
, startupHook = gnomeRegister >> startupHook desktopConfig }
gnomeKeys (XConfig {modMask = modm}) = M.fromList $
[ ((modm, xK_p), gnomeRun)
, ((modm .|. shiftMask, xK_q), spawn "gnome-session-save --kill") ]
gnomeRun :: X ()
gnomeRun = withDisplay $ \dpy -> do
rw <- asks theRoot
gnome_panel <- getAtom "_GNOME_PANEL_ACTION"
panel_run <- getAtom "_GNOME_PANEL_ACTION_RUN_DIALOG"
io $ allocaXEvent $ \e -> do
setEventType e clientMessage
setClientMessageEvent e rw gnome_panel 32 panel_run 0
sendEvent dpy rw False structureNotifyMask e
sync dpy False
xmonad is started .
gnomeRegister :: MonadIO m => m ()
gnomeRegister = io $ do
x <- lookup "DESKTOP_AUTOSTART_ID" `fmap` getEnvironment
whenJust x $ \sessionId -> safeSpawn "dbus-send"
["--session"
,"--print-reply=literal"
,"--dest=org.gnome.SessionManager"
,"/org/gnome/SessionManager"
,"org.gnome.SessionManager.RegisterClient"
,"string:xmonad"
,"string:"++sessionId]
|
721d2afcacb5f22bdd313ab2a8cf1f6a6d86efc611aa85c15b860e6379ca646c | r0man/inflections-clj | project.clj | (defproject inflections "0.14.2-SNAPSHOT"
:description "Rails-like inflections for Clojure(Script)."
:url "-clj"
:author "r0man"
:min-lein-version "2.0.0"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[noencore "0.3.7"]
[org.clojure/clojure "1.10.0"]
[org.clojure/clojurescript "1.10.439" :scope "provided"]]
:aliases {"ci" ["do"
["test"]
["doo" "node" "none" "once"]
["doo" "node" "advanced" "once"]
["lint"]]
"lint" ["do" ["eastwood"]]}
:cljsbuild {:builds [{:id "advanced"
:compiler
{:main inflections.test
:optimizations :none
:output-dir "target/advanced"
:output-to "target/advanced.js"
:parallel-build true
:pretty-print true
:target :nodejs
:verbose false}
:source-paths ["src" "test"]}
{:id "none"
:compiler
{:main inflections.test
:optimizations :advanced
:output-dir "target/none"
:output-to "target/none.js"
:target :nodejs}
:source-paths ["src" "test"]}]}
:deploy-repositories [["releases" :clojars]]
:profiles {:dev {:dependencies [[org.clojure/clojurescript "1.11.54"]]
:plugins [[jonase/eastwood "1.2.3"]
[lein-cljsbuild "1.1.8"]
[lein-difftest "2.0.0"]
[lein-doo "0.1.11"]]}})
| null | https://raw.githubusercontent.com/r0man/inflections-clj/99f8984502fb8f484607fd0aaeb1dcae8afe35c4/project.clj | clojure | (defproject inflections "0.14.2-SNAPSHOT"
:description "Rails-like inflections for Clojure(Script)."
:url "-clj"
:author "r0man"
:min-lein-version "2.0.0"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[noencore "0.3.7"]
[org.clojure/clojure "1.10.0"]
[org.clojure/clojurescript "1.10.439" :scope "provided"]]
:aliases {"ci" ["do"
["test"]
["doo" "node" "none" "once"]
["doo" "node" "advanced" "once"]
["lint"]]
"lint" ["do" ["eastwood"]]}
:cljsbuild {:builds [{:id "advanced"
:compiler
{:main inflections.test
:optimizations :none
:output-dir "target/advanced"
:output-to "target/advanced.js"
:parallel-build true
:pretty-print true
:target :nodejs
:verbose false}
:source-paths ["src" "test"]}
{:id "none"
:compiler
{:main inflections.test
:optimizations :advanced
:output-dir "target/none"
:output-to "target/none.js"
:target :nodejs}
:source-paths ["src" "test"]}]}
:deploy-repositories [["releases" :clojars]]
:profiles {:dev {:dependencies [[org.clojure/clojurescript "1.11.54"]]
:plugins [[jonase/eastwood "1.2.3"]
[lein-cljsbuild "1.1.8"]
[lein-difftest "2.0.0"]
[lein-doo "0.1.11"]]}})
| |
2d62a5a9560a68cb7901ec74646bcf31b3f14c283db6e1b47c0d684f3dc431c6 | ocaml-multicore/ocaml-tsan | listLabels.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* NOTE:
If this file is listLabels.mli, run tools/sync_stdlib_docs after editing it
to generate list.mli.
If this file is list.mli, do not edit it directly -- edit
listLabels.mli instead.
*)
* List operations .
Some functions are flagged as not tail - recursive . A tail - recursive
function uses constant stack space , while a non - tail - recursive function
uses stack space proportional to the length of its list argument , which
can be a problem with very long lists . When the function takes several
list arguments , an approximate formula giving stack usage ( in some
unspecified constant unit ) is shown in parentheses .
The above considerations can usually be ignored if your lists are not
longer than about 10000 elements .
The labeled version of this module can be used as described in the
{ ! StdLabels } module .
Some functions are flagged as not tail-recursive. A tail-recursive
function uses constant stack space, while a non-tail-recursive function
uses stack space proportional to the length of its list argument, which
can be a problem with very long lists. When the function takes several
list arguments, an approximate formula giving stack usage (in some
unspecified constant unit) is shown in parentheses.
The above considerations can usually be ignored if your lists are not
longer than about 10000 elements.
The labeled version of this module can be used as described in the
{!StdLabels} module.
*)
type 'a t = 'a list = [] | (::) of 'a * 'a list (**)
(** An alias for the type of lists. *)
val length : 'a list -> int
(** Return the length (number of elements) of the given list. *)
val compare_lengths : 'a list -> 'b list -> int
* Compare the lengths of two lists . [ compare_lengths l1 l2 ] is
equivalent to [ compare ( length l1 ) ( length l2 ) ] , except that
the computation stops after reaching the end of the shortest list .
@since 4.05
equivalent to [compare (length l1) (length l2)], except that
the computation stops after reaching the end of the shortest list.
@since 4.05
*)
val compare_length_with : 'a list -> len:int -> int
* Compare the length of a list to an integer . [ compare_length_with l len ] is
equivalent to [ compare ( length l ) len ] , except that the computation stops
after at most [ len ] iterations on the list .
@since 4.05
equivalent to [compare (length l) len], except that the computation stops
after at most [len] iterations on the list.
@since 4.05
*)
val is_empty : 'a list -> bool
* [ is_empty l ] is true if and only if [ l ] has no elements . It is equivalent to
[ compare_length_with l 0 = 0 ] .
@since 5.1
[compare_length_with l 0 = 0].
@since 5.1
*)
val cons : 'a -> 'a list -> 'a list
* [ cons x xs ] is [ x : : xs ]
@since 4.03 ( 4.05 in ListLabels )
@since 4.03 (4.05 in ListLabels)
*)
val hd : 'a list -> 'a
* Return the first element of the given list .
@raise Failure if the list is empty .
@raise Failure if the list is empty.
*)
val tl : 'a list -> 'a list
* Return the given list without its first element .
@raise Failure if the list is empty .
@raise Failure if the list is empty.
*)
val nth : 'a list -> int -> 'a
* Return the [ n]-th element of the given list .
The first element ( head of the list ) is at position 0 .
@raise Failure if the list is too short .
@raise Invalid_argument if [ n ] is negative .
The first element (head of the list) is at position 0.
@raise Failure if the list is too short.
@raise Invalid_argument if [n] is negative.
*)
val nth_opt : 'a list -> int -> 'a option
* Return the [ n]-th element of the given list .
The first element ( head of the list ) is at position 0 .
Return [ None ] if the list is too short .
@raise Invalid_argument if [ n ] is negative .
@since 4.05
The first element (head of the list) is at position 0.
Return [None] if the list is too short.
@raise Invalid_argument if [n] is negative.
@since 4.05
*)
val rev : 'a list -> 'a list
(** List reversal. *)
val init : len:int -> f:(int -> 'a) -> 'a list
* [ init ~len ~f ] is [ [ f 0 ; f 1 ; ... ; f ( len-1 ) ] ] , evaluated left to right .
@raise Invalid_argument if ] .
@since 4.06
@raise Invalid_argument if [len < 0].
@since 4.06
*)
val append : 'a list -> 'a list -> 'a list
* two lists . Same function as the infix operator [ @ ] .
Not tail - recursive ( length of the first argument ) . The [ @ ]
operator is not tail - recursive either .
Not tail-recursive (length of the first argument). The [@]
operator is not tail-recursive either.
*)
val rev_append : 'a list -> 'a list -> 'a list
(** [rev_append l1 l2] reverses [l1] and concatenates it with [l2].
This is equivalent to [(]{!rev}[ l1) @ l2], but [rev_append] is
tail-recursive and more efficient.
*)
val concat : 'a list list -> 'a list
* a list of lists . The elements of the argument are all
concatenated together ( in the same order ) to give the result .
Not tail - recursive
( length of the argument + length of the longest sub - list ) .
concatenated together (in the same order) to give the result.
Not tail-recursive
(length of the argument + length of the longest sub-list).
*)
val flatten : 'a list list -> 'a list
(** Same as {!concat}. Not tail-recursive
(length of the argument + length of the longest sub-list).
*)
* { 1 Comparison }
val equal : eq:('a -> 'a -> bool) -> 'a list -> 'a list -> bool
* [ equal eq [ a1 ; ... ; an ] [ b1 ; .. ; bm ] ] holds when
the two input lists have the same length , and for each
pair of elements [ ai ] , [ bi ] at the same position we have
[ eq ai bi ] .
Note : the [ eq ] function may be called even if the
lists have different length . If you know your equality
function is costly , you may want to check { ! compare_lengths }
first .
@since 4.12
the two input lists have the same length, and for each
pair of elements [ai], [bi] at the same position we have
[eq ai bi].
Note: the [eq] function may be called even if the
lists have different length. If you know your equality
function is costly, you may want to check {!compare_lengths}
first.
@since 4.12
*)
val compare : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> int
* [ compare cmp [ a1 ; ... ; an ] [ b1 ; ... ; bm ] ] performs
a lexicographic comparison of the two input lists ,
using the same [ ' a - > ' a - > int ] interface as { ! Stdlib.compare } :
- [ a1 : : l1 ] is smaller than [ a2 : : l2 ] ( negative result )
if [ a1 ] is smaller than [ a2 ] , or if they are equal ( 0 result )
and [ l1 ] is smaller than [ l2 ]
- the empty list [ [ ] ] is strictly smaller than non - empty lists
Note : the [ cmp ] function will be called even if the lists have
different lengths .
@since 4.12
a lexicographic comparison of the two input lists,
using the same ['a -> 'a -> int] interface as {!Stdlib.compare}:
- [a1 :: l1] is smaller than [a2 :: l2] (negative result)
if [a1] is smaller than [a2], or if they are equal (0 result)
and [l1] is smaller than [l2]
- the empty list [[]] is strictly smaller than non-empty lists
Note: the [cmp] function will be called even if the lists have
different lengths.
@since 4.12
*)
(** {1 Iterators} *)
val iter : f:('a -> unit) -> 'a list -> unit
* [ iter ~f [ a1 ; ... ; an ] ] applies function [ f ] in turn to
[ [ a1 ; ... ; an ] ] . It is equivalent to
[ f a1 ; f a2 ; ... ; f an ] .
[[a1; ...; an]]. It is equivalent to
[f a1; f a2; ...; f an].
*)
val iteri : f:(int -> 'a -> unit) -> 'a list -> unit
* Same as { ! iter } , but the function is applied to the index of
the element as first argument ( counting from 0 ) , and the element
itself as second argument .
@since 4.00
the element as first argument (counting from 0), and the element
itself as second argument.
@since 4.00
*)
val map : f:('a -> 'b) -> 'a list -> 'b list
(** [map ~f [a1; ...; an]] applies function [f] to [a1, ..., an],
and builds the list [[f a1; ...; f an]]
with the results returned by [f].
*)
val mapi : f:(int -> 'a -> 'b) -> 'a list -> 'b list
* Same as { ! map } , but the function is applied to the index of
the element as first argument ( counting from 0 ) , and the element
itself as second argument .
@since 4.00
the element as first argument (counting from 0), and the element
itself as second argument.
@since 4.00
*)
val rev_map : f:('a -> 'b) -> 'a list -> 'b list
(** [rev_map ~f l] gives the same result as
{!rev}[ (]{!map}[ f l)], but is more efficient.
*)
val filter_map : f:('a -> 'b option) -> 'a list -> 'b list
* [ filter_map ~f l ] applies [ f ] to every element of [ l ] , filters
out the [ None ] elements and returns the list of the arguments of
the [ Some ] elements .
@since 4.08
out the [None] elements and returns the list of the arguments of
the [Some] elements.
@since 4.08
*)
val concat_map : f:('a -> 'b list) -> 'a list -> 'b list
* [ concat_map ~f l ] gives the same result as
{ ! concat } [ ( ] { ! map } [ f l ) ] . Tail - recursive .
@since 4.10
{!concat}[ (]{!map}[ f l)]. Tail-recursive.
@since 4.10
*)
val fold_left_map :
f:('a -> 'b -> 'a * 'c) -> init:'a -> 'b list -> 'a * 'c list
* [ fold_left_map ] is a combination of [ fold_left ] and [ map ] that threads an
accumulator through calls to [ f ] .
@since 4.11
accumulator through calls to [f].
@since 4.11
*)
val fold_left : f:('a -> 'b -> 'a) -> init:'a -> 'b list -> 'a
(** [fold_left ~f ~init [b1; ...; bn]] is
[f (... (f (f init b1) b2) ...) bn].
*)
val fold_right : f:('a -> 'b -> 'b) -> 'a list -> init:'b -> 'b
(** [fold_right ~f [a1; ...; an] ~init] is
[f a1 (f a2 (... (f an init) ...))]. Not tail-recursive.
*)
* { 1 Iterators on two lists }
val iter2 : f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit
* [ iter2 ~f [ a1 ; ... ; an ] [ b1 ; ... ; bn ] ] calls in turn
[ f a1 b1 ; ... ; f an bn ] .
@raise Invalid_argument if the two lists are determined
to have different lengths .
[f a1 b1; ...; f an bn].
@raise Invalid_argument if the two lists are determined
to have different lengths.
*)
val map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
* [ map2 ~f [ a1 ; ... ; an ] [ b1 ; ... ; bn ] ] is
[ [ f a1 b1 ; ... ; f an bn ] ] .
@raise Invalid_argument if the two lists are determined
to have different lengths .
[[f a1 b1; ...; f an bn]].
@raise Invalid_argument if the two lists are determined
to have different lengths.
*)
val rev_map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
(** [rev_map2 ~f l1 l2] gives the same result as
{!rev}[ (]{!map2}[ f l1 l2)], but is more efficient.
*)
val fold_left2 :
f:('a -> 'b -> 'c -> 'a) -> init:'a -> 'b list -> 'c list -> 'a
* [ ~f ~init [ a1 ; ... ; an ] [ b1 ; ... ; bn ] ] is
[ f ( ... ( f ( f init a1 b1 ) a2 b2 ) ... ) an bn ] .
@raise Invalid_argument if the two lists are determined
to have different lengths .
[f (... (f (f init a1 b1) a2 b2) ...) an bn].
@raise Invalid_argument if the two lists are determined
to have different lengths.
*)
val fold_right2 :
f:('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> init:'c -> 'c
* [ fold_right2 ~f [ a1 ; ... ; an ] [ b1 ; ... ; bn ] ~init ] is
[ f a1 b1 ( f a2 b2 ( ... ( f an bn init ) ... ) ) ] .
@raise Invalid_argument if the two lists are determined
to have different lengths . Not tail - recursive .
[f a1 b1 (f a2 b2 (... (f an bn init) ...))].
@raise Invalid_argument if the two lists are determined
to have different lengths. Not tail-recursive.
*)
* { 1 List scanning }
val for_all : f:('a -> bool) -> 'a list -> bool
* [ for_all ~f [ a1 ; ... ; an ] ] checks if all elements of the list
satisfy the predicate [ f ] . That is , it returns
[ ( f a1 ) & & ( f a2 ) & & ... & & ( f an ) ] for a non - empty list and
[ true ] if the list is empty .
satisfy the predicate [f]. That is, it returns
[(f a1) && (f a2) && ... && (f an)] for a non-empty list and
[true] if the list is empty.
*)
val exists : f:('a -> bool) -> 'a list -> bool
* [ exists ~f [ a1 ; ... ; an ] ] checks if at least one element of
the list satisfies the predicate [ f ] . That is , it returns
[ ( f a1 ) || ( f a2 ) || ... || ( f an ) ] for a non - empty list and
[ false ] if the list is empty .
the list satisfies the predicate [f]. That is, it returns
[(f a1) || (f a2) || ... || (f an)] for a non-empty list and
[false] if the list is empty.
*)
val for_all2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool
* Same as { ! for_all } , but for a two - argument predicate .
@raise Invalid_argument if the two lists are determined
to have different lengths .
@raise Invalid_argument if the two lists are determined
to have different lengths.
*)
val exists2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool
* Same as { ! exists } , but for a two - argument predicate .
@raise Invalid_argument if the two lists are determined
to have different lengths .
@raise Invalid_argument if the two lists are determined
to have different lengths.
*)
val mem : 'a -> set:'a list -> bool
(** [mem a ~set] is true if and only if [a] is equal
to an element of [set].
*)
val memq : 'a -> set:'a list -> bool
(** Same as {!mem}, but uses physical equality instead of structural
equality to compare list elements.
*)
* { 1 List searching }
val find : f:('a -> bool) -> 'a list -> 'a
* [ find ~f l ] returns the first element of the list [ l ]
that satisfies the predicate [ f ] .
@raise Not_found if there is no value that satisfies [ f ] in the
list [ l ] .
that satisfies the predicate [f].
@raise Not_found if there is no value that satisfies [f] in the
list [l].
*)
val find_opt : f:('a -> bool) -> 'a list -> 'a option
* [ find ~f l ] returns the first element of the list [ l ]
that satisfies the predicate [ f ] .
Returns [ None ] if there is no value that satisfies [ f ] in the
list [ l ] .
@since 4.05
that satisfies the predicate [f].
Returns [None] if there is no value that satisfies [f] in the
list [l].
@since 4.05
*)
val find_map : f:('a -> 'b option) -> 'a list -> 'b option
* [ find_map ~f l ] applies [ f ] to the elements of [ l ] in order ,
and returns the first result of the form [ Some v ] , or [ None ]
if none exist .
@since 4.10
and returns the first result of the form [Some v], or [None]
if none exist.
@since 4.10
*)
val filter : f:('a -> bool) -> 'a list -> 'a list
(** [filter ~f l] returns all the elements of the list [l]
that satisfy the predicate [f]. The order of the elements
in the input list is preserved.
*)
val find_all : f:('a -> bool) -> 'a list -> 'a list
(** [find_all] is another name for {!filter}.
*)
val filteri : f:(int -> 'a -> bool) -> 'a list -> 'a list
* Same as { ! filter } , but the predicate is applied to the index of
the element as first argument ( counting from 0 ) , and the element
itself as second argument .
@since 4.11
the element as first argument (counting from 0), and the element
itself as second argument.
@since 4.11
*)
val partition : f:('a -> bool) -> 'a list -> 'a list * 'a list
(** [partition ~f l] returns a pair of lists [(l1, l2)], where
[l1] is the list of all the elements of [l] that
satisfy the predicate [f], and [l2] is the list of all the
elements of [l] that do not satisfy [f].
The order of the elements in the input list is preserved.
*)
val partition_map : f:('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list
* [ partition_map f l ] returns a pair of lists [ ( l1 , l2 ) ] such that ,
for each element [ x ] of the input list [ l ] :
- if [ f x ] is [ Left y1 ] , then [ y1 ] is in [ l1 ] , and
- if [ f x ] is [ Right y2 ] , then [ y2 ] is in [ l2 ] .
The output elements are included in [ l1 ] and [ l2 ] in the same
relative order as the corresponding input elements in [ l ] .
In particular , [ partition_map ( fun x - > if f x then Left x else Right x ) l ]
is equivalent to [ partition f l ] .
@since 4.12
for each element [x] of the input list [l]:
- if [f x] is [Left y1], then [y1] is in [l1], and
- if [f x] is [Right y2], then [y2] is in [l2].
The output elements are included in [l1] and [l2] in the same
relative order as the corresponding input elements in [l].
In particular, [partition_map (fun x -> if f x then Left x else Right x) l]
is equivalent to [partition f l].
@since 4.12
*)
* { 1 Association lists }
val assoc : 'a -> ('a * 'b) list -> 'b
(** [assoc a l] returns the value associated with key [a] in the list of
pairs [l]. That is,
[assoc a [ ...; (a,b); ...] = b]
if [(a,b)] is the leftmost binding of [a] in list [l].
@raise Not_found if there is no value associated with [a] in the
list [l].
*)
val assoc_opt : 'a -> ('a * 'b) list -> 'b option
* [ assoc_opt a l ] returns the value associated with key [ a ] in the list of
pairs [ l ] . That is ,
[ a [ ... ; ( a , b ) ; ... ] = Some b ]
if [ ( a , b ) ] is the leftmost binding of [ a ] in list [ l ] .
Returns [ None ] if there is no value associated with [ a ] in the
list [ l ] .
@since 4.05
pairs [l]. That is,
[assoc_opt a [ ...; (a,b); ...] = Some b]
if [(a,b)] is the leftmost binding of [a] in list [l].
Returns [None] if there is no value associated with [a] in the
list [l].
@since 4.05
*)
val assq : 'a -> ('a * 'b) list -> 'b
(** Same as {!assoc}, but uses physical equality instead of
structural equality to compare keys.
*)
val assq_opt : 'a -> ('a * 'b) list -> 'b option
* Same as { ! } , but uses physical equality instead of
structural equality to compare keys .
@since 4.05
structural equality to compare keys.
@since 4.05
*)
val mem_assoc : 'a -> map:('a * 'b) list -> bool
(** Same as {!assoc}, but simply return [true] if a binding exists,
and [false] if no bindings exist for the given key.
*)
val mem_assq : 'a -> map:('a * 'b) list -> bool
* Same as { ! , but uses physical equality instead of
structural equality to compare keys .
structural equality to compare keys.
*)
val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list
* [ remove_assoc a l ] returns the list of
pairs [ l ] without the first pair with key [ a ] , if any .
Not tail - recursive .
pairs [l] without the first pair with key [a], if any.
Not tail-recursive.
*)
val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list
* Same as { ! , but uses physical equality instead
of structural equality to compare keys . Not tail - recursive .
of structural equality to compare keys. Not tail-recursive.
*)
* { 1 Lists of pairs }
val split : ('a * 'b) list -> 'a list * 'b list
* Transform a list of pairs into a pair of lists :
[ split [ ( a1,b1 ) ; ... ; ( an , bn ) ] ] is [ ( [ a1 ; ... ; an ] , [ b1 ; ... ; bn ] ) ] .
Not tail - recursive .
[split [(a1,b1); ...; (an,bn)]] is [([a1; ...; an], [b1; ...; bn])].
Not tail-recursive.
*)
val combine : 'a list -> 'b list -> ('a * 'b) list
* Transform a pair of lists into a list of pairs :
[ combine [ a1 ; ... ; an ] [ b1 ; ... ; bn ] ] is
[ [ ( a1,b1 ) ; ... ; ( an , bn ) ] ] .
@raise Invalid_argument if the two lists
have different lengths . Not tail - recursive .
[combine [a1; ...; an] [b1; ...; bn]] is
[[(a1,b1); ...; (an,bn)]].
@raise Invalid_argument if the two lists
have different lengths. Not tail-recursive.
*)
(** {1 Sorting} *)
val sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
* Sort a list in increasing order according to a comparison
function . The comparison function must return 0 if its arguments
compare as equal , a positive integer if the first is greater ,
and a negative integer if the first is smaller ( see Array.sort for
a complete specification ) . For example ,
{ ! Stdlib.compare } is a suitable comparison function .
The resulting list is sorted in increasing order .
{ ! sort } is guaranteed to run in constant heap space
( in addition to the size of the result list ) and logarithmic
stack space .
The current implementation uses Merge Sort . It runs in constant
heap space and logarithmic stack space .
function. The comparison function must return 0 if its arguments
compare as equal, a positive integer if the first is greater,
and a negative integer if the first is smaller (see Array.sort for
a complete specification). For example,
{!Stdlib.compare} is a suitable comparison function.
The resulting list is sorted in increasing order.
{!sort} is guaranteed to run in constant heap space
(in addition to the size of the result list) and logarithmic
stack space.
The current implementation uses Merge Sort. It runs in constant
heap space and logarithmic stack space.
*)
val stable_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
(** Same as {!sort}, but the sorting algorithm is guaranteed to
be stable (i.e. elements that compare equal are kept in their
original order).
The current implementation uses Merge Sort. It runs in constant
heap space and logarithmic stack space.
*)
val fast_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
* Same as { ! sort } or { ! } , whichever is
faster on typical input .
faster on typical input.
*)
val sort_uniq : cmp:('a -> 'a -> int) -> 'a list -> 'a list
* Same as { ! sort } , but also remove duplicates .
@since 4.02 ( 4.03 in ListLabels )
@since 4.02 (4.03 in ListLabels)
*)
val merge : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> 'a list
* Merge two lists :
Assuming that [ l1 ] and [ l2 ] are sorted according to the
comparison function [ cmp ] , [ merge ~cmp l1 l2 ] will return a
sorted list containing all the elements of [ l1 ] and [ l2 ] .
If several elements compare equal , the elements of [ l1 ] will be
before the elements of [ l2 ] .
Not tail - recursive ( sum of the lengths of the arguments ) .
Assuming that [l1] and [l2] are sorted according to the
comparison function [cmp], [merge ~cmp l1 l2] will return a
sorted list containing all the elements of [l1] and [l2].
If several elements compare equal, the elements of [l1] will be
before the elements of [l2].
Not tail-recursive (sum of the lengths of the arguments).
*)
* { 1 Lists and Sequences }
val to_seq : 'a list -> 'a Seq.t
* Iterate on the list .
@since 4.07
@since 4.07
*)
val of_seq : 'a Seq.t -> 'a list
* Create a list from a sequence .
@since 4.07
@since 4.07
*)
| null | https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/ae9c1502103845550162a49fcd3f76276cdfa866/stdlib/listLabels.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
NOTE:
If this file is listLabels.mli, run tools/sync_stdlib_docs after editing it
to generate list.mli.
If this file is list.mli, do not edit it directly -- edit
listLabels.mli instead.
* An alias for the type of lists.
* Return the length (number of elements) of the given list.
* List reversal.
* [rev_append l1 l2] reverses [l1] and concatenates it with [l2].
This is equivalent to [(]{!rev}[ l1) @ l2], but [rev_append] is
tail-recursive and more efficient.
* Same as {!concat}. Not tail-recursive
(length of the argument + length of the longest sub-list).
* {1 Iterators}
* [map ~f [a1; ...; an]] applies function [f] to [a1, ..., an],
and builds the list [[f a1; ...; f an]]
with the results returned by [f].
* [rev_map ~f l] gives the same result as
{!rev}[ (]{!map}[ f l)], but is more efficient.
* [fold_left ~f ~init [b1; ...; bn]] is
[f (... (f (f init b1) b2) ...) bn].
* [fold_right ~f [a1; ...; an] ~init] is
[f a1 (f a2 (... (f an init) ...))]. Not tail-recursive.
* [rev_map2 ~f l1 l2] gives the same result as
{!rev}[ (]{!map2}[ f l1 l2)], but is more efficient.
* [mem a ~set] is true if and only if [a] is equal
to an element of [set].
* Same as {!mem}, but uses physical equality instead of structural
equality to compare list elements.
* [filter ~f l] returns all the elements of the list [l]
that satisfy the predicate [f]. The order of the elements
in the input list is preserved.
* [find_all] is another name for {!filter}.
* [partition ~f l] returns a pair of lists [(l1, l2)], where
[l1] is the list of all the elements of [l] that
satisfy the predicate [f], and [l2] is the list of all the
elements of [l] that do not satisfy [f].
The order of the elements in the input list is preserved.
* [assoc a l] returns the value associated with key [a] in the list of
pairs [l]. That is,
[assoc a [ ...; (a,b); ...] = b]
if [(a,b)] is the leftmost binding of [a] in list [l].
@raise Not_found if there is no value associated with [a] in the
list [l].
* Same as {!assoc}, but uses physical equality instead of
structural equality to compare keys.
* Same as {!assoc}, but simply return [true] if a binding exists,
and [false] if no bindings exist for the given key.
* {1 Sorting}
* Same as {!sort}, but the sorting algorithm is guaranteed to
be stable (i.e. elements that compare equal are kept in their
original order).
The current implementation uses Merge Sort. It runs in constant
heap space and logarithmic stack space.
| , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
* List operations .
Some functions are flagged as not tail - recursive . A tail - recursive
function uses constant stack space , while a non - tail - recursive function
uses stack space proportional to the length of its list argument , which
can be a problem with very long lists . When the function takes several
list arguments , an approximate formula giving stack usage ( in some
unspecified constant unit ) is shown in parentheses .
The above considerations can usually be ignored if your lists are not
longer than about 10000 elements .
The labeled version of this module can be used as described in the
{ ! StdLabels } module .
Some functions are flagged as not tail-recursive. A tail-recursive
function uses constant stack space, while a non-tail-recursive function
uses stack space proportional to the length of its list argument, which
can be a problem with very long lists. When the function takes several
list arguments, an approximate formula giving stack usage (in some
unspecified constant unit) is shown in parentheses.
The above considerations can usually be ignored if your lists are not
longer than about 10000 elements.
The labeled version of this module can be used as described in the
{!StdLabels} module.
*)
val length : 'a list -> int
val compare_lengths : 'a list -> 'b list -> int
* Compare the lengths of two lists . [ compare_lengths l1 l2 ] is
equivalent to [ compare ( length l1 ) ( length l2 ) ] , except that
the computation stops after reaching the end of the shortest list .
@since 4.05
equivalent to [compare (length l1) (length l2)], except that
the computation stops after reaching the end of the shortest list.
@since 4.05
*)
val compare_length_with : 'a list -> len:int -> int
* Compare the length of a list to an integer . [ compare_length_with l len ] is
equivalent to [ compare ( length l ) len ] , except that the computation stops
after at most [ len ] iterations on the list .
@since 4.05
equivalent to [compare (length l) len], except that the computation stops
after at most [len] iterations on the list.
@since 4.05
*)
val is_empty : 'a list -> bool
* [ is_empty l ] is true if and only if [ l ] has no elements . It is equivalent to
[ compare_length_with l 0 = 0 ] .
@since 5.1
[compare_length_with l 0 = 0].
@since 5.1
*)
val cons : 'a -> 'a list -> 'a list
* [ cons x xs ] is [ x : : xs ]
@since 4.03 ( 4.05 in ListLabels )
@since 4.03 (4.05 in ListLabels)
*)
val hd : 'a list -> 'a
* Return the first element of the given list .
@raise Failure if the list is empty .
@raise Failure if the list is empty.
*)
val tl : 'a list -> 'a list
* Return the given list without its first element .
@raise Failure if the list is empty .
@raise Failure if the list is empty.
*)
val nth : 'a list -> int -> 'a
* Return the [ n]-th element of the given list .
The first element ( head of the list ) is at position 0 .
@raise Failure if the list is too short .
@raise Invalid_argument if [ n ] is negative .
The first element (head of the list) is at position 0.
@raise Failure if the list is too short.
@raise Invalid_argument if [n] is negative.
*)
val nth_opt : 'a list -> int -> 'a option
* Return the [ n]-th element of the given list .
The first element ( head of the list ) is at position 0 .
Return [ None ] if the list is too short .
@raise Invalid_argument if [ n ] is negative .
@since 4.05
The first element (head of the list) is at position 0.
Return [None] if the list is too short.
@raise Invalid_argument if [n] is negative.
@since 4.05
*)
val rev : 'a list -> 'a list
val init : len:int -> f:(int -> 'a) -> 'a list
* [ init ~len ~f ] is [ [ f 0 ; f 1 ; ... ; f ( len-1 ) ] ] , evaluated left to right .
@raise Invalid_argument if ] .
@since 4.06
@raise Invalid_argument if [len < 0].
@since 4.06
*)
val append : 'a list -> 'a list -> 'a list
* two lists . Same function as the infix operator [ @ ] .
Not tail - recursive ( length of the first argument ) . The [ @ ]
operator is not tail - recursive either .
Not tail-recursive (length of the first argument). The [@]
operator is not tail-recursive either.
*)
val rev_append : 'a list -> 'a list -> 'a list
val concat : 'a list list -> 'a list
* a list of lists . The elements of the argument are all
concatenated together ( in the same order ) to give the result .
Not tail - recursive
( length of the argument + length of the longest sub - list ) .
concatenated together (in the same order) to give the result.
Not tail-recursive
(length of the argument + length of the longest sub-list).
*)
val flatten : 'a list list -> 'a list
* { 1 Comparison }
val equal : eq:('a -> 'a -> bool) -> 'a list -> 'a list -> bool
* [ equal eq [ a1 ; ... ; an ] [ b1 ; .. ; bm ] ] holds when
the two input lists have the same length , and for each
pair of elements [ ai ] , [ bi ] at the same position we have
[ eq ai bi ] .
Note : the [ eq ] function may be called even if the
lists have different length . If you know your equality
function is costly , you may want to check { ! compare_lengths }
first .
@since 4.12
the two input lists have the same length, and for each
pair of elements [ai], [bi] at the same position we have
[eq ai bi].
Note: the [eq] function may be called even if the
lists have different length. If you know your equality
function is costly, you may want to check {!compare_lengths}
first.
@since 4.12
*)
val compare : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> int
* [ compare cmp [ a1 ; ... ; an ] [ b1 ; ... ; bm ] ] performs
a lexicographic comparison of the two input lists ,
using the same [ ' a - > ' a - > int ] interface as { ! Stdlib.compare } :
- [ a1 : : l1 ] is smaller than [ a2 : : l2 ] ( negative result )
if [ a1 ] is smaller than [ a2 ] , or if they are equal ( 0 result )
and [ l1 ] is smaller than [ l2 ]
- the empty list [ [ ] ] is strictly smaller than non - empty lists
Note : the [ cmp ] function will be called even if the lists have
different lengths .
@since 4.12
a lexicographic comparison of the two input lists,
using the same ['a -> 'a -> int] interface as {!Stdlib.compare}:
- [a1 :: l1] is smaller than [a2 :: l2] (negative result)
if [a1] is smaller than [a2], or if they are equal (0 result)
and [l1] is smaller than [l2]
- the empty list [[]] is strictly smaller than non-empty lists
Note: the [cmp] function will be called even if the lists have
different lengths.
@since 4.12
*)
val iter : f:('a -> unit) -> 'a list -> unit
* [ iter ~f [ a1 ; ... ; an ] ] applies function [ f ] in turn to
[ [ a1 ; ... ; an ] ] . It is equivalent to
[ f a1 ; f a2 ; ... ; f an ] .
[[a1; ...; an]]. It is equivalent to
[f a1; f a2; ...; f an].
*)
val iteri : f:(int -> 'a -> unit) -> 'a list -> unit
* Same as { ! iter } , but the function is applied to the index of
the element as first argument ( counting from 0 ) , and the element
itself as second argument .
@since 4.00
the element as first argument (counting from 0), and the element
itself as second argument.
@since 4.00
*)
val map : f:('a -> 'b) -> 'a list -> 'b list
val mapi : f:(int -> 'a -> 'b) -> 'a list -> 'b list
* Same as { ! map } , but the function is applied to the index of
the element as first argument ( counting from 0 ) , and the element
itself as second argument .
@since 4.00
the element as first argument (counting from 0), and the element
itself as second argument.
@since 4.00
*)
val rev_map : f:('a -> 'b) -> 'a list -> 'b list
val filter_map : f:('a -> 'b option) -> 'a list -> 'b list
* [ filter_map ~f l ] applies [ f ] to every element of [ l ] , filters
out the [ None ] elements and returns the list of the arguments of
the [ Some ] elements .
@since 4.08
out the [None] elements and returns the list of the arguments of
the [Some] elements.
@since 4.08
*)
val concat_map : f:('a -> 'b list) -> 'a list -> 'b list
* [ concat_map ~f l ] gives the same result as
{ ! concat } [ ( ] { ! map } [ f l ) ] . Tail - recursive .
@since 4.10
{!concat}[ (]{!map}[ f l)]. Tail-recursive.
@since 4.10
*)
val fold_left_map :
f:('a -> 'b -> 'a * 'c) -> init:'a -> 'b list -> 'a * 'c list
* [ fold_left_map ] is a combination of [ fold_left ] and [ map ] that threads an
accumulator through calls to [ f ] .
@since 4.11
accumulator through calls to [f].
@since 4.11
*)
val fold_left : f:('a -> 'b -> 'a) -> init:'a -> 'b list -> 'a
val fold_right : f:('a -> 'b -> 'b) -> 'a list -> init:'b -> 'b
* { 1 Iterators on two lists }
val iter2 : f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit
* [ iter2 ~f [ a1 ; ... ; an ] [ b1 ; ... ; bn ] ] calls in turn
[ f a1 b1 ; ... ; f an bn ] .
@raise Invalid_argument if the two lists are determined
to have different lengths .
[f a1 b1; ...; f an bn].
@raise Invalid_argument if the two lists are determined
to have different lengths.
*)
val map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
* [ map2 ~f [ a1 ; ... ; an ] [ b1 ; ... ; bn ] ] is
[ [ f a1 b1 ; ... ; f an bn ] ] .
@raise Invalid_argument if the two lists are determined
to have different lengths .
[[f a1 b1; ...; f an bn]].
@raise Invalid_argument if the two lists are determined
to have different lengths.
*)
val rev_map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
val fold_left2 :
f:('a -> 'b -> 'c -> 'a) -> init:'a -> 'b list -> 'c list -> 'a
* [ ~f ~init [ a1 ; ... ; an ] [ b1 ; ... ; bn ] ] is
[ f ( ... ( f ( f init a1 b1 ) a2 b2 ) ... ) an bn ] .
@raise Invalid_argument if the two lists are determined
to have different lengths .
[f (... (f (f init a1 b1) a2 b2) ...) an bn].
@raise Invalid_argument if the two lists are determined
to have different lengths.
*)
val fold_right2 :
f:('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> init:'c -> 'c
* [ fold_right2 ~f [ a1 ; ... ; an ] [ b1 ; ... ; bn ] ~init ] is
[ f a1 b1 ( f a2 b2 ( ... ( f an bn init ) ... ) ) ] .
@raise Invalid_argument if the two lists are determined
to have different lengths . Not tail - recursive .
[f a1 b1 (f a2 b2 (... (f an bn init) ...))].
@raise Invalid_argument if the two lists are determined
to have different lengths. Not tail-recursive.
*)
* { 1 List scanning }
val for_all : f:('a -> bool) -> 'a list -> bool
* [ for_all ~f [ a1 ; ... ; an ] ] checks if all elements of the list
satisfy the predicate [ f ] . That is , it returns
[ ( f a1 ) & & ( f a2 ) & & ... & & ( f an ) ] for a non - empty list and
[ true ] if the list is empty .
satisfy the predicate [f]. That is, it returns
[(f a1) && (f a2) && ... && (f an)] for a non-empty list and
[true] if the list is empty.
*)
val exists : f:('a -> bool) -> 'a list -> bool
* [ exists ~f [ a1 ; ... ; an ] ] checks if at least one element of
the list satisfies the predicate [ f ] . That is , it returns
[ ( f a1 ) || ( f a2 ) || ... || ( f an ) ] for a non - empty list and
[ false ] if the list is empty .
the list satisfies the predicate [f]. That is, it returns
[(f a1) || (f a2) || ... || (f an)] for a non-empty list and
[false] if the list is empty.
*)
val for_all2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool
* Same as { ! for_all } , but for a two - argument predicate .
@raise Invalid_argument if the two lists are determined
to have different lengths .
@raise Invalid_argument if the two lists are determined
to have different lengths.
*)
val exists2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool
* Same as { ! exists } , but for a two - argument predicate .
@raise Invalid_argument if the two lists are determined
to have different lengths .
@raise Invalid_argument if the two lists are determined
to have different lengths.
*)
val mem : 'a -> set:'a list -> bool
val memq : 'a -> set:'a list -> bool
* { 1 List searching }
val find : f:('a -> bool) -> 'a list -> 'a
* [ find ~f l ] returns the first element of the list [ l ]
that satisfies the predicate [ f ] .
@raise Not_found if there is no value that satisfies [ f ] in the
list [ l ] .
that satisfies the predicate [f].
@raise Not_found if there is no value that satisfies [f] in the
list [l].
*)
val find_opt : f:('a -> bool) -> 'a list -> 'a option
* [ find ~f l ] returns the first element of the list [ l ]
that satisfies the predicate [ f ] .
Returns [ None ] if there is no value that satisfies [ f ] in the
list [ l ] .
@since 4.05
that satisfies the predicate [f].
Returns [None] if there is no value that satisfies [f] in the
list [l].
@since 4.05
*)
val find_map : f:('a -> 'b option) -> 'a list -> 'b option
* [ find_map ~f l ] applies [ f ] to the elements of [ l ] in order ,
and returns the first result of the form [ Some v ] , or [ None ]
if none exist .
@since 4.10
and returns the first result of the form [Some v], or [None]
if none exist.
@since 4.10
*)
val filter : f:('a -> bool) -> 'a list -> 'a list
val find_all : f:('a -> bool) -> 'a list -> 'a list
val filteri : f:(int -> 'a -> bool) -> 'a list -> 'a list
* Same as { ! filter } , but the predicate is applied to the index of
the element as first argument ( counting from 0 ) , and the element
itself as second argument .
@since 4.11
the element as first argument (counting from 0), and the element
itself as second argument.
@since 4.11
*)
val partition : f:('a -> bool) -> 'a list -> 'a list * 'a list
val partition_map : f:('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list
* [ partition_map f l ] returns a pair of lists [ ( l1 , l2 ) ] such that ,
for each element [ x ] of the input list [ l ] :
- if [ f x ] is [ Left y1 ] , then [ y1 ] is in [ l1 ] , and
- if [ f x ] is [ Right y2 ] , then [ y2 ] is in [ l2 ] .
The output elements are included in [ l1 ] and [ l2 ] in the same
relative order as the corresponding input elements in [ l ] .
In particular , [ partition_map ( fun x - > if f x then Left x else Right x ) l ]
is equivalent to [ partition f l ] .
@since 4.12
for each element [x] of the input list [l]:
- if [f x] is [Left y1], then [y1] is in [l1], and
- if [f x] is [Right y2], then [y2] is in [l2].
The output elements are included in [l1] and [l2] in the same
relative order as the corresponding input elements in [l].
In particular, [partition_map (fun x -> if f x then Left x else Right x) l]
is equivalent to [partition f l].
@since 4.12
*)
* { 1 Association lists }
val assoc : 'a -> ('a * 'b) list -> 'b
val assoc_opt : 'a -> ('a * 'b) list -> 'b option
* [ assoc_opt a l ] returns the value associated with key [ a ] in the list of
pairs [ l ] . That is ,
[ a [ ... ; ( a , b ) ; ... ] = Some b ]
if [ ( a , b ) ] is the leftmost binding of [ a ] in list [ l ] .
Returns [ None ] if there is no value associated with [ a ] in the
list [ l ] .
@since 4.05
pairs [l]. That is,
[assoc_opt a [ ...; (a,b); ...] = Some b]
if [(a,b)] is the leftmost binding of [a] in list [l].
Returns [None] if there is no value associated with [a] in the
list [l].
@since 4.05
*)
val assq : 'a -> ('a * 'b) list -> 'b
val assq_opt : 'a -> ('a * 'b) list -> 'b option
* Same as { ! } , but uses physical equality instead of
structural equality to compare keys .
@since 4.05
structural equality to compare keys.
@since 4.05
*)
val mem_assoc : 'a -> map:('a * 'b) list -> bool
val mem_assq : 'a -> map:('a * 'b) list -> bool
* Same as { ! , but uses physical equality instead of
structural equality to compare keys .
structural equality to compare keys.
*)
val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list
* [ remove_assoc a l ] returns the list of
pairs [ l ] without the first pair with key [ a ] , if any .
Not tail - recursive .
pairs [l] without the first pair with key [a], if any.
Not tail-recursive.
*)
val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list
* Same as { ! , but uses physical equality instead
of structural equality to compare keys . Not tail - recursive .
of structural equality to compare keys. Not tail-recursive.
*)
* { 1 Lists of pairs }
val split : ('a * 'b) list -> 'a list * 'b list
* Transform a list of pairs into a pair of lists :
[ split [ ( a1,b1 ) ; ... ; ( an , bn ) ] ] is [ ( [ a1 ; ... ; an ] , [ b1 ; ... ; bn ] ) ] .
Not tail - recursive .
[split [(a1,b1); ...; (an,bn)]] is [([a1; ...; an], [b1; ...; bn])].
Not tail-recursive.
*)
val combine : 'a list -> 'b list -> ('a * 'b) list
* Transform a pair of lists into a list of pairs :
[ combine [ a1 ; ... ; an ] [ b1 ; ... ; bn ] ] is
[ [ ( a1,b1 ) ; ... ; ( an , bn ) ] ] .
@raise Invalid_argument if the two lists
have different lengths . Not tail - recursive .
[combine [a1; ...; an] [b1; ...; bn]] is
[[(a1,b1); ...; (an,bn)]].
@raise Invalid_argument if the two lists
have different lengths. Not tail-recursive.
*)
val sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
* Sort a list in increasing order according to a comparison
function . The comparison function must return 0 if its arguments
compare as equal , a positive integer if the first is greater ,
and a negative integer if the first is smaller ( see Array.sort for
a complete specification ) . For example ,
{ ! Stdlib.compare } is a suitable comparison function .
The resulting list is sorted in increasing order .
{ ! sort } is guaranteed to run in constant heap space
( in addition to the size of the result list ) and logarithmic
stack space .
The current implementation uses Merge Sort . It runs in constant
heap space and logarithmic stack space .
function. The comparison function must return 0 if its arguments
compare as equal, a positive integer if the first is greater,
and a negative integer if the first is smaller (see Array.sort for
a complete specification). For example,
{!Stdlib.compare} is a suitable comparison function.
The resulting list is sorted in increasing order.
{!sort} is guaranteed to run in constant heap space
(in addition to the size of the result list) and logarithmic
stack space.
The current implementation uses Merge Sort. It runs in constant
heap space and logarithmic stack space.
*)
val stable_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
val fast_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
* Same as { ! sort } or { ! } , whichever is
faster on typical input .
faster on typical input.
*)
val sort_uniq : cmp:('a -> 'a -> int) -> 'a list -> 'a list
* Same as { ! sort } , but also remove duplicates .
@since 4.02 ( 4.03 in ListLabels )
@since 4.02 (4.03 in ListLabels)
*)
val merge : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> 'a list
* Merge two lists :
Assuming that [ l1 ] and [ l2 ] are sorted according to the
comparison function [ cmp ] , [ merge ~cmp l1 l2 ] will return a
sorted list containing all the elements of [ l1 ] and [ l2 ] .
If several elements compare equal , the elements of [ l1 ] will be
before the elements of [ l2 ] .
Not tail - recursive ( sum of the lengths of the arguments ) .
Assuming that [l1] and [l2] are sorted according to the
comparison function [cmp], [merge ~cmp l1 l2] will return a
sorted list containing all the elements of [l1] and [l2].
If several elements compare equal, the elements of [l1] will be
before the elements of [l2].
Not tail-recursive (sum of the lengths of the arguments).
*)
* { 1 Lists and Sequences }
val to_seq : 'a list -> 'a Seq.t
* Iterate on the list .
@since 4.07
@since 4.07
*)
val of_seq : 'a Seq.t -> 'a list
* Create a list from a sequence .
@since 4.07
@since 4.07
*)
|
464e1b612107534810700115b53007f1de08c65abb4fac790412d8444aa44dd0 | unisonweb/unison | DbHelpers.hs | module Unison.Codebase.SqliteCodebase.Migrations.MigrateSchema1To2.DbHelpers
( dbBranchHash,
dbPatchHash,
syncCausalHash,
)
where
import qualified Data.Set as Set
import qualified Data.Vector as Vector
import U.Codebase.HashTags (BranchHash (..), CausalHash (..), PatchHash (..))
import qualified U.Codebase.Reference as S hiding (Reference)
import qualified U.Codebase.Reference as S.Reference
import qualified U.Codebase.Referent as S.Referent
import U.Codebase.Sqlite.Branch.Full (DbMetadataSet)
import qualified U.Codebase.Sqlite.Branch.Full as S
import qualified U.Codebase.Sqlite.Branch.Full as S.Branch.Full
import qualified U.Codebase.Sqlite.Branch.Full as S.MetadataSet
import qualified U.Codebase.Sqlite.Causal as S
import qualified U.Codebase.Sqlite.DbId as Db
import qualified U.Codebase.Sqlite.Patch.Full as S
import qualified U.Codebase.Sqlite.Patch.TermEdit as S (TermEdit)
import qualified U.Codebase.Sqlite.Patch.TermEdit as S.TermEdit
import qualified U.Codebase.Sqlite.Patch.TypeEdit as S (TypeEdit)
import qualified U.Codebase.Sqlite.Patch.TypeEdit as S.TypeEdit
import qualified U.Codebase.Sqlite.Queries as Q
import qualified U.Codebase.Sqlite.Reference as S
import qualified U.Codebase.Sqlite.Referent as S
import Unison.Hash (Hash)
import qualified Unison.Hashing.V2 as Hashing
import Unison.Prelude
import Unison.Sqlite (Transaction)
import qualified Unison.Util.Map as Map
import qualified Unison.Util.Set as Set
syncCausalHash :: S.SyncCausalFormat -> Transaction CausalHash
syncCausalHash S.SyncCausalFormat {valueHash = valueHashId, parents = parentChIds} = do
fmap (CausalHash . Hashing.contentHash) $
Hashing.Causal
<$> coerce @(Transaction BranchHash) @(Transaction Hash) (Q.expectBranchHash valueHashId)
<*> fmap (Set.fromList . coerce @[CausalHash] @[Hash] . Vector.toList) (traverse Q.expectCausalHash parentChIds)
dbBranchHash :: S.DbBranch -> Transaction BranchHash
dbBranchHash (S.Branch.Full.Branch tms tps patches children) =
fmap (BranchHash . Hashing.contentHash) $
Hashing.Branch
<$> doTerms tms
<*> doTypes tps
<*> doPatches patches
<*> doChildren children
where
doTerms ::
Map Db.TextId (Map S.Referent S.DbMetadataSet) ->
Transaction (Map Hashing.NameSegment (Map Hashing.Referent Hashing.MdValues))
doTerms =
Map.bitraverse
s2hNameSegment
(Map.bitraverse s2hReferent s2hMetadataSet)
doTypes ::
Map Db.TextId (Map S.Reference S.DbMetadataSet) ->
Transaction (Map Hashing.NameSegment (Map Hashing.Reference Hashing.MdValues))
doTypes =
Map.bitraverse
s2hNameSegment
(Map.bitraverse s2hReference s2hMetadataSet)
doPatches :: Map Db.TextId Db.PatchObjectId -> Transaction (Map Hashing.NameSegment Hash)
doPatches =
Map.bitraverse s2hNameSegment (Q.expectPrimaryHashByObjectId . Db.unPatchObjectId)
doChildren :: Map Db.TextId (Db.BranchObjectId, Db.CausalHashId) -> Transaction (Map Hashing.NameSegment Hash)
doChildren =
Map.bitraverse s2hNameSegment \(_boId, chId) -> Q.expectHash (Db.unCausalHashId chId)
dbPatchHash :: S.Patch -> Transaction PatchHash
dbPatchHash S.Patch {S.termEdits, S.typeEdits} =
fmap (PatchHash . Hashing.contentHash) $
Hashing.Patch
<$> doTermEdits termEdits
<*> doTypeEdits typeEdits
where
doTermEdits :: Map S.ReferentH (Set S.TermEdit) -> Transaction (Map Hashing.Referent (Set Hashing.TermEdit))
doTermEdits =
Map.bitraverse s2hReferentH (Set.traverse s2hTermEdit)
doTypeEdits :: Map S.ReferenceH (Set S.TypeEdit) -> Transaction (Map Hashing.Reference (Set Hashing.TypeEdit))
doTypeEdits =
Map.bitraverse s2hReferenceH (Set.traverse s2hTypeEdit)
s2hMetadataSet :: DbMetadataSet -> Transaction Hashing.MdValues
s2hMetadataSet = \case
S.MetadataSet.Inline rs -> Hashing.MdValues <$> Set.traverse s2hReference rs
s2hNameSegment :: Db.TextId -> Transaction Hashing.NameSegment
s2hNameSegment =
fmap Hashing.NameSegment . Q.expectText
s2hReferent :: S.Referent -> Transaction Hashing.Referent
s2hReferent = \case
S.Referent.Ref r -> Hashing.ReferentRef <$> s2hReference r
S.Referent.Con r cid -> Hashing.ReferentCon <$> s2hReference r <*> pure (fromIntegral cid)
s2hReferentH :: S.ReferentH -> Transaction Hashing.Referent
s2hReferentH = \case
S.Referent.Ref r -> Hashing.ReferentRef <$> s2hReferenceH r
S.Referent.Con r cid -> Hashing.ReferentCon <$> s2hReferenceH r <*> pure (fromIntegral cid)
s2hReference :: S.Reference -> Transaction Hashing.Reference
s2hReference = \case
S.ReferenceBuiltin t -> Hashing.ReferenceBuiltin <$> Q.expectText t
S.Reference.Derived h i -> Hashing.ReferenceDerived <$> Q.expectPrimaryHashByObjectId h <*> pure i
s2hReferenceH :: S.ReferenceH -> Transaction Hashing.Reference
s2hReferenceH = \case
S.ReferenceBuiltin t -> Hashing.ReferenceBuiltin <$> Q.expectText t
S.Reference.Derived h i -> Hashing.ReferenceDerived <$> Q.expectHash h <*> pure i
s2hTermEdit :: S.TermEdit -> Transaction Hashing.TermEdit
s2hTermEdit = \case
S.TermEdit.Replace r _typing -> Hashing.TermEditReplace <$> s2hReferent r
S.TermEdit.Deprecate -> pure Hashing.TermEditDeprecate
s2hTypeEdit :: S.TypeEdit -> Transaction Hashing.TypeEdit
s2hTypeEdit = \case
S.TypeEdit.Replace r -> Hashing.TypeEditReplace <$> s2hReference r
S.TypeEdit.Deprecate -> pure Hashing.TypeEditDeprecate
| null | https://raw.githubusercontent.com/unisonweb/unison/bf0186aefb11ef2a9ec44d55adc70f356044f0c7/parser-typechecker/src/Unison/Codebase/SqliteCodebase/Migrations/MigrateSchema1To2/DbHelpers.hs | haskell | module Unison.Codebase.SqliteCodebase.Migrations.MigrateSchema1To2.DbHelpers
( dbBranchHash,
dbPatchHash,
syncCausalHash,
)
where
import qualified Data.Set as Set
import qualified Data.Vector as Vector
import U.Codebase.HashTags (BranchHash (..), CausalHash (..), PatchHash (..))
import qualified U.Codebase.Reference as S hiding (Reference)
import qualified U.Codebase.Reference as S.Reference
import qualified U.Codebase.Referent as S.Referent
import U.Codebase.Sqlite.Branch.Full (DbMetadataSet)
import qualified U.Codebase.Sqlite.Branch.Full as S
import qualified U.Codebase.Sqlite.Branch.Full as S.Branch.Full
import qualified U.Codebase.Sqlite.Branch.Full as S.MetadataSet
import qualified U.Codebase.Sqlite.Causal as S
import qualified U.Codebase.Sqlite.DbId as Db
import qualified U.Codebase.Sqlite.Patch.Full as S
import qualified U.Codebase.Sqlite.Patch.TermEdit as S (TermEdit)
import qualified U.Codebase.Sqlite.Patch.TermEdit as S.TermEdit
import qualified U.Codebase.Sqlite.Patch.TypeEdit as S (TypeEdit)
import qualified U.Codebase.Sqlite.Patch.TypeEdit as S.TypeEdit
import qualified U.Codebase.Sqlite.Queries as Q
import qualified U.Codebase.Sqlite.Reference as S
import qualified U.Codebase.Sqlite.Referent as S
import Unison.Hash (Hash)
import qualified Unison.Hashing.V2 as Hashing
import Unison.Prelude
import Unison.Sqlite (Transaction)
import qualified Unison.Util.Map as Map
import qualified Unison.Util.Set as Set
syncCausalHash :: S.SyncCausalFormat -> Transaction CausalHash
syncCausalHash S.SyncCausalFormat {valueHash = valueHashId, parents = parentChIds} = do
fmap (CausalHash . Hashing.contentHash) $
Hashing.Causal
<$> coerce @(Transaction BranchHash) @(Transaction Hash) (Q.expectBranchHash valueHashId)
<*> fmap (Set.fromList . coerce @[CausalHash] @[Hash] . Vector.toList) (traverse Q.expectCausalHash parentChIds)
dbBranchHash :: S.DbBranch -> Transaction BranchHash
dbBranchHash (S.Branch.Full.Branch tms tps patches children) =
fmap (BranchHash . Hashing.contentHash) $
Hashing.Branch
<$> doTerms tms
<*> doTypes tps
<*> doPatches patches
<*> doChildren children
where
doTerms ::
Map Db.TextId (Map S.Referent S.DbMetadataSet) ->
Transaction (Map Hashing.NameSegment (Map Hashing.Referent Hashing.MdValues))
doTerms =
Map.bitraverse
s2hNameSegment
(Map.bitraverse s2hReferent s2hMetadataSet)
doTypes ::
Map Db.TextId (Map S.Reference S.DbMetadataSet) ->
Transaction (Map Hashing.NameSegment (Map Hashing.Reference Hashing.MdValues))
doTypes =
Map.bitraverse
s2hNameSegment
(Map.bitraverse s2hReference s2hMetadataSet)
doPatches :: Map Db.TextId Db.PatchObjectId -> Transaction (Map Hashing.NameSegment Hash)
doPatches =
Map.bitraverse s2hNameSegment (Q.expectPrimaryHashByObjectId . Db.unPatchObjectId)
doChildren :: Map Db.TextId (Db.BranchObjectId, Db.CausalHashId) -> Transaction (Map Hashing.NameSegment Hash)
doChildren =
Map.bitraverse s2hNameSegment \(_boId, chId) -> Q.expectHash (Db.unCausalHashId chId)
dbPatchHash :: S.Patch -> Transaction PatchHash
dbPatchHash S.Patch {S.termEdits, S.typeEdits} =
fmap (PatchHash . Hashing.contentHash) $
Hashing.Patch
<$> doTermEdits termEdits
<*> doTypeEdits typeEdits
where
doTermEdits :: Map S.ReferentH (Set S.TermEdit) -> Transaction (Map Hashing.Referent (Set Hashing.TermEdit))
doTermEdits =
Map.bitraverse s2hReferentH (Set.traverse s2hTermEdit)
doTypeEdits :: Map S.ReferenceH (Set S.TypeEdit) -> Transaction (Map Hashing.Reference (Set Hashing.TypeEdit))
doTypeEdits =
Map.bitraverse s2hReferenceH (Set.traverse s2hTypeEdit)
s2hMetadataSet :: DbMetadataSet -> Transaction Hashing.MdValues
s2hMetadataSet = \case
S.MetadataSet.Inline rs -> Hashing.MdValues <$> Set.traverse s2hReference rs
s2hNameSegment :: Db.TextId -> Transaction Hashing.NameSegment
s2hNameSegment =
fmap Hashing.NameSegment . Q.expectText
s2hReferent :: S.Referent -> Transaction Hashing.Referent
s2hReferent = \case
S.Referent.Ref r -> Hashing.ReferentRef <$> s2hReference r
S.Referent.Con r cid -> Hashing.ReferentCon <$> s2hReference r <*> pure (fromIntegral cid)
s2hReferentH :: S.ReferentH -> Transaction Hashing.Referent
s2hReferentH = \case
S.Referent.Ref r -> Hashing.ReferentRef <$> s2hReferenceH r
S.Referent.Con r cid -> Hashing.ReferentCon <$> s2hReferenceH r <*> pure (fromIntegral cid)
s2hReference :: S.Reference -> Transaction Hashing.Reference
s2hReference = \case
S.ReferenceBuiltin t -> Hashing.ReferenceBuiltin <$> Q.expectText t
S.Reference.Derived h i -> Hashing.ReferenceDerived <$> Q.expectPrimaryHashByObjectId h <*> pure i
s2hReferenceH :: S.ReferenceH -> Transaction Hashing.Reference
s2hReferenceH = \case
S.ReferenceBuiltin t -> Hashing.ReferenceBuiltin <$> Q.expectText t
S.Reference.Derived h i -> Hashing.ReferenceDerived <$> Q.expectHash h <*> pure i
s2hTermEdit :: S.TermEdit -> Transaction Hashing.TermEdit
s2hTermEdit = \case
S.TermEdit.Replace r _typing -> Hashing.TermEditReplace <$> s2hReferent r
S.TermEdit.Deprecate -> pure Hashing.TermEditDeprecate
s2hTypeEdit :: S.TypeEdit -> Transaction Hashing.TypeEdit
s2hTypeEdit = \case
S.TypeEdit.Replace r -> Hashing.TypeEditReplace <$> s2hReference r
S.TypeEdit.Deprecate -> pure Hashing.TypeEditDeprecate
| |
56b37a1b666b112392731fe279334d781bb1be684d391ca1a91576172d09e990 | backtracking/ocamlgraph | graphviz.mli | (**************************************************************************)
(* *)
: a generic graph library for OCaml
Copyright ( C ) 2004 - 2010
, and
(* *)
(* This software is free software; you can redistribute it and/or *)
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
(* described in file LICENSE. *)
(* *)
(* This software 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. *)
(* *)
(**************************************************************************)
* Interface with { i GraphViz }
This module provides a basic interface with dot and neato ,
two programs of the GraphViz toolbox .
These tools are available at the following URLs :
- { v v }
- { v v }
This module provides a basic interface with dot and neato,
two programs of the GraphViz toolbox.
These tools are available at the following URLs:
- {v v}
- {v v} *)
open Format
(***************************************************************************)
* { 2 Common stuff }
* Because the neato and dot engines present a lot of common points -
in particular in the graph description language , large parts of
the code is shared . The [ CommonAttributes ] module defines
attributes of graphs , vertices and edges that are understood by the
two engines . Then module [ DotAttributes ] and [ NeatoAttributes ]
define attributes specific to dot and neato respectively .
in particular in the graph description language, large parts of
the code is shared. The [CommonAttributes] module defines
attributes of graphs, vertices and edges that are understood by the
two engines. Then module [DotAttributes] and [NeatoAttributes]
define attributes specific to dot and neato respectively. *)
(*-------------------------------------------------------------------------*)
* { 3 Common types and signatures }
type color = int
type color_with_transparency = int32
* The two least significant bytes encode the transparency information ;
the six most signification are the standard RGB color
the six most signification are the standard RGB color *)
val color_to_color_with_transparency: color -> color_with_transparency
type arrow_style =
[ `None | `Normal | `Onormal | `Inv | `Dot | `Odot | `Invdot | `Invodot ]
(** The [ATTRIBUTES] module type defines the interface for the engines. *)
module type ATTRIBUTES = sig
type graph (** Attributes of graphs. *)
type vertex (** Attributes of vertices. *)
type edge (** Attributes of edges. *)
(** Attributes of (optional) boxes around vertices. *)
type subgraph = {
sg_name : string; (** Box name. *)
sg_attributes : vertex list; (** Box attributes. *)
sg_parent : string option; (** Nested subgraphs. *)
}
end
(*-------------------------------------------------------------------------*)
* { 3 Common attributes }
* The [ CommonAttributes ] module defines attributes for graphs , vertices and
edges that are available in the two engines , dot and neato .
edges that are available in the two engines, dot and neato. *)
module CommonAttributes : sig
(** Attributes of graphs. *)
type graph =
[ `Center of bool
(** Centers the drawing on the page. Default value is [false]. *)
| `Fontcolor of color
(** Sets the font color. Default value is [black]. *)
| `Fontname of string
(** Sets the font family name. Default value is ["Times-Roman"]. *)
| `Fontsize of int
* Sets the type size ( in points ) . Default value is [ 14 ] .
| `Label of string
(** Caption for graph drawing. *)
| `HtmlLabel of string
* Caption for graph drawing . In HTML strings , angle brackets must occur in
matched pairs , and newlines and other formatting whitespace characters
are allowed . In addition , the content must be legal XML , so that the
special XML escape sequences for " , & , < , and > may be necessary in
order to embed these characters in attribute values or raw text . "
matched pairs, and newlines and other formatting whitespace characters
are allowed. In addition, the content must be legal XML, so that the
special XML escape sequences for ", &, <, and > may be necessary in
order to embed these characters in attribute values or raw text." *)
| `Orientation of [ `Portrait | `Landscape ]
(** Sets the page orientation. Default value is [`Portrait]. *)
| `Page of float * float
* Sets the PostScript pagination unit , e.g [ 8.5 , 11.0 ] .
| `Pagedir of [ `TopToBottom | `LeftToRight ]
* Traversal order of pages . Default value is [ ` TopToBottom ] .
| `Size of float * float
(** Sets the bounding box of drawing (in inches). *)
| `OrderingOut
(** Constrains order of out-edges in a subgraph according to
their file sequence *)
]
(** Attributes of vertices. *)
type vertex =
[ `Color of color
(** Sets the color of the border of the vertex.
Default value is [black] *)
| `ColorWithTransparency of color_with_transparency
(** Sets the color of the border of the vertex with a transparency
component. Default value is fully opaque [black] *)
| `Fontcolor of color
(** Sets the label font color. Default value is [black]. *)
| `Fontname of string
(** Sets the label font family name. Default value is
["Times-Roman"]. *)
| `Fontsize of int
* Sets the label type size ( in points ) . Default value is [ 14 ] .
*)
| `Height of float
* Sets the minimum height . Default value is [ 0.5 ] .
| `Label of string
* Sets the label printed in the vertex .
The string may include escaped
newlines [ \n ] , [ \l ] , or [ \r ] for center , left , and right justified
lines .
Record labels may contain recursive box lists delimited by { | } .
The string may include escaped
newlines [\n], [\l], or [\r] for center, left, and right justified
lines.
Record labels may contain recursive box lists delimited by { | }.
*)
| `HtmlLabel of string
* Like label , in html style . In HTML strings , angle brackets must occur in
matched pairs , and newlines and other formatting whitespace characters
are allowed . In addition , the content must be legal XML , so that the
special XML escape sequences for " , & , < , and > may be necessary in
order to embed these characters in attribute values or raw text . "
matched pairs, and newlines and other formatting whitespace characters
are allowed. In addition, the content must be legal XML, so that the
special XML escape sequences for ", &, <, and > may be necessary in
order to embed these characters in attribute values or raw text." *)
| `Orientation of float
* Vertex rotation angle , in degrees . Default value is [ 0.0 ] .
| `Penwidth of float
* Width of the pen ( in points ) used to draw the border of the node .
Default value is [ 1.0 ] .
Default value is [1.0]. *)
| `Peripheries of int
(** Sets the number of periphery lines drawn around the polygon. *)
| `Regular of bool
(** If [true], then the polygon is made regular, i.e. symmetric about
the x and y axis, otherwise the polygon takes on the aspect
ratio of the label. Default value is [false]. *)
| `Shape of
[`Ellipse | `Box | `Circle | `Doublecircle | `Diamond
| `Plaintext | `Record
(* Addition through *)
| `Oval | `Egg | `Triangle | `Invtriangle
| `Trapezium | `Invtrapezium
| `House | `Invhouse
| `Parallelogram | `Doubleoctagon | `Tripleoctagon
| `Mdiamond | `Mcircle | `Msquare
| `Star | `Underline
| `Note | `Tab | `Folder
| `Box3d | `Component | `Promoter
| `Cds
| `Terminator | `Utr | `Primersite
| `Restrictionsite
| `Fivepoverhang | `Threepoverhang | `Noverhang
| `Assembly | `Signature | `Insulator | `Ribosite | `Rnastab
| `Proteasesite | `Proteinstab | `Rpromoter | `Rarrow
| `Larrow | `Lpromoter
(* Addition ends here *)
| `Polygon of int * float]
* Sets the shape of the vertex . Default value is [ ` Ellipse ] .
[ ` Polygon ( i , f ) ] draws a polygon with [ n ] sides and a skewing
of [ f ] .
[`Polygon (i, f)] draws a polygon with [n] sides and a skewing
of [f]. *)
| `Style of
[ `Rounded | `Filled | `Solid | `Dashed | `Dotted | `Bold | `Invis ]
(** Sets the layout style of the vertex.
Several styles may be combined simultaneously. *)
| `Width of float
* Sets the minimum width . Default value is [ 0.75 ] .
]
(** Attributes of edges. *)
type edge =
[ `Color of color
(** Sets the edge stroke color. Default value is [black]. *)
| `ColorWithTransparency of color_with_transparency
(** Sets the edge stroke color with a transparency
component. Default value is fully opaque [black] *)
| `Decorate of bool
(** If [true], draws a line connecting labels with their edges. *)
| `Dir of [ `Forward | `Back | `Both | `None ]
(** Sets arrow direction. Default value is [`Forward]. *)
| `Fontcolor of color
(** Sets the label font color. Default value is [black]. *)
| `Fontname of string
(** Sets the label font family name. Default value is
["Times-Roman"]. *)
| `Fontsize of int
* Sets the label type size ( in points ) . Default value is [ 14 ] .
| `Label of string
* Sets the label to be attached to the edge . The string may include
escaped newlines [ \n ] , [ \l ] , or [ \r ] for centered , left , or right
justified lines .
escaped newlines [\n], [\l], or [\r] for centered, left, or right
justified lines. *)
| `HtmlLabel of string
* Like label , in html style . In HTML strings , angle brackets must occur in
matched pairs , and newlines and other formatting whitespace characters
are allowed . In addition , the content must be legal XML , so that the
special XML escape sequences for " , & , < , and > may be necessary in
order to embed these characters in attribute values or raw text . "
matched pairs, and newlines and other formatting whitespace characters
are allowed. In addition, the content must be legal XML, so that the
special XML escape sequences for ", &, <, and > may be necessary in
order to embed these characters in attribute values or raw text." *)
| `Labelfontcolor of color
(** Sets the font color for head and tail labels. Default value is
[black]. *)
| `Labelfontname of string
(** Sets the font family name for head and tail labels. Default
value is ["Times-Roman"]. *)
| `Labelfontsize of int
* Sets the font size for head and tail labels ( in points ) .
Default value is [ 14 ] .
Default value is [14]. *)
| `Penwidth of float
* Width of the pen ( in points ) used to draw the edge . Default value
is [ 1.0 ] .
is [1.0]. *)
| `Style of [ `Solid | `Dashed | `Dotted | `Bold | `Invis ]
(** Sets the layout style of the edge. Several styles may be combined
simultaneously. *)
]
end
(***************************************************************************)
(** {2 Interface with the dot engine} *)
(** [DotAttributes] extends [CommonAttributes] and implements [ATTRIBUTES]. *)
module DotAttributes : sig
* Attributes of graphs . They include all common graph attributes and
several specific ones . All attributes described in the " dot User 's
Manual , February 4 , 2002 " are handled , excepted : clusterank , color ,
compound , labeljust , labelloc , ordering , rank , remincross , rotate ,
searchsize and style .
several specific ones. All attributes described in the "dot User's
Manual, February 4, 2002" are handled, excepted: clusterank, color,
compound, labeljust, labelloc, ordering, rank, remincross, rotate,
searchsize and style. *)
type graph =
[ CommonAttributes.graph
| `Bgcolor of color
(** Sets the background color and the inital fill color. *)
| `BgcolorWithTransparency of color_with_transparency
(** Sets the background color and the inital fill color with
a transparency component. *)
| `Comment of string
(** Comment string. *)
| `Concentrate of bool
(** If [true], enables edge concentrators. Default value is [false]. *)
| `Fontpath of string
(** List of directories for fonts. *)
| `Layers of string list
(** List of layers. *)
| `Margin of float
* Sets the page margin ( included in the page size ) . Default value is
[ 0.5 ] .
[0.5]. *)
| `Mclimit of float
* Scale factor for mincross iterations . Default value is [ 1.0 ] .
| `Nodesep of float
* Sets the minimum separation between nodes , in inches . Default
value is [ 0.25 ] .
value is [0.25]. *)
| `Nslimit of int
(** If set of [f], bounds network simplex iterations by [f *
<number of nodes>] when ranking nodes. *)
| `Nslimit1 of int
(** If set of [f], bounds network simplex iterations by [f *
<number of nodes>] when setting x-coordinates. *)
| `Ranksep of float
(** Sets the minimum separation between ranks. *)
| `Quantum of float
* If not [ 0.0 ] , node label dimensions will be rounded to integral
multiples of it . Default value is [ 0.0 ] .
multiples of it. Default value is [0.0]. *)
| `Rankdir of [ `TopToBottom | `BottomToTop | `LeftToRight | `RightToLeft ]
* Direction of rank ordering . Default value is [ ` TopToBottom ] .
| `Ratio of [ `Float of float | `Fill | `Compress| `Auto ]
(** Sets the aspect ratio. *)
| `Samplepoints of int
* Number of points used to represent ellipses and circles on output .
Default value is [ 8 ] .
Default value is [8]. *)
| `Url of string
(** URL associated with graph (format-dependent). *)
]
* Attributes of nodes . They include all common node attributes and
several specific ones . All attributes described in the " dot User 's
Manual , February 4 , 2002 " are handled , excepted : bottomlabel , group ,
shapefile and toplabel .
several specific ones. All attributes described in the "dot User's
Manual, February 4, 2002" are handled, excepted: bottomlabel, group,
shapefile and toplabel. *)
type vertex =
[ CommonAttributes.vertex
| `Comment of string
(** Comment string. *)
| `Distortion of float
(* TEMPORARY *)
| `Fillcolor of color
(** Sets the fill color (used when `Style filled). Default value
is [lightgrey]. *)
| `FillcolorWithTransparency of color_with_transparency
(** Sets the fill color (used when `Style filled) with a transparency
component. Default value is fully opaque [lightgrey]. *)
| `Fixedsize of bool
(** If [true], forces the given dimensions to be the actual ones.
Default value is [false]. *)
| `Layer of string
(** Overlay. *)
| `Url of string
(** The default url for image map files; in PostScript files,
the base URL for all relative URLs, as recognized by Acrobat
Distiller 3.0 and up. *)
| `Z of float
* z coordinate for VRML output .
]
* Attributes of edges . They include all common edge attributes and
several specific ones . All attributes described in the " dot User 's
Manual , February 4 , 2002 " are handled , excepted : and .
several specific ones. All attributes described in the "dot User's
Manual, February 4, 2002" are handled, excepted: lhead and ltail. *)
type edge =
[ CommonAttributes.edge
| `Arrowhead of arrow_style
(** Sets the style of the head arrow. Default value is [`Normal]. *)
| `Arrowsize of float
* Sets the scaling factor of arrowheads . Default value is [ 1.0 ] .
| `Arrowtail of arrow_style
(** Sets the style of the tail arrow. Default value is [`Normal]. *)
| `Comment of string
(** Comment string. *)
| `Constraint of bool
(** If [false], causes an edge to be ignored for rank assignment.
Default value is [true]. *)
| `Headlabel of string
(** Sets the label attached to the head arrow. *)
| `Headport of [ `N | `NE | `E | `SE | `S | `SW | `W | `NW ]
(* TEMPORARY *)
| `Headurl of string
(** Url attached to head label if output format is ismap. *)
| `Labelangle of float
(** Angle in degrees which head or tail label is rotated off edge.
Default value is [-25.0]. *)
| `Labeldistance of float
* Scaling factor for distance of head or tail label from node .
Default value is [ 1.0 ] .
Default value is [1.0]. *)
| `Labelfloat of bool
(** If [true], lessen constraints on edge label placement.
Default value is [false]. *)
| `Layer of string
(** Overlay. *)
| `Minlen of int
* Minimum rank distance between head an tail .
Default value is [ 1 ] .
Default value is [1]. *)
| `Samehead of string
(** Tag for head node; edge heads with the same tag are merged onto the
same port. *)
| `Sametail of string
(** Tag for tail node; edge tails with the same tag are merged onto the
same port. *)
| `Taillabel of string
(** Sets the label attached to the tail arrow. *)
| `Tailport of [ `N | `NE | `E | `SE | `S | `SW | `W | `NW ]
(* TEMPORARY *)
| `Tailurl of string
(** Url attached to tail label if output format is ismap. *)
| `Weight of int
* Sets the integer cost of stretching the edge . Default value is
[ 1 ] .
[1]. *)
]
(** Subgraphs have a name and some vertices. *)
type subgraph = {
sg_name : string;
sg_attributes : vertex list;
sg_parent : string option;
}
end
(** Graph module with dot attributes *)
module type GraphWithDotAttrs = sig
include Sig.G
val graph_attributes: t -> DotAttributes.graph list
* Vertex attributes
val default_vertex_attributes: t -> DotAttributes.vertex list
val vertex_name : V.t -> string
val vertex_attributes: V.t -> DotAttributes.vertex list
(** Edge attributes *)
val default_edge_attributes: t -> DotAttributes.edge list
val edge_attributes: E.t -> DotAttributes.edge list
val get_subgraph : V.t -> DotAttributes.subgraph option
(** The box (if exists) which the vertex belongs to. Boxes with same
names are not distinguished and so they should have the same
attributes. *)
end
module Dot
(X : sig
(** Graph implementation. Sub-signature of {!Sig.G} *)
type t
module V : sig type t end
module E : sig type t val src : t -> V.t val dst : t -> V.t end
val iter_vertex : (V.t -> unit) -> t -> unit
val iter_edges_e : (E.t -> unit) -> t -> unit
(** Graph, vertex and edge attributes. *)
val graph_attributes: t -> DotAttributes.graph list
val default_vertex_attributes: t -> DotAttributes.vertex list
val vertex_name : V.t -> string
val vertex_attributes: V.t -> DotAttributes.vertex list
val get_subgraph : V.t -> DotAttributes.subgraph option
(** The box (if exists) which the vertex belongs to. Boxes with same
names are not distinguished and so they should have the same
attributes. *)
val default_edge_attributes: t -> DotAttributes.edge list
val edge_attributes: E.t -> DotAttributes.edge list
end) :
sig
val fprint_graph: formatter -> X.t -> unit
(** [fprint_graph ppf graph] pretty prints the graph [graph] in
the CGL language on the formatter [ppf]. *)
val output_graph: out_channel -> X.t -> unit
(** [output_graph oc graph] pretty prints the graph [graph] in the dot
language on the channel [oc]. *)
end
(***************************************************************************)
* { 2 The neato engine }
module NeatoAttributes : sig
* Attributes of graphs . They include all common graph attributes and
several specific ones . All attributes described in the " Neato User 's
manual , April 10 , 2002 " are handled .
several specific ones. All attributes described in the "Neato User's
manual, April 10, 2002" are handled. *)
type graph =
[ CommonAttributes.graph
| `Margin of float * float
* Sets the page margin ( included in the page size ) . Default value is
[ 0.5 , 0.5 ] .
[0.5, 0.5]. *)
| `Start of int
(** Seed for random number generator. *)
| `Overlap of bool
(** Default value is [true]. *)
| `Spline of bool
(** [true] makes edge splines if nodes don't overlap.
Default value is [false]. *)
| `Sep of float
* Edge spline separation factor from nodes . Default value
is [ 0.0 ] .
is [0.0]. *)
]
* Attributes of nodes . They include all common node attributes and
several specific ones . All attributes described in the " Neato User 's
manual , April 10 , 2002 " are handled .
several specific ones. All attributes described in the "Neato User's
manual, April 10, 2002" are handled. *)
type vertex =
[ CommonAttributes.vertex
| `Pos of float * float
(** Initial coordinates of the vertex. *)
]
* Attributes of edges . They include all common edge attributes and
several specific ones . All attributes described in the " Neato User 's
manual , April 10 , 2002 " are handled .
several specific ones. All attributes described in the "Neato User's
manual, April 10, 2002" are handled. *)
type edge =
[ CommonAttributes.edge
| `Id of string
(** Optional value to distinguish multiple edges. *)
| `Len of float
* Preferred length of edge . Default value is [ 1.0 ] .
| `Weight of float
* Strength of edge spring . Default value is [ 1.0 ] .
]
(** Subgraphs have a name and some vertices. *)
type subgraph = {
sg_name : string;
sg_attributes : vertex list;
sg_parent : string option;
}
end
module Neato
(X : sig
(** Graph implementation. Sub-signature of {!Sig.G}. *)
type t
module V : sig type t end
module E : sig type t val src : t -> V.t val dst : t -> V.t end
val iter_vertex : (V.t -> unit) -> t -> unit
val iter_edges_e : (E.t -> unit) -> t -> unit
(** Graph, vertex and edge attributes. *)
val graph_attributes: t -> NeatoAttributes.graph list
val default_vertex_attributes: t -> NeatoAttributes.vertex list
val vertex_name : V.t -> string
val vertex_attributes: V.t -> NeatoAttributes.vertex list
val get_subgraph : V.t -> NeatoAttributes.subgraph option
(** The box (if exists) which the vertex belongs to. Boxes with same
names are not distinguished and so they should have the same
attributes. *)
val default_edge_attributes: t -> NeatoAttributes.edge list
val edge_attributes: E.t -> NeatoAttributes.edge list
end) :
sig
val set_command: string -> unit
(** Several functions provided by this module run the external program
{i neato}. By default, this command is supposed to be in the default
path and is invoked by {i neato}. The function
[set_command] allows to set an alternative path at run time. *)
exception Error of string
val handle_error: ('a -> 'b) -> 'a -> 'b
val fprint_graph: formatter -> X.t -> unit
(** [fprint_graph ppf graph] pretty prints the graph [graph] in
the CGL language on the formatter [ppf]. *)
val output_graph: out_channel -> X.t -> unit
(** [output_graph oc graph] pretty prints the graph [graph] in the dot
language on the channel [oc]. *)
end
(*
Local Variables:
compile-command: "make -C .."
End:
*)
| null | https://raw.githubusercontent.com/backtracking/ocamlgraph/1c028af097339ca8bc379436f7bd9477fa3a49cd/src/graphviz.mli | ocaml | ************************************************************************
This software is free software; you can redistribute it and/or
described in file LICENSE.
This software 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.
************************************************************************
*************************************************************************
-------------------------------------------------------------------------
* The [ATTRIBUTES] module type defines the interface for the engines.
* Attributes of graphs.
* Attributes of vertices.
* Attributes of edges.
* Attributes of (optional) boxes around vertices.
* Box name.
* Box attributes.
* Nested subgraphs.
-------------------------------------------------------------------------
* Attributes of graphs.
* Centers the drawing on the page. Default value is [false].
* Sets the font color. Default value is [black].
* Sets the font family name. Default value is ["Times-Roman"].
* Caption for graph drawing.
* Sets the page orientation. Default value is [`Portrait].
* Sets the bounding box of drawing (in inches).
* Constrains order of out-edges in a subgraph according to
their file sequence
* Attributes of vertices.
* Sets the color of the border of the vertex.
Default value is [black]
* Sets the color of the border of the vertex with a transparency
component. Default value is fully opaque [black]
* Sets the label font color. Default value is [black].
* Sets the label font family name. Default value is
["Times-Roman"].
* Sets the number of periphery lines drawn around the polygon.
* If [true], then the polygon is made regular, i.e. symmetric about
the x and y axis, otherwise the polygon takes on the aspect
ratio of the label. Default value is [false].
Addition through
Addition ends here
* Sets the layout style of the vertex.
Several styles may be combined simultaneously.
* Attributes of edges.
* Sets the edge stroke color. Default value is [black].
* Sets the edge stroke color with a transparency
component. Default value is fully opaque [black]
* If [true], draws a line connecting labels with their edges.
* Sets arrow direction. Default value is [`Forward].
* Sets the label font color. Default value is [black].
* Sets the label font family name. Default value is
["Times-Roman"].
* Sets the font color for head and tail labels. Default value is
[black].
* Sets the font family name for head and tail labels. Default
value is ["Times-Roman"].
* Sets the layout style of the edge. Several styles may be combined
simultaneously.
*************************************************************************
* {2 Interface with the dot engine}
* [DotAttributes] extends [CommonAttributes] and implements [ATTRIBUTES].
* Sets the background color and the inital fill color.
* Sets the background color and the inital fill color with
a transparency component.
* Comment string.
* If [true], enables edge concentrators. Default value is [false].
* List of directories for fonts.
* List of layers.
* If set of [f], bounds network simplex iterations by [f *
<number of nodes>] when ranking nodes.
* If set of [f], bounds network simplex iterations by [f *
<number of nodes>] when setting x-coordinates.
* Sets the minimum separation between ranks.
* Sets the aspect ratio.
* URL associated with graph (format-dependent).
* Comment string.
TEMPORARY
* Sets the fill color (used when `Style filled). Default value
is [lightgrey].
* Sets the fill color (used when `Style filled) with a transparency
component. Default value is fully opaque [lightgrey].
* If [true], forces the given dimensions to be the actual ones.
Default value is [false].
* Overlay.
* The default url for image map files; in PostScript files,
the base URL for all relative URLs, as recognized by Acrobat
Distiller 3.0 and up.
* Sets the style of the head arrow. Default value is [`Normal].
* Sets the style of the tail arrow. Default value is [`Normal].
* Comment string.
* If [false], causes an edge to be ignored for rank assignment.
Default value is [true].
* Sets the label attached to the head arrow.
TEMPORARY
* Url attached to head label if output format is ismap.
* Angle in degrees which head or tail label is rotated off edge.
Default value is [-25.0].
* If [true], lessen constraints on edge label placement.
Default value is [false].
* Overlay.
* Tag for head node; edge heads with the same tag are merged onto the
same port.
* Tag for tail node; edge tails with the same tag are merged onto the
same port.
* Sets the label attached to the tail arrow.
TEMPORARY
* Url attached to tail label if output format is ismap.
* Subgraphs have a name and some vertices.
* Graph module with dot attributes
* Edge attributes
* The box (if exists) which the vertex belongs to. Boxes with same
names are not distinguished and so they should have the same
attributes.
* Graph implementation. Sub-signature of {!Sig.G}
* Graph, vertex and edge attributes.
* The box (if exists) which the vertex belongs to. Boxes with same
names are not distinguished and so they should have the same
attributes.
* [fprint_graph ppf graph] pretty prints the graph [graph] in
the CGL language on the formatter [ppf].
* [output_graph oc graph] pretty prints the graph [graph] in the dot
language on the channel [oc].
*************************************************************************
* Seed for random number generator.
* Default value is [true].
* [true] makes edge splines if nodes don't overlap.
Default value is [false].
* Initial coordinates of the vertex.
* Optional value to distinguish multiple edges.
* Subgraphs have a name and some vertices.
* Graph implementation. Sub-signature of {!Sig.G}.
* Graph, vertex and edge attributes.
* The box (if exists) which the vertex belongs to. Boxes with same
names are not distinguished and so they should have the same
attributes.
* Several functions provided by this module run the external program
{i neato}. By default, this command is supposed to be in the default
path and is invoked by {i neato}. The function
[set_command] allows to set an alternative path at run time.
* [fprint_graph ppf graph] pretty prints the graph [graph] in
the CGL language on the formatter [ppf].
* [output_graph oc graph] pretty prints the graph [graph] in the dot
language on the channel [oc].
Local Variables:
compile-command: "make -C .."
End:
| : a generic graph library for OCaml
Copyright ( C ) 2004 - 2010
, and
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
* Interface with { i GraphViz }
This module provides a basic interface with dot and neato ,
two programs of the GraphViz toolbox .
These tools are available at the following URLs :
- { v v }
- { v v }
This module provides a basic interface with dot and neato,
two programs of the GraphViz toolbox.
These tools are available at the following URLs:
- {v v}
- {v v} *)
open Format
* { 2 Common stuff }
* Because the neato and dot engines present a lot of common points -
in particular in the graph description language , large parts of
the code is shared . The [ CommonAttributes ] module defines
attributes of graphs , vertices and edges that are understood by the
two engines . Then module [ DotAttributes ] and [ NeatoAttributes ]
define attributes specific to dot and neato respectively .
in particular in the graph description language, large parts of
the code is shared. The [CommonAttributes] module defines
attributes of graphs, vertices and edges that are understood by the
two engines. Then module [DotAttributes] and [NeatoAttributes]
define attributes specific to dot and neato respectively. *)
* { 3 Common types and signatures }
type color = int
type color_with_transparency = int32
* The two least significant bytes encode the transparency information ;
the six most signification are the standard RGB color
the six most signification are the standard RGB color *)
val color_to_color_with_transparency: color -> color_with_transparency
type arrow_style =
[ `None | `Normal | `Onormal | `Inv | `Dot | `Odot | `Invdot | `Invodot ]
module type ATTRIBUTES = sig
type subgraph = {
}
end
* { 3 Common attributes }
* The [ CommonAttributes ] module defines attributes for graphs , vertices and
edges that are available in the two engines , dot and neato .
edges that are available in the two engines, dot and neato. *)
module CommonAttributes : sig
type graph =
[ `Center of bool
| `Fontcolor of color
| `Fontname of string
| `Fontsize of int
* Sets the type size ( in points ) . Default value is [ 14 ] .
| `Label of string
| `HtmlLabel of string
* Caption for graph drawing . In HTML strings , angle brackets must occur in
matched pairs , and newlines and other formatting whitespace characters
are allowed . In addition , the content must be legal XML , so that the
special XML escape sequences for " , & , < , and > may be necessary in
order to embed these characters in attribute values or raw text . "
matched pairs, and newlines and other formatting whitespace characters
are allowed. In addition, the content must be legal XML, so that the
special XML escape sequences for ", &, <, and > may be necessary in
order to embed these characters in attribute values or raw text." *)
| `Orientation of [ `Portrait | `Landscape ]
| `Page of float * float
* Sets the PostScript pagination unit , e.g [ 8.5 , 11.0 ] .
| `Pagedir of [ `TopToBottom | `LeftToRight ]
* Traversal order of pages . Default value is [ ` TopToBottom ] .
| `Size of float * float
| `OrderingOut
]
type vertex =
[ `Color of color
| `ColorWithTransparency of color_with_transparency
| `Fontcolor of color
| `Fontname of string
| `Fontsize of int
* Sets the label type size ( in points ) . Default value is [ 14 ] .
*)
| `Height of float
* Sets the minimum height . Default value is [ 0.5 ] .
| `Label of string
* Sets the label printed in the vertex .
The string may include escaped
newlines [ \n ] , [ \l ] , or [ \r ] for center , left , and right justified
lines .
Record labels may contain recursive box lists delimited by { | } .
The string may include escaped
newlines [\n], [\l], or [\r] for center, left, and right justified
lines.
Record labels may contain recursive box lists delimited by { | }.
*)
| `HtmlLabel of string
* Like label , in html style . In HTML strings , angle brackets must occur in
matched pairs , and newlines and other formatting whitespace characters
are allowed . In addition , the content must be legal XML , so that the
special XML escape sequences for " , & , < , and > may be necessary in
order to embed these characters in attribute values or raw text . "
matched pairs, and newlines and other formatting whitespace characters
are allowed. In addition, the content must be legal XML, so that the
special XML escape sequences for ", &, <, and > may be necessary in
order to embed these characters in attribute values or raw text." *)
| `Orientation of float
* Vertex rotation angle , in degrees . Default value is [ 0.0 ] .
| `Penwidth of float
* Width of the pen ( in points ) used to draw the border of the node .
Default value is [ 1.0 ] .
Default value is [1.0]. *)
| `Peripheries of int
| `Regular of bool
| `Shape of
[`Ellipse | `Box | `Circle | `Doublecircle | `Diamond
| `Plaintext | `Record
| `Oval | `Egg | `Triangle | `Invtriangle
| `Trapezium | `Invtrapezium
| `House | `Invhouse
| `Parallelogram | `Doubleoctagon | `Tripleoctagon
| `Mdiamond | `Mcircle | `Msquare
| `Star | `Underline
| `Note | `Tab | `Folder
| `Box3d | `Component | `Promoter
| `Cds
| `Terminator | `Utr | `Primersite
| `Restrictionsite
| `Fivepoverhang | `Threepoverhang | `Noverhang
| `Assembly | `Signature | `Insulator | `Ribosite | `Rnastab
| `Proteasesite | `Proteinstab | `Rpromoter | `Rarrow
| `Larrow | `Lpromoter
| `Polygon of int * float]
* Sets the shape of the vertex . Default value is [ ` Ellipse ] .
[ ` Polygon ( i , f ) ] draws a polygon with [ n ] sides and a skewing
of [ f ] .
[`Polygon (i, f)] draws a polygon with [n] sides and a skewing
of [f]. *)
| `Style of
[ `Rounded | `Filled | `Solid | `Dashed | `Dotted | `Bold | `Invis ]
| `Width of float
* Sets the minimum width . Default value is [ 0.75 ] .
]
type edge =
[ `Color of color
| `ColorWithTransparency of color_with_transparency
| `Decorate of bool
| `Dir of [ `Forward | `Back | `Both | `None ]
| `Fontcolor of color
| `Fontname of string
| `Fontsize of int
* Sets the label type size ( in points ) . Default value is [ 14 ] .
| `Label of string
* Sets the label to be attached to the edge . The string may include
escaped newlines [ \n ] , [ \l ] , or [ \r ] for centered , left , or right
justified lines .
escaped newlines [\n], [\l], or [\r] for centered, left, or right
justified lines. *)
| `HtmlLabel of string
* Like label , in html style . In HTML strings , angle brackets must occur in
matched pairs , and newlines and other formatting whitespace characters
are allowed . In addition , the content must be legal XML , so that the
special XML escape sequences for " , & , < , and > may be necessary in
order to embed these characters in attribute values or raw text . "
matched pairs, and newlines and other formatting whitespace characters
are allowed. In addition, the content must be legal XML, so that the
special XML escape sequences for ", &, <, and > may be necessary in
order to embed these characters in attribute values or raw text." *)
| `Labelfontcolor of color
| `Labelfontname of string
| `Labelfontsize of int
* Sets the font size for head and tail labels ( in points ) .
Default value is [ 14 ] .
Default value is [14]. *)
| `Penwidth of float
* Width of the pen ( in points ) used to draw the edge . Default value
is [ 1.0 ] .
is [1.0]. *)
| `Style of [ `Solid | `Dashed | `Dotted | `Bold | `Invis ]
]
end
module DotAttributes : sig
* Attributes of graphs . They include all common graph attributes and
several specific ones . All attributes described in the " dot User 's
Manual , February 4 , 2002 " are handled , excepted : clusterank , color ,
compound , labeljust , labelloc , ordering , rank , remincross , rotate ,
searchsize and style .
several specific ones. All attributes described in the "dot User's
Manual, February 4, 2002" are handled, excepted: clusterank, color,
compound, labeljust, labelloc, ordering, rank, remincross, rotate,
searchsize and style. *)
type graph =
[ CommonAttributes.graph
| `Bgcolor of color
| `BgcolorWithTransparency of color_with_transparency
| `Comment of string
| `Concentrate of bool
| `Fontpath of string
| `Layers of string list
| `Margin of float
* Sets the page margin ( included in the page size ) . Default value is
[ 0.5 ] .
[0.5]. *)
| `Mclimit of float
* Scale factor for mincross iterations . Default value is [ 1.0 ] .
| `Nodesep of float
* Sets the minimum separation between nodes , in inches . Default
value is [ 0.25 ] .
value is [0.25]. *)
| `Nslimit of int
| `Nslimit1 of int
| `Ranksep of float
| `Quantum of float
* If not [ 0.0 ] , node label dimensions will be rounded to integral
multiples of it . Default value is [ 0.0 ] .
multiples of it. Default value is [0.0]. *)
| `Rankdir of [ `TopToBottom | `BottomToTop | `LeftToRight | `RightToLeft ]
* Direction of rank ordering . Default value is [ ` TopToBottom ] .
| `Ratio of [ `Float of float | `Fill | `Compress| `Auto ]
| `Samplepoints of int
* Number of points used to represent ellipses and circles on output .
Default value is [ 8 ] .
Default value is [8]. *)
| `Url of string
]
* Attributes of nodes . They include all common node attributes and
several specific ones . All attributes described in the " dot User 's
Manual , February 4 , 2002 " are handled , excepted : bottomlabel , group ,
shapefile and toplabel .
several specific ones. All attributes described in the "dot User's
Manual, February 4, 2002" are handled, excepted: bottomlabel, group,
shapefile and toplabel. *)
type vertex =
[ CommonAttributes.vertex
| `Comment of string
| `Distortion of float
| `Fillcolor of color
| `FillcolorWithTransparency of color_with_transparency
| `Fixedsize of bool
| `Layer of string
| `Url of string
| `Z of float
* z coordinate for VRML output .
]
* Attributes of edges . They include all common edge attributes and
several specific ones . All attributes described in the " dot User 's
Manual , February 4 , 2002 " are handled , excepted : and .
several specific ones. All attributes described in the "dot User's
Manual, February 4, 2002" are handled, excepted: lhead and ltail. *)
type edge =
[ CommonAttributes.edge
| `Arrowhead of arrow_style
| `Arrowsize of float
* Sets the scaling factor of arrowheads . Default value is [ 1.0 ] .
| `Arrowtail of arrow_style
| `Comment of string
| `Constraint of bool
| `Headlabel of string
| `Headport of [ `N | `NE | `E | `SE | `S | `SW | `W | `NW ]
| `Headurl of string
| `Labelangle of float
| `Labeldistance of float
* Scaling factor for distance of head or tail label from node .
Default value is [ 1.0 ] .
Default value is [1.0]. *)
| `Labelfloat of bool
| `Layer of string
| `Minlen of int
* Minimum rank distance between head an tail .
Default value is [ 1 ] .
Default value is [1]. *)
| `Samehead of string
| `Sametail of string
| `Taillabel of string
| `Tailport of [ `N | `NE | `E | `SE | `S | `SW | `W | `NW ]
| `Tailurl of string
| `Weight of int
* Sets the integer cost of stretching the edge . Default value is
[ 1 ] .
[1]. *)
]
type subgraph = {
sg_name : string;
sg_attributes : vertex list;
sg_parent : string option;
}
end
module type GraphWithDotAttrs = sig
include Sig.G
val graph_attributes: t -> DotAttributes.graph list
* Vertex attributes
val default_vertex_attributes: t -> DotAttributes.vertex list
val vertex_name : V.t -> string
val vertex_attributes: V.t -> DotAttributes.vertex list
val default_edge_attributes: t -> DotAttributes.edge list
val edge_attributes: E.t -> DotAttributes.edge list
val get_subgraph : V.t -> DotAttributes.subgraph option
end
module Dot
(X : sig
type t
module V : sig type t end
module E : sig type t val src : t -> V.t val dst : t -> V.t end
val iter_vertex : (V.t -> unit) -> t -> unit
val iter_edges_e : (E.t -> unit) -> t -> unit
val graph_attributes: t -> DotAttributes.graph list
val default_vertex_attributes: t -> DotAttributes.vertex list
val vertex_name : V.t -> string
val vertex_attributes: V.t -> DotAttributes.vertex list
val get_subgraph : V.t -> DotAttributes.subgraph option
val default_edge_attributes: t -> DotAttributes.edge list
val edge_attributes: E.t -> DotAttributes.edge list
end) :
sig
val fprint_graph: formatter -> X.t -> unit
val output_graph: out_channel -> X.t -> unit
end
* { 2 The neato engine }
module NeatoAttributes : sig
* Attributes of graphs . They include all common graph attributes and
several specific ones . All attributes described in the " Neato User 's
manual , April 10 , 2002 " are handled .
several specific ones. All attributes described in the "Neato User's
manual, April 10, 2002" are handled. *)
type graph =
[ CommonAttributes.graph
| `Margin of float * float
* Sets the page margin ( included in the page size ) . Default value is
[ 0.5 , 0.5 ] .
[0.5, 0.5]. *)
| `Start of int
| `Overlap of bool
| `Spline of bool
| `Sep of float
* Edge spline separation factor from nodes . Default value
is [ 0.0 ] .
is [0.0]. *)
]
* Attributes of nodes . They include all common node attributes and
several specific ones . All attributes described in the " Neato User 's
manual , April 10 , 2002 " are handled .
several specific ones. All attributes described in the "Neato User's
manual, April 10, 2002" are handled. *)
type vertex =
[ CommonAttributes.vertex
| `Pos of float * float
]
* Attributes of edges . They include all common edge attributes and
several specific ones . All attributes described in the " Neato User 's
manual , April 10 , 2002 " are handled .
several specific ones. All attributes described in the "Neato User's
manual, April 10, 2002" are handled. *)
type edge =
[ CommonAttributes.edge
| `Id of string
| `Len of float
* Preferred length of edge . Default value is [ 1.0 ] .
| `Weight of float
* Strength of edge spring . Default value is [ 1.0 ] .
]
type subgraph = {
sg_name : string;
sg_attributes : vertex list;
sg_parent : string option;
}
end
module Neato
(X : sig
type t
module V : sig type t end
module E : sig type t val src : t -> V.t val dst : t -> V.t end
val iter_vertex : (V.t -> unit) -> t -> unit
val iter_edges_e : (E.t -> unit) -> t -> unit
val graph_attributes: t -> NeatoAttributes.graph list
val default_vertex_attributes: t -> NeatoAttributes.vertex list
val vertex_name : V.t -> string
val vertex_attributes: V.t -> NeatoAttributes.vertex list
val get_subgraph : V.t -> NeatoAttributes.subgraph option
val default_edge_attributes: t -> NeatoAttributes.edge list
val edge_attributes: E.t -> NeatoAttributes.edge list
end) :
sig
val set_command: string -> unit
exception Error of string
val handle_error: ('a -> 'b) -> 'a -> 'b
val fprint_graph: formatter -> X.t -> unit
val output_graph: out_channel -> X.t -> unit
end
|
7f59c275cd6e7cafd4e5bd01b4fe0278c2dc638c1e0d6ff9c5c521d02daeeb45 | reactiveml/rml | asynchrone_yield.ml | open Misc
let brush draw p () =
let st = new_state p in
while true do
move draw st;
Thread.yield ()
done
let main () =
let draw = init () in
let t1 = Thread.create (brush draw p1) ()
and t2 = Thread.create (brush draw p2) () in
Thread.join t1; Thread.join t2
let _ =
main ()
| null | https://raw.githubusercontent.com/reactiveml/rml/d178d49ed923290fa7eee642541bdff3ee90b3b4/examples-extra/rml_peintres/asynchrone_yield.ml | ocaml | open Misc
let brush draw p () =
let st = new_state p in
while true do
move draw st;
Thread.yield ()
done
let main () =
let draw = init () in
let t1 = Thread.create (brush draw p1) ()
and t2 = Thread.create (brush draw p2) () in
Thread.join t1; Thread.join t2
let _ =
main ()
| |
232c2c3cef984164c0b0045321f148705ecd2d24b5afed20df43a90272931cc8 | edgecase/dieter | precompile.clj | (ns dieter.test.precompile
(:require [dieter.core :as core]
[dieter.precompile :as precompile]
[dieter.settings :as settings]
[dieter.cache :as cache]
[clojure.java.io :as io])
(:use clojure.test
ring.mock.request))
(deftest precompile-roundtrip-works
(let [options {:engine :v8
:compress false
:log-level :quiet
:asset-root "test/fixtures"
:cache-root "test/precompile-cache"
:cache-mode :production
:precompiles ["javascripts/app.js"]}]
clear first
(settings/with-options options
(precompile/precompile options)
(precompile/load-precompiled-assets)
(is (= (keys @cache/cached-uris)
(map #(str "/assets/" %)
(:precompiles options))))))) | null | https://raw.githubusercontent.com/edgecase/dieter/f3c7cdd7703c6d1556e68bbe8fc94406b717f6f1/dieter-core/test/dieter/test/precompile.clj | clojure | (ns dieter.test.precompile
(:require [dieter.core :as core]
[dieter.precompile :as precompile]
[dieter.settings :as settings]
[dieter.cache :as cache]
[clojure.java.io :as io])
(:use clojure.test
ring.mock.request))
(deftest precompile-roundtrip-works
(let [options {:engine :v8
:compress false
:log-level :quiet
:asset-root "test/fixtures"
:cache-root "test/precompile-cache"
:cache-mode :production
:precompiles ["javascripts/app.js"]}]
clear first
(settings/with-options options
(precompile/precompile options)
(precompile/load-precompiled-assets)
(is (= (keys @cache/cached-uris)
(map #(str "/assets/" %)
(:precompiles options))))))) | |
3c1326958bd2f163d372555194712decf5551ff76db9a234fb9bef2a3d8508f2 | alasconnect/reflex-material | Checkbox.hs | {-# LANGUAGE OverloadedStrings #-}
module Reflex.Material.Checkbox
( checkbox'_
) where
import Data.Map
import Data.Monoid ((<>))
import Data.Text (Text)
import Reflex.Dom
import Reflex.Material.Types
checkbox'_ :: DomBuilder t m => Enabled -> Selected -> Text -> m (Element EventResult (DomBuilderSpace m) t, ())
checkbox'_ e s v =
elClass "div" (toClass e) $ do
x <- elAttr' "input" ( disabledAttr e $
selectedAttr s $
checkboxAttrs v
) blank
elClass "div" "mdc-checkbox__background" $ do
elAttr "svg" ("class" =: "mdc-checkbox__checkmark" <> "viewBox" =: "0 0 24 24") $
elAttr "path" ("class" =: "mdc-checkbox__checkmark__path" <> "stroke" =: "white" <> "fill" =: "none" <> "d" =: "M1.73,12.91 8.1,19.28 22.79,4.59") blank
elClass "div" "mdc-checkbox__mixedmark" blank
return x
toClass :: Enabled -> Text
toClass Enabled = "mdc-checkbox"
toClass Disabled = "mdc-checkbox mdc-checkbox--disabled"
disabledAttr :: Enabled -> Map Text Text -> Map Text Text
disabledAttr Disabled m = m <> ("disabled" =: "disabled")
disabledAttr Enabled m = m
selectedAttr :: Selected -> Map Text Text -> Map Text Text
selectedAttr Selected m = m <> ("checked" =: "checked")
selectedAttr NotSelected m = m
checkboxAttrs :: Text -> Map Text Text
checkboxAttrs v = "value" =: v <>
"type" =: "checkbox" <>
"class" =: "mdc-checkbox__native-control"
| null | https://raw.githubusercontent.com/alasconnect/reflex-material/0e8ef843a570378ebaf2449b8c4b72616e25f70c/src/Reflex/Material/Checkbox.hs | haskell | # LANGUAGE OverloadedStrings # |
module Reflex.Material.Checkbox
( checkbox'_
) where
import Data.Map
import Data.Monoid ((<>))
import Data.Text (Text)
import Reflex.Dom
import Reflex.Material.Types
checkbox'_ :: DomBuilder t m => Enabled -> Selected -> Text -> m (Element EventResult (DomBuilderSpace m) t, ())
checkbox'_ e s v =
elClass "div" (toClass e) $ do
x <- elAttr' "input" ( disabledAttr e $
selectedAttr s $
checkboxAttrs v
) blank
elClass "div" "mdc-checkbox__background" $ do
elAttr "svg" ("class" =: "mdc-checkbox__checkmark" <> "viewBox" =: "0 0 24 24") $
elAttr "path" ("class" =: "mdc-checkbox__checkmark__path" <> "stroke" =: "white" <> "fill" =: "none" <> "d" =: "M1.73,12.91 8.1,19.28 22.79,4.59") blank
elClass "div" "mdc-checkbox__mixedmark" blank
return x
toClass :: Enabled -> Text
toClass Enabled = "mdc-checkbox"
toClass Disabled = "mdc-checkbox mdc-checkbox--disabled"
disabledAttr :: Enabled -> Map Text Text -> Map Text Text
disabledAttr Disabled m = m <> ("disabled" =: "disabled")
disabledAttr Enabled m = m
selectedAttr :: Selected -> Map Text Text -> Map Text Text
selectedAttr Selected m = m <> ("checked" =: "checked")
selectedAttr NotSelected m = m
checkboxAttrs :: Text -> Map Text Text
checkboxAttrs v = "value" =: v <>
"type" =: "checkbox" <>
"class" =: "mdc-checkbox__native-control"
|
0914d6abdb9a2fd22d06824d00b6ed123075762e220110fc23ce36583567d3d7 | Lambda-X/re-console | io.cljs | (ns re-console.io
(:import [goog.events EventType]
[goog.net XhrIo]))
(defn fetch-file!
"Very simple implementation of XMLHttpRequests that given a file path
calls src-cb with the string fetched of nil in case of error.
See doc at "
[file-url src-cb]
(try
(.send XhrIo file-url
(fn [e]
(if (.isSuccess (.-target e))
(src-cb (.. e -target getResponseText))
(src-cb nil))))
(catch :default e
(src-cb nil))))
| null | https://raw.githubusercontent.com/Lambda-X/re-console/a7a31046ba5066163d46ac586072c92b7414c52b/demo/re_console/io.cljs | clojure | (ns re-console.io
(:import [goog.events EventType]
[goog.net XhrIo]))
(defn fetch-file!
"Very simple implementation of XMLHttpRequests that given a file path
calls src-cb with the string fetched of nil in case of error.
See doc at "
[file-url src-cb]
(try
(.send XhrIo file-url
(fn [e]
(if (.isSuccess (.-target e))
(src-cb (.. e -target getResponseText))
(src-cb nil))))
(catch :default e
(src-cb nil))))
| |
5cc1073e3667c59c40facc304164d6ec21736b862a146607b6cb00cadd48a854 | xapi-project/xen-api | sexprpp.ml |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
let lexer = Lexing.from_channel stdin
let _ =
match Sys.argv with
| [|_; "-nofmt"|] ->
let start_time = Sys.time () in
let sexpr = SExprParser.expr SExprLexer.token lexer in
let parse_time = Sys.time () in
let s = SExpr.string_of sexpr in
let print_time = Sys.time () in
Printf.fprintf stderr "Parse time: %f\nPrint time: %f\n%!"
(parse_time -. start_time) (print_time -. parse_time) ;
print_endline s
| _ ->
let sexpr = SExprParser.expr SExprLexer.token lexer in
let ff = Format.formatter_of_out_channel stdout in
SExpr.output_fmt ff sexpr ; Format.fprintf ff "@."
| null | https://raw.githubusercontent.com/xapi-project/xen-api/5c9c44c6d40a9930f454722c9cd09c7079ec814e/ocaml/libs/sexpr/sexprpp.ml | ocaml |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
let lexer = Lexing.from_channel stdin
let _ =
match Sys.argv with
| [|_; "-nofmt"|] ->
let start_time = Sys.time () in
let sexpr = SExprParser.expr SExprLexer.token lexer in
let parse_time = Sys.time () in
let s = SExpr.string_of sexpr in
let print_time = Sys.time () in
Printf.fprintf stderr "Parse time: %f\nPrint time: %f\n%!"
(parse_time -. start_time) (print_time -. parse_time) ;
print_endline s
| _ ->
let sexpr = SExprParser.expr SExprLexer.token lexer in
let ff = Format.formatter_of_out_channel stdout in
SExpr.output_fmt ff sexpr ; Format.fprintf ff "@."
| |
eacdebe4cf364d48ab9bfd8db911f0fffa2582a47a390c7549af54cb65f53c2b | realworldocaml/book | bootstrap_info.ml | open Import
open Memo.O
let def name dyn =
let open Pp.O in
Pp.box ~indent:2 (Pp.textf "let %s = " name ++ Dyn.pp dyn)
let rule sctx compile (exes : Dune_file.Executables.t) () =
let* locals, externals =
let+ libs =
Resolve.Memo.read_memo
(Memo.Lazy.force (Lib.Compile.requires_link compile))
in
List.partition_map libs ~f:(fun lib ->
match Lib.Local.of_lib lib with
| Some x -> Left x
| None -> Right lib)
in
let link_flags =
let win_link_flags =
[ "-cclib"; "-lshell32"; "-cclib"; "-lole32"; "-cclib"; "-luuid" ]
in
(* additional link flags keyed by the platform *)
[ ( "macosx"
, [ "-cclib"
; "-framework Foundation"
; "-cclib"
; "-framework CoreServices"
] )
; ("win32", win_link_flags)
; ("win64", win_link_flags)
; ("mingw", win_link_flags)
; ("mingw64", win_link_flags)
]
in
let+ locals =
Memo.parallel_map locals ~f:(fun x ->
let info = Lib.Local.info x in
let dir = Lib_info.src_dir info in
let special_builtin_support =
match Lib_info.special_builtin_support info with
| Some (Build_info { data_module; _ }) -> Some data_module
| _ -> None
in
let+ is_multi_dir =
let+ dc = Dir_contents.get sctx ~dir in
match Dir_contents.dirs dc with
| _ :: _ :: _ -> true
| _ -> false
in
Dyn.Tuple
[ Path.Source.to_dyn (Path.Build.drop_build_context_exn dir)
; Dyn.option Module_name.to_dyn
(match Lib_info.main_module_name info with
| From _ -> None
| This x -> x)
; Dyn.Bool is_multi_dir
; Dyn.option Module_name.to_dyn special_builtin_support
])
in
Format.asprintf "%a@." Pp.to_fmt
(Pp.vbox
(Pp.concat ~sep:Pp.cut
[ def "executables"
(List
(* @@DRA Want to be using the public_name here, not the
internal name *)
(List.map ~f:(fun (_, x) -> Dyn.String x) exes.names))
; Pp.nop
; def "external_libraries"
(List
(List.map externals ~f:(fun x -> Lib.name x |> Lib_name.to_dyn)))
; Pp.nop
; def "local_libraries" (List locals)
; Pp.nop
; def "link_flags"
(let open Dyn in
list (pair string (list string)) link_flags)
]))
let gen_rules sctx (exes : Dune_file.Executables.t) ~dir compile =
Memo.Option.iter exes.bootstrap_info ~f:(fun fname ->
Super_context.add_rule sctx ~loc:exes.buildable.loc ~dir
(Action_builder.write_file_dyn
(Path.Build.relative dir fname)
(Action_builder.of_memo (Memo.return () >>= rule sctx compile exes))))
| null | https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/dune_/src/dune_rules/bootstrap_info.ml | ocaml | additional link flags keyed by the platform
@@DRA Want to be using the public_name here, not the
internal name | open Import
open Memo.O
let def name dyn =
let open Pp.O in
Pp.box ~indent:2 (Pp.textf "let %s = " name ++ Dyn.pp dyn)
let rule sctx compile (exes : Dune_file.Executables.t) () =
let* locals, externals =
let+ libs =
Resolve.Memo.read_memo
(Memo.Lazy.force (Lib.Compile.requires_link compile))
in
List.partition_map libs ~f:(fun lib ->
match Lib.Local.of_lib lib with
| Some x -> Left x
| None -> Right lib)
in
let link_flags =
let win_link_flags =
[ "-cclib"; "-lshell32"; "-cclib"; "-lole32"; "-cclib"; "-luuid" ]
in
[ ( "macosx"
, [ "-cclib"
; "-framework Foundation"
; "-cclib"
; "-framework CoreServices"
] )
; ("win32", win_link_flags)
; ("win64", win_link_flags)
; ("mingw", win_link_flags)
; ("mingw64", win_link_flags)
]
in
let+ locals =
Memo.parallel_map locals ~f:(fun x ->
let info = Lib.Local.info x in
let dir = Lib_info.src_dir info in
let special_builtin_support =
match Lib_info.special_builtin_support info with
| Some (Build_info { data_module; _ }) -> Some data_module
| _ -> None
in
let+ is_multi_dir =
let+ dc = Dir_contents.get sctx ~dir in
match Dir_contents.dirs dc with
| _ :: _ :: _ -> true
| _ -> false
in
Dyn.Tuple
[ Path.Source.to_dyn (Path.Build.drop_build_context_exn dir)
; Dyn.option Module_name.to_dyn
(match Lib_info.main_module_name info with
| From _ -> None
| This x -> x)
; Dyn.Bool is_multi_dir
; Dyn.option Module_name.to_dyn special_builtin_support
])
in
Format.asprintf "%a@." Pp.to_fmt
(Pp.vbox
(Pp.concat ~sep:Pp.cut
[ def "executables"
(List
(List.map ~f:(fun (_, x) -> Dyn.String x) exes.names))
; Pp.nop
; def "external_libraries"
(List
(List.map externals ~f:(fun x -> Lib.name x |> Lib_name.to_dyn)))
; Pp.nop
; def "local_libraries" (List locals)
; Pp.nop
; def "link_flags"
(let open Dyn in
list (pair string (list string)) link_flags)
]))
let gen_rules sctx (exes : Dune_file.Executables.t) ~dir compile =
Memo.Option.iter exes.bootstrap_info ~f:(fun fname ->
Super_context.add_rule sctx ~loc:exes.buildable.loc ~dir
(Action_builder.write_file_dyn
(Path.Build.relative dir fname)
(Action_builder.of_memo (Memo.return () >>= rule sctx compile exes))))
|
706f55ee99e48fa0b0e0a3c2f2ec5c3fe1350f1edf45d8ca573aa6f34d2eea35 | aspiwack/porcupine | PTask.hs | {-# LANGUAGE Arrows #-}
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
# LANGUAGE InstanceSigs #
# LANGUAGE TupleSections #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
# OPTIONS_GHC -Wall #
module System.TaskPipeline.PTask
( module Control.Category
, module Control.Arrow
, module Data.Locations.LogAndErrors
, PTask
, Severity(..)
, CanRunPTask
, Properties
, tryTask, throwTask, clockTask, clockTask'
, catchAndLog, throwStringTask
, toTask, toTask'
, ioTask, stepIO, stepIO'
, taskUsedFiles
, taskRequirements
, taskRunnablePart
, taskDataAccessTree
, taskInSubtree
, voidTask
, addContextToTask
, addStaticContextToTask
, addNamespaceToTask
, nameTask
, logTask
, logDebug, logInfo, logNotice, logWarning, logError
) where
import Prelude hiding (id, (.))
import Control.Arrow
import qualified Control.Arrow.Free as AF
import Control.Category
import Control.DeepSeq (NFData (..), force)
import Control.Exception (evaluate)
import Control.Funflow (Properties, stepIO,
stepIO')
import Control.Lens
import Data.Locations
import Data.Locations.LogAndErrors
import Data.String
import Katip
import System.ClockHelpers
import System.TaskPipeline.PorcupineTree
import System.TaskPipeline.PTask.Internal
-- | a tasks that discards its inputs and returns ()
voidTask :: PTask m a ()
voidTask = arr (const ())
-- | Just a shortcut for when you want an IO step that requires no input
ioTask :: (KatipContext m) => PTask m (IO a) a
ioTask = stepIO id
-- | Catches an error happening in a task. Leaves the tree intact if an error
-- occured.
tryTask
:: PTask m a b -> PTask m a (Either SomeException b)
tryTask = AF.try
-- | An version of 'tryPTask' that just logs when an error happens
catchAndLog :: (KatipContext m)
=> Severity -> PTask m a b -> PTask m a (Maybe b)
catchAndLog severity task =
tryTask task
>>> toTask (\i ->
case i of
Left e -> do
logFM severity $ logStr $ displayException (e::SomeException)
return Nothing
Right x -> return $ Just x)
-- | Fails the whole pipeline if an exception occured, or just continues as
-- normal
throwTask :: (Exception e, LogThrow m) => PTask m (Either e b) b
throwTask = arr (over _Left displayException) >>> throwStringTask
-- | Fails the whole pipeline if an exception occured, or just continues as
-- normal
throwStringTask :: (LogThrow m) => PTask m (Either String b) b
throwStringTask = toTask $ \i ->
case i of
Left e -> throwWithPrefix e
Right r -> return r
| Turn an action into a PTask . BEWARE ! The resulting ' PTask ' will have NO
-- requirements, so if the action uses files or resources, they won't appear in
the LocationTree .
toTask :: (KatipContext m)
=> (a -> m b) -> PTask m a b
toTask = makeTask mempty . const
-- | A version of 'toTask' that can perform caching. It's analog to
funflow wrap ' except the action passed here is just a simple function ( it
-- will be wrapped later as a funflow effect).
toTask' :: (KatipContext m)
=> Properties a b -> (a -> m b) -> PTask m a b
toTask' props = makeTask' props mempty . const
| Measures the time taken by a ' PTask ' .
clockTask
:: (KatipContext m) => PTask m a b -> PTask m a (b, TimeSpec)
clockTask task = proc input -> do
start <- time -< ()
output <- task -< input
end <- time -< ()
returnA -< (output, end `diffTimeSpec` start)
where
time = stepIO $ const $ getTime Realtime
| Measures the time taken by a ' PTask ' and the deep evaluation of its result .
clockTask'
:: (NFData b, KatipContext m) => PTask m a b -> PTask m a (b, TimeSpec)
clockTask' task = clockTask $
task >>> stepIO (evaluate . force)
-- | Logs a message during the pipeline execution
logTask :: (KatipContext m) => PTask m (Severity, String) ()
logTask = toTask $ \(sev, s) -> logFM sev $ logStr s
-- | Logs a message at a predefined severity level
logDebug, logInfo, logNotice, logWarning, logError :: (KatipContext m) => PTask m String ()
logDebug = arr (DebugS,) >>> logTask
logInfo = arr (InfoS,) >>> logTask
logNotice = arr (NoticeS,) >>> logTask
logWarning = arr (WarningS,) >>> logTask
logError = arr (ErrorS,) >>> logTask
| To access and transform the requirements of the PTask before it runs
taskRequirements :: Lens' (PTask m a b) VirtualTree
taskRequirements = splitTask . _1
| To access and transform all the ' VirtualFiles ' used by this ' PTask ' . The
parameters of the VirtualFiles will remain hidden , but all the metadata is
-- accessible. NOTE: The original path of the files isn't settable.
taskUsedFiles :: Traversal' (PTask m a b) (VirtualFile NoWrite NoRead)
taskUsedFiles = taskRequirements . traversed . vfnodeFileVoided
| Permits to access the ' RunnableTask ' inside the PTask . It is the PTask ,
devoid of its requirements . It is also and Arrow , and additionally it 's an
ArrowChoice , so by using ' over ptaskRunnablePart ' you can access a structure
-- in which you can use /case/ and /if/ statements.
taskRunnablePart :: Lens (PTask m a b) (PTask m a' b')
(RunnableTask m a b) (RunnableTask m a' b')
taskRunnablePart = splitTask . _2
| To transform the state of the PTask when it will run
taskReaderState :: Setter' (PTask m a b) (PTaskState m)
taskReaderState = taskRunnablePart . runnableTaskReaderState
| To transform the ' DataAccessTree ' of the PTask when it will run
taskDataAccessTree :: Setter' (PTask m a b) (DataAccessTree m)
taskDataAccessTree = taskReaderState . ptrsDataAccessTree
-- | Adds some context to a task, that will be used by the logger. That bit of
-- context is dynamic, that's why what we do is wrap the task into a new one,
expecting the ' ' . See ' katipAddContext ' . If your bit of context can be
-- known statically (ie. before the pipeline actually runs), prefer
-- 'addStaticContextToTask'.
addContextToTask :: (LogItem i, Monad m) => PTask m a b -> PTask m (i,a) b
addContextToTask = over taskRunnablePart $ modifyingRuntimeState
(\(item,_) -> over ptrsKatipContext (<> liftPayload item))
snd
-- | Adds to a task some context that is know _before_ the pipeline run. The
' ' to add is therefore static and can be given just as an argument .
addStaticContextToTask :: (LogItem i) => i -> PTask m a b -> PTask m a b
addStaticContextToTask item =
over (taskReaderState . ptrsKatipContext) (<> liftPayload item)
-- | Adds a namespace to the task. See 'katipAddNamespace'. Like context in
-- 'addStaticContextToTask', the namespace is meant to be static, that's why we
give it as a parameter to ' addNamespaceToTask ' , instead of creating a PTask
-- that expects the namespace as an input.
--
-- NOTE: Prefer the use of 'nameTask', which records the time spent within the
-- task. Directly use 'addNamespaceToTask' only if that time tracking hurts
-- performance.
addNamespaceToTask :: String -> PTask m a b -> PTask m a b
addNamespaceToTask ns =
over (taskReaderState . ptrsKatipNamespace) (<> fromString ns)
-- | This gives the task a name, making porcupine aware that this task should be
-- considered a entity by itself. This has a few effects:
--
-- change the logging output by wrapping it in a namespace (as per
-- 'addNamespaceToTask') and measure and log (InfoS level) the time spent within
-- that task
nameTask :: (KatipContext m) => String -> PTask m a b -> PTask m a b
nameTask ns task =
addNamespaceToTask ns $
clockTask task
>>> toTask (\(output, time) -> do
katipAddContext time $
logFM InfoS $ logStr $ "Finished task '" ++ ns ++ "' in " ++ showTimeSpec time
return output)
| Moves the ' VirtualTree ' associated to the task deeper in the final
-- tree. This can be used to solve conflicts between tasks that have
' VirtualTree 's that are identical ( for instance input files for a model if
-- you want to solve several models, in which case you'd want for instance to
-- add an extra level at the root of the tree with the model name).
taskInSubtree :: [LocationTreePathItem] -> PTask m a b -> PTask m a b
taskInSubtree path = over splitTask $ \(reqTree, runnable) ->
let reqTree' = foldr (\pathItem rest -> folderNode [pathItem :/ rest]) reqTree path
runnable' = runnable & over (runnableTaskReaderState . ptrsDataAccessTree)
(view $ atSubfolderRec path)
in (reqTree', runnable')
| null | https://raw.githubusercontent.com/aspiwack/porcupine/23dcba1523626af0fdf6085f4107987d4bf718d7/porcupine-core/src/System/TaskPipeline/PTask.hs | haskell | # LANGUAGE Arrows #
# LANGUAGE ConstraintKinds #
# LANGUAGE GADTs #
# LANGUAGE TypeOperators #
| a tasks that discards its inputs and returns ()
| Just a shortcut for when you want an IO step that requires no input
| Catches an error happening in a task. Leaves the tree intact if an error
occured.
| An version of 'tryPTask' that just logs when an error happens
| Fails the whole pipeline if an exception occured, or just continues as
normal
| Fails the whole pipeline if an exception occured, or just continues as
normal
requirements, so if the action uses files or resources, they won't appear in
| A version of 'toTask' that can perform caching. It's analog to
will be wrapped later as a funflow effect).
| Logs a message during the pipeline execution
| Logs a message at a predefined severity level
accessible. NOTE: The original path of the files isn't settable.
in which you can use /case/ and /if/ statements.
| Adds some context to a task, that will be used by the logger. That bit of
context is dynamic, that's why what we do is wrap the task into a new one,
known statically (ie. before the pipeline actually runs), prefer
'addStaticContextToTask'.
| Adds to a task some context that is know _before_ the pipeline run. The
| Adds a namespace to the task. See 'katipAddNamespace'. Like context in
'addStaticContextToTask', the namespace is meant to be static, that's why we
that expects the namespace as an input.
NOTE: Prefer the use of 'nameTask', which records the time spent within the
task. Directly use 'addNamespaceToTask' only if that time tracking hurts
performance.
| This gives the task a name, making porcupine aware that this task should be
considered a entity by itself. This has a few effects:
change the logging output by wrapping it in a namespace (as per
'addNamespaceToTask') and measure and log (InfoS level) the time spent within
that task
tree. This can be used to solve conflicts between tasks that have
you want to solve several models, in which case you'd want for instance to
add an extra level at the root of the tree with the model name). | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE InstanceSigs #
# LANGUAGE TupleSections #
# LANGUAGE TypeFamilies #
# OPTIONS_GHC -Wall #
module System.TaskPipeline.PTask
( module Control.Category
, module Control.Arrow
, module Data.Locations.LogAndErrors
, PTask
, Severity(..)
, CanRunPTask
, Properties
, tryTask, throwTask, clockTask, clockTask'
, catchAndLog, throwStringTask
, toTask, toTask'
, ioTask, stepIO, stepIO'
, taskUsedFiles
, taskRequirements
, taskRunnablePart
, taskDataAccessTree
, taskInSubtree
, voidTask
, addContextToTask
, addStaticContextToTask
, addNamespaceToTask
, nameTask
, logTask
, logDebug, logInfo, logNotice, logWarning, logError
) where
import Prelude hiding (id, (.))
import Control.Arrow
import qualified Control.Arrow.Free as AF
import Control.Category
import Control.DeepSeq (NFData (..), force)
import Control.Exception (evaluate)
import Control.Funflow (Properties, stepIO,
stepIO')
import Control.Lens
import Data.Locations
import Data.Locations.LogAndErrors
import Data.String
import Katip
import System.ClockHelpers
import System.TaskPipeline.PorcupineTree
import System.TaskPipeline.PTask.Internal
voidTask :: PTask m a ()
voidTask = arr (const ())
ioTask :: (KatipContext m) => PTask m (IO a) a
ioTask = stepIO id
tryTask
:: PTask m a b -> PTask m a (Either SomeException b)
tryTask = AF.try
catchAndLog :: (KatipContext m)
=> Severity -> PTask m a b -> PTask m a (Maybe b)
catchAndLog severity task =
tryTask task
>>> toTask (\i ->
case i of
Left e -> do
logFM severity $ logStr $ displayException (e::SomeException)
return Nothing
Right x -> return $ Just x)
throwTask :: (Exception e, LogThrow m) => PTask m (Either e b) b
throwTask = arr (over _Left displayException) >>> throwStringTask
throwStringTask :: (LogThrow m) => PTask m (Either String b) b
throwStringTask = toTask $ \i ->
case i of
Left e -> throwWithPrefix e
Right r -> return r
| Turn an action into a PTask . BEWARE ! The resulting ' PTask ' will have NO
the LocationTree .
toTask :: (KatipContext m)
=> (a -> m b) -> PTask m a b
toTask = makeTask mempty . const
funflow wrap ' except the action passed here is just a simple function ( it
toTask' :: (KatipContext m)
=> Properties a b -> (a -> m b) -> PTask m a b
toTask' props = makeTask' props mempty . const
| Measures the time taken by a ' PTask ' .
clockTask
:: (KatipContext m) => PTask m a b -> PTask m a (b, TimeSpec)
clockTask task = proc input -> do
start <- time -< ()
output <- task -< input
end <- time -< ()
returnA -< (output, end `diffTimeSpec` start)
where
time = stepIO $ const $ getTime Realtime
| Measures the time taken by a ' PTask ' and the deep evaluation of its result .
clockTask'
:: (NFData b, KatipContext m) => PTask m a b -> PTask m a (b, TimeSpec)
clockTask' task = clockTask $
task >>> stepIO (evaluate . force)
logTask :: (KatipContext m) => PTask m (Severity, String) ()
logTask = toTask $ \(sev, s) -> logFM sev $ logStr s
logDebug, logInfo, logNotice, logWarning, logError :: (KatipContext m) => PTask m String ()
logDebug = arr (DebugS,) >>> logTask
logInfo = arr (InfoS,) >>> logTask
logNotice = arr (NoticeS,) >>> logTask
logWarning = arr (WarningS,) >>> logTask
logError = arr (ErrorS,) >>> logTask
| To access and transform the requirements of the PTask before it runs
taskRequirements :: Lens' (PTask m a b) VirtualTree
taskRequirements = splitTask . _1
| To access and transform all the ' VirtualFiles ' used by this ' PTask ' . The
parameters of the VirtualFiles will remain hidden , but all the metadata is
taskUsedFiles :: Traversal' (PTask m a b) (VirtualFile NoWrite NoRead)
taskUsedFiles = taskRequirements . traversed . vfnodeFileVoided
| Permits to access the ' RunnableTask ' inside the PTask . It is the PTask ,
devoid of its requirements . It is also and Arrow , and additionally it 's an
ArrowChoice , so by using ' over ptaskRunnablePart ' you can access a structure
taskRunnablePart :: Lens (PTask m a b) (PTask m a' b')
(RunnableTask m a b) (RunnableTask m a' b')
taskRunnablePart = splitTask . _2
| To transform the state of the PTask when it will run
taskReaderState :: Setter' (PTask m a b) (PTaskState m)
taskReaderState = taskRunnablePart . runnableTaskReaderState
| To transform the ' DataAccessTree ' of the PTask when it will run
taskDataAccessTree :: Setter' (PTask m a b) (DataAccessTree m)
taskDataAccessTree = taskReaderState . ptrsDataAccessTree
expecting the ' ' . See ' katipAddContext ' . If your bit of context can be
addContextToTask :: (LogItem i, Monad m) => PTask m a b -> PTask m (i,a) b
addContextToTask = over taskRunnablePart $ modifyingRuntimeState
(\(item,_) -> over ptrsKatipContext (<> liftPayload item))
snd
' ' to add is therefore static and can be given just as an argument .
addStaticContextToTask :: (LogItem i) => i -> PTask m a b -> PTask m a b
addStaticContextToTask item =
over (taskReaderState . ptrsKatipContext) (<> liftPayload item)
give it as a parameter to ' addNamespaceToTask ' , instead of creating a PTask
addNamespaceToTask :: String -> PTask m a b -> PTask m a b
addNamespaceToTask ns =
over (taskReaderState . ptrsKatipNamespace) (<> fromString ns)
nameTask :: (KatipContext m) => String -> PTask m a b -> PTask m a b
nameTask ns task =
addNamespaceToTask ns $
clockTask task
>>> toTask (\(output, time) -> do
katipAddContext time $
logFM InfoS $ logStr $ "Finished task '" ++ ns ++ "' in " ++ showTimeSpec time
return output)
| Moves the ' VirtualTree ' associated to the task deeper in the final
' VirtualTree 's that are identical ( for instance input files for a model if
taskInSubtree :: [LocationTreePathItem] -> PTask m a b -> PTask m a b
taskInSubtree path = over splitTask $ \(reqTree, runnable) ->
let reqTree' = foldr (\pathItem rest -> folderNode [pathItem :/ rest]) reqTree path
runnable' = runnable & over (runnableTaskReaderState . ptrsDataAccessTree)
(view $ atSubfolderRec path)
in (reqTree', runnable')
|
5122dcb7bb483f83b3537d05134d1cf85a5c974bdf5406a299f02510e9ca4c44 | abhay/mochiweb.old | mochiweb_response.erl | @author < >
2007 Mochi Media , Inc.
%% @doc Response abstraction.
-module(mochiweb_response, [Request, Code, Headers]).
-author('').
-define(QUIP, "Any of you quaids got a smint?").
-export([get_header_value/1, get/1, dump/0]).
-export([send/1, write_chunk/1]).
get_header_value(string ( ) | atom ( ) | binary ( ) ) - > string ( ) | undefined
%% @doc Get the value of the given response header.
get_header_value(K) ->
mochiweb_headers:get_value(K, Headers).
%% @spec get(request | code | headers) -> term()
%% @doc Return the internal representation of the given field.
get(request) ->
Request;
get(code) ->
Code;
get(headers) ->
Headers.
@spec dump ( ) - > { mochiweb_request , [ { atom ( ) , term ( ) } ] }
%% @doc Dump the internal representation to a "human readable" set of terms
%% for debugging/inspection purposes.
dump() ->
[{request, Request:dump()},
{code, Code},
{headers, mochiweb_headers:to_list(Headers)}].
( ) ) - > ok
@doc Send data over the socket if the method is not HEAD .
send(Data) ->
case Request:get(method) of
'HEAD' ->
ok;
_ ->
Request:send(Data)
end.
write_chunk(iodata ( ) ) - > ok
@doc Write a chunk of a HTTP chunked response . If Data is zero length ,
%% then the chunked response will be finished.
write_chunk(Data) ->
case Request:get(version) of
Version when Version >= {1, 1} ->
Length = iolist_size(Data),
send(io_lib:format("~.16b\r\n", [Length])),
send([Data, <<"\r\n">>]);
_ ->
send(Data)
end.
| null | https://raw.githubusercontent.com/abhay/mochiweb.old/a22707e1dec0ed79108e98b5c691a623fdff1eae/src/mochiweb_response.erl | erlang | @doc Response abstraction.
@doc Get the value of the given response header.
@spec get(request | code | headers) -> term()
@doc Return the internal representation of the given field.
@doc Dump the internal representation to a "human readable" set of terms
for debugging/inspection purposes.
then the chunked response will be finished. | @author < >
2007 Mochi Media , Inc.
-module(mochiweb_response, [Request, Code, Headers]).
-author('').
-define(QUIP, "Any of you quaids got a smint?").
-export([get_header_value/1, get/1, dump/0]).
-export([send/1, write_chunk/1]).
get_header_value(string ( ) | atom ( ) | binary ( ) ) - > string ( ) | undefined
get_header_value(K) ->
mochiweb_headers:get_value(K, Headers).
get(request) ->
Request;
get(code) ->
Code;
get(headers) ->
Headers.
@spec dump ( ) - > { mochiweb_request , [ { atom ( ) , term ( ) } ] }
dump() ->
[{request, Request:dump()},
{code, Code},
{headers, mochiweb_headers:to_list(Headers)}].
( ) ) - > ok
@doc Send data over the socket if the method is not HEAD .
send(Data) ->
case Request:get(method) of
'HEAD' ->
ok;
_ ->
Request:send(Data)
end.
write_chunk(iodata ( ) ) - > ok
@doc Write a chunk of a HTTP chunked response . If Data is zero length ,
write_chunk(Data) ->
case Request:get(version) of
Version when Version >= {1, 1} ->
Length = iolist_size(Data),
send(io_lib:format("~.16b\r\n", [Length])),
send([Data, <<"\r\n">>]);
_ ->
send(Data)
end.
|
366f1699e971a5176ca75f0eb990bcdfd41a0564d1180118c778bb330e022fa4 | pliant/lein-package | artifact.clj | (ns leiningen.package.artifact
"Allows for the restriction or addition of files that are deployed to the remote repository."
(:require [clojure.java.io :as io]
[clojure.string :as twine]
[leiningen.core.main :as main]
[leiningen.jar :as jar]
[leiningen.pom :as pom]))
(def jar {:extension "jar" :build "jar"})
(def pom {:extension "pom" })
(defn ^java.io.File file
[project artifact]
(let [target (io/file (:target-path project))
suffix (if (:classifier artifact)
(str "-" (:classifier artifact) "." (:extension artifact))
(str "." (:extension artifact)))
file-name (str (:name project) "-" (:version project) suffix)]
(io/file target file-name)))
(defn ^java.lang.String file-path
[project artifact]
(.getAbsolutePath (file project artifact)))
(defn exists?
[project artifact]
(.exists (file project artifact)))
(defn artifactify
[entry]
(cond
(map? entry) entry
:else {:extension (name entry)}))
(defn artifacts
[project]
(let [raw-artifacts (get-in project [:package :artifacts])]
(if raw-artifacts
(let [configured (for [entry raw-artifacts] (artifactify entry))
pomjar #{"pom" "jar"}]
(filter
#(or (not (pomjar (:extension %)))
(and (:classifier %)
(= "jar" (:extension %))))
configured)))))
(defn make-jar?
[project]
(not (true? (get-in project [:package :skipjar]))))
(defn make-jar
[project]
(if (make-jar? project)
(jar/jar project)))
(defn buildable-artifacts
[project]
(if (make-jar? project) (cons jar (artifacts project)) (artifacts project)))
(defn all-artifacts
[project]
(concat [pom] (buildable-artifacts project)))
(defn build-artifact
[project artifact]
(main/debug "Building" (select-keys artifact [:extension :classifier]))
(let [raw-args (twine/split (:build artifact) #"\s+")
task-name (first raw-args)
args (next raw-args)]
(main/apply-task (main/lookup-alias task-name project) project args)))
(defn build-artifacts
[project artifacts]
(doseq [artifact artifacts]
(if (:build artifact)
(build-artifact project artifact))))
(defn built-artifacts
"Gathers artifacts that are already build or able to be built now."
[project]
(let [autobuild (get-in project[:package :autobuild])
artifacts (artifacts project)]
(filter #(cond
(exists? project %) %
(or autobuild (:autobuild %)) (or (build-artifact project %)
true)
:else false)
artifacts)))
(defn coordinates
([project]
[(symbol (:group project) (:name project)) (:version project)])
([project artifact & [suffix]]
(let [extension (str (:extension artifact) suffix)
classifier (if (:classifier artifact)
[:classifier (:classifier artifact)])]
(vec
(concat
[(symbol (:group project) (:name project))
(:version project)
:extension extension]
classifier)))))
(defn mappings
[project]
(let [pom-file (pom/pom project)
pom-coord (coordinates project pom)
pom-entry {:artifact pom :coordinate pom-coord :file pom-file}]
(if (make-jar? project)
(let [jar-files (make-jar project)
jar-entries (map (fn [[k v]] {:artifact k :coordinate (coordinates project k) :file v}) jar-files)]
(conj jar-entries pom-entry))
(list pom-entry))))
(defn mappings->entries
[coll]
(into {} (map (fn [m] [(:coordinate m) (:file m)]) coll))) | null | https://raw.githubusercontent.com/pliant/lein-package/aef327e4698b13f1cf0986f5eaa23968e90b458b/src/leiningen/package/artifact.clj | clojure | (ns leiningen.package.artifact
"Allows for the restriction or addition of files that are deployed to the remote repository."
(:require [clojure.java.io :as io]
[clojure.string :as twine]
[leiningen.core.main :as main]
[leiningen.jar :as jar]
[leiningen.pom :as pom]))
(def jar {:extension "jar" :build "jar"})
(def pom {:extension "pom" })
(defn ^java.io.File file
[project artifact]
(let [target (io/file (:target-path project))
suffix (if (:classifier artifact)
(str "-" (:classifier artifact) "." (:extension artifact))
(str "." (:extension artifact)))
file-name (str (:name project) "-" (:version project) suffix)]
(io/file target file-name)))
(defn ^java.lang.String file-path
[project artifact]
(.getAbsolutePath (file project artifact)))
(defn exists?
[project artifact]
(.exists (file project artifact)))
(defn artifactify
[entry]
(cond
(map? entry) entry
:else {:extension (name entry)}))
(defn artifacts
[project]
(let [raw-artifacts (get-in project [:package :artifacts])]
(if raw-artifacts
(let [configured (for [entry raw-artifacts] (artifactify entry))
pomjar #{"pom" "jar"}]
(filter
#(or (not (pomjar (:extension %)))
(and (:classifier %)
(= "jar" (:extension %))))
configured)))))
(defn make-jar?
[project]
(not (true? (get-in project [:package :skipjar]))))
(defn make-jar
[project]
(if (make-jar? project)
(jar/jar project)))
(defn buildable-artifacts
[project]
(if (make-jar? project) (cons jar (artifacts project)) (artifacts project)))
(defn all-artifacts
[project]
(concat [pom] (buildable-artifacts project)))
(defn build-artifact
[project artifact]
(main/debug "Building" (select-keys artifact [:extension :classifier]))
(let [raw-args (twine/split (:build artifact) #"\s+")
task-name (first raw-args)
args (next raw-args)]
(main/apply-task (main/lookup-alias task-name project) project args)))
(defn build-artifacts
[project artifacts]
(doseq [artifact artifacts]
(if (:build artifact)
(build-artifact project artifact))))
(defn built-artifacts
"Gathers artifacts that are already build or able to be built now."
[project]
(let [autobuild (get-in project[:package :autobuild])
artifacts (artifacts project)]
(filter #(cond
(exists? project %) %
(or autobuild (:autobuild %)) (or (build-artifact project %)
true)
:else false)
artifacts)))
(defn coordinates
([project]
[(symbol (:group project) (:name project)) (:version project)])
([project artifact & [suffix]]
(let [extension (str (:extension artifact) suffix)
classifier (if (:classifier artifact)
[:classifier (:classifier artifact)])]
(vec
(concat
[(symbol (:group project) (:name project))
(:version project)
:extension extension]
classifier)))))
(defn mappings
[project]
(let [pom-file (pom/pom project)
pom-coord (coordinates project pom)
pom-entry {:artifact pom :coordinate pom-coord :file pom-file}]
(if (make-jar? project)
(let [jar-files (make-jar project)
jar-entries (map (fn [[k v]] {:artifact k :coordinate (coordinates project k) :file v}) jar-files)]
(conj jar-entries pom-entry))
(list pom-entry))))
(defn mappings->entries
[coll]
(into {} (map (fn [m] [(:coordinate m) (:file m)]) coll))) | |
5b3409f44ba612e2b44de0e27a03c01972b78e9b1bbed13c6c0a3cb58da3ee24 | bobatkey/foveran | LocallyNameless.hs | # LANGUAGE DeriveFunctor , TypeSynonymInstances , OverloadedStrings , TupleSections , FlexibleInstances #
module Language.Foveran.Syntax.LocallyNameless
( TermPos
, TermCon (..)
, GlobalFlag (..)
, Binding (..)
, bindingOfPattern
, toLocallyNamelessClosed
, toLocallyNameless
, close
)
where
import Text.Show.Functions ()
import Data.Traversable (sequenceA, traverse)
import Control.Applicative
import Data.Rec
import Text.Position (Span)
import Data.FreeMonad
import Data.Pair
import qualified Language.Foveran.Syntax.Display as DS
import Language.Foveran.Syntax.Identifier (Ident)
type TermPos = AnnotRec Span TermCon
type TermPos' p = AnnotRec p TermCon
data GlobalFlag
= IsGlobal
| IsLocal
deriving Show
data Binding
= BindVar Ident
| BindTuple [Binding]
| BindNull
| BindRecur Ident
deriving Show
data TermCon tm
= Free Ident GlobalFlag
| Bound Int
| Lam Ident tm
| App tm tm
| Set Int
| Pi (Maybe Ident) tm tm
| Sigma (Maybe Ident) tm tm
| Tuple tm tm
| Proj1 tm
| Proj2 tm
| Sum tm tm
| Inl tm
| Inr tm
| Case tm (Maybe (Ident, tm)) Ident tm Ident tm
| Unit (Maybe Ident)
| UnitI
| Empty
| ElimEmpty tm (Maybe tm)
| Eq tm tm
| Refl
| ElimEq tm (Maybe (Ident, Ident, tm)) tm
| Desc_K tm
| Desc_Prod tm tm
| Construct tm
| IDesc
| IDesc_Id tm
| IDesc_Sg tm tm
| IDesc_Pi tm tm
| IDesc_Bind tm Ident tm
| IDesc_Elim
| SemI tm Ident tm
| LiftI tm Ident tm Ident Ident tm tm
| MapI tm Ident tm Ident tm tm tm
| MuI tm tm
| Eliminate tm (Maybe (Ident, Ident, tm)) Ident Ident Ident tm
| NamedConstructor Ident [tm]
| CasesOn Bool tm [(Ident, [DS.Pattern], [Binding] -> tm)]
-- a suspended conversion to locally nameless, waiting for the additional variables to be bound
| TypeAscrip tm tm
| Generalise tm tm
| LabelledType Ident [Pair tm] tm
| Return tm
| Call tm
| UserHole
| Hole Ident [tm]
deriving (Show, Functor)
instance Show (TermPos' p) where
show (Annot p t) = "(" ++ show t ++ ")"
--------------------------------------------------------------------------------
identOfPattern :: DS.Pattern -> Ident
identOfPattern (DS.PatVar nm) = nm
identOfPattern (DS.PatTuple _) = "p" -- FIXME: concatenate all the names, or something
identOfPattern DS.PatNull = "__x"
bindingOfPattern :: DS.Pattern -> Binding
bindingOfPattern (DS.PatVar nm) = BindVar nm
bindingOfPattern (DS.PatTuple patterns) = BindTuple (map bindingOfPattern patterns)
bindingOfPattern DS.PatNull = BindNull
--------------------------------------------------------------------------------
data Var -- FIXME: not sure if this the best way of doing things
= VarNormal Ident
| VarRecurse Ident
deriving Eq
lookupVarInBinding :: Var -> Binding -> FM TermCon a -> Maybe (FM TermCon a)
lookupVarInBinding v BindNull t =
Nothing
lookupVarInBinding v (BindRecur nm) t
| v == VarRecurse nm = Just t
| otherwise = Nothing
lookupVarInBinding v (BindVar nm) t
| v == VarNormal nm = Just t
| otherwise = Nothing
lookupVarInBinding v (BindTuple l) t =
lookupVarInTupleBinding l t
where
lookupVarInTupleBinding [] t =
Nothing
lookupVarInTupleBinding [b] t =
lookupVarInBinding v b t
lookupVarInTupleBinding (b:bs) t =
lookupVarInBinding v b (Layer $ Proj1 t)
<|>
lookupVarInTupleBinding bs (Layer $ Proj2 t)
lookupVar :: Var -> [Binding] -> Int -> Maybe (FM TermCon a)
lookupVar v [] k = Nothing
lookupVar v (b:bs) k =
lookupVarInBinding v b (Layer $ Bound k)
<|>
lookupVar v bs (k+1)
--------------------------------------------------------------------------------
toLN :: DS.TermCon ([Binding] -> a) -> [Binding] -> FM TermCon a
toLN (DS.Var nm) bv = case lookupVar (VarNormal nm) bv 0 of
Nothing -> Layer $ Free nm IsGlobal
Just t -> t
toLN (DS.Lam nms body) bv = doBinders nms bv
where
doBinders [] bv = return $ body bv
doBinders (p:nms) bv = Layer $ Lam (identOfPattern p) (doBinders nms (bindingOfPattern p:bv))
toLN (DS.App t ts) bv = doApplications (return $ t bv) ts
where doApplications tm [] = tm
doApplications tm (t:ts) = doApplications (Layer $ App tm (return $ t bv)) ts
toLN (DS.Set i) bv = Layer $ Set i
toLN (DS.Pi bs t) bv = doArrows bs bv
where doArrows [] bv = return $ t bv
doArrows (([],t1):bs) bv = Layer $ Pi Nothing (return $ t1 bv) (doArrows bs (BindNull:bv))
doArrows ((nms,t1):bs) bv = doNames nms t1 bv (doArrows bs)
doNames [] t1 bv k = k bv
doNames (p:ps) t1 bv k = Layer $ Pi (Just $ identOfPattern p) (return $ t1 bv) (doNames ps t1 (bindingOfPattern p:bv) k)
toLN (DS.Sigma nms t1 t2) bv = doBinders nms bv
where doBinders [] bv = return $ t2 bv
doBinders (nm:nms) bv = Layer $ Sigma (Just $ identOfPattern nm) (return $ t1 bv) (doBinders nms (bindingOfPattern nm:bv))
toLN (DS.Prod t1 t2) bv = Layer $ Sigma Nothing (return $ t1 bv) (return $ t2 (BindNull:bv))
toLN (DS.Tuple tms) bv = doTuple tms
where doTuple [] = Layer $ UnitI
doTuple [tm] = Var $ tm bv
doTuple (tm:tms) = Layer $ Tuple (Var $ tm bv) (doTuple tms)
toLN (DS.Proj1 t) bv = Layer $ Proj1 (return $ t bv)
toLN (DS.Proj2 t) bv = Layer $ Proj2 (return $ t bv)
toLN (DS.Sum t1 t2) bv = Layer $ Sum (return $ t1 bv) (return $ t2 bv)
toLN (DS.Inl t) bv = Layer $ Inl (return $ t bv)
toLN (DS.Inr t) bv = Layer $ Inr (return $ t bv)
toLN (DS.Case t1 Nothing y t3 z t4) bv =
Layer $ Case (return $ t1 bv)
Nothing
(identOfPattern y)
(return $ t3 (bindingOfPattern y:bv))
(identOfPattern z)
(return $ t4 (bindingOfPattern z:bv))
toLN (DS.Case t1 (Just (x, t2)) y t3 z t4) bv =
Layer $ Case (return $ t1 bv)
(Just (x, return $ t2 (BindVar x:bv)))
(identOfPattern y)
(return $ t3 (bindingOfPattern y:bv))
(identOfPattern z)
(return $ t4 (bindingOfPattern z:bv))
toLN DS.Unit bv = Layer $ Unit Nothing
toLN DS.UnitI bv = Layer $ UnitI
toLN DS.Empty bv = Layer $ Empty
toLN (DS.ElimEmpty t1 Nothing) bv = Layer $ ElimEmpty (return $ t1 bv) Nothing
toLN (DS.ElimEmpty t1 (Just t2)) bv = Layer $ ElimEmpty (return $ t1 bv) (Just (return $ t2 bv))
toLN (DS.Eq t1 t2) bv = Layer $ Eq (return $ t1 bv) (return $ t2 bv)
toLN DS.Refl bv = Layer $ Refl
toLN (DS.ElimEq t t1 t2) bv =
Layer $ ElimEq (return $ t bv)
((\(x,y,t1) -> (x, y, return $ t1 (BindVar y:BindVar x:bv))) <$> t1)
(return $ t2 bv)
toLN (DS.Desc_K t) bv = Layer $ Desc_K (return $ t bv)
toLN (DS.Desc_Prod t1 t2) bv = Layer $ Desc_Prod (return $ t1 bv) (return $ t2 bv)
toLN (DS.Construct t) bv = Layer $ Construct (return $ t bv)
toLN DS.IDesc bv = Layer $ IDesc
toLN (DS.IDesc_Id t) bv = Layer $ IDesc_Id (return $ t bv)
toLN (DS.IDesc_Sg t1 t2) bv = Layer $ IDesc_Sg (return $ t1 bv) (return $ t2 bv)
toLN (DS.IDesc_Pi t1 t2) bv = Layer $ IDesc_Pi (return $ t1 bv) (return $ t2 bv)
toLN (DS.IDesc_Bind t1 x t2) bv =
Layer $ IDesc_Bind (return $ t1 bv) (identOfPattern x) (return $ t2 (bindingOfPattern x:bv))
toLN DS.IDesc_Elim bv = Layer $ IDesc_Elim
toLN (DS.SemI tD x tA) bv =
Layer $ SemI (return $ tD bv) (identOfPattern x) (return $ tA (bindingOfPattern x:bv))
toLN (DS.MapI tD i1 tA i2 tB tf tx) bv =
Layer $ MapI (return $ tD bv)
(identOfPattern i1) (return $ tA (bindingOfPattern i1:bv))
(identOfPattern i2) (return $ tB (bindingOfPattern i2:bv))
(return $ tf bv)
(return $ tx bv)
toLN (DS.LiftI tD i tA i' a tP tx) bv =
Layer $ LiftI (return $ tD bv)
(identOfPattern i) (return $ tA (bindingOfPattern i:bv))
(identOfPattern i') (identOfPattern a) (return $ tP (bindingOfPattern a:bindingOfPattern i':bv))
(return $ tx bv)
toLN (DS.MuI t1 t2) bv = Layer $ MuI (return $ t1 bv) (return $ t2 bv)
toLN (DS.Eliminate t tP i x p tK) bv =
Layer $ Eliminate (return $ t bv)
((\(x,y,t) -> (identOfPattern x, identOfPattern y, return $ t (bindingOfPattern y:bindingOfPattern x:bv))) <$> tP)
(identOfPattern i)
(identOfPattern x)
(identOfPattern p)
(return $ tK (bindingOfPattern p:bindingOfPattern x:bindingOfPattern i:bv))
toLN (DS.NamedConstructor nm tms) bv =
Layer $ NamedConstructor nm (map (\t -> return (t bv)) tms)
toLN (DS.CasesOn isRecursive tm clauses) bv =
Layer $ CasesOn isRecursive
(return $ tm bv)
(map (\(ident,patterns,tm) -> (ident,patterns,\bv' -> return $ tm (bv' ++ bv))) clauses)
toLN (DS.RecurseOn nm) bv =
case lookupVar (VarRecurse nm) bv 0 of
Nothing -> Layer $ Free nm IsGlobal -- FIXME: should really throw an error
Just t -> t
toLN (DS.TypeAscrip t1 t2) bv = Layer $ TypeAscrip (return $ t1 bv) (return $ t2 bv)
toLN (DS.Generalise t1 t2) bv = Layer $ Generalise (return $ t1 bv) (return $ t2 bv)
toLN (DS.LabelledType nm args ty) bv =
Layer $ LabelledType nm (map (fmap (\x -> return (x bv))) args) (return $ ty bv)
toLN (DS.Return t) bv =
Layer $ Return (return $ t bv)
toLN (DS.Call t) bv =
Layer $ Call (return $ t bv)
toLN DS.UserHole bv = Layer $ UserHole
toLN (DS.Hole nm tms) bv = Layer $ Hole nm (map (\t -> return (t bv)) tms)
toLocallyNamelessClosed :: AnnotRec a DS.TermCon -> AnnotRec a TermCon
toLocallyNamelessClosed t = translateStar toLN t []
toLocallyNameless :: AnnotRec a DS.TermCon -> [Binding] -> AnnotRec a TermCon
toLocallyNameless t = translateStar toLN t
{------------------------------------------------------------------------------}
binder :: (Int -> a) -> Int -> a
binder f i = f (i+1)
close' :: [Ident] -> TermCon (Int -> a) -> Int -> TermCon a
close' fnm (Free nm global) = pure $ Free nm global
close' fnm (Bound k) = \i -> if k < i then Bound k
else let j = k - i
l = length fnm
in if j < length fnm
then Free (fnm !! j) IsLocal
else Bound (k - l)
close' fnm (Lam nm body) = Lam nm <$> binder body
close' fnm (App t ts) = App <$> t <*> ts
close' fnm (Set i) = pure $ Set i
close' fnm (Pi nm t1 t2) = Pi nm <$> t1 <*> binder t2
close' fnm (Sigma nm t1 t2) = Sigma nm <$> t1 <*> binder t2
close' fnm (Tuple t1 t2) = Tuple <$> t1 <*> t2
close' fnm (Proj1 t) = Proj1 <$> t
close' fnm (Proj2 t) = Proj2 <$> t
close' fnm (Sum t1 t2) = Sum <$> t1 <*> t2
close' fnm (Inl t) = Inl <$> t
close' fnm (Inr t) = Inr <$> t
close' fnm (Case t1 tP y t3 z t4) =
Case <$> t1
<*> traverse (\(x,tP) -> (x,) <$> binder tP) tP
<*> pure y <*> binder t3
<*> pure z <*> binder t4
close' fnm (Unit tag) = pure (Unit tag)
close' fnm UnitI = pure UnitI
close' fnm Empty = pure Empty
close' fnm (ElimEmpty t1 t2) = ElimEmpty <$> t1 <*> sequenceA t2
close' fnm (Eq t1 t2) = Eq <$> t1 <*> t2
close' fnm Refl = pure Refl
close' fnm (ElimEq t Nothing t2) = ElimEq <$> t <*> pure Nothing <*> t2
close' fnm (ElimEq t (Just (x,y,t1)) t2) = ElimEq <$> t <*> ((\t1 -> Just (x,y,t1)) <$> binder (binder t1)) <*> t2
close' fnm (Desc_K t) = Desc_K <$> t
close' fnm (Desc_Prod t1 t2)= Desc_Prod <$> t1 <*> t2
close' fnm (Construct t) = Construct <$> t
close' fnm IDesc = pure IDesc
close' fnm (IDesc_Id t) = IDesc_Id <$> t
close' fnm (IDesc_Sg t1 t2) = IDesc_Sg <$> t1 <*> t2
close' fnm (IDesc_Pi t1 t2) = IDesc_Pi <$> t1 <*> t2
close' fnm (IDesc_Bind t1 x t2) = IDesc_Bind <$> t1 <*> pure x <*> binder t2
close' fnm IDesc_Elim = pure IDesc_Elim
close' fnm (SemI tD x tA) = SemI <$> tD <*> pure x <*> binder tA
close' fnm (MapI tD i1 tA i2 tB tf tx) =
MapI <$> tD <*> pure i1 <*> binder tA <*> pure i2 <*> binder tB <*> tf <*> tx
close' fnm (MuI t1 t2) = MuI <$> t1 <*> t2
close' fnm (LiftI tD i tA i' a tP tx) =
LiftI <$> tD <*> pure i <*> binder tA <*> pure i' <*> pure a <*> binder (binder tP) <*> tx
close' fnm (Eliminate t tP i x p tK) =
Eliminate <$> t
<*> traverse (\(i,x,tP) -> (i,x,) <$> binder (binder tP)) tP
<*> pure i <*> pure x <*> pure p <*> binder (binder (binder tK))
close' fnm (NamedConstructor nm tms) = NamedConstructor nm <$> sequenceA tms
close' fnm (CasesOn isRecursive tm clauses) =
CasesOn <$> pure isRecursive
<*> tm
<*> sequenceA (map (\(ident,patterns,tm) i -> (ident,patterns,\bv' -> tm bv' (i + length bv'))) clauses)
close' fnm UserHole = pure UserHole
close' fnm (Hole nm tms) = Hole nm <$> sequenceA tms
close' fnm (TypeAscrip tm ty) = TypeAscrip <$> tm <*> ty
close' fnm (Generalise t1 t2) = Generalise <$> t1 <*> t2
close' fnm (LabelledType nm args ty) =
LabelledType nm <$> traverse sequenceA args <*> ty
close' fnm (Return t) =
Return <$> t
close' fnm (Call t) =
Call <$> t
close :: [Ident] -> AnnotRec a TermCon -> Int -> AnnotRec a TermCon
close nms x offset = translate (close' nms) x offset
| null | https://raw.githubusercontent.com/bobatkey/foveran/e57463e3f6923becdf1249cd2fd0ccfcd566f7c5/src/Language/Foveran/Syntax/LocallyNameless.hs | haskell | a suspended conversion to locally nameless, waiting for the additional variables to be bound
------------------------------------------------------------------------------
FIXME: concatenate all the names, or something
------------------------------------------------------------------------------
FIXME: not sure if this the best way of doing things
------------------------------------------------------------------------------
FIXME: should really throw an error
---------------------------------------------------------------------------- | # LANGUAGE DeriveFunctor , TypeSynonymInstances , OverloadedStrings , TupleSections , FlexibleInstances #
module Language.Foveran.Syntax.LocallyNameless
( TermPos
, TermCon (..)
, GlobalFlag (..)
, Binding (..)
, bindingOfPattern
, toLocallyNamelessClosed
, toLocallyNameless
, close
)
where
import Text.Show.Functions ()
import Data.Traversable (sequenceA, traverse)
import Control.Applicative
import Data.Rec
import Text.Position (Span)
import Data.FreeMonad
import Data.Pair
import qualified Language.Foveran.Syntax.Display as DS
import Language.Foveran.Syntax.Identifier (Ident)
type TermPos = AnnotRec Span TermCon
type TermPos' p = AnnotRec p TermCon
data GlobalFlag
= IsGlobal
| IsLocal
deriving Show
data Binding
= BindVar Ident
| BindTuple [Binding]
| BindNull
| BindRecur Ident
deriving Show
data TermCon tm
= Free Ident GlobalFlag
| Bound Int
| Lam Ident tm
| App tm tm
| Set Int
| Pi (Maybe Ident) tm tm
| Sigma (Maybe Ident) tm tm
| Tuple tm tm
| Proj1 tm
| Proj2 tm
| Sum tm tm
| Inl tm
| Inr tm
| Case tm (Maybe (Ident, tm)) Ident tm Ident tm
| Unit (Maybe Ident)
| UnitI
| Empty
| ElimEmpty tm (Maybe tm)
| Eq tm tm
| Refl
| ElimEq tm (Maybe (Ident, Ident, tm)) tm
| Desc_K tm
| Desc_Prod tm tm
| Construct tm
| IDesc
| IDesc_Id tm
| IDesc_Sg tm tm
| IDesc_Pi tm tm
| IDesc_Bind tm Ident tm
| IDesc_Elim
| SemI tm Ident tm
| LiftI tm Ident tm Ident Ident tm tm
| MapI tm Ident tm Ident tm tm tm
| MuI tm tm
| Eliminate tm (Maybe (Ident, Ident, tm)) Ident Ident Ident tm
| NamedConstructor Ident [tm]
| CasesOn Bool tm [(Ident, [DS.Pattern], [Binding] -> tm)]
| TypeAscrip tm tm
| Generalise tm tm
| LabelledType Ident [Pair tm] tm
| Return tm
| Call tm
| UserHole
| Hole Ident [tm]
deriving (Show, Functor)
instance Show (TermPos' p) where
show (Annot p t) = "(" ++ show t ++ ")"
identOfPattern :: DS.Pattern -> Ident
identOfPattern (DS.PatVar nm) = nm
identOfPattern DS.PatNull = "__x"
bindingOfPattern :: DS.Pattern -> Binding
bindingOfPattern (DS.PatVar nm) = BindVar nm
bindingOfPattern (DS.PatTuple patterns) = BindTuple (map bindingOfPattern patterns)
bindingOfPattern DS.PatNull = BindNull
= VarNormal Ident
| VarRecurse Ident
deriving Eq
lookupVarInBinding :: Var -> Binding -> FM TermCon a -> Maybe (FM TermCon a)
lookupVarInBinding v BindNull t =
Nothing
lookupVarInBinding v (BindRecur nm) t
| v == VarRecurse nm = Just t
| otherwise = Nothing
lookupVarInBinding v (BindVar nm) t
| v == VarNormal nm = Just t
| otherwise = Nothing
lookupVarInBinding v (BindTuple l) t =
lookupVarInTupleBinding l t
where
lookupVarInTupleBinding [] t =
Nothing
lookupVarInTupleBinding [b] t =
lookupVarInBinding v b t
lookupVarInTupleBinding (b:bs) t =
lookupVarInBinding v b (Layer $ Proj1 t)
<|>
lookupVarInTupleBinding bs (Layer $ Proj2 t)
lookupVar :: Var -> [Binding] -> Int -> Maybe (FM TermCon a)
lookupVar v [] k = Nothing
lookupVar v (b:bs) k =
lookupVarInBinding v b (Layer $ Bound k)
<|>
lookupVar v bs (k+1)
toLN :: DS.TermCon ([Binding] -> a) -> [Binding] -> FM TermCon a
toLN (DS.Var nm) bv = case lookupVar (VarNormal nm) bv 0 of
Nothing -> Layer $ Free nm IsGlobal
Just t -> t
toLN (DS.Lam nms body) bv = doBinders nms bv
where
doBinders [] bv = return $ body bv
doBinders (p:nms) bv = Layer $ Lam (identOfPattern p) (doBinders nms (bindingOfPattern p:bv))
toLN (DS.App t ts) bv = doApplications (return $ t bv) ts
where doApplications tm [] = tm
doApplications tm (t:ts) = doApplications (Layer $ App tm (return $ t bv)) ts
toLN (DS.Set i) bv = Layer $ Set i
toLN (DS.Pi bs t) bv = doArrows bs bv
where doArrows [] bv = return $ t bv
doArrows (([],t1):bs) bv = Layer $ Pi Nothing (return $ t1 bv) (doArrows bs (BindNull:bv))
doArrows ((nms,t1):bs) bv = doNames nms t1 bv (doArrows bs)
doNames [] t1 bv k = k bv
doNames (p:ps) t1 bv k = Layer $ Pi (Just $ identOfPattern p) (return $ t1 bv) (doNames ps t1 (bindingOfPattern p:bv) k)
toLN (DS.Sigma nms t1 t2) bv = doBinders nms bv
where doBinders [] bv = return $ t2 bv
doBinders (nm:nms) bv = Layer $ Sigma (Just $ identOfPattern nm) (return $ t1 bv) (doBinders nms (bindingOfPattern nm:bv))
toLN (DS.Prod t1 t2) bv = Layer $ Sigma Nothing (return $ t1 bv) (return $ t2 (BindNull:bv))
toLN (DS.Tuple tms) bv = doTuple tms
where doTuple [] = Layer $ UnitI
doTuple [tm] = Var $ tm bv
doTuple (tm:tms) = Layer $ Tuple (Var $ tm bv) (doTuple tms)
toLN (DS.Proj1 t) bv = Layer $ Proj1 (return $ t bv)
toLN (DS.Proj2 t) bv = Layer $ Proj2 (return $ t bv)
toLN (DS.Sum t1 t2) bv = Layer $ Sum (return $ t1 bv) (return $ t2 bv)
toLN (DS.Inl t) bv = Layer $ Inl (return $ t bv)
toLN (DS.Inr t) bv = Layer $ Inr (return $ t bv)
toLN (DS.Case t1 Nothing y t3 z t4) bv =
Layer $ Case (return $ t1 bv)
Nothing
(identOfPattern y)
(return $ t3 (bindingOfPattern y:bv))
(identOfPattern z)
(return $ t4 (bindingOfPattern z:bv))
toLN (DS.Case t1 (Just (x, t2)) y t3 z t4) bv =
Layer $ Case (return $ t1 bv)
(Just (x, return $ t2 (BindVar x:bv)))
(identOfPattern y)
(return $ t3 (bindingOfPattern y:bv))
(identOfPattern z)
(return $ t4 (bindingOfPattern z:bv))
toLN DS.Unit bv = Layer $ Unit Nothing
toLN DS.UnitI bv = Layer $ UnitI
toLN DS.Empty bv = Layer $ Empty
toLN (DS.ElimEmpty t1 Nothing) bv = Layer $ ElimEmpty (return $ t1 bv) Nothing
toLN (DS.ElimEmpty t1 (Just t2)) bv = Layer $ ElimEmpty (return $ t1 bv) (Just (return $ t2 bv))
toLN (DS.Eq t1 t2) bv = Layer $ Eq (return $ t1 bv) (return $ t2 bv)
toLN DS.Refl bv = Layer $ Refl
toLN (DS.ElimEq t t1 t2) bv =
Layer $ ElimEq (return $ t bv)
((\(x,y,t1) -> (x, y, return $ t1 (BindVar y:BindVar x:bv))) <$> t1)
(return $ t2 bv)
toLN (DS.Desc_K t) bv = Layer $ Desc_K (return $ t bv)
toLN (DS.Desc_Prod t1 t2) bv = Layer $ Desc_Prod (return $ t1 bv) (return $ t2 bv)
toLN (DS.Construct t) bv = Layer $ Construct (return $ t bv)
toLN DS.IDesc bv = Layer $ IDesc
toLN (DS.IDesc_Id t) bv = Layer $ IDesc_Id (return $ t bv)
toLN (DS.IDesc_Sg t1 t2) bv = Layer $ IDesc_Sg (return $ t1 bv) (return $ t2 bv)
toLN (DS.IDesc_Pi t1 t2) bv = Layer $ IDesc_Pi (return $ t1 bv) (return $ t2 bv)
toLN (DS.IDesc_Bind t1 x t2) bv =
Layer $ IDesc_Bind (return $ t1 bv) (identOfPattern x) (return $ t2 (bindingOfPattern x:bv))
toLN DS.IDesc_Elim bv = Layer $ IDesc_Elim
toLN (DS.SemI tD x tA) bv =
Layer $ SemI (return $ tD bv) (identOfPattern x) (return $ tA (bindingOfPattern x:bv))
toLN (DS.MapI tD i1 tA i2 tB tf tx) bv =
Layer $ MapI (return $ tD bv)
(identOfPattern i1) (return $ tA (bindingOfPattern i1:bv))
(identOfPattern i2) (return $ tB (bindingOfPattern i2:bv))
(return $ tf bv)
(return $ tx bv)
toLN (DS.LiftI tD i tA i' a tP tx) bv =
Layer $ LiftI (return $ tD bv)
(identOfPattern i) (return $ tA (bindingOfPattern i:bv))
(identOfPattern i') (identOfPattern a) (return $ tP (bindingOfPattern a:bindingOfPattern i':bv))
(return $ tx bv)
toLN (DS.MuI t1 t2) bv = Layer $ MuI (return $ t1 bv) (return $ t2 bv)
toLN (DS.Eliminate t tP i x p tK) bv =
Layer $ Eliminate (return $ t bv)
((\(x,y,t) -> (identOfPattern x, identOfPattern y, return $ t (bindingOfPattern y:bindingOfPattern x:bv))) <$> tP)
(identOfPattern i)
(identOfPattern x)
(identOfPattern p)
(return $ tK (bindingOfPattern p:bindingOfPattern x:bindingOfPattern i:bv))
toLN (DS.NamedConstructor nm tms) bv =
Layer $ NamedConstructor nm (map (\t -> return (t bv)) tms)
toLN (DS.CasesOn isRecursive tm clauses) bv =
Layer $ CasesOn isRecursive
(return $ tm bv)
(map (\(ident,patterns,tm) -> (ident,patterns,\bv' -> return $ tm (bv' ++ bv))) clauses)
toLN (DS.RecurseOn nm) bv =
case lookupVar (VarRecurse nm) bv 0 of
Just t -> t
toLN (DS.TypeAscrip t1 t2) bv = Layer $ TypeAscrip (return $ t1 bv) (return $ t2 bv)
toLN (DS.Generalise t1 t2) bv = Layer $ Generalise (return $ t1 bv) (return $ t2 bv)
toLN (DS.LabelledType nm args ty) bv =
Layer $ LabelledType nm (map (fmap (\x -> return (x bv))) args) (return $ ty bv)
toLN (DS.Return t) bv =
Layer $ Return (return $ t bv)
toLN (DS.Call t) bv =
Layer $ Call (return $ t bv)
toLN DS.UserHole bv = Layer $ UserHole
toLN (DS.Hole nm tms) bv = Layer $ Hole nm (map (\t -> return (t bv)) tms)
toLocallyNamelessClosed :: AnnotRec a DS.TermCon -> AnnotRec a TermCon
toLocallyNamelessClosed t = translateStar toLN t []
toLocallyNameless :: AnnotRec a DS.TermCon -> [Binding] -> AnnotRec a TermCon
toLocallyNameless t = translateStar toLN t
binder :: (Int -> a) -> Int -> a
binder f i = f (i+1)
close' :: [Ident] -> TermCon (Int -> a) -> Int -> TermCon a
close' fnm (Free nm global) = pure $ Free nm global
close' fnm (Bound k) = \i -> if k < i then Bound k
else let j = k - i
l = length fnm
in if j < length fnm
then Free (fnm !! j) IsLocal
else Bound (k - l)
close' fnm (Lam nm body) = Lam nm <$> binder body
close' fnm (App t ts) = App <$> t <*> ts
close' fnm (Set i) = pure $ Set i
close' fnm (Pi nm t1 t2) = Pi nm <$> t1 <*> binder t2
close' fnm (Sigma nm t1 t2) = Sigma nm <$> t1 <*> binder t2
close' fnm (Tuple t1 t2) = Tuple <$> t1 <*> t2
close' fnm (Proj1 t) = Proj1 <$> t
close' fnm (Proj2 t) = Proj2 <$> t
close' fnm (Sum t1 t2) = Sum <$> t1 <*> t2
close' fnm (Inl t) = Inl <$> t
close' fnm (Inr t) = Inr <$> t
close' fnm (Case t1 tP y t3 z t4) =
Case <$> t1
<*> traverse (\(x,tP) -> (x,) <$> binder tP) tP
<*> pure y <*> binder t3
<*> pure z <*> binder t4
close' fnm (Unit tag) = pure (Unit tag)
close' fnm UnitI = pure UnitI
close' fnm Empty = pure Empty
close' fnm (ElimEmpty t1 t2) = ElimEmpty <$> t1 <*> sequenceA t2
close' fnm (Eq t1 t2) = Eq <$> t1 <*> t2
close' fnm Refl = pure Refl
close' fnm (ElimEq t Nothing t2) = ElimEq <$> t <*> pure Nothing <*> t2
close' fnm (ElimEq t (Just (x,y,t1)) t2) = ElimEq <$> t <*> ((\t1 -> Just (x,y,t1)) <$> binder (binder t1)) <*> t2
close' fnm (Desc_K t) = Desc_K <$> t
close' fnm (Desc_Prod t1 t2)= Desc_Prod <$> t1 <*> t2
close' fnm (Construct t) = Construct <$> t
close' fnm IDesc = pure IDesc
close' fnm (IDesc_Id t) = IDesc_Id <$> t
close' fnm (IDesc_Sg t1 t2) = IDesc_Sg <$> t1 <*> t2
close' fnm (IDesc_Pi t1 t2) = IDesc_Pi <$> t1 <*> t2
close' fnm (IDesc_Bind t1 x t2) = IDesc_Bind <$> t1 <*> pure x <*> binder t2
close' fnm IDesc_Elim = pure IDesc_Elim
close' fnm (SemI tD x tA) = SemI <$> tD <*> pure x <*> binder tA
close' fnm (MapI tD i1 tA i2 tB tf tx) =
MapI <$> tD <*> pure i1 <*> binder tA <*> pure i2 <*> binder tB <*> tf <*> tx
close' fnm (MuI t1 t2) = MuI <$> t1 <*> t2
close' fnm (LiftI tD i tA i' a tP tx) =
LiftI <$> tD <*> pure i <*> binder tA <*> pure i' <*> pure a <*> binder (binder tP) <*> tx
close' fnm (Eliminate t tP i x p tK) =
Eliminate <$> t
<*> traverse (\(i,x,tP) -> (i,x,) <$> binder (binder tP)) tP
<*> pure i <*> pure x <*> pure p <*> binder (binder (binder tK))
close' fnm (NamedConstructor nm tms) = NamedConstructor nm <$> sequenceA tms
close' fnm (CasesOn isRecursive tm clauses) =
CasesOn <$> pure isRecursive
<*> tm
<*> sequenceA (map (\(ident,patterns,tm) i -> (ident,patterns,\bv' -> tm bv' (i + length bv'))) clauses)
close' fnm UserHole = pure UserHole
close' fnm (Hole nm tms) = Hole nm <$> sequenceA tms
close' fnm (TypeAscrip tm ty) = TypeAscrip <$> tm <*> ty
close' fnm (Generalise t1 t2) = Generalise <$> t1 <*> t2
close' fnm (LabelledType nm args ty) =
LabelledType nm <$> traverse sequenceA args <*> ty
close' fnm (Return t) =
Return <$> t
close' fnm (Call t) =
Call <$> t
close :: [Ident] -> AnnotRec a TermCon -> Int -> AnnotRec a TermCon
close nms x offset = translate (close' nms) x offset
|
3a4ace2dea29a5a409a8f87a123562f23ff1316410a260d737e9cb77760e9e25 | mirage/mirage-console | console_unix.mli |
* Copyright ( c ) 2010 - 2013 Anil Madhavapeddy < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2010-2013 Anil Madhavapeddy <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
(** Text console input/output operations. *)
include Mirage_console.S
val connect : string -> t Lwt.t
| null | https://raw.githubusercontent.com/mirage/mirage-console/5e31c2c92f341c0b593217d4a1370a5e0084f722/unix/console_unix.mli | ocaml | * Text console input/output operations. |
* Copyright ( c ) 2010 - 2013 Anil Madhavapeddy < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2010-2013 Anil Madhavapeddy <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
include Mirage_console.S
val connect : string -> t Lwt.t
|
5c75ec9dfcf6591500d5ebba3b76fbcb0b0fe55934cf7f5d187e8279b3d1d27a | clojurecup2014/parade-route | nrepl-editor.clj | (ns unity.nrepl.nrepl-editor
(:refer-clojure)
(:require [clojure.main :as main])
(:import
(UnityEngine Debug GUILayout)
(UnityEditor EditorGUILayout EditorWindow EditorStyles))
(:require [clojure.tools.nrepl.middleware :as middleware]
[unity.nrepl.middleware.interruptible-eval :as eval]
[unity.nrepl.middleware.session :as session]
[unity.nrepl.middleware.load-file :as load-file]
)
(:use [clojure.tools.nrepl.server :only (start-server stop-server
;default-handler
unknown-op)]))
(Debug/Log (str "CLR Version: v." Environment/Version))
(def PORT 4555)
(def HOST "0.0.0.0")
(declare server)
(def default-middlewares
[#'clojure.tools.nrepl.middleware/wrap-describe
#'eval/interruptible-eval
#'load-file/wrap-load-file
#'session/add-stdin
#'session/session])
(defn default-handler
"A default handler supporting interruptible evaluation, stdin, sessions, and
readable representations of evaluated expressions via `pr`.
Additional middlewares to mix into the default stack may be provided; these
should all be values (usually vars) that have an nREPL middleware descriptor
in their metadata (see clojure.tools.nrepl.middleware/set-descriptor!)."
[& additional-middlewares]
(let [stack (middleware/linearize-middleware-stack (concat default-middlewares
additional-middlewares))]
((apply comp (reverse stack)) unknown-op)))
(def server-running? (atom false))
(defn start
([] (start PORT HOST))
([port host]
(do
(def server (start-server :port (or port PORT)
: bind ( or host )
:handler (default-handler)
;;:greeting-fn (fn [msg] (Debug/Log "received greeting: " msg))
))
(swap! server-running? not))))
(defn stop
([] (stop "default-reason"))
([msg]
(if @server-running?
(do
(stop-server server)
(swap! server-running? not)))))
;;(stop)
(defn on-gui [window]
(GUILayout/Label "Connection Settings" EditorStyles/boldLabel nil)
(let [ip HOST
port PORT
ip (EditorGUILayout/TextField "IP:" ip nil)
port (EditorGUILayout/IntField "Port:" port nil)
run (EditorGUILayout/Toggle "Run:" @server-running? nil)]
(if (not= run @server-running?)
(if run
(start port ip)
(stop)))
(if @server-running?
(EditorGUILayout/LabelField "status" "[started]" nil)
(EditorGUILayout/LabelField "status" "[stopped]" nil))
(.Repaint window)))
;;(is-connected)
(defn on-focus []
(Debug/Log "on-focus"))
(defn on-heirarchy-change []
(Debug/Log "on-heirarchy-change"))
(defn on-inspector-update []
;(Debug/Log "on-inspector-update")
)
(defn on-project-change []
(Debug/Log "on-project-change"))
(defn on-selection-change []
(Debug/Log "on-selection-change"))
(defn update []
(eval/process-queue))
(defn on-destroy []
(Debug/Log "on-disable")
(stop "upon destroy."))
(defn on-disable []
(Debug/Log "on-disable")
(stop "upon disable."))
| null | https://raw.githubusercontent.com/clojurecup2014/parade-route/adb2e1ea202228e3da07902849dee08f0bb8d81c/Assets/Clojure/unity/nrepl/nrepl-editor.clj | clojure | default-handler
these
:greeting-fn (fn [msg] (Debug/Log "received greeting: " msg))
(stop)
(is-connected)
(Debug/Log "on-inspector-update") | (ns unity.nrepl.nrepl-editor
(:refer-clojure)
(:require [clojure.main :as main])
(:import
(UnityEngine Debug GUILayout)
(UnityEditor EditorGUILayout EditorWindow EditorStyles))
(:require [clojure.tools.nrepl.middleware :as middleware]
[unity.nrepl.middleware.interruptible-eval :as eval]
[unity.nrepl.middleware.session :as session]
[unity.nrepl.middleware.load-file :as load-file]
)
(:use [clojure.tools.nrepl.server :only (start-server stop-server
unknown-op)]))
(Debug/Log (str "CLR Version: v." Environment/Version))
(def PORT 4555)
(def HOST "0.0.0.0")
(declare server)
(def default-middlewares
[#'clojure.tools.nrepl.middleware/wrap-describe
#'eval/interruptible-eval
#'load-file/wrap-load-file
#'session/add-stdin
#'session/session])
(defn default-handler
"A default handler supporting interruptible evaluation, stdin, sessions, and
readable representations of evaluated expressions via `pr`.
should all be values (usually vars) that have an nREPL middleware descriptor
in their metadata (see clojure.tools.nrepl.middleware/set-descriptor!)."
[& additional-middlewares]
(let [stack (middleware/linearize-middleware-stack (concat default-middlewares
additional-middlewares))]
((apply comp (reverse stack)) unknown-op)))
(def server-running? (atom false))
(defn start
([] (start PORT HOST))
([port host]
(do
(def server (start-server :port (or port PORT)
: bind ( or host )
:handler (default-handler)
))
(swap! server-running? not))))
(defn stop
([] (stop "default-reason"))
([msg]
(if @server-running?
(do
(stop-server server)
(swap! server-running? not)))))
(defn on-gui [window]
(GUILayout/Label "Connection Settings" EditorStyles/boldLabel nil)
(let [ip HOST
port PORT
ip (EditorGUILayout/TextField "IP:" ip nil)
port (EditorGUILayout/IntField "Port:" port nil)
run (EditorGUILayout/Toggle "Run:" @server-running? nil)]
(if (not= run @server-running?)
(if run
(start port ip)
(stop)))
(if @server-running?
(EditorGUILayout/LabelField "status" "[started]" nil)
(EditorGUILayout/LabelField "status" "[stopped]" nil))
(.Repaint window)))
(defn on-focus []
(Debug/Log "on-focus"))
(defn on-heirarchy-change []
(Debug/Log "on-heirarchy-change"))
(defn on-inspector-update []
)
(defn on-project-change []
(Debug/Log "on-project-change"))
(defn on-selection-change []
(Debug/Log "on-selection-change"))
(defn update []
(eval/process-queue))
(defn on-destroy []
(Debug/Log "on-disable")
(stop "upon destroy."))
(defn on-disable []
(Debug/Log "on-disable")
(stop "upon disable."))
|
735427a1e282802c1f45ac5cd7a2e309643494c6f754f03d5c6c8733dc00d8b8 | spechub/Hets | Reduce_Interface.hs | # LANGUAGE FlexibleInstances #
|
Module : ./CSL / Reduce_Interface.hs
Description : interface to Reduce CAS
Copyright : ( c ) , DFKI Bremen , 2010
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non - portable ( uses type - expression in class instances )
Interface for Reduce CAS system .
Module : ./CSL/Reduce_Interface.hs
Description : interface to Reduce CAS
Copyright : (c) Dominik Dietrich, DFKI Bremen, 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non-portable (uses type-expression in class instances)
Interface for Reduce CAS system.
-}
module CSL.Reduce_Interface where
import Common.AS_Annotation
import Common.Id
import Common.ProverTools (missingExecutableInPath)
import Common.Utils (getEnvDef)
import Logic.Prover
import CSL.AS_BASIC_CSL
import CSL.ASUtils
import CSL.Parse_AS_Basic
import CSL.Lemma_Export
import Control.Monad (replicateM_)
import Data.Time (midnight)
import Data.Maybe (maybeToList)
import Data.List (intercalate)
import qualified Data.Map as Map
import System.IO
import System.Process
{- ----------------------------------------------------------------------
Connection handling
---------------------------------------------------------------------- -}
-- | A session is a process connection
class Session a where
outp :: a -> Handle
inp :: a -> Handle
err :: a -> Maybe Handle
err = const Nothing
proch :: a -> Maybe ProcessHandle
proch = const Nothing
-- | The simplest session
instance Session (Handle, Handle) where
inp = fst
outp = snd
-- | Better use this session to properly close the connection
instance Session (Handle, Handle, ProcessHandle) where
inp (x, _, _) = x
outp (_, x, _) = x
proch (_, _, x) = Just x
-- | Left String is success, Right String is failure
lookupRedShellCmd :: IO (Either String String)
lookupRedShellCmd = do
reducecmd <- getEnvDef "HETS_REDUCE" "redcsl"
-- check that prog exists
noProg <- missingExecutableInPath reducecmd
let f = if noProg then Right else Left
return $ f reducecmd
| connects to the CAS , prepares the streams and sets initial options
connectCAS :: String -> IO (Handle, Handle, Handle, ProcessHandle)
connectCAS reducecmd = do
putStrLn "succeeded"
(inpt, out, errh, pid) <- runInteractiveCommand $ reducecmd ++ " -w"
hSetBuffering out NoBuffering
hSetBuffering inpt LineBuffering
hPutStrLn inpt "off nat;"
hPutStrLn inpt "load redlog;"
hPutStrLn inpt "rlset reals;"
read 7 lines
replicateM_ 7 $ hGetLine out
putStrLn "done"
return (inpt, out, errh, pid)
| closes the connection to the CAS
disconnectCAS :: Session a => a -> IO ()
disconnectCAS s = do
hPutStrLn (inp s) "quit;"
case proch s of
Nothing -> return ()
this is always better , because it closes also the shell - process ,
hence use a Session - variant with ProcessHandle !
hence use a Session-variant with ProcessHandle! -}
Just ph -> waitForProcess ph >> return ()
putStrLn "CAS disconnected"
return ()
sendToReduce :: Session a => a -> String -> IO ()
sendToReduce sess = hPutStrLn (inp sess)
{- ----------------------------------------------------------------------
Prover specific
---------------------------------------------------------------------- -}
-- | returns the name of the reduce prover
reduceS :: String
reduceS = "Reduce"
{- | returns a basic proof status for conjecture with name n
where [EXPRESSION] represents the proof tree. -}
openReduceProofStatus :: String -> [EXPRESSION] -> ProofStatus [EXPRESSION]
openReduceProofStatus n = openProofStatus n reduceS
closedReduceProofStatus :: Ord pt => String -- ^ name of the goal
-> pt -> ProofStatus pt
closedReduceProofStatus goalname proof_tree =
ProofStatus
{ goalName = goalname
, goalStatus = Proved True
, usedAxioms = []
, usedProver = reduceS
, proofTree = proof_tree
, usedTime = midnight
, tacticScript = TacticScript ""
, proofLines = [] }
For Quantifier Elimination :
off nat ; -- pretty - printing switch
load redlog ;
rlset reals ;
rlqe(exp ... ) ;
For Quantifier Elimination:
off nat; -- pretty-printing switch
load redlog;
rlset reals;
rlqe(exp...);
-}
{- ----------------------------------------------------------------------
Reduce Pretty Printing
---------------------------------------------------------------------- -}
exportExps :: [EXPRESSION] -> String
exportExps l = intercalate "," $ map exportExp l
-- | those operators declared as infix in Reduce
infixOps :: [String]
infixOps = [ "+", "-", "/", "**", "^", "=", "<=", ">=", "<", ">", "*", "and"
, "impl", "or"]
-- | Exports an expression to Reduce format
exportExp :: EXPRESSION -> String
exportExp (Var token) = tokStr token
exportExp (Op s _ exps@[e1, e2] _)
| elem (simpleName s) infixOps =
concat ["(", exportExp e1, simpleName s, exportExp e2, ")"]
| otherwise = concat [simpleName s, "(", exportExps exps, ")"]
exportExp (Op s _ [] _) = simpleName s
exportExp (Op s _ exps _) = concat [simpleName s, "(", exportExps exps, ")"]
exportExp (List exps _) = "{" ++ exportExps exps ++ "}"
exportExp (Int i _) = show i
exportExp (Rat d _) = show d
exportExp (Interval l r _) = concat [ "[", show l, ",", show r, "]" ]
-- exportExp e = error $ "exportExp: expression not supported: " ++ show e
-- | exports command to Reduce Format
exportReduce :: Named CMD -> String
exportReduce namedcmd = case sentence namedcmd of
Cmd "simplify" exps -> exportExp $ head exps
Cmd "ask" exps -> exportExp $ head exps
Cmd cmd exps -> cmd ++ "(" ++ exportExps exps ++ ")"
_ -> error "exportReduce: not implemented for this case" -- TODO: implement
{- ----------------------------------------------------------------------
Reduce Parsing
---------------------------------------------------------------------- -}
| removes the newlines 4 : from the beginning of the string
skipReduceLineNr :: String -> String
skipReduceLineNr s = dropWhile (`elem` " \n") $ tail
$ dropWhile (/= ':') s
-- | try to get an EXPRESSION from a Reduce string
redOutputToExpression :: String -> Maybe EXPRESSION
redOutputToExpression = parseExpression () . skipReduceLineNr
{- ----------------------------------------------------------------------
Reduce Commands
---------------------------------------------------------------------- -}
cslReduceDefaultMapping :: [(OPNAME, String)]
cslReduceDefaultMapping =
let idmapping = map (\ x -> (x, show x))
in (OP_pow, "**") :
idmapping (Map.keys $ Map.delete OP_pow operatorInfoNameMap)
| reads characters from the specified output until the next result is
complete , indicated by $ when using the maxima mode off nat ;
complete, indicated by $ when using the maxima mode off nat; -}
getNextResultOutput :: Handle -> IO String
getNextResultOutput out = do
b <- hIsEOF out
if b then return "" else do
c <- hGetChar out
if c == '$' then return [] else do
r <- getNextResultOutput out
return (c : r)
procCmd :: Session a => a -> Named CMD
-> IO (ProofStatus [EXPRESSION], [(Named CMD, ProofStatus [EXPRESSION])])
procCmd sess cmd = case cmdstring of
"simplify" -> cassimplify sess cmd
"ask" -> casask sess cmd
"divide" -> casremainder sess cmd
"rlqe" -> casqelim sess cmd
"factorize" -> casfactorExp sess cmd
"int" -> casint sess cmd
"solve" -> cassolve sess cmd
_ -> error "Command not supported"
where Cmd cmdstring _ = sentence cmd
| sends the given string to the CAS , reads the result and tries to parse it .
evalString :: Session a => a -> String -> IO [EXPRESSION]
evalString sess s = do
putStrLn $ "Send CAS cmd " ++ s
hPutStrLn (inp sess) s
res <- getNextResultOutput (outp sess)
putStrLn $ "Result is " ++ res
putStrLn $ "Parsing of --" ++ skipReduceLineNr res ++ "-- yields "
++ show (redOutputToExpression res)
return $ maybeToList $ redOutputToExpression res
| wrap evalString into a ProofStatus
procString :: Session a => a -> String -> String -> IO (ProofStatus [EXPRESSION])
procString h axname s = do
res <- evalString h s
let f = if null res then openReduceProofStatus else closedReduceProofStatus
return $ f axname res
-- | factors a given expression over the reals
casfactorExp :: Session a => a -> Named CMD -> IO (ProofStatus [EXPRESSION],
[(Named CMD, ProofStatus [EXPRESSION])])
casfactorExp sess cmd =
do
proofstatus <- procString sess (senAttr cmd) $ exportReduce cmd ++ ";"
return (proofstatus, [exportLemmaFactor cmd proofstatus])
-- | solves a single equation over the reals
cassolve :: Session a => a -> Named CMD -> IO (ProofStatus [EXPRESSION],
[(Named CMD, ProofStatus [EXPRESSION])])
cassolve sess cmd =
do
proofstatus <- procString sess (senAttr cmd) $ exportReduce cmd ++ ";"
return (proofstatus, [])
-- | simplifies a given expression over the reals
cassimplify :: Session a => a -> Named CMD -> IO (ProofStatus [EXPRESSION],
[(Named CMD, ProofStatus [EXPRESSION])])
cassimplify sess cmd = do
proofstatus <- procString sess (senAttr cmd) $ exportReduce cmd ++ ";"
return (proofstatus, [exportLemmaSimplify cmd proofstatus])
-- | asks value of a given expression
casask :: Session a => a -> Named CMD -> IO (ProofStatus [EXPRESSION],
[(Named CMD, ProofStatus [EXPRESSION])])
casask sess cmd = do
proofstatus <- procString sess (senAttr cmd) $ exportReduce cmd ++ ";"
return (proofstatus, [exportLemmaAsk cmd proofstatus])
-- | computes the remainder of a division
casremainder :: Session a => a -> Named CMD -> IO (ProofStatus [EXPRESSION],
[(Named CMD, ProofStatus [EXPRESSION])])
casremainder sess cmd =
do
proofstatus <- procString sess (senAttr cmd) $ exportReduce
(makeNamed (senAttr cmd) (Cmd "divide" args)) ++ ";"
return (proofstatus, [exportLemmaRemainder cmd proofstatus])
where Cmd _ args = sentence cmd
-- | integrates the given expression
casint :: Session a => a -> Named CMD -> IO (ProofStatus [EXPRESSION],
[(Named CMD, ProofStatus [EXPRESSION])])
casint sess cmd =
do
proofstatus <- procString sess (senAttr cmd) $ exportReduce cmd ++ ";"
return (proofstatus, [exportLemmaInt cmd proofstatus])
-- | performs quantifier elimination of a given expression
casqelim :: Session a => a -> Named CMD -> IO (ProofStatus [EXPRESSION],
[(Named CMD, ProofStatus [EXPRESSION])])
casqelim sess cmd =
do
proofstatus <- procString sess (senAttr cmd) $ exportReduce cmd ++ ";"
return (proofstatus, [exportLemmaQelim cmd proofstatus])
| declares an operator , such that it can used infix / prefix in CAS
casDeclareOperators :: Session a => a -> [EXPRESSION] -> IO ()
casDeclareOperators sess varlist = do
hPutStrLn (inp sess) $ "operator " ++ exportExps varlist ++ ";"
hGetLine (outp sess)
return ()
-- | declares an equation x := exp
casDeclareEquation :: Session a => a -> CMD -> IO ()
casDeclareEquation sess (Ass c def) =
do
let e1 = exportExp $ opDeclToOp c
e2 = exportExp def
putStrLn $ e1 ++ ":=" ++ e2
hPutStrLn (inp sess) $ e1 ++ ":=" ++ e2 ++ ";"
res <- getNextResultOutput (outp sess)
putStrLn $ "Declaration Result: " ++ res
return ()
casDeclareEquation _ _ =
error "casDeclareEquation: not implemented for this case" -- TODO: implement
{- ----------------------------------------------------------------------
Reduce Lemma Export
---------------------------------------------------------------------- -}
exportLemmaGeneric :: Named CMD -> ProofStatus [EXPRESSION] ->
(Named CMD, ProofStatus [EXPRESSION])
exportLemmaGeneric namedcmd ps =
(makeNamed lemmaname lemma, closedReduceProofStatus lemmaname [mkOp "Proof" []])
where Cmd _ exps = sentence namedcmd
lemma = Cmd "=" [head exps, head (proofTree ps)]
lemmaname = ganame namedcmd
exportLemmaQelim :: Named CMD -> ProofStatus [EXPRESSION] ->
(Named CMD, ProofStatus [EXPRESSION])
exportLemmaQelim = exportLemmaGeneric
| generates the lemma for cmd with result ProofStatus
exportLemmaFactor :: Named CMD -> ProofStatus [EXPRESSION] ->
(Named CMD, ProofStatus [EXPRESSION])
exportLemmaFactor = exportLemmaGeneric
exportLemmaSolve :: Named CMD -> ProofStatus [EXPRESSION] ->
(Named CMD, ProofStatus [EXPRESSION])
exportLemmaSolve = exportLemmaGeneric
exportLemmaSimplify :: Named CMD -> ProofStatus [EXPRESSION] ->
(Named CMD, ProofStatus [EXPRESSION])
exportLemmaSimplify = exportLemmaGeneric
exportLemmaAsk :: Named CMD -> ProofStatus [EXPRESSION] ->
(Named CMD, ProofStatus [EXPRESSION])
exportLemmaAsk = exportLemmaGeneric
exportLemmaRemainder :: Named CMD -> ProofStatus [EXPRESSION] ->
(Named CMD, ProofStatus [EXPRESSION])
exportLemmaRemainder = exportLemmaGeneric
exportLemmaInt :: Named CMD -> ProofStatus [EXPRESSION] ->
(Named CMD, ProofStatus [EXPRESSION])
exportLemmaInt = exportLemmaGeneric
| null | https://raw.githubusercontent.com/spechub/Hets/af7b628a75aab0d510b8ae7f067a5c9bc48d0f9e/CSL/Reduce_Interface.hs | haskell | ----------------------------------------------------------------------
Connection handling
----------------------------------------------------------------------
| A session is a process connection
| The simplest session
| Better use this session to properly close the connection
| Left String is success, Right String is failure
check that prog exists
----------------------------------------------------------------------
Prover specific
----------------------------------------------------------------------
| returns the name of the reduce prover
| returns a basic proof status for conjecture with name n
where [EXPRESSION] represents the proof tree.
^ name of the goal
pretty - printing switch
pretty-printing switch
----------------------------------------------------------------------
Reduce Pretty Printing
----------------------------------------------------------------------
| those operators declared as infix in Reduce
| Exports an expression to Reduce format
exportExp e = error $ "exportExp: expression not supported: " ++ show e
| exports command to Reduce Format
TODO: implement
----------------------------------------------------------------------
Reduce Parsing
----------------------------------------------------------------------
| try to get an EXPRESSION from a Reduce string
----------------------------------------------------------------------
Reduce Commands
----------------------------------------------------------------------
| factors a given expression over the reals
| solves a single equation over the reals
| simplifies a given expression over the reals
| asks value of a given expression
| computes the remainder of a division
| integrates the given expression
| performs quantifier elimination of a given expression
| declares an equation x := exp
TODO: implement
----------------------------------------------------------------------
Reduce Lemma Export
---------------------------------------------------------------------- | # LANGUAGE FlexibleInstances #
|
Module : ./CSL / Reduce_Interface.hs
Description : interface to Reduce CAS
Copyright : ( c ) , DFKI Bremen , 2010
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non - portable ( uses type - expression in class instances )
Interface for Reduce CAS system .
Module : ./CSL/Reduce_Interface.hs
Description : interface to Reduce CAS
Copyright : (c) Dominik Dietrich, DFKI Bremen, 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non-portable (uses type-expression in class instances)
Interface for Reduce CAS system.
-}
module CSL.Reduce_Interface where
import Common.AS_Annotation
import Common.Id
import Common.ProverTools (missingExecutableInPath)
import Common.Utils (getEnvDef)
import Logic.Prover
import CSL.AS_BASIC_CSL
import CSL.ASUtils
import CSL.Parse_AS_Basic
import CSL.Lemma_Export
import Control.Monad (replicateM_)
import Data.Time (midnight)
import Data.Maybe (maybeToList)
import Data.List (intercalate)
import qualified Data.Map as Map
import System.IO
import System.Process
class Session a where
outp :: a -> Handle
inp :: a -> Handle
err :: a -> Maybe Handle
err = const Nothing
proch :: a -> Maybe ProcessHandle
proch = const Nothing
instance Session (Handle, Handle) where
inp = fst
outp = snd
instance Session (Handle, Handle, ProcessHandle) where
inp (x, _, _) = x
outp (_, x, _) = x
proch (_, _, x) = Just x
lookupRedShellCmd :: IO (Either String String)
lookupRedShellCmd = do
reducecmd <- getEnvDef "HETS_REDUCE" "redcsl"
noProg <- missingExecutableInPath reducecmd
let f = if noProg then Right else Left
return $ f reducecmd
| connects to the CAS , prepares the streams and sets initial options
connectCAS :: String -> IO (Handle, Handle, Handle, ProcessHandle)
connectCAS reducecmd = do
putStrLn "succeeded"
(inpt, out, errh, pid) <- runInteractiveCommand $ reducecmd ++ " -w"
hSetBuffering out NoBuffering
hSetBuffering inpt LineBuffering
hPutStrLn inpt "off nat;"
hPutStrLn inpt "load redlog;"
hPutStrLn inpt "rlset reals;"
read 7 lines
replicateM_ 7 $ hGetLine out
putStrLn "done"
return (inpt, out, errh, pid)
| closes the connection to the CAS
disconnectCAS :: Session a => a -> IO ()
disconnectCAS s = do
hPutStrLn (inp s) "quit;"
case proch s of
Nothing -> return ()
this is always better , because it closes also the shell - process ,
hence use a Session - variant with ProcessHandle !
hence use a Session-variant with ProcessHandle! -}
Just ph -> waitForProcess ph >> return ()
putStrLn "CAS disconnected"
return ()
sendToReduce :: Session a => a -> String -> IO ()
sendToReduce sess = hPutStrLn (inp sess)
reduceS :: String
reduceS = "Reduce"
openReduceProofStatus :: String -> [EXPRESSION] -> ProofStatus [EXPRESSION]
openReduceProofStatus n = openProofStatus n reduceS
-> pt -> ProofStatus pt
closedReduceProofStatus goalname proof_tree =
ProofStatus
{ goalName = goalname
, goalStatus = Proved True
, usedAxioms = []
, usedProver = reduceS
, proofTree = proof_tree
, usedTime = midnight
, tacticScript = TacticScript ""
, proofLines = [] }
For Quantifier Elimination :
load redlog ;
rlset reals ;
rlqe(exp ... ) ;
For Quantifier Elimination:
load redlog;
rlset reals;
rlqe(exp...);
-}
exportExps :: [EXPRESSION] -> String
exportExps l = intercalate "," $ map exportExp l
infixOps :: [String]
infixOps = [ "+", "-", "/", "**", "^", "=", "<=", ">=", "<", ">", "*", "and"
, "impl", "or"]
exportExp :: EXPRESSION -> String
exportExp (Var token) = tokStr token
exportExp (Op s _ exps@[e1, e2] _)
| elem (simpleName s) infixOps =
concat ["(", exportExp e1, simpleName s, exportExp e2, ")"]
| otherwise = concat [simpleName s, "(", exportExps exps, ")"]
exportExp (Op s _ [] _) = simpleName s
exportExp (Op s _ exps _) = concat [simpleName s, "(", exportExps exps, ")"]
exportExp (List exps _) = "{" ++ exportExps exps ++ "}"
exportExp (Int i _) = show i
exportExp (Rat d _) = show d
exportExp (Interval l r _) = concat [ "[", show l, ",", show r, "]" ]
exportReduce :: Named CMD -> String
exportReduce namedcmd = case sentence namedcmd of
Cmd "simplify" exps -> exportExp $ head exps
Cmd "ask" exps -> exportExp $ head exps
Cmd cmd exps -> cmd ++ "(" ++ exportExps exps ++ ")"
| removes the newlines 4 : from the beginning of the string
skipReduceLineNr :: String -> String
skipReduceLineNr s = dropWhile (`elem` " \n") $ tail
$ dropWhile (/= ':') s
redOutputToExpression :: String -> Maybe EXPRESSION
redOutputToExpression = parseExpression () . skipReduceLineNr
cslReduceDefaultMapping :: [(OPNAME, String)]
cslReduceDefaultMapping =
let idmapping = map (\ x -> (x, show x))
in (OP_pow, "**") :
idmapping (Map.keys $ Map.delete OP_pow operatorInfoNameMap)
| reads characters from the specified output until the next result is
complete , indicated by $ when using the maxima mode off nat ;
complete, indicated by $ when using the maxima mode off nat; -}
getNextResultOutput :: Handle -> IO String
getNextResultOutput out = do
b <- hIsEOF out
if b then return "" else do
c <- hGetChar out
if c == '$' then return [] else do
r <- getNextResultOutput out
return (c : r)
procCmd :: Session a => a -> Named CMD
-> IO (ProofStatus [EXPRESSION], [(Named CMD, ProofStatus [EXPRESSION])])
procCmd sess cmd = case cmdstring of
"simplify" -> cassimplify sess cmd
"ask" -> casask sess cmd
"divide" -> casremainder sess cmd
"rlqe" -> casqelim sess cmd
"factorize" -> casfactorExp sess cmd
"int" -> casint sess cmd
"solve" -> cassolve sess cmd
_ -> error "Command not supported"
where Cmd cmdstring _ = sentence cmd
| sends the given string to the CAS , reads the result and tries to parse it .
evalString :: Session a => a -> String -> IO [EXPRESSION]
evalString sess s = do
putStrLn $ "Send CAS cmd " ++ s
hPutStrLn (inp sess) s
res <- getNextResultOutput (outp sess)
putStrLn $ "Result is " ++ res
putStrLn $ "Parsing of --" ++ skipReduceLineNr res ++ "-- yields "
++ show (redOutputToExpression res)
return $ maybeToList $ redOutputToExpression res
| wrap evalString into a ProofStatus
procString :: Session a => a -> String -> String -> IO (ProofStatus [EXPRESSION])
procString h axname s = do
res <- evalString h s
let f = if null res then openReduceProofStatus else closedReduceProofStatus
return $ f axname res
casfactorExp :: Session a => a -> Named CMD -> IO (ProofStatus [EXPRESSION],
[(Named CMD, ProofStatus [EXPRESSION])])
casfactorExp sess cmd =
do
proofstatus <- procString sess (senAttr cmd) $ exportReduce cmd ++ ";"
return (proofstatus, [exportLemmaFactor cmd proofstatus])
cassolve :: Session a => a -> Named CMD -> IO (ProofStatus [EXPRESSION],
[(Named CMD, ProofStatus [EXPRESSION])])
cassolve sess cmd =
do
proofstatus <- procString sess (senAttr cmd) $ exportReduce cmd ++ ";"
return (proofstatus, [])
cassimplify :: Session a => a -> Named CMD -> IO (ProofStatus [EXPRESSION],
[(Named CMD, ProofStatus [EXPRESSION])])
cassimplify sess cmd = do
proofstatus <- procString sess (senAttr cmd) $ exportReduce cmd ++ ";"
return (proofstatus, [exportLemmaSimplify cmd proofstatus])
casask :: Session a => a -> Named CMD -> IO (ProofStatus [EXPRESSION],
[(Named CMD, ProofStatus [EXPRESSION])])
casask sess cmd = do
proofstatus <- procString sess (senAttr cmd) $ exportReduce cmd ++ ";"
return (proofstatus, [exportLemmaAsk cmd proofstatus])
casremainder :: Session a => a -> Named CMD -> IO (ProofStatus [EXPRESSION],
[(Named CMD, ProofStatus [EXPRESSION])])
casremainder sess cmd =
do
proofstatus <- procString sess (senAttr cmd) $ exportReduce
(makeNamed (senAttr cmd) (Cmd "divide" args)) ++ ";"
return (proofstatus, [exportLemmaRemainder cmd proofstatus])
where Cmd _ args = sentence cmd
casint :: Session a => a -> Named CMD -> IO (ProofStatus [EXPRESSION],
[(Named CMD, ProofStatus [EXPRESSION])])
casint sess cmd =
do
proofstatus <- procString sess (senAttr cmd) $ exportReduce cmd ++ ";"
return (proofstatus, [exportLemmaInt cmd proofstatus])
casqelim :: Session a => a -> Named CMD -> IO (ProofStatus [EXPRESSION],
[(Named CMD, ProofStatus [EXPRESSION])])
casqelim sess cmd =
do
proofstatus <- procString sess (senAttr cmd) $ exportReduce cmd ++ ";"
return (proofstatus, [exportLemmaQelim cmd proofstatus])
| declares an operator , such that it can used infix / prefix in CAS
casDeclareOperators :: Session a => a -> [EXPRESSION] -> IO ()
casDeclareOperators sess varlist = do
hPutStrLn (inp sess) $ "operator " ++ exportExps varlist ++ ";"
hGetLine (outp sess)
return ()
casDeclareEquation :: Session a => a -> CMD -> IO ()
casDeclareEquation sess (Ass c def) =
do
let e1 = exportExp $ opDeclToOp c
e2 = exportExp def
putStrLn $ e1 ++ ":=" ++ e2
hPutStrLn (inp sess) $ e1 ++ ":=" ++ e2 ++ ";"
res <- getNextResultOutput (outp sess)
putStrLn $ "Declaration Result: " ++ res
return ()
casDeclareEquation _ _ =
exportLemmaGeneric :: Named CMD -> ProofStatus [EXPRESSION] ->
(Named CMD, ProofStatus [EXPRESSION])
exportLemmaGeneric namedcmd ps =
(makeNamed lemmaname lemma, closedReduceProofStatus lemmaname [mkOp "Proof" []])
where Cmd _ exps = sentence namedcmd
lemma = Cmd "=" [head exps, head (proofTree ps)]
lemmaname = ganame namedcmd
exportLemmaQelim :: Named CMD -> ProofStatus [EXPRESSION] ->
(Named CMD, ProofStatus [EXPRESSION])
exportLemmaQelim = exportLemmaGeneric
| generates the lemma for cmd with result ProofStatus
exportLemmaFactor :: Named CMD -> ProofStatus [EXPRESSION] ->
(Named CMD, ProofStatus [EXPRESSION])
exportLemmaFactor = exportLemmaGeneric
exportLemmaSolve :: Named CMD -> ProofStatus [EXPRESSION] ->
(Named CMD, ProofStatus [EXPRESSION])
exportLemmaSolve = exportLemmaGeneric
exportLemmaSimplify :: Named CMD -> ProofStatus [EXPRESSION] ->
(Named CMD, ProofStatus [EXPRESSION])
exportLemmaSimplify = exportLemmaGeneric
exportLemmaAsk :: Named CMD -> ProofStatus [EXPRESSION] ->
(Named CMD, ProofStatus [EXPRESSION])
exportLemmaAsk = exportLemmaGeneric
exportLemmaRemainder :: Named CMD -> ProofStatus [EXPRESSION] ->
(Named CMD, ProofStatus [EXPRESSION])
exportLemmaRemainder = exportLemmaGeneric
exportLemmaInt :: Named CMD -> ProofStatus [EXPRESSION] ->
(Named CMD, ProofStatus [EXPRESSION])
exportLemmaInt = exportLemmaGeneric
|
eea11a11563e10442dba03d76782f3cccc7fad4d6fb66c27a3badf95f7aa6083 | rabbitmq/erlang-data-structures | finger_tree.erl | The contents of this file are subject to the Mozilla Public License
%% Version 1.1 (the "License"); you may not use this file except in
%% compliance with the License. You may obtain a copy of the License
%% at /
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and
%% limitations under the License.
%%
The Original Code is RabbitMQ Erlang Data Structures .
%%
The Initial Developer of the Original Code is VMware , Inc.
Copyright ( c ) 2011 - 2013 VMware , Inc. All rights reserved .
%%
-module(finger_tree, [Measure, Null, Add]).
This is an Erlang implementation of 2 - 3 finger trees , as defined by
and in their " Finger Trees : A Simple
General - purpose Data Structure " paper[0 ] .
%%
%% As usual with a queue-like thing, adding and removing from either
end is ) amortized .
%%
On the whole , nearly everything else is ) ) , including
%% join. Whilst there are instances of list append (++) in the code,
it 's only lists that are bounded in length to four items .
%%
Because Erlang lacks type classes , it 's currently forced to cache
sizes . This allows len to be O(1 ) , and permits split_at based on
index , which still remains O(log_2(N ) ) which demonstrates we 're
%% able to take advantage of the tree structure. However, it's not
%% difficult to imagine a callback mechanism to allow the monoid
%% implementation to vary. See the paper[0] for examples of other
%% things that could be implemented.
%%
%% [0]: /~ross/papers/FingerTree.html
-compile([export_all]).
-record(finger_tree_single, {elem}).
-record(finger_tree_deep, {measured, prefix, middle, suffix}).
-record(node, {measured, tuple}).
-record(digit, {list}).
empty() -> finger_tree_empty.
%% To/From list
cons(A, L) -> [A | L].
to_list(FT) -> reduce_r(fun cons/2, FT, []).
from_list(L) -> reduce_r_in(L, finger_tree_empty).
is_empty(finger_tree_empty) -> true;
is_empty(#finger_tree_single {}) -> false;
is_empty(#finger_tree_deep {}) -> false.
Smart constructors
digit(A) -> #digit { list = A }.
node2(A, B) ->
#node { tuple = {A, B}, measured = Add(measure(A), measure(B)) }.
node3(A, B, C) ->
#node { tuple = {A, B, C},
measured = Add(Add(measure(A), measure(B)), measure(C)) }.
deep(Prefix, Middle, Suffix) ->
#finger_tree_deep { measured = Add(Add(measure(Prefix),
measure(Middle)),
measure(Suffix)),
prefix = Prefix, middle = Middle, suffix = Suffix }.
deep_r(#digit { list = [] }, M, S) ->
case uncons_r(M) of
{empty, _ } -> from_list(S);
{{value, A}, M1} -> deep(digit(to_list(A)), M1, S)
end;
deep_r(P, M, S) ->
deep(P, M, S).
deep_l(P, M, #digit { list = [] }) ->
case uncons_l(M) of
{empty, _} -> from_list(P);
{{value, A}, M1} -> deep(P, M1, digit(to_list(A)))
end;
deep_l(P, M, S) ->
deep(P, M, S).
%% Monoid
measure(finger_tree_empty) -> Null();
measure(#finger_tree_single { elem = E }) -> measure(E);
measure(#finger_tree_deep{ measured = V }) -> V;
measure(#node { measured = V }) -> V;
measure(#digit { list = Xs }) ->
reduce_l(fun (A, I) -> Add(I, measure(A)) end, Xs, Null());
measure(X) -> Measure(X).
%% Reduce primitives
reduce_r(_Fun, finger_tree_empty, Z) -> Z;
reduce_r(Fun, #finger_tree_single { elem = E }, Z) -> Fun(E, Z);
reduce_r(Fun, #finger_tree_deep { prefix = P, middle = M, suffix = S }, Z) ->
R = reduce_r(fun (A, B) -> reduce_r(Fun, A, B) end, M, reduce_r(Fun, S, Z)),
reduce_r(Fun, P, R);
reduce_r(Fun, #node { tuple = {A, B} }, Z) -> Fun(A, Fun(B, Z));
reduce_r(Fun, #node { tuple = {A, B, C} }, Z) -> Fun(A, Fun(B, Fun(C, Z)));
reduce_r(Fun, #digit { list = List }, Z) -> lists:foldr(Fun, Z, List);
reduce_r(Fun, X, Z) when is_list(X) -> lists:foldr(Fun, Z, X).
reduce_l(_Fun, finger_tree_empty, Z) -> Z;
reduce_l(Fun, #finger_tree_single { elem = E }, Z) -> Fun(Z, E);
reduce_l(Fun, #finger_tree_deep { prefix = P, middle = M, suffix = S }, Z) ->
L = reduce_l(fun (A, B) -> reduce_l(Fun, A, B) end, reduce_l(Fun, Z, P), M),
reduce_l(Fun, L, S);
reduce_l(Fun, #node { tuple = {A, B} }, Z) -> Fun(Fun(Z, B), A);
reduce_l(Fun, #node { tuple = {A, B, C} }, Z) -> Fun(Fun(Fun(Z, C), B), A);
reduce_l(Fun, #digit { list = List }, Z) -> lists:foldl(Fun, Z, List);
reduce_l(Fun, X, Z) when is_list(X) -> lists:foldl(Fun, Z, X).
reduce_r_in(X, FT) -> reduce_r(fun cons_r/2, X, FT).
reduce_l_in(X, FT) -> reduce_l(fun cons_l/2, X, FT).
Consing
cons_r(A, finger_tree_empty) ->
#finger_tree_single { elem = A };
cons_r(A, #finger_tree_single { elem = B }) ->
deep(digit([A]), finger_tree_empty, digit([B]));
cons_r(A, #finger_tree_deep { prefix = #digit { list = [B, C, D, E] }, middle = M, suffix = S }) ->
deep(digit([A, B]), cons_r(node3(C, D, E), M), S);
cons_r(A, #finger_tree_deep { prefix = #digit { list = P }, middle = M, suffix = S }) ->
deep(digit([A | P]), M, S).
cons_l(A, finger_tree_empty) ->
#finger_tree_single { elem = A };
cons_l(A, #finger_tree_single { elem = B }) ->
deep(digit([B]), finger_tree_empty, digit([A]));
cons_l(A, #finger_tree_deep { prefix = P, middle = M, suffix = #digit { list = [E, D, C, B] } }) ->
deep(P, cons_l(node3(E, D, C), M), digit([B, A]));
cons_l(A, #finger_tree_deep { prefix = P, middle = M, suffix = #digit { list = S } }) ->
deep(P, M, digit(S ++ [A])).
%% Unconsing
uncons_r(finger_tree_empty = FT) ->
{empty, FT};
uncons_r(#finger_tree_single { elem = E }) ->
{{value, E}, finger_tree_empty};
uncons_r(#finger_tree_deep { prefix = #digit { list = [A | P] }, middle = M, suffix = S }) ->
{{value, A}, deep_r(digit(P), M, S)}.
uncons_l(finger_tree_empty = FT) ->
{empty, FT};
uncons_l(#finger_tree_single { elem = E }) ->
{{value, E}, finger_tree_empty};
uncons_l(#finger_tree_deep { prefix = P, middle = M, suffix = #digit { list = S } }) ->
case S of
[A] -> {{value, A}, deep_l(P, M, digit([]))};
_ -> [A | S1] = lists:reverse(S),
{{value, A}, deep_l(P, M, digit(lists:reverse(S1)))}
end.
%% Joining
ft_nodes([A, B]) -> [node2(A, B)];
ft_nodes([A, B, C]) -> [node3(A, B, C)];
ft_nodes([A, B, C, D]) -> [node2(A, B), node2(C, D)];
ft_nodes([A, B, C | Xs]) -> [node3(A, B, C) | ft_nodes(Xs)].
app3(finger_tree_empty, Ts, Xs) ->
reduce_r_in(Ts, Xs);
app3(Xs, Ts, finger_tree_empty) ->
reduce_l_in(Ts, Xs);
app3(#finger_tree_single { elem = E }, Ts, Xs) ->
cons_r(E, reduce_r_in(Ts, Xs));
app3(Xs, Ts, #finger_tree_single { elem = E }) ->
cons_l(E, reduce_l_in(Ts, Xs));
app3(#finger_tree_deep { prefix = P1, middle = M1, suffix = #digit { list = S1 } }, #digit { list = Ts },
#finger_tree_deep { prefix = #digit { list = P2 }, middle = M2, suffix = S2 }) ->
deep(P1, app3(M1, digit(ft_nodes(S1 ++ (Ts ++ P2))), M2), S2).
join(FT1, FT2) -> app3(FT1, digit([]), FT2).
%% Splitting
split_digit(_Pred, _Init, #digit { list = [A] }) ->
{split, digit([]), A, digit([])};
split_digit(Pred, Init, #digit { list = [A | List] }) ->
Init1 = Add(Init, measure(A)),
case Pred(Init1) of
true -> {split, digit([]), A, digit(List)};
false -> {split, #digit { list = L }, X, R} = split_digit(Pred, Init1, digit(List)),
{split, digit([A | L]), X, R}
end.
split_node(Pred, Init, #node { tuple = {A, B} }) ->
Init1 = Add(Init, measure(A)),
case Pred(Init1) of
true -> {split, digit([]), A, digit([B])};
false -> {split, digit([A]), B, digit([])}
end;
split_node(Pred, Init, #node { tuple = {A, B, C} }) ->
Init1 = Add(Init, measure(A)),
case Pred(Init1) of
true -> {split, digit([]), A, digit([B, C])};
false -> Init2 = Add(Init1, measure(B)),
case Pred(Init2) of
true -> {split, digit([A]), B, digit([C])};
false -> {split, digit([A, B]), C, digit([])}
end
end.
split_tree(_Pred, _Init, #finger_tree_single { elem = E }) ->
{split, finger_tree_empty, E, finger_tree_empty};
split_tree(Pred, Init, #finger_tree_deep { prefix = P, middle = M, suffix = S }) ->
VP = Add(Init, measure(P)),
case Pred(VP) of
true ->
{split, #digit { list = L }, X, R} = split_digit(Pred, Init, P),
{split, from_list(L), X, deep_r(R, M, S)};
false ->
VM = Add(VP, measure(M)),
case VM /= VP andalso Pred(VM) of
true ->
{split, ML, Xs, MR} = split_tree(Pred, VP, M),
Init1 = Add(VP, measure(ML)),
{split, L, X, R} = split_node(Pred, Init1, Xs),
{split, deep_l(P, ML, L), X, deep_r(R, MR, S)};
false ->
{split, L, X, #digit { list = R }} = split_digit(Pred, VM, S),
{split, deep_l(P, M, L), X, from_list(R)}
end
end.
split(_Pred, finger_tree_empty) ->
{finger_tree_empty, finger_tree_empty};
split(Pred, FT) ->
{split, L, X, R} = split_tree(Pred, Null(), FT),
case Pred(measure(FT)) of
true -> {L, cons_r(X, R)};
false -> {FT, finger_tree_empty}
end.
| null | https://raw.githubusercontent.com/rabbitmq/erlang-data-structures/7f9b5427200e8247c77ce1cc146eb10be9095791/finger_tree/src/finger_tree.erl | erlang | Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at /
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and
limitations under the License.
As usual with a queue-like thing, adding and removing from either
join. Whilst there are instances of list append (++) in the code,
able to take advantage of the tree structure. However, it's not
difficult to imagine a callback mechanism to allow the monoid
implementation to vary. See the paper[0] for examples of other
things that could be implemented.
[0]: /~ross/papers/FingerTree.html
To/From list
Monoid
Reduce primitives
Unconsing
Joining
Splitting | The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is RabbitMQ Erlang Data Structures .
The Initial Developer of the Original Code is VMware , Inc.
Copyright ( c ) 2011 - 2013 VMware , Inc. All rights reserved .
-module(finger_tree, [Measure, Null, Add]).
This is an Erlang implementation of 2 - 3 finger trees , as defined by
and in their " Finger Trees : A Simple
General - purpose Data Structure " paper[0 ] .
end is ) amortized .
On the whole , nearly everything else is ) ) , including
it 's only lists that are bounded in length to four items .
Because Erlang lacks type classes , it 's currently forced to cache
sizes . This allows len to be O(1 ) , and permits split_at based on
index , which still remains O(log_2(N ) ) which demonstrates we 're
-compile([export_all]).
-record(finger_tree_single, {elem}).
-record(finger_tree_deep, {measured, prefix, middle, suffix}).
-record(node, {measured, tuple}).
-record(digit, {list}).
empty() -> finger_tree_empty.
cons(A, L) -> [A | L].
to_list(FT) -> reduce_r(fun cons/2, FT, []).
from_list(L) -> reduce_r_in(L, finger_tree_empty).
is_empty(finger_tree_empty) -> true;
is_empty(#finger_tree_single {}) -> false;
is_empty(#finger_tree_deep {}) -> false.
Smart constructors
digit(A) -> #digit { list = A }.
node2(A, B) ->
#node { tuple = {A, B}, measured = Add(measure(A), measure(B)) }.
node3(A, B, C) ->
#node { tuple = {A, B, C},
measured = Add(Add(measure(A), measure(B)), measure(C)) }.
deep(Prefix, Middle, Suffix) ->
#finger_tree_deep { measured = Add(Add(measure(Prefix),
measure(Middle)),
measure(Suffix)),
prefix = Prefix, middle = Middle, suffix = Suffix }.
deep_r(#digit { list = [] }, M, S) ->
case uncons_r(M) of
{empty, _ } -> from_list(S);
{{value, A}, M1} -> deep(digit(to_list(A)), M1, S)
end;
deep_r(P, M, S) ->
deep(P, M, S).
deep_l(P, M, #digit { list = [] }) ->
case uncons_l(M) of
{empty, _} -> from_list(P);
{{value, A}, M1} -> deep(P, M1, digit(to_list(A)))
end;
deep_l(P, M, S) ->
deep(P, M, S).
measure(finger_tree_empty) -> Null();
measure(#finger_tree_single { elem = E }) -> measure(E);
measure(#finger_tree_deep{ measured = V }) -> V;
measure(#node { measured = V }) -> V;
measure(#digit { list = Xs }) ->
reduce_l(fun (A, I) -> Add(I, measure(A)) end, Xs, Null());
measure(X) -> Measure(X).
reduce_r(_Fun, finger_tree_empty, Z) -> Z;
reduce_r(Fun, #finger_tree_single { elem = E }, Z) -> Fun(E, Z);
reduce_r(Fun, #finger_tree_deep { prefix = P, middle = M, suffix = S }, Z) ->
R = reduce_r(fun (A, B) -> reduce_r(Fun, A, B) end, M, reduce_r(Fun, S, Z)),
reduce_r(Fun, P, R);
reduce_r(Fun, #node { tuple = {A, B} }, Z) -> Fun(A, Fun(B, Z));
reduce_r(Fun, #node { tuple = {A, B, C} }, Z) -> Fun(A, Fun(B, Fun(C, Z)));
reduce_r(Fun, #digit { list = List }, Z) -> lists:foldr(Fun, Z, List);
reduce_r(Fun, X, Z) when is_list(X) -> lists:foldr(Fun, Z, X).
reduce_l(_Fun, finger_tree_empty, Z) -> Z;
reduce_l(Fun, #finger_tree_single { elem = E }, Z) -> Fun(Z, E);
reduce_l(Fun, #finger_tree_deep { prefix = P, middle = M, suffix = S }, Z) ->
L = reduce_l(fun (A, B) -> reduce_l(Fun, A, B) end, reduce_l(Fun, Z, P), M),
reduce_l(Fun, L, S);
reduce_l(Fun, #node { tuple = {A, B} }, Z) -> Fun(Fun(Z, B), A);
reduce_l(Fun, #node { tuple = {A, B, C} }, Z) -> Fun(Fun(Fun(Z, C), B), A);
reduce_l(Fun, #digit { list = List }, Z) -> lists:foldl(Fun, Z, List);
reduce_l(Fun, X, Z) when is_list(X) -> lists:foldl(Fun, Z, X).
reduce_r_in(X, FT) -> reduce_r(fun cons_r/2, X, FT).
reduce_l_in(X, FT) -> reduce_l(fun cons_l/2, X, FT).
Consing
cons_r(A, finger_tree_empty) ->
#finger_tree_single { elem = A };
cons_r(A, #finger_tree_single { elem = B }) ->
deep(digit([A]), finger_tree_empty, digit([B]));
cons_r(A, #finger_tree_deep { prefix = #digit { list = [B, C, D, E] }, middle = M, suffix = S }) ->
deep(digit([A, B]), cons_r(node3(C, D, E), M), S);
cons_r(A, #finger_tree_deep { prefix = #digit { list = P }, middle = M, suffix = S }) ->
deep(digit([A | P]), M, S).
cons_l(A, finger_tree_empty) ->
#finger_tree_single { elem = A };
cons_l(A, #finger_tree_single { elem = B }) ->
deep(digit([B]), finger_tree_empty, digit([A]));
cons_l(A, #finger_tree_deep { prefix = P, middle = M, suffix = #digit { list = [E, D, C, B] } }) ->
deep(P, cons_l(node3(E, D, C), M), digit([B, A]));
cons_l(A, #finger_tree_deep { prefix = P, middle = M, suffix = #digit { list = S } }) ->
deep(P, M, digit(S ++ [A])).
uncons_r(finger_tree_empty = FT) ->
{empty, FT};
uncons_r(#finger_tree_single { elem = E }) ->
{{value, E}, finger_tree_empty};
uncons_r(#finger_tree_deep { prefix = #digit { list = [A | P] }, middle = M, suffix = S }) ->
{{value, A}, deep_r(digit(P), M, S)}.
uncons_l(finger_tree_empty = FT) ->
{empty, FT};
uncons_l(#finger_tree_single { elem = E }) ->
{{value, E}, finger_tree_empty};
uncons_l(#finger_tree_deep { prefix = P, middle = M, suffix = #digit { list = S } }) ->
case S of
[A] -> {{value, A}, deep_l(P, M, digit([]))};
_ -> [A | S1] = lists:reverse(S),
{{value, A}, deep_l(P, M, digit(lists:reverse(S1)))}
end.
ft_nodes([A, B]) -> [node2(A, B)];
ft_nodes([A, B, C]) -> [node3(A, B, C)];
ft_nodes([A, B, C, D]) -> [node2(A, B), node2(C, D)];
ft_nodes([A, B, C | Xs]) -> [node3(A, B, C) | ft_nodes(Xs)].
app3(finger_tree_empty, Ts, Xs) ->
reduce_r_in(Ts, Xs);
app3(Xs, Ts, finger_tree_empty) ->
reduce_l_in(Ts, Xs);
app3(#finger_tree_single { elem = E }, Ts, Xs) ->
cons_r(E, reduce_r_in(Ts, Xs));
app3(Xs, Ts, #finger_tree_single { elem = E }) ->
cons_l(E, reduce_l_in(Ts, Xs));
app3(#finger_tree_deep { prefix = P1, middle = M1, suffix = #digit { list = S1 } }, #digit { list = Ts },
#finger_tree_deep { prefix = #digit { list = P2 }, middle = M2, suffix = S2 }) ->
deep(P1, app3(M1, digit(ft_nodes(S1 ++ (Ts ++ P2))), M2), S2).
join(FT1, FT2) -> app3(FT1, digit([]), FT2).
split_digit(_Pred, _Init, #digit { list = [A] }) ->
{split, digit([]), A, digit([])};
split_digit(Pred, Init, #digit { list = [A | List] }) ->
Init1 = Add(Init, measure(A)),
case Pred(Init1) of
true -> {split, digit([]), A, digit(List)};
false -> {split, #digit { list = L }, X, R} = split_digit(Pred, Init1, digit(List)),
{split, digit([A | L]), X, R}
end.
split_node(Pred, Init, #node { tuple = {A, B} }) ->
Init1 = Add(Init, measure(A)),
case Pred(Init1) of
true -> {split, digit([]), A, digit([B])};
false -> {split, digit([A]), B, digit([])}
end;
split_node(Pred, Init, #node { tuple = {A, B, C} }) ->
Init1 = Add(Init, measure(A)),
case Pred(Init1) of
true -> {split, digit([]), A, digit([B, C])};
false -> Init2 = Add(Init1, measure(B)),
case Pred(Init2) of
true -> {split, digit([A]), B, digit([C])};
false -> {split, digit([A, B]), C, digit([])}
end
end.
split_tree(_Pred, _Init, #finger_tree_single { elem = E }) ->
{split, finger_tree_empty, E, finger_tree_empty};
split_tree(Pred, Init, #finger_tree_deep { prefix = P, middle = M, suffix = S }) ->
VP = Add(Init, measure(P)),
case Pred(VP) of
true ->
{split, #digit { list = L }, X, R} = split_digit(Pred, Init, P),
{split, from_list(L), X, deep_r(R, M, S)};
false ->
VM = Add(VP, measure(M)),
case VM /= VP andalso Pred(VM) of
true ->
{split, ML, Xs, MR} = split_tree(Pred, VP, M),
Init1 = Add(VP, measure(ML)),
{split, L, X, R} = split_node(Pred, Init1, Xs),
{split, deep_l(P, ML, L), X, deep_r(R, MR, S)};
false ->
{split, L, X, #digit { list = R }} = split_digit(Pred, VM, S),
{split, deep_l(P, M, L), X, from_list(R)}
end
end.
split(_Pred, finger_tree_empty) ->
{finger_tree_empty, finger_tree_empty};
split(Pred, FT) ->
{split, L, X, R} = split_tree(Pred, Null(), FT),
case Pred(measure(FT)) of
true -> {L, cons_r(X, R)};
false -> {FT, finger_tree_empty}
end.
|
99c5fec2d2ef3c9e74e0a129426bfeff63e3a44c0fe2788e0ee2e74d5c38b6f1 | Chris00/ocaml-docker | no_cmd.ml | open Printf
module C = Docker.Container
let () =
(* When one tries to run a non-existing command, the call should
fail with a clear error message. *)
try
let c = C.create "alpine:latest" ["/bin/bash"] ~open_stdin:true in
C.start c;
assert false
with Docker.Failure _ as e ->
printf "Raised %s\n%!" (Printexc.to_string e)
let () =
try
let c = C.create "alpine:latest" ["/bin/ash"] ~open_stdin:true in
C.start c;
let e = C.Exec.create c ["bash"] in
let stream = C.Exec.start e in
let ty, s = Docker.Stream.read stream in
printf "Read %S on %s\n%!" s (match ty with Stdout -> "Stdout"
| Stderr -> "Stderr");
C.stop c;
C.rm c;
(* assert false *)
printf "Unfortunately, Docker does not indicate when a command is not \
available.\n"
with Docker.Failure _ as e ->
printf "Raised %s\n%!" (Printexc.to_string e)
| null | https://raw.githubusercontent.com/Chris00/ocaml-docker/ec5a4c430085f7956e5c41ea3c28567846fab335/test/no_cmd.ml | ocaml | When one tries to run a non-existing command, the call should
fail with a clear error message.
assert false | open Printf
module C = Docker.Container
let () =
try
let c = C.create "alpine:latest" ["/bin/bash"] ~open_stdin:true in
C.start c;
assert false
with Docker.Failure _ as e ->
printf "Raised %s\n%!" (Printexc.to_string e)
let () =
try
let c = C.create "alpine:latest" ["/bin/ash"] ~open_stdin:true in
C.start c;
let e = C.Exec.create c ["bash"] in
let stream = C.Exec.start e in
let ty, s = Docker.Stream.read stream in
printf "Read %S on %s\n%!" s (match ty with Stdout -> "Stdout"
| Stderr -> "Stderr");
C.stop c;
C.rm c;
printf "Unfortunately, Docker does not indicate when a command is not \
available.\n"
with Docker.Failure _ as e ->
printf "Raised %s\n%!" (Printexc.to_string e)
|
a032b093a0b1699479b7e28a9be1342bdaf1d81a2bca0883d5b50a9135e3c19a | tfausak/rattletrap | UnknownSystemId.hs | module Rattletrap.Exception.UnknownSystemId where
import qualified Control.Exception as Exception
import qualified Data.Word as Word
newtype UnknownSystemId
= UnknownSystemId Word.Word8
deriving (Eq, Show)
instance Exception.Exception UnknownSystemId
| null | https://raw.githubusercontent.com/tfausak/rattletrap/4d6e3cc0aa0f45beaf189255943f0d824c80a7df/src/lib/Rattletrap/Exception/UnknownSystemId.hs | haskell | module Rattletrap.Exception.UnknownSystemId where
import qualified Control.Exception as Exception
import qualified Data.Word as Word
newtype UnknownSystemId
= UnknownSystemId Word.Word8
deriving (Eq, Show)
instance Exception.Exception UnknownSystemId
| |
2ae5beb57337422774d21a9055c924c10f8eaa653df7cf9e7c327746996b876e | malgo-lang/malgo | RnState.hs | module Malgo.Rename.RnState (RnState (..), infixInfo, dependencies) where
import Control.Lens (Lens', lens)
import Data.HashMap.Strict qualified as HashMap
import Data.HashSet qualified as HashSet
import Koriel.Id
import Koriel.Pretty
import Malgo.Prelude
import Malgo.Syntax.Extension
data RnState = RnState
{ _infixInfo :: HashMap RnId (Assoc, Int),
_dependencies :: HashSet ModuleName
}
deriving stock (Show)
instance Pretty RnState where
pPrint RnState {_infixInfo, _dependencies} =
"RnState"
<+> braces
( sep
[ sep ["_infixInfo", "=", pPrint $ HashMap.toList _infixInfo],
sep ["_dependencies", "=", pPrint $ HashSet.toList _dependencies]
]
)
infixInfo :: Lens' RnState (HashMap RnId (Assoc, Int))
infixInfo = lens (._infixInfo) (\r x -> r {_infixInfo = x})
dependencies :: Lens' RnState (HashSet ModuleName)
dependencies = lens (._dependencies) (\r x -> r {_dependencies = x})
| null | https://raw.githubusercontent.com/malgo-lang/malgo/eb99b51415991513e7f9b169b66988ac7e447bd8/src/Malgo/Rename/RnState.hs | haskell | module Malgo.Rename.RnState (RnState (..), infixInfo, dependencies) where
import Control.Lens (Lens', lens)
import Data.HashMap.Strict qualified as HashMap
import Data.HashSet qualified as HashSet
import Koriel.Id
import Koriel.Pretty
import Malgo.Prelude
import Malgo.Syntax.Extension
data RnState = RnState
{ _infixInfo :: HashMap RnId (Assoc, Int),
_dependencies :: HashSet ModuleName
}
deriving stock (Show)
instance Pretty RnState where
pPrint RnState {_infixInfo, _dependencies} =
"RnState"
<+> braces
( sep
[ sep ["_infixInfo", "=", pPrint $ HashMap.toList _infixInfo],
sep ["_dependencies", "=", pPrint $ HashSet.toList _dependencies]
]
)
infixInfo :: Lens' RnState (HashMap RnId (Assoc, Int))
infixInfo = lens (._infixInfo) (\r x -> r {_infixInfo = x})
dependencies :: Lens' RnState (HashSet ModuleName)
dependencies = lens (._dependencies) (\r x -> r {_dependencies = x})
| |
70aa0ed35c5acff47daaa50dd62ef4b55c95429006d77d15ad3f656669556efe | jbreindel/battlecraft | bc_web_sup.erl | %%%-------------------------------------------------------------------
%% @doc bc_web top level supervisor.
%% @end
%%%-------------------------------------------------------------------
-module(bc_web_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
-define(SERVER, ?MODULE).
%%====================================================================
%% API functions
%%====================================================================
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
%%====================================================================
%% Supervisor callbacks
%%====================================================================
Child : : { Id , StartFunc , Restart , Shutdown , Type , Modules }
init([]) ->
{ok, { {one_for_all, 0, 1}, []} }.
%%====================================================================
Internal functions
%%====================================================================
| null | https://raw.githubusercontent.com/jbreindel/battlecraft/622131a1ad8c46f19cf9ffd6bf32ba4a74ef4137/apps/bc_web/src/bc_web_sup.erl | erlang | -------------------------------------------------------------------
@doc bc_web top level supervisor.
@end
-------------------------------------------------------------------
API
Supervisor callbacks
====================================================================
API functions
====================================================================
====================================================================
Supervisor callbacks
====================================================================
====================================================================
==================================================================== |
-module(bc_web_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(SERVER, ?MODULE).
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
Child : : { Id , StartFunc , Restart , Shutdown , Type , Modules }
init([]) ->
{ok, { {one_for_all, 0, 1}, []} }.
Internal functions
|
d5194b19e2b95651e8931dac6e16e99d6d39d275451b5aea3399aa679c3a77eb | venantius/yagni | form_test.clj | (ns yagni.namespace.form-test
(:require [clojure.test :refer :all]
[yagni.namespace.form :as form]
[yagni.sample-ns]))
(deftest get-form-works
(is (= (form/get-form 'yagni.sample-ns/form-for-testing-get)
'{:source (defn form-for-testing-get
[& args]
(+ 1 2 3 (first args)))
:sym yagni.sample-ns/form-for-testing-get})))
(deftest try-to-resolve-works
(is (= (form/try-to-resolve 'conj)
#'clojure.core/conj))
(is (= (form/try-to-resolve 'bananas)
nil)))
(deftest maybe-inc-works
(let [graph (atom {'clojure.core/conj #{}
'clojure.core/bananas #{}})]
(form/maybe-inc graph 'clojure.core/bananas 'conj)
(is (= @graph {'clojure.core/conj #{}
'clojure.core/bananas #{'clojure.core/conj}}))))
(deftest count-vars-works
(let [graph (atom {'yagni.sample-ns/y #{}
'yagni.sample-ns/x #{}})]
(form/count-vars graph ['yagni.sample-ns])
(is (= @graph
{'yagni.sample-ns/y #{'yagni.sample-ns/x}
'yagni.sample-ns/x #{}}))))
| null | https://raw.githubusercontent.com/venantius/yagni/54aa78d06279c3258c6bd932e75c9a2d91bb2fc6/test/yagni/namespace/form_test.clj | clojure | (ns yagni.namespace.form-test
(:require [clojure.test :refer :all]
[yagni.namespace.form :as form]
[yagni.sample-ns]))
(deftest get-form-works
(is (= (form/get-form 'yagni.sample-ns/form-for-testing-get)
'{:source (defn form-for-testing-get
[& args]
(+ 1 2 3 (first args)))
:sym yagni.sample-ns/form-for-testing-get})))
(deftest try-to-resolve-works
(is (= (form/try-to-resolve 'conj)
#'clojure.core/conj))
(is (= (form/try-to-resolve 'bananas)
nil)))
(deftest maybe-inc-works
(let [graph (atom {'clojure.core/conj #{}
'clojure.core/bananas #{}})]
(form/maybe-inc graph 'clojure.core/bananas 'conj)
(is (= @graph {'clojure.core/conj #{}
'clojure.core/bananas #{'clojure.core/conj}}))))
(deftest count-vars-works
(let [graph (atom {'yagni.sample-ns/y #{}
'yagni.sample-ns/x #{}})]
(form/count-vars graph ['yagni.sample-ns])
(is (= @graph
{'yagni.sample-ns/y #{'yagni.sample-ns/x}
'yagni.sample-ns/x #{}}))))
| |
de47ea00f2c23687c5289b86e4f0643f22ee6c45e55a6224d3b60d11f3d7376e | gilith/hol-light | word-tools.ml | (* ========================================================================= *)
(* PARAMETRIC PROOF TOOLS FOR THE PARAMETRIC THEORY OF WORDS *)
(* ========================================================================= *)
(*BEGIN-PARAMETRIC*)
needs "opentheory/theories/tools.ml";;
needs "opentheory/theories/natural-bits/natural-bits-tools.ml";;
let word_reduce_conv =
REWRITE_CONV
[word_to_num_to_word;
word_le_def; word_lt_def] THENC
REWRITE_CONV
[num_to_word_to_num] THENC
REWRITE_CONV
[word_width_def; word_size_def; num_to_word_eq] THENC
NUM_REDUCE_CONV;;
let word_width_conv = REWR_CONV word_width_def;;
let list_to_word_to_list_conv =
REWR_CONV list_to_word_to_list_eq THENC
cond_conv
(LAND_CONV length_conv THENC
RAND_CONV word_width_conv THENC
NUM_REDUCE_CONV)
(RAND_CONV
(RAND_CONV
(LAND_CONV word_width_conv THENC
RAND_CONV length_conv THENC
NUM_REDUCE_CONV) THENC
replicate_conv) THENC
append_conv)
(LAND_CONV word_width_conv THENC
take_conv);;
let numeral_to_word_list_conv =
let list_to_word_conv = REWR_CONV (GSYM list_to_word_def) in
RAND_CONV numeral_to_bits_conv THENC
list_to_word_conv;;
let word_and_list_conv =
let th = SPECL [`list_to_word l1`; `list_to_word l2`] word_and_list in
REWR_CONV th THENC
RAND_CONV
(LAND_CONV list_to_word_to_list_conv THENC
RAND_CONV list_to_word_to_list_conv THENC
zipwith_conv and_simp_conv);;
let word_or_list_conv =
let th = SPECL [`list_to_word l1`; `list_to_word l2`] word_or_list in
REWR_CONV th THENC
RAND_CONV
(LAND_CONV list_to_word_to_list_conv THENC
RAND_CONV list_to_word_to_list_conv THENC
zipwith_conv or_simp_conv);;
let word_shr_list_conv =
let th = SPECL [`l : bool list`; `NUMERAL n`] word_shr_list in
REWR_CONV th THENC
cond_conv
(RATOR_CONV (RAND_CONV length_conv) THENC
RAND_CONV word_width_conv THENC
NUM_REDUCE_CONV)
(cond_conv
(RATOR_CONV (RAND_CONV length_conv) THENC
NUM_REDUCE_CONV)
ALL_CONV
(RAND_CONV drop_conv))
(cond_conv
(RATOR_CONV (RAND_CONV word_width_conv) THENC
NUM_REDUCE_CONV)
ALL_CONV
(RAND_CONV
(RAND_CONV
(RATOR_CONV (RAND_CONV word_width_conv) THENC
take_conv) THENC
drop_conv)));;
let word_shl_list_conv =
let th = SPECL [`l : bool list`; `NUMERAL n`] word_shl_list in
REWR_CONV th THENC
RAND_CONV
(LAND_CONV replicate_conv THENC
append_conv);;
let word_bit_list_conv =
let th = SPECL [`l : bool list`; `NUMERAL n`] list_to_word_bit in
REWR_CONV th THENC
andalso_conv
(RAND_CONV word_width_conv THENC
NUM_REDUCE_CONV)
(andalso_conv
(RAND_CONV length_conv THENC
NUM_REDUCE_CONV)
nth_conv);;
let word_bits_lte_conv =
let nil_conv = REWR_CONV word_bits_lte_nil in
let cons_conv = REWR_CONV word_bits_lte_cons in
let rec rewr_conv tm =
(nil_conv ORELSEC
(cons_conv THENC
(RATOR_CONV o RATOR_CONV o RAND_CONV)
((RATOR_CONV o RAND_CONV)
(RATOR_CONV (RAND_CONV (TRY_CONV not_simp_conv)) THENC
TRY_CONV and_simp_conv) THENC
RAND_CONV
((RATOR_CONV o RAND_CONV)
(RAND_CONV
(RAND_CONV (TRY_CONV not_simp_conv) THENC
TRY_CONV and_simp_conv) THENC
TRY_CONV not_simp_conv) THENC
TRY_CONV and_simp_conv) THENC
TRY_CONV or_simp_conv) THENC
rewr_conv)) tm in
rewr_conv;;
let word_le_list_conv =
let th = SYM (SPECL [`list_to_word l1`; `list_to_word l2`] word_le_list) in
REWR_CONV th THENC
LAND_CONV list_to_word_to_list_conv THENC
RAND_CONV list_to_word_to_list_conv THENC
word_bits_lte_conv;;
let word_lt_list_conv =
let th = SYM (SPECL [`list_to_word l1`; `list_to_word l2`] word_lt_list) in
REWR_CONV th THENC
LAND_CONV list_to_word_to_list_conv THENC
RAND_CONV list_to_word_to_list_conv THENC
word_bits_lte_conv;;
let word_eq_list_conv =
let th = SYM (SPECL [`list_to_word l1`; `list_to_word l2`]
word_to_list_inj_eq) in
REWR_CONV th THENC
LAND_CONV list_to_word_to_list_conv THENC
RAND_CONV list_to_word_to_list_conv THENC
list_eq_conv iff_simp_conv;;
let word_bit_conv =
word_width_conv ORELSEC
list_to_word_to_list_conv ORELSEC
numeral_to_word_list_conv ORELSEC
word_and_list_conv ORELSEC
word_or_list_conv ORELSEC
word_shr_list_conv ORELSEC
word_shl_list_conv ORELSEC
word_bit_list_conv ORELSEC
word_le_list_conv ORELSEC
word_lt_list_conv ORELSEC
word_eq_list_conv;;
let bit_blast_subterm_conv = word_bit_conv ORELSEC bit_blast_subterm_conv;;
let bit_blast_conv = DEPTH_CONV bit_blast_subterm_conv;; (* word *)
let bit_blast_tac = CONV_TAC bit_blast_conv;; (* word *)
let prove_word_list_cases n =
let interval =
let rec intv i n = if n = 0 then [] else i :: intv (i + 1) (n - 1) in
intv 0 in
let lemma1 =
let nunary = funpow n (fun t -> mk_comb (`SUC`,t)) `0` in
let goal = mk_eq (`LENGTH (word_to_list w)`,nunary) in
let tac =
REWRITE_TAC [length_word_to_list; word_width_def] THEN
NUM_REDUCE_TAC in
prove (goal,tac) in
let witnesses =
let addtl l = mk_comb (`TL : bool list -> bool list`, hd l) :: l in
let tls = rev (funpow (n - 1) addtl [`l : bool list`]) in
map (fun t -> mk_comb (`HD : bool list -> bool`, t)) tls in
let goal =
let is = interval n in
let xs = map (fun i -> mk_var ("x" ^ string_of_int i, bool_ty)) is in
let w = mk_var ("w", `:word`) in
let body = mk_eq (w, mk_comb (`list_to_word`, mk_list (xs,bool_ty))) in
mk_forall (w, list_mk_exists (xs,body)) in
let tac =
GEN_TAC THEN
CONV_TAC
(funpow n (RAND_CONV o ABS_CONV)
(LAND_CONV (ONCE_REWRITE_CONV [GSYM word_to_list_to_word]))) THEN
MP_TAC lemma1 THEN
SPEC_TAC (`word_to_list w`, `l : bool list`) THEN
REPEAT STRIP_TAC THEN
EVERY (map EXISTS_TAC witnesses) THEN
AP_TERM_TAC THEN
POP_ASSUM MP_TAC THEN
N_TAC n
(MP_TAC (ISPEC `l : bool list` list_cases) THEN
STRIP_TAC THENL
[ASM_REWRITE_TAC [LENGTH; NOT_SUC];
ALL_TAC] THEN
POP_ASSUM SUBST_VAR_TAC THEN
REWRITE_TAC [LENGTH; SUC_INJ; HD; TL; CONS_11] THEN
SPEC_TAC (`t : bool list`, `l : bool list`) THEN
GEN_TAC) THEN
REWRITE_TAC [LENGTH_EQ_NIL] in
prove (goal,tac);;
(*END-PARAMETRIC*)
| null | https://raw.githubusercontent.com/gilith/hol-light/f3f131963f2298b4d65ee5fead6e986a4a14237a/opentheory/theories/word/word-tools.ml | ocaml | =========================================================================
PARAMETRIC PROOF TOOLS FOR THE PARAMETRIC THEORY OF WORDS
=========================================================================
BEGIN-PARAMETRIC
word
word
END-PARAMETRIC |
needs "opentheory/theories/tools.ml";;
needs "opentheory/theories/natural-bits/natural-bits-tools.ml";;
let word_reduce_conv =
REWRITE_CONV
[word_to_num_to_word;
word_le_def; word_lt_def] THENC
REWRITE_CONV
[num_to_word_to_num] THENC
REWRITE_CONV
[word_width_def; word_size_def; num_to_word_eq] THENC
NUM_REDUCE_CONV;;
let word_width_conv = REWR_CONV word_width_def;;
let list_to_word_to_list_conv =
REWR_CONV list_to_word_to_list_eq THENC
cond_conv
(LAND_CONV length_conv THENC
RAND_CONV word_width_conv THENC
NUM_REDUCE_CONV)
(RAND_CONV
(RAND_CONV
(LAND_CONV word_width_conv THENC
RAND_CONV length_conv THENC
NUM_REDUCE_CONV) THENC
replicate_conv) THENC
append_conv)
(LAND_CONV word_width_conv THENC
take_conv);;
let numeral_to_word_list_conv =
let list_to_word_conv = REWR_CONV (GSYM list_to_word_def) in
RAND_CONV numeral_to_bits_conv THENC
list_to_word_conv;;
let word_and_list_conv =
let th = SPECL [`list_to_word l1`; `list_to_word l2`] word_and_list in
REWR_CONV th THENC
RAND_CONV
(LAND_CONV list_to_word_to_list_conv THENC
RAND_CONV list_to_word_to_list_conv THENC
zipwith_conv and_simp_conv);;
let word_or_list_conv =
let th = SPECL [`list_to_word l1`; `list_to_word l2`] word_or_list in
REWR_CONV th THENC
RAND_CONV
(LAND_CONV list_to_word_to_list_conv THENC
RAND_CONV list_to_word_to_list_conv THENC
zipwith_conv or_simp_conv);;
let word_shr_list_conv =
let th = SPECL [`l : bool list`; `NUMERAL n`] word_shr_list in
REWR_CONV th THENC
cond_conv
(RATOR_CONV (RAND_CONV length_conv) THENC
RAND_CONV word_width_conv THENC
NUM_REDUCE_CONV)
(cond_conv
(RATOR_CONV (RAND_CONV length_conv) THENC
NUM_REDUCE_CONV)
ALL_CONV
(RAND_CONV drop_conv))
(cond_conv
(RATOR_CONV (RAND_CONV word_width_conv) THENC
NUM_REDUCE_CONV)
ALL_CONV
(RAND_CONV
(RAND_CONV
(RATOR_CONV (RAND_CONV word_width_conv) THENC
take_conv) THENC
drop_conv)));;
let word_shl_list_conv =
let th = SPECL [`l : bool list`; `NUMERAL n`] word_shl_list in
REWR_CONV th THENC
RAND_CONV
(LAND_CONV replicate_conv THENC
append_conv);;
let word_bit_list_conv =
let th = SPECL [`l : bool list`; `NUMERAL n`] list_to_word_bit in
REWR_CONV th THENC
andalso_conv
(RAND_CONV word_width_conv THENC
NUM_REDUCE_CONV)
(andalso_conv
(RAND_CONV length_conv THENC
NUM_REDUCE_CONV)
nth_conv);;
let word_bits_lte_conv =
let nil_conv = REWR_CONV word_bits_lte_nil in
let cons_conv = REWR_CONV word_bits_lte_cons in
let rec rewr_conv tm =
(nil_conv ORELSEC
(cons_conv THENC
(RATOR_CONV o RATOR_CONV o RAND_CONV)
((RATOR_CONV o RAND_CONV)
(RATOR_CONV (RAND_CONV (TRY_CONV not_simp_conv)) THENC
TRY_CONV and_simp_conv) THENC
RAND_CONV
((RATOR_CONV o RAND_CONV)
(RAND_CONV
(RAND_CONV (TRY_CONV not_simp_conv) THENC
TRY_CONV and_simp_conv) THENC
TRY_CONV not_simp_conv) THENC
TRY_CONV and_simp_conv) THENC
TRY_CONV or_simp_conv) THENC
rewr_conv)) tm in
rewr_conv;;
let word_le_list_conv =
let th = SYM (SPECL [`list_to_word l1`; `list_to_word l2`] word_le_list) in
REWR_CONV th THENC
LAND_CONV list_to_word_to_list_conv THENC
RAND_CONV list_to_word_to_list_conv THENC
word_bits_lte_conv;;
let word_lt_list_conv =
let th = SYM (SPECL [`list_to_word l1`; `list_to_word l2`] word_lt_list) in
REWR_CONV th THENC
LAND_CONV list_to_word_to_list_conv THENC
RAND_CONV list_to_word_to_list_conv THENC
word_bits_lte_conv;;
let word_eq_list_conv =
let th = SYM (SPECL [`list_to_word l1`; `list_to_word l2`]
word_to_list_inj_eq) in
REWR_CONV th THENC
LAND_CONV list_to_word_to_list_conv THENC
RAND_CONV list_to_word_to_list_conv THENC
list_eq_conv iff_simp_conv;;
let word_bit_conv =
word_width_conv ORELSEC
list_to_word_to_list_conv ORELSEC
numeral_to_word_list_conv ORELSEC
word_and_list_conv ORELSEC
word_or_list_conv ORELSEC
word_shr_list_conv ORELSEC
word_shl_list_conv ORELSEC
word_bit_list_conv ORELSEC
word_le_list_conv ORELSEC
word_lt_list_conv ORELSEC
word_eq_list_conv;;
let bit_blast_subterm_conv = word_bit_conv ORELSEC bit_blast_subterm_conv;;
let prove_word_list_cases n =
let interval =
let rec intv i n = if n = 0 then [] else i :: intv (i + 1) (n - 1) in
intv 0 in
let lemma1 =
let nunary = funpow n (fun t -> mk_comb (`SUC`,t)) `0` in
let goal = mk_eq (`LENGTH (word_to_list w)`,nunary) in
let tac =
REWRITE_TAC [length_word_to_list; word_width_def] THEN
NUM_REDUCE_TAC in
prove (goal,tac) in
let witnesses =
let addtl l = mk_comb (`TL : bool list -> bool list`, hd l) :: l in
let tls = rev (funpow (n - 1) addtl [`l : bool list`]) in
map (fun t -> mk_comb (`HD : bool list -> bool`, t)) tls in
let goal =
let is = interval n in
let xs = map (fun i -> mk_var ("x" ^ string_of_int i, bool_ty)) is in
let w = mk_var ("w", `:word`) in
let body = mk_eq (w, mk_comb (`list_to_word`, mk_list (xs,bool_ty))) in
mk_forall (w, list_mk_exists (xs,body)) in
let tac =
GEN_TAC THEN
CONV_TAC
(funpow n (RAND_CONV o ABS_CONV)
(LAND_CONV (ONCE_REWRITE_CONV [GSYM word_to_list_to_word]))) THEN
MP_TAC lemma1 THEN
SPEC_TAC (`word_to_list w`, `l : bool list`) THEN
REPEAT STRIP_TAC THEN
EVERY (map EXISTS_TAC witnesses) THEN
AP_TERM_TAC THEN
POP_ASSUM MP_TAC THEN
N_TAC n
(MP_TAC (ISPEC `l : bool list` list_cases) THEN
STRIP_TAC THENL
[ASM_REWRITE_TAC [LENGTH; NOT_SUC];
ALL_TAC] THEN
POP_ASSUM SUBST_VAR_TAC THEN
REWRITE_TAC [LENGTH; SUC_INJ; HD; TL; CONS_11] THEN
SPEC_TAC (`t : bool list`, `l : bool list`) THEN
GEN_TAC) THEN
REWRITE_TAC [LENGTH_EQ_NIL] in
prove (goal,tac);;
|
975a8bb87e8ef46f090e5425df38d8bac7fbcee430d057f7f7afe35dfea36305 | srid/emanote.obelisk | Emanote.hs | {-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE TypeApplications #
module Emanote where
import Control.Concurrent.Async (race_)
import Control.Concurrent.STM (newTChanIO, readTChan, writeTChan)
import Emanote.Zk (Zk)
import qualified Emanote.Zk as Zk
import Options.Applicative
import Reflex (Reflex (never))
import Reflex.Host.Headless (MonadHeadlessApp, runHeadlessApp)
import Relude
emanoteMainWith :: (forall t m. MonadHeadlessApp t m => m Zk) -> (Zk -> IO ()) -> IO ()
emanoteMainWith runner f = do
ready <- newTChanIO @Zk
race_
Run the Reflex network that will produce the Zettelkasten ( Zk )
( runHeadlessApp $ do
zk <- runner
atomically $ writeTChan ready zk
pure never
)
-- Start consuming the Zk as soon as it is ready.
( do
zk <- atomically $ readTChan ready
race_
-- Custom action
(f zk)
Run TIncremental to process Reflex patches
(Zk.run zk)
)
| null | https://raw.githubusercontent.com/srid/emanote.obelisk/de935cff82fc57085adef1904094c7129c02d995/lib/emanote/src/Emanote.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE RankNTypes #
Start consuming the Zk as soon as it is ready.
Custom action | # LANGUAGE TypeApplications #
module Emanote where
import Control.Concurrent.Async (race_)
import Control.Concurrent.STM (newTChanIO, readTChan, writeTChan)
import Emanote.Zk (Zk)
import qualified Emanote.Zk as Zk
import Options.Applicative
import Reflex (Reflex (never))
import Reflex.Host.Headless (MonadHeadlessApp, runHeadlessApp)
import Relude
emanoteMainWith :: (forall t m. MonadHeadlessApp t m => m Zk) -> (Zk -> IO ()) -> IO ()
emanoteMainWith runner f = do
ready <- newTChanIO @Zk
race_
Run the Reflex network that will produce the Zettelkasten ( Zk )
( runHeadlessApp $ do
zk <- runner
atomically $ writeTChan ready zk
pure never
)
( do
zk <- atomically $ readTChan ready
race_
(f zk)
Run TIncremental to process Reflex patches
(Zk.run zk)
)
|
822f640d0df48833556331706b96c0fe514f77e6ba259cf470ab69427f975cc0 | nuprl/gradual-typing-performance | sequencer.rkt | #lang typed/racket/base
(require benchmark-util
"../base/typed-array-data.rkt")
(require/typed/check "array-struct.rkt"
[build-array (-> (Vectorof Nonnegative-Integer) (-> Indexes Flonum) Array)])
(require/typed/check "array-transform.rkt"
[array-append* (case-> ((Listof Array) -> Array)
((Listof Array) Integer -> Array))])
(require/typed/check "synth.rkt"
[fs Natural])
(require/typed/check "mixer.rkt"
[mix (-> Weighted-Signal * Array)])
(provide sequence note)
details at /~suits/notefreqs.html
(: note-freq (-> Natural Float))
(define (note-freq note)
A4 ( 440Hz ) is 57 semitones above C0 , which is our base .
(: res Nonnegative-Real)
(define res (* 440 (expt (expt 2 1/12) (- note 57))))
(if (flonum? res) res (error "not real")))
;; A note is represented using the number of semitones from C0.
(: name+octave->note (-> Symbol Natural Natural))
(define (name+octave->note name octave)
(+ (* 12 octave)
(case name
[(C) 0]
[(C# Db) 1]
[(D) 2]
[(D# Eb) 3]
[(E) 4]
[(F) 5]
[(F# Gb) 6]
[(G) 7]
[(G# Ab) 8]
[(A) 9]
[(A# Bb) 10]
[(B) 11]
[else 0])))
;; Single note.
(: note (-> Symbol Natural Natural (Pairof Natural Natural)))
(define (note name octave duration)
(cons (name+octave->note name octave) duration))
;; Accepts notes or pauses, but not chords.
(: synthesize-note (-> (U #f Natural)
Natural
(-> Float (-> Indexes Float))
Array))
(define (synthesize-note note n-samples function)
(build-array (vector n-samples)
(if note
(function (note-freq note))
(lambda (x) 0.0)))) ; pause
;; repeats n times the sequence encoded by the pattern, at tempo bpm
;; pattern is a list of either single notes (note . duration) or
;; chords ((note ...) . duration) or pauses (#f . duration)
(: sequence (-> Natural
(Listof (Pairof (U Natural #f) Natural))
Natural
(-> Float (-> Indexes Float)) Array))
(define (sequence n pattern tempo function)
(: samples-per-beat Natural)
(define samples-per-beat (quotient (* fs 60) tempo))
(array-append*
(for*/list : (Listof Array) ([i (in-range n)] ; repeat the whole pattern
[note : (Pairof (U Natural #f) Natural) (in-list pattern)])
(: nsamples Natural)
(define nsamples (* samples-per-beat (cdr note)))
(synthesize-note (car note) nsamples function))))
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/benchmarks/synth/extra/monotown/typed/sequencer.rkt | racket | A note is represented using the number of semitones from C0.
Single note.
Accepts notes or pauses, but not chords.
pause
repeats n times the sequence encoded by the pattern, at tempo bpm
pattern is a list of either single notes (note . duration) or
chords ((note ...) . duration) or pauses (#f . duration)
repeat the whole pattern | #lang typed/racket/base
(require benchmark-util
"../base/typed-array-data.rkt")
(require/typed/check "array-struct.rkt"
[build-array (-> (Vectorof Nonnegative-Integer) (-> Indexes Flonum) Array)])
(require/typed/check "array-transform.rkt"
[array-append* (case-> ((Listof Array) -> Array)
((Listof Array) Integer -> Array))])
(require/typed/check "synth.rkt"
[fs Natural])
(require/typed/check "mixer.rkt"
[mix (-> Weighted-Signal * Array)])
(provide sequence note)
details at /~suits/notefreqs.html
(: note-freq (-> Natural Float))
(define (note-freq note)
A4 ( 440Hz ) is 57 semitones above C0 , which is our base .
(: res Nonnegative-Real)
(define res (* 440 (expt (expt 2 1/12) (- note 57))))
(if (flonum? res) res (error "not real")))
(: name+octave->note (-> Symbol Natural Natural))
(define (name+octave->note name octave)
(+ (* 12 octave)
(case name
[(C) 0]
[(C# Db) 1]
[(D) 2]
[(D# Eb) 3]
[(E) 4]
[(F) 5]
[(F# Gb) 6]
[(G) 7]
[(G# Ab) 8]
[(A) 9]
[(A# Bb) 10]
[(B) 11]
[else 0])))
(: note (-> Symbol Natural Natural (Pairof Natural Natural)))
(define (note name octave duration)
(cons (name+octave->note name octave) duration))
(: synthesize-note (-> (U #f Natural)
Natural
(-> Float (-> Indexes Float))
Array))
(define (synthesize-note note n-samples function)
(build-array (vector n-samples)
(if note
(function (note-freq note))
(: sequence (-> Natural
(Listof (Pairof (U Natural #f) Natural))
Natural
(-> Float (-> Indexes Float)) Array))
(define (sequence n pattern tempo function)
(: samples-per-beat Natural)
(define samples-per-beat (quotient (* fs 60) tempo))
(array-append*
[note : (Pairof (U Natural #f) Natural) (in-list pattern)])
(: nsamples Natural)
(define nsamples (* samples-per-beat (cdr note)))
(synthesize-note (car note) nsamples function))))
|
dfec22cc44550095a8a6d089e6d20e951eeb32384e182ca95f1baa3d8bdea484 | dylex/haskell-nfs | Transport.hs | module Network.ONCRPC.Transport
( sendTransport
, recvTransport
, TransportState
, transportStart
, recvGetFirst
, recvGetNext
) where
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Serialize.Get as S
import qualified Network.Socket as Net
import Network.ONCRPC.RecordMarking
sendTransport :: Net.Socket -> BSL.ByteString -> IO ()
sendTransport sock b = do
t <- Net.getSocketType sock
if t == Net.Stream
then sendRecord sock b
else fail "ONCRPC: Unsupported socket type"
recvTransport :: Net.Socket -> RecordState -> IO (BS.ByteString, RecordState)
recvTransport sock r = do
t <- Net.getSocketType sock
if t == Net.Stream
then recvRecord sock r
else fail "ONCRPC: Unsupported socket type"
data TransportState = TransportState
{ _bufferState :: BS.ByteString
, recordState :: RecordState
}
deriving (Eq, Show)
transportNext :: RecordState -> TransportState
transportNext = TransportState BS.empty
transportStart :: TransportState
transportStart = transportNext RecordStart
recvTransportWith :: Net.Socket -> RecordState -> (BS.ByteString -> RecordState -> IO (Maybe a)) -> IO (Maybe a)
recvTransportWith sock rs f = do
(b, rs') <- recvTransport sock rs
if BS.null b
then return Nothing
else f b rs'
-- |Get the next part of the current record, after calling 'recvGetFirst' to start.
recvGetNext :: Net.Socket -> S.Get a -> TransportState -> IO (Maybe (Either String a, TransportState))
recvGetNext sock getter = start where
start (TransportState b rs) -- continue record
| BS.null b = get Nothing rs -- check for more
| otherwise = got Nothing b rs -- buffered data
get f RecordStart = got f BS.empty RecordStart -- end of record
get f rs = recvTransportWith sock rs $ got f -- read next block
got Nothing b rs = fed rs $ S.runGetChunk getter (recordRemaining rs) b -- start parsing
got (Just f) b rs = fed rs $ f b -- parse block
fed rs (S.Partial f) = get (Just f) rs
fed rs (S.Done r b) = return $ Just (Right r, TransportState b rs)
fed rs (S.Fail e b) = return $ Just (Left e, TransportState b rs)
|Get the first part of the next record , possibly skipping over the rest of the current record .
recvGetFirst :: Net.Socket -> S.Get a -> TransportState -> IO (Maybe (Either String a, TransportState))
recvGetFirst sock getter = get . recordState where
get rs = recvTransportWith sock rs $ got rs -- read next block
got RecordStart b rs = recvGetNext sock getter $ TransportState b rs -- start next record
got _ _ rs = get rs -- ignore remaining record
| null | https://raw.githubusercontent.com/dylex/haskell-nfs/33e8b9c7f20a05f91bb01e4c0a998ae749122a73/rpc/Network/ONCRPC/Transport.hs | haskell | |Get the next part of the current record, after calling 'recvGetFirst' to start.
continue record
check for more
buffered data
end of record
read next block
start parsing
parse block
read next block
start next record
ignore remaining record | module Network.ONCRPC.Transport
( sendTransport
, recvTransport
, TransportState
, transportStart
, recvGetFirst
, recvGetNext
) where
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Serialize.Get as S
import qualified Network.Socket as Net
import Network.ONCRPC.RecordMarking
sendTransport :: Net.Socket -> BSL.ByteString -> IO ()
sendTransport sock b = do
t <- Net.getSocketType sock
if t == Net.Stream
then sendRecord sock b
else fail "ONCRPC: Unsupported socket type"
recvTransport :: Net.Socket -> RecordState -> IO (BS.ByteString, RecordState)
recvTransport sock r = do
t <- Net.getSocketType sock
if t == Net.Stream
then recvRecord sock r
else fail "ONCRPC: Unsupported socket type"
data TransportState = TransportState
{ _bufferState :: BS.ByteString
, recordState :: RecordState
}
deriving (Eq, Show)
transportNext :: RecordState -> TransportState
transportNext = TransportState BS.empty
transportStart :: TransportState
transportStart = transportNext RecordStart
recvTransportWith :: Net.Socket -> RecordState -> (BS.ByteString -> RecordState -> IO (Maybe a)) -> IO (Maybe a)
recvTransportWith sock rs f = do
(b, rs') <- recvTransport sock rs
if BS.null b
then return Nothing
else f b rs'
recvGetNext :: Net.Socket -> S.Get a -> TransportState -> IO (Maybe (Either String a, TransportState))
recvGetNext sock getter = start where
fed rs (S.Partial f) = get (Just f) rs
fed rs (S.Done r b) = return $ Just (Right r, TransportState b rs)
fed rs (S.Fail e b) = return $ Just (Left e, TransportState b rs)
|Get the first part of the next record , possibly skipping over the rest of the current record .
recvGetFirst :: Net.Socket -> S.Get a -> TransportState -> IO (Maybe (Either String a, TransportState))
recvGetFirst sock getter = get . recordState where
|
9cd6aae29c5a7d2b2ea6a2b3ce03a2e17b68a78fe028c96b789465f0969fa83e | Bogdanp/racket-chief | info.rkt | #lang info
(define license 'BSD-3-Clause)
(define version "0.1")
(define collection "chief")
(define deps '("base"
"gregor-lib"))
(define build-deps '("at-exp-lib"
"rackunit-lib"))
(define test-omit-paths '("cli.rkt"))
(define raco-commands '(("chief" chief/cli "run application processes" #f)))
| null | https://raw.githubusercontent.com/Bogdanp/racket-chief/3553d3a38cf615a1c39ff57f1cfcb3b8bacd2afa/chief/info.rkt | racket | #lang info
(define license 'BSD-3-Clause)
(define version "0.1")
(define collection "chief")
(define deps '("base"
"gregor-lib"))
(define build-deps '("at-exp-lib"
"rackunit-lib"))
(define test-omit-paths '("cli.rkt"))
(define raco-commands '(("chief" chief/cli "run application processes" #f)))
| |
dd223a7abbdfd47141dec70c17397c8b6be5d94d310e14dd71d65770a4e81ed3 | fogfish/hash | hash_aws_v4.erl | %%
Copyright 2017 , 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.
%%
%% @doc
%% aws sign v4 protocol implementation
%% -version-4.html
-module(hash_aws_v4).
-export([new/5, sign/7]).
%%
%% internal hash state
-define(ALGORITHM, <<"AWS4-HMAC-SHA256">>).
-record(aws, {
access = undefined :: binary(),
secret = undefined :: binary(),
token = undefined :: binary(),
region = undefined :: binary(),
service = undefined :: binary()
}).
%%
%% seed hash function
new(Access, Secret, Token, Region, Service) ->
#aws{
access = hash:s(Access),
secret = hash:s(Secret),
token = Token,
region = hash:s(Region),
service = hash:s(Service)
}.
sign(Mthd, Host, Path, Query, Head, Data, #aws{access = Access} = Hash) ->
<<Date:8/binary, _/binary>> = AmzDate = amzdate(),
Head1 = headers(AmzDate, Host, Head, Hash),
HeadSgn = signed_headers(Head1),
Request = lists:join(<<$\n>>, [
hash:s(Mthd),
canonical_path(Path),
canonical_q(Query),
canonical_head(Head1),
HeadSgn,
payload_hash(Data)
]),
KeyScope = credential_scope(Date, Hash),
ToSign = lists:join(<<$\n>>, [?ALGORITHM, AmzDate, KeyScope, btoh(crypto:hash(sha256, Request))]),
Signature = btoh(sign(signing_key(Date, Hash), ToSign)),
AwsAuth = iolist_to_binary([
?ALGORITHM,
<<" ">>,
<<"Credential=">>, Access, <<$/>>, KeyScope,
<<", ">>,
<<"SignedHeaders=">>, HeadSgn,
<<", ">>,
<<"Signature=">>, Signature
]),
Tail = [X || X = {K, _} <- Head1,
K =:= 'x-amz-date' orelse K =:= 'Host' orelse K =:= 'x-amz-security-token'],
[{'Authorization', AwsAuth}|Tail].
headers(AmzDate, Host, Head, Hash) ->
header_amz_date(AmzDate,
header_host(Host,
header_amz_token(Hash, Head)
)
).
header_amz_date(AmzDate, Head) ->
[{'x-amz-date', AmzDate} | Head].
header_amz_token(#aws{token = undefined}, Head) ->
Head;
header_amz_token(#aws{token = Token}, Head) ->
[{'x-amz-security-token', Token} | Head].
header_host(Host, Head) ->
case lists:keyfind('Host', 1, Head) of
false ->
[{'Host', hash:s(Host)} | Head];
_ ->
Head
end.
Step 2 : Create canonical URI -- the part of the URI from domain to query
%% string (use '/' if no path)
canonical_path(undefined) -> <<$/>>;
canonical_path(Path) -> Path.
Step 3 : Create the canonical query string . Query string values must
be URL - encoded ( ) . The parameters must be sorted by name .
canonical_q(Query) ->
iolist_to_binary(
lists:join(<<$&>>,
[uri:escape(<<K/binary, $=, V/binary>>) ||
{K, V} <- lists:sort(listT(Query))]
)
).
listT(undefined) -> [];
listT(X) -> X.
Step 4 : Create the canonical headers and signed headers . Header names
%% and value must be trimmed and lowercase, and sorted in ASCII order.
%% Note that there is a trailing \n.
canonical_head(Head) ->
iolist_to_binary(
lists:sort(
[<<(lowercase(K))/binary, $:, (hash:s(V))/binary, $\n>> || {K, V} <- Head]
)
).
Step 5 : Create the list of signed headers . This lists the headers
%% in the canonical_headers list, delimited with ";" and in alpha order.
%% Note: The request can include any headers; canonical_headers and
%% signed_headers lists those that you want to be included in the
%% hash of the request. "Host" and "x-amz-date" are always required.
signed_headers(Head) ->
iolist_to_binary(
lists:join(<<$;>>,
lists:sort(
[lowercase(K) || {K, _} <- Head]
)
)
).
lowercase(X) ->
<< <<(to_lower(C)):8>> || <<C:8>> <= hash:s(X) >>.
to_lower(X)
when X >= $A, X =< $Z ->
X + 32;
to_lower(X) ->
X.
Step 6 : Create payload hash ( hash of the request body content ) .
%% For GET requests, the payload is an empty string ("").
payload_hash(undefined) ->
payload_hash(<<>>);
payload_hash(Payload) ->
btoh(crypto:hash(sha256, Payload)).
%%
%% Create a date for headers and the credential string
amzdate() ->
{{Year,Month,Day},{Hour,Min,Sec}} = calendar:now_to_universal_time(os:timestamp()),
iolist_to_binary(
io_lib:format(
"~4.10.0B~2.10.0B~2.10.0BT~2.10.0B~2.10.0B~2.10.0BZ",
[Year, Month, Day, Hour, Min, Sec]
)
).
%%
%%
credential_scope(Date, #aws{region = Region, service = Service}) ->
iolist_to_binary(
lists:join(<<$/>>, [
Date,
Region,
Service,
<<"aws4_request">>
])
).
%%
%%
signing_key(Date, #aws{secret = Secret, region = Region, service = Service}) ->
get_signature_key(Secret, Date, Region, Service).
%%
%%
get_signature_key(Key, Date, Region, Service) ->
KDate = sign(<<"AWS4", Key/binary>>, Date),
KRegion = sign(KDate, Region),
KService = sign(KRegion, Service),
sign(KService, <<"aws4_request">>).
%%
%%
sign(Key, Data) ->
crypto:hmac(sha256, Key, Data).
btoh(X) ->
<< <<(if A < 10 -> $0 + A; A >= 10 -> $a + (A - 10) end):8>> || <<A:4>> <=X >>.
| null | https://raw.githubusercontent.com/fogfish/hash/a1b9101189e115b4eabbe941639f3c626614e986/src/hash_aws_v4.erl | erlang |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@doc
aws sign v4 protocol implementation
-version-4.html
internal hash state
seed hash function
string (use '/' if no path)
and value must be trimmed and lowercase, and sorted in ASCII order.
Note that there is a trailing \n.
in the canonical_headers list, delimited with ";" and in alpha order.
Note: The request can include any headers; canonical_headers and
signed_headers lists those that you want to be included in the
hash of the request. "Host" and "x-amz-date" are always required.
For GET requests, the payload is an empty string ("").
Create a date for headers and the credential string
| Copyright 2017 , 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(hash_aws_v4).
-export([new/5, sign/7]).
-define(ALGORITHM, <<"AWS4-HMAC-SHA256">>).
-record(aws, {
access = undefined :: binary(),
secret = undefined :: binary(),
token = undefined :: binary(),
region = undefined :: binary(),
service = undefined :: binary()
}).
new(Access, Secret, Token, Region, Service) ->
#aws{
access = hash:s(Access),
secret = hash:s(Secret),
token = Token,
region = hash:s(Region),
service = hash:s(Service)
}.
sign(Mthd, Host, Path, Query, Head, Data, #aws{access = Access} = Hash) ->
<<Date:8/binary, _/binary>> = AmzDate = amzdate(),
Head1 = headers(AmzDate, Host, Head, Hash),
HeadSgn = signed_headers(Head1),
Request = lists:join(<<$\n>>, [
hash:s(Mthd),
canonical_path(Path),
canonical_q(Query),
canonical_head(Head1),
HeadSgn,
payload_hash(Data)
]),
KeyScope = credential_scope(Date, Hash),
ToSign = lists:join(<<$\n>>, [?ALGORITHM, AmzDate, KeyScope, btoh(crypto:hash(sha256, Request))]),
Signature = btoh(sign(signing_key(Date, Hash), ToSign)),
AwsAuth = iolist_to_binary([
?ALGORITHM,
<<" ">>,
<<"Credential=">>, Access, <<$/>>, KeyScope,
<<", ">>,
<<"SignedHeaders=">>, HeadSgn,
<<", ">>,
<<"Signature=">>, Signature
]),
Tail = [X || X = {K, _} <- Head1,
K =:= 'x-amz-date' orelse K =:= 'Host' orelse K =:= 'x-amz-security-token'],
[{'Authorization', AwsAuth}|Tail].
headers(AmzDate, Host, Head, Hash) ->
header_amz_date(AmzDate,
header_host(Host,
header_amz_token(Hash, Head)
)
).
header_amz_date(AmzDate, Head) ->
[{'x-amz-date', AmzDate} | Head].
header_amz_token(#aws{token = undefined}, Head) ->
Head;
header_amz_token(#aws{token = Token}, Head) ->
[{'x-amz-security-token', Token} | Head].
header_host(Host, Head) ->
case lists:keyfind('Host', 1, Head) of
false ->
[{'Host', hash:s(Host)} | Head];
_ ->
Head
end.
Step 2 : Create canonical URI -- the part of the URI from domain to query
canonical_path(undefined) -> <<$/>>;
canonical_path(Path) -> Path.
Step 3 : Create the canonical query string . Query string values must
be URL - encoded ( ) . The parameters must be sorted by name .
canonical_q(Query) ->
iolist_to_binary(
lists:join(<<$&>>,
[uri:escape(<<K/binary, $=, V/binary>>) ||
{K, V} <- lists:sort(listT(Query))]
)
).
listT(undefined) -> [];
listT(X) -> X.
Step 4 : Create the canonical headers and signed headers . Header names
canonical_head(Head) ->
iolist_to_binary(
lists:sort(
[<<(lowercase(K))/binary, $:, (hash:s(V))/binary, $\n>> || {K, V} <- Head]
)
).
Step 5 : Create the list of signed headers . This lists the headers
signed_headers(Head) ->
iolist_to_binary(
lists:join(<<$;>>,
lists:sort(
[lowercase(K) || {K, _} <- Head]
)
)
).
lowercase(X) ->
<< <<(to_lower(C)):8>> || <<C:8>> <= hash:s(X) >>.
to_lower(X)
when X >= $A, X =< $Z ->
X + 32;
to_lower(X) ->
X.
Step 6 : Create payload hash ( hash of the request body content ) .
payload_hash(undefined) ->
payload_hash(<<>>);
payload_hash(Payload) ->
btoh(crypto:hash(sha256, Payload)).
amzdate() ->
{{Year,Month,Day},{Hour,Min,Sec}} = calendar:now_to_universal_time(os:timestamp()),
iolist_to_binary(
io_lib:format(
"~4.10.0B~2.10.0B~2.10.0BT~2.10.0B~2.10.0B~2.10.0BZ",
[Year, Month, Day, Hour, Min, Sec]
)
).
credential_scope(Date, #aws{region = Region, service = Service}) ->
iolist_to_binary(
lists:join(<<$/>>, [
Date,
Region,
Service,
<<"aws4_request">>
])
).
signing_key(Date, #aws{secret = Secret, region = Region, service = Service}) ->
get_signature_key(Secret, Date, Region, Service).
get_signature_key(Key, Date, Region, Service) ->
KDate = sign(<<"AWS4", Key/binary>>, Date),
KRegion = sign(KDate, Region),
KService = sign(KRegion, Service),
sign(KService, <<"aws4_request">>).
sign(Key, Data) ->
crypto:hmac(sha256, Key, Data).
btoh(X) ->
<< <<(if A < 10 -> $0 + A; A >= 10 -> $a + (A - 10) end):8>> || <<A:4>> <=X >>.
|
8a98c07569f58020c43e8a669cffb52d62815ca1afcfd294c60b36b2b389cb90 | racket/web-server | add02-base.rkt | #lang web-server/base
(require web-server/http
web-server/lang/web
net/url)
(define interface-version 'stateless)
(provide start interface-version)
;; get-number-from-user: string -> number
;; ask the user for a number
(define (gn msg)
(let ([req
(send/suspend/url
(lambda (k-url)
(response/xexpr
`(html (head (title ,(format "Get ~a number" msg)))
(body
(form ([action ,(url->string k-url)]
[method "get"]
[enctype "application/x-www-form-urlencoded"])
,(format "Enter the ~a number to add: " msg)
(input ([type "text"] [name "number"] [value ""]))
(input ([type "submit"]))))))))])
(string->number
(cdr (assoc 'number (url-query (request-uri req)))))))
(define (start initial-request)
(response/xexpr
`(html (head (title "Final Page"))
(body
(h1 "Final Page")
(p ,(format "The answer is ~a"
(+ (gn "first") (gn "second"))))))))
| null | https://raw.githubusercontent.com/racket/web-server/f718800b5b3f407f7935adf85dfa663c4bba1651/web-server-lib/web-server/default-web-root/htdocs/lang-servlets/add02-base.rkt | racket | get-number-from-user: string -> number
ask the user for a number | #lang web-server/base
(require web-server/http
web-server/lang/web
net/url)
(define interface-version 'stateless)
(provide start interface-version)
(define (gn msg)
(let ([req
(send/suspend/url
(lambda (k-url)
(response/xexpr
`(html (head (title ,(format "Get ~a number" msg)))
(body
(form ([action ,(url->string k-url)]
[method "get"]
[enctype "application/x-www-form-urlencoded"])
,(format "Enter the ~a number to add: " msg)
(input ([type "text"] [name "number"] [value ""]))
(input ([type "submit"]))))))))])
(string->number
(cdr (assoc 'number (url-query (request-uri req)))))))
(define (start initial-request)
(response/xexpr
`(html (head (title "Final Page"))
(body
(h1 "Final Page")
(p ,(format "The answer is ~a"
(+ (gn "first") (gn "second"))))))))
|
00da7b0d408b71b9c2bcf4bff0f461978fc9d6073c812c297feabf4002f34088 | discus-lang/salt | Driver.hs |
module Salt.LSP.Driver
(runLSP)
where
import Salt.LSP.Protocol
import Salt.LSP.Interface
import Salt.LSP.State
import qualified Salt.LSP.Task.Diagnostics as Task
import Data.IORef
import qualified System.IO as System
import qualified System.Exit as System
import qualified System.Posix.Process as Process
import qualified Control.Exception as Control
import qualified Data.Map as Map
import qualified Text.Show.Pretty as T
---------------------------------------------------------------------------------------------------
-- | Become a language server plugin.
--
* We listen to requests on stdin and send responses to stdout .
-- * We take an optional path for server side logging.
-- * If the server process crashes then try to write the reason to the debug log.
--
runLSP :: Maybe FilePath -> IO ()
runLSP mFileLog
= Control.catch
-- Enter the main server loop.
(do state <- lspBegin mFileLog
lspLoop state)
-- If we get any exception from the server process then try to
-- write it to the log file, if we have one.
(\(e :: Control.SomeException)
-> do (case mFileLog of
Nothing -> return ()
Just file
-> System.appendFile file
$ "\n" ++ T.ppShow e)
System.die $ unlines
[ "salt lsp server crashed"
, T.ppShow e ])
---------------------------------------------------------------------------------------------------
-- | The main event loop for the language server.
--
We do a blocking read of stdin to get a request ,
-- then dispatch it to the appropriat
lspLoop :: State -> IO ()
lspLoop state
= case statePhase state of
PhaseStartup
-> do msg <- lspRead state
lspStartup state msg
PhaseInitialized
-> do msg <- lspRead state
lspInitialized state msg
_ -> do
lspLog state "not done yet"
lspLoop state
---------------------------------------------------------------------------------------------------
-- | Begin the language server plugin.
-- We open our local file and initialize the state.
lspBegin :: Maybe FilePath -> IO State
lspBegin mFileLog
= do
pid <- Process.getProcessID
-- Create a new file for the debug log, if we were asked for one.
mLogDebug
<- case mFileLog of
Nothing -> return Nothing
Just filePath
-> do let filePathPid = filePath ++ "." ++ show pid
hLogDebug <- System.openFile filePathPid System.WriteMode
return $ Just (filePathPid, hLogDebug)
-- The type checked module is stored here, when we have one.
refCoreChecked <- newIORef Map.empty
-- The complete state.
let state
= State
{ stateLogDebug = mLogDebug
, statePhase = PhaseStartup
, stateCoreChecked = refCoreChecked }
lspLog state "* Salt language server starting up"
return state
---------------------------------------------------------------------------------------------------
-- | Handle startup phase where we wait for the
request sent from the client .
lspStartup :: State -> Request JSValue -> IO ()
lspStartup state req
-- Client sends us 'inititialize' with the set of its capabilities.
-- We reply with our own capabilities.
| "initialize" <- reqMethod req
, Just (params :: InitializeParams)
<- join $ fmap unpack $ reqParams req
= do
lspLog state "* Initialize"
-- Log the list of client capabilities.
lspLog state $ T.ppShow params
-- Tell the client what our capabilities are.
lspSend state $ jobj
[ "id" := V $ pack $ reqId req
, "result"
:= O [ "capabilities"
:= O [ "textDocumentSync"
:= O [ "openClose" := B True -- send us open/close notif.
, "change" := I 1 -- send us full file changes.
, "save" := B True -- send us save notif.
]]]]
lspLoop state
-- Cient sends us 'initialized' if it it is happy with the
-- capabilities that we sent.
| "initialized" <- reqMethod req
= do lspLog state "* Initialized"
lspLoop state { statePhase = PhaseInitialized }
-- Something went wrong.
| otherwise
= do lspLog state "* Initialization received unexpected message."
lspLoop state
---------------------------------------------------------------------------------------------------
-- | Main event handler of the server.
--
-- Once initialized we receive the main requests and update our state.
--
lspInitialized :: State -> Request JSValue -> IO ()
lspInitialized state req
On startup VSCode sends us a didChangeConfiguration ,
-- but we don't have any settings define, so the payload is empty.
-- Just drop it on the floor.
| "workspace/didChangeConfiguration" <- reqMethod req
, Just jParams <- reqParams req
, Just jSettings <- getField jParams "settings"
, Just jSettingsSalt <- getField jSettings "salt"
= do
lspLog state "* DidChangeConfiguration (salt)"
lspLog state $ " jSettings: " ++ show jSettingsSalt
lspLoop state
-- A file was opened.
| "textDocument/didOpen" <- reqMethod req
, Just jParams <- reqParams req
, Just jDoc <- getField jParams "textDocument"
, Just sUri <- getString =<< getField jDoc "uri"
, Just sLanguageId <- getString =<< getField jDoc "languageId"
, Just iVersion <- getInteger =<< getField jDoc "version"
, Just sText <- getString =<< getField jDoc "text"
= do
lspLog state "* DidOpen"
lspLog state $ " sUri: " ++ show sUri
lspLog state $ " sLanguageId: " ++ show sLanguageId
lspLog state $ " iVersion: " ++ show iVersion
lspLog state $ " sText: " ++ show sText
Task.updateDiagnostics state sUri sText
lspLoop state
-- A file was closed.
| "textDocument/didClose" <- reqMethod req
, Just jParams <- reqParams req
, Just jDoc <- getField jParams "textDocument"
, Just sUri <- getString =<< getField jDoc "uri"
= do
lspLog state "* DidClose"
lspLog state $ " sUri: " ++ show sUri
-- Once the file is closed, clear any errors that it might still have
-- from the IDE.
Task.sendClearDiagnostics state sUri
lspLoop state
-- A file was saved.
| "textDocument/didSave" <- reqMethod req
, Just jParams <- reqParams req
, Just jDoc <- getField jParams "textDocument"
, Just sUri <- getString =<< getField jDoc "uri"
, Just iVersion <- getInteger =<< getField jDoc "version"
= do
lspLog state "* DidSave"
lspLog state $ " sUri: " ++ show sUri
lspLog state $ " iVersion: " ++ show iVersion
lspLoop state
-- A file was changed.
| "textDocument/didChange" <- reqMethod req
, Just jParams <- reqParams req
, Just jDoc <- getField jParams "textDocument"
, Just sUri <- getString =<< getField jDoc "uri"
, Just iVersion <- getInteger =<< getField jDoc "version"
, Just [jChange] <- getArray =<< getField jParams "contentChanges"
, Just sText <- getString =<< getField jChange "text"
= do
lspLog state "* DidChange"
lspLog state $ " sUri: " ++ show sUri
lspLog state $ " iVersion: " ++ show iVersion
lspLog state $ " sText: " ++ show sText
Task.updateDiagnostics state sUri sText
lspLoop state
-- Some other request that we don't handle.
| otherwise
= do
lspLog state "* Request"
lspLog state (T.ppShow req)
lspLoop state
| null | https://raw.githubusercontent.com/discus-lang/salt/33c14414ac7e238fdbd8161971b8b8ac67fff569/src/salt/Salt/LSP/Driver.hs | haskell | -------------------------------------------------------------------------------------------------
| Become a language server plugin.
* We take an optional path for server side logging.
* If the server process crashes then try to write the reason to the debug log.
Enter the main server loop.
If we get any exception from the server process then try to
write it to the log file, if we have one.
-------------------------------------------------------------------------------------------------
| The main event loop for the language server.
then dispatch it to the appropriat
-------------------------------------------------------------------------------------------------
| Begin the language server plugin.
We open our local file and initialize the state.
Create a new file for the debug log, if we were asked for one.
The type checked module is stored here, when we have one.
The complete state.
-------------------------------------------------------------------------------------------------
| Handle startup phase where we wait for the
Client sends us 'inititialize' with the set of its capabilities.
We reply with our own capabilities.
Log the list of client capabilities.
Tell the client what our capabilities are.
send us open/close notif.
send us full file changes.
send us save notif.
Cient sends us 'initialized' if it it is happy with the
capabilities that we sent.
Something went wrong.
-------------------------------------------------------------------------------------------------
| Main event handler of the server.
Once initialized we receive the main requests and update our state.
but we don't have any settings define, so the payload is empty.
Just drop it on the floor.
A file was opened.
A file was closed.
Once the file is closed, clear any errors that it might still have
from the IDE.
A file was saved.
A file was changed.
Some other request that we don't handle. |
module Salt.LSP.Driver
(runLSP)
where
import Salt.LSP.Protocol
import Salt.LSP.Interface
import Salt.LSP.State
import qualified Salt.LSP.Task.Diagnostics as Task
import Data.IORef
import qualified System.IO as System
import qualified System.Exit as System
import qualified System.Posix.Process as Process
import qualified Control.Exception as Control
import qualified Data.Map as Map
import qualified Text.Show.Pretty as T
* We listen to requests on stdin and send responses to stdout .
runLSP :: Maybe FilePath -> IO ()
runLSP mFileLog
= Control.catch
(do state <- lspBegin mFileLog
lspLoop state)
(\(e :: Control.SomeException)
-> do (case mFileLog of
Nothing -> return ()
Just file
-> System.appendFile file
$ "\n" ++ T.ppShow e)
System.die $ unlines
[ "salt lsp server crashed"
, T.ppShow e ])
We do a blocking read of stdin to get a request ,
lspLoop :: State -> IO ()
lspLoop state
= case statePhase state of
PhaseStartup
-> do msg <- lspRead state
lspStartup state msg
PhaseInitialized
-> do msg <- lspRead state
lspInitialized state msg
_ -> do
lspLog state "not done yet"
lspLoop state
lspBegin :: Maybe FilePath -> IO State
lspBegin mFileLog
= do
pid <- Process.getProcessID
mLogDebug
<- case mFileLog of
Nothing -> return Nothing
Just filePath
-> do let filePathPid = filePath ++ "." ++ show pid
hLogDebug <- System.openFile filePathPid System.WriteMode
return $ Just (filePathPid, hLogDebug)
refCoreChecked <- newIORef Map.empty
let state
= State
{ stateLogDebug = mLogDebug
, statePhase = PhaseStartup
, stateCoreChecked = refCoreChecked }
lspLog state "* Salt language server starting up"
return state
request sent from the client .
lspStartup :: State -> Request JSValue -> IO ()
lspStartup state req
| "initialize" <- reqMethod req
, Just (params :: InitializeParams)
<- join $ fmap unpack $ reqParams req
= do
lspLog state "* Initialize"
lspLog state $ T.ppShow params
lspSend state $ jobj
[ "id" := V $ pack $ reqId req
, "result"
:= O [ "capabilities"
:= O [ "textDocumentSync"
]]]]
lspLoop state
| "initialized" <- reqMethod req
= do lspLog state "* Initialized"
lspLoop state { statePhase = PhaseInitialized }
| otherwise
= do lspLog state "* Initialization received unexpected message."
lspLoop state
lspInitialized :: State -> Request JSValue -> IO ()
lspInitialized state req
On startup VSCode sends us a didChangeConfiguration ,
| "workspace/didChangeConfiguration" <- reqMethod req
, Just jParams <- reqParams req
, Just jSettings <- getField jParams "settings"
, Just jSettingsSalt <- getField jSettings "salt"
= do
lspLog state "* DidChangeConfiguration (salt)"
lspLog state $ " jSettings: " ++ show jSettingsSalt
lspLoop state
| "textDocument/didOpen" <- reqMethod req
, Just jParams <- reqParams req
, Just jDoc <- getField jParams "textDocument"
, Just sUri <- getString =<< getField jDoc "uri"
, Just sLanguageId <- getString =<< getField jDoc "languageId"
, Just iVersion <- getInteger =<< getField jDoc "version"
, Just sText <- getString =<< getField jDoc "text"
= do
lspLog state "* DidOpen"
lspLog state $ " sUri: " ++ show sUri
lspLog state $ " sLanguageId: " ++ show sLanguageId
lspLog state $ " iVersion: " ++ show iVersion
lspLog state $ " sText: " ++ show sText
Task.updateDiagnostics state sUri sText
lspLoop state
| "textDocument/didClose" <- reqMethod req
, Just jParams <- reqParams req
, Just jDoc <- getField jParams "textDocument"
, Just sUri <- getString =<< getField jDoc "uri"
= do
lspLog state "* DidClose"
lspLog state $ " sUri: " ++ show sUri
Task.sendClearDiagnostics state sUri
lspLoop state
| "textDocument/didSave" <- reqMethod req
, Just jParams <- reqParams req
, Just jDoc <- getField jParams "textDocument"
, Just sUri <- getString =<< getField jDoc "uri"
, Just iVersion <- getInteger =<< getField jDoc "version"
= do
lspLog state "* DidSave"
lspLog state $ " sUri: " ++ show sUri
lspLog state $ " iVersion: " ++ show iVersion
lspLoop state
| "textDocument/didChange" <- reqMethod req
, Just jParams <- reqParams req
, Just jDoc <- getField jParams "textDocument"
, Just sUri <- getString =<< getField jDoc "uri"
, Just iVersion <- getInteger =<< getField jDoc "version"
, Just [jChange] <- getArray =<< getField jParams "contentChanges"
, Just sText <- getString =<< getField jChange "text"
= do
lspLog state "* DidChange"
lspLog state $ " sUri: " ++ show sUri
lspLog state $ " iVersion: " ++ show iVersion
lspLog state $ " sText: " ++ show sText
Task.updateDiagnostics state sUri sText
lspLoop state
| otherwise
= do
lspLog state "* Request"
lspLog state (T.ppShow req)
lspLoop state
|
b76667c20cf413a68352752ddd8b224d92f8a3eff35ce6c2d48a306bc2253afc | emaphis/HtDP2e-solutions | 09_02_non_empty_lists.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname 09_02_non_empty_lists) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
HtDP 2e - 9 Designing with Self - Referential Data Definitions
9.2 Non - empty Lists
Exercises : 143 - 148
; A List-of-temperatures is one of:
; – '()
– ( cons CTemperature List - of - temperatures )
A CTemperature is a Number greater than -273 .
; List-of-temperatures -> Number
; computes the average temperature
(check-expect (average (cons 3 '())) 3)
(check-expect
(average (cons 1 (cons 2 (cons 3 '())))) 2)
(define (average alot)
(/ (sum alot) (how-many alot)))
; List-of-temperatures -> Number
; adds up the temperatures on the given list
(check-expect (sum (cons 3 '())) 3)
(check-expect
(sum (cons 1 (cons 2 (cons 3 '())))) 6)
(define (sum alot)
(cond
[(empty? alot) 0]
[else (+ (first alot) (sum (rest alot)))]))
; List-of-temperatures -> Number
; counts the temperatures on the given list
(check-expect (how-many (cons 3 '())) 1)
(check-expect
(how-many (cons 1 (cons 2 (cons 3 '())))) 3)
(define (how-many alot)
(cond
[(empty? alot) 0]
[else (+ 1 (how-many (rest alot)))]))
;;;;;;;;;;;;;;;;;;;;;;;;;;
Ex . 143 :
Determine how average behaves in when applied to the empty list .
;; Then design checked-average, a function that produces an informative error
;; message when it is applied to '().
You have division by zero on empty List - of - temperaturs becuase the how - many
function yields the base case : 0
;> (average '())
/ : division by zero
; List-of-temperatures -> Number
; computes the average temperature
(check-expect (checked-average (cons 3 '())) 3)
(check-expect
(checked-average (cons 1 (cons 2 (cons 3 '())))) 2)
(check-error (checked-average '()))
(define (checked-average alot)
(cond
[(empty? alot)
(error "List of temperatures must have at least one temperature")]
[else (average alot)]))
;;;;;;;;;;;;;;;;;;;;;;;;;;
;; aternative implementation
average temperture should only take lista of at least one member
A NEList - of - temperatures is one of :
– ( cons CTemperature ' ( ) )
– ( cons CTemperature NEList - of - temperatures )
; interpretation non-empty lists of Celsius temperatures
NEList - of - temperatures - > Number
; computes the average temperature
(check-expect (average-n (cons 1 (cons 2 (cons 3 '()))))
2)
(define (average-n ne-l)
(/ (sum ne-l)
(how-many ne-l)))
;;;;;;;;;;;;;
Ex . 144 :
Will sum and how - many work for NEList - of - temperatures even though they are
;; designed for inputs from List-of-temperatures? If you think they don’t work,
;; provide counter-examples. If you think they would, explain why.
They will work , NEList - of - temperatures is a subset of List - of - temperaturs , so
every item in NELOT has a corresponding item in LOT
;;;;;;;;;;;;;;;;;;;;;;
a test for a list of one item :
; (empty? (rest list))
; else -- (cons? (rest list))
NEList - of - temperatures - > Number
; computes the sum of the given temperatures
(check-expect
(sum-n (cons 1 (cons 2 (cons 3 '())))) 6)
;(define (sum-n ne-l) 0)
; NEList - of - temperatures - > Number
(define (sum-n ne-l)
(cond
[(empty? (rest ne-l)) (... (first ne-l) ...)]
[else ... (first ne-l) ... (rest ne-l) ...]))
explain why the first clause does not contain the selector
; expression (rest ne-l):
( first ( rest ne- ) ) returns the second item in the list . We need to access the
first item .
;; Self reference:
#;
(define (sum-n ne-l)
(cond
[(empty? (rest ne-l)) (... (first ne-l) ...)]
[else
(... (first ne-l) ... (sum-n (rest ne-l)) ...)]))
(define (sum-n ne-l)
(cond
[(empty? (rest ne-l)) (first ne-l)]
[else (+ (first ne-l) (sum-n (rest ne-l)))]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Ex > 145 :
Design sorted > ? . The function consumes a NEList - of - temperatures . It produces
;; #true if the temperatures are sorted in descending order, that is, if the
second is smaller than the first , the third smaller than the second , and
;; so on. Otherwise it produces #false.
NEList - of - temperatures - > Boolean
produce # true is NEList - of - temperatures is sorted in desending order
(check-expect (sorted>? (cons 3 '())) #true)
(check-expect (sorted>? (cons 1 (cons 2 '()))) #false)
(check-expect (sorted>? (cons 3 (cons 2 '()))) #true)
(check-expect (sorted>? (cons 0 (cons 3 (cons 2 '())))) #false)
; (sort>?) (sorted>?
l ( first l ) ( rest l ) ( rest l ) ) l )
;-------------------------------------------------------------
( cons 1
( cons 2 1 ( cons 2 # true # false
; '())) '())
( cons 3
( cons 2 3 ( cons 2 # true # true
; '())) '())
( cons 0
( cons 3 0 ( cons 3 # true # false
( cons 2 ( cons 2
; '())) '()))
(define (sorted>? ne-l)
(cond
[(empty? (rest ne-l)) #true]
[else
(and (> (first ne-l) (first (rest ne-l)))
(sorted>? (rest ne-l)))]))
Ex . 146 :
Design how - many for NEList - of - temperatures . Doing so completes average , so
;; ensure that average passes all of its tests, too.
; List-of-temperatures -> Number
; counts the temperatures on the given list
(check-expect (how-many-n (cons 3 '())) 1) ;base case
(check-expect
(how-many-n (cons 1 (cons 2 (cons 3 '())))) 3)
#; ; template
(define (how-many-n ne-l)
(cond
[(empty? (rest ne-l)) (... (first ne-l) ...)]
[else
(... (first ne-l) ... (sum-n (rest ne-l)) ...)]))
( first ne-1 ) represents 1
(define (how-many-n ne-l)
(cond
[(empty? (rest ne-l)) 1]
[else
(+ 1 (how-many-n (rest ne-l)))]))
NEList - of - temperatures - > Number
; computes the average temperature
(check-expect (average-n2 (cons 3 '()))
3)
(check-expect (average-n2 (cons 1 (cons 2 (cons 3 '()))))
2)
(define (average-n2 ne-l)
(/ (sum-n ne-l) ; see above
(how-many-n ne-l)))
Ex . 147
Develop a data definition for NEList - of - Booleans , a representation of
non - empty lists of Boolean values . Then re - design the functions all - true
and one - true from exercise 140 .
A NEList - of - Booleans is one of :
– ( cons Boolean ' ( ) )
– ( cons - of - temperatures )
interpretation non - empty list of Booleans
(define LOB2 (cons #true '())) ;base case
(define LOB3 (cons #false '())) ;base case
(define LOB4 (cons #true (cons #false '())))
(define LOB5 (cons #false (cons #true (cons #true '()))))
#; ; template for nlob
(define (fun-for-nlob nlob)
(cond [(empty? (rest nlob)) (... (first nlob))]
[else
(... (first nlob) ...
(fun-for-nlob (rest nlob)) ....)]))
NEList - of - Booleans - > Boolean
;; produce #true if a list contains all #true, #false otherwise
(check-expect (all-true? (cons #true '())) #true)
(check-expect (all-true? (cons #true (cons #true '()))) #true)
(check-expect (all-true? (cons #true (cons #false '()))) #false)
(check-expect (all-true? (cons #false (cons #true '()))) #false)
(define (all-true? nlob)
(cond [(empty? (rest nlob)) (first nlob)]
[else
(and (first nlob)
(all-true? (rest nlob)))]))
;; List-of-booleans -> Boolean
return # true if at least one item in a lob is # true
(check-expect (one-true? (cons #false '())) #false)
(check-expect (one-true? (cons #true '())) #true)
(check-expect (one-true? (cons #false (cons #false '()))) #false)
(check-expect (one-true? (cons #false (cons #true '()))) #true)
(define (one-true? nlob)
(cond [(empty? (rest nlob)) (first nlob)]
[else
(or (first nlob)
(one-true? (rest nlob)))]))
Ex . 148 :
;; Compare the function definitions from this section (sum, how-many, all-true,
one - true ) with the corresponding function definitions from the preceding
;; sections. Is it better to work with data definitions that accommodate empty
;; lists as opposed to definitions for non-empty lists? Why? Why not?
; I think it's easier to work with lists that can be empty. The templates are
; simpler and the base case and the combining funtions are much easier to
; reason about.
| null | https://raw.githubusercontent.com/emaphis/HtDP2e-solutions/ecb60b9a7bbf9b8999c0122b6ea152a3301f0a68/2-Arbitrarily-Large-Data/09-Designing-Self-Referential/09_02_non_empty_lists.rkt | racket | about the language level of this file in a form that our tools can easily process.
A List-of-temperatures is one of:
– '()
List-of-temperatures -> Number
computes the average temperature
List-of-temperatures -> Number
adds up the temperatures on the given list
List-of-temperatures -> Number
counts the temperatures on the given list
Then design checked-average, a function that produces an informative error
message when it is applied to '().
> (average '())
List-of-temperatures -> Number
computes the average temperature
aternative implementation
interpretation non-empty lists of Celsius temperatures
computes the average temperature
designed for inputs from List-of-temperatures? If you think they don’t work,
provide counter-examples. If you think they would, explain why.
(empty? (rest list))
else -- (cons? (rest list))
computes the sum of the given temperatures
(define (sum-n ne-l) 0)
NEList - of - temperatures - > Number
expression (rest ne-l):
Self reference:
#true if the temperatures are sorted in descending order, that is, if the
so on. Otherwise it produces #false.
(sort>?) (sorted>?
-------------------------------------------------------------
'())) '())
'())) '())
'())) '()))
ensure that average passes all of its tests, too.
List-of-temperatures -> Number
counts the temperatures on the given list
base case
; template
computes the average temperature
see above
base case
base case
; template for nlob
produce #true if a list contains all #true, #false otherwise
List-of-booleans -> Boolean
Compare the function definitions from this section (sum, how-many, all-true,
sections. Is it better to work with data definitions that accommodate empty
lists as opposed to definitions for non-empty lists? Why? Why not?
I think it's easier to work with lists that can be empty. The templates are
simpler and the base case and the combining funtions are much easier to
reason about. | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-reader.ss" "lang")((modname 09_02_non_empty_lists) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
HtDP 2e - 9 Designing with Self - Referential Data Definitions
9.2 Non - empty Lists
Exercises : 143 - 148
– ( cons CTemperature List - of - temperatures )
A CTemperature is a Number greater than -273 .
(check-expect (average (cons 3 '())) 3)
(check-expect
(average (cons 1 (cons 2 (cons 3 '())))) 2)
(define (average alot)
(/ (sum alot) (how-many alot)))
(check-expect (sum (cons 3 '())) 3)
(check-expect
(sum (cons 1 (cons 2 (cons 3 '())))) 6)
(define (sum alot)
(cond
[(empty? alot) 0]
[else (+ (first alot) (sum (rest alot)))]))
(check-expect (how-many (cons 3 '())) 1)
(check-expect
(how-many (cons 1 (cons 2 (cons 3 '())))) 3)
(define (how-many alot)
(cond
[(empty? alot) 0]
[else (+ 1 (how-many (rest alot)))]))
Ex . 143 :
Determine how average behaves in when applied to the empty list .
You have division by zero on empty List - of - temperaturs becuase the how - many
function yields the base case : 0
/ : division by zero
(check-expect (checked-average (cons 3 '())) 3)
(check-expect
(checked-average (cons 1 (cons 2 (cons 3 '())))) 2)
(check-error (checked-average '()))
(define (checked-average alot)
(cond
[(empty? alot)
(error "List of temperatures must have at least one temperature")]
[else (average alot)]))
average temperture should only take lista of at least one member
A NEList - of - temperatures is one of :
– ( cons CTemperature ' ( ) )
– ( cons CTemperature NEList - of - temperatures )
NEList - of - temperatures - > Number
(check-expect (average-n (cons 1 (cons 2 (cons 3 '()))))
2)
(define (average-n ne-l)
(/ (sum ne-l)
(how-many ne-l)))
Ex . 144 :
Will sum and how - many work for NEList - of - temperatures even though they are
They will work , NEList - of - temperatures is a subset of List - of - temperaturs , so
every item in NELOT has a corresponding item in LOT
a test for a list of one item :
NEList - of - temperatures - > Number
(check-expect
(sum-n (cons 1 (cons 2 (cons 3 '())))) 6)
(define (sum-n ne-l)
(cond
[(empty? (rest ne-l)) (... (first ne-l) ...)]
[else ... (first ne-l) ... (rest ne-l) ...]))
explain why the first clause does not contain the selector
( first ( rest ne- ) ) returns the second item in the list . We need to access the
first item .
(define (sum-n ne-l)
(cond
[(empty? (rest ne-l)) (... (first ne-l) ...)]
[else
(... (first ne-l) ... (sum-n (rest ne-l)) ...)]))
(define (sum-n ne-l)
(cond
[(empty? (rest ne-l)) (first ne-l)]
[else (+ (first ne-l) (sum-n (rest ne-l)))]))
Ex > 145 :
Design sorted > ? . The function consumes a NEList - of - temperatures . It produces
second is smaller than the first , the third smaller than the second , and
NEList - of - temperatures - > Boolean
produce # true is NEList - of - temperatures is sorted in desending order
(check-expect (sorted>? (cons 3 '())) #true)
(check-expect (sorted>? (cons 1 (cons 2 '()))) #false)
(check-expect (sorted>? (cons 3 (cons 2 '()))) #true)
(check-expect (sorted>? (cons 0 (cons 3 (cons 2 '())))) #false)
l ( first l ) ( rest l ) ( rest l ) ) l )
( cons 1
( cons 2 1 ( cons 2 # true # false
( cons 3
( cons 2 3 ( cons 2 # true # true
( cons 0
( cons 3 0 ( cons 3 # true # false
( cons 2 ( cons 2
(define (sorted>? ne-l)
(cond
[(empty? (rest ne-l)) #true]
[else
(and (> (first ne-l) (first (rest ne-l)))
(sorted>? (rest ne-l)))]))
Ex . 146 :
Design how - many for NEList - of - temperatures . Doing so completes average , so
(check-expect
(how-many-n (cons 1 (cons 2 (cons 3 '())))) 3)
(define (how-many-n ne-l)
(cond
[(empty? (rest ne-l)) (... (first ne-l) ...)]
[else
(... (first ne-l) ... (sum-n (rest ne-l)) ...)]))
( first ne-1 ) represents 1
(define (how-many-n ne-l)
(cond
[(empty? (rest ne-l)) 1]
[else
(+ 1 (how-many-n (rest ne-l)))]))
NEList - of - temperatures - > Number
(check-expect (average-n2 (cons 3 '()))
3)
(check-expect (average-n2 (cons 1 (cons 2 (cons 3 '()))))
2)
(define (average-n2 ne-l)
(how-many-n ne-l)))
Ex . 147
Develop a data definition for NEList - of - Booleans , a representation of
non - empty lists of Boolean values . Then re - design the functions all - true
and one - true from exercise 140 .
A NEList - of - Booleans is one of :
– ( cons Boolean ' ( ) )
– ( cons - of - temperatures )
interpretation non - empty list of Booleans
(define LOB4 (cons #true (cons #false '())))
(define LOB5 (cons #false (cons #true (cons #true '()))))
(define (fun-for-nlob nlob)
(cond [(empty? (rest nlob)) (... (first nlob))]
[else
(... (first nlob) ...
(fun-for-nlob (rest nlob)) ....)]))
NEList - of - Booleans - > Boolean
(check-expect (all-true? (cons #true '())) #true)
(check-expect (all-true? (cons #true (cons #true '()))) #true)
(check-expect (all-true? (cons #true (cons #false '()))) #false)
(check-expect (all-true? (cons #false (cons #true '()))) #false)
(define (all-true? nlob)
(cond [(empty? (rest nlob)) (first nlob)]
[else
(and (first nlob)
(all-true? (rest nlob)))]))
return # true if at least one item in a lob is # true
(check-expect (one-true? (cons #false '())) #false)
(check-expect (one-true? (cons #true '())) #true)
(check-expect (one-true? (cons #false (cons #false '()))) #false)
(check-expect (one-true? (cons #false (cons #true '()))) #true)
(define (one-true? nlob)
(cond [(empty? (rest nlob)) (first nlob)]
[else
(or (first nlob)
(one-true? (rest nlob)))]))
Ex . 148 :
one - true ) with the corresponding function definitions from the preceding
|
aac35b1031c30e0dce35455b20fd37e0f98eaa394dfc7d845168f3a714810bb5 | vmchale/morphism-zoo | Fib.hs | # LANGUAGE TemplateHaskell #
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
module Fib
( fib
, fibPattern
, fibBig
) where
import Data.Functor.Foldable
import Data.Functor.Foldable.TH
import Data.Int
data Fib a = Add (Fib a) (Fib a)
| Fix a
makeBaseFunctor ''Fib
algebra :: Num t => FibF t t -> t
algebra (AddF x1 x2) = x1 + x2
algebra (FixF x) = x
coalgebra :: (Num a, Num r, Eq r) => r -> FibF a r
coalgebra 0 = FixF 1
coalgebra 1 = FixF 1
coalgebra n = AddF (n-1) (n-2)
fib :: Int -> Int
fib = hylo algebra coalgebra
fibPattern :: Int -> Int
fibPattern 0 = 1
fibPattern 1 = 1
fibPattern n = fibPattern (n-1) + fibPattern (n-2)
fibBig :: Integer -> Integer
fibBig = hylo algebra coalgebra
--fibBig :: Integer -> Integer
fibBig 0 = 1
fibBig 1 = 1
--fibBig n = fibBigPattern (n-1) + fibBigPattern (n-2)
| null | https://raw.githubusercontent.com/vmchale/morphism-zoo/4f1a040ddb3cb1f0292f94d98d34f3075c97d738/src/Fib.hs | haskell | # LANGUAGE KindSignatures #
# LANGUAGE TypeFamilies #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveTraversable #
fibBig :: Integer -> Integer
fibBig n = fibBigPattern (n-1) + fibBigPattern (n-2) | # LANGUAGE TemplateHaskell #
module Fib
( fib
, fibPattern
, fibBig
) where
import Data.Functor.Foldable
import Data.Functor.Foldable.TH
import Data.Int
data Fib a = Add (Fib a) (Fib a)
| Fix a
makeBaseFunctor ''Fib
algebra :: Num t => FibF t t -> t
algebra (AddF x1 x2) = x1 + x2
algebra (FixF x) = x
coalgebra :: (Num a, Num r, Eq r) => r -> FibF a r
coalgebra 0 = FixF 1
coalgebra 1 = FixF 1
coalgebra n = AddF (n-1) (n-2)
fib :: Int -> Int
fib = hylo algebra coalgebra
fibPattern :: Int -> Int
fibPattern 0 = 1
fibPattern 1 = 1
fibPattern n = fibPattern (n-1) + fibPattern (n-2)
fibBig :: Integer -> Integer
fibBig = hylo algebra coalgebra
fibBig 0 = 1
fibBig 1 = 1
|
ebd234768dd3ae82d720af577597b128c9be0455de4de81a2bcdf486c82cb36a | metabase/metabase | handler.clj | (ns metabase.server.handler
"Top-level Metabase Ring handler."
(:require
[metabase.config :as config]
[metabase.server.middleware.auth :as mw.auth]
[metabase.server.middleware.browser-cookie :as mw.browser-cookie]
[metabase.server.middleware.exceptions :as mw.exceptions]
[metabase.server.middleware.json :as mw.json]
[metabase.server.middleware.log :as mw.log]
[metabase.server.middleware.misc :as mw.misc]
[metabase.server.middleware.offset-paging :as mw.offset-paging]
[metabase.server.middleware.security :as mw.security]
[metabase.server.middleware.session :as mw.session]
[metabase.server.middleware.ssl :as mw.ssl]
[metabase.server.routes :as routes]
[metabase.util.log :as log]
[ring.core.protocols :as ring.protocols]
[ring.middleware.cookies :refer [wrap-cookies]]
[ring.middleware.gzip :refer [wrap-gzip]]
[ring.middleware.keyword-params :refer [wrap-keyword-params]]
[ring.middleware.params :refer [wrap-params]]))
(extend-protocol ring.protocols/StreamableResponseBody
java.lang . Double , java.lang . Long , and java.lang . Boolean will be given a Content - Type of " application / json ; charset = utf-8 "
;; so they should be strings, and will be parsed into their respective values.
java.lang.Double
(write-body-to-stream [num response output-stream]
(ring.protocols/write-body-to-stream (str num) response output-stream))
java.lang.Long
(write-body-to-stream [num response output-stream]
(ring.protocols/write-body-to-stream (str num) response output-stream))
java.lang.Boolean
(write-body-to-stream [bool response output-stream]
(ring.protocols/write-body-to-stream (str bool) response output-stream))
clojure.lang.Keyword
(write-body-to-stream [kkey response output-stream]
(ring.protocols/write-body-to-stream
(if-let [key-ns (namespace kkey)]
(str key-ns "/" (name kkey))
(name kkey))
response output-stream)))
(def ^:private middleware
;; ▼▼▼ POST-PROCESSING ▼▼▼ happens from TOP-TO-BOTTOM
[#'mw.exceptions/catch-uncaught-exceptions ; catch any Exceptions that weren't passed to `raise`
#'mw.exceptions/catch-api-exceptions ; catch exceptions and return them in our expected format
#'mw.log/log-api-call
#'mw.browser-cookie/ensure-browser-id-cookie ; add cookie to identify browser; add `:browser-id` to the request
#'mw.security/add-security-headers ; Add HTTP headers to API responses to prevent them from being cached
#'mw.json/wrap-json-body ; extracts json POST body and makes it avaliable on request
#'mw.offset-paging/handle-paging ; binds per-request parameters to handle paging
#'mw.json/wrap-streamed-json-response ; middleware to automatically serialize suitable objects as JSON in responses
#'wrap-keyword-params ; converts string keys in :params to keyword keys
#'wrap-params ; parses GET and POST params as :query-params/:form-params and both as :params
#'mw.misc/maybe-set-site-url ; set the value of `site-url` if it hasn't been set yet
#'mw.session/reset-session-timeout ; Resets the timeout cookie for user activity to [[mw.session/session-timeout]]
#'mw.session/bind-current-user ; Binds *current-user* and *current-user-id* if :metabase-user-id is non-nil
#'mw.session/wrap-current-user-info ; looks for :metabase-session-id and sets :metabase-user-id and other info if Session ID is valid
looks for a Metabase Session ID and assoc as : metabase - session - id
looks for a Metabase API Key on the request and assocs as : metabase - api - key
Parses cookies in the request map and assocs as : cookies
Adds a Content - Type header for any response that does n't already have one
#'mw.misc/disable-streaming-buffering ; Add header to streaming (async) responses so ngnix doesn't buffer keepalive bytes
GZIP response if client can handle it
#'mw.misc/bind-request ; bind `metabase.middleware.misc/*request*` for the duration of the request
#'mw.ssl/redirect-to-https-middleware])
;; ▲▲▲ PRE-PROCESSING ▲▲▲ happens from BOTTOM-TO-TOP
(defn- apply-middleware
[handler]
(reduce
(fn [handler middleware-fn]
(middleware-fn handler))
handler
middleware))
(def app
"The primary entry point to the Ring HTTP server."
(apply-middleware routes/routes))
;; during interactive dev, recreate `app` whenever a middleware var or `routes/routes` changes.
(when config/is-dev?
(doseq [varr (cons #'routes/routes middleware)
:when (instance? clojure.lang.IRef varr)]
(add-watch varr ::reload (fn [_ _ _ _]
(log/infof "%s changed, rebuilding %s" varr #'app)
(alter-var-root #'app (constantly (apply-middleware routes/routes)))))))
| null | https://raw.githubusercontent.com/metabase/metabase/dad3d414e5bec482c15d826dcc97772412c98652/src/metabase/server/handler.clj | clojure | so they should be strings, and will be parsed into their respective values.
▼▼▼ POST-PROCESSING ▼▼▼ happens from TOP-TO-BOTTOM
catch any Exceptions that weren't passed to `raise`
catch exceptions and return them in our expected format
add cookie to identify browser; add `:browser-id` to the request
Add HTTP headers to API responses to prevent them from being cached
extracts json POST body and makes it avaliable on request
binds per-request parameters to handle paging
middleware to automatically serialize suitable objects as JSON in responses
converts string keys in :params to keyword keys
parses GET and POST params as :query-params/:form-params and both as :params
set the value of `site-url` if it hasn't been set yet
Resets the timeout cookie for user activity to [[mw.session/session-timeout]]
Binds *current-user* and *current-user-id* if :metabase-user-id is non-nil
looks for :metabase-session-id and sets :metabase-user-id and other info if Session ID is valid
Add header to streaming (async) responses so ngnix doesn't buffer keepalive bytes
bind `metabase.middleware.misc/*request*` for the duration of the request
▲▲▲ PRE-PROCESSING ▲▲▲ happens from BOTTOM-TO-TOP
during interactive dev, recreate `app` whenever a middleware var or `routes/routes` changes. | (ns metabase.server.handler
"Top-level Metabase Ring handler."
(:require
[metabase.config :as config]
[metabase.server.middleware.auth :as mw.auth]
[metabase.server.middleware.browser-cookie :as mw.browser-cookie]
[metabase.server.middleware.exceptions :as mw.exceptions]
[metabase.server.middleware.json :as mw.json]
[metabase.server.middleware.log :as mw.log]
[metabase.server.middleware.misc :as mw.misc]
[metabase.server.middleware.offset-paging :as mw.offset-paging]
[metabase.server.middleware.security :as mw.security]
[metabase.server.middleware.session :as mw.session]
[metabase.server.middleware.ssl :as mw.ssl]
[metabase.server.routes :as routes]
[metabase.util.log :as log]
[ring.core.protocols :as ring.protocols]
[ring.middleware.cookies :refer [wrap-cookies]]
[ring.middleware.gzip :refer [wrap-gzip]]
[ring.middleware.keyword-params :refer [wrap-keyword-params]]
[ring.middleware.params :refer [wrap-params]]))
(extend-protocol ring.protocols/StreamableResponseBody
java.lang . Double , java.lang . Long , and java.lang . Boolean will be given a Content - Type of " application / json ; charset = utf-8 "
java.lang.Double
(write-body-to-stream [num response output-stream]
(ring.protocols/write-body-to-stream (str num) response output-stream))
java.lang.Long
(write-body-to-stream [num response output-stream]
(ring.protocols/write-body-to-stream (str num) response output-stream))
java.lang.Boolean
(write-body-to-stream [bool response output-stream]
(ring.protocols/write-body-to-stream (str bool) response output-stream))
clojure.lang.Keyword
(write-body-to-stream [kkey response output-stream]
(ring.protocols/write-body-to-stream
(if-let [key-ns (namespace kkey)]
(str key-ns "/" (name kkey))
(name kkey))
response output-stream)))
(def ^:private middleware
#'mw.log/log-api-call
looks for a Metabase Session ID and assoc as : metabase - session - id
looks for a Metabase API Key on the request and assocs as : metabase - api - key
Parses cookies in the request map and assocs as : cookies
Adds a Content - Type header for any response that does n't already have one
GZIP response if client can handle it
#'mw.ssl/redirect-to-https-middleware])
(defn- apply-middleware
[handler]
(reduce
(fn [handler middleware-fn]
(middleware-fn handler))
handler
middleware))
(def app
"The primary entry point to the Ring HTTP server."
(apply-middleware routes/routes))
(when config/is-dev?
(doseq [varr (cons #'routes/routes middleware)
:when (instance? clojure.lang.IRef varr)]
(add-watch varr ::reload (fn [_ _ _ _]
(log/infof "%s changed, rebuilding %s" varr #'app)
(alter-var-root #'app (constantly (apply-middleware routes/routes)))))))
|
31129071ea5afe27a639fd4d9f578a4617ec4295d118daf88fbfc88534700aef | google/codeworld | Prelude.hs | {-# LANGUAGE PackageImports #-}
module Prelude (module Core, P.drawingOf, P.circle, foo) where
import Core
import qualified "codeworld-base" Prelude as P
foo = 42
| null | https://raw.githubusercontent.com/google/codeworld/77b0863075be12e3bc5f182a53fcc38b038c3e16/codeworld-compiler/test/testcases/magicImport_prelude/Prelude.hs | haskell | # LANGUAGE PackageImports # |
module Prelude (module Core, P.drawingOf, P.circle, foo) where
import Core
import qualified "codeworld-base" Prelude as P
foo = 42
|
d04a2623b6099953690571fa20afbc3ab2d174de32a048aaf4e2f7123d120071 | bsansouci/bsb-native | selection.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1997 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
(* Instruction selection for the Power PC processor *)
open Cmm
open Arch
open Mach
Recognition of addressing modes
type addressing_expr =
Asymbol of string
| Alinear of expression
| Aadd of expression * expression
let rec select_addr = function
Cconst_symbol s ->
(Asymbol s, 0)
| Cop((Caddi | Cadda), [arg; Cconst_int m]) ->
let (a, n) = select_addr arg in (a, n + m)
| Cop((Caddi | Cadda), [Cconst_int m; arg]) ->
let (a, n) = select_addr arg in (a, n + m)
| Cop((Caddi | Cadda), [arg1; arg2]) ->
begin match (select_addr arg1, select_addr arg2) with
((Alinear e1, n1), (Alinear e2, n2)) ->
(Aadd(e1, e2), n1 + n2)
| _ ->
(Aadd(arg1, arg2), 0)
end
| exp ->
(Alinear exp, 0)
(* Instruction selection *)
class selector = object (self)
inherit Selectgen.selector_generic as super
method is_immediate n = (n <= 32767) && (n >= -32768)
method select_addressing chunk exp =
match select_addr exp with
(Asymbol s, d) ->
(Ibased(s, d), Ctuple [])
| (Alinear e, d) ->
(Iindexed d, e)
| (Aadd(e1, e2), d) ->
if d = 0
then (Iindexed2, Ctuple[e1; e2])
else (Iindexed d, Cop(Cadda, [e1; e2]))
method! select_operation op args =
match (op, args) with
(* PowerPC does not support immediate operands for multiply high *)
(Cmulhi, _) -> (Iintop Imulh, args)
(* The and, or and xor instructions have a different range of immediate
operands than the other instructions *)
| (Cand, _) -> self#select_logical Iand args
| (Cor, _) -> self#select_logical Ior args
| (Cxor, _) -> self#select_logical Ixor args
Recognize mult - add and mult - sub instructions
| (Caddf, [Cop(Cmulf, [arg1; arg2]); arg3]) ->
(Ispecific Imultaddf, [arg1; arg2; arg3])
| (Caddf, [arg3; Cop(Cmulf, [arg1; arg2])]) ->
(Ispecific Imultaddf, [arg1; arg2; arg3])
| (Csubf, [Cop(Cmulf, [arg1; arg2]); arg3]) ->
(Ispecific Imultsubf, [arg1; arg2; arg3])
| _ ->
super#select_operation op args
method select_logical op = function
[arg; Cconst_int n] when n >= 0 && n <= 0xFFFF ->
(Iintop_imm(op, n), [arg])
| [Cconst_int n; arg] when n >= 0 && n <= 0xFFFF ->
(Iintop_imm(op, n), [arg])
| args ->
(Iintop op, args)
end
let fundecl f = (new selector)#emit_fundecl f
| null | https://raw.githubusercontent.com/bsansouci/bsb-native/9a89457783d6e80deb0fba9ca7372c10a768a9ea/vendor/ocaml/asmcomp/power/selection.ml | ocaml | *********************************************************************
OCaml
*********************************************************************
Instruction selection for the Power PC processor
Instruction selection
PowerPC does not support immediate operands for multiply high
The and, or and xor instructions have a different range of immediate
operands than the other instructions | , projet Cristal , INRIA Rocquencourt
Copyright 1997 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
open Cmm
open Arch
open Mach
Recognition of addressing modes
type addressing_expr =
Asymbol of string
| Alinear of expression
| Aadd of expression * expression
let rec select_addr = function
Cconst_symbol s ->
(Asymbol s, 0)
| Cop((Caddi | Cadda), [arg; Cconst_int m]) ->
let (a, n) = select_addr arg in (a, n + m)
| Cop((Caddi | Cadda), [Cconst_int m; arg]) ->
let (a, n) = select_addr arg in (a, n + m)
| Cop((Caddi | Cadda), [arg1; arg2]) ->
begin match (select_addr arg1, select_addr arg2) with
((Alinear e1, n1), (Alinear e2, n2)) ->
(Aadd(e1, e2), n1 + n2)
| _ ->
(Aadd(arg1, arg2), 0)
end
| exp ->
(Alinear exp, 0)
class selector = object (self)
inherit Selectgen.selector_generic as super
method is_immediate n = (n <= 32767) && (n >= -32768)
method select_addressing chunk exp =
match select_addr exp with
(Asymbol s, d) ->
(Ibased(s, d), Ctuple [])
| (Alinear e, d) ->
(Iindexed d, e)
| (Aadd(e1, e2), d) ->
if d = 0
then (Iindexed2, Ctuple[e1; e2])
else (Iindexed d, Cop(Cadda, [e1; e2]))
method! select_operation op args =
match (op, args) with
(Cmulhi, _) -> (Iintop Imulh, args)
| (Cand, _) -> self#select_logical Iand args
| (Cor, _) -> self#select_logical Ior args
| (Cxor, _) -> self#select_logical Ixor args
Recognize mult - add and mult - sub instructions
| (Caddf, [Cop(Cmulf, [arg1; arg2]); arg3]) ->
(Ispecific Imultaddf, [arg1; arg2; arg3])
| (Caddf, [arg3; Cop(Cmulf, [arg1; arg2])]) ->
(Ispecific Imultaddf, [arg1; arg2; arg3])
| (Csubf, [Cop(Cmulf, [arg1; arg2]); arg3]) ->
(Ispecific Imultsubf, [arg1; arg2; arg3])
| _ ->
super#select_operation op args
method select_logical op = function
[arg; Cconst_int n] when n >= 0 && n <= 0xFFFF ->
(Iintop_imm(op, n), [arg])
| [Cconst_int n; arg] when n >= 0 && n <= 0xFFFF ->
(Iintop_imm(op, n), [arg])
| args ->
(Iintop op, args)
end
let fundecl f = (new selector)#emit_fundecl f
|
64da5e15801e7d8891343f538335020c7786f7d4ff1469d748e55846ca2816b4 | clj-easy/graalvm-clojure | main.clj | (ns simple.main
(:require [fastmath.core :as m]
[fastmath.vector :as v]
[fastmath.random :as r]
[fastmath.fields :as f]
[fastmath.kernel :as k]
[fastmath.interpolation :as i]
[fastmath.classification :as cl]
[fastmath.clustering :as clust]
[fastmath.regression :as regr]
[fastmath.signal :as sig]
[fastmath.transform :as trans]
[fastmath.stats :as stats]
[clojure.java.io :as io]
[clojure.data.csv :as csv])
(:gen-class))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn)
(m/use-primitive-operators)
;; fields
(def field (f/field :cpow3 1.0 (f/parametrization :cpow3)))
;; interpolation
(defn interpolator
[]
(i/rbf (k/rbf :multiquadratic) [1 2 3 4] [0.3 0.5 -1 2]))
;; classification
(def iris-data (->> (io/resource "iris.csv")
(io/reader)
(csv/read-csv)
(drop 1)
(map (fn [v]
(let [[x y z w nm] (map read-string v)]
[[x y z w] (keyword (str nm))])))))
(def split
(let [split-point (* 0.7 (count iris-data))
iris-shuffled (shuffle iris-data)
iris-v (map first iris-shuffled)
iris-l (map second iris-shuffled)
[dd dt] (split-at split-point iris-v)
[ld lt] (split-at split-point iris-l)]
{:data dd
:labels ld
:test-data dt
:test-labels lt}))
(def train-data (:data split))
(def train-labels (:labels split))
(def test-data (:test-data split))
(def test-labels (:test-labels split))
(defn ada-boost
[]
(let [cl (cl/ada-boost train-data train-labels)]
(select-keys (cl/validate cl test-data test-labels) [:invalid :stats])))
;; clustering
(defn cluster
[]
(dissoc (clust/dbscan
(repeatedly 10000 (fn* []
(vector (r/randval 0.1 (r/irand -10 10) (r/irand 100 150))
(r/randval (r/irand -10 10) (r/irand 100 150))
(r/randval (r/irand -10 10) (r/irand 100 150)))))
10 20)
:data :clustering :obj :predict))
;; regression
(defn regr
[]
(let [r (regr/random-forest [[1] [2] [3] [4]] [0.3 0.5 -1 2])]
(:stats (regr/validate r [[1] [2] [3] [4]] [0.3 0.5 -1 2]))))
;; signal
(defn signal
[]
(let [lpf (sig/effect :vcf303 {:rate 10000})
sgnal [-1.0 1.0 -0.5 0.5 -0.1 0.1 0 0]]
(sig/apply-effects sgnal lpf)))
;; wavelets
(defn wavelets
[]
(let [t (trans/transformer :fast :symlet-5)]
(seq (trans/reverse-1d t (trans/compress (trans/forward-1d t [1 2 3 4]) 0.3)))))
;; dft
(defn dft
[]
(let [t (trans/transformer :standard :dft)]
(seq (trans/reverse-1d t (trans/forward-1d t [-1 8 7 6])))))
(defn -main []
(println "Hello GraalVM.")
(println "--------------")
(println)
(println "Random field function")
(println " f(x,y)=" (field (v/vec2 (r/grand) (r/grand))))
(println "Interpolate")
(println " interpolate(x,y)=" ((interpolator) 2.5))
(println "Classification")
(println " ada-boost: " (ada-boost))
;; (println "Clustering")
( println " dbscan : " ( cluster ) )
(println "Regression")
(println " random-forest: " (regr))
(println "Signal processing")
(println " vcf303 filter: " (signal))
;; (println "Wavelet compression")
;; (println " symlet-5: " (wavelets))
(println "DFT")
(println " dft: " (dft))
(println "Stats")
(println " " (stats/stats-map (map ffirst iris-data))))
| null | https://raw.githubusercontent.com/clj-easy/graalvm-clojure/5de155ad4f95d5dac97aac1ab3d118400e7d186f/fastmath/src/simple/main.clj | clojure | fields
interpolation
classification
clustering
regression
signal
wavelets
dft
(println "Clustering")
(println "Wavelet compression")
(println " symlet-5: " (wavelets)) | (ns simple.main
(:require [fastmath.core :as m]
[fastmath.vector :as v]
[fastmath.random :as r]
[fastmath.fields :as f]
[fastmath.kernel :as k]
[fastmath.interpolation :as i]
[fastmath.classification :as cl]
[fastmath.clustering :as clust]
[fastmath.regression :as regr]
[fastmath.signal :as sig]
[fastmath.transform :as trans]
[fastmath.stats :as stats]
[clojure.java.io :as io]
[clojure.data.csv :as csv])
(:gen-class))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn)
(m/use-primitive-operators)
(def field (f/field :cpow3 1.0 (f/parametrization :cpow3)))
(defn interpolator
[]
(i/rbf (k/rbf :multiquadratic) [1 2 3 4] [0.3 0.5 -1 2]))
(def iris-data (->> (io/resource "iris.csv")
(io/reader)
(csv/read-csv)
(drop 1)
(map (fn [v]
(let [[x y z w nm] (map read-string v)]
[[x y z w] (keyword (str nm))])))))
(def split
(let [split-point (* 0.7 (count iris-data))
iris-shuffled (shuffle iris-data)
iris-v (map first iris-shuffled)
iris-l (map second iris-shuffled)
[dd dt] (split-at split-point iris-v)
[ld lt] (split-at split-point iris-l)]
{:data dd
:labels ld
:test-data dt
:test-labels lt}))
(def train-data (:data split))
(def train-labels (:labels split))
(def test-data (:test-data split))
(def test-labels (:test-labels split))
(defn ada-boost
[]
(let [cl (cl/ada-boost train-data train-labels)]
(select-keys (cl/validate cl test-data test-labels) [:invalid :stats])))
(defn cluster
[]
(dissoc (clust/dbscan
(repeatedly 10000 (fn* []
(vector (r/randval 0.1 (r/irand -10 10) (r/irand 100 150))
(r/randval (r/irand -10 10) (r/irand 100 150))
(r/randval (r/irand -10 10) (r/irand 100 150)))))
10 20)
:data :clustering :obj :predict))
(defn regr
[]
(let [r (regr/random-forest [[1] [2] [3] [4]] [0.3 0.5 -1 2])]
(:stats (regr/validate r [[1] [2] [3] [4]] [0.3 0.5 -1 2]))))
(defn signal
[]
(let [lpf (sig/effect :vcf303 {:rate 10000})
sgnal [-1.0 1.0 -0.5 0.5 -0.1 0.1 0 0]]
(sig/apply-effects sgnal lpf)))
(defn wavelets
[]
(let [t (trans/transformer :fast :symlet-5)]
(seq (trans/reverse-1d t (trans/compress (trans/forward-1d t [1 2 3 4]) 0.3)))))
(defn dft
[]
(let [t (trans/transformer :standard :dft)]
(seq (trans/reverse-1d t (trans/forward-1d t [-1 8 7 6])))))
(defn -main []
(println "Hello GraalVM.")
(println "--------------")
(println)
(println "Random field function")
(println " f(x,y)=" (field (v/vec2 (r/grand) (r/grand))))
(println "Interpolate")
(println " interpolate(x,y)=" ((interpolator) 2.5))
(println "Classification")
(println " ada-boost: " (ada-boost))
( println " dbscan : " ( cluster ) )
(println "Regression")
(println " random-forest: " (regr))
(println "Signal processing")
(println " vcf303 filter: " (signal))
(println "DFT")
(println " dft: " (dft))
(println "Stats")
(println " " (stats/stats-map (map ffirst iris-data))))
|
33faf121adeb4c2fa38243249d10ff830cfe72546ebc99842894531c0b37ed3f | pixlsus/registry.gimp.org_static | JMS-Sierpinski_carpet.scm |
( c ) 2011 ,
;;
;; 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 </>.
;;
(define (script-fu-SierpinskiCarpet
width ; width of the smallest "hole" in the carpet
height ; height of the smallest "hole" in the carpet
recursions ; Levels used in making the carpet
fgColor ; Color of the "holes"
bgColor ; Background color
alphaYN ; Transparent holes
)
(let* (
(theImage (car (gimp-image-new width height 0)))
(bgLayer (car (gimp-layer-new theImage width height RGBA-IMAGE "Carpet" 100 NORMAL-MODE)))
(flag 0) ; iteration number we are currently on
)
(gimp-context-set-foreground fgColor)
(gimp-context-set-background bgColor)
(gimp-image-add-layer theImage bgLayer 0)
(gimp-drawable-fill bgLayer BACKGROUND-FILL)
(while (> recursions flag)
(set! width (car (gimp-drawable-width bgLayer)))
(set! height (car (gimp-drawable-height bgLayer)))
(plug-in-tile RUN-NONINTERACTIVE theImage bgLayer (* width 3) (* height 3) 0)
(set! bgLayer (car (gimp-image-get-active-layer theImage)))
(gimp-rect-select theImage width height width height CHANNEL-OP-REPLACE 0 0)
(gimp-edit-bucket-fill bgLayer FG-BUCKET-FILL NORMAL-MODE 100 0 FALSE 0 0)
(gimp-selection-none theImage)
(set! flag (+ 1 flag))
)
(if (= alphaYN TRUE)
(plug-in-colortoalpha RUN-NONINTERACTIVE theImage bgLayer fgColor)
)
; Show the new image.
(gimp-display-new theImage)
)
)
(script-fu-register
"script-fu-SierpinskiCarpet"
_"Carpet..."
_"Makes a Sierpinski carpet"
"James Sambrook"
"GNU GPL"
"1 September 2011"
""
SF-ADJUSTMENT _"Initial Block Width" '(1 1 10 1 1 0 0)
SF-ADJUSTMENT _"Initial Block Height" '(1 1 10 1 1 0 0)
SF-ADJUSTMENT _"Number of iterations (final size of image will be width*3^x by height*3^x)" '(6 1 8 1 1 0 0)
SF-COLOR _"Color of the 'holes'" '(255 255 255)
SF-COLOR _"Background Color" '(0 0 0)
SF-TOGGLE _"Transparent holes?" FALSE
)
(script-fu-menu-register "script-fu-SierpinskiCarpet"
"<Image>/Filters/SambrookJM/Sierpinski/") | null | https://raw.githubusercontent.com/pixlsus/registry.gimp.org_static/ffcde7400f402728373ff6579947c6ffe87d1a5e/registry.gimp.org/files/JMS-Sierpinski_carpet.scm | scheme |
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>.
width of the smallest "hole" in the carpet
height of the smallest "hole" in the carpet
Levels used in making the carpet
Color of the "holes"
Background color
Transparent holes
iteration number we are currently on
Show the new image.
|
( c ) 2011 ,
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
(define (script-fu-SierpinskiCarpet
)
(let* (
(theImage (car (gimp-image-new width height 0)))
(bgLayer (car (gimp-layer-new theImage width height RGBA-IMAGE "Carpet" 100 NORMAL-MODE)))
)
(gimp-context-set-foreground fgColor)
(gimp-context-set-background bgColor)
(gimp-image-add-layer theImage bgLayer 0)
(gimp-drawable-fill bgLayer BACKGROUND-FILL)
(while (> recursions flag)
(set! width (car (gimp-drawable-width bgLayer)))
(set! height (car (gimp-drawable-height bgLayer)))
(plug-in-tile RUN-NONINTERACTIVE theImage bgLayer (* width 3) (* height 3) 0)
(set! bgLayer (car (gimp-image-get-active-layer theImage)))
(gimp-rect-select theImage width height width height CHANNEL-OP-REPLACE 0 0)
(gimp-edit-bucket-fill bgLayer FG-BUCKET-FILL NORMAL-MODE 100 0 FALSE 0 0)
(gimp-selection-none theImage)
(set! flag (+ 1 flag))
)
(if (= alphaYN TRUE)
(plug-in-colortoalpha RUN-NONINTERACTIVE theImage bgLayer fgColor)
)
(gimp-display-new theImage)
)
)
(script-fu-register
"script-fu-SierpinskiCarpet"
_"Carpet..."
_"Makes a Sierpinski carpet"
"James Sambrook"
"GNU GPL"
"1 September 2011"
""
SF-ADJUSTMENT _"Initial Block Width" '(1 1 10 1 1 0 0)
SF-ADJUSTMENT _"Initial Block Height" '(1 1 10 1 1 0 0)
SF-ADJUSTMENT _"Number of iterations (final size of image will be width*3^x by height*3^x)" '(6 1 8 1 1 0 0)
SF-COLOR _"Color of the 'holes'" '(255 255 255)
SF-COLOR _"Background Color" '(0 0 0)
SF-TOGGLE _"Transparent holes?" FALSE
)
(script-fu-menu-register "script-fu-SierpinskiCarpet"
"<Image>/Filters/SambrookJM/Sierpinski/") |
b6907bf2470e915d30a404f6de28c3d139c65418ba27af3d0aae7dc881d6d3e8 | dgiot/dgiot | dgiot_task.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(dgiot_task).
-include("dgiot_task.hrl").
-include_lib("dgiot/include/logger.hrl").
-include_lib("dgiot_bridge/include/dgiot_bridge.hrl").
-export([start/1, start/2, send/3, get_pnque_len/1, save_pnque/4, get_pnque/1, del_pnque/1, save_td/4, merge_cache_data/3, save_cache_data/2]).
-export([get_control/3, get_collection/3, get_calculated/2, get_instruct/2, get_storage/2, string2value/2, string2value/3]).
-export([save_td_no_match/4]).
start(ChannelId) ->
lists:map(fun(Y) ->
case Y of
{ClientId, _} ->
dgiot_client:start(ChannelId, ClientId);
_ ->
pass
end
end, ets:tab2list(?DGIOT_PNQUE)).
start(ChannelId, ClientId) ->
dgiot_client:start(ChannelId, ClientId).
send(ProductId, DevAddr, Payload) ->
case dgiot_data:get({?TYPE, ProductId}) of
not_find ->
pass;
ChannelId ->
Topic = <<"$dg/thing/", ProductId/binary, "/", DevAddr/binary, "/properties/report">>,
dgiot_client:send(ChannelId, DevAddr, Topic, Payload)
end.
%%获取计算值,必须返回物模型里面的数据表示,不能用寄存器地址
get_calculated(ProductId, Calculated) ->
case dgiot_product:lookup_prod(ProductId) of
{ok, #{<<"thing">> := #{<<"properties">> := Props}}} ->
lists:foldl(fun(X, Acc) ->
case Acc of
error ->
Acc;
_ ->
case X of
#{<<"isstorage">> := true,
<<"identifier">> := Identifier, <<"dataForm">> := #{
<<"strategy">> := <<"计算值"/utf8>>, <<"collection">> := Collection},
<<"dataType">> := #{<<"type">> := Type, <<"specs">> := Specs}} ->
Str1 = maps:fold(fun(K, V, Acc2) ->
Str = re:replace(Acc2, dgiot_utils:to_list(<<"%%", K/binary>>), "(" ++ dgiot_utils:to_list(V) ++ ")", [global, {return, list}]),
re:replace(Str, "%s", "(" ++ dgiot_utils:to_list(V) ++ ")", [global, {return, list}])
end, dgiot_utils:to_list(Collection), Calculated),
case string2value(Str1, Type, Specs) of
error ->
maps:without([Identifier], Acc);
Value1 ->
Acc#{Identifier => Value1}
end;
_ ->
Acc
end
end
end, Calculated, Props);
_Error ->
Calculated
end.
%% 主动上报 dis为[]
get_collection(ProductId, [], Payload) ->
case dgiot_product:lookup_prod(ProductId) of
{ok, #{<<"thing">> := #{<<"properties">> := Props}}} ->
lists:foldl(fun(X, Acc2) ->
case Acc2 of
error ->
Acc2;
_ ->
case X of
#{<<"dataForm">> := #{<<"strategy">> := Strategy} = DataForm,
<<"dataType">> := DataType,
<<"identifier">> := Identifier} when Strategy =/= <<"计算值"/utf8>> ->
dgiot_task_data:get_userdata(ProductId, Identifier, DataForm, DataType, Payload, Acc2);
_ ->
Acc2
end
end
end, Payload, Props);
_Error ->
Payload
end;
%%转换设备上报值,必须返回物模型里面的数据表示,不能用寄存器地址
get_collection(ProductId, Dis, Payload) ->
case dgiot_product:lookup_prod(ProductId) of
{ok, #{<<"thing">> := #{<<"properties">> := Props}}} ->
lists:foldl(fun(Identifier, Acc1) ->
lists:foldl(fun(X, Acc2) ->
case Acc2 of
error ->
Acc2;
_ ->
case X of
#{<<"dataForm">> := #{<<"strategy">> := Strategy} = DataForm,
<<"dataType">> := DataType,
<<"identifier">> := Identifier} when Strategy =/= <<"计算值"/utf8>> ->
dgiot_task_data:get_userdata(ProductId, Identifier, DataForm, DataType, Payload, Acc2);
_ ->
Acc2
end
end
end, Acc1, Props)
end, Payload, Dis);
_Error ->
Payload
end.
%% 获取控制值
get_control(Round, Data, Control) ->
case Data of
<<"null">> ->
<<"null">>;
Data ->
Str = re:replace(dgiot_utils:to_list(Control), "%d", "(" ++ dgiot_utils:to_list(Data) ++ ")", [global, {return, list}]),
Str1 = re:replace(Str, "%r", "(" ++ dgiot_utils:to_list(Round) ++ ")", [global, {return, list}]),
dgiot_task:string2value(Str1, <<"type">>)
end.
get_storage(ProductId, Calculated) ->
case dgiot_product:lookup_prod(ProductId) of
{ok, #{<<"thing">> := #{<<"properties">> := Props}}} ->
lists:foldl(fun(X, Acc) ->
case Acc of
error ->
Acc;
_ ->
case X of
#{<<"isstorage">> := true, <<"identifier">> := Identifier} ->
case maps:find(Identifier, Calculated) of
{ok, Value} ->
Acc#{Identifier => Value};
_ ->
Acc
end;
_ ->
Acc
end
end
end, #{}, Props);
_Error ->
Calculated
end.
get_instruct(ProductId, Round) ->
case dgiot_product:lookup_prod(ProductId) of
{ok, #{<<"thing">> := #{<<"properties">> := Props}}} when length(Props) > 0 ->
{_, NewList} = lists:foldl(fun(X, Acc) ->
{Seq, List} = Acc,
case X of
#{<<"dataForm">> := #{<<"strategy">> := <<"计算值"/utf8>>}} -> %% 计算值加入采集指令队列
Acc;
#{<<"dataForm">> := #{<<"strategy">> := <<"主动上报"/utf8>>}} -> %% 主动上报值加入采集指令队列
Acc;
#{<<"accessMode">> := AccessMode,
<<"identifier">> := Identifier,
<<"dataType">> := #{<<"specs">> := Specs},
<<"dataForm">> := DataForm,
<<"dataSource">> := DataSource} ->
Min = maps:get(<<"min">>, Specs, 0),
Protocol = maps:get(<<"protocol">>, DataForm, <<"Dlink">>),
控制参数
控制参数的初始值,可以根据轮次进行计算
NewDataSource = dgiot_task_data:get_datasource(Protocol, AccessMode, Data, DataSource), %% 根据协议类型生成采集数据格式
Order = maps:get(<<"order">>, DataForm, Seq), %% 指令顺序
Interval = dgiot_utils:to_int(maps:get(<<"strategy">>, DataForm, 20)), %% 下一个指令的采集间隔
物模型中的指令轮次规则
BinRound = dgiot_utils:to_binary(Round), %% 判断本轮是否需要加入采集指令队列
case ThingRound of
<<"all">> -> %% 所有轮次
{Seq + 1, List ++ [{Order, Interval, Identifier, NewDataSource}]};
BinRound ->
{Seq + 1, List ++ [{Order, Interval, Identifier, NewDataSource}]};
Rounds ->
RoundList = binary:split(Rounds, <<",">>, [global]),
case lists:member(BinRound, RoundList) of
true ->
{Seq + 1, List ++ [{Order, Interval, Identifier, NewDataSource}]};
false ->
Acc
end
end;
_ ->
Acc
end
end, {1, []}, Props),
lists:keysort(1, NewList);
_ ->
[]
end.
string2value(Str, <<"TEXT">>) when is_list(Str) ->
eralng语法中 .
case string:find(Str, "%%") of
nomatch ->
Str;
_ -> error
end;
string2value(Str, _) ->
eralng语法中 .
case string:find(Str, "%%") of
nomatch ->
{ok, Tokens, _} = erl_scan:string(Str ++ "."),
case erl_parse:parse_exprs(Tokens) of
{error, _} ->
error;
{ok, Exprs} ->
Bindings = erl_eval:new_bindings(),
{value, Value, _} = erl_eval:exprs(Exprs, Bindings),
Value
end;
_ -> error
end.
string2value(Str, Type, Specs) ->
Type1 = list_to_binary(string:to_upper(binary_to_list(Type))),
case string2value(Str, Type1) of
error ->
error;
Value ->
case Type1 of
<<"INT">> ->
round(Value);
Type2 when Type2 == <<"FLOAT">>; Type2 == <<"DOUBLE">> ->
Precision = maps:get(<<"precision">>, Specs, 3),
case binary:split(dgiot_utils:to_binary(string:to_lower(dgiot_utils:to_list(Value))), <<$e>>, [global, trim]) of
[Value1, Pow] ->
Valuefloat = dgiot_utils:to_float(Value1),
PowInt = dgiot_utils:to_int(Pow),
dgiot_utils:to_float(Valuefloat * math:pow(10, PowInt), Precision);
[Value2] ->
dgiot_utils:to_float(Value2, Precision)
end;
_ ->
Value
end
end.
save_pnque(DtuProductId, DtuAddr, ProductId, DevAddr) ->
DtuId = dgiot_parse_id:get_deviceid(DtuProductId, DtuAddr),
Topic = <<"$dg/device/", ProductId/binary, "/", DevAddr/binary, "/properties">>,
dgiot_mqtt:subscribe(Topic),
case dgiot_data:get(?DGIOT_PNQUE, DtuId) of
not_find ->
dgiot_data:insert(?DGIOT_PNQUE, DtuId, [{ProductId, DevAddr}]);
Pn_que ->
New_Pn_que = dgiot_utils:unique_2(Pn_que ++ [{ProductId, DevAddr}]),
dgiot_data:insert(?DGIOT_PNQUE, DtuId, New_Pn_que)
end,
case dgiot_data:get({task_args, DtuProductId}) of
not_find ->
pass;
#{<<"channel">> := Channel} = Args ->
io : format("Args ~p.~n " , [ ] ) ,
supervisor:start_child(?TASK_SUP(Channel), [Args#{<<"dtuid">> => DtuId}])
end.
get_pnque_len(DtuId) ->
case dgiot_data:get(?DGIOT_PNQUE, DtuId) of
not_find ->
0;
PnQue ->
length(PnQue)
end.
get_pnque(DtuId) ->
case dgiot_data:get(?DGIOT_PNQUE, DtuId) of
not_find ->
not_find;
PnQue when length(PnQue) > 0 ->
Head = lists:nth(1, PnQue),
dgiot_data:insert(?DGIOT_PNQUE, DtuId, lists:nthtail(1, PnQue) ++ [Head]),
Head;
_ ->
not_find
end.
INSERT INTO _ b8b630322d._4ad9ab0830 using _ b8b630322d._b8b630322d TAGS ( ' _ 862607057395777 ' ) VALUES ( now,638,67,2.1,0.11,0,27,38,0.3,0.0,0.0,11.4,0 ) ;
del_pnque(DtuId) ->
case dgiot_data:get(?DGIOT_PNQUE, DtuId) of
not_find ->
pass;
PnQue when length(PnQue) > 0 ->
dgiot_data:delete(?DGIOT_PNQUE, DtuId);
_ ->
pass
end.
save_td(ProductId, DevAddr, Ack, _AppData) ->
case length(maps:to_list(Ack)) of
0 ->
#{};
_ ->
%% 计算上报值
Collection = dgiot_task:get_collection(ProductId, [], Ack),
%% 计算计算值
Calculated = dgiot_task:get_calculated(ProductId, Collection),
DeviceId = dgiot_parse_id:get_deviceid(ProductId, DevAddr),
case dgiot_product:get_interval(ProductId) of
0 ->
Storage = dgiot_task:get_storage(ProductId, Calculated),
dealwith_data(ProductId, DevAddr, DeviceId, Calculated, Storage);
Interval ->
%% 是否有缓存
AllData = merge_cache_data(DeviceId, Calculated, Interval),
Storage = dgiot_task:get_storage(ProductId, AllData),
Keys = dgiot_product:get_keys(ProductId),
AllStorageKey = maps:keys(Storage),
case Keys -- AllStorageKey of
List when length(List) == 0 andalso length(AllStorageKey) =/= 0 ->
dealwith_data(ProductId, DevAddr, DeviceId, AllData, Storage);
_ ->
save_cache_data(DeviceId, AllData),
AllData
end
end
end.
%% 处理数据
dealwith_data(ProductId, DevAddr, DeviceId, AllData, Storage) ->
%% 告警
NotificationTopic = <<"$dg/user/alarm/", ProductId/binary, "/", DeviceId/binary, "/properties/report">>,
dgiot_mqtt:publish(DeviceId, NotificationTopic, jsx:encode(AllData)),
%% 实时数据
ChannelId = dgiot_parse_id:get_channelid(dgiot_utils:to_binary(?BRIDGE_CHL), <<"DGIOTTOPO">>, <<"TOPO组态通道"/utf8>>),
dgiot_channelx:do_message(ChannelId, {topo_thing, ProductId, DeviceId, AllData}),
%% save td
dgiot_tdengine_adapter:save(ProductId, DevAddr, Storage),
Channel = dgiot_product:get_taskchannel(ProductId),
dgiot_bridge:send_log(Channel, ProductId, DevAddr, "~s ~p save td => ProductId ~p DevAddr ~p ~ts ", [?FILE, ?LINE, ProductId, DevAddr, unicode:characters_to_list(jsx:encode(AllData))]),
dgiot_metrics:inc(dgiot_task, <<"task_save">>, 1),
AllData.
save_cache_data(DeviceId, Data) ->
NewData = maps:fold(fun(K, V, Acc) ->
AtomKey = dgiot_utils:to_atom(K),
Acc#{AtomKey => V}
end, #{}, Data),
dgiot_data:insert(?DGIOT_DATA_CACHE, DeviceId, {NewData, dgiot_datetime:now_secs()}).
merge_cache_data(DeviceId, NewData, Interval) ->
case dgiot_data:get(dgiot_data_cache, DeviceId) of
not_find ->
NewData;
{OldData, Ts} ->
case dgiot_datetime:now_secs() - Ts < Interval of
true ->
NewOldData =
maps:fold(fun(K, V, Acc) ->
Key = dgiot_utils:to_binary(K),
Acc#{Key => V}
end, #{}, OldData),
dgiot_map:merge(NewOldData, NewData);
false ->
save_cache_data(DeviceId, NewData),
NewData
end
end.
save_td_no_match(ProductId, DevAddr, Ack, AppData) ->
case length(maps:to_list(Ack)) of
0 ->
#{};
_ ->
%% 计算上报值
Collection = dgiot_task:get_collection(ProductId, [], Ack),
%% 计算计算值
Calculated = dgiot_task:get_calculated(ProductId, Collection),
Storage = dgiot_task:get_storage(ProductId, Calculated),
DeviceId = dgiot_parse_id:get_deviceid(ProductId, DevAddr),
Interval = maps:get(<<"interval">>, AppData, 3),
AllData = merge_cache_data(DeviceId, Storage, Interval),
ChannelId = dgiot_parse_id:get_channelid(dgiot_utils:to_binary(?BRIDGE_CHL), <<"DGIOTTOPO">>, <<"TOPO组态通道"/utf8>>),
dgiot_channelx:do_message(ChannelId, {topo_thing, ProductId, DeviceId, AllData}),
dgiot_tdengine_adapter:save(ProductId, DevAddr, AllData),
Channel = dgiot_product:get_taskchannel(ProductId),
dgiot_bridge:send_log(Channel, ProductId, DevAddr, "~s ~p save td => ProductId ~p DevAddr ~p ~ts ", [?FILE, ?LINE, ProductId, DevAddr, unicode:characters_to_list(jsx:encode(AllData))]),
dgiot_metrics:inc(dgiot_task, <<"task_save">>, 1),
NotificationTopic = <<"$dg/user/alarm/", ProductId/binary, "/", DeviceId/binary, "/properties/report">>,
dgiot_mqtt:publish(DeviceId, NotificationTopic, jsx:encode(AllData)),
AllData
end.
| null | https://raw.githubusercontent.com/dgiot/dgiot/a6b816a094b1c9bd024ce40b8142375a0f0289d8/apps/dgiot_task/src/dgiot_task.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------
获取计算值,必须返回物模型里面的数据表示,不能用寄存器地址
主动上报 dis为[]
转换设备上报值,必须返回物模型里面的数据表示,不能用寄存器地址
获取控制值
计算值加入采集指令队列
主动上报值加入采集指令队列
根据协议类型生成采集数据格式
指令顺序
下一个指令的采集间隔
判断本轮是否需要加入采集指令队列
所有轮次
计算上报值
计算计算值
是否有缓存
处理数据
告警
实时数据
save td
计算上报值
计算计算值 | Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. 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(dgiot_task).
-include("dgiot_task.hrl").
-include_lib("dgiot/include/logger.hrl").
-include_lib("dgiot_bridge/include/dgiot_bridge.hrl").
-export([start/1, start/2, send/3, get_pnque_len/1, save_pnque/4, get_pnque/1, del_pnque/1, save_td/4, merge_cache_data/3, save_cache_data/2]).
-export([get_control/3, get_collection/3, get_calculated/2, get_instruct/2, get_storage/2, string2value/2, string2value/3]).
-export([save_td_no_match/4]).
start(ChannelId) ->
lists:map(fun(Y) ->
case Y of
{ClientId, _} ->
dgiot_client:start(ChannelId, ClientId);
_ ->
pass
end
end, ets:tab2list(?DGIOT_PNQUE)).
start(ChannelId, ClientId) ->
dgiot_client:start(ChannelId, ClientId).
send(ProductId, DevAddr, Payload) ->
case dgiot_data:get({?TYPE, ProductId}) of
not_find ->
pass;
ChannelId ->
Topic = <<"$dg/thing/", ProductId/binary, "/", DevAddr/binary, "/properties/report">>,
dgiot_client:send(ChannelId, DevAddr, Topic, Payload)
end.
get_calculated(ProductId, Calculated) ->
case dgiot_product:lookup_prod(ProductId) of
{ok, #{<<"thing">> := #{<<"properties">> := Props}}} ->
lists:foldl(fun(X, Acc) ->
case Acc of
error ->
Acc;
_ ->
case X of
#{<<"isstorage">> := true,
<<"identifier">> := Identifier, <<"dataForm">> := #{
<<"strategy">> := <<"计算值"/utf8>>, <<"collection">> := Collection},
<<"dataType">> := #{<<"type">> := Type, <<"specs">> := Specs}} ->
Str1 = maps:fold(fun(K, V, Acc2) ->
Str = re:replace(Acc2, dgiot_utils:to_list(<<"%%", K/binary>>), "(" ++ dgiot_utils:to_list(V) ++ ")", [global, {return, list}]),
re:replace(Str, "%s", "(" ++ dgiot_utils:to_list(V) ++ ")", [global, {return, list}])
end, dgiot_utils:to_list(Collection), Calculated),
case string2value(Str1, Type, Specs) of
error ->
maps:without([Identifier], Acc);
Value1 ->
Acc#{Identifier => Value1}
end;
_ ->
Acc
end
end
end, Calculated, Props);
_Error ->
Calculated
end.
get_collection(ProductId, [], Payload) ->
case dgiot_product:lookup_prod(ProductId) of
{ok, #{<<"thing">> := #{<<"properties">> := Props}}} ->
lists:foldl(fun(X, Acc2) ->
case Acc2 of
error ->
Acc2;
_ ->
case X of
#{<<"dataForm">> := #{<<"strategy">> := Strategy} = DataForm,
<<"dataType">> := DataType,
<<"identifier">> := Identifier} when Strategy =/= <<"计算值"/utf8>> ->
dgiot_task_data:get_userdata(ProductId, Identifier, DataForm, DataType, Payload, Acc2);
_ ->
Acc2
end
end
end, Payload, Props);
_Error ->
Payload
end;
get_collection(ProductId, Dis, Payload) ->
case dgiot_product:lookup_prod(ProductId) of
{ok, #{<<"thing">> := #{<<"properties">> := Props}}} ->
lists:foldl(fun(Identifier, Acc1) ->
lists:foldl(fun(X, Acc2) ->
case Acc2 of
error ->
Acc2;
_ ->
case X of
#{<<"dataForm">> := #{<<"strategy">> := Strategy} = DataForm,
<<"dataType">> := DataType,
<<"identifier">> := Identifier} when Strategy =/= <<"计算值"/utf8>> ->
dgiot_task_data:get_userdata(ProductId, Identifier, DataForm, DataType, Payload, Acc2);
_ ->
Acc2
end
end
end, Acc1, Props)
end, Payload, Dis);
_Error ->
Payload
end.
get_control(Round, Data, Control) ->
case Data of
<<"null">> ->
<<"null">>;
Data ->
Str = re:replace(dgiot_utils:to_list(Control), "%d", "(" ++ dgiot_utils:to_list(Data) ++ ")", [global, {return, list}]),
Str1 = re:replace(Str, "%r", "(" ++ dgiot_utils:to_list(Round) ++ ")", [global, {return, list}]),
dgiot_task:string2value(Str1, <<"type">>)
end.
get_storage(ProductId, Calculated) ->
case dgiot_product:lookup_prod(ProductId) of
{ok, #{<<"thing">> := #{<<"properties">> := Props}}} ->
lists:foldl(fun(X, Acc) ->
case Acc of
error ->
Acc;
_ ->
case X of
#{<<"isstorage">> := true, <<"identifier">> := Identifier} ->
case maps:find(Identifier, Calculated) of
{ok, Value} ->
Acc#{Identifier => Value};
_ ->
Acc
end;
_ ->
Acc
end
end
end, #{}, Props);
_Error ->
Calculated
end.
get_instruct(ProductId, Round) ->
case dgiot_product:lookup_prod(ProductId) of
{ok, #{<<"thing">> := #{<<"properties">> := Props}}} when length(Props) > 0 ->
{_, NewList} = lists:foldl(fun(X, Acc) ->
{Seq, List} = Acc,
case X of
Acc;
Acc;
#{<<"accessMode">> := AccessMode,
<<"identifier">> := Identifier,
<<"dataType">> := #{<<"specs">> := Specs},
<<"dataForm">> := DataForm,
<<"dataSource">> := DataSource} ->
Min = maps:get(<<"min">>, Specs, 0),
Protocol = maps:get(<<"protocol">>, DataForm, <<"Dlink">>),
控制参数
控制参数的初始值,可以根据轮次进行计算
物模型中的指令轮次规则
case ThingRound of
{Seq + 1, List ++ [{Order, Interval, Identifier, NewDataSource}]};
BinRound ->
{Seq + 1, List ++ [{Order, Interval, Identifier, NewDataSource}]};
Rounds ->
RoundList = binary:split(Rounds, <<",">>, [global]),
case lists:member(BinRound, RoundList) of
true ->
{Seq + 1, List ++ [{Order, Interval, Identifier, NewDataSource}]};
false ->
Acc
end
end;
_ ->
Acc
end
end, {1, []}, Props),
lists:keysort(1, NewList);
_ ->
[]
end.
string2value(Str, <<"TEXT">>) when is_list(Str) ->
eralng语法中 .
case string:find(Str, "%%") of
nomatch ->
Str;
_ -> error
end;
string2value(Str, _) ->
eralng语法中 .
case string:find(Str, "%%") of
nomatch ->
{ok, Tokens, _} = erl_scan:string(Str ++ "."),
case erl_parse:parse_exprs(Tokens) of
{error, _} ->
error;
{ok, Exprs} ->
Bindings = erl_eval:new_bindings(),
{value, Value, _} = erl_eval:exprs(Exprs, Bindings),
Value
end;
_ -> error
end.
string2value(Str, Type, Specs) ->
Type1 = list_to_binary(string:to_upper(binary_to_list(Type))),
case string2value(Str, Type1) of
error ->
error;
Value ->
case Type1 of
<<"INT">> ->
round(Value);
Type2 when Type2 == <<"FLOAT">>; Type2 == <<"DOUBLE">> ->
Precision = maps:get(<<"precision">>, Specs, 3),
case binary:split(dgiot_utils:to_binary(string:to_lower(dgiot_utils:to_list(Value))), <<$e>>, [global, trim]) of
[Value1, Pow] ->
Valuefloat = dgiot_utils:to_float(Value1),
PowInt = dgiot_utils:to_int(Pow),
dgiot_utils:to_float(Valuefloat * math:pow(10, PowInt), Precision);
[Value2] ->
dgiot_utils:to_float(Value2, Precision)
end;
_ ->
Value
end
end.
save_pnque(DtuProductId, DtuAddr, ProductId, DevAddr) ->
DtuId = dgiot_parse_id:get_deviceid(DtuProductId, DtuAddr),
Topic = <<"$dg/device/", ProductId/binary, "/", DevAddr/binary, "/properties">>,
dgiot_mqtt:subscribe(Topic),
case dgiot_data:get(?DGIOT_PNQUE, DtuId) of
not_find ->
dgiot_data:insert(?DGIOT_PNQUE, DtuId, [{ProductId, DevAddr}]);
Pn_que ->
New_Pn_que = dgiot_utils:unique_2(Pn_que ++ [{ProductId, DevAddr}]),
dgiot_data:insert(?DGIOT_PNQUE, DtuId, New_Pn_que)
end,
case dgiot_data:get({task_args, DtuProductId}) of
not_find ->
pass;
#{<<"channel">> := Channel} = Args ->
io : format("Args ~p.~n " , [ ] ) ,
supervisor:start_child(?TASK_SUP(Channel), [Args#{<<"dtuid">> => DtuId}])
end.
get_pnque_len(DtuId) ->
case dgiot_data:get(?DGIOT_PNQUE, DtuId) of
not_find ->
0;
PnQue ->
length(PnQue)
end.
get_pnque(DtuId) ->
case dgiot_data:get(?DGIOT_PNQUE, DtuId) of
not_find ->
not_find;
PnQue when length(PnQue) > 0 ->
Head = lists:nth(1, PnQue),
dgiot_data:insert(?DGIOT_PNQUE, DtuId, lists:nthtail(1, PnQue) ++ [Head]),
Head;
_ ->
not_find
end.
INSERT INTO _ b8b630322d._4ad9ab0830 using _ b8b630322d._b8b630322d TAGS ( ' _ 862607057395777 ' ) VALUES ( now,638,67,2.1,0.11,0,27,38,0.3,0.0,0.0,11.4,0 ) ;
del_pnque(DtuId) ->
case dgiot_data:get(?DGIOT_PNQUE, DtuId) of
not_find ->
pass;
PnQue when length(PnQue) > 0 ->
dgiot_data:delete(?DGIOT_PNQUE, DtuId);
_ ->
pass
end.
save_td(ProductId, DevAddr, Ack, _AppData) ->
case length(maps:to_list(Ack)) of
0 ->
#{};
_ ->
Collection = dgiot_task:get_collection(ProductId, [], Ack),
Calculated = dgiot_task:get_calculated(ProductId, Collection),
DeviceId = dgiot_parse_id:get_deviceid(ProductId, DevAddr),
case dgiot_product:get_interval(ProductId) of
0 ->
Storage = dgiot_task:get_storage(ProductId, Calculated),
dealwith_data(ProductId, DevAddr, DeviceId, Calculated, Storage);
Interval ->
AllData = merge_cache_data(DeviceId, Calculated, Interval),
Storage = dgiot_task:get_storage(ProductId, AllData),
Keys = dgiot_product:get_keys(ProductId),
AllStorageKey = maps:keys(Storage),
case Keys -- AllStorageKey of
List when length(List) == 0 andalso length(AllStorageKey) =/= 0 ->
dealwith_data(ProductId, DevAddr, DeviceId, AllData, Storage);
_ ->
save_cache_data(DeviceId, AllData),
AllData
end
end
end.
dealwith_data(ProductId, DevAddr, DeviceId, AllData, Storage) ->
NotificationTopic = <<"$dg/user/alarm/", ProductId/binary, "/", DeviceId/binary, "/properties/report">>,
dgiot_mqtt:publish(DeviceId, NotificationTopic, jsx:encode(AllData)),
ChannelId = dgiot_parse_id:get_channelid(dgiot_utils:to_binary(?BRIDGE_CHL), <<"DGIOTTOPO">>, <<"TOPO组态通道"/utf8>>),
dgiot_channelx:do_message(ChannelId, {topo_thing, ProductId, DeviceId, AllData}),
dgiot_tdengine_adapter:save(ProductId, DevAddr, Storage),
Channel = dgiot_product:get_taskchannel(ProductId),
dgiot_bridge:send_log(Channel, ProductId, DevAddr, "~s ~p save td => ProductId ~p DevAddr ~p ~ts ", [?FILE, ?LINE, ProductId, DevAddr, unicode:characters_to_list(jsx:encode(AllData))]),
dgiot_metrics:inc(dgiot_task, <<"task_save">>, 1),
AllData.
save_cache_data(DeviceId, Data) ->
NewData = maps:fold(fun(K, V, Acc) ->
AtomKey = dgiot_utils:to_atom(K),
Acc#{AtomKey => V}
end, #{}, Data),
dgiot_data:insert(?DGIOT_DATA_CACHE, DeviceId, {NewData, dgiot_datetime:now_secs()}).
merge_cache_data(DeviceId, NewData, Interval) ->
case dgiot_data:get(dgiot_data_cache, DeviceId) of
not_find ->
NewData;
{OldData, Ts} ->
case dgiot_datetime:now_secs() - Ts < Interval of
true ->
NewOldData =
maps:fold(fun(K, V, Acc) ->
Key = dgiot_utils:to_binary(K),
Acc#{Key => V}
end, #{}, OldData),
dgiot_map:merge(NewOldData, NewData);
false ->
save_cache_data(DeviceId, NewData),
NewData
end
end.
save_td_no_match(ProductId, DevAddr, Ack, AppData) ->
case length(maps:to_list(Ack)) of
0 ->
#{};
_ ->
Collection = dgiot_task:get_collection(ProductId, [], Ack),
Calculated = dgiot_task:get_calculated(ProductId, Collection),
Storage = dgiot_task:get_storage(ProductId, Calculated),
DeviceId = dgiot_parse_id:get_deviceid(ProductId, DevAddr),
Interval = maps:get(<<"interval">>, AppData, 3),
AllData = merge_cache_data(DeviceId, Storage, Interval),
ChannelId = dgiot_parse_id:get_channelid(dgiot_utils:to_binary(?BRIDGE_CHL), <<"DGIOTTOPO">>, <<"TOPO组态通道"/utf8>>),
dgiot_channelx:do_message(ChannelId, {topo_thing, ProductId, DeviceId, AllData}),
dgiot_tdengine_adapter:save(ProductId, DevAddr, AllData),
Channel = dgiot_product:get_taskchannel(ProductId),
dgiot_bridge:send_log(Channel, ProductId, DevAddr, "~s ~p save td => ProductId ~p DevAddr ~p ~ts ", [?FILE, ?LINE, ProductId, DevAddr, unicode:characters_to_list(jsx:encode(AllData))]),
dgiot_metrics:inc(dgiot_task, <<"task_save">>, 1),
NotificationTopic = <<"$dg/user/alarm/", ProductId/binary, "/", DeviceId/binary, "/properties/report">>,
dgiot_mqtt:publish(DeviceId, NotificationTopic, jsx:encode(AllData)),
AllData
end.
|
6089596a786b9eafaba6a4224fb867c4f3b57ed9ec59cce0dff4012b8abf805f | duncanatt/detecter | cow_base64url.erl | Copyright ( c ) 2017 - 2018 , < >
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% This module implements "base64url" following the algorithm
%% found in Appendix C of RFC7515. The option #{padding => false}
%% must be given to reproduce this variant exactly. The default
%% will leave the padding characters.
-module(cow_base64url).
-export([decode/1]).
-export([decode/2]).
-export([encode/1]).
-export([encode/2]).
%%-ifdef(TEST).
%%-include_lib("proper/include/proper.hrl").
%%-endif.
decode(Enc) ->
decode(Enc, #{}).
decode(Enc0, Opts) ->
Enc1 = << << case C of
$- -> $+;
$_ -> $/;
_ -> C
end >> || << C >> <= Enc0 >>,
Enc = case Opts of
#{padding := false} ->
case byte_size(Enc1) rem 4 of
0 -> Enc1;
2 -> << Enc1/binary, "==" >>;
3 -> << Enc1/binary, "=" >>
end;
_ ->
Enc1
end,
base64:decode(Enc).
encode(Dec) ->
encode(Dec, #{}).
encode(Dec, Opts) ->
encode(base64:encode(Dec), Opts, <<>>).
encode(<<$+, R/bits>>, Opts, Acc) -> encode(R, Opts, <<Acc/binary, $->>);
encode(<<$/, R/bits>>, Opts, Acc) -> encode(R, Opts, <<Acc/binary, $_>>);
encode(<<$=, _/bits>>, #{padding := false}, Acc) -> Acc;
encode(<<C, R/bits>>, Opts, Acc) -> encode(R, Opts, <<Acc/binary, C>>);
encode(<<>>, _, Acc) -> Acc.
%%-ifdef(TEST).
%%
%%rfc7515_test() ->
%% Dec = <<3,236,255,224,193>>,
%% Enc = <<"A-z_4ME">>,
Pad = < < " A - z_4ME= " > > ,
Dec = decode(<<Enc / binary,$= > > ) ,
%% Dec = decode(Enc, #{padding => false}),
%% Pad = encode(Dec),
%% Enc = encode(Dec, #{padding => false}),
%% ok.
%%
%%prop_identity() ->
? FORALL(B , binary ( ) , B = : ) ) ) .
%%
%%prop_identity_no_padding() ->
? FORALL(B , binary ( ) , B = : , # { padding = > false } ) , # { padding = > false } ) ) .
%%
%%-endif.
| null | https://raw.githubusercontent.com/duncanatt/detecter/95b6a758ce6c60f3b7377c07607f24d126cbdacf/experiments/coordination_2022/src/cowlib/cow_base64url.erl | erlang |
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
This module implements "base64url" following the algorithm
found in Appendix C of RFC7515. The option #{padding => false}
must be given to reproduce this variant exactly. The default
will leave the padding characters.
-ifdef(TEST).
-include_lib("proper/include/proper.hrl").
-endif.
-ifdef(TEST).
rfc7515_test() ->
Dec = <<3,236,255,224,193>>,
Enc = <<"A-z_4ME">>,
Dec = decode(Enc, #{padding => false}),
Pad = encode(Dec),
Enc = encode(Dec, #{padding => false}),
ok.
prop_identity() ->
prop_identity_no_padding() ->
-endif. | Copyright ( c ) 2017 - 2018 , < >
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
-module(cow_base64url).
-export([decode/1]).
-export([decode/2]).
-export([encode/1]).
-export([encode/2]).
decode(Enc) ->
decode(Enc, #{}).
decode(Enc0, Opts) ->
Enc1 = << << case C of
$- -> $+;
$_ -> $/;
_ -> C
end >> || << C >> <= Enc0 >>,
Enc = case Opts of
#{padding := false} ->
case byte_size(Enc1) rem 4 of
0 -> Enc1;
2 -> << Enc1/binary, "==" >>;
3 -> << Enc1/binary, "=" >>
end;
_ ->
Enc1
end,
base64:decode(Enc).
encode(Dec) ->
encode(Dec, #{}).
encode(Dec, Opts) ->
encode(base64:encode(Dec), Opts, <<>>).
encode(<<$+, R/bits>>, Opts, Acc) -> encode(R, Opts, <<Acc/binary, $->>);
encode(<<$/, R/bits>>, Opts, Acc) -> encode(R, Opts, <<Acc/binary, $_>>);
encode(<<$=, _/bits>>, #{padding := false}, Acc) -> Acc;
encode(<<C, R/bits>>, Opts, Acc) -> encode(R, Opts, <<Acc/binary, C>>);
encode(<<>>, _, Acc) -> Acc.
Pad = < < " A - z_4ME= " > > ,
Dec = decode(<<Enc / binary,$= > > ) ,
? FORALL(B , binary ( ) , B = : ) ) ) .
? FORALL(B , binary ( ) , B = : , # { padding = > false } ) , # { padding = > false } ) ) .
|
375a6a3e9c2a04f404b5726d0a7324ca41391737f48d149f6a8a1806a632498b | spurious/sagittarius-scheme-mirror | %3a31.scm | (import (rnrs)
(srfi :31 rec)
(srfi :64 testing))
(test-begin "SRFI-31 tests")
(define F (rec (F N)
((rec (G K L)
(if (zero? K) L
(G (- K 1) (* K L)))) N 1)))
(test-assert (procedure? F))
(test-equal 1 (F 0))
( test - equal 3628800 ( F 10 ) )
(test-end)
| null | https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/test/tests/srfi/%253a31.scm | scheme | (import (rnrs)
(srfi :31 rec)
(srfi :64 testing))
(test-begin "SRFI-31 tests")
(define F (rec (F N)
((rec (G K L)
(if (zero? K) L
(G (- K 1) (* K L)))) N 1)))
(test-assert (procedure? F))
(test-equal 1 (F 0))
( test - equal 3628800 ( F 10 ) )
(test-end)
| |
90c35b0d82fb453540e2fda35366ad0cc71cf548ab97358dece80c1b9b497923 | bmeurer/ocaml-arm | opttopdirs.mli | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ Id$
(* The toplevel directives. *)
open Format
val dir_quit : unit -> unit
val dir_directory : string -> unit
val dir_cd : string -> unit
val dir_load : formatter -> string -> unit
val dir_use : formatter -> string -> unit
val dir_install_printer : formatter -> Longident.t -> unit
val dir_remove_printer : formatter -> Longident.t -> unit
type 'a printer_type_new = Format.formatter -> 'a -> unit
type 'a printer_type_old = 'a -> unit
(* For topmain.ml. Maybe shouldn't be there *)
val load_file : formatter -> string -> bool
| null | https://raw.githubusercontent.com/bmeurer/ocaml-arm/43f7689c76a349febe3d06ae7a4fc1d52984fd8b/toplevel/opttopdirs.mli | ocaml | *********************************************************************
OCaml
*********************************************************************
The toplevel directives.
For topmain.ml. Maybe shouldn't be there | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ Id$
open Format
val dir_quit : unit -> unit
val dir_directory : string -> unit
val dir_cd : string -> unit
val dir_load : formatter -> string -> unit
val dir_use : formatter -> string -> unit
val dir_install_printer : formatter -> Longident.t -> unit
val dir_remove_printer : formatter -> Longident.t -> unit
type 'a printer_type_new = Format.formatter -> 'a -> unit
type 'a printer_type_old = 'a -> unit
val load_file : formatter -> string -> bool
|
de12b3f10052765dc30e98dd99fc045cdc7076e8555303289909a2a7eda7a2d4 | samee/netlist | StableMarriage-old.hs | module Test.StableMarriage where
import Data.List
import Data.Array
import Debug.Trace
import System.Random
import Circuit.Interpreted.StableMarriage
import Util
randomTest :: RandomGen r => Int -> r -> (Bool,r)
randomTest n rgen = (checkStability,rgen3) where
(_,orderM) = mapAccumL (\rgen _ -> swap $ randomlist rgen) rgen1 [1..n]
(_,orderF) = mapAccumL (\rgen _ -> swap $ randomlist rgen) rgen2 [1..n]
[rgen1,rgen2,rgen3] = randSplit 3 rgen
rankM = arraymat $ map inversePermute orderM
rankF = arraymat $ map inversePermute orderF
marriage = traceShow ("OrderM",orderM) $ traceShow ("OrderF",orderF) $ stableMarriage orderM orderF
curRankF = arrayfy [rankF!f!match | (f,match) <- zip [0..n-1] marriage]
curRankM = arrayfy [rankM!m!match | (m,match) <- zip [0..n-1]
$ inversePermute marriage]
checkStability = and [ curRankM!m <= rankM!m!f || curRankF!f <= rankF!f!m
| m <- [0..n-1], f <- [0..n-1]]
randomlist rgen = randomPermute [0..n-1] rgen
arrayfy l = listArray (0,n-1) l
arraymat mat = arrayfy (map arrayfy mat)
swap (a,b) = (b,a)
$ randomTest 10
let res = fst $ randomTest 10 $ mkStdGen 1
putStrLn $ show $ res
| null | https://raw.githubusercontent.com/samee/netlist/9fc20829f29724dc1148e54bd64fefd7e70af5ba/Test/StableMarriage-old.hs | haskell | module Test.StableMarriage where
import Data.List
import Data.Array
import Debug.Trace
import System.Random
import Circuit.Interpreted.StableMarriage
import Util
randomTest :: RandomGen r => Int -> r -> (Bool,r)
randomTest n rgen = (checkStability,rgen3) where
(_,orderM) = mapAccumL (\rgen _ -> swap $ randomlist rgen) rgen1 [1..n]
(_,orderF) = mapAccumL (\rgen _ -> swap $ randomlist rgen) rgen2 [1..n]
[rgen1,rgen2,rgen3] = randSplit 3 rgen
rankM = arraymat $ map inversePermute orderM
rankF = arraymat $ map inversePermute orderF
marriage = traceShow ("OrderM",orderM) $ traceShow ("OrderF",orderF) $ stableMarriage orderM orderF
curRankF = arrayfy [rankF!f!match | (f,match) <- zip [0..n-1] marriage]
curRankM = arrayfy [rankM!m!match | (m,match) <- zip [0..n-1]
$ inversePermute marriage]
checkStability = and [ curRankM!m <= rankM!m!f || curRankF!f <= rankF!f!m
| m <- [0..n-1], f <- [0..n-1]]
randomlist rgen = randomPermute [0..n-1] rgen
arrayfy l = listArray (0,n-1) l
arraymat mat = arrayfy (map arrayfy mat)
swap (a,b) = (b,a)
$ randomTest 10
let res = fst $ randomTest 10 $ mkStdGen 1
putStrLn $ show $ res
| |
af9acce0f1c238acd1b05b970ff8e54f9dbade7ff2956b421ceb5d61d01ef0e3 | hspec/hspec | Pretty.hs | # LANGUAGE CPP #
{-# LANGUAGE OverloadedStrings #-}
module Test.Hspec.Core.Formatters.Pretty (
pretty2
#ifdef TEST
, pretty
, recoverString
, recoverMultiLineString
#endif
) where
import Prelude ()
import Test.Hspec.Core.Compat hiding (shows, intercalate)
import Data.Char
import Data.String
import Data.List (intersperse)
import qualified Text.Show as Show
import Test.Hspec.Core.Formatters.Pretty.Unicode
import Test.Hspec.Core.Formatters.Pretty.Parser
pretty2 :: Bool -> String -> String -> (String, String)
pretty2 unicode expected actual = case (recoverMultiLineString unicode expected, recoverMultiLineString unicode actual) of
(Just expected_, Just actual_) -> (expected_, actual_)
_ -> case (pretty unicode expected, pretty unicode actual) of
(Just expected_, Just actual_) | expected_ /= actual_ -> (expected_, actual_)
_ -> (expected, actual)
recoverString :: String -> Maybe String
recoverString xs = case xs of
'"' : _ -> case reverse xs of
'"' : _ -> readMaybe xs
_ -> Nothing
_ -> Nothing
recoverMultiLineString :: Bool -> String -> Maybe String
recoverMultiLineString unicode input = case recoverString input of
Just r | shouldParseBack r -> Just r
_ -> Nothing
where
shouldParseBack = (&&) <$> all isSafe <*> isMultiLine
isMultiLine = lines >>> length >>> (> 1)
isSafe c = (unicode || isAscii c) && not (isControl c) || c == '\n'
pretty :: Bool -> String -> Maybe String
pretty unicode = parseValue >=> render_
where
render_ :: Value -> Maybe String
render_ value = guard (shouldParseBack value) >> Just (renderValue unicode value)
shouldParseBack :: Value -> Bool
shouldParseBack = go
where
go value = case value of
Char _ -> False
String _ -> True
Rational _ _ -> False
Number _ -> False
Record _ _ -> True
Constructor _ xs -> any go xs
Tuple xs -> any go xs
List xs -> any go xs
newtype Builder = Builder ShowS
instance Monoid Builder where
mempty = Builder id
#if MIN_VERSION_base(4,11,0)
instance Semigroup Builder where
#endif
Builder xs
#if MIN_VERSION_base(4,11,0)
<>
#else
`mappend`
#endif
Builder ys = Builder (xs . ys)
runBuilder :: Builder -> String
runBuilder (Builder xs) = xs ""
intercalate :: Builder -> [Builder] -> Builder
intercalate x xs = mconcat $ intersperse x xs
shows :: Show a => a -> Builder
shows = Builder . Show.shows
instance IsString Builder where
fromString = Builder . showString
renderValue :: Bool -> Value -> String
renderValue unicode = runBuilder . render
where
render :: Value -> Builder
render value = case value of
Char c -> shows c
String str -> if unicode then Builder $ ushows str else shows str
Rational n d -> render n <> " % " <> render d
Number n -> fromString n
Record name fields -> fromString name <> " {\n " <> (intercalate ",\n " $ map renderField fields) <> "\n}"
Constructor name values -> intercalate " " (fromString name : map render values)
Tuple [e@Record{}] -> render e
Tuple xs -> "(" <> intercalate ", " (map render xs) <> ")"
List xs -> "[" <> intercalate ", " (map render xs) <> "]"
renderField (name, value) = fromString name <> " = " <> render value
| null | https://raw.githubusercontent.com/hspec/hspec/a4441abd20039638826b3574216bf945bd2b6d76/hspec-core/src/Test/Hspec/Core/Formatters/Pretty.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE CPP #
module Test.Hspec.Core.Formatters.Pretty (
pretty2
#ifdef TEST
, pretty
, recoverString
, recoverMultiLineString
#endif
) where
import Prelude ()
import Test.Hspec.Core.Compat hiding (shows, intercalate)
import Data.Char
import Data.String
import Data.List (intersperse)
import qualified Text.Show as Show
import Test.Hspec.Core.Formatters.Pretty.Unicode
import Test.Hspec.Core.Formatters.Pretty.Parser
pretty2 :: Bool -> String -> String -> (String, String)
pretty2 unicode expected actual = case (recoverMultiLineString unicode expected, recoverMultiLineString unicode actual) of
(Just expected_, Just actual_) -> (expected_, actual_)
_ -> case (pretty unicode expected, pretty unicode actual) of
(Just expected_, Just actual_) | expected_ /= actual_ -> (expected_, actual_)
_ -> (expected, actual)
recoverString :: String -> Maybe String
recoverString xs = case xs of
'"' : _ -> case reverse xs of
'"' : _ -> readMaybe xs
_ -> Nothing
_ -> Nothing
recoverMultiLineString :: Bool -> String -> Maybe String
recoverMultiLineString unicode input = case recoverString input of
Just r | shouldParseBack r -> Just r
_ -> Nothing
where
shouldParseBack = (&&) <$> all isSafe <*> isMultiLine
isMultiLine = lines >>> length >>> (> 1)
isSafe c = (unicode || isAscii c) && not (isControl c) || c == '\n'
pretty :: Bool -> String -> Maybe String
pretty unicode = parseValue >=> render_
where
render_ :: Value -> Maybe String
render_ value = guard (shouldParseBack value) >> Just (renderValue unicode value)
shouldParseBack :: Value -> Bool
shouldParseBack = go
where
go value = case value of
Char _ -> False
String _ -> True
Rational _ _ -> False
Number _ -> False
Record _ _ -> True
Constructor _ xs -> any go xs
Tuple xs -> any go xs
List xs -> any go xs
newtype Builder = Builder ShowS
instance Monoid Builder where
mempty = Builder id
#if MIN_VERSION_base(4,11,0)
instance Semigroup Builder where
#endif
Builder xs
#if MIN_VERSION_base(4,11,0)
<>
#else
`mappend`
#endif
Builder ys = Builder (xs . ys)
runBuilder :: Builder -> String
runBuilder (Builder xs) = xs ""
intercalate :: Builder -> [Builder] -> Builder
intercalate x xs = mconcat $ intersperse x xs
shows :: Show a => a -> Builder
shows = Builder . Show.shows
instance IsString Builder where
fromString = Builder . showString
renderValue :: Bool -> Value -> String
renderValue unicode = runBuilder . render
where
render :: Value -> Builder
render value = case value of
Char c -> shows c
String str -> if unicode then Builder $ ushows str else shows str
Rational n d -> render n <> " % " <> render d
Number n -> fromString n
Record name fields -> fromString name <> " {\n " <> (intercalate ",\n " $ map renderField fields) <> "\n}"
Constructor name values -> intercalate " " (fromString name : map render values)
Tuple [e@Record{}] -> render e
Tuple xs -> "(" <> intercalate ", " (map render xs) <> ")"
List xs -> "[" <> intercalate ", " (map render xs) <> "]"
renderField (name, value) = fromString name <> " = " <> render value
|
405c9e3e602a7465757f4e090c801dfa2eb0e27acea6e7295edd19c67346c07e | adityavkk/N-Body-Simulations | Main.hs | module Main where
import Graphics.Gloss
import Gravity
import SolarSystem
import qualified DataTypes as T
type PixToKg = Float
type PixToMeter = Float
w = 1500
off = 100
fps = 80 :: Int
window =
InWindow "N-Body Simulation (Direct Sim) by Aditya K." (w, w) (off, off)
render :: T.Universe -> Picture
render u = pictures $ (draw pToM pToKg) <$> bs
where bs = T.bodies u
pToM = T.pixelToM u
pToKg = T.pixelToKg u
draw :: PixToMeter -> PixToKg -> T.Body -> Picture
draw pToM pToKg (T.B m (T.P px py) _ c) =
translate (pToM * px) ( pToM * py ) $ color c $ (circleSolid 4)
move :: Float -> T.Universe -> T.Universe
move t u = moveUniv (T.simTimeRatio u * t) u
update = const move
main :: IO ()
main = simulate window black fps solarSystem render update
| null | https://raw.githubusercontent.com/adityavkk/N-Body-Simulations/23e379e513b3254cd7144408fe132a5280ff9ce6/Direct-Simulation/src/Main.hs | haskell | module Main where
import Graphics.Gloss
import Gravity
import SolarSystem
import qualified DataTypes as T
type PixToKg = Float
type PixToMeter = Float
w = 1500
off = 100
fps = 80 :: Int
window =
InWindow "N-Body Simulation (Direct Sim) by Aditya K." (w, w) (off, off)
render :: T.Universe -> Picture
render u = pictures $ (draw pToM pToKg) <$> bs
where bs = T.bodies u
pToM = T.pixelToM u
pToKg = T.pixelToKg u
draw :: PixToMeter -> PixToKg -> T.Body -> Picture
draw pToM pToKg (T.B m (T.P px py) _ c) =
translate (pToM * px) ( pToM * py ) $ color c $ (circleSolid 4)
move :: Float -> T.Universe -> T.Universe
move t u = moveUniv (T.simTimeRatio u * t) u
update = const move
main :: IO ()
main = simulate window black fps solarSystem render update
| |
5dff4296887f52c4dabe37fa2bee2f80cc79f75050664709f77969e26b562f60 | tisnik/clojure-examples | core_test.clj | ;
( C ) Copyright 2016 , 2020
;
; All rights reserved. This program and the accompanying materials
; are made available under the terms of the Eclipse Public License v1.0
; which accompanies this distribution, and is available at
-v10.html
;
; Contributors:
;
(ns async10.core-test
(:require [clojure.test :refer :all]
[async10.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| null | https://raw.githubusercontent.com/tisnik/clojure-examples/984af4a3e20d994b4f4989678ee1330e409fdae3/async10/test/async10/core_test.clj | clojure |
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
Contributors:
| ( C ) Copyright 2016 , 2020
-v10.html
(ns async10.core-test
(:require [clojure.test :refer :all]
[async10.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
|
a8bd60f7339697f4a8da474ac260ec0edaf8e96f30009cd1c69fa2fa719baf66 | filecoin-project/orient | zigzag-security.lisp | (in-package :filecoin)
(in-suite filecoin-suite)
(defschema zigzag-security-schema
"ZigZag Security"
(zigzag-soundness "ZigZag soundness: Unit fraction")
(zigzag-lambda "ZigZag soundness: Unit bits")
(zigzag-epsilon "Maximum allowable deletion (space tightness): Unit: fraction")
(zigzag-delta "Maximum allowable cheating on labels (block corruption)")
(zigzag-basic-layer-challenges "Multiple of lambda challenges per layer, without tapering optimization.")
(zigzag-basic-layer-challenge-factor "Number of challenges which, when multiplied by lambda, yields the number of challenges per layer without tapering optimization.")
(zigzag-space-gap "Maximum allowable gap between actual and claimed storage. Unit: fraction")
(zigzag-layer-challenges "Number of challenges in this (indexed) layer of ZigZag PoRep. Unit: integer")
(layers "Number of layers specified for this construction (not necessarily same as calculated from security parameters).")
)
(defconstraint-system zigzag-security-constraint-system
((zigzag-lambda (logn zigzag-soundness 0.5))
(zigzag-space-gap (+ zigzag-epsilon zigzag-delta))
(zigzag-basic-layer-challenge-factor (/ 1 zigzag-delta))
(zigzag-basic-layer-challenges (* zigzag-lambda zigzag-basic-layer-challenge-factor))
(zigzag-layers (compute-zigzag-layers zigzag-epsilon zigzag-delta))
(total-untapered-challenges (* zigzag-layers zigzag-basic-layer-challenges))
#+(or) ;; TODO: Allow specifying like this.
(zigzag-layers (+ (log2 (/ 1
(* 3 (- zigzag-epsilon (* 2 zigzag-delta)))))
4))
(total-challenges (== total-zigzag-challenges)))
:schema 'zigzag-security-schema)
(defparameter *default-zigzag-security*
(tuple
(zigzag-lambda 8)
(zigzag-taper (/ 1 3))
(zigzag-epsilon 0.007)
(zigzag-delta 0.003)))
| null | https://raw.githubusercontent.com/filecoin-project/orient/3a9ec7c41fd9f8ac5185c358ce908e5646ddffca/filecoin/zigzag-security.lisp | lisp | TODO: Allow specifying like this. | (in-package :filecoin)
(in-suite filecoin-suite)
(defschema zigzag-security-schema
"ZigZag Security"
(zigzag-soundness "ZigZag soundness: Unit fraction")
(zigzag-lambda "ZigZag soundness: Unit bits")
(zigzag-epsilon "Maximum allowable deletion (space tightness): Unit: fraction")
(zigzag-delta "Maximum allowable cheating on labels (block corruption)")
(zigzag-basic-layer-challenges "Multiple of lambda challenges per layer, without tapering optimization.")
(zigzag-basic-layer-challenge-factor "Number of challenges which, when multiplied by lambda, yields the number of challenges per layer without tapering optimization.")
(zigzag-space-gap "Maximum allowable gap between actual and claimed storage. Unit: fraction")
(zigzag-layer-challenges "Number of challenges in this (indexed) layer of ZigZag PoRep. Unit: integer")
(layers "Number of layers specified for this construction (not necessarily same as calculated from security parameters).")
)
(defconstraint-system zigzag-security-constraint-system
((zigzag-lambda (logn zigzag-soundness 0.5))
(zigzag-space-gap (+ zigzag-epsilon zigzag-delta))
(zigzag-basic-layer-challenge-factor (/ 1 zigzag-delta))
(zigzag-basic-layer-challenges (* zigzag-lambda zigzag-basic-layer-challenge-factor))
(zigzag-layers (compute-zigzag-layers zigzag-epsilon zigzag-delta))
(total-untapered-challenges (* zigzag-layers zigzag-basic-layer-challenges))
(zigzag-layers (+ (log2 (/ 1
(* 3 (- zigzag-epsilon (* 2 zigzag-delta)))))
4))
(total-challenges (== total-zigzag-challenges)))
:schema 'zigzag-security-schema)
(defparameter *default-zigzag-security*
(tuple
(zigzag-lambda 8)
(zigzag-taper (/ 1 3))
(zigzag-epsilon 0.007)
(zigzag-delta 0.003)))
|
f5272639bf14dcd2dd368c8f987e68107cac0fca01eb70d28887555d9b6783e4 | clojure-interop/google-cloud-clients | JobServiceClient$SearchJobsPage.clj | (ns com.google.cloud.talent.v4beta1.JobServiceClient$SearchJobsPage
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.talent.v4beta1 JobServiceClient$SearchJobsPage]))
(defn create-page-async
"context - `com.google.api.gax.rpc.PageContext`
future-response - `com.google.api.core.ApiFuture`
returns: `com.google.api.core.ApiFuture<com.google.cloud.talent.v4beta1.JobServiceClient$SearchJobsPage>`"
(^com.google.api.core.ApiFuture [^JobServiceClient$SearchJobsPage this ^com.google.api.gax.rpc.PageContext context ^com.google.api.core.ApiFuture future-response]
(-> this (.createPageAsync context future-response))))
| null | https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.talent/src/com/google/cloud/talent/v4beta1/JobServiceClient%24SearchJobsPage.clj | clojure | (ns com.google.cloud.talent.v4beta1.JobServiceClient$SearchJobsPage
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.talent.v4beta1 JobServiceClient$SearchJobsPage]))
(defn create-page-async
"context - `com.google.api.gax.rpc.PageContext`
future-response - `com.google.api.core.ApiFuture`
returns: `com.google.api.core.ApiFuture<com.google.cloud.talent.v4beta1.JobServiceClient$SearchJobsPage>`"
(^com.google.api.core.ApiFuture [^JobServiceClient$SearchJobsPage this ^com.google.api.gax.rpc.PageContext context ^com.google.api.core.ApiFuture future-response]
(-> this (.createPageAsync context future-response))))
| |
6eb0a1bc0981c90aa40cc9292fb11eed70109f00a6d2fe952c28aa701678fda2 | brianium/clean-todos | create.clj | (ns todos.delivery.api.create
(:require [clojure.spec.alpha :as s]
[ring.util.response :refer [response]]
[yoose.core :as yoose]
[todos.delivery.api.spec :as ts]
[todos.delivery.api.json :refer [todo->json]]
[todos.delivery.use-cases :refer [create-todo]]
[todos.core.entity :as e]
[todos.core.entity.todo :as t]
[todos.core.action :as action]))
;; @todo maybe just parse the explanation from spec
(def bad-request
{:status 422
:body {:error "Invalid title or complete? keys"}})
(defn- action->response
"Converts an action to a response"
[{:keys [::action/error? ::action/payload]}]
(if error?
{:status 500
:body {:error "There was an error creating the todo"}}
{:status 201
:body {:data (todo->json (:result payload))}}))
(defn- assoc-id
[id todo]
(if id
(assoc todo ::e/id (e/string->uuid id))
todo))
(defn- create
"Creates a new todo from the request"
[{:keys [title complete? id]}]
(let [todo (t/make-todo title)]
(->> (if complete? (t/mark-complete todo) todo)
(assoc-id id)
(yoose/push! create-todo)
yoose/pull!!
action->response)))
(defn respond
"Handles a request to create a new todo"
[{:keys [body]}]
(let [payload (s/conform ::ts/create-request body)]
(if (= payload ::s/invalid)
bad-request
(create payload))))
| null | https://raw.githubusercontent.com/brianium/clean-todos/fca2320fe3bca052787c4ace479ce69d23d58a12/src/todos/delivery/api/create.clj | clojure | @todo maybe just parse the explanation from spec | (ns todos.delivery.api.create
(:require [clojure.spec.alpha :as s]
[ring.util.response :refer [response]]
[yoose.core :as yoose]
[todos.delivery.api.spec :as ts]
[todos.delivery.api.json :refer [todo->json]]
[todos.delivery.use-cases :refer [create-todo]]
[todos.core.entity :as e]
[todos.core.entity.todo :as t]
[todos.core.action :as action]))
(def bad-request
{:status 422
:body {:error "Invalid title or complete? keys"}})
(defn- action->response
"Converts an action to a response"
[{:keys [::action/error? ::action/payload]}]
(if error?
{:status 500
:body {:error "There was an error creating the todo"}}
{:status 201
:body {:data (todo->json (:result payload))}}))
(defn- assoc-id
[id todo]
(if id
(assoc todo ::e/id (e/string->uuid id))
todo))
(defn- create
"Creates a new todo from the request"
[{:keys [title complete? id]}]
(let [todo (t/make-todo title)]
(->> (if complete? (t/mark-complete todo) todo)
(assoc-id id)
(yoose/push! create-todo)
yoose/pull!!
action->response)))
(defn respond
"Handles a request to create a new todo"
[{:keys [body]}]
(let [payload (s/conform ::ts/create-request body)]
(if (= payload ::s/invalid)
bad-request
(create payload))))
|
2585ee140564f96bf04aa88fd054c92b7945bd1cecbfbbc9e8bb0a3e91b59a86 | gwkkwg/cl-markdown | test-regexes.lisp | (in-package #:cl-markdown-test)
(deftestsuite test-regexes (cl-markdown-test-all) ())
(deftestsuite test-url (test-regexes) ())
(addtest (test-url)
test-1
(ensure-same
(scan-to-strings
'(:sequence url) "My page is at /~gwking/public.")
(values "/~gwking/public"
#("www.metabang.com" "~gwking/public"))
:test 'equalp))
;;; ---------------------------------------------------------------------------
(deftestsuite test-link-label (test-regexes) ())
(addtest (test-link-label)
test-link
(bind (((values nil registers)
(scan-to-strings '(:sequence link-label) " [aa]: ")))
(ensure-same (aref registers 0) "aa")
(ensure-same (aref registers 1) "")
(ensure-same (aref registers 2) nil)))
(addtest (test-link-label)
test-link-with-title
(bind (((values nil registers)
(scan-to-strings '(:sequence link-label)
" [aa]: \"best foos\"")))
(ensure-same (aref registers 0) "aa")
(ensure-same (aref registers 1) "")
(ensure-same (aref registers 2) "best foos")))
;;; ---------------------------------------------------------------------------
(deftestsuite test-inline-links (test-regexes) ())
(addtest (test-inline-links)
test-1
(ensure-same
(nth-value 1
(scan-to-strings
'(:sequence inline-link)
"This is an [in-line](/ \"Link to Google\") link"))
#("in-line" "/" "Link to Google")
:test 'equalp))
(addtest (test-inline-links)
test-2
(ensure-same
(nth-value 1
(scan-to-strings
'(:sequence inline-link)
"This is an [in-line](/) link with no title"))
#("in-line" "/" nil)
:test 'equalp))
(addtest (test-inline-links)
test-2
(ensure-same
(scan-to-strings
'(:sequence inline-link)
"This is not an (in-line)(/) link with no title") nil))
;;; ---------------------------------------------------------------------------
(deftestsuite test-reference-links (test-regexes) ())
(addtest (test-reference-links)
test-1
(ensure-same
(nth-value 1
(scan-to-strings
'(:sequence reference-link)
"This is an [in-line][id] link"))
#("in-line" "id")
:test 'equalp))
(addtest (test-reference-links)
test-2
(ensure-same
(nth-value 1
(scan-to-strings
'(:sequence reference-link)
"This is an [in-line] [id] link with no title"))
#("in-line" "id")
:test 'equalp))
| null | https://raw.githubusercontent.com/gwkkwg/cl-markdown/098e89251adf3337578aacd0a7b029956efc1478/unit-tests/test-regexes.lisp | lisp | ---------------------------------------------------------------------------
---------------------------------------------------------------------------
--------------------------------------------------------------------------- | (in-package #:cl-markdown-test)
(deftestsuite test-regexes (cl-markdown-test-all) ())
(deftestsuite test-url (test-regexes) ())
(addtest (test-url)
test-1
(ensure-same
(scan-to-strings
'(:sequence url) "My page is at /~gwking/public.")
(values "/~gwking/public"
#("www.metabang.com" "~gwking/public"))
:test 'equalp))
(deftestsuite test-link-label (test-regexes) ())
(addtest (test-link-label)
test-link
(bind (((values nil registers)
(scan-to-strings '(:sequence link-label) " [aa]: ")))
(ensure-same (aref registers 0) "aa")
(ensure-same (aref registers 1) "")
(ensure-same (aref registers 2) nil)))
(addtest (test-link-label)
test-link-with-title
(bind (((values nil registers)
(scan-to-strings '(:sequence link-label)
" [aa]: \"best foos\"")))
(ensure-same (aref registers 0) "aa")
(ensure-same (aref registers 1) "")
(ensure-same (aref registers 2) "best foos")))
(deftestsuite test-inline-links (test-regexes) ())
(addtest (test-inline-links)
test-1
(ensure-same
(nth-value 1
(scan-to-strings
'(:sequence inline-link)
"This is an [in-line](/ \"Link to Google\") link"))
#("in-line" "/" "Link to Google")
:test 'equalp))
(addtest (test-inline-links)
test-2
(ensure-same
(nth-value 1
(scan-to-strings
'(:sequence inline-link)
"This is an [in-line](/) link with no title"))
#("in-line" "/" nil)
:test 'equalp))
(addtest (test-inline-links)
test-2
(ensure-same
(scan-to-strings
'(:sequence inline-link)
"This is not an (in-line)(/) link with no title") nil))
(deftestsuite test-reference-links (test-regexes) ())
(addtest (test-reference-links)
test-1
(ensure-same
(nth-value 1
(scan-to-strings
'(:sequence reference-link)
"This is an [in-line][id] link"))
#("in-line" "id")
:test 'equalp))
(addtest (test-reference-links)
test-2
(ensure-same
(nth-value 1
(scan-to-strings
'(:sequence reference-link)
"This is an [in-line] [id] link with no title"))
#("in-line" "id")
:test 'equalp))
|
7a8102935509688609c07fa38d1ddc96cde22859f669505101d8f8c09814bde1 | spawnfest/eep49ers | tftp_logger.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2018 . 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(tftp_logger).
%%-------------------------------------------------------------------
Interface
%%-------------------------------------------------------------------
%% public functions
-export([
error_msg/2,
warning_msg/2,
info_msg/2
]).
-export([behaviour_info/1]).
behaviour_info(callbacks) ->
[{error_msg, 2}, {warning_msg, 2}, {info_msg, 2}];
behaviour_info(_) ->
undefined.
%%-------------------------------------------------------------------
%% error_msg(Format, Data) -> ok | exit(Reason)
%%
%% Format = string()
%% Data = [term()]
%% Reason = term()
%%
%% Log an error message
%%-------------------------------------------------------------------
error_msg(Format, Data) ->
{Format2, Data2} = add_timestamp(Format, Data),
error_logger:error_msg(Format2, Data2).
%%-------------------------------------------------------------------
%% warning_msg(Format, Data) -> ok | exit(Reason)
%%
%% Format = string()
%% Data = [term()]
%% Reason = term()
%%
%% Log a warning message
%%-------------------------------------------------------------------
warning_msg(Format, Data) ->
{Format2, Data2} = add_timestamp(Format, Data),
error_logger:warning_msg(Format2, Data2).
%%-------------------------------------------------------------------
%% info_msg(Format, Data) -> ok | exit(Reason)
%%
%% Format = string()
%% Data = [term()]
%% Reason = term()
%%
%% Log an info message
%%-------------------------------------------------------------------
info_msg(Format, Data) ->
{Format2, Data2} = add_timestamp(Format, Data),
io:format(Format2, Data2).
%%-------------------------------------------------------------------
%% Add timestamp to log message
%%-------------------------------------------------------------------
add_timestamp(Format, Data) ->
Time = erlang:timestamp(),
{{_Y, _Mo, _D}, {H, Mi, S}} = calendar:now_to_universal_time(Time),
%% {"~p-~s-~sT~s:~s:~sZ,~6.6.0w tftp: " ++ Format ++ "\n",
[ Y , t(Mo ) , t(D ) , t(H ) , t(Mi ) , t(S ) , MicroSecs | Data ] } .
{"~s:~s:~s tftp: " ++ Format, [t(H), t(Mi), t(S) | Data]}.
%% Convert 9 to "09".
t(Int) ->
case integer_to_list(Int) of
[Single] -> [$0, Single];
Multi -> Multi
end.
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/tftp/src/tftp_logger.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%
-------------------------------------------------------------------
-------------------------------------------------------------------
public functions
-------------------------------------------------------------------
error_msg(Format, Data) -> ok | exit(Reason)
Format = string()
Data = [term()]
Reason = term()
Log an error message
-------------------------------------------------------------------
-------------------------------------------------------------------
warning_msg(Format, Data) -> ok | exit(Reason)
Format = string()
Data = [term()]
Reason = term()
Log a warning message
-------------------------------------------------------------------
-------------------------------------------------------------------
info_msg(Format, Data) -> ok | exit(Reason)
Format = string()
Data = [term()]
Reason = term()
Log an info message
-------------------------------------------------------------------
-------------------------------------------------------------------
Add timestamp to log message
-------------------------------------------------------------------
{"~p-~s-~sT~s:~s:~sZ,~6.6.0w tftp: " ++ Format ++ "\n",
Convert 9 to "09". | Copyright Ericsson AB 2008 - 2018 . 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(tftp_logger).
Interface
-export([
error_msg/2,
warning_msg/2,
info_msg/2
]).
-export([behaviour_info/1]).
behaviour_info(callbacks) ->
[{error_msg, 2}, {warning_msg, 2}, {info_msg, 2}];
behaviour_info(_) ->
undefined.
error_msg(Format, Data) ->
{Format2, Data2} = add_timestamp(Format, Data),
error_logger:error_msg(Format2, Data2).
warning_msg(Format, Data) ->
{Format2, Data2} = add_timestamp(Format, Data),
error_logger:warning_msg(Format2, Data2).
info_msg(Format, Data) ->
{Format2, Data2} = add_timestamp(Format, Data),
io:format(Format2, Data2).
add_timestamp(Format, Data) ->
Time = erlang:timestamp(),
{{_Y, _Mo, _D}, {H, Mi, S}} = calendar:now_to_universal_time(Time),
[ Y , t(Mo ) , t(D ) , t(H ) , t(Mi ) , t(S ) , MicroSecs | Data ] } .
{"~s:~s:~s tftp: " ++ Format, [t(H), t(Mi), t(S) | Data]}.
t(Int) ->
case integer_to_list(Int) of
[Single] -> [$0, Single];
Multi -> Multi
end.
|
5c5ac74a692ea50e21bb00f9334b795067edde12fc1a54f1fbd3d3aafd259ff0 | odj/Ouch | Mol.hs | ------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Module : Ouch . Output . Mol
-- Maintainer :
-- Stability : Unstable
-- Portability :
Copyright ( c ) 2010 Orion
This file is part of Ouch , a chemical informatics toolkit
written entirely in Haskell .
Ouch 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 .
Ouch 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 Ouch . If not , see < / > .
--------------------------------------------------------------------------------
------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Module : Ouch.Output.Mol
-- Maintainer : Orion Jankowski
-- Stability : Unstable
-- Portability :
Copyright (c) 2010 Orion D. Jankowski
This file is part of Ouch, a chemical informatics toolkit
written entirely in Haskell.
Ouch 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.
Ouch 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 Ouch. If not, see </>.
--------------------------------------------------------------------------------
-------------------------------------------------------------------------------}
module Ouch.Output.Mol (
molfile
) where
import Ouch.Structure.Atom
import {-# SOURCE #-} Ouch.Structure.Molecule
import Ouch.Structure.Bond
import Ouch.Structure.Marker
import Ouch.Text.String
import Ouch.Property.Builder
import Data.Maybe
import Data.Char
import Data.Set as Set
import qualified Data.List as List
import Data.Map as Map
import Control.Applicative
{------------------------------------------------------------------------------}
{-------------------------------Functions--------------------------------------}
{------------------------------------------------------------------------------}
molfile :: Molecule -> Maybe String
molfile m = List.foldr (\s acc -> (++) <$> s <*> acc) (Just "") lineList
where m' = removeAtoms m isLonePair
lineList = List.map (>>= \s -> Just $ s ++ _CR)
$ headerBlock m'
++ countsLine m'
++ atomBlock m'
++ bondBlock m'
++ propertiesBlock m'
++ [Just _END]
headerBlock :: Molecule -> [Maybe String]
headerBlock m = let
line1 = case getName m of Nothing -> [Just ""]; s -> [s]
line2 = [Just $ initials ++ _PROGRAM ++ date ++ dim]
initials = " "
date = " "
dim = "2d"
scaling = " "
energy = " "
registry = " "
line3 = case getPropertyForKey m "COMMENT" of
Nothing -> [Just ""]
Just s -> case value s of
Left v -> [Just $ show v]
Right f -> [Just "function"]
in line1 ++ line2 ++ line3
countsLine :: Molecule -> [Maybe String]
countsLine m = let
aaa = padCountsElem $ show $ Map.size $ atomMap m
bbb = padCountsElem $ show $ Map.size $ getBondMap m
lll = padCountsElem "0"
fff = padCountsElem "0"
ccc | isChiral = padCountsElem "1" | otherwise = padCountsElem "0"
sss = padCountsElem "0"
xxx = padCountsElem "0"
mmm = padCountsElem "999"
isChiral = Map.fold (\a acc -> (&&) acc $ hasMarker a $ Chiral Dextro) False (atomMap m)
in [Just $ aaa
++ bbb
++ lll
++ fff
++ ccc
++ sss
++ xxx ++ xxx ++ xxx ++ xxx
++ mmm
++ _VERSION]
atomBlock :: Molecule -> [Maybe String]
atomBlock m = let
atomLine a = Just $ posX ++ posY ++ posZ ++ " "
++ aaa ++ dd ++ ccc ++ sss ++ hhh
++ bbb ++ vvv ++ hHH ++ rrr ++ iii
++ mmm ++ eee
where hasPos = hasMarker a $ Position (0, 0, 0)
hasChg = hasMarker a $ Charge 0
(x, y, z) | hasPos = position $ fromJust $ getMarker a $ Position (0, 0, 0)
| otherwise = (0 ,0, 0)
ccc | hasChg = padAtomLineElem $ showCharge $ charge $ fromJust $ getMarker a $ Charge 0
| otherwise = padAtomLineElem "0"
posX = padPosElem x
posY = padPosElem y
posZ = padPosElem z
aaa = padAtomSymbolElem $ atomicSymbolForAtom a
dd = padString RightJustify 2 ' ' $ show 0
sss = padAtomLineElem $ show $ 0
hhh = padAtomLineElem $ show $ 0
bbb = padAtomLineElem $ show $ 0
vvv = padAtomLineElem $ show $ 0
hHH = padAtomLineElem $ show $ 0
rrr = padAtomLineElem ""
iii = padAtomLineElem ""
mmm = padAtomLineElem ""
eee = padAtomLineElem ""
showCharge i | i == 3 = "1"
| i == 2 = "2"
| i == 1 = "3"
| i == -1 = "5"
| i == -2 = "6"
| i == -3 = "7"
| otherwise = "0"
in Map.fold (\a acc -> [atomLine a] ++ acc ) [] $ Map.filter isElement $ atomMap m
propertiesBlock :: Molecule -> [Maybe String]
propertiesBlock m = [Just ""]
bondBlock :: Molecule -> [Maybe String]
bondBlock m = let
bondMap = Map.toList $ getBondMap m
bondLine ((a1, a2), nb) = Just $ atom1 ++ atom2
++ ttt ++ sss ++ xxx
++ rrr ++ ccc
where atom1 = padBondLineElem $ show (a1 + 1)
atom2 = padBondLineElem $ show (a2 + 1)
ttt = padBondLineElem $ showBondType nb
sss = padBondLineElem "0"
xxx = padBondLineElem ""
rrr = padBondLineElem ""
ccc = padBondLineElem "0"
showBondType b' | b' == Single = "1"
| b' == Double = "2"
| b' == Triple = "3"
| b' == AromaticOnly = "4"
| b' == SingleOrDouble = "5"
| b' == SingleOrAromatic = "6"
| b' == DoubleOrAromatic = "7"
| b' == AnyBond = "8"
| otherwise = "8"
in List.foldr (\b acc -> [bondLine b] ++ acc ) [] bondMap
{------------------------------------------------------------------------------}
{-------------------------------Constants--------------------------------------}
{------------------------------------------------------------------------------}
_CR = "\n"
_VERSION = " V2000"
_PROGRAM = " OUCH"
_END = "M END"
padCountsElem = padString RightJustify 3 ' '
padAtomLineElem = padString RightJustify 3 ' '
padAtomSymbolElem = padString LeftJustify 3 ' '
padBondLineElem = padString RightJustify 3 ' '
padPosElem = padString RightJustify 10 ' ' . formatNumber 4
| null | https://raw.githubusercontent.com/odj/Ouch/ed20599214cf77b0cb81cc7cefb4cd9c35bc7cf7/Ouch/Output/Mol.hs | haskell | ----------------------------------------------------------------------------
------------------------------------------------------------------------------
Module : Ouch . Output . Mol
Maintainer :
Stability : Unstable
Portability :
------------------------------------------------------------------------------
----------------------------------------------------------------------------
------------------------------------------------------------------------------
Module : Ouch.Output.Mol
Maintainer : Orion Jankowski
Stability : Unstable
Portability :
------------------------------------------------------------------------------
-----------------------------------------------------------------------------}
# SOURCE #
----------------------------------------------------------------------------
------------------------------Functions-------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
------------------------------Constants-------------------------------------
---------------------------------------------------------------------------- |
Copyright ( c ) 2010 Orion
This file is part of Ouch , a chemical informatics toolkit
written entirely in Haskell .
Ouch 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 .
Ouch 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 Ouch . If not , see < / > .
Copyright (c) 2010 Orion D. Jankowski
This file is part of Ouch, a chemical informatics toolkit
written entirely in Haskell.
Ouch 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.
Ouch 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 Ouch. If not, see </>.
module Ouch.Output.Mol (
molfile
) where
import Ouch.Structure.Atom
import Ouch.Structure.Bond
import Ouch.Structure.Marker
import Ouch.Text.String
import Ouch.Property.Builder
import Data.Maybe
import Data.Char
import Data.Set as Set
import qualified Data.List as List
import Data.Map as Map
import Control.Applicative
molfile :: Molecule -> Maybe String
molfile m = List.foldr (\s acc -> (++) <$> s <*> acc) (Just "") lineList
where m' = removeAtoms m isLonePair
lineList = List.map (>>= \s -> Just $ s ++ _CR)
$ headerBlock m'
++ countsLine m'
++ atomBlock m'
++ bondBlock m'
++ propertiesBlock m'
++ [Just _END]
headerBlock :: Molecule -> [Maybe String]
headerBlock m = let
line1 = case getName m of Nothing -> [Just ""]; s -> [s]
line2 = [Just $ initials ++ _PROGRAM ++ date ++ dim]
initials = " "
date = " "
dim = "2d"
scaling = " "
energy = " "
registry = " "
line3 = case getPropertyForKey m "COMMENT" of
Nothing -> [Just ""]
Just s -> case value s of
Left v -> [Just $ show v]
Right f -> [Just "function"]
in line1 ++ line2 ++ line3
countsLine :: Molecule -> [Maybe String]
countsLine m = let
aaa = padCountsElem $ show $ Map.size $ atomMap m
bbb = padCountsElem $ show $ Map.size $ getBondMap m
lll = padCountsElem "0"
fff = padCountsElem "0"
ccc | isChiral = padCountsElem "1" | otherwise = padCountsElem "0"
sss = padCountsElem "0"
xxx = padCountsElem "0"
mmm = padCountsElem "999"
isChiral = Map.fold (\a acc -> (&&) acc $ hasMarker a $ Chiral Dextro) False (atomMap m)
in [Just $ aaa
++ bbb
++ lll
++ fff
++ ccc
++ sss
++ xxx ++ xxx ++ xxx ++ xxx
++ mmm
++ _VERSION]
atomBlock :: Molecule -> [Maybe String]
atomBlock m = let
atomLine a = Just $ posX ++ posY ++ posZ ++ " "
++ aaa ++ dd ++ ccc ++ sss ++ hhh
++ bbb ++ vvv ++ hHH ++ rrr ++ iii
++ mmm ++ eee
where hasPos = hasMarker a $ Position (0, 0, 0)
hasChg = hasMarker a $ Charge 0
(x, y, z) | hasPos = position $ fromJust $ getMarker a $ Position (0, 0, 0)
| otherwise = (0 ,0, 0)
ccc | hasChg = padAtomLineElem $ showCharge $ charge $ fromJust $ getMarker a $ Charge 0
| otherwise = padAtomLineElem "0"
posX = padPosElem x
posY = padPosElem y
posZ = padPosElem z
aaa = padAtomSymbolElem $ atomicSymbolForAtom a
dd = padString RightJustify 2 ' ' $ show 0
sss = padAtomLineElem $ show $ 0
hhh = padAtomLineElem $ show $ 0
bbb = padAtomLineElem $ show $ 0
vvv = padAtomLineElem $ show $ 0
hHH = padAtomLineElem $ show $ 0
rrr = padAtomLineElem ""
iii = padAtomLineElem ""
mmm = padAtomLineElem ""
eee = padAtomLineElem ""
showCharge i | i == 3 = "1"
| i == 2 = "2"
| i == 1 = "3"
| i == -1 = "5"
| i == -2 = "6"
| i == -3 = "7"
| otherwise = "0"
in Map.fold (\a acc -> [atomLine a] ++ acc ) [] $ Map.filter isElement $ atomMap m
propertiesBlock :: Molecule -> [Maybe String]
propertiesBlock m = [Just ""]
bondBlock :: Molecule -> [Maybe String]
bondBlock m = let
bondMap = Map.toList $ getBondMap m
bondLine ((a1, a2), nb) = Just $ atom1 ++ atom2
++ ttt ++ sss ++ xxx
++ rrr ++ ccc
where atom1 = padBondLineElem $ show (a1 + 1)
atom2 = padBondLineElem $ show (a2 + 1)
ttt = padBondLineElem $ showBondType nb
sss = padBondLineElem "0"
xxx = padBondLineElem ""
rrr = padBondLineElem ""
ccc = padBondLineElem "0"
showBondType b' | b' == Single = "1"
| b' == Double = "2"
| b' == Triple = "3"
| b' == AromaticOnly = "4"
| b' == SingleOrDouble = "5"
| b' == SingleOrAromatic = "6"
| b' == DoubleOrAromatic = "7"
| b' == AnyBond = "8"
| otherwise = "8"
in List.foldr (\b acc -> [bondLine b] ++ acc ) [] bondMap
_CR = "\n"
_VERSION = " V2000"
_PROGRAM = " OUCH"
_END = "M END"
padCountsElem = padString RightJustify 3 ' '
padAtomLineElem = padString RightJustify 3 ' '
padAtomSymbolElem = padString LeftJustify 3 ' '
padBondLineElem = padString RightJustify 3 ' '
padPosElem = padString RightJustify 10 ' ' . formatNumber 4
|
c865b798c13c98b1ac928b5b6b59883baeeed6fab714dffb2e290c153bee280d | Chris00/ocaml-dropbox | create_folder.ml | open Lwt
module D = Dropbox_lwt_unix
* We assume there is only two entries in command line and that Sys.argv.(0 )
is the path of the folder and Sys.argv.(1 ) is the root
is the path of the folder and Sys.argv.(1) is the root *)
let string_to_root a = match a with
| "auto" -> `Auto
| "dropbox" -> `Dropbox
| "sandbox" -> `Sandbox
| _ -> invalid_arg "root must be auto, dropbox or sandbox"
let create_folder t ?root path =
D.create_folder t ?root path
>>= function
| `Some m -> Lwt_io.printlf "%s" (Dropbox_j.string_of_metadata m)
| `Invalid s -> Lwt_io.printlf "Invalid: %s" s
let main t args =
match args with
| [path] -> create_folder t path
| [path; root] -> create_folder t ~root:(string_to_root root) path
| _ -> Lwt_io.printlf "%s <path> [root]\n" Sys.argv.(0)
let () =
Common.run main
| null | https://raw.githubusercontent.com/Chris00/ocaml-dropbox/36b222269e6bc7e5486cbb69738841d87a1212fb/tests/create_folder.ml | ocaml | open Lwt
module D = Dropbox_lwt_unix
* We assume there is only two entries in command line and that Sys.argv.(0 )
is the path of the folder and Sys.argv.(1 ) is the root
is the path of the folder and Sys.argv.(1) is the root *)
let string_to_root a = match a with
| "auto" -> `Auto
| "dropbox" -> `Dropbox
| "sandbox" -> `Sandbox
| _ -> invalid_arg "root must be auto, dropbox or sandbox"
let create_folder t ?root path =
D.create_folder t ?root path
>>= function
| `Some m -> Lwt_io.printlf "%s" (Dropbox_j.string_of_metadata m)
| `Invalid s -> Lwt_io.printlf "Invalid: %s" s
let main t args =
match args with
| [path] -> create_folder t path
| [path; root] -> create_folder t ~root:(string_to_root root) path
| _ -> Lwt_io.printlf "%s <path> [root]\n" Sys.argv.(0)
let () =
Common.run main
| |
a450ab066c512316440087d5cd153fef70ab337742d530c46641266ced9ab7c0 | chrislloyd/kepler | decomposition.clj | (ns kepler.systems.decomposition
(:require [kepler.component.life :refer [is-dead?]]))
(defn decomposition-system [state action]
(if (= (:type action) :tick)
(let [dead-entities (->> state
(filter
(fn [{:keys [type val]}]
(and
(= type :life)
(is-dead? val))))
(map :entity)
(set))]
(filter (fn [{:keys [entity]}]
(not (contains? dead-entities entity)))
state))
state))
| null | https://raw.githubusercontent.com/chrislloyd/kepler/bd6f30c20ff9e5ad6749bab0d3589d9ccce6f14f/src/kepler/systems/decomposition.clj | clojure | (ns kepler.systems.decomposition
(:require [kepler.component.life :refer [is-dead?]]))
(defn decomposition-system [state action]
(if (= (:type action) :tick)
(let [dead-entities (->> state
(filter
(fn [{:keys [type val]}]
(and
(= type :life)
(is-dead? val))))
(map :entity)
(set))]
(filter (fn [{:keys [entity]}]
(not (contains? dead-entities entity)))
state))
state))
| |
97ad42b13e558431a1adcae1907e669e4a116695cff77b86a6e5c7cbde6dca94 | synduce/Synduce | mpss_noe.ml |
let s0 a = (max a 0, a)
let s1 (b0, b1) (c0, c1) = (max b0 (b1 + c0), b1 + c1)
let rec target =
function Sglt(x) -> s0 (tsum x) | Cat(l, r) -> s1 (target r) (target l)
and tsum = function Elt(x) -> x | Cons(hd, tl) -> hd + (tsum tl)
| null | https://raw.githubusercontent.com/synduce/Synduce/289888afb1c312adfd631ce8d90df2134de827b8/extras/solutions/constraints/ensures/mpss_noe.ml | ocaml |
let s0 a = (max a 0, a)
let s1 (b0, b1) (c0, c1) = (max b0 (b1 + c0), b1 + c1)
let rec target =
function Sglt(x) -> s0 (tsum x) | Cat(l, r) -> s1 (target r) (target l)
and tsum = function Elt(x) -> x | Cons(hd, tl) -> hd + (tsum tl)
| |
70905892a3b1118ee5fa2d6085db663b63d22eb0ddecba377c9fed70ca24c5bf | higherkindness/mu-haskell | Producer.hs | # language DeriveGeneric #
{-# language FlexibleContexts #-}
# language TypeFamilies #
|
Description : streams of terms as producers
This module allows you to open a " sink " to .
Every value you sent to the sink will be sent over
to the corresponding instance .
This module is a wrapper over ' . Conduit . Sink '
from the ( awesome ) package @hw - kafka - client@.
Description : streams of Mu terms as Kafka producers
This module allows you to open a "sink" to Kafka.
Every value you sent to the sink will be sent over
to the corresponding Kafka instance.
This module is a wrapper over 'Kafka.Conduit.Sink'
from the (awesome) package @hw-kafka-client@.
-}
module Mu.Kafka.Producer (
ProducerRecord'(..)
, kafkaSink
, kafkaSinkAutoClose
, kafkaSinkNoClose
, kafkaBatchSinkNoClose
, module X
) where
import Conduit (mapC)
import Control.Monad.IO.Class
import Control.Monad.Trans.Resource
import qualified Data.Avro as A
import Data.ByteString
import Data.Conduit
import Data.Typeable
import GHC.Generics
import Mu.Schema
import qualified Kafka.Conduit.Sink as S
import Kafka.Producer (ProducerRecord (..))
import Kafka.Conduit.Combinators as X
import Kafka.Consumer as X (KafkaConsumer)
import Kafka.Producer as X (KafkaError, KafkaProducer, ProducePartition,
ProducerProperties, TopicName)
import Mu.Kafka.Internal
data ProducerRecord' k v = ProducerRecord'
{ prTopic :: !TopicName
, prPartition :: !ProducePartition
, prKey :: Maybe k
, prValue :: Maybe v
} deriving (Eq, Show, Typeable, Generic)
toPR
:: ( ToSchema sch sty t
, A.ToAvro (WithSchema sch sty t)
, A.HasAvroSchema (WithSchema sch sty t) )
=> Proxy sch -> ProducerRecord' ByteString t -> ProducerRecord
toPR proxy (ProducerRecord' t p k v)
= ProducerRecord t p k (toBS proxy <$> v)
-- | Creates a kafka producer for given properties and returns a Sink.
--
This method of creating a Sink represents a simple case
and does not provide access to ` KafkaProducer ` . For more complex scenarious
-- 'kafkaSinkAutoClose' or 'kafkaSinkNoClose' can be used.
kafkaSink
:: ( MonadResource m
, ToSchema sch sty t
, A.ToAvro (WithSchema sch sty t)
, A.HasAvroSchema (WithSchema sch sty t) )
=> Proxy sch -> X.ProducerProperties
-> ConduitT (ProducerRecord' ByteString t) Void m (Maybe KafkaError)
kafkaSink proxy prod
= mapC (toPR proxy) .| S.kafkaSink prod
| Creates a Sink for a given ` KafkaProducer ` .
-- The producer will be closed when the Sink is closed.
kafkaSinkAutoClose
:: ( MonadResource m
, ToSchema sch sty t
, A.ToAvro (WithSchema sch sty t)
, A.HasAvroSchema (WithSchema sch sty t) )
=> Proxy sch -> KafkaProducer
-> ConduitT (ProducerRecord' ByteString t) Void m (Maybe X.KafkaError)
kafkaSinkAutoClose proxy prod
= mapC (toPR proxy) .| S.kafkaSinkAutoClose prod
| Creates a Sink for a given ` KafkaProducer ` .
-- The producer will NOT be closed automatically.
kafkaSinkNoClose
:: ( MonadIO m
, ToSchema sch sty t
, A.ToAvro (WithSchema sch sty t)
, A.HasAvroSchema (WithSchema sch sty t) )
=> Proxy sch -> KafkaProducer
-> ConduitT (ProducerRecord' ByteString t) Void m (Maybe X.KafkaError)
kafkaSinkNoClose proxy prod
= mapC (toPR proxy) .| S.kafkaSinkNoClose prod
| Creates a batching Sink for a given ` KafkaProducer ` .
-- The producer will NOT be closed automatically.
kafkaBatchSinkNoClose
:: ( MonadIO m
, ToSchema sch sty t
, A.ToAvro (WithSchema sch sty t)
, A.HasAvroSchema (WithSchema sch sty t) )
=> Proxy sch -> KafkaProducer
-> ConduitT [ProducerRecord' ByteString t] Void m [(ProducerRecord, KafkaError)]
kafkaBatchSinkNoClose proxy prod
= mapC (fmap (toPR proxy)) .| S.kafkaBatchSinkNoClose prod
| null | https://raw.githubusercontent.com/higherkindness/mu-haskell/e41ba786f556cfac962e0f183b36bf9ae81d69e4/adapter/kafka/src/Mu/Kafka/Producer.hs | haskell | # language FlexibleContexts #
| Creates a kafka producer for given properties and returns a Sink.
'kafkaSinkAutoClose' or 'kafkaSinkNoClose' can be used.
The producer will be closed when the Sink is closed.
The producer will NOT be closed automatically.
The producer will NOT be closed automatically. | # language DeriveGeneric #
# language TypeFamilies #
|
Description : streams of terms as producers
This module allows you to open a " sink " to .
Every value you sent to the sink will be sent over
to the corresponding instance .
This module is a wrapper over ' . Conduit . Sink '
from the ( awesome ) package @hw - kafka - client@.
Description : streams of Mu terms as Kafka producers
This module allows you to open a "sink" to Kafka.
Every value you sent to the sink will be sent over
to the corresponding Kafka instance.
This module is a wrapper over 'Kafka.Conduit.Sink'
from the (awesome) package @hw-kafka-client@.
-}
module Mu.Kafka.Producer (
ProducerRecord'(..)
, kafkaSink
, kafkaSinkAutoClose
, kafkaSinkNoClose
, kafkaBatchSinkNoClose
, module X
) where
import Conduit (mapC)
import Control.Monad.IO.Class
import Control.Monad.Trans.Resource
import qualified Data.Avro as A
import Data.ByteString
import Data.Conduit
import Data.Typeable
import GHC.Generics
import Mu.Schema
import qualified Kafka.Conduit.Sink as S
import Kafka.Producer (ProducerRecord (..))
import Kafka.Conduit.Combinators as X
import Kafka.Consumer as X (KafkaConsumer)
import Kafka.Producer as X (KafkaError, KafkaProducer, ProducePartition,
ProducerProperties, TopicName)
import Mu.Kafka.Internal
data ProducerRecord' k v = ProducerRecord'
{ prTopic :: !TopicName
, prPartition :: !ProducePartition
, prKey :: Maybe k
, prValue :: Maybe v
} deriving (Eq, Show, Typeable, Generic)
toPR
:: ( ToSchema sch sty t
, A.ToAvro (WithSchema sch sty t)
, A.HasAvroSchema (WithSchema sch sty t) )
=> Proxy sch -> ProducerRecord' ByteString t -> ProducerRecord
toPR proxy (ProducerRecord' t p k v)
= ProducerRecord t p k (toBS proxy <$> v)
This method of creating a Sink represents a simple case
and does not provide access to ` KafkaProducer ` . For more complex scenarious
kafkaSink
:: ( MonadResource m
, ToSchema sch sty t
, A.ToAvro (WithSchema sch sty t)
, A.HasAvroSchema (WithSchema sch sty t) )
=> Proxy sch -> X.ProducerProperties
-> ConduitT (ProducerRecord' ByteString t) Void m (Maybe KafkaError)
kafkaSink proxy prod
= mapC (toPR proxy) .| S.kafkaSink prod
| Creates a Sink for a given ` KafkaProducer ` .
kafkaSinkAutoClose
:: ( MonadResource m
, ToSchema sch sty t
, A.ToAvro (WithSchema sch sty t)
, A.HasAvroSchema (WithSchema sch sty t) )
=> Proxy sch -> KafkaProducer
-> ConduitT (ProducerRecord' ByteString t) Void m (Maybe X.KafkaError)
kafkaSinkAutoClose proxy prod
= mapC (toPR proxy) .| S.kafkaSinkAutoClose prod
| Creates a Sink for a given ` KafkaProducer ` .
kafkaSinkNoClose
:: ( MonadIO m
, ToSchema sch sty t
, A.ToAvro (WithSchema sch sty t)
, A.HasAvroSchema (WithSchema sch sty t) )
=> Proxy sch -> KafkaProducer
-> ConduitT (ProducerRecord' ByteString t) Void m (Maybe X.KafkaError)
kafkaSinkNoClose proxy prod
= mapC (toPR proxy) .| S.kafkaSinkNoClose prod
| Creates a batching Sink for a given ` KafkaProducer ` .
kafkaBatchSinkNoClose
:: ( MonadIO m
, ToSchema sch sty t
, A.ToAvro (WithSchema sch sty t)
, A.HasAvroSchema (WithSchema sch sty t) )
=> Proxy sch -> KafkaProducer
-> ConduitT [ProducerRecord' ByteString t] Void m [(ProducerRecord, KafkaError)]
kafkaBatchSinkNoClose proxy prod
= mapC (fmap (toPR proxy)) .| S.kafkaBatchSinkNoClose prod
|
143499f0c1efdd6ab633c418ba0357ce9bc6dfda87df18bfc0f7671a5d9dbb7a | haskell-opengl/OpenGLRaw | VertexShader.hs | # LANGUAGE PatternSynonyms #
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.EXT.VertexShader
Copyright : ( c ) 2019
-- License : BSD3
--
Maintainer : < >
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.EXT.VertexShader (
-- * Extension Support
glGetEXTVertexShader,
gl_EXT_vertex_shader,
-- * Enums
pattern GL_CURRENT_VERTEX_EXT,
pattern GL_FULL_RANGE_EXT,
pattern GL_INVARIANT_DATATYPE_EXT,
pattern GL_INVARIANT_EXT,
pattern GL_INVARIANT_VALUE_EXT,
pattern GL_LOCAL_CONSTANT_DATATYPE_EXT,
pattern GL_LOCAL_CONSTANT_EXT,
pattern GL_LOCAL_CONSTANT_VALUE_EXT,
pattern GL_LOCAL_EXT,
pattern GL_MATRIX_EXT,
pattern GL_MAX_OPTIMIZED_VERTEX_SHADER_INSTRUCTIONS_EXT,
pattern GL_MAX_OPTIMIZED_VERTEX_SHADER_INVARIANTS_EXT,
pattern GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCALS_EXT,
pattern GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCAL_CONSTANTS_EXT,
pattern GL_MAX_OPTIMIZED_VERTEX_SHADER_VARIANTS_EXT,
pattern GL_MAX_VERTEX_SHADER_INSTRUCTIONS_EXT,
pattern GL_MAX_VERTEX_SHADER_INVARIANTS_EXT,
pattern GL_MAX_VERTEX_SHADER_LOCALS_EXT,
pattern GL_MAX_VERTEX_SHADER_LOCAL_CONSTANTS_EXT,
pattern GL_MAX_VERTEX_SHADER_VARIANTS_EXT,
pattern GL_MVP_MATRIX_EXT,
pattern GL_NEGATIVE_ONE_EXT,
pattern GL_NEGATIVE_W_EXT,
pattern GL_NEGATIVE_X_EXT,
pattern GL_NEGATIVE_Y_EXT,
pattern GL_NEGATIVE_Z_EXT,
pattern GL_NORMALIZED_RANGE_EXT,
pattern GL_ONE_EXT,
pattern GL_OP_ADD_EXT,
pattern GL_OP_CLAMP_EXT,
pattern GL_OP_CROSS_PRODUCT_EXT,
pattern GL_OP_DOT3_EXT,
pattern GL_OP_DOT4_EXT,
pattern GL_OP_EXP_BASE_2_EXT,
pattern GL_OP_FLOOR_EXT,
pattern GL_OP_FRAC_EXT,
pattern GL_OP_INDEX_EXT,
pattern GL_OP_LOG_BASE_2_EXT,
pattern GL_OP_MADD_EXT,
pattern GL_OP_MAX_EXT,
pattern GL_OP_MIN_EXT,
pattern GL_OP_MOV_EXT,
pattern GL_OP_MULTIPLY_MATRIX_EXT,
pattern GL_OP_MUL_EXT,
pattern GL_OP_NEGATE_EXT,
pattern GL_OP_POWER_EXT,
pattern GL_OP_RECIP_EXT,
pattern GL_OP_RECIP_SQRT_EXT,
pattern GL_OP_ROUND_EXT,
pattern GL_OP_SET_GE_EXT,
pattern GL_OP_SET_LT_EXT,
pattern GL_OP_SUB_EXT,
pattern GL_OUTPUT_COLOR0_EXT,
pattern GL_OUTPUT_COLOR1_EXT,
pattern GL_OUTPUT_FOG_EXT,
pattern GL_OUTPUT_TEXTURE_COORD0_EXT,
pattern GL_OUTPUT_TEXTURE_COORD10_EXT,
pattern GL_OUTPUT_TEXTURE_COORD11_EXT,
pattern GL_OUTPUT_TEXTURE_COORD12_EXT,
pattern GL_OUTPUT_TEXTURE_COORD13_EXT,
pattern GL_OUTPUT_TEXTURE_COORD14_EXT,
pattern GL_OUTPUT_TEXTURE_COORD15_EXT,
pattern GL_OUTPUT_TEXTURE_COORD16_EXT,
pattern GL_OUTPUT_TEXTURE_COORD17_EXT,
pattern GL_OUTPUT_TEXTURE_COORD18_EXT,
pattern GL_OUTPUT_TEXTURE_COORD19_EXT,
pattern GL_OUTPUT_TEXTURE_COORD1_EXT,
pattern GL_OUTPUT_TEXTURE_COORD20_EXT,
pattern GL_OUTPUT_TEXTURE_COORD21_EXT,
pattern GL_OUTPUT_TEXTURE_COORD22_EXT,
pattern GL_OUTPUT_TEXTURE_COORD23_EXT,
pattern GL_OUTPUT_TEXTURE_COORD24_EXT,
pattern GL_OUTPUT_TEXTURE_COORD25_EXT,
pattern GL_OUTPUT_TEXTURE_COORD26_EXT,
pattern GL_OUTPUT_TEXTURE_COORD27_EXT,
pattern GL_OUTPUT_TEXTURE_COORD28_EXT,
pattern GL_OUTPUT_TEXTURE_COORD29_EXT,
pattern GL_OUTPUT_TEXTURE_COORD2_EXT,
pattern GL_OUTPUT_TEXTURE_COORD30_EXT,
pattern GL_OUTPUT_TEXTURE_COORD31_EXT,
pattern GL_OUTPUT_TEXTURE_COORD3_EXT,
pattern GL_OUTPUT_TEXTURE_COORD4_EXT,
pattern GL_OUTPUT_TEXTURE_COORD5_EXT,
pattern GL_OUTPUT_TEXTURE_COORD6_EXT,
pattern GL_OUTPUT_TEXTURE_COORD7_EXT,
pattern GL_OUTPUT_TEXTURE_COORD8_EXT,
pattern GL_OUTPUT_TEXTURE_COORD9_EXT,
pattern GL_OUTPUT_VERTEX_EXT,
pattern GL_SCALAR_EXT,
pattern GL_VARIANT_ARRAY_EXT,
pattern GL_VARIANT_ARRAY_POINTER_EXT,
pattern GL_VARIANT_ARRAY_STRIDE_EXT,
pattern GL_VARIANT_ARRAY_TYPE_EXT,
pattern GL_VARIANT_DATATYPE_EXT,
pattern GL_VARIANT_EXT,
pattern GL_VARIANT_VALUE_EXT,
pattern GL_VECTOR_EXT,
pattern GL_VERTEX_SHADER_BINDING_EXT,
pattern GL_VERTEX_SHADER_EXT,
pattern GL_VERTEX_SHADER_INSTRUCTIONS_EXT,
pattern GL_VERTEX_SHADER_INVARIANTS_EXT,
pattern GL_VERTEX_SHADER_LOCALS_EXT,
pattern GL_VERTEX_SHADER_LOCAL_CONSTANTS_EXT,
pattern GL_VERTEX_SHADER_OPTIMIZED_EXT,
pattern GL_VERTEX_SHADER_VARIANTS_EXT,
pattern GL_W_EXT,
pattern GL_X_EXT,
pattern GL_Y_EXT,
pattern GL_ZERO_EXT,
pattern GL_Z_EXT,
-- * Functions
glBeginVertexShaderEXT,
glBindLightParameterEXT,
glBindMaterialParameterEXT,
glBindParameterEXT,
glBindTexGenParameterEXT,
glBindTextureUnitParameterEXT,
glBindVertexShaderEXT,
glDeleteVertexShaderEXT,
glDisableVariantClientStateEXT,
glEnableVariantClientStateEXT,
glEndVertexShaderEXT,
glExtractComponentEXT,
glGenSymbolsEXT,
glGenVertexShadersEXT,
glGetInvariantBooleanvEXT,
glGetInvariantFloatvEXT,
glGetInvariantIntegervEXT,
glGetLocalConstantBooleanvEXT,
glGetLocalConstantFloatvEXT,
glGetLocalConstantIntegervEXT,
glGetVariantBooleanvEXT,
glGetVariantFloatvEXT,
glGetVariantIntegervEXT,
glGetVariantPointervEXT,
glInsertComponentEXT,
glIsVariantEnabledEXT,
glSetInvariantEXT,
glSetLocalConstantEXT,
glShaderOp1EXT,
glShaderOp2EXT,
glShaderOp3EXT,
glSwizzleEXT,
glVariantPointerEXT,
glVariantbvEXT,
glVariantdvEXT,
glVariantfvEXT,
glVariantivEXT,
glVariantsvEXT,
glVariantubvEXT,
glVariantuivEXT,
glVariantusvEXT,
glWriteMaskEXT
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| null | https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/EXT/VertexShader.hs | haskell | ------------------------------------------------------------------------------
|
Module : Graphics.GL.EXT.VertexShader
License : BSD3
Stability : stable
Portability : portable
------------------------------------------------------------------------------
* Extension Support
* Enums
* Functions | # LANGUAGE PatternSynonyms #
Copyright : ( c ) 2019
Maintainer : < >
module Graphics.GL.EXT.VertexShader (
glGetEXTVertexShader,
gl_EXT_vertex_shader,
pattern GL_CURRENT_VERTEX_EXT,
pattern GL_FULL_RANGE_EXT,
pattern GL_INVARIANT_DATATYPE_EXT,
pattern GL_INVARIANT_EXT,
pattern GL_INVARIANT_VALUE_EXT,
pattern GL_LOCAL_CONSTANT_DATATYPE_EXT,
pattern GL_LOCAL_CONSTANT_EXT,
pattern GL_LOCAL_CONSTANT_VALUE_EXT,
pattern GL_LOCAL_EXT,
pattern GL_MATRIX_EXT,
pattern GL_MAX_OPTIMIZED_VERTEX_SHADER_INSTRUCTIONS_EXT,
pattern GL_MAX_OPTIMIZED_VERTEX_SHADER_INVARIANTS_EXT,
pattern GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCALS_EXT,
pattern GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCAL_CONSTANTS_EXT,
pattern GL_MAX_OPTIMIZED_VERTEX_SHADER_VARIANTS_EXT,
pattern GL_MAX_VERTEX_SHADER_INSTRUCTIONS_EXT,
pattern GL_MAX_VERTEX_SHADER_INVARIANTS_EXT,
pattern GL_MAX_VERTEX_SHADER_LOCALS_EXT,
pattern GL_MAX_VERTEX_SHADER_LOCAL_CONSTANTS_EXT,
pattern GL_MAX_VERTEX_SHADER_VARIANTS_EXT,
pattern GL_MVP_MATRIX_EXT,
pattern GL_NEGATIVE_ONE_EXT,
pattern GL_NEGATIVE_W_EXT,
pattern GL_NEGATIVE_X_EXT,
pattern GL_NEGATIVE_Y_EXT,
pattern GL_NEGATIVE_Z_EXT,
pattern GL_NORMALIZED_RANGE_EXT,
pattern GL_ONE_EXT,
pattern GL_OP_ADD_EXT,
pattern GL_OP_CLAMP_EXT,
pattern GL_OP_CROSS_PRODUCT_EXT,
pattern GL_OP_DOT3_EXT,
pattern GL_OP_DOT4_EXT,
pattern GL_OP_EXP_BASE_2_EXT,
pattern GL_OP_FLOOR_EXT,
pattern GL_OP_FRAC_EXT,
pattern GL_OP_INDEX_EXT,
pattern GL_OP_LOG_BASE_2_EXT,
pattern GL_OP_MADD_EXT,
pattern GL_OP_MAX_EXT,
pattern GL_OP_MIN_EXT,
pattern GL_OP_MOV_EXT,
pattern GL_OP_MULTIPLY_MATRIX_EXT,
pattern GL_OP_MUL_EXT,
pattern GL_OP_NEGATE_EXT,
pattern GL_OP_POWER_EXT,
pattern GL_OP_RECIP_EXT,
pattern GL_OP_RECIP_SQRT_EXT,
pattern GL_OP_ROUND_EXT,
pattern GL_OP_SET_GE_EXT,
pattern GL_OP_SET_LT_EXT,
pattern GL_OP_SUB_EXT,
pattern GL_OUTPUT_COLOR0_EXT,
pattern GL_OUTPUT_COLOR1_EXT,
pattern GL_OUTPUT_FOG_EXT,
pattern GL_OUTPUT_TEXTURE_COORD0_EXT,
pattern GL_OUTPUT_TEXTURE_COORD10_EXT,
pattern GL_OUTPUT_TEXTURE_COORD11_EXT,
pattern GL_OUTPUT_TEXTURE_COORD12_EXT,
pattern GL_OUTPUT_TEXTURE_COORD13_EXT,
pattern GL_OUTPUT_TEXTURE_COORD14_EXT,
pattern GL_OUTPUT_TEXTURE_COORD15_EXT,
pattern GL_OUTPUT_TEXTURE_COORD16_EXT,
pattern GL_OUTPUT_TEXTURE_COORD17_EXT,
pattern GL_OUTPUT_TEXTURE_COORD18_EXT,
pattern GL_OUTPUT_TEXTURE_COORD19_EXT,
pattern GL_OUTPUT_TEXTURE_COORD1_EXT,
pattern GL_OUTPUT_TEXTURE_COORD20_EXT,
pattern GL_OUTPUT_TEXTURE_COORD21_EXT,
pattern GL_OUTPUT_TEXTURE_COORD22_EXT,
pattern GL_OUTPUT_TEXTURE_COORD23_EXT,
pattern GL_OUTPUT_TEXTURE_COORD24_EXT,
pattern GL_OUTPUT_TEXTURE_COORD25_EXT,
pattern GL_OUTPUT_TEXTURE_COORD26_EXT,
pattern GL_OUTPUT_TEXTURE_COORD27_EXT,
pattern GL_OUTPUT_TEXTURE_COORD28_EXT,
pattern GL_OUTPUT_TEXTURE_COORD29_EXT,
pattern GL_OUTPUT_TEXTURE_COORD2_EXT,
pattern GL_OUTPUT_TEXTURE_COORD30_EXT,
pattern GL_OUTPUT_TEXTURE_COORD31_EXT,
pattern GL_OUTPUT_TEXTURE_COORD3_EXT,
pattern GL_OUTPUT_TEXTURE_COORD4_EXT,
pattern GL_OUTPUT_TEXTURE_COORD5_EXT,
pattern GL_OUTPUT_TEXTURE_COORD6_EXT,
pattern GL_OUTPUT_TEXTURE_COORD7_EXT,
pattern GL_OUTPUT_TEXTURE_COORD8_EXT,
pattern GL_OUTPUT_TEXTURE_COORD9_EXT,
pattern GL_OUTPUT_VERTEX_EXT,
pattern GL_SCALAR_EXT,
pattern GL_VARIANT_ARRAY_EXT,
pattern GL_VARIANT_ARRAY_POINTER_EXT,
pattern GL_VARIANT_ARRAY_STRIDE_EXT,
pattern GL_VARIANT_ARRAY_TYPE_EXT,
pattern GL_VARIANT_DATATYPE_EXT,
pattern GL_VARIANT_EXT,
pattern GL_VARIANT_VALUE_EXT,
pattern GL_VECTOR_EXT,
pattern GL_VERTEX_SHADER_BINDING_EXT,
pattern GL_VERTEX_SHADER_EXT,
pattern GL_VERTEX_SHADER_INSTRUCTIONS_EXT,
pattern GL_VERTEX_SHADER_INVARIANTS_EXT,
pattern GL_VERTEX_SHADER_LOCALS_EXT,
pattern GL_VERTEX_SHADER_LOCAL_CONSTANTS_EXT,
pattern GL_VERTEX_SHADER_OPTIMIZED_EXT,
pattern GL_VERTEX_SHADER_VARIANTS_EXT,
pattern GL_W_EXT,
pattern GL_X_EXT,
pattern GL_Y_EXT,
pattern GL_ZERO_EXT,
pattern GL_Z_EXT,
glBeginVertexShaderEXT,
glBindLightParameterEXT,
glBindMaterialParameterEXT,
glBindParameterEXT,
glBindTexGenParameterEXT,
glBindTextureUnitParameterEXT,
glBindVertexShaderEXT,
glDeleteVertexShaderEXT,
glDisableVariantClientStateEXT,
glEnableVariantClientStateEXT,
glEndVertexShaderEXT,
glExtractComponentEXT,
glGenSymbolsEXT,
glGenVertexShadersEXT,
glGetInvariantBooleanvEXT,
glGetInvariantFloatvEXT,
glGetInvariantIntegervEXT,
glGetLocalConstantBooleanvEXT,
glGetLocalConstantFloatvEXT,
glGetLocalConstantIntegervEXT,
glGetVariantBooleanvEXT,
glGetVariantFloatvEXT,
glGetVariantIntegervEXT,
glGetVariantPointervEXT,
glInsertComponentEXT,
glIsVariantEnabledEXT,
glSetInvariantEXT,
glSetLocalConstantEXT,
glShaderOp1EXT,
glShaderOp2EXT,
glShaderOp3EXT,
glSwizzleEXT,
glVariantPointerEXT,
glVariantbvEXT,
glVariantdvEXT,
glVariantfvEXT,
glVariantivEXT,
glVariantsvEXT,
glVariantubvEXT,
glVariantuivEXT,
glVariantusvEXT,
glWriteMaskEXT
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
|
c601ee04b20904e1af6427c06338b408b4e724b8424f082a7afe99bc3bf1431a | ScottBrooks/Erlcraft | mc_world.erl | -module(mc_world).
-behaviour(gen_server).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-record(state, {world_path, world, chunk_store, block_store, clients, world_updates}).
-define(SERVER_TIMEOUT, 30000).
%% External API
-export([start_link/1, get_chunk/3, get_spawn/0, load_chunk/5, dbg_chunk/3, block_dig/6, register_client/2]).
generate_pre_chunk(X,Z, Update) ->
mc_util:write_packet(16#32, [{int, X}, {int, Z}, {bool, Update}]).
block_from_bin(Binary, Offset) ->
<<_:Offset/binary, Block:8/integer, _/binary>> = Binary,
Block.
block_from_bin_packed(Binary, Offset) ->
AdjOffset = Offset * 4,
<<_:AdjOffset/bits, Block:8/integer, _/bits>> = Binary,
Block bsr 4.
generate_chunk(X , Y , Z , SizeX , SizeY , ) - >
% Data = mc_util:chunk_data(SizeX * SizeY * SizeX),
Compressed = zlib : compress(mc_util : encode_list(Data ) ) ,
mc_util : write_packet(16#33 , lists : flatten([{int , X*16 } , { short , Y } , { int , } , { byte , SizeX-1 } , { byte , SizeY-1 } , { byte , SizeZ-1 } , { int , size(Compressed ) } , { binary , Compressed } ] ) ) .
block_dig(State, _X, _Y, _Z, _Direction, _Client, _ChunkStore) when State =:= 0 ->
ok;
block_dig(State, _X, _Y, _Z, _Direction, _Client, _ChunkStore) when State =:= 1 ->
ok;
block_dig(State, _X, _Y, _Z, _Direction, _Client, _ChunkStore) when State =:= 2 ->
ok;
block_dig(State, X, Y, Z, Direction, _Client, ChunkStore) when State =:= 3 ->
io:format("Dig: S: ~p [~p,~p,~p], D: ~p~n", [State, X, Y, Z, Direction]),
Key = {X, Z},
case ets:lookup(ChunkStore, Key) of
[] ->
io:format("Key: ~p not found[~p,~p,~p]~n", [Key, X, Y, Z]);
[{Key, BD, MD, WL}] ->
Offset = Y,
HalfOffset = trunc(Y/2),
Block = block_from_bin(BD, Offset),
Meta = block_from_bin_packed(MD, HalfOffset),
io:format("B: ~p M: ~p~n", [Block, Meta]),
<<Before:Offset/binary, Block:8/integer, After/binary>> = BD,
NBD = <<Before/binary, 0:8/integer, After/binary>>,
ets:insert(ChunkStore, {Key, NBD, MD, WL}),
% Random location inside the block that was broken
RX = X * 32 + 8 + random:uniform() * 16,
RZ = Z * 32 + 8 + random:uniform() * 16,
[{block, X, Y, Z, 0, 8}, {spawn, random:uniform(8192), Block, 1, RX, (Y+1) * 32, RZ, 0, 0, 0}];
Else ->
io:format("unknown: ~p key: ~p~n", [Else, Key]),
ok
end.
load_chunk(X, Y, Z, Root, ChunkStore) ->
SizeX = 16, SizeY = 128, SizeZ = 16,
[BlockData, MetaData, LightData] = try ets:member(ChunkStore, {X*16, Z*16}) of
true -> load_chunk_ets(X, Y, Z, ChunkStore);
false-> load_chunk_disk(X, Y, Z, Root, ChunkStore)
catch _:_ ->
load_chunk_disk(X, Y, Z, Root, ChunkStore)
end,
Compressed = zlib:compress(<<BlockData/binary, MetaData/binary, MetaData/binary, LightData/binary>>),
mc_util:write_packet(16#33, lists:flatten([{int, X*16}, {short, Y}, {int, Z*16}, {byte, SizeX-1}, {byte, SizeY-1}, {byte, SizeZ-1}, {int, size(Compressed)}, {binary, Compressed}])).
load_chunk_ets(X, _Y, Z, ChunkStore) ->
lists:foldl(fun(Idx, [Blocks, Meta, Light]) ->
OZ = Idx rem 16,
OX = trunc(Idx/16),
case ets:lookup(ChunkStore, {X * 16 + OX, Z * 16 + OZ}) of
[{{_,_}, BD, MD, WL}] ->
[<<Blocks/binary, BD/binary>>, <<Meta/binary, MD/binary>>, <<Light/binary, WL/binary>>];
_ -> io:format("Could not find key: [~p,~p]", [X*16 + OX, Z*16 + OZ])
end
end, [<<>>, <<>>, <<>>], lists:seq(0, 255)).
load_chunk_disk(X, _Y, Z, Root, ChunkStore) ->
F1 = string:to_lower(case X of
PosX when PosX >= 0 ->
erlang:integer_to_list(X rem 64, 36);
_ ->
erlang:integer_to_list((64+X) rem 64, 36)
end),
F2 = string:to_lower(case Z of
PosZ when PosZ >= 0 ->
erlang:integer_to_list(Z rem 64, 36);
_ ->
erlang:integer_to_list((64+Z) rem 64, 36)
end),
FileName = string:to_lower(string:join(["c", erlang:integer_to_list(X, 36), erlang:integer_to_list(Z, 36), "dat"], ".")),
Path = string:join([Root, F1, F2, FileName], "/"),
Data = nbt:load_file(Path),
{tag_compound, <<"Level">>, LevelData} = Data,
{tag_byte_array, <<"Blocks">>, Blocks} = lists:keyfind(<<"Blocks">>, 2, LevelData),
{tag_byte_array, <<"BlockLight">>, BlockLight} = lists:keyfind(<<"BlockLight">>, 2, LevelData),
{tag_byte_array, <<"SkyLight">>, SkyLight} = lists:keyfind(<<"SkyLight">>, 2, LevelData),
{tag_byte_array, <<"Data">>, MetaData} = lists:keyfind(<<"Data">>, 2, LevelData),
WorldLight = mc_util:or_binaries(BlockLight, SkyLight),
lists:foreach(fun(Idx) ->
BlockIdx = Idx * 128,
MetaIdx = Idx * 64,
OZ = Idx rem 16,
OX = trunc(Idx/16),
<<_:BlockIdx/binary, BD:128/binary, _/binary>> = Blocks,
<<_:MetaIdx/binary, MD:64/binary, _/binary>> = MetaData,
<<_:MetaIdx/binary, WL:64/binary, _/binary>> = WorldLight,
true = ets:insert(ChunkStore, {{X * 16 + OX,Z * 16 + OZ}, BD, MD, WL})
end, lists:seq(0, 255)),
io:format("Wrote [~p,~p] to [~p, ~p]~n", [X*16, Z*16, X*16+16, Z*16+16]),
[Blocks, MetaData, WorldLight].
dbg_chunk(<<>>, <<>>, <<>>) ->
ok;
dbg_chunk(Blocks, MetaData, LightData) ->
<<Block:8/integer, RestBlocks/binary>> = Blocks,
io : format("Block : ~p ~ n " , [ Block ] ) ,
<<Meta:8/integer, RestMeta/binary>> = MetaData,
%io:format("Meta: ~p~n", [Meta]),
<<Light:4/bits, RestLight/bits>> = LightData,
io : format("Light : ~p ~ n " , [ Light ] ) ,
case Block of
71 ->
io:format("Iron door: ~p M: ~p L: ~p~n", [Block, Meta, Light]);
65 ->
io:format("Ladder: ~p M: ~p L: ~p~n", [Block, Meta, Light]);
50 ->
io:format("Torch: ~p M: ~p L: ~p~n", [Block, Meta, Light]);
_ -> ok
end,
dbg_chunk(RestBlocks, RestMeta, RestLight).
block_dig(Stage, X, Y, Z, Direction, Client) ->
gen_server:call(?MODULE, {block_dig, Stage, X, Y, Z, Direction, Client}, ?SERVER_TIMEOUT).
get_spawn() ->
gen_server:call(?MODULE, {get_spawn}, ?SERVER_TIMEOUT).
get_chunk(X,Y,Z) ->
gen_server:call(?MODULE, {get_chunk, trunc(X), trunc(Y), trunc(Z)}, ?SERVER_TIMEOUT).
register_client(Client, Details) ->
gen_server:call(?MODULE, {register_client, Client, Details}, ?SERVER_TIMEOUT).
start_link(World) ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [World], []).
%% gen_server events
init([MapName]) ->
io:format("World Server started~n", []),
{ok, Cwd} = file:get_cwd(),
Path = string:join([Cwd, MapName] , "/"),
LevelPath = string:join([Path, "level.dat"], "/"),
World = nbt:load_file(LevelPath),
ChunkStore = ets:new(world, []),
BlockStore = ets:new(blocks, []),
timer:send_after(500, flush_world_updates),
{ok, #state{world_path = Path, world = World, chunk_store = ChunkStore, clients = [], world_updates = [], block_store = BlockStore}}.
handle_call({register_client, Client, Details}, _From, #state{clients = Clients} = State) when is_pid(Client) ->
lists:foreach(fun(C) ->
{client, ClientPid} = C,
{client_details, ID, Name, X, Y, Z, R, P, I} = Details,
io:format("Sending named spawn[~p]: ~p to ~p~n", [ID, Name, ClientPid]),
gen_server:cast(ClientPid, {packet, mc_reply:named_spawn(ID, Name, X ,Y, Z, R, P, I)})
end, Clients),
NewClients = lists:keystore(Client, 2, Clients, {client, Client}),
io:format("Registering client: ~p~n", [Client]),
{reply, ok, State#state{clients = NewClients}};
handle_call({get_chunk, X, Y, Z}, _From, #state{world_path = WorldPath, chunk_store = ChunkStore} = State) when is_integer(X), is_integer(Z) ->
io:format("Chunk Request: [~p, ~p, ~p]~n", [X, Y, Z]),
PreChunk = generate_pre_chunk(X, Z, 1),
ChunkData = generate_chunk(X , Y , Z , 16 , 128 , 16 ) ,
ChunkData = load_chunk(X, Y, Z, WorldPath, ChunkStore),
{reply, {chunk, PreChunk, ChunkData}, State};
handle_call({get_spawn}, _From, #state{world = World} = State) ->
{tag_compound, <<"Data">>, Data} = World,
{SX, SY, SZ} = case lists:keyfind(<<"Player">>, 2, Data) of
{tag_compound, <<"Player">>, PlayerInfo} ->
{tag_list, <<"Pos">>, _, [SpawnX, SpawnY, SpawnZ]} = lists:keyfind(<<"Pos">>, 2, PlayerInfo),
{SpawnX, SpawnY, SpawnZ};
_ ->
SpawnX = case lists:keyfind(<<"SpawnX">>, 2, Data) of
{tag_int, <<"SpawnX">>, X} -> X;
_ -> 0
end,
SpawnY = case lists:keyfind(<<"SpawnY">>, 2, Data) of
{tag_int, <<"SpawnY">>, Y} -> Y;
_ -> 96
end,
SpawnZ = case lists:keyfind(<<"SpawnZ">>, 2, Data) of
{tag_int, <<"SpawnZ">>, Z} -> Z;
_ -> 0
end,
{SpawnX, SpawnY, SpawnZ}
end,
io:format("Spawning player at: [~p, ~p, ~p]~n", [SpawnX, SpawnY, SpawnZ]),
{reply, {loc, SX, SY, SZ, SY - 1.5, 0.0, 0.0}, State};
handle_call({block_dig, Stage, X, Y, Z, Direction, Client}, _From, #state{chunk_store = ChunkStore, world_updates = WorldUpdates} = State) ->
NewUpdates = case block_dig(Stage, X, Y, Z, Direction, Client, ChunkStore) of
ok ->
WorldUpdates;
Update -> lists:flatten([Update | WorldUpdates])
end,
{reply, none, State#state{world_updates = NewUpdates}};
handle_call(_Request, _From, _State) ->
io:format("Call: ~p~n", [_Request]),
{reply, none, _State}.
handle_cast(_Request, _State) ->
io:format("Cast: ~p~n", [_Request]),
{noreply, _State}.
handle_info(flush_world_updates, #state{clients = Clients, world_updates = WorldUpdates, block_store = BlockStore} = State) ->
lists:foreach(fun(Item) ->
Packet = case Item of
{block, X, Y, Z, Type, Meta} ->
mc_reply:block_change(trunc(X), trunc(Y), trunc(Z), Type, Meta);
{spawn, ID, ItemID, U1, X, Y, Z, R, P, U2} ->
Key = {trunc(X/32), trunc(Z/32)},
io:format("Spawn block at: ~p~n", [Key]),
case ets:lookup(BlockStore, Key) of
[] ->
ets:insert(BlockStore, {Key, [{ID, ItemID}]});
{Key, Values} ->
ets:insert(BlockStore, {Key, [{ID, ItemID}|Values]})
end,
mc_reply:item_spawn(ID, ItemID, U1, trunc(X), trunc(Y), trunc(Z), R, P, U2)
end,
lists:foreach(fun(Client) ->
{client, ClientPid} = Client,
gen_server:cast(ClientPid, {packet, Packet})
end, Clients)
end, WorldUpdates),
BlocksSent = lists:foldl(fun(Client, Acc) ->
{client, ClientPid} = Client,
{loc, X, _Y, Z} = gen_server:call(ClientPid, {get_location}, infinity),
Key = {trunc(X), trunc(Z)},
io:format("Key: ~p~n", [Key]),
case ets:lookup(BlockStore, Key) of
[{Key, Values}] ->
io:format("Found block for client~n", []),
[gen_server:cast(ClientPid, {give_item, ID, ItemID}) || {ID, ItemID} <- Values],
[Key | Acc];
_ -> Acc
end
end, [], Clients),
[ets:delete(BlockStore, Key) || Key <- BlocksSent],
timer:send_after(500, flush_world_updates),
{noreply, State#state{world_updates = []}};
handle_info(_Info, _State) ->
io:format("Info: ~p~n", [_Info]),
{noreply, _State}.
terminate(_Reason, _State) ->
io:format("Term: ~p~n", [_Reason]),
normal.
code_change(_OldVsn, _State, _Extra) ->
{ok, _State}.
%%
%% Tests
%%
-include_lib("eunit/include/eunit.hrl").
-ifdef(TEST).
-endif.
| null | https://raw.githubusercontent.com/ScottBrooks/Erlcraft/ed336eb8da4d83e937687ce34feecb76b4128288/src/mc_world.erl | erlang | External API
Data = mc_util:chunk_data(SizeX * SizeY * SizeX),
Random location inside the block that was broken
io:format("Meta: ~p~n", [Meta]),
gen_server events
Tests
| -module(mc_world).
-behaviour(gen_server).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-record(state, {world_path, world, chunk_store, block_store, clients, world_updates}).
-define(SERVER_TIMEOUT, 30000).
-export([start_link/1, get_chunk/3, get_spawn/0, load_chunk/5, dbg_chunk/3, block_dig/6, register_client/2]).
generate_pre_chunk(X,Z, Update) ->
mc_util:write_packet(16#32, [{int, X}, {int, Z}, {bool, Update}]).
block_from_bin(Binary, Offset) ->
<<_:Offset/binary, Block:8/integer, _/binary>> = Binary,
Block.
block_from_bin_packed(Binary, Offset) ->
AdjOffset = Offset * 4,
<<_:AdjOffset/bits, Block:8/integer, _/bits>> = Binary,
Block bsr 4.
generate_chunk(X , Y , Z , SizeX , SizeY , ) - >
Compressed = zlib : compress(mc_util : encode_list(Data ) ) ,
mc_util : write_packet(16#33 , lists : flatten([{int , X*16 } , { short , Y } , { int , } , { byte , SizeX-1 } , { byte , SizeY-1 } , { byte , SizeZ-1 } , { int , size(Compressed ) } , { binary , Compressed } ] ) ) .
block_dig(State, _X, _Y, _Z, _Direction, _Client, _ChunkStore) when State =:= 0 ->
ok;
block_dig(State, _X, _Y, _Z, _Direction, _Client, _ChunkStore) when State =:= 1 ->
ok;
block_dig(State, _X, _Y, _Z, _Direction, _Client, _ChunkStore) when State =:= 2 ->
ok;
block_dig(State, X, Y, Z, Direction, _Client, ChunkStore) when State =:= 3 ->
io:format("Dig: S: ~p [~p,~p,~p], D: ~p~n", [State, X, Y, Z, Direction]),
Key = {X, Z},
case ets:lookup(ChunkStore, Key) of
[] ->
io:format("Key: ~p not found[~p,~p,~p]~n", [Key, X, Y, Z]);
[{Key, BD, MD, WL}] ->
Offset = Y,
HalfOffset = trunc(Y/2),
Block = block_from_bin(BD, Offset),
Meta = block_from_bin_packed(MD, HalfOffset),
io:format("B: ~p M: ~p~n", [Block, Meta]),
<<Before:Offset/binary, Block:8/integer, After/binary>> = BD,
NBD = <<Before/binary, 0:8/integer, After/binary>>,
ets:insert(ChunkStore, {Key, NBD, MD, WL}),
RX = X * 32 + 8 + random:uniform() * 16,
RZ = Z * 32 + 8 + random:uniform() * 16,
[{block, X, Y, Z, 0, 8}, {spawn, random:uniform(8192), Block, 1, RX, (Y+1) * 32, RZ, 0, 0, 0}];
Else ->
io:format("unknown: ~p key: ~p~n", [Else, Key]),
ok
end.
load_chunk(X, Y, Z, Root, ChunkStore) ->
SizeX = 16, SizeY = 128, SizeZ = 16,
[BlockData, MetaData, LightData] = try ets:member(ChunkStore, {X*16, Z*16}) of
true -> load_chunk_ets(X, Y, Z, ChunkStore);
false-> load_chunk_disk(X, Y, Z, Root, ChunkStore)
catch _:_ ->
load_chunk_disk(X, Y, Z, Root, ChunkStore)
end,
Compressed = zlib:compress(<<BlockData/binary, MetaData/binary, MetaData/binary, LightData/binary>>),
mc_util:write_packet(16#33, lists:flatten([{int, X*16}, {short, Y}, {int, Z*16}, {byte, SizeX-1}, {byte, SizeY-1}, {byte, SizeZ-1}, {int, size(Compressed)}, {binary, Compressed}])).
load_chunk_ets(X, _Y, Z, ChunkStore) ->
lists:foldl(fun(Idx, [Blocks, Meta, Light]) ->
OZ = Idx rem 16,
OX = trunc(Idx/16),
case ets:lookup(ChunkStore, {X * 16 + OX, Z * 16 + OZ}) of
[{{_,_}, BD, MD, WL}] ->
[<<Blocks/binary, BD/binary>>, <<Meta/binary, MD/binary>>, <<Light/binary, WL/binary>>];
_ -> io:format("Could not find key: [~p,~p]", [X*16 + OX, Z*16 + OZ])
end
end, [<<>>, <<>>, <<>>], lists:seq(0, 255)).
load_chunk_disk(X, _Y, Z, Root, ChunkStore) ->
F1 = string:to_lower(case X of
PosX when PosX >= 0 ->
erlang:integer_to_list(X rem 64, 36);
_ ->
erlang:integer_to_list((64+X) rem 64, 36)
end),
F2 = string:to_lower(case Z of
PosZ when PosZ >= 0 ->
erlang:integer_to_list(Z rem 64, 36);
_ ->
erlang:integer_to_list((64+Z) rem 64, 36)
end),
FileName = string:to_lower(string:join(["c", erlang:integer_to_list(X, 36), erlang:integer_to_list(Z, 36), "dat"], ".")),
Path = string:join([Root, F1, F2, FileName], "/"),
Data = nbt:load_file(Path),
{tag_compound, <<"Level">>, LevelData} = Data,
{tag_byte_array, <<"Blocks">>, Blocks} = lists:keyfind(<<"Blocks">>, 2, LevelData),
{tag_byte_array, <<"BlockLight">>, BlockLight} = lists:keyfind(<<"BlockLight">>, 2, LevelData),
{tag_byte_array, <<"SkyLight">>, SkyLight} = lists:keyfind(<<"SkyLight">>, 2, LevelData),
{tag_byte_array, <<"Data">>, MetaData} = lists:keyfind(<<"Data">>, 2, LevelData),
WorldLight = mc_util:or_binaries(BlockLight, SkyLight),
lists:foreach(fun(Idx) ->
BlockIdx = Idx * 128,
MetaIdx = Idx * 64,
OZ = Idx rem 16,
OX = trunc(Idx/16),
<<_:BlockIdx/binary, BD:128/binary, _/binary>> = Blocks,
<<_:MetaIdx/binary, MD:64/binary, _/binary>> = MetaData,
<<_:MetaIdx/binary, WL:64/binary, _/binary>> = WorldLight,
true = ets:insert(ChunkStore, {{X * 16 + OX,Z * 16 + OZ}, BD, MD, WL})
end, lists:seq(0, 255)),
io:format("Wrote [~p,~p] to [~p, ~p]~n", [X*16, Z*16, X*16+16, Z*16+16]),
[Blocks, MetaData, WorldLight].
dbg_chunk(<<>>, <<>>, <<>>) ->
ok;
dbg_chunk(Blocks, MetaData, LightData) ->
<<Block:8/integer, RestBlocks/binary>> = Blocks,
io : format("Block : ~p ~ n " , [ Block ] ) ,
<<Meta:8/integer, RestMeta/binary>> = MetaData,
<<Light:4/bits, RestLight/bits>> = LightData,
io : format("Light : ~p ~ n " , [ Light ] ) ,
case Block of
71 ->
io:format("Iron door: ~p M: ~p L: ~p~n", [Block, Meta, Light]);
65 ->
io:format("Ladder: ~p M: ~p L: ~p~n", [Block, Meta, Light]);
50 ->
io:format("Torch: ~p M: ~p L: ~p~n", [Block, Meta, Light]);
_ -> ok
end,
dbg_chunk(RestBlocks, RestMeta, RestLight).
block_dig(Stage, X, Y, Z, Direction, Client) ->
gen_server:call(?MODULE, {block_dig, Stage, X, Y, Z, Direction, Client}, ?SERVER_TIMEOUT).
get_spawn() ->
gen_server:call(?MODULE, {get_spawn}, ?SERVER_TIMEOUT).
get_chunk(X,Y,Z) ->
gen_server:call(?MODULE, {get_chunk, trunc(X), trunc(Y), trunc(Z)}, ?SERVER_TIMEOUT).
register_client(Client, Details) ->
gen_server:call(?MODULE, {register_client, Client, Details}, ?SERVER_TIMEOUT).
start_link(World) ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [World], []).
init([MapName]) ->
io:format("World Server started~n", []),
{ok, Cwd} = file:get_cwd(),
Path = string:join([Cwd, MapName] , "/"),
LevelPath = string:join([Path, "level.dat"], "/"),
World = nbt:load_file(LevelPath),
ChunkStore = ets:new(world, []),
BlockStore = ets:new(blocks, []),
timer:send_after(500, flush_world_updates),
{ok, #state{world_path = Path, world = World, chunk_store = ChunkStore, clients = [], world_updates = [], block_store = BlockStore}}.
handle_call({register_client, Client, Details}, _From, #state{clients = Clients} = State) when is_pid(Client) ->
lists:foreach(fun(C) ->
{client, ClientPid} = C,
{client_details, ID, Name, X, Y, Z, R, P, I} = Details,
io:format("Sending named spawn[~p]: ~p to ~p~n", [ID, Name, ClientPid]),
gen_server:cast(ClientPid, {packet, mc_reply:named_spawn(ID, Name, X ,Y, Z, R, P, I)})
end, Clients),
NewClients = lists:keystore(Client, 2, Clients, {client, Client}),
io:format("Registering client: ~p~n", [Client]),
{reply, ok, State#state{clients = NewClients}};
handle_call({get_chunk, X, Y, Z}, _From, #state{world_path = WorldPath, chunk_store = ChunkStore} = State) when is_integer(X), is_integer(Z) ->
io:format("Chunk Request: [~p, ~p, ~p]~n", [X, Y, Z]),
PreChunk = generate_pre_chunk(X, Z, 1),
ChunkData = generate_chunk(X , Y , Z , 16 , 128 , 16 ) ,
ChunkData = load_chunk(X, Y, Z, WorldPath, ChunkStore),
{reply, {chunk, PreChunk, ChunkData}, State};
handle_call({get_spawn}, _From, #state{world = World} = State) ->
{tag_compound, <<"Data">>, Data} = World,
{SX, SY, SZ} = case lists:keyfind(<<"Player">>, 2, Data) of
{tag_compound, <<"Player">>, PlayerInfo} ->
{tag_list, <<"Pos">>, _, [SpawnX, SpawnY, SpawnZ]} = lists:keyfind(<<"Pos">>, 2, PlayerInfo),
{SpawnX, SpawnY, SpawnZ};
_ ->
SpawnX = case lists:keyfind(<<"SpawnX">>, 2, Data) of
{tag_int, <<"SpawnX">>, X} -> X;
_ -> 0
end,
SpawnY = case lists:keyfind(<<"SpawnY">>, 2, Data) of
{tag_int, <<"SpawnY">>, Y} -> Y;
_ -> 96
end,
SpawnZ = case lists:keyfind(<<"SpawnZ">>, 2, Data) of
{tag_int, <<"SpawnZ">>, Z} -> Z;
_ -> 0
end,
{SpawnX, SpawnY, SpawnZ}
end,
io:format("Spawning player at: [~p, ~p, ~p]~n", [SpawnX, SpawnY, SpawnZ]),
{reply, {loc, SX, SY, SZ, SY - 1.5, 0.0, 0.0}, State};
handle_call({block_dig, Stage, X, Y, Z, Direction, Client}, _From, #state{chunk_store = ChunkStore, world_updates = WorldUpdates} = State) ->
NewUpdates = case block_dig(Stage, X, Y, Z, Direction, Client, ChunkStore) of
ok ->
WorldUpdates;
Update -> lists:flatten([Update | WorldUpdates])
end,
{reply, none, State#state{world_updates = NewUpdates}};
handle_call(_Request, _From, _State) ->
io:format("Call: ~p~n", [_Request]),
{reply, none, _State}.
handle_cast(_Request, _State) ->
io:format("Cast: ~p~n", [_Request]),
{noreply, _State}.
handle_info(flush_world_updates, #state{clients = Clients, world_updates = WorldUpdates, block_store = BlockStore} = State) ->
lists:foreach(fun(Item) ->
Packet = case Item of
{block, X, Y, Z, Type, Meta} ->
mc_reply:block_change(trunc(X), trunc(Y), trunc(Z), Type, Meta);
{spawn, ID, ItemID, U1, X, Y, Z, R, P, U2} ->
Key = {trunc(X/32), trunc(Z/32)},
io:format("Spawn block at: ~p~n", [Key]),
case ets:lookup(BlockStore, Key) of
[] ->
ets:insert(BlockStore, {Key, [{ID, ItemID}]});
{Key, Values} ->
ets:insert(BlockStore, {Key, [{ID, ItemID}|Values]})
end,
mc_reply:item_spawn(ID, ItemID, U1, trunc(X), trunc(Y), trunc(Z), R, P, U2)
end,
lists:foreach(fun(Client) ->
{client, ClientPid} = Client,
gen_server:cast(ClientPid, {packet, Packet})
end, Clients)
end, WorldUpdates),
BlocksSent = lists:foldl(fun(Client, Acc) ->
{client, ClientPid} = Client,
{loc, X, _Y, Z} = gen_server:call(ClientPid, {get_location}, infinity),
Key = {trunc(X), trunc(Z)},
io:format("Key: ~p~n", [Key]),
case ets:lookup(BlockStore, Key) of
[{Key, Values}] ->
io:format("Found block for client~n", []),
[gen_server:cast(ClientPid, {give_item, ID, ItemID}) || {ID, ItemID} <- Values],
[Key | Acc];
_ -> Acc
end
end, [], Clients),
[ets:delete(BlockStore, Key) || Key <- BlocksSent],
timer:send_after(500, flush_world_updates),
{noreply, State#state{world_updates = []}};
handle_info(_Info, _State) ->
io:format("Info: ~p~n", [_Info]),
{noreply, _State}.
terminate(_Reason, _State) ->
io:format("Term: ~p~n", [_Reason]),
normal.
code_change(_OldVsn, _State, _Extra) ->
{ok, _State}.
-include_lib("eunit/include/eunit.hrl").
-ifdef(TEST).
-endif.
|
6abc89c4329ae650f85d4265aff731c7be6491dea02babe2ea3dcfc0624aae79 | melange-re/melange | test_nested_print.ml |
let u x x = x + x
let f g x =
let u = g x in u + u
| null | https://raw.githubusercontent.com/melange-re/melange/246e6df78fe3b6cc124cb48e5a37fdffd99379ed/jscomp/test/test_nested_print.ml | ocaml |
let u x x = x + x
let f g x =
let u = g x in u + u
| |
1948f83e59eb2e4caf3ba7a1d855bd089f7774e2447ffe5c25214e6326c29008 | lattenwald/erl-tdlib | tdlib_nif.erl | -module(tdlib_nif).
%% API exports
-export([new/0, send/2, execute/2, recv/2]).
-on_load(init/0).
init() ->
PrivDir = code:priv_dir(tdlib),
File = filename:join([PrivDir, "libtdlib_nif.so"]),
erlang:load_nif(filename:rootname(File), 0).
%%====================================================================
%% API functions
%%====================================================================
new() ->
exit(nif_lirary_not_loaded).
send(_, _) ->
exit(nif_lirary_not_loaded).
execute(_, _) ->
exit(nif_lirary_not_loaded).
recv(_, _) ->
exit(nif_lirary_not_loaded).
%%====================================================================
Internal functions
%%====================================================================
| null | https://raw.githubusercontent.com/lattenwald/erl-tdlib/8e72658ca12c731e2fb39762f325142a3fe558f8/src/tdlib_nif.erl | erlang | API exports
====================================================================
API functions
====================================================================
====================================================================
==================================================================== | -module(tdlib_nif).
-export([new/0, send/2, execute/2, recv/2]).
-on_load(init/0).
init() ->
PrivDir = code:priv_dir(tdlib),
File = filename:join([PrivDir, "libtdlib_nif.so"]),
erlang:load_nif(filename:rootname(File), 0).
new() ->
exit(nif_lirary_not_loaded).
send(_, _) ->
exit(nif_lirary_not_loaded).
execute(_, _) ->
exit(nif_lirary_not_loaded).
recv(_, _) ->
exit(nif_lirary_not_loaded).
Internal functions
|
bbe9064a30429f4c8fc20278cd062b6578d36336775a308fe403fe3882125ead | zotonic/zotonic | z_admin_rsc_import.erl | @author < >
2021
%%
%% @doc Support for admin tasks around non authoritative resources.
Copyright 2021
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
-module(z_admin_rsc_import).
-export([
event/2
]).
-include_lib("zotonic_core/include/zotonic.hrl").
event(#postback{ message={import_refresh, Args} }, Context) ->
OnError = proplists:get_value(on_error, Args),
{id, Id} = proplists:lookup(id, Args),
case m_rsc_import:reimport_recursive_async(Id, Context) of
{ok, {_Id, _ObjectIds}} ->
case proplists:get_all_values(on_success, Args) of
[] ->
z_render:growl(?__("Succesfully imported page from the remote server.", Context), Context);
OnSuccess ->
z_render:wire(OnSuccess, Context)
end;
{error, Reason} ->
?LOG_ERROR(#{
text => <<"Error on reimport of resource">>,
in => zotonic_mod_admin,
rsc_id => Id,
result => error,
reason => Reason
}),
Context1 = z_render:wire(OnError, Context),
z_render:growl_error(?__("Error importing page from the remote server.", Context1), Context1)
end.
| null | https://raw.githubusercontent.com/zotonic/zotonic/1bb4aa8a0688d007dd8ec8ba271546f658312da8/apps/zotonic_mod_admin/src/support/z_admin_rsc_import.erl | erlang |
@doc Support for admin tasks around non authoritative resources.
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. | @author < >
2021
Copyright 2021
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(z_admin_rsc_import).
-export([
event/2
]).
-include_lib("zotonic_core/include/zotonic.hrl").
event(#postback{ message={import_refresh, Args} }, Context) ->
OnError = proplists:get_value(on_error, Args),
{id, Id} = proplists:lookup(id, Args),
case m_rsc_import:reimport_recursive_async(Id, Context) of
{ok, {_Id, _ObjectIds}} ->
case proplists:get_all_values(on_success, Args) of
[] ->
z_render:growl(?__("Succesfully imported page from the remote server.", Context), Context);
OnSuccess ->
z_render:wire(OnSuccess, Context)
end;
{error, Reason} ->
?LOG_ERROR(#{
text => <<"Error on reimport of resource">>,
in => zotonic_mod_admin,
rsc_id => Id,
result => error,
reason => Reason
}),
Context1 = z_render:wire(OnError, Context),
z_render:growl_error(?__("Error importing page from the remote server.", Context1), Context1)
end.
|
ad5fdf7761b2802c43b3591a67edcaa9ea6fe8ed73b947045ba6cc32b5cc7e83 | esl/MongooseIM | mod_inbox_muc.erl | %%%-------------------------------------------------------------------
@author
( C ) 2018 , Erlang - Solutions
%%% @doc
%%%
%%% @end
Created : 6.07.2018
%%%-------------------------------------------------------------------
-module(mod_inbox_muc).
-author("").
-include("jlib.hrl").
-include("mongoose.hrl").
-export([update_inbox_for_muc/3, start/1, stop/1]).
%% User jid example is "alice@localhost"
-type user_jid() :: jid:jid().
-type receiver_bare_user_jid() :: user_jid().
-type room_bare_jid() :: jid:jid().
-type packet() :: exml:element().
start(HostType) ->
gen_hook:add_handlers(hooks(HostType)),
TODO check ooptions : if system messages stored - >
% add hook handler for system messages on hook ie. invitation_sent
ok.
stop(HostType) ->
gen_hook:delete_handlers(hooks(HostType)),
ok.
hooks(HostType) ->
[{update_inbox_for_muc, HostType, fun ?MODULE:update_inbox_for_muc/3, #{}, 90}].
-spec update_inbox_for_muc(Acc, Params, Extra) -> {ok, Acc} when
Acc :: mod_muc_room:update_inbox_for_muc_payload(),
Params :: map(),
Extra :: gen_hook:extra().
update_inbox_for_muc(
#{host_type := HostType,
room_jid := Room,
from_jid := From,
from_room_jid := FromRoomJid,
packet := Packet,
affiliations_map := AffsMap} = Acc, _, _) ->
F = fun(AffLJID, Affiliation) ->
case is_allowed_affiliation(Affiliation) of
true ->
To = jid:to_bare(jid:make(AffLJID)),
Guess direction based on user JIDs
Direction = direction(From, To),
Packet2 = jlib:replace_from_to(FromRoomJid, To, Packet),
update_inbox_for_user(HostType, Direction, Room, To, Packet2);
false ->
ok
end
end,
mongoose_lib:maps_foreach(F, AffsMap),
{ok, Acc}.
-spec is_allowed_affiliation(mod_muc:affiliation()) -> boolean().
is_allowed_affiliation(outcast) -> false;
is_allowed_affiliation(_) -> true.
-spec update_inbox_for_user(HostType, Direction, Room, To, Packet) -> term() when
HostType :: mongooseim:host_type(),
Direction :: incoming | outgoing,
Room :: room_bare_jid(),
To :: receiver_bare_user_jid(),
Packet :: packet().
update_inbox_for_user(HostType, Direction, Room, To, Packet) ->
ReceiverDomain = To#jid.lserver,
MucDomain = mod_muc:server_host_to_muc_host(HostType, ReceiverDomain),
case Room#jid.lserver of
MucDomain ->
handle_message(HostType, Room, To, Packet, Direction);
_ ->
%% We ignore inbox for users on the remote (s2s) hosts
%% We ignore inbox for components (also known as services or bots)
ok
end.
handle_message(HostType, Room, To, Packet, outgoing) ->
handle_outgoing_message(HostType, Room, To, Packet);
handle_message(HostType, Room, To, Packet, incoming) ->
handle_incoming_message(HostType, Room, To, Packet).
-spec direction(From :: user_jid(), To :: user_jid()) -> incoming | outgoing.
direction(From, To) ->
case jid:are_bare_equal(From, To) of
true -> outgoing;
false -> incoming
end.
%% Sender and receiver is the same user
-spec handle_outgoing_message(HostType, Room, To, Packet) -> term() when
HostType :: mongooseim:host_type(),
Room :: room_bare_jid(),
To :: receiver_bare_user_jid(),
Packet :: packet().
handle_outgoing_message(HostType, Room, To, Packet) ->
Acc = mongoose_acc:new(#{location => ?LOCATION, lserver => To#jid.lserver, host_type => HostType}),
maybe_reset_unread_count(HostType, To, Room, Packet, Acc),
maybe_write_to_inbox(HostType, To, Room, Packet, Acc, fun write_to_sender_inbox/5).
-spec handle_incoming_message(HostType, Room, To, Packet) -> term() when
HostType :: mongooseim:host_type(),
Room :: room_bare_jid(),
To :: receiver_bare_user_jid(),
Packet :: packet().
handle_incoming_message(HostType, Room, To, Packet) ->
Acc = mongoose_acc:new(#{location => ?LOCATION, lserver => To#jid.lserver, host_type => HostType}),
maybe_write_to_inbox(HostType, Room, To, Packet, Acc, fun write_to_receiver_inbox/5).
maybe_reset_unread_count(HostType, User, Room, Packet, Acc) ->
mod_inbox_utils:maybe_reset_unread_count(HostType, User, Room, Packet, Acc).
maybe_write_to_inbox(HostType, User, Remote, Packet, Acc, WriteF) ->
mod_inbox_utils:maybe_write_to_inbox(HostType, User, Remote, Packet, Acc, WriteF).
write_to_sender_inbox(Server, User, Remote, Packet, Acc) ->
mod_inbox_utils:write_to_sender_inbox(Server, User, Remote, Packet, Acc).
write_to_receiver_inbox(Server, User, Remote, Packet, Acc) ->
mod_inbox_utils:write_to_receiver_inbox(Server, User, Remote, Packet, Acc).
| null | https://raw.githubusercontent.com/esl/MongooseIM/c3383bc66ddd042553d38223fa7e2aa9f9f505fe/src/inbox/mod_inbox_muc.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
User jid example is "alice@localhost"
add hook handler for system messages on hook ie. invitation_sent
We ignore inbox for users on the remote (s2s) hosts
We ignore inbox for components (also known as services or bots)
Sender and receiver is the same user | @author
( C ) 2018 , Erlang - Solutions
Created : 6.07.2018
-module(mod_inbox_muc).
-author("").
-include("jlib.hrl").
-include("mongoose.hrl").
-export([update_inbox_for_muc/3, start/1, stop/1]).
-type user_jid() :: jid:jid().
-type receiver_bare_user_jid() :: user_jid().
-type room_bare_jid() :: jid:jid().
-type packet() :: exml:element().
start(HostType) ->
gen_hook:add_handlers(hooks(HostType)),
TODO check ooptions : if system messages stored - >
ok.
stop(HostType) ->
gen_hook:delete_handlers(hooks(HostType)),
ok.
hooks(HostType) ->
[{update_inbox_for_muc, HostType, fun ?MODULE:update_inbox_for_muc/3, #{}, 90}].
-spec update_inbox_for_muc(Acc, Params, Extra) -> {ok, Acc} when
Acc :: mod_muc_room:update_inbox_for_muc_payload(),
Params :: map(),
Extra :: gen_hook:extra().
update_inbox_for_muc(
#{host_type := HostType,
room_jid := Room,
from_jid := From,
from_room_jid := FromRoomJid,
packet := Packet,
affiliations_map := AffsMap} = Acc, _, _) ->
F = fun(AffLJID, Affiliation) ->
case is_allowed_affiliation(Affiliation) of
true ->
To = jid:to_bare(jid:make(AffLJID)),
Guess direction based on user JIDs
Direction = direction(From, To),
Packet2 = jlib:replace_from_to(FromRoomJid, To, Packet),
update_inbox_for_user(HostType, Direction, Room, To, Packet2);
false ->
ok
end
end,
mongoose_lib:maps_foreach(F, AffsMap),
{ok, Acc}.
-spec is_allowed_affiliation(mod_muc:affiliation()) -> boolean().
is_allowed_affiliation(outcast) -> false;
is_allowed_affiliation(_) -> true.
-spec update_inbox_for_user(HostType, Direction, Room, To, Packet) -> term() when
HostType :: mongooseim:host_type(),
Direction :: incoming | outgoing,
Room :: room_bare_jid(),
To :: receiver_bare_user_jid(),
Packet :: packet().
update_inbox_for_user(HostType, Direction, Room, To, Packet) ->
ReceiverDomain = To#jid.lserver,
MucDomain = mod_muc:server_host_to_muc_host(HostType, ReceiverDomain),
case Room#jid.lserver of
MucDomain ->
handle_message(HostType, Room, To, Packet, Direction);
_ ->
ok
end.
handle_message(HostType, Room, To, Packet, outgoing) ->
handle_outgoing_message(HostType, Room, To, Packet);
handle_message(HostType, Room, To, Packet, incoming) ->
handle_incoming_message(HostType, Room, To, Packet).
-spec direction(From :: user_jid(), To :: user_jid()) -> incoming | outgoing.
direction(From, To) ->
case jid:are_bare_equal(From, To) of
true -> outgoing;
false -> incoming
end.
-spec handle_outgoing_message(HostType, Room, To, Packet) -> term() when
HostType :: mongooseim:host_type(),
Room :: room_bare_jid(),
To :: receiver_bare_user_jid(),
Packet :: packet().
handle_outgoing_message(HostType, Room, To, Packet) ->
Acc = mongoose_acc:new(#{location => ?LOCATION, lserver => To#jid.lserver, host_type => HostType}),
maybe_reset_unread_count(HostType, To, Room, Packet, Acc),
maybe_write_to_inbox(HostType, To, Room, Packet, Acc, fun write_to_sender_inbox/5).
-spec handle_incoming_message(HostType, Room, To, Packet) -> term() when
HostType :: mongooseim:host_type(),
Room :: room_bare_jid(),
To :: receiver_bare_user_jid(),
Packet :: packet().
handle_incoming_message(HostType, Room, To, Packet) ->
Acc = mongoose_acc:new(#{location => ?LOCATION, lserver => To#jid.lserver, host_type => HostType}),
maybe_write_to_inbox(HostType, Room, To, Packet, Acc, fun write_to_receiver_inbox/5).
maybe_reset_unread_count(HostType, User, Room, Packet, Acc) ->
mod_inbox_utils:maybe_reset_unread_count(HostType, User, Room, Packet, Acc).
maybe_write_to_inbox(HostType, User, Remote, Packet, Acc, WriteF) ->
mod_inbox_utils:maybe_write_to_inbox(HostType, User, Remote, Packet, Acc, WriteF).
write_to_sender_inbox(Server, User, Remote, Packet, Acc) ->
mod_inbox_utils:write_to_sender_inbox(Server, User, Remote, Packet, Acc).
write_to_receiver_inbox(Server, User, Remote, Packet, Acc) ->
mod_inbox_utils:write_to_receiver_inbox(Server, User, Remote, Packet, Acc).
|
59f24dff932aad09317ee4da091baa93ca26eca43488afaeefab089d3048df1d | Liam-Eagen/BulletproofsPP | InnerProductArgument.hs | # LANGUAGE StandaloneDeriving #
module Bulletproof.InnerProductArgument where
import Data.Bifunctor
import Data.Foldable (foldrM, toList)
import Control.Monad (replicateM)
import Data.VectorSpace
import Control.Parallel.Strategies
import Utils
import Commitment
import Bulletproof
foldLR :: (CanCommit v s, BPCollection f)
=> (a -> s -> s -> g v s -> g v s -> (a, s, s, g v s, g v s)) -- Swaps the scalars/basis points
-> a
Zeros
-> BPFrame'' g f v s -> (s, BPFrame'' g f v s, s, BPFrame'' g f v s)
foldLR swap a z (BPF'' n sgs) = (lFin, BPF'' n $ fst <$> fs, rFin, BPF'' n $ snd <$> fs)
where
((_, lFin, rFin), fs) = foldMapHalves go z (a, 0, 0) sgs
go l r (!a, !lS, !rS) = ((a', lS', rS'), (l', r'))
where (a', lS', rS', l', r') = swap a lS rS l r
-------------------
-- Inner Product --
data IPF v s = IPF { xIPF :: s, gIPF :: v, yIPF :: s, hIPF :: v } deriving (Eq, Show)
instance Bifunctor IPF where
bimap f g (IPF x p y q) = IPF (g x) (f p) (g y) (f q)
instance Opening IPF where
openWith (IPF x g y h) (*:) (+:) z = (x *: g) +: ( (y *: h) +: z )
the vectors are normalized differently due to weight and BPF only keeps track
of one normalization value . However , storing them is more convenient for
-- locality
data InnerProduct f v s = IP { sIP :: s, nrmlzYIP :: s, qIP :: s, qInvIP :: s, bodyIP :: BPFrame'' IPF f v s }
deriving instance (Eq v, Eq s, BPCollection f) => Eq (InnerProduct f v s)
deriving instance (Show v, Show s, BPCollection f) => Show (InnerProduct f v s)
makeIP :: (CanCommit v s, BPCollection f) => s -> s -> f s -> f v -> f s -> f v -> InnerProduct f v s
makeIP s q ss0 gs0 ss1 gs1 = IP s 1 q (recip q) $ BPF'' 1 ips
where ips = zipWithDef'' (uncurry $ uncurry IPF) ((0, zeroV), 0) zeroV (zipWithDef'' (,) (0, zeroV) 0 (zipWithDef'' (,) 0 zeroV ss0 gs0) ss1) gs1
instance Functor f => Bifunctor (InnerProduct f) where
bimap f g (IP s ny q qInv bpf) = IP (g s) (g ny) (g q) (g qInv) (bimap f g bpf)
instance (Zip f, Foldable f) => Opening (InnerProduct f) where
openWith = openWith . bodyIP
instance BPCollection f => BPOpening (InnerProduct f) where
The inner product must reduce the vectors to either 1 or 2 since there are
two of them . Length already < 5 , so just need one more round
optimalRounds (IP _ _ _ _ (BPF'' _ sgs)) = numberRoundsReduce' $ length $ toList $ sgs
-- Better way to do this?
evalScalar (IP s ny q qInv bpf@(BPF'' nx ws)) = s * nx * ny * dotZip scs (fromList' $ powers' $ q)
where
sc (IPF x _ y _) = x * y
scs = sc <$> ws
makeEs _ e = (recip e, e)
makeScalarsComs (IP s ny q qInv bpf@(BPF'' nx _)) = (sL'', mkIP 1 wL', sR'', mkIP qInv wR')
where
q2 = q^2
(sL', wL', sR', wR') = foldLR swap 1 (IPF 0 zeroV 0 zeroV) bpf
sL'' = s * q * nx * ny * sL'
sR'' = s * q2 * nx * ny * sR'
mkIP t (BPF'' nx bpf) = IP s ny (q^2) (qInv^2) $ BPF'' (t*nx) bpf
swap s l r (IPF xL gL yL hL) (IPF xR gR yR hR) = (s', l + s * xL * yR, r + s * xR * yL, l', r')
where
s' = q2*s
l' = IPF (qInv * xL) gR yR hL
r' = IPF (q * xR) gL yL hR
getWitness (IP s ny _ _ (BPF'' nx sgs)) = unPairs $ toList $ go <$> sgs
where go (IPF x _ y _) = (nx * x, ny * y)
collapse e (IP s ny q qInv (BPF'' nx sgs)) = IP s (ny * d0) (q^2) (qInv^2) $ BPF'' (nx * b0 * qInv) sgs'
where
eInv = recip e
(a', b') = rationalReduceScalar (qInv * eInv)
b0 = extractScalar b'
b0Inv = recip b0
(c', d') = rationalReduceScalar e
d0 = extractScalar d'
d0Inv = recip d0
sgs' = mapHalves cps (IPF 0 zeroV 0 zeroV) sgs
cps (IPF xL gL yL hL) (IPF xR gR yR hR) = IPF (b0Inv * (xL + e*q*xR)) g' (d0Inv * (yL + eInv*yR)) h'
where
g' = collapsePoints b' a' gL gR
h' = collapsePoints d' c' hL hR
expandChallenges esY wit@(IP s ny q' _ (BPF'' nx b)) ipP ipG = res
where
IP s _ q qInv (BPF'' _ bP) = ipP
IP _ _ _ _ (BPF'' _ bG) = ipG
-- For evaluation of scalar
qF = head $ drop (length esY) $ iterate (^2) $ q
TODO not necessary
esX = recip <$> esY
-- NOTE this is why independent normalization is necessary
vsX = (nx *) . xIPF <$> b
vsY = (ny *) . yIPF <$> b
sc = s * weightedDotZip (powers' $ qF) vsX vsY
tsX = tensor' vsX esX $ iterate (^2) q
tsY = tensor' vsY esY $ repeat 1
sgs' = zipWithDef' exp (0,0) (zip' bP bG) $ zip' tsX tsY
exp ((IPF pX _ pY _), (IPF _ g _ h)) (eX, eY) = IPF (pX - eX) g (pY - eY) h
res = (sc, IP s 1 qF qFInv $ BPF'' 1 sgs')
instance BPCollection f => Weighted (InnerProduct f) where
qPowers' _ = powers'
------------
Linear --
data LinearF v s = LF { cLF :: s, xLF :: s, gLF :: v } deriving (Eq, Show)
instance Bifunctor LinearF where
bimap f g (LF c x p) = LF (g c) (g x) (f p)
instance Opening LinearF where
openWith (LF _ x g) (*:) (+:) z = (x *: g) +: z
TODO not sure if the order of public scalars / witness is swapped wrt paper
newtype Linear f v s = L { linF :: BPFrame'' LinearF f v s }
deriving (Bifunctor, Opening)
deriving instance (Eq v, Eq s, BPCollection f) => Eq (Linear f v s)
deriving instance (Show v, Show s, BPCollection f) => Show (Linear f v s)
makeLinear :: (CanCommit v s, BPCollection f) => f s -> f s -> f v -> Linear f v s
makeLinear cs ss gs = L $ BPF'' 1 $ zipWithDef'' (uncurry LF) (0, 0) zeroV (zipWithDef'' (,) 0 0 cs ss) gs
instance BPCollection f => BPOpening (Linear f) where
optimalRounds (L (BPF'' _ sgs)) = numberRoundsReduce $ length $ toList sgs
makeEs _ e = (recip e, e)
evalScalar (L (BPF'' _ scs)) = sum $ sc <$> scs
where sc (LF c x _) = c * x
makeScalarsComs (L bpf) = (sL', L wL', sR', L wR')
where
(sL', wL', sR', wR') = foldLR swap () (LF 0 0 zeroV) bpf
swap _ l r (LF cL xL gL) (LF cR xR gR) = ((), l + cR * xL, r + cL * xR, LF cR xL gR, LF cL xR gL)
getWitness (L bpf) = toList $ (nrmlz'' bpf *) . xLF <$> body'' bpf
collapse e (L (BPF'' n sgs)) = L $ BPF'' (n*b0) sgs''
where
(a', b') = rationalReduceScalar $ recip e
a0 = extractScalar a'
b0 = extractScalar b'
b0Inv = recip b0
sgs'' = mapHalves cps (LF 0 0 zeroV) sgs
cps (LF cL xL gL) (LF cR xR gR) = LF (b0*cL + a0*cR) (b0Inv*xL + e*b0Inv*xR) (collapsePoints b' a' gL gR)
expandChallenges es' (L (BPF'' n b)) (L (BPF'' _ sps)) (L (BPF'' _ sgs)) = (sc, L $ BPF'' 1 sgs')
where
es = recip <$> es'
expEs = tensor' (single' 1) es $ repeat 1
cs' = contract' expEs $ cLF <$> sps
vs = (n *) . xLF <$> b
sc = dotZip cs' vs
exp ((LF c p _), (LF _ _ g)) eP = LF c (p - eP) g
sgs' = zipWithDef' exp 0 (zip' sps sgs) $ tensor' vs es $ repeat 1
----------
-- Norm --
-- Norm wraps the inner product and does basis modification, but otherwise works
-- exactly the same internally. TODO we need to bypass the basis computation in
-- the verifier case, it takes way too long. Probably requires a different
organization to defer until the first collapse or something
newtype Norm f v s = N { norm :: InnerProduct f v s }
, BPOpening )
-- Does the basis transformation. Accepts the r such that q = -r^2
makeNorm :: (CanCommit v s, BPCollection f) => s -> f s -> f v -> Norm f v s
makeNorm r ss gs = N $ IP 4 1 q (recip q) $ BPF'' 1 $ mapHalves mkIP (0, zeroV) $ zipWithDef'' (,) 0 zeroV ss gs
where
q = r^4
half = recip 2
r2Inv = recip (2*r)
mkIP (s0, g0) (s1, g1) = IPF x' g' y' h'
where
x' = r2Inv * s0 + half * s1
y' = -r2Inv * s0 + half * s1
p = commit $ CP r g0
g' = g1 ^+^ p
h' = g1 ^-^ p
instance BPCollection f => BPOpening (Norm f) where
optimalRounds = optimalRounds . norm
-- These functions are all the same
evalScalar = evalScalar . norm
makeEs = makeEs . norm
makeScalarsComs (N w) = (sL, N wL, sR, N wR)
where (sL, wL, sR, wR) = makeScalarsComs w
collapse e (N w) = N $ collapse e w
This returns a vector such that calling makeNorm 1 with that witness yields
-- the original value. This is so that encodeing/decoding work generically in
-- the range proofs.
getWitness (N (IP s ny _ _ (BPF'' nx sgs))) = unPairs $ toList $ go <$> sgs
where go (IPF x _ y _) = (nx * x - ny * y, nx * x + ny * y)
TODO currently , this performs the inital basis transformation before
-- calling this, which we don't want. Modifying to not do this requires
-- defering the basis transformation.
expandChallenges es (N w) (N p) (N b) = N <$> expandChallenges es w p b
instance BPCollection f => Weighted (Norm f) where
qPowers' _ q = powers' $ negate $ q^2
----------------
NormLinear --
-- Scales the scalar by the inverse of scalarNL by multiplying the evaluated
-- scalars from the norm and linear substructures. Avoids modifying the scalar
-- basis element.
newtype NormLinear f v s = NL { compNL :: BPCompose (Norm f) (Linear f) v s }
deriving (Eq, Show, Bifunctor, Opening, BPOpening)
instance BPCollection f => Weighted (NormLinear f) where
qPowers' = qPowers' . fmap compNL
instance BPCollection f => NormLinearBP (NormLinear f) where
type Coll (NormLinear f) = f
makeNormLinearBP' s q cs nss ngs lss lgs = NL $ BPComp s (makeNorm q nss ngs) (makeLinear cs lss lgs)
NOTE nLen is the length of the norm vector , not the length of the inner
product vectors . First need to pad to an even length and then need to
reduce half
optimalWitnessSize _ nLen lLen = res
where
nLenEven = (nLen + (nLen `mod` 2)) `div` 2
Either 1 , 2 , 3 , 4
(lR, lLen') = numberRoundsReduce lLen -- Also
-- Perform the same number of reduction on both
r = max nR lR
nLen'' = roundReduceBy nLen' $ r - nR
lLen'' = roundReduceBy lLen' $ r - lR
In the ( 4 , n ) with n > 1 case do one more reduction
res = if 2*nLen'' + lLen'' > 5
then (r + 1, (2*roundReduce nLen'', roundReduce lLen''))
else (r, (2*nLen'', lLen''))
| null | https://raw.githubusercontent.com/Liam-Eagen/BulletproofsPP/0494201e2048f5c679f4ce3ee0cc6ac0ff9d3ef7/src/Bulletproof/InnerProductArgument.hs | haskell | Swaps the scalars/basis points
-----------------
Inner Product --
locality
Better way to do this?
For evaluation of scalar
NOTE this is why independent normalization is necessary
----------
--------
Norm --
Norm wraps the inner product and does basis modification, but otherwise works
exactly the same internally. TODO we need to bypass the basis computation in
the verifier case, it takes way too long. Probably requires a different
Does the basis transformation. Accepts the r such that q = -r^2
These functions are all the same
the original value. This is so that encodeing/decoding work generically in
the range proofs.
calling this, which we don't want. Modifying to not do this requires
defering the basis transformation.
--------------
Scales the scalar by the inverse of scalarNL by multiplying the evaluated
scalars from the norm and linear substructures. Avoids modifying the scalar
basis element.
Also
Perform the same number of reduction on both | # LANGUAGE StandaloneDeriving #
module Bulletproof.InnerProductArgument where
import Data.Bifunctor
import Data.Foldable (foldrM, toList)
import Control.Monad (replicateM)
import Data.VectorSpace
import Control.Parallel.Strategies
import Utils
import Commitment
import Bulletproof
foldLR :: (CanCommit v s, BPCollection f)
-> a
Zeros
-> BPFrame'' g f v s -> (s, BPFrame'' g f v s, s, BPFrame'' g f v s)
foldLR swap a z (BPF'' n sgs) = (lFin, BPF'' n $ fst <$> fs, rFin, BPF'' n $ snd <$> fs)
where
((_, lFin, rFin), fs) = foldMapHalves go z (a, 0, 0) sgs
go l r (!a, !lS, !rS) = ((a', lS', rS'), (l', r'))
where (a', lS', rS', l', r') = swap a lS rS l r
data IPF v s = IPF { xIPF :: s, gIPF :: v, yIPF :: s, hIPF :: v } deriving (Eq, Show)
instance Bifunctor IPF where
bimap f g (IPF x p y q) = IPF (g x) (f p) (g y) (f q)
instance Opening IPF where
openWith (IPF x g y h) (*:) (+:) z = (x *: g) +: ( (y *: h) +: z )
the vectors are normalized differently due to weight and BPF only keeps track
of one normalization value . However , storing them is more convenient for
data InnerProduct f v s = IP { sIP :: s, nrmlzYIP :: s, qIP :: s, qInvIP :: s, bodyIP :: BPFrame'' IPF f v s }
deriving instance (Eq v, Eq s, BPCollection f) => Eq (InnerProduct f v s)
deriving instance (Show v, Show s, BPCollection f) => Show (InnerProduct f v s)
makeIP :: (CanCommit v s, BPCollection f) => s -> s -> f s -> f v -> f s -> f v -> InnerProduct f v s
makeIP s q ss0 gs0 ss1 gs1 = IP s 1 q (recip q) $ BPF'' 1 ips
where ips = zipWithDef'' (uncurry $ uncurry IPF) ((0, zeroV), 0) zeroV (zipWithDef'' (,) (0, zeroV) 0 (zipWithDef'' (,) 0 zeroV ss0 gs0) ss1) gs1
instance Functor f => Bifunctor (InnerProduct f) where
bimap f g (IP s ny q qInv bpf) = IP (g s) (g ny) (g q) (g qInv) (bimap f g bpf)
instance (Zip f, Foldable f) => Opening (InnerProduct f) where
openWith = openWith . bodyIP
instance BPCollection f => BPOpening (InnerProduct f) where
The inner product must reduce the vectors to either 1 or 2 since there are
two of them . Length already < 5 , so just need one more round
optimalRounds (IP _ _ _ _ (BPF'' _ sgs)) = numberRoundsReduce' $ length $ toList $ sgs
evalScalar (IP s ny q qInv bpf@(BPF'' nx ws)) = s * nx * ny * dotZip scs (fromList' $ powers' $ q)
where
sc (IPF x _ y _) = x * y
scs = sc <$> ws
makeEs _ e = (recip e, e)
makeScalarsComs (IP s ny q qInv bpf@(BPF'' nx _)) = (sL'', mkIP 1 wL', sR'', mkIP qInv wR')
where
q2 = q^2
(sL', wL', sR', wR') = foldLR swap 1 (IPF 0 zeroV 0 zeroV) bpf
sL'' = s * q * nx * ny * sL'
sR'' = s * q2 * nx * ny * sR'
mkIP t (BPF'' nx bpf) = IP s ny (q^2) (qInv^2) $ BPF'' (t*nx) bpf
swap s l r (IPF xL gL yL hL) (IPF xR gR yR hR) = (s', l + s * xL * yR, r + s * xR * yL, l', r')
where
s' = q2*s
l' = IPF (qInv * xL) gR yR hL
r' = IPF (q * xR) gL yL hR
getWitness (IP s ny _ _ (BPF'' nx sgs)) = unPairs $ toList $ go <$> sgs
where go (IPF x _ y _) = (nx * x, ny * y)
collapse e (IP s ny q qInv (BPF'' nx sgs)) = IP s (ny * d0) (q^2) (qInv^2) $ BPF'' (nx * b0 * qInv) sgs'
where
eInv = recip e
(a', b') = rationalReduceScalar (qInv * eInv)
b0 = extractScalar b'
b0Inv = recip b0
(c', d') = rationalReduceScalar e
d0 = extractScalar d'
d0Inv = recip d0
sgs' = mapHalves cps (IPF 0 zeroV 0 zeroV) sgs
cps (IPF xL gL yL hL) (IPF xR gR yR hR) = IPF (b0Inv * (xL + e*q*xR)) g' (d0Inv * (yL + eInv*yR)) h'
where
g' = collapsePoints b' a' gL gR
h' = collapsePoints d' c' hL hR
expandChallenges esY wit@(IP s ny q' _ (BPF'' nx b)) ipP ipG = res
where
IP s _ q qInv (BPF'' _ bP) = ipP
IP _ _ _ _ (BPF'' _ bG) = ipG
qF = head $ drop (length esY) $ iterate (^2) $ q
TODO not necessary
esX = recip <$> esY
vsX = (nx *) . xIPF <$> b
vsY = (ny *) . yIPF <$> b
sc = s * weightedDotZip (powers' $ qF) vsX vsY
tsX = tensor' vsX esX $ iterate (^2) q
tsY = tensor' vsY esY $ repeat 1
sgs' = zipWithDef' exp (0,0) (zip' bP bG) $ zip' tsX tsY
exp ((IPF pX _ pY _), (IPF _ g _ h)) (eX, eY) = IPF (pX - eX) g (pY - eY) h
res = (sc, IP s 1 qF qFInv $ BPF'' 1 sgs')
instance BPCollection f => Weighted (InnerProduct f) where
qPowers' _ = powers'
data LinearF v s = LF { cLF :: s, xLF :: s, gLF :: v } deriving (Eq, Show)
instance Bifunctor LinearF where
bimap f g (LF c x p) = LF (g c) (g x) (f p)
instance Opening LinearF where
openWith (LF _ x g) (*:) (+:) z = (x *: g) +: z
TODO not sure if the order of public scalars / witness is swapped wrt paper
newtype Linear f v s = L { linF :: BPFrame'' LinearF f v s }
deriving (Bifunctor, Opening)
deriving instance (Eq v, Eq s, BPCollection f) => Eq (Linear f v s)
deriving instance (Show v, Show s, BPCollection f) => Show (Linear f v s)
makeLinear :: (CanCommit v s, BPCollection f) => f s -> f s -> f v -> Linear f v s
makeLinear cs ss gs = L $ BPF'' 1 $ zipWithDef'' (uncurry LF) (0, 0) zeroV (zipWithDef'' (,) 0 0 cs ss) gs
instance BPCollection f => BPOpening (Linear f) where
optimalRounds (L (BPF'' _ sgs)) = numberRoundsReduce $ length $ toList sgs
makeEs _ e = (recip e, e)
evalScalar (L (BPF'' _ scs)) = sum $ sc <$> scs
where sc (LF c x _) = c * x
makeScalarsComs (L bpf) = (sL', L wL', sR', L wR')
where
(sL', wL', sR', wR') = foldLR swap () (LF 0 0 zeroV) bpf
swap _ l r (LF cL xL gL) (LF cR xR gR) = ((), l + cR * xL, r + cL * xR, LF cR xL gR, LF cL xR gL)
getWitness (L bpf) = toList $ (nrmlz'' bpf *) . xLF <$> body'' bpf
collapse e (L (BPF'' n sgs)) = L $ BPF'' (n*b0) sgs''
where
(a', b') = rationalReduceScalar $ recip e
a0 = extractScalar a'
b0 = extractScalar b'
b0Inv = recip b0
sgs'' = mapHalves cps (LF 0 0 zeroV) sgs
cps (LF cL xL gL) (LF cR xR gR) = LF (b0*cL + a0*cR) (b0Inv*xL + e*b0Inv*xR) (collapsePoints b' a' gL gR)
expandChallenges es' (L (BPF'' n b)) (L (BPF'' _ sps)) (L (BPF'' _ sgs)) = (sc, L $ BPF'' 1 sgs')
where
es = recip <$> es'
expEs = tensor' (single' 1) es $ repeat 1
cs' = contract' expEs $ cLF <$> sps
vs = (n *) . xLF <$> b
sc = dotZip cs' vs
exp ((LF c p _), (LF _ _ g)) eP = LF c (p - eP) g
sgs' = zipWithDef' exp 0 (zip' sps sgs) $ tensor' vs es $ repeat 1
organization to defer until the first collapse or something
newtype Norm f v s = N { norm :: InnerProduct f v s }
, BPOpening )
makeNorm :: (CanCommit v s, BPCollection f) => s -> f s -> f v -> Norm f v s
makeNorm r ss gs = N $ IP 4 1 q (recip q) $ BPF'' 1 $ mapHalves mkIP (0, zeroV) $ zipWithDef'' (,) 0 zeroV ss gs
where
q = r^4
half = recip 2
r2Inv = recip (2*r)
mkIP (s0, g0) (s1, g1) = IPF x' g' y' h'
where
x' = r2Inv * s0 + half * s1
y' = -r2Inv * s0 + half * s1
p = commit $ CP r g0
g' = g1 ^+^ p
h' = g1 ^-^ p
instance BPCollection f => BPOpening (Norm f) where
optimalRounds = optimalRounds . norm
evalScalar = evalScalar . norm
makeEs = makeEs . norm
makeScalarsComs (N w) = (sL, N wL, sR, N wR)
where (sL, wL, sR, wR) = makeScalarsComs w
collapse e (N w) = N $ collapse e w
This returns a vector such that calling makeNorm 1 with that witness yields
getWitness (N (IP s ny _ _ (BPF'' nx sgs))) = unPairs $ toList $ go <$> sgs
where go (IPF x _ y _) = (nx * x - ny * y, nx * x + ny * y)
TODO currently , this performs the inital basis transformation before
expandChallenges es (N w) (N p) (N b) = N <$> expandChallenges es w p b
instance BPCollection f => Weighted (Norm f) where
qPowers' _ q = powers' $ negate $ q^2
newtype NormLinear f v s = NL { compNL :: BPCompose (Norm f) (Linear f) v s }
deriving (Eq, Show, Bifunctor, Opening, BPOpening)
instance BPCollection f => Weighted (NormLinear f) where
qPowers' = qPowers' . fmap compNL
instance BPCollection f => NormLinearBP (NormLinear f) where
type Coll (NormLinear f) = f
makeNormLinearBP' s q cs nss ngs lss lgs = NL $ BPComp s (makeNorm q nss ngs) (makeLinear cs lss lgs)
NOTE nLen is the length of the norm vector , not the length of the inner
product vectors . First need to pad to an even length and then need to
reduce half
optimalWitnessSize _ nLen lLen = res
where
nLenEven = (nLen + (nLen `mod` 2)) `div` 2
Either 1 , 2 , 3 , 4
r = max nR lR
nLen'' = roundReduceBy nLen' $ r - nR
lLen'' = roundReduceBy lLen' $ r - lR
In the ( 4 , n ) with n > 1 case do one more reduction
res = if 2*nLen'' + lLen'' > 5
then (r + 1, (2*roundReduce nLen'', roundReduce lLen''))
else (r, (2*nLen'', lLen''))
|
9c4a91801efe5130c9dbd24517e5e1d5c18c8926cfab168f367148504c0534e2 | rubenbarroso/EOPL | 3_25.scm | (load "/Users/ruben/Dropbox/EOPL/src/interps/r5rs.scm")
(load "/Users/ruben/Dropbox/EOPL/src/interps/define-datatype.scm")
(load "/Users/ruben/Dropbox/EOPL/src/interps/sllgen.scm")
(define-datatype environment nameless-environment?
(empty-nameless-env-record)
(extended-nameless-env-record
(vals (list-of scheme-value?))
(env nameless-environment?)))
(define scheme-value? (lambda (v) #t))
(define empty-nameless-env
(lambda ()
(empty-nameless-env-record)))
(define extend-nameless-env
(lambda (vals env)
(extended-nameless-env-record vals env)))
(define apply-nameless-env
(lambda (env depth pos)
(if (= pos -1)
(eopl:error 'apply-nameless-env
"Error accessing free variable at (~s ~s)"
depth pos))
(cases environment env
(empty-nameless-env-record ()
(eopl:error 'apply-nameless-env "No binding for ~s" sym))
(extended-nameless-env-record (vals env)
(if (= depth 0)
(list-ref vals pos)
(apply-nameless-env env (- depth 1) pos))))))
;Some tests:
;> (apply-nameless-env
; (extend-nameless-env
' ( 24 4 )
; (extend-nameless-env
' ( 5 28 )
; (empty-nameless-env)))
0 1 )
4
;
;> (apply-nameless-env
; (extend-nameless-env
' ( 24 4 )
; (extend-nameless-env
' ( 5 28 )
; (empty-nameless-env)))
1 1 )
28
(define scanner-spec-3-13
'((white-sp
(whitespace) skip)
(comment
("%" (arbno (not #\newline))) skip)
(identifier
(letter (arbno (or letter digit "?"))) symbol)
(number
(digit (arbno digit)) number)))
(define grammar-3-13
'((program
(expression)
a-program)
(expression
(number)
lit-exp)
(expression
(identifier)
var-exp)
(expression
("lexvar" "(" number number ")")
lexvar-exp)
(expression
(primitive "(" (separated-list expression ",") ")")
primapp-exp)
(expression
("if" expression "then" expression "else" expression)
if-exp)
(expression
("let" (arbno identifier "=" expression) "in" expression)
let-exp)
(expression
("proc" "(" (separated-list identifier ",") ")" expression)
proc-exp)
(expression
("(" expression (arbno expression) ")")
app-exp)
(primitive
("+")
add-prim)
(primitive
("-")
substract-prim)
(primitive
("*")
mult-prim)
(primitive
("add1")
incr-prim)
(primitive
("sub1")
decr-prim)
(primitive
("equal?")
equal-prim)
(primitive
("zero?")
zero-prim)
(primitive
("greater?")
greater-prim)
(primitive
("less?")
less-prim)))
(define scan&parse
(sllgen:make-string-parser
scanner-spec-3-13
grammar-3-13))
(sllgen:make-define-datatypes scanner-spec-3-13 grammar-3-13)
(define run
(lambda (string)
(eval-program
(lexical-address-calc
(scan&parse string)))))
;helpers
(define true-value?
(lambda (x)
(not (zero? x))))
; the interpreter
(define eval-program
(lambda (pgm)
(cases program pgm
(a-program (body)
(eval-expression body (init-nameless-env))))))
(define eval-expression
(lambda (exp env)
(cases expression exp
(lit-exp (datum) datum)
(var-exp (id) (eopl:error
'eval-expression
"var-exp should not appear in the instrumented interpreter"))
(lexvar-exp (depth pos) (apply-nameless-env env depth pos))
(primapp-exp (prim rands)
(let ((args (eval-rands rands env)))
(apply-primitive prim args)))
(if-exp (test-exp true-exp false-exp)
(if (true-value? (eval-expression test-exp env))
(eval-expression true-exp env)
(eval-expression false-exp env)))
(let-exp (ids rands body)
(let ((args (eval-rands rands env)))
(eval-expression body (extend-nameless-env args env))))
(proc-exp (ids body) (closure body env))
(app-exp (rator rands)
(let ((proc (eval-expression rator env))
(args (eval-rands rands env)))
(if (procval? proc)
(apply-procval proc args)
(eopl:error 'eval-expression
"Attempt to apply a non-procedure ~s" proc)))))))
(define eval-rands
(lambda (rands env)
(map (lambda (x) (eval-rand x env)) rands)))
(define eval-rand
(lambda (rand env)
(eval-expression rand env)))
(define apply-primitive
(lambda (prim args)
(cases primitive prim
(add-prim () (+ (car args) (cadr args)))
(substract-prim () (- (car args) (cadr args)))
(mult-prim () (* (car args) (cadr args)))
(incr-prim () (+ (car args) 1))
(decr-prim () (- (car args) 1))
(equal-prim () (if (= (car args) (cadr args)) 1 0))
(zero-prim () (if (zero? (car args)) 1 0))
(greater-prim () (if (> (car args) (cadr args)) 1 0))
(less-prim () (if (< (car args) (cadr args)) 1 0)))))
(define-datatype procval procval?
(closure
(body expression?)
(env nameless-environment?)))
(define apply-procval
(lambda (proc args)
(cases procval proc
(closure (body env)
(eval-expression body
(extend-nameless-env args env))))))
(define init-nameless-env
(lambda ()
(extend-nameless-env
'(1 5 10)
(empty-nameless-env))))
;Helper procedures from exercise 1.31
(define make-lexical-address
(lambda (v d p)
(list v ': d p)))
(define get-v
(lambda (address)
(car address)))
(define get-d
(lambda (address)
(caddr address)))
(define get-p
(lambda (address)
(cadddr address)))
(define increment-depth
(lambda (address)
(make-lexical-address (get-v address)
(+ 1 (get-d address))
(get-p address))))
;we will represent free variables with (v -1 -1)
(define get-lexical-address
(lambda (exp addresses)
(define iter
(lambda (lst)
(cond ((null? lst) (make-lexical-address exp -1 -1))
((eqv? exp (get-v (car lst))) (car lst))
(else (get-lexical-address exp (cdr lst))))))
(iter addresses)))
(define index-of
(lambda (v declarations)
(define helper
(lambda (lst index)
(cond ((null? lst) 'free)
((eqv? (car lst) v) index)
(else (helper (cdr lst) (+ index 1))))))
(helper declarations 0)))
(define cross-contour
(lambda (declarations addresses)
(let ((bound (filter-bound declarations))
(free (filter-free declarations addresses)))
(append bound free))))
(define filter-bound
(lambda (declarations)
(map (lambda (decl)
(make-lexical-address decl
0
(index-of decl declarations)))
declarations)))
(define filter-free
(lambda (declarations addresses)
(define iter
(lambda (lst)
(cond ((null? lst) '())
((not (memq (get-v (car lst)) declarations))
(cons (increment-depth (car lst))
(iter (cdr lst))))
(else (iter (cdr lst))))))
(iter addresses)))
;Exercise - Lexical address calculator
(define lexical-address-calc-helper
(lambda (exp addresses)
(cases expression exp
(lit-exp (datum)
(lit-exp datum))
(var-exp (id)
(let ((lexical-address (get-lexical-address id addresses)))
(lexvar-exp (get-d lexical-address)
(get-p lexical-address))))
(lexvar-exp (depth pos)
(lexvar-exp depth pos))
(primapp-exp (prim rands)
(primapp-exp prim
(map (lambda (rand)
(lexical-address-calc-helper rand addresses))
rands)))
(if-exp (test-exp true-exp false-exp)
(if-exp (lexical-address-calc-helper test-exp addresses)
(lexical-address-calc-helper true-exp addresses)
(lexical-address-calc-helper false-exp addresses)))
(let-exp (ids rands body)
(let-exp ids
(map (lambda (rand)
(lexical-address-calc-helper rand addresses))
rands)
(lexical-address-calc-helper
body
(cross-contour ids addresses))))
(proc-exp (ids body)
(proc-exp ids
(lexical-address-calc-helper
body
(cross-contour ids addresses))))
(app-exp (rator rands)
(app-exp (lexical-address-calc-helper
rator
addresses)
(map (lambda (rand)
(lexical-address-calc-helper rand addresses))
rands))))))
(define lexical-address-calc
(lambda (pgm)
(a-program
(cases program pgm
(a-program (body)
(lexical-address-calc-helper body '()))))))
;> (lexical-address-calc
; (scan&parse
" let x = 1
y = 2
; in let a = +(x,2)
; p = proc (a, b) -(a, b)
; in (p a +(x,y))"))
;(a-program
; (let-exp
; (x y)
; ((lit-exp 1) (lit-exp 2))
; (let-exp
; (a p)
; ((primapp-exp
; (add-prim)
; ((lexvar-exp 0 0) (lit-exp 2)))
; (proc-exp
; (a b)
; (primapp-exp
; (substract-prim)
; ((lexvar-exp 0 0) (lexvar-exp 0 1)))))
; (app-exp
; (lexvar-exp 0 1)
; ((lexvar-exp 0 0)
; (primapp-exp
; (add-prim)
; ((lexvar-exp 1 0) (lexvar-exp 1 1))))))))
;Evaluation tests:
> ( run " let a = 1 in + ( a,1 ) " )
2
> ( run " let a = 1 in + ( a , b ) " )
;Error reported by apply-nameless-env:
;Error accessing free variable at (-1 -1)
;> (run
" let x = 1
y = 2
; in let a = +(x,2)
; p = proc (a, b) -(a, b)
; in (p a +(x,y))")
0
| null | https://raw.githubusercontent.com/rubenbarroso/EOPL/f9b3c03c2fcbaddf64694ee3243d54be95bfe31d/src/chapter3/3_25.scm | scheme | Some tests:
> (apply-nameless-env
(extend-nameless-env
(extend-nameless-env
(empty-nameless-env)))
> (apply-nameless-env
(extend-nameless-env
(extend-nameless-env
(empty-nameless-env)))
helpers
the interpreter
Helper procedures from exercise 1.31
we will represent free variables with (v -1 -1)
Exercise - Lexical address calculator
> (lexical-address-calc
(scan&parse
in let a = +(x,2)
p = proc (a, b) -(a, b)
in (p a +(x,y))"))
(a-program
(let-exp
(x y)
((lit-exp 1) (lit-exp 2))
(let-exp
(a p)
((primapp-exp
(add-prim)
((lexvar-exp 0 0) (lit-exp 2)))
(proc-exp
(a b)
(primapp-exp
(substract-prim)
((lexvar-exp 0 0) (lexvar-exp 0 1)))))
(app-exp
(lexvar-exp 0 1)
((lexvar-exp 0 0)
(primapp-exp
(add-prim)
((lexvar-exp 1 0) (lexvar-exp 1 1))))))))
Evaluation tests:
Error reported by apply-nameless-env:
Error accessing free variable at (-1 -1)
> (run
in let a = +(x,2)
p = proc (a, b) -(a, b)
in (p a +(x,y))") | (load "/Users/ruben/Dropbox/EOPL/src/interps/r5rs.scm")
(load "/Users/ruben/Dropbox/EOPL/src/interps/define-datatype.scm")
(load "/Users/ruben/Dropbox/EOPL/src/interps/sllgen.scm")
(define-datatype environment nameless-environment?
(empty-nameless-env-record)
(extended-nameless-env-record
(vals (list-of scheme-value?))
(env nameless-environment?)))
(define scheme-value? (lambda (v) #t))
(define empty-nameless-env
(lambda ()
(empty-nameless-env-record)))
(define extend-nameless-env
(lambda (vals env)
(extended-nameless-env-record vals env)))
(define apply-nameless-env
(lambda (env depth pos)
(if (= pos -1)
(eopl:error 'apply-nameless-env
"Error accessing free variable at (~s ~s)"
depth pos))
(cases environment env
(empty-nameless-env-record ()
(eopl:error 'apply-nameless-env "No binding for ~s" sym))
(extended-nameless-env-record (vals env)
(if (= depth 0)
(list-ref vals pos)
(apply-nameless-env env (- depth 1) pos))))))
' ( 24 4 )
' ( 5 28 )
0 1 )
4
' ( 24 4 )
' ( 5 28 )
1 1 )
28
(define scanner-spec-3-13
'((white-sp
(whitespace) skip)
(comment
("%" (arbno (not #\newline))) skip)
(identifier
(letter (arbno (or letter digit "?"))) symbol)
(number
(digit (arbno digit)) number)))
(define grammar-3-13
'((program
(expression)
a-program)
(expression
(number)
lit-exp)
(expression
(identifier)
var-exp)
(expression
("lexvar" "(" number number ")")
lexvar-exp)
(expression
(primitive "(" (separated-list expression ",") ")")
primapp-exp)
(expression
("if" expression "then" expression "else" expression)
if-exp)
(expression
("let" (arbno identifier "=" expression) "in" expression)
let-exp)
(expression
("proc" "(" (separated-list identifier ",") ")" expression)
proc-exp)
(expression
("(" expression (arbno expression) ")")
app-exp)
(primitive
("+")
add-prim)
(primitive
("-")
substract-prim)
(primitive
("*")
mult-prim)
(primitive
("add1")
incr-prim)
(primitive
("sub1")
decr-prim)
(primitive
("equal?")
equal-prim)
(primitive
("zero?")
zero-prim)
(primitive
("greater?")
greater-prim)
(primitive
("less?")
less-prim)))
(define scan&parse
(sllgen:make-string-parser
scanner-spec-3-13
grammar-3-13))
(sllgen:make-define-datatypes scanner-spec-3-13 grammar-3-13)
(define run
(lambda (string)
(eval-program
(lexical-address-calc
(scan&parse string)))))
(define true-value?
(lambda (x)
(not (zero? x))))
(define eval-program
(lambda (pgm)
(cases program pgm
(a-program (body)
(eval-expression body (init-nameless-env))))))
(define eval-expression
(lambda (exp env)
(cases expression exp
(lit-exp (datum) datum)
(var-exp (id) (eopl:error
'eval-expression
"var-exp should not appear in the instrumented interpreter"))
(lexvar-exp (depth pos) (apply-nameless-env env depth pos))
(primapp-exp (prim rands)
(let ((args (eval-rands rands env)))
(apply-primitive prim args)))
(if-exp (test-exp true-exp false-exp)
(if (true-value? (eval-expression test-exp env))
(eval-expression true-exp env)
(eval-expression false-exp env)))
(let-exp (ids rands body)
(let ((args (eval-rands rands env)))
(eval-expression body (extend-nameless-env args env))))
(proc-exp (ids body) (closure body env))
(app-exp (rator rands)
(let ((proc (eval-expression rator env))
(args (eval-rands rands env)))
(if (procval? proc)
(apply-procval proc args)
(eopl:error 'eval-expression
"Attempt to apply a non-procedure ~s" proc)))))))
(define eval-rands
(lambda (rands env)
(map (lambda (x) (eval-rand x env)) rands)))
(define eval-rand
(lambda (rand env)
(eval-expression rand env)))
(define apply-primitive
(lambda (prim args)
(cases primitive prim
(add-prim () (+ (car args) (cadr args)))
(substract-prim () (- (car args) (cadr args)))
(mult-prim () (* (car args) (cadr args)))
(incr-prim () (+ (car args) 1))
(decr-prim () (- (car args) 1))
(equal-prim () (if (= (car args) (cadr args)) 1 0))
(zero-prim () (if (zero? (car args)) 1 0))
(greater-prim () (if (> (car args) (cadr args)) 1 0))
(less-prim () (if (< (car args) (cadr args)) 1 0)))))
(define-datatype procval procval?
(closure
(body expression?)
(env nameless-environment?)))
(define apply-procval
(lambda (proc args)
(cases procval proc
(closure (body env)
(eval-expression body
(extend-nameless-env args env))))))
(define init-nameless-env
(lambda ()
(extend-nameless-env
'(1 5 10)
(empty-nameless-env))))
(define make-lexical-address
(lambda (v d p)
(list v ': d p)))
(define get-v
(lambda (address)
(car address)))
(define get-d
(lambda (address)
(caddr address)))
(define get-p
(lambda (address)
(cadddr address)))
(define increment-depth
(lambda (address)
(make-lexical-address (get-v address)
(+ 1 (get-d address))
(get-p address))))
(define get-lexical-address
(lambda (exp addresses)
(define iter
(lambda (lst)
(cond ((null? lst) (make-lexical-address exp -1 -1))
((eqv? exp (get-v (car lst))) (car lst))
(else (get-lexical-address exp (cdr lst))))))
(iter addresses)))
(define index-of
(lambda (v declarations)
(define helper
(lambda (lst index)
(cond ((null? lst) 'free)
((eqv? (car lst) v) index)
(else (helper (cdr lst) (+ index 1))))))
(helper declarations 0)))
(define cross-contour
(lambda (declarations addresses)
(let ((bound (filter-bound declarations))
(free (filter-free declarations addresses)))
(append bound free))))
(define filter-bound
(lambda (declarations)
(map (lambda (decl)
(make-lexical-address decl
0
(index-of decl declarations)))
declarations)))
(define filter-free
(lambda (declarations addresses)
(define iter
(lambda (lst)
(cond ((null? lst) '())
((not (memq (get-v (car lst)) declarations))
(cons (increment-depth (car lst))
(iter (cdr lst))))
(else (iter (cdr lst))))))
(iter addresses)))
(define lexical-address-calc-helper
(lambda (exp addresses)
(cases expression exp
(lit-exp (datum)
(lit-exp datum))
(var-exp (id)
(let ((lexical-address (get-lexical-address id addresses)))
(lexvar-exp (get-d lexical-address)
(get-p lexical-address))))
(lexvar-exp (depth pos)
(lexvar-exp depth pos))
(primapp-exp (prim rands)
(primapp-exp prim
(map (lambda (rand)
(lexical-address-calc-helper rand addresses))
rands)))
(if-exp (test-exp true-exp false-exp)
(if-exp (lexical-address-calc-helper test-exp addresses)
(lexical-address-calc-helper true-exp addresses)
(lexical-address-calc-helper false-exp addresses)))
(let-exp (ids rands body)
(let-exp ids
(map (lambda (rand)
(lexical-address-calc-helper rand addresses))
rands)
(lexical-address-calc-helper
body
(cross-contour ids addresses))))
(proc-exp (ids body)
(proc-exp ids
(lexical-address-calc-helper
body
(cross-contour ids addresses))))
(app-exp (rator rands)
(app-exp (lexical-address-calc-helper
rator
addresses)
(map (lambda (rand)
(lexical-address-calc-helper rand addresses))
rands))))))
(define lexical-address-calc
(lambda (pgm)
(a-program
(cases program pgm
(a-program (body)
(lexical-address-calc-helper body '()))))))
" let x = 1
y = 2
> ( run " let a = 1 in + ( a,1 ) " )
2
> ( run " let a = 1 in + ( a , b ) " )
" let x = 1
y = 2
0
|
e040cf570e21f2248dc1af3980a718a2f6a210deb86823ee2a38941578c4599d | Decentralized-Pictures/T4L3NT | fees_storage.mli | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
type error += Cannot_pay_storage_fee (* `Temporary *)
type error += Operation_quota_exceeded (* `Temporary *)
type error += Storage_limit_too_high (* `Permanent *)
* [ record_global_constant_storage_space size ] records
paid storage space for registering a new global constant .
Cost is < size > in bytes + 65 additional bytes for the key
hash of the expression . Returns new context and the cost .
paid storage space for registering a new global constant.
Cost is <size> in bytes + 65 additional bytes for the key
hash of the expression. Returns new context and the cost.
*)
val record_global_constant_storage_space :
Raw_context.t -> Z.t -> Raw_context.t * Z.t
* [ record_paid_storage_space contract ] updates the amount of storage
consumed by the [ contract ] and considered as accounted for as far as
future payment is concerned . Returns a new context , the total space
consumed by the [ contract ] , and the additional ( and unpaid ) space consumed
since the last call of this function on this [ contract ] .
consumed by the [contract] and considered as accounted for as far as
future payment is concerned. Returns a new context, the total space
consumed by the [contract], and the additional (and unpaid) space consumed
since the last call of this function on this [contract]. *)
val record_paid_storage_space :
Raw_context.t -> Contract_repr.t -> (Raw_context.t * Z.t * Z.t) tzresult Lwt.t
* [ ~storage_limit ] raises the [ Storage_limit_too_high ]
error iff [ storage_limit ] is negative or greater the constant
[ hard_storage_limit_per_operation ] .
error iff [storage_limit] is negative or greater the constant
[hard_storage_limit_per_operation]. *)
val check_storage_limit : Raw_context.t -> storage_limit:Z.t -> unit tzresult
(** [burn_storage_fees ctxt ~storage_limit ~payer consumed] takes funds from the
[payer] to pay the cost of the [consumed] storage. This function has an
optional parameter [~origin] that allows to set the origin of returned
balance updates (by default the parameter is set to [Block_application]).
Returns an updated context, an updated storage limit equal to
[storage_limit - consumed], and the relevant balance updates.
Raises the [Operation_quota_exceeded] error if [storage_limit < consumed].
Raises the [Cannot_pay_storage_fee] error if the funds from the [payer] are
not sufficient to pay the storage fees. *)
val burn_storage_fees :
?origin:Receipt_repr.update_origin ->
Raw_context.t ->
storage_limit:Z.t ->
payer:Token.source ->
Z.t ->
(Raw_context.t * Z.t * Receipt_repr.balance_updates) tzresult Lwt.t
(** Calls [burn_storage_fees] with the parameter [consumed] mapped to the
constant [origination_size]. *)
val burn_origination_fees :
?origin:Receipt_repr.update_origin ->
Raw_context.t ->
storage_limit:Z.t ->
payer:Token.source ->
(Raw_context.t * Z.t * Receipt_repr.balance_updates) tzresult Lwt.t
| null | https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/proto_012_Psithaca/lib_protocol/fees_storage.mli | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
`Temporary
`Temporary
`Permanent
* [burn_storage_fees ctxt ~storage_limit ~payer consumed] takes funds from the
[payer] to pay the cost of the [consumed] storage. This function has an
optional parameter [~origin] that allows to set the origin of returned
balance updates (by default the parameter is set to [Block_application]).
Returns an updated context, an updated storage limit equal to
[storage_limit - consumed], and the relevant balance updates.
Raises the [Operation_quota_exceeded] error if [storage_limit < consumed].
Raises the [Cannot_pay_storage_fee] error if the funds from the [payer] are
not sufficient to pay the storage fees.
* Calls [burn_storage_fees] with the parameter [consumed] mapped to the
constant [origination_size]. | Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
* [ record_global_constant_storage_space size ] records
paid storage space for registering a new global constant .
Cost is < size > in bytes + 65 additional bytes for the key
hash of the expression . Returns new context and the cost .
paid storage space for registering a new global constant.
Cost is <size> in bytes + 65 additional bytes for the key
hash of the expression. Returns new context and the cost.
*)
val record_global_constant_storage_space :
Raw_context.t -> Z.t -> Raw_context.t * Z.t
* [ record_paid_storage_space contract ] updates the amount of storage
consumed by the [ contract ] and considered as accounted for as far as
future payment is concerned . Returns a new context , the total space
consumed by the [ contract ] , and the additional ( and unpaid ) space consumed
since the last call of this function on this [ contract ] .
consumed by the [contract] and considered as accounted for as far as
future payment is concerned. Returns a new context, the total space
consumed by the [contract], and the additional (and unpaid) space consumed
since the last call of this function on this [contract]. *)
val record_paid_storage_space :
Raw_context.t -> Contract_repr.t -> (Raw_context.t * Z.t * Z.t) tzresult Lwt.t
* [ ~storage_limit ] raises the [ Storage_limit_too_high ]
error iff [ storage_limit ] is negative or greater the constant
[ hard_storage_limit_per_operation ] .
error iff [storage_limit] is negative or greater the constant
[hard_storage_limit_per_operation]. *)
val check_storage_limit : Raw_context.t -> storage_limit:Z.t -> unit tzresult
val burn_storage_fees :
?origin:Receipt_repr.update_origin ->
Raw_context.t ->
storage_limit:Z.t ->
payer:Token.source ->
Z.t ->
(Raw_context.t * Z.t * Receipt_repr.balance_updates) tzresult Lwt.t
val burn_origination_fees :
?origin:Receipt_repr.update_origin ->
Raw_context.t ->
storage_limit:Z.t ->
payer:Token.source ->
(Raw_context.t * Z.t * Receipt_repr.balance_updates) tzresult Lwt.t
|
5c689050e266c9e314ec853283b4170579f3203d642994b50af314b3d5625814 | ZHaskell/z-data | Regex.hs | |
Module : Z.Data . Text . Regex
Description : RE2 regex
Copyright : ( c ) , 2017 - 2018
License : BSD
Maintainer :
Stability : experimental
Portability : non - portable
Binding to google 's < RE2 > , microsoft did a nice job on RE2 regex syntaxs :
< -us/deployedge/edge-learnmore-regex > . Note GHC string literals need @\\@ to
be escaped , e.g.
> > > match ( regex " ( [ a - z0 - 9_\\.-]+)@([\\da - z\\.-]+)\\.([a - z\\.]{2,6 } ) " ) " please end email to , "
> > > ( " ",[Just " hello",Just " world",Just " com " ] , " , " )
Module : Z.Data.Text.Regex
Description : RE2 regex
Copyright : (c) Dong Han, 2017-2018
License : BSD
Maintainer :
Stability : experimental
Portability : non-portable
Binding to google's < RE2>, microsoft did a nice job on RE2 regex syntaxs:
<-us/deployedge/edge-learnmore-regex>. Note GHC string literals need @\\@ to
be escaped, e.g.
>>> match (regex "([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})") "please end email to , "
>>> ("",[Just "hello",Just "world",Just "com"],", ")
-}
module Z.Data.Text.Regex
( -- * RE2 regex
Regex, regex, RegexOpts(..), defaultRegexOpts, regexOpts
, escape, regexCaptureNum, regexPattern
, RegexException(..)
-- * regex operations
, test
, match
, replace
, extract
) where
import Control.Exception
import Control.Monad
import Data.Int
import Data.Word
import GHC.Stack
import GHC.Generics
import Foreign.Marshal.Utils (fromBool)
import System.IO.Unsafe
import qualified Z.Data.Text.Base as T
import qualified Z.Data.Text.Print as T
import qualified Z.Data.Vector.Base as V
import qualified Z.Data.Array as A
import Z.Foreign.CPtr
import Z.Foreign
-- | A compiled RE2 regex.
data Regex = Regex
{ regexPtr :: {-# UNPACK #-} !(CPtr Regex)
^ capturing group )
, regexPattern :: T.Text -- ^ Get back regex's pattern.
} deriving (Show, Generic)
deriving anyclass T.Print
-- | RE2 Regex options.
--
-- The options are ('defaultRegexOpts' in parentheses):
--
-- @
posix_syntax ( false ) restrict regexps to POSIX egrep syntax
longest_match ( false ) search for longest match , not first match
-- log_errors (true) log syntax and execution errors to ERROR
max_mem ( 8<<20 ) approx . max memory footprint of RE2
-- literal (false) interpret string as literal, not regexp
never_nl ( false ) never match \\n , even if it is in regexp
-- dot_nl (false) dot matches everything including new line
-- never_capture (false) parse all parens as non-capturing
-- case_sensitive (true) match is case-sensitive (regexp can override
-- with (?i) unless in posix_syntax mode)
-- @
--
-- The following options are only consulted when posix_syntax == true.
-- When posix_syntax == false, these features are always enabled and
-- cannot be turned off; to perform multi-line matching in that case,
begin the regexp with
--
-- @
perl_classes ( false ) allow 's \\d \\s \\w \\D \\S \\W
word_boundary ( false ) allow Perl 's \\b \\B ( word boundary and not )
-- one_line (false) ^ and $ only match beginning and end of text
-- @
--
data RegexOpts = RegexOpts
{ posix_syntax :: Bool
, longest_match :: Bool
, max_mem :: {-# UNPACK #-} !Int64
, literal :: Bool
, never_nl :: Bool
, dot_nl :: Bool
, never_capture :: Bool
, case_sensitive :: Bool
, perl_classes :: Bool
, word_boundary :: Bool
, one_line :: Bool
} deriving (Eq, Ord, Show, Generic)
deriving anyclass T.Print
-- | Default regex options, see 'RegexOpts'.
--
defaultRegexOpts :: RegexOpts
defaultRegexOpts = RegexOpts
False False hs_re2_kDefaultMaxMem
False False False False
True False False False
-- | Exception thrown when using regex.
data RegexException = InvalidRegexPattern T.Text CallStack deriving Show
instance Exception RegexException
-- | Compile a regex pattern, throw 'InvalidRegexPattern' in case of illegal patterns.
--
regex :: HasCallStack => T.Text -> Regex
# NOINLINE regex #
regex t = unsafePerformIO $ do
(cp, r) <- newCPtrUnsafe (\ mba# ->
withPrimVectorUnsafe
(T.getUTF8Bytes t)
(hs_re2_compile_pattern_default mba#))
p_hs_re2_delete_pattern
when (r == nullPtr) (throwIO (InvalidRegexPattern t callStack))
ok <- hs_re2_ok r
when (ok == 0) (throwIO (InvalidRegexPattern t callStack))
n <- withCPtr cp hs_num_capture_groups
return (Regex cp n t)
-- | Compile a regex pattern withOptions, throw 'InvalidRegexPattern' in case of illegal patterns.
regexOpts :: HasCallStack => RegexOpts -> T.Text -> Regex
# NOINLINE regexOpts #
regexOpts RegexOpts{..} t = unsafePerformIO $ do
(cp, r) <- newCPtrUnsafe ( \ mba# ->
withPrimVectorUnsafe (T.getUTF8Bytes t) $ \ p o l ->
hs_re2_compile_pattern mba# p o l
(fromBool posix_syntax )
(fromBool longest_match )
max_mem
(fromBool literal )
(fromBool never_nl )
(fromBool dot_nl )
(fromBool never_capture )
(fromBool case_sensitive)
(fromBool perl_classes )
(fromBool word_boundary )
(fromBool one_line ))
p_hs_re2_delete_pattern
when (r == nullPtr) (throwIO (InvalidRegexPattern t callStack))
ok <- hs_re2_ok r
when (ok == 0) (throwIO (InvalidRegexPattern t callStack))
n <- withCPtr cp hs_num_capture_groups
return (Regex cp n t)
-- | Escape a piece of text literal so that it can be safely used in regex pattern.
--
-- >>> escape "(\\d+)"
-- >>> "\\(\\\\d\\+\\)"
--
escape :: T.Text -> T.Text
# INLINABLE escape #
escape t = T.Text . unsafePerformIO . fromStdString $
withPrimVectorUnsafe (T.getUTF8Bytes t) hs_re2_quote_meta
-- | Check if text matched regex pattern.
test :: Regex -> T.Text -> Bool
# INLINABLE test #
test (Regex fp _ _) (T.Text bs) = unsafePerformIO $ do
withCPtr fp $ \ p ->
withPrimVectorUnsafe bs $ \ ba# s l -> do
r <- hs_re2_test p ba# s l
return $! r /= 0
-- | Check if text matched regex pattern,
-- if so return matched part, all capturing groups(from @\\1@) and the text after matched part.
--
-- @Nothing@ indicate a non-matching capturing group, e.g.
--
-- >>> match (regex "(foo)|(bar)baz") "barbazbla"
-- >>> ("barbaz",[Nothing,Just "bar"], "bla")
--
match :: Regex -> T.Text -> (T.Text, [Maybe T.Text], T.Text)
# INLINABLE match #
match (Regex fp n _) t@(T.Text bs@(V.PrimVector ba _ _)) = unsafePerformIO $ do
withCPtr fp $ \ p ->
withPrimVectorUnsafe bs $ \ ba# s l -> do
(starts, (lens, r)) <- allocPrimArrayUnsafe n $ \ p_starts ->
allocPrimArrayUnsafe n $ \ p_ends ->
hs_re2_match p ba# s l n p_starts p_ends
if r == 0
then return (T.empty, [], t)
else do
let !s0 = A.indexArr starts 0
!l0 = A.indexArr lens 0
caps = (map (\ !i ->
let !s' = A.indexArr starts i
!l' = A.indexArr lens i
in if l' == -1
then Nothing
else (Just (T.Text (V.PrimVector ba s' l')))) [1..n-1])
return (T.Text (V.PrimVector ba s0 l0)
, caps
, T.Text (V.PrimVector ba (s0+l0) (s+l-s0-l0)))
-- | Replace matched part in input with a rewrite pattern.
-- If no matched part found, return the original input.
--
-- >>> replace (regex "red") False "A red fox with red fur" "yellow"
-- >>> "A yellow fox with red fur"
> > > replace ( regex " red " ) True " A red fox with red fur " " yellow "
-- >>> "A yellow fox with yellow fur"
--
replace :: Regex
-> Bool -- ^ globally replace?
-> T.Text -- ^ input
-> T.Text -- ^ rewrite
-> T.Text
# INLINABLE replace #
replace (Regex fp _ _) g inp rew = T.Text . unsafePerformIO $ do
withCPtr fp $ \ p ->
withPrimVectorUnsafe (T.getUTF8Bytes inp) $ \ inpp inpoff inplen ->
withPrimVectorUnsafe (T.getUTF8Bytes rew) $ \ rewp rewoff rewlen ->
fromStdString ((if g then hs_re2_replace_g else hs_re2_replace)
p inpp inpoff inplen rewp rewoff rewlen)
-- | Extract capturing group to an extract pattern.
-- If no matched capturing group found, return an empty string.
--
> > > extract ( regex " ( \\d{4})-(\\d{2})-(\\d{2 } ) " ) " Today is 2020 - 12 - 15 " " month : \\2 , date : \\3 "
> > > " month : 12 , date : 15 "
--
extract :: Regex
-> T.Text -- ^ input
-> T.Text -- ^ extract
-> T.Text
# INLINABLE extract #
extract (Regex fp _ _) inp rew = T.Text . unsafePerformIO $ do
withCPtr fp $ \ p ->
withPrimVectorUnsafe (T.getUTF8Bytes inp) $ \ inpp inpoff inplen ->
withPrimVectorUnsafe (T.getUTF8Bytes rew) $ \ rewp rewoff rewlen ->
fromStdString (hs_re2_extract p inpp inpoff inplen rewp rewoff rewlen)
--------------------------------------------------------------------------------
foreign import ccall unsafe hs_re2_compile_pattern_default
:: MBA# (Ptr Regex) -> BA# Word8 -> Int -> Int
-> IO (Ptr Regex)
foreign import ccall unsafe hs_re2_compile_pattern
:: MBA# (Ptr Regex)
-> BA# Word8 -> Int -> Int
-> CBool -- ^ posix_syntax
-> CBool -- ^ longest_match
-> Int64 -- ^ max_mem
-> CBool -- ^ literal
^ never_nl
-> CBool -- ^ dot_nl
-> CBool -- ^ never_capture
-> CBool -- ^ case_sensitive
^ perl_classes
-> CBool -- ^ word_boundary
-> CBool -- ^ one_line
-> IO (Ptr Regex)
foreign import ccall unsafe "&hs_re2_delete_pattern" p_hs_re2_delete_pattern :: FunPtr (Ptr Regex -> IO ())
foreign import ccall unsafe hs_re2_ok :: Ptr Regex -> IO CInt
foreign import ccall unsafe hs_num_capture_groups :: Ptr Regex -> IO Int
foreign import ccall unsafe hs_re2_quote_meta :: BA# Word8 -> Int -> Int -> IO (Ptr StdString)
foreign import ccall unsafe hs_re2_match :: Ptr Regex
-> BA# Word8 -- ^ input
-> Int -- ^ input offest
-> Int -- ^ input length
-> Int -- ^ capture num
-> MBA# Int -- ^ capture starts
-> MBA# Int -- ^ capture lens
^ 0 for failure , 1 for success
foreign import ccall unsafe hs_re2_test :: Ptr Regex
-> BA# Word8 -- ^ input
-> Int -- ^ input offest
-> Int -- ^ input length
^ 0 for failure , 1 for success
foreign import ccall unsafe hs_re2_replace :: Ptr Regex
-> BA# Word8 -- ^ input
-> Int -- ^ input offest
-> Int -- ^ input length
-> BA# Word8 -- ^ rewrite
-> Int -- ^ rewrite offest
-> Int -- ^ rewrite length
-> IO (Ptr StdString) -- ^ NULL for failure
foreign import ccall unsafe hs_re2_replace_g :: Ptr Regex
-> BA# Word8 -- ^ input
-> Int -- ^ input offest
-> Int -- ^ input length
-> BA# Word8 -- ^ rewrite
-> Int -- ^ rewrite offest
-> Int -- ^ rewrite length
-> IO (Ptr StdString) -- ^ NULL for failure
foreign import ccall unsafe hs_re2_extract :: Ptr Regex
-> BA# Word8 -- ^ input
-> Int -- ^ input offest
-> Int -- ^ input length
-> BA# Word8 -- ^ rewrite
-> Int -- ^ rewrite offest
-> Int -- ^ rewrite length
-> IO (Ptr StdString) -- ^ NULL for failure
foreign import ccall unsafe hs_re2_kDefaultMaxMem :: Int64
| null | https://raw.githubusercontent.com/ZHaskell/z-data/82e31fea77ab9384000a21cb3fedcfd3eee6cc4a/Z/Data/Text/Regex.hs | haskell | * RE2 regex
* regex operations
| A compiled RE2 regex.
# UNPACK #
^ Get back regex's pattern.
| RE2 Regex options.
The options are ('defaultRegexOpts' in parentheses):
@
log_errors (true) log syntax and execution errors to ERROR
literal (false) interpret string as literal, not regexp
dot_nl (false) dot matches everything including new line
never_capture (false) parse all parens as non-capturing
case_sensitive (true) match is case-sensitive (regexp can override
with (?i) unless in posix_syntax mode)
@
The following options are only consulted when posix_syntax == true.
When posix_syntax == false, these features are always enabled and
cannot be turned off; to perform multi-line matching in that case,
@
one_line (false) ^ and $ only match beginning and end of text
@
# UNPACK #
| Default regex options, see 'RegexOpts'.
| Exception thrown when using regex.
| Compile a regex pattern, throw 'InvalidRegexPattern' in case of illegal patterns.
| Compile a regex pattern withOptions, throw 'InvalidRegexPattern' in case of illegal patterns.
| Escape a piece of text literal so that it can be safely used in regex pattern.
>>> escape "(\\d+)"
>>> "\\(\\\\d\\+\\)"
| Check if text matched regex pattern.
| Check if text matched regex pattern,
if so return matched part, all capturing groups(from @\\1@) and the text after matched part.
@Nothing@ indicate a non-matching capturing group, e.g.
>>> match (regex "(foo)|(bar)baz") "barbazbla"
>>> ("barbaz",[Nothing,Just "bar"], "bla")
| Replace matched part in input with a rewrite pattern.
If no matched part found, return the original input.
>>> replace (regex "red") False "A red fox with red fur" "yellow"
>>> "A yellow fox with red fur"
>>> "A yellow fox with yellow fur"
^ globally replace?
^ input
^ rewrite
| Extract capturing group to an extract pattern.
If no matched capturing group found, return an empty string.
^ input
^ extract
------------------------------------------------------------------------------
^ posix_syntax
^ longest_match
^ max_mem
^ literal
^ dot_nl
^ never_capture
^ case_sensitive
^ word_boundary
^ one_line
^ input
^ input offest
^ input length
^ capture num
^ capture starts
^ capture lens
^ input
^ input offest
^ input length
^ input
^ input offest
^ input length
^ rewrite
^ rewrite offest
^ rewrite length
^ NULL for failure
^ input
^ input offest
^ input length
^ rewrite
^ rewrite offest
^ rewrite length
^ NULL for failure
^ input
^ input offest
^ input length
^ rewrite
^ rewrite offest
^ rewrite length
^ NULL for failure | |
Module : Z.Data . Text . Regex
Description : RE2 regex
Copyright : ( c ) , 2017 - 2018
License : BSD
Maintainer :
Stability : experimental
Portability : non - portable
Binding to google 's < RE2 > , microsoft did a nice job on RE2 regex syntaxs :
< -us/deployedge/edge-learnmore-regex > . Note GHC string literals need @\\@ to
be escaped , e.g.
> > > match ( regex " ( [ a - z0 - 9_\\.-]+)@([\\da - z\\.-]+)\\.([a - z\\.]{2,6 } ) " ) " please end email to , "
> > > ( " ",[Just " hello",Just " world",Just " com " ] , " , " )
Module : Z.Data.Text.Regex
Description : RE2 regex
Copyright : (c) Dong Han, 2017-2018
License : BSD
Maintainer :
Stability : experimental
Portability : non-portable
Binding to google's < RE2>, microsoft did a nice job on RE2 regex syntaxs:
<-us/deployedge/edge-learnmore-regex>. Note GHC string literals need @\\@ to
be escaped, e.g.
>>> match (regex "([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})") "please end email to , "
>>> ("",[Just "hello",Just "world",Just "com"],", ")
-}
module Z.Data.Text.Regex
Regex, regex, RegexOpts(..), defaultRegexOpts, regexOpts
, escape, regexCaptureNum, regexPattern
, RegexException(..)
, test
, match
, replace
, extract
) where
import Control.Exception
import Control.Monad
import Data.Int
import Data.Word
import GHC.Stack
import GHC.Generics
import Foreign.Marshal.Utils (fromBool)
import System.IO.Unsafe
import qualified Z.Data.Text.Base as T
import qualified Z.Data.Text.Print as T
import qualified Z.Data.Vector.Base as V
import qualified Z.Data.Array as A
import Z.Foreign.CPtr
import Z.Foreign
data Regex = Regex
^ capturing group )
} deriving (Show, Generic)
deriving anyclass T.Print
posix_syntax ( false ) restrict regexps to POSIX egrep syntax
longest_match ( false ) search for longest match , not first match
max_mem ( 8<<20 ) approx . max memory footprint of RE2
never_nl ( false ) never match \\n , even if it is in regexp
begin the regexp with
perl_classes ( false ) allow 's \\d \\s \\w \\D \\S \\W
word_boundary ( false ) allow Perl 's \\b \\B ( word boundary and not )
data RegexOpts = RegexOpts
{ posix_syntax :: Bool
, longest_match :: Bool
, literal :: Bool
, never_nl :: Bool
, dot_nl :: Bool
, never_capture :: Bool
, case_sensitive :: Bool
, perl_classes :: Bool
, word_boundary :: Bool
, one_line :: Bool
} deriving (Eq, Ord, Show, Generic)
deriving anyclass T.Print
defaultRegexOpts :: RegexOpts
defaultRegexOpts = RegexOpts
False False hs_re2_kDefaultMaxMem
False False False False
True False False False
data RegexException = InvalidRegexPattern T.Text CallStack deriving Show
instance Exception RegexException
regex :: HasCallStack => T.Text -> Regex
# NOINLINE regex #
regex t = unsafePerformIO $ do
(cp, r) <- newCPtrUnsafe (\ mba# ->
withPrimVectorUnsafe
(T.getUTF8Bytes t)
(hs_re2_compile_pattern_default mba#))
p_hs_re2_delete_pattern
when (r == nullPtr) (throwIO (InvalidRegexPattern t callStack))
ok <- hs_re2_ok r
when (ok == 0) (throwIO (InvalidRegexPattern t callStack))
n <- withCPtr cp hs_num_capture_groups
return (Regex cp n t)
regexOpts :: HasCallStack => RegexOpts -> T.Text -> Regex
# NOINLINE regexOpts #
regexOpts RegexOpts{..} t = unsafePerformIO $ do
(cp, r) <- newCPtrUnsafe ( \ mba# ->
withPrimVectorUnsafe (T.getUTF8Bytes t) $ \ p o l ->
hs_re2_compile_pattern mba# p o l
(fromBool posix_syntax )
(fromBool longest_match )
max_mem
(fromBool literal )
(fromBool never_nl )
(fromBool dot_nl )
(fromBool never_capture )
(fromBool case_sensitive)
(fromBool perl_classes )
(fromBool word_boundary )
(fromBool one_line ))
p_hs_re2_delete_pattern
when (r == nullPtr) (throwIO (InvalidRegexPattern t callStack))
ok <- hs_re2_ok r
when (ok == 0) (throwIO (InvalidRegexPattern t callStack))
n <- withCPtr cp hs_num_capture_groups
return (Regex cp n t)
escape :: T.Text -> T.Text
# INLINABLE escape #
escape t = T.Text . unsafePerformIO . fromStdString $
withPrimVectorUnsafe (T.getUTF8Bytes t) hs_re2_quote_meta
test :: Regex -> T.Text -> Bool
# INLINABLE test #
test (Regex fp _ _) (T.Text bs) = unsafePerformIO $ do
withCPtr fp $ \ p ->
withPrimVectorUnsafe bs $ \ ba# s l -> do
r <- hs_re2_test p ba# s l
return $! r /= 0
match :: Regex -> T.Text -> (T.Text, [Maybe T.Text], T.Text)
# INLINABLE match #
match (Regex fp n _) t@(T.Text bs@(V.PrimVector ba _ _)) = unsafePerformIO $ do
withCPtr fp $ \ p ->
withPrimVectorUnsafe bs $ \ ba# s l -> do
(starts, (lens, r)) <- allocPrimArrayUnsafe n $ \ p_starts ->
allocPrimArrayUnsafe n $ \ p_ends ->
hs_re2_match p ba# s l n p_starts p_ends
if r == 0
then return (T.empty, [], t)
else do
let !s0 = A.indexArr starts 0
!l0 = A.indexArr lens 0
caps = (map (\ !i ->
let !s' = A.indexArr starts i
!l' = A.indexArr lens i
in if l' == -1
then Nothing
else (Just (T.Text (V.PrimVector ba s' l')))) [1..n-1])
return (T.Text (V.PrimVector ba s0 l0)
, caps
, T.Text (V.PrimVector ba (s0+l0) (s+l-s0-l0)))
> > > replace ( regex " red " ) True " A red fox with red fur " " yellow "
replace :: Regex
-> T.Text
# INLINABLE replace #
replace (Regex fp _ _) g inp rew = T.Text . unsafePerformIO $ do
withCPtr fp $ \ p ->
withPrimVectorUnsafe (T.getUTF8Bytes inp) $ \ inpp inpoff inplen ->
withPrimVectorUnsafe (T.getUTF8Bytes rew) $ \ rewp rewoff rewlen ->
fromStdString ((if g then hs_re2_replace_g else hs_re2_replace)
p inpp inpoff inplen rewp rewoff rewlen)
> > > extract ( regex " ( \\d{4})-(\\d{2})-(\\d{2 } ) " ) " Today is 2020 - 12 - 15 " " month : \\2 , date : \\3 "
> > > " month : 12 , date : 15 "
extract :: Regex
-> T.Text
# INLINABLE extract #
extract (Regex fp _ _) inp rew = T.Text . unsafePerformIO $ do
withCPtr fp $ \ p ->
withPrimVectorUnsafe (T.getUTF8Bytes inp) $ \ inpp inpoff inplen ->
withPrimVectorUnsafe (T.getUTF8Bytes rew) $ \ rewp rewoff rewlen ->
fromStdString (hs_re2_extract p inpp inpoff inplen rewp rewoff rewlen)
foreign import ccall unsafe hs_re2_compile_pattern_default
:: MBA# (Ptr Regex) -> BA# Word8 -> Int -> Int
-> IO (Ptr Regex)
foreign import ccall unsafe hs_re2_compile_pattern
:: MBA# (Ptr Regex)
-> BA# Word8 -> Int -> Int
^ never_nl
^ perl_classes
-> IO (Ptr Regex)
foreign import ccall unsafe "&hs_re2_delete_pattern" p_hs_re2_delete_pattern :: FunPtr (Ptr Regex -> IO ())
foreign import ccall unsafe hs_re2_ok :: Ptr Regex -> IO CInt
foreign import ccall unsafe hs_num_capture_groups :: Ptr Regex -> IO Int
foreign import ccall unsafe hs_re2_quote_meta :: BA# Word8 -> Int -> Int -> IO (Ptr StdString)
foreign import ccall unsafe hs_re2_match :: Ptr Regex
^ 0 for failure , 1 for success
foreign import ccall unsafe hs_re2_test :: Ptr Regex
^ 0 for failure , 1 for success
foreign import ccall unsafe hs_re2_replace :: Ptr Regex
foreign import ccall unsafe hs_re2_replace_g :: Ptr Regex
foreign import ccall unsafe hs_re2_extract :: Ptr Regex
foreign import ccall unsafe hs_re2_kDefaultMaxMem :: Int64
|
4becd54126d7257f8a7b5ee315fb0e1b65709255211b769d46eedda826775a3b | walfie/ac-tune-maker | Note.ml | type note =
| Rest
| Hold
| G
| A
| B
| C
| D
| E
| F
| G'
| A'
| B'
| C'
| D'
| E'
| Random
type meta =
{ index : int
; as_str : I18n.t
; color : string
; next : note option
; prev : note option
}
let all = [| Rest; Hold; G; A; B; C; D; E; F; G'; A'; B'; C'; D'; E'; Random |]
let random () = Js.Array.length all |> Js.Math.random_int 0 |> Js.Array.unsafe_get all
let meta n =
let m index (en, fr) color next prev =
let open I18n in
{ index; as_str = { en; fr }; color; next; prev }
in
match n with
| Rest -> m 0 ("z", "z") "#aeadae" (Some Hold) None
| Hold -> m 1 ("-", "-") "#b063d5" (Some G) (Some Rest)
| G -> m 2 ("g", "sol") "#b428d4" (Some A) (Some Hold)
| A -> m 3 ("a", "la") "#2689cf" (Some B) (Some G)
| B -> m 4 ("b", "si") "#0fb8d9" (Some C) (Some A)
| C -> m 5 ("c", "do") "#30e2a0" (Some D) (Some B)
| D -> m 6 ("d", {js|ré|js}) "#0cc408" (Some E) (Some C)
| E -> m 7 ("e", "mi") "#88db08" (Some F) (Some D)
| F -> m 8 ("f", "fa") "#f1d009" (Some G') (Some E)
| G' -> m 9 ("G", "Sol") "#f5a306" (Some A') (Some F)
| A' -> m 10 ("A", "La") "#eb6d04" (Some B') (Some G')
| B' -> m 11 ("B", "Si") "#df5506" (Some C') (Some A')
| C' -> m 12 ("C", "Do") "#ce2310" (Some D') (Some B')
| D' -> m 13 ("D", {js|Ré|js}) "#d21e87" (Some E') (Some C')
| E' -> m 14 ("E", "Mi") "#c336a0" (Some Random) (Some D')
| Random -> m 15 ("q", "q") "#f35fd2" None (Some E')
;;
let next note = (meta note).next
let prev note = (meta note).prev
let color note = (meta note).color
let string_of_note note = (meta note).as_str
let from_char = function
| "z" -> Some Rest
| "-" -> Some Hold
| "g" -> Some G
| "a" -> Some A
| "b" -> Some B
| "c" -> Some C
| "d" -> Some D
| "e" -> Some E
| "f" -> Some F
| "G" -> Some G'
| "A" -> Some A'
| "B" -> Some B'
| "C" -> Some C'
| "D" -> Some D'
| "E" -> Some E'
| "q" -> Some Random
| _ -> None
;;
let notes_of_string str =
let get_or_rest c = from_char c |. Belt.Option.getWithDefault Rest in
Js.String.split "" str |> Array.map get_or_rest |> Array.to_list
;;
let has_next = function
| Random -> false
| _ -> true
;;
let has_prev = function
| Rest -> false
| _ -> true
;;
| null | https://raw.githubusercontent.com/walfie/ac-tune-maker/fe98aa88ae643630a572612367411b63da60df92/src/Note.ml | ocaml | type note =
| Rest
| Hold
| G
| A
| B
| C
| D
| E
| F
| G'
| A'
| B'
| C'
| D'
| E'
| Random
type meta =
{ index : int
; as_str : I18n.t
; color : string
; next : note option
; prev : note option
}
let all = [| Rest; Hold; G; A; B; C; D; E; F; G'; A'; B'; C'; D'; E'; Random |]
let random () = Js.Array.length all |> Js.Math.random_int 0 |> Js.Array.unsafe_get all
let meta n =
let m index (en, fr) color next prev =
let open I18n in
{ index; as_str = { en; fr }; color; next; prev }
in
match n with
| Rest -> m 0 ("z", "z") "#aeadae" (Some Hold) None
| Hold -> m 1 ("-", "-") "#b063d5" (Some G) (Some Rest)
| G -> m 2 ("g", "sol") "#b428d4" (Some A) (Some Hold)
| A -> m 3 ("a", "la") "#2689cf" (Some B) (Some G)
| B -> m 4 ("b", "si") "#0fb8d9" (Some C) (Some A)
| C -> m 5 ("c", "do") "#30e2a0" (Some D) (Some B)
| D -> m 6 ("d", {js|ré|js}) "#0cc408" (Some E) (Some C)
| E -> m 7 ("e", "mi") "#88db08" (Some F) (Some D)
| F -> m 8 ("f", "fa") "#f1d009" (Some G') (Some E)
| G' -> m 9 ("G", "Sol") "#f5a306" (Some A') (Some F)
| A' -> m 10 ("A", "La") "#eb6d04" (Some B') (Some G')
| B' -> m 11 ("B", "Si") "#df5506" (Some C') (Some A')
| C' -> m 12 ("C", "Do") "#ce2310" (Some D') (Some B')
| D' -> m 13 ("D", {js|Ré|js}) "#d21e87" (Some E') (Some C')
| E' -> m 14 ("E", "Mi") "#c336a0" (Some Random) (Some D')
| Random -> m 15 ("q", "q") "#f35fd2" None (Some E')
;;
let next note = (meta note).next
let prev note = (meta note).prev
let color note = (meta note).color
let string_of_note note = (meta note).as_str
let from_char = function
| "z" -> Some Rest
| "-" -> Some Hold
| "g" -> Some G
| "a" -> Some A
| "b" -> Some B
| "c" -> Some C
| "d" -> Some D
| "e" -> Some E
| "f" -> Some F
| "G" -> Some G'
| "A" -> Some A'
| "B" -> Some B'
| "C" -> Some C'
| "D" -> Some D'
| "E" -> Some E'
| "q" -> Some Random
| _ -> None
;;
let notes_of_string str =
let get_or_rest c = from_char c |. Belt.Option.getWithDefault Rest in
Js.String.split "" str |> Array.map get_or_rest |> Array.to_list
;;
let has_next = function
| Random -> false
| _ -> true
;;
let has_prev = function
| Rest -> false
| _ -> true
;;
| |
d2ee555751f5adea4f20134f996302d9025d8d6333b900da80a19f1e4f664fd3 | lspitzner/brittany | Test380.hs | -- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
func :: [a -> b]
| null | https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test380.hs | haskell | brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft } | func :: [a -> b]
|
b3af49c012c5ae2be02d1bdd155068c9ad2854d8c754e36364a2403fea156d16 | anoma/juvix | Transformation.hs | module Asm.Transformation where
import Asm.Transformation.Prealloc qualified as Prealloc
import Base
allTests :: TestTree
allTests = testGroup "JuvixAsm transformations" [Prealloc.allTests]
| null | https://raw.githubusercontent.com/anoma/juvix/9d4f843262b7bf14ad8f943988bf1cc5bffdc887/test/Asm/Transformation.hs | haskell | module Asm.Transformation where
import Asm.Transformation.Prealloc qualified as Prealloc
import Base
allTests :: TestTree
allTests = testGroup "JuvixAsm transformations" [Prealloc.allTests]
| |
13acd6b40006fb819d835039f035bf2e02c95a1fa8f8c3a01c5f389f8631fdf6 | input-output-hk/cardano-ledger | Example.hs | # LANGUAGE DataKinds #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeApplications #
module Test.Cardano.Chain.Update.Example (
exampleApplicationName,
exampleProtocolVersion,
exampleProtocolParameters,
exampleProtocolParametersUpdate,
exampleSoftwareVersion,
exampleSystemTag,
exampleInstallerHash,
examplePayload,
exampleProof,
exampleProposal,
exampleProposalBody,
exampleUpId,
exampleVote,
)
where
import Cardano.Chain.Common (
TxFeePolicy (..),
TxSizeLinear (..),
mkKnownLovelace,
rationalToLovelacePortion,
)
import Cardano.Chain.Slotting (EpochNumber (..), SlotNumber (..))
import Cardano.Chain.Update (
ApplicationName (..),
InstallerHash (..),
Payload,
Proof,
Proposal,
ProposalBody (..),
ProtocolParameters (..),
ProtocolParametersUpdate (..),
ProtocolVersion (..),
SoftforkRule (..),
SoftwareVersion (..),
SystemTag (..),
UpId,
Vote,
mkProof,
payload,
signProposal,
signVote,
)
import Cardano.Crypto (ProtocolMagicId (..), serializeCborHash)
import Cardano.Crypto.Raw (Raw (..))
import Cardano.Prelude
import Data.List ((!!))
import qualified Data.Map.Strict as Map
import Test.Cardano.Crypto.CBOR (getBytes)
import Test.Cardano.Crypto.Example (exampleSafeSigner)
import Test.Cardano.Prelude
exampleApplicationName :: ApplicationName
exampleApplicationName = ApplicationName "Golden"
exampleProtocolVersion :: ProtocolVersion
exampleProtocolVersion = ProtocolVersion 1 1 1
exampleProtocolParameters :: ProtocolParameters
exampleProtocolParameters =
ProtocolParameters
(999 :: Word16)
(999 :: Natural)
(999 :: Natural)
(999 :: Natural)
(999 :: Natural)
(999 :: Natural)
(rationalToLovelacePortion 99e-15)
(rationalToLovelacePortion 99e-15)
(rationalToLovelacePortion 99e-15)
(rationalToLovelacePortion 99e-15)
(SlotNumber 99)
sfrule
(TxFeePolicyTxSizeLinear tslin)
(EpochNumber 99)
where
tslin = TxSizeLinear c1' c2'
c1' = mkKnownLovelace @999
c2' = 77 :: Rational
sfrule =
SoftforkRule
(rationalToLovelacePortion 99e-15)
(rationalToLovelacePortion 99e-15)
(rationalToLovelacePortion 99e-15)
exampleProtocolParametersUpdate :: ProtocolParametersUpdate
exampleProtocolParametersUpdate =
ProtocolParametersUpdate
(Just (999 :: Word16))
(Just (999 :: Natural))
(Just (999 :: Natural))
(Just (999 :: Natural))
(Just (999 :: Natural))
(Just (999 :: Natural))
(Just $ rationalToLovelacePortion 99e-15)
(Just $ rationalToLovelacePortion 99e-15)
(Just $ rationalToLovelacePortion 99e-15)
(Just $ rationalToLovelacePortion 99e-15)
(Just $ SlotNumber 99)
(Just sfrule')
(Just $ TxFeePolicyTxSizeLinear tslin')
(Just $ EpochNumber 99)
where
tslin' = TxSizeLinear co1 co2
co1 = mkKnownLovelace @999
co2 = 77 :: Rational
sfrule' =
SoftforkRule
(rationalToLovelacePortion 99e-15)
(rationalToLovelacePortion 99e-15)
(rationalToLovelacePortion 99e-15)
exampleSystemTag :: SystemTag
exampleSystemTag = exampleSystemTags 0 1 !! 0
exampleSystemTags :: Int -> Int -> [SystemTag]
exampleSystemTags offset count =
map
(toSystemTag . (* offset))
[0 .. count - 1]
where
toSystemTag start = SystemTag (getText start 16)
exampleInstallerHash :: InstallerHash
exampleInstallerHash = exampleInstallerHashes 10 2 !! 1
exampleInstallerHashes :: Int -> Int -> [InstallerHash]
exampleInstallerHashes offset count =
map
(toInstallerHash . (* offset))
[0 .. count - 1]
where
toInstallerHash start = InstallerHash . serializeCborHash . Raw $ getBytes start 128
exampleUpId :: UpId
exampleUpId = serializeCborHash exampleProposal
examplePayload :: Payload
examplePayload = payload up uv
where
up = Just exampleProposal
uv = [exampleVote]
exampleProof :: Proof
exampleProof = mkProof examplePayload
exampleProposal :: Proposal
exampleProposal = signProposal pm exampleProposalBody ss
where
pm = ProtocolMagicId 0
ss = exampleSafeSigner 0
exampleProposalBody :: ProposalBody
exampleProposalBody = ProposalBody bv bvm sv hm
where
bv = exampleProtocolVersion
bvm = exampleProtocolParametersUpdate
sv = exampleSoftwareVersion
hm =
Map.fromList $ zip (exampleSystemTags 10 5) (exampleInstallerHashes 10 5)
exampleVote :: Vote
exampleVote = signVote pm ui ar ss
where
pm = ProtocolMagicId 0
ss = exampleSafeSigner 0
ui = exampleUpId
ar = True
exampleSoftwareVersion :: SoftwareVersion
exampleSoftwareVersion = SoftwareVersion (ApplicationName "Golden") 99
| null | https://raw.githubusercontent.com/input-output-hk/cardano-ledger/31c0bb1f5e78e40b83adfd1a916e69f47fdc9835/eras/byron/ledger/impl/test/Test/Cardano/Chain/Update/Example.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE DataKinds #
# LANGUAGE TypeApplications #
module Test.Cardano.Chain.Update.Example (
exampleApplicationName,
exampleProtocolVersion,
exampleProtocolParameters,
exampleProtocolParametersUpdate,
exampleSoftwareVersion,
exampleSystemTag,
exampleInstallerHash,
examplePayload,
exampleProof,
exampleProposal,
exampleProposalBody,
exampleUpId,
exampleVote,
)
where
import Cardano.Chain.Common (
TxFeePolicy (..),
TxSizeLinear (..),
mkKnownLovelace,
rationalToLovelacePortion,
)
import Cardano.Chain.Slotting (EpochNumber (..), SlotNumber (..))
import Cardano.Chain.Update (
ApplicationName (..),
InstallerHash (..),
Payload,
Proof,
Proposal,
ProposalBody (..),
ProtocolParameters (..),
ProtocolParametersUpdate (..),
ProtocolVersion (..),
SoftforkRule (..),
SoftwareVersion (..),
SystemTag (..),
UpId,
Vote,
mkProof,
payload,
signProposal,
signVote,
)
import Cardano.Crypto (ProtocolMagicId (..), serializeCborHash)
import Cardano.Crypto.Raw (Raw (..))
import Cardano.Prelude
import Data.List ((!!))
import qualified Data.Map.Strict as Map
import Test.Cardano.Crypto.CBOR (getBytes)
import Test.Cardano.Crypto.Example (exampleSafeSigner)
import Test.Cardano.Prelude
exampleApplicationName :: ApplicationName
exampleApplicationName = ApplicationName "Golden"
exampleProtocolVersion :: ProtocolVersion
exampleProtocolVersion = ProtocolVersion 1 1 1
exampleProtocolParameters :: ProtocolParameters
exampleProtocolParameters =
ProtocolParameters
(999 :: Word16)
(999 :: Natural)
(999 :: Natural)
(999 :: Natural)
(999 :: Natural)
(999 :: Natural)
(rationalToLovelacePortion 99e-15)
(rationalToLovelacePortion 99e-15)
(rationalToLovelacePortion 99e-15)
(rationalToLovelacePortion 99e-15)
(SlotNumber 99)
sfrule
(TxFeePolicyTxSizeLinear tslin)
(EpochNumber 99)
where
tslin = TxSizeLinear c1' c2'
c1' = mkKnownLovelace @999
c2' = 77 :: Rational
sfrule =
SoftforkRule
(rationalToLovelacePortion 99e-15)
(rationalToLovelacePortion 99e-15)
(rationalToLovelacePortion 99e-15)
exampleProtocolParametersUpdate :: ProtocolParametersUpdate
exampleProtocolParametersUpdate =
ProtocolParametersUpdate
(Just (999 :: Word16))
(Just (999 :: Natural))
(Just (999 :: Natural))
(Just (999 :: Natural))
(Just (999 :: Natural))
(Just (999 :: Natural))
(Just $ rationalToLovelacePortion 99e-15)
(Just $ rationalToLovelacePortion 99e-15)
(Just $ rationalToLovelacePortion 99e-15)
(Just $ rationalToLovelacePortion 99e-15)
(Just $ SlotNumber 99)
(Just sfrule')
(Just $ TxFeePolicyTxSizeLinear tslin')
(Just $ EpochNumber 99)
where
tslin' = TxSizeLinear co1 co2
co1 = mkKnownLovelace @999
co2 = 77 :: Rational
sfrule' =
SoftforkRule
(rationalToLovelacePortion 99e-15)
(rationalToLovelacePortion 99e-15)
(rationalToLovelacePortion 99e-15)
exampleSystemTag :: SystemTag
exampleSystemTag = exampleSystemTags 0 1 !! 0
exampleSystemTags :: Int -> Int -> [SystemTag]
exampleSystemTags offset count =
map
(toSystemTag . (* offset))
[0 .. count - 1]
where
toSystemTag start = SystemTag (getText start 16)
exampleInstallerHash :: InstallerHash
exampleInstallerHash = exampleInstallerHashes 10 2 !! 1
exampleInstallerHashes :: Int -> Int -> [InstallerHash]
exampleInstallerHashes offset count =
map
(toInstallerHash . (* offset))
[0 .. count - 1]
where
toInstallerHash start = InstallerHash . serializeCborHash . Raw $ getBytes start 128
exampleUpId :: UpId
exampleUpId = serializeCborHash exampleProposal
examplePayload :: Payload
examplePayload = payload up uv
where
up = Just exampleProposal
uv = [exampleVote]
exampleProof :: Proof
exampleProof = mkProof examplePayload
exampleProposal :: Proposal
exampleProposal = signProposal pm exampleProposalBody ss
where
pm = ProtocolMagicId 0
ss = exampleSafeSigner 0
exampleProposalBody :: ProposalBody
exampleProposalBody = ProposalBody bv bvm sv hm
where
bv = exampleProtocolVersion
bvm = exampleProtocolParametersUpdate
sv = exampleSoftwareVersion
hm =
Map.fromList $ zip (exampleSystemTags 10 5) (exampleInstallerHashes 10 5)
exampleVote :: Vote
exampleVote = signVote pm ui ar ss
where
pm = ProtocolMagicId 0
ss = exampleSafeSigner 0
ui = exampleUpId
ar = True
exampleSoftwareVersion :: SoftwareVersion
exampleSoftwareVersion = SoftwareVersion (ApplicationName "Golden") 99
|
de1066dddc92b621f61239e67dbe3fd8ffada14206f09ee44894788fa5a3dd7e | Frama-C/Frama-C-snapshot | export_whycore.ml | (**************************************************************************)
(* *)
This file is part of WP plug - in of Frama - C.
(* *)
Copyright ( C ) 2007 - 2019
CEA ( Commissariat a l'energie atomique et aux energies
(* alternatives) *)
(* *)
(* 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 , version 2.1 .
(* *)
(* It 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. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
(* -------------------------------------------------------------------------- *)
--- Common Exportation Engine for Alt - Ergo and Why3 ---
(* -------------------------------------------------------------------------- *)
open Logic
open Format
open Plib
open Engine
open Export
module Make(T : Term) =
struct
open T
module T = T
module E = Export.Make(T)
module Env = E.Env
type trigger = (T.var,Fun.t) ftrigger
type typedef = (tau,Field.t,Fun.t) ftypedef
let rec full_trigger = function
| TgAny -> false
| TgVar _ -> true
| TgGet(a,k) -> full_trigger a && full_trigger k
| TgSet(a,k,v) -> full_trigger a && full_trigger k && full_trigger v
| TgFun(_,xs) | TgProp(_,xs) -> List.for_all full_trigger xs
let rec full_triggers = function
| [] -> []
| ts :: tgs ->
match List.filter full_trigger ts with
| [] -> full_triggers tgs
| ts -> ts :: full_triggers tgs
class virtual engine =
object(self)
inherit E.engine
(* -------------------------------------------------------------------------- *)
(* --- Types --- *)
(* -------------------------------------------------------------------------- *)
method t_int = "int"
method t_real = "real"
method t_bool = "bool"
method t_prop = "prop"
method pp_tvar fmt k =
if 1 <= k && k <= 26
then fprintf fmt "'%c" (char_of_int (int_of_char 'a' + k - 1))
else fprintf fmt "'_%d" k
(* -------------------------------------------------------------------------- *)
(* --- Scope --- *)
(* -------------------------------------------------------------------------- *)
method op_scope _ = None
(* -------------------------------------------------------------------------- *)
(* --- Arrays --- *)
(* -------------------------------------------------------------------------- *)
method pp_array_get fmt a k =
fprintf fmt "@[<hov 2>%a[%a]@]" self#pp_atom a self#pp_flow k
method pp_array_set fmt a k v =
fprintf fmt "@[<hov 2>%a[%a@ <- %a]@]"
self#pp_atom a self#pp_atom k self#pp_flow v
(* -------------------------------------------------------------------------- *)
(* --- Records --- *)
(* -------------------------------------------------------------------------- *)
method virtual op_record : string * string
method pp_get_field fmt r f =
fprintf fmt "%a.%s" self#pp_atom r (self#field f)
method pp_def_fields fmt fvs =
let base,fvs = match T.record_with fvs with
| None -> None,fvs | Some(r,fvs) -> Some r,fvs in
begin
let (left,right) = self#op_record in
fprintf fmt "@[<hov 2>%s" left ;
Plib.iteri
(fun i (f,v) ->
( match i , base with
| (Isingle | Ifirst) , Some r ->
fprintf fmt "@ %a with" self#pp_flow r
| _ -> () ) ;
( match i with
| Ifirst | Imiddle ->
fprintf fmt "@ @[<hov 2>%s = %a ;@]"
(self#field f) self#pp_flow v
| Isingle | Ilast ->
fprintf fmt "@ @[<hov 2>%s = %a@]"
(self#field f) self#pp_flow v )
) fvs ;
fprintf fmt "@ %s@]" right ;
end
(* -------------------------------------------------------------------------- *)
(* --- Higher Order --- *)
(* -------------------------------------------------------------------------- *)
method pp_apply (_:cmode) (_:term) (_:formatter) (_:term list) =
failwith "Qed.Export.Why: higher-order application"
(* -------------------------------------------------------------------------- *)
(* --- Higher Order --- *)
(* -------------------------------------------------------------------------- *)
method pp_param fmt ((x,t) : string * tau) =
fprintf fmt "%a:%a" self#pp_var x self#pp_tau t
method pp_lambda (_:formatter) (_: (string * tau) list) =
failwith "Qed.Export.Why : lambda abstraction"
(* -------------------------------------------------------------------------- *)
(* --- Declarations --- *)
(* -------------------------------------------------------------------------- *)
method virtual pp_declare_adt : formatter -> ADT.t -> int -> unit
method virtual pp_declare_def : formatter -> ADT.t -> int -> tau -> unit
method virtual pp_declare_sum : formatter -> ADT.t -> int -> (Fun.t * tau list) list -> unit
method declare_type fmt adt n = function
| Tabs ->
self#pp_declare_adt fmt adt n ;
pp_print_newline fmt ()
| Tdef def ->
self#pp_declare_def fmt adt n def ;
pp_print_newline fmt ()
| Tsum cases ->
self#pp_declare_sum fmt adt n cases ;
pp_print_newline fmt ()
| Trec fts ->
begin
Format.fprintf fmt "@[<hv 0>@[<hv 2>" ;
self#pp_declare_adt fmt adt n ;
let left,right = self#op_record in
fprintf fmt " = %s" left ;
Plib.iteri
(fun index (f,t) ->
match index with
| Isingle | Ilast ->
fprintf fmt "@ @[<hov 2>%s : %a@]" (self#field f) self#pp_tau t
| Imiddle | Ifirst ->
fprintf fmt "@ @[<hov 2>%s : %a@] ;" (self#field f) self#pp_tau t
) fts ;
fprintf fmt "@] %s@]@\n" right ;
end
method pp_declare_symbol t fmt f =
let name = link_name (self#link f) in
match t with
| Cprop -> fprintf fmt "predicate %s" name
| Cterm -> fprintf fmt "function %s" name
method virtual pp_trigger : trigger printer
method virtual pp_intros : tau -> string list printer (* forall with no separator *)
method declare_prop ~kind fmt lemma xs tgs (p : term) =
self#global
begin fun () ->
fprintf fmt "@[<hv 2>%s %s:" kind lemma ;
let groups = List.fold_left
(fun groups x ->
let a = self#bind x in
let t = T.tau_of_var x in
let xs = try E.TauMap.find t groups with Not_found -> [] in
E.TauMap.add t (a::xs) groups
) E.TauMap.empty xs in
let order = E.TauMap.fold
(fun t xs order -> (t,List.sort String.compare xs)::order)
groups [] in
let tgs = full_triggers tgs in
Plib.iteri
(fun index (t,xs) ->
let do_triggers = match index with
| Ifirst | Imiddle -> false
| Isingle | Ilast -> tgs<>[] in
if do_triggers then
begin
let pp_or = Plib.pp_listcompact ~sep:"|" in
let pp_and = Plib.pp_listcompact ~sep:"," in
let pp_triggers = pp_or (pp_and self#pp_trigger) in
fprintf fmt "@ @[<hov 2>%a@]" (self#pp_intros t) xs ;
fprintf fmt "@ @[<hov 2>[%a].@]" pp_triggers tgs ;
end
else
fprintf fmt "@ @[<hov 2>%a.@]" (self#pp_intros t) xs
) order ;
fprintf fmt "@ @[<hov 2>%a@]@]@\n" self#pp_prop p
end
method declare_axiom = self#declare_prop ~kind:"axiom"
end
end
| null | https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/qed/export_whycore.ml | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It 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.
************************************************************************
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Types ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Scope ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Arrays ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Records ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Higher Order ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Higher Order ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Declarations ---
--------------------------------------------------------------------------
forall with no separator | This file is part of WP plug - in of Frama - C.
Copyright ( C ) 2007 - 2019
CEA ( Commissariat a l'energie atomique et aux energies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
--- Common Exportation Engine for Alt - Ergo and Why3 ---
open Logic
open Format
open Plib
open Engine
open Export
module Make(T : Term) =
struct
open T
module T = T
module E = Export.Make(T)
module Env = E.Env
type trigger = (T.var,Fun.t) ftrigger
type typedef = (tau,Field.t,Fun.t) ftypedef
let rec full_trigger = function
| TgAny -> false
| TgVar _ -> true
| TgGet(a,k) -> full_trigger a && full_trigger k
| TgSet(a,k,v) -> full_trigger a && full_trigger k && full_trigger v
| TgFun(_,xs) | TgProp(_,xs) -> List.for_all full_trigger xs
let rec full_triggers = function
| [] -> []
| ts :: tgs ->
match List.filter full_trigger ts with
| [] -> full_triggers tgs
| ts -> ts :: full_triggers tgs
class virtual engine =
object(self)
inherit E.engine
method t_int = "int"
method t_real = "real"
method t_bool = "bool"
method t_prop = "prop"
method pp_tvar fmt k =
if 1 <= k && k <= 26
then fprintf fmt "'%c" (char_of_int (int_of_char 'a' + k - 1))
else fprintf fmt "'_%d" k
method op_scope _ = None
method pp_array_get fmt a k =
fprintf fmt "@[<hov 2>%a[%a]@]" self#pp_atom a self#pp_flow k
method pp_array_set fmt a k v =
fprintf fmt "@[<hov 2>%a[%a@ <- %a]@]"
self#pp_atom a self#pp_atom k self#pp_flow v
method virtual op_record : string * string
method pp_get_field fmt r f =
fprintf fmt "%a.%s" self#pp_atom r (self#field f)
method pp_def_fields fmt fvs =
let base,fvs = match T.record_with fvs with
| None -> None,fvs | Some(r,fvs) -> Some r,fvs in
begin
let (left,right) = self#op_record in
fprintf fmt "@[<hov 2>%s" left ;
Plib.iteri
(fun i (f,v) ->
( match i , base with
| (Isingle | Ifirst) , Some r ->
fprintf fmt "@ %a with" self#pp_flow r
| _ -> () ) ;
( match i with
| Ifirst | Imiddle ->
fprintf fmt "@ @[<hov 2>%s = %a ;@]"
(self#field f) self#pp_flow v
| Isingle | Ilast ->
fprintf fmt "@ @[<hov 2>%s = %a@]"
(self#field f) self#pp_flow v )
) fvs ;
fprintf fmt "@ %s@]" right ;
end
method pp_apply (_:cmode) (_:term) (_:formatter) (_:term list) =
failwith "Qed.Export.Why: higher-order application"
method pp_param fmt ((x,t) : string * tau) =
fprintf fmt "%a:%a" self#pp_var x self#pp_tau t
method pp_lambda (_:formatter) (_: (string * tau) list) =
failwith "Qed.Export.Why : lambda abstraction"
method virtual pp_declare_adt : formatter -> ADT.t -> int -> unit
method virtual pp_declare_def : formatter -> ADT.t -> int -> tau -> unit
method virtual pp_declare_sum : formatter -> ADT.t -> int -> (Fun.t * tau list) list -> unit
method declare_type fmt adt n = function
| Tabs ->
self#pp_declare_adt fmt adt n ;
pp_print_newline fmt ()
| Tdef def ->
self#pp_declare_def fmt adt n def ;
pp_print_newline fmt ()
| Tsum cases ->
self#pp_declare_sum fmt adt n cases ;
pp_print_newline fmt ()
| Trec fts ->
begin
Format.fprintf fmt "@[<hv 0>@[<hv 2>" ;
self#pp_declare_adt fmt adt n ;
let left,right = self#op_record in
fprintf fmt " = %s" left ;
Plib.iteri
(fun index (f,t) ->
match index with
| Isingle | Ilast ->
fprintf fmt "@ @[<hov 2>%s : %a@]" (self#field f) self#pp_tau t
| Imiddle | Ifirst ->
fprintf fmt "@ @[<hov 2>%s : %a@] ;" (self#field f) self#pp_tau t
) fts ;
fprintf fmt "@] %s@]@\n" right ;
end
method pp_declare_symbol t fmt f =
let name = link_name (self#link f) in
match t with
| Cprop -> fprintf fmt "predicate %s" name
| Cterm -> fprintf fmt "function %s" name
method virtual pp_trigger : trigger printer
method declare_prop ~kind fmt lemma xs tgs (p : term) =
self#global
begin fun () ->
fprintf fmt "@[<hv 2>%s %s:" kind lemma ;
let groups = List.fold_left
(fun groups x ->
let a = self#bind x in
let t = T.tau_of_var x in
let xs = try E.TauMap.find t groups with Not_found -> [] in
E.TauMap.add t (a::xs) groups
) E.TauMap.empty xs in
let order = E.TauMap.fold
(fun t xs order -> (t,List.sort String.compare xs)::order)
groups [] in
let tgs = full_triggers tgs in
Plib.iteri
(fun index (t,xs) ->
let do_triggers = match index with
| Ifirst | Imiddle -> false
| Isingle | Ilast -> tgs<>[] in
if do_triggers then
begin
let pp_or = Plib.pp_listcompact ~sep:"|" in
let pp_and = Plib.pp_listcompact ~sep:"," in
let pp_triggers = pp_or (pp_and self#pp_trigger) in
fprintf fmt "@ @[<hov 2>%a@]" (self#pp_intros t) xs ;
fprintf fmt "@ @[<hov 2>[%a].@]" pp_triggers tgs ;
end
else
fprintf fmt "@ @[<hov 2>%a.@]" (self#pp_intros t) xs
) order ;
fprintf fmt "@ @[<hov 2>%a@]@]@\n" self#pp_prop p
end
method declare_axiom = self#declare_prop ~kind:"axiom"
end
end
|
cd7f24568530413cd6830fb09492bbccd7b6f4753cdf9408b9f5386360024506 | rtoy/cmucl | xref.lisp | xref.lisp -- a cross - reference facility for CMUCL
;;;
Author : < >
;;;
(ext:file-comment
"$Header: src/compiler/xref.lisp $")
;;
This code was written as part of the CMUCL project and has been
;; placed in the public domain.
;;
;;
;; The cross-referencing facility provides the ability to discover
;; information such as which functions call which other functions and
;; in which program contexts a given global variables may be used. The
;; cross-referencer maintains a database of cross-reference
;; information which can be queried by the user to provide answers to
;; questions like:
;;
;; - the program contexts where a given function may be called,
;; either directly or indirectly (via its function-object).
;;
;; - the program contexts where a global variable (ie a dynamic
;; variable or a constant variable -- something declared with
;; DEFVAR or DEFPARAMETER or DEFCONSTANT) may be read, or bound, or
;; modified.
;;
More details are available in " Cross - Referencing Facility " chapter
of the CMUCL User 's Manual .
;;
;;
;; Missing functionality:
;;
- maybe add macros EXT : WITH - XREF .
;;
- in ( defun foo ( x ) ( flet ( ( bar ( y ) ( + x y ) ) ) ( bar 3 ) ) ) , we want to see
FOO calling (: internal BAR FOO )
;;
;; The cross-reference facility is implemented by walking the IR1
representation that is generated by CMUCL when compiling ( for both
;; native and byte-compiled code, and irrespective of whether you're
;; compiling from a file, from a stream, or interactively from the
;; listener).
(in-package :xref)
(intl:textdomain "cmucl")
(export '(init-xref-database
register-xref
who-calls
who-references
who-binds
who-sets
who-macroexpands
who-subclasses
who-superclasses
who-specializes
make-xref-context
xref-context-name
xref-context-file
xref-context-source-path
invalidate-xrefs-for-namestring
find-xrefs-for-pathname))
(defstruct (xref-context
(:print-function %print-xref-context)
(:make-load-form-fun :just-dump-it-normally))
name
(file *compile-file-truename*)
(source-path nil))
(defun %print-xref-context (s stream d)
(declare (ignore d))
(cond (*print-readably*
(format stream "#S(xref::xref-context :name '~S ~_ :file ~S ~_ :source-path '~A)"
(xref-context-name s)
(xref-context-file s)
(xref-context-source-path s)))
(t
(format stream "#<xref-context ~S~@[ in ~S~]>"
(xref-context-name s)
(xref-context-file s)))))
;; program contexts where a globally-defined function may be called at runtime
(defvar *who-calls* (make-hash-table :test #'eq))
(defvar *who-is-called* (make-hash-table :test #'eq))
;; program contexts where a global variable may be referenced
(defvar *who-references* (make-hash-table :test #'eq))
;; program contexts where a global variable may be bound
(defvar *who-binds* (make-hash-table :test #'eq))
;; program contexts where a global variable may be set
(defvar *who-sets* (make-hash-table :test #'eq))
;; program contexts where a global variable may be set
(defvar *who-macroexpands* (make-hash-table :test #'eq))
;; you can print these conveniently with code like
;; (maphash (lambda (k v) (format t "~S <-~{ ~S~^,~}~%" k v)) xref::*who-sets*)
;; or
;; (maphash (lambda (k v) (format t "~S <-~% ~@<~@;~S~^~%~:>~%" k v)) xref::*who-calls*)
(defun register-xref (type target context)
(declare (type xref-context context))
(let ((database (ecase type
(:calls *who-calls*)
(:called *who-is-called*)
(:references *who-references*)
(:binds *who-binds*)
(:sets *who-sets*)
(:macroexpands *who-macroexpands*))))
(if (gethash target database)
(pushnew context (gethash target database) :test 'equalp)
(setf (gethash target database) (list context)))
context))
INIT - XREF - DATABASE -- interface
;;
(defun init-xref-database ()
"Reinitialize the cross-reference database."
(setf *who-calls* (make-hash-table :test #'eq))
(setf *who-is-called* (make-hash-table :test #'eq))
(setf *who-references* (make-hash-table :test #'eq))
(setf *who-binds* (make-hash-table :test #'eq))
(setf *who-sets* (make-hash-table :test #'eq))
(setf *who-macroexpands* (make-hash-table :test #'eq))
(values))
WHO - CALLS -- interface
;;
(defun who-calls (function-name &key (reverse nil))
"Return a list of those program contexts where a globally-defined
function may be called at runtime."
(if reverse
(gethash function-name *who-is-called*)
(gethash function-name *who-calls*)))
;; WHO-REFERENCES -- interface
;;
(defun who-references (global-variable)
"Return a list of those program contexts where GLOBAL-VARIABLE
may be referenced at runtime."
(declare (type symbol global-variable))
(gethash global-variable *who-references*))
WHO - BINDS -- interface
;;
(defun who-binds (global-variable)
"Return a list of those program contexts where GLOBAL-VARIABLE may
be bound at runtime."
(declare (type symbol global-variable))
(gethash global-variable *who-binds*))
;; WHO-SETS -- interface
;;
(defun who-sets (global-variable)
"Return a list of those program contexts where GLOBAL-VARIABLE may
be set at runtime."
(declare (type symbol global-variable))
(gethash global-variable *who-sets*))
(defun who-macroexpands (macro)
(declare (type symbol macro))
(gethash macro *who-macroexpands*))
introspection functions from the CLOS metaobject protocol
;; WHO-SUBCLASSES -- interface
;;
(defun who-subclasses (class)
(pcl::class-direct-subclasses class))
;; WHO-SUPERCLASSES -- interface
;;
(defun who-superclasses (class)
(pcl::class-direct-superclasses class))
WHO - SPECIALIZES -- interface
;;
;; generic functions defined for this class
(defun who-specializes (class)
(pcl::specializer-direct-methods class))
;; Go through all the databases and remove entries from that that
;; reference the given Namestring.
(defun invalidate-xrefs-for-namestring (namestring)
(labels ((matching-context (ctx)
(equal namestring (if (pathnamep (xref-context-file ctx))
(namestring (xref-context-file ctx))
(xref-context-file ctx))))
(invalidate-for-database (db)
(maphash (lambda (target contexts)
(let ((valid-contexts (remove-if #'matching-context contexts)))
(if (null valid-contexts)
(remhash target db)
(setf (gethash target db) valid-contexts))))
db)))
(dolist (db (list *who-calls* *who-is-called* *who-references* *who-binds*
*who-sets* *who-macroexpands*))
(invalidate-for-database db))))
Look in Db for entries that reference the supplied and
;; return a list of all the matches. Each element of the list is a
;; list of the target followed by the entries.
(defun find-xrefs-for-pathname (db pathname)
(let ((entries '()))
(maphash #'(lambda (target contexts)
(let ((matches '()))
(dolist (ctx contexts)
(when (equal pathname (xref-context-file ctx))
(push ctx matches)))
(push (list target matches) entries)))
(ecase db
(:calls *who-calls*)
(:called *who-is-called*)
(:references *who-references*)
(:binds *who-binds*)
(:sets *who-sets*)
(:macroexpands *who-macroexpands*)))
entries))
(in-package :compiler)
(defun lambda-contains-calls-p (clambda)
(declare (type clambda clambda))
(some #'lambda-p (lambda-dfo-dependencies clambda)))
(defun prettiest-caller-name (lambda-node toplevel-name)
(cond
((not lambda-node)
(list :anonymous toplevel-name))
;; LET and FLET bindings introduce new unnamed LAMBDA nodes.
;; If the home slot contains a lambda with a nice name, we use
;; that; otherwise fall back on the toplevel-name.
((or (not (eq (lambda-home lambda-node) lambda-node))
(lambda-contains-calls-p lambda-node))
(let ((home (lambda-name (lambda-home lambda-node)))
(here (lambda-name lambda-node)))
(cond ((and home here)
(list :internal home here))
((symbolp here) here)
((symbolp home) home)
(t
(or here home toplevel-name)))))
((and (listp (lambda-name lambda-node))
(eq :macro (first (lambda-name lambda-node))))
(lambda-name lambda-node))
;; a reference from a macro is named (:macro name)
#+nil
((eql 0 (search "defmacro" toplevel-name :test 'char-equal))
(list :macro (subseq toplevel-name 9)))
probably " Top - Level Form "
((stringp (lambda-name lambda-node))
(lambda-name lambda-node))
probably ( setf foo )
((listp (lambda-name lambda-node))
(lambda-name lambda-node))
(t
;; distinguish between nested functions (FLET/LABELS) and
;; global functions by checking whether the node has a HOME
;; slot that is different from itself. Furthermore, a LABELS
node at the first level inside a lambda may have a
;; self-referential home slot, but still be internal.
(cond ((not (eq (lambda-home lambda-node) lambda-node))
(list :internal
(lambda-name (lambda-home lambda-node))
(lambda-name lambda-node)))
((lambda-contains-calls-p lambda-node)
(list :internal/calls
(lambda-name (lambda-home lambda-node))
(lambda-name lambda-node)))
(t (lambda-name lambda-node))))))
;; RECORD-NODE-XREFS -- internal
;;
TOPLEVEL - NAME is an indication of the name of the COMPONENT that
contains this node , or NIL if it was really " Top - Level Form " .
(defun record-node-xrefs (node toplevel-name)
(declare (type node node))
(let ((context (xref:make-xref-context)))
(when *compile-file-truename*
(setf (xref:xref-context-source-path context)
(reverse
(source-path-original-source
(node-source-path node)))))
(typecase node
(ref
(let* ((leaf (ref-leaf node))
(lexenv (ref-lexenv node))
(lambda (lexenv-lambda lexenv))
(home (node-home-lambda node))
(caller (or (and home (lambda-name home))
(prettiest-caller-name lambda toplevel-name))))
(setf (xref:xref-context-name context) caller)
(typecase leaf
a reference to a LEAF of type GLOBAL - VAR
(global-var
(let ((called (global-var-name leaf)))
a reference to # ' C::%SPECIAL - BIND means that we are
;; binding a special variable. The information on which
;; variable is being bound, and within which function, is
;; available in the ref's LEXENV object.
(cond ((eq called 'c::%special-bind)
(setf (xref:xref-context-name context) (caar (lexenv-blocks lexenv)))
(xref:register-xref :binds (caar (lexenv-variables lexenv)) context))
;; we're not interested in lexical environments
;; that have no name; they are mostly due to code
;; inserted by the compiler (eg calls to %VERIFY-ARGUMENT-COUNT)
((not caller)
:no-caller)
;; we're not interested in lexical environments
named " Top - Level Form " .
((and (stringp caller)
(string= "Top-Level Form" caller))
:top-level-form)
((not (eq 'original-source-start (first (node-source-path node))))
#+nil
(format *debug-io* "~&Ignoring compiler-generated call with source-path ~A~%"
(node-source-path node))
:compiler-generated)
((not called)
:no-called)
((eq :global-function (global-var-kind leaf))
(xref:register-xref :calls called context)
(xref:register-xref :called caller context))
((eq :special (global-var-kind leaf))
(xref:register-xref :references called context)))))
a reference to a LEAF of type CONSTANT
(constant
(let ((called (constant-name leaf)))
(and called
(not (eq called t)) ; ignore references to trivial variables
caller
(not (and (stringp caller) (string= "Top-Level Form" caller)))
(xref:register-xref :references called context)))))))
;; a variable is being set
(cset
(let* ((variable (set-var node))
(lexenv (set-lexenv node)))
(and (global-var-p variable)
(eq :special (global-var-kind variable))
(let* ((lblock (first (lexenv-blocks lexenv)))
(user (or (and lblock (car lblock)) toplevel-name))
(used (global-var-name variable)))
(setf (xref:xref-context-name context) user)
(and user used (xref:register-xref :sets used context))))))
nodes of type BIND are used to bind symbols to LAMBDA objects
;; (including for macros), but apparently not for bindings of
;; variables.
(bind
t))))
;; RECORD-COMPONENT-XREFS -- internal
;;
(defun record-component-xrefs (component)
(declare (type component component))
(do ((block (block-next (component-head component)) (block-next block)))
((null (block-next block)))
(let ((fun (block-home-lambda block))
(name (component-name component))
(this-cont (block-start block))
(last (block-last block)))
(unless (eq :deleted (functional-kind fun))
(loop
(let ((node (continuation-next this-cont)))
(record-node-xrefs node name)
(let ((cont (node-cont node)))
(when (eq node last) (return))
(setq this-cont cont))))))))
EOF
| null | https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/compiler/xref.lisp | lisp |
placed in the public domain.
The cross-referencing facility provides the ability to discover
information such as which functions call which other functions and
in which program contexts a given global variables may be used. The
cross-referencer maintains a database of cross-reference
information which can be queried by the user to provide answers to
questions like:
- the program contexts where a given function may be called,
either directly or indirectly (via its function-object).
- the program contexts where a global variable (ie a dynamic
variable or a constant variable -- something declared with
DEFVAR or DEFPARAMETER or DEFCONSTANT) may be read, or bound, or
modified.
Missing functionality:
The cross-reference facility is implemented by walking the IR1
native and byte-compiled code, and irrespective of whether you're
compiling from a file, from a stream, or interactively from the
listener).
program contexts where a globally-defined function may be called at runtime
program contexts where a global variable may be referenced
program contexts where a global variable may be bound
program contexts where a global variable may be set
program contexts where a global variable may be set
you can print these conveniently with code like
(maphash (lambda (k v) (format t "~S <-~{ ~S~^,~}~%" k v)) xref::*who-sets*)
or
(maphash (lambda (k v) (format t "~S <-~% ~@<~@;~S~^~%~:>~%" k v)) xref::*who-calls*)
WHO-REFERENCES -- interface
WHO-SETS -- interface
WHO-SUBCLASSES -- interface
WHO-SUPERCLASSES -- interface
generic functions defined for this class
Go through all the databases and remove entries from that that
reference the given Namestring.
return a list of all the matches. Each element of the list is a
list of the target followed by the entries.
LET and FLET bindings introduce new unnamed LAMBDA nodes.
If the home slot contains a lambda with a nice name, we use
that; otherwise fall back on the toplevel-name.
a reference from a macro is named (:macro name)
distinguish between nested functions (FLET/LABELS) and
global functions by checking whether the node has a HOME
slot that is different from itself. Furthermore, a LABELS
self-referential home slot, but still be internal.
RECORD-NODE-XREFS -- internal
binding a special variable. The information on which
variable is being bound, and within which function, is
available in the ref's LEXENV object.
we're not interested in lexical environments
that have no name; they are mostly due to code
inserted by the compiler (eg calls to %VERIFY-ARGUMENT-COUNT)
we're not interested in lexical environments
ignore references to trivial variables
a variable is being set
(including for macros), but apparently not for bindings of
variables.
RECORD-COMPONENT-XREFS -- internal
| xref.lisp -- a cross - reference facility for CMUCL
Author : < >
(ext:file-comment
"$Header: src/compiler/xref.lisp $")
This code was written as part of the CMUCL project and has been
More details are available in " Cross - Referencing Facility " chapter
of the CMUCL User 's Manual .
- maybe add macros EXT : WITH - XREF .
- in ( defun foo ( x ) ( flet ( ( bar ( y ) ( + x y ) ) ) ( bar 3 ) ) ) , we want to see
FOO calling (: internal BAR FOO )
representation that is generated by CMUCL when compiling ( for both
(in-package :xref)
(intl:textdomain "cmucl")
(export '(init-xref-database
register-xref
who-calls
who-references
who-binds
who-sets
who-macroexpands
who-subclasses
who-superclasses
who-specializes
make-xref-context
xref-context-name
xref-context-file
xref-context-source-path
invalidate-xrefs-for-namestring
find-xrefs-for-pathname))
(defstruct (xref-context
(:print-function %print-xref-context)
(:make-load-form-fun :just-dump-it-normally))
name
(file *compile-file-truename*)
(source-path nil))
(defun %print-xref-context (s stream d)
(declare (ignore d))
(cond (*print-readably*
(format stream "#S(xref::xref-context :name '~S ~_ :file ~S ~_ :source-path '~A)"
(xref-context-name s)
(xref-context-file s)
(xref-context-source-path s)))
(t
(format stream "#<xref-context ~S~@[ in ~S~]>"
(xref-context-name s)
(xref-context-file s)))))
(defvar *who-calls* (make-hash-table :test #'eq))
(defvar *who-is-called* (make-hash-table :test #'eq))
(defvar *who-references* (make-hash-table :test #'eq))
(defvar *who-binds* (make-hash-table :test #'eq))
(defvar *who-sets* (make-hash-table :test #'eq))
(defvar *who-macroexpands* (make-hash-table :test #'eq))
(defun register-xref (type target context)
(declare (type xref-context context))
(let ((database (ecase type
(:calls *who-calls*)
(:called *who-is-called*)
(:references *who-references*)
(:binds *who-binds*)
(:sets *who-sets*)
(:macroexpands *who-macroexpands*))))
(if (gethash target database)
(pushnew context (gethash target database) :test 'equalp)
(setf (gethash target database) (list context)))
context))
INIT - XREF - DATABASE -- interface
(defun init-xref-database ()
"Reinitialize the cross-reference database."
(setf *who-calls* (make-hash-table :test #'eq))
(setf *who-is-called* (make-hash-table :test #'eq))
(setf *who-references* (make-hash-table :test #'eq))
(setf *who-binds* (make-hash-table :test #'eq))
(setf *who-sets* (make-hash-table :test #'eq))
(setf *who-macroexpands* (make-hash-table :test #'eq))
(values))
WHO - CALLS -- interface
(defun who-calls (function-name &key (reverse nil))
"Return a list of those program contexts where a globally-defined
function may be called at runtime."
(if reverse
(gethash function-name *who-is-called*)
(gethash function-name *who-calls*)))
(defun who-references (global-variable)
"Return a list of those program contexts where GLOBAL-VARIABLE
may be referenced at runtime."
(declare (type symbol global-variable))
(gethash global-variable *who-references*))
WHO - BINDS -- interface
(defun who-binds (global-variable)
"Return a list of those program contexts where GLOBAL-VARIABLE may
be bound at runtime."
(declare (type symbol global-variable))
(gethash global-variable *who-binds*))
(defun who-sets (global-variable)
"Return a list of those program contexts where GLOBAL-VARIABLE may
be set at runtime."
(declare (type symbol global-variable))
(gethash global-variable *who-sets*))
(defun who-macroexpands (macro)
(declare (type symbol macro))
(gethash macro *who-macroexpands*))
introspection functions from the CLOS metaobject protocol
(defun who-subclasses (class)
(pcl::class-direct-subclasses class))
(defun who-superclasses (class)
(pcl::class-direct-superclasses class))
WHO - SPECIALIZES -- interface
(defun who-specializes (class)
(pcl::specializer-direct-methods class))
(defun invalidate-xrefs-for-namestring (namestring)
(labels ((matching-context (ctx)
(equal namestring (if (pathnamep (xref-context-file ctx))
(namestring (xref-context-file ctx))
(xref-context-file ctx))))
(invalidate-for-database (db)
(maphash (lambda (target contexts)
(let ((valid-contexts (remove-if #'matching-context contexts)))
(if (null valid-contexts)
(remhash target db)
(setf (gethash target db) valid-contexts))))
db)))
(dolist (db (list *who-calls* *who-is-called* *who-references* *who-binds*
*who-sets* *who-macroexpands*))
(invalidate-for-database db))))
Look in Db for entries that reference the supplied and
(defun find-xrefs-for-pathname (db pathname)
(let ((entries '()))
(maphash #'(lambda (target contexts)
(let ((matches '()))
(dolist (ctx contexts)
(when (equal pathname (xref-context-file ctx))
(push ctx matches)))
(push (list target matches) entries)))
(ecase db
(:calls *who-calls*)
(:called *who-is-called*)
(:references *who-references*)
(:binds *who-binds*)
(:sets *who-sets*)
(:macroexpands *who-macroexpands*)))
entries))
(in-package :compiler)
(defun lambda-contains-calls-p (clambda)
(declare (type clambda clambda))
(some #'lambda-p (lambda-dfo-dependencies clambda)))
(defun prettiest-caller-name (lambda-node toplevel-name)
(cond
((not lambda-node)
(list :anonymous toplevel-name))
((or (not (eq (lambda-home lambda-node) lambda-node))
(lambda-contains-calls-p lambda-node))
(let ((home (lambda-name (lambda-home lambda-node)))
(here (lambda-name lambda-node)))
(cond ((and home here)
(list :internal home here))
((symbolp here) here)
((symbolp home) home)
(t
(or here home toplevel-name)))))
((and (listp (lambda-name lambda-node))
(eq :macro (first (lambda-name lambda-node))))
(lambda-name lambda-node))
#+nil
((eql 0 (search "defmacro" toplevel-name :test 'char-equal))
(list :macro (subseq toplevel-name 9)))
probably " Top - Level Form "
((stringp (lambda-name lambda-node))
(lambda-name lambda-node))
probably ( setf foo )
((listp (lambda-name lambda-node))
(lambda-name lambda-node))
(t
node at the first level inside a lambda may have a
(cond ((not (eq (lambda-home lambda-node) lambda-node))
(list :internal
(lambda-name (lambda-home lambda-node))
(lambda-name lambda-node)))
((lambda-contains-calls-p lambda-node)
(list :internal/calls
(lambda-name (lambda-home lambda-node))
(lambda-name lambda-node)))
(t (lambda-name lambda-node))))))
TOPLEVEL - NAME is an indication of the name of the COMPONENT that
contains this node , or NIL if it was really " Top - Level Form " .
(defun record-node-xrefs (node toplevel-name)
(declare (type node node))
(let ((context (xref:make-xref-context)))
(when *compile-file-truename*
(setf (xref:xref-context-source-path context)
(reverse
(source-path-original-source
(node-source-path node)))))
(typecase node
(ref
(let* ((leaf (ref-leaf node))
(lexenv (ref-lexenv node))
(lambda (lexenv-lambda lexenv))
(home (node-home-lambda node))
(caller (or (and home (lambda-name home))
(prettiest-caller-name lambda toplevel-name))))
(setf (xref:xref-context-name context) caller)
(typecase leaf
a reference to a LEAF of type GLOBAL - VAR
(global-var
(let ((called (global-var-name leaf)))
a reference to # ' C::%SPECIAL - BIND means that we are
(cond ((eq called 'c::%special-bind)
(setf (xref:xref-context-name context) (caar (lexenv-blocks lexenv)))
(xref:register-xref :binds (caar (lexenv-variables lexenv)) context))
((not caller)
:no-caller)
named " Top - Level Form " .
((and (stringp caller)
(string= "Top-Level Form" caller))
:top-level-form)
((not (eq 'original-source-start (first (node-source-path node))))
#+nil
(format *debug-io* "~&Ignoring compiler-generated call with source-path ~A~%"
(node-source-path node))
:compiler-generated)
((not called)
:no-called)
((eq :global-function (global-var-kind leaf))
(xref:register-xref :calls called context)
(xref:register-xref :called caller context))
((eq :special (global-var-kind leaf))
(xref:register-xref :references called context)))))
a reference to a LEAF of type CONSTANT
(constant
(let ((called (constant-name leaf)))
(and called
caller
(not (and (stringp caller) (string= "Top-Level Form" caller)))
(xref:register-xref :references called context)))))))
(cset
(let* ((variable (set-var node))
(lexenv (set-lexenv node)))
(and (global-var-p variable)
(eq :special (global-var-kind variable))
(let* ((lblock (first (lexenv-blocks lexenv)))
(user (or (and lblock (car lblock)) toplevel-name))
(used (global-var-name variable)))
(setf (xref:xref-context-name context) user)
(and user used (xref:register-xref :sets used context))))))
nodes of type BIND are used to bind symbols to LAMBDA objects
(bind
t))))
(defun record-component-xrefs (component)
(declare (type component component))
(do ((block (block-next (component-head component)) (block-next block)))
((null (block-next block)))
(let ((fun (block-home-lambda block))
(name (component-name component))
(this-cont (block-start block))
(last (block-last block)))
(unless (eq :deleted (functional-kind fun))
(loop
(let ((node (continuation-next this-cont)))
(record-node-xrefs node name)
(let ((cont (node-cont node)))
(when (eq node last) (return))
(setq this-cont cont))))))))
EOF
|
362b9169913c6e777548a0ba8d5cd51b889f95cacd174aa19428ab70d9f5d135 | ManasJayanth/reason-on-multicore | ast_mapper_class.ml | (* This file is part of the ppx_tools package. It is released *)
under the terms of the MIT license ( see LICENSE file ) .
Copyright 2013 and LexiFi
(** Class-based customizable mapper *)
open Parsetree
open Asttypes
open Ast_helper
let map_fst f (x, y) = (f x, y)
let map_snd f (x, y) = (x, f y)
let map_tuple f1 f2 (x, y) = (f1 x, f2 y)
let map_tuple3 f1 f2 f3 (x, y, z) = (f1 x, f2 y, f3 z)
let map_opt f = function None -> None | Some x -> Some (f x)
let map_loc sub {loc; txt} = {loc = sub # location loc; txt}
module T = struct
(* Type expressions for the core language *)
let row_field_desc sub = function
| Rtag (l, b, tl) -> Rtag (l, b, List.map (sub # typ) tl)
| Rinherit t -> Rinherit (sub # typ t)
let row_field sub {prf_desc = desc; prf_loc = loc; prf_attributes = attrs} =
let desc = row_field_desc sub desc in
let loc = sub # location loc in
let attrs = sub # attributes attrs in
{prf_desc = desc; prf_loc = loc; prf_attributes = attrs}
let object_field_desc sub = function
| Otag (s, t) -> Otag (s, sub # typ t)
| Oinherit t -> Oinherit (sub # typ t)
let object_field sub {pof_desc = desc; pof_loc = loc; pof_attributes = attrs} =
let desc = object_field_desc sub desc in
let loc = sub # location loc in
let attrs = sub # attributes attrs in
{pof_desc = desc; pof_loc = loc; pof_attributes = attrs}
let map sub {ptyp_desc = desc; ptyp_loc = loc; ptyp_loc_stack = _; ptyp_attributes = attrs} =
let open Typ in
let loc = sub # location loc in
let attrs = sub # attributes attrs in
match desc with
| Ptyp_any -> any ~loc ~attrs ()
| Ptyp_var s -> var ~loc ~attrs s
| Ptyp_arrow (lab, t1, t2) ->
arrow ~loc ~attrs lab (sub # typ t1) (sub # typ t2)
| Ptyp_tuple tyl -> tuple ~loc ~attrs (List.map (sub # typ) tyl)
| Ptyp_constr (lid, tl) ->
constr ~loc ~attrs (map_loc sub lid) (List.map (sub # typ) tl)
| Ptyp_object (l, o) ->
object_ ~loc ~attrs (List.map (object_field sub) l) o
| Ptyp_class (lid, tl) ->
class_ ~loc ~attrs (map_loc sub lid) (List.map (sub # typ) tl)
| Ptyp_alias (t, s) -> alias ~loc ~attrs (sub # typ t) s
| Ptyp_variant (rl, b, ll) ->
variant ~loc ~attrs (List.map (row_field sub) rl) b ll
| Ptyp_poly (sl, t) -> poly ~loc ~attrs sl (sub # typ t)
| Ptyp_package (lid, l) ->
package ~loc ~attrs (map_loc sub lid)
(List.map (map_tuple (map_loc sub) (sub # typ)) l)
| Ptyp_extension x -> extension ~loc ~attrs (sub # extension x)
let map_type_declaration sub
{ptype_name; ptype_params; ptype_cstrs;
ptype_kind;
ptype_private;
ptype_manifest;
ptype_attributes;
ptype_loc} =
Type.mk (map_loc sub ptype_name)
~params:(List.map (map_fst (sub # typ)) ptype_params)
~priv:ptype_private
~cstrs:(List.map (map_tuple3 (sub # typ) (sub # typ) (sub # location))
ptype_cstrs)
~kind:(sub # type_kind ptype_kind)
?manifest:(map_opt (sub # typ) ptype_manifest)
~loc:(sub # location ptype_loc)
~attrs:(sub # attributes ptype_attributes)
let map_type_kind sub = function
| Ptype_abstract -> Ptype_abstract
| Ptype_variant l ->
Ptype_variant (List.map (sub # constructor_declaration) l)
| Ptype_record l -> Ptype_record (List.map (sub # label_declaration) l)
| Ptype_open -> Ptype_open
let map_type_extension sub
{ptyext_path; ptyext_params;
ptyext_constructors;
ptyext_private;
ptyext_loc;
ptyext_attributes} =
Te.mk
(map_loc sub ptyext_path)
(List.map (sub # extension_constructor) ptyext_constructors)
~params:(List.map (map_fst (sub # typ)) ptyext_params)
~priv:ptyext_private
~loc:(sub # location ptyext_loc)
~attrs:(sub # attributes ptyext_attributes)
let map_extension_constructor_kind sub = function
Pext_decl(ctl, cto) ->
Pext_decl(sub # constructor_arguments ctl, map_opt (sub # typ) cto)
| Pext_rebind li ->
Pext_rebind (map_loc sub li)
let map_extension_constructor sub
{pext_name;
pext_kind;
pext_loc;
pext_attributes} =
Te.constructor
(map_loc sub pext_name)
(map_extension_constructor_kind sub pext_kind)
~loc:(sub # location pext_loc)
~attrs:(sub # attributes pext_attributes)
let map_type_exception sub {ptyexn_constructor; ptyexn_loc; ptyexn_attributes} =
Te.mk_exception
(map_extension_constructor sub ptyexn_constructor)
~loc:(sub # location ptyexn_loc)
~attrs:(sub # attributes ptyexn_attributes)
end
module CT = struct
(* Type expressions for the class language *)
let map sub {pcty_loc = loc; pcty_desc = desc; pcty_attributes = attrs} =
let open Cty in
let loc = sub # location loc in
match desc with
| Pcty_constr (lid, tys) ->
constr ~loc ~attrs (map_loc sub lid) (List.map (sub # typ) tys)
| Pcty_signature x -> signature ~loc ~attrs (sub # class_signature x)
| Pcty_arrow (lab, t, ct) ->
arrow ~loc ~attrs lab (sub # typ t) (sub # class_type ct)
| Pcty_extension x -> extension ~loc ~attrs (sub # extension x)
| Pcty_open (od, ct) ->
open_ ~loc ~attrs (sub # open_description od) (sub # class_type ct)
let map_field sub {pctf_desc = desc; pctf_loc = loc; pctf_attributes = attrs}
=
let open Ctf in
let loc = sub # location loc in
match desc with
| Pctf_inherit ct -> inherit_ ~loc ~attrs (sub # class_type ct)
| Pctf_val (s, m, v, t) -> val_ ~loc ~attrs s m v (sub # typ t)
| Pctf_method (s, p, v, t) -> method_ ~loc ~attrs s p v (sub # typ t)
| Pctf_constraint (t1, t2) ->
constraint_ ~loc ~attrs (sub # typ t1) (sub # typ t2)
| Pctf_attribute x -> attribute ~loc (sub # attribute x)
| Pctf_extension x -> extension ~loc ~attrs (sub # extension x)
let map_signature sub {pcsig_self; pcsig_fields} =
Csig.mk
(sub # typ pcsig_self)
(List.map (sub # class_type_field) pcsig_fields)
end
#if OCAML_VERSION >= (4, 10, 0)
let map_functor_param sub = function
| Unit -> Unit
| Named (s, mt) -> Named (map_loc sub s, sub # module_type mt)
#endif
module MT = struct
(* Type expressions for the module language *)
let map sub {pmty_desc = desc; pmty_loc = loc; pmty_attributes = attrs} =
let open Mty in
let loc = sub # location loc in
let attrs = sub # attributes attrs in
match desc with
| Pmty_ident s -> ident ~loc ~attrs (map_loc sub s)
| Pmty_alias s -> alias ~loc ~attrs (map_loc sub s)
| Pmty_signature sg -> signature ~loc ~attrs (sub # signature sg)
#if OCAML_VERSION >= (4, 10, 0)
| Pmty_functor (param, mt) ->
functor_ ~loc ~attrs
(map_functor_param sub param)
(sub # module_type mt)
#else
| Pmty_functor (s, mt1, mt2) ->
functor_ ~loc ~attrs (map_loc sub s)
(map_opt (sub # module_type) mt1)
(sub # module_type mt2)
#endif
| Pmty_with (mt, l) ->
with_ ~loc ~attrs (sub # module_type mt)
(List.map (sub # with_constraint) l)
| Pmty_typeof me -> typeof_ ~loc ~attrs (sub # module_expr me)
| Pmty_extension x -> extension ~loc ~attrs (sub # extension x)
let map_with_constraint sub = function
| Pwith_type (lid, d) ->
Pwith_type (map_loc sub lid, sub # type_declaration d)
| Pwith_module (lid, lid2) ->
Pwith_module (map_loc sub lid, map_loc sub lid2)
| Pwith_typesubst (lid, d) ->
Pwith_typesubst (map_loc sub lid, sub # type_declaration d)
| Pwith_modsubst (lid, lid2) ->
Pwith_modsubst (map_loc sub lid, map_loc sub lid2)
let map_signature_item sub {psig_desc = desc; psig_loc = loc} =
let open Sig in
let loc = sub # location loc in
match desc with
| Psig_value vd -> value ~loc (sub # value_description vd)
| Psig_type (rf, l) -> type_ ~loc rf (List.map (sub # type_declaration) l)
| Psig_typesubst l -> type_subst ~loc (List.map (sub # type_declaration) l)
| Psig_typext te -> type_extension ~loc (sub # type_extension te)
| Psig_exception texn -> exception_ ~loc (sub # type_exception texn)
| Psig_module x -> module_ ~loc (sub # module_declaration x)
| Psig_modsubst ms -> mod_subst ~loc (sub # module_substitution ms)
| Psig_recmodule l ->
rec_module ~loc (List.map (sub # module_declaration) l)
| Psig_modtype x -> modtype ~loc (sub # module_type_declaration x)
| Psig_open od -> open_ ~loc (sub # open_description od)
| Psig_include x -> include_ ~loc (sub # include_description x)
| Psig_class l -> class_ ~loc (List.map (sub # class_description) l)
| Psig_class_type l ->
class_type ~loc (List.map (sub # class_type_declaration) l)
| Psig_extension (x, attrs) ->
extension ~loc (sub # extension x) ~attrs:(sub # attributes attrs)
| Psig_attribute x -> attribute ~loc (sub # attribute x)
end
module M = struct
(* Value expressions for the module language *)
let map sub {pmod_loc = loc; pmod_desc = desc; pmod_attributes = attrs} =
let open Mod in
let loc = sub # location loc in
let attrs = sub # attributes attrs in
match desc with
| Pmod_ident x -> ident ~loc ~attrs (map_loc sub x)
| Pmod_structure str -> structure ~loc ~attrs (sub # structure str)
#if OCAML_VERSION >= (4, 10, 0)
| Pmod_functor (param, body) ->
functor_ ~loc ~attrs
(map_functor_param sub param)
(sub # module_expr body)
#else
| Pmod_functor (arg, arg_ty, body) ->
functor_ ~loc ~attrs (map_loc sub arg)
(map_opt (sub # module_type) arg_ty)
(sub # module_expr body)
#endif
| Pmod_apply (m1, m2) ->
apply ~loc ~attrs (sub # module_expr m1) (sub # module_expr m2)
| Pmod_constraint (m, mty) ->
constraint_ ~loc ~attrs (sub # module_expr m) (sub # module_type mty)
| Pmod_unpack e -> unpack ~loc ~attrs (sub # expr e)
| Pmod_extension x -> extension ~loc ~attrs (sub # extension x)
let map_structure_item sub {pstr_loc = loc; pstr_desc = desc} =
let open Str in
let loc = sub # location loc in
match desc with
| Pstr_eval (x, attrs) ->
eval ~loc ~attrs:(sub # attributes attrs) (sub # expr x)
| Pstr_value (r, vbs) -> value ~loc r (List.map (sub # value_binding) vbs)
| Pstr_primitive vd -> primitive ~loc (sub # value_description vd)
| Pstr_type (rf, l) -> type_ ~loc rf (List.map (sub # type_declaration) l)
| Pstr_typext te -> type_extension ~loc (sub # type_extension te)
| Pstr_exception ed -> exception_ ~loc (sub # type_exception ed)
| Pstr_module x -> module_ ~loc (sub # module_binding x)
| Pstr_recmodule l -> rec_module ~loc (List.map (sub # module_binding) l)
| Pstr_modtype x -> modtype ~loc (sub # module_type_declaration x)
| Pstr_open od -> open_ ~loc (sub # open_declaration od)
| Pstr_class l -> class_ ~loc (List.map (sub # class_declaration) l)
| Pstr_class_type l ->
class_type ~loc (List.map (sub # class_type_declaration) l)
| Pstr_include x -> include_ ~loc (sub # include_declaration x)
| Pstr_extension (x, attrs) ->
extension ~loc (sub # extension x) ~attrs:(sub # attributes attrs)
| Pstr_attribute x -> attribute ~loc (sub # attribute x)
end
module E = struct
(* Value expressions for the core language *)
let map_binding_op sub {pbop_op = op; pbop_pat = pat; pbop_exp = exp; pbop_loc = loc} =
let op = map_loc sub op in
let pat = sub # pat pat in
let exp = sub # expr exp in
let loc = sub # location loc in
{pbop_op = op; pbop_pat = pat; pbop_exp = exp; pbop_loc = loc}
let map sub {pexp_loc = loc; pexp_loc_stack = _; pexp_desc = desc; pexp_attributes = attrs} =
let open Exp in
let loc = sub # location loc in
let attrs = sub # attributes attrs in
match desc with
| Pexp_ident x -> ident ~loc ~attrs (map_loc sub x)
| Pexp_constant x -> constant ~loc ~attrs x
| Pexp_let (r, vbs, e) ->
let_ ~loc ~attrs r (List.map (sub # value_binding) vbs) (sub # expr e)
| Pexp_fun (lab, def, p, e) ->
fun_ ~loc ~attrs lab (map_opt (sub # expr) def) (sub # pat p)
(sub # expr e)
| Pexp_function pel -> function_ ~loc ~attrs (sub # cases pel)
| Pexp_apply (e, l) ->
apply ~loc ~attrs (sub # expr e) (List.map (map_snd (sub # expr)) l)
| Pexp_match (e, pel) -> match_ ~loc ~attrs (sub # expr e) (sub # cases pel)
| Pexp_try (e, pel) -> try_ ~loc ~attrs (sub # expr e) (sub # cases pel)
| Pexp_tuple el -> tuple ~loc ~attrs (List.map (sub # expr) el)
| Pexp_construct (lid, arg) ->
construct ~loc ~attrs (map_loc sub lid) (map_opt (sub # expr) arg)
| Pexp_variant (lab, eo) ->
variant ~loc ~attrs lab (map_opt (sub # expr) eo)
| Pexp_record (l, eo) ->
record ~loc ~attrs (List.map (map_tuple (map_loc sub) (sub # expr)) l)
(map_opt (sub # expr) eo)
| Pexp_field (e, lid) -> field ~loc ~attrs (sub # expr e) (map_loc sub lid)
| Pexp_setfield (e1, lid, e2) ->
setfield ~loc ~attrs (sub # expr e1) (map_loc sub lid) (sub # expr e2)
| Pexp_array el -> array ~loc ~attrs (List.map (sub # expr) el)
| Pexp_ifthenelse (e1, e2, e3) ->
ifthenelse ~loc ~attrs (sub # expr e1) (sub # expr e2)
(map_opt (sub # expr) e3)
| Pexp_sequence (e1, e2) ->
sequence ~loc ~attrs (sub # expr e1) (sub # expr e2)
| Pexp_while (e1, e2) -> while_ ~loc ~attrs (sub # expr e1) (sub # expr e2)
| Pexp_for (p, e1, e2, d, e3) ->
for_ ~loc ~attrs (sub # pat p) (sub # expr e1) (sub # expr e2) d
(sub # expr e3)
| Pexp_coerce (e, t1, t2) ->
coerce ~loc ~attrs (sub # expr e) (map_opt (sub # typ) t1)
(sub # typ t2)
| Pexp_constraint (e, t) ->
constraint_ ~loc ~attrs (sub # expr e) (sub # typ t)
| Pexp_send (e, s) -> send ~loc ~attrs (sub # expr e) s
| Pexp_new lid -> new_ ~loc ~attrs (map_loc sub lid)
| Pexp_setinstvar (s, e) ->
setinstvar ~loc ~attrs (map_loc sub s) (sub # expr e)
| Pexp_override sel ->
override ~loc ~attrs
(List.map (map_tuple (map_loc sub) (sub # expr)) sel)
| Pexp_letmodule (s, me, e) ->
letmodule ~loc ~attrs (map_loc sub s) (sub # module_expr me)
(sub # expr e)
| Pexp_letexception (cd, e) ->
letexception ~loc ~attrs
(sub # extension_constructor cd)
(sub # expr e)
| Pexp_assert e -> assert_ ~loc ~attrs (sub # expr e)
| Pexp_lazy e -> lazy_ ~loc ~attrs (sub # expr e)
| Pexp_poly (e, t) ->
poly ~loc ~attrs (sub # expr e) (map_opt (sub # typ) t)
| Pexp_object cls -> object_ ~loc ~attrs (sub # class_structure cls)
| Pexp_newtype (s, e) -> newtype ~loc ~attrs s (sub # expr e)
| Pexp_pack me -> pack ~loc ~attrs (sub # module_expr me)
| Pexp_open (od, e) ->
open_ ~loc ~attrs (sub # open_declaration od) (sub # expr e)
| Pexp_letop x ->
let let_ = map_binding_op sub x.let_ in
let ands = List.map (map_binding_op sub) x.ands in
let body = sub # expr x.body in
letop ~loc ~attrs let_ ands body
| Pexp_extension x -> extension ~loc ~attrs (sub # extension x)
| Pexp_unreachable -> unreachable ~loc ~attrs ()
end
module P = struct
(* Patterns *)
let map sub {ppat_desc = desc; ppat_loc = loc; ppat_loc_stack = _; ppat_attributes = attrs} =
let open Pat in
let loc = sub # location loc in
let attrs = sub # attributes attrs in
match desc with
| Ppat_any -> any ~loc ~attrs ()
| Ppat_var s -> var ~loc ~attrs (map_loc sub s)
| Ppat_alias (p, s) -> alias ~loc ~attrs (sub # pat p) (map_loc sub s)
| Ppat_constant c -> constant ~loc ~attrs c
| Ppat_interval (c1, c2) -> interval ~loc ~attrs c1 c2
| Ppat_tuple pl -> tuple ~loc ~attrs (List.map (sub # pat) pl)
| Ppat_construct (l, p) ->
construct ~loc ~attrs (map_loc sub l) (map_opt (sub # pat) p)
| Ppat_variant (l, p) -> variant ~loc ~attrs l (map_opt (sub # pat) p)
| Ppat_record (lpl, cf) ->
record ~loc ~attrs (List.map (map_tuple (map_loc sub) (sub # pat)) lpl)
cf
| Ppat_array pl -> array ~loc ~attrs (List.map (sub # pat) pl)
| Ppat_or (p1, p2) -> or_ ~loc ~attrs (sub # pat p1) (sub # pat p2)
| Ppat_constraint (p, t) ->
constraint_ ~loc ~attrs (sub # pat p) (sub # typ t)
| Ppat_type s -> type_ ~loc ~attrs (map_loc sub s)
| Ppat_lazy p -> lazy_ ~loc ~attrs (sub # pat p)
| Ppat_unpack s -> unpack ~loc ~attrs (map_loc sub s)
| Ppat_exception p -> exception_ ~loc ~attrs (sub # pat p)
| Ppat_extension x -> extension ~loc ~attrs (sub # extension x)
| Ppat_open (l, p) -> open_ ~loc ~attrs (map_loc sub l) (sub # pat p)
end
module CE = struct
(* Value expressions for the class language *)
let map sub {pcl_loc = loc; pcl_desc = desc; pcl_attributes = attrs} =
let open Cl in
let loc = sub # location loc in
match desc with
| Pcl_constr (lid, tys) ->
constr ~loc ~attrs (map_loc sub lid) (List.map (sub # typ) tys)
| Pcl_structure s ->
structure ~loc ~attrs (sub # class_structure s)
| Pcl_fun (lab, e, p, ce) ->
fun_ ~loc ~attrs lab
(map_opt (sub # expr) e)
(sub # pat p)
(sub # class_expr ce)
| Pcl_apply (ce, l) ->
apply ~loc ~attrs (sub # class_expr ce)
(List.map (map_snd (sub # expr)) l)
| Pcl_let (r, vbs, ce) ->
let_ ~loc ~attrs r (List.map (sub # value_binding) vbs)
(sub # class_expr ce)
| Pcl_constraint (ce, ct) ->
constraint_ ~loc ~attrs (sub # class_expr ce) (sub # class_type ct)
| Pcl_extension x -> extension ~loc ~attrs (sub # extension x)
| Pcl_open (od, ce) ->
open_ ~loc ~attrs (sub # open_description od) (sub # class_expr ce)
let map_kind sub = function
| Cfk_concrete (o, e) -> Cfk_concrete (o, sub # expr e)
| Cfk_virtual t -> Cfk_virtual (sub # typ t)
let map_field sub {pcf_desc = desc; pcf_loc = loc; pcf_attributes = attrs} =
let open Cf in
let loc = sub # location loc in
match desc with
| Pcf_inherit (o, ce, s) -> inherit_ ~loc ~attrs o (sub # class_expr ce) s
| Pcf_val (s, m, k) -> val_ ~loc ~attrs (map_loc sub s) m (map_kind sub k)
| Pcf_method (s, p, k) ->
method_ ~loc ~attrs (map_loc sub s) p (map_kind sub k)
| Pcf_constraint (t1, t2) ->
constraint_ ~loc ~attrs (sub # typ t1) (sub # typ t2)
| Pcf_initializer e -> initializer_ ~loc ~attrs (sub # expr e)
| Pcf_attribute x -> attribute ~loc (sub # attribute x)
| Pcf_extension x -> extension ~loc ~attrs (sub # extension x)
let map_structure sub {pcstr_self; pcstr_fields} =
{
pcstr_self = sub # pat pcstr_self;
pcstr_fields = List.map (sub # class_field) pcstr_fields;
}
let class_infos sub f {pci_virt; pci_params = pl; pci_name; pci_expr;
pci_loc; pci_attributes} =
Ci.mk
~virt:pci_virt
~params:(List.map (map_fst (sub # typ)) pl)
(map_loc sub pci_name)
(f pci_expr)
~loc:(sub # location pci_loc)
~attrs:(sub # attributes pci_attributes)
end
Now , a generic AST mapper class , to be extended to cover all kinds
and cases of the OCaml grammar . The default behavior of the mapper
is the identity .
and cases of the OCaml grammar. The default behavior of the mapper
is the identity. *)
class mapper =
object(this)
method structure l = List.map (this # structure_item) l
method structure_item si = M.map_structure_item this si
method module_expr = M.map this
method signature l = List.map (this # signature_item) l
method signature_item si = MT.map_signature_item this si
method module_type = MT.map this
method with_constraint c = MT.map_with_constraint this c
method class_declaration = CE.class_infos this (this # class_expr)
method class_expr = CE.map this
method class_field = CE.map_field this
method class_structure = CE.map_structure this
method class_type = CT.map this
method class_type_field = CT.map_field this
method class_signature = CT.map_signature this
method class_type_declaration = CE.class_infos this (this # class_type)
method class_description = CE.class_infos this (this # class_type)
method binding_op = E.map_binding_op this
method type_declaration = T.map_type_declaration this
method type_kind = T.map_type_kind this
method typ = T.map this
method type_extension = T.map_type_extension this
method type_exception = T.map_type_exception this
method extension_constructor = T.map_extension_constructor this
method value_description {pval_name; pval_type; pval_prim; pval_loc;
pval_attributes} =
Val.mk
(map_loc this pval_name)
(this # typ pval_type)
~attrs:(this # attributes pval_attributes)
~loc:(this # location pval_loc)
~prim:pval_prim
method pat = P.map this
method expr = E.map this
method module_declaration {pmd_name; pmd_type; pmd_attributes; pmd_loc} =
Md.mk
(map_loc this pmd_name)
(this # module_type pmd_type)
~attrs:(this # attributes pmd_attributes)
~loc:(this # location pmd_loc)
method module_substitution {pms_name; pms_manifest; pms_attributes; pms_loc} =
Ms.mk
(map_loc this pms_name)
(map_loc this pms_manifest)
~attrs:(this # attributes pms_attributes)
~loc:(this # location pms_loc)
method module_type_declaration {pmtd_name; pmtd_type; pmtd_attributes; pmtd_loc} =
Mtd.mk
(map_loc this pmtd_name)
?typ:(map_opt (this # module_type) pmtd_type)
~attrs:(this # attributes pmtd_attributes)
~loc:(this # location pmtd_loc)
method module_binding {pmb_name; pmb_expr; pmb_attributes; pmb_loc} =
Mb.mk (map_loc this pmb_name) (this # module_expr pmb_expr)
~attrs:(this # attributes pmb_attributes)
~loc:(this # location pmb_loc)
method value_binding {pvb_pat; pvb_expr; pvb_attributes; pvb_loc} =
Vb.mk
(this # pat pvb_pat)
(this # expr pvb_expr)
~attrs:(this # attributes pvb_attributes)
~loc:(this # location pvb_loc)
method constructor_arguments = function
| Pcstr_tuple (tys) -> Pcstr_tuple (List.map (this # typ) tys)
| Pcstr_record (ls) -> Pcstr_record (List.map (this # label_declaration) ls)
method constructor_declaration {pcd_name; pcd_args; pcd_res; pcd_loc;
pcd_attributes} =
Type.constructor
(map_loc this pcd_name)
~args:(this # constructor_arguments pcd_args)
?res:(map_opt (this # typ) pcd_res)
~loc:(this # location pcd_loc)
~attrs:(this # attributes pcd_attributes)
method label_declaration {pld_name; pld_type; pld_loc; pld_mutable;
pld_attributes} =
Type.field
(map_loc this pld_name)
(this # typ pld_type)
~mut:pld_mutable
~loc:(this # location pld_loc)
~attrs:(this # attributes pld_attributes)
method cases l = List.map (this # case) l
method case {pc_lhs; pc_guard; pc_rhs} =
{
pc_lhs = this # pat pc_lhs;
pc_guard = map_opt (this # expr) pc_guard;
pc_rhs = this # expr pc_rhs;
}
method open_declaration
{popen_expr; popen_override; popen_attributes; popen_loc} =
Opn.mk (this # module_expr popen_expr)
~override:popen_override
~loc:(this # location popen_loc)
~attrs:(this # attributes popen_attributes)
method open_description
{popen_expr; popen_override; popen_attributes; popen_loc} =
Opn.mk (map_loc this popen_expr)
~override:popen_override
~loc:(this # location popen_loc)
~attrs:(this # attributes popen_attributes)
method include_description
{pincl_mod; pincl_attributes; pincl_loc} =
Incl.mk (this # module_type pincl_mod)
~loc:(this # location pincl_loc)
~attrs:(this # attributes pincl_attributes)
method include_declaration
{pincl_mod; pincl_attributes; pincl_loc} =
Incl.mk (this # module_expr pincl_mod)
~loc:(this # location pincl_loc)
~attrs:(this # attributes pincl_attributes)
method location l = l
method extension (s, e) = (map_loc this s, this # payload e)
method attribute a =
{
attr_name = map_loc this a.attr_name;
attr_payload = this # payload a.attr_payload;
attr_loc = this # location a.attr_loc;
}
method attributes l = List.map (this # attribute) l
method payload = function
| PStr x -> PStr (this # structure x)
| PTyp x -> PTyp (this # typ x)
| PPat (x, g) -> PPat (this # pat x, map_opt (this # expr) g)
| PSig x -> PSig (this # signature x)
#if OCAML_VERSION >= (4, 11, 0)
method constant = function
| Pconst_integer (str, suffix) -> Pconst_integer (str, suffix)
| Pconst_char c -> Pconst_char c
| Pconst_string (str, loc, delim) -> Pconst_string (str, this # location loc, delim)
| Pconst_float (str, suffix) -> Pconst_float (str, suffix)
#endif
end
let to_mapper this =
let open Ast_mapper in
{
attribute = (fun _ -> this # attribute);
attributes = (fun _ -> this # attributes);
binding_op = (fun _ -> this # binding_op);
case = (fun _ -> this # case);
cases = (fun _ -> this # cases);
class_declaration = (fun _ -> this # class_declaration);
class_description = (fun _ -> this # class_description);
class_expr = (fun _ -> this # class_expr);
class_field = (fun _ -> this # class_field);
class_signature = (fun _ -> this # class_signature);
class_structure = (fun _ -> this # class_structure);
class_type = (fun _ -> this # class_type);
class_type_declaration = (fun _ -> this # class_type_declaration);
class_type_field = (fun _ -> this # class_type_field);
#if OCAML_VERSION >= (4, 11, 0)
constant = (fun _ -> this # constant);
#endif
constructor_declaration = (fun _ -> this # constructor_declaration);
expr = (fun _ -> this # expr);
extension = (fun _ -> this # extension);
extension_constructor = (fun _ -> this # extension_constructor);
include_declaration = (fun _ -> this # include_declaration);
include_description = (fun _ -> this # include_description);
label_declaration = (fun _ -> this # label_declaration);
location = (fun _ -> this # location);
module_binding = (fun _ -> this # module_binding);
module_declaration = (fun _ -> this # module_declaration);
module_expr = (fun _ -> this # module_expr);
module_substitution = (fun _ -> this # module_substitution);
module_type = (fun _ -> this # module_type);
module_type_declaration = (fun _ -> this # module_type_declaration);
open_declaration = (fun _ -> this # open_declaration);
open_description = (fun _ -> this # open_description);
pat = (fun _ -> this # pat);
payload = (fun _ -> this # payload);
signature = (fun _ -> this # signature);
signature_item = (fun _ -> this # signature_item);
structure = (fun _ -> this # structure);
structure_item = (fun _ -> this # structure_item);
typ = (fun _ -> this # typ);
type_declaration = (fun _ -> this # type_declaration);
type_exception = (fun _ -> this # type_exception);
type_extension = (fun _ -> this # type_extension);
type_kind = (fun _ -> this # type_kind);
value_binding = (fun _ -> this # value_binding);
value_description = (fun _ -> this # value_description);
with_constraint = (fun _ -> this # with_constraint);
}
| null | https://raw.githubusercontent.com/ManasJayanth/reason-on-multicore/39de4889f27ec43ab8a34732fb40b7adae08d1ed/vendor/ppx_tools/src/ast_mapper_class.ml | ocaml | This file is part of the ppx_tools package. It is released
* Class-based customizable mapper
Type expressions for the core language
Type expressions for the class language
Type expressions for the module language
Value expressions for the module language
Value expressions for the core language
Patterns
Value expressions for the class language | under the terms of the MIT license ( see LICENSE file ) .
Copyright 2013 and LexiFi
open Parsetree
open Asttypes
open Ast_helper
let map_fst f (x, y) = (f x, y)
let map_snd f (x, y) = (x, f y)
let map_tuple f1 f2 (x, y) = (f1 x, f2 y)
let map_tuple3 f1 f2 f3 (x, y, z) = (f1 x, f2 y, f3 z)
let map_opt f = function None -> None | Some x -> Some (f x)
let map_loc sub {loc; txt} = {loc = sub # location loc; txt}
module T = struct
let row_field_desc sub = function
| Rtag (l, b, tl) -> Rtag (l, b, List.map (sub # typ) tl)
| Rinherit t -> Rinherit (sub # typ t)
let row_field sub {prf_desc = desc; prf_loc = loc; prf_attributes = attrs} =
let desc = row_field_desc sub desc in
let loc = sub # location loc in
let attrs = sub # attributes attrs in
{prf_desc = desc; prf_loc = loc; prf_attributes = attrs}
let object_field_desc sub = function
| Otag (s, t) -> Otag (s, sub # typ t)
| Oinherit t -> Oinherit (sub # typ t)
let object_field sub {pof_desc = desc; pof_loc = loc; pof_attributes = attrs} =
let desc = object_field_desc sub desc in
let loc = sub # location loc in
let attrs = sub # attributes attrs in
{pof_desc = desc; pof_loc = loc; pof_attributes = attrs}
let map sub {ptyp_desc = desc; ptyp_loc = loc; ptyp_loc_stack = _; ptyp_attributes = attrs} =
let open Typ in
let loc = sub # location loc in
let attrs = sub # attributes attrs in
match desc with
| Ptyp_any -> any ~loc ~attrs ()
| Ptyp_var s -> var ~loc ~attrs s
| Ptyp_arrow (lab, t1, t2) ->
arrow ~loc ~attrs lab (sub # typ t1) (sub # typ t2)
| Ptyp_tuple tyl -> tuple ~loc ~attrs (List.map (sub # typ) tyl)
| Ptyp_constr (lid, tl) ->
constr ~loc ~attrs (map_loc sub lid) (List.map (sub # typ) tl)
| Ptyp_object (l, o) ->
object_ ~loc ~attrs (List.map (object_field sub) l) o
| Ptyp_class (lid, tl) ->
class_ ~loc ~attrs (map_loc sub lid) (List.map (sub # typ) tl)
| Ptyp_alias (t, s) -> alias ~loc ~attrs (sub # typ t) s
| Ptyp_variant (rl, b, ll) ->
variant ~loc ~attrs (List.map (row_field sub) rl) b ll
| Ptyp_poly (sl, t) -> poly ~loc ~attrs sl (sub # typ t)
| Ptyp_package (lid, l) ->
package ~loc ~attrs (map_loc sub lid)
(List.map (map_tuple (map_loc sub) (sub # typ)) l)
| Ptyp_extension x -> extension ~loc ~attrs (sub # extension x)
let map_type_declaration sub
{ptype_name; ptype_params; ptype_cstrs;
ptype_kind;
ptype_private;
ptype_manifest;
ptype_attributes;
ptype_loc} =
Type.mk (map_loc sub ptype_name)
~params:(List.map (map_fst (sub # typ)) ptype_params)
~priv:ptype_private
~cstrs:(List.map (map_tuple3 (sub # typ) (sub # typ) (sub # location))
ptype_cstrs)
~kind:(sub # type_kind ptype_kind)
?manifest:(map_opt (sub # typ) ptype_manifest)
~loc:(sub # location ptype_loc)
~attrs:(sub # attributes ptype_attributes)
let map_type_kind sub = function
| Ptype_abstract -> Ptype_abstract
| Ptype_variant l ->
Ptype_variant (List.map (sub # constructor_declaration) l)
| Ptype_record l -> Ptype_record (List.map (sub # label_declaration) l)
| Ptype_open -> Ptype_open
let map_type_extension sub
{ptyext_path; ptyext_params;
ptyext_constructors;
ptyext_private;
ptyext_loc;
ptyext_attributes} =
Te.mk
(map_loc sub ptyext_path)
(List.map (sub # extension_constructor) ptyext_constructors)
~params:(List.map (map_fst (sub # typ)) ptyext_params)
~priv:ptyext_private
~loc:(sub # location ptyext_loc)
~attrs:(sub # attributes ptyext_attributes)
let map_extension_constructor_kind sub = function
Pext_decl(ctl, cto) ->
Pext_decl(sub # constructor_arguments ctl, map_opt (sub # typ) cto)
| Pext_rebind li ->
Pext_rebind (map_loc sub li)
let map_extension_constructor sub
{pext_name;
pext_kind;
pext_loc;
pext_attributes} =
Te.constructor
(map_loc sub pext_name)
(map_extension_constructor_kind sub pext_kind)
~loc:(sub # location pext_loc)
~attrs:(sub # attributes pext_attributes)
let map_type_exception sub {ptyexn_constructor; ptyexn_loc; ptyexn_attributes} =
Te.mk_exception
(map_extension_constructor sub ptyexn_constructor)
~loc:(sub # location ptyexn_loc)
~attrs:(sub # attributes ptyexn_attributes)
end
module CT = struct
let map sub {pcty_loc = loc; pcty_desc = desc; pcty_attributes = attrs} =
let open Cty in
let loc = sub # location loc in
match desc with
| Pcty_constr (lid, tys) ->
constr ~loc ~attrs (map_loc sub lid) (List.map (sub # typ) tys)
| Pcty_signature x -> signature ~loc ~attrs (sub # class_signature x)
| Pcty_arrow (lab, t, ct) ->
arrow ~loc ~attrs lab (sub # typ t) (sub # class_type ct)
| Pcty_extension x -> extension ~loc ~attrs (sub # extension x)
| Pcty_open (od, ct) ->
open_ ~loc ~attrs (sub # open_description od) (sub # class_type ct)
let map_field sub {pctf_desc = desc; pctf_loc = loc; pctf_attributes = attrs}
=
let open Ctf in
let loc = sub # location loc in
match desc with
| Pctf_inherit ct -> inherit_ ~loc ~attrs (sub # class_type ct)
| Pctf_val (s, m, v, t) -> val_ ~loc ~attrs s m v (sub # typ t)
| Pctf_method (s, p, v, t) -> method_ ~loc ~attrs s p v (sub # typ t)
| Pctf_constraint (t1, t2) ->
constraint_ ~loc ~attrs (sub # typ t1) (sub # typ t2)
| Pctf_attribute x -> attribute ~loc (sub # attribute x)
| Pctf_extension x -> extension ~loc ~attrs (sub # extension x)
let map_signature sub {pcsig_self; pcsig_fields} =
Csig.mk
(sub # typ pcsig_self)
(List.map (sub # class_type_field) pcsig_fields)
end
#if OCAML_VERSION >= (4, 10, 0)
let map_functor_param sub = function
| Unit -> Unit
| Named (s, mt) -> Named (map_loc sub s, sub # module_type mt)
#endif
module MT = struct
let map sub {pmty_desc = desc; pmty_loc = loc; pmty_attributes = attrs} =
let open Mty in
let loc = sub # location loc in
let attrs = sub # attributes attrs in
match desc with
| Pmty_ident s -> ident ~loc ~attrs (map_loc sub s)
| Pmty_alias s -> alias ~loc ~attrs (map_loc sub s)
| Pmty_signature sg -> signature ~loc ~attrs (sub # signature sg)
#if OCAML_VERSION >= (4, 10, 0)
| Pmty_functor (param, mt) ->
functor_ ~loc ~attrs
(map_functor_param sub param)
(sub # module_type mt)
#else
| Pmty_functor (s, mt1, mt2) ->
functor_ ~loc ~attrs (map_loc sub s)
(map_opt (sub # module_type) mt1)
(sub # module_type mt2)
#endif
| Pmty_with (mt, l) ->
with_ ~loc ~attrs (sub # module_type mt)
(List.map (sub # with_constraint) l)
| Pmty_typeof me -> typeof_ ~loc ~attrs (sub # module_expr me)
| Pmty_extension x -> extension ~loc ~attrs (sub # extension x)
let map_with_constraint sub = function
| Pwith_type (lid, d) ->
Pwith_type (map_loc sub lid, sub # type_declaration d)
| Pwith_module (lid, lid2) ->
Pwith_module (map_loc sub lid, map_loc sub lid2)
| Pwith_typesubst (lid, d) ->
Pwith_typesubst (map_loc sub lid, sub # type_declaration d)
| Pwith_modsubst (lid, lid2) ->
Pwith_modsubst (map_loc sub lid, map_loc sub lid2)
let map_signature_item sub {psig_desc = desc; psig_loc = loc} =
let open Sig in
let loc = sub # location loc in
match desc with
| Psig_value vd -> value ~loc (sub # value_description vd)
| Psig_type (rf, l) -> type_ ~loc rf (List.map (sub # type_declaration) l)
| Psig_typesubst l -> type_subst ~loc (List.map (sub # type_declaration) l)
| Psig_typext te -> type_extension ~loc (sub # type_extension te)
| Psig_exception texn -> exception_ ~loc (sub # type_exception texn)
| Psig_module x -> module_ ~loc (sub # module_declaration x)
| Psig_modsubst ms -> mod_subst ~loc (sub # module_substitution ms)
| Psig_recmodule l ->
rec_module ~loc (List.map (sub # module_declaration) l)
| Psig_modtype x -> modtype ~loc (sub # module_type_declaration x)
| Psig_open od -> open_ ~loc (sub # open_description od)
| Psig_include x -> include_ ~loc (sub # include_description x)
| Psig_class l -> class_ ~loc (List.map (sub # class_description) l)
| Psig_class_type l ->
class_type ~loc (List.map (sub # class_type_declaration) l)
| Psig_extension (x, attrs) ->
extension ~loc (sub # extension x) ~attrs:(sub # attributes attrs)
| Psig_attribute x -> attribute ~loc (sub # attribute x)
end
module M = struct
let map sub {pmod_loc = loc; pmod_desc = desc; pmod_attributes = attrs} =
let open Mod in
let loc = sub # location loc in
let attrs = sub # attributes attrs in
match desc with
| Pmod_ident x -> ident ~loc ~attrs (map_loc sub x)
| Pmod_structure str -> structure ~loc ~attrs (sub # structure str)
#if OCAML_VERSION >= (4, 10, 0)
| Pmod_functor (param, body) ->
functor_ ~loc ~attrs
(map_functor_param sub param)
(sub # module_expr body)
#else
| Pmod_functor (arg, arg_ty, body) ->
functor_ ~loc ~attrs (map_loc sub arg)
(map_opt (sub # module_type) arg_ty)
(sub # module_expr body)
#endif
| Pmod_apply (m1, m2) ->
apply ~loc ~attrs (sub # module_expr m1) (sub # module_expr m2)
| Pmod_constraint (m, mty) ->
constraint_ ~loc ~attrs (sub # module_expr m) (sub # module_type mty)
| Pmod_unpack e -> unpack ~loc ~attrs (sub # expr e)
| Pmod_extension x -> extension ~loc ~attrs (sub # extension x)
let map_structure_item sub {pstr_loc = loc; pstr_desc = desc} =
let open Str in
let loc = sub # location loc in
match desc with
| Pstr_eval (x, attrs) ->
eval ~loc ~attrs:(sub # attributes attrs) (sub # expr x)
| Pstr_value (r, vbs) -> value ~loc r (List.map (sub # value_binding) vbs)
| Pstr_primitive vd -> primitive ~loc (sub # value_description vd)
| Pstr_type (rf, l) -> type_ ~loc rf (List.map (sub # type_declaration) l)
| Pstr_typext te -> type_extension ~loc (sub # type_extension te)
| Pstr_exception ed -> exception_ ~loc (sub # type_exception ed)
| Pstr_module x -> module_ ~loc (sub # module_binding x)
| Pstr_recmodule l -> rec_module ~loc (List.map (sub # module_binding) l)
| Pstr_modtype x -> modtype ~loc (sub # module_type_declaration x)
| Pstr_open od -> open_ ~loc (sub # open_declaration od)
| Pstr_class l -> class_ ~loc (List.map (sub # class_declaration) l)
| Pstr_class_type l ->
class_type ~loc (List.map (sub # class_type_declaration) l)
| Pstr_include x -> include_ ~loc (sub # include_declaration x)
| Pstr_extension (x, attrs) ->
extension ~loc (sub # extension x) ~attrs:(sub # attributes attrs)
| Pstr_attribute x -> attribute ~loc (sub # attribute x)
end
module E = struct
let map_binding_op sub {pbop_op = op; pbop_pat = pat; pbop_exp = exp; pbop_loc = loc} =
let op = map_loc sub op in
let pat = sub # pat pat in
let exp = sub # expr exp in
let loc = sub # location loc in
{pbop_op = op; pbop_pat = pat; pbop_exp = exp; pbop_loc = loc}
let map sub {pexp_loc = loc; pexp_loc_stack = _; pexp_desc = desc; pexp_attributes = attrs} =
let open Exp in
let loc = sub # location loc in
let attrs = sub # attributes attrs in
match desc with
| Pexp_ident x -> ident ~loc ~attrs (map_loc sub x)
| Pexp_constant x -> constant ~loc ~attrs x
| Pexp_let (r, vbs, e) ->
let_ ~loc ~attrs r (List.map (sub # value_binding) vbs) (sub # expr e)
| Pexp_fun (lab, def, p, e) ->
fun_ ~loc ~attrs lab (map_opt (sub # expr) def) (sub # pat p)
(sub # expr e)
| Pexp_function pel -> function_ ~loc ~attrs (sub # cases pel)
| Pexp_apply (e, l) ->
apply ~loc ~attrs (sub # expr e) (List.map (map_snd (sub # expr)) l)
| Pexp_match (e, pel) -> match_ ~loc ~attrs (sub # expr e) (sub # cases pel)
| Pexp_try (e, pel) -> try_ ~loc ~attrs (sub # expr e) (sub # cases pel)
| Pexp_tuple el -> tuple ~loc ~attrs (List.map (sub # expr) el)
| Pexp_construct (lid, arg) ->
construct ~loc ~attrs (map_loc sub lid) (map_opt (sub # expr) arg)
| Pexp_variant (lab, eo) ->
variant ~loc ~attrs lab (map_opt (sub # expr) eo)
| Pexp_record (l, eo) ->
record ~loc ~attrs (List.map (map_tuple (map_loc sub) (sub # expr)) l)
(map_opt (sub # expr) eo)
| Pexp_field (e, lid) -> field ~loc ~attrs (sub # expr e) (map_loc sub lid)
| Pexp_setfield (e1, lid, e2) ->
setfield ~loc ~attrs (sub # expr e1) (map_loc sub lid) (sub # expr e2)
| Pexp_array el -> array ~loc ~attrs (List.map (sub # expr) el)
| Pexp_ifthenelse (e1, e2, e3) ->
ifthenelse ~loc ~attrs (sub # expr e1) (sub # expr e2)
(map_opt (sub # expr) e3)
| Pexp_sequence (e1, e2) ->
sequence ~loc ~attrs (sub # expr e1) (sub # expr e2)
| Pexp_while (e1, e2) -> while_ ~loc ~attrs (sub # expr e1) (sub # expr e2)
| Pexp_for (p, e1, e2, d, e3) ->
for_ ~loc ~attrs (sub # pat p) (sub # expr e1) (sub # expr e2) d
(sub # expr e3)
| Pexp_coerce (e, t1, t2) ->
coerce ~loc ~attrs (sub # expr e) (map_opt (sub # typ) t1)
(sub # typ t2)
| Pexp_constraint (e, t) ->
constraint_ ~loc ~attrs (sub # expr e) (sub # typ t)
| Pexp_send (e, s) -> send ~loc ~attrs (sub # expr e) s
| Pexp_new lid -> new_ ~loc ~attrs (map_loc sub lid)
| Pexp_setinstvar (s, e) ->
setinstvar ~loc ~attrs (map_loc sub s) (sub # expr e)
| Pexp_override sel ->
override ~loc ~attrs
(List.map (map_tuple (map_loc sub) (sub # expr)) sel)
| Pexp_letmodule (s, me, e) ->
letmodule ~loc ~attrs (map_loc sub s) (sub # module_expr me)
(sub # expr e)
| Pexp_letexception (cd, e) ->
letexception ~loc ~attrs
(sub # extension_constructor cd)
(sub # expr e)
| Pexp_assert e -> assert_ ~loc ~attrs (sub # expr e)
| Pexp_lazy e -> lazy_ ~loc ~attrs (sub # expr e)
| Pexp_poly (e, t) ->
poly ~loc ~attrs (sub # expr e) (map_opt (sub # typ) t)
| Pexp_object cls -> object_ ~loc ~attrs (sub # class_structure cls)
| Pexp_newtype (s, e) -> newtype ~loc ~attrs s (sub # expr e)
| Pexp_pack me -> pack ~loc ~attrs (sub # module_expr me)
| Pexp_open (od, e) ->
open_ ~loc ~attrs (sub # open_declaration od) (sub # expr e)
| Pexp_letop x ->
let let_ = map_binding_op sub x.let_ in
let ands = List.map (map_binding_op sub) x.ands in
let body = sub # expr x.body in
letop ~loc ~attrs let_ ands body
| Pexp_extension x -> extension ~loc ~attrs (sub # extension x)
| Pexp_unreachable -> unreachable ~loc ~attrs ()
end
module P = struct
let map sub {ppat_desc = desc; ppat_loc = loc; ppat_loc_stack = _; ppat_attributes = attrs} =
let open Pat in
let loc = sub # location loc in
let attrs = sub # attributes attrs in
match desc with
| Ppat_any -> any ~loc ~attrs ()
| Ppat_var s -> var ~loc ~attrs (map_loc sub s)
| Ppat_alias (p, s) -> alias ~loc ~attrs (sub # pat p) (map_loc sub s)
| Ppat_constant c -> constant ~loc ~attrs c
| Ppat_interval (c1, c2) -> interval ~loc ~attrs c1 c2
| Ppat_tuple pl -> tuple ~loc ~attrs (List.map (sub # pat) pl)
| Ppat_construct (l, p) ->
construct ~loc ~attrs (map_loc sub l) (map_opt (sub # pat) p)
| Ppat_variant (l, p) -> variant ~loc ~attrs l (map_opt (sub # pat) p)
| Ppat_record (lpl, cf) ->
record ~loc ~attrs (List.map (map_tuple (map_loc sub) (sub # pat)) lpl)
cf
| Ppat_array pl -> array ~loc ~attrs (List.map (sub # pat) pl)
| Ppat_or (p1, p2) -> or_ ~loc ~attrs (sub # pat p1) (sub # pat p2)
| Ppat_constraint (p, t) ->
constraint_ ~loc ~attrs (sub # pat p) (sub # typ t)
| Ppat_type s -> type_ ~loc ~attrs (map_loc sub s)
| Ppat_lazy p -> lazy_ ~loc ~attrs (sub # pat p)
| Ppat_unpack s -> unpack ~loc ~attrs (map_loc sub s)
| Ppat_exception p -> exception_ ~loc ~attrs (sub # pat p)
| Ppat_extension x -> extension ~loc ~attrs (sub # extension x)
| Ppat_open (l, p) -> open_ ~loc ~attrs (map_loc sub l) (sub # pat p)
end
module CE = struct
let map sub {pcl_loc = loc; pcl_desc = desc; pcl_attributes = attrs} =
let open Cl in
let loc = sub # location loc in
match desc with
| Pcl_constr (lid, tys) ->
constr ~loc ~attrs (map_loc sub lid) (List.map (sub # typ) tys)
| Pcl_structure s ->
structure ~loc ~attrs (sub # class_structure s)
| Pcl_fun (lab, e, p, ce) ->
fun_ ~loc ~attrs lab
(map_opt (sub # expr) e)
(sub # pat p)
(sub # class_expr ce)
| Pcl_apply (ce, l) ->
apply ~loc ~attrs (sub # class_expr ce)
(List.map (map_snd (sub # expr)) l)
| Pcl_let (r, vbs, ce) ->
let_ ~loc ~attrs r (List.map (sub # value_binding) vbs)
(sub # class_expr ce)
| Pcl_constraint (ce, ct) ->
constraint_ ~loc ~attrs (sub # class_expr ce) (sub # class_type ct)
| Pcl_extension x -> extension ~loc ~attrs (sub # extension x)
| Pcl_open (od, ce) ->
open_ ~loc ~attrs (sub # open_description od) (sub # class_expr ce)
let map_kind sub = function
| Cfk_concrete (o, e) -> Cfk_concrete (o, sub # expr e)
| Cfk_virtual t -> Cfk_virtual (sub # typ t)
let map_field sub {pcf_desc = desc; pcf_loc = loc; pcf_attributes = attrs} =
let open Cf in
let loc = sub # location loc in
match desc with
| Pcf_inherit (o, ce, s) -> inherit_ ~loc ~attrs o (sub # class_expr ce) s
| Pcf_val (s, m, k) -> val_ ~loc ~attrs (map_loc sub s) m (map_kind sub k)
| Pcf_method (s, p, k) ->
method_ ~loc ~attrs (map_loc sub s) p (map_kind sub k)
| Pcf_constraint (t1, t2) ->
constraint_ ~loc ~attrs (sub # typ t1) (sub # typ t2)
| Pcf_initializer e -> initializer_ ~loc ~attrs (sub # expr e)
| Pcf_attribute x -> attribute ~loc (sub # attribute x)
| Pcf_extension x -> extension ~loc ~attrs (sub # extension x)
let map_structure sub {pcstr_self; pcstr_fields} =
{
pcstr_self = sub # pat pcstr_self;
pcstr_fields = List.map (sub # class_field) pcstr_fields;
}
let class_infos sub f {pci_virt; pci_params = pl; pci_name; pci_expr;
pci_loc; pci_attributes} =
Ci.mk
~virt:pci_virt
~params:(List.map (map_fst (sub # typ)) pl)
(map_loc sub pci_name)
(f pci_expr)
~loc:(sub # location pci_loc)
~attrs:(sub # attributes pci_attributes)
end
Now , a generic AST mapper class , to be extended to cover all kinds
and cases of the OCaml grammar . The default behavior of the mapper
is the identity .
and cases of the OCaml grammar. The default behavior of the mapper
is the identity. *)
class mapper =
object(this)
method structure l = List.map (this # structure_item) l
method structure_item si = M.map_structure_item this si
method module_expr = M.map this
method signature l = List.map (this # signature_item) l
method signature_item si = MT.map_signature_item this si
method module_type = MT.map this
method with_constraint c = MT.map_with_constraint this c
method class_declaration = CE.class_infos this (this # class_expr)
method class_expr = CE.map this
method class_field = CE.map_field this
method class_structure = CE.map_structure this
method class_type = CT.map this
method class_type_field = CT.map_field this
method class_signature = CT.map_signature this
method class_type_declaration = CE.class_infos this (this # class_type)
method class_description = CE.class_infos this (this # class_type)
method binding_op = E.map_binding_op this
method type_declaration = T.map_type_declaration this
method type_kind = T.map_type_kind this
method typ = T.map this
method type_extension = T.map_type_extension this
method type_exception = T.map_type_exception this
method extension_constructor = T.map_extension_constructor this
method value_description {pval_name; pval_type; pval_prim; pval_loc;
pval_attributes} =
Val.mk
(map_loc this pval_name)
(this # typ pval_type)
~attrs:(this # attributes pval_attributes)
~loc:(this # location pval_loc)
~prim:pval_prim
method pat = P.map this
method expr = E.map this
method module_declaration {pmd_name; pmd_type; pmd_attributes; pmd_loc} =
Md.mk
(map_loc this pmd_name)
(this # module_type pmd_type)
~attrs:(this # attributes pmd_attributes)
~loc:(this # location pmd_loc)
method module_substitution {pms_name; pms_manifest; pms_attributes; pms_loc} =
Ms.mk
(map_loc this pms_name)
(map_loc this pms_manifest)
~attrs:(this # attributes pms_attributes)
~loc:(this # location pms_loc)
method module_type_declaration {pmtd_name; pmtd_type; pmtd_attributes; pmtd_loc} =
Mtd.mk
(map_loc this pmtd_name)
?typ:(map_opt (this # module_type) pmtd_type)
~attrs:(this # attributes pmtd_attributes)
~loc:(this # location pmtd_loc)
method module_binding {pmb_name; pmb_expr; pmb_attributes; pmb_loc} =
Mb.mk (map_loc this pmb_name) (this # module_expr pmb_expr)
~attrs:(this # attributes pmb_attributes)
~loc:(this # location pmb_loc)
method value_binding {pvb_pat; pvb_expr; pvb_attributes; pvb_loc} =
Vb.mk
(this # pat pvb_pat)
(this # expr pvb_expr)
~attrs:(this # attributes pvb_attributes)
~loc:(this # location pvb_loc)
method constructor_arguments = function
| Pcstr_tuple (tys) -> Pcstr_tuple (List.map (this # typ) tys)
| Pcstr_record (ls) -> Pcstr_record (List.map (this # label_declaration) ls)
method constructor_declaration {pcd_name; pcd_args; pcd_res; pcd_loc;
pcd_attributes} =
Type.constructor
(map_loc this pcd_name)
~args:(this # constructor_arguments pcd_args)
?res:(map_opt (this # typ) pcd_res)
~loc:(this # location pcd_loc)
~attrs:(this # attributes pcd_attributes)
method label_declaration {pld_name; pld_type; pld_loc; pld_mutable;
pld_attributes} =
Type.field
(map_loc this pld_name)
(this # typ pld_type)
~mut:pld_mutable
~loc:(this # location pld_loc)
~attrs:(this # attributes pld_attributes)
method cases l = List.map (this # case) l
method case {pc_lhs; pc_guard; pc_rhs} =
{
pc_lhs = this # pat pc_lhs;
pc_guard = map_opt (this # expr) pc_guard;
pc_rhs = this # expr pc_rhs;
}
method open_declaration
{popen_expr; popen_override; popen_attributes; popen_loc} =
Opn.mk (this # module_expr popen_expr)
~override:popen_override
~loc:(this # location popen_loc)
~attrs:(this # attributes popen_attributes)
method open_description
{popen_expr; popen_override; popen_attributes; popen_loc} =
Opn.mk (map_loc this popen_expr)
~override:popen_override
~loc:(this # location popen_loc)
~attrs:(this # attributes popen_attributes)
method include_description
{pincl_mod; pincl_attributes; pincl_loc} =
Incl.mk (this # module_type pincl_mod)
~loc:(this # location pincl_loc)
~attrs:(this # attributes pincl_attributes)
method include_declaration
{pincl_mod; pincl_attributes; pincl_loc} =
Incl.mk (this # module_expr pincl_mod)
~loc:(this # location pincl_loc)
~attrs:(this # attributes pincl_attributes)
method location l = l
method extension (s, e) = (map_loc this s, this # payload e)
method attribute a =
{
attr_name = map_loc this a.attr_name;
attr_payload = this # payload a.attr_payload;
attr_loc = this # location a.attr_loc;
}
method attributes l = List.map (this # attribute) l
method payload = function
| PStr x -> PStr (this # structure x)
| PTyp x -> PTyp (this # typ x)
| PPat (x, g) -> PPat (this # pat x, map_opt (this # expr) g)
| PSig x -> PSig (this # signature x)
#if OCAML_VERSION >= (4, 11, 0)
method constant = function
| Pconst_integer (str, suffix) -> Pconst_integer (str, suffix)
| Pconst_char c -> Pconst_char c
| Pconst_string (str, loc, delim) -> Pconst_string (str, this # location loc, delim)
| Pconst_float (str, suffix) -> Pconst_float (str, suffix)
#endif
end
let to_mapper this =
let open Ast_mapper in
{
attribute = (fun _ -> this # attribute);
attributes = (fun _ -> this # attributes);
binding_op = (fun _ -> this # binding_op);
case = (fun _ -> this # case);
cases = (fun _ -> this # cases);
class_declaration = (fun _ -> this # class_declaration);
class_description = (fun _ -> this # class_description);
class_expr = (fun _ -> this # class_expr);
class_field = (fun _ -> this # class_field);
class_signature = (fun _ -> this # class_signature);
class_structure = (fun _ -> this # class_structure);
class_type = (fun _ -> this # class_type);
class_type_declaration = (fun _ -> this # class_type_declaration);
class_type_field = (fun _ -> this # class_type_field);
#if OCAML_VERSION >= (4, 11, 0)
constant = (fun _ -> this # constant);
#endif
constructor_declaration = (fun _ -> this # constructor_declaration);
expr = (fun _ -> this # expr);
extension = (fun _ -> this # extension);
extension_constructor = (fun _ -> this # extension_constructor);
include_declaration = (fun _ -> this # include_declaration);
include_description = (fun _ -> this # include_description);
label_declaration = (fun _ -> this # label_declaration);
location = (fun _ -> this # location);
module_binding = (fun _ -> this # module_binding);
module_declaration = (fun _ -> this # module_declaration);
module_expr = (fun _ -> this # module_expr);
module_substitution = (fun _ -> this # module_substitution);
module_type = (fun _ -> this # module_type);
module_type_declaration = (fun _ -> this # module_type_declaration);
open_declaration = (fun _ -> this # open_declaration);
open_description = (fun _ -> this # open_description);
pat = (fun _ -> this # pat);
payload = (fun _ -> this # payload);
signature = (fun _ -> this # signature);
signature_item = (fun _ -> this # signature_item);
structure = (fun _ -> this # structure);
structure_item = (fun _ -> this # structure_item);
typ = (fun _ -> this # typ);
type_declaration = (fun _ -> this # type_declaration);
type_exception = (fun _ -> this # type_exception);
type_extension = (fun _ -> this # type_extension);
type_kind = (fun _ -> this # type_kind);
value_binding = (fun _ -> this # value_binding);
value_description = (fun _ -> this # value_description);
with_constraint = (fun _ -> this # with_constraint);
}
|
b51986bba62a3e6f38a0333c8bef0639a72c1961c334d03aba0ebf3dfcd956df | deadpendency/deadpendency | VerifyPlanRetC.hs | module RP.Effect.VerifyPlan.Carrier.VerifyPlanRetC
( runVerifyPlanRet,
)
where
import Control.Algebra (Algebra (..), (:+:) (..))
import RP.Effect.VerifyPlan.VerifyPlan (VerifyPlan (..))
newtype VerifyPlanRetC m a = VerifyPlanRetC {runVerifyPlanRetC :: m a}
deriving newtype (Functor, Applicative, Monad)
instance (Algebra sig m) => Algebra (VerifyPlan :+: sig) (VerifyPlanRetC m) where
alg hdl sig ctx = case sig of
(L PlanVerify) -> VerifyPlanRetC $ pure $ ctx $> ()
(R other) -> VerifyPlanRetC $ alg (runVerifyPlanRetC . hdl) other ctx
runVerifyPlanRet :: VerifyPlanRetC m a -> m a
runVerifyPlanRet = runVerifyPlanRetC
| null | https://raw.githubusercontent.com/deadpendency/deadpendency/170d6689658f81842168b90aa3d9e235d416c8bd/apps/run-preparer/src/RP/Effect/VerifyPlan/Carrier/VerifyPlanRetC.hs | haskell | module RP.Effect.VerifyPlan.Carrier.VerifyPlanRetC
( runVerifyPlanRet,
)
where
import Control.Algebra (Algebra (..), (:+:) (..))
import RP.Effect.VerifyPlan.VerifyPlan (VerifyPlan (..))
newtype VerifyPlanRetC m a = VerifyPlanRetC {runVerifyPlanRetC :: m a}
deriving newtype (Functor, Applicative, Monad)
instance (Algebra sig m) => Algebra (VerifyPlan :+: sig) (VerifyPlanRetC m) where
alg hdl sig ctx = case sig of
(L PlanVerify) -> VerifyPlanRetC $ pure $ ctx $> ()
(R other) -> VerifyPlanRetC $ alg (runVerifyPlanRetC . hdl) other ctx
runVerifyPlanRet :: VerifyPlanRetC m a -> m a
runVerifyPlanRet = runVerifyPlanRetC
| |
ac27370a656a3bdd313d0a57769e24808938b35d9a6eb6618888fb09b382df43 | haskell-rewriting/term-rewriting | Parse.hs | -- This file is part of the 'term-rewriting' library. It is licensed
under an MIT license . See the accompanying ' LICENSE ' file for details .
--
Authors : , Christian Sternagel
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
module Data.Rewriting.Problem.Parse (
parseIO,
parseFileIO,
fromString,
fromFile,
fromCharStream,
ProblemParseError (..)
) where
import Data.Rewriting.Utils.Parse (lex, par, ident)
import qualified Data.Rewriting.Problem.Type as Prob
import Data.Rewriting.Problem.Type (Problem)
import Data.Rewriting.Rule (Rule (..))
import qualified Data.Rewriting.Term as Term
import qualified Data.Rewriting.Rules as Rules
import Data.List (partition, union)
import Data.Maybe (isJust)
import Prelude hiding (lex, catch)
import Control.Exception (catch)
import Control.Monad.Error
import Control.Monad (liftM, liftM3)
import Text.Parsec hiding (parse)
import System.IO (readFile)
data ProblemParseError = UnknownParseError String
| UnsupportedStrategy String
| FileReadError IOError
| UnsupportedDeclaration String
| SomeParseError ParseError deriving (Show)
instance Error ProblemParseError where strMsg = UnknownParseError
parseFileIO :: FilePath -> IO (Problem String String)
parseFileIO file = do r <- fromFile file
case r of
Left err -> do { putStrLn "following error occured:"; print err; mzero }
Right t -> return t
parseIO :: String -> IO (Problem String String)
parseIO string = case fromString string of
Left err -> do { putStrLn "following error occured:"; print err; mzero }
Right t -> return t
fromFile :: FilePath -> IO (Either ProblemParseError (Problem String String))
fromFile file = fromFile' `catch` (return . Left . FileReadError) where
fromFile' = fromCharStream sn `liftM` readFile file
sn = "<file " ++ file ++ ">"
fromString :: String -> Either ProblemParseError (Problem String String)
fromString = fromCharStream "supplied string"
fromCharStream :: (Stream s (Either ProblemParseError) Char)
=> SourceName -> s -> Either ProblemParseError (Problem String String)
fromCharStream sourcename input =
case runParserT parse initialState sourcename input of
Right (Left e) -> Left $ SomeParseError e
Right (Right p) -> Right p
Left e -> Left e
where initialState = Prob.Problem { Prob.startTerms = Prob.AllTerms ,
Prob.strategy = Prob.Full ,
Prob.theory = Nothing ,
Prob.rules = Prob.RulesPair { Prob.strictRules = [],
Prob.weakRules = [] } ,
Prob.variables = [] ,
Prob.symbols = [] ,
Prob.signature = Nothing,
Prob.comment = Nothing }
type ParserState = Problem String String
type WSTParser s a = ParsecT s ParserState (Either ProblemParseError) a
modifyProblem :: (Problem String String -> Problem String String) -> WSTParser s ()
modifyProblem = modifyState
parsedVariables :: WSTParser s [String]
parsedVariables = Prob.variables `liftM` getState
parse :: (Stream s (Either ProblemParseError) Char) => WSTParser s (Problem String String)
parse = spaces >> parseDecls >> eof >> getState where
parseDecls = many1 parseDecl
parseDecl = decl "VAR" vars (\ e p -> p {Prob.variables = e `union` Prob.variables p})
<|> decl "THEORY" theory (\ e p -> p {Prob.theory = maybeAppend Prob.theory e p})
<|> decl "SIG" signature (\ e p -> p {Prob.signature = maybeAppend Prob.signature e p})
FIXME multiple RULES blocks ?
Prob.symbols = Rules.funsDL (Prob.allRules e) [] })
<|> decl "STRATEGY" strategy (\ e p -> p {Prob.strategy = e})
<|> decl "STARTTERM" startterms (\ e p -> p {Prob.startTerms = e})
<|> (decl "COMMENT" comment (\ e p -> p {Prob.comment = maybeAppend Prob.comment e p}) <?> "comment")
<|> (par comment >>= modifyProblem . (\ e p -> p {Prob.comment = maybeAppend Prob.comment e p}) <?> "comment")
decl name p f = try (par $ do
lex $ string name
r <- p
modifyProblem $ f r) <?> (name ++ " block")
maybeAppend fld e p = Just $ maybe [] id (fld p) ++ e
vars :: (Stream s (Either ProblemParseError) Char) => WSTParser s [String]
vars = do vs <- many (lex $ ident "()," [])
return vs
signature :: (Stream s (Either ProblemParseError) Char) => WSTParser s [(String,Int)]
signature = many fundecl
where
fundecl = par (do
f <- lex $ ident "()," []
ar <- lex (read <$> many1 digit)
return $ (f,ar))
theory :: (Stream s (Either ProblemParseError) Char) => WSTParser s [Prob.Theory String String]
theory = many thdecl where
thdecl = par ((equations >>= return . Prob.Equations)
<|> (idlist >>= \ (x:xs) -> return $ Prob.SymbolProperty x xs))
equations = try (do
vs <- parsedVariables
lex $ string "EQUATIONS"
many $ equation vs) <?> "EQUATIONS block"
equation vs = do
l <- Term.parseWST vs
lex $ string "=="
r <- Term.parseWST vs
return $ Rule l r
idlist = many1 $ (lex $ ident "()," [])
rules :: (Stream s (Either ProblemParseError) Char) => WSTParser s (Prob.RulesPair String String)
rules = do vs <- parsedVariables
rs <- many $ rule vs
let (s,w) = partition fst rs
return Prob.RulesPair { Prob.strictRules = map snd s ,
Prob.weakRules = map snd w }
where rule vs = do l <- Term.parseWST vs
sep <- lex $ (try $ string "->=") <|> string "->"
r <- Term.parseWST vs
return (sep == "->", Rule {lhs = l, rhs = r})
strategy :: (Stream s (Either ProblemParseError) Char) => WSTParser s Prob.Strategy
strategy = innermost <|> outermost where
innermost = string "INNERMOST" >> return Prob.Innermost
outermost = string "OUTERMOST" >> return Prob.Outermost
startterms :: (Stream s (Either ProblemParseError) Char) => WSTParser s Prob.StartTerms
startterms = basic <|> terms where
basic = string "CONSTRUCTOR-BASED" >> return Prob.BasicTerms
terms = string "FULL" >> return Prob.AllTerms
comment :: (Stream s (Either ProblemParseError) Char) => WSTParser s String
comment = withpars <|> liftM2 (++) idents comment <|> return ""
where idents = many1 (noneOf "()")
withpars = do _ <- char '('
pre <- comment
_ <- char ')'
suf <- comment
return $ "(" ++ pre ++ ")" ++ suf
| null | https://raw.githubusercontent.com/haskell-rewriting/term-rewriting/d01ee419f9fd3c2011d37b6417326a9373d5ee9c/src/Data/Rewriting/Problem/Parse.hs | haskell | This file is part of the 'term-rewriting' library. It is licensed
| under an MIT license . See the accompanying ' LICENSE ' file for details .
Authors : , Christian Sternagel
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
module Data.Rewriting.Problem.Parse (
parseIO,
parseFileIO,
fromString,
fromFile,
fromCharStream,
ProblemParseError (..)
) where
import Data.Rewriting.Utils.Parse (lex, par, ident)
import qualified Data.Rewriting.Problem.Type as Prob
import Data.Rewriting.Problem.Type (Problem)
import Data.Rewriting.Rule (Rule (..))
import qualified Data.Rewriting.Term as Term
import qualified Data.Rewriting.Rules as Rules
import Data.List (partition, union)
import Data.Maybe (isJust)
import Prelude hiding (lex, catch)
import Control.Exception (catch)
import Control.Monad.Error
import Control.Monad (liftM, liftM3)
import Text.Parsec hiding (parse)
import System.IO (readFile)
data ProblemParseError = UnknownParseError String
| UnsupportedStrategy String
| FileReadError IOError
| UnsupportedDeclaration String
| SomeParseError ParseError deriving (Show)
instance Error ProblemParseError where strMsg = UnknownParseError
parseFileIO :: FilePath -> IO (Problem String String)
parseFileIO file = do r <- fromFile file
case r of
Left err -> do { putStrLn "following error occured:"; print err; mzero }
Right t -> return t
parseIO :: String -> IO (Problem String String)
parseIO string = case fromString string of
Left err -> do { putStrLn "following error occured:"; print err; mzero }
Right t -> return t
fromFile :: FilePath -> IO (Either ProblemParseError (Problem String String))
fromFile file = fromFile' `catch` (return . Left . FileReadError) where
fromFile' = fromCharStream sn `liftM` readFile file
sn = "<file " ++ file ++ ">"
fromString :: String -> Either ProblemParseError (Problem String String)
fromString = fromCharStream "supplied string"
fromCharStream :: (Stream s (Either ProblemParseError) Char)
=> SourceName -> s -> Either ProblemParseError (Problem String String)
fromCharStream sourcename input =
case runParserT parse initialState sourcename input of
Right (Left e) -> Left $ SomeParseError e
Right (Right p) -> Right p
Left e -> Left e
where initialState = Prob.Problem { Prob.startTerms = Prob.AllTerms ,
Prob.strategy = Prob.Full ,
Prob.theory = Nothing ,
Prob.rules = Prob.RulesPair { Prob.strictRules = [],
Prob.weakRules = [] } ,
Prob.variables = [] ,
Prob.symbols = [] ,
Prob.signature = Nothing,
Prob.comment = Nothing }
type ParserState = Problem String String
type WSTParser s a = ParsecT s ParserState (Either ProblemParseError) a
modifyProblem :: (Problem String String -> Problem String String) -> WSTParser s ()
modifyProblem = modifyState
parsedVariables :: WSTParser s [String]
parsedVariables = Prob.variables `liftM` getState
parse :: (Stream s (Either ProblemParseError) Char) => WSTParser s (Problem String String)
parse = spaces >> parseDecls >> eof >> getState where
parseDecls = many1 parseDecl
parseDecl = decl "VAR" vars (\ e p -> p {Prob.variables = e `union` Prob.variables p})
<|> decl "THEORY" theory (\ e p -> p {Prob.theory = maybeAppend Prob.theory e p})
<|> decl "SIG" signature (\ e p -> p {Prob.signature = maybeAppend Prob.signature e p})
FIXME multiple RULES blocks ?
Prob.symbols = Rules.funsDL (Prob.allRules e) [] })
<|> decl "STRATEGY" strategy (\ e p -> p {Prob.strategy = e})
<|> decl "STARTTERM" startterms (\ e p -> p {Prob.startTerms = e})
<|> (decl "COMMENT" comment (\ e p -> p {Prob.comment = maybeAppend Prob.comment e p}) <?> "comment")
<|> (par comment >>= modifyProblem . (\ e p -> p {Prob.comment = maybeAppend Prob.comment e p}) <?> "comment")
decl name p f = try (par $ do
lex $ string name
r <- p
modifyProblem $ f r) <?> (name ++ " block")
maybeAppend fld e p = Just $ maybe [] id (fld p) ++ e
vars :: (Stream s (Either ProblemParseError) Char) => WSTParser s [String]
vars = do vs <- many (lex $ ident "()," [])
return vs
signature :: (Stream s (Either ProblemParseError) Char) => WSTParser s [(String,Int)]
signature = many fundecl
where
fundecl = par (do
f <- lex $ ident "()," []
ar <- lex (read <$> many1 digit)
return $ (f,ar))
theory :: (Stream s (Either ProblemParseError) Char) => WSTParser s [Prob.Theory String String]
theory = many thdecl where
thdecl = par ((equations >>= return . Prob.Equations)
<|> (idlist >>= \ (x:xs) -> return $ Prob.SymbolProperty x xs))
equations = try (do
vs <- parsedVariables
lex $ string "EQUATIONS"
many $ equation vs) <?> "EQUATIONS block"
equation vs = do
l <- Term.parseWST vs
lex $ string "=="
r <- Term.parseWST vs
return $ Rule l r
idlist = many1 $ (lex $ ident "()," [])
rules :: (Stream s (Either ProblemParseError) Char) => WSTParser s (Prob.RulesPair String String)
rules = do vs <- parsedVariables
rs <- many $ rule vs
let (s,w) = partition fst rs
return Prob.RulesPair { Prob.strictRules = map snd s ,
Prob.weakRules = map snd w }
where rule vs = do l <- Term.parseWST vs
sep <- lex $ (try $ string "->=") <|> string "->"
r <- Term.parseWST vs
return (sep == "->", Rule {lhs = l, rhs = r})
strategy :: (Stream s (Either ProblemParseError) Char) => WSTParser s Prob.Strategy
strategy = innermost <|> outermost where
innermost = string "INNERMOST" >> return Prob.Innermost
outermost = string "OUTERMOST" >> return Prob.Outermost
startterms :: (Stream s (Either ProblemParseError) Char) => WSTParser s Prob.StartTerms
startterms = basic <|> terms where
basic = string "CONSTRUCTOR-BASED" >> return Prob.BasicTerms
terms = string "FULL" >> return Prob.AllTerms
comment :: (Stream s (Either ProblemParseError) Char) => WSTParser s String
comment = withpars <|> liftM2 (++) idents comment <|> return ""
where idents = many1 (noneOf "()")
withpars = do _ <- char '('
pre <- comment
_ <- char ')'
suf <- comment
return $ "(" ++ pre ++ ")" ++ suf
|
4b4dcba05e7c05a73b56eb9bfda3fe1053db0ac1bc92b7bdb2498f355937372b | dktr0/Punctual | Tests.hs | {-# LANGUAGE OverloadedStrings #-}
import Test.Microspec
-- import Data.Set as Set
import Data.IntMap.Strict as IntMap
import Data.Time
import Sound.Punctual.Parser
import Sound.Punctual.Program
import Sound.Punctual.Action
import Sound.Punctual.Graph
import Sound.Punctual.Transition
import Sound.Punctual.DefTime
import Sound.Punctual.Duration
import Sound.Punctual.Output
main :: IO ()
main = do
now <- getCurrentTime
microspec $ do
describe "the parser parses empty programs from " $ do
let emptyPrograms = Right $ emptyProgram now
it "the empty string" $ parse now "" `shouldBe` emptyPrograms
it "just spaces" $ parse now " " `shouldBe` emptyPrograms
it "a mix of tabs, newlines, and spaces" $ parse now " \t\n \t\t\t\t\n \t" `shouldBe` emptyPrograms
it "a semi-colon" $ parse now ";" `shouldBe` emptyPrograms
it "two semi-colons" $ parse now ";;" `shouldBe` emptyPrograms
it "a one-line comment" $ parse now "-- this is a comment" `shouldBe` emptyPrograms
it "a one-line comment with a semicolon" $ parse now "-- this is a comment;" `shouldBe` emptyPrograms
it "a one-line comment with two actions separated by a semicolon" $ parse now "-- circle 0 0.25 >> rgb; vline 0 0.002 >> rgb" `shouldBe` emptyPrograms
it "just two one-line comments" $ parse now "-- comment\n--another comment" `shouldBe` emptyPrograms
it "just a multi-line comment" $ parse now "{- this is a\n comment-}" `shouldBe` emptyPrograms
it "just a multi-line comment with a semicolon" $ parse now "{- this is a;\n comment-}" `shouldBe` emptyPrograms
it "a non-output 0" $ parse now "0" `shouldBe` emptyPrograms
it "a non-output 0 and a one-line comment" $ parse now "0 -- comment" `shouldBe` emptyPrograms
it "a non-output 0 and a multi-line comment" $ parse now "0 {- comment\n-}" `shouldBe` emptyPrograms
describe "the parse parses simple programs, eg." $ do
let x = emptyProgram now
it "a simple sine wave to splay" $ parse now "sin 440 >> splay" `shouldBe` Right (x{ actions = IntMap.fromList [(0,Action {graph = Sin (Constant 440.0), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [Splay]})]})
it "a simple sine wave to splay, with a final semicolon" $ parse now "sin 440 >> splay;" `shouldBe` Right (x { actions = IntMap.fromList [(0,Action {graph = Sin (Constant 440.0), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [Splay]})]})
it "two sine waves to splay, with no final semicolon" $ parse now "sin 440 >> splay;\n sin 550 >> splay" `shouldBe` Right (x { actions = IntMap.fromList [(0,Action {graph = Sin (Constant 440.0), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [Splay]}),(1,Action {graph = Sin (Constant 550.0), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [Splay]})]})
it "two sine waves to splay, with a final semicolon" $ parse now "sin 440 >> splay;\n sin 550 >> splay;" `shouldBe` Right (x { actions = IntMap.fromList [(0,Action {graph = Sin (Constant 440.0), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [Splay]}),(1,Action {graph = Sin (Constant 550.0), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [Splay]})]})
it "two sine waves to splay, but the first commented out" $ parse now "-- sin 440 >> splay;\n sin 550 >> splay" `shouldBe` Right (x {actions = IntMap.fromList [(0,Action {graph = Sin (Constant 550.0), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [Splay]})]})
it "two sine waves to splay, the first commented out with a final semicolon" $ parse now "-- sin 440 >> splay;\n sin 550 >> splay;" `shouldBe` Right (x {actions = IntMap.fromList [(0,Action {graph = Sin (Constant 550.0), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [Splay]})]})
it "a simple circle, with no final semicolon" $ parse now "circle 0 0.25 >> rgb" `shouldBe` Right (x { actions = IntMap.fromList [(0,Action {graph = Circle (Constant 0.0) (Constant 0.25), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [RGB]})]})
it "a simple circle, with a final semicolon" $ parse now "circle 0 0.25 >> rgb;" `shouldBe` Right (x { actions = IntMap.fromList [(0,Action {graph = Circle (Constant 0.0) (Constant 0.25), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [RGB]})]})
it "a simple circle, with two final semicolons" $ parse now "circle 0 0.25 >> rgb;;" `shouldBe` Right (x { actions = IntMap.fromList [(0,Action {graph = Circle (Constant 0.0) (Constant 0.25), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [RGB]})]})
it "a circle, with a transition time" $ parse now "circle 0 0.25 >> rgb <> 5" `shouldBe` Right (x { actions = fromList [(0,Action {graph = Circle (Constant 0.0) (Constant 0.25), defTime = Quant 1.0 (Seconds 0.0), transition = CrossFade (Seconds 5.0), outputs = [RGB]})]})
it "a circle, with a transition time (and a semi-colon)" $ parse now "circle 0 0.25 >> rgb <> 5;" `shouldBe` Right (x { actions = fromList [(0,Action {graph = Circle (Constant 0.0) (Constant 0.25), defTime = Quant 1.0 (Seconds 0.0), transition = CrossFade (Seconds 5.0), outputs = [RGB]})]})
it "a circle, with a definition time" $ parse now "circle 0 0.25 >> rgb @@ 5" `shouldBe` Right (x { actions = fromList [(0,Action {graph = Circle (Constant 0.0) (Constant 0.25), defTime = After (Seconds 5.0), transition = DefaultCrossFade, outputs = [RGB]})]})
it "a circle, with a definition time (and a semi-colon)" $ parse now "circle 0 0.25 >> rgb @@ 5" `shouldBe` Right (x { actions = fromList [(0,Action {graph = Circle (Constant 0.0) (Constant 0.25), defTime = After (Seconds 5.0), transition = DefaultCrossFade, outputs = [RGB]})]})
it "zero assigned to a variable, routed to RGB output" $ parse now "t << 0; t >> rgb" `shouldBe` Right (x { actions = fromList [(0,Action {graph = Constant 0.0, defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [RGB]})]})
| null | https://raw.githubusercontent.com/dktr0/Punctual/300345fb919c2a300a50105fa3e7b2663244a5d7/tests/Tests.hs | haskell | # LANGUAGE OverloadedStrings #
import Data.Set as Set |
import Test.Microspec
import Data.IntMap.Strict as IntMap
import Data.Time
import Sound.Punctual.Parser
import Sound.Punctual.Program
import Sound.Punctual.Action
import Sound.Punctual.Graph
import Sound.Punctual.Transition
import Sound.Punctual.DefTime
import Sound.Punctual.Duration
import Sound.Punctual.Output
main :: IO ()
main = do
now <- getCurrentTime
microspec $ do
describe "the parser parses empty programs from " $ do
let emptyPrograms = Right $ emptyProgram now
it "the empty string" $ parse now "" `shouldBe` emptyPrograms
it "just spaces" $ parse now " " `shouldBe` emptyPrograms
it "a mix of tabs, newlines, and spaces" $ parse now " \t\n \t\t\t\t\n \t" `shouldBe` emptyPrograms
it "a semi-colon" $ parse now ";" `shouldBe` emptyPrograms
it "two semi-colons" $ parse now ";;" `shouldBe` emptyPrograms
it "a one-line comment" $ parse now "-- this is a comment" `shouldBe` emptyPrograms
it "a one-line comment with a semicolon" $ parse now "-- this is a comment;" `shouldBe` emptyPrograms
it "a one-line comment with two actions separated by a semicolon" $ parse now "-- circle 0 0.25 >> rgb; vline 0 0.002 >> rgb" `shouldBe` emptyPrograms
it "just two one-line comments" $ parse now "-- comment\n--another comment" `shouldBe` emptyPrograms
it "just a multi-line comment" $ parse now "{- this is a\n comment-}" `shouldBe` emptyPrograms
it "just a multi-line comment with a semicolon" $ parse now "{- this is a;\n comment-}" `shouldBe` emptyPrograms
it "a non-output 0" $ parse now "0" `shouldBe` emptyPrograms
it "a non-output 0 and a one-line comment" $ parse now "0 -- comment" `shouldBe` emptyPrograms
it "a non-output 0 and a multi-line comment" $ parse now "0 {- comment\n-}" `shouldBe` emptyPrograms
describe "the parse parses simple programs, eg." $ do
let x = emptyProgram now
it "a simple sine wave to splay" $ parse now "sin 440 >> splay" `shouldBe` Right (x{ actions = IntMap.fromList [(0,Action {graph = Sin (Constant 440.0), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [Splay]})]})
it "a simple sine wave to splay, with a final semicolon" $ parse now "sin 440 >> splay;" `shouldBe` Right (x { actions = IntMap.fromList [(0,Action {graph = Sin (Constant 440.0), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [Splay]})]})
it "two sine waves to splay, with no final semicolon" $ parse now "sin 440 >> splay;\n sin 550 >> splay" `shouldBe` Right (x { actions = IntMap.fromList [(0,Action {graph = Sin (Constant 440.0), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [Splay]}),(1,Action {graph = Sin (Constant 550.0), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [Splay]})]})
it "two sine waves to splay, with a final semicolon" $ parse now "sin 440 >> splay;\n sin 550 >> splay;" `shouldBe` Right (x { actions = IntMap.fromList [(0,Action {graph = Sin (Constant 440.0), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [Splay]}),(1,Action {graph = Sin (Constant 550.0), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [Splay]})]})
it "two sine waves to splay, but the first commented out" $ parse now "-- sin 440 >> splay;\n sin 550 >> splay" `shouldBe` Right (x {actions = IntMap.fromList [(0,Action {graph = Sin (Constant 550.0), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [Splay]})]})
it "two sine waves to splay, the first commented out with a final semicolon" $ parse now "-- sin 440 >> splay;\n sin 550 >> splay;" `shouldBe` Right (x {actions = IntMap.fromList [(0,Action {graph = Sin (Constant 550.0), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [Splay]})]})
it "a simple circle, with no final semicolon" $ parse now "circle 0 0.25 >> rgb" `shouldBe` Right (x { actions = IntMap.fromList [(0,Action {graph = Circle (Constant 0.0) (Constant 0.25), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [RGB]})]})
it "a simple circle, with a final semicolon" $ parse now "circle 0 0.25 >> rgb;" `shouldBe` Right (x { actions = IntMap.fromList [(0,Action {graph = Circle (Constant 0.0) (Constant 0.25), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [RGB]})]})
it "a simple circle, with two final semicolons" $ parse now "circle 0 0.25 >> rgb;;" `shouldBe` Right (x { actions = IntMap.fromList [(0,Action {graph = Circle (Constant 0.0) (Constant 0.25), defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [RGB]})]})
it "a circle, with a transition time" $ parse now "circle 0 0.25 >> rgb <> 5" `shouldBe` Right (x { actions = fromList [(0,Action {graph = Circle (Constant 0.0) (Constant 0.25), defTime = Quant 1.0 (Seconds 0.0), transition = CrossFade (Seconds 5.0), outputs = [RGB]})]})
it "a circle, with a transition time (and a semi-colon)" $ parse now "circle 0 0.25 >> rgb <> 5;" `shouldBe` Right (x { actions = fromList [(0,Action {graph = Circle (Constant 0.0) (Constant 0.25), defTime = Quant 1.0 (Seconds 0.0), transition = CrossFade (Seconds 5.0), outputs = [RGB]})]})
it "a circle, with a definition time" $ parse now "circle 0 0.25 >> rgb @@ 5" `shouldBe` Right (x { actions = fromList [(0,Action {graph = Circle (Constant 0.0) (Constant 0.25), defTime = After (Seconds 5.0), transition = DefaultCrossFade, outputs = [RGB]})]})
it "a circle, with a definition time (and a semi-colon)" $ parse now "circle 0 0.25 >> rgb @@ 5" `shouldBe` Right (x { actions = fromList [(0,Action {graph = Circle (Constant 0.0) (Constant 0.25), defTime = After (Seconds 5.0), transition = DefaultCrossFade, outputs = [RGB]})]})
it "zero assigned to a variable, routed to RGB output" $ parse now "t << 0; t >> rgb" `shouldBe` Right (x { actions = fromList [(0,Action {graph = Constant 0.0, defTime = Quant 1.0 (Seconds 0.0), transition = DefaultCrossFade, outputs = [RGB]})]})
|
66c7624c5038d12db46d98b76005e794fceab6146ad5c01d2c91e32c28fe420a | s-expressionists/Eclector | macro-functions.lisp | (cl:in-package #:eclector.reader)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Macro WITH-FORBIDDEN-QUASIQUOTATION.
;;;
;;; This macro controls whether quasiquote and/or unquote should be
;;; allowed in a given context.
(defmacro with-forbidden-quasiquotation
((context &optional (quasiquote-forbidden-p t)
(unquote-forbidden-p t))
&body body)
(alexandria:with-unique-names (context*)
(let ((context-used-p nil))
(flet ((make-binding (variable value-form)
(cond ((constantp value-form)
(case (eval value-form)
(:keep
'())
((nil)
`((,variable nil)))
(t
(setf context-used-p t)
`((,variable ,context*)))))
(t
(setf context-used-p t)
`((,variable (case ,value-form
(:keep ,variable)
((nil) nil)
(t ,context*))))))))
`(let* ((,context* ,context)
,@(make-binding '*quasiquote-forbidden* quasiquote-forbidden-p)
,@(make-binding '*unquote-forbidden* unquote-forbidden-p))
,@(unless context-used-p
`((declare (ignore ,context*))))
,@body)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macro for semicolon.
;;;
;;; We read characters until end-of-file or until we have read a
;;; newline character. Since reading a comment does not generate an
;;; object, the semicolon reader must indicate that fact by returning
zero values .
(defun semicolon (stream char)
(declare (ignore char))
(loop with state = :semicolon
for char = (read-char stream nil nil t)
until (or (null char) (eql char #\Newline))
if (and (eq state :semicolon) (char= char #\;))
count 1 into semicolons
else
do (setf state nil)
finally (setf *skip-reason* (cons :line-comment (1+ semicolons))))
(values))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macro for single quote.
;;;
They HyperSpec says that the reader signals an error if
;;; end-of-file is encountered before an object has been entirely
;;; parsed, independently of whether EOF-ERROR-P is true or not. For
;;; that reason, we call the reader recursively with the value of
;;; EOF-ERROR-P being T.
(defun single-quote (stream char)
(declare (ignore char))
(let ((material (handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-quote
:stream-position (stream-position condition)
:report 'inject-nil)
nil)
(end-of-list (condition)
(%recoverable-reader-error
stream 'object-must-follow-quote
:position-offset -1 :report 'inject-nil)
(unread-char (%character condition) stream)
nil))))
(wrap-in-quote *client* material)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macro for double quote.
;;;
;;; We identify a single escape character by its syntax type, so that
;;; if a user wants a different escape chacacter, we can handle that.
;;;
Furthermore , They HyperSpec says that the reader signals an error
;;; if end-of-file is encountered before an object has been entirely
;;; parsed, independently of whether EOF-ERROR-P is true or not. For
;;; that reason, we call READ-CHAR with the value of EOF-ERROR-P being
;;; T.
;;;
;;; We accumulate characters in an adjustable vector. However, the
HyperSpec says that we must return a SIMPLE - STRING . For that
reason , we call COPY - SEQ in the end . COPY - SEQ is guaranteed to
;;; return a simple vector.
(defun double-quote (stream char)
(let ((result (make-array 100 :element-type 'character
:adjustable t
:fill-pointer 0)))
(loop with readtable = *readtable*
for char2 = (read-char-or-recoverable-error
stream char 'unterminated-string
:delimiter char :report 'use-partial-string)
until (eql char2 char)
when (eq (eclector.readtable:syntax-type readtable char2) :single-escape)
do (setf char2 (read-char-or-recoverable-error
stream nil 'unterminated-single-escape-in-string
:position-offset -1
:escape-char char2 :report 'use-partial-string))
when char2
do (vector-push-extend char2 result)
finally (return (copy-seq result)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macros for backquote and comma.
;;;
;;;
The control structure we use for backquote requires some
;;; explanation.
;;;
The HyperSpec says ( see section 2.4.6 ) that backquote and comma
;;; are allowed only inside lists and vectors. Since READ can be
;;; called recursively from other functions as well (such as the
;;; reader for arrays, or user-defined readers), we somehow need to
;;; track whether backquote and comma are allowed in the current
;;; context.
;;;
;;; We could (and previously did) forbid backquote and comma except
;;; inside lists and vectors, but in practice, clients expect control
;;; over this behavior in order to implement reader macros such as
;;;
# L`(,!1 , ! 1 ) = > ( lambda ( g1 ) ` ( , g1 , g1 ) )
;;; `#{,key ,value} => (let ((g1 (make-hash-table ...))) ...)
;;;
We use the flags * * and
;;; *UNQUOTE-FORBIDDEN-P* to control whether backquote and comma are
;;; allowed. Initially, both variables are bound to T, allowing
backquote and comma ( * QUASIQUOTE - DEPTH * ensures that backquote and
;;; comma are nested properly). Reader macros such as #C, #A,
;;; etc. bind the variables to a true value that also indicates the
;;; context (usually the symbol naming the reader macro function).
;;; The only way these variables can be re-bound to NIL (in the
standard readtable ) is the - DOT reader macro .
;;;
;;;
;;; Representation of quasiquoted forms
;;;
The HyperSpec explicitly encourages us ( see section 2.4.6.1 ) to
follow the example of Scheme for representing backquote
;;; expression. We see no reason for choosing a different
representation , so we use ( QUASIQUOTE < form > ) , ( UNQUOTE < form > ) ,
;;; and (UNQUOTE-SPLICING <form>). Then we define QUASIQUOTE as a
macro that expands to a CL form that will build the final data
;;; structure.
(defun backquote (stream char)
(declare (ignore char))
(alexandria:when-let ((context *quasiquote-forbidden*))
(unless *read-suppress*
(%recoverable-reader-error
stream 'backquote-in-invalid-context
:position-offset -1 :context context :report 'ignore-quasiquote)
(return-from backquote
(let ((*backquote-depth* 0))
(read stream t nil t)))))
(let ((material (let ((*backquote-depth* (1+ *backquote-depth*))
(*unquote-forbidden* nil))
(handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-backquote
:stream-position (stream-position condition)
:report 'inject-nil)
nil)
(end-of-list (condition)
(%recoverable-reader-error
stream 'object-must-follow-backquote
:position-offset -1 :report 'inject-nil)
(unread-char (%character condition) stream)
nil)))))
(wrap-in-quasiquote *client* material)))
(defun comma (stream char)
(declare (ignore char))
(let* ((depth *backquote-depth*)
(char2 (read-char stream nil nil t))
(splicing-p (case char2
((#\@ #\.) t)
((nil) nil) ; end-of-input, but we may recover
(t (unread-char char2 stream)))))
(flet ((read-material ()
(handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-unquote
:stream-position (stream-position condition)
:splicing-p splicing-p :report 'inject-nil)
nil)
(end-of-list (condition)
(%recoverable-reader-error
stream 'object-must-follow-unquote
:position-offset -1
:splicing-p splicing-p :report 'inject-nil)
(unread-char (%character condition) stream)
nil))))
(unless (plusp depth)
(%recoverable-reader-error
stream 'unquote-not-inside-backquote
:position-offset (if splicing-p -2 -1)
:splicing-p splicing-p :report 'ignore-unquote)
(return-from comma (read-material)))
(alexandria:when-let ((context *unquote-forbidden*))
(unless *read-suppress*
(%recoverable-reader-error
stream 'unquote-in-invalid-context
:position-offset (if splicing-p -2 -1)
:splicing-p splicing-p :context context :report 'ignore-unquote)
(return-from comma (read-material))))
(let* ((*backquote-depth* (1- depth))
(form (read-material)))
(if splicing-p
(wrap-in-unquote-splicing *client* form)
(wrap-in-unquote *client* form))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macros for left-parenthesis and right-parenthesis.
;;;
The HyperSpec says that right - parenthesis is a macro character .
;;; In the reader macro for left-parenthesis, we can not just read
;;; until we find a right parenthesis, because it is possible that
;;; some other character has been assigned the same meaning, and we
;;; need to handle that situation too.
;;;
Another problem we need to solve is that of the CONSING - DOT . The
HyperSpec says that it is a token . For that reason , we can not
;;; just read characters and look for a single period, because it is
;;; possible that the single dot has a different syntax type in this
;;; particular readtable. Furthermore, we must handle error
situations such as an attempt to use more than one dot in a list ,
or having zero or strictly more than one expression following a
;;; dot.
;;;
;;; We solve these problems as follows: the reader macro for a right
parenthesis calls SIGNAL with a particular condition ( of type
;;; END-OF-LIST). In situations where the right parenthesis is
;;; allowed, there will be a handler for this condition type.
Therefore , in that situation , the call to SIGNAL will not return .
If the call to SIGNAL returns , we signal and ERROR , because then
;;; the right parenthesis was read in a context where it is not
;;; allowed.
;;;
The reader macro for left parenthesis manages two local variables ,
;;; REVERSED-RESULT and TAIL. The variable REVERSED-RESULT is used to
;;; accumulate elements of the list (preceding a possible consing dot)
;;; being read, in reverse order. A handler for END-OF-LIST is
;;; established around the recursive calls to READ inside the reader
macro function . When this handler is invoked , it calls NRECONC to
;;; reverse the value of REVERSED-RESULT and attach the value of TAIL
to the end . Normally , the value of TAIL is NIL , so the handler
;;; will create and return a proper list containing the accumulated
;;; elements.
;;;
We use a special variable name * CONSING - DOT - ALLOWED - P * to
;;; determine the contexts in which a consing dot is allowed.
;;; Whenever the token parser detects a consing dot, it examines this
variable , and if it is true it returns the unique CONSING - DOT
;;; token, and if it is false, signals an error. Initially, this
;;; variable has the value FALSE. Whenever the reader macro for left
;;; parenthesis is called, it binds this variable to TRUE. When a
;;; recursive call to READ returns with the consing dot as a value,
the reader macro for left parenthesis does three things . First it
SETS ( as opposed to BINDS ) * CONSING - DOT - ALLOWED - P * to FALSE , so
that if a second consing dot should occur , then the token reader
signals an error . Second , it establishes a nested handler for
;;; END-OF-LIST, so that if a right parenthesis should occur
;;; immediately after the consing dot, then an error is signaled.
;;; With this handler established, READ is called. If it returns
;;; normally, then the return value becomes the value of the variable
;;; TAIL. Third, it calls READ again without any nested handler
;;; established. This call had better result in a right parenthesis,
;;; so that END-OF-LIST is signaled, which is caught by the outermost
;;; handler and the correct list is built and returned. If this call
;;; should return normally, we have a problem, because this means that
there was a second subform after the consing dot in the list , so
;;; we signal an ERROR.
(defun left-parenthesis (stream char)
(declare (ignore char))
(%read-delimited-list stream #\)))
(defun right-parenthesis (stream char)
If the call to SIGNAL returns , then there is no handler for this
;; condition, which means that the right parenthesis was found in a
;; context where it is not allowed.
(signal-end-of-list char)
(%recoverable-reader-error
stream 'invalid-context-for-right-parenthesis
:position-offset -1
:found-character char :report 'ignore-trailing-right-paren))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macro for sharpsign single quote.
(defun %sharpsign-single-quote (stream char parameter allow-unquote)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-single-quote parameter))
(let ((name (with-forbidden-quasiquotation
('sharpsign-single-quote :keep (if allow-unquote :keep t))
(handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-sharpsign-single-quote
:stream-position (stream-position condition)
:report 'inject-nil)
nil)
(end-of-list (condition)
(%recoverable-reader-error
stream 'object-must-follow-sharpsign-single-quote
:position-offset -1 :report 'inject-nil)
(unread-char (%character condition) stream)
nil)))))
(cond (*read-suppress*
nil)
((null name)
nil)
(t
(wrap-in-function *client* name)))))
This variation of - SINGLE - QUOTE allows unquote within # ' ,
;;; that is `#',(foo) is read as
;;;
;;; (quasiquote (function (unquote (foo))))
;;;
;;; . It is not clear that this behavior is supported by the
;;; specification, but it is widely relied upon and thus the default
;;; behavior.
(defun sharpsign-single-quote (stream char parameter)
(%sharpsign-single-quote stream char parameter t))
This variation of - SINGLE - QUOTE does not allow unquote
;;; within #'.
(defun strict-sharpsign-single-quote (stream char parameter)
(%sharpsign-single-quote stream char parameter nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macro for sharpsign left parenthesis.
(defun sharpsign-left-parenthesis (stream char parameter)
(declare (ignore char))
(flet ((next-element ()
(handler-case
(values (read stream t nil t) t)
(end-of-list ()
(values nil nil))
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'unterminated-vector
:stream-position (stream-position condition)
:delimiter #\) :report 'use-partial-vector)
(values nil nil)))))
(cond (*read-suppress*
(loop for elementp = (nth-value 1 (next-element))
while elementp))
((null parameter)
(loop with result = (make-array 10 :adjustable t :fill-pointer 0)
for (element elementp) = (multiple-value-list (next-element))
while elementp
do (vector-push-extend element result)
finally (return (coerce result 'simple-vector))))
(t
(loop with result = (make-array parameter)
with excess-position = nil
for index from 0
for (element elementp) = (multiple-value-list
(next-element))
while elementp
if (< index parameter)
do (setf (aref result index) element)
else
do (setf excess-position (eclector.base:source-position
*client* stream))
finally (cond ((and (zerop index) (plusp parameter))
(%recoverable-reader-error
stream 'no-elements-found
:position-offset -1
:array-type 'vector :expected-number parameter
:report 'use-empty-vector)
(setf result (make-array 0)
index parameter))
((> index parameter)
(%recoverable-reader-error
stream 'too-many-elements
:stream-position excess-position ; inaccurate
:position-offset -1
:array-type 'vector
:expected-number parameter
:number-found index
:report 'ignore-excess-elements)))
(return
(if (< index parameter)
(fill result (aref result (1- index))
:start index)
result)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macro for sharpsign dot.
(defun sharpsign-dot (stream char parameter)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-dot parameter))
(cond ((not *read-eval*)
(%reader-error stream 'read-time-evaluation-inhibited))
(*read-suppress*
(read stream t nil t))
(t
(let ((expression (with-forbidden-quasiquotation (nil nil nil)
(let ((*list-reader* nil))
(handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-sharpsign-dot
:stream-position (stream-position condition)
:report 'inject-nil)
nil)
(end-of-list (condition)
(%recoverable-reader-error
stream 'object-must-follow-sharpsign-dot
:position-offset -1 :report 'inject-nil)
(unread-char (%character condition) stream)
nil))))))
(handler-case
(evaluate-expression *client* expression)
(error (condition)
(%recoverable-reader-error
stream 'read-time-evaluation-error
:expression expression :original-condition condition
:report 'inject-nil)
nil))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macro for sharpsign backslash.
Mandatory character names according to 13.1.7 Character Names .
(defparameter *character-names*
(alexandria:alist-hash-table '(("NEWLINE" . #.(code-char 10))
("SPACE" . #.(code-char 32))
("RUBOUT" . #.(code-char 127))
("PAGE" . #.(code-char 12))
("TAB" . #.(code-char 9))
("BACKSPACE" . #.(code-char 8))
("RETURN" . #.(code-char 13))
("LINEFEED" . #.(code-char 10)))
:test 'equalp))
(defun find-standard-character (name)
(gethash name *character-names*))
(defun sharpsign-backslash (stream char parameter)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-backslash parameter))
(let ((char1 (read-char-or-recoverable-error
stream nil 'end-of-input-after-backslash
:report '(use-replacement-character #1=#\?))))
(when (null char1) ; can happen when recovering
(return-from sharpsign-backslash #1#))
(with-token-info (push-char () finalize :lazy t)
(labels ((handle-char (char escapep)
(declare (ignore escapep))
(when (not (null char1))
(push-char char1)
(setf char1 nil))
(push-char char))
(unterminated-single-escape (escape-char)
(%recoverable-reader-error
stream 'unterminated-single-escape-in-character-name
:escape-char escape-char :report 'use-partial-character-name))
(unterminated-multiple-escape (delimiter)
(%recoverable-reader-error
stream 'unterminated-multiple-escape-in-character-name
:delimiter delimiter :report 'use-partial-character-name))
(lookup (name)
(let ((character (find-character *client* name)))
(cond ((null character)
(%recoverable-reader-error
stream 'unknown-character-name
:position-offset (- (if (characterp name)
1
(length name)))
:name name
:report '(use-replacement-character #2=#\?))
#2#)
(t
character))))
(terminate-character ()
(return-from sharpsign-backslash
(cond (*read-suppress* nil)
((not (null char1)) ; no additional characters pushed (same as (null token))
(lookup char1))
(t
(lookup (finalize)))))))
(token-state-machine
stream *readtable* handle-char nil nil
unterminated-single-escape unterminated-multiple-escape
terminate-character)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macro for sharpsign B, X, O and R.
(defun read-rational (stream base)
(let ((readtable *readtable*)
(read-suppress *read-suppress*))
(labels ((next-char (eof-error-p)
(let ((char (read-char stream nil nil t)))
(cond ((not (null char))
(values char (eclector.readtable:syntax-type
readtable char)))
((and eof-error-p (not read-suppress))
(%recoverable-reader-error
stream 'end-of-input-before-digit
:base base :report 'replace-invalid-digit)
(values #\1 :constituent))
(t
(values nil nil)))))
(digit-expected (char type recover-value)
(%recoverable-reader-error
stream 'digit-expected
:position-offset -1
:character-found char :base base
:report 'replace-invalid-digit)
(unless (eq type :constituent)
(unread-char char stream))
recover-value)
(ensure-digit (char type)
(let ((value (digit-char-p char base)))
(if (null value)
(digit-expected char type 1)
value)))
(maybe-sign ()
(multiple-value-bind (char type) (next-char t)
(cond (read-suppress
(values 1 0))
((not (eq type :constituent))
(digit-expected char type nil))
((char= char #\-)
(values -1 0))
(t
(values 1 (ensure-digit char type))))))
(integer (empty-allowed /-allowed initial-value)
(let ((value initial-value))
(tagbody
(when empty-allowed (go rest)) ; also when READ-SUPPRESS
(multiple-value-bind (char type) (next-char t)
(case type
(:constituent
(setf value (ensure-digit char type)))
(t
(digit-expected char type nil)
(return-from integer value))))
rest
(multiple-value-bind (char type) (next-char nil)
(ecase type
((nil)
(return-from integer value))
(:whitespace
(unread-char char stream)
(return-from integer value))
(:terminating-macro
(unread-char char stream)
(return-from integer value))
((:non-terminating-macro
:single-escape :multiple-escape)
(cond (read-suppress
(go rest))
(t
(digit-expected char type nil)
(return-from integer value))))
(:constituent
(cond (read-suppress
(go rest))
((and /-allowed (eql char #\/))
(return-from integer (values value t)))
(t
(setf value (+ (* base (or value 0))
(ensure-digit char type)))
(go rest)))))))))
(read-denominator ()
(let ((value (integer nil nil nil)))
(cond ((eql value 0)
(%recoverable-reader-error
stream 'zero-denominator
:position-offset -1 :report 'replace-invalid-digit)
nil)
(t
value)))))
(multiple-value-bind (sign numerator) (maybe-sign)
(if (null sign)
0
(multiple-value-bind (numerator slashp)
(integer (= sign 1) t numerator)
(unless read-suppress ; When READ-SUPPRESS, / has been consumed
(let ((denominator (when slashp (read-denominator))))
(* sign (if denominator
(/ numerator denominator)
numerator))))))))))
(defun sharpsign-b (stream char parameter)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-b parameter))
(read-rational stream 2.))
(defun sharpsign-x (stream char parameter)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-x parameter))
(read-rational stream 16.))
(defun sharpsign-o (stream char parameter)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-o parameter))
(read-rational stream 8.))
(defun sharpsign-r (stream char parameter)
(declare (ignore char))
(let ((radix (cond ((not parameter)
(numeric-parameter-not-supplied stream 'sharpsign-r)
36)
((not (<= 2 parameter 36))
(unless *read-suppress*
(%recoverable-reader-error
stream 'invalid-radix
:position-offset (- (+ (parameter-length parameter) 1))
:radix parameter :report 'use-replacement-radix))
36)
(t
parameter))))
(read-rational stream radix)))
(defun sharpsign-asterisk (stream char parameter)
(declare (ignore char))
(let ((read-suppress *read-suppress*)
(readtable *readtable*))
(flet ((next-bit ()
(let ((char (read-char stream nil nil t)))
(multiple-value-bind (syntax-type value)
(unless (null char)
(values (eclector.readtable:syntax-type
readtable char)
(digit-char-p char 2)))
(when (eq syntax-type :terminating-macro)
(unread-char char stream))
(cond ((member syntax-type '(nil :whitespace :terminating-macro))
nil)
(read-suppress
t)
((null value)
(%recoverable-reader-error
stream 'digit-expected
:position-offset -1
:character-found char :base 2.
:report 'replace-invalid-digit)
0)
(t
value))))))
(cond (read-suppress
(loop for value = (next-bit) while value))
((null parameter)
(loop with bits = (make-array 10 :element-type 'bit
:adjustable t :fill-pointer 0)
for value = (next-bit)
while value
do (vector-push-extend value bits)
finally (return (coerce bits 'simple-bit-vector))))
(t
(loop with result = (make-array parameter :element-type 'bit)
for index from 0
for value = (next-bit)
while value
when (< index parameter)
do (setf (sbit result index) value)
finally (cond ((and (zerop index) (plusp parameter))
(%recoverable-reader-error
stream 'no-elements-found
:array-type 'bit-vector
:expected-number parameter
:report 'use-empty-vector)
(setf result (make-array 0 :element-type 'bit)
index parameter))
((> index parameter)
(%recoverable-reader-error
stream 'too-many-elements
:position-offset (- (- index parameter))
:array-type 'bit-vector
:expected-number parameter
:number-found index
:report 'ignore-excess-elements)))
(return
(if (< index parameter)
(fill result (sbit result (1- index))
:start index)
result))))))))
(defun sharpsign-vertical-bar (stream sub-char parameter)
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-vertical-bar parameter))
(handler-case
(loop for char = (read-char stream t nil t)
do (cond ((eql char #\#)
(let ((char2 (read-char stream t nil t)))
(if (eql char2 sub-char)
(sharpsign-vertical-bar stream sub-char nil)
(unread-char char2 stream))))
((eql char sub-char)
(let ((char2 (read-char stream t nil t)))
(if (eql char2 #\#)
(progn
(setf *skip-reason* :block-comment)
(return-from sharpsign-vertical-bar (values)))
(unread-char char2 stream))))
(t
nil)))
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'unterminated-block-comment
:stream-position (stream-position condition)
:delimiter sub-char :report 'ignore-missing-delimiter))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macro for sharpsign A.
(labels ((check-sequence (stream object)
(when (not (typep object 'alexandria:proper-sequence))
(%recoverable-reader-error
stream 'read-object-type-error
:position-offset -1 ; inaccurate
:expected-type 'sequence :datum object
:report 'use-empty-array)
(invoke-restart '%make-empty))
nil)
(make-empty-dimensions (rank)
(make-list rank :initial-element 0))
(determine-dimensions (stream rank initial-contents)
(labels ((rec (rank initial-contents)
(cond ((zerop rank)
'())
((check-sequence stream initial-contents))
(t
(let ((length (length initial-contents)))
(if (zerop length)
(make-empty-dimensions rank)
(list* length
(rec (1- rank)
(elt initial-contents 0)))))))))
(rec rank initial-contents)))
(check-dimensions (stream dimensions initial-contents)
(labels ((rec (first rest axis initial-contents)
(cond ((not first))
((check-sequence stream initial-contents))
((not (eql (length initial-contents) (or first 0)))
(%recoverable-reader-error
stream 'incorrect-initialization-length
:array-type 'array :axis axis
:expected-length first :datum initial-contents
:report 'use-empty-array)
(invoke-restart '%make-empty))
(t
(every (lambda (subseq)
(rec (first rest) (rest rest)
(1+ axis) subseq))
initial-contents)))))
(rec (first dimensions) (rest dimensions) 0 initial-contents)))
(read-init (stream)
(with-forbidden-quasiquotation ('sharpsign-a :keep)
(handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-sharpsign-a
:stream-position (stream-position condition)
:report 'use-empty-array)
(invoke-restart '%make-empty))
(end-of-list (condition)
(%recoverable-reader-error
stream 'object-must-follow-sharpsign-a
:position-offset -1 :report 'use-empty-array)
(unread-char (%character condition) stream)
(invoke-restart '%make-empty))))))
(defun sharpsign-a (stream char parameter)
(declare (ignore char))
(when *read-suppress*
(return-from sharpsign-a (read stream t nil t)))
(let ((rank (cond ((null parameter)
(numeric-parameter-not-supplied stream 'sharpsign-a)
0)
(t
parameter))))
(multiple-value-bind (dimensions init)
(restart-case
(let* ((init (read-init stream))
(dimensions (determine-dimensions
stream rank init)))
(check-dimensions stream dimensions init)
(values dimensions init))
(%make-empty ()
(values (make-empty-dimensions rank) '())))
(make-array dimensions :initial-contents init)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macro for sharpsign colon.
(defun symbol-from-token (stream token token-escapes package-marker)
(when *read-suppress*
(return-from symbol-from-token nil))
(when package-marker
(%recoverable-reader-error
stream 'uninterned-symbol-must-not-contain-package-marker
:stream-position package-marker :position-offset -1
:token token :report 'treat-as-escaped))
(convert-according-to-readtable-case token token-escapes)
(interpret-symbol *client* stream nil (copy-seq token) nil))
(defun sharpsign-colon (stream char parameter)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-colon parameter))
(with-token-info (push-char (start-escape end-escape) finalize)
(let ((package-marker nil))
(labels ((handle-char (char escapep)
(when (and (not escapep)
(char= char #\:)
(not package-marker))
(setf package-marker (eclector.base:source-position
*client* stream)))
(push-char char))
(unterminated-single-escape (escape-char)
(%recoverable-reader-error
stream 'unterminated-single-escape-in-symbol
:escape-char escape-char :report 'use-partial-symbol))
(unterminated-multiple-escape (delimiter)
(%recoverable-reader-error
stream 'unterminated-multiple-escape-in-symbol
:delimiter delimiter :report 'use-partial-symbol))
(return-symbol ()
(return-from sharpsign-colon
(multiple-value-bind (token escape-ranges) (finalize)
(symbol-from-token stream token escape-ranges package-marker)))))
(token-state-machine
stream *readtable* handle-char start-escape end-escape
unterminated-single-escape unterminated-multiple-escape
return-symbol)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macro for sharpsign C.
(defun %sharpsign-c (stream char parameter allow-non-list)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-c parameter))
(when *read-suppress*
(read stream t nil t)
(return-from %sharpsign-c nil))
;; When we get here, we have to read a list of the form
;; (REAL-PART-REAL-NUMBER-LITERAL IMAGINARY-PART-REAL-NUMBER) that
is , a list of exactly two elements of type REAL .
;;
;; We call %READ-LIST-ELEMENTS which calls the local function PART
;; for each list element as well as the events such as the end of
;; the list or the end of input. The variable PART keeps track of
;; the currently expected part which can be :REAL, :IMAGINARY, :END
;; or :PAST-END (the latter only comes into play when reading more
than two list elements due to error recovery ) .
(let ((listp nil)
(part :real)
(real 1) (imaginary 1))
(labels ((check-value (value)
(typecase value
((eql #1=#.(gensym "END-OF-LIST"))
(%recoverable-reader-error
stream 'complex-part-expected
:position-offset -1
:which part :report 'use-partial-complex)
1)
((eql #2=#.(gensym "END-OF-INPUT"))
(%recoverable-reader-error
stream 'end-of-input-before-complex-part
:which part :report 'use-partial-complex)
1)
(real
value)
(t
(%recoverable-reader-error stream 'read-object-type-error
:datum value :expected-type 'real
:report 'use-replacement-part)
1)))
(part (kind value)
(declare (ignore kind))
(case part
(:real
(setf real (check-value value)
part :imaginary)
t)
(:imaginary
(setf imaginary (check-value value)
part :end)
t)
((:end :past-end)
(case value
(#1# t)
(#2# nil)
(t
(when (eq part :end)
(%recoverable-reader-error
stream 'too-many-complex-parts
:position-offset -1
:report 'ignore-excess-parts)
(setf part :past-end))
t)))))
(read-parts (stream char)
;; If this is called, the input started with "#C(" (or,
;; generally, "#C" followed by any input resulting in a
;; LEFT-PARENTHESIS call). We record that fact (for
error reporting ) by setting LISTP . We reset
;; *LIST-READER* so lists appearing in the complex
;; parts are processed normally instead of with
;; READ-PARTS.
(setf listp t)
(let ((*list-reader* nil))
(%read-list-elements stream #'part '#1# '#2# char nil))
nil)) ; unused, but must not return (values)
(handler-case
;; Depending on ALLOW-NON-LIST, we call either READ or
;; %READ-MAYBE-NOTHING. Calling %READ-MAYBE-NOTHING will:
;; - not skip whitespace or comments (the spec is not clear
;; about whether #C<skippable things>(...) is valid syntax)
;; - invoke reader macros, in particular LEFT-PARENTHESIS to
;; initiate reading a list
;; - not behave like a full READ call in terms of e.g. parse
result construction so ( 1 2 ) will not appear as a list
result with two atom result children .
;; We bind *LIST-READER* to use READ-PARTS for reading lists.
(with-forbidden-quasiquotation ('sharpsign-c)
(let ((*list-reader* #'read-parts))
(values (if allow-non-list
(read stream t nil t)
(%read-maybe-nothing *client* stream t nil)))))
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-sharpsign-c
:stream-position (stream-position condition)
:report 'use-replacement-part))
(end-of-list (condition) ; (... #C)
(%recoverable-reader-error
stream 'complex-parts-must-follow-sharpsign-c
:position-offset -1 :report 'use-partial-complex)
(unread-char (%character condition) stream))
(:no-error (object)
;; If we got here, we managed to read an object.
(cond (listp)
((or (not allow-non-list) (not (typep object 'cons)))
(%recoverable-reader-error
stream 'non-list-following-sharpsign-c
:position-offset -1 ; inaccurate
:report 'use-replacement-part))
((typep object #3='(cons real (cons real null)))
(setf real (first object)
imaginary (second object)))
(t
(%recoverable-reader-error
stream 'read-object-type-error
:position-offset -1 ; inaccurate
:datum object :expected-type #3#
:report 'use-replacement-part)))))
(complex real imaginary))))
(defun sharpsign-c (stream char parameter)
(%sharpsign-c stream char parameter t))
(defun strict-sharpsign-c (stream char parameter)
(%sharpsign-c stream char parameter nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macro for sharpsign S.
;;;
In contrast to 2.4.8.11 Sharpsign C which says " # C reads a
;;; following object …" thus allowing whitespace preceding the object,
2.4.8.13 S spells out the syntax as " # s ( … ) " . However ,
;;; since a strict reading of this would also preclude "#S(…)" we
;;; assume that the intention is to allow whitespace after "#s".
(defun sharpsign-s (stream char parameter)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-s parameter))
(when *read-suppress*
(read stream t nil t)
(return-from sharpsign-s nil))
;; When we get here, we have to read a list of the form
( STRUCTURE - TYPE - NAME SLOT - NAME SLOT - VALUE … ) . We call
;; %READ-LIST-ELEMENTS which calls the local function ELEMENT for
;; each list element as well as events such as the end of the list
;; or the end of input. The variable ELEMENT keeps track of the
currently expected ELEMENT which can be : TYPE , : SLOT - NAME , or
: SLOT - VALUE .
(let ((old-quasiquote-forbidden *quasiquote-forbidden*)
(listp nil)
(element :type)
(type)
(slot-name)
(initargs '()))
(labels ((element (kind value)
(declare (ignore kind))
(case element
(:type
(typecase value
((eql #1=#.(gensym "END-OF-LIST"))
(%recoverable-reader-error
stream 'no-structure-type-name-found
:position-offset -1 :report 'inject-nil))
((eql #2=#.(gensym "END-OF-INPUT"))
(%recoverable-reader-error
stream 'end-of-input-before-structure-type-name
:report 'inject-nil))
(symbol
(setf type value))
(t
(%recoverable-reader-error
stream 'structure-type-name-is-not-a-symbol
:position-offset -1 :datum value :report 'inject-nil)))
(setf *quasiquote-forbidden* 'sharpsign-s-slot-name
*unquote-forbidden* 'sharpsign-s-slot-name
element :name))
(:name
(typecase value
((eql #1#))
((eql #2#)
(%recoverable-reader-error
stream 'end-of-input-before-slot-name
:report 'use-partial-initargs))
(alexandria:string-designator
(setf slot-name value))
(t
(%recoverable-reader-error
stream 'slot-name-is-not-a-string-designator
:position-offset -1 :datum value :report 'skip-slot)
(setf slot-name value)))
(setf *quasiquote-forbidden* old-quasiquote-forbidden
*unquote-forbidden* 'sharpsign-s-slot-value
element :object))
(:object
(typecase value
((eql #1#)
(%recoverable-reader-error
stream 'no-slot-value-found
:position-offset -1
:slot-name slot-name :report 'skip-slot))
((eql #2#)
(%recoverable-reader-error
stream 'end-of-input-before-slot-value
:slot-name slot-name :report 'skip-slot))
(t
(push slot-name initargs)
(push value initargs)))
(setf *quasiquote-forbidden* 'sharpsign-s-slot-name
*unquote-forbidden* 'sharpsign-s-slot-name
element :name))))
(read-constructor (stream char)
;; If this is called, the input started with "#S(" (or,
;; generally, "#S" followed by any input resulting in a
;; LEFT-PARENTHESIS call). We record that fact (for
error reporting ) by setting LISTP . We reset
;; *LIST-READER* so lists appearing in the constructor
;; parts are processed normally instead of with
;; READ-CONSTRUCTOR.
(setf listp t)
(setf *quasiquote-forbidden* 'sharpsign-s-type
*unquote-forbidden* 'sharpsign-s-type)
(let ((*list-reader* nil))
(%read-list-elements stream #'element '#1# '#2# char nil))))
(handler-case
;; Instead of READ we call %READ-MAYBE-NOTHING which will
;; - not skip whitespace or comments (the spec is not clear
;; about whether #S<skippable things>(...) is valid syntax)
;; - invoke reader macros, in particular LEFT-PARENTHESIS to
;; initiate reading a list
;; - not behave like a full READ call in terms of e.g. parse
result construction so ( foo : bar 2 ) will not appear as
a list result with three atom result children .
;; We bind *LIST-READER* to use READ-CONSTRUCTOR for reading lists.
(with-forbidden-quasiquotation ('sharpsign-s)
(let ((*list-reader* #'read-constructor))
(%read-maybe-nothing *client* stream t nil)))
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-sharpsign-s
:stream-position (stream-position condition)
:report 'inject-nil))
(end-of-list (condition)
(%recoverable-reader-error
stream 'structure-constructor-must-follow-sharpsign-s
:position-offset -1 :report 'inject-nil)
(unread-char (%character condition) stream))
(:no-error (&rest values)
(declare (ignore values))
(unless listp
(%recoverable-reader-error
stream 'non-list-following-sharpsign-s
:position-offset -1 :report 'inject-nil))))
(if (not (null type))
(make-structure-instance *client* type (nreverse initargs))
nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macro for sharpsign P.
(defun sharpsign-p (stream char parameter)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-p parameter))
(when *read-suppress*
(read stream t nil t)
(return-from sharpsign-p nil))
(let ((expression
(with-forbidden-quasiquotation ('sharpsign-p)
(handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-sharpsign-p
:stream-position (stream-position condition)
:report 'replace-namestring)
".")
(end-of-list (condition)
(%recoverable-reader-error
stream 'namestring-must-follow-sharpsign-p
:position-offset -1 :report 'replace-namestring)
(unread-char (%character condition) stream)
".")))))
(cond ((stringp expression)
(values (parse-namestring expression)))
(t
(%recoverable-reader-error
stream 'non-string-following-sharpsign-p
:position-offset -1
:expected-type 'string :datum expression
:report 'replace-namestring)
#P"."))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macros for sharpsign + and sharpsign -.
;;; This variable is bound to the current input stream in
;;; SHARPSIGN-PLUS-MINUS to make the stream available for error
reporting in CHECK - STANDARD - FEATURE - EXPRESSION .
(defvar *input-stream*)
(deftype feature-expression-operator ()
'(member :not :or :and))
(defun check-standard-feature-expression (feature-expression)
(flet ((lose (stream-condition no-stream-condition &rest arguments)
(alexandria:if-let ((stream *input-stream*))
(apply #'%reader-error stream stream-condition
:position-offset -1 arguments)
(apply #'error no-stream-condition arguments))))
(unless (or (symbolp feature-expression)
(alexandria:proper-list-p feature-expression))
(lose 'feature-expression-type-error/reader
'feature-expression-type-error
:datum feature-expression
:expected-type '(or symbol cons)))
(when (consp feature-expression)
(destructuring-bind (operator &rest operands) feature-expression
(unless (typep operator 'feature-expression-operator)
(lose 'feature-expression-type-error/reader
'feature-expression-type-error
:datum operator
:expected-type 'feature-expression-operator))
(when (and (eq operator :not)
(not (alexandria:length= 1 operands)))
(lose 'single-feature-expected/reader 'single-feature-expected
:features (cdr feature-expression)))))))
(defun evaluate-standard-feature-expression
(feature-expression
&key
(check 'check-standard-feature-expression)
(recurse 'evaluate-standard-feature-expression))
(funcall check feature-expression)
(typecase feature-expression
(symbol
(member feature-expression *features* :test #'eq))
((cons (eql :not))
(not (funcall recurse (second feature-expression))))
((cons (eql :or))
(some recurse (rest feature-expression)))
((cons (eql :and))
(every recurse (rest feature-expression)))))
(defun sharpsign-plus-minus (stream char parameter invertp)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-plus-minus parameter))
(let ((context (if invertp
:sharpsign-minus
:sharpsign-plus)))
(flet ((read-expression (end-of-file-condition end-of-list-condition
fallback-value)
(handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream end-of-file-condition
:stream-position (stream-position condition)
:context context :report 'inject-nil)
fallback-value)
(end-of-list (condition)
(%recoverable-reader-error
stream end-of-list-condition
:position-offset -1 :context context :report 'inject-nil)
(unread-char (%character condition) stream)
fallback-value))))
(let* ((client *client*)
(feature-expression
(call-with-current-package
client (lambda ()
(let ((*read-suppress* nil))
(with-forbidden-quasiquotation (context)
(read-expression
'end-of-input-after-sharpsign-plus-minus
'feature-expression-must-follow-sharpsign-plus-minus
'(:and)))))
'#:keyword)))
(if (alexandria:xor
(with-simple-restart
(recover (recovery-description 'treat-as-false))
(let ((*input-stream* stream))
(evaluate-feature-expression client feature-expression)))
invertp)
(read-expression 'end-of-input-after-feature-expression
'object-must-follow-feature-expression
nil)
(progn
(setf *skip-reason* (cons context feature-expression))
(let ((*read-suppress* t))
(read-expression 'end-of-input-after-feature-expression
'object-must-follow-feature-expression
nil))
(values)))))))
(defun sharpsign-plus (stream char parameter)
(sharpsign-plus-minus stream char parameter nil))
(defun sharpsign-minus (stream char parameter)
(sharpsign-plus-minus stream char parameter t))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macros for sharpsign equals and sharpsign sharpsign.
;;;
When the - EQUALS reader macro encounters # N = EXPRESSION ,
it associates a marker object with When the - SHARPSIGN
reader macros encounters # N # , the marker for N is looked up and
;;; examined. If the marker has been finalized, the final object is
;;; inserted. Otherwise the marker is inserted, to be fixed up later.
After reading EXPRESSION , the marker is finalized with the
;;; resulting object. If circular references have been encountered
while reading EXPRESSION , FIXUP - GRAPH is called to replace markers
;;; with final objects (this fixup processing may be delayed if a the
;;; fixup processing for a surrounding circular object subsumes the
processing for the current object , see Fixup work tree in
labeled-objects.lisp ) . Subsequent # N # encounters can directly use
;;; the object.
;;;
;;; See the *LABELED-OBJECT* generic functions and the file
labeled-objects.lisp for more details .
;;; Track the immediately surrounding labeled object of the current
;;; labeled object in order to potentially avoid unnecessary fixup
work . See work tree in labeled-objects.lisp for details .
(defvar *parent-labeled-object* nil)
(defun sharpsign-equals (stream char parameter)
(declare (ignore char))
(flet ((read-object ()
(handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-sharpsign-equals
:stream-position (stream-position condition)
:report 'inject-nil)
nil)
(end-of-list (condition)
(%recoverable-reader-error
stream 'object-must-follow-sharpsign-equals
:position-offset -1 :report 'inject-nil)
(unread-char (%character condition) stream)
nil))))
(when *read-suppress*
(return-from sharpsign-equals (read-object)))
(when (null parameter)
(numeric-parameter-not-supplied stream 'sharpsign-equals)
(return-from sharpsign-equals (read-object)))
(let ((client *client*))
(unless (null (find-labeled-object client parameter))
(%recoverable-reader-error
stream 'sharpsign-equals-label-defined-more-than-once
:position-offset (- (+ 1 (parameter-length parameter) 1))
:label parameter :report 'ignore-label)
(return-from sharpsign-equals (read-object)))
Make a labeled object for the label PARAMETER and read the
;; following object. Reading the object may encounter references
to the label PARAMETER in which case LABELED - OBJECT will
;; appear as a placeholder in RESULT and the state of
;; LABELED-OBJECT will be changed to :CIRCULAR.
(let* ((parent *parent-labeled-object*)
(labeled-object (note-labeled-object
client stream parameter parent))
(result (let ((*parent-labeled-object* labeled-object))
(read-object))))
;; If RESULT is just LABELED-OBJECT, the input was of the form
;; #N=#N#.
(when (eq result labeled-object)
(%recoverable-reader-error
stream 'sharpsign-equals-only-refers-to-self
:position-offset -1 :label parameter :report 'inject-nil)
(forget-labeled-object client parameter)
(return-from sharpsign-equals nil))
;; Perform (or defer) fixup work in case LABELED-OBJECT
;; changed its state to :CIRCULAR.
(finalize-labeled-object client labeled-object result)
result))))
(defun sharpsign-sharpsign (stream char parameter)
(declare (ignore char))
(when *read-suppress*
(return-from sharpsign-sharpsign nil))
(when (null parameter)
(numeric-parameter-not-supplied stream 'sharpsign-equals)
(return-from sharpsign-sharpsign nil))
(let* ((client *client*)
(labeled-object (find-labeled-object client parameter)))
(when (null labeled-object)
(%recoverable-reader-error
stream 'sharpsign-sharpsign-undefined-label
:position-offset (- (+ 1 (parameter-length parameter) 1))
:label parameter :report 'inject-nil)
(return-from sharpsign-sharpsign nil))
(reference-labeled-object client stream labeled-object)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reader macros for sharpsign < and sharpsign )
(defun sharpsign-invalid (stream char parameter)
(declare (ignore parameter))
(%recoverable-reader-error
stream 'sharpsign-invalid
:position-offset -1 :character-found char :report 'inject-nil)
nil)
| null | https://raw.githubusercontent.com/s-expressionists/Eclector/acd141db4efdbd88d57a8fe4f258ffc18cc47baa/code/reader/macro-functions.lisp | lisp |
Macro WITH-FORBIDDEN-QUASIQUOTATION.
This macro controls whether quasiquote and/or unquote should be
allowed in a given context.
Reader macro for semicolon.
We read characters until end-of-file or until we have read a
newline character. Since reading a comment does not generate an
object, the semicolon reader must indicate that fact by returning
))
Reader macro for single quote.
end-of-file is encountered before an object has been entirely
parsed, independently of whether EOF-ERROR-P is true or not. For
that reason, we call the reader recursively with the value of
EOF-ERROR-P being T.
Reader macro for double quote.
We identify a single escape character by its syntax type, so that
if a user wants a different escape chacacter, we can handle that.
if end-of-file is encountered before an object has been entirely
parsed, independently of whether EOF-ERROR-P is true or not. For
that reason, we call READ-CHAR with the value of EOF-ERROR-P being
T.
We accumulate characters in an adjustable vector. However, the
return a simple vector.
Reader macros for backquote and comma.
explanation.
are allowed only inside lists and vectors. Since READ can be
called recursively from other functions as well (such as the
reader for arrays, or user-defined readers), we somehow need to
track whether backquote and comma are allowed in the current
context.
We could (and previously did) forbid backquote and comma except
inside lists and vectors, but in practice, clients expect control
over this behavior in order to implement reader macros such as
`#{,key ,value} => (let ((g1 (make-hash-table ...))) ...)
*UNQUOTE-FORBIDDEN-P* to control whether backquote and comma are
allowed. Initially, both variables are bound to T, allowing
comma are nested properly). Reader macros such as #C, #A,
etc. bind the variables to a true value that also indicates the
context (usually the symbol naming the reader macro function).
The only way these variables can be re-bound to NIL (in the
Representation of quasiquoted forms
expression. We see no reason for choosing a different
and (UNQUOTE-SPLICING <form>). Then we define QUASIQUOTE as a
structure.
end-of-input, but we may recover
Reader macros for left-parenthesis and right-parenthesis.
In the reader macro for left-parenthesis, we can not just read
until we find a right parenthesis, because it is possible that
some other character has been assigned the same meaning, and we
need to handle that situation too.
just read characters and look for a single period, because it is
possible that the single dot has a different syntax type in this
particular readtable. Furthermore, we must handle error
dot.
We solve these problems as follows: the reader macro for a right
END-OF-LIST). In situations where the right parenthesis is
allowed, there will be a handler for this condition type.
the right parenthesis was read in a context where it is not
allowed.
REVERSED-RESULT and TAIL. The variable REVERSED-RESULT is used to
accumulate elements of the list (preceding a possible consing dot)
being read, in reverse order. A handler for END-OF-LIST is
established around the recursive calls to READ inside the reader
reverse the value of REVERSED-RESULT and attach the value of TAIL
will create and return a proper list containing the accumulated
elements.
determine the contexts in which a consing dot is allowed.
Whenever the token parser detects a consing dot, it examines this
token, and if it is false, signals an error. Initially, this
variable has the value FALSE. Whenever the reader macro for left
parenthesis is called, it binds this variable to TRUE. When a
recursive call to READ returns with the consing dot as a value,
END-OF-LIST, so that if a right parenthesis should occur
immediately after the consing dot, then an error is signaled.
With this handler established, READ is called. If it returns
normally, then the return value becomes the value of the variable
TAIL. Third, it calls READ again without any nested handler
established. This call had better result in a right parenthesis,
so that END-OF-LIST is signaled, which is caught by the outermost
handler and the correct list is built and returned. If this call
should return normally, we have a problem, because this means that
we signal an ERROR.
condition, which means that the right parenthesis was found in a
context where it is not allowed.
Reader macro for sharpsign single quote.
that is `#',(foo) is read as
(quasiquote (function (unquote (foo))))
. It is not clear that this behavior is supported by the
specification, but it is widely relied upon and thus the default
behavior.
within #'.
Reader macro for sharpsign left parenthesis.
inaccurate
Reader macro for sharpsign dot.
Reader macro for sharpsign backslash.
can happen when recovering
no additional characters pushed (same as (null token))
Reader macro for sharpsign B, X, O and R.
also when READ-SUPPRESS
When READ-SUPPRESS, / has been consumed
Reader macro for sharpsign A.
inaccurate
Reader macro for sharpsign colon.
Reader macro for sharpsign C.
When we get here, we have to read a list of the form
(REAL-PART-REAL-NUMBER-LITERAL IMAGINARY-PART-REAL-NUMBER) that
We call %READ-LIST-ELEMENTS which calls the local function PART
for each list element as well as the events such as the end of
the list or the end of input. The variable PART keeps track of
the currently expected part which can be :REAL, :IMAGINARY, :END
or :PAST-END (the latter only comes into play when reading more
If this is called, the input started with "#C(" (or,
generally, "#C" followed by any input resulting in a
LEFT-PARENTHESIS call). We record that fact (for
*LIST-READER* so lists appearing in the complex
parts are processed normally instead of with
READ-PARTS.
unused, but must not return (values)
Depending on ALLOW-NON-LIST, we call either READ or
%READ-MAYBE-NOTHING. Calling %READ-MAYBE-NOTHING will:
- not skip whitespace or comments (the spec is not clear
about whether #C<skippable things>(...) is valid syntax)
- invoke reader macros, in particular LEFT-PARENTHESIS to
initiate reading a list
- not behave like a full READ call in terms of e.g. parse
We bind *LIST-READER* to use READ-PARTS for reading lists.
(... #C)
If we got here, we managed to read an object.
inaccurate
inaccurate
Reader macro for sharpsign S.
following object …" thus allowing whitespace preceding the object,
since a strict reading of this would also preclude "#S(…)" we
assume that the intention is to allow whitespace after "#s".
When we get here, we have to read a list of the form
%READ-LIST-ELEMENTS which calls the local function ELEMENT for
each list element as well as events such as the end of the list
or the end of input. The variable ELEMENT keeps track of the
If this is called, the input started with "#S(" (or,
generally, "#S" followed by any input resulting in a
LEFT-PARENTHESIS call). We record that fact (for
*LIST-READER* so lists appearing in the constructor
parts are processed normally instead of with
READ-CONSTRUCTOR.
Instead of READ we call %READ-MAYBE-NOTHING which will
- not skip whitespace or comments (the spec is not clear
about whether #S<skippable things>(...) is valid syntax)
- invoke reader macros, in particular LEFT-PARENTHESIS to
initiate reading a list
- not behave like a full READ call in terms of e.g. parse
We bind *LIST-READER* to use READ-CONSTRUCTOR for reading lists.
Reader macro for sharpsign P.
Reader macros for sharpsign + and sharpsign -.
This variable is bound to the current input stream in
SHARPSIGN-PLUS-MINUS to make the stream available for error
Reader macros for sharpsign equals and sharpsign sharpsign.
examined. If the marker has been finalized, the final object is
inserted. Otherwise the marker is inserted, to be fixed up later.
resulting object. If circular references have been encountered
with final objects (this fixup processing may be delayed if a the
fixup processing for a surrounding circular object subsumes the
the object.
See the *LABELED-OBJECT* generic functions and the file
Track the immediately surrounding labeled object of the current
labeled object in order to potentially avoid unnecessary fixup
following object. Reading the object may encounter references
appear as a placeholder in RESULT and the state of
LABELED-OBJECT will be changed to :CIRCULAR.
If RESULT is just LABELED-OBJECT, the input was of the form
#N=#N#.
Perform (or defer) fixup work in case LABELED-OBJECT
changed its state to :CIRCULAR.
Reader macros for sharpsign < and sharpsign ) | (cl:in-package #:eclector.reader)
(defmacro with-forbidden-quasiquotation
((context &optional (quasiquote-forbidden-p t)
(unquote-forbidden-p t))
&body body)
(alexandria:with-unique-names (context*)
(let ((context-used-p nil))
(flet ((make-binding (variable value-form)
(cond ((constantp value-form)
(case (eval value-form)
(:keep
'())
((nil)
`((,variable nil)))
(t
(setf context-used-p t)
`((,variable ,context*)))))
(t
(setf context-used-p t)
`((,variable (case ,value-form
(:keep ,variable)
((nil) nil)
(t ,context*))))))))
`(let* ((,context* ,context)
,@(make-binding '*quasiquote-forbidden* quasiquote-forbidden-p)
,@(make-binding '*unquote-forbidden* unquote-forbidden-p))
,@(unless context-used-p
`((declare (ignore ,context*))))
,@body)))))
zero values .
(defun semicolon (stream char)
(declare (ignore char))
(loop with state = :semicolon
for char = (read-char stream nil nil t)
until (or (null char) (eql char #\Newline))
count 1 into semicolons
else
do (setf state nil)
finally (setf *skip-reason* (cons :line-comment (1+ semicolons))))
(values))
They HyperSpec says that the reader signals an error if
(defun single-quote (stream char)
(declare (ignore char))
(let ((material (handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-quote
:stream-position (stream-position condition)
:report 'inject-nil)
nil)
(end-of-list (condition)
(%recoverable-reader-error
stream 'object-must-follow-quote
:position-offset -1 :report 'inject-nil)
(unread-char (%character condition) stream)
nil))))
(wrap-in-quote *client* material)))
Furthermore , They HyperSpec says that the reader signals an error
HyperSpec says that we must return a SIMPLE - STRING . For that
reason , we call COPY - SEQ in the end . COPY - SEQ is guaranteed to
(defun double-quote (stream char)
(let ((result (make-array 100 :element-type 'character
:adjustable t
:fill-pointer 0)))
(loop with readtable = *readtable*
for char2 = (read-char-or-recoverable-error
stream char 'unterminated-string
:delimiter char :report 'use-partial-string)
until (eql char2 char)
when (eq (eclector.readtable:syntax-type readtable char2) :single-escape)
do (setf char2 (read-char-or-recoverable-error
stream nil 'unterminated-single-escape-in-string
:position-offset -1
:escape-char char2 :report 'use-partial-string))
when char2
do (vector-push-extend char2 result)
finally (return (copy-seq result)))))
The control structure we use for backquote requires some
The HyperSpec says ( see section 2.4.6 ) that backquote and comma
# L`(,!1 , ! 1 ) = > ( lambda ( g1 ) ` ( , g1 , g1 ) )
We use the flags * * and
backquote and comma ( * QUASIQUOTE - DEPTH * ensures that backquote and
standard readtable ) is the - DOT reader macro .
The HyperSpec explicitly encourages us ( see section 2.4.6.1 ) to
follow the example of Scheme for representing backquote
representation , so we use ( QUASIQUOTE < form > ) , ( UNQUOTE < form > ) ,
macro that expands to a CL form that will build the final data
(defun backquote (stream char)
(declare (ignore char))
(alexandria:when-let ((context *quasiquote-forbidden*))
(unless *read-suppress*
(%recoverable-reader-error
stream 'backquote-in-invalid-context
:position-offset -1 :context context :report 'ignore-quasiquote)
(return-from backquote
(let ((*backquote-depth* 0))
(read stream t nil t)))))
(let ((material (let ((*backquote-depth* (1+ *backquote-depth*))
(*unquote-forbidden* nil))
(handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-backquote
:stream-position (stream-position condition)
:report 'inject-nil)
nil)
(end-of-list (condition)
(%recoverable-reader-error
stream 'object-must-follow-backquote
:position-offset -1 :report 'inject-nil)
(unread-char (%character condition) stream)
nil)))))
(wrap-in-quasiquote *client* material)))
(defun comma (stream char)
(declare (ignore char))
(let* ((depth *backquote-depth*)
(char2 (read-char stream nil nil t))
(splicing-p (case char2
((#\@ #\.) t)
(t (unread-char char2 stream)))))
(flet ((read-material ()
(handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-unquote
:stream-position (stream-position condition)
:splicing-p splicing-p :report 'inject-nil)
nil)
(end-of-list (condition)
(%recoverable-reader-error
stream 'object-must-follow-unquote
:position-offset -1
:splicing-p splicing-p :report 'inject-nil)
(unread-char (%character condition) stream)
nil))))
(unless (plusp depth)
(%recoverable-reader-error
stream 'unquote-not-inside-backquote
:position-offset (if splicing-p -2 -1)
:splicing-p splicing-p :report 'ignore-unquote)
(return-from comma (read-material)))
(alexandria:when-let ((context *unquote-forbidden*))
(unless *read-suppress*
(%recoverable-reader-error
stream 'unquote-in-invalid-context
:position-offset (if splicing-p -2 -1)
:splicing-p splicing-p :context context :report 'ignore-unquote)
(return-from comma (read-material))))
(let* ((*backquote-depth* (1- depth))
(form (read-material)))
(if splicing-p
(wrap-in-unquote-splicing *client* form)
(wrap-in-unquote *client* form))))))
The HyperSpec says that right - parenthesis is a macro character .
Another problem we need to solve is that of the CONSING - DOT . The
HyperSpec says that it is a token . For that reason , we can not
situations such as an attempt to use more than one dot in a list ,
or having zero or strictly more than one expression following a
parenthesis calls SIGNAL with a particular condition ( of type
Therefore , in that situation , the call to SIGNAL will not return .
If the call to SIGNAL returns , we signal and ERROR , because then
The reader macro for left parenthesis manages two local variables ,
macro function . When this handler is invoked , it calls NRECONC to
to the end . Normally , the value of TAIL is NIL , so the handler
We use a special variable name * CONSING - DOT - ALLOWED - P * to
variable , and if it is true it returns the unique CONSING - DOT
the reader macro for left parenthesis does three things . First it
SETS ( as opposed to BINDS ) * CONSING - DOT - ALLOWED - P * to FALSE , so
that if a second consing dot should occur , then the token reader
signals an error . Second , it establishes a nested handler for
there was a second subform after the consing dot in the list , so
(defun left-parenthesis (stream char)
(declare (ignore char))
(%read-delimited-list stream #\)))
(defun right-parenthesis (stream char)
If the call to SIGNAL returns , then there is no handler for this
(signal-end-of-list char)
(%recoverable-reader-error
stream 'invalid-context-for-right-parenthesis
:position-offset -1
:found-character char :report 'ignore-trailing-right-paren))
(defun %sharpsign-single-quote (stream char parameter allow-unquote)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-single-quote parameter))
(let ((name (with-forbidden-quasiquotation
('sharpsign-single-quote :keep (if allow-unquote :keep t))
(handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-sharpsign-single-quote
:stream-position (stream-position condition)
:report 'inject-nil)
nil)
(end-of-list (condition)
(%recoverable-reader-error
stream 'object-must-follow-sharpsign-single-quote
:position-offset -1 :report 'inject-nil)
(unread-char (%character condition) stream)
nil)))))
(cond (*read-suppress*
nil)
((null name)
nil)
(t
(wrap-in-function *client* name)))))
This variation of - SINGLE - QUOTE allows unquote within # ' ,
(defun sharpsign-single-quote (stream char parameter)
(%sharpsign-single-quote stream char parameter t))
This variation of - SINGLE - QUOTE does not allow unquote
(defun strict-sharpsign-single-quote (stream char parameter)
(%sharpsign-single-quote stream char parameter nil))
(defun sharpsign-left-parenthesis (stream char parameter)
(declare (ignore char))
(flet ((next-element ()
(handler-case
(values (read stream t nil t) t)
(end-of-list ()
(values nil nil))
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'unterminated-vector
:stream-position (stream-position condition)
:delimiter #\) :report 'use-partial-vector)
(values nil nil)))))
(cond (*read-suppress*
(loop for elementp = (nth-value 1 (next-element))
while elementp))
((null parameter)
(loop with result = (make-array 10 :adjustable t :fill-pointer 0)
for (element elementp) = (multiple-value-list (next-element))
while elementp
do (vector-push-extend element result)
finally (return (coerce result 'simple-vector))))
(t
(loop with result = (make-array parameter)
with excess-position = nil
for index from 0
for (element elementp) = (multiple-value-list
(next-element))
while elementp
if (< index parameter)
do (setf (aref result index) element)
else
do (setf excess-position (eclector.base:source-position
*client* stream))
finally (cond ((and (zerop index) (plusp parameter))
(%recoverable-reader-error
stream 'no-elements-found
:position-offset -1
:array-type 'vector :expected-number parameter
:report 'use-empty-vector)
(setf result (make-array 0)
index parameter))
((> index parameter)
(%recoverable-reader-error
stream 'too-many-elements
:position-offset -1
:array-type 'vector
:expected-number parameter
:number-found index
:report 'ignore-excess-elements)))
(return
(if (< index parameter)
(fill result (aref result (1- index))
:start index)
result)))))))
(defun sharpsign-dot (stream char parameter)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-dot parameter))
(cond ((not *read-eval*)
(%reader-error stream 'read-time-evaluation-inhibited))
(*read-suppress*
(read stream t nil t))
(t
(let ((expression (with-forbidden-quasiquotation (nil nil nil)
(let ((*list-reader* nil))
(handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-sharpsign-dot
:stream-position (stream-position condition)
:report 'inject-nil)
nil)
(end-of-list (condition)
(%recoverable-reader-error
stream 'object-must-follow-sharpsign-dot
:position-offset -1 :report 'inject-nil)
(unread-char (%character condition) stream)
nil))))))
(handler-case
(evaluate-expression *client* expression)
(error (condition)
(%recoverable-reader-error
stream 'read-time-evaluation-error
:expression expression :original-condition condition
:report 'inject-nil)
nil))))))
Mandatory character names according to 13.1.7 Character Names .
(defparameter *character-names*
(alexandria:alist-hash-table '(("NEWLINE" . #.(code-char 10))
("SPACE" . #.(code-char 32))
("RUBOUT" . #.(code-char 127))
("PAGE" . #.(code-char 12))
("TAB" . #.(code-char 9))
("BACKSPACE" . #.(code-char 8))
("RETURN" . #.(code-char 13))
("LINEFEED" . #.(code-char 10)))
:test 'equalp))
(defun find-standard-character (name)
(gethash name *character-names*))
(defun sharpsign-backslash (stream char parameter)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-backslash parameter))
(let ((char1 (read-char-or-recoverable-error
stream nil 'end-of-input-after-backslash
:report '(use-replacement-character #1=#\?))))
(return-from sharpsign-backslash #1#))
(with-token-info (push-char () finalize :lazy t)
(labels ((handle-char (char escapep)
(declare (ignore escapep))
(when (not (null char1))
(push-char char1)
(setf char1 nil))
(push-char char))
(unterminated-single-escape (escape-char)
(%recoverable-reader-error
stream 'unterminated-single-escape-in-character-name
:escape-char escape-char :report 'use-partial-character-name))
(unterminated-multiple-escape (delimiter)
(%recoverable-reader-error
stream 'unterminated-multiple-escape-in-character-name
:delimiter delimiter :report 'use-partial-character-name))
(lookup (name)
(let ((character (find-character *client* name)))
(cond ((null character)
(%recoverable-reader-error
stream 'unknown-character-name
:position-offset (- (if (characterp name)
1
(length name)))
:name name
:report '(use-replacement-character #2=#\?))
#2#)
(t
character))))
(terminate-character ()
(return-from sharpsign-backslash
(cond (*read-suppress* nil)
(lookup char1))
(t
(lookup (finalize)))))))
(token-state-machine
stream *readtable* handle-char nil nil
unterminated-single-escape unterminated-multiple-escape
terminate-character)))))
(defun read-rational (stream base)
(let ((readtable *readtable*)
(read-suppress *read-suppress*))
(labels ((next-char (eof-error-p)
(let ((char (read-char stream nil nil t)))
(cond ((not (null char))
(values char (eclector.readtable:syntax-type
readtable char)))
((and eof-error-p (not read-suppress))
(%recoverable-reader-error
stream 'end-of-input-before-digit
:base base :report 'replace-invalid-digit)
(values #\1 :constituent))
(t
(values nil nil)))))
(digit-expected (char type recover-value)
(%recoverable-reader-error
stream 'digit-expected
:position-offset -1
:character-found char :base base
:report 'replace-invalid-digit)
(unless (eq type :constituent)
(unread-char char stream))
recover-value)
(ensure-digit (char type)
(let ((value (digit-char-p char base)))
(if (null value)
(digit-expected char type 1)
value)))
(maybe-sign ()
(multiple-value-bind (char type) (next-char t)
(cond (read-suppress
(values 1 0))
((not (eq type :constituent))
(digit-expected char type nil))
((char= char #\-)
(values -1 0))
(t
(values 1 (ensure-digit char type))))))
(integer (empty-allowed /-allowed initial-value)
(let ((value initial-value))
(tagbody
(multiple-value-bind (char type) (next-char t)
(case type
(:constituent
(setf value (ensure-digit char type)))
(t
(digit-expected char type nil)
(return-from integer value))))
rest
(multiple-value-bind (char type) (next-char nil)
(ecase type
((nil)
(return-from integer value))
(:whitespace
(unread-char char stream)
(return-from integer value))
(:terminating-macro
(unread-char char stream)
(return-from integer value))
((:non-terminating-macro
:single-escape :multiple-escape)
(cond (read-suppress
(go rest))
(t
(digit-expected char type nil)
(return-from integer value))))
(:constituent
(cond (read-suppress
(go rest))
((and /-allowed (eql char #\/))
(return-from integer (values value t)))
(t
(setf value (+ (* base (or value 0))
(ensure-digit char type)))
(go rest)))))))))
(read-denominator ()
(let ((value (integer nil nil nil)))
(cond ((eql value 0)
(%recoverable-reader-error
stream 'zero-denominator
:position-offset -1 :report 'replace-invalid-digit)
nil)
(t
value)))))
(multiple-value-bind (sign numerator) (maybe-sign)
(if (null sign)
0
(multiple-value-bind (numerator slashp)
(integer (= sign 1) t numerator)
(let ((denominator (when slashp (read-denominator))))
(* sign (if denominator
(/ numerator denominator)
numerator))))))))))
(defun sharpsign-b (stream char parameter)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-b parameter))
(read-rational stream 2.))
(defun sharpsign-x (stream char parameter)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-x parameter))
(read-rational stream 16.))
(defun sharpsign-o (stream char parameter)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-o parameter))
(read-rational stream 8.))
(defun sharpsign-r (stream char parameter)
(declare (ignore char))
(let ((radix (cond ((not parameter)
(numeric-parameter-not-supplied stream 'sharpsign-r)
36)
((not (<= 2 parameter 36))
(unless *read-suppress*
(%recoverable-reader-error
stream 'invalid-radix
:position-offset (- (+ (parameter-length parameter) 1))
:radix parameter :report 'use-replacement-radix))
36)
(t
parameter))))
(read-rational stream radix)))
(defun sharpsign-asterisk (stream char parameter)
(declare (ignore char))
(let ((read-suppress *read-suppress*)
(readtable *readtable*))
(flet ((next-bit ()
(let ((char (read-char stream nil nil t)))
(multiple-value-bind (syntax-type value)
(unless (null char)
(values (eclector.readtable:syntax-type
readtable char)
(digit-char-p char 2)))
(when (eq syntax-type :terminating-macro)
(unread-char char stream))
(cond ((member syntax-type '(nil :whitespace :terminating-macro))
nil)
(read-suppress
t)
((null value)
(%recoverable-reader-error
stream 'digit-expected
:position-offset -1
:character-found char :base 2.
:report 'replace-invalid-digit)
0)
(t
value))))))
(cond (read-suppress
(loop for value = (next-bit) while value))
((null parameter)
(loop with bits = (make-array 10 :element-type 'bit
:adjustable t :fill-pointer 0)
for value = (next-bit)
while value
do (vector-push-extend value bits)
finally (return (coerce bits 'simple-bit-vector))))
(t
(loop with result = (make-array parameter :element-type 'bit)
for index from 0
for value = (next-bit)
while value
when (< index parameter)
do (setf (sbit result index) value)
finally (cond ((and (zerop index) (plusp parameter))
(%recoverable-reader-error
stream 'no-elements-found
:array-type 'bit-vector
:expected-number parameter
:report 'use-empty-vector)
(setf result (make-array 0 :element-type 'bit)
index parameter))
((> index parameter)
(%recoverable-reader-error
stream 'too-many-elements
:position-offset (- (- index parameter))
:array-type 'bit-vector
:expected-number parameter
:number-found index
:report 'ignore-excess-elements)))
(return
(if (< index parameter)
(fill result (sbit result (1- index))
:start index)
result))))))))
(defun sharpsign-vertical-bar (stream sub-char parameter)
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-vertical-bar parameter))
(handler-case
(loop for char = (read-char stream t nil t)
do (cond ((eql char #\#)
(let ((char2 (read-char stream t nil t)))
(if (eql char2 sub-char)
(sharpsign-vertical-bar stream sub-char nil)
(unread-char char2 stream))))
((eql char sub-char)
(let ((char2 (read-char stream t nil t)))
(if (eql char2 #\#)
(progn
(setf *skip-reason* :block-comment)
(return-from sharpsign-vertical-bar (values)))
(unread-char char2 stream))))
(t
nil)))
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'unterminated-block-comment
:stream-position (stream-position condition)
:delimiter sub-char :report 'ignore-missing-delimiter))))
(labels ((check-sequence (stream object)
(when (not (typep object 'alexandria:proper-sequence))
(%recoverable-reader-error
stream 'read-object-type-error
:expected-type 'sequence :datum object
:report 'use-empty-array)
(invoke-restart '%make-empty))
nil)
(make-empty-dimensions (rank)
(make-list rank :initial-element 0))
(determine-dimensions (stream rank initial-contents)
(labels ((rec (rank initial-contents)
(cond ((zerop rank)
'())
((check-sequence stream initial-contents))
(t
(let ((length (length initial-contents)))
(if (zerop length)
(make-empty-dimensions rank)
(list* length
(rec (1- rank)
(elt initial-contents 0)))))))))
(rec rank initial-contents)))
(check-dimensions (stream dimensions initial-contents)
(labels ((rec (first rest axis initial-contents)
(cond ((not first))
((check-sequence stream initial-contents))
((not (eql (length initial-contents) (or first 0)))
(%recoverable-reader-error
stream 'incorrect-initialization-length
:array-type 'array :axis axis
:expected-length first :datum initial-contents
:report 'use-empty-array)
(invoke-restart '%make-empty))
(t
(every (lambda (subseq)
(rec (first rest) (rest rest)
(1+ axis) subseq))
initial-contents)))))
(rec (first dimensions) (rest dimensions) 0 initial-contents)))
(read-init (stream)
(with-forbidden-quasiquotation ('sharpsign-a :keep)
(handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-sharpsign-a
:stream-position (stream-position condition)
:report 'use-empty-array)
(invoke-restart '%make-empty))
(end-of-list (condition)
(%recoverable-reader-error
stream 'object-must-follow-sharpsign-a
:position-offset -1 :report 'use-empty-array)
(unread-char (%character condition) stream)
(invoke-restart '%make-empty))))))
(defun sharpsign-a (stream char parameter)
(declare (ignore char))
(when *read-suppress*
(return-from sharpsign-a (read stream t nil t)))
(let ((rank (cond ((null parameter)
(numeric-parameter-not-supplied stream 'sharpsign-a)
0)
(t
parameter))))
(multiple-value-bind (dimensions init)
(restart-case
(let* ((init (read-init stream))
(dimensions (determine-dimensions
stream rank init)))
(check-dimensions stream dimensions init)
(values dimensions init))
(%make-empty ()
(values (make-empty-dimensions rank) '())))
(make-array dimensions :initial-contents init)))))
(defun symbol-from-token (stream token token-escapes package-marker)
(when *read-suppress*
(return-from symbol-from-token nil))
(when package-marker
(%recoverable-reader-error
stream 'uninterned-symbol-must-not-contain-package-marker
:stream-position package-marker :position-offset -1
:token token :report 'treat-as-escaped))
(convert-according-to-readtable-case token token-escapes)
(interpret-symbol *client* stream nil (copy-seq token) nil))
(defun sharpsign-colon (stream char parameter)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-colon parameter))
(with-token-info (push-char (start-escape end-escape) finalize)
(let ((package-marker nil))
(labels ((handle-char (char escapep)
(when (and (not escapep)
(char= char #\:)
(not package-marker))
(setf package-marker (eclector.base:source-position
*client* stream)))
(push-char char))
(unterminated-single-escape (escape-char)
(%recoverable-reader-error
stream 'unterminated-single-escape-in-symbol
:escape-char escape-char :report 'use-partial-symbol))
(unterminated-multiple-escape (delimiter)
(%recoverable-reader-error
stream 'unterminated-multiple-escape-in-symbol
:delimiter delimiter :report 'use-partial-symbol))
(return-symbol ()
(return-from sharpsign-colon
(multiple-value-bind (token escape-ranges) (finalize)
(symbol-from-token stream token escape-ranges package-marker)))))
(token-state-machine
stream *readtable* handle-char start-escape end-escape
unterminated-single-escape unterminated-multiple-escape
return-symbol)))))
(defun %sharpsign-c (stream char parameter allow-non-list)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-c parameter))
(when *read-suppress*
(read stream t nil t)
(return-from %sharpsign-c nil))
is , a list of exactly two elements of type REAL .
than two list elements due to error recovery ) .
(let ((listp nil)
(part :real)
(real 1) (imaginary 1))
(labels ((check-value (value)
(typecase value
((eql #1=#.(gensym "END-OF-LIST"))
(%recoverable-reader-error
stream 'complex-part-expected
:position-offset -1
:which part :report 'use-partial-complex)
1)
((eql #2=#.(gensym "END-OF-INPUT"))
(%recoverable-reader-error
stream 'end-of-input-before-complex-part
:which part :report 'use-partial-complex)
1)
(real
value)
(t
(%recoverable-reader-error stream 'read-object-type-error
:datum value :expected-type 'real
:report 'use-replacement-part)
1)))
(part (kind value)
(declare (ignore kind))
(case part
(:real
(setf real (check-value value)
part :imaginary)
t)
(:imaginary
(setf imaginary (check-value value)
part :end)
t)
((:end :past-end)
(case value
(#1# t)
(#2# nil)
(t
(when (eq part :end)
(%recoverable-reader-error
stream 'too-many-complex-parts
:position-offset -1
:report 'ignore-excess-parts)
(setf part :past-end))
t)))))
(read-parts (stream char)
error reporting ) by setting LISTP . We reset
(setf listp t)
(let ((*list-reader* nil))
(%read-list-elements stream #'part '#1# '#2# char nil))
(handler-case
result construction so ( 1 2 ) will not appear as a list
result with two atom result children .
(with-forbidden-quasiquotation ('sharpsign-c)
(let ((*list-reader* #'read-parts))
(values (if allow-non-list
(read stream t nil t)
(%read-maybe-nothing *client* stream t nil)))))
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-sharpsign-c
:stream-position (stream-position condition)
:report 'use-replacement-part))
(%recoverable-reader-error
stream 'complex-parts-must-follow-sharpsign-c
:position-offset -1 :report 'use-partial-complex)
(unread-char (%character condition) stream))
(:no-error (object)
(cond (listp)
((or (not allow-non-list) (not (typep object 'cons)))
(%recoverable-reader-error
stream 'non-list-following-sharpsign-c
:report 'use-replacement-part))
((typep object #3='(cons real (cons real null)))
(setf real (first object)
imaginary (second object)))
(t
(%recoverable-reader-error
stream 'read-object-type-error
:datum object :expected-type #3#
:report 'use-replacement-part)))))
(complex real imaginary))))
(defun sharpsign-c (stream char parameter)
(%sharpsign-c stream char parameter t))
(defun strict-sharpsign-c (stream char parameter)
(%sharpsign-c stream char parameter nil))
In contrast to 2.4.8.11 Sharpsign C which says " # C reads a
2.4.8.13 S spells out the syntax as " # s ( … ) " . However ,
(defun sharpsign-s (stream char parameter)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-s parameter))
(when *read-suppress*
(read stream t nil t)
(return-from sharpsign-s nil))
( STRUCTURE - TYPE - NAME SLOT - NAME SLOT - VALUE … ) . We call
currently expected ELEMENT which can be : TYPE , : SLOT - NAME , or
: SLOT - VALUE .
(let ((old-quasiquote-forbidden *quasiquote-forbidden*)
(listp nil)
(element :type)
(type)
(slot-name)
(initargs '()))
(labels ((element (kind value)
(declare (ignore kind))
(case element
(:type
(typecase value
((eql #1=#.(gensym "END-OF-LIST"))
(%recoverable-reader-error
stream 'no-structure-type-name-found
:position-offset -1 :report 'inject-nil))
((eql #2=#.(gensym "END-OF-INPUT"))
(%recoverable-reader-error
stream 'end-of-input-before-structure-type-name
:report 'inject-nil))
(symbol
(setf type value))
(t
(%recoverable-reader-error
stream 'structure-type-name-is-not-a-symbol
:position-offset -1 :datum value :report 'inject-nil)))
(setf *quasiquote-forbidden* 'sharpsign-s-slot-name
*unquote-forbidden* 'sharpsign-s-slot-name
element :name))
(:name
(typecase value
((eql #1#))
((eql #2#)
(%recoverable-reader-error
stream 'end-of-input-before-slot-name
:report 'use-partial-initargs))
(alexandria:string-designator
(setf slot-name value))
(t
(%recoverable-reader-error
stream 'slot-name-is-not-a-string-designator
:position-offset -1 :datum value :report 'skip-slot)
(setf slot-name value)))
(setf *quasiquote-forbidden* old-quasiquote-forbidden
*unquote-forbidden* 'sharpsign-s-slot-value
element :object))
(:object
(typecase value
((eql #1#)
(%recoverable-reader-error
stream 'no-slot-value-found
:position-offset -1
:slot-name slot-name :report 'skip-slot))
((eql #2#)
(%recoverable-reader-error
stream 'end-of-input-before-slot-value
:slot-name slot-name :report 'skip-slot))
(t
(push slot-name initargs)
(push value initargs)))
(setf *quasiquote-forbidden* 'sharpsign-s-slot-name
*unquote-forbidden* 'sharpsign-s-slot-name
element :name))))
(read-constructor (stream char)
error reporting ) by setting LISTP . We reset
(setf listp t)
(setf *quasiquote-forbidden* 'sharpsign-s-type
*unquote-forbidden* 'sharpsign-s-type)
(let ((*list-reader* nil))
(%read-list-elements stream #'element '#1# '#2# char nil))))
(handler-case
result construction so ( foo : bar 2 ) will not appear as
a list result with three atom result children .
(with-forbidden-quasiquotation ('sharpsign-s)
(let ((*list-reader* #'read-constructor))
(%read-maybe-nothing *client* stream t nil)))
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-sharpsign-s
:stream-position (stream-position condition)
:report 'inject-nil))
(end-of-list (condition)
(%recoverable-reader-error
stream 'structure-constructor-must-follow-sharpsign-s
:position-offset -1 :report 'inject-nil)
(unread-char (%character condition) stream))
(:no-error (&rest values)
(declare (ignore values))
(unless listp
(%recoverable-reader-error
stream 'non-list-following-sharpsign-s
:position-offset -1 :report 'inject-nil))))
(if (not (null type))
(make-structure-instance *client* type (nreverse initargs))
nil))))
(defun sharpsign-p (stream char parameter)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-p parameter))
(when *read-suppress*
(read stream t nil t)
(return-from sharpsign-p nil))
(let ((expression
(with-forbidden-quasiquotation ('sharpsign-p)
(handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-sharpsign-p
:stream-position (stream-position condition)
:report 'replace-namestring)
".")
(end-of-list (condition)
(%recoverable-reader-error
stream 'namestring-must-follow-sharpsign-p
:position-offset -1 :report 'replace-namestring)
(unread-char (%character condition) stream)
".")))))
(cond ((stringp expression)
(values (parse-namestring expression)))
(t
(%recoverable-reader-error
stream 'non-string-following-sharpsign-p
:position-offset -1
:expected-type 'string :datum expression
:report 'replace-namestring)
#P"."))))
reporting in CHECK - STANDARD - FEATURE - EXPRESSION .
(defvar *input-stream*)
(deftype feature-expression-operator ()
'(member :not :or :and))
(defun check-standard-feature-expression (feature-expression)
(flet ((lose (stream-condition no-stream-condition &rest arguments)
(alexandria:if-let ((stream *input-stream*))
(apply #'%reader-error stream stream-condition
:position-offset -1 arguments)
(apply #'error no-stream-condition arguments))))
(unless (or (symbolp feature-expression)
(alexandria:proper-list-p feature-expression))
(lose 'feature-expression-type-error/reader
'feature-expression-type-error
:datum feature-expression
:expected-type '(or symbol cons)))
(when (consp feature-expression)
(destructuring-bind (operator &rest operands) feature-expression
(unless (typep operator 'feature-expression-operator)
(lose 'feature-expression-type-error/reader
'feature-expression-type-error
:datum operator
:expected-type 'feature-expression-operator))
(when (and (eq operator :not)
(not (alexandria:length= 1 operands)))
(lose 'single-feature-expected/reader 'single-feature-expected
:features (cdr feature-expression)))))))
(defun evaluate-standard-feature-expression
(feature-expression
&key
(check 'check-standard-feature-expression)
(recurse 'evaluate-standard-feature-expression))
(funcall check feature-expression)
(typecase feature-expression
(symbol
(member feature-expression *features* :test #'eq))
((cons (eql :not))
(not (funcall recurse (second feature-expression))))
((cons (eql :or))
(some recurse (rest feature-expression)))
((cons (eql :and))
(every recurse (rest feature-expression)))))
(defun sharpsign-plus-minus (stream char parameter invertp)
(declare (ignore char))
(unless (null parameter)
(numeric-parameter-ignored stream 'sharpsign-plus-minus parameter))
(let ((context (if invertp
:sharpsign-minus
:sharpsign-plus)))
(flet ((read-expression (end-of-file-condition end-of-list-condition
fallback-value)
(handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream end-of-file-condition
:stream-position (stream-position condition)
:context context :report 'inject-nil)
fallback-value)
(end-of-list (condition)
(%recoverable-reader-error
stream end-of-list-condition
:position-offset -1 :context context :report 'inject-nil)
(unread-char (%character condition) stream)
fallback-value))))
(let* ((client *client*)
(feature-expression
(call-with-current-package
client (lambda ()
(let ((*read-suppress* nil))
(with-forbidden-quasiquotation (context)
(read-expression
'end-of-input-after-sharpsign-plus-minus
'feature-expression-must-follow-sharpsign-plus-minus
'(:and)))))
'#:keyword)))
(if (alexandria:xor
(with-simple-restart
(recover (recovery-description 'treat-as-false))
(let ((*input-stream* stream))
(evaluate-feature-expression client feature-expression)))
invertp)
(read-expression 'end-of-input-after-feature-expression
'object-must-follow-feature-expression
nil)
(progn
(setf *skip-reason* (cons context feature-expression))
(let ((*read-suppress* t))
(read-expression 'end-of-input-after-feature-expression
'object-must-follow-feature-expression
nil))
(values)))))))
(defun sharpsign-plus (stream char parameter)
(sharpsign-plus-minus stream char parameter nil))
(defun sharpsign-minus (stream char parameter)
(sharpsign-plus-minus stream char parameter t))
When the - EQUALS reader macro encounters # N = EXPRESSION ,
it associates a marker object with When the - SHARPSIGN
reader macros encounters # N # , the marker for N is looked up and
After reading EXPRESSION , the marker is finalized with the
while reading EXPRESSION , FIXUP - GRAPH is called to replace markers
processing for the current object , see Fixup work tree in
labeled-objects.lisp ) . Subsequent # N # encounters can directly use
labeled-objects.lisp for more details .
work . See work tree in labeled-objects.lisp for details .
(defvar *parent-labeled-object* nil)
(defun sharpsign-equals (stream char parameter)
(declare (ignore char))
(flet ((read-object ()
(handler-case
(read stream t nil t)
((and end-of-file (not incomplete-construct)) (condition)
(%recoverable-reader-error
stream 'end-of-input-after-sharpsign-equals
:stream-position (stream-position condition)
:report 'inject-nil)
nil)
(end-of-list (condition)
(%recoverable-reader-error
stream 'object-must-follow-sharpsign-equals
:position-offset -1 :report 'inject-nil)
(unread-char (%character condition) stream)
nil))))
(when *read-suppress*
(return-from sharpsign-equals (read-object)))
(when (null parameter)
(numeric-parameter-not-supplied stream 'sharpsign-equals)
(return-from sharpsign-equals (read-object)))
(let ((client *client*))
(unless (null (find-labeled-object client parameter))
(%recoverable-reader-error
stream 'sharpsign-equals-label-defined-more-than-once
:position-offset (- (+ 1 (parameter-length parameter) 1))
:label parameter :report 'ignore-label)
(return-from sharpsign-equals (read-object)))
Make a labeled object for the label PARAMETER and read the
to the label PARAMETER in which case LABELED - OBJECT will
(let* ((parent *parent-labeled-object*)
(labeled-object (note-labeled-object
client stream parameter parent))
(result (let ((*parent-labeled-object* labeled-object))
(read-object))))
(when (eq result labeled-object)
(%recoverable-reader-error
stream 'sharpsign-equals-only-refers-to-self
:position-offset -1 :label parameter :report 'inject-nil)
(forget-labeled-object client parameter)
(return-from sharpsign-equals nil))
(finalize-labeled-object client labeled-object result)
result))))
(defun sharpsign-sharpsign (stream char parameter)
(declare (ignore char))
(when *read-suppress*
(return-from sharpsign-sharpsign nil))
(when (null parameter)
(numeric-parameter-not-supplied stream 'sharpsign-equals)
(return-from sharpsign-sharpsign nil))
(let* ((client *client*)
(labeled-object (find-labeled-object client parameter)))
(when (null labeled-object)
(%recoverable-reader-error
stream 'sharpsign-sharpsign-undefined-label
:position-offset (- (+ 1 (parameter-length parameter) 1))
:label parameter :report 'inject-nil)
(return-from sharpsign-sharpsign nil))
(reference-labeled-object client stream labeled-object)))
(defun sharpsign-invalid (stream char parameter)
(declare (ignore parameter))
(%recoverable-reader-error
stream 'sharpsign-invalid
:position-offset -1 :character-found char :report 'inject-nil)
nil)
|
b5c468121d8ddcd9c3e964729df8eb2d5e1eb0a75fa08d687135af2b6c8fbc2e | jacquev6/General | Scanable.signatures.Short.Right.ml | module type S0 = sig
type elt
type t
val scan_short_right: t -> init:elt -> f:(elt -> elt -> Shorten.t * elt) -> t
val scan_short_right_i: t -> init:elt -> f:(i:int -> elt -> elt -> Shorten.t * elt) -> t
val scan_short_right_acc: acc:'acc -> t -> init:elt -> f:(acc:'acc -> elt -> elt -> 'acc * Shorten.t * elt) -> t
end
module type S1 = sig
type 'a t
val scan_short_right: 'a t -> init:'b -> f:('a -> 'b -> Shorten.t * 'b) -> 'b t
val scan_short_right_i: 'a t -> init:'b -> f:(i:int -> 'a -> 'b -> Shorten.t * 'b) -> 'b t
val scan_short_right_acc: acc:'acc -> 'a t -> init:'b -> f:(acc:'acc -> 'a -> 'b -> 'acc * Shorten.t * 'b) -> 'b t
end
| null | https://raw.githubusercontent.com/jacquev6/General/5237123668e939c0cb83aa3e1c4756473336bc7e/src/Traits/Scanable.signatures.Short.Right.ml | ocaml | module type S0 = sig
type elt
type t
val scan_short_right: t -> init:elt -> f:(elt -> elt -> Shorten.t * elt) -> t
val scan_short_right_i: t -> init:elt -> f:(i:int -> elt -> elt -> Shorten.t * elt) -> t
val scan_short_right_acc: acc:'acc -> t -> init:elt -> f:(acc:'acc -> elt -> elt -> 'acc * Shorten.t * elt) -> t
end
module type S1 = sig
type 'a t
val scan_short_right: 'a t -> init:'b -> f:('a -> 'b -> Shorten.t * 'b) -> 'b t
val scan_short_right_i: 'a t -> init:'b -> f:(i:int -> 'a -> 'b -> Shorten.t * 'b) -> 'b t
val scan_short_right_acc: acc:'acc -> 'a t -> init:'b -> f:(acc:'acc -> 'a -> 'b -> 'acc * Shorten.t * 'b) -> 'b t
end
| |
2775beabc634c9a2f762215a88ed60c3a76062e62b16826875124f200a519ca6 | zelark/AoC-2020 | day_07.clj | (ns zelark.aoc-2020.day-07
(:require [clojure.java.io :as io]
[clojure.string :as str]))
;; --- Day 7: Handy Haversacks ---
;;
(def input (slurp (io/resource "input_07.txt")))
(defn parse-entry [entry]
(let [p (re-find #"\w+ \w+" entry)
cs (->> (re-seq #"(\d+) (\w+ \w+)" entry)
(reduce (fn [m [_ v k]] (assoc m k (Long/parseLong v))) {}))]
[p cs]))
(def bags (into {} (map parse-entry (str/split-lines input))))
part 1
(defn find-outer-bags [bags bag]
(let [found-bags (keys (filter #(contains? (val %) bag) bags))]
(into (set found-bags) (mapcat #(find-outer-bags bags %) found-bags))))
103
part 2
(defn count-bags [bags [bag n]]
(* n (apply + 1 (map #(count-bags bags %) (get bags bag)))))
1469
| null | https://raw.githubusercontent.com/zelark/AoC-2020/5417c3514889eb02efc23f6be7d69e29fdfa0376/src/zelark/aoc_2020/day_07.clj | clojure | --- Day 7: Handy Haversacks ---
| (ns zelark.aoc-2020.day-07
(:require [clojure.java.io :as io]
[clojure.string :as str]))
(def input (slurp (io/resource "input_07.txt")))
(defn parse-entry [entry]
(let [p (re-find #"\w+ \w+" entry)
cs (->> (re-seq #"(\d+) (\w+ \w+)" entry)
(reduce (fn [m [_ v k]] (assoc m k (Long/parseLong v))) {}))]
[p cs]))
(def bags (into {} (map parse-entry (str/split-lines input))))
part 1
(defn find-outer-bags [bags bag]
(let [found-bags (keys (filter #(contains? (val %) bag) bags))]
(into (set found-bags) (mapcat #(find-outer-bags bags %) found-bags))))
103
part 2
(defn count-bags [bags [bag n]]
(* n (apply + 1 (map #(count-bags bags %) (get bags bag)))))
1469
|
c8725cd0610c14d925b1ebe214e2558d81dd24ae5233442bec4e870c7310d4a4 | klutometis/aima | zmq-server.scm | #!/usr/bin/env chicken-scheme
[ [ file:~/prg / scm / aima / aima.org::*5.5][5\.5:3 ] ]
(use debug loops zmq)
(let ((socket (make-socket 'rep)))
(bind-socket socket "tcp://*:5555")
(do-times i 4
(let ((message (receive-message* socket)))
(send-message socket message))))
5\.5:3 ends here
| null | https://raw.githubusercontent.com/klutometis/aima/df78e161f22ddb677dbf2fa819e5a4869be22f50/zmq-server.scm | scheme | #!/usr/bin/env chicken-scheme
[ [ file:~/prg / scm / aima / aima.org::*5.5][5\.5:3 ] ]
(use debug loops zmq)
(let ((socket (make-socket 'rep)))
(bind-socket socket "tcp://*:5555")
(do-times i 4
(let ((message (receive-message* socket)))
(send-message socket message))))
5\.5:3 ends here
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.