_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 |
|---|---|---|---|---|---|---|---|---|
0e360532b2895714c94dae8f99cb4991821bb3522f0d73e348dfac3052532604 | IronScheme/IronScheme | procedural.sps | #!r6rs
(import (tests r6rs records procedural)
(tests r6rs test)
(rnrs io simple))
(display "Running tests for (rnrs records procedural)\n")
(run-records-procedural-tests)
(report-test-results)
| null | https://raw.githubusercontent.com/IronScheme/IronScheme/687cde5d4e463a119e4ba28296f2af42a5c4a9df/IronScheme/IronScheme.Console/tests/r6rs/run/records/procedural.sps | scheme | #!r6rs
(import (tests r6rs records procedural)
(tests r6rs test)
(rnrs io simple))
(display "Running tests for (rnrs records procedural)\n")
(run-records-procedural-tests)
(report-test-results)
| |
9539e4571bf6dab9cf0bfec8ae55093bfa2df1ac2a3eea9ffbd2fbcd105f5f2e | footprintanalytics/footprint-web | check_features.clj | (ns metabase.query-processor.middleware.check-features
(:require [metabase.driver :as driver]
[metabase.mbql.schema :as mbql.s]
[metabase.mbql.util :as mbql.u]
[metabase.query-processor.error-type :as qp.error-type]
[metabase.query-processor.store :as qp.store]
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]))
(defn assert-driver-supports
"Assert that the driver/database supports keyword `feature`."
[feature]
(when-not (driver/database-supports? driver/*driver* feature (qp.store/database))
(throw (ex-info (tru "{0} is not supported by this driver." (name feature))
{:type qp.error-type/unsupported-feature
:feature feature}))))
;; TODO - definitely a little incomplete. It would be cool if we cool look at the metadata in the schema namespace and
;; auto-generate this logic
(defn- query->required-features [query]
(into
#{}
(mbql.u/match (:query query)
:stddev
:standard-deviation-aggregations
(join :guard (every-pred map? (comp mbql.s/join-strategies :strategy)))
(let [{:keys [strategy]} join]
(assert-driver-supports strategy)))))
(defn check-features
"Middleware that checks that drivers support the `:features` required to use certain clauses, like `:stddev`."
[{query-type :type, :as query}]
(if-not (= query-type :query)
query
(u/prog1 query
(doseq [required-feature (query->required-features query)]
(assert-driver-supports required-feature)))))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/src/metabase/query_processor/middleware/check_features.clj | clojure | TODO - definitely a little incomplete. It would be cool if we cool look at the metadata in the schema namespace and
auto-generate this logic | (ns metabase.query-processor.middleware.check-features
(:require [metabase.driver :as driver]
[metabase.mbql.schema :as mbql.s]
[metabase.mbql.util :as mbql.u]
[metabase.query-processor.error-type :as qp.error-type]
[metabase.query-processor.store :as qp.store]
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]))
(defn assert-driver-supports
"Assert that the driver/database supports keyword `feature`."
[feature]
(when-not (driver/database-supports? driver/*driver* feature (qp.store/database))
(throw (ex-info (tru "{0} is not supported by this driver." (name feature))
{:type qp.error-type/unsupported-feature
:feature feature}))))
(defn- query->required-features [query]
(into
#{}
(mbql.u/match (:query query)
:stddev
:standard-deviation-aggregations
(join :guard (every-pred map? (comp mbql.s/join-strategies :strategy)))
(let [{:keys [strategy]} join]
(assert-driver-supports strategy)))))
(defn check-features
"Middleware that checks that drivers support the `:features` required to use certain clauses, like `:stddev`."
[{query-type :type, :as query}]
(if-not (= query-type :query)
query
(u/prog1 query
(doseq [required-feature (query->required-features query)]
(assert-driver-supports required-feature)))))
|
513f939f5f3586d993191e3ad7b050ed8726f82591047893ac1fa3c45bb32453 | dalaing/little-languages | Infer.hs | |
Copyright : ( c ) , 2016
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) Dave Laing, 2016
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Test.Term.Infer (
inferTests
) where
-- from 'base'
import Data.Maybe (mapMaybe)
-- from 'tasty'
import Test.Tasty (TestTree, testGroup)
-- from 'tasty-quickcheck'
import Test.Tasty.QuickCheck (testProperty)
-- from 'QuickCheck'
import Test.QuickCheck (Property, property,
(.||.), (===))
-- local
import Term (Term)
import Term.Eval.SmallStep (canStep, smallStep)
import Term.Eval.Value (isValue)
import Term.Gen (AnyTerm(..))
import Term.Infer (inferTerm, inferTermRules, runInfer)
import Type (Type)
import Type.Error (TypeError(..))
inferTests :: TestTree
inferTests = testGroup "infer"
[ testProperty "patterns unique" propPatternUnique
, testProperty "never NoMatchingTypeRule" propNeverNoMatchingTypeRule
, testProperty "well-typed infer" propWellTypedInfer
, testProperty "progress" propProgress
, testProperty "preservation" propPreservation
]
isRight :: Either a b
-> Bool
isRight (Right _) =
True
isRight _ =
False
infer :: Term
-> Either TypeError Type
infer =
runInfer .
inferTerm
propPatternUnique :: AnyTerm
-> Property
propPatternUnique (AnyTerm tm) =
let
matches =
length .
mapMaybe (\i -> fmap runInfer . i $ tm) $
inferTermRules
in
matches === 1
propNeverNoMatchingTypeRule :: AnyTerm
-> Bool
propNeverNoMatchingTypeRule (AnyTerm tm) =
infer tm /= Left NoMatchingTypeRule
-- For now, all of our terms are well typed.
propWellTypedInfer :: AnyTerm
-> Bool
propWellTypedInfer (AnyTerm tm) =
isRight .
infer $
tm
-- Assumes we are dealing with a well-typed term.
propProgress :: AnyTerm
-> Property
propProgress (AnyTerm tm) =
isValue tm .||. canStep tm
-- Assumes we are dealing with a well-typed term.
propPreservation :: AnyTerm
-> Property
propPreservation (AnyTerm tm) =
case smallStep tm of
Nothing -> property True
Just tm' -> infer tm === infer tm'
| null | https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/i/tests/Test/Term/Infer.hs | haskell | from 'base'
from 'tasty'
from 'tasty-quickcheck'
from 'QuickCheck'
local
For now, all of our terms are well typed.
Assumes we are dealing with a well-typed term.
Assumes we are dealing with a well-typed term. | |
Copyright : ( c ) , 2016
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) Dave Laing, 2016
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Test.Term.Infer (
inferTests
) where
import Data.Maybe (mapMaybe)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck (testProperty)
import Test.QuickCheck (Property, property,
(.||.), (===))
import Term (Term)
import Term.Eval.SmallStep (canStep, smallStep)
import Term.Eval.Value (isValue)
import Term.Gen (AnyTerm(..))
import Term.Infer (inferTerm, inferTermRules, runInfer)
import Type (Type)
import Type.Error (TypeError(..))
inferTests :: TestTree
inferTests = testGroup "infer"
[ testProperty "patterns unique" propPatternUnique
, testProperty "never NoMatchingTypeRule" propNeverNoMatchingTypeRule
, testProperty "well-typed infer" propWellTypedInfer
, testProperty "progress" propProgress
, testProperty "preservation" propPreservation
]
isRight :: Either a b
-> Bool
isRight (Right _) =
True
isRight _ =
False
infer :: Term
-> Either TypeError Type
infer =
runInfer .
inferTerm
propPatternUnique :: AnyTerm
-> Property
propPatternUnique (AnyTerm tm) =
let
matches =
length .
mapMaybe (\i -> fmap runInfer . i $ tm) $
inferTermRules
in
matches === 1
propNeverNoMatchingTypeRule :: AnyTerm
-> Bool
propNeverNoMatchingTypeRule (AnyTerm tm) =
infer tm /= Left NoMatchingTypeRule
propWellTypedInfer :: AnyTerm
-> Bool
propWellTypedInfer (AnyTerm tm) =
isRight .
infer $
tm
propProgress :: AnyTerm
-> Property
propProgress (AnyTerm tm) =
isValue tm .||. canStep tm
propPreservation :: AnyTerm
-> Property
propPreservation (AnyTerm tm) =
case smallStep tm of
Nothing -> property True
Just tm' -> infer tm === infer tm'
|
a9489b4aa2671c1c1f1a7804ffa0760d499812f8ed19017634eb2f45b1849534 | jpmonettas/clindex | test_code.cljc | (ns test-code
"A not so well documented namespace"
(:require [clojure.string :as str]
[dep-code :as dep]))
#?(:clj
(defmacro some-macro [a b]
`(+ a b)))
(defn some-function [arg1 arg2]
;; Some comment
(let [a 1
b (+ arg1 arg2)]
(+ a b)))
(defprotocol TheProtocol
(do-something [_]))
(defmulti the-multi-method type)
(defmethod the-multi-method java.lang.String
[s]
(dep/concatenate "Hello " s))
| null | https://raw.githubusercontent.com/jpmonettas/clindex/77097d80a23aa85d2ff50e55645a1452f2dcb3c0/test-resources/test-project/src/test_code.cljc | clojure | Some comment | (ns test-code
"A not so well documented namespace"
(:require [clojure.string :as str]
[dep-code :as dep]))
#?(:clj
(defmacro some-macro [a b]
`(+ a b)))
(defn some-function [arg1 arg2]
(let [a 1
b (+ arg1 arg2)]
(+ a b)))
(defprotocol TheProtocol
(do-something [_]))
(defmulti the-multi-method type)
(defmethod the-multi-method java.lang.String
[s]
(dep/concatenate "Hello " s))
|
db11e84894b7647a6c021c298ce7a15efd4980bae327224b44c39c597d92b00f | geophf/1HaskellADay | Solution.hs | module Y2018.M05.D17.Solution where
-
Today 's problem is partially written out . That provides its own set of
problems : you have code that you are inheriting , and you need to build function-
ality on top of the existing code base .
Not that that ever happens in industry .
So , today you have to learn what exists and how to work with that . This exercise
also works with a customized Writer / State / IO monad , so working in the monadic
domain is part of today 's problem .
HAVE AT IT !
-
Today's Haskell problem is partially written out. That provides its own set of
problems: you have code that you are inheriting, and you need to build function-
ality on top of the existing code base.
Not that that ever happens in industry.
So, today you have to learn what exists and how to work with that. This exercise
also works with a customized Writer/State/IO monad, so working in the monadic
domain is part of today's problem.
HAVE AT IT!
--}
import Codec.Text.IConv (convert, EncodingName)
import Control.Monad.State
import Data.Aeson
import Data.Aeson.Encode.Pretty (encodePretty)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.List (intercalate)
import Data.Maybe (mapMaybe)
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.Types
below imports available via 1HaskellADay git repository
import Data.Logger
import Data.LookupTable
import Data.Time.Stamped (stampIt)
import Store.SQL.Util.Indexed
import Store.SQL.Util.Logging (insertStampedEntries)
import Y2017.M11.D01.Solution (SpecialCharTable)
import Y2018.M04.D02.Solution -- Article
import Y2018.M04.D04.Solution (MemoizedAuthors)
import Y2018.M05.D08.Solution
-
In a prior exercise ( see above import ) we were able to triage articles we are
getting from a REST endpoint into NEW , UPDATED , REDUNDANT vis - a - vis already-
stored articles in a PostgreSQL database .
Today we 're going to be handling two cases REDUNDANT and UPDATED ; tomorrow ,
we 'll handle the case where we insert NEW articles into the database .
( justification : REDUNDANT and UPDATED , together , are less work than assembling
everything that needs to go into inserting a NEW article )
Our dispatch function is as follows :
-
In a prior exercise (see above import) we were able to triage articles we are
getting from a REST endpoint into NEW, UPDATED, REDUNDANT vis-a-vis already-
stored articles in a PostgreSQL database.
Today we're going to be handling two cases REDUNDANT and UPDATED; tomorrow,
we'll handle the case where we insert NEW articles into the database.
(justification: REDUNDANT and UPDATED, together, are less work than assembling
everything that needs to go into inserting a NEW article)
Our dispatch function is as follows:
--}
processArts :: Connection -> Integer -> LookupTable -> SpecialCharTable
-> (Triage, [WPJATI]) -> MemoizedAuthors IO
processArts conn _ lk _ (REDUNDANT, infos) =
roff conn lk INFO
("Ignoring " ++ show (length infos) ++ " redundant articles.")
processArts conn _ lk _ (UPDATED, infos) =
lift (mapM_ (\wpj -> updateArts conn [wpj] >>= updateJSON conn wpj) infos) >>
roff conn lk INFO ("Updated " ++ show (length infos) ++ " articles.")
processArts conn pidx lk spc (NEW, infos) = undefined
-- I write all the above to show the work-flow. For redundant articles, we
-- simply log that they are redundant, so we need a logging function:
roff :: Connection -> LookupTable -> Severity -> String -> MemoizedAuthors IO
roff conn severityLookup level msg = lift (roff' conn severityLookup level msg)
roff' :: Connection -> LookupTable -> Severity -> String -> IO ()
roff' conn sev lvl =
stampIt . Entry lvl "ETL" "Y2018.M05.D09.Solution" >=> \ent ->
if lvl > DEBUG then print ent else return () >>
insertStampedEntries conn sev [ent]
For updating articles we need to define updateArts and updateJSON
-- UPDATE UPDATE UPDATE -------------------------------------------------------
-- ... updating articles is much simpler (lift-n-shift from Y2018.M02.D07):
updateArtStmt :: WPJATI -> Query
updateArtStmt (ATI _ (_, Art (Art' ix _ up _ _ _ _ _ _) pl ht tit sum) (Just (IxV idx _))) =
let (p:arams) = mapMaybe sequence
[("excerpt", Just sum),
("update_dt", show <$> up),
("plain_text", Just pl),
("html", Just ht)]
strfn (a,b) = a ++ ('=':enquote b)
rendered = strfn p ++ concatMap ((", " ++) . strfn) arams
in Query (B.pack ("UPDATE article SET " ++ rendered
++ " WHERE art_id=" ++ show ix ++ " returning json_id"))
enquote :: String -> String
enquote str = quote ++ convert' "LATIN1" "UTF8" str ++ quote
where quote = "$sqs$"
takes a string converts it from " LATIN1 " to " UTF8 "
( hint : see ) and surrounds it with ' $ sqs$ '
convert' :: EncodingName -> EncodingName -> String -> String
convert' src dest = BL.unpack . convert src dest . BL.pack
and we get the i d from the Index of the IxValue of the ArticleMetaData
updateArts :: Connection -> [WPJATI] -> IO [Index]
updateArts conn arts =
-- it looks like, because of the nature of the return, that we have
-- to do this as a mapM function. m'kay. This will hurt.
concat <$> mapM (query_ conn . updateArtStmt) arts
-- we also have to update the JSON block for the article
updateJSON :: Connection -> WPJATI -> [Index] -> IO ()
updateJSON conn wpj =
void . execute_ conn . Query . B.pack
. intercalate "; " . map (updateJSONStmt (fst $ article wpj))
updateJSONStmt :: Value -> Index -> String
updateJSONStmt val ix =
"UPDATE article_json SET json=" ++ enquote (BL.unpack (encodePretty val))
++ " WHERE id=" ++ show ix
-- and do some logging and auditing here and there, don't forget to tie in
-- author insertion using memoization, and there you go! 'SIMPLE'! ... um.
we 'll look at processing articles that are NEW tomorrow .
| null | https://raw.githubusercontent.com/geophf/1HaskellADay/514792071226cd1e2ba7640af942667b85601006/exercises/HAD/Y2018/M05/D17/Solution.hs | haskell | }
Article
}
I write all the above to show the work-flow. For redundant articles, we
simply log that they are redundant, so we need a logging function:
UPDATE UPDATE UPDATE -------------------------------------------------------
... updating articles is much simpler (lift-n-shift from Y2018.M02.D07):
it looks like, because of the nature of the return, that we have
to do this as a mapM function. m'kay. This will hurt.
we also have to update the JSON block for the article
and do some logging and auditing here and there, don't forget to tie in
author insertion using memoization, and there you go! 'SIMPLE'! ... um. | module Y2018.M05.D17.Solution where
-
Today 's problem is partially written out . That provides its own set of
problems : you have code that you are inheriting , and you need to build function-
ality on top of the existing code base .
Not that that ever happens in industry .
So , today you have to learn what exists and how to work with that . This exercise
also works with a customized Writer / State / IO monad , so working in the monadic
domain is part of today 's problem .
HAVE AT IT !
-
Today's Haskell problem is partially written out. That provides its own set of
problems: you have code that you are inheriting, and you need to build function-
ality on top of the existing code base.
Not that that ever happens in industry.
So, today you have to learn what exists and how to work with that. This exercise
also works with a customized Writer/State/IO monad, so working in the monadic
domain is part of today's problem.
HAVE AT IT!
import Codec.Text.IConv (convert, EncodingName)
import Control.Monad.State
import Data.Aeson
import Data.Aeson.Encode.Pretty (encodePretty)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.List (intercalate)
import Data.Maybe (mapMaybe)
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.Types
below imports available via 1HaskellADay git repository
import Data.Logger
import Data.LookupTable
import Data.Time.Stamped (stampIt)
import Store.SQL.Util.Indexed
import Store.SQL.Util.Logging (insertStampedEntries)
import Y2017.M11.D01.Solution (SpecialCharTable)
import Y2018.M04.D04.Solution (MemoizedAuthors)
import Y2018.M05.D08.Solution
-
In a prior exercise ( see above import ) we were able to triage articles we are
getting from a REST endpoint into NEW , UPDATED , REDUNDANT vis - a - vis already-
stored articles in a PostgreSQL database .
Today we 're going to be handling two cases REDUNDANT and UPDATED ; tomorrow ,
we 'll handle the case where we insert NEW articles into the database .
( justification : REDUNDANT and UPDATED , together , are less work than assembling
everything that needs to go into inserting a NEW article )
Our dispatch function is as follows :
-
In a prior exercise (see above import) we were able to triage articles we are
getting from a REST endpoint into NEW, UPDATED, REDUNDANT vis-a-vis already-
stored articles in a PostgreSQL database.
Today we're going to be handling two cases REDUNDANT and UPDATED; tomorrow,
we'll handle the case where we insert NEW articles into the database.
(justification: REDUNDANT and UPDATED, together, are less work than assembling
everything that needs to go into inserting a NEW article)
Our dispatch function is as follows:
processArts :: Connection -> Integer -> LookupTable -> SpecialCharTable
-> (Triage, [WPJATI]) -> MemoizedAuthors IO
processArts conn _ lk _ (REDUNDANT, infos) =
roff conn lk INFO
("Ignoring " ++ show (length infos) ++ " redundant articles.")
processArts conn _ lk _ (UPDATED, infos) =
lift (mapM_ (\wpj -> updateArts conn [wpj] >>= updateJSON conn wpj) infos) >>
roff conn lk INFO ("Updated " ++ show (length infos) ++ " articles.")
processArts conn pidx lk spc (NEW, infos) = undefined
roff :: Connection -> LookupTable -> Severity -> String -> MemoizedAuthors IO
roff conn severityLookup level msg = lift (roff' conn severityLookup level msg)
roff' :: Connection -> LookupTable -> Severity -> String -> IO ()
roff' conn sev lvl =
stampIt . Entry lvl "ETL" "Y2018.M05.D09.Solution" >=> \ent ->
if lvl > DEBUG then print ent else return () >>
insertStampedEntries conn sev [ent]
For updating articles we need to define updateArts and updateJSON
updateArtStmt :: WPJATI -> Query
updateArtStmt (ATI _ (_, Art (Art' ix _ up _ _ _ _ _ _) pl ht tit sum) (Just (IxV idx _))) =
let (p:arams) = mapMaybe sequence
[("excerpt", Just sum),
("update_dt", show <$> up),
("plain_text", Just pl),
("html", Just ht)]
strfn (a,b) = a ++ ('=':enquote b)
rendered = strfn p ++ concatMap ((", " ++) . strfn) arams
in Query (B.pack ("UPDATE article SET " ++ rendered
++ " WHERE art_id=" ++ show ix ++ " returning json_id"))
enquote :: String -> String
enquote str = quote ++ convert' "LATIN1" "UTF8" str ++ quote
where quote = "$sqs$"
takes a string converts it from " LATIN1 " to " UTF8 "
( hint : see ) and surrounds it with ' $ sqs$ '
convert' :: EncodingName -> EncodingName -> String -> String
convert' src dest = BL.unpack . convert src dest . BL.pack
and we get the i d from the Index of the IxValue of the ArticleMetaData
updateArts :: Connection -> [WPJATI] -> IO [Index]
updateArts conn arts =
concat <$> mapM (query_ conn . updateArtStmt) arts
updateJSON :: Connection -> WPJATI -> [Index] -> IO ()
updateJSON conn wpj =
void . execute_ conn . Query . B.pack
. intercalate "; " . map (updateJSONStmt (fst $ article wpj))
updateJSONStmt :: Value -> Index -> String
updateJSONStmt val ix =
"UPDATE article_json SET json=" ++ enquote (BL.unpack (encodePretty val))
++ " WHERE id=" ++ show ix
we 'll look at processing articles that are NEW tomorrow .
|
db839e82d61b744d39dfd8fccd5200af4c41cbc3c3b022ae9865a57ffb2dba7b | moostang/autolisp | chainage_label.lsp | ;; ------------------------------------------------------------------------- ;;
;; ------------------------------------------------------------------------- ;;
;; FUNCTION chainage_label ;;
;; ----------------------- ;;
Converts a numeric chainage value of XXXX into a string X+XXX ; ;
;; ;;
;; INPUT: ;;
;; ;;
;; chainage, ;;
;; Chainage value (FLOAT) ;;
;; ;;
;; OUTPUT (GLOBAL): ;;
;; ;;
;; ;;
;; DEPENDENCIES: None ;;
;; ;;
;; USAGE: ;;
;; ;;
( ) ; ;
;; ;;
Created on : May 7 , 2019 ; ;
Written by : ; ;
;; ------------------------------------------------------------------------- ;;
;; ------------------------------------------------------------------------- ;;
(defun chainageLabel (chainage / prefix suffix
)
(setq chainage (fix chainage))
(if (< chainage 1000)
(progn
(setq suffix (rtos chainage))
(while (< (strlen suffix) 3)
(setq suffix (strcat "0" suffix))
);; while
(setq label (strcat "0+" suffix))
);; progn
(progn
(setq prefix (substr (rtos (fix (/ chainage 1000))) 1)
suffix (substr (rtos chainage ) (+ (strlen prefix) 1) 3)
label (strcat prefix "+" suffix)
)
);; progn
);; if
);; defun
;; ------------------------------------------------------------------------- ;;
;; ------------------------------------------------------------------------- ;;
| null | https://raw.githubusercontent.com/moostang/autolisp/e4f9e624175880a6383850bae58718c48e31ff43/chainage_label.lsp | lisp | ------------------------------------------------------------------------- ;;
------------------------------------------------------------------------- ;;
FUNCTION chainage_label ;;
----------------------- ;;
;
;;
INPUT: ;;
;;
chainage, ;;
Chainage value (FLOAT) ;;
;;
OUTPUT (GLOBAL): ;;
;;
;;
DEPENDENCIES: None ;;
;;
USAGE: ;;
;;
;
;;
;
;
------------------------------------------------------------------------- ;;
------------------------------------------------------------------------- ;;
while
progn
progn
if
defun
------------------------------------------------------------------------- ;;
------------------------------------------------------------------------- ;; | (defun chainageLabel (chainage / prefix suffix
)
(setq chainage (fix chainage))
(if (< chainage 1000)
(progn
(setq suffix (rtos chainage))
(while (< (strlen suffix) 3)
(setq suffix (strcat "0" suffix))
(setq label (strcat "0+" suffix))
(progn
(setq prefix (substr (rtos (fix (/ chainage 1000))) 1)
suffix (substr (rtos chainage ) (+ (strlen prefix) 1) 3)
label (strcat prefix "+" suffix)
)
|
395bcc2df232449881994666c8fc9144976307f8997e811cfe16ab0ebda67345 | Swirrl/cubiql | data.clj | (ns cubiql.data
(:require
[grafter.rdf.repository :as repo]
[grafter.rdf.formats :as formats]
[grafter.rdf :refer [add]]
[grafter.rdf.formats :as formats]
[clojure.java.io :as io])
(:import [java.io File FileFilter]
[java.net URI URISyntaxException]))
(defn- ^FileFilter create-file-filter [p]
(reify FileFilter
(accept [_this file]
(p file))))
(defn- is-rdf-file? [^File file]
(some? (formats/filename->rdf-format file)))
(defn directory-repo
"Creates a sail repository from a directory containing RDF files"
[^File dir]
{:pre [(and (.isDirectory dir) (.exists dir))]}
(let [rdf-files (.listFiles dir (create-file-filter is-rdf-file?))]
(apply repo/fixture-repo rdf-files)))
(defn file->endpoint [^File f]
(if (.exists f)
(if (.isDirectory f)
(directory-repo f)
(repo/fixture-repo f))
(throw (IllegalArgumentException. (format "%s does not exist" f)))))
(defmulti uri->endpoint (fn [^URI uri] (keyword (.getScheme uri))))
(defmethod uri->endpoint :http [^URI uri]
(repo/sparql-repo uri))
(defmethod uri->endpoint :https [^URI uri]
(repo/sparql-repo uri))
(defmethod uri->endpoint :file [^URI uri]
(let [f (File. uri)]
(file->endpoint f)))
(defmethod uri->endpoint :default [^URI uri]
(let [f (File. (str uri))]
(file->endpoint f)))
(defn parse-endpoint [^String endpoint-str]
(try
(let [uri (URI. endpoint-str)]
(uri->endpoint uri))
(catch URISyntaxException ex
(let [f (io/file endpoint-str)]
(file->endpoint f)))))
(defn get-test-repo []
(directory-repo (io/file "data")))
(defn get-scotland-repo []
(repo/sparql-repo "-drafter-sg.publishmydata.com/v1/sparql/live"))
| null | https://raw.githubusercontent.com/Swirrl/cubiql/67efdc51750b9ac4fd1cdfbcddfb80398189807f/src/cubiql/data.clj | clojure | (ns cubiql.data
(:require
[grafter.rdf.repository :as repo]
[grafter.rdf.formats :as formats]
[grafter.rdf :refer [add]]
[grafter.rdf.formats :as formats]
[clojure.java.io :as io])
(:import [java.io File FileFilter]
[java.net URI URISyntaxException]))
(defn- ^FileFilter create-file-filter [p]
(reify FileFilter
(accept [_this file]
(p file))))
(defn- is-rdf-file? [^File file]
(some? (formats/filename->rdf-format file)))
(defn directory-repo
"Creates a sail repository from a directory containing RDF files"
[^File dir]
{:pre [(and (.isDirectory dir) (.exists dir))]}
(let [rdf-files (.listFiles dir (create-file-filter is-rdf-file?))]
(apply repo/fixture-repo rdf-files)))
(defn file->endpoint [^File f]
(if (.exists f)
(if (.isDirectory f)
(directory-repo f)
(repo/fixture-repo f))
(throw (IllegalArgumentException. (format "%s does not exist" f)))))
(defmulti uri->endpoint (fn [^URI uri] (keyword (.getScheme uri))))
(defmethod uri->endpoint :http [^URI uri]
(repo/sparql-repo uri))
(defmethod uri->endpoint :https [^URI uri]
(repo/sparql-repo uri))
(defmethod uri->endpoint :file [^URI uri]
(let [f (File. uri)]
(file->endpoint f)))
(defmethod uri->endpoint :default [^URI uri]
(let [f (File. (str uri))]
(file->endpoint f)))
(defn parse-endpoint [^String endpoint-str]
(try
(let [uri (URI. endpoint-str)]
(uri->endpoint uri))
(catch URISyntaxException ex
(let [f (io/file endpoint-str)]
(file->endpoint f)))))
(defn get-test-repo []
(directory-repo (io/file "data")))
(defn get-scotland-repo []
(repo/sparql-repo "-drafter-sg.publishmydata.com/v1/sparql/live"))
| |
aef399fd850a03997af53eb27e2753c55c83bb2aedee2f7b6819aba7471b2a3a | sjl/euler | 001.lisp | (defpackage :euler/001 #.euler:*use*)
(in-package :euler/001)
If we list all the natural numbers below 10 that are multiples of 3 or 5 , we
get 3 , 5 , 6 and 9 . The sum of these multiples is 23 .
;;
Find the sum of all the multiples of 3 or 5 below 1000 .
(define-problem (1 233168)
(iterate (for i :from 1 :below 1000)
(when (or (dividesp i 3)
(dividesp i 5))
(summing i))))
| null | https://raw.githubusercontent.com/sjl/euler/29cd8242172a2d11128439bb99217a0a859057ed/src/problems/001.lisp | lisp | (defpackage :euler/001 #.euler:*use*)
(in-package :euler/001)
If we list all the natural numbers below 10 that are multiples of 3 or 5 , we
get 3 , 5 , 6 and 9 . The sum of these multiples is 23 .
Find the sum of all the multiples of 3 or 5 below 1000 .
(define-problem (1 233168)
(iterate (for i :from 1 :below 1000)
(when (or (dividesp i 3)
(dividesp i 5))
(summing i))))
| |
4b7f3c50838222362235fae816730b18d57158baad13e5f6a08cf6a8b27eecdb | JPMoresmau/dbIDE | Types.hs | # LANGUAGE RecordWildCards #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE DataKinds #
# LANGUAGE DeriveDataTypeable , TemplateHaskell , OverloadedStrings #
module Language.Haskell.ASBrowser.Types where
import Language.Haskell.ASBrowser.Utils
import Control.Arrow
import Control.Monad
import Data.Data
import Data.SafeCopy hiding (Version)
import Data.Text hiding (empty,map,drop)
import Distribution.Version
import Distribution.Text (simpleParse, display)
import Data.IxSet.Typed
import Data.Time
import Data.Default
import Data.String
import Data.Version
import Text.ParserCombinators.ReadP (readP_to_S)
import Data.Maybe
import Data.Aeson
import Data.Aeson.TH
import qualified Text.PrettyPrint as PP
import qualified Text.PrettyPrint.HughesPJClass as PP
newtype PackageName = PackageName {unPkgName :: Text}
deriving (Show,Read,Eq,Ord,Typeable,Data)
} '' PackageName
instance ToJSON PackageName where
toJSON = toJSON . unPkgName
instance FromJSON PackageName where
parseJSON (String s) = pure $ PackageName s
parseJSON _ = mzero
instance IsString PackageName where
fromString = PackageName . pack
newtype PackageNameCI = PackageNameCI {unPkgNameCI :: Text}
deriving (Show,Read,Eq,Ord,Typeable,Data)
'' PackageNameCI
instance ToJSON PackageNameCI where
toJSON = toJSON . unPkgNameCI
instance FromJSON PackageNameCI where
parseJSON (String s) = pure $ PackageNameCI s
parseJSON _ = mzero
textToPackageNameCI :: Text -> PackageNameCI
textToPackageNameCI = PackageNameCI . Data.Text.toLower
textTupleToPackageNameCI :: (Text,Text) -> (PackageNameCI,PackageNameCI)
textTupleToPackageNameCI = join (***) textToPackageNameCI
deriveSafeCopy 0 'base ''PackageName
deriveSafeCopy 0 'base ''PackageNameCI
deriveSafeCopy 0 'base ''Version
deriveSafeCopy 0 'base ''VersionRange
instance IsString Version where
fromString = fst . Prelude.head . Prelude.filter (\(_,rest)->Prelude.null rest). readP_to_S parseVersion
instance ToJSON Version where
toJSON = String . pack . showVersion
instance FromJSON Version where
parseJSON (String v)=pure $ fromString $ unpack v
parseJSON _ = fail "Version"
instance IsString VersionRange where
fromString = fromJust . simpleParse
instance ToJSON VersionRange where
toJSON = String . pack . display
instance FromJSON VersionRange where
parseJSON (String v)=pure $ fromString $ unpack v
parseJSON _ = fail "VersionRange"
data Local = Local | Packaged
deriving (Show, Read, Eq, Ord, Bounded,Enum,Typeable,Data)
deriveSafeCopy 0 'base ''Local
deriveJSON defaultOptions ''Local
data Expose = Exposed | Included | Main FilePath
deriving (Show, Read, Eq, Ord, Typeable,Data)
deriveSafeCopy 0 'base ''Expose
deriveJSON defaultOptions ''Expose
data PackageMetaData = PackageMetaData
{ pkgMDAuthor :: !Text
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''PackageMetaData
deriveJSON defaultOptions{fieldLabelModifier=jsonField 3} ''PackageMetaData
instance Default PackageMetaData where
def = PackageMetaData ""
data Doc = Doc
{ dShort :: !Text
, dLong :: !Text
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveJSON defaultOptions{fieldLabelModifier=jsonField 1} ''Doc
instance Default Doc where
def = Doc "" ""
deriveSafeCopy 0 'base ''Doc
newtype ComponentName = ComponentName {unCompName :: Text}
deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''ComponentName
instance IsString ComponentName where
fromString = ComponentName . pack
'' ComponentName
instance ToJSON ComponentName where
toJSON = toJSON . unCompName
instance FromJSON ComponentName where
parseJSON (String s) = pure $ ComponentName s
parseJSON _ = mzero
data ComponentType = Library | Executable | Test | BenchMark
deriving (Show,Read,Eq,Ord,Bounded,Enum,Typeable,Data)
deriveSafeCopy 0 'base ''ComponentType
deriveJSON defaultOptions ''ComponentType
newtype URL = URL {unURLName :: Text}
deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''URL
instance IsString URL where
fromString = URL . pack
'' URL
instance ToJSON URL where
toJSON = toJSON . unURLName
instance FromJSON URL where
parseJSON (String s) = pure $ URL s
parseJSON _ = mzero
data URLs = URLs
{ uSrcURL :: !(Maybe URL)
, uDocURL :: !(Maybe URL)
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''URLs
deriveJSON defaultOptions{fieldLabelModifier=jsonField 1} ''URLs
instance Default URLs where
def = URLs Nothing Nothing
data PackageKey = PackageKey
{ pkgName :: !PackageName
, pkgVersion :: !Version
, pkgLocal :: !Local
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''PackageKey
deriveJSON defaultOptions{fieldLabelModifier=jsonField 3} ''PackageKey
instance PP.Pretty PackageKey where
pPrint PackageKey{..} = PP.text (unpack $ unPkgName pkgName) PP.<> PP.char '-' PP.<> (PP.text $ showVersion pkgVersion)
data PackageRef = PackageRef
{ prName :: !PackageName
, prRange :: !VersionRange
} deriving (Show,Read,Eq,Typeable,Data)
deriveSafeCopy 0 'base ''PackageRef
deriveJSON defaultOptions{fieldLabelModifier=jsonField 2} ''PackageRef
instance Ord PackageRef where
compare (PackageRef name1 range1) (PackageRef name2 range2) =
case compare name1 name2 of
EQ -> compare (show range1) (show range2)
c -> c
data ComponentKey = ComponentKey
{ cPackageKey :: !PackageKey
, cName :: !ComponentName
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''ComponentKey
deriveJSON defaultOptions{fieldLabelModifier=jsonField 1} ''ComponentKey
data Component = Component
{ cKey :: !ComponentKey
, cType :: !ComponentType
, cRefs :: [PackageRef]
do n't use the Extension type since it only got instance recently , etc
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''Component
deriveJSON defaultOptions{fieldLabelModifier=jsonField 1} ''Component
newtype ModuleName = ModuleName {unModName :: Text}
deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''ModuleName
'' ModuleName
instance ToJSON ModuleName where
toJSON = toJSON . unModName
instance FromJSON ModuleName where
parseJSON (String s) = pure $ ModuleName s
parseJSON _ = mzero
instance IsString ModuleName where
fromString = ModuleName . pack
data Location = Location
{ lLine :: !Int
, lColumn :: !Int
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''Location
deriveJSON defaultOptions{fieldLabelModifier=jsonField 1} ''Location
data MarkerLevel = MLError | MLWarning | MLInfo
deriving (Show,Read,Eq,Ord,Typeable,Data,Bounded,Enum)
deriveSafeCopy 0 'base ''MarkerLevel
deriveJSON defaultOptions ''MarkerLevel
data Marker = Marker
{ mText :: Text
, mLevel :: MarkerLevel
, mLocation :: Location
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''Marker
deriveJSON defaultOptions{fieldLabelModifier=jsonField 1} ''Marker
newtype DeclName = DeclName {unDeclName :: Text}
deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''DeclName
'' DeclName
instance ToJSON DeclName where
toJSON = toJSON . unDeclName
instance FromJSON DeclName where
parseJSON (String s) = pure $ DeclName s
parseJSON _ = mzero
instance IsString DeclName where
fromString = DeclName . pack
data DeclType = DeclData | DeclNewType | DeclClass | DeclInstance | DeclType
| DeclDataFamily | DeclTypeFamily | DeclDataInstance | DeclTypeInstance
| DeclFunction | DeclConstructor | DeclMethod
deriving (Show, Read, Eq, Ord, Bounded,Enum,Typeable,Data)
deriveSafeCopy 0 'base ''DeclType
deriveJSON defaultOptions ''DeclType
data WriteDate = WriteDate
{ wdCreated :: UTCTime
, wdUpdated :: UTCTime
} deriving (Show, Read, Eq, Ord, Typeable,Data)
deriveSafeCopy 0 'base ''WriteDate
data Package = Package
{ pkgKey :: !PackageKey
, pkgDoc :: !Doc
, pkgMeta :: !PackageMetaData
, pkgDocURL :: !(Maybe URL)
, pkgModulesAnalysedDate :: !(Maybe UTCTime)
, pkgDeclsAnalysedDate :: !(Maybe UTCTime)
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''Package
deriveJSON defaultOptions{fieldLabelModifier=jsonField 3} ''Package
data ModuleKey = ModuleKey
{ modName :: ModuleName
, modPackageKey :: PackageKey
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''ModuleKey
deriveJSON defaultOptions{fieldLabelModifier=jsonField 3} ''ModuleKey
data ModuleInclusion = ModuleInclusion
{ miComponent :: ComponentName
, miExpose :: Expose
, miMarkers :: Maybe [Marker]
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''ModuleInclusion
deriveJSON defaultOptions{fieldLabelModifier=jsonField 2} ''ModuleInclusion
data Module = Module
{ modKey :: ModuleKey
, modDoc :: Doc
, modComponents :: [ModuleInclusion]
, modURLs :: URLs
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''Module
deriveJSON defaultOptions{fieldLabelModifier=jsonField 3} ''Module
data DeclKey = DeclKey
{ decName :: DeclName
, decModuleKey :: ModuleKey
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''DeclKey
deriveJSON defaultOptions{fieldLabelModifier=jsonField 3} ''DeclKey
data Decl = Decl
{ dKey :: DeclKey
, dType :: DeclType
, dSignature :: Text
, dDoc :: Doc
, dURLs :: URLs
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''Decl
deriveJSON defaultOptions{fieldLabelModifier=jsonField 1} ''Decl
data FullPackage = FullPackage
{ fpPackage :: !Package
, fpComponents :: ![Component]
, fpModules :: ![Module]
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''FullPackage
deriveJSON defaultOptions{fieldLabelModifier=jsonField 2} ''FullPackage
type ComponentIxs = '[PackageKey, ComponentKey,PackageName]
type IxComponent = IxSet ComponentIxs Component
instance Indexable ComponentIxs Component where
indices = ixList
(ixFun $ \c -> [ cPackageKey $ cKey c ])
(ixFun $ \c -> [ cKey c ])
(ixFun $ \c -> Prelude.map prName $ cRefs c)
type PackageIxs = '[PackageKey, PackageName, Local, Text]
type IxPackage = IxSet PackageIxs Package
packageSep :: Char
packageSep = '-'
instance Indexable PackageIxs Package where
indices = ixList
(ixFun $ \pkg -> [ pkgKey pkg ])
(ixFun $ \pkg -> [pkgName $ pkgKey pkg] )
(ixFun $ \pkg -> [ pkgLocal $ pkgKey pkg ])
(ixFun $ \pkg -> splitCaseFold packageSep $ unPkgName $ pkgName $ pkgKey pkg )
type ModuleIxs = '[PackageKey, ComponentKey, Text, ModuleKey]
type IxModule = IxSet ModuleIxs Module
moduleSep :: Char
moduleSep = '-'
instance Indexable ModuleIxs Module where
indices = ixList
(ixFun $ \mo -> [ modPackageKey $ modKey mo ])
(ixFun $ \mo -> Prelude.map ((ComponentKey $ modPackageKey $ modKey mo) . miComponent) $ modComponents mo)
(ixFun $ \mo -> splitCaseFold moduleSep $ unModName $ modName $ modKey mo)
(ixFun $ \mo -> [ modKey mo ])
type DeclIxs = '[PackageKey, ModuleKey, DeclName]
type IxDecl = IxSet DeclIxs Decl
instance Indexable DeclIxs Decl where
indices = ixList
(ixFun $ \de -> [modPackageKey $ decModuleKey $ dKey de])
(ixFun $ \de -> [decModuleKey $ dKey de])
(ixFun $ \de -> [decName $ dKey de])
data Database = Database
{ dPackages :: IxPackage
, dComponents :: IxComponent
, dModules :: IxModule
, dDecls :: IxDecl
} deriving (Typeable)
deriveSafeCopy 0 'base ''Database
instance Default Database where
def = Database empty empty empty empty
| null | https://raw.githubusercontent.com/JPMoresmau/dbIDE/dae37edf67fbe55660e7e22c9c5356d0ada47c61/as-browser/src/Language/Haskell/ASBrowser/Types.hs | haskell | # LANGUAGE TypeSynonymInstances # | # LANGUAGE RecordWildCards #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FlexibleInstances #
# LANGUAGE DataKinds #
# LANGUAGE DeriveDataTypeable , TemplateHaskell , OverloadedStrings #
module Language.Haskell.ASBrowser.Types where
import Language.Haskell.ASBrowser.Utils
import Control.Arrow
import Control.Monad
import Data.Data
import Data.SafeCopy hiding (Version)
import Data.Text hiding (empty,map,drop)
import Distribution.Version
import Distribution.Text (simpleParse, display)
import Data.IxSet.Typed
import Data.Time
import Data.Default
import Data.String
import Data.Version
import Text.ParserCombinators.ReadP (readP_to_S)
import Data.Maybe
import Data.Aeson
import Data.Aeson.TH
import qualified Text.PrettyPrint as PP
import qualified Text.PrettyPrint.HughesPJClass as PP
newtype PackageName = PackageName {unPkgName :: Text}
deriving (Show,Read,Eq,Ord,Typeable,Data)
} '' PackageName
instance ToJSON PackageName where
toJSON = toJSON . unPkgName
instance FromJSON PackageName where
parseJSON (String s) = pure $ PackageName s
parseJSON _ = mzero
instance IsString PackageName where
fromString = PackageName . pack
newtype PackageNameCI = PackageNameCI {unPkgNameCI :: Text}
deriving (Show,Read,Eq,Ord,Typeable,Data)
'' PackageNameCI
instance ToJSON PackageNameCI where
toJSON = toJSON . unPkgNameCI
instance FromJSON PackageNameCI where
parseJSON (String s) = pure $ PackageNameCI s
parseJSON _ = mzero
textToPackageNameCI :: Text -> PackageNameCI
textToPackageNameCI = PackageNameCI . Data.Text.toLower
textTupleToPackageNameCI :: (Text,Text) -> (PackageNameCI,PackageNameCI)
textTupleToPackageNameCI = join (***) textToPackageNameCI
deriveSafeCopy 0 'base ''PackageName
deriveSafeCopy 0 'base ''PackageNameCI
deriveSafeCopy 0 'base ''Version
deriveSafeCopy 0 'base ''VersionRange
instance IsString Version where
fromString = fst . Prelude.head . Prelude.filter (\(_,rest)->Prelude.null rest). readP_to_S parseVersion
instance ToJSON Version where
toJSON = String . pack . showVersion
instance FromJSON Version where
parseJSON (String v)=pure $ fromString $ unpack v
parseJSON _ = fail "Version"
instance IsString VersionRange where
fromString = fromJust . simpleParse
instance ToJSON VersionRange where
toJSON = String . pack . display
instance FromJSON VersionRange where
parseJSON (String v)=pure $ fromString $ unpack v
parseJSON _ = fail "VersionRange"
data Local = Local | Packaged
deriving (Show, Read, Eq, Ord, Bounded,Enum,Typeable,Data)
deriveSafeCopy 0 'base ''Local
deriveJSON defaultOptions ''Local
data Expose = Exposed | Included | Main FilePath
deriving (Show, Read, Eq, Ord, Typeable,Data)
deriveSafeCopy 0 'base ''Expose
deriveJSON defaultOptions ''Expose
data PackageMetaData = PackageMetaData
{ pkgMDAuthor :: !Text
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''PackageMetaData
deriveJSON defaultOptions{fieldLabelModifier=jsonField 3} ''PackageMetaData
instance Default PackageMetaData where
def = PackageMetaData ""
data Doc = Doc
{ dShort :: !Text
, dLong :: !Text
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveJSON defaultOptions{fieldLabelModifier=jsonField 1} ''Doc
instance Default Doc where
def = Doc "" ""
deriveSafeCopy 0 'base ''Doc
newtype ComponentName = ComponentName {unCompName :: Text}
deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''ComponentName
instance IsString ComponentName where
fromString = ComponentName . pack
'' ComponentName
instance ToJSON ComponentName where
toJSON = toJSON . unCompName
instance FromJSON ComponentName where
parseJSON (String s) = pure $ ComponentName s
parseJSON _ = mzero
data ComponentType = Library | Executable | Test | BenchMark
deriving (Show,Read,Eq,Ord,Bounded,Enum,Typeable,Data)
deriveSafeCopy 0 'base ''ComponentType
deriveJSON defaultOptions ''ComponentType
newtype URL = URL {unURLName :: Text}
deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''URL
instance IsString URL where
fromString = URL . pack
'' URL
instance ToJSON URL where
toJSON = toJSON . unURLName
instance FromJSON URL where
parseJSON (String s) = pure $ URL s
parseJSON _ = mzero
data URLs = URLs
{ uSrcURL :: !(Maybe URL)
, uDocURL :: !(Maybe URL)
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''URLs
deriveJSON defaultOptions{fieldLabelModifier=jsonField 1} ''URLs
instance Default URLs where
def = URLs Nothing Nothing
data PackageKey = PackageKey
{ pkgName :: !PackageName
, pkgVersion :: !Version
, pkgLocal :: !Local
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''PackageKey
deriveJSON defaultOptions{fieldLabelModifier=jsonField 3} ''PackageKey
instance PP.Pretty PackageKey where
pPrint PackageKey{..} = PP.text (unpack $ unPkgName pkgName) PP.<> PP.char '-' PP.<> (PP.text $ showVersion pkgVersion)
data PackageRef = PackageRef
{ prName :: !PackageName
, prRange :: !VersionRange
} deriving (Show,Read,Eq,Typeable,Data)
deriveSafeCopy 0 'base ''PackageRef
deriveJSON defaultOptions{fieldLabelModifier=jsonField 2} ''PackageRef
instance Ord PackageRef where
compare (PackageRef name1 range1) (PackageRef name2 range2) =
case compare name1 name2 of
EQ -> compare (show range1) (show range2)
c -> c
data ComponentKey = ComponentKey
{ cPackageKey :: !PackageKey
, cName :: !ComponentName
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''ComponentKey
deriveJSON defaultOptions{fieldLabelModifier=jsonField 1} ''ComponentKey
data Component = Component
{ cKey :: !ComponentKey
, cType :: !ComponentType
, cRefs :: [PackageRef]
do n't use the Extension type since it only got instance recently , etc
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''Component
deriveJSON defaultOptions{fieldLabelModifier=jsonField 1} ''Component
newtype ModuleName = ModuleName {unModName :: Text}
deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''ModuleName
'' ModuleName
instance ToJSON ModuleName where
toJSON = toJSON . unModName
instance FromJSON ModuleName where
parseJSON (String s) = pure $ ModuleName s
parseJSON _ = mzero
instance IsString ModuleName where
fromString = ModuleName . pack
data Location = Location
{ lLine :: !Int
, lColumn :: !Int
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''Location
deriveJSON defaultOptions{fieldLabelModifier=jsonField 1} ''Location
data MarkerLevel = MLError | MLWarning | MLInfo
deriving (Show,Read,Eq,Ord,Typeable,Data,Bounded,Enum)
deriveSafeCopy 0 'base ''MarkerLevel
deriveJSON defaultOptions ''MarkerLevel
data Marker = Marker
{ mText :: Text
, mLevel :: MarkerLevel
, mLocation :: Location
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''Marker
deriveJSON defaultOptions{fieldLabelModifier=jsonField 1} ''Marker
newtype DeclName = DeclName {unDeclName :: Text}
deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''DeclName
'' DeclName
instance ToJSON DeclName where
toJSON = toJSON . unDeclName
instance FromJSON DeclName where
parseJSON (String s) = pure $ DeclName s
parseJSON _ = mzero
instance IsString DeclName where
fromString = DeclName . pack
data DeclType = DeclData | DeclNewType | DeclClass | DeclInstance | DeclType
| DeclDataFamily | DeclTypeFamily | DeclDataInstance | DeclTypeInstance
| DeclFunction | DeclConstructor | DeclMethod
deriving (Show, Read, Eq, Ord, Bounded,Enum,Typeable,Data)
deriveSafeCopy 0 'base ''DeclType
deriveJSON defaultOptions ''DeclType
data WriteDate = WriteDate
{ wdCreated :: UTCTime
, wdUpdated :: UTCTime
} deriving (Show, Read, Eq, Ord, Typeable,Data)
deriveSafeCopy 0 'base ''WriteDate
data Package = Package
{ pkgKey :: !PackageKey
, pkgDoc :: !Doc
, pkgMeta :: !PackageMetaData
, pkgDocURL :: !(Maybe URL)
, pkgModulesAnalysedDate :: !(Maybe UTCTime)
, pkgDeclsAnalysedDate :: !(Maybe UTCTime)
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''Package
deriveJSON defaultOptions{fieldLabelModifier=jsonField 3} ''Package
data ModuleKey = ModuleKey
{ modName :: ModuleName
, modPackageKey :: PackageKey
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''ModuleKey
deriveJSON defaultOptions{fieldLabelModifier=jsonField 3} ''ModuleKey
data ModuleInclusion = ModuleInclusion
{ miComponent :: ComponentName
, miExpose :: Expose
, miMarkers :: Maybe [Marker]
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''ModuleInclusion
deriveJSON defaultOptions{fieldLabelModifier=jsonField 2} ''ModuleInclusion
data Module = Module
{ modKey :: ModuleKey
, modDoc :: Doc
, modComponents :: [ModuleInclusion]
, modURLs :: URLs
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''Module
deriveJSON defaultOptions{fieldLabelModifier=jsonField 3} ''Module
data DeclKey = DeclKey
{ decName :: DeclName
, decModuleKey :: ModuleKey
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''DeclKey
deriveJSON defaultOptions{fieldLabelModifier=jsonField 3} ''DeclKey
data Decl = Decl
{ dKey :: DeclKey
, dType :: DeclType
, dSignature :: Text
, dDoc :: Doc
, dURLs :: URLs
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''Decl
deriveJSON defaultOptions{fieldLabelModifier=jsonField 1} ''Decl
data FullPackage = FullPackage
{ fpPackage :: !Package
, fpComponents :: ![Component]
, fpModules :: ![Module]
} deriving (Show,Read,Eq,Ord,Typeable,Data)
deriveSafeCopy 0 'base ''FullPackage
deriveJSON defaultOptions{fieldLabelModifier=jsonField 2} ''FullPackage
type ComponentIxs = '[PackageKey, ComponentKey,PackageName]
type IxComponent = IxSet ComponentIxs Component
instance Indexable ComponentIxs Component where
indices = ixList
(ixFun $ \c -> [ cPackageKey $ cKey c ])
(ixFun $ \c -> [ cKey c ])
(ixFun $ \c -> Prelude.map prName $ cRefs c)
type PackageIxs = '[PackageKey, PackageName, Local, Text]
type IxPackage = IxSet PackageIxs Package
packageSep :: Char
packageSep = '-'
instance Indexable PackageIxs Package where
indices = ixList
(ixFun $ \pkg -> [ pkgKey pkg ])
(ixFun $ \pkg -> [pkgName $ pkgKey pkg] )
(ixFun $ \pkg -> [ pkgLocal $ pkgKey pkg ])
(ixFun $ \pkg -> splitCaseFold packageSep $ unPkgName $ pkgName $ pkgKey pkg )
type ModuleIxs = '[PackageKey, ComponentKey, Text, ModuleKey]
type IxModule = IxSet ModuleIxs Module
moduleSep :: Char
moduleSep = '-'
instance Indexable ModuleIxs Module where
indices = ixList
(ixFun $ \mo -> [ modPackageKey $ modKey mo ])
(ixFun $ \mo -> Prelude.map ((ComponentKey $ modPackageKey $ modKey mo) . miComponent) $ modComponents mo)
(ixFun $ \mo -> splitCaseFold moduleSep $ unModName $ modName $ modKey mo)
(ixFun $ \mo -> [ modKey mo ])
type DeclIxs = '[PackageKey, ModuleKey, DeclName]
type IxDecl = IxSet DeclIxs Decl
instance Indexable DeclIxs Decl where
indices = ixList
(ixFun $ \de -> [modPackageKey $ decModuleKey $ dKey de])
(ixFun $ \de -> [decModuleKey $ dKey de])
(ixFun $ \de -> [decName $ dKey de])
data Database = Database
{ dPackages :: IxPackage
, dComponents :: IxComponent
, dModules :: IxModule
, dDecls :: IxDecl
} deriving (Typeable)
deriveSafeCopy 0 'base ''Database
instance Default Database where
def = Database empty empty empty empty
|
706e78e7222e6b2dcf47c85f68fdb4cfc2fa73bfe29ddfc2d3f24c8da59fd76b | rmascarenhas/foppl | toposort.clj | (ns foppl.toposort
"Performs topological sort of an acyclic graph."
(:require [clojure.set :as set]))
Based on original implementation
;;
(defn- without
"Returns set s with x removed."
[s x] (set/difference s #{x}))
(defn- take-1
"Returns the pair [element, s'] where s' is set s with element removed."
[s] {:pre [(not (empty? s))]}
(let [item (first s)]
[item (without s item)]))
(defn- no-incoming
"Returns the set of nodes in graph g for which there are no incoming
edges, where g is a map of nodes to sets of nodes."
[g]
(let [nodes (set (keys g))
have-incoming (apply set/union (vals g))]
(set/difference nodes have-incoming)))
(defn- normalize
"Returns g with empty outgoing edges added for nodes with incoming
edges only. Example: {:a #{:b}} => {:a #{:b}, :b #{}}"
[g]
(let [have-incoming (apply set/union (vals g))]
(reduce #(if (get % %2) % (assoc % %2 #{})) g have-incoming)))
(defn- toposort
"Proposes a topological sort for directed graph g using Kahn's
algorithm, where g is a map of nodes to sets of nodes. If g is
cyclic, returns nil."
([g]
(toposort (normalize g) [] (no-incoming g)))
([g l s]
(if (empty? s)
(when (every? empty? (vals g)) l)
(let [[n s'] (take-1 s)
m (g n)
g' (reduce #(update-in % [n] without %2) g m)]
(recur g' (conj l n) (set/union s' (set/intersection (no-incoming g') m)))))))
(defn perform [{{A :A} :G}]
"Performs topological sort of a graphical model, given as a
foppl.graphical.model record. Returns an array of random-variable
names that representa topological sort of the graph."
(let [sources (map (fn [[from to]] from) A)
graph (zipmap sources (repeat #{}))
combine (fn [g [from to]] (assoc g from (conj (get g from) to)))
graph (reduce combine graph A)]
(toposort graph)))
| null | https://raw.githubusercontent.com/rmascarenhas/foppl/f3d7013c97652c8b555dae2bd7067e2b0134b030/src/foppl/toposort.clj | clojure | (ns foppl.toposort
"Performs topological sort of an acyclic graph."
(:require [clojure.set :as set]))
Based on original implementation
(defn- without
"Returns set s with x removed."
[s x] (set/difference s #{x}))
(defn- take-1
"Returns the pair [element, s'] where s' is set s with element removed."
[s] {:pre [(not (empty? s))]}
(let [item (first s)]
[item (without s item)]))
(defn- no-incoming
"Returns the set of nodes in graph g for which there are no incoming
edges, where g is a map of nodes to sets of nodes."
[g]
(let [nodes (set (keys g))
have-incoming (apply set/union (vals g))]
(set/difference nodes have-incoming)))
(defn- normalize
"Returns g with empty outgoing edges added for nodes with incoming
edges only. Example: {:a #{:b}} => {:a #{:b}, :b #{}}"
[g]
(let [have-incoming (apply set/union (vals g))]
(reduce #(if (get % %2) % (assoc % %2 #{})) g have-incoming)))
(defn- toposort
"Proposes a topological sort for directed graph g using Kahn's
algorithm, where g is a map of nodes to sets of nodes. If g is
cyclic, returns nil."
([g]
(toposort (normalize g) [] (no-incoming g)))
([g l s]
(if (empty? s)
(when (every? empty? (vals g)) l)
(let [[n s'] (take-1 s)
m (g n)
g' (reduce #(update-in % [n] without %2) g m)]
(recur g' (conj l n) (set/union s' (set/intersection (no-incoming g') m)))))))
(defn perform [{{A :A} :G}]
"Performs topological sort of a graphical model, given as a
foppl.graphical.model record. Returns an array of random-variable
names that representa topological sort of the graph."
(let [sources (map (fn [[from to]] from) A)
graph (zipmap sources (repeat #{}))
combine (fn [g [from to]] (assoc g from (conj (get g from) to)))
graph (reduce combine graph A)]
(toposort graph)))
| |
44c7105cd383885f7420367aaf07531bb4b6f50fa2d7d8cfb7f38f5e4d8da19a | gillchristian/tailwind-purs | Util.hs | module Util where
import Control.Applicative (Applicative (liftA2))
import Data.Char (isSpace)
import Data.List (dropWhileEnd)
trimEnd :: String -> String
trimEnd = dropWhileEnd isSpace
replace :: Eq a => a -> a -> [a] -> [a]
replace a b = map $ \c -> if c == a then b else c
startsWith :: (a -> Bool) -> [a] -> Bool
startsWith _ [] = False
startsWith f (x : _) = f x
(<&&>) :: Applicative f => f Bool -> f Bool -> f Bool
(<&&>) = liftA2 (&&)
(<||>) :: Applicative f => f Bool -> f Bool -> f Bool
(<||>) = liftA2 (||)
| null | https://raw.githubusercontent.com/gillchristian/tailwind-purs/87474189c951320959797b7a77488343de203771/src/Util.hs | haskell | module Util where
import Control.Applicative (Applicative (liftA2))
import Data.Char (isSpace)
import Data.List (dropWhileEnd)
trimEnd :: String -> String
trimEnd = dropWhileEnd isSpace
replace :: Eq a => a -> a -> [a] -> [a]
replace a b = map $ \c -> if c == a then b else c
startsWith :: (a -> Bool) -> [a] -> Bool
startsWith _ [] = False
startsWith f (x : _) = f x
(<&&>) :: Applicative f => f Bool -> f Bool -> f Bool
(<&&>) = liftA2 (&&)
(<||>) :: Applicative f => f Bool -> f Bool -> f Bool
(<||>) = liftA2 (||)
| |
ea46480acc81890b7bfd813dbc844d7e67437f8490f6dc7370a45bb5878773d6 | rizo/snowflake-os | linkerTest.ml |
(* Build the snowflake kernel (eventually) *)
(* -T kernel/kernel.ldscript -L . -L libraries/stdlib -L libraries/threads -L libraries/extlib -L libraries/bitstring *)
let input_files = [|
"kernel/snowflake.native.startup.o";
"kernel/snowflake.o";
(*"kernel/vga.o";*)
"kernel/tarFile.o";
"kernel/trie.o";
" kernel / keyboard.o " ;
"kernel/interrupts.o";
(*"kernel/PCI.o";
"kernel/deviceManager.o";*)
"kernel/ELF.o";
"kernel/vt100.o";
"kernel/linkerTest.o";
" kernel / audioMixer.o " ;
" kernel / blockIO.o " ;
" kernel / e1000.o " ;
" kernel / ext2fs.o " ;
" kernel / fileSystems.o " ;
" kernel / ICH0.o " ;
" kernel / ircLexer.o " ;
" kernel / IRC.o " ;
" kernel / ircParser.o " ;
" kernel / kernelBuffer.o " ;
" kernel / networkProtocolStack.o " ;
" kernel / networkStack.o " ;
" kernel / packetParsing.o " ;
" kernel / partitions.o " ;
" kernel / play.o " ;
" kernel / realTek8139.o " ;
" kernel / ringBuffer.o " ;
" kernel / shell.o " ;
" kernel / IDE.o " ;
" kernel / TCP.o " ;
"kernel/blockIO.o";
"kernel/e1000.o";
"kernel/ext2fs.o";
"kernel/fileSystems.o";
"kernel/ICH0.o";
"kernel/ircLexer.o";
"kernel/IRC.o";
"kernel/ircParser.o";
"kernel/kernelBuffer.o";
"kernel/networkProtocolStack.o";
"kernel/networkStack.o";
"kernel/packetParsing.o";
"kernel/partitions.o";
"kernel/play.o";
"kernel/realTek8139.o";
"kernel/ringBuffer.o";
"kernel/shell.o";
"kernel/IDE.o";
"kernel/TCP.o";*)
"libraries/bigarray/bigarray.o";
"libraries/bitstring/bitstring.a";
"libraries/extlib/extlib.a";
"libraries/threads/threads.a";
"libraries/stdlib/stdlib.a";
"libraries/kernel/stage1.o";
"libraries/kernel/stage2.o";
"libkernel.a";
"libm.a";
"libc.a";
"libgcc.a";
"libbigarray.a";
"libthreads.a";
"libbitstring.a";
" libkernel.a " ;
" libgcc.a " ;
" libc.a " ;
" libm.a " ;
" libbigarray.a " ;
" libthreads.a " ;
" libbitstring.a " ;
"libgcc.a";
"libc.a";
"libm.a";
"libbigarray.a";
"libthreads.a";
"libbitstring.a";*)
|]
| null | https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/kernel/linkerTest.ml | ocaml | Build the snowflake kernel (eventually)
-T kernel/kernel.ldscript -L . -L libraries/stdlib -L libraries/threads -L libraries/extlib -L libraries/bitstring
"kernel/vga.o";
"kernel/PCI.o";
"kernel/deviceManager.o"; |
let input_files = [|
"kernel/snowflake.native.startup.o";
"kernel/snowflake.o";
"kernel/tarFile.o";
"kernel/trie.o";
" kernel / keyboard.o " ;
"kernel/interrupts.o";
"kernel/ELF.o";
"kernel/vt100.o";
"kernel/linkerTest.o";
" kernel / audioMixer.o " ;
" kernel / blockIO.o " ;
" kernel / e1000.o " ;
" kernel / ext2fs.o " ;
" kernel / fileSystems.o " ;
" kernel / ICH0.o " ;
" kernel / ircLexer.o " ;
" kernel / IRC.o " ;
" kernel / ircParser.o " ;
" kernel / kernelBuffer.o " ;
" kernel / networkProtocolStack.o " ;
" kernel / networkStack.o " ;
" kernel / packetParsing.o " ;
" kernel / partitions.o " ;
" kernel / play.o " ;
" kernel / realTek8139.o " ;
" kernel / ringBuffer.o " ;
" kernel / shell.o " ;
" kernel / IDE.o " ;
" kernel / TCP.o " ;
"kernel/blockIO.o";
"kernel/e1000.o";
"kernel/ext2fs.o";
"kernel/fileSystems.o";
"kernel/ICH0.o";
"kernel/ircLexer.o";
"kernel/IRC.o";
"kernel/ircParser.o";
"kernel/kernelBuffer.o";
"kernel/networkProtocolStack.o";
"kernel/networkStack.o";
"kernel/packetParsing.o";
"kernel/partitions.o";
"kernel/play.o";
"kernel/realTek8139.o";
"kernel/ringBuffer.o";
"kernel/shell.o";
"kernel/IDE.o";
"kernel/TCP.o";*)
"libraries/bigarray/bigarray.o";
"libraries/bitstring/bitstring.a";
"libraries/extlib/extlib.a";
"libraries/threads/threads.a";
"libraries/stdlib/stdlib.a";
"libraries/kernel/stage1.o";
"libraries/kernel/stage2.o";
"libkernel.a";
"libm.a";
"libc.a";
"libgcc.a";
"libbigarray.a";
"libthreads.a";
"libbitstring.a";
" libkernel.a " ;
" libgcc.a " ;
" libc.a " ;
" libm.a " ;
" libbigarray.a " ;
" libthreads.a " ;
" libbitstring.a " ;
"libgcc.a";
"libc.a";
"libm.a";
"libbigarray.a";
"libthreads.a";
"libbitstring.a";*)
|]
|
8f60a1a4ffd867057f5bca2bf5cd86b429d4913ce26a34b95946724970ad0c39 | rixed/ramen | RamenGraphiteSink.ml | (* Collector for graphite plain text protocol (as described in
* -carbon.html).
*
* Graphite metrics are organized as a hierarchy (with added tags on top).
* We make no attempt to map that hierarchy into several functions; instead,
* like for collectd we merely queue all received metrics into a single
* stream representing the type of a generic graphite metric and let
* interested functions select what they want from it. This is both simpler
* and more versatile. Also, it is somewhat required by the fact that all
* metrics have to be received by a single listener.
*)
open Batteries
open DessserOCamlBackEndHelpers
open RamenConsts
open RamenHelpersNoLog
open RamenHelpers
open RamenLog
open RamenTuple
open RamenTypes
module DT = DessserTypes
module N = RamenName
module T = RamenTypes
let tuple_typ =
[ { name = N.field "metric" ;
typ = DT.required TString ;
units = None ;
doc = "The graphite metric path." ;
aggr = None } ;
{ name = N.field "receipt_time" ;
typ = DT.required TFloat ;
units = Some RamenUnits.seconds_since_epoch ;
doc = "When this metric has been received." ;
aggr = None } ;
{ name = N.field "sender" ;
typ = DT.optional T.ip ;
units = None ;
doc = "Where we received this metric from." ;
aggr = None } ;
{ name = N.field "start" ;
typ = DT.required TFloat ;
units = Some RamenUnits.seconds_since_epoch ;
doc = "Event time." ;
aggr = None } ;
{ name = N.field "tags" ;
typ = DT.required (TArr (DT.required (TTup [|
DT.required TString ; DT.required TString |]))) ;
units = None ;
doc = "Accompanying tags." ;
aggr = None } ;
{ name = N.field "value" ;
typ = DT.required TFloat ;
units = None ;
doc = "The metric value." ;
aggr = None } ]
let event_time =
let open Event_time.DessserGen in
let open Event_time_field.DessserGen in
Some ((N.field "start", OutputField, 1.),
DurationConst 0.)
let factors =
[ N.field "sender" ;
N.field "metric" ]
let print oc (metric, _recept_time, _sender, start, tags, value) =
Printf.fprintf oc "%s%s%a %s %s"
metric
(if tags <> [||] then ";" else "")
(Array.print ~first:"" ~last:"" ~sep:";" (fun oc (n,v) ->
Printf.fprintf oc "%s=%s" n v)) tags
(nice_string_of_float value)
(nice_string_of_float start)
let to_string m =
Printf.sprintf2 "%a" print m
(*$inject
open Batteries
open DessserOCamlBackEndHelpers *)
$ = to_string & ~printer : identity
" foo.bar 42 123.12 " \
( to_string ( " foo.bar " , 0 . , None , 123.12 , [ || ] , 42 . ) )
" foo;tag1 = val1;tag2 = val2 0.1 123.12 " \
( to_string ( " foo " , 0 . , None , 123.12 , \
[ | " tag1 " , " val1 " ; " tag2 " , " val2 " | ] , 0.1 ) )
"foo.bar 42 123.12" \
(to_string ("foo.bar", 0., None, 123.12, [||], 42.))
"foo;tag1=val1;tag2=val2 0.1 123.12" \
(to_string ("foo", 0., None, 123.12, \
[| "tag1", "val1"; "tag2", "val2" |], 0.1))
*)
let parse ?sender ~recept_time line =
let parse_err () =
Printf.sprintf "Cannot parse %S as graphite" line |>
invalid_arg in
let s2f f =
try float_of_string f with _ -> parse_err () in
let metric, value, start =
match string_split_on_char ' ' line with
| [ metric ; value ; start ] -> metric, s2f value, s2f start
| [ metric ; value ] -> metric, s2f value, recept_time
| _ -> parse_err () in
let metric, tags =
match string_split_on_char ';' metric with
| [] | [""] -> parse_err ()
| metric :: tags ->
metric,
List.enum tags /@
(fun t ->
try String.split ~by:"=" t
with Not_found -> parse_err ()) |>
Array.of_enum in
(* In serialization order: *)
metric, recept_time, sender, start, tags, value
$ = parse & ~printer : to_string
( " foo.bar " , 1 . , None , 123.12 , [ || ] , 42 . ) \
( parse ~recept_time:1 . " foo.bar 42 123.12 " )
( " foo " , 1 . , None , 123.12 , [ | " " ; " tag2 " , " val2 " | ] , 0.1 ) \
( parse ~recept_time:1 . " foo;tag1 = val1;tag2 = val2 0.1 123.12 " )
( " foo.bar " , 1.23 , None , 1.23 , [ || ] , 42 . ) \
( parse ~recept_time:1.23 " foo.bar 42 " )
("foo.bar", 1., None, 123.12, [||], 42.) \
(parse ~recept_time:1. "foo.bar 42 123.12")
("foo", 1., None, 123.12, [| "tag1","val1"; "tag2", "val2" |], 0.1) \
(parse ~recept_time:1. "foo;tag1=val1;tag2=val2 0.1 123.12")
("foo.bar", 1.23, None, 1.23, [||], 42.) \
(parse ~recept_time:1.23 "foo.bar 42")
*)
let collector ~inet_addr ~port ~ip_proto ?while_ k =
let lines_of_string s =
(string_split_on_char '\n' s |> List.enum) // ((<>) "")
in
let serve ?sender buffer start stop =
let sender = Option.map RamenIp.of_unix_addr sender in
let recv_len = stop - start in
(* Look for the actual stop we are going to use: the last newline
* character *)
match Bytes.rindex_from buffer (stop - 1) '\n' with
| exception Not_found ->
0
| newline when newline < start ->
0
| newline ->
let stop = newline + 1 in
!logger.debug
"Received a graphite message of %d bytes (out of %d) from %a"
(stop - start) recv_len
(Option.print RamenIp.print) sender ;
let recept_time = Unix.gettimeofday () in
match
(Bytes.sub_string buffer start stop |>
lines_of_string) /@
String.trim /@
parse ?sender ~recept_time with
| exception e ->
print_exception ~what:"Converting graphite plain text into tuple" e ;
(* Ignore that batch and proceed: *)
stop - start
| tuples ->
Enum.iter k tuples ;
stop - start
in
ip_server ~ip_proto
~what:"graphite sink" ~buffer_size:60000 ~inet_addr ~port ?while_ serve
| null | https://raw.githubusercontent.com/rixed/ramen/f4e8fb56ac43fe91a175efa273ff81066032dcff/src/RamenGraphiteSink.ml | ocaml | Collector for graphite plain text protocol (as described in
* -carbon.html).
*
* Graphite metrics are organized as a hierarchy (with added tags on top).
* We make no attempt to map that hierarchy into several functions; instead,
* like for collectd we merely queue all received metrics into a single
* stream representing the type of a generic graphite metric and let
* interested functions select what they want from it. This is both simpler
* and more versatile. Also, it is somewhat required by the fact that all
* metrics have to be received by a single listener.
$inject
open Batteries
open DessserOCamlBackEndHelpers
In serialization order:
Look for the actual stop we are going to use: the last newline
* character
Ignore that batch and proceed: | open Batteries
open DessserOCamlBackEndHelpers
open RamenConsts
open RamenHelpersNoLog
open RamenHelpers
open RamenLog
open RamenTuple
open RamenTypes
module DT = DessserTypes
module N = RamenName
module T = RamenTypes
let tuple_typ =
[ { name = N.field "metric" ;
typ = DT.required TString ;
units = None ;
doc = "The graphite metric path." ;
aggr = None } ;
{ name = N.field "receipt_time" ;
typ = DT.required TFloat ;
units = Some RamenUnits.seconds_since_epoch ;
doc = "When this metric has been received." ;
aggr = None } ;
{ name = N.field "sender" ;
typ = DT.optional T.ip ;
units = None ;
doc = "Where we received this metric from." ;
aggr = None } ;
{ name = N.field "start" ;
typ = DT.required TFloat ;
units = Some RamenUnits.seconds_since_epoch ;
doc = "Event time." ;
aggr = None } ;
{ name = N.field "tags" ;
typ = DT.required (TArr (DT.required (TTup [|
DT.required TString ; DT.required TString |]))) ;
units = None ;
doc = "Accompanying tags." ;
aggr = None } ;
{ name = N.field "value" ;
typ = DT.required TFloat ;
units = None ;
doc = "The metric value." ;
aggr = None } ]
let event_time =
let open Event_time.DessserGen in
let open Event_time_field.DessserGen in
Some ((N.field "start", OutputField, 1.),
DurationConst 0.)
let factors =
[ N.field "sender" ;
N.field "metric" ]
let print oc (metric, _recept_time, _sender, start, tags, value) =
Printf.fprintf oc "%s%s%a %s %s"
metric
(if tags <> [||] then ";" else "")
(Array.print ~first:"" ~last:"" ~sep:";" (fun oc (n,v) ->
Printf.fprintf oc "%s=%s" n v)) tags
(nice_string_of_float value)
(nice_string_of_float start)
let to_string m =
Printf.sprintf2 "%a" print m
$ = to_string & ~printer : identity
" foo.bar 42 123.12 " \
( to_string ( " foo.bar " , 0 . , None , 123.12 , [ || ] , 42 . ) )
" foo;tag1 = val1;tag2 = val2 0.1 123.12 " \
( to_string ( " foo " , 0 . , None , 123.12 , \
[ | " tag1 " , " val1 " ; " tag2 " , " val2 " | ] , 0.1 ) )
"foo.bar 42 123.12" \
(to_string ("foo.bar", 0., None, 123.12, [||], 42.))
"foo;tag1=val1;tag2=val2 0.1 123.12" \
(to_string ("foo", 0., None, 123.12, \
[| "tag1", "val1"; "tag2", "val2" |], 0.1))
*)
let parse ?sender ~recept_time line =
let parse_err () =
Printf.sprintf "Cannot parse %S as graphite" line |>
invalid_arg in
let s2f f =
try float_of_string f with _ -> parse_err () in
let metric, value, start =
match string_split_on_char ' ' line with
| [ metric ; value ; start ] -> metric, s2f value, s2f start
| [ metric ; value ] -> metric, s2f value, recept_time
| _ -> parse_err () in
let metric, tags =
match string_split_on_char ';' metric with
| [] | [""] -> parse_err ()
| metric :: tags ->
metric,
List.enum tags /@
(fun t ->
try String.split ~by:"=" t
with Not_found -> parse_err ()) |>
Array.of_enum in
metric, recept_time, sender, start, tags, value
$ = parse & ~printer : to_string
( " foo.bar " , 1 . , None , 123.12 , [ || ] , 42 . ) \
( parse ~recept_time:1 . " foo.bar 42 123.12 " )
( " foo " , 1 . , None , 123.12 , [ | " " ; " tag2 " , " val2 " | ] , 0.1 ) \
( parse ~recept_time:1 . " foo;tag1 = val1;tag2 = val2 0.1 123.12 " )
( " foo.bar " , 1.23 , None , 1.23 , [ || ] , 42 . ) \
( parse ~recept_time:1.23 " foo.bar 42 " )
("foo.bar", 1., None, 123.12, [||], 42.) \
(parse ~recept_time:1. "foo.bar 42 123.12")
("foo", 1., None, 123.12, [| "tag1","val1"; "tag2", "val2" |], 0.1) \
(parse ~recept_time:1. "foo;tag1=val1;tag2=val2 0.1 123.12")
("foo.bar", 1.23, None, 1.23, [||], 42.) \
(parse ~recept_time:1.23 "foo.bar 42")
*)
let collector ~inet_addr ~port ~ip_proto ?while_ k =
let lines_of_string s =
(string_split_on_char '\n' s |> List.enum) // ((<>) "")
in
let serve ?sender buffer start stop =
let sender = Option.map RamenIp.of_unix_addr sender in
let recv_len = stop - start in
match Bytes.rindex_from buffer (stop - 1) '\n' with
| exception Not_found ->
0
| newline when newline < start ->
0
| newline ->
let stop = newline + 1 in
!logger.debug
"Received a graphite message of %d bytes (out of %d) from %a"
(stop - start) recv_len
(Option.print RamenIp.print) sender ;
let recept_time = Unix.gettimeofday () in
match
(Bytes.sub_string buffer start stop |>
lines_of_string) /@
String.trim /@
parse ?sender ~recept_time with
| exception e ->
print_exception ~what:"Converting graphite plain text into tuple" e ;
stop - start
| tuples ->
Enum.iter k tuples ;
stop - start
in
ip_server ~ip_proto
~what:"graphite sink" ~buffer_size:60000 ~inet_addr ~port ?while_ serve
|
b975d16bfad03df13267804deed9674a9b39d935081bfc17295b320b05cb9547 | jfischoff/twitch | InternalRule.hs | module Tests.Twitch.InternalRule where
import Test.Hspec
tests :: Spec
tests = return () | null | https://raw.githubusercontent.com/jfischoff/twitch/9ed10b0aaff8aace3b8b2eb47d605d9107194b95/tests/Tests/Twitch/InternalRule.hs | haskell | module Tests.Twitch.InternalRule where
import Test.Hspec
tests :: Spec
tests = return () | |
6bfd95a5dc311b5413bc70ad405bf3d8706df403bb839dd29d29fa86878aad6d | vvvvalvalval/datomock | impl_test.clj | (ns datomock.impl-test
(:require [clojure.test :refer :all]
[clojure.test.check :as tc]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop]
[clojure.test.check.clojure-test :refer [defspec]]
[datomock.test.utils :as tu]
[datomock.impl :as impl]
[datomock.core :as dm]
[datomic.api :as d])
(:import (java.util Date)))
(defspec gen-basic-txs-chain--yields-valid-tx-chains
10
(prop/for-all [txs tu/gen-basic-txs-chain]
(some? (tu/db-after-tx-chain txs))))
(defspec coerce-to-t--works-idempotently
100
(prop/for-all [txs tu/gen-basic-txs-chain]
(let [db (tu/db-after-tx-chain txs)
tid-tx (d/tempid :db.part/tx)
tx [[:db/add tid-tx :db/txInstant #inst "2012"]]
{:keys [tempids db-after]} (d/with db tx)
t (d/basis-t db-after)
tx-eid (d/resolve-tempid db-after tempids tid-tx)]
(=
t
(impl/coerce-to-t tx-eid)
(impl/coerce-to-t t))
)))
(deftest find-db-txInstant--works-on-empty-db
(is
(instance? Date (impl/find-db-txInstant (dm/empty-db)))))
(defspec find-db-txInstant--finds-the-txInstant-of-the-last-tx
100
(prop/for-all [txs tu/gen-basic-txs-chain
d (tu/gen-date* {:min #inst "2011" :max #inst "2012"})
other-date (tu/gen-date* {})]
(let [db (tu/db-after-tx-chain txs)
tid-tx (d/tempid :db.part/tx)
tx [[:db/add (d/tempid :db.part/user) :db/txInstant other-date]
[:db/add tid-tx :db/txInstant d]]
{:keys [db-after]} (d/with db tx)]
(= d (impl/find-db-txInstant db-after))))) | null | https://raw.githubusercontent.com/vvvvalvalval/datomock/3ab532f24bca982e23f1897bd5656bd5be15b0ba/test/datomock/impl_test.clj | clojure | (ns datomock.impl-test
(:require [clojure.test :refer :all]
[clojure.test.check :as tc]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop]
[clojure.test.check.clojure-test :refer [defspec]]
[datomock.test.utils :as tu]
[datomock.impl :as impl]
[datomock.core :as dm]
[datomic.api :as d])
(:import (java.util Date)))
(defspec gen-basic-txs-chain--yields-valid-tx-chains
10
(prop/for-all [txs tu/gen-basic-txs-chain]
(some? (tu/db-after-tx-chain txs))))
(defspec coerce-to-t--works-idempotently
100
(prop/for-all [txs tu/gen-basic-txs-chain]
(let [db (tu/db-after-tx-chain txs)
tid-tx (d/tempid :db.part/tx)
tx [[:db/add tid-tx :db/txInstant #inst "2012"]]
{:keys [tempids db-after]} (d/with db tx)
t (d/basis-t db-after)
tx-eid (d/resolve-tempid db-after tempids tid-tx)]
(=
t
(impl/coerce-to-t tx-eid)
(impl/coerce-to-t t))
)))
(deftest find-db-txInstant--works-on-empty-db
(is
(instance? Date (impl/find-db-txInstant (dm/empty-db)))))
(defspec find-db-txInstant--finds-the-txInstant-of-the-last-tx
100
(prop/for-all [txs tu/gen-basic-txs-chain
d (tu/gen-date* {:min #inst "2011" :max #inst "2012"})
other-date (tu/gen-date* {})]
(let [db (tu/db-after-tx-chain txs)
tid-tx (d/tempid :db.part/tx)
tx [[:db/add (d/tempid :db.part/user) :db/txInstant other-date]
[:db/add tid-tx :db/txInstant d]]
{:keys [db-after]} (d/with db tx)]
(= d (impl/find-db-txInstant db-after))))) | |
2ac00137cf8652d24f2929de8ee0e7bfba19a7a7e2885f62a2e3cf4c0ed1e689 | incoherentsoftware/defect-process | Bat.hs | module Configs.All.Enemy.Bat
( BatEnemyConfig(..)
) where
import Data.Aeson.Types (FromJSON, genericParseJSON, parseJSON)
import GHC.Generics (Generic)
import Attack.Util
import Enemy.DeathEffectData.Types
import Enemy.HurtEffectData.Types
import Enemy.SpawnEffectData.Types
import Util
import Window.Graphics.Util
data BatEnemyConfig = BatEnemyConfig
{ _health :: Health
, _width :: Float
, _height :: Float
, _riseRecoverVelY :: VelY
, _idleSecs :: Secs
, _patrolSpeed :: Speed
, _staggerThreshold :: Stagger
, _groundImpactEffectDrawScale :: DrawScale
, _wallImpactEffectDrawScale :: DrawScale
, _hurtEffectData :: EnemyHurtEffectData
, _deathEffectData :: EnemyDeathEffectData
, _spawnEffectData :: EnemySpawnEffectData
}
deriving Generic
instance FromJSON BatEnemyConfig where
parseJSON = genericParseJSON aesonFieldDropUnderscore
| null | https://raw.githubusercontent.com/incoherentsoftware/defect-process/14ec46dec2c48135bc4e5965b7b75532ef19268e/src/Configs/All/Enemy/Bat.hs | haskell | module Configs.All.Enemy.Bat
( BatEnemyConfig(..)
) where
import Data.Aeson.Types (FromJSON, genericParseJSON, parseJSON)
import GHC.Generics (Generic)
import Attack.Util
import Enemy.DeathEffectData.Types
import Enemy.HurtEffectData.Types
import Enemy.SpawnEffectData.Types
import Util
import Window.Graphics.Util
data BatEnemyConfig = BatEnemyConfig
{ _health :: Health
, _width :: Float
, _height :: Float
, _riseRecoverVelY :: VelY
, _idleSecs :: Secs
, _patrolSpeed :: Speed
, _staggerThreshold :: Stagger
, _groundImpactEffectDrawScale :: DrawScale
, _wallImpactEffectDrawScale :: DrawScale
, _hurtEffectData :: EnemyHurtEffectData
, _deathEffectData :: EnemyDeathEffectData
, _spawnEffectData :: EnemySpawnEffectData
}
deriving Generic
instance FromJSON BatEnemyConfig where
parseJSON = genericParseJSON aesonFieldDropUnderscore
| |
758e23899b49c7669b9de915ee7efa4cdb90738b71d7a9666e2f3a478216a64d | rudenoise/mirage-dashboard | releases.ml | open Lwt
*
* example github release values
* " i d " : 3009723 ,
* " tag_name " : " " ,
* " target_commitish " : " " ,
* " name " : " " ,
* " body " : " " ,
* " draft " : false ,
* " prerelease " : false ,
* " created_at " : " 2016 - 04 - 13T10:39:07Z " ,
* " published_at " : " 2016 - 04 - 13T10:41:24Z " ,
* " url " : " / ... " ,
* " html_url " : " ... " ,
* " assets_url " : " / ... " ,
* " upload_url " : " / ... "
* example github release values
* "id": 3009723,
* "tag_name": "",
* "target_commitish": "",
* "name": "",
* "body": "",
* "draft": false,
* "prerelease": false,
* "created_at": "2016-04-13T10:39:07Z",
* "published_at": "2016-04-13T10:41:24Z",
* "url": "/...",
* "html_url": "/...",
* "assets_url": "/...",
* "upload_url": "/..."
*)
module G = Github
let release_to_json detail =
let (name, published_at, total, release_type) = detail in
`Assoc [
("name", `String (name));
("published_at", `String published_at);
("of_total", `Int total);
("type", `String release_type)
]
(* RELEASES:*)
let get_releases_for_repo (repo_with_token:Github_wrapper.repo_with_token) =
let (token, user, repo) = repo_with_token in
return (G.Release.for_repo ~token ~user ~repo ())
let release_values release total =
let release_str = Github_j.string_of_release release in
let release_data = Yojson.Safe.from_string release_str in
let name = (
Yojson.Safe.Util.member
"tag_name"
release_data
) in
let published = (
Yojson.Safe.Util.member
"published_at"
release_data
) in
(
(Github_wrapper.strip_quotes (Yojson.Safe.to_string name)),
(Github_wrapper.strip_quotes (Yojson.Safe.to_string published)),
total,
"release"
)
let latest_relese releases total =
release_values (List.hd releases) total
let get_latest_release (repo_with_token:Github_wrapper.repo_with_token) =
get_releases_for_repo repo_with_token
>>= fun releases ->
Github_wrapper.stream_to_list releases
>>= fun releases_list ->
let total = List.length releases_list in
if total > 0
then return (latest_relese releases_list total)
else return ("No releases, yet...", "", 0, "release")
(* TAGS: *)
let get_tags_for_repo (repo_with_token:Github_wrapper.repo_with_token) =
let (token, user, repo) = repo_with_token in
return (G.Repo.get_tags_and_times ~token ~user ~repo ())
let sort_tags tags =
List.sort
(
fun a b ->
let (_, created_a) = a in
let (_, created_b) = b in
if created_a < created_b then 1 else 0
)
tags
let latest_tag tags =
let total = List.length tags in
if total > 0
then
let sorted_tags = sort_tags tags in
let (tag_name, created_at) = (List.hd sorted_tags) in
(
tag_name,
created_at,
total,
"tag"
)
else ("No tag or release, yet...", "", 0, "releases or tags")
let get_latest_tag (repo_with_token:Github_wrapper.repo_with_token) =
get_tags_for_repo repo_with_token
>>= fun tags ->
Github_wrapper.stream_to_list tags
>>= fun tags_list ->
return (latest_tag tags_list)
combine the two , returning release if there is one , then tag , or none / default
let get_current_release_or_tag (repo_with_token:Github_wrapper.repo_with_token) =
Lwt_list.map_p
(
fun closure ->
closure
)
[
(get_latest_release repo_with_token);
(get_latest_tag repo_with_token)
]
>>= fun rel_list ->
let release = List.nth rel_list 0 in
let tag = List.nth rel_list 1 in
let (_, release_date, _, _) = release in
let (_, tag_date, _, _) = tag in
if release_date > tag_date
then return (release_to_json release)
else return (release_to_json tag)
| null | https://raw.githubusercontent.com/rudenoise/mirage-dashboard/f109ad96d68701addd2ac7cc0be87d706f7eab50/src/releases.ml | ocaml | RELEASES:
TAGS: | open Lwt
*
* example github release values
* " i d " : 3009723 ,
* " tag_name " : " " ,
* " target_commitish " : " " ,
* " name " : " " ,
* " body " : " " ,
* " draft " : false ,
* " prerelease " : false ,
* " created_at " : " 2016 - 04 - 13T10:39:07Z " ,
* " published_at " : " 2016 - 04 - 13T10:41:24Z " ,
* " url " : " / ... " ,
* " html_url " : " ... " ,
* " assets_url " : " / ... " ,
* " upload_url " : " / ... "
* example github release values
* "id": 3009723,
* "tag_name": "",
* "target_commitish": "",
* "name": "",
* "body": "",
* "draft": false,
* "prerelease": false,
* "created_at": "2016-04-13T10:39:07Z",
* "published_at": "2016-04-13T10:41:24Z",
* "url": "/...",
* "html_url": "/...",
* "assets_url": "/...",
* "upload_url": "/..."
*)
module G = Github
let release_to_json detail =
let (name, published_at, total, release_type) = detail in
`Assoc [
("name", `String (name));
("published_at", `String published_at);
("of_total", `Int total);
("type", `String release_type)
]
let get_releases_for_repo (repo_with_token:Github_wrapper.repo_with_token) =
let (token, user, repo) = repo_with_token in
return (G.Release.for_repo ~token ~user ~repo ())
let release_values release total =
let release_str = Github_j.string_of_release release in
let release_data = Yojson.Safe.from_string release_str in
let name = (
Yojson.Safe.Util.member
"tag_name"
release_data
) in
let published = (
Yojson.Safe.Util.member
"published_at"
release_data
) in
(
(Github_wrapper.strip_quotes (Yojson.Safe.to_string name)),
(Github_wrapper.strip_quotes (Yojson.Safe.to_string published)),
total,
"release"
)
let latest_relese releases total =
release_values (List.hd releases) total
let get_latest_release (repo_with_token:Github_wrapper.repo_with_token) =
get_releases_for_repo repo_with_token
>>= fun releases ->
Github_wrapper.stream_to_list releases
>>= fun releases_list ->
let total = List.length releases_list in
if total > 0
then return (latest_relese releases_list total)
else return ("No releases, yet...", "", 0, "release")
let get_tags_for_repo (repo_with_token:Github_wrapper.repo_with_token) =
let (token, user, repo) = repo_with_token in
return (G.Repo.get_tags_and_times ~token ~user ~repo ())
let sort_tags tags =
List.sort
(
fun a b ->
let (_, created_a) = a in
let (_, created_b) = b in
if created_a < created_b then 1 else 0
)
tags
let latest_tag tags =
let total = List.length tags in
if total > 0
then
let sorted_tags = sort_tags tags in
let (tag_name, created_at) = (List.hd sorted_tags) in
(
tag_name,
created_at,
total,
"tag"
)
else ("No tag or release, yet...", "", 0, "releases or tags")
let get_latest_tag (repo_with_token:Github_wrapper.repo_with_token) =
get_tags_for_repo repo_with_token
>>= fun tags ->
Github_wrapper.stream_to_list tags
>>= fun tags_list ->
return (latest_tag tags_list)
combine the two , returning release if there is one , then tag , or none / default
let get_current_release_or_tag (repo_with_token:Github_wrapper.repo_with_token) =
Lwt_list.map_p
(
fun closure ->
closure
)
[
(get_latest_release repo_with_token);
(get_latest_tag repo_with_token)
]
>>= fun rel_list ->
let release = List.nth rel_list 0 in
let tag = List.nth rel_list 1 in
let (_, release_date, _, _) = release in
let (_, tag_date, _, _) = tag in
if release_date > tag_date
then return (release_to_json release)
else return (release_to_json tag)
|
8e76b25909d6b6addc46a02fe92d6b5a3a8286a603d8b4c0e5a685688ee8babb | rabbitmq/looking_glass | lg_socket_client.erl | %% Copyright (c) 2017-Present Pivotal Software, Inc. All rights reserved.
%%
This package , Looking , is double - licensed under the Mozilla
Public License 1.1 ( " MPL " ) and the Apache License version 2
( " ASL " ) . For the MPL , please see LICENSE - MPL - RabbitMQ . For the ASL ,
%% please see LICENSE-APACHE2.
%%
This software is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY KIND ,
%% either express or implied. See the LICENSE file for specific language governing
%% rights and limitations of this software.
%%
%% If you have any questions regarding licensing, please contact us at
%% .
-module(lg_socket_client).
-behavior(gen_statem).
-export([start_link/2]).
-export([stop/1]).
%% gen_statem.
-export([callback_mode/0]).
-export([init/1]).
-export([connect/3]).
-export([open_file/3]).
-export([process_events/3]).
-export([close_file/3]).
-export([code_change/4]).
-export([terminate/3]).
-record(state, {
port :: inet:port_number(),
base_filename :: file:filename_all(),
nth = 0 :: non_neg_integer(),
socket :: inet:socket() | undefined,
io_device :: file:io_device() | undefined,
events_per_frame = 100000 :: pos_integer(),
events_this_frame = 0 :: non_neg_integer(),
buffer = <<>> :: binary()
}).
start_link(Port, BaseFilename) ->
gen_statem:start_link(?MODULE, [Port, BaseFilename], []).
stop(Pid) ->
gen_statem:stop(Pid).
callback_mode() ->
state_functions.
init([Port, BaseFilename]) ->
Store all messages off the heap to avoid unnecessary GC .
process_flag(message_queue_data, off_heap),
%% We need to trap exit signals in order to shutdown properly.
process_flag(trap_exit, true),
{ok, connect, #state{port=Port, base_filename=BaseFilename},
{next_event, internal, run}}.
connect(internal, _, State) ->
do_connect(State);
connect({timeout, retry}, retry, State) ->
do_connect(State);
connect(_, _, State) ->
{keep_state, State}.
do_connect(State=#state{port=Port}) ->
case gen_tcp:connect("localhost", Port, [binary, {packet, 2}, {active, true}]) of
{ok, Socket} ->
{next_state, open_file, State#state{socket=Socket},
{next_event, internal, run}};
{error, _} ->
{keep_state, State, [{{timeout, retry}, 1000, retry}]}
end.
open_file(internal, _, State=#state{base_filename=Filename0, nth=Nth}) ->
Filename = filename:flatten([Filename0, ".", integer_to_list(Nth)]),
{ok, IoDevice} = file:open(Filename, [write, raw]),
{next_state, process_events, State#state{nth=Nth + 1, io_device=IoDevice}}.
process_events(info, {tcp, Socket, Bin}, State=#state{socket=Socket, io_device=IoDevice,
events_per_frame=MaxEvents, events_this_frame=NumEvents0, buffer=Buffer0}) ->
BinSize = byte_size(Bin),
Buffer = <<Buffer0/binary, BinSize:16, Bin/binary>>,
NumEvents = NumEvents0 + 1,
if
MaxEvents =:= NumEvents ->
ok = file:write(IoDevice, lz4f:compress_frame(Buffer)),
{keep_state, State#state{events_this_frame=0, buffer= <<>>}};
true ->
{keep_state, State#state{events_this_frame=NumEvents, buffer=Buffer}}
end;
process_events(info, {tcp_closed, Socket}, State=#state{socket=Socket}) ->
{next_state, close_file, State#state{socket=undefined},
{next_event, internal, run}};
process_events(info, {tcp_error, Socket, _}, State=#state{socket=Socket}) ->
_ = gen_tcp:close(Socket),
{next_state, close_file, State#state{socket=undefined},
{next_event, internal, run}}.
close_file(internal, _, State) ->
do_close_file(State),
{next_state, connect, State#state{io_device=undefined},
{next_event, internal, run}}.
do_close_file(#state{io_device=IoDevice, buffer=Buffer}) ->
_ = file:write(IoDevice, lz4f:compress_frame(Buffer)),
_ = file:close(IoDevice),
ok.
code_change(_OldVsn, OldState, OldData, _Extra) ->
{callback_mode(), OldState, OldData}.
terminate(_, _, #state{io_device=undefined}) ->
ok;
terminate(_, _, State) ->
do_close_file(State),
ok.
| null | https://raw.githubusercontent.com/rabbitmq/looking_glass/0ae891a8cee16603cdead0caf2d4c0b0800b22c9/src/lg_socket_client.erl | erlang | Copyright (c) 2017-Present Pivotal Software, Inc. All rights reserved.
please see LICENSE-APACHE2.
either express or implied. See the LICENSE file for specific language governing
rights and limitations of this software.
If you have any questions regarding licensing, please contact us at
.
gen_statem.
We need to trap exit signals in order to shutdown properly. | This package , Looking , is double - licensed under the Mozilla
Public License 1.1 ( " MPL " ) and the Apache License version 2
( " ASL " ) . For the MPL , please see LICENSE - MPL - RabbitMQ . For the ASL ,
This software is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY KIND ,
-module(lg_socket_client).
-behavior(gen_statem).
-export([start_link/2]).
-export([stop/1]).
-export([callback_mode/0]).
-export([init/1]).
-export([connect/3]).
-export([open_file/3]).
-export([process_events/3]).
-export([close_file/3]).
-export([code_change/4]).
-export([terminate/3]).
-record(state, {
port :: inet:port_number(),
base_filename :: file:filename_all(),
nth = 0 :: non_neg_integer(),
socket :: inet:socket() | undefined,
io_device :: file:io_device() | undefined,
events_per_frame = 100000 :: pos_integer(),
events_this_frame = 0 :: non_neg_integer(),
buffer = <<>> :: binary()
}).
start_link(Port, BaseFilename) ->
gen_statem:start_link(?MODULE, [Port, BaseFilename], []).
stop(Pid) ->
gen_statem:stop(Pid).
callback_mode() ->
state_functions.
init([Port, BaseFilename]) ->
Store all messages off the heap to avoid unnecessary GC .
process_flag(message_queue_data, off_heap),
process_flag(trap_exit, true),
{ok, connect, #state{port=Port, base_filename=BaseFilename},
{next_event, internal, run}}.
connect(internal, _, State) ->
do_connect(State);
connect({timeout, retry}, retry, State) ->
do_connect(State);
connect(_, _, State) ->
{keep_state, State}.
do_connect(State=#state{port=Port}) ->
case gen_tcp:connect("localhost", Port, [binary, {packet, 2}, {active, true}]) of
{ok, Socket} ->
{next_state, open_file, State#state{socket=Socket},
{next_event, internal, run}};
{error, _} ->
{keep_state, State, [{{timeout, retry}, 1000, retry}]}
end.
open_file(internal, _, State=#state{base_filename=Filename0, nth=Nth}) ->
Filename = filename:flatten([Filename0, ".", integer_to_list(Nth)]),
{ok, IoDevice} = file:open(Filename, [write, raw]),
{next_state, process_events, State#state{nth=Nth + 1, io_device=IoDevice}}.
process_events(info, {tcp, Socket, Bin}, State=#state{socket=Socket, io_device=IoDevice,
events_per_frame=MaxEvents, events_this_frame=NumEvents0, buffer=Buffer0}) ->
BinSize = byte_size(Bin),
Buffer = <<Buffer0/binary, BinSize:16, Bin/binary>>,
NumEvents = NumEvents0 + 1,
if
MaxEvents =:= NumEvents ->
ok = file:write(IoDevice, lz4f:compress_frame(Buffer)),
{keep_state, State#state{events_this_frame=0, buffer= <<>>}};
true ->
{keep_state, State#state{events_this_frame=NumEvents, buffer=Buffer}}
end;
process_events(info, {tcp_closed, Socket}, State=#state{socket=Socket}) ->
{next_state, close_file, State#state{socket=undefined},
{next_event, internal, run}};
process_events(info, {tcp_error, Socket, _}, State=#state{socket=Socket}) ->
_ = gen_tcp:close(Socket),
{next_state, close_file, State#state{socket=undefined},
{next_event, internal, run}}.
close_file(internal, _, State) ->
do_close_file(State),
{next_state, connect, State#state{io_device=undefined},
{next_event, internal, run}}.
do_close_file(#state{io_device=IoDevice, buffer=Buffer}) ->
_ = file:write(IoDevice, lz4f:compress_frame(Buffer)),
_ = file:close(IoDevice),
ok.
code_change(_OldVsn, OldState, OldData, _Extra) ->
{callback_mode(), OldState, OldData}.
terminate(_, _, #state{io_device=undefined}) ->
ok;
terminate(_, _, State) ->
do_close_file(State),
ok.
|
33c812fb3b3a52669d1aa5bb0876e1fa9c292f3e6ea493a877ecdc27444d88f8 | pirapira/coq2rust | find_subterm.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Names
open Locus
open Context
open Term
open Evd
open Pretype_errors
open Environ
(** Finding subterms, possibly up to some unification function,
possibly at some given occurrences *)
exception NotUnifiable of (constr * constr * unification_error) option
exception SubtermUnificationError of subterm_unification_error
* A testing function is typically a unification function returning a
substitution or failing with a NotUnifiable error , together with a
function to merge substitutions and an initial substitution ;
last_found is used for error messages and it has to be initialized
with None .
substitution or failing with a NotUnifiable error, together with a
function to merge substitutions and an initial substitution;
last_found is used for error messages and it has to be initialized
with None. *)
type 'a testing_function = {
match_fun : 'a -> constr -> 'a;
merge_fun : 'a -> 'a -> 'a;
mutable testing_state : 'a;
mutable last_found : position_reporting option
}
(** This is the basic testing function, looking for exact matches of a
closed term *)
val make_eq_univs_test : env -> evar_map -> constr -> evar_map testing_function
* [ replace_term_occ_modulo occl test mk c ] looks in [ c ] for subterm
modulo a testing function [ test ] and replaces successfully
matching subterms at the indicated occurrences [ occl ] with [ mk
( ) ] ; it turns a NotUnifiable exception raised by the testing
function into a SubtermUnificationError .
modulo a testing function [test] and replaces successfully
matching subterms at the indicated occurrences [occl] with [mk
()]; it turns a NotUnifiable exception raised by the testing
function into a SubtermUnificationError. *)
val replace_term_occ_modulo : occurrences or_like_first ->
'a testing_function -> (unit -> constr) -> constr -> constr
(** [replace_term_occ_decl_modulo] is similar to
[replace_term_occ_modulo] but for a named_declaration. *)
val replace_term_occ_decl_modulo :
(occurrences * hyp_location_flag) or_like_first ->
'a testing_function -> (unit -> constr) ->
named_declaration -> named_declaration
* [ subst_closed_term_occ occl c d ] replaces occurrences of
closed [ c ] at positions [ occl ] by [ Rel 1 ] in [ d ] ( see also Note OCC ) ,
unifying universes which results in a set of constraints .
closed [c] at positions [occl] by [Rel 1] in [d] (see also Note OCC),
unifying universes which results in a set of constraints. *)
val subst_closed_term_occ : env -> evar_map -> occurrences or_like_first ->
constr -> constr -> constr * evar_map
* [ subst_closed_term_occ_decl evd occl c ] replaces occurrences of
closed [ c ] at positions [ occl ] by [ Rel 1 ] in [ ] .
closed [c] at positions [occl] by [Rel 1] in [decl]. *)
val subst_closed_term_occ_decl : env -> evar_map ->
(occurrences * hyp_location_flag) or_like_first ->
constr -> named_declaration -> named_declaration * evar_map
(** Miscellaneous *)
val error_invalid_occurrence : int list -> 'a
| null | https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/pretyping/find_subterm.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* Finding subterms, possibly up to some unification function,
possibly at some given occurrences
* This is the basic testing function, looking for exact matches of a
closed term
* [replace_term_occ_decl_modulo] is similar to
[replace_term_occ_modulo] but for a named_declaration.
* Miscellaneous | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Names
open Locus
open Context
open Term
open Evd
open Pretype_errors
open Environ
exception NotUnifiable of (constr * constr * unification_error) option
exception SubtermUnificationError of subterm_unification_error
* A testing function is typically a unification function returning a
substitution or failing with a NotUnifiable error , together with a
function to merge substitutions and an initial substitution ;
last_found is used for error messages and it has to be initialized
with None .
substitution or failing with a NotUnifiable error, together with a
function to merge substitutions and an initial substitution;
last_found is used for error messages and it has to be initialized
with None. *)
type 'a testing_function = {
match_fun : 'a -> constr -> 'a;
merge_fun : 'a -> 'a -> 'a;
mutable testing_state : 'a;
mutable last_found : position_reporting option
}
val make_eq_univs_test : env -> evar_map -> constr -> evar_map testing_function
* [ replace_term_occ_modulo occl test mk c ] looks in [ c ] for subterm
modulo a testing function [ test ] and replaces successfully
matching subterms at the indicated occurrences [ occl ] with [ mk
( ) ] ; it turns a NotUnifiable exception raised by the testing
function into a SubtermUnificationError .
modulo a testing function [test] and replaces successfully
matching subterms at the indicated occurrences [occl] with [mk
()]; it turns a NotUnifiable exception raised by the testing
function into a SubtermUnificationError. *)
val replace_term_occ_modulo : occurrences or_like_first ->
'a testing_function -> (unit -> constr) -> constr -> constr
val replace_term_occ_decl_modulo :
(occurrences * hyp_location_flag) or_like_first ->
'a testing_function -> (unit -> constr) ->
named_declaration -> named_declaration
* [ subst_closed_term_occ occl c d ] replaces occurrences of
closed [ c ] at positions [ occl ] by [ Rel 1 ] in [ d ] ( see also Note OCC ) ,
unifying universes which results in a set of constraints .
closed [c] at positions [occl] by [Rel 1] in [d] (see also Note OCC),
unifying universes which results in a set of constraints. *)
val subst_closed_term_occ : env -> evar_map -> occurrences or_like_first ->
constr -> constr -> constr * evar_map
* [ subst_closed_term_occ_decl evd occl c ] replaces occurrences of
closed [ c ] at positions [ occl ] by [ Rel 1 ] in [ ] .
closed [c] at positions [occl] by [Rel 1] in [decl]. *)
val subst_closed_term_occ_decl : env -> evar_map ->
(occurrences * hyp_location_flag) or_like_first ->
constr -> named_declaration -> named_declaration * evar_map
val error_invalid_occurrence : int list -> 'a
|
1aa7a2c473a30a0df5f583b1750e4ef3fbad2489bb1906fe02721c82f135f4e9 | haslab/HAAP | MoveViewer.hs | # LANGUAGE PatternGuards #
# LANGUAGE ScopedTypeVariables #
module Main where
import JSImages
import LI11718
import OracleT4
import OracleT3
import OracleT2
import OracleT1
import System.Environment
import Test.QuickCheck.Gen
import Data.List
import Data.Maybe
import Safe
import Data.Char
import Debug.Trace
import GHC.Float
import Text.Printf
import Data.Map (Map(..))
import qualified Data.Map as Map
import Control.Monad
import Control.Exception
import qualified Data.Text as Text
import Text.Read
import qualified CodeWorld as CW
import Graphics.Gloss hiding ((.*.),(.+.),(.-.))
import Graphics . Gloss
import Graphics . Gloss . Data . Picture
import Graphics . Gloss . Interface . Pure . Game
import Graphics . Gloss .
import Graphics . Gloss . Geometry . Line
standard = Propriedades (1.5) 1 4 2 15 90
parado = Acao False False False False Nothing
data Estado = Estado
{ jogo :: Jogo
-- , acoes :: [Acao]
, tamBloco :: Float
, batotas :: [Float]
, mortes :: [Float]
, imagens :: [(String,Picture)]
}
centroPeca : : - > Posicao - > Ponto
centroPeca ( ) ( a , b ) = ( toEnum a+0.7,toEnum b+0.7 )
centroPeca ( ) ( a , b ) = ( toEnum a+0.3,toEnum b+0.7 )
centroPeca ( Curva Sul ) ( a , b ) = ( toEnum a+0.3,toEnum b+0.3 )
centroPeca ( ) ( a , b ) = ( toEnum a+0.7,toEnum b+0.3 )
--centroPeca _ (a,b) = (toEnum a+0.5,toEnum b+0.5)
estadoInicial :: Jogo -> Float -> [(String,Picture)] -> Estado
estadoInicial m tam imgs = Estado { jogo = m
, acoes = replicate njogadores parado
-- , timer = 0
, tamBloco = tam
, batotas = replicate (length (carros m)) 0
, mortes = replicate (length (carros m)) 0
, imagens = imgs }
qntnitro = 5
carroInicial :: Tabuleiro -> Posicao -> Int -> Carro
carroInicial t (a,b) i = Carro { posicao = centroPeca tp (a,b)
, direcao = 0
, velocidade = (0,0)
}
where (Peca tp _) = (atNote2 "carroInicial" t b a)
atualizaEMovimenta :: Tempo -> Jogo -> [Acao] -> (Jogo,[Float],[Float])
atualizaEMovimenta t j a = (jogoT4 { carros = map (\(i,_,_) -> i) carrosT3 }
, map (\(_,i,_) -> i) carrosT3
, map (\(_,_,i) -> i) carrosT3)
where jogadores = length (carros j) - 1
jogoT4 = geraJogoT4 jogadores
carrosT3 = map movimentaT3 [0..jogadores]
geraJogoT4 n | n<0 = j
| n>=0 = atualiza t (geraJogoT4 (n-1)) n (atNote "atualiza" a n)
Mapa _ tab = mapa jogoT4
movimentaT3 i | c == Nothing = (l, 1.5, 0)
| batota (mapa jogoT4) hi ci = (l', 0, 1.5)
| otherwise = (fromJust c, 0, 0)
where c = colide tab t ci
l = lixa (mapa jogoT4) hi ci
l' = lixa (mapa jogoT4) (tail hi) ci
hi = (atNote "hist" (historico jogoT4) i)
ci = (atNote "carr" (carros jogoT4) i)
batota :: Mapa -> [Posicao] -> Carro -> Bool
batota (Mapa p0 m) (h1:h2:_) _ = (length whereWasI - length whereAmI) > 4
where prc = percorre [] m (fst p0) (snd p0)
whereAmI = dropWhile (\(_,i,_) -> i /= h1) (prc++prc)
whereWasI = dropWhile (\(_,i,_) -> i /= h2) (prc++prc)
batota _ _ _ = False
lixa :: Mapa -> [Posicao] -> Carro -> Carro
lixa (Mapa _ t) ((i,j):_) c = c { posicao = p , velocidade = (0,0) }
where Peca tp _ = atNote2 "lixa" t j i
p = centroPeca tp (i,j)
--- begin gloss ---
getImage x e = fromJust $ lookup x (imagens e)
glossDesenha :: Bool -> Estado -> [Acao] -> Picture
glossDesenha drawMapa e acoes = Pictures
[Translate (-toEnum x*(tamBloco e)/2) (toEnum y*(tamBloco e)/2) (Pictures (m'++meta:p))]
, Translate ( ( -100)+toEnum x*(tamBloco e)/2 ) ( toEnum ) barra ]
where (Mapa ((i,j),_) m) = mapa (jogo e)
m' = if drawMapa then glossMapa e (0,0) m else [Blank]
barra = barraEstado e
[ 0 .. 3 ]
meta = Color green $ Line [((toEnum i*tamBloco e),-(toEnum j*tamBloco e))
,((toEnum i*tamBloco e),-(toEnum j*tamBloco e)-tamBloco e)]
x = (length (head m))
y = (length m)
glossBloco :: Estado -> Peca -> Picture
glossBloco e (Peca Recta p) = Color (corAltura p) $ Polygon [(0,-tamBloco e),(0,0),(tamBloco e,0),(tamBloco e,-tamBloco e)]
glossBloco e (Peca (Rampa Norte) p) = transitaBloco e (corAltura (p+1),corAltura p) False
glossBloco e (Peca (Rampa Oeste) p) = transitaBloco e (corAltura (p+1),corAltura p) True
glossBloco e (Peca (Rampa Sul) p) = transitaBloco e (corAltura p,corAltura (p+1)) False
glossBloco e (Peca (Rampa Este) p) = transitaBloco e (corAltura p,corAltura (p+1)) True
glossBloco e (Peca (Curva Oeste) p) = Pictures [getImage "lava" e,Color (corAltura p) $ Polygon [(0,0),(tamBloco e,0),(tamBloco e,-tamBloco e)]]
glossBloco e (Peca (Curva Sul) p) = Pictures [getImage "lava" e,Color (corAltura p) $ Polygon [(0,-tamBloco e),(tamBloco e,0),(0,0)]]
glossBloco e (Peca (Curva Norte) p) = Pictures [getImage "lava" e,Color (corAltura p) $ Polygon [(0,-tamBloco e),(tamBloco e,-tamBloco e),(tamBloco e,0)]]
glossBloco e (Peca (Curva Este) p) = Pictures [getImage "lava" e,Color (corAltura p) $ Polygon [(0,0),(0,-tamBloco e),(tamBloco e,-tamBloco e)]]
glossBloco e (Peca Lava _) = getImage "lava" e
numalturas = 5
corAltura :: Altura -> Color
corAltura a | a >= 0 = makeColor c c c 1
where c = (toEnum a) * 1 / numalturas
corAltura a | a < 0 = makeColor r 0 0 1
where r = abs (toEnum a) * 1 / numalturas
transitaBloco :: Estado -> (Color,Color) -> Bool -> Picture
transitaBloco e (c1,c2) i = Translate 0 gy $ Rotate g $ Pictures [a,b,c]
where a = Color c1 $ Polygon [(0,0),(tamBloco e/2,-tamBloco e),(tamBloco e,0)]
b = Color c2 $ Polygon [(0,0),(tamBloco e/2,-tamBloco e),(0,-tamBloco e)]
c = Color c2 $ Polygon [(tamBloco e,0),(tamBloco e/2,-tamBloco e),(tamBloco e,-tamBloco e)]
g = if i then -90 else 0
gy = if i then -tamBloco e else 0
glossMapa :: Estado -> (Float,Float) -> Tabuleiro -> [Picture]
glossMapa e (x,y) [] = []
glossMapa e (x,y) ([]:ls) = glossMapa e (0,y-tamBloco e) ls
glossMapa e (x,y) ((c:cs):ls) = (Translate x y $ glossBloco e c) : glossMapa e (x+tamBloco e,y) (cs:ls)
glossCarro :: Estado -> [Acao] -> Int -> Picture
glossCarro s acoes i = Pictures [Translate (fromx) (fromy) $ Scale 0.5 0.5 $ Rotate (-double2Float a) (Pictures [nits,pic,mrt,btt]),vel]
where p@(x,y) = posicao ci
v = velocidade ci
a = direcao ci
pic = getImage ("c"++(show (i+1))) s
nitpic i = getImage ("nitro" ++ show (i+1)) s
pufpic = getImage "puff" s
Mapa _ m = mapa (jogo s)
t = atNote2 "glossCarro" m (floor y) (floor x)
isnit = isTarget s acoes i
nits = Pictures $ map nit isnit
nit i | ni > 0 = Translate (-tamBloco s / 3) 0 (nitpic i)
| ni <= 0 = Translate (-tamBloco s / 3) 0 pufpic
| otherwise = Blank
(x',y') = p .+. v
fromx = realToFrac x * tamBloco s
fromy = - realToFrac y * tamBloco s
tox = realToFrac x' * tamBloco s
toy = -realToFrac y' * tamBloco s
vel = Color yellow $ Line [(fromx,fromy),(tox,toy)]
mrt = if (atNote "glossMor" (mortes s) i > 0) then Scale 2 2 (Translate (-tamBloco s / 2) (tamBloco s / 2) (getImage "mrt" s)) else Blank
btt = if (atNote "glossBat" (batotas s) i > 0) then Scale 2 2 (Translate (-tamBloco s / 2) (tamBloco s / 2) (getImage "btt" s)) else Blank
ci = atNote "glossCarr" (carros $ jogo s) i
ni = atNote "glossNitr" (nitros $ jogo s) i
isTarget :: Estado -> [Acao] -> Int -> [Int]
isTarget e acoes i = map fst (filter (\(x,y) -> y == Just i) as)
where as = zip [0..] (map nitro acoes)
glossTempo :: Float -> Estado -> [Acao] -> Estado
glossTempo t m acoes = m { jogo = j'
, batotas = (zipWith (\a b -> (max a b)-t) (batotas m) btts)
, mortes = (zipWith (\a b -> (max a b)-t) (mortes m) mrts)
}
where (j',mrts,btts) = atualizaEMovimenta (float2Double t) (jogo m) acoes
-- end gloss --
joga :: IO ()
joga = do
screen@(Display screenx screeny) <- getDisplay
txt <- CW.getTextContent
(tempo,jog,acao) <- case readMaybe txt :: Maybe (Tempo,Jogo,Acao) of
Nothing -> error $ "erro ao carregar (Tempo,Jogo,Acao): " ++ show txt
Just (tempo,jog,acao) -> return (tempo,jog,acao)
unless (validaJogo' tempo jog) $ error $ "teste (Tempo,Jogo,Acao) inválido: " ++ show (tempo,jog,acao)
let m@(Mapa _ tab) = mapa jog
let x::Int = length (head tab)
y::Int = length tab
tamanhoX::Float = (realToFrac screenx) / (realToFrac x)
tamanhoY::Float = (realToFrac screeny) / (realToFrac y)
tamanho = min tamanhoX tamanhoY
s = tamanho / 100
imgs <- loadImages tamanho screen
let e1 = estadoInicial jog tamanho imgs
replicate i parado + + [ acao ] + + replicate ( 3 - i ) parado
let e2 = glossTempo (realToFrac tempo) e1 acoes
let p1 = glossDesenha True e1 acoes
let p2 = glossDesenha False e2 []
display screen back (Pictures [p1,p2])
where
screenx = 1024
screeny = 768
screen = ( InWindow " MicroMachines " ( screenx , screeny ) ( 0 , 0 ) )
back = greyN 0.5
main = catch (joga) $ \(e::SomeException) -> CW.trace (Text.pack $ displayException e) $ throw e
--main = do
joga teste 0
teste : : ( Tempo , , Acao )
teste = ( 0.4,j',acao )
-- where
= [ ( ( 3,1),Este ) testeMapa ]
ini@(Mapa ) = mapas!!0
( Just 0 )
j =
j ' = j { = ( ( head $ carros j ) { velocidade = ( 1,0 ) } ) : tail ( carros j ) }
dir :: Ponto -> (Peca,Posicao,Orientacao) -> Double
dir p0 (Peca t _,p,_) = snd $ componentsToArrow (p'.-.p0)
where p' = centroPeca t p
distRad :: Int -> Int -> Int
distRad r1 r2 = ((r2-r1) + 180) `mod` 360 - 180
xys x y = atNote str ( atNote str xys x ) y | null | https://raw.githubusercontent.com/haslab/HAAP/5acf9efaf0e5f6cba1c2482e51bda703f405a86f/examples/plab/oracle/MoveViewer.hs | haskell | , acoes :: [Acao]
centroPeca _ (a,b) = (toEnum a+0.5,toEnum b+0.5)
, timer = 0
- begin gloss ---
end gloss --
main = do
where | # LANGUAGE PatternGuards #
# LANGUAGE ScopedTypeVariables #
module Main where
import JSImages
import LI11718
import OracleT4
import OracleT3
import OracleT2
import OracleT1
import System.Environment
import Test.QuickCheck.Gen
import Data.List
import Data.Maybe
import Safe
import Data.Char
import Debug.Trace
import GHC.Float
import Text.Printf
import Data.Map (Map(..))
import qualified Data.Map as Map
import Control.Monad
import Control.Exception
import qualified Data.Text as Text
import Text.Read
import qualified CodeWorld as CW
import Graphics.Gloss hiding ((.*.),(.+.),(.-.))
import Graphics . Gloss
import Graphics . Gloss . Data . Picture
import Graphics . Gloss . Interface . Pure . Game
import Graphics . Gloss .
import Graphics . Gloss . Geometry . Line
standard = Propriedades (1.5) 1 4 2 15 90
parado = Acao False False False False Nothing
data Estado = Estado
{ jogo :: Jogo
, tamBloco :: Float
, batotas :: [Float]
, mortes :: [Float]
, imagens :: [(String,Picture)]
}
centroPeca : : - > Posicao - > Ponto
centroPeca ( ) ( a , b ) = ( toEnum a+0.7,toEnum b+0.7 )
centroPeca ( ) ( a , b ) = ( toEnum a+0.3,toEnum b+0.7 )
centroPeca ( Curva Sul ) ( a , b ) = ( toEnum a+0.3,toEnum b+0.3 )
centroPeca ( ) ( a , b ) = ( toEnum a+0.7,toEnum b+0.3 )
estadoInicial :: Jogo -> Float -> [(String,Picture)] -> Estado
estadoInicial m tam imgs = Estado { jogo = m
, acoes = replicate njogadores parado
, tamBloco = tam
, batotas = replicate (length (carros m)) 0
, mortes = replicate (length (carros m)) 0
, imagens = imgs }
qntnitro = 5
carroInicial :: Tabuleiro -> Posicao -> Int -> Carro
carroInicial t (a,b) i = Carro { posicao = centroPeca tp (a,b)
, direcao = 0
, velocidade = (0,0)
}
where (Peca tp _) = (atNote2 "carroInicial" t b a)
atualizaEMovimenta :: Tempo -> Jogo -> [Acao] -> (Jogo,[Float],[Float])
atualizaEMovimenta t j a = (jogoT4 { carros = map (\(i,_,_) -> i) carrosT3 }
, map (\(_,i,_) -> i) carrosT3
, map (\(_,_,i) -> i) carrosT3)
where jogadores = length (carros j) - 1
jogoT4 = geraJogoT4 jogadores
carrosT3 = map movimentaT3 [0..jogadores]
geraJogoT4 n | n<0 = j
| n>=0 = atualiza t (geraJogoT4 (n-1)) n (atNote "atualiza" a n)
Mapa _ tab = mapa jogoT4
movimentaT3 i | c == Nothing = (l, 1.5, 0)
| batota (mapa jogoT4) hi ci = (l', 0, 1.5)
| otherwise = (fromJust c, 0, 0)
where c = colide tab t ci
l = lixa (mapa jogoT4) hi ci
l' = lixa (mapa jogoT4) (tail hi) ci
hi = (atNote "hist" (historico jogoT4) i)
ci = (atNote "carr" (carros jogoT4) i)
batota :: Mapa -> [Posicao] -> Carro -> Bool
batota (Mapa p0 m) (h1:h2:_) _ = (length whereWasI - length whereAmI) > 4
where prc = percorre [] m (fst p0) (snd p0)
whereAmI = dropWhile (\(_,i,_) -> i /= h1) (prc++prc)
whereWasI = dropWhile (\(_,i,_) -> i /= h2) (prc++prc)
batota _ _ _ = False
lixa :: Mapa -> [Posicao] -> Carro -> Carro
lixa (Mapa _ t) ((i,j):_) c = c { posicao = p , velocidade = (0,0) }
where Peca tp _ = atNote2 "lixa" t j i
p = centroPeca tp (i,j)
getImage x e = fromJust $ lookup x (imagens e)
glossDesenha :: Bool -> Estado -> [Acao] -> Picture
glossDesenha drawMapa e acoes = Pictures
[Translate (-toEnum x*(tamBloco e)/2) (toEnum y*(tamBloco e)/2) (Pictures (m'++meta:p))]
, Translate ( ( -100)+toEnum x*(tamBloco e)/2 ) ( toEnum ) barra ]
where (Mapa ((i,j),_) m) = mapa (jogo e)
m' = if drawMapa then glossMapa e (0,0) m else [Blank]
barra = barraEstado e
[ 0 .. 3 ]
meta = Color green $ Line [((toEnum i*tamBloco e),-(toEnum j*tamBloco e))
,((toEnum i*tamBloco e),-(toEnum j*tamBloco e)-tamBloco e)]
x = (length (head m))
y = (length m)
glossBloco :: Estado -> Peca -> Picture
glossBloco e (Peca Recta p) = Color (corAltura p) $ Polygon [(0,-tamBloco e),(0,0),(tamBloco e,0),(tamBloco e,-tamBloco e)]
glossBloco e (Peca (Rampa Norte) p) = transitaBloco e (corAltura (p+1),corAltura p) False
glossBloco e (Peca (Rampa Oeste) p) = transitaBloco e (corAltura (p+1),corAltura p) True
glossBloco e (Peca (Rampa Sul) p) = transitaBloco e (corAltura p,corAltura (p+1)) False
glossBloco e (Peca (Rampa Este) p) = transitaBloco e (corAltura p,corAltura (p+1)) True
glossBloco e (Peca (Curva Oeste) p) = Pictures [getImage "lava" e,Color (corAltura p) $ Polygon [(0,0),(tamBloco e,0),(tamBloco e,-tamBloco e)]]
glossBloco e (Peca (Curva Sul) p) = Pictures [getImage "lava" e,Color (corAltura p) $ Polygon [(0,-tamBloco e),(tamBloco e,0),(0,0)]]
glossBloco e (Peca (Curva Norte) p) = Pictures [getImage "lava" e,Color (corAltura p) $ Polygon [(0,-tamBloco e),(tamBloco e,-tamBloco e),(tamBloco e,0)]]
glossBloco e (Peca (Curva Este) p) = Pictures [getImage "lava" e,Color (corAltura p) $ Polygon [(0,0),(0,-tamBloco e),(tamBloco e,-tamBloco e)]]
glossBloco e (Peca Lava _) = getImage "lava" e
numalturas = 5
corAltura :: Altura -> Color
corAltura a | a >= 0 = makeColor c c c 1
where c = (toEnum a) * 1 / numalturas
corAltura a | a < 0 = makeColor r 0 0 1
where r = abs (toEnum a) * 1 / numalturas
transitaBloco :: Estado -> (Color,Color) -> Bool -> Picture
transitaBloco e (c1,c2) i = Translate 0 gy $ Rotate g $ Pictures [a,b,c]
where a = Color c1 $ Polygon [(0,0),(tamBloco e/2,-tamBloco e),(tamBloco e,0)]
b = Color c2 $ Polygon [(0,0),(tamBloco e/2,-tamBloco e),(0,-tamBloco e)]
c = Color c2 $ Polygon [(tamBloco e,0),(tamBloco e/2,-tamBloco e),(tamBloco e,-tamBloco e)]
g = if i then -90 else 0
gy = if i then -tamBloco e else 0
glossMapa :: Estado -> (Float,Float) -> Tabuleiro -> [Picture]
glossMapa e (x,y) [] = []
glossMapa e (x,y) ([]:ls) = glossMapa e (0,y-tamBloco e) ls
glossMapa e (x,y) ((c:cs):ls) = (Translate x y $ glossBloco e c) : glossMapa e (x+tamBloco e,y) (cs:ls)
glossCarro :: Estado -> [Acao] -> Int -> Picture
glossCarro s acoes i = Pictures [Translate (fromx) (fromy) $ Scale 0.5 0.5 $ Rotate (-double2Float a) (Pictures [nits,pic,mrt,btt]),vel]
where p@(x,y) = posicao ci
v = velocidade ci
a = direcao ci
pic = getImage ("c"++(show (i+1))) s
nitpic i = getImage ("nitro" ++ show (i+1)) s
pufpic = getImage "puff" s
Mapa _ m = mapa (jogo s)
t = atNote2 "glossCarro" m (floor y) (floor x)
isnit = isTarget s acoes i
nits = Pictures $ map nit isnit
nit i | ni > 0 = Translate (-tamBloco s / 3) 0 (nitpic i)
| ni <= 0 = Translate (-tamBloco s / 3) 0 pufpic
| otherwise = Blank
(x',y') = p .+. v
fromx = realToFrac x * tamBloco s
fromy = - realToFrac y * tamBloco s
tox = realToFrac x' * tamBloco s
toy = -realToFrac y' * tamBloco s
vel = Color yellow $ Line [(fromx,fromy),(tox,toy)]
mrt = if (atNote "glossMor" (mortes s) i > 0) then Scale 2 2 (Translate (-tamBloco s / 2) (tamBloco s / 2) (getImage "mrt" s)) else Blank
btt = if (atNote "glossBat" (batotas s) i > 0) then Scale 2 2 (Translate (-tamBloco s / 2) (tamBloco s / 2) (getImage "btt" s)) else Blank
ci = atNote "glossCarr" (carros $ jogo s) i
ni = atNote "glossNitr" (nitros $ jogo s) i
isTarget :: Estado -> [Acao] -> Int -> [Int]
isTarget e acoes i = map fst (filter (\(x,y) -> y == Just i) as)
where as = zip [0..] (map nitro acoes)
glossTempo :: Float -> Estado -> [Acao] -> Estado
glossTempo t m acoes = m { jogo = j'
, batotas = (zipWith (\a b -> (max a b)-t) (batotas m) btts)
, mortes = (zipWith (\a b -> (max a b)-t) (mortes m) mrts)
}
where (j',mrts,btts) = atualizaEMovimenta (float2Double t) (jogo m) acoes
joga :: IO ()
joga = do
screen@(Display screenx screeny) <- getDisplay
txt <- CW.getTextContent
(tempo,jog,acao) <- case readMaybe txt :: Maybe (Tempo,Jogo,Acao) of
Nothing -> error $ "erro ao carregar (Tempo,Jogo,Acao): " ++ show txt
Just (tempo,jog,acao) -> return (tempo,jog,acao)
unless (validaJogo' tempo jog) $ error $ "teste (Tempo,Jogo,Acao) inválido: " ++ show (tempo,jog,acao)
let m@(Mapa _ tab) = mapa jog
let x::Int = length (head tab)
y::Int = length tab
tamanhoX::Float = (realToFrac screenx) / (realToFrac x)
tamanhoY::Float = (realToFrac screeny) / (realToFrac y)
tamanho = min tamanhoX tamanhoY
s = tamanho / 100
imgs <- loadImages tamanho screen
let e1 = estadoInicial jog tamanho imgs
replicate i parado + + [ acao ] + + replicate ( 3 - i ) parado
let e2 = glossTempo (realToFrac tempo) e1 acoes
let p1 = glossDesenha True e1 acoes
let p2 = glossDesenha False e2 []
display screen back (Pictures [p1,p2])
where
screenx = 1024
screeny = 768
screen = ( InWindow " MicroMachines " ( screenx , screeny ) ( 0 , 0 ) )
back = greyN 0.5
main = catch (joga) $ \(e::SomeException) -> CW.trace (Text.pack $ displayException e) $ throw e
joga teste 0
teste : : ( Tempo , , Acao )
teste = ( 0.4,j',acao )
= [ ( ( 3,1),Este ) testeMapa ]
ini@(Mapa ) = mapas!!0
( Just 0 )
j =
j ' = j { = ( ( head $ carros j ) { velocidade = ( 1,0 ) } ) : tail ( carros j ) }
dir :: Ponto -> (Peca,Posicao,Orientacao) -> Double
dir p0 (Peca t _,p,_) = snd $ componentsToArrow (p'.-.p0)
where p' = centroPeca t p
distRad :: Int -> Int -> Int
distRad r1 r2 = ((r2-r1) + 180) `mod` 360 - 180
xys x y = atNote str ( atNote str xys x ) y |
453fb5939acf02423864da26c322f890eeec1527d56efd1da041145751f86a00 | reanimate/reanimate | morphology_closest.hs | #!/usr/bin/env stack
-- stack runghc --package reanimate
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ParallelListComp #-}
module Main(main) where
import Codec.Picture
import Codec.Picture.Types
import Control.Lens ((&))
import Control.Monad
import Graphics.SvgTree (LineJoin (..))
import Reanimate
import Reanimate.Morph.Common
import Reanimate.Morph.Linear
bgColor :: PixelRGBA8
bgColor = PixelRGBA8 252 252 252 0xFF
main :: IO ()
main = reanimate $
addStatic (mkBackgroundPixel bgColor) $
mapA (withStrokeWidth defaultStrokeWidth) $
mapA (withStrokeColor "black") $
mapA (withStrokeLineJoin JoinRound) $
mapA (withFillOpacity 1) $
scene $ do
_ <- newSpriteSVG $
withStrokeWidth 0 $ translate (-4) 4 $
center $ latex "no-op"
_ <- newSpriteSVG $
withStrokeWidth 0 $ translate 4 4 $
center $ latex "closest"
forM_ pairs $ uncurry showPair
where
showPair from to =
waitOn $ do
fork $ play $ mkAnimation 4 (morph rawLinear from to)
& mapA (translate (-4) (-0.5))
& signalA (curveS 4)
fork $ play $ mkAnimation 4 (morph linear from to)
& mapA (translate 4 (-0.5))
& signalA (curveS 4)
pairs = zip stages (tail stages ++ [head stages])
stages = map (lowerTransformations . scale 8 . pathify . center) $ colorize
[ latex "X"
, latex "$\\aleph$"
, latex "Y"
, latex "$\\infty$"
, latex "I"
, latex "$\\pi$"
, latex "1"
, latex "S"
, mkRect 0.5 0.5
]
colorize :: [SVG] -> [SVG]
colorize lst =
[ withFillColorPixel (promotePixel $ parula (n/fromIntegral (length lst-1))) elt
| elt <- lst
| n <- [0..]
]
| null | https://raw.githubusercontent.com/reanimate/reanimate/5ea023980ff7f488934d40593cc5069f5fd038b0/examples/morphology_closest.hs | haskell | stack runghc --package reanimate
# LANGUAGE OverloadedStrings #
# LANGUAGE ParallelListComp # | #!/usr/bin/env stack
module Main(main) where
import Codec.Picture
import Codec.Picture.Types
import Control.Lens ((&))
import Control.Monad
import Graphics.SvgTree (LineJoin (..))
import Reanimate
import Reanimate.Morph.Common
import Reanimate.Morph.Linear
bgColor :: PixelRGBA8
bgColor = PixelRGBA8 252 252 252 0xFF
main :: IO ()
main = reanimate $
addStatic (mkBackgroundPixel bgColor) $
mapA (withStrokeWidth defaultStrokeWidth) $
mapA (withStrokeColor "black") $
mapA (withStrokeLineJoin JoinRound) $
mapA (withFillOpacity 1) $
scene $ do
_ <- newSpriteSVG $
withStrokeWidth 0 $ translate (-4) 4 $
center $ latex "no-op"
_ <- newSpriteSVG $
withStrokeWidth 0 $ translate 4 4 $
center $ latex "closest"
forM_ pairs $ uncurry showPair
where
showPair from to =
waitOn $ do
fork $ play $ mkAnimation 4 (morph rawLinear from to)
& mapA (translate (-4) (-0.5))
& signalA (curveS 4)
fork $ play $ mkAnimation 4 (morph linear from to)
& mapA (translate 4 (-0.5))
& signalA (curveS 4)
pairs = zip stages (tail stages ++ [head stages])
stages = map (lowerTransformations . scale 8 . pathify . center) $ colorize
[ latex "X"
, latex "$\\aleph$"
, latex "Y"
, latex "$\\infty$"
, latex "I"
, latex "$\\pi$"
, latex "1"
, latex "S"
, mkRect 0.5 0.5
]
colorize :: [SVG] -> [SVG]
colorize lst =
[ withFillColorPixel (promotePixel $ parula (n/fromIntegral (length lst-1))) elt
| elt <- lst
| n <- [0..]
]
|
d2bdc93725bc8c652ed289329434d1779314e8a0d2f05381850a4c128c98d820 | sondresl/AdventOfCode | Day24.hs | module Day24 where
import Lib
import Control.Lens
import Data.List.Extra
parseInput = id
part1 input = undefined
part2 input = undefined
main :: IO ()
main = do
input <- parseInput <$> readFile "../data/day01.in"
print input
-- print $ part1 input
-- print $ part2 input
| null | https://raw.githubusercontent.com/sondresl/AdventOfCode/224cf59354c7c1c31821f36884fe8909c5fdf9a6/2015/Haskell/src/Day24.hs | haskell | print $ part1 input
print $ part2 input | module Day24 where
import Lib
import Control.Lens
import Data.List.Extra
parseInput = id
part1 input = undefined
part2 input = undefined
main :: IO ()
main = do
input <- parseInput <$> readFile "../data/day01.in"
print input
|
505ee45ad982f5c2b5344acc0ebc5a2aaa8c016200ac81cc4dd989b586c00739 | rescript-lang/syntax | res_parser.mli | module Scanner = Res_scanner
module Token = Res_token
module Grammar = Res_grammar
module Reporting = Res_reporting
module Diagnostics = Res_diagnostics
module Comment = Res_comment
type mode = ParseForTypeChecker | Default
type regionStatus = Report | Silent
type t = {
mode: mode;
mutable scanner: Scanner.t;
mutable token: Token.t;
mutable startPos: Lexing.position;
mutable endPos: Lexing.position;
mutable prevEndPos: Lexing.position;
mutable breadcrumbs: (Grammar.t * Lexing.position) list;
mutable errors: Reporting.parseError list;
mutable diagnostics: Diagnostics.t list;
mutable comments: Comment.t list;
mutable regions: regionStatus ref list;
}
val make : ?mode:mode -> string -> string -> t
val expect : ?grammar:Grammar.t -> Token.t -> t -> unit
val optional : t -> Token.t -> bool
val next : ?prevEndPos:Lexing.position -> t -> unit
Does not assert on Eof , makes no progress
val nextTemplateLiteralToken : t -> unit
val lookahead : t -> (t -> 'a) -> 'a
val err :
?startPos:Lexing.position ->
?endPos:Lexing.position ->
t ->
Diagnostics.category ->
unit
val leaveBreadcrumb : t -> Grammar.t -> unit
val eatBreadcrumb : t -> unit
val beginRegion : t -> unit
val endRegion : t -> unit
val checkProgress : prevEndPos:Lexing.position -> result:'a -> t -> 'a option
| null | https://raw.githubusercontent.com/rescript-lang/syntax/67fec537284579e58bee8e70120bff8e03688fa8/src/res_parser.mli | ocaml | module Scanner = Res_scanner
module Token = Res_token
module Grammar = Res_grammar
module Reporting = Res_reporting
module Diagnostics = Res_diagnostics
module Comment = Res_comment
type mode = ParseForTypeChecker | Default
type regionStatus = Report | Silent
type t = {
mode: mode;
mutable scanner: Scanner.t;
mutable token: Token.t;
mutable startPos: Lexing.position;
mutable endPos: Lexing.position;
mutable prevEndPos: Lexing.position;
mutable breadcrumbs: (Grammar.t * Lexing.position) list;
mutable errors: Reporting.parseError list;
mutable diagnostics: Diagnostics.t list;
mutable comments: Comment.t list;
mutable regions: regionStatus ref list;
}
val make : ?mode:mode -> string -> string -> t
val expect : ?grammar:Grammar.t -> Token.t -> t -> unit
val optional : t -> Token.t -> bool
val next : ?prevEndPos:Lexing.position -> t -> unit
Does not assert on Eof , makes no progress
val nextTemplateLiteralToken : t -> unit
val lookahead : t -> (t -> 'a) -> 'a
val err :
?startPos:Lexing.position ->
?endPos:Lexing.position ->
t ->
Diagnostics.category ->
unit
val leaveBreadcrumb : t -> Grammar.t -> unit
val eatBreadcrumb : t -> unit
val beginRegion : t -> unit
val endRegion : t -> unit
val checkProgress : prevEndPos:Lexing.position -> result:'a -> t -> 'a option
| |
0befaad4e5c8a47a41f5a1375ff118be4f9a7d6ae0eeabd60d29dddffcc56de5 | cndreisbach/clojure-web-dev-workshop | handler.clj | (ns we-owe.handler
(:require [clojure.pprint :refer [pprint]]
[ring.middleware
[stacktrace :refer [wrap-stacktrace]]
[mime-extensions :refer [wrap-convert-extension-to-accept-header]]]
[compojure.core :refer :all]
[compojure.route :as route]
[compojure.handler :as handler]
[noir.response :as response]
[noir.util.route :refer [restricted]]
[noir.util.middleware :refer [app-handler]]
[noir.session :as session]
[we-owe.views :as views]
[we-owe.resources :as resources]))
(defn- logged-in? [request]
(session/get :user))
(defn create-routes [db]
(routes
(GET "/" [] (response/redirect "/debts" :permanent))
(GET "/debts" [] resources/debts)
(ANY "/debts/add" [] (restricted resources/add-debt))
(POST "/debts/add.json" {body :body} (views/add-debt-json db (slurp body)))
(GET "/user/:user.json" [user] (restricted (resources/user user)))
(GET "/user/:user" [user] (restricted (resources/user user)))
(GET "/login" [] (views/login-page))
(POST "/login" [username password]
(views/login-post db {:username username :password password}))
(ANY "/logout" [] (views/logout-page))
(GET "/*.css" {{path :*} :route-params} (views/css-page path))
(route/resources "/")
(route/not-found "Page not found")))
(defn wrap-db [handler db]
(fn [{:as request}]
(-> request
(assoc :db db)
handler)))
(defn create-handler [db]
(-> (app-handler
[(create-routes db)]
:access-rules [{:redirect "/login"
:rules [logged-in?]}])
(wrap-db db)
(wrap-convert-extension-to-accept-header)
(wrap-stacktrace)))
(def ring-handler
(create-handler
(atom {:debts [{:from "Clinton" :to "Pete" :amount 3.50}
{:from "Clinton" :to "Diego" :amount 2.00}
{:from "Pete" :to "Clinton" :amount 1.25}
{:from "Jill" :to "Pete" :amount 10.00}]})))
| null | https://raw.githubusercontent.com/cndreisbach/clojure-web-dev-workshop/95d9fdf94b39f8a1e408b8bf75a81b92899ee7d9/code/05-liberator/src/we_owe/handler.clj | clojure | (ns we-owe.handler
(:require [clojure.pprint :refer [pprint]]
[ring.middleware
[stacktrace :refer [wrap-stacktrace]]
[mime-extensions :refer [wrap-convert-extension-to-accept-header]]]
[compojure.core :refer :all]
[compojure.route :as route]
[compojure.handler :as handler]
[noir.response :as response]
[noir.util.route :refer [restricted]]
[noir.util.middleware :refer [app-handler]]
[noir.session :as session]
[we-owe.views :as views]
[we-owe.resources :as resources]))
(defn- logged-in? [request]
(session/get :user))
(defn create-routes [db]
(routes
(GET "/" [] (response/redirect "/debts" :permanent))
(GET "/debts" [] resources/debts)
(ANY "/debts/add" [] (restricted resources/add-debt))
(POST "/debts/add.json" {body :body} (views/add-debt-json db (slurp body)))
(GET "/user/:user.json" [user] (restricted (resources/user user)))
(GET "/user/:user" [user] (restricted (resources/user user)))
(GET "/login" [] (views/login-page))
(POST "/login" [username password]
(views/login-post db {:username username :password password}))
(ANY "/logout" [] (views/logout-page))
(GET "/*.css" {{path :*} :route-params} (views/css-page path))
(route/resources "/")
(route/not-found "Page not found")))
(defn wrap-db [handler db]
(fn [{:as request}]
(-> request
(assoc :db db)
handler)))
(defn create-handler [db]
(-> (app-handler
[(create-routes db)]
:access-rules [{:redirect "/login"
:rules [logged-in?]}])
(wrap-db db)
(wrap-convert-extension-to-accept-header)
(wrap-stacktrace)))
(def ring-handler
(create-handler
(atom {:debts [{:from "Clinton" :to "Pete" :amount 3.50}
{:from "Clinton" :to "Diego" :amount 2.00}
{:from "Pete" :to "Clinton" :amount 1.25}
{:from "Jill" :to "Pete" :amount 10.00}]})))
| |
9682a29c23cf56aa4ded884c54d7f44038a93331a9368b9e9b5325e7781011ef | fmthoma/vty-workshop | Pong.hs | module Pong (pong) where
import Brick
import Brick.BChan
import Brick.Widgets.Border
import Brick.Widgets.Center
import Brick.Widgets.Dialog
import Control.Concurrent
import Control.Concurrent.Async
import Control.Monad
import Graphics.Vty as Vty
import Lens.Micro
import Lens.Micro.Extras
import Pong.Motions
import Pong.Opponent
import Pong.Physics
import Pong.Types
pong :: IO ()
pong = do
events <- newBChan 1000
eventThread (writeBChan events PhysicsTick >> threadDelay physicsDelay)
eventThread (writeBChan events OpponentTick >> threadDelay opponentDelay)
void (customMain (Vty.mkVty Vty.defaultConfig) (Just events) app Ready)
where
physicsDelay, opponentDelay :: Int
physicsDelay = microseconds (1 / 100)
opponentDelay = microseconds (1 / 10)
microseconds :: Double -> Int
microseconds = round . (* 1000000)
eventThread = void . async . forever
data Tick = PhysicsTick | OpponentTick
app :: App AppState Tick ()
app = App
{ appDraw = \state -> case state of
Running gameState -> [renderGame gameState]
Paused gameState d -> [suspended d, renderGame gameState]
Ready -> [areYouReady]
, appChooseCursor = const (const Nothing)
, appHandleEvent = appEvent
, appStartEvent = pure
, appAttrMap = const (attrMap defAttr [(buttonSelectedAttr, defAttr `withStyle` standout)]) }
data AppState
= Running GameState
| Paused GameState (Dialog Bool)
| Ready
newGame :: GameState
newGame = GameState
{ _lPlayer = Player { _pTop = 10, _pHeight = 10, _score = 0 }
, _rPlayer = Player { _pTop = 10, _pHeight = 10, _score = 0 }
, _field = Field {_fHeight = 30, _fWidth = 116 }
, _ball = Ball
{ _position = Cartesian { _x = 60, _y = 15 }
, _velocity = Polar { _r = 0.5, _phi = -0.13 } } }
appEvent :: AppState -> BrickEvent n Tick -> EventM n (Next AppState)
appEvent (Running gameState) event = case event of
VtyEvent e -> case e of
Vty.EvKey Vty.KEsc [] -> continue (Paused gameState yesNoDialog)
Vty.EvKey Vty.KUp [] -> continue (Running (mvLPlayer (-1) gameState))
Vty.EvKey Vty.KDown [] -> continue (Running (mvLPlayer 1 gameState))
_ -> continue (Running gameState)
AppEvent e -> case e of
PhysicsTick -> case collisions (inertialMovement gameState) of
WithinBounds gameState' -> continue (Running gameState')
LeftOutOfBounds -> continue (Running (over (rPlayer . score) (+1) (resetGame gameState newGame)))
RightOutOfBounds -> continue (Running (over (lPlayer . score) (+1) (resetGame gameState newGame)))
OpponentTick -> continue (Running (mvOpponent gameState))
_ -> continue (Running gameState)
appEvent (Paused gameState d) event = case event of
VtyEvent (EvKey KEnter []) -> case dialogSelection d of
Nothing -> continue (Paused gameState d)
Just True -> continue (Running gameState)
Just False -> halt (Running gameState)
VtyEvent e -> handleDialogEvent e d >>= continue . Paused gameState
_ -> continue (Paused gameState d)
appEvent Ready event = case event of
VtyEvent (EvKey KEnter []) -> continue (Running newGame)
_ -> continue Ready
renderPaddle :: Player -> Widget n
renderPaddle playerState = Widget
{ hSize = Fixed
, vSize = Fixed
, render = pure emptyResult { image = paddleImg } }
where
paddleImg = Vty.translateY paddleTop (Vty.charFill Vty.defAttr '#' 1 paddleHeight)
paddleTop = view pTop playerState
paddleHeight = view pHeight playerState
renderField :: Field -> Ball -> Widget n
renderField f b = Widget
{ hSize = Fixed
, vSize = Fixed
, render = pure emptyResult { image = fieldImage } }
where
fieldImage = Vty.resize fieldWidth fieldHeight
( Vty.translate ballX ballY
( Vty.char Vty.defAttr 'o' ) )
ballX = view (position . x . to round) b
ballY = view (position . y . to round) b
fieldWidth = view fWidth f
fieldHeight = view fHeight f
renderGame :: GameState -> Widget n
renderGame gameState = center $ borderWithLabel scoreWidget fieldWidget
where
scoreWidget = padLeftRight 1 $ hBox
[ view (lPlayer . score . to show . to str) gameState
, str " : "
, view (rPlayer . score . to show . to str) gameState ]
fieldWidget = vLimit fieldHeight $ hBox
[ renderPaddle (view lPlayer gameState)
, renderField (view field gameState) (view ball gameState)
, renderPaddle (view rPlayer gameState) ]
fieldHeight = view (field . fHeight) gameState
readyDialog :: Dialog ()
readyDialog = dialog (Just "Pong") (Just (0, [("Go!", ())])) 40
yesNoDialog :: Dialog Bool
yesNoDialog = dialog (Just "Pong") (Just (0, [("Yes", True), ("No", False)])) 40
areYouReady :: Widget n
areYouReady = renderDialog readyDialog (hCenter (padAll 2 (str "Are you ready?")))
suspended :: Dialog Bool -> Widget n
suspended d = renderDialog d (hCenter (padAll 2 (str "Game paused." <=> str "Do you want to continue?")))
| null | https://raw.githubusercontent.com/fmthoma/vty-workshop/7e39ee78e059009a3caa1c4924e4517bda428902/code/src/Pong.hs | haskell | module Pong (pong) where
import Brick
import Brick.BChan
import Brick.Widgets.Border
import Brick.Widgets.Center
import Brick.Widgets.Dialog
import Control.Concurrent
import Control.Concurrent.Async
import Control.Monad
import Graphics.Vty as Vty
import Lens.Micro
import Lens.Micro.Extras
import Pong.Motions
import Pong.Opponent
import Pong.Physics
import Pong.Types
pong :: IO ()
pong = do
events <- newBChan 1000
eventThread (writeBChan events PhysicsTick >> threadDelay physicsDelay)
eventThread (writeBChan events OpponentTick >> threadDelay opponentDelay)
void (customMain (Vty.mkVty Vty.defaultConfig) (Just events) app Ready)
where
physicsDelay, opponentDelay :: Int
physicsDelay = microseconds (1 / 100)
opponentDelay = microseconds (1 / 10)
microseconds :: Double -> Int
microseconds = round . (* 1000000)
eventThread = void . async . forever
data Tick = PhysicsTick | OpponentTick
app :: App AppState Tick ()
app = App
{ appDraw = \state -> case state of
Running gameState -> [renderGame gameState]
Paused gameState d -> [suspended d, renderGame gameState]
Ready -> [areYouReady]
, appChooseCursor = const (const Nothing)
, appHandleEvent = appEvent
, appStartEvent = pure
, appAttrMap = const (attrMap defAttr [(buttonSelectedAttr, defAttr `withStyle` standout)]) }
data AppState
= Running GameState
| Paused GameState (Dialog Bool)
| Ready
newGame :: GameState
newGame = GameState
{ _lPlayer = Player { _pTop = 10, _pHeight = 10, _score = 0 }
, _rPlayer = Player { _pTop = 10, _pHeight = 10, _score = 0 }
, _field = Field {_fHeight = 30, _fWidth = 116 }
, _ball = Ball
{ _position = Cartesian { _x = 60, _y = 15 }
, _velocity = Polar { _r = 0.5, _phi = -0.13 } } }
appEvent :: AppState -> BrickEvent n Tick -> EventM n (Next AppState)
appEvent (Running gameState) event = case event of
VtyEvent e -> case e of
Vty.EvKey Vty.KEsc [] -> continue (Paused gameState yesNoDialog)
Vty.EvKey Vty.KUp [] -> continue (Running (mvLPlayer (-1) gameState))
Vty.EvKey Vty.KDown [] -> continue (Running (mvLPlayer 1 gameState))
_ -> continue (Running gameState)
AppEvent e -> case e of
PhysicsTick -> case collisions (inertialMovement gameState) of
WithinBounds gameState' -> continue (Running gameState')
LeftOutOfBounds -> continue (Running (over (rPlayer . score) (+1) (resetGame gameState newGame)))
RightOutOfBounds -> continue (Running (over (lPlayer . score) (+1) (resetGame gameState newGame)))
OpponentTick -> continue (Running (mvOpponent gameState))
_ -> continue (Running gameState)
appEvent (Paused gameState d) event = case event of
VtyEvent (EvKey KEnter []) -> case dialogSelection d of
Nothing -> continue (Paused gameState d)
Just True -> continue (Running gameState)
Just False -> halt (Running gameState)
VtyEvent e -> handleDialogEvent e d >>= continue . Paused gameState
_ -> continue (Paused gameState d)
appEvent Ready event = case event of
VtyEvent (EvKey KEnter []) -> continue (Running newGame)
_ -> continue Ready
renderPaddle :: Player -> Widget n
renderPaddle playerState = Widget
{ hSize = Fixed
, vSize = Fixed
, render = pure emptyResult { image = paddleImg } }
where
paddleImg = Vty.translateY paddleTop (Vty.charFill Vty.defAttr '#' 1 paddleHeight)
paddleTop = view pTop playerState
paddleHeight = view pHeight playerState
renderField :: Field -> Ball -> Widget n
renderField f b = Widget
{ hSize = Fixed
, vSize = Fixed
, render = pure emptyResult { image = fieldImage } }
where
fieldImage = Vty.resize fieldWidth fieldHeight
( Vty.translate ballX ballY
( Vty.char Vty.defAttr 'o' ) )
ballX = view (position . x . to round) b
ballY = view (position . y . to round) b
fieldWidth = view fWidth f
fieldHeight = view fHeight f
renderGame :: GameState -> Widget n
renderGame gameState = center $ borderWithLabel scoreWidget fieldWidget
where
scoreWidget = padLeftRight 1 $ hBox
[ view (lPlayer . score . to show . to str) gameState
, str " : "
, view (rPlayer . score . to show . to str) gameState ]
fieldWidget = vLimit fieldHeight $ hBox
[ renderPaddle (view lPlayer gameState)
, renderField (view field gameState) (view ball gameState)
, renderPaddle (view rPlayer gameState) ]
fieldHeight = view (field . fHeight) gameState
readyDialog :: Dialog ()
readyDialog = dialog (Just "Pong") (Just (0, [("Go!", ())])) 40
yesNoDialog :: Dialog Bool
yesNoDialog = dialog (Just "Pong") (Just (0, [("Yes", True), ("No", False)])) 40
areYouReady :: Widget n
areYouReady = renderDialog readyDialog (hCenter (padAll 2 (str "Are you ready?")))
suspended :: Dialog Bool -> Widget n
suspended d = renderDialog d (hCenter (padAll 2 (str "Game paused." <=> str "Do you want to continue?")))
| |
cddb89aa5d9fae63cb713f3adc1a73a1e45d9f5e85af9192692b5dbb0765a63a | xapi-project/squeezed | squeezed_xenstore.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.
*)
open Xcp_service
module D = Debug.Make (struct let name = Memory_interface.service_name end)
open D
open Xs_protocol
module Client = Xs_client_unix.Client (Xs_transport_unix_client)
let myclient = ref None
let myclient_m = Mutex.create ()
let open_client () =
try Client.make ()
with e ->
error "Failed to connect to xenstore. The raw error was: %s"
(Printexc.to_string e) ;
( match e with
| Unix.Unix_error (Unix.EACCES, _, _) ->
error "Access to xenstore was denied." ;
let euid = Unix.geteuid () in
if euid <> 0 then (
error "My effective uid is %d." euid ;
error "Typically xenstore can only be accessed by root (uid 0)." ;
error "Please switch to root (uid 0) and retry."
)
| Unix.Unix_error (Unix.ECONNREFUSED, _, _) ->
error "Access to xenstore was refused." ;
error "This normally indicates that the service is not running." ;
error "Please start the xenstore service and retry."
| _ ->
()
) ;
raise e
let get_client () =
Xapi_stdext_threads.Threadext.Mutex.execute myclient_m (fun () ->
match !myclient with
| None -> (
let finished = ref false in
while not !finished do
try
let client = open_client () in
myclient := Some client ;
finished := true
with e ->
error
"Caught %s connecting to xenstore; waiting 5s before retrying"
(Printexc.to_string e) ;
Thread.delay 5.
done ;
match !myclient with None -> assert false | Some x -> x
)
| Some c ->
c)
| null | https://raw.githubusercontent.com/xapi-project/squeezed/1c23bfe2d8284384ad66fa0dedb1583b570369b8/src/squeezed_xenstore.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.
*)
open Xcp_service
module D = Debug.Make (struct let name = Memory_interface.service_name end)
open D
open Xs_protocol
module Client = Xs_client_unix.Client (Xs_transport_unix_client)
let myclient = ref None
let myclient_m = Mutex.create ()
let open_client () =
try Client.make ()
with e ->
error "Failed to connect to xenstore. The raw error was: %s"
(Printexc.to_string e) ;
( match e with
| Unix.Unix_error (Unix.EACCES, _, _) ->
error "Access to xenstore was denied." ;
let euid = Unix.geteuid () in
if euid <> 0 then (
error "My effective uid is %d." euid ;
error "Typically xenstore can only be accessed by root (uid 0)." ;
error "Please switch to root (uid 0) and retry."
)
| Unix.Unix_error (Unix.ECONNREFUSED, _, _) ->
error "Access to xenstore was refused." ;
error "This normally indicates that the service is not running." ;
error "Please start the xenstore service and retry."
| _ ->
()
) ;
raise e
let get_client () =
Xapi_stdext_threads.Threadext.Mutex.execute myclient_m (fun () ->
match !myclient with
| None -> (
let finished = ref false in
while not !finished do
try
let client = open_client () in
myclient := Some client ;
finished := true
with e ->
error
"Caught %s connecting to xenstore; waiting 5s before retrying"
(Printexc.to_string e) ;
Thread.delay 5.
done ;
match !myclient with None -> assert false | Some x -> x
)
| Some c ->
c)
| |
140cbf8c0d5064559ea6ff1255070332411982caae7b78c3d41e1ac234204e3c | typelead/intellij-eta | VirtualFile.hs | module FFI.Com.IntelliJ.OpenApi.Vfs.VirtualFile where
import P.Base
data {-# CLASS "com.intellij.openapi.vfs.VirtualFile" #-}
VirtualFile = VirtualFile (Object# VirtualFile)
deriving Class
foreign import java unsafe "getPath" getPath :: Java VirtualFile JString
| null | https://raw.githubusercontent.com/typelead/intellij-eta/ee66d621aa0bfdf56d7d287279a9a54e89802cf9/plugin/src/main/eta/FFI/Com/IntelliJ/OpenApi/Vfs/VirtualFile.hs | haskell | # CLASS "com.intellij.openapi.vfs.VirtualFile" # | module FFI.Com.IntelliJ.OpenApi.Vfs.VirtualFile where
import P.Base
VirtualFile = VirtualFile (Object# VirtualFile)
deriving Class
foreign import java unsafe "getPath" getPath :: Java VirtualFile JString
|
f98e8db12847fac7a48e0f9bb01d354eb2de70c2a7965770bbde689b378dd4ad | dgtized/lein-vanity | project.clj | (defproject lein-vanity "0.3.0-SNAPSHOT"
:description "Vanity clojure LOC metrics plugin for leiningen"
:url "-vanity"
:license {:name "MIT"
:url "-vanity/master/LICENSE"}
:dependencies [[org.clojure/clojure "1.5.1"]]
:min-lein-version "2.0.0"
:eval-in-leiningen true)
| null | https://raw.githubusercontent.com/dgtized/lein-vanity/c9a87b78571b3e7dc79baf64c6606286a2e18cae/project.clj | clojure | (defproject lein-vanity "0.3.0-SNAPSHOT"
:description "Vanity clojure LOC metrics plugin for leiningen"
:url "-vanity"
:license {:name "MIT"
:url "-vanity/master/LICENSE"}
:dependencies [[org.clojure/clojure "1.5.1"]]
:min-lein-version "2.0.0"
:eval-in-leiningen true)
| |
2e07cf3b9d7ab98ab97142710436f5f3979cabfc6670654c2784f8020dffe137 | turlando/airhead | utils_test.clj | (ns airhead.utils-test
(:require [clojure.test :refer :all]
[airhead.utils :as sut]))
(deftest test-seek
;; Taken from -2056
;; always nil for nil or empty coll/seq
(are [x] (= (sut/seek pos? x) nil)
nil
() [] {} #{}
(lazy-seq [])
(into-array []))
(are [x y] (= x y)
nil (sut/seek nil nil)
1 (sut/seek pos? [1])
1 (sut/seek pos? [1 2])
nil (sut/seek pos? [-1])
nil (sut/seek pos? [-1 -2])
2 (sut/seek pos? [-1 2])
1 (sut/seek pos? [1 -2])
;; does not consume whole sequence
10 (sut/seek #(>= % 10) (range))
:a (sut/seek #{:a} '(:a :b))
:a (sut/seek #{:a} #{:a :b})
;; can find false
false (sut/seek false? [false])
false (sut/seek false? [true false])
false (sut/seek false? [true false true])
nil (sut/seek false? [true true])
;; not-found value
::nf (sut/seek false? [true] ::nf)
::nf (sut/seek pos? [] ::nf)
::nf (sut/seek nil nil ::nf)))
| null | https://raw.githubusercontent.com/turlando/airhead/f38d8b3177d90462ad377c207a84966388cb326e/backend/test/airhead/utils_test.clj | clojure | Taken from -2056
always nil for nil or empty coll/seq
does not consume whole sequence
can find false
not-found value | (ns airhead.utils-test
(:require [clojure.test :refer :all]
[airhead.utils :as sut]))
(deftest test-seek
(are [x] (= (sut/seek pos? x) nil)
nil
() [] {} #{}
(lazy-seq [])
(into-array []))
(are [x y] (= x y)
nil (sut/seek nil nil)
1 (sut/seek pos? [1])
1 (sut/seek pos? [1 2])
nil (sut/seek pos? [-1])
nil (sut/seek pos? [-1 -2])
2 (sut/seek pos? [-1 2])
1 (sut/seek pos? [1 -2])
10 (sut/seek #(>= % 10) (range))
:a (sut/seek #{:a} '(:a :b))
:a (sut/seek #{:a} #{:a :b})
false (sut/seek false? [false])
false (sut/seek false? [true false])
false (sut/seek false? [true false true])
nil (sut/seek false? [true true])
::nf (sut/seek false? [true] ::nf)
::nf (sut/seek pos? [] ::nf)
::nf (sut/seek nil nil ::nf)))
|
9c241699a5a65fa3d9e914f8367ba8ed3c8b43986c557d5a38043edc107fe7a2 | jpmonettas/clindex | some_specs.cljc | (ns some-specs
(:require [clojure.spec.alpha :as s]
[dep-code :as dc]))
(s/def :person/name string?)
(s/fdef dc/function-with-doc
:args (s/cat :args (s/coll-of :person/name))
:ret boolean?)
| null | https://raw.githubusercontent.com/jpmonettas/clindex/77097d80a23aa85d2ff50e55645a1452f2dcb3c0/test-resources/test-project/src/some_specs.cljc | clojure | (ns some-specs
(:require [clojure.spec.alpha :as s]
[dep-code :as dc]))
(s/def :person/name string?)
(s/fdef dc/function-with-doc
:args (s/cat :args (s/coll-of :person/name))
:ret boolean?)
| |
ed907cda307e9e501d088967b08cc6461aef34eae95b4ebf577c66e527e29af3 | clojure/tools.analyzer.jvm | fix_case_test.clj | Copyright ( c ) , Rich Hickey & contributors .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns clojure.tools.analyzer.passes.jvm.fix-case-test
(:require [clojure.tools.analyzer.passes.add-binding-atom :refer [add-binding-atom]]))
(defn fix-case-test
"If the node is a :case-test, annotates in the atom shared
by the binding and the local node with :case-test"
{:pass-info {:walk :pre :depends #{#'add-binding-atom}}}
[ast]
(when (:case-test ast)
(swap! (:atom ast) assoc :case-test true))
ast)
| null | https://raw.githubusercontent.com/clojure/tools.analyzer.jvm/f00d92317307c3e9e326fd99d337292925dc9db1/src/main/clojure/clojure/tools/analyzer/passes/jvm/fix_case_test.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) , Rich Hickey & contributors .
(ns clojure.tools.analyzer.passes.jvm.fix-case-test
(:require [clojure.tools.analyzer.passes.add-binding-atom :refer [add-binding-atom]]))
(defn fix-case-test
"If the node is a :case-test, annotates in the atom shared
by the binding and the local node with :case-test"
{:pass-info {:walk :pre :depends #{#'add-binding-atom}}}
[ast]
(when (:case-test ast)
(swap! (:atom ast) assoc :case-test true))
ast)
|
883ccb48f7d2b45d5d56beb6ba5fe34e3d1bd2f5cb0ce6270e89838ce162a299 | overtone/overtone | linter.clj | (ns overtone.linter
"Helpers for linting overtone vars correctly (using clj-kondo)."
(:require
[clojure.string :as str]
[clojure.java.io :as io]
[clojure.pprint :as pp]
[overtone.api]))
(defn find-vars
"Find vars in your project according to one or more of the following queries:
- `:namespaces` (collection of namespaces in symbol or string format)
- `:ns-meta` (namespaces which contain this metadata)
- `:ns-prefix` (namespaces with this prefix)
- `:vars` (collection of vars in symbol or string format)
- `:var-meta` (vars which contain this metadata)"
[{:keys [namespaces ns-meta ns-prefix vars var-meta]}]
(when (or (seq namespaces) ns-meta (seq ns-prefix) (seq vars) var-meta)
(let [namespaces-set (set (mapv str namespaces))
vars-set (set (mapv (comp str symbol) vars))]
(cond->> (all-ns)
(seq ns-prefix) (filter #(str/starts-with? % ns-prefix))
(seq namespaces) (filter #(contains? namespaces-set (str %)))
ns-meta (filter #(-> % meta ns-meta))
true (mapv ns-interns)
true (mapcat vals)
(seq vars) (filter #(contains? vars-set (str (symbol %))))
var-meta (filter #(-> % meta var-meta))
true (sort-by symbol)))))
(defn- linter-hooks
"Generate hook ns from vars.
All the arguments and returns are of "
[vars]
['(ns overtone.overtone.clj-kondo-hooks
(:require [clj-kondo.hooks-api :as api]))
'(def overloaded-ugens
'[= < <= * min not= > mod - or / >= + max and])
'(defn defsynth [{:keys [node]}]
(let [var-sym (second (:children node))
binding-vec-or-docstring+body (drop 2 (:children node))
[_docstring binding-vec body] (if (api/vector-node? (first binding-vec-or-docstring+body))
[nil
(first binding-vec-or-docstring+body)
(vec (rest binding-vec-or-docstring+body))]
[(first binding-vec-or-docstring+body)
(second binding-vec-or-docstring+body)
(vec (drop 2 binding-vec-or-docstring+body))])
new-node (api/list-node
(list
(api/token-node 'defn)
var-sym
(api/coerce '[& _])
(api/list-node
(list*
(api/token-node 'let)
(api/coerce (vec (concat (mapcat (fn [v]
[v (constantly nil)])
;; See `with-overloaded-ugens`.
overloaded-ugens)
(:children binding-vec))))
;; "Use" the overloaded ugens so we don't have unused bindings
;; warnings.
(api/coerce overloaded-ugens)
body))))]
{:node new-node}))
'(defn demo [{:keys [node]}]
(let [body (rest (:children node))
new-node (api/list-node
(list*
(api/token-node 'let)
(api/coerce (vec (mapcat (fn [v]
[v (constantly nil)])
;; See `with-overloaded-ugens`.
overloaded-ugens)))
;; "Use" the overloaded ugens so we don't have unused bindings
;; warnings.
(api/coerce overloaded-ugens)
body))]
{:node new-node}))
'(defn defunk [{:keys [node]}]
(let [[var-sym _docstring binding-vec & body] (rest (:children node))
new-node (api/list-node
(list
(api/token-node 'defn)
var-sym
(api/coerce '[& _])
(api/list-node
(list*
(api/token-node 'let)
binding-vec
body))))]
{:node new-node}))
'(defn defunk-env [{:keys [node]}]
(let [[var-sym docstring binding-vec & body] (rest (:children node))
new-node (api/list-node
(list
(api/token-node 'do)
(api/list-node
(list*
(api/token-node 'overtone.helpers.lib/defunk)
var-sym
docstring
binding-vec
body))
(api/list-node
(list*
(api/token-node 'overtone.helpers.lib/defunk)
(api/token-node (symbol (str "env-" (:string-value var-sym))))
docstring
binding-vec
body))))]
{:node new-node}))
'(defn defcgen [{:keys [node]}]
(let [var-sym (second (:children node))
[_docstring binding-vec & body] (drop 2 (:children node))
rates (api/sexpr (->> body
(filter #(and (= (api/tag %) :list)
(contains? #{:ar :ir :kr :dr}
(:k (first (:children %))))))
(mapv #(:k (first (:children %))))
set))
new-node (api/list-node
(list*
(api/token-node 'do)
Create one defn for each defined rate + default .
(->> (conj rates nil)
(mapv (fn [rate]
(api/list-node
(list
(api/token-node 'defn)
(api/token-node (symbol (str (:string-value var-sym)
(when rate
(str ":" (name rate))))))
(api/coerce '[& _])
(api/list-node
(list*
(api/token-node 'let)
(api/coerce (api/vector-node
(->> (vec (concat overloaded-ugens (:children binding-vec)))
api/coerce
:children
(filter #(= (api/tag %) :token))
(mapcat (fn [token]
[token
(api/list-node
(list
(api/token-node 'eval)
(api/token-node nil)))]))
vec)))
;; "Use" the overloaded ugens so we don't have unused bindings
;; warnings.
(api/coerce overloaded-ugens)
body)))))))))]
{:node new-node}))
'(comment
(-> {:node (api/parse-string
(str '(defcgen varlag
"Variable shaped lag"
[in {:default 0 :doc "Input to lag"}
time {:default 0.1 :doc "Lag time in seconds"}
curvature {:default 0 :doc "Control curvature if shape input is 5 (default). 0 means linear, positive and negative numbers curve the segment up and down."}
shape {:default 5 :doc "Shape of curve. 0: step, 1: linear, 2: exponential, 3: sine, 4: welch, 5: custom (use curvature param), 6: squared, 7: cubed, 8: hold"}
]
"Similar to Lag but with other curve shapes than exponential. A change on the input will take the specified time to reach the new value. Useful for smoothing out control signals."
(:kr
(let [gate (+ (+ (impulse:kr 0 0) (> (abs (hpz1 in)) 0))
(> (abs (hpz1 time)) 0))]
(env-gen [in 1 -99 -99 in time shape curvature] gate))))))}
defcgen
:node
api/sexpr)
())
'(defn defrecord-ifn [{:keys [node]}]
(let [var-sym (second (:children node))
[fields invoke-fn & body] (drop 2 (:children node))
new-node (api/list-node
(list*
(api/token-node 'defrecord)
var-sym
fields
(list*
(api/token-node 'Object)
invoke-fn
body)))]
{:node new-node}))
'(defn defsynth-load [{:keys [node]}]
(let [var-sym (second (:children node))
string (first (drop 2 (:children node)))
new-node (api/list-node
(list
(api/token-node 'defn)
var-sym
(api/coerce '[& _])
string))]
{:node new-node}))
'(defn gen-stringed-synth [{:keys [node]}]
(let [var-sym (second (:children node))
binding-vec-or-docstring+body (drop 2 (:children node))
new-node (api/list-node
(list
(api/token-node 'defn)
var-sym
(api/coerce '[& _])
(api/list-node
(list
(api/token-node 'eval)
(api/token-node nil)))))]
{:node new-node}))
'(defn defcheck [{:keys [node]}]
(let [[var-sym params default-message & body] (rest (:children node))
body-node (api/list-node
(list*
(api/token-node 'let)
(api/coerce (vec
(mapcat (fn [v] [v (constantly nil)])
'[rate num-outs inputs ugen spec])))
;; "Use" the overloaded ugens so we don't have unused bindings
;; warnings.
(api/coerce '[rate num-outs inputs ugen spec])
default-message
body))
new-node (api/list-node
(list
(api/token-node 'defn)
var-sym
(api/list-node
(list
params
body-node))
(api/list-node
(list
(api/coerce (vec (conj (:children params) 'message)))
(api/token-node 'message)
body-node))))]
{:node new-node}))
'(defn defspec [{:keys [node]}]
(let [[var-sym & body] (rest (:children node))
new-node (api/list-node
(list
(api/token-node 'def)
var-sym
(api/vector-node body)))]
{:node new-node}))
'(defn defexamples [{:keys [node]}]
(let [[var-sym & body] (rest (:children node))
new-node (api/list-node
(list*
(api/token-node 'def)
var-sym
(map (fn [{:keys [children]}]
(let [[name _summary _long-doc _rate-sym _rate _params _body-str _contributor-sym _contributor]
children]
name))
body)))]
{:node new-node}))
'(comment
(-> {:node (api/parse-string
"(defexamples send-reply
(:count
\"Short\"
\"Full\"
rate :kr
[rate {:default 3 :doc \"Rate of count in times per second. Increase to up the count rate\"}]
\"
(let [tr (impulse rate)
step (stepper tr 0 0 12)]
(send-reply tr \\\"/count\\\" [step] 42))\"
contributor \"Sam Aaron\"))")}
defexamples
:node
str)
())
'(defn defclib [{:keys [node]}]
(let [[var-sym & body] (rest (:children node))
new-node (api/list-node
(list
(api/token-node 'def)
var-sym
(api/list-node
(list
'quote
body))))]
{:node new-node}))
'(comment
(str
(:node
(defsynth
{:node
(api/parse-string "
(defsynth ppp2
[bus 0
eita 3
amp 1]
(out bus (* amp (mda-piano :freq (midicps 50)
#_ #_ #_ #_:release 0.5
:decay 0))))")})))
())
(list 'def 'vars (list 'quote
(->> vars
(mapv (fn [v]
(let [var-meta (meta v)
var-value (deref v)]
[(symbol v)
(merge (select-keys var-meta [:arglists])
(when (:macro var-meta) {:macro (:macro var-meta)})
Arglists for synths , insts , ugens and similars
do not follow Clojure conventions , so for these
;; we define a variable arity.
(when (or (:arglists-modified? var-meta)
(contains? #{:overtone.sc.machinery.ugen.fn-gen/ugen
:overtone.sc.defcgen/cgen}
(:type var-value))
(contains? #{:overtone.helpers.lib/unk}
(:type var-meta))
(instance? overtone.sc.synth.Synth var-value)
(instance? overtone.studio.inst.Inst var-value))
{:arglists '([& _])
:special? true}))])))
(into {}))))
'(defn intern-vars [vars]
(let [new-node (api/list-node
(list*
(api/token-node 'do)
(->> (keys vars)
(group-by namespace)
(mapv (fn [[namespace' var-syms]]
(api/list-node
(list*
(api/token-node 'do)
;; Require namespace.
(api/list-node
(list
(api/token-node 'require)
(api/list-node
(list
(api/token-node 'quote)
(symbol namespace')))))
;; Define all the vars from a namespace for the current
;; namespace.
(->> var-syms
(mapv (fn [var-sym]
;; Consider macros as `def`s as they have to be
;; handled case by case.
(if (and (not (:macro (get vars var-sym)))
(seq (:arglists (get vars var-sym))))
defn
(api/list-node
(if (> (count (:arglists (get vars var-sym)))
1)
(list*
(api/token-node 'defn)
(api/token-node (symbol (name var-sym)))
(->> (:arglists (get vars var-sym))
(mapv (fn [arity]
(api/list-node
(list
(api/coerce
(if (some #{'&} arity)
['& '_]
(vec (repeat (count arity) '_))))))))))
(list
(api/token-node 'defn)
(api/token-node (symbol (name var-sym)))
(->> (:arglists (get vars var-sym))
(mapv (fn [arity]
(api/coerce
(if (some #{'&} arity)
['& '_]
(vec (repeat (count arity) '_))))))
first)
;; Use `eval` so we don't have clj-kondo
;; trying to infer the return of the
;; functions.
(api/list-node
(list
(api/token-node 'eval)
(api/token-node nil))))))
;; def
(api/list-node
(list
(api/token-node 'def)
(api/token-node (symbol (name var-sym))))))))))))))))]
{:node new-node}))
'(defn immigrate-overtone-api [_]
(intern-vars vars))
'(defn intern-ugens [_]
(intern-vars (->> vars
(filter (comp #{"overtone.sc.ugens"} namespace first))
(into {}))))
'(comment
(->> (-> (str (:node (immigrate-overtone-api nil)))
(clojure.string/split #"require"))
(remove empty?)
(mapv #(clojure.string/replace % #"\(do" ""))
(mapv clojure.string/trim)
(remove empty?)
(mapv #(->> (clojure.string/split % #"defn")
(mapv clojure.string/trim))))
())])
(defn emit!
"Generate clj-kondo files.
The generated files should NOT be version-controlled as they are generated
dynamically and may be huge."
[]
(let [hooks (linter-hooks
(->> (find-vars {:namespaces overtone.api/immigrated-namespaces})
(remove (comp :private meta))
#_(take 10)))
config '{:lint-as
{overtone.music.pitch/defratio
clojure.core/def}
:hooks
{:analyze-call
{overtone.api/immigrate-overtone-api
overtone.overtone.clj-kondo-hooks/immigrate-overtone-api
overtone.sc.synth/demo
overtone.overtone.clj-kondo-hooks/demo
overtone.core/demo
overtone.overtone.clj-kondo-hooks/demo
overtone.live/demo
overtone.overtone.clj-kondo-hooks/demo
overtone.core/defsynth
overtone.overtone.clj-kondo-hooks/defsynth
overtone.live/defsynth
overtone.overtone.clj-kondo-hooks/defsynth
overtone.sc.synth/defsynth
overtone.overtone.clj-kondo-hooks/defsynth
overtone.core/definst
overtone.overtone.clj-kondo-hooks/defsynth
overtone.live/definst
overtone.overtone.clj-kondo-hooks/defsynth
overtone.studio.inst/definst
overtone.overtone.clj-kondo-hooks/defsynth
overtone.core/defsynth-load
overtone.overtone.clj-kondo-hooks/defsynth-load
overtone.live/defsynth-load
overtone.overtone.clj-kondo-hooks/defsynth-load
overtone.sc.synth/defsynth-load
overtone.overtone.clj-kondo-hooks/defsynth-load
overtone.sc.machinery.ugen.fn-gen/intern-ugens
overtone.overtone.clj-kondo-hooks/intern-ugens
overtone.synth.stringed/gen-stringed-synth
overtone.overtone.clj-kondo-hooks/gen-stringed-synth
overtone.sc.defcgen/defcgen
overtone.overtone.clj-kondo-hooks/defcgen
overtone.core/defcgen
overtone.overtone.clj-kondo-hooks/defcgen
overtone.live/defcgen
overtone.overtone.clj-kondo-hooks/defcgen
overtone.helpers.lib/defrecord-ifn
overtone.overtone.clj-kondo-hooks/defrecord-ifn
overtone.sc.machinery.ugen.check/defcheck
overtone.overtone.clj-kondo-hooks/defcheck
overtone.byte-spec/defspec
overtone.overtone.clj-kondo-hooks/defspec
clj-native.direct/defclib
overtone.overtone.clj-kondo-hooks/defclib
overtone.sc.machinery.defexample/defexamples
overtone.overtone.clj-kondo-hooks/defexamples
overtone.helpers.lib/defunk
overtone.overtone.clj-kondo-hooks/defunk
overtone.sc.envelope/defunk-env
overtone.overtone.clj-kondo-hooks/defunk-env}}
:config-in-ns
{overtone.studio.util
{:linters {:inline-def {:level :off}}}
overtone.studio.mixer
{:linters {:inline-def {:level :off}}}
overtone.sc.ugens
{:linters {:inline-def {:level :off}}}
overtone.sc.machinery.server.native
{:linters {:unresolved-symbol {:exclude [world-run
world-new
world-cleanup
world-open-tcp-port
world-open-udp-port
world-send-packet
world-copy-sound-buffer]}}}}}
cfg-file (io/file ".clj-kondo" "overtone" "do_not_commit_me" "config.edn")
hooks-file (io/file ".clj-kondo" "overtone" "do_not_commit_me" "overtone" "overtone" "clj_kondo_hooks.clj")]
(io/make-parents cfg-file)
(io/make-parents hooks-file)
(spit cfg-file (with-out-str (pp/pprint config)))
(spit hooks-file (->> hooks
(mapv #(with-out-str (pp/pprint %)))
(str/join "\n")))
(str cfg-file)))
#_(emit!)
| null | https://raw.githubusercontent.com/overtone/overtone/9afb513297662716860a4010bc76a0e73c65ca37/src/overtone/linter.clj | clojure | See `with-overloaded-ugens`.
"Use" the overloaded ugens so we don't have unused bindings
warnings.
See `with-overloaded-ugens`.
"Use" the overloaded ugens so we don't have unused bindings
warnings.
"Use" the overloaded ugens so we don't have unused bindings
warnings.
"Use" the overloaded ugens so we don't have unused bindings
warnings.
we define a variable arity.
Require namespace.
Define all the vars from a namespace for the current
namespace.
Consider macros as `def`s as they have to be
handled case by case.
Use `eval` so we don't have clj-kondo
trying to infer the return of the
functions.
def | (ns overtone.linter
"Helpers for linting overtone vars correctly (using clj-kondo)."
(:require
[clojure.string :as str]
[clojure.java.io :as io]
[clojure.pprint :as pp]
[overtone.api]))
(defn find-vars
"Find vars in your project according to one or more of the following queries:
- `:namespaces` (collection of namespaces in symbol or string format)
- `:ns-meta` (namespaces which contain this metadata)
- `:ns-prefix` (namespaces with this prefix)
- `:vars` (collection of vars in symbol or string format)
- `:var-meta` (vars which contain this metadata)"
[{:keys [namespaces ns-meta ns-prefix vars var-meta]}]
(when (or (seq namespaces) ns-meta (seq ns-prefix) (seq vars) var-meta)
(let [namespaces-set (set (mapv str namespaces))
vars-set (set (mapv (comp str symbol) vars))]
(cond->> (all-ns)
(seq ns-prefix) (filter #(str/starts-with? % ns-prefix))
(seq namespaces) (filter #(contains? namespaces-set (str %)))
ns-meta (filter #(-> % meta ns-meta))
true (mapv ns-interns)
true (mapcat vals)
(seq vars) (filter #(contains? vars-set (str (symbol %))))
var-meta (filter #(-> % meta var-meta))
true (sort-by symbol)))))
(defn- linter-hooks
"Generate hook ns from vars.
All the arguments and returns are of "
[vars]
['(ns overtone.overtone.clj-kondo-hooks
(:require [clj-kondo.hooks-api :as api]))
'(def overloaded-ugens
'[= < <= * min not= > mod - or / >= + max and])
'(defn defsynth [{:keys [node]}]
(let [var-sym (second (:children node))
binding-vec-or-docstring+body (drop 2 (:children node))
[_docstring binding-vec body] (if (api/vector-node? (first binding-vec-or-docstring+body))
[nil
(first binding-vec-or-docstring+body)
(vec (rest binding-vec-or-docstring+body))]
[(first binding-vec-or-docstring+body)
(second binding-vec-or-docstring+body)
(vec (drop 2 binding-vec-or-docstring+body))])
new-node (api/list-node
(list
(api/token-node 'defn)
var-sym
(api/coerce '[& _])
(api/list-node
(list*
(api/token-node 'let)
(api/coerce (vec (concat (mapcat (fn [v]
[v (constantly nil)])
overloaded-ugens)
(:children binding-vec))))
(api/coerce overloaded-ugens)
body))))]
{:node new-node}))
'(defn demo [{:keys [node]}]
(let [body (rest (:children node))
new-node (api/list-node
(list*
(api/token-node 'let)
(api/coerce (vec (mapcat (fn [v]
[v (constantly nil)])
overloaded-ugens)))
(api/coerce overloaded-ugens)
body))]
{:node new-node}))
'(defn defunk [{:keys [node]}]
(let [[var-sym _docstring binding-vec & body] (rest (:children node))
new-node (api/list-node
(list
(api/token-node 'defn)
var-sym
(api/coerce '[& _])
(api/list-node
(list*
(api/token-node 'let)
binding-vec
body))))]
{:node new-node}))
'(defn defunk-env [{:keys [node]}]
(let [[var-sym docstring binding-vec & body] (rest (:children node))
new-node (api/list-node
(list
(api/token-node 'do)
(api/list-node
(list*
(api/token-node 'overtone.helpers.lib/defunk)
var-sym
docstring
binding-vec
body))
(api/list-node
(list*
(api/token-node 'overtone.helpers.lib/defunk)
(api/token-node (symbol (str "env-" (:string-value var-sym))))
docstring
binding-vec
body))))]
{:node new-node}))
'(defn defcgen [{:keys [node]}]
(let [var-sym (second (:children node))
[_docstring binding-vec & body] (drop 2 (:children node))
rates (api/sexpr (->> body
(filter #(and (= (api/tag %) :list)
(contains? #{:ar :ir :kr :dr}
(:k (first (:children %))))))
(mapv #(:k (first (:children %))))
set))
new-node (api/list-node
(list*
(api/token-node 'do)
Create one defn for each defined rate + default .
(->> (conj rates nil)
(mapv (fn [rate]
(api/list-node
(list
(api/token-node 'defn)
(api/token-node (symbol (str (:string-value var-sym)
(when rate
(str ":" (name rate))))))
(api/coerce '[& _])
(api/list-node
(list*
(api/token-node 'let)
(api/coerce (api/vector-node
(->> (vec (concat overloaded-ugens (:children binding-vec)))
api/coerce
:children
(filter #(= (api/tag %) :token))
(mapcat (fn [token]
[token
(api/list-node
(list
(api/token-node 'eval)
(api/token-node nil)))]))
vec)))
(api/coerce overloaded-ugens)
body)))))))))]
{:node new-node}))
'(comment
(-> {:node (api/parse-string
(str '(defcgen varlag
"Variable shaped lag"
[in {:default 0 :doc "Input to lag"}
time {:default 0.1 :doc "Lag time in seconds"}
curvature {:default 0 :doc "Control curvature if shape input is 5 (default). 0 means linear, positive and negative numbers curve the segment up and down."}
shape {:default 5 :doc "Shape of curve. 0: step, 1: linear, 2: exponential, 3: sine, 4: welch, 5: custom (use curvature param), 6: squared, 7: cubed, 8: hold"}
]
"Similar to Lag but with other curve shapes than exponential. A change on the input will take the specified time to reach the new value. Useful for smoothing out control signals."
(:kr
(let [gate (+ (+ (impulse:kr 0 0) (> (abs (hpz1 in)) 0))
(> (abs (hpz1 time)) 0))]
(env-gen [in 1 -99 -99 in time shape curvature] gate))))))}
defcgen
:node
api/sexpr)
())
'(defn defrecord-ifn [{:keys [node]}]
(let [var-sym (second (:children node))
[fields invoke-fn & body] (drop 2 (:children node))
new-node (api/list-node
(list*
(api/token-node 'defrecord)
var-sym
fields
(list*
(api/token-node 'Object)
invoke-fn
body)))]
{:node new-node}))
'(defn defsynth-load [{:keys [node]}]
(let [var-sym (second (:children node))
string (first (drop 2 (:children node)))
new-node (api/list-node
(list
(api/token-node 'defn)
var-sym
(api/coerce '[& _])
string))]
{:node new-node}))
'(defn gen-stringed-synth [{:keys [node]}]
(let [var-sym (second (:children node))
binding-vec-or-docstring+body (drop 2 (:children node))
new-node (api/list-node
(list
(api/token-node 'defn)
var-sym
(api/coerce '[& _])
(api/list-node
(list
(api/token-node 'eval)
(api/token-node nil)))))]
{:node new-node}))
'(defn defcheck [{:keys [node]}]
(let [[var-sym params default-message & body] (rest (:children node))
body-node (api/list-node
(list*
(api/token-node 'let)
(api/coerce (vec
(mapcat (fn [v] [v (constantly nil)])
'[rate num-outs inputs ugen spec])))
(api/coerce '[rate num-outs inputs ugen spec])
default-message
body))
new-node (api/list-node
(list
(api/token-node 'defn)
var-sym
(api/list-node
(list
params
body-node))
(api/list-node
(list
(api/coerce (vec (conj (:children params) 'message)))
(api/token-node 'message)
body-node))))]
{:node new-node}))
'(defn defspec [{:keys [node]}]
(let [[var-sym & body] (rest (:children node))
new-node (api/list-node
(list
(api/token-node 'def)
var-sym
(api/vector-node body)))]
{:node new-node}))
'(defn defexamples [{:keys [node]}]
(let [[var-sym & body] (rest (:children node))
new-node (api/list-node
(list*
(api/token-node 'def)
var-sym
(map (fn [{:keys [children]}]
(let [[name _summary _long-doc _rate-sym _rate _params _body-str _contributor-sym _contributor]
children]
name))
body)))]
{:node new-node}))
'(comment
(-> {:node (api/parse-string
"(defexamples send-reply
(:count
\"Short\"
\"Full\"
rate :kr
[rate {:default 3 :doc \"Rate of count in times per second. Increase to up the count rate\"}]
\"
(let [tr (impulse rate)
step (stepper tr 0 0 12)]
(send-reply tr \\\"/count\\\" [step] 42))\"
contributor \"Sam Aaron\"))")}
defexamples
:node
str)
())
'(defn defclib [{:keys [node]}]
(let [[var-sym & body] (rest (:children node))
new-node (api/list-node
(list
(api/token-node 'def)
var-sym
(api/list-node
(list
'quote
body))))]
{:node new-node}))
'(comment
(str
(:node
(defsynth
{:node
(api/parse-string "
(defsynth ppp2
[bus 0
eita 3
amp 1]
(out bus (* amp (mda-piano :freq (midicps 50)
#_ #_ #_ #_:release 0.5
:decay 0))))")})))
())
(list 'def 'vars (list 'quote
(->> vars
(mapv (fn [v]
(let [var-meta (meta v)
var-value (deref v)]
[(symbol v)
(merge (select-keys var-meta [:arglists])
(when (:macro var-meta) {:macro (:macro var-meta)})
Arglists for synths , insts , ugens and similars
do not follow Clojure conventions , so for these
(when (or (:arglists-modified? var-meta)
(contains? #{:overtone.sc.machinery.ugen.fn-gen/ugen
:overtone.sc.defcgen/cgen}
(:type var-value))
(contains? #{:overtone.helpers.lib/unk}
(:type var-meta))
(instance? overtone.sc.synth.Synth var-value)
(instance? overtone.studio.inst.Inst var-value))
{:arglists '([& _])
:special? true}))])))
(into {}))))
'(defn intern-vars [vars]
(let [new-node (api/list-node
(list*
(api/token-node 'do)
(->> (keys vars)
(group-by namespace)
(mapv (fn [[namespace' var-syms]]
(api/list-node
(list*
(api/token-node 'do)
(api/list-node
(list
(api/token-node 'require)
(api/list-node
(list
(api/token-node 'quote)
(symbol namespace')))))
(->> var-syms
(mapv (fn [var-sym]
(if (and (not (:macro (get vars var-sym)))
(seq (:arglists (get vars var-sym))))
defn
(api/list-node
(if (> (count (:arglists (get vars var-sym)))
1)
(list*
(api/token-node 'defn)
(api/token-node (symbol (name var-sym)))
(->> (:arglists (get vars var-sym))
(mapv (fn [arity]
(api/list-node
(list
(api/coerce
(if (some #{'&} arity)
['& '_]
(vec (repeat (count arity) '_))))))))))
(list
(api/token-node 'defn)
(api/token-node (symbol (name var-sym)))
(->> (:arglists (get vars var-sym))
(mapv (fn [arity]
(api/coerce
(if (some #{'&} arity)
['& '_]
(vec (repeat (count arity) '_))))))
first)
(api/list-node
(list
(api/token-node 'eval)
(api/token-node nil))))))
(api/list-node
(list
(api/token-node 'def)
(api/token-node (symbol (name var-sym))))))))))))))))]
{:node new-node}))
'(defn immigrate-overtone-api [_]
(intern-vars vars))
'(defn intern-ugens [_]
(intern-vars (->> vars
(filter (comp #{"overtone.sc.ugens"} namespace first))
(into {}))))
'(comment
(->> (-> (str (:node (immigrate-overtone-api nil)))
(clojure.string/split #"require"))
(remove empty?)
(mapv #(clojure.string/replace % #"\(do" ""))
(mapv clojure.string/trim)
(remove empty?)
(mapv #(->> (clojure.string/split % #"defn")
(mapv clojure.string/trim))))
())])
(defn emit!
"Generate clj-kondo files.
The generated files should NOT be version-controlled as they are generated
dynamically and may be huge."
[]
(let [hooks (linter-hooks
(->> (find-vars {:namespaces overtone.api/immigrated-namespaces})
(remove (comp :private meta))
#_(take 10)))
config '{:lint-as
{overtone.music.pitch/defratio
clojure.core/def}
:hooks
{:analyze-call
{overtone.api/immigrate-overtone-api
overtone.overtone.clj-kondo-hooks/immigrate-overtone-api
overtone.sc.synth/demo
overtone.overtone.clj-kondo-hooks/demo
overtone.core/demo
overtone.overtone.clj-kondo-hooks/demo
overtone.live/demo
overtone.overtone.clj-kondo-hooks/demo
overtone.core/defsynth
overtone.overtone.clj-kondo-hooks/defsynth
overtone.live/defsynth
overtone.overtone.clj-kondo-hooks/defsynth
overtone.sc.synth/defsynth
overtone.overtone.clj-kondo-hooks/defsynth
overtone.core/definst
overtone.overtone.clj-kondo-hooks/defsynth
overtone.live/definst
overtone.overtone.clj-kondo-hooks/defsynth
overtone.studio.inst/definst
overtone.overtone.clj-kondo-hooks/defsynth
overtone.core/defsynth-load
overtone.overtone.clj-kondo-hooks/defsynth-load
overtone.live/defsynth-load
overtone.overtone.clj-kondo-hooks/defsynth-load
overtone.sc.synth/defsynth-load
overtone.overtone.clj-kondo-hooks/defsynth-load
overtone.sc.machinery.ugen.fn-gen/intern-ugens
overtone.overtone.clj-kondo-hooks/intern-ugens
overtone.synth.stringed/gen-stringed-synth
overtone.overtone.clj-kondo-hooks/gen-stringed-synth
overtone.sc.defcgen/defcgen
overtone.overtone.clj-kondo-hooks/defcgen
overtone.core/defcgen
overtone.overtone.clj-kondo-hooks/defcgen
overtone.live/defcgen
overtone.overtone.clj-kondo-hooks/defcgen
overtone.helpers.lib/defrecord-ifn
overtone.overtone.clj-kondo-hooks/defrecord-ifn
overtone.sc.machinery.ugen.check/defcheck
overtone.overtone.clj-kondo-hooks/defcheck
overtone.byte-spec/defspec
overtone.overtone.clj-kondo-hooks/defspec
clj-native.direct/defclib
overtone.overtone.clj-kondo-hooks/defclib
overtone.sc.machinery.defexample/defexamples
overtone.overtone.clj-kondo-hooks/defexamples
overtone.helpers.lib/defunk
overtone.overtone.clj-kondo-hooks/defunk
overtone.sc.envelope/defunk-env
overtone.overtone.clj-kondo-hooks/defunk-env}}
:config-in-ns
{overtone.studio.util
{:linters {:inline-def {:level :off}}}
overtone.studio.mixer
{:linters {:inline-def {:level :off}}}
overtone.sc.ugens
{:linters {:inline-def {:level :off}}}
overtone.sc.machinery.server.native
{:linters {:unresolved-symbol {:exclude [world-run
world-new
world-cleanup
world-open-tcp-port
world-open-udp-port
world-send-packet
world-copy-sound-buffer]}}}}}
cfg-file (io/file ".clj-kondo" "overtone" "do_not_commit_me" "config.edn")
hooks-file (io/file ".clj-kondo" "overtone" "do_not_commit_me" "overtone" "overtone" "clj_kondo_hooks.clj")]
(io/make-parents cfg-file)
(io/make-parents hooks-file)
(spit cfg-file (with-out-str (pp/pprint config)))
(spit hooks-file (->> hooks
(mapv #(with-out-str (pp/pprint %)))
(str/join "\n")))
(str cfg-file)))
#_(emit!)
|
0bf721c42c5d00af053eea4e657486c4ee794a11e77777a58647b1a84c80c7fd | nuvla/api-server | user_minimum_lifecycle_test.clj | (ns sixsq.nuvla.server.resources.user-minimum-lifecycle-test
(:require
[clojure.data.json :as json]
[clojure.test :refer [deftest is use-fixtures]]
[peridot.core :refer [content-type header request session]]
[ring.util.codec :as rc]
[sixsq.nuvla.server.app.params :as p]
[sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]]
[sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu]
[sixsq.nuvla.server.resources.user :as user]
[sixsq.nuvla.server.resources.user-identifier :as user-identifier]
[sixsq.nuvla.server.resources.user-template :as user-tpl]
[sixsq.nuvla.server.resources.user-template-minimum :as minimum]
[sixsq.nuvla.server.util.metadata-test-utils :as mdtu]))
(use-fixtures :once ltu/with-test-server-fixture)
(def base-uri (str p/service-context user/resource-type))
(deftest check-metadata
(mdtu/check-metadata-exists (str user-tpl/resource-type "-" minimum/resource-url)))
(deftest lifecycle
(let [template-href (str user-tpl/resource-type "/" minimum/registration-method)
template-url (str p/service-context template-href)
session (-> (ltu/ring-app)
session
(content-type "application/json"))
session-admin (header session authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
session-user (header session authn-info-header "user/jane user/jane group/nuvla-user group/nuvla-anon")
session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")
template (-> session-admin
(request template-url)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body))
description-attr "description"
tags-attr ["one", "two"]
no-href-create {:template (ltu/strip-unwanted-attrs template)}
href-create {:description description-attr
:tags tags-attr
:template {:href template-href
:username "user/jane"
:email ""
:password "Some-password-1?"}}
invalid-create (assoc-in href-create [:template :href] "user-template/unknown-template")
bad-params-create (assoc-in href-create [:template :invalid] "BAD")]
;; user collection query should succeed but be empty for all users
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)))
(-> session-admin
(content-type "application/x-www-form-urlencoded")
(request base-uri
:request-method :put
:body (rc/form-encode {:filter "name!='super'"}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?)
(ltu/is-operation-present :add)
(ltu/is-operation-absent :delete)
(ltu/is-operation-absent :edit))
;; create a new user; fails without reference
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str no-href-create))
(ltu/body->edn)
(ltu/is-status 400)))
;; create with invalid template fails
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str invalid-create))
(ltu/body->edn)
(ltu/is-status 404)))
;; create with bad parameters fails
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str bad-params-create))
(ltu/body->edn)
(ltu/is-status 400)))
;; user collection query should succeed but be empty for all users
(doseq [session [session-anon session-user session-admin]]
(-> session
(content-type "application/x-www-form-urlencoded")
(request base-uri
:request-method :put
:body (rc/form-encode {:filter "name!='super'"}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?)
(ltu/is-operation-present :add)
(ltu/is-operation-absent :delete)
(ltu/is-operation-absent :edit)))
;; create a new user; fails without reference
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str no-href-create))
(ltu/body->edn)
(ltu/is-status 400)))
;; create with invalid template fails
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str invalid-create))
(ltu/body->edn)
(ltu/is-status 404)))
;; create with bad parameters fails
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str bad-params-create))
(ltu/body->edn)
(ltu/is-status 400)))
;; create user, minimum template is only accessible by admin
(let [user-id (-> session-admin
(request base-uri
:request-method :post
:body (json/write-str href-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
username-id (get-in href-create [:template :username])
email (get-in href-create [:template :email])
session-created-user (header session authn-info-header (str user-id " " user-id " group/nuvla-user group/nuvla-anon"))
{user-acl :acl
email-id :email
password-id :credential-password
user-name :name :as _user} (-> session-created-user
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body))]
;; verify the ACL of the user
(is (some #{"group/nuvla-admin"} (:owners user-acl)))
;; user should have all rights
(doseq [right [:view-meta :view-data :view-acl
:edit-meta :edit-data :edit-acl
:manage :delete]]
(is (some #{user-id} (right user-acl))))
;; verify name attribute (should default to username)
(is (= "user/jane" user-name))
1 identifier for the username is visible for the created user ; find by identifier
(-> session-created-user
(content-type "application/x-www-form-urlencoded")
(request (str p/service-context user-identifier/resource-type)
:request-method :put
:body (rc/form-encode {:filter (format "identifier='%s'" username-id)}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 1))
;; email resource has been created and is visible for the user
(-> session-created-user
(request (str p/service-context email-id))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-key-value :validated true))
(-> session-created-user
(request (str p/service-context password-id))
(ltu/body->edn)
(ltu/is-status 200))
1 identifier for the email is visible for the created user ; find by identifier
(-> session-created-user
(content-type "application/x-www-form-urlencoded")
(request (str p/service-context user-identifier/resource-type)
:request-method :put
:body (rc/form-encode {:filter (format "identifier='%s'" email)}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 1))
;; find identifiers by parent
(-> session-created-user
(content-type "application/x-www-form-urlencoded")
(request (str p/service-context user-identifier/resource-type)
:request-method :put
:body (rc/form-encode {:filter (format "parent='%s'" user-id)}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 2))
(-> session-admin
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/is-status 200))
(let [{:keys [state] :as _user} (-> session-created-user
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/body))]
(is (= "ACTIVE" state)))
;; user can delete his account
(-> session-created-user
(request (str p/service-context user-id)
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 200))
;; all identifiers pointing to user are gone
(-> session-created-user
(content-type "application/x-www-form-urlencoded")
(request (str p/service-context user-identifier/resource-type)
:request-method :put
:body (rc/form-encode {:filter (format "parent='%s'" user-id)}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 0))
;; the email resource is gone also
(-> session-created-user
(content-type "application/x-www-form-urlencoded")
(request (str p/service-context email-id))
(ltu/body->edn)
(ltu/is-status 404))
;; the user resource is gone as well
(-> session-created-user
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/is-status 404)))))
| null | https://raw.githubusercontent.com/nuvla/api-server/d1291d0499cd33ce3b331db84ea00f6e01c1b1b5/code/test/sixsq/nuvla/server/resources/user_minimum_lifecycle_test.clj | clojure | user collection query should succeed but be empty for all users
create a new user; fails without reference
create with invalid template fails
create with bad parameters fails
user collection query should succeed but be empty for all users
create a new user; fails without reference
create with invalid template fails
create with bad parameters fails
create user, minimum template is only accessible by admin
verify the ACL of the user
user should have all rights
verify name attribute (should default to username)
find by identifier
email resource has been created and is visible for the user
find by identifier
find identifiers by parent
user can delete his account
all identifiers pointing to user are gone
the email resource is gone also
the user resource is gone as well | (ns sixsq.nuvla.server.resources.user-minimum-lifecycle-test
(:require
[clojure.data.json :as json]
[clojure.test :refer [deftest is use-fixtures]]
[peridot.core :refer [content-type header request session]]
[ring.util.codec :as rc]
[sixsq.nuvla.server.app.params :as p]
[sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]]
[sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu]
[sixsq.nuvla.server.resources.user :as user]
[sixsq.nuvla.server.resources.user-identifier :as user-identifier]
[sixsq.nuvla.server.resources.user-template :as user-tpl]
[sixsq.nuvla.server.resources.user-template-minimum :as minimum]
[sixsq.nuvla.server.util.metadata-test-utils :as mdtu]))
(use-fixtures :once ltu/with-test-server-fixture)
(def base-uri (str p/service-context user/resource-type))
(deftest check-metadata
(mdtu/check-metadata-exists (str user-tpl/resource-type "-" minimum/resource-url)))
(deftest lifecycle
(let [template-href (str user-tpl/resource-type "/" minimum/registration-method)
template-url (str p/service-context template-href)
session (-> (ltu/ring-app)
session
(content-type "application/json"))
session-admin (header session authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
session-user (header session authn-info-header "user/jane user/jane group/nuvla-user group/nuvla-anon")
session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")
template (-> session-admin
(request template-url)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body))
description-attr "description"
tags-attr ["one", "two"]
no-href-create {:template (ltu/strip-unwanted-attrs template)}
href-create {:description description-attr
:tags tags-attr
:template {:href template-href
:username "user/jane"
:email ""
:password "Some-password-1?"}}
invalid-create (assoc-in href-create [:template :href] "user-template/unknown-template")
bad-params-create (assoc-in href-create [:template :invalid] "BAD")]
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)))
(-> session-admin
(content-type "application/x-www-form-urlencoded")
(request base-uri
:request-method :put
:body (rc/form-encode {:filter "name!='super'"}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?)
(ltu/is-operation-present :add)
(ltu/is-operation-absent :delete)
(ltu/is-operation-absent :edit))
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str no-href-create))
(ltu/body->edn)
(ltu/is-status 400)))
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str invalid-create))
(ltu/body->edn)
(ltu/is-status 404)))
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str bad-params-create))
(ltu/body->edn)
(ltu/is-status 400)))
(doseq [session [session-anon session-user session-admin]]
(-> session
(content-type "application/x-www-form-urlencoded")
(request base-uri
:request-method :put
:body (rc/form-encode {:filter "name!='super'"}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?)
(ltu/is-operation-present :add)
(ltu/is-operation-absent :delete)
(ltu/is-operation-absent :edit)))
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str no-href-create))
(ltu/body->edn)
(ltu/is-status 400)))
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str invalid-create))
(ltu/body->edn)
(ltu/is-status 404)))
(doseq [session [session-anon session-user session-admin]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str bad-params-create))
(ltu/body->edn)
(ltu/is-status 400)))
(let [user-id (-> session-admin
(request base-uri
:request-method :post
:body (json/write-str href-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
username-id (get-in href-create [:template :username])
email (get-in href-create [:template :email])
session-created-user (header session authn-info-header (str user-id " " user-id " group/nuvla-user group/nuvla-anon"))
{user-acl :acl
email-id :email
password-id :credential-password
user-name :name :as _user} (-> session-created-user
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body))]
(is (some #{"group/nuvla-admin"} (:owners user-acl)))
(doseq [right [:view-meta :view-data :view-acl
:edit-meta :edit-data :edit-acl
:manage :delete]]
(is (some #{user-id} (right user-acl))))
(is (= "user/jane" user-name))
(-> session-created-user
(content-type "application/x-www-form-urlencoded")
(request (str p/service-context user-identifier/resource-type)
:request-method :put
:body (rc/form-encode {:filter (format "identifier='%s'" username-id)}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 1))
(-> session-created-user
(request (str p/service-context email-id))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-key-value :validated true))
(-> session-created-user
(request (str p/service-context password-id))
(ltu/body->edn)
(ltu/is-status 200))
(-> session-created-user
(content-type "application/x-www-form-urlencoded")
(request (str p/service-context user-identifier/resource-type)
:request-method :put
:body (rc/form-encode {:filter (format "identifier='%s'" email)}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 1))
(-> session-created-user
(content-type "application/x-www-form-urlencoded")
(request (str p/service-context user-identifier/resource-type)
:request-method :put
:body (rc/form-encode {:filter (format "parent='%s'" user-id)}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 2))
(-> session-admin
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/is-status 200))
(let [{:keys [state] :as _user} (-> session-created-user
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/body))]
(is (= "ACTIVE" state)))
(-> session-created-user
(request (str p/service-context user-id)
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 200))
(-> session-created-user
(content-type "application/x-www-form-urlencoded")
(request (str p/service-context user-identifier/resource-type)
:request-method :put
:body (rc/form-encode {:filter (format "parent='%s'" user-id)}))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 0))
(-> session-created-user
(content-type "application/x-www-form-urlencoded")
(request (str p/service-context email-id))
(ltu/body->edn)
(ltu/is-status 404))
(-> session-created-user
(request (str p/service-context user-id))
(ltu/body->edn)
(ltu/is-status 404)))))
|
78660a3545ead4973bc48783318f21eb2e8bd07f6a3cf1898936c062eeac67f6 | BioHaskell/hPDB | Internals.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE DisambiguateRecordFields #
# LANGUAGE FlexibleContexts #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-} -- for convenient debugging
# OPTIONS_GHC -fspec - constr - count=2 #
-- | This module allows access to internal interface of @StructureBuilder@ in case that user wants to extend it
-- by redefining parts.
module Bio.PDB.StructureBuilder.Internals
--(parse)
where
import Prelude hiding (String)
import qualified Data.ByteString.Char8 as BS hiding (reverse)
import qualified Control.Monad.ST as ST
import Control.Monad.State.Strict as State
import Control.Monad(when)
import Data.STRef as STRef
import Data.Maybe(isNothing, isJust)
import Bio.PDB.EventParser.PDBEvents(PDBEvent(..), RESID(..))
import qualified Bio.PDB.EventParser.PDBEventParser(parsePDBRecords)
import Bio.PDB.Structure
import Bio.PDB.Structure.List as L
| Shorthand for the State monad in which parsing is done .
-- `t` is existential 'phantom' type to keep ST effects from escaping
type ParsingMonad t a = State.StateT (BState t) (ST.ST t) a
-- TODO: with option of online reporting of errors?
-- parsePDBRec :: (Monad m) => String -> String -> (() -> PDBEvent -> m ()) -> () -> m ()
| Parses PDB records given as ByteString , given filename fileContents and a monadic
action to be executed for each PDB event .
parsePDBRec :: String -> String -> (() -> PDBEvent -> ParsingMonad t ()) -> () -> ParsingMonad t ()
parsePDBRec = Bio.PDB.EventParser.PDBEventParser.parsePDBRecords
| Given filename , and contents , parses a whole PDB file , returning a monadic action
-- | with a tuple of (Structure, [PDBEvent]), where the list of events contains all
-- | parsing or construction errors.
parseSerial :: FilePath -> String -> (Structure, List PDBEvent)
parseSerial fname contents = ST.runST $ do initial <- initializeState
(s, e) <- State.evalStateT parsing initial
return (s :: Structure, e :: L.List PDBEvent)
where parsing = do parsePDBRec (BS.pack fname) contents (\() !ev -> parseStep ev) ()
closeStructure
s <- State.gets currentStructure
e <- State.gets errors
e' <- L.finalize e
return (s, e')
-- | Record holding a current state of the structure record builder.
data BState s = BState { currentResidue :: Maybe Residue,
currentModel :: Maybe Model,
currentChain :: Maybe Chain,
currentStructure :: Structure,
residueContents :: L.TempList s Atom,
chainContents :: L.TempList s Residue,
modelContents :: L.TempList s Chain,
structureContents :: L.TempList s Model,
errors :: L.TempList s PDBEvent,
lineNo :: STRef.STRef s Int
}
-- | Initial state of the structure record builder.
initializeState :: ST.ST t (BState t)
initializeState = do r <- L.initialNew L.residueVectorSize
c <- L.initialNew L.chainVectorSize
m <- L.initialNew 1
s <- L.initialNew 1
e <- L.initialNew 100
l <- STRef.newSTRef 1
return BState { currentResidue = Nothing,
currentModel = Nothing,
currentChain = Nothing,
currentStructure = Structure { models = L.empty },
residueContents = r,
chainContents = c,
modelContents = m,
structureContents = s,
errors = e,
lineNo = l }
-- | Checks that a residue with a given identification tuple is current,
-- | or if not, then closes previous residue (if present),
-- | and marks a new ,,current'' residue in a state of builder.
checkResidue :: Bio.PDB.EventParser.PDBEvents.RESID -> ParsingMonad t ()
checkResidue (RESID (newName, newChain, newResseq, newInsCode)) =
do checkChain newChain
res <- State.gets currentResidue
when (residueChanged res) $ do closeResidue
l <- L.new L.residueVectorSize
State.modify $! createResidue l
where
residueChanged Nothing = True
residueChanged (Just (Residue { resName = oldResName,
resSeq = oldResSeq ,
insCode = oldInsCode,
atoms = _atoms })) =
(oldResName, oldResSeq, oldInsCode) /= (newName, newResseq, newInsCode)
createResidue l st = st { currentResidue = Just newResidue,
residueContents = l }
newResidue = Bio.PDB.Structure.Residue { resName = newName,
resSeq = newResseq,
insCode = newInsCode,
atoms = L.empty }
-- | Checks that a chain with a given identification character is current,
-- | and if not, creates one. Also checks that we have any model in which
-- | to assign the chain.
checkChain :: Char -> ParsingMonad t ()
checkChain name = do checkModel
curChain <- State.gets currentChain
when (chainChanged curChain) $ do closeChain
l <- L.new L.chainVectorSize
State.modify $ createChain l
where
chainChanged Nothing = True
chainChanged (Just (Chain { chainId = oldChain })) = oldChain /= name
createChain l state = state { currentChain = Just Chain { chainId = name,
residues = L.empty },
chainContents = l }
-- | Checks that a current model has been declared, and creates zeroth model,
-- | if no such model exists.
checkModel :: ParsingMonad t ()
checkModel = do curModel <- State.gets currentModel
when (isNothing curModel) $ openModel defaultModelId
--closeResidue :: State.State BState ()
-- TODO: when createing a dummy model, check that there are no models declared before
-- [Otherwise one needs to report an error!]
-- | Default model id, in case none was indicated (for comparison.)
defaultModelId = 1
| Closes construction of a current residue and appends this residue to a current chain . ( Monadic action . )
closeResidue :: ParsingMonad t ()
closeResidue = do r <- State.gets currentResidue
when (isJust r) $ do let Just res = r
rc <- State.gets residueContents
rf <- L.finalize rc
cc <- State.gets chainContents
cc' <- L.add cc $ res { Bio.PDB.Structure.atoms = rf }
State.modify clearResidue
where
clearResidue st = st { currentResidue = Nothing }
-- | Finalizes construction of current chain, and appends it to current model.
--closeChain :: State.State BState ()
closeChain :: ParsingMonad t ()
closeChain = do closeResidue
c <- State.gets currentChain
ac <- State.gets chainContents
when (isJust c) $ do l <- State.gets chainContents
l' <- L.finalize l
let Just ch = c
ch' = ch { Bio.PDB.Structure.residues = l' }
m <- State.gets currentModel
when (isNothing m) $ do mli <- State.gets structureContents
i <- L.tempLength mli
openModel i
addError ["Trying to close chain when currentChain is ",
BS.pack . show $ ch,
" and currentModel is ",
BS.pack . show $ m]
ml <- State.gets modelContents
ml' <- L.add ml ch'
State.modify clearChain
where
clearChain st = st { currentChain = Nothing }
| Reports error during building of structure for PDB entry .
-- TODO: This should be probably monadic action
-- TODO: forgot about line/column number passing!
addError :: [String] -> ParsingMonad t ()
addError msg = do e <- State.gets errors
lnref <- State.gets lineNo
ln <- lift $ STRef.readSTRef lnref
lift $ STRef.modifySTRef lnref (+1)
L.add e $ anError ln
where
anError ln = PDBParseError ln 0 $ BS.concat msg
-- | Finalizes construction of current model
closeModel :: ParsingMonad t ()
closeModel = do closeChain
cm <- State.gets currentModel
case cm of
Nothing -> return ()
Just m -> do mc <- State.gets modelContents
chs <- L.finalize mc
let m' = m { chains = chs }
sc <- State.gets structureContents
State.modify clearModel
L.add sc m'
where clearModel st = st { currentModel = Nothing }
| Finalizes construction of record holding PDB entry data .
-- NOTE: this one is different and should only be used after parsing is complete!
closeStructure :: ParsingMonad t ()
closeStructure = do closeModel
sc <- State.gets structureContents
sc' <- L.finalize sc
State.modify (closeStructure' sc')
where
closeStructure' sc bstate@(BState { currentStructure = aStructure}) =
bstate { currentStructure = aStructure { models = sc },
structureContents = undefined }
-- | Updates line counter.
nextLine :: ParsingMonad t ()
nextLine = do lnref <- State.gets lineNo
lift $ STRef.modifySTRef lnref (+1)
| Performs a match on a single PDBEvent and performs relevant change to a BState of structure builder .
parseStep : : ( State . MonadState m ) = > PDBEvent - > m ( )
parseStep pe@(PDBParseError l _ _) = do e <- State.gets errors
L.add e pe
lnref <- State.gets lineNo
lift $ STRef.writeSTRef lnref l
parseStep (ATOM { no = atSer, -- :: !Int,
atomtype = atType, -- :: !String,
restype = resName, -- :: !String,
: : ! ,
resid = resSeq, -- :: !Int,
: : ! ,
: : ! , - atom name
coords = atCoord, -- :: !Vector3,
occupancy = atOccupancy,-- :: !Double,
bfactor = atBFactor, -- :: !Double,
segid = atSegId, -- :: !String,
elt = atElement, -- :: !String,
charge = atCharge, -- :: !String, -- why not a number?
: : !
}) =
do checkResidue $ RESID (resName, chainName, resSeq, resInsCode)
reslist <- State.gets residueContents
newAtom `seq` L.add reslist newAtom
nextLine
where newAtom = Atom { atName = atType,
atSerial = atSer,
coord = atCoord,
bFactor = atBFactor,
occupancy = atOccupancy,
element = atElement,
segid = atSegId,
charge = atCharge,
hetatm = isHet
}
parseStep (MODEL { num = n }) = do closeModel
openModel n
nextLine
parseStep ENDMDL = do closeModel
nextLine
parseStep END = do closeModel
nextLine
TODO : check TER with currentChain parameters
nextLine
parseStep (MASTER {..}) = do closeModel -- TODO: check MASTER parameters with current model -- is it really model end?
nextLine
parseStep _ = nextLine
-- | Creates a new model within structure builder. (For internal use.)
-- WARNING: And forgets anything that was there before!
openModel :: Int -> ParsingMonad t ()
openModel n = do l <- L.new L.defaultSize
State.modify $ changeModel l
where changeModel l st = st { currentModel = Just newModel,
modelContents = l }
newModel = Bio.PDB.Structure.Model { modelId = n,
chains = empty }
-- | Finalizes state of structure builder, and returns pair of a structure, and list of errors.
-- NOTE: should have a monadic action for each error instead. Then possibly default monad that accumulates these errors.
parseFinish :: ParsingMonad t (Structure, L.List PDBEvent)
parseFinish = do closeStructure
st <- State.gets currentStructure
er <- State.gets errors
er' <- finalize er
st `seq` return (st, er')
| null | https://raw.githubusercontent.com/BioHaskell/hPDB/5be747e2f2c57370b498f4c11f9f1887fdab0418/Bio/PDB/StructureBuilder/Internals.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE NamedFieldPuns #
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
# LANGUAGE RecordWildCards #
for convenient debugging
| This module allows access to internal interface of @StructureBuilder@ in case that user wants to extend it
by redefining parts.
(parse)
`t` is existential 'phantom' type to keep ST effects from escaping
TODO: with option of online reporting of errors?
parsePDBRec :: (Monad m) => String -> String -> (() -> PDBEvent -> m ()) -> () -> m ()
| with a tuple of (Structure, [PDBEvent]), where the list of events contains all
| parsing or construction errors.
| Record holding a current state of the structure record builder.
| Initial state of the structure record builder.
| Checks that a residue with a given identification tuple is current,
| or if not, then closes previous residue (if present),
| and marks a new ,,current'' residue in a state of builder.
| Checks that a chain with a given identification character is current,
| and if not, creates one. Also checks that we have any model in which
| to assign the chain.
| Checks that a current model has been declared, and creates zeroth model,
| if no such model exists.
closeResidue :: State.State BState ()
TODO: when createing a dummy model, check that there are no models declared before
[Otherwise one needs to report an error!]
| Default model id, in case none was indicated (for comparison.)
| Finalizes construction of current chain, and appends it to current model.
closeChain :: State.State BState ()
TODO: This should be probably monadic action
TODO: forgot about line/column number passing!
| Finalizes construction of current model
NOTE: this one is different and should only be used after parsing is complete!
| Updates line counter.
:: !Int,
:: !String,
:: !String,
:: !Int,
:: !Vector3,
:: !Double,
:: !Double,
:: !String,
:: !String,
:: !String, -- why not a number?
TODO: check MASTER parameters with current model -- is it really model end?
| Creates a new model within structure builder. (For internal use.)
WARNING: And forgets anything that was there before!
| Finalizes state of structure builder, and returns pair of a structure, and list of errors.
NOTE: should have a monadic action for each error instead. Then possibly default monad that accumulates these errors. | # LANGUAGE DisambiguateRecordFields #
# LANGUAGE FlexibleContexts #
# LANGUAGE MultiParamTypeClasses #
# OPTIONS_GHC -fspec - constr - count=2 #
module Bio.PDB.StructureBuilder.Internals
where
import Prelude hiding (String)
import qualified Data.ByteString.Char8 as BS hiding (reverse)
import qualified Control.Monad.ST as ST
import Control.Monad.State.Strict as State
import Control.Monad(when)
import Data.STRef as STRef
import Data.Maybe(isNothing, isJust)
import Bio.PDB.EventParser.PDBEvents(PDBEvent(..), RESID(..))
import qualified Bio.PDB.EventParser.PDBEventParser(parsePDBRecords)
import Bio.PDB.Structure
import Bio.PDB.Structure.List as L
| Shorthand for the State monad in which parsing is done .
type ParsingMonad t a = State.StateT (BState t) (ST.ST t) a
| Parses PDB records given as ByteString , given filename fileContents and a monadic
action to be executed for each PDB event .
parsePDBRec :: String -> String -> (() -> PDBEvent -> ParsingMonad t ()) -> () -> ParsingMonad t ()
parsePDBRec = Bio.PDB.EventParser.PDBEventParser.parsePDBRecords
| Given filename , and contents , parses a whole PDB file , returning a monadic action
parseSerial :: FilePath -> String -> (Structure, List PDBEvent)
parseSerial fname contents = ST.runST $ do initial <- initializeState
(s, e) <- State.evalStateT parsing initial
return (s :: Structure, e :: L.List PDBEvent)
where parsing = do parsePDBRec (BS.pack fname) contents (\() !ev -> parseStep ev) ()
closeStructure
s <- State.gets currentStructure
e <- State.gets errors
e' <- L.finalize e
return (s, e')
data BState s = BState { currentResidue :: Maybe Residue,
currentModel :: Maybe Model,
currentChain :: Maybe Chain,
currentStructure :: Structure,
residueContents :: L.TempList s Atom,
chainContents :: L.TempList s Residue,
modelContents :: L.TempList s Chain,
structureContents :: L.TempList s Model,
errors :: L.TempList s PDBEvent,
lineNo :: STRef.STRef s Int
}
initializeState :: ST.ST t (BState t)
initializeState = do r <- L.initialNew L.residueVectorSize
c <- L.initialNew L.chainVectorSize
m <- L.initialNew 1
s <- L.initialNew 1
e <- L.initialNew 100
l <- STRef.newSTRef 1
return BState { currentResidue = Nothing,
currentModel = Nothing,
currentChain = Nothing,
currentStructure = Structure { models = L.empty },
residueContents = r,
chainContents = c,
modelContents = m,
structureContents = s,
errors = e,
lineNo = l }
checkResidue :: Bio.PDB.EventParser.PDBEvents.RESID -> ParsingMonad t ()
checkResidue (RESID (newName, newChain, newResseq, newInsCode)) =
do checkChain newChain
res <- State.gets currentResidue
when (residueChanged res) $ do closeResidue
l <- L.new L.residueVectorSize
State.modify $! createResidue l
where
residueChanged Nothing = True
residueChanged (Just (Residue { resName = oldResName,
resSeq = oldResSeq ,
insCode = oldInsCode,
atoms = _atoms })) =
(oldResName, oldResSeq, oldInsCode) /= (newName, newResseq, newInsCode)
createResidue l st = st { currentResidue = Just newResidue,
residueContents = l }
newResidue = Bio.PDB.Structure.Residue { resName = newName,
resSeq = newResseq,
insCode = newInsCode,
atoms = L.empty }
checkChain :: Char -> ParsingMonad t ()
checkChain name = do checkModel
curChain <- State.gets currentChain
when (chainChanged curChain) $ do closeChain
l <- L.new L.chainVectorSize
State.modify $ createChain l
where
chainChanged Nothing = True
chainChanged (Just (Chain { chainId = oldChain })) = oldChain /= name
createChain l state = state { currentChain = Just Chain { chainId = name,
residues = L.empty },
chainContents = l }
checkModel :: ParsingMonad t ()
checkModel = do curModel <- State.gets currentModel
when (isNothing curModel) $ openModel defaultModelId
defaultModelId = 1
| Closes construction of a current residue and appends this residue to a current chain . ( Monadic action . )
closeResidue :: ParsingMonad t ()
closeResidue = do r <- State.gets currentResidue
when (isJust r) $ do let Just res = r
rc <- State.gets residueContents
rf <- L.finalize rc
cc <- State.gets chainContents
cc' <- L.add cc $ res { Bio.PDB.Structure.atoms = rf }
State.modify clearResidue
where
clearResidue st = st { currentResidue = Nothing }
closeChain :: ParsingMonad t ()
closeChain = do closeResidue
c <- State.gets currentChain
ac <- State.gets chainContents
when (isJust c) $ do l <- State.gets chainContents
l' <- L.finalize l
let Just ch = c
ch' = ch { Bio.PDB.Structure.residues = l' }
m <- State.gets currentModel
when (isNothing m) $ do mli <- State.gets structureContents
i <- L.tempLength mli
openModel i
addError ["Trying to close chain when currentChain is ",
BS.pack . show $ ch,
" and currentModel is ",
BS.pack . show $ m]
ml <- State.gets modelContents
ml' <- L.add ml ch'
State.modify clearChain
where
clearChain st = st { currentChain = Nothing }
| Reports error during building of structure for PDB entry .
addError :: [String] -> ParsingMonad t ()
addError msg = do e <- State.gets errors
lnref <- State.gets lineNo
ln <- lift $ STRef.readSTRef lnref
lift $ STRef.modifySTRef lnref (+1)
L.add e $ anError ln
where
anError ln = PDBParseError ln 0 $ BS.concat msg
closeModel :: ParsingMonad t ()
closeModel = do closeChain
cm <- State.gets currentModel
case cm of
Nothing -> return ()
Just m -> do mc <- State.gets modelContents
chs <- L.finalize mc
let m' = m { chains = chs }
sc <- State.gets structureContents
State.modify clearModel
L.add sc m'
where clearModel st = st { currentModel = Nothing }
| Finalizes construction of record holding PDB entry data .
closeStructure :: ParsingMonad t ()
closeStructure = do closeModel
sc <- State.gets structureContents
sc' <- L.finalize sc
State.modify (closeStructure' sc')
where
closeStructure' sc bstate@(BState { currentStructure = aStructure}) =
bstate { currentStructure = aStructure { models = sc },
structureContents = undefined }
nextLine :: ParsingMonad t ()
nextLine = do lnref <- State.gets lineNo
lift $ STRef.modifySTRef lnref (+1)
| Performs a match on a single PDBEvent and performs relevant change to a BState of structure builder .
parseStep : : ( State . MonadState m ) = > PDBEvent - > m ( )
parseStep pe@(PDBParseError l _ _) = do e <- State.gets errors
L.add e pe
lnref <- State.gets lineNo
lift $ STRef.writeSTRef lnref l
: : ! ,
: : ! ,
: : ! , - atom name
: : !
}) =
do checkResidue $ RESID (resName, chainName, resSeq, resInsCode)
reslist <- State.gets residueContents
newAtom `seq` L.add reslist newAtom
nextLine
where newAtom = Atom { atName = atType,
atSerial = atSer,
coord = atCoord,
bFactor = atBFactor,
occupancy = atOccupancy,
element = atElement,
segid = atSegId,
charge = atCharge,
hetatm = isHet
}
parseStep (MODEL { num = n }) = do closeModel
openModel n
nextLine
parseStep ENDMDL = do closeModel
nextLine
parseStep END = do closeModel
nextLine
TODO : check TER with currentChain parameters
nextLine
nextLine
parseStep _ = nextLine
openModel :: Int -> ParsingMonad t ()
openModel n = do l <- L.new L.defaultSize
State.modify $ changeModel l
where changeModel l st = st { currentModel = Just newModel,
modelContents = l }
newModel = Bio.PDB.Structure.Model { modelId = n,
chains = empty }
parseFinish :: ParsingMonad t (Structure, L.List PDBEvent)
parseFinish = do closeStructure
st <- State.gets currentStructure
er <- State.gets errors
er' <- finalize er
st `seq` return (st, er')
|
7767a98fc592813f32d9c442ca99006e78239df51b4c99ff5ea1ea0298f3584b | florence/cover | error-file.rkt | #lang racket
(require rackunit)
(check-true #f)
(test-begin
(error "this is supposed to happend"))
| null | https://raw.githubusercontent.com/florence/cover/bc17e4e22d47b1da91ddaa5eafefe28f4675e85c/cover-test/cover/tests/error-file.rkt | racket | #lang racket
(require rackunit)
(check-true #f)
(test-begin
(error "this is supposed to happend"))
| |
e56ad059b5722b87512fe91d1500cfbbc090c49e9350c1f4a2919194449fec74 | lpw25/ocaml-typed-effects | mctest.ml |
* Copyright ( c ) 2015 , < >
* Copyright ( c ) 2015 , < >
*
* 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 .
* Copyright (c) 2015, Théo Laurent <>
* Copyright (c) 2015, KC Sivaramakrishnan <>
*
* 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.
*)
queue
module type BS = sig
type t
val create : ?max:int -> unit -> t
val once : t -> unit
val reset : t -> unit
end
module B : BS = struct
type t = int * int ref
let _ = Random.self_init ()
let create ?(max=32) () = (max, ref 1)
let once (maxv, r) =
let t = Random.int (!r) in
r := min (2 * !r) maxv;
if t = 0 then ()
else ignore (Unix.select [] [] [] (0.001 *. (float_of_int t)))
let reset (_,r) = r := 1
end
(* TODO KC: Replace with concurrent lock free bag --
* *)
module type QS = sig
type 'a t
val create : unit -> 'a t
val is_empty : 'a t -> bool
val push : 'a t -> 'a -> unit
val pop : 'a t -> 'a option
val clean_until : 'a t -> ('a -> bool) -> unit
type 'a cursor
val snapshot : 'a t -> 'a cursor
val next : 'a cursor -> ('a * 'a cursor) option
end
module Q : QS = struct
type 'a node =
| Nil
| Next of 'a * 'a node Atomic.t
type 'a t =
{ head : 'a node Atomic.t ;
tail : 'a node Atomic.t }
let create () =
let head = (Next (Obj.magic (), Atomic.make Nil)) in
{ head = Atomic.make head ; tail = Atomic.make head }
let is_empty q =
match Atomic.get q.head with
| Nil -> failwith "MSQueue.is_empty: impossible"
| Next (_,x) ->
( match Atomic.get x with
| Nil -> true
| _ -> false )
let pop q =
let b = B.create () in
let rec loop () =
let s = Atomic.get q.head in
let nhead = match s with
| Nil -> failwith "MSQueue.pop: impossible"
| Next (_, x) -> Atomic.get x
in match nhead with
| Nil -> None
| Next (v, _) when Atomic.compare_and_set q.head s nhead -> Some v
| _ -> ( B.once b ; loop () )
in loop ()
let push q v =
let rec find_tail_and_enq curr_end node =
if Atomic.compare_and_set curr_end Nil node then ()
else match Atomic.get curr_end with
| Nil -> find_tail_and_enq curr_end node
| Next (_, n) -> find_tail_and_enq n node
in
let newnode = Next (v, Atomic.make Nil) in
let tail = Atomic.get q.tail in
match tail with
| Nil -> failwith "HW_MSQueue.push: impossible"
| Next (_, n) -> begin
find_tail_and_enq n newnode;
ignore (Atomic.compare_and_set q.tail tail newnode)
end
let rec clean_until q f =
let b = B.create () in
let rec loop () =
let s = Atomic.get q.head in
let nhead = match s with
| Nil -> failwith "MSQueue.pop: impossible"
| Next (_, x) -> Atomic.get x
in match nhead with
| Nil -> ()
| Next (v, _) ->
if not (f v) then
if Atomic.compare_and_set q.head s nhead
then (B.reset b; loop ())
else (B.once b; loop ())
else ()
in loop ()
type 'a cursor = 'a node
let snapshot q =
match Atomic.get q.head with
| Nil -> failwith "MSQueue.snapshot: impossible"
| Next (_, n) -> Atomic.get n
let next c =
match c with
| Nil -> None
| Next (a, n) -> Some (a, Atomic.get n)
end
module Scheduler =
struct
type 'a cont = ('a, unit) continuation
effect Suspend : ('a cont -> 'a option) -> 'a
effect Resume : ('a cont * 'a) -> unit
effect GetTid : int
effect Spawn : (unit -> unit) -> unit
effect Yield : unit
let suspend f = perform (Suspend f)
let resume t v = perform (Resume (t, v))
let get_tid () = perform GetTid
let spawn f = perform (Spawn f)
let yield () = perform Yield
let pqueue = Q.create ()
let get_free_pid () = Oo.id (object end)
let enqueue k = Q.push pqueue k; Gc.minor ()
let rec dequeue () =
match Q.pop pqueue with
| Some k ->
continue k ()
| None ->
ignore (Unix.select [] [] [] 0.01);
dequeue ()
let rec exec f =
let pid = get_free_pid () in
match f () with
| () -> dequeue ()
| effect (Suspend f) k -> (
match f k with
| None -> dequeue ()
| Some v -> continue k v
)
| effect (Resume (t, v)) k ->
enqueue k;
continue t v
| effect GetTid k ->
continue k pid
| effect (Spawn f) k ->
enqueue k;
exec f
| effect Yield k ->
enqueue k;
dequeue ()
let num_threads = 2
let start f =
for i = 1 to num_threads - 1 do
ignore (Domain.spawn dequeue)
done;
exec f
end
let _ =
let procs = 4 in
let counter = Atomic.make 0 in
let rec finish () =
let v = Atomic.get counter in
if not (Atomic.compare_and_set counter v (v+1)) then finish ();
if v + 1 = procs then exit 0
in
let rec worker n =
let r = ref 0 in
for i = 1 to 10000 do
Scheduler.yield ();
for j = 1 to 10000 do
incr r
done
done;
print_string (Printf.sprintf "done %d\n" !r); flush stdout;
finish ()
in
Scheduler.start
(fun () ->
for i = 1 to procs do
( ) ;
Scheduler.spawn (fun () -> worker i)
done;
)
| null | https://raw.githubusercontent.com/lpw25/ocaml-typed-effects/79ea08b285c1fd9caf3f5a4d2aa112877f882bea/testsuite/tests/parallel/mctest.ml | ocaml | TODO KC: Replace with concurrent lock free bag --
* |
* Copyright ( c ) 2015 , < >
* Copyright ( c ) 2015 , < >
*
* 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 .
* Copyright (c) 2015, Théo Laurent <>
* Copyright (c) 2015, KC Sivaramakrishnan <>
*
* 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.
*)
queue
module type BS = sig
type t
val create : ?max:int -> unit -> t
val once : t -> unit
val reset : t -> unit
end
module B : BS = struct
type t = int * int ref
let _ = Random.self_init ()
let create ?(max=32) () = (max, ref 1)
let once (maxv, r) =
let t = Random.int (!r) in
r := min (2 * !r) maxv;
if t = 0 then ()
else ignore (Unix.select [] [] [] (0.001 *. (float_of_int t)))
let reset (_,r) = r := 1
end
module type QS = sig
type 'a t
val create : unit -> 'a t
val is_empty : 'a t -> bool
val push : 'a t -> 'a -> unit
val pop : 'a t -> 'a option
val clean_until : 'a t -> ('a -> bool) -> unit
type 'a cursor
val snapshot : 'a t -> 'a cursor
val next : 'a cursor -> ('a * 'a cursor) option
end
module Q : QS = struct
type 'a node =
| Nil
| Next of 'a * 'a node Atomic.t
type 'a t =
{ head : 'a node Atomic.t ;
tail : 'a node Atomic.t }
let create () =
let head = (Next (Obj.magic (), Atomic.make Nil)) in
{ head = Atomic.make head ; tail = Atomic.make head }
let is_empty q =
match Atomic.get q.head with
| Nil -> failwith "MSQueue.is_empty: impossible"
| Next (_,x) ->
( match Atomic.get x with
| Nil -> true
| _ -> false )
let pop q =
let b = B.create () in
let rec loop () =
let s = Atomic.get q.head in
let nhead = match s with
| Nil -> failwith "MSQueue.pop: impossible"
| Next (_, x) -> Atomic.get x
in match nhead with
| Nil -> None
| Next (v, _) when Atomic.compare_and_set q.head s nhead -> Some v
| _ -> ( B.once b ; loop () )
in loop ()
let push q v =
let rec find_tail_and_enq curr_end node =
if Atomic.compare_and_set curr_end Nil node then ()
else match Atomic.get curr_end with
| Nil -> find_tail_and_enq curr_end node
| Next (_, n) -> find_tail_and_enq n node
in
let newnode = Next (v, Atomic.make Nil) in
let tail = Atomic.get q.tail in
match tail with
| Nil -> failwith "HW_MSQueue.push: impossible"
| Next (_, n) -> begin
find_tail_and_enq n newnode;
ignore (Atomic.compare_and_set q.tail tail newnode)
end
let rec clean_until q f =
let b = B.create () in
let rec loop () =
let s = Atomic.get q.head in
let nhead = match s with
| Nil -> failwith "MSQueue.pop: impossible"
| Next (_, x) -> Atomic.get x
in match nhead with
| Nil -> ()
| Next (v, _) ->
if not (f v) then
if Atomic.compare_and_set q.head s nhead
then (B.reset b; loop ())
else (B.once b; loop ())
else ()
in loop ()
type 'a cursor = 'a node
let snapshot q =
match Atomic.get q.head with
| Nil -> failwith "MSQueue.snapshot: impossible"
| Next (_, n) -> Atomic.get n
let next c =
match c with
| Nil -> None
| Next (a, n) -> Some (a, Atomic.get n)
end
module Scheduler =
struct
type 'a cont = ('a, unit) continuation
effect Suspend : ('a cont -> 'a option) -> 'a
effect Resume : ('a cont * 'a) -> unit
effect GetTid : int
effect Spawn : (unit -> unit) -> unit
effect Yield : unit
let suspend f = perform (Suspend f)
let resume t v = perform (Resume (t, v))
let get_tid () = perform GetTid
let spawn f = perform (Spawn f)
let yield () = perform Yield
let pqueue = Q.create ()
let get_free_pid () = Oo.id (object end)
let enqueue k = Q.push pqueue k; Gc.minor ()
let rec dequeue () =
match Q.pop pqueue with
| Some k ->
continue k ()
| None ->
ignore (Unix.select [] [] [] 0.01);
dequeue ()
let rec exec f =
let pid = get_free_pid () in
match f () with
| () -> dequeue ()
| effect (Suspend f) k -> (
match f k with
| None -> dequeue ()
| Some v -> continue k v
)
| effect (Resume (t, v)) k ->
enqueue k;
continue t v
| effect GetTid k ->
continue k pid
| effect (Spawn f) k ->
enqueue k;
exec f
| effect Yield k ->
enqueue k;
dequeue ()
let num_threads = 2
let start f =
for i = 1 to num_threads - 1 do
ignore (Domain.spawn dequeue)
done;
exec f
end
let _ =
let procs = 4 in
let counter = Atomic.make 0 in
let rec finish () =
let v = Atomic.get counter in
if not (Atomic.compare_and_set counter v (v+1)) then finish ();
if v + 1 = procs then exit 0
in
let rec worker n =
let r = ref 0 in
for i = 1 to 10000 do
Scheduler.yield ();
for j = 1 to 10000 do
incr r
done
done;
print_string (Printf.sprintf "done %d\n" !r); flush stdout;
finish ()
in
Scheduler.start
(fun () ->
for i = 1 to procs do
( ) ;
Scheduler.spawn (fun () -> worker i)
done;
)
|
109803aa1f3d061bfa8ea7babbd6747edbead10d214bd2a763f6e930814c4183 | tsloughter/epubnub | epn_basic_examples.erl | -module(epn_basic_examples).
-compile([export_all]).
publish() ->
epubnub:publish(<<"hello_world">>, <<"hello">>).
subscribe() ->
epubnub:subscribe(<<"hello_world">>, fun(X)-> io:format("~p~n", [X]) end).
history() ->
epubnub:history(<<"hello_world">>, 10).
time() ->
epubnub:time().
| null | https://raw.githubusercontent.com/tsloughter/epubnub/7c2168dce81631ab5e8d66bfed71ef187940a367/src/epn_basic_examples.erl | erlang | -module(epn_basic_examples).
-compile([export_all]).
publish() ->
epubnub:publish(<<"hello_world">>, <<"hello">>).
subscribe() ->
epubnub:subscribe(<<"hello_world">>, fun(X)-> io:format("~p~n", [X]) end).
history() ->
epubnub:history(<<"hello_world">>, 10).
time() ->
epubnub:time().
| |
f6ab5cdf8c2e9e6a4e62242e079bcac673112367fc1468a74c98a5689e39b2a0 | spechub/Hets | Morphism.hs | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE FunctionalDependencies #
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleInstances #
# LANGUAGE UndecidableInstances #
# LANGUAGE ExistentialQuantification #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE StandaloneDeriving #
|
Module : ./Logic / Morphism.hs
Description : interface ( type class ) for logic projections ( morphisms ) in Hets
Copyright : ( c ) , Uni Bremen 2002 - 2004
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non - portable ( via Logic )
Interface ( type class ) for logic projections ( morphisms ) in Hets
Provides data structures for institution morphisms .
These are just collections of
functions between ( some of ) the types of logics .
Module : ./Logic/Morphism.hs
Description : interface (type class) for logic projections (morphisms) in Hets
Copyright : (c) Till Mossakowski, Uni Bremen 2002-2004
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non-portable (via Logic)
Interface (type class) for logic projections (morphisms) in Hets
Provides data structures for institution morphisms.
These are just collections of
functions between (some of) the types of logics.
-}
{- References: see Logic.hs
Todo:
morphism modifications / representation maps
-}
module Logic.Morphism where
import Logic.Logic
import Logic.Comorphism
import Data.Data
import qualified Data.Set as Set
import ATerm.Lib
import Common.DocUtils
import Common.AS_Annotation
import Common.Id
import Common.Json
import Common.ToXml
import GHC.Generics (Generic)
class (Language cid,
Logic lid1 sublogics1
basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 sign_symbol1 symbol1 proof_tree1,
Logic lid2 sublogics2
basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 sign_symbol2 symbol2 proof_tree2) =>
Morphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 sign_symbol1 symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 sign_symbol2 symbol2 proof_tree2
| cid -> lid1, cid -> lid2
, lid1 -> sublogics1 basic_spec1 sentence1 symb_items1
symb_map_items1 sign1 morphism1 sign_symbol1 symbol1 proof_tree1
, lid2 -> sublogics2 basic_spec2 sentence2 symb_items2
symb_map_items2 sign2 morphism2 sign_symbol2 symbol2 proof_tree2
where
source and target logic and sublogic
the source sublogic is the maximal one for which the comorphism works
the target sublogic is the resulting one
the source sublogic is the maximal one for which the comorphism works
the target sublogic is the resulting one -}
morSourceLogic :: cid -> lid1
morSourceSublogic :: cid -> sublogics1
morTargetLogic :: cid -> lid2
morTargetSublogic :: cid -> sublogics2
finer information of target sublogics corresponding to source sublogics
morMapSublogicSign :: cid -> sublogics1 -> sublogics2
information about the source sublogics corresponding to target sublogics
morMapSublogicSen :: cid -> sublogics2 -> sublogics1
the translation functions are partial
because the target may be a sublanguage
map_basic_spec : : cid - > basic_spec1 - > Maybe basic_spec2
we do not cover theoroidal morphisms ,
since there are no relevant examples and they do not compose nicely
no mapping of theories , since signatures and sentences are mapped
contravariantly
because the target may be a sublanguage
map_basic_spec :: cid -> basic_spec1 -> Maybe basic_spec2
we do not cover theoroidal morphisms,
since there are no relevant examples and they do not compose nicely
no mapping of theories, since signatures and sentences are mapped
contravariantly -}
morMap_sign :: cid -> sign1 -> Maybe sign2
morMap_morphism :: cid -> morphism1 -> Maybe morphism2
morMap_sentence :: cid -> sign1 -> sentence2 -> Maybe sentence1
{- also covers semi-morphisms ??
with no sentence translation
- but these are spans! -}
morMap_sign_symbol :: cid -> sign_symbol1 -> Set.Set sign_symbol2
morConstituents not needed , because composition only via lax triangles
-- | identity morphisms
data IdMorphism lid sublogics =
IdMorphism lid sublogics deriving (Typeable, Show)
instance Logic lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism sign_symbol symbol proof_tree =>
Language (IdMorphism lid sublogics) where
language_name (IdMorphism lid sub) = "id_" ++ language_name lid
++ case sublogicName sub of
[] -> ""
h -> '.' : h
instance Logic lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism sign_symbol symbol proof_tree =>
Morphism (IdMorphism lid sublogics)
lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism sign_symbol symbol proof_tree
lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism sign_symbol symbol proof_tree
where
morSourceLogic (IdMorphism lid _sub) = lid
morTargetLogic (IdMorphism lid _sub) = lid
morSourceSublogic (IdMorphism _lid sub) = sub
morTargetSublogic (IdMorphism _lid sub) = sub
-- changed to identities!
morMapSublogicSign _ x = x
morMapSublogicSen _ x = x
morMap_sign _ = Just
morMap_morphism _ = Just
morMap_sentence _ _ = Just
morMap_sign_symbol _ = Set.singleton
-- composition not needed, use lax triangles instead
-- | comorphisms inducing morphisms
class Comorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 sign_symbol1 symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 sign_symbol2 symbol2 proof_tree2 =>
InducingComorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 sign_symbol1 symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 sign_symbol2 symbol2 proof_tree2
where
indMorMap_sign :: cid -> sign2 -> Maybe sign1
indMorMap_morphism :: cid -> morphism2 -> Maybe morphism1
epsilon :: cid -> sign2 -> Maybe morphism2
-- ------------------------------------------------------------------------
Morphisms as spans of comorphisms
if the morphism is ( psi , alpha , beta ) : I - > J
it is replaced with the following span
SignI i d - >
SenI alpha < - i d - > psi;SenJ
ModI beta - > psi^op;ModJ i d < - psi^op;ModJ
it is replaced with the following span
SignI id -> SignI psi -> SignJ
SenI alpha <- psi;SenJ id -> psi;SenJ
ModI beta -> psi^op;ModJ id <- psi^op;ModJ -}
1 . introduce a new logic for the domain of the span
this logic will have
the name ( SpanDomain cid ) where cid is the name of the morphism
sublogics - pairs ( s1 , s2 ) with s1 being a sublogic of I and s2
being a sublogic of J ; the lattice is the product lattice of the two
existing lattices
basic_spec will be ( ) - the unit type , because we mix signatures
with sentences in specifications
sentence - sentences of J , wrapped
symb_items - ( )
symb_map_items - ( )
sign - signatures of I
morphism - morphisms of I
sign_symbol - sign_symbols of I
symbol - symbols of I
proof_tree - proof_tree of J
this logic will have
the name (SpanDomain cid) where cid is the name of the morphism
sublogics - pairs (s1, s2) with s1 being a sublogic of I and s2
being a sublogic of J; the lattice is the product lattice of the two
existing lattices
basic_spec will be () - the unit type, because we mix signatures
with sentences in specifications
sentence - sentences of J, wrapped
symb_items - ()
symb_map_items - ()
sign - signatures of I
morphism - morphisms of I
sign_symbol - sign_symbols of I
symbol - symbols of I
proof_tree - proof_tree of J -}
data SpanDomain cid = SpanDomain cid deriving (Eq, Show)
data SublogicsPair a b = SublogicsPair a b deriving (Eq, Ord, Show, Typeable)
instance Language cid => Language (SpanDomain cid) where
language_name (SpanDomain cid) = "SpanDomain" ++ language_name cid
{- the category of signatures is exactly the category of signatures of
the sublogic on which the morphism is defined, but with another name -}
instance (Morphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 sign_symbol1 symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 sign_symbol2 symbol2 proof_tree2
, Pretty sign_symbol1)
=> Syntax (SpanDomain cid) () sign_symbol1 () ()
-- default is ok
newtype S2 s = S2 { sentence2 :: s }
deriving (Eq, Ord, Show, Typeable, ShATermConvertible, Pretty, GetRange, Data, Generic)
deriving instance {-# OVERLAPPING #-} Data a => ToJson (S2 a)
deriving instance {-# OVERLAPPING #-} Data a => ToXml (S2 a)
instance (Morphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 sign_symbol1 symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 sign_symbol2 symbol2 proof_tree2
, Category sign1 morphism1, Ord sign_symbol1, GetRange sign_symbol1, Data sentence2)
=> Sentences (SpanDomain cid) (S2 sentence2) sign1 morphism1
sign_symbol1 where
{- one has to take care about signature and morphisms
and translate them to targetLogic
we get a Maybe sign/morphism -}
map_sen (SpanDomain cid) mor1 (S2 sen) =
case morMap_morphism cid mor1 of
Just mor2 -> fmap S2 $
map_sen (morTargetLogic cid) mor2 sen
Nothing -> statFail (SpanDomain cid) "map_sen"
simplify_sen (SpanDomain cid) sigma (S2 sen) =
case morMap_sign cid sigma of
Just sigma2 -> S2 $
simplify_sen (morTargetLogic cid) sigma2 sen
Nothing -> error "simplify_sen"
print_named (SpanDomain cid) = print_named (morTargetLogic cid)
. mapNamed sentence2
sym_of (SpanDomain cid) = sym_of (morSourceLogic cid)
symmap_of (SpanDomain cid) = symmap_of (morSourceLogic cid)
sym_name (SpanDomain cid) = sym_name (morSourceLogic cid)
instance (Morphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 sign_symbol1 symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 sign_symbol2 symbol2 proof_tree2
, Ord symbol1, GetRange symbol1, Pretty symbol1, Typeable symbol1, Data sentence2)
=> StaticAnalysis (SpanDomain cid) () (S2 sentence2) () ()
sign1 morphism1 sign_symbol1 symbol1 where
ensures_amalgamability l _ = statFail l "ensures_amalgamability"
symbol_to_raw (SpanDomain cid) = symbol_to_raw (morSourceLogic cid)
id_to_raw (SpanDomain cid) = id_to_raw (morSourceLogic cid)
matches (SpanDomain cid) = matches (morSourceLogic cid)
empty_signature (SpanDomain cid) = empty_signature (morSourceLogic cid)
signature_union (SpanDomain cid) = signature_union (morSourceLogic cid)
final_union (SpanDomain cid) = final_union (morSourceLogic cid)
morphism_union (SpanDomain cid) = morphism_union (morSourceLogic cid)
is_subsig (SpanDomain cid) = is_subsig (morSourceLogic cid)
subsig_inclusion (SpanDomain cid) = subsig_inclusion (morSourceLogic cid)
generated_sign (SpanDomain cid) = generated_sign (morSourceLogic cid)
cogenerated_sign (SpanDomain cid) = cogenerated_sign (morSourceLogic cid)
is_transportable (SpanDomain cid) = is_transportable (morSourceLogic cid)
is_injective (SpanDomain cid) = is_injective (morSourceLogic cid)
instance (SemiLatticeWithTop sublogics1, SemiLatticeWithTop sublogics2)
=> SemiLatticeWithTop (SublogicsPair sublogics1 sublogics2) where
top = SublogicsPair top top
lub (SublogicsPair x1 y1) (SublogicsPair x2 y2) =
SublogicsPair (lub x1 x2) (lub y1 y2)
instance {-# OVERLAPS #-} (SemiLatticeWithTop sublogics1, MinSublogic sublogics2 sentence2)
=> MinSublogic (SublogicsPair sublogics1 sublogics2) (S2 sentence2) where
minSublogic (S2 sen2) = SublogicsPair top (minSublogic sen2)
just a dummy implementation , it should be the sublogic of sen2 in J
paired with its image through morMapSublogicSen ?
paired with its image through morMapSublogicSen? -}
instance {-# OVERLAPS #-} (MinSublogic sublogics1 alpha, SemiLatticeWithTop sublogics2)
=> MinSublogic (SublogicsPair sublogics1 sublogics2) alpha where
minSublogic x = SublogicsPair (minSublogic x) top
also should have instances of MinSublogic class for Sublogics - pair
and , sign_symbol1 , this is why the wrapping is needed
and morphism1, sign_symbol1, sign1 this is why the wrapping is needed -}
instance SemiLatticeWithTop sublogics = > MinSublogic sublogics ( ) where
minSublogic _ = top
minSublogic _ = top -}
instance (MinSublogic sublogics1 alpha, SemiLatticeWithTop sublogics2)
=> ProjectSublogic (SublogicsPair sublogics1 sublogics2) alpha where
projectSublogic _ x = x
it should be used for ( ) , , sign_symbol1 ,
instance (MinSublogic sublogics1 sign1, SemiLatticeWithTop sublogics2)
=> ProjectSublogicM (SublogicsPair sublogics1 sublogics2) sign1 where
projectSublogicM _ = Just
instance (ShATermConvertible a, ShATermConvertible b)
=> ShATermConvertible (SublogicsPair a b) where
toShATermAux att0 (SublogicsPair a b) = do
(att1, a') <- toShATerm' att0 a
(att2, b') <- toShATerm' att1 b
return $ addATerm (ShAAppl "SublogicsPair" [a', b'] []) att2
fromShATermAux ix att0 = case getShATerm ix att0 of
ShAAppl "SublogicsPair" [a, b] _ ->
case fromShATerm' a att0 of { (att1, a') ->
case fromShATerm' b att1 of { (att2, b') ->
(att2, SublogicsPair a' b') }}
u -> fromShATermError "SublogicsPair" u
instance (SublogicName sublogics1, SublogicName sublogics2)
=> SublogicName (SublogicsPair sublogics1 sublogics2) where
sublogicName (SublogicsPair sub1 sub2) =
let s1 = sublogicName sub1
s2 = sublogicName sub2
in if null s1 then s2 else if null s2 then s1 else
s1 ++ "|" ++ s2
instance (MinSublogic sublogics1 ()
, Morphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 sign_symbol1 symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 sign_symbol2 symbol2 proof_tree2
, Ord proof_tree2, Show proof_tree2, Data sentence2)
=> Logic (SpanDomain cid) (SublogicsPair sublogics1 sublogics2) ()
(S2 sentence2) () () sign1 morphism1 sign_symbol1 symbol1 proof_tree2
where
stability (SpanDomain _) = Experimental
data_logic (SpanDomain _) = Nothing
top_sublogic (SpanDomain cid) = SublogicsPair
(top_sublogic $ morSourceLogic cid) $ top_sublogic $ morTargetLogic cid
all_sublogics (SpanDomain cid) =
[ SublogicsPair x y
| x <- all_sublogics (morSourceLogic cid)
, y <- all_sublogics (morTargetLogic cid) ]
-- project_sublogic_epsilon - default implementation for now
provers _ = []
cons_checkers _ = []
conservativityCheck _ = []
empty_proof_tree (SpanDomain cid) = empty_proof_tree (morTargetLogic cid)
*
-- | Existential type for morphisms
data AnyMorphism = forall cid lid1 sublogics1
basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2
basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2 .
Morphism cid
lid1 sublogics1 basic_spec1 sentence1
symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2
symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2 =>
Morphism cid
instance where
Morphism cid1 = = =
constituents cid1 = = constituents -- need to be refined , using morphism translations ! ! !
instance Eq AnyMorphism where
Morphism cid1 == Morphism cid2 =
constituents cid1 == constituents cid2
-- need to be refined, using morphism translations !!!
-}
instance Show AnyMorphism where
show (Morphism cid) = language_name cid
++ " : " ++ language_name (morSourceLogic cid)
++ " -> " ++ language_name (morTargetLogic cid)
| null | https://raw.githubusercontent.com/spechub/Hets/4cedaf8dbdb8909955e0066b465c331973043bbf/Logic/Morphism.hs | haskell | # LANGUAGE DeriveDataTypeable #
References: see Logic.hs
Todo:
morphism modifications / representation maps
also covers semi-morphisms ??
with no sentence translation
- but these are spans!
| identity morphisms
changed to identities!
composition not needed, use lax triangles instead
| comorphisms inducing morphisms
------------------------------------------------------------------------
the category of signatures is exactly the category of signatures of
the sublogic on which the morphism is defined, but with another name
default is ok
# OVERLAPPING #
# OVERLAPPING #
one has to take care about signature and morphisms
and translate them to targetLogic
we get a Maybe sign/morphism
# OVERLAPS #
# OVERLAPS #
project_sublogic_epsilon - default implementation for now
| Existential type for morphisms
need to be refined , using morphism translations ! ! !
need to be refined, using morphism translations !!! | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE FunctionalDependencies #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleInstances #
# LANGUAGE UndecidableInstances #
# LANGUAGE ExistentialQuantification #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE StandaloneDeriving #
|
Module : ./Logic / Morphism.hs
Description : interface ( type class ) for logic projections ( morphisms ) in Hets
Copyright : ( c ) , Uni Bremen 2002 - 2004
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non - portable ( via Logic )
Interface ( type class ) for logic projections ( morphisms ) in Hets
Provides data structures for institution morphisms .
These are just collections of
functions between ( some of ) the types of logics .
Module : ./Logic/Morphism.hs
Description : interface (type class) for logic projections (morphisms) in Hets
Copyright : (c) Till Mossakowski, Uni Bremen 2002-2004
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non-portable (via Logic)
Interface (type class) for logic projections (morphisms) in Hets
Provides data structures for institution morphisms.
These are just collections of
functions between (some of) the types of logics.
-}
module Logic.Morphism where
import Logic.Logic
import Logic.Comorphism
import Data.Data
import qualified Data.Set as Set
import ATerm.Lib
import Common.DocUtils
import Common.AS_Annotation
import Common.Id
import Common.Json
import Common.ToXml
import GHC.Generics (Generic)
class (Language cid,
Logic lid1 sublogics1
basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 sign_symbol1 symbol1 proof_tree1,
Logic lid2 sublogics2
basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 sign_symbol2 symbol2 proof_tree2) =>
Morphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 sign_symbol1 symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 sign_symbol2 symbol2 proof_tree2
| cid -> lid1, cid -> lid2
, lid1 -> sublogics1 basic_spec1 sentence1 symb_items1
symb_map_items1 sign1 morphism1 sign_symbol1 symbol1 proof_tree1
, lid2 -> sublogics2 basic_spec2 sentence2 symb_items2
symb_map_items2 sign2 morphism2 sign_symbol2 symbol2 proof_tree2
where
source and target logic and sublogic
the source sublogic is the maximal one for which the comorphism works
the target sublogic is the resulting one
the source sublogic is the maximal one for which the comorphism works
the target sublogic is the resulting one -}
morSourceLogic :: cid -> lid1
morSourceSublogic :: cid -> sublogics1
morTargetLogic :: cid -> lid2
morTargetSublogic :: cid -> sublogics2
finer information of target sublogics corresponding to source sublogics
morMapSublogicSign :: cid -> sublogics1 -> sublogics2
information about the source sublogics corresponding to target sublogics
morMapSublogicSen :: cid -> sublogics2 -> sublogics1
the translation functions are partial
because the target may be a sublanguage
map_basic_spec : : cid - > basic_spec1 - > Maybe basic_spec2
we do not cover theoroidal morphisms ,
since there are no relevant examples and they do not compose nicely
no mapping of theories , since signatures and sentences are mapped
contravariantly
because the target may be a sublanguage
map_basic_spec :: cid -> basic_spec1 -> Maybe basic_spec2
we do not cover theoroidal morphisms,
since there are no relevant examples and they do not compose nicely
no mapping of theories, since signatures and sentences are mapped
contravariantly -}
morMap_sign :: cid -> sign1 -> Maybe sign2
morMap_morphism :: cid -> morphism1 -> Maybe morphism2
morMap_sentence :: cid -> sign1 -> sentence2 -> Maybe sentence1
morMap_sign_symbol :: cid -> sign_symbol1 -> Set.Set sign_symbol2
morConstituents not needed , because composition only via lax triangles
data IdMorphism lid sublogics =
IdMorphism lid sublogics deriving (Typeable, Show)
instance Logic lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism sign_symbol symbol proof_tree =>
Language (IdMorphism lid sublogics) where
language_name (IdMorphism lid sub) = "id_" ++ language_name lid
++ case sublogicName sub of
[] -> ""
h -> '.' : h
instance Logic lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism sign_symbol symbol proof_tree =>
Morphism (IdMorphism lid sublogics)
lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism sign_symbol symbol proof_tree
lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism sign_symbol symbol proof_tree
where
morSourceLogic (IdMorphism lid _sub) = lid
morTargetLogic (IdMorphism lid _sub) = lid
morSourceSublogic (IdMorphism _lid sub) = sub
morTargetSublogic (IdMorphism _lid sub) = sub
morMapSublogicSign _ x = x
morMapSublogicSen _ x = x
morMap_sign _ = Just
morMap_morphism _ = Just
morMap_sentence _ _ = Just
morMap_sign_symbol _ = Set.singleton
class Comorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 sign_symbol1 symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 sign_symbol2 symbol2 proof_tree2 =>
InducingComorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 sign_symbol1 symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 sign_symbol2 symbol2 proof_tree2
where
indMorMap_sign :: cid -> sign2 -> Maybe sign1
indMorMap_morphism :: cid -> morphism2 -> Maybe morphism1
epsilon :: cid -> sign2 -> Maybe morphism2
Morphisms as spans of comorphisms
if the morphism is ( psi , alpha , beta ) : I - > J
it is replaced with the following span
SignI i d - >
SenI alpha < - i d - > psi;SenJ
ModI beta - > psi^op;ModJ i d < - psi^op;ModJ
it is replaced with the following span
SignI id -> SignI psi -> SignJ
SenI alpha <- psi;SenJ id -> psi;SenJ
ModI beta -> psi^op;ModJ id <- psi^op;ModJ -}
1 . introduce a new logic for the domain of the span
this logic will have
the name ( SpanDomain cid ) where cid is the name of the morphism
sublogics - pairs ( s1 , s2 ) with s1 being a sublogic of I and s2
being a sublogic of J ; the lattice is the product lattice of the two
existing lattices
basic_spec will be ( ) - the unit type , because we mix signatures
with sentences in specifications
sentence - sentences of J , wrapped
symb_items - ( )
symb_map_items - ( )
sign - signatures of I
morphism - morphisms of I
sign_symbol - sign_symbols of I
symbol - symbols of I
proof_tree - proof_tree of J
this logic will have
the name (SpanDomain cid) where cid is the name of the morphism
sublogics - pairs (s1, s2) with s1 being a sublogic of I and s2
being a sublogic of J; the lattice is the product lattice of the two
existing lattices
basic_spec will be () - the unit type, because we mix signatures
with sentences in specifications
sentence - sentences of J, wrapped
symb_items - ()
symb_map_items - ()
sign - signatures of I
morphism - morphisms of I
sign_symbol - sign_symbols of I
symbol - symbols of I
proof_tree - proof_tree of J -}
data SpanDomain cid = SpanDomain cid deriving (Eq, Show)
data SublogicsPair a b = SublogicsPair a b deriving (Eq, Ord, Show, Typeable)
instance Language cid => Language (SpanDomain cid) where
language_name (SpanDomain cid) = "SpanDomain" ++ language_name cid
instance (Morphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 sign_symbol1 symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 sign_symbol2 symbol2 proof_tree2
, Pretty sign_symbol1)
=> Syntax (SpanDomain cid) () sign_symbol1 () ()
newtype S2 s = S2 { sentence2 :: s }
deriving (Eq, Ord, Show, Typeable, ShATermConvertible, Pretty, GetRange, Data, Generic)
instance (Morphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 sign_symbol1 symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 sign_symbol2 symbol2 proof_tree2
, Category sign1 morphism1, Ord sign_symbol1, GetRange sign_symbol1, Data sentence2)
=> Sentences (SpanDomain cid) (S2 sentence2) sign1 morphism1
sign_symbol1 where
map_sen (SpanDomain cid) mor1 (S2 sen) =
case morMap_morphism cid mor1 of
Just mor2 -> fmap S2 $
map_sen (morTargetLogic cid) mor2 sen
Nothing -> statFail (SpanDomain cid) "map_sen"
simplify_sen (SpanDomain cid) sigma (S2 sen) =
case morMap_sign cid sigma of
Just sigma2 -> S2 $
simplify_sen (morTargetLogic cid) sigma2 sen
Nothing -> error "simplify_sen"
print_named (SpanDomain cid) = print_named (morTargetLogic cid)
. mapNamed sentence2
sym_of (SpanDomain cid) = sym_of (morSourceLogic cid)
symmap_of (SpanDomain cid) = symmap_of (morSourceLogic cid)
sym_name (SpanDomain cid) = sym_name (morSourceLogic cid)
instance (Morphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 sign_symbol1 symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 sign_symbol2 symbol2 proof_tree2
, Ord symbol1, GetRange symbol1, Pretty symbol1, Typeable symbol1, Data sentence2)
=> StaticAnalysis (SpanDomain cid) () (S2 sentence2) () ()
sign1 morphism1 sign_symbol1 symbol1 where
ensures_amalgamability l _ = statFail l "ensures_amalgamability"
symbol_to_raw (SpanDomain cid) = symbol_to_raw (morSourceLogic cid)
id_to_raw (SpanDomain cid) = id_to_raw (morSourceLogic cid)
matches (SpanDomain cid) = matches (morSourceLogic cid)
empty_signature (SpanDomain cid) = empty_signature (morSourceLogic cid)
signature_union (SpanDomain cid) = signature_union (morSourceLogic cid)
final_union (SpanDomain cid) = final_union (morSourceLogic cid)
morphism_union (SpanDomain cid) = morphism_union (morSourceLogic cid)
is_subsig (SpanDomain cid) = is_subsig (morSourceLogic cid)
subsig_inclusion (SpanDomain cid) = subsig_inclusion (morSourceLogic cid)
generated_sign (SpanDomain cid) = generated_sign (morSourceLogic cid)
cogenerated_sign (SpanDomain cid) = cogenerated_sign (morSourceLogic cid)
is_transportable (SpanDomain cid) = is_transportable (morSourceLogic cid)
is_injective (SpanDomain cid) = is_injective (morSourceLogic cid)
instance (SemiLatticeWithTop sublogics1, SemiLatticeWithTop sublogics2)
=> SemiLatticeWithTop (SublogicsPair sublogics1 sublogics2) where
top = SublogicsPair top top
lub (SublogicsPair x1 y1) (SublogicsPair x2 y2) =
SublogicsPair (lub x1 x2) (lub y1 y2)
=> MinSublogic (SublogicsPair sublogics1 sublogics2) (S2 sentence2) where
minSublogic (S2 sen2) = SublogicsPair top (minSublogic sen2)
just a dummy implementation , it should be the sublogic of sen2 in J
paired with its image through morMapSublogicSen ?
paired with its image through morMapSublogicSen? -}
=> MinSublogic (SublogicsPair sublogics1 sublogics2) alpha where
minSublogic x = SublogicsPair (minSublogic x) top
also should have instances of MinSublogic class for Sublogics - pair
and , sign_symbol1 , this is why the wrapping is needed
and morphism1, sign_symbol1, sign1 this is why the wrapping is needed -}
instance SemiLatticeWithTop sublogics = > MinSublogic sublogics ( ) where
minSublogic _ = top
minSublogic _ = top -}
instance (MinSublogic sublogics1 alpha, SemiLatticeWithTop sublogics2)
=> ProjectSublogic (SublogicsPair sublogics1 sublogics2) alpha where
projectSublogic _ x = x
it should be used for ( ) , , sign_symbol1 ,
instance (MinSublogic sublogics1 sign1, SemiLatticeWithTop sublogics2)
=> ProjectSublogicM (SublogicsPair sublogics1 sublogics2) sign1 where
projectSublogicM _ = Just
instance (ShATermConvertible a, ShATermConvertible b)
=> ShATermConvertible (SublogicsPair a b) where
toShATermAux att0 (SublogicsPair a b) = do
(att1, a') <- toShATerm' att0 a
(att2, b') <- toShATerm' att1 b
return $ addATerm (ShAAppl "SublogicsPair" [a', b'] []) att2
fromShATermAux ix att0 = case getShATerm ix att0 of
ShAAppl "SublogicsPair" [a, b] _ ->
case fromShATerm' a att0 of { (att1, a') ->
case fromShATerm' b att1 of { (att2, b') ->
(att2, SublogicsPair a' b') }}
u -> fromShATermError "SublogicsPair" u
instance (SublogicName sublogics1, SublogicName sublogics2)
=> SublogicName (SublogicsPair sublogics1 sublogics2) where
sublogicName (SublogicsPair sub1 sub2) =
let s1 = sublogicName sub1
s2 = sublogicName sub2
in if null s1 then s2 else if null s2 then s1 else
s1 ++ "|" ++ s2
instance (MinSublogic sublogics1 ()
, Morphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 sign_symbol1 symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 sign_symbol2 symbol2 proof_tree2
, Ord proof_tree2, Show proof_tree2, Data sentence2)
=> Logic (SpanDomain cid) (SublogicsPair sublogics1 sublogics2) ()
(S2 sentence2) () () sign1 morphism1 sign_symbol1 symbol1 proof_tree2
where
stability (SpanDomain _) = Experimental
data_logic (SpanDomain _) = Nothing
top_sublogic (SpanDomain cid) = SublogicsPair
(top_sublogic $ morSourceLogic cid) $ top_sublogic $ morTargetLogic cid
all_sublogics (SpanDomain cid) =
[ SublogicsPair x y
| x <- all_sublogics (morSourceLogic cid)
, y <- all_sublogics (morTargetLogic cid) ]
provers _ = []
cons_checkers _ = []
conservativityCheck _ = []
empty_proof_tree (SpanDomain cid) = empty_proof_tree (morTargetLogic cid)
*
data AnyMorphism = forall cid lid1 sublogics1
basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2
basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2 .
Morphism cid
lid1 sublogics1 basic_spec1 sentence1
symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2
symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2 =>
Morphism cid
instance where
Morphism cid1 = = =
instance Eq AnyMorphism where
Morphism cid1 == Morphism cid2 =
constituents cid1 == constituents cid2
-}
instance Show AnyMorphism where
show (Morphism cid) = language_name cid
++ " : " ++ language_name (morSourceLogic cid)
++ " -> " ++ language_name (morTargetLogic cid)
|
9fd5d0dd59c2e6762c96a42b0983b2ca4eef5a34a8adda9b97fd0e6bff9aea2e | exercism/clojure | bank_account.clj | (ns bank-account)
(defn open-account [] ;; <- arglist goes here
;; your code goes here
)
(defn close-account [] ;; <- arglist goes here
;; your code goes here
)
(defn get-balance [] ;; <- arglist goes here
;; your code goes here
)
(defn update-balance [] ;; <- arglist goes here
;; your code goes here
)
| null | https://raw.githubusercontent.com/exercism/clojure/04cb3e274f7c3f8d91229e0f64471e20433db6a1/exercises/practice/bank-account/src/bank_account.clj | clojure | <- arglist goes here
your code goes here
<- arglist goes here
your code goes here
<- arglist goes here
your code goes here
<- arglist goes here
your code goes here | (ns bank-account)
)
)
)
)
|
1194997616f153cfc6f56f1bb0aa020c25d3b4a947d5d611aaad522c78e84626 | issuu/ocaml-protoc-plugin | ocaml_protoc_plugin.ml | (**/**)
module Serialize = Serialize
module Deserialize = Deserialize
module Spec = Spec
module Runtime = Runtime
(**/**)
module Reader = Reader
module Writer = Writer
module Service = Service
module Result = Result
module Extensions = Extensions
(**/**)
let test () =
Writer.Test.test ();
Serialize.Test.test ();
()
(**/**)
| null | https://raw.githubusercontent.com/issuu/ocaml-protoc-plugin/1893507045110c6176b96f9a2156519fffbd6c26/src/ocaml_protoc_plugin/ocaml_protoc_plugin.ml | ocaml | */*
*/*
*/*
*/* | module Serialize = Serialize
module Deserialize = Deserialize
module Spec = Spec
module Runtime = Runtime
module Reader = Reader
module Writer = Writer
module Service = Service
module Result = Result
module Extensions = Extensions
let test () =
Writer.Test.test ();
Serialize.Test.test ();
()
|
3e190dc622372d5f6f37997c10a13d0cdcda156869bf961ae9d5f76550811c80 | tweag/linear-base | Many.hs | {-# LANGUAGE GADTs #-}
# LANGUAGE LambdaCase #
{-# LANGUAGE LinearTypes #-}
# LANGUAGE QualifiedDo #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
{-# OPTIONS_GHC -Wno-name-shadowing #-}
{-# OPTIONS_HADDOCK hide #-}
-- | This module contains all functions that do something with
-- multiple streams as input or output. This includes combining
-- streams, splitting a stream, etc.
module Streaming.Linear.Internal.Many
( -- * Operations that use or return multiple 'Stream's
* * and Unzip
unzip,
ZipResidual,
ZipResidual3,
zip,
zipR,
zipWith,
zipWithR,
zip3,
zip3R,
zipWith3,
zipWith3R,
Either3 (..),
-- ** Merging
-- $
merge,
mergeOn,
mergeBy,
)
where
import qualified Control.Functor.Linear as Control
import Prelude.Linear (($), (&))
import Streaming.Linear.Internal.Consume
import Streaming.Linear.Internal.Type
import Prelude (Either (..), Ord (..), Ordering (..))
# Zips and Unzip
-------------------------------------------------------------------------------
-- | The type
--
-- > Data.List.unzip :: [(a,b)] -> ([a],[b])
--
-- might lead us to expect
--
-- > Streaming.unzip :: Stream (Of (a,b)) m r -> Stream (Of a) m (Stream (Of b) m r)
--
which would not stream , since it would have to accumulate the second stream ( of @b@s ) .
-- Of course, @Data.List@ 'Data.List.unzip' doesn't stream either.
--
-- This @unzip@ does
-- stream, though of course you can spoil this by using e.g. 'toList':
--
-- @
> let ( \x - > ( x , ) ) [ 1 .. 5 : : Int ]
--
> S.toList $ S.toList $ S.unzip ( S.each ' xs )
[ " 1","2","3","4","5 " ] :> ( [ 1,2,3,4,5 ] :> ( ) )
--
> Prelude.unzip xs
( [ 1,2,3,4,5],["1","2","3","4","5 " ] )
-- @
--
-- Note the difference of order in the results. It may be of some use to think why.
The first application of ' toList ' was applied to a stream of integers :
--
-- @
> : t S.unzip $ S.each ' xs
S.unzip $ S.each ' xs : : Control . Monad m = > Stream ( Of Int ) ( Stream ( Of String ) m ) ( )
-- @
--
-- Like any fold, 'toList' takes no notice of the monad of effects.
--
> toList : : Control . Monad m = > Stream ( Of a ) m r % 1- > m ( Of [ a ] r )
--
-- In the case at hand (since I am in @ghci@) @m = Stream (Of String) IO@.
-- So when I apply 'toList', I exhaust that stream of integers, folding
-- it into a list:
--
-- @
> : t S.toList $ S.unzip $ S.each ' xs
S.toList $ S.unzip $ S.each ' xs
: : Control . Monad m = > Stream ( Of String ) m ( Of [ Int ] ( ) )
-- @
--
When I apply ' toList ' to /this/ , I reduce everything to an ordinary action in @IO@ ,
-- and return a list of strings:
--
-- @
> S.toList $ S.toList $ S.unzip ( S.each ' xs )
[ " 1","2","3","4","5 " ] :> ( [ 1,2,3,4,5 ] :> ( ) )
-- @
--
-- 'unzip' can be considered a special case of either 'unzips' or 'expand':
--
-- @
-- unzip = 'unzips' . 'maps' (\((a,b) :> x) -> Compose (a :> b :> x))
unzip = ' expand ' $ ( ( a , b ) :> abs ) - > b :> p ( a :> abs )
-- @
unzip ::
Control.Monad m =>
Stream (Of (a, b)) m r %1 ->
Stream (Of a) (Stream (Of b) m) r
unzip = loop
where
loop ::
Control.Monad m =>
Stream (Of (a, b)) m r %1 ->
Stream (Of a) (Stream (Of b) m) r
loop stream =
stream & \case
Return r -> Return r
Effect m -> Effect $ Control.fmap loop $ Control.lift m
Step ((a, b) :> rest) -> Step (a :> Effect (Step (b :> Return (loop rest))))
# INLINEABLE unzip #
Remarks on the design of zip functions
Zip functions have two design choices :
( 1 ) What do we do with the end - of - stream values of both streams ?
( 2 ) If the streams are of different length , do we keep or throw out the
remainder of the longer stream ?
\ * We are assuming not to take infinite streams as input and instead deal with
reasonably small finite streams .
\ * To avoid making choices for the user , we keep both end - of - stream payloads
\ * The default zips ( ones without a prime in the name ) use @effects@ to consume
the remainder stream after zipping . We include zip function variants that
return no remainder ( for equal length streams ) , or the remainder of the
longer stream .
Zip functions have two design choices:
(1) What do we do with the end-of-stream values of both streams?
(2) If the streams are of different length, do we keep or throw out the
remainder of the longer stream?
\* We are assuming not to take infinite streams as input and instead deal with
reasonably small finite streams.
\* To avoid making choices for the user, we keep both end-of-stream payloads
\* The default zips (ones without a prime in the name) use @effects@ to consume
the remainder stream after zipping. We include zip function variants that
return no remainder (for equal length streams), or the remainder of the
longer stream.
-}
data Either3 a b c where
Left3 :: a %1 -> Either3 a b c
Middle3 :: b %1 -> Either3 a b c
Right3 :: c %1 -> Either3 a b c
| The remainder of zipping two streams
type ZipResidual a b m r1 r2 =
Either3
(r1, r2)
(r1, Stream (Of b) m r2)
(Stream (Of a) m r1, r2)
| @zipWithR@ zips two streams applying a function along the way ,
keeping the remainder of zipping if there is one . Note . If two streams have
-- the same length, but one needs to perform some effects to obtain the
-- end-of-stream result, that stream is treated as a residual.
zipWithR ::
Control.Monad m =>
(a -> b -> c) ->
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of c) m (ZipResidual a b m r1 r2)
zipWithR = loop
where
loop ::
Control.Monad m =>
(a -> b -> c) ->
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of c) m (ZipResidual a b m r1 r2)
loop f st1 st2 =
st1 & \case
Effect ms -> Effect $ Control.fmap (\s -> loop f s st2) ms
Return r1 ->
st2 & \case
Return r2 -> Return $ Left3 (r1, r2)
st2' -> Return $ Middle3 (r1, st2')
Step (a :> as) ->
st2 & \case
Effect ms ->
Effect $ Control.fmap (\s -> loop f (Step (a :> as)) s) ms
Return r2 -> Return $ Right3 (Step (a :> as), r2)
Step (b :> bs) -> Step $ (f a b) :> loop f as bs
{-# INLINEABLE zipWithR #-}
zipWith ::
Control.Monad m =>
(a -> b -> c) ->
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of c) m (r1, r2)
zipWith f s1 s2 = Control.do
result <- zipWithR f s1 s2
result & \case
Left3 rets -> Control.return rets
Middle3 (r1, s2') -> Control.do
r2 <- Control.lift $ effects s2'
Control.return (r1, r2)
Right3 (s1', r2) -> Control.do
r1 <- Control.lift $ effects s1'
Control.return (r1, r2)
{-# INLINEABLE zipWith #-}
| zips two streams exhausing the remainder of the longer
-- stream and consuming its effects.
zip ::
Control.Monad m =>
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of (a, b)) m (r1, r2)
zip = zipWith (,)
# INLINE zip #
| @zipR@ zips two streams keeping the remainder if there is one .
zipR ::
Control.Monad m =>
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of (a, b)) m (ZipResidual a b m r1 r2)
zipR = zipWithR (,)
# INLINE zipR #
Remark . For simplicity , we do not create an @Either7@ which is the
-- proper remainder type for 'zip3R'. Our type simply has one impossible
case which is when all three streams have a remainder .
| The ( liberal ) remainder of zipping three streams .
This has the downside that the possibility of three remainders
-- is allowed, though it will never occur.
type ZipResidual3 a b c m r1 r2 r3 =
( Either r1 (Stream (Of a) m r1),
Either r2 (Stream (Of b) m r2),
Either r3 (Stream (Of c) m r3)
)
| Like @zipWithR@ but with three streams .
zipWith3R ::
Control.Monad m =>
(a -> b -> c -> d) ->
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of c) m r3 %1 ->
Stream (Of d) m (ZipResidual3 a b c m r1 r2 r3)
zipWith3R = loop
where
loop ::
Control.Monad m =>
(a -> b -> c -> d) ->
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of c) m r3 %1 ->
Stream (Of d) m (ZipResidual3 a b c m r1 r2 r3)
loop f s1 s2 s3 =
s1 & \case
Effect ms -> Effect $ Control.fmap (\s -> loop f s s2 s3) ms
Return r1 ->
(s2, s3) & \case
(Return r2, Return r3) -> Return (Left r1, Left r2, Left r3)
(s2', s3') -> Return (Left r1, Right s2', Right s3')
Step (a :> as) ->
s2 & \case
Effect ms ->
Effect $
Control.fmap (\s -> loop f (Step $ a :> as) s s3) ms
Return r2 -> Return (Right (Step $ a :> as), Left r2, Right s3)
Step (b :> bs) ->
s3 & \case
Effect ms ->
Effect $
Control.fmap (\s -> loop f (Step $ a :> as) (Step $ b :> bs) s) ms
Return r3 ->
Return (Right (Step $ a :> as), Right (Step $ b :> bs), Left r3)
Step (c :> cs) -> Step $ (f a b c) :> loop f as bs cs
# #
| Like but with three streams
zipWith3 ::
Control.Monad m =>
(a -> b -> c -> d) ->
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of c) m r3 %1 ->
Stream (Of d) m (r1, r2, r3)
zipWith3 f s1 s2 s3 = Control.do
result <- zipWith3R f s1 s2 s3
result & \case
(res1, res2, res3) -> Control.do
r1 <- Control.lift $ extractResult res1
r2 <- Control.lift $ extractResult res2
r3 <- Control.lift $ extractResult res3
Control.return (r1, r2, r3)
{-# INLINEABLE zipWith3 #-}
| Like but with three streams .
zip3 ::
Control.Monad m =>
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of c) m r3 %1 ->
Stream (Of (a, b, c)) m (r1, r2, r3)
zip3 = zipWith3 (,,)
# INLINEABLE zip3 #
| Like but with three streams .
zip3R ::
Control.Monad m =>
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of c) m r3 %1 ->
Stream (Of (a, b, c)) m (ZipResidual3 a b c m r1 r2 r3)
zip3R = zipWith3R (,,)
{-# INLINEABLE zip3R #-}
-- | Internal function to consume a stream remainder to
-- get the payload
extractResult :: Control.Monad m => Either r (Stream (Of a) m r) %1 -> m r
extractResult (Left r) = Control.return r
extractResult (Right s) = effects s
-- # Merging
-------------------------------------------------------------------------------
-- $merging
These functions combine two sorted streams of orderable elements
-- into one sorted stream. The elements of the merged stream are
guaranteed to be in a sorted order if the two input streams are
-- also sorted.
--
The merge operation is /left - biased/ : when merging two elements
that compare as equal , the left element is chosen first .
| Merge two streams of elements ordered with their ' Ord ' instance .
--
-- The return values of both streams are returned.
--
-- @
> S.print $ merge ( each [ 1,3,5 ] ) ( each [ 2,4 ] )
1
2
3
4
5
-- ((), ())
-- @
merge ::
(Control.Monad m, Ord a) =>
Stream (Of a) m r %1 ->
Stream (Of a) m s %1 ->
Stream (Of a) m (r, s)
merge = mergeBy compare
# INLINE merge #
| Merge two streams , ordering them by applying the given function to
-- each element before comparing.
--
-- The return values of both streams are returned.
mergeOn ::
(Control.Monad m, Ord b) =>
(a -> b) ->
Stream (Of a) m r %1 ->
Stream (Of a) m s %1 ->
Stream (Of a) m (r, s)
mergeOn f = mergeBy (\x y -> compare (f x) (f y))
# INLINE mergeOn #
| Merge two streams , ordering the elements using the given comparison function .
--
-- The return values of both streams are returned.
mergeBy ::
forall m a r s.
Control.Monad m =>
(a -> a -> Ordering) ->
Stream (Of a) m r %1 ->
Stream (Of a) m s %1 ->
Stream (Of a) m (r, s)
mergeBy comp s1 s2 = loop s1 s2
where
loop :: Stream (Of a) m r %1 -> Stream (Of a) m s %1 -> Stream (Of a) m (r, s)
loop s1 s2 =
s1 & \case
Return r ->
Effect $ effects s2 Control.>>= \s -> Control.return $ Return (r, s)
Effect ms ->
Effect $
ms Control.>>= \s1' -> Control.return $ mergeBy comp s1' s2
Step (a :> as) ->
s2 & \case
Return s ->
Effect $ effects as Control.>>= \r -> Control.return $ Return (r, s)
Effect ms ->
Effect $
ms Control.>>= \s2' ->
Control.return $ mergeBy comp (Step (a :> as)) s2'
Step (b :> bs) -> case comp a b of
LT -> Step (a :> Step (b :> mergeBy comp as bs))
_ -> Step (b :> Step (a :> mergeBy comp as bs))
{-# INLINEABLE mergeBy #-}
| null | https://raw.githubusercontent.com/tweag/linear-base/aef2124a98ecca377ad55205eb60d24a65c8910d/src/Streaming/Linear/Internal/Many.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE LinearTypes #
# OPTIONS_GHC -Wno-name-shadowing #
# OPTIONS_HADDOCK hide #
| This module contains all functions that do something with
multiple streams as input or output. This includes combining
streams, splitting a stream, etc.
* Operations that use or return multiple 'Stream's
** Merging
$
-----------------------------------------------------------------------------
| The type
> Data.List.unzip :: [(a,b)] -> ([a],[b])
might lead us to expect
> Streaming.unzip :: Stream (Of (a,b)) m r -> Stream (Of a) m (Stream (Of b) m r)
Of course, @Data.List@ 'Data.List.unzip' doesn't stream either.
This @unzip@ does
stream, though of course you can spoil this by using e.g. 'toList':
@
@
Note the difference of order in the results. It may be of some use to think why.
@
@
Like any fold, 'toList' takes no notice of the monad of effects.
In the case at hand (since I am in @ghci@) @m = Stream (Of String) IO@.
So when I apply 'toList', I exhaust that stream of integers, folding
it into a list:
@
@
and return a list of strings:
@
@
'unzip' can be considered a special case of either 'unzips' or 'expand':
@
unzip = 'unzips' . 'maps' (\((a,b) :> x) -> Compose (a :> b :> x))
@
the same length, but one needs to perform some effects to obtain the
end-of-stream result, that stream is treated as a residual.
# INLINEABLE zipWithR #
# INLINEABLE zipWith #
stream and consuming its effects.
proper remainder type for 'zip3R'. Our type simply has one impossible
is allowed, though it will never occur.
# INLINEABLE zipWith3 #
# INLINEABLE zip3R #
| Internal function to consume a stream remainder to
get the payload
# Merging
-----------------------------------------------------------------------------
$merging
into one sorted stream. The elements of the merged stream are
also sorted.
The return values of both streams are returned.
@
((), ())
@
each element before comparing.
The return values of both streams are returned.
The return values of both streams are returned.
# INLINEABLE mergeBy # | # LANGUAGE LambdaCase #
# LANGUAGE QualifiedDo #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
module Streaming.Linear.Internal.Many
* * and Unzip
unzip,
ZipResidual,
ZipResidual3,
zip,
zipR,
zipWith,
zipWithR,
zip3,
zip3R,
zipWith3,
zipWith3R,
Either3 (..),
merge,
mergeOn,
mergeBy,
)
where
import qualified Control.Functor.Linear as Control
import Prelude.Linear (($), (&))
import Streaming.Linear.Internal.Consume
import Streaming.Linear.Internal.Type
import Prelude (Either (..), Ord (..), Ordering (..))
# Zips and Unzip
which would not stream , since it would have to accumulate the second stream ( of @b@s ) .
> let ( \x - > ( x , ) ) [ 1 .. 5 : : Int ]
> S.toList $ S.toList $ S.unzip ( S.each ' xs )
[ " 1","2","3","4","5 " ] :> ( [ 1,2,3,4,5 ] :> ( ) )
> Prelude.unzip xs
( [ 1,2,3,4,5],["1","2","3","4","5 " ] )
The first application of ' toList ' was applied to a stream of integers :
> : t S.unzip $ S.each ' xs
S.unzip $ S.each ' xs : : Control . Monad m = > Stream ( Of Int ) ( Stream ( Of String ) m ) ( )
> toList : : Control . Monad m = > Stream ( Of a ) m r % 1- > m ( Of [ a ] r )
> : t S.toList $ S.unzip $ S.each ' xs
S.toList $ S.unzip $ S.each ' xs
: : Control . Monad m = > Stream ( Of String ) m ( Of [ Int ] ( ) )
When I apply ' toList ' to /this/ , I reduce everything to an ordinary action in @IO@ ,
> S.toList $ S.toList $ S.unzip ( S.each ' xs )
[ " 1","2","3","4","5 " ] :> ( [ 1,2,3,4,5 ] :> ( ) )
unzip = ' expand ' $ ( ( a , b ) :> abs ) - > b :> p ( a :> abs )
unzip ::
Control.Monad m =>
Stream (Of (a, b)) m r %1 ->
Stream (Of a) (Stream (Of b) m) r
unzip = loop
where
loop ::
Control.Monad m =>
Stream (Of (a, b)) m r %1 ->
Stream (Of a) (Stream (Of b) m) r
loop stream =
stream & \case
Return r -> Return r
Effect m -> Effect $ Control.fmap loop $ Control.lift m
Step ((a, b) :> rest) -> Step (a :> Effect (Step (b :> Return (loop rest))))
# INLINEABLE unzip #
Remarks on the design of zip functions
Zip functions have two design choices :
( 1 ) What do we do with the end - of - stream values of both streams ?
( 2 ) If the streams are of different length , do we keep or throw out the
remainder of the longer stream ?
\ * We are assuming not to take infinite streams as input and instead deal with
reasonably small finite streams .
\ * To avoid making choices for the user , we keep both end - of - stream payloads
\ * The default zips ( ones without a prime in the name ) use @effects@ to consume
the remainder stream after zipping . We include zip function variants that
return no remainder ( for equal length streams ) , or the remainder of the
longer stream .
Zip functions have two design choices:
(1) What do we do with the end-of-stream values of both streams?
(2) If the streams are of different length, do we keep or throw out the
remainder of the longer stream?
\* We are assuming not to take infinite streams as input and instead deal with
reasonably small finite streams.
\* To avoid making choices for the user, we keep both end-of-stream payloads
\* The default zips (ones without a prime in the name) use @effects@ to consume
the remainder stream after zipping. We include zip function variants that
return no remainder (for equal length streams), or the remainder of the
longer stream.
-}
data Either3 a b c where
Left3 :: a %1 -> Either3 a b c
Middle3 :: b %1 -> Either3 a b c
Right3 :: c %1 -> Either3 a b c
| The remainder of zipping two streams
type ZipResidual a b m r1 r2 =
Either3
(r1, r2)
(r1, Stream (Of b) m r2)
(Stream (Of a) m r1, r2)
| @zipWithR@ zips two streams applying a function along the way ,
keeping the remainder of zipping if there is one . Note . If two streams have
zipWithR ::
Control.Monad m =>
(a -> b -> c) ->
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of c) m (ZipResidual a b m r1 r2)
zipWithR = loop
where
loop ::
Control.Monad m =>
(a -> b -> c) ->
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of c) m (ZipResidual a b m r1 r2)
loop f st1 st2 =
st1 & \case
Effect ms -> Effect $ Control.fmap (\s -> loop f s st2) ms
Return r1 ->
st2 & \case
Return r2 -> Return $ Left3 (r1, r2)
st2' -> Return $ Middle3 (r1, st2')
Step (a :> as) ->
st2 & \case
Effect ms ->
Effect $ Control.fmap (\s -> loop f (Step (a :> as)) s) ms
Return r2 -> Return $ Right3 (Step (a :> as), r2)
Step (b :> bs) -> Step $ (f a b) :> loop f as bs
zipWith ::
Control.Monad m =>
(a -> b -> c) ->
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of c) m (r1, r2)
zipWith f s1 s2 = Control.do
result <- zipWithR f s1 s2
result & \case
Left3 rets -> Control.return rets
Middle3 (r1, s2') -> Control.do
r2 <- Control.lift $ effects s2'
Control.return (r1, r2)
Right3 (s1', r2) -> Control.do
r1 <- Control.lift $ effects s1'
Control.return (r1, r2)
| zips two streams exhausing the remainder of the longer
zip ::
Control.Monad m =>
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of (a, b)) m (r1, r2)
zip = zipWith (,)
# INLINE zip #
| @zipR@ zips two streams keeping the remainder if there is one .
zipR ::
Control.Monad m =>
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of (a, b)) m (ZipResidual a b m r1 r2)
zipR = zipWithR (,)
# INLINE zipR #
Remark . For simplicity , we do not create an @Either7@ which is the
case which is when all three streams have a remainder .
| The ( liberal ) remainder of zipping three streams .
This has the downside that the possibility of three remainders
type ZipResidual3 a b c m r1 r2 r3 =
( Either r1 (Stream (Of a) m r1),
Either r2 (Stream (Of b) m r2),
Either r3 (Stream (Of c) m r3)
)
| Like @zipWithR@ but with three streams .
zipWith3R ::
Control.Monad m =>
(a -> b -> c -> d) ->
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of c) m r3 %1 ->
Stream (Of d) m (ZipResidual3 a b c m r1 r2 r3)
zipWith3R = loop
where
loop ::
Control.Monad m =>
(a -> b -> c -> d) ->
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of c) m r3 %1 ->
Stream (Of d) m (ZipResidual3 a b c m r1 r2 r3)
loop f s1 s2 s3 =
s1 & \case
Effect ms -> Effect $ Control.fmap (\s -> loop f s s2 s3) ms
Return r1 ->
(s2, s3) & \case
(Return r2, Return r3) -> Return (Left r1, Left r2, Left r3)
(s2', s3') -> Return (Left r1, Right s2', Right s3')
Step (a :> as) ->
s2 & \case
Effect ms ->
Effect $
Control.fmap (\s -> loop f (Step $ a :> as) s s3) ms
Return r2 -> Return (Right (Step $ a :> as), Left r2, Right s3)
Step (b :> bs) ->
s3 & \case
Effect ms ->
Effect $
Control.fmap (\s -> loop f (Step $ a :> as) (Step $ b :> bs) s) ms
Return r3 ->
Return (Right (Step $ a :> as), Right (Step $ b :> bs), Left r3)
Step (c :> cs) -> Step $ (f a b c) :> loop f as bs cs
# #
| Like but with three streams
zipWith3 ::
Control.Monad m =>
(a -> b -> c -> d) ->
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of c) m r3 %1 ->
Stream (Of d) m (r1, r2, r3)
zipWith3 f s1 s2 s3 = Control.do
result <- zipWith3R f s1 s2 s3
result & \case
(res1, res2, res3) -> Control.do
r1 <- Control.lift $ extractResult res1
r2 <- Control.lift $ extractResult res2
r3 <- Control.lift $ extractResult res3
Control.return (r1, r2, r3)
| Like but with three streams .
zip3 ::
Control.Monad m =>
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of c) m r3 %1 ->
Stream (Of (a, b, c)) m (r1, r2, r3)
zip3 = zipWith3 (,,)
# INLINEABLE zip3 #
| Like but with three streams .
zip3R ::
Control.Monad m =>
Stream (Of a) m r1 %1 ->
Stream (Of b) m r2 %1 ->
Stream (Of c) m r3 %1 ->
Stream (Of (a, b, c)) m (ZipResidual3 a b c m r1 r2 r3)
zip3R = zipWith3R (,,)
extractResult :: Control.Monad m => Either r (Stream (Of a) m r) %1 -> m r
extractResult (Left r) = Control.return r
extractResult (Right s) = effects s
These functions combine two sorted streams of orderable elements
guaranteed to be in a sorted order if the two input streams are
The merge operation is /left - biased/ : when merging two elements
that compare as equal , the left element is chosen first .
| Merge two streams of elements ordered with their ' Ord ' instance .
> S.print $ merge ( each [ 1,3,5 ] ) ( each [ 2,4 ] )
1
2
3
4
5
merge ::
(Control.Monad m, Ord a) =>
Stream (Of a) m r %1 ->
Stream (Of a) m s %1 ->
Stream (Of a) m (r, s)
merge = mergeBy compare
# INLINE merge #
| Merge two streams , ordering them by applying the given function to
mergeOn ::
(Control.Monad m, Ord b) =>
(a -> b) ->
Stream (Of a) m r %1 ->
Stream (Of a) m s %1 ->
Stream (Of a) m (r, s)
mergeOn f = mergeBy (\x y -> compare (f x) (f y))
# INLINE mergeOn #
| Merge two streams , ordering the elements using the given comparison function .
mergeBy ::
forall m a r s.
Control.Monad m =>
(a -> a -> Ordering) ->
Stream (Of a) m r %1 ->
Stream (Of a) m s %1 ->
Stream (Of a) m (r, s)
mergeBy comp s1 s2 = loop s1 s2
where
loop :: Stream (Of a) m r %1 -> Stream (Of a) m s %1 -> Stream (Of a) m (r, s)
loop s1 s2 =
s1 & \case
Return r ->
Effect $ effects s2 Control.>>= \s -> Control.return $ Return (r, s)
Effect ms ->
Effect $
ms Control.>>= \s1' -> Control.return $ mergeBy comp s1' s2
Step (a :> as) ->
s2 & \case
Return s ->
Effect $ effects as Control.>>= \r -> Control.return $ Return (r, s)
Effect ms ->
Effect $
ms Control.>>= \s2' ->
Control.return $ mergeBy comp (Step (a :> as)) s2'
Step (b :> bs) -> case comp a b of
LT -> Step (a :> Step (b :> mergeBy comp as bs))
_ -> Step (b :> Step (a :> mergeBy comp as bs))
|
936f76ef087b980e55f1bdd5fcb3766dec513603366830cf6bb76c9fced0065d | googleson78/fp-lab-2022-23 | Solutions.hs | -- cover all cases!
# OPTIONS_GHC -fwarn - incomplete - patterns #
-- warn about incomplete patterns v2
# OPTIONS_GHC -fwarn - incomplete - uni - patterns #
-- write all your toplevel signatures!
# OPTIONS_GHC -fwarn - missing - signatures #
-- use different names!
{-# OPTIONS_GHC -fwarn-name-shadowing #-}
-- use all your pattern matches!
# OPTIONS_GHC -fwarn - unused - matches #
module Solutions where
import Data.Maybe (fromMaybe)
import Debug.Trace
import Prelude hiding (cycle, foldl, repeat, scanl)
-- hof: -12-01-higherorderness-is-interaction/
f(1,2,3 )
> x = 3 + 5
> y = 4 + x
> z = y = = 3
-- z
-- False
f ( 2 + 3 ) ( 4 + 5 ) ( 6 + 7 )
-- thunk -- delayed computation, replaced when done
: print , : sprint -- do n't forget type annos -- sometimes unreliable , different results between ghc versions
data Nat = Zero | Suc Nat
deriving (Show)
evaluate to WHNF
-- weak head normal form
isZero :: Nat -> Bool
isZero Zero = True
isZero (Suc _) = False
x : :
x = Zero
--
y : :
y = Suc ( Suc Zero )
-- Nat, isZero, some tuple stuff?
-- when do we "need" to evalute something? case matches!
-- how much do we need to evaluate it? WHNF
-- infinite structures
-- data Stream a = Cons a (Stream a)
-- Stream, but we will use [] with asserts*
-- show take def?
-- take :: Int -> [a] -> [a]
-- take 0 _ = []
-- take _ [] = []
-- take n (x : xs) = x : take (n - 1) xs
addNat :: Nat -> Nat -> Nat
addNat Zero m = m
addNat (Suc n) m = Suc $ addNat n m
foldl :: (b -> a -> b) -> b -> [a] -> b
foldl _ acc [] = acc
foldl f acc (x : xs) = foldl f (f acc x) xs
-- bla :: [Nat] -> Nat
bla = foldl addNat Zero
--
-- ones :: [Nat]
ones = Suc Zero : ones
-- seq :: a -> b -> b
-- seq x y
( seq x 5 )
foldl' :: (b -> a -> b) -> b -> [a] -> b
foldl' _ acc [] = acc
foldl' f acc (x : xs) =
seq (f acc x) (foldl' f (f acc x) xs)
WHNF
boo :: [(Int, Int)] -> (Int, Int)
boo = foldl' go (0, 0)
where
go (accx, accy) (x, y) =
(accx + x, accy + y)
-- (<голяма сметка>, <голяма сметка2>)
deepseq
-- foldl - не
import Data . List ( foldl ' )
-- foldl' - да
-- foldr, foldl, stack space
-- seq a b - "evaluate a and b together" - no enforced order, but usually used to mean a before b
-- seq a b terminates iff a terminates
-- very detailed SO answer describing seq in more detail:
-- A note on evaluation order: the expression seq a b does not guarantee that a will be evaluated before b.
-- The only guarantee given by seq is that the both a and b will be evaluated before seq returns a value.
-- In particular, this means that b may be evaluated before a.
--
-- foldl'
mention
-- EXERCISE
-- Infinitely repeat a value
> > > take 4 $ repeat ' a '
-- "aaaa"
repeat :: a -> [a]
repeat x = x : repeat x
-- EXERCISE
-- A list of all the natural numbers.
-- EXAMPLES
> > > take 10 nats
-- [0,1,2,3,4,5,6,7,8,9]
nats :: [Integer]
nats = 0 : map succ nats
-- EXERCISE
-- Generate an infinite list of numbers, starting with the given number, with the given interval between each numbe.
-- EXAMPLES
> > > take 10 $ fromThen 0 1
-- [0,1,2,3,4,5,6,7,8,9]
> > > take 20 $ fromThen 0 1
-- [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
> > > take 10 $ fromThen 4 9
[ 4,13,22,31,40,49,58,67,76,85 ]
> > > take 10 $ fromThen 0 ( -10 )
[ 0,-10,-20,-30,-40,-50,-60,-70,-80,-90 ]
fromThen :: Integer -> Integer -> [Integer]
fromThen start end = start : fromThen (start + end) end
-- EXERCISE
-- Implement a list of all the factorial numbers
-- Use a where or let to "cache" the current number, so we don't do all the multiplications every time.
i.e. if we 've already calculated 5 ! , we can simply multiply the result by 6 , we do n't need to calculate 5 ! again .
-- EXAMPLES
> > > take 10 facts
[ 1,1,2,6,24,120,720,5040,40320,362880 ]
facts :: [Integer]
facts = go 0 1
where
invariant : acc is always the factorial of n
go n acc = acc : go (succ n) (acc * succ n)
-- EXERCISE
-- "Caching foldl"
-- It's sometimes useful to have all the "intermediate" results of a fold. It's also helpful for debugging sometimes.
-- Intermediate meaning that we're interested in all the values the accumulator of the foldl goes through.
--
-- Implement a version of foldl that returns all of the intermediate results it has.
These are called " scans " in the standard library .
-- EXAMPLES
> > > ( + ) 0 [ 1 .. 10 ]
-- [0,1,3,6,10,15,21,28,36,45,55]
scanl :: (b -> a -> b) -> b -> [a] -> [b]
scanl _ acc [] = [acc]
scanl f acc (x : xs) = acc : scanl f (f acc x) xs
-- EXERCISE
Use to implement facts .
-- EXAMPLES
> > > take 10 factsScanl
-- [1,1,2,6,24,120,720,5040,40320,362880,3628800]
factsScanl :: [Integer]
factsScanl = scanl (*) 1 (drop 1 nats)
-- EXERCISE
-- Implement a list of all the fibonacci numbers.
-- Use the following idea:
The fibonacci numbers start with 0 1
To generate the next fibonacci number , we need to sum the previous two , so assuming we already have
fibs : : [ Integer ]
that would mean summing the head of fibs with the head of the tail of fibs
-- zipWith will be useful here.
-- EXAMPLES
> > > take 10 fibs
[ 0,1,1,2,3,5,8,13,21,34 ]
fibs :: [Integer]
fibs = 0 : 1 : zipWith (+) fibs (drop 1 fibs)
-- EXERCISE
-- Idea:
-- We can get the all the primes with the following algorithm.
Let 's start with all the numbers > = 2
The current number - call it x - is prime ( this is true in the beginning - x = 2 is prime ) - leave it in our list
-- All of the other numbers that are divisible by x aren't prime - filter them out
This is called the sieve of Eratosthenes
-- Implement this for a given input list
Now all we need to do is apply it to all the natural numbers > = 2 to get a list of all the primes .
-- EXAMPLES
> > > take 10 $ primes
[ 2,3,5,7,11,13,17,19,23,29 ]
> > > take 20 $ primes
[ 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71 ]
primes :: [Integer]
primes = eratosthenes $ drop 2 nats
where
eratosthenes :: [Integer] -> [Integer]
eratosthenes [] = error "assert: expected infinite list"
eratosthenes (x : xs) = x : eratosthenes (filter (not . divides x) xs)
divides x y = y `rem` x == 0
-- EXERCISE
-- Infinitely repeat a list
> > > take 7 $ cycle [ 1,2,3 ]
-- [1,2,3,1,2,3,1]
cycle :: [a] -> [a]
cycle xs = xs ++ cycle xs
-- Let's consider the following problem:
-- We have a "circle" of n people. We have an integer k.
We repeat the following procedure , starting from the first person , until there is only one left :
--
" Kill " the person . Repeat this , " starting " from the k+1th person , i.e. we start indexing from the k+1th person .
--
Example execution for n = 5 , k = 2 :
-- 1 2 3 4 5 (start)
1 2 4 5 ( we kill 3 , since 0 + 2 = 2 )
2 4 5 ( we kill 1 , since 4 + 2 = 6 , circling back to 1 )
2 4
4
--
The question is , given an n and k , what 's the number of the final person left . ( 4 in the example above )
--
-- This is called the josephus problem. See #History for some flavour.
--
Your task is to implement : : Integer - > Int - > Integer
-- which takes n and k, and returns the last surviving person.
--
-- Your hint is to use `cycle` to express our circle, and then to drop and filter things from it.
E.g. the representation of our circle for n = 5 would be [ 0,1,2,3,4,0,1,2,3,4,0,1,2,3,4 ... ]
-- EXAMPLES
> > > jos 5 2
4
-- >>> jos 10 4
3
-- >>> jos 10 8
7
> > > map ( \(x , y ) - > ( x , y , y ) ) [ ( x , y ) | x < - [ 2 .. 5 ] , y < - [ 2 .. 5 ] ]
[ ( 2,2,2),(2,3,1),(2,4,2),(2,5,1),(3,2,2),(3,3,2),(3,4,1),(3,5,1),(4,2,1),(4,3,2),(4,4,2),(4,5,3),(5,2,4),(5,3,1),(5,4,2),(5,5,4 ) ]
jos :: Integer -> Int -> Integer
jos n k = untilJust sameFirstTwo go circle
where
-- figure out what this function should do based only on the types and the name
-- ask me if you're confused
--
fromMaybe is from Data . Maybe
untilJust :: (a -> Maybe b) -> (a -> a) -> a -> b
untilJust g f x =
fromMaybe (untilJust g f (f x)) $ g x
-- our infinite circle
circle :: [Integer]
circle = cycle [1 .. n]
-- the procedure which actually does the removal
go :: [Integer] -> [Integer]
go start =
case drop k start of
(x : xs) -> filter (/= x) xs
[] -> error "assert: jos.go expects an infinite list"
sameFirstTwo (x : y : _) | x == y = Just x
sameFirstTwo _ = Nothing
| null | https://raw.githubusercontent.com/googleson78/fp-lab-2022-23/a023f5c9cad9686f3dbd224faf0a3796dfcf376d/exercises/08/Solutions.hs | haskell | cover all cases!
warn about incomplete patterns v2
write all your toplevel signatures!
use different names!
# OPTIONS_GHC -fwarn-name-shadowing #
use all your pattern matches!
hof: -12-01-higherorderness-is-interaction/
z
False
thunk -- delayed computation, replaced when done
do n't forget type annos -- sometimes unreliable , different results between ghc versions
weak head normal form
Nat, isZero, some tuple stuff?
when do we "need" to evalute something? case matches!
how much do we need to evaluate it? WHNF
infinite structures
data Stream a = Cons a (Stream a)
Stream, but we will use [] with asserts*
show take def?
take :: Int -> [a] -> [a]
take 0 _ = []
take _ [] = []
take n (x : xs) = x : take (n - 1) xs
bla :: [Nat] -> Nat
ones :: [Nat]
seq :: a -> b -> b
seq x y
(<голяма сметка>, <голяма сметка2>)
foldl - не
foldl' - да
foldr, foldl, stack space
seq a b - "evaluate a and b together" - no enforced order, but usually used to mean a before b
seq a b terminates iff a terminates
very detailed SO answer describing seq in more detail:
A note on evaluation order: the expression seq a b does not guarantee that a will be evaluated before b.
The only guarantee given by seq is that the both a and b will be evaluated before seq returns a value.
In particular, this means that b may be evaluated before a.
foldl'
EXERCISE
Infinitely repeat a value
"aaaa"
EXERCISE
A list of all the natural numbers.
EXAMPLES
[0,1,2,3,4,5,6,7,8,9]
EXERCISE
Generate an infinite list of numbers, starting with the given number, with the given interval between each numbe.
EXAMPLES
[0,1,2,3,4,5,6,7,8,9]
[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
EXERCISE
Implement a list of all the factorial numbers
Use a where or let to "cache" the current number, so we don't do all the multiplications every time.
EXAMPLES
EXERCISE
"Caching foldl"
It's sometimes useful to have all the "intermediate" results of a fold. It's also helpful for debugging sometimes.
Intermediate meaning that we're interested in all the values the accumulator of the foldl goes through.
Implement a version of foldl that returns all of the intermediate results it has.
EXAMPLES
[0,1,3,6,10,15,21,28,36,45,55]
EXERCISE
EXAMPLES
[1,1,2,6,24,120,720,5040,40320,362880,3628800]
EXERCISE
Implement a list of all the fibonacci numbers.
Use the following idea:
zipWith will be useful here.
EXAMPLES
EXERCISE
Idea:
We can get the all the primes with the following algorithm.
All of the other numbers that are divisible by x aren't prime - filter them out
Implement this for a given input list
EXAMPLES
EXERCISE
Infinitely repeat a list
[1,2,3,1,2,3,1]
Let's consider the following problem:
We have a "circle" of n people. We have an integer k.
1 2 3 4 5 (start)
This is called the josephus problem. See #History for some flavour.
which takes n and k, and returns the last surviving person.
Your hint is to use `cycle` to express our circle, and then to drop and filter things from it.
EXAMPLES
>>> jos 10 4
>>> jos 10 8
figure out what this function should do based only on the types and the name
ask me if you're confused
our infinite circle
the procedure which actually does the removal | # OPTIONS_GHC -fwarn - incomplete - patterns #
# OPTIONS_GHC -fwarn - incomplete - uni - patterns #
# OPTIONS_GHC -fwarn - missing - signatures #
# OPTIONS_GHC -fwarn - unused - matches #
module Solutions where
import Data.Maybe (fromMaybe)
import Debug.Trace
import Prelude hiding (cycle, foldl, repeat, scanl)
f(1,2,3 )
> x = 3 + 5
> y = 4 + x
> z = y = = 3
f ( 2 + 3 ) ( 4 + 5 ) ( 6 + 7 )
data Nat = Zero | Suc Nat
deriving (Show)
evaluate to WHNF
isZero :: Nat -> Bool
isZero Zero = True
isZero (Suc _) = False
x : :
x = Zero
y : :
y = Suc ( Suc Zero )
addNat :: Nat -> Nat -> Nat
addNat Zero m = m
addNat (Suc n) m = Suc $ addNat n m
foldl :: (b -> a -> b) -> b -> [a] -> b
foldl _ acc [] = acc
foldl f acc (x : xs) = foldl f (f acc x) xs
bla = foldl addNat Zero
ones = Suc Zero : ones
( seq x 5 )
foldl' :: (b -> a -> b) -> b -> [a] -> b
foldl' _ acc [] = acc
foldl' f acc (x : xs) =
seq (f acc x) (foldl' f (f acc x) xs)
WHNF
boo :: [(Int, Int)] -> (Int, Int)
boo = foldl' go (0, 0)
where
go (accx, accy) (x, y) =
(accx + x, accy + y)
deepseq
import Data . List ( foldl ' )
mention
> > > take 4 $ repeat ' a '
repeat :: a -> [a]
repeat x = x : repeat x
> > > take 10 nats
nats :: [Integer]
nats = 0 : map succ nats
> > > take 10 $ fromThen 0 1
> > > take 20 $ fromThen 0 1
> > > take 10 $ fromThen 4 9
[ 4,13,22,31,40,49,58,67,76,85 ]
> > > take 10 $ fromThen 0 ( -10 )
[ 0,-10,-20,-30,-40,-50,-60,-70,-80,-90 ]
fromThen :: Integer -> Integer -> [Integer]
fromThen start end = start : fromThen (start + end) end
i.e. if we 've already calculated 5 ! , we can simply multiply the result by 6 , we do n't need to calculate 5 ! again .
> > > take 10 facts
[ 1,1,2,6,24,120,720,5040,40320,362880 ]
facts :: [Integer]
facts = go 0 1
where
invariant : acc is always the factorial of n
go n acc = acc : go (succ n) (acc * succ n)
These are called " scans " in the standard library .
> > > ( + ) 0 [ 1 .. 10 ]
scanl :: (b -> a -> b) -> b -> [a] -> [b]
scanl _ acc [] = [acc]
scanl f acc (x : xs) = acc : scanl f (f acc x) xs
Use to implement facts .
> > > take 10 factsScanl
factsScanl :: [Integer]
factsScanl = scanl (*) 1 (drop 1 nats)
The fibonacci numbers start with 0 1
To generate the next fibonacci number , we need to sum the previous two , so assuming we already have
fibs : : [ Integer ]
that would mean summing the head of fibs with the head of the tail of fibs
> > > take 10 fibs
[ 0,1,1,2,3,5,8,13,21,34 ]
fibs :: [Integer]
fibs = 0 : 1 : zipWith (+) fibs (drop 1 fibs)
Let 's start with all the numbers > = 2
The current number - call it x - is prime ( this is true in the beginning - x = 2 is prime ) - leave it in our list
This is called the sieve of Eratosthenes
Now all we need to do is apply it to all the natural numbers > = 2 to get a list of all the primes .
> > > take 10 $ primes
[ 2,3,5,7,11,13,17,19,23,29 ]
> > > take 20 $ primes
[ 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71 ]
primes :: [Integer]
primes = eratosthenes $ drop 2 nats
where
eratosthenes :: [Integer] -> [Integer]
eratosthenes [] = error "assert: expected infinite list"
eratosthenes (x : xs) = x : eratosthenes (filter (not . divides x) xs)
divides x y = y `rem` x == 0
> > > take 7 $ cycle [ 1,2,3 ]
cycle :: [a] -> [a]
cycle xs = xs ++ cycle xs
We repeat the following procedure , starting from the first person , until there is only one left :
" Kill " the person . Repeat this , " starting " from the k+1th person , i.e. we start indexing from the k+1th person .
Example execution for n = 5 , k = 2 :
1 2 4 5 ( we kill 3 , since 0 + 2 = 2 )
2 4 5 ( we kill 1 , since 4 + 2 = 6 , circling back to 1 )
2 4
4
The question is , given an n and k , what 's the number of the final person left . ( 4 in the example above )
Your task is to implement : : Integer - > Int - > Integer
E.g. the representation of our circle for n = 5 would be [ 0,1,2,3,4,0,1,2,3,4,0,1,2,3,4 ... ]
> > > jos 5 2
4
3
7
> > > map ( \(x , y ) - > ( x , y , y ) ) [ ( x , y ) | x < - [ 2 .. 5 ] , y < - [ 2 .. 5 ] ]
[ ( 2,2,2),(2,3,1),(2,4,2),(2,5,1),(3,2,2),(3,3,2),(3,4,1),(3,5,1),(4,2,1),(4,3,2),(4,4,2),(4,5,3),(5,2,4),(5,3,1),(5,4,2),(5,5,4 ) ]
jos :: Integer -> Int -> Integer
jos n k = untilJust sameFirstTwo go circle
where
fromMaybe is from Data . Maybe
untilJust :: (a -> Maybe b) -> (a -> a) -> a -> b
untilJust g f x =
fromMaybe (untilJust g f (f x)) $ g x
circle :: [Integer]
circle = cycle [1 .. n]
go :: [Integer] -> [Integer]
go start =
case drop k start of
(x : xs) -> filter (/= x) xs
[] -> error "assert: jos.go expects an infinite list"
sameFirstTwo (x : y : _) | x == y = Just x
sameFirstTwo _ = Nothing
|
743a97c80f726b0466ad236f6675792599747ca281e85a563cb94b822564050e | casperschipper/ocaml-cisp | sndfiletest.ml | open Process
reading the first channel of an audio file
let _ =
(* replace with another audio file *)
let snd = Sndfile.read "/Users/casperschipper/Downloads/tmp/applaud.wav" in
let sndproc = Sndfile.toProc snd 0 in
let filtered = bhpf_static 1350. 1. sndproc *~ ~.0.3 in
Jack.playSeqs
| null | https://raw.githubusercontent.com/casperschipper/ocaml-cisp/571ffb8e508c5427d01e407ba5e91ff2a4604f40/examples/sndfiletest.ml | ocaml | replace with another audio file | open Process
reading the first channel of an audio file
let _ =
let snd = Sndfile.read "/Users/casperschipper/Downloads/tmp/applaud.wav" in
let sndproc = Sndfile.toProc snd 0 in
let filtered = bhpf_static 1350. 1. sndproc *~ ~.0.3 in
Jack.playSeqs
|
d3c6ff889ec9578fc0fbce3a6a68f8f87f7d1df7758f59f01cf0c24dd91edde7 | josefs/Gradualizer | constraints.erl | @private
-module(constraints).
-export([empty/0,
vars/1,
upper/2,
lower/2,
combine/1, combine/2,
combine_with/4,
add_var/2,
solve/3,
append_values/3,
has_upper_bound/2]).
-export_type([t/0,
mapset/1,
var/0]).
-include_lib("stdlib/include/assert.hrl").
-type type() :: gradualizer_type:abstract_type().
-include("constraints.hrl").
-type t() :: #constraints{}.
-type mapset(T) :: #{T => true}.
-type var() :: gradualizer_type:gr_type_var().
-spec empty() -> t().
empty() ->
#constraints{}.
-spec vars(mapset(var())) -> #constraints{}.
vars(Vars) ->
#constraints{ exist_vars = Vars }.
-spec add_var(var(), t()) -> t().
add_var(Var, Cs) ->
Cs#constraints{ exist_vars = maps:put(Var, true, Cs#constraints.exist_vars) }.
-spec upper(var(), type()) -> t().
upper(Var, Ty) ->
#constraints{ upper_bounds = #{ Var => [Ty] } }.
-spec lower(var(), type()) -> t().
lower(Var, Ty) ->
#constraints{ lower_bounds = #{ Var => [Ty] } }.
-spec combine(t(), t()) -> t().
combine(C1, C2) ->
combine([C1, C2]).
-spec combine([t()]) -> t().
combine([]) ->
empty();
combine([Cs]) ->
Cs;
combine([C1, C2 | Cs]) ->
C = combine_with(C1, C2, fun append_values/3, fun append_values/3),
combine([C | Cs]).
-spec combine_with(t(), t(), BoundsMergeF, BoundsMergeF) -> t() when
BoundsMergeF :: fun((var(), [type()], [type()]) -> [type()]).
combine_with(C1, C2, MergeLBounds, MergeUBounds) ->
LBounds = gradualizer_lib:merge_with(MergeLBounds,
C1#constraints.lower_bounds,
C2#constraints.lower_bounds),
UBounds = gradualizer_lib:merge_with(MergeUBounds,
C1#constraints.upper_bounds,
C2#constraints.upper_bounds),
EVars = maps:merge(C1#constraints.exist_vars, C2#constraints.exist_vars),
#constraints{lower_bounds = LBounds,
upper_bounds = UBounds,
exist_vars = EVars}.
-spec solve(t(), erl_anno:anno(), typechecker:env()) -> R when
R :: {t(), {#{var() => type()}, #{var() => type()}}}.
solve(Constraints, Anno, Env) ->
ElimVars = Constraints#constraints.exist_vars,
WorkList = [ {E, LB, UB} || E <- lists:sort(maps:keys(ElimVars)),
LB <- maps:get(E, Constraints#constraints.lower_bounds, []),
UB <- maps:get(E, Constraints#constraints.upper_bounds, []) ],
Cs = solve_loop(WorkList, maps:new(), Constraints, ElimVars, Anno, Env),
GlbSubs = fun(_Var, Tys) ->
{Ty, _C} = typechecker:glb(Tys, Env),
% TODO: Don't throw away the constraints
Ty
end,
LubSubs = fun(_Var, Tys) ->
Ty = typechecker:lub(Tys, Env),
Ty
end,
% TODO: What if the substition contains occurrences of the variables we're eliminating
% in the range of the substitution?
Subst = { maps:map(GlbSubs, maps:with(maps:keys(ElimVars), Cs#constraints.upper_bounds)),
maps:map(LubSubs, maps:with(maps:keys(ElimVars), Cs#constraints.lower_bounds)) },
UBounds = maps:without(maps:keys(ElimVars), Cs#constraints.upper_bounds),
LBounds = maps:without(maps:keys(ElimVars), Cs#constraints.lower_bounds),
C = #constraints{upper_bounds = UBounds,
lower_bounds = LBounds,
exist_vars = maps:new()},
{C, Subst}.
solve_loop([], _, Constraints, _, _, _) ->
Constraints;
solve_loop([I = {E, LB, UB} | WL], Seen, Constraints0, ElimVars, Anno, Env) ->
case maps:is_key(I, Seen) of
true ->
solve_loop(WL, Seen, Constraints0, ElimVars, Anno, Env);
false ->
Constraints1 = case typechecker:subtype(LB, UB, Env) of
false ->
throw({constraint_error, Anno, E, LB, UB});
{true, Cs} ->
Cs
end,
% Subtyping should not create new existential variables
?assert(Constraints1#constraints.exist_vars == #{}),
ELowerBounds = maps:with(maps:keys(ElimVars), Constraints1#constraints.lower_bounds),
EUpperBounds = maps:with(maps:keys(ElimVars), Constraints1#constraints.upper_bounds),
LBounds = gradualizer_lib:merge_with(fun append_values/3,
Constraints0#constraints.lower_bounds,
Constraints1#constraints.lower_bounds),
UBounds = gradualizer_lib:merge_with(fun append_values/3,
Constraints0#constraints.upper_bounds,
Constraints1#constraints.upper_bounds),
Constraints2 = #constraints{lower_bounds = LBounds,
upper_bounds = UBounds},
NewWL = ([ {EVar, Lower, Upper}
|| {EVar, Lowers} <- maps:to_list(ELowerBounds),
Lower <- Lowers,
Upper <- maps:get(EVar, Constraints2#constraints.upper_bounds, []) ] ++
[ {EVar, Lower, Upper}
|| {EVar, Uppers} <- maps:to_list(EUpperBounds),
Upper <- Uppers,
Lower <- maps:get(EVar, Constraints2#constraints.lower_bounds, []) ] ++
WL),
solve_loop(NewWL, maps:put(I, true, Seen), Constraints2, ElimVars, Anno, Env)
end.
append_values(_, Xs, Ys) ->
Xs ++ Ys.
has_upper_bound(Var, Cs) ->
maps:is_key(Var, Cs#constraints.upper_bounds).
| null | https://raw.githubusercontent.com/josefs/Gradualizer/d09a29a143b22b94de8892e6a0d8cc94df40cdb4/src/constraints.erl | erlang | TODO: Don't throw away the constraints
TODO: What if the substition contains occurrences of the variables we're eliminating
in the range of the substitution?
Subtyping should not create new existential variables | @private
-module(constraints).
-export([empty/0,
vars/1,
upper/2,
lower/2,
combine/1, combine/2,
combine_with/4,
add_var/2,
solve/3,
append_values/3,
has_upper_bound/2]).
-export_type([t/0,
mapset/1,
var/0]).
-include_lib("stdlib/include/assert.hrl").
-type type() :: gradualizer_type:abstract_type().
-include("constraints.hrl").
-type t() :: #constraints{}.
-type mapset(T) :: #{T => true}.
-type var() :: gradualizer_type:gr_type_var().
-spec empty() -> t().
empty() ->
#constraints{}.
-spec vars(mapset(var())) -> #constraints{}.
vars(Vars) ->
#constraints{ exist_vars = Vars }.
-spec add_var(var(), t()) -> t().
add_var(Var, Cs) ->
Cs#constraints{ exist_vars = maps:put(Var, true, Cs#constraints.exist_vars) }.
-spec upper(var(), type()) -> t().
upper(Var, Ty) ->
#constraints{ upper_bounds = #{ Var => [Ty] } }.
-spec lower(var(), type()) -> t().
lower(Var, Ty) ->
#constraints{ lower_bounds = #{ Var => [Ty] } }.
-spec combine(t(), t()) -> t().
combine(C1, C2) ->
combine([C1, C2]).
-spec combine([t()]) -> t().
combine([]) ->
empty();
combine([Cs]) ->
Cs;
combine([C1, C2 | Cs]) ->
C = combine_with(C1, C2, fun append_values/3, fun append_values/3),
combine([C | Cs]).
-spec combine_with(t(), t(), BoundsMergeF, BoundsMergeF) -> t() when
BoundsMergeF :: fun((var(), [type()], [type()]) -> [type()]).
combine_with(C1, C2, MergeLBounds, MergeUBounds) ->
LBounds = gradualizer_lib:merge_with(MergeLBounds,
C1#constraints.lower_bounds,
C2#constraints.lower_bounds),
UBounds = gradualizer_lib:merge_with(MergeUBounds,
C1#constraints.upper_bounds,
C2#constraints.upper_bounds),
EVars = maps:merge(C1#constraints.exist_vars, C2#constraints.exist_vars),
#constraints{lower_bounds = LBounds,
upper_bounds = UBounds,
exist_vars = EVars}.
-spec solve(t(), erl_anno:anno(), typechecker:env()) -> R when
R :: {t(), {#{var() => type()}, #{var() => type()}}}.
solve(Constraints, Anno, Env) ->
ElimVars = Constraints#constraints.exist_vars,
WorkList = [ {E, LB, UB} || E <- lists:sort(maps:keys(ElimVars)),
LB <- maps:get(E, Constraints#constraints.lower_bounds, []),
UB <- maps:get(E, Constraints#constraints.upper_bounds, []) ],
Cs = solve_loop(WorkList, maps:new(), Constraints, ElimVars, Anno, Env),
GlbSubs = fun(_Var, Tys) ->
{Ty, _C} = typechecker:glb(Tys, Env),
Ty
end,
LubSubs = fun(_Var, Tys) ->
Ty = typechecker:lub(Tys, Env),
Ty
end,
Subst = { maps:map(GlbSubs, maps:with(maps:keys(ElimVars), Cs#constraints.upper_bounds)),
maps:map(LubSubs, maps:with(maps:keys(ElimVars), Cs#constraints.lower_bounds)) },
UBounds = maps:without(maps:keys(ElimVars), Cs#constraints.upper_bounds),
LBounds = maps:without(maps:keys(ElimVars), Cs#constraints.lower_bounds),
C = #constraints{upper_bounds = UBounds,
lower_bounds = LBounds,
exist_vars = maps:new()},
{C, Subst}.
solve_loop([], _, Constraints, _, _, _) ->
Constraints;
solve_loop([I = {E, LB, UB} | WL], Seen, Constraints0, ElimVars, Anno, Env) ->
case maps:is_key(I, Seen) of
true ->
solve_loop(WL, Seen, Constraints0, ElimVars, Anno, Env);
false ->
Constraints1 = case typechecker:subtype(LB, UB, Env) of
false ->
throw({constraint_error, Anno, E, LB, UB});
{true, Cs} ->
Cs
end,
?assert(Constraints1#constraints.exist_vars == #{}),
ELowerBounds = maps:with(maps:keys(ElimVars), Constraints1#constraints.lower_bounds),
EUpperBounds = maps:with(maps:keys(ElimVars), Constraints1#constraints.upper_bounds),
LBounds = gradualizer_lib:merge_with(fun append_values/3,
Constraints0#constraints.lower_bounds,
Constraints1#constraints.lower_bounds),
UBounds = gradualizer_lib:merge_with(fun append_values/3,
Constraints0#constraints.upper_bounds,
Constraints1#constraints.upper_bounds),
Constraints2 = #constraints{lower_bounds = LBounds,
upper_bounds = UBounds},
NewWL = ([ {EVar, Lower, Upper}
|| {EVar, Lowers} <- maps:to_list(ELowerBounds),
Lower <- Lowers,
Upper <- maps:get(EVar, Constraints2#constraints.upper_bounds, []) ] ++
[ {EVar, Lower, Upper}
|| {EVar, Uppers} <- maps:to_list(EUpperBounds),
Upper <- Uppers,
Lower <- maps:get(EVar, Constraints2#constraints.lower_bounds, []) ] ++
WL),
solve_loop(NewWL, maps:put(I, true, Seen), Constraints2, ElimVars, Anno, Env)
end.
append_values(_, Xs, Ys) ->
Xs ++ Ys.
has_upper_bound(Var, Cs) ->
maps:is_key(Var, Cs#constraints.upper_bounds).
|
ad0f4992d49866e8239d7dc97da640e72a4e0c54d68db91b2c367ff0cf9efb43 | lehins/primal | StablePtr.hs | # LANGUAGE FlexibleContexts #
# OPTIONS_GHC -fno - warn - orphans #
-- |
-- Module : Primal.Foreign.StablePtr
Copyright : ( c ) 2020 - 2022
-- License : BSD3
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable
--
module Primal.Foreign.StablePtr
( GHC.StablePtr(..)
, newStablePtr
, deRefStablePtr
, freeStablePtr
, GHC.castStablePtrToPtr
, GHC.castPtrToStablePtr
) where
import Control.DeepSeq
import Primal.Monad
import qualified GHC.Stable as GHC
-- | Orphan in @primal@
instance NFData (GHC.StablePtr a) where
rnf (GHC.StablePtr _) = ()
-- | Orphan in @primal@
instance Show (GHC.StablePtr a) where
show = show . GHC.castStablePtrToPtr
| Same as ` GHC.newStablePtr ` , but generalized to ` Primal `
newStablePtr :: PrimalIO m => a -> m (GHC.StablePtr a)
newStablePtr = liftP . GHC.newStablePtr
-- | Same as `GHC.deRefStablePtr`, but generalized to `Primal`
deRefStablePtr :: PrimalIO m => GHC.StablePtr a -> m a
deRefStablePtr = liftP . GHC.deRefStablePtr
| Same as ` GHC.freeStablePtr ` , but generalized to ` Primal `
freeStablePtr :: PrimalIO m => GHC.StablePtr a -> m ()
freeStablePtr = liftP . GHC.freeStablePtr
| null | https://raw.githubusercontent.com/lehins/primal/c620bfd4f2a6475f1c12183fbe8138cf29ab1dad/primal/src/Primal/Foreign/StablePtr.hs | haskell | |
Module : Primal.Foreign.StablePtr
License : BSD3
Stability : experimental
Portability : non-portable
| Orphan in @primal@
| Orphan in @primal@
| Same as `GHC.deRefStablePtr`, but generalized to `Primal` | # LANGUAGE FlexibleContexts #
# OPTIONS_GHC -fno - warn - orphans #
Copyright : ( c ) 2020 - 2022
Maintainer : < >
module Primal.Foreign.StablePtr
( GHC.StablePtr(..)
, newStablePtr
, deRefStablePtr
, freeStablePtr
, GHC.castStablePtrToPtr
, GHC.castPtrToStablePtr
) where
import Control.DeepSeq
import Primal.Monad
import qualified GHC.Stable as GHC
instance NFData (GHC.StablePtr a) where
rnf (GHC.StablePtr _) = ()
instance Show (GHC.StablePtr a) where
show = show . GHC.castStablePtrToPtr
| Same as ` GHC.newStablePtr ` , but generalized to ` Primal `
newStablePtr :: PrimalIO m => a -> m (GHC.StablePtr a)
newStablePtr = liftP . GHC.newStablePtr
deRefStablePtr :: PrimalIO m => GHC.StablePtr a -> m a
deRefStablePtr = liftP . GHC.deRefStablePtr
| Same as ` GHC.freeStablePtr ` , but generalized to ` Primal `
freeStablePtr :: PrimalIO m => GHC.StablePtr a -> m ()
freeStablePtr = liftP . GHC.freeStablePtr
|
c6242e98cfb912c47f36fe1d2c54b53639067ff6c893c234adffd79e6d81fe27 | bmeurer/ocamljit2 | test8.ml | open Event
type 'a buffer_channel = { input: 'a channel; output: 'a channel }
let new_buffer_channel() =
let ic = new_channel() in
let oc = new_channel() in
let buff = Queue.create() in
let rec buffer_process front rear =
match (front, rear) with
([], []) -> buffer_process [sync(receive ic)] []
| (hd::tl, _) ->
select [
wrap (receive ic) (fun x -> buffer_process front (x::rear));
wrap (send oc hd) (fun () -> buffer_process tl rear)
]
| ([], _) -> buffer_process (List.rev rear) [] in
Thread.create (buffer_process []) [];
{ input = ic; output = oc }
let buffer_send bc data =
sync(send bc.input data)
let buffer_receive bc =
receive bc.output
(* Test *)
let box = new_buffer_channel()
let ch = new_channel()
let f () =
buffer_send box "un";
buffer_send box "deux";
sync (send ch 3)
let g () =
print_int (sync(receive ch)); print_newline();
print_string (sync(buffer_receive box)); print_newline();
print_string (sync(buffer_receive box)); print_newline()
let _ =
Thread.create f ();
g()
| null | https://raw.githubusercontent.com/bmeurer/ocamljit2/ef06db5c688c1160acc1de1f63c29473bcd0055c/testsuite/tests/lib-threads/test8.ml | ocaml | Test | open Event
type 'a buffer_channel = { input: 'a channel; output: 'a channel }
let new_buffer_channel() =
let ic = new_channel() in
let oc = new_channel() in
let buff = Queue.create() in
let rec buffer_process front rear =
match (front, rear) with
([], []) -> buffer_process [sync(receive ic)] []
| (hd::tl, _) ->
select [
wrap (receive ic) (fun x -> buffer_process front (x::rear));
wrap (send oc hd) (fun () -> buffer_process tl rear)
]
| ([], _) -> buffer_process (List.rev rear) [] in
Thread.create (buffer_process []) [];
{ input = ic; output = oc }
let buffer_send bc data =
sync(send bc.input data)
let buffer_receive bc =
receive bc.output
let box = new_buffer_channel()
let ch = new_channel()
let f () =
buffer_send box "un";
buffer_send box "deux";
sync (send ch 3)
let g () =
print_int (sync(receive ch)); print_newline();
print_string (sync(buffer_receive box)); print_newline();
print_string (sync(buffer_receive box)); print_newline()
let _ =
Thread.create f ();
g()
|
848133176160f7faaa0fd87bcf65bbed52324353ce91c3dfa26dee697e3c3a91 | isovector/circuitry | Graph.hs | # LANGUAGE AllowAmbiguousTypes #
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE OverloadedLabels #-}
module Circuitry.Graph where
import Circuitry.Category (Category(..))
import Clash.Sized.Vector (Vec(..))
import qualified Clash.Sized.Vector as V
import Control.Monad.Reader (ReaderT, MonadReader)
import Control.Monad.State
import Data.Generics.Labels ()
import GHC.Generics
import Prelude hiding ((.), id, sum)
import Circuitry.Embed
import Circus.Types (Bit)
import Circus.DSL
newtype Graph a b = Graph
{ unGraph :: Vec (SizeOf a) Bit -> GraphM (Vec (SizeOf b) Bit)
}
instance Category Graph where
type Ok Graph = Embed
id = Graph pure
Graph g . Graph f = Graph (g <=< f)
coerceGraph
:: (SizeOf a ~ SizeOf a', SizeOf b ~ SizeOf b')
=> Graph a b
-> Graph a' b'
coerceGraph = Graph . unGraph
synthesizeBits :: Embed a => GraphM (Vec (SizeOf a) Bit)
synthesizeBits = flip V.traverse# (V.repeat ()) $ const freshBit
data RenderOptions = RenderOptions
{ ro_unpack_gates :: Bool
, ro_unpack_constants :: Bool
, ro_depth :: Int
}
deriving stock (Eq, Ord, Show, Generic)
newtype GraphM a = GraphM { unGraphM :: ReaderT RenderOptions (State GraphState) a }
deriving newtype ( Functor
, Applicative
, Monad
, MonadState GraphState
, MonadReader RenderOptions
, MonadFix
)
| null | https://raw.githubusercontent.com/isovector/circuitry/55b9697a8e34b4ae2effe7b4cbb8fbf4c1419c85/src/Circuitry/Graph.hs | haskell | # LANGUAGE MagicHash #
# LANGUAGE OverloadedLabels # | # LANGUAGE AllowAmbiguousTypes #
module Circuitry.Graph where
import Circuitry.Category (Category(..))
import Clash.Sized.Vector (Vec(..))
import qualified Clash.Sized.Vector as V
import Control.Monad.Reader (ReaderT, MonadReader)
import Control.Monad.State
import Data.Generics.Labels ()
import GHC.Generics
import Prelude hiding ((.), id, sum)
import Circuitry.Embed
import Circus.Types (Bit)
import Circus.DSL
newtype Graph a b = Graph
{ unGraph :: Vec (SizeOf a) Bit -> GraphM (Vec (SizeOf b) Bit)
}
instance Category Graph where
type Ok Graph = Embed
id = Graph pure
Graph g . Graph f = Graph (g <=< f)
coerceGraph
:: (SizeOf a ~ SizeOf a', SizeOf b ~ SizeOf b')
=> Graph a b
-> Graph a' b'
coerceGraph = Graph . unGraph
synthesizeBits :: Embed a => GraphM (Vec (SizeOf a) Bit)
synthesizeBits = flip V.traverse# (V.repeat ()) $ const freshBit
data RenderOptions = RenderOptions
{ ro_unpack_gates :: Bool
, ro_unpack_constants :: Bool
, ro_depth :: Int
}
deriving stock (Eq, Ord, Show, Generic)
newtype GraphM a = GraphM { unGraphM :: ReaderT RenderOptions (State GraphState) a }
deriving newtype ( Functor
, Applicative
, Monad
, MonadState GraphState
, MonadReader RenderOptions
, MonadFix
)
|
a3f63441a3eb95a515af4483c547d7fef96f9dfdc67c1da44b4ea7dd7621deae | jjtolton/libapl-clj | pointer.clj | (ns libapl-clj.impl.pointer
(:refer-clojure :exclude [- = * > < / + -])
(:require [libapl-clj.impl.jna :as jna]
tech.v3.datatype.jna ;; <-- this is criticial
[tech.v3.datatype :as dtype]
[libapl-clj.impl.api :as api])
(:import [com.sun.jna Pointer]))
(defn ^:private getfn
"Import an APL function into Clojure as a pointer"
^Pointer [^String fstring]
(api/get-function-ucs fstring))
(def + (getfn '+))
(def - (getfn '-))
(def × (getfn '×))
(def = (getfn '=))
(def ÷ (getfn '÷))
(def * (getfn '*))
(def ⌈ (getfn '⌈))
(def ⌊ (getfn '⌊))
(def | (getfn '|))
(def < (getfn '<))
(def ≤ (getfn '≤))
(def = (getfn '=))
(def > (getfn '>))
(def ≥ (getfn '≥))
(def ≠ (getfn '≠))
(def ⍴ (getfn '⍴))
(def ∊ (getfn '∊))
(def ∨ (getfn '∨))
(def ∧ (getfn '∧))
(def ⍱ (getfn '⍱))
(def ⍲ (getfn '⍲))
(def ... (getfn ","))
(def ⍪ (getfn '⍪))
(def / (getfn '/))
(def ⌿ (getfn '⌿))
(def ⍳ (getfn '⍳))
(def ⌷ (getfn '⌷))
(def ⍕ (getfn '⍕))
(def ⍎ (getfn '⍎))
(def ∼ (getfn '∼))
(def ↑ (getfn '↑))
(def ↓ (getfn '↓))
(def backslash (getfn "\\"))
(def ⌽ (getfn '⌽))
(def ⍉ (getfn '⍉))
(def ⊖ (getfn '⊖))
(def ¯ (getfn '¯))
(def ⍬ (getfn '⍬))
(def ← (getfn '←))
(def → (getfn '→))
( def ⍞ ( " ⍞ " ) )
(def hashtag (getfn "#"))
( def ⎕ ( " ⎕ " ) )
(def ⍋ (getfn '⍋))
(def ⍒ (getfn '⍒))
(def ⊥ (getfn '⊥))
(def ⊤ (getfn '⊤))
(def ? (getfn '?))
(def ⍟ (getfn '⍟))
(def ! (getfn '!))
(def ○ (getfn '○))
(def ⌹ (getfn '⌹))
(def ∩ (getfn '∩))
(def ∪ (getfn '∪))
(def ≡ (getfn '≡))
(def ≢ (getfn '≢))
(def ¨ (getfn '¨))
(def ∘. (getfn '∘.)) ;; ⍝ not sure if this will work
(def ⍤ (getfn '⍤))
(def . (getfn '.))
(def ⍳ (getfn '⍳))
(def ⍷ (getfn '⍷))
(def ⊣ (getfn '⊣))
(def ⊢ (getfn '⊢))
(def ⊂ (getfn '⊂))
(def ⊃ (getfn '⊃))
| null | https://raw.githubusercontent.com/jjtolton/libapl-clj/01e2bf7e0d20abd9f8f36c2d9fc829dd4082d455/src/libapl_clj/impl/pointer.clj | clojure | <-- this is criticial
⍝ not sure if this will work | (ns libapl-clj.impl.pointer
(:refer-clojure :exclude [- = * > < / + -])
(:require [libapl-clj.impl.jna :as jna]
[tech.v3.datatype :as dtype]
[libapl-clj.impl.api :as api])
(:import [com.sun.jna Pointer]))
(defn ^:private getfn
"Import an APL function into Clojure as a pointer"
^Pointer [^String fstring]
(api/get-function-ucs fstring))
(def + (getfn '+))
(def - (getfn '-))
(def × (getfn '×))
(def = (getfn '=))
(def ÷ (getfn '÷))
(def * (getfn '*))
(def ⌈ (getfn '⌈))
(def ⌊ (getfn '⌊))
(def | (getfn '|))
(def < (getfn '<))
(def ≤ (getfn '≤))
(def = (getfn '=))
(def > (getfn '>))
(def ≥ (getfn '≥))
(def ≠ (getfn '≠))
(def ⍴ (getfn '⍴))
(def ∊ (getfn '∊))
(def ∨ (getfn '∨))
(def ∧ (getfn '∧))
(def ⍱ (getfn '⍱))
(def ⍲ (getfn '⍲))
(def ... (getfn ","))
(def ⍪ (getfn '⍪))
(def / (getfn '/))
(def ⌿ (getfn '⌿))
(def ⍳ (getfn '⍳))
(def ⌷ (getfn '⌷))
(def ⍕ (getfn '⍕))
(def ⍎ (getfn '⍎))
(def ∼ (getfn '∼))
(def ↑ (getfn '↑))
(def ↓ (getfn '↓))
(def backslash (getfn "\\"))
(def ⌽ (getfn '⌽))
(def ⍉ (getfn '⍉))
(def ⊖ (getfn '⊖))
(def ¯ (getfn '¯))
(def ⍬ (getfn '⍬))
(def ← (getfn '←))
(def → (getfn '→))
( def ⍞ ( " ⍞ " ) )
(def hashtag (getfn "#"))
( def ⎕ ( " ⎕ " ) )
(def ⍋ (getfn '⍋))
(def ⍒ (getfn '⍒))
(def ⊥ (getfn '⊥))
(def ⊤ (getfn '⊤))
(def ? (getfn '?))
(def ⍟ (getfn '⍟))
(def ! (getfn '!))
(def ○ (getfn '○))
(def ⌹ (getfn '⌹))
(def ∩ (getfn '∩))
(def ∪ (getfn '∪))
(def ≡ (getfn '≡))
(def ≢ (getfn '≢))
(def ¨ (getfn '¨))
(def ⍤ (getfn '⍤))
(def . (getfn '.))
(def ⍳ (getfn '⍳))
(def ⍷ (getfn '⍷))
(def ⊣ (getfn '⊣))
(def ⊢ (getfn '⊢))
(def ⊂ (getfn '⊂))
(def ⊃ (getfn '⊃))
|
48bd4789feab176ceabea8fccc3465da608d4314b8b9babc3012488965e1ff31 | haskell/haskell-language-server | RuleTypes.hs | Copyright ( c ) 2019 The DAML Authors . All rights reserved .
SPDX - License - Identifier : Apache-2.0
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
-- | A Shake implementation of the compiler service, built
using the " " abstraction layer for in - memory use .
--
module Development.IDE.Core.RuleTypes(
GhcSessionDeps(.., GhcSessionDeps),
module Development.IDE.Core.RuleTypes
) where
import Control.DeepSeq
import Control.Exception (assert)
import Control.Lens
import Data.Aeson.Types (Value)
import Data.Hashable
import qualified Data.Map as M
import Data.Time.Clock.POSIX
import Data.Typeable
import Development.IDE.GHC.Compat hiding
(HieFileResult)
import Development.IDE.GHC.Compat.Util
import Development.IDE.GHC.CoreFile
import Development.IDE.GHC.Util
import Development.IDE.Graph
import Development.IDE.Import.DependencyInformation
import Development.IDE.Types.HscEnvEq (HscEnvEq)
import Development.IDE.Types.KnownTargets
import GHC.Generics (Generic)
import Data.ByteString (ByteString)
import Data.Text (Text)
import Development.IDE.Import.FindImports (ArtifactsLocation)
import Development.IDE.Spans.Common
import Development.IDE.Spans.LocalBindings
import Development.IDE.Types.Diagnostics
import GHC.Serialized (Serialized)
import Language.LSP.Types (Int32,
NormalizedFilePath)
data LinkableType = ObjectLinkable | BCOLinkable
deriving (Eq,Ord,Show, Generic)
instance Hashable LinkableType
instance NFData LinkableType
-- | Encode the linkable into an ordered bytestring.
-- This is used to drive an ordered "newness" predicate in the
' NeedsCompilation ' build rule .
encodeLinkableType :: Maybe LinkableType -> ByteString
encodeLinkableType Nothing = "0"
encodeLinkableType (Just BCOLinkable) = "1"
encodeLinkableType (Just ObjectLinkable) = "2"
NOTATION
Foo+ means for the dependencies
Foo * means for me and Foo+
-- | The parse tree for the file using GetFileContents
type instance RuleResult GetParsedModule = ParsedModule
-- | The parse tree for the file using GetFileContents,
-- all comments included using Opt_KeepRawTokenStream
type instance RuleResult GetParsedModuleWithComments = ParsedModule
-- | The dependency information produced by following the imports recursively.
-- This rule will succeed even if there is an error, e.g., a module could not be located,
-- a module could not be parsed or an import cycle.
type instance RuleResult GetDependencyInformation = DependencyInformation
type instance RuleResult GetModuleGraph = DependencyInformation
data GetKnownTargets = GetKnownTargets
deriving (Show, Generic, Eq, Ord)
instance Hashable GetKnownTargets
instance NFData GetKnownTargets
type instance RuleResult GetKnownTargets = KnownTargets
| Convert to Core , requires *
type instance RuleResult GenerateCore = ModGuts
data GenerateCore = GenerateCore
deriving (Eq, Show, Typeable, Generic)
instance Hashable GenerateCore
instance NFData GenerateCore
type instance RuleResult GetLinkable = LinkableResult
data LinkableResult
= LinkableResult
{ linkableHomeMod :: !HomeModInfo
, linkableHash :: !ByteString
-- ^ The hash of the core file
}
instance Show LinkableResult where
show = show . mi_module . hm_iface . linkableHomeMod
instance NFData LinkableResult where
rnf = rwhnf
data GetLinkable = GetLinkable
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetLinkable
instance NFData GetLinkable
data GetImportMap = GetImportMap
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetImportMap
instance NFData GetImportMap
type instance RuleResult GetImportMap = ImportMap
newtype ImportMap = ImportMap
{ importMap :: M.Map ModuleName NormalizedFilePath -- ^ Where are the modules imported by this file located?
} deriving stock Show
deriving newtype NFData
data Splices = Splices
{ exprSplices :: [(LHsExpr GhcTc, LHsExpr GhcPs)]
, patSplices :: [(LHsExpr GhcTc, LPat GhcPs)]
, typeSplices :: [(LHsExpr GhcTc, LHsType GhcPs)]
, declSplices :: [(LHsExpr GhcTc, [LHsDecl GhcPs])]
, awSplices :: [(LHsExpr GhcTc, Serialized)]
}
instance Semigroup Splices where
Splices e p t d aw <> Splices e' p' t' d' aw' =
Splices
(e <> e')
(p <> p')
(t <> t')
(d <> d')
(aw <> aw')
instance Monoid Splices where
mempty = Splices mempty mempty mempty mempty mempty
instance NFData Splices where
rnf Splices {..} =
liftRnf rwhnf exprSplices `seq`
liftRnf rwhnf patSplices `seq`
liftRnf rwhnf typeSplices `seq` liftRnf rwhnf declSplices `seq` ()
-- | Contains the typechecked module and the OrigNameCache entry for
-- that module.
data TcModuleResult = TcModuleResult
{ tmrParsed :: ParsedModule
, tmrRenamed :: RenamedSource
, tmrTypechecked :: TcGblEnv
, tmrTopLevelSplices :: Splices
-- ^ Typechecked splice information
, tmrDeferredError :: !Bool
-- ^ Did we defer any type errors for this module?
, tmrRuntimeModules :: !(ModuleEnv ByteString)
-- ^ Which modules did we need at runtime while compiling this file?
Used for recompilation checking in the presence of TH
-- Stores the hash of their core file
}
instance Show TcModuleResult where
show = show . pm_mod_summary . tmrParsed
instance NFData TcModuleResult where
rnf = rwhnf
tmrModSummary :: TcModuleResult -> ModSummary
tmrModSummary = pm_mod_summary . tmrParsed
data HiFileResult = HiFileResult
{ hirModSummary :: !ModSummary
-- Bang patterns here are important to stop the result retaining
-- a reference to a typechecked module
, hirModIface :: !ModIface
, hirModDetails :: ModDetails
-- ^ Populated lazily
, hirIfaceFp :: !ByteString
^ Fingerprint for the ModIface
, hirRuntimeModules :: !(ModuleEnv ByteString)
-- ^ same as tmrRuntimeModules
, hirCoreFp :: !(Maybe (CoreFile, ByteString))
-- ^ If we wrote a core file for this module, then its contents (lazily deserialised)
-- along with its hash
}
hiFileFingerPrint :: HiFileResult -> ByteString
hiFileFingerPrint HiFileResult{..} = hirIfaceFp <> maybe "" snd hirCoreFp
mkHiFileResult :: ModSummary -> ModIface -> ModDetails -> ModuleEnv ByteString -> Maybe (CoreFile, ByteString) -> HiFileResult
mkHiFileResult hirModSummary hirModIface hirModDetails hirRuntimeModules hirCoreFp =
assert (case hirCoreFp of Just (CoreFile{cf_iface_hash}, _)
-> getModuleHash hirModIface == cf_iface_hash
_ -> True)
HiFileResult{..}
where
will always be two bytes
instance NFData HiFileResult where
rnf = rwhnf
instance Show HiFileResult where
show = show . hirModSummary
-- | Save the uncompressed AST here, we compress it just before writing to disk
data HieAstResult
= forall a . (Typeable a) => HAR
{ hieModule :: Module
, hieAst :: !(HieASTs a)
, refMap :: RefMap a
-- ^ Lazy because its value only depends on the hieAst, which is bundled in this type
Lazyness ca n't cause leaks here because the lifetime of ` refMap ` will be the same
-- as that of `hieAst`
, typeRefs :: M.Map Name [RealSrcSpan]
-- ^ type references in this file
, hieKind :: !(HieKind a)
-- ^ Is this hie file loaded from the disk, or freshly computed?
}
data HieKind a where
HieFromDisk :: !HieFile -> HieKind TypeIndex
HieFresh :: HieKind Type
instance NFData (HieKind a) where
rnf (HieFromDisk hf) = rnf hf
rnf HieFresh = ()
instance NFData HieAstResult where
rnf (HAR m hf _rm _tr kind) = rnf m `seq` rwhnf hf `seq` rnf kind
instance Show HieAstResult where
show = show . hieModule
| The type checked version of this file , requires TypeCheck+
type instance RuleResult TypeCheck = TcModuleResult
| The uncompressed HieAST
type instance RuleResult GetHieAst = HieAstResult
| A telling us what is in scope at each point
type instance RuleResult GetBindings = Bindings
data DocAndKindMap = DKMap {getDocMap :: !DocMap, getKindMap :: !KindMap}
instance NFData DocAndKindMap where
rnf (DKMap a b) = rwhnf a `seq` rwhnf b
instance Show DocAndKindMap where
show = const "docmap"
type instance RuleResult GetDocMap = DocAndKindMap
| A GHC session that we reuse .
type instance RuleResult GhcSession = HscEnvEq
| A GHC session preloaded with all the dependencies
-- This rule is also responsible for calling ReportImportCycles for the direct dependencies
type instance RuleResult GhcSessionDeps = HscEnvEq
-- | Resolve the imports in a module to the file path of a module in the same package
type instance RuleResult GetLocatedImports = [(Located ModuleName, Maybe ArtifactsLocation)]
-- | This rule is used to report import cycles. It depends on GetDependencyInformation.
-- We cannot report the cycles directly from GetDependencyInformation since
-- we can only report diagnostics for the current file.
type instance RuleResult ReportImportCycles = ()
| Read the module interface file from disk . Throws an error for VFS files .
This is an internal rule , use ' GetModIface ' instead .
type instance RuleResult GetModIfaceFromDisk = HiFileResult
-- | GetModIfaceFromDisk and index the `.hie` file into the database.
This is an internal rule , use ' GetModIface ' instead .
type instance RuleResult GetModIfaceFromDiskAndIndex = HiFileResult
-- | Get a module interface details, either from an interface file or a typechecked module
type instance RuleResult GetModIface = HiFileResult
-- | Get the contents of a file, either dirty (if the buffer is modified) or Nothing to mean use from disk.
type instance RuleResult GetFileContents = (FileVersion, Maybe Text)
type instance RuleResult GetFileExists = Bool
type instance RuleResult AddWatchedFile = Bool
-- The Shake key type for getModificationTime queries
newtype GetModificationTime = GetModificationTime_
{ missingFileDiagnostics :: Bool
-- ^ If false, missing file diagnostics are not reported
}
deriving (Generic)
instance Show GetModificationTime where
show _ = "GetModificationTime"
instance Eq GetModificationTime where
-- Since the diagnostics are not part of the answer, the query identity is
-- independent from the 'missingFileDiagnostics' field
_ == _ = True
instance Hashable GetModificationTime where
-- Since the diagnostics are not part of the answer, the query identity is
-- independent from the 'missingFileDiagnostics' field
hashWithSalt salt _ = salt
instance NFData GetModificationTime
pattern GetModificationTime :: GetModificationTime
pattern GetModificationTime = GetModificationTime_ {missingFileDiagnostics=True}
-- | Get the modification time of a file.
type instance RuleResult GetModificationTime = FileVersion
| Either the from disk or an LSP version
LSP versions always compare as greater than on disk versions
data FileVersion
= ModificationTime !POSIXTime -- order of constructors is relevant
| VFSVersion !Int32
deriving (Show, Generic, Eq, Ord)
instance NFData FileVersion
vfsVersion :: FileVersion -> Maybe Int32
vfsVersion (VFSVersion i) = Just i
vfsVersion ModificationTime{} = Nothing
data GetFileContents = GetFileContents
deriving (Eq, Show, Generic)
instance Hashable GetFileContents
instance NFData GetFileContents
data GetFileExists = GetFileExists
deriving (Eq, Show, Typeable, Generic)
instance NFData GetFileExists
instance Hashable GetFileExists
data FileOfInterestStatus
= OnDisk
| Modified { firstOpen :: !Bool -- ^ was this file just opened
}
deriving (Eq, Show, Typeable, Generic)
instance Hashable FileOfInterestStatus
instance NFData FileOfInterestStatus
data IsFileOfInterestResult = NotFOI | IsFOI FileOfInterestStatus
deriving (Eq, Show, Typeable, Generic)
instance Hashable IsFileOfInterestResult
instance NFData IsFileOfInterestResult
type instance RuleResult IsFileOfInterest = IsFileOfInterestResult
data ModSummaryResult = ModSummaryResult
{ msrModSummary :: !ModSummary
, msrImports :: [LImportDecl GhcPs]
, msrFingerprint :: !Fingerprint
, msrHscEnv :: !HscEnv
^ HscEnv for this particular ModSummary .
-- Contains initialised plugins, parsed options, etc...
--
Implicit assumption : DynFlags in ' msrModSummary ' are the same as
the DynFlags in ' msrHscEnv ' .
}
instance Show ModSummaryResult where
show _ = "<ModSummaryResult>"
instance NFData ModSummaryResult where
rnf ModSummaryResult{..} =
rnf msrModSummary `seq` rnf msrImports `seq` rnf msrFingerprint
| Generate a ModSummary that has enough information to be used to get .hi and .hie files .
-- without needing to parse the entire source
type instance RuleResult GetModSummary = ModSummaryResult
| Generate a ModSummary with the timestamps and preprocessed content elided , for more successful early cutoff
type instance RuleResult GetModSummaryWithoutTimestamps = ModSummaryResult
data GetParsedModule = GetParsedModule
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetParsedModule
instance NFData GetParsedModule
data GetParsedModuleWithComments = GetParsedModuleWithComments
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetParsedModuleWithComments
instance NFData GetParsedModuleWithComments
data GetLocatedImports = GetLocatedImports
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetLocatedImports
instance NFData GetLocatedImports
-- | Does this module need to be compiled?
type instance RuleResult NeedsCompilation = Maybe LinkableType
data NeedsCompilation = NeedsCompilation
deriving (Eq, Show, Typeable, Generic)
instance Hashable NeedsCompilation
instance NFData NeedsCompilation
data GetDependencyInformation = GetDependencyInformation
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetDependencyInformation
instance NFData GetDependencyInformation
data GetModuleGraph = GetModuleGraph
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetModuleGraph
instance NFData GetModuleGraph
data ReportImportCycles = ReportImportCycles
deriving (Eq, Show, Typeable, Generic)
instance Hashable ReportImportCycles
instance NFData ReportImportCycles
data TypeCheck = TypeCheck
deriving (Eq, Show, Typeable, Generic)
instance Hashable TypeCheck
instance NFData TypeCheck
data GetDocMap = GetDocMap
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetDocMap
instance NFData GetDocMap
data GetHieAst = GetHieAst
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetHieAst
instance NFData GetHieAst
data GetBindings = GetBindings
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetBindings
instance NFData GetBindings
data GhcSession = GhcSession
deriving (Eq, Show, Typeable, Generic)
instance Hashable GhcSession
instance NFData GhcSession
newtype GhcSessionDeps = GhcSessionDeps_
| Load full ModSummary values in the GHC session .
-- Required for interactive evaluation, but leads to more cache invalidations
fullModSummary :: Bool
}
deriving newtype (Eq, Typeable, Hashable, NFData)
instance Show GhcSessionDeps where
show (GhcSessionDeps_ False) = "GhcSessionDeps"
show (GhcSessionDeps_ True) = "GhcSessionDepsFull"
pattern GhcSessionDeps :: GhcSessionDeps
pattern GhcSessionDeps = GhcSessionDeps_ False
data GetModIfaceFromDisk = GetModIfaceFromDisk
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetModIfaceFromDisk
instance NFData GetModIfaceFromDisk
data GetModIfaceFromDiskAndIndex = GetModIfaceFromDiskAndIndex
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetModIfaceFromDiskAndIndex
instance NFData GetModIfaceFromDiskAndIndex
data GetModIface = GetModIface
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetModIface
instance NFData GetModIface
data IsFileOfInterest = IsFileOfInterest
deriving (Eq, Show, Typeable, Generic)
instance Hashable IsFileOfInterest
instance NFData IsFileOfInterest
data GetModSummaryWithoutTimestamps = GetModSummaryWithoutTimestamps
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetModSummaryWithoutTimestamps
instance NFData GetModSummaryWithoutTimestamps
data GetModSummary = GetModSummary
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetModSummary
instance NFData GetModSummary
-- | Get the vscode client settings stored in the ide state
data GetClientSettings = GetClientSettings
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetClientSettings
instance NFData GetClientSettings
type instance RuleResult GetClientSettings = Hashed (Maybe Value)
data AddWatchedFile = AddWatchedFile deriving (Eq, Show, Typeable, Generic)
instance Hashable AddWatchedFile
instance NFData AddWatchedFile
A local rule type to get caching . We want to use newCache , but it has
-- thread killed exception issues, so we lift it to a full rule.
-- -asset/daml/pull/2808#issuecomment-529639547
type instance RuleResult GhcSessionIO = IdeGhcSession
data IdeGhcSession = IdeGhcSession
{ loadSessionFun :: FilePath -> IO (IdeResult HscEnvEq, [FilePath])
^ Returns the Ghc session and the cradle dependencies
, sessionVersion :: !Int
-- ^ Used as Shake key, versions must be unique and not reused
}
instance Show IdeGhcSession where show _ = "IdeGhcSession"
instance NFData IdeGhcSession where rnf !_ = ()
data GhcSessionIO = GhcSessionIO deriving (Eq, Show, Typeable, Generic)
instance Hashable GhcSessionIO
instance NFData GhcSessionIO
makeLensesWith
(lensRules & lensField .~ mappingNamer (pure . (++ "L")))
''Splices
| null | https://raw.githubusercontent.com/haskell/haskell-language-server/ff28990e042f6ae9df39dab435b94ce9b20356a5/ghcide/src/Development/IDE/Core/RuleTypes.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE PatternSynonyms #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
| A Shake implementation of the compiler service, built
| Encode the linkable into an ordered bytestring.
This is used to drive an ordered "newness" predicate in the
| The parse tree for the file using GetFileContents
| The parse tree for the file using GetFileContents,
all comments included using Opt_KeepRawTokenStream
| The dependency information produced by following the imports recursively.
This rule will succeed even if there is an error, e.g., a module could not be located,
a module could not be parsed or an import cycle.
^ The hash of the core file
^ Where are the modules imported by this file located?
| Contains the typechecked module and the OrigNameCache entry for
that module.
^ Typechecked splice information
^ Did we defer any type errors for this module?
^ Which modules did we need at runtime while compiling this file?
Stores the hash of their core file
Bang patterns here are important to stop the result retaining
a reference to a typechecked module
^ Populated lazily
^ same as tmrRuntimeModules
^ If we wrote a core file for this module, then its contents (lazily deserialised)
along with its hash
| Save the uncompressed AST here, we compress it just before writing to disk
^ Lazy because its value only depends on the hieAst, which is bundled in this type
as that of `hieAst`
^ type references in this file
^ Is this hie file loaded from the disk, or freshly computed?
This rule is also responsible for calling ReportImportCycles for the direct dependencies
| Resolve the imports in a module to the file path of a module in the same package
| This rule is used to report import cycles. It depends on GetDependencyInformation.
We cannot report the cycles directly from GetDependencyInformation since
we can only report diagnostics for the current file.
| GetModIfaceFromDisk and index the `.hie` file into the database.
| Get a module interface details, either from an interface file or a typechecked module
| Get the contents of a file, either dirty (if the buffer is modified) or Nothing to mean use from disk.
The Shake key type for getModificationTime queries
^ If false, missing file diagnostics are not reported
Since the diagnostics are not part of the answer, the query identity is
independent from the 'missingFileDiagnostics' field
Since the diagnostics are not part of the answer, the query identity is
independent from the 'missingFileDiagnostics' field
| Get the modification time of a file.
order of constructors is relevant
^ was this file just opened
Contains initialised plugins, parsed options, etc...
without needing to parse the entire source
| Does this module need to be compiled?
Required for interactive evaluation, but leads to more cache invalidations
| Get the vscode client settings stored in the ide state
thread killed exception issues, so we lift it to a full rule.
-asset/daml/pull/2808#issuecomment-529639547
^ Used as Shake key, versions must be unique and not reused | Copyright ( c ) 2019 The DAML Authors . All rights reserved .
SPDX - License - Identifier : Apache-2.0
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleInstances #
using the " " abstraction layer for in - memory use .
module Development.IDE.Core.RuleTypes(
GhcSessionDeps(.., GhcSessionDeps),
module Development.IDE.Core.RuleTypes
) where
import Control.DeepSeq
import Control.Exception (assert)
import Control.Lens
import Data.Aeson.Types (Value)
import Data.Hashable
import qualified Data.Map as M
import Data.Time.Clock.POSIX
import Data.Typeable
import Development.IDE.GHC.Compat hiding
(HieFileResult)
import Development.IDE.GHC.Compat.Util
import Development.IDE.GHC.CoreFile
import Development.IDE.GHC.Util
import Development.IDE.Graph
import Development.IDE.Import.DependencyInformation
import Development.IDE.Types.HscEnvEq (HscEnvEq)
import Development.IDE.Types.KnownTargets
import GHC.Generics (Generic)
import Data.ByteString (ByteString)
import Data.Text (Text)
import Development.IDE.Import.FindImports (ArtifactsLocation)
import Development.IDE.Spans.Common
import Development.IDE.Spans.LocalBindings
import Development.IDE.Types.Diagnostics
import GHC.Serialized (Serialized)
import Language.LSP.Types (Int32,
NormalizedFilePath)
data LinkableType = ObjectLinkable | BCOLinkable
deriving (Eq,Ord,Show, Generic)
instance Hashable LinkableType
instance NFData LinkableType
' NeedsCompilation ' build rule .
encodeLinkableType :: Maybe LinkableType -> ByteString
encodeLinkableType Nothing = "0"
encodeLinkableType (Just BCOLinkable) = "1"
encodeLinkableType (Just ObjectLinkable) = "2"
NOTATION
Foo+ means for the dependencies
Foo * means for me and Foo+
type instance RuleResult GetParsedModule = ParsedModule
type instance RuleResult GetParsedModuleWithComments = ParsedModule
type instance RuleResult GetDependencyInformation = DependencyInformation
type instance RuleResult GetModuleGraph = DependencyInformation
data GetKnownTargets = GetKnownTargets
deriving (Show, Generic, Eq, Ord)
instance Hashable GetKnownTargets
instance NFData GetKnownTargets
type instance RuleResult GetKnownTargets = KnownTargets
| Convert to Core , requires *
type instance RuleResult GenerateCore = ModGuts
data GenerateCore = GenerateCore
deriving (Eq, Show, Typeable, Generic)
instance Hashable GenerateCore
instance NFData GenerateCore
type instance RuleResult GetLinkable = LinkableResult
data LinkableResult
= LinkableResult
{ linkableHomeMod :: !HomeModInfo
, linkableHash :: !ByteString
}
instance Show LinkableResult where
show = show . mi_module . hm_iface . linkableHomeMod
instance NFData LinkableResult where
rnf = rwhnf
data GetLinkable = GetLinkable
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetLinkable
instance NFData GetLinkable
data GetImportMap = GetImportMap
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetImportMap
instance NFData GetImportMap
type instance RuleResult GetImportMap = ImportMap
newtype ImportMap = ImportMap
} deriving stock Show
deriving newtype NFData
data Splices = Splices
{ exprSplices :: [(LHsExpr GhcTc, LHsExpr GhcPs)]
, patSplices :: [(LHsExpr GhcTc, LPat GhcPs)]
, typeSplices :: [(LHsExpr GhcTc, LHsType GhcPs)]
, declSplices :: [(LHsExpr GhcTc, [LHsDecl GhcPs])]
, awSplices :: [(LHsExpr GhcTc, Serialized)]
}
instance Semigroup Splices where
Splices e p t d aw <> Splices e' p' t' d' aw' =
Splices
(e <> e')
(p <> p')
(t <> t')
(d <> d')
(aw <> aw')
instance Monoid Splices where
mempty = Splices mempty mempty mempty mempty mempty
instance NFData Splices where
rnf Splices {..} =
liftRnf rwhnf exprSplices `seq`
liftRnf rwhnf patSplices `seq`
liftRnf rwhnf typeSplices `seq` liftRnf rwhnf declSplices `seq` ()
data TcModuleResult = TcModuleResult
{ tmrParsed :: ParsedModule
, tmrRenamed :: RenamedSource
, tmrTypechecked :: TcGblEnv
, tmrTopLevelSplices :: Splices
, tmrDeferredError :: !Bool
, tmrRuntimeModules :: !(ModuleEnv ByteString)
Used for recompilation checking in the presence of TH
}
instance Show TcModuleResult where
show = show . pm_mod_summary . tmrParsed
instance NFData TcModuleResult where
rnf = rwhnf
tmrModSummary :: TcModuleResult -> ModSummary
tmrModSummary = pm_mod_summary . tmrParsed
data HiFileResult = HiFileResult
{ hirModSummary :: !ModSummary
, hirModIface :: !ModIface
, hirModDetails :: ModDetails
, hirIfaceFp :: !ByteString
^ Fingerprint for the ModIface
, hirRuntimeModules :: !(ModuleEnv ByteString)
, hirCoreFp :: !(Maybe (CoreFile, ByteString))
}
hiFileFingerPrint :: HiFileResult -> ByteString
hiFileFingerPrint HiFileResult{..} = hirIfaceFp <> maybe "" snd hirCoreFp
mkHiFileResult :: ModSummary -> ModIface -> ModDetails -> ModuleEnv ByteString -> Maybe (CoreFile, ByteString) -> HiFileResult
mkHiFileResult hirModSummary hirModIface hirModDetails hirRuntimeModules hirCoreFp =
assert (case hirCoreFp of Just (CoreFile{cf_iface_hash}, _)
-> getModuleHash hirModIface == cf_iface_hash
_ -> True)
HiFileResult{..}
where
will always be two bytes
instance NFData HiFileResult where
rnf = rwhnf
instance Show HiFileResult where
show = show . hirModSummary
data HieAstResult
= forall a . (Typeable a) => HAR
{ hieModule :: Module
, hieAst :: !(HieASTs a)
, refMap :: RefMap a
Lazyness ca n't cause leaks here because the lifetime of ` refMap ` will be the same
, typeRefs :: M.Map Name [RealSrcSpan]
, hieKind :: !(HieKind a)
}
data HieKind a where
HieFromDisk :: !HieFile -> HieKind TypeIndex
HieFresh :: HieKind Type
instance NFData (HieKind a) where
rnf (HieFromDisk hf) = rnf hf
rnf HieFresh = ()
instance NFData HieAstResult where
rnf (HAR m hf _rm _tr kind) = rnf m `seq` rwhnf hf `seq` rnf kind
instance Show HieAstResult where
show = show . hieModule
| The type checked version of this file , requires TypeCheck+
type instance RuleResult TypeCheck = TcModuleResult
| The uncompressed HieAST
type instance RuleResult GetHieAst = HieAstResult
| A telling us what is in scope at each point
type instance RuleResult GetBindings = Bindings
data DocAndKindMap = DKMap {getDocMap :: !DocMap, getKindMap :: !KindMap}
instance NFData DocAndKindMap where
rnf (DKMap a b) = rwhnf a `seq` rwhnf b
instance Show DocAndKindMap where
show = const "docmap"
type instance RuleResult GetDocMap = DocAndKindMap
| A GHC session that we reuse .
type instance RuleResult GhcSession = HscEnvEq
| A GHC session preloaded with all the dependencies
type instance RuleResult GhcSessionDeps = HscEnvEq
type instance RuleResult GetLocatedImports = [(Located ModuleName, Maybe ArtifactsLocation)]
type instance RuleResult ReportImportCycles = ()
| Read the module interface file from disk . Throws an error for VFS files .
This is an internal rule , use ' GetModIface ' instead .
type instance RuleResult GetModIfaceFromDisk = HiFileResult
This is an internal rule , use ' GetModIface ' instead .
type instance RuleResult GetModIfaceFromDiskAndIndex = HiFileResult
type instance RuleResult GetModIface = HiFileResult
type instance RuleResult GetFileContents = (FileVersion, Maybe Text)
type instance RuleResult GetFileExists = Bool
type instance RuleResult AddWatchedFile = Bool
newtype GetModificationTime = GetModificationTime_
{ missingFileDiagnostics :: Bool
}
deriving (Generic)
instance Show GetModificationTime where
show _ = "GetModificationTime"
instance Eq GetModificationTime where
_ == _ = True
instance Hashable GetModificationTime where
hashWithSalt salt _ = salt
instance NFData GetModificationTime
pattern GetModificationTime :: GetModificationTime
pattern GetModificationTime = GetModificationTime_ {missingFileDiagnostics=True}
type instance RuleResult GetModificationTime = FileVersion
| Either the from disk or an LSP version
LSP versions always compare as greater than on disk versions
data FileVersion
| VFSVersion !Int32
deriving (Show, Generic, Eq, Ord)
instance NFData FileVersion
vfsVersion :: FileVersion -> Maybe Int32
vfsVersion (VFSVersion i) = Just i
vfsVersion ModificationTime{} = Nothing
data GetFileContents = GetFileContents
deriving (Eq, Show, Generic)
instance Hashable GetFileContents
instance NFData GetFileContents
data GetFileExists = GetFileExists
deriving (Eq, Show, Typeable, Generic)
instance NFData GetFileExists
instance Hashable GetFileExists
data FileOfInterestStatus
= OnDisk
}
deriving (Eq, Show, Typeable, Generic)
instance Hashable FileOfInterestStatus
instance NFData FileOfInterestStatus
data IsFileOfInterestResult = NotFOI | IsFOI FileOfInterestStatus
deriving (Eq, Show, Typeable, Generic)
instance Hashable IsFileOfInterestResult
instance NFData IsFileOfInterestResult
type instance RuleResult IsFileOfInterest = IsFileOfInterestResult
data ModSummaryResult = ModSummaryResult
{ msrModSummary :: !ModSummary
, msrImports :: [LImportDecl GhcPs]
, msrFingerprint :: !Fingerprint
, msrHscEnv :: !HscEnv
^ HscEnv for this particular ModSummary .
Implicit assumption : DynFlags in ' msrModSummary ' are the same as
the DynFlags in ' msrHscEnv ' .
}
instance Show ModSummaryResult where
show _ = "<ModSummaryResult>"
instance NFData ModSummaryResult where
rnf ModSummaryResult{..} =
rnf msrModSummary `seq` rnf msrImports `seq` rnf msrFingerprint
| Generate a ModSummary that has enough information to be used to get .hi and .hie files .
type instance RuleResult GetModSummary = ModSummaryResult
| Generate a ModSummary with the timestamps and preprocessed content elided , for more successful early cutoff
type instance RuleResult GetModSummaryWithoutTimestamps = ModSummaryResult
data GetParsedModule = GetParsedModule
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetParsedModule
instance NFData GetParsedModule
data GetParsedModuleWithComments = GetParsedModuleWithComments
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetParsedModuleWithComments
instance NFData GetParsedModuleWithComments
data GetLocatedImports = GetLocatedImports
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetLocatedImports
instance NFData GetLocatedImports
type instance RuleResult NeedsCompilation = Maybe LinkableType
data NeedsCompilation = NeedsCompilation
deriving (Eq, Show, Typeable, Generic)
instance Hashable NeedsCompilation
instance NFData NeedsCompilation
data GetDependencyInformation = GetDependencyInformation
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetDependencyInformation
instance NFData GetDependencyInformation
data GetModuleGraph = GetModuleGraph
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetModuleGraph
instance NFData GetModuleGraph
data ReportImportCycles = ReportImportCycles
deriving (Eq, Show, Typeable, Generic)
instance Hashable ReportImportCycles
instance NFData ReportImportCycles
data TypeCheck = TypeCheck
deriving (Eq, Show, Typeable, Generic)
instance Hashable TypeCheck
instance NFData TypeCheck
data GetDocMap = GetDocMap
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetDocMap
instance NFData GetDocMap
data GetHieAst = GetHieAst
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetHieAst
instance NFData GetHieAst
data GetBindings = GetBindings
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetBindings
instance NFData GetBindings
data GhcSession = GhcSession
deriving (Eq, Show, Typeable, Generic)
instance Hashable GhcSession
instance NFData GhcSession
newtype GhcSessionDeps = GhcSessionDeps_
| Load full ModSummary values in the GHC session .
fullModSummary :: Bool
}
deriving newtype (Eq, Typeable, Hashable, NFData)
instance Show GhcSessionDeps where
show (GhcSessionDeps_ False) = "GhcSessionDeps"
show (GhcSessionDeps_ True) = "GhcSessionDepsFull"
pattern GhcSessionDeps :: GhcSessionDeps
pattern GhcSessionDeps = GhcSessionDeps_ False
data GetModIfaceFromDisk = GetModIfaceFromDisk
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetModIfaceFromDisk
instance NFData GetModIfaceFromDisk
data GetModIfaceFromDiskAndIndex = GetModIfaceFromDiskAndIndex
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetModIfaceFromDiskAndIndex
instance NFData GetModIfaceFromDiskAndIndex
data GetModIface = GetModIface
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetModIface
instance NFData GetModIface
data IsFileOfInterest = IsFileOfInterest
deriving (Eq, Show, Typeable, Generic)
instance Hashable IsFileOfInterest
instance NFData IsFileOfInterest
data GetModSummaryWithoutTimestamps = GetModSummaryWithoutTimestamps
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetModSummaryWithoutTimestamps
instance NFData GetModSummaryWithoutTimestamps
data GetModSummary = GetModSummary
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetModSummary
instance NFData GetModSummary
data GetClientSettings = GetClientSettings
deriving (Eq, Show, Typeable, Generic)
instance Hashable GetClientSettings
instance NFData GetClientSettings
type instance RuleResult GetClientSettings = Hashed (Maybe Value)
data AddWatchedFile = AddWatchedFile deriving (Eq, Show, Typeable, Generic)
instance Hashable AddWatchedFile
instance NFData AddWatchedFile
A local rule type to get caching . We want to use newCache , but it has
type instance RuleResult GhcSessionIO = IdeGhcSession
data IdeGhcSession = IdeGhcSession
{ loadSessionFun :: FilePath -> IO (IdeResult HscEnvEq, [FilePath])
^ Returns the Ghc session and the cradle dependencies
, sessionVersion :: !Int
}
instance Show IdeGhcSession where show _ = "IdeGhcSession"
instance NFData IdeGhcSession where rnf !_ = ()
data GhcSessionIO = GhcSessionIO deriving (Eq, Show, Typeable, Generic)
instance Hashable GhcSessionIO
instance NFData GhcSessionIO
makeLensesWith
(lensRules & lensField .~ mappingNamer (pure . (++ "L")))
''Splices
|
9926a800c3be8c299e395cf07e072b33c79faa07a26ae8654b25b55eabb3af14 | g000001/MacLISP-compat | ARYFIL.lisp | ;;; -*-LISP-*-
;;; (LIVE-ARRAYS <kind>) returns a list of all allocated arrays (not
;;; currently considered "dead" space). Its argument permits selecting
only certain kinds of arrays : OBARRAY , READTABLE , FILE , T , NIL ,
;;; FIXNUM, or FLONUM. An argument of ALL gets all non-dead arrays.
;;; In addition, an argument of OPEN-FILE selects only open files.
;;; (OPEN-FILES) returns a list of all open file objects
(defun (OPEN-FILES macro) (()) `(LIVE-ARRAYS 'OPEN-FILE))
(defun LIVE-ARRAYS (kind)
(or kind (setq kind 'T))
(and (not (memq kind '(OBARRAY READTABLE FILE FIXNUM FLONUM T NIL)))
(not (eq kind 'OPEN-FILE))
(setq kind 'ALL))
(let ((dedsar (getddtsym 'DEDSAR))
(gcmkl (munkam (examine (getddtsym 'GCMKL))))
(open-file-flag (cond ((eq kind 'OPEN-FILE)
(setq kind 'FILE)
'T))))
(do ((l gcmkl (cddr l)) (z) )
((null l) (nreverse z))
(and (not (eq (car l) dedsar))
(cond ((eq kind 'ALL))
((eq kind (car (arraydims (car l))))
(or (not open-file-flag)
(status filemode (car l)))))
(push (car l) z)))))
| null | https://raw.githubusercontent.com/g000001/MacLISP-compat/a147d09b98dca4d7c089424c3cbaf832d2fd857a/ARYFIL.lisp | lisp | -*-LISP-*-
(LIVE-ARRAYS <kind>) returns a list of all allocated arrays (not
currently considered "dead" space). Its argument permits selecting
FIXNUM, or FLONUM. An argument of ALL gets all non-dead arrays.
In addition, an argument of OPEN-FILE selects only open files.
(OPEN-FILES) returns a list of all open file objects |
only certain kinds of arrays : OBARRAY , READTABLE , FILE , T , NIL ,
(defun (OPEN-FILES macro) (()) `(LIVE-ARRAYS 'OPEN-FILE))
(defun LIVE-ARRAYS (kind)
(or kind (setq kind 'T))
(and (not (memq kind '(OBARRAY READTABLE FILE FIXNUM FLONUM T NIL)))
(not (eq kind 'OPEN-FILE))
(setq kind 'ALL))
(let ((dedsar (getddtsym 'DEDSAR))
(gcmkl (munkam (examine (getddtsym 'GCMKL))))
(open-file-flag (cond ((eq kind 'OPEN-FILE)
(setq kind 'FILE)
'T))))
(do ((l gcmkl (cddr l)) (z) )
((null l) (nreverse z))
(and (not (eq (car l) dedsar))
(cond ((eq kind 'ALL))
((eq kind (car (arraydims (car l))))
(or (not open-file-flag)
(status filemode (car l)))))
(push (car l) z)))))
|
5067c4300372e3ed9fa199d152246555af41fe33a83ddf381a1939b7306d5603 | mirage/charrua | dhcp_ipv4.ml | open Lwt.Infix
module Make(R : Mirage_random.S) (C : Mirage_clock.MCLOCK) (Time : Mirage_time.S) (Network : Mirage_net.S) (E : Ethernet.S) (Arp : Arp.S) = struct
(* for now, just wrap a static ipv4 *)
module DHCP = Dhcp_client_mirage.Make(R)(Time)(Network)
include Static_ipv4.Make(R)(C)(E)(Arp)
let connect net ethernet arp =
DHCP.connect net >>= fun dhcp ->
Lwt_stream.last_new dhcp >>= fun (cidr, gateway) ->
connect ~cidr ?gateway ethernet arp
end
| null | https://raw.githubusercontent.com/mirage/charrua/a06207ea4d174697c8a0226865f0390584aa8433/client/mirage/dhcp_ipv4.ml | ocaml | for now, just wrap a static ipv4 | open Lwt.Infix
module Make(R : Mirage_random.S) (C : Mirage_clock.MCLOCK) (Time : Mirage_time.S) (Network : Mirage_net.S) (E : Ethernet.S) (Arp : Arp.S) = struct
module DHCP = Dhcp_client_mirage.Make(R)(Time)(Network)
include Static_ipv4.Make(R)(C)(E)(Arp)
let connect net ethernet arp =
DHCP.connect net >>= fun dhcp ->
Lwt_stream.last_new dhcp >>= fun (cidr, gateway) ->
connect ~cidr ?gateway ethernet arp
end
|
fffd761bfc237cce5d5eee476925f999c8f728119bf58afe77bda2b5588c58c1 | ytomino/headmaster | stringSet.ml | include Set.Make (String);;
| null | https://raw.githubusercontent.com/ytomino/headmaster/6c52709c7355b6418d5094f2b96da168fe276bae/source/stringSet.ml | ocaml | include Set.Make (String);;
| |
f0acc35be98c4d71238e6b5882db11db982007d27e317e08c281b2a3b2563e5c | janestreet/virtual_dom | global_listeners.mli | open! Core
open! Js_of_ocaml
(** Hooks to set events listeners on [window]. This is needed as if we only set
them on individual elements we will miss ones that happen outside of the viewport
-mouse-events-that-work-even-when-mouse-is-moved-outside-the-window *)
(** Mouse-event handlers *)
val mouseup : (Dom_html.mouseEvent Js.t -> unit Ui_effect.t) -> Attr.t
val mousemove : (Dom_html.mouseEvent Js.t -> unit Ui_effect.t) -> Attr.t
val click : (Dom_html.mouseEvent Js.t -> unit Ui_effect.t) -> Attr.t
val contextmenu : (Dom_html.mouseEvent Js.t -> unit Ui_effect.t) -> Attr.t
(** Keyboard-event handlers *)
val keydown : (Dom_html.keyboardEvent Js.t -> unit Ui_effect.t) -> Attr.t
(** Other event handlers *)
val visibilitychange : (Dom_html.event Js.t -> unit Ui_effect.t) -> Attr.t
val beforeunload
: (Dom_html.event Js.t -> [ `Show_warning | `Do_nothing ] Ui_effect.t)
-> Attr.t
module For_testing : sig
val mouseup_type_id : (Dom_html.mouseEvent Js.t -> unit Ui_effect.t) Type_equal.Id.t
val mousemove_type_id : (Dom_html.mouseEvent Js.t -> unit Ui_effect.t) Type_equal.Id.t
val click_type_id : (Dom_html.mouseEvent Js.t -> unit Ui_effect.t) Type_equal.Id.t
val contextmenu_type_id : (Dom_html.mouseEvent Js.t -> unit Ui_effect.t) Type_equal.Id.t
val keydown_type_id : (Dom_html.keyboardEvent Js.t -> unit Ui_effect.t) Type_equal.Id.t
val visibilitychange_type_id : (Dom_html.event Js.t -> unit Ui_effect.t) Type_equal.Id.t
val beforeunload_type_id : (Dom_html.event Js.t -> unit Ui_effect.t) Type_equal.Id.t
end
| null | https://raw.githubusercontent.com/janestreet/virtual_dom/3dd6e8080bdc54fe32e1e9701700ad27df81bf83/src/global_listeners.mli | ocaml | * Hooks to set events listeners on [window]. This is needed as if we only set
them on individual elements we will miss ones that happen outside of the viewport
-mouse-events-that-work-even-when-mouse-is-moved-outside-the-window
* Mouse-event handlers
* Keyboard-event handlers
* Other event handlers | open! Core
open! Js_of_ocaml
val mouseup : (Dom_html.mouseEvent Js.t -> unit Ui_effect.t) -> Attr.t
val mousemove : (Dom_html.mouseEvent Js.t -> unit Ui_effect.t) -> Attr.t
val click : (Dom_html.mouseEvent Js.t -> unit Ui_effect.t) -> Attr.t
val contextmenu : (Dom_html.mouseEvent Js.t -> unit Ui_effect.t) -> Attr.t
val keydown : (Dom_html.keyboardEvent Js.t -> unit Ui_effect.t) -> Attr.t
val visibilitychange : (Dom_html.event Js.t -> unit Ui_effect.t) -> Attr.t
val beforeunload
: (Dom_html.event Js.t -> [ `Show_warning | `Do_nothing ] Ui_effect.t)
-> Attr.t
module For_testing : sig
val mouseup_type_id : (Dom_html.mouseEvent Js.t -> unit Ui_effect.t) Type_equal.Id.t
val mousemove_type_id : (Dom_html.mouseEvent Js.t -> unit Ui_effect.t) Type_equal.Id.t
val click_type_id : (Dom_html.mouseEvent Js.t -> unit Ui_effect.t) Type_equal.Id.t
val contextmenu_type_id : (Dom_html.mouseEvent Js.t -> unit Ui_effect.t) Type_equal.Id.t
val keydown_type_id : (Dom_html.keyboardEvent Js.t -> unit Ui_effect.t) Type_equal.Id.t
val visibilitychange_type_id : (Dom_html.event Js.t -> unit Ui_effect.t) Type_equal.Id.t
val beforeunload_type_id : (Dom_html.event Js.t -> unit Ui_effect.t) Type_equal.Id.t
end
|
4761b5cf71a90744b5a38019b5a749d6c50f52635877e971f7a4fc268a990f99 | bytekid/mkbtt | mascott.ml | module Main = Mascottx.Main;;
module Kernel = struct
let execute = Main.execute
let execute_with = Main.execute_with
end
| null | https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/mascott/src/mascott.ml | ocaml | module Main = Mascottx.Main;;
module Kernel = struct
let execute = Main.execute
let execute_with = Main.execute_with
end
| |
1b78fb159483980d122f3679f73a8c789442ba46daf58a577ed434ce3589b805 | batebobo/fp1819 | 5-append.rkt | #lang racket
(require rackunit)
(require rackunit/text-ui)
; Искаме да залепим два списъка
(define tests
(test-suite "Append tests"
(test-case "" (check-equal? (my-append '(1 2 3) '()) '(1 2 3)))
(test-case "" (check-equal? (my-append '() '(1 2 3)) '(1 2 3)))
(test-case "" (check-equal? (my-append '(4 5 6) '(1 2 3)) '(4 5 6 1 2 3)))
)
)
(run-tests tests 'verbose)
| null | https://raw.githubusercontent.com/batebobo/fp1819/2061b7e62a1a9ade3a5fff9753f9fe0da5684275/scheme/4/5-append.rkt | racket | Искаме да залепим два списъка | #lang racket
(require rackunit)
(require rackunit/text-ui)
(define tests
(test-suite "Append tests"
(test-case "" (check-equal? (my-append '(1 2 3) '()) '(1 2 3)))
(test-case "" (check-equal? (my-append '() '(1 2 3)) '(1 2 3)))
(test-case "" (check-equal? (my-append '(4 5 6) '(1 2 3)) '(4 5 6 1 2 3)))
)
)
(run-tests tests 'verbose)
|
f5c2c7a764e4f02233f8f8d1cf8325e815b9f251e2af05642f1b950a999e45d7 | Zulu-Inuoe/clution | static-vectors-tests.lisp | ;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*-
;;;
;;; --- FiveAM Tests
;;;
(defpackage :static-vectors/test
(:use #:cl #:static-vectors #:fiveam)
(:import-from #:static-vectors #:cmfuncall))
(in-package :static-vectors/test)
(in-suite* :static-vectors)
(test (make-static-vector.plain.notinline
:compile-at :definition-time)
(locally
(declare (notinline make-static-vector))
(let ((v (make-static-vector 5)))
(is (equal 5 (length v))))))
(test (make-static-vector.plain.compiler-macro.noerror
:compile-at :definition-time)
(finishes
(compile nil '(lambda ()
(declare (optimize (speed 3) (debug 1)))
(make-static-vector 5)))))
(test (make-static-vector.plain.inline
:depends-on make-static-vector.plain.compiler-macro.noerror)
(let ((v (cmfuncall make-static-vector 5)))
(is (equal 5 (length v)))))
(test (make-static-vector.initial-element.notinline
:compile-at :definition-time)
(locally
(declare (notinline make-static-vector))
(let ((v (make-static-vector 5 :initial-element 3)))
(is (equal 5 (length v)))
(is (not (find 3 v :test-not #'=))))))
(test (make-static-vector.initial-element.compiler-macro.noerror
:compile-at :definition-time)
(finishes
(compile nil '(lambda ()
(cmfuncall make-static-vector 5 :initial-element 3)))))
(test (make-static-vector.initial-element.inline
:depends-on make-static-vector.initial-element.compiler-macro.noerror)
(let ((v (cmfuncall make-static-vector 5 :initial-element 3)))
(is (equal 5 (length v)))
(is (not (find 3 v :test-not #'=)))))
(test (make-static-vector.initial-contents.notinline
:compile-at :definition-time)
(locally
(declare (notinline make-static-vector))
(let ((v (make-static-vector 5 :initial-contents '(1 2 3 4 5))))
(is (equal 5 (length v)))
(is (not (mismatch v '(1 2 3 4 5)))))))
(test (make-static-vector.initial-contents.compiler-macro.noerror
:compile-at :definition-time)
(finishes
(compile nil '(lambda ()
(cmfuncall make-static-vector 5 :initial-contents '(1 2 3 4 5))))))
(test (make-static-vector.initial-contents.inline
:depends-on make-static-vector.initial-contents.compiler-macro.noerror)
(let ((v (cmfuncall make-static-vector 5 :initial-contents '(1 2 3 4 5))))
(is (equal 5 (length v)))
(is (not (mismatch v '(1 2 3 4 5))))))
(test (make-static-vector.initial-element-and-contents.compiler-macro.error
:compile-at :definition-time)
(multiple-value-bind (function warnp failp)
(ignore-errors
(compile nil '(lambda ()
(cmfuncall make-static-vector 5 :initial-element 3
:initial-contents '(1 2 3 4 5)))))
(declare (ignore warnp))
(is-false (and function (not failp)))))
(test (with-static-vector.defaults
:compile-at :definition-time)
(with-static-vector (v 5)
(is (= 5 (length v)))
(is (equal '(unsigned-byte 8) (array-element-type v)))))
(test (with-static-vector.element-type
:compile-at :definition-time)
(with-static-vector (v 3 :element-type '(unsigned-byte 16))
(is (= 3 (length v)))
(is (equal '(unsigned-byte 16) (array-element-type v)))))
(test (with-static-vector.initial-element
:compile-at :definition-time)
(with-static-vector (v 3 :initial-element 7)
(is (= 3 (length v)))
(is (equalp v #(7 7 7)))))
(test (with-static-vector.initial-contents
:compile-at :definition-time)
(with-static-vector (v 3 :initial-contents '(3 14 29))
(is (= 3 (length v)))
(is (equalp v #(3 14 29)))))
(test (with-static-vectors.initialization
:compile-at :definition-time)
(with-static-vectors ((v1 3 :initial-element 7)
(v2 5 :initial-contents '(1 2 3 4 5)))
(is (equalp v1 #(7 7 7)))
(is (equalp v2 #(1 2 3 4 5)))))
| null | https://raw.githubusercontent.com/Zulu-Inuoe/clution/b72f7afe5f770ff68a066184a389c23551863f7f/cl-clution/qlfile-libs/static-vectors-v1.8.3/tests/static-vectors-tests.lisp | lisp | -*- Mode: Lisp; indent-tabs-mode: nil -*-
--- FiveAM Tests
|
(defpackage :static-vectors/test
(:use #:cl #:static-vectors #:fiveam)
(:import-from #:static-vectors #:cmfuncall))
(in-package :static-vectors/test)
(in-suite* :static-vectors)
(test (make-static-vector.plain.notinline
:compile-at :definition-time)
(locally
(declare (notinline make-static-vector))
(let ((v (make-static-vector 5)))
(is (equal 5 (length v))))))
(test (make-static-vector.plain.compiler-macro.noerror
:compile-at :definition-time)
(finishes
(compile nil '(lambda ()
(declare (optimize (speed 3) (debug 1)))
(make-static-vector 5)))))
(test (make-static-vector.plain.inline
:depends-on make-static-vector.plain.compiler-macro.noerror)
(let ((v (cmfuncall make-static-vector 5)))
(is (equal 5 (length v)))))
(test (make-static-vector.initial-element.notinline
:compile-at :definition-time)
(locally
(declare (notinline make-static-vector))
(let ((v (make-static-vector 5 :initial-element 3)))
(is (equal 5 (length v)))
(is (not (find 3 v :test-not #'=))))))
(test (make-static-vector.initial-element.compiler-macro.noerror
:compile-at :definition-time)
(finishes
(compile nil '(lambda ()
(cmfuncall make-static-vector 5 :initial-element 3)))))
(test (make-static-vector.initial-element.inline
:depends-on make-static-vector.initial-element.compiler-macro.noerror)
(let ((v (cmfuncall make-static-vector 5 :initial-element 3)))
(is (equal 5 (length v)))
(is (not (find 3 v :test-not #'=)))))
(test (make-static-vector.initial-contents.notinline
:compile-at :definition-time)
(locally
(declare (notinline make-static-vector))
(let ((v (make-static-vector 5 :initial-contents '(1 2 3 4 5))))
(is (equal 5 (length v)))
(is (not (mismatch v '(1 2 3 4 5)))))))
(test (make-static-vector.initial-contents.compiler-macro.noerror
:compile-at :definition-time)
(finishes
(compile nil '(lambda ()
(cmfuncall make-static-vector 5 :initial-contents '(1 2 3 4 5))))))
(test (make-static-vector.initial-contents.inline
:depends-on make-static-vector.initial-contents.compiler-macro.noerror)
(let ((v (cmfuncall make-static-vector 5 :initial-contents '(1 2 3 4 5))))
(is (equal 5 (length v)))
(is (not (mismatch v '(1 2 3 4 5))))))
(test (make-static-vector.initial-element-and-contents.compiler-macro.error
:compile-at :definition-time)
(multiple-value-bind (function warnp failp)
(ignore-errors
(compile nil '(lambda ()
(cmfuncall make-static-vector 5 :initial-element 3
:initial-contents '(1 2 3 4 5)))))
(declare (ignore warnp))
(is-false (and function (not failp)))))
(test (with-static-vector.defaults
:compile-at :definition-time)
(with-static-vector (v 5)
(is (= 5 (length v)))
(is (equal '(unsigned-byte 8) (array-element-type v)))))
(test (with-static-vector.element-type
:compile-at :definition-time)
(with-static-vector (v 3 :element-type '(unsigned-byte 16))
(is (= 3 (length v)))
(is (equal '(unsigned-byte 16) (array-element-type v)))))
(test (with-static-vector.initial-element
:compile-at :definition-time)
(with-static-vector (v 3 :initial-element 7)
(is (= 3 (length v)))
(is (equalp v #(7 7 7)))))
(test (with-static-vector.initial-contents
:compile-at :definition-time)
(with-static-vector (v 3 :initial-contents '(3 14 29))
(is (= 3 (length v)))
(is (equalp v #(3 14 29)))))
(test (with-static-vectors.initialization
:compile-at :definition-time)
(with-static-vectors ((v1 3 :initial-element 7)
(v2 5 :initial-contents '(1 2 3 4 5)))
(is (equalp v1 #(7 7 7)))
(is (equalp v2 #(1 2 3 4 5)))))
|
e41dae8b9bf7c6cb606bb75a505493caba4cab8899109892a09fdfa8c9333ddf | jnear/compiler-construction-assignments | r2_2.rkt | (let ([x #f])
42)
| null | https://raw.githubusercontent.com/jnear/compiler-construction-assignments/17a1edbd59627341622203056180d9af7830756d/tests/r2_2.rkt | racket | (let ([x #f])
42)
| |
bf2c7cdf4d426563fca4f1cbbfe9cc4a01520a75bd6f7b7133fb892378cf684d | karamellpelle/grid | Drawer.hs | grid is a game written in Haskell
Copyright ( C ) 2018
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
You should have received a copy of the GNU General Public License
-- along with grid. If not, see </>.
--
module Game.Output.Drawer
(
Drawer (..),
) where
import Game.MEnv
import OpenGL
-- we parameterize the type, in order to differate between drawers using
-- different shaders
data Drawer shader =
Drawer
{
drawerDraw :: Tick -> MEnv' (),
drawerStep :: Tick -> MEnv' (Maybe Drawer)
}
| null | https://raw.githubusercontent.com/karamellpelle/grid/56729e63ed6404fd6cfd6d11e73fa358f03c386f/source/Game/Output/Drawer.hs | haskell |
This file is part of grid.
grid is free software: you can redistribute it and/or modify
(at your option) any later version.
grid is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with grid. If not, see </>.
we parameterize the type, in order to differate between drawers using
different shaders | grid is a game written in Haskell
Copyright ( C ) 2018
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
module Game.Output.Drawer
(
Drawer (..),
) where
import Game.MEnv
import OpenGL
data Drawer shader =
Drawer
{
drawerDraw :: Tick -> MEnv' (),
drawerStep :: Tick -> MEnv' (Maybe Drawer)
}
|
4754eb9d92ca76280eb4136643b2b52aef69bb5fc056fe2f422525ad5a1e2563 | herd/herdtools7 | CTestHash.ml | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2014 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
(**********)
Digest
(**********)
module type Input = sig
type code
val dump_prog : bool -> code -> string list
end
module Make(P:Input)
= struct
open Printf
open MiscParser
let verbose = 0
let debug tag s =
if verbose > 0 then eprintf "%s:\n%s\n" tag s
else ()
(* Code digest *)
let digest_code code =
let code = List.map (P.dump_prog true) code in
let pp = Misc.string_of_prog code in
debug "CODE" pp ;
Digest.string pp
(* Observed locations digest *)
let digest_observed locs =
let locs = MiscParser.RLocSet.elements locs in
let pp =
String.concat "; "
(List.map (ConstrGen.dump_rloc dump_location) locs) in
debug "LOCS" pp ;
Digest.string pp
let digest info init code observed =
Digest.to_hex
(Digest.string
(String.concat ""
[TestHash.digest_info info; TestHash.digest_init debug init;
digest_code code; digest_observed observed;]))
end
| null | https://raw.githubusercontent.com/herd/herdtools7/8ceb2e10d07e04cfcced6e13886bca3fff5358d5/lib/CTestHash.ml | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
**************************************************************************
********
********
Code digest
Observed locations digest | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2014 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
Digest
module type Input = sig
type code
val dump_prog : bool -> code -> string list
end
module Make(P:Input)
= struct
open Printf
open MiscParser
let verbose = 0
let debug tag s =
if verbose > 0 then eprintf "%s:\n%s\n" tag s
else ()
let digest_code code =
let code = List.map (P.dump_prog true) code in
let pp = Misc.string_of_prog code in
debug "CODE" pp ;
Digest.string pp
let digest_observed locs =
let locs = MiscParser.RLocSet.elements locs in
let pp =
String.concat "; "
(List.map (ConstrGen.dump_rloc dump_location) locs) in
debug "LOCS" pp ;
Digest.string pp
let digest info init code observed =
Digest.to_hex
(Digest.string
(String.concat ""
[TestHash.digest_info info; TestHash.digest_init debug init;
digest_code code; digest_observed observed;]))
end
|
b04eb9d842630a2907ab128145617765abf3a9a20b94ed1646a152fc26931296 | fukamachi/clozure-cl | sequence-utils.lisp | -*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Base : 10 ; Package : cl - user -*-
;;;; ***********************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name: sequence-utils.lisp
Version : 0.2
;;;; Project: utilities
;;;; Purpose: utilities for working with sequences
;;;;
;;;; ***********************************************************************
(in-package "CCL")
;;; -----------------------------------------------------------------
;;; splitting sequences
;;; -----------------------------------------------------------------
Split a sequence SEQ at each point where TEST is true
DIR should be one of : BEFORE , : AFTER or : ELIDE
(defun split-if (test seq &optional (dir :before))
(remove-if
#'(lambda (x) (equal x (subseq seq 0 0)))
(loop for start fixnum = 0
then (if (eq dir :before) stop (the fixnum (1+ (the fixnum stop))))
while (< start (length seq))
for stop = (position-if
test seq
:start (if (eq dir :elide) start (the fixnum (1+ start))))
collect (subseq
seq start
(if (and stop (eq dir :after))
(the fixnum (1+ (the fixnum stop)))
stop))
while stop)))
(defun split-if-char (char seq &optional dir)
(split-if #'(lambda (ch) (eq ch char)) seq dir))
(defmethod split-lines ((text string))
(delete-if (lambda (x) (string= x ""))
(mapcar (lambda (s)
(string-trim '(#\return #\newline) s))
(split-if (lambda (c) (member c '(#\return #\newline) :test #'char=))
text))))
;;; -----------------------------------------------------------------
;;; matching subsequences
;;; -----------------------------------------------------------------
(defun match-subsequence (subseq seq &key (test #'eql) (start 0))
(let ((max-index (1- (length seq))))
(block matching
;; search for mismatches
(dotimes (i (length subseq))
(let ((pos (+ start i)))
(when (or (> pos max-index)
(not (funcall test (elt seq pos)
(elt subseq i))))
(return-from matching nil))))
;; no mismatches found; return true
(return-from matching t))))
(defun %find-matching-subsequence-backward (subseq seq &key (test #'eql) (start 0) end)
(let ((end (or end (length seq)))
(pos end)
(min-index (or start 0)))
(block finding
(dotimes (i (- (length seq) start))
(setf pos (- end i))
(if (<= pos min-index)
(return-from finding nil)
(when (match-subsequence subseq seq :test test :start pos)
(return-from finding pos))))
nil)))
(defun %find-matching-subsequence-forward (subseq seq &key (test #'eql) (start 0) end)
(let ((pos start)
(max-index (or end (length seq))))
(block finding
(dotimes (i (- (length seq) start))
(setf pos (+ start i))
(if (>= pos max-index)
(return-from finding nil)
(when (match-subsequence subseq seq :test test :start pos)
(return-from finding pos))))
nil)))
(defun find-matching-subsequence (subseq seq &key (test #'eql) (start 0) end from-end)
(if from-end
(%find-matching-subsequence-backward subseq seq :test test :start start :end end)
(%find-matching-subsequence-forward subseq seq :test test :start start :end end))) | null | https://raw.githubusercontent.com/fukamachi/clozure-cl/4b0c69452386ae57b08984ed815d9b50b4bcc8a2/library/sequence-utils.lisp | lisp | Syntax : ANSI - Common - Lisp ; Base : 10 ; Package : cl - user -*-
***********************************************************************
FILE IDENTIFICATION
Name: sequence-utils.lisp
Project: utilities
Purpose: utilities for working with sequences
***********************************************************************
-----------------------------------------------------------------
splitting sequences
-----------------------------------------------------------------
-----------------------------------------------------------------
matching subsequences
-----------------------------------------------------------------
search for mismatches
no mismatches found; return true | Version : 0.2
(in-package "CCL")
Split a sequence SEQ at each point where TEST is true
DIR should be one of : BEFORE , : AFTER or : ELIDE
(defun split-if (test seq &optional (dir :before))
(remove-if
#'(lambda (x) (equal x (subseq seq 0 0)))
(loop for start fixnum = 0
then (if (eq dir :before) stop (the fixnum (1+ (the fixnum stop))))
while (< start (length seq))
for stop = (position-if
test seq
:start (if (eq dir :elide) start (the fixnum (1+ start))))
collect (subseq
seq start
(if (and stop (eq dir :after))
(the fixnum (1+ (the fixnum stop)))
stop))
while stop)))
(defun split-if-char (char seq &optional dir)
(split-if #'(lambda (ch) (eq ch char)) seq dir))
(defmethod split-lines ((text string))
(delete-if (lambda (x) (string= x ""))
(mapcar (lambda (s)
(string-trim '(#\return #\newline) s))
(split-if (lambda (c) (member c '(#\return #\newline) :test #'char=))
text))))
(defun match-subsequence (subseq seq &key (test #'eql) (start 0))
(let ((max-index (1- (length seq))))
(block matching
(dotimes (i (length subseq))
(let ((pos (+ start i)))
(when (or (> pos max-index)
(not (funcall test (elt seq pos)
(elt subseq i))))
(return-from matching nil))))
(return-from matching t))))
(defun %find-matching-subsequence-backward (subseq seq &key (test #'eql) (start 0) end)
(let ((end (or end (length seq)))
(pos end)
(min-index (or start 0)))
(block finding
(dotimes (i (- (length seq) start))
(setf pos (- end i))
(if (<= pos min-index)
(return-from finding nil)
(when (match-subsequence subseq seq :test test :start pos)
(return-from finding pos))))
nil)))
(defun %find-matching-subsequence-forward (subseq seq &key (test #'eql) (start 0) end)
(let ((pos start)
(max-index (or end (length seq))))
(block finding
(dotimes (i (- (length seq) start))
(setf pos (+ start i))
(if (>= pos max-index)
(return-from finding nil)
(when (match-subsequence subseq seq :test test :start pos)
(return-from finding pos))))
nil)))
(defun find-matching-subsequence (subseq seq &key (test #'eql) (start 0) end from-end)
(if from-end
(%find-matching-subsequence-backward subseq seq :test test :start start :end end)
(%find-matching-subsequence-forward subseq seq :test test :start start :end end))) |
04f7e8c98c27ccad05f583d87c42da0463034b4680612d7297175f6c6a9349a0 | janestreet/vcaml | simple_editor.ml | open Core
open Async
open Vcaml
open Deferred.Or_error.Let_syntax
(* Simple Vcaml plugin to create a new buffer/window which the user can use as a
scratchpad, with no vim bindings. The plugin is killed on window close.
The editor only supports lowercase/uppercase letters + space/enter/backspace. *)
let of_ascii_list ascii_chars =
ascii_chars |> List.map ~f:(Fn.compose String.of_char Char.of_int_exn)
;;
let lowercase = of_ascii_list (List.init 26 ~f:(( + ) 97))
let uppercase = of_ascii_list (List.init 26 ~f:(( + ) 65))
let alphabet = lowercase @ uppercase
module Special_characters = struct
let space = "space"
let backspace = "bs"
let enter = "cr"
let all = [ space; backspace; enter ]
end
module State = struct
type t =
{ buffer : Buffer.t Set_once.t
; window : Window.t Set_once.t
}
[@@deriving sexp_of]
end
module type S = Vcaml_plugin.Persistent.S with type state := State.t
include Vcaml_plugin.Persistent.Make (struct
let name = "simple-editor"
let description = "A simple editor plugin for Neovim"
type state = State.t [@@deriving sexp_of]
let init_state () = { State.buffer = Set_once.create (); window = Set_once.create () }
let set_modifiable buffer value =
Buffer.set_option (Id buffer) ~scope:`Local ~name:"modifiable" ~type_:Boolean ~value
;;
let get_split_window =
let%map.Api_call.Or_error () = Nvim.command "split"
and window = Nvim.get_current_win in
window
;;
let shutdown_plugin_when_buffer_is_closed ~window ~buffer ~channel =
let shutdown_on_leave =
Printf.sprintf
"autocmd BufWinLeave <buffer> silent! call rpcrequest(%d, 'shutdown')"
channel
in
Api_call.Or_error.all_unit
[ Nvim.set_current_win window
; Nvim.set_current_buf buffer
; Nvim.command shutdown_on_leave
]
;;
let add_vim_binding ~channel ~key_bind ~rpc_name =
Nvim.command
(Printf.sprintf
"nnoremap <silent> <nowait> <buffer> %s <Cmd>call rpcrequest(%d, \"%s\")<CR>"
key_bind
channel
rpc_name)
;;
let add_key_listener ~channel key = add_vim_binding ~channel ~key_bind:key ~rpc_name:key
let add_special_character_listener ~channel key =
add_vim_binding ~channel ~key_bind:(Printf.sprintf "<%s>" key) ~rpc_name:key
;;
let add_key_listeners_api_call channel =
let typable_api_call = alphabet |> List.map ~f:(add_key_listener ~channel) in
let special_api_call =
Special_characters.all |> List.map ~f:(add_special_character_listener ~channel)
in
typable_api_call @ special_api_call |> Api_call.Or_error.all_unit
;;
let set_virtualedit_inside_buffer =
let code =
{| augroup simple_editor_save_virtualedit
autocmd! * <buffer>
autocmd BufEnter <buffer> let b:saved_virtualedit = &virtualedit
autocmd BufEnter <buffer> set virtualedit=onemore
autocmd BufLeave <buffer> let &virtualedit = b:saved_virtualedit
augroup END
let b:saved_virtualedit = &virtualedit
set virtualedit=onemore |}
in
Nvim.source code |> Api_call.Or_error.ignore_m
;;
let on_startup client state ~shutdown:_ =
let channel = Client.channel client in
let%bind buffer =
Buffer.find_by_name_or_create ~name:"simple-editor" |> run_join [%here] client
in
let%bind window = run_join [%here] client get_split_window in
let%bind () =
shutdown_plugin_when_buffer_is_closed ~window ~buffer ~channel
|> run_join [%here] client
in
let%bind () = add_key_listeners_api_call channel |> run_join [%here] client in
let%bind () = set_virtualedit_inside_buffer |> run_join [%here] client in
let%bind () =
[ set_modifiable buffer false
; Buffer.set_option
(Id buffer)
~scope:`Local
~name:"buftype"
~type_:String
~value:"nofile"
;
Window.Untested.set_option
(Id window)
~scope:`Local
~name:"list"
~type_:Boolean
~value:false
]
|> Api_call.Or_error.all_unit
|> run_join [%here] client
in
Set_once.set_exn state.State.buffer [%here] buffer;
Set_once.set_exn state.State.window [%here] window;
return ()
;;
let on_error = `Raise
let vimscript_notify_fn = None
let on_shutdown _client _state = return ()
let get_nth_line ~client ~buffer n =
Buffer.get_lines (Id buffer) ~start:(n - 1) ~end_:n ~strict_indexing:true
|> run_join [%here] client
;;
let with_modifiable ~buffer ~api_call =
let%map.Api_call unlock_buf_or_err = set_modifiable buffer true
and api_res_or_err = api_call
and lock_buf_or_err = set_modifiable buffer false in
let%bind.Or_error () = Or_error.all_unit [ unlock_buf_or_err; lock_buf_or_err ] in
api_res_or_err
;;
let set_lines ~client ~buffer ~start_at ~num_lines ~content =
with_modifiable
~buffer
~api_call:
(Buffer.set_lines
(Id buffer)
~start:start_at
~end_:(start_at + num_lines)
~replacement:content
~strict_indexing:false)
|> run_join [%here] client
;;
let set_line ~client ~buffer ~content ~row =
set_lines ~client ~buffer ~start_at:(row - 1) ~num_lines:1 ~content
;;
let set_cursor ~client ~window ~row ~col =
Window.set_cursor (Id window) { row; col } |> run_join [%here] client
;;
let split_string_at st i =
match i with
| 0 -> "", st
| i -> String.slice st 0 i, String.slice st i 0
;;
let add_newline_at_mark client buffer window { Position.One_indexed_row.row; col } =
let%bind line = get_nth_line ~client ~buffer row in
let first_line, second_line = split_string_at (List.nth_exn line 0) col in
let%bind () = set_line ~client ~buffer ~content:[ first_line; second_line ] ~row in
set_cursor ~client ~window ~row:(row + 1) ~col:0
;;
let insert_character_in_line col character line =
let before, after = split_string_at line col in
String.concat [ before; character; after ]
;;
let set_character_at_mark
character
client
buffer
window
{ Position.One_indexed_row.row; col }
=
let%bind line = get_nth_line ~client ~buffer row in
let new_line = line |> List.map ~f:(insert_character_in_line col character) in
let%bind () = set_line ~client ~buffer ~content:new_line ~row in
set_cursor ~client ~window ~row ~col:(col + 1)
;;
let delete_from_beginning_of_line client buffer window row =
let%bind curr_line = get_nth_line ~client ~buffer row in
let%bind prev_line = get_nth_line ~client ~buffer (row - 1) in
let result = String.concat (prev_line @ curr_line) in
let%bind () =
set_lines ~client ~buffer ~start_at:(row - 2) ~num_lines:2 ~content:[ result ]
in
set_cursor
~client
~window
~row:(row - 1)
~col:(String.length (List.nth_exn prev_line 0))
;;
let delete_in_line client buffer window row col =
let%bind line = get_nth_line ~client ~buffer row in
let new_line =
line
|> List.map ~f:String.to_list
|> List.map ~f:(List.filteri ~f:(fun i _ -> i <> col - 1))
|> List.map ~f:String.of_char_list
in
let%bind () = set_line ~client ~buffer ~content:new_line ~row in
set_cursor ~client ~window ~row ~col:(col - 1)
;;
let delete_character_at_mark client buffer window { Position.One_indexed_row.row; col } =
match row, col with
| 1, 0 -> Deferred.Or_error.return ()
| r, 0 -> delete_from_beginning_of_line client buffer window r
| r, c -> delete_in_line client buffer window r c
;;
let handle_edit_request ~f client { State.buffer; window } ~shutdown:_ =
let buffer = Set_once.get_exn buffer [%here] in
let window = Set_once.get_exn window [%here] in
let%bind mark = Window.get_cursor (Id window) |> run_join [%here] client in
f client buffer window mark
;;
let handle_enter_request = handle_edit_request ~f:add_newline_at_mark
let handle_key_rpc_request key = handle_edit_request ~f:(set_character_at_mark key)
let handle_backspace_request = handle_edit_request ~f:delete_character_at_mark
let create_rpc_handler ~rpc_name ~handling_fn =
Vcaml_plugin.Persistent.Rpc.create_sync
~name:rpc_name
~type_:Defun.Ocaml.Sync.(return Nil)
~f:(fun state ~shutdown ~keyboard_interrupted:_ ~client ->
handling_fn client state ~shutdown)
;;
let create_key_rpc_handler ~key ~str_to_insert =
create_rpc_handler ~rpc_name:key ~handling_fn:(handle_key_rpc_request str_to_insert)
;;
let call_shutdown _client _state ~shutdown =
shutdown ();
Deferred.Or_error.return ()
;;
let alphabet_handlers =
List.map alphabet ~f:(fun key -> create_key_rpc_handler ~key ~str_to_insert:key)
;;
let space_handler =
create_key_rpc_handler ~key:Special_characters.space ~str_to_insert:" "
;;
let enter_handler =
create_rpc_handler
~rpc_name:Special_characters.enter
~handling_fn:handle_enter_request
;;
let backspace_handler =
create_rpc_handler
~rpc_name:Special_characters.backspace
~handling_fn:handle_backspace_request
;;
let shutdown_handler =
create_rpc_handler ~rpc_name:"shutdown" ~handling_fn:call_shutdown
;;
let rpc_handlers =
alphabet_handlers
@ [ space_handler; enter_handler; backspace_handler; shutdown_handler ]
;;
end)
| null | https://raw.githubusercontent.com/janestreet/vcaml/64d205c2d6eee4a7e57abd2d452f5979dc6cd797/example/simple_editor/src/simple_editor.ml | ocaml | Simple Vcaml plugin to create a new buffer/window which the user can use as a
scratchpad, with no vim bindings. The plugin is killed on window close.
The editor only supports lowercase/uppercase letters + space/enter/backspace. | open Core
open Async
open Vcaml
open Deferred.Or_error.Let_syntax
let of_ascii_list ascii_chars =
ascii_chars |> List.map ~f:(Fn.compose String.of_char Char.of_int_exn)
;;
let lowercase = of_ascii_list (List.init 26 ~f:(( + ) 97))
let uppercase = of_ascii_list (List.init 26 ~f:(( + ) 65))
let alphabet = lowercase @ uppercase
module Special_characters = struct
let space = "space"
let backspace = "bs"
let enter = "cr"
let all = [ space; backspace; enter ]
end
module State = struct
type t =
{ buffer : Buffer.t Set_once.t
; window : Window.t Set_once.t
}
[@@deriving sexp_of]
end
module type S = Vcaml_plugin.Persistent.S with type state := State.t
include Vcaml_plugin.Persistent.Make (struct
let name = "simple-editor"
let description = "A simple editor plugin for Neovim"
type state = State.t [@@deriving sexp_of]
let init_state () = { State.buffer = Set_once.create (); window = Set_once.create () }
let set_modifiable buffer value =
Buffer.set_option (Id buffer) ~scope:`Local ~name:"modifiable" ~type_:Boolean ~value
;;
let get_split_window =
let%map.Api_call.Or_error () = Nvim.command "split"
and window = Nvim.get_current_win in
window
;;
let shutdown_plugin_when_buffer_is_closed ~window ~buffer ~channel =
let shutdown_on_leave =
Printf.sprintf
"autocmd BufWinLeave <buffer> silent! call rpcrequest(%d, 'shutdown')"
channel
in
Api_call.Or_error.all_unit
[ Nvim.set_current_win window
; Nvim.set_current_buf buffer
; Nvim.command shutdown_on_leave
]
;;
let add_vim_binding ~channel ~key_bind ~rpc_name =
Nvim.command
(Printf.sprintf
"nnoremap <silent> <nowait> <buffer> %s <Cmd>call rpcrequest(%d, \"%s\")<CR>"
key_bind
channel
rpc_name)
;;
let add_key_listener ~channel key = add_vim_binding ~channel ~key_bind:key ~rpc_name:key
let add_special_character_listener ~channel key =
add_vim_binding ~channel ~key_bind:(Printf.sprintf "<%s>" key) ~rpc_name:key
;;
let add_key_listeners_api_call channel =
let typable_api_call = alphabet |> List.map ~f:(add_key_listener ~channel) in
let special_api_call =
Special_characters.all |> List.map ~f:(add_special_character_listener ~channel)
in
typable_api_call @ special_api_call |> Api_call.Or_error.all_unit
;;
let set_virtualedit_inside_buffer =
let code =
{| augroup simple_editor_save_virtualedit
autocmd! * <buffer>
autocmd BufEnter <buffer> let b:saved_virtualedit = &virtualedit
autocmd BufEnter <buffer> set virtualedit=onemore
autocmd BufLeave <buffer> let &virtualedit = b:saved_virtualedit
augroup END
let b:saved_virtualedit = &virtualedit
set virtualedit=onemore |}
in
Nvim.source code |> Api_call.Or_error.ignore_m
;;
let on_startup client state ~shutdown:_ =
let channel = Client.channel client in
let%bind buffer =
Buffer.find_by_name_or_create ~name:"simple-editor" |> run_join [%here] client
in
let%bind window = run_join [%here] client get_split_window in
let%bind () =
shutdown_plugin_when_buffer_is_closed ~window ~buffer ~channel
|> run_join [%here] client
in
let%bind () = add_key_listeners_api_call channel |> run_join [%here] client in
let%bind () = set_virtualedit_inside_buffer |> run_join [%here] client in
let%bind () =
[ set_modifiable buffer false
; Buffer.set_option
(Id buffer)
~scope:`Local
~name:"buftype"
~type_:String
~value:"nofile"
;
Window.Untested.set_option
(Id window)
~scope:`Local
~name:"list"
~type_:Boolean
~value:false
]
|> Api_call.Or_error.all_unit
|> run_join [%here] client
in
Set_once.set_exn state.State.buffer [%here] buffer;
Set_once.set_exn state.State.window [%here] window;
return ()
;;
let on_error = `Raise
let vimscript_notify_fn = None
let on_shutdown _client _state = return ()
let get_nth_line ~client ~buffer n =
Buffer.get_lines (Id buffer) ~start:(n - 1) ~end_:n ~strict_indexing:true
|> run_join [%here] client
;;
let with_modifiable ~buffer ~api_call =
let%map.Api_call unlock_buf_or_err = set_modifiable buffer true
and api_res_or_err = api_call
and lock_buf_or_err = set_modifiable buffer false in
let%bind.Or_error () = Or_error.all_unit [ unlock_buf_or_err; lock_buf_or_err ] in
api_res_or_err
;;
let set_lines ~client ~buffer ~start_at ~num_lines ~content =
with_modifiable
~buffer
~api_call:
(Buffer.set_lines
(Id buffer)
~start:start_at
~end_:(start_at + num_lines)
~replacement:content
~strict_indexing:false)
|> run_join [%here] client
;;
let set_line ~client ~buffer ~content ~row =
set_lines ~client ~buffer ~start_at:(row - 1) ~num_lines:1 ~content
;;
let set_cursor ~client ~window ~row ~col =
Window.set_cursor (Id window) { row; col } |> run_join [%here] client
;;
let split_string_at st i =
match i with
| 0 -> "", st
| i -> String.slice st 0 i, String.slice st i 0
;;
let add_newline_at_mark client buffer window { Position.One_indexed_row.row; col } =
let%bind line = get_nth_line ~client ~buffer row in
let first_line, second_line = split_string_at (List.nth_exn line 0) col in
let%bind () = set_line ~client ~buffer ~content:[ first_line; second_line ] ~row in
set_cursor ~client ~window ~row:(row + 1) ~col:0
;;
let insert_character_in_line col character line =
let before, after = split_string_at line col in
String.concat [ before; character; after ]
;;
let set_character_at_mark
character
client
buffer
window
{ Position.One_indexed_row.row; col }
=
let%bind line = get_nth_line ~client ~buffer row in
let new_line = line |> List.map ~f:(insert_character_in_line col character) in
let%bind () = set_line ~client ~buffer ~content:new_line ~row in
set_cursor ~client ~window ~row ~col:(col + 1)
;;
let delete_from_beginning_of_line client buffer window row =
let%bind curr_line = get_nth_line ~client ~buffer row in
let%bind prev_line = get_nth_line ~client ~buffer (row - 1) in
let result = String.concat (prev_line @ curr_line) in
let%bind () =
set_lines ~client ~buffer ~start_at:(row - 2) ~num_lines:2 ~content:[ result ]
in
set_cursor
~client
~window
~row:(row - 1)
~col:(String.length (List.nth_exn prev_line 0))
;;
let delete_in_line client buffer window row col =
let%bind line = get_nth_line ~client ~buffer row in
let new_line =
line
|> List.map ~f:String.to_list
|> List.map ~f:(List.filteri ~f:(fun i _ -> i <> col - 1))
|> List.map ~f:String.of_char_list
in
let%bind () = set_line ~client ~buffer ~content:new_line ~row in
set_cursor ~client ~window ~row ~col:(col - 1)
;;
let delete_character_at_mark client buffer window { Position.One_indexed_row.row; col } =
match row, col with
| 1, 0 -> Deferred.Or_error.return ()
| r, 0 -> delete_from_beginning_of_line client buffer window r
| r, c -> delete_in_line client buffer window r c
;;
let handle_edit_request ~f client { State.buffer; window } ~shutdown:_ =
let buffer = Set_once.get_exn buffer [%here] in
let window = Set_once.get_exn window [%here] in
let%bind mark = Window.get_cursor (Id window) |> run_join [%here] client in
f client buffer window mark
;;
let handle_enter_request = handle_edit_request ~f:add_newline_at_mark
let handle_key_rpc_request key = handle_edit_request ~f:(set_character_at_mark key)
let handle_backspace_request = handle_edit_request ~f:delete_character_at_mark
let create_rpc_handler ~rpc_name ~handling_fn =
Vcaml_plugin.Persistent.Rpc.create_sync
~name:rpc_name
~type_:Defun.Ocaml.Sync.(return Nil)
~f:(fun state ~shutdown ~keyboard_interrupted:_ ~client ->
handling_fn client state ~shutdown)
;;
let create_key_rpc_handler ~key ~str_to_insert =
create_rpc_handler ~rpc_name:key ~handling_fn:(handle_key_rpc_request str_to_insert)
;;
let call_shutdown _client _state ~shutdown =
shutdown ();
Deferred.Or_error.return ()
;;
let alphabet_handlers =
List.map alphabet ~f:(fun key -> create_key_rpc_handler ~key ~str_to_insert:key)
;;
let space_handler =
create_key_rpc_handler ~key:Special_characters.space ~str_to_insert:" "
;;
let enter_handler =
create_rpc_handler
~rpc_name:Special_characters.enter
~handling_fn:handle_enter_request
;;
let backspace_handler =
create_rpc_handler
~rpc_name:Special_characters.backspace
~handling_fn:handle_backspace_request
;;
let shutdown_handler =
create_rpc_handler ~rpc_name:"shutdown" ~handling_fn:call_shutdown
;;
let rpc_handlers =
alphabet_handlers
@ [ space_handler; enter_handler; backspace_handler; shutdown_handler ]
;;
end)
|
0dc0525fde8d582f049ba931c77f8499e2ad0ebea7573adb420f5f20d899f369 | LeventErkok/sbv | Fibonacci.hs | -----------------------------------------------------------------------------
-- |
-- Module : Documentation.SBV.Examples.Lists.Fibonacci
Copyright : ( c )
-- License : BSD3
-- Maintainer:
-- Stability : experimental
--
Define the fibonacci sequence as an SBV symbolic list .
-----------------------------------------------------------------------------
{-# OPTIONS_GHC -Wall -Werror #-}
module Documentation.SBV.Examples.Lists.Fibonacci where
import Data.SBV
import Prelude hiding ((!!))
import Data.SBV.List ((!!))
import qualified Data.SBV.List as L
import Data.SBV.Control
-- | Compute a prefix of the fibonacci numbers. We have:
--
-- >>> mkFibs 10
-- [1,1,2,3,5,8,13,21,34,55]
mkFibs :: Int -> IO [Integer]
mkFibs n = take n <$> runSMT genFibs
-- | Generate fibonacci numbers as a sequence. Note that we constrain only
the first 200 entries .
genFibs :: Symbolic [Integer]
genFibs = do fibs <- sList "fibs"
-- constrain the length
constrain $ L.length fibs .== 200
Constrain first two elements
constrain $ fibs !! 0 .== 1
constrain $ fibs !! 1 .== 1
-- Constrain an arbitrary element at index `i`
let constr i = constrain $ fibs !! i + fibs !! (i+1) .== fibs !! (i+2)
-- Constrain the remaining elts
mapM_ (constr . fromIntegral) [(0::Int) .. 197]
query $ do cs <- checkSat
case cs of
Unk -> error "Solver returned unknown!"
DSat{} -> error "Unexpected dsat result!"
Unsat -> error "Solver couldn't generate the fibonacci sequence!"
Sat -> getValue fibs
| null | https://raw.githubusercontent.com/LeventErkok/sbv/fdd4b9e7607b0a14ce87057130e55a6be6910bd5/Documentation/SBV/Examples/Lists/Fibonacci.hs | haskell | ---------------------------------------------------------------------------
|
Module : Documentation.SBV.Examples.Lists.Fibonacci
License : BSD3
Maintainer:
Stability : experimental
---------------------------------------------------------------------------
# OPTIONS_GHC -Wall -Werror #
| Compute a prefix of the fibonacci numbers. We have:
>>> mkFibs 10
[1,1,2,3,5,8,13,21,34,55]
| Generate fibonacci numbers as a sequence. Note that we constrain only
constrain the length
Constrain an arbitrary element at index `i`
Constrain the remaining elts | Copyright : ( c )
Define the fibonacci sequence as an SBV symbolic list .
module Documentation.SBV.Examples.Lists.Fibonacci where
import Data.SBV
import Prelude hiding ((!!))
import Data.SBV.List ((!!))
import qualified Data.SBV.List as L
import Data.SBV.Control
mkFibs :: Int -> IO [Integer]
mkFibs n = take n <$> runSMT genFibs
the first 200 entries .
genFibs :: Symbolic [Integer]
genFibs = do fibs <- sList "fibs"
constrain $ L.length fibs .== 200
Constrain first two elements
constrain $ fibs !! 0 .== 1
constrain $ fibs !! 1 .== 1
let constr i = constrain $ fibs !! i + fibs !! (i+1) .== fibs !! (i+2)
mapM_ (constr . fromIntegral) [(0::Int) .. 197]
query $ do cs <- checkSat
case cs of
Unk -> error "Solver returned unknown!"
DSat{} -> error "Unexpected dsat result!"
Unsat -> error "Solver couldn't generate the fibonacci sequence!"
Sat -> getValue fibs
|
c1f2d0ec08cbea8133bd3d4cb64b496afa4536d4d6c2d72263d34750ce209dce | ocaml-multicore/tezos | delegate_storage.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
Copyright ( c ) 2021 Nomadic Labs , < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
type error +=
| (* `Permanent *) No_deletion of Signature.Public_key_hash.t
| (* `Temporary *) Active_delegate
| (* `Temporary *) Current_delegate
| (* `Permanent *) Empty_delegate_account of Signature.Public_key_hash.t
| (* `Permanent *) Unregistered_delegate of Signature.Public_key_hash.t
| (* `Permanent *) Unassigned_validation_slot_for_level of Level_repr.t * int
| (* `Permanent *)
Cannot_find_active_stake of {
cycle : Cycle_repr.t;
delegate : Signature.Public_key_hash.t;
}
| (* `Temporary *) Not_registered of Signature.Public_key_hash.t
let () =
register_error_kind
`Permanent
~id:"delegate.no_deletion"
~title:"Forbidden delegate deletion"
~description:"Tried to unregister a delegate"
~pp:(fun ppf delegate ->
Format.fprintf
ppf
"Delegate deletion is forbidden (%a)"
Signature.Public_key_hash.pp
delegate)
Data_encoding.(obj1 (req "delegate" Signature.Public_key_hash.encoding))
(function No_deletion c -> Some c | _ -> None)
(fun c -> No_deletion c) ;
register_error_kind
`Temporary
~id:"delegate.already_active"
~title:"Delegate already active"
~description:"Useless delegate reactivation"
~pp:(fun ppf () ->
Format.fprintf ppf "The delegate is still active, no need to refresh it")
Data_encoding.empty
(function Active_delegate -> Some () | _ -> None)
(fun () -> Active_delegate) ;
register_error_kind
`Temporary
~id:"delegate.unchanged"
~title:"Unchanged delegated"
~description:"Contract already delegated to the given delegate"
~pp:(fun ppf () ->
Format.fprintf
ppf
"The contract is already delegated to the same delegate")
Data_encoding.empty
(function Current_delegate -> Some () | _ -> None)
(fun () -> Current_delegate) ;
register_error_kind
`Permanent
~id:"delegate.empty_delegate_account"
~title:"Empty delegate account"
~description:"Cannot register a delegate when its implicit account is empty"
~pp:(fun ppf delegate ->
Format.fprintf
ppf
"Delegate registration is forbidden when the delegate\n\
\ implicit account is empty (%a)"
Signature.Public_key_hash.pp
delegate)
Data_encoding.(obj1 (req "delegate" Signature.Public_key_hash.encoding))
(function Empty_delegate_account c -> Some c | _ -> None)
(fun c -> Empty_delegate_account c) ;
(* Unregistered delegate *)
register_error_kind
`Permanent
~id:"contract.manager.unregistered_delegate"
~title:"Unregistered delegate"
~description:"A contract cannot be delegated to an unregistered delegate"
~pp:(fun ppf k ->
Format.fprintf
ppf
"The provided public key (with hash %a) is not registered as valid \
delegate key."
Signature.Public_key_hash.pp
k)
Data_encoding.(obj1 (req "hash" Signature.Public_key_hash.encoding))
(function Unregistered_delegate k -> Some k | _ -> None)
(fun k -> Unregistered_delegate k) ;
(* Unassigned_validation_slot_for_level *)
register_error_kind
`Permanent
~id:"delegate.unassigned_validation_slot_for_level"
~title:"Unassigned validation slot for level"
~description:
"The validation slot for the given level is not assigned. Nobody payed \
for that slot, or the level is either in the past or too far in the \
future (further than the validatiors_selection_offset constant)"
~pp:(fun ppf (l, slot) ->
Format.fprintf
ppf
"The validation slot %i for the level %a is not assigned. Nobody payed \
for that slot, or the level is either in the past or too far in the \
future (further than the validatiors_selection_offset constant)"
slot
Level_repr.pp
l)
Data_encoding.(obj2 (req "level" Level_repr.encoding) (req "slot" int31))
(function
| Unassigned_validation_slot_for_level (l, s) -> Some (l, s) | _ -> None)
(fun (l, s) -> Unassigned_validation_slot_for_level (l, s)) ;
register_error_kind
`Permanent
~id:"delegate.cannot_find_active_stake"
~title:"Cannot find active stake"
~description:
"The active stake of a delegate cannot be found for the given cycle."
~pp:(fun ppf (cycle, delegate) ->
Format.fprintf
ppf
"The active stake of the delegate %a cannot be found for the cycle %a."
Cycle_repr.pp
cycle
Signature.Public_key_hash.pp
delegate)
Data_encoding.(
obj2
(req "cycle" Cycle_repr.encoding)
(req "delegate" Signature.Public_key_hash.encoding))
(function
| Cannot_find_active_stake {cycle; delegate} -> Some (cycle, delegate)
| _ -> None)
(fun (cycle, delegate) -> Cannot_find_active_stake {cycle; delegate}) ;
register_error_kind
`Temporary
~id:"delegate.not_registered"
~title:"Not a registered delegate"
~description:
"The provided public key hash is not the address of a registered \
delegate."
~pp:(fun ppf pkh ->
Format.fprintf
ppf
"The provided public key hash (%a) is not the address of a registered \
delegate. If you own this account and want to register it as a \
delegate, use a delegation operation to delegate the account to \
itself."
Signature.Public_key_hash.pp
pkh)
Data_encoding.(obj1 (req "pkh" Signature.Public_key_hash.encoding))
(function Not_registered pkh -> Some pkh | _ -> None)
(fun pkh -> Not_registered pkh)
let set_inactive ctxt delegate =
let delegate_contract = Contract_repr.implicit_contract delegate in
Delegate_activation_storage.set_inactive ctxt delegate_contract
>>= fun ctxt ->
Stake_storage.deactivate_only_call_from_delegate_storage ctxt delegate >|= ok
let set_active ctxt delegate =
Delegate_activation_storage.set_active ctxt delegate
>>=? fun (ctxt, inactive) ->
if not inactive then return ctxt
else Stake_storage.activate_only_call_from_delegate_storage ctxt delegate
let staking_balance ctxt delegate =
Contract_delegate_storage.registered ctxt delegate >>=? fun is_registered ->
if is_registered then Stake_storage.get_staking_balance ctxt delegate
else return Tez_repr.zero
let pubkey ctxt delegate =
Contract_manager_storage.get_manager_key
ctxt
delegate
~error:(Unregistered_delegate delegate)
let init ctxt contract delegate =
Contract_manager_storage.is_manager_key_revealed ctxt delegate
>>=? fun known_delegate ->
error_unless known_delegate (Unregistered_delegate delegate) >>?= fun () ->
Contract_delegate_storage.registered ctxt delegate >>=? fun is_registered ->
error_unless is_registered (Unregistered_delegate delegate) >>?= fun () ->
Contract_delegate_storage.init ctxt contract delegate
let set c contract delegate =
match delegate with
| None -> (
match Contract_repr.is_implicit contract with
| Some pkh ->
(* check if contract is a registered delegate *)
Contract_delegate_storage.registered c pkh >>=? fun is_registered ->
if is_registered then fail (No_deletion pkh)
else Contract_delegate_storage.delete c contract
| None -> Contract_delegate_storage.delete c contract)
| Some delegate ->
Contract_manager_storage.is_manager_key_revealed c delegate
>>=? fun known_delegate ->
Contract_delegate_storage.registered c delegate
>>=? fun registered_delegate ->
let self_delegation =
match Contract_repr.is_implicit contract with
| Some pkh -> Signature.Public_key_hash.equal pkh delegate
| None -> false
in
if (not known_delegate) || not (registered_delegate || self_delegation)
then fail (Unregistered_delegate delegate)
else
(Contract_delegate_storage.find c contract >>=? function
| Some current_delegate
when Signature.Public_key_hash.equal delegate current_delegate ->
if self_delegation then
Delegate_activation_storage.is_inactive c delegate >>=? function
| true -> return_unit
| false -> fail Active_delegate
else fail Current_delegate
| None | Some _ -> return_unit)
>>=? fun () ->
(* check if contract is a registered delegate *)
(match Contract_repr.is_implicit contract with
| Some pkh ->
Contract_delegate_storage.registered c pkh >>=? fun is_registered ->
(* allow self-delegation to re-activate *)
if (not self_delegation) && is_registered then
fail (No_deletion pkh)
else return_unit
| None -> return_unit)
>>=? fun () ->
Storage.Contract.Balance.mem c contract >>= fun exists ->
error_when
(self_delegation && not exists)
(Empty_delegate_account delegate)
>>?= fun () ->
Contract_delegate_storage.set c contract delegate >>=? fun c ->
if self_delegation then
Storage.Delegates.add c delegate >>= fun c -> set_active c delegate
else return c
let frozen_deposits_limit ctxt delegate =
Storage.Contract.Frozen_deposits_limit.find
ctxt
(Contract_repr.implicit_contract delegate)
let set_frozen_deposits_limit ctxt delegate limit =
Storage.Contract.Frozen_deposits_limit.add_or_remove
ctxt
(Contract_repr.implicit_contract delegate)
limit
let update_activity ctxt last_cycle =
let preserved = Constants_storage.preserved_cycles ctxt in
match Cycle_repr.sub last_cycle preserved with
| None -> return (ctxt, [])
| Some _unfrozen_cycle ->
Stake_storage.fold_on_active_delegates_with_rolls
ctxt
~order:`Sorted
~init:(Ok (ctxt, []))
~f:(fun delegate () acc ->
acc >>?= fun (ctxt, deactivated) ->
Delegate_activation_storage.grace_period ctxt delegate
>>=? fun cycle ->
if Cycle_repr.(cycle <= last_cycle) then
set_inactive ctxt delegate >|=? fun ctxt ->
(ctxt, delegate :: deactivated)
else return (ctxt, deactivated))
>|=? fun (ctxt, deactivated) -> (ctxt, deactivated)
let expected_slots_for_given_active_stake ctxt ~total_active_stake ~active_stake
=
let blocks_per_cycle =
Int32.to_int (Constants_storage.blocks_per_cycle ctxt)
in
let consensus_committee_size =
Constants_storage.consensus_committee_size ctxt
in
let number_of_endorsements_per_cycle =
blocks_per_cycle * consensus_committee_size
in
Result.return
(Z.to_int
(Z.div
(Z.mul
(Z.of_int64 (Tez_repr.to_mutez active_stake))
(Z.of_int number_of_endorsements_per_cycle))
(Z.of_int64 (Tez_repr.to_mutez total_active_stake))))
let delegate_participated_enough ctxt delegate =
Storage.Contract.Missed_endorsements.find ctxt delegate >>=? function
| None -> return_true
| Some missed_endorsements ->
return Compare.Int.(missed_endorsements.remaining_slots >= 0)
let delegate_has_revealed_nonces delegate unrevelead_nonces_set =
not (Signature.Public_key_hash.Set.mem delegate unrevelead_nonces_set)
let distribute_endorsing_rewards ctxt last_cycle unrevealed_nonces =
let endorsing_reward_per_slot =
Constants_storage.endorsing_reward_per_slot ctxt
in
let unrevealed_nonces_set =
List.fold_left
(fun set {Storage.Seed.nonce_hash = _; delegate} ->
Signature.Public_key_hash.Set.add delegate set)
Signature.Public_key_hash.Set.empty
unrevealed_nonces
in
Stake_storage.get_total_active_stake ctxt last_cycle
>>=? fun total_active_stake ->
Stake_storage.get_selected_distribution ctxt last_cycle >>=? fun delegates ->
List.fold_left_es
(fun (ctxt, balance_updates) (delegate, active_stake) ->
let delegate_contract = Contract_repr.implicit_contract delegate in
delegate_participated_enough ctxt delegate_contract
>>=? fun sufficient_participation ->
let has_revealed_nonces =
delegate_has_revealed_nonces delegate unrevealed_nonces_set
in
expected_slots_for_given_active_stake
ctxt
~total_active_stake
~active_stake
>>?= fun expected_slots ->
let rewards = Tez_repr.mul_exn endorsing_reward_per_slot expected_slots in
(if sufficient_participation && has_revealed_nonces then
(* Sufficient participation: we pay the rewards *)
Token.transfer
ctxt
`Endorsing_rewards
(`Contract delegate_contract)
rewards
>|=? fun (ctxt, payed_rewards_receipts) ->
(ctxt, payed_rewards_receipts @ balance_updates)
else
(* Insufficient participation or unrevealed nonce: no rewards *)
Token.transfer
ctxt
`Endorsing_rewards
(`Lost_endorsing_rewards
(delegate, not sufficient_participation, not has_revealed_nonces))
rewards
>|=? fun (ctxt, payed_rewards_receipts) ->
(ctxt, payed_rewards_receipts @ balance_updates))
>>=? fun (ctxt, balance_updates) ->
Storage.Contract.Missed_endorsements.remove ctxt delegate_contract
>>= fun ctxt -> return (ctxt, balance_updates))
(ctxt, [])
delegates
let clear_outdated_slashed_deposits ctxt ~new_cycle =
let max_slashable_period = Constants_storage.max_slashing_period ctxt in
match Cycle_repr.(sub new_cycle max_slashable_period) with
| None -> Lwt.return ctxt
| Some outdated_cycle -> Storage.Slashed_deposits.clear (ctxt, outdated_cycle)
(* Return a map from delegates (with active stake at some cycle
in the cycle window [from_cycle, to_cycle]) to the maximum
of the stake to be deposited for each such cycle (which is just the
[frozen_deposits_percentage] of the active stake at that cycle). Also
return the delegates that have fallen out of the sliding window. *)
let max_frozen_deposits_and_delegates_to_remove ctxt ~from_cycle ~to_cycle =
let frozen_deposits_percentage =
Constants_storage.frozen_deposits_percentage ctxt
in
let cycles = Cycle_repr.(from_cycle ---> to_cycle) in
(match Cycle_repr.pred from_cycle with
| None -> return Signature.Public_key_hash.Set.empty
| Some cleared_cycle -> (
Stake_storage.find_selected_distribution ctxt cleared_cycle
>|=? fun cleared_cycle_delegates ->
match cleared_cycle_delegates with
| None -> Signature.Public_key_hash.Set.empty
| Some delegates ->
List.fold_left
(fun set (d, _) -> Signature.Public_key_hash.Set.add d set)
Signature.Public_key_hash.Set.empty
delegates))
>>=? fun cleared_cycle_delegates ->
List.fold_left_es
(fun (maxima, delegates_to_remove) (cycle : Cycle_repr.t) ->
Stake_storage.get_selected_distribution ctxt cycle
>|=? fun active_stakes ->
List.fold_left
(fun (maxima, delegates_to_remove) (delegate, stake) ->
let stake_to_be_deposited =
Tez_repr.(div_exn (mul_exn stake frozen_deposits_percentage) 100)
in
let maxima =
Signature.Public_key_hash.Map.update
delegate
(function
| None -> Some stake_to_be_deposited
| Some maximum ->
Some (Tez_repr.max maximum stake_to_be_deposited))
maxima
in
let delegates_to_remove =
Signature.Public_key_hash.Set.remove delegate delegates_to_remove
in
(maxima, delegates_to_remove))
(maxima, delegates_to_remove)
active_stakes)
(Signature.Public_key_hash.Map.empty, cleared_cycle_delegates)
cycles
let freeze_deposits ?(origin = Receipt_repr.Block_application) ctxt ~new_cycle
~balance_updates =
let max_slashable_period = Constants_storage.max_slashing_period ctxt in
(* We want to be able to slash for at most [max_slashable_period] *)
(match Cycle_repr.(sub new_cycle (max_slashable_period - 1)) with
| None ->
Storage.Tenderbake.First_level.get ctxt
>>=? fun first_level_of_tenderbake ->
let cycle_eras = Raw_context.cycle_eras ctxt in
let level =
Level_repr.level_from_raw ~cycle_eras first_level_of_tenderbake
in
return level.cycle
| Some cycle -> return cycle)
>>=? fun from_cycle ->
let preserved_cycles = Constants_storage.preserved_cycles ctxt in
let to_cycle = Cycle_repr.(add new_cycle preserved_cycles) in
max_frozen_deposits_and_delegates_to_remove ctxt ~from_cycle ~to_cycle
>>=? fun (maxima, delegates_to_remove) ->
Signature.Public_key_hash.Map.fold_es
(fun delegate maximum_stake_to_be_deposited (ctxt, balance_updates) ->
Here we make sure to preserve the following invariant :
maximum_stake_to_be_deposited < = frozen_deposits + balance
See select_distribution_for_cycle
maximum_stake_to_be_deposited <= frozen_deposits + balance
See select_distribution_for_cycle *)
let delegate_contract = Contract_repr.implicit_contract delegate in
Frozen_deposits_storage.update_initial_amount
ctxt
delegate_contract
maximum_stake_to_be_deposited
>>=? fun ctxt ->
Frozen_deposits_storage.get ctxt delegate_contract >>=? fun deposits ->
let current_amount = deposits.current_amount in
if Tez_repr.(current_amount > maximum_stake_to_be_deposited) then
Tez_repr.(current_amount -? maximum_stake_to_be_deposited)
>>?= fun to_reimburse ->
Token.transfer
~origin
ctxt
(`Frozen_deposits delegate)
(`Delegate_balance delegate)
to_reimburse
>|=? fun (ctxt, bupds) -> (ctxt, bupds @ balance_updates)
else if Tez_repr.(current_amount < maximum_stake_to_be_deposited) then
Tez_repr.(maximum_stake_to_be_deposited -? current_amount)
>>?= fun desired_to_freeze ->
Storage.Contract.Balance.get ctxt delegate_contract >>=? fun balance ->
In case the delegate has n't been slashed in this cycle ,
the following invariant holds :
maximum_stake_to_be_deposited < = frozen_deposits + balance
See select_distribution_for_cycle
If the delegate has been slashed during the cycle , the invariant
above does n't necessarily hold . In this case , we freeze the
we can for the delegate .
the following invariant holds:
maximum_stake_to_be_deposited <= frozen_deposits + balance
See select_distribution_for_cycle
If the delegate has been slashed during the cycle, the invariant
above doesn't necessarily hold. In this case, we freeze the max
we can for the delegate. *)
let to_freeze = Tez_repr.(min balance desired_to_freeze) in
Token.transfer
~origin
ctxt
(`Delegate_balance delegate)
(`Frozen_deposits delegate)
to_freeze
>|=? fun (ctxt, bupds) -> (ctxt, bupds @ balance_updates)
else return (ctxt, balance_updates))
maxima
(ctxt, balance_updates)
>>=? fun (ctxt, balance_updates) ->
Unfreeze deposits ( that is , set them to zero ) for delegates that
were previously in the relevant window ( and therefore had some
frozen deposits ) but are not in the new window ; because that means
that such a delegate had no active stake in the relevant cycles ,
and therefore it should have no frozen deposits .
were previously in the relevant window (and therefore had some
frozen deposits) but are not in the new window; because that means
that such a delegate had no active stake in the relevant cycles,
and therefore it should have no frozen deposits. *)
Signature.Public_key_hash.Set.fold_es
(fun delegate (ctxt, balance_updates) ->
let delegate_contract = Contract_repr.implicit_contract delegate in
Frozen_deposits_storage.update_initial_amount
ctxt
delegate_contract
Tez_repr.zero
>>=? fun ctxt ->
Frozen_deposits_storage.get ctxt delegate_contract
>>=? fun frozen_deposits ->
if Tez_repr.(frozen_deposits.current_amount > zero) then
Token.transfer
~origin
ctxt
(`Frozen_deposits delegate)
(`Delegate_balance delegate)
frozen_deposits.current_amount
>|=? fun (ctxt, bupds) -> (ctxt, bupds @ balance_updates)
else return (ctxt, balance_updates))
delegates_to_remove
(ctxt, balance_updates)
let freeze_deposits_do_not_call_except_for_migration =
freeze_deposits ~origin:Protocol_migration
let cycle_end ctxt last_cycle unrevealed_nonces =
let new_cycle = Cycle_repr.add last_cycle 1 in
Stake_storage.select_new_distribution_at_cycle_end ctxt ~new_cycle pubkey
>>=? fun ctxt ->
clear_outdated_slashed_deposits ctxt ~new_cycle >>= fun ctxt ->
distribute_endorsing_rewards ctxt last_cycle unrevealed_nonces
>>=? fun (ctxt, balance_updates) ->
freeze_deposits ctxt ~new_cycle ~balance_updates
>>=? fun (ctxt, balance_updates) ->
Stake_storage.clear_at_cycle_end ctxt ~new_cycle >>=? fun ctxt ->
update_activity ctxt last_cycle >>=? fun (ctxt, deactivated_delagates) ->
return (ctxt, balance_updates, deactivated_delagates)
let balance ctxt delegate =
let contract = Contract_repr.implicit_contract delegate in
Storage.Contract.Balance.get ctxt contract
let frozen_deposits ctxt delegate =
Frozen_deposits_storage.get ctxt (Contract_repr.implicit_contract delegate)
let full_balance ctxt delegate =
frozen_deposits ctxt delegate >>=? fun frozen_deposits ->
balance ctxt delegate >>=? fun balance ->
Lwt.return Tez_repr.(frozen_deposits.current_amount +? balance)
let deactivated = Delegate_activation_storage.is_inactive
let delegated_balance ctxt delegate =
staking_balance ctxt delegate >>=? fun staking_balance ->
balance ctxt delegate >>=? fun balance ->
frozen_deposits ctxt delegate >>=? fun frozen_deposits ->
Tez_repr.(balance +? frozen_deposits.current_amount)
>>?= fun self_staking_balance ->
Lwt.return Tez_repr.(staking_balance -? self_staking_balance)
let fold = Storage.Delegates.fold
let list = Storage.Delegates.elements
The fact that this succeeds iff [ registered ] returns true is an
invariant of the [ set ] function .
invariant of the [set] function. *)
let check_delegate ctxt pkh =
Storage.Delegates.mem ctxt pkh >>= function
| true -> return_unit
| false -> fail (Not_registered pkh)
module Random = struct
[ init_random_state ] initialize a random sequence drawing state
that 's unique for a given ( seed , level , index ) triple . Elements
from this sequence are drawn using [ take_int64 ] , updating the
state for the next draw . The initial state is the hash of
the three randomness sources , and an offset set to zero
( indicating that zero bits of randomness have been
consumed ) . When drawing random elements , bits are extracted from
the state until exhaustion ( 256 bits ) , at which point the state
is rehashed and the offset reset to 0 .
that's unique for a given (seed, level, index) triple. Elements
from this sequence are drawn using [take_int64], updating the
state for the next draw. The initial state is the Blake2b hash of
the three randomness sources, and an offset set to zero
(indicating that zero bits of randomness have been
consumed). When drawing random elements, bits are extracted from
the state until exhaustion (256 bits), at which point the state
is rehashed and the offset reset to 0. *)
let init_random_state seed level index =
( Raw_hashes.blake2b
(Data_encoding.Binary.to_bytes_exn
Data_encoding.(tup3 Seed_repr.seed_encoding int32 int32)
(seed, level.Level_repr.cycle_position, Int32.of_int index)),
0 )
let take_int64 bound state =
let drop_if_over =
This function draws random values in [ 0-(bound-1 ) ] by drawing
in [ 0-(2 ^ 63 - 1 ) ] ( 64 - bit ) and computing the value modulo
[ bound ] . For the application of [ mod bound ] to preserve
uniformity , the input space must be of the form
[ 0-(n*bound-1 ) ] . We enforce this by rejecting 64 - bit samples
above this limit ( in which case , we draw a new 64 - sample from
the sequence and try again ) .
in [0-(2^63-1)] (64-bit) and computing the value modulo
[bound]. For the application of [mod bound] to preserve
uniformity, the input space must be of the form
[0-(n*bound-1)]. We enforce this by rejecting 64-bit samples
above this limit (in which case, we draw a new 64-sample from
the sequence and try again). *)
Int64.sub Int64.max_int (Int64.rem Int64.max_int bound)
in
let rec loop (bytes, n) =
let consumed_bytes = 8 in
let state_size = Bytes.length bytes in
if Compare.Int.(n > state_size - consumed_bytes) then
loop (Raw_hashes.blake2b bytes, 0)
else
let r = Int64.abs (TzEndian.get_int64 bytes n) in
if Compare.Int64.(r >= drop_if_over) then
loop (bytes, n + consumed_bytes)
else
let v = Int64.rem r bound in
(v, (bytes, n + consumed_bytes))
in
loop state
let owner c (level : Level_repr.t) offset =
(* TODO: /-/issues/2084
compute sampler at stake distribution snapshot instead of lazily. *)
let cycle = level.Level_repr.cycle in
(match Raw_context.sampler_for_cycle c cycle with
| Error `Sampler_not_set ->
Seed_storage.for_cycle c cycle >>=? fun seed ->
Stake_storage.Delegate_sampler_state.get c cycle >>=? fun state ->
let (c, seed, state) =
match Raw_context.set_sampler_for_cycle c cycle (seed, state) with
| Error `Sampler_already_set -> assert false
| Ok c -> (c, seed, state)
in
return (c, seed, state)
| Ok (seed, state) -> return (c, seed, state))
>>=? fun (c, seed, state) ->
let sample ~int_bound ~mass_bound =
let state = init_random_state seed level offset in
let (i, state) = take_int64 (Int64.of_int int_bound) state in
let (elt, _) = take_int64 mass_bound state in
(Int64.to_int i, elt)
in
let (pk, pkh) = Sampler.sample state sample in
return (c, (pk, pkh))
end
let slot_owner c level slot = Random.owner c level (Slot_repr.to_int slot)
let baking_rights_owner c (level : Level_repr.t) ~round =
Round_repr.to_int round >>?= fun round ->
let consensus_committee_size = Constants_storage.consensus_committee_size c in
Slot_repr.of_int (round mod consensus_committee_size) >>?= fun slot ->
slot_owner c level slot >>=? fun (ctxt, pk) -> return (ctxt, slot, pk)
let already_slashed_for_double_endorsing ctxt delegate (level : Level_repr.t) =
Storage.Slashed_deposits.find (ctxt, level.cycle) (level.level, delegate)
>>=? function
| None -> return_false
| Some slashed -> return slashed.for_double_endorsing
let already_slashed_for_double_baking ctxt delegate (level : Level_repr.t) =
Storage.Slashed_deposits.find (ctxt, level.cycle) (level.level, delegate)
>>=? function
| None -> return_false
| Some slashed -> return slashed.for_double_baking
let punish_double_endorsing ctxt delegate (level : Level_repr.t) =
let delegate_contract = Contract_repr.implicit_contract delegate in
Frozen_deposits_storage.get ctxt delegate_contract >>=? fun frozen_deposits ->
let slashing_ratio : Constants_repr.ratio =
Constants_storage.ratio_of_frozen_deposits_slashed_per_double_endorsement
ctxt
in
let punish_value =
Tez_repr.(
div_exn
(mul_exn frozen_deposits.initial_amount slashing_ratio.numerator)
slashing_ratio.denominator)
in
let amount_to_burn =
Tez_repr.(min frozen_deposits.current_amount punish_value)
in
Token.transfer
ctxt
(`Frozen_deposits delegate)
`Double_signing_punishments
amount_to_burn
>>=? fun (ctxt, balance_updates) ->
Stake_storage.remove_stake ctxt delegate amount_to_burn >>=? fun ctxt ->
Storage.Slashed_deposits.find (ctxt, level.cycle) (level.level, delegate)
>>=? fun slashed ->
let slashed : Storage.slashed_level =
match slashed with
| None -> {for_double_endorsing = true; for_double_baking = false}
| Some slashed ->
assert (Compare.Bool.(slashed.for_double_endorsing = false)) ;
{slashed with for_double_endorsing = true}
in
Storage.Slashed_deposits.add
(ctxt, level.cycle)
(level.level, delegate)
slashed
>>= fun ctxt -> return (ctxt, amount_to_burn, balance_updates)
let punish_double_baking ctxt delegate (level : Level_repr.t) =
let delegate_contract = Contract_repr.implicit_contract delegate in
Frozen_deposits_storage.get ctxt delegate_contract >>=? fun frozen_deposits ->
let slashing_for_one_block =
Constants_storage.double_baking_punishment ctxt
in
let amount_to_burn =
Tez_repr.(min frozen_deposits.current_amount slashing_for_one_block)
in
Token.transfer
ctxt
(`Frozen_deposits delegate)
`Double_signing_punishments
amount_to_burn
>>=? fun (ctxt, balance_updates) ->
Stake_storage.remove_stake ctxt delegate amount_to_burn >>=? fun ctxt ->
Storage.Slashed_deposits.find (ctxt, level.cycle) (level.level, delegate)
>>=? fun slashed ->
let slashed : Storage.slashed_level =
match slashed with
| None -> {for_double_endorsing = false; for_double_baking = true}
| Some slashed ->
assert (Compare.Bool.(slashed.for_double_baking = false)) ;
{slashed with for_double_baking = true}
in
Storage.Slashed_deposits.add
(ctxt, level.cycle)
(level.level, delegate)
slashed
>>= fun ctxt -> return (ctxt, amount_to_burn, balance_updates)
type level_participation = Participated | Didn't_participate
(* Note that the participation for the last block of a cycle is
recorded in the next cycle. *)
let record_endorsing_participation ctxt ~delegate ~participation
~endorsing_power =
match participation with
| Participated -> set_active ctxt delegate
| Didn't_participate -> (
let contract = Contract_repr.implicit_contract delegate in
Storage.Contract.Missed_endorsements.find ctxt contract >>=? function
| Some {remaining_slots; missed_levels} ->
let remaining_slots = remaining_slots - endorsing_power in
Storage.Contract.Missed_endorsements.update
ctxt
contract
{remaining_slots; missed_levels = missed_levels + 1}
| None -> (
let level = Level_storage.current ctxt in
Raw_context.stake_distribution_for_current_cycle ctxt
>>?= fun stake_distribution ->
match
Signature.Public_key_hash.Map.find delegate stake_distribution
with
| None ->
This happens when the block is the first one in a
cycle , and therefore the endorsements are for the last
block of the previous cycle , and when the delegate does
not have an active stake at the current cycle ; in this
case its participation is simply ignored .
cycle, and therefore the endorsements are for the last
block of the previous cycle, and when the delegate does
not have an active stake at the current cycle; in this
case its participation is simply ignored. *)
assert (Compare.Int32.(level.cycle_position = 0l)) ;
return ctxt
| Some active_stake ->
Stake_storage.get_total_active_stake ctxt level.cycle
>>=? fun total_active_stake ->
expected_slots_for_given_active_stake
ctxt
~total_active_stake
~active_stake
>>?= fun expected_slots ->
let Constants_repr.{numerator; denominator} =
Constants_storage.minimal_participation_ratio ctxt
in
let minimal_activity = expected_slots * numerator / denominator in
let maximal_inactivity = expected_slots - minimal_activity in
let remaining_slots = maximal_inactivity - endorsing_power in
Storage.Contract.Missed_endorsements.init
ctxt
contract
{remaining_slots; missed_levels = 1}))
let record_baking_activity_and_pay_rewards_and_fees ctxt ~payload_producer
~block_producer ~baking_reward ~reward_bonus =
set_active ctxt payload_producer >>=? fun ctxt ->
(if not (Signature.Public_key_hash.equal payload_producer block_producer) then
set_active ctxt block_producer
else return ctxt)
>>=? fun ctxt ->
let pay_payload_producer ctxt delegate =
let contract = Contract_repr.implicit_contract delegate in
Token.balance ctxt `Block_fees >>=? fun block_fees ->
Token.transfer_n
ctxt
[(`Block_fees, block_fees); (`Baking_rewards, baking_reward)]
(`Contract contract)
in
let pay_block_producer ctxt delegate bonus =
let contract = Contract_repr.implicit_contract delegate in
Token.transfer ctxt `Baking_bonuses (`Contract contract) bonus
in
pay_payload_producer ctxt payload_producer
>>=? fun (ctxt, balance_updates_payload_producer) ->
(match reward_bonus with
| Some bonus -> pay_block_producer ctxt block_producer bonus
| None -> return (ctxt, []))
>>=? fun (ctxt, balance_updates_block_producer) ->
return
(ctxt, balance_updates_payload_producer @ balance_updates_block_producer)
type participation_info = {
expected_cycle_activity : int;
minimal_cycle_activity : int;
missed_slots : int;
missed_levels : int;
remaining_allowed_missed_slots : int;
expected_endorsing_rewards : Tez_repr.t;
}
(* Inefficient, only for RPC *)
let delegate_participation_info ctxt delegate =
let level = Level_storage.current ctxt in
Stake_storage.get_selected_distribution ctxt level.cycle
>>=? fun stake_distribution ->
match
List.assoc_opt
~equal:Signature.Public_key_hash.equal
delegate
stake_distribution
with
| None ->
(* delegate does not have an active stake at the current cycle *)
return
{
expected_cycle_activity = 0;
minimal_cycle_activity = 0;
missed_slots = 0;
missed_levels = 0;
remaining_allowed_missed_slots = 0;
expected_endorsing_rewards = Tez_repr.zero;
}
| Some active_stake ->
Stake_storage.get_total_active_stake ctxt level.cycle
>>=? fun total_active_stake ->
expected_slots_for_given_active_stake
ctxt
~total_active_stake
~active_stake
>>?= fun expected_cycle_activity ->
let Constants_repr.{numerator; denominator} =
Constants_storage.minimal_participation_ratio ctxt
in
let endorsing_reward_per_slot =
Constants_storage.endorsing_reward_per_slot ctxt
in
let minimal_cycle_activity =
expected_cycle_activity * numerator / denominator
in
let maximal_cycle_inactivity =
expected_cycle_activity - minimal_cycle_activity
in
let expected_endorsing_rewards =
Tez_repr.mul_exn endorsing_reward_per_slot expected_cycle_activity
in
let contract = Contract_repr.implicit_contract delegate in
Storage.Contract.Missed_endorsements.find ctxt contract
>>=? fun missed_endorsements ->
let (missed_slots, missed_levels, remaining_allowed_missed_slots) =
match missed_endorsements with
| None -> (0, 0, maximal_cycle_inactivity)
| Some {remaining_slots; missed_levels} ->
( maximal_cycle_inactivity - remaining_slots,
missed_levels,
Compare.Int.max 0 remaining_slots )
in
let expected_endorsing_rewards =
match missed_endorsements with
| Some r when Compare.Int.(r.remaining_slots < 0) -> Tez_repr.zero
| _ -> expected_endorsing_rewards
in
return
{
expected_cycle_activity;
minimal_cycle_activity;
missed_slots;
missed_levels;
remaining_allowed_missed_slots;
expected_endorsing_rewards;
}
| null | https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_alpha/lib_protocol/delegate_storage.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
`Permanent
`Temporary
`Temporary
`Permanent
`Permanent
`Permanent
`Permanent
`Temporary
Unregistered delegate
Unassigned_validation_slot_for_level
check if contract is a registered delegate
check if contract is a registered delegate
allow self-delegation to re-activate
Sufficient participation: we pay the rewards
Insufficient participation or unrevealed nonce: no rewards
Return a map from delegates (with active stake at some cycle
in the cycle window [from_cycle, to_cycle]) to the maximum
of the stake to be deposited for each such cycle (which is just the
[frozen_deposits_percentage] of the active stake at that cycle). Also
return the delegates that have fallen out of the sliding window.
We want to be able to slash for at most [max_slashable_period]
TODO: /-/issues/2084
compute sampler at stake distribution snapshot instead of lazily.
Note that the participation for the last block of a cycle is
recorded in the next cycle.
Inefficient, only for RPC
delegate does not have an active stake at the current cycle | Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
Copyright ( c ) 2021 Nomadic Labs , < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
type error +=
Cannot_find_active_stake of {
cycle : Cycle_repr.t;
delegate : Signature.Public_key_hash.t;
}
let () =
register_error_kind
`Permanent
~id:"delegate.no_deletion"
~title:"Forbidden delegate deletion"
~description:"Tried to unregister a delegate"
~pp:(fun ppf delegate ->
Format.fprintf
ppf
"Delegate deletion is forbidden (%a)"
Signature.Public_key_hash.pp
delegate)
Data_encoding.(obj1 (req "delegate" Signature.Public_key_hash.encoding))
(function No_deletion c -> Some c | _ -> None)
(fun c -> No_deletion c) ;
register_error_kind
`Temporary
~id:"delegate.already_active"
~title:"Delegate already active"
~description:"Useless delegate reactivation"
~pp:(fun ppf () ->
Format.fprintf ppf "The delegate is still active, no need to refresh it")
Data_encoding.empty
(function Active_delegate -> Some () | _ -> None)
(fun () -> Active_delegate) ;
register_error_kind
`Temporary
~id:"delegate.unchanged"
~title:"Unchanged delegated"
~description:"Contract already delegated to the given delegate"
~pp:(fun ppf () ->
Format.fprintf
ppf
"The contract is already delegated to the same delegate")
Data_encoding.empty
(function Current_delegate -> Some () | _ -> None)
(fun () -> Current_delegate) ;
register_error_kind
`Permanent
~id:"delegate.empty_delegate_account"
~title:"Empty delegate account"
~description:"Cannot register a delegate when its implicit account is empty"
~pp:(fun ppf delegate ->
Format.fprintf
ppf
"Delegate registration is forbidden when the delegate\n\
\ implicit account is empty (%a)"
Signature.Public_key_hash.pp
delegate)
Data_encoding.(obj1 (req "delegate" Signature.Public_key_hash.encoding))
(function Empty_delegate_account c -> Some c | _ -> None)
(fun c -> Empty_delegate_account c) ;
register_error_kind
`Permanent
~id:"contract.manager.unregistered_delegate"
~title:"Unregistered delegate"
~description:"A contract cannot be delegated to an unregistered delegate"
~pp:(fun ppf k ->
Format.fprintf
ppf
"The provided public key (with hash %a) is not registered as valid \
delegate key."
Signature.Public_key_hash.pp
k)
Data_encoding.(obj1 (req "hash" Signature.Public_key_hash.encoding))
(function Unregistered_delegate k -> Some k | _ -> None)
(fun k -> Unregistered_delegate k) ;
register_error_kind
`Permanent
~id:"delegate.unassigned_validation_slot_for_level"
~title:"Unassigned validation slot for level"
~description:
"The validation slot for the given level is not assigned. Nobody payed \
for that slot, or the level is either in the past or too far in the \
future (further than the validatiors_selection_offset constant)"
~pp:(fun ppf (l, slot) ->
Format.fprintf
ppf
"The validation slot %i for the level %a is not assigned. Nobody payed \
for that slot, or the level is either in the past or too far in the \
future (further than the validatiors_selection_offset constant)"
slot
Level_repr.pp
l)
Data_encoding.(obj2 (req "level" Level_repr.encoding) (req "slot" int31))
(function
| Unassigned_validation_slot_for_level (l, s) -> Some (l, s) | _ -> None)
(fun (l, s) -> Unassigned_validation_slot_for_level (l, s)) ;
register_error_kind
`Permanent
~id:"delegate.cannot_find_active_stake"
~title:"Cannot find active stake"
~description:
"The active stake of a delegate cannot be found for the given cycle."
~pp:(fun ppf (cycle, delegate) ->
Format.fprintf
ppf
"The active stake of the delegate %a cannot be found for the cycle %a."
Cycle_repr.pp
cycle
Signature.Public_key_hash.pp
delegate)
Data_encoding.(
obj2
(req "cycle" Cycle_repr.encoding)
(req "delegate" Signature.Public_key_hash.encoding))
(function
| Cannot_find_active_stake {cycle; delegate} -> Some (cycle, delegate)
| _ -> None)
(fun (cycle, delegate) -> Cannot_find_active_stake {cycle; delegate}) ;
register_error_kind
`Temporary
~id:"delegate.not_registered"
~title:"Not a registered delegate"
~description:
"The provided public key hash is not the address of a registered \
delegate."
~pp:(fun ppf pkh ->
Format.fprintf
ppf
"The provided public key hash (%a) is not the address of a registered \
delegate. If you own this account and want to register it as a \
delegate, use a delegation operation to delegate the account to \
itself."
Signature.Public_key_hash.pp
pkh)
Data_encoding.(obj1 (req "pkh" Signature.Public_key_hash.encoding))
(function Not_registered pkh -> Some pkh | _ -> None)
(fun pkh -> Not_registered pkh)
let set_inactive ctxt delegate =
let delegate_contract = Contract_repr.implicit_contract delegate in
Delegate_activation_storage.set_inactive ctxt delegate_contract
>>= fun ctxt ->
Stake_storage.deactivate_only_call_from_delegate_storage ctxt delegate >|= ok
let set_active ctxt delegate =
Delegate_activation_storage.set_active ctxt delegate
>>=? fun (ctxt, inactive) ->
if not inactive then return ctxt
else Stake_storage.activate_only_call_from_delegate_storage ctxt delegate
let staking_balance ctxt delegate =
Contract_delegate_storage.registered ctxt delegate >>=? fun is_registered ->
if is_registered then Stake_storage.get_staking_balance ctxt delegate
else return Tez_repr.zero
let pubkey ctxt delegate =
Contract_manager_storage.get_manager_key
ctxt
delegate
~error:(Unregistered_delegate delegate)
let init ctxt contract delegate =
Contract_manager_storage.is_manager_key_revealed ctxt delegate
>>=? fun known_delegate ->
error_unless known_delegate (Unregistered_delegate delegate) >>?= fun () ->
Contract_delegate_storage.registered ctxt delegate >>=? fun is_registered ->
error_unless is_registered (Unregistered_delegate delegate) >>?= fun () ->
Contract_delegate_storage.init ctxt contract delegate
let set c contract delegate =
match delegate with
| None -> (
match Contract_repr.is_implicit contract with
| Some pkh ->
Contract_delegate_storage.registered c pkh >>=? fun is_registered ->
if is_registered then fail (No_deletion pkh)
else Contract_delegate_storage.delete c contract
| None -> Contract_delegate_storage.delete c contract)
| Some delegate ->
Contract_manager_storage.is_manager_key_revealed c delegate
>>=? fun known_delegate ->
Contract_delegate_storage.registered c delegate
>>=? fun registered_delegate ->
let self_delegation =
match Contract_repr.is_implicit contract with
| Some pkh -> Signature.Public_key_hash.equal pkh delegate
| None -> false
in
if (not known_delegate) || not (registered_delegate || self_delegation)
then fail (Unregistered_delegate delegate)
else
(Contract_delegate_storage.find c contract >>=? function
| Some current_delegate
when Signature.Public_key_hash.equal delegate current_delegate ->
if self_delegation then
Delegate_activation_storage.is_inactive c delegate >>=? function
| true -> return_unit
| false -> fail Active_delegate
else fail Current_delegate
| None | Some _ -> return_unit)
>>=? fun () ->
(match Contract_repr.is_implicit contract with
| Some pkh ->
Contract_delegate_storage.registered c pkh >>=? fun is_registered ->
if (not self_delegation) && is_registered then
fail (No_deletion pkh)
else return_unit
| None -> return_unit)
>>=? fun () ->
Storage.Contract.Balance.mem c contract >>= fun exists ->
error_when
(self_delegation && not exists)
(Empty_delegate_account delegate)
>>?= fun () ->
Contract_delegate_storage.set c contract delegate >>=? fun c ->
if self_delegation then
Storage.Delegates.add c delegate >>= fun c -> set_active c delegate
else return c
let frozen_deposits_limit ctxt delegate =
Storage.Contract.Frozen_deposits_limit.find
ctxt
(Contract_repr.implicit_contract delegate)
let set_frozen_deposits_limit ctxt delegate limit =
Storage.Contract.Frozen_deposits_limit.add_or_remove
ctxt
(Contract_repr.implicit_contract delegate)
limit
let update_activity ctxt last_cycle =
let preserved = Constants_storage.preserved_cycles ctxt in
match Cycle_repr.sub last_cycle preserved with
| None -> return (ctxt, [])
| Some _unfrozen_cycle ->
Stake_storage.fold_on_active_delegates_with_rolls
ctxt
~order:`Sorted
~init:(Ok (ctxt, []))
~f:(fun delegate () acc ->
acc >>?= fun (ctxt, deactivated) ->
Delegate_activation_storage.grace_period ctxt delegate
>>=? fun cycle ->
if Cycle_repr.(cycle <= last_cycle) then
set_inactive ctxt delegate >|=? fun ctxt ->
(ctxt, delegate :: deactivated)
else return (ctxt, deactivated))
>|=? fun (ctxt, deactivated) -> (ctxt, deactivated)
let expected_slots_for_given_active_stake ctxt ~total_active_stake ~active_stake
=
let blocks_per_cycle =
Int32.to_int (Constants_storage.blocks_per_cycle ctxt)
in
let consensus_committee_size =
Constants_storage.consensus_committee_size ctxt
in
let number_of_endorsements_per_cycle =
blocks_per_cycle * consensus_committee_size
in
Result.return
(Z.to_int
(Z.div
(Z.mul
(Z.of_int64 (Tez_repr.to_mutez active_stake))
(Z.of_int number_of_endorsements_per_cycle))
(Z.of_int64 (Tez_repr.to_mutez total_active_stake))))
let delegate_participated_enough ctxt delegate =
Storage.Contract.Missed_endorsements.find ctxt delegate >>=? function
| None -> return_true
| Some missed_endorsements ->
return Compare.Int.(missed_endorsements.remaining_slots >= 0)
let delegate_has_revealed_nonces delegate unrevelead_nonces_set =
not (Signature.Public_key_hash.Set.mem delegate unrevelead_nonces_set)
let distribute_endorsing_rewards ctxt last_cycle unrevealed_nonces =
let endorsing_reward_per_slot =
Constants_storage.endorsing_reward_per_slot ctxt
in
let unrevealed_nonces_set =
List.fold_left
(fun set {Storage.Seed.nonce_hash = _; delegate} ->
Signature.Public_key_hash.Set.add delegate set)
Signature.Public_key_hash.Set.empty
unrevealed_nonces
in
Stake_storage.get_total_active_stake ctxt last_cycle
>>=? fun total_active_stake ->
Stake_storage.get_selected_distribution ctxt last_cycle >>=? fun delegates ->
List.fold_left_es
(fun (ctxt, balance_updates) (delegate, active_stake) ->
let delegate_contract = Contract_repr.implicit_contract delegate in
delegate_participated_enough ctxt delegate_contract
>>=? fun sufficient_participation ->
let has_revealed_nonces =
delegate_has_revealed_nonces delegate unrevealed_nonces_set
in
expected_slots_for_given_active_stake
ctxt
~total_active_stake
~active_stake
>>?= fun expected_slots ->
let rewards = Tez_repr.mul_exn endorsing_reward_per_slot expected_slots in
(if sufficient_participation && has_revealed_nonces then
Token.transfer
ctxt
`Endorsing_rewards
(`Contract delegate_contract)
rewards
>|=? fun (ctxt, payed_rewards_receipts) ->
(ctxt, payed_rewards_receipts @ balance_updates)
else
Token.transfer
ctxt
`Endorsing_rewards
(`Lost_endorsing_rewards
(delegate, not sufficient_participation, not has_revealed_nonces))
rewards
>|=? fun (ctxt, payed_rewards_receipts) ->
(ctxt, payed_rewards_receipts @ balance_updates))
>>=? fun (ctxt, balance_updates) ->
Storage.Contract.Missed_endorsements.remove ctxt delegate_contract
>>= fun ctxt -> return (ctxt, balance_updates))
(ctxt, [])
delegates
let clear_outdated_slashed_deposits ctxt ~new_cycle =
let max_slashable_period = Constants_storage.max_slashing_period ctxt in
match Cycle_repr.(sub new_cycle max_slashable_period) with
| None -> Lwt.return ctxt
| Some outdated_cycle -> Storage.Slashed_deposits.clear (ctxt, outdated_cycle)
let max_frozen_deposits_and_delegates_to_remove ctxt ~from_cycle ~to_cycle =
let frozen_deposits_percentage =
Constants_storage.frozen_deposits_percentage ctxt
in
let cycles = Cycle_repr.(from_cycle ---> to_cycle) in
(match Cycle_repr.pred from_cycle with
| None -> return Signature.Public_key_hash.Set.empty
| Some cleared_cycle -> (
Stake_storage.find_selected_distribution ctxt cleared_cycle
>|=? fun cleared_cycle_delegates ->
match cleared_cycle_delegates with
| None -> Signature.Public_key_hash.Set.empty
| Some delegates ->
List.fold_left
(fun set (d, _) -> Signature.Public_key_hash.Set.add d set)
Signature.Public_key_hash.Set.empty
delegates))
>>=? fun cleared_cycle_delegates ->
List.fold_left_es
(fun (maxima, delegates_to_remove) (cycle : Cycle_repr.t) ->
Stake_storage.get_selected_distribution ctxt cycle
>|=? fun active_stakes ->
List.fold_left
(fun (maxima, delegates_to_remove) (delegate, stake) ->
let stake_to_be_deposited =
Tez_repr.(div_exn (mul_exn stake frozen_deposits_percentage) 100)
in
let maxima =
Signature.Public_key_hash.Map.update
delegate
(function
| None -> Some stake_to_be_deposited
| Some maximum ->
Some (Tez_repr.max maximum stake_to_be_deposited))
maxima
in
let delegates_to_remove =
Signature.Public_key_hash.Set.remove delegate delegates_to_remove
in
(maxima, delegates_to_remove))
(maxima, delegates_to_remove)
active_stakes)
(Signature.Public_key_hash.Map.empty, cleared_cycle_delegates)
cycles
let freeze_deposits ?(origin = Receipt_repr.Block_application) ctxt ~new_cycle
~balance_updates =
let max_slashable_period = Constants_storage.max_slashing_period ctxt in
(match Cycle_repr.(sub new_cycle (max_slashable_period - 1)) with
| None ->
Storage.Tenderbake.First_level.get ctxt
>>=? fun first_level_of_tenderbake ->
let cycle_eras = Raw_context.cycle_eras ctxt in
let level =
Level_repr.level_from_raw ~cycle_eras first_level_of_tenderbake
in
return level.cycle
| Some cycle -> return cycle)
>>=? fun from_cycle ->
let preserved_cycles = Constants_storage.preserved_cycles ctxt in
let to_cycle = Cycle_repr.(add new_cycle preserved_cycles) in
max_frozen_deposits_and_delegates_to_remove ctxt ~from_cycle ~to_cycle
>>=? fun (maxima, delegates_to_remove) ->
Signature.Public_key_hash.Map.fold_es
(fun delegate maximum_stake_to_be_deposited (ctxt, balance_updates) ->
Here we make sure to preserve the following invariant :
maximum_stake_to_be_deposited < = frozen_deposits + balance
See select_distribution_for_cycle
maximum_stake_to_be_deposited <= frozen_deposits + balance
See select_distribution_for_cycle *)
let delegate_contract = Contract_repr.implicit_contract delegate in
Frozen_deposits_storage.update_initial_amount
ctxt
delegate_contract
maximum_stake_to_be_deposited
>>=? fun ctxt ->
Frozen_deposits_storage.get ctxt delegate_contract >>=? fun deposits ->
let current_amount = deposits.current_amount in
if Tez_repr.(current_amount > maximum_stake_to_be_deposited) then
Tez_repr.(current_amount -? maximum_stake_to_be_deposited)
>>?= fun to_reimburse ->
Token.transfer
~origin
ctxt
(`Frozen_deposits delegate)
(`Delegate_balance delegate)
to_reimburse
>|=? fun (ctxt, bupds) -> (ctxt, bupds @ balance_updates)
else if Tez_repr.(current_amount < maximum_stake_to_be_deposited) then
Tez_repr.(maximum_stake_to_be_deposited -? current_amount)
>>?= fun desired_to_freeze ->
Storage.Contract.Balance.get ctxt delegate_contract >>=? fun balance ->
In case the delegate has n't been slashed in this cycle ,
the following invariant holds :
maximum_stake_to_be_deposited < = frozen_deposits + balance
See select_distribution_for_cycle
If the delegate has been slashed during the cycle , the invariant
above does n't necessarily hold . In this case , we freeze the
we can for the delegate .
the following invariant holds:
maximum_stake_to_be_deposited <= frozen_deposits + balance
See select_distribution_for_cycle
If the delegate has been slashed during the cycle, the invariant
above doesn't necessarily hold. In this case, we freeze the max
we can for the delegate. *)
let to_freeze = Tez_repr.(min balance desired_to_freeze) in
Token.transfer
~origin
ctxt
(`Delegate_balance delegate)
(`Frozen_deposits delegate)
to_freeze
>|=? fun (ctxt, bupds) -> (ctxt, bupds @ balance_updates)
else return (ctxt, balance_updates))
maxima
(ctxt, balance_updates)
>>=? fun (ctxt, balance_updates) ->
Unfreeze deposits ( that is , set them to zero ) for delegates that
were previously in the relevant window ( and therefore had some
frozen deposits ) but are not in the new window ; because that means
that such a delegate had no active stake in the relevant cycles ,
and therefore it should have no frozen deposits .
were previously in the relevant window (and therefore had some
frozen deposits) but are not in the new window; because that means
that such a delegate had no active stake in the relevant cycles,
and therefore it should have no frozen deposits. *)
Signature.Public_key_hash.Set.fold_es
(fun delegate (ctxt, balance_updates) ->
let delegate_contract = Contract_repr.implicit_contract delegate in
Frozen_deposits_storage.update_initial_amount
ctxt
delegate_contract
Tez_repr.zero
>>=? fun ctxt ->
Frozen_deposits_storage.get ctxt delegate_contract
>>=? fun frozen_deposits ->
if Tez_repr.(frozen_deposits.current_amount > zero) then
Token.transfer
~origin
ctxt
(`Frozen_deposits delegate)
(`Delegate_balance delegate)
frozen_deposits.current_amount
>|=? fun (ctxt, bupds) -> (ctxt, bupds @ balance_updates)
else return (ctxt, balance_updates))
delegates_to_remove
(ctxt, balance_updates)
let freeze_deposits_do_not_call_except_for_migration =
freeze_deposits ~origin:Protocol_migration
let cycle_end ctxt last_cycle unrevealed_nonces =
let new_cycle = Cycle_repr.add last_cycle 1 in
Stake_storage.select_new_distribution_at_cycle_end ctxt ~new_cycle pubkey
>>=? fun ctxt ->
clear_outdated_slashed_deposits ctxt ~new_cycle >>= fun ctxt ->
distribute_endorsing_rewards ctxt last_cycle unrevealed_nonces
>>=? fun (ctxt, balance_updates) ->
freeze_deposits ctxt ~new_cycle ~balance_updates
>>=? fun (ctxt, balance_updates) ->
Stake_storage.clear_at_cycle_end ctxt ~new_cycle >>=? fun ctxt ->
update_activity ctxt last_cycle >>=? fun (ctxt, deactivated_delagates) ->
return (ctxt, balance_updates, deactivated_delagates)
let balance ctxt delegate =
let contract = Contract_repr.implicit_contract delegate in
Storage.Contract.Balance.get ctxt contract
let frozen_deposits ctxt delegate =
Frozen_deposits_storage.get ctxt (Contract_repr.implicit_contract delegate)
let full_balance ctxt delegate =
frozen_deposits ctxt delegate >>=? fun frozen_deposits ->
balance ctxt delegate >>=? fun balance ->
Lwt.return Tez_repr.(frozen_deposits.current_amount +? balance)
let deactivated = Delegate_activation_storage.is_inactive
let delegated_balance ctxt delegate =
staking_balance ctxt delegate >>=? fun staking_balance ->
balance ctxt delegate >>=? fun balance ->
frozen_deposits ctxt delegate >>=? fun frozen_deposits ->
Tez_repr.(balance +? frozen_deposits.current_amount)
>>?= fun self_staking_balance ->
Lwt.return Tez_repr.(staking_balance -? self_staking_balance)
let fold = Storage.Delegates.fold
let list = Storage.Delegates.elements
The fact that this succeeds iff [ registered ] returns true is an
invariant of the [ set ] function .
invariant of the [set] function. *)
let check_delegate ctxt pkh =
Storage.Delegates.mem ctxt pkh >>= function
| true -> return_unit
| false -> fail (Not_registered pkh)
module Random = struct
[ init_random_state ] initialize a random sequence drawing state
that 's unique for a given ( seed , level , index ) triple . Elements
from this sequence are drawn using [ take_int64 ] , updating the
state for the next draw . The initial state is the hash of
the three randomness sources , and an offset set to zero
( indicating that zero bits of randomness have been
consumed ) . When drawing random elements , bits are extracted from
the state until exhaustion ( 256 bits ) , at which point the state
is rehashed and the offset reset to 0 .
that's unique for a given (seed, level, index) triple. Elements
from this sequence are drawn using [take_int64], updating the
state for the next draw. The initial state is the Blake2b hash of
the three randomness sources, and an offset set to zero
(indicating that zero bits of randomness have been
consumed). When drawing random elements, bits are extracted from
the state until exhaustion (256 bits), at which point the state
is rehashed and the offset reset to 0. *)
let init_random_state seed level index =
( Raw_hashes.blake2b
(Data_encoding.Binary.to_bytes_exn
Data_encoding.(tup3 Seed_repr.seed_encoding int32 int32)
(seed, level.Level_repr.cycle_position, Int32.of_int index)),
0 )
let take_int64 bound state =
let drop_if_over =
This function draws random values in [ 0-(bound-1 ) ] by drawing
in [ 0-(2 ^ 63 - 1 ) ] ( 64 - bit ) and computing the value modulo
[ bound ] . For the application of [ mod bound ] to preserve
uniformity , the input space must be of the form
[ 0-(n*bound-1 ) ] . We enforce this by rejecting 64 - bit samples
above this limit ( in which case , we draw a new 64 - sample from
the sequence and try again ) .
in [0-(2^63-1)] (64-bit) and computing the value modulo
[bound]. For the application of [mod bound] to preserve
uniformity, the input space must be of the form
[0-(n*bound-1)]. We enforce this by rejecting 64-bit samples
above this limit (in which case, we draw a new 64-sample from
the sequence and try again). *)
Int64.sub Int64.max_int (Int64.rem Int64.max_int bound)
in
let rec loop (bytes, n) =
let consumed_bytes = 8 in
let state_size = Bytes.length bytes in
if Compare.Int.(n > state_size - consumed_bytes) then
loop (Raw_hashes.blake2b bytes, 0)
else
let r = Int64.abs (TzEndian.get_int64 bytes n) in
if Compare.Int64.(r >= drop_if_over) then
loop (bytes, n + consumed_bytes)
else
let v = Int64.rem r bound in
(v, (bytes, n + consumed_bytes))
in
loop state
let owner c (level : Level_repr.t) offset =
let cycle = level.Level_repr.cycle in
(match Raw_context.sampler_for_cycle c cycle with
| Error `Sampler_not_set ->
Seed_storage.for_cycle c cycle >>=? fun seed ->
Stake_storage.Delegate_sampler_state.get c cycle >>=? fun state ->
let (c, seed, state) =
match Raw_context.set_sampler_for_cycle c cycle (seed, state) with
| Error `Sampler_already_set -> assert false
| Ok c -> (c, seed, state)
in
return (c, seed, state)
| Ok (seed, state) -> return (c, seed, state))
>>=? fun (c, seed, state) ->
let sample ~int_bound ~mass_bound =
let state = init_random_state seed level offset in
let (i, state) = take_int64 (Int64.of_int int_bound) state in
let (elt, _) = take_int64 mass_bound state in
(Int64.to_int i, elt)
in
let (pk, pkh) = Sampler.sample state sample in
return (c, (pk, pkh))
end
let slot_owner c level slot = Random.owner c level (Slot_repr.to_int slot)
let baking_rights_owner c (level : Level_repr.t) ~round =
Round_repr.to_int round >>?= fun round ->
let consensus_committee_size = Constants_storage.consensus_committee_size c in
Slot_repr.of_int (round mod consensus_committee_size) >>?= fun slot ->
slot_owner c level slot >>=? fun (ctxt, pk) -> return (ctxt, slot, pk)
let already_slashed_for_double_endorsing ctxt delegate (level : Level_repr.t) =
Storage.Slashed_deposits.find (ctxt, level.cycle) (level.level, delegate)
>>=? function
| None -> return_false
| Some slashed -> return slashed.for_double_endorsing
let already_slashed_for_double_baking ctxt delegate (level : Level_repr.t) =
Storage.Slashed_deposits.find (ctxt, level.cycle) (level.level, delegate)
>>=? function
| None -> return_false
| Some slashed -> return slashed.for_double_baking
let punish_double_endorsing ctxt delegate (level : Level_repr.t) =
let delegate_contract = Contract_repr.implicit_contract delegate in
Frozen_deposits_storage.get ctxt delegate_contract >>=? fun frozen_deposits ->
let slashing_ratio : Constants_repr.ratio =
Constants_storage.ratio_of_frozen_deposits_slashed_per_double_endorsement
ctxt
in
let punish_value =
Tez_repr.(
div_exn
(mul_exn frozen_deposits.initial_amount slashing_ratio.numerator)
slashing_ratio.denominator)
in
let amount_to_burn =
Tez_repr.(min frozen_deposits.current_amount punish_value)
in
Token.transfer
ctxt
(`Frozen_deposits delegate)
`Double_signing_punishments
amount_to_burn
>>=? fun (ctxt, balance_updates) ->
Stake_storage.remove_stake ctxt delegate amount_to_burn >>=? fun ctxt ->
Storage.Slashed_deposits.find (ctxt, level.cycle) (level.level, delegate)
>>=? fun slashed ->
let slashed : Storage.slashed_level =
match slashed with
| None -> {for_double_endorsing = true; for_double_baking = false}
| Some slashed ->
assert (Compare.Bool.(slashed.for_double_endorsing = false)) ;
{slashed with for_double_endorsing = true}
in
Storage.Slashed_deposits.add
(ctxt, level.cycle)
(level.level, delegate)
slashed
>>= fun ctxt -> return (ctxt, amount_to_burn, balance_updates)
let punish_double_baking ctxt delegate (level : Level_repr.t) =
let delegate_contract = Contract_repr.implicit_contract delegate in
Frozen_deposits_storage.get ctxt delegate_contract >>=? fun frozen_deposits ->
let slashing_for_one_block =
Constants_storage.double_baking_punishment ctxt
in
let amount_to_burn =
Tez_repr.(min frozen_deposits.current_amount slashing_for_one_block)
in
Token.transfer
ctxt
(`Frozen_deposits delegate)
`Double_signing_punishments
amount_to_burn
>>=? fun (ctxt, balance_updates) ->
Stake_storage.remove_stake ctxt delegate amount_to_burn >>=? fun ctxt ->
Storage.Slashed_deposits.find (ctxt, level.cycle) (level.level, delegate)
>>=? fun slashed ->
let slashed : Storage.slashed_level =
match slashed with
| None -> {for_double_endorsing = false; for_double_baking = true}
| Some slashed ->
assert (Compare.Bool.(slashed.for_double_baking = false)) ;
{slashed with for_double_baking = true}
in
Storage.Slashed_deposits.add
(ctxt, level.cycle)
(level.level, delegate)
slashed
>>= fun ctxt -> return (ctxt, amount_to_burn, balance_updates)
type level_participation = Participated | Didn't_participate
let record_endorsing_participation ctxt ~delegate ~participation
~endorsing_power =
match participation with
| Participated -> set_active ctxt delegate
| Didn't_participate -> (
let contract = Contract_repr.implicit_contract delegate in
Storage.Contract.Missed_endorsements.find ctxt contract >>=? function
| Some {remaining_slots; missed_levels} ->
let remaining_slots = remaining_slots - endorsing_power in
Storage.Contract.Missed_endorsements.update
ctxt
contract
{remaining_slots; missed_levels = missed_levels + 1}
| None -> (
let level = Level_storage.current ctxt in
Raw_context.stake_distribution_for_current_cycle ctxt
>>?= fun stake_distribution ->
match
Signature.Public_key_hash.Map.find delegate stake_distribution
with
| None ->
This happens when the block is the first one in a
cycle , and therefore the endorsements are for the last
block of the previous cycle , and when the delegate does
not have an active stake at the current cycle ; in this
case its participation is simply ignored .
cycle, and therefore the endorsements are for the last
block of the previous cycle, and when the delegate does
not have an active stake at the current cycle; in this
case its participation is simply ignored. *)
assert (Compare.Int32.(level.cycle_position = 0l)) ;
return ctxt
| Some active_stake ->
Stake_storage.get_total_active_stake ctxt level.cycle
>>=? fun total_active_stake ->
expected_slots_for_given_active_stake
ctxt
~total_active_stake
~active_stake
>>?= fun expected_slots ->
let Constants_repr.{numerator; denominator} =
Constants_storage.minimal_participation_ratio ctxt
in
let minimal_activity = expected_slots * numerator / denominator in
let maximal_inactivity = expected_slots - minimal_activity in
let remaining_slots = maximal_inactivity - endorsing_power in
Storage.Contract.Missed_endorsements.init
ctxt
contract
{remaining_slots; missed_levels = 1}))
let record_baking_activity_and_pay_rewards_and_fees ctxt ~payload_producer
~block_producer ~baking_reward ~reward_bonus =
set_active ctxt payload_producer >>=? fun ctxt ->
(if not (Signature.Public_key_hash.equal payload_producer block_producer) then
set_active ctxt block_producer
else return ctxt)
>>=? fun ctxt ->
let pay_payload_producer ctxt delegate =
let contract = Contract_repr.implicit_contract delegate in
Token.balance ctxt `Block_fees >>=? fun block_fees ->
Token.transfer_n
ctxt
[(`Block_fees, block_fees); (`Baking_rewards, baking_reward)]
(`Contract contract)
in
let pay_block_producer ctxt delegate bonus =
let contract = Contract_repr.implicit_contract delegate in
Token.transfer ctxt `Baking_bonuses (`Contract contract) bonus
in
pay_payload_producer ctxt payload_producer
>>=? fun (ctxt, balance_updates_payload_producer) ->
(match reward_bonus with
| Some bonus -> pay_block_producer ctxt block_producer bonus
| None -> return (ctxt, []))
>>=? fun (ctxt, balance_updates_block_producer) ->
return
(ctxt, balance_updates_payload_producer @ balance_updates_block_producer)
type participation_info = {
expected_cycle_activity : int;
minimal_cycle_activity : int;
missed_slots : int;
missed_levels : int;
remaining_allowed_missed_slots : int;
expected_endorsing_rewards : Tez_repr.t;
}
let delegate_participation_info ctxt delegate =
let level = Level_storage.current ctxt in
Stake_storage.get_selected_distribution ctxt level.cycle
>>=? fun stake_distribution ->
match
List.assoc_opt
~equal:Signature.Public_key_hash.equal
delegate
stake_distribution
with
| None ->
return
{
expected_cycle_activity = 0;
minimal_cycle_activity = 0;
missed_slots = 0;
missed_levels = 0;
remaining_allowed_missed_slots = 0;
expected_endorsing_rewards = Tez_repr.zero;
}
| Some active_stake ->
Stake_storage.get_total_active_stake ctxt level.cycle
>>=? fun total_active_stake ->
expected_slots_for_given_active_stake
ctxt
~total_active_stake
~active_stake
>>?= fun expected_cycle_activity ->
let Constants_repr.{numerator; denominator} =
Constants_storage.minimal_participation_ratio ctxt
in
let endorsing_reward_per_slot =
Constants_storage.endorsing_reward_per_slot ctxt
in
let minimal_cycle_activity =
expected_cycle_activity * numerator / denominator
in
let maximal_cycle_inactivity =
expected_cycle_activity - minimal_cycle_activity
in
let expected_endorsing_rewards =
Tez_repr.mul_exn endorsing_reward_per_slot expected_cycle_activity
in
let contract = Contract_repr.implicit_contract delegate in
Storage.Contract.Missed_endorsements.find ctxt contract
>>=? fun missed_endorsements ->
let (missed_slots, missed_levels, remaining_allowed_missed_slots) =
match missed_endorsements with
| None -> (0, 0, maximal_cycle_inactivity)
| Some {remaining_slots; missed_levels} ->
( maximal_cycle_inactivity - remaining_slots,
missed_levels,
Compare.Int.max 0 remaining_slots )
in
let expected_endorsing_rewards =
match missed_endorsements with
| Some r when Compare.Int.(r.remaining_slots < 0) -> Tez_repr.zero
| _ -> expected_endorsing_rewards
in
return
{
expected_cycle_activity;
minimal_cycle_activity;
missed_slots;
missed_levels;
remaining_allowed_missed_slots;
expected_endorsing_rewards;
}
|
bbc7181971d185597026ae415e707febd35d32d28f22039ad38f56bb7103d9d0 | cram2/cram | fk.lisp | ;;;
Copyright ( c ) 2016 , < >
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are met:
;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
* Neither the name of the Institute for Artificial Intelligence/
;;; Universitaet Bremen nor the names of its contributors may be used to
;;; endorse or promote products derived from this software without
;;; specific prior written permission.
;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
;;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
;;; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
;;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
;;; POSSIBILITY OF SUCH DAMAGE.
(in-package :pr2-ik-fk)
(defparameter *fk-service-names* '(:moveit "moveit/compute_fk"
:left "pr2_left_arm_kinematics/get_fk"
:right "pr2_right_arm_kinematics/get_fk"))
(defvar *fk-solver-infos* '(:left nil :right nil)
"fk solver infos for the left and right arm fk solvers")
(defparameter *fk-info-service-names* '(:left "pr2_left_arm_kinematics/get_fk_solver_info"
:right "pr2_right_arm_kinematics/get_fk_solver_info"))
(defun get-fk-solver-info (left-or-right)
(or (getf *fk-solver-infos* left-or-right)
(setf (getf *fk-solver-infos* left-or-right)
(roslisp:with-fields (kinematic_solver_info)
(roslisp:call-service
(getf *fk-info-service-names* left-or-right)
'moveit_msgs-srv:getkinematicsolverinfo)
kinematic_solver_info))))
(defun get-fk-solver-joints (left-or-right)
(roslisp:with-fields (joint_names)
(get-fk-solver-info left-or-right)
joint_names))
(defun get-fk-links (left-or-right)
(ecase left-or-right
(:left (vector "l_wrist_roll_link" "l_elbow_flex_link"))
(:right (vector "r_wrist_roll_link" "r_elbow_flex_link"))))
(defun call-fk-service (left-or-right link-names-vector
&optional (fk-base-frame "torso_lift_link"))
(declare (type keyword left-or-right))
(handler-case
(roslisp:with-fields ((response-error-code (val error_code))
pose_stamped fk_link_names)
(progn
(roslisp:wait-for-service (getf *fk-info-service-names* left-or-right) 10.0)
(roslisp:call-service
(getf *fk-service-names* left-or-right)
"moveit_msgs/GetPositionFK"
(roslisp:make-request
"moveit_msgs/GetPositionFK"
(:frame_id :header) fk-base-frame
:fk_link_names (or link-names-vector (get-fk-links left-or-right))
(:joint_state :robot_state) (make-zero-seed-state left-or-right))))
(cond ((eql response-error-code
(roslisp-msg-protocol:symbol-code
'moveit_msgs-msg:moveiterrorcodes
:success))
(map 'list
(lambda (name pose-stamped-msg)
(list name (cl-transforms-stamped:from-msg pose-stamped-msg)))
fk_link_names
pose_stamped))
(t (error 'simple-error
:format-control "FK service failed: ~a"
:format-arguments (list
(roslisp-msg-protocol:code-symbol
'moveit_msgs-msg:moveiterrorcodes
response-error-code))))))
(simple-error (e)
(format t "~a~%FK service call freaked out. Hmmm...~%" e))))
| null | https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_pr2/cram_pr2_arm_kinematics/src/fk.lisp | lisp |
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Universitaet Bremen nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE. | Copyright ( c ) 2016 , < >
* Neither the name of the Institute for Artificial Intelligence/
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
(in-package :pr2-ik-fk)
(defparameter *fk-service-names* '(:moveit "moveit/compute_fk"
:left "pr2_left_arm_kinematics/get_fk"
:right "pr2_right_arm_kinematics/get_fk"))
(defvar *fk-solver-infos* '(:left nil :right nil)
"fk solver infos for the left and right arm fk solvers")
(defparameter *fk-info-service-names* '(:left "pr2_left_arm_kinematics/get_fk_solver_info"
:right "pr2_right_arm_kinematics/get_fk_solver_info"))
(defun get-fk-solver-info (left-or-right)
(or (getf *fk-solver-infos* left-or-right)
(setf (getf *fk-solver-infos* left-or-right)
(roslisp:with-fields (kinematic_solver_info)
(roslisp:call-service
(getf *fk-info-service-names* left-or-right)
'moveit_msgs-srv:getkinematicsolverinfo)
kinematic_solver_info))))
(defun get-fk-solver-joints (left-or-right)
(roslisp:with-fields (joint_names)
(get-fk-solver-info left-or-right)
joint_names))
(defun get-fk-links (left-or-right)
(ecase left-or-right
(:left (vector "l_wrist_roll_link" "l_elbow_flex_link"))
(:right (vector "r_wrist_roll_link" "r_elbow_flex_link"))))
(defun call-fk-service (left-or-right link-names-vector
&optional (fk-base-frame "torso_lift_link"))
(declare (type keyword left-or-right))
(handler-case
(roslisp:with-fields ((response-error-code (val error_code))
pose_stamped fk_link_names)
(progn
(roslisp:wait-for-service (getf *fk-info-service-names* left-or-right) 10.0)
(roslisp:call-service
(getf *fk-service-names* left-or-right)
"moveit_msgs/GetPositionFK"
(roslisp:make-request
"moveit_msgs/GetPositionFK"
(:frame_id :header) fk-base-frame
:fk_link_names (or link-names-vector (get-fk-links left-or-right))
(:joint_state :robot_state) (make-zero-seed-state left-or-right))))
(cond ((eql response-error-code
(roslisp-msg-protocol:symbol-code
'moveit_msgs-msg:moveiterrorcodes
:success))
(map 'list
(lambda (name pose-stamped-msg)
(list name (cl-transforms-stamped:from-msg pose-stamped-msg)))
fk_link_names
pose_stamped))
(t (error 'simple-error
:format-control "FK service failed: ~a"
:format-arguments (list
(roslisp-msg-protocol:code-symbol
'moveit_msgs-msg:moveiterrorcodes
response-error-code))))))
(simple-error (e)
(format t "~a~%FK service call freaked out. Hmmm...~%" e))))
|
0af170247d5caed7d2bfaab117ea9837971af38767224086cf3b38abced6e126 | qrilka/xlsx | Util.hs | module Codec.Xlsx.Parser.Internal.Util
( boolean
, eitherBoolean
, decimal
, eitherDecimal
, rational
, eitherRational
) where
import Data.Text (Text)
import Control.Monad.Fail (MonadFail)
import qualified Data.Text as T
import qualified Data.Text.Read as T
import qualified Control.Monad.Fail as F
decimal :: (MonadFail m, Integral a) => Text -> m a
decimal = fromEither . eitherDecimal
eitherDecimal :: (Integral a) => Text -> Either String a
eitherDecimal t = case T.signed T.decimal t of
Right (d, leftover) | T.null leftover -> Right d
_ -> Left $ "invalid decimal: " ++ show t
rational :: (MonadFail m) => Text -> m Double
rational = fromEither . eitherRational
eitherRational :: Text -> Either String Double
eitherRational t = case T.signed T.rational t of
Right (r, leftover) | T.null leftover -> Right r
_ -> Left $ "invalid rational: " ++ show t
boolean :: (MonadFail m) => Text -> m Bool
boolean = fromEither . eitherBoolean
eitherBoolean :: Text -> Either String Bool
eitherBoolean t = case T.unpack $ T.strip t of
"true" -> Right True
"false" -> Right False
_ -> Left $ "invalid boolean: " ++ show t
fromEither :: (MonadFail m) => Either String b -> m b
fromEither (Left a) = F.fail a
fromEither (Right b) = return b
| null | https://raw.githubusercontent.com/qrilka/xlsx/397c3c9db965419a2d2d72470ba68f478748c573/src/Codec/Xlsx/Parser/Internal/Util.hs | haskell | module Codec.Xlsx.Parser.Internal.Util
( boolean
, eitherBoolean
, decimal
, eitherDecimal
, rational
, eitherRational
) where
import Data.Text (Text)
import Control.Monad.Fail (MonadFail)
import qualified Data.Text as T
import qualified Data.Text.Read as T
import qualified Control.Monad.Fail as F
decimal :: (MonadFail m, Integral a) => Text -> m a
decimal = fromEither . eitherDecimal
eitherDecimal :: (Integral a) => Text -> Either String a
eitherDecimal t = case T.signed T.decimal t of
Right (d, leftover) | T.null leftover -> Right d
_ -> Left $ "invalid decimal: " ++ show t
rational :: (MonadFail m) => Text -> m Double
rational = fromEither . eitherRational
eitherRational :: Text -> Either String Double
eitherRational t = case T.signed T.rational t of
Right (r, leftover) | T.null leftover -> Right r
_ -> Left $ "invalid rational: " ++ show t
boolean :: (MonadFail m) => Text -> m Bool
boolean = fromEither . eitherBoolean
eitherBoolean :: Text -> Either String Bool
eitherBoolean t = case T.unpack $ T.strip t of
"true" -> Right True
"false" -> Right False
_ -> Left $ "invalid boolean: " ++ show t
fromEither :: (MonadFail m) => Either String b -> m b
fromEither (Left a) = F.fail a
fromEither (Right b) = return b
| |
43fe58414253d7c9d7b3d67f4b2689136036cae4a426c1759abf8c2d8369cf41 | yi-editor/yi | LineNumbers.hs | {-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.UI.LineNumbers
-- License : GPL-2
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
-- Line numbers.
module Yi.UI.LineNumbers
( getDisplayLineNumbersLocal
, setDisplayLineNumbersLocal
) where
import Data.Binary (Binary (..))
import Data.Default (Default (..))
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import Yi.Buffer (getBufferDyn, putBufferDyn)
import Yi.Types (BufferM, YiVariable)
newtype DisplayLineNumbersLocal = DisplayLineNumbersLocal { unDisplayLineNumbersLocal :: Maybe Bool }
deriving (Generic, Typeable)
instance Default DisplayLineNumbersLocal where
def = DisplayLineNumbersLocal Nothing
instance Binary DisplayLineNumbersLocal
instance YiVariable DisplayLineNumbersLocal
-- | Get the buffer-local line number setting.
getDisplayLineNumbersLocal :: BufferM (Maybe Bool)
getDisplayLineNumbersLocal = unDisplayLineNumbersLocal <$> getBufferDyn
-- | Set the buffer-local line number setting.
-- Nothing: use global setting
-- Just True: display line numbers only in this buffer
-- Just False: hide line numbers only in this buffer
setDisplayLineNumbersLocal :: Maybe Bool -> BufferM ()
setDisplayLineNumbersLocal = putBufferDyn . DisplayLineNumbersLocal
| null | https://raw.githubusercontent.com/yi-editor/yi/58c239e3a77cef8f4f77e94677bd6a295f585f5f/yi-core/src/Yi/UI/LineNumbers.hs | haskell | # LANGUAGE DeriveDataTypeable #
# OPTIONS_HADDOCK show-extensions #
|
Module : Yi.UI.LineNumbers
License : GPL-2
Maintainer :
Stability : experimental
Portability : portable
Line numbers.
| Get the buffer-local line number setting.
| Set the buffer-local line number setting.
Nothing: use global setting
Just True: display line numbers only in this buffer
Just False: hide line numbers only in this buffer | # LANGUAGE DeriveGeneric #
module Yi.UI.LineNumbers
( getDisplayLineNumbersLocal
, setDisplayLineNumbersLocal
) where
import Data.Binary (Binary (..))
import Data.Default (Default (..))
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import Yi.Buffer (getBufferDyn, putBufferDyn)
import Yi.Types (BufferM, YiVariable)
newtype DisplayLineNumbersLocal = DisplayLineNumbersLocal { unDisplayLineNumbersLocal :: Maybe Bool }
deriving (Generic, Typeable)
instance Default DisplayLineNumbersLocal where
def = DisplayLineNumbersLocal Nothing
instance Binary DisplayLineNumbersLocal
instance YiVariable DisplayLineNumbersLocal
getDisplayLineNumbersLocal :: BufferM (Maybe Bool)
getDisplayLineNumbersLocal = unDisplayLineNumbersLocal <$> getBufferDyn
setDisplayLineNumbersLocal :: Maybe Bool -> BufferM ()
setDisplayLineNumbersLocal = putBufferDyn . DisplayLineNumbersLocal
|
387c21e20601ed6b6435cff9e35cc971faf8d6db47b94afda6b9806449d45b1d | bobot/FetedelascienceINRIAsaclay | snapshot.ml | open Graphics
File : snapshot.ml
Copyright ( C ) 2008
< >
WWW : /
This library is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2.1 or
later as published by the Free Software Foundation , with the special
exception on linking described in the file LICENSE .
This library is distributed in the hope that it will be useful , but
WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file
LICENSE for more details .
Copyright (C) 2008
Christophe Troestler <>
WWW: /
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2.1 or
later as published by the Free Software Foundation, with the special
exception on linking described in the file LICENSE.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
LICENSE for more details. *)
(* FIXME: this file needs some cleanup *)
type color = int
let imagemagick_convert = "convert"
let convert fname1 fname2 =
let cmd = imagemagick_convert ^ " " ^ fname1 ^ " " ^ fname2 in
Printf.eprintf "### %s\n%!" cmd;
ignore(Sys.command cmd)
(* Helpers
***********************************************************************)
let copy fname1 fname2 =
let buf = String.create 8192 in
let fin = open_in_bin fname1 in
let fout = open_out_bin fname2 in
let read = ref(-1) in
while !read <> 0 do
read := input fin buf 0 8192;
output fout buf 0 !read;
done;
close_in fin;
close_out fout
let must_wait_longer = function
| None -> true
| Some st ->
st.Unix.st_size = 0
&& (st.Unix.st_mtime -. st.Unix.st_atime <= 10.)
let rec wait_for_file fname =
Wait ( unfortunately busily ) that w.png exists AND is > 0 bytes
AND is a few seconds old ( for automatic color adjustments ) .
AND is a few seconds old (for automatic color adjustments). *)
let st = try Some(Unix.stat fname) with _ -> None in
if must_wait_longer st then begin
prerr_endline "wait for webcam";
Unix.sleep 1;
wait_for_file fname
end
;;
let exchange_rb img =
let ret = Array.make_matrix (Array.length img) (Array.length img.(0)) red in
let rgb_components c =
(c lsr 16) land 0xFF,
(c lsr 8) land 0xFF,
c land 0xFF in
for i = 0 to (Array.length img) - 1
do
for j = 0 to (Array.length img.(0)) -1
do
let (r,g,b) = rgb_components img.(i).(j) in
ret.(i).(j) <- Graphics.rgb b g r
done;
done;
ret
(************************************************************************)
IFDEF WIN32 THEN
(* This approach saves snapshots in a file that we can read in
(execute "vlc -p image" for more info). The "-I rc" starts the
remote-control interface, so no display is shown and we have an
easy way to quit. *)
let vlc_remote = "c:/\"Program files\"/VideoLAN/VLC/vlc -I rc \
dshow:// :dshow-adev=\"none\" --vout=image --image-out-replace \
--image-out-format=png --image-out-prefix=rubik"
let vlc = "c:/Program files/VideoLAN/VLC/vlc"
let vlc_args fname =
[| "--intf=rc"; "dshow://"; "--vout=image"; "--dshow-adev=\"none\"";
"--image-out-replace"; "--image-out-format=png";
"--image-out-prefix=" ^ fname |]
ELSE
IFDEF MACOS THEN
(* MacOS
----------------------------------------------------------------------
vlc does not connect to a webcam *)
let vlc = "/usr/bin/vlc"
let vlc_args fname =
[| "--intf=rc"; "v4l://"; "--vout=image"; "--image-out-replace";
"--image-out-format=png"; "--image-out-prefix=" ^ fname |]
ELSE
Unix
----------------------------------------------------------------------
At the beginning " gqcam --dump " was expected to deliver webcam
snapshots . However when using this command line snapshot
facility , the colors did not come out well .
We then tried using
* the rc or telnet interface but there is currently no way of
requesting a snapshot through these interfaces -- it should be
available in future version according to
. (
--intf = rc v4l:// --snapshot - path /tmp/ --snapshot - prefix ocaml
--snapshot - format png )
* the continuous file saving mode ( along the lines of " vlc
--intf = rc v4l:// --vout = image --image - out - replace
--image - out - format = png --image - out - prefix = rubik " ) but no color
correction is the applied
Finally , we tried the simple ' webcam ' program ( from xawtv , Debian
package : webcam ) to grab the frames but it simply does not work ...
= > We use vlc for its potential future ...
----------------------------------------------------------------------
At the beginning "gqcam --dump" was expected to deliver webcam
snapshots. However when using this command line snapshot
facility, the colors did not come out well.
We then tried vlc using
* the rc or telnet interface but there is currently no way of
requesting a snapshot through these interfaces -- it should be
available in future version according to
. (vlc
--intf=rc v4l:// --snapshot-path /tmp/ --snapshot-prefix ocaml
--snapshot-format png)
* the continuous file saving mode (along the lines of "vlc
--intf=rc v4l:// --vout=image --image-out-replace
--image-out-format=png --image-out-prefix=rubik") but no color
correction is the applied
Finally, we tried the simple 'webcam' program (from xawtv, Debian
package: webcam) to grab the frames but it simply does not work...
=> We use vlc for its potential future...
*)
let vlc = "vlc"
let vlc_args fname =
[| "--intf=rc"; "v4l://"; "--vout=image"; "--image-out-replace";
"--image-out-format=png"; "--image-out-prefix=" ^ fname |]
ENDIF
ENDIF
type webcam = {
pid : int;
png : string;
}
let start () =
let fname = Filename.temp_file "rubik" "" in
FIXME : If one connects a pipe to input commands to , does
not work as expected . With [ Unix.open_process_in ] ,
[ Unix.close_process_in ] does not terminate the process . So we
use the pid and [ kill ] .
not work as expected. With [Unix.open_process_in],
[Unix.close_process_in] does not terminate the process. So we
use the pid and [kill]. *)
IFDEF WIN32 THEN (
let pid =
Unix.create_process vlc (vlc_args fname)
Unix.stdin Unix.stdout Unix.stderr in
{ pid = pid; png = fname ^ ".png" }
)
ELSE (
match Unix.fork() with
| 0 -> Unix.execv vlc (vlc_args fname)
| pid -> { pid = pid; png = fname ^ ".png" }
)
ENDIF
;;
let stop w =
Unix.kill w.pid Sys.sigkill;
Unix.unlink w.png
;;
let exchange_rb img =
let ret = Array.make_matrix (Array.length img) (Array.length img.(0)) red in
let rgb_components c =
(c lsr 16) land 0xFF,
(c lsr 8) land 0xFF,
c land 0xFF in
for i = 0 to (Array.length img) - 1
do
for j = 0 to (Array.length img.(0)) -1
do
let (r,g,b) = rgb_components img.(i).(j) in
ret.(i).(j) <- Graphics.rgb b g r
done;
done;
ret
let take w =
wait_for_file w.png;
let png = Filename.temp_file "rubik_" ".png" in
copy w.png png;
let ppm = Filename.temp_file "rubik_" ".ppm" in
convert png ppm;
let img = exchange_rb (Ppm.as_matrix_exn ppm) in
Unix.unlink png;
Unix.unlink ppm;
img
(* Local Variables: *)
compile - command : " make snapshot.cmo "
(* End: *)
| null | https://raw.githubusercontent.com/bobot/FetedelascienceINRIAsaclay/87765db9f9c7211a26a09eb93e9c92f99a49b0bc/2010/robot/examples_mindstorm_lab/rubik/snapshot.ml | ocaml | FIXME: this file needs some cleanup
Helpers
**********************************************************************
**********************************************************************
This approach saves snapshots in a file that we can read in
(execute "vlc -p image" for more info). The "-I rc" starts the
remote-control interface, so no display is shown and we have an
easy way to quit.
MacOS
----------------------------------------------------------------------
vlc does not connect to a webcam
Local Variables:
End: | open Graphics
File : snapshot.ml
Copyright ( C ) 2008
< >
WWW : /
This library is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2.1 or
later as published by the Free Software Foundation , with the special
exception on linking described in the file LICENSE .
This library is distributed in the hope that it will be useful , but
WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file
LICENSE for more details .
Copyright (C) 2008
Christophe Troestler <>
WWW: /
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2.1 or
later as published by the Free Software Foundation, with the special
exception on linking described in the file LICENSE.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
LICENSE for more details. *)
type color = int
let imagemagick_convert = "convert"
let convert fname1 fname2 =
let cmd = imagemagick_convert ^ " " ^ fname1 ^ " " ^ fname2 in
Printf.eprintf "### %s\n%!" cmd;
ignore(Sys.command cmd)
let copy fname1 fname2 =
let buf = String.create 8192 in
let fin = open_in_bin fname1 in
let fout = open_out_bin fname2 in
let read = ref(-1) in
while !read <> 0 do
read := input fin buf 0 8192;
output fout buf 0 !read;
done;
close_in fin;
close_out fout
let must_wait_longer = function
| None -> true
| Some st ->
st.Unix.st_size = 0
&& (st.Unix.st_mtime -. st.Unix.st_atime <= 10.)
let rec wait_for_file fname =
Wait ( unfortunately busily ) that w.png exists AND is > 0 bytes
AND is a few seconds old ( for automatic color adjustments ) .
AND is a few seconds old (for automatic color adjustments). *)
let st = try Some(Unix.stat fname) with _ -> None in
if must_wait_longer st then begin
prerr_endline "wait for webcam";
Unix.sleep 1;
wait_for_file fname
end
;;
let exchange_rb img =
let ret = Array.make_matrix (Array.length img) (Array.length img.(0)) red in
let rgb_components c =
(c lsr 16) land 0xFF,
(c lsr 8) land 0xFF,
c land 0xFF in
for i = 0 to (Array.length img) - 1
do
for j = 0 to (Array.length img.(0)) -1
do
let (r,g,b) = rgb_components img.(i).(j) in
ret.(i).(j) <- Graphics.rgb b g r
done;
done;
ret
IFDEF WIN32 THEN
let vlc_remote = "c:/\"Program files\"/VideoLAN/VLC/vlc -I rc \
dshow:// :dshow-adev=\"none\" --vout=image --image-out-replace \
--image-out-format=png --image-out-prefix=rubik"
let vlc = "c:/Program files/VideoLAN/VLC/vlc"
let vlc_args fname =
[| "--intf=rc"; "dshow://"; "--vout=image"; "--dshow-adev=\"none\"";
"--image-out-replace"; "--image-out-format=png";
"--image-out-prefix=" ^ fname |]
ELSE
IFDEF MACOS THEN
let vlc = "/usr/bin/vlc"
let vlc_args fname =
[| "--intf=rc"; "v4l://"; "--vout=image"; "--image-out-replace";
"--image-out-format=png"; "--image-out-prefix=" ^ fname |]
ELSE
Unix
----------------------------------------------------------------------
At the beginning " gqcam --dump " was expected to deliver webcam
snapshots . However when using this command line snapshot
facility , the colors did not come out well .
We then tried using
* the rc or telnet interface but there is currently no way of
requesting a snapshot through these interfaces -- it should be
available in future version according to
. (
--intf = rc v4l:// --snapshot - path /tmp/ --snapshot - prefix ocaml
--snapshot - format png )
* the continuous file saving mode ( along the lines of " vlc
--intf = rc v4l:// --vout = image --image - out - replace
--image - out - format = png --image - out - prefix = rubik " ) but no color
correction is the applied
Finally , we tried the simple ' webcam ' program ( from xawtv , Debian
package : webcam ) to grab the frames but it simply does not work ...
= > We use vlc for its potential future ...
----------------------------------------------------------------------
At the beginning "gqcam --dump" was expected to deliver webcam
snapshots. However when using this command line snapshot
facility, the colors did not come out well.
We then tried vlc using
* the rc or telnet interface but there is currently no way of
requesting a snapshot through these interfaces -- it should be
available in future version according to
. (vlc
--intf=rc v4l:// --snapshot-path /tmp/ --snapshot-prefix ocaml
--snapshot-format png)
* the continuous file saving mode (along the lines of "vlc
--intf=rc v4l:// --vout=image --image-out-replace
--image-out-format=png --image-out-prefix=rubik") but no color
correction is the applied
Finally, we tried the simple 'webcam' program (from xawtv, Debian
package: webcam) to grab the frames but it simply does not work...
=> We use vlc for its potential future...
*)
let vlc = "vlc"
let vlc_args fname =
[| "--intf=rc"; "v4l://"; "--vout=image"; "--image-out-replace";
"--image-out-format=png"; "--image-out-prefix=" ^ fname |]
ENDIF
ENDIF
type webcam = {
pid : int;
png : string;
}
let start () =
let fname = Filename.temp_file "rubik" "" in
FIXME : If one connects a pipe to input commands to , does
not work as expected . With [ Unix.open_process_in ] ,
[ Unix.close_process_in ] does not terminate the process . So we
use the pid and [ kill ] .
not work as expected. With [Unix.open_process_in],
[Unix.close_process_in] does not terminate the process. So we
use the pid and [kill]. *)
IFDEF WIN32 THEN (
let pid =
Unix.create_process vlc (vlc_args fname)
Unix.stdin Unix.stdout Unix.stderr in
{ pid = pid; png = fname ^ ".png" }
)
ELSE (
match Unix.fork() with
| 0 -> Unix.execv vlc (vlc_args fname)
| pid -> { pid = pid; png = fname ^ ".png" }
)
ENDIF
;;
let stop w =
Unix.kill w.pid Sys.sigkill;
Unix.unlink w.png
;;
let exchange_rb img =
let ret = Array.make_matrix (Array.length img) (Array.length img.(0)) red in
let rgb_components c =
(c lsr 16) land 0xFF,
(c lsr 8) land 0xFF,
c land 0xFF in
for i = 0 to (Array.length img) - 1
do
for j = 0 to (Array.length img.(0)) -1
do
let (r,g,b) = rgb_components img.(i).(j) in
ret.(i).(j) <- Graphics.rgb b g r
done;
done;
ret
let take w =
wait_for_file w.png;
let png = Filename.temp_file "rubik_" ".png" in
copy w.png png;
let ppm = Filename.temp_file "rubik_" ".ppm" in
convert png ppm;
let img = exchange_rb (Ppm.as_matrix_exn ppm) in
Unix.unlink png;
Unix.unlink ppm;
img
compile - command : " make snapshot.cmo "
|
75139f843090f695ad1c913824529db69113b065d7d35144d0b62e11fea51353 | stackbuilders/tutorials | Main.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
module Main where
import Asterius.Types
import Control.Monad
import Data.Aeson hiding (Object)
import qualified Data.Aeson as A
import Data.Aeson.TH
import qualified Data.ByteString.Lazy.Char8 as B8
import Data.Text
data User =
User
{ name :: Text
, age :: Int
}
$(deriveJSON defaultOptions 'User)
handleReq :: JSString -> JSString -> IO JSObject
handleReq method rawBody =
case fromJSString method of
"POST" ->
let eitherUser :: Either String User
eitherUser = eitherDecode (B8.pack $ fromJSString rawBody)
in case eitherUser of
Right _ -> js_new_response (toJSString "Success!") 200
Left err -> js_new_response (toJSString err) 400
_ -> js_new_response (toJSString "Not a valid method") 405
foreign export javascript "handleReq" handleReq :: JSString -> JSString -> IO JSObject
foreign import javascript "new Response($1, {\"status\": $2})"
js_new_response :: JSString -> Int -> IO JSObject
main :: IO ()
main = putStrLn "CFW Cabal"
| null | https://raw.githubusercontent.com/stackbuilders/tutorials/c6100b5bf7a00a3669444313159dfc2ca0cf8eb7/tutorials/haskell/wasm-and-cloudflare-workers/code/cabal-cfw-example/Main.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE TemplateHaskell #
module Main where
import Asterius.Types
import Control.Monad
import Data.Aeson hiding (Object)
import qualified Data.Aeson as A
import Data.Aeson.TH
import qualified Data.ByteString.Lazy.Char8 as B8
import Data.Text
data User =
User
{ name :: Text
, age :: Int
}
$(deriveJSON defaultOptions 'User)
handleReq :: JSString -> JSString -> IO JSObject
handleReq method rawBody =
case fromJSString method of
"POST" ->
let eitherUser :: Either String User
eitherUser = eitherDecode (B8.pack $ fromJSString rawBody)
in case eitherUser of
Right _ -> js_new_response (toJSString "Success!") 200
Left err -> js_new_response (toJSString err) 400
_ -> js_new_response (toJSString "Not a valid method") 405
foreign export javascript "handleReq" handleReq :: JSString -> JSString -> IO JSObject
foreign import javascript "new Response($1, {\"status\": $2})"
js_new_response :: JSString -> Int -> IO JSObject
main :: IO ()
main = putStrLn "CFW Cabal"
|
b65a19ba147735b1d68f54351e7822b7105cca2ceb4b47d30155ad1e036ebe99 | tweag/asterius | rebindable7.hs | {-# OPTIONS -XRebindableSyntax #-}
This one tests rebindable syntax for do - notation
module Main where
import qualified Prelude
import GHC.Num
import GHC.Base hiding( Monad(..) )
class Foo a where
op :: a -> a
data T a = MkT a
instance Foo Int where
op x = x+1
(>>=) :: Foo a => T a -> (a -> T b) -> T b
(>>=) (MkT x) f = f (op x)
(>>) :: Foo a => T a -> T b -> T b
(>>) x y = x >>= (\_ -> y)
return :: Num a => a -> T a
return x = MkT (x+1)
fail :: String -> T a
fail s = error "urk"
t1 :: T Int
t1 = MkT 4
myt = do { x <- t1
; return x }
main = case myt of
MkT i -> Prelude.print i
| null | https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/test/ghc-testsuite/rebindable/rebindable7.hs | haskell | # OPTIONS -XRebindableSyntax # |
This one tests rebindable syntax for do - notation
module Main where
import qualified Prelude
import GHC.Num
import GHC.Base hiding( Monad(..) )
class Foo a where
op :: a -> a
data T a = MkT a
instance Foo Int where
op x = x+1
(>>=) :: Foo a => T a -> (a -> T b) -> T b
(>>=) (MkT x) f = f (op x)
(>>) :: Foo a => T a -> T b -> T b
(>>) x y = x >>= (\_ -> y)
return :: Num a => a -> T a
return x = MkT (x+1)
fail :: String -> T a
fail s = error "urk"
t1 :: T Int
t1 = MkT 4
myt = do { x <- t1
; return x }
main = case myt of
MkT i -> Prelude.print i
|
a3b4b55ae9c4531618e273a3f12242aed6531d990dc4738c4e2771136cc45707 | mfoemmel/erlang-otp | mnesia_backup.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1996 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
%%
%%-behaviour(mnesia_backup).
0
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
This module contains one implementation of callback functions
used by at backup and restore . The user may however
write an own module the same interface as mnesia_backup and
configure so the alternate module performs the actual
%% accesses to the backup media. This means that the user may put
the backup on medias that does not know about , possibly
on hosts where Erlang is not running .
%%
The OpaqueData argument is never interpreted by other parts of
%% Mnesia. It is the property of this module. Alternate implementations
of this module may have different interpretations of OpaqueData .
The OpaqueData argument given to open_write/1 and open_read/1
%% are forwarded directly from the user.
%%
%% All functions must return {ok, NewOpaqueData} or {error, Reason}.
%%
%% The NewOpaqueData arguments returned by backup callback functions will
%% be given as input when the next backup callback function is invoked.
%% If any return value does not match {ok, _} the backup will be aborted.
%%
%% The NewOpaqueData arguments returned by restore callback functions will
%% be given as input when the next restore callback function is invoked
%% If any return value does not match {ok, _} the restore will be aborted.
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-module(mnesia_backup).
-include_lib("kernel/include/file.hrl").
-export([
%% Write access
open_write/1,
write/2,
commit_write/1,
abort_write/1,
%% Read access
open_read/1,
read/1,
close_read/1
]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Backup callback interface
-record(backup, {tmp_file, file, file_desc}).
Opens backup media for write
%%
Returns { ok , OpaqueData } or { error , Reason }
open_write(OpaqueData) ->
File = OpaqueData,
Tmp = lists:concat([File,".BUPTMP"]),
file:delete(Tmp),
file:delete(File),
case disk_log:open([{name, make_ref()},
{file, Tmp},
{repair, false},
{linkto, self()}]) of
{ok, Fd} ->
{ok, #backup{tmp_file = Tmp, file = File, file_desc = Fd}};
{error, Reason} ->
{error, Reason}
end.
Writes BackupItems to the backup media
%%
Returns { ok , OpaqueData } or { error , Reason }
write(OpaqueData, BackupItems) ->
B = OpaqueData,
case disk_log:log_terms(B#backup.file_desc, BackupItems) of
ok ->
{ok, B};
{error, Reason} ->
abort_write(B),
{error, Reason}
end.
%% Closes the backup media after a successful backup
%%
Returns { ok , } or { error , Reason }
commit_write(OpaqueData) ->
B = OpaqueData,
case disk_log:sync(B#backup.file_desc) of
ok ->
case disk_log:close(B#backup.file_desc) of
ok ->
case file:rename(B#backup.tmp_file, B#backup.file) of
ok ->
{ok, B#backup.file};
{error, Reason} ->
{error, Reason}
end;
{error, Reason} ->
{error, Reason}
end;
{error, Reason} ->
{error, Reason}
end.
%% Closes the backup media after an interrupted backup
%%
Returns { ok , } or { error , Reason }
abort_write(BackupRef) ->
Res = disk_log:close(BackupRef#backup.file_desc),
file:delete(BackupRef#backup.tmp_file),
case Res of
ok ->
{ok, BackupRef#backup.file};
{error, Reason} ->
{error, Reason}
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Restore callback interface
-record(restore, {file, file_desc, cont}).
Opens backup media for read
%%
Returns { ok , OpaqueData } or { error , Reason }
open_read(OpaqueData) ->
File = OpaqueData,
case file:read_file_info(File) of
{error, Reason} ->
{error, Reason};
_FileInfo -> %% file exists
case disk_log:open([{file, File},
{name, make_ref()},
{repair, false},
{mode, read_only},
{linkto, self()}]) of
{ok, Fd} ->
{ok, #restore{file = File, file_desc = Fd, cont = start}};
{repaired, Fd, _, {badbytes, 0}} ->
{ok, #restore{file = File, file_desc = Fd, cont = start}};
{repaired, Fd, _, _} ->
{ok, #restore{file = File, file_desc = Fd, cont = start}};
{error, Reason} ->
{error, Reason}
end
end.
Reads BackupItems from the backup media
%%
Returns { ok , OpaqueData , BackupItems } or { error , Reason }
%%
BackupItems = = [ ] is interpreted as eof
read(OpaqueData) ->
R = OpaqueData,
Fd = R#restore.file_desc,
case disk_log:chunk(Fd, R#restore.cont) of
{error, Reason} ->
{error, {"Possibly truncated", Reason}};
eof ->
{ok, R, []};
{Cont, []} ->
read(R#restore{cont = Cont});
{Cont, BackupItems, _BadBytes} ->
{ok, R#restore{cont = Cont}, BackupItems};
{Cont, BackupItems} ->
{ok, R#restore{cont = Cont}, BackupItems}
end.
%% Closes the backup media after restore
%%
Returns { ok , } or { error , Reason }
close_read(OpaqueData) ->
R = OpaqueData,
case disk_log:close(R#restore.file_desc) of
ok -> {ok, R#restore.file};
{error, Reason} -> {error, Reason}
end.
0
| null | https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/mnesia/src/mnesia_backup.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
-behaviour(mnesia_backup).
accesses to the backup media. This means that the user may put
Mnesia. It is the property of this module. Alternate implementations
are forwarded directly from the user.
All functions must return {ok, NewOpaqueData} or {error, Reason}.
The NewOpaqueData arguments returned by backup callback functions will
be given as input when the next backup callback function is invoked.
If any return value does not match {ok, _} the backup will be aborted.
The NewOpaqueData arguments returned by restore callback functions will
be given as input when the next restore callback function is invoked
If any return value does not match {ok, _} the restore will be aborted.
Write access
Read access
Backup callback interface
Closes the backup media after a successful backup
Closes the backup media after an interrupted backup
Restore callback interface
file exists
Closes the backup media after restore
| Copyright Ericsson AB 1996 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
0
This module contains one implementation of callback functions
used by at backup and restore . The user may however
write an own module the same interface as mnesia_backup and
configure so the alternate module performs the actual
the backup on medias that does not know about , possibly
on hosts where Erlang is not running .
The OpaqueData argument is never interpreted by other parts of
of this module may have different interpretations of OpaqueData .
The OpaqueData argument given to open_write/1 and open_read/1
-module(mnesia_backup).
-include_lib("kernel/include/file.hrl").
-export([
open_write/1,
write/2,
commit_write/1,
abort_write/1,
open_read/1,
read/1,
close_read/1
]).
-record(backup, {tmp_file, file, file_desc}).
Opens backup media for write
Returns { ok , OpaqueData } or { error , Reason }
open_write(OpaqueData) ->
File = OpaqueData,
Tmp = lists:concat([File,".BUPTMP"]),
file:delete(Tmp),
file:delete(File),
case disk_log:open([{name, make_ref()},
{file, Tmp},
{repair, false},
{linkto, self()}]) of
{ok, Fd} ->
{ok, #backup{tmp_file = Tmp, file = File, file_desc = Fd}};
{error, Reason} ->
{error, Reason}
end.
Writes BackupItems to the backup media
Returns { ok , OpaqueData } or { error , Reason }
write(OpaqueData, BackupItems) ->
B = OpaqueData,
case disk_log:log_terms(B#backup.file_desc, BackupItems) of
ok ->
{ok, B};
{error, Reason} ->
abort_write(B),
{error, Reason}
end.
Returns { ok , } or { error , Reason }
commit_write(OpaqueData) ->
B = OpaqueData,
case disk_log:sync(B#backup.file_desc) of
ok ->
case disk_log:close(B#backup.file_desc) of
ok ->
case file:rename(B#backup.tmp_file, B#backup.file) of
ok ->
{ok, B#backup.file};
{error, Reason} ->
{error, Reason}
end;
{error, Reason} ->
{error, Reason}
end;
{error, Reason} ->
{error, Reason}
end.
Returns { ok , } or { error , Reason }
abort_write(BackupRef) ->
Res = disk_log:close(BackupRef#backup.file_desc),
file:delete(BackupRef#backup.tmp_file),
case Res of
ok ->
{ok, BackupRef#backup.file};
{error, Reason} ->
{error, Reason}
end.
-record(restore, {file, file_desc, cont}).
Opens backup media for read
Returns { ok , OpaqueData } or { error , Reason }
open_read(OpaqueData) ->
File = OpaqueData,
case file:read_file_info(File) of
{error, Reason} ->
{error, Reason};
case disk_log:open([{file, File},
{name, make_ref()},
{repair, false},
{mode, read_only},
{linkto, self()}]) of
{ok, Fd} ->
{ok, #restore{file = File, file_desc = Fd, cont = start}};
{repaired, Fd, _, {badbytes, 0}} ->
{ok, #restore{file = File, file_desc = Fd, cont = start}};
{repaired, Fd, _, _} ->
{ok, #restore{file = File, file_desc = Fd, cont = start}};
{error, Reason} ->
{error, Reason}
end
end.
Reads BackupItems from the backup media
Returns { ok , OpaqueData , BackupItems } or { error , Reason }
BackupItems = = [ ] is interpreted as eof
read(OpaqueData) ->
R = OpaqueData,
Fd = R#restore.file_desc,
case disk_log:chunk(Fd, R#restore.cont) of
{error, Reason} ->
{error, {"Possibly truncated", Reason}};
eof ->
{ok, R, []};
{Cont, []} ->
read(R#restore{cont = Cont});
{Cont, BackupItems, _BadBytes} ->
{ok, R#restore{cont = Cont}, BackupItems};
{Cont, BackupItems} ->
{ok, R#restore{cont = Cont}, BackupItems}
end.
Returns { ok , } or { error , Reason }
close_read(OpaqueData) ->
R = OpaqueData,
case disk_log:close(R#restore.file_desc) of
ok -> {ok, R#restore.file};
{error, Reason} -> {error, Reason}
end.
0
|
bf5cab8e579213b0f73b7f61491ffb04479a421bd8549871aea67e35eb7f8e78 | bitnomial/bitcoind-rpc | Wallet.hs | # LANGUAGE NumericUnderscores #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TupleSections #
module Bitcoin.Core.Test.Wallet (
walletRPC,
) where
import Control.Monad (replicateM, replicateM_, when)
import Control.Monad.IO.Class (liftIO)
import Data.Functor (void)
import Data.List (sortOn)
import qualified Data.Map.Strict as Map
import qualified Data.Text as Text
import Haskoin (OutPoint (OutPoint))
import Network.HTTP.Client (Manager)
import System.Directory (removeFile)
import System.IO.Temp (getCanonicalTemporaryDirectory)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (assertBool, (@?=))
import Bitcoin.Core.RPC (
AddressType (..),
BitcoindClient,
BumpFeeOptions (BumpFeeOptions),
CreatePsbtOptions (CreatePsbtOptions),
DescriptorRequest (DescriptorRequest),
ListUnspentOptions (ListUnspentOptions),
OutputDetails,
PsbtOutputs (PsbtOutputs),
Purpose (PurposeRecv),
withWallet,
)
import qualified Bitcoin.Core.RPC as RPC
import Bitcoin.Core.Regtest (NodeHandle, Version, nodeVersion, v20_1, v21_1)
import Bitcoin.Core.Test.Utils (
bitcoindTest,
generate,
initWallet,
shouldMatch,
testRpc,
)
walletRPC :: Manager -> NodeHandle -> TestTree
walletRPC mgr h =
testGroup "wallet-rpc" $
if v > v20_1
then
bitcoindTest mgr h
<$> [ testRpc "walletCommands" testWalletCommands
, testRpc "addressCommands" testAddressCommands
, testRpc "transactionCommands" testTransactionCommands
, testRpc "descriptorCommands" $ testDescriptorCommands v
, testRpc "psbtCommands" testPsbtCommands
]
else mempty
where
v = nodeVersion h
testWalletCommands :: BitcoindClient ()
testWalletCommands = do
loadWalletR <-
RPC.createWallet
walletName
Nothing
Nothing
walletPassword
(Just True)
Nothing
Nothing
Nothing
liftIO $ RPC.loadWalletName loadWalletR @?= walletName
RPC.listWallets >>= shouldMatch [walletName] . filter (not . Text.null)
RPC.unloadWallet (Just walletName) Nothing
RPC.listWallets >>= shouldMatch mempty
RPC.loadWallet walletName Nothing
RPC.listWallets >>= shouldMatch [walletName]
walletInfo <- RPC.getWalletInfo
liftIO $ do
RPC.walletStateName walletInfo @?= walletName
RPC.walletStateTxCount walletInfo @?= 0
RPC.rescanBlockchain (Just 0) (Just 0)
RPC.abortRescan
RPC.walletLock
RPC.walletPassphrase walletPassword 60
RPC.setTxFee 1000
tmpDir <- liftIO getCanonicalTemporaryDirectory
let walletDump = tmpDir <> "/wallet-dump"
RPC.dumpWallet walletDump
let walletBackup = tmpDir <> "/wallet-backup"
RPC.backupWallet walletBackup
RPC.walletLock
liftIO $ mapM_ removeFile [walletDump, walletBackup]
void $ RPC.unloadWallet (Just walletName) Nothing
where
walletName = "testCreateWallet"
walletPassword = "abc123"
testAddressCommands :: BitcoindClient ()
testAddressCommands = do
mapM_ initWallet [wallet1, wallet2]
(privKey, someAddress) <- withWallet wallet1 $ do
newAddress <- RPC.getNewAddress (Just label1) (Just Bech32)
newAddress2 <- RPC.getNewAddress (Just label2) (Just Legacy)
newAddress3 <- RPC.getNewAddress (Just label2) (Just P2SHSegwit)
newAddress4 <- RPC.getNewAddress (Just label2) Nothing
RPC.listLabels Nothing >>= shouldMatch [label1, label2]
RPC.getAddressesByLabel label1 >>= shouldMatch [(newAddress, PurposeRecv)] . Map.toList
RPC.getAddressesByLabel label2
>>= shouldMatch
( sortOn
fst
[ (newAddress2, PurposeRecv)
, (newAddress3, PurposeRecv)
, (newAddress4, PurposeRecv)
]
)
. Map.toList
RPC.setLabel newAddress label3
RPC.getAddressesByLabel label3 >>= shouldMatch [(newAddress, PurposeRecv)] . Map.toList
RPC.addMultisigAddress 2 [newAddress2, newAddress3, newAddress4] Nothing Nothing
privKey <- RPC.dumpPrivKey newAddress
signingAddress <- RPC.getNewAddress Nothing (Just Legacy)
RPC.signMessage signingAddress "TEST"
pure (privKey, newAddress2)
withWallet wallet2 $ do
RPC.importPrivKey privKey (Just "priv-test") Nothing
RPC.importAddress someAddress (Just "addr-test") (Just True) Nothing
where
label1 = "account-1"
label2 = "account-2"
label3 = "account-3"
wallet1 = "testAddressCommands1"
wallet2 = "testAddressCommands2"
testTransactionCommands :: BitcoindClient ()
testTransactionCommands = do
mapM_ initWallet [userWalletA, minerWallet]
addressA1 <- withWallet userWalletA $ RPC.getNewAddress (Just labelA1) Nothing
txId <- withWallet minerWallet $ do
replicateM_ 200 generate
txId <- sendSimple addressA1 sendAmount1 "funding" "user-a"
replicateM_ 200 generate
pure txId
addrs <- withWallet userWalletA $ do
RPC.getBalances
RPC.getBalance Nothing Nothing Nothing >>= shouldMatch sendAmount1
RPC.listReceivedByAddress Nothing Nothing Nothing Nothing
>>= shouldMatch 1 . length
RPC.listReceivedByLabel Nothing Nothing Nothing
>>= shouldMatch 1 . length
RPC.getAddressInfo addressA1
RPC.getRawChangeAddress Nothing
RPC.getReceivedByAddress addressA1 Nothing >>= shouldMatch sendAmount1
RPC.getReceivedByLabel labelA1 Nothing >>= shouldMatch sendAmount1
RPC.getTransaction txId Nothing
RPC.listSinceBlock Nothing Nothing Nothing Nothing
RPC.listTransactions Nothing Nothing Nothing Nothing
replicateM 20 $ RPC.getNewAddress (Just labelA2) Nothing
withWallet minerWallet $ do
unspent <-
RPC.listUnspent
Nothing
Nothing
Nothing
(Just True)
(ListUnspentOptions Nothing Nothing Nothing Nothing)
liftIO . assertBool "At least one output" $ (not . null) unspent
RPC.lockUnspent False $ toOutPoint <$> unspent
RPC.listLockUnspent >>= shouldMatch (toOutPoint <$> unspent)
RPC.lockUnspent True $ toOutPoint <$> unspent
txId2 <-
RPC.sendMany
(Map.fromList $ (,100_000) <$> addrs)
(Just "send-many")
mempty
(Just True)
Nothing
Nothing
(Just 1)
let options =
BumpFeeOptions
{ RPC.bumpFeeConfTarget = Nothing
, RPC.bumpFeeFeeRate = Just 10
, RPC.bumpFeeReplaceable = True
, RPC.bumpFeeEstimateMode = Nothing
}
RPC.psbtBumpFee txId2 (Just options)
RPC.bumpFee txId2 (Just options)
pure ()
where
userWalletA = "testTransactionCommands-A"
minerWallet = "testTransactionCommands-M"
labelA1 = "recv-1"
labelA2 = "recv-2"
sendAmount1 = 3_0000_0000
sendSimple addr amount what to =
RPC.sendToAddress
addr
amount
(Just what)
(Just to)
Nothing
(Just True)
Nothing
Nothing
(Just True)
(Just 1)
toOutPoint :: OutputDetails -> OutPoint
toOutPoint = OutPoint <$> RPC.outputTxId <*> fromIntegral . RPC.outputVOut
testDescriptorCommands :: Version -> BitcoindClient ()
testDescriptorCommands v = do
RPC.createWallet walletName Nothing Nothing mempty (Just True) (Just True) Nothing Nothing
withWallet walletName $ do
RPC.getNewAddress (Just "internal") Nothing
RPC.importDescriptors
[ DescriptorRequest
theDescriptor
Nothing
(Just (0, Just 100))
Nothing
Nothing
Nothing
(Just "imported-descriptor")
]
when (v > v21_1) $ RPC.listDescriptors >>= shouldMatch 6 . length
where
walletName = "descriptorWallet"
-- Taken from bitcoind descriptor wallet documentation
theDescriptor = "pkh([d34db33f/44'/0'/0']xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/1/*)"
testPsbtCommands :: BitcoindClient ()
testPsbtCommands = do
mapM_ initWallet [walletA, walletB, walletC]
changeAddr <- withWallet walletA $ do
replicateM_ 200 generate
RPC.getNewAddress (Just "change") Nothing
utxos <- withWallet walletB $ do
replicateM_ 200 generate
take 3 . sortOn isConfirmed
<$> RPC.listUnspent
Nothing
Nothing
Nothing
Nothing
(ListUnspentOptions Nothing Nothing Nothing Nothing)
liftIO $ length utxos @?= 3
recvAddr <- withWallet walletC $ RPC.getNewAddress Nothing Nothing
let theAmount = sum (RPC.outputAmount <$> utxos) `quot` 2
outputs = PsbtOutputs [(recvAddr, theAmount)] mempty
options =
CreatePsbtOptions
{ RPC.createPsbtAddInputs = Just True
, RPC.createPsbtChangeAddress = Just changeAddr
, RPC.createPsbtChangePosition = Just 1
, RPC.createPsbtChangeType = Nothing
, RPC.createPsbtIncludeWatching = Just True
, RPC.createPsbtLockUnspents = Just True
, RPC.createPsbtFeeRate = Just 1
, RPC.createPsbtSubtractFee = mempty
, RPC.createPsbtReplaceable = Just True
, RPC.createPsbtConfTarget = Nothing
, RPC.createPsbtEstimateMode = Nothing
}
void . withWallet walletA $ do
RPC.createFundedPsbt mempty outputs Nothing (Just options) (Just True)
where
walletA = "psbtWallet-A"
walletB = "psbtWallet-B"
walletC = "psbtWallet-C"
isConfirmed = (> 6) . RPC.outputConfs
TODO encryptWallet ,
-- TODO importWallet,
TODO importMulti ,
-- TODO signRawTx,
TODO processPbst
| null | https://raw.githubusercontent.com/bitnomial/bitcoind-rpc/6a8befdce7828f2ae867fc7dcb411a36a363de52/bitcoind-regtest/test/Bitcoin/Core/Test/Wallet.hs | haskell | # LANGUAGE OverloadedStrings #
Taken from bitcoind descriptor wallet documentation
TODO importWallet,
TODO signRawTx, | # LANGUAGE NumericUnderscores #
# LANGUAGE TupleSections #
module Bitcoin.Core.Test.Wallet (
walletRPC,
) where
import Control.Monad (replicateM, replicateM_, when)
import Control.Monad.IO.Class (liftIO)
import Data.Functor (void)
import Data.List (sortOn)
import qualified Data.Map.Strict as Map
import qualified Data.Text as Text
import Haskoin (OutPoint (OutPoint))
import Network.HTTP.Client (Manager)
import System.Directory (removeFile)
import System.IO.Temp (getCanonicalTemporaryDirectory)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (assertBool, (@?=))
import Bitcoin.Core.RPC (
AddressType (..),
BitcoindClient,
BumpFeeOptions (BumpFeeOptions),
CreatePsbtOptions (CreatePsbtOptions),
DescriptorRequest (DescriptorRequest),
ListUnspentOptions (ListUnspentOptions),
OutputDetails,
PsbtOutputs (PsbtOutputs),
Purpose (PurposeRecv),
withWallet,
)
import qualified Bitcoin.Core.RPC as RPC
import Bitcoin.Core.Regtest (NodeHandle, Version, nodeVersion, v20_1, v21_1)
import Bitcoin.Core.Test.Utils (
bitcoindTest,
generate,
initWallet,
shouldMatch,
testRpc,
)
walletRPC :: Manager -> NodeHandle -> TestTree
walletRPC mgr h =
testGroup "wallet-rpc" $
if v > v20_1
then
bitcoindTest mgr h
<$> [ testRpc "walletCommands" testWalletCommands
, testRpc "addressCommands" testAddressCommands
, testRpc "transactionCommands" testTransactionCommands
, testRpc "descriptorCommands" $ testDescriptorCommands v
, testRpc "psbtCommands" testPsbtCommands
]
else mempty
where
v = nodeVersion h
testWalletCommands :: BitcoindClient ()
testWalletCommands = do
loadWalletR <-
RPC.createWallet
walletName
Nothing
Nothing
walletPassword
(Just True)
Nothing
Nothing
Nothing
liftIO $ RPC.loadWalletName loadWalletR @?= walletName
RPC.listWallets >>= shouldMatch [walletName] . filter (not . Text.null)
RPC.unloadWallet (Just walletName) Nothing
RPC.listWallets >>= shouldMatch mempty
RPC.loadWallet walletName Nothing
RPC.listWallets >>= shouldMatch [walletName]
walletInfo <- RPC.getWalletInfo
liftIO $ do
RPC.walletStateName walletInfo @?= walletName
RPC.walletStateTxCount walletInfo @?= 0
RPC.rescanBlockchain (Just 0) (Just 0)
RPC.abortRescan
RPC.walletLock
RPC.walletPassphrase walletPassword 60
RPC.setTxFee 1000
tmpDir <- liftIO getCanonicalTemporaryDirectory
let walletDump = tmpDir <> "/wallet-dump"
RPC.dumpWallet walletDump
let walletBackup = tmpDir <> "/wallet-backup"
RPC.backupWallet walletBackup
RPC.walletLock
liftIO $ mapM_ removeFile [walletDump, walletBackup]
void $ RPC.unloadWallet (Just walletName) Nothing
where
walletName = "testCreateWallet"
walletPassword = "abc123"
testAddressCommands :: BitcoindClient ()
testAddressCommands = do
mapM_ initWallet [wallet1, wallet2]
(privKey, someAddress) <- withWallet wallet1 $ do
newAddress <- RPC.getNewAddress (Just label1) (Just Bech32)
newAddress2 <- RPC.getNewAddress (Just label2) (Just Legacy)
newAddress3 <- RPC.getNewAddress (Just label2) (Just P2SHSegwit)
newAddress4 <- RPC.getNewAddress (Just label2) Nothing
RPC.listLabels Nothing >>= shouldMatch [label1, label2]
RPC.getAddressesByLabel label1 >>= shouldMatch [(newAddress, PurposeRecv)] . Map.toList
RPC.getAddressesByLabel label2
>>= shouldMatch
( sortOn
fst
[ (newAddress2, PurposeRecv)
, (newAddress3, PurposeRecv)
, (newAddress4, PurposeRecv)
]
)
. Map.toList
RPC.setLabel newAddress label3
RPC.getAddressesByLabel label3 >>= shouldMatch [(newAddress, PurposeRecv)] . Map.toList
RPC.addMultisigAddress 2 [newAddress2, newAddress3, newAddress4] Nothing Nothing
privKey <- RPC.dumpPrivKey newAddress
signingAddress <- RPC.getNewAddress Nothing (Just Legacy)
RPC.signMessage signingAddress "TEST"
pure (privKey, newAddress2)
withWallet wallet2 $ do
RPC.importPrivKey privKey (Just "priv-test") Nothing
RPC.importAddress someAddress (Just "addr-test") (Just True) Nothing
where
label1 = "account-1"
label2 = "account-2"
label3 = "account-3"
wallet1 = "testAddressCommands1"
wallet2 = "testAddressCommands2"
testTransactionCommands :: BitcoindClient ()
testTransactionCommands = do
mapM_ initWallet [userWalletA, minerWallet]
addressA1 <- withWallet userWalletA $ RPC.getNewAddress (Just labelA1) Nothing
txId <- withWallet minerWallet $ do
replicateM_ 200 generate
txId <- sendSimple addressA1 sendAmount1 "funding" "user-a"
replicateM_ 200 generate
pure txId
addrs <- withWallet userWalletA $ do
RPC.getBalances
RPC.getBalance Nothing Nothing Nothing >>= shouldMatch sendAmount1
RPC.listReceivedByAddress Nothing Nothing Nothing Nothing
>>= shouldMatch 1 . length
RPC.listReceivedByLabel Nothing Nothing Nothing
>>= shouldMatch 1 . length
RPC.getAddressInfo addressA1
RPC.getRawChangeAddress Nothing
RPC.getReceivedByAddress addressA1 Nothing >>= shouldMatch sendAmount1
RPC.getReceivedByLabel labelA1 Nothing >>= shouldMatch sendAmount1
RPC.getTransaction txId Nothing
RPC.listSinceBlock Nothing Nothing Nothing Nothing
RPC.listTransactions Nothing Nothing Nothing Nothing
replicateM 20 $ RPC.getNewAddress (Just labelA2) Nothing
withWallet minerWallet $ do
unspent <-
RPC.listUnspent
Nothing
Nothing
Nothing
(Just True)
(ListUnspentOptions Nothing Nothing Nothing Nothing)
liftIO . assertBool "At least one output" $ (not . null) unspent
RPC.lockUnspent False $ toOutPoint <$> unspent
RPC.listLockUnspent >>= shouldMatch (toOutPoint <$> unspent)
RPC.lockUnspent True $ toOutPoint <$> unspent
txId2 <-
RPC.sendMany
(Map.fromList $ (,100_000) <$> addrs)
(Just "send-many")
mempty
(Just True)
Nothing
Nothing
(Just 1)
let options =
BumpFeeOptions
{ RPC.bumpFeeConfTarget = Nothing
, RPC.bumpFeeFeeRate = Just 10
, RPC.bumpFeeReplaceable = True
, RPC.bumpFeeEstimateMode = Nothing
}
RPC.psbtBumpFee txId2 (Just options)
RPC.bumpFee txId2 (Just options)
pure ()
where
userWalletA = "testTransactionCommands-A"
minerWallet = "testTransactionCommands-M"
labelA1 = "recv-1"
labelA2 = "recv-2"
sendAmount1 = 3_0000_0000
sendSimple addr amount what to =
RPC.sendToAddress
addr
amount
(Just what)
(Just to)
Nothing
(Just True)
Nothing
Nothing
(Just True)
(Just 1)
toOutPoint :: OutputDetails -> OutPoint
toOutPoint = OutPoint <$> RPC.outputTxId <*> fromIntegral . RPC.outputVOut
testDescriptorCommands :: Version -> BitcoindClient ()
testDescriptorCommands v = do
RPC.createWallet walletName Nothing Nothing mempty (Just True) (Just True) Nothing Nothing
withWallet walletName $ do
RPC.getNewAddress (Just "internal") Nothing
RPC.importDescriptors
[ DescriptorRequest
theDescriptor
Nothing
(Just (0, Just 100))
Nothing
Nothing
Nothing
(Just "imported-descriptor")
]
when (v > v21_1) $ RPC.listDescriptors >>= shouldMatch 6 . length
where
walletName = "descriptorWallet"
theDescriptor = "pkh([d34db33f/44'/0'/0']xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/1/*)"
testPsbtCommands :: BitcoindClient ()
testPsbtCommands = do
mapM_ initWallet [walletA, walletB, walletC]
changeAddr <- withWallet walletA $ do
replicateM_ 200 generate
RPC.getNewAddress (Just "change") Nothing
utxos <- withWallet walletB $ do
replicateM_ 200 generate
take 3 . sortOn isConfirmed
<$> RPC.listUnspent
Nothing
Nothing
Nothing
Nothing
(ListUnspentOptions Nothing Nothing Nothing Nothing)
liftIO $ length utxos @?= 3
recvAddr <- withWallet walletC $ RPC.getNewAddress Nothing Nothing
let theAmount = sum (RPC.outputAmount <$> utxos) `quot` 2
outputs = PsbtOutputs [(recvAddr, theAmount)] mempty
options =
CreatePsbtOptions
{ RPC.createPsbtAddInputs = Just True
, RPC.createPsbtChangeAddress = Just changeAddr
, RPC.createPsbtChangePosition = Just 1
, RPC.createPsbtChangeType = Nothing
, RPC.createPsbtIncludeWatching = Just True
, RPC.createPsbtLockUnspents = Just True
, RPC.createPsbtFeeRate = Just 1
, RPC.createPsbtSubtractFee = mempty
, RPC.createPsbtReplaceable = Just True
, RPC.createPsbtConfTarget = Nothing
, RPC.createPsbtEstimateMode = Nothing
}
void . withWallet walletA $ do
RPC.createFundedPsbt mempty outputs Nothing (Just options) (Just True)
where
walletA = "psbtWallet-A"
walletB = "psbtWallet-B"
walletC = "psbtWallet-C"
isConfirmed = (> 6) . RPC.outputConfs
TODO encryptWallet ,
TODO importMulti ,
TODO processPbst
|
8d0fa4fca3db29f0c5a1b91faed20b1ad30fab0d1be890789b3b97ee59e44c83 | digital-dj-tools/dj-data-converter | stats.cljc | (ns converter.stats
(:require [clojure.core.matrix.stats :as stats]
[converter.universal.core :as u]
[converter.universal.tempo :as ut]))
(defn mean-tempos
[library]
(double (stats/mean (map (comp count ::u/tempos) (::u/collection library)))))
(defn count-tempos-of-rand-n-items
[library n]
(map (comp count ::u/tempos) (take n (shuffle (::u/collection library)))))
(defn max-tempos
[library]
(apply max (map (comp count ::u/tempos) (::u/collection library))))
(defn tempo-battitos-of-rand-n-items
[library n]
(map #(map ::ut/battito (::u/tempos %)) (take n (shuffle (::u/collection library)))))
(defn mean-markers
[library]
(double (stats/mean (map (comp count ::u/markers) (::u/collection library))))) | null | https://raw.githubusercontent.com/digital-dj-tools/dj-data-converter/de1ae5cda60bc64ee3cca1a09b11e1808dd4738a/test/converter/stats.cljc | clojure | (ns converter.stats
(:require [clojure.core.matrix.stats :as stats]
[converter.universal.core :as u]
[converter.universal.tempo :as ut]))
(defn mean-tempos
[library]
(double (stats/mean (map (comp count ::u/tempos) (::u/collection library)))))
(defn count-tempos-of-rand-n-items
[library n]
(map (comp count ::u/tempos) (take n (shuffle (::u/collection library)))))
(defn max-tempos
[library]
(apply max (map (comp count ::u/tempos) (::u/collection library))))
(defn tempo-battitos-of-rand-n-items
[library n]
(map #(map ::ut/battito (::u/tempos %)) (take n (shuffle (::u/collection library)))))
(defn mean-markers
[library]
(double (stats/mean (map (comp count ::u/markers) (::u/collection library))))) | |
d1f28c0c105c7e282824899202f1a7811fe40e2e36391568419cfa163098a478 | thesis/shale | configurer.clj | (ns shale.configurer
(:use shale.utils)
(:require [carica.core :refer [resources]]
[environ.core :refer [env]]
clojure.walk
[clojure.java.io :as io]
clojure.edn
[shale.logging :as logging]
[shale.utils :refer [pretty]]))
(defn strip-namespace [kw]
(keyword (name kw)))
(defn resolve-env-keyword!
"If a keyword has the namespace :env, look it up in the environment and return the env var value"
[kw]
(if (and (keyword? kw) (namespace kw) (= "env" (namespace kw)))
(get env (strip-namespace kw))
kw))
(defn get-config
"Get the config file. Path can either be specified by a CONFIG_FILE
environment variable, or can be found on the classpath as config.clj."
[]
(let [config-paths (->> [(some->> (env :config-file)
(str "file://"))
(resources "config.clj")]
flatten
(filter identity)
(map io/as-url)
concat)]
(if-let [raw-config (some-> config-paths first slurp clojure.edn/read-string)]
(do
(logging/info "Loading config...\n")
(logging/info (pretty raw-config))
(logging/info "Resolving environment variables...\n")
(clojure.walk/postwalk resolve-env-keyword! raw-config))
(throw (ex-info "Configuration not found. Requires either config.clj on classpath or CONFIG_FILE env var" {})))))
| null | https://raw.githubusercontent.com/thesis/shale/84180532e46ee5d9ee0218138da04ea035bcf7d2/src/clj/shale/configurer.clj | clojure | (ns shale.configurer
(:use shale.utils)
(:require [carica.core :refer [resources]]
[environ.core :refer [env]]
clojure.walk
[clojure.java.io :as io]
clojure.edn
[shale.logging :as logging]
[shale.utils :refer [pretty]]))
(defn strip-namespace [kw]
(keyword (name kw)))
(defn resolve-env-keyword!
"If a keyword has the namespace :env, look it up in the environment and return the env var value"
[kw]
(if (and (keyword? kw) (namespace kw) (= "env" (namespace kw)))
(get env (strip-namespace kw))
kw))
(defn get-config
"Get the config file. Path can either be specified by a CONFIG_FILE
environment variable, or can be found on the classpath as config.clj."
[]
(let [config-paths (->> [(some->> (env :config-file)
(str "file://"))
(resources "config.clj")]
flatten
(filter identity)
(map io/as-url)
concat)]
(if-let [raw-config (some-> config-paths first slurp clojure.edn/read-string)]
(do
(logging/info "Loading config...\n")
(logging/info (pretty raw-config))
(logging/info "Resolving environment variables...\n")
(clojure.walk/postwalk resolve-env-keyword! raw-config))
(throw (ex-info "Configuration not found. Requires either config.clj on classpath or CONFIG_FILE env var" {})))))
| |
2ec7c551aab2ac9d1af4b8c26e022a2dacfdf5e4e3e3de99b8a3b7c67a2ba055 | patricoferris/ocaml-multicore-monorepo | sql.eml.ml | module type DB = Caqti_lwt.CONNECTION
module R = Caqti_request
module T = Caqti_type
let list_comments =
let query =
R.collect T.unit T.(tup2 int string)
"SELECT id, text FROM comment" in
fun (module Db : DB) ->
let%lwt comments_or_error = Db.collect_list query () in
Caqti_lwt.or_fail comments_or_error
let add_comment =
let query =
R.exec T.string
"INSERT INTO comment (text) VALUES ($1)" in
fun text (module Db : DB) ->
let%lwt unit_or_error = Db.exec query text in
Caqti_lwt.or_fail unit_or_error
let render comments request =
<html>
<body>
% comments |> List.iter (fun (_id, comment) ->
<p><%s comment %></p><% ); %>
<%s! Dream.form_tag ~action:"/" request %>
<input name="text" autofocus>
</form>
</body>
</html>
let () =
Eio_main.run @@ fun env ->
Dream.run env
@@ Dream.logger
@@ Dream.sql_pool "sqlite3:db.sqlite"
@@ Dream.sql_sessions
@@ Dream.router [
Dream.get "/" (fun request ->
let comments = Dream.sql request list_comments in
Dream.html (render comments request));
Dream.post "/" (fun request ->
match Dream.form request with
| `Ok ["text", text] ->
Dream.sql request (add_comment text);
Dream.redirect request "/"
| _ ->
Dream.empty `Bad_Request);
]
@@ Dream.not_found
| null | https://raw.githubusercontent.com/patricoferris/ocaml-multicore-monorepo/22b441e6727bc303950b3b37c8fbc024c748fe55/duniverse/dream/example/h-sql/sql.eml.ml | ocaml | module type DB = Caqti_lwt.CONNECTION
module R = Caqti_request
module T = Caqti_type
let list_comments =
let query =
R.collect T.unit T.(tup2 int string)
"SELECT id, text FROM comment" in
fun (module Db : DB) ->
let%lwt comments_or_error = Db.collect_list query () in
Caqti_lwt.or_fail comments_or_error
let add_comment =
let query =
R.exec T.string
"INSERT INTO comment (text) VALUES ($1)" in
fun text (module Db : DB) ->
let%lwt unit_or_error = Db.exec query text in
Caqti_lwt.or_fail unit_or_error
let render comments request =
<html>
<body>
% comments |> List.iter (fun (_id, comment) ->
<p><%s comment %></p><% ); %>
<%s! Dream.form_tag ~action:"/" request %>
<input name="text" autofocus>
</form>
</body>
</html>
let () =
Eio_main.run @@ fun env ->
Dream.run env
@@ Dream.logger
@@ Dream.sql_pool "sqlite3:db.sqlite"
@@ Dream.sql_sessions
@@ Dream.router [
Dream.get "/" (fun request ->
let comments = Dream.sql request list_comments in
Dream.html (render comments request));
Dream.post "/" (fun request ->
match Dream.form request with
| `Ok ["text", text] ->
Dream.sql request (add_comment text);
Dream.redirect request "/"
| _ ->
Dream.empty `Bad_Request);
]
@@ Dream.not_found
| |
46f9cb72e2c0542bdfa93cb157b59a84b8783b059afc05a00339f4273e2d1086 | OtpChatBot/Ybot | web_admin_req_handler.erl | %%%-----------------------------------------------------------------------------
%%% @author 0xAX <>
%%% @doc
Ybot web admin requests handler .
%%% @end
%%%-----------------------------------------------------------------------------
-module(web_admin_req_handler).
-export([init/3]).
-export([handle/2]).
-export([terminate/3]).
%%=============================================================================
%% Cowboy handler callback
%%=============================================================================
init(_Transport, Req, []) ->
{ok, Req, undefined}.
handle(Req, State) ->
{ok, WebAdmin} = application:get_env(ybot, web_admin),
%% check access credentials if auth is enabled
case config_option(webadmin_auth, WebAdmin) of
true ->
%% get configured credentials
AuthUser = list_to_binary(
config_option(webadmin_auth_user, WebAdmin)),
AuthPasswd = list_to_binary(
config_option(webadmin_auth_passwd, WebAdmin)),
case is_authorized(Req, AuthUser, AuthPasswd) of
{true, Req1} -> authorized(Req1, State);
{false, Req1} -> unauthorized(Req1, State)
end;
_ ->
authorized(Req, State)
end.
terminate(_Reason, _Req, _State) ->
ok.
%%=============================================================================
Internal functions
%%=============================================================================
authorized(Req, State) ->
{Path, Req1} = cowboy_req:path(Req),
case Path of
<<"/">> ->
{ok, Bin} = file:read_file(web_admin:docroot("index.html")),
{ok, Req2} = cowboy_req:reply(200,
[
{<<"content-type">>, <<"text/html">>}
], Bin, Req1),
{ok, Req2, State};
<<"/admin">> ->
%% check body
case cowboy_req:has_body(Req1) of
true ->
%% get body
case cowboy_req:body(Req1) of
{ok, Body, Req2} ->
handle_request(Body, Req2, State);
_ ->
{ok, Req1, State}
end;
false ->
{ok, Req1, State}
end
end.
handle_request(Body, Req, State) ->
% get method and params
{[{<<"method">>, Method},{<<"params">>, Params}]} = jiffy:decode(Body),
case Method of
<<"get_start_page">> ->
% get runned transports
Transports = [atom_to_list(element(1, Transport)) ++ " " ++
pid_to_list(element(2, Transport)) ++ " " ++ "\n" || Transport <- gen_server:call(ybot_manager, get_transports),
(element(1, Transport) /= http) or (element(1, Transport) /= skype)],
% Get plugins
Plugins = {plugins, format_plugins_helper(gen_server:call(ybot_manager, get_plugins))},
% Is history using
IsHistory = ybot_utils:get_val(ybot_history, {is_history, false}),
% History limit
HistoryLimit = ybot_utils:get_val(ybot_history, {history_limit, 0}),
% Get observer
IsObserver = ybot_utils:get_val(ybot_plugins_observer, {is_observer, false}),
% Get observer timeout
ObserverTimeout = ybot_utils:get_val(ybot_plugins_observer, {observer_timeout, 0}),
% Get storage
Storage = {storage_type, ybot_utils:get_config_val(brain_storage, mnesia)},
% prepare data to json
Data = {[{transport, list_to_binary(Transports)}, IsHistory, HistoryLimit, Plugins, IsObserver, ObserverTimeout,
Storage]},
% Convert to json
Json = jiffy:encode(Data),
Send info to
cowboy_req:reply(200, [], Json, Req);
<<"update_observer">> ->
% Get params
{[{<<"timeout">>, Timeout},{<<"is_observer">>, UseObserver}]} = Params,
% convert time to integer
Time = ybot_utils:to_int(Timeout),
case UseObserver of
true ->
case whereis(ybot_plugins_observer) of
undefined ->
% get plugins directory
{ok, PluginsDirectory} = application:get_env(ybot, plugins_path),
% get all plugins paths
PluginsPaths = gen_server:call(ybot_manager, get_plugins_paths),
% start observer
ybot_plugins_observer:start_link(PluginsDirectory, PluginsPaths, Time);
_ ->
% update plugins observer timeout
gen_server:cast(ybot_plugins_observer, {update_timeout, Time})
end;
false ->
case whereis(ybot_plugins_observer) of
undefined ->
ok;
_ ->
ybot_plugins_observer:stop()
end
end;
<<"update_history">> ->
% Get params
{[{<<"timeout">>, Timeout},{<<"is_history">>, IsHistory}]} = Params,
% Convert history parama to integer
HistoryLimit = ybot_utils:to_int(Timeout),
% Check use history or not
case IsHistory of
true ->
case whereis(ybot_history) of
undefined ->
% start ybot_history process
ybot_history:start_link(HistoryLimit);
_ ->
% update history limit
gen_server:cast(ybot_history, {update_history_limit, HistoryLimit})
end;
false ->
case whereis(ybot_history) of
undefined ->
ok;
_ ->
ybot_history:stop()
end
end;
<<"upload_plugin">> ->
% Get params
{[{<<"upload_plugin_path">>, PluginPath}]} = Params,
PluginName = filename:basename(binary_to_list(PluginPath)),
{ok, PluginsDirectory} = application:get_env(ybot, plugins_path),
{_, _, _, PluginData} = ibrowse:send_req(binary_to_list(PluginPath), [], get),
{ok, IODevice} = file:open(PluginsDirectory ++ PluginName, [write]),
file:write(IODevice, PluginData), file:close(IODevice),
file:close(IODevice);
<<"get_runned_transports">> ->
Transports = [atom_to_list(element(1, Transport)) ++ " " ++
pid_to_list(element(2, Transport)) ++ " " ++ "\n" || Transport <- gen_server:call(ybot_manager, get_transports),
(element(1, Transport) /= http) or (element(1, Transport) /= skype)],
Data = jiffy:encode({[{transport, list_to_binary(Transports)}]}),
cowboy_req:reply(200, [], Data, Req);
<<"start_irc">> ->
{[{<<"irc_login">>, IrcLogin}, {<<"irc_password">>, Password},
{<<"irc_channel">>, IrcChannel}, {<<"irc_channel_key">>, Key}, {<<"irc_server_host">>, Host},
{<<"irc_server_port">>, Port}, {<<"irc_use_ssl">>, Ssl}, {<<"irc_reconnect_timeout">>, RecTimeout}]} = Params,
Options = [{port, ybot_utils:to_int(Port)}, {use_ssl, Ssl}, {reconnect_timeout, ybot_utils:to_int(RecTimeout)}],
ybot_manager:run_transport({irc, IrcLogin, {IrcChannel, Key}, {Host, Password}, Options}),
cowboy_req:reply(200, [], <<"ok">>, Req);
<<"start_xmpp">> ->
{[{<<"xmpp_login">>, Login}, {<<"xmpp_password">>, Password},
{<<"xmpp_room">>, Room}, {<<"xmpp_nick">>, Nick}, {<<"xmpp_server">>, Host}, {<<"xmpp_resource">>, Resource},
{<<"xmpp_port">>, Port}, {<<"xmpp_ssl">>, Ssl}, {<<"xmpp_reconnect_timeout">>, RecTimeout}]} = Params,
Options = [{port, ybot_utils:to_int(Port)}, {use_ssl, Ssl}, {reconnect_timeout, ybot_utils:to_int(RecTimeout)}],
ybot_manager:run_transport({xmpp, Login, Password, Room, Nick, Host, Resource, Options}),
cowboy_req:reply(200, [], <<"ok">>, Req);
<<"start_campfire">> ->
{[{<<"login">>, Login}, {<<"token">>, Token},
{<<"room">>, Room}, {<<"subdomain">>, SubDomain}, {<<"reconnect_timeout">>, RecTimeout}]} = Params,
ybot_manager:run_transport({campfire, Login, Token, ybot_utils:to_int(Room), SubDomain, [{reconnect_timeout, ybot_utils:to_int(RecTimeout)}]}),
cowboy_req:reply(200, [], <<"ok">>, Req);
<<"start_hipchat">> ->
{[{<<"hipchat_jid">>, Jid}, {<<"hipchat_password">>, Password},
{<<"hipchat_room">>, Room}, {<<"hipchat_nick">>, Nick}, {<<"hipchat_reconnect_timeout">>, RecTimeout}]} = Params,
ybot_manager:run_transport({hipchat, Jid, Password, Room, <<"chat.hipchat.com">>, <<"bot">>, Nick, [{reconnect_timeout, ybot_utils:to_int(RecTimeout)}]}),
cowboy_req:reply(200, [], <<"ok">>, Req);
<<"start_skype">> ->
{[{<<"skype_http_host">>, Host}, {<<"skype_http_port">>, Port}]} = Params,
ybot_manager:run_transport({skype, true, Host, ybot_utils:to_int(Port)}),
cowboy_req:reply(200, [], <<"ok">>, Req);
<<"start_http">> ->
{[{<<"http_host">>, Host}, {<<"http_port">>, Port}, {<<"http_bot_nick">>, Nick}]} = Params,
ybot_manager:run_transport({http, Host, ybot_utils:to_int(Port), Nick}),
cowboy_req:reply(200, [], <<"ok">>, Req);
<<"start_flowdock">> ->
{[{<<"flowdock_nick">>, Nick}, {<<"flowdock_login">>, Login},
{<<"flowdock_password">>, Password}, {<<"flowdock_org">>, Org}, {<<"flowdock_flow">>, Flow}]} = Params,
ybot_manager:run_transport({flowdock, Nick, Login, Password, Org, Flow}),
cowboy_req:reply(200, [], <<"ok">>, Req);
<<"start_talkerapp">> ->
{[{<<"talkerapp_nick">>, Nick}, {<<"talkerapp_room">>, Room}, {<<"talkerapp_token">>, Token}]} = Params,
ybot_manager:run_transport({talkerapp, Nick, Room, Token}),
cowboy_req:reply(200, [], <<"ok">>, Req);
<<"get_storage_info">> ->
StorageHost = ybot_utils:get_val(brain_api_host, {storage_host, false}),
StoragePort = ybot_utils:get_val(brain_api_port, {storage_port, 0}),
Data = jiffy:encode({[StorageHost, StoragePort]}),
cowboy_req:reply(200, [], Data, Req);
_ ->
ok
end,
{ok, Req, State}.
%% @doc Format plugins
format_plugins_helper(Plugins) ->
list_to_binary([Lang ++ " " ++ Name ++ " " ++ Path ++ "\n" || {plugin, Lang, Name, Path} <- Plugins]).
%% Authorization helpers
is_authorized(Req, User, Passwd) ->
{ok, Auth, Req1} = cowboy_req:parse_header(<<"authorization">>, Req),
case Auth of
{<<"basic">>, {User, Passwd}} ->
{true, Req1};
_ ->
{false, Req1}
end.
unauthorized(Req, State) ->
Req1 = cowboy_req:set_resp_header(<<"Www-Authenticate">>,
<<"Basic realm=\"Secure Area\"">>, Req),
Req2 = cowboy_req:set_resp_body(unauthorized_body(), Req1),
{ok, Req3} = cowboy_req:reply(401, Req2),
{ok, Req3, State}.
unauthorized_body() ->
<<"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"
\"-html401-19991224/loose.dt\">
<html>
<head>
<title>Error</title>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">
</head>
<body><h1>401 Unauthorized.</h1></body>
</html>
">>.
config_option(Key, Options) ->
case lists:keyfind(Key, 1, Options) of
{Key, Value} -> Value;
false -> false
end.
| null | https://raw.githubusercontent.com/OtpChatBot/Ybot/5ce05fea0eb9001d1c0ff89702729f4c80743872/src/web/web_admin_req_handler.erl | erlang | -----------------------------------------------------------------------------
@author 0xAX <>
@doc
@end
-----------------------------------------------------------------------------
=============================================================================
Cowboy handler callback
=============================================================================
check access credentials if auth is enabled
get configured credentials
=============================================================================
=============================================================================
check body
get body
get method and params
get runned transports
Get plugins
Is history using
History limit
Get observer
Get observer timeout
Get storage
prepare data to json
Convert to json
Get params
convert time to integer
get plugins directory
get all plugins paths
start observer
update plugins observer timeout
Get params
Convert history parama to integer
Check use history or not
start ybot_history process
update history limit
Get params
@doc Format plugins
Authorization helpers | Ybot web admin requests handler .
-module(web_admin_req_handler).
-export([init/3]).
-export([handle/2]).
-export([terminate/3]).
init(_Transport, Req, []) ->
{ok, Req, undefined}.
handle(Req, State) ->
{ok, WebAdmin} = application:get_env(ybot, web_admin),
case config_option(webadmin_auth, WebAdmin) of
true ->
AuthUser = list_to_binary(
config_option(webadmin_auth_user, WebAdmin)),
AuthPasswd = list_to_binary(
config_option(webadmin_auth_passwd, WebAdmin)),
case is_authorized(Req, AuthUser, AuthPasswd) of
{true, Req1} -> authorized(Req1, State);
{false, Req1} -> unauthorized(Req1, State)
end;
_ ->
authorized(Req, State)
end.
terminate(_Reason, _Req, _State) ->
ok.
Internal functions
authorized(Req, State) ->
{Path, Req1} = cowboy_req:path(Req),
case Path of
<<"/">> ->
{ok, Bin} = file:read_file(web_admin:docroot("index.html")),
{ok, Req2} = cowboy_req:reply(200,
[
{<<"content-type">>, <<"text/html">>}
], Bin, Req1),
{ok, Req2, State};
<<"/admin">> ->
case cowboy_req:has_body(Req1) of
true ->
case cowboy_req:body(Req1) of
{ok, Body, Req2} ->
handle_request(Body, Req2, State);
_ ->
{ok, Req1, State}
end;
false ->
{ok, Req1, State}
end
end.
handle_request(Body, Req, State) ->
{[{<<"method">>, Method},{<<"params">>, Params}]} = jiffy:decode(Body),
case Method of
<<"get_start_page">> ->
Transports = [atom_to_list(element(1, Transport)) ++ " " ++
pid_to_list(element(2, Transport)) ++ " " ++ "\n" || Transport <- gen_server:call(ybot_manager, get_transports),
(element(1, Transport) /= http) or (element(1, Transport) /= skype)],
Plugins = {plugins, format_plugins_helper(gen_server:call(ybot_manager, get_plugins))},
IsHistory = ybot_utils:get_val(ybot_history, {is_history, false}),
HistoryLimit = ybot_utils:get_val(ybot_history, {history_limit, 0}),
IsObserver = ybot_utils:get_val(ybot_plugins_observer, {is_observer, false}),
ObserverTimeout = ybot_utils:get_val(ybot_plugins_observer, {observer_timeout, 0}),
Storage = {storage_type, ybot_utils:get_config_val(brain_storage, mnesia)},
Data = {[{transport, list_to_binary(Transports)}, IsHistory, HistoryLimit, Plugins, IsObserver, ObserverTimeout,
Storage]},
Json = jiffy:encode(Data),
Send info to
cowboy_req:reply(200, [], Json, Req);
<<"update_observer">> ->
{[{<<"timeout">>, Timeout},{<<"is_observer">>, UseObserver}]} = Params,
Time = ybot_utils:to_int(Timeout),
case UseObserver of
true ->
case whereis(ybot_plugins_observer) of
undefined ->
{ok, PluginsDirectory} = application:get_env(ybot, plugins_path),
PluginsPaths = gen_server:call(ybot_manager, get_plugins_paths),
ybot_plugins_observer:start_link(PluginsDirectory, PluginsPaths, Time);
_ ->
gen_server:cast(ybot_plugins_observer, {update_timeout, Time})
end;
false ->
case whereis(ybot_plugins_observer) of
undefined ->
ok;
_ ->
ybot_plugins_observer:stop()
end
end;
<<"update_history">> ->
{[{<<"timeout">>, Timeout},{<<"is_history">>, IsHistory}]} = Params,
HistoryLimit = ybot_utils:to_int(Timeout),
case IsHistory of
true ->
case whereis(ybot_history) of
undefined ->
ybot_history:start_link(HistoryLimit);
_ ->
gen_server:cast(ybot_history, {update_history_limit, HistoryLimit})
end;
false ->
case whereis(ybot_history) of
undefined ->
ok;
_ ->
ybot_history:stop()
end
end;
<<"upload_plugin">> ->
{[{<<"upload_plugin_path">>, PluginPath}]} = Params,
PluginName = filename:basename(binary_to_list(PluginPath)),
{ok, PluginsDirectory} = application:get_env(ybot, plugins_path),
{_, _, _, PluginData} = ibrowse:send_req(binary_to_list(PluginPath), [], get),
{ok, IODevice} = file:open(PluginsDirectory ++ PluginName, [write]),
file:write(IODevice, PluginData), file:close(IODevice),
file:close(IODevice);
<<"get_runned_transports">> ->
Transports = [atom_to_list(element(1, Transport)) ++ " " ++
pid_to_list(element(2, Transport)) ++ " " ++ "\n" || Transport <- gen_server:call(ybot_manager, get_transports),
(element(1, Transport) /= http) or (element(1, Transport) /= skype)],
Data = jiffy:encode({[{transport, list_to_binary(Transports)}]}),
cowboy_req:reply(200, [], Data, Req);
<<"start_irc">> ->
{[{<<"irc_login">>, IrcLogin}, {<<"irc_password">>, Password},
{<<"irc_channel">>, IrcChannel}, {<<"irc_channel_key">>, Key}, {<<"irc_server_host">>, Host},
{<<"irc_server_port">>, Port}, {<<"irc_use_ssl">>, Ssl}, {<<"irc_reconnect_timeout">>, RecTimeout}]} = Params,
Options = [{port, ybot_utils:to_int(Port)}, {use_ssl, Ssl}, {reconnect_timeout, ybot_utils:to_int(RecTimeout)}],
ybot_manager:run_transport({irc, IrcLogin, {IrcChannel, Key}, {Host, Password}, Options}),
cowboy_req:reply(200, [], <<"ok">>, Req);
<<"start_xmpp">> ->
{[{<<"xmpp_login">>, Login}, {<<"xmpp_password">>, Password},
{<<"xmpp_room">>, Room}, {<<"xmpp_nick">>, Nick}, {<<"xmpp_server">>, Host}, {<<"xmpp_resource">>, Resource},
{<<"xmpp_port">>, Port}, {<<"xmpp_ssl">>, Ssl}, {<<"xmpp_reconnect_timeout">>, RecTimeout}]} = Params,
Options = [{port, ybot_utils:to_int(Port)}, {use_ssl, Ssl}, {reconnect_timeout, ybot_utils:to_int(RecTimeout)}],
ybot_manager:run_transport({xmpp, Login, Password, Room, Nick, Host, Resource, Options}),
cowboy_req:reply(200, [], <<"ok">>, Req);
<<"start_campfire">> ->
{[{<<"login">>, Login}, {<<"token">>, Token},
{<<"room">>, Room}, {<<"subdomain">>, SubDomain}, {<<"reconnect_timeout">>, RecTimeout}]} = Params,
ybot_manager:run_transport({campfire, Login, Token, ybot_utils:to_int(Room), SubDomain, [{reconnect_timeout, ybot_utils:to_int(RecTimeout)}]}),
cowboy_req:reply(200, [], <<"ok">>, Req);
<<"start_hipchat">> ->
{[{<<"hipchat_jid">>, Jid}, {<<"hipchat_password">>, Password},
{<<"hipchat_room">>, Room}, {<<"hipchat_nick">>, Nick}, {<<"hipchat_reconnect_timeout">>, RecTimeout}]} = Params,
ybot_manager:run_transport({hipchat, Jid, Password, Room, <<"chat.hipchat.com">>, <<"bot">>, Nick, [{reconnect_timeout, ybot_utils:to_int(RecTimeout)}]}),
cowboy_req:reply(200, [], <<"ok">>, Req);
<<"start_skype">> ->
{[{<<"skype_http_host">>, Host}, {<<"skype_http_port">>, Port}]} = Params,
ybot_manager:run_transport({skype, true, Host, ybot_utils:to_int(Port)}),
cowboy_req:reply(200, [], <<"ok">>, Req);
<<"start_http">> ->
{[{<<"http_host">>, Host}, {<<"http_port">>, Port}, {<<"http_bot_nick">>, Nick}]} = Params,
ybot_manager:run_transport({http, Host, ybot_utils:to_int(Port), Nick}),
cowboy_req:reply(200, [], <<"ok">>, Req);
<<"start_flowdock">> ->
{[{<<"flowdock_nick">>, Nick}, {<<"flowdock_login">>, Login},
{<<"flowdock_password">>, Password}, {<<"flowdock_org">>, Org}, {<<"flowdock_flow">>, Flow}]} = Params,
ybot_manager:run_transport({flowdock, Nick, Login, Password, Org, Flow}),
cowboy_req:reply(200, [], <<"ok">>, Req);
<<"start_talkerapp">> ->
{[{<<"talkerapp_nick">>, Nick}, {<<"talkerapp_room">>, Room}, {<<"talkerapp_token">>, Token}]} = Params,
ybot_manager:run_transport({talkerapp, Nick, Room, Token}),
cowboy_req:reply(200, [], <<"ok">>, Req);
<<"get_storage_info">> ->
StorageHost = ybot_utils:get_val(brain_api_host, {storage_host, false}),
StoragePort = ybot_utils:get_val(brain_api_port, {storage_port, 0}),
Data = jiffy:encode({[StorageHost, StoragePort]}),
cowboy_req:reply(200, [], Data, Req);
_ ->
ok
end,
{ok, Req, State}.
format_plugins_helper(Plugins) ->
list_to_binary([Lang ++ " " ++ Name ++ " " ++ Path ++ "\n" || {plugin, Lang, Name, Path} <- Plugins]).
is_authorized(Req, User, Passwd) ->
{ok, Auth, Req1} = cowboy_req:parse_header(<<"authorization">>, Req),
case Auth of
{<<"basic">>, {User, Passwd}} ->
{true, Req1};
_ ->
{false, Req1}
end.
unauthorized(Req, State) ->
Req1 = cowboy_req:set_resp_header(<<"Www-Authenticate">>,
<<"Basic realm=\"Secure Area\"">>, Req),
Req2 = cowboy_req:set_resp_body(unauthorized_body(), Req1),
{ok, Req3} = cowboy_req:reply(401, Req2),
{ok, Req3, State}.
unauthorized_body() ->
<<"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"
\"-html401-19991224/loose.dt\">
<html>
<head>
<title>Error</title>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">
</head>
<body><h1>401 Unauthorized.</h1></body>
</html>
">>.
config_option(Key, Options) ->
case lists:keyfind(Key, 1, Options) of
{Key, Value} -> Value;
false -> false
end.
|
ba063d5bd8236466ebe1c88fd47206212f5594acc6baa537d82af545f0b7037d | conreality/conreality | bcm2836.mli | (* This is free and unencumbered software released into the public domain. *)
module GPIO : sig
module Pin : sig
val construct : Scripting.Table.t -> Device.t
end
end
| null | https://raw.githubusercontent.com/conreality/conreality/e03328ef1f0056b58e4ffe181a279a1dc776e094/src/consensus/machinery/bcm2836.mli | ocaml | This is free and unencumbered software released into the public domain. |
module GPIO : sig
module Pin : sig
val construct : Scripting.Table.t -> Device.t
end
end
|
eced361868749e0292a3dc238cf1b0b31ac70c4ccc0552dd37320eeb84d2fb6b | solatis/haskell-network-anonymous-i2p | Parser.hs | -- | Parser defintions
--
-- Defines parsers used by the I2P SAM protocol
--
-- __Warning__: This function is used internally by 'Network.Anonymous.I2P'
-- and using these functions directly is unsupported. The
-- interface of these functions might change at any time without
-- prior notice.
--
module Network.Anonymous.I2P.Protocol.Parser where
import Control.Applicative ((*>), (<$>), (<*),
(<|>))
import qualified Data.Attoparsec.ByteString as Atto
import qualified Data.Attoparsec.ByteString.Char8 as Atto8
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.Word (Word8)
import qualified Network.Anonymous.I2P.Protocol.Parser.Ast as A
-- | Ascii offset representation of a double quote.
doubleQuote :: Word8
doubleQuote = 34
-- | Ascii offset representation of a single quote.
singleQuote :: Word8
singleQuote = 39
-- | Ascii offset representation of a backslash.
backslash :: Word8
backslash = 92
-- | Ascii offset representation of an equality sign.
equals :: Word8
equals = 61
-- | Parses a single- or double-quoted value, and returns all bytes within the
-- value; the unescaping is beyond the scope of this function (since different
-- unescaping mechanisms might be desired).
--
Looking at the SAMv3 code on github , it appears as if the protocol is kind
-- hacked together at the moment: no character escaping is performed at all,
-- and no formal tokens / AST is used.
--
-- So this function already goes way beyond what is required, but it cannot
-- hurt to do so.
quotedValue :: Atto.Parser BS.ByteString
quotedValue =
let quoted :: Word8 -- ^ The character used for quoting
-> Atto.Parser BS.ByteString -- ^ The value inside the quotes, without the surrounding quotes
quoted c = (Atto.word8 c *> escaped c <* Atto.word8 c)
-- | Parses an escaped string, with an arbitrary surrounding quote type.
escaped :: Word8 -> Atto.Parser BS.ByteString
escaped c = BS8.concat <$> Atto8.many'
-- Make sure that we eat pairs of backslashes; this will make sure
-- that a string such as "\\\\" is interpreted correctly, and the
-- ending quoted will not be interpreted as escaped.
( Atto8.string (BS8.pack "\\\\")
-- This eats all escaped quotes and leaves them in tact; the unescaping
-- is beyond the scope of this function.
<|> Atto8.string (BS.pack [backslash, c])
-- And for the rest: eat everything that is not a quote.
<|> (BS.singleton <$> Atto.satisfy (/= c)))
in quoted doubleQuote <|> quoted singleQuote
-- | An unquoted value is "everything until a whitespace or newline is reached".
-- This is pretty broad, but the SAM implementation in I2P just uses a strtok,
-- and is quite hackish.
unquotedValue :: Atto.Parser BS.ByteString
unquotedValue =
Atto8.takeWhile1 (not . Atto8.isSpace)
-- | Parses either a quoted value or an unquoted value
value :: Atto.Parser BS.ByteString
value =
quotedValue <|> unquotedValue
-- | Parses key and value
keyValue :: Atto.Parser A.Token
keyValue = do
A.Token k _ <- key
_ <- Atto.word8 equals
v <- value
return (A.Token k (Just v))
| Parses a key , which , after studying the SAMv3 code , is anything until either
-- a space has been reached, or an '=' is reached.
key :: Atto.Parser A.Token
key =
let isKeyEnd '=' = True
isKeyEnd c = Atto8.isSpace c
in flip A.Token Nothing <$> Atto8.takeWhile1 (not . isKeyEnd)
-- | A Token is either a Key or a Key/Value combination.
token :: Atto.Parser A.Token
token =
Atto.skipWhile Atto8.isHorizontalSpace *> (keyValue <|> key)
-- | Parser that reads keys or key/values
tokens :: Atto.Parser [A.Token]
tokens =
Atto.many' token
-- | A generic parser that reads a whole line of key/values and ends in a newline
line :: Atto.Parser A.Line
line =
tokens <* Atto8.endOfLine
| null | https://raw.githubusercontent.com/solatis/haskell-network-anonymous-i2p/57681eedc06ed349f3ac011ada221c567c91739a/src/Network/Anonymous/I2P/Protocol/Parser.hs | haskell | | Parser defintions
Defines parsers used by the I2P SAM protocol
__Warning__: This function is used internally by 'Network.Anonymous.I2P'
and using these functions directly is unsupported. The
interface of these functions might change at any time without
prior notice.
| Ascii offset representation of a double quote.
| Ascii offset representation of a single quote.
| Ascii offset representation of a backslash.
| Ascii offset representation of an equality sign.
| Parses a single- or double-quoted value, and returns all bytes within the
value; the unescaping is beyond the scope of this function (since different
unescaping mechanisms might be desired).
hacked together at the moment: no character escaping is performed at all,
and no formal tokens / AST is used.
So this function already goes way beyond what is required, but it cannot
hurt to do so.
^ The character used for quoting
^ The value inside the quotes, without the surrounding quotes
| Parses an escaped string, with an arbitrary surrounding quote type.
Make sure that we eat pairs of backslashes; this will make sure
that a string such as "\\\\" is interpreted correctly, and the
ending quoted will not be interpreted as escaped.
This eats all escaped quotes and leaves them in tact; the unescaping
is beyond the scope of this function.
And for the rest: eat everything that is not a quote.
| An unquoted value is "everything until a whitespace or newline is reached".
This is pretty broad, but the SAM implementation in I2P just uses a strtok,
and is quite hackish.
| Parses either a quoted value or an unquoted value
| Parses key and value
a space has been reached, or an '=' is reached.
| A Token is either a Key or a Key/Value combination.
| Parser that reads keys or key/values
| A generic parser that reads a whole line of key/values and ends in a newline |
module Network.Anonymous.I2P.Protocol.Parser where
import Control.Applicative ((*>), (<$>), (<*),
(<|>))
import qualified Data.Attoparsec.ByteString as Atto
import qualified Data.Attoparsec.ByteString.Char8 as Atto8
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.Word (Word8)
import qualified Network.Anonymous.I2P.Protocol.Parser.Ast as A
doubleQuote :: Word8
doubleQuote = 34
singleQuote :: Word8
singleQuote = 39
backslash :: Word8
backslash = 92
equals :: Word8
equals = 61
Looking at the SAMv3 code on github , it appears as if the protocol is kind
quotedValue :: Atto.Parser BS.ByteString
quotedValue =
quoted c = (Atto.word8 c *> escaped c <* Atto.word8 c)
escaped :: Word8 -> Atto.Parser BS.ByteString
escaped c = BS8.concat <$> Atto8.many'
( Atto8.string (BS8.pack "\\\\")
<|> Atto8.string (BS.pack [backslash, c])
<|> (BS.singleton <$> Atto.satisfy (/= c)))
in quoted doubleQuote <|> quoted singleQuote
unquotedValue :: Atto.Parser BS.ByteString
unquotedValue =
Atto8.takeWhile1 (not . Atto8.isSpace)
value :: Atto.Parser BS.ByteString
value =
quotedValue <|> unquotedValue
keyValue :: Atto.Parser A.Token
keyValue = do
A.Token k _ <- key
_ <- Atto.word8 equals
v <- value
return (A.Token k (Just v))
| Parses a key , which , after studying the SAMv3 code , is anything until either
key :: Atto.Parser A.Token
key =
let isKeyEnd '=' = True
isKeyEnd c = Atto8.isSpace c
in flip A.Token Nothing <$> Atto8.takeWhile1 (not . isKeyEnd)
token :: Atto.Parser A.Token
token =
Atto.skipWhile Atto8.isHorizontalSpace *> (keyValue <|> key)
tokens :: Atto.Parser [A.Token]
tokens =
Atto.many' token
line :: Atto.Parser A.Line
line =
tokens <* Atto8.endOfLine
|
007575e887c9575f35c638b390448c51a19211b515a33596a14b03d72a846f09 | cwmaguire/zombunity-mud | move_test.clj | (ns zombunity.move-test
(:use clojure.test)
(:require [zombunity.dispatch :as disp]
[zombunity.data :as data]
[zombunity.data.simple-data :as simple-data]))
(def conn-id (rand 100))
(def no-movement-msg {:message "No movement commands as of yet." :conn-id conn-id})
(deftest test-chat
(disp/register-daemon (first (disp/filter-classpath-namespaces #"\.move$")))
(data/set-target :zombunity.data.simple-data/simple)
(for [cmd ["n" "s" "e" "w" "u" "d" "ne" "nw" "se" "sw"]]
(do
(disp/dispatch {:type cmd :conn-id conn-id})
(is (= no-movement-msg @simple-data/msg-client) "Expected \"no movements yet\" message"))))
| null | https://raw.githubusercontent.com/cwmaguire/zombunity-mud/ec14406f4addac9b9a0742d3043a6e7bccef1fa6/zombunity_server/test/zombunity/move_test.clj | clojure | (ns zombunity.move-test
(:use clojure.test)
(:require [zombunity.dispatch :as disp]
[zombunity.data :as data]
[zombunity.data.simple-data :as simple-data]))
(def conn-id (rand 100))
(def no-movement-msg {:message "No movement commands as of yet." :conn-id conn-id})
(deftest test-chat
(disp/register-daemon (first (disp/filter-classpath-namespaces #"\.move$")))
(data/set-target :zombunity.data.simple-data/simple)
(for [cmd ["n" "s" "e" "w" "u" "d" "ne" "nw" "se" "sw"]]
(do
(disp/dispatch {:type cmd :conn-id conn-id})
(is (= no-movement-msg @simple-data/msg-client) "Expected \"no movements yet\" message"))))
| |
e75e14e1d4e61fe56a287dc7af6e9bacd7765b3de721164ca2a480be80dee091 | g000001/MacLISP-compat | GRIND.lisp |
;;; -*-LISP-*-
;;; ***********************************************************************
* * * * * * * * * * * S - expression formatter for files ( grind ) * * * * * * * * *
;;; ***********************************************************************
* * ( c ) Copyright 1980 Massachusetts Institute of Technology * * * * * * * * * * *
;;; ****** this is a read-only file! (all writes reserved) ****************
;;; ***********************************************************************
This version of Grind works in both ITS and Multics Maclisp
GFILE - fns for pretty - printing and grinding files .
(eval-when (eval compile)
(or (status nofeature MACLISP)
(status macro /#)
(load '((LISP) SHARPM)))
)
(herald GRIND /422)
(declare (array* (notype (gtab/| 128.)))
(special merge readtable grindreadtable remsemi ~r
grindpredict grindproperties grindef predict
grindfn grindmacro programspace topwidth
/;/ ; user - paging form
prog? n m l h arg chrct linel pagewidth gap comspace
/ ; ? ^d macro unbnd - vrbl
cnvrgrindflag outfiles infile stringp)
(*expr form topwidth programspace pagewidth comspace
nomerge remsemi stringp)
(*fexpr trace slashify unslashify grindfn grindmacro
unreadmacro readmacro grindef)
(*lexpr merge predict user-paging grindfill testl)
(mapex t)
(genprefix gr+)
(fixnum nn
mm
(grchrct)
(newlinel-set fixnum)
(prog-predict notype fixnum fixnum)
(block-predict notype fixnum fixnum)
(setq-predict notype fixnum fixnum)
(panmax notype fixnum fixnum)
(maxpan notype fixnum fixnum)
(gflatsize)))
(prog () ;some initializations
(and (not (boundp 'grind-use-original-readtable))
(setq grind-use-original-readtable t))
(and (or (not (boundp 'grindreadtable)) ;readtable (default).
(null grindreadtable))
((lambda (readtable) (setsyntax 12. 'single ()) ;^l made noticeable.
(setsyntax '/;
'splicing
'semi-comment))
(setq grindreadtable
(*array ()
'readtable
grind-use-original-readtable))))
(setq macro '/;
( copysymbol ' / ; ( ) )
/ ; ( copysymbol ' /;/ ; ( ) ) )
(setq grindlinct 8. global-lincnt 59. comnt () /;/;? ())
(setq stringp (status feature string))
)
;;; Grinds and files file.
(defun grind fexpr (file)
((lambda (x)
(cond ((and stringp (stringp (car file)))) ;already filed.
(t (cond ((not (status feature its))
(cond ((status feature DEC20)
(setq x (append (namelist x) () ))
(rplacd (cddr x) () ))
((probef x) (deletef x)))))
(apply 'ufile x)))
file)
(apply 'grind0 file)))
(defun grind0 fexpr (file) ;grinds file and returns file
(or (status feature grindef)
(funcall autoload (cons 'grindef (get 'grindef 'autoload))))
(prog (remsemi linel *nopoint readtable base l ^q ^r ^w ^d
outfiles eof n /;/;? comnt terpri)
(setq base 10. linel programspace
readtable grindreadtable remsemi t)
(cond
((and stringp (stringp (car file)))
(inpush (openi (car file)))
(setq
outfiles
(list
(openo
(mergef
(cond ((null (cdr file))
(princ '|/
Filing as !GRIND OUTPUT |)
'(* /!GRIND OUTPUT))
((cadr file)))
(cons (car (namelist ())) '*) )))))
('t (apply (cond ((status feature sail) 'eread) ('uread))
(cond ((and (null (cdr file)) (symbolp (car file)))
(car file))
((and (status feature sail)
(cadr file)
(eq (cadr file) 'dsk))
(cons (car file) (cons '| | (cdr file))))
('t file)))
(uwrite)))
(setq eof (list ()) n topwidth)
(setq ^q t ^r t ^w t grindlinct global-lincnt)
read (and (= (tyipeek 47791616. -1)
59.) ;catch top-level splicing macro
(readch)
(cond ((eq (car (setq l (car (semi-comment)))) /;)
(rem/;)
(go read))
(t (go read1))))
(and (null ^q) (setq l eof) (go read1)) ;catch eof in tyipeek
(and (eq (car (setq l (read eof))) /;) ;store /; strings of /; comments.
(rem/;)
(go read))
read1(prinallcmnt) ;print stored /; comments
(or (eq eof l) (go process))
exit (terpri)
(setq ~r ())
(and stringp
(stringp (car file))
(close (car outfiles))) ;won't get ufile'd
(return file)
process
(cond ((eq l (ascii 12.)) ;formfeed read in ppage mode
(or user-paging (go read)) ;ignore ^l except in user-paging mode.
(and (< (tyipeek 50167296. -1) 0)
(go exit)) ;any non-trivial characters before eof?
(terpri)
(grindpage)
(setq /;/;? t)
(go read))
((eq (car l) /;/;) ;toplevel ;;... comment
(newlinel-set topwidth)
/ ; ? (= linel ( grchrct ) ) ( turpri ) ( turpri ) ) ; produces blank line preceding new
/ ;) ; block of /;/ ; comments . ( turpri is
already in rem/;/ ;) . a total of 3
turpri 's are necessary if initially
(fillarray 'gtab/| '(())) ;chrct is not linel, ie we have just
(cond (user-paging (turpri) (turpri)) ;finished a line and have not yet cr.
((< (turpri)
(catch (\ (panmax l (grchrct) 0.) 60.))) ;clear hash array
(grindpage))
((turpri)))
(cond ((eq (car l) 'lap) (lap-grind))
((sprint1 l linel 0.) (prin1 l)))
(tyo 32.) ;prevents toplevel atoms from being
(go read))) ;accidentally merged by being separated only by
;cr.
(defun newlinel-set (x)
(setq chrct (+ chrct (- x linel))
linel x))
(putprop /; '(lambda (l n m) 0.) 'grindpredict)
/ ; ' ( lambda ( l n m ) 1 . ) ' grindpredict )
;;semi-colon comments
(defun rem/; ()
(prog (c retval)
a (cond ((atom l) (return retval))
((eq (car l) /;)
(setq c (cdr l))
(setq retval 'car)
(setq l ()))
((and (null (atom (car l))) (eq (caar l) /;))
(setq c (cdar l))
(setq retval 'caar)
(setq l (cdr l)))
(t (cond ((and (eq retval 'caar) ;look ahead to separate comments.
(cdr l)
(null (atom (cdr l)))
(null (atom (cadr l)))
(eq (caadr l) /;))
(prinallcmnt)
(indent-to n)))
(return retval)))
b (cond ((null comnt) (setq comnt c))
((< comspace (length comnt)) (turpri) (go b))
((nconc comnt (cons '/ c))))
(go a)))
(defun rem/;/; ()
(prog (c retval)
a (cond ((atom l)
(and (eq retval 'caar) (indent-to n))
(return retval))
((eq (car l) /;/;)
(setq c (cdr l))
(setq retval 'car)
(setq l ()))
((and (null (atom (car l))) (eq (caar l) /;/;))
(setq c (cdar l))
(setq retval 'caar)
(setq l (cdr l)))
(t (and (eq retval 'caar) (indent-to n)) ;restore indentation for upcoming code
(return retval)))
(prinallcmnt)
/ ; ? ) ( turpri ) )
(prog (comnt pagewidth comspace macro)
(setq comnt c)
(and (or (memq (car c) '(/; *))
. update pagewidth , comspace
(setq /;/;? '/;/;/;) ;appropriate for a total line of
comspace (+ n (- topwidth linel)))
(go prinall))
(setq pagewidth linel)
(cond ((eq /;/;? /;/;) ;preceding comnt. merge.
(setq comnt (cons '/ comnt))
(setq macro (ascii 0.))
(setq comspace (grchrct))
(prin50com))
((setq /;/;? /;/;)))
(setq comspace n)
prinall
(setq macro /;/;)
(prinallcmnt))
(tj6 c)
(go a)))
commands : ; ; * --- or ; ; * ( ... ) ( ... )
(and
(eq (car x) '*)
(setq x (cdr x))
(turpri)
(cond
((errset
(cond ((atom (car (setq x
(readlist (cons '/(
(nconc x
'(/))))))))
(eval x))
((mapc 'eval x)))))
/;*/ error x 11 . ) ) ) ) )
prints one line of ; comment
(prog (next)
update linel , chrct for space of pagewidth .
(prog (comnt) (indent-to comspace))
(princ macro)
pl
(cond ((null comnt) (return ()))
((eq (car comnt) '/ )
(setq comnt (cdr comnt))
(setq next
(do ((x comnt (cdr x)) (num 2. (1+ num))) ;number of characters till next space.
((or (null x) (eq (car x) '/ ))
num)))
(cond ((and (or (eq macro /;) (eq /;/;? /;/;))
grindfill
(= next 2.)
(go pl)))
((and (not (eq macro (ascii 0.)))
(> next comspace)))
((< (grchrct) next) (return ())))
(tyo 32.)
(go pl))
((> (grchrct) 0.)
(princ (car comnt))
(and (or (eq macro /;) (eq /;/;? /;/;))
grindfill
(eq (car comnt) '/.)
(eq (cadr comnt) '/ )
(tyo 32.)))
(t (return ())))
(setq comnt (cdr comnt))
(go pl))
(newlinel-set programspace)) ;may restore chrct to be negative.
(defun prinallcmnt () (cond (comnt (prin50com) (prinallcmnt)))) ;prints \ of ; comment
(defun semi-comment () ;converts ; and ;; comments to exploded
(prog (com last char) ;lists
(setq com (cons /; ()) last com)
(setq char (readch)) ;decide type of semi comment
(cond ((eq char '/
) (return (list com)))
) ( rplaca last /;/ ;) )
((rplacd last (cons char ()))
(setq last (cdr last))))
a (setq char (readch))
(cond ((eq char '/
) (return (list com)))
((rplacd last (cons char ()))
(setq last (cdr last))
(go a)))))
(defun grindcolmac () (list ': (read)))
(defun grindcommac () (list '/, (read)))
(defun grindatmac () (cons '@ (read)))
(defun grindexmac ()
(prog (c f)
(setq c (grindnxtchr))
ta (cond ((setq f (assq c '((" /!") (@ /!@) ($ /!$))))
(tyi)
(return (cons (cadr f) (read))))
((setq f (assq c
'((? /!?) (/' /!/') (> /!>) (/, /!/,)
(< /!<) (/; /!/;))))
(tyi)
(setq f (cadr f)))
(t (setq c (error 'bad/ /!/ macro
c
'wrng-type-arg))
(go ta)))
(return (cond ((grindseparator (grindnxtchr))
(list f ()))
((atom (setq c (read))) (list f c))
(t (cons f c))))))
(defun grindnxtchr () (ascii (tyipeek)))
(defun grindseparator (char) (memq char '(| | | | |)|))) ;space, tab, rparens
(sstatus feature grind)
| null | https://raw.githubusercontent.com/g000001/MacLISP-compat/a147d09b98dca4d7c089424c3cbaf832d2fd857a/GRIND.lisp | lisp | -*-LISP-*-
***********************************************************************
***********************************************************************
****** this is a read-only file! (all writes reserved) ****************
***********************************************************************
/ ; user - paging form
? ^d macro unbnd - vrbl
some initializations
readtable (default).
^l made noticeable.
( ) )
( copysymbol ' /;/ ; ( ) ) )
/;? ())
Grinds and files file.
already filed.
grinds file and returns file
/;? comnt terpri)
catch top-level splicing macro
)
)
catch eof in tyipeek
) ;store /; strings of /; comments.
)
print stored /; comments
won't get ufile'd
formfeed read in ppage mode
ignore ^l except in user-paging mode.
any non-trivial characters before eof?
/;? t)
/;) ;toplevel ;;... comment
? (= linel ( grchrct ) ) ( turpri ) ( turpri ) ) ; produces blank line preceding new
) ; block of /;/ ; comments . ( turpri is
/ ;) . a total of 3
chrct is not linel, ie we have just
finished a line and have not yet cr.
clear hash array
prevents toplevel atoms from being
accidentally merged by being separated only by
cr.
'(lambda (l n m) 0.) 'grindpredict)
' ( lambda ( l n m ) 1 . ) ' grindpredict )
semi-colon comments
()
)
))
look ahead to separate comments.
))
/; ()
/;)
/;))
restore indentation for upcoming code
? ) ( turpri ) )
*))
/;? '/;/;/;) ;appropriate for a total line of
/;? /;/;) ;preceding comnt. merge.
/;? /;/;)))
/;)
; * --- or ; ; * ( ... ) ( ... )
*/ error x 11 . ) ) ) ) )
comment
number of characters till next space.
) (eq /;/;? /;/;))
) (eq /;/;? /;/;))
may restore chrct to be negative.
prints \ of ; comment
converts ; and ;; comments to exploded
lists
()) last com)
decide type of semi comment
/ ;) )
/!/;))))
space, tab, rparens |
* * * * * * * * * * * S - expression formatter for files ( grind ) * * * * * * * * *
* * ( c ) Copyright 1980 Massachusetts Institute of Technology * * * * * * * * * * *
This version of Grind works in both ITS and Multics Maclisp
GFILE - fns for pretty - printing and grinding files .
(eval-when (eval compile)
(or (status nofeature MACLISP)
(status macro /#)
(load '((LISP) SHARPM)))
)
(herald GRIND /422)
(declare (array* (notype (gtab/| 128.)))
(special merge readtable grindreadtable remsemi ~r
grindpredict grindproperties grindef predict
grindfn grindmacro programspace topwidth
prog? n m l h arg chrct linel pagewidth gap comspace
cnvrgrindflag outfiles infile stringp)
(*expr form topwidth programspace pagewidth comspace
nomerge remsemi stringp)
(*fexpr trace slashify unslashify grindfn grindmacro
unreadmacro readmacro grindef)
(*lexpr merge predict user-paging grindfill testl)
(mapex t)
(genprefix gr+)
(fixnum nn
mm
(grchrct)
(newlinel-set fixnum)
(prog-predict notype fixnum fixnum)
(block-predict notype fixnum fixnum)
(setq-predict notype fixnum fixnum)
(panmax notype fixnum fixnum)
(maxpan notype fixnum fixnum)
(gflatsize)))
(and (not (boundp 'grind-use-original-readtable))
(setq grind-use-original-readtable t))
(null grindreadtable))
'splicing
'semi-comment))
(setq grindreadtable
(*array ()
'readtable
grind-use-original-readtable))))
(setq stringp (status feature string))
)
(defun grind fexpr (file)
((lambda (x)
(t (cond ((not (status feature its))
(cond ((status feature DEC20)
(setq x (append (namelist x) () ))
(rplacd (cddr x) () ))
((probef x) (deletef x)))))
(apply 'ufile x)))
file)
(apply 'grind0 file)))
(or (status feature grindef)
(funcall autoload (cons 'grindef (get 'grindef 'autoload))))
(prog (remsemi linel *nopoint readtable base l ^q ^r ^w ^d
(setq base 10. linel programspace
readtable grindreadtable remsemi t)
(cond
((and stringp (stringp (car file)))
(inpush (openi (car file)))
(setq
outfiles
(list
(openo
(mergef
(cond ((null (cdr file))
(princ '|/
Filing as !GRIND OUTPUT |)
'(* /!GRIND OUTPUT))
((cadr file)))
(cons (car (namelist ())) '*) )))))
('t (apply (cond ((status feature sail) 'eread) ('uread))
(cond ((and (null (cdr file)) (symbolp (car file)))
(car file))
((and (status feature sail)
(cadr file)
(eq (cadr file) 'dsk))
(cons (car file) (cons '| | (cdr file))))
('t file)))
(uwrite)))
(setq eof (list ()) n topwidth)
(setq ^q t ^r t ^w t grindlinct global-lincnt)
read (and (= (tyipeek 47791616. -1)
(readch)
(go read))
(t (go read1))))
(go read))
(or (eq eof l) (go process))
exit (terpri)
(setq ~r ())
(and stringp
(stringp (car file))
(return file)
process
(and (< (tyipeek 50167296. -1) 0)
(terpri)
(grindpage)
(go read))
(newlinel-set topwidth)
turpri 's are necessary if initially
((< (turpri)
(grindpage))
((turpri)))
(cond ((eq (car l) 'lap) (lap-grind))
((sprint1 l linel 0.) (prin1 l)))
(defun newlinel-set (x)
(setq chrct (+ chrct (- x linel))
linel x))
(prog (c retval)
a (cond ((atom l) (return retval))
(setq c (cdr l))
(setq retval 'car)
(setq l ()))
(setq c (cdar l))
(setq retval 'caar)
(setq l (cdr l)))
(cdr l)
(null (atom (cdr l)))
(null (atom (cadr l)))
(prinallcmnt)
(indent-to n)))
(return retval)))
b (cond ((null comnt) (setq comnt c))
((< comspace (length comnt)) (turpri) (go b))
((nconc comnt (cons '/ c))))
(go a)))
(prog (c retval)
a (cond ((atom l)
(and (eq retval 'caar) (indent-to n))
(return retval))
(setq c (cdr l))
(setq retval 'car)
(setq l ()))
(setq c (cdar l))
(setq retval 'caar)
(setq l (cdr l)))
(return retval)))
(prinallcmnt)
(prog (comnt pagewidth comspace macro)
(setq comnt c)
. update pagewidth , comspace
comspace (+ n (- topwidth linel)))
(go prinall))
(setq pagewidth linel)
(setq comnt (cons '/ comnt))
(setq macro (ascii 0.))
(setq comspace (grchrct))
(prin50com))
(setq comspace n)
prinall
(prinallcmnt))
(tj6 c)
(go a)))
(and
(eq (car x) '*)
(setq x (cdr x))
(turpri)
(cond
((errset
(cond ((atom (car (setq x
(readlist (cons '/(
(nconc x
'(/))))))))
(eval x))
((mapc 'eval x)))))
(prog (next)
update linel , chrct for space of pagewidth .
(prog (comnt) (indent-to comspace))
(princ macro)
pl
(cond ((null comnt) (return ()))
((eq (car comnt) '/ )
(setq comnt (cdr comnt))
(setq next
((or (null x) (eq (car x) '/ ))
num)))
grindfill
(= next 2.)
(go pl)))
((and (not (eq macro (ascii 0.)))
(> next comspace)))
((< (grchrct) next) (return ())))
(tyo 32.)
(go pl))
((> (grchrct) 0.)
(princ (car comnt))
grindfill
(eq (car comnt) '/.)
(eq (cadr comnt) '/ )
(tyo 32.)))
(t (return ())))
(setq comnt (cdr comnt))
(go pl))
(cond ((eq char '/
) (return (list com)))
((rplacd last (cons char ()))
(setq last (cdr last))))
a (setq char (readch))
(cond ((eq char '/
) (return (list com)))
((rplacd last (cons char ()))
(setq last (cdr last))
(go a)))))
(defun grindcolmac () (list ': (read)))
(defun grindcommac () (list '/, (read)))
(defun grindatmac () (cons '@ (read)))
(defun grindexmac ()
(prog (c f)
(setq c (grindnxtchr))
ta (cond ((setq f (assq c '((" /!") (@ /!@) ($ /!$))))
(tyi)
(return (cons (cadr f) (read))))
((setq f (assq c
'((? /!?) (/' /!/') (> /!>) (/, /!/,)
(tyi)
(setq f (cadr f)))
(t (setq c (error 'bad/ /!/ macro
c
'wrng-type-arg))
(go ta)))
(return (cond ((grindseparator (grindnxtchr))
(list f ()))
((atom (setq c (read))) (list f c))
(t (cons f c))))))
(defun grindnxtchr () (ascii (tyipeek)))
(sstatus feature grind)
|
e84de4b2e4e5d4d01858f24a8c97b68490fb9a950d69e0f46d446bed800d9b46 | typelead/intellij-eta | AbstractModuleBuilder.hs | module FFI.Com.IntelliJ.Ide.Util.ProjectWizard.AbstractModuleBuilder where
import P.Base
data AbstractModuleBuilder = AbstractModuleBuilder
@com.intellij.ide.util.projectWizard.AbstractModuleBuilder
deriving Class
| null | https://raw.githubusercontent.com/typelead/intellij-eta/ee66d621aa0bfdf56d7d287279a9a54e89802cf9/plugin/src/main/eta/FFI/Com/IntelliJ/Ide/Util/ProjectWizard/AbstractModuleBuilder.hs | haskell | module FFI.Com.IntelliJ.Ide.Util.ProjectWizard.AbstractModuleBuilder where
import P.Base
data AbstractModuleBuilder = AbstractModuleBuilder
@com.intellij.ide.util.projectWizard.AbstractModuleBuilder
deriving Class
| |
4db0a56a43abe6cba1f8a1ddef3a736982ff1bf734b50b4d76434fd09f11d944 | ringstellung/Enigma | EnigmaI.hs | module EnigmaI (module EnigmaI) where
import Data.Char
import Auxiliars
import Types
import Rotors
CIFRADO
CIFRADO
-}
isInPositionToCJump :: RotorGS -> Bool
isInPositionToCJump (RotorGS r c) = c `elem` (extractNotch r)
rotateRotorOne :: RotorGS -> RotorGS
rotateRotorOne (RotorGS (Rotor rr n r w iw) c) = RotorGS (Rotor (rotateLevOne rr) n r (rotateLevOne w) (rotateLevOne iw)) d
where
d = nextInAlphabet c
stepForward ordena set de rotores caracter entrante .
stepForward ordena el avance de un set de rotores para proceder al cifrado de
un caracter entrante.
-}
stepForward :: RotorSet -> RotorSet
stepForward (RotorSet r r3 r2 r1)
| (not i) && (not ii) = RotorSet r r3 r2 (rotateRotorOne r1)
| (not i) && ii = RotorSet r (rotateRotorOne r3) (rotateRotorOne r2) (rotateRotorOne r1)
| i && (not ii) = RotorSet r r3 (rotateRotorOne r2) (rotateRotorOne r1)
| i && ii = RotorSet r (rotateRotorOne r3) (rotateRotorOne r2) (rotateRotorOne r1)
where
i = isInPositionToCJump r1
ii = isInPositionToCJump r2
FUNCIONES PARA EL CIFRADO CON PLUGBOARD
FUNCIONES PARA EL CIFRADO CON PLUGBOARD
-}
processAChar :: Pb -> RotorSet -> Char -> Char
processAChar pb rs c = equivalentChar (foldr t m [(iw1,rs1,gs1),(iw2,rs2,gs2),(iw3,rs3,gs3),(r,0,0),(w3,rs3,gs3),(w2,rs2,gs2),(w1,rs1,gs1)]) pb
where
m = equivalentChar c pb
w1 = extractWiring.extractRotorFromRotorGS.extractRGS1RotorSet $ rs
a1 = extractRSW.extractRotorFromRotorGS.extractRGS1RotorSet $ rs
rs1 = 1 + a1
gs1 = charToIndexA.extractCharFromRotorGS.extractRGS1RotorSet $ rs
w2 = extractWiring.extractRotorFromRotorGS.extractRGS2RotorSet $ rs
a2 = extractRSW.extractRotorFromRotorGS.extractRGS2RotorSet $ rs
rs2 = 1 + a2
gs2 = charToIndexA.extractCharFromRotorGS.extractRGS2RotorSet $ rs
w3 = extractWiring.extractRotorFromRotorGS.extractRGS3RotorSet $ rs
a3 = extractRSW.extractRotorFromRotorGS.extractRGS3RotorSet $ rs
rs3 = 1 + a3
gs3 = charToIndexA.extractCharFromRotorGS.extractRGS3RotorSet $ rs
r = extractWiringRef.extractRefRotorSet $ rs
iw3 = extractIWiring.extractRotorFromRotorGS.extractRGS3RotorSet $ rs
iw2 = extractIWiring.extractRotorFromRotorGS.extractRGS2RotorSet $ rs
iw1 = extractIWiring.extractRotorFromRotorGS.extractRGS1RotorSet $ rs
encodeTextEnigmaI :: RotorSet -> Pb -> String -> String
encodeTextEnigmaI rs pb str = zipWith (processAChar pb) (iterate stepForward nrsSf) str
where
nrsSf = stepForward.norm $ rs
| null | https://raw.githubusercontent.com/ringstellung/Enigma/f21aa7617355b804f0e43ae76ae66a750fabc615/Enigma_I/EnigmaI.hs | haskell | module EnigmaI (module EnigmaI) where
import Data.Char
import Auxiliars
import Types
import Rotors
CIFRADO
CIFRADO
-}
isInPositionToCJump :: RotorGS -> Bool
isInPositionToCJump (RotorGS r c) = c `elem` (extractNotch r)
rotateRotorOne :: RotorGS -> RotorGS
rotateRotorOne (RotorGS (Rotor rr n r w iw) c) = RotorGS (Rotor (rotateLevOne rr) n r (rotateLevOne w) (rotateLevOne iw)) d
where
d = nextInAlphabet c
stepForward ordena set de rotores caracter entrante .
stepForward ordena el avance de un set de rotores para proceder al cifrado de
un caracter entrante.
-}
stepForward :: RotorSet -> RotorSet
stepForward (RotorSet r r3 r2 r1)
| (not i) && (not ii) = RotorSet r r3 r2 (rotateRotorOne r1)
| (not i) && ii = RotorSet r (rotateRotorOne r3) (rotateRotorOne r2) (rotateRotorOne r1)
| i && (not ii) = RotorSet r r3 (rotateRotorOne r2) (rotateRotorOne r1)
| i && ii = RotorSet r (rotateRotorOne r3) (rotateRotorOne r2) (rotateRotorOne r1)
where
i = isInPositionToCJump r1
ii = isInPositionToCJump r2
FUNCIONES PARA EL CIFRADO CON PLUGBOARD
FUNCIONES PARA EL CIFRADO CON PLUGBOARD
-}
processAChar :: Pb -> RotorSet -> Char -> Char
processAChar pb rs c = equivalentChar (foldr t m [(iw1,rs1,gs1),(iw2,rs2,gs2),(iw3,rs3,gs3),(r,0,0),(w3,rs3,gs3),(w2,rs2,gs2),(w1,rs1,gs1)]) pb
where
m = equivalentChar c pb
w1 = extractWiring.extractRotorFromRotorGS.extractRGS1RotorSet $ rs
a1 = extractRSW.extractRotorFromRotorGS.extractRGS1RotorSet $ rs
rs1 = 1 + a1
gs1 = charToIndexA.extractCharFromRotorGS.extractRGS1RotorSet $ rs
w2 = extractWiring.extractRotorFromRotorGS.extractRGS2RotorSet $ rs
a2 = extractRSW.extractRotorFromRotorGS.extractRGS2RotorSet $ rs
rs2 = 1 + a2
gs2 = charToIndexA.extractCharFromRotorGS.extractRGS2RotorSet $ rs
w3 = extractWiring.extractRotorFromRotorGS.extractRGS3RotorSet $ rs
a3 = extractRSW.extractRotorFromRotorGS.extractRGS3RotorSet $ rs
rs3 = 1 + a3
gs3 = charToIndexA.extractCharFromRotorGS.extractRGS3RotorSet $ rs
r = extractWiringRef.extractRefRotorSet $ rs
iw3 = extractIWiring.extractRotorFromRotorGS.extractRGS3RotorSet $ rs
iw2 = extractIWiring.extractRotorFromRotorGS.extractRGS2RotorSet $ rs
iw1 = extractIWiring.extractRotorFromRotorGS.extractRGS1RotorSet $ rs
encodeTextEnigmaI :: RotorSet -> Pb -> String -> String
encodeTextEnigmaI rs pb str = zipWith (processAChar pb) (iterate stepForward nrsSf) str
where
nrsSf = stepForward.norm $ rs
| |
b8057945e3b7a077034424904d0455e28e027916561e6cee27733ad4e481bb47 | nikomatsakis/a-mir-formality | subtype.rkt | #lang racket
(require redex/reduction-semantics
"occurs-check.rkt"
"universe-check.rkt"
"rigid.rkt"
"../kind.rkt"
"../grammar.rkt"
"../extrude.rkt"
"../hypothesized-bounds.rkt"
"../../logic/env.rkt"
"../../logic/env-inequalities.rkt"
)
(provide compare/one/substituted
)
(define-metafunction formality-ty
compare/one/substituted : Env_in (Parameter_a SubtypeOp Parameter_b) -> (Env Goals) or Error
#:pre ,(eq? (term (parameter-kind Env_in Parameter_a))
(term (parameter-kind Env_in Parameter_b)))
[; X ?= X:
; Always ok.
(compare/one/substituted Env (Parameter SubtypeOp Parameter))
(Env ())
]
[; 'a <= 'b if 'a -outlives- 'b
; 'a >= 'b if 'a -outlived-by- 'b
(compare/one/substituted Env (Parameter_a SubtypeOp Parameter_b))
(Env ((Parameter_a (subtype->outlives SubtypeOp) Parameter_b)))
(where lifetime (parameter-kind Env Parameter_a))
(where/error lifetime (parameter-kind Env Parameter_b)) ; ought to be well-kinded
]
[; X ?= R<...> -- Inequality between a variable and a rigid type
(compare/one/substituted Env (VarId SubtypeOp (rigid-ty RigidName (Parameter ...))))
(relate-var-to-rigid Env (VarId SubtypeOp (rigid-ty RigidName (Parameter ...))))
(where #t (env-contains-existential-var Env VarId))
]
[; R<...> ?= X -- Inequality between a variable and a rigid type
(compare/one/substituted Env ((rigid-ty RigidName (Parameter ...)) SubtypeOp VarId))
(relate-var-to-rigid Env (VarId (invert-inequality-op SubtypeOp) (rigid-ty RigidName (Parameter ...))))
(where #t (env-contains-existential-var Env VarId))
]
[; R<...> ?= X -- Inequality between a variable and a rigid type
(compare/one/substituted Env ((rigid-ty RigidName (Parameter ...)) SubtypeOp VarId))
(relate-var-to-rigid Env (VarId (invert-inequality-op SubtypeOp) (rigid-ty RigidName (Parameter ...))))
(where #t (env-contains-existential-var Env VarId))
]
R < ... > ? = R < ... > -- Relating two rigid types with the same name : relate their parameters according to the declared variance .
(compare/one/substituted Env ((rigid-ty RigidName (Parameter_1 ..._1)) SubtypeOp (rigid-ty RigidName (Parameter_2 ..._1))))
(relate-rigid-to-rigid Env ((rigid-ty RigidName (Parameter_1 ...)) SubtypeOp (rigid-ty RigidName (Parameter_2 ...))))
]
[; `?X <= T` where occurs, universes ok:
; Add `X <= P` as a bound and, for each bound `B` where `X >= B`,
; require that `B <= P` (respectively `>=`).
(compare/one/substituted Env (VarId SubtypeOp Parameter))
(Env_1 ((Parameter_bound SubtypeOp Parameter) ...))
(where #t (env-contains-existential-var Env VarId))
(where #t (occurs-check-ok? Env VarId Parameter))
(where #t (universe-check-ok? Env VarId Parameter))
(where/error (Parameter_bound ...) (known-bounds Env VarId (invert-inequality-op SubtypeOp)))
(where/error Env_1 (env-with-var-related-to-parameter Env VarId SubtypeOp Parameter))
]
[; `T <= ?X` where occurs, universes ok:
Flip to ` ? X < = T ` and use above rule .
(compare/one/substituted Env (Parameter SubtypeOp VarId))
(compare/one/substituted Env (VarId (invert-inequality-op SubtypeOp) Parameter))
(where #t (env-contains-existential-var Env VarId))
(where #t (occurs-check-ok? Env VarId Parameter))
(where #t (universe-check-ok? Env VarId Parameter))
]
[; `?X <= T` where occurs ok, universes not ok:
; Add `X <= P` as a bound and, for each bound `B` where `B <= X`,
; require that `B <= P` (respectively `>=`).
(compare/one/substituted Env (VarId SubtypeOp Parameter))
(Env_1 ((VarId SubtypeOp Parameter_extruded) Goal ...))
(where #t (env-contains-existential-var Env VarId))
(where #t (occurs-check-ok? Env VarId Parameter))
(where #f (universe-check-ok? Env VarId Parameter))
(where/error Universe_VarId (universe-of-var-in-env Env VarId))
(where/error (Env_1 Parameter_extruded (Goal ...)) (extrude-parameter Env Universe_VarId SubtypeOp Parameter))
]
[; `T <= ?X` where occurs ok, universes not ok:
; Invert and use above rule.
(compare/one/substituted Env (Parameter SubtypeOp VarId))
(compare/one/substituted Env (VarId (invert-inequality-op SubtypeOp) Parameter))
(where #t (env-contains-existential-var Env VarId))
(where #t (occurs-check-ok? Env VarId Parameter))
(where #f (universe-check-ok? Env VarId Parameter))
]
[; Flip `>=` to `<=` for remaining rules
(compare/one/substituted Env (Parameter_1 >= Parameter_2))
(compare/one/substituted Env (Parameter_2 <= Parameter_1))
]
[; ∀ on the supertype side
;
; if I have to prove that `T <: forall<'a> U`...
; I can prove...
; `forall<'a> { T <: U }`... and that's the same thing
(compare/one/substituted Env (Parameter_1 <= (∀ KindedVarIds Parameter_2)))
NB : Redex binding forms ensure that names in ` KindedVarIds ` do not appear free in ` Parameter_1 `
(Env ((∀ KindedVarIds (Parameter_1 <= Parameter_2))))
]
[; Implication on the supertype side
(compare/one/substituted Env (Parameter_1 <= (implies Biformulas Parameter_2)))
(Env ((implies Biformulas (Parameter_1 <= Parameter_2))))
]
[; Ensures on the subtype side
(compare/one/substituted Env ((ensures Parameter_1 Biformulas) <= Parameter_2))
(Env ((implies Biformulas (Parameter_1 <= Parameter_2))))
]
[; ∀ on the subtype side
;
; if I have to prove that `forall<'a> T <: U`...
; I can prove...
; `exists<'a> { T <: U }`... and that's the same thing
(compare/one/substituted Env ((∀ KindedVarIds Parameter_1) <= Parameter_2))
NB : Redex binding forms ensure that all names in ` KindedVarIds ` do not appear free in ` Parameter_2 `
(Env ((∃ KindedVarIds (Parameter_1 <= Parameter_2))))
]
[; Implication on the subtype side
(compare/one/substituted Env ((implies [Biformula ...] Parameter_1) <= Parameter_2))
(Env [Biformula ... (Parameter_1 <= Parameter_2)])
]
[; Ensures on the supertype side
(compare/one/substituted Env (Parameter_1 <= (ensures Parameter_2 [Biformula ...])))
(Env [Biformula ... (Parameter_1 <= Parameter_2)])
]
on both sides with same name
(compare/one/substituted Env ((alias-ty AliasName (Parameter_1 ...)) <= (alias-ty AliasName (Parameter_2 ...))))
(Env ((|| (Goal_eq Goal_n))))
(; Either all the parameters are equal (note that we have no variance on alias-ty, so they
; must be equal)
where/error Goal_eq (&& ((Parameter_1 == Parameter_2) ...)))
(; Or we can normalize both aliases to the same type
where/error Goal_n (∃ ((type T1) (type T2))
(&& ((T1 <= T2)
(normalizes-to (alias-ty AliasName (Parameter_1 ...)) T1)
(normalizes-to (alias-ty AliasName (Parameter_2 ...)) T2)))
))
]
on subtype
(compare/one/substituted Env (AliasTy <= Ty))
(Env (Goal_n))
(; The alias has to normalize to a subtype of Ty
where/error Goal_n (∃ ((type T))
(&& ((T <= Ty)
(normalizes-to AliasTy T)))))
]
[; Alias on supertype
(compare/one/substituted Env (Ty <= AliasTy))
(Env (Goal_n))
(; The alias has to normalize to a supertype of Ty
where/error Goal_n (∃ ((type T))
(&& ((Ty <= T)
(normalizes-to AliasTy T)))))
]
[; `!X <= T` where:
Prove ` X < = T1 ` for any ` T1 < = P ` from environment .
(compare/one/substituted Env (VarId <= Parameter))
(Env ((|| Goals)))
(where #t (env-contains-placeholder-var Env VarId))
(where/error Goals (bound-placeholder-from-hypotheses Env VarId <= Parameter))
]
[; `T <= !X` where:
Flip to ` ! X > = T ` and use above rule .
(compare/one/substituted Env (Parameter <= VarId))
(Env ((|| Goals)))
(where #t (env-contains-placeholder-var Env VarId))
(where/error Goals (bound-placeholder-from-hypotheses Env VarId >= Parameter))
]
[; all other sets of types cannot be compared
(compare/one/substituted _ _)
Error
]
)
(define-metafunction formality-ty
;; Convert a subtype relation (on lifetimes) to an outlives op.
subtype->outlives : SubtypeOp -> OutlivesOp
[(subtype->outlives <=) -outlives-]
[(subtype->outlives >=) -outlived-by-]
)
| null | https://raw.githubusercontent.com/nikomatsakis/a-mir-formality/bc951e21bff2bae1ccab8cc05b2b39cfb6365bfd/racket-src/ty/relate/subtype.rkt | racket | X ?= X:
Always ok.
'a <= 'b if 'a -outlives- 'b
'a >= 'b if 'a -outlived-by- 'b
ought to be well-kinded
X ?= R<...> -- Inequality between a variable and a rigid type
R<...> ?= X -- Inequality between a variable and a rigid type
R<...> ?= X -- Inequality between a variable and a rigid type
`?X <= T` where occurs, universes ok:
Add `X <= P` as a bound and, for each bound `B` where `X >= B`,
require that `B <= P` (respectively `>=`).
`T <= ?X` where occurs, universes ok:
`?X <= T` where occurs ok, universes not ok:
Add `X <= P` as a bound and, for each bound `B` where `B <= X`,
require that `B <= P` (respectively `>=`).
`T <= ?X` where occurs ok, universes not ok:
Invert and use above rule.
Flip `>=` to `<=` for remaining rules
∀ on the supertype side
if I have to prove that `T <: forall<'a> U`...
I can prove...
`forall<'a> { T <: U }`... and that's the same thing
Implication on the supertype side
Ensures on the subtype side
∀ on the subtype side
if I have to prove that `forall<'a> T <: U`...
I can prove...
`exists<'a> { T <: U }`... and that's the same thing
Implication on the subtype side
Ensures on the supertype side
Either all the parameters are equal (note that we have no variance on alias-ty, so they
must be equal)
Or we can normalize both aliases to the same type
The alias has to normalize to a subtype of Ty
Alias on supertype
The alias has to normalize to a supertype of Ty
`!X <= T` where:
`T <= !X` where:
all other sets of types cannot be compared
Convert a subtype relation (on lifetimes) to an outlives op. | #lang racket
(require redex/reduction-semantics
"occurs-check.rkt"
"universe-check.rkt"
"rigid.rkt"
"../kind.rkt"
"../grammar.rkt"
"../extrude.rkt"
"../hypothesized-bounds.rkt"
"../../logic/env.rkt"
"../../logic/env-inequalities.rkt"
)
(provide compare/one/substituted
)
(define-metafunction formality-ty
compare/one/substituted : Env_in (Parameter_a SubtypeOp Parameter_b) -> (Env Goals) or Error
#:pre ,(eq? (term (parameter-kind Env_in Parameter_a))
(term (parameter-kind Env_in Parameter_b)))
(compare/one/substituted Env (Parameter SubtypeOp Parameter))
(Env ())
]
(compare/one/substituted Env (Parameter_a SubtypeOp Parameter_b))
(Env ((Parameter_a (subtype->outlives SubtypeOp) Parameter_b)))
(where lifetime (parameter-kind Env Parameter_a))
]
(compare/one/substituted Env (VarId SubtypeOp (rigid-ty RigidName (Parameter ...))))
(relate-var-to-rigid Env (VarId SubtypeOp (rigid-ty RigidName (Parameter ...))))
(where #t (env-contains-existential-var Env VarId))
]
(compare/one/substituted Env ((rigid-ty RigidName (Parameter ...)) SubtypeOp VarId))
(relate-var-to-rigid Env (VarId (invert-inequality-op SubtypeOp) (rigid-ty RigidName (Parameter ...))))
(where #t (env-contains-existential-var Env VarId))
]
(compare/one/substituted Env ((rigid-ty RigidName (Parameter ...)) SubtypeOp VarId))
(relate-var-to-rigid Env (VarId (invert-inequality-op SubtypeOp) (rigid-ty RigidName (Parameter ...))))
(where #t (env-contains-existential-var Env VarId))
]
R < ... > ? = R < ... > -- Relating two rigid types with the same name : relate their parameters according to the declared variance .
(compare/one/substituted Env ((rigid-ty RigidName (Parameter_1 ..._1)) SubtypeOp (rigid-ty RigidName (Parameter_2 ..._1))))
(relate-rigid-to-rigid Env ((rigid-ty RigidName (Parameter_1 ...)) SubtypeOp (rigid-ty RigidName (Parameter_2 ...))))
]
(compare/one/substituted Env (VarId SubtypeOp Parameter))
(Env_1 ((Parameter_bound SubtypeOp Parameter) ...))
(where #t (env-contains-existential-var Env VarId))
(where #t (occurs-check-ok? Env VarId Parameter))
(where #t (universe-check-ok? Env VarId Parameter))
(where/error (Parameter_bound ...) (known-bounds Env VarId (invert-inequality-op SubtypeOp)))
(where/error Env_1 (env-with-var-related-to-parameter Env VarId SubtypeOp Parameter))
]
Flip to ` ? X < = T ` and use above rule .
(compare/one/substituted Env (Parameter SubtypeOp VarId))
(compare/one/substituted Env (VarId (invert-inequality-op SubtypeOp) Parameter))
(where #t (env-contains-existential-var Env VarId))
(where #t (occurs-check-ok? Env VarId Parameter))
(where #t (universe-check-ok? Env VarId Parameter))
]
(compare/one/substituted Env (VarId SubtypeOp Parameter))
(Env_1 ((VarId SubtypeOp Parameter_extruded) Goal ...))
(where #t (env-contains-existential-var Env VarId))
(where #t (occurs-check-ok? Env VarId Parameter))
(where #f (universe-check-ok? Env VarId Parameter))
(where/error Universe_VarId (universe-of-var-in-env Env VarId))
(where/error (Env_1 Parameter_extruded (Goal ...)) (extrude-parameter Env Universe_VarId SubtypeOp Parameter))
]
(compare/one/substituted Env (Parameter SubtypeOp VarId))
(compare/one/substituted Env (VarId (invert-inequality-op SubtypeOp) Parameter))
(where #t (env-contains-existential-var Env VarId))
(where #t (occurs-check-ok? Env VarId Parameter))
(where #f (universe-check-ok? Env VarId Parameter))
]
(compare/one/substituted Env (Parameter_1 >= Parameter_2))
(compare/one/substituted Env (Parameter_2 <= Parameter_1))
]
(compare/one/substituted Env (Parameter_1 <= (∀ KindedVarIds Parameter_2)))
NB : Redex binding forms ensure that names in ` KindedVarIds ` do not appear free in ` Parameter_1 `
(Env ((∀ KindedVarIds (Parameter_1 <= Parameter_2))))
]
(compare/one/substituted Env (Parameter_1 <= (implies Biformulas Parameter_2)))
(Env ((implies Biformulas (Parameter_1 <= Parameter_2))))
]
(compare/one/substituted Env ((ensures Parameter_1 Biformulas) <= Parameter_2))
(Env ((implies Biformulas (Parameter_1 <= Parameter_2))))
]
(compare/one/substituted Env ((∀ KindedVarIds Parameter_1) <= Parameter_2))
NB : Redex binding forms ensure that all names in ` KindedVarIds ` do not appear free in ` Parameter_2 `
(Env ((∃ KindedVarIds (Parameter_1 <= Parameter_2))))
]
(compare/one/substituted Env ((implies [Biformula ...] Parameter_1) <= Parameter_2))
(Env [Biformula ... (Parameter_1 <= Parameter_2)])
]
(compare/one/substituted Env (Parameter_1 <= (ensures Parameter_2 [Biformula ...])))
(Env [Biformula ... (Parameter_1 <= Parameter_2)])
]
on both sides with same name
(compare/one/substituted Env ((alias-ty AliasName (Parameter_1 ...)) <= (alias-ty AliasName (Parameter_2 ...))))
(Env ((|| (Goal_eq Goal_n))))
where/error Goal_eq (&& ((Parameter_1 == Parameter_2) ...)))
where/error Goal_n (∃ ((type T1) (type T2))
(&& ((T1 <= T2)
(normalizes-to (alias-ty AliasName (Parameter_1 ...)) T1)
(normalizes-to (alias-ty AliasName (Parameter_2 ...)) T2)))
))
]
on subtype
(compare/one/substituted Env (AliasTy <= Ty))
(Env (Goal_n))
where/error Goal_n (∃ ((type T))
(&& ((T <= Ty)
(normalizes-to AliasTy T)))))
]
(compare/one/substituted Env (Ty <= AliasTy))
(Env (Goal_n))
where/error Goal_n (∃ ((type T))
(&& ((Ty <= T)
(normalizes-to AliasTy T)))))
]
Prove ` X < = T1 ` for any ` T1 < = P ` from environment .
(compare/one/substituted Env (VarId <= Parameter))
(Env ((|| Goals)))
(where #t (env-contains-placeholder-var Env VarId))
(where/error Goals (bound-placeholder-from-hypotheses Env VarId <= Parameter))
]
Flip to ` ! X > = T ` and use above rule .
(compare/one/substituted Env (Parameter <= VarId))
(Env ((|| Goals)))
(where #t (env-contains-placeholder-var Env VarId))
(where/error Goals (bound-placeholder-from-hypotheses Env VarId >= Parameter))
]
(compare/one/substituted _ _)
Error
]
)
(define-metafunction formality-ty
subtype->outlives : SubtypeOp -> OutlivesOp
[(subtype->outlives <=) -outlives-]
[(subtype->outlives >=) -outlived-by-]
)
|
fdee1e1c89d7c5ee0da1199bc521137d81c83e4734f8fb60f688eff3b85beef9 | jrm-code-project/LISP-Machine | open.lisp | -*- Mode : LISP ; Package : FILE - SYSTEM ; Base:8 ; : ZL -*-
;;;; Global interface functions, and random file stuff
First define the error flavors and signal names used by all file errors .
(DEFFLAVOR FILE-ERROR (PATHNAME OPERATION) (NO-ACTION-MIXIN ERROR)
:ABSTRACT-FLAVOR
:GETTABLE-INSTANCE-VARIABLES
:INITTABLE-INSTANCE-VARIABLES)
(DEFMETHOD (FILE-ERROR :AFTER :INIT) (IGNORE)
(SETQ PATHNAME (GETF SI:PROPERTY-LIST ':PATHNAME))
(OR (VARIABLE-BOUNDP OPERATION)
(SETQ OPERATION (GETF SI:PROPERTY-LIST ':OPERATION))))
(DEFMETHOD (FILE-ERROR :SET-FORMAT-ARGS) (NEW-ARGS)
(SETQ EH:FORMAT-ARGS NEW-ARGS))
(DEFMETHOD (FILE-ERROR :CASE :PROCEED-ASKING-USER :RETRY-FILE-OPERATION)
(CONTINUATION IGNORE)
"Proceeds, trying the file operation again."
(FUNCALL CONTINUATION ':RETRY-FILE-OPERATION))
(DEFMETHOD (FILE-ERROR :CASE :PROCEED-ASKING-USER :NEW-PATHNAME)
(CONTINUATION READ-OBJECT-FUNCTION)
"Proceeds, reading a new filename and using that instead."
(FUNCALL CONTINUATION ':NEW-PATHNAME
(FUNCALL READ-OBJECT-FUNCTION
`(:PATHNAME :DEFAULTS ,PATHNAME)
"Pathname to use instead: (default ~A) "
PATHNAME)))
(DEFFLAVOR FILE-REQUEST-FAILURE () (FILE-ERROR))
(DEFPROP DAT DATA-ERROR FILE-ERROR)
(DEFPROP DATA-ERROR DAT FILE-ERROR)
(DEFSIGNAL DATA-ERROR FILE-REQUEST-FAILURE (PATHNAME OPERATION)
"Inconsistent data found in the file system.")
(DEFPROP HNA HOST-NOT-AVAILABLE FILE-ERROR)
(DEFPROP HOST-NOT-AVAILABLE HNA FILE-ERROR)
(DEFSIGNAL HOST-NOT-AVAILABLE FILE-REQUEST-FAILURE (PATHNAME OPERATION)
"A file system is refusing to listen to requests.")
(DEFPROP NFS NO-FILE-SYSTEM FILE-ERROR)
(DEFPROP NO-FILE-SYSTEM NFS FILE-ERROR)
(DEFSIGNAL NO-FILE-SYSTEM FILE-REQUEST-FAILURE (PATHNAME OPERATION)
"The file system does not seem to exist.")
(DEFSIGNAL NETWORK-LOSSAGE FILE-REQUEST-FAILURE (PATHNAME OPERATION)
"Misc. network problems during file accessing.
In particular, failure to open data connection.")
(DEFPROP NER NOT-ENOUGH-RESOURCES FILE-ERROR)
(DEFPROP NOT-ENOUGH-RESOURCES NER FILE-ERROR)
(DEFSIGNAL NOT-ENOUGH-RESOURCES FILE-REQUEST-FAILURE (PATHNAME OPERATION)
"Shortage of resources (network or file server) to transmit operation.
This is if the file server itself says it hasn't got enough resources.")
(DEFPROP UOP UNKNOWN-OPERATION FILE-ERROR)
(DEFPROP UNKNOWN-OPERATION UOP FILE-ERROR)
(DEFPROP UKC UNKNOWN-OPERATION FILE-ERROR)
(DEFSIGNAL UNKNOWN-OPERATION FILE-REQUEST-FAILURE (PATHNAME OPERATION)
"OPERATION is not supported on the particular file system used.")
(DEFPROP LIP LOGIN-PROBLEMS FILE-ERROR)
(DEFPROP LOGIN-PROBLEMS LIP FILE-ERROR)
(DEFSIGNAL LOGIN-PROBLEMS FILE-REQUEST-FAILURE ()
"Some sort of failure to log in.")
(DEFPROP UNK UNKNOWN-USER FILE-ERROR)
(DEFPROP UNKNOWN-USER UNK FILE-ERROR)
(DEFSIGNAL UNKNOWN-USER
(FILE-REQUEST-FAILURE LOGIN-PROBLEMS CORRECTABLE-LOGIN-PROBLEMS UNKNOWN-USER)
()
"USER is not a known login-name at HOST.")
(DEFPROP IP? INVALID-PASSWORD FILE-ERROR)
(DEFPROP INVALID-PASSWORD IP? FILE-ERROR)
(DEFSIGNAL INVALID-PASSWORD (FILE-REQUEST-FAILURE LOGIN-PROBLEMS
CORRECTABLE-LOGIN-PROBLEMS INVALID-PASSWORD)
()
"PASSWORD is not USER's password at HOST.")
(DEFPROP NLI NOT-LOGGED-IN FILE-ERROR)
(DEFPROP NOT-LOGGED-IN NLI FILE-ERROR)
(DEFSIGNAL NOT-LOGGED-IN (FILE-REQUEST-FAILURE NOT-LOGGED-IN)
(PATHNAME OPERATION)
"The file server said you were not logged in when the Lispm thought you should be.")
(DEFFLAVOR FILE-OPERATION-FAILURE () (FILE-ERROR)
(:DOCUMENTATION "The file system understood an operation but decided it was erroneous."))
(DEFMETHOD (FILE-OPERATION-FAILURE :CASE :PROCEED-ASKING-USER :DIRED) (&REST IGNORE)
"Runs DIRED, then returns to the debugger when you type Control-Z."
(DIRED (SEND (SEND SELF :PATHNAME) :NEW-PATHNAME
:NAME :WILD :TYPE :WILD :VERSION :WILD))
NIL)
(DEFMETHOD (FILE-OPERATION-FAILURE :CASE :PROCEED-ASKING-USER :CLEAN-DIRECTORY) (&REST IGNORE)
"Calls (ZWEI:CLEAN-DIRECTORY), then returns to debugger."
(ZWEI:CLEAN-DIRECTORY (SEND (SEND SELF :PATHNAME) :NEW-PATHNAME
:NAME :WILD :TYPE :WILD :VERSION :WILD))
NIL)
(DEFMETHOD (FILE-OPERATION-FAILURE :CASE :PROCEED-ASKING-USER :EXPUNGE-DIRECTORY) (&REST IGNORE)
"Expunges the directory, then returns to debugger."
(EXPUNGE-DIRECTORY (SEND (SEND SELF ':PATHNAME) ':NEW-PATHNAME
':NAME ':WILD ':TYPE ':WILD ':VERSION ':WILD))
NIL)
(DEFSIGNAL FILE-OPERATION-FAILURE-1 FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"Unrecognized file error codes signal this.")
(DEFSIGNAL FILE-OPEN-FOR-OUTPUT FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"How is this different from FILE-LOCKED?")
(DEFPROP LCK FILE-LOCKED FILE-ERROR)
(DEFPROP FILE-LOCKED LCK FILE-ERROR)
(DEFSIGNAL FILE-LOCKED FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"File cannot be accessed because someone else is using it.")
(DEFPROP CIR CIRCULAR-LINK FILE-ERROR)
(DEFPROP CIRCULAR-LINK CIR FILE-ERROR)
(DEFSIGNAL CIRCULAR-LINK FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"A link pointed to a link which pointed to a link ... too deeply.")
;;;Unimplemented-option
(DEFPROP UOO UNIMPLEMENTED-OPTION FILE-ERROR)
(DEFPROP UNIMPLEMENTED-OPTION UOO FILE-ERROR)
(DEFSIGNAL UNIMPLEMENTED-OPTION FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"Specified some option this file system doesn't understand.")
(DEFPROP IBS INVALID-BYTE-SIZE FILE-ERROR)
(DEFPROP INVALID-BYTE-SIZE IBS FILE-ERROR)
(DEFSIGNAL INVALID-BYTE-SIZE (FILE-OPERATION-FAILURE UNIMPLEMENTED-OPTION INVALID-BYTE-SIZE)
(PATHNAME OPERATION)
"Specified a byte size that the file system cannot handle.")
(DEFPROP ICO INCONSISTENT-OPTIONS FILE-ERROR)
(DEFPROP INCONSISTENT-OPTIONS ICO FILE-ERROR)
(DEFSIGNAL INCONSISTENT-OPTIONS FILE-OPERATION-FAILURE
(PATHNAME OPERATION)
"Specified a byte size that the file system cannot handle.")
(DEFFLAVOR NO-MORE-ROOM-ERROR () (FILE-OPERATION-FAILURE))
(DEFMETHOD (NO-MORE-ROOM-ERROR :USER-PROCEED-TYPES) (REAL-PROCEED-TYPES)
(APPEND (INTERSECTION '(:NO-ACTION :RETRY-FILE-OPERATION) REAL-PROCEED-TYPES)
'(:DIRED :CLEAN-DIRECTORY :expunge-directory)
(REM-IF #'(LAMBDA (ELT)
(MEMQ ELT '(:NO-ACTION :RETRY-FILE-OPERATION :DIRED :CLEAN-DIRECTORY :expunge-directory)))
REAL-PROCEED-TYPES)))
(DEFPROP NMR NO-MORE-ROOM FILE-ERROR)
(DEFPROP NO-MORE-ROOM NMR FILE-ERROR)
(DEFSIGNAL NO-MORE-ROOM NO-MORE-ROOM-ERROR (PATHNAME OPERATION)
"Out of resources within the file system.")
(DEFPROP FOR FILEPOS-OUT-OF-RANGE FILE-ERROR)
(DEFPROP FILEPOS-OUT-OF-RANGE FOR FILE-ERROR)
(DEFSIGNAL FILEPOS-OUT-OF-RANGE FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"Access pointer set to bad value, outside 0 to length of file.")
(DEFPROP NAV NOT-AVAILABLE FILE-ERROR)
(DEFPROP NOT-AVAILABLE NAV FILE-ERROR)
(DEFSIGNAL NOT-AVAILABLE FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"File, pack etc. exists but is currently down.")
(DEFSIGNAL INVALID-FILE-ATTRIBUTE ERROR (PATHNAME ATTRIBUTE VALUE)
"An attribute in the file attribute list had a bad value.
This is detected in the Lisp machine, not in the file server.")
;;; Subclasses of FILE-OPERATION-FAILURE.
(DEFFLAVOR FILE-LOOKUP-ERROR () (FILE-OPERATION-FAILURE))
(DEFPROP FNF FILE-NOT-FOUND FILE-ERROR)
(DEFPROP FILE-NOT-FOUND FNF FILE-ERROR)
(DEFSIGNAL FILE-NOT-FOUND FILE-LOOKUP-ERROR (PATHNAME OPERATION)
"The file was not found in the containing directory.")
(DEFSIGNAL MULTIPLE-FILE-NOT-FOUND FILE-LOOKUP-ERROR (OPERATION PATHNAME PATHNAMES)
"None of the files was found in the containing directory.")
(DEFFLAVOR DIRECTORY-NOT-FOUND-ERROR () (FILE-LOOKUP-ERROR))
(DEFMETHOD (DIRECTORY-NOT-FOUND-ERROR :USER-PROCEED-TYPES) (REAL-PROCEED-TYPES)
(APPEND (INTERSECTION '(:NO-ACTION :RETRY-FILE-OPERATION) REAL-PROCEED-TYPES)
'(:CREATE-DIRECTORY-AND-RETRY)
(REM-IF #'(LAMBDA (ELT) (MEMQ ELT '(:NO-ACTION :RETRY-FILE-OPERATION
:CREATE-DIRECTORY-AND-RETRY)))
REAL-PROCEED-TYPES)))
(DEFMETHOD (DIRECTORY-NOT-FOUND-ERROR :CASE :PROCEED-ASKING-USER :CREATE-DIRECTORY-AND-RETRY)
(CONTINUATION IGNORE)
"Creates the directory and tries again."
(CREATE-DIRECTORY (SEND SELF ':PATHNAME) ':RECURSIVE T)
(FUNCALL CONTINUATION ':RETRY-FILE-OPERATION))
(DEFPROP DNF DIRECTORY-NOT-FOUND FILE-ERROR)
(DEFPROP DIRECTORY-NOT-FOUND DNF FILE-ERROR)
(DEFSIGNAL DIRECTORY-NOT-FOUND DIRECTORY-NOT-FOUND-ERROR (PATHNAME OPERATION)
"Containing directory is not found.")
(DEFPROP DEV DEVICE-NOT-FOUND FILE-ERROR)
(DEFPROP DEVICE-NOT-FOUND DEV FILE-ERROR)
(DEFSIGNAL DEVICE-NOT-FOUND FILE-LOOKUP-ERROR (PATHNAME OPERATION)
"Device specified in pathname not found.")
(DEFPROP LNF LINK-TARGET-NOT-FOUND FILE-ERROR)
(DEFPROP LINK-TARGET-NOT-FOUND LNF FILE-ERROR)
(DEFSIGNAL LINK-TARGET-NOT-FOUND FILE-LOOKUP-ERROR (PATHNAME OPERATION)
"Failure in looking up the target of a link that was found.")
;;; ACCESS-ERROR means some kind of protection failure.
(DEFPROP ACC ACCESS-ERROR FILE-ERROR)
(DEFPROP ACCESS-ERROR ACC FILE-ERROR)
(DEFSIGNAL ACCESS-ERROR FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"Some sort of protection screwed you.")
(DEFPROP ATF INCORRECT-ACCESS-TO-FILE FILE-ERROR)
(DEFPROP INCORRECT-ACCESS-TO-FILE ATF FILE-ERROR)
(DEFSIGNAL INCORRECT-ACCESS-TO-FILE
(FILE-OPERATION-FAILURE ACCESS-ERROR INCORRECT-ACCESS-TO-FILE)
(PATHNAME OPERATION)
"File protection screwed you.")
(DEFPROP ATD INCORRECT-ACCESS-TO-DIRECTORY FILE-ERROR)
(DEFPROP INCORRECT-ACCESS-TO-DIRECTORY ATD FILE-ERROR)
(DEFSIGNAL INCORRECT-ACCESS-TO-DIRECTORY
(FILE-OPERATION-FAILURE ACCESS-ERROR INCORRECT-ACCESS-TO-DIRECTORY)
(PATHNAME OPERATION)
"Directory protection screwed you.")
INVALID - PATHNAME - SYNTAX
(DEFPROP IPS INVALID-PATHNAME-SYNTAX FILE-ERROR)
(DEFPROP INVALID-PATHNAME-SYNTAX IPS FILE-ERROR)
(DEFSIGNAL INVALID-PATHNAME-SYNTAX FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"Some weird syntax got through pathname parsing but file system didn't like it.")
(DEFPROP IWC INVALID-WILDCARD FILE-ERROR)
(DEFPROP INVALID-WILDCARD IWC FILE-ERROR)
(DEFSIGNAL INVALID-WILDCARD (FILE-OPERATION-FAILURE INVALID-PATHNAME-SYNTAX INVALID-WILDCARD)
(PATHNAME OPERATION)
"Wildcard that got through pathname parsing but file system didn't like it.")
(DEFPROP WNA WILDCARD-NOT-ALLOWED FILE-ERROR)
(DEFPROP WILDCARD-NOT-ALLOWED WNA FILE-ERROR)
(DEFSIGNAL WILDCARD-NOT-ALLOWED
(FILE-OPERATION-FAILURE INVALID-PATHNAME-SYNTAX WILDCARD-NOT-ALLOWED)
(PATHNAME OPERATION)
"Wildcard is ok but you did something to it that doesn't like wildcards.")
WRONG - KIND - OF - FILE
(DEFPROP WKF WRONG-KIND-OF-FILE FILE-ERROR)
(DEFPROP WRONG-KIND-OF-FILE WKF FILE-ERROR)
(DEFSIGNAL WRONG-KIND-OF-FILE FILE-OPERATION-FAILURE (PATHNAME OPERATION))
(DEFSIGNAL INVALID-OPERATION-FOR-LINK
(FILE-OPERATION-FAILURE WRONG-KIND-OF-FILE INVALID-OPERATION-FOR-LINK)
(PATHNAME OPERATION))
(DEFPROP IOD INVALID-OPERATION-FOR-DIRECTORY FILE-ERROR)
(DEFPROP INVALID-OPERATION-FOR-DIRECTORY IOD FILE-ERROR)
(DEFSIGNAL INVALID-OPERATION-FOR-DIRECTORY
(FILE-OPERATION-FAILURE WRONG-KIND-OF-FILE INVALID-OPERATION-FOR-DIRECTORY)
(PATHNAME OPERATION))
;;; CREATION-FAILUREs
(DEFPROP FAE FILE-ALREADY-EXISTS FILE-ERROR)
(DEFPROP FILE-ALREADY-EXISTS FAE FILE-ERROR)
(DEFSIGNAL FILE-ALREADY-EXISTS (FILE-OPERATION-FAILURE CREATION-FAILURE FILE-ALREADY-EXISTS)
(PATHNAME OPERATION)
"A file of this name already exists.")
(DEFPROP SND SUPERIOR-NOT-DIRECTORY FILE-ERROR)
(DEFPROP SUPERIOR-NOT-DIRECTORY SND FILE-ERROR)
(DEFSIGNAL SUPERIOR-NOT-DIRECTORY
(FILE-OPERATION-FAILURE WRONG-KIND-OF-FILE CREATION-FAILURE SUPERIOR-NOT-DIRECTORY)
(PATHNAME OPERATION)
"The /"directory/" was not a directory.")
(DEFPROP CCD CREATE-DIRECTORY-FAILURE FILE-ERROR)
(DEFPROP CREATE-DIRECTORY-FAILURE CCD FILE-ERROR)
(DEFSIGNAL CREATE-DIRECTORY-FAILURE
(FILE-OPERATION-FAILURE CREATION-FAILURE CREATE-DIRECTORY-FAILURE)
(PATHNAME OPERATION)
"")
(DEFPROP DAE DIRECTORY-ALREADY-EXISTS FILE-ERROR)
(DEFPROP DIRECTORY-ALREADY-EXISTS DAE FILE-ERROR)
(DEFSIGNAL DIRECTORY-ALREADY-EXISTS
(FILE-OPERATION-FAILURE CREATION-FAILURE CREATE-DIRECTORY-FAILURE
FILE-ALREADY-EXISTS DIRECTORY-ALREADY-EXISTS)
(PATHNAME OPERATION)
"A directory of this name already exists.")
(DEFPROP CCL CREATE-LINK-FAILURE FILE-ERROR)
(DEFPROP CREATE-LINK-FAILURE CCL FILE-ERROR)
(DEFSIGNAL CREATE-LINK-FAILURE (FILE-OPERATION-FAILURE CREATION-FAILURE CREATE-LINK-FAILURE)
(PATHNAME OPERATION)
"Some problem creating a link.")
(DEFFLAVOR RENAME-FAILURE () (FILE-OPERATION-FAILURE)
(:DEFAULT-INIT-PLIST :OPERATION ':RENAME))
;Should have property :NEW-PATHNAME.
(DEFPROP REF RENAME-TO-EXISTING-FILE FILE-ERROR)
(DEFPROP RENAME-TO-EXISTING-FILE REF FILE-ERROR)
(DEFSIGNAL RENAME-TO-EXISTING-FILE RENAME-FAILURE (PATHNAME NEW-PATHNAME)
"NEW-PATHNAME already exists.")
(DEFPROP RAD RENAME-ACROSS-DIRECTORIES FILE-ERROR)
(DEFPROP RENAME-ACROSS-DIRECTORIES RAD FILE-ERROR)
(DEFSIGNAL RENAME-ACROSS-DIRECTORIES RENAME-FAILURE (PATHNAME NEW-PATHNAME)
"PATHNAME and NEW-PATHNAME are on different directories.")
(DEFFLAVOR CHANGE-PROPERTY-FAILURE () (FILE-OPERATION-FAILURE)
(:DEFAULT-INIT-PLIST :OPERATION ':CHANGE-PROPERTIES))
(DEFPROP UKP UNKNOWN-PROPERTY FILE-ERROR)
(DEFPROP UNKNOWN-PROPERTY UKP FILE-ERROR)
(DEFSIGNAL UNKNOWN-PROPERTY CHANGE-PROPERTY-FAILURE (PATHNAME PROPERTY)
"PROPERTY isn't one of the properties this file system handles.")
(DEFPROP IPV INVALID-PROPERTY-VALUE FILE-ERROR)
(DEFPROP INVALID-PROPERTY-VALUE IPV FILE-ERROR)
(DEFSIGNAL INVALID-PROPERTY-VALUE CHANGE-PROPERTY-FAILURE (PATHNAME PROPERTY VALUE)
"VALUE is not a legal value for PROPERTY.")
(DEFPROP IPN INVALID-PROPERTY-NAME FILE-ERROR)
(DEFPROP INVALID-PROPERTY-NAME IPN FILE-ERROR)
(DEFSIGNAL INVALID-PROPERTY-NAME CHANGE-PROPERTY-FAILURE (PATHNAME PROPERTY)
"Property name is syntactically bad.")
(DEFFLAVOR DELETE-FAILURE () (FILE-OPERATION-FAILURE)
(:DEFAULT-INIT-PLIST :OPERATION ':DELETE))
(DEFPROP DNE DIRECTORY-NOT-EMPTY FILE-ERROR)
(DEFPROP DIRECTORY-NOT-EMPTY DNE FILE-ERROR)
(DEFSIGNAL DIRECTORY-NOT-EMPTY DELETE-FAILURE (PATHNAME)
"Deleting a directory that is not empty.")
(DEFPROP DND DONT-DELETE-FLAG-SET FILE-ERROR)
(DEFPROP DONT-DELETE-FLAG-SET DND FILE-ERROR)
(DEFSIGNAL DONT-DELETE-FLAG-SET DELETE-FAILURE (PATHNAME)
"File's dont-delete flag was set.")
(COMPILE-FLAVOR-METHODS
FILE-ERROR
FILE-REQUEST-FAILURE
FILE-OPERATION-FAILURE
FILE-LOOKUP-ERROR
NO-MORE-ROOM-ERROR
DIRECTORY-NOT-FOUND-ERROR
RENAME-FAILURE
CHANGE-PROPERTY-FAILURE
DELETE-FAILURE)
;;; This variable is to make DIRED have a guess at what is losing, it should work better
;;; somehow.
(DEFVAR LAST-FILE-OPENED NIL
"This is the last filename that was opened, successfully or not.")
For compatibility , the OPEN function accepts an option name
;;; or a list of options (a single arg), as an alternative to
;;; keywords and values. These option names can be in any package.
;;; Possible keywords and values include the following:
Keyword Possible Values Default Comment
: DIRECTION : INPUT : INPUT
;;; :OUTPUT
;;; NIL This is a probe opening,
;;; no data is transfered.
;;; :CHARACTERS boolean T T if file is textual data.
:
;;; :ERROR boolean T An error is signaled if T.
: BYTE - SIZE NIL NIL 16 for binary files .
;;; System-dependent fixed value for
;;; text files.
: Whatever size the file says it is .
;;; fixnum
;;; :INHIBIT-LINKS boolean NIL
;;; :DELETED boolean NIL
;;; :TEMPORARY boolean NIL
;;; :PRESERVE-DATES boolean NIL Do not update reference or
;;; modification dates.
: FLAVOR NIL NIL Normal file
: DIRECTORY Directory file
;;; :LINK
;;; :LINK-TO pathname Creates a link when used with
;;; :LINK flavor.
;;; :ESTIMATED-SIZE NIL NIL
;;; fixnum (number of bytes)
;;; :NEW-FILE boolean T iff output T means ok to create new file.
;;; :NEW-VERSION boolean NEW-FILE NIL says version = NEWEST
;;; finds newest existing version.
: OLD - FILE : ERROR ( NOT NEW - FILE ) Generate an error when overwriting .
T or : Use the old file .
: Use it , but append if output .
;;; NIL or :REPLACE Overwrite the file when closed.
;;; :RENAME Rename old file
;;; :RENAME-AND-DELETE Same, but delete when closed.
;;; :NEW-VERSION If version is a number and there
;;; is an old file, create new version.
;;; :PHYSICAL-VOLUME NIL NIL
;;; string Where to put file.
: LOGICAL - VOLUME NIL NIL In some systems the pathname can
;;; string specify this.
;;; :INCREMENTAL-UPDATE boolean NIL Attempt to save recoverable data
;;; more often.
Copied from LAD : ; OPEN.LISP#208 on 2 - Oct-86 05:46:47
(DEFUN OPEN (FILENAME &REST KEYWORD-ARGS)
"Open a file and return a stream. FILENAME is a pathname or a string.
DIRECTION is :INPUT, :OUTPUT, :PROBE, :PROBE-LINK :PROBE-DIRECTORY
ELEMENT-TYPE specifies how the data of the stream file are to be interpreted.
Possible values include :DEFAULT CHARACTER (UNSIGNED-BYTE n) (SIGNED-BYTE n) (MOD n) BIT
One may also specify the type using the following two options:
CHARACTERS may be T, NIL or :DEFAULT.
BYTE-SIZE specifies byte size to use for non-character files.
IF-EXISTS specifies what to do if FILENAME already exists when opening it for output.
NIL means return NIL from OPEN if file already exists
:ERROR Signal an error (FS:FILE-ALREADY-EXISTS) See the ERROR option
:NEW-VERSION Default for when FILENAME's version is :NEWEST. Create a higher-version file
:SUPERSEDE Create a new file which, when closed, replaces the old one
:OVERWRITE Writes over the data of the old file.
Sets file length to length of the data written during this open when the file is closed.
:TRUNCATE Like :OVERWRITE, but sets length to 0 immediately upon open
:APPEND Append new data to the end of the existing file
:RENAME Rename the existing file to something and then create and use a new one
:RENAME-AND-DELETE Like :RENAME, only the old (renamed) file is deleted when we close
IF-DOES-NOT-EXIST is one of :CREATE (default for most output opens, except if otherwise
specified by IF-EXISTS), :ERROR (default for input opens, and the other output opens)
means signal FS:FILE-NOT-FOUND, or NIL (default for :PROBE-mumble opens) meaning return NIL
ERROR specifies what to do if an error is signaled in the process of opening the file
T (the default) means that nothing special is done; handlers are invoked if they exist
or else the debugger is entered.
NIL means to return the condition object itself as the value of OPEN
:REPROMPT means to ask the user for a different filename to use instead, and retries.
See also WITH-OPEN-FILE-RETRY and FILE-RETRY-NEW-PATHNAME, which may be The Right Thing
PRESERVE-DATES means not to alter the files reference or modification dates
ESTIMATED-SIZE informs the remote file system what thew estimated final file size will be
RAW, SUPER-IMAGE disable character set translation from ascii servers
DELETED, TEMPORARY mean to allow opening of deleted or temporary files respectively,
on systems which support those concepts.
SUBMIT means to submit the file as a batch job on the remote host when the file is closed.
Other system-specific keywords may be supported for some file systems."
(DECLARE (ARGLIST FILENAME &KEY (DIRECTION :INPUT) (ERROR T) (ELEMENT-TYPE :DEFAULT)
CHARACTERS BYTE-SIZE IF-EXISTS IF-DOES-NOT-EXIST ERROR
PRESERVE-DATES DELETED TEMPORARY SUBMIT PRESERVE-DATES
RAW SUPER-IMAGE INHIBIT-LINKS
&ALLOW-OTHER-KEYS))
(FORCE-USER-TO-LOGIN)
(IF (STREAMP FILENAME)
(SETQ FILENAME (SEND FILENAME :PATHNAME)))
(SETQ FILENAME (MERGE-PATHNAME-DEFAULTS FILENAME))
(SETQ LAST-FILE-OPENED FILENAME)
(IF (OR (NULL KEYWORD-ARGS) ;No args is good args
(NOT (NULL (CDR KEYWORD-ARGS))))
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ (GETF KEYWORD-ARGS ':ERROR) '(:RETRY :REPROMPT))
(FILENAME FILE-ERROR)
(LEXPR-SEND FILENAME :OPEN FILENAME KEYWORD-ARGS))
;; Old Syntax.
(DO ((KEYL (IF (AND (CAR KEYWORD-ARGS) (SYMBOLP (CAR KEYWORD-ARGS)))
(LIST (CAR KEYWORD-ARGS))
(CAR KEYWORD-ARGS))
(CDR KEYL))
(KEY)
(CHARACTERS T)
(DIRECTION :INPUT)
(BYTE-SIZE NIL)
(ERRORP T)
(ERRORP-SPECD NIL)
(DELETED-P NIL)
(TEMPORARY-P NIL)
These two are really only useful for machines that do not natively store
8 - bit characters .
(RAW-P NIL)
(SUPER-IMAGE-P NIL)
)
((NULL KEYL)
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ ERRORP '(:RETRY :REPROMPT))
(FILENAME FILE-ERROR)
;; Because we don't want to send meaningless keywords to file systems
;; which don't support them, and we don't want to cons...
(%ASSURE-PDL-ROOM 19.) ;Worst case
(%OPEN-CALL-BLOCK FILENAME 0 4) ;D-RETURN
(%PUSH :OPEN) (%PUSH FILENAME)
(%PUSH :CHARACTERS) (%PUSH CHARACTERS)
(%PUSH :DIRECTION) (%PUSH DIRECTION)
(COND (BYTE-SIZE (%PUSH :BYTE-SIZE) (%PUSH BYTE-SIZE)))
(COND (ERRORP-SPECD (%PUSH :ERROR) (%PUSH ERRORP)))
(COND (DELETED-P (%PUSH :DELETED) (%PUSH DELETED-P)))
(COND (TEMPORARY-P (%PUSH :TEMPORARY) (%PUSH TEMPORARY-P)))
(COND (SUPER-IMAGE-P (%PUSH :SUPER-IMAGE) (%PUSH SUPER-IMAGE-P)))
(COND (RAW-P (%PUSH :RAW) (%PUSH RAW-P)))
(%ACTIVATE-OPEN-CALL-BLOCK)))
(SETQ KEY (CAR KEYL))
(SELECTOR KEY STRING-EQUAL
((:IN :READ) (SETQ DIRECTION :INPUT))
((:OUT :WRITE :PRINT) (SETQ DIRECTION :OUTPUT))
((:BINARY :FIXNUM) (SETQ CHARACTERS NIL))
((:CHARACTER :ASCII) (SETQ CHARACTERS T))
((:BYTE-SIZE) (SETQ KEYL (CDR KEYL)
BYTE-SIZE (CAR KEYL)))
((:PROBE) (SETQ DIRECTION NIL
CHARACTERS NIL
ERRORP (IF (NOT ERRORP-SPECD) NIL ERRORP)
ERRORP-SPECD T))
((:NOERROR) (SETQ ERRORP NIL ERRORP-SPECD T))
((:ERROR) (SETQ ERRORP T ERRORP-SPECD T))
((:RAW) (SETQ RAW-P T))
((:SUPER-IMAGE) (SETQ SUPER-IMAGE-P T))
((:DELETED) (SETQ DELETED-P T))
((:TEMPORARY) (SETQ TEMPORARY-P T))
Ignored for compatility with
(OTHERWISE (FERROR NIL "~S is not a known OPEN option" KEY))))))
(DEFUN OPEN-FILE-SEARCH (BASE-PATHNAME TYPE-LIST DEFAULTS FOR-FUNCTION &REST OPEN-OPTIONS)
(COND ((NULL (PATHNAME-RAW-TYPE BASE-PATHNAME)))
((AND (EQ (PATHNAME-RAW-TYPE BASE-PATHNAME) :UNSPECIFIC)
(SEND BASE-PATHNAME :UNSPECIFIC-TYPE-IS-DEFAULT))
If type is really insignificant , replace it with NIL
so we will get the same behavior as if it were already NIL .
(SETQ BASE-PATHNAME (SEND BASE-PATHNAME ':NEW-TYPE NIL)))
;; Otherwise, will use only the specified type,
;; so the elements of TYPE-LIST matter only in how many they are,
and we might as well have only one to avoid wasting time on duplicate opens .
(T (SETQ TYPE-LIST '(NIL))))
(DOLIST (TYPE TYPE-LIST
(FERROR 'FS:MULTIPLE-FILE-NOT-FOUND
"~S could not find any file related to ~A."
FOR-FUNCTION BASE-PATHNAME
(MAPCAR #'(LAMBDA (TYPE)
(FS:MERGE-PATHNAME-DEFAULTS
BASE-PATHNAME DEFAULTS TYPE))
TYPE-LIST)))
(CONDITION-CASE (OPEN-VALUE)
(APPLY 'OPEN (FS:MERGE-PATHNAME-DEFAULTS
BASE-PATHNAME DEFAULTS TYPE)
OPEN-OPTIONS)
(FILE-NOT-FOUND)
(:NO-ERROR (RETURN OPEN-VALUE)))))
(DEFUN CLOSE (STREAM &OPTIONAL ABORTP)
"Close STREAM. ABORTP says discard file, if output."
(SEND STREAM ':CLOSE ABORTP))
(DEFUN CLI:CLOSE (STREAM &KEY ABORT)
"Close STREAM. ABORT non-NIL says discard file, if output."
(SEND STREAM ':CLOSE (IF ABORT ':ABORT)))
(DEFUN WILDCARDED-FILE-OPERATION (STRING-OR-STREAM
HELPER-FUNCTION
DIR-LIST-OPTIONS
&REST ARGS)
"Call HELPER-FUNCTION for each file which STRING-OR-STREAM refers to.
If STRING-OR-STREAM is a string (or a pathname) then it can refer to
more than one file by containing wildcards.
The arguments passed to HELPER-FUNCTION each time are
1) the truename of a file,
2) the possibly wildcarded pathname being mapped over
followed by ARGS.
DIR-LIST-OPTIONS are passed to FS:DIRECTORY-LIST when finding out
what files exist to be processed."
(FORCE-USER-TO-LOGIN)
(IF (OR (STRINGP STRING-OR-STREAM)
(TYPEP STRING-OR-STREAM 'PATHNAME)) ;Not a stream
(LET ((SPECIFIED-PATHNAME (MERGE-PATHNAME-DEFAULTS STRING-OR-STREAM)))
(LEXPR-SEND SPECIFIED-PATHNAME ':WILDCARD-MAP HELPER-FUNCTION
NIL DIR-LIST-OPTIONS SPECIFIED-PATHNAME ARGS))
(LET ((SPECIFIED-PATHNAME (SEND STRING-OR-STREAM ':TRUENAME)))
(LIST (APPLY HELPER-FUNCTION
SPECIFIED-PATHNAME
SPECIFIED-PATHNAME
ARGS)))))
;;; Handle special file query stuff. Each of the file operations expects
;;; the query optional argument to be a format style function. The result
;;; of calling the query function is a boolean, and by using this particular
;;; function with *FILE-QUERY-FLAG* closed over it, it is possible to proceed too.
;;;
The function returns 4 possible values :
;;;
NIL , T = = asked the user , got Y or N response .
;;; :PROCEED == asked the user, got P response.
;;; :NEVER-ASKED == didn't ask the user.
(DEFVAR *FILE-QUERY-FLAG* NIL)
(DEFVAR *FILE-QUERY-OPTIONS*
`(:CHOICES (,@FORMAT:Y-OR-N-P-CHOICES
((:PROCEED "Proceed.") #/P #/HAND-RIGHT))))
(DEFUN FILE-QUERY-FUNCTION (FORMAT-STRING &REST ARGS)
(IF (NULL *FILE-QUERY-FLAG*)
':NEVER-ASKED
(LET ((QRESULT (APPLY 'FQUERY *FILE-QUERY-OPTIONS* FORMAT-STRING ARGS)))
(IF (EQ QRESULT ':PROCEED)
(SETQ *FILE-QUERY-FLAG* NIL))
QRESULT)))
(DEFUN MAKE-FILE-QUERY-FUNCTION (QUERY?)
"Return a suitable query-function to pass to PRIMITIVE-DELETE-FILE, etc.
This query function, a closure, accepts a format-string and format-arguments,
queries the user and returns T or NIL.
If the user types P instead of Y, the query function returns ':PROCEED
and also returns ':NEVER-ASKED on all successive calls without asking any more.
If QUERY? is NIL, the query function always returns ':NEVER-ASKED without asking."
(LET-CLOSED ((*FILE-QUERY-FLAG* QUERY?)) 'FILE-QUERY-FUNCTION))
(DEFF COPYF 'COPY-FILE) ;a logical assumption
(DEFUN COPY-FILE (PATHNAME-OR-STREAM NEW-NAME
&REST OPTIONS
&KEY (ERROR T)
&ALLOW-OTHER-KEYS)
"Copy a file, specified as a pathname, string or I//O stream.
CHARACTERS can be T, NIL, meaning the same as in OPEN.
or it can be :ASK, meaning always ask the user,
or :MAYBE-ASK meaning ask the user unless the answer is clear,
or :DEFAULT meaning guess as well as possible but never ask.
Specify BYTE-SIZE to force copying in a certain byte size.
BYTE-SIZE affects only binary mode copying.
REPORT-STREAM is a stream to output messages to as files are copied.
If it is NIL, no messages are output.
COPY-CREATION-DATE if NIL means don't copy the file creation date;
make now be the new file's creation date.
COPY-AUTHOR if NIL means don't copy the author; make you the new file's author.
CREATE-DIRECTORIES says whether to create a directory to be copied into.
Values are T, NIL and :QUERY (meaning ask the user if the situation comes up).
Values returned:
1) the first value is normally the defaulted pathname to copy to,
or a list of such if multiple files were considered.
2) the second value is the old truename of the file considered,
or a list of old truenames of the files considered.
3) the third value is the outcome, or a list of outcomes.
An outcome is either a truename if the file was renamed,
an error object if it failed to be renamed,
or NIL if the user was asked and said no.
4) the fourth value is a mode of copying, or a list of such.
A mode of copying is a type specifier such as STRING-CHAR or (UNSIGNED-BYTE 8).
Error objects can appear in the values only if ERROR is NIL."
(DECLARE (ARGLIST PATHNAME-OR-STREAM NEW-NAME
&KEY (ERROR T) (COPY-CREATION-DATE T) (COPY-AUTHOR T)
REPORT-STREAM (CREATE-DIRECTORIES ':QUERY)
(CHARACTERS ':DEFAULT) (BYTE-SIZE ':DEFAULT))
(VALUES TARGET-PATHNAME TARGET-TRUENAME RESULT-PATHNAME COPY-MODE))
(FORCE-USER-TO-LOGIN)
(LET ((RESULT
(IF (OR (STRINGP PATHNAME-OR-STREAM)
(TYPEP PATHNAME-OR-STREAM 'PATHNAME)) ;Not a stream
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ ERROR '(:RETRY :REPROMPT))
(PATHNAME-OR-STREAM FILE-ERROR)
(LET ((MERGED-PATHNAME (MERGE-PATHNAME-DEFAULTS PATHNAME-OR-STREAM)))
(APPLY MERGED-PATHNAME
':WILDCARD-MAP #'PRIMITIVE-COPY-FILE
':MAYBE NIL
MERGED-PATHNAME (PARSE-PATHNAME NEW-NAME NIL MERGED-PATHNAME) OPTIONS)))
(LET ((TRUENAME (SEND PATHNAME-OR-STREAM ':TRUENAME)))
(LIST (APPLY 'PRIMITIVE-COPY-FILE
(FILE-PROPERTIES TRUENAME)
TRUENAME (PARSE-PATHNAME NEW-NAME NIL TRUENAME) OPTIONS))))))
(IF (EQ (CAAR RESULT) (CADAR RESULT))
(VALUES (THIRD (CAR RESULT))
(FOURTH (CAR RESULT))
(FIFTH (CAR RESULT))
(SIXTH (CAR RESULT)))
(VALUES (MAPCAR 'THIRD RESULT)
(MAPCAR 'FOURTH RESULT)
(MAPCAR 'FIFTH RESULT)
(MAPCAR 'SIXTH RESULT)))))
(DEFCONST *COPY-FILE-KNOWN-TEXT-TYPES* '(:LISP :TEXT :MIDAS :PALX :PATCH-DIRECTORY :C
:INIT :UNFASL :BABYL :XMAIL :MAIL :QWABL :DOC :BOTEX
"LPT" "XGP" "ULOAD")
"Files whose names have these canonical types are normally copied as characters.")
(DEFCONST *COPY-FILE-KNOWN-BINARY-TYPES* '(:QFASL :PRESS :WIDTHS :KST
:impress :dvi
"FASL" "MCR" "QBIN" "EXE" "BIN")
"Files whose names have these canonical types are normally copied as binary.")
(DEFUN PRIMITIVE-COPY-FILE (INPUT-PLIST-OR-PATHNAME MAPPED-PATHNAME OUTPUT-SPEC
&KEY (ERROR T) (COPY-CREATION-DATE T) (COPY-AUTHOR T)
REPORT-STREAM (CREATE-DIRECTORIES ':QUERY)
(CHARACTERS ':DEFAULT) (BYTE-SIZE ':DEFAULT)
&AUX INTYPE INPUT-PLIST INPUT-PATHNAME INPUT-TRUENAME)
(IF (NLISTP INPUT-PLIST-OR-PATHNAME)
(SETQ INPUT-PATHNAME INPUT-PLIST-OR-PATHNAME
INPUT-PLIST NIL)
(SETQ INPUT-PATHNAME (CAR INPUT-PLIST-OR-PATHNAME)
INPUT-PLIST INPUT-PLIST-OR-PATHNAME))
;; Decide whether to copy as binary file.
;; Either do as told, guess from file byte size or type, or ask the user.
(LET ((CHARACTERS?
(SELECTQ CHARACTERS
((T) CHARACTERS)
(:ASK (FQUERY NIL "~&Is ~A a text file? " INPUT-PATHNAME))
(OTHERWISE
;; At this point we really need to refer to the file's property list,
so get it if we were not given it as the first arg .
(IF (NULL INPUT-PLIST)
(SETQ INPUT-PLIST (FILE-PROPERTIES INPUT-PATHNAME)
INPUT-PATHNAME (CAR INPUT-PLIST)))
(LET ((BYTE-SIZE (GET INPUT-PLIST ':BYTE-SIZE)))
(COND ((NULL CHARACTERS) NIL)
((MEMQ BYTE-SIZE '(7 8)) T)
((EQ BYTE-SIZE 16.) NIL)
((MEMBER (SETQ INTYPE (SEND INPUT-PATHNAME ':CANONICAL-TYPE))
*COPY-FILE-KNOWN-TEXT-TYPES*)
T)
((MEMBER INTYPE *COPY-FILE-KNOWN-BINARY-TYPES*) NIL)
((EQ CHARACTERS ':DEFAULT) ':DEFAULT)
(T (FQUERY '(:BEEP T) "~&Is ~A a text file? " INPUT-PATHNAME))))))))
(IF (EQ BYTE-SIZE ':DEFAULT)
(SETQ BYTE-SIZE (OR (GET INPUT-PLIST ':BYTE-SIZE) ':DEFAULT)))
(IF (EQ BYTE-SIZE 36.)
(SETQ BYTE-SIZE 12.))
(CONDITION-CASE-IF (NOT ERROR) (ERROR)
(WITH-OPEN-FILE (INSTREAM INPUT-PATHNAME
':DIRECTION ':INPUT
':CHARACTERS CHARACTERS?
':BYTE-SIZE BYTE-SIZE)
(SETQ INPUT-TRUENAME (SEND INSTREAM ':TRUENAME))
(LET ((DEFAULTED-NEW-NAME
(LET ((*ALWAYS-MERGE-TYPE-AND-VERSION* T))
(MERGE-PATHNAME-DEFAULTS
(SEND MAPPED-PATHNAME ':TRANSLATE-WILD-PATHNAME
OUTPUT-SPEC INPUT-TRUENAME)
INPUT-TRUENAME))))
(CONDITION-BIND ((DIRECTORY-NOT-FOUND
#'(LAMBDA (ERROR)
(WHEN (IF (EQ CREATE-DIRECTORIES ':QUERY)
(PROGN
(SEND *QUERY-IO* ':FRESH-LINE)
(SEND ERROR ':REPORT *QUERY-IO*)
(Y-OR-N-P "Create the directory? "))
CREATE-DIRECTORIES)
(CREATE-DIRECTORY defaulted-new-name ':RECURSIVE T)
':RETRY-FILE-OPERATION))))
(WITH-OPEN-FILE (OUTSTREAM DEFAULTED-NEW-NAME
':DIRECTION ':OUTPUT
':CHARACTERS CHARACTERS?
':BYTE-SIZE (IF CHARACTERS? ':DEFAULT BYTE-SIZE))
(IF COPY-AUTHOR
(IF COPY-CREATION-DATE
(SEND OUTSTREAM ':CHANGE-PROPERTIES NIL
':CREATION-DATE (SEND INSTREAM ':CREATION-DATE)
':AUTHOR (OR (SEND INSTREAM ':GET ':AUTHOR)
(GET INPUT-PLIST ':AUTHOR)))
(SEND OUTSTREAM ':CHANGE-PROPERTIES NIL
':AUTHOR (OR (SEND INSTREAM ':GET ':AUTHOR)
(GET INPUT-PLIST ':AUTHOR))))
(IF COPY-CREATION-DATE
(SEND OUTSTREAM ':CHANGE-PROPERTIES NIL
':CREATION-DATE (SEND INSTREAM ':CREATION-DATE))))
(STREAM-COPY-UNTIL-EOF INSTREAM OUTSTREAM)
(CLOSE OUTSTREAM)
(WHEN REPORT-STREAM
(FORMAT REPORT-STREAM "~&Copied ~A to ~A "
INPUT-TRUENAME (SEND OUTSTREAM ':TRUENAME))
(IF CHARACTERS?
(FORMAT REPORT-STREAM "in character mode.~%")
(FORMAT REPORT-STREAM "in byte size ~D.~%"
BYTE-SIZE)))
(LIST MAPPED-PATHNAME INPUT-PATHNAME DEFAULTED-NEW-NAME
INPUT-TRUENAME (SEND OUTSTREAM ':TRUENAME)
(STREAM-ELEMENT-TYPE INSTREAM))))))
((FILE-ERROR SYS:REMOTE-NETWORK-ERROR)
(LIST MAPPED-PATHNAME INPUT-PATHNAME
(LET ((*ALWAYS-MERGE-TYPE-AND-VERSION* T))
(MERGE-PATHNAME-DEFAULTS
(SEND MAPPED-PATHNAME ':TRANSLATE-WILD-PATHNAME
OUTPUT-SPEC (OR INPUT-TRUENAME INPUT-PATHNAME))
(OR INPUT-TRUENAME INPUT-PATHNAME)))
INPUT-PATHNAME ERROR)))))
(DEFUN RENAME-FILE (STRING-OR-STREAM NEW-NAME &KEY (ERROR T) QUERY)
"Rename a file, specified as a pathname, string or I//O stream.
Wildcards are allowed.
QUERY, if true, means ask about each file before renaming it.
Values returned:
1) the first value is normally the defaulted pathname to rename to,
or a list of such if multiple files were considered.
2) the second value is the old truename of the file considered,
or a list of old truenames of the files considered.
3) the third value is the outcome, or a list of outcomes.
An outcome is either a truename if the file was renamed,
an error object if it failed to be renamed,
or NIL if the user was asked and said no.
Error objects can appear in the values only if ERROR is NIL."
(DECLARE (VALUES OLD-NAME OLD-TRUENAME NEW-TRUENAME))
(RENAMEF STRING-OR-STREAM NEW-NAME ERROR QUERY))
(DEFUN RENAMEF (STRING-OR-STREAM NEW-NAME &OPTIONAL (ERROR-P T) QUERY?)
"Rename a file, specified as a pathname, string or I//O stream.
Wildcards are allowed.
QUERY?, if true, means ask about each file before renaming it.
Values returned:
1) the first value is normally the defaulted pathname to rename to,
or a list of such if multiple files were considered.
2) the second value is the old truename of the file considered,
or a list of old truenames of the files considered.
3) the third value is the outcome, or a list of outcomes.
An outcome is either a truename if the file was renamed,
an error object if it failed to be renamed,
or NIL if the user was asked and said no.
Error objects can appear in the values only if ERROR-P is NIL."
(DECLARE (VALUES OLD-NAME OLD-TRUENAME NEW-TRUENAME))
(FILE-RETRY-NEW-PATHNAME-IF (AND (OR (STRINGP STRING-OR-STREAM)
(TYPEP STRING-OR-STREAM 'PATHNAME))
(MEMQ ERROR-P '(:RETRY :REPROMPT)))
(STRING-OR-STREAM FILE-ERROR)
(LET* ((FROM-PATHNAME (PATHNAME STRING-OR-STREAM))
(RESULT (WILDCARDED-FILE-OPERATION
STRING-OR-STREAM
#'PRIMITIVE-RENAME-FILE
NIL
(PARSE-PATHNAME NEW-NAME NIL FROM-PATHNAME) ERROR-P
(MAKE-FILE-QUERY-FUNCTION QUERY?))))
(IF (EQ (CAAR RESULT) (CADAR RESULT))
(VALUES (THIRD (CAR RESULT))
(FOURTH (CAR RESULT))
(FIFTH (CAR RESULT)))
(VALUES (MAPCAR 'THIRD RESULT)
(MAPCAR 'FOURTH RESULT)
(MAPCAR 'FIFTH RESULT))))))
(DEFUN PRIMITIVE-RENAME-FILE (OLD-NAME MAPPED-PATHNAME NEW-NAME &OPTIONAL (ERROR-P T) QUERYF)
(LET ((TRUENAME (IF (or (EQ OLD-NAME MAPPED-PATHNAME)
(typep old-name 'logical-pathname))
(SEND OLD-NAME ':TRUENAME ERROR-P)
OLD-NAME))
(newname (if (typep new-name 'logical-pathname)
(translated-pathname (merge-pathname-defaults new-name mapped-pathname))
new-name)))
(IF (ERRORP TRUENAME)
(LIST MAPPED-PATHNAME OLD-NAME NIL OLD-NAME TRUENAME)
(LET* ((DEFAULTED-NEW-NAME
(LET ((*ALWAYS-MERGE-TYPE-AND-VERSION* T))
(MERGE-PATHNAME-DEFAULTS
(SEND MAPPED-PATHNAME ':TRANSLATE-WILD-PATHNAME newname TRUENAME)
TRUENAME)))
(RENAMED? (FUNCALL QUERYF "~&Rename ~A to ~A? "
TRUENAME DEFAULTED-NEW-NAME))
(RESULT (AND RENAMED? (SEND TRUENAME ':RENAME
DEFAULTED-NEW-NAME ERROR-P))))
(LIST MAPPED-PATHNAME OLD-NAME DEFAULTED-NEW-NAME TRUENAME RESULT)))))
(DEFUN CREATE-LINK (LINK LINK-TO &KEY (ERROR T))
"Create a link, which is specified as a pathname or string, to the file LINK-TO."
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ ERROR '(:RETRY :REPROMPT))
(LINK FILE-ERROR)
(LET ((PATHNAME (MERGE-PATHNAME-DEFAULTS LINK)))
(SEND PATHNAME ':CREATE-LINK (LET ((*ALWAYS-MERGE-TYPE-AND-VERSION* T))
(MERGE-PATHNAME-DEFAULTS LINK-TO PATHNAME))
':ERROR ERROR))))
(DEFUN DELETE-FILE (STRING-OR-STREAM &KEY (ERROR T) QUERY)
"Delete a file, specified as a pathname, string or I//O stream.
Wildcards are allowed.
QUERY, if true, means to ask the user before deleting each file.
The value is a list containing one element for each file we considered;
the element looks like (TRUENAME OUTCOME), where OUTCOME
is either an error object, NIL if the user said don't delete this one,
or another non-NIL object if the file was deleted.
OUTCOME can be an error object only if ERROR is NIL.
ERROR does not affect errors that happen in determining
what files match a wildcarded pathname."
(DELETEF STRING-OR-STREAM ERROR QUERY))
(DEFUN DELETEF (STRING-OR-STREAM &OPTIONAL (ERROR-P T) QUERY?)
"Delete a file, specified as a pathname, string or I//O stream.
Wildcards are allowed.
QUERY?, if true, means to ask the user before deleting each file.
The value is a list containing one element for each file we considered;
the element looks like (TRUENAME OUTCOME), where OUTCOME
is either an error object, NIL if the user said don't delete this one,
or another non-NIL object if the file was deleted.
OUTCOME can be an error object only if ERROR-P is NIL.
ERROR-P does not affect errors that happen in determining
what files match a wildcarded pathname."
(FILE-RETRY-NEW-PATHNAME-IF (AND (OR (STRINGP STRING-OR-STREAM)
(TYPEP STRING-OR-STREAM 'PATHNAME))
(MEMQ ERROR-P '(:RETRY :REPROMPT)))
(STRING-OR-STREAM FILE-ERROR)
(WILDCARDED-FILE-OPERATION STRING-OR-STREAM
#'PRIMITIVE-DELETE-FILE NIL
ERROR-P
(MAKE-FILE-QUERY-FUNCTION QUERY?))))
(DEFUN PRIMITIVE-DELETE-FILE (PATHNAME MAPPED-PATHNAME &OPTIONAL (ERROR-P T) QUERYF)
"QUERYF should be a function that takes a format-string and a pathname
and returns T or NIL saying whether to delete that file.
If you don't want any querying, pass FILE-QUERY-TRUE as QUERYF."
(LET ((TRUENAME (cond
((EQ PATHNAME MAPPED-PATHNAME) (SEND PATHNAME ':TRUENAME ERROR-P))
((typep pathname 'logical-pathname) (translated-pathname pathname))
(t PATHNAME))))
(IF (ERRORP TRUENAME)
(LIST PATHNAME TRUENAME)
(LET* ((DELETE? (FUNCALL QUERYF "~&Delete ~A? " TRUENAME))
(RESULT (AND DELETE? (SEND TRUENAME ':DELETE ERROR-P))))
(LIST TRUENAME (IF (ERRORP RESULT) RESULT DELETE?))))))
(DEFUN UNDELETE-FILE (STRING-OR-STREAM &KEY (ERROR T) QUERY)
"Undelete a file, specified as a pathname, string or I//O stream.
Wildcards are allowed. Not all file servers support undeletion.
QUERY, if true, means to ask the user before undeleting each file.
The value is a list containing one element for each file we considered;
the element looks like (TRUENAME OUTCOME), where OUTCOME
is either an error object, NIL if the user said don't undelete this one,
or another non-NIL object if the file was undeleted.
OUTCOME can be an error object only if ERROR is NIL.
ERROR does not affect errors that happen in determining
what files match a wildcarded pathname."
(UNDELETEF STRING-OR-STREAM ERROR QUERY))
(DEFUN UNDELETEF (STRING-OR-STREAM &OPTIONAL (ERROR-P T) QUERY?)
"Undelete a file, specified as a pathname, string or I//O stream.
Wildcards are allowed. Not all file servers support undeletion.
QUERY?, if true, means to ask the user before undeleting each file.
The value is a list containing one element for each file we considered;
the element looks like (TRUENAME OUTCOME), where OUTCOME
is either an error object, NIL if the user said don't undelete this one,
or another non-NIL object if the file was undeleted.
OUTCOME can be an error object only if ERROR-P is NIL.
ERROR-P does not affect errors that happen in determining
what files match a wildcarded pathname."
(FILE-RETRY-NEW-PATHNAME-IF (AND (OR (STRINGP STRING-OR-STREAM)
(TYPEP STRING-OR-STREAM 'PATHNAME))
(MEMQ ERROR-P '(:RETRY :REPROMPT)))
(STRING-OR-STREAM FILE-ERROR)
(WILDCARDED-FILE-OPERATION STRING-OR-STREAM
#'PRIMITIVE-UNDELETE-FILE '(:DELETED)
ERROR-P
(MAKE-FILE-QUERY-FUNCTION QUERY?))))
(DEFUN PRIMITIVE-UNDELETE-FILE (PATHNAME MAPPED-PATHNAME &OPTIONAL (ERROR-P T) QUERYF)
"QUERYF should be a function that takes a format-string and a pathname
and returns T or NIL saying whether to delete that file.
If you don't want any querying, pass FILE-QUERY-TRUE as QUERYF."
(LET ((TRUENAME (IF (EQ PATHNAME MAPPED-PATHNAME)
(WITH-OPEN-FILE (STREAM PATHNAME ':ERROR ERROR-P ':DELETED T
':DIRECTION NIL)
(IF (ERRORP STREAM) STREAM
(SEND STREAM ':TRUENAME)))
PATHNAME)))
(IF (ERRORP TRUENAME)
(LIST PATHNAME TRUENAME)
(LET* ((UNDELETE? (FUNCALL QUERYF "~&Undelete ~A? " TRUENAME))
(RESULT (AND UNDELETE? (SEND TRUENAME ':UNDELETE ERROR-P))))
(LIST TRUENAME (IF (ERRORP RESULT) RESULT UNDELETE?))))))
(DEFF PROBE-FILE 'PROBEF)
(DEFUN PROBEF (FILE)
"Non-NIL if FILE exists.
Return the file's truename if successful, NIL if file-not-found.
Any other error condition is not handled."
(IF (STREAMP FILE)
(SEND FILE ':TRUENAME)
(CONDITION-CASE (STREAM)
(OPEN FILE ':DIRECTION NIL)
(FILE-NOT-FOUND NIL)
(:NO-ERROR (PROG1 (SEND STREAM ':TRUENAME) (CLOSE STREAM))))))
(DEFUN FILE-WRITE-DATE (FILENAME-OR-STREAM)
"Return file's creation or last write date. Specify pathname, namestring or file stream."
(IF (OR (STRINGP FILENAME-OR-STREAM)
(SYMBOLP FILENAME-OR-STREAM)
(TYPEP FILENAME-OR-STREAM 'PATHNAME))
(WITH-OPEN-FILE (STREAM FILENAME-OR-STREAM ':DIRECTION NIL)
(SEND STREAM ':CREATION-DATE))
(SEND FILENAME-OR-STREAM ':CREATION-DATE)))
(DEFUN FILE-AUTHOR (FILENAME-OR-STREAM)
"Return file's author's name (a string). Specify pathname, namestring or file stream."
(IF (OR (STRINGP FILENAME-OR-STREAM)
(SYMBOLP FILENAME-OR-STREAM)
(TYPEP FILENAME-OR-STREAM 'PATHNAME))
(WITH-OPEN-FILE (STREAM FILENAME-OR-STREAM ':DIRECTION NIL)
(SEND STREAM ':GET ':AUTHOR))
(SEND FILENAME-OR-STREAM ':GET ':AUTHOR)))
Copied from LAD : ; OPEN.LISP#208 on 2 - Oct-86 05:46:52
(DEFUN FILE-POSITION (FILE-STREAM &OPTIONAL NEW-POSITION)
"Return or set the stream pointer of FILE-STREAM.
With one argument, return the stream pointer of FILE-STREAM, or NIL if not known.
With two arguments, try to set the stream pointer to NEW-POSITION
and return T if it was possible to do so."
(COND (NEW-POSITION
(SEND-IF-HANDLES FILE-STREAM :SET-POINTER NEW-POSITION))
(T
(SEND-IF-HANDLES FILE-STREAM :READ-POINTER))))
Copied from LAD : ; OPEN.LISP#208 on 2 - Oct-86 05:46:53
(DEFUN FILE-LENGTH (FILE-STREAM)
"Return the length of the file that is open, or NIL if not known."
(SEND FILE-STREAM :LENGTH))
(DEFUN VIEWF (FILE &OPTIONAL (OUTPUT-STREAM *STANDARD-OUTPUT*) LEADER)
"Print the contents of a file on the output stream.
LEADER is passed to the :LINE-IN operation."
(WITH-OPEN-FILE (FILE-STREAM FILE ':ERROR ':REPROMPT)
(IF (ERRORP FILE-STREAM)
FILE-STREAM
(SEND OUTPUT-STREAM ':FRESH-LINE)
(STREAM-COPY-UNTIL-EOF FILE-STREAM OUTPUT-STREAM LEADER))))
;;this isn't the right place for this, but its not clear where it should go
(DEFUN FS:WORKING-DIRECTORY () ;&optional defaults
(LET ((PATHNAME (FS:DEFAULT-PATHNAME)))
(FS:MAKE-PATHNAME ':HOST (SEND PATHNAME ':HOST) ':DIRECTORY (SEND PATHNAME ':DIRECTORY))))
(DEFUN LISTF (&OPTIONAL (DIRECTORY (FS:WORKING-DIRECTORY))
(OUTPUT-STREAM *STANDARD-OUTPUT*) LEADER)
"Print a listing of DIRECTORY on OUTPUT-STREAM.
LEADER is passed to the :LINE-IN operation."
(SETQ DIRECTORY (FS:PARSE-PATHNAME DIRECTORY))
(OR (SEND DIRECTORY ':NAME)
(SETQ DIRECTORY (SEND DIRECTORY ':NEW-NAME ':WILD)))
(SETQ DIRECTORY (FS:MERGE-PATHNAME-DEFAULTS DIRECTORY NIL ':WILD ':WILD))
(SEND OUTPUT-STREAM ':FRESH-LINE)
(FILE-RETRY-NEW-PATHNAME (DIRECTORY FS:FILE-ERROR)
(WITH-OPEN-STREAM (STREAM (ZWEI:DIRECTORY-INPUT-STREAM DIRECTORY))
(STREAM-COPY-UNTIL-EOF STREAM OUTPUT-STREAM LEADER)))
DIRECTORY)
(DEFVAR USER-HOMEDIRS NIL
"Alist mapping host objects to pathnames. Gives the home device//directory for each host.")
(DEFVAR USER-PERSONAL-NAME ""
"The user's full name, last name first. Obtained from the FS:USER-LOGIN-MACHINE.")
(DEFVAR USER-PERSONAL-NAME-FIRST-NAME-FIRST ""
"The user's full name, first name first. Obtained from the FS:USER-LOGIN-MACHINE.")
(DEFVAR USER-GROUP-AFFILIATION #/-
"The user's /"group affiliation/", a character. Obtained from the FS:USER-LOGIN-MACHINE.")
(DEFVAR USER-LOGIN-MACHINE SI:ASSOCIATED-MACHINE
"The host the user logged in on.")
(DEFF USER-HOMEDIR-PATHNAME 'USER-HOMEDIR)
(DEFUN USER-HOMEDIR (&OPTIONAL (HOST USER-LOGIN-MACHINE) RESET-P (USER USER-ID))
"Return a pathname describing the home directory for USER on host HOST.
This is used as a default, sometimes. RESET-P says make this our login host."
(SETQ HOST (GET-PATHNAME-HOST HOST))
(AND (TYPEP HOST 'LOGICAL-HOST) (SETQ HOST (SEND HOST ':PHYSICAL-HOST))) ;Just in case
(AND RESET-P (SETQ USER-LOGIN-MACHINE HOST))
(CONDITION-CASE ()
(SEND (SAMPLE-PATHNAME HOST) ':HOMEDIR USER)
(FILE-ERROR
(QUIET-USER-HOMEDIR HOST))))
(DEFUN QUIET-USER-HOMEDIR (HOST)
(OR (CDR (ASSQ HOST USER-HOMEDIRS))
(SEND (SAMPLE-PATHNAME HOST) ':QUIET-HOMEDIR)))
(DEFUN FORCE-USER-TO-LOGIN (&OPTIONAL (HOST SI:ASSOCIATED-MACHINE)
&AUX INPUT USER DONT-READ-INIT IDX IDX2)
"Require the user to log in. HOST is a default for logging in."
(WHEN (OR (NULL USER-ID) (STRING-EQUAL USER-ID ""))
(SEND *QUERY-IO* ':BEEP)
(FORMAT *QUERY-IO*
"~&Please log in. ~
~<~%~:;Type username or username@host ~<~%~:;(host defaults to ~A)~>~>
To avoid loading your init file, ~<~%~:;follow by <space>T : ~>"
HOST)
(SETQ INPUT (STRING-TRIM '(#/SPACE #/TAB) (READLINE *QUERY-IO*)))
(AND (SETQ IDX (STRING-SEARCH-CHAR #/@ INPUT))
(SETQ USER (SUBSTRING INPUT 0 IDX)))
(AND (SETQ IDX2 (STRING-SEARCH-SET '(#/SPACE #/TAB) INPUT (OR IDX 0)))
(SETQ DONT-READ-INIT (READ-FROM-STRING INPUT T IDX2)))
(IF IDX
(SETQ HOST (SUBSTRING INPUT (1+ IDX) IDX2))
(SETQ USER (SUBSTRING INPUT 0 IDX2)))
(OR (STRING-EQUAL USER "")
(LOGIN USER HOST DONT-READ-INIT))))
(DEFVAR USER-UNAMES NIL "Alist mapping host objects into usernames.")
(DEFUN FILE-HOST-USER-ID (UID HOST)
"Specify the user-id UID for use on host HOST."
(AND (MEMQ (SEND HOST ':SYSTEM-TYPE) '(:ITS :LMFILE))
;; All ITS's have the same set of unames, so record as ITS rather than the host.
(SETQ HOST 'ITS
UID (SUBSTRING UID 0 (MIN (STRING-LENGTH UID) 6))))
(LET ((AE (ASSQ HOST USER-UNAMES)))
(IF AE
(RPLACD AE UID)
(PUSH (CONS HOST UID) USER-UNAMES))))
(DEFUN UNAME-ON-HOST (HOST) ; Must be a host object
(CDR (ASSQ (IF (EQ (SEND HOST ':SYSTEM-TYPE) ':ITS) 'ITS HOST) USER-UNAMES)))
(ADD-INITIALIZATION "File Host User ID" '(FILE-HOST-USER-ID USER-ID USER-LOGIN-MACHINE)
'(LOGIN))
(ADD-INITIALIZATION "Reset File Host User ID" '(SETQ USER-UNAMES NIL) '(LOGOUT))
Alist of elements ( ( username host ) password - string )
(DEFVAR USER-HOST-PASSWORD-ALIST NIL
"Alist of elements ((USERNAME HOST-NAME) PASSWORD).
The three data in each element are all strings.")
(DEFVAR RECORD-PASSWORDS-FLAG T
"T => record passwords when the user types them, in case they are useful again.")
; brand s name
(DEFVAR *REMEMBER-PASSWORDS* :UNBOUND
"T => record passwords when the user types them, in case they are useful again.")
(FORWARD-VALUE-CELL '*REMEMBER-PASSWORDS* 'RECORD-PASSWORDS-FLAG)
(ADD-INITIALIZATION "Forget Passwords" '(SETQ USER-HOST-PASSWORD-ALIST NIL) '(BEFORE-COLD))
(DEFUN FILE-GET-PASSWORD (UID HOST &OPTIONAL DIRECTORY-FLAG)
"Given a username and host, ask for either a password or a username and password.
If DIRECTORY-FLAG is set, we are using directory names, not passwords"
(DECLARE (VALUES NEW-USER-ID PASSWORD ENABLE-CAPABILITIES))
(LET* ((LINE (MAKE-STRING 30 ':FILL-POINTER 0))
ENABLE-CAPABILITIES CHAR UID-P
(HACK (AND (SEND *QUERY-IO* ':OPERATION-HANDLED-P ':CLEAR-BETWEEN-CURSORPOSES)
(SEND *QUERY-IO* ':OPERATION-HANDLED-P ':COMPUTE-MOTION)))
START-X START-Y)
(UNLESS DIRECTORY-FLAG
(SETQ UID (OR (CDR (ASSQ HOST USER-UNAMES)) UID)))
(LET ((PW (CADR (ASSOC-EQUALP (LIST UID (SEND HOST ':NAME))
USER-HOST-PASSWORD-ALIST))))
(WHEN PW (RETURN-FROM FILE-GET-PASSWORD (values UID PW))))
(TAGBODY
(WHEN HACK (SETQ HACK (MAKE-STRING 30. ':INITIAL-VALUE #/X ':FILL-POINTER 0)))
RESTART
(UNLESS DIRECTORY-FLAG
(SETQ UID (OR (CDR (ASSQ HOST USER-UNAMES)) UID)))
(LET ((PW (CADR (ASSOC-EQUALP (LIST UID (SEND HOST ':NAME))
USER-HOST-PASSWORD-ALIST))))
(WHEN PW (RETURN-FROM FILE-GET-PASSWORD (values UID PW))))
(FORMAT *QUERY-IO*
(IF DIRECTORY-FLAG "~&Type the password for directory ~A on host ~A,
or a directory and password. /"Directory/" here includes devices as well: "
for host ~A.~ >
Type either password or ~<~%~:;loginname<space>password: ~>")
UID HOST)
(WHEN HACK (MULTIPLE-VALUE (START-X START-Y) (SEND *QUERY-IO* ':READ-CURSORPOS)))
L (SETQ CHAR (SEND *QUERY-IO* ':TYI))
(COND ((= CHAR #/C-Q) ;quoting character.
(VECTOR-PUSH-EXTEND (SEND *QUERY-IO* ':TYI) LINE)
(WHEN HACK
(VECTOR-PUSH-EXTEND #/X HACK)
(SEND *QUERY-IO* ':TYO #/X)))
((= CHAR #/RUBOUT)
(WHEN (ZEROP (FILL-POINTER LINE))
(GO FLUSH))
(VECTOR-POP LINE)
(WHEN HACK
(VECTOR-POP HACK)
(MULTIPLE-VALUE-BIND (X Y)
(SEND *QUERY-IO* ':COMPUTE-MOTION HACK 0 NIL
START-X START-Y)
(MULTIPLE-VALUE-BIND (CX CY) (SEND *QUERY-IO* ':READ-CURSORPOS)
(SEND *QUERY-IO* ':CLEAR-BETWEEN-CURSORPOSES X Y CX CY))
(SEND *QUERY-IO* ':SET-CURSORPOS X Y))))
((= CHAR #/CLEAR-INPUT)
(GO FLUSH))
((AND (= CHAR #/SPACE)
(NOT UID-P)) ;allow spaces in passwords
(WHEN ENABLE-CAPABILITIES
(VECTOR-PUSH-EXTEND #/* LINE 1);make sure we have room for extra element
(DOTIMES (I (1- (FILL-POINTER LINE)))
(SETF (AREF LINE (1+ I)) (AREF LINE (1- I))))
(SETF (CHAR LINE 0) #/*)
(SETQ ENABLE-CAPABILITIES NIL))
(SETQ UID-P T
UID LINE
LINE (MAKE-STRING 30. :FILL-POINTER 0))
(WHEN HACK
(MULTIPLE-VALUE-BIND (CX CY) (SEND *QUERY-IO* ':READ-CURSORPOS)
(SEND *QUERY-IO* ':CLEAR-BETWEEN-CURSORPOSES START-X START-Y CX CY))
(SEND *QUERY-IO* ':SET-CURSORPOS START-X START-Y))
(FORMAT *QUERY-IO* "~A " UID)
(WHEN HACK (MULTIPLE-VALUE (START-X START-Y)
(SEND *QUERY-IO* ':READ-CURSORPOS))))
((= CHAR #/RETURN)
(OR DIRECTORY-FLAG (FILE-HOST-USER-ID UID HOST))
(IF RECORD-PASSWORDS-FLAG
(PUSH `((,UID ,(SEND HOST ':NAME)) ,LINE) USER-HOST-PASSWORD-ALIST))
(WHEN HACK
(MULTIPLE-VALUE-BIND (CX CY) (SEND *QUERY-IO* ':READ-CURSORPOS)
(SEND *QUERY-IO* ':CLEAR-BETWEEN-CURSORPOSES START-X START-Y CX CY))
(SEND *QUERY-IO* ':SET-CURSORPOS START-X START-Y))
(FRESH-LINE *QUERY-IO*)
(SEND *QUERY-IO* ':SEND-IF-HANDLES ':MAKE-COMPLETE)
(RETURN-FROM FILE-GET-PASSWORD (values UID LINE ENABLE-CAPABILITIES)))
((AND (= CHAR #/*)
(= (FILL-POINTER LINE) 0))
(SETQ ENABLE-CAPABILITIES T))
(( 0 (CHAR-BITS CHAR)) (BEEP))
(T (WHEN HACK
(VECTOR-PUSH-EXTEND #/X HACK)
(SEND *QUERY-IO* ':TYO #/X))
(VECTOR-PUSH-EXTEND CHAR LINE)))
(GO L)
FLUSH
(WHEN HACK
(MULTIPLE-VALUE-BIND (CX CY) (SEND *QUERY-IO* ':READ-CURSORPOS)
(SEND *QUERY-IO* ':CLEAR-BETWEEN-CURSORPOSES START-X START-Y CX CY))
(SEND *QUERY-IO* ':SET-CURSORPOS START-X START-Y)
(SETF (FILL-POINTER HACK) 0))
(WHEN UID-P (RETURN-ARRAY (PROG1 LINE (SETQ LINE UID UID NIL))))
(FORMAT *QUERY-IO* "Flushed.~&")
(SETF (FILL-POINTER LINE) 0 UID-P NIL)
(GO RESTART))))
;;; Used by MAKE-SYSTEM for fast INFO access
(DEFUN MULTIPLE-FILE-PLISTS (FILENAMES &REST OPTIONS &AUX HOST-FILE-LIST)
"Given a list of pathnames or namestrings, return a list of property lists.
Each element of the value looks like (pathname . properties)."
(FORCE-USER-TO-LOGIN)
(DOLIST (FILENAME FILENAMES)
(SETQ FILENAME (MERGE-PATHNAME-DEFAULTS FILENAME))
(DO ((HOST (SEND FILENAME ':HOST))
(LIST HOST-FILE-LIST (CDR LIST)))
((NULL LIST)
(PUSH (NCONS FILENAME) HOST-FILE-LIST))
(COND ((EQ HOST (SEND (CAAR HOST-FILE-LIST) ':HOST))
(PUSH FILENAME (CAR LIST))
(RETURN)))))
(LOOP FOR LIST IN (NREVERSE HOST-FILE-LIST)
NCONC (SEND (CAR LIST) ':MULTIPLE-FILE-PLISTS (NREVERSE LIST) OPTIONS)))
;;; Old name for compatibility
(DEFUN MULTIPLE-FILE-PROPERTY-LISTS (BINARY-P FILENAMES)
(MULTIPLE-FILE-PLISTS FILENAMES ':CHARACTERS (NOT BINARY-P)))
(DEFUN CLOSE-ALL-FILES (&OPTIONAL (MODE :ABORT))
"Close all file streams that are open."
(NCONC (AND (BOUNDP 'TV::WHO-LINE-FILE-STATE-SHEET)
TV::WHO-LINE-FILE-STATE-SHEET
(DO ((F (SEND TV::WHO-LINE-FILE-STATE-SHEET :OPEN-STREAMS)
(CDR F))
(THINGS-CLOSED NIL))
((NULL F)
(SEND TV::WHO-LINE-FILE-STATE-SHEET :DELETE-ALL-STREAMS)
(NREVERSE THINGS-CLOSED))
(FORMAT *ERROR-OUTPUT* "~%Closing ~S" (CAR F))
(PUSH (CAR F) THINGS-CLOSED)
(SEND (CAR F) :CLOSE MODE)))
(LOOP FOR HOST IN *PATHNAME-HOST-LIST*
NCONC (SEND HOST :CLOSE-ALL-FILES MODE))))
(DEFUN ALL-OPEN-FILES ()
"Return a list of all file streams that are open."
(SI:ELIMINATE-DUPLICATES (APPEND (SEND TV:WHO-LINE-FILE-STATE-SHEET ':OPEN-STREAMS)
(LOOP FOR HOST IN *PATHNAME-HOST-LIST*
APPEND (SEND HOST ':OPEN-STREAMS)))))
;;;; Directory stuff
Copied from LAD : ; OPEN.LISP#208 on 2 - Oct-86 05:46:55
(DEFUN DIRECTORY (PATHNAME)
"Common Lisp function to get the list of files in a directory.
The value is just a list of truenames.
You will get much more useful information by using FS:DIRECTORY-LIST."
(let ((path (pathname pathname)))
(unless (send path :name)
(setq path (send path :new-name :wild)))
(MAPCAR 'CAR (CDR (DIRECTORY-LIST path :fast)))))
;;; This is the primary user interface to the directory listing
stuff . It returns a list of lists , one for each file . The format
;;; of these lists is (PATHNAME . PLIST). The currently defined indicators
for PLIST are :
;;; :ACCOUNT <string>
;;; :AUTHOR <string>
;;; :BLOCK-SIZE <number>
: BYTE - SIZE < number >
;;; :CREATION-DATE <universal-date>
;;; :DELETED <boolean>
;;; :DONT-DELETE <boolean>
;;; :DONT-DUMP <boolean>
;;; :DONT-REAP <boolean>
: DUMPED < boolean >
;;; :GENERATION-RETENTION-COUNT <number>
;;; :LENGTH-IN-BLOCKS <number>
;;; :LENGTH-IN-BYTES <number>
;;; :LINK-TO <string>
;;; :OFFLINE <boolean>
;;; :PHYSICAL-VOLUME <string>
;;; :PROTECTION <string>
;;; :READER <string>
;;; :REFERENCE-DATE <universal-date>
;;; :TEMPORARY <boolean>
A pathname of NIL is treated specially and gives properties for all
;;; the files listed. The indicators for this "pathname" are:
;;; :SETTABLE-PROPERTIES <list-of-indicators, or just T>
;;; :BLOCK-SIZE <number>
;;; :PHYSICAL-VOLUME-FREE-BLOCKS alist of (<string> . <number>)
;;; :DISK-SPACE-DESCRIPTION <string>
;;; The currently defined OPTIONS are:
;;; :NOERROR - as with OPEN.
;;; :DELETED - also (rather than exclusively) list deleted files.
;;; :NO-EXTRA-INFO - only include enough information for listing directory as in DIRED.
;;; :SORTED - we want the directory sorted at least so that
;;; multiple versions of a file are consecutive in increasing version order.
(DEFUN DIRECTORY-LIST (FILENAME &REST OPTIONS)
"Return a listing of the directory specified in FILENAME, a pathname or string.
OPTIONS can include :NOERROR, :DELETED (mention deleted files),
:SORTED and :NO-EXTRA-INFO.
The value is an alist of elements (pathname . properties).
There is an element whose car is NIL. It describes the directory as a whole.
One of its properties is :PATHNAME, whose value is the directory's pathname."
(FORCE-USER-TO-LOGIN)
(SETQ FILENAME (MERGE-PATHNAME-DEFAULTS FILENAME NIL ':WILD ':WILD))
(SEND FILENAME ':DIRECTORY-LIST OPTIONS))
(DEFUN DIRECTORY-LIST-STREAM (FILENAME &REST OPTIONS)
"Return a stream which returns elements of a directory-list one by one.
The stream's operations are :ENTRY, to return the next element, and :CLOSE."
(FORCE-USER-TO-LOGIN)
(SETQ FILENAME (MERGE-PATHNAME-DEFAULTS FILENAME NIL ':WILD ':WILD))
(SEND FILENAME ':DIRECTORY-LIST-STREAM OPTIONS))
;;; These are the understood indicators
;;; Format is ((PARSER-FROM-STRING PRINTER TYPE-FOR-CHOOSE-VARIABLE-VALUES) . INDICATORS)
(DEFVAR *KNOWN-DIRECTORY-PROPERTIES*
'(((PARSE-DIRECTORY-BOOLEAN-PROPERTY PRIN1 :BOOLEAN)
. (:DELETED :DONT-DELETE :DONT-DUMP :DONT-REAP :DELETE-PROTECT :SUPERSEDE-PROTECT
:NOT-BACKED-UP :OFFLINE :TEMPORARY :CHARACTERS :DUMPED :DIRECTORY
;; Supported by LM
:QFASLP :PDP10 :MAY-BE-REAPED))
((SUBSTRING PRINC :STRING) . (:ACCOUNT :AUTHOR :LINK-TO :PHYSICAL-VOLUME :PROTECTION
:VOLUME-NAME :PACK-NUMBER :READER :DISK-SPACE-DESCRIPTION
:INCREMENTAL-DUMP-TAPE :COMPLETE-DUMP-TAPE))
((ZWEI:PARSE-NUMBER PRINT-DECIMAL-PROPERTY :NUMBER)
. (:BLOCK-SIZE :BYTE-SIZE :GENERATION-RETENTION-COUNT :LENGTH-IN-BLOCKS
:LENGTH-IN-BYTES :DEFAULT-GENERATION-RETENTION-COUNT))
((PARSE-DIRECTORY-DATE-PROPERTY PRINT-DIRECTORY-DATE-PROPERTY :DATE)
. (:CREATION-DATE :MODIFICATION-DATE))
((PARSE-DIRECTORY-DATE-PROPERTY PRINT-UNIVERSAL-TIME-OR-NEVER-FOR-DIRLIST :DATE-OR-NEVER)
. ( :REFERENCE-DATE :INCREMENTAL-DUMP-DATE :COMPLETE-DUMP-DATE :DATE-LAST-EXPUNGED
:EXPIRATION-DATE))
((PARSE-SETTABLE-PROPERTIES PRINT-SETTABLE-PROPERTIES)
. (:SETTABLE-PROPERTIES :LINK-TRANSPARENCIES :DEFAULT-LINK-TRANSPARENCIES))
((PARSE-DIRECTORY-FREE-SPACE PRINT-DIRECTORY-FREE-SPACE) . (:PHYSICAL-VOLUME-FREE-BLOCKS))
((TIME:PARSE-INTERVAL-OR-NEVER TIME:PRINT-INTERVAL-OR-NEVER :TIME-INTERVAL-OR-NEVER)
. (:AUTO-EXPUNGE-INTERVAL))
))
(DEFVAR *TRANSFORMED-DIRECTORY-PROPERTIES* NIL
"Fast access to directory properties for READ-DIRECTORY-STREAM-ENTRY.
Each element is a list (first-char . alist)
where alist's elements look like (propstring propsymbol parser printer cvv-type).")
(DEFUN TRANSFORM-DIRECTORY-PROPERTIES ()
(SETQ *TRANSFORMED-DIRECTORY-PROPERTIES* NIL)
(DOLIST (ELT *KNOWN-DIRECTORY-PROPERTIES*)
(DOLIST (PROP (CDR ELT))
(LET* ((HASH (AREF (GET-PNAME PROP) 0))
(HASHELT
(OR (ASSQ HASH *TRANSFORMED-DIRECTORY-PROPERTIES*)
(CAR (PUSH (CONS HASH NIL) *TRANSFORMED-DIRECTORY-PROPERTIES*)))))
(PUSH (LIST* (GET-PNAME PROP) PROP (CAR ELT)) (CDR HASHELT))))))
(TRANSFORM-DIRECTORY-PROPERTIES)
Read the text describing one element of a directory - list from STREAM .
;Default the pathname in it using DEFAULTING-PATHNAME, which should
;be the pathname of the directory being listed.
If this is the entry for NIL , which describes the whole directory ,
;then we append the directory pathname as the :PATHNAME property to this entry.
(DEFUN READ-DIRECTORY-STREAM-ENTRY (STREAM DEFAULTING-PATHNAME options &AUX PATH EOF IND FUN
(DEFAULT-FUN (SEND DEFAULTING-PATHNAME
':DIRECTORY-STREAM-DEFAULT-PARSER)))
;options is options to DIRECTORY-LIST. See below.
(MULTIPLE-VALUE (PATH EOF)
(SEND STREAM ':LINE-IN))
(IF EOF NIL
(IF (ZEROP (ARRAY-ACTIVE-LENGTH PATH))
(SETQ PATH NIL)
(MULTIPLE-VALUE-BIND (DEV DIR NAM TYP VER)
(SEND DEFAULTING-PATHNAME ':PARSE-NAMESTRING NIL PATH)
(SETQ PATH (MAKE-PATHNAME-INTERNAL
(PATHNAME-HOST DEFAULTING-PATHNAME)
(OR DEV (PATHNAME-DEVICE DEFAULTING-PATHNAME))
(OR DIR (PATHNAME-DIRECTORY DEFAULTING-PATHNAME))
NAM (OR TYP ':UNSPECIFIC) VER))))
;; This is a little hairy to try to avoid page faults when interning.
(LOOP AS LINE = (SEND STREAM ':LINE-IN)
AS LEN = (ARRAY-ACTIVE-LENGTH LINE)
UNTIL (ZEROP LEN)
AS I = (%STRING-SEARCH-CHAR #/SPACE LINE 0 LEN)
DO (LOOP NAMED FOO
FOR X IN (CDR (ASSQ (AREF LINE 0) *TRANSFORMED-DIRECTORY-PROPERTIES*))
WHEN (%STRING-EQUAL LINE 0 (CAR X) 0 I)
DO (RETURN (SETQ IND (CADR X) FUN (CADDR X)))
FINALLY (SETQ IND (INTERN (SUBSTRING LINE 0 I) SI:PKG-KEYWORD-PACKAGE)
FUN DEFAULT-FUN))
NCONC (LIST* IND (OR (NULL I) (SEND FUN LINE (1+ I))) NIL) INTO PLIST
this allows c - u m - x dired on " ai :* ; " to work !
(not (get-from-alternating-list plist :directory)))
(setq plist (list* :directory t plist)))
(RETURN (CONS PATH (IF PATH PLIST
(LIST* ':PATHNAME DEFAULTING-PATHNAME PLIST))))))))
;;; Nifty, handy function for adding new ones
(DEFUN PUSH-DIRECTORY-PROPERTY-ON-TYPE (TYPE PROP)
(LET ((X (OR (DOLIST (E *KNOWN-DIRECTORY-PROPERTIES*)
(IF (EQ (CADDAR E) TYPE) (RETURN E)))
(FERROR NIL "Unknown property type: ~A" TYPE))))
(OR (MEMQ TYPE (CDR X))
(PUSH PROP (CDR X))))
(TRANSFORM-DIRECTORY-PROPERTIES))
(DEFUN PARSE-RANDOM-SEXP (STRING START)
(LET ((*READ-BASE* 10.)
(*READTABLE* SI:INITIAL-READTABLE)
(*PACKAGE* SI:PKG-KEYWORD-PACKAGE))
(READ-FROM-STRING STRING NIL START)))
(DEFUN PRINT-RANDOM-SEXP (SEXP &OPTIONAL (STREAM *STANDARD-OUTPUT*))
(LET ((*PRINT-BASE* 10.)
(*NOPOINT T) (*PRINT-RADIX* NIL)
(*READTABLE* SI:INITIAL-READTABLE)
(*PACKAGE* SI:PKG-KEYWORD-PACKAGE))
(PRIN1 SEXP STREAM)))
Fast date parser for simple case of MM / DD / : MM : SS
(DEFUN PARSE-DIRECTORY-DATE-PROPERTY (STRING START &OPTIONAL END &AUX FLAG)
(OR END (SETQ END (ARRAY-ACTIVE-LENGTH STRING)))
addition to " protocol " of 10/3/85 : string consisting entirely of digits is
;; directly universal time in decimal, so read it in.
((NULL (STRING-SEARCH-NOT-SET "0123456789" STRING START END))
(LET ((*read-base* 10.)
(*print-base* 10.))
(READ-FROM-STRING STRING NIL START END)))
((NOT (FBOUNDP 'ENCODE-UNIVERSAL-TIME))
;; in cold load --- filesystem initialization fixes this up later.
NIL)
((AND (OR (= END (+ START 8))
(SETQ FLAG (= END (+ START 17.))))
(EQL (CHAR STRING (+ START 2)) #//)
(EQL (CHAR STRING (+ START 5)) #//)
(OR (NULL FLAG)
(AND (EQL (CHAR STRING (+ START 8)) #/SPACE)
(EQL (CHAR STRING (+ START 11.)) #/:)
(EQL (CHAR STRING (+ START 14.)) #/:))))
(FLET ((GET-TWO-DIGITS (START)
(+ (* (DIGIT-CHAR-P (CHAR STRING START)) 10.)
(DIGIT-CHAR-P (CHAR STRING (1+ START))))))
(LET* ((MONTH (GET-TWO-DIGITS START))
(DAY (GET-TWO-DIGITS (+ START 3)))
(YEAR (GET-TWO-DIGITS (+ START 6)))
(HOURS (IF FLAG (GET-TWO-DIGITS (+ START 9.)) 0))
(MINUTES (IF FLAG (GET-TWO-DIGITS (+ START 12.)) 0))
(SECONDS (IF FLAG (GET-TWO-DIGITS (+ START 15.)) 0)))
The file job is wo nt to give dates of the form 00/00/00 for things made by
;; ITS DSKDMP, e.g.. Avoid errors later.
(AND (PLUSP MONTH)
(ENCODE-UNIVERSAL-TIME SECONDS MINUTES HOURS DAY MONTH YEAR)))))
(T
;;Not in simple format, escape to full parser
;;>> This should signal a qfile-protocol-violation error!
(CONDITION-CASE ()
(TIME:PARSE-UNIVERSAL-TIME STRING START END)
(ERROR NIL)))))
(DEFUN PRINT-UNIVERSAL-TIME-OR-NEVER-FOR-DIRLIST (TIME STREAM)
(IF (NULL TIME) (PRINC "never" STREAM)
(TIME:PRINT-UNIVERSAL-TIME TIME STREAM NIL ':mm//dd//yy)))
Printer which always prints MM / DD / : MM : SS
* * * This is a needed bug fix . Strict time protocol says that the year must be given as two digits .
What happens in year 2000 ?
(DEFUN PRINT-DIRECTORY-DATE-PROPERTY (UT STREAM)
(if (numberp ut) ;"defensive"
(MULTIPLE-VALUE-BIND (SEC MIN HR DAY MON YR)
(TIME:DECODE-UNIVERSAL-TIME UT)
(FORMAT STREAM "~2,'0D//~2,'0D//~2,'0D ~2,'0D:~2,'0D:~2,'0D"
MON DAY (MOD YR 100.) HR MIN SEC))))
(DEFUN PARSE-DIRECTORY-BOOLEAN-PROPERTY (STRING START)
(LET ((TEM (READ-FROM-STRING STRING NIL START)))
(IF (EQ TEM ':NIL) NIL TEM)))
(DEFUN PARSE-SETTABLE-PROPERTIES (STRING START)
(IF (SETQ START (STRING-SEARCH-NOT-CHAR #/SPACE STRING START))
(DO ((I START (1+ J))
(J)
(LIST NIL))
(NIL)
(SETQ J (STRING-SEARCH-CHAR #/SPACE STRING I))
(PUSH (INTERN (STRING-UPCASE (SUBSTRING STRING I J)) "") LIST)
(OR J (RETURN (NREVERSE LIST))))
T)) ;Treat like blank line
(DEFUN PRINT-SETTABLE-PROPERTIES (PROPERTIES &OPTIONAL (*STANDARD-OUTPUT* *STANDARD-OUTPUT*))
(AND (LISTP PROPERTIES)
(DO ((TAIL PROPERTIES (CDR TAIL))) ((NULL TAIL))
(PRINC (CAR TAIL))
(IF (CDR TAIL) (TYO #/SPACE)))))
(DEFUN PARSE-DIRECTORY-FREE-SPACE (STRING START &AUX LIST)
(DO ((I START (1+ I))
(J)
(VOL))
(NIL)
(OR (SETQ J (STRING-SEARCH-CHAR #/: STRING I))
(RETURN))
(SETQ VOL (SUBSTRING STRING I J))
(SETQ I (STRING-SEARCH-CHAR #/, STRING (SETQ J (1+ J))))
(PUSH (CONS VOL (ZWEI:PARSE-NUMBER STRING J I)) LIST)
(OR I (RETURN)))
(NREVERSE LIST))
(DEFUN PRINT-DIRECTORY-FREE-SPACE (ALIST &OPTIONAL (*STANDARD-OUTPUT* *STANDARD-OUTPUT*))
(DO ((TAIL ALIST (CDR TAIL)))
((NULL TAIL))
(PRINC (CAAR TAIL))
(PRINC ":")
(PRINC (CDAR TAIL))
(IF (CDDR TAIL) (PRINC ","))))
(DEFUN PRINT-DECIMAL-PROPERTY (PROP STREAM)
(LET ((*PRINT-BASE* 10.)
(*NOPOINT T)
(*PRINT-RADIX* NIL)
(*READTABLE* SI:INITIAL-READTABLE))
(PRIN1 PROP STREAM)))
;;; List all directories w.r.t. the pathname. The only option currently defined
;;; is :NOERROR, which causes the function to return a string rather than an error.
;;; A successful return returns a plist, as in :DIRECTORY-LIST, of pathnames with
;;; one for each directory. Currently the only non-nil fields in these pathnames
;;; are host, directory, and device, but this may be changed later on by some options.
;;; Also, there are no properties defined yet.
First argument may be a host name for convenience
(DEFUN ALL-DIRECTORIES (&OPTIONAL (PATHNAME USER-LOGIN-MACHINE) &REST OPTIONS &AUX TEM)
"Return a list of pathnames describing all directories on a specified host.
The argument is either a host, a hostname, or a pathname or namestring
whose host is used. The only option is :NOERROR."
(FORCE-USER-TO-LOGIN)
(IF (AND (TYPEP PATHNAME '(OR STRING SI:HOST))
(SETQ TEM (GET-PATHNAME-HOST PATHNAME T)))
(SETQ PATHNAME (SEND (SAMPLE-PATHNAME TEM) ':NEW-PATHNAME
':DEVICE ':WILD ':DIRECTORY ':WILD))
(SETQ PATHNAME (MERGE-PATHNAME-DEFAULTS PATHNAME)))
(SEND PATHNAME ':ALL-DIRECTORIES OPTIONS))
;;; Default is to complain that it can't be done.
(DEFMETHOD (PATHNAME :ALL-DIRECTORIES) (OPTIONS)
(LET ((ERROR (MAKE-CONDITION 'UNKNOWN-OPERATION "Can't list all directories on file system of ~A."
SELF ':ALL-DIRECTORIES)))
(IF (MEMQ ':NOERROR OPTIONS) ERROR (SIGNAL ERROR))))
(DEFMETHOD (MEANINGFUL-ROOT-MIXIN :ALL-DIRECTORIES) (OPTIONS)
(LOOP FOR FILE IN (CDR (APPLY #'DIRECTORY-LIST
(SEND SELF ':NEW-PATHNAME
':DIRECTORY ':ROOT
':NAME ':WILD
':TYPE ':WILD
':VERSION ':WILD)
OPTIONS))
WHEN (GET FILE ':DIRECTORY)
COLLECT (NCONS (SEND (CAR FILE) ':PATHNAME-AS-DIRECTORY))))
(DEFUN COMPLETE-PATHNAME (DEFAULTS STRING TYPE VERSION &REST OPTIONS &AUX PATHNAME)
"Attempt to complete the filename STRING, returning the results.
DEFAULTS, TYPE and VERSION are as in MERGE-PATHNAME-DEFAULTS.
OPTIONS are :DELETED, :READ (file is for input), :WRITE (it's for output),
:OLD (only existing files allowed), :NEW-OK (new files are allowed too).
There are two values: a string which is the completion as far as possible,
and SUCCESS, which can be :OLD, :NEW or NIL.
:OLD says that the returned string names an existing file,
:NEW says that the returned string is no file but some completion was done,
NIL says that no completion was possible."
(DECLARE (VALUES STRING SUCCESS))
(FORCE-USER-TO-LOGIN)
(MULTIPLE-VALUE-BIND (HOST START END)
(PARSE-PATHNAME-FIND-COLON STRING)
(AND HOST (SETQ START (OR (STRING-SEARCH-NOT-CHAR #/SPACE STRING START END) END)
STRING (SUBSTRING STRING START END)))
(SETQ PATHNAME (DEFAULT-PATHNAME DEFAULTS HOST TYPE VERSION T)))
(SEND PATHNAME ':COMPLETE-STRING STRING OPTIONS))
(defun pathname-completion-list (defaults string type version &rest options
&AUX pathname whole-directory directory-pathname
directory-list)
"Returns a list of possible completions of string."
type version
(declare (values string success))
(force-user-to-login)
(setq pathname (fs:merge-pathname-defaults string defaults ':WILD ':WILD))
now get a pathname with just the first word of the name and a magic
;; character that signifies wild card match at end of name.
(let ((name (send pathname ':NAME)))
(if (or (null name) (equalp name "")
(eq ':WILD name))
(setq whole-directory T
directory-pathname
(send pathname ':NEW-PATHNAME ':NAME ':WILD ':VERSION ':WILD))
;; otherwise clip off whatever is necessary from the name
(let ((position (string-search-set '(#/SPACE #/. #/-) name)))
(if position (setq name (substring name 0 position))))
(setq name (string-append name "*"))
(let ((temp-pathname (fs:parse-pathname name (send pathname ':HOST))))
(setq directory-pathname (send pathname
':NEW-PATHNAME
':NAME (send temp-pathname ':NAME) ':VERSION ':WILD)))))
;; now get directory-list
(setq directory-list (send directory-pathname ':DIRECTORY-LIST options))
(if (errorp directory-list)
directory-list
(setq directory-list (cdr directory-list))
;; maybe do more completion
(if (null whole-directory)
(multiple-value-bind (NIL matching-subset)
(zwei:complete-string (send pathname ':NAME)
(LOOP FOR entry IN directory-list
AS pathname = (car entry)
AS name = (send pathname ':NAME)
COLLECT (list name pathname))
'(#/. #/- #/SPACE))
(setq directory-list
(LOOP FOR (pathname-name pathname) IN matching-subset
COLLECT pathname)))
(setq directory-list
(LOOP FOR entry IN directory-list
COLLECT (car entry))))
directory-list))
;;; Alter properties as returned by DIRECTORY-LIST. PROPERTIES is a
;;; PLIST with the same indicators as returned by that.
(DEFUN CHANGE-FILE-PROPERTIES (PATHNAME ERROR-P &REST PROPERTIES)
"Change some file properties of a file, specified as pathname or namestring.
The file properties are those that are returned by FILE-PROPERTIES.
PROPERTIES are the alternating properties and new values."
(FORCE-USER-TO-LOGIN)
(SETQ PATHNAME (MERGE-PATHNAME-DEFAULTS PATHNAME))
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ ERROR-P '(:RETRY :REPROMPT))
(PATHNAME FILE-ERROR)
(LEXPR-SEND PATHNAME ':CHANGE-PROPERTIES ERROR-P PROPERTIES)))
(DEFF CHANGE-PATHNAME-PROPERTIES 'CHANGE-FILE-PROPERTIES) ;Obsolete old name
;;; Find the properties, like those returned by DIRECTORY-LIST, of a single file.
;;; Returns a plist whose car is the truename and whose cdr is the properties.
(DEFUN FILE-PROPERTIES (PATHNAME &OPTIONAL (ERROR-P T))
"Return the property list of a file, specified as a pathname or namestring.
These properties are the same ones that appear in a directory-list.
The car of the value is the truename.
The second value is a list of properties whose values can be changed."
(DECLARE (VALUES PROPERTIES SETTABLE-PROPERTIES))
(FORCE-USER-TO-LOGIN)
(SETQ PATHNAME (MERGE-PATHNAME-DEFAULTS PATHNAME))
(MULTIPLE-VALUE-BIND (PLIST SETTABLE-PROPERTIES)
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ ERROR-P '(:RETRY :REPROMPT))
(PATHNAME FILE-ERROR)
(SEND PATHNAME ':PROPERTIES ERROR-P))
(OR SETTABLE-PROPERTIES
(IF (SEND PATHNAME ':OPERATION-HANDLED-P ':PROPERTY-SETTABLE-P)
(SETQ SETTABLE-PROPERTIES
(UNION (SEND PATHNAME ':DEFAULT-SETTABLE-PROPERTIES)
(LOOP FOR IND IN (CDR PLIST) BY 'CDDR
WHEN (SEND PATHNAME ':PROPERTY-SETTABLE-P IND)
COLLECT IND)))))
(VALUES PLIST SETTABLE-PROPERTIES)))
(DEFUN EXPUNGE-DIRECTORY (PATHNAME &REST OPTIONS &KEY (ERROR T))
"Expunge all deleted files in the directory specified in PATHNAME.
PATHNAME can be a pathname or a namestring."
(DECLARE (VALUES BLOCKS-FREED))
(FORCE-USER-TO-LOGIN)
;; avoid merge-pathname-defaults braindeath
(OR (SEND (SETQ PATHNAME (FS:PARSE-PATHNAME PATHNAME)) :NAME)
(SETQ PATHNAME (SEND PATHNAME :NEW-NAME :WILD)))
(SETQ PATHNAME (FS:MERGE-PATHNAME-DEFAULTS PATHNAME NIL :WILD :WILD))
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ ERROR '(:RETRY :REPROMPT))
(PATHNAME FILE-ERROR)
(LEXPR-SEND PATHNAME :EXPUNGE OPTIONS)))
(DEFMETHOD (PATHNAME :EXPUNGE) (&REST ARGS)
(LET ((ERROR (MAKE-CONDITION 'UNKNOWN-OPERATION "Can't expunge or undelete on file system of ~A."
SELF ':EXPUNGE))
(ERRORP (COND ((NULL ARGS) T)
((NULL (CDR ARGS))
(CAR ARGS))
(T (GET (LOCF ARGS) ':ERROR)))))
(IF ERRORP (SIGNAL ERROR) ERROR)))
(DEFUN REMOTE-CONNECT (PATHNAME &REST OPTIONS &KEY (ERROR T) ACCESS)
"Tell file servers to connect or access to a directory.
PATHNAME, either a pathname or a namestring, specifies both the host
and the device and directory to connect or access to."
ERROR ACCESS
(FORCE-USER-TO-LOGIN)
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ ERROR '(:RETRY :REPROMPT))
(PATHNAME FILE-ERROR)
(LEXPR-SEND (MERGE-PATHNAME-DEFAULTS PATHNAME NIL) ':REMOTE-CONNECT OPTIONS)))
(DEFMETHOD (PATHNAME :REMOTE-CONNECT) (&KEY ERROR ACCESS)
ACCESS
(LET ((CONDITION
(MAKE-CONDITION 'UNKNOWN-OPERATION "Can't do remote connect or access on file system of ~A."
SELF ':REMOTE-CONNECT)))
(IF ERROR (SIGNAL CONDITION) CONDITION)))
(DEFUN ENABLE-CAPABILITIES (HOST &REST CAPABILITIES)
"Tell file servers on HOST to enable some capabilities.
Defaults are according to operating system."
(FORCE-USER-TO-LOGIN)
(LEXPR-SEND (GET-PATHNAME-HOST HOST) ':ENABLE-CAPABILITIES CAPABILITIES))
(DEFUN DISABLE-CAPABILITIES (HOST &REST CAPABILITIES)
"Tell file servers on HOST to disable some capabilities.
Defaults are according to operating system."
(FORCE-USER-TO-LOGIN)
(LEXPR-SEND (GET-PATHNAME-HOST HOST) ':DISABLE-CAPABILITIES CAPABILITIES))
(DEFUN CREATE-DIRECTORY (PATHNAME &KEY (ERROR T) RECURSIVE)
"Create a directory specified in PATHNAME, either a pathname or a namestring.
RECURSIVE non-NIL says if this directory is supposed to be a subdirectory
of another directory which also fails to exist, create that one too, etc."
(FORCE-USER-TO-LOGIN)
(LET ((PN (MERGE-PATHNAME-DEFAULTS PATHNAME NIL)))
(CONDITION-CASE-IF RECURSIVE ()
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ ERROR '(:RETRY :REPROMPT))
(PATHNAME FILE-ERROR)
(SEND PN :CREATE-DIRECTORY :ERROR ERROR))
(DIRECTORY-NOT-FOUND
(CREATE-DIRECTORY (SEND PN :DIRECTORY-PATHNAME-AS-FILE) :RECURSIVE T :error error)
(CREATE-DIRECTORY PN :ERROR ERROR)))))
(DEFMETHOD (PATHNAME :CREATE-LINK) (LINK-TO &KEY (ERROR T))
(DECLARE (IGNORE LINK-TO))
(LET ((CONDITION
(MAKE-CONDITION 'UNKNOWN-OPERATION "Can't create links on file system of ~A."
SELF ':CREATE-LINK)))
(IF ERROR (SIGNAL CONDITION) CONDITION)))
(DEFMETHOD (PATHNAME :CREATE-DIRECTORY) (&KEY (ERROR T))
(LET ((CONDITION
(MAKE-CONDITION 'UNKNOWN-OPERATION "Can't create directory on file system of ~A."
SELF :CREATE-DIRECTORY)))
(IF ERROR (SIGNAL CONDITION) CONDITION)))
;;;; Handle File attribute lists
;;; If no :MODE property is in the file's -*- line, and the file type is on this
;;; list, then the corresponding :MODE property is put on the file's plist.
This helps losers who do n't have -*- lines get the right mode on TWENEX , etc .
(DEFCONST *FILE-TYPE-MODE-ALIST*
'((:LISP . :LISP)
(:TEXT . :TEXT)
(:MIDAS . :MIDAS)
(:DOC . :TEXT)
(:MSS . :SCRIBE)
(:PALX . :TEXT)
(:MAC . :MIDAS)
(:TASM . :MIDAS)
(:C . :PL1)
(:CLU . :PL1)
(:PL1 . :PL1)
(:scheme . :scheme))
"Alist mapping standard pathname type component strings into editor major mode name keywords.")
;;; New faster parser, uses :READ-INPUT-BUFFER, returns the new property list.
;;; Works for multiple-line plists.
;;; Beware of making streams do :LINE-INs on files which aren't really ASCII.
;;; :LINE-IN can lose rather badly on such files.
;;; PATHNAME may be NIL if you don't want any properties put on any pathname.
But it is better to call FILE - EXTRACT - ATTRIBUTE - LIST if you want that .
(DEFF READ-SYNTAX-PLIST 'READ-ATTRIBUTE-LIST)
(DEFF FILE-READ-PROPERTY-LIST 'READ-ATTRIBUTE-LIST)
(DEFF FILE-READ-ATTRIBUTE-LIST 'READ-ATTRIBUTE-LIST)
(DEFUN READ-ATTRIBUTE-LIST (PATHNAME STREAM &AUX PLIST)
"Return the attribute list read from STREAM, and put properties on PATHNAME.
STREAM can be reading either a text file or a QFASL file.
PATHNAME should be the generic pathname that was opened."
(SETQ PLIST (FILE-EXTRACT-ATTRIBUTE-LIST STREAM))
First remove any properties that we put on the last time we parsed
;; this file's plist, so that we update correctly if some property has been deleted.
(AND PATHNAME
(LET ((OLD-PLIST (SEND PATHNAME ':GET 'LAST-FILE-PLIST)))
(DO ((L OLD-PLIST (CDDR L))) ((NULL L))
(SEND PATHNAME ':REMPROP (CAR L)))))
;; Now put on the properties desired this time.
(AND PATHNAME
(DO ((L PLIST (CDDR L)))
((NULL L))
(SEND PATHNAME ':PUTPROP (SECOND L) (FIRST L))))
;; Record the entire plist, so we can update properly next time.
(AND PATHNAME
(SEND PATHNAME ':PUTPROP PLIST 'LAST-FILE-PLIST))
PLIST)
;Return the property list from a stream, but don't alter any pathname's plist.
(DEFF FILE-EXTRACT-PROPERTY-LIST 'EXTRACT-ATTRIBUTE-LIST)
(DEFF EXTRACT-PROPERTY-LIST 'EXTRACT-ATTRIBUTE-LIST)
(DEFF FILE-EXTRACT-ATTRIBUTE-LIST 'EXTRACT-ATTRIBUTE-LIST)
(DEFUN EXTRACT-ATTRIBUTE-LIST (STREAM &AUX WO PLIST PATH MODE ERROR)
"Return the attribute list read from STREAM.
STREAM can be reading either a text file or a QFASL file."
(declare (values plist error))
(SETQ WO (SEND STREAM ':WHICH-OPERATIONS))
(COND ((MEMQ ':SYNTAX-PLIST WO)
(SETQ PLIST (SEND STREAM ':SYNTAX-PLIST)))
((NOT (SEND STREAM ':CHARACTERS))
(SETQ PLIST (SI:QFASL-STREAM-PROPERTY-LIST STREAM)))
;; If the file supports :READ-INPUT-BUFFER, check for absence of a plist
;; without risk that :LINE-IN will read the whole file
;; if the file contains no Return characters.
((AND (MEMQ ':READ-INPUT-BUFFER WO)
(MULTIPLE-VALUE-BIND (BUFFER START END)
(SEND STREAM ':READ-INPUT-BUFFER)
(AND BUFFER
(NOT (STRING-SEARCH "-*-" BUFFER START END)))))
NIL)
;; If stream does not support :SET-POINTER, there is no hope
;; of parsing a plist, so give up on it.
((NOT (MEMQ ':SET-POINTER WO))
NIL)
(T (DO ((LINE) (EOF)) (NIL)
(MULTIPLE-VALUE (LINE EOF) (SEND STREAM ':LINE-IN NIL))
(COND ((NULL LINE)
(SEND STREAM ':SET-POINTER 0)
(RETURN NIL))
((STRING-SEARCH "-*-" LINE)
(SETQ LINE (FILE-GRAB-WHOLE-PROPERTY-LIST LINE STREAM))
(SEND STREAM ':SET-POINTER 0)
(SETF (VALUES PLIST ERROR) (FILE-PARSE-PROPERTY-LIST LINE))
(RETURN NIL))
((OR EOF (STRING-SEARCH-NOT-SET '(#/SPACE #/TAB) LINE))
(SEND STREAM ':SET-POINTER 0)
(RETURN NIL))))))
;;
;;From here on, infer properties where possible.
;;
;;Infer: Iff no MODE, try to get from pathname type
(AND (NOT (GETF PLIST ':MODE))
(MEMQ ':PATHNAME WO)
(SETQ PATH (SEND STREAM ':PATHNAME))
(SETQ MODE (CDR (ASSOC (SEND PATH ':TYPE) *FILE-TYPE-MODE-ALIST*)))
(PUTPROP (LOCF PLIST) MODE ':MODE))
Infer : Iff MODE or SYNTAX is CommonLISP or equivalent , set READTABLE
( this assumes ZL is still " traditional " and default ! )
(when (and (null (getf plist :readtable))
(or (member (getf plist :mode) '(:commonlisp :common-lisp))
(eq (getf plist :syntax) :CL)))
(putprop (locf plist) :CL :readtable))
;;
Finally return PLIST and any error from along the way .
;;
(VALUES PLIST ERROR))
;Given a line on which a file's property list starts,
;read through the file appending onto the line until we get to
;the end of the property list.
;So we return a string that contains the whole thing.
(DEFUN FILE-GRAB-WHOLE-PROPERTY-LIST (STARTING-LINE STREAM)
(DO ((START (+ 3 (STRING-SEARCH "-*-" STARTING-LINE)) 0)
(STRING STARTING-LINE (SEND STREAM ':LINE-IN))
(COUNT 0 (1+ COUNT))
(ACCUM (MAKE-ARRAY 0 ':TYPE ART-STRING ':FILL-POINTER 0)))
((= COUNT 100.)
(FORMAT *QUERY-IO* "~&The file ~A has an unterminated property list line."
(SEND STREAM ':PATHNAME))
"")
(SETQ ACCUM (STRING-NCONC ACCUM #/NEWLINE STRING))
(IF (STRING-SEARCH "-*-" STRING START)
(RETURN ACCUM))))
Copied from LAD : ; OPEN.LISP#208 on 2 - Oct-86 05:47:00
;;; This takes a string which probably has a property list in it, and returns the plist.
;;; If it has any trouble parsing, returns whatever plist it could find.
(DEFUN FILE-PARSE-PROPERTY-LIST (STRING &OPTIONAL (START 0) (END (LENGTH STRING))
&AUX PLIST ERROR
(*READ-BASE* 10.)
(*PACKAGE* SI:PKG-KEYWORD-PACKAGE)
(*READTABLE* SI:INITIAL-COMMON-LISP-READTABLE))
(AND STRING
(ARRAYP STRING)
(= (ARRAY-ELEMENT-SIZE STRING) 8)
;; Narrow down to the stuff between the -*-'s
(SETQ START (STRING-SEARCH "-*-" STRING START END))
(SETQ END (STRING-SEARCH "-*-" STRING (SETQ START (+ START 3)) END))
;; Now parse it.
(IF (NOT (%STRING-SEARCH-CHAR #/: STRING START END))
(SETQ PLIST (LIST ':MODE (READ-FROM-SUBSTRING STRING START END)))
(DO ((S START (1+ SEMI-IDX))
(COLON-IDX) (SEMI-IDX) (SYM) (ELEMENT NIL NIL) (DONE)
(WIN-THIS-TIME NIL NIL))
(NIL)
(OR (SETQ SEMI-IDX (%STRING-SEARCH-CHAR #/; STRING S END))
(SETQ DONE T SEMI-IDX END))
(OR (SETQ COLON-IDX (%STRING-SEARCH-CHAR #/: STRING S SEMI-IDX))
(RETURN NIL))
(IGNORE-ERRORS
(OR (SETQ SYM (READ-FROM-SUBSTRING STRING S COLON-IDX))
(RETURN NIL))
(IGNORE-ERRORS
(IF (%STRING-SEARCH-CHAR #/, STRING (SETQ S (1+ COLON-IDX)) SEMI-IDX)
(DO ((COMMA-IDX) (ELEMENT-DONE))
(NIL)
(OR (SETQ COMMA-IDX (%STRING-SEARCH-CHAR #/, STRING S SEMI-IDX))
(SETQ ELEMENT-DONE T COMMA-IDX SEMI-IDX))
(SETQ ELEMENT
(NCONC ELEMENT
(NCONS (LET ((TEM (READ-FROM-SUBSTRING STRING S COMMA-IDX)))
(setq tem (nsubst nil :nil tem))))))
(AND ELEMENT-DONE (RETURN NIL))
(SETQ S (1+ COMMA-IDX)))
(SETQ ELEMENT (LET ((TEM (READ-FROM-SUBSTRING STRING S SEMI-IDX)))
(setq tem (nsubst nil :nil tem)))))
(SETQ WIN-THIS-TIME T))
(UNLESS WIN-THIS-TIME
(SETQ ERROR T))
(AND DONE (RETURN NIL)))))
(VALUES PLIST ERROR))
(DEFUN READ-FROM-SUBSTRING (STRING &OPTIONAL (START 0) (END (LENGTH STRING)))
(READ-FROM-STRING STRING NIL START END))
(DEFF FILE-PROPERTY-BINDINGS 'FILE-ATTRIBUTE-BINDINGS)
(DEFUN (:SYNTAX FILE-ATTRIBUTE-BINDINGS) (IGNORE IGNORE VAL)
(VALUES (NCONS '*READTABLE*) (NCONS (SI:FIND-READTABLE-NAMED VAL :ERROR))))
(DEFUN FILE-ATTRIBUTE-BINDINGS (PATHNAME)
"Return bindings to be made according to the attribute list of PATHNAME.
READ-ATTRIBUTE-LIST should have been done previously on that pathname.
Returns two values, a list of special variables and a list of values to bind them to.
Use the two values in a PROGV if you READ expressions from the file."
(ATTRIBUTE-BINDINGS-FROM-LIST
(IF (LOCATIVEP PATHNAME) (CONTENTS PATHNAME) (SEND PATHNAME :PROPERTY-LIST))
PATHNAME))
(DEFUN ATTRIBUTE-BINDINGS-FROM-LIST (ATTLIST PATHNAME)
(DO ((ATTLIST ATTLIST (CDDR ATTLIST))
(VARS NIL)
(VALS NIL)
(BINDING-FUNCTION))
((NULL ATTLIST)
(VALUES VARS VALS))
(AND (SETQ BINDING-FUNCTION (GET (CAR ATTLIST) 'FILE-ATTRIBUTE-BINDINGS))
(MULTIPLE-VALUE-BIND (VARS1 VALS1)
(FUNCALL BINDING-FUNCTION PATHNAME (CAR ATTLIST) (CADR ATTLIST))
(SETQ VARS (NCONC VARS1 VARS)
VALS (NCONC VALS1 VALS))))))
(DEFUN EXTRACT-ATTRIBUTE-BINDINGS (STREAM)
"Return a list of variables and values corresponding to STREAM's attribute list.
Useful for arguments to the PROGV special form."
(ATTRIBUTE-BINDINGS-FROM-LIST
(EXTRACT-ATTRIBUTE-LIST STREAM)
(OR (SEND STREAM ':SEND-IF-HANDLES ':TRUENAME) ':NO-PATHNAME))) ; Best one can do
(DEFUN (:PACKAGE FILE-ATTRIBUTE-BINDINGS) (IGNORE IGNORE PKG)
(VALUES (NCONS '*PACKAGE*) (NCONS (PKG-FIND-PACKAGE PKG :ERROR *package*))))
(defun (:compile-in-roots file-attribute-bindings) (ignore ignore roots-to-compile-in)
(values (ncons 'si:roots-to-compile-in)
(ncons roots-to-compile-in)))
(DEFUN (:BASE FILE-ATTRIBUTE-BINDINGS) (FILE IGNORE BSE)
(UNLESS (TYPEP BSE '(INTEGER 1 36.))
(FERROR 'INVALID-FILE-ATTRIBUTE "File ~A has an illegal -*- BASE:~*~S -*-"
FILE ':BASE BSE))
(VALUES (LIST* '*READ-BASE* '*PRINT-BASE* NIL) (LIST* BSE BSE NIL)))
(DEFUN (:COLD-LOAD FILE-ATTRIBUTE-BINDINGS) (IGNORE IGNORE FLAG)
(VALUES (NCONS 'SI:FILE-IN-COLD-LOAD) (NCONS FLAG)))
;;; So that functions can tell if they are being loaded out of, or compiled in, a patch file
(DEFVAR-RESETTABLE THIS-IS-A-PATCH-FILE NIL NIL
"Non-NIL while loading a patch file.")
(DEFUN (:PATCH-FILE FILE-ATTRIBUTE-BINDINGS) (IGNORE IGNORE VAL)
(VALUES (NCONS 'THIS-IS-A-PATCH-FILE) (NCONS VAL)))
( DEFUN (: COMMON - LISP FILE - ATTRIBUTE - BINDINGS ) ( IGNORE IGNORE )
; (VALUES (LIST* '*READTABLE* 'SI:*READER-SYMBOL-SUBSTITUTIONS*
' SI : INTERPRETER - FUNCTION - ENVIRONMENT ' * NOPOINT
; NIL)
; (LIST* (IF VAL SI:COMMON-LISP-READTABLE SI:STANDARD-READTABLE)
; (IF VAL SI:*COMMON-LISP-SYMBOL-SUBSTITUTIONS* NIL)
; NIL T
; NIL)))
(DEFUN (:READTABLE FILE-ATTRIBUTE-BINDINGS) (IGNORE IGNORE VAL)
(VALUES (NCONS '*READTABLE*) (NCONS (SI:FIND-READTABLE-NAMED VAL :ERROR))))
(DEFUN (:FONTS FILE-ATTRIBUTE-BINDINGS) (IGNORE IGNORE IGNORE)
(VALUES (NCONS 'SI:READ-DISCARD-FONT-CHANGES) (NCONS T)))
(DEFVAR *NAMED-READER-ALIST* '((:T ZL:READ)(NIL ZL:READ))
"An alist of (:keyword <function>) for names of readers in the file mode line
Note these take args like ZL:READ")
(DEFUN (:READ FILE-ATTRIBUTE-BINDINGS) (FILE IGNORE VAL)
(VALUES (NCONS 'SI:*READFILE-READ-FUNCTION*)
(NCONS (OR (CADR (ASSQ VAL *NAMED-READER-ALIST*))
(FERROR 'INVALID-FILE-ATTRIBUTE "File ~A has an illegal -*- READ:~*~S -*-"
FILE :READ VAL)))))
This returns the -*- properties for a ascii file , the qfasl properties for a qfasl file
(DEFF PATHNAME-SYNTAX-PLIST 'FILE-ATTRIBUTE-LIST)
(DEFF PATHNAME-ATTRIBUTE-LIST 'FILE-ATTRIBUTE-LIST)
(DEFF FILE-PROPERTY-LIST 'FILE-ATTRIBUTE-LIST)
(DEFUN FILE-ATTRIBUTE-LIST (PATHNAME)
"Return the attribute list for the file specified by PATHNAME, a pathname or namestring."
(WITH-OPEN-FILE (STREAM PATHNAME ':CHARACTERS ':DEFAULT)
(COND ((SEND STREAM ':SEND-IF-HANDLES ':FILE-PLIST))
((SEND STREAM ':CHARACTERS)
(EXTRACT-ATTRIBUTE-LIST STREAM))
(T
(SI:QFASL-STREAM-PROPERTY-LIST STREAM)))))
(DEFVAR LOAD-PATHNAME-DEFAULTS :UNBOUND
"Now the same as *default-pathname-defaults*
Used to be used as the pathname-defaults list for LOAD, COMPILE-FILE, etc.")
(FORWARD-VALUE-CELL 'LOAD-PATHNAME-DEFAULTS '*DEFAULT-PATHNAME-DEFAULTS*)
(DEFVAR *LOAD-VERBOSE* T
"Non-NIL means LOAD can print a message saying what it is loading.
Can be overridden by the :VERBOSE keyword when LOAD is called.")
(DEFVAR *LOAD-SET-DEFAULT-PATHNAME* T
"Non-NIL means LOAD sets the default pathname to the name of the file loaded.
Can be overridden by the :SET-DEFAULT-PATHNAME keyword when LOAD is called.")
in sys ; qfasl
Copied from LAD : ; OPEN.LISP#208 on 2 - Oct-86 05:47:02
(DEFUN LOAD (FILE &REST KEY-OR-POSITIONAL-ARGS)
"Load the specified text file or QFASL file or input stream.
If the specified filename has no type field, we try QFASL and then LISP and then INIT.
Regardless of the filename type, we can tell QFASL files from text files.
if missing or NIL ,
the package specified by the file's attribute list is used.
VERBOSE non-NIL says it's ok to print a message saying what is being loaded.
Default comes from *LOAD-VERBOSE*, normally T.
SET-DEFAULT-PATHNAME non-NIL says set the default pathname for LOAD
to the name of this file. Default from *LOAD-SET-DEFAULT-PATHNAME*, normally T.
IF-DOES-NOT-EXIST NIL says just return NIL for file-not-found. Default T.
In all other cases the value is the truename of the loaded file, or T.
PRINT non-NIL says print all forms loaded."
(DECLARE (ARGLIST FILE &KEY PACKAGE
(VERBOSE *LOAD-VERBOSE*)
(SET-DEFAULT-PATHNAME *LOAD-SET-DEFAULT-PATHNAME*)
(IF-DOES-NOT-EXIST T)
PRINT))
;;This used to be enforced by SI:LOAD-PATCH-FILE in a horrible kludge.
;;Now, it is merely a recommendation.
(when fs:this-is-a-patch-file
(cerror "Proceed to LOAD ~S anyway."
"The use of LOAD in a patch file is not recommended."
file))
(IF (AND (CAR KEY-OR-POSITIONAL-ARGS)
(MEMQ (CAR KEY-OR-POSITIONAL-ARGS)
'(:PACKAGE :PRINT :IF-DOES-NOT-EXIST :SET-DEFAULT-PATHNAME :VERBOSE)))
(LET ((SI::PRINT-LOADED-FORMS (GETF KEY-OR-POSITIONAL-ARGS ':PRINT)))
(LOAD-1 FILE
(GETF KEY-OR-POSITIONAL-ARGS ':PACKAGE)
(NOT (GETF KEY-OR-POSITIONAL-ARGS ':IF-DOES-NOT-EXIST T))
(NOT (GETF KEY-OR-POSITIONAL-ARGS ':SET-DEFAULT-PATHNAME
*LOAD-SET-DEFAULT-PATHNAME*))
(NOT (GETF KEY-OR-POSITIONAL-ARGS ':VERBOSE *LOAD-VERBOSE*))))
(APPLY #'LOAD-1 FILE KEY-OR-POSITIONAL-ARGS)))
Copied from LAD : ; OPEN.LISP#208 on 2 - Oct-86 05:47:03
(DEFUN LOAD-1 (FILE &OPTIONAL PKG NONEXISTENT-OK-FLAG DONT-SET-DEFAULT-P NO-MSG-P)
(IF (STREAMP FILE)
(PROGN
;; Set the defaults from the pathname we finally opened
(OR DONT-SET-DEFAULT-P
(SET-DEFAULT-PATHNAME (SEND FILE :PATHNAME) LOAD-PATHNAME-DEFAULTS))
(CATCH-ERROR-RESTART (EH:DEBUGGER-CONDITION "Give up on loading ~A."
(SEND FILE :PATHNAME))
(ERROR-RESTART (EH:DEBUGGER-CONDITION "Retry loading ~A." (SEND FILE :PATHNAME))
;; If the file was a character file, read it, else try to fasload it.
(FUNCALL (IF (SEND FILE :CHARACTERS)
#'SI::READFILE-INTERNAL #'SI::FASLOAD-INTERNAL)
FILE PKG NO-MSG-P)
(OR (SEND FILE :SEND-IF-HANDLES :TRUENAME) T))))
(LET ((PATHNAME (PARSE-PATHNAME FILE)))
(CATCH-ERROR-RESTART (EH:DEBUGGER-CONDITION "Give up on loading ~A." PATHNAME)
(ERROR-RESTART (EH:DEBUGGER-CONDITION "Retry loading ~A." PATHNAME)
;; Broken off from due to hairy macrology exceeding frame size!
(FLET ((KLUDGE ()
(CONDITION-CASE-IF NONEXISTENT-OK-FLAG ()
(WITH-OPEN-FILE-SEARCH
(STREAM ('LOAD LOAD-PATHNAME-DEFAULTS
(NOT NONEXISTENT-OK-FLAG))
(VALUES
(LIST (SI:PATHNAME-DEFAULT-BINARY-FILE-TYPE
PATHNAME)
:LISP :INIT)
PATHNAME)
:CHARACTERS :DEFAULT)
;; Set the defaults from the pathname we finally opened
(OR DONT-SET-DEFAULT-P
(SET-DEFAULT-PATHNAME (SEND STREAM :PATHNAME)
LOAD-PATHNAME-DEFAULTS))
;; If the file was a character file, read it, else try to fasload it.
(FUNCALL (IF (SEND STREAM :CHARACTERS)
#'SI::READFILE-INTERNAL #'SI::FASLOAD-INTERNAL)
STREAM PKG NO-MSG-P)
(SEND STREAM :TRUENAME))
(MULTIPLE-FILE-NOT-FOUND
NIL))))
(KLUDGE)))))))
Avoid lossage in LOAD-1 before this function is loaded from MAKSYS .
(IF (NOT (FBOUNDP 'SI:PATHNAME-DEFAULT-BINARY-FILE-TYPE))
(FSET 'SI:PATHNAME-DEFAULT-BINARY-FILE-TYPE
'(LAMBDA (IGNORE) ':QFASL)))
(DEFUN READFILE (FILE-NAME &OPTIONAL PKG NO-MSG-P)
"Read and evaluate the expressions from a text file.
if it is NIL ,
the file's attribute list specifies the package.
NO-MSG-P suppresses the message saying that a file is being loaded."
(WITH-OPEN-STREAM (STREAM (SEND (MERGE-PATHNAME-DEFAULTS
FILE-NAME LOAD-PATHNAME-DEFAULTS NIL)
:OPEN-CANONICAL-DEFAULT-TYPE :LISP
:ERROR :REPROMPT))
(SET-DEFAULT-PATHNAME (SEND STREAM :PATHNAME) LOAD-PATHNAME-DEFAULTS)
(SI::READFILE-INTERNAL STREAM PKG NO-MSG-P)))
| null | https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/io/file/open.lisp | lisp | Package : FILE - SYSTEM ; Base:8 ; : ZL -*-
Global interface functions, and random file stuff
Unimplemented-option
Subclasses of FILE-OPERATION-FAILURE.
ACCESS-ERROR means some kind of protection failure.
CREATION-FAILUREs
Should have property :NEW-PATHNAME.
This variable is to make DIRED have a guess at what is losing, it should work better
somehow.
or a list of options (a single arg), as an alternative to
keywords and values. These option names can be in any package.
Possible keywords and values include the following:
:OUTPUT
NIL This is a probe opening,
no data is transfered.
:CHARACTERS boolean T T if file is textual data.
:ERROR boolean T An error is signaled if T.
System-dependent fixed value for
text files.
fixnum
:INHIBIT-LINKS boolean NIL
:DELETED boolean NIL
:TEMPORARY boolean NIL
:PRESERVE-DATES boolean NIL Do not update reference or
modification dates.
:LINK
:LINK-TO pathname Creates a link when used with
:LINK flavor.
:ESTIMATED-SIZE NIL NIL
fixnum (number of bytes)
:NEW-FILE boolean T iff output T means ok to create new file.
:NEW-VERSION boolean NEW-FILE NIL says version = NEWEST
finds newest existing version.
NIL or :REPLACE Overwrite the file when closed.
:RENAME Rename old file
:RENAME-AND-DELETE Same, but delete when closed.
:NEW-VERSION If version is a number and there
is an old file, create new version.
:PHYSICAL-VOLUME NIL NIL
string Where to put file.
string specify this.
:INCREMENTAL-UPDATE boolean NIL Attempt to save recoverable data
more often.
OPEN.LISP#208 on 2 - Oct-86 05:46:47
handlers are invoked if they exist
No args is good args
Old Syntax.
Because we don't want to send meaningless keywords to file systems
which don't support them, and we don't want to cons...
Worst case
D-RETURN
Otherwise, will use only the specified type,
so the elements of TYPE-LIST matter only in how many they are,
Not a stream
Handle special file query stuff. Each of the file operations expects
the query optional argument to be a format style function. The result
of calling the query function is a boolean, and by using this particular
function with *FILE-QUERY-FLAG* closed over it, it is possible to proceed too.
:PROCEED == asked the user, got P response.
:NEVER-ASKED == didn't ask the user.
a logical assumption
make you the new file's author.
Not a stream
Decide whether to copy as binary file.
Either do as told, guess from file byte size or type, or ask the user.
At this point we really need to refer to the file's property list,
OPEN.LISP#208 on 2 - Oct-86 05:46:52
OPEN.LISP#208 on 2 - Oct-86 05:46:53
this isn't the right place for this, but its not clear where it should go
&optional defaults
Just in case
Type username or username@host ~<~%~:;(host defaults to ~A)~>~>
follow by <space>T : ~>"
All ITS's have the same set of unames, so record as ITS rather than the host.
Must be a host object
brand s name
loginname<space>password: ~>")
quoting character.
allow spaces in passwords
make sure we have room for extra element
Used by MAKE-SYSTEM for fast INFO access
Old name for compatibility
Directory stuff
OPEN.LISP#208 on 2 - Oct-86 05:46:55
This is the primary user interface to the directory listing
of these lists is (PATHNAME . PLIST). The currently defined indicators
:ACCOUNT <string>
:AUTHOR <string>
:BLOCK-SIZE <number>
:CREATION-DATE <universal-date>
:DELETED <boolean>
:DONT-DELETE <boolean>
:DONT-DUMP <boolean>
:DONT-REAP <boolean>
:GENERATION-RETENTION-COUNT <number>
:LENGTH-IN-BLOCKS <number>
:LENGTH-IN-BYTES <number>
:LINK-TO <string>
:OFFLINE <boolean>
:PHYSICAL-VOLUME <string>
:PROTECTION <string>
:READER <string>
:REFERENCE-DATE <universal-date>
:TEMPORARY <boolean>
the files listed. The indicators for this "pathname" are:
:SETTABLE-PROPERTIES <list-of-indicators, or just T>
:BLOCK-SIZE <number>
:PHYSICAL-VOLUME-FREE-BLOCKS alist of (<string> . <number>)
:DISK-SPACE-DESCRIPTION <string>
The currently defined OPTIONS are:
:NOERROR - as with OPEN.
:DELETED - also (rather than exclusively) list deleted files.
:NO-EXTRA-INFO - only include enough information for listing directory as in DIRED.
:SORTED - we want the directory sorted at least so that
multiple versions of a file are consecutive in increasing version order.
These are the understood indicators
Format is ((PARSER-FROM-STRING PRINTER TYPE-FOR-CHOOSE-VARIABLE-VALUES) . INDICATORS)
Supported by LM
Default the pathname in it using DEFAULTING-PATHNAME, which should
be the pathname of the directory being listed.
then we append the directory pathname as the :PATHNAME property to this entry.
options is options to DIRECTORY-LIST. See below.
This is a little hairy to try to avoid page faults when interning.
Nifty, handy function for adding new ones
directly universal time in decimal, so read it in.
in cold load --- filesystem initialization fixes this up later.
ITS DSKDMP, e.g.. Avoid errors later.
Not in simple format, escape to full parser
>> This should signal a qfile-protocol-violation error!
"defensive"
Treat like blank line
List all directories w.r.t. the pathname. The only option currently defined
is :NOERROR, which causes the function to return a string rather than an error.
A successful return returns a plist, as in :DIRECTORY-LIST, of pathnames with
one for each directory. Currently the only non-nil fields in these pathnames
are host, directory, and device, but this may be changed later on by some options.
Also, there are no properties defined yet.
Default is to complain that it can't be done.
character that signifies wild card match at end of name.
otherwise clip off whatever is necessary from the name
now get directory-list
maybe do more completion
Alter properties as returned by DIRECTORY-LIST. PROPERTIES is a
PLIST with the same indicators as returned by that.
Obsolete old name
Find the properties, like those returned by DIRECTORY-LIST, of a single file.
Returns a plist whose car is the truename and whose cdr is the properties.
avoid merge-pathname-defaults braindeath
Handle File attribute lists
If no :MODE property is in the file's -*- line, and the file type is on this
list, then the corresponding :MODE property is put on the file's plist.
New faster parser, uses :READ-INPUT-BUFFER, returns the new property list.
Works for multiple-line plists.
Beware of making streams do :LINE-INs on files which aren't really ASCII.
:LINE-IN can lose rather badly on such files.
PATHNAME may be NIL if you don't want any properties put on any pathname.
this file's plist, so that we update correctly if some property has been deleted.
Now put on the properties desired this time.
Record the entire plist, so we can update properly next time.
Return the property list from a stream, but don't alter any pathname's plist.
If the file supports :READ-INPUT-BUFFER, check for absence of a plist
without risk that :LINE-IN will read the whole file
if the file contains no Return characters.
If stream does not support :SET-POINTER, there is no hope
of parsing a plist, so give up on it.
From here on, infer properties where possible.
Infer: Iff no MODE, try to get from pathname type
Given a line on which a file's property list starts,
read through the file appending onto the line until we get to
the end of the property list.
So we return a string that contains the whole thing.
OPEN.LISP#208 on 2 - Oct-86 05:47:00
This takes a string which probably has a property list in it, and returns the plist.
If it has any trouble parsing, returns whatever plist it could find.
Narrow down to the stuff between the -*-'s
Now parse it.
STRING S END))
Best one can do
So that functions can tell if they are being loaded out of, or compiled in, a patch file
(VALUES (LIST* '*READTABLE* 'SI:*READER-SYMBOL-SUBSTITUTIONS*
NIL)
(LIST* (IF VAL SI:COMMON-LISP-READTABLE SI:STANDARD-READTABLE)
(IF VAL SI:*COMMON-LISP-SYMBOL-SUBSTITUTIONS* NIL)
NIL T
NIL)))
qfasl
OPEN.LISP#208 on 2 - Oct-86 05:47:02
This used to be enforced by SI:LOAD-PATCH-FILE in a horrible kludge.
Now, it is merely a recommendation.
OPEN.LISP#208 on 2 - Oct-86 05:47:03
Set the defaults from the pathname we finally opened
If the file was a character file, read it, else try to fasload it.
Broken off from due to hairy macrology exceeding frame size!
Set the defaults from the pathname we finally opened
If the file was a character file, read it, else try to fasload it. |
First define the error flavors and signal names used by all file errors .
(DEFFLAVOR FILE-ERROR (PATHNAME OPERATION) (NO-ACTION-MIXIN ERROR)
:ABSTRACT-FLAVOR
:GETTABLE-INSTANCE-VARIABLES
:INITTABLE-INSTANCE-VARIABLES)
(DEFMETHOD (FILE-ERROR :AFTER :INIT) (IGNORE)
(SETQ PATHNAME (GETF SI:PROPERTY-LIST ':PATHNAME))
(OR (VARIABLE-BOUNDP OPERATION)
(SETQ OPERATION (GETF SI:PROPERTY-LIST ':OPERATION))))
(DEFMETHOD (FILE-ERROR :SET-FORMAT-ARGS) (NEW-ARGS)
(SETQ EH:FORMAT-ARGS NEW-ARGS))
(DEFMETHOD (FILE-ERROR :CASE :PROCEED-ASKING-USER :RETRY-FILE-OPERATION)
(CONTINUATION IGNORE)
"Proceeds, trying the file operation again."
(FUNCALL CONTINUATION ':RETRY-FILE-OPERATION))
(DEFMETHOD (FILE-ERROR :CASE :PROCEED-ASKING-USER :NEW-PATHNAME)
(CONTINUATION READ-OBJECT-FUNCTION)
"Proceeds, reading a new filename and using that instead."
(FUNCALL CONTINUATION ':NEW-PATHNAME
(FUNCALL READ-OBJECT-FUNCTION
`(:PATHNAME :DEFAULTS ,PATHNAME)
"Pathname to use instead: (default ~A) "
PATHNAME)))
(DEFFLAVOR FILE-REQUEST-FAILURE () (FILE-ERROR))
(DEFPROP DAT DATA-ERROR FILE-ERROR)
(DEFPROP DATA-ERROR DAT FILE-ERROR)
(DEFSIGNAL DATA-ERROR FILE-REQUEST-FAILURE (PATHNAME OPERATION)
"Inconsistent data found in the file system.")
(DEFPROP HNA HOST-NOT-AVAILABLE FILE-ERROR)
(DEFPROP HOST-NOT-AVAILABLE HNA FILE-ERROR)
(DEFSIGNAL HOST-NOT-AVAILABLE FILE-REQUEST-FAILURE (PATHNAME OPERATION)
"A file system is refusing to listen to requests.")
(DEFPROP NFS NO-FILE-SYSTEM FILE-ERROR)
(DEFPROP NO-FILE-SYSTEM NFS FILE-ERROR)
(DEFSIGNAL NO-FILE-SYSTEM FILE-REQUEST-FAILURE (PATHNAME OPERATION)
"The file system does not seem to exist.")
(DEFSIGNAL NETWORK-LOSSAGE FILE-REQUEST-FAILURE (PATHNAME OPERATION)
"Misc. network problems during file accessing.
In particular, failure to open data connection.")
(DEFPROP NER NOT-ENOUGH-RESOURCES FILE-ERROR)
(DEFPROP NOT-ENOUGH-RESOURCES NER FILE-ERROR)
(DEFSIGNAL NOT-ENOUGH-RESOURCES FILE-REQUEST-FAILURE (PATHNAME OPERATION)
"Shortage of resources (network or file server) to transmit operation.
This is if the file server itself says it hasn't got enough resources.")
(DEFPROP UOP UNKNOWN-OPERATION FILE-ERROR)
(DEFPROP UNKNOWN-OPERATION UOP FILE-ERROR)
(DEFPROP UKC UNKNOWN-OPERATION FILE-ERROR)
(DEFSIGNAL UNKNOWN-OPERATION FILE-REQUEST-FAILURE (PATHNAME OPERATION)
"OPERATION is not supported on the particular file system used.")
(DEFPROP LIP LOGIN-PROBLEMS FILE-ERROR)
(DEFPROP LOGIN-PROBLEMS LIP FILE-ERROR)
(DEFSIGNAL LOGIN-PROBLEMS FILE-REQUEST-FAILURE ()
"Some sort of failure to log in.")
(DEFPROP UNK UNKNOWN-USER FILE-ERROR)
(DEFPROP UNKNOWN-USER UNK FILE-ERROR)
(DEFSIGNAL UNKNOWN-USER
(FILE-REQUEST-FAILURE LOGIN-PROBLEMS CORRECTABLE-LOGIN-PROBLEMS UNKNOWN-USER)
()
"USER is not a known login-name at HOST.")
(DEFPROP IP? INVALID-PASSWORD FILE-ERROR)
(DEFPROP INVALID-PASSWORD IP? FILE-ERROR)
(DEFSIGNAL INVALID-PASSWORD (FILE-REQUEST-FAILURE LOGIN-PROBLEMS
CORRECTABLE-LOGIN-PROBLEMS INVALID-PASSWORD)
()
"PASSWORD is not USER's password at HOST.")
(DEFPROP NLI NOT-LOGGED-IN FILE-ERROR)
(DEFPROP NOT-LOGGED-IN NLI FILE-ERROR)
(DEFSIGNAL NOT-LOGGED-IN (FILE-REQUEST-FAILURE NOT-LOGGED-IN)
(PATHNAME OPERATION)
"The file server said you were not logged in when the Lispm thought you should be.")
(DEFFLAVOR FILE-OPERATION-FAILURE () (FILE-ERROR)
(:DOCUMENTATION "The file system understood an operation but decided it was erroneous."))
(DEFMETHOD (FILE-OPERATION-FAILURE :CASE :PROCEED-ASKING-USER :DIRED) (&REST IGNORE)
"Runs DIRED, then returns to the debugger when you type Control-Z."
(DIRED (SEND (SEND SELF :PATHNAME) :NEW-PATHNAME
:NAME :WILD :TYPE :WILD :VERSION :WILD))
NIL)
(DEFMETHOD (FILE-OPERATION-FAILURE :CASE :PROCEED-ASKING-USER :CLEAN-DIRECTORY) (&REST IGNORE)
"Calls (ZWEI:CLEAN-DIRECTORY), then returns to debugger."
(ZWEI:CLEAN-DIRECTORY (SEND (SEND SELF :PATHNAME) :NEW-PATHNAME
:NAME :WILD :TYPE :WILD :VERSION :WILD))
NIL)
(DEFMETHOD (FILE-OPERATION-FAILURE :CASE :PROCEED-ASKING-USER :EXPUNGE-DIRECTORY) (&REST IGNORE)
"Expunges the directory, then returns to debugger."
(EXPUNGE-DIRECTORY (SEND (SEND SELF ':PATHNAME) ':NEW-PATHNAME
':NAME ':WILD ':TYPE ':WILD ':VERSION ':WILD))
NIL)
(DEFSIGNAL FILE-OPERATION-FAILURE-1 FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"Unrecognized file error codes signal this.")
(DEFSIGNAL FILE-OPEN-FOR-OUTPUT FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"How is this different from FILE-LOCKED?")
(DEFPROP LCK FILE-LOCKED FILE-ERROR)
(DEFPROP FILE-LOCKED LCK FILE-ERROR)
(DEFSIGNAL FILE-LOCKED FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"File cannot be accessed because someone else is using it.")
(DEFPROP CIR CIRCULAR-LINK FILE-ERROR)
(DEFPROP CIRCULAR-LINK CIR FILE-ERROR)
(DEFSIGNAL CIRCULAR-LINK FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"A link pointed to a link which pointed to a link ... too deeply.")
(DEFPROP UOO UNIMPLEMENTED-OPTION FILE-ERROR)
(DEFPROP UNIMPLEMENTED-OPTION UOO FILE-ERROR)
(DEFSIGNAL UNIMPLEMENTED-OPTION FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"Specified some option this file system doesn't understand.")
(DEFPROP IBS INVALID-BYTE-SIZE FILE-ERROR)
(DEFPROP INVALID-BYTE-SIZE IBS FILE-ERROR)
(DEFSIGNAL INVALID-BYTE-SIZE (FILE-OPERATION-FAILURE UNIMPLEMENTED-OPTION INVALID-BYTE-SIZE)
(PATHNAME OPERATION)
"Specified a byte size that the file system cannot handle.")
(DEFPROP ICO INCONSISTENT-OPTIONS FILE-ERROR)
(DEFPROP INCONSISTENT-OPTIONS ICO FILE-ERROR)
(DEFSIGNAL INCONSISTENT-OPTIONS FILE-OPERATION-FAILURE
(PATHNAME OPERATION)
"Specified a byte size that the file system cannot handle.")
(DEFFLAVOR NO-MORE-ROOM-ERROR () (FILE-OPERATION-FAILURE))
(DEFMETHOD (NO-MORE-ROOM-ERROR :USER-PROCEED-TYPES) (REAL-PROCEED-TYPES)
(APPEND (INTERSECTION '(:NO-ACTION :RETRY-FILE-OPERATION) REAL-PROCEED-TYPES)
'(:DIRED :CLEAN-DIRECTORY :expunge-directory)
(REM-IF #'(LAMBDA (ELT)
(MEMQ ELT '(:NO-ACTION :RETRY-FILE-OPERATION :DIRED :CLEAN-DIRECTORY :expunge-directory)))
REAL-PROCEED-TYPES)))
(DEFPROP NMR NO-MORE-ROOM FILE-ERROR)
(DEFPROP NO-MORE-ROOM NMR FILE-ERROR)
(DEFSIGNAL NO-MORE-ROOM NO-MORE-ROOM-ERROR (PATHNAME OPERATION)
"Out of resources within the file system.")
(DEFPROP FOR FILEPOS-OUT-OF-RANGE FILE-ERROR)
(DEFPROP FILEPOS-OUT-OF-RANGE FOR FILE-ERROR)
(DEFSIGNAL FILEPOS-OUT-OF-RANGE FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"Access pointer set to bad value, outside 0 to length of file.")
(DEFPROP NAV NOT-AVAILABLE FILE-ERROR)
(DEFPROP NOT-AVAILABLE NAV FILE-ERROR)
(DEFSIGNAL NOT-AVAILABLE FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"File, pack etc. exists but is currently down.")
(DEFSIGNAL INVALID-FILE-ATTRIBUTE ERROR (PATHNAME ATTRIBUTE VALUE)
"An attribute in the file attribute list had a bad value.
This is detected in the Lisp machine, not in the file server.")
(DEFFLAVOR FILE-LOOKUP-ERROR () (FILE-OPERATION-FAILURE))
(DEFPROP FNF FILE-NOT-FOUND FILE-ERROR)
(DEFPROP FILE-NOT-FOUND FNF FILE-ERROR)
(DEFSIGNAL FILE-NOT-FOUND FILE-LOOKUP-ERROR (PATHNAME OPERATION)
"The file was not found in the containing directory.")
(DEFSIGNAL MULTIPLE-FILE-NOT-FOUND FILE-LOOKUP-ERROR (OPERATION PATHNAME PATHNAMES)
"None of the files was found in the containing directory.")
(DEFFLAVOR DIRECTORY-NOT-FOUND-ERROR () (FILE-LOOKUP-ERROR))
(DEFMETHOD (DIRECTORY-NOT-FOUND-ERROR :USER-PROCEED-TYPES) (REAL-PROCEED-TYPES)
(APPEND (INTERSECTION '(:NO-ACTION :RETRY-FILE-OPERATION) REAL-PROCEED-TYPES)
'(:CREATE-DIRECTORY-AND-RETRY)
(REM-IF #'(LAMBDA (ELT) (MEMQ ELT '(:NO-ACTION :RETRY-FILE-OPERATION
:CREATE-DIRECTORY-AND-RETRY)))
REAL-PROCEED-TYPES)))
(DEFMETHOD (DIRECTORY-NOT-FOUND-ERROR :CASE :PROCEED-ASKING-USER :CREATE-DIRECTORY-AND-RETRY)
(CONTINUATION IGNORE)
"Creates the directory and tries again."
(CREATE-DIRECTORY (SEND SELF ':PATHNAME) ':RECURSIVE T)
(FUNCALL CONTINUATION ':RETRY-FILE-OPERATION))
(DEFPROP DNF DIRECTORY-NOT-FOUND FILE-ERROR)
(DEFPROP DIRECTORY-NOT-FOUND DNF FILE-ERROR)
(DEFSIGNAL DIRECTORY-NOT-FOUND DIRECTORY-NOT-FOUND-ERROR (PATHNAME OPERATION)
"Containing directory is not found.")
(DEFPROP DEV DEVICE-NOT-FOUND FILE-ERROR)
(DEFPROP DEVICE-NOT-FOUND DEV FILE-ERROR)
(DEFSIGNAL DEVICE-NOT-FOUND FILE-LOOKUP-ERROR (PATHNAME OPERATION)
"Device specified in pathname not found.")
(DEFPROP LNF LINK-TARGET-NOT-FOUND FILE-ERROR)
(DEFPROP LINK-TARGET-NOT-FOUND LNF FILE-ERROR)
(DEFSIGNAL LINK-TARGET-NOT-FOUND FILE-LOOKUP-ERROR (PATHNAME OPERATION)
"Failure in looking up the target of a link that was found.")
(DEFPROP ACC ACCESS-ERROR FILE-ERROR)
(DEFPROP ACCESS-ERROR ACC FILE-ERROR)
(DEFSIGNAL ACCESS-ERROR FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"Some sort of protection screwed you.")
(DEFPROP ATF INCORRECT-ACCESS-TO-FILE FILE-ERROR)
(DEFPROP INCORRECT-ACCESS-TO-FILE ATF FILE-ERROR)
(DEFSIGNAL INCORRECT-ACCESS-TO-FILE
(FILE-OPERATION-FAILURE ACCESS-ERROR INCORRECT-ACCESS-TO-FILE)
(PATHNAME OPERATION)
"File protection screwed you.")
(DEFPROP ATD INCORRECT-ACCESS-TO-DIRECTORY FILE-ERROR)
(DEFPROP INCORRECT-ACCESS-TO-DIRECTORY ATD FILE-ERROR)
(DEFSIGNAL INCORRECT-ACCESS-TO-DIRECTORY
(FILE-OPERATION-FAILURE ACCESS-ERROR INCORRECT-ACCESS-TO-DIRECTORY)
(PATHNAME OPERATION)
"Directory protection screwed you.")
INVALID - PATHNAME - SYNTAX
(DEFPROP IPS INVALID-PATHNAME-SYNTAX FILE-ERROR)
(DEFPROP INVALID-PATHNAME-SYNTAX IPS FILE-ERROR)
(DEFSIGNAL INVALID-PATHNAME-SYNTAX FILE-OPERATION-FAILURE (PATHNAME OPERATION)
"Some weird syntax got through pathname parsing but file system didn't like it.")
(DEFPROP IWC INVALID-WILDCARD FILE-ERROR)
(DEFPROP INVALID-WILDCARD IWC FILE-ERROR)
(DEFSIGNAL INVALID-WILDCARD (FILE-OPERATION-FAILURE INVALID-PATHNAME-SYNTAX INVALID-WILDCARD)
(PATHNAME OPERATION)
"Wildcard that got through pathname parsing but file system didn't like it.")
(DEFPROP WNA WILDCARD-NOT-ALLOWED FILE-ERROR)
(DEFPROP WILDCARD-NOT-ALLOWED WNA FILE-ERROR)
(DEFSIGNAL WILDCARD-NOT-ALLOWED
(FILE-OPERATION-FAILURE INVALID-PATHNAME-SYNTAX WILDCARD-NOT-ALLOWED)
(PATHNAME OPERATION)
"Wildcard is ok but you did something to it that doesn't like wildcards.")
WRONG - KIND - OF - FILE
(DEFPROP WKF WRONG-KIND-OF-FILE FILE-ERROR)
(DEFPROP WRONG-KIND-OF-FILE WKF FILE-ERROR)
(DEFSIGNAL WRONG-KIND-OF-FILE FILE-OPERATION-FAILURE (PATHNAME OPERATION))
(DEFSIGNAL INVALID-OPERATION-FOR-LINK
(FILE-OPERATION-FAILURE WRONG-KIND-OF-FILE INVALID-OPERATION-FOR-LINK)
(PATHNAME OPERATION))
(DEFPROP IOD INVALID-OPERATION-FOR-DIRECTORY FILE-ERROR)
(DEFPROP INVALID-OPERATION-FOR-DIRECTORY IOD FILE-ERROR)
(DEFSIGNAL INVALID-OPERATION-FOR-DIRECTORY
(FILE-OPERATION-FAILURE WRONG-KIND-OF-FILE INVALID-OPERATION-FOR-DIRECTORY)
(PATHNAME OPERATION))
(DEFPROP FAE FILE-ALREADY-EXISTS FILE-ERROR)
(DEFPROP FILE-ALREADY-EXISTS FAE FILE-ERROR)
(DEFSIGNAL FILE-ALREADY-EXISTS (FILE-OPERATION-FAILURE CREATION-FAILURE FILE-ALREADY-EXISTS)
(PATHNAME OPERATION)
"A file of this name already exists.")
(DEFPROP SND SUPERIOR-NOT-DIRECTORY FILE-ERROR)
(DEFPROP SUPERIOR-NOT-DIRECTORY SND FILE-ERROR)
(DEFSIGNAL SUPERIOR-NOT-DIRECTORY
(FILE-OPERATION-FAILURE WRONG-KIND-OF-FILE CREATION-FAILURE SUPERIOR-NOT-DIRECTORY)
(PATHNAME OPERATION)
"The /"directory/" was not a directory.")
(DEFPROP CCD CREATE-DIRECTORY-FAILURE FILE-ERROR)
(DEFPROP CREATE-DIRECTORY-FAILURE CCD FILE-ERROR)
(DEFSIGNAL CREATE-DIRECTORY-FAILURE
(FILE-OPERATION-FAILURE CREATION-FAILURE CREATE-DIRECTORY-FAILURE)
(PATHNAME OPERATION)
"")
(DEFPROP DAE DIRECTORY-ALREADY-EXISTS FILE-ERROR)
(DEFPROP DIRECTORY-ALREADY-EXISTS DAE FILE-ERROR)
(DEFSIGNAL DIRECTORY-ALREADY-EXISTS
(FILE-OPERATION-FAILURE CREATION-FAILURE CREATE-DIRECTORY-FAILURE
FILE-ALREADY-EXISTS DIRECTORY-ALREADY-EXISTS)
(PATHNAME OPERATION)
"A directory of this name already exists.")
(DEFPROP CCL CREATE-LINK-FAILURE FILE-ERROR)
(DEFPROP CREATE-LINK-FAILURE CCL FILE-ERROR)
(DEFSIGNAL CREATE-LINK-FAILURE (FILE-OPERATION-FAILURE CREATION-FAILURE CREATE-LINK-FAILURE)
(PATHNAME OPERATION)
"Some problem creating a link.")
(DEFFLAVOR RENAME-FAILURE () (FILE-OPERATION-FAILURE)
(:DEFAULT-INIT-PLIST :OPERATION ':RENAME))
(DEFPROP REF RENAME-TO-EXISTING-FILE FILE-ERROR)
(DEFPROP RENAME-TO-EXISTING-FILE REF FILE-ERROR)
(DEFSIGNAL RENAME-TO-EXISTING-FILE RENAME-FAILURE (PATHNAME NEW-PATHNAME)
"NEW-PATHNAME already exists.")
(DEFPROP RAD RENAME-ACROSS-DIRECTORIES FILE-ERROR)
(DEFPROP RENAME-ACROSS-DIRECTORIES RAD FILE-ERROR)
(DEFSIGNAL RENAME-ACROSS-DIRECTORIES RENAME-FAILURE (PATHNAME NEW-PATHNAME)
"PATHNAME and NEW-PATHNAME are on different directories.")
(DEFFLAVOR CHANGE-PROPERTY-FAILURE () (FILE-OPERATION-FAILURE)
(:DEFAULT-INIT-PLIST :OPERATION ':CHANGE-PROPERTIES))
(DEFPROP UKP UNKNOWN-PROPERTY FILE-ERROR)
(DEFPROP UNKNOWN-PROPERTY UKP FILE-ERROR)
(DEFSIGNAL UNKNOWN-PROPERTY CHANGE-PROPERTY-FAILURE (PATHNAME PROPERTY)
"PROPERTY isn't one of the properties this file system handles.")
(DEFPROP IPV INVALID-PROPERTY-VALUE FILE-ERROR)
(DEFPROP INVALID-PROPERTY-VALUE IPV FILE-ERROR)
(DEFSIGNAL INVALID-PROPERTY-VALUE CHANGE-PROPERTY-FAILURE (PATHNAME PROPERTY VALUE)
"VALUE is not a legal value for PROPERTY.")
(DEFPROP IPN INVALID-PROPERTY-NAME FILE-ERROR)
(DEFPROP INVALID-PROPERTY-NAME IPN FILE-ERROR)
(DEFSIGNAL INVALID-PROPERTY-NAME CHANGE-PROPERTY-FAILURE (PATHNAME PROPERTY)
"Property name is syntactically bad.")
(DEFFLAVOR DELETE-FAILURE () (FILE-OPERATION-FAILURE)
(:DEFAULT-INIT-PLIST :OPERATION ':DELETE))
(DEFPROP DNE DIRECTORY-NOT-EMPTY FILE-ERROR)
(DEFPROP DIRECTORY-NOT-EMPTY DNE FILE-ERROR)
(DEFSIGNAL DIRECTORY-NOT-EMPTY DELETE-FAILURE (PATHNAME)
"Deleting a directory that is not empty.")
(DEFPROP DND DONT-DELETE-FLAG-SET FILE-ERROR)
(DEFPROP DONT-DELETE-FLAG-SET DND FILE-ERROR)
(DEFSIGNAL DONT-DELETE-FLAG-SET DELETE-FAILURE (PATHNAME)
"File's dont-delete flag was set.")
(COMPILE-FLAVOR-METHODS
FILE-ERROR
FILE-REQUEST-FAILURE
FILE-OPERATION-FAILURE
FILE-LOOKUP-ERROR
NO-MORE-ROOM-ERROR
DIRECTORY-NOT-FOUND-ERROR
RENAME-FAILURE
CHANGE-PROPERTY-FAILURE
DELETE-FAILURE)
(DEFVAR LAST-FILE-OPENED NIL
"This is the last filename that was opened, successfully or not.")
For compatibility , the OPEN function accepts an option name
Keyword Possible Values Default Comment
: DIRECTION : INPUT : INPUT
:
: BYTE - SIZE NIL NIL 16 for binary files .
: Whatever size the file says it is .
: FLAVOR NIL NIL Normal file
: DIRECTORY Directory file
: OLD - FILE : ERROR ( NOT NEW - FILE ) Generate an error when overwriting .
T or : Use the old file .
: Use it , but append if output .
: LOGICAL - VOLUME NIL NIL In some systems the pathname can
(DEFUN OPEN (FILENAME &REST KEYWORD-ARGS)
"Open a file and return a stream. FILENAME is a pathname or a string.
DIRECTION is :INPUT, :OUTPUT, :PROBE, :PROBE-LINK :PROBE-DIRECTORY
ELEMENT-TYPE specifies how the data of the stream file are to be interpreted.
Possible values include :DEFAULT CHARACTER (UNSIGNED-BYTE n) (SIGNED-BYTE n) (MOD n) BIT
One may also specify the type using the following two options:
CHARACTERS may be T, NIL or :DEFAULT.
BYTE-SIZE specifies byte size to use for non-character files.
IF-EXISTS specifies what to do if FILENAME already exists when opening it for output.
NIL means return NIL from OPEN if file already exists
:ERROR Signal an error (FS:FILE-ALREADY-EXISTS) See the ERROR option
:NEW-VERSION Default for when FILENAME's version is :NEWEST. Create a higher-version file
:SUPERSEDE Create a new file which, when closed, replaces the old one
:OVERWRITE Writes over the data of the old file.
Sets file length to length of the data written during this open when the file is closed.
:TRUNCATE Like :OVERWRITE, but sets length to 0 immediately upon open
:APPEND Append new data to the end of the existing file
:RENAME Rename the existing file to something and then create and use a new one
:RENAME-AND-DELETE Like :RENAME, only the old (renamed) file is deleted when we close
IF-DOES-NOT-EXIST is one of :CREATE (default for most output opens, except if otherwise
specified by IF-EXISTS), :ERROR (default for input opens, and the other output opens)
means signal FS:FILE-NOT-FOUND, or NIL (default for :PROBE-mumble opens) meaning return NIL
ERROR specifies what to do if an error is signaled in the process of opening the file
or else the debugger is entered.
NIL means to return the condition object itself as the value of OPEN
:REPROMPT means to ask the user for a different filename to use instead, and retries.
See also WITH-OPEN-FILE-RETRY and FILE-RETRY-NEW-PATHNAME, which may be The Right Thing
PRESERVE-DATES means not to alter the files reference or modification dates
ESTIMATED-SIZE informs the remote file system what thew estimated final file size will be
RAW, SUPER-IMAGE disable character set translation from ascii servers
DELETED, TEMPORARY mean to allow opening of deleted or temporary files respectively,
on systems which support those concepts.
SUBMIT means to submit the file as a batch job on the remote host when the file is closed.
Other system-specific keywords may be supported for some file systems."
(DECLARE (ARGLIST FILENAME &KEY (DIRECTION :INPUT) (ERROR T) (ELEMENT-TYPE :DEFAULT)
CHARACTERS BYTE-SIZE IF-EXISTS IF-DOES-NOT-EXIST ERROR
PRESERVE-DATES DELETED TEMPORARY SUBMIT PRESERVE-DATES
RAW SUPER-IMAGE INHIBIT-LINKS
&ALLOW-OTHER-KEYS))
(FORCE-USER-TO-LOGIN)
(IF (STREAMP FILENAME)
(SETQ FILENAME (SEND FILENAME :PATHNAME)))
(SETQ FILENAME (MERGE-PATHNAME-DEFAULTS FILENAME))
(SETQ LAST-FILE-OPENED FILENAME)
(NOT (NULL (CDR KEYWORD-ARGS))))
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ (GETF KEYWORD-ARGS ':ERROR) '(:RETRY :REPROMPT))
(FILENAME FILE-ERROR)
(LEXPR-SEND FILENAME :OPEN FILENAME KEYWORD-ARGS))
(DO ((KEYL (IF (AND (CAR KEYWORD-ARGS) (SYMBOLP (CAR KEYWORD-ARGS)))
(LIST (CAR KEYWORD-ARGS))
(CAR KEYWORD-ARGS))
(CDR KEYL))
(KEY)
(CHARACTERS T)
(DIRECTION :INPUT)
(BYTE-SIZE NIL)
(ERRORP T)
(ERRORP-SPECD NIL)
(DELETED-P NIL)
(TEMPORARY-P NIL)
These two are really only useful for machines that do not natively store
8 - bit characters .
(RAW-P NIL)
(SUPER-IMAGE-P NIL)
)
((NULL KEYL)
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ ERRORP '(:RETRY :REPROMPT))
(FILENAME FILE-ERROR)
(%PUSH :OPEN) (%PUSH FILENAME)
(%PUSH :CHARACTERS) (%PUSH CHARACTERS)
(%PUSH :DIRECTION) (%PUSH DIRECTION)
(COND (BYTE-SIZE (%PUSH :BYTE-SIZE) (%PUSH BYTE-SIZE)))
(COND (ERRORP-SPECD (%PUSH :ERROR) (%PUSH ERRORP)))
(COND (DELETED-P (%PUSH :DELETED) (%PUSH DELETED-P)))
(COND (TEMPORARY-P (%PUSH :TEMPORARY) (%PUSH TEMPORARY-P)))
(COND (SUPER-IMAGE-P (%PUSH :SUPER-IMAGE) (%PUSH SUPER-IMAGE-P)))
(COND (RAW-P (%PUSH :RAW) (%PUSH RAW-P)))
(%ACTIVATE-OPEN-CALL-BLOCK)))
(SETQ KEY (CAR KEYL))
(SELECTOR KEY STRING-EQUAL
((:IN :READ) (SETQ DIRECTION :INPUT))
((:OUT :WRITE :PRINT) (SETQ DIRECTION :OUTPUT))
((:BINARY :FIXNUM) (SETQ CHARACTERS NIL))
((:CHARACTER :ASCII) (SETQ CHARACTERS T))
((:BYTE-SIZE) (SETQ KEYL (CDR KEYL)
BYTE-SIZE (CAR KEYL)))
((:PROBE) (SETQ DIRECTION NIL
CHARACTERS NIL
ERRORP (IF (NOT ERRORP-SPECD) NIL ERRORP)
ERRORP-SPECD T))
((:NOERROR) (SETQ ERRORP NIL ERRORP-SPECD T))
((:ERROR) (SETQ ERRORP T ERRORP-SPECD T))
((:RAW) (SETQ RAW-P T))
((:SUPER-IMAGE) (SETQ SUPER-IMAGE-P T))
((:DELETED) (SETQ DELETED-P T))
((:TEMPORARY) (SETQ TEMPORARY-P T))
Ignored for compatility with
(OTHERWISE (FERROR NIL "~S is not a known OPEN option" KEY))))))
(DEFUN OPEN-FILE-SEARCH (BASE-PATHNAME TYPE-LIST DEFAULTS FOR-FUNCTION &REST OPEN-OPTIONS)
(COND ((NULL (PATHNAME-RAW-TYPE BASE-PATHNAME)))
((AND (EQ (PATHNAME-RAW-TYPE BASE-PATHNAME) :UNSPECIFIC)
(SEND BASE-PATHNAME :UNSPECIFIC-TYPE-IS-DEFAULT))
If type is really insignificant , replace it with NIL
so we will get the same behavior as if it were already NIL .
(SETQ BASE-PATHNAME (SEND BASE-PATHNAME ':NEW-TYPE NIL)))
and we might as well have only one to avoid wasting time on duplicate opens .
(T (SETQ TYPE-LIST '(NIL))))
(DOLIST (TYPE TYPE-LIST
(FERROR 'FS:MULTIPLE-FILE-NOT-FOUND
"~S could not find any file related to ~A."
FOR-FUNCTION BASE-PATHNAME
(MAPCAR #'(LAMBDA (TYPE)
(FS:MERGE-PATHNAME-DEFAULTS
BASE-PATHNAME DEFAULTS TYPE))
TYPE-LIST)))
(CONDITION-CASE (OPEN-VALUE)
(APPLY 'OPEN (FS:MERGE-PATHNAME-DEFAULTS
BASE-PATHNAME DEFAULTS TYPE)
OPEN-OPTIONS)
(FILE-NOT-FOUND)
(:NO-ERROR (RETURN OPEN-VALUE)))))
(DEFUN CLOSE (STREAM &OPTIONAL ABORTP)
"Close STREAM. ABORTP says discard file, if output."
(SEND STREAM ':CLOSE ABORTP))
(DEFUN CLI:CLOSE (STREAM &KEY ABORT)
"Close STREAM. ABORT non-NIL says discard file, if output."
(SEND STREAM ':CLOSE (IF ABORT ':ABORT)))
(DEFUN WILDCARDED-FILE-OPERATION (STRING-OR-STREAM
HELPER-FUNCTION
DIR-LIST-OPTIONS
&REST ARGS)
"Call HELPER-FUNCTION for each file which STRING-OR-STREAM refers to.
If STRING-OR-STREAM is a string (or a pathname) then it can refer to
more than one file by containing wildcards.
The arguments passed to HELPER-FUNCTION each time are
1) the truename of a file,
2) the possibly wildcarded pathname being mapped over
followed by ARGS.
DIR-LIST-OPTIONS are passed to FS:DIRECTORY-LIST when finding out
what files exist to be processed."
(FORCE-USER-TO-LOGIN)
(IF (OR (STRINGP STRING-OR-STREAM)
(LET ((SPECIFIED-PATHNAME (MERGE-PATHNAME-DEFAULTS STRING-OR-STREAM)))
(LEXPR-SEND SPECIFIED-PATHNAME ':WILDCARD-MAP HELPER-FUNCTION
NIL DIR-LIST-OPTIONS SPECIFIED-PATHNAME ARGS))
(LET ((SPECIFIED-PATHNAME (SEND STRING-OR-STREAM ':TRUENAME)))
(LIST (APPLY HELPER-FUNCTION
SPECIFIED-PATHNAME
SPECIFIED-PATHNAME
ARGS)))))
The function returns 4 possible values :
NIL , T = = asked the user , got Y or N response .
(DEFVAR *FILE-QUERY-FLAG* NIL)
(DEFVAR *FILE-QUERY-OPTIONS*
`(:CHOICES (,@FORMAT:Y-OR-N-P-CHOICES
((:PROCEED "Proceed.") #/P #/HAND-RIGHT))))
(DEFUN FILE-QUERY-FUNCTION (FORMAT-STRING &REST ARGS)
(IF (NULL *FILE-QUERY-FLAG*)
':NEVER-ASKED
(LET ((QRESULT (APPLY 'FQUERY *FILE-QUERY-OPTIONS* FORMAT-STRING ARGS)))
(IF (EQ QRESULT ':PROCEED)
(SETQ *FILE-QUERY-FLAG* NIL))
QRESULT)))
(DEFUN MAKE-FILE-QUERY-FUNCTION (QUERY?)
"Return a suitable query-function to pass to PRIMITIVE-DELETE-FILE, etc.
This query function, a closure, accepts a format-string and format-arguments,
queries the user and returns T or NIL.
If the user types P instead of Y, the query function returns ':PROCEED
and also returns ':NEVER-ASKED on all successive calls without asking any more.
If QUERY? is NIL, the query function always returns ':NEVER-ASKED without asking."
(LET-CLOSED ((*FILE-QUERY-FLAG* QUERY?)) 'FILE-QUERY-FUNCTION))
(DEFUN COPY-FILE (PATHNAME-OR-STREAM NEW-NAME
&REST OPTIONS
&KEY (ERROR T)
&ALLOW-OTHER-KEYS)
"Copy a file, specified as a pathname, string or I//O stream.
CHARACTERS can be T, NIL, meaning the same as in OPEN.
or it can be :ASK, meaning always ask the user,
or :MAYBE-ASK meaning ask the user unless the answer is clear,
or :DEFAULT meaning guess as well as possible but never ask.
Specify BYTE-SIZE to force copying in a certain byte size.
BYTE-SIZE affects only binary mode copying.
REPORT-STREAM is a stream to output messages to as files are copied.
If it is NIL, no messages are output.
make now be the new file's creation date.
CREATE-DIRECTORIES says whether to create a directory to be copied into.
Values are T, NIL and :QUERY (meaning ask the user if the situation comes up).
Values returned:
1) the first value is normally the defaulted pathname to copy to,
or a list of such if multiple files were considered.
2) the second value is the old truename of the file considered,
or a list of old truenames of the files considered.
3) the third value is the outcome, or a list of outcomes.
An outcome is either a truename if the file was renamed,
an error object if it failed to be renamed,
or NIL if the user was asked and said no.
4) the fourth value is a mode of copying, or a list of such.
A mode of copying is a type specifier such as STRING-CHAR or (UNSIGNED-BYTE 8).
Error objects can appear in the values only if ERROR is NIL."
(DECLARE (ARGLIST PATHNAME-OR-STREAM NEW-NAME
&KEY (ERROR T) (COPY-CREATION-DATE T) (COPY-AUTHOR T)
REPORT-STREAM (CREATE-DIRECTORIES ':QUERY)
(CHARACTERS ':DEFAULT) (BYTE-SIZE ':DEFAULT))
(VALUES TARGET-PATHNAME TARGET-TRUENAME RESULT-PATHNAME COPY-MODE))
(FORCE-USER-TO-LOGIN)
(LET ((RESULT
(IF (OR (STRINGP PATHNAME-OR-STREAM)
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ ERROR '(:RETRY :REPROMPT))
(PATHNAME-OR-STREAM FILE-ERROR)
(LET ((MERGED-PATHNAME (MERGE-PATHNAME-DEFAULTS PATHNAME-OR-STREAM)))
(APPLY MERGED-PATHNAME
':WILDCARD-MAP #'PRIMITIVE-COPY-FILE
':MAYBE NIL
MERGED-PATHNAME (PARSE-PATHNAME NEW-NAME NIL MERGED-PATHNAME) OPTIONS)))
(LET ((TRUENAME (SEND PATHNAME-OR-STREAM ':TRUENAME)))
(LIST (APPLY 'PRIMITIVE-COPY-FILE
(FILE-PROPERTIES TRUENAME)
TRUENAME (PARSE-PATHNAME NEW-NAME NIL TRUENAME) OPTIONS))))))
(IF (EQ (CAAR RESULT) (CADAR RESULT))
(VALUES (THIRD (CAR RESULT))
(FOURTH (CAR RESULT))
(FIFTH (CAR RESULT))
(SIXTH (CAR RESULT)))
(VALUES (MAPCAR 'THIRD RESULT)
(MAPCAR 'FOURTH RESULT)
(MAPCAR 'FIFTH RESULT)
(MAPCAR 'SIXTH RESULT)))))
(DEFCONST *COPY-FILE-KNOWN-TEXT-TYPES* '(:LISP :TEXT :MIDAS :PALX :PATCH-DIRECTORY :C
:INIT :UNFASL :BABYL :XMAIL :MAIL :QWABL :DOC :BOTEX
"LPT" "XGP" "ULOAD")
"Files whose names have these canonical types are normally copied as characters.")
(DEFCONST *COPY-FILE-KNOWN-BINARY-TYPES* '(:QFASL :PRESS :WIDTHS :KST
:impress :dvi
"FASL" "MCR" "QBIN" "EXE" "BIN")
"Files whose names have these canonical types are normally copied as binary.")
(DEFUN PRIMITIVE-COPY-FILE (INPUT-PLIST-OR-PATHNAME MAPPED-PATHNAME OUTPUT-SPEC
&KEY (ERROR T) (COPY-CREATION-DATE T) (COPY-AUTHOR T)
REPORT-STREAM (CREATE-DIRECTORIES ':QUERY)
(CHARACTERS ':DEFAULT) (BYTE-SIZE ':DEFAULT)
&AUX INTYPE INPUT-PLIST INPUT-PATHNAME INPUT-TRUENAME)
(IF (NLISTP INPUT-PLIST-OR-PATHNAME)
(SETQ INPUT-PATHNAME INPUT-PLIST-OR-PATHNAME
INPUT-PLIST NIL)
(SETQ INPUT-PATHNAME (CAR INPUT-PLIST-OR-PATHNAME)
INPUT-PLIST INPUT-PLIST-OR-PATHNAME))
(LET ((CHARACTERS?
(SELECTQ CHARACTERS
((T) CHARACTERS)
(:ASK (FQUERY NIL "~&Is ~A a text file? " INPUT-PATHNAME))
(OTHERWISE
so get it if we were not given it as the first arg .
(IF (NULL INPUT-PLIST)
(SETQ INPUT-PLIST (FILE-PROPERTIES INPUT-PATHNAME)
INPUT-PATHNAME (CAR INPUT-PLIST)))
(LET ((BYTE-SIZE (GET INPUT-PLIST ':BYTE-SIZE)))
(COND ((NULL CHARACTERS) NIL)
((MEMQ BYTE-SIZE '(7 8)) T)
((EQ BYTE-SIZE 16.) NIL)
((MEMBER (SETQ INTYPE (SEND INPUT-PATHNAME ':CANONICAL-TYPE))
*COPY-FILE-KNOWN-TEXT-TYPES*)
T)
((MEMBER INTYPE *COPY-FILE-KNOWN-BINARY-TYPES*) NIL)
((EQ CHARACTERS ':DEFAULT) ':DEFAULT)
(T (FQUERY '(:BEEP T) "~&Is ~A a text file? " INPUT-PATHNAME))))))))
(IF (EQ BYTE-SIZE ':DEFAULT)
(SETQ BYTE-SIZE (OR (GET INPUT-PLIST ':BYTE-SIZE) ':DEFAULT)))
(IF (EQ BYTE-SIZE 36.)
(SETQ BYTE-SIZE 12.))
(CONDITION-CASE-IF (NOT ERROR) (ERROR)
(WITH-OPEN-FILE (INSTREAM INPUT-PATHNAME
':DIRECTION ':INPUT
':CHARACTERS CHARACTERS?
':BYTE-SIZE BYTE-SIZE)
(SETQ INPUT-TRUENAME (SEND INSTREAM ':TRUENAME))
(LET ((DEFAULTED-NEW-NAME
(LET ((*ALWAYS-MERGE-TYPE-AND-VERSION* T))
(MERGE-PATHNAME-DEFAULTS
(SEND MAPPED-PATHNAME ':TRANSLATE-WILD-PATHNAME
OUTPUT-SPEC INPUT-TRUENAME)
INPUT-TRUENAME))))
(CONDITION-BIND ((DIRECTORY-NOT-FOUND
#'(LAMBDA (ERROR)
(WHEN (IF (EQ CREATE-DIRECTORIES ':QUERY)
(PROGN
(SEND *QUERY-IO* ':FRESH-LINE)
(SEND ERROR ':REPORT *QUERY-IO*)
(Y-OR-N-P "Create the directory? "))
CREATE-DIRECTORIES)
(CREATE-DIRECTORY defaulted-new-name ':RECURSIVE T)
':RETRY-FILE-OPERATION))))
(WITH-OPEN-FILE (OUTSTREAM DEFAULTED-NEW-NAME
':DIRECTION ':OUTPUT
':CHARACTERS CHARACTERS?
':BYTE-SIZE (IF CHARACTERS? ':DEFAULT BYTE-SIZE))
(IF COPY-AUTHOR
(IF COPY-CREATION-DATE
(SEND OUTSTREAM ':CHANGE-PROPERTIES NIL
':CREATION-DATE (SEND INSTREAM ':CREATION-DATE)
':AUTHOR (OR (SEND INSTREAM ':GET ':AUTHOR)
(GET INPUT-PLIST ':AUTHOR)))
(SEND OUTSTREAM ':CHANGE-PROPERTIES NIL
':AUTHOR (OR (SEND INSTREAM ':GET ':AUTHOR)
(GET INPUT-PLIST ':AUTHOR))))
(IF COPY-CREATION-DATE
(SEND OUTSTREAM ':CHANGE-PROPERTIES NIL
':CREATION-DATE (SEND INSTREAM ':CREATION-DATE))))
(STREAM-COPY-UNTIL-EOF INSTREAM OUTSTREAM)
(CLOSE OUTSTREAM)
(WHEN REPORT-STREAM
(FORMAT REPORT-STREAM "~&Copied ~A to ~A "
INPUT-TRUENAME (SEND OUTSTREAM ':TRUENAME))
(IF CHARACTERS?
(FORMAT REPORT-STREAM "in character mode.~%")
(FORMAT REPORT-STREAM "in byte size ~D.~%"
BYTE-SIZE)))
(LIST MAPPED-PATHNAME INPUT-PATHNAME DEFAULTED-NEW-NAME
INPUT-TRUENAME (SEND OUTSTREAM ':TRUENAME)
(STREAM-ELEMENT-TYPE INSTREAM))))))
((FILE-ERROR SYS:REMOTE-NETWORK-ERROR)
(LIST MAPPED-PATHNAME INPUT-PATHNAME
(LET ((*ALWAYS-MERGE-TYPE-AND-VERSION* T))
(MERGE-PATHNAME-DEFAULTS
(SEND MAPPED-PATHNAME ':TRANSLATE-WILD-PATHNAME
OUTPUT-SPEC (OR INPUT-TRUENAME INPUT-PATHNAME))
(OR INPUT-TRUENAME INPUT-PATHNAME)))
INPUT-PATHNAME ERROR)))))
(DEFUN RENAME-FILE (STRING-OR-STREAM NEW-NAME &KEY (ERROR T) QUERY)
"Rename a file, specified as a pathname, string or I//O stream.
Wildcards are allowed.
QUERY, if true, means ask about each file before renaming it.
Values returned:
1) the first value is normally the defaulted pathname to rename to,
or a list of such if multiple files were considered.
2) the second value is the old truename of the file considered,
or a list of old truenames of the files considered.
3) the third value is the outcome, or a list of outcomes.
An outcome is either a truename if the file was renamed,
an error object if it failed to be renamed,
or NIL if the user was asked and said no.
Error objects can appear in the values only if ERROR is NIL."
(DECLARE (VALUES OLD-NAME OLD-TRUENAME NEW-TRUENAME))
(RENAMEF STRING-OR-STREAM NEW-NAME ERROR QUERY))
(DEFUN RENAMEF (STRING-OR-STREAM NEW-NAME &OPTIONAL (ERROR-P T) QUERY?)
"Rename a file, specified as a pathname, string or I//O stream.
Wildcards are allowed.
QUERY?, if true, means ask about each file before renaming it.
Values returned:
1) the first value is normally the defaulted pathname to rename to,
or a list of such if multiple files were considered.
2) the second value is the old truename of the file considered,
or a list of old truenames of the files considered.
3) the third value is the outcome, or a list of outcomes.
An outcome is either a truename if the file was renamed,
an error object if it failed to be renamed,
or NIL if the user was asked and said no.
Error objects can appear in the values only if ERROR-P is NIL."
(DECLARE (VALUES OLD-NAME OLD-TRUENAME NEW-TRUENAME))
(FILE-RETRY-NEW-PATHNAME-IF (AND (OR (STRINGP STRING-OR-STREAM)
(TYPEP STRING-OR-STREAM 'PATHNAME))
(MEMQ ERROR-P '(:RETRY :REPROMPT)))
(STRING-OR-STREAM FILE-ERROR)
(LET* ((FROM-PATHNAME (PATHNAME STRING-OR-STREAM))
(RESULT (WILDCARDED-FILE-OPERATION
STRING-OR-STREAM
#'PRIMITIVE-RENAME-FILE
NIL
(PARSE-PATHNAME NEW-NAME NIL FROM-PATHNAME) ERROR-P
(MAKE-FILE-QUERY-FUNCTION QUERY?))))
(IF (EQ (CAAR RESULT) (CADAR RESULT))
(VALUES (THIRD (CAR RESULT))
(FOURTH (CAR RESULT))
(FIFTH (CAR RESULT)))
(VALUES (MAPCAR 'THIRD RESULT)
(MAPCAR 'FOURTH RESULT)
(MAPCAR 'FIFTH RESULT))))))
(DEFUN PRIMITIVE-RENAME-FILE (OLD-NAME MAPPED-PATHNAME NEW-NAME &OPTIONAL (ERROR-P T) QUERYF)
(LET ((TRUENAME (IF (or (EQ OLD-NAME MAPPED-PATHNAME)
(typep old-name 'logical-pathname))
(SEND OLD-NAME ':TRUENAME ERROR-P)
OLD-NAME))
(newname (if (typep new-name 'logical-pathname)
(translated-pathname (merge-pathname-defaults new-name mapped-pathname))
new-name)))
(IF (ERRORP TRUENAME)
(LIST MAPPED-PATHNAME OLD-NAME NIL OLD-NAME TRUENAME)
(LET* ((DEFAULTED-NEW-NAME
(LET ((*ALWAYS-MERGE-TYPE-AND-VERSION* T))
(MERGE-PATHNAME-DEFAULTS
(SEND MAPPED-PATHNAME ':TRANSLATE-WILD-PATHNAME newname TRUENAME)
TRUENAME)))
(RENAMED? (FUNCALL QUERYF "~&Rename ~A to ~A? "
TRUENAME DEFAULTED-NEW-NAME))
(RESULT (AND RENAMED? (SEND TRUENAME ':RENAME
DEFAULTED-NEW-NAME ERROR-P))))
(LIST MAPPED-PATHNAME OLD-NAME DEFAULTED-NEW-NAME TRUENAME RESULT)))))
(DEFUN CREATE-LINK (LINK LINK-TO &KEY (ERROR T))
"Create a link, which is specified as a pathname or string, to the file LINK-TO."
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ ERROR '(:RETRY :REPROMPT))
(LINK FILE-ERROR)
(LET ((PATHNAME (MERGE-PATHNAME-DEFAULTS LINK)))
(SEND PATHNAME ':CREATE-LINK (LET ((*ALWAYS-MERGE-TYPE-AND-VERSION* T))
(MERGE-PATHNAME-DEFAULTS LINK-TO PATHNAME))
':ERROR ERROR))))
(DEFUN DELETE-FILE (STRING-OR-STREAM &KEY (ERROR T) QUERY)
"Delete a file, specified as a pathname, string or I//O stream.
Wildcards are allowed.
QUERY, if true, means to ask the user before deleting each file.
the element looks like (TRUENAME OUTCOME), where OUTCOME
is either an error object, NIL if the user said don't delete this one,
or another non-NIL object if the file was deleted.
OUTCOME can be an error object only if ERROR is NIL.
ERROR does not affect errors that happen in determining
what files match a wildcarded pathname."
(DELETEF STRING-OR-STREAM ERROR QUERY))
(DEFUN DELETEF (STRING-OR-STREAM &OPTIONAL (ERROR-P T) QUERY?)
"Delete a file, specified as a pathname, string or I//O stream.
Wildcards are allowed.
QUERY?, if true, means to ask the user before deleting each file.
the element looks like (TRUENAME OUTCOME), where OUTCOME
is either an error object, NIL if the user said don't delete this one,
or another non-NIL object if the file was deleted.
OUTCOME can be an error object only if ERROR-P is NIL.
ERROR-P does not affect errors that happen in determining
what files match a wildcarded pathname."
(FILE-RETRY-NEW-PATHNAME-IF (AND (OR (STRINGP STRING-OR-STREAM)
(TYPEP STRING-OR-STREAM 'PATHNAME))
(MEMQ ERROR-P '(:RETRY :REPROMPT)))
(STRING-OR-STREAM FILE-ERROR)
(WILDCARDED-FILE-OPERATION STRING-OR-STREAM
#'PRIMITIVE-DELETE-FILE NIL
ERROR-P
(MAKE-FILE-QUERY-FUNCTION QUERY?))))
(DEFUN PRIMITIVE-DELETE-FILE (PATHNAME MAPPED-PATHNAME &OPTIONAL (ERROR-P T) QUERYF)
"QUERYF should be a function that takes a format-string and a pathname
and returns T or NIL saying whether to delete that file.
If you don't want any querying, pass FILE-QUERY-TRUE as QUERYF."
(LET ((TRUENAME (cond
((EQ PATHNAME MAPPED-PATHNAME) (SEND PATHNAME ':TRUENAME ERROR-P))
((typep pathname 'logical-pathname) (translated-pathname pathname))
(t PATHNAME))))
(IF (ERRORP TRUENAME)
(LIST PATHNAME TRUENAME)
(LET* ((DELETE? (FUNCALL QUERYF "~&Delete ~A? " TRUENAME))
(RESULT (AND DELETE? (SEND TRUENAME ':DELETE ERROR-P))))
(LIST TRUENAME (IF (ERRORP RESULT) RESULT DELETE?))))))
(DEFUN UNDELETE-FILE (STRING-OR-STREAM &KEY (ERROR T) QUERY)
"Undelete a file, specified as a pathname, string or I//O stream.
Wildcards are allowed. Not all file servers support undeletion.
QUERY, if true, means to ask the user before undeleting each file.
the element looks like (TRUENAME OUTCOME), where OUTCOME
is either an error object, NIL if the user said don't undelete this one,
or another non-NIL object if the file was undeleted.
OUTCOME can be an error object only if ERROR is NIL.
ERROR does not affect errors that happen in determining
what files match a wildcarded pathname."
(UNDELETEF STRING-OR-STREAM ERROR QUERY))
(DEFUN UNDELETEF (STRING-OR-STREAM &OPTIONAL (ERROR-P T) QUERY?)
"Undelete a file, specified as a pathname, string or I//O stream.
Wildcards are allowed. Not all file servers support undeletion.
QUERY?, if true, means to ask the user before undeleting each file.
the element looks like (TRUENAME OUTCOME), where OUTCOME
is either an error object, NIL if the user said don't undelete this one,
or another non-NIL object if the file was undeleted.
OUTCOME can be an error object only if ERROR-P is NIL.
ERROR-P does not affect errors that happen in determining
what files match a wildcarded pathname."
(FILE-RETRY-NEW-PATHNAME-IF (AND (OR (STRINGP STRING-OR-STREAM)
(TYPEP STRING-OR-STREAM 'PATHNAME))
(MEMQ ERROR-P '(:RETRY :REPROMPT)))
(STRING-OR-STREAM FILE-ERROR)
(WILDCARDED-FILE-OPERATION STRING-OR-STREAM
#'PRIMITIVE-UNDELETE-FILE '(:DELETED)
ERROR-P
(MAKE-FILE-QUERY-FUNCTION QUERY?))))
(DEFUN PRIMITIVE-UNDELETE-FILE (PATHNAME MAPPED-PATHNAME &OPTIONAL (ERROR-P T) QUERYF)
"QUERYF should be a function that takes a format-string and a pathname
and returns T or NIL saying whether to delete that file.
If you don't want any querying, pass FILE-QUERY-TRUE as QUERYF."
(LET ((TRUENAME (IF (EQ PATHNAME MAPPED-PATHNAME)
(WITH-OPEN-FILE (STREAM PATHNAME ':ERROR ERROR-P ':DELETED T
':DIRECTION NIL)
(IF (ERRORP STREAM) STREAM
(SEND STREAM ':TRUENAME)))
PATHNAME)))
(IF (ERRORP TRUENAME)
(LIST PATHNAME TRUENAME)
(LET* ((UNDELETE? (FUNCALL QUERYF "~&Undelete ~A? " TRUENAME))
(RESULT (AND UNDELETE? (SEND TRUENAME ':UNDELETE ERROR-P))))
(LIST TRUENAME (IF (ERRORP RESULT) RESULT UNDELETE?))))))
(DEFF PROBE-FILE 'PROBEF)
(DEFUN PROBEF (FILE)
"Non-NIL if FILE exists.
Return the file's truename if successful, NIL if file-not-found.
Any other error condition is not handled."
(IF (STREAMP FILE)
(SEND FILE ':TRUENAME)
(CONDITION-CASE (STREAM)
(OPEN FILE ':DIRECTION NIL)
(FILE-NOT-FOUND NIL)
(:NO-ERROR (PROG1 (SEND STREAM ':TRUENAME) (CLOSE STREAM))))))
(DEFUN FILE-WRITE-DATE (FILENAME-OR-STREAM)
"Return file's creation or last write date. Specify pathname, namestring or file stream."
(IF (OR (STRINGP FILENAME-OR-STREAM)
(SYMBOLP FILENAME-OR-STREAM)
(TYPEP FILENAME-OR-STREAM 'PATHNAME))
(WITH-OPEN-FILE (STREAM FILENAME-OR-STREAM ':DIRECTION NIL)
(SEND STREAM ':CREATION-DATE))
(SEND FILENAME-OR-STREAM ':CREATION-DATE)))
(DEFUN FILE-AUTHOR (FILENAME-OR-STREAM)
"Return file's author's name (a string). Specify pathname, namestring or file stream."
(IF (OR (STRINGP FILENAME-OR-STREAM)
(SYMBOLP FILENAME-OR-STREAM)
(TYPEP FILENAME-OR-STREAM 'PATHNAME))
(WITH-OPEN-FILE (STREAM FILENAME-OR-STREAM ':DIRECTION NIL)
(SEND STREAM ':GET ':AUTHOR))
(SEND FILENAME-OR-STREAM ':GET ':AUTHOR)))
(DEFUN FILE-POSITION (FILE-STREAM &OPTIONAL NEW-POSITION)
"Return or set the stream pointer of FILE-STREAM.
With one argument, return the stream pointer of FILE-STREAM, or NIL if not known.
With two arguments, try to set the stream pointer to NEW-POSITION
and return T if it was possible to do so."
(COND (NEW-POSITION
(SEND-IF-HANDLES FILE-STREAM :SET-POINTER NEW-POSITION))
(T
(SEND-IF-HANDLES FILE-STREAM :READ-POINTER))))
(DEFUN FILE-LENGTH (FILE-STREAM)
"Return the length of the file that is open, or NIL if not known."
(SEND FILE-STREAM :LENGTH))
(DEFUN VIEWF (FILE &OPTIONAL (OUTPUT-STREAM *STANDARD-OUTPUT*) LEADER)
"Print the contents of a file on the output stream.
LEADER is passed to the :LINE-IN operation."
(WITH-OPEN-FILE (FILE-STREAM FILE ':ERROR ':REPROMPT)
(IF (ERRORP FILE-STREAM)
FILE-STREAM
(SEND OUTPUT-STREAM ':FRESH-LINE)
(STREAM-COPY-UNTIL-EOF FILE-STREAM OUTPUT-STREAM LEADER))))
(LET ((PATHNAME (FS:DEFAULT-PATHNAME)))
(FS:MAKE-PATHNAME ':HOST (SEND PATHNAME ':HOST) ':DIRECTORY (SEND PATHNAME ':DIRECTORY))))
(DEFUN LISTF (&OPTIONAL (DIRECTORY (FS:WORKING-DIRECTORY))
(OUTPUT-STREAM *STANDARD-OUTPUT*) LEADER)
"Print a listing of DIRECTORY on OUTPUT-STREAM.
LEADER is passed to the :LINE-IN operation."
(SETQ DIRECTORY (FS:PARSE-PATHNAME DIRECTORY))
(OR (SEND DIRECTORY ':NAME)
(SETQ DIRECTORY (SEND DIRECTORY ':NEW-NAME ':WILD)))
(SETQ DIRECTORY (FS:MERGE-PATHNAME-DEFAULTS DIRECTORY NIL ':WILD ':WILD))
(SEND OUTPUT-STREAM ':FRESH-LINE)
(FILE-RETRY-NEW-PATHNAME (DIRECTORY FS:FILE-ERROR)
(WITH-OPEN-STREAM (STREAM (ZWEI:DIRECTORY-INPUT-STREAM DIRECTORY))
(STREAM-COPY-UNTIL-EOF STREAM OUTPUT-STREAM LEADER)))
DIRECTORY)
(DEFVAR USER-HOMEDIRS NIL
"Alist mapping host objects to pathnames. Gives the home device//directory for each host.")
(DEFVAR USER-PERSONAL-NAME ""
"The user's full name, last name first. Obtained from the FS:USER-LOGIN-MACHINE.")
(DEFVAR USER-PERSONAL-NAME-FIRST-NAME-FIRST ""
"The user's full name, first name first. Obtained from the FS:USER-LOGIN-MACHINE.")
(DEFVAR USER-GROUP-AFFILIATION #/-
"The user's /"group affiliation/", a character. Obtained from the FS:USER-LOGIN-MACHINE.")
(DEFVAR USER-LOGIN-MACHINE SI:ASSOCIATED-MACHINE
"The host the user logged in on.")
(DEFF USER-HOMEDIR-PATHNAME 'USER-HOMEDIR)
(DEFUN USER-HOMEDIR (&OPTIONAL (HOST USER-LOGIN-MACHINE) RESET-P (USER USER-ID))
"Return a pathname describing the home directory for USER on host HOST.
This is used as a default, sometimes. RESET-P says make this our login host."
(SETQ HOST (GET-PATHNAME-HOST HOST))
(AND RESET-P (SETQ USER-LOGIN-MACHINE HOST))
(CONDITION-CASE ()
(SEND (SAMPLE-PATHNAME HOST) ':HOMEDIR USER)
(FILE-ERROR
(QUIET-USER-HOMEDIR HOST))))
(DEFUN QUIET-USER-HOMEDIR (HOST)
(OR (CDR (ASSQ HOST USER-HOMEDIRS))
(SEND (SAMPLE-PATHNAME HOST) ':QUIET-HOMEDIR)))
(DEFUN FORCE-USER-TO-LOGIN (&OPTIONAL (HOST SI:ASSOCIATED-MACHINE)
&AUX INPUT USER DONT-READ-INIT IDX IDX2)
"Require the user to log in. HOST is a default for logging in."
(WHEN (OR (NULL USER-ID) (STRING-EQUAL USER-ID ""))
(SEND *QUERY-IO* ':BEEP)
(FORMAT *QUERY-IO*
"~&Please log in. ~
HOST)
(SETQ INPUT (STRING-TRIM '(#/SPACE #/TAB) (READLINE *QUERY-IO*)))
(AND (SETQ IDX (STRING-SEARCH-CHAR #/@ INPUT))
(SETQ USER (SUBSTRING INPUT 0 IDX)))
(AND (SETQ IDX2 (STRING-SEARCH-SET '(#/SPACE #/TAB) INPUT (OR IDX 0)))
(SETQ DONT-READ-INIT (READ-FROM-STRING INPUT T IDX2)))
(IF IDX
(SETQ HOST (SUBSTRING INPUT (1+ IDX) IDX2))
(SETQ USER (SUBSTRING INPUT 0 IDX2)))
(OR (STRING-EQUAL USER "")
(LOGIN USER HOST DONT-READ-INIT))))
(DEFVAR USER-UNAMES NIL "Alist mapping host objects into usernames.")
(DEFUN FILE-HOST-USER-ID (UID HOST)
"Specify the user-id UID for use on host HOST."
(AND (MEMQ (SEND HOST ':SYSTEM-TYPE) '(:ITS :LMFILE))
(SETQ HOST 'ITS
UID (SUBSTRING UID 0 (MIN (STRING-LENGTH UID) 6))))
(LET ((AE (ASSQ HOST USER-UNAMES)))
(IF AE
(RPLACD AE UID)
(PUSH (CONS HOST UID) USER-UNAMES))))
(CDR (ASSQ (IF (EQ (SEND HOST ':SYSTEM-TYPE) ':ITS) 'ITS HOST) USER-UNAMES)))
(ADD-INITIALIZATION "File Host User ID" '(FILE-HOST-USER-ID USER-ID USER-LOGIN-MACHINE)
'(LOGIN))
(ADD-INITIALIZATION "Reset File Host User ID" '(SETQ USER-UNAMES NIL) '(LOGOUT))
Alist of elements ( ( username host ) password - string )
(DEFVAR USER-HOST-PASSWORD-ALIST NIL
"Alist of elements ((USERNAME HOST-NAME) PASSWORD).
The three data in each element are all strings.")
(DEFVAR RECORD-PASSWORDS-FLAG T
"T => record passwords when the user types them, in case they are useful again.")
(DEFVAR *REMEMBER-PASSWORDS* :UNBOUND
"T => record passwords when the user types them, in case they are useful again.")
(FORWARD-VALUE-CELL '*REMEMBER-PASSWORDS* 'RECORD-PASSWORDS-FLAG)
(ADD-INITIALIZATION "Forget Passwords" '(SETQ USER-HOST-PASSWORD-ALIST NIL) '(BEFORE-COLD))
(DEFUN FILE-GET-PASSWORD (UID HOST &OPTIONAL DIRECTORY-FLAG)
"Given a username and host, ask for either a password or a username and password.
If DIRECTORY-FLAG is set, we are using directory names, not passwords"
(DECLARE (VALUES NEW-USER-ID PASSWORD ENABLE-CAPABILITIES))
(LET* ((LINE (MAKE-STRING 30 ':FILL-POINTER 0))
ENABLE-CAPABILITIES CHAR UID-P
(HACK (AND (SEND *QUERY-IO* ':OPERATION-HANDLED-P ':CLEAR-BETWEEN-CURSORPOSES)
(SEND *QUERY-IO* ':OPERATION-HANDLED-P ':COMPUTE-MOTION)))
START-X START-Y)
(UNLESS DIRECTORY-FLAG
(SETQ UID (OR (CDR (ASSQ HOST USER-UNAMES)) UID)))
(LET ((PW (CADR (ASSOC-EQUALP (LIST UID (SEND HOST ':NAME))
USER-HOST-PASSWORD-ALIST))))
(WHEN PW (RETURN-FROM FILE-GET-PASSWORD (values UID PW))))
(TAGBODY
(WHEN HACK (SETQ HACK (MAKE-STRING 30. ':INITIAL-VALUE #/X ':FILL-POINTER 0)))
RESTART
(UNLESS DIRECTORY-FLAG
(SETQ UID (OR (CDR (ASSQ HOST USER-UNAMES)) UID)))
(LET ((PW (CADR (ASSOC-EQUALP (LIST UID (SEND HOST ':NAME))
USER-HOST-PASSWORD-ALIST))))
(WHEN PW (RETURN-FROM FILE-GET-PASSWORD (values UID PW))))
(FORMAT *QUERY-IO*
(IF DIRECTORY-FLAG "~&Type the password for directory ~A on host ~A,
or a directory and password. /"Directory/" here includes devices as well: "
for host ~A.~ >
UID HOST)
(WHEN HACK (MULTIPLE-VALUE (START-X START-Y) (SEND *QUERY-IO* ':READ-CURSORPOS)))
L (SETQ CHAR (SEND *QUERY-IO* ':TYI))
(VECTOR-PUSH-EXTEND (SEND *QUERY-IO* ':TYI) LINE)
(WHEN HACK
(VECTOR-PUSH-EXTEND #/X HACK)
(SEND *QUERY-IO* ':TYO #/X)))
((= CHAR #/RUBOUT)
(WHEN (ZEROP (FILL-POINTER LINE))
(GO FLUSH))
(VECTOR-POP LINE)
(WHEN HACK
(VECTOR-POP HACK)
(MULTIPLE-VALUE-BIND (X Y)
(SEND *QUERY-IO* ':COMPUTE-MOTION HACK 0 NIL
START-X START-Y)
(MULTIPLE-VALUE-BIND (CX CY) (SEND *QUERY-IO* ':READ-CURSORPOS)
(SEND *QUERY-IO* ':CLEAR-BETWEEN-CURSORPOSES X Y CX CY))
(SEND *QUERY-IO* ':SET-CURSORPOS X Y))))
((= CHAR #/CLEAR-INPUT)
(GO FLUSH))
((AND (= CHAR #/SPACE)
(WHEN ENABLE-CAPABILITIES
(DOTIMES (I (1- (FILL-POINTER LINE)))
(SETF (AREF LINE (1+ I)) (AREF LINE (1- I))))
(SETF (CHAR LINE 0) #/*)
(SETQ ENABLE-CAPABILITIES NIL))
(SETQ UID-P T
UID LINE
LINE (MAKE-STRING 30. :FILL-POINTER 0))
(WHEN HACK
(MULTIPLE-VALUE-BIND (CX CY) (SEND *QUERY-IO* ':READ-CURSORPOS)
(SEND *QUERY-IO* ':CLEAR-BETWEEN-CURSORPOSES START-X START-Y CX CY))
(SEND *QUERY-IO* ':SET-CURSORPOS START-X START-Y))
(FORMAT *QUERY-IO* "~A " UID)
(WHEN HACK (MULTIPLE-VALUE (START-X START-Y)
(SEND *QUERY-IO* ':READ-CURSORPOS))))
((= CHAR #/RETURN)
(OR DIRECTORY-FLAG (FILE-HOST-USER-ID UID HOST))
(IF RECORD-PASSWORDS-FLAG
(PUSH `((,UID ,(SEND HOST ':NAME)) ,LINE) USER-HOST-PASSWORD-ALIST))
(WHEN HACK
(MULTIPLE-VALUE-BIND (CX CY) (SEND *QUERY-IO* ':READ-CURSORPOS)
(SEND *QUERY-IO* ':CLEAR-BETWEEN-CURSORPOSES START-X START-Y CX CY))
(SEND *QUERY-IO* ':SET-CURSORPOS START-X START-Y))
(FRESH-LINE *QUERY-IO*)
(SEND *QUERY-IO* ':SEND-IF-HANDLES ':MAKE-COMPLETE)
(RETURN-FROM FILE-GET-PASSWORD (values UID LINE ENABLE-CAPABILITIES)))
((AND (= CHAR #/*)
(= (FILL-POINTER LINE) 0))
(SETQ ENABLE-CAPABILITIES T))
(( 0 (CHAR-BITS CHAR)) (BEEP))
(T (WHEN HACK
(VECTOR-PUSH-EXTEND #/X HACK)
(SEND *QUERY-IO* ':TYO #/X))
(VECTOR-PUSH-EXTEND CHAR LINE)))
(GO L)
FLUSH
(WHEN HACK
(MULTIPLE-VALUE-BIND (CX CY) (SEND *QUERY-IO* ':READ-CURSORPOS)
(SEND *QUERY-IO* ':CLEAR-BETWEEN-CURSORPOSES START-X START-Y CX CY))
(SEND *QUERY-IO* ':SET-CURSORPOS START-X START-Y)
(SETF (FILL-POINTER HACK) 0))
(WHEN UID-P (RETURN-ARRAY (PROG1 LINE (SETQ LINE UID UID NIL))))
(FORMAT *QUERY-IO* "Flushed.~&")
(SETF (FILL-POINTER LINE) 0 UID-P NIL)
(GO RESTART))))
(DEFUN MULTIPLE-FILE-PLISTS (FILENAMES &REST OPTIONS &AUX HOST-FILE-LIST)
"Given a list of pathnames or namestrings, return a list of property lists.
Each element of the value looks like (pathname . properties)."
(FORCE-USER-TO-LOGIN)
(DOLIST (FILENAME FILENAMES)
(SETQ FILENAME (MERGE-PATHNAME-DEFAULTS FILENAME))
(DO ((HOST (SEND FILENAME ':HOST))
(LIST HOST-FILE-LIST (CDR LIST)))
((NULL LIST)
(PUSH (NCONS FILENAME) HOST-FILE-LIST))
(COND ((EQ HOST (SEND (CAAR HOST-FILE-LIST) ':HOST))
(PUSH FILENAME (CAR LIST))
(RETURN)))))
(LOOP FOR LIST IN (NREVERSE HOST-FILE-LIST)
NCONC (SEND (CAR LIST) ':MULTIPLE-FILE-PLISTS (NREVERSE LIST) OPTIONS)))
(DEFUN MULTIPLE-FILE-PROPERTY-LISTS (BINARY-P FILENAMES)
(MULTIPLE-FILE-PLISTS FILENAMES ':CHARACTERS (NOT BINARY-P)))
(DEFUN CLOSE-ALL-FILES (&OPTIONAL (MODE :ABORT))
"Close all file streams that are open."
(NCONC (AND (BOUNDP 'TV::WHO-LINE-FILE-STATE-SHEET)
TV::WHO-LINE-FILE-STATE-SHEET
(DO ((F (SEND TV::WHO-LINE-FILE-STATE-SHEET :OPEN-STREAMS)
(CDR F))
(THINGS-CLOSED NIL))
((NULL F)
(SEND TV::WHO-LINE-FILE-STATE-SHEET :DELETE-ALL-STREAMS)
(NREVERSE THINGS-CLOSED))
(FORMAT *ERROR-OUTPUT* "~%Closing ~S" (CAR F))
(PUSH (CAR F) THINGS-CLOSED)
(SEND (CAR F) :CLOSE MODE)))
(LOOP FOR HOST IN *PATHNAME-HOST-LIST*
NCONC (SEND HOST :CLOSE-ALL-FILES MODE))))
(DEFUN ALL-OPEN-FILES ()
"Return a list of all file streams that are open."
(SI:ELIMINATE-DUPLICATES (APPEND (SEND TV:WHO-LINE-FILE-STATE-SHEET ':OPEN-STREAMS)
(LOOP FOR HOST IN *PATHNAME-HOST-LIST*
APPEND (SEND HOST ':OPEN-STREAMS)))))
(DEFUN DIRECTORY (PATHNAME)
"Common Lisp function to get the list of files in a directory.
The value is just a list of truenames.
You will get much more useful information by using FS:DIRECTORY-LIST."
(let ((path (pathname pathname)))
(unless (send path :name)
(setq path (send path :new-name :wild)))
(MAPCAR 'CAR (CDR (DIRECTORY-LIST path :fast)))))
stuff . It returns a list of lists , one for each file . The format
for PLIST are :
: BYTE - SIZE < number >
: DUMPED < boolean >
A pathname of NIL is treated specially and gives properties for all
(DEFUN DIRECTORY-LIST (FILENAME &REST OPTIONS)
"Return a listing of the directory specified in FILENAME, a pathname or string.
OPTIONS can include :NOERROR, :DELETED (mention deleted files),
:SORTED and :NO-EXTRA-INFO.
The value is an alist of elements (pathname . properties).
There is an element whose car is NIL. It describes the directory as a whole.
One of its properties is :PATHNAME, whose value is the directory's pathname."
(FORCE-USER-TO-LOGIN)
(SETQ FILENAME (MERGE-PATHNAME-DEFAULTS FILENAME NIL ':WILD ':WILD))
(SEND FILENAME ':DIRECTORY-LIST OPTIONS))
(DEFUN DIRECTORY-LIST-STREAM (FILENAME &REST OPTIONS)
"Return a stream which returns elements of a directory-list one by one.
The stream's operations are :ENTRY, to return the next element, and :CLOSE."
(FORCE-USER-TO-LOGIN)
(SETQ FILENAME (MERGE-PATHNAME-DEFAULTS FILENAME NIL ':WILD ':WILD))
(SEND FILENAME ':DIRECTORY-LIST-STREAM OPTIONS))
(DEFVAR *KNOWN-DIRECTORY-PROPERTIES*
'(((PARSE-DIRECTORY-BOOLEAN-PROPERTY PRIN1 :BOOLEAN)
. (:DELETED :DONT-DELETE :DONT-DUMP :DONT-REAP :DELETE-PROTECT :SUPERSEDE-PROTECT
:NOT-BACKED-UP :OFFLINE :TEMPORARY :CHARACTERS :DUMPED :DIRECTORY
:QFASLP :PDP10 :MAY-BE-REAPED))
((SUBSTRING PRINC :STRING) . (:ACCOUNT :AUTHOR :LINK-TO :PHYSICAL-VOLUME :PROTECTION
:VOLUME-NAME :PACK-NUMBER :READER :DISK-SPACE-DESCRIPTION
:INCREMENTAL-DUMP-TAPE :COMPLETE-DUMP-TAPE))
((ZWEI:PARSE-NUMBER PRINT-DECIMAL-PROPERTY :NUMBER)
. (:BLOCK-SIZE :BYTE-SIZE :GENERATION-RETENTION-COUNT :LENGTH-IN-BLOCKS
:LENGTH-IN-BYTES :DEFAULT-GENERATION-RETENTION-COUNT))
((PARSE-DIRECTORY-DATE-PROPERTY PRINT-DIRECTORY-DATE-PROPERTY :DATE)
. (:CREATION-DATE :MODIFICATION-DATE))
((PARSE-DIRECTORY-DATE-PROPERTY PRINT-UNIVERSAL-TIME-OR-NEVER-FOR-DIRLIST :DATE-OR-NEVER)
. ( :REFERENCE-DATE :INCREMENTAL-DUMP-DATE :COMPLETE-DUMP-DATE :DATE-LAST-EXPUNGED
:EXPIRATION-DATE))
((PARSE-SETTABLE-PROPERTIES PRINT-SETTABLE-PROPERTIES)
. (:SETTABLE-PROPERTIES :LINK-TRANSPARENCIES :DEFAULT-LINK-TRANSPARENCIES))
((PARSE-DIRECTORY-FREE-SPACE PRINT-DIRECTORY-FREE-SPACE) . (:PHYSICAL-VOLUME-FREE-BLOCKS))
((TIME:PARSE-INTERVAL-OR-NEVER TIME:PRINT-INTERVAL-OR-NEVER :TIME-INTERVAL-OR-NEVER)
. (:AUTO-EXPUNGE-INTERVAL))
))
(DEFVAR *TRANSFORMED-DIRECTORY-PROPERTIES* NIL
"Fast access to directory properties for READ-DIRECTORY-STREAM-ENTRY.
Each element is a list (first-char . alist)
where alist's elements look like (propstring propsymbol parser printer cvv-type).")
(DEFUN TRANSFORM-DIRECTORY-PROPERTIES ()
(SETQ *TRANSFORMED-DIRECTORY-PROPERTIES* NIL)
(DOLIST (ELT *KNOWN-DIRECTORY-PROPERTIES*)
(DOLIST (PROP (CDR ELT))
(LET* ((HASH (AREF (GET-PNAME PROP) 0))
(HASHELT
(OR (ASSQ HASH *TRANSFORMED-DIRECTORY-PROPERTIES*)
(CAR (PUSH (CONS HASH NIL) *TRANSFORMED-DIRECTORY-PROPERTIES*)))))
(PUSH (LIST* (GET-PNAME PROP) PROP (CAR ELT)) (CDR HASHELT))))))
(TRANSFORM-DIRECTORY-PROPERTIES)
Read the text describing one element of a directory - list from STREAM .
If this is the entry for NIL , which describes the whole directory ,
(DEFUN READ-DIRECTORY-STREAM-ENTRY (STREAM DEFAULTING-PATHNAME options &AUX PATH EOF IND FUN
(DEFAULT-FUN (SEND DEFAULTING-PATHNAME
':DIRECTORY-STREAM-DEFAULT-PARSER)))
(MULTIPLE-VALUE (PATH EOF)
(SEND STREAM ':LINE-IN))
(IF EOF NIL
(IF (ZEROP (ARRAY-ACTIVE-LENGTH PATH))
(SETQ PATH NIL)
(MULTIPLE-VALUE-BIND (DEV DIR NAM TYP VER)
(SEND DEFAULTING-PATHNAME ':PARSE-NAMESTRING NIL PATH)
(SETQ PATH (MAKE-PATHNAME-INTERNAL
(PATHNAME-HOST DEFAULTING-PATHNAME)
(OR DEV (PATHNAME-DEVICE DEFAULTING-PATHNAME))
(OR DIR (PATHNAME-DIRECTORY DEFAULTING-PATHNAME))
NAM (OR TYP ':UNSPECIFIC) VER))))
(LOOP AS LINE = (SEND STREAM ':LINE-IN)
AS LEN = (ARRAY-ACTIVE-LENGTH LINE)
UNTIL (ZEROP LEN)
AS I = (%STRING-SEARCH-CHAR #/SPACE LINE 0 LEN)
DO (LOOP NAMED FOO
FOR X IN (CDR (ASSQ (AREF LINE 0) *TRANSFORMED-DIRECTORY-PROPERTIES*))
WHEN (%STRING-EQUAL LINE 0 (CAR X) 0 I)
DO (RETURN (SETQ IND (CADR X) FUN (CADDR X)))
FINALLY (SETQ IND (INTERN (SUBSTRING LINE 0 I) SI:PKG-KEYWORD-PACKAGE)
FUN DEFAULT-FUN))
NCONC (LIST* IND (OR (NULL I) (SEND FUN LINE (1+ I))) NIL) INTO PLIST
this allows c - u m - x dired on " ai :* ; " to work !
(not (get-from-alternating-list plist :directory)))
(setq plist (list* :directory t plist)))
(RETURN (CONS PATH (IF PATH PLIST
(LIST* ':PATHNAME DEFAULTING-PATHNAME PLIST))))))))
(DEFUN PUSH-DIRECTORY-PROPERTY-ON-TYPE (TYPE PROP)
(LET ((X (OR (DOLIST (E *KNOWN-DIRECTORY-PROPERTIES*)
(IF (EQ (CADDAR E) TYPE) (RETURN E)))
(FERROR NIL "Unknown property type: ~A" TYPE))))
(OR (MEMQ TYPE (CDR X))
(PUSH PROP (CDR X))))
(TRANSFORM-DIRECTORY-PROPERTIES))
(DEFUN PARSE-RANDOM-SEXP (STRING START)
(LET ((*READ-BASE* 10.)
(*READTABLE* SI:INITIAL-READTABLE)
(*PACKAGE* SI:PKG-KEYWORD-PACKAGE))
(READ-FROM-STRING STRING NIL START)))
(DEFUN PRINT-RANDOM-SEXP (SEXP &OPTIONAL (STREAM *STANDARD-OUTPUT*))
(LET ((*PRINT-BASE* 10.)
(*NOPOINT T) (*PRINT-RADIX* NIL)
(*READTABLE* SI:INITIAL-READTABLE)
(*PACKAGE* SI:PKG-KEYWORD-PACKAGE))
(PRIN1 SEXP STREAM)))
Fast date parser for simple case of MM / DD / : MM : SS
(DEFUN PARSE-DIRECTORY-DATE-PROPERTY (STRING START &OPTIONAL END &AUX FLAG)
(OR END (SETQ END (ARRAY-ACTIVE-LENGTH STRING)))
addition to " protocol " of 10/3/85 : string consisting entirely of digits is
((NULL (STRING-SEARCH-NOT-SET "0123456789" STRING START END))
(LET ((*read-base* 10.)
(*print-base* 10.))
(READ-FROM-STRING STRING NIL START END)))
((NOT (FBOUNDP 'ENCODE-UNIVERSAL-TIME))
NIL)
((AND (OR (= END (+ START 8))
(SETQ FLAG (= END (+ START 17.))))
(EQL (CHAR STRING (+ START 2)) #//)
(EQL (CHAR STRING (+ START 5)) #//)
(OR (NULL FLAG)
(AND (EQL (CHAR STRING (+ START 8)) #/SPACE)
(EQL (CHAR STRING (+ START 11.)) #/:)
(EQL (CHAR STRING (+ START 14.)) #/:))))
(FLET ((GET-TWO-DIGITS (START)
(+ (* (DIGIT-CHAR-P (CHAR STRING START)) 10.)
(DIGIT-CHAR-P (CHAR STRING (1+ START))))))
(LET* ((MONTH (GET-TWO-DIGITS START))
(DAY (GET-TWO-DIGITS (+ START 3)))
(YEAR (GET-TWO-DIGITS (+ START 6)))
(HOURS (IF FLAG (GET-TWO-DIGITS (+ START 9.)) 0))
(MINUTES (IF FLAG (GET-TWO-DIGITS (+ START 12.)) 0))
(SECONDS (IF FLAG (GET-TWO-DIGITS (+ START 15.)) 0)))
The file job is wo nt to give dates of the form 00/00/00 for things made by
(AND (PLUSP MONTH)
(ENCODE-UNIVERSAL-TIME SECONDS MINUTES HOURS DAY MONTH YEAR)))))
(T
(CONDITION-CASE ()
(TIME:PARSE-UNIVERSAL-TIME STRING START END)
(ERROR NIL)))))
(DEFUN PRINT-UNIVERSAL-TIME-OR-NEVER-FOR-DIRLIST (TIME STREAM)
(IF (NULL TIME) (PRINC "never" STREAM)
(TIME:PRINT-UNIVERSAL-TIME TIME STREAM NIL ':mm//dd//yy)))
Printer which always prints MM / DD / : MM : SS
* * * This is a needed bug fix . Strict time protocol says that the year must be given as two digits .
What happens in year 2000 ?
(DEFUN PRINT-DIRECTORY-DATE-PROPERTY (UT STREAM)
(MULTIPLE-VALUE-BIND (SEC MIN HR DAY MON YR)
(TIME:DECODE-UNIVERSAL-TIME UT)
(FORMAT STREAM "~2,'0D//~2,'0D//~2,'0D ~2,'0D:~2,'0D:~2,'0D"
MON DAY (MOD YR 100.) HR MIN SEC))))
(DEFUN PARSE-DIRECTORY-BOOLEAN-PROPERTY (STRING START)
(LET ((TEM (READ-FROM-STRING STRING NIL START)))
(IF (EQ TEM ':NIL) NIL TEM)))
(DEFUN PARSE-SETTABLE-PROPERTIES (STRING START)
(IF (SETQ START (STRING-SEARCH-NOT-CHAR #/SPACE STRING START))
(DO ((I START (1+ J))
(J)
(LIST NIL))
(NIL)
(SETQ J (STRING-SEARCH-CHAR #/SPACE STRING I))
(PUSH (INTERN (STRING-UPCASE (SUBSTRING STRING I J)) "") LIST)
(OR J (RETURN (NREVERSE LIST))))
(DEFUN PRINT-SETTABLE-PROPERTIES (PROPERTIES &OPTIONAL (*STANDARD-OUTPUT* *STANDARD-OUTPUT*))
(AND (LISTP PROPERTIES)
(DO ((TAIL PROPERTIES (CDR TAIL))) ((NULL TAIL))
(PRINC (CAR TAIL))
(IF (CDR TAIL) (TYO #/SPACE)))))
(DEFUN PARSE-DIRECTORY-FREE-SPACE (STRING START &AUX LIST)
(DO ((I START (1+ I))
(J)
(VOL))
(NIL)
(OR (SETQ J (STRING-SEARCH-CHAR #/: STRING I))
(RETURN))
(SETQ VOL (SUBSTRING STRING I J))
(SETQ I (STRING-SEARCH-CHAR #/, STRING (SETQ J (1+ J))))
(PUSH (CONS VOL (ZWEI:PARSE-NUMBER STRING J I)) LIST)
(OR I (RETURN)))
(NREVERSE LIST))
(DEFUN PRINT-DIRECTORY-FREE-SPACE (ALIST &OPTIONAL (*STANDARD-OUTPUT* *STANDARD-OUTPUT*))
(DO ((TAIL ALIST (CDR TAIL)))
((NULL TAIL))
(PRINC (CAAR TAIL))
(PRINC ":")
(PRINC (CDAR TAIL))
(IF (CDDR TAIL) (PRINC ","))))
(DEFUN PRINT-DECIMAL-PROPERTY (PROP STREAM)
(LET ((*PRINT-BASE* 10.)
(*NOPOINT T)
(*PRINT-RADIX* NIL)
(*READTABLE* SI:INITIAL-READTABLE))
(PRIN1 PROP STREAM)))
First argument may be a host name for convenience
(DEFUN ALL-DIRECTORIES (&OPTIONAL (PATHNAME USER-LOGIN-MACHINE) &REST OPTIONS &AUX TEM)
"Return a list of pathnames describing all directories on a specified host.
The argument is either a host, a hostname, or a pathname or namestring
whose host is used. The only option is :NOERROR."
(FORCE-USER-TO-LOGIN)
(IF (AND (TYPEP PATHNAME '(OR STRING SI:HOST))
(SETQ TEM (GET-PATHNAME-HOST PATHNAME T)))
(SETQ PATHNAME (SEND (SAMPLE-PATHNAME TEM) ':NEW-PATHNAME
':DEVICE ':WILD ':DIRECTORY ':WILD))
(SETQ PATHNAME (MERGE-PATHNAME-DEFAULTS PATHNAME)))
(SEND PATHNAME ':ALL-DIRECTORIES OPTIONS))
(DEFMETHOD (PATHNAME :ALL-DIRECTORIES) (OPTIONS)
(LET ((ERROR (MAKE-CONDITION 'UNKNOWN-OPERATION "Can't list all directories on file system of ~A."
SELF ':ALL-DIRECTORIES)))
(IF (MEMQ ':NOERROR OPTIONS) ERROR (SIGNAL ERROR))))
(DEFMETHOD (MEANINGFUL-ROOT-MIXIN :ALL-DIRECTORIES) (OPTIONS)
(LOOP FOR FILE IN (CDR (APPLY #'DIRECTORY-LIST
(SEND SELF ':NEW-PATHNAME
':DIRECTORY ':ROOT
':NAME ':WILD
':TYPE ':WILD
':VERSION ':WILD)
OPTIONS))
WHEN (GET FILE ':DIRECTORY)
COLLECT (NCONS (SEND (CAR FILE) ':PATHNAME-AS-DIRECTORY))))
(DEFUN COMPLETE-PATHNAME (DEFAULTS STRING TYPE VERSION &REST OPTIONS &AUX PATHNAME)
"Attempt to complete the filename STRING, returning the results.
DEFAULTS, TYPE and VERSION are as in MERGE-PATHNAME-DEFAULTS.
OPTIONS are :DELETED, :READ (file is for input), :WRITE (it's for output),
:OLD (only existing files allowed), :NEW-OK (new files are allowed too).
There are two values: a string which is the completion as far as possible,
and SUCCESS, which can be :OLD, :NEW or NIL.
:OLD says that the returned string names an existing file,
:NEW says that the returned string is no file but some completion was done,
NIL says that no completion was possible."
(DECLARE (VALUES STRING SUCCESS))
(FORCE-USER-TO-LOGIN)
(MULTIPLE-VALUE-BIND (HOST START END)
(PARSE-PATHNAME-FIND-COLON STRING)
(AND HOST (SETQ START (OR (STRING-SEARCH-NOT-CHAR #/SPACE STRING START END) END)
STRING (SUBSTRING STRING START END)))
(SETQ PATHNAME (DEFAULT-PATHNAME DEFAULTS HOST TYPE VERSION T)))
(SEND PATHNAME ':COMPLETE-STRING STRING OPTIONS))
(defun pathname-completion-list (defaults string type version &rest options
&AUX pathname whole-directory directory-pathname
directory-list)
"Returns a list of possible completions of string."
type version
(declare (values string success))
(force-user-to-login)
(setq pathname (fs:merge-pathname-defaults string defaults ':WILD ':WILD))
now get a pathname with just the first word of the name and a magic
(let ((name (send pathname ':NAME)))
(if (or (null name) (equalp name "")
(eq ':WILD name))
(setq whole-directory T
directory-pathname
(send pathname ':NEW-PATHNAME ':NAME ':WILD ':VERSION ':WILD))
(let ((position (string-search-set '(#/SPACE #/. #/-) name)))
(if position (setq name (substring name 0 position))))
(setq name (string-append name "*"))
(let ((temp-pathname (fs:parse-pathname name (send pathname ':HOST))))
(setq directory-pathname (send pathname
':NEW-PATHNAME
':NAME (send temp-pathname ':NAME) ':VERSION ':WILD)))))
(setq directory-list (send directory-pathname ':DIRECTORY-LIST options))
(if (errorp directory-list)
directory-list
(setq directory-list (cdr directory-list))
(if (null whole-directory)
(multiple-value-bind (NIL matching-subset)
(zwei:complete-string (send pathname ':NAME)
(LOOP FOR entry IN directory-list
AS pathname = (car entry)
AS name = (send pathname ':NAME)
COLLECT (list name pathname))
'(#/. #/- #/SPACE))
(setq directory-list
(LOOP FOR (pathname-name pathname) IN matching-subset
COLLECT pathname)))
(setq directory-list
(LOOP FOR entry IN directory-list
COLLECT (car entry))))
directory-list))
(DEFUN CHANGE-FILE-PROPERTIES (PATHNAME ERROR-P &REST PROPERTIES)
"Change some file properties of a file, specified as pathname or namestring.
The file properties are those that are returned by FILE-PROPERTIES.
PROPERTIES are the alternating properties and new values."
(FORCE-USER-TO-LOGIN)
(SETQ PATHNAME (MERGE-PATHNAME-DEFAULTS PATHNAME))
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ ERROR-P '(:RETRY :REPROMPT))
(PATHNAME FILE-ERROR)
(LEXPR-SEND PATHNAME ':CHANGE-PROPERTIES ERROR-P PROPERTIES)))
(DEFUN FILE-PROPERTIES (PATHNAME &OPTIONAL (ERROR-P T))
"Return the property list of a file, specified as a pathname or namestring.
These properties are the same ones that appear in a directory-list.
The car of the value is the truename.
The second value is a list of properties whose values can be changed."
(DECLARE (VALUES PROPERTIES SETTABLE-PROPERTIES))
(FORCE-USER-TO-LOGIN)
(SETQ PATHNAME (MERGE-PATHNAME-DEFAULTS PATHNAME))
(MULTIPLE-VALUE-BIND (PLIST SETTABLE-PROPERTIES)
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ ERROR-P '(:RETRY :REPROMPT))
(PATHNAME FILE-ERROR)
(SEND PATHNAME ':PROPERTIES ERROR-P))
(OR SETTABLE-PROPERTIES
(IF (SEND PATHNAME ':OPERATION-HANDLED-P ':PROPERTY-SETTABLE-P)
(SETQ SETTABLE-PROPERTIES
(UNION (SEND PATHNAME ':DEFAULT-SETTABLE-PROPERTIES)
(LOOP FOR IND IN (CDR PLIST) BY 'CDDR
WHEN (SEND PATHNAME ':PROPERTY-SETTABLE-P IND)
COLLECT IND)))))
(VALUES PLIST SETTABLE-PROPERTIES)))
(DEFUN EXPUNGE-DIRECTORY (PATHNAME &REST OPTIONS &KEY (ERROR T))
"Expunge all deleted files in the directory specified in PATHNAME.
PATHNAME can be a pathname or a namestring."
(DECLARE (VALUES BLOCKS-FREED))
(FORCE-USER-TO-LOGIN)
(OR (SEND (SETQ PATHNAME (FS:PARSE-PATHNAME PATHNAME)) :NAME)
(SETQ PATHNAME (SEND PATHNAME :NEW-NAME :WILD)))
(SETQ PATHNAME (FS:MERGE-PATHNAME-DEFAULTS PATHNAME NIL :WILD :WILD))
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ ERROR '(:RETRY :REPROMPT))
(PATHNAME FILE-ERROR)
(LEXPR-SEND PATHNAME :EXPUNGE OPTIONS)))
(DEFMETHOD (PATHNAME :EXPUNGE) (&REST ARGS)
(LET ((ERROR (MAKE-CONDITION 'UNKNOWN-OPERATION "Can't expunge or undelete on file system of ~A."
SELF ':EXPUNGE))
(ERRORP (COND ((NULL ARGS) T)
((NULL (CDR ARGS))
(CAR ARGS))
(T (GET (LOCF ARGS) ':ERROR)))))
(IF ERRORP (SIGNAL ERROR) ERROR)))
(DEFUN REMOTE-CONNECT (PATHNAME &REST OPTIONS &KEY (ERROR T) ACCESS)
"Tell file servers to connect or access to a directory.
PATHNAME, either a pathname or a namestring, specifies both the host
and the device and directory to connect or access to."
ERROR ACCESS
(FORCE-USER-TO-LOGIN)
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ ERROR '(:RETRY :REPROMPT))
(PATHNAME FILE-ERROR)
(LEXPR-SEND (MERGE-PATHNAME-DEFAULTS PATHNAME NIL) ':REMOTE-CONNECT OPTIONS)))
(DEFMETHOD (PATHNAME :REMOTE-CONNECT) (&KEY ERROR ACCESS)
ACCESS
(LET ((CONDITION
(MAKE-CONDITION 'UNKNOWN-OPERATION "Can't do remote connect or access on file system of ~A."
SELF ':REMOTE-CONNECT)))
(IF ERROR (SIGNAL CONDITION) CONDITION)))
(DEFUN ENABLE-CAPABILITIES (HOST &REST CAPABILITIES)
"Tell file servers on HOST to enable some capabilities.
Defaults are according to operating system."
(FORCE-USER-TO-LOGIN)
(LEXPR-SEND (GET-PATHNAME-HOST HOST) ':ENABLE-CAPABILITIES CAPABILITIES))
(DEFUN DISABLE-CAPABILITIES (HOST &REST CAPABILITIES)
"Tell file servers on HOST to disable some capabilities.
Defaults are according to operating system."
(FORCE-USER-TO-LOGIN)
(LEXPR-SEND (GET-PATHNAME-HOST HOST) ':DISABLE-CAPABILITIES CAPABILITIES))
(DEFUN CREATE-DIRECTORY (PATHNAME &KEY (ERROR T) RECURSIVE)
"Create a directory specified in PATHNAME, either a pathname or a namestring.
RECURSIVE non-NIL says if this directory is supposed to be a subdirectory
of another directory which also fails to exist, create that one too, etc."
(FORCE-USER-TO-LOGIN)
(LET ((PN (MERGE-PATHNAME-DEFAULTS PATHNAME NIL)))
(CONDITION-CASE-IF RECURSIVE ()
(FILE-RETRY-NEW-PATHNAME-IF (MEMQ ERROR '(:RETRY :REPROMPT))
(PATHNAME FILE-ERROR)
(SEND PN :CREATE-DIRECTORY :ERROR ERROR))
(DIRECTORY-NOT-FOUND
(CREATE-DIRECTORY (SEND PN :DIRECTORY-PATHNAME-AS-FILE) :RECURSIVE T :error error)
(CREATE-DIRECTORY PN :ERROR ERROR)))))
(DEFMETHOD (PATHNAME :CREATE-LINK) (LINK-TO &KEY (ERROR T))
(DECLARE (IGNORE LINK-TO))
(LET ((CONDITION
(MAKE-CONDITION 'UNKNOWN-OPERATION "Can't create links on file system of ~A."
SELF ':CREATE-LINK)))
(IF ERROR (SIGNAL CONDITION) CONDITION)))
(DEFMETHOD (PATHNAME :CREATE-DIRECTORY) (&KEY (ERROR T))
(LET ((CONDITION
(MAKE-CONDITION 'UNKNOWN-OPERATION "Can't create directory on file system of ~A."
SELF :CREATE-DIRECTORY)))
(IF ERROR (SIGNAL CONDITION) CONDITION)))
This helps losers who do n't have -*- lines get the right mode on TWENEX , etc .
(DEFCONST *FILE-TYPE-MODE-ALIST*
'((:LISP . :LISP)
(:TEXT . :TEXT)
(:MIDAS . :MIDAS)
(:DOC . :TEXT)
(:MSS . :SCRIBE)
(:PALX . :TEXT)
(:MAC . :MIDAS)
(:TASM . :MIDAS)
(:C . :PL1)
(:CLU . :PL1)
(:PL1 . :PL1)
(:scheme . :scheme))
"Alist mapping standard pathname type component strings into editor major mode name keywords.")
But it is better to call FILE - EXTRACT - ATTRIBUTE - LIST if you want that .
(DEFF READ-SYNTAX-PLIST 'READ-ATTRIBUTE-LIST)
(DEFF FILE-READ-PROPERTY-LIST 'READ-ATTRIBUTE-LIST)
(DEFF FILE-READ-ATTRIBUTE-LIST 'READ-ATTRIBUTE-LIST)
(DEFUN READ-ATTRIBUTE-LIST (PATHNAME STREAM &AUX PLIST)
"Return the attribute list read from STREAM, and put properties on PATHNAME.
STREAM can be reading either a text file or a QFASL file.
PATHNAME should be the generic pathname that was opened."
(SETQ PLIST (FILE-EXTRACT-ATTRIBUTE-LIST STREAM))
First remove any properties that we put on the last time we parsed
(AND PATHNAME
(LET ((OLD-PLIST (SEND PATHNAME ':GET 'LAST-FILE-PLIST)))
(DO ((L OLD-PLIST (CDDR L))) ((NULL L))
(SEND PATHNAME ':REMPROP (CAR L)))))
(AND PATHNAME
(DO ((L PLIST (CDDR L)))
((NULL L))
(SEND PATHNAME ':PUTPROP (SECOND L) (FIRST L))))
(AND PATHNAME
(SEND PATHNAME ':PUTPROP PLIST 'LAST-FILE-PLIST))
PLIST)
(DEFF FILE-EXTRACT-PROPERTY-LIST 'EXTRACT-ATTRIBUTE-LIST)
(DEFF EXTRACT-PROPERTY-LIST 'EXTRACT-ATTRIBUTE-LIST)
(DEFF FILE-EXTRACT-ATTRIBUTE-LIST 'EXTRACT-ATTRIBUTE-LIST)
(DEFUN EXTRACT-ATTRIBUTE-LIST (STREAM &AUX WO PLIST PATH MODE ERROR)
"Return the attribute list read from STREAM.
STREAM can be reading either a text file or a QFASL file."
(declare (values plist error))
(SETQ WO (SEND STREAM ':WHICH-OPERATIONS))
(COND ((MEMQ ':SYNTAX-PLIST WO)
(SETQ PLIST (SEND STREAM ':SYNTAX-PLIST)))
((NOT (SEND STREAM ':CHARACTERS))
(SETQ PLIST (SI:QFASL-STREAM-PROPERTY-LIST STREAM)))
((AND (MEMQ ':READ-INPUT-BUFFER WO)
(MULTIPLE-VALUE-BIND (BUFFER START END)
(SEND STREAM ':READ-INPUT-BUFFER)
(AND BUFFER
(NOT (STRING-SEARCH "-*-" BUFFER START END)))))
NIL)
((NOT (MEMQ ':SET-POINTER WO))
NIL)
(T (DO ((LINE) (EOF)) (NIL)
(MULTIPLE-VALUE (LINE EOF) (SEND STREAM ':LINE-IN NIL))
(COND ((NULL LINE)
(SEND STREAM ':SET-POINTER 0)
(RETURN NIL))
((STRING-SEARCH "-*-" LINE)
(SETQ LINE (FILE-GRAB-WHOLE-PROPERTY-LIST LINE STREAM))
(SEND STREAM ':SET-POINTER 0)
(SETF (VALUES PLIST ERROR) (FILE-PARSE-PROPERTY-LIST LINE))
(RETURN NIL))
((OR EOF (STRING-SEARCH-NOT-SET '(#/SPACE #/TAB) LINE))
(SEND STREAM ':SET-POINTER 0)
(RETURN NIL))))))
(AND (NOT (GETF PLIST ':MODE))
(MEMQ ':PATHNAME WO)
(SETQ PATH (SEND STREAM ':PATHNAME))
(SETQ MODE (CDR (ASSOC (SEND PATH ':TYPE) *FILE-TYPE-MODE-ALIST*)))
(PUTPROP (LOCF PLIST) MODE ':MODE))
Infer : Iff MODE or SYNTAX is CommonLISP or equivalent , set READTABLE
( this assumes ZL is still " traditional " and default ! )
(when (and (null (getf plist :readtable))
(or (member (getf plist :mode) '(:commonlisp :common-lisp))
(eq (getf plist :syntax) :CL)))
(putprop (locf plist) :CL :readtable))
Finally return PLIST and any error from along the way .
(VALUES PLIST ERROR))
(DEFUN FILE-GRAB-WHOLE-PROPERTY-LIST (STARTING-LINE STREAM)
(DO ((START (+ 3 (STRING-SEARCH "-*-" STARTING-LINE)) 0)
(STRING STARTING-LINE (SEND STREAM ':LINE-IN))
(COUNT 0 (1+ COUNT))
(ACCUM (MAKE-ARRAY 0 ':TYPE ART-STRING ':FILL-POINTER 0)))
((= COUNT 100.)
(FORMAT *QUERY-IO* "~&The file ~A has an unterminated property list line."
(SEND STREAM ':PATHNAME))
"")
(SETQ ACCUM (STRING-NCONC ACCUM #/NEWLINE STRING))
(IF (STRING-SEARCH "-*-" STRING START)
(RETURN ACCUM))))
(DEFUN FILE-PARSE-PROPERTY-LIST (STRING &OPTIONAL (START 0) (END (LENGTH STRING))
&AUX PLIST ERROR
(*READ-BASE* 10.)
(*PACKAGE* SI:PKG-KEYWORD-PACKAGE)
(*READTABLE* SI:INITIAL-COMMON-LISP-READTABLE))
(AND STRING
(ARRAYP STRING)
(= (ARRAY-ELEMENT-SIZE STRING) 8)
(SETQ START (STRING-SEARCH "-*-" STRING START END))
(SETQ END (STRING-SEARCH "-*-" STRING (SETQ START (+ START 3)) END))
(IF (NOT (%STRING-SEARCH-CHAR #/: STRING START END))
(SETQ PLIST (LIST ':MODE (READ-FROM-SUBSTRING STRING START END)))
(DO ((S START (1+ SEMI-IDX))
(COLON-IDX) (SEMI-IDX) (SYM) (ELEMENT NIL NIL) (DONE)
(WIN-THIS-TIME NIL NIL))
(NIL)
(SETQ DONE T SEMI-IDX END))
(OR (SETQ COLON-IDX (%STRING-SEARCH-CHAR #/: STRING S SEMI-IDX))
(RETURN NIL))
(IGNORE-ERRORS
(OR (SETQ SYM (READ-FROM-SUBSTRING STRING S COLON-IDX))
(RETURN NIL))
(IGNORE-ERRORS
(IF (%STRING-SEARCH-CHAR #/, STRING (SETQ S (1+ COLON-IDX)) SEMI-IDX)
(DO ((COMMA-IDX) (ELEMENT-DONE))
(NIL)
(OR (SETQ COMMA-IDX (%STRING-SEARCH-CHAR #/, STRING S SEMI-IDX))
(SETQ ELEMENT-DONE T COMMA-IDX SEMI-IDX))
(SETQ ELEMENT
(NCONC ELEMENT
(NCONS (LET ((TEM (READ-FROM-SUBSTRING STRING S COMMA-IDX)))
(setq tem (nsubst nil :nil tem))))))
(AND ELEMENT-DONE (RETURN NIL))
(SETQ S (1+ COMMA-IDX)))
(SETQ ELEMENT (LET ((TEM (READ-FROM-SUBSTRING STRING S SEMI-IDX)))
(setq tem (nsubst nil :nil tem)))))
(SETQ WIN-THIS-TIME T))
(UNLESS WIN-THIS-TIME
(SETQ ERROR T))
(AND DONE (RETURN NIL)))))
(VALUES PLIST ERROR))
(DEFUN READ-FROM-SUBSTRING (STRING &OPTIONAL (START 0) (END (LENGTH STRING)))
(READ-FROM-STRING STRING NIL START END))
(DEFF FILE-PROPERTY-BINDINGS 'FILE-ATTRIBUTE-BINDINGS)
(DEFUN (:SYNTAX FILE-ATTRIBUTE-BINDINGS) (IGNORE IGNORE VAL)
(VALUES (NCONS '*READTABLE*) (NCONS (SI:FIND-READTABLE-NAMED VAL :ERROR))))
(DEFUN FILE-ATTRIBUTE-BINDINGS (PATHNAME)
"Return bindings to be made according to the attribute list of PATHNAME.
READ-ATTRIBUTE-LIST should have been done previously on that pathname.
Returns two values, a list of special variables and a list of values to bind them to.
Use the two values in a PROGV if you READ expressions from the file."
(ATTRIBUTE-BINDINGS-FROM-LIST
(IF (LOCATIVEP PATHNAME) (CONTENTS PATHNAME) (SEND PATHNAME :PROPERTY-LIST))
PATHNAME))
(DEFUN ATTRIBUTE-BINDINGS-FROM-LIST (ATTLIST PATHNAME)
(DO ((ATTLIST ATTLIST (CDDR ATTLIST))
(VARS NIL)
(VALS NIL)
(BINDING-FUNCTION))
((NULL ATTLIST)
(VALUES VARS VALS))
(AND (SETQ BINDING-FUNCTION (GET (CAR ATTLIST) 'FILE-ATTRIBUTE-BINDINGS))
(MULTIPLE-VALUE-BIND (VARS1 VALS1)
(FUNCALL BINDING-FUNCTION PATHNAME (CAR ATTLIST) (CADR ATTLIST))
(SETQ VARS (NCONC VARS1 VARS)
VALS (NCONC VALS1 VALS))))))
(DEFUN EXTRACT-ATTRIBUTE-BINDINGS (STREAM)
"Return a list of variables and values corresponding to STREAM's attribute list.
Useful for arguments to the PROGV special form."
(ATTRIBUTE-BINDINGS-FROM-LIST
(EXTRACT-ATTRIBUTE-LIST STREAM)
(DEFUN (:PACKAGE FILE-ATTRIBUTE-BINDINGS) (IGNORE IGNORE PKG)
(VALUES (NCONS '*PACKAGE*) (NCONS (PKG-FIND-PACKAGE PKG :ERROR *package*))))
(defun (:compile-in-roots file-attribute-bindings) (ignore ignore roots-to-compile-in)
(values (ncons 'si:roots-to-compile-in)
(ncons roots-to-compile-in)))
(DEFUN (:BASE FILE-ATTRIBUTE-BINDINGS) (FILE IGNORE BSE)
(UNLESS (TYPEP BSE '(INTEGER 1 36.))
(FERROR 'INVALID-FILE-ATTRIBUTE "File ~A has an illegal -*- BASE:~*~S -*-"
FILE ':BASE BSE))
(VALUES (LIST* '*READ-BASE* '*PRINT-BASE* NIL) (LIST* BSE BSE NIL)))
(DEFUN (:COLD-LOAD FILE-ATTRIBUTE-BINDINGS) (IGNORE IGNORE FLAG)
(VALUES (NCONS 'SI:FILE-IN-COLD-LOAD) (NCONS FLAG)))
(DEFVAR-RESETTABLE THIS-IS-A-PATCH-FILE NIL NIL
"Non-NIL while loading a patch file.")
(DEFUN (:PATCH-FILE FILE-ATTRIBUTE-BINDINGS) (IGNORE IGNORE VAL)
(VALUES (NCONS 'THIS-IS-A-PATCH-FILE) (NCONS VAL)))
( DEFUN (: COMMON - LISP FILE - ATTRIBUTE - BINDINGS ) ( IGNORE IGNORE )
' SI : INTERPRETER - FUNCTION - ENVIRONMENT ' * NOPOINT
(DEFUN (:READTABLE FILE-ATTRIBUTE-BINDINGS) (IGNORE IGNORE VAL)
(VALUES (NCONS '*READTABLE*) (NCONS (SI:FIND-READTABLE-NAMED VAL :ERROR))))
(DEFUN (:FONTS FILE-ATTRIBUTE-BINDINGS) (IGNORE IGNORE IGNORE)
(VALUES (NCONS 'SI:READ-DISCARD-FONT-CHANGES) (NCONS T)))
(DEFVAR *NAMED-READER-ALIST* '((:T ZL:READ)(NIL ZL:READ))
"An alist of (:keyword <function>) for names of readers in the file mode line
Note these take args like ZL:READ")
(DEFUN (:READ FILE-ATTRIBUTE-BINDINGS) (FILE IGNORE VAL)
(VALUES (NCONS 'SI:*READFILE-READ-FUNCTION*)
(NCONS (OR (CADR (ASSQ VAL *NAMED-READER-ALIST*))
(FERROR 'INVALID-FILE-ATTRIBUTE "File ~A has an illegal -*- READ:~*~S -*-"
FILE :READ VAL)))))
This returns the -*- properties for a ascii file , the qfasl properties for a qfasl file
(DEFF PATHNAME-SYNTAX-PLIST 'FILE-ATTRIBUTE-LIST)
(DEFF PATHNAME-ATTRIBUTE-LIST 'FILE-ATTRIBUTE-LIST)
(DEFF FILE-PROPERTY-LIST 'FILE-ATTRIBUTE-LIST)
(DEFUN FILE-ATTRIBUTE-LIST (PATHNAME)
"Return the attribute list for the file specified by PATHNAME, a pathname or namestring."
(WITH-OPEN-FILE (STREAM PATHNAME ':CHARACTERS ':DEFAULT)
(COND ((SEND STREAM ':SEND-IF-HANDLES ':FILE-PLIST))
((SEND STREAM ':CHARACTERS)
(EXTRACT-ATTRIBUTE-LIST STREAM))
(T
(SI:QFASL-STREAM-PROPERTY-LIST STREAM)))))
(DEFVAR LOAD-PATHNAME-DEFAULTS :UNBOUND
"Now the same as *default-pathname-defaults*
Used to be used as the pathname-defaults list for LOAD, COMPILE-FILE, etc.")
(FORWARD-VALUE-CELL 'LOAD-PATHNAME-DEFAULTS '*DEFAULT-PATHNAME-DEFAULTS*)
(DEFVAR *LOAD-VERBOSE* T
"Non-NIL means LOAD can print a message saying what it is loading.
Can be overridden by the :VERBOSE keyword when LOAD is called.")
(DEFVAR *LOAD-SET-DEFAULT-PATHNAME* T
"Non-NIL means LOAD sets the default pathname to the name of the file loaded.
Can be overridden by the :SET-DEFAULT-PATHNAME keyword when LOAD is called.")
(DEFUN LOAD (FILE &REST KEY-OR-POSITIONAL-ARGS)
"Load the specified text file or QFASL file or input stream.
If the specified filename has no type field, we try QFASL and then LISP and then INIT.
Regardless of the filename type, we can tell QFASL files from text files.
if missing or NIL ,
the package specified by the file's attribute list is used.
VERBOSE non-NIL says it's ok to print a message saying what is being loaded.
Default comes from *LOAD-VERBOSE*, normally T.
SET-DEFAULT-PATHNAME non-NIL says set the default pathname for LOAD
to the name of this file. Default from *LOAD-SET-DEFAULT-PATHNAME*, normally T.
IF-DOES-NOT-EXIST NIL says just return NIL for file-not-found. Default T.
In all other cases the value is the truename of the loaded file, or T.
PRINT non-NIL says print all forms loaded."
(DECLARE (ARGLIST FILE &KEY PACKAGE
(VERBOSE *LOAD-VERBOSE*)
(SET-DEFAULT-PATHNAME *LOAD-SET-DEFAULT-PATHNAME*)
(IF-DOES-NOT-EXIST T)
PRINT))
(when fs:this-is-a-patch-file
(cerror "Proceed to LOAD ~S anyway."
"The use of LOAD in a patch file is not recommended."
file))
(IF (AND (CAR KEY-OR-POSITIONAL-ARGS)
(MEMQ (CAR KEY-OR-POSITIONAL-ARGS)
'(:PACKAGE :PRINT :IF-DOES-NOT-EXIST :SET-DEFAULT-PATHNAME :VERBOSE)))
(LET ((SI::PRINT-LOADED-FORMS (GETF KEY-OR-POSITIONAL-ARGS ':PRINT)))
(LOAD-1 FILE
(GETF KEY-OR-POSITIONAL-ARGS ':PACKAGE)
(NOT (GETF KEY-OR-POSITIONAL-ARGS ':IF-DOES-NOT-EXIST T))
(NOT (GETF KEY-OR-POSITIONAL-ARGS ':SET-DEFAULT-PATHNAME
*LOAD-SET-DEFAULT-PATHNAME*))
(NOT (GETF KEY-OR-POSITIONAL-ARGS ':VERBOSE *LOAD-VERBOSE*))))
(APPLY #'LOAD-1 FILE KEY-OR-POSITIONAL-ARGS)))
(DEFUN LOAD-1 (FILE &OPTIONAL PKG NONEXISTENT-OK-FLAG DONT-SET-DEFAULT-P NO-MSG-P)
(IF (STREAMP FILE)
(PROGN
(OR DONT-SET-DEFAULT-P
(SET-DEFAULT-PATHNAME (SEND FILE :PATHNAME) LOAD-PATHNAME-DEFAULTS))
(CATCH-ERROR-RESTART (EH:DEBUGGER-CONDITION "Give up on loading ~A."
(SEND FILE :PATHNAME))
(ERROR-RESTART (EH:DEBUGGER-CONDITION "Retry loading ~A." (SEND FILE :PATHNAME))
(FUNCALL (IF (SEND FILE :CHARACTERS)
#'SI::READFILE-INTERNAL #'SI::FASLOAD-INTERNAL)
FILE PKG NO-MSG-P)
(OR (SEND FILE :SEND-IF-HANDLES :TRUENAME) T))))
(LET ((PATHNAME (PARSE-PATHNAME FILE)))
(CATCH-ERROR-RESTART (EH:DEBUGGER-CONDITION "Give up on loading ~A." PATHNAME)
(ERROR-RESTART (EH:DEBUGGER-CONDITION "Retry loading ~A." PATHNAME)
(FLET ((KLUDGE ()
(CONDITION-CASE-IF NONEXISTENT-OK-FLAG ()
(WITH-OPEN-FILE-SEARCH
(STREAM ('LOAD LOAD-PATHNAME-DEFAULTS
(NOT NONEXISTENT-OK-FLAG))
(VALUES
(LIST (SI:PATHNAME-DEFAULT-BINARY-FILE-TYPE
PATHNAME)
:LISP :INIT)
PATHNAME)
:CHARACTERS :DEFAULT)
(OR DONT-SET-DEFAULT-P
(SET-DEFAULT-PATHNAME (SEND STREAM :PATHNAME)
LOAD-PATHNAME-DEFAULTS))
(FUNCALL (IF (SEND STREAM :CHARACTERS)
#'SI::READFILE-INTERNAL #'SI::FASLOAD-INTERNAL)
STREAM PKG NO-MSG-P)
(SEND STREAM :TRUENAME))
(MULTIPLE-FILE-NOT-FOUND
NIL))))
(KLUDGE)))))))
Avoid lossage in LOAD-1 before this function is loaded from MAKSYS .
(IF (NOT (FBOUNDP 'SI:PATHNAME-DEFAULT-BINARY-FILE-TYPE))
(FSET 'SI:PATHNAME-DEFAULT-BINARY-FILE-TYPE
'(LAMBDA (IGNORE) ':QFASL)))
(DEFUN READFILE (FILE-NAME &OPTIONAL PKG NO-MSG-P)
"Read and evaluate the expressions from a text file.
if it is NIL ,
the file's attribute list specifies the package.
NO-MSG-P suppresses the message saying that a file is being loaded."
(WITH-OPEN-STREAM (STREAM (SEND (MERGE-PATHNAME-DEFAULTS
FILE-NAME LOAD-PATHNAME-DEFAULTS NIL)
:OPEN-CANONICAL-DEFAULT-TYPE :LISP
:ERROR :REPROMPT))
(SET-DEFAULT-PATHNAME (SEND STREAM :PATHNAME) LOAD-PATHNAME-DEFAULTS)
(SI::READFILE-INTERNAL STREAM PKG NO-MSG-P)))
|
b675a681af4ce36c998126c44dd6a361cf7f00b2d530d6c82f1f51e7b1b26db5 | zeniuseducation/poly-euler | prob51-100.clj | (ns euler.prob51-100)
(load-file "math.clj")
Do nt know berapa
(defn sqr [x] (* x x))
(defn a->bc
"Consider a^2 + b^2 = c^2, this fn returns the value of a+b+c from a
given a, or nil if it's impossible to construct integer-value b and
c from a given a."
[a lim]
(let [asqr (sqr a)]
(loop [b (inc a)]
(if (or (> (* 2 b) asqr)
(> (+ a b) (* 2 (/ lim 3))))
nil
(if-let [sol (loop [x 1]
(let [tmp (* x (+ x (* 2 b)))]
(if (or (> tmp asqr)
(> (+ a b (+ b x)) lim))
nil
(if (= tmp asqr)
(+ a b (+ b x))
(recur (inc x))))))]
sol
(recur (inc b)))))))
(defn lazyfor
[a lim]
(let [asqr (sqr a)]
(for [b (iterate inc a)
:while (or (<= (* 2 b) asqr)
(<= (+ a b) (* 2 (/ lim 3))))
:let [sol (loop [x 1]
(let [tmp (* x (+ x (* 2 b)))]
(if (or (> tmp asqr)
(> (+ a b (+ b x)) lim))
nil
(if (= tmp asqr)
(+ a b (+ b x))
(recur (inc x))))))]] sol)))
(defn soulmate
[lim]
(->> (inc (quot lim 3))
(range 3)
(mapcat #(lazyfor % lim))
(remove nil?)
(group-by identity)
(filter #(= 1 (count (second %))))
count))
(defn foulmate
[lim]
(->> (inc (quot lim 3))
(range 3)
(map #(a->bc % lim))
(remove nil?)
frequencies
(filter #(= 1 (val %)))
count))
Problem 61
(defn figurates
[ftype n]
(cond (= ftype 3) (/ (* n (inc n)) 2)
(= ftype 4) (sqr n)
(= ftype 5) (/ (* n (dec (* 3 n))) 2)
(= ftype 6) (* n (dec (* 2 n)))
(= ftype 7) (/ (* n (- (* 5 n) 3)) 2)
(= ftype 8) (* n (- (* 3 n) 2))
:else 0))
(defn look1
[n digit]
(->> (iterate inc 1)
(map #(figurates n %))
(drop-while #(< % (expt 10 (dec digit))))
(take-while #(< % (expt 10 digit)))))
(defn look2
[digit]
(map #(look1 % digit) (range 3 9)))
Problem 66
;; x^2 = 1 + dy2
for d < = 1000
(defn psqr?
[n]
(let [x (Math/sqrt n)]
(== (bigint x) x)))
(defn qdiop
[d]
(loop [y 1]
(let [xsqr (inc (*' d y y))]
(if (psqr? xsqr)
[d (bigint (Math/sqrt xsqr)) y]
(recur (inc y))))))
(defn look66-1
[i j]
(time (loop [d i [dr xr yr] [0 0 0]]
(if (> d j)
[dr xr yr]
(if (psqr? d)
(recur (inc d) [dr xr yr])
(recur (inc d)
(let [[dt x y] (qdiop d)]
(if (> x xr)
[dt x y]
[dr xr yr]))))))))
Problem 100
(defn look100-1
[start]
(for [i (iterate inc start)
:let [b (-' (bigint (* i (/ 1 (Math/sqrt 2)))) 100)
tmp (/ (*' b (dec b))
(*' i (dec i)))]
:when (== tmp 1/2)] [i b tmp]))
(defn look100-2
[start]
(loop [tot start]
(if-let [sol (loop [b (-' (bigint (* tot (/ 1 (Math/sqrt 2)))) 2)]
(let [tmp (/ (*' b (dec b)) (*' tot (dec tot)))]
(if (> tmp 1/2)
nil
(if (== 1/2 tmp)
[tot b]
(recur (inc b))))))]
sol
(recur (inc tot)))))
(defn sol100
[n]
(->> (iterate #(let [tmp (/ (first %) (nth % 2))
sol (look100-2 (dec (bigint (* tmp (first %)))))]
(conj sol (first %)))
[120 0 21])
(drop-while #(< (first %) (expt 10 n)))
(take 1)))
(defn look100-3
[n]
(iterate #(look100-2 (dec (bigint (* 5.8 (first %)))))
[120 0 0]))
(comment )
| null | https://raw.githubusercontent.com/zeniuseducation/poly-euler/734fdcf1ddd096a8730600b684bf7398d071d499/clojure/prob51-100.clj | clojure | x^2 = 1 + dy2 | (ns euler.prob51-100)
(load-file "math.clj")
Do nt know berapa
(defn sqr [x] (* x x))
(defn a->bc
"Consider a^2 + b^2 = c^2, this fn returns the value of a+b+c from a
given a, or nil if it's impossible to construct integer-value b and
c from a given a."
[a lim]
(let [asqr (sqr a)]
(loop [b (inc a)]
(if (or (> (* 2 b) asqr)
(> (+ a b) (* 2 (/ lim 3))))
nil
(if-let [sol (loop [x 1]
(let [tmp (* x (+ x (* 2 b)))]
(if (or (> tmp asqr)
(> (+ a b (+ b x)) lim))
nil
(if (= tmp asqr)
(+ a b (+ b x))
(recur (inc x))))))]
sol
(recur (inc b)))))))
(defn lazyfor
[a lim]
(let [asqr (sqr a)]
(for [b (iterate inc a)
:while (or (<= (* 2 b) asqr)
(<= (+ a b) (* 2 (/ lim 3))))
:let [sol (loop [x 1]
(let [tmp (* x (+ x (* 2 b)))]
(if (or (> tmp asqr)
(> (+ a b (+ b x)) lim))
nil
(if (= tmp asqr)
(+ a b (+ b x))
(recur (inc x))))))]] sol)))
(defn soulmate
[lim]
(->> (inc (quot lim 3))
(range 3)
(mapcat #(lazyfor % lim))
(remove nil?)
(group-by identity)
(filter #(= 1 (count (second %))))
count))
(defn foulmate
[lim]
(->> (inc (quot lim 3))
(range 3)
(map #(a->bc % lim))
(remove nil?)
frequencies
(filter #(= 1 (val %)))
count))
Problem 61
(defn figurates
[ftype n]
(cond (= ftype 3) (/ (* n (inc n)) 2)
(= ftype 4) (sqr n)
(= ftype 5) (/ (* n (dec (* 3 n))) 2)
(= ftype 6) (* n (dec (* 2 n)))
(= ftype 7) (/ (* n (- (* 5 n) 3)) 2)
(= ftype 8) (* n (- (* 3 n) 2))
:else 0))
(defn look1
[n digit]
(->> (iterate inc 1)
(map #(figurates n %))
(drop-while #(< % (expt 10 (dec digit))))
(take-while #(< % (expt 10 digit)))))
(defn look2
[digit]
(map #(look1 % digit) (range 3 9)))
Problem 66
for d < = 1000
(defn psqr?
[n]
(let [x (Math/sqrt n)]
(== (bigint x) x)))
(defn qdiop
[d]
(loop [y 1]
(let [xsqr (inc (*' d y y))]
(if (psqr? xsqr)
[d (bigint (Math/sqrt xsqr)) y]
(recur (inc y))))))
(defn look66-1
[i j]
(time (loop [d i [dr xr yr] [0 0 0]]
(if (> d j)
[dr xr yr]
(if (psqr? d)
(recur (inc d) [dr xr yr])
(recur (inc d)
(let [[dt x y] (qdiop d)]
(if (> x xr)
[dt x y]
[dr xr yr]))))))))
Problem 100
(defn look100-1
[start]
(for [i (iterate inc start)
:let [b (-' (bigint (* i (/ 1 (Math/sqrt 2)))) 100)
tmp (/ (*' b (dec b))
(*' i (dec i)))]
:when (== tmp 1/2)] [i b tmp]))
(defn look100-2
[start]
(loop [tot start]
(if-let [sol (loop [b (-' (bigint (* tot (/ 1 (Math/sqrt 2)))) 2)]
(let [tmp (/ (*' b (dec b)) (*' tot (dec tot)))]
(if (> tmp 1/2)
nil
(if (== 1/2 tmp)
[tot b]
(recur (inc b))))))]
sol
(recur (inc tot)))))
(defn sol100
[n]
(->> (iterate #(let [tmp (/ (first %) (nth % 2))
sol (look100-2 (dec (bigint (* tmp (first %)))))]
(conj sol (first %)))
[120 0 21])
(drop-while #(< (first %) (expt 10 n)))
(take 1)))
(defn look100-3
[n]
(iterate #(look100-2 (dec (bigint (* 5.8 (first %)))))
[120 0 0]))
(comment )
|
329e3afe73d62126e3ff8cf0a0e47b735f8dba5f01a802376aecc0a76453b7de | DerekCuevas/interview-cake-clj | core.clj | (ns highest-product-of-three.core
(:gen-class))
(defn- rotation
"Rotates bucket of k length around the bottom and top of arr by idx."
[arr k idx]
(let [top (- (count arr) (- k idx))]
(vec (concat (subvec arr 0 idx)
(subvec arr top)))))
(defn highest-product-of-k
"O(nlgn) time + O(n + (k + k^2)) space solution."
[k arr]
(if (>= k (count arr))
(reduce * arr)
(->> (range (inc k))
(map (partial rotation (vec (sort arr)) k))
(map (partial reduce *))
(apply max))))
| null | https://raw.githubusercontent.com/DerekCuevas/interview-cake-clj/f17d3239bb30bcc17ced473f055a9859f9d1fb8d/highest-product-of-three/src/highest_product_of_three/core.clj | clojure | (ns highest-product-of-three.core
(:gen-class))
(defn- rotation
"Rotates bucket of k length around the bottom and top of arr by idx."
[arr k idx]
(let [top (- (count arr) (- k idx))]
(vec (concat (subvec arr 0 idx)
(subvec arr top)))))
(defn highest-product-of-k
"O(nlgn) time + O(n + (k + k^2)) space solution."
[k arr]
(if (>= k (count arr))
(reduce * arr)
(->> (range (inc k))
(map (partial rotation (vec (sort arr)) k))
(map (partial reduce *))
(apply max))))
| |
fee29ed0b8ed089b1540148c733c106c66ef9b274d1cd43cdf8ba77759117d44 | danieljharvey/nix-mate | Tags.hs | # LANGUAGE DerivingStrategies #
# LANGUAGE GeneralisedNewtypeDeriving #
module NixMate.Types.Tags
( Tag (..),
TagName,
mkTagName,
getTagName,
tagsPrefix,
)
where
import qualified Data.Char as Char
import Data.List (isInfixOf)
import NixMate.Types.Config
newtype TagName = TagName String
deriving newtype (Eq, Ord, Show)
tagsPrefix :: String
tagsPrefix = "refs/tags/"
mkTagName :: String -> Maybe TagName
mkTagName s =
let clean = drop (length tagsPrefix) s
in if not (null clean)
&& not ("{}" `isInfixOf` clean)
&& not ("backups" `isInfixOf` clean)
&& not ("alpha" `isInfixOf` clean)
&& not ("beta" `isInfixOf` clean)
&& matchesPred (\a -> Char.isDigit a || a == '.') clean
then Just (TagName clean)
else Nothing
matchesPred :: (Char -> Bool) -> String -> Bool
matchesPred f s = length (filter f s) == length s
getTagName :: TagName -> String
getTagName (TagName s) = s
data Tag = Tag
{ tTagName :: TagName,
tTagHash :: Rev
}
deriving (Eq, Ord, Show)
| null | https://raw.githubusercontent.com/danieljharvey/nix-mate/0197b8517319a4ad4c9cb489579a6ed36ad9aec1/src/NixMate/Types/Tags.hs | haskell | # LANGUAGE DerivingStrategies #
# LANGUAGE GeneralisedNewtypeDeriving #
module NixMate.Types.Tags
( Tag (..),
TagName,
mkTagName,
getTagName,
tagsPrefix,
)
where
import qualified Data.Char as Char
import Data.List (isInfixOf)
import NixMate.Types.Config
newtype TagName = TagName String
deriving newtype (Eq, Ord, Show)
tagsPrefix :: String
tagsPrefix = "refs/tags/"
mkTagName :: String -> Maybe TagName
mkTagName s =
let clean = drop (length tagsPrefix) s
in if not (null clean)
&& not ("{}" `isInfixOf` clean)
&& not ("backups" `isInfixOf` clean)
&& not ("alpha" `isInfixOf` clean)
&& not ("beta" `isInfixOf` clean)
&& matchesPred (\a -> Char.isDigit a || a == '.') clean
then Just (TagName clean)
else Nothing
matchesPred :: (Char -> Bool) -> String -> Bool
matchesPred f s = length (filter f s) == length s
getTagName :: TagName -> String
getTagName (TagName s) = s
data Tag = Tag
{ tTagName :: TagName,
tTagHash :: Rev
}
deriving (Eq, Ord, Show)
| |
677abdd2f0baa1c6909fb40d83d9f5dae02e8604e26ed4300e4f7246f4ee7722 | con-kitty/categorifier-c | Utils.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE QuasiQuotes #
module Categorifier.C.CTypes.Codegen.Render.Utils
( indentWith,
staticAssertTriviallyCopyable,
staticAssertTriviallyCopyable',
toCommentText,
nolintNextLineReadabilityIdentifierNaming,
nolintReadabilityIdentifierNaming,
staticAssert,
)
where
import Categorifier.C.CTypes.DSL.CxxAst (CExpr (..), Comment (..), Identifier (..), (#!))
import Categorifier.C.CTypes.DSL.FunctionWriter (FunWriter, force_)
import qualified Categorifier.C.CTypes.Render as R
import Categorifier.C.CTypes.Types (CType)
import Data.Proxy (Proxy (..))
import qualified Data.Text as T
import PyF (fmt)
indentWith :: T.Text -> T.Text -> T.Text
indentWith leadingSpaces = T.intercalate "\n" . fmap indent . T.splitOn "\n"
where
indent :: T.Text -> T.Text
indent x
| T.null x = x
| -- don't add spaces to an empty line
otherwise =
leadingSpaces <> x
staticAssertTriviallyCopyable :: CType Proxy -> FunWriter ()
staticAssertTriviallyCopyable = staticAssertTriviallyCopyable' . R.renderCType
staticAssertTriviallyCopyable' :: T.Text -> FunWriter ()
staticAssertTriviallyCopyable' typeName =
staticAssert
(Ident (Identifier [fmt|std::is_trivially_copyable<{typeName}>::value|]))
[fmt|{typeName} is not trivially copyable|]
toCommentText :: Maybe Comment -> T.Text
toCommentText Nothing = ""
toCommentText (Just (Comment comment)) = "// " <> T.replace "\n" "\n// " comment <> "\n"
nolintNextLineReadabilityIdentifierNaming :: T.Text
nolintNextLineReadabilityIdentifierNaming = "// NOLINTNEXTLINE(readability-identifier-naming)"
nolintReadabilityIdentifierNaming :: T.Text
nolintReadabilityIdentifierNaming = "// NOLINT(readability-identifier-naming)"
staticAssert :: CExpr -> CExpr -> FunWriter ()
staticAssert a b = force_ $ Identifier "static_assert" #! [a, b]
| null | https://raw.githubusercontent.com/con-kitty/categorifier-c/167ff5cfdeb60b6fa00b10ec74033c32132d45a0/Categorifier/C/CTypes/Codegen/Render/Utils.hs | haskell | # LANGUAGE OverloadedStrings #
don't add spaces to an empty line | # LANGUAGE QuasiQuotes #
module Categorifier.C.CTypes.Codegen.Render.Utils
( indentWith,
staticAssertTriviallyCopyable,
staticAssertTriviallyCopyable',
toCommentText,
nolintNextLineReadabilityIdentifierNaming,
nolintReadabilityIdentifierNaming,
staticAssert,
)
where
import Categorifier.C.CTypes.DSL.CxxAst (CExpr (..), Comment (..), Identifier (..), (#!))
import Categorifier.C.CTypes.DSL.FunctionWriter (FunWriter, force_)
import qualified Categorifier.C.CTypes.Render as R
import Categorifier.C.CTypes.Types (CType)
import Data.Proxy (Proxy (..))
import qualified Data.Text as T
import PyF (fmt)
indentWith :: T.Text -> T.Text -> T.Text
indentWith leadingSpaces = T.intercalate "\n" . fmap indent . T.splitOn "\n"
where
indent :: T.Text -> T.Text
indent x
| T.null x = x
otherwise =
leadingSpaces <> x
staticAssertTriviallyCopyable :: CType Proxy -> FunWriter ()
staticAssertTriviallyCopyable = staticAssertTriviallyCopyable' . R.renderCType
staticAssertTriviallyCopyable' :: T.Text -> FunWriter ()
staticAssertTriviallyCopyable' typeName =
staticAssert
(Ident (Identifier [fmt|std::is_trivially_copyable<{typeName}>::value|]))
[fmt|{typeName} is not trivially copyable|]
toCommentText :: Maybe Comment -> T.Text
toCommentText Nothing = ""
toCommentText (Just (Comment comment)) = "// " <> T.replace "\n" "\n// " comment <> "\n"
nolintNextLineReadabilityIdentifierNaming :: T.Text
nolintNextLineReadabilityIdentifierNaming = "// NOLINTNEXTLINE(readability-identifier-naming)"
nolintReadabilityIdentifierNaming :: T.Text
nolintReadabilityIdentifierNaming = "// NOLINT(readability-identifier-naming)"
staticAssert :: CExpr -> CExpr -> FunWriter ()
staticAssert a b = force_ $ Identifier "static_assert" #! [a, b]
|
74400a65fb8efd3181779793f205b088f9545b6e236dc221bbf6198e32c0f795 | janestreet/memtrace_viewer_with_deps | app.ml | open! Core_kernel
open! Async_kernel
open Incr_dom
module Model = struct
type t = unit
let cutoff = phys_equal
end
module State = struct
type t = unit
end
module Action = struct
type t = Nothing.t [@@deriving sexp]
end
let initial_model = ()
let on_startup ~schedule_action:_ _model = Deferred.unit
let create model ~old_model:_ ~inject:_ =
let open Incr.Let_syntax in
let%map model = model in
let apply_action action _ ~schedule_action:_ = Nothing.unreachable_code action in
let view = Vdom.Node.text "hello world" in
Component.create ~apply_action model view
;;
| null | https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/incr_dom/example/hello_world/lib/app.ml | ocaml | open! Core_kernel
open! Async_kernel
open Incr_dom
module Model = struct
type t = unit
let cutoff = phys_equal
end
module State = struct
type t = unit
end
module Action = struct
type t = Nothing.t [@@deriving sexp]
end
let initial_model = ()
let on_startup ~schedule_action:_ _model = Deferred.unit
let create model ~old_model:_ ~inject:_ =
let open Incr.Let_syntax in
let%map model = model in
let apply_action action _ ~schedule_action:_ = Nothing.unreachable_code action in
let view = Vdom.Node.text "hello world" in
Component.create ~apply_action model view
;;
| |
728ebdd3576632f6411be6162f1374dd50f140cf1bc3fbd46cccca623843ffda | ryleelyman/latex.nvim | conceal_greek.scm | greek conceal
(generic_command
command: ((command_name) @text.math
(#any-of? @text.math
"\\alpha" "\\beta" "\\gamma" "\\delta"
"\\epsilon" "\\varepsilon" "\\zeta" "\\eta"
"\\theta" "\\vartheta" "\\iota" "\\kappa"
"\\lambda" "\\mu" "\\nu" "\\xi"
"\\pi" "\\varpi" "\\rho" "\\varrho"
"\\sigma" "\\varsigma" "\\tau" "\\upsilon"
"\\phi" "\\varphi" "\\chi" "\\psi"
"\\omega" "\\Gamma" "\\Delta" "\\Theta"
"\\Lambda" "\\Xi" "\\Pi" "\\Sigma"
"\\Upsilon" "\\Phi" "\\Chi" "\\Psi"
"\\Omega"))
(#has-ancestor? @text.math math_environment inline_formula displayed_equation)
(#not-has-ancestor? @text.math label_definition text_mode)
(#set-pairs! @text.math conceal
"\\alpha" "α"
"\\beta" "β"
"\\gamma" "γ"
"\\delta" "δ"
"\\epsilon" "ϵ"
"\\varepsilon" "ε"
"\\zeta" "ζ"
"\\eta" "η"
"\\theta" "θ"
"\\vartheta" "ϑ"
"\\iota" "ι"
"\\kappa" "κ"
"\\lambda" "λ"
"\\mu" "μ"
"\\nu" "ν"
"\\xi" "ξ"
"\\pi" "π"
"\\varpi" "ϖ"
"\\rho" "ρ"
"\\varrho" "ϱ"
"\\sigma" "σ"
"\\varsigma" "ς"
"\\tau" "τ"
"\\upsilon" "υ"
"\\phi" "ϕ"
"\\varphi" "φ"
"\\chi" "χ"
"\\psi" "ψ"
"\\omega" "ω"
"\\Gamma" "Γ"
"\\Delta" "Δ"
"\\Theta" "Θ"
"\\Lambda" "Λ"
"\\Xi" "Ξ"
"\\Pi" "Π"
"\\Sigma" "Σ"
"\\Upsilon" "Υ"
"\\Phi" "Φ"
"\\Chi" "Χ"
"\\Psi" "Ψ"
"\\Omega" "Ω"))
| null | https://raw.githubusercontent.com/ryleelyman/latex.nvim/966a4fe978b8bef82d153fd6321801bd0683eb15/queries/latex/conceal_greek.scm | scheme | greek conceal
(generic_command
command: ((command_name) @text.math
(#any-of? @text.math
"\\alpha" "\\beta" "\\gamma" "\\delta"
"\\epsilon" "\\varepsilon" "\\zeta" "\\eta"
"\\theta" "\\vartheta" "\\iota" "\\kappa"
"\\lambda" "\\mu" "\\nu" "\\xi"
"\\pi" "\\varpi" "\\rho" "\\varrho"
"\\sigma" "\\varsigma" "\\tau" "\\upsilon"
"\\phi" "\\varphi" "\\chi" "\\psi"
"\\omega" "\\Gamma" "\\Delta" "\\Theta"
"\\Lambda" "\\Xi" "\\Pi" "\\Sigma"
"\\Upsilon" "\\Phi" "\\Chi" "\\Psi"
"\\Omega"))
(#has-ancestor? @text.math math_environment inline_formula displayed_equation)
(#not-has-ancestor? @text.math label_definition text_mode)
(#set-pairs! @text.math conceal
"\\alpha" "α"
"\\beta" "β"
"\\gamma" "γ"
"\\delta" "δ"
"\\epsilon" "ϵ"
"\\varepsilon" "ε"
"\\zeta" "ζ"
"\\eta" "η"
"\\theta" "θ"
"\\vartheta" "ϑ"
"\\iota" "ι"
"\\kappa" "κ"
"\\lambda" "λ"
"\\mu" "μ"
"\\nu" "ν"
"\\xi" "ξ"
"\\pi" "π"
"\\varpi" "ϖ"
"\\rho" "ρ"
"\\varrho" "ϱ"
"\\sigma" "σ"
"\\varsigma" "ς"
"\\tau" "τ"
"\\upsilon" "υ"
"\\phi" "ϕ"
"\\varphi" "φ"
"\\chi" "χ"
"\\psi" "ψ"
"\\omega" "ω"
"\\Gamma" "Γ"
"\\Delta" "Δ"
"\\Theta" "Θ"
"\\Lambda" "Λ"
"\\Xi" "Ξ"
"\\Pi" "Π"
"\\Sigma" "Σ"
"\\Upsilon" "Υ"
"\\Phi" "Φ"
"\\Chi" "Χ"
"\\Psi" "Ψ"
"\\Omega" "Ω"))
| |
f017f30bcaeb063d0573862190c381c5bb00cae9182cdbb443087d4fa54a419b | manuel-serrano/bigloo | pgp_s2k.scm | (module __openpgp-s2k
(library crypto)
(import __openpgp-human
__openpgp-algo
__openpgp-util
__openpgp-error)
(export (simple-s2k::bstring str::bstring len::long hash-fun::procedure)
(salted-s2k::bstring str::bstring len::long hash-fun::procedure
salt::bstring)
(iterated-salted-s2k::bstring str::bstring len::long
hash-fun::procedure salt::bstring
count::long)
(make-s2k algo hash salt count)
(s2k-algo s2k)
(s2k-hash s2k)
(s2k-salt s2k)
(s2k-count s2k)
(apply-s2k s2k passwd::bstring len::long)
(octet->iterated-salted-s2k-count::long o::char)
(iterated-salted-s2k-count->octet::long count::long)
(round-iterated-salted-s2k-count::long count::long)
(s2k-salt-length::int)))
(define *s2k-salt-length* 8)
(define (s2k-salt-length::int) *s2k-salt-length*)
(define *s2k-EXPBIAS* 6)
(define *s2k-OFFSET* 16)
min - s2k - count = = 1024
(define *min-s2k-count* (bit-lsh (+fx #x0 *s2k-OFFSET*)
(+fx #x0 *s2k-EXPBIAS*)))
max - s2k - count = = 65011712
(define *max-s2k-count* (bit-lsh (+fx #xF *s2k-OFFSET*)
(+fx #xF *s2k-EXPBIAS*)))
;; rounds the input number, so that it can be exactly encoded by the
;; s2k-encoding mechanism.
(define (round-iterated-salted-s2k-count::long count::long)
(let ((octet (iterated-salted-s2k-count->octet count)))
(octet->iterated-salted-s2k-count (integer->char octet))))
(define (octet->iterated-salted-s2k-count::long o::char)
(let ((ov (char->integer o)))
(bit-lsh (+fx *s2k-OFFSET* (bit-and ov #x0F))
(+fx (bit-rsh ov 4) *s2k-EXPBIAS*))))
;; if we are in between iterations just round up.
(define (iterated-salted-s2k-count->octet::long count::long)
(cond
((<=fx count *min-s2k-count*) #x00)
((>=fx count *max-s2k-count*) #xFF)
(else
(let loop ((right-digit+offset (bit-rsh count *s2k-EXPBIAS*))
(left-digit 0))
;; the left digit decides how far we must shift the right digit.
the right digit+offset ( offset=16 ) has a value of 16 - 31 .
;; We thus shift the initial count to the right until we satisfy this
;; property. (As we come from above, we only need to check if we are
< = 31 )
;; Note that we shift the initial count to the right by the
;; obligatory *s2k-EXPBIAS*
( < = fx .. 31 )
combine the two and round up ( if necessary ) .
(let ((res (+fx (bit-lsh left-digit 4)
(-fx right-digit+offset *s2k-OFFSET*))))
;; now the rounding up.
(let liip ((res res))
(let ((c (integer->char-ur res)))
(if (< (octet->iterated-salted-s2k-count c) count)
(liip (+fx res 1))
res))))
(loop (bit-rsh right-digit+offset 1)
(+fx left-digit 1)))))))
(define (simple-s2k::bstring str::bstring len::long hash-fun::procedure)
(string->key-simple str len hash-fun))
(define (salted-s2k::bstring str::bstring len::long hash-fun::procedure
salt::bstring)
(string->key-salted str len hash-fun salt))
;; note: we take the byte-count and not the char.
;; the char must hence be already decoded.
CARE : long might not be enough for ' count ' . [ flo ]
(define (iterated-salted-s2k::bstring str::bstring len::long
hash-fun::procedure salt::bstring
count::long)
(string->key-iterated-salted str len hash-fun salt count))
(define (make-s2k algo hash salt count)
(let ((t (make-S2K)))
(S2K-algo-set! t algo)
(S2K-hash-set! t hash)
(S2K-salt-set! t salt)
(S2K-count-set! t count)
t))
(define (s2k-algo s2k) (S2K-algo s2k))
(define (s2k-hash s2k) (S2K-hash s2k))
(define (s2k-salt s2k) (S2K-salt s2k))
(define (s2k-count s2k) (S2K-count s2k))
(define-struct S2K algo hash salt count)
(define (apply-s2k s2k pwd::bstring len::long)
(with-trace 'pgp "apply-s2k"
(when (not (S2K? s2k))
(openpgp-error "apply-s2k"
"S2K-struct expected"
s2k))
(trace-item "Applying s2k " pwd " (" len ")")
(let ((algo (S2K-algo s2k))
(hash-algo (S2K-hash s2k))
(salt (S2K-salt s2k))
(count (S2K-count s2k)))
(case algo
((simple) ;; simple-hash
(trace-item "Simple S2K (no salt no iteration)")
(simple-s2k pwd len (hash-algo->procedure hash-algo)))
((salted) ;; salted s2k
(let ((salt (S2K-salt s2k)))
(trace-item "Salted S2K: " (str->hex-string salt))
(salted-s2k pwd len (hash-algo->procedure hash-algo) salt)))
((iterated) ;; iterated and salted s2k
(let ((salt (S2K-salt s2k))
(count (S2K-count s2k)))
(trace-item "Salted iterated S2K: " count " " (str->hex-string salt))
(iterated-salted-s2k pwd len (hash-algo->procedure hash-algo) salt
count)))
(else (openpgp-error "apply-s2k"
"bad S2K struct"
s2k))))))
| null | https://raw.githubusercontent.com/manuel-serrano/bigloo/6afa8068fa5889b3615f4b6fe5991b7d2387318a/api/openpgp/src/Llib/pgp_s2k.scm | scheme | rounds the input number, so that it can be exactly encoded by the
s2k-encoding mechanism.
if we are in between iterations just round up.
the left digit decides how far we must shift the right digit.
We thus shift the initial count to the right until we satisfy this
property. (As we come from above, we only need to check if we are
Note that we shift the initial count to the right by the
obligatory *s2k-EXPBIAS*
now the rounding up.
note: we take the byte-count and not the char.
the char must hence be already decoded.
simple-hash
salted s2k
iterated and salted s2k | (module __openpgp-s2k
(library crypto)
(import __openpgp-human
__openpgp-algo
__openpgp-util
__openpgp-error)
(export (simple-s2k::bstring str::bstring len::long hash-fun::procedure)
(salted-s2k::bstring str::bstring len::long hash-fun::procedure
salt::bstring)
(iterated-salted-s2k::bstring str::bstring len::long
hash-fun::procedure salt::bstring
count::long)
(make-s2k algo hash salt count)
(s2k-algo s2k)
(s2k-hash s2k)
(s2k-salt s2k)
(s2k-count s2k)
(apply-s2k s2k passwd::bstring len::long)
(octet->iterated-salted-s2k-count::long o::char)
(iterated-salted-s2k-count->octet::long count::long)
(round-iterated-salted-s2k-count::long count::long)
(s2k-salt-length::int)))
(define *s2k-salt-length* 8)
(define (s2k-salt-length::int) *s2k-salt-length*)
(define *s2k-EXPBIAS* 6)
(define *s2k-OFFSET* 16)
min - s2k - count = = 1024
(define *min-s2k-count* (bit-lsh (+fx #x0 *s2k-OFFSET*)
(+fx #x0 *s2k-EXPBIAS*)))
max - s2k - count = = 65011712
(define *max-s2k-count* (bit-lsh (+fx #xF *s2k-OFFSET*)
(+fx #xF *s2k-EXPBIAS*)))
(define (round-iterated-salted-s2k-count::long count::long)
(let ((octet (iterated-salted-s2k-count->octet count)))
(octet->iterated-salted-s2k-count (integer->char octet))))
(define (octet->iterated-salted-s2k-count::long o::char)
(let ((ov (char->integer o)))
(bit-lsh (+fx *s2k-OFFSET* (bit-and ov #x0F))
(+fx (bit-rsh ov 4) *s2k-EXPBIAS*))))
(define (iterated-salted-s2k-count->octet::long count::long)
(cond
((<=fx count *min-s2k-count*) #x00)
((>=fx count *max-s2k-count*) #xFF)
(else
(let loop ((right-digit+offset (bit-rsh count *s2k-EXPBIAS*))
(left-digit 0))
the right digit+offset ( offset=16 ) has a value of 16 - 31 .
< = 31 )
( < = fx .. 31 )
combine the two and round up ( if necessary ) .
(let ((res (+fx (bit-lsh left-digit 4)
(-fx right-digit+offset *s2k-OFFSET*))))
(let liip ((res res))
(let ((c (integer->char-ur res)))
(if (< (octet->iterated-salted-s2k-count c) count)
(liip (+fx res 1))
res))))
(loop (bit-rsh right-digit+offset 1)
(+fx left-digit 1)))))))
(define (simple-s2k::bstring str::bstring len::long hash-fun::procedure)
(string->key-simple str len hash-fun))
(define (salted-s2k::bstring str::bstring len::long hash-fun::procedure
salt::bstring)
(string->key-salted str len hash-fun salt))
CARE : long might not be enough for ' count ' . [ flo ]
(define (iterated-salted-s2k::bstring str::bstring len::long
hash-fun::procedure salt::bstring
count::long)
(string->key-iterated-salted str len hash-fun salt count))
(define (make-s2k algo hash salt count)
(let ((t (make-S2K)))
(S2K-algo-set! t algo)
(S2K-hash-set! t hash)
(S2K-salt-set! t salt)
(S2K-count-set! t count)
t))
(define (s2k-algo s2k) (S2K-algo s2k))
(define (s2k-hash s2k) (S2K-hash s2k))
(define (s2k-salt s2k) (S2K-salt s2k))
(define (s2k-count s2k) (S2K-count s2k))
(define-struct S2K algo hash salt count)
(define (apply-s2k s2k pwd::bstring len::long)
(with-trace 'pgp "apply-s2k"
(when (not (S2K? s2k))
(openpgp-error "apply-s2k"
"S2K-struct expected"
s2k))
(trace-item "Applying s2k " pwd " (" len ")")
(let ((algo (S2K-algo s2k))
(hash-algo (S2K-hash s2k))
(salt (S2K-salt s2k))
(count (S2K-count s2k)))
(case algo
(trace-item "Simple S2K (no salt no iteration)")
(simple-s2k pwd len (hash-algo->procedure hash-algo)))
(let ((salt (S2K-salt s2k)))
(trace-item "Salted S2K: " (str->hex-string salt))
(salted-s2k pwd len (hash-algo->procedure hash-algo) salt)))
(let ((salt (S2K-salt s2k))
(count (S2K-count s2k)))
(trace-item "Salted iterated S2K: " count " " (str->hex-string salt))
(iterated-salted-s2k pwd len (hash-algo->procedure hash-algo) salt
count)))
(else (openpgp-error "apply-s2k"
"bad S2K struct"
s2k))))))
|
64cee1541b95c3013e4d8dcc45f6a8ace3a5facceaeb35023cbc11d1d4fe4174 | wies/grasshopper | prioQueue.mli | * Priority Search Queues .
Implements the data structure from this paper :
A Simple Implementation Technique for Priority Search Queues
, ICFP 2001
Implements the data structure from this paper:
A Simple Implementation Technique for Priority Search Queues
Ralf Hinze, ICFP 2001
*)
module type OrderedType = sig
type t
val compare: t -> t -> int
end
module Make(K: OrderedType)(P: OrderedType): sig
type t
val empty: t
val is_empty: t -> bool
runs in O(1 )
val size: t -> int
runs in O(1 )
val insert: K.t -> P.t -> t -> t
runs in O(log n )
val delete: K.t -> t -> t
runs in O(log n )
val min: t -> K.t * P.t
runs in O(1 )
val extract_min: t -> K.t * P.t * t
runs in O(log n )
val adjust: (P.t -> P.t) -> K.t -> t -> t
runs in O(log n )
val find_opt: K.t -> t -> P.t option
val fold: (K.t -> P.t -> 'a -> 'a) -> t -> 'a -> 'a
val exists: (K.t -> P.t -> bool) -> t -> bool
val forall: (K.t -> P.t -> bool) -> t -> bool
end
| null | https://raw.githubusercontent.com/wies/grasshopper/108473b0a678f0d93fffec6da2ad6bcdce5bddb9/src/util/prioQueue.mli | ocaml | * Priority Search Queues .
Implements the data structure from this paper :
A Simple Implementation Technique for Priority Search Queues
, ICFP 2001
Implements the data structure from this paper:
A Simple Implementation Technique for Priority Search Queues
Ralf Hinze, ICFP 2001
*)
module type OrderedType = sig
type t
val compare: t -> t -> int
end
module Make(K: OrderedType)(P: OrderedType): sig
type t
val empty: t
val is_empty: t -> bool
runs in O(1 )
val size: t -> int
runs in O(1 )
val insert: K.t -> P.t -> t -> t
runs in O(log n )
val delete: K.t -> t -> t
runs in O(log n )
val min: t -> K.t * P.t
runs in O(1 )
val extract_min: t -> K.t * P.t * t
runs in O(log n )
val adjust: (P.t -> P.t) -> K.t -> t -> t
runs in O(log n )
val find_opt: K.t -> t -> P.t option
val fold: (K.t -> P.t -> 'a -> 'a) -> t -> 'a -> 'a
val exists: (K.t -> P.t -> bool) -> t -> bool
val forall: (K.t -> P.t -> bool) -> t -> bool
end
| |
2214a5ac2319bf6a71020b9630ab2e0cbc2727ba67d1c8b4215ffe3f7d27f307 | jaseemabid/mit-scheme | tak.scm | (declare (usual-integrations))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; File: tak.sch
Description : TAK benchmark from the tests
Author :
; Created: 12-Apr-85
Modified : 12 - Apr-85 09:58:18 ( )
22 - Jul-87 ( )
; Language: Scheme
; Status: Public Domain
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
TAK -- A vanilla version of the TAKeuchi function
(define (tak x y z)
(if (not (< y x))
z
(tak (tak (- x 1) y z)
(tak (- y 1) z x)
(tak (- z 1) x y))))
call : ( tak 18 12 6 )
(lambda ()
(list (tak 18 12 6) (tak 18 12 6) (tak 18 12 6) (tak 18 12 6)
(tak 18 12 6) (tak 18 12 6) (tak 18 12 6) (tak 18 12 6)
(tak 18 12 6) (tak 18 12 6) (tak 18 12 6) (tak 18 12 6)
(tak 18 12 6) (tak 18 12 6) (tak 18 12 6) (tak 18 12 6)
(tak 18 12 6) (tak 18 12 6) (tak 18 12 6) (tak 18 12 6)))
| null | https://raw.githubusercontent.com/jaseemabid/mit-scheme/d30da6b2c103e34b6e0805bd5cbefeb9501382c1/v8/src/bench/tak.scm | scheme |
File: tak.sch
Created: 12-Apr-85
Language: Scheme
Status: Public Domain
| (declare (usual-integrations))
Description : TAK benchmark from the tests
Author :
Modified : 12 - Apr-85 09:58:18 ( )
22 - Jul-87 ( )
TAK -- A vanilla version of the TAKeuchi function
(define (tak x y z)
(if (not (< y x))
z
(tak (tak (- x 1) y z)
(tak (- y 1) z x)
(tak (- z 1) x y))))
call : ( tak 18 12 6 )
(lambda ()
(list (tak 18 12 6) (tak 18 12 6) (tak 18 12 6) (tak 18 12 6)
(tak 18 12 6) (tak 18 12 6) (tak 18 12 6) (tak 18 12 6)
(tak 18 12 6) (tak 18 12 6) (tak 18 12 6) (tak 18 12 6)
(tak 18 12 6) (tak 18 12 6) (tak 18 12 6) (tak 18 12 6)
(tak 18 12 6) (tak 18 12 6) (tak 18 12 6) (tak 18 12 6)))
|
bb5150cbcea1711d4c32cc21cdb6eba180ceeaa51d3cd6e05278ae82ce21a39e | flavioc/cl-meld | typecheck.lisp | (in-package :cl-meld)
(define-condition type-invalid-error (error)
((text :initarg :text :reader text)))
(defun check-home-argument (name typs)
(when (null typs)
(error 'type-invalid-error :text (concatenate 'string name " has no arguments")))
(let ((fst (first typs)))
(unless (or (type-addr-p fst) (type-thread-p fst) (type-node-p fst))
(error 'type-invalid-error
:text (concatenate 'string "first argument of tuple " name " must be of type 'node'")))))
(defun no-types-p (ls) (null ls))
(defun merge-type (t1 t2)
(assert (not (null t1)))
(assert (not (null t2)))
(if (equal t1 t2)
(return-from merge-type t1))
(cond
((eq t1 :all) t2)
((eq t2 :all) t1)
((and (type-node-p t1) (type-node-p t2))
(let ((a (type-node-type t1))
(b (type-node-type t2)))
(if (string-equal a b)
t1 nil)))
((and (type-addr-p t1) (type-node-p t2)) t2)
((and (type-node-p t1) (type-addr-p t2)) t1)
((and (type-list-p t1) (type-list-p t2))
(let* ((sub1 (type-list-element t1))
(sub2 (type-list-element t2))
(merged (merge-type sub1 sub2)))
(if merged
(make-list-type merged))))
((and (type-array-p t1) (type-array-p t2))
(let* ((sub1 (type-array-element t1))
(sub2 (type-array-element t2))
(merged (merge-type sub1 sub2)))
(if merged
(make-array-type merged))))
((and (type-set-p t1) (type-set-p t2))
(let* ((sub1 (type-set-element t1))
(sub2 (type-set-element t2))
(merged (merge-type sub1 sub2)))
(if merged
(make-set-type merged))))
((and (type-struct-p t1) (type-struct-p t2))
(let ((l1 (type-struct-list t1))
(l2 (type-struct-list t2)))
(cond
((eq l2 :all) t1)
((eq l1 :all) t2)
((not (= (length l1) (length l2))) nil)
(t
(let ((result
(loop for t1 in l1
for t2 in l2
collect (merge-types t1 t2))))
(if (find-if #'null result)
nil
(make-struct-type result)))))))
((and (listp t1) (listp t2))
(merge-types t1 t2))
((and (listp t1) (not (listp t2)) (eq t2 (first t1))) t2)
((and (listp t2) (not (listp t1)) (eq t1 (first t2))) t1)
((and (listp t1) (not (listp t2))) nil)
((and (not (listp t2)) (listp t2)) nil)
((and (not (listp t1)) (not (listp t2)))
(if (eq t1 t2)
t1
nil))
(t nil)))
(defun merge-with-suitable-list-type (types subtype)
(let ((ls (filter #'type-list-p types)))
(if (eq subtype :all)
ls
(let ((f (find-if #L(eq (type-list-element !1) subtype) ls)))
(when f
`(,f))))))
(defun merge-types (ls types)
(cond
((= (length ls) (length types) 1)
(let ((t1 (first ls))
(t2 (first types)))
(cond
((and (type-list-p t1)
(type-list-p t2))
(let ((t11 (type-list-element t1))
(t22 (type-list-element t2)))
(let ((merged-type (merge-type t11 t22)))
(when merged-type
`(,(make-list-type merged-type))))))
(t
(let ((merged (merge-type t1 t2)))
(when merged
`(,merged)))))))
((= (length ls) 1)
(let ((t1 (first ls)))
(if (eq t1 :all)
types
(if (type-list-p t1)
(let ((sub (type-list-element t1)))
(merge-with-suitable-list-type types sub))
(intersection ls types)))))
((= (length types) 1)
(let ((t2 (first types)))
(cond
((eq t2 :all) ls)
((type-list-p t2)
(let* ((t21 (type-list-element t2))
(list-types (filter #'type-list-p ls))
(elements (mapcar #'type-list-element list-types))
(merged (loop for element in elements
append (let ((m (merge-types (list element) (list t21))))
(when m
(list (make-list-type (first m))))))))
merged))
(t
(intersection ls types)))))
(t (intersection ls types :test #'equal))))
(defparameter *constraints* nil)
(defparameter *defined* nil)
(defparameter *defined-in-context* nil)
(defparameter *node-constraints* nil)
(defmacro with-node-type-context (&body body)
`(let ((*node-constraints* (make-hash-table))
(*node-types* nil))
,@body))
(defun get-node-constraint (addr-num)
(multiple-value-bind (type-found found-p) (gethash addr-num *node-constraints*)
type-found))
(defun find-node-type-id (node-type)
(when (or (null node-type) (type-addr-p node-type))
(return-from find-node-type-id 0))
(let ((x (type-node-type node-type)))
(loop for name in *node-types*
for c from 1
when (string-equal name x)
do (return-from find-node-type-id c))))
(defun add-node-constraint (addr typ)
(multiple-value-bind (type-found found-p) (gethash (addr-num addr) *node-constraints*)
(cond
((not (or (type-addr-p typ) (type-node-p typ)))
(error 'type-invalid-error :text (tostring "add-node-constraint: invalid node type ~a" typ)))
(found-p
(let ((result (merge-type type-found typ)))
(unless result
(error 'type-invalid-error :text (tostring "add-node-constraint: could not merge types '~a' and '~a' for node ~a"
(type-to-string type-found) (type-to-string typ) (addr-num addr))))
(setf (gethash (addr-num addr) *node-constraints*) result)
result))
(t
(setf (gethash (addr-num addr) *node-constraints*) typ)
typ))))
(defmacro with-typecheck-context (&body body)
`(let ((*defined* nil)
(*defined-in-context* nil)
(*constraints* (make-hash-table)))
,@body))
(defmacro extend-typecheck-context (&body body)
`(let ((*defined* (copy-list *defined*))
(*defined-in-context* nil)
(*constraints* (copy-hash-table *constraints*)))
,@body))
(defun reset-typecheck-context ()
(setf *defined* nil)
(setf *defined-in-context* nil)
(setf *constraints* (make-hash-table)))
(defun variable-is-defined (var)
(unless (has-elem-p *defined* (var-name var))
(push (var-name var) *defined-in-context*)
(push (var-name var) *defined*)))
(defun variable-defined-p (var) (has-elem-p *defined* (var-name var)))
(defun has-variables-defined (expr) (every #'variable-defined-p (all-variables expr)))
(defun set-type (expr typs)
(let ((typ (list (try-one typs))))
(when (and (one-elem-p typs)
(not (has-all-type-p typs)))
(setf *program-types* (add-type-to-typelist *program-types* (first typs))))
(cond
((or (nil-p expr) (host-p expr) (cpus-p expr)
(world-p expr) (host-id-p expr) (thread-id-p expr))
(setf (cdr expr) typ))
((or (var-p expr) (bool-p expr) (int-p expr) (float-p expr) (string-constant-p expr) (tail-p expr) (head-p expr)
(not-p expr) (test-nil-p expr) (addr-p expr) (convert-float-p expr)
(get-constant-p expr) (struct-p expr))
(setf (cddr expr) typ))
((or (call-p expr) (op-p expr) (callf-p expr)
(cons-p expr) (struct-val-p expr))
(setf (cdddr expr) typ))
((or (let-p expr) (if-p expr)) (setf (cddddr expr) typ))
((or (argument-p expr))) ; do nothing
(t (error 'type-invalid-error :text (tostring "set-type: Unknown expression ~a" expr))))))
(defun force-constraint (var new-types)
(multiple-value-bind (types ok) (gethash var *constraints*)
(when ok
(let ((old-types new-types))
(setf new-types (merge-types types new-types))
(when (no-types-p new-types)
(error 'type-invalid-error :text
(tostring "Type error in variable ~a: new constraint are types '~a' but variable is set as '~a'"
var (type-to-string (first old-types)) (type-to-string (first types)))))))
(set-var-constraint var new-types)))
(defun set-var-constraint (var new-types)
(assert (listp new-types))
(setf (gethash var *constraints*) new-types))
(defun get-var-constraint (var)
(gethash var *constraints*))
(defun select-simpler-types (types)
(cond
((= (length types) 1) types)
((= (length types) 2)
(if (and (has-elem-p types :type-int)
(has-elem-p types :type-float))
'(:type-int)
(if (every #'type-list-p types)
(let* ((list-types (mapcar #'type-list-element types))
(simplified (select-simpler-types list-types)))
(if (= (length simplified) 1)
(make-list-type (first simplified))
types))
types)))
(t types)))
(defun get-list-elements (forced-types)
(if (is-all-type-p forced-types)
forced-types
(mapcar #'type-list-element (filter #'type-list-p forced-types))))
(defun get-struct-lists (forced-types)
(if (is-all-type-p forced-types)
forced-types
(mapcar #'type-struct-list (filter #'type-struct-p forced-types))))
(defun unify-types (typ concrete-type concrete-template)
"Unify 'typ' by matching the concrete-template with concrete-type."
(cond
((eq concrete-template :all)
(subst concrete-type :all typ :test #'equal))
((type-list-p concrete-template)
(unify-types typ (type-list-element concrete-type) (type-list-element concrete-template)))
((type-array-p concrete-template)
(unify-types typ (type-array-element concrete-type) (type-array-element concrete-template)))
((type-set-p concrete-template)
(unify-types typ (type-set-element concrete-type) (type-set-element concrete-template)))
((type-struct-p concrete-template)
(cond
((eq (type-struct-list concrete-template) :all)
(subst (type-struct-list concrete-type) :all typ :test #'equal))
(t
(loop for conc in (type-struct-list concrete-type)
for temp in (type-struct-list concrete-template)
do (setf typ (unify-types typ conc temp)))
typ)))
(t typ)))
(defun unify-arg-types (arg-types template-ret ret-types)
(unless (has-all-type-p template-ret)
(return-from unify-arg-types arg-types))
(cond
((and (one-elem-p ret-types)
(not (has-all-type-p ret-types)))
(let ((f (first ret-types)))
(loop for arg in arg-types
collect (unify-types arg f template-ret))))
(t arg-types)))
(defun find-all-type (template concrete)
(cond
((eq template :all) concrete)
((type-list-p template) (find-all-type (type-list-element template) (type-list-element concrete)))
((type-array-p template) (find-all-type (type-array-element template) (type-array-element concrete)))
((type-set-p template) (find-all-type (type-set-element template) (type-set-element concrete)))
((type-struct-p template)
(when (eq (type-struct-list template) :all)
(return-from find-all-type concrete))
(loop for temp in (type-struct-list template)
for conc in (type-struct-list concrete)
do (let ((x (find-all-type temp conc)))
(when x
(return-from find-all-type x))))
(assert nil))
(t
nil)))
(defun get-type (expr forced-types body-p)
(assert (not (null forced-types)))
(assert (not (null (first forced-types))))
(labels ((do-get-type (expr forced-types)
(cond
((string-constant-p expr) (merge-types forced-types '(:type-string)))
((addr-p expr)
(when (one-elem-p forced-types)
(let ((ty (first forced-types)))
(cond
((is-all-type-p forced-types)
(add-node-constraint expr :type-addr)
'(:type-addr))
((type-addr-p ty)
(add-node-constraint expr ty)
'(:type-addr))
((type-node-p ty)
(add-node-constraint expr ty)
`(,ty))
(t nil)))))
((thread-id-p expr)
(when (one-elem-p forced-types)
(let ((ty (first forced-types)))
(cond
((is-all-type-p forced-types) '(:type-thread))
((type-thread-p ty) '(:type-thread))
(t nil)))))
((or (host-p expr) (host-id-p expr))
(when (one-elem-p forced-types)
(let ((ty (first forced-types)))
(cond
((is-all-type-p forced-types) '(:type-addr))
((type-addr-p ty) '(:type-addr))
((type-node-p ty) `(,ty))
(t nil)))))
((var-p expr)
(cond
(body-p
(variable-is-defined expr)
(let ((ret (force-constraint (var-name expr) forced-types)))
ret))
(t
(when (not (variable-defined-p expr))
(error 'type-invalid-error :text
(tostring "variable ~a is not defined" (var-name expr))))
(let ((ret (force-constraint (var-name expr) forced-types)))
ret))))
((bool-p expr) (merge-types forced-types '(:type-bool)))
((int-p expr) (let ((new-types (merge-types forced-types '(:type-int :type-float))))
(if (one-elem-this new-types :type-float)
(transform-int-to-float expr))
new-types))
((float-p expr) (merge-types forced-types '(:type-float)))
((argument-p expr) (merge-types forced-types '(:type-string)))
((get-constant-p expr)
(with-get-constant expr (:name name)
(let ((const (lookup-const name)))
(unless const
(error 'type-invalid-error :text
(tostring "could not find constant ~a" name)))
(merge-types forced-types (list (constant-type const))))))
((if-p expr)
(get-type (if-cmp expr) '(:type-bool) body-p)
(let ((t1 (get-type (if-e1 expr) forced-types body-p))
(t2 (get-type (if-e2 expr) forced-types body-p)))
(unless (equal t1 t2)
(error 'type-invalid-error :text
(tostring "expressions ~a and ~a must have equal types" (if-e1 expr) (if-e2 expr))))
t1))
((callf-p expr)
(let ((fun (lookup-function (callf-name expr))))
(unless fun (error 'type-invalid-error :text (tostring "undefined call ~a" (callf-name expr))))
(when (not (= (length (function-args expr)) (length (callf-args fun))))
(error 'type-invalid-error :text
(tostring "function call ~a has invalid number of arguments (should have ~a arguments)"
expr (length (function-args fun)))))
(loop for var in (function-args fun)
for arg in (callf-args expr)
do (progn
(get-type arg `(,(var-type var)) body-p)))
(merge-types forced-types `(,(function-ret-type fun)))))
((call-p expr)
(let ((extern (lookup-external-definition (call-name expr))))
(unless extern (error 'type-invalid-error :text (tostring "undefined call ~a" (call-name expr))))
(when (not (= (length (extern-types extern)) (length (call-args expr))))
(error 'type-invalid-error :text
(tostring "external call ~a has invalid number of arguments (should have ~a arguments)"
extern (length (extern-types extern)))))
(let* ((ret-types (merge-types forced-types `(,(extern-ret-type extern))))
(arg-types (extern-types extern))
(unified-arg-types (unify-arg-types arg-types (extern-ret-type extern) ret-types)))
(loop for typ in unified-arg-types
for arg in (call-args expr)
do (get-type arg `(,typ) body-p))
(let (change (concrete-arg-types (mapcar #'expr-type (call-args expr))))
(loop for i from 0 upto (1- (length concrete-arg-types))
for template-arg-type in arg-types
do (let ((concrete-type (nth i concrete-arg-types)))
(when (and (not (has-all-type-p concrete-type))
(has-all-type-p template-arg-type))
(setf change t)
(setf ret-types (loop for ret-type in ret-types
collect (unify-types ret-type concrete-type template-arg-type)))
(setf concrete-arg-types (loop for ty in concrete-arg-types
collect (unify-types ty concrete-type template-arg-type))))))
(when change
(loop for typ in concrete-arg-types
for arg in (call-args expr)
do (get-type arg `(,typ) body-p))))
ret-types)))
((let-p expr)
(if (variable-defined-p (let-var expr))
(error 'type-invalid-error :text (tostring "Variable ~a in LET is already defined" (let-var expr))))
(let* (ret
constraints
(var (let-var expr))
(typ-expr (get-type (let-expr expr) *all-types* body-p)))
(extend-typecheck-context
(force-constraint (var-name var) typ-expr)
(variable-is-defined var)
(setf ret (get-type (let-body expr) forced-types body-p))
(setf constraints (get-var-constraint (var-name var))))
(when (and (equal typ-expr constraints)
(> (length constraints) 1))
(error 'type-invalid-error :text
(tostring "Type of variable ~a cannot be properly defined. Maybe it is not being used in the LET?" var)))
(get-type (let-expr expr) constraints body-p)
ret
))
((convert-float-p expr)
(get-type (convert-float-expr expr) '(:type-int) body-p)
(merge-types forced-types '(:type-float)))
((nil-p expr) (merge-types forced-types *list-types*))
((world-p expr) (merge-types '(:type-int) forced-types))
((cpus-p expr) (merge-types '(:type-int) forced-types))
((struct-val-p expr)
(let* ((idx (struct-val-idx expr))
(var (struct-val-var expr)) ;; var is already typed
(vart (var-type var))
(ls (type-struct-list vart)))
(merge-types forced-types `(,(nth idx ls)))))
((struct-p expr)
(let ((types (get-struct-lists forced-types)))
(cond
((is-all-type-p types)
(list (make-struct-type (loop for subexpr in (struct-list expr)
collect (let ((ty (get-type subexpr types body-p)))
(if (and (listp ty) (one-elem-p ty))
(first ty)
ty))))))
(t
(loop for typ-list in types
do (when (= (length typ-list) (length (struct-list expr)))
(let ((new-types (loop for typ in typ-list
for subexpr in (struct-list expr)
collect (get-type subexpr `(,typ) body-p))))
(when (every #'(lambda (x) (not (null x))) new-types)
(return-from do-get-type `(,(make-struct-type (mapcar #'(lambda (x) (first x)) new-types))))))))))))
((cons-p expr)
(let* ((tail (cons-tail expr))
(head (cons-head expr))
(base-types (get-list-elements forced-types))
(head-types (get-type head base-types body-p))
(list-head-types (mapcar #'make-list-type head-types))
(new-types (merge-types list-head-types forced-types)))
;(warn "types ~a base-types ~a head-types ~a list-head-types ~a new-types ~a" forced-types
; base-types head-types list-head-types new-types)
(let ((tail-type (get-type tail new-types body-p)))
(when tail-type
;; re-updated head-type
(let* ((base-types (if (is-all-type-p tail-type) tail-type
(mapcar #'type-list-element tail-type)))
(head-types (get-type head base-types body-p)))
tail-type)))))
((head-p expr)
(let ((ls (head-list expr))
(list-types (mapcar #'make-list-type forced-types)))
(mapcar #'type-list-element (get-type ls list-types body-p))))
((tail-p expr)
(get-type (tail-list expr) forced-types body-p))
((not-p expr)
(merge-types forced-types (get-type (not-expr expr) '(:type-bool) body-p)))
((test-nil-p expr)
(get-type (test-nil-expr expr) *list-types* body-p)
(merge-types forced-types '(:type-bool)))
((op-p expr)
(let* ((op1 (op-op1 expr)) (op2 (op-op2 expr)) (op (op-op expr))
(typ-oper (type-operands op forced-types)) (typ-op (type-op op forced-types)))
(when (no-types-p typ-op)
(error 'type-invalid-error :text (tostring "no types error for result ~a or operands ~a" typ-op typ-oper)))
(let ((t1 (get-type op1 typ-oper body-p)) (t2 (get-type op2 typ-oper body-p)))
(when (< (length t1) (length t2))
(setf t2 (get-type op2 t1 body-p)))
(when (< (length t2) (length t1))
(setf t1 (get-type op1 t2 body-p)))
(let ((oper-type (merge-types t1 t2)))
(unless oper-type
(error 'type-invalid-error :text (tostring "can't merge operand types ~a ~a" t1 t2)))
(setf oper-type (get-type op1 oper-type body-p))
(setf oper-type (get-type op2 oper-type body-p))
(setf t1 oper-type)
(setf t2 oper-type)
(when (and (= (length oper-type) 2) (one-elem-p forced-types) (eq (first forced-types) :type-bool))
if having more than two types , select the simpler one
(setf t1 (get-type op1 (select-simpler-types oper-type) body-p))
(setf t2 (get-type op2 (select-simpler-types oper-type) body-p)))
(unless (equal t1 t2)
(error 'type-invalid-error :text (tostring "expressions ~a and ~a have different types: ~a ~a" op1 op2 (first t1) (first t2))))
(type-oper-op op t1)))))
(t (error 'type-invalid-error :text (tostring "get-type: Unknown expression ~a" expr))))))
(let ((types (do-get-type expr forced-types)))
(when (no-types-p types)
(error 'type-invalid-error :text (tostring "Type error in expression ~a: wanted types ~a but got ~a" expr forced-types types)))
(set-type expr types)
types)))
(defun do-type-check-subgoal (name args options &key (body-p nil) (axiom-p nil))
(let* ((def (lookup-definition name))
(definition (definition-types def)))
(unless def
(error 'type-invalid-error :text (concatenate 'string "Definition " name " not found")))
(when (not (= (length definition) (length args)))
(error 'type-invalid-error :text (tostring "Invalid number of arguments in subgoal ~a~a" name args)))
(cond
((is-linear-p def) ;; linear fact
(dolist (opt options)
(case opt
(:reused
(unless body-p
(error 'type-invalid-error :text (tostring "Linear reuse of facts must be used in the body, not the head: ~a" name))))
(:persistent
(error 'type-invalid-error :text (tostring "Only persistent facts may use !: ~a" name)))
(:random)
(:delay)
(:linear)
(otherwise
(cond
((listp opt))
(t
(error 'type-invalid-error :text (tostring "Unrecognized option ~a for subgoal ~a" opt name))))))))
(t ;; persistent fact
(let ((has-persistent-p nil))
(dolist (opt options)
(case opt
(:linear (error 'type-invalid-error :text (tostring "Only linear facts may use ?: ~a" name)))
(:reused
(error 'type-invalid-error :text (tostring "Reuse option $ may only be used with linear facts: ~a" name)))
(:persistent
(setf has-persistent-p t))
(:random)
(:delay)
(otherwise
(cond
((listp opt))
(t
(error 'type-invalid-error :text (tostring "Unrecognized option ~a for subgoal ~a" opt name)))))))
(unless has-persistent-p
(warn (tostring "Subgoal ~a needs to have a !" name))))))
(dolist2 (arg args) (forced-type (definition-arg-types definition))
(assert arg)
(let ((type-ret (get-type arg `(,forced-type) body-p)))
(unless type-ret
(error 'type-invalid-error :text (tostring "subgoal argument ~a from subgoal ~a~a has no type." arg name args)))
(unless (one-elem-p type-ret)
(error 'type-invalid-error :text (tostring "type error ~a type ~a" arg type-ret)))))))
(defun do-type-check-agg-construct (c in-body-p clause)
(let ((old-defined (copy-list *defined*))
(types nil))
(extend-typecheck-context
(do-subgoals (agg-construct-body c) (:name name :args args :options options)
(do-type-check-subgoal name args options :body-p t)))
(transform-agg-constructs-constants c)
(extend-typecheck-context
(do-subgoals (agg-construct-body c) (:args args)
(dolist (arg args)
(when (var-p arg)
(variable-is-defined arg)
(force-constraint (var-name arg) `(,(var-type arg))))))
(create-assignments (agg-construct-body c))
(assert-assignment-undefined (get-assignments (agg-construct-body c)))
(do-type-check-assignments (agg-construct-body c))
(do-constraints (agg-construct-body c) (:expr expr)
(do-type-check-constraints expr))
(optimize-agg-construct-constraints c clause)
(type-check-clause-head-assignments (agg-construct-head0 c))
(type-check-all-subgoals-and-conditionals (agg-construct-head0 c))
;; replace spec variable's types.
(do-agg-specs (agg-construct-specs c) (:op op :var to :args args)
(case op
(:custom
(let* ((fun (first args))
(start (second args))
(vtype (get-var-constraint (var-name to)))
(start-type (get-type start vtype nil))
(extern (lookup-external-definition fun))
(ret-type (extern-ret-type extern))
(args-type (extern-types extern)))
(assert (one-elem-p vtype))
(set-type to vtype)
(unless (and (every #L(equal !1 ret-type) args-type)
(= (length args-type) 2))
(error 'type-invalid-error :text (tostring "External function ~a must have equal types." fun)))
(set-type start start-type)
(let ((res (merge-type (first vtype) ret-type)))
(unless res
(error 'type-invalid-error :text (tostring "Types ~a and ~a from external ~a do not match." (first vtype) ret-type fun))))))
((:min :sum)
(let* ((vtype (get-var-constraint (var-name to))))
(assert (= 1 (length vtype)))
(set-type to vtype)
(set-var-constraint (var-name to) vtype)))
(:collect
(let* ((vtype (get-var-constraint (var-name to)))
(vtype-list (mapcar #'make-list-type vtype)))
(assert (= 1 (length vtype)))
(set-type to vtype-list)
(set-var-constraint (var-name to) vtype-list)))
(:count
(variable-is-defined to)
(set-type to '(:type-int))
(set-var-constraint (var-name to) '(:type-int)))
(otherwise
(error 'type-invalid-error :text (tostring "Not handling operator ~a" op)))))
(type-check-clause-head-assignments (agg-construct-head c))
(type-check-all-subgoals-and-conditionals (agg-construct-head c))
(cleanup-assignments-from-agg-construct c)
(optimize-subgoals (agg-construct-head c) (append (clause-body clause) (agg-construct-body c)))
(optimize-subgoals (agg-construct-head0 c) (append (clause-body clause) (agg-construct-body c)))
(cleanup-assignments-from-agg-construct c)
(let ((new-ones *defined-in-context*)
(target-variables (mapcar #'var-name (agg-construct-vlist c))))
(do-agg-specs (agg-construct-specs c) (:op op :var to :args args)
(when (or (eq op :sum)
(eq op :collect)
(eq op :count)
(eq op :min))
(push (var-name to) target-variables)))
(unless (subsetp new-ones target-variables)
(error 'type-invalid-error :text (tostring "Aggregate ~a is using more variables than it specifies ~a -> ~a" c new-ones target-variables)))
(unless (subsetp target-variables new-ones)
(error 'type-invalid-error :text (tostring "Aggregate ~a is not using enough variables ~a ~a" c target-variables new-ones)))))))
(defun do-type-check-constraints (expr)
;; LET has problems with this
;(unless (has-variables-defined expr)
; (error 'type-invalid-error :text (tostring "all variables must be defined: ~a , ~a" expr (all-variables expr))))
(let ((typs (get-type expr '(:type-bool) nil)))
(unless (and (one-elem-p typs) (type-bool-p (first typs)))
(error 'type-invalid-error :text "constraint must be of type bool"))))
(defun update-assignment (assignments assign)
(let* ((var (assignment-var assign)) (var-name (var-name var)))
(multiple-value-bind (forced-types ok) (gethash var-name *constraints*)
(let ((ty (get-type (assignment-expr assign) (if ok forced-types *all-types*) t)))
(variable-is-defined var)
(force-constraint var-name ty)
(set-type var ty)
(dolist (used-var (all-variables (assignment-expr assign)))
(alexandria:when-let ((other (find-if #'(lambda (a)
(and (var-eq-p used-var (assignment-var a))
(not (one-elem-p (expr-type (assignment-var a))))))
assignments)))
(update-assignment assignments other)))))))
(defun assert-assignment-undefined (assignments)
(unless (every #'(lambda (a) (not (variable-defined-p a))) (get-assignment-vars assignments))
(error 'type-invalid-error :text "some variables are already defined")))
(defun do-type-check-assignments (body)
(let ((assignments (get-assignments body)))
(loop while assignments
for assign = (find-if #'(lambda (a)
(has-variables-defined (assignment-expr a)))
assignments)
do (unless assign
(error 'type-invalid-error :text (tostring "undefined variables ~a" assignments)))
(setf assignments (delete assign assignments :test #'equal))
(when (< 1 (count-if #L(var-eq-p (assignment-var assign) !1) (get-assignment-vars assignments)))
(error 'type-invalid-error :text "cannot set multiple variables"))
(update-assignment assignments assign))))
(defun create-assignments (body)
"Turn undefined equal constraints to assignments"
(let (vars)
(do-constraints body (:expr expr :constraint orig)
(let ((op1 (op-op1 expr)) (op2 (op-op2 expr)))
(when (and (op-p expr) (equal-p expr) (var-p op1)
(not (variable-defined-p op1))
(not (has-elem-p vars (var-name op1))))
;; changes constraints to assignments
(setf (first orig) :assign)
(setf (second orig) op1)
(setf (cddr orig) (list op2))
(push (var-name op1) vars))))))
(defun unfold-cons (mangled-var cons)
(let* ((tail-var (generate-random-var (expr-type cons)))
(tail (cons-tail cons))
(head (cons-head cons))
(c1 (make-constraint (make-not (make-test-nil mangled-var)) 100)))
(multiple-value-bind (new-head head-constraints head-vars) (transform-constant-to-constraint head)
(let ((c2 (make-constraint (make-equal new-head '= (make-head mangled-var)))))
(cond
((cons-p tail)
(multiple-value-bind (tail-constraints tail-vars)
(unfold-cons tail-var tail)
(values (append `(,c1 ,c2
,(make-constraint (make-equal tail-var '= (make-tail mangled-var))))
(append head-constraints tail-constraints))
`(,tail-var ,@tail-vars ,@head-vars))))
(t
(values `(,c1 ,c2 ,@head-constraints ,(make-constraint (make-equal tail '= (make-tail mangled-var))))
`(,tail-var ,@head-vars))))))))
(defun unfold-struct (mangled-var struct)
(let* (all-constraints all-vars)
(let ((new-expr-list (loop for expr in (struct-list struct)
for typ in (type-struct-list (expr-type struct))
for i = 0 then (1+ i)
collect (let ((sval (make-struct-val i mangled-var typ)))
(multiple-value-bind (new-var constraints new-vars)
(transform-constant-to-constraint expr)
(push (make-constraint (make-equal new-var '= sval)) all-constraints)
(setf all-constraints (append all-constraints constraints))
(setf all-vars (append all-vars new-vars))
new-var)))))
(setf (struct-list struct) new-expr-list)
(values all-constraints all-vars))))
(defun transform-constant-to-constraint (arg &key use-host-p)
(cond
((var-p arg)
(values arg nil nil))
((and (addr-p arg) use-host-p)
(values (make-host-id) `(,(make-constraint (make-equal (make-host-id) '= arg))) nil))
((and (addr-p arg) (not use-host-p))
(let ((new-var (generate-random-var (expr-type arg))))
(values new-var `(,(make-constraint (make-equal new-var '= arg))) nil)))
((and (get-constant-p arg) use-host-p)
(values (make-host-id) `(,(make-constraint (make-equal (make-host-id) '= arg))) nil))
((const-p arg)
(let ((new-var (generate-random-var (expr-type arg))))
(values new-var `(,(make-constraint (make-equal new-var '= arg))) `(,new-var))))
((nil-p arg)
(let ((new-var (generate-random-var (expr-type arg))))
(values new-var `(,(make-constraint (make-test-nil new-var) 100)) `(,new-var))))
((cons-p arg)
(let ((new-var (generate-random-var (expr-type arg))))
(multiple-value-bind (new-constraints new-vars)
(unfold-cons new-var arg)
(values new-var new-constraints `(,new-var ,@new-vars)))))
((struct-p arg)
(let ((new-var (generate-random-var (expr-type arg))))
(multiple-value-bind (new-constraints new-vars)
(unfold-struct new-var arg)
(values new-var new-constraints `(,new-var ,@new-vars)))))
((op-p arg)
(let ((new-var (generate-random-var (expr-type arg))))
(values new-var `(,(make-constraint (make-equal new-var '= arg))) `(,new-var))))
(t (error 'type-invalid-error :text (tostring "subgoal argument ~a is invalid" arg)))))
(defun optimize-constraints-assignments (assigns constraints &optional constant-assigns constant-constraints)
"Optimizes constraints by computing constant expressions.
Returns new optimized set of constraints and assignments."
(let ((new-constraints constraints) (new-assigns assigns))
(loop for ass in assigns
do (setf (assignment-expr ass) (optimize-expr (assignment-expr ass) (append constraints constant-constraints) (append assigns constant-assigns))))
(loop for constr in constraints
do (let ((result (optimize-expr (constraint-expr constr) (append assigns constant-assigns) (append (remove-tree constraints constr) constant-constraints))))
(cond
((and (bool-p result) (bool-val result))
(warn "CONSTRAINT ~a is always true!" constr)
;; remove this constraint because it is always true
(delete-one new-constraints constr))
((and (bool-p result) (not (bool-val result)))
;; just a warning
(warn "CONSTRAINT ~a is always false!" constr))
(t
(setf (constraint-expr constr) result)))))
(append new-assigns new-constraints)))
(defun optimize-clause-constraints (clause)
(let* ((assigns (get-assignments (clause-body clause)))
(constraints (get-constraints (clause-body clause)))
(new-body (remove-all (remove-all (clause-body clause) assigns) constraints))
(new-assigns-constraints (optimize-constraints-assignments assigns constraints)))
(setf (clause-body clause) (append new-body new-assigns-constraints))))
(defun optimize-comprehension-constraints (compr clause)
(let* ((assigns (get-assignments (comprehension-left compr)))
(constraints (get-constraints (comprehension-left compr)))
(new-body (remove-all (remove-all (comprehension-left compr) assigns) constraints))
(new-assigns-constraints (optimize-constraints-assignments assigns constraints
(get-assignments (clause-body clause)) (get-constraints (clause-body clause)))))
(setf (comprehension-left compr) (append new-body new-assigns-constraints))))
(defun optimize-agg-construct-constraints (agg clause)
(let* ((assigns (get-assignments (agg-construct-body agg)))
(constraints (get-constraints (agg-construct-body agg)))
(new-body (remove-all (remove-all (agg-construct-body agg) assigns) constraints))
(new-assigns-constraints (optimize-constraints-assignments assigns constraints
(get-assignments (clause-body clause)) (get-constraints (clause-body clause)))))
(setf (agg-construct-body agg) (append new-body new-assigns-constraints))))
(defun transform-clause-constants (clause)
"Removes all constants from the subgoal arguments by creating constraints."
(let ((found-variables (make-hash-table :test #'equal)))
(do-subgoals (clause-body clause) (:args args :subgoal sub)
(let ((new-args (loop for arg in args
for i from 0
collect (cond
((and (var-p arg) (= i 0)) arg)
((var-p arg)
(multiple-value-bind (found found-p) (gethash (var-name arg) found-variables)
(cond
(found-p
(let ((new-var (generate-random-var (var-type arg))))
(push-end (make-constraint (make-equal new-var '= arg)) (clause-body clause))
new-var))
(t (setf (gethash (var-name arg) found-variables) arg)))))
(t
(multiple-value-bind (new-arg new-constraints)
(transform-constant-to-constraint arg :use-host-p nil)
(dolist (new-c new-constraints)
(assert (constraint-p new-c))
(push-end new-c (clause-body clause)))
new-arg))))))
(setf (subgoal-args sub) new-args)))))
(defun transform-constants-to-constraints-comprehension (comp args)
(mapcar #'(lambda (arg)
(multiple-value-bind (new-arg new-constraints)
(transform-constant-to-constraint arg)
(dolist (new-constraint new-constraints)
(push-end new-constraint (comprehension-left comp)))
new-arg))
args))
(defun transform-comprehension-constants (comp)
(do-subgoals (comprehension-left comp) (:args args :subgoal sub)
(setf (subgoal-args sub) (transform-constants-to-constraints-comprehension comp args))))
(defun transform-constants-to-constraints-agg-construct (c args &optional only-addr-p)
(mapcar #'(lambda (arg)
(multiple-value-bind (new-arg new-constraints new-vars)
(transform-constant-to-constraint arg :use-host-p only-addr-p)
(when new-vars
(setf (agg-construct-vlist c) (append (agg-construct-vlist c) new-vars)))
(dolist (new-constraint new-constraints)
(assert (constraint-p new-constraint))
(push-end new-constraint (agg-construct-body c)))
new-arg))
args))
(defun transform-agg-constructs-constants (c)
(do-subgoals (agg-construct-body c) (:args args :subgoal sub)
(setf (subgoal-args sub) (transform-constants-to-constraints-agg-construct c args))))
(defun add-variable-head-clause (clause &key (use-host-p nil))
(do-subgoals (clause-head clause) (:args args :subgoal sub)
(multiple-value-bind (new-arg constraints)
(transform-constant-to-constraint (first args) :use-host-p use-host-p)
(dolist (constraint constraints)
(push constraint (clause-body clause)))
(setf (first (subgoal-args sub)) new-arg))))
(defun add-variable-head ()
(do-rules (:clause clause)
(add-variable-head-clause clause))
(do-all-var-axioms (:clause clause)
(add-variable-head-clause clause :use-host-p t)))
(defun do-type-check-comprehension (comp clause)
(let ((target-variables (mapcar #'var-name (comprehension-variables comp))))
(extend-typecheck-context
(type-check-comprehension comp clause)
;; check if the set of new defined variables is identical to target-variables
(let ((new-ones *defined-in-context*))
(unless (subsetp new-ones target-variables)
(error 'type-invalid-error :text (tostring "Comprehension ~a is using more variables than it specifies" comp)))
(unless (subsetp target-variables new-ones)
(error 'type-invalid-error :text (tostring "Comprehension ~a is not using enough variables ~a ~a" comp target-variables new-ones)))))))
(defun do-type-check-exists (vars body clause)
(extend-typecheck-context
(dolist (var vars)
(force-constraint (var-name var) '(:type-addr))
(variable-is-defined var))
(do-type-check-head body clause :axiom-p nil)))
(defun type-check-body (clause host thread axiom-p)
(do-subgoals (clause-body clause) (:name name :args args :options options)
(handler-case
(do-type-check-subgoal name args options :body-p t)
(type-invalid-error (c) (error 'type-invalid-error :text
(tostring "In clause ~a~%~a" (clause-to-string clause) (text c))))))
(do-agg-constructs (clause-body clause) (:agg-construct c)
(do-type-check-agg-construct c t clause))
(transform-clause-constants clause)
(reset-typecheck-context)
(when axiom-p
(variable-is-defined host)
(force-constraint (var-name host) '(:type-addr)))
(do-subgoals (clause-body clause) (:args args)
(dolist (arg args)
(when (var-p arg)
(variable-is-defined arg)
(force-constraint (var-name arg) `(,(var-type arg))))))
(create-assignments (clause-body clause))
(assert-assignment-undefined (get-assignments (clause-body clause)))
(do-type-check-assignments (clause-body clause))
(do-constraints (clause-body clause) (:expr expr)
(do-type-check-constraints expr))
(optimize-clause-constraints clause))
(defun do-type-check-conditional (cond clause &key (axiom-p nil))
(with-conditional cond (:cmp cmp :term1 term1 :term2 term2)
(do-type-check-constraints cmp)
(do-type-check-head term1 clause :axiom-p axiom-p)
(do-type-check-head term2 clause :axiom-p axiom-p)))
(defun cleanup-assignments-from-clause (clause)
(let ((new-body (remove-unneeded-assignments (clause-body clause) (clause-head clause))))
(do-type-check-assignments new-body)
(setf (clause-body clause) new-body)))
(defun cleanup-assignments-from-comprehension (comp)
(let ((new-left (remove-unneeded-assignments (comprehension-left comp) (comprehension-right comp))))
(do-type-check-assignments new-left)
(setf (comprehension-left comp) new-left)))
(defun cleanup-assignments-from-agg-construct (agg)
(let ((new-body (remove-unneeded-assignments (agg-construct-body agg) (append (agg-construct-head0 agg) (agg-construct-head agg)))))
(do-type-check-assignments new-body)
(setf (agg-construct-body agg) new-body)))
(defun type-check-clause-head-subgoals (clause-head &key axiom-p)
(do-subgoals clause-head (:name name :args args :options options)
(do-type-check-subgoal name args options :axiom-p axiom-p)))
(defun type-check-clause-head-assignments (clause-head)
;; transforms equal constraints to assignments
(create-assignments clause-head)
(do-type-check-assignments clause-head))
(defun do-type-check-head (head clause &key axiom-p)
(type-check-clause-head-subgoals head :axiom-p axiom-p)
(do-comprehensions head (:comprehension comp)
(do-type-check-comprehension comp clause))
(do-agg-constructs head (:agg-construct c)
(do-type-check-agg-construct c nil clause))
(do-exists head (:var-list vars :body body)
(do-type-check-exists vars body clause)
(optimize-subgoals body (clause-body clause)))
(do-conditionals head (:conditional cond)
(optimize-conditional cond (clause-body clause))
(do-type-check-conditional cond clause :axiom-p axiom-p)))
(defun type-check-all-except-body (clause host thread &key axiom-p)
(when (and host axiom-p (not (variable-defined-p host)))
(variable-is-defined host))
(when (and thread axiom-p (not (variable-defined-p thread)))
(variable-is-defined thread))
(do-type-check-head (clause-head clause) clause :axiom-p axiom-p))
(defun optimize-subgoals (subgoals ass-constrs)
(let ((ass (get-assignments ass-constrs))
(constrs (get-constraints ass-constrs)))
(do-subgoals subgoals (:args args :subgoal sub)
(let ((new-args (mapcar #L(optimize-expr !1 ass constrs) args)))
(setf (subgoal-args sub) new-args)))))
(defun optimize-conditional (cond body)
(let ((ass (get-assignments body))
(constrs (get-constraints body)))
(setf (conditional-cmp cond) (optimize-expr (conditional-cmp cond) ass constrs))))
(defun type-check-body-and-head (clause host thread &key axiom-p)
(type-check-body clause host thread axiom-p)
(type-check-clause-head-assignments (clause-head clause))
(type-check-all-except-body clause host thread :axiom-p axiom-p)
(optimize-subgoals (clause-head clause) (clause-body clause))
;; we may need to re-check subgoals again because of optimizations
(type-check-clause-head-subgoals (clause-head clause) :axiom-p axiom-p)
(cleanup-assignments-from-clause clause))
(defun type-check-all-subgoals-and-conditionals (head)
(do-subgoals head (:name name :args args :options options)
(do-type-check-subgoal name args options))
(do-conditionals head (:cmp cmp :term1 term1 :term2 term2)
(do-type-check-constraints cmp)
(type-check-all-subgoals-and-conditionals term1)
(type-check-all-subgoals-and-conditionals term2)))
(defun type-check-comprehension (comp clause)
(extend-typecheck-context
(with-comprehension comp (:left left :right right)
(do-subgoals left (:name name :args args :options options)
(do-type-check-subgoal name args options :body-p t))))
(transform-comprehension-constants comp)
(with-comprehension comp (:left left :right right)
(do-subgoals left (:args args)
(dolist (arg args)
(when (var-p arg)
(variable-is-defined arg)
(force-constraint (var-name arg) `(,(var-type arg))))))
(create-assignments left)
(assert-assignment-undefined (get-assignments left))
(do-type-check-assignments left)
(do-constraints left (:expr expr)
(do-type-check-constraints expr)))
(optimize-comprehension-constraints comp clause)
(with-comprehension comp (:right right)
(type-check-clause-head-assignments right)
(type-check-all-subgoals-and-conditionals right)
(optimize-subgoals (recursively-get-subgoals right) (append (comprehension-left comp) (clause-body clause))))
(cleanup-assignments-from-comprehension comp))
(defun type-check-clause (clause axiom-p)
(with-typecheck-context
(multiple-value-bind (host thread) (find-host-nodes clause)
(type-check-body-and-head clause host thread :axiom-p axiom-p))
add : random to every subgoal with such variable
(when (clause-has-random-p clause)
(let ((var (clause-get-random-variable clause)))
(unless (variable-defined-p var)
(error 'type-invalid-error :text
(tostring "can't randomize variable ~a because such variable is not defined in the subgoal body" var)))
(do-subgoals (clause-body clause) (:subgoal sub)
(when (subgoal-has-var-p sub var)
(subgoal-add-option sub :random)))))
add : min to every subgoal with such variable
(when (clause-has-min-p clause)
(let ((var (clause-get-min-variable clause))
(involved-variables nil))
(unless (variable-defined-p var)
(error 'type-invalid-error :text
(tostring "can't minimize variable ~a because such variable is not defined in the subgoal body" var)))
(do-subgoals (clause-body clause) (:subgoal sub)
(when (subgoal-has-var-p sub var)
(subgoal-add-min sub var)
(with-subgoal sub (:args args)
(dolist (arg (rest args))
(unless (var-eq-p var arg)
(push arg involved-variables))))))))))
(defun type-check-const (const)
(with-constant const (:name name :expr expr)
(let* ((first-types (get-type expr *all-types* nil))
(res (select-simpler-types first-types)))
(unless (one-elem-p res)
(error 'type-invalid-error :text (tostring "could not determine type of const ~a" name)))
(unless (same-types-p first-types res)
(get-type expr res nil))
(unless (valid-type-p (first res))
(error 'type-invalid-error :text (tostring "could not determine type of const ~a" name)))
(setf (constant-type const) (first res)))))
(defun type-check-function (fun)
(with-typecheck-context
(with-function fun (:name name :args args :ret-type ret-type :body body)
(dolist (arg args)
(variable-is-defined arg)
(set-var-constraint (var-name arg) `(,(var-type arg))))
(get-type body `(,ret-type) nil))))
(defun check-repeated-definitions ()
(do-definitions (:name name1 :definition def1)
(do-definitions (:name name2 :definition def2)
(unless (eq def1 def2)
(if (string-equal name1 name2)
(error 'type-invalid-error :text (tostring "multiple definitions of ~a: ~a ~a" name1 def1 def2)))))))
(defun test-same-arguments-p (args1 args2 constraints)
(every #'(lambda (arg1 arg2)
(member arg2 (find-all-possible-assignments constraints arg1)
:test #'equal))
args1 args2))
(defun find-action-problems ()
"Build rule dependency graph and check if an action
can be derived in rules that dependent on each other.
For example:
a -o setColor, b.
b, c -o setColor.
This case is problematic because retraction will not work as intended when retracting c.
"
(let ((rgraph (make-hash-table)))
(do-all-rules (:clause clause :head head)
(do-subgoals head (:name name)
(let ((fired-rules (find-clauses-with-subgoal-in-body name)))
add new rules affected by this head subgoal
(loop for rule in fired-rules
unless (eq clause rule)
collect rule)
(gethash clause rgraph)))))
(iterate-hash (rgraph rule rules)
For each rule perform a DFS and check if there is any rule
;; that fires the same actions.
(with-clause rule (:head head)
(do-subgoals head (:name action-name)
(let ((def (lookup-definition action-name)))
head subgoal must be an action .
(when (is-action-p def)
(let ((visited (make-hash-table)))
(setf (gethash rule visited) t)
(labels ((dfs (visited-rule)
(multiple-value-bind (in found-p) (gethash visited-rule visited)
(unless found-p
(when (clause-head-matches-subgoal-p visited-rule action-name)
(warn "Action ~a in rule ~a may be used incorrectly"
action-name (clause-to-string rule)))
(setf (gethash visited-rule visited) t)
(multiple-value-bind (ls found-p) (gethash visited-rule rgraph)
(dolist (new-rule ls)
(dfs new-rule)))))))
(multiple-value-bind (ls found-p) (gethash rule rgraph)
(dolist (new-rule ls)
(dfs new-rule))))))))))))
(defun collect-basic-types ()
(setf *program-types* nil)
(do-definitions (:types types)
(dolist (ty types)
(setf *program-types* (add-type-to-typelist *program-types* (arg-type ty)))))
(do-constant-list *consts* (:type typ)
(setf *program-types* (add-type-to-typelist *program-types* typ)))
(do-externs *externs* (:types types :ret-type ret)
(setf *program-types* (add-type-to-typelist *program-types* ret))
(dolist (typ types)
(setf *program-types* (add-type-to-typelist *program-types* typ))))
(do-functions *functions* (:ret-type typ :args args)
(setf *program-types* (add-type-to-typelist *program-types* typ))
(dolist (arg args)
(setf *program-types* (add-type-to-typelist *program-types* (var-type arg))))))
(defun type-check ()
(do-definitions (:name name :types typs :definition def)
(check-home-argument name typs))
(check-repeated-definitions)
(do-index-list *directives* (:name name :field field)
(let ((def (lookup-definition name)))
(unless def
(error 'type-invalid-error :text
(tostring "Cannot find definition ~a from index directive" name)))
(unless (and (>= (length (definition-types def)) field)
(not (= field 0)))
(error 'type-invalid-error :text
(tostring "Field ~a from index in ~a does not exist" field name)))))
(dolist (const *consts*)
(type-check-const const))
(dolist (fun *functions*)
(type-check-function fun))
(do-externs *externs* (:name name :ret-type ret-type :types types)
(let ((extern (lookup-external-definition name)))
(unless extern
(error 'type-invalid-error :text (tostring "could not found external definition ~a" name)))
(unless (type-eq-p ret-type (extern-ret-type extern))
(error 'type-invalid-error :text
(tostring "external function return types do not match: ~a and ~a"
ret-type (extern-ret-type extern))))
(dolist2 (t1 types) (t2 (extern-types extern))
(unless (type-eq-p t1 t2)
(error 'type-invalid-error :text
(tostring "external function argument types do not match: ~a and ~a"
t1 t2))))))
(dolist (name *exported-predicates*)
(let ((def (lookup-definition name)))
(unless def
(error 'type-invalid-error :text (tostring "exported predicate ~a was not found" name)))))
(add-variable-head)
(collect-basic-types) ;; collect all basic types from predicates, funs and constants.
(do-all-rules (:clause clause)
(handler-case
(type-check-clause clause nil)
(type-invalid-error (c) (error 'type-invalid-error :text
(tostring "In clause ~a~%~a" (clause-to-string clause) (text c))))))
(do-all-const-axioms (:subgoal sub)
(with-subgoal sub (:name name :args args :options opts)
(do-type-check-subgoal name args opts :axiom-p t)
(optimize-subgoals (list sub) nil)))
(do-all-var-axioms (:clause clause)
(type-check-clause clause t))
;; remove unneeded constants
(let (to-remove)
;; constants that are really constant do not need to be stored anymore since their values have been computed
(dolist (const *consts*)
(with-constant const (:name name :expr expr)
(when (expr-is-constant-p expr nil nil)
(push const to-remove))))
(delete-all *consts* to-remove))
(find-action-problems))
| null | https://raw.githubusercontent.com/flavioc/cl-meld/8bfedb30137a15bfd94c6cfafe0a5107a050dd35/typecheck.lisp | lisp | do nothing
var is already typed
(warn "types ~a base-types ~a head-types ~a list-head-types ~a new-types ~a" forced-types
base-types head-types list-head-types new-types)
re-updated head-type
linear fact
persistent fact
replace spec variable's types.
LET has problems with this
(unless (has-variables-defined expr)
(error 'type-invalid-error :text (tostring "all variables must be defined: ~a , ~a" expr (all-variables expr))))
changes constraints to assignments
remove this constraint because it is always true
just a warning
check if the set of new defined variables is identical to target-variables
transforms equal constraints to assignments
we may need to re-check subgoals again because of optimizations
that fires the same actions.
collect all basic types from predicates, funs and constants.
remove unneeded constants
constants that are really constant do not need to be stored anymore since their values have been computed | (in-package :cl-meld)
(define-condition type-invalid-error (error)
((text :initarg :text :reader text)))
(defun check-home-argument (name typs)
(when (null typs)
(error 'type-invalid-error :text (concatenate 'string name " has no arguments")))
(let ((fst (first typs)))
(unless (or (type-addr-p fst) (type-thread-p fst) (type-node-p fst))
(error 'type-invalid-error
:text (concatenate 'string "first argument of tuple " name " must be of type 'node'")))))
(defun no-types-p (ls) (null ls))
(defun merge-type (t1 t2)
(assert (not (null t1)))
(assert (not (null t2)))
(if (equal t1 t2)
(return-from merge-type t1))
(cond
((eq t1 :all) t2)
((eq t2 :all) t1)
((and (type-node-p t1) (type-node-p t2))
(let ((a (type-node-type t1))
(b (type-node-type t2)))
(if (string-equal a b)
t1 nil)))
((and (type-addr-p t1) (type-node-p t2)) t2)
((and (type-node-p t1) (type-addr-p t2)) t1)
((and (type-list-p t1) (type-list-p t2))
(let* ((sub1 (type-list-element t1))
(sub2 (type-list-element t2))
(merged (merge-type sub1 sub2)))
(if merged
(make-list-type merged))))
((and (type-array-p t1) (type-array-p t2))
(let* ((sub1 (type-array-element t1))
(sub2 (type-array-element t2))
(merged (merge-type sub1 sub2)))
(if merged
(make-array-type merged))))
((and (type-set-p t1) (type-set-p t2))
(let* ((sub1 (type-set-element t1))
(sub2 (type-set-element t2))
(merged (merge-type sub1 sub2)))
(if merged
(make-set-type merged))))
((and (type-struct-p t1) (type-struct-p t2))
(let ((l1 (type-struct-list t1))
(l2 (type-struct-list t2)))
(cond
((eq l2 :all) t1)
((eq l1 :all) t2)
((not (= (length l1) (length l2))) nil)
(t
(let ((result
(loop for t1 in l1
for t2 in l2
collect (merge-types t1 t2))))
(if (find-if #'null result)
nil
(make-struct-type result)))))))
((and (listp t1) (listp t2))
(merge-types t1 t2))
((and (listp t1) (not (listp t2)) (eq t2 (first t1))) t2)
((and (listp t2) (not (listp t1)) (eq t1 (first t2))) t1)
((and (listp t1) (not (listp t2))) nil)
((and (not (listp t2)) (listp t2)) nil)
((and (not (listp t1)) (not (listp t2)))
(if (eq t1 t2)
t1
nil))
(t nil)))
(defun merge-with-suitable-list-type (types subtype)
(let ((ls (filter #'type-list-p types)))
(if (eq subtype :all)
ls
(let ((f (find-if #L(eq (type-list-element !1) subtype) ls)))
(when f
`(,f))))))
(defun merge-types (ls types)
(cond
((= (length ls) (length types) 1)
(let ((t1 (first ls))
(t2 (first types)))
(cond
((and (type-list-p t1)
(type-list-p t2))
(let ((t11 (type-list-element t1))
(t22 (type-list-element t2)))
(let ((merged-type (merge-type t11 t22)))
(when merged-type
`(,(make-list-type merged-type))))))
(t
(let ((merged (merge-type t1 t2)))
(when merged
`(,merged)))))))
((= (length ls) 1)
(let ((t1 (first ls)))
(if (eq t1 :all)
types
(if (type-list-p t1)
(let ((sub (type-list-element t1)))
(merge-with-suitable-list-type types sub))
(intersection ls types)))))
((= (length types) 1)
(let ((t2 (first types)))
(cond
((eq t2 :all) ls)
((type-list-p t2)
(let* ((t21 (type-list-element t2))
(list-types (filter #'type-list-p ls))
(elements (mapcar #'type-list-element list-types))
(merged (loop for element in elements
append (let ((m (merge-types (list element) (list t21))))
(when m
(list (make-list-type (first m))))))))
merged))
(t
(intersection ls types)))))
(t (intersection ls types :test #'equal))))
(defparameter *constraints* nil)
(defparameter *defined* nil)
(defparameter *defined-in-context* nil)
(defparameter *node-constraints* nil)
(defmacro with-node-type-context (&body body)
`(let ((*node-constraints* (make-hash-table))
(*node-types* nil))
,@body))
(defun get-node-constraint (addr-num)
(multiple-value-bind (type-found found-p) (gethash addr-num *node-constraints*)
type-found))
(defun find-node-type-id (node-type)
(when (or (null node-type) (type-addr-p node-type))
(return-from find-node-type-id 0))
(let ((x (type-node-type node-type)))
(loop for name in *node-types*
for c from 1
when (string-equal name x)
do (return-from find-node-type-id c))))
(defun add-node-constraint (addr typ)
(multiple-value-bind (type-found found-p) (gethash (addr-num addr) *node-constraints*)
(cond
((not (or (type-addr-p typ) (type-node-p typ)))
(error 'type-invalid-error :text (tostring "add-node-constraint: invalid node type ~a" typ)))
(found-p
(let ((result (merge-type type-found typ)))
(unless result
(error 'type-invalid-error :text (tostring "add-node-constraint: could not merge types '~a' and '~a' for node ~a"
(type-to-string type-found) (type-to-string typ) (addr-num addr))))
(setf (gethash (addr-num addr) *node-constraints*) result)
result))
(t
(setf (gethash (addr-num addr) *node-constraints*) typ)
typ))))
(defmacro with-typecheck-context (&body body)
`(let ((*defined* nil)
(*defined-in-context* nil)
(*constraints* (make-hash-table)))
,@body))
(defmacro extend-typecheck-context (&body body)
`(let ((*defined* (copy-list *defined*))
(*defined-in-context* nil)
(*constraints* (copy-hash-table *constraints*)))
,@body))
(defun reset-typecheck-context ()
(setf *defined* nil)
(setf *defined-in-context* nil)
(setf *constraints* (make-hash-table)))
(defun variable-is-defined (var)
(unless (has-elem-p *defined* (var-name var))
(push (var-name var) *defined-in-context*)
(push (var-name var) *defined*)))
(defun variable-defined-p (var) (has-elem-p *defined* (var-name var)))
(defun has-variables-defined (expr) (every #'variable-defined-p (all-variables expr)))
(defun set-type (expr typs)
(let ((typ (list (try-one typs))))
(when (and (one-elem-p typs)
(not (has-all-type-p typs)))
(setf *program-types* (add-type-to-typelist *program-types* (first typs))))
(cond
((or (nil-p expr) (host-p expr) (cpus-p expr)
(world-p expr) (host-id-p expr) (thread-id-p expr))
(setf (cdr expr) typ))
((or (var-p expr) (bool-p expr) (int-p expr) (float-p expr) (string-constant-p expr) (tail-p expr) (head-p expr)
(not-p expr) (test-nil-p expr) (addr-p expr) (convert-float-p expr)
(get-constant-p expr) (struct-p expr))
(setf (cddr expr) typ))
((or (call-p expr) (op-p expr) (callf-p expr)
(cons-p expr) (struct-val-p expr))
(setf (cdddr expr) typ))
((or (let-p expr) (if-p expr)) (setf (cddddr expr) typ))
(t (error 'type-invalid-error :text (tostring "set-type: Unknown expression ~a" expr))))))
(defun force-constraint (var new-types)
(multiple-value-bind (types ok) (gethash var *constraints*)
(when ok
(let ((old-types new-types))
(setf new-types (merge-types types new-types))
(when (no-types-p new-types)
(error 'type-invalid-error :text
(tostring "Type error in variable ~a: new constraint are types '~a' but variable is set as '~a'"
var (type-to-string (first old-types)) (type-to-string (first types)))))))
(set-var-constraint var new-types)))
(defun set-var-constraint (var new-types)
(assert (listp new-types))
(setf (gethash var *constraints*) new-types))
(defun get-var-constraint (var)
(gethash var *constraints*))
(defun select-simpler-types (types)
(cond
((= (length types) 1) types)
((= (length types) 2)
(if (and (has-elem-p types :type-int)
(has-elem-p types :type-float))
'(:type-int)
(if (every #'type-list-p types)
(let* ((list-types (mapcar #'type-list-element types))
(simplified (select-simpler-types list-types)))
(if (= (length simplified) 1)
(make-list-type (first simplified))
types))
types)))
(t types)))
(defun get-list-elements (forced-types)
(if (is-all-type-p forced-types)
forced-types
(mapcar #'type-list-element (filter #'type-list-p forced-types))))
(defun get-struct-lists (forced-types)
(if (is-all-type-p forced-types)
forced-types
(mapcar #'type-struct-list (filter #'type-struct-p forced-types))))
(defun unify-types (typ concrete-type concrete-template)
"Unify 'typ' by matching the concrete-template with concrete-type."
(cond
((eq concrete-template :all)
(subst concrete-type :all typ :test #'equal))
((type-list-p concrete-template)
(unify-types typ (type-list-element concrete-type) (type-list-element concrete-template)))
((type-array-p concrete-template)
(unify-types typ (type-array-element concrete-type) (type-array-element concrete-template)))
((type-set-p concrete-template)
(unify-types typ (type-set-element concrete-type) (type-set-element concrete-template)))
((type-struct-p concrete-template)
(cond
((eq (type-struct-list concrete-template) :all)
(subst (type-struct-list concrete-type) :all typ :test #'equal))
(t
(loop for conc in (type-struct-list concrete-type)
for temp in (type-struct-list concrete-template)
do (setf typ (unify-types typ conc temp)))
typ)))
(t typ)))
(defun unify-arg-types (arg-types template-ret ret-types)
(unless (has-all-type-p template-ret)
(return-from unify-arg-types arg-types))
(cond
((and (one-elem-p ret-types)
(not (has-all-type-p ret-types)))
(let ((f (first ret-types)))
(loop for arg in arg-types
collect (unify-types arg f template-ret))))
(t arg-types)))
(defun find-all-type (template concrete)
(cond
((eq template :all) concrete)
((type-list-p template) (find-all-type (type-list-element template) (type-list-element concrete)))
((type-array-p template) (find-all-type (type-array-element template) (type-array-element concrete)))
((type-set-p template) (find-all-type (type-set-element template) (type-set-element concrete)))
((type-struct-p template)
(when (eq (type-struct-list template) :all)
(return-from find-all-type concrete))
(loop for temp in (type-struct-list template)
for conc in (type-struct-list concrete)
do (let ((x (find-all-type temp conc)))
(when x
(return-from find-all-type x))))
(assert nil))
(t
nil)))
(defun get-type (expr forced-types body-p)
(assert (not (null forced-types)))
(assert (not (null (first forced-types))))
(labels ((do-get-type (expr forced-types)
(cond
((string-constant-p expr) (merge-types forced-types '(:type-string)))
((addr-p expr)
(when (one-elem-p forced-types)
(let ((ty (first forced-types)))
(cond
((is-all-type-p forced-types)
(add-node-constraint expr :type-addr)
'(:type-addr))
((type-addr-p ty)
(add-node-constraint expr ty)
'(:type-addr))
((type-node-p ty)
(add-node-constraint expr ty)
`(,ty))
(t nil)))))
((thread-id-p expr)
(when (one-elem-p forced-types)
(let ((ty (first forced-types)))
(cond
((is-all-type-p forced-types) '(:type-thread))
((type-thread-p ty) '(:type-thread))
(t nil)))))
((or (host-p expr) (host-id-p expr))
(when (one-elem-p forced-types)
(let ((ty (first forced-types)))
(cond
((is-all-type-p forced-types) '(:type-addr))
((type-addr-p ty) '(:type-addr))
((type-node-p ty) `(,ty))
(t nil)))))
((var-p expr)
(cond
(body-p
(variable-is-defined expr)
(let ((ret (force-constraint (var-name expr) forced-types)))
ret))
(t
(when (not (variable-defined-p expr))
(error 'type-invalid-error :text
(tostring "variable ~a is not defined" (var-name expr))))
(let ((ret (force-constraint (var-name expr) forced-types)))
ret))))
((bool-p expr) (merge-types forced-types '(:type-bool)))
((int-p expr) (let ((new-types (merge-types forced-types '(:type-int :type-float))))
(if (one-elem-this new-types :type-float)
(transform-int-to-float expr))
new-types))
((float-p expr) (merge-types forced-types '(:type-float)))
((argument-p expr) (merge-types forced-types '(:type-string)))
((get-constant-p expr)
(with-get-constant expr (:name name)
(let ((const (lookup-const name)))
(unless const
(error 'type-invalid-error :text
(tostring "could not find constant ~a" name)))
(merge-types forced-types (list (constant-type const))))))
((if-p expr)
(get-type (if-cmp expr) '(:type-bool) body-p)
(let ((t1 (get-type (if-e1 expr) forced-types body-p))
(t2 (get-type (if-e2 expr) forced-types body-p)))
(unless (equal t1 t2)
(error 'type-invalid-error :text
(tostring "expressions ~a and ~a must have equal types" (if-e1 expr) (if-e2 expr))))
t1))
((callf-p expr)
(let ((fun (lookup-function (callf-name expr))))
(unless fun (error 'type-invalid-error :text (tostring "undefined call ~a" (callf-name expr))))
(when (not (= (length (function-args expr)) (length (callf-args fun))))
(error 'type-invalid-error :text
(tostring "function call ~a has invalid number of arguments (should have ~a arguments)"
expr (length (function-args fun)))))
(loop for var in (function-args fun)
for arg in (callf-args expr)
do (progn
(get-type arg `(,(var-type var)) body-p)))
(merge-types forced-types `(,(function-ret-type fun)))))
((call-p expr)
(let ((extern (lookup-external-definition (call-name expr))))
(unless extern (error 'type-invalid-error :text (tostring "undefined call ~a" (call-name expr))))
(when (not (= (length (extern-types extern)) (length (call-args expr))))
(error 'type-invalid-error :text
(tostring "external call ~a has invalid number of arguments (should have ~a arguments)"
extern (length (extern-types extern)))))
(let* ((ret-types (merge-types forced-types `(,(extern-ret-type extern))))
(arg-types (extern-types extern))
(unified-arg-types (unify-arg-types arg-types (extern-ret-type extern) ret-types)))
(loop for typ in unified-arg-types
for arg in (call-args expr)
do (get-type arg `(,typ) body-p))
(let (change (concrete-arg-types (mapcar #'expr-type (call-args expr))))
(loop for i from 0 upto (1- (length concrete-arg-types))
for template-arg-type in arg-types
do (let ((concrete-type (nth i concrete-arg-types)))
(when (and (not (has-all-type-p concrete-type))
(has-all-type-p template-arg-type))
(setf change t)
(setf ret-types (loop for ret-type in ret-types
collect (unify-types ret-type concrete-type template-arg-type)))
(setf concrete-arg-types (loop for ty in concrete-arg-types
collect (unify-types ty concrete-type template-arg-type))))))
(when change
(loop for typ in concrete-arg-types
for arg in (call-args expr)
do (get-type arg `(,typ) body-p))))
ret-types)))
((let-p expr)
(if (variable-defined-p (let-var expr))
(error 'type-invalid-error :text (tostring "Variable ~a in LET is already defined" (let-var expr))))
(let* (ret
constraints
(var (let-var expr))
(typ-expr (get-type (let-expr expr) *all-types* body-p)))
(extend-typecheck-context
(force-constraint (var-name var) typ-expr)
(variable-is-defined var)
(setf ret (get-type (let-body expr) forced-types body-p))
(setf constraints (get-var-constraint (var-name var))))
(when (and (equal typ-expr constraints)
(> (length constraints) 1))
(error 'type-invalid-error :text
(tostring "Type of variable ~a cannot be properly defined. Maybe it is not being used in the LET?" var)))
(get-type (let-expr expr) constraints body-p)
ret
))
((convert-float-p expr)
(get-type (convert-float-expr expr) '(:type-int) body-p)
(merge-types forced-types '(:type-float)))
((nil-p expr) (merge-types forced-types *list-types*))
((world-p expr) (merge-types '(:type-int) forced-types))
((cpus-p expr) (merge-types '(:type-int) forced-types))
((struct-val-p expr)
(let* ((idx (struct-val-idx expr))
(vart (var-type var))
(ls (type-struct-list vart)))
(merge-types forced-types `(,(nth idx ls)))))
((struct-p expr)
(let ((types (get-struct-lists forced-types)))
(cond
((is-all-type-p types)
(list (make-struct-type (loop for subexpr in (struct-list expr)
collect (let ((ty (get-type subexpr types body-p)))
(if (and (listp ty) (one-elem-p ty))
(first ty)
ty))))))
(t
(loop for typ-list in types
do (when (= (length typ-list) (length (struct-list expr)))
(let ((new-types (loop for typ in typ-list
for subexpr in (struct-list expr)
collect (get-type subexpr `(,typ) body-p))))
(when (every #'(lambda (x) (not (null x))) new-types)
(return-from do-get-type `(,(make-struct-type (mapcar #'(lambda (x) (first x)) new-types))))))))))))
((cons-p expr)
(let* ((tail (cons-tail expr))
(head (cons-head expr))
(base-types (get-list-elements forced-types))
(head-types (get-type head base-types body-p))
(list-head-types (mapcar #'make-list-type head-types))
(new-types (merge-types list-head-types forced-types)))
(let ((tail-type (get-type tail new-types body-p)))
(when tail-type
(let* ((base-types (if (is-all-type-p tail-type) tail-type
(mapcar #'type-list-element tail-type)))
(head-types (get-type head base-types body-p)))
tail-type)))))
((head-p expr)
(let ((ls (head-list expr))
(list-types (mapcar #'make-list-type forced-types)))
(mapcar #'type-list-element (get-type ls list-types body-p))))
((tail-p expr)
(get-type (tail-list expr) forced-types body-p))
((not-p expr)
(merge-types forced-types (get-type (not-expr expr) '(:type-bool) body-p)))
((test-nil-p expr)
(get-type (test-nil-expr expr) *list-types* body-p)
(merge-types forced-types '(:type-bool)))
((op-p expr)
(let* ((op1 (op-op1 expr)) (op2 (op-op2 expr)) (op (op-op expr))
(typ-oper (type-operands op forced-types)) (typ-op (type-op op forced-types)))
(when (no-types-p typ-op)
(error 'type-invalid-error :text (tostring "no types error for result ~a or operands ~a" typ-op typ-oper)))
(let ((t1 (get-type op1 typ-oper body-p)) (t2 (get-type op2 typ-oper body-p)))
(when (< (length t1) (length t2))
(setf t2 (get-type op2 t1 body-p)))
(when (< (length t2) (length t1))
(setf t1 (get-type op1 t2 body-p)))
(let ((oper-type (merge-types t1 t2)))
(unless oper-type
(error 'type-invalid-error :text (tostring "can't merge operand types ~a ~a" t1 t2)))
(setf oper-type (get-type op1 oper-type body-p))
(setf oper-type (get-type op2 oper-type body-p))
(setf t1 oper-type)
(setf t2 oper-type)
(when (and (= (length oper-type) 2) (one-elem-p forced-types) (eq (first forced-types) :type-bool))
if having more than two types , select the simpler one
(setf t1 (get-type op1 (select-simpler-types oper-type) body-p))
(setf t2 (get-type op2 (select-simpler-types oper-type) body-p)))
(unless (equal t1 t2)
(error 'type-invalid-error :text (tostring "expressions ~a and ~a have different types: ~a ~a" op1 op2 (first t1) (first t2))))
(type-oper-op op t1)))))
(t (error 'type-invalid-error :text (tostring "get-type: Unknown expression ~a" expr))))))
(let ((types (do-get-type expr forced-types)))
(when (no-types-p types)
(error 'type-invalid-error :text (tostring "Type error in expression ~a: wanted types ~a but got ~a" expr forced-types types)))
(set-type expr types)
types)))
(defun do-type-check-subgoal (name args options &key (body-p nil) (axiom-p nil))
(let* ((def (lookup-definition name))
(definition (definition-types def)))
(unless def
(error 'type-invalid-error :text (concatenate 'string "Definition " name " not found")))
(when (not (= (length definition) (length args)))
(error 'type-invalid-error :text (tostring "Invalid number of arguments in subgoal ~a~a" name args)))
(cond
(dolist (opt options)
(case opt
(:reused
(unless body-p
(error 'type-invalid-error :text (tostring "Linear reuse of facts must be used in the body, not the head: ~a" name))))
(:persistent
(error 'type-invalid-error :text (tostring "Only persistent facts may use !: ~a" name)))
(:random)
(:delay)
(:linear)
(otherwise
(cond
((listp opt))
(t
(error 'type-invalid-error :text (tostring "Unrecognized option ~a for subgoal ~a" opt name))))))))
(let ((has-persistent-p nil))
(dolist (opt options)
(case opt
(:linear (error 'type-invalid-error :text (tostring "Only linear facts may use ?: ~a" name)))
(:reused
(error 'type-invalid-error :text (tostring "Reuse option $ may only be used with linear facts: ~a" name)))
(:persistent
(setf has-persistent-p t))
(:random)
(:delay)
(otherwise
(cond
((listp opt))
(t
(error 'type-invalid-error :text (tostring "Unrecognized option ~a for subgoal ~a" opt name)))))))
(unless has-persistent-p
(warn (tostring "Subgoal ~a needs to have a !" name))))))
(dolist2 (arg args) (forced-type (definition-arg-types definition))
(assert arg)
(let ((type-ret (get-type arg `(,forced-type) body-p)))
(unless type-ret
(error 'type-invalid-error :text (tostring "subgoal argument ~a from subgoal ~a~a has no type." arg name args)))
(unless (one-elem-p type-ret)
(error 'type-invalid-error :text (tostring "type error ~a type ~a" arg type-ret)))))))
(defun do-type-check-agg-construct (c in-body-p clause)
(let ((old-defined (copy-list *defined*))
(types nil))
(extend-typecheck-context
(do-subgoals (agg-construct-body c) (:name name :args args :options options)
(do-type-check-subgoal name args options :body-p t)))
(transform-agg-constructs-constants c)
(extend-typecheck-context
(do-subgoals (agg-construct-body c) (:args args)
(dolist (arg args)
(when (var-p arg)
(variable-is-defined arg)
(force-constraint (var-name arg) `(,(var-type arg))))))
(create-assignments (agg-construct-body c))
(assert-assignment-undefined (get-assignments (agg-construct-body c)))
(do-type-check-assignments (agg-construct-body c))
(do-constraints (agg-construct-body c) (:expr expr)
(do-type-check-constraints expr))
(optimize-agg-construct-constraints c clause)
(type-check-clause-head-assignments (agg-construct-head0 c))
(type-check-all-subgoals-and-conditionals (agg-construct-head0 c))
(do-agg-specs (agg-construct-specs c) (:op op :var to :args args)
(case op
(:custom
(let* ((fun (first args))
(start (second args))
(vtype (get-var-constraint (var-name to)))
(start-type (get-type start vtype nil))
(extern (lookup-external-definition fun))
(ret-type (extern-ret-type extern))
(args-type (extern-types extern)))
(assert (one-elem-p vtype))
(set-type to vtype)
(unless (and (every #L(equal !1 ret-type) args-type)
(= (length args-type) 2))
(error 'type-invalid-error :text (tostring "External function ~a must have equal types." fun)))
(set-type start start-type)
(let ((res (merge-type (first vtype) ret-type)))
(unless res
(error 'type-invalid-error :text (tostring "Types ~a and ~a from external ~a do not match." (first vtype) ret-type fun))))))
((:min :sum)
(let* ((vtype (get-var-constraint (var-name to))))
(assert (= 1 (length vtype)))
(set-type to vtype)
(set-var-constraint (var-name to) vtype)))
(:collect
(let* ((vtype (get-var-constraint (var-name to)))
(vtype-list (mapcar #'make-list-type vtype)))
(assert (= 1 (length vtype)))
(set-type to vtype-list)
(set-var-constraint (var-name to) vtype-list)))
(:count
(variable-is-defined to)
(set-type to '(:type-int))
(set-var-constraint (var-name to) '(:type-int)))
(otherwise
(error 'type-invalid-error :text (tostring "Not handling operator ~a" op)))))
(type-check-clause-head-assignments (agg-construct-head c))
(type-check-all-subgoals-and-conditionals (agg-construct-head c))
(cleanup-assignments-from-agg-construct c)
(optimize-subgoals (agg-construct-head c) (append (clause-body clause) (agg-construct-body c)))
(optimize-subgoals (agg-construct-head0 c) (append (clause-body clause) (agg-construct-body c)))
(cleanup-assignments-from-agg-construct c)
(let ((new-ones *defined-in-context*)
(target-variables (mapcar #'var-name (agg-construct-vlist c))))
(do-agg-specs (agg-construct-specs c) (:op op :var to :args args)
(when (or (eq op :sum)
(eq op :collect)
(eq op :count)
(eq op :min))
(push (var-name to) target-variables)))
(unless (subsetp new-ones target-variables)
(error 'type-invalid-error :text (tostring "Aggregate ~a is using more variables than it specifies ~a -> ~a" c new-ones target-variables)))
(unless (subsetp target-variables new-ones)
(error 'type-invalid-error :text (tostring "Aggregate ~a is not using enough variables ~a ~a" c target-variables new-ones)))))))
(defun do-type-check-constraints (expr)
(let ((typs (get-type expr '(:type-bool) nil)))
(unless (and (one-elem-p typs) (type-bool-p (first typs)))
(error 'type-invalid-error :text "constraint must be of type bool"))))
(defun update-assignment (assignments assign)
(let* ((var (assignment-var assign)) (var-name (var-name var)))
(multiple-value-bind (forced-types ok) (gethash var-name *constraints*)
(let ((ty (get-type (assignment-expr assign) (if ok forced-types *all-types*) t)))
(variable-is-defined var)
(force-constraint var-name ty)
(set-type var ty)
(dolist (used-var (all-variables (assignment-expr assign)))
(alexandria:when-let ((other (find-if #'(lambda (a)
(and (var-eq-p used-var (assignment-var a))
(not (one-elem-p (expr-type (assignment-var a))))))
assignments)))
(update-assignment assignments other)))))))
(defun assert-assignment-undefined (assignments)
(unless (every #'(lambda (a) (not (variable-defined-p a))) (get-assignment-vars assignments))
(error 'type-invalid-error :text "some variables are already defined")))
(defun do-type-check-assignments (body)
(let ((assignments (get-assignments body)))
(loop while assignments
for assign = (find-if #'(lambda (a)
(has-variables-defined (assignment-expr a)))
assignments)
do (unless assign
(error 'type-invalid-error :text (tostring "undefined variables ~a" assignments)))
(setf assignments (delete assign assignments :test #'equal))
(when (< 1 (count-if #L(var-eq-p (assignment-var assign) !1) (get-assignment-vars assignments)))
(error 'type-invalid-error :text "cannot set multiple variables"))
(update-assignment assignments assign))))
(defun create-assignments (body)
"Turn undefined equal constraints to assignments"
(let (vars)
(do-constraints body (:expr expr :constraint orig)
(let ((op1 (op-op1 expr)) (op2 (op-op2 expr)))
(when (and (op-p expr) (equal-p expr) (var-p op1)
(not (variable-defined-p op1))
(not (has-elem-p vars (var-name op1))))
(setf (first orig) :assign)
(setf (second orig) op1)
(setf (cddr orig) (list op2))
(push (var-name op1) vars))))))
(defun unfold-cons (mangled-var cons)
(let* ((tail-var (generate-random-var (expr-type cons)))
(tail (cons-tail cons))
(head (cons-head cons))
(c1 (make-constraint (make-not (make-test-nil mangled-var)) 100)))
(multiple-value-bind (new-head head-constraints head-vars) (transform-constant-to-constraint head)
(let ((c2 (make-constraint (make-equal new-head '= (make-head mangled-var)))))
(cond
((cons-p tail)
(multiple-value-bind (tail-constraints tail-vars)
(unfold-cons tail-var tail)
(values (append `(,c1 ,c2
,(make-constraint (make-equal tail-var '= (make-tail mangled-var))))
(append head-constraints tail-constraints))
`(,tail-var ,@tail-vars ,@head-vars))))
(t
(values `(,c1 ,c2 ,@head-constraints ,(make-constraint (make-equal tail '= (make-tail mangled-var))))
`(,tail-var ,@head-vars))))))))
(defun unfold-struct (mangled-var struct)
(let* (all-constraints all-vars)
(let ((new-expr-list (loop for expr in (struct-list struct)
for typ in (type-struct-list (expr-type struct))
for i = 0 then (1+ i)
collect (let ((sval (make-struct-val i mangled-var typ)))
(multiple-value-bind (new-var constraints new-vars)
(transform-constant-to-constraint expr)
(push (make-constraint (make-equal new-var '= sval)) all-constraints)
(setf all-constraints (append all-constraints constraints))
(setf all-vars (append all-vars new-vars))
new-var)))))
(setf (struct-list struct) new-expr-list)
(values all-constraints all-vars))))
(defun transform-constant-to-constraint (arg &key use-host-p)
(cond
((var-p arg)
(values arg nil nil))
((and (addr-p arg) use-host-p)
(values (make-host-id) `(,(make-constraint (make-equal (make-host-id) '= arg))) nil))
((and (addr-p arg) (not use-host-p))
(let ((new-var (generate-random-var (expr-type arg))))
(values new-var `(,(make-constraint (make-equal new-var '= arg))) nil)))
((and (get-constant-p arg) use-host-p)
(values (make-host-id) `(,(make-constraint (make-equal (make-host-id) '= arg))) nil))
((const-p arg)
(let ((new-var (generate-random-var (expr-type arg))))
(values new-var `(,(make-constraint (make-equal new-var '= arg))) `(,new-var))))
((nil-p arg)
(let ((new-var (generate-random-var (expr-type arg))))
(values new-var `(,(make-constraint (make-test-nil new-var) 100)) `(,new-var))))
((cons-p arg)
(let ((new-var (generate-random-var (expr-type arg))))
(multiple-value-bind (new-constraints new-vars)
(unfold-cons new-var arg)
(values new-var new-constraints `(,new-var ,@new-vars)))))
((struct-p arg)
(let ((new-var (generate-random-var (expr-type arg))))
(multiple-value-bind (new-constraints new-vars)
(unfold-struct new-var arg)
(values new-var new-constraints `(,new-var ,@new-vars)))))
((op-p arg)
(let ((new-var (generate-random-var (expr-type arg))))
(values new-var `(,(make-constraint (make-equal new-var '= arg))) `(,new-var))))
(t (error 'type-invalid-error :text (tostring "subgoal argument ~a is invalid" arg)))))
(defun optimize-constraints-assignments (assigns constraints &optional constant-assigns constant-constraints)
"Optimizes constraints by computing constant expressions.
Returns new optimized set of constraints and assignments."
(let ((new-constraints constraints) (new-assigns assigns))
(loop for ass in assigns
do (setf (assignment-expr ass) (optimize-expr (assignment-expr ass) (append constraints constant-constraints) (append assigns constant-assigns))))
(loop for constr in constraints
do (let ((result (optimize-expr (constraint-expr constr) (append assigns constant-assigns) (append (remove-tree constraints constr) constant-constraints))))
(cond
((and (bool-p result) (bool-val result))
(warn "CONSTRAINT ~a is always true!" constr)
(delete-one new-constraints constr))
((and (bool-p result) (not (bool-val result)))
(warn "CONSTRAINT ~a is always false!" constr))
(t
(setf (constraint-expr constr) result)))))
(append new-assigns new-constraints)))
(defun optimize-clause-constraints (clause)
(let* ((assigns (get-assignments (clause-body clause)))
(constraints (get-constraints (clause-body clause)))
(new-body (remove-all (remove-all (clause-body clause) assigns) constraints))
(new-assigns-constraints (optimize-constraints-assignments assigns constraints)))
(setf (clause-body clause) (append new-body new-assigns-constraints))))
(defun optimize-comprehension-constraints (compr clause)
(let* ((assigns (get-assignments (comprehension-left compr)))
(constraints (get-constraints (comprehension-left compr)))
(new-body (remove-all (remove-all (comprehension-left compr) assigns) constraints))
(new-assigns-constraints (optimize-constraints-assignments assigns constraints
(get-assignments (clause-body clause)) (get-constraints (clause-body clause)))))
(setf (comprehension-left compr) (append new-body new-assigns-constraints))))
(defun optimize-agg-construct-constraints (agg clause)
(let* ((assigns (get-assignments (agg-construct-body agg)))
(constraints (get-constraints (agg-construct-body agg)))
(new-body (remove-all (remove-all (agg-construct-body agg) assigns) constraints))
(new-assigns-constraints (optimize-constraints-assignments assigns constraints
(get-assignments (clause-body clause)) (get-constraints (clause-body clause)))))
(setf (agg-construct-body agg) (append new-body new-assigns-constraints))))
(defun transform-clause-constants (clause)
"Removes all constants from the subgoal arguments by creating constraints."
(let ((found-variables (make-hash-table :test #'equal)))
(do-subgoals (clause-body clause) (:args args :subgoal sub)
(let ((new-args (loop for arg in args
for i from 0
collect (cond
((and (var-p arg) (= i 0)) arg)
((var-p arg)
(multiple-value-bind (found found-p) (gethash (var-name arg) found-variables)
(cond
(found-p
(let ((new-var (generate-random-var (var-type arg))))
(push-end (make-constraint (make-equal new-var '= arg)) (clause-body clause))
new-var))
(t (setf (gethash (var-name arg) found-variables) arg)))))
(t
(multiple-value-bind (new-arg new-constraints)
(transform-constant-to-constraint arg :use-host-p nil)
(dolist (new-c new-constraints)
(assert (constraint-p new-c))
(push-end new-c (clause-body clause)))
new-arg))))))
(setf (subgoal-args sub) new-args)))))
(defun transform-constants-to-constraints-comprehension (comp args)
(mapcar #'(lambda (arg)
(multiple-value-bind (new-arg new-constraints)
(transform-constant-to-constraint arg)
(dolist (new-constraint new-constraints)
(push-end new-constraint (comprehension-left comp)))
new-arg))
args))
(defun transform-comprehension-constants (comp)
(do-subgoals (comprehension-left comp) (:args args :subgoal sub)
(setf (subgoal-args sub) (transform-constants-to-constraints-comprehension comp args))))
(defun transform-constants-to-constraints-agg-construct (c args &optional only-addr-p)
(mapcar #'(lambda (arg)
(multiple-value-bind (new-arg new-constraints new-vars)
(transform-constant-to-constraint arg :use-host-p only-addr-p)
(when new-vars
(setf (agg-construct-vlist c) (append (agg-construct-vlist c) new-vars)))
(dolist (new-constraint new-constraints)
(assert (constraint-p new-constraint))
(push-end new-constraint (agg-construct-body c)))
new-arg))
args))
(defun transform-agg-constructs-constants (c)
(do-subgoals (agg-construct-body c) (:args args :subgoal sub)
(setf (subgoal-args sub) (transform-constants-to-constraints-agg-construct c args))))
(defun add-variable-head-clause (clause &key (use-host-p nil))
(do-subgoals (clause-head clause) (:args args :subgoal sub)
(multiple-value-bind (new-arg constraints)
(transform-constant-to-constraint (first args) :use-host-p use-host-p)
(dolist (constraint constraints)
(push constraint (clause-body clause)))
(setf (first (subgoal-args sub)) new-arg))))
(defun add-variable-head ()
(do-rules (:clause clause)
(add-variable-head-clause clause))
(do-all-var-axioms (:clause clause)
(add-variable-head-clause clause :use-host-p t)))
(defun do-type-check-comprehension (comp clause)
(let ((target-variables (mapcar #'var-name (comprehension-variables comp))))
(extend-typecheck-context
(type-check-comprehension comp clause)
(let ((new-ones *defined-in-context*))
(unless (subsetp new-ones target-variables)
(error 'type-invalid-error :text (tostring "Comprehension ~a is using more variables than it specifies" comp)))
(unless (subsetp target-variables new-ones)
(error 'type-invalid-error :text (tostring "Comprehension ~a is not using enough variables ~a ~a" comp target-variables new-ones)))))))
(defun do-type-check-exists (vars body clause)
(extend-typecheck-context
(dolist (var vars)
(force-constraint (var-name var) '(:type-addr))
(variable-is-defined var))
(do-type-check-head body clause :axiom-p nil)))
(defun type-check-body (clause host thread axiom-p)
(do-subgoals (clause-body clause) (:name name :args args :options options)
(handler-case
(do-type-check-subgoal name args options :body-p t)
(type-invalid-error (c) (error 'type-invalid-error :text
(tostring "In clause ~a~%~a" (clause-to-string clause) (text c))))))
(do-agg-constructs (clause-body clause) (:agg-construct c)
(do-type-check-agg-construct c t clause))
(transform-clause-constants clause)
(reset-typecheck-context)
(when axiom-p
(variable-is-defined host)
(force-constraint (var-name host) '(:type-addr)))
(do-subgoals (clause-body clause) (:args args)
(dolist (arg args)
(when (var-p arg)
(variable-is-defined arg)
(force-constraint (var-name arg) `(,(var-type arg))))))
(create-assignments (clause-body clause))
(assert-assignment-undefined (get-assignments (clause-body clause)))
(do-type-check-assignments (clause-body clause))
(do-constraints (clause-body clause) (:expr expr)
(do-type-check-constraints expr))
(optimize-clause-constraints clause))
(defun do-type-check-conditional (cond clause &key (axiom-p nil))
(with-conditional cond (:cmp cmp :term1 term1 :term2 term2)
(do-type-check-constraints cmp)
(do-type-check-head term1 clause :axiom-p axiom-p)
(do-type-check-head term2 clause :axiom-p axiom-p)))
(defun cleanup-assignments-from-clause (clause)
(let ((new-body (remove-unneeded-assignments (clause-body clause) (clause-head clause))))
(do-type-check-assignments new-body)
(setf (clause-body clause) new-body)))
(defun cleanup-assignments-from-comprehension (comp)
(let ((new-left (remove-unneeded-assignments (comprehension-left comp) (comprehension-right comp))))
(do-type-check-assignments new-left)
(setf (comprehension-left comp) new-left)))
(defun cleanup-assignments-from-agg-construct (agg)
(let ((new-body (remove-unneeded-assignments (agg-construct-body agg) (append (agg-construct-head0 agg) (agg-construct-head agg)))))
(do-type-check-assignments new-body)
(setf (agg-construct-body agg) new-body)))
(defun type-check-clause-head-subgoals (clause-head &key axiom-p)
(do-subgoals clause-head (:name name :args args :options options)
(do-type-check-subgoal name args options :axiom-p axiom-p)))
(defun type-check-clause-head-assignments (clause-head)
(create-assignments clause-head)
(do-type-check-assignments clause-head))
(defun do-type-check-head (head clause &key axiom-p)
(type-check-clause-head-subgoals head :axiom-p axiom-p)
(do-comprehensions head (:comprehension comp)
(do-type-check-comprehension comp clause))
(do-agg-constructs head (:agg-construct c)
(do-type-check-agg-construct c nil clause))
(do-exists head (:var-list vars :body body)
(do-type-check-exists vars body clause)
(optimize-subgoals body (clause-body clause)))
(do-conditionals head (:conditional cond)
(optimize-conditional cond (clause-body clause))
(do-type-check-conditional cond clause :axiom-p axiom-p)))
(defun type-check-all-except-body (clause host thread &key axiom-p)
(when (and host axiom-p (not (variable-defined-p host)))
(variable-is-defined host))
(when (and thread axiom-p (not (variable-defined-p thread)))
(variable-is-defined thread))
(do-type-check-head (clause-head clause) clause :axiom-p axiom-p))
(defun optimize-subgoals (subgoals ass-constrs)
(let ((ass (get-assignments ass-constrs))
(constrs (get-constraints ass-constrs)))
(do-subgoals subgoals (:args args :subgoal sub)
(let ((new-args (mapcar #L(optimize-expr !1 ass constrs) args)))
(setf (subgoal-args sub) new-args)))))
(defun optimize-conditional (cond body)
(let ((ass (get-assignments body))
(constrs (get-constraints body)))
(setf (conditional-cmp cond) (optimize-expr (conditional-cmp cond) ass constrs))))
(defun type-check-body-and-head (clause host thread &key axiom-p)
(type-check-body clause host thread axiom-p)
(type-check-clause-head-assignments (clause-head clause))
(type-check-all-except-body clause host thread :axiom-p axiom-p)
(optimize-subgoals (clause-head clause) (clause-body clause))
(type-check-clause-head-subgoals (clause-head clause) :axiom-p axiom-p)
(cleanup-assignments-from-clause clause))
(defun type-check-all-subgoals-and-conditionals (head)
(do-subgoals head (:name name :args args :options options)
(do-type-check-subgoal name args options))
(do-conditionals head (:cmp cmp :term1 term1 :term2 term2)
(do-type-check-constraints cmp)
(type-check-all-subgoals-and-conditionals term1)
(type-check-all-subgoals-and-conditionals term2)))
(defun type-check-comprehension (comp clause)
(extend-typecheck-context
(with-comprehension comp (:left left :right right)
(do-subgoals left (:name name :args args :options options)
(do-type-check-subgoal name args options :body-p t))))
(transform-comprehension-constants comp)
(with-comprehension comp (:left left :right right)
(do-subgoals left (:args args)
(dolist (arg args)
(when (var-p arg)
(variable-is-defined arg)
(force-constraint (var-name arg) `(,(var-type arg))))))
(create-assignments left)
(assert-assignment-undefined (get-assignments left))
(do-type-check-assignments left)
(do-constraints left (:expr expr)
(do-type-check-constraints expr)))
(optimize-comprehension-constraints comp clause)
(with-comprehension comp (:right right)
(type-check-clause-head-assignments right)
(type-check-all-subgoals-and-conditionals right)
(optimize-subgoals (recursively-get-subgoals right) (append (comprehension-left comp) (clause-body clause))))
(cleanup-assignments-from-comprehension comp))
(defun type-check-clause (clause axiom-p)
(with-typecheck-context
(multiple-value-bind (host thread) (find-host-nodes clause)
(type-check-body-and-head clause host thread :axiom-p axiom-p))
add : random to every subgoal with such variable
(when (clause-has-random-p clause)
(let ((var (clause-get-random-variable clause)))
(unless (variable-defined-p var)
(error 'type-invalid-error :text
(tostring "can't randomize variable ~a because such variable is not defined in the subgoal body" var)))
(do-subgoals (clause-body clause) (:subgoal sub)
(when (subgoal-has-var-p sub var)
(subgoal-add-option sub :random)))))
add : min to every subgoal with such variable
(when (clause-has-min-p clause)
(let ((var (clause-get-min-variable clause))
(involved-variables nil))
(unless (variable-defined-p var)
(error 'type-invalid-error :text
(tostring "can't minimize variable ~a because such variable is not defined in the subgoal body" var)))
(do-subgoals (clause-body clause) (:subgoal sub)
(when (subgoal-has-var-p sub var)
(subgoal-add-min sub var)
(with-subgoal sub (:args args)
(dolist (arg (rest args))
(unless (var-eq-p var arg)
(push arg involved-variables))))))))))
(defun type-check-const (const)
(with-constant const (:name name :expr expr)
(let* ((first-types (get-type expr *all-types* nil))
(res (select-simpler-types first-types)))
(unless (one-elem-p res)
(error 'type-invalid-error :text (tostring "could not determine type of const ~a" name)))
(unless (same-types-p first-types res)
(get-type expr res nil))
(unless (valid-type-p (first res))
(error 'type-invalid-error :text (tostring "could not determine type of const ~a" name)))
(setf (constant-type const) (first res)))))
(defun type-check-function (fun)
(with-typecheck-context
(with-function fun (:name name :args args :ret-type ret-type :body body)
(dolist (arg args)
(variable-is-defined arg)
(set-var-constraint (var-name arg) `(,(var-type arg))))
(get-type body `(,ret-type) nil))))
(defun check-repeated-definitions ()
(do-definitions (:name name1 :definition def1)
(do-definitions (:name name2 :definition def2)
(unless (eq def1 def2)
(if (string-equal name1 name2)
(error 'type-invalid-error :text (tostring "multiple definitions of ~a: ~a ~a" name1 def1 def2)))))))
(defun test-same-arguments-p (args1 args2 constraints)
(every #'(lambda (arg1 arg2)
(member arg2 (find-all-possible-assignments constraints arg1)
:test #'equal))
args1 args2))
(defun find-action-problems ()
"Build rule dependency graph and check if an action
can be derived in rules that dependent on each other.
For example:
a -o setColor, b.
b, c -o setColor.
This case is problematic because retraction will not work as intended when retracting c.
"
(let ((rgraph (make-hash-table)))
(do-all-rules (:clause clause :head head)
(do-subgoals head (:name name)
(let ((fired-rules (find-clauses-with-subgoal-in-body name)))
add new rules affected by this head subgoal
(loop for rule in fired-rules
unless (eq clause rule)
collect rule)
(gethash clause rgraph)))))
(iterate-hash (rgraph rule rules)
For each rule perform a DFS and check if there is any rule
(with-clause rule (:head head)
(do-subgoals head (:name action-name)
(let ((def (lookup-definition action-name)))
head subgoal must be an action .
(when (is-action-p def)
(let ((visited (make-hash-table)))
(setf (gethash rule visited) t)
(labels ((dfs (visited-rule)
(multiple-value-bind (in found-p) (gethash visited-rule visited)
(unless found-p
(when (clause-head-matches-subgoal-p visited-rule action-name)
(warn "Action ~a in rule ~a may be used incorrectly"
action-name (clause-to-string rule)))
(setf (gethash visited-rule visited) t)
(multiple-value-bind (ls found-p) (gethash visited-rule rgraph)
(dolist (new-rule ls)
(dfs new-rule)))))))
(multiple-value-bind (ls found-p) (gethash rule rgraph)
(dolist (new-rule ls)
(dfs new-rule))))))))))))
(defun collect-basic-types ()
(setf *program-types* nil)
(do-definitions (:types types)
(dolist (ty types)
(setf *program-types* (add-type-to-typelist *program-types* (arg-type ty)))))
(do-constant-list *consts* (:type typ)
(setf *program-types* (add-type-to-typelist *program-types* typ)))
(do-externs *externs* (:types types :ret-type ret)
(setf *program-types* (add-type-to-typelist *program-types* ret))
(dolist (typ types)
(setf *program-types* (add-type-to-typelist *program-types* typ))))
(do-functions *functions* (:ret-type typ :args args)
(setf *program-types* (add-type-to-typelist *program-types* typ))
(dolist (arg args)
(setf *program-types* (add-type-to-typelist *program-types* (var-type arg))))))
(defun type-check ()
(do-definitions (:name name :types typs :definition def)
(check-home-argument name typs))
(check-repeated-definitions)
(do-index-list *directives* (:name name :field field)
(let ((def (lookup-definition name)))
(unless def
(error 'type-invalid-error :text
(tostring "Cannot find definition ~a from index directive" name)))
(unless (and (>= (length (definition-types def)) field)
(not (= field 0)))
(error 'type-invalid-error :text
(tostring "Field ~a from index in ~a does not exist" field name)))))
(dolist (const *consts*)
(type-check-const const))
(dolist (fun *functions*)
(type-check-function fun))
(do-externs *externs* (:name name :ret-type ret-type :types types)
(let ((extern (lookup-external-definition name)))
(unless extern
(error 'type-invalid-error :text (tostring "could not found external definition ~a" name)))
(unless (type-eq-p ret-type (extern-ret-type extern))
(error 'type-invalid-error :text
(tostring "external function return types do not match: ~a and ~a"
ret-type (extern-ret-type extern))))
(dolist2 (t1 types) (t2 (extern-types extern))
(unless (type-eq-p t1 t2)
(error 'type-invalid-error :text
(tostring "external function argument types do not match: ~a and ~a"
t1 t2))))))
(dolist (name *exported-predicates*)
(let ((def (lookup-definition name)))
(unless def
(error 'type-invalid-error :text (tostring "exported predicate ~a was not found" name)))))
(add-variable-head)
(do-all-rules (:clause clause)
(handler-case
(type-check-clause clause nil)
(type-invalid-error (c) (error 'type-invalid-error :text
(tostring "In clause ~a~%~a" (clause-to-string clause) (text c))))))
(do-all-const-axioms (:subgoal sub)
(with-subgoal sub (:name name :args args :options opts)
(do-type-check-subgoal name args opts :axiom-p t)
(optimize-subgoals (list sub) nil)))
(do-all-var-axioms (:clause clause)
(type-check-clause clause t))
(let (to-remove)
(dolist (const *consts*)
(with-constant const (:name name :expr expr)
(when (expr-is-constant-p expr nil nil)
(push const to-remove))))
(delete-all *consts* to-remove))
(find-action-problems))
|
3be34ed910c1c04467670b903cda0c7db2ef426b3f14c85ef18d2f6d8b590493 | google/ormolu | grouped-splices-out.hs | $(deriveJSON fieldLabelMod ''A)
$(deriveJSON fieldLabelMod ''B)
$(deriveJSON fieldLabelMod ''C)
| null | https://raw.githubusercontent.com/google/ormolu/ffdf145bbdf917d54a3ef4951fc2655e35847ff0/data/examples/declaration/splice/grouped-splices-out.hs | haskell | $(deriveJSON fieldLabelMod ''A)
$(deriveJSON fieldLabelMod ''B)
$(deriveJSON fieldLabelMod ''C)
| |
72f4e352b14e60852916ae42b2df6e7519dd7032537dbbe82070f7171bcf4c10 | jixiuf/helloerlang | test.erl | -module(test).
-export([terminate/2,handle_cast/2,handle_call/3,init/1,start_link/0]).
start_link()->
gen_server_2:start_link(?MODULE,[])
.
init(State)->
{ok,State}
.
handle_call(hello,_From,State)->
io:format("you say hello~n",[]),
{reply,you_say_hello, State};
handle_call(world,From,State)->
Reply=gen_server_2:reply(self(),you_say_world),
io:format("~p:~p~n",[self(),From]),
io:format("the reply is :~p~n",[Reply]) ,
{noreply, State};
handle_call(terminate,_From,State)->
{stop, shutdown, shutdown, State};
handle_call(_Req,_From,State)->
{noreply, State}
.
handle_cast(hello,State)->
io:format("you say hello by cast!~n",[]),
{noreply, State} ;
handle_cast(world,State)->
io:format("you say world by cast!~n",[]),
{noreply, State} .
terminate(_Reason,_State)->
ok .
| null | https://raw.githubusercontent.com/jixiuf/helloerlang/3960eb4237b026f98edf35d6064539259a816d58/gen_server_2/src/test.erl | erlang | -module(test).
-export([terminate/2,handle_cast/2,handle_call/3,init/1,start_link/0]).
start_link()->
gen_server_2:start_link(?MODULE,[])
.
init(State)->
{ok,State}
.
handle_call(hello,_From,State)->
io:format("you say hello~n",[]),
{reply,you_say_hello, State};
handle_call(world,From,State)->
Reply=gen_server_2:reply(self(),you_say_world),
io:format("~p:~p~n",[self(),From]),
io:format("the reply is :~p~n",[Reply]) ,
{noreply, State};
handle_call(terminate,_From,State)->
{stop, shutdown, shutdown, State};
handle_call(_Req,_From,State)->
{noreply, State}
.
handle_cast(hello,State)->
io:format("you say hello by cast!~n",[]),
{noreply, State} ;
handle_cast(world,State)->
io:format("you say world by cast!~n",[]),
{noreply, State} .
terminate(_Reason,_State)->
ok .
| |
c8af026d99d7a9d21c129f0ac41faa55a66ec8ac5df1943994b346909f0fa05a | chetmurthy/typpx | sugar.ml | open Ast_helper
open Parsetree
open Asttypes
open Ast_mapper
let extend super =
let structure_item self sitem = match sitem.pstr_desc with
| Pstr_extension ( ({txt="overloaded"}, PStr [{pstr_desc= Pstr_primitive vd}] ), _attr ) ->
(* val%overloaded x : t => external x : t = "__OVERLOADED" *)
Str.primitive ~loc:sitem.pstr_loc { vd with pval_prim = [ "__OVERLOADED" ] }
| _ -> super.structure_item self sitem
in
let signature_item self sitem = match sitem.psig_desc with
| Psig_extension ( ({txt="overloaded"}, PSig [{psig_desc= Psig_value vd}] ), _attr ) ->
(* val%overloaded x : t => external x : t = "__OVERLOADED" *)
Sig.value ~loc:sitem.psig_loc { vd with pval_prim = [ "__OVERLOADED" ] }
| _ -> super.signature_item self sitem
in
{ super with signature_item; structure_item }
| null | https://raw.githubusercontent.com/chetmurthy/typpx/a740750b75739e686da49b46ded7db7d6874e108/examples/ppx_overload/sugar.ml | ocaml | val%overloaded x : t => external x : t = "__OVERLOADED"
val%overloaded x : t => external x : t = "__OVERLOADED" | open Ast_helper
open Parsetree
open Asttypes
open Ast_mapper
let extend super =
let structure_item self sitem = match sitem.pstr_desc with
| Pstr_extension ( ({txt="overloaded"}, PStr [{pstr_desc= Pstr_primitive vd}] ), _attr ) ->
Str.primitive ~loc:sitem.pstr_loc { vd with pval_prim = [ "__OVERLOADED" ] }
| _ -> super.structure_item self sitem
in
let signature_item self sitem = match sitem.psig_desc with
| Psig_extension ( ({txt="overloaded"}, PSig [{psig_desc= Psig_value vd}] ), _attr ) ->
Sig.value ~loc:sitem.psig_loc { vd with pval_prim = [ "__OVERLOADED" ] }
| _ -> super.signature_item self sitem
in
{ super with signature_item; structure_item }
|
1cd3a01c7b1f863dc445d0bae0374b838491a99724b22f34aa659ad1e41ffa43 | haskell-opengl/OpenGLRaw | TextureFloat.hs | # LANGUAGE PatternSynonyms #
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ATI.TextureFloat
Copyright : ( c ) 2019
-- License : BSD3
--
Maintainer : < >
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ATI.TextureFloat (
-- * Extension Support
glGetATITextureFloat,
gl_ATI_texture_float,
-- * Enums
pattern GL_ALPHA_FLOAT16_ATI,
pattern GL_ALPHA_FLOAT32_ATI,
pattern GL_INTENSITY_FLOAT16_ATI,
pattern GL_INTENSITY_FLOAT32_ATI,
pattern GL_LUMINANCE_ALPHA_FLOAT16_ATI,
pattern GL_LUMINANCE_ALPHA_FLOAT32_ATI,
pattern GL_LUMINANCE_FLOAT16_ATI,
pattern GL_LUMINANCE_FLOAT32_ATI,
pattern GL_RGBA_FLOAT16_ATI,
pattern GL_RGBA_FLOAT32_ATI,
pattern GL_RGB_FLOAT16_ATI,
pattern GL_RGB_FLOAT32_ATI
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
| null | https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/ATI/TextureFloat.hs | haskell | ------------------------------------------------------------------------------
|
Module : Graphics.GL.ATI.TextureFloat
License : BSD3
Stability : stable
Portability : portable
------------------------------------------------------------------------------
* Extension Support
* Enums | # LANGUAGE PatternSynonyms #
Copyright : ( c ) 2019
Maintainer : < >
module Graphics.GL.ATI.TextureFloat (
glGetATITextureFloat,
gl_ATI_texture_float,
pattern GL_ALPHA_FLOAT16_ATI,
pattern GL_ALPHA_FLOAT32_ATI,
pattern GL_INTENSITY_FLOAT16_ATI,
pattern GL_INTENSITY_FLOAT32_ATI,
pattern GL_LUMINANCE_ALPHA_FLOAT16_ATI,
pattern GL_LUMINANCE_ALPHA_FLOAT32_ATI,
pattern GL_LUMINANCE_FLOAT16_ATI,
pattern GL_LUMINANCE_FLOAT32_ATI,
pattern GL_RGBA_FLOAT16_ATI,
pattern GL_RGBA_FLOAT32_ATI,
pattern GL_RGB_FLOAT16_ATI,
pattern GL_RGB_FLOAT32_ATI
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
|
df5c8bd328a30337f69c8dba33df4d3dac3b240e28279b5543592589fc8fe09a | gedge-platform/gedge-platform | rabbit_exchange_type.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(rabbit_exchange_type).
-behaviour(rabbit_registry_class).
-export([added_to_rabbit_registry/2, removed_from_rabbit_registry/1]).
-type(tx() :: 'transaction' | 'none').
-type(serial() :: pos_integer() | tx()).
-callback description() -> [proplists:property()].
%% Should Rabbit ensure that all binding events that are
%% delivered to an individual exchange can be serialised? (they
%% might still be delivered out of order, but there'll be a
%% serial number).
-callback serialise_events() -> boolean().
%% The no_return is there so that we can have an "invalid" exchange
%% type (see rabbit_exchange_type_invalid).
-callback route(rabbit_types:exchange(), rabbit_types:delivery()) ->
rabbit_router:match_result().
called BEFORE declaration , to check args etc ; may exit with # amqp_error { }
-callback validate(rabbit_types:exchange()) -> 'ok'.
called BEFORE declaration , to check args etc
-callback validate_binding(rabbit_types:exchange(), rabbit_types:binding()) ->
rabbit_types:ok_or_error({'binding_invalid', string(), [any()]}).
%% called after declaration and recovery
-callback create(tx(), rabbit_types:exchange()) -> 'ok'.
%% called after exchange (auto)deletion.
-callback delete(tx(), rabbit_types:exchange(), [rabbit_types:binding()]) ->
'ok'.
%% called when the policy attached to this exchange changes.
-callback policy_changed(rabbit_types:exchange(), rabbit_types:exchange()) ->
'ok'.
%% called after a binding has been added or recovered
-callback add_binding(serial(), rabbit_types:exchange(),
rabbit_types:binding()) -> 'ok'.
%% called after bindings have been deleted.
-callback remove_bindings(serial(), rabbit_types:exchange(),
[rabbit_types:binding()]) -> 'ok'.
%% called when comparing exchanges for equivalence - should return ok or
%% exit with #amqp_error{}
-callback assert_args_equivalence(rabbit_types:exchange(),
rabbit_framing:amqp_table()) ->
'ok' | rabbit_types:connection_exit().
Exchange type specific info keys
-callback info(rabbit_types:exchange()) -> [{atom(), term()}].
-callback info(rabbit_types:exchange(), [atom()]) -> [{atom(), term()}].
added_to_rabbit_registry(_Type, _ModuleName) -> ok.
removed_from_rabbit_registry(_Type) -> ok.
| null | https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbit_common/src/rabbit_exchange_type.erl | erlang |
Should Rabbit ensure that all binding events that are
delivered to an individual exchange can be serialised? (they
might still be delivered out of order, but there'll be a
serial number).
The no_return is there so that we can have an "invalid" exchange
type (see rabbit_exchange_type_invalid).
called after declaration and recovery
called after exchange (auto)deletion.
called when the policy attached to this exchange changes.
called after a binding has been added or recovered
called after bindings have been deleted.
called when comparing exchanges for equivalence - should return ok or
exit with #amqp_error{} | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved .
-module(rabbit_exchange_type).
-behaviour(rabbit_registry_class).
-export([added_to_rabbit_registry/2, removed_from_rabbit_registry/1]).
-type(tx() :: 'transaction' | 'none').
-type(serial() :: pos_integer() | tx()).
-callback description() -> [proplists:property()].
-callback serialise_events() -> boolean().
-callback route(rabbit_types:exchange(), rabbit_types:delivery()) ->
rabbit_router:match_result().
called BEFORE declaration , to check args etc ; may exit with # amqp_error { }
-callback validate(rabbit_types:exchange()) -> 'ok'.
called BEFORE declaration , to check args etc
-callback validate_binding(rabbit_types:exchange(), rabbit_types:binding()) ->
rabbit_types:ok_or_error({'binding_invalid', string(), [any()]}).
-callback create(tx(), rabbit_types:exchange()) -> 'ok'.
-callback delete(tx(), rabbit_types:exchange(), [rabbit_types:binding()]) ->
'ok'.
-callback policy_changed(rabbit_types:exchange(), rabbit_types:exchange()) ->
'ok'.
-callback add_binding(serial(), rabbit_types:exchange(),
rabbit_types:binding()) -> 'ok'.
-callback remove_bindings(serial(), rabbit_types:exchange(),
[rabbit_types:binding()]) -> 'ok'.
-callback assert_args_equivalence(rabbit_types:exchange(),
rabbit_framing:amqp_table()) ->
'ok' | rabbit_types:connection_exit().
Exchange type specific info keys
-callback info(rabbit_types:exchange()) -> [{atom(), term()}].
-callback info(rabbit_types:exchange(), [atom()]) -> [{atom(), term()}].
added_to_rabbit_registry(_Type, _ModuleName) -> ok.
removed_from_rabbit_registry(_Type) -> ok.
|
c1a38d50165e2d4eda1bd85f2d94db5c3dd2b7057e5423fea464fc95550ad911 | magthe/sandi | Base64Url.hs | # LANGUAGE ForeignFunctionInterface #
-- |
-- Module: Codec.Binary.Base64Url
Copyright : ( c ) 2012
-- License: BSD3
--
Implemented as specified in RFC 4648 ( < > ) .
--
The difference compared to vanilla Base64 encoding is just in two
characters . In Base64 the characters are used , and in Base64Url they
are replaced by @_-@ respectively .
--
-- Please refer to "Codec.Binary.Base64" for the details of all functions in
-- this module.
module Codec.Binary.Base64Url
( b64uEncodePart
, b64uEncodeFinal
, b64uDecodePart
, b64uDecodeFinal
, encode
, decode
) where
import Foreign
import Foreign.C.Types
import qualified Data.ByteString as BS
import Data.ByteString.Unsafe
import System.IO.Unsafe as U
castEnum :: (Enum a, Enum b) => a -> b
castEnum = toEnum . fromEnum
foreign import ccall "static b64.h b64u_enc_part"
c_b64u_enc_part :: Ptr Word8 -> CSize -> Ptr Word8 -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr CSize -> IO ()
foreign import ccall "static b64.h b64u_enc_final"
c_b64u_enc_final :: Ptr Word8 -> CSize -> Ptr Word8 -> Ptr CSize -> IO CInt
foreign import ccall "static b64.h b64u_dec_part"
c_b64u_dec_part :: Ptr Word8 -> CSize -> Ptr Word8 -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr CSize -> IO CInt
foreign import ccall "static b64.h b64u_dec_final"
c_b64u_dec_final :: Ptr Word8 -> CSize -> Ptr Word8 -> Ptr CSize -> IO CInt
b64uEncodePart :: BS.ByteString -> (BS.ByteString, BS.ByteString)
b64uEncodePart bs = U.unsafePerformIO $ unsafeUseAsCStringLen bs $ \ (inBuf, inLen) -> do
let maxOutLen = inLen `div` 3 * 4
outBuf <- mallocBytes maxOutLen
alloca $ \ pOutLen ->
alloca $ \ pRemBuf ->
alloca $ \ pRemLen -> do
poke pOutLen (castEnum maxOutLen)
c_b64u_enc_part (castPtr inBuf) (castEnum inLen) outBuf pOutLen pRemBuf pRemLen
outLen <- peek pOutLen
remBuf <- peek pRemBuf
remLen <- peek pRemLen
remBs <- BS.packCStringLen (castPtr remBuf, castEnum remLen)
outBs <- unsafePackCStringFinalizer outBuf (castEnum outLen) (free outBuf)
return (outBs, remBs)
b64uEncodeFinal :: BS.ByteString -> Maybe BS.ByteString
b64uEncodeFinal bs = U.unsafePerformIO $ unsafeUseAsCStringLen bs $ \ (inBuf, inLen) -> do
outBuf <- mallocBytes 4
alloca $ \ pOutLen -> do
r <- c_b64u_enc_final (castPtr inBuf) (castEnum inLen) outBuf pOutLen
if r == 0
then do
outLen <- peek pOutLen
newOutBuf <- reallocBytes outBuf (castEnum outLen)
outBs <- unsafePackCStringFinalizer newOutBuf (castEnum outLen) (free newOutBuf)
return $ Just outBs
else free outBuf >> return Nothing
b64uDecodePart :: BS.ByteString -> Either (BS.ByteString, BS.ByteString) (BS.ByteString, BS.ByteString)
b64uDecodePart bs = U.unsafePerformIO $ unsafeUseAsCStringLen bs $ \ (inBuf, inLen) -> do
let maxOutLen = inLen `div` 4 * 3
outBuf <- mallocBytes maxOutLen
alloca $ \ pOutLen ->
alloca $ \ pRemBuf ->
alloca $ \ pRemLen -> do
poke pOutLen (castEnum maxOutLen)
r <- c_b64u_dec_part (castPtr inBuf) (castEnum inLen) outBuf pOutLen pRemBuf pRemLen
outLen <- peek pOutLen
newOutBuf <- reallocBytes outBuf (castEnum outLen)
remBuf <- peek pRemBuf
remLen <- peek pRemLen
remBs <- BS.packCStringLen (castPtr remBuf, castEnum remLen)
outBs <- unsafePackCStringFinalizer newOutBuf (castEnum outLen) (free newOutBuf)
if r == 0
then return $ Right (outBs, remBs)
else return $ Left (outBs, remBs)
b64uDecodeFinal :: BS.ByteString -> Maybe BS.ByteString
b64uDecodeFinal bs = U.unsafePerformIO $ unsafeUseAsCStringLen bs $ \ (inBuf, inLen) -> do
outBuf <- mallocBytes 3
alloca $ \ pOutLen -> do
r <- c_b64u_dec_final (castPtr inBuf) (castEnum inLen) outBuf pOutLen
if r == 0
then do
outLen <- peek pOutLen
newOutBuf <- reallocBytes outBuf (castEnum outLen)
outBs <- unsafePackCStringFinalizer newOutBuf (castEnum outLen) (free newOutBuf)
return $ Just outBs
else free outBuf >> return Nothing
encode :: BS.ByteString -> BS.ByteString
encode bs = first `BS.append` final
where
(first, rest) = b64uEncodePart bs
Just final = b64uEncodeFinal rest
decode :: BS.ByteString -> Either (BS.ByteString, BS.ByteString) BS.ByteString
decode bs = either
Left
(\ (first, rest) ->
maybe
(Left (first, rest))
(\ fin -> Right (first `BS.append` fin))
(b64uDecodeFinal rest))
(b64uDecodePart bs)
| null | https://raw.githubusercontent.com/magthe/sandi/a8ef86ec3798a640d86342421a7fa7fa97bdedd4/sandi/src/Codec/Binary/Base64Url.hs | haskell | |
Module: Codec.Binary.Base64Url
License: BSD3
Please refer to "Codec.Binary.Base64" for the details of all functions in
this module. | # LANGUAGE ForeignFunctionInterface #
Copyright : ( c ) 2012
Implemented as specified in RFC 4648 ( < > ) .
The difference compared to vanilla Base64 encoding is just in two
characters . In Base64 the characters are used , and in Base64Url they
are replaced by @_-@ respectively .
module Codec.Binary.Base64Url
( b64uEncodePart
, b64uEncodeFinal
, b64uDecodePart
, b64uDecodeFinal
, encode
, decode
) where
import Foreign
import Foreign.C.Types
import qualified Data.ByteString as BS
import Data.ByteString.Unsafe
import System.IO.Unsafe as U
castEnum :: (Enum a, Enum b) => a -> b
castEnum = toEnum . fromEnum
foreign import ccall "static b64.h b64u_enc_part"
c_b64u_enc_part :: Ptr Word8 -> CSize -> Ptr Word8 -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr CSize -> IO ()
foreign import ccall "static b64.h b64u_enc_final"
c_b64u_enc_final :: Ptr Word8 -> CSize -> Ptr Word8 -> Ptr CSize -> IO CInt
foreign import ccall "static b64.h b64u_dec_part"
c_b64u_dec_part :: Ptr Word8 -> CSize -> Ptr Word8 -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr CSize -> IO CInt
foreign import ccall "static b64.h b64u_dec_final"
c_b64u_dec_final :: Ptr Word8 -> CSize -> Ptr Word8 -> Ptr CSize -> IO CInt
b64uEncodePart :: BS.ByteString -> (BS.ByteString, BS.ByteString)
b64uEncodePart bs = U.unsafePerformIO $ unsafeUseAsCStringLen bs $ \ (inBuf, inLen) -> do
let maxOutLen = inLen `div` 3 * 4
outBuf <- mallocBytes maxOutLen
alloca $ \ pOutLen ->
alloca $ \ pRemBuf ->
alloca $ \ pRemLen -> do
poke pOutLen (castEnum maxOutLen)
c_b64u_enc_part (castPtr inBuf) (castEnum inLen) outBuf pOutLen pRemBuf pRemLen
outLen <- peek pOutLen
remBuf <- peek pRemBuf
remLen <- peek pRemLen
remBs <- BS.packCStringLen (castPtr remBuf, castEnum remLen)
outBs <- unsafePackCStringFinalizer outBuf (castEnum outLen) (free outBuf)
return (outBs, remBs)
b64uEncodeFinal :: BS.ByteString -> Maybe BS.ByteString
b64uEncodeFinal bs = U.unsafePerformIO $ unsafeUseAsCStringLen bs $ \ (inBuf, inLen) -> do
outBuf <- mallocBytes 4
alloca $ \ pOutLen -> do
r <- c_b64u_enc_final (castPtr inBuf) (castEnum inLen) outBuf pOutLen
if r == 0
then do
outLen <- peek pOutLen
newOutBuf <- reallocBytes outBuf (castEnum outLen)
outBs <- unsafePackCStringFinalizer newOutBuf (castEnum outLen) (free newOutBuf)
return $ Just outBs
else free outBuf >> return Nothing
b64uDecodePart :: BS.ByteString -> Either (BS.ByteString, BS.ByteString) (BS.ByteString, BS.ByteString)
b64uDecodePart bs = U.unsafePerformIO $ unsafeUseAsCStringLen bs $ \ (inBuf, inLen) -> do
let maxOutLen = inLen `div` 4 * 3
outBuf <- mallocBytes maxOutLen
alloca $ \ pOutLen ->
alloca $ \ pRemBuf ->
alloca $ \ pRemLen -> do
poke pOutLen (castEnum maxOutLen)
r <- c_b64u_dec_part (castPtr inBuf) (castEnum inLen) outBuf pOutLen pRemBuf pRemLen
outLen <- peek pOutLen
newOutBuf <- reallocBytes outBuf (castEnum outLen)
remBuf <- peek pRemBuf
remLen <- peek pRemLen
remBs <- BS.packCStringLen (castPtr remBuf, castEnum remLen)
outBs <- unsafePackCStringFinalizer newOutBuf (castEnum outLen) (free newOutBuf)
if r == 0
then return $ Right (outBs, remBs)
else return $ Left (outBs, remBs)
b64uDecodeFinal :: BS.ByteString -> Maybe BS.ByteString
b64uDecodeFinal bs = U.unsafePerformIO $ unsafeUseAsCStringLen bs $ \ (inBuf, inLen) -> do
outBuf <- mallocBytes 3
alloca $ \ pOutLen -> do
r <- c_b64u_dec_final (castPtr inBuf) (castEnum inLen) outBuf pOutLen
if r == 0
then do
outLen <- peek pOutLen
newOutBuf <- reallocBytes outBuf (castEnum outLen)
outBs <- unsafePackCStringFinalizer newOutBuf (castEnum outLen) (free newOutBuf)
return $ Just outBs
else free outBuf >> return Nothing
encode :: BS.ByteString -> BS.ByteString
encode bs = first `BS.append` final
where
(first, rest) = b64uEncodePart bs
Just final = b64uEncodeFinal rest
decode :: BS.ByteString -> Either (BS.ByteString, BS.ByteString) BS.ByteString
decode bs = either
Left
(\ (first, rest) ->
maybe
(Left (first, rest))
(\ fin -> Right (first `BS.append` fin))
(b64uDecodeFinal rest))
(b64uDecodePart bs)
|
ec535dde81887201330ff39d4b0318956780f879e33b4dd96dc5afb52b08f0dc | jrh13/hol-light | parser.ml | (* ========================================================================= *)
(* Lexical analyzer, type and preterm parsers. *)
(* *)
, University of Cambridge Computer Laboratory
(* *)
( c ) Copyright , University of Cambridge 1998
( c ) Copyright , 1998 - 2007
( c ) Copyright , , 2017 - 2018
(* ========================================================================= *)
needs "preterm.ml";;
(* ------------------------------------------------------------------------- *)
(* Need to have this now for set enums, since "," isn't a reserved word. *)
(* ------------------------------------------------------------------------- *)
parse_as_infix (",",(14,"right"));;
(* ------------------------------------------------------------------------- *)
(* Basic parser combinators. *)
(* ------------------------------------------------------------------------- *)
exception Noparse;;
let (|||) parser1 parser2 input =
try parser1 input
with Noparse -> parser2 input;;
let (++) parser1 parser2 input =
let result1,rest1 = parser1 input in
let result2,rest2 = parser2 rest1 in
(result1,result2),rest2;;
let rec many prs input =
try let result,next = prs input in
let results,rest = many prs next in
(result::results),rest
with Noparse -> [],input;;
let (>>) prs treatment input =
let result,rest = prs input in
treatment(result),rest;;
let fix err prs input =
try prs input
with Noparse -> failwith (err ^ " expected");;
let rec listof prs sep err =
prs ++ many (sep ++ fix err prs >> snd) >> (fun (h,t) -> h::t);;
let nothing input = [],input;;
let elistof prs sep err =
listof prs sep err ||| nothing;;
let leftbin prs sep cons err =
prs ++ many (sep ++ fix err prs) >>
(fun (x,opxs) -> let ops,xs = unzip opxs in
itlist2 (fun op y x -> cons op x y) (rev ops) (rev xs) x);;
let rightbin prs sep cons err =
prs ++ many (sep ++ fix err prs) >>
(fun (x,opxs) -> if opxs = [] then x else
let ops,xs = unzip opxs in
itlist2 cons ops (x::butlast xs) (last xs));;
let possibly prs input =
try let x,rest = prs input in [x],rest
with Noparse -> [],input;;
let some p =
function
[] -> raise Noparse
| (h::t) -> if p h then (h,t) else raise Noparse;;
let a tok = some (fun item -> item = tok);;
let rec atleast n prs i =
(if n <= 0 then many prs
else prs ++ atleast (n - 1) prs >> (fun (h,t) -> h::t)) i;;
let finished input =
if input = [] then 0,input else failwith "Unparsed input";;
(* ------------------------------------------------------------------------- *)
(* The basic lexical classes: identifiers, strings and reserved words. *)
(* ------------------------------------------------------------------------- *)
type lexcode = Ident of string
| Resword of string;;
(* ------------------------------------------------------------------------- *)
(* Lexical analyzer. Apart from some special bracket symbols, each *)
(* identifier is made up of the longest string of alphanumerics or *)
(* the longest string of symbolics. *)
(* ------------------------------------------------------------------------- *)
reserve_words ["//"];;
let comment_token = ref (Resword "//");;
let lex =
let collect (h,t) = end_itlist (^) (h::t) in
let reserve =
function
(Ident n as tok) ->
if is_reserved_word n then Resword(n) else tok
| t -> t in
let stringof p = atleast 1 p >> end_itlist (^) in
let simple_ident = stringof(some isalnum) ||| stringof(some issymb) in
let undertail = stringof (a "_") ++ possibly simple_ident >> collect in
let ident = (undertail ||| simple_ident) ++ many undertail >> collect in
let septok = stringof(some issep) in
let escapecode i =
match i with
"\\"::rst -> "\\",rst
| "\""::rst -> "\"",rst
| "\'"::rst -> "\'",rst
| "n"::rst -> "\n",rst
| "r"::rst -> "\r",rst
| "t"::rst -> "\t",rst
| "b"::rst -> "\b",rst
| " "::rst -> " ",rst
| "x"::h::l::rst ->
String.make 1 (Char.chr(int_of_string("0x"^h^l))),rst
| a::b::c::rst when forall isnum [a;b;c] ->
String.make 1 (Char.chr(int_of_string(a^b^c))),rst
| _ -> failwith "lex:unrecognized OCaml-style escape in string" in
let stringchar =
some (fun i -> i <> "\\" && i <> "\"")
||| (a "\\" ++ escapecode >> snd) in
let string = a "\"" ++ many stringchar ++ a "\"" >>
(fun ((_,s),_) -> "\""^implode s^"\"") in
let rawtoken = (string ||| some isbra ||| septok ||| ident) >>
(fun x -> Ident x) in
let simptoken = many (some isspace) ++ rawtoken >> (reserve o snd) in
let rec tokens i =
try let (t,rst) = simptoken i in
if t = !comment_token then
(many (fun i -> if i <> [] && hd i <> "\n" then 1,tl i
else raise Noparse) ++ tokens >> snd) rst
else
let toks,rst1 = tokens rst in t::toks,rst1
with Noparse -> [],i in
fst o (tokens ++ many (some isspace) ++ finished >> (fst o fst));;
(* ------------------------------------------------------------------------- *)
Parser for pretypes . Concrete syntax :
(* *)
TYPE : : SUMTYPE - > TYPE
| SUMTYPE
(* *)
SUMTYPE : : PRODTYPE + SUMTYPE
(* | PRODTYPE *)
(* *)
PRODTYPE : : POWTYPE #
| POWTYPE
(* *)
POWTYPE : : APPTYPE ^ POWTYPE
(* | APPTYPE *)
(* *)
APPTYPE : : ATOMICTYPES type - constructor [ Provided arity matches ]
| ATOMICTYPES [ Provided only 1 ATOMICTYPE ]
(* *)
ATOMICTYPES : : type - constructor [ Provided arity zero ]
(* | type-variable *)
(* | ( TYPE ) *)
(* | ( TYPE LIST ) *)
(* *)
TYPELIST : : TYPE , TYPELIST
(* | TYPE *)
(* *)
Two features make this different from previous HOL type syntax :
(* *)
(* o Any identifier not in use as a type constant will be parsed as a *)
(* type variable; a ' is not needed and a * is not allowed. *)
(* *)
(* o Antiquotation is not supported. *)
(* ------------------------------------------------------------------------- *)
let parse_pretype =
let mk_prefinty:num->pretype =
let rec prefinty n =
if n =/ num_1 then Ptycon("1",[]) else
let c = if Num.mod_num n num_2 =/ num_0 then "tybit0" else "tybit1" in
Ptycon(c,[prefinty(Num.quo_num n num_2)]) in
fun n ->
if not(is_integer_num n) || n </ num_1 then failwith "mk_prefinty" else
prefinty n in
let btyop n n' x y = Ptycon(n,[x;y])
and mk_apptype =
function
([s],[]) -> s
| (tys,[c]) -> Ptycon(c,tys)
| _ -> failwith "Bad type construction"
and type_atom input =
match input with
(Ident s)::rest ->
(try pretype_of_type(assoc s (type_abbrevs())) with Failure _ ->
try mk_prefinty (num_of_string s) with Failure _ ->
if try get_type_arity s = 0 with Failure _ -> false
then Ptycon(s,[]) else Utv(s)),rest
| _ -> raise Noparse
and type_constructor input =
match input with
(Ident s)::rest -> if try get_type_arity s > 0 with Failure _ -> false
then s,rest else raise Noparse
| _ -> raise Noparse in
let rec pretype i =
rightbin sumtype (a (Resword "->")) (btyop "fun") "proper use of type operator (->)" i
and sumtype i = rightbin prodtype (a (Ident "+")) (btyop "sum") "proper use of type operator (+)" i
and prodtype i = rightbin carttype (a (Ident "#")) (btyop "prod") "proper use of type operator (#)" i
and carttype i = leftbin apptype (a (Ident "^")) (btyop "cart") "proper use of type operator (^)" i
and apptype i = (atomictypes ++ (type_constructor >> (fun x -> [x])
||| nothing) >> mk_apptype) i
and atomictypes i =
(((a (Resword "(")) ++ typelist ++ a (Resword ")") >> (snd o fst))
||| (type_atom >> (fun x -> [x]))) i
and typelist i = listof pretype (a (Ident ",")) "comma separated list for type constructor" i in
pretype;;
(* ------------------------------------------------------------------------- *)
(* Hook to allow installation of user parsers. *)
(* ------------------------------------------------------------------------- *)
let install_parser,delete_parser,installed_parsers,try_user_parser =
let rec try_parsers ps i =
if ps = [] then raise Noparse else
try snd(hd ps) i with Noparse -> try_parsers (tl ps) i in
let parser_list =
ref([]:(string*(lexcode list -> preterm * lexcode list))list) in
(fun dat -> parser_list := dat::(!parser_list)),
(fun key -> try parser_list := snd (remove (fun (key',_) -> key = key')
(!parser_list))
with Failure _ -> ()),
(fun () -> !parser_list),
(fun i -> try_parsers (!parser_list) i);;
(* ------------------------------------------------------------------------- *)
(* Initial preterm parsing. This uses binder and precedence/associativity/ *)
(* prefix status to guide parsing and preterm construction, but treats all *)
(* identifiers as variables. *)
(* *)
(* PRETERM :: APPL_PRETERM binop APPL_PRETERM *)
(* | APPL_PRETERM *)
(* *)
(* APPL_PRETERM :: APPL_PRETERM : type *)
(* | APPL_PRETERM BINDER_PRETERM *)
(* | BINDER_PRETERM *)
(* *)
(* BINDER_PRETERM :: binder VARSTRUCT_PRETERMS . PRETERM *)
(* | let PRETERM and ... and PRETERM in PRETERM *)
(* | ATOMIC_PRETERM *)
(* *)
(* VARSTRUCT_PRETERMS :: TYPED_PRETERM VARSTRUCT_PRETERMS *)
(* | TYPED_PRETERM *)
(* *)
(* TYPED_PRETERM :: TYPED_PRETERM : type *)
(* | ATOMIC_PRETERM *)
(* *)
ATOMIC_PRETERM : : ( PRETERM )
(* | if PRETERM then PRETERM else PRETERM *)
(* | [ PRETERM; .. ; PRETERM ] *)
(* | { PRETERM, .. , PRETERM } *)
(* | { PRETERM | PRETERM } *)
(* | identifier *)
(* *)
Note that arbitrary preterms are allowed as varstructs . This allows
(* more general forms of matching and considerably regularizes the syntax. *)
(* ------------------------------------------------------------------------- *)
let parse_preterm =
let rec pairwise r l =
match l with
[] -> true
| h::t -> forall (r h) t && pairwise r t in
let rec pfrees ptm =
match ptm with
Varp(v,pty) ->
if v = "" && pty = dpty then []
else if can get_const_type v || can num_of_string v
|| exists (fun (w,_) -> v = w) (!the_interface) then []
else [ptm]
| Constp(_,_) -> []
| Combp(p1,p2) -> union (pfrees p1) (pfrees p2)
| Absp(p1,p2) -> subtract (pfrees p2) (pfrees p1)
| Typing(p,_) -> pfrees p in
let pdest_eq (Combp(Combp(Varp(("="|"<=>"),_),l),r)) = l,r in
let pmk_let (letbindings,body) =
let vars,tms = unzip (map pdest_eq letbindings) in
let _ = warn(not
(pairwise (fun s t -> intersect(pfrees s) (pfrees t) = []) vars))
"duplicate names on left of let-binding: latest is used" in
let lend = Combp(Varp("LET_END",dpty),body) in
let abs = itlist (fun v t -> Absp(v,t)) vars lend in
let labs = Combp(Varp("LET",dpty),abs) in
rev_itlist (fun x f -> Combp(f,x)) tms labs in
let pmk_vbinder(n,v,bod) =
if n = "\\" then Absp(v,bod)
else Combp(Varp(n,dpty),Absp(v,bod)) in
let pmk_binder(n,vs,bod) =
itlist (fun v b -> pmk_vbinder(n,v,b)) vs bod in
let pmk_set_enum ptms =
itlist (fun x t -> Combp(Combp(Varp("INSERT",dpty),x),t)) ptms
(Varp("EMPTY",dpty)) in
let pgenvar =
let gcounter = ref 0 in
fun () -> let count = !gcounter in
(gcounter := count + 1;
Varp("GEN%PVAR%"^(string_of_int count),dpty)) in
let pmk_exists(v,ptm) = Combp(Varp("?",dpty),Absp(v,ptm)) in
let pmk_list els =
itlist (fun x y -> Combp(Combp(Varp("CONS",dpty),x),y))
els (Varp("NIL",dpty)) in
let pmk_bool =
let tt = Varp("T",dpty) and ff = Varp("F",dpty) in
fun b -> if b then tt else ff in
let pmk_char c =
let lis = map (fun i -> pmk_bool((c / (1 lsl i)) mod 2 = 1)) (0--7) in
itlist (fun x y -> Combp(y,x)) lis (Varp("ASCII",dpty)) in
let pmk_string s =
let ns = map (fun i -> Char.code(String.get s i))
(0--(String.length s - 1)) in
pmk_list(map pmk_char ns) in
let pmk_setcompr (fabs,bvs,babs) =
let v = pgenvar() in
let bod = itlist (curry pmk_exists) bvs
(Combp(Combp(Combp(Varp("SETSPEC",dpty),v),babs),fabs)) in
Combp(Varp("GSPEC",dpty),Absp(v,bod)) in
let pmk_setabs (fabs,babs) =
let evs =
let fvs = pfrees fabs
and bvs = pfrees babs in
if length fvs <= 1 || bvs = [] then fvs
else intersect fvs bvs in
pmk_setcompr (fabs,evs,babs) in
let rec mk_precedence infxs prs inp =
match infxs with
(s,(p,at))::_ ->
let topins,rest = partition (fun (s',pat') -> pat' = (p,at)) infxs in
(if at = "right" then rightbin else leftbin)
(mk_precedence rest prs)
(end_itlist (|||) (map (fun (s,_) -> a (Ident s)) topins))
(fun (Ident op) x y -> Combp(Combp(Varp(op,dpty),x),y))
("term after binary operator")
inp
| _ -> prs inp in
let pmk_geq s t = Combp(Combp(Varp("GEQ",dpty),s),t) in
let pmk_pattern ((pat,guards),res) =
let x = pgenvar() and y = pgenvar() in
let vs = pfrees pat
and bod =
if guards = [] then
Combp(Combp(Varp("_UNGUARDED_PATTERN",dpty),pmk_geq pat x),
pmk_geq res y)
else
Combp(Combp(Combp(Varp("_GUARDED_PATTERN",dpty),pmk_geq pat x),
hd guards),
pmk_geq res y) in
Absp(x,Absp(y,itlist (curry pmk_exists) vs bod)) in
let pretype = parse_pretype
and string inp =
match inp with
Ident s::rst when String.length s >= 2 &&
String.sub s 0 1 = "\"" &&
String.sub s (String.length s - 1) 1 = "\""
-> String.sub s 1 (String.length s - 2),rst
| _ -> raise Noparse
and singleton1 x = [x]
and lmk_ite (((((_,b),_),l),_),r) =
Combp(Combp(Combp(Varp("COND",dpty),b),l),r)
and lmk_typed =
function (p,[]) -> p | (p,[ty]) -> Typing(p,ty) | _ -> fail()
and lmk_let (((_,bnds),_),ptm) = pmk_let (bnds,ptm)
and lmk_binder ((((s,h),t),_),p) = pmk_binder(s,h::t,p)
and lmk_setenum(l,_) = pmk_set_enum l
and lmk_setabs(((l,_),r),_) = pmk_setabs(l,r)
and lmk_setcompr(((((f,_),vs),_),b),_) =
pmk_setcompr(f,pfrees vs,b)
and lmk_decimal ((_,l0),ropt) =
let l,r = if ropt = [] then l0,"1" else
let r0 = hd ropt in
let n_l = num_of_string l0
and n_r = num_of_string r0 in
let n_d = power_num (Int 10) (Int (String.length r0)) in
let n_n = n_l */ n_d +/ n_r in
string_of_num n_n,string_of_num n_d in
Combp(Combp(Varp("DECIMAL",dpty),Varp(l,dpty)),Varp(r,dpty))
and lmk_univ((_,pty),_) =
Typing(Varp("UNIV",dpty),Ptycon("fun",[pty;Ptycon("bool",[])]))
and any_identifier =
function
((Ident s):: rest) -> s,rest
| _ -> raise Noparse
and identifier =
function
((Ident s):: rest) ->
if can get_infix_status s || is_prefix s || parses_as_binder s
then raise Noparse else s,rest
| _ -> raise Noparse
and binder =
function
((Ident s):: rest) ->
if parses_as_binder s then s,rest else raise Noparse
| _ -> raise Noparse
and pre_fix =
function
((Ident s):: rest) ->
if is_prefix s then s,rest else raise Noparse
| _ -> raise Noparse in
let rec preterm i =
mk_precedence (infixes()) typed_appl_preterm i
and nocommapreterm i =
let infs = filter (fun (s,_) -> s <> ",") (infixes()) in
mk_precedence infs typed_appl_preterm i
and typed_appl_preterm i =
(appl_preterm ++
possibly (a (Resword ":") ++ pretype >> snd)
>> lmk_typed) i
and appl_preterm i =
(pre_fix ++ appl_preterm
>> (fun (x,y) -> Combp(Varp(x,dpty),y))
||| (binder_preterm ++ many binder_preterm >>
(fun (h,t) -> itlist (fun x y -> Combp(y,x)) (rev t) h))) i
and binder_preterm i =
((a (Resword "let") ++
leftbin (preterm >> singleton1) (a (Resword "and")) (K (@)) "binding" ++
a (Resword "in") ++
preterm
>> lmk_let)
||| (binder ++
typed_apreterm ++
many typed_apreterm ++
a (Resword ".") ++
preterm
>> lmk_binder)
||| atomic_preterm) i
and typed_apreterm i =
(atomic_preterm ++
possibly (a (Resword ":") ++ pretype >> snd)
>> lmk_typed) i
and atomic_preterm i =
(try_user_parser
||| ((a (Resword "(") ++ a (Resword ":")) ++ pretype ++ a (Resword ")")
>> lmk_univ)
||| ((a (Resword "(") ++ a (Resword ":")) ++ pretype
>> (fun _ -> failwith "closing right parenthesis on universe expected"))
||| ((a (Resword "(") ++ a (Resword ":"))
>> (fun _ -> failwith "type in universe construction expected"))
||| (string >> pmk_string)
||| (a (Resword "(") ++
(any_identifier >> (fun s -> Varp(s,dpty))) ++
a (Resword ")")
>> (snd o fst))
||| (a (Resword "(") ++
preterm ++
a (Resword ")")
>> (snd o fst))
||| (a (Resword "if") ++
preterm ++
a (Resword "then") ++
preterm ++
a (Resword "else") ++
preterm
>> lmk_ite)
||| ((a (Resword "if") ) ++ preterm ++ a (Resword "then") ++ preterm ++ a (Resword "else")
>> (fun _ -> failwith "malformed else clause"))
||| ((a (Resword "if") ) ++ preterm ++ a (Resword "then") ++ preterm
>> (fun _ -> failwith "missing else following then clause"))
||| ((a (Resword "if") ) ++ preterm ++ a (Resword "then")
>> (fun _ -> failwith "malformed then clause in if-then-else statement"))
||| ((a (Resword "if") ) ++ preterm
>> (fun _ -> failwith "missing 'then' reserved word in if-then-else statement"))
||| ((a (Resword "if") )
>> (fun _ -> failwith "malformed if-then-else"))
||| (a (Resword "[") ++
elistof preterm (a (Resword ";")) "semicolon separated list of terms" ++
a (Resword "]")
>> (pmk_list o snd o fst))
||| (a (Resword "[") ++
elistof preterm (a (Resword ";")) "semicolon separated list of terms"
>> (fun _ -> failwith "closing square bracket of list expected"))
||| (a (Resword "{") ++
(elistof nocommapreterm (a (Ident ",")) "comma separated list of terms" ++ a (Resword "}")
>> lmk_setenum
||| (preterm ++ a (Resword "|") ++ preterm ++ a (Resword "}")
>> lmk_setabs)
||| (preterm ++ a (Resword "|") ++ preterm ++
a (Resword "|") ++ preterm ++ a (Resword "}")
>> lmk_setcompr))
>> snd)
||| (a (Resword "{") >> (fun _ -> failwith "malformed set {}"))
||| (a (Resword "match") ++ preterm ++ a (Resword "with") ++ clauses
>> (fun (((_,e),_),c) -> Combp(Combp(Varp("_MATCH",dpty),e),c)))
||| (a (Resword "match") >> (fun _ -> failwith "malformed match-with statement"))
||| (a (Resword "function") ++ clauses
>> (fun (_,c) -> Combp(Varp("_FUNCTION",dpty),c)))
||| (a (Resword "function") >> (fun _ -> failwith "malformed function and pattern clauses"))
||| (a (Ident "#") ++ identifier ++
possibly (a (Resword ".") ++ identifier >> snd)
>> lmk_decimal)
||| (a (Ident "#") >> (fun _ -> failwith "malformed numerical # identifier"))
||| (identifier >> (fun s -> Varp(s,dpty)))) i
and pattern i =
(preterm ++ possibly (a (Resword "when") ++ preterm >> snd)) i
and clause i =
((pattern ++ (a (Resword "->") ++ preterm >> snd)) >> pmk_pattern) i
and clauses i =
((possibly (a (Resword "|")) ++
listof clause (a (Resword "|")) "pattern-match clause" >> snd)
>> end_itlist (fun s t -> Combp(Combp(Varp("_SEQPATTERN",dpty),s),t))) i in
(fun inp ->
match inp with
[Ident s] when
not(String.length s >= 2 &&
String.sub s 0 1 = "\"" &&
String.sub s (String.length s - 1) 1 = "\"")
-> Varp(s,dpty),[]
| _ -> preterm inp);;
(* ------------------------------------------------------------------------- *)
(* Type and term parsers. *)
(* ------------------------------------------------------------------------- *)
let parse_type s =
let pty,l = (parse_pretype o lex o explode) s in
if l = [] then type_of_pretype pty
else failwith "Unparsed input following type";;
let parse_term s =
let ptm,l = (parse_preterm o lex o explode) s in
if l = [] then
(term_of_preterm o (retypecheck [])) ptm
else failwith "Unparsed input following term";;
| null | https://raw.githubusercontent.com/jrh13/hol-light/74560a4095e4ed5d50e784c5b82df6d929fe214a/parser.ml | ocaml | =========================================================================
Lexical analyzer, type and preterm parsers.
=========================================================================
-------------------------------------------------------------------------
Need to have this now for set enums, since "," isn't a reserved word.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Basic parser combinators.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
The basic lexical classes: identifiers, strings and reserved words.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Lexical analyzer. Apart from some special bracket symbols, each
identifier is made up of the longest string of alphanumerics or
the longest string of symbolics.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
| PRODTYPE
| APPTYPE
| type-variable
| ( TYPE )
| ( TYPE LIST )
| TYPE
o Any identifier not in use as a type constant will be parsed as a
type variable; a ' is not needed and a * is not allowed.
o Antiquotation is not supported.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Hook to allow installation of user parsers.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Initial preterm parsing. This uses binder and precedence/associativity/
prefix status to guide parsing and preterm construction, but treats all
identifiers as variables.
PRETERM :: APPL_PRETERM binop APPL_PRETERM
| APPL_PRETERM
APPL_PRETERM :: APPL_PRETERM : type
| APPL_PRETERM BINDER_PRETERM
| BINDER_PRETERM
BINDER_PRETERM :: binder VARSTRUCT_PRETERMS . PRETERM
| let PRETERM and ... and PRETERM in PRETERM
| ATOMIC_PRETERM
VARSTRUCT_PRETERMS :: TYPED_PRETERM VARSTRUCT_PRETERMS
| TYPED_PRETERM
TYPED_PRETERM :: TYPED_PRETERM : type
| ATOMIC_PRETERM
| if PRETERM then PRETERM else PRETERM
| [ PRETERM; .. ; PRETERM ]
| { PRETERM, .. , PRETERM }
| { PRETERM | PRETERM }
| identifier
more general forms of matching and considerably regularizes the syntax.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Type and term parsers.
------------------------------------------------------------------------- | , University of Cambridge Computer Laboratory
( c ) Copyright , University of Cambridge 1998
( c ) Copyright , 1998 - 2007
( c ) Copyright , , 2017 - 2018
needs "preterm.ml";;
parse_as_infix (",",(14,"right"));;
exception Noparse;;
let (|||) parser1 parser2 input =
try parser1 input
with Noparse -> parser2 input;;
let (++) parser1 parser2 input =
let result1,rest1 = parser1 input in
let result2,rest2 = parser2 rest1 in
(result1,result2),rest2;;
let rec many prs input =
try let result,next = prs input in
let results,rest = many prs next in
(result::results),rest
with Noparse -> [],input;;
let (>>) prs treatment input =
let result,rest = prs input in
treatment(result),rest;;
let fix err prs input =
try prs input
with Noparse -> failwith (err ^ " expected");;
let rec listof prs sep err =
prs ++ many (sep ++ fix err prs >> snd) >> (fun (h,t) -> h::t);;
let nothing input = [],input;;
let elistof prs sep err =
listof prs sep err ||| nothing;;
let leftbin prs sep cons err =
prs ++ many (sep ++ fix err prs) >>
(fun (x,opxs) -> let ops,xs = unzip opxs in
itlist2 (fun op y x -> cons op x y) (rev ops) (rev xs) x);;
let rightbin prs sep cons err =
prs ++ many (sep ++ fix err prs) >>
(fun (x,opxs) -> if opxs = [] then x else
let ops,xs = unzip opxs in
itlist2 cons ops (x::butlast xs) (last xs));;
let possibly prs input =
try let x,rest = prs input in [x],rest
with Noparse -> [],input;;
let some p =
function
[] -> raise Noparse
| (h::t) -> if p h then (h,t) else raise Noparse;;
let a tok = some (fun item -> item = tok);;
let rec atleast n prs i =
(if n <= 0 then many prs
else prs ++ atleast (n - 1) prs >> (fun (h,t) -> h::t)) i;;
let finished input =
if input = [] then 0,input else failwith "Unparsed input";;
type lexcode = Ident of string
| Resword of string;;
reserve_words ["//"];;
let comment_token = ref (Resword "//");;
let lex =
let collect (h,t) = end_itlist (^) (h::t) in
let reserve =
function
(Ident n as tok) ->
if is_reserved_word n then Resword(n) else tok
| t -> t in
let stringof p = atleast 1 p >> end_itlist (^) in
let simple_ident = stringof(some isalnum) ||| stringof(some issymb) in
let undertail = stringof (a "_") ++ possibly simple_ident >> collect in
let ident = (undertail ||| simple_ident) ++ many undertail >> collect in
let septok = stringof(some issep) in
let escapecode i =
match i with
"\\"::rst -> "\\",rst
| "\""::rst -> "\"",rst
| "\'"::rst -> "\'",rst
| "n"::rst -> "\n",rst
| "r"::rst -> "\r",rst
| "t"::rst -> "\t",rst
| "b"::rst -> "\b",rst
| " "::rst -> " ",rst
| "x"::h::l::rst ->
String.make 1 (Char.chr(int_of_string("0x"^h^l))),rst
| a::b::c::rst when forall isnum [a;b;c] ->
String.make 1 (Char.chr(int_of_string(a^b^c))),rst
| _ -> failwith "lex:unrecognized OCaml-style escape in string" in
let stringchar =
some (fun i -> i <> "\\" && i <> "\"")
||| (a "\\" ++ escapecode >> snd) in
let string = a "\"" ++ many stringchar ++ a "\"" >>
(fun ((_,s),_) -> "\""^implode s^"\"") in
let rawtoken = (string ||| some isbra ||| septok ||| ident) >>
(fun x -> Ident x) in
let simptoken = many (some isspace) ++ rawtoken >> (reserve o snd) in
let rec tokens i =
try let (t,rst) = simptoken i in
if t = !comment_token then
(many (fun i -> if i <> [] && hd i <> "\n" then 1,tl i
else raise Noparse) ++ tokens >> snd) rst
else
let toks,rst1 = tokens rst in t::toks,rst1
with Noparse -> [],i in
fst o (tokens ++ many (some isspace) ++ finished >> (fst o fst));;
Parser for pretypes . Concrete syntax :
TYPE : : SUMTYPE - > TYPE
| SUMTYPE
SUMTYPE : : PRODTYPE + SUMTYPE
PRODTYPE : : POWTYPE #
| POWTYPE
POWTYPE : : APPTYPE ^ POWTYPE
APPTYPE : : ATOMICTYPES type - constructor [ Provided arity matches ]
| ATOMICTYPES [ Provided only 1 ATOMICTYPE ]
ATOMICTYPES : : type - constructor [ Provided arity zero ]
TYPELIST : : TYPE , TYPELIST
Two features make this different from previous HOL type syntax :
let parse_pretype =
let mk_prefinty:num->pretype =
let rec prefinty n =
if n =/ num_1 then Ptycon("1",[]) else
let c = if Num.mod_num n num_2 =/ num_0 then "tybit0" else "tybit1" in
Ptycon(c,[prefinty(Num.quo_num n num_2)]) in
fun n ->
if not(is_integer_num n) || n </ num_1 then failwith "mk_prefinty" else
prefinty n in
let btyop n n' x y = Ptycon(n,[x;y])
and mk_apptype =
function
([s],[]) -> s
| (tys,[c]) -> Ptycon(c,tys)
| _ -> failwith "Bad type construction"
and type_atom input =
match input with
(Ident s)::rest ->
(try pretype_of_type(assoc s (type_abbrevs())) with Failure _ ->
try mk_prefinty (num_of_string s) with Failure _ ->
if try get_type_arity s = 0 with Failure _ -> false
then Ptycon(s,[]) else Utv(s)),rest
| _ -> raise Noparse
and type_constructor input =
match input with
(Ident s)::rest -> if try get_type_arity s > 0 with Failure _ -> false
then s,rest else raise Noparse
| _ -> raise Noparse in
let rec pretype i =
rightbin sumtype (a (Resword "->")) (btyop "fun") "proper use of type operator (->)" i
and sumtype i = rightbin prodtype (a (Ident "+")) (btyop "sum") "proper use of type operator (+)" i
and prodtype i = rightbin carttype (a (Ident "#")) (btyop "prod") "proper use of type operator (#)" i
and carttype i = leftbin apptype (a (Ident "^")) (btyop "cart") "proper use of type operator (^)" i
and apptype i = (atomictypes ++ (type_constructor >> (fun x -> [x])
||| nothing) >> mk_apptype) i
and atomictypes i =
(((a (Resword "(")) ++ typelist ++ a (Resword ")") >> (snd o fst))
||| (type_atom >> (fun x -> [x]))) i
and typelist i = listof pretype (a (Ident ",")) "comma separated list for type constructor" i in
pretype;;
let install_parser,delete_parser,installed_parsers,try_user_parser =
let rec try_parsers ps i =
if ps = [] then raise Noparse else
try snd(hd ps) i with Noparse -> try_parsers (tl ps) i in
let parser_list =
ref([]:(string*(lexcode list -> preterm * lexcode list))list) in
(fun dat -> parser_list := dat::(!parser_list)),
(fun key -> try parser_list := snd (remove (fun (key',_) -> key = key')
(!parser_list))
with Failure _ -> ()),
(fun () -> !parser_list),
(fun i -> try_parsers (!parser_list) i);;
ATOMIC_PRETERM : : ( PRETERM )
Note that arbitrary preterms are allowed as varstructs . This allows
let parse_preterm =
let rec pairwise r l =
match l with
[] -> true
| h::t -> forall (r h) t && pairwise r t in
let rec pfrees ptm =
match ptm with
Varp(v,pty) ->
if v = "" && pty = dpty then []
else if can get_const_type v || can num_of_string v
|| exists (fun (w,_) -> v = w) (!the_interface) then []
else [ptm]
| Constp(_,_) -> []
| Combp(p1,p2) -> union (pfrees p1) (pfrees p2)
| Absp(p1,p2) -> subtract (pfrees p2) (pfrees p1)
| Typing(p,_) -> pfrees p in
let pdest_eq (Combp(Combp(Varp(("="|"<=>"),_),l),r)) = l,r in
let pmk_let (letbindings,body) =
let vars,tms = unzip (map pdest_eq letbindings) in
let _ = warn(not
(pairwise (fun s t -> intersect(pfrees s) (pfrees t) = []) vars))
"duplicate names on left of let-binding: latest is used" in
let lend = Combp(Varp("LET_END",dpty),body) in
let abs = itlist (fun v t -> Absp(v,t)) vars lend in
let labs = Combp(Varp("LET",dpty),abs) in
rev_itlist (fun x f -> Combp(f,x)) tms labs in
let pmk_vbinder(n,v,bod) =
if n = "\\" then Absp(v,bod)
else Combp(Varp(n,dpty),Absp(v,bod)) in
let pmk_binder(n,vs,bod) =
itlist (fun v b -> pmk_vbinder(n,v,b)) vs bod in
let pmk_set_enum ptms =
itlist (fun x t -> Combp(Combp(Varp("INSERT",dpty),x),t)) ptms
(Varp("EMPTY",dpty)) in
let pgenvar =
let gcounter = ref 0 in
fun () -> let count = !gcounter in
(gcounter := count + 1;
Varp("GEN%PVAR%"^(string_of_int count),dpty)) in
let pmk_exists(v,ptm) = Combp(Varp("?",dpty),Absp(v,ptm)) in
let pmk_list els =
itlist (fun x y -> Combp(Combp(Varp("CONS",dpty),x),y))
els (Varp("NIL",dpty)) in
let pmk_bool =
let tt = Varp("T",dpty) and ff = Varp("F",dpty) in
fun b -> if b then tt else ff in
let pmk_char c =
let lis = map (fun i -> pmk_bool((c / (1 lsl i)) mod 2 = 1)) (0--7) in
itlist (fun x y -> Combp(y,x)) lis (Varp("ASCII",dpty)) in
let pmk_string s =
let ns = map (fun i -> Char.code(String.get s i))
(0--(String.length s - 1)) in
pmk_list(map pmk_char ns) in
let pmk_setcompr (fabs,bvs,babs) =
let v = pgenvar() in
let bod = itlist (curry pmk_exists) bvs
(Combp(Combp(Combp(Varp("SETSPEC",dpty),v),babs),fabs)) in
Combp(Varp("GSPEC",dpty),Absp(v,bod)) in
let pmk_setabs (fabs,babs) =
let evs =
let fvs = pfrees fabs
and bvs = pfrees babs in
if length fvs <= 1 || bvs = [] then fvs
else intersect fvs bvs in
pmk_setcompr (fabs,evs,babs) in
let rec mk_precedence infxs prs inp =
match infxs with
(s,(p,at))::_ ->
let topins,rest = partition (fun (s',pat') -> pat' = (p,at)) infxs in
(if at = "right" then rightbin else leftbin)
(mk_precedence rest prs)
(end_itlist (|||) (map (fun (s,_) -> a (Ident s)) topins))
(fun (Ident op) x y -> Combp(Combp(Varp(op,dpty),x),y))
("term after binary operator")
inp
| _ -> prs inp in
let pmk_geq s t = Combp(Combp(Varp("GEQ",dpty),s),t) in
let pmk_pattern ((pat,guards),res) =
let x = pgenvar() and y = pgenvar() in
let vs = pfrees pat
and bod =
if guards = [] then
Combp(Combp(Varp("_UNGUARDED_PATTERN",dpty),pmk_geq pat x),
pmk_geq res y)
else
Combp(Combp(Combp(Varp("_GUARDED_PATTERN",dpty),pmk_geq pat x),
hd guards),
pmk_geq res y) in
Absp(x,Absp(y,itlist (curry pmk_exists) vs bod)) in
let pretype = parse_pretype
and string inp =
match inp with
Ident s::rst when String.length s >= 2 &&
String.sub s 0 1 = "\"" &&
String.sub s (String.length s - 1) 1 = "\""
-> String.sub s 1 (String.length s - 2),rst
| _ -> raise Noparse
and singleton1 x = [x]
and lmk_ite (((((_,b),_),l),_),r) =
Combp(Combp(Combp(Varp("COND",dpty),b),l),r)
and lmk_typed =
function (p,[]) -> p | (p,[ty]) -> Typing(p,ty) | _ -> fail()
and lmk_let (((_,bnds),_),ptm) = pmk_let (bnds,ptm)
and lmk_binder ((((s,h),t),_),p) = pmk_binder(s,h::t,p)
and lmk_setenum(l,_) = pmk_set_enum l
and lmk_setabs(((l,_),r),_) = pmk_setabs(l,r)
and lmk_setcompr(((((f,_),vs),_),b),_) =
pmk_setcompr(f,pfrees vs,b)
and lmk_decimal ((_,l0),ropt) =
let l,r = if ropt = [] then l0,"1" else
let r0 = hd ropt in
let n_l = num_of_string l0
and n_r = num_of_string r0 in
let n_d = power_num (Int 10) (Int (String.length r0)) in
let n_n = n_l */ n_d +/ n_r in
string_of_num n_n,string_of_num n_d in
Combp(Combp(Varp("DECIMAL",dpty),Varp(l,dpty)),Varp(r,dpty))
and lmk_univ((_,pty),_) =
Typing(Varp("UNIV",dpty),Ptycon("fun",[pty;Ptycon("bool",[])]))
and any_identifier =
function
((Ident s):: rest) -> s,rest
| _ -> raise Noparse
and identifier =
function
((Ident s):: rest) ->
if can get_infix_status s || is_prefix s || parses_as_binder s
then raise Noparse else s,rest
| _ -> raise Noparse
and binder =
function
((Ident s):: rest) ->
if parses_as_binder s then s,rest else raise Noparse
| _ -> raise Noparse
and pre_fix =
function
((Ident s):: rest) ->
if is_prefix s then s,rest else raise Noparse
| _ -> raise Noparse in
let rec preterm i =
mk_precedence (infixes()) typed_appl_preterm i
and nocommapreterm i =
let infs = filter (fun (s,_) -> s <> ",") (infixes()) in
mk_precedence infs typed_appl_preterm i
and typed_appl_preterm i =
(appl_preterm ++
possibly (a (Resword ":") ++ pretype >> snd)
>> lmk_typed) i
and appl_preterm i =
(pre_fix ++ appl_preterm
>> (fun (x,y) -> Combp(Varp(x,dpty),y))
||| (binder_preterm ++ many binder_preterm >>
(fun (h,t) -> itlist (fun x y -> Combp(y,x)) (rev t) h))) i
and binder_preterm i =
((a (Resword "let") ++
leftbin (preterm >> singleton1) (a (Resword "and")) (K (@)) "binding" ++
a (Resword "in") ++
preterm
>> lmk_let)
||| (binder ++
typed_apreterm ++
many typed_apreterm ++
a (Resword ".") ++
preterm
>> lmk_binder)
||| atomic_preterm) i
and typed_apreterm i =
(atomic_preterm ++
possibly (a (Resword ":") ++ pretype >> snd)
>> lmk_typed) i
and atomic_preterm i =
(try_user_parser
||| ((a (Resword "(") ++ a (Resword ":")) ++ pretype ++ a (Resword ")")
>> lmk_univ)
||| ((a (Resword "(") ++ a (Resword ":")) ++ pretype
>> (fun _ -> failwith "closing right parenthesis on universe expected"))
||| ((a (Resword "(") ++ a (Resword ":"))
>> (fun _ -> failwith "type in universe construction expected"))
||| (string >> pmk_string)
||| (a (Resword "(") ++
(any_identifier >> (fun s -> Varp(s,dpty))) ++
a (Resword ")")
>> (snd o fst))
||| (a (Resword "(") ++
preterm ++
a (Resword ")")
>> (snd o fst))
||| (a (Resword "if") ++
preterm ++
a (Resword "then") ++
preterm ++
a (Resword "else") ++
preterm
>> lmk_ite)
||| ((a (Resword "if") ) ++ preterm ++ a (Resword "then") ++ preterm ++ a (Resword "else")
>> (fun _ -> failwith "malformed else clause"))
||| ((a (Resword "if") ) ++ preterm ++ a (Resword "then") ++ preterm
>> (fun _ -> failwith "missing else following then clause"))
||| ((a (Resword "if") ) ++ preterm ++ a (Resword "then")
>> (fun _ -> failwith "malformed then clause in if-then-else statement"))
||| ((a (Resword "if") ) ++ preterm
>> (fun _ -> failwith "missing 'then' reserved word in if-then-else statement"))
||| ((a (Resword "if") )
>> (fun _ -> failwith "malformed if-then-else"))
||| (a (Resword "[") ++
elistof preterm (a (Resword ";")) "semicolon separated list of terms" ++
a (Resword "]")
>> (pmk_list o snd o fst))
||| (a (Resword "[") ++
elistof preterm (a (Resword ";")) "semicolon separated list of terms"
>> (fun _ -> failwith "closing square bracket of list expected"))
||| (a (Resword "{") ++
(elistof nocommapreterm (a (Ident ",")) "comma separated list of terms" ++ a (Resword "}")
>> lmk_setenum
||| (preterm ++ a (Resword "|") ++ preterm ++ a (Resword "}")
>> lmk_setabs)
||| (preterm ++ a (Resword "|") ++ preterm ++
a (Resword "|") ++ preterm ++ a (Resword "}")
>> lmk_setcompr))
>> snd)
||| (a (Resword "{") >> (fun _ -> failwith "malformed set {}"))
||| (a (Resword "match") ++ preterm ++ a (Resword "with") ++ clauses
>> (fun (((_,e),_),c) -> Combp(Combp(Varp("_MATCH",dpty),e),c)))
||| (a (Resword "match") >> (fun _ -> failwith "malformed match-with statement"))
||| (a (Resword "function") ++ clauses
>> (fun (_,c) -> Combp(Varp("_FUNCTION",dpty),c)))
||| (a (Resword "function") >> (fun _ -> failwith "malformed function and pattern clauses"))
||| (a (Ident "#") ++ identifier ++
possibly (a (Resword ".") ++ identifier >> snd)
>> lmk_decimal)
||| (a (Ident "#") >> (fun _ -> failwith "malformed numerical # identifier"))
||| (identifier >> (fun s -> Varp(s,dpty)))) i
and pattern i =
(preterm ++ possibly (a (Resword "when") ++ preterm >> snd)) i
and clause i =
((pattern ++ (a (Resword "->") ++ preterm >> snd)) >> pmk_pattern) i
and clauses i =
((possibly (a (Resword "|")) ++
listof clause (a (Resword "|")) "pattern-match clause" >> snd)
>> end_itlist (fun s t -> Combp(Combp(Varp("_SEQPATTERN",dpty),s),t))) i in
(fun inp ->
match inp with
[Ident s] when
not(String.length s >= 2 &&
String.sub s 0 1 = "\"" &&
String.sub s (String.length s - 1) 1 = "\"")
-> Varp(s,dpty),[]
| _ -> preterm inp);;
let parse_type s =
let pty,l = (parse_pretype o lex o explode) s in
if l = [] then type_of_pretype pty
else failwith "Unparsed input following type";;
let parse_term s =
let ptm,l = (parse_preterm o lex o explode) s in
if l = [] then
(term_of_preterm o (retypecheck [])) ptm
else failwith "Unparsed input following term";;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.