_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
|
---|---|---|---|---|---|---|---|---|
98e920b38d9ffda29b7166f6676b392e6d9f2de301120f2cc7642f77180c48f0 | footprintanalytics/footprint-web | specs.clj | (ns metabase.transforms.specs
(:require [medley.core :as m]
[metabase.domain-entities.specs :refer [FieldType MBQL]]
[metabase.mbql.normalize :as mbql.normalize]
[metabase.mbql.schema :as mbql.s]
[metabase.mbql.util :as mbql.u]
[metabase.util :as u]
[metabase.util.schema :as su]
[metabase.util.yaml :as yaml]
[schema.coerce :as sc]
[schema.core :as s]))
(def ^:private Source s/Str)
(def ^:private Dimension s/Str)
(def ^:private Breakout [MBQL])
(def ^:private Aggregation {Dimension MBQL})
(def ^:private Expressions {Dimension MBQL})
(def ^:private Description s/Str)
(def ^:private Filter MBQL)
(def ^:private Limit su/IntGreaterThanZero)
(def ^:private Joins [{(s/required-key :source) Source
(s/required-key :condition) MBQL
(s/optional-key :strategy) mbql.s/JoinStrategy}])
(def ^:private TransformName s/Str)
(def Step
"Transform step"
{(s/required-key :source) Source
(s/required-key :name) Source
(s/required-key :transform) TransformName
(s/optional-key :aggregation) Aggregation
(s/optional-key :breakout) Breakout
(s/optional-key :expressions) Expressions
(s/optional-key :joins) Joins
(s/optional-key :description) Description
(s/optional-key :limit) Limit
(s/optional-key :filter) Filter})
(def ^:private Steps {Source Step})
(def ^:private DomainEntity s/Str)
(def ^:private Requires [DomainEntity])
(def ^:private Provides [DomainEntity])
(def TransformSpec
"Transform spec"
{(s/required-key :name) TransformName
(s/required-key :requires) Requires
(s/required-key :provides) Provides
(s/required-key :steps) Steps
(s/optional-key :description) Description})
(defn- extract-dimensions
[mbql]
(mbql.u/match (mbql.normalize/normalize mbql) [:dimension dimension & _] dimension))
(def ^:private ^{:arglists '([m])} stringify-keys
(partial m/map-keys name))
(defn- add-metadata-to-steps
[spec]
(update spec :steps (partial m/map-kv-vals (fn [step-name step]
(assoc step
:name step-name
:transform (:name spec))))))
(def ^:private transform-spec-parser
(sc/coercer!
TransformSpec
{MBQL mbql.normalize/normalize
Steps (fn [steps]
(->> steps
stringify-keys
(u/topological-sort (fn [{:keys [source joins]}]
(conj (map :source joins) source)))))
Breakout (fn [breakouts]
(for [breakout (u/one-or-many breakouts)]
(if (s/check MBQL breakout)
[:dimension breakout]
breakout)))
FieldType (partial keyword "type")
[DomainEntity] u/one-or-many
mbql.s/JoinStrategy keyword
;; Since `Aggregation` and `Expressions` are structurally the same, we can't use them directly
{Dimension MBQL} (comp (partial u/topological-sort extract-dimensions)
stringify-keys)
;; Some map keys are names (ie. strings) while the rest are keywords, a distinction lost in YAML
s/Str name}))
(def ^:private transforms-dir "transforms/")
(def transform-specs
"List of registered dataset transforms."
(delay (yaml/load-dir transforms-dir (comp transform-spec-parser add-metadata-to-steps))))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/src/metabase/transforms/specs.clj | clojure | Since `Aggregation` and `Expressions` are structurally the same, we can't use them directly
Some map keys are names (ie. strings) while the rest are keywords, a distinction lost in YAML | (ns metabase.transforms.specs
(:require [medley.core :as m]
[metabase.domain-entities.specs :refer [FieldType MBQL]]
[metabase.mbql.normalize :as mbql.normalize]
[metabase.mbql.schema :as mbql.s]
[metabase.mbql.util :as mbql.u]
[metabase.util :as u]
[metabase.util.schema :as su]
[metabase.util.yaml :as yaml]
[schema.coerce :as sc]
[schema.core :as s]))
(def ^:private Source s/Str)
(def ^:private Dimension s/Str)
(def ^:private Breakout [MBQL])
(def ^:private Aggregation {Dimension MBQL})
(def ^:private Expressions {Dimension MBQL})
(def ^:private Description s/Str)
(def ^:private Filter MBQL)
(def ^:private Limit su/IntGreaterThanZero)
(def ^:private Joins [{(s/required-key :source) Source
(s/required-key :condition) MBQL
(s/optional-key :strategy) mbql.s/JoinStrategy}])
(def ^:private TransformName s/Str)
(def Step
"Transform step"
{(s/required-key :source) Source
(s/required-key :name) Source
(s/required-key :transform) TransformName
(s/optional-key :aggregation) Aggregation
(s/optional-key :breakout) Breakout
(s/optional-key :expressions) Expressions
(s/optional-key :joins) Joins
(s/optional-key :description) Description
(s/optional-key :limit) Limit
(s/optional-key :filter) Filter})
(def ^:private Steps {Source Step})
(def ^:private DomainEntity s/Str)
(def ^:private Requires [DomainEntity])
(def ^:private Provides [DomainEntity])
(def TransformSpec
"Transform spec"
{(s/required-key :name) TransformName
(s/required-key :requires) Requires
(s/required-key :provides) Provides
(s/required-key :steps) Steps
(s/optional-key :description) Description})
(defn- extract-dimensions
[mbql]
(mbql.u/match (mbql.normalize/normalize mbql) [:dimension dimension & _] dimension))
(def ^:private ^{:arglists '([m])} stringify-keys
(partial m/map-keys name))
(defn- add-metadata-to-steps
[spec]
(update spec :steps (partial m/map-kv-vals (fn [step-name step]
(assoc step
:name step-name
:transform (:name spec))))))
(def ^:private transform-spec-parser
(sc/coercer!
TransformSpec
{MBQL mbql.normalize/normalize
Steps (fn [steps]
(->> steps
stringify-keys
(u/topological-sort (fn [{:keys [source joins]}]
(conj (map :source joins) source)))))
Breakout (fn [breakouts]
(for [breakout (u/one-or-many breakouts)]
(if (s/check MBQL breakout)
[:dimension breakout]
breakout)))
FieldType (partial keyword "type")
[DomainEntity] u/one-or-many
mbql.s/JoinStrategy keyword
{Dimension MBQL} (comp (partial u/topological-sort extract-dimensions)
stringify-keys)
s/Str name}))
(def ^:private transforms-dir "transforms/")
(def transform-specs
"List of registered dataset transforms."
(delay (yaml/load-dir transforms-dir (comp transform-spec-parser add-metadata-to-steps))))
|
4d87939b19eab52928cef88b43b9919b5a7efc603a405c3df6d61814f3e0db3e | ocsigen/eliom | eliom_lib.client.ml | Ocsigen
* Copyright ( C ) 2005 - 2008 ,
*
* 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 , with linking exception ;
* either version 2.1 of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* Copyright (C) 2005-2008 Vincent Balat, Stéphane Glondu
*
* 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, with linking exception;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open Js_of_ocaml
include Ocsigen_lib_base
include (
Eliom_lib_base :
module type of Eliom_lib_base
with type 'a Int64_map.t = 'a Eliom_lib_base.Int64_map.t
with type 'a String_map.t = 'a Eliom_lib_base.String_map.t
with type 'a Int_map.t = 'a Eliom_lib_base.Int_map.t)
(*****************************************************************************)
module Url = struct
include Url
include Url_base
let decode = Url.urldecode
let encode ?plus s = Url.urlencode ?with_plus:plus s
let make_encoded_parameters = Url.encode_arguments
let split_path = Url.path_of_path_string
let ssl_re = Regexp.regexp "^(https?):\\/\\/"
let get_ssl s =
Option.map
(fun r -> Regexp.matched_group r 1 = Some "https")
(Regexp.string_match ssl_re s 0)
let resolve s =
let a = Dom_html.createA Dom_html.document in
a##.href := Js.string s;
Js.to_string a##.href
let has_get_args url =
try
ignore (String.index url '?');
true
with Not_found -> false
let add_get_args url get_args =
if get_args = []
then url
else
url ^ (if has_get_args url then "&" else "?") ^ encode_arguments get_args
let string_of_url_path ~encode l =
if encode
then print_endline "Warning: Eliom_lib.string_of_url_path ignores ~encode";
String.concat "/" l
let path_of_url = function
| Url.Http {Url.hu_path = path}
| Url.Https {Url.hu_path = path}
| Url.File {Url.fu_path = path} ->
path
let path_of_url_string s =
match Url.url_of_string s with
| Some path -> path_of_url path
| _ -> (
(* assuming relative URL and improvising *)
split_path
@@ try String.(sub s 0 (index s '?')) with Not_found -> s)
end
module Lwt_log = struct
include Lwt_log_js
let raise_error ?inspect ?exn ?section ?location ?logger msg =
Lwt.ignore_result
(log ?inspect ?exn ?section ?location ?logger ~level:Error msg);
match exn with Some exn -> raise exn | None -> failwith msg
let raise_error_f ?inspect ?exn ?section ?location ?logger fmt =
Printf.ksprintf (raise_error ?inspect ?exn ?section ?location ?logger) fmt
let eliom = Section.make "eliom"
end
let _ =
Lwt_log.default := Lwt_log.console;
Lwt.async_exception_hook :=
fun exn ->
Firebug.console##error_3 (Js.string "Lwt.async:")
(Js.string (Printexc.to_string exn))
exn
(* Deprecated ON *)
let debug_exn fmt exn = Lwt_log.ign_info_f ~exn fmt
let debug fmt = Lwt_log.ign_info_f fmt
let error fmt = Lwt_log.raise_error_f fmt
let error_any any fmt = Lwt_log.raise_error_f ~inspect:any fmt
let jsdebug a = Lwt_log.ign_info ~inspect:a "Jsdebug"
(* Deprecated OFF *)
let trace fmt =
if Eliom_config.get_tracing ()
then Lwt_log.ign_info_f (">> " ^^ fmt)
else Printf.ksprintf ignore fmt
let lwt_ignore ?(message = "") t =
Lwt.on_failure t (fun exn -> Lwt_log.ign_info_f ~exn "%s" message)
let jsalert a = Dom_html.window ## (alert a)
let alert fmt = Printf.ksprintf (fun s -> jsalert (Js.string s)) fmt
let confirm =
let f s =
let s = Js.string s in
Dom_html.window ## (confirm s) |> Js.to_bool
in
fun fmt -> Printf.ksprintf f fmt
let debug_var s v = Js.Unsafe.set Dom_html.window (Js.string s) v
module String = struct
include String_base
let eol_re = Regexp.regexp "[\r\n]"
let remove_eols s = Regexp.global_replace eol_re s ""
end
(*****************************************************************************)
(* let () =
(Js.Unsafe.coerce Dom_html.window)##set_tracing <-
Js.wrap_callback (fun v -> set_tracing (Js.to_bool v)) *)
(* We do not use the deriving (un)marshaling even if typ is available
because direct jsn (un)marshaling is very fast client side
*)
let to_json ?typ:_ s = Js.to_string (Json.output s)
let of_json ?typ:_ v = Json.unsafe_input (Js.string v)
(* to marshal data and put it in a form *)
let encode_form_value x = to_json x
(* Url.urlencode ~with_plus:true (Marshal.to_string x [])
(* I encode the data because it seems that multipart does not
like \0 character ... *)
*)
let encode_header_value x =
(* We remove end of lines *)
String.remove_eols (to_json x)
let unmarshal_js var = Marshal.from_string (Js.to_bytestring var) 0
type file_info = File.file Js.t
let make_cryptographic_safe_string ?len:_ () =
failwith "make_cryptographic_safe_string not implemented client-side"
| null | https://raw.githubusercontent.com/ocsigen/eliom/c3e0eea5bef02e0af3942b6d27585add95d01d6c/src/lib/eliom_lib.client.ml | ocaml | ***************************************************************************
assuming relative URL and improvising
Deprecated ON
Deprecated OFF
***************************************************************************
let () =
(Js.Unsafe.coerce Dom_html.window)##set_tracing <-
Js.wrap_callback (fun v -> set_tracing (Js.to_bool v))
We do not use the deriving (un)marshaling even if typ is available
because direct jsn (un)marshaling is very fast client side
to marshal data and put it in a form
Url.urlencode ~with_plus:true (Marshal.to_string x [])
(* I encode the data because it seems that multipart does not
like \0 character ...
We remove end of lines | Ocsigen
* Copyright ( C ) 2005 - 2008 ,
*
* 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 , with linking exception ;
* either version 2.1 of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* Copyright (C) 2005-2008 Vincent Balat, Stéphane Glondu
*
* 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, with linking exception;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open Js_of_ocaml
include Ocsigen_lib_base
include (
Eliom_lib_base :
module type of Eliom_lib_base
with type 'a Int64_map.t = 'a Eliom_lib_base.Int64_map.t
with type 'a String_map.t = 'a Eliom_lib_base.String_map.t
with type 'a Int_map.t = 'a Eliom_lib_base.Int_map.t)
module Url = struct
include Url
include Url_base
let decode = Url.urldecode
let encode ?plus s = Url.urlencode ?with_plus:plus s
let make_encoded_parameters = Url.encode_arguments
let split_path = Url.path_of_path_string
let ssl_re = Regexp.regexp "^(https?):\\/\\/"
let get_ssl s =
Option.map
(fun r -> Regexp.matched_group r 1 = Some "https")
(Regexp.string_match ssl_re s 0)
let resolve s =
let a = Dom_html.createA Dom_html.document in
a##.href := Js.string s;
Js.to_string a##.href
let has_get_args url =
try
ignore (String.index url '?');
true
with Not_found -> false
let add_get_args url get_args =
if get_args = []
then url
else
url ^ (if has_get_args url then "&" else "?") ^ encode_arguments get_args
let string_of_url_path ~encode l =
if encode
then print_endline "Warning: Eliom_lib.string_of_url_path ignores ~encode";
String.concat "/" l
let path_of_url = function
| Url.Http {Url.hu_path = path}
| Url.Https {Url.hu_path = path}
| Url.File {Url.fu_path = path} ->
path
let path_of_url_string s =
match Url.url_of_string s with
| Some path -> path_of_url path
| _ -> (
split_path
@@ try String.(sub s 0 (index s '?')) with Not_found -> s)
end
module Lwt_log = struct
include Lwt_log_js
let raise_error ?inspect ?exn ?section ?location ?logger msg =
Lwt.ignore_result
(log ?inspect ?exn ?section ?location ?logger ~level:Error msg);
match exn with Some exn -> raise exn | None -> failwith msg
let raise_error_f ?inspect ?exn ?section ?location ?logger fmt =
Printf.ksprintf (raise_error ?inspect ?exn ?section ?location ?logger) fmt
let eliom = Section.make "eliom"
end
let _ =
Lwt_log.default := Lwt_log.console;
Lwt.async_exception_hook :=
fun exn ->
Firebug.console##error_3 (Js.string "Lwt.async:")
(Js.string (Printexc.to_string exn))
exn
let debug_exn fmt exn = Lwt_log.ign_info_f ~exn fmt
let debug fmt = Lwt_log.ign_info_f fmt
let error fmt = Lwt_log.raise_error_f fmt
let error_any any fmt = Lwt_log.raise_error_f ~inspect:any fmt
let jsdebug a = Lwt_log.ign_info ~inspect:a "Jsdebug"
let trace fmt =
if Eliom_config.get_tracing ()
then Lwt_log.ign_info_f (">> " ^^ fmt)
else Printf.ksprintf ignore fmt
let lwt_ignore ?(message = "") t =
Lwt.on_failure t (fun exn -> Lwt_log.ign_info_f ~exn "%s" message)
let jsalert a = Dom_html.window ## (alert a)
let alert fmt = Printf.ksprintf (fun s -> jsalert (Js.string s)) fmt
let confirm =
let f s =
let s = Js.string s in
Dom_html.window ## (confirm s) |> Js.to_bool
in
fun fmt -> Printf.ksprintf f fmt
let debug_var s v = Js.Unsafe.set Dom_html.window (Js.string s) v
module String = struct
include String_base
let eol_re = Regexp.regexp "[\r\n]"
let remove_eols s = Regexp.global_replace eol_re s ""
end
let to_json ?typ:_ s = Js.to_string (Json.output s)
let of_json ?typ:_ v = Json.unsafe_input (Js.string v)
let encode_form_value x = to_json x
*)
let encode_header_value x =
String.remove_eols (to_json x)
let unmarshal_js var = Marshal.from_string (Js.to_bytestring var) 0
type file_info = File.file Js.t
let make_cryptographic_safe_string ?len:_ () =
failwith "make_cryptographic_safe_string not implemented client-side"
|
a0d3a8320b160db480cc23861a423e0e6876d36ea3f3805860dd477ab3cb023e | macchiato-framework/macchiato-template | middleware.cljs | (ns {{project-ns}}.middleware
(:require
[macchiato.middleware.defaults :as defaults]))
(defn wrap-defaults [handler]
(defaults/wrap-defaults handler defaults/site-defaults))
| null | https://raw.githubusercontent.com/macchiato-framework/macchiato-template/fff6f0cc640b43933d1e94c85a0b393e89cbe14d/resources/leiningen/new/macchiato/src/server/middleware.cljs | clojure | (ns {{project-ns}}.middleware
(:require
[macchiato.middleware.defaults :as defaults]))
(defn wrap-defaults [handler]
(defaults/wrap-defaults handler defaults/site-defaults))
|
|
4282f0e87a44c84ce980c8a98fb6f64c57f99fbcaa580107b8dec992b1beda12 | ronwalf/HTN-Translation | htnunlift.hs | {-# OPTIONS_GHC
-freduction-depth=30
-Wall
#-}
{-# LANGUAGE
FlexibleContexts,
FlexibleInstances,
OverloadedStrings,
RankNTypes,
ScopedTypeVariables,
TypeOperators,
UndecidableInstances
#-}
module Main where
import Control.Monad (liftM)
import Data.Function (on)
import Data.List
import Data.Maybe
import Data.Text (Text, append, pack)
import qualified Data.Text as DT
--import Debug.Trace
import System.Environment
import System.Exit
import System.FilePath
import System.IO
import Text.ParserCombinators.Parsec hiding (space)
import qualified Text.ParserCombinators.Parsec.Token as T
import Planning.PDDL.PDDL3_0
import Planning.PDDL.Parser
import Planning.Util (cfConversion, findAtoms, findFreeVars, FreeVarsFindable, liftE)
import HTNTranslation.HTNPDDL
import HTNTranslation.ProgressionBounds (findReachableTasks, findMethods)
nunidString :: Text
nunidString = "nunlift_id"
nunid :: (Atomic t :<: f) => t -> t -> Expr f
nunid x y = eAtomic nunidString [x,y]
nuntmemPrefix :: Text
nuntmemPrefix = "nunlift_mem_of_"
nuntmem :: (Atomic t :<: f) => t -> Text -> Expr f
nuntmem x t = eAtomic (append nuntmemPrefix t) [x]
class Functor f => SpecialPredsFindable f where
findNunPreds' :: f (Bool, [Text]) -> (Bool, [Text])
findNunPreds :: SpecialPredsFindable f => Expr f -> (Bool, [Text])
findNunPreds e =
let (i, t) = foldExpr findNunPreds' e in
(i, nub $ sort $ t)
findAllSpecials :: StandardHTNDomain -> (Bool, [Text])
findAllSpecials dom =
foldr (\(xi, xt) (yi, yt) -> (xi || yi, xt ++ yt)) (False, []) $
map (findNunPreds . snd) $
concatMap getPrecondition $
getActions dom
instance (SpecialPredsFindable f, SpecialPredsFindable g) => SpecialPredsFindable (f :+: g) where
findNunPreds' (Inl x) = findNunPreds' x
findNunPreds' (Inr y) = findNunPreds' y
instance SpecialPredsFindable (Atomic (Expr t)) where
findNunPreds' (Atomic p _) = case DT.stripPrefix nuntmemPrefix p of
Just t -> (False, [t])
Nothing -> if (p == nunidString) then (True, []) else (False, [])
instance SpecialPredsFindable Not where
findNunPreds' (Not t) = t
instance SpecialPredsFindable (ForAll vt) where
findNunPreds' (ForAll _ t) = t
instance SpecialPredsFindable (Exists vt) where
findNunPreds' (Exists _ t) = t
instance SpecialPredsFindable Imply where
findNunPreds' (Imply (xi, xt) (yi, yt)) = (xi || yi, xt ++ yt)
instance SpecialPredsFindable And where
findNunPreds' (And el) = foldr (\(xi, xt) (yi, yt) -> (xi || yi, xt ++ yt)) (False, []) el
instance SpecialPredsFindable Or where
findNunPreds' (Or el) = foldr (\(xi, xt) (yi, yt) -> (xi || yi, xt ++ yt)) (False, []) el
class (Functor f, FreeVarsFindable f) => TypedVarsFindable f where
findTypedVars' :: [TypedPredicateExpr] -> f [TypedVarExpr] -> [TypedVarExpr]
findTypedVars :: TypedVarsFindable f => [TypedPredicateExpr] -> Expr f -> [TypedVarExpr]
findTypedVars typeDefs = foldExpr (findTypedVars' typeDefs)
instance (TypedVarsFindable f, TypedVarsFindable g) => TypedVarsFindable (f :+: g) where
findTypedVars' typeDefs (Inl x) = findTypedVars' typeDefs x
findTypedVars' typeDefs (Inr y) = findTypedVars' typeDefs y
instance FreeVarsFindable t => TypedVarsFindable (Atomic (Expr t)) where
findTypedVars' typeDefs (Atomic p tl) = concat $ zipWith pvlookup [0..] tl
where
pvlookup :: Int -> (Expr t) -> [TypedVarExpr]
pvlookup n t =
let types :: [Text] =
concatMap (getType . (!! n)) $
filter ((> n) . length) $
map taskArgs $
filter ((==) p . taskName) typeDefs in
map (flip eTyped types) $ findFreeVars t -- Actually quite wrong if functions are allowed.
findAllTypedVars :: TypedVarsFindable f => [TypedPredicateExpr] -> [Expr f] -> [TypedVarExpr]
findAllTypedVars typeDefs = concatMap retype . groupBy ((==) `on` removeType) . sort . concatMap (findTypedVars typeDefs)
where
retype :: [TypedVarExpr] -> [TypedVarExpr]
retype [] = []
retype tl@(t:_) = [eTyped (removeType t) $ nub $ sort $ concatMap getType tl]
type LiftedHTNProblem = HProblem InitLiteralExpr PreferenceGDExpr ConstraintGDExpr TermExpr
liftedProblemParser :: GenParser Char LiftedHTNProblem LiftedHTNProblem
liftedProblemParser =
let
stateP = T.parens pddlExprLexer $ initLiteralParser pddlExprLexer :: CharParser LiftedHTNProblem InitLiteralExpr
goalP = prefGDParser pddlExprLexer :: CharParser LiftedHTNProblem PreferenceGDExpr
constraintP = constraintGDParser pddlExprLexer :: CharParser LiftedHTNProblem ConstraintGDExpr
infoP =
(taskListParser htnDescLexer (termParser pddlExprLexer) >>= updateState)
<|> (taskConstraintParser htnDescLexer >>= updateState)
<|> problemInfoParser htnDescLexer stateP goalP constraintP
in
problemParser htnDescLexer infoP
parseLiftedHTN :: SourceName -> String -> Either ParseError LiftedHTNProblem
parseLiftedHTN source input =
runParser liftedProblemParser emptyHProblem source input
-- Copy a problem without its initial task list and constraints
copyProblem :: LiftedHTNProblem -> StandardHTNProblem
copyProblem prob =
setName (getName prob) $
setDomainName (getDomainName prob) $
setRequirements (getRequirements prob) $
setConstants (getConstants prob) $
setInitial (getInitial prob) $
setGoal (getGoal prob) $
setConstraints (getConstraints prob) $
(emptyHProblem :: StandardHTNProblem)
trivialConversion :: (Monad m) => LiftedHTNProblem -> m StandardHTNProblem
trivialConversion prob = do
taskLists <- mapM convertList $ getTaskLists prob
return $
setTaskLists taskLists $
setTaskConstraints (getTaskConstraints prob) $
copyProblem prob
where
convertList :: (Monad m) => (Maybe Text, [Expr (Atomic TermExpr)]) -> m (Maybe Text, [Expr (Atomic ConstTermExpr)])
convertList (name, tasks) = do
ctasks <- mapM (\t -> do {(tl :: [ConstTermExpr]) <- mapM cfConversion (taskArgs t); return (eAtomic (taskName t) tl)}) tasks
return (name, ctasks :: [Expr (Atomic ConstTermExpr)])
injectionConversion :: StandardHTNDomain -> LiftedHTNProblem -> (StandardHTNDomain, StandardHTNProblem)
injectionConversion dom lprob =
( injectDomain $ injectMethod (getTaskLists lprob) (getTaskConstraints lprob)
, setTaskLists [(Nothing, [tname :: Expr (Atomic ConstTermExpr)])] $ copyProblem lprob)
where
tname :: forall t . Expr (Atomic t)
tname = eAtomic "htn_initial_task" ([] :: [t])
injectDomain :: StandardMethod -> StandardHTNDomain
injectDomain m =
setTaskHead (tname : getTaskHead dom) $
setActions (m : getActions dom) $
dom
injectMethod :: [TaskList TermExpr] -> [TaskConstraint] -> StandardMethod
injectMethod taskLists taskConstraints =
let
tdefs =
( \x - > trace ( ( " TDefs : " + + ) $ show $ map pddlDoc x ) x ) $
getTaskHead dom ++ getPredicates dom
params =
( \x - > trace ( ( " Params : " + + ) $ show $ pddlDoc x ) x ) $
findAllTypedVars tdefs $
( \x - > trace ( ( " Tasks : " + + ) $ show $ map pddlDoc x ) x ) $
concatMap snd taskLists
in
setName "assert_initial_tasks" $
setTaskHead (Just tname) $
setParameters params $
setTaskLists taskLists $
setTaskConstraints taskConstraints $
defaultMethod
removeEmptyTypes :: StandardHTNDomain -> StandardHTNProblem -> StandardHTNDomain
removeEmptyTypes dom prob =
let
usedBaseTypes :: [Text] = concatMap getType $ getConstants dom ++ getConstants prob
usedTypes :: [Text] = nub $ sort $ fst $ last $
takeWhile (not . null . snd) $
iterate (\(at, _) ->
let nt = filter (flip notElem at) $
concatMap getType $
filter (flip elem at . removeType) $
getTypes dom
in
(at ++ nt, nt))
(usedBaseTypes, usedBaseTypes)
missingTPNames :: [Text] =
map taskName $
filter (or . map (and . (\x -> (not $ null x) : x) . map (flip notElem usedTypes) . getType) . taskArgs) $
(getTaskHead dom ++ getPredicates dom)
useableActions :: [StandardMethod] =
-- Doesn't remove old types from params with (either...)
filter (not . missingSubtask) $
filter (not . missingParameter) $
getActions dom
missingParameter :: StandardMethod -> Bool
missingParameter = or . map (and . (\x -> (not $ null x) : x) . map (flip notElem usedTypes) . getType) . getParameters
missingSubtask :: StandardMethod -> Bool
missingSubtask = or . map (flip elem missingTPNames . taskName . snd) . enumerateTasks
in
setTypes (filter (flip elem usedTypes . removeType) $ getTypes dom) $
setTaskHead (filter (flip notElem missingTPNames . taskName) $ getTaskHead dom) $
setPredicates (filter (flip notElem missingTPNames . taskName) $ getPredicates dom) $
setActions useableActions $
dom
compileTypes :: (StandardHTNDomain, StandardHTNProblem) -> (StandardHTNDomain, StandardHTNProblem)
compileTypes (dom, prob) =
( setTypes [eTyped ("POBJ" :: Text) []]
$ setTaskHead utTasks
$ setPredicates utPreds
$ setConstants utDConsts
$ setActions (map utAction $ getActions dom) dom
, setConstants utConsts $ setInitial utInitial prob )
where
allTypes :: [Text]
allTypes = nub $ sort $ concatMap (\t -> removeType t : getType t) $ getTypes dom
retype :: forall f g . Untypeable f g => Expr f -> Expr (Typed g)
retype tvar = eTyped (removeType tvar) ["POBJ"]
utDConsts :: [TypedConstExpr]
utDConsts = map retype $ getConstants dom
utConsts :: [TypedConstExpr]
utConsts = map retype $ getConstants prob
utTasks :: [TypedPredicateExpr]
utTasks = map (\l -> eAtomic (taskName l) (map retype (taskArgs l) :: [TypedVarExpr])) $ getTaskHead dom
utPreds :: [TypedPredicateExpr]
utPreds =
map (flip eAtomic [eTyped (eVar "x" :: Expr Var) ["POBJ"] :: TypedVarExpr]) allTypes
++ (map (\l -> eAtomic (taskName l) (map retype (taskArgs l) :: [TypedVarExpr])) $ getPredicates dom)
utInitial :: [InitLiteralExpr]
utInitial =
(flip concatMap allTypes $ \t ->
map (eAtomic t . (:[]) . (liftE :: Expr Const -> ConstTermExpr) . removeType) $ nub $ sort $ findmems t)
++ getInitial prob
-- Currently ignores all quantification
utAction :: StandardMethod -> StandardMethod
utAction action =
setParameters (map retype $ getParameters action) $
setPrecondition (concat (map paramPreds (getParameters action) ++ [getPrecondition action])) $
action
paramPreds :: TypedVarExpr -> [(Maybe Text, GDExpr)]
paramPreds (In (Typed _ [])) = []
paramPreds (In (Typed v [t])) = [(Nothing, eAtomic t [liftE v :: TermExpr])]
paramPreds (In (Typed v tl)) = [(Nothing, eOr $ map (flip eAtomic [liftE v :: TermExpr]) tl)]
findmems t =
filter (\c -> t `elem` getType c) (getConstants dom ++ getConstants prob)
++ concatMap (findmems . removeType)
(filter (elem t . getType) $ getTypes dom)
processSpecials :: (StandardHTNDomain, StandardHTNProblem) -> (StandardHTNDomain, StandardHTNProblem)
processSpecials (dom, prob) =
let (usesId, tmems) = findAllSpecials dom in
addIdentity usesId $
flip (foldl addTypeMem) tmems $
(dom, prob)
where
addIdentity :: Bool -> (StandardHTNDomain, StandardHTNProblem) -> (StandardHTNDomain, StandardHTNProblem)
addIdentity False (dom', prob') = (dom', prob')
addIdentity True (dom', prob') =
( setPredicates (nunid (eTyped (eVar "x" :: Expr Var) [] :: TypedVarExpr) (eTyped (eVar "y" :: Expr Var) []) : getPredicates dom') dom'
, setInitial ([nunid (liftE (removeType i) :: ConstTermExpr) (liftE $ removeType i)
| i <- getConstants dom' ++ getConstants prob']
++ getInitial prob')
prob')
addTypeMem :: (StandardHTNDomain, StandardHTNProblem) -> Text -> (StandardHTNDomain, StandardHTNProblem)
addTypeMem (dom', prob') t =
( setPredicates (nuntmem (eTyped (eVar "x" :: Expr Var) [] :: TypedVarExpr) t : getPredicates dom') dom'
, setInitial
( map (flip nuntmem t :: ConstTermExpr -> InitLiteralExpr)
(nub $ sort $ map (liftE . removeType) $ findmems t)
++ getInitial prob') prob')
findmems t =
filter (\c -> t `elem` getType c) (getConstants dom ++ getConstants prob)
++ concatMap (findmems . removeType)
(filter (elem t . getType) $ getTypes dom)
stripUnreachable :: StandardHTNDomain -> StandardHTNProblem -> StandardHTNDomain
stripUnreachable dom prob =
setActions (reachable ++ headless) dom
where
headless = filter (isNothing . getTaskHead) $ getActions dom
reachable =
concatMap (findMethods dom :: Text -> [StandardMethod]) $
findReachableTasks dom $
listTaskNames prob
ensurePrimitiveTasks :: StandardHTNDomain -> StandardHTNDomain
ensurePrimitiveTasks dom =
flip setTaskHead dom $
(++ getTaskHead dom) $
map (\a -> eAtomic (getName a) (getParameters a)) $
filter (\a -> (getName a) `notElem` (map taskName $ getTaskHead dom)) $
filter (\a -> (Just $ getName a) == ((getTaskHead a) >>= (return . taskName))) $
getActions dom
ensurePredicates :: StandardHTNDomain -> StandardHTNProblem -> StandardHTNDomain
ensurePredicates dom prob = setPredicates (getPredicates dom ++ tpreds) dom
where
typedVars :: [TypedVarExpr]
typedVars = map (flip eTyped ["POBJ"] . (eVar :: Text -> Expr Var) . (append "v") . pack . show) ([1..] :: [Int])
definedAtoms :: [Text]
definedAtoms = ("=":) $ map taskName $ getPredicates dom
nameArity :: forall g . Expr (Atomic g) -> (Text, Int)
nameArity p = (taskName p, length $ taskArgs p)
precondAtoms :: PDDLPrecond -> [(Text, Int)]
precondAtoms = map nameArity . (findAtoms :: GDExpr -> [Expr (Atomic TermExpr)]) . snd
effectAtoms :: PDDLEffect -> [(Text,Int)]
effectAtoms (_, Just p, e) = (map nameArity (findAtoms p :: [Expr (Atomic TermExpr)])) ++ (effectAtoms ([], Nothing, e))
effectAtoms (_, Nothing, e) = map nameArity $ concatMap (findAtoms :: EffectDExpr -> [Expr (Atomic TermExpr)]) e
actionAtoms :: StandardMethod -> [(Text, Int)]
actionAtoms action =
concatMap precondAtoms (getPrecondition action)
++ concatMap effectAtoms (getEffect action)
tpreds :: [TypedPredicateExpr]
tpreds = map (\(p,n) -> eAtomic p (take n typedVars)) $
filter (flip notElem definedAtoms . fst) $
nub $ sort $
(concatMap actionAtoms (getActions dom))
++ (map nameArity $ concatMap (findAtoms :: InitLiteralExpr -> [Expr (Atomic ConstTermExpr)]) $ getInitial prob)
processProblem :: StandardHTNDomain -> String -> IO ()
processProblem domain probFile = do
contents <- readFile probFile
problem <- errCheck $ parseLiftedHTN probFile contents
let (dom',prob') =
( \x - > trace ( ( " Post type removal:\n " + + ) $
show $ pddlDoc $ fst x ) x ) $
compileTypes $ (\(d, p) -> (removeEmptyTypes d p, p)) $
( \x - > trace ( ( " Pre type removal:\n " + + ) $
show $ pddlDoc $ fst x ) x ) $
( \x - > trace ( ( " Reachable : " + + ) $
show $ findReachableTasks ( fst x ) ( snd x ) ) x ) $
case (trivialConversion problem) of
(Just p) -> (domain, p)
Nothing -> injectionConversion domain problem
saveFiles (flip ensurePredicates prob' $ stripUnreachable dom' prob') prob' probFile
return ()
saveFiles :: StandardHTNDomain -> StandardHTNProblem -> String -> IO ()
saveFiles dom prob fname = do
let oname = '-' : addExtension (takeBaseName fname) "hpddl"
writeFile ('d' : oname) (show $ pddlDoc dom)
writeFile ('p' : oname) (show $ pddlDoc prob)
return ()
errCheck :: (Show t) => Either t b -> IO b
errCheck (Left err) = do
hPrint stderr err
exitFailure
errCheck (Right prob) = return prob
main :: IO ()
main = do
argv <- getArgs
(domFile, files) <- case argv of
(dom : files @ (_ : _)) -> do return (dom, files)
_ -> ioError $ userError "Usage: htnunlift domain.hpddl problem1.hpddl [problem2.hpddl, ...]\nOutputs: d-problem1.hpddl, p-problem1.hpddl, d-problem2.hpddl..."
domContents <- readFile domFile
domain <- liftM ensurePrimitiveTasks (errCheck $ parseHTNPDDL domFile domContents)
mapM_ (processProblem domain) files
return ()
| null | https://raw.githubusercontent.com/ronwalf/HTN-Translation/dfe39a9444c944e2efd48306e122a17d6c0f2d89/src-cmdline/htnunlift.hs | haskell | # OPTIONS_GHC
-freduction-depth=30
-Wall
#
# LANGUAGE
FlexibleContexts,
FlexibleInstances,
OverloadedStrings,
RankNTypes,
ScopedTypeVariables,
TypeOperators,
UndecidableInstances
#
import Debug.Trace
Actually quite wrong if functions are allowed.
Copy a problem without its initial task list and constraints
Doesn't remove old types from params with (either...)
Currently ignores all quantification | module Main where
import Control.Monad (liftM)
import Data.Function (on)
import Data.List
import Data.Maybe
import Data.Text (Text, append, pack)
import qualified Data.Text as DT
import System.Environment
import System.Exit
import System.FilePath
import System.IO
import Text.ParserCombinators.Parsec hiding (space)
import qualified Text.ParserCombinators.Parsec.Token as T
import Planning.PDDL.PDDL3_0
import Planning.PDDL.Parser
import Planning.Util (cfConversion, findAtoms, findFreeVars, FreeVarsFindable, liftE)
import HTNTranslation.HTNPDDL
import HTNTranslation.ProgressionBounds (findReachableTasks, findMethods)
nunidString :: Text
nunidString = "nunlift_id"
nunid :: (Atomic t :<: f) => t -> t -> Expr f
nunid x y = eAtomic nunidString [x,y]
nuntmemPrefix :: Text
nuntmemPrefix = "nunlift_mem_of_"
nuntmem :: (Atomic t :<: f) => t -> Text -> Expr f
nuntmem x t = eAtomic (append nuntmemPrefix t) [x]
class Functor f => SpecialPredsFindable f where
findNunPreds' :: f (Bool, [Text]) -> (Bool, [Text])
findNunPreds :: SpecialPredsFindable f => Expr f -> (Bool, [Text])
findNunPreds e =
let (i, t) = foldExpr findNunPreds' e in
(i, nub $ sort $ t)
findAllSpecials :: StandardHTNDomain -> (Bool, [Text])
findAllSpecials dom =
foldr (\(xi, xt) (yi, yt) -> (xi || yi, xt ++ yt)) (False, []) $
map (findNunPreds . snd) $
concatMap getPrecondition $
getActions dom
instance (SpecialPredsFindable f, SpecialPredsFindable g) => SpecialPredsFindable (f :+: g) where
findNunPreds' (Inl x) = findNunPreds' x
findNunPreds' (Inr y) = findNunPreds' y
instance SpecialPredsFindable (Atomic (Expr t)) where
findNunPreds' (Atomic p _) = case DT.stripPrefix nuntmemPrefix p of
Just t -> (False, [t])
Nothing -> if (p == nunidString) then (True, []) else (False, [])
instance SpecialPredsFindable Not where
findNunPreds' (Not t) = t
instance SpecialPredsFindable (ForAll vt) where
findNunPreds' (ForAll _ t) = t
instance SpecialPredsFindable (Exists vt) where
findNunPreds' (Exists _ t) = t
instance SpecialPredsFindable Imply where
findNunPreds' (Imply (xi, xt) (yi, yt)) = (xi || yi, xt ++ yt)
instance SpecialPredsFindable And where
findNunPreds' (And el) = foldr (\(xi, xt) (yi, yt) -> (xi || yi, xt ++ yt)) (False, []) el
instance SpecialPredsFindable Or where
findNunPreds' (Or el) = foldr (\(xi, xt) (yi, yt) -> (xi || yi, xt ++ yt)) (False, []) el
class (Functor f, FreeVarsFindable f) => TypedVarsFindable f where
findTypedVars' :: [TypedPredicateExpr] -> f [TypedVarExpr] -> [TypedVarExpr]
findTypedVars :: TypedVarsFindable f => [TypedPredicateExpr] -> Expr f -> [TypedVarExpr]
findTypedVars typeDefs = foldExpr (findTypedVars' typeDefs)
instance (TypedVarsFindable f, TypedVarsFindable g) => TypedVarsFindable (f :+: g) where
findTypedVars' typeDefs (Inl x) = findTypedVars' typeDefs x
findTypedVars' typeDefs (Inr y) = findTypedVars' typeDefs y
instance FreeVarsFindable t => TypedVarsFindable (Atomic (Expr t)) where
findTypedVars' typeDefs (Atomic p tl) = concat $ zipWith pvlookup [0..] tl
where
pvlookup :: Int -> (Expr t) -> [TypedVarExpr]
pvlookup n t =
let types :: [Text] =
concatMap (getType . (!! n)) $
filter ((> n) . length) $
map taskArgs $
filter ((==) p . taskName) typeDefs in
findAllTypedVars :: TypedVarsFindable f => [TypedPredicateExpr] -> [Expr f] -> [TypedVarExpr]
findAllTypedVars typeDefs = concatMap retype . groupBy ((==) `on` removeType) . sort . concatMap (findTypedVars typeDefs)
where
retype :: [TypedVarExpr] -> [TypedVarExpr]
retype [] = []
retype tl@(t:_) = [eTyped (removeType t) $ nub $ sort $ concatMap getType tl]
type LiftedHTNProblem = HProblem InitLiteralExpr PreferenceGDExpr ConstraintGDExpr TermExpr
liftedProblemParser :: GenParser Char LiftedHTNProblem LiftedHTNProblem
liftedProblemParser =
let
stateP = T.parens pddlExprLexer $ initLiteralParser pddlExprLexer :: CharParser LiftedHTNProblem InitLiteralExpr
goalP = prefGDParser pddlExprLexer :: CharParser LiftedHTNProblem PreferenceGDExpr
constraintP = constraintGDParser pddlExprLexer :: CharParser LiftedHTNProblem ConstraintGDExpr
infoP =
(taskListParser htnDescLexer (termParser pddlExprLexer) >>= updateState)
<|> (taskConstraintParser htnDescLexer >>= updateState)
<|> problemInfoParser htnDescLexer stateP goalP constraintP
in
problemParser htnDescLexer infoP
parseLiftedHTN :: SourceName -> String -> Either ParseError LiftedHTNProblem
parseLiftedHTN source input =
runParser liftedProblemParser emptyHProblem source input
copyProblem :: LiftedHTNProblem -> StandardHTNProblem
copyProblem prob =
setName (getName prob) $
setDomainName (getDomainName prob) $
setRequirements (getRequirements prob) $
setConstants (getConstants prob) $
setInitial (getInitial prob) $
setGoal (getGoal prob) $
setConstraints (getConstraints prob) $
(emptyHProblem :: StandardHTNProblem)
trivialConversion :: (Monad m) => LiftedHTNProblem -> m StandardHTNProblem
trivialConversion prob = do
taskLists <- mapM convertList $ getTaskLists prob
return $
setTaskLists taskLists $
setTaskConstraints (getTaskConstraints prob) $
copyProblem prob
where
convertList :: (Monad m) => (Maybe Text, [Expr (Atomic TermExpr)]) -> m (Maybe Text, [Expr (Atomic ConstTermExpr)])
convertList (name, tasks) = do
ctasks <- mapM (\t -> do {(tl :: [ConstTermExpr]) <- mapM cfConversion (taskArgs t); return (eAtomic (taskName t) tl)}) tasks
return (name, ctasks :: [Expr (Atomic ConstTermExpr)])
injectionConversion :: StandardHTNDomain -> LiftedHTNProblem -> (StandardHTNDomain, StandardHTNProblem)
injectionConversion dom lprob =
( injectDomain $ injectMethod (getTaskLists lprob) (getTaskConstraints lprob)
, setTaskLists [(Nothing, [tname :: Expr (Atomic ConstTermExpr)])] $ copyProblem lprob)
where
tname :: forall t . Expr (Atomic t)
tname = eAtomic "htn_initial_task" ([] :: [t])
injectDomain :: StandardMethod -> StandardHTNDomain
injectDomain m =
setTaskHead (tname : getTaskHead dom) $
setActions (m : getActions dom) $
dom
injectMethod :: [TaskList TermExpr] -> [TaskConstraint] -> StandardMethod
injectMethod taskLists taskConstraints =
let
tdefs =
( \x - > trace ( ( " TDefs : " + + ) $ show $ map pddlDoc x ) x ) $
getTaskHead dom ++ getPredicates dom
params =
( \x - > trace ( ( " Params : " + + ) $ show $ pddlDoc x ) x ) $
findAllTypedVars tdefs $
( \x - > trace ( ( " Tasks : " + + ) $ show $ map pddlDoc x ) x ) $
concatMap snd taskLists
in
setName "assert_initial_tasks" $
setTaskHead (Just tname) $
setParameters params $
setTaskLists taskLists $
setTaskConstraints taskConstraints $
defaultMethod
removeEmptyTypes :: StandardHTNDomain -> StandardHTNProblem -> StandardHTNDomain
removeEmptyTypes dom prob =
let
usedBaseTypes :: [Text] = concatMap getType $ getConstants dom ++ getConstants prob
usedTypes :: [Text] = nub $ sort $ fst $ last $
takeWhile (not . null . snd) $
iterate (\(at, _) ->
let nt = filter (flip notElem at) $
concatMap getType $
filter (flip elem at . removeType) $
getTypes dom
in
(at ++ nt, nt))
(usedBaseTypes, usedBaseTypes)
missingTPNames :: [Text] =
map taskName $
filter (or . map (and . (\x -> (not $ null x) : x) . map (flip notElem usedTypes) . getType) . taskArgs) $
(getTaskHead dom ++ getPredicates dom)
useableActions :: [StandardMethod] =
filter (not . missingSubtask) $
filter (not . missingParameter) $
getActions dom
missingParameter :: StandardMethod -> Bool
missingParameter = or . map (and . (\x -> (not $ null x) : x) . map (flip notElem usedTypes) . getType) . getParameters
missingSubtask :: StandardMethod -> Bool
missingSubtask = or . map (flip elem missingTPNames . taskName . snd) . enumerateTasks
in
setTypes (filter (flip elem usedTypes . removeType) $ getTypes dom) $
setTaskHead (filter (flip notElem missingTPNames . taskName) $ getTaskHead dom) $
setPredicates (filter (flip notElem missingTPNames . taskName) $ getPredicates dom) $
setActions useableActions $
dom
compileTypes :: (StandardHTNDomain, StandardHTNProblem) -> (StandardHTNDomain, StandardHTNProblem)
compileTypes (dom, prob) =
( setTypes [eTyped ("POBJ" :: Text) []]
$ setTaskHead utTasks
$ setPredicates utPreds
$ setConstants utDConsts
$ setActions (map utAction $ getActions dom) dom
, setConstants utConsts $ setInitial utInitial prob )
where
allTypes :: [Text]
allTypes = nub $ sort $ concatMap (\t -> removeType t : getType t) $ getTypes dom
retype :: forall f g . Untypeable f g => Expr f -> Expr (Typed g)
retype tvar = eTyped (removeType tvar) ["POBJ"]
utDConsts :: [TypedConstExpr]
utDConsts = map retype $ getConstants dom
utConsts :: [TypedConstExpr]
utConsts = map retype $ getConstants prob
utTasks :: [TypedPredicateExpr]
utTasks = map (\l -> eAtomic (taskName l) (map retype (taskArgs l) :: [TypedVarExpr])) $ getTaskHead dom
utPreds :: [TypedPredicateExpr]
utPreds =
map (flip eAtomic [eTyped (eVar "x" :: Expr Var) ["POBJ"] :: TypedVarExpr]) allTypes
++ (map (\l -> eAtomic (taskName l) (map retype (taskArgs l) :: [TypedVarExpr])) $ getPredicates dom)
utInitial :: [InitLiteralExpr]
utInitial =
(flip concatMap allTypes $ \t ->
map (eAtomic t . (:[]) . (liftE :: Expr Const -> ConstTermExpr) . removeType) $ nub $ sort $ findmems t)
++ getInitial prob
utAction :: StandardMethod -> StandardMethod
utAction action =
setParameters (map retype $ getParameters action) $
setPrecondition (concat (map paramPreds (getParameters action) ++ [getPrecondition action])) $
action
paramPreds :: TypedVarExpr -> [(Maybe Text, GDExpr)]
paramPreds (In (Typed _ [])) = []
paramPreds (In (Typed v [t])) = [(Nothing, eAtomic t [liftE v :: TermExpr])]
paramPreds (In (Typed v tl)) = [(Nothing, eOr $ map (flip eAtomic [liftE v :: TermExpr]) tl)]
findmems t =
filter (\c -> t `elem` getType c) (getConstants dom ++ getConstants prob)
++ concatMap (findmems . removeType)
(filter (elem t . getType) $ getTypes dom)
processSpecials :: (StandardHTNDomain, StandardHTNProblem) -> (StandardHTNDomain, StandardHTNProblem)
processSpecials (dom, prob) =
let (usesId, tmems) = findAllSpecials dom in
addIdentity usesId $
flip (foldl addTypeMem) tmems $
(dom, prob)
where
addIdentity :: Bool -> (StandardHTNDomain, StandardHTNProblem) -> (StandardHTNDomain, StandardHTNProblem)
addIdentity False (dom', prob') = (dom', prob')
addIdentity True (dom', prob') =
( setPredicates (nunid (eTyped (eVar "x" :: Expr Var) [] :: TypedVarExpr) (eTyped (eVar "y" :: Expr Var) []) : getPredicates dom') dom'
, setInitial ([nunid (liftE (removeType i) :: ConstTermExpr) (liftE $ removeType i)
| i <- getConstants dom' ++ getConstants prob']
++ getInitial prob')
prob')
addTypeMem :: (StandardHTNDomain, StandardHTNProblem) -> Text -> (StandardHTNDomain, StandardHTNProblem)
addTypeMem (dom', prob') t =
( setPredicates (nuntmem (eTyped (eVar "x" :: Expr Var) [] :: TypedVarExpr) t : getPredicates dom') dom'
, setInitial
( map (flip nuntmem t :: ConstTermExpr -> InitLiteralExpr)
(nub $ sort $ map (liftE . removeType) $ findmems t)
++ getInitial prob') prob')
findmems t =
filter (\c -> t `elem` getType c) (getConstants dom ++ getConstants prob)
++ concatMap (findmems . removeType)
(filter (elem t . getType) $ getTypes dom)
stripUnreachable :: StandardHTNDomain -> StandardHTNProblem -> StandardHTNDomain
stripUnreachable dom prob =
setActions (reachable ++ headless) dom
where
headless = filter (isNothing . getTaskHead) $ getActions dom
reachable =
concatMap (findMethods dom :: Text -> [StandardMethod]) $
findReachableTasks dom $
listTaskNames prob
ensurePrimitiveTasks :: StandardHTNDomain -> StandardHTNDomain
ensurePrimitiveTasks dom =
flip setTaskHead dom $
(++ getTaskHead dom) $
map (\a -> eAtomic (getName a) (getParameters a)) $
filter (\a -> (getName a) `notElem` (map taskName $ getTaskHead dom)) $
filter (\a -> (Just $ getName a) == ((getTaskHead a) >>= (return . taskName))) $
getActions dom
ensurePredicates :: StandardHTNDomain -> StandardHTNProblem -> StandardHTNDomain
ensurePredicates dom prob = setPredicates (getPredicates dom ++ tpreds) dom
where
typedVars :: [TypedVarExpr]
typedVars = map (flip eTyped ["POBJ"] . (eVar :: Text -> Expr Var) . (append "v") . pack . show) ([1..] :: [Int])
definedAtoms :: [Text]
definedAtoms = ("=":) $ map taskName $ getPredicates dom
nameArity :: forall g . Expr (Atomic g) -> (Text, Int)
nameArity p = (taskName p, length $ taskArgs p)
precondAtoms :: PDDLPrecond -> [(Text, Int)]
precondAtoms = map nameArity . (findAtoms :: GDExpr -> [Expr (Atomic TermExpr)]) . snd
effectAtoms :: PDDLEffect -> [(Text,Int)]
effectAtoms (_, Just p, e) = (map nameArity (findAtoms p :: [Expr (Atomic TermExpr)])) ++ (effectAtoms ([], Nothing, e))
effectAtoms (_, Nothing, e) = map nameArity $ concatMap (findAtoms :: EffectDExpr -> [Expr (Atomic TermExpr)]) e
actionAtoms :: StandardMethod -> [(Text, Int)]
actionAtoms action =
concatMap precondAtoms (getPrecondition action)
++ concatMap effectAtoms (getEffect action)
tpreds :: [TypedPredicateExpr]
tpreds = map (\(p,n) -> eAtomic p (take n typedVars)) $
filter (flip notElem definedAtoms . fst) $
nub $ sort $
(concatMap actionAtoms (getActions dom))
++ (map nameArity $ concatMap (findAtoms :: InitLiteralExpr -> [Expr (Atomic ConstTermExpr)]) $ getInitial prob)
processProblem :: StandardHTNDomain -> String -> IO ()
processProblem domain probFile = do
contents <- readFile probFile
problem <- errCheck $ parseLiftedHTN probFile contents
let (dom',prob') =
( \x - > trace ( ( " Post type removal:\n " + + ) $
show $ pddlDoc $ fst x ) x ) $
compileTypes $ (\(d, p) -> (removeEmptyTypes d p, p)) $
( \x - > trace ( ( " Pre type removal:\n " + + ) $
show $ pddlDoc $ fst x ) x ) $
( \x - > trace ( ( " Reachable : " + + ) $
show $ findReachableTasks ( fst x ) ( snd x ) ) x ) $
case (trivialConversion problem) of
(Just p) -> (domain, p)
Nothing -> injectionConversion domain problem
saveFiles (flip ensurePredicates prob' $ stripUnreachable dom' prob') prob' probFile
return ()
saveFiles :: StandardHTNDomain -> StandardHTNProblem -> String -> IO ()
saveFiles dom prob fname = do
let oname = '-' : addExtension (takeBaseName fname) "hpddl"
writeFile ('d' : oname) (show $ pddlDoc dom)
writeFile ('p' : oname) (show $ pddlDoc prob)
return ()
errCheck :: (Show t) => Either t b -> IO b
errCheck (Left err) = do
hPrint stderr err
exitFailure
errCheck (Right prob) = return prob
main :: IO ()
main = do
argv <- getArgs
(domFile, files) <- case argv of
(dom : files @ (_ : _)) -> do return (dom, files)
_ -> ioError $ userError "Usage: htnunlift domain.hpddl problem1.hpddl [problem2.hpddl, ...]\nOutputs: d-problem1.hpddl, p-problem1.hpddl, d-problem2.hpddl..."
domContents <- readFile domFile
domain <- liftM ensurePrimitiveTasks (errCheck $ parseHTNPDDL domFile domContents)
mapM_ (processProblem domain) files
return ()
|
21033e865909cb00ac3842e007831493155f53255abd57d9bcdd4fb54bd5e4f8 | inconvergent/weird | ortho.lisp |
(in-package :ortho)
"
Simple orthographic projection with camera position (cam), view vector (vpn)
view plane offset (xy) and scaling (s).
"
(declaim (inline 3identity))
(veq:fvdef 3identity ((:va 3 x)) (values x))
(declaim (inline zero))
(veq:fvdef zero () (veq:f3$point 0f0 0f0 0f0))
(defstruct (ortho)
away from dop
(up (zero) :type veq:fvec :read-only nil) ; cam up
(cam (zero) :type veq:fvec :read-only nil) ; cam position
(u (zero) :type veq:fvec :read-only nil) ; view plane horizontal
(v (zero) :type veq:fvec :read-only nil) ; view plane vertical
(su (zero) :type veq:fvec :read-only nil) ; u scaled by s
(sv (zero) :type veq:fvec :read-only nil) ; v scaled by s
(xy (veq:f2$point 0f0 0f0) :type veq:fvec :read-only nil) ; view plane offset
(s 1f0 :type veq:ff :read-only nil) ; scale
(raylen 5000f0 :type veq:ff :read-only nil)
(projfx #'3identity :type function :read-only nil)
(dstfx #'3identity :type function :read-only nil)
(rayfx #'3identity :type function :read-only nil))
(veq:fvdef -get-u-v (up* vpn* &optional (s 1f0))
(declare #.*opt* (veq:fvec up* vpn*) (veq:ff s))
(veq:f3let ((up (veq:f3$ up*))
(vpn (veq:f3$ vpn*)))
(unless (< (abs (veq:f3. up vpn)) #.(- 1f0 veq:*eps*))
(error "ortho: gimbal lock.~%up: ~a~%vpn: ~a" up* vpn*))
(veq:f3let ((v (veq:f3norm (veq:f3neg (veq:f3from up vpn
(- (veq:f3. up vpn))))))
(u (veq:f3rot v vpn veq:fpi5)))
(veq:~ u v (veq:f3scale u s) (veq:f3scale v s)))))
(veq:fvdef -look (cam look)
(declare #.*opt* (veq:fvec cam look))
(veq:f3$point (veq:f3norm (veq:f3- (veq:f3$ cam) (veq:f3$ look)))))
(veq:fvdef make-dstfx (proj)
(declare #.*opt*)
"distance from pt to camera plane with current parameters"
(veq:f3let ((cam (veq:f3$ (ortho-cam proj)))
(vpn (veq:f3$ (ortho-vpn proj))))
(lambda ((:va 3 pt)) (declare (veq:ff pt))
(weird:mvb (hit d) (veq:f3planex vpn cam pt (veq:f3+ pt vpn))
(declare (boolean hit) (veq:ff d))
(if hit d 0f0)))))
(veq:fvdef make-projfx (proj)
(declare #.*opt*)
"function to project pt into 2d with current parameters"
(veq:f3let ((su (veq:f3$ (ortho-su proj)))
(sv (veq:f3$ (ortho-sv proj)))
(cam (veq:f3$ (ortho-cam proj))))
(weird:mvb (x y) (veq:f2$ (ortho-xy proj))
(declare (veq:ff x y))
(lambda ((:va 3 pt))
(declare #.*opt* (veq:ff pt))
(veq:f3let ((pt* (veq:f3- pt cam)))
(veq:f2 (+ x (veq:f3. su pt*)) (+ y (veq:f3. sv pt*))))))))
(veq:fvdef make-rayfx (proj)
(declare #.*opt* (ortho proj))
"cast a ray in direction -vpn from pt"
(veq:f3let ((dir (veq:f3scale (veq:f3neg (veq:f3$ (ortho-vpn proj)))
(ortho-raylen proj))))
(lambda ((:va 3 pt))
(declare #.*opt* (veq:ff pt))
(veq:~ pt (veq:f3+ pt dir)))))
(veq:fvdef make (&key (up (veq:f3$point 0f0 0f0 1f0))
(cam (veq:f3$point 1000f0 1000f0 1000f0))
(xy (veq:f2$point 500f0 500f0))
(s 1f0) vpn look (raylen 5000f0))
(declare (veq:fvec up cam xy) (veq:ff s raylen))
"
make projection.
default up is (0 0 1)
default cam is (1000 1000 1000)
if look and vpn are unset, the camera will look at the origin.
default scale is 1
default xy is (0 0)
"
(assert (not (and vpn look)) (vpn look)
"make: can only use (or vpn look)." vpn look)
(let* ((look (if look look (veq:f3$point 0f0 0f0 0f0)))
(vpn* (if vpn vpn (-look cam look))))
(weird:mvb ((:va 3 u v su sv)) (-get-u-v up vpn* s)
(declare (veq:ff u v su sv))
(let ((res (make-ortho :vpn vpn* :up up :cam cam
:s s :xy xy :raylen raylen
:u (veq:f3$point u)
:v (veq:f3$point v)
:su (veq:f3$point su)
:sv (veq:f3$point sv))))
(setf (ortho-dstfx res) (make-dstfx res)
(ortho-projfx res) (make-projfx res)
(ortho-rayfx res) (make-rayfx res))
res))))
(veq:fvdef update (proj &key s xy up cam vpn look)
"
update projection parameters.
use vpn to set view plane normal directly, or look to set view plane normal
relative to camera.
ensures that internal state is updated appropriately.
"
(declare #.*opt* (ortho proj))
(assert (not (and vpn look)) (vpn look)
"update: can only use (or vpn look)." vpn look)
(when cam (setf (ortho-cam proj) cam))
(when up (setf (ortho-up proj) up))
(when vpn (setf (ortho-vpn proj) vpn))
(when look (setf (ortho-vpn proj) (-look (ortho-cam proj) look)))
(when s (setf (ortho-s proj) (the veq:ff s)))
(when xy (setf (ortho-xy proj) xy))
; TODO: there appears to be a bug where u,v is not updated if cam is changed??
(when (or cam s up vpn look)
(weird:mvb ((:va 3 u v su sv))
(-get-u-v (ortho-up proj) (ortho-vpn proj) (ortho-s proj))
(declare (veq:ff u v su sv))
(setf (veq:3$ (ortho-u proj)) (list u)
(veq:3$ (ortho-v proj)) (list v)
(veq:3$ (ortho-su proj)) (list su)
(veq:3$ (ortho-sv proj)) (list sv))))
(setf (ortho-dstfx proj) (make-dstfx proj)
(ortho-projfx proj) (make-projfx proj)
(ortho-rayfx proj) (make-rayfx proj))
proj)
(veq:fvdef around (c axis val &key (look (veq:f3$point (veq:f3rep 0f0))))
(declare (ortho c) (keyword axis) (veq:ff val) (veq:fvec look))
(unless (> (abs val) 0) (return-from around nil))
(macrolet ((_ (&rest rest) `(veq:fvprogn (veq:f_ (veq:lst ,@rest))))
(rot (a b) `(veq:fvprogn (veq:f3rots (veq:f3$s ortho- c ,a ,b val) 0f0 0f0 0f0))))
(case axis
(:pitch (veq:f3let ((pos (rot :cam :u))
(up (veq:f3norm (rot :up :u)))
(vpn (veq:f3norm (veq:f3- pos (veq:f3$ look)))))
(update c :cam (_ pos) :vpn (_ vpn) :up (_ up))))
(:yaw (veq:f3let ((pos (rot :cam :v))
(up (veq:f3norm (rot :up :v)))
(vpn (veq:f3norm (veq:f3- pos (veq:f3$ look)))))
(update c :cam (_ pos) :vpn (_ vpn) :up (_ up))))
(:roll (update c :up (veq:f3$point
(veq:f3rot (veq:f3$s ortho- c :up :vpn val))))))))
(veq:fvdef* project (proj (:va 3 pt))
(declare #.*opt* (ortho proj) (veq:ff pt))
"project single point. returns (values x y d)"
(veq:~ (funcall (ortho-projfx proj) pt)
(funcall (ortho-dstfx proj) pt)))
(veq:vdef project* (proj path)
(declare #.*opt* (ortho proj) (veq:fvec path))
"project a path #(x1 y1 z1 x2 y2 z2 ...).
returns projected path and distances: (values #(px1 py1 px2 py2 ...)
#(d1 d2 ...)) "
(with-struct (ortho- projfx dstfx) proj
(declare (function projfx dstfx))
(veq:fwith-arrays (:n (veq:3$num path) :itr k
:arr ((path 3 path) (p 2) (d 1))
:fxs ((proj ((:va 3 x)) (declare #.*opt* (veq:ff x))
(funcall projfx x))
(dst ((:va 3 x)) (declare #.*opt* (veq:ff x))
(funcall dstfx x)))
:exs ((p k (proj path))
(d k (dst path))))
(values p d))))
(defun export-data (p)
(declare (ortho p))
"export the neccessary values to recreate ortho"
(weird:with-struct (ortho- vpn cam up s xy raylen) p
`((:vpn . ,vpn) (:cam . ,cam) (:up . ,up)
(:s . ,s) (:xy . ,xy) (:raylen . ,raylen))))
(defun import-data (p)
(declare (list p))
"recreate proj from an a list exported by ortho:export-data"
(labels ((as (i a) (cdr (assoc i a)))
(as-float (i a) (veq:ff (as i a)))
(as-arr (i a) (veq:f_ (coerce (as i a) 'list))))
(ortho:make :cam (as-arr :cam p) :vpn (as-arr :vpn p)
:up (as-arr :up p) :xy (as-arr :xy p)
:s (as-float :s p) :raylen (as-float :raylen p))))
| null | https://raw.githubusercontent.com/inconvergent/weird/106d154ec2cd0e4ec977c3672ba717d6305c1056/src/draw/ortho.lisp | lisp | cam up
cam position
view plane horizontal
view plane vertical
u scaled by s
v scaled by s
view plane offset
scale
TODO: there appears to be a bug where u,v is not updated if cam is changed?? |
(in-package :ortho)
"
Simple orthographic projection with camera position (cam), view vector (vpn)
view plane offset (xy) and scaling (s).
"
(declaim (inline 3identity))
(veq:fvdef 3identity ((:va 3 x)) (values x))
(declaim (inline zero))
(veq:fvdef zero () (veq:f3$point 0f0 0f0 0f0))
(defstruct (ortho)
away from dop
(raylen 5000f0 :type veq:ff :read-only nil)
(projfx #'3identity :type function :read-only nil)
(dstfx #'3identity :type function :read-only nil)
(rayfx #'3identity :type function :read-only nil))
(veq:fvdef -get-u-v (up* vpn* &optional (s 1f0))
(declare #.*opt* (veq:fvec up* vpn*) (veq:ff s))
(veq:f3let ((up (veq:f3$ up*))
(vpn (veq:f3$ vpn*)))
(unless (< (abs (veq:f3. up vpn)) #.(- 1f0 veq:*eps*))
(error "ortho: gimbal lock.~%up: ~a~%vpn: ~a" up* vpn*))
(veq:f3let ((v (veq:f3norm (veq:f3neg (veq:f3from up vpn
(- (veq:f3. up vpn))))))
(u (veq:f3rot v vpn veq:fpi5)))
(veq:~ u v (veq:f3scale u s) (veq:f3scale v s)))))
(veq:fvdef -look (cam look)
(declare #.*opt* (veq:fvec cam look))
(veq:f3$point (veq:f3norm (veq:f3- (veq:f3$ cam) (veq:f3$ look)))))
(veq:fvdef make-dstfx (proj)
(declare #.*opt*)
"distance from pt to camera plane with current parameters"
(veq:f3let ((cam (veq:f3$ (ortho-cam proj)))
(vpn (veq:f3$ (ortho-vpn proj))))
(lambda ((:va 3 pt)) (declare (veq:ff pt))
(weird:mvb (hit d) (veq:f3planex vpn cam pt (veq:f3+ pt vpn))
(declare (boolean hit) (veq:ff d))
(if hit d 0f0)))))
(veq:fvdef make-projfx (proj)
(declare #.*opt*)
"function to project pt into 2d with current parameters"
(veq:f3let ((su (veq:f3$ (ortho-su proj)))
(sv (veq:f3$ (ortho-sv proj)))
(cam (veq:f3$ (ortho-cam proj))))
(weird:mvb (x y) (veq:f2$ (ortho-xy proj))
(declare (veq:ff x y))
(lambda ((:va 3 pt))
(declare #.*opt* (veq:ff pt))
(veq:f3let ((pt* (veq:f3- pt cam)))
(veq:f2 (+ x (veq:f3. su pt*)) (+ y (veq:f3. sv pt*))))))))
(veq:fvdef make-rayfx (proj)
(declare #.*opt* (ortho proj))
"cast a ray in direction -vpn from pt"
(veq:f3let ((dir (veq:f3scale (veq:f3neg (veq:f3$ (ortho-vpn proj)))
(ortho-raylen proj))))
(lambda ((:va 3 pt))
(declare #.*opt* (veq:ff pt))
(veq:~ pt (veq:f3+ pt dir)))))
(veq:fvdef make (&key (up (veq:f3$point 0f0 0f0 1f0))
(cam (veq:f3$point 1000f0 1000f0 1000f0))
(xy (veq:f2$point 500f0 500f0))
(s 1f0) vpn look (raylen 5000f0))
(declare (veq:fvec up cam xy) (veq:ff s raylen))
"
make projection.
default up is (0 0 1)
default cam is (1000 1000 1000)
if look and vpn are unset, the camera will look at the origin.
default scale is 1
default xy is (0 0)
"
(assert (not (and vpn look)) (vpn look)
"make: can only use (or vpn look)." vpn look)
(let* ((look (if look look (veq:f3$point 0f0 0f0 0f0)))
(vpn* (if vpn vpn (-look cam look))))
(weird:mvb ((:va 3 u v su sv)) (-get-u-v up vpn* s)
(declare (veq:ff u v su sv))
(let ((res (make-ortho :vpn vpn* :up up :cam cam
:s s :xy xy :raylen raylen
:u (veq:f3$point u)
:v (veq:f3$point v)
:su (veq:f3$point su)
:sv (veq:f3$point sv))))
(setf (ortho-dstfx res) (make-dstfx res)
(ortho-projfx res) (make-projfx res)
(ortho-rayfx res) (make-rayfx res))
res))))
(veq:fvdef update (proj &key s xy up cam vpn look)
"
update projection parameters.
use vpn to set view plane normal directly, or look to set view plane normal
relative to camera.
ensures that internal state is updated appropriately.
"
(declare #.*opt* (ortho proj))
(assert (not (and vpn look)) (vpn look)
"update: can only use (or vpn look)." vpn look)
(when cam (setf (ortho-cam proj) cam))
(when up (setf (ortho-up proj) up))
(when vpn (setf (ortho-vpn proj) vpn))
(when look (setf (ortho-vpn proj) (-look (ortho-cam proj) look)))
(when s (setf (ortho-s proj) (the veq:ff s)))
(when xy (setf (ortho-xy proj) xy))
(when (or cam s up vpn look)
(weird:mvb ((:va 3 u v su sv))
(-get-u-v (ortho-up proj) (ortho-vpn proj) (ortho-s proj))
(declare (veq:ff u v su sv))
(setf (veq:3$ (ortho-u proj)) (list u)
(veq:3$ (ortho-v proj)) (list v)
(veq:3$ (ortho-su proj)) (list su)
(veq:3$ (ortho-sv proj)) (list sv))))
(setf (ortho-dstfx proj) (make-dstfx proj)
(ortho-projfx proj) (make-projfx proj)
(ortho-rayfx proj) (make-rayfx proj))
proj)
(veq:fvdef around (c axis val &key (look (veq:f3$point (veq:f3rep 0f0))))
(declare (ortho c) (keyword axis) (veq:ff val) (veq:fvec look))
(unless (> (abs val) 0) (return-from around nil))
(macrolet ((_ (&rest rest) `(veq:fvprogn (veq:f_ (veq:lst ,@rest))))
(rot (a b) `(veq:fvprogn (veq:f3rots (veq:f3$s ortho- c ,a ,b val) 0f0 0f0 0f0))))
(case axis
(:pitch (veq:f3let ((pos (rot :cam :u))
(up (veq:f3norm (rot :up :u)))
(vpn (veq:f3norm (veq:f3- pos (veq:f3$ look)))))
(update c :cam (_ pos) :vpn (_ vpn) :up (_ up))))
(:yaw (veq:f3let ((pos (rot :cam :v))
(up (veq:f3norm (rot :up :v)))
(vpn (veq:f3norm (veq:f3- pos (veq:f3$ look)))))
(update c :cam (_ pos) :vpn (_ vpn) :up (_ up))))
(:roll (update c :up (veq:f3$point
(veq:f3rot (veq:f3$s ortho- c :up :vpn val))))))))
(veq:fvdef* project (proj (:va 3 pt))
(declare #.*opt* (ortho proj) (veq:ff pt))
"project single point. returns (values x y d)"
(veq:~ (funcall (ortho-projfx proj) pt)
(funcall (ortho-dstfx proj) pt)))
(veq:vdef project* (proj path)
(declare #.*opt* (ortho proj) (veq:fvec path))
"project a path #(x1 y1 z1 x2 y2 z2 ...).
returns projected path and distances: (values #(px1 py1 px2 py2 ...)
#(d1 d2 ...)) "
(with-struct (ortho- projfx dstfx) proj
(declare (function projfx dstfx))
(veq:fwith-arrays (:n (veq:3$num path) :itr k
:arr ((path 3 path) (p 2) (d 1))
:fxs ((proj ((:va 3 x)) (declare #.*opt* (veq:ff x))
(funcall projfx x))
(dst ((:va 3 x)) (declare #.*opt* (veq:ff x))
(funcall dstfx x)))
:exs ((p k (proj path))
(d k (dst path))))
(values p d))))
(defun export-data (p)
(declare (ortho p))
"export the neccessary values to recreate ortho"
(weird:with-struct (ortho- vpn cam up s xy raylen) p
`((:vpn . ,vpn) (:cam . ,cam) (:up . ,up)
(:s . ,s) (:xy . ,xy) (:raylen . ,raylen))))
(defun import-data (p)
(declare (list p))
"recreate proj from an a list exported by ortho:export-data"
(labels ((as (i a) (cdr (assoc i a)))
(as-float (i a) (veq:ff (as i a)))
(as-arr (i a) (veq:f_ (coerce (as i a) 'list))))
(ortho:make :cam (as-arr :cam p) :vpn (as-arr :vpn p)
:up (as-arr :up p) :xy (as-arr :xy p)
:s (as-float :s p) :raylen (as-float :raylen p))))
|
46d57b4a4a8ca2d409c1969402900661961554e356978c44f3402d5f08e39239 | odis-labs/options | Options.ml |
type nonrec 'a option = 'a option =
| None
| Some of 'a
module Option = struct
type nonrec 'a t = 'a option =
| None
| Some of 'a
exception No_value
let case ~some ~none self =
match self with
| Some x -> some x
| None -> none ()
module Prelude = struct
let some x = Some x
let none = None
let is_some = function Some _ -> true | None -> false
let is_none = function Some _ -> false | None -> true
let (or) self default =
match self with
| Some x -> x
| None -> default
let or_else default self =
match self with
| Some x -> x
| None -> default ()
let if_some f t =
match t with
| None -> ()
| Some x -> f x
let if_none f t =
match t with
| None -> f ()
| Some _ -> ()
end
include Prelude
let is_empty = is_none
let catch f =
try
Some (f ())
with _ -> None
let to_list self =
match self with
| Some x -> [x]
| None -> []
let to_result ~error self =
match self with
| Some x -> Ok x
| None -> Error error
let to_bool self =
match self with
| Some _ -> true
| None -> false
let hash item_hash self =
match self with
| None -> 42
| Some x -> Hashtbl.seeded_hash 43 (item_hash x)
(* let dump pp1 fmt self = *)
(* match self with *)
(* | None -> *)
(* Format.pp_print_string fmt "None" *)
(* | Some x -> *)
(* Format.pp_print_string fmt "(Some "; *)
(* (pp1 fmt) x; *)
(* Format.pp_print_string fmt ")" *)
let equal eq_a t1 t2 =
match t1, t2 with
| None, None -> true
| Some a1, Some a2 -> eq_a a1 a2
| _ -> false
let compare cmp_a t1 t2 =
match t1, t2 with
| None, None -> `Equal
| None, Some _ -> `Less
| Some _, None -> `Greater
| Some a1, Some a2 -> cmp_a a1 a2
module Compat = struct
let compare cmp_a t1 t2 =
match t1, t2 with
| None, None -> 0
| None, Some _ -> -1
| Some _, None -> 1
| Some a1, Some a2 -> cmp_a a1 a2
end
(* Unsafe *)
let force self =
match self with
| Some x -> x
| None -> raise No_value
let or_fail message self =
match self with
| Some x -> x
| None -> failwith message
Monad
let return x = Some x
let bind f self =
match self with
| Some x -> f x
| None -> None
let map f self =
match self with
| Some x -> Some (f x)
| None -> None
let (<@>) = map
end
include Option.Prelude
| null | https://raw.githubusercontent.com/odis-labs/options/5b1165d99aba112d550ddc3133a8eb1d174441ec/src/Options.ml | ocaml | let dump pp1 fmt self =
match self with
| None ->
Format.pp_print_string fmt "None"
| Some x ->
Format.pp_print_string fmt "(Some ";
(pp1 fmt) x;
Format.pp_print_string fmt ")"
Unsafe |
type nonrec 'a option = 'a option =
| None
| Some of 'a
module Option = struct
type nonrec 'a t = 'a option =
| None
| Some of 'a
exception No_value
let case ~some ~none self =
match self with
| Some x -> some x
| None -> none ()
module Prelude = struct
let some x = Some x
let none = None
let is_some = function Some _ -> true | None -> false
let is_none = function Some _ -> false | None -> true
let (or) self default =
match self with
| Some x -> x
| None -> default
let or_else default self =
match self with
| Some x -> x
| None -> default ()
let if_some f t =
match t with
| None -> ()
| Some x -> f x
let if_none f t =
match t with
| None -> f ()
| Some _ -> ()
end
include Prelude
let is_empty = is_none
let catch f =
try
Some (f ())
with _ -> None
let to_list self =
match self with
| Some x -> [x]
| None -> []
let to_result ~error self =
match self with
| Some x -> Ok x
| None -> Error error
let to_bool self =
match self with
| Some _ -> true
| None -> false
let hash item_hash self =
match self with
| None -> 42
| Some x -> Hashtbl.seeded_hash 43 (item_hash x)
let equal eq_a t1 t2 =
match t1, t2 with
| None, None -> true
| Some a1, Some a2 -> eq_a a1 a2
| _ -> false
let compare cmp_a t1 t2 =
match t1, t2 with
| None, None -> `Equal
| None, Some _ -> `Less
| Some _, None -> `Greater
| Some a1, Some a2 -> cmp_a a1 a2
module Compat = struct
let compare cmp_a t1 t2 =
match t1, t2 with
| None, None -> 0
| None, Some _ -> -1
| Some _, None -> 1
| Some a1, Some a2 -> cmp_a a1 a2
end
let force self =
match self with
| Some x -> x
| None -> raise No_value
let or_fail message self =
match self with
| Some x -> x
| None -> failwith message
Monad
let return x = Some x
let bind f self =
match self with
| Some x -> f x
| None -> None
let map f self =
match self with
| Some x -> Some (f x)
| None -> None
let (<@>) = map
end
include Option.Prelude
|
be534ecae601264b81827b97a8808b6f5fbb634ba21057a9dc9418c62a85c392 | tweag/smtlib-backends | EdgeCases.hs | {-# LANGUAGE OverloadedStrings #-}
module EdgeCases (edgeCases) where
import Data.ByteString.Builder (Builder)
import SMTLIB.Backends as SMT
import qualified SMTLIB.Backends.Z3 as Z3
import Test.Tasty
import Test.Tasty.HUnit
edgeCases :: [TestTree]
edgeCases =
[ testCase "Sending an empty command" emptyCommand,
testCase "Sending a command expecting no response" commandNoResponse
]
-- | Upon processing an empty command, the backend will respond with an empty output.
emptyCommand :: IO ()
emptyCommand = checkEmptyResponse ""
-- | Upon processing a command producing no output, the backend will respond
-- with an empty output.
commandNoResponse :: IO ()
commandNoResponse = checkEmptyResponse "(set-option :print-success false)"
checkEmptyResponse :: Builder -> IO ()
checkEmptyResponse cmd = Z3.with Z3.defaultConfig $ \handle -> do
let backend = Z3.toBackend handle
response <- SMT.send backend cmd
assertEqual "expected no response" "" response
| null | https://raw.githubusercontent.com/tweag/smtlib-backends/366d2f404af52135273c45b6a0d7d6d8fe4ec974/smtlib-backends-z3/tests/EdgeCases.hs | haskell | # LANGUAGE OverloadedStrings #
| Upon processing an empty command, the backend will respond with an empty output.
| Upon processing a command producing no output, the backend will respond
with an empty output. |
module EdgeCases (edgeCases) where
import Data.ByteString.Builder (Builder)
import SMTLIB.Backends as SMT
import qualified SMTLIB.Backends.Z3 as Z3
import Test.Tasty
import Test.Tasty.HUnit
edgeCases :: [TestTree]
edgeCases =
[ testCase "Sending an empty command" emptyCommand,
testCase "Sending a command expecting no response" commandNoResponse
]
emptyCommand :: IO ()
emptyCommand = checkEmptyResponse ""
commandNoResponse :: IO ()
commandNoResponse = checkEmptyResponse "(set-option :print-success false)"
checkEmptyResponse :: Builder -> IO ()
checkEmptyResponse cmd = Z3.with Z3.defaultConfig $ \handle -> do
let backend = Z3.toBackend handle
response <- SMT.send backend cmd
assertEqual "expected no response" "" response
|
87fa78a67ca59a5dfd6a7b1c5aacc7039112aeff8d864597a14fefc755ae7174 | conal/Fran | SoundB.hs | -- "Sound behaviors"
module SoundB where
import qualified HSpriteLib
import BaseTypes (Time)
import Behavior
import Event
import GBehavior
data SoundB = SilentS
| BufferS (HSpriteLib.HDSBuffer) Bool -- buffer, whether repeats
| MixS SoundB SoundB
scale ( only < 1 , sorry ! )
| PanS RealB SoundB -- units?, combines?
| PitchS RealB SoundB -- multiplies
-- | ImageS ImageB -- listen to an image
| UntilS SoundB (Event SoundB)
timeTransform on SoundB
deriving Show
-- Primitives
silence :: SoundB
silence = SilentS
bufferSound :: HSpriteLib.HDSBuffer -> Bool -> SoundB
bufferSound = BufferS
mix :: SoundB -> SoundB -> SoundB
mix = MixS
-- multiplies (intensity, not dB)
volume :: RealB -> SoundB -> SoundB
volume = VolumeS
-- multiplies
pitch :: RealB -> SoundB -> SoundB
pitch = PitchS
-- In dB, and so combines additively. What's best??
pan :: RealB -> SoundB -> SoundB
pan = PanS
instance GBehavior SoundB where
untilB = UntilS
afterTimes = afterTimesS
timeTransform = TimeTransS
condBUnOpt c snd snd' =
-- tweak volume's and mix
volume v snd `mix` volume v' snd'
where
v = ifB c 1 0
v' = 1 - v
afterTimesS :: SoundB -> [Time] -> [SoundB]
s@SilentS `afterTimesS` _ = repeat s
s@(BufferS _ _) `afterTimesS` _ = repeat s
(snd `MixS` snd') `afterTimesS` ts =
zipWith MixS (snd `afterTimesS` ts) (snd' `afterTimesS` ts)
VolumeS v snd `afterTimesS` ts =
zipWith VolumeS (v `afterTimes` ts) (snd `afterTimesS` ts)
PitchS p snd `afterTimesS` ts =
zipWith PitchS (p `afterTimes` ts) (snd `afterTimesS` ts)
PanS p snd `afterTimesS` ts =
zipWith PanS (p `afterTimes` ts) (snd `afterTimesS` ts)
-- ## This guy is wrong!!
(snd `UntilS` e) `afterTimesS` ts =
( snd ` afterTimesS ` t ) ` UntilS ` ( e = = > ( ` afterTimesS ` ts ) )
error "No afterTimes yet on SoundB untilB, sorry."
| null | https://raw.githubusercontent.com/conal/Fran/a113693cfab23f9ac9704cfee9c610c5edc13d9d/src/SoundB.hs | haskell | "Sound behaviors"
buffer, whether repeats
units?, combines?
multiplies
| ImageS ImageB -- listen to an image
Primitives
multiplies (intensity, not dB)
multiplies
In dB, and so combines additively. What's best??
tweak volume's and mix
## This guy is wrong!!
|
module SoundB where
import qualified HSpriteLib
import BaseTypes (Time)
import Behavior
import Event
import GBehavior
data SoundB = SilentS
| MixS SoundB SoundB
scale ( only < 1 , sorry ! )
| UntilS SoundB (Event SoundB)
timeTransform on SoundB
deriving Show
silence :: SoundB
silence = SilentS
bufferSound :: HSpriteLib.HDSBuffer -> Bool -> SoundB
bufferSound = BufferS
mix :: SoundB -> SoundB -> SoundB
mix = MixS
volume :: RealB -> SoundB -> SoundB
volume = VolumeS
pitch :: RealB -> SoundB -> SoundB
pitch = PitchS
pan :: RealB -> SoundB -> SoundB
pan = PanS
instance GBehavior SoundB where
untilB = UntilS
afterTimes = afterTimesS
timeTransform = TimeTransS
condBUnOpt c snd snd' =
volume v snd `mix` volume v' snd'
where
v = ifB c 1 0
v' = 1 - v
afterTimesS :: SoundB -> [Time] -> [SoundB]
s@SilentS `afterTimesS` _ = repeat s
s@(BufferS _ _) `afterTimesS` _ = repeat s
(snd `MixS` snd') `afterTimesS` ts =
zipWith MixS (snd `afterTimesS` ts) (snd' `afterTimesS` ts)
VolumeS v snd `afterTimesS` ts =
zipWith VolumeS (v `afterTimes` ts) (snd `afterTimesS` ts)
PitchS p snd `afterTimesS` ts =
zipWith PitchS (p `afterTimes` ts) (snd `afterTimesS` ts)
PanS p snd `afterTimesS` ts =
zipWith PanS (p `afterTimes` ts) (snd `afterTimesS` ts)
(snd `UntilS` e) `afterTimesS` ts =
( snd ` afterTimesS ` t ) ` UntilS ` ( e = = > ( ` afterTimesS ` ts ) )
error "No afterTimes yet on SoundB untilB, sorry."
|
18d5cb86ef9a12beed5d8cf03dc75077bcba3a634f3f1371078fa4b63edd45e6 | AshleyYakeley/Truth | Model.hs | module Changes.Core.Model
( module I
) where
import Changes.Core.Model.AutoClose as I
import Changes.Core.Model.Cache as I
import Changes.Core.Model.DeferActionT as I
import Changes.Core.Model.EditContext as I
import Changes.Core.Model.MemoryCell as I
import Changes.Core.Model.Model as I
import Changes.Core.Model.Premodel as I
import Changes.Core.Model.Reference as I
import Changes.Core.Model.ReferenceEdit as I
import Changes.Core.Model.Savable as I
import Changes.Core.Model.Tuple as I
import Changes.Core.Model.Undo as I
import Changes.Core.Model.WModel as I
| null | https://raw.githubusercontent.com/AshleyYakeley/Truth/32d5f7ac9fe38331bd137e722b7780ca45a04ca9/Changes/changes-core/lib/Changes/Core/Model.hs | haskell | module Changes.Core.Model
( module I
) where
import Changes.Core.Model.AutoClose as I
import Changes.Core.Model.Cache as I
import Changes.Core.Model.DeferActionT as I
import Changes.Core.Model.EditContext as I
import Changes.Core.Model.MemoryCell as I
import Changes.Core.Model.Model as I
import Changes.Core.Model.Premodel as I
import Changes.Core.Model.Reference as I
import Changes.Core.Model.ReferenceEdit as I
import Changes.Core.Model.Savable as I
import Changes.Core.Model.Tuple as I
import Changes.Core.Model.Undo as I
import Changes.Core.Model.WModel as I
|
|
5cd67ec020cd6059dae2bed0796db9050286b2cfb129f0bce1ca3a92c4c41c90 | FranklinChen/hugs98-plus-Sep2006 | Convolution.hs | --------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.PixelRectangles.Convolution
Copyright : ( c ) 2002 - 2005
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
This module corresponds to a part of section 3.6.1 ( Pixel Storage Modes ) of
the OpenGL 1.5 specs .
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.PixelRectangles.Convolution (
ConvolutionTarget(..), convolution,
convolutionFilter1D, getConvolutionFilter1D,
convolutionFilter2D, getConvolutionFilter2D,
separableFilter2D, getSeparableFilter2D,
copyConvolutionFilter1D, copyConvolutionFilter2D,
convolutionWidth, convolutionHeight,
maxConvolutionWidth, maxConvolutionHeight,
ConvolutionBorderMode(..), convolutionBorderMode,
convolutionFilterScale, convolutionFilterBias,
) where
import Foreign.Marshal.Alloc ( alloca )
import Foreign.Marshal.Utils ( with )
import Foreign.Ptr ( Ptr, nullPtr )
import Foreign.Storable ( Storable(..) )
import Graphics.Rendering.OpenGL.GL.Capability (
EnableCap(CapConvolution1D, CapConvolution2D,CapSeparable2D),
makeCapability )
import Graphics.Rendering.OpenGL.GL.BasicTypes (
GLenum, GLint, GLsizei, GLfloat, Capability )
import Graphics.Rendering.OpenGL.GL.CoordTrans ( Position(..), Size(..) )
import Graphics.Rendering.OpenGL.GL.Extensions (
FunPtr, unsafePerformIO, Invoker, getProcAddress )
import Graphics.Rendering.OpenGL.GL.PeekPoke ( peek1 )
import Graphics.Rendering.OpenGL.GL.PixelRectangles.ColorTable (
PixelInternalFormat )
import Graphics.Rendering.OpenGL.GL.PixelRectangles.Rasterization (
PixelData(..) )
import Graphics.Rendering.OpenGL.GL.PixelData ( withPixelData )
import Graphics.Rendering.OpenGL.GL.Texturing.PixelInternalFormat (
marshalPixelInternalFormat' )
import Graphics.Rendering.OpenGL.GL.StateVar (
GettableStateVar, makeGettableStateVar, StateVar, makeStateVar )
import Graphics.Rendering.OpenGL.GL.VertexSpec ( Color4(..) )
import Graphics.Rendering.OpenGL.GLU.ErrorsInternal (
recordInvalidValue )
--------------------------------------------------------------------------------
#include "HsOpenGLExt.h"
--------------------------------------------------------------------------------
data ConvolutionTarget =
Convolution1D
| Convolution2D
| Separable2D
deriving ( Eq, Ord, Show )
marshalConvolutionTarget :: ConvolutionTarget -> GLenum
marshalConvolutionTarget x = case x of
Convolution1D -> 0x8010
Convolution2D -> 0x8011
Separable2D -> 0x8012
convolutionTargetToEnableCap :: ConvolutionTarget -> EnableCap
convolutionTargetToEnableCap x = case x of
Convolution1D -> CapConvolution1D
Convolution2D -> CapConvolution2D
Separable2D -> CapSeparable2D
--------------------------------------------------------------------------------
convolution :: ConvolutionTarget -> StateVar Capability
convolution = makeCapability . convolutionTargetToEnableCap
--------------------------------------------------------------------------------
convolutionFilter1D :: PixelInternalFormat -> GLsizei -> PixelData a -> IO ()
convolutionFilter1D int w pd =
withPixelData pd $
glConvolutionFilter1D
(marshalConvolutionTarget Convolution1D)
(marshalPixelInternalFormat' int) w
EXTENSION_ENTRY("GL_ARB_imaging",glConvolutionFilter1D,GLenum -> GLenum -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ())
--------------------------------------------------------------------------------
getConvolutionFilter1D :: PixelData a -> IO ()
getConvolutionFilter1D = getConvolutionFilter Convolution1D
getConvolutionFilter :: ConvolutionTarget -> PixelData a -> IO ()
getConvolutionFilter t pd =
withPixelData pd $ glGetConvolutionFilter (marshalConvolutionTarget t)
EXTENSION_ENTRY("GL_ARB_imaging",glGetConvolutionFilter,GLenum -> GLenum -> GLenum -> Ptr a -> IO ())
--------------------------------------------------------------------------------
convolutionFilter2D :: PixelInternalFormat -> Size -> PixelData a -> IO ()
convolutionFilter2D int (Size w h) pd =
withPixelData pd $
glConvolutionFilter2D
(marshalConvolutionTarget Convolution2D)
(marshalPixelInternalFormat' int) w h
EXTENSION_ENTRY("GL_ARB_imaging",glConvolutionFilter2D,GLenum -> GLenum -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ())
--------------------------------------------------------------------------------
getConvolutionFilter2D :: PixelData a -> IO ()
getConvolutionFilter2D = getConvolutionFilter Convolution2D
--------------------------------------------------------------------------------
separableFilter2D ::
PixelInternalFormat -> Size -> PixelData a -> PixelData a -> IO ()
separableFilter2D int (Size w h) pdRow pdCol =
withPixelData pdRow $ \f1 d1 p1 ->
withPixelData pdCol $ \f2 d2 p2 ->
if f1 == f2 && d1 == d2
then glSeparableFilter2D
(marshalConvolutionTarget Separable2D)
(marshalPixelInternalFormat' int) w h f1 d1 p1 p2
else recordInvalidValue
EXTENSION_ENTRY("GL_ARB_imaging",glSeparableFilter2D,GLenum -> GLenum -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> Ptr a -> IO ())
--------------------------------------------------------------------------------
getSeparableFilter2D :: PixelData a -> PixelData a -> IO ()
getSeparableFilter2D pdRow pdCol =
withPixelData pdRow $ \f1 d1 p1 ->
withPixelData pdCol $ \f2 d2 p2 ->
if f1 == f2 && d1 == d2
then glGetSeparableFilter
(marshalConvolutionTarget Separable2D) f1 d1 p1 p2 nullPtr
else recordInvalidValue
EXTENSION_ENTRY("GL_ARB_imaging",glGetSeparableFilter,GLenum -> GLenum -> GLenum -> Ptr a -> Ptr a -> Ptr a -> IO ())
--------------------------------------------------------------------------------
copyConvolutionFilter1D :: PixelInternalFormat -> Position -> GLsizei -> IO ()
copyConvolutionFilter1D int (Position x y) =
glCopyConvolutionFilter1D
(marshalConvolutionTarget Convolution1D) (marshalPixelInternalFormat' int)
x y
EXTENSION_ENTRY("GL_ARB_imaging",glCopyConvolutionFilter1D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> IO ())
--------------------------------------------------------------------------------
copyConvolutionFilter2D :: PixelInternalFormat -> Position -> Size -> IO ()
copyConvolutionFilter2D int (Position x y) (Size w h) =
glCopyConvolutionFilter2D
(marshalConvolutionTarget Convolution2D) (marshalPixelInternalFormat' int)
x y w h
EXTENSION_ENTRY("GL_ARB_imaging",glCopyConvolutionFilter2D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> IO ())
--------------------------------------------------------------------------------
data ConvolutionParameter =
ConvolutionBorderColor
| ConvolutionBorderMode
| ConvolutionFilterScale
| ConvolutionFilterBias
| ConvolutionFormat
| ConvolutionWidth
| ConvolutionHeight
| MaxConvolutionWidth
| MaxConvolutionHeight
deriving ( Eq, Ord, Show )
marshalConvolutionParameter :: ConvolutionParameter -> GLenum
marshalConvolutionParameter x = case x of
ConvolutionBorderColor -> 0x8154
ConvolutionBorderMode -> 0x8013
ConvolutionFilterScale -> 0x8014
ConvolutionFilterBias -> 0x8015
ConvolutionFormat -> 0x8017
ConvolutionWidth -> 0x8018
ConvolutionHeight -> 0x8019
MaxConvolutionWidth -> 0x801a
MaxConvolutionHeight -> 0x801b
--------------------------------------------------------------------------------
convolutionWidth :: ConvolutionTarget -> GettableStateVar GLsizei
convolutionWidth t = convolutionParameteri t ConvolutionWidth
convolutionHeight :: ConvolutionTarget -> GettableStateVar GLsizei
convolutionHeight t = convolutionParameteri t ConvolutionHeight
maxConvolutionWidth :: ConvolutionTarget -> GettableStateVar GLsizei
maxConvolutionWidth t = convolutionParameteri t MaxConvolutionWidth
maxConvolutionHeight :: ConvolutionTarget -> GettableStateVar GLsizei
maxConvolutionHeight t = convolutionParameteri t MaxConvolutionHeight
convolutionParameteri ::
ConvolutionTarget -> ConvolutionParameter -> GettableStateVar GLsizei
convolutionParameteri t p =
makeGettableStateVar (getConvolutionParameteri fromIntegral t p)
getConvolutionParameteri ::
(GLint -> a) -> ConvolutionTarget -> ConvolutionParameter -> IO a
getConvolutionParameteri f t p =
alloca $ \buf -> do
glGetConvolutionParameteriv
(marshalConvolutionTarget t) (marshalConvolutionParameter p) buf
peek1 f buf
EXTENSION_ENTRY("GL_ARB_imaging",glGetConvolutionParameteriv,GLenum -> GLenum -> Ptr GLint -> IO ())
--------------------------------------------------------------------------------
data ConvolutionBorderMode' =
Reduce'
| ConstantBorder'
| ReplicateBorder'
marshalConvolutionBorderMode' :: ConvolutionBorderMode' -> GLint
marshalConvolutionBorderMode' x = case x of
Reduce' -> 0x8016
ConstantBorder' -> 0x8151
ReplicateBorder' -> 0x8153
unmarshalConvolutionBorderMode' :: GLint -> ConvolutionBorderMode'
unmarshalConvolutionBorderMode' x
| x == 0x8016 = Reduce'
| x == 0x8151 = ConstantBorder'
| x == 0x8153 = ReplicateBorder'
| otherwise = error ("unmarshalConvolutionBorderMode': illegal value " ++ show x)
--------------------------------------------------------------------------------
data ConvolutionBorderMode =
Reduce
| ConstantBorder (Color4 GLfloat)
| ReplicateBorder
deriving ( Eq, Ord, Show )
--------------------------------------------------------------------------------
convolutionBorderMode :: ConvolutionTarget -> StateVar ConvolutionBorderMode
convolutionBorderMode t =
makeStateVar (getConvolutionBorderMode t) (setConvolutionBorderMode t)
getConvolutionBorderMode :: ConvolutionTarget -> IO ConvolutionBorderMode
getConvolutionBorderMode t = do
mode <- getConvolutionParameteri
unmarshalConvolutionBorderMode' t ConvolutionBorderMode
case mode of
Reduce' -> return Reduce
ConstantBorder' -> do
c <- getConvolutionParameterC4f t ConvolutionBorderColor
return $ ConstantBorder c
ReplicateBorder' -> return ReplicateBorder
setConvolutionBorderMode :: ConvolutionTarget -> ConvolutionBorderMode -> IO ()
setConvolutionBorderMode t mode = do
let setBM = setConvolutionParameteri
marshalConvolutionBorderMode' t ConvolutionBorderMode
case mode of
Reduce -> setBM Reduce'
ConstantBorder c -> do
setBM ConstantBorder'
convolutionParameterC4f t ConvolutionBorderColor c
ReplicateBorder -> setBM ReplicateBorder'
setConvolutionParameteri ::
(a -> GLint) -> ConvolutionTarget -> ConvolutionParameter -> a -> IO ()
setConvolutionParameteri f t p x =
glConvolutionParameteri
(marshalConvolutionTarget t) (marshalConvolutionParameter p) (f x)
EXTENSION_ENTRY("GL_ARB_imaging",glConvolutionParameteri,GLenum -> GLenum -> GLint -> IO ())
--------------------------------------------------------------------------------
convolutionFilterScale :: ConvolutionTarget -> StateVar (Color4 GLfloat)
convolutionFilterScale = convolutionC4f ConvolutionFilterScale
convolutionFilterBias :: ConvolutionTarget -> StateVar (Color4 GLfloat)
convolutionFilterBias = convolutionC4f ConvolutionFilterBias
convolutionC4f ::
ConvolutionParameter -> ConvolutionTarget -> StateVar (Color4 GLfloat)
convolutionC4f p t =
makeStateVar (getConvolutionParameterC4f t p) (convolutionParameterC4f t p)
getConvolutionParameterC4f ::
ConvolutionTarget -> ConvolutionParameter -> IO (Color4 GLfloat)
getConvolutionParameterC4f t p =
alloca $ \buf -> do
glGetConvolutionParameterfv
(marshalConvolutionTarget t) (marshalConvolutionParameter p) buf
peek buf
EXTENSION_ENTRY("GL_ARB_imaging",glGetConvolutionParameterfv,GLenum -> GLenum -> Ptr (Color4 GLfloat) -> IO ())
convolutionParameterC4f ::
ConvolutionTarget -> ConvolutionParameter -> Color4 GLfloat -> IO ()
convolutionParameterC4f t p c =
with c $
glConvolutionParameterfv
(marshalConvolutionTarget t) (marshalConvolutionParameter p)
EXTENSION_ENTRY("GL_ARB_imaging",glConvolutionParameterfv,GLenum -> GLenum -> Ptr (Color4 GLfloat) -> IO ())
| null | https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/OpenGL/Graphics/Rendering/OpenGL/GL/PixelRectangles/Convolution.hs | haskell | ------------------------------------------------------------------------------
|
Module : Graphics.Rendering.OpenGL.GL.PixelRectangles.Convolution
License : BSD-style (see the file libraries/OpenGL/LICENSE)
Maintainer :
Stability : provisional
Portability : portable
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | Copyright : ( c ) 2002 - 2005
This module corresponds to a part of section 3.6.1 ( Pixel Storage Modes ) of
the OpenGL 1.5 specs .
module Graphics.Rendering.OpenGL.GL.PixelRectangles.Convolution (
ConvolutionTarget(..), convolution,
convolutionFilter1D, getConvolutionFilter1D,
convolutionFilter2D, getConvolutionFilter2D,
separableFilter2D, getSeparableFilter2D,
copyConvolutionFilter1D, copyConvolutionFilter2D,
convolutionWidth, convolutionHeight,
maxConvolutionWidth, maxConvolutionHeight,
ConvolutionBorderMode(..), convolutionBorderMode,
convolutionFilterScale, convolutionFilterBias,
) where
import Foreign.Marshal.Alloc ( alloca )
import Foreign.Marshal.Utils ( with )
import Foreign.Ptr ( Ptr, nullPtr )
import Foreign.Storable ( Storable(..) )
import Graphics.Rendering.OpenGL.GL.Capability (
EnableCap(CapConvolution1D, CapConvolution2D,CapSeparable2D),
makeCapability )
import Graphics.Rendering.OpenGL.GL.BasicTypes (
GLenum, GLint, GLsizei, GLfloat, Capability )
import Graphics.Rendering.OpenGL.GL.CoordTrans ( Position(..), Size(..) )
import Graphics.Rendering.OpenGL.GL.Extensions (
FunPtr, unsafePerformIO, Invoker, getProcAddress )
import Graphics.Rendering.OpenGL.GL.PeekPoke ( peek1 )
import Graphics.Rendering.OpenGL.GL.PixelRectangles.ColorTable (
PixelInternalFormat )
import Graphics.Rendering.OpenGL.GL.PixelRectangles.Rasterization (
PixelData(..) )
import Graphics.Rendering.OpenGL.GL.PixelData ( withPixelData )
import Graphics.Rendering.OpenGL.GL.Texturing.PixelInternalFormat (
marshalPixelInternalFormat' )
import Graphics.Rendering.OpenGL.GL.StateVar (
GettableStateVar, makeGettableStateVar, StateVar, makeStateVar )
import Graphics.Rendering.OpenGL.GL.VertexSpec ( Color4(..) )
import Graphics.Rendering.OpenGL.GLU.ErrorsInternal (
recordInvalidValue )
#include "HsOpenGLExt.h"
data ConvolutionTarget =
Convolution1D
| Convolution2D
| Separable2D
deriving ( Eq, Ord, Show )
marshalConvolutionTarget :: ConvolutionTarget -> GLenum
marshalConvolutionTarget x = case x of
Convolution1D -> 0x8010
Convolution2D -> 0x8011
Separable2D -> 0x8012
convolutionTargetToEnableCap :: ConvolutionTarget -> EnableCap
convolutionTargetToEnableCap x = case x of
Convolution1D -> CapConvolution1D
Convolution2D -> CapConvolution2D
Separable2D -> CapSeparable2D
convolution :: ConvolutionTarget -> StateVar Capability
convolution = makeCapability . convolutionTargetToEnableCap
convolutionFilter1D :: PixelInternalFormat -> GLsizei -> PixelData a -> IO ()
convolutionFilter1D int w pd =
withPixelData pd $
glConvolutionFilter1D
(marshalConvolutionTarget Convolution1D)
(marshalPixelInternalFormat' int) w
EXTENSION_ENTRY("GL_ARB_imaging",glConvolutionFilter1D,GLenum -> GLenum -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ())
getConvolutionFilter1D :: PixelData a -> IO ()
getConvolutionFilter1D = getConvolutionFilter Convolution1D
getConvolutionFilter :: ConvolutionTarget -> PixelData a -> IO ()
getConvolutionFilter t pd =
withPixelData pd $ glGetConvolutionFilter (marshalConvolutionTarget t)
EXTENSION_ENTRY("GL_ARB_imaging",glGetConvolutionFilter,GLenum -> GLenum -> GLenum -> Ptr a -> IO ())
convolutionFilter2D :: PixelInternalFormat -> Size -> PixelData a -> IO ()
convolutionFilter2D int (Size w h) pd =
withPixelData pd $
glConvolutionFilter2D
(marshalConvolutionTarget Convolution2D)
(marshalPixelInternalFormat' int) w h
EXTENSION_ENTRY("GL_ARB_imaging",glConvolutionFilter2D,GLenum -> GLenum -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ())
getConvolutionFilter2D :: PixelData a -> IO ()
getConvolutionFilter2D = getConvolutionFilter Convolution2D
separableFilter2D ::
PixelInternalFormat -> Size -> PixelData a -> PixelData a -> IO ()
separableFilter2D int (Size w h) pdRow pdCol =
withPixelData pdRow $ \f1 d1 p1 ->
withPixelData pdCol $ \f2 d2 p2 ->
if f1 == f2 && d1 == d2
then glSeparableFilter2D
(marshalConvolutionTarget Separable2D)
(marshalPixelInternalFormat' int) w h f1 d1 p1 p2
else recordInvalidValue
EXTENSION_ENTRY("GL_ARB_imaging",glSeparableFilter2D,GLenum -> GLenum -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> Ptr a -> IO ())
getSeparableFilter2D :: PixelData a -> PixelData a -> IO ()
getSeparableFilter2D pdRow pdCol =
withPixelData pdRow $ \f1 d1 p1 ->
withPixelData pdCol $ \f2 d2 p2 ->
if f1 == f2 && d1 == d2
then glGetSeparableFilter
(marshalConvolutionTarget Separable2D) f1 d1 p1 p2 nullPtr
else recordInvalidValue
EXTENSION_ENTRY("GL_ARB_imaging",glGetSeparableFilter,GLenum -> GLenum -> GLenum -> Ptr a -> Ptr a -> Ptr a -> IO ())
copyConvolutionFilter1D :: PixelInternalFormat -> Position -> GLsizei -> IO ()
copyConvolutionFilter1D int (Position x y) =
glCopyConvolutionFilter1D
(marshalConvolutionTarget Convolution1D) (marshalPixelInternalFormat' int)
x y
EXTENSION_ENTRY("GL_ARB_imaging",glCopyConvolutionFilter1D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> IO ())
copyConvolutionFilter2D :: PixelInternalFormat -> Position -> Size -> IO ()
copyConvolutionFilter2D int (Position x y) (Size w h) =
glCopyConvolutionFilter2D
(marshalConvolutionTarget Convolution2D) (marshalPixelInternalFormat' int)
x y w h
EXTENSION_ENTRY("GL_ARB_imaging",glCopyConvolutionFilter2D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> IO ())
data ConvolutionParameter =
ConvolutionBorderColor
| ConvolutionBorderMode
| ConvolutionFilterScale
| ConvolutionFilterBias
| ConvolutionFormat
| ConvolutionWidth
| ConvolutionHeight
| MaxConvolutionWidth
| MaxConvolutionHeight
deriving ( Eq, Ord, Show )
marshalConvolutionParameter :: ConvolutionParameter -> GLenum
marshalConvolutionParameter x = case x of
ConvolutionBorderColor -> 0x8154
ConvolutionBorderMode -> 0x8013
ConvolutionFilterScale -> 0x8014
ConvolutionFilterBias -> 0x8015
ConvolutionFormat -> 0x8017
ConvolutionWidth -> 0x8018
ConvolutionHeight -> 0x8019
MaxConvolutionWidth -> 0x801a
MaxConvolutionHeight -> 0x801b
convolutionWidth :: ConvolutionTarget -> GettableStateVar GLsizei
convolutionWidth t = convolutionParameteri t ConvolutionWidth
convolutionHeight :: ConvolutionTarget -> GettableStateVar GLsizei
convolutionHeight t = convolutionParameteri t ConvolutionHeight
maxConvolutionWidth :: ConvolutionTarget -> GettableStateVar GLsizei
maxConvolutionWidth t = convolutionParameteri t MaxConvolutionWidth
maxConvolutionHeight :: ConvolutionTarget -> GettableStateVar GLsizei
maxConvolutionHeight t = convolutionParameteri t MaxConvolutionHeight
convolutionParameteri ::
ConvolutionTarget -> ConvolutionParameter -> GettableStateVar GLsizei
convolutionParameteri t p =
makeGettableStateVar (getConvolutionParameteri fromIntegral t p)
getConvolutionParameteri ::
(GLint -> a) -> ConvolutionTarget -> ConvolutionParameter -> IO a
getConvolutionParameteri f t p =
alloca $ \buf -> do
glGetConvolutionParameteriv
(marshalConvolutionTarget t) (marshalConvolutionParameter p) buf
peek1 f buf
EXTENSION_ENTRY("GL_ARB_imaging",glGetConvolutionParameteriv,GLenum -> GLenum -> Ptr GLint -> IO ())
data ConvolutionBorderMode' =
Reduce'
| ConstantBorder'
| ReplicateBorder'
marshalConvolutionBorderMode' :: ConvolutionBorderMode' -> GLint
marshalConvolutionBorderMode' x = case x of
Reduce' -> 0x8016
ConstantBorder' -> 0x8151
ReplicateBorder' -> 0x8153
unmarshalConvolutionBorderMode' :: GLint -> ConvolutionBorderMode'
unmarshalConvolutionBorderMode' x
| x == 0x8016 = Reduce'
| x == 0x8151 = ConstantBorder'
| x == 0x8153 = ReplicateBorder'
| otherwise = error ("unmarshalConvolutionBorderMode': illegal value " ++ show x)
data ConvolutionBorderMode =
Reduce
| ConstantBorder (Color4 GLfloat)
| ReplicateBorder
deriving ( Eq, Ord, Show )
convolutionBorderMode :: ConvolutionTarget -> StateVar ConvolutionBorderMode
convolutionBorderMode t =
makeStateVar (getConvolutionBorderMode t) (setConvolutionBorderMode t)
getConvolutionBorderMode :: ConvolutionTarget -> IO ConvolutionBorderMode
getConvolutionBorderMode t = do
mode <- getConvolutionParameteri
unmarshalConvolutionBorderMode' t ConvolutionBorderMode
case mode of
Reduce' -> return Reduce
ConstantBorder' -> do
c <- getConvolutionParameterC4f t ConvolutionBorderColor
return $ ConstantBorder c
ReplicateBorder' -> return ReplicateBorder
setConvolutionBorderMode :: ConvolutionTarget -> ConvolutionBorderMode -> IO ()
setConvolutionBorderMode t mode = do
let setBM = setConvolutionParameteri
marshalConvolutionBorderMode' t ConvolutionBorderMode
case mode of
Reduce -> setBM Reduce'
ConstantBorder c -> do
setBM ConstantBorder'
convolutionParameterC4f t ConvolutionBorderColor c
ReplicateBorder -> setBM ReplicateBorder'
setConvolutionParameteri ::
(a -> GLint) -> ConvolutionTarget -> ConvolutionParameter -> a -> IO ()
setConvolutionParameteri f t p x =
glConvolutionParameteri
(marshalConvolutionTarget t) (marshalConvolutionParameter p) (f x)
EXTENSION_ENTRY("GL_ARB_imaging",glConvolutionParameteri,GLenum -> GLenum -> GLint -> IO ())
convolutionFilterScale :: ConvolutionTarget -> StateVar (Color4 GLfloat)
convolutionFilterScale = convolutionC4f ConvolutionFilterScale
convolutionFilterBias :: ConvolutionTarget -> StateVar (Color4 GLfloat)
convolutionFilterBias = convolutionC4f ConvolutionFilterBias
convolutionC4f ::
ConvolutionParameter -> ConvolutionTarget -> StateVar (Color4 GLfloat)
convolutionC4f p t =
makeStateVar (getConvolutionParameterC4f t p) (convolutionParameterC4f t p)
getConvolutionParameterC4f ::
ConvolutionTarget -> ConvolutionParameter -> IO (Color4 GLfloat)
getConvolutionParameterC4f t p =
alloca $ \buf -> do
glGetConvolutionParameterfv
(marshalConvolutionTarget t) (marshalConvolutionParameter p) buf
peek buf
EXTENSION_ENTRY("GL_ARB_imaging",glGetConvolutionParameterfv,GLenum -> GLenum -> Ptr (Color4 GLfloat) -> IO ())
convolutionParameterC4f ::
ConvolutionTarget -> ConvolutionParameter -> Color4 GLfloat -> IO ()
convolutionParameterC4f t p c =
with c $
glConvolutionParameterfv
(marshalConvolutionTarget t) (marshalConvolutionParameter p)
EXTENSION_ENTRY("GL_ARB_imaging",glConvolutionParameterfv,GLenum -> GLenum -> Ptr (Color4 GLfloat) -> IO ())
|
cb9929ef854adb55387a3f2d55088e16b54f97196a60c168d85d052c4c46a7b8 | CryptoKami/cryptokami-core | Update.hs | | ' Bi ' instances for various types from cryptokami - sl - update .
# OPTIONS_GHC -F -pgmF autoexporter #
{-# OPTIONS_GHC -Wno-unused-imports #-}
# OPTIONS_GHC -Wno - dodgy - exports #
| null | https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/update/Pos/Binary/Update.hs | haskell | # OPTIONS_GHC -Wno-unused-imports # | | ' Bi ' instances for various types from cryptokami - sl - update .
# OPTIONS_GHC -F -pgmF autoexporter #
# OPTIONS_GHC -Wno - dodgy - exports #
|
660dd1eb670cc621a6619bcc4f20b2a083fd022d9763afad2c95f29a40d887ad | g000001/tagger | lexicon-protocol.lisp | -*- Package : TDB ; Syntax : Common - Lisp ; Mode : Lisp ; Base : 10 -*-
Copyright ( c ) 1992 by Xerox Corporation .
(cl:in-package :tdb)
(eval-when (compile eval load)
(use-package :sv-resource)
(export '(lexicon
lexicon-tags lexicon-classes lexicon-open-class
lexicon-lookup class-order
lexicon-filter ts-lexicon
*the-keyword-package*
*tokenizer-class* re-read-lexicon)))
(defvar *the-keyword-package* (find-package :keyword))
(defclass lexicon ()
((lexicon-open-class :writer (setf lexicon-open-class))))
(defmethod initialize-instance :before ((lexicon lexicon)
&key lexicon-open-class
&allow-other-keys)
(setf (lexicon-open-class lexicon)
(sort (map 'simple-vector #'identity lexicon-open-class) #'string<)))
The Lexicon Protocol
Returns ( 1 ) a vector of stems ( strings ) or a single string if all stems are
the same ; and ( 2 ) a parallel sorted vector of tags ( keywords ) .
;;; All vectors and strings are from resources.
(defgeneric lexicon-lookup (token lexicon))
(defmethod lexicon-lookup (token (lexicon lexicon))
(values (simple-string-copy token) (sv-copy (lexicon-open-class lexicon))))
;;;; Returns a vector of classes. Each class is a sorted vector of tags.
(defgeneric lexicon-classes (lexicon))
(defmethod lexicon-classes ((lexicon lexicon))
(with-slots (lexicon-open-class) lexicon
(vector lexicon-open-class)))
;;; Returns a vector of open class tags (from the vector resource).
(defgeneric lexicon-open-class (lexicon))
(defmethod lexicon-open-class ((lexicon lexicon))
(with-slots (lexicon-open-class) lexicon
(sv-copy lexicon-open-class)))
;;;; Returns a vector of tags.
(defun lexicon-tags (lexicon)
(let* ((classes (lexicon-classes lexicon))
(table (make-hash-table :size (length classes))))
(dotimes (i (length classes))
(let ((class (svref classes i)))
(dotimes (j (length class))
(setf (gethash (svref class j) table) t))))
(let ((result (make-array (hash-table-count table)))
(index -1))
(maphash #'(lambda (tag ignore)
(declare (ignore ignore))
(setf (svref result (incf index)) tag))
table)
result)))
(defun class-order (class1 class2)
(let ((l1 (length class1))
(l2 (length class2)))
(if (= l1 l2)
(dotimes (i l1 :equal)
(when (string/= (svref class1 i) (svref class2 i))
(return (string< (svref class1 i) (svref class2 i)))))
(< l1 l2))))
;;;; LEXICON-FILTER: splices a lexicon into a token stream. The tokenizer
;;;; class :WORD is looked up in the lexicon, others are passed on. Makes the
;;;; TS masquerade as a lexicon. Most clients access the lexicon through this.
(defclass lexicon-filter (token-filter)
((lexicon :accessor ts-lexicon :initarg :lexicon)))
(defmethod lexicon-classes ((ts lexicon-filter))
(remove-duplicates
(concatenate 'simple-vector
(lexicon-classes (ts-lexicon ts))
(map 'simple-vector #'vector
(remove :word (funcall (get-qua ts-types ts lexicon-filter) ts))))
:test #'equalp))
(defmethod lexicon-lookup (token (ts lexicon-filter))
(lexicon-lookup token (ts-lexicon ts)))
(defmethod lexicon-open-class ((ts lexicon-filter))
(lexicon-open-class (ts-lexicon ts)))
(defmethod next-token ((ts lexicon-filter))
Returns three values ( stems type surface ) . Stems may be a string or a
;; vector of strings. Type is a symbol and surface is a string. The strings
;; are all reclaimable
(multiple-value-bind (token type) (call-next-method)
(when token
(if (eq type :word)
(multiple-value-bind (stems type)
(lexicon-lookup token (ts-lexicon ts))
(values stems type token))
(values token (%vector type) (simple-string-copy token))))))
;;;; *tokenizer-class* names a class suitable for embedding in
;;;; tagger tokenerizer classes. These typically mixin basic-tag-ts
and fsa - tokenizer with some number of intervening filters
(defvar *tokenizer-class*)
(defun re-read-lexicon ()
(reinitialize-instance (ts-lexicon (make-instance *tokenizer-class*))))
| null | https://raw.githubusercontent.com/g000001/tagger/a4e0650c55aba44250871b96e2220e1b4953c6ab/orig/src/analysis/lexicon-protocol.lisp | lisp | Syntax : Common - Lisp ; Mode : Lisp ; Base : 10 -*-
and ( 2 ) a parallel sorted vector of tags ( keywords ) .
All vectors and strings are from resources.
Returns a vector of classes. Each class is a sorted vector of tags.
Returns a vector of open class tags (from the vector resource).
Returns a vector of tags.
LEXICON-FILTER: splices a lexicon into a token stream. The tokenizer
class :WORD is looked up in the lexicon, others are passed on. Makes the
TS masquerade as a lexicon. Most clients access the lexicon through this.
vector of strings. Type is a symbol and surface is a string. The strings
are all reclaimable
*tokenizer-class* names a class suitable for embedding in
tagger tokenerizer classes. These typically mixin basic-tag-ts |
Copyright ( c ) 1992 by Xerox Corporation .
(cl:in-package :tdb)
(eval-when (compile eval load)
(use-package :sv-resource)
(export '(lexicon
lexicon-tags lexicon-classes lexicon-open-class
lexicon-lookup class-order
lexicon-filter ts-lexicon
*the-keyword-package*
*tokenizer-class* re-read-lexicon)))
(defvar *the-keyword-package* (find-package :keyword))
(defclass lexicon ()
((lexicon-open-class :writer (setf lexicon-open-class))))
(defmethod initialize-instance :before ((lexicon lexicon)
&key lexicon-open-class
&allow-other-keys)
(setf (lexicon-open-class lexicon)
(sort (map 'simple-vector #'identity lexicon-open-class) #'string<)))
The Lexicon Protocol
Returns ( 1 ) a vector of stems ( strings ) or a single string if all stems are
(defgeneric lexicon-lookup (token lexicon))
(defmethod lexicon-lookup (token (lexicon lexicon))
(values (simple-string-copy token) (sv-copy (lexicon-open-class lexicon))))
(defgeneric lexicon-classes (lexicon))
(defmethod lexicon-classes ((lexicon lexicon))
(with-slots (lexicon-open-class) lexicon
(vector lexicon-open-class)))
(defgeneric lexicon-open-class (lexicon))
(defmethod lexicon-open-class ((lexicon lexicon))
(with-slots (lexicon-open-class) lexicon
(sv-copy lexicon-open-class)))
(defun lexicon-tags (lexicon)
(let* ((classes (lexicon-classes lexicon))
(table (make-hash-table :size (length classes))))
(dotimes (i (length classes))
(let ((class (svref classes i)))
(dotimes (j (length class))
(setf (gethash (svref class j) table) t))))
(let ((result (make-array (hash-table-count table)))
(index -1))
(maphash #'(lambda (tag ignore)
(declare (ignore ignore))
(setf (svref result (incf index)) tag))
table)
result)))
(defun class-order (class1 class2)
(let ((l1 (length class1))
(l2 (length class2)))
(if (= l1 l2)
(dotimes (i l1 :equal)
(when (string/= (svref class1 i) (svref class2 i))
(return (string< (svref class1 i) (svref class2 i)))))
(< l1 l2))))
(defclass lexicon-filter (token-filter)
((lexicon :accessor ts-lexicon :initarg :lexicon)))
(defmethod lexicon-classes ((ts lexicon-filter))
(remove-duplicates
(concatenate 'simple-vector
(lexicon-classes (ts-lexicon ts))
(map 'simple-vector #'vector
(remove :word (funcall (get-qua ts-types ts lexicon-filter) ts))))
:test #'equalp))
(defmethod lexicon-lookup (token (ts lexicon-filter))
(lexicon-lookup token (ts-lexicon ts)))
(defmethod lexicon-open-class ((ts lexicon-filter))
(lexicon-open-class (ts-lexicon ts)))
(defmethod next-token ((ts lexicon-filter))
Returns three values ( stems type surface ) . Stems may be a string or a
(multiple-value-bind (token type) (call-next-method)
(when token
(if (eq type :word)
(multiple-value-bind (stems type)
(lexicon-lookup token (ts-lexicon ts))
(values stems type token))
(values token (%vector type) (simple-string-copy token))))))
and fsa - tokenizer with some number of intervening filters
(defvar *tokenizer-class*)
(defun re-read-lexicon ()
(reinitialize-instance (ts-lexicon (make-instance *tokenizer-class*))))
|
1027328a52a80528dc3ff5c7c09f14fce345cd5a97561b571abc180e99bdf774 | bobzhang/fan | pr4452.ml | open Camlp4.PreCast
let _loc = Loc.mk "?"
let base base fields ty =
let fields = List.fold_right (fun field acc ->
let c = <:ctyp< $lid:field$ : $uid:field$.record >> in
<:ctyp< $c$ ; $acc$ >>) fields <:ctyp< >>
in
<:module_binding< $uid:base$ :
sig type record = {
key : $ty$;
$fields$
} end = struct
type record = {
key : $ty$;
$fields$
} end
>>
let _ =
let b = base "b" ["f1"; "f2"] <:ctyp< int >> in
Camlp4.PreCast.Printers.OCaml.print_implem
<:str_item< module rec $b$ >>
| null | https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/todoml/test/fixtures/pr4452.ml | ocaml | open Camlp4.PreCast
let _loc = Loc.mk "?"
let base base fields ty =
let fields = List.fold_right (fun field acc ->
let c = <:ctyp< $lid:field$ : $uid:field$.record >> in
<:ctyp< $c$ ; $acc$ >>) fields <:ctyp< >>
in
<:module_binding< $uid:base$ :
sig type record = {
key : $ty$;
$fields$
} end = struct
type record = {
key : $ty$;
$fields$
} end
>>
let _ =
let b = base "b" ["f1"; "f2"] <:ctyp< int >> in
Camlp4.PreCast.Printers.OCaml.print_implem
<:str_item< module rec $b$ >>
|
|
165b68daf354d795500c20987f08a634dbb3756423b7ce55781baa15146c34fa | D4ryus/cl-netstat | cl-netstat.lisp | ;;;; cl-stats.lisp
(in-package #:cl-netstat)
;;; "cl-stats" goes here. Hacks and glory await!
(defparameter *max* (* 1024 1024))
(defparameter *refresh-time* 0.25)
(defparameter *print-time-p* nil)
(defparameter *color-mode* :256)
(defparameter *unicode-mode* t)
(defparameter *icons* (list #\Space #\▁ #\▂ #\▃ #\▄ #\▅ #\▆ #\▇ #\█))
(defparameter *rgy-percentage*
over 90 % - > red
over 75 % - > yellow
under 10 % - > green
(defmacro with-thing ((window new thing) &body body)
(let ((old-thing (gensym "old-thing"))
(new-thing (gensym "new-thing")))
`(let ((,old-thing (,thing ,window))
(,new-thing ,new))
(flet ((call-body ()
,@body))
(if ,new-thing
(progn
(setf (,thing ,window) ,new-thing)
(prog1 (call-body)
(setf (,thing ,window) ,old-thing)))
(call-body))))))
(defmacro with-style ((window color-pair &optional attributes) &body body)
(cond
((and (null color-pair) (null attributes))
`(progn ,@body))
((and (null color-pair) attributes)
`(with-thing (,window ,attributes croatoan:attributes)
(progn ,@body)))
((and color-pair (null attributes))
`(with-thing (,window ,color-pair croatoan:color-pair)
(progn ,@body)))
(t
`(with-thing (,window ,attributes croatoan:attributes)
(with-thing (,window ,color-pair croatoan:color-pair)
(progn ,@body))))))
(defclass array-loop ()
((size :initarg :size)
(data :initarg :data)
(index :initform 0)))
(defmethod initialize-instance :after ((array-loop array-loop) &rest initargs)
(declare (ignorable initargs))
(with-slots (size data) array-loop
(setf data (make-array size :initial-element 0))
(let ((data-arg (getf initargs :data)))
(when data-arg
(mapc (lambda (element)
(push-element array-loop element))
(reverse data-arg))))))
(defmethod push-element ((array-loop array-loop) element)
(with-slots (size data index) array-loop
(setf (aref data (setf index (mod (1+ index) size)))
element)))
(defmethod get-list ((array-loop array-loop))
(with-slots (size data index) array-loop
(loop :for i :from index :downto (1+ (- index size))
:collect (aref data
(if (>= i 0)
i
(+ i size))))))
(defmethod get-max ((array-loop array-loop))
(reduce #'max (slot-value array-loop 'data)))
(defun to-icon (value &key (max 100) (icons *icons*))
(unless *unicode-mode*
(setf icons (list #\Space #\. #\o #\O #\^)))
(let ((icon-cnt (length icons)))
(cond ((<= value 0) (car icons))
((= max 0) (car icons))
((>= value max) (car (last icons)))
((< icon-cnt 3) (car (last icons)))
(t (nth (+ 1 (truncate (/ value (/ max (- icon-cnt 2)))))
icons)))))
(defun format-graph-part (window number &optional (max *max*))
(multiple-value-bind (_ color)
(format-size number :max *max*)
(declare (ignore _))
(with-style (window (reverse color))
(croatoan:add-wide-char window
(to-icon number :max max)))))
(defmethod format-graph ((array-loop array-loop) window)
(let* ((lst (get-list array-loop))
(first (car lst)))
(loop :for nbr :in lst
:do (format-graph-part window nbr))))
(defun get-rgy-color (size max)
(when max
(if (eql 0 size)
'(:black (:number 2))
(let ((percentage (/ size (/ max 100))))
(destructuring-bind (up mid low)
*rgy-percentage*
(cond
((> percentage up) '(:black :red))
((> percentage mid) '(:black :yellow))
((< percentage low) '(:black :green))
(t nil)))))))
8xb
8 tb
8 gb
8 mb
8 kb
(defun format-size (size &key (when-zero nil when-zero-given?) (max nil))
"formats given size (number) to a more readable format (string),
when-zero can be given to return it instead of \"0Byt\""
(if (and (eql 0 size)
when-zero-given?)
when-zero
(values
(cond
((> size xb) (format nil "~4d PiB" (ash size -50)))
((> size tb) (format nil "~4d TiB" (ash size -40)))
((> size gb) (format nil "~4d GiB" (ash size -30)))
((> size mb) (format nil "~4d MiB" (ash size -20)))
((> size kb) (format nil "~4d KiB" (ash size -10)))
(t (format nil "~4d Byt" size) ))
(case *color-mode*
(:8 (get-rgy-color size max))
(:256
(list :black
(if (eql 0 size)
:white
(list :number (color-size->term size max)))))
(t nil))))))
(defun get-interface-data ()
(with-open-file (stream "/proc/net/dev"
:direction :input)
ignore first 2 lines
(dotimes (ignored 2) (read-line stream nil nil))
(sort
(loop :for line = (read-line stream nil nil)
:while line
:collect
(destructuring-bind (interface data)
(cl-ppcre:split ":" (string-trim " " line))
(cons interface
(mapcar (lambda (val data)
(cons val
(parse-integer data)))
(list :rec-bytes :rec-packets :rec-errs
:rec-drop :rec-fifo :rec-frame
:rec-compressed :rec-multicast
:trans-bytes :trans-packets :trans-errs
:trans-drop :trans-fifo :trans-colls
:trans-carrier :trans-compressed)
(cdr (cl-ppcre:split "\\s+" data))))))
#'string< :key #'car)))
(defmacro assoc-chain (args data)
`(assoc ,(car (last args))
,(if (cdr args)
`(cdr (assoc-chain ,(butlast args)
,data))
data)
:test #'equalp))
(defmacro with-assocs (bindings data &body body)
(let ((data-sym (gensym "data")))
`(let ((,data-sym ,data))
(let ,(loop :for (var chain) :in bindings
:collect (list var `(assoc-chain ,chain ,data-sym)))
,@body))))
(defmacro mapassoc (function list &rest more-lists)
(let ((args (gensym "args")))
`(mapcar (lambda (&rest ,args)
(cons (caar ,args)
(apply ,function
(mapcar #'cdr ,args))))
,list
,@more-lists)))
(defun diff-interface-data (a b)
(loop :for (interface-a . data-a) :in a
:for (interface-b . data-b) :in b
:when (string= interface-a interface-b)
:collect (cons interface-a
( mapassoc # ' - data - b data - a )
(mapassoc (lambda (b a)
(truncate (/ (- b a) *refresh-time*)))
data-b data-a))))
(defparameter *interface-graphs* nil)
(let ((width 0))
(defun update-graphs (stats current-width)
;; add new interfaces
(loop :for (interface . stat) :in stats
:unless (gethash interface *interface-graphs*)
:do (setf (gethash interface *interface-graphs*)
(make-instance 'array-loop :size current-width)))
;; update length
(unless (and (eql current-width width)
(> current-width 57))
(setf width current-width)
(loop :for key :being :the :hash-key :of *interface-graphs*
:do (let ((data (gethash key *interface-graphs*)))
(setf (gethash key *interface-graphs*)
(make-instance 'array-loop :size (- width 57)
:data (get-list data))))))
;; update data
(loop :for key :being :the :hash-key :of *interface-graphs*
:do (let ((data (cdr (assoc key stats :test #'equal))))
(push-element (gethash key *interface-graphs*)
(if data
(+ (nth 2 data)
(nth 3 data))
0))))))
(defun format-bytes (window bytes &key max)
(multiple-value-bind (str color) (format-size bytes :max max)
(with-style (window color)
(format window "~8,,,' a" str))))
(defun format-interfaces (window stats)
(let ((refresh-time (when *print-time-p*
(format nil " ~,2f" *refresh-time*))))
(with-style (window '(:white :black) '(:bold :underline))
(format window "~a~a~a~a~a~a~a"
"NETWORK "
"Total Rx "
"Total Tx "
" Rx/s "
" Tx/s "
"Graph"
(if *print-time-p*
refresh-time
""))))
(loop :for stat :in stats
:do
(croatoan:new-line window)
(destructuring-bind (interface total-rx total-tx rx tx)
stat
(format window "~16,,,' a" interface)
(croatoan:add-char window #\Space)
(format-bytes window total-rx)
(croatoan:add-char window #\Space)
(format-bytes window total-tx)
(croatoan:add-char window #\Space)
(format-bytes window rx :max *max*)
(croatoan:add-char window #\Space)
(format-graph-part window rx)
(format-graph-part window tx)
(croatoan:add-char window #\Space)
(format-bytes window tx :max *max*)
(croatoan:add-char window #\Space))
(format-graph (gethash (car stat) *interface-graphs*) window)))
(defun gen-stats (last cur)
(loop :for (interface . data) :in (diff-interface-data last cur)
:collect (list interface
(cdr (assoc-chain (interface :rec-bytes) cur))
(cdr (assoc-chain (interface :trans-bytes) cur))
(cdr (assoc-chain (:rec-bytes) data))
(cdr (assoc-chain (:trans-bytes) data)))))
(defun draw-stats (window stats)
(croatoan:move window 0 0)
(setf (croatoan:color-pair window)
'(:white :black))
(update-graphs stats (croatoan:width window))
(format-interfaces window stats))
(defparameter *last-stats* nil)
(defun draw (screen)
(let ((stats (gen-stats *last-stats*
(setf *last-stats*
(get-interface-data)))))
(croatoan:clear screen)
(draw-stats screen stats)))
(defun clear (scr)
(croatoan:clear scr)
(croatoan:refresh scr))
(defun reset (scr)
(setf *last-stats* (get-interface-data))
(setf *interface-graphs* (make-hash-table :test 'equal))
(clear scr))
(defun window ()
(croatoan:with-screen (scr :input-echoing nil
:input-blocking nil
:enable-function-keys t
:cursor-visible nil)
(reset scr)
(let ((refresh-step 0.05))
(croatoan:event-case (scr event)
(#\q (return-from croatoan:event-case))
(#\+ (incf *refresh-time* refresh-step))
(#\- (when (< (decf *refresh-time* refresh-step) refresh-step)
(setf *refresh-time* refresh-step)))
(#\r (reset scr))
(#\c (clear scr))
(#\Space (setf *print-time-p* (not *print-time-p*)))
((nil)
(restart-case (progn
(sleep *refresh-time*)
(draw scr))
(continue ()
:report (lambda (stream)
(format stream "Continue Croatoan Event-Loop"))
(values nil t))
(reset ()
:report (lambda (stream)
(format stream "Reset values"))
(reset scr)
(values nil t))
(abort ()
:report (lambda (stream)
(format stream "Quit Croatoan Event-Loop"))
(return-from croatoan:event-case))))))))
(defun red-yellow-green-gradient-generator (count)
(let ((red 255)
(green 0)
(step-size (/ 255 (/ count 2))))
(flet ((fmt (red green)
(format nil "#~2,'0X~2,'0X00" (round red) (round green))))
(reverse
(append
(loop :while (< green 255)
:do (incf green step-size)
:when (> green 255)
:do (setf green 255)
:collect (fmt red green))
(loop :while (> red 0)
:do (decf red step-size)
:when (< red 0)
:do (setf red 0)
:collect (fmt red green)))))))
(let ((lookup (make-array '(42)
:initial-contents (red-yellow-green-gradient-generator 42)
:adjustable nil)))
(defun get-size-color (size &optional max)
(let ((spot (if max
(truncate (* 41 (/ size max)))
(integer-length size))))
(if (> spot 41)
(aref lookup 41)
(aref lookup spot)))))
(defun color-size->term (size &optional max)
(get-match (get-size-color size max)))
(defun color-hashtag-p (color)
(if (char-equal #\# (aref color 0)) t nil))
(defun color-rgb->string (r g b &optional hashtag-p)
(concatenate 'string
(when hashtag-p "#")
(write-to-string r :base 16)
(write-to-string g :base 16)
(write-to-string b :base 16)))
(defun color-string->rgb (color)
(when (color-hashtag-p color)
(setf color (subseq color 1 7)))
(values (parse-integer (subseq color 0 2) :radix 16)
(parse-integer (subseq color 2 4) :radix 16)
(parse-integer (subseq color 4 6) :radix 16)))
(defun parse-hex (string)
(parse-integer string :radix 16))
(defun color-diff (a b)
(declare (type list a b))
(reduce #'+
(mapcar (alexandria:compose #'abs #'-) a b)))
(let ((table (make-hash-table)))
(defun get-match (color)
(let ((match (gethash color table)))
(when match
(return-from get-match match)))
(let ((best-match-diff (* 3 255))
(best-match 0))
(multiple-value-bind (r g b)
(color-string->rgb color)
(loop :for (k . (rr gg bb))
:in (mapassoc (lambda (rgb)
(mapcar #'parse-hex rgb))
*term->rgb*)
:do (let ((diff (color-diff (list r g b)
(list rr gg bb))))
(when (< diff best-match-diff)
(setf best-match k
best-match-diff diff))
(when (eql 0 best-match-diff)
(return)))))
(setf (gethash color table) best-match))))
(defun usage (&optional error-msg &rest args)
(when error-msg
(apply #'format t error-msg args))
(format t "usage: cl-netstat [--color | -c (8 256 none)] [--max | -m number] ~
[--graph | -g \".oO\"] [--start-swank | -s] [--no-unicode | -n] ~
[--help | -h]~%")
(when error-msg
(error error-msg args)))
(defmacro switch-args (args usage-fn &rest cases)
`(with-args (,args ,usage-fn)
(str-case arg
,@cases
(t (funcall ,usage-fn "unknown argument ~a~%" arg)))))
(defmacro with-args ((args usage-fn) &body body)
(let ((cur (gensym "current")))
`(let* ((,cur ,args)
(arg (car ,cur)))
(flet ((shift (&optional (print-error t))
(setf ,cur (cdr ,cur))
(setf arg (car ,cur))
(when (and print-error
(not arg))
(funcall ,usage-fn "out of arguments~%"))))
(loop :while ,cur
:do
(prog1 (progn ,@body)
(shift nil)))))))
(defmacro str-case (string-form &body cases)
"'case' for strings, expands to cond clause with string=
as compare function"
(let ((result (gensym "result")))
`(let ((,result ,string-form))
(declare (ignorable ,result))
(cond
,@(loop :for (str form) :in cases
:collect
(typecase str
(boolean (if str
`(t ,form)
(error "nil is not a string")))
(string `((string= ,result ,str) ,form))
(list `((or ,@(loop :for s :in str
:collect `(string= ,result ,s)))
,form))))))))
(defun help ()
(format t
"cl-netstat: Showing per interface Network stats~%")
(usage)
(fresh-line)
(format t "Arguments:~%")
(format t " --color | -c (8 | 256 | none)~%")
(format t " Show output in colors:~%")
(format t " 8: only Red, Green and Yellow~%")
(format t " 256: 256 Colors~%")
(format t " none: dont use colors~%")
(format t " Default: 256~%")
(format t " --max | -m number~%")
(format t " Given number describes maximum network traffic,~%")
(format t " used for color output.~%")
(format t " Default: 1048576 (* 1024 1024)~%")
(format t " --refresh-time | -r number~%")
(format t " Refresh timeout given in milliseconds.~%")
(format t " Default: 250 (1/4 second)~%")
(format t " --graph | -g string~%")
(format t " Specify graph characters from lowest to highest.~%")
(format t " Default: ▁▂▃▄▅▆▇█ ( .oO^)~%")
(format t " --start-swank | -s~%")
(format t " Run (swank:create-server).~%")
(format t " --no-unicode | -n~%")
(format t " Show .oO instead of unicode bars as graph.~%")
(format t " This will overwrite --graph~%")
(format t " --help | -h~%")
(format t " Show this message.~%"))
(defun main ()
(when (uiop:command-line-arguments)
(switch-args (uiop:command-line-arguments) #'usage
(("--color" "-c")
(progn
(shift)
(setf *color-mode*
(str-case arg
("8" :8)
("256" :256)
(("None" "none") nil)
(t (usage "unknown color: ~a~%" arg))))))
(("--max" "-m")
(progn
(shift)
(setf *max* (parse-integer arg))))
(("--refresh-time" "-r")
(progn
(shift)
(setf *refresh-time* (* 0.001 (parse-integer arg)))))
(("--graph" "-g")
(progn
(shift)
(setf *icons* (map 'list #'identity arg))))
(("--no-unicode" "-n")
(setf *unicode-mode* nil))
(("--start-swank" "-s")
(swank:create-server))
(("--help" "-h")
(progn
(help)
(uiop:quit 0)))
("--options"
(progn
(mapcar (lambda (op)
(princ op)
(fresh-line))
(list "--color" "-c"
"--max" "-m"
"--refresh-time" "-r"
"--graph" "-g"
"--no-unicode" "-n"
"--help" "-h"
"--start-swank" "-s"))
(uiop:quit 0)))))
(window))
| null | https://raw.githubusercontent.com/D4ryus/cl-netstat/e7187a4bec2f23b08c7a236f0c52503a444b941d/cl-netstat.lisp | lisp | cl-stats.lisp
"cl-stats" goes here. Hacks and glory await!
add new interfaces
update length
update data |
(in-package #:cl-netstat)
(defparameter *max* (* 1024 1024))
(defparameter *refresh-time* 0.25)
(defparameter *print-time-p* nil)
(defparameter *color-mode* :256)
(defparameter *unicode-mode* t)
(defparameter *icons* (list #\Space #\▁ #\▂ #\▃ #\▄ #\▅ #\▆ #\▇ #\█))
(defparameter *rgy-percentage*
over 90 % - > red
over 75 % - > yellow
under 10 % - > green
(defmacro with-thing ((window new thing) &body body)
(let ((old-thing (gensym "old-thing"))
(new-thing (gensym "new-thing")))
`(let ((,old-thing (,thing ,window))
(,new-thing ,new))
(flet ((call-body ()
,@body))
(if ,new-thing
(progn
(setf (,thing ,window) ,new-thing)
(prog1 (call-body)
(setf (,thing ,window) ,old-thing)))
(call-body))))))
(defmacro with-style ((window color-pair &optional attributes) &body body)
(cond
((and (null color-pair) (null attributes))
`(progn ,@body))
((and (null color-pair) attributes)
`(with-thing (,window ,attributes croatoan:attributes)
(progn ,@body)))
((and color-pair (null attributes))
`(with-thing (,window ,color-pair croatoan:color-pair)
(progn ,@body)))
(t
`(with-thing (,window ,attributes croatoan:attributes)
(with-thing (,window ,color-pair croatoan:color-pair)
(progn ,@body))))))
(defclass array-loop ()
((size :initarg :size)
(data :initarg :data)
(index :initform 0)))
(defmethod initialize-instance :after ((array-loop array-loop) &rest initargs)
(declare (ignorable initargs))
(with-slots (size data) array-loop
(setf data (make-array size :initial-element 0))
(let ((data-arg (getf initargs :data)))
(when data-arg
(mapc (lambda (element)
(push-element array-loop element))
(reverse data-arg))))))
(defmethod push-element ((array-loop array-loop) element)
(with-slots (size data index) array-loop
(setf (aref data (setf index (mod (1+ index) size)))
element)))
(defmethod get-list ((array-loop array-loop))
(with-slots (size data index) array-loop
(loop :for i :from index :downto (1+ (- index size))
:collect (aref data
(if (>= i 0)
i
(+ i size))))))
(defmethod get-max ((array-loop array-loop))
(reduce #'max (slot-value array-loop 'data)))
(defun to-icon (value &key (max 100) (icons *icons*))
(unless *unicode-mode*
(setf icons (list #\Space #\. #\o #\O #\^)))
(let ((icon-cnt (length icons)))
(cond ((<= value 0) (car icons))
((= max 0) (car icons))
((>= value max) (car (last icons)))
((< icon-cnt 3) (car (last icons)))
(t (nth (+ 1 (truncate (/ value (/ max (- icon-cnt 2)))))
icons)))))
(defun format-graph-part (window number &optional (max *max*))
(multiple-value-bind (_ color)
(format-size number :max *max*)
(declare (ignore _))
(with-style (window (reverse color))
(croatoan:add-wide-char window
(to-icon number :max max)))))
(defmethod format-graph ((array-loop array-loop) window)
(let* ((lst (get-list array-loop))
(first (car lst)))
(loop :for nbr :in lst
:do (format-graph-part window nbr))))
(defun get-rgy-color (size max)
(when max
(if (eql 0 size)
'(:black (:number 2))
(let ((percentage (/ size (/ max 100))))
(destructuring-bind (up mid low)
*rgy-percentage*
(cond
((> percentage up) '(:black :red))
((> percentage mid) '(:black :yellow))
((< percentage low) '(:black :green))
(t nil)))))))
8xb
8 tb
8 gb
8 mb
8 kb
(defun format-size (size &key (when-zero nil when-zero-given?) (max nil))
"formats given size (number) to a more readable format (string),
when-zero can be given to return it instead of \"0Byt\""
(if (and (eql 0 size)
when-zero-given?)
when-zero
(values
(cond
((> size xb) (format nil "~4d PiB" (ash size -50)))
((> size tb) (format nil "~4d TiB" (ash size -40)))
((> size gb) (format nil "~4d GiB" (ash size -30)))
((> size mb) (format nil "~4d MiB" (ash size -20)))
((> size kb) (format nil "~4d KiB" (ash size -10)))
(t (format nil "~4d Byt" size) ))
(case *color-mode*
(:8 (get-rgy-color size max))
(:256
(list :black
(if (eql 0 size)
:white
(list :number (color-size->term size max)))))
(t nil))))))
(defun get-interface-data ()
(with-open-file (stream "/proc/net/dev"
:direction :input)
ignore first 2 lines
(dotimes (ignored 2) (read-line stream nil nil))
(sort
(loop :for line = (read-line stream nil nil)
:while line
:collect
(destructuring-bind (interface data)
(cl-ppcre:split ":" (string-trim " " line))
(cons interface
(mapcar (lambda (val data)
(cons val
(parse-integer data)))
(list :rec-bytes :rec-packets :rec-errs
:rec-drop :rec-fifo :rec-frame
:rec-compressed :rec-multicast
:trans-bytes :trans-packets :trans-errs
:trans-drop :trans-fifo :trans-colls
:trans-carrier :trans-compressed)
(cdr (cl-ppcre:split "\\s+" data))))))
#'string< :key #'car)))
(defmacro assoc-chain (args data)
`(assoc ,(car (last args))
,(if (cdr args)
`(cdr (assoc-chain ,(butlast args)
,data))
data)
:test #'equalp))
(defmacro with-assocs (bindings data &body body)
(let ((data-sym (gensym "data")))
`(let ((,data-sym ,data))
(let ,(loop :for (var chain) :in bindings
:collect (list var `(assoc-chain ,chain ,data-sym)))
,@body))))
(defmacro mapassoc (function list &rest more-lists)
(let ((args (gensym "args")))
`(mapcar (lambda (&rest ,args)
(cons (caar ,args)
(apply ,function
(mapcar #'cdr ,args))))
,list
,@more-lists)))
(defun diff-interface-data (a b)
(loop :for (interface-a . data-a) :in a
:for (interface-b . data-b) :in b
:when (string= interface-a interface-b)
:collect (cons interface-a
( mapassoc # ' - data - b data - a )
(mapassoc (lambda (b a)
(truncate (/ (- b a) *refresh-time*)))
data-b data-a))))
(defparameter *interface-graphs* nil)
(let ((width 0))
(defun update-graphs (stats current-width)
(loop :for (interface . stat) :in stats
:unless (gethash interface *interface-graphs*)
:do (setf (gethash interface *interface-graphs*)
(make-instance 'array-loop :size current-width)))
(unless (and (eql current-width width)
(> current-width 57))
(setf width current-width)
(loop :for key :being :the :hash-key :of *interface-graphs*
:do (let ((data (gethash key *interface-graphs*)))
(setf (gethash key *interface-graphs*)
(make-instance 'array-loop :size (- width 57)
:data (get-list data))))))
(loop :for key :being :the :hash-key :of *interface-graphs*
:do (let ((data (cdr (assoc key stats :test #'equal))))
(push-element (gethash key *interface-graphs*)
(if data
(+ (nth 2 data)
(nth 3 data))
0))))))
(defun format-bytes (window bytes &key max)
(multiple-value-bind (str color) (format-size bytes :max max)
(with-style (window color)
(format window "~8,,,' a" str))))
(defun format-interfaces (window stats)
(let ((refresh-time (when *print-time-p*
(format nil " ~,2f" *refresh-time*))))
(with-style (window '(:white :black) '(:bold :underline))
(format window "~a~a~a~a~a~a~a"
"NETWORK "
"Total Rx "
"Total Tx "
" Rx/s "
" Tx/s "
"Graph"
(if *print-time-p*
refresh-time
""))))
(loop :for stat :in stats
:do
(croatoan:new-line window)
(destructuring-bind (interface total-rx total-tx rx tx)
stat
(format window "~16,,,' a" interface)
(croatoan:add-char window #\Space)
(format-bytes window total-rx)
(croatoan:add-char window #\Space)
(format-bytes window total-tx)
(croatoan:add-char window #\Space)
(format-bytes window rx :max *max*)
(croatoan:add-char window #\Space)
(format-graph-part window rx)
(format-graph-part window tx)
(croatoan:add-char window #\Space)
(format-bytes window tx :max *max*)
(croatoan:add-char window #\Space))
(format-graph (gethash (car stat) *interface-graphs*) window)))
(defun gen-stats (last cur)
(loop :for (interface . data) :in (diff-interface-data last cur)
:collect (list interface
(cdr (assoc-chain (interface :rec-bytes) cur))
(cdr (assoc-chain (interface :trans-bytes) cur))
(cdr (assoc-chain (:rec-bytes) data))
(cdr (assoc-chain (:trans-bytes) data)))))
(defun draw-stats (window stats)
(croatoan:move window 0 0)
(setf (croatoan:color-pair window)
'(:white :black))
(update-graphs stats (croatoan:width window))
(format-interfaces window stats))
(defparameter *last-stats* nil)
(defun draw (screen)
(let ((stats (gen-stats *last-stats*
(setf *last-stats*
(get-interface-data)))))
(croatoan:clear screen)
(draw-stats screen stats)))
(defun clear (scr)
(croatoan:clear scr)
(croatoan:refresh scr))
(defun reset (scr)
(setf *last-stats* (get-interface-data))
(setf *interface-graphs* (make-hash-table :test 'equal))
(clear scr))
(defun window ()
(croatoan:with-screen (scr :input-echoing nil
:input-blocking nil
:enable-function-keys t
:cursor-visible nil)
(reset scr)
(let ((refresh-step 0.05))
(croatoan:event-case (scr event)
(#\q (return-from croatoan:event-case))
(#\+ (incf *refresh-time* refresh-step))
(#\- (when (< (decf *refresh-time* refresh-step) refresh-step)
(setf *refresh-time* refresh-step)))
(#\r (reset scr))
(#\c (clear scr))
(#\Space (setf *print-time-p* (not *print-time-p*)))
((nil)
(restart-case (progn
(sleep *refresh-time*)
(draw scr))
(continue ()
:report (lambda (stream)
(format stream "Continue Croatoan Event-Loop"))
(values nil t))
(reset ()
:report (lambda (stream)
(format stream "Reset values"))
(reset scr)
(values nil t))
(abort ()
:report (lambda (stream)
(format stream "Quit Croatoan Event-Loop"))
(return-from croatoan:event-case))))))))
(defun red-yellow-green-gradient-generator (count)
(let ((red 255)
(green 0)
(step-size (/ 255 (/ count 2))))
(flet ((fmt (red green)
(format nil "#~2,'0X~2,'0X00" (round red) (round green))))
(reverse
(append
(loop :while (< green 255)
:do (incf green step-size)
:when (> green 255)
:do (setf green 255)
:collect (fmt red green))
(loop :while (> red 0)
:do (decf red step-size)
:when (< red 0)
:do (setf red 0)
:collect (fmt red green)))))))
(let ((lookup (make-array '(42)
:initial-contents (red-yellow-green-gradient-generator 42)
:adjustable nil)))
(defun get-size-color (size &optional max)
(let ((spot (if max
(truncate (* 41 (/ size max)))
(integer-length size))))
(if (> spot 41)
(aref lookup 41)
(aref lookup spot)))))
(defun color-size->term (size &optional max)
(get-match (get-size-color size max)))
(defun color-hashtag-p (color)
(if (char-equal #\# (aref color 0)) t nil))
(defun color-rgb->string (r g b &optional hashtag-p)
(concatenate 'string
(when hashtag-p "#")
(write-to-string r :base 16)
(write-to-string g :base 16)
(write-to-string b :base 16)))
(defun color-string->rgb (color)
(when (color-hashtag-p color)
(setf color (subseq color 1 7)))
(values (parse-integer (subseq color 0 2) :radix 16)
(parse-integer (subseq color 2 4) :radix 16)
(parse-integer (subseq color 4 6) :radix 16)))
(defun parse-hex (string)
(parse-integer string :radix 16))
(defun color-diff (a b)
(declare (type list a b))
(reduce #'+
(mapcar (alexandria:compose #'abs #'-) a b)))
(let ((table (make-hash-table)))
(defun get-match (color)
(let ((match (gethash color table)))
(when match
(return-from get-match match)))
(let ((best-match-diff (* 3 255))
(best-match 0))
(multiple-value-bind (r g b)
(color-string->rgb color)
(loop :for (k . (rr gg bb))
:in (mapassoc (lambda (rgb)
(mapcar #'parse-hex rgb))
*term->rgb*)
:do (let ((diff (color-diff (list r g b)
(list rr gg bb))))
(when (< diff best-match-diff)
(setf best-match k
best-match-diff diff))
(when (eql 0 best-match-diff)
(return)))))
(setf (gethash color table) best-match))))
(defun usage (&optional error-msg &rest args)
(when error-msg
(apply #'format t error-msg args))
(format t "usage: cl-netstat [--color | -c (8 256 none)] [--max | -m number] ~
[--graph | -g \".oO\"] [--start-swank | -s] [--no-unicode | -n] ~
[--help | -h]~%")
(when error-msg
(error error-msg args)))
(defmacro switch-args (args usage-fn &rest cases)
`(with-args (,args ,usage-fn)
(str-case arg
,@cases
(t (funcall ,usage-fn "unknown argument ~a~%" arg)))))
(defmacro with-args ((args usage-fn) &body body)
(let ((cur (gensym "current")))
`(let* ((,cur ,args)
(arg (car ,cur)))
(flet ((shift (&optional (print-error t))
(setf ,cur (cdr ,cur))
(setf arg (car ,cur))
(when (and print-error
(not arg))
(funcall ,usage-fn "out of arguments~%"))))
(loop :while ,cur
:do
(prog1 (progn ,@body)
(shift nil)))))))
(defmacro str-case (string-form &body cases)
"'case' for strings, expands to cond clause with string=
as compare function"
(let ((result (gensym "result")))
`(let ((,result ,string-form))
(declare (ignorable ,result))
(cond
,@(loop :for (str form) :in cases
:collect
(typecase str
(boolean (if str
`(t ,form)
(error "nil is not a string")))
(string `((string= ,result ,str) ,form))
(list `((or ,@(loop :for s :in str
:collect `(string= ,result ,s)))
,form))))))))
(defun help ()
(format t
"cl-netstat: Showing per interface Network stats~%")
(usage)
(fresh-line)
(format t "Arguments:~%")
(format t " --color | -c (8 | 256 | none)~%")
(format t " Show output in colors:~%")
(format t " 8: only Red, Green and Yellow~%")
(format t " 256: 256 Colors~%")
(format t " none: dont use colors~%")
(format t " Default: 256~%")
(format t " --max | -m number~%")
(format t " Given number describes maximum network traffic,~%")
(format t " used for color output.~%")
(format t " Default: 1048576 (* 1024 1024)~%")
(format t " --refresh-time | -r number~%")
(format t " Refresh timeout given in milliseconds.~%")
(format t " Default: 250 (1/4 second)~%")
(format t " --graph | -g string~%")
(format t " Specify graph characters from lowest to highest.~%")
(format t " Default: ▁▂▃▄▅▆▇█ ( .oO^)~%")
(format t " --start-swank | -s~%")
(format t " Run (swank:create-server).~%")
(format t " --no-unicode | -n~%")
(format t " Show .oO instead of unicode bars as graph.~%")
(format t " This will overwrite --graph~%")
(format t " --help | -h~%")
(format t " Show this message.~%"))
(defun main ()
(when (uiop:command-line-arguments)
(switch-args (uiop:command-line-arguments) #'usage
(("--color" "-c")
(progn
(shift)
(setf *color-mode*
(str-case arg
("8" :8)
("256" :256)
(("None" "none") nil)
(t (usage "unknown color: ~a~%" arg))))))
(("--max" "-m")
(progn
(shift)
(setf *max* (parse-integer arg))))
(("--refresh-time" "-r")
(progn
(shift)
(setf *refresh-time* (* 0.001 (parse-integer arg)))))
(("--graph" "-g")
(progn
(shift)
(setf *icons* (map 'list #'identity arg))))
(("--no-unicode" "-n")
(setf *unicode-mode* nil))
(("--start-swank" "-s")
(swank:create-server))
(("--help" "-h")
(progn
(help)
(uiop:quit 0)))
("--options"
(progn
(mapcar (lambda (op)
(princ op)
(fresh-line))
(list "--color" "-c"
"--max" "-m"
"--refresh-time" "-r"
"--graph" "-g"
"--no-unicode" "-n"
"--help" "-h"
"--start-swank" "-s"))
(uiop:quit 0)))))
(window))
|
ff5f1c12305afb0ee88509b4bcba60c5586e6726845c5c010134b4963daff935 | ygmpkk/house | IOState.hs | -- #hide
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.IOState
Copyright : ( c ) 2003
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- This is a purely internal module for an IO monad with a pointer as an
-- additional state, basically a /StateT (Ptr s) IO a/.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.IOState (
IOState(..), getIOState, peekIOState, evalIOState, nTimes
) where
import Foreign.Ptr ( Ptr, plusPtr )
import Foreign.Storable ( Storable(sizeOf,peek) )
--------------------------------------------------------------------------------
newtype IOState s a = IOState { runIOState :: Ptr s -> IO (a, Ptr s) }
instance Functor (IOState s) where
fmap f m = IOState $ \s -> do (x, s') <- runIOState m s ; return (f x, s')
instance Monad (IOState s) where
return a = IOState $ \s -> return (a, s)
m >>= k = IOState $ \s -> do (a, s') <- runIOState m s ; runIOState (k a) s'
fail str = IOState $ \_ -> fail str
getIOState :: IOState s (Ptr s)
getIOState = IOState $ \s -> return (s, s)
putIOState :: Ptr s -> IOState s ()
putIOState s = IOState $ \_ -> return ((), s)
peekIOState :: Storable a => IOState a a
peekIOState = do
ptr <- getIOState
x <- liftIOState $ peek ptr
putIOState (ptr `plusPtr` sizeOf x)
return x
liftIOState :: IO a -> IOState s a
liftIOState m = IOState $ \s -> do a <- m ; return (a, s)
evalIOState :: IOState s a -> Ptr s -> IO a
evalIOState m s = do (a, _) <- runIOState m s ; return a
nTimes :: Integral a => a -> IOState b c -> IOState b [c]
nTimes n = sequence . replicate (fromIntegral n)
| null | https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/libraries/OpenGL/Graphics/Rendering/OpenGL/GL/IOState.hs | haskell | #hide
------------------------------------------------------------------------------
|
Module : Graphics.Rendering.OpenGL.GL.IOState
License : BSD-style (see the file libraries/OpenGL/LICENSE)
Maintainer :
Stability : provisional
Portability : portable
This is a purely internal module for an IO monad with a pointer as an
additional state, basically a /StateT (Ptr s) IO a/.
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | Copyright : ( c ) 2003
module Graphics.Rendering.OpenGL.GL.IOState (
IOState(..), getIOState, peekIOState, evalIOState, nTimes
) where
import Foreign.Ptr ( Ptr, plusPtr )
import Foreign.Storable ( Storable(sizeOf,peek) )
newtype IOState s a = IOState { runIOState :: Ptr s -> IO (a, Ptr s) }
instance Functor (IOState s) where
fmap f m = IOState $ \s -> do (x, s') <- runIOState m s ; return (f x, s')
instance Monad (IOState s) where
return a = IOState $ \s -> return (a, s)
m >>= k = IOState $ \s -> do (a, s') <- runIOState m s ; runIOState (k a) s'
fail str = IOState $ \_ -> fail str
getIOState :: IOState s (Ptr s)
getIOState = IOState $ \s -> return (s, s)
putIOState :: Ptr s -> IOState s ()
putIOState s = IOState $ \_ -> return ((), s)
peekIOState :: Storable a => IOState a a
peekIOState = do
ptr <- getIOState
x <- liftIOState $ peek ptr
putIOState (ptr `plusPtr` sizeOf x)
return x
liftIOState :: IO a -> IOState s a
liftIOState m = IOState $ \s -> do a <- m ; return (a, s)
evalIOState :: IOState s a -> Ptr s -> IO a
evalIOState m s = do (a, _) <- runIOState m s ; return a
nTimes :: Integral a => a -> IOState b c -> IOState b [c]
nTimes n = sequence . replicate (fromIntegral n)
|
ef5a38f2f4192b1543cfa2ad222fc6bbbb31804bb50a37466ec4433d30d4d6fd | tonyg/udp-exchange | udp_exchange_relay.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 /.
%%
-module(udp_exchange_relay).
-include_lib("rabbit_common/include/rabbit.hrl").
-include("udp_exchange.hrl").
-behaviour(gen_server).
-export([start_link/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
code_change/3, terminate/2]).
-record(state, {params, socket}).
start_link(Params = #params{process_name = ProcessName}) ->
gen_server:start_link({local, ProcessName}, ?MODULE, [Params], []).
%%----------------------------------------------------------------------------
init([#params{ip_addr = IpAddr, port = Port} = Params]) ->
Opts = [{recbuf, 65536}, binary],
{ok, Socket} = case IpAddr of
{0,0,0,0} -> gen_udp:open(Port, Opts);
_ -> gen_udp:open(Port, [{ip, IpAddr} | Opts])
end,
{ok, #state{params = Params, socket = Socket}}.
handle_call(Msg, _From, State) ->
{stop, {unhandled_call, Msg}, State}.
handle_cast(Msg, State) ->
{stop, {unhandled_cast, Msg}, State}.
handle_info(Delivery = #delivery{}, State = #state{params = Params,
socket = Socket}) ->
case catch analyze_delivery(Delivery, Params) of
{TargetIp, TargetPort, Packet} ->
ok = gen_udp:send(Socket, TargetIp, TargetPort, Packet);
ignore ->
ok;
{'EXIT', Reason} ->
Discard messages we ca n't shoehorn into UDP .
RKs = (Delivery#delivery.message)#basic_message.routing_keys,
#params{exchange_def = #exchange{name = XName},
packet_module = PacketModule} = Params,
error_logger:warning_report({?MODULE, PacketModule, format,
{Reason,
[{exchange, XName},
{routing_keys, RKs}]}}),
ok
end,
{noreply, State};
handle_info({udp, _Socket, SourceIp, SourcePort, Packet},
State = #state{params = Params}) ->
case udp_delivery(SourceIp, SourcePort, Packet, Params) of
ignore ->
ok;
{ok, Delivery} ->
ok = udp_exchange:deliver(Params#params.exchange_def, Delivery)
end,
{noreply, State};
handle_info(Msg, State) ->
{stop, {unhandled_info, Msg}, State}.
terminate(_Reason, #state{socket = Socket}) ->
ok = gen_udp:close(Socket),
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%----------------------------------------------------------------------------
analyze_delivery(Delivery =
#delivery{message =
#basic_message{routing_keys = [RoutingKey],
content =
#content{payload_fragments_rev =
PayloadRev}}},
#params{packet_module = PacketModule,
packet_config = PacketConfig}) ->
<<"ipv4.", Rest/binary>> = RoutingKey,
%% re:split(X,Y) can be replaced with binary:split(X,Y,[global]) once we
drop support for Erlangs older than R14 .
[AStr, BStr, CStr, DStr, PortStr | RoutingKeySuffixes] = re:split(Rest, "\\."),
A = list_to_integer(binary_to_list(AStr)),
B = list_to_integer(binary_to_list(BStr)),
C = list_to_integer(binary_to_list(CStr)),
D = list_to_integer(binary_to_list(DStr)),
IpAddr = {A, B, C, D},
Port = list_to_integer(binary_to_list(PortStr)),
PacketModule:format(IpAddr,
Port,
RoutingKeySuffixes,
list_to_binary(lists:reverse(PayloadRev)),
Delivery,
PacketConfig).
udp_delivery(IpAddr = {A, B, C, D},
Port,
Packet,
#params{exchange_def = #exchange{name = XName},
packet_module = PacketModule,
packet_config = PacketConfig}) ->
case PacketModule:parse(IpAddr, Port, Packet, PacketConfig) of
{ok, {RoutingKeySuffix, Properties, Body}} ->
IpStr = list_to_binary(io_lib:format("~p.~p.~p.~p", [A, B, C, D])),
RoutingKey = udp_exchange:truncate_bin(
255, list_to_binary(["ipv4",
".", IpStr,
".", integer_to_list(Port),
".", RoutingKeySuffix])),
{ok, rabbit_basic:delivery(false, %% mandatory?
false, %% should confirm message?
rabbit_basic:message(XName, RoutingKey, Properties, Body),
undefined)};
ignore ->
ignore;
{error, Error} ->
error_logger:error_report({?MODULE, PacketModule, parse, Error}),
ignore
end.
| null | https://raw.githubusercontent.com/tonyg/udp-exchange/99ee53ffe6f34130920ae3a741ecf6d43955681b/src/udp_exchange_relay.erl | erlang |
----------------------------------------------------------------------------
----------------------------------------------------------------------------
re:split(X,Y) can be replaced with binary:split(X,Y,[global]) once we
mandatory?
should confirm message? | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
-module(udp_exchange_relay).
-include_lib("rabbit_common/include/rabbit.hrl").
-include("udp_exchange.hrl").
-behaviour(gen_server).
-export([start_link/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
code_change/3, terminate/2]).
-record(state, {params, socket}).
start_link(Params = #params{process_name = ProcessName}) ->
gen_server:start_link({local, ProcessName}, ?MODULE, [Params], []).
init([#params{ip_addr = IpAddr, port = Port} = Params]) ->
Opts = [{recbuf, 65536}, binary],
{ok, Socket} = case IpAddr of
{0,0,0,0} -> gen_udp:open(Port, Opts);
_ -> gen_udp:open(Port, [{ip, IpAddr} | Opts])
end,
{ok, #state{params = Params, socket = Socket}}.
handle_call(Msg, _From, State) ->
{stop, {unhandled_call, Msg}, State}.
handle_cast(Msg, State) ->
{stop, {unhandled_cast, Msg}, State}.
handle_info(Delivery = #delivery{}, State = #state{params = Params,
socket = Socket}) ->
case catch analyze_delivery(Delivery, Params) of
{TargetIp, TargetPort, Packet} ->
ok = gen_udp:send(Socket, TargetIp, TargetPort, Packet);
ignore ->
ok;
{'EXIT', Reason} ->
Discard messages we ca n't shoehorn into UDP .
RKs = (Delivery#delivery.message)#basic_message.routing_keys,
#params{exchange_def = #exchange{name = XName},
packet_module = PacketModule} = Params,
error_logger:warning_report({?MODULE, PacketModule, format,
{Reason,
[{exchange, XName},
{routing_keys, RKs}]}}),
ok
end,
{noreply, State};
handle_info({udp, _Socket, SourceIp, SourcePort, Packet},
State = #state{params = Params}) ->
case udp_delivery(SourceIp, SourcePort, Packet, Params) of
ignore ->
ok;
{ok, Delivery} ->
ok = udp_exchange:deliver(Params#params.exchange_def, Delivery)
end,
{noreply, State};
handle_info(Msg, State) ->
{stop, {unhandled_info, Msg}, State}.
terminate(_Reason, #state{socket = Socket}) ->
ok = gen_udp:close(Socket),
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
analyze_delivery(Delivery =
#delivery{message =
#basic_message{routing_keys = [RoutingKey],
content =
#content{payload_fragments_rev =
PayloadRev}}},
#params{packet_module = PacketModule,
packet_config = PacketConfig}) ->
<<"ipv4.", Rest/binary>> = RoutingKey,
drop support for Erlangs older than R14 .
[AStr, BStr, CStr, DStr, PortStr | RoutingKeySuffixes] = re:split(Rest, "\\."),
A = list_to_integer(binary_to_list(AStr)),
B = list_to_integer(binary_to_list(BStr)),
C = list_to_integer(binary_to_list(CStr)),
D = list_to_integer(binary_to_list(DStr)),
IpAddr = {A, B, C, D},
Port = list_to_integer(binary_to_list(PortStr)),
PacketModule:format(IpAddr,
Port,
RoutingKeySuffixes,
list_to_binary(lists:reverse(PayloadRev)),
Delivery,
PacketConfig).
udp_delivery(IpAddr = {A, B, C, D},
Port,
Packet,
#params{exchange_def = #exchange{name = XName},
packet_module = PacketModule,
packet_config = PacketConfig}) ->
case PacketModule:parse(IpAddr, Port, Packet, PacketConfig) of
{ok, {RoutingKeySuffix, Properties, Body}} ->
IpStr = list_to_binary(io_lib:format("~p.~p.~p.~p", [A, B, C, D])),
RoutingKey = udp_exchange:truncate_bin(
255, list_to_binary(["ipv4",
".", IpStr,
".", integer_to_list(Port),
".", RoutingKeySuffix])),
rabbit_basic:message(XName, RoutingKey, Properties, Body),
undefined)};
ignore ->
ignore;
{error, Error} ->
error_logger:error_report({?MODULE, PacketModule, parse, Error}),
ignore
end.
|
844ddc30cb895d71186a820bf4e039f98ed14a1ac6df9e0b21e37cfaacf2e51f | abeniaminov/transaction | tgen_sampl.erl | % -*- coding: utf8 -*-
%%%-------------------------------------------------------------------
@author
( C ) 2015 , < COMPANY >
%%% @doc
%%%
%%% @end
%%%-------------------------------------------------------------------
-module(tgen_sampl).
-author("Alexander").
-behaviour(tgen_server).
%% API
-export([start_link/3, start_link/2]).
-export([set_value/3, get_value/2, stop/2, start_from/3]).
%% gen_server callbacks
-export([init/2,
handle_call/4,
handle_cast/3,
handle_info/3,
terminate/3,
code_change/3]).
-define(SERVER, ?MODULE).
%%%===================================================================
%%% API
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% Starts the server
%%
%% @end
%%--------------------------------------------------------------------
-spec(start_link(atom(), tgen_sever:transaction(), term()) ->
{ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
start_link(Name, Tr, InitVal) ->
tgen_server:start_link({local, Name}, ?MODULE, InitVal, Tr, []).
start_link(Tr, InitVal) ->
tgen_server:start_link(?MODULE, InitVal, Tr, []).
set_value(Pid, Tr, Value) ->
tgen_server:call(Pid, Tr, {set_value, Value}).
get_value(Pid, Tr) ->
tgen_server:call(Pid, Tr, get_value).
start_from(Pid, Tr, Value) ->
tgen_server:call(Pid, Tr, {start_from, Value}).
stop(Pid, Tr) ->
tgen_server:stop(Pid, Tr).
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
%%--------------------------------------------------------------------
@private
%% @doc
%% Initializes the server
%%
%%--------------------------------------------------------------------
init(_Tr, InitVal) ->
{ok, InitVal}.
%%--------------------------------------------------------------------
@private
%% @doc
%% Handling call messages
%%
%% @end
%%--------------------------------------------------------------------
handle_call(_Tr, {set_value, Value}, _From, _State) ->
{reply, ok, Value};
handle_call(Tr, {start_from, Value}, _From, _State) ->
NewPid = start_link(Tr, Value),
{reply, NewPid, Value};
handle_call(_Tr, get_value, _From, State) ->
{reply, State, State}.
%%--------------------------------------------------------------------
@private
%% @doc
%% Handling cast messages
%%
%% @end
%%--------------------------------------------------------------------
handle_cast(_Tr,_Request, State) ->
{noreply, State}.
%%--------------------------------------------------------------------
@private
%% @doc
%% @end
%%--------------------------------------------------------------------
handle_info(_Tr,_Info, State) ->
{noreply, State}.
%%--------------------------------------------------------------------
@private
%% @doc
%% @end
%%--------------------------------------------------------------------
terminate(_Tr, _Reason, _State) ->
ok.
%%--------------------------------------------------------------------
@private
%% @doc
%% Convert process state when code is changed
%%
, State , Extra ) - > { ok , NewState }
%% @end
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%===================================================================
Internal functions
%%%===================================================================
| null | https://raw.githubusercontent.com/abeniaminov/transaction/bdf3dbf352f8d13286bcf85428938a5f0fbb432f/test/tgen_sampl.erl | erlang | -*- coding: utf8 -*-
-------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API
gen_server callbacks
===================================================================
API
===================================================================
--------------------------------------------------------------------
@doc
Starts the server
@end
--------------------------------------------------------------------
===================================================================
gen_server callbacks
===================================================================
--------------------------------------------------------------------
@doc
Initializes the server
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Handling call messages
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Handling cast messages
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Convert process state when code is changed
@end
--------------------------------------------------------------------
===================================================================
=================================================================== | @author
( C ) 2015 , < COMPANY >
-module(tgen_sampl).
-author("Alexander").
-behaviour(tgen_server).
-export([start_link/3, start_link/2]).
-export([set_value/3, get_value/2, stop/2, start_from/3]).
-export([init/2,
handle_call/4,
handle_cast/3,
handle_info/3,
terminate/3,
code_change/3]).
-define(SERVER, ?MODULE).
-spec(start_link(atom(), tgen_sever:transaction(), term()) ->
{ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
start_link(Name, Tr, InitVal) ->
tgen_server:start_link({local, Name}, ?MODULE, InitVal, Tr, []).
start_link(Tr, InitVal) ->
tgen_server:start_link(?MODULE, InitVal, Tr, []).
set_value(Pid, Tr, Value) ->
tgen_server:call(Pid, Tr, {set_value, Value}).
get_value(Pid, Tr) ->
tgen_server:call(Pid, Tr, get_value).
start_from(Pid, Tr, Value) ->
tgen_server:call(Pid, Tr, {start_from, Value}).
stop(Pid, Tr) ->
tgen_server:stop(Pid, Tr).
@private
init(_Tr, InitVal) ->
{ok, InitVal}.
@private
handle_call(_Tr, {set_value, Value}, _From, _State) ->
{reply, ok, Value};
handle_call(Tr, {start_from, Value}, _From, _State) ->
NewPid = start_link(Tr, Value),
{reply, NewPid, Value};
handle_call(_Tr, get_value, _From, State) ->
{reply, State, State}.
@private
handle_cast(_Tr,_Request, State) ->
{noreply, State}.
@private
handle_info(_Tr,_Info, State) ->
{noreply, State}.
@private
terminate(_Tr, _Reason, _State) ->
ok.
@private
, State , Extra ) - > { ok , NewState }
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
|
ca4ccc51872d46ce08f9d526c19c4f0b1739ef22599f79a864cd3531a02b50e3 | 40ants/40ants-critic | ci.lisp | (uiop:define-package #:40ants-critic/ci
(:use #:cl)
(:import-from #:40ants-ci/jobs/linter
#:linter)
(:import-from #:40ants-ci/jobs/critic
#:critic)
(:import-from #:40ants-ci/jobs/run-tests
#:run-tests)
(:import-from #:40ants-ci/jobs/docs
#:build-docs)
(:import-from #:40ants-ci/workflow
#:defworkflow))
(in-package #:40ants-critic/ci)
(defworkflow docs
:on-push-to "master"
:on-pull-request t
:cache t
:jobs ((build-docs)))
(defworkflow ci
:on-push-to "master"
:by-cron "0 10 * * 1"
:on-pull-request t
:cache t
:jobs ((linter)
(critic)
;; (run-tests :coverage t)
))
| null | https://raw.githubusercontent.com/40ants/40ants-critic/912a23ac5f55ae47c03c0889376e54273adbfb50/src/ci.lisp | lisp | (run-tests :coverage t) | (uiop:define-package #:40ants-critic/ci
(:use #:cl)
(:import-from #:40ants-ci/jobs/linter
#:linter)
(:import-from #:40ants-ci/jobs/critic
#:critic)
(:import-from #:40ants-ci/jobs/run-tests
#:run-tests)
(:import-from #:40ants-ci/jobs/docs
#:build-docs)
(:import-from #:40ants-ci/workflow
#:defworkflow))
(in-package #:40ants-critic/ci)
(defworkflow docs
:on-push-to "master"
:on-pull-request t
:cache t
:jobs ((build-docs)))
(defworkflow ci
:on-push-to "master"
:by-cron "0 10 * * 1"
:on-pull-request t
:cache t
:jobs ((linter)
(critic)
))
|
11b8621fd764e9bbafe34f5d84ce9c8cf494d56be37323b1452618c3f0be57a9 | gas2serra/mcclim-desktop | config.lisp | (in-package :desktop-user)
(find-applications)
(configure-application (find-application :listener))
(configure-application (find-application :climacs))
(use-application-as-external-debugger "swank-debugger")
(use-application-as-debugger "swank-debugger")
;;(use-application-as-debugger "desktop-debugger")
| null | https://raw.githubusercontent.com/gas2serra/mcclim-desktop/f85d19c57d76322ae3c05f98ae43bfc8c0d0a554/dot-mcclim-desktop/config.lisp | lisp | (use-application-as-debugger "desktop-debugger") | (in-package :desktop-user)
(find-applications)
(configure-application (find-application :listener))
(configure-application (find-application :climacs))
(use-application-as-external-debugger "swank-debugger")
(use-application-as-debugger "swank-debugger")
|
65beb7ed04a60b1f790e250428aa2365b77d5d7878519a75206c4afe5fa44e21 | andreas/ocaml-graphql-tutorial | github.ml | github_request : token : string - >
* query : string - >
* variables : Yojson . Basic.json - >
* ( Yojson.Basic.json ,
* [ ` JSON of string | ` HTTP of Cohttp . Response.t * string ]
* ) result
* query:string ->
* variables:Yojson.Basic.json ->
* (Yojson.Basic.json,
* [`JSON of string | `HTTP of Cohttp.Response.t * string]
* ) result Lwt.t
*)
let github_request ~token ~query ~variables =
let open Lwt.Infix in
let uri = Uri.of_string "" in
let headers = Cohttp.Header.of_list [
"Authorization", "bearer " ^ token;
"User-Agent", "andreas/ppx_graphql";
] in
let body = `Assoc [
"query", `String query;
"variables", variables;
] in
let serialized_body = Yojson.Basic.to_string body in
Cohttp_lwt_unix.Client.post ~headers ~body:(`String serialized_body) uri >>= fun (rsp, body) ->
Cohttp_lwt_body.to_string body >|= fun body' ->
match Cohttp.Code.(code_of_status rsp.status |> is_success) with
| false ->
Error (`HTTP (rsp, body'))
| true ->
try Ok (Yojson.Basic.from_string body') with
| Yojson.Json_error err ->
Error (`JSON err)
(* executable_query : (string *
* ((Yojson.Basic.json -> 'a) -> 'a) *
* (Yojson.Basic.json -> 'b)
* ) ->
* token:string -> 'a
*)
let executable_query (query, kvariables, parse) =
let open Lwt_result.Infix in
fun ~token -> (
kvariables (fun variables ->
github_request token query variables >|= fun rsp ->
parse rsp
)
)
let find_repo = executable_query [%graphql {|
query FindRepo($owner: String!, $name: String!) {
repository(owner: $owner, name: $name) {
stargazers {
totalCount
}
issues(first: 5) {
nodes {
title
body
url
}
}
}
}
|}]
| null | https://raw.githubusercontent.com/andreas/ocaml-graphql-tutorial/b8ec76b8b2f5a3abc5ad229cbc43587dc652f854/github.ml | ocaml | executable_query : (string *
* ((Yojson.Basic.json -> 'a) -> 'a) *
* (Yojson.Basic.json -> 'b)
* ) ->
* token:string -> 'a
| github_request : token : string - >
* query : string - >
* variables : Yojson . Basic.json - >
* ( Yojson.Basic.json ,
* [ ` JSON of string | ` HTTP of Cohttp . Response.t * string ]
* ) result
* query:string ->
* variables:Yojson.Basic.json ->
* (Yojson.Basic.json,
* [`JSON of string | `HTTP of Cohttp.Response.t * string]
* ) result Lwt.t
*)
let github_request ~token ~query ~variables =
let open Lwt.Infix in
let uri = Uri.of_string "" in
let headers = Cohttp.Header.of_list [
"Authorization", "bearer " ^ token;
"User-Agent", "andreas/ppx_graphql";
] in
let body = `Assoc [
"query", `String query;
"variables", variables;
] in
let serialized_body = Yojson.Basic.to_string body in
Cohttp_lwt_unix.Client.post ~headers ~body:(`String serialized_body) uri >>= fun (rsp, body) ->
Cohttp_lwt_body.to_string body >|= fun body' ->
match Cohttp.Code.(code_of_status rsp.status |> is_success) with
| false ->
Error (`HTTP (rsp, body'))
| true ->
try Ok (Yojson.Basic.from_string body') with
| Yojson.Json_error err ->
Error (`JSON err)
let executable_query (query, kvariables, parse) =
let open Lwt_result.Infix in
fun ~token -> (
kvariables (fun variables ->
github_request token query variables >|= fun rsp ->
parse rsp
)
)
let find_repo = executable_query [%graphql {|
query FindRepo($owner: String!, $name: String!) {
repository(owner: $owner, name: $name) {
stargazers {
totalCount
}
issues(first: 5) {
nodes {
title
body
url
}
}
}
}
|}]
|
d4130be728179ddfc823311c1cf9eeffcf8996ffd67f774031afbe6f977741e3 | gowthamk/ocaml-irmin | msigs.ml | module type PATCHABLE = sig
type t
type edit
type patch = edit list
val op_diff: t -> t -> patch
val op_transform: patch -> patch -> patch * patch
end
module type MERGEABLE = sig
type t
val merge3: ancestor:t -> t -> t -> t
end
module type RESOLVEABLE = sig
type t
val resolve: t -> t -> t
include MERGEABLE with type t := t
end | null | https://raw.githubusercontent.com/gowthamk/ocaml-irmin/54775f6c3012e87d2d0308f37a2ec7b27477e887/queue/msigs.ml | ocaml | module type PATCHABLE = sig
type t
type edit
type patch = edit list
val op_diff: t -> t -> patch
val op_transform: patch -> patch -> patch * patch
end
module type MERGEABLE = sig
type t
val merge3: ancestor:t -> t -> t -> t
end
module type RESOLVEABLE = sig
type t
val resolve: t -> t -> t
include MERGEABLE with type t := t
end |
|
48ce2c2509128727074b26e3dd01b5f924d343659e982c25304a776587c4112d | ThoughtWorksInc/stonecutter | profile.clj | (ns stonecutter.test.view.profile
(:require [midje.sweet :refer :all]
[net.cgrand.enlive-html :as html]
[stonecutter.routes :as r]
[stonecutter.test.view.test-helpers :as th]
[stonecutter.translation :as t]
[stonecutter.view.profile :refer [profile]]
[stonecutter.helper :as helper]
[stonecutter.config :as config]))
(fact "profile should return some html"
(let [page (-> (th/create-request) profile)]
(html/select page [:body]) =not=> empty?))
(fact "work in progress should be removed from page"
(let [page (-> (th/create-request) profile)]
page => th/work-in-progress-removed))
(fact "sign out link should go to correct endpoint"
(let [page (-> (th/create-request) profile)]
page => (th/has-attr? [:.clj--sign-out__link] :href (r/path :sign-out))))
(fact "profile link should go to correct endpoint"
(let [page (-> (th/create-request) profile)]
page => (th/has-attr? [:.clj--profile__link] :href (r/path :show-profile))))
(fact "change password link should go to correct endpoint"
(let [page (-> (th/create-request) profile)]
page => (th/has-attr? [:.clj--change-password__link] :href (r/path :show-change-password-form))))
(fact "change profile details link should go to correct endpoint"
(let [page (-> (th/create-request) profile)]
page => (th/has-attr? [:.clj--change-profile-details__link] :href (r/path :show-change-profile-form))))
(fact "change email link should go to the correct endpoint"
(let [page (-> (th/create-request) profile)]
page => (th/has-attr? [:.clj--change-email__link] :href (r/path :show-change-email-form))))
(fact "delete account link should go to correct endpoint"
(let [page (-> (th/create-request) profile)]
page => (th/has-attr? [:.clj--delete-account__link] :href (r/path :show-delete-account-confirmation))))
(fact "download vCard link should go to correct endpoint"
(let [page (-> (th/create-request) profile)]
(html/select page [:.clj--download-vcard__link]) => (th/has-form-action? (r/path :download-vcard))))
(fact "update profile picture should post to correct endpoint"
(let [page (-> (th/create-request) profile)]
(html/select page [:.clj--card-photo-upload]) => (th/has-form-action? (r/path :update-profile-image))))
(fact
(let [translator (t/translations-fn t/translation-map)
request (-> (th/create-request translator)
(assoc-in [:context :authorised-clients] [{:name "Bloc Party" :client-id "some-client-id"}]))]
(th/test-translations "profile" profile request)))
(fact "csrf token should be inserted"
(let [page (-> (th/create-request) (assoc-in [:context :confirmed?] false) profile)]
page => (th/element-exists? [:input#__anti-forgery-token])))
(facts "about displaying navigation bar"
(fact "apps and users links are not displayed if the user role is not admin"
(let [page (-> (th/create-request)
profile)]
(-> page (html/select [:.clj--apps-list__link])) => empty?
(-> page (html/select [:.clj--users-list__link])) => empty?))
(fact "apps and users links are displayed and go to the correct endpoint if the user role is admin"
(let [page (-> (th/create-request)
(assoc-in [:session :role] (:admin config/roles))
profile)]
(-> page (html/select [:.clj--apps-list__link])) =not=> empty?
(-> page (html/select [:.clj--user-list__link])) =not=> empty?
page => (th/has-attr? [:.clj--apps-list__link] :href (r/path :show-apps-list))
page => (th/has-attr? [:.clj--user-list__link] :href (r/path :show-user-list)))))
(facts "about flash messages"
(fact "no flash messages are displayed by default"
(let [page (-> (th/create-request)
profile)]
(-> page (html/select [:.clj--flash-message-container])) => empty?))
(tabular
(fact "appropriate flash message is displayed on page when a flash key is included in the request"
(let [page (-> (th/create-request) (assoc :flash ?flash-key) profile)]
(-> page (html/select [:.clj--flash-message-container])) =not=> empty?
(-> page (html/select [:.clj--flash-message-text]) first :attrs :data-l8n)
=> ?translation-key))
?flash-key ?translation-key
:email-changed "content:flash/email-changed"
:password-changed "content:flash/password-changed"
:email-confirmed "content:flash/email-confirmed"
:confirmation-email-sent "content:flash/confirmation-email-sent"
:email-already-confirmed "content:flash/email-already-confirmed"))
(facts "about image upload errors"
(fact "no errors are displayed by default"
(let [page (-> (th/create-request)
profile)]
page => (th/has-attr? [:.clj--profile-image-error-container] :hidden "hidden")))
(tabular
(fact "appropriate error message is displayed on page when an image error key is included in the request"
(let [page (-> (th/create-request) (assoc :flash ?error-key) profile)]
(-> page (html/select [:.clj--profile-image-error-container])) =not=> empty?
(-> page (html/select [:.clj--profile-image-error-text]) first :attrs :data-l8n)
=> ?translation-key))
?error-key ?translation-key
:not-image "content:upload-profile-picture/file-not-image-validation-message"
:too-large "content:upload-profile-picture/file-too-large-validation-message"
:unsupported-extension "content:upload-profile-picture/file-type-not-supported-validation-message"))
(facts "about displaying email confirmation status"
(fact "the unconfirmed email message is removed when :confirmed? context is not false"
(let [page (-> (th/create-request) profile)]
(-> page (html/select [:.clj--unconfirmed-email-message-container])) => empty?))
(fact "accounts with unconfirmed email addresses display unconfirmed message as if it were a flash message"
(let [page (-> (th/create-request)
(assoc-in [:context :confirmed?] false)
(assoc-in [:session :user-login] "")
profile)]
(-> page (html/select [:.clj--unconfirmed-email-message-container])) =not=> empty?
(-> page (html/select [:.clj--unconfirmed-email]) first html/text) => "")))
(facts "about displaying authorised clients"
(fact "names of authorised clients are displayed"
(let [page (-> (th/create-request)
(assoc-in [:context :authorised-clients] [{:name "Bloc Party"}
{:name "Tabletennis Party"}])
profile)]
(-> page
(html/select [:.func--app__list])
first
html/text) => (contains #"Bloc Party[\s\S]+Tabletennis Party")))
(fact "unshare card button links include the client_id query param"
(let [client-id "bloc_party_client-id"
page (-> (th/create-request)
(assoc-in [:context :authorised-clients] [{:name "Bloc Party" :client-id client-id}])
profile)]
page => (th/has-attr? [:.clj--app-item__unshare-link]
:href (str (r/path :show-unshare-profile-card) "?client_id=" client-id))))
(fact "empty application-list item is used when there are no authorised clients"
(let [page (-> (th/create-request)
profile)]
(html/select page [:.clj--authorised-app__list-item--empty]) =not=> empty?
(html/select page [:.clj--authorised-app__list-item]) => empty?)))
(facts "about displaying profile card"
(let [page (-> (th/create-request)
(assoc-in [:context :user-login] "")
(assoc-in [:context :user-first-name] "Frank")
(assoc-in [:context :user-last-name] "Lasty")
(assoc-in [:context :user-profile-picture] "/images/temp-avatar-300x300.png")
profile)]
(fact "it should display email address"
(-> page (html/select [:.clj--card-email]) first html/text) => "")
(fact "it should display full name"
(-> page (html/select [:.clj--card-name]) first html/text) => "Frank Lasty")
(fact "it should display profile picture"
(-> page (html/select [:.clj--card-image :img]) first :attrs :src) => "/images/temp-avatar-300x300.png")))
| null | https://raw.githubusercontent.com/ThoughtWorksInc/stonecutter/37ed22dd276ac652176c4d880e0f1b0c1e27abfe/test/stonecutter/test/view/profile.clj | clojure | (ns stonecutter.test.view.profile
(:require [midje.sweet :refer :all]
[net.cgrand.enlive-html :as html]
[stonecutter.routes :as r]
[stonecutter.test.view.test-helpers :as th]
[stonecutter.translation :as t]
[stonecutter.view.profile :refer [profile]]
[stonecutter.helper :as helper]
[stonecutter.config :as config]))
(fact "profile should return some html"
(let [page (-> (th/create-request) profile)]
(html/select page [:body]) =not=> empty?))
(fact "work in progress should be removed from page"
(let [page (-> (th/create-request) profile)]
page => th/work-in-progress-removed))
(fact "sign out link should go to correct endpoint"
(let [page (-> (th/create-request) profile)]
page => (th/has-attr? [:.clj--sign-out__link] :href (r/path :sign-out))))
(fact "profile link should go to correct endpoint"
(let [page (-> (th/create-request) profile)]
page => (th/has-attr? [:.clj--profile__link] :href (r/path :show-profile))))
(fact "change password link should go to correct endpoint"
(let [page (-> (th/create-request) profile)]
page => (th/has-attr? [:.clj--change-password__link] :href (r/path :show-change-password-form))))
(fact "change profile details link should go to correct endpoint"
(let [page (-> (th/create-request) profile)]
page => (th/has-attr? [:.clj--change-profile-details__link] :href (r/path :show-change-profile-form))))
(fact "change email link should go to the correct endpoint"
(let [page (-> (th/create-request) profile)]
page => (th/has-attr? [:.clj--change-email__link] :href (r/path :show-change-email-form))))
(fact "delete account link should go to correct endpoint"
(let [page (-> (th/create-request) profile)]
page => (th/has-attr? [:.clj--delete-account__link] :href (r/path :show-delete-account-confirmation))))
(fact "download vCard link should go to correct endpoint"
(let [page (-> (th/create-request) profile)]
(html/select page [:.clj--download-vcard__link]) => (th/has-form-action? (r/path :download-vcard))))
(fact "update profile picture should post to correct endpoint"
(let [page (-> (th/create-request) profile)]
(html/select page [:.clj--card-photo-upload]) => (th/has-form-action? (r/path :update-profile-image))))
(fact
(let [translator (t/translations-fn t/translation-map)
request (-> (th/create-request translator)
(assoc-in [:context :authorised-clients] [{:name "Bloc Party" :client-id "some-client-id"}]))]
(th/test-translations "profile" profile request)))
(fact "csrf token should be inserted"
(let [page (-> (th/create-request) (assoc-in [:context :confirmed?] false) profile)]
page => (th/element-exists? [:input#__anti-forgery-token])))
(facts "about displaying navigation bar"
(fact "apps and users links are not displayed if the user role is not admin"
(let [page (-> (th/create-request)
profile)]
(-> page (html/select [:.clj--apps-list__link])) => empty?
(-> page (html/select [:.clj--users-list__link])) => empty?))
(fact "apps and users links are displayed and go to the correct endpoint if the user role is admin"
(let [page (-> (th/create-request)
(assoc-in [:session :role] (:admin config/roles))
profile)]
(-> page (html/select [:.clj--apps-list__link])) =not=> empty?
(-> page (html/select [:.clj--user-list__link])) =not=> empty?
page => (th/has-attr? [:.clj--apps-list__link] :href (r/path :show-apps-list))
page => (th/has-attr? [:.clj--user-list__link] :href (r/path :show-user-list)))))
(facts "about flash messages"
(fact "no flash messages are displayed by default"
(let [page (-> (th/create-request)
profile)]
(-> page (html/select [:.clj--flash-message-container])) => empty?))
(tabular
(fact "appropriate flash message is displayed on page when a flash key is included in the request"
(let [page (-> (th/create-request) (assoc :flash ?flash-key) profile)]
(-> page (html/select [:.clj--flash-message-container])) =not=> empty?
(-> page (html/select [:.clj--flash-message-text]) first :attrs :data-l8n)
=> ?translation-key))
?flash-key ?translation-key
:email-changed "content:flash/email-changed"
:password-changed "content:flash/password-changed"
:email-confirmed "content:flash/email-confirmed"
:confirmation-email-sent "content:flash/confirmation-email-sent"
:email-already-confirmed "content:flash/email-already-confirmed"))
(facts "about image upload errors"
(fact "no errors are displayed by default"
(let [page (-> (th/create-request)
profile)]
page => (th/has-attr? [:.clj--profile-image-error-container] :hidden "hidden")))
(tabular
(fact "appropriate error message is displayed on page when an image error key is included in the request"
(let [page (-> (th/create-request) (assoc :flash ?error-key) profile)]
(-> page (html/select [:.clj--profile-image-error-container])) =not=> empty?
(-> page (html/select [:.clj--profile-image-error-text]) first :attrs :data-l8n)
=> ?translation-key))
?error-key ?translation-key
:not-image "content:upload-profile-picture/file-not-image-validation-message"
:too-large "content:upload-profile-picture/file-too-large-validation-message"
:unsupported-extension "content:upload-profile-picture/file-type-not-supported-validation-message"))
(facts "about displaying email confirmation status"
(fact "the unconfirmed email message is removed when :confirmed? context is not false"
(let [page (-> (th/create-request) profile)]
(-> page (html/select [:.clj--unconfirmed-email-message-container])) => empty?))
(fact "accounts with unconfirmed email addresses display unconfirmed message as if it were a flash message"
(let [page (-> (th/create-request)
(assoc-in [:context :confirmed?] false)
(assoc-in [:session :user-login] "")
profile)]
(-> page (html/select [:.clj--unconfirmed-email-message-container])) =not=> empty?
(-> page (html/select [:.clj--unconfirmed-email]) first html/text) => "")))
(facts "about displaying authorised clients"
(fact "names of authorised clients are displayed"
(let [page (-> (th/create-request)
(assoc-in [:context :authorised-clients] [{:name "Bloc Party"}
{:name "Tabletennis Party"}])
profile)]
(-> page
(html/select [:.func--app__list])
first
html/text) => (contains #"Bloc Party[\s\S]+Tabletennis Party")))
(fact "unshare card button links include the client_id query param"
(let [client-id "bloc_party_client-id"
page (-> (th/create-request)
(assoc-in [:context :authorised-clients] [{:name "Bloc Party" :client-id client-id}])
profile)]
page => (th/has-attr? [:.clj--app-item__unshare-link]
:href (str (r/path :show-unshare-profile-card) "?client_id=" client-id))))
(fact "empty application-list item is used when there are no authorised clients"
(let [page (-> (th/create-request)
profile)]
(html/select page [:.clj--authorised-app__list-item--empty]) =not=> empty?
(html/select page [:.clj--authorised-app__list-item]) => empty?)))
(facts "about displaying profile card"
(let [page (-> (th/create-request)
(assoc-in [:context :user-login] "")
(assoc-in [:context :user-first-name] "Frank")
(assoc-in [:context :user-last-name] "Lasty")
(assoc-in [:context :user-profile-picture] "/images/temp-avatar-300x300.png")
profile)]
(fact "it should display email address"
(-> page (html/select [:.clj--card-email]) first html/text) => "")
(fact "it should display full name"
(-> page (html/select [:.clj--card-name]) first html/text) => "Frank Lasty")
(fact "it should display profile picture"
(-> page (html/select [:.clj--card-image :img]) first :attrs :src) => "/images/temp-avatar-300x300.png")))
|
|
df11067347c9b206ec0251cf243628b7f73eb3ac8c99c785fb3b7380d05761aa | mk270/archipelago | game.mli |
Archipelago , a multi - user dungeon ( MUD ) server , by ( C ) 2009 - 2013
This programme is free software ; you may redistribute and/or modify
it under the terms of the GNU Affero General Public Licence as published by
the Free Software Foundation , either version 3 of said Licence , or
( at your option ) any later version .
Archipelago, a multi-user dungeon (MUD) server, by Martin Keegan
Copyright (C) 2009-2013 Martin Keegan
This programme is free software; you may redistribute and/or modify
it under the terms of the GNU Affero General Public Licence as published by
the Free Software Foundation, either version 3 of said Licence, or
(at your option) any later version.
*)
open Model
val init : unit -> unit
val fini : unit -> unit
val emitl : mudobject -> string -> unit
val current_players : unit -> mudobject list
val add_current_player : mudobject -> unit
val remove_current_player : mudobject -> unit
val output_iter : (mudobject -> string -> unit) -> unit
wrapper for workqueue
type thunk = unit -> unit
val pump_till_current : unit -> unit
val top_priority : unit -> float
val workqueue_post : delay : float -> thunk -> unit
(* wrapper for reset *)
val do_shutdown : unit -> bool
val set_shutdown : unit -> unit
| null | https://raw.githubusercontent.com/mk270/archipelago/4241bdc994da6d846637bcc079051405ee905c9b/src/game/game.mli | ocaml | wrapper for reset |
Archipelago , a multi - user dungeon ( MUD ) server , by ( C ) 2009 - 2013
This programme is free software ; you may redistribute and/or modify
it under the terms of the GNU Affero General Public Licence as published by
the Free Software Foundation , either version 3 of said Licence , or
( at your option ) any later version .
Archipelago, a multi-user dungeon (MUD) server, by Martin Keegan
Copyright (C) 2009-2013 Martin Keegan
This programme is free software; you may redistribute and/or modify
it under the terms of the GNU Affero General Public Licence as published by
the Free Software Foundation, either version 3 of said Licence, or
(at your option) any later version.
*)
open Model
val init : unit -> unit
val fini : unit -> unit
val emitl : mudobject -> string -> unit
val current_players : unit -> mudobject list
val add_current_player : mudobject -> unit
val remove_current_player : mudobject -> unit
val output_iter : (mudobject -> string -> unit) -> unit
wrapper for workqueue
type thunk = unit -> unit
val pump_till_current : unit -> unit
val top_priority : unit -> float
val workqueue_post : delay : float -> thunk -> unit
val do_shutdown : unit -> bool
val set_shutdown : unit -> unit
|
88253cd9b1406bd99557d4d24dadbe74716c410ab37cf2fba54ca46faf2f743b | privet-kitty/dufy | spectrum.lisp | ;;;
Spectrum , Observer , and
;;;
(in-package :dufy/core)
FIXME : ABCL signals an error and claims that FUNCTION types are not
a legal argument to TYPEP .
(deftype spectrum-function ()
#-abcl '(function * (values double-float &optional))
#+abcl t)
(define-colorspace spectrum (spectrum)
:arg-types (spectrum-function)
:return-types (spectrum-function)
:documentation "A spectrum is just a function which receives a real number as
a wavelength (nm) and returns a double-float. The ftype is (function * (values
double-float &optional))")
(defun gen-spectrum (spectrum-seq &optional (begin-wl 360) (end-wl 830))
"GEN-SPECTRUM returns a spectral power distribution
function, #'(lambda (wavelength-nm) ...), which interpolates SPECTRUM-SEQ
linearly.
Note: SPECTRUM-SEQ must be a sequence of double-float. If the type of
SPECTRUM-SEQ is (simple-array double-float (*)), it is not copied but
referenced, otherwise it is copied by (coerce spectrum-seq '(simple-array
double-float (*)))."
(check-type spectrum-seq sequence)
(let* ((spectrum-arr (if (typep spectrum-seq '(simple-array double-float (*)))
spectrum-seq
(coerce spectrum-seq '(simple-array double-float (*)))))
(size (- (length spectrum-arr) 1))
(begin-wl-f (float begin-wl 1d0))
(end-wl-f (float end-wl 1d0)))
(if (= size (- end-wl begin-wl))
If SPECTRUM - SEQ is defined just for each integer , the spectrum
;; function can be simpler and more efficient:
#'(lambda (wl-nm)
(declare (optimize (speed 3) (safety 1)))
(multiple-value-bind (quot rem)
(floor (- (clamp (float wl-nm 1d0) begin-wl-f end-wl-f)
begin-wl-f))
(lerp rem
(aref spectrum-arr quot)
(aref spectrum-arr (min (1+ quot) size)))))
(let* ((band (/ (- end-wl-f begin-wl-f) size))
(/band (/ band)))
#'(lambda (wl-nm)
(declare (optimize (speed 3) (safety 1)))
(let* ((wl-offset (- (clamp (float wl-nm 1d0) begin-wl-f end-wl-f)
begin-wl-f))
(frac (mod wl-offset band))
(coef (* frac /band))
(idx (round (* (- wl-offset frac) /band))))
(lerp coef
(aref spectrum-arr idx)
(aref spectrum-arr (min (+ idx 1) size)))))))))
(defun approximate-spectrum (spectrum &key (begin-wl 360d0) (end-wl 830d0) (band 1d0))
"Generates an approximate spectrum of SPECTRUM by pieacewise linearization. It
is used to lighten a \"heavy\" spectrum function."
(declare (optimize (speed 3) (safety 1))
(spectrum-function spectrum))
(with-ensuring-type double-float (begin-wl end-wl band)
(let* ((partitions (max 2 (round (/ (- end-wl begin-wl) band))))
(partitions-f (float partitions 1d0))
(points (make-array (1+ partitions) :element-type 'double-float)))
(declare (fixnum partitions))
(gen-spectrum (loop for i from 0 to partitions
for wl = (lerp (/ i partitions-f) begin-wl end-wl)
do (setf (aref points i) (funcall spectrum wl))
finally (return points))
begin-wl
end-wl))))
;;;
Observer
;;;
(defstruct (observer (:constructor %make-observer))
"OBSERVER is a structure of color matching functions."
(begin-wl 360 :type (integer 0))
(end-wl 830 :type (integer 0))
(cmf-table nil :type (simple-array double-float (* 3)))
Below are ( linear ) interpolation functions for cmf - table .
(cmf-x nil :type spectrum-function)
(cmf-y nil :type spectrum-function)
(cmf-z nil :type spectrum-function)
(cmf nil :type (function * (values double-float double-float double-float &optional))))
(defmethod print-object ((obs observer) stream)
(let ((*print-array* nil))
(call-next-method)))
(defun make-observer (cmf-table &optional (begin-wl 360) (end-wl 830))
"Generates an observer object based on CMF arrays, which must be (SIMPLE-ARRAY
DOUBLE-FLOAT (* 3)). The response outside the interval [begin-wl, end-wl] is
regarded as 0."
(let ((begin-wl-f (float begin-wl 1d0))
(end-wl-f (float end-wl 1d0)))
(labels ((gen-cmf-1dim (arr num &optional (begin-wl 360) (end-wl 830))
;; FIXME: verbose, almost equivalent code to GEN-SPECTRUM
(declare ((simple-array double-float (* 3)) arr))
(let ((size (- (array-dimension arr 0) 1)))
(if (= size (- end-wl begin-wl))
#'(lambda (wl)
(declare (optimize (speed 3) (safety 1)))
(let ((wl (float wl 1d0)))
(if (or (< wl begin-wl-f) (< end-wl-f wl))
0d0
(multiple-value-bind (quot rem)
(floor (- wl begin-wl-f))
(lerp rem
(aref arr quot num)
(aref arr (min (1+ quot) size) num))))))
(let* ((band (/ (- end-wl-f begin-wl-f) size))
(/band (/ band)))
#'(lambda (wl)
(declare (optimize (speed 3) (safety 1)))
(let ((wl (float wl 1d0)))
(if (or (< wl begin-wl-f) (< end-wl-f wl))
0d0
(let* ((wl-offset (- wl begin-wl-f))
(frac (mod wl-offset band))
(coef (* frac /band))
(idx (round (* (- wl-offset frac) /band))))
(lerp coef
(aref arr idx num)
(aref arr (min (+ idx 1) size) num))))))))))
(gen-cmf-3dims (arr &optional (begin-wl 360) (end-wl 830))
(declare ((simple-array double-float (* 3)) arr))
(let ((size (- (array-dimension arr 0) 1)))
(if (= size (- end-wl begin-wl))
#'(lambda (wl)
(declare (optimize (speed 3) (safety 1)))
(let ((wl (float wl 1d0)))
(if (or (< wl begin-wl-f) (< end-wl-f wl))
(values 0d0 0d0 0d0)
(multiple-value-bind (quot rem)
(floor (- wl begin-wl-f))
(values (lerp rem
(aref arr quot 0)
(aref arr (min (1+ quot) size) 0))
(lerp rem
(aref arr quot 1)
(aref arr (min (1+ quot) size) 1))
(lerp rem
(aref arr quot 2)
(aref arr (min (1+ quot) size) 2)))))))
(let* ((band (/ (- end-wl-f begin-wl-f) size))
(/band (/ band)))
#'(lambda (wl)
(declare (optimize (speed 3) (safety 1)))
(let ((wl (float wl 1d0)))
(if (or (< wl begin-wl-f) (< end-wl-f wl))
(values 0d0 0d0 0d0)
(let* ((wl-offset (- wl begin-wl-f))
(frac (mod wl-offset band))
(coef (* frac /band))
(idx (round (* (- wl-offset frac) /band)))
(idx+1 (min (1+ idx) size)))
(values (lerp coef
(aref arr idx 0)
(aref arr idx+1 0))
(lerp coef
(aref arr idx 1)
(aref arr idx+1 1))
(lerp coef
(aref arr idx 2)
(aref arr idx+1 2))))))))))))
(%make-observer
:begin-wl begin-wl
:end-wl end-wl
:cmf-table cmf-table
:cmf-x (gen-cmf-1dim cmf-table 0 begin-wl end-wl)
:cmf-y (gen-cmf-1dim cmf-table 1 begin-wl end-wl)
:cmf-z (gen-cmf-1dim cmf-table 2 begin-wl end-wl)
:cmf (gen-cmf-3dims cmf-table begin-wl end-wl)))))
(defparameter +obs-cie1931+ (make-observer +cmf-table-cie1931+)
"CIE 1931 Standard Colorimetric Observer (2-degree).")
(defparameter +obs-cie1964+ (make-observer +cmf-table-cie1964+)
"CIE 1964 Standard Colorimetric Observer (10-degree).")
;; s0, s1, s2 for illuminant series D
;; See
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter +s0-table+
(make-array 54
:element-type 'double-float
:initial-contents '(0.04d0 6d0 29.6d0 55.3d0 57.3d0 61.8d0 61.5d0 68.8d0 63.4d0 65.8d0 94.8d0 104.8d0 105.9d0 96.8d0 113.9d0 125.6d0 125.5d0 121.3d0 121.3d0 113.5d0 113.1d0 110.8d0 106.5d0 108.8d0 105.3d0 104.4d0 100d0 96d0 95.1d0 89.1d0 90.5d0 90.3d0 88.4d0 84d0 85.1d0 81.9d0 82.6d0 84.9d0 81.3d0 71.9d0 74.3d0 76.4d0 63.3d0 71.7d0 77d0 65.2d0 47.7d0 68.6d0 65d0 66d0 61d0 53.3d0 58.9d0 61.9d0)))
(defparameter +s1-table+
(make-array 54
:element-type 'double-float
:initial-contents '(0.02d0 4.5d0 22.4d0 42d0 40.6d0 41.6d0 38d0 42.4d0 38.5d0 35d0 43.4d0 46.3d0 43.9d0 37.1d0 36.7d0 35.9d0 32.6d0 27.9d0 24.3d0 20.1d0 16.2d0 13.2d0 8.6d0 6.1d0 4.2d0 1.9d0 0d0 -1.6d0 -3.5d0 -3.5d0 -5.8d0 -7.2d0 -8.6d0 -9.5d0 -10.9d0 -10.7d0 -12d0 -14d0 -13.6d0 -12d0 -13.3d0 -12.9d0 -10.6d0 -11.6d0 -12.2d0 -10.2d0 -7.8d0 -11.2d0 -10.4d0 -10.6d0 -9.7d0 -8.3d0 -9.3d0 -9.8d0)))
(defparameter +s2-table+
(make-array 54
:element-type 'double-float
:initial-contents '(0d0 2d0 4d0 8.5d0 7.8d0 6.7d0 5.3d0 6.1d0 2d0 1.2d0 -1.1d0 -0.5d0 -0.7d0 -1.2d0 -2.6d0 -2.9d0 -2.8d0 -2.6d0 -2.6d0 -1.8d0 -1.5d0 -1.3d0 -1.2d0 -1d0 -0.5d0 -0.3d0 0d0 0.2d0 0.5d0 2.1d0 3.2d0 4.1d0 4.7d0 5.1d0 6.7d0 7.3d0 8.6d0 9.8d0 10.2d0 8.3d0 9.6d0 8.5d0 7d0 7.6d0 8d0 6.7d0 5.2d0 7.4d0 6.8d0 7d0 6.4d0 5.5d0 6.1d0 6.5d0))))
(defun make-illum-d-spectrum-array (temperature &optional (begin-wl 300) (end-wl 830))
(declare (optimize (speed 3) (safety 1)))
(check-type begin-wl fixnum)
(check-type end-wl fixnum)
(let ((s0-func (load-time-value (gen-spectrum +s0-table+ 300 830) t))
(s1-func (load-time-value (gen-spectrum +s1-table+ 300 830) t))
(s2-func (load-time-value (gen-spectrum +s2-table+ 300 830) t)))
(declare (type spectrum-function s0-func s1-func s2-func))
(labels ((calc-xd (temp)
(let ((/temp (/ temp)))
(if (<= temp 7000d0)
(+ 0.244063d0 (* /temp (+ 0.09911d3 (* /temp (+ 2.9678d6 (* /temp -4.607d9))))))
(+ 0.237040d0 (* /temp (+ 0.24748d3 (* /temp (+ 1.9018d6 (* /temp -2.0064d9)))))))))
(calc-yd (xd)
(+ -0.275d0 (* xd (+ 2.870d0 (* xd -3d0))))))
(let* ((xd (calc-xd (float temperature 1d0)))
(yd (calc-yd xd))
(denom (+ 0.0241d0 (* xd 0.2562d0) (* yd -0.7341d0)))
(m1 (/ (+ -1.3515d0 (* xd -1.7703d0) (* yd 5.9114d0)) denom))
(m2 (/ (+ 0.03d0 (* xd -31.4424d0) (* yd 30.0717d0)) denom))
(spd-arr (make-array (1+ (- end-wl begin-wl))
:element-type 'double-float
:initial-element 0d0)))
(loop for wl from begin-wl to end-wl
do (setf (aref spd-arr (- wl begin-wl))
(+ (funcall s0-func wl)
(* m1 (funcall s1-func wl))
(* m2 (funcall s2-func wl)))))
spd-arr))))
(defun gen-illum-d-spectrum (temperature &key rectify)
"Generates the spectrum of the illuminant series D for a given
temperature (from 300 nm to 830 nm with band-width 1 nm). If RECTIFY is true,
the temperature multiplied by 1.4388/1.438 is used instead. (roughly 6504K for
6500K, etc.)"
(let ((temp (if rectify
(* temperature #.(/ 1.43880d0 1.438d0))
temperature)))
(gen-spectrum (make-illum-d-spectrum-array temp 300 830)
300 830)))
(declaim (inline bb-spectrum))
(defun bb-spectrum (wavelength-nm &optional (temperature 5000d0))
"Spectrum function of a blackbody. Note that it is not normalized."
(declare (optimize (speed 3) (safety 1)))
(let ((wlm (* (float wavelength-nm 1d0) 1d-9)))
(check-type wlm (double-float 0d0))
(/ (* 3.74183d-16 (expt wlm -5d0))
(- (exp (/ 1.4388d-2 (* wlm (float temperature 1d0)))) 1d0))))
(declaim (inline optimal-spectrum-peak))
(defun optimal-spectrum-peak (wavelength-nm &optional (wl1 300d0) (wl2 830d0))
"Spectrum function of optimal colors:
f(x) = 1d0 if wl1 <= x <= wl2,
f(x) = 0d0 otherwise."
(declare (optimize (speed 3) (safety 1)))
(if (<= wl1 wavelength-nm wl2) 1d0 0d0))
(declaim (inline optimal-spectrum-trough))
(defun optimal-spectrum-trough (wavelength-nm &optional (wl1 300d0) (wl2 830d0))
"Spectrum function of optimal colors:
f(x) = 1d0 if x <= wl2 or wl1 <= x,
f(x) = 0d0 otherwise."
(declare (optimize (speed 3) (safety 1)))
(if (or (<= wavelength-nm wl1)
(<= wl2 wavelength-nm))
1d0 0d0))
(declaim (inline flat-spectrum))
(defun flat-spectrum (wavelength-nm)
"(constantly 1d0)"
(declare (optimize (speed 3) (safety 0)))
(declare (ignore wavelength-nm))
1d0)
(defun empty-spectrum ()
"Used internally instead of NIL."
0d0)
;;;
;;; Illuminant, White Point
;;;
(defstruct (illuminant (:constructor %make-illuminant)
(:copier nil))
(x 1d0 :type double-float)
(z 1d0 :type double-float)
(spectrum #'empty-spectrum :type spectrum-function)
(observer +obs-cie1931+ :type observer)
;; used in xyz-to-spectrum conversion
(to-spectrum-matrix +empty-matrix+ :type (simple-array double-float (3 3))))
(defun illuminant-xy (illuminant)
"Returns the xy chromacity coordinates of a given illuminant."
(declare (optimize (speed 3) (safety 1))
(type illuminant illuminant))
(let* ((x (illuminant-x illuminant))
(z (illuminant-z illuminant))
(sum (+ x 1d0 z)))
(if (= sum 0)
(values 0d0 0d0)
(values (/ x sum) (/ sum)))))
(declaim (inline illuminant-no-spd-p))
(defun illuminant-no-spd-p (illuminant)
(eq #'empty-spectrum (illuminant-spectrum illuminant)))
(define-condition no-spd-error (simple-error)
((illuminant :initarg :illuminant
:initform nil
:accessor cond-illuminant))
(:report (lambda (condition stream)
(let ((*print-array* nil))
(format stream "The illuminant has no spectrum: ~A"
(cond-illuminant condition))))))
(defun %spectrum-to-xyz (spectrum illuminant-spd observer &optional (begin-wl 360) (end-wl 830) (band 1))
(declare (optimize (speed 3) (safety 1))
(spectrum-function spectrum illuminant-spd))
"Is an internal function and will be called in SPECTRUM-TO-XYZ in another module.
SPECTRUM := spectral reflectance (or transmittance) ILLUMINANT-SPD :=
SPD of illuminant"
(let ((x 0d0) (y 0d0) (z 0d0) (max-y 0d0)
(cmf (observer-cmf observer)))
(declare (double-float x y z max-y))
(loop for wl from begin-wl to end-wl by band
do (let* ((p (funcall illuminant-spd wl))
(reflec (funcall spectrum wl))
(factor (* p reflec)))
(multiple-value-bind (x-match y-match z-match) (funcall cmf wl)
(incf x (* x-match factor))
(incf y (* y-match factor))
(incf z (* z-match factor))
(incf max-y (* y-match p)))))
(let ((normalizing-factor (/ max-y)))
(values (* x normalizing-factor)
(* y normalizing-factor)
(* z normalizing-factor)))))
(defun calc-to-spectrum-matrix (illuminant-spd observer &optional (begin-wl 360) (end-wl 830) (band 1))
(declare (optimize (speed 3) (safety 1)))
"The returned matrix will be used in XYZ-to-spectrum conversion."
(let ((mat (load-time-value
(make-array '(3 3) :element-type 'double-float
:initial-element 0d0))))
(multiple-value-bind (a00 a10 a20)
(%spectrum-to-xyz (observer-cmf-x observer) illuminant-spd observer begin-wl end-wl band)
(multiple-value-bind (a01 a11 a21)
(%spectrum-to-xyz (observer-cmf-y observer) illuminant-spd observer begin-wl end-wl band)
(multiple-value-bind (a02 a12 a22)
(%spectrum-to-xyz (observer-cmf-z observer) illuminant-spd observer begin-wl end-wl band)
(setf (aref mat 0 0) a00
(aref mat 0 1) a01
(aref mat 0 2) a02
(aref mat 1 0) a10
(aref mat 1 1) a11
(aref mat 1 2) a12
(aref mat 2 0) a20
(aref mat 2 1) a21
(aref mat 2 2) a22))))
(invert-matrix mat)))
(defun make-illuminant (&key x z spectrum (observer +obs-cie1931+) (compile-time nil) (begin-wl 360) (end-wl 830) (band 1))
(declare (ignore compile-time))
"Generates an illuminant from a spectral distribution or a white point. If
SPECTRUM is nil, the returned illuminant contains only a white point. If X and Z
are nil, on the other hand, the white point (X, 1d0, Z) is automatically
calculated from the spectrum. You can also specify the both though you should
note that no error occurs even if the given white point and SPD contradicts to
each other.
(make-illuminant :x 1.0 :z 1.0)
= > illuminant without SPD
(make-illuminant :x 1.0 :z 1.0 :spectrum #'flat-spectrum)
(make-illuminant :spectrum #'flat-spectrum)
= > ( almost same ) illuminants with SPD
(make-illuminant :x 0.9 :z 1.1 :spectrum #'flat-spectrum)
= > ( valid but meaningless ) illuminant with SPD
If X and Y are NIL and COMPILE-TIME is T, the white point is
calculated at compile time. (Avoid side effects in this case as the
parameters are EVALed.)"
(macrolet
((make (x z)
`(%make-illuminant
:x (float ,x 1d0)
:z (float ,z 1d0)
:spectrum (or spectrum #'empty-spectrum)
:observer observer
:to-spectrum-matrix (if spectrum
(calc-to-spectrum-matrix spectrum observer begin-wl end-wl band)
+empty-matrix+))))
(if (and (null x) (null z))
(multiple-value-bind (x y z)
(%spectrum-to-xyz #'flat-spectrum spectrum observer begin-wl end-wl band)
(declare (ignore y))
(make x z))
(make x z))))
(define-compiler-macro make-illuminant (&whole form &key x z spectrum (observer '+obs-cie1931+) (begin-wl 360) (end-wl 830) (band 1) (compile-time nil))
(if (and compile-time (null x) (null z))
(let ((spctrm (eval spectrum))
(obs (eval observer))
(bwl (eval begin-wl))
(ewl (eval end-wl))
(bnd (eval band)))
(multiple-value-bind (x y z)
(%spectrum-to-xyz #'flat-spectrum spctrm obs bwl ewl bnd)
(declare (ignore y))
`(%make-illuminant
:x (float ,x 1d0)
:z (float ,z 1d0)
:spectrum ,spectrum
:observer ,observer
:to-spectrum-matrix ,(calc-to-spectrum-matrix spctrm obs bwl ewl bnd))))
form))
| null | https://raw.githubusercontent.com/privet-kitty/dufy/c6ad03a9fca16a759c1c52449ac88420a536feca/src/core/spectrum.lisp | lisp |
function can be simpler and more efficient:
FIXME: verbose, almost equivalent code to GEN-SPECTRUM
s0, s1, s2 for illuminant series D
See
Illuminant, White Point
used in xyz-to-spectrum conversion | Spectrum , Observer , and
(in-package :dufy/core)
FIXME : ABCL signals an error and claims that FUNCTION types are not
a legal argument to TYPEP .
(deftype spectrum-function ()
#-abcl '(function * (values double-float &optional))
#+abcl t)
(define-colorspace spectrum (spectrum)
:arg-types (spectrum-function)
:return-types (spectrum-function)
:documentation "A spectrum is just a function which receives a real number as
a wavelength (nm) and returns a double-float. The ftype is (function * (values
double-float &optional))")
(defun gen-spectrum (spectrum-seq &optional (begin-wl 360) (end-wl 830))
"GEN-SPECTRUM returns a spectral power distribution
function, #'(lambda (wavelength-nm) ...), which interpolates SPECTRUM-SEQ
linearly.
Note: SPECTRUM-SEQ must be a sequence of double-float. If the type of
SPECTRUM-SEQ is (simple-array double-float (*)), it is not copied but
referenced, otherwise it is copied by (coerce spectrum-seq '(simple-array
double-float (*)))."
(check-type spectrum-seq sequence)
(let* ((spectrum-arr (if (typep spectrum-seq '(simple-array double-float (*)))
spectrum-seq
(coerce spectrum-seq '(simple-array double-float (*)))))
(size (- (length spectrum-arr) 1))
(begin-wl-f (float begin-wl 1d0))
(end-wl-f (float end-wl 1d0)))
(if (= size (- end-wl begin-wl))
If SPECTRUM - SEQ is defined just for each integer , the spectrum
#'(lambda (wl-nm)
(declare (optimize (speed 3) (safety 1)))
(multiple-value-bind (quot rem)
(floor (- (clamp (float wl-nm 1d0) begin-wl-f end-wl-f)
begin-wl-f))
(lerp rem
(aref spectrum-arr quot)
(aref spectrum-arr (min (1+ quot) size)))))
(let* ((band (/ (- end-wl-f begin-wl-f) size))
(/band (/ band)))
#'(lambda (wl-nm)
(declare (optimize (speed 3) (safety 1)))
(let* ((wl-offset (- (clamp (float wl-nm 1d0) begin-wl-f end-wl-f)
begin-wl-f))
(frac (mod wl-offset band))
(coef (* frac /band))
(idx (round (* (- wl-offset frac) /band))))
(lerp coef
(aref spectrum-arr idx)
(aref spectrum-arr (min (+ idx 1) size)))))))))
(defun approximate-spectrum (spectrum &key (begin-wl 360d0) (end-wl 830d0) (band 1d0))
"Generates an approximate spectrum of SPECTRUM by pieacewise linearization. It
is used to lighten a \"heavy\" spectrum function."
(declare (optimize (speed 3) (safety 1))
(spectrum-function spectrum))
(with-ensuring-type double-float (begin-wl end-wl band)
(let* ((partitions (max 2 (round (/ (- end-wl begin-wl) band))))
(partitions-f (float partitions 1d0))
(points (make-array (1+ partitions) :element-type 'double-float)))
(declare (fixnum partitions))
(gen-spectrum (loop for i from 0 to partitions
for wl = (lerp (/ i partitions-f) begin-wl end-wl)
do (setf (aref points i) (funcall spectrum wl))
finally (return points))
begin-wl
end-wl))))
Observer
(defstruct (observer (:constructor %make-observer))
"OBSERVER is a structure of color matching functions."
(begin-wl 360 :type (integer 0))
(end-wl 830 :type (integer 0))
(cmf-table nil :type (simple-array double-float (* 3)))
Below are ( linear ) interpolation functions for cmf - table .
(cmf-x nil :type spectrum-function)
(cmf-y nil :type spectrum-function)
(cmf-z nil :type spectrum-function)
(cmf nil :type (function * (values double-float double-float double-float &optional))))
(defmethod print-object ((obs observer) stream)
(let ((*print-array* nil))
(call-next-method)))
(defun make-observer (cmf-table &optional (begin-wl 360) (end-wl 830))
"Generates an observer object based on CMF arrays, which must be (SIMPLE-ARRAY
DOUBLE-FLOAT (* 3)). The response outside the interval [begin-wl, end-wl] is
regarded as 0."
(let ((begin-wl-f (float begin-wl 1d0))
(end-wl-f (float end-wl 1d0)))
(labels ((gen-cmf-1dim (arr num &optional (begin-wl 360) (end-wl 830))
(declare ((simple-array double-float (* 3)) arr))
(let ((size (- (array-dimension arr 0) 1)))
(if (= size (- end-wl begin-wl))
#'(lambda (wl)
(declare (optimize (speed 3) (safety 1)))
(let ((wl (float wl 1d0)))
(if (or (< wl begin-wl-f) (< end-wl-f wl))
0d0
(multiple-value-bind (quot rem)
(floor (- wl begin-wl-f))
(lerp rem
(aref arr quot num)
(aref arr (min (1+ quot) size) num))))))
(let* ((band (/ (- end-wl-f begin-wl-f) size))
(/band (/ band)))
#'(lambda (wl)
(declare (optimize (speed 3) (safety 1)))
(let ((wl (float wl 1d0)))
(if (or (< wl begin-wl-f) (< end-wl-f wl))
0d0
(let* ((wl-offset (- wl begin-wl-f))
(frac (mod wl-offset band))
(coef (* frac /band))
(idx (round (* (- wl-offset frac) /band))))
(lerp coef
(aref arr idx num)
(aref arr (min (+ idx 1) size) num))))))))))
(gen-cmf-3dims (arr &optional (begin-wl 360) (end-wl 830))
(declare ((simple-array double-float (* 3)) arr))
(let ((size (- (array-dimension arr 0) 1)))
(if (= size (- end-wl begin-wl))
#'(lambda (wl)
(declare (optimize (speed 3) (safety 1)))
(let ((wl (float wl 1d0)))
(if (or (< wl begin-wl-f) (< end-wl-f wl))
(values 0d0 0d0 0d0)
(multiple-value-bind (quot rem)
(floor (- wl begin-wl-f))
(values (lerp rem
(aref arr quot 0)
(aref arr (min (1+ quot) size) 0))
(lerp rem
(aref arr quot 1)
(aref arr (min (1+ quot) size) 1))
(lerp rem
(aref arr quot 2)
(aref arr (min (1+ quot) size) 2)))))))
(let* ((band (/ (- end-wl-f begin-wl-f) size))
(/band (/ band)))
#'(lambda (wl)
(declare (optimize (speed 3) (safety 1)))
(let ((wl (float wl 1d0)))
(if (or (< wl begin-wl-f) (< end-wl-f wl))
(values 0d0 0d0 0d0)
(let* ((wl-offset (- wl begin-wl-f))
(frac (mod wl-offset band))
(coef (* frac /band))
(idx (round (* (- wl-offset frac) /band)))
(idx+1 (min (1+ idx) size)))
(values (lerp coef
(aref arr idx 0)
(aref arr idx+1 0))
(lerp coef
(aref arr idx 1)
(aref arr idx+1 1))
(lerp coef
(aref arr idx 2)
(aref arr idx+1 2))))))))))))
(%make-observer
:begin-wl begin-wl
:end-wl end-wl
:cmf-table cmf-table
:cmf-x (gen-cmf-1dim cmf-table 0 begin-wl end-wl)
:cmf-y (gen-cmf-1dim cmf-table 1 begin-wl end-wl)
:cmf-z (gen-cmf-1dim cmf-table 2 begin-wl end-wl)
:cmf (gen-cmf-3dims cmf-table begin-wl end-wl)))))
(defparameter +obs-cie1931+ (make-observer +cmf-table-cie1931+)
"CIE 1931 Standard Colorimetric Observer (2-degree).")
(defparameter +obs-cie1964+ (make-observer +cmf-table-cie1964+)
"CIE 1964 Standard Colorimetric Observer (10-degree).")
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter +s0-table+
(make-array 54
:element-type 'double-float
:initial-contents '(0.04d0 6d0 29.6d0 55.3d0 57.3d0 61.8d0 61.5d0 68.8d0 63.4d0 65.8d0 94.8d0 104.8d0 105.9d0 96.8d0 113.9d0 125.6d0 125.5d0 121.3d0 121.3d0 113.5d0 113.1d0 110.8d0 106.5d0 108.8d0 105.3d0 104.4d0 100d0 96d0 95.1d0 89.1d0 90.5d0 90.3d0 88.4d0 84d0 85.1d0 81.9d0 82.6d0 84.9d0 81.3d0 71.9d0 74.3d0 76.4d0 63.3d0 71.7d0 77d0 65.2d0 47.7d0 68.6d0 65d0 66d0 61d0 53.3d0 58.9d0 61.9d0)))
(defparameter +s1-table+
(make-array 54
:element-type 'double-float
:initial-contents '(0.02d0 4.5d0 22.4d0 42d0 40.6d0 41.6d0 38d0 42.4d0 38.5d0 35d0 43.4d0 46.3d0 43.9d0 37.1d0 36.7d0 35.9d0 32.6d0 27.9d0 24.3d0 20.1d0 16.2d0 13.2d0 8.6d0 6.1d0 4.2d0 1.9d0 0d0 -1.6d0 -3.5d0 -3.5d0 -5.8d0 -7.2d0 -8.6d0 -9.5d0 -10.9d0 -10.7d0 -12d0 -14d0 -13.6d0 -12d0 -13.3d0 -12.9d0 -10.6d0 -11.6d0 -12.2d0 -10.2d0 -7.8d0 -11.2d0 -10.4d0 -10.6d0 -9.7d0 -8.3d0 -9.3d0 -9.8d0)))
(defparameter +s2-table+
(make-array 54
:element-type 'double-float
:initial-contents '(0d0 2d0 4d0 8.5d0 7.8d0 6.7d0 5.3d0 6.1d0 2d0 1.2d0 -1.1d0 -0.5d0 -0.7d0 -1.2d0 -2.6d0 -2.9d0 -2.8d0 -2.6d0 -2.6d0 -1.8d0 -1.5d0 -1.3d0 -1.2d0 -1d0 -0.5d0 -0.3d0 0d0 0.2d0 0.5d0 2.1d0 3.2d0 4.1d0 4.7d0 5.1d0 6.7d0 7.3d0 8.6d0 9.8d0 10.2d0 8.3d0 9.6d0 8.5d0 7d0 7.6d0 8d0 6.7d0 5.2d0 7.4d0 6.8d0 7d0 6.4d0 5.5d0 6.1d0 6.5d0))))
(defun make-illum-d-spectrum-array (temperature &optional (begin-wl 300) (end-wl 830))
(declare (optimize (speed 3) (safety 1)))
(check-type begin-wl fixnum)
(check-type end-wl fixnum)
(let ((s0-func (load-time-value (gen-spectrum +s0-table+ 300 830) t))
(s1-func (load-time-value (gen-spectrum +s1-table+ 300 830) t))
(s2-func (load-time-value (gen-spectrum +s2-table+ 300 830) t)))
(declare (type spectrum-function s0-func s1-func s2-func))
(labels ((calc-xd (temp)
(let ((/temp (/ temp)))
(if (<= temp 7000d0)
(+ 0.244063d0 (* /temp (+ 0.09911d3 (* /temp (+ 2.9678d6 (* /temp -4.607d9))))))
(+ 0.237040d0 (* /temp (+ 0.24748d3 (* /temp (+ 1.9018d6 (* /temp -2.0064d9)))))))))
(calc-yd (xd)
(+ -0.275d0 (* xd (+ 2.870d0 (* xd -3d0))))))
(let* ((xd (calc-xd (float temperature 1d0)))
(yd (calc-yd xd))
(denom (+ 0.0241d0 (* xd 0.2562d0) (* yd -0.7341d0)))
(m1 (/ (+ -1.3515d0 (* xd -1.7703d0) (* yd 5.9114d0)) denom))
(m2 (/ (+ 0.03d0 (* xd -31.4424d0) (* yd 30.0717d0)) denom))
(spd-arr (make-array (1+ (- end-wl begin-wl))
:element-type 'double-float
:initial-element 0d0)))
(loop for wl from begin-wl to end-wl
do (setf (aref spd-arr (- wl begin-wl))
(+ (funcall s0-func wl)
(* m1 (funcall s1-func wl))
(* m2 (funcall s2-func wl)))))
spd-arr))))
(defun gen-illum-d-spectrum (temperature &key rectify)
"Generates the spectrum of the illuminant series D for a given
temperature (from 300 nm to 830 nm with band-width 1 nm). If RECTIFY is true,
the temperature multiplied by 1.4388/1.438 is used instead. (roughly 6504K for
6500K, etc.)"
(let ((temp (if rectify
(* temperature #.(/ 1.43880d0 1.438d0))
temperature)))
(gen-spectrum (make-illum-d-spectrum-array temp 300 830)
300 830)))
(declaim (inline bb-spectrum))
(defun bb-spectrum (wavelength-nm &optional (temperature 5000d0))
"Spectrum function of a blackbody. Note that it is not normalized."
(declare (optimize (speed 3) (safety 1)))
(let ((wlm (* (float wavelength-nm 1d0) 1d-9)))
(check-type wlm (double-float 0d0))
(/ (* 3.74183d-16 (expt wlm -5d0))
(- (exp (/ 1.4388d-2 (* wlm (float temperature 1d0)))) 1d0))))
(declaim (inline optimal-spectrum-peak))
(defun optimal-spectrum-peak (wavelength-nm &optional (wl1 300d0) (wl2 830d0))
"Spectrum function of optimal colors:
f(x) = 1d0 if wl1 <= x <= wl2,
f(x) = 0d0 otherwise."
(declare (optimize (speed 3) (safety 1)))
(if (<= wl1 wavelength-nm wl2) 1d0 0d0))
(declaim (inline optimal-spectrum-trough))
(defun optimal-spectrum-trough (wavelength-nm &optional (wl1 300d0) (wl2 830d0))
"Spectrum function of optimal colors:
f(x) = 1d0 if x <= wl2 or wl1 <= x,
f(x) = 0d0 otherwise."
(declare (optimize (speed 3) (safety 1)))
(if (or (<= wavelength-nm wl1)
(<= wl2 wavelength-nm))
1d0 0d0))
(declaim (inline flat-spectrum))
(defun flat-spectrum (wavelength-nm)
"(constantly 1d0)"
(declare (optimize (speed 3) (safety 0)))
(declare (ignore wavelength-nm))
1d0)
(defun empty-spectrum ()
"Used internally instead of NIL."
0d0)
(defstruct (illuminant (:constructor %make-illuminant)
(:copier nil))
(x 1d0 :type double-float)
(z 1d0 :type double-float)
(spectrum #'empty-spectrum :type spectrum-function)
(observer +obs-cie1931+ :type observer)
(to-spectrum-matrix +empty-matrix+ :type (simple-array double-float (3 3))))
(defun illuminant-xy (illuminant)
"Returns the xy chromacity coordinates of a given illuminant."
(declare (optimize (speed 3) (safety 1))
(type illuminant illuminant))
(let* ((x (illuminant-x illuminant))
(z (illuminant-z illuminant))
(sum (+ x 1d0 z)))
(if (= sum 0)
(values 0d0 0d0)
(values (/ x sum) (/ sum)))))
(declaim (inline illuminant-no-spd-p))
(defun illuminant-no-spd-p (illuminant)
(eq #'empty-spectrum (illuminant-spectrum illuminant)))
(define-condition no-spd-error (simple-error)
((illuminant :initarg :illuminant
:initform nil
:accessor cond-illuminant))
(:report (lambda (condition stream)
(let ((*print-array* nil))
(format stream "The illuminant has no spectrum: ~A"
(cond-illuminant condition))))))
(defun %spectrum-to-xyz (spectrum illuminant-spd observer &optional (begin-wl 360) (end-wl 830) (band 1))
(declare (optimize (speed 3) (safety 1))
(spectrum-function spectrum illuminant-spd))
"Is an internal function and will be called in SPECTRUM-TO-XYZ in another module.
SPECTRUM := spectral reflectance (or transmittance) ILLUMINANT-SPD :=
SPD of illuminant"
(let ((x 0d0) (y 0d0) (z 0d0) (max-y 0d0)
(cmf (observer-cmf observer)))
(declare (double-float x y z max-y))
(loop for wl from begin-wl to end-wl by band
do (let* ((p (funcall illuminant-spd wl))
(reflec (funcall spectrum wl))
(factor (* p reflec)))
(multiple-value-bind (x-match y-match z-match) (funcall cmf wl)
(incf x (* x-match factor))
(incf y (* y-match factor))
(incf z (* z-match factor))
(incf max-y (* y-match p)))))
(let ((normalizing-factor (/ max-y)))
(values (* x normalizing-factor)
(* y normalizing-factor)
(* z normalizing-factor)))))
(defun calc-to-spectrum-matrix (illuminant-spd observer &optional (begin-wl 360) (end-wl 830) (band 1))
(declare (optimize (speed 3) (safety 1)))
"The returned matrix will be used in XYZ-to-spectrum conversion."
(let ((mat (load-time-value
(make-array '(3 3) :element-type 'double-float
:initial-element 0d0))))
(multiple-value-bind (a00 a10 a20)
(%spectrum-to-xyz (observer-cmf-x observer) illuminant-spd observer begin-wl end-wl band)
(multiple-value-bind (a01 a11 a21)
(%spectrum-to-xyz (observer-cmf-y observer) illuminant-spd observer begin-wl end-wl band)
(multiple-value-bind (a02 a12 a22)
(%spectrum-to-xyz (observer-cmf-z observer) illuminant-spd observer begin-wl end-wl band)
(setf (aref mat 0 0) a00
(aref mat 0 1) a01
(aref mat 0 2) a02
(aref mat 1 0) a10
(aref mat 1 1) a11
(aref mat 1 2) a12
(aref mat 2 0) a20
(aref mat 2 1) a21
(aref mat 2 2) a22))))
(invert-matrix mat)))
(defun make-illuminant (&key x z spectrum (observer +obs-cie1931+) (compile-time nil) (begin-wl 360) (end-wl 830) (band 1))
(declare (ignore compile-time))
"Generates an illuminant from a spectral distribution or a white point. If
SPECTRUM is nil, the returned illuminant contains only a white point. If X and Z
are nil, on the other hand, the white point (X, 1d0, Z) is automatically
calculated from the spectrum. You can also specify the both though you should
note that no error occurs even if the given white point and SPD contradicts to
each other.
(make-illuminant :x 1.0 :z 1.0)
= > illuminant without SPD
(make-illuminant :x 1.0 :z 1.0 :spectrum #'flat-spectrum)
(make-illuminant :spectrum #'flat-spectrum)
= > ( almost same ) illuminants with SPD
(make-illuminant :x 0.9 :z 1.1 :spectrum #'flat-spectrum)
= > ( valid but meaningless ) illuminant with SPD
If X and Y are NIL and COMPILE-TIME is T, the white point is
calculated at compile time. (Avoid side effects in this case as the
parameters are EVALed.)"
(macrolet
((make (x z)
`(%make-illuminant
:x (float ,x 1d0)
:z (float ,z 1d0)
:spectrum (or spectrum #'empty-spectrum)
:observer observer
:to-spectrum-matrix (if spectrum
(calc-to-spectrum-matrix spectrum observer begin-wl end-wl band)
+empty-matrix+))))
(if (and (null x) (null z))
(multiple-value-bind (x y z)
(%spectrum-to-xyz #'flat-spectrum spectrum observer begin-wl end-wl band)
(declare (ignore y))
(make x z))
(make x z))))
(define-compiler-macro make-illuminant (&whole form &key x z spectrum (observer '+obs-cie1931+) (begin-wl 360) (end-wl 830) (band 1) (compile-time nil))
(if (and compile-time (null x) (null z))
(let ((spctrm (eval spectrum))
(obs (eval observer))
(bwl (eval begin-wl))
(ewl (eval end-wl))
(bnd (eval band)))
(multiple-value-bind (x y z)
(%spectrum-to-xyz #'flat-spectrum spctrm obs bwl ewl bnd)
(declare (ignore y))
`(%make-illuminant
:x (float ,x 1d0)
:z (float ,z 1d0)
:spectrum ,spectrum
:observer ,observer
:to-spectrum-matrix ,(calc-to-spectrum-matrix spctrm obs bwl ewl bnd))))
form))
|
ed0d84c32060b71873ce72bb5a8e3f13969e2c5e7905745da6f199ce933ed236 | gigasquid/clj-drone | at.clj | (ns clj-drone.at
(:import (java.util BitSet)
(java.nio ByteBuffer))
(:require [clj-drone.commands :refer :all]))
(defn build-command-int [command-bit-vec]
(reduce #(bit-set %1 %2) 0 command-bit-vec))
(defn cast-float-to-int [f]
(let [bbuffer (ByteBuffer/allocate 4)]
(.put (.asFloatBuffer bbuffer) 0 f)
(.get (.asIntBuffer bbuffer) 0)))
(defn build-base-command [command-class counter]
(str command-class "=" counter ","))
(defn build-ref-command [command-key counter]
(let [{:keys [command-class command-bit-vec]} (command-key commands)]
(str (build-base-command command-class counter)
(build-command-int command-bit-vec)
"\r")))
(defn build-pcmd-command [command-key counter & [[v w x y]]]
(let [{:keys [command-class command-vec dir] or {dir 1}} (command-key commands)
v-val (when v (cast-float-to-int (* dir v)))
w-val (when w (cast-float-to-int w))
x-val (when x (cast-float-to-int x))
y-val (when y (cast-float-to-int y))]
(str (build-base-command command-class counter)
(apply str (interpose "," (replace {:v v-val :w w-val :x x-val :y y-val} command-vec)))
"\r")))
(defn build-simple-command [command-key counter]
(let [{:keys [command-class value]} (command-key commands)]
(str (build-base-command command-class counter)
value
"\r")))
(defn build-config-command [command-key counter]
(let [{:keys [command-class option value]} (command-key commands)]
(str (build-base-command command-class counter)
(apply str (interpose "," [option, value]))
"\r")))
(defn build-command [command-key counter & values]
(let [{:keys [command-class]} (command-key commands)]
(case command-class
"AT*REF" (build-ref-command command-key counter)
"AT*PCMD" (build-pcmd-command command-key counter values)
"AT*FTRIM" (build-simple-command command-key counter)
"AT*COMWDG" (build-simple-command command-key counter)
"AT*CONFIG" (build-config-command command-key counter)
"AT*CTRL" (build-simple-command command-key counter)
:else (throw (Exception. "Unsupported Drone Command")))))
| null | https://raw.githubusercontent.com/gigasquid/clj-drone/b85320a0ab5e4d8589aaf77a0bd57e8a46e2905b/src/clj_drone/at.clj | clojure | (ns clj-drone.at
(:import (java.util BitSet)
(java.nio ByteBuffer))
(:require [clj-drone.commands :refer :all]))
(defn build-command-int [command-bit-vec]
(reduce #(bit-set %1 %2) 0 command-bit-vec))
(defn cast-float-to-int [f]
(let [bbuffer (ByteBuffer/allocate 4)]
(.put (.asFloatBuffer bbuffer) 0 f)
(.get (.asIntBuffer bbuffer) 0)))
(defn build-base-command [command-class counter]
(str command-class "=" counter ","))
(defn build-ref-command [command-key counter]
(let [{:keys [command-class command-bit-vec]} (command-key commands)]
(str (build-base-command command-class counter)
(build-command-int command-bit-vec)
"\r")))
(defn build-pcmd-command [command-key counter & [[v w x y]]]
(let [{:keys [command-class command-vec dir] or {dir 1}} (command-key commands)
v-val (when v (cast-float-to-int (* dir v)))
w-val (when w (cast-float-to-int w))
x-val (when x (cast-float-to-int x))
y-val (when y (cast-float-to-int y))]
(str (build-base-command command-class counter)
(apply str (interpose "," (replace {:v v-val :w w-val :x x-val :y y-val} command-vec)))
"\r")))
(defn build-simple-command [command-key counter]
(let [{:keys [command-class value]} (command-key commands)]
(str (build-base-command command-class counter)
value
"\r")))
(defn build-config-command [command-key counter]
(let [{:keys [command-class option value]} (command-key commands)]
(str (build-base-command command-class counter)
(apply str (interpose "," [option, value]))
"\r")))
(defn build-command [command-key counter & values]
(let [{:keys [command-class]} (command-key commands)]
(case command-class
"AT*REF" (build-ref-command command-key counter)
"AT*PCMD" (build-pcmd-command command-key counter values)
"AT*FTRIM" (build-simple-command command-key counter)
"AT*COMWDG" (build-simple-command command-key counter)
"AT*CONFIG" (build-config-command command-key counter)
"AT*CTRL" (build-simple-command command-key counter)
:else (throw (Exception. "Unsupported Drone Command")))))
|
|
629a9e1254c9cf244e66cbc1469bdb3dc55688bf12bd5e45e359ed5adcee18c6 | drathier/elm-offline | Error.hs | # OPTIONS_GHC -Wall #
{-# LANGUAGE OverloadedStrings #-}
module Type.Error
( Type(..)
, Super(..)
, Extension(..)
, iteratedDealias
, toDoc
, Problem(..)
, Direction(..)
, toComparison
, isInt
, isFloat
, isString
, isChar
, isList
)
where
import qualified Data.Map as Map
import qualified Data.Maybe as Maybe
import Data.Monoid ((<>))
import qualified AST.Module.Name as ModuleName
import qualified Data.Bag as Bag
import qualified Elm.Name as N
import qualified Reporting.Doc as D
import qualified Reporting.Render.Type as RT
import qualified Reporting.Render.Type.Localizer as L
-- ERROR TYPES
data Type
= Lambda Type Type [Type]
| Infinite
| Error
| FlexVar N.Name
| FlexSuper Super N.Name
| RigidVar N.Name
| RigidSuper Super N.Name
| Type ModuleName.Canonical N.Name [Type]
| Record (Map.Map N.Name Type) Extension
| Unit
| Tuple Type Type (Maybe Type)
| Alias ModuleName.Canonical N.Name [(N.Name, Type)] Type
data Super
= Number
| Comparable
| Appendable
| CompAppend
deriving (Eq)
data Extension
= Closed
| FlexOpen N.Name
| RigidOpen N.Name
iteratedDealias :: Type -> Type
iteratedDealias tipe =
case tipe of
Alias _ _ _ real ->
iteratedDealias real
_ ->
tipe
TO DOC
toDoc :: L.Localizer -> RT.Context -> Type -> D.Doc
toDoc localizer ctx tipe =
case tipe of
Lambda a b cs ->
RT.lambda ctx
(toDoc localizer RT.Func a)
(toDoc localizer RT.Func b)
(map (toDoc localizer RT.Func) cs)
Infinite ->
"∞"
Error ->
"?"
FlexVar name ->
D.fromName name
FlexSuper _ name ->
D.fromName name
RigidVar name ->
D.fromName name
RigidSuper _ name ->
D.fromName name
Type home name args ->
RT.apply ctx
(L.toDoc localizer home name)
(map (toDoc localizer RT.App) args)
Record fields ext ->
RT.record (fieldsToDocs localizer fields) (extToDoc ext)
Unit ->
"()"
Tuple a b maybeC ->
RT.tuple
(toDoc localizer RT.None a)
(toDoc localizer RT.None b)
(map (toDoc localizer RT.None) (Maybe.maybeToList maybeC))
Alias home name args _ ->
aliasToDoc localizer ctx home name args
aliasToDoc :: L.Localizer -> RT.Context -> ModuleName.Canonical -> N.Name -> [(N.Name, Type)] -> D.Doc
aliasToDoc localizer ctx home name args =
RT.apply ctx
(L.toDoc localizer home name)
(map (toDoc localizer RT.App . snd) args)
fieldsToDocs :: L.Localizer -> Map.Map N.Name Type -> [(D.Doc, D.Doc)]
fieldsToDocs localizer fields =
Map.foldrWithKey (addField localizer) [] fields
addField :: L.Localizer -> N.Name -> Type -> [(D.Doc, D.Doc)] -> [(D.Doc, D.Doc)]
addField localizer fieldName fieldType docs =
let
f = D.fromName fieldName
t = toDoc localizer RT.None fieldType
in
(f,t) : docs
extToDoc :: Extension -> Maybe D.Doc
extToDoc ext =
case ext of
Closed -> Nothing
FlexOpen x -> Just (D.fromName x)
RigidOpen x -> Just (D.fromName x)
DIFF
data Diff a =
Diff a a Status
data Status
= Similar
| Different (Bag.Bag Problem)
data Problem
= IntFloat
| StringFromInt
| StringFromFloat
| StringToInt
| StringToFloat
| AnythingToBool
| AnythingFromMaybe
| AnythingToList
| MissingArgs Int
| ReturnMismatch
| BadFlexSuper Direction Super N.Name Type
| BadRigidVar N.Name Type
| BadRigidSuper Super N.Name Type
| FieldTypo N.Name [N.Name]
| FieldsMissing [N.Name]
data Direction = Have | Need
instance Functor Diff where
fmap func (Diff a b status) =
Diff (func a) (func b) status
instance Applicative Diff where
pure a =
Diff a a Similar
(<*>) (Diff aFunc bFunc status1) (Diff aArg bArg status2) =
Diff (aFunc aArg) (bFunc bArg) (merge status1 status2)
merge :: Status -> Status -> Status
merge status1 status2 =
case status1 of
Similar ->
status2
Different problems1 ->
case status2 of
Similar ->
status1
Different problems2 ->
Different (Bag.append problems1 problems2)
COMPARISON
toComparison :: L.Localizer -> Type -> Type -> (D.Doc, D.Doc, [Problem])
toComparison localizer tipe1 tipe2 =
case toDiff localizer RT.None tipe1 tipe2 of
Diff doc1 doc2 Similar ->
(doc1, doc2, [])
Diff doc1 doc2 (Different problems) ->
(doc1, doc2, Bag.toList problems)
toDiff :: L.Localizer -> RT.Context -> Type -> Type -> Diff D.Doc
toDiff localizer ctx tipe1 tipe2 =
case (tipe1, tipe2) of
(Unit , Unit ) -> same localizer ctx tipe1
(Error , Error ) -> same localizer ctx tipe1
(Infinite, Infinite) -> same localizer ctx tipe1
(FlexVar x, FlexVar y) | x == y -> same localizer ctx tipe1
(FlexSuper _ x, FlexSuper _ y) | x == y -> same localizer ctx tipe1
(RigidVar x, RigidVar y) | x == y -> same localizer ctx tipe1
(RigidSuper _ x, RigidSuper _ y) | x == y -> same localizer ctx tipe1
(FlexVar _, _ ) -> similar localizer ctx tipe1 tipe2
(_ , FlexVar _) -> similar localizer ctx tipe1 tipe2
(FlexSuper s _, t ) | isSuper s t -> similar localizer ctx tipe1 tipe2
(t , FlexSuper s _) | isSuper s t -> similar localizer ctx tipe1 tipe2
(Lambda a b cs, Lambda x y zs) ->
if length cs == length zs then
RT.lambda ctx
<$> toDiff localizer RT.Func a x
<*> toDiff localizer RT.Func b y
<*> sequenceA (zipWith (toDiff localizer RT.Func) cs zs)
else
diffLambda localizer ctx a b cs x y zs
(Tuple a b Nothing, Tuple x y Nothing) ->
RT.tuple
<$> toDiff localizer RT.None a x
<*> toDiff localizer RT.None b y
<*> pure []
(Tuple a b (Just c), Tuple x y (Just z)) ->
RT.tuple
<$> toDiff localizer RT.None a x
<*> toDiff localizer RT.None b y
<*> ((:[]) <$> toDiff localizer RT.None c z)
(Record fields1 ext1, Record fields2 ext2) ->
diffRecord localizer fields1 ext1 fields2 ext2
(Type home1 name1 args1, Type home2 name2 args2) | home1 == home2 && name1 == name2 ->
RT.apply ctx (L.toDoc localizer home1 name1)
<$> sequenceA (zipWith (toDiff localizer RT.App) args1 args2)
(Alias home1 name1 args1 _, Alias home2 name2 args2 _) | home1 == home2 && name1 == name2 ->
RT.apply ctx (L.toDoc localizer home1 name1)
<$> sequenceA (zipWith (toDiff localizer RT.App) (map snd args1) (map snd args2))
-- start trying to find specific problems
(Type home1 name1 args1, Type home2 name2 args2) | L.toString localizer home1 name1 == L.toString localizer home2 name2 ->
different
(nameClashToDoc ctx localizer home1 name1 args1)
(nameClashToDoc ctx localizer home2 name2 args2)
Bag.empty
(Type home name [t1], t2) | isMaybe home name && isSimilar (toDiff localizer ctx t1 t2) ->
different
(RT.apply ctx (D.dullyellow (L.toDoc localizer home name)) [toDoc localizer RT.App t1])
(toDoc localizer ctx t2)
(Bag.one AnythingFromMaybe)
(t1, Type home name [t2]) | isList home name && isSimilar (toDiff localizer ctx t1 t2) ->
different
(toDoc localizer ctx t1)
(RT.apply ctx (D.dullyellow (L.toDoc localizer home name)) [toDoc localizer RT.App t2])
(Bag.one AnythingToList)
(Alias home1 name1 args1 t1, t2) ->
case diffAliasedRecord localizer t1 t2 of
Just (Diff _ doc2 status) ->
Diff (D.dullyellow (aliasToDoc localizer ctx home1 name1 args1)) doc2 status
Nothing ->
case t2 of
Type home2 name2 args2 | L.toString localizer home1 name1 == L.toString localizer home2 name2 ->
different
(nameClashToDoc ctx localizer home1 name1 (map snd args1))
(nameClashToDoc ctx localizer home2 name2 args2)
Bag.empty
_ ->
different
(D.dullyellow (toDoc localizer ctx tipe1))
(D.dullyellow (toDoc localizer ctx tipe2))
Bag.empty
(t1, Alias home2 name2 args2 t2) ->
case diffAliasedRecord localizer t1 t2 of
Just (Diff doc1 _ status) ->
Diff doc1 (D.dullyellow (aliasToDoc localizer ctx home2 name2 args2)) status
Nothing ->
case t1 of
Type home1 name1 args1 | L.toString localizer home1 name1 == L.toString localizer home2 name2 ->
different
(nameClashToDoc ctx localizer home1 name1 args1)
(nameClashToDoc ctx localizer home2 name2 (map snd args2))
Bag.empty
_ ->
different
(D.dullyellow (toDoc localizer ctx tipe1))
(D.dullyellow (toDoc localizer ctx tipe2))
Bag.empty
pair ->
let
doc1 = D.dullyellow (toDoc localizer ctx tipe1)
doc2 = D.dullyellow (toDoc localizer ctx tipe2)
in
different doc1 doc2 $
case pair of
(RigidVar x, other) -> Bag.one $ BadRigidVar x other
(FlexSuper s x, other) -> Bag.one $ BadFlexSuper Have s x other
(RigidSuper s x, other) -> Bag.one $ BadRigidSuper s x other
(other, RigidVar x) -> Bag.one $ BadRigidVar x other
(other, FlexSuper s x) -> Bag.one $ BadFlexSuper Need s x other
(other, RigidSuper s x) -> Bag.one $ BadRigidSuper s x other
(Type home1 name1 [], Type home2 name2 [])
| isInt home1 name1 && isFloat home2 name2 -> Bag.one IntFloat
| isFloat home1 name1 && isInt home2 name2 -> Bag.one IntFloat
| isInt home1 name1 && isString home2 name2 -> Bag.one StringFromInt
| isFloat home1 name1 && isString home2 name2 -> Bag.one StringFromFloat
| isString home1 name1 && isInt home2 name2 -> Bag.one StringToInt
| isString home1 name1 && isFloat home2 name2 -> Bag.one StringToFloat
| isBool home2 name2 -> Bag.one AnythingToBool
(_, _) ->
Bag.empty
DIFF HELPERS
same :: L.Localizer -> RT.Context -> Type -> Diff D.Doc
same localizer ctx tipe =
let
doc = toDoc localizer ctx tipe
in
Diff doc doc Similar
similar :: L.Localizer -> RT.Context -> Type -> Type -> Diff D.Doc
similar localizer ctx t1 t2 =
Diff (toDoc localizer ctx t1) (toDoc localizer ctx t2) Similar
different :: a -> a -> Bag.Bag Problem -> Diff a
different a b problems =
Diff a b (Different problems)
isSimilar :: Diff a -> Bool
isSimilar (Diff _ _ status) =
case status of
Similar -> True
Different _ -> False
-- IS TYPE?
isBool :: ModuleName.Canonical -> N.Name -> Bool
isBool home name =
home == ModuleName.basics && name == N.bool
isInt :: ModuleName.Canonical -> N.Name -> Bool
isInt home name =
home == ModuleName.basics && name == N.int
isFloat :: ModuleName.Canonical -> N.Name -> Bool
isFloat home name =
home == ModuleName.basics && name == N.float
isString :: ModuleName.Canonical -> N.Name -> Bool
isString home name =
home == ModuleName.string && name == N.string
isChar :: ModuleName.Canonical -> N.Name -> Bool
isChar home name =
home == ModuleName.char && name == N.char
isMaybe :: ModuleName.Canonical -> N.Name -> Bool
isMaybe home name =
home == ModuleName.maybe && name == N.maybe
isList :: ModuleName.Canonical -> N.Name -> Bool
isList home name =
home == ModuleName.list && name == N.list
-- IS SUPER?
isSuper :: Super -> Type -> Bool
isSuper super tipe =
case iteratedDealias tipe of
Type h n args ->
case super of
Number -> isInt h n || isFloat h n
Comparable -> isInt h n || isFloat h n || isString h n || isChar h n || isList h n && isSuper super (head args)
Appendable -> isString h n || isList h n
CompAppend -> isString h n || isList h n && isSuper Comparable (head args)
_ ->
False
NAME CLASH
nameClashToDoc :: RT.Context -> L.Localizer -> ModuleName.Canonical -> N.Name -> [Type] -> D.Doc
nameClashToDoc ctx localizer (ModuleName.Canonical _ home) name args =
RT.apply ctx
(D.yellow (D.fromName home) <> D.dullyellow ("." <> D.fromName name))
(map (toDoc localizer RT.App) args)
DIFF ALIASED RECORD
diffAliasedRecord :: L.Localizer -> Type -> Type -> Maybe (Diff D.Doc)
diffAliasedRecord localizer t1 t2 =
case (iteratedDealias t1, iteratedDealias t2) of
(Record fields1 ext1, Record fields2 ext2) ->
Just (diffRecord localizer fields1 ext1 fields2 ext2)
_ ->
Nothing
DIFF LAMBDAS
--
-- INVARIANTS:
-- length cs1 /= length cs2
--
diffLambda :: L.Localizer -> RT.Context -> Type -> Type -> [Type] -> Type -> Type -> [Type] -> Diff D.Doc
diffLambda localizer ctx a1 b1 cs1 a2 b2 cs2 =
let
(result1:revArgs1) = reverse (a1:b1:cs1)
(result2:revArgs2) = reverse (a2:b2:cs2)
numArgs1 = length revArgs1
numArgs2 = length revArgs2
in
case toDiff localizer RT.Func result1 result2 of
Diff resultDoc1 resultDoc2 Similar ->
if numArgs1 < numArgs2 then
diffArgMismatch localizer ctx revArgs1 resultDoc1 revArgs2 resultDoc2
else
diffArgMismatch localizer ctx revArgs2 resultDoc2 revArgs1 resultDoc1
Diff resultDoc1 resultDoc2 (Different problems) ->
let
(a:b:cs) = reverse (resultDoc1 : map (toDoc localizer RT.Func) revArgs1)
(x:y:zs) = reverse (resultDoc2 : map (toDoc localizer RT.Func) revArgs2)
in
different
(D.dullyellow (RT.lambda ctx a b cs))
(D.dullyellow (RT.lambda ctx x y zs))
(Bag.append problems (Bag.one ReturnMismatch))
--
-- INVARIANTS:
length shortRevArgs > = 2
length longRevArgs > = 2
length shortRevArgs < length longRevArgs
--
diffArgMismatch :: L.Localizer -> RT.Context -> [Type] -> D.Doc -> [Type] -> D.Doc -> Diff D.Doc
diffArgMismatch localizer ctx shortRevArgs shortResult longRevArgs longResult =
let
(a:b:cs, x:y:zs) =
case toGreedyMatch localizer shortRevArgs longRevArgs of
Just (GreedyMatch shortRevArgDocs longRevArgDocs) ->
( reverse (shortResult:shortRevArgDocs)
, reverse (longResult:longRevArgDocs)
)
Nothing ->
case toGreedyMatch localizer (reverse shortRevArgs) (reverse longRevArgs) of
Just (GreedyMatch shortArgDocs longArgDocs) ->
( shortArgDocs ++ [shortResult]
, longArgDocs ++ [longResult]
)
Nothing ->
let
toYellowDoc tipe =
D.dullyellow (toDoc localizer RT.Func tipe)
in
( reverse (shortResult : map toYellowDoc shortRevArgs)
, reverse (longResult : map toYellowDoc longRevArgs )
)
in
different
(RT.lambda ctx a b cs)
(RT.lambda ctx x y zs)
(Bag.one (MissingArgs (length longRevArgs - length shortRevArgs)))
-- GREEDY ARG MATCHER
data GreedyMatch =
GreedyMatch [D.Doc] [D.Doc]
--
-- INVARIANTS:
-- length shorterArgs < length longerArgs
--
toGreedyMatch :: L.Localizer -> [Type] -> [Type] -> Maybe GreedyMatch
toGreedyMatch localizer shorterArgs longerArgs =
toGreedyMatchHelp localizer shorterArgs longerArgs (GreedyMatch [] [])
toGreedyMatchHelp :: L.Localizer -> [Type] -> [Type] -> GreedyMatch -> Maybe GreedyMatch
toGreedyMatchHelp localizer shorterArgs longerArgs match@(GreedyMatch shorterDocs longerDocs) =
let
toYellowDoc tipe =
D.dullyellow (toDoc localizer RT.Func tipe)
in
case (shorterArgs, longerArgs) of
(x:xs, y:ys) ->
case toDiff localizer RT.Func x y of
Diff a b Similar ->
toGreedyMatchHelp localizer xs ys $
GreedyMatch (a:shorterDocs) (b:longerDocs)
Diff _ _ (Different _) ->
toGreedyMatchHelp localizer shorterArgs ys $
GreedyMatch shorterDocs (toYellowDoc y : longerDocs)
([], []) ->
Just match
([], _:_) ->
Just (GreedyMatch shorterDocs (map toYellowDoc longerArgs))
(_:_, []) ->
Nothing
-- RECORD DIFFS
diffRecord :: L.Localizer -> Map.Map N.Name Type -> Extension -> Map.Map N.Name Type -> Extension -> Diff D.Doc
diffRecord localizer fields1 ext1 fields2 ext2 =
let
toUnknownDocs field tipe =
( D.dullyellow (D.fromName field), toDoc localizer RT.None tipe )
toOverlapDocs field t1 t2 =
(,) (D.fromName field) <$> toDiff localizer RT.None t1 t2
left = Map.mapWithKey toUnknownDocs (Map.difference fields1 fields2)
both = Map.intersectionWithKey toOverlapDocs fields1 fields2
right = Map.mapWithKey toUnknownDocs (Map.difference fields2 fields1)
fieldsDiff =
Map.elems <$>
if Map.null left && Map.null right then
sequenceA both
else
Map.union
<$> sequenceA both
<*> Diff left right (Different Bag.empty)
(Diff doc1 doc2 status) =
RT.record
<$> fieldsDiff
<*> extToDiff ext1 ext2
in
Diff doc1 doc2 $ merge status $
case (hasFixedFields ext1, hasFixedFields ext2) of
(True, True) ->
case Map.lookupMin left of
Just (f,_) -> Different $ Bag.one $ FieldTypo f (Map.keys fields2)
Nothing ->
if Map.null right
then Similar
else Different $ Bag.one $ FieldsMissing (Map.keys right)
(False, True) ->
case Map.lookupMin left of
Just (f,_) -> Different $ Bag.one $ FieldTypo f (Map.keys fields2)
Nothing -> Similar
(True, False) ->
case Map.lookupMin right of
Just (f,_) -> Different $ Bag.one $ FieldTypo f (Map.keys fields1)
Nothing -> Similar
(False, False) ->
Similar
hasFixedFields :: Extension -> Bool
hasFixedFields ext =
case ext of
Closed -> True
FlexOpen _ -> False
RigidOpen _ -> True
DIFF RECORD EXTENSION
extToDiff :: Extension -> Extension -> Diff (Maybe D.Doc)
extToDiff ext1 ext2 =
let
status = extToStatus ext1 ext2
extDoc1 = extToDoc ext1
extDoc2 = extToDoc ext2
in
case status of
Similar ->
Diff extDoc1 extDoc2 status
Different _ ->
Diff (D.dullyellow <$> extDoc1) (D.dullyellow <$> extDoc2) status
extToStatus :: Extension -> Extension -> Status
extToStatus ext1 ext2 =
case ext1 of
Closed ->
case ext2 of
Closed -> Similar
FlexOpen _ -> Similar
RigidOpen _ -> Different Bag.empty
FlexOpen _ ->
Similar
RigidOpen x ->
case ext2 of
Closed -> Different Bag.empty
FlexOpen _ -> Similar
RigidOpen y ->
if x == y
then Similar
else Different $ Bag.one $ BadRigidVar x (RigidVar y)
| null | https://raw.githubusercontent.com/drathier/elm-offline/f562198cac29f4cda15b69fde7e66edde89b34fa/compiler/src/Type/Error.hs | haskell | # LANGUAGE OverloadedStrings #
ERROR TYPES
start trying to find specific problems
IS TYPE?
IS SUPER?
INVARIANTS:
length cs1 /= length cs2
INVARIANTS:
GREEDY ARG MATCHER
INVARIANTS:
length shorterArgs < length longerArgs
RECORD DIFFS | # OPTIONS_GHC -Wall #
module Type.Error
( Type(..)
, Super(..)
, Extension(..)
, iteratedDealias
, toDoc
, Problem(..)
, Direction(..)
, toComparison
, isInt
, isFloat
, isString
, isChar
, isList
)
where
import qualified Data.Map as Map
import qualified Data.Maybe as Maybe
import Data.Monoid ((<>))
import qualified AST.Module.Name as ModuleName
import qualified Data.Bag as Bag
import qualified Elm.Name as N
import qualified Reporting.Doc as D
import qualified Reporting.Render.Type as RT
import qualified Reporting.Render.Type.Localizer as L
data Type
= Lambda Type Type [Type]
| Infinite
| Error
| FlexVar N.Name
| FlexSuper Super N.Name
| RigidVar N.Name
| RigidSuper Super N.Name
| Type ModuleName.Canonical N.Name [Type]
| Record (Map.Map N.Name Type) Extension
| Unit
| Tuple Type Type (Maybe Type)
| Alias ModuleName.Canonical N.Name [(N.Name, Type)] Type
data Super
= Number
| Comparable
| Appendable
| CompAppend
deriving (Eq)
data Extension
= Closed
| FlexOpen N.Name
| RigidOpen N.Name
iteratedDealias :: Type -> Type
iteratedDealias tipe =
case tipe of
Alias _ _ _ real ->
iteratedDealias real
_ ->
tipe
TO DOC
toDoc :: L.Localizer -> RT.Context -> Type -> D.Doc
toDoc localizer ctx tipe =
case tipe of
Lambda a b cs ->
RT.lambda ctx
(toDoc localizer RT.Func a)
(toDoc localizer RT.Func b)
(map (toDoc localizer RT.Func) cs)
Infinite ->
"∞"
Error ->
"?"
FlexVar name ->
D.fromName name
FlexSuper _ name ->
D.fromName name
RigidVar name ->
D.fromName name
RigidSuper _ name ->
D.fromName name
Type home name args ->
RT.apply ctx
(L.toDoc localizer home name)
(map (toDoc localizer RT.App) args)
Record fields ext ->
RT.record (fieldsToDocs localizer fields) (extToDoc ext)
Unit ->
"()"
Tuple a b maybeC ->
RT.tuple
(toDoc localizer RT.None a)
(toDoc localizer RT.None b)
(map (toDoc localizer RT.None) (Maybe.maybeToList maybeC))
Alias home name args _ ->
aliasToDoc localizer ctx home name args
aliasToDoc :: L.Localizer -> RT.Context -> ModuleName.Canonical -> N.Name -> [(N.Name, Type)] -> D.Doc
aliasToDoc localizer ctx home name args =
RT.apply ctx
(L.toDoc localizer home name)
(map (toDoc localizer RT.App . snd) args)
fieldsToDocs :: L.Localizer -> Map.Map N.Name Type -> [(D.Doc, D.Doc)]
fieldsToDocs localizer fields =
Map.foldrWithKey (addField localizer) [] fields
addField :: L.Localizer -> N.Name -> Type -> [(D.Doc, D.Doc)] -> [(D.Doc, D.Doc)]
addField localizer fieldName fieldType docs =
let
f = D.fromName fieldName
t = toDoc localizer RT.None fieldType
in
(f,t) : docs
extToDoc :: Extension -> Maybe D.Doc
extToDoc ext =
case ext of
Closed -> Nothing
FlexOpen x -> Just (D.fromName x)
RigidOpen x -> Just (D.fromName x)
DIFF
data Diff a =
Diff a a Status
data Status
= Similar
| Different (Bag.Bag Problem)
data Problem
= IntFloat
| StringFromInt
| StringFromFloat
| StringToInt
| StringToFloat
| AnythingToBool
| AnythingFromMaybe
| AnythingToList
| MissingArgs Int
| ReturnMismatch
| BadFlexSuper Direction Super N.Name Type
| BadRigidVar N.Name Type
| BadRigidSuper Super N.Name Type
| FieldTypo N.Name [N.Name]
| FieldsMissing [N.Name]
data Direction = Have | Need
instance Functor Diff where
fmap func (Diff a b status) =
Diff (func a) (func b) status
instance Applicative Diff where
pure a =
Diff a a Similar
(<*>) (Diff aFunc bFunc status1) (Diff aArg bArg status2) =
Diff (aFunc aArg) (bFunc bArg) (merge status1 status2)
merge :: Status -> Status -> Status
merge status1 status2 =
case status1 of
Similar ->
status2
Different problems1 ->
case status2 of
Similar ->
status1
Different problems2 ->
Different (Bag.append problems1 problems2)
COMPARISON
toComparison :: L.Localizer -> Type -> Type -> (D.Doc, D.Doc, [Problem])
toComparison localizer tipe1 tipe2 =
case toDiff localizer RT.None tipe1 tipe2 of
Diff doc1 doc2 Similar ->
(doc1, doc2, [])
Diff doc1 doc2 (Different problems) ->
(doc1, doc2, Bag.toList problems)
toDiff :: L.Localizer -> RT.Context -> Type -> Type -> Diff D.Doc
toDiff localizer ctx tipe1 tipe2 =
case (tipe1, tipe2) of
(Unit , Unit ) -> same localizer ctx tipe1
(Error , Error ) -> same localizer ctx tipe1
(Infinite, Infinite) -> same localizer ctx tipe1
(FlexVar x, FlexVar y) | x == y -> same localizer ctx tipe1
(FlexSuper _ x, FlexSuper _ y) | x == y -> same localizer ctx tipe1
(RigidVar x, RigidVar y) | x == y -> same localizer ctx tipe1
(RigidSuper _ x, RigidSuper _ y) | x == y -> same localizer ctx tipe1
(FlexVar _, _ ) -> similar localizer ctx tipe1 tipe2
(_ , FlexVar _) -> similar localizer ctx tipe1 tipe2
(FlexSuper s _, t ) | isSuper s t -> similar localizer ctx tipe1 tipe2
(t , FlexSuper s _) | isSuper s t -> similar localizer ctx tipe1 tipe2
(Lambda a b cs, Lambda x y zs) ->
if length cs == length zs then
RT.lambda ctx
<$> toDiff localizer RT.Func a x
<*> toDiff localizer RT.Func b y
<*> sequenceA (zipWith (toDiff localizer RT.Func) cs zs)
else
diffLambda localizer ctx a b cs x y zs
(Tuple a b Nothing, Tuple x y Nothing) ->
RT.tuple
<$> toDiff localizer RT.None a x
<*> toDiff localizer RT.None b y
<*> pure []
(Tuple a b (Just c), Tuple x y (Just z)) ->
RT.tuple
<$> toDiff localizer RT.None a x
<*> toDiff localizer RT.None b y
<*> ((:[]) <$> toDiff localizer RT.None c z)
(Record fields1 ext1, Record fields2 ext2) ->
diffRecord localizer fields1 ext1 fields2 ext2
(Type home1 name1 args1, Type home2 name2 args2) | home1 == home2 && name1 == name2 ->
RT.apply ctx (L.toDoc localizer home1 name1)
<$> sequenceA (zipWith (toDiff localizer RT.App) args1 args2)
(Alias home1 name1 args1 _, Alias home2 name2 args2 _) | home1 == home2 && name1 == name2 ->
RT.apply ctx (L.toDoc localizer home1 name1)
<$> sequenceA (zipWith (toDiff localizer RT.App) (map snd args1) (map snd args2))
(Type home1 name1 args1, Type home2 name2 args2) | L.toString localizer home1 name1 == L.toString localizer home2 name2 ->
different
(nameClashToDoc ctx localizer home1 name1 args1)
(nameClashToDoc ctx localizer home2 name2 args2)
Bag.empty
(Type home name [t1], t2) | isMaybe home name && isSimilar (toDiff localizer ctx t1 t2) ->
different
(RT.apply ctx (D.dullyellow (L.toDoc localizer home name)) [toDoc localizer RT.App t1])
(toDoc localizer ctx t2)
(Bag.one AnythingFromMaybe)
(t1, Type home name [t2]) | isList home name && isSimilar (toDiff localizer ctx t1 t2) ->
different
(toDoc localizer ctx t1)
(RT.apply ctx (D.dullyellow (L.toDoc localizer home name)) [toDoc localizer RT.App t2])
(Bag.one AnythingToList)
(Alias home1 name1 args1 t1, t2) ->
case diffAliasedRecord localizer t1 t2 of
Just (Diff _ doc2 status) ->
Diff (D.dullyellow (aliasToDoc localizer ctx home1 name1 args1)) doc2 status
Nothing ->
case t2 of
Type home2 name2 args2 | L.toString localizer home1 name1 == L.toString localizer home2 name2 ->
different
(nameClashToDoc ctx localizer home1 name1 (map snd args1))
(nameClashToDoc ctx localizer home2 name2 args2)
Bag.empty
_ ->
different
(D.dullyellow (toDoc localizer ctx tipe1))
(D.dullyellow (toDoc localizer ctx tipe2))
Bag.empty
(t1, Alias home2 name2 args2 t2) ->
case diffAliasedRecord localizer t1 t2 of
Just (Diff doc1 _ status) ->
Diff doc1 (D.dullyellow (aliasToDoc localizer ctx home2 name2 args2)) status
Nothing ->
case t1 of
Type home1 name1 args1 | L.toString localizer home1 name1 == L.toString localizer home2 name2 ->
different
(nameClashToDoc ctx localizer home1 name1 args1)
(nameClashToDoc ctx localizer home2 name2 (map snd args2))
Bag.empty
_ ->
different
(D.dullyellow (toDoc localizer ctx tipe1))
(D.dullyellow (toDoc localizer ctx tipe2))
Bag.empty
pair ->
let
doc1 = D.dullyellow (toDoc localizer ctx tipe1)
doc2 = D.dullyellow (toDoc localizer ctx tipe2)
in
different doc1 doc2 $
case pair of
(RigidVar x, other) -> Bag.one $ BadRigidVar x other
(FlexSuper s x, other) -> Bag.one $ BadFlexSuper Have s x other
(RigidSuper s x, other) -> Bag.one $ BadRigidSuper s x other
(other, RigidVar x) -> Bag.one $ BadRigidVar x other
(other, FlexSuper s x) -> Bag.one $ BadFlexSuper Need s x other
(other, RigidSuper s x) -> Bag.one $ BadRigidSuper s x other
(Type home1 name1 [], Type home2 name2 [])
| isInt home1 name1 && isFloat home2 name2 -> Bag.one IntFloat
| isFloat home1 name1 && isInt home2 name2 -> Bag.one IntFloat
| isInt home1 name1 && isString home2 name2 -> Bag.one StringFromInt
| isFloat home1 name1 && isString home2 name2 -> Bag.one StringFromFloat
| isString home1 name1 && isInt home2 name2 -> Bag.one StringToInt
| isString home1 name1 && isFloat home2 name2 -> Bag.one StringToFloat
| isBool home2 name2 -> Bag.one AnythingToBool
(_, _) ->
Bag.empty
DIFF HELPERS
same :: L.Localizer -> RT.Context -> Type -> Diff D.Doc
same localizer ctx tipe =
let
doc = toDoc localizer ctx tipe
in
Diff doc doc Similar
similar :: L.Localizer -> RT.Context -> Type -> Type -> Diff D.Doc
similar localizer ctx t1 t2 =
Diff (toDoc localizer ctx t1) (toDoc localizer ctx t2) Similar
different :: a -> a -> Bag.Bag Problem -> Diff a
different a b problems =
Diff a b (Different problems)
isSimilar :: Diff a -> Bool
isSimilar (Diff _ _ status) =
case status of
Similar -> True
Different _ -> False
isBool :: ModuleName.Canonical -> N.Name -> Bool
isBool home name =
home == ModuleName.basics && name == N.bool
isInt :: ModuleName.Canonical -> N.Name -> Bool
isInt home name =
home == ModuleName.basics && name == N.int
isFloat :: ModuleName.Canonical -> N.Name -> Bool
isFloat home name =
home == ModuleName.basics && name == N.float
isString :: ModuleName.Canonical -> N.Name -> Bool
isString home name =
home == ModuleName.string && name == N.string
isChar :: ModuleName.Canonical -> N.Name -> Bool
isChar home name =
home == ModuleName.char && name == N.char
isMaybe :: ModuleName.Canonical -> N.Name -> Bool
isMaybe home name =
home == ModuleName.maybe && name == N.maybe
isList :: ModuleName.Canonical -> N.Name -> Bool
isList home name =
home == ModuleName.list && name == N.list
isSuper :: Super -> Type -> Bool
isSuper super tipe =
case iteratedDealias tipe of
Type h n args ->
case super of
Number -> isInt h n || isFloat h n
Comparable -> isInt h n || isFloat h n || isString h n || isChar h n || isList h n && isSuper super (head args)
Appendable -> isString h n || isList h n
CompAppend -> isString h n || isList h n && isSuper Comparable (head args)
_ ->
False
NAME CLASH
nameClashToDoc :: RT.Context -> L.Localizer -> ModuleName.Canonical -> N.Name -> [Type] -> D.Doc
nameClashToDoc ctx localizer (ModuleName.Canonical _ home) name args =
RT.apply ctx
(D.yellow (D.fromName home) <> D.dullyellow ("." <> D.fromName name))
(map (toDoc localizer RT.App) args)
DIFF ALIASED RECORD
diffAliasedRecord :: L.Localizer -> Type -> Type -> Maybe (Diff D.Doc)
diffAliasedRecord localizer t1 t2 =
case (iteratedDealias t1, iteratedDealias t2) of
(Record fields1 ext1, Record fields2 ext2) ->
Just (diffRecord localizer fields1 ext1 fields2 ext2)
_ ->
Nothing
DIFF LAMBDAS
diffLambda :: L.Localizer -> RT.Context -> Type -> Type -> [Type] -> Type -> Type -> [Type] -> Diff D.Doc
diffLambda localizer ctx a1 b1 cs1 a2 b2 cs2 =
let
(result1:revArgs1) = reverse (a1:b1:cs1)
(result2:revArgs2) = reverse (a2:b2:cs2)
numArgs1 = length revArgs1
numArgs2 = length revArgs2
in
case toDiff localizer RT.Func result1 result2 of
Diff resultDoc1 resultDoc2 Similar ->
if numArgs1 < numArgs2 then
diffArgMismatch localizer ctx revArgs1 resultDoc1 revArgs2 resultDoc2
else
diffArgMismatch localizer ctx revArgs2 resultDoc2 revArgs1 resultDoc1
Diff resultDoc1 resultDoc2 (Different problems) ->
let
(a:b:cs) = reverse (resultDoc1 : map (toDoc localizer RT.Func) revArgs1)
(x:y:zs) = reverse (resultDoc2 : map (toDoc localizer RT.Func) revArgs2)
in
different
(D.dullyellow (RT.lambda ctx a b cs))
(D.dullyellow (RT.lambda ctx x y zs))
(Bag.append problems (Bag.one ReturnMismatch))
length shortRevArgs > = 2
length longRevArgs > = 2
length shortRevArgs < length longRevArgs
diffArgMismatch :: L.Localizer -> RT.Context -> [Type] -> D.Doc -> [Type] -> D.Doc -> Diff D.Doc
diffArgMismatch localizer ctx shortRevArgs shortResult longRevArgs longResult =
let
(a:b:cs, x:y:zs) =
case toGreedyMatch localizer shortRevArgs longRevArgs of
Just (GreedyMatch shortRevArgDocs longRevArgDocs) ->
( reverse (shortResult:shortRevArgDocs)
, reverse (longResult:longRevArgDocs)
)
Nothing ->
case toGreedyMatch localizer (reverse shortRevArgs) (reverse longRevArgs) of
Just (GreedyMatch shortArgDocs longArgDocs) ->
( shortArgDocs ++ [shortResult]
, longArgDocs ++ [longResult]
)
Nothing ->
let
toYellowDoc tipe =
D.dullyellow (toDoc localizer RT.Func tipe)
in
( reverse (shortResult : map toYellowDoc shortRevArgs)
, reverse (longResult : map toYellowDoc longRevArgs )
)
in
different
(RT.lambda ctx a b cs)
(RT.lambda ctx x y zs)
(Bag.one (MissingArgs (length longRevArgs - length shortRevArgs)))
data GreedyMatch =
GreedyMatch [D.Doc] [D.Doc]
toGreedyMatch :: L.Localizer -> [Type] -> [Type] -> Maybe GreedyMatch
toGreedyMatch localizer shorterArgs longerArgs =
toGreedyMatchHelp localizer shorterArgs longerArgs (GreedyMatch [] [])
toGreedyMatchHelp :: L.Localizer -> [Type] -> [Type] -> GreedyMatch -> Maybe GreedyMatch
toGreedyMatchHelp localizer shorterArgs longerArgs match@(GreedyMatch shorterDocs longerDocs) =
let
toYellowDoc tipe =
D.dullyellow (toDoc localizer RT.Func tipe)
in
case (shorterArgs, longerArgs) of
(x:xs, y:ys) ->
case toDiff localizer RT.Func x y of
Diff a b Similar ->
toGreedyMatchHelp localizer xs ys $
GreedyMatch (a:shorterDocs) (b:longerDocs)
Diff _ _ (Different _) ->
toGreedyMatchHelp localizer shorterArgs ys $
GreedyMatch shorterDocs (toYellowDoc y : longerDocs)
([], []) ->
Just match
([], _:_) ->
Just (GreedyMatch shorterDocs (map toYellowDoc longerArgs))
(_:_, []) ->
Nothing
diffRecord :: L.Localizer -> Map.Map N.Name Type -> Extension -> Map.Map N.Name Type -> Extension -> Diff D.Doc
diffRecord localizer fields1 ext1 fields2 ext2 =
let
toUnknownDocs field tipe =
( D.dullyellow (D.fromName field), toDoc localizer RT.None tipe )
toOverlapDocs field t1 t2 =
(,) (D.fromName field) <$> toDiff localizer RT.None t1 t2
left = Map.mapWithKey toUnknownDocs (Map.difference fields1 fields2)
both = Map.intersectionWithKey toOverlapDocs fields1 fields2
right = Map.mapWithKey toUnknownDocs (Map.difference fields2 fields1)
fieldsDiff =
Map.elems <$>
if Map.null left && Map.null right then
sequenceA both
else
Map.union
<$> sequenceA both
<*> Diff left right (Different Bag.empty)
(Diff doc1 doc2 status) =
RT.record
<$> fieldsDiff
<*> extToDiff ext1 ext2
in
Diff doc1 doc2 $ merge status $
case (hasFixedFields ext1, hasFixedFields ext2) of
(True, True) ->
case Map.lookupMin left of
Just (f,_) -> Different $ Bag.one $ FieldTypo f (Map.keys fields2)
Nothing ->
if Map.null right
then Similar
else Different $ Bag.one $ FieldsMissing (Map.keys right)
(False, True) ->
case Map.lookupMin left of
Just (f,_) -> Different $ Bag.one $ FieldTypo f (Map.keys fields2)
Nothing -> Similar
(True, False) ->
case Map.lookupMin right of
Just (f,_) -> Different $ Bag.one $ FieldTypo f (Map.keys fields1)
Nothing -> Similar
(False, False) ->
Similar
hasFixedFields :: Extension -> Bool
hasFixedFields ext =
case ext of
Closed -> True
FlexOpen _ -> False
RigidOpen _ -> True
DIFF RECORD EXTENSION
extToDiff :: Extension -> Extension -> Diff (Maybe D.Doc)
extToDiff ext1 ext2 =
let
status = extToStatus ext1 ext2
extDoc1 = extToDoc ext1
extDoc2 = extToDoc ext2
in
case status of
Similar ->
Diff extDoc1 extDoc2 status
Different _ ->
Diff (D.dullyellow <$> extDoc1) (D.dullyellow <$> extDoc2) status
extToStatus :: Extension -> Extension -> Status
extToStatus ext1 ext2 =
case ext1 of
Closed ->
case ext2 of
Closed -> Similar
FlexOpen _ -> Similar
RigidOpen _ -> Different Bag.empty
FlexOpen _ ->
Similar
RigidOpen x ->
case ext2 of
Closed -> Different Bag.empty
FlexOpen _ -> Similar
RigidOpen y ->
if x == y
then Similar
else Different $ Bag.one $ BadRigidVar x (RigidVar y)
|
34f47542610ea16e149b45337f97b7edd183b36c6aa118819714454e8e5ed780 | syucream/hastodon | Streaming.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module Web.Hastodon.Streaming
( StreamingPayload(..)
, StreamingResponse
, streamUser
, streamPublic
, streamLocal
, streamHashtag
, streamList
) where
import Prelude hiding (takeWhile)
import Control.Applicative ((<|>), many, some)
import Data.Aeson
import Data.Attoparsec.ByteString as A
import Data.Attoparsec.ByteString.Char8 as C8
import qualified Data.ByteString as BS
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B8
import Data.Maybe (maybeToList)
import Conduit
import Network.HTTP.Simple
import Web.Hastodon.Util
import Web.Hastodon.Types
----
-- Public API
----
pStreamUser = "/api/v1/streaming/user"
pStreamPublic = "/api/v1/streaming/public"
pStreamLocal = "/api/v1/streaming/public/local"
pStreamHashtag = "/api/v1/streaming/hashtag"
pStreamList = "/api/v1/streaming/list"
type StreamingResponse m =
forall m. MonadResource m => ConduitT () StreamingPayload m ()
data StreamingPayload = SUpdate Status |
SNotification Notification |
SDelete StatusId |
Thump
deriving (Show)
data EventType = EUpdate | ENotification | EDelete
streamUser :: HastodonClient -> StreamingResponse m
streamUser client = getStreamingResponse pStreamUser client
streamPublic :: HastodonClient -> StreamingResponse m
streamPublic client = getStreamingResponse pStreamPublic client
streamLocal :: HastodonClient -> StreamingResponse m
streamLocal client = getStreamingResponse pStreamLocal client
streamHashtag :: HastodonClient -> String -> StreamingResponse m
streamHashtag client hashtag = getStreamingResponse ph client where
ph = pStreamHashtag ++ "?hashtag=" ++ hashtag
streamList :: HastodonClient -> String -> StreamingResponse m
streamList client list = getStreamingResponse l client where
l = pStreamList ++ "?list=" ++ list
----
-- Private stuff
----
stream :: ByteString -> ByteString -> (ByteString, [StreamingPayload])
stream i a | isThump i = ("", [Thump])
| isEvent i = (i, [])
| otherwise = parseE a i
where parseE et d =
case parseET et of
(Just EDelete) -> ("", p parseDelete d)
(Just ENotification) -> ("", p parseNotification d)
(Just EUpdate) -> ("",p parseUpdate d)
Nothing -> ("", [])
p r s = maybeToList $ maybeResult $ parse r s
isThump = (":thump" `B8.isPrefixOf`)
isEvent = ("event: " `B8.isPrefixOf`)
parseET s = maybeResult $ parse parseEvent s
parseEvent :: Parser EventType
parseEvent = do
string "event: "
try ("delete" *> return EDelete) <|>
try ("update" *> return EUpdate) <|>
try ("notification" *> return ENotification)
pd = string "data: "
parseDelete :: Parser StreamingPayload
parseDelete = do
pd
i <- StatusId <$> many C8.digit
return $ SDelete i
eoc :: String -> Char -> Maybe String
eoc "\n" '\n' = Nothing
eoc acc c = Just (c:acc)
parseNotification :: Parser StreamingPayload
parseNotification = do
pd
s <- C8.takeTill (== '\n')
case (decodeStrict' s :: Maybe Notification) of
Nothing -> fail $ "decode error"
(Just n) -> return $ SNotification n
parseUpdate :: Parser StreamingPayload
parseUpdate = do
pd
s <- C8.takeTill (== '\n')
case (decodeStrict' s :: Maybe Status) of
Nothing -> fail $ "decode error"
(Just s) -> return $ SUpdate s
parseStream :: forall m. MonadResource m =>
ConduitT ByteString StreamingPayload m ()
parseStream = concatMapAccumC stream ""
getStreamingResponse path client = do
req <- liftIO $ mkHastodonRequest path client
httpSource req getResponseBody .| parseStream
| null | https://raw.githubusercontent.com/syucream/hastodon/70227686d9f7f3b3950fc689e1fbcb66dc9f15a8/Web/Hastodon/Streaming.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
--
Public API
--
--
Private stuff
-- |
module Web.Hastodon.Streaming
( StreamingPayload(..)
, StreamingResponse
, streamUser
, streamPublic
, streamLocal
, streamHashtag
, streamList
) where
import Prelude hiding (takeWhile)
import Control.Applicative ((<|>), many, some)
import Data.Aeson
import Data.Attoparsec.ByteString as A
import Data.Attoparsec.ByteString.Char8 as C8
import qualified Data.ByteString as BS
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B8
import Data.Maybe (maybeToList)
import Conduit
import Network.HTTP.Simple
import Web.Hastodon.Util
import Web.Hastodon.Types
pStreamUser = "/api/v1/streaming/user"
pStreamPublic = "/api/v1/streaming/public"
pStreamLocal = "/api/v1/streaming/public/local"
pStreamHashtag = "/api/v1/streaming/hashtag"
pStreamList = "/api/v1/streaming/list"
type StreamingResponse m =
forall m. MonadResource m => ConduitT () StreamingPayload m ()
data StreamingPayload = SUpdate Status |
SNotification Notification |
SDelete StatusId |
Thump
deriving (Show)
data EventType = EUpdate | ENotification | EDelete
streamUser :: HastodonClient -> StreamingResponse m
streamUser client = getStreamingResponse pStreamUser client
streamPublic :: HastodonClient -> StreamingResponse m
streamPublic client = getStreamingResponse pStreamPublic client
streamLocal :: HastodonClient -> StreamingResponse m
streamLocal client = getStreamingResponse pStreamLocal client
streamHashtag :: HastodonClient -> String -> StreamingResponse m
streamHashtag client hashtag = getStreamingResponse ph client where
ph = pStreamHashtag ++ "?hashtag=" ++ hashtag
streamList :: HastodonClient -> String -> StreamingResponse m
streamList client list = getStreamingResponse l client where
l = pStreamList ++ "?list=" ++ list
stream :: ByteString -> ByteString -> (ByteString, [StreamingPayload])
stream i a | isThump i = ("", [Thump])
| isEvent i = (i, [])
| otherwise = parseE a i
where parseE et d =
case parseET et of
(Just EDelete) -> ("", p parseDelete d)
(Just ENotification) -> ("", p parseNotification d)
(Just EUpdate) -> ("",p parseUpdate d)
Nothing -> ("", [])
p r s = maybeToList $ maybeResult $ parse r s
isThump = (":thump" `B8.isPrefixOf`)
isEvent = ("event: " `B8.isPrefixOf`)
parseET s = maybeResult $ parse parseEvent s
parseEvent :: Parser EventType
parseEvent = do
string "event: "
try ("delete" *> return EDelete) <|>
try ("update" *> return EUpdate) <|>
try ("notification" *> return ENotification)
pd = string "data: "
parseDelete :: Parser StreamingPayload
parseDelete = do
pd
i <- StatusId <$> many C8.digit
return $ SDelete i
eoc :: String -> Char -> Maybe String
eoc "\n" '\n' = Nothing
eoc acc c = Just (c:acc)
parseNotification :: Parser StreamingPayload
parseNotification = do
pd
s <- C8.takeTill (== '\n')
case (decodeStrict' s :: Maybe Notification) of
Nothing -> fail $ "decode error"
(Just n) -> return $ SNotification n
parseUpdate :: Parser StreamingPayload
parseUpdate = do
pd
s <- C8.takeTill (== '\n')
case (decodeStrict' s :: Maybe Status) of
Nothing -> fail $ "decode error"
(Just s) -> return $ SUpdate s
parseStream :: forall m. MonadResource m =>
ConduitT ByteString StreamingPayload m ()
parseStream = concatMapAccumC stream ""
getStreamingResponse path client = do
req <- liftIO $ mkHastodonRequest path client
httpSource req getResponseBody .| parseStream
|
5107985b04a22c2b04d4229c62c82eab3a1235c9d6294ad35ca3f1296535f239 | pkamenarsky/concur-replica | Main.hs | {-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Applicative
import Control.Monad.IO.Class (liftIO)
import Concur.Core.Types (Widget)
import Concur.Replica (HTML, runDefault)
import Concur.Replica.DOM (button, input, li, text, ul)
import Concur.Replica.DOM.Events (BaseEvent (target), onClick, onInput, targetValue)
import Concur.Replica.DOM.Props (value)
import Data.Text (Text)
import Control.Concurrent.STM (TVar, atomically, modifyTVar', newTVarIO, readTVar)
import Control.Concurrent.STM.TChan (TChan, dupTChan, newTChanIO, readTChan, writeTChan)
A simple chat app demonstrating communication between clients using STM .
The chatWidget is waiting for either the user to send a message or
-- another client to alert a new message. When a client sends a message
the chatWidget will update the messageHistory and then alert the other
clients by writing to .
type Message = Text
data EditorAction
= Typing Message -- The message the user is currently typing
| Send Message -- The message the user sends to other users
data ChatAction
Message from one client to the others
| NewMessagePosted
chatWidget :: TVar [Message] -> TChan () -> Widget HTML Message
chatWidget msgsTVar messageAlert = do
messageHistory <- liftIO . atomically . readTVar $ msgsTVar
-- Render messageList and messageEditor and wait for user to send
let newMessageToPost = NewMessageToPost <$> (messageEditor "" <|> messagesList messageHistory)
-- Wait for a message from other user
let newMessagePosted = NewMessagePosted <$ (liftIO . atomically . readTChan $ messageAlert)
Wait for whatever chatAction to happen first
chatAction <- newMessageToPost <|> newMessagePosted
case chatAction of
NewMessagePosted -> chatWidget msgsTVar messageAlert
NewMessageToPost newMessage -> do
liftIO . atomically $ do
-- Add this message to the messageHistory
modifyTVar' msgsTVar (newMessage :)
-- Notify all clients about the updates
writeTChan messageAlert ()
chatWidget msgsTVar messageAlert
messageEditor :: Message -> Widget HTML Message
messageEditor typing = do
let textInput = Typing . targetValue . target <$> input [value $ typing, onInput]
let submitButton = Send typing <$ button [onClick] [text "Send"]
Wait for whatever editorAction to happen first
editorAction <- textInput <|> submitButton
case editorAction of
Typing tm -> messageEditor tm
Send msg -> pure msg
messagesList :: [Message] -> Widget HTML Message
messagesList messageHistory = ul [] $ messageItem <$> messageHistory
messageItem :: Message -> Widget HTML Message
messageItem message = li [] [text message]
main :: IO ()
main = do
-- Channel to alert other clients that the messageHistory is updated
messageAlert <- newTChanIO
messageHistory <- newTVarIO []
runDefault 8080 "Chat" $ \_ -> chatWidget messageHistory
=<< (liftIO . atomically $ dupTChan messageAlert)
| null | https://raw.githubusercontent.com/pkamenarsky/concur-replica/e15785b3b09e97790ae23c8ae8671c191d039a2c/examples/Chat/Main.hs | haskell | # LANGUAGE OverloadedStrings #
another client to alert a new message. When a client sends a message
The message the user is currently typing
The message the user sends to other users
Render messageList and messageEditor and wait for user to send
Wait for a message from other user
Add this message to the messageHistory
Notify all clients about the updates
Channel to alert other clients that the messageHistory is updated |
module Main where
import Control.Applicative
import Control.Monad.IO.Class (liftIO)
import Concur.Core.Types (Widget)
import Concur.Replica (HTML, runDefault)
import Concur.Replica.DOM (button, input, li, text, ul)
import Concur.Replica.DOM.Events (BaseEvent (target), onClick, onInput, targetValue)
import Concur.Replica.DOM.Props (value)
import Data.Text (Text)
import Control.Concurrent.STM (TVar, atomically, modifyTVar', newTVarIO, readTVar)
import Control.Concurrent.STM.TChan (TChan, dupTChan, newTChanIO, readTChan, writeTChan)
A simple chat app demonstrating communication between clients using STM .
The chatWidget is waiting for either the user to send a message or
the chatWidget will update the messageHistory and then alert the other
clients by writing to .
type Message = Text
data EditorAction
data ChatAction
Message from one client to the others
| NewMessagePosted
chatWidget :: TVar [Message] -> TChan () -> Widget HTML Message
chatWidget msgsTVar messageAlert = do
messageHistory <- liftIO . atomically . readTVar $ msgsTVar
let newMessageToPost = NewMessageToPost <$> (messageEditor "" <|> messagesList messageHistory)
let newMessagePosted = NewMessagePosted <$ (liftIO . atomically . readTChan $ messageAlert)
Wait for whatever chatAction to happen first
chatAction <- newMessageToPost <|> newMessagePosted
case chatAction of
NewMessagePosted -> chatWidget msgsTVar messageAlert
NewMessageToPost newMessage -> do
liftIO . atomically $ do
modifyTVar' msgsTVar (newMessage :)
writeTChan messageAlert ()
chatWidget msgsTVar messageAlert
messageEditor :: Message -> Widget HTML Message
messageEditor typing = do
let textInput = Typing . targetValue . target <$> input [value $ typing, onInput]
let submitButton = Send typing <$ button [onClick] [text "Send"]
Wait for whatever editorAction to happen first
editorAction <- textInput <|> submitButton
case editorAction of
Typing tm -> messageEditor tm
Send msg -> pure msg
messagesList :: [Message] -> Widget HTML Message
messagesList messageHistory = ul [] $ messageItem <$> messageHistory
messageItem :: Message -> Widget HTML Message
messageItem message = li [] [text message]
main :: IO ()
main = do
messageAlert <- newTChanIO
messageHistory <- newTVarIO []
runDefault 8080 "Chat" $ \_ -> chatWidget messageHistory
=<< (liftIO . atomically $ dupTChan messageAlert)
|
d6c77165b12fd206a42a7d987ed65e5640e0ae7c79e02c70336a5a2cdf36959e | fulcrologic/guardrails | core_spec.cljc | (ns com.fulcrologic.guardrails.core-spec
(:require
[com.fulcrologic.guardrails.core :as gr :refer [>defn =>]]
[com.fulcrologic.guardrails.config :as config]
[clojure.spec.alpha :as s]
[fulcro-spec.core :refer [specification assertions component when-mocking provided]]
[clojure.test :refer [deftest is]]))
#?(:clj
(do
(System/setProperty "guardrails.enabled" "")
(System/setProperty "guardrails.config" "guardrails-test.edn")))
#?(:clj
(specification "loading config"
(assertions
"loads the config from the disk file"
(config/get-env-config false) => {:defn-macro nil
:throw? true
:expound {:show-valid-values? true
:print-specs? true}})))
#?(:clj
(specification "Normal mode >defn macro"
(let [test-fn '(>defn f [x] [int? => int?] (inc x))]
(provided "There is no config"
(config/get-env-config) => nil
(let [output (gr/>defn* {} test-fn (rest test-fn) {})]
(assertions
"Emits a normal function"
output => '(defn f [x] (inc x)))))
(provided "There is a free config"
(config/get-env-config & _) => {}
(gr/generate-defn & _) => '(:stub/free-defn)
(let [output (gr/>defn* {} test-fn (rest test-fn) {})]
(assertions
"Emits the free version"
output => `(:stub/free-defn)))))))
(>defn test-function
"docstring"
([a]
[int? => int?]
(if (> a 0)
(* a (test-function (dec a)))
1))
([a b]
[int? int? => int?]
(if (> a b)
(recur a (inc b))
(+ a b)))
([a b c & d]
[int? int? int? (s/* int?) => int?]
(if (seq d)
(reduce + 0 d)
(+ a b c))))
(s/def ::a int?)
(s/def ::b int?)
(>defn kw-func
[& {:keys [a b] :as c}]
[(s/keys* :req-un [::a] :opt-un [::b]) => int?]
(+ a b))
(>defn kw-func2
[x & {:keys [a b] :as c}]
[int? (s/keys* :req-un [::a] :opt-un [::b]) => int?]
(+ x a b))
(>defn seq-func
[x & [a b & more]]
[int? (s/* int?) => int?]
(+ x a b))
(>defn vararg-seq [& targets]
[(s/* vector?) => vector?]
(into [] (seq targets)))
(specification "General transformed functions"
(assertions
"fixed arity, recursive"
(test-function 3) => 6
"fixed arity, tail recusive"
(test-function 3 2) => 6
"vararg with no extra args"
(test-function 1 1 1) => 3
"vararg with extra args"
(test-function 1 1 1 1 1) => 2
"kwargs"
(kw-func :a 1 :b 2) => 3
(kw-func2 100 :a 1 :b 2) => 103
"seq destructuring on vararg"
(seq-func 100 1 2) => 103
"vararg of sequences"
(vararg-seq [:a 1] [:b 2]) => [[:a 1] [:b 2]]))
| null | https://raw.githubusercontent.com/fulcrologic/guardrails/17b47a7869314efbffe5dbe0c0daea7c30ed9006/src/test/com/fulcrologic/guardrails/core_spec.cljc | clojure | (ns com.fulcrologic.guardrails.core-spec
(:require
[com.fulcrologic.guardrails.core :as gr :refer [>defn =>]]
[com.fulcrologic.guardrails.config :as config]
[clojure.spec.alpha :as s]
[fulcro-spec.core :refer [specification assertions component when-mocking provided]]
[clojure.test :refer [deftest is]]))
#?(:clj
(do
(System/setProperty "guardrails.enabled" "")
(System/setProperty "guardrails.config" "guardrails-test.edn")))
#?(:clj
(specification "loading config"
(assertions
"loads the config from the disk file"
(config/get-env-config false) => {:defn-macro nil
:throw? true
:expound {:show-valid-values? true
:print-specs? true}})))
#?(:clj
(specification "Normal mode >defn macro"
(let [test-fn '(>defn f [x] [int? => int?] (inc x))]
(provided "There is no config"
(config/get-env-config) => nil
(let [output (gr/>defn* {} test-fn (rest test-fn) {})]
(assertions
"Emits a normal function"
output => '(defn f [x] (inc x)))))
(provided "There is a free config"
(config/get-env-config & _) => {}
(gr/generate-defn & _) => '(:stub/free-defn)
(let [output (gr/>defn* {} test-fn (rest test-fn) {})]
(assertions
"Emits the free version"
output => `(:stub/free-defn)))))))
(>defn test-function
"docstring"
([a]
[int? => int?]
(if (> a 0)
(* a (test-function (dec a)))
1))
([a b]
[int? int? => int?]
(if (> a b)
(recur a (inc b))
(+ a b)))
([a b c & d]
[int? int? int? (s/* int?) => int?]
(if (seq d)
(reduce + 0 d)
(+ a b c))))
(s/def ::a int?)
(s/def ::b int?)
(>defn kw-func
[& {:keys [a b] :as c}]
[(s/keys* :req-un [::a] :opt-un [::b]) => int?]
(+ a b))
(>defn kw-func2
[x & {:keys [a b] :as c}]
[int? (s/keys* :req-un [::a] :opt-un [::b]) => int?]
(+ x a b))
(>defn seq-func
[x & [a b & more]]
[int? (s/* int?) => int?]
(+ x a b))
(>defn vararg-seq [& targets]
[(s/* vector?) => vector?]
(into [] (seq targets)))
(specification "General transformed functions"
(assertions
"fixed arity, recursive"
(test-function 3) => 6
"fixed arity, tail recusive"
(test-function 3 2) => 6
"vararg with no extra args"
(test-function 1 1 1) => 3
"vararg with extra args"
(test-function 1 1 1 1 1) => 2
"kwargs"
(kw-func :a 1 :b 2) => 3
(kw-func2 100 :a 1 :b 2) => 103
"seq destructuring on vararg"
(seq-func 100 1 2) => 103
"vararg of sequences"
(vararg-seq [:a 1] [:b 2]) => [[:a 1] [:b 2]]))
|
|
d20156b2056eb228424d82885e3a91e32e8ae05d5f1abe0eb430ac4d495c2472 | AbstractMachinesLab/caramel | range.ml | open Import
include Lsp.Types.Range
(* Compares ranges by their lengths*)
let compare_size (x : t) (y : t) =
let dx = Position.(x.end_ - x.start) in
let dy = Position.(y.end_ - y.start) in
Stdune.Tuple.T2.compare Int.compare Int.compare (dx.line, dy.line)
(dx.character, dy.character)
let first_line =
let start = { Position.line = 1; character = 0 } in
let end_ = { Position.line = 2; character = 0 } in
{ start; end_ }
let of_loc (loc : Loc.t) : t =
(let open Option.O in
let* start = Position.of_lexical_position loc.loc_start in
let+ end_ = Position.of_lexical_position loc.loc_end in
{ start; end_ })
|> Option.value ~default:first_line
| null | https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/src/range.ml | ocaml | Compares ranges by their lengths | open Import
include Lsp.Types.Range
let compare_size (x : t) (y : t) =
let dx = Position.(x.end_ - x.start) in
let dy = Position.(y.end_ - y.start) in
Stdune.Tuple.T2.compare Int.compare Int.compare (dx.line, dy.line)
(dx.character, dy.character)
let first_line =
let start = { Position.line = 1; character = 0 } in
let end_ = { Position.line = 2; character = 0 } in
{ start; end_ }
let of_loc (loc : Loc.t) : t =
(let open Option.O in
let* start = Position.of_lexical_position loc.loc_start in
let+ end_ = Position.of_lexical_position loc.loc_end in
{ start; end_ })
|> Option.value ~default:first_line
|
0cbe657f67f30c170aed7d60c8593846354cb73c8a1cfcb1b0e32efaa79d3aa2 | whitequark/pry.ml | pry_instruct.ml | let pp_ident_tbl pp fmt tbl =
Format.fprintf fmt "{@[<hov> ";
tbl |> Ident.iter (fun id x ->
Format.fprintf fmt "%s.%d => %a;@ " id.Ident.name id.Ident.stamp pp x);
Format.fprintf fmt " @]}"
type compilation_env = Instruct.compilation_env =
{ ce_stack: int Ident.tbl [@polyprinter pp_ident_tbl];
ce_heap: int Ident.tbl [@polyprinter pp_ident_tbl];
ce_rec: int Ident.tbl [@polyprinter pp_ident_tbl] }
and debug_event = Instruct.debug_event =
{ mutable ev_pos: int;
ev_module: string;
ev_loc: Location.t [@printer Location.print_loc];
ev_kind: debug_event_kind;
ev_info: debug_event_info;
ev_typenv: Env.summary [@opaque];
ev_typsubst: Subst.t [@opaque];
ev_compenv: compilation_env;
ev_stacksize: int;
ev_repr: debug_event_repr }
and debug_event_kind = Instruct.debug_event_kind =
Event_before
| Event_after of Types.type_expr [@printer Printtyp.type_expr]
| Event_pseudo
and debug_event_info = Instruct.debug_event_info =
Event_function
| Event_return of int
| Event_other
and debug_event_repr = Instruct.debug_event_repr =
Event_none
| Event_parent of int ref
| Event_child of int ref
[@@deriving Show]
let compare_debug_event { ev_pos = a } { ev_pos = b } =
compare a b
| null | https://raw.githubusercontent.com/whitequark/pry.ml/ff8d8e9861ddd67f68994c468f199643416c5f42/src/pry_instruct.ml | ocaml | let pp_ident_tbl pp fmt tbl =
Format.fprintf fmt "{@[<hov> ";
tbl |> Ident.iter (fun id x ->
Format.fprintf fmt "%s.%d => %a;@ " id.Ident.name id.Ident.stamp pp x);
Format.fprintf fmt " @]}"
type compilation_env = Instruct.compilation_env =
{ ce_stack: int Ident.tbl [@polyprinter pp_ident_tbl];
ce_heap: int Ident.tbl [@polyprinter pp_ident_tbl];
ce_rec: int Ident.tbl [@polyprinter pp_ident_tbl] }
and debug_event = Instruct.debug_event =
{ mutable ev_pos: int;
ev_module: string;
ev_loc: Location.t [@printer Location.print_loc];
ev_kind: debug_event_kind;
ev_info: debug_event_info;
ev_typenv: Env.summary [@opaque];
ev_typsubst: Subst.t [@opaque];
ev_compenv: compilation_env;
ev_stacksize: int;
ev_repr: debug_event_repr }
and debug_event_kind = Instruct.debug_event_kind =
Event_before
| Event_after of Types.type_expr [@printer Printtyp.type_expr]
| Event_pseudo
and debug_event_info = Instruct.debug_event_info =
Event_function
| Event_return of int
| Event_other
and debug_event_repr = Instruct.debug_event_repr =
Event_none
| Event_parent of int ref
| Event_child of int ref
[@@deriving Show]
let compare_debug_event { ev_pos = a } { ev_pos = b } =
compare a b
|
|
53faf34854862465fd751882af1609984f3bc71374fcc87544c5ba8b93e6d399 | hunt-framework/hunt | Command.hs | module Hunt.CLI.Command
( Command (..)
, run
, parser
) where
import Data.Monoid ((<>))
import qualified Hunt.CLI.Command.Client as Client
import qualified Hunt.CLI.Command.Server as Server
import Options.Applicative
-- COMMAND
data Command
= Client Client.Command
| Server Server.Command
deriving (Show)
-- PARSER
parser :: Parser Command
parser =
subparser
( command "query" (info (Client <$> Client.parser <**> helper) (progDesc "Query a running hunt-server"))
<> command "server" (info (Server <$> Server.parser <**> helper) (progDesc "Start a new Hunt server"))
)
-- RUN
run :: Command -> IO ()
run command =
case command of
Client clientCommand ->
Client.run clientCommand
Server serverCommand ->
Server.run serverCommand
| null | https://raw.githubusercontent.com/hunt-framework/hunt/d692aae756b7bdfb4c99f5a3951aec12893649a8/hunt-cli/src/Hunt/CLI/Command.hs | haskell | COMMAND
PARSER
RUN | module Hunt.CLI.Command
( Command (..)
, run
, parser
) where
import Data.Monoid ((<>))
import qualified Hunt.CLI.Command.Client as Client
import qualified Hunt.CLI.Command.Server as Server
import Options.Applicative
data Command
= Client Client.Command
| Server Server.Command
deriving (Show)
parser :: Parser Command
parser =
subparser
( command "query" (info (Client <$> Client.parser <**> helper) (progDesc "Query a running hunt-server"))
<> command "server" (info (Server <$> Server.parser <**> helper) (progDesc "Start a new Hunt server"))
)
run :: Command -> IO ()
run command =
case command of
Client clientCommand ->
Client.run clientCommand
Server serverCommand ->
Server.run serverCommand
|
a9953ec071e6e508e0d5720a02293a60085e78eb7b26ebae57f73b349aef9c46 | c4-project/c4f | reify.mli | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
* Functions for reifying a FIR program into an AST .
These functions reify various top - level elements of a FIR program . Other
modules govern smaller components :
- { ! Reify_atomic } for atomics ;
- { ! Reify_prim } for miscellaneous primitives ;
- { ! Reify_expr } for expressions ;
- { ! Reify_stm } for statements .
These functions reify various top-level elements of a FIR program. Other
modules govern smaller components:
- {!Reify_atomic} for atomics;
- {!Reify_prim} for miscellaneous primitives;
- {!Reify_expr} for expressions;
- {!Reify_stm} for statements. *)
val func : _ C4f_fir.Function.t C4f_common.C_named.t -> Ast.External_decl.t
* [ func f ] reifies the FIR function [ f ] into the C AST .
val program : _ C4f_fir.Program.t -> Ast.Translation_unit.t
* [ program p ] reifies the FIR program [ p ] into the C AST .
* { 1 Pretty printers using reification }
val pp_func : _ C4f_fir.Function.t C4f_common.C_named.t Fmt.t
* [ pp_func ] pretty - prints FIR functions via { ! func } .
val pp : _ C4f_fir.Program.t Fmt.t
* [ pp ] pretty - prints FIR programs via { ! program } .
* { 2 Litmus tests }
val pp_litmus_raw : C4f_litmus.Test.Raw.M(C4f_fir.Litmus.Lang).t Fmt.t
* [ pp_litmus_raw ] pretty - prints unverified FIR litmus tests .
val pp_litmus : C4f_fir.Litmus.Test.t Fmt.t
* [ pp_litmus ] pretty - prints verified FIR litmus tests .
| null | https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/litmus_c/src/reify.mli | ocaml | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
* Functions for reifying a FIR program into an AST .
These functions reify various top - level elements of a FIR program . Other
modules govern smaller components :
- { ! Reify_atomic } for atomics ;
- { ! Reify_prim } for miscellaneous primitives ;
- { ! Reify_expr } for expressions ;
- { ! Reify_stm } for statements .
These functions reify various top-level elements of a FIR program. Other
modules govern smaller components:
- {!Reify_atomic} for atomics;
- {!Reify_prim} for miscellaneous primitives;
- {!Reify_expr} for expressions;
- {!Reify_stm} for statements. *)
val func : _ C4f_fir.Function.t C4f_common.C_named.t -> Ast.External_decl.t
* [ func f ] reifies the FIR function [ f ] into the C AST .
val program : _ C4f_fir.Program.t -> Ast.Translation_unit.t
* [ program p ] reifies the FIR program [ p ] into the C AST .
* { 1 Pretty printers using reification }
val pp_func : _ C4f_fir.Function.t C4f_common.C_named.t Fmt.t
* [ pp_func ] pretty - prints FIR functions via { ! func } .
val pp : _ C4f_fir.Program.t Fmt.t
* [ pp ] pretty - prints FIR programs via { ! program } .
* { 2 Litmus tests }
val pp_litmus_raw : C4f_litmus.Test.Raw.M(C4f_fir.Litmus.Lang).t Fmt.t
* [ pp_litmus_raw ] pretty - prints unverified FIR litmus tests .
val pp_litmus : C4f_fir.Litmus.Test.t Fmt.t
* [ pp_litmus ] pretty - prints verified FIR litmus tests .
|
|
3fe3a91137fbd5c29c0412ea00d795183ed64989abce707b8ae1b7b841be5890 | fission-codes/fission | Prefix.hs | module Fission.Unit.Prefix
( convert
, module Fission.Unit.Prefix.Class
, module Fission.Unit.Prefix.Types
) where
import RIO
import Fission.Unit.Prefix.Class
import Fission.Unit.Prefix.Types
convert :: (FromPrefixed n a, ToPrefixed m a) => n a -> m a
convert = toPrefixed . fromPrefixed
| null | https://raw.githubusercontent.com/fission-codes/fission/11d14b729ccebfd69499a534445fb072ac3433a3/fission-core/library/Fission/Unit/Prefix.hs | haskell | module Fission.Unit.Prefix
( convert
, module Fission.Unit.Prefix.Class
, module Fission.Unit.Prefix.Types
) where
import RIO
import Fission.Unit.Prefix.Class
import Fission.Unit.Prefix.Types
convert :: (FromPrefixed n a, ToPrefixed m a) => n a -> m a
convert = toPrefixed . fromPrefixed
|
|
d3b54ccf087db20342b14878c9e20b59b64ea2f4176a13bdda6257f7f4949659 | arachne-framework/aristotle | validation_test.clj | (ns arachne.aristotle.validation-test
(:require [clojure.test :refer :all]
[arachne.aristotle :as aa]
[arachne.aristotle.registry :as reg]
[arachne.aristotle.validation :as v]
[clojure.java.io :as io]))
(reg/prefix 'daml "+oil#")
(reg/prefix 'wo.tf "#")
(reg/prefix 'arachne "-framework.org/#")
(deftest disjoint-classes
(let [g (aa/read (aa/graph :jena-mini) (io/resource "TheFirm.n3"))
g (aa/add g {:rdf/about :wo.tf/TheFirm
:wo.tf/freeLancesTo :wo.tf/TheFirm})]
(is (empty? (v/validate g)))
(let [g (aa/add g {:rdf/about :wo.tf/Company
:owl/disjointWith :wo.tf/Person})
errors (v/validate g)]
(is (= 2 (count errors)))
(is (re-find #"disjoint" (::v/description (first errors))))
(is (re-find #"same and different" (::v/description (second errors)))))))
(deftest functional-object-properties
(let [g (aa/add (aa/graph :jena-mini)
[{:rdf/about :arachne/legalSpouse
:rdf/type [:owl/ObjectProperty :owl/FunctionalProperty]
:rdfs/domain :arachne/Person
:rdfs/range :arachne/Person}
{:rdf/about :arachne/jon
:arachne/name "John"
:arachne/legalSpouse [{:rdf/about :arachne/will
:arachne/name "William"}]}
{:rdf/about :arachne/jon
:arachne/legalSpouse [{:rdf/about :arachne/bill
:arachne/name "Bill"
:owl/differentFrom :arachne/will}]}])]
(let [errors (v/validate g)]
(is (not (empty? errors)))
(is (some #(re-find #"too many values" (::v/jena-type %)) errors)))))
(deftest functional-datatype-properties
(let [g (aa/add (aa/graph :jena-mini)
[{:rdf/about :arachne/name
:rdf/type [:owl/DatatypeProperty :owl/FunctionalProperty]
:rdfs/domain :arachne/Person
:rdfs/range :xsd/string}
{:rdf/about :arachne/jon
:arachne/name #{"John" "Jeff"}}])]
(let [errors (v/validate g)]
(is (not (empty? errors)))
(is (some #(re-find #"too many values" (::v/jena-type %)) errors)))))
(deftest max-cardinality-datatype
(let [g (aa/add (aa/graph :jena-mini)
[{:rdf/about :arachne/Person
:rdfs/subClassOf {:rdf/type :owl/Restriction
:owl/onProperty :arachne/name
:owl/maxCardinality 2}}
{:rdf/about :arachne/name
:rdf/type [:owl/DatatypeProperty]
:rdfs/domain :arachne/Person
:rdfs/range :xsd/string}
{:rdf/about :arachne/jon
:arachne/name #{"John" "Jeff" "James"}}])]
(let [errors (v/validate g)]
(is (not (empty? errors)))
(is (some #(re-find #"too many values" (::v/jena-type %)) errors)))))
(deftest max-cardinality-object
(testing "max 1"
(let [g (aa/add (aa/graph :jena-mini)
[{:rdf/about :arachne/Person
:rdfs/subClassOf {:rdf/type :owl/Restriction
:owl/onProperty :arachne/friends
:owl/maxCardinality 1}}
{:rdf/about :arachne/friends
:rdf/type [:owl/ObjectProperty]
:rdfs/domain :arachne/Person
:rdfs/range :arachne/Person}
{:rdf/about :arachne/jon
:arachne/name "John"
:arachne/friends #{{:rdf/about :arachne/jeff
:arachne/name "Jeff"
:owl/differentFrom :arachne/jim}
{:rdf/about :arachne/jim
:arachne/name "James"}}}])]
(let [errors (v/validate g)]
(is (not (empty? errors)))
(is (some #(re-find #"too many values" (::v/jena-type %)) errors))))
(testing "max N"
(let [g (aa/add (aa/graph :jena-mini)
[{:rdf/about :arachne/Person
:rdfs/subClassOf {:rdf/type :owl/Restriction
:owl/onProperty :arachne/friends
:owl/maxCardinality 2}}
{:rdf/about :arachne/friends
:rdf/type [:owl/ObjectProperty]
:rdfs/domain :arachne/Person
:rdfs/range :arachne/Person}
{:rdf/about :arachne/jon
:arachne/name "John"
:arachne/friends #{{:rdf/about :arachne/jeff
:arachne/name "Jeff"
:owl/differentFrom [:arachne/jim :arachne/sara]}
{:rdf/about :arachne/jim
:arachne/name "James"
:owl/differentFrom [:arachne/sara :arachne/jeff]}
{:rdf/about :arachne/sara
:arachne/name "Sarah"
:owl/differentFrom [:arachne/jim :arachne/jeff]}}}])]
(let [errors (v/validate g)]
;; The reasoner doesn't support this currently and there isn't a
;; great way to write a query, so we'll do without
(is (empty? errors)))))))
(deftest min-cardinality
(let [schema [{:rdf/about :arachne/Person
:rdfs/subClassOf [{:rdf/type :owl/Restriction
:owl/onProperty :arachne/name
:owl/cardinality 1}
{:rdf/type :owl/Restriction
:owl/onProperty :arachne/friends
:owl/minCardinality 2}]}
{:rdf/about :arachne/name
:rdf/type [:owl/DatatypeProperty]
:rdfs/domain :arachne/Person
:rdfs/range :xsd/string}
{:rdf/about :arachne/friends
:rdf/type [:owl/ObjectProperty]
:rdfs/domain :arachne/Person
:rdfs/range :arachne/Person}]]
(let [g (-> (aa/graph :jena-mini) (aa/add schema)
(aa/add [{:rdf/about :arachne/jon
:arachne/name "John"
:arachne/friends {:rdf/about :arachne/nicole}}]))]
(let [errors (v/validate g [v/min-cardinality])]
(is (= 3 (count errors)))
(is (= #{::v/min-cardinality} (set (map ::v/type errors))))
(is (= {:arachne/name 1
:arachne/friends 2} (frequencies
(map (comp :property ::v/details) errors))))
(is (= {:arachne/jon 1
:arachne/nicole 2} (frequencies
(map (comp :entity ::v/details) errors))))))))
| null | https://raw.githubusercontent.com/arachne-framework/aristotle/86f3ace210318bd9820322da45e627cec9cfba48/test/arachne/aristotle/validation_test.clj | clojure | The reasoner doesn't support this currently and there isn't a
great way to write a query, so we'll do without | (ns arachne.aristotle.validation-test
(:require [clojure.test :refer :all]
[arachne.aristotle :as aa]
[arachne.aristotle.registry :as reg]
[arachne.aristotle.validation :as v]
[clojure.java.io :as io]))
(reg/prefix 'daml "+oil#")
(reg/prefix 'wo.tf "#")
(reg/prefix 'arachne "-framework.org/#")
(deftest disjoint-classes
(let [g (aa/read (aa/graph :jena-mini) (io/resource "TheFirm.n3"))
g (aa/add g {:rdf/about :wo.tf/TheFirm
:wo.tf/freeLancesTo :wo.tf/TheFirm})]
(is (empty? (v/validate g)))
(let [g (aa/add g {:rdf/about :wo.tf/Company
:owl/disjointWith :wo.tf/Person})
errors (v/validate g)]
(is (= 2 (count errors)))
(is (re-find #"disjoint" (::v/description (first errors))))
(is (re-find #"same and different" (::v/description (second errors)))))))
(deftest functional-object-properties
(let [g (aa/add (aa/graph :jena-mini)
[{:rdf/about :arachne/legalSpouse
:rdf/type [:owl/ObjectProperty :owl/FunctionalProperty]
:rdfs/domain :arachne/Person
:rdfs/range :arachne/Person}
{:rdf/about :arachne/jon
:arachne/name "John"
:arachne/legalSpouse [{:rdf/about :arachne/will
:arachne/name "William"}]}
{:rdf/about :arachne/jon
:arachne/legalSpouse [{:rdf/about :arachne/bill
:arachne/name "Bill"
:owl/differentFrom :arachne/will}]}])]
(let [errors (v/validate g)]
(is (not (empty? errors)))
(is (some #(re-find #"too many values" (::v/jena-type %)) errors)))))
(deftest functional-datatype-properties
(let [g (aa/add (aa/graph :jena-mini)
[{:rdf/about :arachne/name
:rdf/type [:owl/DatatypeProperty :owl/FunctionalProperty]
:rdfs/domain :arachne/Person
:rdfs/range :xsd/string}
{:rdf/about :arachne/jon
:arachne/name #{"John" "Jeff"}}])]
(let [errors (v/validate g)]
(is (not (empty? errors)))
(is (some #(re-find #"too many values" (::v/jena-type %)) errors)))))
(deftest max-cardinality-datatype
(let [g (aa/add (aa/graph :jena-mini)
[{:rdf/about :arachne/Person
:rdfs/subClassOf {:rdf/type :owl/Restriction
:owl/onProperty :arachne/name
:owl/maxCardinality 2}}
{:rdf/about :arachne/name
:rdf/type [:owl/DatatypeProperty]
:rdfs/domain :arachne/Person
:rdfs/range :xsd/string}
{:rdf/about :arachne/jon
:arachne/name #{"John" "Jeff" "James"}}])]
(let [errors (v/validate g)]
(is (not (empty? errors)))
(is (some #(re-find #"too many values" (::v/jena-type %)) errors)))))
(deftest max-cardinality-object
(testing "max 1"
(let [g (aa/add (aa/graph :jena-mini)
[{:rdf/about :arachne/Person
:rdfs/subClassOf {:rdf/type :owl/Restriction
:owl/onProperty :arachne/friends
:owl/maxCardinality 1}}
{:rdf/about :arachne/friends
:rdf/type [:owl/ObjectProperty]
:rdfs/domain :arachne/Person
:rdfs/range :arachne/Person}
{:rdf/about :arachne/jon
:arachne/name "John"
:arachne/friends #{{:rdf/about :arachne/jeff
:arachne/name "Jeff"
:owl/differentFrom :arachne/jim}
{:rdf/about :arachne/jim
:arachne/name "James"}}}])]
(let [errors (v/validate g)]
(is (not (empty? errors)))
(is (some #(re-find #"too many values" (::v/jena-type %)) errors))))
(testing "max N"
(let [g (aa/add (aa/graph :jena-mini)
[{:rdf/about :arachne/Person
:rdfs/subClassOf {:rdf/type :owl/Restriction
:owl/onProperty :arachne/friends
:owl/maxCardinality 2}}
{:rdf/about :arachne/friends
:rdf/type [:owl/ObjectProperty]
:rdfs/domain :arachne/Person
:rdfs/range :arachne/Person}
{:rdf/about :arachne/jon
:arachne/name "John"
:arachne/friends #{{:rdf/about :arachne/jeff
:arachne/name "Jeff"
:owl/differentFrom [:arachne/jim :arachne/sara]}
{:rdf/about :arachne/jim
:arachne/name "James"
:owl/differentFrom [:arachne/sara :arachne/jeff]}
{:rdf/about :arachne/sara
:arachne/name "Sarah"
:owl/differentFrom [:arachne/jim :arachne/jeff]}}}])]
(let [errors (v/validate g)]
(is (empty? errors)))))))
(deftest min-cardinality
(let [schema [{:rdf/about :arachne/Person
:rdfs/subClassOf [{:rdf/type :owl/Restriction
:owl/onProperty :arachne/name
:owl/cardinality 1}
{:rdf/type :owl/Restriction
:owl/onProperty :arachne/friends
:owl/minCardinality 2}]}
{:rdf/about :arachne/name
:rdf/type [:owl/DatatypeProperty]
:rdfs/domain :arachne/Person
:rdfs/range :xsd/string}
{:rdf/about :arachne/friends
:rdf/type [:owl/ObjectProperty]
:rdfs/domain :arachne/Person
:rdfs/range :arachne/Person}]]
(let [g (-> (aa/graph :jena-mini) (aa/add schema)
(aa/add [{:rdf/about :arachne/jon
:arachne/name "John"
:arachne/friends {:rdf/about :arachne/nicole}}]))]
(let [errors (v/validate g [v/min-cardinality])]
(is (= 3 (count errors)))
(is (= #{::v/min-cardinality} (set (map ::v/type errors))))
(is (= {:arachne/name 1
:arachne/friends 2} (frequencies
(map (comp :property ::v/details) errors))))
(is (= {:arachne/jon 1
:arachne/nicole 2} (frequencies
(map (comp :entity ::v/details) errors))))))))
|
b6d50729a8e8ecf3097edde8c6dde35f4dce7d41b35625954503a94af0f7da0e | rtoy/ansi-cl-tests | import.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Thu Feb 19 07:06:48 2004
;;;; Contains: Tests of IMPORT
(in-package :cl-test)
(compile-and-load "package-aux.lsp")
;;; Create a package name that does not collide with an existing package
;;; name or nickname
(defvar *import-package-test-name*
(loop for i from 1
for name = (format nil "ITP-~A" i)
unless (find-package name) return name))
(deftest import.1
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo))
(values
(multiple-value-list (import sym pkg))
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(eqlt (symbol-package sym) (find-package :cl-test))
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.2
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo))
(values
(multiple-value-list (import (list sym) pkg))
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(eqlt (symbol-package sym) (find-package :cl-test))
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.3
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((*package* (eval `(defpackage ,pkg-name (:use))))
(sym 'foo))
(values
(multiple-value-list (import sym))
(eqlt (find-symbol (symbol-name sym)) sym)
(eqlt (symbol-package sym) (find-package :cl-test))
(external-symbols-in-package *package*)
)))
(t) t t nil)
(deftest import.4
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(syms '(foo bar baz)))
(values
(multiple-value-list (import syms pkg))
(loop for sym in syms always
(eqlt (find-symbol (symbol-name sym) pkg) sym))
(loop for sym in syms always
(eqlt (symbol-package sym) (find-package :cl-test)))
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.5
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym (make-symbol (symbol-name :foo))))
(values
(multiple-value-list (import sym pkg))
(eqlt (symbol-package sym) pkg)
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.6
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let* ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym (intern (symbol-name :foo) pkg)))
(values
(multiple-value-list (import sym pkg))
(eqlt (symbol-package sym) pkg)
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.7
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let* ((pkg (eval `(defpackage ,pkg-name (:use) (:export #:foo))))
(sym (intern (symbol-name :foo) pkg)))
(values
(multiple-value-list (import sym pkg))
(eqlt (symbol-package sym) pkg)
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(length (external-symbols-in-package pkg))
(eqlt (car (external-symbols-in-package pkg)) sym)
)))
(t) t t 1 t)
(deftest import.8
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo))
(values
(multiple-value-list (import sym pkg-name))
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(eqlt (symbol-package sym) (find-package :cl-test))
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.9
(let ((pkg-name "Z"))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo))
(values
(multiple-value-list (import sym #\Z))
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(eqlt (symbol-package sym) (find-package :cl-test))
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.10
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo))
(values
(let ((pname (make-array (length pkg-name) :element-type 'base-char
:initial-contents pkg-name)))
(multiple-value-list (import sym pname)))
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(eqlt (symbol-package sym) (find-package :cl-test))
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.11
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo))
(values
(let ((pname (make-array (+ 3 (length pkg-name))
:element-type 'base-char
:fill-pointer (length pkg-name)
:initial-contents (concatenate 'string pkg-name "XYZ"))))
(multiple-value-list (import sym pname)))
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(eqlt (symbol-package sym) (find-package :cl-test))
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.12
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo))
(values
(let* ((pname0 (make-array (+ 4 (length pkg-name))
:element-type 'base-char
:fill-pointer (length pkg-name)
:initial-contents (concatenate 'string " " pkg-name "XY")))
(pname (make-array (length pkg-name) :element-type 'base-char
:displaced-to pname0
:displaced-index-offset 2)))
(multiple-value-list (import sym pname)))
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(eqlt (symbol-package sym) (find-package :cl-test))
(external-symbols-in-package pkg)
)))
(t) t t nil)
;;; Error tests
(deftest import.error.1
(signals-error (import) program-error)
t)
(deftest import.error.2
(signals-error (import 'nil (find-package :cl-test) nil) program-error)
t)
(deftest import.error.3
(signals-error
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let* ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo)
(name (symbol-name sym)))
(intern name pkg)
(import sym pkg)))
package-error)
t)
(deftest import.error.4
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let* ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo)
(name (symbol-name sym))
(isym (intern name pkg))
(outer-restarts (compute-restarts)))
(block done
(and
(handler-bind
((package-error
#'(lambda (c)
There should be at least one restart
;; associated with this condition that was
;; not a preexisting restart
(let ((my-restarts
(remove 'abort
(set-difference (compute-restarts c)
outer-restarts)
:key #'restart-name)))
(assert my-restarts)
; (unintern isym pkg)
; (when (find 'continue my-restarts :key #'restart-name) (continue c))
(return-from done :good)))))
(import sym pkg))
(eqlt (find-symbol name pkg) sym)
(eqlt (symbol-package sym) (find-package "CL-TEST"))
:good))))
:good)
(deftest import.error.5
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let* ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo)
(name (symbol-name sym))
(isym (shadow name pkg)) ;; shadow instead of intern
(outer-restarts (compute-restarts)))
(block done
(and
(handler-bind
((package-error
#'(lambda (c)
There should be at least one restart
;; associated with this condition that was
;; not a preexisting restart
(let ((my-restarts
(remove 'abort
(set-difference (compute-restarts c)
outer-restarts)
:key #'restart-name)))
(assert my-restarts)
; (unintern isym pkg)
; (when (find 'continue my-restarts :key #'restart-name) (continue c))
(return-from done :good)))))
(import sym pkg))
(eqlt (find-symbol name pkg) sym)
(eqlt (symbol-package sym) (find-package "CL-TEST"))
:good))))
:good)
| null | https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/import.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests of IMPORT
Create a package name that does not collide with an existing package
name or nickname
Error tests
associated with this condition that was
not a preexisting restart
(unintern isym pkg)
(when (find 'continue my-restarts :key #'restart-name) (continue c))
shadow instead of intern
associated with this condition that was
not a preexisting restart
(unintern isym pkg)
(when (find 'continue my-restarts :key #'restart-name) (continue c)) | Author :
Created : Thu Feb 19 07:06:48 2004
(in-package :cl-test)
(compile-and-load "package-aux.lsp")
(defvar *import-package-test-name*
(loop for i from 1
for name = (format nil "ITP-~A" i)
unless (find-package name) return name))
(deftest import.1
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo))
(values
(multiple-value-list (import sym pkg))
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(eqlt (symbol-package sym) (find-package :cl-test))
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.2
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo))
(values
(multiple-value-list (import (list sym) pkg))
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(eqlt (symbol-package sym) (find-package :cl-test))
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.3
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((*package* (eval `(defpackage ,pkg-name (:use))))
(sym 'foo))
(values
(multiple-value-list (import sym))
(eqlt (find-symbol (symbol-name sym)) sym)
(eqlt (symbol-package sym) (find-package :cl-test))
(external-symbols-in-package *package*)
)))
(t) t t nil)
(deftest import.4
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(syms '(foo bar baz)))
(values
(multiple-value-list (import syms pkg))
(loop for sym in syms always
(eqlt (find-symbol (symbol-name sym) pkg) sym))
(loop for sym in syms always
(eqlt (symbol-package sym) (find-package :cl-test)))
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.5
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym (make-symbol (symbol-name :foo))))
(values
(multiple-value-list (import sym pkg))
(eqlt (symbol-package sym) pkg)
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.6
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let* ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym (intern (symbol-name :foo) pkg)))
(values
(multiple-value-list (import sym pkg))
(eqlt (symbol-package sym) pkg)
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.7
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let* ((pkg (eval `(defpackage ,pkg-name (:use) (:export #:foo))))
(sym (intern (symbol-name :foo) pkg)))
(values
(multiple-value-list (import sym pkg))
(eqlt (symbol-package sym) pkg)
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(length (external-symbols-in-package pkg))
(eqlt (car (external-symbols-in-package pkg)) sym)
)))
(t) t t 1 t)
(deftest import.8
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo))
(values
(multiple-value-list (import sym pkg-name))
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(eqlt (symbol-package sym) (find-package :cl-test))
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.9
(let ((pkg-name "Z"))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo))
(values
(multiple-value-list (import sym #\Z))
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(eqlt (symbol-package sym) (find-package :cl-test))
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.10
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo))
(values
(let ((pname (make-array (length pkg-name) :element-type 'base-char
:initial-contents pkg-name)))
(multiple-value-list (import sym pname)))
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(eqlt (symbol-package sym) (find-package :cl-test))
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.11
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo))
(values
(let ((pname (make-array (+ 3 (length pkg-name))
:element-type 'base-char
:fill-pointer (length pkg-name)
:initial-contents (concatenate 'string pkg-name "XYZ"))))
(multiple-value-list (import sym pname)))
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(eqlt (symbol-package sym) (find-package :cl-test))
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.12
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo))
(values
(let* ((pname0 (make-array (+ 4 (length pkg-name))
:element-type 'base-char
:fill-pointer (length pkg-name)
:initial-contents (concatenate 'string " " pkg-name "XY")))
(pname (make-array (length pkg-name) :element-type 'base-char
:displaced-to pname0
:displaced-index-offset 2)))
(multiple-value-list (import sym pname)))
(eqlt (find-symbol (symbol-name sym) pkg) sym)
(eqlt (symbol-package sym) (find-package :cl-test))
(external-symbols-in-package pkg)
)))
(t) t t nil)
(deftest import.error.1
(signals-error (import) program-error)
t)
(deftest import.error.2
(signals-error (import 'nil (find-package :cl-test) nil) program-error)
t)
(deftest import.error.3
(signals-error
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let* ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo)
(name (symbol-name sym)))
(intern name pkg)
(import sym pkg)))
package-error)
t)
(deftest import.error.4
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let* ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo)
(name (symbol-name sym))
(isym (intern name pkg))
(outer-restarts (compute-restarts)))
(block done
(and
(handler-bind
((package-error
#'(lambda (c)
There should be at least one restart
(let ((my-restarts
(remove 'abort
(set-difference (compute-restarts c)
outer-restarts)
:key #'restart-name)))
(assert my-restarts)
(return-from done :good)))))
(import sym pkg))
(eqlt (find-symbol name pkg) sym)
(eqlt (symbol-package sym) (find-package "CL-TEST"))
:good))))
:good)
(deftest import.error.5
(let ((pkg-name *import-package-test-name*))
(safely-delete-package pkg-name)
(let* ((pkg (eval `(defpackage ,pkg-name (:use))))
(sym 'foo)
(name (symbol-name sym))
(outer-restarts (compute-restarts)))
(block done
(and
(handler-bind
((package-error
#'(lambda (c)
There should be at least one restart
(let ((my-restarts
(remove 'abort
(set-difference (compute-restarts c)
outer-restarts)
:key #'restart-name)))
(assert my-restarts)
(return-from done :good)))))
(import sym pkg))
(eqlt (find-symbol name pkg) sym)
(eqlt (symbol-package sym) (find-package "CL-TEST"))
:good))))
:good)
|
67b7f10490726fe150413d2c05fcd36f50954cd92a0b751cbf9bfbc85a7ff597 | ekmett/contravariant | Divisible.hs | # LANGUAGE CPP #
# LANGUAGE TypeOperators #
# LANGUAGE BlockArguments #
{-# LANGUAGE Safe #-}
-- |
Copyright : ( C ) 2014 - 2021
License : BSD-2 - Clause OR Apache-2.0
Maintainer : < >
-- Stability : provisional
-- Portability : portable
--
-- This module supplies contravariant analogues to the 'Applicative' and 'Alternative' classes.
module Data.Functor.Contravariant.Divisible
(
*
Divisible(..), divided, conquered, liftD
*
, Decidable(..), chosen, lost, (>*<)
-- * Mathematical definitions
-- ** Divisible
-- $divisible
-- *** A note on 'conquer'
-- $conquer
* *
-- $decidable
) where
import Control.Applicative
import Control.Applicative.Backwards
import Control.Arrow
import Control.Monad.Trans.Except
import Control.Monad.Trans.Identity
import Control.Monad.Trans.Maybe
import qualified Control.Monad.Trans.RWS.Lazy as Lazy
import qualified Control.Monad.Trans.RWS.Strict as Strict
import Control.Monad.Trans.Reader
import qualified Control.Monad.Trans.State.Lazy as Lazy
import qualified Control.Monad.Trans.State.Strict as Strict
import qualified Control.Monad.Trans.Writer.Lazy as Lazy
import qualified Control.Monad.Trans.Writer.Strict as Strict
import Data.Functor.Compose
import Data.Functor.Constant
import Data.Functor.Contravariant
import Data.Functor.Product
import Data.Functor.Reverse
import Data.Void
import Data.Monoid (Alt(..))
import Data.Proxy
#ifdef MIN_VERSION_StateVar
import Data.StateVar
#endif
import GHC.Generics
--------------------------------------------------------------------------------
*
--------------------------------------------------------------------------------
-- |
--
-- A 'Divisible' contravariant functor is the contravariant analogue of 'Applicative'.
--
Continuing the intuition that ' ' functors consume input , a ' Divisible '
-- contravariant functor also has the ability to be composed "beside" another contravariant
-- functor.
--
provide a good example of ' Divisible ' contravariant functors . To begin
-- let's start with the type of serializers for specific types:
--
-- @
newtype a = Serializer { runSerializer : : a - > ByteString }
-- @
--
-- This is a contravariant functor:
--
-- @
instance where
f s = Serializer ( runSerializer s . f )
-- @
--
That is , given a serializer for @a@ ( @s : : a@ ) , and a way to turn
@b@s into @a@s ( a mapping @f : : b - > a@ ) , we have a serializer for @b@ :
@contramap f s : :
--
Divisible gives us a way to combine two serializers that focus on different
parts of a structure . If we postulate the existence of two primitive
serializers - @string : : Serializer String@ and @int : : , we
-- would like to be able to combine these into a serializer for pairs of
@String@s and @Int@s . How can we do this ? Simply run both serializers and
-- combine their output!
--
-- @
data StringAndInt = StringAndInt String Int
--
stringAndInt : : Serializer StringAndInt
stringAndInt = Serializer \\(StringAndInt s i ) - >
-- let sBytes = runSerializer string s
-- iBytes = runSerializer int i
-- in sBytes <> iBytes
-- @
--
-- 'divide' is a generalization by also taking a 'contramap' like function to
-- split any @a@ into a pair. This conveniently allows you to target fields of
a record , for instance , by extracting the values under two fields and
-- combining them into a tuple.
--
To complete the example , here is how to write @stringAndInt@ using a
-- @Divisible@ instance:
--
-- @
instance where
conquer = Serializer ( const mempty )
--
-- divide toBC bSerializer cSerializer = Serializer \\a ->
-- case toBC a of
-- (b, c) ->
-- let bBytes = runSerializer bSerializer b
-- cBytes = runSerializer cSerializer c
-- in bBytes <> cBytes
--
stringAndInt : : Serializer StringAndInt
-- stringAndInt =
-- divide (\\(StringAndInt s i) -> (s, i)) string int
-- @
--
class Contravariant f => Divisible f where
--- | If one can handle split `a` into `(b, c)`, as well as handle `b`s and `c`s, then one can handle `a`s
divide :: (a -> (b, c)) -> f b -> f c -> f a
-- | Conquer acts as an identity for combining @Divisible@ functors.
conquer :: f a
-- |
-- @
-- 'divided' = 'divide' 'id'
-- @
divided :: Divisible f => f a -> f b -> f (a, b)
divided = divide id
-- | Redundant, but provided for symmetry.
--
-- @
-- 'conquered' = 'conquer'
-- @
conquered :: Divisible f => f ()
conquered = conquer
-- |
This is the divisible analogue of ' liftA ' . It gives a viable default definition for ' ' in terms
-- of the members of 'Divisible'.
--
-- @
-- 'liftD' f = 'divide' ((,) () . f) 'conquer'
-- @
liftD :: Divisible f => (a -> b) -> f b -> f a
liftD f = divide ((,) () . f) conquer
instance Monoid r => Divisible (Op r) where
divide f (Op g) (Op h) = Op \a -> case f a of
(b, c) -> g b `mappend` h c
conquer = Op $ const mempty
instance Divisible Comparison where
divide f (Comparison g) (Comparison h) = Comparison \a b -> case f a of
(a',a'') -> case f b of
(b',b'') -> g a' b' `mappend` h a'' b''
conquer = Comparison \_ _ -> EQ
instance Divisible Equivalence where
divide f (Equivalence g) (Equivalence h) = Equivalence \a b -> case f a of
(a',a'') -> case f b of
(b',b'') -> g a' b' && h a'' b''
conquer = Equivalence \_ _ -> True
instance Divisible Predicate where
divide f (Predicate g) (Predicate h) = Predicate \a -> case f a of
(b, c) -> g b && h c
conquer = Predicate \_ -> True
instance Monoid m => Divisible (Const m) where
divide _ (Const a) (Const b) = Const (mappend a b)
conquer = Const mempty
instance Divisible f => Divisible (Alt f) where
divide f (Alt l) (Alt r) = Alt $ divide f l r
conquer = Alt conquer
instance Divisible U1 where
divide _ U1 U1 = U1
conquer = U1
instance Divisible f => Divisible (Rec1 f) where
divide f (Rec1 l) (Rec1 r) = Rec1 $ divide f l r
conquer = Rec1 conquer
instance Divisible f => Divisible (M1 i c f) where
divide f (M1 l) (M1 r) = M1 $ divide f l r
conquer = M1 conquer
instance (Divisible f, Divisible g) => Divisible (f :*: g) where
divide f (l1 :*: r1) (l2 :*: r2) = divide f l1 l2 :*: divide f r1 r2
conquer = conquer :*: conquer
instance (Applicative f, Divisible g) => Divisible (f :.: g) where
divide f (Comp1 l) (Comp1 r) = Comp1 (divide f <$> l <*> r)
conquer = Comp1 $ pure conquer
instance Divisible f => Divisible (Backwards f) where
divide f (Backwards l) (Backwards r) = Backwards $ divide f l r
conquer = Backwards conquer
instance Divisible m => Divisible (ExceptT e m) where
divide f (ExceptT l) (ExceptT r) = ExceptT $ divide (funzip . fmap f) l r
conquer = ExceptT conquer
instance Divisible f => Divisible (IdentityT f) where
divide f (IdentityT l) (IdentityT r) = IdentityT $ divide f l r
conquer = IdentityT conquer
instance Divisible m => Divisible (MaybeT m) where
divide f (MaybeT l) (MaybeT r) = MaybeT $ divide (funzip . fmap f) l r
conquer = MaybeT conquer
instance Divisible m => Divisible (ReaderT r m) where
divide abc (ReaderT rmb) (ReaderT rmc) = ReaderT \r -> divide abc (rmb r) (rmc r)
conquer = ReaderT \_ -> conquer
instance Divisible m => Divisible (Lazy.RWST r w s m) where
divide abc (Lazy.RWST rsmb) (Lazy.RWST rsmc) = Lazy.RWST \r s ->
divide (\ ~(a, s', w) -> case abc a of
~(b, c) -> ((b, s', w), (c, s', w)))
(rsmb r s) (rsmc r s)
conquer = Lazy.RWST \_ _ -> conquer
instance Divisible m => Divisible (Strict.RWST r w s m) where
divide abc (Strict.RWST rsmb) (Strict.RWST rsmc) = Strict.RWST \r s ->
divide (\(a, s', w) -> case abc a of
(b, c) -> ((b, s', w), (c, s', w)))
(rsmb r s) (rsmc r s)
conquer = Strict.RWST \_ _ -> conquer
instance Divisible m => Divisible (Lazy.StateT s m) where
divide f (Lazy.StateT l) (Lazy.StateT r) = Lazy.StateT \s ->
divide (lazyFanout f) (l s) (r s)
conquer = Lazy.StateT \_ -> conquer
instance Divisible m => Divisible (Strict.StateT s m) where
divide f (Strict.StateT l) (Strict.StateT r) = Strict.StateT \s ->
divide (strictFanout f) (l s) (r s)
conquer = Strict.StateT \_ -> conquer
instance Divisible m => Divisible (Lazy.WriterT w m) where
divide f (Lazy.WriterT l) (Lazy.WriterT r) = Lazy.WriterT $
divide (lazyFanout f) l r
conquer = Lazy.WriterT conquer
instance Divisible m => Divisible (Strict.WriterT w m) where
divide f (Strict.WriterT l) (Strict.WriterT r) = Strict.WriterT $
divide (strictFanout f) l r
conquer = Strict.WriterT conquer
instance (Applicative f, Divisible g) => Divisible (Compose f g) where
divide f (Compose l) (Compose r) = Compose (divide f <$> l <*> r)
conquer = Compose $ pure conquer
instance Monoid m => Divisible (Constant m) where
divide _ (Constant l) (Constant r) = Constant $ mappend l r
conquer = Constant mempty
instance (Divisible f, Divisible g) => Divisible (Product f g) where
divide f (Pair l1 r1) (Pair l2 r2) = Pair (divide f l1 l2) (divide f r1 r2)
conquer = Pair conquer conquer
instance Divisible f => Divisible (Reverse f) where
divide f (Reverse l) (Reverse r) = Reverse $ divide f l r
conquer = Reverse conquer
instance Divisible Proxy where
divide _ Proxy Proxy = Proxy
conquer = Proxy
#ifdef MIN_VERSION_StateVar
instance Divisible SettableStateVar where
divide k (SettableStateVar l) (SettableStateVar r) = SettableStateVar \ a -> case k a of
(b, c) -> l b >> r c
conquer = SettableStateVar \_ -> return ()
#endif
lazyFanout :: (a -> (b, c)) -> (a, s) -> ((b, s), (c, s))
lazyFanout f ~(a, s) = case f a of
~(b, c) -> ((b, s), (c, s))
strictFanout :: (a -> (b, c)) -> (a, s) -> ((b, s), (c, s))
strictFanout f (a, s) = case f a of
(b, c) -> ((b, s), (c, s))
funzip :: Functor f => f (a, b) -> (f a, f b)
funzip = fmap fst &&& fmap snd
--------------------------------------------------------------------------------
*
--------------------------------------------------------------------------------
| A ' ' contravariant functor is the contravariant analogue of ' Alternative ' .
--
Noting the superclass constraint that @f@ must also be ' Divisible ' , a @Decidable@
-- functor has the ability to "fan out" input, under the intuition that contravariant
-- functors consume input.
--
In the discussion for @Divisible@ , an example was demonstrated with @Serializer@s ,
that turn @a@s into @ByteString@s . @Divisible@ allowed us to serialize the /product/
-- of multiple values by concatenation. By making our @Serializer@ also @Decidable@-
-- we now have the ability to serialize the /sum/ of multiple values - for example
different constructors in an ADT .
--
Consider serializing arbitrary identifiers that can be either @String@s or @Int@s :
--
-- @
data Identifier = StringId String | IntId Int
-- @
--
We know we have serializers for @String@s and @Int@s , but how do we combine them
into a @Serializer@ for @Identifier@ ? Essentially , our @Serializer@ needs to
-- scrutinise the incoming value and choose how to serialize it:
--
-- @
-- identifier :: Serializer Identifier
-- identifier = Serializer \\identifier ->
-- case identifier of
s - > runSerializer string s
-- IntId i -> runSerializer int i
-- @
--
-- It is exactly this notion of choice that @Decidable@ encodes. Hence if we add
-- an instance of @Decidable@ for @Serializer@...
--
-- @
instance where
-- lose f = Serializer \\a -> absurd (f a)
-- choose split l r = Serializer \\a ->
-- either (runSerializer l) (runSerializer r) (split a)
-- @
--
-- Then our @identifier@ @Serializer@ is
--
-- @
-- identifier :: Serializer Identifier
-- identifier = choose toEither string int where
toEither ( StringId s ) = Left s
toEither ( IntId i ) = Right i
-- @
class Divisible f => Decidable f where
-- | Acts as identity to 'choose'.
lose :: (a -> Void) -> f a
choose :: (a -> Either b c) -> f b -> f c -> f a
-- |
-- @
-- 'lost' = 'lose' 'id'
-- @
lost :: Decidable f => f Void
lost = lose id
-- |
-- @
-- 'chosen' = 'choose' 'id'
-- @
chosen :: Decidable f => f b -> f c -> f (Either b c)
chosen = choose id
-- | Infix 'divided'
--
-- You can use this and @(`>$<`)@ in a manner analogous to `Applicative`
-- style:
--
-- @
data Point = Point { x : : ' Double ' , y : : ' Double ' , z : : Double }
--
nonNegative : : ' Predicate ' ' Double '
nonNegative = ' Predicate ' ( 0 < =)
--
-- nonNegativeOctant :: 'Predicate' Point
-- nonNegativeOctant =
adapt ' > $ < ' nonNegative ' > * < ' nonNegative ' > * < ' nonNegative
-- where
adapt Point { .. } = ( x , ( y , z ) )
-- @
(>*<) :: Divisible f => f a -> f b -> f (a, b)
(>*<) = divided
infixr 5 >*<
instance Decidable Comparison where
lose f = Comparison \a _ -> absurd (f a)
choose f (Comparison g) (Comparison h) = Comparison \a b -> case f a of
Left c -> case f b of
Left d -> g c d
Right{} -> LT
Right c -> case f b of
Left{} -> GT
Right d -> h c d
instance Decidable Equivalence where
lose f = Equivalence $ absurd . f
choose f (Equivalence g) (Equivalence h) = Equivalence \a b -> case f a of
Left c -> case f b of
Left d -> g c d
Right{} -> False
Right c -> case f b of
Left{} -> False
Right d -> h c d
instance Decidable Predicate where
lose f = Predicate $ absurd . f
choose f (Predicate g) (Predicate h) = Predicate $ either g h . f
instance Monoid r => Decidable (Op r) where
lose f = Op $ absurd . f
choose f (Op g) (Op h) = Op $ either g h . f
instance Decidable f => Decidable (Alt f) where
lose = Alt . lose
choose f (Alt l) (Alt r) = Alt $ choose f l r
instance Decidable U1 where
lose _ = U1
choose _ U1 U1 = U1
instance Decidable f => Decidable (Rec1 f) where
lose = Rec1 . lose
choose f (Rec1 l) (Rec1 r) = Rec1 $ choose f l r
instance Decidable f => Decidable (M1 i c f) where
lose = M1 . lose
choose f (M1 l) (M1 r) = M1 $ choose f l r
instance (Decidable f, Decidable g) => Decidable (f :*: g) where
lose f = lose f :*: lose f
choose f (l1 :*: r1) (l2 :*: r2) = choose f l1 l2 :*: choose f r1 r2
instance (Applicative f, Decidable g) => Decidable (f :.: g) where
lose = Comp1 . pure . lose
choose f (Comp1 l) (Comp1 r) = Comp1 (choose f <$> l <*> r)
instance Decidable f => Decidable (Backwards f) where
lose = Backwards . lose
choose f (Backwards l) (Backwards r) = Backwards $ choose f l r
instance Decidable f => Decidable (IdentityT f) where
lose = IdentityT . lose
choose f (IdentityT l) (IdentityT r) = IdentityT $ choose f l r
instance Decidable m => Decidable (ReaderT r m) where
lose f = ReaderT \_ -> lose f
choose abc (ReaderT rmb) (ReaderT rmc) = ReaderT \r -> choose abc (rmb r) (rmc r)
instance Decidable m => Decidable (Lazy.RWST r w s m) where
lose f = Lazy.RWST \_ _ -> contramap (\ ~(a, _, _) -> a) (lose f)
choose abc (Lazy.RWST rsmb) (Lazy.RWST rsmc) = Lazy.RWST \r s ->
choose (\ ~(a, s', w) -> either (Left . betuple3 s' w)
(Right . betuple3 s' w)
(abc a))
(rsmb r s) (rsmc r s)
instance Decidable m => Decidable (Strict.RWST r w s m) where
lose f = Strict.RWST \_ _ -> contramap (\(a, _, _) -> a) (lose f)
choose abc (Strict.RWST rsmb) (Strict.RWST rsmc) = Strict.RWST \r s ->
choose (\(a, s', w) -> either (Left . betuple3 s' w)
(Right . betuple3 s' w)
(abc a))
(rsmb r s) (rsmc r s)
instance Divisible m => Decidable (MaybeT m) where
lose _ = MaybeT conquer
choose f (MaybeT l) (MaybeT r) = MaybeT $
divide ( maybe (Nothing, Nothing)
(either (\b -> (Just b, Nothing))
(\c -> (Nothing, Just c)) . f)
) l r
instance Decidable m => Decidable (Lazy.StateT s m) where
lose f = Lazy.StateT \_ -> contramap lazyFst (lose f)
choose f (Lazy.StateT l) (Lazy.StateT r) = Lazy.StateT \s ->
choose (\ ~(a, s') -> either (Left . betuple s') (Right . betuple s') (f a))
(l s) (r s)
instance Decidable m => Decidable (Strict.StateT s m) where
lose f = Strict.StateT \_ -> contramap fst (lose f)
choose f (Strict.StateT l) (Strict.StateT r) = Strict.StateT \s ->
choose (\(a, s') -> either (Left . betuple s') (Right . betuple s') (f a))
(l s) (r s)
instance Decidable m => Decidable (Lazy.WriterT w m) where
lose f = Lazy.WriterT $ contramap lazyFst (lose f)
choose f (Lazy.WriterT l) (Lazy.WriterT r) = Lazy.WriterT $
choose (\ ~(a, s') -> either (Left . betuple s') (Right . betuple s') (f a)) l r
instance Decidable m => Decidable (Strict.WriterT w m) where
lose f = Strict.WriterT $ contramap fst (lose f)
choose f (Strict.WriterT l) (Strict.WriterT r) = Strict.WriterT $
choose (\(a, s') -> either (Left . betuple s') (Right . betuple s') (f a)) l r
instance (Applicative f, Decidable g) => Decidable (Compose f g) where
lose = Compose . pure . lose
choose f (Compose l) (Compose r) = Compose (choose f <$> l <*> r)
instance (Decidable f, Decidable g) => Decidable (Product f g) where
lose f = Pair (lose f) (lose f)
choose f (Pair l1 r1) (Pair l2 r2) = Pair (choose f l1 l2) (choose f r1 r2)
instance Decidable f => Decidable (Reverse f) where
lose = Reverse . lose
choose f (Reverse l) (Reverse r) = Reverse $ choose f l r
betuple :: s -> a -> (a, s)
betuple s a = (a, s)
betuple3 :: s -> w -> a -> (a, s, w)
betuple3 s w a = (a, s, w)
lazyFst :: (a, b) -> a
lazyFst ~(a, _) = a
instance Decidable Proxy where
lose _ = Proxy
choose _ Proxy Proxy = Proxy
#ifdef MIN_VERSION_StateVar
instance Decidable SettableStateVar where
lose k = SettableStateVar (absurd . k)
choose k (SettableStateVar l) (SettableStateVar r) = SettableStateVar \ a -> case k a of
Left b -> l b
Right c -> r c
#endif
-- $divisible
--
-- In denser jargon, a 'Divisible' contravariant functor is a monoid object in the category
of presheaves from Hask to Hask , equipped with Day convolution mapping the Cartesian
product of the source to the Cartesian product of the target .
--
-- By way of contrast, an 'Applicative' functor can be viewed as a monoid object in the
category of copresheaves from Hask to Hask , equipped with Day convolution mapping the
Cartesian product of the source to the Cartesian product of the target .
--
-- Given the canonical diagonal morphism:
--
-- @
-- delta a = (a,a)
-- @
--
-- @'divide' 'delta'@ should be associative with 'conquer' as a unit
--
-- @
-- 'divide' 'delta' m 'conquer' = m
-- 'divide' 'delta' 'conquer' m = m
-- 'divide' 'delta' ('divide' 'delta' m n) o = 'divide' 'delta' m ('divide' 'delta' n o)
-- @
--
-- With more general arguments you'll need to reassociate and project using the monoidal
structure of the source category . ( Here fst and snd are used in lieu of the more restricted
-- lambda and rho, but this construction works with just a monoidal category.)
--
-- @
' divide ' f m ' conquer ' = ' ' ( ' fst ' . f ) m
' divide ' f ' conquer ' m = ' ' ( ' snd ' . f ) m
-- 'divide' f ('divide' g m n) o = 'divide' f' m ('divide' 'id' n o) where
-- f' a = let (bc, d) = f a; (b, c) = g bc in (b, (c, d))
-- @
-- $conquer
-- The underlying theory would suggest that this should be:
--
-- @
-- conquer :: (a -> ()) -> f a
-- @
--
However , as we are working over a Cartesian category ( Hask ) and the Cartesian product , such an input
-- morphism is uniquely determined to be @'const' 'mempty'@, so we elide it.
-- $decidable
--
A ' Divisible ' contravariant functor is a monoid object in the category of presheaves
from Hask to Hask , equipped with Day convolution mapping the cartesian product of the
source to the Cartesian product of the target .
--
-- @
-- 'choose' 'Left' m ('lose' f) = m
-- 'choose' 'Right' ('lose' f) m = m
-- 'choose' f ('choose' g m n) o = 'choose' f' m ('choose' 'id' n o) where
f ' = ' either ' ( ' either ' ' i d ' ' Left ' . ) ( ' Right ' . ' Right ' ) . f
-- @
--
-- In addition, we expect the same kind of distributive law as is satisfied by the usual
-- covariant 'Alternative', w.r.t 'Applicative', which should be fully formulated and
-- added here at some point!
| null | https://raw.githubusercontent.com/ekmett/contravariant/a5817556ab184bc2de0f44e163b98f336bba3226/src/Data/Functor/Contravariant/Divisible.hs | haskell | # LANGUAGE Safe #
|
Stability : provisional
Portability : portable
This module supplies contravariant analogues to the 'Applicative' and 'Alternative' classes.
* Mathematical definitions
** Divisible
$divisible
*** A note on 'conquer'
$conquer
$decidable
------------------------------------------------------------------------------
------------------------------------------------------------------------------
|
A 'Divisible' contravariant functor is the contravariant analogue of 'Applicative'.
contravariant functor also has the ability to be composed "beside" another contravariant
functor.
let's start with the type of serializers for specific types:
@
@
This is a contravariant functor:
@
@
would like to be able to combine these into a serializer for pairs of
combine their output!
@
let sBytes = runSerializer string s
iBytes = runSerializer int i
in sBytes <> iBytes
@
'divide' is a generalization by also taking a 'contramap' like function to
split any @a@ into a pair. This conveniently allows you to target fields of
combining them into a tuple.
@Divisible@ instance:
@
divide toBC bSerializer cSerializer = Serializer \\a ->
case toBC a of
(b, c) ->
let bBytes = runSerializer bSerializer b
cBytes = runSerializer cSerializer c
in bBytes <> cBytes
stringAndInt =
divide (\\(StringAndInt s i) -> (s, i)) string int
@
- | If one can handle split `a` into `(b, c)`, as well as handle `b`s and `c`s, then one can handle `a`s
| Conquer acts as an identity for combining @Divisible@ functors.
|
@
'divided' = 'divide' 'id'
@
| Redundant, but provided for symmetry.
@
'conquered' = 'conquer'
@
|
of the members of 'Divisible'.
@
'liftD' f = 'divide' ((,) () . f) 'conquer'
@
------------------------------------------------------------------------------
------------------------------------------------------------------------------
functor has the ability to "fan out" input, under the intuition that contravariant
functors consume input.
of multiple values by concatenation. By making our @Serializer@ also @Decidable@-
we now have the ability to serialize the /sum/ of multiple values - for example
@
@
scrutinise the incoming value and choose how to serialize it:
@
identifier :: Serializer Identifier
identifier = Serializer \\identifier ->
case identifier of
IntId i -> runSerializer int i
@
It is exactly this notion of choice that @Decidable@ encodes. Hence if we add
an instance of @Decidable@ for @Serializer@...
@
lose f = Serializer \\a -> absurd (f a)
choose split l r = Serializer \\a ->
either (runSerializer l) (runSerializer r) (split a)
@
Then our @identifier@ @Serializer@ is
@
identifier :: Serializer Identifier
identifier = choose toEither string int where
@
| Acts as identity to 'choose'.
|
@
'lost' = 'lose' 'id'
@
|
@
'chosen' = 'choose' 'id'
@
| Infix 'divided'
You can use this and @(`>$<`)@ in a manner analogous to `Applicative`
style:
@
nonNegativeOctant :: 'Predicate' Point
nonNegativeOctant =
where
@
$divisible
In denser jargon, a 'Divisible' contravariant functor is a monoid object in the category
By way of contrast, an 'Applicative' functor can be viewed as a monoid object in the
Given the canonical diagonal morphism:
@
delta a = (a,a)
@
@'divide' 'delta'@ should be associative with 'conquer' as a unit
@
'divide' 'delta' m 'conquer' = m
'divide' 'delta' 'conquer' m = m
'divide' 'delta' ('divide' 'delta' m n) o = 'divide' 'delta' m ('divide' 'delta' n o)
@
With more general arguments you'll need to reassociate and project using the monoidal
lambda and rho, but this construction works with just a monoidal category.)
@
'divide' f ('divide' g m n) o = 'divide' f' m ('divide' 'id' n o) where
f' a = let (bc, d) = f a; (b, c) = g bc in (b, (c, d))
@
$conquer
The underlying theory would suggest that this should be:
@
conquer :: (a -> ()) -> f a
@
morphism is uniquely determined to be @'const' 'mempty'@, so we elide it.
$decidable
@
'choose' 'Left' m ('lose' f) = m
'choose' 'Right' ('lose' f) m = m
'choose' f ('choose' g m n) o = 'choose' f' m ('choose' 'id' n o) where
@
In addition, we expect the same kind of distributive law as is satisfied by the usual
covariant 'Alternative', w.r.t 'Applicative', which should be fully formulated and
added here at some point! | # LANGUAGE CPP #
# LANGUAGE TypeOperators #
# LANGUAGE BlockArguments #
Copyright : ( C ) 2014 - 2021
License : BSD-2 - Clause OR Apache-2.0
Maintainer : < >
module Data.Functor.Contravariant.Divisible
(
*
Divisible(..), divided, conquered, liftD
*
, Decidable(..), chosen, lost, (>*<)
* *
) where
import Control.Applicative
import Control.Applicative.Backwards
import Control.Arrow
import Control.Monad.Trans.Except
import Control.Monad.Trans.Identity
import Control.Monad.Trans.Maybe
import qualified Control.Monad.Trans.RWS.Lazy as Lazy
import qualified Control.Monad.Trans.RWS.Strict as Strict
import Control.Monad.Trans.Reader
import qualified Control.Monad.Trans.State.Lazy as Lazy
import qualified Control.Monad.Trans.State.Strict as Strict
import qualified Control.Monad.Trans.Writer.Lazy as Lazy
import qualified Control.Monad.Trans.Writer.Strict as Strict
import Data.Functor.Compose
import Data.Functor.Constant
import Data.Functor.Contravariant
import Data.Functor.Product
import Data.Functor.Reverse
import Data.Void
import Data.Monoid (Alt(..))
import Data.Proxy
#ifdef MIN_VERSION_StateVar
import Data.StateVar
#endif
import GHC.Generics
*
Continuing the intuition that ' ' functors consume input , a ' Divisible '
provide a good example of ' Divisible ' contravariant functors . To begin
newtype a = Serializer { runSerializer : : a - > ByteString }
instance where
f s = Serializer ( runSerializer s . f )
That is , given a serializer for @a@ ( @s : : a@ ) , and a way to turn
@b@s into @a@s ( a mapping @f : : b - > a@ ) , we have a serializer for @b@ :
@contramap f s : :
Divisible gives us a way to combine two serializers that focus on different
parts of a structure . If we postulate the existence of two primitive
serializers - @string : : Serializer String@ and @int : : , we
@String@s and @Int@s . How can we do this ? Simply run both serializers and
data StringAndInt = StringAndInt String Int
stringAndInt : : Serializer StringAndInt
stringAndInt = Serializer \\(StringAndInt s i ) - >
a record , for instance , by extracting the values under two fields and
To complete the example , here is how to write @stringAndInt@ using a
instance where
conquer = Serializer ( const mempty )
stringAndInt : : Serializer StringAndInt
class Contravariant f => Divisible f where
divide :: (a -> (b, c)) -> f b -> f c -> f a
conquer :: f a
divided :: Divisible f => f a -> f b -> f (a, b)
divided = divide id
conquered :: Divisible f => f ()
conquered = conquer
This is the divisible analogue of ' liftA ' . It gives a viable default definition for ' ' in terms
liftD :: Divisible f => (a -> b) -> f b -> f a
liftD f = divide ((,) () . f) conquer
instance Monoid r => Divisible (Op r) where
divide f (Op g) (Op h) = Op \a -> case f a of
(b, c) -> g b `mappend` h c
conquer = Op $ const mempty
instance Divisible Comparison where
divide f (Comparison g) (Comparison h) = Comparison \a b -> case f a of
(a',a'') -> case f b of
(b',b'') -> g a' b' `mappend` h a'' b''
conquer = Comparison \_ _ -> EQ
instance Divisible Equivalence where
divide f (Equivalence g) (Equivalence h) = Equivalence \a b -> case f a of
(a',a'') -> case f b of
(b',b'') -> g a' b' && h a'' b''
conquer = Equivalence \_ _ -> True
instance Divisible Predicate where
divide f (Predicate g) (Predicate h) = Predicate \a -> case f a of
(b, c) -> g b && h c
conquer = Predicate \_ -> True
instance Monoid m => Divisible (Const m) where
divide _ (Const a) (Const b) = Const (mappend a b)
conquer = Const mempty
instance Divisible f => Divisible (Alt f) where
divide f (Alt l) (Alt r) = Alt $ divide f l r
conquer = Alt conquer
instance Divisible U1 where
divide _ U1 U1 = U1
conquer = U1
instance Divisible f => Divisible (Rec1 f) where
divide f (Rec1 l) (Rec1 r) = Rec1 $ divide f l r
conquer = Rec1 conquer
instance Divisible f => Divisible (M1 i c f) where
divide f (M1 l) (M1 r) = M1 $ divide f l r
conquer = M1 conquer
instance (Divisible f, Divisible g) => Divisible (f :*: g) where
divide f (l1 :*: r1) (l2 :*: r2) = divide f l1 l2 :*: divide f r1 r2
conquer = conquer :*: conquer
instance (Applicative f, Divisible g) => Divisible (f :.: g) where
divide f (Comp1 l) (Comp1 r) = Comp1 (divide f <$> l <*> r)
conquer = Comp1 $ pure conquer
instance Divisible f => Divisible (Backwards f) where
divide f (Backwards l) (Backwards r) = Backwards $ divide f l r
conquer = Backwards conquer
instance Divisible m => Divisible (ExceptT e m) where
divide f (ExceptT l) (ExceptT r) = ExceptT $ divide (funzip . fmap f) l r
conquer = ExceptT conquer
instance Divisible f => Divisible (IdentityT f) where
divide f (IdentityT l) (IdentityT r) = IdentityT $ divide f l r
conquer = IdentityT conquer
instance Divisible m => Divisible (MaybeT m) where
divide f (MaybeT l) (MaybeT r) = MaybeT $ divide (funzip . fmap f) l r
conquer = MaybeT conquer
instance Divisible m => Divisible (ReaderT r m) where
divide abc (ReaderT rmb) (ReaderT rmc) = ReaderT \r -> divide abc (rmb r) (rmc r)
conquer = ReaderT \_ -> conquer
instance Divisible m => Divisible (Lazy.RWST r w s m) where
divide abc (Lazy.RWST rsmb) (Lazy.RWST rsmc) = Lazy.RWST \r s ->
divide (\ ~(a, s', w) -> case abc a of
~(b, c) -> ((b, s', w), (c, s', w)))
(rsmb r s) (rsmc r s)
conquer = Lazy.RWST \_ _ -> conquer
instance Divisible m => Divisible (Strict.RWST r w s m) where
divide abc (Strict.RWST rsmb) (Strict.RWST rsmc) = Strict.RWST \r s ->
divide (\(a, s', w) -> case abc a of
(b, c) -> ((b, s', w), (c, s', w)))
(rsmb r s) (rsmc r s)
conquer = Strict.RWST \_ _ -> conquer
instance Divisible m => Divisible (Lazy.StateT s m) where
divide f (Lazy.StateT l) (Lazy.StateT r) = Lazy.StateT \s ->
divide (lazyFanout f) (l s) (r s)
conquer = Lazy.StateT \_ -> conquer
instance Divisible m => Divisible (Strict.StateT s m) where
divide f (Strict.StateT l) (Strict.StateT r) = Strict.StateT \s ->
divide (strictFanout f) (l s) (r s)
conquer = Strict.StateT \_ -> conquer
instance Divisible m => Divisible (Lazy.WriterT w m) where
divide f (Lazy.WriterT l) (Lazy.WriterT r) = Lazy.WriterT $
divide (lazyFanout f) l r
conquer = Lazy.WriterT conquer
instance Divisible m => Divisible (Strict.WriterT w m) where
divide f (Strict.WriterT l) (Strict.WriterT r) = Strict.WriterT $
divide (strictFanout f) l r
conquer = Strict.WriterT conquer
instance (Applicative f, Divisible g) => Divisible (Compose f g) where
divide f (Compose l) (Compose r) = Compose (divide f <$> l <*> r)
conquer = Compose $ pure conquer
instance Monoid m => Divisible (Constant m) where
divide _ (Constant l) (Constant r) = Constant $ mappend l r
conquer = Constant mempty
instance (Divisible f, Divisible g) => Divisible (Product f g) where
divide f (Pair l1 r1) (Pair l2 r2) = Pair (divide f l1 l2) (divide f r1 r2)
conquer = Pair conquer conquer
instance Divisible f => Divisible (Reverse f) where
divide f (Reverse l) (Reverse r) = Reverse $ divide f l r
conquer = Reverse conquer
instance Divisible Proxy where
divide _ Proxy Proxy = Proxy
conquer = Proxy
#ifdef MIN_VERSION_StateVar
instance Divisible SettableStateVar where
divide k (SettableStateVar l) (SettableStateVar r) = SettableStateVar \ a -> case k a of
(b, c) -> l b >> r c
conquer = SettableStateVar \_ -> return ()
#endif
lazyFanout :: (a -> (b, c)) -> (a, s) -> ((b, s), (c, s))
lazyFanout f ~(a, s) = case f a of
~(b, c) -> ((b, s), (c, s))
strictFanout :: (a -> (b, c)) -> (a, s) -> ((b, s), (c, s))
strictFanout f (a, s) = case f a of
(b, c) -> ((b, s), (c, s))
funzip :: Functor f => f (a, b) -> (f a, f b)
funzip = fmap fst &&& fmap snd
*
| A ' ' contravariant functor is the contravariant analogue of ' Alternative ' .
Noting the superclass constraint that @f@ must also be ' Divisible ' , a @Decidable@
In the discussion for @Divisible@ , an example was demonstrated with @Serializer@s ,
that turn @a@s into @ByteString@s . @Divisible@ allowed us to serialize the /product/
different constructors in an ADT .
Consider serializing arbitrary identifiers that can be either @String@s or @Int@s :
data Identifier = StringId String | IntId Int
We know we have serializers for @String@s and @Int@s , but how do we combine them
into a @Serializer@ for @Identifier@ ? Essentially , our @Serializer@ needs to
s - > runSerializer string s
instance where
toEither ( StringId s ) = Left s
toEither ( IntId i ) = Right i
class Divisible f => Decidable f where
lose :: (a -> Void) -> f a
choose :: (a -> Either b c) -> f b -> f c -> f a
lost :: Decidable f => f Void
lost = lose id
chosen :: Decidable f => f b -> f c -> f (Either b c)
chosen = choose id
data Point = Point { x : : ' Double ' , y : : ' Double ' , z : : Double }
nonNegative : : ' Predicate ' ' Double '
nonNegative = ' Predicate ' ( 0 < =)
adapt ' > $ < ' nonNegative ' > * < ' nonNegative ' > * < ' nonNegative
adapt Point { .. } = ( x , ( y , z ) )
(>*<) :: Divisible f => f a -> f b -> f (a, b)
(>*<) = divided
infixr 5 >*<
instance Decidable Comparison where
lose f = Comparison \a _ -> absurd (f a)
choose f (Comparison g) (Comparison h) = Comparison \a b -> case f a of
Left c -> case f b of
Left d -> g c d
Right{} -> LT
Right c -> case f b of
Left{} -> GT
Right d -> h c d
instance Decidable Equivalence where
lose f = Equivalence $ absurd . f
choose f (Equivalence g) (Equivalence h) = Equivalence \a b -> case f a of
Left c -> case f b of
Left d -> g c d
Right{} -> False
Right c -> case f b of
Left{} -> False
Right d -> h c d
instance Decidable Predicate where
lose f = Predicate $ absurd . f
choose f (Predicate g) (Predicate h) = Predicate $ either g h . f
instance Monoid r => Decidable (Op r) where
lose f = Op $ absurd . f
choose f (Op g) (Op h) = Op $ either g h . f
instance Decidable f => Decidable (Alt f) where
lose = Alt . lose
choose f (Alt l) (Alt r) = Alt $ choose f l r
instance Decidable U1 where
lose _ = U1
choose _ U1 U1 = U1
instance Decidable f => Decidable (Rec1 f) where
lose = Rec1 . lose
choose f (Rec1 l) (Rec1 r) = Rec1 $ choose f l r
instance Decidable f => Decidable (M1 i c f) where
lose = M1 . lose
choose f (M1 l) (M1 r) = M1 $ choose f l r
instance (Decidable f, Decidable g) => Decidable (f :*: g) where
lose f = lose f :*: lose f
choose f (l1 :*: r1) (l2 :*: r2) = choose f l1 l2 :*: choose f r1 r2
instance (Applicative f, Decidable g) => Decidable (f :.: g) where
lose = Comp1 . pure . lose
choose f (Comp1 l) (Comp1 r) = Comp1 (choose f <$> l <*> r)
instance Decidable f => Decidable (Backwards f) where
lose = Backwards . lose
choose f (Backwards l) (Backwards r) = Backwards $ choose f l r
instance Decidable f => Decidable (IdentityT f) where
lose = IdentityT . lose
choose f (IdentityT l) (IdentityT r) = IdentityT $ choose f l r
instance Decidable m => Decidable (ReaderT r m) where
lose f = ReaderT \_ -> lose f
choose abc (ReaderT rmb) (ReaderT rmc) = ReaderT \r -> choose abc (rmb r) (rmc r)
instance Decidable m => Decidable (Lazy.RWST r w s m) where
lose f = Lazy.RWST \_ _ -> contramap (\ ~(a, _, _) -> a) (lose f)
choose abc (Lazy.RWST rsmb) (Lazy.RWST rsmc) = Lazy.RWST \r s ->
choose (\ ~(a, s', w) -> either (Left . betuple3 s' w)
(Right . betuple3 s' w)
(abc a))
(rsmb r s) (rsmc r s)
instance Decidable m => Decidable (Strict.RWST r w s m) where
lose f = Strict.RWST \_ _ -> contramap (\(a, _, _) -> a) (lose f)
choose abc (Strict.RWST rsmb) (Strict.RWST rsmc) = Strict.RWST \r s ->
choose (\(a, s', w) -> either (Left . betuple3 s' w)
(Right . betuple3 s' w)
(abc a))
(rsmb r s) (rsmc r s)
instance Divisible m => Decidable (MaybeT m) where
lose _ = MaybeT conquer
choose f (MaybeT l) (MaybeT r) = MaybeT $
divide ( maybe (Nothing, Nothing)
(either (\b -> (Just b, Nothing))
(\c -> (Nothing, Just c)) . f)
) l r
instance Decidable m => Decidable (Lazy.StateT s m) where
lose f = Lazy.StateT \_ -> contramap lazyFst (lose f)
choose f (Lazy.StateT l) (Lazy.StateT r) = Lazy.StateT \s ->
choose (\ ~(a, s') -> either (Left . betuple s') (Right . betuple s') (f a))
(l s) (r s)
instance Decidable m => Decidable (Strict.StateT s m) where
lose f = Strict.StateT \_ -> contramap fst (lose f)
choose f (Strict.StateT l) (Strict.StateT r) = Strict.StateT \s ->
choose (\(a, s') -> either (Left . betuple s') (Right . betuple s') (f a))
(l s) (r s)
instance Decidable m => Decidable (Lazy.WriterT w m) where
lose f = Lazy.WriterT $ contramap lazyFst (lose f)
choose f (Lazy.WriterT l) (Lazy.WriterT r) = Lazy.WriterT $
choose (\ ~(a, s') -> either (Left . betuple s') (Right . betuple s') (f a)) l r
instance Decidable m => Decidable (Strict.WriterT w m) where
lose f = Strict.WriterT $ contramap fst (lose f)
choose f (Strict.WriterT l) (Strict.WriterT r) = Strict.WriterT $
choose (\(a, s') -> either (Left . betuple s') (Right . betuple s') (f a)) l r
instance (Applicative f, Decidable g) => Decidable (Compose f g) where
lose = Compose . pure . lose
choose f (Compose l) (Compose r) = Compose (choose f <$> l <*> r)
instance (Decidable f, Decidable g) => Decidable (Product f g) where
lose f = Pair (lose f) (lose f)
choose f (Pair l1 r1) (Pair l2 r2) = Pair (choose f l1 l2) (choose f r1 r2)
instance Decidable f => Decidable (Reverse f) where
lose = Reverse . lose
choose f (Reverse l) (Reverse r) = Reverse $ choose f l r
betuple :: s -> a -> (a, s)
betuple s a = (a, s)
betuple3 :: s -> w -> a -> (a, s, w)
betuple3 s w a = (a, s, w)
lazyFst :: (a, b) -> a
lazyFst ~(a, _) = a
instance Decidable Proxy where
lose _ = Proxy
choose _ Proxy Proxy = Proxy
#ifdef MIN_VERSION_StateVar
instance Decidable SettableStateVar where
lose k = SettableStateVar (absurd . k)
choose k (SettableStateVar l) (SettableStateVar r) = SettableStateVar \ a -> case k a of
Left b -> l b
Right c -> r c
#endif
of presheaves from Hask to Hask , equipped with Day convolution mapping the Cartesian
product of the source to the Cartesian product of the target .
category of copresheaves from Hask to Hask , equipped with Day convolution mapping the
Cartesian product of the source to the Cartesian product of the target .
structure of the source category . ( Here fst and snd are used in lieu of the more restricted
' divide ' f m ' conquer ' = ' ' ( ' fst ' . f ) m
' divide ' f ' conquer ' m = ' ' ( ' snd ' . f ) m
However , as we are working over a Cartesian category ( Hask ) and the Cartesian product , such an input
A ' Divisible ' contravariant functor is a monoid object in the category of presheaves
from Hask to Hask , equipped with Day convolution mapping the cartesian product of the
source to the Cartesian product of the target .
f ' = ' either ' ( ' either ' ' i d ' ' Left ' . ) ( ' Right ' . ' Right ' ) . f
|
630013d11ff1ab34b9f08d83242d8ffbfb01685fcfa733c83f4db5bd3e72c3f3 | sellout/haskerwaul | NonInvolutive.hs | # language UndecidableSuperClasses #
module Haskerwaul.Meadow.NonInvolutive
( module Haskerwaul.Meadow.NonInvolutive
-- * extended modules
, module Haskerwaul.Meadow
) where
import Haskerwaul.Meadow
| [ Division by zero in non - involutive meadows]( / science / article / pii / S1570868314000652 )
class Meadow c t a => NonInvolutiveMeadow c t a
| null | https://raw.githubusercontent.com/sellout/haskerwaul/cf54bd7ce5bf4f3d1fd0d9d991dc733785b66a73/src/Haskerwaul/Meadow/NonInvolutive.hs | haskell | * extended modules | # language UndecidableSuperClasses #
module Haskerwaul.Meadow.NonInvolutive
( module Haskerwaul.Meadow.NonInvolutive
, module Haskerwaul.Meadow
) where
import Haskerwaul.Meadow
| [ Division by zero in non - involutive meadows]( / science / article / pii / S1570868314000652 )
class Meadow c t a => NonInvolutiveMeadow c t a
|
41eafc8778981f17bfb2da9d443d97ce1bb64fc68d14838590de424ee85cd57a | sealchain-project/sealchain | IntTrans.hs | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE UndecidableInstances #-}
-- | A common interpretation for the UTxO DSL and abstract chain into Cardano
module UTxO.IntTrans
(
-- * Interpretation errors
IntException(..)
-- * Interpretation context
, IntCheckpoint(..)
, mkCheckpoint
, createEpochBoundary
-- * Interpretation monad transformer
, ConIntT(..)
-- * Interpretation type classes and a rollback
, Interpretation(..)
, Interpret(..)
, IntRollback(..)
-- * Translation context
, constants
, magic
)
where
import Control.Monad.Except (MonadError, throwError)
import qualified Data.HashMap.Strict as HM
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Reflection (give)
import Formatting (bprint, build, shown, (%))
import qualified Formatting.Buildable
import Pos.Chain.Block (BlockHeader (..), GenesisBlock, HeaderHash,
MainBlock, gbBody, gbHeader, genBlockLeaders, headerHash,
mbTxs, mbWitnesses, mkGenesisBlock)
import Pos.Chain.Genesis (GenesisWStakeholders, gdBootStakeholders,
gdProtocolConsts,
genesisProtocolConstantsToProtocolConstants)
import Pos.Chain.Lrc (followTheSatoshi)
import Pos.Chain.Txp (Tx (..), TxAux (..), TxIn (..), TxOut (..),
txInputs, txOutStake, txOutputs)
import Pos.Client.Txp.Failure (TxError (..))
import Pos.Core (ProtocolConstants, SlotId (..))
import Pos.Core.Common (Coin, SharedSeed (..), SlotLeaders,
StakeholderId, StakesList, StakesMap, addCoin, subCoin)
import Pos.Core.Slotting (EpochIndex (..), crucialSlot)
import Pos.Crypto (ProtocolMagic)
import Serokell.Data.Memory.Units (Byte)
import Serokell.Util (mapJson)
import Test.Pos.Core.Dummy (dummyK)
import Universum
import UTxO.Context (CardanoContext (..), TransCtxt (..))
import UTxO.Translate (TranslateT, withConfig)
{-------------------------------------------------------------------------------
Errors that may occur during interpretation
-------------------------------------------------------------------------------}
-- | Interpretation error
data IntException =
IntExNonOrdinaryAddress
| IntExClassifyInputs Text
| IntExMkDlg Text
| IntExCreateBlock Text
| IntExMkSlot Text
| IntExTx TxError -- ^ Occurs during fee calculation
| IntUnknownHash Text
| IntIndexOutOfRange Text Word32 -- ^ During input resolution (hash and index)
-- | Unknown stake holder during stake calculation
| IntUnknownStakeholder StakeholderId
-- | Coin overflow during stake calculation
--
-- We record the old stake and the stake we were suppose to add
| IntStakeOverflow StakeholderId Coin Coin
| Coin underflow during stake
--
-- We record the old stake and the stake we were supposed to subtract
| IntStakeUnderflow StakeholderId Coin Coin
-- | Attempt to rollback without previous checkpoints
| IntCannotRollback
-- | The size of the attributes in the transaction exceeded our bounds
--
In order to estimate transaction size we use two values
-- `boundAddrAttrSize` and `boundTxAttrSize`. If the attributes in an actual
-- transaction exceeds these values, we will end up underestimating the fees
-- we need to pay. This isn't really a problem for the interpreter, but it's
-- a problem elsewhere and when this happens various tests will fail. So we
-- check this right at the point where we generate a transaction, and fail
-- early if the bounds are exceeded.
--
-- We record the size of the attributes on the transaction as well as the
-- size of the attributes of all addresses in the outputs.
| IntTxAttrBoundsExceeded Byte
-- | The size of the attributes of an address exceeded our bounds
--
-- See 'IntTxAttrBoundsExceeded' for details.
| IntAddrAttrBoundsExceeded Byte
deriving (Show)
instance Exception IntException
instance Buildable IntException where
build = bprint shown
{-------------------------------------------------------------------------------
Interpretation context
-------------------------------------------------------------------------------}
-- | Checkpoint (we create one for each block we translate)
data IntCheckpoint = IntCheckpoint {
-- | Slot number of this checkpoint
icSlotId :: !SlotId
-- | Header of the block in this slot
--
-- Will be initialized to the header of the genesis block.
, icBlockHeader :: !BlockHeader
-- | The header of the /main/ block in this slot
--
-- This may be different at epoch boundaries, when 'icBlockHeader' will
-- be set to the header of the EBB.
--
Set to ' Nothing ' for the first checkpoint .
, icMainBlockHdr :: !(Maybe HeaderHash)
-- | The header hash of the previous /main/ block.
, icPrevMainHH :: !(Maybe HeaderHash)
-- | Slot leaders for the current epoch
, icEpochLeaders :: !SlotLeaders
-- | Running stakes
, icStakes :: !StakesMap
-- | Snapshot of the stakes at the 'crucial' slot in the current epoch; in
other words , the stakes used to compute the slot leaders for the next epoch .
, icCrucialStakes :: !StakesMap
}
{-------------------------------------------------------------------------------
The interpretation monad
-------------------------------------------------------------------------------}
-- | Interpretation monad with a parameterised context
newtype ConIntT (ctxt :: (* -> *) -> *) h e m a = IntT {
unIntT :: StateT (ctxt h) (TranslateT (Either IntException e) m) a
}
deriving ( Functor
, Applicative
, Monad
, MonadReader TransCtxt
, MonadError (Either IntException e)
)
-- | Evaluate state strictly
instance (ctxth ~ ctxt h, Monad m) => MonadState ctxth (ConIntT ctxt h e m) where
get = IntT $ get
put !s = IntT $ put s
{-------------------------------------------------------------------------------
Extract some values we need from the translation context
-------------------------------------------------------------------------------}
constants :: TransCtxt -> ProtocolConstants
constants = genesisProtocolConstantsToProtocolConstants
. gdProtocolConsts
. ccData
. tcCardano
weights :: TransCtxt -> GenesisWStakeholders
weights = gdBootStakeholders . ccData . tcCardano
magic :: TransCtxt -> ProtocolMagic
magic = ccMagic . tcCardano
{-------------------------------------------------------------------------------
Constructing checkpoints
-------------------------------------------------------------------------------}
mkCheckpoint :: Monad m
=> IntCheckpoint -- ^ Previous checkpoint
-> SlotId -- ^ Slot of the new block just created
-> MainBlock -- ^ The block just created
-> [NonEmpty TxOut] -- ^ Resolved inputs
-> TranslateT IntException m IntCheckpoint
mkCheckpoint prev slot block inputs = do
gs <- asks weights
let isCrucial = slot == crucialSlot dummyK (siEpoch slot)
newStakes <- updateStakes gs block inputs (icStakes prev)
return IntCheckpoint {
icSlotId = slot
, icBlockHeader = BlockHeaderMain $ block ^. gbHeader
, icMainBlockHdr = Just $ headerHash block
, icPrevMainHH = Just $ headerHash (icBlockHeader prev)
, icEpochLeaders = icEpochLeaders prev
, icStakes = newStakes
, icCrucialStakes = if isCrucial
then newStakes
else icCrucialStakes prev
}
-- | Update the stakes map as a result of a block.
--
-- We follow the 'Stakes modification' section of the txp.md document.
updateStakes :: forall m. MonadError IntException m
=> GenesisWStakeholders
-> MainBlock
-> [NonEmpty TxOut] -- ^ Resolved inputs
-> StakesMap -> m StakesMap
updateStakes gs b resolvedInputs =
foldr ((>=>) . go) return (zip (b ^. gbBody . mbTxs) resolvedInputs)
where
go :: (Tx, NonEmpty TxOut) -> StakesMap -> m StakesMap
go (tx, ris) =
subStake >=> addStake
where
subStakes, addStakes :: [(StakeholderId, Coin)]
subStakes = concatMap txOutStake' $ toList ris
addStakes = concatMap txOutStake' $ tx ^. txOutputs
subStake, addStake :: StakesMap -> m StakesMap
subStake sm = foldM (flip subStake1) sm subStakes
addStake sm = foldM (flip addStake1) sm addStakes
subStake1, addStake1 :: (StakeholderId, Coin) -> StakesMap -> m StakesMap
subStake1 (id, c) sm = do
stake <- stakeOf id sm
case stake `subCoin` c of
Just stake' -> return $! HM.insert id stake' sm
Nothing -> throwError $ IntStakeUnderflow id stake c
addStake1 (id, c) sm = do
stake <- stakeOf id sm
case stake `addCoin` c of
Just stake' -> return $! HM.insert id stake' sm
Nothing -> throwError $ IntStakeOverflow id stake c
stakeOf :: StakeholderId -> StakesMap -> m Coin
stakeOf hId sm =
case HM.lookup hId sm of
Just s -> return s
Nothing -> throwError $ IntUnknownStakeholder hId
txOutStake' :: TxOut -> StakesList
txOutStake' = txOutStake gs
-- | Create an epoch boundary block
--
In between each epoch there is an epoch boundary block ( or EBB ) , that records
the stakes for the next epoch ( in the Cardano codebase is referred to as a
-- "genesis block", and indeed the types are the same; we follow the terminology
-- from the spec here).
--
-- We /update/ the most recent checkpoint so that when we rollback, we effectively
-- rollback /two/ blocks. This is important, because the abstract chain has no
-- concept of EBBs.
createEpochBoundary :: Monad m
=> IntCheckpoint
-> TranslateT IntException m (IntCheckpoint, GenesisBlock)
createEpochBoundary ic = do
pm <- asks magic
pc <- asks constants
slots <- asks (ccEpochSlots . tcCardano)
let newLeaders = give pc $ followTheSatoshi
slots
boringSharedSeed
(HM.toList $ icCrucialStakes ic)
ebb = mkGenesisBlock
pm
(Right $ icBlockHeader ic)
(nextEpoch $ icSlotId ic)
newLeaders
return (
ic { icEpochLeaders = ebb ^. genBlockLeaders
, icBlockHeader = BlockHeaderGenesis $ ebb ^. gbHeader
}
, ebb
)
where
-- This is a shared seed which never changes. Obviously it is not an
-- accurate reflection of how Cardano works.
boringSharedSeed :: SharedSeed
boringSharedSeed = SharedSeed "Static shared seed"
nextEpoch :: SlotId -> EpochIndex
nextEpoch (SlotId (EpochIndex i) _) = EpochIndex $ i + 1
-- | Gives a type for an interpretation context.
--
-- 'i' is a parameter binding interpretations for a given pair of a source
-- and a target language.
class Interpretation i where
-- | Denotes an interpretation context, typically a monad transformer
--
- The first kind ( * - > * ) usually represents hash functions .
- The second kind usually represents error types .
- The third kind usually represents monad instances .
- The fourth kind usually represents source types ( the source of the
-- translation).
type IntCtx i :: (* -> *) -> * -> (* -> *) -> * -> *
-- | Interpretation of a source language to a target language, e.g. from
-- the UTxO DSL into Cardano.
--
-- 'fromTo' is a parameter binding interpretations for a given pair of a source
-- and a target language.
-- 'h' is a hash type.
-- 'a' is the source language's type being interpreted.
-- 'Interpreted fromTo a' is the target language's type being interpreted to.
class Interpretation fromTo => Interpret fromTo h a where
type Interpreted fromTo a :: *
-- | The single method of the type class that performs the interpretation
int :: Monad m => a -> IntCtx fromTo h e m (Interpreted fromTo a)
-- | For convenience, we provide an event that corresponds to rollback
--
-- This makes interpreting DSL blocks and these "pseudo-DSL" rollbacks uniform.
data IntRollback = IntRollback
instance Buildable IntCheckpoint where
build IntCheckpoint{..} = bprint
( "Checkpoint {"
% " slotId: " % build
% ", stakes: " % mapJson
)
icSlotId
icStakes
| null | https://raw.githubusercontent.com/sealchain-project/sealchain/e97b4bac865fb147979cb14723a12c716a62e51e/utxo/src/UTxO/IntTrans.hs | haskell | # LANGUAGE UndecidableInstances #
| A common interpretation for the UTxO DSL and abstract chain into Cardano
* Interpretation errors
* Interpretation context
* Interpretation monad transformer
* Interpretation type classes and a rollback
* Translation context
------------------------------------------------------------------------------
Errors that may occur during interpretation
------------------------------------------------------------------------------
| Interpretation error
^ Occurs during fee calculation
^ During input resolution (hash and index)
| Unknown stake holder during stake calculation
| Coin overflow during stake calculation
We record the old stake and the stake we were suppose to add
We record the old stake and the stake we were supposed to subtract
| Attempt to rollback without previous checkpoints
| The size of the attributes in the transaction exceeded our bounds
`boundAddrAttrSize` and `boundTxAttrSize`. If the attributes in an actual
transaction exceeds these values, we will end up underestimating the fees
we need to pay. This isn't really a problem for the interpreter, but it's
a problem elsewhere and when this happens various tests will fail. So we
check this right at the point where we generate a transaction, and fail
early if the bounds are exceeded.
We record the size of the attributes on the transaction as well as the
size of the attributes of all addresses in the outputs.
| The size of the attributes of an address exceeded our bounds
See 'IntTxAttrBoundsExceeded' for details.
------------------------------------------------------------------------------
Interpretation context
------------------------------------------------------------------------------
| Checkpoint (we create one for each block we translate)
| Slot number of this checkpoint
| Header of the block in this slot
Will be initialized to the header of the genesis block.
| The header of the /main/ block in this slot
This may be different at epoch boundaries, when 'icBlockHeader' will
be set to the header of the EBB.
| The header hash of the previous /main/ block.
| Slot leaders for the current epoch
| Running stakes
| Snapshot of the stakes at the 'crucial' slot in the current epoch; in
------------------------------------------------------------------------------
The interpretation monad
------------------------------------------------------------------------------
| Interpretation monad with a parameterised context
| Evaluate state strictly
------------------------------------------------------------------------------
Extract some values we need from the translation context
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Constructing checkpoints
------------------------------------------------------------------------------
^ Previous checkpoint
^ Slot of the new block just created
^ The block just created
^ Resolved inputs
| Update the stakes map as a result of a block.
We follow the 'Stakes modification' section of the txp.md document.
^ Resolved inputs
| Create an epoch boundary block
"genesis block", and indeed the types are the same; we follow the terminology
from the spec here).
We /update/ the most recent checkpoint so that when we rollback, we effectively
rollback /two/ blocks. This is important, because the abstract chain has no
concept of EBBs.
This is a shared seed which never changes. Obviously it is not an
accurate reflection of how Cardano works.
| Gives a type for an interpretation context.
'i' is a parameter binding interpretations for a given pair of a source
and a target language.
| Denotes an interpretation context, typically a monad transformer
translation).
| Interpretation of a source language to a target language, e.g. from
the UTxO DSL into Cardano.
'fromTo' is a parameter binding interpretations for a given pair of a source
and a target language.
'h' is a hash type.
'a' is the source language's type being interpreted.
'Interpreted fromTo a' is the target language's type being interpreted to.
| The single method of the type class that performs the interpretation
| For convenience, we provide an event that corresponds to rollback
This makes interpreting DSL blocks and these "pseudo-DSL" rollbacks uniform. | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
module UTxO.IntTrans
(
IntException(..)
, IntCheckpoint(..)
, mkCheckpoint
, createEpochBoundary
, ConIntT(..)
, Interpretation(..)
, Interpret(..)
, IntRollback(..)
, constants
, magic
)
where
import Control.Monad.Except (MonadError, throwError)
import qualified Data.HashMap.Strict as HM
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Reflection (give)
import Formatting (bprint, build, shown, (%))
import qualified Formatting.Buildable
import Pos.Chain.Block (BlockHeader (..), GenesisBlock, HeaderHash,
MainBlock, gbBody, gbHeader, genBlockLeaders, headerHash,
mbTxs, mbWitnesses, mkGenesisBlock)
import Pos.Chain.Genesis (GenesisWStakeholders, gdBootStakeholders,
gdProtocolConsts,
genesisProtocolConstantsToProtocolConstants)
import Pos.Chain.Lrc (followTheSatoshi)
import Pos.Chain.Txp (Tx (..), TxAux (..), TxIn (..), TxOut (..),
txInputs, txOutStake, txOutputs)
import Pos.Client.Txp.Failure (TxError (..))
import Pos.Core (ProtocolConstants, SlotId (..))
import Pos.Core.Common (Coin, SharedSeed (..), SlotLeaders,
StakeholderId, StakesList, StakesMap, addCoin, subCoin)
import Pos.Core.Slotting (EpochIndex (..), crucialSlot)
import Pos.Crypto (ProtocolMagic)
import Serokell.Data.Memory.Units (Byte)
import Serokell.Util (mapJson)
import Test.Pos.Core.Dummy (dummyK)
import Universum
import UTxO.Context (CardanoContext (..), TransCtxt (..))
import UTxO.Translate (TranslateT, withConfig)
data IntException =
IntExNonOrdinaryAddress
| IntExClassifyInputs Text
| IntExMkDlg Text
| IntExCreateBlock Text
| IntExMkSlot Text
| IntUnknownHash Text
| IntUnknownStakeholder StakeholderId
| IntStakeOverflow StakeholderId Coin Coin
| Coin underflow during stake
| IntStakeUnderflow StakeholderId Coin Coin
| IntCannotRollback
In order to estimate transaction size we use two values
| IntTxAttrBoundsExceeded Byte
| IntAddrAttrBoundsExceeded Byte
deriving (Show)
instance Exception IntException
instance Buildable IntException where
build = bprint shown
data IntCheckpoint = IntCheckpoint {
icSlotId :: !SlotId
, icBlockHeader :: !BlockHeader
Set to ' Nothing ' for the first checkpoint .
, icMainBlockHdr :: !(Maybe HeaderHash)
, icPrevMainHH :: !(Maybe HeaderHash)
, icEpochLeaders :: !SlotLeaders
, icStakes :: !StakesMap
other words , the stakes used to compute the slot leaders for the next epoch .
, icCrucialStakes :: !StakesMap
}
newtype ConIntT (ctxt :: (* -> *) -> *) h e m a = IntT {
unIntT :: StateT (ctxt h) (TranslateT (Either IntException e) m) a
}
deriving ( Functor
, Applicative
, Monad
, MonadReader TransCtxt
, MonadError (Either IntException e)
)
instance (ctxth ~ ctxt h, Monad m) => MonadState ctxth (ConIntT ctxt h e m) where
get = IntT $ get
put !s = IntT $ put s
constants :: TransCtxt -> ProtocolConstants
constants = genesisProtocolConstantsToProtocolConstants
. gdProtocolConsts
. ccData
. tcCardano
weights :: TransCtxt -> GenesisWStakeholders
weights = gdBootStakeholders . ccData . tcCardano
magic :: TransCtxt -> ProtocolMagic
magic = ccMagic . tcCardano
mkCheckpoint :: Monad m
-> TranslateT IntException m IntCheckpoint
mkCheckpoint prev slot block inputs = do
gs <- asks weights
let isCrucial = slot == crucialSlot dummyK (siEpoch slot)
newStakes <- updateStakes gs block inputs (icStakes prev)
return IntCheckpoint {
icSlotId = slot
, icBlockHeader = BlockHeaderMain $ block ^. gbHeader
, icMainBlockHdr = Just $ headerHash block
, icPrevMainHH = Just $ headerHash (icBlockHeader prev)
, icEpochLeaders = icEpochLeaders prev
, icStakes = newStakes
, icCrucialStakes = if isCrucial
then newStakes
else icCrucialStakes prev
}
updateStakes :: forall m. MonadError IntException m
=> GenesisWStakeholders
-> MainBlock
-> StakesMap -> m StakesMap
updateStakes gs b resolvedInputs =
foldr ((>=>) . go) return (zip (b ^. gbBody . mbTxs) resolvedInputs)
where
go :: (Tx, NonEmpty TxOut) -> StakesMap -> m StakesMap
go (tx, ris) =
subStake >=> addStake
where
subStakes, addStakes :: [(StakeholderId, Coin)]
subStakes = concatMap txOutStake' $ toList ris
addStakes = concatMap txOutStake' $ tx ^. txOutputs
subStake, addStake :: StakesMap -> m StakesMap
subStake sm = foldM (flip subStake1) sm subStakes
addStake sm = foldM (flip addStake1) sm addStakes
subStake1, addStake1 :: (StakeholderId, Coin) -> StakesMap -> m StakesMap
subStake1 (id, c) sm = do
stake <- stakeOf id sm
case stake `subCoin` c of
Just stake' -> return $! HM.insert id stake' sm
Nothing -> throwError $ IntStakeUnderflow id stake c
addStake1 (id, c) sm = do
stake <- stakeOf id sm
case stake `addCoin` c of
Just stake' -> return $! HM.insert id stake' sm
Nothing -> throwError $ IntStakeOverflow id stake c
stakeOf :: StakeholderId -> StakesMap -> m Coin
stakeOf hId sm =
case HM.lookup hId sm of
Just s -> return s
Nothing -> throwError $ IntUnknownStakeholder hId
txOutStake' :: TxOut -> StakesList
txOutStake' = txOutStake gs
In between each epoch there is an epoch boundary block ( or EBB ) , that records
the stakes for the next epoch ( in the Cardano codebase is referred to as a
createEpochBoundary :: Monad m
=> IntCheckpoint
-> TranslateT IntException m (IntCheckpoint, GenesisBlock)
createEpochBoundary ic = do
pm <- asks magic
pc <- asks constants
slots <- asks (ccEpochSlots . tcCardano)
let newLeaders = give pc $ followTheSatoshi
slots
boringSharedSeed
(HM.toList $ icCrucialStakes ic)
ebb = mkGenesisBlock
pm
(Right $ icBlockHeader ic)
(nextEpoch $ icSlotId ic)
newLeaders
return (
ic { icEpochLeaders = ebb ^. genBlockLeaders
, icBlockHeader = BlockHeaderGenesis $ ebb ^. gbHeader
}
, ebb
)
where
boringSharedSeed :: SharedSeed
boringSharedSeed = SharedSeed "Static shared seed"
nextEpoch :: SlotId -> EpochIndex
nextEpoch (SlotId (EpochIndex i) _) = EpochIndex $ i + 1
class Interpretation i where
- The first kind ( * - > * ) usually represents hash functions .
- The second kind usually represents error types .
- The third kind usually represents monad instances .
- The fourth kind usually represents source types ( the source of the
type IntCtx i :: (* -> *) -> * -> (* -> *) -> * -> *
class Interpretation fromTo => Interpret fromTo h a where
type Interpreted fromTo a :: *
int :: Monad m => a -> IntCtx fromTo h e m (Interpreted fromTo a)
data IntRollback = IntRollback
instance Buildable IntCheckpoint where
build IntCheckpoint{..} = bprint
( "Checkpoint {"
% " slotId: " % build
% ", stakes: " % mapJson
)
icSlotId
icStakes
|
f7ab69469ce43c95a06ec15ae5240276d2b27d108dc4ba6420952a611088f9bc | fpco/schoolofhaskell.com | GroupDesc.hs | module Import.GroupDesc
( externalDesc
, internalDesc
) where
import ClassyPrelude.Yesod
import Data.Text (breakOn)
externalDesc :: Text -> Text
externalDesc x = maybe x fst $ splitter x
internalDesc :: Text -> Text
internalDesc x = maybe x snd $ splitter x
splitter :: Text -> Maybe (Text, Text)
splitter x = do
let (y, z) = breakOn breaker $ filter (/= '\r') x
z' <- stripPrefix breaker z
return (y, z')
where
breaker = "\n---\n"
| null | https://raw.githubusercontent.com/fpco/schoolofhaskell.com/15ec1a03cb9d593ee9c0d167dc522afe45ba4f8e/src/Import/GroupDesc.hs | haskell | module Import.GroupDesc
( externalDesc
, internalDesc
) where
import ClassyPrelude.Yesod
import Data.Text (breakOn)
externalDesc :: Text -> Text
externalDesc x = maybe x fst $ splitter x
internalDesc :: Text -> Text
internalDesc x = maybe x snd $ splitter x
splitter :: Text -> Maybe (Text, Text)
splitter x = do
let (y, z) = breakOn breaker $ filter (/= '\r') x
z' <- stripPrefix breaker z
return (y, z')
where
breaker = "\n---\n"
|
|
09e3b49d3391a96f741a09d7726c71f6b2629cceeaaee3a1b64842e0d78f44c5 | xh4/web-toolkit | serpent.lisp | ;;;; -*- mode: lisp; indent-tabs-mode: nil -*-
;;;; serpent.lisp -- implementation of the Serpent block cipher
(in-package :crypto)
S - Boxes
(defmacro serpent-sbox0 (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r3 (logxor ,r3 ,r0)
,t0 ,r1
,r1 (logand ,r1 ,r3)
,t0 (logxor ,t0 ,r2)
,r1 (logxor ,r1 ,r0)
,r0 (logior ,r0 ,r3)
,r0 (logxor ,r0 ,t0)
,t0 (logxor ,t0 ,r3)
,r3 (logxor ,r3 ,r2)
,r2 (logior ,r2 ,r1)
,r2 (logxor ,r2 ,t0)
,t0 (mod32lognot ,t0)
,t0 (logior ,t0 ,r1)
,r1 (logxor ,r1 ,r3)
,r1 (logxor ,r1 ,t0)
,r3 (logior ,r3 ,r0)
,r1 (logxor ,r1 ,r3)
,t0 (logxor ,t0 ,r3)
,o0 ,r1
,o1 ,t0
,o2 ,r2
,o3 ,r0))
(defmacro serpent-sbox0-inverse (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r2 (mod32lognot ,r2)
,t0 ,r1
,r1 (logior ,r1 ,r0)
,t0 (mod32lognot ,t0)
,r1 (logxor ,r1 ,r2)
,r2 (logior ,r2 ,t0)
,r1 (logxor ,r1 ,r3)
,r0 (logxor ,r0 ,t0)
,r2 (logxor ,r2 ,r0)
,r0 (logand ,r0 ,r3)
,t0 (logxor ,t0 ,r0)
,r0 (logior ,r0 ,r1)
,r0 (logxor ,r0 ,r2)
,r3 (logxor ,r3 ,t0)
,r2 (logxor ,r2 ,r1)
,r3 (logxor ,r3 ,r0)
,r3 (logxor ,r3 ,r1)
,r2 (logand ,r2 ,r3)
,t0 (logxor ,t0 ,r2)
,o0 ,r0
,o1 ,t0
,o2 ,r1
,o3 ,r3))
(defmacro serpent-sbox1 (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r0 (mod32lognot ,r0)
,r2 (mod32lognot ,r2)
,t0 ,r0
,r0 (logand ,r0 ,r1)
,r2 (logxor ,r0 ,r2)
,r0 (logior ,r0 ,r3)
,r3 (logxor ,r3 ,r2)
,r1 (logxor ,r1 ,r0)
,r0 (logxor ,r0 ,t0)
,t0 (logior ,t0 ,r1)
,r1 (logxor ,r1 ,r3)
,r2 (logior ,r2 ,r0)
,r2 (logand ,r2 ,t0)
,r0 (logxor ,r0 ,r1)
,r1 (logand ,r1 ,r2)
,r1 (logxor ,r1 ,r0)
,r0 (logand ,r0 ,r2)
,r0 (logxor ,r0 ,t0)
,o0 ,r2
,o1 ,r0
,o2 ,r3
,o3 ,r1))
(defmacro serpent-sbox1-inverse (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,t0 ,r1
,r1 (logxor ,r1 ,r3)
,r3 (logand ,r3 ,r1)
,t0 (logxor ,t0 ,r2)
,r3 (logxor ,r3 ,r0)
,r0 (logior ,r0 ,r1)
,r2 (logxor ,r2 ,r3)
,r0 (logxor ,r0 ,t0)
,r0 (logior ,r0 ,r2)
,r1 (logxor ,r1 ,r3)
,r0 (logxor ,r0 ,r1)
,r1 (logior ,r1 ,r3)
,r1 (logxor ,r1 ,r0)
,t0 (mod32lognot ,t0)
,t0 (logxor ,t0 ,r1)
,r1 (logior ,r1 ,r0)
,r1 (logxor ,r1 ,r0)
,r1 (logior ,r1 ,t0)
,r3 (logxor ,r3 ,r1)
,o0 ,t0
,o1 ,r0
,o2 ,r3
,o3 ,r2))
(defmacro serpent-sbox2 (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,t0 ,r0
,r0 (logand ,r0 ,r2)
,r0 (logxor ,r0 ,r3)
,r2 (logxor ,r2 ,r1)
,r2 (logxor ,r2 ,r0)
,r3 (logior ,r3 ,t0)
,r3 (logxor ,r3 ,r1)
,t0 (logxor ,t0 ,r2)
,r1 ,r3
,r3 (logior ,r3 ,t0)
,r3 (logxor ,r3 ,r0)
,r0 (logand ,r0 ,r1)
,t0 (logxor ,t0 ,r0)
,r1 (logxor ,r1 ,r3)
,r1 (logxor ,r1 ,t0)
,t0 (mod32lognot ,t0)
,o0 ,r2
,o1 ,r3
,o2 ,r1
,o3 ,t0))
(defmacro serpent-sbox2-inverse (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r2 (logxor ,r2 ,r3)
,r3 (logxor ,r3 ,r0)
,t0 ,r3
,r3 (logand ,r3 ,r2)
,r3 (logxor ,r3 ,r1)
,r1 (logior ,r1 ,r2)
,r1 (logxor ,r1 ,t0)
,t0 (logand ,t0 ,r3)
,r2 (logxor ,r2 ,r3)
,t0 (logand ,t0 ,r0)
,t0 (logxor ,t0 ,r2)
,r2 (logand ,r2 ,r1)
,r2 (logior ,r2 ,r0)
,r3 (mod32lognot ,r3)
,r2 (logxor ,r2 ,r3)
,r0 (logxor ,r0 ,r3)
,r0 (logand ,r0 ,r1)
,r3 (logxor ,r3 ,t0)
,r3 (logxor ,r3 ,r0)
,o0 ,r1
,o1 ,t0
,o2 ,r2
,o3 ,r3))
(defmacro serpent-sbox3 (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,t0 ,r0
,r0 (logior ,r0 ,r3)
,r3 (logxor ,r3 ,r1)
,r1 (logand ,r1 ,t0)
,t0 (logxor ,t0 ,r2)
,r2 (logxor ,r2 ,r3)
,r3 (logand ,r3 ,r0)
,t0 (logior ,t0 ,r1)
,r3 (logxor ,r3 ,t0)
,r0 (logxor ,r0 ,r1)
,t0 (logand ,t0 ,r0)
,r1 (logxor ,r1 ,r3)
,t0 (logxor ,t0 ,r2)
,r1 (logior ,r1 ,r0)
,r1 (logxor ,r1 ,r2)
,r0 (logxor ,r0 ,r3)
,r2 ,r1
,r1 (logior ,r1 ,r3)
,r1 (logxor ,r1 ,r0)
,o0 ,r1
,o1 ,r2
,o2 ,r3
,o3 ,t0))
(defmacro serpent-sbox3-inverse (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,t0 ,r2
,r2 (logxor ,r2 ,r1)
,r0 (logxor ,r0 ,r2)
,t0 (logand ,t0 ,r2)
,t0 (logxor ,t0 ,r0)
,r0 (logand ,r0 ,r1)
,r1 (logxor ,r1 ,r3)
,r3 (logior ,r3 ,t0)
,r2 (logxor ,r2 ,r3)
,r0 (logxor ,r0 ,r3)
,r1 (logxor ,r1 ,t0)
,r3 (logand ,r3 ,r2)
,r3 (logxor ,r3 ,r1)
,r1 (logxor ,r1 ,r0)
,r1 (logior ,r1 ,r2)
,r0 (logxor ,r0 ,r3)
,r1 (logxor ,r1 ,t0)
,r0 (logxor ,r0 ,r1)
,o0 ,r2
,o1 ,r1
,o2 ,r3
,o3 ,r0))
(defmacro serpent-sbox4 (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r1 (logxor ,r1 ,r3)
,r3 (mod32lognot ,r3)
,r2 (logxor ,r2 ,r3)
,r3 (logxor ,r3 ,r0)
,t0 ,r1
,r1 (logand ,r1 ,r3)
,r1 (logxor ,r1 ,r2)
,t0 (logxor ,t0 ,r3)
,r0 (logxor ,r0 ,t0)
,r2 (logand ,r2 ,t0)
,r2 (logxor ,r2 ,r0)
,r0 (logand ,r0 ,r1)
,r3 (logxor ,r3 ,r0)
,t0 (logior ,t0 ,r1)
,t0 (logxor ,t0 ,r0)
,r0 (logior ,r0 ,r3)
,r0 (logxor ,r0 ,r2)
,r2 (logand ,r2 ,r3)
,r0 (mod32lognot ,r0)
,t0 (logxor ,t0 ,r2)
,o0 ,r1
,o1 ,t0
,o2 ,r0
,o3 ,r3))
(defmacro serpent-sbox4-inverse (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,t0 ,r2
,r2 (logand ,r2 ,r3)
,r2 (logxor ,r2 ,r1)
,r1 (logior ,r1 ,r3)
,r1 (logand ,r1 ,r0)
,t0 (logxor ,t0 ,r2)
,t0 (logxor ,t0 ,r1)
,r1 (logand ,r1 ,r2)
,r0 (mod32lognot ,r0)
,r3 (logxor ,r3 ,t0)
,r1 (logxor ,r1 ,r3)
,r3 (logand ,r3 ,r0)
,r3 (logxor ,r3 ,r2)
,r0 (logxor ,r0 ,r1)
,r2 (logand ,r2 ,r0)
,r3 (logxor ,r3 ,r0)
,r2 (logxor ,r2 ,t0)
,r2 (logior ,r2 ,r3)
,r3 (logxor ,r3 ,r0)
,r2 (logxor ,r2 ,r1)
,o0 ,r0
,o1 ,r3
,o2 ,r2
,o3 ,t0))
(defmacro serpent-sbox5 (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r0 (logxor ,r0 ,r1)
,r1 (logxor ,r1 ,r3)
,r3 (mod32lognot ,r3)
,t0 ,r1
,r1 (logand ,r1 ,r0)
,r2 (logxor ,r2 ,r3)
,r1 (logxor ,r1 ,r2)
,r2 (logior ,r2 ,t0)
,t0 (logxor ,t0 ,r3)
,r3 (logand ,r3 ,r1)
,r3 (logxor ,r3 ,r0)
,t0 (logxor ,t0 ,r1)
,t0 (logxor ,t0 ,r2)
,r2 (logxor ,r2 ,r0)
,r0 (logand ,r0 ,r3)
,r2 (mod32lognot ,r2)
,r0 (logxor ,r0 ,t0)
,t0 (logior ,t0 ,r3)
,r2 (logxor ,r2 ,t0)
,o0 ,r1
,o1 ,r3
,o2 ,r0
,o3 ,r2))
(defmacro serpent-sbox5-inverse (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r1 (mod32lognot ,r1)
,t0 ,r3
,r2 (logxor ,r2 ,r1)
,r3 (logior ,r3 ,r0)
,r3 (logxor ,r3 ,r2)
,r2 (logior ,r2 ,r1)
,r2 (logand ,r2 ,r0)
,t0 (logxor ,t0 ,r3)
,r2 (logxor ,r2 ,t0)
,t0 (logior ,t0 ,r0)
,t0 (logxor ,t0 ,r1)
,r1 (logand ,r1 ,r2)
,r1 (logxor ,r1 ,r3)
,t0 (logxor ,t0 ,r2)
,r3 (logand ,r3 ,t0)
,t0 (logxor ,t0 ,r1)
,r3 (logxor ,r3 ,t0)
,t0 (mod32lognot ,t0)
,r3 (logxor ,r3 ,r0)
,o0 ,r1
,o1 ,t0
,o2 ,r3
,o3 ,r2))
(defmacro serpent-sbox6 (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r2 (mod32lognot ,r2)
,t0 ,r3
,r3 (logand ,r3 ,r0)
,r0 (logxor ,r0 ,t0)
,r3 (logxor ,r3 ,r2)
,r2 (logior ,r2 ,t0)
,r1 (logxor ,r1 ,r3)
,r2 (logxor ,r2 ,r0)
,r0 (logior ,r0 ,r1)
,r2 (logxor ,r2 ,r1)
,t0 (logxor ,t0 ,r0)
,r0 (logior ,r0 ,r3)
,r0 (logxor ,r0 ,r2)
,t0 (logxor ,t0 ,r3)
,t0 (logxor ,t0 ,r0)
,r3 (mod32lognot ,r3)
,r2 (logand ,r2 ,t0)
,r2 (logxor ,r2 ,r3)
,o0 ,r0
,o1 ,r1
,o2 ,t0
,o3 ,r2))
(defmacro serpent-sbox6-inverse (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r0 (logxor ,r0 ,r2)
,t0 ,r2
,r2 (logand ,r2 ,r0)
,t0 (logxor ,t0 ,r3)
,r2 (mod32lognot ,r2)
,r3 (logxor ,r3 ,r1)
,r2 (logxor ,r2 ,r3)
,t0 (logior ,t0 ,r0)
,r0 (logxor ,r0 ,r2)
,r3 (logxor ,r3 ,t0)
,t0 (logxor ,t0 ,r1)
,r1 (logand ,r1 ,r3)
,r1 (logxor ,r1 ,r0)
,r0 (logxor ,r0 ,r3)
,r0 (logior ,r0 ,r2)
,r3 (logxor ,r3 ,r1)
,t0 (logxor ,t0 ,r0)
,o0 ,r1
,o1 ,r2
,o2 ,t0
,o3 ,r3))
(defmacro serpent-sbox7 (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,t0 ,r1
,r1 (logior ,r1 ,r2)
,r1 (logxor ,r1 ,r3)
,t0 (logxor ,t0 ,r2)
,r2 (logxor ,r2 ,r1)
,r3 (logior ,r3 ,t0)
,r3 (logand ,r3 ,r0)
,t0 (logxor ,t0 ,r2)
,r3 (logxor ,r3 ,r1)
,r1 (logior ,r1 ,t0)
,r1 (logxor ,r1 ,r0)
,r0 (logior ,r0 ,t0)
,r0 (logxor ,r0 ,r2)
,r1 (logxor ,r1 ,t0)
,r2 (logxor ,r2 ,r1)
,r1 (logand ,r1 ,r0)
,r1 (logxor ,r1 ,t0)
,r2 (mod32lognot ,r2)
,r2 (logior ,r2 ,r0)
,t0 (logxor ,t0 ,r2)
,o0 ,t0
,o1 ,r3
,o2 ,r1
,o3 ,r0))
(defmacro serpent-sbox7-inverse (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,t0 ,r2
,r2 (logxor ,r2 ,r0)
,r0 (logand ,r0 ,r3)
,t0 (logior ,t0 ,r3)
,r2 (mod32lognot ,r2)
,r3 (logxor ,r3 ,r1)
,r1 (logior ,r1 ,r0)
,r0 (logxor ,r0 ,r2)
,r2 (logand ,r2 ,t0)
,r3 (logand ,r3 ,t0)
,r1 (logxor ,r1 ,r2)
,r2 (logxor ,r2 ,r0)
,r0 (logior ,r0 ,r2)
,t0 (logxor ,t0 ,r1)
,r0 (logxor ,r0 ,r3)
,r3 (logxor ,r3 ,t0)
,t0 (logior ,t0 ,r0)
,r3 (logxor ,r3 ,r2)
,t0 (logxor ,t0 ,r2)
,o0 ,r3
,o1 ,r0
,o2 ,r1
,o3 ,t0))
Linear transformation
(defmacro serpent-linear-transformation (r0 r1 r2 r3)
`(setf ,r0 (rol32 ,r0 13)
,r2 (rol32 ,r2 3)
,r1 (logxor ,r1 ,r0 ,r2)
,r3 (logxor ,r3 ,r2 (mod32ash ,r0 3))
,r1 (rol32 ,r1 1)
,r3 (rol32 ,r3 7)
,r0 (logxor ,r0 ,r1 ,r3)
,r2 (logxor ,r2 ,r3 (mod32ash ,r1 7))
,r0 (rol32 ,r0 5)
,r2 (rol32 ,r2 22)))
(defmacro serpent-linear-transformation-inverse (r0 r1 r2 r3)
`(setf ,r2 (rol32 ,r2 10)
,r0 (rol32 ,r0 27)
,r2 (logxor ,r2 ,r3 (mod32ash ,r1 7))
,r0 (logxor ,r0 ,r1 ,r3)
,r3 (rol32 ,r3 25)
,r1 (rol32 ,r1 31)
,r3 (logxor ,r3 ,r2 (mod32ash ,r0 3))
,r1 (logxor ,r1 ,r0 ,r2)
,r2 (rol32 ,r2 29)
,r0 (rol32 ,r0 19)))
;;; Key schedule
(defconstant +serpent-phi+ #x9e3779b9)
(defclass serpent (cipher 16-byte-block-mixin)
((subkeys :accessor serpent-subkeys
:type (simple-array (unsigned-byte 32) (33 4)))))
(defun serpent-pad-key (key)
(let ((padded-key (make-array 8 :element-type '(unsigned-byte 32)))
(len (floor (length key) 4)))
(dotimes (i len)
(setf (aref padded-key i) (ub32ref/le key (* i 4))))
(when (< len 8)
(setf (aref padded-key len) 1)
(loop for i from (1+ len) below 8
do (setf (aref padded-key i) 0)))
padded-key))
(defun serpent-generate-subkeys (key)
(declare (type (simple-array (unsigned-byte 32) (8)) key)
(optimize (speed 3) (space 0) (safety 0) (debug 0)))
(let ((subkeys (make-array '(33 4) :element-type '(unsigned-byte 32)))
(w (copy-seq key))
(ws (make-array 4 :element-type '(unsigned-byte 32)))
(wt (make-array 4 :element-type '(unsigned-byte 32)))
(t0 0)
(t1 0)
(t2 0)
(t3 0)
(t4 0))
(declare (type (simple-array (unsigned-byte 32) (33 4)) subkeys)
(type (simple-array (unsigned-byte 32) (8)) w)
(type (simple-array (unsigned-byte 32) (4)) ws wt)
(type (unsigned-byte 32) t0 t1 t2 t3 t4))
(macrolet ((expand-key4 (wo r)
`(setf (aref ,wo 0) (rol32 (logxor (aref w ,(mod (+ r 0) 8))
(aref w ,(mod (+ r 3) 8))
(aref w ,(mod (+ r 5) 8))
(aref w ,(mod (+ r 7) 8))
+serpent-phi+
,(+ r 0))
11)
(aref w ,(mod (+ r 0) 8)) (aref ,wo 0)
(aref ,wo 1) (rol32 (logxor (aref w ,(mod (+ r 1) 8))
(aref w ,(mod (+ r 4) 8))
(aref w ,(mod (+ r 6) 8))
(aref w ,(mod (+ r 0) 8))
+serpent-phi+
,(+ r 1))
11)
(aref w ,(mod (+ r 1) 8)) (aref ,wo 1)
(aref ,wo 2) (rol32 (logxor (aref w ,(mod (+ r 2) 8))
(aref w ,(mod (+ r 5) 8))
(aref w ,(mod (+ r 7) 8))
(aref w ,(mod (+ r 1) 8))
+serpent-phi+
,(+ r 2))
11)
(aref w ,(mod (+ r 2) 8)) (aref ,wo 2)
(aref ,wo 3) (rol32 (logxor (aref w ,(mod (+ r 3) 8))
(aref w ,(mod (+ r 6) 8))
(aref w ,(mod (+ r 0) 8))
(aref w ,(mod (+ r 2) 8))
+serpent-phi+
,(+ r 3))
11)
(aref w ,(mod (+ r 3) 8)) (aref ,wo 3)))
(make-subkeys ()
(loop for i from 0 to 15
for sbox-a = (read-from-string (format nil "serpent-sbox~d" (mod (- 3 (* 2 i)) 8)))
for sbox-b = (read-from-string (format nil "serpent-sbox~d" (mod (- 2 (* 2 i)) 8)))
append (list `(expand-key4 ws ,(* 8 i))
`(expand-key4 wt ,(+ (* 8 i) 4))
`(setf t0 (aref ws 0)
t1 (aref ws 1)
t2 (aref ws 2)
t3 (aref ws 3))
`(,sbox-a t0 t1 t2 t3 (aref ws 0) (aref ws 1) (aref ws 2) (aref ws 3) t4)
`(setf (aref subkeys ,(* 2 i) 0) (aref ws 0)
(aref subkeys ,(* 2 i) 1) (aref ws 1)
(aref subkeys ,(* 2 i) 2) (aref ws 2)
(aref subkeys ,(* 2 i) 3) (aref ws 3))
`(setf t0 (aref wt 0)
t1 (aref wt 1)
t2 (aref wt 2)
t3 (aref wt 3))
`(,sbox-b t0 t1 t2 t3 (aref wt 0) (aref wt 1) (aref wt 2) (aref wt 3) t4)
`(setf (aref subkeys ,(1+ (* 2 i)) 0) (aref wt 0)
(aref subkeys ,(1+ (* 2 i)) 1) (aref wt 1)
(aref subkeys ,(1+ (* 2 i)) 2) (aref wt 2)
(aref subkeys ,(1+ (* 2 i)) 3) (aref wt 3)))
into forms
finally (return `(progn ,@forms)))))
(make-subkeys)
(expand-key4 ws 128)
(setf t0 (aref ws 0)
t1 (aref ws 1)
t2 (aref ws 2)
t3 (aref ws 3))
(serpent-sbox3 t0 t1 t2 t3 (aref ws 0) (aref ws 1) (aref ws 2) (aref ws 3) t4)
(setf (aref subkeys 32 0) (aref ws 0)
(aref subkeys 32 1) (aref ws 1)
(aref subkeys 32 2) (aref ws 2)
(aref subkeys 32 3) (aref ws 3))
subkeys)))
(defmethod schedule-key ((cipher serpent) key)
(setf (serpent-subkeys cipher) (serpent-generate-subkeys (serpent-pad-key key)))
cipher)
;;; Rounds
(define-block-encryptor serpent 16
(let ((subkeys (serpent-subkeys context))
(t0 0)
(t1 0)
(t2 0)
(t3 0)
(t4 0))
(declare (type (simple-array (unsigned-byte 32) (33 4)) subkeys)
(type (unsigned-byte 32) t0 t1 t2 t3 t4))
(with-words ((b0 b1 b2 b3) plaintext plaintext-start :big-endian nil :size 4)
(macrolet ((serpent-rounds ()
(loop for i from 0 to 30
for sbox = (read-from-string (format nil "serpent-sbox~d" (mod i 8)))
append (list `(setf t0 (logxor b0 (aref subkeys ,i 0))
t1 (logxor b1 (aref subkeys ,i 1))
t2 (logxor b2 (aref subkeys ,i 2))
t3 (logxor b3 (aref subkeys ,i 3)))
`(,sbox t0 t1 t2 t3 b0 b1 b2 b3 t4)
`(serpent-linear-transformation b0 b1 b2 b3))
into forms
finally (return `(progn ,@forms)))))
;; Regular rounds
(serpent-rounds)
;; Last round
(setf b0 (logxor b0 (aref subkeys 31 0))
b1 (logxor b1 (aref subkeys 31 1))
b2 (logxor b2 (aref subkeys 31 2))
b3 (logxor b3 (aref subkeys 31 3)))
(serpent-sbox7 b0 b1 b2 b3 t0 t1 t2 t3 t4)
(setf b0 (logxor t0 (aref subkeys 32 0))
b1 (logxor t1 (aref subkeys 32 1))
b2 (logxor t2 (aref subkeys 32 2))
b3 (logxor t3 (aref subkeys 32 3)))
(store-words ciphertext ciphertext-start b0 b1 b2 b3)
(values)))))
(define-block-decryptor serpent 16
(let ((subkeys (serpent-subkeys context))
(t0 0)
(t1 0)
(t2 0)
(t3 0)
(t4 0))
(declare (type (simple-array (unsigned-byte 32) (33 4)) subkeys)
(type (unsigned-byte 32) t0 t1 t2 t3 t4))
(with-words ((b0 b1 b2 b3) ciphertext ciphertext-start :big-endian nil :size 4)
(macrolet ((serpent-rounds-inverse ()
(loop for i from 30 downto 0
for sbox-inverse = (read-from-string (format nil "serpent-sbox~d-inverse" (mod i 8)))
append (list `(serpent-linear-transformation-inverse b0 b1 b2 b3)
`(,sbox-inverse b0 b1 b2 b3 t0 t1 t2 t3 t4)
`(setf b0 (logxor t0 (aref subkeys ,i 0))
b1 (logxor t1 (aref subkeys ,i 1))
b2 (logxor t2 (aref subkeys ,i 2))
b3 (logxor t3 (aref subkeys ,i 3))))
into forms
finally (return `(progn ,@forms)))))
First inverse round
(setf b0 (logxor b0 (aref subkeys 32 0))
b1 (logxor b1 (aref subkeys 32 1))
b2 (logxor b2 (aref subkeys 32 2))
b3 (logxor b3 (aref subkeys 32 3)))
(serpent-sbox7-inverse b0 b1 b2 b3 t0 t1 t2 t3 t4)
(setf b0 (logxor t0 (aref subkeys 31 0))
b1 (logxor t1 (aref subkeys 31 1))
b2 (logxor t2 (aref subkeys 31 2))
b3 (logxor t3 (aref subkeys 31 3)))
;; Regular inverse rounds
(serpent-rounds-inverse)
(store-words plaintext plaintext-start b0 b1 b2 b3)
(values)))))
(defcipher serpent
(:encrypt-function serpent-encrypt-block)
(:decrypt-function serpent-decrypt-block)
(:block-length 16)
(:key-length (:fixed 16 24 32)))
| null | https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/ironclad-v0.47/src/ciphers/serpent.lisp | lisp | -*- mode: lisp; indent-tabs-mode: nil -*-
serpent.lisp -- implementation of the Serpent block cipher
Key schedule
Rounds
Regular rounds
Last round
Regular inverse rounds |
(in-package :crypto)
S - Boxes
(defmacro serpent-sbox0 (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r3 (logxor ,r3 ,r0)
,t0 ,r1
,r1 (logand ,r1 ,r3)
,t0 (logxor ,t0 ,r2)
,r1 (logxor ,r1 ,r0)
,r0 (logior ,r0 ,r3)
,r0 (logxor ,r0 ,t0)
,t0 (logxor ,t0 ,r3)
,r3 (logxor ,r3 ,r2)
,r2 (logior ,r2 ,r1)
,r2 (logxor ,r2 ,t0)
,t0 (mod32lognot ,t0)
,t0 (logior ,t0 ,r1)
,r1 (logxor ,r1 ,r3)
,r1 (logxor ,r1 ,t0)
,r3 (logior ,r3 ,r0)
,r1 (logxor ,r1 ,r3)
,t0 (logxor ,t0 ,r3)
,o0 ,r1
,o1 ,t0
,o2 ,r2
,o3 ,r0))
(defmacro serpent-sbox0-inverse (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r2 (mod32lognot ,r2)
,t0 ,r1
,r1 (logior ,r1 ,r0)
,t0 (mod32lognot ,t0)
,r1 (logxor ,r1 ,r2)
,r2 (logior ,r2 ,t0)
,r1 (logxor ,r1 ,r3)
,r0 (logxor ,r0 ,t0)
,r2 (logxor ,r2 ,r0)
,r0 (logand ,r0 ,r3)
,t0 (logxor ,t0 ,r0)
,r0 (logior ,r0 ,r1)
,r0 (logxor ,r0 ,r2)
,r3 (logxor ,r3 ,t0)
,r2 (logxor ,r2 ,r1)
,r3 (logxor ,r3 ,r0)
,r3 (logxor ,r3 ,r1)
,r2 (logand ,r2 ,r3)
,t0 (logxor ,t0 ,r2)
,o0 ,r0
,o1 ,t0
,o2 ,r1
,o3 ,r3))
(defmacro serpent-sbox1 (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r0 (mod32lognot ,r0)
,r2 (mod32lognot ,r2)
,t0 ,r0
,r0 (logand ,r0 ,r1)
,r2 (logxor ,r0 ,r2)
,r0 (logior ,r0 ,r3)
,r3 (logxor ,r3 ,r2)
,r1 (logxor ,r1 ,r0)
,r0 (logxor ,r0 ,t0)
,t0 (logior ,t0 ,r1)
,r1 (logxor ,r1 ,r3)
,r2 (logior ,r2 ,r0)
,r2 (logand ,r2 ,t0)
,r0 (logxor ,r0 ,r1)
,r1 (logand ,r1 ,r2)
,r1 (logxor ,r1 ,r0)
,r0 (logand ,r0 ,r2)
,r0 (logxor ,r0 ,t0)
,o0 ,r2
,o1 ,r0
,o2 ,r3
,o3 ,r1))
(defmacro serpent-sbox1-inverse (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,t0 ,r1
,r1 (logxor ,r1 ,r3)
,r3 (logand ,r3 ,r1)
,t0 (logxor ,t0 ,r2)
,r3 (logxor ,r3 ,r0)
,r0 (logior ,r0 ,r1)
,r2 (logxor ,r2 ,r3)
,r0 (logxor ,r0 ,t0)
,r0 (logior ,r0 ,r2)
,r1 (logxor ,r1 ,r3)
,r0 (logxor ,r0 ,r1)
,r1 (logior ,r1 ,r3)
,r1 (logxor ,r1 ,r0)
,t0 (mod32lognot ,t0)
,t0 (logxor ,t0 ,r1)
,r1 (logior ,r1 ,r0)
,r1 (logxor ,r1 ,r0)
,r1 (logior ,r1 ,t0)
,r3 (logxor ,r3 ,r1)
,o0 ,t0
,o1 ,r0
,o2 ,r3
,o3 ,r2))
(defmacro serpent-sbox2 (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,t0 ,r0
,r0 (logand ,r0 ,r2)
,r0 (logxor ,r0 ,r3)
,r2 (logxor ,r2 ,r1)
,r2 (logxor ,r2 ,r0)
,r3 (logior ,r3 ,t0)
,r3 (logxor ,r3 ,r1)
,t0 (logxor ,t0 ,r2)
,r1 ,r3
,r3 (logior ,r3 ,t0)
,r3 (logxor ,r3 ,r0)
,r0 (logand ,r0 ,r1)
,t0 (logxor ,t0 ,r0)
,r1 (logxor ,r1 ,r3)
,r1 (logxor ,r1 ,t0)
,t0 (mod32lognot ,t0)
,o0 ,r2
,o1 ,r3
,o2 ,r1
,o3 ,t0))
(defmacro serpent-sbox2-inverse (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r2 (logxor ,r2 ,r3)
,r3 (logxor ,r3 ,r0)
,t0 ,r3
,r3 (logand ,r3 ,r2)
,r3 (logxor ,r3 ,r1)
,r1 (logior ,r1 ,r2)
,r1 (logxor ,r1 ,t0)
,t0 (logand ,t0 ,r3)
,r2 (logxor ,r2 ,r3)
,t0 (logand ,t0 ,r0)
,t0 (logxor ,t0 ,r2)
,r2 (logand ,r2 ,r1)
,r2 (logior ,r2 ,r0)
,r3 (mod32lognot ,r3)
,r2 (logxor ,r2 ,r3)
,r0 (logxor ,r0 ,r3)
,r0 (logand ,r0 ,r1)
,r3 (logxor ,r3 ,t0)
,r3 (logxor ,r3 ,r0)
,o0 ,r1
,o1 ,t0
,o2 ,r2
,o3 ,r3))
(defmacro serpent-sbox3 (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,t0 ,r0
,r0 (logior ,r0 ,r3)
,r3 (logxor ,r3 ,r1)
,r1 (logand ,r1 ,t0)
,t0 (logxor ,t0 ,r2)
,r2 (logxor ,r2 ,r3)
,r3 (logand ,r3 ,r0)
,t0 (logior ,t0 ,r1)
,r3 (logxor ,r3 ,t0)
,r0 (logxor ,r0 ,r1)
,t0 (logand ,t0 ,r0)
,r1 (logxor ,r1 ,r3)
,t0 (logxor ,t0 ,r2)
,r1 (logior ,r1 ,r0)
,r1 (logxor ,r1 ,r2)
,r0 (logxor ,r0 ,r3)
,r2 ,r1
,r1 (logior ,r1 ,r3)
,r1 (logxor ,r1 ,r0)
,o0 ,r1
,o1 ,r2
,o2 ,r3
,o3 ,t0))
(defmacro serpent-sbox3-inverse (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,t0 ,r2
,r2 (logxor ,r2 ,r1)
,r0 (logxor ,r0 ,r2)
,t0 (logand ,t0 ,r2)
,t0 (logxor ,t0 ,r0)
,r0 (logand ,r0 ,r1)
,r1 (logxor ,r1 ,r3)
,r3 (logior ,r3 ,t0)
,r2 (logxor ,r2 ,r3)
,r0 (logxor ,r0 ,r3)
,r1 (logxor ,r1 ,t0)
,r3 (logand ,r3 ,r2)
,r3 (logxor ,r3 ,r1)
,r1 (logxor ,r1 ,r0)
,r1 (logior ,r1 ,r2)
,r0 (logxor ,r0 ,r3)
,r1 (logxor ,r1 ,t0)
,r0 (logxor ,r0 ,r1)
,o0 ,r2
,o1 ,r1
,o2 ,r3
,o3 ,r0))
(defmacro serpent-sbox4 (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r1 (logxor ,r1 ,r3)
,r3 (mod32lognot ,r3)
,r2 (logxor ,r2 ,r3)
,r3 (logxor ,r3 ,r0)
,t0 ,r1
,r1 (logand ,r1 ,r3)
,r1 (logxor ,r1 ,r2)
,t0 (logxor ,t0 ,r3)
,r0 (logxor ,r0 ,t0)
,r2 (logand ,r2 ,t0)
,r2 (logxor ,r2 ,r0)
,r0 (logand ,r0 ,r1)
,r3 (logxor ,r3 ,r0)
,t0 (logior ,t0 ,r1)
,t0 (logxor ,t0 ,r0)
,r0 (logior ,r0 ,r3)
,r0 (logxor ,r0 ,r2)
,r2 (logand ,r2 ,r3)
,r0 (mod32lognot ,r0)
,t0 (logxor ,t0 ,r2)
,o0 ,r1
,o1 ,t0
,o2 ,r0
,o3 ,r3))
(defmacro serpent-sbox4-inverse (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,t0 ,r2
,r2 (logand ,r2 ,r3)
,r2 (logxor ,r2 ,r1)
,r1 (logior ,r1 ,r3)
,r1 (logand ,r1 ,r0)
,t0 (logxor ,t0 ,r2)
,t0 (logxor ,t0 ,r1)
,r1 (logand ,r1 ,r2)
,r0 (mod32lognot ,r0)
,r3 (logxor ,r3 ,t0)
,r1 (logxor ,r1 ,r3)
,r3 (logand ,r3 ,r0)
,r3 (logxor ,r3 ,r2)
,r0 (logxor ,r0 ,r1)
,r2 (logand ,r2 ,r0)
,r3 (logxor ,r3 ,r0)
,r2 (logxor ,r2 ,t0)
,r2 (logior ,r2 ,r3)
,r3 (logxor ,r3 ,r0)
,r2 (logxor ,r2 ,r1)
,o0 ,r0
,o1 ,r3
,o2 ,r2
,o3 ,t0))
(defmacro serpent-sbox5 (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r0 (logxor ,r0 ,r1)
,r1 (logxor ,r1 ,r3)
,r3 (mod32lognot ,r3)
,t0 ,r1
,r1 (logand ,r1 ,r0)
,r2 (logxor ,r2 ,r3)
,r1 (logxor ,r1 ,r2)
,r2 (logior ,r2 ,t0)
,t0 (logxor ,t0 ,r3)
,r3 (logand ,r3 ,r1)
,r3 (logxor ,r3 ,r0)
,t0 (logxor ,t0 ,r1)
,t0 (logxor ,t0 ,r2)
,r2 (logxor ,r2 ,r0)
,r0 (logand ,r0 ,r3)
,r2 (mod32lognot ,r2)
,r0 (logxor ,r0 ,t0)
,t0 (logior ,t0 ,r3)
,r2 (logxor ,r2 ,t0)
,o0 ,r1
,o1 ,r3
,o2 ,r0
,o3 ,r2))
(defmacro serpent-sbox5-inverse (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r1 (mod32lognot ,r1)
,t0 ,r3
,r2 (logxor ,r2 ,r1)
,r3 (logior ,r3 ,r0)
,r3 (logxor ,r3 ,r2)
,r2 (logior ,r2 ,r1)
,r2 (logand ,r2 ,r0)
,t0 (logxor ,t0 ,r3)
,r2 (logxor ,r2 ,t0)
,t0 (logior ,t0 ,r0)
,t0 (logxor ,t0 ,r1)
,r1 (logand ,r1 ,r2)
,r1 (logxor ,r1 ,r3)
,t0 (logxor ,t0 ,r2)
,r3 (logand ,r3 ,t0)
,t0 (logxor ,t0 ,r1)
,r3 (logxor ,r3 ,t0)
,t0 (mod32lognot ,t0)
,r3 (logxor ,r3 ,r0)
,o0 ,r1
,o1 ,t0
,o2 ,r3
,o3 ,r2))
(defmacro serpent-sbox6 (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r2 (mod32lognot ,r2)
,t0 ,r3
,r3 (logand ,r3 ,r0)
,r0 (logxor ,r0 ,t0)
,r3 (logxor ,r3 ,r2)
,r2 (logior ,r2 ,t0)
,r1 (logxor ,r1 ,r3)
,r2 (logxor ,r2 ,r0)
,r0 (logior ,r0 ,r1)
,r2 (logxor ,r2 ,r1)
,t0 (logxor ,t0 ,r0)
,r0 (logior ,r0 ,r3)
,r0 (logxor ,r0 ,r2)
,t0 (logxor ,t0 ,r3)
,t0 (logxor ,t0 ,r0)
,r3 (mod32lognot ,r3)
,r2 (logand ,r2 ,t0)
,r2 (logxor ,r2 ,r3)
,o0 ,r0
,o1 ,r1
,o2 ,t0
,o3 ,r2))
(defmacro serpent-sbox6-inverse (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,r0 (logxor ,r0 ,r2)
,t0 ,r2
,r2 (logand ,r2 ,r0)
,t0 (logxor ,t0 ,r3)
,r2 (mod32lognot ,r2)
,r3 (logxor ,r3 ,r1)
,r2 (logxor ,r2 ,r3)
,t0 (logior ,t0 ,r0)
,r0 (logxor ,r0 ,r2)
,r3 (logxor ,r3 ,t0)
,t0 (logxor ,t0 ,r1)
,r1 (logand ,r1 ,r3)
,r1 (logxor ,r1 ,r0)
,r0 (logxor ,r0 ,r3)
,r0 (logior ,r0 ,r2)
,r3 (logxor ,r3 ,r1)
,t0 (logxor ,t0 ,r0)
,o0 ,r1
,o1 ,r2
,o2 ,t0
,o3 ,r3))
(defmacro serpent-sbox7 (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,t0 ,r1
,r1 (logior ,r1 ,r2)
,r1 (logxor ,r1 ,r3)
,t0 (logxor ,t0 ,r2)
,r2 (logxor ,r2 ,r1)
,r3 (logior ,r3 ,t0)
,r3 (logand ,r3 ,r0)
,t0 (logxor ,t0 ,r2)
,r3 (logxor ,r3 ,r1)
,r1 (logior ,r1 ,t0)
,r1 (logxor ,r1 ,r0)
,r0 (logior ,r0 ,t0)
,r0 (logxor ,r0 ,r2)
,r1 (logxor ,r1 ,t0)
,r2 (logxor ,r2 ,r1)
,r1 (logand ,r1 ,r0)
,r1 (logxor ,r1 ,t0)
,r2 (mod32lognot ,r2)
,r2 (logior ,r2 ,r0)
,t0 (logxor ,t0 ,r2)
,o0 ,t0
,o1 ,r3
,o2 ,r1
,o3 ,r0))
(defmacro serpent-sbox7-inverse (r0 r1 r2 r3 o0 o1 o2 o3 t0)
`(setf ,t0 ,r2
,r2 (logxor ,r2 ,r0)
,r0 (logand ,r0 ,r3)
,t0 (logior ,t0 ,r3)
,r2 (mod32lognot ,r2)
,r3 (logxor ,r3 ,r1)
,r1 (logior ,r1 ,r0)
,r0 (logxor ,r0 ,r2)
,r2 (logand ,r2 ,t0)
,r3 (logand ,r3 ,t0)
,r1 (logxor ,r1 ,r2)
,r2 (logxor ,r2 ,r0)
,r0 (logior ,r0 ,r2)
,t0 (logxor ,t0 ,r1)
,r0 (logxor ,r0 ,r3)
,r3 (logxor ,r3 ,t0)
,t0 (logior ,t0 ,r0)
,r3 (logxor ,r3 ,r2)
,t0 (logxor ,t0 ,r2)
,o0 ,r3
,o1 ,r0
,o2 ,r1
,o3 ,t0))
Linear transformation
(defmacro serpent-linear-transformation (r0 r1 r2 r3)
`(setf ,r0 (rol32 ,r0 13)
,r2 (rol32 ,r2 3)
,r1 (logxor ,r1 ,r0 ,r2)
,r3 (logxor ,r3 ,r2 (mod32ash ,r0 3))
,r1 (rol32 ,r1 1)
,r3 (rol32 ,r3 7)
,r0 (logxor ,r0 ,r1 ,r3)
,r2 (logxor ,r2 ,r3 (mod32ash ,r1 7))
,r0 (rol32 ,r0 5)
,r2 (rol32 ,r2 22)))
(defmacro serpent-linear-transformation-inverse (r0 r1 r2 r3)
`(setf ,r2 (rol32 ,r2 10)
,r0 (rol32 ,r0 27)
,r2 (logxor ,r2 ,r3 (mod32ash ,r1 7))
,r0 (logxor ,r0 ,r1 ,r3)
,r3 (rol32 ,r3 25)
,r1 (rol32 ,r1 31)
,r3 (logxor ,r3 ,r2 (mod32ash ,r0 3))
,r1 (logxor ,r1 ,r0 ,r2)
,r2 (rol32 ,r2 29)
,r0 (rol32 ,r0 19)))
(defconstant +serpent-phi+ #x9e3779b9)
(defclass serpent (cipher 16-byte-block-mixin)
((subkeys :accessor serpent-subkeys
:type (simple-array (unsigned-byte 32) (33 4)))))
(defun serpent-pad-key (key)
(let ((padded-key (make-array 8 :element-type '(unsigned-byte 32)))
(len (floor (length key) 4)))
(dotimes (i len)
(setf (aref padded-key i) (ub32ref/le key (* i 4))))
(when (< len 8)
(setf (aref padded-key len) 1)
(loop for i from (1+ len) below 8
do (setf (aref padded-key i) 0)))
padded-key))
(defun serpent-generate-subkeys (key)
(declare (type (simple-array (unsigned-byte 32) (8)) key)
(optimize (speed 3) (space 0) (safety 0) (debug 0)))
(let ((subkeys (make-array '(33 4) :element-type '(unsigned-byte 32)))
(w (copy-seq key))
(ws (make-array 4 :element-type '(unsigned-byte 32)))
(wt (make-array 4 :element-type '(unsigned-byte 32)))
(t0 0)
(t1 0)
(t2 0)
(t3 0)
(t4 0))
(declare (type (simple-array (unsigned-byte 32) (33 4)) subkeys)
(type (simple-array (unsigned-byte 32) (8)) w)
(type (simple-array (unsigned-byte 32) (4)) ws wt)
(type (unsigned-byte 32) t0 t1 t2 t3 t4))
(macrolet ((expand-key4 (wo r)
`(setf (aref ,wo 0) (rol32 (logxor (aref w ,(mod (+ r 0) 8))
(aref w ,(mod (+ r 3) 8))
(aref w ,(mod (+ r 5) 8))
(aref w ,(mod (+ r 7) 8))
+serpent-phi+
,(+ r 0))
11)
(aref w ,(mod (+ r 0) 8)) (aref ,wo 0)
(aref ,wo 1) (rol32 (logxor (aref w ,(mod (+ r 1) 8))
(aref w ,(mod (+ r 4) 8))
(aref w ,(mod (+ r 6) 8))
(aref w ,(mod (+ r 0) 8))
+serpent-phi+
,(+ r 1))
11)
(aref w ,(mod (+ r 1) 8)) (aref ,wo 1)
(aref ,wo 2) (rol32 (logxor (aref w ,(mod (+ r 2) 8))
(aref w ,(mod (+ r 5) 8))
(aref w ,(mod (+ r 7) 8))
(aref w ,(mod (+ r 1) 8))
+serpent-phi+
,(+ r 2))
11)
(aref w ,(mod (+ r 2) 8)) (aref ,wo 2)
(aref ,wo 3) (rol32 (logxor (aref w ,(mod (+ r 3) 8))
(aref w ,(mod (+ r 6) 8))
(aref w ,(mod (+ r 0) 8))
(aref w ,(mod (+ r 2) 8))
+serpent-phi+
,(+ r 3))
11)
(aref w ,(mod (+ r 3) 8)) (aref ,wo 3)))
(make-subkeys ()
(loop for i from 0 to 15
for sbox-a = (read-from-string (format nil "serpent-sbox~d" (mod (- 3 (* 2 i)) 8)))
for sbox-b = (read-from-string (format nil "serpent-sbox~d" (mod (- 2 (* 2 i)) 8)))
append (list `(expand-key4 ws ,(* 8 i))
`(expand-key4 wt ,(+ (* 8 i) 4))
`(setf t0 (aref ws 0)
t1 (aref ws 1)
t2 (aref ws 2)
t3 (aref ws 3))
`(,sbox-a t0 t1 t2 t3 (aref ws 0) (aref ws 1) (aref ws 2) (aref ws 3) t4)
`(setf (aref subkeys ,(* 2 i) 0) (aref ws 0)
(aref subkeys ,(* 2 i) 1) (aref ws 1)
(aref subkeys ,(* 2 i) 2) (aref ws 2)
(aref subkeys ,(* 2 i) 3) (aref ws 3))
`(setf t0 (aref wt 0)
t1 (aref wt 1)
t2 (aref wt 2)
t3 (aref wt 3))
`(,sbox-b t0 t1 t2 t3 (aref wt 0) (aref wt 1) (aref wt 2) (aref wt 3) t4)
`(setf (aref subkeys ,(1+ (* 2 i)) 0) (aref wt 0)
(aref subkeys ,(1+ (* 2 i)) 1) (aref wt 1)
(aref subkeys ,(1+ (* 2 i)) 2) (aref wt 2)
(aref subkeys ,(1+ (* 2 i)) 3) (aref wt 3)))
into forms
finally (return `(progn ,@forms)))))
(make-subkeys)
(expand-key4 ws 128)
(setf t0 (aref ws 0)
t1 (aref ws 1)
t2 (aref ws 2)
t3 (aref ws 3))
(serpent-sbox3 t0 t1 t2 t3 (aref ws 0) (aref ws 1) (aref ws 2) (aref ws 3) t4)
(setf (aref subkeys 32 0) (aref ws 0)
(aref subkeys 32 1) (aref ws 1)
(aref subkeys 32 2) (aref ws 2)
(aref subkeys 32 3) (aref ws 3))
subkeys)))
(defmethod schedule-key ((cipher serpent) key)
(setf (serpent-subkeys cipher) (serpent-generate-subkeys (serpent-pad-key key)))
cipher)
(define-block-encryptor serpent 16
(let ((subkeys (serpent-subkeys context))
(t0 0)
(t1 0)
(t2 0)
(t3 0)
(t4 0))
(declare (type (simple-array (unsigned-byte 32) (33 4)) subkeys)
(type (unsigned-byte 32) t0 t1 t2 t3 t4))
(with-words ((b0 b1 b2 b3) plaintext plaintext-start :big-endian nil :size 4)
(macrolet ((serpent-rounds ()
(loop for i from 0 to 30
for sbox = (read-from-string (format nil "serpent-sbox~d" (mod i 8)))
append (list `(setf t0 (logxor b0 (aref subkeys ,i 0))
t1 (logxor b1 (aref subkeys ,i 1))
t2 (logxor b2 (aref subkeys ,i 2))
t3 (logxor b3 (aref subkeys ,i 3)))
`(,sbox t0 t1 t2 t3 b0 b1 b2 b3 t4)
`(serpent-linear-transformation b0 b1 b2 b3))
into forms
finally (return `(progn ,@forms)))))
(serpent-rounds)
(setf b0 (logxor b0 (aref subkeys 31 0))
b1 (logxor b1 (aref subkeys 31 1))
b2 (logxor b2 (aref subkeys 31 2))
b3 (logxor b3 (aref subkeys 31 3)))
(serpent-sbox7 b0 b1 b2 b3 t0 t1 t2 t3 t4)
(setf b0 (logxor t0 (aref subkeys 32 0))
b1 (logxor t1 (aref subkeys 32 1))
b2 (logxor t2 (aref subkeys 32 2))
b3 (logxor t3 (aref subkeys 32 3)))
(store-words ciphertext ciphertext-start b0 b1 b2 b3)
(values)))))
(define-block-decryptor serpent 16
(let ((subkeys (serpent-subkeys context))
(t0 0)
(t1 0)
(t2 0)
(t3 0)
(t4 0))
(declare (type (simple-array (unsigned-byte 32) (33 4)) subkeys)
(type (unsigned-byte 32) t0 t1 t2 t3 t4))
(with-words ((b0 b1 b2 b3) ciphertext ciphertext-start :big-endian nil :size 4)
(macrolet ((serpent-rounds-inverse ()
(loop for i from 30 downto 0
for sbox-inverse = (read-from-string (format nil "serpent-sbox~d-inverse" (mod i 8)))
append (list `(serpent-linear-transformation-inverse b0 b1 b2 b3)
`(,sbox-inverse b0 b1 b2 b3 t0 t1 t2 t3 t4)
`(setf b0 (logxor t0 (aref subkeys ,i 0))
b1 (logxor t1 (aref subkeys ,i 1))
b2 (logxor t2 (aref subkeys ,i 2))
b3 (logxor t3 (aref subkeys ,i 3))))
into forms
finally (return `(progn ,@forms)))))
First inverse round
(setf b0 (logxor b0 (aref subkeys 32 0))
b1 (logxor b1 (aref subkeys 32 1))
b2 (logxor b2 (aref subkeys 32 2))
b3 (logxor b3 (aref subkeys 32 3)))
(serpent-sbox7-inverse b0 b1 b2 b3 t0 t1 t2 t3 t4)
(setf b0 (logxor t0 (aref subkeys 31 0))
b1 (logxor t1 (aref subkeys 31 1))
b2 (logxor t2 (aref subkeys 31 2))
b3 (logxor t3 (aref subkeys 31 3)))
(serpent-rounds-inverse)
(store-words plaintext plaintext-start b0 b1 b2 b3)
(values)))))
(defcipher serpent
(:encrypt-function serpent-encrypt-block)
(:decrypt-function serpent-decrypt-block)
(:block-length 16)
(:key-length (:fixed 16 24 32)))
|
a34bdc1a1f5baacb1a023c02cb8c63773bce3eb71b06911f1fbbdd6c0aca9c38 | gas2serra/cldk | prim-text.lisp | (in-package :cldk-render-internals)
;;;
;;; Converting string into paths
;;;
;;; Font's utilities
(defparameter *text-sizes* '(:normal 14
:tiny 8
:very-small 10
:small 12
:large 18
:very-large 20
:huge 24))
(defun string-primitive-paths (x y string font size fn)
(declare (ignore size))
(let ((scale (zpb-ttf-font-units->pixels font)))
(declare (ignore scale))
(paths-from-string font string fn
:offset (paths:make-point x y))))
(defun paths-from-string (font text fn &key (offset (make-point 0 0))
(scale-x 1.0) (scale-y 1.0)
(kerning t) (auto-orient nil))
"Extract paths from a string."
(declare (ignore scale-x scale-y auto-orient))
(let ((font-loader (zpb-ttf-font-loader (truetype-font-face font)))
(scale (zpb-ttf-font-units->pixels font)))
(loop
for previous-char = nil then char
for char across text
for paths = (font-glyph-paths font char)
for opacity-image = (font-glyph-opacity-image font char)
for dx = (font-glyph-left font char)
for dy = (font-glyph-top font char)
for previous-width = nil then width
for width = (max
(font-glyph-right font char)
(font-glyph-width font char))
do (when previous-char
(setf offset
(paths-ttf::p+ offset
(paths:make-point (* 1
(+ previous-width
(* scale (if kerning
(paths-ttf::kerning-offset previous-char
char
font-loader)
0))))
0))))
(funcall fn paths opacity-image dx dy
(make-translation-transformation
(paths:point-x offset)
(paths:point-y offset))))))
(defun glyph-paths (font char)
"Render a character of 'face', returning a 2D (unsigned-byte 8) array
suitable as an alpha mask, and dimensions. This function returns five
values: alpha mask byte array, x-origin, y-origin (subtracted from
position before rendering), horizontal and vertical advances."
(climi::with-lock-held (*zpb-font-lock*)
(with-slots (units->pixels size ascent descent) font
(let* ((units->pixels (zpb-ttf-font-units->pixels font))
(size (truetype-font-size font))
(ascent (truetype-font-ascent font))
(descent (truetype-font-descent font))
(glyph (zpb-ttf:find-glyph char (zpb-ttf-font-loader
(truetype-font-face font))))
(left-side-bearing (* units->pixels (zpb-ttf:left-side-bearing glyph)))
(right-side-bearing (* units->pixels (zpb-ttf:right-side-bearing glyph)))
(advance-width (* units->pixels (zpb-ttf:advance-width glyph)))
(bounding-box (map 'vector (lambda (x) (float (* x units->pixels)))
(zpb-ttf:bounding-box glyph)))
(min-x (elt bounding-box 0))
(min-y (elt bounding-box 1))
(max-x (elt bounding-box 2))
(max-y (elt bounding-box 3))
(width (- (ceiling max-x) (floor min-x)))
(height (- (ceiling max-y) (floor min-y)))
(paths (paths-ttf:paths-from-glyph glyph
:offset (paths:make-point 0 0)
:scale-x units->pixels
:scale-y (- units->pixels))))
(declare (ignore SIZE ASCENT DESCENT LEFT-SIDE-BEARING RIGHT-SIDE-BEARING))
(values paths
(floor min-x)
(ceiling max-y)
width
height
(round advance-width)
0)))))
| null | https://raw.githubusercontent.com/gas2serra/cldk/63c8322aedac44249ff8f28cd4f5f59a48ab1441/mcclim/render/cl-vectors/prim-text.lisp | lisp |
Converting string into paths
Font's utilities | (in-package :cldk-render-internals)
(defparameter *text-sizes* '(:normal 14
:tiny 8
:very-small 10
:small 12
:large 18
:very-large 20
:huge 24))
(defun string-primitive-paths (x y string font size fn)
(declare (ignore size))
(let ((scale (zpb-ttf-font-units->pixels font)))
(declare (ignore scale))
(paths-from-string font string fn
:offset (paths:make-point x y))))
(defun paths-from-string (font text fn &key (offset (make-point 0 0))
(scale-x 1.0) (scale-y 1.0)
(kerning t) (auto-orient nil))
"Extract paths from a string."
(declare (ignore scale-x scale-y auto-orient))
(let ((font-loader (zpb-ttf-font-loader (truetype-font-face font)))
(scale (zpb-ttf-font-units->pixels font)))
(loop
for previous-char = nil then char
for char across text
for paths = (font-glyph-paths font char)
for opacity-image = (font-glyph-opacity-image font char)
for dx = (font-glyph-left font char)
for dy = (font-glyph-top font char)
for previous-width = nil then width
for width = (max
(font-glyph-right font char)
(font-glyph-width font char))
do (when previous-char
(setf offset
(paths-ttf::p+ offset
(paths:make-point (* 1
(+ previous-width
(* scale (if kerning
(paths-ttf::kerning-offset previous-char
char
font-loader)
0))))
0))))
(funcall fn paths opacity-image dx dy
(make-translation-transformation
(paths:point-x offset)
(paths:point-y offset))))))
(defun glyph-paths (font char)
"Render a character of 'face', returning a 2D (unsigned-byte 8) array
suitable as an alpha mask, and dimensions. This function returns five
values: alpha mask byte array, x-origin, y-origin (subtracted from
position before rendering), horizontal and vertical advances."
(climi::with-lock-held (*zpb-font-lock*)
(with-slots (units->pixels size ascent descent) font
(let* ((units->pixels (zpb-ttf-font-units->pixels font))
(size (truetype-font-size font))
(ascent (truetype-font-ascent font))
(descent (truetype-font-descent font))
(glyph (zpb-ttf:find-glyph char (zpb-ttf-font-loader
(truetype-font-face font))))
(left-side-bearing (* units->pixels (zpb-ttf:left-side-bearing glyph)))
(right-side-bearing (* units->pixels (zpb-ttf:right-side-bearing glyph)))
(advance-width (* units->pixels (zpb-ttf:advance-width glyph)))
(bounding-box (map 'vector (lambda (x) (float (* x units->pixels)))
(zpb-ttf:bounding-box glyph)))
(min-x (elt bounding-box 0))
(min-y (elt bounding-box 1))
(max-x (elt bounding-box 2))
(max-y (elt bounding-box 3))
(width (- (ceiling max-x) (floor min-x)))
(height (- (ceiling max-y) (floor min-y)))
(paths (paths-ttf:paths-from-glyph glyph
:offset (paths:make-point 0 0)
:scale-x units->pixels
:scale-y (- units->pixels))))
(declare (ignore SIZE ASCENT DESCENT LEFT-SIDE-BEARING RIGHT-SIDE-BEARING))
(values paths
(floor min-x)
(ceiling max-y)
width
height
(round advance-width)
0)))))
|
da46bbc5d60ad505cebf3a37fd83258e6654750d48da7186d3c587286238fe46 | lemonidas/Alan-Compiler | Semantic.ml | open Types
open Identifier
open Symbol
open Printing
open Error
open Lexing
open QuadTypes
(* Semantic checking of values in binary expressions *)
let check_types op_name type_1 type_2 sp ep=
match (type_1, type_2) with
(* Same kind of types in expression are correct *)
|(TYPE_int, TYPE_int)
|(TYPE_byte, TYPE_byte)
-> true
If anything is Type_none a message has allready been created
|(TYPE_int, TYPE_none)
|(TYPE_none, TYPE_int)
|(TYPE_byte, TYPE_none)
|(TYPE_none, TYPE_byte)
-> false
If TYPE_byte is found yield that as the " correct " one
|(TYPE_byte,_ )
|(_, TYPE_byte) ->
print_type_error op_name type_1 type_2 TYPE_byte sp ep;
false
(* Default is to expect Int in expressions *)
|_ ->
print_type_error op_name type_1 type_2 TYPE_int sp ep;
false
(* Semantic checking of entries *)
let check_entry_type lval_t id pos arr =
match lval_t with
Entries can be ints , bytes or arrays
|TYPE_int
|TYPE_byte
|TYPE_array _
-> true
|TYPE_none
-> false
(* Yield an error in case of anything else *)
|_ -> error "Identifier (%s%s) has type %s when int or \
byte was expected, at line %d, position %d"
id arr (string_of_typ lval_t)
(pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
false
(* Semantic check for L-Values *)
let check_lvalue id pos is_array=
(* Extract entry from id *)
let ent = lookupEntry (id_make id) LOOKUP_ALL_SCOPES true in
L - Value must be either a variable or a parameter
let lvalue_type =
match ent.entry_info with
|ENTRY_variable (info) -> info.variable_type
|ENTRY_parameter (info) -> info.parameter_type
|_ ->
error "The identifier (%s) does not correspond to \
a variable or a parameter, at line %d, position %d."
id (pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
TYPE_none in
(* If the lvalue corresponds to an array then extract the inner type *)
if (is_array)
then
match lvalue_type with
|TYPE_array (typ, _) ->
(ent, typ, check_entry_type typ id pos "[_]")
|_ ->
error "The identifier (%s) does not correspond to \
an array, at line %d, position %d."
id (pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
(ent, TYPE_none, false)
else
(ent, lvalue_type, check_entry_type lvalue_type id pos "")
Semantic check of a function Call
* Important : Return parameter is passed as a parameter by reference ,
* therefore expect one more parameter in such a case
* Important: Return parameter is passed as a parameter by reference,
* therefore expect one more parameter in such a case *)
let check_func_call fun_info id param_list pos =
In the tuple , the first argument consists of the parameters of
* the function ( as registered in the symbol table ) and the second
* argument contains the parameters the function call is made with
* the function (as registered in the symbol table) and the second
* argument contains the parameters the function call is made with *)
let rec check_parameters i acc = function
(* Both lists empty simultaneously:
* Correct only for TYPE_proc *)
|([],[]) ->
if (fun_info.function_result = TYPE_proc)
then acc
else (
error "Too many arguments in function call %s() \
in line %d, position %d"
id (pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
false
)
(* Under no circumstances can the parameters called be more *)
|([], _) ->
error "Too many arguments in function call %s() \
in line %d, position %d"
id (pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
false
In case of TYPE_byte or TYPE_int return type then we have
* an extraneous parameter to account for
* an extraneous parameter to account for *)
|([_], []) ->
if (fun_info.function_result = TYPE_byte ||
fun_info.function_result = TYPE_int )
then acc
else (
error "Too few arguments in function call %s() \
in line %d, position %d"
id (pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
false
)
More than 2 arguments less is also invalid
|(_,[]) ->
error "Too few arguments in function call %s() \
in line %d, position %d"
id (pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
false
(* Main recursive case *)
|(h1::t1, h2::t2) -> (
match h1.entry_info with
(* Extract the type of the "correct" parameter *)
|ENTRY_parameter (par_info) ->
(* Check for type correctness *)
if (equalType par_info.parameter_type h2)
(* If semantically correct continue recursing *)
then check_parameters (i+1) acc (t1,t2)
(* Otherwise print an ML-like error message *)
else (
error "Type Mismatch: Argument number %d in \
function call %s() has wrong type:\n\
\tExpected:\t %s\n\
\tFound: \t %s\n\
\tAt line %d.\n"
i id
(string_of_typ (par_info.parameter_type))
(string_of_typ h2)
(pos.pos_lnum);
check_parameters (i+1) false (t1,t2)
)
(* I'd be really surprised if this happens... *)
|_ ->
internal "Function parameter not a parameter???";
raise Terminate
)
in
check_parameters 1 true (fun_info.function_paramlist, param_list)
let check_param_by_reference param id =
match param with
|Quad_entry ent -> (
match ent.entry_info with
| ENTRY_parameter _
| ENTRY_variable _ -> ()
| ENTRY_temporary temp_info -> (
match temp_info.temporary_type with
| TYPE_pointer _ -> ()
| _ -> error "A temporary parameter is passed by reference in function %s" id
)
| _ -> internal "Whut?"; raise Terminate
)
| Quad_valof ent -> ()
| Quad_char ch -> error "A Char (%s) is passed by reference in function %s " ch id
| Quad_string str -> ()
| Quad_int i -> error "A constant (%s) is passed by reference in function %s" i id
| Quad_none -> ()
(* Check that all arrays are passed by reference *)
let check_array_reference id ttype pos =
match ttype with
|TYPE_array (_,_) ->
warning "Invalid parameter: Array (%s) can only be passed by \
reference, at line %d, position %d...Fixing automatically"
id (pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
false;
|_ -> true
Ensure that the first function ( program ) is proc
let check_first_proc ent =
if (equalType !currentScope.sco_ret_type TYPE_proc)
then (
closeScope ent;
)
else (
fatal "Invalid program: Main function must have type proc";
raise Terminate
)
(* Ensure that a function is proc and return its code *)
let check_func_proc func_ret pos =
match func_ret.place with
|Quad_none -> func_ret.code
|Quad_entry(ent) ->
error "Function %s has non-proc return value \
at line %d, position %d."
(id_name ent.entry_id)
(pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
[]
|_ -> internal "Function returns neither entry or proc"; raise Terminate
(* Otherwise ensure the function has a return type and return the code with
* the return location *)
let check_func_expr func_ret pos =
match func_ret.place with
|Quad_entry(_) -> func_ret
|Quad_none ->
error "Function has proc return value and is used as an \
expression at line %d, position %d"
(pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
return_null ()
|_ -> internal "Function returns neither entry or proc"; raise Terminate
| null | https://raw.githubusercontent.com/lemonidas/Alan-Compiler/bbedcbf91028d45a2e26839790df2a1347e8bc52/Semantic.ml | ocaml | Semantic checking of values in binary expressions
Same kind of types in expression are correct
Default is to expect Int in expressions
Semantic checking of entries
Yield an error in case of anything else
Semantic check for L-Values
Extract entry from id
If the lvalue corresponds to an array then extract the inner type
Both lists empty simultaneously:
* Correct only for TYPE_proc
Under no circumstances can the parameters called be more
Main recursive case
Extract the type of the "correct" parameter
Check for type correctness
If semantically correct continue recursing
Otherwise print an ML-like error message
I'd be really surprised if this happens...
Check that all arrays are passed by reference
Ensure that a function is proc and return its code
Otherwise ensure the function has a return type and return the code with
* the return location | open Types
open Identifier
open Symbol
open Printing
open Error
open Lexing
open QuadTypes
let check_types op_name type_1 type_2 sp ep=
match (type_1, type_2) with
|(TYPE_int, TYPE_int)
|(TYPE_byte, TYPE_byte)
-> true
If anything is Type_none a message has allready been created
|(TYPE_int, TYPE_none)
|(TYPE_none, TYPE_int)
|(TYPE_byte, TYPE_none)
|(TYPE_none, TYPE_byte)
-> false
If TYPE_byte is found yield that as the " correct " one
|(TYPE_byte,_ )
|(_, TYPE_byte) ->
print_type_error op_name type_1 type_2 TYPE_byte sp ep;
false
|_ ->
print_type_error op_name type_1 type_2 TYPE_int sp ep;
false
let check_entry_type lval_t id pos arr =
match lval_t with
Entries can be ints , bytes or arrays
|TYPE_int
|TYPE_byte
|TYPE_array _
-> true
|TYPE_none
-> false
|_ -> error "Identifier (%s%s) has type %s when int or \
byte was expected, at line %d, position %d"
id arr (string_of_typ lval_t)
(pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
false
let check_lvalue id pos is_array=
let ent = lookupEntry (id_make id) LOOKUP_ALL_SCOPES true in
L - Value must be either a variable or a parameter
let lvalue_type =
match ent.entry_info with
|ENTRY_variable (info) -> info.variable_type
|ENTRY_parameter (info) -> info.parameter_type
|_ ->
error "The identifier (%s) does not correspond to \
a variable or a parameter, at line %d, position %d."
id (pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
TYPE_none in
if (is_array)
then
match lvalue_type with
|TYPE_array (typ, _) ->
(ent, typ, check_entry_type typ id pos "[_]")
|_ ->
error "The identifier (%s) does not correspond to \
an array, at line %d, position %d."
id (pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
(ent, TYPE_none, false)
else
(ent, lvalue_type, check_entry_type lvalue_type id pos "")
Semantic check of a function Call
* Important : Return parameter is passed as a parameter by reference ,
* therefore expect one more parameter in such a case
* Important: Return parameter is passed as a parameter by reference,
* therefore expect one more parameter in such a case *)
let check_func_call fun_info id param_list pos =
In the tuple , the first argument consists of the parameters of
* the function ( as registered in the symbol table ) and the second
* argument contains the parameters the function call is made with
* the function (as registered in the symbol table) and the second
* argument contains the parameters the function call is made with *)
let rec check_parameters i acc = function
|([],[]) ->
if (fun_info.function_result = TYPE_proc)
then acc
else (
error "Too many arguments in function call %s() \
in line %d, position %d"
id (pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
false
)
|([], _) ->
error "Too many arguments in function call %s() \
in line %d, position %d"
id (pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
false
In case of TYPE_byte or TYPE_int return type then we have
* an extraneous parameter to account for
* an extraneous parameter to account for *)
|([_], []) ->
if (fun_info.function_result = TYPE_byte ||
fun_info.function_result = TYPE_int )
then acc
else (
error "Too few arguments in function call %s() \
in line %d, position %d"
id (pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
false
)
More than 2 arguments less is also invalid
|(_,[]) ->
error "Too few arguments in function call %s() \
in line %d, position %d"
id (pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
false
|(h1::t1, h2::t2) -> (
match h1.entry_info with
|ENTRY_parameter (par_info) ->
if (equalType par_info.parameter_type h2)
then check_parameters (i+1) acc (t1,t2)
else (
error "Type Mismatch: Argument number %d in \
function call %s() has wrong type:\n\
\tExpected:\t %s\n\
\tFound: \t %s\n\
\tAt line %d.\n"
i id
(string_of_typ (par_info.parameter_type))
(string_of_typ h2)
(pos.pos_lnum);
check_parameters (i+1) false (t1,t2)
)
|_ ->
internal "Function parameter not a parameter???";
raise Terminate
)
in
check_parameters 1 true (fun_info.function_paramlist, param_list)
let check_param_by_reference param id =
match param with
|Quad_entry ent -> (
match ent.entry_info with
| ENTRY_parameter _
| ENTRY_variable _ -> ()
| ENTRY_temporary temp_info -> (
match temp_info.temporary_type with
| TYPE_pointer _ -> ()
| _ -> error "A temporary parameter is passed by reference in function %s" id
)
| _ -> internal "Whut?"; raise Terminate
)
| Quad_valof ent -> ()
| Quad_char ch -> error "A Char (%s) is passed by reference in function %s " ch id
| Quad_string str -> ()
| Quad_int i -> error "A constant (%s) is passed by reference in function %s" i id
| Quad_none -> ()
let check_array_reference id ttype pos =
match ttype with
|TYPE_array (_,_) ->
warning "Invalid parameter: Array (%s) can only be passed by \
reference, at line %d, position %d...Fixing automatically"
id (pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
false;
|_ -> true
Ensure that the first function ( program ) is proc
let check_first_proc ent =
if (equalType !currentScope.sco_ret_type TYPE_proc)
then (
closeScope ent;
)
else (
fatal "Invalid program: Main function must have type proc";
raise Terminate
)
let check_func_proc func_ret pos =
match func_ret.place with
|Quad_none -> func_ret.code
|Quad_entry(ent) ->
error "Function %s has non-proc return value \
at line %d, position %d."
(id_name ent.entry_id)
(pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
[]
|_ -> internal "Function returns neither entry or proc"; raise Terminate
let check_func_expr func_ret pos =
match func_ret.place with
|Quad_entry(_) -> func_ret
|Quad_none ->
error "Function has proc return value and is used as an \
expression at line %d, position %d"
(pos.pos_lnum) (pos.pos_cnum - pos.pos_bol);
return_null ()
|_ -> internal "Function returns neither entry or proc"; raise Terminate
|
42b1de43a2fe2c72485eda07a3ff97e7f1343df94e0b1ab93f1d9e758515d59d | Chris00/ocaml-interval | precision.ml | (* Ill conditioned function *)
open Interval_base
let f_I x y =
I.(333.75 *. y**6
+ x**2 * (11. *. x**2 * y**2 - y**6 - 121. *. y**4 -. 2.0)
+ 5.5 *. y**8
+ x / (2. *. y))
let f x y =
333.75 *. y**6.
+. x**2. *. (11.0 *. x**2. *. y**2. -. y**6. -. 121. *. y**4. -. 2.0)
+. 5.5 *. y**8.0
+. x /. (2. *. y)
let g u v =
Printf.printf "Computing f(%f, %f)\n" u v;
let a = I.v u u and b = I.v v v in
let x = f u v in
let y = f_I a b in
Printf.printf "f(x,y) = %e\nf(I) = %a\n" x I.pr y;
let err = 100.0 *. I.width_up y /. (abs_float x) in
Printf.printf "error (in percent) = %e\n" err;
print_newline();;
let () =
g 77617.0 33095.999;
g 77617.0 33096.001;
g 77617.0 33096.0
| null | https://raw.githubusercontent.com/Chris00/ocaml-interval/69a8587bc98070bf27bd6d2d2d82457829fc7b0d/examples/precision.ml | ocaml | Ill conditioned function |
open Interval_base
let f_I x y =
I.(333.75 *. y**6
+ x**2 * (11. *. x**2 * y**2 - y**6 - 121. *. y**4 -. 2.0)
+ 5.5 *. y**8
+ x / (2. *. y))
let f x y =
333.75 *. y**6.
+. x**2. *. (11.0 *. x**2. *. y**2. -. y**6. -. 121. *. y**4. -. 2.0)
+. 5.5 *. y**8.0
+. x /. (2. *. y)
let g u v =
Printf.printf "Computing f(%f, %f)\n" u v;
let a = I.v u u and b = I.v v v in
let x = f u v in
let y = f_I a b in
Printf.printf "f(x,y) = %e\nf(I) = %a\n" x I.pr y;
let err = 100.0 *. I.width_up y /. (abs_float x) in
Printf.printf "error (in percent) = %e\n" err;
print_newline();;
let () =
g 77617.0 33095.999;
g 77617.0 33096.001;
g 77617.0 33096.0
|
f11dfc287d8eef271799b94da63c2b2e427753fff0b2b57607181d09d5ad2726 | choener/ADPfusion | Common.hs |
module BenchFun.Common where
import Data.Vector.Fusion.Stream.Monadic as S
import Data.Vector.Fusion.Util
import Data.Vector.Unboxed as VU
import Debug.Trace
import Data.Char (ord)
import ADP.Fusion.Point
import Data.PrimitiveArray hiding (map, unsafeIndex)
-- * * Epsilon
stream_Epsilon_S : : Int - > Int
stream_Epsilon_S k = unId $ ( f < < < Epsilon ... h ) ( pointLI 10 ) ( pointLI k )
where f _ = 100099 : : Int
h = S.foldl ' max 100011
{ - # NoInline stream_Epsilon_S #
-- ** Epsilon
stream_Epsilon_S :: Int -> Int
stream_Epsilon_S k = unId $ (f <<< Epsilon ... h) (pointLI 10) (pointLI k)
where f _ = 100099 :: Int
h = S.foldl' max 100011
{-# NoInline stream_Epsilon_S #-}
stream_Epsilon_V :: Int -> Int
stream_Epsilon_V k = unId $ (f <<< (M:|Epsilon:|Epsilon) ... h) (Z:.pointLI 10:.pointLI 10) (Z:.pointLI k:.pointLI k)
where f _ = 100099 :: Int
h = S.foldl' max 100011
# NoInline stream_Epsilon_V #
-}
* *
v1 = VU.fromList "ACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGU1"
v2 = VU.fromList "ACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGU2"
v3 = VU.fromList "ACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGU3"
v4 = VU.fromList "ACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGU4"
# NoInline v1 #
# NoInline v2 #
# NoInline v3 #
# NoInline v4 #
stream_Chr_S : : Int - > Int
stream_Chr_S k = seq v1 $ unId $ ( f < < < chr v1 ... h ) ( pointLI 10 ) ( pointLI k )
where f p = ord p + 100099 : : Int
h = S.foldl ' max 100011
{ - # NoInline stream_Chr_S #
stream_Chr_S :: Int -> Int
stream_Chr_S k = seq v1 $ unId $ (f <<< chr v1 ... h) (pointLI 10) (pointLI k)
where f p = ord p + 100099 :: Int
h = S.foldl' max 100011
{-# NoInline stream_Chr_S #-}
stream_Chr_V :: Int -> Int
stream_Chr_V k = seq v1 $ seq v2 $ unId $ (f <<< (M:|chr v1:|chr v2) ... h) (Z:.pointLI 10:.pointLI 10) (Z:.pointLI k:.pointLI k)
where f (Z:.p:.q) = ord p + ord q + 100099 :: Int
h = S.foldl' max 100011
# NoInline stream_Chr_V #
-- **
stream_Strng_S :: Int -> Int
stream_Strng_S k = seq v1 $ unId $ (f <<< Strng v1 ... h) (pointLI 10) (pointLI k)
where f zs = VU.sum (VU.map ord zs)
h = S.foldl' (+) 0
# NoInline stream_Strng_S #
stream_Strng_V :: Int -> Int
stream_Strng_V k = seq v1 $ seq v2 $ unId $ (f <<< (M:|Strng v1:|Strng v2) ... h)
(Z:.pointLI 10:.pointLI 10) (Z:.pointLI k:.pointLI k)
where f (Z:.zs:.qs) = VU.sum (VU.map ord zs VU.++ VU.map ord qs)
h = S.foldl' (+) 0
# NoInline stream_Strng_V #
stream_Strng2_S :: Int -> Int
stream_Strng2_S k = seq v1 $ seq v2 $
unId $ (f <<< Strng v1 % Strng v2 ... h)
(pointLI 10) (pointLI k)
VU.sum ( VU.map ord qs VU.++ VU.map ord zs )
h = S.foldl' (+) 0
# NoInline stream_Strng2_S #
-}
| null | https://raw.githubusercontent.com/choener/ADPfusion/fcbbf05d0f438883928077e3d8a7f1cbf8c2e58d/tests/BenchFun/Common.hs | haskell | * * Epsilon
** Epsilon
# NoInline stream_Epsilon_S #
# NoInline stream_Chr_S #
** |
module BenchFun.Common where
import Data.Vector.Fusion.Stream.Monadic as S
import Data.Vector.Fusion.Util
import Data.Vector.Unboxed as VU
import Debug.Trace
import Data.Char (ord)
import ADP.Fusion.Point
import Data.PrimitiveArray hiding (map, unsafeIndex)
stream_Epsilon_S : : Int - > Int
stream_Epsilon_S k = unId $ ( f < < < Epsilon ... h ) ( pointLI 10 ) ( pointLI k )
where f _ = 100099 : : Int
h = S.foldl ' max 100011
{ - # NoInline stream_Epsilon_S #
stream_Epsilon_S :: Int -> Int
stream_Epsilon_S k = unId $ (f <<< Epsilon ... h) (pointLI 10) (pointLI k)
where f _ = 100099 :: Int
h = S.foldl' max 100011
stream_Epsilon_V :: Int -> Int
stream_Epsilon_V k = unId $ (f <<< (M:|Epsilon:|Epsilon) ... h) (Z:.pointLI 10:.pointLI 10) (Z:.pointLI k:.pointLI k)
where f _ = 100099 :: Int
h = S.foldl' max 100011
# NoInline stream_Epsilon_V #
-}
* *
v1 = VU.fromList "ACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGU1"
v2 = VU.fromList "ACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGU2"
v3 = VU.fromList "ACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGU3"
v4 = VU.fromList "ACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGUACGU4"
# NoInline v1 #
# NoInline v2 #
# NoInline v3 #
# NoInline v4 #
stream_Chr_S : : Int - > Int
stream_Chr_S k = seq v1 $ unId $ ( f < < < chr v1 ... h ) ( pointLI 10 ) ( pointLI k )
where f p = ord p + 100099 : : Int
h = S.foldl ' max 100011
{ - # NoInline stream_Chr_S #
stream_Chr_S :: Int -> Int
stream_Chr_S k = seq v1 $ unId $ (f <<< chr v1 ... h) (pointLI 10) (pointLI k)
where f p = ord p + 100099 :: Int
h = S.foldl' max 100011
stream_Chr_V :: Int -> Int
stream_Chr_V k = seq v1 $ seq v2 $ unId $ (f <<< (M:|chr v1:|chr v2) ... h) (Z:.pointLI 10:.pointLI 10) (Z:.pointLI k:.pointLI k)
where f (Z:.p:.q) = ord p + ord q + 100099 :: Int
h = S.foldl' max 100011
# NoInline stream_Chr_V #
stream_Strng_S :: Int -> Int
stream_Strng_S k = seq v1 $ unId $ (f <<< Strng v1 ... h) (pointLI 10) (pointLI k)
where f zs = VU.sum (VU.map ord zs)
h = S.foldl' (+) 0
# NoInline stream_Strng_S #
stream_Strng_V :: Int -> Int
stream_Strng_V k = seq v1 $ seq v2 $ unId $ (f <<< (M:|Strng v1:|Strng v2) ... h)
(Z:.pointLI 10:.pointLI 10) (Z:.pointLI k:.pointLI k)
where f (Z:.zs:.qs) = VU.sum (VU.map ord zs VU.++ VU.map ord qs)
h = S.foldl' (+) 0
# NoInline stream_Strng_V #
stream_Strng2_S :: Int -> Int
stream_Strng2_S k = seq v1 $ seq v2 $
unId $ (f <<< Strng v1 % Strng v2 ... h)
(pointLI 10) (pointLI k)
VU.sum ( VU.map ord qs VU.++ VU.map ord zs )
h = S.foldl' (+) 0
# NoInline stream_Strng2_S #
-}
|
0398996f26f8e2fef74606de207386db929ef8f24dd43ae3c523862556b06131 | serokell/qtah | QMenuBar.hs | This file is part of Qtah .
--
Copyright 2015 - 2018 The Qtah Authors .
--
-- 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 , either version 3 of the License , or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details .
--
You should have received a copy of the GNU Lesser General Public License
-- along with this program. If not, see </>.
module Graphics.UI.Qtah.Generator.Interface.Widgets.QMenuBar (
aModule,
c_QMenuBar,
) where
import Foreign.Hoppy.Generator.Spec (
Export (ExportClass),
addReqIncludes,
classSetEntityPrefix,
ident,
includeStd,
makeClass,
mkBoolIsProp,
mkConstMethod,
mkCtor,
mkMethod,
mkMethod',
mkProp,
)
import Foreign.Hoppy.Generator.Types (enumT, objT, ptrT, voidT)
import Foreign.Hoppy.Generator.Version (collect, just, test)
import Graphics.UI.Qtah.Generator.Flags (wsWince)
import Graphics.UI.Qtah.Generator.Interface.Core.QPoint (c_QPoint)
import Graphics.UI.Qtah.Generator.Interface.Core.QRect (c_QRect)
import Graphics.UI.Qtah.Generator.Interface.Core.QString (c_QString)
import Graphics.UI.Qtah.Generator.Interface.Core.Types (e_Corner)
import Graphics.UI.Qtah.Generator.Interface.Gui.QIcon (c_QIcon)
import Graphics.UI.Qtah.Generator.Interface.Internal.Listener (c_ListenerPtrQAction)
import Graphics.UI.Qtah.Generator.Interface.Widgets.QAction (c_QAction)
import Graphics.UI.Qtah.Generator.Interface.Widgets.QMenu (c_QMenu)
import Graphics.UI.Qtah.Generator.Interface.Widgets.QWidget (c_QWidget)
import Graphics.UI.Qtah.Generator.Module (AModule (AQtModule), makeQtModule)
import Graphics.UI.Qtah.Generator.Types
aModule =
AQtModule $
makeQtModule ["Widgets", "QMenuBar"] $
QtExport (ExportClass c_QMenuBar) :
map QtExportSignal signals
c_QMenuBar =
addReqIncludes [includeStd "QMenuBar"] $
classSetEntityPrefix "" $
makeClass (ident "QMenuBar") Nothing [c_QWidget] $
collect
[ just $ mkCtor "new" []
, just $ mkCtor "newWithParent" [ptrT $ objT c_QWidget]
, just $ mkConstMethod "actionAt" [objT c_QPoint] $ ptrT $ objT c_QAction
, just $ mkConstMethod "actionGeometry" [ptrT $ objT c_QAction] $ objT c_QRect
, just $ mkProp "activeAction" $ ptrT $ objT c_QAction
, just $ mkMethod' "addAction" "addAction" [ptrT $ objT c_QAction] voidT
, just $ mkMethod' "addAction" "addNewAction" [objT c_QString] $ ptrT $ objT c_QAction
, just $ mkMethod' "addMenu" "addMenu" [ptrT $ objT c_QMenu] $ ptrT $ objT c_QAction
, just $ mkMethod' "addMenu" "addNewMenu" [objT c_QString] $ ptrT $ objT c_QMenu
, just $ mkMethod' "addMenu" "addNewMenuWithIcon" [objT c_QIcon, objT c_QString] $
ptrT $ objT c_QMenu
, just $ mkMethod "addSeparator" [] $ ptrT $ objT c_QAction
, just $ mkMethod "clear" [] voidT
, just $ mkConstMethod "cornerWidget" [enumT e_Corner] $ ptrT $ objT c_QWidget
, test wsWince $ mkProp "defaultAction" $ ptrT $ objT c_QAction
, just $ mkBoolIsProp "defaultUp"
, just $
mkMethod "insertMenu" [ptrT $ objT c_QAction, ptrT $ objT c_QMenu] $ ptrT $ objT c_QAction
, just $ mkMethod "insertSeparator" [ptrT $ objT c_QAction] $ ptrT $ objT c_QAction
, just $ mkBoolIsProp "nativeMenuBar"
, just $ mkMethod "setCornerWidget" [ptrT $ objT c_QWidget, enumT e_Corner] voidT
]
signals =
[ makeSignal c_QMenuBar "hovered" c_ListenerPtrQAction
, makeSignal c_QMenuBar "triggered" c_ListenerPtrQAction
]
| null | https://raw.githubusercontent.com/serokell/qtah/abb4932248c82dc5c662a20d8f177acbc7cfa722/qtah-generator/src/Graphics/UI/Qtah/Generator/Interface/Widgets/QMenuBar.hs | haskell |
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
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see </>. | This file is part of Qtah .
Copyright 2015 - 2018 The Qtah Authors .
the Free Software Foundation , either version 3 of the License , or
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
module Graphics.UI.Qtah.Generator.Interface.Widgets.QMenuBar (
aModule,
c_QMenuBar,
) where
import Foreign.Hoppy.Generator.Spec (
Export (ExportClass),
addReqIncludes,
classSetEntityPrefix,
ident,
includeStd,
makeClass,
mkBoolIsProp,
mkConstMethod,
mkCtor,
mkMethod,
mkMethod',
mkProp,
)
import Foreign.Hoppy.Generator.Types (enumT, objT, ptrT, voidT)
import Foreign.Hoppy.Generator.Version (collect, just, test)
import Graphics.UI.Qtah.Generator.Flags (wsWince)
import Graphics.UI.Qtah.Generator.Interface.Core.QPoint (c_QPoint)
import Graphics.UI.Qtah.Generator.Interface.Core.QRect (c_QRect)
import Graphics.UI.Qtah.Generator.Interface.Core.QString (c_QString)
import Graphics.UI.Qtah.Generator.Interface.Core.Types (e_Corner)
import Graphics.UI.Qtah.Generator.Interface.Gui.QIcon (c_QIcon)
import Graphics.UI.Qtah.Generator.Interface.Internal.Listener (c_ListenerPtrQAction)
import Graphics.UI.Qtah.Generator.Interface.Widgets.QAction (c_QAction)
import Graphics.UI.Qtah.Generator.Interface.Widgets.QMenu (c_QMenu)
import Graphics.UI.Qtah.Generator.Interface.Widgets.QWidget (c_QWidget)
import Graphics.UI.Qtah.Generator.Module (AModule (AQtModule), makeQtModule)
import Graphics.UI.Qtah.Generator.Types
aModule =
AQtModule $
makeQtModule ["Widgets", "QMenuBar"] $
QtExport (ExportClass c_QMenuBar) :
map QtExportSignal signals
c_QMenuBar =
addReqIncludes [includeStd "QMenuBar"] $
classSetEntityPrefix "" $
makeClass (ident "QMenuBar") Nothing [c_QWidget] $
collect
[ just $ mkCtor "new" []
, just $ mkCtor "newWithParent" [ptrT $ objT c_QWidget]
, just $ mkConstMethod "actionAt" [objT c_QPoint] $ ptrT $ objT c_QAction
, just $ mkConstMethod "actionGeometry" [ptrT $ objT c_QAction] $ objT c_QRect
, just $ mkProp "activeAction" $ ptrT $ objT c_QAction
, just $ mkMethod' "addAction" "addAction" [ptrT $ objT c_QAction] voidT
, just $ mkMethod' "addAction" "addNewAction" [objT c_QString] $ ptrT $ objT c_QAction
, just $ mkMethod' "addMenu" "addMenu" [ptrT $ objT c_QMenu] $ ptrT $ objT c_QAction
, just $ mkMethod' "addMenu" "addNewMenu" [objT c_QString] $ ptrT $ objT c_QMenu
, just $ mkMethod' "addMenu" "addNewMenuWithIcon" [objT c_QIcon, objT c_QString] $
ptrT $ objT c_QMenu
, just $ mkMethod "addSeparator" [] $ ptrT $ objT c_QAction
, just $ mkMethod "clear" [] voidT
, just $ mkConstMethod "cornerWidget" [enumT e_Corner] $ ptrT $ objT c_QWidget
, test wsWince $ mkProp "defaultAction" $ ptrT $ objT c_QAction
, just $ mkBoolIsProp "defaultUp"
, just $
mkMethod "insertMenu" [ptrT $ objT c_QAction, ptrT $ objT c_QMenu] $ ptrT $ objT c_QAction
, just $ mkMethod "insertSeparator" [ptrT $ objT c_QAction] $ ptrT $ objT c_QAction
, just $ mkBoolIsProp "nativeMenuBar"
, just $ mkMethod "setCornerWidget" [ptrT $ objT c_QWidget, enumT e_Corner] voidT
]
signals =
[ makeSignal c_QMenuBar "hovered" c_ListenerPtrQAction
, makeSignal c_QMenuBar "triggered" c_ListenerPtrQAction
]
|
558ddba7d50c66748e84b25923b34dcfd9ba85a9ae828e57bea567a75cf53e1f | JacquesCarette/Drasil | HelloWorld.hs | # LANGUAGE PostfixOperators #
| GOOL test program for various OO program functionality .
-- Should run print statements, basic loops, math, and create a helper module without errors.
module HelloWorld (helloWorld) where
import GOOL.Drasil (GSProgram, MSBody, MSBlock, MSStatement, SMethod, OOProg,
ProgramSym(..), FileSym(..), BodySym(..), bodyStatements, oneLiner,
BlockSym(..), listSlice, TypeSym(..), StatementSym(..), AssignStatement(..), (&=),
DeclStatement(..), IOStatement(..), StringStatement(..), CommentStatement(..), ControlStatement(..),
VariableSym(..), listVar, Literal(..), VariableValue(..), CommandLineArgs(..), NumericExpression(..), BooleanExpression(..), Comparison(..),
ValueExpression(..), extFuncApp, List(..),
MethodSym(..), ModuleSym(..))
import Prelude hiding (return,print,log,exp,sin,cos,tan,const)
import Helper (helper)
| Creates the HelloWorld program and necessary files .
helloWorld :: (OOProg r) => GSProgram r
helloWorld = prog "HelloWorld" [docMod description
["Brooks MacLachlan"] "" $ fileDoc (buildModule "HelloWorld" []
[helloWorldMain] []), helper]
-- | Description of program.
description :: String
description = "Tests various GOOL functions. It should run without errors."
-- | Main function. Initializes variables and combines all the helper functions defined below.
helloWorldMain :: (OOProg r) => SMethod r
helloWorldMain = mainFunction (body [ helloInitVariables,
helloListSlice,
block [ifCond [(valueOf (var "b" int) ?>= litInt 6, bodyStatements [varDecDef (var "dummy" string) (litString "dummy")]),
(valueOf (var "b" int) ?== litInt 5, helloIfBody)] helloElseBody, helloIfExists,
helloSwitch, helloForLoop, helloWhileLoop, helloForEachLoop, helloTryCatch]])
-- | Initialize variables used in the generated program.
helloInitVariables :: (OOProg r) => MSBlock r
helloInitVariables = block [comment "Initializing variables",
varDec $ var "a" int,
varDecDef (var "b" int) (litInt 5),
listDecDef (var "myOtherList" (listType double)) [litDouble 1.0,
litDouble 1.5],
varDecDef (var "oneIndex" int) (indexOf (valueOf $ var "myOtherList"
(listType double)) (litDouble 1.0)),
printLn (valueOf $ var "oneIndex" int),
var "a" int &= listSize (valueOf $ var "myOtherList" (listType double)),
valStmt (listAdd (valueOf $ var "myOtherList" (listType double))
(litInt 2) (litDouble 2.0)),
valStmt (listAppend (valueOf $ var "myOtherList" (listType double))
(litDouble 2.5)),
varDec $ var "e" double,
var "e" int &= listAccess (valueOf $ var "myOtherList"
(listType double)) (litInt 1),
valStmt (listSet (valueOf $ var "myOtherList" (listType double))
(litInt 1) (litDouble 17.4)),
listDec 7 (var "myName" (listType string)),
stringSplit ' ' (var "myName" (listType string)) (litString "Brooks Mac"),
printLn (valueOf $ var "myName" (listType string)),
listDecDef (var "boringList" (listType bool))
[litFalse, litFalse, litFalse, litFalse, litFalse],
printLn (valueOf $ var "boringList" (listType bool)),
listDec 2 $ var "mySlicedList" (listType double)]
-- | Initialize and assign a value to a new variable @mySlicedList@.
helloListSlice :: (OOProg r) => MSBlock r
helloListSlice = listSlice (var "mySlicedList" (listType double))
(valueOf $ var "myOtherList" (listType double)) (Just (litInt 1))
(Just (litInt 3)) Nothing
-- | Create an If statement.
{-# ANN module "HLint: ignore Evaluate" #-}
helloIfBody :: (OOProg r) => MSBody r
helloIfBody = addComments "If body" (body [
block [
varDec $ var "c" int,
varDec $ var "d" int,
assign (var "a" int) (litInt 5),
var "b" int &= (valueOf (var "a" int) #+ litInt 2),
var "c" int &= (valueOf (var "b" int) #+ litInt 3),
var "d" int &= valueOf (var "b" int),
var "d" int &-= valueOf (var "a" int),
var "c" int &-= valueOf (var "d" int),
var "b" int &+= litInt 17,
var "c" int &+= litInt 17,
(&++) (var "a" int),
(&++) (var "d" int),
(&--) (var "c" int),
(&--) (var "b" int),
listDec 5 (var "myList" (listType int)),
objDecDef (var "myObj" char) (litChar 'o'),
constDecDef (const "myConst" string) (litString "Imconstant"),
printLn (valueOf $ var "a" int),
printLn (valueOf $ var "b" int),
printLn (valueOf $ var "c" int),
printLn (valueOf $ var "d" int),
printLn (valueOf $ var "myOtherList" (listType double)),
printLn (valueOf $ var "mySlicedList" (listType double)),
printStrLn "Type an int",
getInput (var "d" int),
printStrLn "Type another",
discardInput],
block [
printLn (litString " too"),
printStr "boo",
print litTrue,
print (litInt 0),
print (litChar 'c'),
printLn (litTrue ?!),
printLn (litInt 1 #~),
printLn (litDouble 4.0 #/^),
printLn (litInt (-4) #|),
printLn (log (litDouble 2.0)),
multi [printLn (ln (litDouble 2.0)),
printLn (exp (litDouble 2.0 #~)),
printLn (sin (litDouble 2.0)),
printLn (cos (litDouble 2.0)),
printLn (tan (litDouble 2.0))],
printLn (tan (litDouble 2.0)),
printLn (litTrue ?&& litFalse),
printLn (litTrue ?|| litFalse),
printLn (litTrue ?&& (litFalse ?!)),
printLn ((litTrue ?&& litTrue) ?!),
printLn (litInt 6 #+ litInt 2),
printLn (litInt 6 #- litInt 2),
printLn (litInt 6 #* litInt 2),
printLn (litInt 6 #/ litInt 2),
printLn (litInt 6 #% litInt 4),
printLn (litInt 6 #^ litInt 2),
printLn (litInt 6 #+ (litInt 2 #* litInt 3)),
printLn (csc (litDouble 1.0)),
printLn (sec (litDouble 1.0)),
printLn (valueOf $ var "a" int),
printLn (inlineIf litTrue (litInt 5) (litInt 0)),
printLn (cot (litDouble 1.0))]])
| Print the 5th given argument .
helloElseBody :: (OOProg r) => MSBody r
helloElseBody = bodyStatements [printLn (arg 5)]
-- | If-else statement checking if a list is empty.
helloIfExists :: (OOProg r) => MSStatement r
helloIfExists = ifExists (valueOf $ var "boringList" (listType bool))
(oneLiner (printStrLn "Ew, boring list!")) (oneLiner (printStrLn "Great, no bores!"))
-- | Creates a switch statement.
helloSwitch :: (OOProg r) => MSStatement r
helloSwitch = switch (valueOf $ var "a" int) [(litInt 5, oneLiner (var "b" int &= litInt 10)),
(litInt 0, oneLiner (var "b" int &= litInt 5))]
(oneLiner (var "b" int &= litInt 0))
-- | Creates a for loop.
helloForLoop :: (OOProg r) => MSStatement r
helloForLoop = forRange i (litInt 0) (litInt 9) (litInt 1) (oneLiner (printLn
(valueOf i)))
where i = var "i" int
-- | Creates a while loop.
helloWhileLoop :: (OOProg r) => MSStatement r
helloWhileLoop = while (valueOf (var "a" int) ?< litInt 13) (bodyStatements
[printStrLn "Hello", (&++) (var "a" int)])
-- | Creates a for-each loop.
helloForEachLoop :: (OOProg r) => MSStatement r
helloForEachLoop = forEach i (valueOf $ listVar "myOtherList" double)
(oneLiner (printLn (extFuncApp "Helper" "doubleAndAdd" double [valueOf i,
litDouble 1.0])))
where i = var "num" double
-- | Creates a try statement to catch an intentional error.
helloTryCatch :: (OOProg r) => MSStatement r
helloTryCatch = tryCatch (oneLiner (throw "Good-bye!"))
(oneLiner (printStrLn "Caught intentional error"))
| null | https://raw.githubusercontent.com/JacquesCarette/Drasil/adfc15f13c7cf81101c1dbab97a6aa61f10a4ec6/code/drasil-code/test/HelloWorld.hs | haskell | Should run print statements, basic loops, math, and create a helper module without errors.
| Description of program.
| Main function. Initializes variables and combines all the helper functions defined below.
| Initialize variables used in the generated program.
| Initialize and assign a value to a new variable @mySlicedList@.
| Create an If statement.
# ANN module "HLint: ignore Evaluate" #
) (var "c" int),
) (var "b" int),
| If-else statement checking if a list is empty.
| Creates a switch statement.
| Creates a for loop.
| Creates a while loop.
| Creates a for-each loop.
| Creates a try statement to catch an intentional error. | # LANGUAGE PostfixOperators #
| GOOL test program for various OO program functionality .
module HelloWorld (helloWorld) where
import GOOL.Drasil (GSProgram, MSBody, MSBlock, MSStatement, SMethod, OOProg,
ProgramSym(..), FileSym(..), BodySym(..), bodyStatements, oneLiner,
BlockSym(..), listSlice, TypeSym(..), StatementSym(..), AssignStatement(..), (&=),
DeclStatement(..), IOStatement(..), StringStatement(..), CommentStatement(..), ControlStatement(..),
VariableSym(..), listVar, Literal(..), VariableValue(..), CommandLineArgs(..), NumericExpression(..), BooleanExpression(..), Comparison(..),
ValueExpression(..), extFuncApp, List(..),
MethodSym(..), ModuleSym(..))
import Prelude hiding (return,print,log,exp,sin,cos,tan,const)
import Helper (helper)
| Creates the HelloWorld program and necessary files .
helloWorld :: (OOProg r) => GSProgram r
helloWorld = prog "HelloWorld" [docMod description
["Brooks MacLachlan"] "" $ fileDoc (buildModule "HelloWorld" []
[helloWorldMain] []), helper]
description :: String
description = "Tests various GOOL functions. It should run without errors."
helloWorldMain :: (OOProg r) => SMethod r
helloWorldMain = mainFunction (body [ helloInitVariables,
helloListSlice,
block [ifCond [(valueOf (var "b" int) ?>= litInt 6, bodyStatements [varDecDef (var "dummy" string) (litString "dummy")]),
(valueOf (var "b" int) ?== litInt 5, helloIfBody)] helloElseBody, helloIfExists,
helloSwitch, helloForLoop, helloWhileLoop, helloForEachLoop, helloTryCatch]])
helloInitVariables :: (OOProg r) => MSBlock r
helloInitVariables = block [comment "Initializing variables",
varDec $ var "a" int,
varDecDef (var "b" int) (litInt 5),
listDecDef (var "myOtherList" (listType double)) [litDouble 1.0,
litDouble 1.5],
varDecDef (var "oneIndex" int) (indexOf (valueOf $ var "myOtherList"
(listType double)) (litDouble 1.0)),
printLn (valueOf $ var "oneIndex" int),
var "a" int &= listSize (valueOf $ var "myOtherList" (listType double)),
valStmt (listAdd (valueOf $ var "myOtherList" (listType double))
(litInt 2) (litDouble 2.0)),
valStmt (listAppend (valueOf $ var "myOtherList" (listType double))
(litDouble 2.5)),
varDec $ var "e" double,
var "e" int &= listAccess (valueOf $ var "myOtherList"
(listType double)) (litInt 1),
valStmt (listSet (valueOf $ var "myOtherList" (listType double))
(litInt 1) (litDouble 17.4)),
listDec 7 (var "myName" (listType string)),
stringSplit ' ' (var "myName" (listType string)) (litString "Brooks Mac"),
printLn (valueOf $ var "myName" (listType string)),
listDecDef (var "boringList" (listType bool))
[litFalse, litFalse, litFalse, litFalse, litFalse],
printLn (valueOf $ var "boringList" (listType bool)),
listDec 2 $ var "mySlicedList" (listType double)]
helloListSlice :: (OOProg r) => MSBlock r
helloListSlice = listSlice (var "mySlicedList" (listType double))
(valueOf $ var "myOtherList" (listType double)) (Just (litInt 1))
(Just (litInt 3)) Nothing
helloIfBody :: (OOProg r) => MSBody r
helloIfBody = addComments "If body" (body [
block [
varDec $ var "c" int,
varDec $ var "d" int,
assign (var "a" int) (litInt 5),
var "b" int &= (valueOf (var "a" int) #+ litInt 2),
var "c" int &= (valueOf (var "b" int) #+ litInt 3),
var "d" int &= valueOf (var "b" int),
var "d" int &-= valueOf (var "a" int),
var "c" int &-= valueOf (var "d" int),
var "b" int &+= litInt 17,
var "c" int &+= litInt 17,
(&++) (var "a" int),
(&++) (var "d" int),
listDec 5 (var "myList" (listType int)),
objDecDef (var "myObj" char) (litChar 'o'),
constDecDef (const "myConst" string) (litString "Imconstant"),
printLn (valueOf $ var "a" int),
printLn (valueOf $ var "b" int),
printLn (valueOf $ var "c" int),
printLn (valueOf $ var "d" int),
printLn (valueOf $ var "myOtherList" (listType double)),
printLn (valueOf $ var "mySlicedList" (listType double)),
printStrLn "Type an int",
getInput (var "d" int),
printStrLn "Type another",
discardInput],
block [
printLn (litString " too"),
printStr "boo",
print litTrue,
print (litInt 0),
print (litChar 'c'),
printLn (litTrue ?!),
printLn (litInt 1 #~),
printLn (litDouble 4.0 #/^),
printLn (litInt (-4) #|),
printLn (log (litDouble 2.0)),
multi [printLn (ln (litDouble 2.0)),
printLn (exp (litDouble 2.0 #~)),
printLn (sin (litDouble 2.0)),
printLn (cos (litDouble 2.0)),
printLn (tan (litDouble 2.0))],
printLn (tan (litDouble 2.0)),
printLn (litTrue ?&& litFalse),
printLn (litTrue ?|| litFalse),
printLn (litTrue ?&& (litFalse ?!)),
printLn ((litTrue ?&& litTrue) ?!),
printLn (litInt 6 #+ litInt 2),
printLn (litInt 6 #- litInt 2),
printLn (litInt 6 #* litInt 2),
printLn (litInt 6 #/ litInt 2),
printLn (litInt 6 #% litInt 4),
printLn (litInt 6 #^ litInt 2),
printLn (litInt 6 #+ (litInt 2 #* litInt 3)),
printLn (csc (litDouble 1.0)),
printLn (sec (litDouble 1.0)),
printLn (valueOf $ var "a" int),
printLn (inlineIf litTrue (litInt 5) (litInt 0)),
printLn (cot (litDouble 1.0))]])
| Print the 5th given argument .
helloElseBody :: (OOProg r) => MSBody r
helloElseBody = bodyStatements [printLn (arg 5)]
helloIfExists :: (OOProg r) => MSStatement r
helloIfExists = ifExists (valueOf $ var "boringList" (listType bool))
(oneLiner (printStrLn "Ew, boring list!")) (oneLiner (printStrLn "Great, no bores!"))
helloSwitch :: (OOProg r) => MSStatement r
helloSwitch = switch (valueOf $ var "a" int) [(litInt 5, oneLiner (var "b" int &= litInt 10)),
(litInt 0, oneLiner (var "b" int &= litInt 5))]
(oneLiner (var "b" int &= litInt 0))
helloForLoop :: (OOProg r) => MSStatement r
helloForLoop = forRange i (litInt 0) (litInt 9) (litInt 1) (oneLiner (printLn
(valueOf i)))
where i = var "i" int
helloWhileLoop :: (OOProg r) => MSStatement r
helloWhileLoop = while (valueOf (var "a" int) ?< litInt 13) (bodyStatements
[printStrLn "Hello", (&++) (var "a" int)])
helloForEachLoop :: (OOProg r) => MSStatement r
helloForEachLoop = forEach i (valueOf $ listVar "myOtherList" double)
(oneLiner (printLn (extFuncApp "Helper" "doubleAndAdd" double [valueOf i,
litDouble 1.0])))
where i = var "num" double
helloTryCatch :: (OOProg r) => MSStatement r
helloTryCatch = tryCatch (oneLiner (throw "Good-bye!"))
(oneLiner (printStrLn "Caught intentional error"))
|
0a4f75c8544438b33728016776a8d02dfa1b10ee1ae93b39d337c95aef1266fa | facebook/duckling | Corpus.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Volume.DE.Corpus
( corpus ) where
import Data.String
import Prelude
import Duckling.Locale
import Duckling.Resolve
import Duckling.Testing.Types
import Duckling.Volume.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale DE Nothing}, testOptions, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (simple Litre 1)
[ "1 liter"
--, "ein liter"
]
, examples (simple Litre 2)
[ "2 liter"
, "2l"
]
, examples (simple Litre 1000)
[ "1000 liter"
, "tausend liter"
]
, examples (simple Litre 0.5)
[ "halber liter"
, "ein halber liter"
]
, examples (simple Litre 0.25)
[ "viertel liter"
, "ein viertel liter"
]
, examples (simple Millilitre 1)
[ "ein milliliter"
, "ein ml"
, "1ml"
]
, examples (simple Millilitre 250)
[ "250 milliliter"
, "250ml"
, "250 ml"
]
, examples (simple Hectolitre 3)
[ "3 hektoliter"
]
, examples (between Litre (100,1000))
[ "zwischen 100 und 1000 litern"
, "100-1000 liter"
, "von 100 bis 1000 l"
, "100 - 1000 l"
]
, examples (between Litre (2,7))
[ "etwa 2 -7 l"
, "~2-7 liter"
, "von 2 bis 7 l"
, "zwischen 2,0 l und ungefähr 7,0 l"
, "zwischen 2l und etwa 7l"
, "2 - ~7 liter"
]
, examples (under Hectolitre 2)
[ "nicht mehr als 2 hektoliter"
, "höchstens zwei hektoliter"
, "unter 2 hektolitern"
, "weniger als 2 hektoliter"
]
, examples (above Millilitre 4)
[ "mehr als 4 ml"
, "wenigstens 4,0 ml"
, "über vier milliliter"
, "mindestens vier ml"
]
]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/Volume/DE/Corpus.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
# LANGUAGE OverloadedStrings #
, "ein liter" | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.Volume.DE.Corpus
( corpus ) where
import Data.String
import Prelude
import Duckling.Locale
import Duckling.Resolve
import Duckling.Testing.Types
import Duckling.Volume.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale DE Nothing}, testOptions, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (simple Litre 1)
[ "1 liter"
]
, examples (simple Litre 2)
[ "2 liter"
, "2l"
]
, examples (simple Litre 1000)
[ "1000 liter"
, "tausend liter"
]
, examples (simple Litre 0.5)
[ "halber liter"
, "ein halber liter"
]
, examples (simple Litre 0.25)
[ "viertel liter"
, "ein viertel liter"
]
, examples (simple Millilitre 1)
[ "ein milliliter"
, "ein ml"
, "1ml"
]
, examples (simple Millilitre 250)
[ "250 milliliter"
, "250ml"
, "250 ml"
]
, examples (simple Hectolitre 3)
[ "3 hektoliter"
]
, examples (between Litre (100,1000))
[ "zwischen 100 und 1000 litern"
, "100-1000 liter"
, "von 100 bis 1000 l"
, "100 - 1000 l"
]
, examples (between Litre (2,7))
[ "etwa 2 -7 l"
, "~2-7 liter"
, "von 2 bis 7 l"
, "zwischen 2,0 l und ungefähr 7,0 l"
, "zwischen 2l und etwa 7l"
, "2 - ~7 liter"
]
, examples (under Hectolitre 2)
[ "nicht mehr als 2 hektoliter"
, "höchstens zwei hektoliter"
, "unter 2 hektolitern"
, "weniger als 2 hektoliter"
]
, examples (above Millilitre 4)
[ "mehr als 4 ml"
, "wenigstens 4,0 ml"
, "über vier milliliter"
, "mindestens vier ml"
]
]
|
9621762b8f44e5f07f9d06c88d472195b06a156a8520d1b2a7018a22a6bb291e | expipiplus1/vulkan | VK_EXT_shader_viewport_index_layer.hs | {-# language CPP #-}
-- | = Name
--
-- VK_EXT_shader_viewport_index_layer - device extension
--
-- == VK_EXT_shader_viewport_index_layer
--
-- [__Name String__]
-- @VK_EXT_shader_viewport_index_layer@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
163
--
-- [__Revision__]
1
--
-- [__Extension and Version Dependencies__]
--
- Requires support for Vulkan 1.0
--
-- [__Deprecation state__]
--
-- - /Promoted/ to
-- <-extensions/html/vkspec.html#versions-1.2-promotions Vulkan 1.2>
--
-- [__Contact__]
--
-
-- <-Docs/issues/new?body=[VK_EXT_shader_viewport_index_layer] @dgkoch%0A*Here describe the issue or question you have about the VK_EXT_shader_viewport_index_layer extension* >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
2017 - 08 - 08
--
-- [__Interactions and External Dependencies__]
--
- Promoted to Vulkan 1.2 Core
--
-- - This extension requires
-- <-Registry/blob/master/extensions/EXT/SPV_EXT_shader_viewport_index_layer.html SPV_EXT_shader_viewport_index_layer>
--
-- - This extension provides API support for
-- < GL_ARB_shader_viewport_layer_array>,
< > ,
-- < GL_AMD_vertex_shader_viewport_index>,
-- and
-- < GL_NV_viewport_array2>
--
-- - This extension requires the @multiViewport@ feature.
--
-- - This extension interacts with the @tessellationShader@ feature.
--
-- [__Contributors__]
--
- , NVIDIA
--
- , NVIDIA
--
- Jan - , ARM
--
- , AMD
--
- , Intel
--
-- == Description
--
This extension adds support for the @ShaderViewportIndexLayerEXT@
capability from the @SPV_EXT_shader_viewport_index_layer@ extension in
Vulkan .
--
-- This extension allows variables decorated with the @Layer@ and
-- @ViewportIndex@ built-ins to be exported from vertex or tessellation
shaders , using the @ShaderViewportIndexLayerEXT@ capability .
--
When using GLSL source - based shading languages , the
-- and @gl_Layer@ built-in variables map to the SPIR-V @ViewportIndex@ and
-- @Layer@ built-in decorations, respectively. Behaviour of these variables
-- is extended as described in the @GL_ARB_shader_viewport_layer_array@ (or
-- the precursor @GL_AMD_vertex_shader_layer@,
@GL_AMD_vertex_shader_viewport_index@ , and @GL_NV_viewport_array2@
-- extensions).
--
-- Note
--
-- The @ShaderViewportIndexLayerEXT@ capability is equivalent to the
-- @ShaderViewportIndexLayerNV@ capability added by
-- @VK_NV_viewport_array2@.
--
= = Promotion to Vulkan 1.2
--
All functionality in this extension is included in core Vulkan 1.2 .
--
-- The single @ShaderViewportIndexLayerEXT@ capability from the
@SPV_EXT_shader_viewport_index_layer@ extension is replaced by the
-- <-extensions/html/vkspec.html#spirvenv-capabilities-table-ShaderViewportIndex ShaderViewportIndex>
-- and
-- <-extensions/html/vkspec.html#spirvenv-capabilities-table-ShaderLayer ShaderLayer>
-- capabilities from SPIR-V 1.5 which are enabled by the
< >
-- and
-- <-extensions/html/vkspec.html#features-shaderOutputLayer shaderOutputLayer>
features , respectively . Additionally , if Vulkan 1.2 is supported but
-- this extension is not, these capabilities are optional.
--
-- Enabling both features is equivalent to enabling the
-- @VK_EXT_shader_viewport_index_layer@ extension.
--
-- == New Enum Constants
--
-- - 'EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME'
--
-- - 'EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION'
--
-- == New or Modified Built-In Variables
--
-- - (modified)
-- <-extensions/html/vkspec.html#interfaces-builtin-variables-layer Layer>
--
-- - (modified)
< -extensions/html/vkspec.html#interfaces-builtin-variables-viewportindex ViewportIndex >
--
-- == New SPIR-V Capabilities
--
-- - <-extensions/html/vkspec.html#spirvenv-capabilities-table-ShaderViewportIndexLayerEXT ShaderViewportIndexLayerEXT>
--
-- == Version History
--
- Revision 1 , 2017 - 08 - 08 ( )
--
- Internal drafts
--
-- == See Also
--
-- No cross-references are available
--
-- == Document Notes
--
-- For more information, see the
-- <-extensions/html/vkspec.html#VK_EXT_shader_viewport_index_layer Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_EXT_shader_viewport_index_layer ( EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION
, pattern EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION
, EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME
, pattern EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME
) where
import Data.String (IsString)
type EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION = 1
No documentation found for TopLevel " VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION "
pattern EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION :: forall a . Integral a => a
pattern EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION = 1
type EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME = "VK_EXT_shader_viewport_index_layer"
No documentation found for TopLevel " VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME "
pattern EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME = "VK_EXT_shader_viewport_index_layer"
| null | https://raw.githubusercontent.com/expipiplus1/vulkan/b1e33d1031779b4740c279c68879d05aee371659/src/Vulkan/Extensions/VK_EXT_shader_viewport_index_layer.hs | haskell | # language CPP #
| = Name
VK_EXT_shader_viewport_index_layer - device extension
== VK_EXT_shader_viewport_index_layer
[__Name String__]
@VK_EXT_shader_viewport_index_layer@
[__Extension Type__]
Device extension
[__Registered Extension Number__]
[__Revision__]
[__Extension and Version Dependencies__]
[__Deprecation state__]
- /Promoted/ to
<-extensions/html/vkspec.html#versions-1.2-promotions Vulkan 1.2>
[__Contact__]
<-Docs/issues/new?body=[VK_EXT_shader_viewport_index_layer] @dgkoch%0A*Here describe the issue or question you have about the VK_EXT_shader_viewport_index_layer extension* >
== Other Extension Metadata
[__Last Modified Date__]
[__Interactions and External Dependencies__]
- This extension requires
<-Registry/blob/master/extensions/EXT/SPV_EXT_shader_viewport_index_layer.html SPV_EXT_shader_viewport_index_layer>
- This extension provides API support for
< GL_ARB_shader_viewport_layer_array>,
< GL_AMD_vertex_shader_viewport_index>,
and
< GL_NV_viewport_array2>
- This extension requires the @multiViewport@ feature.
- This extension interacts with the @tessellationShader@ feature.
[__Contributors__]
== Description
This extension allows variables decorated with the @Layer@ and
@ViewportIndex@ built-ins to be exported from vertex or tessellation
and @gl_Layer@ built-in variables map to the SPIR-V @ViewportIndex@ and
@Layer@ built-in decorations, respectively. Behaviour of these variables
is extended as described in the @GL_ARB_shader_viewport_layer_array@ (or
the precursor @GL_AMD_vertex_shader_layer@,
extensions).
Note
The @ShaderViewportIndexLayerEXT@ capability is equivalent to the
@ShaderViewportIndexLayerNV@ capability added by
@VK_NV_viewport_array2@.
The single @ShaderViewportIndexLayerEXT@ capability from the
<-extensions/html/vkspec.html#spirvenv-capabilities-table-ShaderViewportIndex ShaderViewportIndex>
and
<-extensions/html/vkspec.html#spirvenv-capabilities-table-ShaderLayer ShaderLayer>
capabilities from SPIR-V 1.5 which are enabled by the
and
<-extensions/html/vkspec.html#features-shaderOutputLayer shaderOutputLayer>
this extension is not, these capabilities are optional.
Enabling both features is equivalent to enabling the
@VK_EXT_shader_viewport_index_layer@ extension.
== New Enum Constants
- 'EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME'
- 'EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION'
== New or Modified Built-In Variables
- (modified)
<-extensions/html/vkspec.html#interfaces-builtin-variables-layer Layer>
- (modified)
== New SPIR-V Capabilities
- <-extensions/html/vkspec.html#spirvenv-capabilities-table-ShaderViewportIndexLayerEXT ShaderViewportIndexLayerEXT>
== Version History
== See Also
No cross-references are available
== Document Notes
For more information, see the
<-extensions/html/vkspec.html#VK_EXT_shader_viewport_index_layer Vulkan Specification>
This page is a generated document. Fixes and changes should be made to
the generator scripts, not directly. | 163
1
- Requires support for Vulkan 1.0
-
2017 - 08 - 08
- Promoted to Vulkan 1.2 Core
< > ,
- , NVIDIA
- , NVIDIA
- Jan - , ARM
- , AMD
- , Intel
This extension adds support for the @ShaderViewportIndexLayerEXT@
capability from the @SPV_EXT_shader_viewport_index_layer@ extension in
Vulkan .
shaders , using the @ShaderViewportIndexLayerEXT@ capability .
When using GLSL source - based shading languages , the
@GL_AMD_vertex_shader_viewport_index@ , and @GL_NV_viewport_array2@
= = Promotion to Vulkan 1.2
All functionality in this extension is included in core Vulkan 1.2 .
@SPV_EXT_shader_viewport_index_layer@ extension is replaced by the
< >
features , respectively . Additionally , if Vulkan 1.2 is supported but
< -extensions/html/vkspec.html#interfaces-builtin-variables-viewportindex ViewportIndex >
- Revision 1 , 2017 - 08 - 08 ( )
- Internal drafts
module Vulkan.Extensions.VK_EXT_shader_viewport_index_layer ( EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION
, pattern EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION
, EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME
, pattern EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME
) where
import Data.String (IsString)
type EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION = 1
No documentation found for TopLevel " VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION "
pattern EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION :: forall a . Integral a => a
pattern EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION = 1
type EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME = "VK_EXT_shader_viewport_index_layer"
No documentation found for TopLevel " VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME "
pattern EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME = "VK_EXT_shader_viewport_index_layer"
|
da928e4b8dd1841e269690b6b67be9ea1dd0dd745228879f64abcf6ecc1d0ce1 | solita/mnt-teet | vektorio_core.clj | (ns teet.integration.vektorio.vektorio-core
(:require [teet.integration.vektorio.vektorio-client :as vektorio-client]
[teet.integration.vektorio.vektorio-db :as vektorio-db]
[datomic.client.api :as d]
[teet.project.project-db :as project-db]
[teet.log :as log]
[teet.integration.integration-s3 :as integration-s3]
[teet.file.file-storage :as file-storage]
[teet.localization :refer [with-language tr-enum tr]]
[teet.file.file-db :as file-db]
[teet.file.filename-metadata :as filename-metadata]))
(defn get-or-create-user!
[user vektorio-config]
(or
(:id (vektorio-client/get-user-by-account
vektorio-config
(:user/person-id user)))
(:id (vektorio-client/create-user! vektorio-config
{:account (:user/person-id user)
:name (str (:user/given-name user) " " (:user/family-name user))}))))
(defn create-project-in-vektorio!
[conn vektor-config project-eid]
(let [db (d/db conn)
project (d/pull db [:db/id :thk.project/name :thk.project/project-name :thk.project/id] project-eid)
project-name (or (:thk.project/project-name project)
(:thk.project/name project))
project-name-for-vektor (str project-name " (THK" (:thk.project/id project) ")")
resp (vektorio-client/create-project! vektor-config {:name project-name-for-vektor})
vektorio-project-id (str (:id resp))]
(log/info "Creating project in vektorio for project" project vektorio-project-id)
(if-not (some? vektorio-project-id)
(throw (ex-info "No id for project in Vektorio response"
{:resp resp
:error :no-project-id-in-response}))
(do
(d/transact conn {:tx-data [{:db/id (:db/id project)
:vektorio/project-id vektorio-project-id}]})
vektorio-project-id))))
(defn ensure-project-vektorio-id!
[conn vektor-config file-eid]
(let [db (d/db conn)
project-id (project-db/file-project-id db file-eid)]
(log/info "Ensure the project exists in vektorio for project:" project-id)
(if-let
[project-vektorio-id (:vektorio/project-id (d/pull db [:vektorio/project-id] project-id))]
project-vektorio-id
(create-project-in-vektorio! conn vektor-config project-id))))
(defn- vektorio-filepath
"Returns {activity-code - activity-name}/{task-code - task-name}/{DD - file-part-name} for given file"
[db file-id]
(let [task-activity-code (vektorio-db/activity-and-task-info db file-id)
file-part (vektorio-db/file-part-info db file-id)]
(with-language :et
(str
(:activity-code task-activity-code) " - "
(tr-enum (:activity-name task-activity-code)) "/"
(:task-code task-activity-code) " - "
(tr-enum (:task-name task-activity-code))
(if (some? file-part)
(str "/" (format "%02d" (:part-number file-part)) " - " (:part-name file-part))
(str "/00 - " (tr [:file-upload :general-part])))))))
(defn- vektorio-filename
"Returns for example '02_1_Uskuna.dwg'"
[db file-id]
(let [file-meta-data (filename-metadata/metadata->vektorio-filename
(file-db/file-metadata-by-id db file-id))]
file-meta-data))
(defn upload-file-to-vektor!
[conn vektor-config file-id]
(log/info "Uploading file" file-id "to vektorio")
(let [db (d/db conn)
project-vektor-id (ensure-project-vektorio-id! conn vektor-config file-id)
file-data (d/pull db '[:file/name :db/id :file/s3-key] file-id)
response (vektorio-client/add-model-to-project! vektor-config {:project-id project-vektor-id
:model-file (integration-s3/get-object-stream-http
(file-storage/storage-bucket)
(:file/s3-key file-data))
:vektorio-filename (vektorio-filename db file-id)
:vektorio-filepath (vektorio-filepath db file-id)})
vektorio-model-id (str (:id response))]
(log/info "Model id from vektorio response:" vektorio-model-id)
(if-not (some? vektorio-model-id)
(throw (ex-info "No model id in Vektorio response"
{:response response
:error :no-model-id-in-response}))
(d/transact conn {:tx-data [{:db/id (:db/id file-data)
:vektorio/model-id vektorio-model-id}]}))))
(defn delete-file-from-project! [db vektorio-config project-eid file-eid]
( du / retractions db file - id / model - id ] ) ; ; wo n't need if we rely on the file entity being deleted immediately after
(let [params (merge
(d/pull db [:vektorio/model-id] file-eid)
(d/pull db [:vektorio/project-id ] project-eid))
response (if (not= 2 (count params))
(log/info "skipping vektorio delete due to missing model/project ids for file" file-eid)
(vektorio-client/delete-model! vektorio-config params))]
(when response
(log/info "successfully deleted vektorio model for file" file-eid))
response))
(defn instant-login
"Login to VektorIO."
[vektorio-config vektorio-user-id]
(vektorio-client/instant-login vektorio-config {:user-id vektorio-user-id}))
(defn update-project-in-vektorio!
"Updates the project name in Vektor.io should it be changed in TEET"
[db vektor-config project-id project-name]
(let [project (d/pull db [:db/id :thk.project/name :thk.project/project-name :thk.project/id :vektorio/project-id] project-id)
vektor-project-name (str project-name " (THK" (:thk.project/id project) ")")
vektor-project-id (:vektorio/project-id project)
resp (if (some? vektor-project-id)
(vektorio-client/update-project! vektor-config vektor-project-id vektor-project-name)
(do (log/info "No Vektor project id found for " project-id)
true))]
resp))
(defn update-model-in-vektorio!
"Updates the model name in Vektor.io in case it is changed in TEET"
[conn db vektor-config file-id]
(let [vektor-model-id (:vektorio/model-id (d/pull db [:db/id :vektorio/model-id] file-id))
vektor-project-id (ensure-project-vektorio-id! conn vektor-config file-id)
vektor-filename (vektorio-filename db file-id)
vektor-filepath (vektorio-filepath db file-id)
resp (if (and
(some? vektor-model-id)
(some? vektor-project-id))
(vektorio-client/update-model! vektor-config vektor-project-id vektor-model-id vektor-filename vektor-filepath)
(do (log/info "No Vektor project/model id found for " file-id vektor-project-id vektor-model-id)
true))]
resp))
| null | https://raw.githubusercontent.com/solita/mnt-teet/8d518c283452cee3346ab03d7f730914c24c53e2/app/backend/src/clj/teet/integration/vektorio/vektorio_core.clj | clojure | ; wo n't need if we rely on the file entity being deleted immediately after | (ns teet.integration.vektorio.vektorio-core
(:require [teet.integration.vektorio.vektorio-client :as vektorio-client]
[teet.integration.vektorio.vektorio-db :as vektorio-db]
[datomic.client.api :as d]
[teet.project.project-db :as project-db]
[teet.log :as log]
[teet.integration.integration-s3 :as integration-s3]
[teet.file.file-storage :as file-storage]
[teet.localization :refer [with-language tr-enum tr]]
[teet.file.file-db :as file-db]
[teet.file.filename-metadata :as filename-metadata]))
(defn get-or-create-user!
[user vektorio-config]
(or
(:id (vektorio-client/get-user-by-account
vektorio-config
(:user/person-id user)))
(:id (vektorio-client/create-user! vektorio-config
{:account (:user/person-id user)
:name (str (:user/given-name user) " " (:user/family-name user))}))))
(defn create-project-in-vektorio!
[conn vektor-config project-eid]
(let [db (d/db conn)
project (d/pull db [:db/id :thk.project/name :thk.project/project-name :thk.project/id] project-eid)
project-name (or (:thk.project/project-name project)
(:thk.project/name project))
project-name-for-vektor (str project-name " (THK" (:thk.project/id project) ")")
resp (vektorio-client/create-project! vektor-config {:name project-name-for-vektor})
vektorio-project-id (str (:id resp))]
(log/info "Creating project in vektorio for project" project vektorio-project-id)
(if-not (some? vektorio-project-id)
(throw (ex-info "No id for project in Vektorio response"
{:resp resp
:error :no-project-id-in-response}))
(do
(d/transact conn {:tx-data [{:db/id (:db/id project)
:vektorio/project-id vektorio-project-id}]})
vektorio-project-id))))
(defn ensure-project-vektorio-id!
[conn vektor-config file-eid]
(let [db (d/db conn)
project-id (project-db/file-project-id db file-eid)]
(log/info "Ensure the project exists in vektorio for project:" project-id)
(if-let
[project-vektorio-id (:vektorio/project-id (d/pull db [:vektorio/project-id] project-id))]
project-vektorio-id
(create-project-in-vektorio! conn vektor-config project-id))))
(defn- vektorio-filepath
"Returns {activity-code - activity-name}/{task-code - task-name}/{DD - file-part-name} for given file"
[db file-id]
(let [task-activity-code (vektorio-db/activity-and-task-info db file-id)
file-part (vektorio-db/file-part-info db file-id)]
(with-language :et
(str
(:activity-code task-activity-code) " - "
(tr-enum (:activity-name task-activity-code)) "/"
(:task-code task-activity-code) " - "
(tr-enum (:task-name task-activity-code))
(if (some? file-part)
(str "/" (format "%02d" (:part-number file-part)) " - " (:part-name file-part))
(str "/00 - " (tr [:file-upload :general-part])))))))
(defn- vektorio-filename
"Returns for example '02_1_Uskuna.dwg'"
[db file-id]
(let [file-meta-data (filename-metadata/metadata->vektorio-filename
(file-db/file-metadata-by-id db file-id))]
file-meta-data))
(defn upload-file-to-vektor!
[conn vektor-config file-id]
(log/info "Uploading file" file-id "to vektorio")
(let [db (d/db conn)
project-vektor-id (ensure-project-vektorio-id! conn vektor-config file-id)
file-data (d/pull db '[:file/name :db/id :file/s3-key] file-id)
response (vektorio-client/add-model-to-project! vektor-config {:project-id project-vektor-id
:model-file (integration-s3/get-object-stream-http
(file-storage/storage-bucket)
(:file/s3-key file-data))
:vektorio-filename (vektorio-filename db file-id)
:vektorio-filepath (vektorio-filepath db file-id)})
vektorio-model-id (str (:id response))]
(log/info "Model id from vektorio response:" vektorio-model-id)
(if-not (some? vektorio-model-id)
(throw (ex-info "No model id in Vektorio response"
{:response response
:error :no-model-id-in-response}))
(d/transact conn {:tx-data [{:db/id (:db/id file-data)
:vektorio/model-id vektorio-model-id}]}))))
(defn delete-file-from-project! [db vektorio-config project-eid file-eid]
(let [params (merge
(d/pull db [:vektorio/model-id] file-eid)
(d/pull db [:vektorio/project-id ] project-eid))
response (if (not= 2 (count params))
(log/info "skipping vektorio delete due to missing model/project ids for file" file-eid)
(vektorio-client/delete-model! vektorio-config params))]
(when response
(log/info "successfully deleted vektorio model for file" file-eid))
response))
(defn instant-login
"Login to VektorIO."
[vektorio-config vektorio-user-id]
(vektorio-client/instant-login vektorio-config {:user-id vektorio-user-id}))
(defn update-project-in-vektorio!
"Updates the project name in Vektor.io should it be changed in TEET"
[db vektor-config project-id project-name]
(let [project (d/pull db [:db/id :thk.project/name :thk.project/project-name :thk.project/id :vektorio/project-id] project-id)
vektor-project-name (str project-name " (THK" (:thk.project/id project) ")")
vektor-project-id (:vektorio/project-id project)
resp (if (some? vektor-project-id)
(vektorio-client/update-project! vektor-config vektor-project-id vektor-project-name)
(do (log/info "No Vektor project id found for " project-id)
true))]
resp))
(defn update-model-in-vektorio!
"Updates the model name in Vektor.io in case it is changed in TEET"
[conn db vektor-config file-id]
(let [vektor-model-id (:vektorio/model-id (d/pull db [:db/id :vektorio/model-id] file-id))
vektor-project-id (ensure-project-vektorio-id! conn vektor-config file-id)
vektor-filename (vektorio-filename db file-id)
vektor-filepath (vektorio-filepath db file-id)
resp (if (and
(some? vektor-model-id)
(some? vektor-project-id))
(vektorio-client/update-model! vektor-config vektor-project-id vektor-model-id vektor-filename vektor-filepath)
(do (log/info "No Vektor project/model id found for " file-id vektor-project-id vektor-model-id)
true))]
resp))
|
18e6a25b182c2ac181d1b82f129efb4d84d4fde424b810f607724fbd26b967a3 | ayato-p/mokuhan | mokuhan.cljc | (ns org.panchromatic.mokuhan
(:require [org.panchromatic.mokuhan.parser :as parser]
[org.panchromatic.mokuhan.renderer :as renderer]))
(defn render
([mustache data]
(render mustache data {}))
([mustache data opts]
(let [render' (fn [& [opts']] #(render % data (merge opts opts')))]
(-> (parser/parse mustache opts)
(renderer/render data (assoc opts :render render'))))))
| null | https://raw.githubusercontent.com/ayato-p/mokuhan/8f6de17b5c4a3712aa83ba4f37234de86f3c630b/src/org/panchromatic/mokuhan.cljc | clojure | (ns org.panchromatic.mokuhan
(:require [org.panchromatic.mokuhan.parser :as parser]
[org.panchromatic.mokuhan.renderer :as renderer]))
(defn render
([mustache data]
(render mustache data {}))
([mustache data opts]
(let [render' (fn [& [opts']] #(render % data (merge opts opts')))]
(-> (parser/parse mustache opts)
(renderer/render data (assoc opts :render render'))))))
|
|
c0f8d9bb730236ebf3d095f04cd157cf2f9a6171266b194cd5968fd6e96b7c3a | ghc/testsuite | TcRun038_B.hs | # LANGUAGE FlexibleContexts #
module TcRun038_B where
class Foo a where
op :: a -> Int
-- Note the (Foo Int) constraint here; and the fact
that there is no ( ) instance in this module
-- It's in the importing module!
bar :: Foo Int => Int -> Int
bar x = op x + 7
| null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_run/TcRun038_B.hs | haskell | Note the (Foo Int) constraint here; and the fact
It's in the importing module!
| # LANGUAGE FlexibleContexts #
module TcRun038_B where
class Foo a where
op :: a -> Int
that there is no ( ) instance in this module
bar :: Foo Int => Int -> Int
bar x = op x + 7
|
44e0b131b02efc1e45a8598ad9d87acbfbbc658e323ef90534a09f71048357cb | kronusaturn/lw2-viewer | hash-utils.lisp | (uiop:define-package #:lw2.hash-utils
(:use #:cl #:iter)
(:import-from #:flexi-streams #:string-to-octets #:octets-to-string #:with-output-to-sequence)
(:export #:city-hash-128-vector #:hash-string #:hash-printable-object #:hash-file-list)
(:recycle #:lw2.lmdb))
(in-package #:lw2.hash-utils)
(defun city-hash-128-vector (data)
(let ((array (make-array 16 :element-type '(unsigned-byte 8))))
(multiple-value-bind (r1 r2) (city-hash:city-hash-128
(coerce data '(simple-array (unsigned-byte 8) (*))))
(setf (nibbles:ub64ref/be array 0) r1
(nibbles:ub64ref/be array 8) r2))
array))
(defun hash-string (string)
(city-hash-128-vector (string-to-octets string :external-format :utf-8)))
(defun hash-printable-object (object)
(hash-string (write-to-string object :circle nil :escape nil :pretty nil)))
(defun hash-file-list (file-list)
(city-hash-128-vector
(with-output-to-sequence (out-stream)
(iter (for f in file-list)
(with-open-file (in-stream (asdf:system-relative-pathname :lw2-viewer f) :direction :input :element-type '(unsigned-byte 8))
(uiop:copy-stream-to-stream in-stream out-stream :element-type '(unsigned-byte 8)))))))
| null | https://raw.githubusercontent.com/kronusaturn/lw2-viewer/f328105e9640be1314d166203c8706f9470054fa/src/hash-utils.lisp | lisp | (uiop:define-package #:lw2.hash-utils
(:use #:cl #:iter)
(:import-from #:flexi-streams #:string-to-octets #:octets-to-string #:with-output-to-sequence)
(:export #:city-hash-128-vector #:hash-string #:hash-printable-object #:hash-file-list)
(:recycle #:lw2.lmdb))
(in-package #:lw2.hash-utils)
(defun city-hash-128-vector (data)
(let ((array (make-array 16 :element-type '(unsigned-byte 8))))
(multiple-value-bind (r1 r2) (city-hash:city-hash-128
(coerce data '(simple-array (unsigned-byte 8) (*))))
(setf (nibbles:ub64ref/be array 0) r1
(nibbles:ub64ref/be array 8) r2))
array))
(defun hash-string (string)
(city-hash-128-vector (string-to-octets string :external-format :utf-8)))
(defun hash-printable-object (object)
(hash-string (write-to-string object :circle nil :escape nil :pretty nil)))
(defun hash-file-list (file-list)
(city-hash-128-vector
(with-output-to-sequence (out-stream)
(iter (for f in file-list)
(with-open-file (in-stream (asdf:system-relative-pathname :lw2-viewer f) :direction :input :element-type '(unsigned-byte 8))
(uiop:copy-stream-to-stream in-stream out-stream :element-type '(unsigned-byte 8)))))))
|
|
dee287b93fc09930ce6655ec743a165180fb31c2bd39c27a5daa7d68832fd9e4 | ghl3/dataframe | profiles.clj | {:dev {:dependencies [[expectations "2.1.9"]]
:plugins [[jonase/eastwood "0.2.3"]
[lein-cljfmt "0.5.6" :exclusions [org.clojure/clojure]]
[lein-expectations "0.0.8" :exclusions [org.clojure/clojure]]]
; Generate docs
:codox {:output-path "resources/codox"
:metadata {:doc/format :markdown}
:source-uri "/{filepath}#L{line}"}
:eastwood {:exclude-namespaces [:test-paths]}
; Format code
:cljfmt {:indents
{require [[:block 0]]
ns [[:block 0]]
#"^(?!:require|:import).*" [[:inner 0]]}}}
}
| null | https://raw.githubusercontent.com/ghl3/dataframe/31212c14669e31797ec13cde650a61fd97dbe6d2/profiles.clj | clojure | Generate docs
Format code | {:dev {:dependencies [[expectations "2.1.9"]]
:plugins [[jonase/eastwood "0.2.3"]
[lein-cljfmt "0.5.6" :exclusions [org.clojure/clojure]]
[lein-expectations "0.0.8" :exclusions [org.clojure/clojure]]]
:codox {:output-path "resources/codox"
:metadata {:doc/format :markdown}
:source-uri "/{filepath}#L{line}"}
:eastwood {:exclude-namespaces [:test-paths]}
:cljfmt {:indents
{require [[:block 0]]
ns [[:block 0]]
#"^(?!:require|:import).*" [[:inner 0]]}}}
}
|
d802cdc1b97b4dd0ecc337881b10254cd6c3e7df66303ef61eaa8d68443f2b77 | Smart-Sql/smart-sql | my_ml_train_data.clj | (ns org.gridgain.plus.ml.my-ml-train-data
(:require
[org.gridgain.plus.dml.select-lexical :as my-lexical]
[clojure.core.reducers :as r]
[clojure.string :as str]
[clojure.walk :as w])
(:import (org.apache.ignite Ignite)
(org.gridgain.smart MyVar MyLetLayer)
(com.google.common.base Strings)
(cn.plus.model MyKeyValue MyLogCache SqlType)
(org.gridgain.dml.util MyCacheExUtil)
(org.gridgain.myservice MyLoadSmartSqlService)
(cn.plus.model.db MyCallScenesPk MyCallScenes MyScenesCache ScenesType MyScenesParams MyScenesParamsPk MyScenesCachePk)
(org.apache.ignite.cache.query SqlFieldsQuery)
(java.math BigDecimal)
(org.apache.ignite.cache CacheMode)
(org.apache.ignite.configuration CacheConfiguration)
(org.apache.ignite.cache.affinity.rendezvous RendezvousAffinityFunction)
(java.util List ArrayList Hashtable Date Iterator)
(org.apache.ignite.ml.math.primitives.vector VectorUtils)
(org.gridgain.smart.ml MyTrianDataUtil)
(cn.plus.model.ddl MyCachePK MyMlCaches MyTransData MyMlShowData MyTransDataLoad)
(org.tools MyConvertUtil))
(:gen-class
; 生成 class 的类名
:name org.gridgain.plus.ml.MyMlTrainData
是否生成 class 的 main 方法
:main false
生成 java 静态的方法
;:methods [^:static [myDoubleTest [Object Object] Object]]
))
(defn hastable-to-cache [^Hashtable ht]
(letfn [(get-ds-name [^Hashtable ht]
(if (contains? ht "schema_name")
(get ht "schema_name")))
(get-table-name [^Hashtable ht]
(if (contains? ht "table_name")
(get ht "table_name")
(throw (Exception. "必须有 table_name 的属性!"))))
(get-describe [^Hashtable ht]
(if (contains? ht "describe")
(get ht "describe")))
(get-is-clustering [^Hashtable ht]
(if (contains? ht "is_clustering")
(get ht "is_clustering")
false))]
(doto (MyMlCaches.) (.setSchema_name (get-ds-name ht))
(.setTable_name (get-table-name ht))
(.setDescribe (get-describe ht))
(.setIs_clustering (get-is-clustering ht)))))
(defn hashtable-to-trans-data [^Ignite ignite ^Hashtable ht]
(letfn [(get-ds-name [^Hashtable ht]
(if (contains? ht "schema_name")
(get ht "schema_name")))
(get-table-name [^Hashtable ht]
(if (contains? ht "table_name")
(get ht "table_name")
(throw (Exception. "必须有 table_name 的属性!"))))
(get-value [^Hashtable ht]
(if (contains? ht "value")
(get ht "value")
(throw (Exception. "必须有 value 的属性!"))))
(get-label [^Hashtable ht]
(if (contains? ht "label")
(MyConvertUtil/ConvertToDouble (get ht "label"))
(throw (Exception. "必须有 label 的属性!"))))
(get-is-clustering [^Ignite ignite ^String ds-name ^String table-name]
(let [m (.get (.cache ignite "ml_train_data") (MyCachePK. ds-name table-name))]
(.getIs_clustering m)))]
(doto (MyTransData.)
(.setSchema_name (get-ds-name ht))
(.setTable_name (get-table-name ht))
(.setValue (get-value ht))
(.setLabel (get-label ht))
(.setIs_clustering (get-is-clustering ignite (get-ds-name ht) (get-table-name ht))))))
(defn hastable-to-data-load [^Hashtable ht]
(letfn [(get-ds-name [^Hashtable ht]
(if (contains? ht "schema_name")
(get ht "schema_name")))
(get-table-name [^Hashtable ht]
(if (contains? ht "table_name")
(get ht "table_name")
(throw (Exception. "必须有 table_name 的属性!"))))
(get-value [^Hashtable ht]
(if (contains? ht "value")
(get ht "value")))
(get-is-clustering [^Hashtable ht]
(if (contains? ht "is_clustering")
(get ht "is_clustering")
false))]
(doto (MyTransDataLoad.) (.setSchema_name (get-ds-name ht))
(.setTable_name (get-table-name ht))
(.setValue (get-value ht))
(.setIs_clustering (get-is-clustering ht)))))
(defn to-double [m]
(MyConvertUtil/ConvertToDouble m))
(defn my-to-double
([lst] (double-array (map to-double lst)))
([item lst]
(double-array (cons (to-double item) (map to-double lst)))))
(defn ml-train-matrix [^Ignite ignite ^Hashtable ht]
(if-let [m (hashtable-to-trans-data ignite ht)]
(let [cacheName (MyTrianDataUtil/getCacheName m)]
(let [key (.incrementAndGet (.atomicSequence ignite cacheName 0 true))]
(if (true? (.getIs_clustering m))
(let [vs (VectorUtils/of (my-to-double 0 (.getValue m)))]
(.put (.cache ignite cacheName) key vs))
(let [vs (VectorUtils/of (my-to-double (.getLabel m) (.getValue m)))]
(.put (.cache ignite cacheName) key vs)))
))))
(defn ml-train-matrix-single [^Ignite ignite ^Hashtable ht]
(if-let [m (hastable-to-data-load ht)]
(let [cacheName (MyTrianDataUtil/getCacheName m)]
(let [key (.incrementAndGet (.atomicSequence ignite cacheName 0 true))]
(if-not (nil? (.getValue m))
(if (true? (.getIs_clustering m))
(let [vs (VectorUtils/of (my-to-double (cons 0 (.getValue m))))]
(.put (.cache ignite cacheName) key vs))
(let [vs (VectorUtils/of (my-to-double (.getValue m)))]
(.put (.cache ignite cacheName) key vs)))
)))))
(defn ml-create-train-matrix [^Ignite ignite ^MyMlCaches mlCaches]
(let [cacheName (MyTrianDataUtil/getCacheName mlCaches)]
(if-not (.cache ignite cacheName)
(do
(.getOrCreateCache ignite (MyTrianDataUtil/trainCfg cacheName))
(.put (.cache ignite "ml_train_data") (MyCachePK. (.getSchema_name mlCaches) (.getTable_name mlCaches)) mlCaches)))))
; 定一个分布式的矩阵
(defn create-train-matrix [^Ignite ignite group_id ^Hashtable ht]
(let [ds-name (second group_id)]
(cond (and (my-lexical/is-eq? ds-name "MY_META") (not (contains? ht "schema_name"))) (throw (Exception. "MY_META 下面不能创建机器学习的训练数据!"))
(and (my-lexical/is-eq? ds-name "MY_META") (contains? ht "schema_name") (my-lexical/is-eq? (get ht "schema_name") "MY_META")) (throw (Exception. "MY_META 下面不能创建机器学习的训练数据!"))
(and (my-lexical/is-eq? ds-name "MY_META") (contains? ht "schema_name") (not (my-lexical/is-eq? (get ht "schema_name") "MY_META"))) (ml-create-train-matrix ignite (hastable-to-cache ht))
(not (contains? ht "schema_name")) (ml-create-train-matrix ignite (hastable-to-cache (doto ht (.put "schema_name" (str/lower-case ds-name)))))
(contains? ht "schema_name") (cond (my-lexical/is-eq? (get ht "schema_name") "public") (ml-create-train-matrix ignite (hastable-to-cache ht))
(my-lexical/is-eq? (get ht "schema_name") ds-name) (ml-create-train-matrix ignite (hastable-to-cache ht))
:else (throw (Exception. "不能在其它非公共数据集下面不能创建机器学习的训练数据!")))
:else
(throw (Exception. "不能创建机器学习的训练数据!"))
)
))
; 是否有个叫 "训练数据集" 的矩阵
(defn has-train-matrix [^Ignite ignite group_id ^Hashtable ht]
(let [ds-name (second group_id)]
(cond
(and (my-lexical/is-eq? ds-name "MY_META") (contains? ht "schema_name") (not (my-lexical/is-eq? (get ht "schema_name") "MY_META"))) (MyTrianDataUtil/hasTrainMatrix ignite (hastable-to-cache ht))
(not (contains? ht "schema_name")) (MyTrianDataUtil/hasTrainMatrix ignite (hastable-to-cache (doto ht (.put "schema_name" (str/lower-case ds-name)))))
(contains? ht "schema_name") (cond (my-lexical/is-eq? (get ht "schema_name") "public") (MyTrianDataUtil/hasTrainMatrix ignite (hastable-to-cache ht))
(my-lexical/is-eq? (get ht "schema_name") ds-name) (MyTrianDataUtil/hasTrainMatrix ignite (hastable-to-cache ht))
:else (throw (Exception. "不能在其它非公共数据集下面查询机器学习的训练数据!")))
:else
(throw (Exception. "不存在机器学习的训练数据!"))
)
))
; 删除有个叫 "训练数据集" 的矩阵
(defn drop-train-matrix [^Ignite ignite group_id ^Hashtable ht]
(let [ds-name (second group_id)]
(cond
(and (my-lexical/is-eq? ds-name "MY_META") (contains? ht "schema_name") (not (my-lexical/is-eq? (get ht "schema_name") "MY_META"))) (MyTrianDataUtil/dropTrainMatrix ignite (hastable-to-cache ht))
(not (contains? ht "schema_name")) (MyTrianDataUtil/dropTrainMatrix ignite (hastable-to-cache (doto ht (.put "schema_name" (str/lower-case ds-name)))))
(contains? ht "schema_name") (cond (my-lexical/is-eq? (get ht "schema_name") "public") (MyTrianDataUtil/dropTrainMatrix ignite (hastable-to-cache ht))
(my-lexical/is-eq? (get ht "schema_name") ds-name) (MyTrianDataUtil/dropTrainMatrix ignite (hastable-to-cache ht))
:else (throw (Exception. "不能在其它非公共数据集下面删除机器学习的训练数据!")))
:else
(throw (Exception. "不存在机器学习的训练数据!"))
)
))
为分布式矩阵添加数据
(defn train-matrix [^Ignite ignite group_id ^Hashtable ht]
(let [ds-name (second group_id)]
(cond
(and (my-lexical/is-eq? ds-name "MY_META") (contains? ht "schema_name") (not (my-lexical/is-eq? (get ht "schema_name") "MY_META"))) (ml-train-matrix ignite ht)
(not (contains? ht "schema_name")) (ml-train-matrix ignite (hastable-to-cache (doto ht (.put "schema_name" (str/lower-case ds-name)))))
(contains? ht "schema_name") (cond (my-lexical/is-eq? (get ht "schema_name") "public") (ml-train-matrix ignite ht)
(my-lexical/is-eq? (get ht "schema_name") ds-name) (ml-train-matrix ignite ht)
:else (throw (Exception. "不能在其它非公共数据集下面添加机器学习的训练数据!")))
:else
(throw (Exception. "不存在机器学习的训练数据!"))
)
))
为分布式矩阵添加数据 -- 在 load csv 中使用
(defn train-matrix-single [^Ignite ignite group_id ^Hashtable ht]
(let [ds-name (second group_id)]
(cond
(and (my-lexical/is-eq? ds-name "MY_META") (contains? ht "schema_name") (not (my-lexical/is-eq? (get ht "schema_name") "MY_META"))) (ml-train-matrix-single ignite ht)
(not (contains? ht "schema_name")) (ml-train-matrix-single ignite (hastable-to-cache (doto ht (.put "schema_name" (str/lower-case ds-name)))))
(contains? ht "schema_name") (cond (my-lexical/is-eq? (get ht "schema_name") "public") (ml-train-matrix-single ignite ht)
(my-lexical/is-eq? (get ht "schema_name") ds-name) (ml-train-matrix-single ignite ht)
:else (throw (Exception. "不能在其它非公共数据集下面添加机器学习的训练数据!")))
:else
(throw (Exception. "不存在机器学习的训练数据!"))
)
))
; 测试 double-array
( defn -myDoubleTest [ item lst ]
( [ ( to - double [ m ]
( MyConvertUtil / ConvertToDouble m ) ) ]
; (double-array (cons (to-double item) (map to-double lst)))))
| null | https://raw.githubusercontent.com/Smart-Sql/smart-sql/d2f237f935472942a143816925221cdcf8246aff/src/main/clojure/org/gridgain/plus/ml/my_ml_train_data.clj | clojure | 生成 class 的类名
:methods [^:static [myDoubleTest [Object Object] Object]]
定一个分布式的矩阵
是否有个叫 "训练数据集" 的矩阵
删除有个叫 "训练数据集" 的矩阵
测试 double-array
(double-array (cons (to-double item) (map to-double lst))))) | (ns org.gridgain.plus.ml.my-ml-train-data
(:require
[org.gridgain.plus.dml.select-lexical :as my-lexical]
[clojure.core.reducers :as r]
[clojure.string :as str]
[clojure.walk :as w])
(:import (org.apache.ignite Ignite)
(org.gridgain.smart MyVar MyLetLayer)
(com.google.common.base Strings)
(cn.plus.model MyKeyValue MyLogCache SqlType)
(org.gridgain.dml.util MyCacheExUtil)
(org.gridgain.myservice MyLoadSmartSqlService)
(cn.plus.model.db MyCallScenesPk MyCallScenes MyScenesCache ScenesType MyScenesParams MyScenesParamsPk MyScenesCachePk)
(org.apache.ignite.cache.query SqlFieldsQuery)
(java.math BigDecimal)
(org.apache.ignite.cache CacheMode)
(org.apache.ignite.configuration CacheConfiguration)
(org.apache.ignite.cache.affinity.rendezvous RendezvousAffinityFunction)
(java.util List ArrayList Hashtable Date Iterator)
(org.apache.ignite.ml.math.primitives.vector VectorUtils)
(org.gridgain.smart.ml MyTrianDataUtil)
(cn.plus.model.ddl MyCachePK MyMlCaches MyTransData MyMlShowData MyTransDataLoad)
(org.tools MyConvertUtil))
(:gen-class
:name org.gridgain.plus.ml.MyMlTrainData
是否生成 class 的 main 方法
:main false
生成 java 静态的方法
))
(defn hastable-to-cache [^Hashtable ht]
(letfn [(get-ds-name [^Hashtable ht]
(if (contains? ht "schema_name")
(get ht "schema_name")))
(get-table-name [^Hashtable ht]
(if (contains? ht "table_name")
(get ht "table_name")
(throw (Exception. "必须有 table_name 的属性!"))))
(get-describe [^Hashtable ht]
(if (contains? ht "describe")
(get ht "describe")))
(get-is-clustering [^Hashtable ht]
(if (contains? ht "is_clustering")
(get ht "is_clustering")
false))]
(doto (MyMlCaches.) (.setSchema_name (get-ds-name ht))
(.setTable_name (get-table-name ht))
(.setDescribe (get-describe ht))
(.setIs_clustering (get-is-clustering ht)))))
(defn hashtable-to-trans-data [^Ignite ignite ^Hashtable ht]
(letfn [(get-ds-name [^Hashtable ht]
(if (contains? ht "schema_name")
(get ht "schema_name")))
(get-table-name [^Hashtable ht]
(if (contains? ht "table_name")
(get ht "table_name")
(throw (Exception. "必须有 table_name 的属性!"))))
(get-value [^Hashtable ht]
(if (contains? ht "value")
(get ht "value")
(throw (Exception. "必须有 value 的属性!"))))
(get-label [^Hashtable ht]
(if (contains? ht "label")
(MyConvertUtil/ConvertToDouble (get ht "label"))
(throw (Exception. "必须有 label 的属性!"))))
(get-is-clustering [^Ignite ignite ^String ds-name ^String table-name]
(let [m (.get (.cache ignite "ml_train_data") (MyCachePK. ds-name table-name))]
(.getIs_clustering m)))]
(doto (MyTransData.)
(.setSchema_name (get-ds-name ht))
(.setTable_name (get-table-name ht))
(.setValue (get-value ht))
(.setLabel (get-label ht))
(.setIs_clustering (get-is-clustering ignite (get-ds-name ht) (get-table-name ht))))))
(defn hastable-to-data-load [^Hashtable ht]
(letfn [(get-ds-name [^Hashtable ht]
(if (contains? ht "schema_name")
(get ht "schema_name")))
(get-table-name [^Hashtable ht]
(if (contains? ht "table_name")
(get ht "table_name")
(throw (Exception. "必须有 table_name 的属性!"))))
(get-value [^Hashtable ht]
(if (contains? ht "value")
(get ht "value")))
(get-is-clustering [^Hashtable ht]
(if (contains? ht "is_clustering")
(get ht "is_clustering")
false))]
(doto (MyTransDataLoad.) (.setSchema_name (get-ds-name ht))
(.setTable_name (get-table-name ht))
(.setValue (get-value ht))
(.setIs_clustering (get-is-clustering ht)))))
(defn to-double [m]
(MyConvertUtil/ConvertToDouble m))
(defn my-to-double
([lst] (double-array (map to-double lst)))
([item lst]
(double-array (cons (to-double item) (map to-double lst)))))
(defn ml-train-matrix [^Ignite ignite ^Hashtable ht]
(if-let [m (hashtable-to-trans-data ignite ht)]
(let [cacheName (MyTrianDataUtil/getCacheName m)]
(let [key (.incrementAndGet (.atomicSequence ignite cacheName 0 true))]
(if (true? (.getIs_clustering m))
(let [vs (VectorUtils/of (my-to-double 0 (.getValue m)))]
(.put (.cache ignite cacheName) key vs))
(let [vs (VectorUtils/of (my-to-double (.getLabel m) (.getValue m)))]
(.put (.cache ignite cacheName) key vs)))
))))
(defn ml-train-matrix-single [^Ignite ignite ^Hashtable ht]
(if-let [m (hastable-to-data-load ht)]
(let [cacheName (MyTrianDataUtil/getCacheName m)]
(let [key (.incrementAndGet (.atomicSequence ignite cacheName 0 true))]
(if-not (nil? (.getValue m))
(if (true? (.getIs_clustering m))
(let [vs (VectorUtils/of (my-to-double (cons 0 (.getValue m))))]
(.put (.cache ignite cacheName) key vs))
(let [vs (VectorUtils/of (my-to-double (.getValue m)))]
(.put (.cache ignite cacheName) key vs)))
)))))
(defn ml-create-train-matrix [^Ignite ignite ^MyMlCaches mlCaches]
(let [cacheName (MyTrianDataUtil/getCacheName mlCaches)]
(if-not (.cache ignite cacheName)
(do
(.getOrCreateCache ignite (MyTrianDataUtil/trainCfg cacheName))
(.put (.cache ignite "ml_train_data") (MyCachePK. (.getSchema_name mlCaches) (.getTable_name mlCaches)) mlCaches)))))
(defn create-train-matrix [^Ignite ignite group_id ^Hashtable ht]
(let [ds-name (second group_id)]
(cond (and (my-lexical/is-eq? ds-name "MY_META") (not (contains? ht "schema_name"))) (throw (Exception. "MY_META 下面不能创建机器学习的训练数据!"))
(and (my-lexical/is-eq? ds-name "MY_META") (contains? ht "schema_name") (my-lexical/is-eq? (get ht "schema_name") "MY_META")) (throw (Exception. "MY_META 下面不能创建机器学习的训练数据!"))
(and (my-lexical/is-eq? ds-name "MY_META") (contains? ht "schema_name") (not (my-lexical/is-eq? (get ht "schema_name") "MY_META"))) (ml-create-train-matrix ignite (hastable-to-cache ht))
(not (contains? ht "schema_name")) (ml-create-train-matrix ignite (hastable-to-cache (doto ht (.put "schema_name" (str/lower-case ds-name)))))
(contains? ht "schema_name") (cond (my-lexical/is-eq? (get ht "schema_name") "public") (ml-create-train-matrix ignite (hastable-to-cache ht))
(my-lexical/is-eq? (get ht "schema_name") ds-name) (ml-create-train-matrix ignite (hastable-to-cache ht))
:else (throw (Exception. "不能在其它非公共数据集下面不能创建机器学习的训练数据!")))
:else
(throw (Exception. "不能创建机器学习的训练数据!"))
)
))
(defn has-train-matrix [^Ignite ignite group_id ^Hashtable ht]
(let [ds-name (second group_id)]
(cond
(and (my-lexical/is-eq? ds-name "MY_META") (contains? ht "schema_name") (not (my-lexical/is-eq? (get ht "schema_name") "MY_META"))) (MyTrianDataUtil/hasTrainMatrix ignite (hastable-to-cache ht))
(not (contains? ht "schema_name")) (MyTrianDataUtil/hasTrainMatrix ignite (hastable-to-cache (doto ht (.put "schema_name" (str/lower-case ds-name)))))
(contains? ht "schema_name") (cond (my-lexical/is-eq? (get ht "schema_name") "public") (MyTrianDataUtil/hasTrainMatrix ignite (hastable-to-cache ht))
(my-lexical/is-eq? (get ht "schema_name") ds-name) (MyTrianDataUtil/hasTrainMatrix ignite (hastable-to-cache ht))
:else (throw (Exception. "不能在其它非公共数据集下面查询机器学习的训练数据!")))
:else
(throw (Exception. "不存在机器学习的训练数据!"))
)
))
(defn drop-train-matrix [^Ignite ignite group_id ^Hashtable ht]
(let [ds-name (second group_id)]
(cond
(and (my-lexical/is-eq? ds-name "MY_META") (contains? ht "schema_name") (not (my-lexical/is-eq? (get ht "schema_name") "MY_META"))) (MyTrianDataUtil/dropTrainMatrix ignite (hastable-to-cache ht))
(not (contains? ht "schema_name")) (MyTrianDataUtil/dropTrainMatrix ignite (hastable-to-cache (doto ht (.put "schema_name" (str/lower-case ds-name)))))
(contains? ht "schema_name") (cond (my-lexical/is-eq? (get ht "schema_name") "public") (MyTrianDataUtil/dropTrainMatrix ignite (hastable-to-cache ht))
(my-lexical/is-eq? (get ht "schema_name") ds-name) (MyTrianDataUtil/dropTrainMatrix ignite (hastable-to-cache ht))
:else (throw (Exception. "不能在其它非公共数据集下面删除机器学习的训练数据!")))
:else
(throw (Exception. "不存在机器学习的训练数据!"))
)
))
为分布式矩阵添加数据
(defn train-matrix [^Ignite ignite group_id ^Hashtable ht]
(let [ds-name (second group_id)]
(cond
(and (my-lexical/is-eq? ds-name "MY_META") (contains? ht "schema_name") (not (my-lexical/is-eq? (get ht "schema_name") "MY_META"))) (ml-train-matrix ignite ht)
(not (contains? ht "schema_name")) (ml-train-matrix ignite (hastable-to-cache (doto ht (.put "schema_name" (str/lower-case ds-name)))))
(contains? ht "schema_name") (cond (my-lexical/is-eq? (get ht "schema_name") "public") (ml-train-matrix ignite ht)
(my-lexical/is-eq? (get ht "schema_name") ds-name) (ml-train-matrix ignite ht)
:else (throw (Exception. "不能在其它非公共数据集下面添加机器学习的训练数据!")))
:else
(throw (Exception. "不存在机器学习的训练数据!"))
)
))
为分布式矩阵添加数据 -- 在 load csv 中使用
(defn train-matrix-single [^Ignite ignite group_id ^Hashtable ht]
(let [ds-name (second group_id)]
(cond
(and (my-lexical/is-eq? ds-name "MY_META") (contains? ht "schema_name") (not (my-lexical/is-eq? (get ht "schema_name") "MY_META"))) (ml-train-matrix-single ignite ht)
(not (contains? ht "schema_name")) (ml-train-matrix-single ignite (hastable-to-cache (doto ht (.put "schema_name" (str/lower-case ds-name)))))
(contains? ht "schema_name") (cond (my-lexical/is-eq? (get ht "schema_name") "public") (ml-train-matrix-single ignite ht)
(my-lexical/is-eq? (get ht "schema_name") ds-name) (ml-train-matrix-single ignite ht)
:else (throw (Exception. "不能在其它非公共数据集下面添加机器学习的训练数据!")))
:else
(throw (Exception. "不存在机器学习的训练数据!"))
)
))
( defn -myDoubleTest [ item lst ]
( [ ( to - double [ m ]
( MyConvertUtil / ConvertToDouble m ) ) ]
|
e118572ba614b3d63f14347f62ce3ec69b0e53e2a83d7f0d9c844460cc398708 | 2600hz-archive/whistle | erlydtl_dateformat.erl | -module(erlydtl_dateformat).
-export([format/1, format/2]).
-define(TAG_SUPPORTED(C),
C =:= $a orelse
C =:= $A orelse
C =:= $b orelse
C =:= $B orelse
C =:= $c orelse
C =:= $d orelse
C =:= $D orelse
C =:= $f orelse
C =:= $F orelse
C =:= $g orelse
C =:= $G orelse
C =:= $h orelse
C =:= $H orelse
C =:= $i orelse
C =:= $I orelse
C =:= $j orelse
C =:= $l orelse
C =:= $L orelse
C =:= $m orelse
C =:= $M orelse
C =:= $n orelse
C =:= $N orelse
C =:= $O orelse
C =:= $P orelse
C =:= $r orelse
C =:= $s orelse
C =:= $S orelse
C =:= $t orelse
C =:= $T orelse
C =:= $U orelse
C =:= $w orelse
C =:= $W orelse
C =:= $y orelse
C =:= $Y orelse
C =:= $z orelse
C =:= $Z
).
%
% Format the current date/time
%
format(FormatString) ->
{Date, Time} = erlang:localtime(),
replace_tags(Date, Time, FormatString).
%
% Format a tuple of the form {{Y,M,D},{H,M,S}}
This is the format returned by erlang : ( )
% and other standard date/time BIFs
%
format({{_,_,_} = Date,{_,_,_} = Time}, FormatString) ->
replace_tags(Date, Time, FormatString);
%
% Format a tuple of the form {Y,M,D}
%
format({_,_,_} = Date, FormatString) ->
replace_tags(Date, {0,0,0}, FormatString);
format(DateTime, FormatString) ->
io:format("Unrecognised date paramater : ~p~n", [DateTime]),
FormatString.
replace_tags(Date, Time, Input) ->
replace_tags(Date, Time, Input, [], noslash).
replace_tags(_Date, _Time, [], Out, _State) ->
lists:reverse(Out);
replace_tags(Date, Time, [C|Rest], Out, noslash) when ?TAG_SUPPORTED(C) ->
replace_tags(Date, Time, Rest,
lists:reverse(tag_to_value(C, Date, Time)) ++ Out, noslash);
replace_tags(Date, Time, [$\\|Rest], Out, noslash) ->
replace_tags(Date, Time, Rest, Out, slash);
replace_tags(Date, Time, [C|Rest], Out, slash) ->
replace_tags(Date, Time, Rest, [C|Out], noslash);
replace_tags(Date, Time, [C|Rest], Out, _State) ->
replace_tags(Date, Time, Rest, [C|Out], noslash).
%-----------------------------------------------------------
Time formatting
%-----------------------------------------------------------
% 'a.m.' or 'p.m.'
tag_to_value($a, _, {H, _, _}) when H > 11 -> "p.m.";
tag_to_value($a, _, _) -> "a.m.";
% 'AM' or 'PM'
tag_to_value($A, _, {H, _, _}) when H > 11 -> "PM";
tag_to_value($A, _, _) -> "AM";
Swatch Internet time
tag_to_value($B, _, _) ->
NotImplementedError
% ISO 8601 Format.
tag_to_value($c, Date, Time) ->
tag_to_value($Y, Date, Time) ++
"-" ++ tag_to_value($m, Date, Time) ++
"-" ++ tag_to_value($d, Date, Time) ++
"T" ++ tag_to_value($H, Date, Time) ++
":" ++ tag_to_value($i, Date, Time) ++
":" ++ tag_to_value($s, Date, Time);
%
Time , in 12 - hour hours and minutes , with minutes
left off if they 're zero .
%
% Examples: '1', '1:30', '2:05', '2'
%
% Proprietary extension.
%
tag_to_value($f, Date, {H, 0, S}) ->
If min is zero then return the hour only
tag_to_value($g, Date, {H, 0, S});
tag_to_value($f, Date, Time) ->
% Otherwise return hours and mins
tag_to_value($g, Date, Time)
++ ":" ++ tag_to_value($i, Date, Time);
Hour , 12 - hour format without leading zeros ; i.e. ' 1 ' to ' 12 '
tag_to_value($g, _, {H,_,_}) ->
integer_to_list(hour_24to12(H));
Hour , 24 - hour format without leading zeros ; i.e. ' 0 ' to ' 23 '
tag_to_value($G, _, {H,_,_}) ->
integer_to_list(H);
Hour , 12 - hour format ; i.e. ' 01 ' to ' 12 '
tag_to_value($h, _, {H,_,_}) ->
integer_to_list_zerofill(integer_to_list(hour_24to12(H)));
Hour , 24 - hour format ; i.e. ' 00 ' to ' 23 '
tag_to_value($H, _, {H,_,_}) ->
integer_to_list_zerofill(H);
% Minutes; i.e. '00' to '59'
tag_to_value($i, _, {_,M,_}) ->
integer_to_list_zerofill(M);
Time , in 12 - hour hours , minutes and ' a.m. . ' , with minutes left off
if they 're zero and the strings ' midnight ' and ' noon ' if appropriate .
Examples : ' 1 a.m. ' , ' 1:30 p.m. ' , ' midnight ' , ' noon ' , ' 12:30 p.m. '
% Proprietary extension.
tag_to_value($P, _, {0, 0, _}) -> "midnight";
tag_to_value($P, _, {12, 0, _}) -> "noon";
tag_to_value($P, Date, Time) ->
tag_to_value($f, Date, Time)
++ " " ++ tag_to_value($a, Date, Time);
% Seconds; i.e. '00' to '59'
tag_to_value($s, _, {_,_,S}) ->
integer_to_list_zerofill(S);
%-----------------------------------------------------------
% Date formatting
%-----------------------------------------------------------
Month , textual , 3 letters , lowercase ; e.g. ' jan '
tag_to_value($b, {_,M,_}, _) ->
string:sub_string(monthname(M), 1, 3);
Day of the month , 2 digits with leading zeros ; i.e. ' 01 ' to ' 31 '
tag_to_value($d, {_, _, D}, _) ->
integer_to_list_zerofill(D);
Day of the week , textual , 3 letters ; e.g. ' Fri '
tag_to_value($D, Date, _) ->
Dow = calendar:day_of_the_week(Date),
ucfirst(string:sub_string(dayname(Dow), 1, 3));
Month , textual , long ; e.g. ' January '
tag_to_value($F, {_,M,_}, _) ->
ucfirst(monthname(M));
' 1 ' if Daylight Savings Time , ' 0 ' otherwise .
tag_to_value($I, _, _) ->
"TODO";
Day of the month without leading zeros ; i.e. ' 1 ' to ' 31 '
tag_to_value($j, {_, _, D}, _) ->
integer_to_list(D);
Day of the week , textual , long ; e.g. ' Friday '
tag_to_value($l, Date, _) ->
ucfirst(dayname(calendar:day_of_the_week(Date)));
Boolean for whether it is a leap year ; i.e. True or False
tag_to_value($L, {Y,_,_}, _) ->
case calendar:is_leap_year(Y) of
true -> "True";
_ -> "False"
end;
% Month; i.e. '01' to '12'
tag_to_value($m, {_, M, _}, _) ->
integer_to_list_zerofill(M);
Month , textual , 3 letters ; e.g. ' Jan '
tag_to_value($M, {_,M,_}, _) ->
ucfirst(string:sub_string(monthname(M), 1, 3));
Month without leading zeros ; i.e. ' 1 ' to ' 12 '
tag_to_value($n, {_, M, _}, _) ->
integer_to_list(M);
Month abbreviation in Associated Press style . Proprietary extension .
tag_to_value($N, {_,M,_}, _) when M =:= 9 ->
Special case - " Sept. "
ucfirst(string:sub_string(monthname(M), 1, 4)) ++ ".";
tag_to_value($N, {_,M,_}, _) when M < 3 orelse M > 7 ->
Jan , Feb , Aug , Oct , Nov , Dec are all
% abbreviated with a full-stop appended.
ucfirst(string:sub_string(monthname(M), 1, 3)) ++ ".";
tag_to_value($N, {_,M,_}, _) ->
% The rest are the fullname.
ucfirst(monthname(M));
Difference to Greenwich time in hours ; e.g. ' +0200 '
tag_to_value($O, Date, Time) ->
Diff = utc_diff(Date, Time),
Offset = if
Diff < 0 ->
io_lib:format("-~4..0w", [abs(Diff)]);
true ->
io_lib:format("+~4..0w", [Diff])
end,
lists:flatten(Offset);
RFC 2822 formatted date ; e.g. ' Thu , 21 Dec 2000 16:01:07 +0200 '
tag_to_value($r, Date, Time) ->
replace_tags(Date, Time, "D, j M Y H:i:s O");
English ordinal suffix for the day of the month , 2 characters ;
% i.e. 'st', 'nd', 'rd' or 'th'
tag_to_value($S, {_, _, D}, _) when
D rem 100 =:= 11 orelse
D rem 100 =:= 12 orelse
D rem 100 =:= 13 -> "th";
tag_to_value($S, {_, _, D}, _) when D rem 10 =:= 1 -> "st";
tag_to_value($S, {_, _, D}, _) when D rem 10 =:= 2 -> "nd";
tag_to_value($S, {_, _, D}, _) when D rem 10 =:= 3 -> "rd";
tag_to_value($S, _, _) -> "th";
Number of days in the given month ; i.e. ' 28 ' to ' 31 '
tag_to_value($t, {Y,M,_}, _) ->
integer_to_list(calendar:last_day_of_the_month(Y,M));
Time zone of this machine ; e.g. ' EST ' or ' MDT '
tag_to_value($T, _, _) ->
"TODO";
Seconds since the Unix epoch ( January 1 1970 00:00:00 GMT )
tag_to_value($U, Date, Time) ->
EpochSecs = calendar:datetime_to_gregorian_seconds({Date, Time})
- calendar:datetime_to_gregorian_seconds({{1970,1,1},{0,0,0}}),
integer_to_list(EpochSecs);
Day of the week , numeric , i.e. ' 0 ' ( Sunday ) to ' 6 ' ( Saturday )
tag_to_value($w, Date, _) ->
Note : calendar : day_of_the_week returns
1 | .. | 7 . Monday = 1 , Tuesday = 2 , ... , Sunday = 7
integer_to_list(calendar:day_of_the_week(Date) rem 7);
ISO-8601 week number of year , weeks starting on Monday
tag_to_value($W, {Y,M,D}, _) ->
integer_to_list(year_weeknum(Y,M,D));
Year , 2 digits ; e.g. ' 99 '
tag_to_value($y, {Y, _, _}, _) ->
string:sub_string(integer_to_list(Y), 3);
Year , 4 digits ; e.g. ' 1999 '
tag_to_value($Y, {Y, _, _}, _) ->
integer_to_list(Y);
% Day of the year; i.e. '0' to '365'
tag_to_value($z, {Y,M,D}, _) ->
integer_to_list(day_of_year(Y,M,D));
Time zone offset in seconds ( i.e. ' -43200 ' to ' 43200 ' ) . The offset for
% timezones west of UTC is always negative, and for those east of UTC is
% always positive.
tag_to_value($Z, _, _) ->
"TODO";
tag_to_value(C, Date, Time) ->
io:format("Unimplemented tag : ~p [Date : ~p] [Time : ~p]",
[C, Date, Time]),
"".
% Date helper functions
day_of_year(Y,M,D) ->
day_of_year(Y,M,D,0).
day_of_year(_Y,M,D,Count) when M =< 1 ->
D + Count;
day_of_year(Y,M,D,Count) when M =< 12 ->
day_of_year(Y, M - 1, D, Count + calendar:last_day_of_the_month(Y,M));
day_of_year(Y,_M,D,_Count) ->
day_of_year(Y, 12, D, 0).
hour_24to12(0) -> 12;
hour_24to12(H) when H < 13 -> H;
hour_24to12(H) when H < 24 -> H - 12;
hour_24to12(H) -> H.
year_weeknum(Y,M,D) ->
First = (calendar:day_of_the_week(Y, 1, 1) rem 7) - 1,
Wk = ((((calendar:date_to_gregorian_days(Y, M, D) -
calendar:date_to_gregorian_days(Y, 1, 1)) + First) div 7)
+ (case First < 4 of true -> 1; _ -> 0 end)),
case Wk of
0 -> weeks_in_year(Y - 1);
_ -> case weeks_in_year(Y) of
WksInThisYear when Wk > WksInThisYear -> 1;
_ -> Wk
end
end.
weeks_in_year(Y) ->
D1 = calendar:day_of_the_week(Y, 1, 1),
D2 = calendar:day_of_the_week(Y, 12, 31),
if (D1 =:= 4 orelse D2 =:= 4) -> 53; true -> 52 end.
utc_diff({Y, M, D}, Time) when Y < 1970->
utc_diff({1970, M, D}, Time);
utc_diff(Date, Time) ->
LTime = {Date, Time},
UTime = erlang:localtime_to_universaltime(LTime),
DiffSecs = calendar:datetime_to_gregorian_seconds(LTime) -
calendar:datetime_to_gregorian_seconds(UTime),
trunc((DiffSecs / 3600) * 100).
dayname(1) -> "monday";
dayname(2) -> "tuesday";
dayname(3) -> "wednesday";
dayname(4) -> "thursday";
dayname(5) -> "friday";
dayname(6) -> "saturday";
dayname(7) -> "sunday";
dayname(_) -> "???".
monthname(1) -> "january";
monthname(2) -> "february";
monthname(3) -> "march";
monthname(4) -> "april";
monthname(5) -> "may";
monthname(6) -> "june";
monthname(7) -> "july";
monthname(8) -> "august";
monthname(9) -> "september";
monthname(10) -> "october";
monthname(11) -> "november";
monthname(12) -> "december";
monthname(_) -> "???".
% Utility functions
integer_to_list_zerofill(N) when N < 10 ->
lists:flatten(io_lib:format("~2..0B", [N]));
integer_to_list_zerofill(N) ->
integer_to_list(N).
ucfirst([First | Rest]) when First >= $a, First =< $z ->
[First-($a-$A) | Rest];
ucfirst(Other) ->
Other.
| null | https://raw.githubusercontent.com/2600hz-archive/whistle/1a256604f0d037fac409ad5a55b6b17e545dcbf9/lib/erlydtl-0.7.0/src/filter_lib/erlydtl_dateformat.erl | erlang |
Format the current date/time
Format a tuple of the form {{Y,M,D},{H,M,S}}
and other standard date/time BIFs
Format a tuple of the form {Y,M,D}
-----------------------------------------------------------
-----------------------------------------------------------
'a.m.' or 'p.m.'
'AM' or 'PM'
ISO 8601 Format.
Examples: '1', '1:30', '2:05', '2'
Proprietary extension.
Otherwise return hours and mins
Minutes; i.e. '00' to '59'
Proprietary extension.
Seconds; i.e. '00' to '59'
-----------------------------------------------------------
Date formatting
-----------------------------------------------------------
Month; i.e. '01' to '12'
abbreviated with a full-stop appended.
The rest are the fullname.
i.e. 'st', 'nd', 'rd' or 'th'
Day of the year; i.e. '0' to '365'
timezones west of UTC is always negative, and for those east of UTC is
always positive.
Date helper functions
Utility functions | -module(erlydtl_dateformat).
-export([format/1, format/2]).
-define(TAG_SUPPORTED(C),
C =:= $a orelse
C =:= $A orelse
C =:= $b orelse
C =:= $B orelse
C =:= $c orelse
C =:= $d orelse
C =:= $D orelse
C =:= $f orelse
C =:= $F orelse
C =:= $g orelse
C =:= $G orelse
C =:= $h orelse
C =:= $H orelse
C =:= $i orelse
C =:= $I orelse
C =:= $j orelse
C =:= $l orelse
C =:= $L orelse
C =:= $m orelse
C =:= $M orelse
C =:= $n orelse
C =:= $N orelse
C =:= $O orelse
C =:= $P orelse
C =:= $r orelse
C =:= $s orelse
C =:= $S orelse
C =:= $t orelse
C =:= $T orelse
C =:= $U orelse
C =:= $w orelse
C =:= $W orelse
C =:= $y orelse
C =:= $Y orelse
C =:= $z orelse
C =:= $Z
).
format(FormatString) ->
{Date, Time} = erlang:localtime(),
replace_tags(Date, Time, FormatString).
This is the format returned by erlang : ( )
format({{_,_,_} = Date,{_,_,_} = Time}, FormatString) ->
replace_tags(Date, Time, FormatString);
format({_,_,_} = Date, FormatString) ->
replace_tags(Date, {0,0,0}, FormatString);
format(DateTime, FormatString) ->
io:format("Unrecognised date paramater : ~p~n", [DateTime]),
FormatString.
replace_tags(Date, Time, Input) ->
replace_tags(Date, Time, Input, [], noslash).
replace_tags(_Date, _Time, [], Out, _State) ->
lists:reverse(Out);
replace_tags(Date, Time, [C|Rest], Out, noslash) when ?TAG_SUPPORTED(C) ->
replace_tags(Date, Time, Rest,
lists:reverse(tag_to_value(C, Date, Time)) ++ Out, noslash);
replace_tags(Date, Time, [$\\|Rest], Out, noslash) ->
replace_tags(Date, Time, Rest, Out, slash);
replace_tags(Date, Time, [C|Rest], Out, slash) ->
replace_tags(Date, Time, Rest, [C|Out], noslash);
replace_tags(Date, Time, [C|Rest], Out, _State) ->
replace_tags(Date, Time, Rest, [C|Out], noslash).
Time formatting
tag_to_value($a, _, {H, _, _}) when H > 11 -> "p.m.";
tag_to_value($a, _, _) -> "a.m.";
tag_to_value($A, _, {H, _, _}) when H > 11 -> "PM";
tag_to_value($A, _, _) -> "AM";
Swatch Internet time
tag_to_value($B, _, _) ->
NotImplementedError
tag_to_value($c, Date, Time) ->
tag_to_value($Y, Date, Time) ++
"-" ++ tag_to_value($m, Date, Time) ++
"-" ++ tag_to_value($d, Date, Time) ++
"T" ++ tag_to_value($H, Date, Time) ++
":" ++ tag_to_value($i, Date, Time) ++
":" ++ tag_to_value($s, Date, Time);
Time , in 12 - hour hours and minutes , with minutes
left off if they 're zero .
tag_to_value($f, Date, {H, 0, S}) ->
If min is zero then return the hour only
tag_to_value($g, Date, {H, 0, S});
tag_to_value($f, Date, Time) ->
tag_to_value($g, Date, Time)
++ ":" ++ tag_to_value($i, Date, Time);
Hour , 12 - hour format without leading zeros ; i.e. ' 1 ' to ' 12 '
tag_to_value($g, _, {H,_,_}) ->
integer_to_list(hour_24to12(H));
Hour , 24 - hour format without leading zeros ; i.e. ' 0 ' to ' 23 '
tag_to_value($G, _, {H,_,_}) ->
integer_to_list(H);
Hour , 12 - hour format ; i.e. ' 01 ' to ' 12 '
tag_to_value($h, _, {H,_,_}) ->
integer_to_list_zerofill(integer_to_list(hour_24to12(H)));
Hour , 24 - hour format ; i.e. ' 00 ' to ' 23 '
tag_to_value($H, _, {H,_,_}) ->
integer_to_list_zerofill(H);
tag_to_value($i, _, {_,M,_}) ->
integer_to_list_zerofill(M);
Time , in 12 - hour hours , minutes and ' a.m. . ' , with minutes left off
if they 're zero and the strings ' midnight ' and ' noon ' if appropriate .
Examples : ' 1 a.m. ' , ' 1:30 p.m. ' , ' midnight ' , ' noon ' , ' 12:30 p.m. '
tag_to_value($P, _, {0, 0, _}) -> "midnight";
tag_to_value($P, _, {12, 0, _}) -> "noon";
tag_to_value($P, Date, Time) ->
tag_to_value($f, Date, Time)
++ " " ++ tag_to_value($a, Date, Time);
tag_to_value($s, _, {_,_,S}) ->
integer_to_list_zerofill(S);
Month , textual , 3 letters , lowercase ; e.g. ' jan '
tag_to_value($b, {_,M,_}, _) ->
string:sub_string(monthname(M), 1, 3);
Day of the month , 2 digits with leading zeros ; i.e. ' 01 ' to ' 31 '
tag_to_value($d, {_, _, D}, _) ->
integer_to_list_zerofill(D);
Day of the week , textual , 3 letters ; e.g. ' Fri '
tag_to_value($D, Date, _) ->
Dow = calendar:day_of_the_week(Date),
ucfirst(string:sub_string(dayname(Dow), 1, 3));
Month , textual , long ; e.g. ' January '
tag_to_value($F, {_,M,_}, _) ->
ucfirst(monthname(M));
' 1 ' if Daylight Savings Time , ' 0 ' otherwise .
tag_to_value($I, _, _) ->
"TODO";
Day of the month without leading zeros ; i.e. ' 1 ' to ' 31 '
tag_to_value($j, {_, _, D}, _) ->
integer_to_list(D);
Day of the week , textual , long ; e.g. ' Friday '
tag_to_value($l, Date, _) ->
ucfirst(dayname(calendar:day_of_the_week(Date)));
Boolean for whether it is a leap year ; i.e. True or False
tag_to_value($L, {Y,_,_}, _) ->
case calendar:is_leap_year(Y) of
true -> "True";
_ -> "False"
end;
tag_to_value($m, {_, M, _}, _) ->
integer_to_list_zerofill(M);
Month , textual , 3 letters ; e.g. ' Jan '
tag_to_value($M, {_,M,_}, _) ->
ucfirst(string:sub_string(monthname(M), 1, 3));
Month without leading zeros ; i.e. ' 1 ' to ' 12 '
tag_to_value($n, {_, M, _}, _) ->
integer_to_list(M);
Month abbreviation in Associated Press style . Proprietary extension .
tag_to_value($N, {_,M,_}, _) when M =:= 9 ->
Special case - " Sept. "
ucfirst(string:sub_string(monthname(M), 1, 4)) ++ ".";
tag_to_value($N, {_,M,_}, _) when M < 3 orelse M > 7 ->
Jan , Feb , Aug , Oct , Nov , Dec are all
ucfirst(string:sub_string(monthname(M), 1, 3)) ++ ".";
tag_to_value($N, {_,M,_}, _) ->
ucfirst(monthname(M));
Difference to Greenwich time in hours ; e.g. ' +0200 '
tag_to_value($O, Date, Time) ->
Diff = utc_diff(Date, Time),
Offset = if
Diff < 0 ->
io_lib:format("-~4..0w", [abs(Diff)]);
true ->
io_lib:format("+~4..0w", [Diff])
end,
lists:flatten(Offset);
RFC 2822 formatted date ; e.g. ' Thu , 21 Dec 2000 16:01:07 +0200 '
tag_to_value($r, Date, Time) ->
replace_tags(Date, Time, "D, j M Y H:i:s O");
English ordinal suffix for the day of the month , 2 characters ;
tag_to_value($S, {_, _, D}, _) when
D rem 100 =:= 11 orelse
D rem 100 =:= 12 orelse
D rem 100 =:= 13 -> "th";
tag_to_value($S, {_, _, D}, _) when D rem 10 =:= 1 -> "st";
tag_to_value($S, {_, _, D}, _) when D rem 10 =:= 2 -> "nd";
tag_to_value($S, {_, _, D}, _) when D rem 10 =:= 3 -> "rd";
tag_to_value($S, _, _) -> "th";
Number of days in the given month ; i.e. ' 28 ' to ' 31 '
tag_to_value($t, {Y,M,_}, _) ->
integer_to_list(calendar:last_day_of_the_month(Y,M));
Time zone of this machine ; e.g. ' EST ' or ' MDT '
tag_to_value($T, _, _) ->
"TODO";
Seconds since the Unix epoch ( January 1 1970 00:00:00 GMT )
tag_to_value($U, Date, Time) ->
EpochSecs = calendar:datetime_to_gregorian_seconds({Date, Time})
- calendar:datetime_to_gregorian_seconds({{1970,1,1},{0,0,0}}),
integer_to_list(EpochSecs);
Day of the week , numeric , i.e. ' 0 ' ( Sunday ) to ' 6 ' ( Saturday )
tag_to_value($w, Date, _) ->
Note : calendar : day_of_the_week returns
1 | .. | 7 . Monday = 1 , Tuesday = 2 , ... , Sunday = 7
integer_to_list(calendar:day_of_the_week(Date) rem 7);
ISO-8601 week number of year , weeks starting on Monday
tag_to_value($W, {Y,M,D}, _) ->
integer_to_list(year_weeknum(Y,M,D));
Year , 2 digits ; e.g. ' 99 '
tag_to_value($y, {Y, _, _}, _) ->
string:sub_string(integer_to_list(Y), 3);
Year , 4 digits ; e.g. ' 1999 '
tag_to_value($Y, {Y, _, _}, _) ->
integer_to_list(Y);
tag_to_value($z, {Y,M,D}, _) ->
integer_to_list(day_of_year(Y,M,D));
Time zone offset in seconds ( i.e. ' -43200 ' to ' 43200 ' ) . The offset for
tag_to_value($Z, _, _) ->
"TODO";
tag_to_value(C, Date, Time) ->
io:format("Unimplemented tag : ~p [Date : ~p] [Time : ~p]",
[C, Date, Time]),
"".
day_of_year(Y,M,D) ->
day_of_year(Y,M,D,0).
day_of_year(_Y,M,D,Count) when M =< 1 ->
D + Count;
day_of_year(Y,M,D,Count) when M =< 12 ->
day_of_year(Y, M - 1, D, Count + calendar:last_day_of_the_month(Y,M));
day_of_year(Y,_M,D,_Count) ->
day_of_year(Y, 12, D, 0).
hour_24to12(0) -> 12;
hour_24to12(H) when H < 13 -> H;
hour_24to12(H) when H < 24 -> H - 12;
hour_24to12(H) -> H.
year_weeknum(Y,M,D) ->
First = (calendar:day_of_the_week(Y, 1, 1) rem 7) - 1,
Wk = ((((calendar:date_to_gregorian_days(Y, M, D) -
calendar:date_to_gregorian_days(Y, 1, 1)) + First) div 7)
+ (case First < 4 of true -> 1; _ -> 0 end)),
case Wk of
0 -> weeks_in_year(Y - 1);
_ -> case weeks_in_year(Y) of
WksInThisYear when Wk > WksInThisYear -> 1;
_ -> Wk
end
end.
weeks_in_year(Y) ->
D1 = calendar:day_of_the_week(Y, 1, 1),
D2 = calendar:day_of_the_week(Y, 12, 31),
if (D1 =:= 4 orelse D2 =:= 4) -> 53; true -> 52 end.
utc_diff({Y, M, D}, Time) when Y < 1970->
utc_diff({1970, M, D}, Time);
utc_diff(Date, Time) ->
LTime = {Date, Time},
UTime = erlang:localtime_to_universaltime(LTime),
DiffSecs = calendar:datetime_to_gregorian_seconds(LTime) -
calendar:datetime_to_gregorian_seconds(UTime),
trunc((DiffSecs / 3600) * 100).
dayname(1) -> "monday";
dayname(2) -> "tuesday";
dayname(3) -> "wednesday";
dayname(4) -> "thursday";
dayname(5) -> "friday";
dayname(6) -> "saturday";
dayname(7) -> "sunday";
dayname(_) -> "???".
monthname(1) -> "january";
monthname(2) -> "february";
monthname(3) -> "march";
monthname(4) -> "april";
monthname(5) -> "may";
monthname(6) -> "june";
monthname(7) -> "july";
monthname(8) -> "august";
monthname(9) -> "september";
monthname(10) -> "october";
monthname(11) -> "november";
monthname(12) -> "december";
monthname(_) -> "???".
integer_to_list_zerofill(N) when N < 10 ->
lists:flatten(io_lib:format("~2..0B", [N]));
integer_to_list_zerofill(N) ->
integer_to_list(N).
ucfirst([First | Rest]) when First >= $a, First =< $z ->
[First-($a-$A) | Rest];
ucfirst(Other) ->
Other.
|
8a3e0e2e0ab2be5fbd28bfe44e36d3d79d680cb6eb28f1609f8769e58c1cfab5 | Lambda-X/re-console | parinfer.cljs | (ns re-console.parinfer
"Glues Parinfer's formatter to a CodeMirror editor"
(:require [clojure.string :refer [join]]
[re-frame.core :refer [subscribe dispatch dispatch-sync]]
[parinfer.indent-mode :as indent-mode]
[parinfer.paren-mode :as paren-mode]
[re-console.common :as common]))
;;; Editor support
(defn update-cursor-fn
"Correctly position cursor after text that was just typed.
We need this since reformatting the text can shift things forward past our cursor."
[console-key]
(let [cm (subscribe [:get-console console-key])]
(fn [change]
(when (= "+input" (.-origin change))
(let [selection? (.somethingSelected @cm)
text (join "\n" (.-text change))
from-x (.. change -from -ch)
line-no (.. change -from -line)
line (.getLine @cm line-no)
insert-x (.indexOf line text from-x)
after-x (+ insert-x (count text))]
(cond
;; something is selected, don't touch the cursor
selection?
nil
;; pressing return, keep current position then.
(= text "\n")
nil
;; only move the semicolon ahead since it can be pushed forward by
;; commenting out inferred parens meaning they are immediately
;; reinserted behind it.
(= text ";")
(.setCursor @cm line-no after-x)
;; typed character not found where expected it, we probably prevented it. keep cursor where it was.
(or (= -1 insert-x)
(> insert-x from-x))
(.setCursor @cm line-no from-x)
:else nil))))))
(defn compute-cursor-dx
[cursor change]
(when change
(let [;; This is a hack for codemirror.
;; For some reason codemirror triggers an "+input" change after the
;; indent spaces are already applied. So I modified codemirror to
;; label these changes as +indenthack so we can ignore them.
ignore? (= "+indenthack" (.-origin change))]
(if ignore?
0
(let [start-x (.. change -to -ch)
new-lines (.. change -text)
len-last-line (count (last new-lines))
end-x (if (> (count new-lines) 1)
len-last-line
(+ len-last-line (.. change -from -ch)))]
(- end-x start-x))))))
(defn compute-cm-change
[cm change options prev-state]
(let [{:keys [start-line end-line num-new-lines]}
(if change
{:start-line (.. change -from -line)
:end-line (inc (.. change -to -line))
:num-new-lines (alength (.-text change))}
(let [start (:cursor-line prev-state)
end (inc start)]
{:start-line start
:end-line end
:num-new-lines (- end start)}))
lines (for [i (range start-line (+ start-line num-new-lines))]
(.getLine cm i))]
{:line-no [start-line end-line]
:new-line lines}))
(defn fix-text-fn
"Correctly format the text from the given editor."
[console-key]
(let [cm (subscribe [:get-console console-key])
mode (subscribe [:get-console-mode console-key])
eval-opts (subscribe [:get-console-eval-opts console-key])
prev-state (atom nil)]
(fn [& {:keys [change use-cache?]
:or {change nil, use-cache? false}}]
(let [current-text (.getValue @cm)
selection? (.somethingSelected @cm)
selections (.listSelections @cm)
cursor (.getCursor @cm)
scroller (.getScrollerElement @cm)
scroll-x (.-scrollLeft scroller)
scroll-y (.-scrollTop scroller)
options {:cursor-line (.-line cursor)
:cursor-x (.-ch cursor)
:cursor-dx (compute-cursor-dx cursor change)}
new-text (case @mode
:indent-mode
(let [result (if (and use-cache? @prev-state)
(indent-mode/format-text-change
current-text
@prev-state
(compute-cm-change @cm change options @prev-state)
options)
(indent-mode/format-text current-text options))]
(when (:valid? result)
(reset! prev-state (:state result)))
(:text result))
:paren-mode
(let [result (paren-mode/format-text current-text options)]
(:text result))
nil)]
(dispatch [:console-set-text console-key (common/source-without-prompt new-text)])
(.setValue @cm (str ((:get-prompt @eval-opts)) (common/source-without-prompt new-text)))
;; restore the selection, cursor, and scroll
;; since these are reset when overwriting codemirror's value.
(if selection?
(.setSelections @cm selections)
(.setCursor @cm cursor))
(.scrollTo @cm scroll-x scroll-y)))))
;; NOTE:
;; Text is either updated after a change in text or
;; a cursor movement, but not both.
;; When typing, on-change is called, then on-cursor-activity.
;; So we prevent updating the text twice by using an update flag.
(defn before-change
"Called before any change is applied to the editor."
[cm change]
keep CodeMirror from reacting to a change from " "
;; if it is not a new value.
(when (and (= "setValue" (.-origin change))
(= (.getValue cm) (join "\n" (.-text change))))
(.cancel change)))
(defn on-change
"Called after any change is applied to the editor."
[console-key]
(let [fix-text! (fix-text-fn console-key)
update-cursor! (update-cursor-fn console-key)
mode (subscribe [:get-console-mode console-key])
on-before-change (subscribe [:get-console-on-before-change console-key])
on-after-change (subscribe [:get-console-on-after-change console-key])]
(fn [inst change]
(when-not (= :none @mode)
(when (not= "setValue" (.-origin change))
(when @on-before-change
(@on-before-change inst change))
(fix-text! :change change)
(update-cursor! change)
(dispatch-sync [:set-console-frame-updated console-key true])
(when @on-after-change
(@on-after-change inst change)))))))
(defn on-cursor-activity
"Called after the cursor moves in the editor."
[console-key]
(let [frame-updated? (subscribe [:get-console-frame-updated console-key])
fix-text! (fix-text-fn console-key)
mode (subscribe [:get-console-mode console-key])
on-before-change (subscribe [:get-console-on-before-change console-key])
on-after-change (subscribe [:get-console-on-after-change console-key])]
(fn [inst evt]
(when-not (= :none @mode)
(when-not @frame-updated?
(when @on-before-change
(@on-before-change inst evt))
(fix-text!)
(when @on-after-change
(@on-after-change inst evt)))
(dispatch-sync [:set-console-frame-updated console-key false])))))
(defn parinferize!
"Add parinfer goodness to a codemirror editor"
[cm console-key]
(.on cm "change" (on-change console-key))
(.on cm "beforeChange" before-change))
| null | https://raw.githubusercontent.com/Lambda-X/re-console/a7a31046ba5066163d46ac586072c92b7414c52b/src/re_console/parinfer.cljs | clojure | Editor support
something is selected, don't touch the cursor
pressing return, keep current position then.
only move the semicolon ahead since it can be pushed forward by
commenting out inferred parens meaning they are immediately
reinserted behind it.
typed character not found where expected it, we probably prevented it. keep cursor where it was.
This is a hack for codemirror.
For some reason codemirror triggers an "+input" change after the
indent spaces are already applied. So I modified codemirror to
label these changes as +indenthack so we can ignore them.
restore the selection, cursor, and scroll
since these are reset when overwriting codemirror's value.
NOTE:
Text is either updated after a change in text or
a cursor movement, but not both.
When typing, on-change is called, then on-cursor-activity.
So we prevent updating the text twice by using an update flag.
if it is not a new value. | (ns re-console.parinfer
"Glues Parinfer's formatter to a CodeMirror editor"
(:require [clojure.string :refer [join]]
[re-frame.core :refer [subscribe dispatch dispatch-sync]]
[parinfer.indent-mode :as indent-mode]
[parinfer.paren-mode :as paren-mode]
[re-console.common :as common]))
(defn update-cursor-fn
"Correctly position cursor after text that was just typed.
We need this since reformatting the text can shift things forward past our cursor."
[console-key]
(let [cm (subscribe [:get-console console-key])]
(fn [change]
(when (= "+input" (.-origin change))
(let [selection? (.somethingSelected @cm)
text (join "\n" (.-text change))
from-x (.. change -from -ch)
line-no (.. change -from -line)
line (.getLine @cm line-no)
insert-x (.indexOf line text from-x)
after-x (+ insert-x (count text))]
(cond
selection?
nil
(= text "\n")
nil
(= text ";")
(.setCursor @cm line-no after-x)
(or (= -1 insert-x)
(> insert-x from-x))
(.setCursor @cm line-no from-x)
:else nil))))))
(defn compute-cursor-dx
[cursor change]
(when change
ignore? (= "+indenthack" (.-origin change))]
(if ignore?
0
(let [start-x (.. change -to -ch)
new-lines (.. change -text)
len-last-line (count (last new-lines))
end-x (if (> (count new-lines) 1)
len-last-line
(+ len-last-line (.. change -from -ch)))]
(- end-x start-x))))))
(defn compute-cm-change
[cm change options prev-state]
(let [{:keys [start-line end-line num-new-lines]}
(if change
{:start-line (.. change -from -line)
:end-line (inc (.. change -to -line))
:num-new-lines (alength (.-text change))}
(let [start (:cursor-line prev-state)
end (inc start)]
{:start-line start
:end-line end
:num-new-lines (- end start)}))
lines (for [i (range start-line (+ start-line num-new-lines))]
(.getLine cm i))]
{:line-no [start-line end-line]
:new-line lines}))
(defn fix-text-fn
"Correctly format the text from the given editor."
[console-key]
(let [cm (subscribe [:get-console console-key])
mode (subscribe [:get-console-mode console-key])
eval-opts (subscribe [:get-console-eval-opts console-key])
prev-state (atom nil)]
(fn [& {:keys [change use-cache?]
:or {change nil, use-cache? false}}]
(let [current-text (.getValue @cm)
selection? (.somethingSelected @cm)
selections (.listSelections @cm)
cursor (.getCursor @cm)
scroller (.getScrollerElement @cm)
scroll-x (.-scrollLeft scroller)
scroll-y (.-scrollTop scroller)
options {:cursor-line (.-line cursor)
:cursor-x (.-ch cursor)
:cursor-dx (compute-cursor-dx cursor change)}
new-text (case @mode
:indent-mode
(let [result (if (and use-cache? @prev-state)
(indent-mode/format-text-change
current-text
@prev-state
(compute-cm-change @cm change options @prev-state)
options)
(indent-mode/format-text current-text options))]
(when (:valid? result)
(reset! prev-state (:state result)))
(:text result))
:paren-mode
(let [result (paren-mode/format-text current-text options)]
(:text result))
nil)]
(dispatch [:console-set-text console-key (common/source-without-prompt new-text)])
(.setValue @cm (str ((:get-prompt @eval-opts)) (common/source-without-prompt new-text)))
(if selection?
(.setSelections @cm selections)
(.setCursor @cm cursor))
(.scrollTo @cm scroll-x scroll-y)))))
(defn before-change
"Called before any change is applied to the editor."
[cm change]
keep CodeMirror from reacting to a change from " "
(when (and (= "setValue" (.-origin change))
(= (.getValue cm) (join "\n" (.-text change))))
(.cancel change)))
(defn on-change
"Called after any change is applied to the editor."
[console-key]
(let [fix-text! (fix-text-fn console-key)
update-cursor! (update-cursor-fn console-key)
mode (subscribe [:get-console-mode console-key])
on-before-change (subscribe [:get-console-on-before-change console-key])
on-after-change (subscribe [:get-console-on-after-change console-key])]
(fn [inst change]
(when-not (= :none @mode)
(when (not= "setValue" (.-origin change))
(when @on-before-change
(@on-before-change inst change))
(fix-text! :change change)
(update-cursor! change)
(dispatch-sync [:set-console-frame-updated console-key true])
(when @on-after-change
(@on-after-change inst change)))))))
(defn on-cursor-activity
"Called after the cursor moves in the editor."
[console-key]
(let [frame-updated? (subscribe [:get-console-frame-updated console-key])
fix-text! (fix-text-fn console-key)
mode (subscribe [:get-console-mode console-key])
on-before-change (subscribe [:get-console-on-before-change console-key])
on-after-change (subscribe [:get-console-on-after-change console-key])]
(fn [inst evt]
(when-not (= :none @mode)
(when-not @frame-updated?
(when @on-before-change
(@on-before-change inst evt))
(fix-text!)
(when @on-after-change
(@on-after-change inst evt)))
(dispatch-sync [:set-console-frame-updated console-key false])))))
(defn parinferize!
"Add parinfer goodness to a codemirror editor"
[cm console-key]
(.on cm "change" (on-change console-key))
(.on cm "beforeChange" before-change))
|
e2ad9c706b477be3ce657b93ef87bd439b21bc04e47ccf3258c29938f74e2db8 | fission-codes/fission | Types.hs | -- | App configuration for AWS
module Fission.Web.Server.Environment.AWS.Types (Environment (..)) where
import qualified Network.AWS.Auth as AWS
import Fission.Prelude
import qualified Fission.Web.Server.AWS.Types as AWS
data Environment
= Environment
{ accessKey :: AWS.AccessKey -- ^ Access Key
, secretKey :: AWS.SecretKey -- ^ Secret Key
, baseZoneID :: AWS.ZoneID -- ^ Hosted Zone of
, mockRoute53 :: AWS.MockRoute53
}
deriving Eq
instance Show Environment where
show Environment {..} = intercalate "\n"
[ "Environment {"
, " accessKey = HIDDEN"
, " secretKey = HIDDEN"
, " baseZoneId = " <> show baseZoneID
, " mockRoute53 = " <> show mockRoute53
, "}"
]
instance FromJSON Environment where
parseJSON = withObject "AWS.Environment" \obj -> do
accessKey <- obj .: "access_key"
secretKey <- obj .: "secret_key"
baseZoneID <- obj .: "zone_id"
mockRoute53 <- obj .:? "mock_route53" .!= AWS.MockRoute53 False
return Environment {..}
| null | https://raw.githubusercontent.com/fission-codes/fission/11d14b729ccebfd69499a534445fb072ac3433a3/fission-web-server/library/Fission/Web/Server/Environment/AWS/Types.hs | haskell | | App configuration for AWS
^ Access Key
^ Secret Key
^ Hosted Zone of | module Fission.Web.Server.Environment.AWS.Types (Environment (..)) where
import qualified Network.AWS.Auth as AWS
import Fission.Prelude
import qualified Fission.Web.Server.AWS.Types as AWS
data Environment
= Environment
, mockRoute53 :: AWS.MockRoute53
}
deriving Eq
instance Show Environment where
show Environment {..} = intercalate "\n"
[ "Environment {"
, " accessKey = HIDDEN"
, " secretKey = HIDDEN"
, " baseZoneId = " <> show baseZoneID
, " mockRoute53 = " <> show mockRoute53
, "}"
]
instance FromJSON Environment where
parseJSON = withObject "AWS.Environment" \obj -> do
accessKey <- obj .: "access_key"
secretKey <- obj .: "secret_key"
baseZoneID <- obj .: "zone_id"
mockRoute53 <- obj .:? "mock_route53" .!= AWS.MockRoute53 False
return Environment {..}
|
c3bbceb749d669ce26a0d067055f9ed1d89afa115edf06bb080769fa81ac4e73 | yallop/ocaml-ctypes | driver.ml |
* Copyright ( c ) 2014 .
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2014 Jeremy Yallop.
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
(* Stub generation driver for the value printing tests. *)
let () = Tests_common.run Sys.argv (module Functions.Stubs)
| null | https://raw.githubusercontent.com/yallop/ocaml-ctypes/52ff621f47dbc1ee5a90c30af0ae0474549946b4/tests/test-value_printing/stub-generator/driver.ml | ocaml | Stub generation driver for the value printing tests. |
* Copyright ( c ) 2014 .
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2014 Jeremy Yallop.
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
let () = Tests_common.run Sys.argv (module Functions.Stubs)
|
0a345d165045a8e1ee2f439c5a7c4ca20042bc44316fcf6915ba68f19bbcbc09 | aumouvantsillage/Virgule-CPU | register_unit.rkt | 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 /.
#lang racket
(require
rackunit
(except-in hydromel/support zero)
"../cpu/common.mel"
"../cpu/decoder.mel"
"../cpu/register_unit.mel"
"../asm/assembler.rkt")
(define (write-value n)
(* #x1000 (add1 n)))
(define (read-value n)
(if (zero? n)
0
(write-value n)))
(define (write-test-case rd)
; src-instr dest-instr enable xd xs1 xs2
(list (ADD 0 rd rd) (ADD rd 0 0) 1 (write-value rd) 0 0))
(define (read-test-case rs1 rs2)
; src-instr dest-instr enable xd xs1 xs2
(list (ADD 0 rs1 rs2) (ADD 0 0 0) 0 0 (read-value rs1) (read-value rs2)))
(define write-test-cases
(for/list ([n 32])
(write-test-case n)))
(define read-test-cases
(apply append
(for/list ([n 32])
(list
(read-test-case n 0)
(read-test-case 0 n)
(read-test-case n (- 31 n))))))
(define test-cases
(append write-test-cases read-test-cases))
(define test-count (length test-cases))
(define lst-src-data (map fake-asm (map first test-cases)))
(define lst-dest-data (map fake-asm (map second test-cases)))
(define lst-enable (map third test-cases))
(define lst-xd (map (word_t) (map fourth test-cases)))
(define lst-expected-xs1 (map (word_t) (map fifth test-cases)))
(define lst-expected-xs2 (map (word_t) (map sixth test-cases)))
(define dec-src-inst (decoder))
(instance-set! dec-src-inst 'data (list->signal lst-src-data))
(define dec-dest-inst (decoder))
(instance-set! dec-dest-inst 'data (list->signal lst-dest-data))
(define reg-inst (register_unit 32))
(instance-set! reg-inst 'src_instr (instance-ref dec-src-inst 'instr))
(instance-set! reg-inst 'dest_instr (instance-ref dec-dest-inst 'instr))
(instance-set! reg-inst 'reset (signal 0))
(instance-set! reg-inst 'enable (list->signal lst-enable))
(instance-set! reg-inst 'xd (list->signal lst-xd))
(define lst-xs1 (signal-take (instance-ref reg-inst 'xs1) test-count))
(define lst-xs2 (signal-take (instance-ref reg-inst 'xs2) test-count))
(for ([n test-count]
[si (in-list lst-src-data)]
[di (in-list lst-dest-data)]
[r1 (in-list lst-xs1)]
[r2 (in-list lst-xs2)]
[x1 (in-list lst-expected-xs1)]
[x2 (in-list lst-expected-xs2)])
(test-equal? (format "Register unit #~a: rs1" n)
r1 x1)
(test-equal? (format "Register unit #~a: rs2" n)
r2 x2))
| null | https://raw.githubusercontent.com/aumouvantsillage/Virgule-CPU/1be168c9740795e6f0bdac23d23dc26250e8a7d3/virgule/tests/register_unit.rkt | racket | src-instr dest-instr enable xd xs1 xs2
src-instr dest-instr enable xd xs1 xs2 | 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 /.
#lang racket
(require
rackunit
(except-in hydromel/support zero)
"../cpu/common.mel"
"../cpu/decoder.mel"
"../cpu/register_unit.mel"
"../asm/assembler.rkt")
(define (write-value n)
(* #x1000 (add1 n)))
(define (read-value n)
(if (zero? n)
0
(write-value n)))
(define (write-test-case rd)
(list (ADD 0 rd rd) (ADD rd 0 0) 1 (write-value rd) 0 0))
(define (read-test-case rs1 rs2)
(list (ADD 0 rs1 rs2) (ADD 0 0 0) 0 0 (read-value rs1) (read-value rs2)))
(define write-test-cases
(for/list ([n 32])
(write-test-case n)))
(define read-test-cases
(apply append
(for/list ([n 32])
(list
(read-test-case n 0)
(read-test-case 0 n)
(read-test-case n (- 31 n))))))
(define test-cases
(append write-test-cases read-test-cases))
(define test-count (length test-cases))
(define lst-src-data (map fake-asm (map first test-cases)))
(define lst-dest-data (map fake-asm (map second test-cases)))
(define lst-enable (map third test-cases))
(define lst-xd (map (word_t) (map fourth test-cases)))
(define lst-expected-xs1 (map (word_t) (map fifth test-cases)))
(define lst-expected-xs2 (map (word_t) (map sixth test-cases)))
(define dec-src-inst (decoder))
(instance-set! dec-src-inst 'data (list->signal lst-src-data))
(define dec-dest-inst (decoder))
(instance-set! dec-dest-inst 'data (list->signal lst-dest-data))
(define reg-inst (register_unit 32))
(instance-set! reg-inst 'src_instr (instance-ref dec-src-inst 'instr))
(instance-set! reg-inst 'dest_instr (instance-ref dec-dest-inst 'instr))
(instance-set! reg-inst 'reset (signal 0))
(instance-set! reg-inst 'enable (list->signal lst-enable))
(instance-set! reg-inst 'xd (list->signal lst-xd))
(define lst-xs1 (signal-take (instance-ref reg-inst 'xs1) test-count))
(define lst-xs2 (signal-take (instance-ref reg-inst 'xs2) test-count))
(for ([n test-count]
[si (in-list lst-src-data)]
[di (in-list lst-dest-data)]
[r1 (in-list lst-xs1)]
[r2 (in-list lst-xs2)]
[x1 (in-list lst-expected-xs1)]
[x2 (in-list lst-expected-xs2)])
(test-equal? (format "Register unit #~a: rs1" n)
r1 x1)
(test-equal? (format "Register unit #~a: rs2" n)
r2 x2))
|
369b4c3cea7fbf5dab6e09da5528c69c5985d1ab6d22af10a00a31107e245c71 | modular-macros/ocaml-macros | pr6690.ml | type 'a visit_action
type insert
type 'a local_visit_action
type ('a, 'result, 'visit_action) context =
| Local : ('a, ('a * insert) as 'result, 'a local_visit_action) context
| Global : ('a, 'a, 'a visit_action) context
;;
let vexpr (type visit_action)
: (_, _, visit_action) context -> _ -> visit_action =
function
| Local -> fun _ -> raise Exit
| Global -> fun _ -> raise Exit
;;
[%%expect{|
type 'a visit_action
type insert
type 'a local_visit_action
type ('a, 'result, 'visit_action) context =
Local : ('a, 'a * insert, 'a local_visit_action) context
| Global : ('a, 'a, 'a visit_action) context
Line _, characters 4-9:
Error: This pattern matches values of type
($0, $0 * insert, $0 local_visit_action) context
but a pattern was expected which matches values of type
($0, $0 * insert, visit_action) context
The type constructor $0 would escape its scope
|}, Principal{|
type 'a visit_action
type insert
type 'a local_visit_action
type ('a, 'result, 'visit_action) context =
Local : ('a, 'a * insert, 'a local_visit_action) context
| Global : ('a, 'a, 'a visit_action) context
Line _, characters 4-10:
Error: This pattern matches values of type ($1, $1, visit_action) context
but a pattern was expected which matches values of type
($0, $0 * insert, visit_action) context
Type $1 is not compatible with type $0
|}];;
let vexpr (type visit_action)
: ('a, 'result, visit_action) context -> 'a -> visit_action =
function
| Local -> fun _ -> raise Exit
| Global -> fun _ -> raise Exit
;;
[%%expect{|
Line _, characters 4-9:
Error: This pattern matches values of type
($'a, $'a * insert, $'a local_visit_action) context
but a pattern was expected which matches values of type
($'a, $'a * insert, visit_action) context
The type constructor $'a would escape its scope
|}, Principal{|
Line _, characters 4-10:
Error: This pattern matches values of type ($1, $1, visit_action) context
but a pattern was expected which matches values of type
($0, $0 * insert, visit_action) context
Type $1 is not compatible with type $0
|}];;
let vexpr (type result) (type visit_action)
: (unit, result, visit_action) context -> unit -> visit_action =
function
| Local -> fun _ -> raise Exit
| Global -> fun _ -> raise Exit
;;
[%%expect{|
val vexpr : (unit, 'a, 'b) context -> unit -> 'b = <fun>
|}];;
| null | https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/testsuite/tests/typing-gadts/pr6690.ml | ocaml | type 'a visit_action
type insert
type 'a local_visit_action
type ('a, 'result, 'visit_action) context =
| Local : ('a, ('a * insert) as 'result, 'a local_visit_action) context
| Global : ('a, 'a, 'a visit_action) context
;;
let vexpr (type visit_action)
: (_, _, visit_action) context -> _ -> visit_action =
function
| Local -> fun _ -> raise Exit
| Global -> fun _ -> raise Exit
;;
[%%expect{|
type 'a visit_action
type insert
type 'a local_visit_action
type ('a, 'result, 'visit_action) context =
Local : ('a, 'a * insert, 'a local_visit_action) context
| Global : ('a, 'a, 'a visit_action) context
Line _, characters 4-9:
Error: This pattern matches values of type
($0, $0 * insert, $0 local_visit_action) context
but a pattern was expected which matches values of type
($0, $0 * insert, visit_action) context
The type constructor $0 would escape its scope
|}, Principal{|
type 'a visit_action
type insert
type 'a local_visit_action
type ('a, 'result, 'visit_action) context =
Local : ('a, 'a * insert, 'a local_visit_action) context
| Global : ('a, 'a, 'a visit_action) context
Line _, characters 4-10:
Error: This pattern matches values of type ($1, $1, visit_action) context
but a pattern was expected which matches values of type
($0, $0 * insert, visit_action) context
Type $1 is not compatible with type $0
|}];;
let vexpr (type visit_action)
: ('a, 'result, visit_action) context -> 'a -> visit_action =
function
| Local -> fun _ -> raise Exit
| Global -> fun _ -> raise Exit
;;
[%%expect{|
Line _, characters 4-9:
Error: This pattern matches values of type
($'a, $'a * insert, $'a local_visit_action) context
but a pattern was expected which matches values of type
($'a, $'a * insert, visit_action) context
The type constructor $'a would escape its scope
|}, Principal{|
Line _, characters 4-10:
Error: This pattern matches values of type ($1, $1, visit_action) context
but a pattern was expected which matches values of type
($0, $0 * insert, visit_action) context
Type $1 is not compatible with type $0
|}];;
let vexpr (type result) (type visit_action)
: (unit, result, visit_action) context -> unit -> visit_action =
function
| Local -> fun _ -> raise Exit
| Global -> fun _ -> raise Exit
;;
[%%expect{|
val vexpr : (unit, 'a, 'b) context -> unit -> 'b = <fun>
|}];;
|
|
b3cb8bbd1d31ff3a07512467b0c47f7a2d671448a9de0fa7adc4b1124fa47ac8 | apibot-org/apibot | mixpanel.cljs | (ns apibot.mixpanel
(:require
[apibot.env :as env]))
(def mixpanel js/mixpanel)
(.init mixpanel env/mixpanel-token)
(defn track
"Tracks the given event with the given data.
Example:
(track :ev-registration-click {:email \"foo\"})"
([event-name data]
(.track mixpanel
(name event-name)
(clj->js data)))
([event-name]
(track event-name {})))
(defn trackfn
[event-name func]
(fn [& args]
(track event-name)
(apply func args)))
(defn set-user-id! [user-id]
(println "Setting user ID to " user-id)
(.identify mixpanel user-id))
(defn set!
"Sets arbitrary data for the current user.
Make sure you have first called set-user-id!
Example:
(set-user-id! \"some-user-id\")
(set! {\"$first_name\" \"Joe\"
\"$last_name\" \"Doe\"
\"$created\" \"2013-04-01T09:02:00\"
\"$email\" \"\"}
"
[data]
(-> mixpanel .-people (.set (clj->js data))))
| null | https://raw.githubusercontent.com/apibot-org/apibot/26c77c688980549a8deceeeb39f01108be016435/src/cljs/apibot/mixpanel.cljs | clojure | (ns apibot.mixpanel
(:require
[apibot.env :as env]))
(def mixpanel js/mixpanel)
(.init mixpanel env/mixpanel-token)
(defn track
"Tracks the given event with the given data.
Example:
(track :ev-registration-click {:email \"foo\"})"
([event-name data]
(.track mixpanel
(name event-name)
(clj->js data)))
([event-name]
(track event-name {})))
(defn trackfn
[event-name func]
(fn [& args]
(track event-name)
(apply func args)))
(defn set-user-id! [user-id]
(println "Setting user ID to " user-id)
(.identify mixpanel user-id))
(defn set!
"Sets arbitrary data for the current user.
Make sure you have first called set-user-id!
Example:
(set-user-id! \"some-user-id\")
(set! {\"$first_name\" \"Joe\"
\"$last_name\" \"Doe\"
\"$created\" \"2013-04-01T09:02:00\"
\"$email\" \"\"}
"
[data]
(-> mixpanel .-people (.set (clj->js data))))
|
|
6bdea3e2b1b13ecc4876f8086b03465d5a26b1de4ef081ad83bfa6b7379d723b | returntocorp/sexp-fmt | Print.mli | (*
S-expression pretty-printer.
*)
(* Pretty-print an S-expression into a string. *)
val to_string : AST.t -> string
(* Write a pretty-printed S-expression to a channel. *)
val to_channel : out_channel -> AST.t -> unit
| null | https://raw.githubusercontent.com/returntocorp/sexp-fmt/1ea0b84693a26a7ca2c36ea9b424fbf51d0133c5/src/lib/Print.mli | ocaml |
S-expression pretty-printer.
Pretty-print an S-expression into a string.
Write a pretty-printed S-expression to a channel. |
val to_string : AST.t -> string
val to_channel : out_channel -> AST.t -> unit
|
721908f2ba075efb4787c187007ba2dfdb1347764a22e047666145b02fd8232a | vaibhavsagar/experiments | Compiler.hs | # OPTIONS_GHC -cpp #
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Compiler
Copyright : 2003 - 2004
--
Maintainer : < >
-- Stability : alpha
-- Portability : portable
--
Haskell implementations .
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 nor the names of other
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 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 .
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 Isaac Jones nor the names of other
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 CONTRIBUTORS BE 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. -}
module Distribution.Compiler (
* implementations
CompilerFlavor(..), Compiler(..), showCompilerId,
compilerBinaryName,
-- * Support for language extensions
Opt,
extensionsToFlags,
extensionsToGHCFlag, extensionsToHugsFlag,
extensionsToNHCFlag, extensionsToJHCFlag,
#ifdef DEBUG
hunitTests
#endif
) where
import Distribution.Version (Version(..), showVersion)
import Language.Haskell.Extension (Extension(..))
import Data.List (nub)
#ifdef DEBUG
import HUnit (Test)
#endif
-- ------------------------------------------------------------
-- * Command Line Types and Exports
-- ------------------------------------------------------------
data CompilerFlavor
= GHC | NHC | Hugs | HBC | Helium | JHC | OtherCompiler String
deriving (Show, Read, Eq)
data Compiler = Compiler {compilerFlavor:: CompilerFlavor,
compilerVersion :: Version,
compilerPath :: FilePath,
compilerPkgTool :: FilePath}
deriving (Show, Read, Eq)
showCompilerId :: Compiler -> String
showCompilerId (Compiler f (Version [] _) _ _) = compilerBinaryName f
showCompilerId (Compiler f v _ _) = compilerBinaryName f ++ '-': showVersion v
compilerBinaryName :: CompilerFlavor -> String
compilerBinaryName GHC = "ghc"
FIX : uses for now
compilerBinaryName Hugs = "ffihugs"
compilerBinaryName JHC = "jhc"
compilerBinaryName cmp = error $ "Unsupported compiler: " ++ (show cmp)
-- ------------------------------------------------------------
-- * Extensions
-- ------------------------------------------------------------
-- |For the given compiler, return the unsupported extensions, and the
-- flags for the supported extensions.
extensionsToFlags :: CompilerFlavor -> [ Extension ] -> ([Extension], [Opt])
extensionsToFlags GHC exts = extensionsToGHCFlag exts
extensionsToFlags Hugs exts = extensionsToHugsFlag exts
extensionsToFlags NHC exts = extensionsToNHCFlag exts
extensionsToFlags JHC exts = extensionsToJHCFlag exts
extensionsToFlags _ exts = (exts, [])
-- |GHC: Return the unsupported extensions, and the flags for the supported extensions
extensionsToGHCFlag :: [ Extension ] -> ([Extension], [Opt])
extensionsToGHCFlag l
= splitEither $ nub $ map extensionToGHCFlag l
where
extensionToGHCFlag :: Extension -> Either Extension String
extensionToGHCFlag OverlappingInstances = Right "-fallow-overlapping-instances"
extensionToGHCFlag TypeSynonymInstances = Right "-fglasgow-exts"
extensionToGHCFlag TemplateHaskell = Right "-fth"
extensionToGHCFlag ForeignFunctionInterface = Right "-fffi"
extensionToGHCFlag NoMonomorphismRestriction = Right "-fno-monomorphism-restriction"
extensionToGHCFlag UndecidableInstances = Right "-fallow-undecidable-instances"
extensionToGHCFlag IncoherentInstances = Right "-fallow-incoherent-instances"
extensionToGHCFlag InlinePhase = Right "-finline-phase"
extensionToGHCFlag ContextStack = Right "-fcontext-stack"
extensionToGHCFlag Arrows = Right "-farrows"
extensionToGHCFlag Generics = Right "-fgenerics"
extensionToGHCFlag NoImplicitPrelude = Right "-fno-implicit-prelude"
extensionToGHCFlag ImplicitParams = Right "-fimplicit-params"
extensionToGHCFlag CPP = Right "-cpp"
extensionToGHCFlag BangPatterns = Right "-fbang-patterns"
extensionToGHCFlag RecursiveDo = Right "-fglasgow-exts"
extensionToGHCFlag ParallelListComp = Right "-fglasgow-exts"
extensionToGHCFlag MultiParamTypeClasses = Right "-fglasgow-exts"
extensionToGHCFlag FunctionalDependencies = Right "-fglasgow-exts"
extensionToGHCFlag Rank2Types = Right "-fglasgow-exts"
extensionToGHCFlag RankNTypes = Right "-fglasgow-exts"
extensionToGHCFlag PolymorphicComponents = Right "-fglasgow-exts"
extensionToGHCFlag ExistentialQuantification = Right "-fglasgow-exts"
extensionToGHCFlag ScopedTypeVariables = Right "-fglasgow-exts"
extensionToGHCFlag FlexibleContexts = Right "-fglasgow-exts"
extensionToGHCFlag FlexibleInstances = Right "-fglasgow-exts"
extensionToGHCFlag EmptyDataDecls = Right "-fglasgow-exts"
extensionToGHCFlag PatternGuards = Right "-fglasgow-exts"
extensionToGHCFlag GeneralizedNewtypeDeriving = Right "-fglasgow-exts"
extensionToGHCFlag e@ExtensibleRecords = Left e
extensionToGHCFlag e@RestrictedTypeSynonyms = Left e
extensionToGHCFlag e@HereDocuments = Left e
extensionToGHCFlag e@NamedFieldPuns = Left e
-- |NHC: Return the unsupported extensions, and the flags for the supported extensions
extensionsToNHCFlag :: [ Extension ] -> ([Extension], [Opt])
extensionsToNHCFlag l
= splitEither $ nub $ map extensionToNHCFlag l
where
NHC does n't enforce the monomorphism restriction at all .
extensionToNHCFlag NoMonomorphismRestriction = Right ""
extensionToNHCFlag ForeignFunctionInterface = Right ""
extensionToNHCFlag ExistentialQuantification = Right ""
extensionToNHCFlag EmptyDataDecls = Right ""
extensionToNHCFlag NamedFieldPuns = Right "-puns"
extensionToNHCFlag CPP = Right "-cpp"
extensionToNHCFlag e = Left e
-- |JHC: Return the unsupported extensions, and the flags for the supported extensions
extensionsToJHCFlag :: [ Extension ] -> ([Extension], [Opt])
extensionsToJHCFlag l = (es, filter (not . null) rs)
where
(es,rs) = splitEither $ nub $ map extensionToJHCFlag l
extensionToJHCFlag TypeSynonymInstances = Right ""
extensionToJHCFlag ForeignFunctionInterface = Right ""
extensionToJHCFlag NoImplicitPrelude = Right "--noprelude"
extensionToJHCFlag CPP = Right "-fcpp"
extensionToJHCFlag e = Left e
-- |Hugs: Return the unsupported extensions, and the flags for the supported extensions
extensionsToHugsFlag :: [ Extension ] -> ([Extension], [Opt])
extensionsToHugsFlag l
= splitEither $ nub $ map extensionToHugsFlag l
where
extensionToHugsFlag OverlappingInstances = Right "+o"
extensionToHugsFlag IncoherentInstances = Right "+oO"
extensionToHugsFlag HereDocuments = Right "+H"
extensionToHugsFlag TypeSynonymInstances = Right "-98"
extensionToHugsFlag RecursiveDo = Right "-98"
extensionToHugsFlag ParallelListComp = Right "-98"
extensionToHugsFlag MultiParamTypeClasses = Right "-98"
extensionToHugsFlag FunctionalDependencies = Right "-98"
extensionToHugsFlag Rank2Types = Right "-98"
extensionToHugsFlag PolymorphicComponents = Right "-98"
extensionToHugsFlag ExistentialQuantification = Right "-98"
extensionToHugsFlag ScopedTypeVariables = Right "-98"
extensionToHugsFlag ImplicitParams = Right "-98"
extensionToHugsFlag ExtensibleRecords = Right "-98"
extensionToHugsFlag RestrictedTypeSynonyms = Right "-98"
extensionToHugsFlag FlexibleContexts = Right "-98"
extensionToHugsFlag FlexibleInstances = Right "-98"
extensionToHugsFlag ForeignFunctionInterface = Right ""
extensionToHugsFlag EmptyDataDecls = Right ""
extensionToHugsFlag CPP = Right ""
extensionToHugsFlag e = Left e
splitEither :: [Either a b] -> ([a], [b])
splitEither l = ([a | Left a <- l], [b | Right b <- l])
type Opt = String
-- ------------------------------------------------------------
-- * Testing
-- ------------------------------------------------------------
#ifdef DEBUG
hunitTests :: [Test]
hunitTests = []
#endif
| null | https://raw.githubusercontent.com/vaibhavsagar/experiments/378d7ba97eabfc7bbeaa4116380369ea6612bfeb/hugs/packages/Cabal/Distribution/Compiler.hs | haskell | ---------------------------------------------------------------------------
|
Module : Distribution.Compiler
Stability : alpha
Portability : portable
* Support for language extensions
------------------------------------------------------------
* Command Line Types and Exports
------------------------------------------------------------
------------------------------------------------------------
* Extensions
------------------------------------------------------------
|For the given compiler, return the unsupported extensions, and the
flags for the supported extensions.
|GHC: Return the unsupported extensions, and the flags for the supported extensions
|NHC: Return the unsupported extensions, and the flags for the supported extensions
|JHC: Return the unsupported extensions, and the flags for the supported extensions
|Hugs: Return the unsupported extensions, and the flags for the supported extensions
------------------------------------------------------------
* Testing
------------------------------------------------------------ | # OPTIONS_GHC -cpp #
Copyright : 2003 - 2004
Maintainer : < >
Haskell implementations .
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 nor the names of other
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 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 .
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 Isaac Jones nor the names of other
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 CONTRIBUTORS BE 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. -}
module Distribution.Compiler (
* implementations
CompilerFlavor(..), Compiler(..), showCompilerId,
compilerBinaryName,
Opt,
extensionsToFlags,
extensionsToGHCFlag, extensionsToHugsFlag,
extensionsToNHCFlag, extensionsToJHCFlag,
#ifdef DEBUG
hunitTests
#endif
) where
import Distribution.Version (Version(..), showVersion)
import Language.Haskell.Extension (Extension(..))
import Data.List (nub)
#ifdef DEBUG
import HUnit (Test)
#endif
data CompilerFlavor
= GHC | NHC | Hugs | HBC | Helium | JHC | OtherCompiler String
deriving (Show, Read, Eq)
data Compiler = Compiler {compilerFlavor:: CompilerFlavor,
compilerVersion :: Version,
compilerPath :: FilePath,
compilerPkgTool :: FilePath}
deriving (Show, Read, Eq)
showCompilerId :: Compiler -> String
showCompilerId (Compiler f (Version [] _) _ _) = compilerBinaryName f
showCompilerId (Compiler f v _ _) = compilerBinaryName f ++ '-': showVersion v
compilerBinaryName :: CompilerFlavor -> String
compilerBinaryName GHC = "ghc"
FIX : uses for now
compilerBinaryName Hugs = "ffihugs"
compilerBinaryName JHC = "jhc"
compilerBinaryName cmp = error $ "Unsupported compiler: " ++ (show cmp)
extensionsToFlags :: CompilerFlavor -> [ Extension ] -> ([Extension], [Opt])
extensionsToFlags GHC exts = extensionsToGHCFlag exts
extensionsToFlags Hugs exts = extensionsToHugsFlag exts
extensionsToFlags NHC exts = extensionsToNHCFlag exts
extensionsToFlags JHC exts = extensionsToJHCFlag exts
extensionsToFlags _ exts = (exts, [])
extensionsToGHCFlag :: [ Extension ] -> ([Extension], [Opt])
extensionsToGHCFlag l
= splitEither $ nub $ map extensionToGHCFlag l
where
extensionToGHCFlag :: Extension -> Either Extension String
extensionToGHCFlag OverlappingInstances = Right "-fallow-overlapping-instances"
extensionToGHCFlag TypeSynonymInstances = Right "-fglasgow-exts"
extensionToGHCFlag TemplateHaskell = Right "-fth"
extensionToGHCFlag ForeignFunctionInterface = Right "-fffi"
extensionToGHCFlag NoMonomorphismRestriction = Right "-fno-monomorphism-restriction"
extensionToGHCFlag UndecidableInstances = Right "-fallow-undecidable-instances"
extensionToGHCFlag IncoherentInstances = Right "-fallow-incoherent-instances"
extensionToGHCFlag InlinePhase = Right "-finline-phase"
extensionToGHCFlag ContextStack = Right "-fcontext-stack"
extensionToGHCFlag Arrows = Right "-farrows"
extensionToGHCFlag Generics = Right "-fgenerics"
extensionToGHCFlag NoImplicitPrelude = Right "-fno-implicit-prelude"
extensionToGHCFlag ImplicitParams = Right "-fimplicit-params"
extensionToGHCFlag CPP = Right "-cpp"
extensionToGHCFlag BangPatterns = Right "-fbang-patterns"
extensionToGHCFlag RecursiveDo = Right "-fglasgow-exts"
extensionToGHCFlag ParallelListComp = Right "-fglasgow-exts"
extensionToGHCFlag MultiParamTypeClasses = Right "-fglasgow-exts"
extensionToGHCFlag FunctionalDependencies = Right "-fglasgow-exts"
extensionToGHCFlag Rank2Types = Right "-fglasgow-exts"
extensionToGHCFlag RankNTypes = Right "-fglasgow-exts"
extensionToGHCFlag PolymorphicComponents = Right "-fglasgow-exts"
extensionToGHCFlag ExistentialQuantification = Right "-fglasgow-exts"
extensionToGHCFlag ScopedTypeVariables = Right "-fglasgow-exts"
extensionToGHCFlag FlexibleContexts = Right "-fglasgow-exts"
extensionToGHCFlag FlexibleInstances = Right "-fglasgow-exts"
extensionToGHCFlag EmptyDataDecls = Right "-fglasgow-exts"
extensionToGHCFlag PatternGuards = Right "-fglasgow-exts"
extensionToGHCFlag GeneralizedNewtypeDeriving = Right "-fglasgow-exts"
extensionToGHCFlag e@ExtensibleRecords = Left e
extensionToGHCFlag e@RestrictedTypeSynonyms = Left e
extensionToGHCFlag e@HereDocuments = Left e
extensionToGHCFlag e@NamedFieldPuns = Left e
extensionsToNHCFlag :: [ Extension ] -> ([Extension], [Opt])
extensionsToNHCFlag l
= splitEither $ nub $ map extensionToNHCFlag l
where
NHC does n't enforce the monomorphism restriction at all .
extensionToNHCFlag NoMonomorphismRestriction = Right ""
extensionToNHCFlag ForeignFunctionInterface = Right ""
extensionToNHCFlag ExistentialQuantification = Right ""
extensionToNHCFlag EmptyDataDecls = Right ""
extensionToNHCFlag NamedFieldPuns = Right "-puns"
extensionToNHCFlag CPP = Right "-cpp"
extensionToNHCFlag e = Left e
extensionsToJHCFlag :: [ Extension ] -> ([Extension], [Opt])
extensionsToJHCFlag l = (es, filter (not . null) rs)
where
(es,rs) = splitEither $ nub $ map extensionToJHCFlag l
extensionToJHCFlag TypeSynonymInstances = Right ""
extensionToJHCFlag ForeignFunctionInterface = Right ""
extensionToJHCFlag NoImplicitPrelude = Right "--noprelude"
extensionToJHCFlag CPP = Right "-fcpp"
extensionToJHCFlag e = Left e
extensionsToHugsFlag :: [ Extension ] -> ([Extension], [Opt])
extensionsToHugsFlag l
= splitEither $ nub $ map extensionToHugsFlag l
where
extensionToHugsFlag OverlappingInstances = Right "+o"
extensionToHugsFlag IncoherentInstances = Right "+oO"
extensionToHugsFlag HereDocuments = Right "+H"
extensionToHugsFlag TypeSynonymInstances = Right "-98"
extensionToHugsFlag RecursiveDo = Right "-98"
extensionToHugsFlag ParallelListComp = Right "-98"
extensionToHugsFlag MultiParamTypeClasses = Right "-98"
extensionToHugsFlag FunctionalDependencies = Right "-98"
extensionToHugsFlag Rank2Types = Right "-98"
extensionToHugsFlag PolymorphicComponents = Right "-98"
extensionToHugsFlag ExistentialQuantification = Right "-98"
extensionToHugsFlag ScopedTypeVariables = Right "-98"
extensionToHugsFlag ImplicitParams = Right "-98"
extensionToHugsFlag ExtensibleRecords = Right "-98"
extensionToHugsFlag RestrictedTypeSynonyms = Right "-98"
extensionToHugsFlag FlexibleContexts = Right "-98"
extensionToHugsFlag FlexibleInstances = Right "-98"
extensionToHugsFlag ForeignFunctionInterface = Right ""
extensionToHugsFlag EmptyDataDecls = Right ""
extensionToHugsFlag CPP = Right ""
extensionToHugsFlag e = Left e
splitEither :: [Either a b] -> ([a], [b])
splitEither l = ([a | Left a <- l], [b | Right b <- l])
type Opt = String
#ifdef DEBUG
hunitTests :: [Test]
hunitTests = []
#endif
|
f95b445217e161b21eb5d0a733b01500b1635eeff577a54b68ea8b0e06d5d1a4 | binghe/PCL | fast-init.lisp | -*-Mode : LISP ; Package:(PCL LISP 1000 ) ; ; Syntax : Common - lisp -*-
;;;
;;; *************************************************************************
Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation .
;;; All rights reserved.
;;;
;;; Use and copying of this software and preparation of derivative works
;;; based upon this software are permitted. Any distribution of this
software or derivative works must comply with all applicable United
;;; States export control laws.
;;;
This software is made available AS IS , and Xerox Corporation makes no
;;; warranty about the software, its performance or its conformity to any
;;; specification.
;;;
;;; Any person obtaining a copy of this software is requested to send their
;;; name and post office or electronic mail address to:
CommonLoops Coordinator
Xerox PARC
3333 Coyote Hill Rd .
Palo Alto , CA 94304
( or send Arpanet mail to )
;;;
;;; Suggestions, comments and requests for improvements are also welcome.
;;; *************************************************************************
;;;
;;;
;;; This file defines the optimized make-instance functions.
;;;
(in-package :pcl)
(defvar *compile-make-instance-functions-p* nil)
(defun update-make-instance-function-table (&optional (class *the-class-t*))
(when (symbolp class) (setq class (find-class class)))
(when (eq class *the-class-t*) (setq class *the-class-slot-object*))
(when (memq *the-class-slot-object* (class-precedence-list class))
(map-all-classes #'reset-class-initialize-info class)))
(defun constant-symbol-p (form)
(and (constantp form)
(let ((object (eval form)))
(and (symbolp object)
(symbol-package object)))))
(defvar *make-instance-function-keys* nil)
(defun expand-make-instance-form (form)
(let ((class (cadr form)) (initargs (cddr form))
(keys nil)(allow-other-keys-p nil) key value)
(when (and (constant-symbol-p class)
(let ((initargs-tail initargs))
(loop (when (null initargs-tail) (return t))
(unless (constant-symbol-p (car initargs-tail))
(return nil))
(setq key (eval (pop initargs-tail)))
(setq value (pop initargs-tail))
(when (eq ':allow-other-keys key)
(setq allow-other-keys-p value))
(push key keys))))
(let* ((class (eval class))
(keys (nreverse keys))
(key (list class keys allow-other-keys-p))
(sym (make-instance-function-symbol key)))
(push key *make-instance-function-keys*)
(when sym
`(,sym ',class (list ,@initargs)))))))
(defmacro expanding-make-instance-top-level (&rest forms &environment env)
(let* ((*make-instance-function-keys* nil)
(form (macroexpand `(expanding-make-instance ,@forms) env)))
`(progn
,@(when *make-instance-function-keys*
`((get-make-instance-functions ',*make-instance-function-keys*)))
,form)))
(defmacro expanding-make-instance (&rest forms &environment env)
`(progn
,@(mapcar #'(lambda (form)
(walk-form form env
#'(lambda (subform context env)
(declare (ignore env))
(or (and (eq context ':eval)
(consp subform)
(eq (car subform) 'make-instance)
(expand-make-instance-form subform))
subform))))
forms)))
(defmacro defconstructor
(name class lambda-list &rest initialization-arguments)
`(expanding-make-instance-top-level
(defun ,name ,lambda-list
(make-instance ',class ,@initialization-arguments))))
(defun get-make-instance-functions (key-list)
(dolist (key key-list)
(let* ((cell (find-class-cell (car key)))
(make-instance-function-keys
(find-class-cell-make-instance-function-keys cell))
(mif-key (cons (cadr key) (caddr key))))
(unless (find mif-key make-instance-function-keys
:test #'equal)
(push mif-key (find-class-cell-make-instance-function-keys cell))
(let ((class (find-class-cell-class cell)))
(when (and class (not (forward-referenced-class-p class)))
(update-initialize-info-internal
(initialize-info class (car mif-key) nil (cdr mif-key))
'make-instance-function)))))))
(defun make-instance-function-symbol (key)
(let* ((class (car key))
(symbolp (symbolp class)))
(when (or symbolp (classp class))
(let* ((class-name (if (symbolp class) class (class-name class)))
(keys (cadr key))
(allow-other-keys-p (caddr key)))
(when (and (or symbolp
(and (symbolp class-name)
(eq class (find-class class-name nil))))
(symbol-package class-name))
(let ((*package* *the-pcl-package*)
(*print-length* nil) (*print-level* nil)
(*print-circle* nil) (*print-case* :upcase)
(*print-pretty* nil))
(intern (format nil "MAKE-INSTANCE ~S ~S ~S"
class-name keys allow-other-keys-p))))))))
(defun make-instance-1 (class initargs)
(apply #'make-instance class initargs))
(defmacro define-cached-reader (type name trap)
(let ((reader-name (intern (format nil "~A-~A" type name)))
(cached-name (intern (format nil "~A-CACHED-~A" type name))))
`(defmacro ,reader-name (info)
`(let ((value (,',cached-name ,info)))
(if (eq value ':unknown)
(progn
(,',trap ,info ',',name)
(,',cached-name ,info))
value)))))
(eval-when (compile load eval)
(defparameter initialize-info-cached-slots
'(valid-p ; t or (:invalid key)
ri-valid-p
initargs-form-list
new-keys
default-initargs-function
shared-initialize-t-function
shared-initialize-nil-function
constants
combined-initialize-function ; allocate-instance + shared-initialize
make-instance-function ; nil means use gf
make-instance-function-symbol)))
(defmacro define-initialize-info ()
(let ((cached-slot-names
(mapcar #'(lambda (name)
(intern (format nil "CACHED-~A" name)))
initialize-info-cached-slots))
(cached-names
(mapcar #'(lambda (name)
(intern (format nil "~A-CACHED-~A"
'initialize-info name)))
initialize-info-cached-slots)))
`(progn
(defstruct initialize-info
key wrapper
,@(mapcar #'(lambda (name)
`(,name :unknown))
cached-slot-names))
(defmacro reset-initialize-info-internal (info)
`(progn
,@(mapcar #'(lambda (cname)
`(setf (,cname ,info) ':unknown))
',cached-names)))
(defun initialize-info-bound-slots (info)
(let ((slots nil))
,@(mapcar #'(lambda (name cached-name)
`(unless (eq ':unknown (,cached-name info))
(push ',name slots)))
initialize-info-cached-slots cached-names)
slots))
,@(mapcar #'(lambda (name)
`(define-cached-reader initialize-info ,name
update-initialize-info-internal))
initialize-info-cached-slots))))
(define-initialize-info)
(defvar *initialize-info-cache-class* nil)
(defvar *initialize-info-cache-initargs* nil)
(defvar *initialize-info-cache-info* nil)
(defvar *revert-initialize-info-p* nil)
(defun reset-initialize-info (info)
(setf (initialize-info-wrapper info)
(class-wrapper (car (initialize-info-key info))))
(let ((slots-to-revert (if *revert-initialize-info-p*
(initialize-info-bound-slots info)
'(make-instance-function))))
(reset-initialize-info-internal info)
(dolist (slot slots-to-revert)
(update-initialize-info-internal info slot))
info))
(defun reset-class-initialize-info (class)
(reset-class-initialize-info-1 (class-initialize-info class)))
(defun reset-class-initialize-info-1 (cell)
(when (consp cell)
(when (car cell)
(reset-initialize-info (car cell)))
(let ((alist (cdr cell)))
(dolist (a alist)
(reset-class-initialize-info-1 (cdr a))))))
(defun initialize-info (class initargs &optional (plist-p t) allow-other-keys-arg)
(let ((info nil))
(if (and (eq *initialize-info-cache-class* class)
(eq *initialize-info-cache-initargs* initargs))
(setq info *initialize-info-cache-info*)
(let ((initargs-tail initargs)
(cell (or (class-initialize-info class)
(setf (class-initialize-info class) (cons nil nil)))))
(loop (when (null initargs-tail) (return nil))
(let ((keyword (pop initargs-tail))
(alist-cell cell))
(when plist-p
(if (eq keyword :allow-other-keys)
(setq allow-other-keys-arg (pop initargs-tail))
(pop initargs-tail)))
(loop (let ((alist (cdr alist-cell)))
(when (null alist)
(setq cell (cons nil nil))
(setf (cdr alist-cell) (list (cons keyword cell)))
(return nil))
(when (eql keyword (caar alist))
(setq cell (cdar alist))
(return nil))
(setq alist-cell alist)))))
(setq info (or (car cell)
(setf (car cell) (make-initialize-info))))))
(let ((wrapper (initialize-info-wrapper info)))
(unless (eq wrapper (class-wrapper class))
(unless wrapper
(let* ((initargs-tail initargs)
(klist-cell (list nil))
(klist-tail klist-cell))
(loop (when (null initargs-tail) (return nil))
(let ((key (pop initargs-tail)))
(setf (cdr klist-tail) (list key)))
(setf klist-tail (cdr klist-tail))
(when plist-p (pop initargs-tail)))
(setf (initialize-info-key info)
(list class (cdr klist-cell) allow-other-keys-arg))))
(reset-initialize-info info)))
(setq *initialize-info-cache-class* class)
(setq *initialize-info-cache-initargs* initargs)
(setq *initialize-info-cache-info* info)
info))
(defun update-initialize-info-internal (info name)
(let* ((key (initialize-info-key info))
(class (car key))
(keys (cadr key))
(allow-other-keys-arg (caddr key)))
(ecase name
((initargs-form-list new-keys)
(multiple-value-bind (initargs-form-list new-keys)
(make-default-initargs-form-list class keys)
(setf (initialize-info-cached-initargs-form-list info) initargs-form-list)
(setf (initialize-info-cached-new-keys info) new-keys)))
((default-initargs-function)
(let ((initargs-form-list (initialize-info-initargs-form-list info)))
(setf (initialize-info-cached-default-initargs-function info)
(initialize-instance-simple-function
'default-initargs-function info
class initargs-form-list))))
((valid-p ri-valid-p)
(flet ((compute-valid-p (methods)
(or (not (null allow-other-keys-arg))
(multiple-value-bind (legal allow-other-keys)
(check-initargs-values class methods)
(or (not (null allow-other-keys))
(dolist (key keys t)
(unless (member key legal)
(return (cons :invalid key)))))))))
(let ((proto (class-prototype class)))
(setf (initialize-info-cached-valid-p info)
(compute-valid-p
(list (list* 'allocate-instance class nil)
(list* 'initialize-instance proto nil)
(list* 'shared-initialize proto t nil))))
(setf (initialize-info-cached-ri-valid-p info)
(compute-valid-p
(list (list* 'reinitialize-instance proto nil)
(list* 'shared-initialize proto nil nil)))))))
((shared-initialize-t-function)
(multiple-value-bind (initialize-form-list ignore)
(make-shared-initialize-form-list class keys t nil)
(declare (ignore ignore))
(setf (initialize-info-cached-shared-initialize-t-function info)
(initialize-instance-simple-function
'shared-initialize-t-function info
class initialize-form-list))))
((shared-initialize-nil-function)
(multiple-value-bind (initialize-form-list ignore)
(make-shared-initialize-form-list class keys nil nil)
(declare (ignore ignore))
(setf (initialize-info-cached-shared-initialize-nil-function info)
(initialize-instance-simple-function
'shared-initialize-nil-function info
class initialize-form-list))))
((constants combined-initialize-function)
(let ((initargs-form-list (initialize-info-initargs-form-list info))
(new-keys (initialize-info-new-keys info)))
(multiple-value-bind (initialize-form-list constants)
(make-shared-initialize-form-list class new-keys t t)
(setf (initialize-info-cached-constants info) constants)
(setf (initialize-info-cached-combined-initialize-function info)
(initialize-instance-simple-function
'combined-initialize-function info
class (append initargs-form-list initialize-form-list))))))
((make-instance-function-symbol)
(setf (initialize-info-cached-make-instance-function-symbol info)
(make-instance-function-symbol key)))
((make-instance-function)
(let* ((function (get-make-instance-function key))
(symbol (initialize-info-make-instance-function-symbol info)))
(setf (initialize-info-cached-make-instance-function info) function)
(when symbol (setf (gdefinition symbol)
(or function #'make-instance-1)))))))
info)
(defun get-make-instance-function (key)
(let* ((class (car key))
(keys (cadr key)))
(unless (eq *boot-state* 'complete)
(return-from get-make-instance-function nil))
(when (symbolp class)
(setq class (find-class class)))
(when (classp class)
(unless (class-finalized-p class) (finalize-inheritance class)))
(let* ((initargs (mapcan #'(lambda (key) (list key nil)) keys))
(class-and-initargs (list* class initargs))
(make-instance (gdefinition 'make-instance))
(make-instance-methods
(compute-applicable-methods make-instance class-and-initargs))
(std-mi-meth (find-standard-ii-method make-instance-methods 'class))
(class+initargs (list class initargs))
(default-initargs (gdefinition 'default-initargs))
(default-initargs-methods
(compute-applicable-methods default-initargs class+initargs))
(proto (and (classp class) (class-prototype class)))
(initialize-instance-methods
(when proto
(compute-applicable-methods (gdefinition 'initialize-instance)
(list* proto initargs))))
(shared-initialize-methods
(when proto
(compute-applicable-methods (gdefinition 'shared-initialize)
(list* proto t initargs)))))
(when (null make-instance-methods)
(return-from get-make-instance-function
#'(lambda (class initargs)
(apply #'no-applicable-method make-instance class initargs))))
(unless (and (null (cdr make-instance-methods))
(eq (car make-instance-methods) std-mi-meth)
(null (cdr default-initargs-methods))
(eq (car (method-specializers (car default-initargs-methods)))
*the-class-slot-class*)
(flet ((check-meth (meth)
(let ((quals (method-qualifiers meth)))
(if (null quals)
(eq (car (method-specializers meth))
*the-class-slot-object*)
(and (null (cdr quals))
(or (eq (car quals) ':before)
(eq (car quals) ':after)))))))
(and (every #'check-meth initialize-instance-methods)
(every #'check-meth shared-initialize-methods))))
(return-from get-make-instance-function nil))
(get-make-instance-function-internal
class key (default-initargs class initargs)
initialize-instance-methods shared-initialize-methods))))
(defun get-make-instance-function-internal (class key initargs
initialize-instance-methods
shared-initialize-methods)
(let* ((keys (cadr key))
(allow-other-keys-p (caddr key))
(allocate-instance-methods
(compute-applicable-methods (gdefinition 'allocate-instance)
(list* class initargs))))
(unless allow-other-keys-p
(unless (check-initargs-1
class initargs
(append allocate-instance-methods
initialize-instance-methods
shared-initialize-methods)
t nil)
(return-from get-make-instance-function-internal nil)))
(if (or (cdr allocate-instance-methods)
(some #'complicated-instance-creation-method
initialize-instance-methods)
(some #'complicated-instance-creation-method
shared-initialize-methods))
(make-instance-function-complex
key class keys
initialize-instance-methods shared-initialize-methods)
(make-instance-function-simple
key class keys
initialize-instance-methods shared-initialize-methods))))
(defun complicated-instance-creation-method (m)
(let ((qual (method-qualifiers m)))
(if qual
(not (and (null (cdr qual)) (eq (car qual) ':after)))
(let ((specl (car (method-specializers m))))
(or (not (classp specl))
(not (eq 'slot-object (class-name specl))))))))
(defun find-standard-ii-method (methods class-names)
(dolist (m methods)
(when (null (method-qualifiers m))
(let ((specl (car (method-specializers m))))
(when (and (classp specl)
(if (listp class-names)
(member (class-name specl) class-names)
(eq (class-name specl) class-names)))
(return m))))))
(defmacro call-initialize-function (initialize-function instance initargs)
`(let ((.function. ,initialize-function))
(if (and (consp .function.)
(eq (car .function.) 'call-initialize-instance-simple))
(initialize-instance-simple (cadr .function.) (caddr .function.)
,instance ,initargs)
(funcall (the function .function.) ,instance ,initargs))))
(defun make-instance-function-simple (key class keys
initialize-instance-methods
shared-initialize-methods)
(multiple-value-bind (initialize-function constants)
(get-simple-initialization-function class keys (caddr key))
(let* ((wrapper (class-wrapper class))
(lwrapper (list wrapper))
(allocate-function
(cond ((structure-class-p class)
#'allocate-structure-instance)
((standard-class-p class)
#'allocate-standard-instance)
((funcallable-standard-class-p class)
#'allocate-funcallable-instance)
(t
(error "error in make-instance-function-simple"))))
(std-si-meth (find-standard-ii-method shared-initialize-methods
'slot-object))
(shared-initfns
(nreverse (mapcar #'(lambda (method)
(make-effective-method-function
#'shared-initialize
`(call-method ,method nil)
nil lwrapper))
(remove std-si-meth shared-initialize-methods))))
(std-ii-meth (find-standard-ii-method initialize-instance-methods
'slot-object))
(initialize-initfns
(nreverse (mapcar #'(lambda (method)
(make-effective-method-function
#'initialize-instance
`(call-method ,method nil)
nil lwrapper))
(remove std-ii-meth
initialize-instance-methods)))))
#'(lambda (class1 initargs)
(if (not (eq wrapper (class-wrapper class)))
(let* ((info (initialize-info class1 initargs))
(fn (initialize-info-make-instance-function info)))
(declare (type function fn))
(funcall fn class1 initargs))
(let* ((instance (funcall allocate-function wrapper constants))
(initargs (call-initialize-function initialize-function
instance initargs)))
(dolist (fn shared-initfns)
(invoke-effective-method-function fn t instance t initargs))
(dolist (fn initialize-initfns)
(invoke-effective-method-function fn t instance initargs))
instance))))))
(defun make-instance-function-complex (key class keys
initialize-instance-methods
shared-initialize-methods)
(multiple-value-bind (initargs-function initialize-function)
(get-complex-initialization-functions class keys (caddr key))
(let* ((wrapper (class-wrapper class))
(shared-initialize
(get-secondary-dispatch-function
#'shared-initialize shared-initialize-methods
`((class-eq ,class) t t)
`((,(find-standard-ii-method shared-initialize-methods 'slot-object)
,#'(lambda (instance init-type &rest initargs)
(declare (ignore init-type))
#+copy-&rest-arg (setq initargs (copy-list initargs))
(call-initialize-function initialize-function
instance initargs)
instance)))
(list wrapper *the-wrapper-of-t* *the-wrapper-of-t*)))
(initialize-instance
(get-secondary-dispatch-function
#'initialize-instance initialize-instance-methods
`((class-eq ,class) t)
`((,(find-standard-ii-method initialize-instance-methods 'slot-object)
,#'(lambda (instance &rest initargs)
#+copy-&rest-arg (setq initargs (copy-list initargs))
(invoke-effective-method-function
shared-initialize t instance t initargs))))
(list wrapper *the-wrapper-of-t*))))
#'(lambda (class1 initargs)
(if (not (eq wrapper (class-wrapper class)))
(let* ((info (initialize-info class1 initargs))
(fn (initialize-info-make-instance-function info)))
(declare (type function fn))
(funcall fn class1 initargs))
(let* ((initargs (call-initialize-function initargs-function
nil initargs))
(instance (apply #'allocate-instance class initargs)))
(invoke-effective-method-function
initialize-instance t instance initargs)
instance))))))
(defun get-simple-initialization-function (class keys &optional allow-other-keys-arg)
(let ((info (initialize-info class keys nil allow-other-keys-arg)))
(values (initialize-info-combined-initialize-function info)
(initialize-info-constants info))))
(defun get-complex-initialization-functions (class keys &optional allow-other-keys-arg
separate-p)
(let* ((info (initialize-info class keys nil allow-other-keys-arg))
(default-initargs-function (initialize-info-default-initargs-function info)))
(if separate-p
(values default-initargs-function
(initialize-info-shared-initialize-t-function info))
(values default-initargs-function
(initialize-info-shared-initialize-t-function
(initialize-info class (initialize-info-new-keys info)
nil allow-other-keys-arg))))))
(defun add-forms (forms forms-list)
(when forms
(setq forms (copy-list forms))
(if (null (car forms-list))
(setf (car forms-list) forms)
(setf (cddr forms-list) forms))
(setf (cdr forms-list) (last forms)))
(car forms-list))
(defun make-default-initargs-form-list (class keys &optional (separate-p t))
(let ((initargs-form-list (cons nil nil))
(default-initargs (class-default-initargs class))
(nkeys keys))
(dolist (default default-initargs)
(let ((key (car default))
(function (cadr default)))
(unless (member key nkeys)
(add-forms `((funcall ,function) (push-initarg ,key))
initargs-form-list)
(push key nkeys))))
(when separate-p
(add-forms `((update-initialize-info-cache
,class ,(initialize-info class nkeys nil)))
initargs-form-list))
(add-forms `((finish-pushing-initargs))
initargs-form-list)
(values (car initargs-form-list) nkeys)))
(defun make-shared-initialize-form-list (class keys si-slot-names simple-p)
(let* ((initialize-form-list (cons nil nil))
(type (cond ((structure-class-p class)
'structure)
((standard-class-p class)
'standard)
((funcallable-standard-class-p class)
'funcallable)
(t (error "error in make-shared-initialize-form-list"))))
(wrapper (class-wrapper class))
(constants (when simple-p
(make-list (wrapper-no-of-instance-slots wrapper)
':initial-element *slot-unbound*)))
(slots (class-slots class))
(slot-names (mapcar #'slot-definition-name slots))
(slots-key (mapcar #'(lambda (slot)
(let ((index most-positive-fixnum))
(dolist (key (slot-definition-initargs slot))
(let ((pos (position key keys)))
(when pos (setq index (min index pos)))))
(cons slot index)))
slots))
(slots (stable-sort slots-key #'< :key #'cdr)))
(let ((n-popped 0))
(dolist (slot+index slots)
(let* ((slot (car slot+index))
(name (slot-definition-name slot))
(npop (1+ (- (cdr slot+index) n-popped))))
(unless (eql (cdr slot+index) most-positive-fixnum)
(let* ((pv-offset (1+ (position name slot-names))))
(add-forms `(,@(when (plusp npop)
`((pop-initargs ,(* 2 npop))))
(instance-set ,pv-offset ,slot))
initialize-form-list))
(incf n-popped npop)))))
(dolist (slot+index slots)
(let* ((slot (car slot+index))
(name (slot-definition-name slot)))
(when (and (eql (cdr slot+index) most-positive-fixnum)
(or (eq si-slot-names 't)
(member name si-slot-names)))
(let* ((initform (slot-definition-initform slot))
(initfunction (slot-definition-initfunction slot))
(location (unless (eq type 'structure)
(slot-definition-location slot)))
(pv-offset (1+ (position name slot-names)))
(forms (cond ((null initfunction)
nil)
((constantp initform)
(let ((value (funcall initfunction)))
(if (and simple-p (integerp location))
(progn (setf (nth location constants) value)
nil)
`((const ,value)
(instance-set ,pv-offset ,slot)))))
(t
`((funcall ,(slot-definition-initfunction slot))
(instance-set ,pv-offset ,slot))))))
(add-forms `(,@(unless (or simple-p (null forms))
`((skip-when-instance-boundp ,pv-offset ,slot
,(length forms))))
,@forms)
initialize-form-list)))))
(values (car initialize-form-list) constants)))
(defvar *class-pv-table-table* (make-hash-table :test 'eq))
(defun get-pv-cell-for-class (class)
(let* ((slot-names (mapcar #'slot-definition-name (class-slots class)))
(slot-name-lists (list (cons nil slot-names)))
(pv-table (gethash class *class-pv-table-table*)))
(unless (and pv-table
(equal slot-name-lists (pv-table-slot-name-lists pv-table)))
(setq pv-table (intern-pv-table :slot-name-lists slot-name-lists))
(setf (gethash class *class-pv-table-table*) pv-table))
(pv-table-lookup pv-table (class-wrapper class))))
(defvar *initialize-instance-simple-alist* nil)
(defvar *note-iis-entry-p* nil)
(defvar *compiled-initialize-instance-simple-functions*
(make-hash-table :test #'equal))
(defun initialize-instance-simple-function (use info class form-list)
(let* ((pv-cell (get-pv-cell-for-class class))
(key (initialize-info-key info))
(sf-key (list* use (class-name (car key)) (cdr key))))
(if (or *compile-make-instance-functions-p*
(gethash sf-key *compiled-initialize-instance-simple-functions*))
(multiple-value-bind (form args)
(form-list-to-lisp pv-cell form-list)
(let ((entry (assoc form *initialize-instance-simple-alist*
:test #'equal)))
(setf (gethash sf-key
*compiled-initialize-instance-simple-functions*)
t)
(if entry
(setf (cdddr entry) (union (list sf-key) (cdddr entry)
:test #'equal))
(progn
(setq entry (list* form nil nil (list sf-key)))
(setq *initialize-instance-simple-alist*
(nconc *initialize-instance-simple-alist*
(list entry)))))
(unless (or *note-iis-entry-p* (cadr entry))
(setf (cadr entry) (compile-lambda (car entry))))
(if (cadr entry)
(apply (the function (cadr entry)) args)
`(call-initialize-instance-simple ,pv-cell ,form-list))))
#||
#'(lambda (instance initargs)
(initialize-instance-simple pv-cell form-list instance initargs))
||#
`(call-initialize-instance-simple ,pv-cell ,form-list))))
(defun load-precompiled-iis-entry (form function system uses)
(let ((entry (assoc form *initialize-instance-simple-alist*
:test #'equal)))
(unless entry
(setq entry (list* form nil nil nil))
(setq *initialize-instance-simple-alist*
(nconc *initialize-instance-simple-alist*
(list entry))))
(setf (cadr entry) function)
(setf (caddr entry) system)
(dolist (use uses)
(setf (gethash use *compiled-initialize-instance-simple-functions*) t))
(setf (cdddr entry) (union uses (cdddr entry)
:test #'equal))))
(defmacro precompile-iis-functions (&optional system)
(let ((index -1))
`(progn
,@(gathering1 (collecting)
(dolist (iis-entry *initialize-instance-simple-alist*)
(when (or (null (caddr iis-entry))
(eq (caddr iis-entry) system))
(when system (setf (caddr iis-entry) system))
(gather1
(make-top-level-form
`(precompile-initialize-instance-simple ,system ,(incf index))
'(load)
`(load-precompiled-iis-entry
',(car iis-entry)
#',(car iis-entry)
',system
',(cdddr iis-entry))))))))))
(defun compile-iis-functions (after-p)
(let ((*compile-make-instance-functions-p* t)
(*revert-initialize-info-p* t)
(*note-iis-entry-p* (not after-p)))
(declare (special *compile-make-instance-functions-p*))
(when (eq *boot-state* 'complete)
(update-make-instance-function-table))))
;(const const)
;(funcall function)
;(push-initarg const)
;(pop-supplied count) ; a positive odd number
;(instance-set pv-offset slotd)
;(skip-when-instance-boundp pv-offset slotd n)
(defun initialize-instance-simple (pv-cell form-list instance initargs)
(let ((pv (car pv-cell))
(initargs-tail initargs)
(slots (get-slots-or-nil instance))
(class (class-of instance))
value)
(loop (when (null form-list) (return nil))
(let ((form (pop form-list)))
(ecase (car form)
(push-initarg
(push value initargs)
(push (cadr form) initargs))
(const
(setq value (cadr form)))
(funcall
(setq value (funcall (the function (cadr form)))))
(pop-initargs
(setq initargs-tail (nthcdr (1- (cadr form)) initargs-tail))
(setq value (pop initargs-tail)))
(instance-set
(instance-write-internal
pv slots (cadr form) value
(setf (slot-value-using-class class instance (caddr form)) value)))
(skip-when-instance-boundp
(when (instance-boundp-internal
pv slots (cadr form)
(slot-boundp-using-class class instance (caddr form)))
(dotimes (i (cadddr form))
(pop form-list))))
(update-initialize-info-cache
(when (consp initargs)
(setq initargs (cons (car initargs) (cdr initargs))))
(setq *initialize-info-cache-class* (cadr form))
(setq *initialize-info-cache-initargs* initargs)
(setq *initialize-info-cache-info* (caddr form)))
(finish-pushing-initargs
(setq initargs-tail initargs)))))
initargs))
(defun add-to-cvector (cvector constant)
(or (position constant cvector)
(prog1 (fill-pointer cvector)
(vector-push-extend constant cvector))))
(defvar *inline-iis-instance-locations-p* t)
(defun first-form-to-lisp (forms cvector pv)
(flet ((const (constant)
(cond ((or (numberp constant) (characterp constant))
constant)
((and (symbolp constant) (symbol-package constant))
`',constant)
(t
`(svref cvector ,(add-to-cvector cvector constant))))))
(let ((form (pop (car forms))))
(ecase (car form)
(push-initarg
`((push value initargs)
(push ,(const (cadr form)) initargs)))
(const
`((setq value ,(const (cadr form)))))
(funcall
`((setq value (funcall (the function ,(const (cadr form)))))))
(pop-initargs
`((setq initargs-tail (,@(let ((pop (1- (cadr form))))
(case pop
(1 `(cdr))
(3 `(cdddr))
(t `(nthcdr ,pop))))
initargs-tail))
(setq value (pop initargs-tail))))
(instance-set
(let* ((pv-offset (cadr form))
(location (pvref pv pv-offset))
(default `(setf (slot-value-using-class class instance
,(const (caddr form)))
value)))
(if *inline-iis-instance-locations-p*
(typecase location
(fixnum `((setf (%instance-ref slots ,(const location)) value)))
(cons `((setf (cdr ,(const location)) value)))
(t `(,default)))
`((instance-write-internal pv slots ,(const pv-offset) value
,default
,(typecase location
(fixnum ':instance)
(cons ':class)
(t ':default)))))))
(skip-when-instance-boundp
(let* ((pv-offset (cadr form))
(location (pvref pv pv-offset))
(default `(slot-boundp-using-class class instance
,(const (caddr form)))))
`((unless ,(if *inline-iis-instance-locations-p*
(typecase location
(fixnum `(not (eq (%instance-ref slots ,(const location))
',*slot-unbound*)))
(cons `(not (eq (cdr ,(const location)) ',*slot-unbound*)))
(t default))
`(instance-boundp-internal pv slots ,(const pv-offset)
,default
,(typecase (pvref pv pv-offset)
(fixnum ':instance)
(cons ':class)
(t ':default))))
,@(let ((sforms (cons nil nil)))
(dotimes (i (cadddr form) (car sforms))
(add-forms (first-form-to-lisp forms cvector pv) sforms)))))))
(update-initialize-info-cache
`((when (consp initargs)
(setq initargs (cons (car initargs) (cdr initargs))))
(setq *initialize-info-cache-class* ,(const (cadr form)))
(setq *initialize-info-cache-initargs* initargs)
(setq *initialize-info-cache-info* ,(const (caddr form)))))
(finish-pushing-initargs
`((setq initargs-tail initargs)))))))
(defmacro iis-body (&body forms)
`(let ((initargs-tail initargs)
(slots (get-slots-or-nil instance))
(class (class-of instance))
(pv (car pv-cell))
value)
initargs instance initargs-tail pv cvector slots class value
,@forms))
(defun form-list-to-lisp (pv-cell form-list)
(let* ((forms (list form-list))
(cvector (make-array (floor (length form-list) 2)
:fill-pointer 0 :adjustable t))
(pv (car pv-cell))
(body (let ((rforms (cons nil nil)))
(loop (when (null (car forms)) (return (car rforms)))
(add-forms (first-form-to-lisp forms cvector pv)
rforms))))
(cvector-type `(simple-vector ,(length cvector))))
(values
`(lambda (pv-cell cvector)
(declare (type ,cvector-type cvector))
#'(lambda (instance initargs)
(declare #.*optimize-speed*)
(iis-body ,@body)
initargs))
(list pv-cell (coerce cvector cvector-type)))))
| null | https://raw.githubusercontent.com/binghe/PCL/7021c061c5eef1466e563c4abb664ab468ee0d80/pcl/fast-init.lisp | lisp | Package:(PCL LISP 1000 ) ; ; Syntax : Common - lisp -*-
*************************************************************************
All rights reserved.
Use and copying of this software and preparation of derivative works
based upon this software are permitted. Any distribution of this
States export control laws.
warranty about the software, its performance or its conformity to any
specification.
Any person obtaining a copy of this software is requested to send their
name and post office or electronic mail address to:
Suggestions, comments and requests for improvements are also welcome.
*************************************************************************
This file defines the optimized make-instance functions.
t or (:invalid key)
allocate-instance + shared-initialize
nil means use gf
#'(lambda (instance initargs)
(initialize-instance-simple pv-cell form-list instance initargs))
(const const)
(funcall function)
(push-initarg const)
(pop-supplied count) ; a positive odd number
(instance-set pv-offset slotd)
(skip-when-instance-boundp pv-offset slotd n) | Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation .
software or derivative works must comply with all applicable United
This software is made available AS IS , and Xerox Corporation makes no
CommonLoops Coordinator
Xerox PARC
3333 Coyote Hill Rd .
Palo Alto , CA 94304
( or send Arpanet mail to )
(in-package :pcl)
(defvar *compile-make-instance-functions-p* nil)
(defun update-make-instance-function-table (&optional (class *the-class-t*))
(when (symbolp class) (setq class (find-class class)))
(when (eq class *the-class-t*) (setq class *the-class-slot-object*))
(when (memq *the-class-slot-object* (class-precedence-list class))
(map-all-classes #'reset-class-initialize-info class)))
(defun constant-symbol-p (form)
(and (constantp form)
(let ((object (eval form)))
(and (symbolp object)
(symbol-package object)))))
(defvar *make-instance-function-keys* nil)
(defun expand-make-instance-form (form)
(let ((class (cadr form)) (initargs (cddr form))
(keys nil)(allow-other-keys-p nil) key value)
(when (and (constant-symbol-p class)
(let ((initargs-tail initargs))
(loop (when (null initargs-tail) (return t))
(unless (constant-symbol-p (car initargs-tail))
(return nil))
(setq key (eval (pop initargs-tail)))
(setq value (pop initargs-tail))
(when (eq ':allow-other-keys key)
(setq allow-other-keys-p value))
(push key keys))))
(let* ((class (eval class))
(keys (nreverse keys))
(key (list class keys allow-other-keys-p))
(sym (make-instance-function-symbol key)))
(push key *make-instance-function-keys*)
(when sym
`(,sym ',class (list ,@initargs)))))))
(defmacro expanding-make-instance-top-level (&rest forms &environment env)
(let* ((*make-instance-function-keys* nil)
(form (macroexpand `(expanding-make-instance ,@forms) env)))
`(progn
,@(when *make-instance-function-keys*
`((get-make-instance-functions ',*make-instance-function-keys*)))
,form)))
(defmacro expanding-make-instance (&rest forms &environment env)
`(progn
,@(mapcar #'(lambda (form)
(walk-form form env
#'(lambda (subform context env)
(declare (ignore env))
(or (and (eq context ':eval)
(consp subform)
(eq (car subform) 'make-instance)
(expand-make-instance-form subform))
subform))))
forms)))
(defmacro defconstructor
(name class lambda-list &rest initialization-arguments)
`(expanding-make-instance-top-level
(defun ,name ,lambda-list
(make-instance ',class ,@initialization-arguments))))
(defun get-make-instance-functions (key-list)
(dolist (key key-list)
(let* ((cell (find-class-cell (car key)))
(make-instance-function-keys
(find-class-cell-make-instance-function-keys cell))
(mif-key (cons (cadr key) (caddr key))))
(unless (find mif-key make-instance-function-keys
:test #'equal)
(push mif-key (find-class-cell-make-instance-function-keys cell))
(let ((class (find-class-cell-class cell)))
(when (and class (not (forward-referenced-class-p class)))
(update-initialize-info-internal
(initialize-info class (car mif-key) nil (cdr mif-key))
'make-instance-function)))))))
(defun make-instance-function-symbol (key)
(let* ((class (car key))
(symbolp (symbolp class)))
(when (or symbolp (classp class))
(let* ((class-name (if (symbolp class) class (class-name class)))
(keys (cadr key))
(allow-other-keys-p (caddr key)))
(when (and (or symbolp
(and (symbolp class-name)
(eq class (find-class class-name nil))))
(symbol-package class-name))
(let ((*package* *the-pcl-package*)
(*print-length* nil) (*print-level* nil)
(*print-circle* nil) (*print-case* :upcase)
(*print-pretty* nil))
(intern (format nil "MAKE-INSTANCE ~S ~S ~S"
class-name keys allow-other-keys-p))))))))
(defun make-instance-1 (class initargs)
(apply #'make-instance class initargs))
(defmacro define-cached-reader (type name trap)
(let ((reader-name (intern (format nil "~A-~A" type name)))
(cached-name (intern (format nil "~A-CACHED-~A" type name))))
`(defmacro ,reader-name (info)
`(let ((value (,',cached-name ,info)))
(if (eq value ':unknown)
(progn
(,',trap ,info ',',name)
(,',cached-name ,info))
value)))))
(eval-when (compile load eval)
(defparameter initialize-info-cached-slots
ri-valid-p
initargs-form-list
new-keys
default-initargs-function
shared-initialize-t-function
shared-initialize-nil-function
constants
make-instance-function-symbol)))
(defmacro define-initialize-info ()
(let ((cached-slot-names
(mapcar #'(lambda (name)
(intern (format nil "CACHED-~A" name)))
initialize-info-cached-slots))
(cached-names
(mapcar #'(lambda (name)
(intern (format nil "~A-CACHED-~A"
'initialize-info name)))
initialize-info-cached-slots)))
`(progn
(defstruct initialize-info
key wrapper
,@(mapcar #'(lambda (name)
`(,name :unknown))
cached-slot-names))
(defmacro reset-initialize-info-internal (info)
`(progn
,@(mapcar #'(lambda (cname)
`(setf (,cname ,info) ':unknown))
',cached-names)))
(defun initialize-info-bound-slots (info)
(let ((slots nil))
,@(mapcar #'(lambda (name cached-name)
`(unless (eq ':unknown (,cached-name info))
(push ',name slots)))
initialize-info-cached-slots cached-names)
slots))
,@(mapcar #'(lambda (name)
`(define-cached-reader initialize-info ,name
update-initialize-info-internal))
initialize-info-cached-slots))))
(define-initialize-info)
(defvar *initialize-info-cache-class* nil)
(defvar *initialize-info-cache-initargs* nil)
(defvar *initialize-info-cache-info* nil)
(defvar *revert-initialize-info-p* nil)
(defun reset-initialize-info (info)
(setf (initialize-info-wrapper info)
(class-wrapper (car (initialize-info-key info))))
(let ((slots-to-revert (if *revert-initialize-info-p*
(initialize-info-bound-slots info)
'(make-instance-function))))
(reset-initialize-info-internal info)
(dolist (slot slots-to-revert)
(update-initialize-info-internal info slot))
info))
(defun reset-class-initialize-info (class)
(reset-class-initialize-info-1 (class-initialize-info class)))
(defun reset-class-initialize-info-1 (cell)
(when (consp cell)
(when (car cell)
(reset-initialize-info (car cell)))
(let ((alist (cdr cell)))
(dolist (a alist)
(reset-class-initialize-info-1 (cdr a))))))
(defun initialize-info (class initargs &optional (plist-p t) allow-other-keys-arg)
(let ((info nil))
(if (and (eq *initialize-info-cache-class* class)
(eq *initialize-info-cache-initargs* initargs))
(setq info *initialize-info-cache-info*)
(let ((initargs-tail initargs)
(cell (or (class-initialize-info class)
(setf (class-initialize-info class) (cons nil nil)))))
(loop (when (null initargs-tail) (return nil))
(let ((keyword (pop initargs-tail))
(alist-cell cell))
(when plist-p
(if (eq keyword :allow-other-keys)
(setq allow-other-keys-arg (pop initargs-tail))
(pop initargs-tail)))
(loop (let ((alist (cdr alist-cell)))
(when (null alist)
(setq cell (cons nil nil))
(setf (cdr alist-cell) (list (cons keyword cell)))
(return nil))
(when (eql keyword (caar alist))
(setq cell (cdar alist))
(return nil))
(setq alist-cell alist)))))
(setq info (or (car cell)
(setf (car cell) (make-initialize-info))))))
(let ((wrapper (initialize-info-wrapper info)))
(unless (eq wrapper (class-wrapper class))
(unless wrapper
(let* ((initargs-tail initargs)
(klist-cell (list nil))
(klist-tail klist-cell))
(loop (when (null initargs-tail) (return nil))
(let ((key (pop initargs-tail)))
(setf (cdr klist-tail) (list key)))
(setf klist-tail (cdr klist-tail))
(when plist-p (pop initargs-tail)))
(setf (initialize-info-key info)
(list class (cdr klist-cell) allow-other-keys-arg))))
(reset-initialize-info info)))
(setq *initialize-info-cache-class* class)
(setq *initialize-info-cache-initargs* initargs)
(setq *initialize-info-cache-info* info)
info))
(defun update-initialize-info-internal (info name)
(let* ((key (initialize-info-key info))
(class (car key))
(keys (cadr key))
(allow-other-keys-arg (caddr key)))
(ecase name
((initargs-form-list new-keys)
(multiple-value-bind (initargs-form-list new-keys)
(make-default-initargs-form-list class keys)
(setf (initialize-info-cached-initargs-form-list info) initargs-form-list)
(setf (initialize-info-cached-new-keys info) new-keys)))
((default-initargs-function)
(let ((initargs-form-list (initialize-info-initargs-form-list info)))
(setf (initialize-info-cached-default-initargs-function info)
(initialize-instance-simple-function
'default-initargs-function info
class initargs-form-list))))
((valid-p ri-valid-p)
(flet ((compute-valid-p (methods)
(or (not (null allow-other-keys-arg))
(multiple-value-bind (legal allow-other-keys)
(check-initargs-values class methods)
(or (not (null allow-other-keys))
(dolist (key keys t)
(unless (member key legal)
(return (cons :invalid key)))))))))
(let ((proto (class-prototype class)))
(setf (initialize-info-cached-valid-p info)
(compute-valid-p
(list (list* 'allocate-instance class nil)
(list* 'initialize-instance proto nil)
(list* 'shared-initialize proto t nil))))
(setf (initialize-info-cached-ri-valid-p info)
(compute-valid-p
(list (list* 'reinitialize-instance proto nil)
(list* 'shared-initialize proto nil nil)))))))
((shared-initialize-t-function)
(multiple-value-bind (initialize-form-list ignore)
(make-shared-initialize-form-list class keys t nil)
(declare (ignore ignore))
(setf (initialize-info-cached-shared-initialize-t-function info)
(initialize-instance-simple-function
'shared-initialize-t-function info
class initialize-form-list))))
((shared-initialize-nil-function)
(multiple-value-bind (initialize-form-list ignore)
(make-shared-initialize-form-list class keys nil nil)
(declare (ignore ignore))
(setf (initialize-info-cached-shared-initialize-nil-function info)
(initialize-instance-simple-function
'shared-initialize-nil-function info
class initialize-form-list))))
((constants combined-initialize-function)
(let ((initargs-form-list (initialize-info-initargs-form-list info))
(new-keys (initialize-info-new-keys info)))
(multiple-value-bind (initialize-form-list constants)
(make-shared-initialize-form-list class new-keys t t)
(setf (initialize-info-cached-constants info) constants)
(setf (initialize-info-cached-combined-initialize-function info)
(initialize-instance-simple-function
'combined-initialize-function info
class (append initargs-form-list initialize-form-list))))))
((make-instance-function-symbol)
(setf (initialize-info-cached-make-instance-function-symbol info)
(make-instance-function-symbol key)))
((make-instance-function)
(let* ((function (get-make-instance-function key))
(symbol (initialize-info-make-instance-function-symbol info)))
(setf (initialize-info-cached-make-instance-function info) function)
(when symbol (setf (gdefinition symbol)
(or function #'make-instance-1)))))))
info)
(defun get-make-instance-function (key)
(let* ((class (car key))
(keys (cadr key)))
(unless (eq *boot-state* 'complete)
(return-from get-make-instance-function nil))
(when (symbolp class)
(setq class (find-class class)))
(when (classp class)
(unless (class-finalized-p class) (finalize-inheritance class)))
(let* ((initargs (mapcan #'(lambda (key) (list key nil)) keys))
(class-and-initargs (list* class initargs))
(make-instance (gdefinition 'make-instance))
(make-instance-methods
(compute-applicable-methods make-instance class-and-initargs))
(std-mi-meth (find-standard-ii-method make-instance-methods 'class))
(class+initargs (list class initargs))
(default-initargs (gdefinition 'default-initargs))
(default-initargs-methods
(compute-applicable-methods default-initargs class+initargs))
(proto (and (classp class) (class-prototype class)))
(initialize-instance-methods
(when proto
(compute-applicable-methods (gdefinition 'initialize-instance)
(list* proto initargs))))
(shared-initialize-methods
(when proto
(compute-applicable-methods (gdefinition 'shared-initialize)
(list* proto t initargs)))))
(when (null make-instance-methods)
(return-from get-make-instance-function
#'(lambda (class initargs)
(apply #'no-applicable-method make-instance class initargs))))
(unless (and (null (cdr make-instance-methods))
(eq (car make-instance-methods) std-mi-meth)
(null (cdr default-initargs-methods))
(eq (car (method-specializers (car default-initargs-methods)))
*the-class-slot-class*)
(flet ((check-meth (meth)
(let ((quals (method-qualifiers meth)))
(if (null quals)
(eq (car (method-specializers meth))
*the-class-slot-object*)
(and (null (cdr quals))
(or (eq (car quals) ':before)
(eq (car quals) ':after)))))))
(and (every #'check-meth initialize-instance-methods)
(every #'check-meth shared-initialize-methods))))
(return-from get-make-instance-function nil))
(get-make-instance-function-internal
class key (default-initargs class initargs)
initialize-instance-methods shared-initialize-methods))))
(defun get-make-instance-function-internal (class key initargs
initialize-instance-methods
shared-initialize-methods)
(let* ((keys (cadr key))
(allow-other-keys-p (caddr key))
(allocate-instance-methods
(compute-applicable-methods (gdefinition 'allocate-instance)
(list* class initargs))))
(unless allow-other-keys-p
(unless (check-initargs-1
class initargs
(append allocate-instance-methods
initialize-instance-methods
shared-initialize-methods)
t nil)
(return-from get-make-instance-function-internal nil)))
(if (or (cdr allocate-instance-methods)
(some #'complicated-instance-creation-method
initialize-instance-methods)
(some #'complicated-instance-creation-method
shared-initialize-methods))
(make-instance-function-complex
key class keys
initialize-instance-methods shared-initialize-methods)
(make-instance-function-simple
key class keys
initialize-instance-methods shared-initialize-methods))))
(defun complicated-instance-creation-method (m)
(let ((qual (method-qualifiers m)))
(if qual
(not (and (null (cdr qual)) (eq (car qual) ':after)))
(let ((specl (car (method-specializers m))))
(or (not (classp specl))
(not (eq 'slot-object (class-name specl))))))))
(defun find-standard-ii-method (methods class-names)
(dolist (m methods)
(when (null (method-qualifiers m))
(let ((specl (car (method-specializers m))))
(when (and (classp specl)
(if (listp class-names)
(member (class-name specl) class-names)
(eq (class-name specl) class-names)))
(return m))))))
(defmacro call-initialize-function (initialize-function instance initargs)
`(let ((.function. ,initialize-function))
(if (and (consp .function.)
(eq (car .function.) 'call-initialize-instance-simple))
(initialize-instance-simple (cadr .function.) (caddr .function.)
,instance ,initargs)
(funcall (the function .function.) ,instance ,initargs))))
(defun make-instance-function-simple (key class keys
initialize-instance-methods
shared-initialize-methods)
(multiple-value-bind (initialize-function constants)
(get-simple-initialization-function class keys (caddr key))
(let* ((wrapper (class-wrapper class))
(lwrapper (list wrapper))
(allocate-function
(cond ((structure-class-p class)
#'allocate-structure-instance)
((standard-class-p class)
#'allocate-standard-instance)
((funcallable-standard-class-p class)
#'allocate-funcallable-instance)
(t
(error "error in make-instance-function-simple"))))
(std-si-meth (find-standard-ii-method shared-initialize-methods
'slot-object))
(shared-initfns
(nreverse (mapcar #'(lambda (method)
(make-effective-method-function
#'shared-initialize
`(call-method ,method nil)
nil lwrapper))
(remove std-si-meth shared-initialize-methods))))
(std-ii-meth (find-standard-ii-method initialize-instance-methods
'slot-object))
(initialize-initfns
(nreverse (mapcar #'(lambda (method)
(make-effective-method-function
#'initialize-instance
`(call-method ,method nil)
nil lwrapper))
(remove std-ii-meth
initialize-instance-methods)))))
#'(lambda (class1 initargs)
(if (not (eq wrapper (class-wrapper class)))
(let* ((info (initialize-info class1 initargs))
(fn (initialize-info-make-instance-function info)))
(declare (type function fn))
(funcall fn class1 initargs))
(let* ((instance (funcall allocate-function wrapper constants))
(initargs (call-initialize-function initialize-function
instance initargs)))
(dolist (fn shared-initfns)
(invoke-effective-method-function fn t instance t initargs))
(dolist (fn initialize-initfns)
(invoke-effective-method-function fn t instance initargs))
instance))))))
(defun make-instance-function-complex (key class keys
initialize-instance-methods
shared-initialize-methods)
(multiple-value-bind (initargs-function initialize-function)
(get-complex-initialization-functions class keys (caddr key))
(let* ((wrapper (class-wrapper class))
(shared-initialize
(get-secondary-dispatch-function
#'shared-initialize shared-initialize-methods
`((class-eq ,class) t t)
`((,(find-standard-ii-method shared-initialize-methods 'slot-object)
,#'(lambda (instance init-type &rest initargs)
(declare (ignore init-type))
#+copy-&rest-arg (setq initargs (copy-list initargs))
(call-initialize-function initialize-function
instance initargs)
instance)))
(list wrapper *the-wrapper-of-t* *the-wrapper-of-t*)))
(initialize-instance
(get-secondary-dispatch-function
#'initialize-instance initialize-instance-methods
`((class-eq ,class) t)
`((,(find-standard-ii-method initialize-instance-methods 'slot-object)
,#'(lambda (instance &rest initargs)
#+copy-&rest-arg (setq initargs (copy-list initargs))
(invoke-effective-method-function
shared-initialize t instance t initargs))))
(list wrapper *the-wrapper-of-t*))))
#'(lambda (class1 initargs)
(if (not (eq wrapper (class-wrapper class)))
(let* ((info (initialize-info class1 initargs))
(fn (initialize-info-make-instance-function info)))
(declare (type function fn))
(funcall fn class1 initargs))
(let* ((initargs (call-initialize-function initargs-function
nil initargs))
(instance (apply #'allocate-instance class initargs)))
(invoke-effective-method-function
initialize-instance t instance initargs)
instance))))))
(defun get-simple-initialization-function (class keys &optional allow-other-keys-arg)
(let ((info (initialize-info class keys nil allow-other-keys-arg)))
(values (initialize-info-combined-initialize-function info)
(initialize-info-constants info))))
(defun get-complex-initialization-functions (class keys &optional allow-other-keys-arg
separate-p)
(let* ((info (initialize-info class keys nil allow-other-keys-arg))
(default-initargs-function (initialize-info-default-initargs-function info)))
(if separate-p
(values default-initargs-function
(initialize-info-shared-initialize-t-function info))
(values default-initargs-function
(initialize-info-shared-initialize-t-function
(initialize-info class (initialize-info-new-keys info)
nil allow-other-keys-arg))))))
(defun add-forms (forms forms-list)
(when forms
(setq forms (copy-list forms))
(if (null (car forms-list))
(setf (car forms-list) forms)
(setf (cddr forms-list) forms))
(setf (cdr forms-list) (last forms)))
(car forms-list))
(defun make-default-initargs-form-list (class keys &optional (separate-p t))
(let ((initargs-form-list (cons nil nil))
(default-initargs (class-default-initargs class))
(nkeys keys))
(dolist (default default-initargs)
(let ((key (car default))
(function (cadr default)))
(unless (member key nkeys)
(add-forms `((funcall ,function) (push-initarg ,key))
initargs-form-list)
(push key nkeys))))
(when separate-p
(add-forms `((update-initialize-info-cache
,class ,(initialize-info class nkeys nil)))
initargs-form-list))
(add-forms `((finish-pushing-initargs))
initargs-form-list)
(values (car initargs-form-list) nkeys)))
(defun make-shared-initialize-form-list (class keys si-slot-names simple-p)
(let* ((initialize-form-list (cons nil nil))
(type (cond ((structure-class-p class)
'structure)
((standard-class-p class)
'standard)
((funcallable-standard-class-p class)
'funcallable)
(t (error "error in make-shared-initialize-form-list"))))
(wrapper (class-wrapper class))
(constants (when simple-p
(make-list (wrapper-no-of-instance-slots wrapper)
':initial-element *slot-unbound*)))
(slots (class-slots class))
(slot-names (mapcar #'slot-definition-name slots))
(slots-key (mapcar #'(lambda (slot)
(let ((index most-positive-fixnum))
(dolist (key (slot-definition-initargs slot))
(let ((pos (position key keys)))
(when pos (setq index (min index pos)))))
(cons slot index)))
slots))
(slots (stable-sort slots-key #'< :key #'cdr)))
(let ((n-popped 0))
(dolist (slot+index slots)
(let* ((slot (car slot+index))
(name (slot-definition-name slot))
(npop (1+ (- (cdr slot+index) n-popped))))
(unless (eql (cdr slot+index) most-positive-fixnum)
(let* ((pv-offset (1+ (position name slot-names))))
(add-forms `(,@(when (plusp npop)
`((pop-initargs ,(* 2 npop))))
(instance-set ,pv-offset ,slot))
initialize-form-list))
(incf n-popped npop)))))
(dolist (slot+index slots)
(let* ((slot (car slot+index))
(name (slot-definition-name slot)))
(when (and (eql (cdr slot+index) most-positive-fixnum)
(or (eq si-slot-names 't)
(member name si-slot-names)))
(let* ((initform (slot-definition-initform slot))
(initfunction (slot-definition-initfunction slot))
(location (unless (eq type 'structure)
(slot-definition-location slot)))
(pv-offset (1+ (position name slot-names)))
(forms (cond ((null initfunction)
nil)
((constantp initform)
(let ((value (funcall initfunction)))
(if (and simple-p (integerp location))
(progn (setf (nth location constants) value)
nil)
`((const ,value)
(instance-set ,pv-offset ,slot)))))
(t
`((funcall ,(slot-definition-initfunction slot))
(instance-set ,pv-offset ,slot))))))
(add-forms `(,@(unless (or simple-p (null forms))
`((skip-when-instance-boundp ,pv-offset ,slot
,(length forms))))
,@forms)
initialize-form-list)))))
(values (car initialize-form-list) constants)))
(defvar *class-pv-table-table* (make-hash-table :test 'eq))
(defun get-pv-cell-for-class (class)
(let* ((slot-names (mapcar #'slot-definition-name (class-slots class)))
(slot-name-lists (list (cons nil slot-names)))
(pv-table (gethash class *class-pv-table-table*)))
(unless (and pv-table
(equal slot-name-lists (pv-table-slot-name-lists pv-table)))
(setq pv-table (intern-pv-table :slot-name-lists slot-name-lists))
(setf (gethash class *class-pv-table-table*) pv-table))
(pv-table-lookup pv-table (class-wrapper class))))
(defvar *initialize-instance-simple-alist* nil)
(defvar *note-iis-entry-p* nil)
(defvar *compiled-initialize-instance-simple-functions*
(make-hash-table :test #'equal))
(defun initialize-instance-simple-function (use info class form-list)
(let* ((pv-cell (get-pv-cell-for-class class))
(key (initialize-info-key info))
(sf-key (list* use (class-name (car key)) (cdr key))))
(if (or *compile-make-instance-functions-p*
(gethash sf-key *compiled-initialize-instance-simple-functions*))
(multiple-value-bind (form args)
(form-list-to-lisp pv-cell form-list)
(let ((entry (assoc form *initialize-instance-simple-alist*
:test #'equal)))
(setf (gethash sf-key
*compiled-initialize-instance-simple-functions*)
t)
(if entry
(setf (cdddr entry) (union (list sf-key) (cdddr entry)
:test #'equal))
(progn
(setq entry (list* form nil nil (list sf-key)))
(setq *initialize-instance-simple-alist*
(nconc *initialize-instance-simple-alist*
(list entry)))))
(unless (or *note-iis-entry-p* (cadr entry))
(setf (cadr entry) (compile-lambda (car entry))))
(if (cadr entry)
(apply (the function (cadr entry)) args)
`(call-initialize-instance-simple ,pv-cell ,form-list))))
`(call-initialize-instance-simple ,pv-cell ,form-list))))
(defun load-precompiled-iis-entry (form function system uses)
(let ((entry (assoc form *initialize-instance-simple-alist*
:test #'equal)))
(unless entry
(setq entry (list* form nil nil nil))
(setq *initialize-instance-simple-alist*
(nconc *initialize-instance-simple-alist*
(list entry))))
(setf (cadr entry) function)
(setf (caddr entry) system)
(dolist (use uses)
(setf (gethash use *compiled-initialize-instance-simple-functions*) t))
(setf (cdddr entry) (union uses (cdddr entry)
:test #'equal))))
(defmacro precompile-iis-functions (&optional system)
(let ((index -1))
`(progn
,@(gathering1 (collecting)
(dolist (iis-entry *initialize-instance-simple-alist*)
(when (or (null (caddr iis-entry))
(eq (caddr iis-entry) system))
(when system (setf (caddr iis-entry) system))
(gather1
(make-top-level-form
`(precompile-initialize-instance-simple ,system ,(incf index))
'(load)
`(load-precompiled-iis-entry
',(car iis-entry)
#',(car iis-entry)
',system
',(cdddr iis-entry))))))))))
(defun compile-iis-functions (after-p)
(let ((*compile-make-instance-functions-p* t)
(*revert-initialize-info-p* t)
(*note-iis-entry-p* (not after-p)))
(declare (special *compile-make-instance-functions-p*))
(when (eq *boot-state* 'complete)
(update-make-instance-function-table))))
(defun initialize-instance-simple (pv-cell form-list instance initargs)
(let ((pv (car pv-cell))
(initargs-tail initargs)
(slots (get-slots-or-nil instance))
(class (class-of instance))
value)
(loop (when (null form-list) (return nil))
(let ((form (pop form-list)))
(ecase (car form)
(push-initarg
(push value initargs)
(push (cadr form) initargs))
(const
(setq value (cadr form)))
(funcall
(setq value (funcall (the function (cadr form)))))
(pop-initargs
(setq initargs-tail (nthcdr (1- (cadr form)) initargs-tail))
(setq value (pop initargs-tail)))
(instance-set
(instance-write-internal
pv slots (cadr form) value
(setf (slot-value-using-class class instance (caddr form)) value)))
(skip-when-instance-boundp
(when (instance-boundp-internal
pv slots (cadr form)
(slot-boundp-using-class class instance (caddr form)))
(dotimes (i (cadddr form))
(pop form-list))))
(update-initialize-info-cache
(when (consp initargs)
(setq initargs (cons (car initargs) (cdr initargs))))
(setq *initialize-info-cache-class* (cadr form))
(setq *initialize-info-cache-initargs* initargs)
(setq *initialize-info-cache-info* (caddr form)))
(finish-pushing-initargs
(setq initargs-tail initargs)))))
initargs))
(defun add-to-cvector (cvector constant)
(or (position constant cvector)
(prog1 (fill-pointer cvector)
(vector-push-extend constant cvector))))
(defvar *inline-iis-instance-locations-p* t)
(defun first-form-to-lisp (forms cvector pv)
(flet ((const (constant)
(cond ((or (numberp constant) (characterp constant))
constant)
((and (symbolp constant) (symbol-package constant))
`',constant)
(t
`(svref cvector ,(add-to-cvector cvector constant))))))
(let ((form (pop (car forms))))
(ecase (car form)
(push-initarg
`((push value initargs)
(push ,(const (cadr form)) initargs)))
(const
`((setq value ,(const (cadr form)))))
(funcall
`((setq value (funcall (the function ,(const (cadr form)))))))
(pop-initargs
`((setq initargs-tail (,@(let ((pop (1- (cadr form))))
(case pop
(1 `(cdr))
(3 `(cdddr))
(t `(nthcdr ,pop))))
initargs-tail))
(setq value (pop initargs-tail))))
(instance-set
(let* ((pv-offset (cadr form))
(location (pvref pv pv-offset))
(default `(setf (slot-value-using-class class instance
,(const (caddr form)))
value)))
(if *inline-iis-instance-locations-p*
(typecase location
(fixnum `((setf (%instance-ref slots ,(const location)) value)))
(cons `((setf (cdr ,(const location)) value)))
(t `(,default)))
`((instance-write-internal pv slots ,(const pv-offset) value
,default
,(typecase location
(fixnum ':instance)
(cons ':class)
(t ':default)))))))
(skip-when-instance-boundp
(let* ((pv-offset (cadr form))
(location (pvref pv pv-offset))
(default `(slot-boundp-using-class class instance
,(const (caddr form)))))
`((unless ,(if *inline-iis-instance-locations-p*
(typecase location
(fixnum `(not (eq (%instance-ref slots ,(const location))
',*slot-unbound*)))
(cons `(not (eq (cdr ,(const location)) ',*slot-unbound*)))
(t default))
`(instance-boundp-internal pv slots ,(const pv-offset)
,default
,(typecase (pvref pv pv-offset)
(fixnum ':instance)
(cons ':class)
(t ':default))))
,@(let ((sforms (cons nil nil)))
(dotimes (i (cadddr form) (car sforms))
(add-forms (first-form-to-lisp forms cvector pv) sforms)))))))
(update-initialize-info-cache
`((when (consp initargs)
(setq initargs (cons (car initargs) (cdr initargs))))
(setq *initialize-info-cache-class* ,(const (cadr form)))
(setq *initialize-info-cache-initargs* initargs)
(setq *initialize-info-cache-info* ,(const (caddr form)))))
(finish-pushing-initargs
`((setq initargs-tail initargs)))))))
(defmacro iis-body (&body forms)
`(let ((initargs-tail initargs)
(slots (get-slots-or-nil instance))
(class (class-of instance))
(pv (car pv-cell))
value)
initargs instance initargs-tail pv cvector slots class value
,@forms))
(defun form-list-to-lisp (pv-cell form-list)
(let* ((forms (list form-list))
(cvector (make-array (floor (length form-list) 2)
:fill-pointer 0 :adjustable t))
(pv (car pv-cell))
(body (let ((rforms (cons nil nil)))
(loop (when (null (car forms)) (return (car rforms)))
(add-forms (first-form-to-lisp forms cvector pv)
rforms))))
(cvector-type `(simple-vector ,(length cvector))))
(values
`(lambda (pv-cell cvector)
(declare (type ,cvector-type cvector))
#'(lambda (instance initargs)
(declare #.*optimize-speed*)
(iis-body ,@body)
initargs))
(list pv-cell (coerce cvector cvector-type)))))
|
3e66f7f52523cdf5da9091cff5e135a5f770f1f6418307e006b0592ccdb73dd7 | melange-re/melange | leaf.ml | (* module Other = Other *)
let x = Other.t
let t = 1
| null | https://raw.githubusercontent.com/melange-re/melange/0d838a0c3bdac37a23bb558a29e66e2eee3eed8a/test/shadow-internal-lib.t/node/leaf.ml | ocaml | module Other = Other |
let x = Other.t
let t = 1
|
df3ce58ba3a5c5a4b305b2fd1c56f19a48331e12b2381f791c130e783d102580 | cl-axon/shop2 | problem-converter.lisp | (in-package :common-lisp-user)
(defun parse-object-list (object-list)
(unless (null object-list)
(cons (list (third object-list) (first object-list)) (parse-object-list (cdr (cdr (cdr object-list)))))))
(setq problems '(
"pfile1"
"pfile2"
"pfile3"
"pfile4"
"pfile5"
"pfile6"
"pfile7"
"pfile8"
"pfile9"
"pfile10"
"pfile11"
"pfile12"
"pfile13"
"pfile14"
"pfile15"
"pfile16"
"pfile17"
"pfile18"
"pfile19"
"pfile20"))
(defun all-convert()
(dolist (prob problems)
(p-convert prob
(concatenate 'string "./" prob)
(concatenate 'string "./" prob ".lisp"))))
(defun p-convert (problem-name pddl-file shop-file)
(progn
(with-open-file (instr pddl-file :direction :input)
(let ((pddl (read instr)))
(with-open-file (outstr shop-file :direction :output
:if-exists :supersede)
(format outstr "(in-package :shop2-user)~%")
(format outstr "(defproblem ")
(format outstr (concatenate 'string "" problem-name))
(format outstr " ZENOTRAVEL ~%")
;;; getting the objects
(setq object-list (cdr (nth 3 pddl)))
;;; getting the initial state
(setq init-state (append (parse-object-list object-list) (cdr (nth 4 pddl))))
;;; getting the goals
(setq goal-list (mapcar #'(lambda (x) (cdr x)) (rest (first (cdr (nth 5 pddl))))))
;;; getting the metric
(setq metric (third (nth 6 pddl)))
(setq a-list nil)
(setq p-list nil)
(format outstr "( ~%")
(when (eq (first metric) '+)
(setq exp (second metric))
(cond ((eq (first exp) '+)
(format outstr "(TOTALTIME-COEFF ~s)~%" (second (second exp)))
(format outstr "(DRIVEN-COEFF ~s)~%" (second (third exp)))
(format outstr "(WALKED-COEFF ~s)~%" (second (third metric))))
(t
(format outstr "(TOTALTIME-COEFF ~s)~%" (second exp))
(format outstr "(FUELUSED-COEFF ~s)~%" (second (third metric))))))
(format outstr "(MAXTIME 0)~%")
(dolist (atom init-state)
(cond ((eq (first atom) 'aircraft)
(format outstr "~s ~%" atom)
(format outstr "(TIMESTAMP ~s 0)~%" (second atom))
(format outstr "(PTIMESTAMP ~s 0)~%" (second atom))
(setq a-list (cons (second atom) a-list))
)
((eq (first atom) 'person)
(format outstr "~s ~%" atom)
(format outstr (if (setq x (assoc (second atom) goal-list))
"~s~%"
"")
(if x (cons 'GOAL x)))
(setq p-list (cons (second atom) p-list))
)
((and (eq (first atom) '=)
(or (eq (first (second atom)) 'fuel)
(eq (first (second atom)) 'distance)
(eq (first (second atom)) 'refuel-rate)
(eq (first (second atom)) 'slow-speed)
(eq (first (second atom)) 'fast-speed)
(eq (first (second atom)) 'slow-burn)
(eq (first (second atom)) 'fast-burn)
(eq (first (second atom)) 'capacity)
(eq (first (second atom)) 'boarding-time)
(eq (first (second atom)) 'debarking-time)
(eq (first (second atom)) 'total-fuel-used)
(eq (first (second atom)) 'onboard)
(eq (first (second atom)) 'zoom-limit)
))
(format outstr "~s~%" (append (second atom) (list (third atom))))
)
(t
(format outstr "~s ~%" atom)
)))
(format outstr ") ~%")
(format outstr "(:ordered ~%")
; (format outstr "(:task !!preprocessing ~s) ~%" shop-file)
(format outstr "(:unordered ~%")
(dolist (p (reverse p-list))
(if (setq tuple (assoc p goal-list))
(format outstr "(:task transport-person ~s ~s)~%"
(first tuple) (second tuple))))
(format outstr ") ~%")
(format outstr "(:unordered ~%")
(dolist (ar (reverse a-list))
(if (setq tuple (assoc ar goal-list))
(format outstr "(:task transport-aircraft ~s ~s)~%"
(first tuple) (second tuple))))
(format outstr ") ~%")
(format outstr ") ~%")
(format outstr ") ~%")
)))))
(all-convert)
| null | https://raw.githubusercontent.com/cl-axon/shop2/9136e51f7845b46232cc17ca3618f515ddcf2787/examples/IPC-2002/ZenoTravel/SimpleTime/easy_probs/problem-converter.lisp | lisp | getting the objects
getting the initial state
getting the goals
getting the metric
(format outstr "(:task !!preprocessing ~s) ~%" shop-file) | (in-package :common-lisp-user)
(defun parse-object-list (object-list)
(unless (null object-list)
(cons (list (third object-list) (first object-list)) (parse-object-list (cdr (cdr (cdr object-list)))))))
(setq problems '(
"pfile1"
"pfile2"
"pfile3"
"pfile4"
"pfile5"
"pfile6"
"pfile7"
"pfile8"
"pfile9"
"pfile10"
"pfile11"
"pfile12"
"pfile13"
"pfile14"
"pfile15"
"pfile16"
"pfile17"
"pfile18"
"pfile19"
"pfile20"))
(defun all-convert()
(dolist (prob problems)
(p-convert prob
(concatenate 'string "./" prob)
(concatenate 'string "./" prob ".lisp"))))
(defun p-convert (problem-name pddl-file shop-file)
(progn
(with-open-file (instr pddl-file :direction :input)
(let ((pddl (read instr)))
(with-open-file (outstr shop-file :direction :output
:if-exists :supersede)
(format outstr "(in-package :shop2-user)~%")
(format outstr "(defproblem ")
(format outstr (concatenate 'string "" problem-name))
(format outstr " ZENOTRAVEL ~%")
(setq object-list (cdr (nth 3 pddl)))
(setq init-state (append (parse-object-list object-list) (cdr (nth 4 pddl))))
(setq goal-list (mapcar #'(lambda (x) (cdr x)) (rest (first (cdr (nth 5 pddl))))))
(setq metric (third (nth 6 pddl)))
(setq a-list nil)
(setq p-list nil)
(format outstr "( ~%")
(when (eq (first metric) '+)
(setq exp (second metric))
(cond ((eq (first exp) '+)
(format outstr "(TOTALTIME-COEFF ~s)~%" (second (second exp)))
(format outstr "(DRIVEN-COEFF ~s)~%" (second (third exp)))
(format outstr "(WALKED-COEFF ~s)~%" (second (third metric))))
(t
(format outstr "(TOTALTIME-COEFF ~s)~%" (second exp))
(format outstr "(FUELUSED-COEFF ~s)~%" (second (third metric))))))
(format outstr "(MAXTIME 0)~%")
(dolist (atom init-state)
(cond ((eq (first atom) 'aircraft)
(format outstr "~s ~%" atom)
(format outstr "(TIMESTAMP ~s 0)~%" (second atom))
(format outstr "(PTIMESTAMP ~s 0)~%" (second atom))
(setq a-list (cons (second atom) a-list))
)
((eq (first atom) 'person)
(format outstr "~s ~%" atom)
(format outstr (if (setq x (assoc (second atom) goal-list))
"~s~%"
"")
(if x (cons 'GOAL x)))
(setq p-list (cons (second atom) p-list))
)
((and (eq (first atom) '=)
(or (eq (first (second atom)) 'fuel)
(eq (first (second atom)) 'distance)
(eq (first (second atom)) 'refuel-rate)
(eq (first (second atom)) 'slow-speed)
(eq (first (second atom)) 'fast-speed)
(eq (first (second atom)) 'slow-burn)
(eq (first (second atom)) 'fast-burn)
(eq (first (second atom)) 'capacity)
(eq (first (second atom)) 'boarding-time)
(eq (first (second atom)) 'debarking-time)
(eq (first (second atom)) 'total-fuel-used)
(eq (first (second atom)) 'onboard)
(eq (first (second atom)) 'zoom-limit)
))
(format outstr "~s~%" (append (second atom) (list (third atom))))
)
(t
(format outstr "~s ~%" atom)
)))
(format outstr ") ~%")
(format outstr "(:ordered ~%")
(format outstr "(:unordered ~%")
(dolist (p (reverse p-list))
(if (setq tuple (assoc p goal-list))
(format outstr "(:task transport-person ~s ~s)~%"
(first tuple) (second tuple))))
(format outstr ") ~%")
(format outstr "(:unordered ~%")
(dolist (ar (reverse a-list))
(if (setq tuple (assoc ar goal-list))
(format outstr "(:task transport-aircraft ~s ~s)~%"
(first tuple) (second tuple))))
(format outstr ") ~%")
(format outstr ") ~%")
(format outstr ") ~%")
)))))
(all-convert)
|
d1596bef36a32b3b00ef5109ca961715a27b3fe95c8277a33888efdd690d7842 | jimcrayne/jhc | Property.hs | module Info.Property where
import Data.Dynamic
import Data.Monoid
import Info.Properties
import Util.BitSet
import Util.HasSize
import Util.SetLike
instance Show Properties where
showsPrec _ props = shows (toList props)
-- | list of properties of a function, such as specified by use pragmas or options
newtype Properties = Properties (EnumBitSet Property)
deriving(Eq,Collection,SetLike,HasSize,Monoid,Unionize,IsEmpty)
type instance Elem Properties = Property
type instance Key Properties = Property
class HasProperties a where
modifyProperties :: (Properties -> Properties) -> a -> a
getProperties :: a -> Properties
putProperties :: Properties -> a -> a
setProperty :: Property -> a -> a
unsetProperty :: Property -> a -> a
getProperty :: Property -> a -> Bool
setProperties :: [Property] -> a -> a
unsetProperty prop = modifyProperties (delete prop)
setProperty prop = modifyProperties (insert prop)
setProperties xs = modifyProperties (`mappend` fromList xs)
getProperty atom = member atom . getProperties
instance HasProperties Properties where
getProperties prop = prop
putProperties prop _ = prop
modifyProperties f = f
| null | https://raw.githubusercontent.com/jimcrayne/jhc/1ff035af3d697f9175f8761c8d08edbffde03b4e/src/Info/Property.hs | haskell | | list of properties of a function, such as specified by use pragmas or options | module Info.Property where
import Data.Dynamic
import Data.Monoid
import Info.Properties
import Util.BitSet
import Util.HasSize
import Util.SetLike
instance Show Properties where
showsPrec _ props = shows (toList props)
newtype Properties = Properties (EnumBitSet Property)
deriving(Eq,Collection,SetLike,HasSize,Monoid,Unionize,IsEmpty)
type instance Elem Properties = Property
type instance Key Properties = Property
class HasProperties a where
modifyProperties :: (Properties -> Properties) -> a -> a
getProperties :: a -> Properties
putProperties :: Properties -> a -> a
setProperty :: Property -> a -> a
unsetProperty :: Property -> a -> a
getProperty :: Property -> a -> Bool
setProperties :: [Property] -> a -> a
unsetProperty prop = modifyProperties (delete prop)
setProperty prop = modifyProperties (insert prop)
setProperties xs = modifyProperties (`mappend` fromList xs)
getProperty atom = member atom . getProperties
instance HasProperties Properties where
getProperties prop = prop
putProperties prop _ = prop
modifyProperties f = f
|
c492928fb65b51c645bd56e7e68ad1442aaaad451db1ab552f936c5e494ea63a | Tyruiop/syncretism | state.cljs | (ns synfron.state
(:require
[cljs.reader :refer [read-string]]
[reagent.core :as r]
["idb-keyval" :as idb]
[synfron.time :refer [cur-local-time]]))
(def worker (js/Worker. "/js/worker.js"))
(def app-state
(r/atom
{;; :home | :options | :search
:cur-view :home
;; Whether the sidebar is visible
:sidebar true
:home
{;; Which options are being tracked + their data
:tracked-options {}
:columns #{:contractSymbol :symbol :optType :strike
:expiration :impliedVolatility :bid :ask :lastPrice
:volume :openInterest :lastCrawl}
;; Store historical data
:historical {}
;; User spreads, relie on the data in `:options :ladder`
:spreads #{}}
:filters
{;; Current values of different filters
:values {}
;; Are we searching for a specific filter
:search nil
;; Window to load/delete existing filter
:management false
;; List of saved filters
:saved {2 ["θ crush" {"min-price" 10.0 "max-exp" 60 "itm" false}]
3 ["YOLO" {"min-exp" 250, "stock" true, "calls" true, "max-diff" 10, "itm" false, "puts" true, "max-price" 1, "etf" false, "otm" true, "exclude" true, "order-by" "md_desc", "active" true}]}}
:options
{;; Which options have their info box opened
:infobox #{}
;; Which columns do we show (with sane defaults)
:columns #{:contractSymbol :symbol :optType :strike
:expiration :impliedVolatility :bid :ask :lastPrice
:volume :openInterest}
;; search result
:data {}
;; option ladders
:ladder {}
;; Which options do we want to see a spread for
:spreads #{}
;; Which column do we use to sort the results (& asc or desc), e.g. [:gamma "asc"]
:order-col nil}
Is there an alert to display on FE .
:alert nil
}))
(defn print-cur-opts [] (println (get-in @app-state [:options :data])))
(defn print-cur-filter [] (println (get-in @app-state [:filters :values])))
(defn print-cur-hist [] (println (map #(get % "timestamp") (take 5 (get-in @app-state [:historical])))))
(defn print-home-data [] (println (get-in @app-state [:home :tracked-options])))
(defn print-home-spreads [] (println (get-in @app-state [:home :spreads])))
(defn print-catalysts [] (println (get-in @app-state [:options :data :catalysts])))
(defn toggle-set [s el]
(if (contains? s el)
(disj s el)
(conj s el)))
(defn swap-view [view] (swap! app-state #(assoc % :cur-view view)))
(defn reset-alert [] (swap! app-state #(assoc % :alert nil)))
(defn trigger-alert
[class text]
(swap! app-state #(assoc % :alert {:class class :text text}))
(js/setTimeout reset-alert 2500))
(defn toggle-sidebar [] (swap! app-state #(update % :sidebar not)))
;; To call every time the state needs to be saved locally.
(def key-name "syncretism-local")
(defn save-state
[]
(let [clean-state (-> @app-state
(assoc :cur-view :home)
(assoc :alert nil)
(assoc-in [:options :data] {})
(assoc-in [:options :ladder] {})
(assoc-in [:options :spreads] #{}))]
(->
(js/Promise.resolve
(idb/set key-name (pr-str clean-state)))
(.then (fn [_] (trigger-alert :success "Saved user state."))))))
;; To load
(defn load-state
[]
(-> (idb/get key-name)
(.then
(fn [data]
(when data
(reset! app-state (read-string data)))))
(.catch
(fn [err]
(.log js/console "No data saved.")))))
;; Filter functions
(defn swap-filter-search [txt]
(swap! app-state #(assoc-in % [:filters :search] (if (= txt "") nil txt))))
(defn forget-filter [id]
(swap! app-state #(update-in % [:filters :saved] dissoc id))
(save-state))
(defn set-cur-filter [v]
(swap! app-state #(assoc-in % [:filters :values] v)))
(defn update-cur-filter [k v]
(swap! app-state #(assoc-in % [:filters :values k] v)))
(defn save-filter [title data]
(swap! app-state #(assoc-in % [:filters :saved (str (random-uuid))] [title data]))
(save-state))
;; Options listing functions
(defn toggle-column [col-id]
(swap! app-state #(update-in % [:options :columns] toggle-set col-id))
(save-state))
(defn set-data [data]
(swap! app-state #(assoc-in % [:options :data] data)))
(defn append-data
[{:keys [catalysts options quotes]}]
(swap! app-state #(update-in % [:options :data :catalysts] merge catalysts))
(swap! app-state #(update-in % [:options :data :quotes] merge quotes))
(swap! app-state (fn [old]
(update-in
old [:options :data :options]
#(-> %
(into options)
distinct)))))
(defn toggle-spread [home? cs]
(swap! app-state #(update-in % [(if home? :home :options) :spreads] toggle-set cs)))
(defn toggle-tracked-options [cs data]
(if (contains? (get-in @app-state [:home :tracked-options]) cs)
(do
(swap! app-state #(update-in % [:home :tracked-options] dissoc cs))
(swap! app-state #(update-in % [:home :historical] dissoc cs)))
(do
(swap! app-state #(update-in % [:home :tracked-options] assoc-in [cs :data] data))
(.postMessage worker (clj->js {:message "historical" :data cs}))))
(save-state))
(defn toggle-order-by-opts
[v]
(swap! app-state #(assoc-in % [:options :order-col] v)))
;; Dashboard functions
(defn init-historical [cs data]
(swap! app-state
#(assoc-in % [:home :historical cs] {:data data :left "bid" :right "delta"}))
(save-state))
(defn toggle-chart [cs side v]
(swap! app-state #(assoc-in % [:home :historical cs side] v)))
(defn set-cs-time [cs ts]
(swap! app-state #(assoc-in % [:home :tracked-options cs :ts] ts)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Service worker handling ( communication between app & SW )
(defn err-message
[message]
(println "Unknown message:" message))
(defn parse-message
[e]
(let [{:keys [message data]} (js->clj (.-data e) :keywordize-keys true)]
(case message
"pong" (println data)
"search" (do
(set-data data)
(swap-view :options))
"search-append" (append-data data)
"ladder" (let [[ladder-def ladder-data] data]
(swap! app-state #(assoc-in % [:options :ladder ladder-def] ladder-data)))
"contract"
(let [[cs cs-data] data]
(swap! app-state #(-> %
(assoc-in [:home :tracked-options cs :data] cs-data)
(assoc-in [:home :tracked-options cs :ts] (cur-local-time)))))
"historical" (let [[cs cs-data] data]
(init-historical cs cs-data))
(err-message message))))
(.. worker (addEventListener "message" parse-message))
(defn test-sw []
(.postMessage worker (clj->js {:message "ping"})))
| null | https://raw.githubusercontent.com/Tyruiop/syncretism/0b6152ac87be35b7edbd0f282c6580befce19290/syncretism-frontend/src/main/synfron/state.cljs | clojure | :home | :options | :search
Whether the sidebar is visible
Which options are being tracked + their data
Store historical data
User spreads, relie on the data in `:options :ladder`
Current values of different filters
Are we searching for a specific filter
Window to load/delete existing filter
List of saved filters
Which options have their info box opened
Which columns do we show (with sane defaults)
search result
option ladders
Which options do we want to see a spread for
Which column do we use to sort the results (& asc or desc), e.g. [:gamma "asc"]
To call every time the state needs to be saved locally.
To load
Filter functions
Options listing functions
Dashboard functions
| (ns synfron.state
(:require
[cljs.reader :refer [read-string]]
[reagent.core :as r]
["idb-keyval" :as idb]
[synfron.time :refer [cur-local-time]]))
(def worker (js/Worker. "/js/worker.js"))
(def app-state
(r/atom
:cur-view :home
:sidebar true
:home
:tracked-options {}
:columns #{:contractSymbol :symbol :optType :strike
:expiration :impliedVolatility :bid :ask :lastPrice
:volume :openInterest :lastCrawl}
:historical {}
:spreads #{}}
:filters
:values {}
:search nil
:management false
:saved {2 ["θ crush" {"min-price" 10.0 "max-exp" 60 "itm" false}]
3 ["YOLO" {"min-exp" 250, "stock" true, "calls" true, "max-diff" 10, "itm" false, "puts" true, "max-price" 1, "etf" false, "otm" true, "exclude" true, "order-by" "md_desc", "active" true}]}}
:options
:infobox #{}
:columns #{:contractSymbol :symbol :optType :strike
:expiration :impliedVolatility :bid :ask :lastPrice
:volume :openInterest}
:data {}
:ladder {}
:spreads #{}
:order-col nil}
Is there an alert to display on FE .
:alert nil
}))
(defn print-cur-opts [] (println (get-in @app-state [:options :data])))
(defn print-cur-filter [] (println (get-in @app-state [:filters :values])))
(defn print-cur-hist [] (println (map #(get % "timestamp") (take 5 (get-in @app-state [:historical])))))
(defn print-home-data [] (println (get-in @app-state [:home :tracked-options])))
(defn print-home-spreads [] (println (get-in @app-state [:home :spreads])))
(defn print-catalysts [] (println (get-in @app-state [:options :data :catalysts])))
(defn toggle-set [s el]
(if (contains? s el)
(disj s el)
(conj s el)))
(defn swap-view [view] (swap! app-state #(assoc % :cur-view view)))
(defn reset-alert [] (swap! app-state #(assoc % :alert nil)))
(defn trigger-alert
[class text]
(swap! app-state #(assoc % :alert {:class class :text text}))
(js/setTimeout reset-alert 2500))
(defn toggle-sidebar [] (swap! app-state #(update % :sidebar not)))
(def key-name "syncretism-local")
(defn save-state
[]
(let [clean-state (-> @app-state
(assoc :cur-view :home)
(assoc :alert nil)
(assoc-in [:options :data] {})
(assoc-in [:options :ladder] {})
(assoc-in [:options :spreads] #{}))]
(->
(js/Promise.resolve
(idb/set key-name (pr-str clean-state)))
(.then (fn [_] (trigger-alert :success "Saved user state."))))))
(defn load-state
[]
(-> (idb/get key-name)
(.then
(fn [data]
(when data
(reset! app-state (read-string data)))))
(.catch
(fn [err]
(.log js/console "No data saved.")))))
(defn swap-filter-search [txt]
(swap! app-state #(assoc-in % [:filters :search] (if (= txt "") nil txt))))
(defn forget-filter [id]
(swap! app-state #(update-in % [:filters :saved] dissoc id))
(save-state))
(defn set-cur-filter [v]
(swap! app-state #(assoc-in % [:filters :values] v)))
(defn update-cur-filter [k v]
(swap! app-state #(assoc-in % [:filters :values k] v)))
(defn save-filter [title data]
(swap! app-state #(assoc-in % [:filters :saved (str (random-uuid))] [title data]))
(save-state))
(defn toggle-column [col-id]
(swap! app-state #(update-in % [:options :columns] toggle-set col-id))
(save-state))
(defn set-data [data]
(swap! app-state #(assoc-in % [:options :data] data)))
(defn append-data
[{:keys [catalysts options quotes]}]
(swap! app-state #(update-in % [:options :data :catalysts] merge catalysts))
(swap! app-state #(update-in % [:options :data :quotes] merge quotes))
(swap! app-state (fn [old]
(update-in
old [:options :data :options]
#(-> %
(into options)
distinct)))))
(defn toggle-spread [home? cs]
(swap! app-state #(update-in % [(if home? :home :options) :spreads] toggle-set cs)))
(defn toggle-tracked-options [cs data]
(if (contains? (get-in @app-state [:home :tracked-options]) cs)
(do
(swap! app-state #(update-in % [:home :tracked-options] dissoc cs))
(swap! app-state #(update-in % [:home :historical] dissoc cs)))
(do
(swap! app-state #(update-in % [:home :tracked-options] assoc-in [cs :data] data))
(.postMessage worker (clj->js {:message "historical" :data cs}))))
(save-state))
(defn toggle-order-by-opts
[v]
(swap! app-state #(assoc-in % [:options :order-col] v)))
(defn init-historical [cs data]
(swap! app-state
#(assoc-in % [:home :historical cs] {:data data :left "bid" :right "delta"}))
(save-state))
(defn toggle-chart [cs side v]
(swap! app-state #(assoc-in % [:home :historical cs side] v)))
(defn set-cs-time [cs ts]
(swap! app-state #(assoc-in % [:home :tracked-options cs :ts] ts)))
Service worker handling ( communication between app & SW )
(defn err-message
[message]
(println "Unknown message:" message))
(defn parse-message
[e]
(let [{:keys [message data]} (js->clj (.-data e) :keywordize-keys true)]
(case message
"pong" (println data)
"search" (do
(set-data data)
(swap-view :options))
"search-append" (append-data data)
"ladder" (let [[ladder-def ladder-data] data]
(swap! app-state #(assoc-in % [:options :ladder ladder-def] ladder-data)))
"contract"
(let [[cs cs-data] data]
(swap! app-state #(-> %
(assoc-in [:home :tracked-options cs :data] cs-data)
(assoc-in [:home :tracked-options cs :ts] (cur-local-time)))))
"historical" (let [[cs cs-data] data]
(init-historical cs cs-data))
(err-message message))))
(.. worker (addEventListener "message" parse-message))
(defn test-sw []
(.postMessage worker (clj->js {:message "ping"})))
|
8bfc1a3faf3831d5db02ff9d17ebb7d3dd35bcdce3438e51bff50678b47d462f | NetComposer/nkmedia | nkmedia_room_api.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2016 . All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
%% @doc Room Plugin API
-module(nkmedia_room_api).
-author('Carlos Gonzalez <>').
-export([cmd/3]).
-include_lib("nkservice/include/nkservice.hrl").
%% ===================================================================
%% Commands
%% ===================================================================
cmd(<<"create">>, #api_req{srv_id=SrvId, data=Data}, State) ->
case nkmedia_room:start(SrvId, Data) of
{ok, Id, _Pid} ->
{ok, #{room_id=>Id}, State};
{error, Error} ->
{error, Error, State}
end;
cmd(<<"destroy">>, #api_req{data=#{room_id:=Id}}, State) ->
case nkmedia_room:stop(Id, api_stop) of
ok ->
{ok, #{}, State};
{error, Error} ->
{error, Error, State}
end;
cmd(<<"get_list">>, _Req, State) ->
Ids = [#{room_id=>Id, class=>Class} || {Id, Class, _Pid} <- nkmedia_room:get_all()],
{ok, Ids, State};
cmd(<<"get_info">>, #api_req{data=#{room_id:=RoomId}}, State) ->
case nkmedia_room:get_room(RoomId) of
{ok, Room} ->
{ok, nkmedia_room_api_syntax:get_info(Room), State};
{error, Error} ->
{error, Error, State}
end;
cmd(_Cmd, _Data, _State) ->
continue.
| null | https://raw.githubusercontent.com/NetComposer/nkmedia/24480866a523bfd6490abfe90ea46c6130ffe51f/src/plugins/nkmedia_room_api.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
@doc Room Plugin API
===================================================================
Commands
=================================================================== | Copyright ( c ) 2016 . All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(nkmedia_room_api).
-author('Carlos Gonzalez <>').
-export([cmd/3]).
-include_lib("nkservice/include/nkservice.hrl").
cmd(<<"create">>, #api_req{srv_id=SrvId, data=Data}, State) ->
case nkmedia_room:start(SrvId, Data) of
{ok, Id, _Pid} ->
{ok, #{room_id=>Id}, State};
{error, Error} ->
{error, Error, State}
end;
cmd(<<"destroy">>, #api_req{data=#{room_id:=Id}}, State) ->
case nkmedia_room:stop(Id, api_stop) of
ok ->
{ok, #{}, State};
{error, Error} ->
{error, Error, State}
end;
cmd(<<"get_list">>, _Req, State) ->
Ids = [#{room_id=>Id, class=>Class} || {Id, Class, _Pid} <- nkmedia_room:get_all()],
{ok, Ids, State};
cmd(<<"get_info">>, #api_req{data=#{room_id:=RoomId}}, State) ->
case nkmedia_room:get_room(RoomId) of
{ok, Room} ->
{ok, nkmedia_room_api_syntax:get_info(Room), State};
{error, Error} ->
{error, Error, State}
end;
cmd(_Cmd, _Data, _State) ->
continue.
|
cd1a184ffef5afc7e9081f3b18429dd2bbcb92f1e33467d449eb50167560a36d | K1D77A/validate-list | tests.lisp | (in-package #:validate-list/tests)
;;;these should go in another file
(defparameter *test-list1*
'("key" "abcdeegadfgfsdf"))
(defparameter *test-template1*
'((:equal "key") (:type string :maxlen 40)))
(defparameter *test-list2*
'("year" 2020 ("country" "USA")))
(defparameter *test-template2*
'((:equal "year")(:type integer :between (2100 1900))
((:or ("cookie" "country"))(:type string :maxlen 50))))
(defparameter *test-list3*
'("year" 98 ("country" ("USA" "UK" "Poland"))))
(defparameter *test-template3*
'((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country"))
((:equal "USA")(:equal "UK")(:equal "Poland")))))
(defparameter *test-list4*
'("year" 98 ("country" ("USA" "UK" "Poland"))))
(defparameter *test-template4*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country"))
,(repeat-test 3 '(:type string :maxlen 6 :minlen 2)))))
(defparameter *test-list5*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96))))
(defparameter *test-template5*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country" "keyvals"))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100)))))))
(defparameter *test-list6*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96))))
(defparameter *test-template6*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country" "keyvals"))
,(repeat-pattern 4 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100)))))))
^should fail because the end is len 4 instead of len 3
(defparameter *test-list7*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96) 2 4 6)))
(defparameter *test-template7*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country" "keyvals"))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
,@(repeat-test 3 '(:type number :satisfies evenp)))))
(defparameter *test-list8*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96) 2 5 6)))
(defparameter *test-template8*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country" "keyvals"))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
,@(repeat-test 3 '(:type number :satisfies (evenp oddp))))))
9 is broken intentionally . bad : or
(defparameter *test-list9*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96) 2 5 6)))
(defparameter *test-template9*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country"))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100)))))
,(repeat-test 3 '(:type number :satisfies (evenp oddp)))))
10 is broken intentionally . bad : equal
(defparameter *test-list10*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96) 2 5 6)))
(defparameter *test-template10*
`((:equal "year")(:type integer :or (96 97 98))
((:or ) ;;broken intentionally
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100)))))
,(repeat-test 3 '(:type number :satisfies (evenp oddp)))))
11 is broken intentionally . invalid : or
(defparameter *test-list11*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96) 2 5 6)))
(defparameter *test-template11*
`((:equal "year")(:type integer :or (96 97 98))
((:or abc def hhh) ;;broken intentionally
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100)))))
,(repeat-test 3 '(:type number :satisfies (evenp oddp)))))
12 is broken intentionally , bad : or
(defparameter *test-list12*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96) 2 5 (6 7 8))))
(defparameter *test-template12*
`((:equal "year")(:type integer :or (96 97 98))
((:or "keyvals" "time") ;;broken intentionally
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100)))))
,(repeat-test 2 '(:type number :satisfies (evenp oddp)))
(:type list :minlen 1 :maxlen 3)))
(defparameter *test-list12a*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96)
1 2 (6 7) (8) "abc")))
(defparameter *test-template12a*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("keyvals" "time")) ;;broken intentionally
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
,@(repeat-test 2 '(:type number :satisfies (evenp oddp)))
(:type list :length 2)
(:type list :minlen 1)
(:type string :equal "abc"))))
(defparameter *test-list13*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96)
(2) (6 7) ("oof" "boof" "kadoof") "abc")))
(defparameter *test-template13*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("keyvals" "time")) ;;broken intentionally
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
(:type list :minlen 1)
(:type list :maxlen 2)
(:type list :minlen 1 :maxlen 5 :contents (:type string))
(:type string :equal "abc"))))
14 is bad on purpose , , instead of , @
(defparameter *test-list14*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96)
1 2 (2) (6 7) ("oof" 23 "kadoof") "abc")))
(defparameter *test-template14*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("keyvals" "time")) ;;broken intentionally
;;this is an example of messing up ,@
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
;;fixing this template would be easy with ,@ here instead of ,
this is because @ , will generate two lists , while , is
a list with two lists inside , this has a big effect on the
;;validation
,(repeat-test 2 '(:type number :satisfies (evenp oddp)))
(:type list :length 1)
(:type list :length 2)
(:type list :minlen 1 :maxlen 5 :contents (:type string))
(:type string :equal "abc"))))
(defparameter *test-list15*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96)
(2) (6 7) ("oof" 23 "kadoof") "abc")))
(defparameter *test-template15*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("keyvals" "time"))
,(repeat-pattern 3
'((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
(:type list :length 1 :contents (:type number))
(:type list :length 2)
(:type list :minlen 1 :maxlen 5 :contents (:type (string number)))
(:type string :equal "abc"))))
(defparameter *test-list16*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96)
1 2 (2) (6 7) ("oof" "oof" "oof") "abc")))
(defparameter *test-template16*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("keyvals" "time"))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
,@(repeat-test 2 '(:type number :satisfies (evenp oddp)))
(:type list :length 1)
(:type list :contents (:type number :satisfies (evenp oddp)))
(:type list :minlen 1 :maxlen 5
:contents (:type string :maxlen 5 :equal "oof"))
(:type string :equal "abc"))))
bad : maxlen 3 when maxlen is 6
(defparameter *test-list17*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96)
1 2 (2) (6 7) ("oof" "oof" "oof") "abc")))
(defparameter *test-template17*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("keyvals" "time"))
,(repeat-pattern 3 '((:type string :maxlen 3 :minlen 2)
(:type number :between (0 100))))
,@(repeat-test 2 '(:type number :satisfies (evenp oddp)))
(:type list :length 1)
(:type list :contents (:type number :satisfies (evenp oddp)))
(:type list :minlen 1 :maxlen 5
:contents (:type string :maxlen 5 :equal "oof"))
(:type string :equal "abc"))))
;;bad :type string when number
(defparameter *test-list18*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96)
1 2 (2) (6 7) ("oof" "oof" "oof") "abc")))
(defparameter *test-template18*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("keyvals" "time"))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
,@(repeat-test 2 '(:type number :satisfies (evenp oddp)))
(:type list :length 1)
(:type list :contents (:type string))
(:type list :minlen 1 :maxlen 5
:contents (:type string :maxlen 5 :equal "oof"))
(:type string :equal "abc"))))
bad : equal " abcd " instead of " abc "
(defparameter *test-list19*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96)
1 2 (2) (6 7) ("oof" "oof" "oof") "abc")))
(defparameter *test-template19*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("keyvals" "time"))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
,@(repeat-test 2 '(:type number :satisfies (evenp oddp)))
(:type list :length 1)
(:type list :contents (:type number :satisfies (evenp oddp)))
(:type list :minlen 1 :maxlen 5
:contents (:type string :maxlen 5 :equal "oof"))
(:type string :equal "abcd"))))
;;;broken structures
(defparameter *broken-struct-list1*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96) 2 5 6)))
(defparameter *broken-struct1*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country" "keyvals"))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
,(repeat-test 3 '(:type number :satisfies (evenp oddp))))))
;;because its of type list we don't want to recurse over it...
(defun compile-template-and-test (list template)
(check-type template list)
(check-type list list)
(let ((compiled (compile-template template)))
(check-type compiled function)
(funcall compiled list)))
(define-test test-validation-true
(assert-true (validate-list *test-list1* *test-template1*))
(assert-true (validate-list *test-list2* *test-template2*))
(assert-true (validate-list *test-list3* *test-template3*))
(assert-true (validate-list *test-list4* *test-template4*))
(assert-true (validate-list *test-list5* *test-template5*))
(assert-true (validate-list *test-list7* *test-template7*))
(assert-true (validate-list *test-list8* *test-template8*))
(assert-true (validate-list *test-list12a* *test-template12a*))
(assert-true (validate-list *test-list15* *test-template15*))
(assert-true (validate-list *test-list13* *test-template13*))
(assert-true (validate-list *test-list16* *test-template16*)))
(define-test test-validation-false
(assert-error 'failed-to-validate (validate-list *test-list1* *test-template2*))
;;^ fails to validate before the bad structure is noticed
(assert-error 'failed-to-validate (validate-list *test-list2* *test-template1*))
;;^ fails to validate before the bad structure is noticed
(assert-error 'failed-to-validate (validate-list *test-list9* *test-template9*))
(assert-error 'failed-to-validate (validate-list *test-list17* *test-template17*))
(assert-error 'failed-to-validate (validate-list *test-list18* *test-template18*))
(assert-error 'failed-to-validate
(validate-list *test-list19* *test-template19*))
(assert-error 'bad-template-format
(validate-list *test-list14* *test-template14*)))
(define-test test-validation-error
(assert-error 'bad-template-format (validate-list *test-list6* *test-template6*))
(assert-error 'bad-template-format (validate-list *test-list10* *test-template10*))
(assert-error 'bad-template-format (validate-list *test-list12* *test-template12*))
(assert-error 'bad-template-format
(validate-list *test-list11* *test-template11*)))
(define-test test-compiled-true
(assert-true (compile-template-and-test *test-list1* *test-template1*))
(assert-true (compile-template-and-test *test-list2* *test-template2*))
(assert-true (compile-template-and-test *test-list3* *test-template3*))
(assert-true (compile-template-and-test *test-list4* *test-template4*))
(assert-true (compile-template-and-test *test-list5* *test-template5*))
(assert-true (compile-template-and-test *test-list7* *test-template7*))
(assert-true (compile-template-and-test *test-list8* *test-template8*))
(assert-true (compile-template-and-test *test-list12a* *test-template12a*))
(assert-true (compile-template-and-test *test-list15* *test-template15*))
(assert-true (compile-template-and-test *test-list13* *test-template13*))
(assert-true (compile-template-and-test *test-list16* *test-template16*)))
(define-test test-compiled-false
(assert-error 'bad-template-format
(compile-template-and-test *test-list6* *test-template6*))
(assert-error 'bad-template-format
(compile-template-and-test *test-list10* *test-template10*))
(assert-error 'bad-template-format
(compile-template-and-test *test-list12* *test-template12*))
(assert-error 'bad-template-format
(compile-template-and-test *test-list10* *test-template10*))
(assert-error 'bad-template-format
(compile-template-and-test *test-list11* *test-template11*))
(assert-error 'bad-template-format
(compile-template-and-test *test-list1* *test-template2*))
;;^ fails to validate before the bad structure is noticed
(assert-error 'bad-template-format
(compile-template-and-test *test-list2* *test-template1*))
;;^ fails to validate before the bad structure is noticed
(assert-error 'bad-template-format
(compile-template-and-test *test-list9* *test-template9*))
(assert-error 'bad-template-format
(compile-template-and-test *test-list14* *test-template14*))
(assert-error 'failed-to-validate
(compile-template-and-test *test-list17* *test-template17*))
(assert-error 'failed-to-validate
(compile-template-and-test *test-list18* *test-template18*))
(assert-error 'failed-to-validate
(compile-template-and-test *test-list19* *test-template19*)))
(define-test test-compiled-error
(assert-error 'bad-template-format
(compile-template-and-test *test-list10* *test-template10*))
(assert-error 'bad-template-format
(compile-template-and-test *test-list11* *test-template11*)))
(define-test compile-quoted
"Test compiling quoted templates"
(assert-true (funcall (compile-template *test-template7*) *test-list7*))
(assert-true (funcall (compile-template *test-template7c*) *test-list7*)))
(define-test validate-quoted
"Test validating with quoted templates"
(assert-true (validate-list *test-list7* *test-template7c*)))
(define-test compiler-macro
"Automatic conversion of the constant list to its compiled counterpart."
(assert-true (validate-list *test-list7*
'((:EQUAL "year") (:TYPE INTEGER :OR (96 97 98))
((:OR ("cookie" "country" "keyvals"))
((:TYPE STRING :MAXLEN 6 :MINLEN 2)
(:TYPE NUMBER :BETWEEN (0 100))
(:TYPE STRING :MAXLEN 6 :MINLEN 2)
(:TYPE NUMBER :BETWEEN (0 100))
(:TYPE STRING :MAXLEN 6 :MINLEN 2)
(:TYPE NUMBER :BETWEEN (0 100)))
(:TYPE NUMBER :SATISFIES EVENP)
(:TYPE NUMBER :SATISFIES EVENP)
(:TYPE NUMBER :SATISFIES EVENP)))))
(assert-true (validate-list *test-list8*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country" "keyvals"))
,(repeat-pattern 3 '((:type string :maxlen 6
:minlen 2)
(:type number
:between (0 100))))
,@(repeat-test 3 '(:type number
:satisfies (evenp oddp))))))))
| null | https://raw.githubusercontent.com/K1D77A/validate-list/223b89469c49b382cfabf2add9c27951728c81c0/tests/tests.lisp | lisp | these should go in another file
broken intentionally
broken intentionally
broken intentionally
broken intentionally
broken intentionally
broken intentionally
this is an example of messing up ,@
fixing this template would be easy with ,@ here instead of ,
validation
bad :type string when number
broken structures
because its of type list we don't want to recurse over it...
^ fails to validate before the bad structure is noticed
^ fails to validate before the bad structure is noticed
^ fails to validate before the bad structure is noticed
^ fails to validate before the bad structure is noticed | (in-package #:validate-list/tests)
(defparameter *test-list1*
'("key" "abcdeegadfgfsdf"))
(defparameter *test-template1*
'((:equal "key") (:type string :maxlen 40)))
(defparameter *test-list2*
'("year" 2020 ("country" "USA")))
(defparameter *test-template2*
'((:equal "year")(:type integer :between (2100 1900))
((:or ("cookie" "country"))(:type string :maxlen 50))))
(defparameter *test-list3*
'("year" 98 ("country" ("USA" "UK" "Poland"))))
(defparameter *test-template3*
'((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country"))
((:equal "USA")(:equal "UK")(:equal "Poland")))))
(defparameter *test-list4*
'("year" 98 ("country" ("USA" "UK" "Poland"))))
(defparameter *test-template4*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country"))
,(repeat-test 3 '(:type string :maxlen 6 :minlen 2)))))
(defparameter *test-list5*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96))))
(defparameter *test-template5*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country" "keyvals"))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100)))))))
(defparameter *test-list6*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96))))
(defparameter *test-template6*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country" "keyvals"))
,(repeat-pattern 4 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100)))))))
^should fail because the end is len 4 instead of len 3
(defparameter *test-list7*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96) 2 4 6)))
(defparameter *test-template7*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country" "keyvals"))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
,@(repeat-test 3 '(:type number :satisfies evenp)))))
(defparameter *test-list8*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96) 2 5 6)))
(defparameter *test-template8*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country" "keyvals"))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
,@(repeat-test 3 '(:type number :satisfies (evenp oddp))))))
9 is broken intentionally . bad : or
(defparameter *test-list9*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96) 2 5 6)))
(defparameter *test-template9*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country"))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100)))))
,(repeat-test 3 '(:type number :satisfies (evenp oddp)))))
10 is broken intentionally . bad : equal
(defparameter *test-list10*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96) 2 5 6)))
(defparameter *test-template10*
`((:equal "year")(:type integer :or (96 97 98))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100)))))
,(repeat-test 3 '(:type number :satisfies (evenp oddp)))))
11 is broken intentionally . invalid : or
(defparameter *test-list11*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96) 2 5 6)))
(defparameter *test-template11*
`((:equal "year")(:type integer :or (96 97 98))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100)))))
,(repeat-test 3 '(:type number :satisfies (evenp oddp)))))
12 is broken intentionally , bad : or
(defparameter *test-list12*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96) 2 5 (6 7 8))))
(defparameter *test-template12*
`((:equal "year")(:type integer :or (96 97 98))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100)))))
,(repeat-test 2 '(:type number :satisfies (evenp oddp)))
(:type list :minlen 1 :maxlen 3)))
(defparameter *test-list12a*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96)
1 2 (6 7) (8) "abc")))
(defparameter *test-template12a*
`((:equal "year")(:type integer :or (96 97 98))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
,@(repeat-test 2 '(:type number :satisfies (evenp oddp)))
(:type list :length 2)
(:type list :minlen 1)
(:type string :equal "abc"))))
(defparameter *test-list13*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96)
(2) (6 7) ("oof" "boof" "kadoof") "abc")))
(defparameter *test-template13*
`((:equal "year")(:type integer :or (96 97 98))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
(:type list :minlen 1)
(:type list :maxlen 2)
(:type list :minlen 1 :maxlen 5 :contents (:type string))
(:type string :equal "abc"))))
14 is bad on purpose , , instead of , @
(defparameter *test-list14*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96)
1 2 (2) (6 7) ("oof" 23 "kadoof") "abc")))
(defparameter *test-template14*
`((:equal "year")(:type integer :or (96 97 98))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
this is because @ , will generate two lists , while , is
a list with two lists inside , this has a big effect on the
,(repeat-test 2 '(:type number :satisfies (evenp oddp)))
(:type list :length 1)
(:type list :length 2)
(:type list :minlen 1 :maxlen 5 :contents (:type string))
(:type string :equal "abc"))))
(defparameter *test-list15*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96)
(2) (6 7) ("oof" 23 "kadoof") "abc")))
(defparameter *test-template15*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("keyvals" "time"))
,(repeat-pattern 3
'((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
(:type list :length 1 :contents (:type number))
(:type list :length 2)
(:type list :minlen 1 :maxlen 5 :contents (:type (string number)))
(:type string :equal "abc"))))
(defparameter *test-list16*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96)
1 2 (2) (6 7) ("oof" "oof" "oof") "abc")))
(defparameter *test-template16*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("keyvals" "time"))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
,@(repeat-test 2 '(:type number :satisfies (evenp oddp)))
(:type list :length 1)
(:type list :contents (:type number :satisfies (evenp oddp)))
(:type list :minlen 1 :maxlen 5
:contents (:type string :maxlen 5 :equal "oof"))
(:type string :equal "abc"))))
bad : maxlen 3 when maxlen is 6
(defparameter *test-list17*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96)
1 2 (2) (6 7) ("oof" "oof" "oof") "abc")))
(defparameter *test-template17*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("keyvals" "time"))
,(repeat-pattern 3 '((:type string :maxlen 3 :minlen 2)
(:type number :between (0 100))))
,@(repeat-test 2 '(:type number :satisfies (evenp oddp)))
(:type list :length 1)
(:type list :contents (:type number :satisfies (evenp oddp)))
(:type list :minlen 1 :maxlen 5
:contents (:type string :maxlen 5 :equal "oof"))
(:type string :equal "abc"))))
(defparameter *test-list18*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96)
1 2 (2) (6 7) ("oof" "oof" "oof") "abc")))
(defparameter *test-template18*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("keyvals" "time"))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
,@(repeat-test 2 '(:type number :satisfies (evenp oddp)))
(:type list :length 1)
(:type list :contents (:type string))
(:type list :minlen 1 :maxlen 5
:contents (:type string :maxlen 5 :equal "oof"))
(:type string :equal "abc"))))
bad : equal " abcd " instead of " abc "
(defparameter *test-list19*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96)
1 2 (2) (6 7) ("oof" "oof" "oof") "abc")))
(defparameter *test-template19*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("keyvals" "time"))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
,@(repeat-test 2 '(:type number :satisfies (evenp oddp)))
(:type list :length 1)
(:type list :contents (:type number :satisfies (evenp oddp)))
(:type list :minlen 1 :maxlen 5
:contents (:type string :maxlen 5 :equal "oof"))
(:type string :equal "abcd"))))
(defparameter *broken-struct-list1*
'("year" 98 ("keyvals" ("USA" 35 "Poland" 55 "UK" 96) 2 5 6)))
(defparameter *broken-struct1*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country" "keyvals"))
,(repeat-pattern 3 '((:type string :maxlen 6 :minlen 2)
(:type number :between (0 100))))
,(repeat-test 3 '(:type number :satisfies (evenp oddp))))))
(defun compile-template-and-test (list template)
(check-type template list)
(check-type list list)
(let ((compiled (compile-template template)))
(check-type compiled function)
(funcall compiled list)))
(define-test test-validation-true
(assert-true (validate-list *test-list1* *test-template1*))
(assert-true (validate-list *test-list2* *test-template2*))
(assert-true (validate-list *test-list3* *test-template3*))
(assert-true (validate-list *test-list4* *test-template4*))
(assert-true (validate-list *test-list5* *test-template5*))
(assert-true (validate-list *test-list7* *test-template7*))
(assert-true (validate-list *test-list8* *test-template8*))
(assert-true (validate-list *test-list12a* *test-template12a*))
(assert-true (validate-list *test-list15* *test-template15*))
(assert-true (validate-list *test-list13* *test-template13*))
(assert-true (validate-list *test-list16* *test-template16*)))
(define-test test-validation-false
(assert-error 'failed-to-validate (validate-list *test-list1* *test-template2*))
(assert-error 'failed-to-validate (validate-list *test-list2* *test-template1*))
(assert-error 'failed-to-validate (validate-list *test-list9* *test-template9*))
(assert-error 'failed-to-validate (validate-list *test-list17* *test-template17*))
(assert-error 'failed-to-validate (validate-list *test-list18* *test-template18*))
(assert-error 'failed-to-validate
(validate-list *test-list19* *test-template19*))
(assert-error 'bad-template-format
(validate-list *test-list14* *test-template14*)))
(define-test test-validation-error
(assert-error 'bad-template-format (validate-list *test-list6* *test-template6*))
(assert-error 'bad-template-format (validate-list *test-list10* *test-template10*))
(assert-error 'bad-template-format (validate-list *test-list12* *test-template12*))
(assert-error 'bad-template-format
(validate-list *test-list11* *test-template11*)))
(define-test test-compiled-true
(assert-true (compile-template-and-test *test-list1* *test-template1*))
(assert-true (compile-template-and-test *test-list2* *test-template2*))
(assert-true (compile-template-and-test *test-list3* *test-template3*))
(assert-true (compile-template-and-test *test-list4* *test-template4*))
(assert-true (compile-template-and-test *test-list5* *test-template5*))
(assert-true (compile-template-and-test *test-list7* *test-template7*))
(assert-true (compile-template-and-test *test-list8* *test-template8*))
(assert-true (compile-template-and-test *test-list12a* *test-template12a*))
(assert-true (compile-template-and-test *test-list15* *test-template15*))
(assert-true (compile-template-and-test *test-list13* *test-template13*))
(assert-true (compile-template-and-test *test-list16* *test-template16*)))
(define-test test-compiled-false
(assert-error 'bad-template-format
(compile-template-and-test *test-list6* *test-template6*))
(assert-error 'bad-template-format
(compile-template-and-test *test-list10* *test-template10*))
(assert-error 'bad-template-format
(compile-template-and-test *test-list12* *test-template12*))
(assert-error 'bad-template-format
(compile-template-and-test *test-list10* *test-template10*))
(assert-error 'bad-template-format
(compile-template-and-test *test-list11* *test-template11*))
(assert-error 'bad-template-format
(compile-template-and-test *test-list1* *test-template2*))
(assert-error 'bad-template-format
(compile-template-and-test *test-list2* *test-template1*))
(assert-error 'bad-template-format
(compile-template-and-test *test-list9* *test-template9*))
(assert-error 'bad-template-format
(compile-template-and-test *test-list14* *test-template14*))
(assert-error 'failed-to-validate
(compile-template-and-test *test-list17* *test-template17*))
(assert-error 'failed-to-validate
(compile-template-and-test *test-list18* *test-template18*))
(assert-error 'failed-to-validate
(compile-template-and-test *test-list19* *test-template19*)))
(define-test test-compiled-error
(assert-error 'bad-template-format
(compile-template-and-test *test-list10* *test-template10*))
(assert-error 'bad-template-format
(compile-template-and-test *test-list11* *test-template11*)))
(define-test compile-quoted
"Test compiling quoted templates"
(assert-true (funcall (compile-template *test-template7*) *test-list7*))
(assert-true (funcall (compile-template *test-template7c*) *test-list7*)))
(define-test validate-quoted
"Test validating with quoted templates"
(assert-true (validate-list *test-list7* *test-template7c*)))
(define-test compiler-macro
"Automatic conversion of the constant list to its compiled counterpart."
(assert-true (validate-list *test-list7*
'((:EQUAL "year") (:TYPE INTEGER :OR (96 97 98))
((:OR ("cookie" "country" "keyvals"))
((:TYPE STRING :MAXLEN 6 :MINLEN 2)
(:TYPE NUMBER :BETWEEN (0 100))
(:TYPE STRING :MAXLEN 6 :MINLEN 2)
(:TYPE NUMBER :BETWEEN (0 100))
(:TYPE STRING :MAXLEN 6 :MINLEN 2)
(:TYPE NUMBER :BETWEEN (0 100)))
(:TYPE NUMBER :SATISFIES EVENP)
(:TYPE NUMBER :SATISFIES EVENP)
(:TYPE NUMBER :SATISFIES EVENP)))))
(assert-true (validate-list *test-list8*
`((:equal "year")(:type integer :or (96 97 98))
((:or ("cookie" "country" "keyvals"))
,(repeat-pattern 3 '((:type string :maxlen 6
:minlen 2)
(:type number
:between (0 100))))
,@(repeat-test 3 '(:type number
:satisfies (evenp oddp))))))))
|
17bf83f1493e730fc8916596373d050c315c0ecbd8a11cca9e33f56d986c2139 | conreality/conreality | devices.ml | (* This is free and unencumbered software released into the public domain. *)
open Prelude
open Lua_api
open Lwt.Infix
open Machinery
open Scripting
type t = {
classes: (string, unit) Hashtbl.t; (* FIXME: figure out the hashtbl value *)
instances: (string, Device.t) Hashtbl.t;
}
let create () = {
classes = Hashtbl.create 0;
instances = Hashtbl.create 0;
}
let is_registered devices device_name =
Hashtbl.mem devices.instances device_name
let register devices device_name config =
Lwt_log.ign_info_f "Registering the device /%s..." device_name;
let driver_name = Value.to_string (Table.lookup config (Value.of_string "driver")) in
let driver = Driver.find driver_name in
let device = driver.constructor config in
Hashtbl.replace devices.instances device_name device;
Lwt_log.ign_notice_f "Registered the device /%s." device_name
let unregister devices device_name =
Hashtbl.remove devices.instances device_name;
Lwt_log.ign_notice_f "Unregistered the device /%s." device_name
let load devices context =
let table = Context.pop_table context in
Table.iter table
(fun k v -> match (k, v) with
| (Value.String name, Value.Table config) ->
register devices name config
| _ ->
Lwt_log.ign_error_f "Skipped invalid %s configuration key: %s"
"devices" (Value.to_string k))
let find devices device_name =
try Some (Hashtbl.find devices.instances device_name) with Not_found -> None
| null | https://raw.githubusercontent.com/conreality/conreality/e03328ef1f0056b58e4ffe181a279a1dc776e094/src/consensus/config/devices.ml | ocaml | This is free and unencumbered software released into the public domain.
FIXME: figure out the hashtbl value |
open Prelude
open Lua_api
open Lwt.Infix
open Machinery
open Scripting
type t = {
instances: (string, Device.t) Hashtbl.t;
}
let create () = {
classes = Hashtbl.create 0;
instances = Hashtbl.create 0;
}
let is_registered devices device_name =
Hashtbl.mem devices.instances device_name
let register devices device_name config =
Lwt_log.ign_info_f "Registering the device /%s..." device_name;
let driver_name = Value.to_string (Table.lookup config (Value.of_string "driver")) in
let driver = Driver.find driver_name in
let device = driver.constructor config in
Hashtbl.replace devices.instances device_name device;
Lwt_log.ign_notice_f "Registered the device /%s." device_name
let unregister devices device_name =
Hashtbl.remove devices.instances device_name;
Lwt_log.ign_notice_f "Unregistered the device /%s." device_name
let load devices context =
let table = Context.pop_table context in
Table.iter table
(fun k v -> match (k, v) with
| (Value.String name, Value.Table config) ->
register devices name config
| _ ->
Lwt_log.ign_error_f "Skipped invalid %s configuration key: %s"
"devices" (Value.to_string k))
let find devices device_name =
try Some (Hashtbl.find devices.instances device_name) with Not_found -> None
|
40bea74fb10d4ac3f40e7176cc2d3ec1fb3cade00c9dc68d2e1bac49e284f28e | ghc/packages-dph | DphOps.hs | | DPH operations : how long they took , totals , etc
module DphOps
( dphOpsMachine
, dphOpsSumMachine
, DphTrace(..)
, ParseComp(..)
, parseComp
, getGangEvents
, pprGangEvents
, clearJoinComp
, clearJoinWhat)
where
import qualified Data.Array.Parallel.Unlifted.Distributed.What as W
import GHC.RTS.Events
import GHC.RTS.Events.Analysis
import Data.Map (Map)
import qualified Data.Map as M
import Data.List (sortBy, stripPrefix)
import Pretty
| Set of interesting things that DPH might tell us
data DphTrace
= DTComplete W.Comp Timestamp
| DTIssuing W.Comp
deriving (Eq,Show)
| Result of attempting to parse a CapEvent
data ParseComp
= POk DphTrace Timestamp -- ^ valid event and its time
| PUnparsable -- ^ looks like a comp, but invalid
| PIgnored -- ^ not a comp at all, just ignore
-- | Attempt to get a Comp
eg " GANG Complete par CompMap { ... } in 44us "
parseComp :: GangEvent -> ParseComp
parseComp (GangEvent _ ts gmsg)
" Complete par Map ( Join ... ) in 44us . "
| Just compStr <- stripPrefix "Complete par " gmsg
, (comp,inStr):_ <- reads compStr
, Just muStr <- stripPrefix " in " inStr
, (mus,"us."):_ <- reads muStr
= POk (DTComplete comp (mus * 10^(3 :: Int))) ts
-- prefix is there, but the rest didn't parse properly
| Just _ <- stripPrefix "Complete par " gmsg
= PUnparsable
-- "Issuing par Map (Join ...)"
| Just issuStr <- stripPrefix "Issuing par " gmsg
, (comp,""):_ <- reads issuStr
= POk (DTIssuing comp) ts
-- prefix is there, but the rest didn't parse properly
| Just _ <- stripPrefix "Issuing par " gmsg
= PUnparsable
-- prefix isn't there, so just ignore it
| otherwise
= PIgnored
data GangEvent = GangEvent (Maybe Int) Timestamp String
deriving Show
| Potentially merge multiple CapEvents into single GangEvent
Because each event can only be 500 or so characters ,
-- and our comps are quite large, so they must be split across events.
" GANG[1/2 ] Complete par xxx "
-- "GANG[2/2] yyy zzz"
getGangEvents :: [CapEvent] -> [GangEvent]
getGangEvents xs = snd $ foldl (flip gang) (Nothing,[]) xs
where
-- GANG[1/4] Complete par ...
gang (CapEvent c (Event t (UserMessage gmsg)))
(no,ls)
| Just numS <- stripPrefix "GANG[" gmsg
, [(n,'/':n2S)] <- reads numS :: [(Int,String)]
, [(m,']':' ':restS)]<- reads n2S :: [(Int,String)]
= app (n,m) no (GangEvent c t restS) ls
| otherwise
= (no,ls)
gang _ acc = acc
app (n,m) se ge ls
| n == 1 && m == 1
= (Nothing, ls ++ [ge])
| n == 1
= (Just ge, ls)
| n == m
= (Nothing, ls ++ [se `merge` ge])
| otherwise
= (Just $ se `merge` ge, ls)
merge Nothing ge
= ge
merge (Just (GangEvent c t s)) (GangEvent _ _ s')
= GangEvent c t (s++s')
pprGangEvents :: [GangEvent] -> Doc
pprGangEvents gs = vcat $ map ppr gs
instance Pretty GangEvent where
ppr (GangEvent c t s) =
padL 10 (text $ show c) <>
padR 15 (pprTimestampAbs t) <>
text s
-- Display all operations and duration, ordered decreasing
data DphOpsState = DphOpsState (Map Timestamp [(W.Comp, Timestamp)]) Timestamp Int
dphOpsMachine :: Machine DphOpsState GangEvent
dphOpsMachine = Machine
{ initial = DphOpsState M.empty 0 0
, final = const False
, alpha = alph
, delta = delt
}
where
alph _ = True
delt (DphOpsState ops total unparse) evt
= case parseComp evt of
POk (DTComplete comp duration) t ->
Just $ DphOpsState (update ops duration (comp,t)) (total + duration) unparse
PUnparsable ->
Just $ DphOpsState ops total (unparse+1)
_ ->
Just $ DphOpsState ops total unparse
delt s _ = Just s
update !counts !k !v = M.insertWith' (++) k [v] counts
instance Pretty DphOpsState where
ppr (DphOpsState ops total unparse) = vcat [unparse', ops']
where
unparse'
= if unparse == 0
then text ""
else text "Errors: " <> ppr unparse <> text " events unable to be parsed"
ops' = vcat $ map pprOps $ reverse $ M.assocs ops
pprOps (duration,cs) = vcat $ map (pprOp duration) cs
pprOp duration (c,t) = padLines (cat
[ pprPercent duration
, text " "
, padR 10 (text "(" <> pprTimestampEng duration <> text ")")
, text " "
, padR 15 $ pprTimestampAbs t
, text " "
]) (show $ ppr c)
pprPercent v = padR 5 $ ppr (v * 100 `div` total) <> text "%"
data DphOpsSumState = DphOpsSumState (Map W.Comp (Int,Timestamp)) Timestamp Int
dphOpsSumMachine :: Machine DphOpsSumState GangEvent
dphOpsSumMachine = Machine
{ initial = DphOpsSumState M.empty 0 0
, final = const False
, alpha = alph
, delta = delt
}
where
alph _ = True
" GANG Complete par CompMap { ... } in 44us "
delt (DphOpsSumState ops total unparse) evt
= case parseComp evt of
POk (DTComplete comp duration) _ ->
Just $ DphOpsSumState (update ops (clearJoinComp comp) (1,duration)) (total + duration) unparse
PUnparsable ->
Just $ DphOpsSumState ops total (unparse+1)
_ ->
Just $ DphOpsSumState ops total unparse
delt s _ = Just s
update !counts !k !v = M.insertWith' pairAdd k v counts
pairAdd (aa,ab) (ba,bb) = (aa+ba, ab+bb)
Reset the elements arg of all JoinCopies so they show up as total
clearJoinComp :: W.Comp -> W.Comp
clearJoinComp (W.CGen c w) = W.CGen c $ clearJoinWhat w
clearJoinComp (W.CMap w) = W.CMap $ clearJoinWhat w
clearJoinComp (W.CFold w) = W.CFold $ clearJoinWhat w
clearJoinComp (W.CScan w) = W.CScan $ clearJoinWhat w
clearJoinComp (W.CDist w) = W.CDist $ clearJoinWhat w
clearJoinWhat :: W.What -> W.What
clearJoinWhat (W.WJoinCopy _)= W.WJoinCopy (-1)
clearJoinWhat (W.WFMapMap p q) = W.WFMapMap (clearJoinWhat p) (clearJoinWhat q)
clearJoinWhat (W.WFMapGen p q) = W.WFMapGen (clearJoinWhat p) (clearJoinWhat q)
clearJoinWhat (W.WFZipMap p q) = W.WFZipMap (clearJoinWhat p) (clearJoinWhat q)
clearJoinWhat w = w
instance Pretty DphOpsSumState where
ppr (DphOpsSumState ops total unparse) = vcat [unparse', ops']
where
unparse'
= if unparse == 0
then text ""
else text "Errors: " <> ppr unparse <> text " events unable to be parsed"
ops' = vcat $ map pprOp $ sortBy cmp $ M.assocs ops
cmp (_,(_,p)) (_,(_,q))
= case compare p q of
GT -> LT
EQ -> EQ
LT -> GT
pprOp (c,(calls,duration)) = padLines (cat
[ pprPercent duration
, text " "
, padR 10 (text "(" <> pprTimestampEng duration <> text ")")
, text " "
, padR 10 (ppr calls)
, text " "
]) (show $ ppr c)
pprPercent v = padR 5 $ ppr (v * 100 `div` total) <> text "%"
instance Pretty W.Comp where
ppr (W.CGen cheap what)
= cheap' <> ppr what
where
cheap' = if cheap
then text "GenC "
else text "Gen "
ppr (W.CMap what)
= text "Map " <> ppr what
ppr (W.CFold what)
= text "Fold " <> ppr what
ppr (W.CScan what)
= text "Scan " <> ppr what
ppr (W.CDist what)
= text "Dist " <> ppr what
instance Pretty W.What where
ppr (W.What what) = text $ show what
ppr (W.WScalar) = text "Scalar"
ppr (W.WZip) = text "Zip"
ppr (W.WSlice) = text "Slice"
ppr (W.WLength) = text "Length"
ppr (W.WLengthIdx) = text "LengthIdx"
ppr (W.WBpermute) = text "Bpermute"
ppr (W.WJoinCopy (-1)) = text "JoinCp"
ppr (W.WJoinCopy n) = text ("JoinCp(" ++ show n ++ ")")
ppr (W.WFMapMap p q) = text "(" <> ppr p <> text " mapMap " <> ppr q <> text ")"
ppr (W.WFMapGen p q) = text "(" <> ppr p <> text " mapGen " <> ppr q <> text ")"
ppr (W.WFZipMap p q) = text "(" <> ppr p <> text " zipMap " <> ppr q <> text ")"
| null | https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/dph-event-seer/src/DphOps.hs | haskell | ^ valid event and its time
^ looks like a comp, but invalid
^ not a comp at all, just ignore
| Attempt to get a Comp
prefix is there, but the rest didn't parse properly
"Issuing par Map (Join ...)"
prefix is there, but the rest didn't parse properly
prefix isn't there, so just ignore it
and our comps are quite large, so they must be split across events.
"GANG[2/2] yyy zzz"
GANG[1/4] Complete par ...
Display all operations and duration, ordered decreasing | | DPH operations : how long they took , totals , etc
module DphOps
( dphOpsMachine
, dphOpsSumMachine
, DphTrace(..)
, ParseComp(..)
, parseComp
, getGangEvents
, pprGangEvents
, clearJoinComp
, clearJoinWhat)
where
import qualified Data.Array.Parallel.Unlifted.Distributed.What as W
import GHC.RTS.Events
import GHC.RTS.Events.Analysis
import Data.Map (Map)
import qualified Data.Map as M
import Data.List (sortBy, stripPrefix)
import Pretty
| Set of interesting things that DPH might tell us
data DphTrace
= DTComplete W.Comp Timestamp
| DTIssuing W.Comp
deriving (Eq,Show)
| Result of attempting to parse a CapEvent
data ParseComp
eg " GANG Complete par CompMap { ... } in 44us "
parseComp :: GangEvent -> ParseComp
parseComp (GangEvent _ ts gmsg)
" Complete par Map ( Join ... ) in 44us . "
| Just compStr <- stripPrefix "Complete par " gmsg
, (comp,inStr):_ <- reads compStr
, Just muStr <- stripPrefix " in " inStr
, (mus,"us."):_ <- reads muStr
= POk (DTComplete comp (mus * 10^(3 :: Int))) ts
| Just _ <- stripPrefix "Complete par " gmsg
= PUnparsable
| Just issuStr <- stripPrefix "Issuing par " gmsg
, (comp,""):_ <- reads issuStr
= POk (DTIssuing comp) ts
| Just _ <- stripPrefix "Issuing par " gmsg
= PUnparsable
| otherwise
= PIgnored
data GangEvent = GangEvent (Maybe Int) Timestamp String
deriving Show
| Potentially merge multiple CapEvents into single GangEvent
Because each event can only be 500 or so characters ,
" GANG[1/2 ] Complete par xxx "
getGangEvents :: [CapEvent] -> [GangEvent]
getGangEvents xs = snd $ foldl (flip gang) (Nothing,[]) xs
where
gang (CapEvent c (Event t (UserMessage gmsg)))
(no,ls)
| Just numS <- stripPrefix "GANG[" gmsg
, [(n,'/':n2S)] <- reads numS :: [(Int,String)]
, [(m,']':' ':restS)]<- reads n2S :: [(Int,String)]
= app (n,m) no (GangEvent c t restS) ls
| otherwise
= (no,ls)
gang _ acc = acc
app (n,m) se ge ls
| n == 1 && m == 1
= (Nothing, ls ++ [ge])
| n == 1
= (Just ge, ls)
| n == m
= (Nothing, ls ++ [se `merge` ge])
| otherwise
= (Just $ se `merge` ge, ls)
merge Nothing ge
= ge
merge (Just (GangEvent c t s)) (GangEvent _ _ s')
= GangEvent c t (s++s')
pprGangEvents :: [GangEvent] -> Doc
pprGangEvents gs = vcat $ map ppr gs
instance Pretty GangEvent where
ppr (GangEvent c t s) =
padL 10 (text $ show c) <>
padR 15 (pprTimestampAbs t) <>
text s
data DphOpsState = DphOpsState (Map Timestamp [(W.Comp, Timestamp)]) Timestamp Int
dphOpsMachine :: Machine DphOpsState GangEvent
dphOpsMachine = Machine
{ initial = DphOpsState M.empty 0 0
, final = const False
, alpha = alph
, delta = delt
}
where
alph _ = True
delt (DphOpsState ops total unparse) evt
= case parseComp evt of
POk (DTComplete comp duration) t ->
Just $ DphOpsState (update ops duration (comp,t)) (total + duration) unparse
PUnparsable ->
Just $ DphOpsState ops total (unparse+1)
_ ->
Just $ DphOpsState ops total unparse
delt s _ = Just s
update !counts !k !v = M.insertWith' (++) k [v] counts
instance Pretty DphOpsState where
ppr (DphOpsState ops total unparse) = vcat [unparse', ops']
where
unparse'
= if unparse == 0
then text ""
else text "Errors: " <> ppr unparse <> text " events unable to be parsed"
ops' = vcat $ map pprOps $ reverse $ M.assocs ops
pprOps (duration,cs) = vcat $ map (pprOp duration) cs
pprOp duration (c,t) = padLines (cat
[ pprPercent duration
, text " "
, padR 10 (text "(" <> pprTimestampEng duration <> text ")")
, text " "
, padR 15 $ pprTimestampAbs t
, text " "
]) (show $ ppr c)
pprPercent v = padR 5 $ ppr (v * 100 `div` total) <> text "%"
data DphOpsSumState = DphOpsSumState (Map W.Comp (Int,Timestamp)) Timestamp Int
dphOpsSumMachine :: Machine DphOpsSumState GangEvent
dphOpsSumMachine = Machine
{ initial = DphOpsSumState M.empty 0 0
, final = const False
, alpha = alph
, delta = delt
}
where
alph _ = True
" GANG Complete par CompMap { ... } in 44us "
delt (DphOpsSumState ops total unparse) evt
= case parseComp evt of
POk (DTComplete comp duration) _ ->
Just $ DphOpsSumState (update ops (clearJoinComp comp) (1,duration)) (total + duration) unparse
PUnparsable ->
Just $ DphOpsSumState ops total (unparse+1)
_ ->
Just $ DphOpsSumState ops total unparse
delt s _ = Just s
update !counts !k !v = M.insertWith' pairAdd k v counts
pairAdd (aa,ab) (ba,bb) = (aa+ba, ab+bb)
Reset the elements arg of all JoinCopies so they show up as total
clearJoinComp :: W.Comp -> W.Comp
clearJoinComp (W.CGen c w) = W.CGen c $ clearJoinWhat w
clearJoinComp (W.CMap w) = W.CMap $ clearJoinWhat w
clearJoinComp (W.CFold w) = W.CFold $ clearJoinWhat w
clearJoinComp (W.CScan w) = W.CScan $ clearJoinWhat w
clearJoinComp (W.CDist w) = W.CDist $ clearJoinWhat w
clearJoinWhat :: W.What -> W.What
clearJoinWhat (W.WJoinCopy _)= W.WJoinCopy (-1)
clearJoinWhat (W.WFMapMap p q) = W.WFMapMap (clearJoinWhat p) (clearJoinWhat q)
clearJoinWhat (W.WFMapGen p q) = W.WFMapGen (clearJoinWhat p) (clearJoinWhat q)
clearJoinWhat (W.WFZipMap p q) = W.WFZipMap (clearJoinWhat p) (clearJoinWhat q)
clearJoinWhat w = w
instance Pretty DphOpsSumState where
ppr (DphOpsSumState ops total unparse) = vcat [unparse', ops']
where
unparse'
= if unparse == 0
then text ""
else text "Errors: " <> ppr unparse <> text " events unable to be parsed"
ops' = vcat $ map pprOp $ sortBy cmp $ M.assocs ops
cmp (_,(_,p)) (_,(_,q))
= case compare p q of
GT -> LT
EQ -> EQ
LT -> GT
pprOp (c,(calls,duration)) = padLines (cat
[ pprPercent duration
, text " "
, padR 10 (text "(" <> pprTimestampEng duration <> text ")")
, text " "
, padR 10 (ppr calls)
, text " "
]) (show $ ppr c)
pprPercent v = padR 5 $ ppr (v * 100 `div` total) <> text "%"
instance Pretty W.Comp where
ppr (W.CGen cheap what)
= cheap' <> ppr what
where
cheap' = if cheap
then text "GenC "
else text "Gen "
ppr (W.CMap what)
= text "Map " <> ppr what
ppr (W.CFold what)
= text "Fold " <> ppr what
ppr (W.CScan what)
= text "Scan " <> ppr what
ppr (W.CDist what)
= text "Dist " <> ppr what
instance Pretty W.What where
ppr (W.What what) = text $ show what
ppr (W.WScalar) = text "Scalar"
ppr (W.WZip) = text "Zip"
ppr (W.WSlice) = text "Slice"
ppr (W.WLength) = text "Length"
ppr (W.WLengthIdx) = text "LengthIdx"
ppr (W.WBpermute) = text "Bpermute"
ppr (W.WJoinCopy (-1)) = text "JoinCp"
ppr (W.WJoinCopy n) = text ("JoinCp(" ++ show n ++ ")")
ppr (W.WFMapMap p q) = text "(" <> ppr p <> text " mapMap " <> ppr q <> text ")"
ppr (W.WFMapGen p q) = text "(" <> ppr p <> text " mapGen " <> ppr q <> text ")"
ppr (W.WFZipMap p q) = text "(" <> ppr p <> text " zipMap " <> ppr q <> text ")"
|
387b6e2bd08aeb8348f25fdb90343f329d99a80e087c7393b4a28839085619af | adityaathalye/sicp | ex1-05-normal-or-applicative.scm | (define (p) (p))
(define (test x y)
(if (= x 0)
0
y)) | null | https://raw.githubusercontent.com/adityaathalye/sicp/c8b62c366dade1d5101238a32267dab177808105/ex1-05-normal-or-applicative.scm | scheme | (define (p) (p))
(define (test x y)
(if (= x 0)
0
y)) |
|
7310752bcf8f815606cc6d727931e9188564b75b75582a227a3248fcbeaa79b3 | space-lang/space | type_env.ml | let check_identifier_assignable class_defns identifier env loc =
let open Result in
match identifier with
| Parsed_ast.Variable x ->
if x = Var_nameof_string "this" then
Error
(Error.of_string
(Fmt.str "%s Type error - Assigning expr to 'this'.@." (string_of_loc loc)))
else Ok ()
| Parsed_ast.ObjField (obj_name, field_name) ->
get_obj_class_defn obj_name env class_defns loc
>>= fun class_defn ->
get_class_field field_name class_defn loc
>>= fun (TField (modifier, _, _, _)) ->
if modifier = MConst then
Error
(Error.of_string
(Fmt.str "%s Type error - Assigning expr to a const field.@."
(string_of_loc loc)))
else Ok () | null | https://raw.githubusercontent.com/space-lang/space/23b03f71ea57486171bbf22ed2a7a42486fb4124/src/frontend/typing/type_env.ml | ocaml | let check_identifier_assignable class_defns identifier env loc =
let open Result in
match identifier with
| Parsed_ast.Variable x ->
if x = Var_nameof_string "this" then
Error
(Error.of_string
(Fmt.str "%s Type error - Assigning expr to 'this'.@." (string_of_loc loc)))
else Ok ()
| Parsed_ast.ObjField (obj_name, field_name) ->
get_obj_class_defn obj_name env class_defns loc
>>= fun class_defn ->
get_class_field field_name class_defn loc
>>= fun (TField (modifier, _, _, _)) ->
if modifier = MConst then
Error
(Error.of_string
(Fmt.str "%s Type error - Assigning expr to a const field.@."
(string_of_loc loc)))
else Ok () |
|
f920a35b8e06760410392c12ad38c2f2b4ddc3ba6574f98716a09f4d5d3e002a | eval/deps-try | main.clj | (ns rebel-readline.clojure.main
(:require
[rebel-readline.core :as core]
[rebel-readline.clojure.line-reader :as clj-line-reader]
[rebel-readline.jline-api :as api]
[rebel-readline.tools :as tools]
[rebel-readline.clojure.service.local :as clj-service]
[clojure.main]))
(defn syntax-highlight-prn
"Print a syntax highlighted clojure value.
This printer respects the current color settings set in the
service.
The `rebel-readline.jline-api/*line-reader*` and
`rebel-readline.jline-api/*service*` dynamic vars have to be set for
this to work.
See `rebel-readline.main` for an example of how this function is normally used"
[x]
(binding [*out* (.. api/*line-reader* getTerminal writer)]
(try
(println (api/->ansi (clj-line-reader/highlight-clj-str (pr-str x))))
(catch java.lang.StackOverflowError e
(println (pr-str x))))))
;; this is intended to only be used with clojure repls
(def create-repl-read
"A drop in replacement for clojure.main/repl-read, since a readline
can return multiple Clojure forms this function is stateful and
buffers the forms and returns the next form on subsequent reads.
This function is a constructor that takes a line-reader and returns
a function that can replace `clojure.main/repl-read`.
Example Usage:
(clojure.main/repl
:prompt (fn []) ;; prompt is handled by line-reader
:read (clj-repl-read
(line-reader
(rebel-readline.clojure.service.local/create))))
Or catch a bad terminal error and fall back to clojure.main/repl-read:
(clojure.main/repl
:prompt (fn [])
:read (try
(clj-repl-read
(line-reader
(rebel-readline.clojure.service.local/create)))
(catch clojure.lang.ExceptionInfo e
(if (-> e ex-data :type (= :rebel-readline.jline-api/bad-terminal))
(do (println (.getMessage e))
clojure.main/repl-read)
(throw e)))))"
(core/create-buffered-repl-reader-fn
(fn [s] (clojure.lang.LineNumberingPushbackReader.
(java.io.StringReader. s)))
core/has-remaining?
clojure.main/repl-read))
(let [clj-repl clojure.main/repl]
(defn repl* [opts]
(core/with-line-reader
(clj-line-reader/create
(clj-service/create
(when api/*line-reader* @api/*line-reader*)))
;; still debating about wether to include the following line in
;; `with-line-reader`. I am thinking that taking over out should
;; be opt in when using the lib taking over out provides
guarantees by that Ascii commands are processed correctly
;; on different platforms, this particular writer also protects
;; the prompt from corruption by ensuring a newline on flush and
;; forcing a prompt to redisplay if the output is printed while
;; the readline editor is enguaged
(binding [*out* (api/safe-terminal-writer api/*line-reader*)]
(when-let [prompt-fn (:prompt opts)]
(swap! api/*line-reader* assoc :prompt prompt-fn))
(println (core/help-message))
(apply
clj-repl
(-> {:print syntax-highlight-prn
:read (create-repl-read)}
(merge opts {:prompt (fn [])})
seq
flatten))))))
(defn repl [& opts]
(repl* (apply hash-map opts)))
;; --------------------------------------------
;; Debug repl (Joy of Clojure)
;; --------------------------------------------
(defn contextual-eval [ctx expr]
(eval
`(let [~@(mapcat (fn [[k v]] [k `'~v]) ctx)]
~expr)))
(defmacro local-context []
(let [symbols (keys &env)]
(zipmap (map (fn [sym] `(quote ~sym)) symbols) symbols)))
(defmacro break []
`(repl
:prompt #(print "debug=> ")
:eval (partial contextual-eval (local-context))))
(defn -main [& args]
(core/ensure-terminal (repl)))
| null | https://raw.githubusercontent.com/eval/deps-try/da691c68b527ad5f9e770dbad82cce6cbbe16fb4/vendor/rebel-readline/rebel-readline/src/rebel_readline/clojure/main.clj | clojure | this is intended to only be used with clojure repls
prompt is handled by line-reader
still debating about wether to include the following line in
`with-line-reader`. I am thinking that taking over out should
be opt in when using the lib taking over out provides
on different platforms, this particular writer also protects
the prompt from corruption by ensuring a newline on flush and
forcing a prompt to redisplay if the output is printed while
the readline editor is enguaged
--------------------------------------------
Debug repl (Joy of Clojure)
-------------------------------------------- | (ns rebel-readline.clojure.main
(:require
[rebel-readline.core :as core]
[rebel-readline.clojure.line-reader :as clj-line-reader]
[rebel-readline.jline-api :as api]
[rebel-readline.tools :as tools]
[rebel-readline.clojure.service.local :as clj-service]
[clojure.main]))
(defn syntax-highlight-prn
"Print a syntax highlighted clojure value.
This printer respects the current color settings set in the
service.
The `rebel-readline.jline-api/*line-reader*` and
`rebel-readline.jline-api/*service*` dynamic vars have to be set for
this to work.
See `rebel-readline.main` for an example of how this function is normally used"
[x]
(binding [*out* (.. api/*line-reader* getTerminal writer)]
(try
(println (api/->ansi (clj-line-reader/highlight-clj-str (pr-str x))))
(catch java.lang.StackOverflowError e
(println (pr-str x))))))
(def create-repl-read
"A drop in replacement for clojure.main/repl-read, since a readline
can return multiple Clojure forms this function is stateful and
buffers the forms and returns the next form on subsequent reads.
This function is a constructor that takes a line-reader and returns
a function that can replace `clojure.main/repl-read`.
Example Usage:
(clojure.main/repl
:read (clj-repl-read
(line-reader
(rebel-readline.clojure.service.local/create))))
Or catch a bad terminal error and fall back to clojure.main/repl-read:
(clojure.main/repl
:prompt (fn [])
:read (try
(clj-repl-read
(line-reader
(rebel-readline.clojure.service.local/create)))
(catch clojure.lang.ExceptionInfo e
(if (-> e ex-data :type (= :rebel-readline.jline-api/bad-terminal))
(do (println (.getMessage e))
clojure.main/repl-read)
(throw e)))))"
(core/create-buffered-repl-reader-fn
(fn [s] (clojure.lang.LineNumberingPushbackReader.
(java.io.StringReader. s)))
core/has-remaining?
clojure.main/repl-read))
(let [clj-repl clojure.main/repl]
(defn repl* [opts]
(core/with-line-reader
(clj-line-reader/create
(clj-service/create
(when api/*line-reader* @api/*line-reader*)))
guarantees by that Ascii commands are processed correctly
(binding [*out* (api/safe-terminal-writer api/*line-reader*)]
(when-let [prompt-fn (:prompt opts)]
(swap! api/*line-reader* assoc :prompt prompt-fn))
(println (core/help-message))
(apply
clj-repl
(-> {:print syntax-highlight-prn
:read (create-repl-read)}
(merge opts {:prompt (fn [])})
seq
flatten))))))
(defn repl [& opts]
(repl* (apply hash-map opts)))
(defn contextual-eval [ctx expr]
(eval
`(let [~@(mapcat (fn [[k v]] [k `'~v]) ctx)]
~expr)))
(defmacro local-context []
(let [symbols (keys &env)]
(zipmap (map (fn [sym] `(quote ~sym)) symbols) symbols)))
(defmacro break []
`(repl
:prompt #(print "debug=> ")
:eval (partial contextual-eval (local-context))))
(defn -main [& args]
(core/ensure-terminal (repl)))
|
c051607f3a9847f12f0d3baed68df9dc3a4202b72b23ce92a76e59a5b950b653 | SquidDev/illuaminate | lint.mli | open IlluaminateCore
open Lsp.Types
(** All notes for a given program. *)
val notes : IlluaminateLint.Driver.Note.any array IlluaminateData.Programs.key
* a program and export any diagnostics .
val diagnostics : Store.t -> Store.document -> Diagnostic.t list
(** Get any code actions for a given range. *)
val code_actions : Store.t -> Span.filename -> Syntax.program -> Range.t -> CodeActionResult.t
(** Fix a program given a specific id, or fail. *)
val fix : Store.t -> Span.filename -> int -> (TextEdit.t, string) result
| null | https://raw.githubusercontent.com/SquidDev/illuaminate/7a6e4bf56f01e81a47c743cb452791c2168ccbda/src/bin/lsp/lint.mli | ocaml | * All notes for a given program.
* Get any code actions for a given range.
* Fix a program given a specific id, or fail. | open IlluaminateCore
open Lsp.Types
val notes : IlluaminateLint.Driver.Note.any array IlluaminateData.Programs.key
* a program and export any diagnostics .
val diagnostics : Store.t -> Store.document -> Diagnostic.t list
val code_actions : Store.t -> Span.filename -> Syntax.program -> Range.t -> CodeActionResult.t
val fix : Store.t -> Span.filename -> int -> (TextEdit.t, string) result
|
7b3492161e020f4d5bd0102533917b2e47b8d84659294ab898c4faa69517cfc6 | Fresheyeball/Shpadoinkle | Form.hs | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE CPP #
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DerivingStrategies #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
module Shpadoinkle.Widgets.Types.Form
( module Shpadoinkle.Widgets.Types.Form
) where
import Control.Applicative (Alternative (empty),
Applicative (liftA2),
Const (Const, getConst))
import Control.Monad.Except (MonadError (..))
import Data.Aeson (FromJSON, ToJSON)
import Data.Kind (Type)
import Data.String (IsString)
import Data.Text (Text)
import GHC.Generics
#ifdef TESTING
import Test.QuickCheck (Arbitrary (..), elements)
#endif
import Shpadoinkle (NFData)
import Shpadoinkle.Widgets.Types.Core (Hygiene)
data Input a = Input
{ _hygiene :: Hygiene
, _value :: a
} deriving (Eq, Ord, Show, Read, Functor, Traversable, Foldable, Generic, ToJSON, FromJSON, NFData)
#ifdef TESTING
instance Arbitrary a => Arbitrary (Input a) where arbitrary = Input <$> arbitrary <*> arbitrary
#endif
class Control g where
type Val g a :: Type
type Val g a = a
hygiene :: Applicative f => (Hygiene -> f Hygiene) -> g a -> f (g a)
value :: (Applicative f, Ord a) => (Val g a -> f (Val g a)) -> g a -> f (g a)
getValue :: (Ord a, Monoid (Val g a), Control g) => g a -> Val g a
getValue = getConst . value Const
getHygiene :: Control g => g a -> Hygiene
getHygiene = getConst . hygiene Const
instance Control Input where
hygiene f i = (\h -> i { _hygiene = h }) <$> f (_hygiene i)
value f i = (\a -> i { _value = a }) <$> f (_value i)
instance Applicative Input where
Input h fa <*> Input h' a = Input (h <> h') (fa a)
pure = Input mempty
instance Monad Input where
Input h a >>= f = let Input h' a' = f a in Input (h <> h') a'
instance Semigroup a => Semigroup (Input a) where
Input h a <> Input h' a' = Input (h <> h') (a <> a')
instance Monoid a => Monoid (Input a) where
mempty = Input mempty mempty
newtype Placeholder = Placeholder { unPlaceholder :: Text }
deriving newtype (Eq, Ord, Show, Read, IsString, Semigroup, Monoid, ToJSON, FromJSON)
deriving stock Generic
deriving anyclass NFData
data Validated e a = Validated a | Invalid e [e]
deriving (Eq, Ord, Show, Read, Generic, ToJSON, FromJSON, Functor, Foldable, Traversable, NFData)
instance Semigroup (Validated e a) where
Validated a <> Validated _ = Validated a
Validated _ <> x = x
x <> Validated _ = x
Invalid x xs <> Invalid y ys = Invalid x (xs <> (y:ys))
instance Applicative (Validated e) where
Validated f <*> Validated a = Validated (f a)
Invalid x xs <*> _ = Invalid x xs
_ <*> Invalid x xs = Invalid x xs
pure = Validated
instance Monad (Validated e) where
Validated a >>= f = f a
Invalid x xs >>= _ = Invalid x xs
instance MonadError e (Validated e) where
throwError e = Invalid e []
catchError (Invalid x _) f = f x
catchError v _ = v
data Status = Edit | Rules | Valid | Errors
type family Field (s :: Status) (e :: Type) (f :: Type -> Type) (x :: Type) :: Type where
Field 'Valid _ _ a = a
Field 'Errors e _ a = Validated e a
Field 'Edit _ f a = f a
Field 'Rules e f a = Val f a -> Validated e a
class ValidateG rules edit errs where
validateg :: rules a -> edit a -> errs a
instance ValidateG U1 U1 U1 where
validateg _ _ = U1
instance (ValidateG a b c, ValidateG d e f)
=> ValidateG (a :*: d) (b :*: e) (c :*: f) where
validateg (a :*: b) (c :*: d) = validateg a c :*: validateg b d
instance (ValidateG a b c, ValidateG d e f, Alternative (c :+: f))
=> ValidateG (a :+: d) (b :+: e) (c :+: f) where
validateg (L1 a) (L1 b) = L1 $ validateg a b
validateg (R1 a) (R1 b) = R1 $ validateg a b
validateg _ _ = empty
instance ValidateG a b c
=> ValidateG (M1 i x a) (M1 i' x' b) (M1 i'' x'' c) where
validateg (M1 a) (M1 b) = M1 $ validateg a b
instance (Control c, Monoid v, Val c a ~ v, Ord a)
=> ValidateG (K1 i (v -> b)) (K1 i' (c a)) (K1 i'' b) where
validateg (K1 f) (K1 x) = K1 (f $ getValue x)
class ValidG err valid where
validg :: err a -> Maybe (valid a)
instance ValidG U1 U1 where
validg _ = Just U1
instance (ValidG a c, ValidG b d) => ValidG (a :*: b) (c :*: d) where
validg (a :*: b) = liftA2 (:*:) (validg a) (validg b)
instance (ValidG a c, ValidG b d) => ValidG (a :+: b) (c :+: d) where
validg (L1 a) = L1 <$> validg a
validg (R1 a) = R1 <$> validg a
instance (ValidG a b) => ValidG (M1 i c a) (M1 i' c' b) where
validg (M1 a) = M1 <$> validg a
instance ValidG (K1 i (Validated t a)) (K1 i' a) where
validg (K1 (Validated a)) = Just $ K1 a
validg _ = Nothing
class Validate (f :: Status -> Type) where
validate :: f 'Edit -> f 'Errors
default validate
:: Generic (f 'Edit)
=> Generic (f 'Rules)
=> Generic (f 'Errors)
=> ValidateG (Rep (f 'Rules)) (Rep (f 'Edit)) (Rep (f 'Errors))
=> f 'Edit -> f 'Errors
validate edit = to $ validateg (from (rules @ f)) (from edit)
getValid :: f 'Errors -> Maybe (f 'Valid)
default getValid
:: Generic (f 'Errors)
=> Generic (f 'Valid)
=> ValidG (Rep (f 'Errors)) (Rep (f 'Valid))
=> f 'Errors -> Maybe (f 'Valid)
getValid = fmap to . validg . from
rules :: f 'Rules
#ifdef TESTING
instance (Arbitrary a, Arbitrary b) => Arbitrary (Validated a b) where
arbitrary = do
(e, es, a) <- (,,) <$> arbitrary <*> arbitrary <*> arbitrary
elements [ Validated a, Invalid e es ]
#endif
| null | https://raw.githubusercontent.com/Fresheyeball/Shpadoinkle/8e0efbb11857a1af47038dae07b8140291c251ed/widgets/Shpadoinkle/Widgets/Types/Form.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DefaultSignatures #
# LANGUAGE DeriveAnyClass #
# LANGUAGE DeriveGeneric #
# LANGUAGE DeriveTraversable #
# LANGUAGE DerivingStrategies #
# LANGUAGE PartialTypeSignatures #
# LANGUAGE RankNTypes #
# LANGUAGE TypeOperators # | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module Shpadoinkle.Widgets.Types.Form
( module Shpadoinkle.Widgets.Types.Form
) where
import Control.Applicative (Alternative (empty),
Applicative (liftA2),
Const (Const, getConst))
import Control.Monad.Except (MonadError (..))
import Data.Aeson (FromJSON, ToJSON)
import Data.Kind (Type)
import Data.String (IsString)
import Data.Text (Text)
import GHC.Generics
#ifdef TESTING
import Test.QuickCheck (Arbitrary (..), elements)
#endif
import Shpadoinkle (NFData)
import Shpadoinkle.Widgets.Types.Core (Hygiene)
data Input a = Input
{ _hygiene :: Hygiene
, _value :: a
} deriving (Eq, Ord, Show, Read, Functor, Traversable, Foldable, Generic, ToJSON, FromJSON, NFData)
#ifdef TESTING
instance Arbitrary a => Arbitrary (Input a) where arbitrary = Input <$> arbitrary <*> arbitrary
#endif
class Control g where
type Val g a :: Type
type Val g a = a
hygiene :: Applicative f => (Hygiene -> f Hygiene) -> g a -> f (g a)
value :: (Applicative f, Ord a) => (Val g a -> f (Val g a)) -> g a -> f (g a)
getValue :: (Ord a, Monoid (Val g a), Control g) => g a -> Val g a
getValue = getConst . value Const
getHygiene :: Control g => g a -> Hygiene
getHygiene = getConst . hygiene Const
instance Control Input where
hygiene f i = (\h -> i { _hygiene = h }) <$> f (_hygiene i)
value f i = (\a -> i { _value = a }) <$> f (_value i)
instance Applicative Input where
Input h fa <*> Input h' a = Input (h <> h') (fa a)
pure = Input mempty
instance Monad Input where
Input h a >>= f = let Input h' a' = f a in Input (h <> h') a'
instance Semigroup a => Semigroup (Input a) where
Input h a <> Input h' a' = Input (h <> h') (a <> a')
instance Monoid a => Monoid (Input a) where
mempty = Input mempty mempty
newtype Placeholder = Placeholder { unPlaceholder :: Text }
deriving newtype (Eq, Ord, Show, Read, IsString, Semigroup, Monoid, ToJSON, FromJSON)
deriving stock Generic
deriving anyclass NFData
data Validated e a = Validated a | Invalid e [e]
deriving (Eq, Ord, Show, Read, Generic, ToJSON, FromJSON, Functor, Foldable, Traversable, NFData)
instance Semigroup (Validated e a) where
Validated a <> Validated _ = Validated a
Validated _ <> x = x
x <> Validated _ = x
Invalid x xs <> Invalid y ys = Invalid x (xs <> (y:ys))
instance Applicative (Validated e) where
Validated f <*> Validated a = Validated (f a)
Invalid x xs <*> _ = Invalid x xs
_ <*> Invalid x xs = Invalid x xs
pure = Validated
instance Monad (Validated e) where
Validated a >>= f = f a
Invalid x xs >>= _ = Invalid x xs
instance MonadError e (Validated e) where
throwError e = Invalid e []
catchError (Invalid x _) f = f x
catchError v _ = v
data Status = Edit | Rules | Valid | Errors
type family Field (s :: Status) (e :: Type) (f :: Type -> Type) (x :: Type) :: Type where
Field 'Valid _ _ a = a
Field 'Errors e _ a = Validated e a
Field 'Edit _ f a = f a
Field 'Rules e f a = Val f a -> Validated e a
class ValidateG rules edit errs where
validateg :: rules a -> edit a -> errs a
instance ValidateG U1 U1 U1 where
validateg _ _ = U1
instance (ValidateG a b c, ValidateG d e f)
=> ValidateG (a :*: d) (b :*: e) (c :*: f) where
validateg (a :*: b) (c :*: d) = validateg a c :*: validateg b d
instance (ValidateG a b c, ValidateG d e f, Alternative (c :+: f))
=> ValidateG (a :+: d) (b :+: e) (c :+: f) where
validateg (L1 a) (L1 b) = L1 $ validateg a b
validateg (R1 a) (R1 b) = R1 $ validateg a b
validateg _ _ = empty
instance ValidateG a b c
=> ValidateG (M1 i x a) (M1 i' x' b) (M1 i'' x'' c) where
validateg (M1 a) (M1 b) = M1 $ validateg a b
instance (Control c, Monoid v, Val c a ~ v, Ord a)
=> ValidateG (K1 i (v -> b)) (K1 i' (c a)) (K1 i'' b) where
validateg (K1 f) (K1 x) = K1 (f $ getValue x)
class ValidG err valid where
validg :: err a -> Maybe (valid a)
instance ValidG U1 U1 where
validg _ = Just U1
instance (ValidG a c, ValidG b d) => ValidG (a :*: b) (c :*: d) where
validg (a :*: b) = liftA2 (:*:) (validg a) (validg b)
instance (ValidG a c, ValidG b d) => ValidG (a :+: b) (c :+: d) where
validg (L1 a) = L1 <$> validg a
validg (R1 a) = R1 <$> validg a
instance (ValidG a b) => ValidG (M1 i c a) (M1 i' c' b) where
validg (M1 a) = M1 <$> validg a
instance ValidG (K1 i (Validated t a)) (K1 i' a) where
validg (K1 (Validated a)) = Just $ K1 a
validg _ = Nothing
class Validate (f :: Status -> Type) where
validate :: f 'Edit -> f 'Errors
default validate
:: Generic (f 'Edit)
=> Generic (f 'Rules)
=> Generic (f 'Errors)
=> ValidateG (Rep (f 'Rules)) (Rep (f 'Edit)) (Rep (f 'Errors))
=> f 'Edit -> f 'Errors
validate edit = to $ validateg (from (rules @ f)) (from edit)
getValid :: f 'Errors -> Maybe (f 'Valid)
default getValid
:: Generic (f 'Errors)
=> Generic (f 'Valid)
=> ValidG (Rep (f 'Errors)) (Rep (f 'Valid))
=> f 'Errors -> Maybe (f 'Valid)
getValid = fmap to . validg . from
rules :: f 'Rules
#ifdef TESTING
instance (Arbitrary a, Arbitrary b) => Arbitrary (Validated a b) where
arbitrary = do
(e, es, a) <- (,,) <$> arbitrary <*> arbitrary <*> arbitrary
elements [ Validated a, Invalid e es ]
#endif
|
1ab28d789abe97087ff3e0d89c6032e6b5104d16829881bdd37017277ebfd023 | gdevanla/haskell-lox | main.hs | # LANGUAGE NoImplicitPrelude #
# LANGUAGE TemplateHaskell #
import Import
import Run
import RIO.Process
import Options.Applicative.Simple
import qualified Paths_haskell_lox
main :: IO ()
main = do
(options, ()) <- simpleOptions
$(simpleVersion Paths_haskell_lox.version)
"Header for command line arguments"
"Program description, also for command line arguments"
(Options
<$> switch ( long "verbose"
<> short 'v'
<> help "Verbose output?"
)
)
empty
lo <- logOptionsHandle stderr (optionsVerbose options)
pc <- mkDefaultProcessContext
withLogFunc lo $ \lf ->
let app = App
{ appLogFunc = lf
, appProcessContext = pc
, appOptions = options
}
in runRIO app run
| null | https://raw.githubusercontent.com/gdevanla/haskell-lox/43fe7155b50a5f4eaaad75e7cb4e6e5aed58701f/app/main.hs | haskell | # LANGUAGE NoImplicitPrelude #
# LANGUAGE TemplateHaskell #
import Import
import Run
import RIO.Process
import Options.Applicative.Simple
import qualified Paths_haskell_lox
main :: IO ()
main = do
(options, ()) <- simpleOptions
$(simpleVersion Paths_haskell_lox.version)
"Header for command line arguments"
"Program description, also for command line arguments"
(Options
<$> switch ( long "verbose"
<> short 'v'
<> help "Verbose output?"
)
)
empty
lo <- logOptionsHandle stderr (optionsVerbose options)
pc <- mkDefaultProcessContext
withLogFunc lo $ \lf ->
let app = App
{ appLogFunc = lf
, appProcessContext = pc
, appOptions = options
}
in runRIO app run
|
|
ee3ad967786c4db9ffbc89741ba7c3542b1b09543794ff63285f5ea6a495916d | edbutler/nonograms-rule-synthesis | test-parallel.rkt | #lang racket
; testing the thread parallelism
(require
rackunit
rackunit/text-ui
"util.rkt"
"../core/core.rkt")
(define (test-parmap f lst)
(check-set=? (parallel-map/thread f lst) (map f lst)))
(void (run-tests (test-suite
"parallel"
(test-case "simple"
(let ([lst '(1 2 3 4 5 6 7 8 9)])
(test-parmap identity lst)
(test-parmap add1 lst)
(test-parmap (λ (x) (cons x 45)) lst)
(void)))
)))
| null | https://raw.githubusercontent.com/edbutler/nonograms-rule-synthesis/16f8dacb17bd77c9d927ab9fa0b8c1678dc68088/src/test/test-parallel.rkt | racket | testing the thread parallelism | #lang racket
(require
rackunit
rackunit/text-ui
"util.rkt"
"../core/core.rkt")
(define (test-parmap f lst)
(check-set=? (parallel-map/thread f lst) (map f lst)))
(void (run-tests (test-suite
"parallel"
(test-case "simple"
(let ([lst '(1 2 3 4 5 6 7 8 9)])
(test-parmap identity lst)
(test-parmap add1 lst)
(test-parmap (λ (x) (cons x 45)) lst)
(void)))
)))
|
9b00fb18d61603c786a87b902637a4fac88dbcb62f5f048d1f7ae07cb19260fa | sternenseemann/spacecookie | Socket.hs | -- | Internal socket utilities implementing missing
-- features of 'System.Socket' which are yet to be
-- upstreamed.
module Network.Gopher.Util.Socket
( gracefulClose
) where
import Control.Concurrent.MVar (withMVar)
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (race)
import Control.Exception.Base (throwIO)
import Control.Monad (void, when)
import Data.Functor ((<&>))
import Foreign.C.Error (Errno (..), getErrno)
import Foreign.C.Types (CInt (..))
import System.Socket (receive, msgNoSignal, SocketException (..), close, Family ())
import System.Socket.Type.Stream (Stream ())
import System.Socket.Protocol.TCP (TCP ())
import System.Socket.Unsafe (Socket (..))
-- Until -socket/pull/67 gets
-- merged, we have to implement shutdown ourselves.
foreign import ccall unsafe "shutdown"
c_shutdown :: CInt -> CInt -> IO CInt
data ShutdownHow
-- | Disallow Reading (calls to 'receive' are empty).
= ShutdownRead
-- | Disallow Writing (calls to 'send' throw).
| ShutdownWrite
-- | Disallow both.
| ShutdownReadWrite
deriving (Show, Eq, Ord, Enum)
-- | Shutdown a stream connection (partially).
-- Will send TCP FIN and prompt a client to
-- close the connection.
--
-- Not exposed to prevent future name clash.
shutdown :: Socket a Stream TCP -> ShutdownHow -> IO ()
shutdown (Socket mvar) how = withMVar mvar $ \fd -> do
res <- c_shutdown (fromIntegral fd)
$ fromIntegral $ fromEnum how
when (res /= 0) $ throwIO =<<
(getErrno <&> \(Errno errno) -> SocketException errno)
-- | Shutdown connection and give client a bit
-- of time to clean up on its end before closing
-- the connection to avoid a broken pipe on the
-- other side.
gracefulClose :: Family f => Socket f Stream TCP -> IO ()
gracefulClose sock = do
-- send TCP FIN
shutdown sock ShutdownWrite
-- wait for some kind of read from the
client ( either mempty , meaning TCP FIN ,
-- something else which would mean protocol
violation ) . Give up after 1s .
_ <- race (void $ receive sock 16 msgNoSignal) (threadDelay 1000000)
close sock
| null | https://raw.githubusercontent.com/sternenseemann/spacecookie/687bc78c1e9355468bf4eb480750b819e520f20e/src/Network/Gopher/Util/Socket.hs | haskell | | Internal socket utilities implementing missing
features of 'System.Socket' which are yet to be
upstreamed.
Until -socket/pull/67 gets
merged, we have to implement shutdown ourselves.
| Disallow Reading (calls to 'receive' are empty).
| Disallow Writing (calls to 'send' throw).
| Disallow both.
| Shutdown a stream connection (partially).
Will send TCP FIN and prompt a client to
close the connection.
Not exposed to prevent future name clash.
| Shutdown connection and give client a bit
of time to clean up on its end before closing
the connection to avoid a broken pipe on the
other side.
send TCP FIN
wait for some kind of read from the
something else which would mean protocol | module Network.Gopher.Util.Socket
( gracefulClose
) where
import Control.Concurrent.MVar (withMVar)
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (race)
import Control.Exception.Base (throwIO)
import Control.Monad (void, when)
import Data.Functor ((<&>))
import Foreign.C.Error (Errno (..), getErrno)
import Foreign.C.Types (CInt (..))
import System.Socket (receive, msgNoSignal, SocketException (..), close, Family ())
import System.Socket.Type.Stream (Stream ())
import System.Socket.Protocol.TCP (TCP ())
import System.Socket.Unsafe (Socket (..))
foreign import ccall unsafe "shutdown"
c_shutdown :: CInt -> CInt -> IO CInt
data ShutdownHow
= ShutdownRead
| ShutdownWrite
| ShutdownReadWrite
deriving (Show, Eq, Ord, Enum)
shutdown :: Socket a Stream TCP -> ShutdownHow -> IO ()
shutdown (Socket mvar) how = withMVar mvar $ \fd -> do
res <- c_shutdown (fromIntegral fd)
$ fromIntegral $ fromEnum how
when (res /= 0) $ throwIO =<<
(getErrno <&> \(Errno errno) -> SocketException errno)
gracefulClose :: Family f => Socket f Stream TCP -> IO ()
gracefulClose sock = do
shutdown sock ShutdownWrite
client ( either mempty , meaning TCP FIN ,
violation ) . Give up after 1s .
_ <- race (void $ receive sock 16 msgNoSignal) (threadDelay 1000000)
close sock
|
fb7e1c159f5813c89d5f921d4963e12a6588dbb7a4cd4b5eabbc1152fac10211 | bakyeono/bitmap-font | color.clj | ;; bitmap-font.color
;; 자주 사용되는 색상을 정의
(ns bitmap-font.color)
(def ^:const absolute-zero [(/ 0 255.0) (/ 72 255.0) (/ 186 255.0)])
(def ^:const alien-armpit [(/ 132 255.0) (/ 222 255.0) (/ 2 255.0)])
(def ^:const alloy-orange [(/ 196 255.0) (/ 98 255.0) (/ 16 255.0)])
(def ^:const almond [(/ 239 255.0) (/ 222 255.0) (/ 205 255.0)])
(def ^:const amethyst [(/ 100 255.0) (/ 96 255.0) (/ 154 255.0)])
(def ^:const antique-brass [(/ 205 255.0) (/ 149 255.0) (/ 117 255.0)])
(def ^:const apricot [(/ 253 255.0) (/ 217 255.0) (/ 181 255.0)])
(def ^:const aqua-pearl [(/ 95 255.0) (/ 190 255.0) (/ 215 255.0)])
(def ^:const aquamarine [(/ 120 255.0) (/ 219 255.0) (/ 226 255.0)])
(def ^:const asparagus [(/ 135 255.0) (/ 169 255.0) (/ 107 255.0)])
(def ^:const atomic-tangerine [(/ 255 255.0) (/ 164 255.0) (/ 116 255.0)])
(def ^:const aztec-gold [(/ 195 255.0) (/ 153 255.0) (/ 83 255.0)])
(def ^:const b-dazzled-blue [(/ 46 255.0) (/ 88 255.0) (/ 148 255.0)])
(def ^:const baby-powder [(/ 254 255.0) (/ 254 255.0) (/ 250 255.0)])
(def ^:const banana [(/ 255 255.0) (/ 209 255.0) (/ 42 255.0)])
(def ^:const banana-mania [(/ 250 255.0) (/ 231 255.0) (/ 181 255.0)])
(def ^:const beaver [(/ 159 255.0) (/ 129 255.0) (/ 112 255.0)])
(def ^:const big-dip-o-ruby [(/ 156 255.0) (/ 37 255.0) (/ 66 255.0)])
(def ^:const big-foot-feet [(/ 232 255.0) (/ 142 255.0) (/ 90 255.0)])
(def ^:const bittersweet [(/ 253 255.0) (/ 124 255.0) (/ 110 255.0)])
(def ^:const bittersweet-shimmer [(/ 191 255.0) (/ 79 255.0) (/ 81 255.0)])
(def ^:const black [(/ 0 255.0) (/ 0 255.0) (/ 0 255.0)])
(def ^:const black-coral-pearl [(/ 84 255.0) (/ 98 255.0) (/ 111 255.0)])
(def ^:const black-shadows [(/ 191 255.0) (/ 175 255.0) (/ 178 255.0)])
(def ^:const blast-off-bronze [(/ 165 255.0) (/ 113 255.0) (/ 100 255.0)])
(def ^:const blizzard-blue [(/ 172 255.0) (/ 229 255.0) (/ 238 255.0)])
(def ^:const blue [(/ 31 255.0) (/ 117 255.0) (/ 254 255.0)])
(def ^:const blue-bell [(/ 162 255.0) (/ 162 255.0) (/ 208 255.0)])
(def ^:const blue-gray [(/ 102 255.0) (/ 153 255.0) (/ 204 255.0)])
(def ^:const blue-green [(/ 13 255.0) (/ 152 255.0) (/ 186 255.0)])
(def ^:const blue-jeans [(/ 93 255.0) (/ 173 255.0) (/ 236 255.0)])
(def ^:const blue-violet [(/ 115 255.0) (/ 102 255.0) (/ 189 255.0)])
(def ^:const blueberry [(/ 79 255.0) (/ 134 255.0) (/ 247 255.0)])
(def ^:const blush [(/ 222 255.0) (/ 93 255.0) (/ 131 255.0)])
(def ^:const booger-buster [(/ 221 255.0) (/ 226 255.0) (/ 106 255.0)])
(def ^:const brick-red [(/ 203 255.0) (/ 65 255.0) (/ 84 255.0)])
(def ^:const bright-yellow [(/ 255 255.0) (/ 170 255.0) (/ 29 255.0)])
(def ^:const brown [(/ 180 255.0) (/ 103 255.0) (/ 77 255.0)])
(def ^:const brown-sugar [(/ 175 255.0) (/ 110 255.0) (/ 77 255.0)])
(def ^:const bubble-gum [(/ 255 255.0) (/ 211 255.0) (/ 248 255.0)])
(def ^:const burnished-brown [(/ 161 255.0) (/ 122 255.0) (/ 116 255.0)])
(def ^:const burnt-orange [(/ 255 255.0) (/ 127 255.0) (/ 73 255.0)])
(def ^:const burnt-sienna [(/ 234 255.0) (/ 126 255.0) (/ 93 255.0)])
(def ^:const cadet-blue [(/ 176 255.0) (/ 183 255.0) (/ 198 255.0)])
(def ^:const canary [(/ 255 255.0) (/ 255 255.0) (/ 153 255.0)])
(def ^:const caribbean-green [(/ 28 255.0) (/ 211 255.0) (/ 162 255.0)])
(def ^:const caribbean-green-pearl [(/ 106 255.0) (/ 218 255.0) (/ 142 255.0)])
(def ^:const carnation-pink [(/ 255 255.0) (/ 170 255.0) (/ 204 255.0)])
(def ^:const cedar-chest [(/ 201 255.0) (/ 90 255.0) (/ 73 255.0)])
(def ^:const cerise [(/ 221 255.0) (/ 68 255.0) (/ 146 255.0)])
(def ^:const cerulean [(/ 29 255.0) (/ 172 255.0) (/ 214 255.0)])
(def ^:const cerulean-frost [(/ 109 255.0) (/ 155 255.0) (/ 195 255.0)])
(def ^:const cherry [(/ 218 255.0) (/ 38 255.0) (/ 71 255.0)])
(def ^:const chestnut [(/ 188 255.0) (/ 93 255.0) (/ 88 255.0)])
(def ^:const chocolate [(/ 189 255.0) (/ 130 255.0) (/ 96 255.0)])
(def ^:const cinnamon-satin [(/ 205 255.0) (/ 96 255.0) (/ 126 255.0)])
(def ^:const citrine [(/ 147 255.0) (/ 55 255.0) (/ 9 255.0)])
(def ^:const coconut [(/ 254 255.0) (/ 254 255.0) (/ 254 255.0)])
(def ^:const copper [(/ 221 255.0) (/ 148 255.0) (/ 117 255.0)])
(def ^:const copper-penny [(/ 173 255.0) (/ 111 255.0) (/ 105 255.0)])
(def ^:const cornflower [(/ 154 255.0) (/ 206 255.0) (/ 235 255.0)])
(def ^:const cosmic-cobalt [(/ 46 255.0) (/ 45 255.0) (/ 136 255.0)])
(def ^:const cotton-candy [(/ 255 255.0) (/ 188 255.0) (/ 217 255.0)])
(def ^:const cultured-pearl [(/ 245 255.0) (/ 245 255.0) (/ 245 255.0)])
(def ^:const cyber-grape [(/ 88 255.0) (/ 66 255.0) (/ 124 255.0)])
(def ^:const daffodil [(/ 255 255.0) (/ 255 255.0) (/ 49 255.0)])
(def ^:const dandelion [(/ 253 255.0) (/ 219 255.0) (/ 109 255.0)])
(def ^:const deep-space-sparkle [(/ 74 255.0) (/ 100 255.0) (/ 108 255.0)])
(def ^:const denim [(/ 43 255.0) (/ 108 255.0) (/ 196 255.0)])
(def ^:const denim-blue [(/ 34 255.0) (/ 67 255.0) (/ 182 255.0)])
(def ^:const desert-sand [(/ 239 255.0) (/ 205 255.0) (/ 184 255.0)])
(def ^:const dingy-dungeon [(/ 197 255.0) (/ 49 255.0) (/ 81 255.0)])
(def ^:const dirt [(/ 155 255.0) (/ 118 255.0) (/ 83 255.0)])
(def ^:const eerie-black [(/ 27 255.0) (/ 27 255.0) (/ 27 255.0)])
(def ^:const eggplant [(/ 110 255.0) (/ 81 255.0) (/ 96 255.0)])
(def ^:const electric-lime [(/ 206 255.0) (/ 255 255.0) (/ 29 255.0)])
(def ^:const emerald [(/ 20 255.0) (/ 169 255.0) (/ 137 255.0)])
(def ^:const eucalyptus [(/ 68 255.0) (/ 215 255.0) (/ 168 255.0)])
(def ^:const fern [(/ 113 255.0) (/ 188 255.0) (/ 120 255.0)])
(def ^:const fiery-rose [(/ 255 255.0) (/ 84 255.0) (/ 112 255.0)])
(def ^:const forest-green [(/ 109 255.0) (/ 174 255.0) (/ 129 255.0)])
(def ^:const fresh-air [(/ 166 255.0) (/ 231 255.0) (/ 255 255.0)])
(def ^:const frostbite [(/ 233 255.0) (/ 54 255.0) (/ 167 255.0)])
(def ^:const fuchsia [(/ 195 255.0) (/ 100 255.0) (/ 197 255.0)])
(def ^:const fuzzy-wuzzy [(/ 204 255.0) (/ 102 255.0) (/ 102 255.0)])
(def ^:const gargoyle-gas [(/ 255 255.0) (/ 223 255.0) (/ 70 255.0)])
(def ^:const giants-club [(/ 176 255.0) (/ 92 255.0) (/ 82 255.0)])
(def ^:const glossy-grape [(/ 171 255.0) (/ 146 255.0) (/ 179 255.0)])
(def ^:const gold [(/ 231 255.0) (/ 198 255.0) (/ 151 255.0)])
(def ^:const gold-fusion [(/ 133 255.0) (/ 117 255.0) (/ 78 255.0)])
(def ^:const goldenrod [(/ 252 255.0) (/ 217 255.0) (/ 117 255.0)])
(def ^:const granite-gray [(/ 103 255.0) (/ 103 255.0) (/ 103 255.0)])
(def ^:const granny-smith-apple [(/ 168 255.0) (/ 228 255.0) (/ 160 255.0)])
(def ^:const grape [(/ 111 255.0) (/ 45 255.0) (/ 168 255.0)])
(def ^:const gray [(/ 149 255.0) (/ 145 255.0) (/ 140 255.0)])
(def ^:const green [(/ 28 255.0) (/ 172 255.0) (/ 120 255.0)])
(def ^:const green-blue [(/ 17 255.0) (/ 100 255.0) (/ 180 255.0)])
(def ^:const green-lizard [(/ 167 255.0) (/ 244 255.0) (/ 50 255.0)])
(def ^:const green-sheen [(/ 110 255.0) (/ 174 255.0) (/ 161 255.0)])
(def ^:const green-yellow [(/ 240 255.0) (/ 232 255.0) (/ 145 255.0)])
(def ^:const heat-wave [(/ 255 255.0) (/ 122 255.0) (/ 0 255.0)])
(def ^:const hot-magenta [(/ 255 255.0) (/ 29 255.0) (/ 206 255.0)])
(def ^:const illuminating-emerald [(/ 49 255.0) (/ 145 255.0) (/ 119 255.0)])
(def ^:const inchworm [(/ 178 255.0) (/ 236 255.0) (/ 93 255.0)])
(def ^:const indigo [(/ 93 255.0) (/ 118 255.0) (/ 203 255.0)])
(def ^:const jade [(/ 70 255.0) (/ 154 255.0) (/ 132 255.0)])
(def ^:const jasper [(/ 208 255.0) (/ 83 255.0) (/ 64 255.0)])
(def ^:const jazzberry-jam [(/ 202 255.0) (/ 55 255.0) (/ 103 255.0)])
(def ^:const jelly-bean [(/ 218 255.0) (/ 97 255.0) (/ 78 255.0)])
(def ^:const jungle-green [(/ 59 255.0) (/ 176 255.0) (/ 143 255.0)])
(def ^:const key-lime-pearl [(/ 232 255.0) (/ 244 255.0) (/ 140 255.0)])
(def ^:const lapis-lazuli [(/ 67 255.0) (/ 108 255.0) (/ 185 255.0)])
(def ^:const laser-lemon [(/ 254 255.0) (/ 254 255.0) (/ 34 255.0)])
(def ^:const lavender [(/ 252 255.0) (/ 180 255.0) (/ 213 255.0)])
(def ^:const leather-jacket [(/ 37 255.0) (/ 53 255.0) (/ 41 255.0)])
(def ^:const lemon [(/ 255 255.0) (/ 255 255.0) (/ 56 255.0)])
(def ^:const lemon-glacier [(/ 253 255.0) (/ 255 255.0) (/ 0 255.0)])
(def ^:const lemon-yellow [(/ 255 255.0) (/ 244 255.0) (/ 79 255.0)])
(def ^:const licorice [(/ 26 255.0) (/ 17 255.0) (/ 16 255.0)])
(def ^:const lilac [(/ 219 255.0) (/ 145 255.0) (/ 239 255.0)])
(def ^:const lilac-luster [(/ 174 255.0) (/ 152 255.0) (/ 170 255.0)])
(def ^:const lime [(/ 178 255.0) (/ 243 255.0) (/ 2 255.0)])
(def ^:const lumber [(/ 255 255.0) (/ 228 255.0) (/ 205 255.0)])
(def ^:const macaroni-and-cheese [(/ 255 255.0) (/ 189 255.0) (/ 136 255.0)])
(def ^:const magenta [(/ 246 255.0) (/ 100 255.0) (/ 175 255.0)])
(def ^:const magic-mint [(/ 170 255.0) (/ 240 255.0) (/ 209 255.0)])
(def ^:const magic-potion [(/ 255 255.0) (/ 68 255.0) (/ 102 255.0)])
(def ^:const mahogany [(/ 205 255.0) (/ 74 255.0) (/ 76 255.0)])
(def ^:const maize [(/ 237 255.0) (/ 209 255.0) (/ 156 255.0)])
(def ^:const malachite [(/ 70 255.0) (/ 148 255.0) (/ 150 255.0)])
(def ^:const manatee [(/ 151 255.0) (/ 154 255.0) (/ 170 255.0)])
(def ^:const mandarin-pearl [(/ 243 255.0) (/ 122 255.0) (/ 72 255.0)])
(def ^:const mango-tango [(/ 255 255.0) (/ 130 255.0) (/ 67 255.0)])
(def ^:const maroon [(/ 200 255.0) (/ 56 255.0) (/ 90 255.0)])
(def ^:const mauvelous [(/ 239 255.0) (/ 152 255.0) (/ 170 255.0)])
(def ^:const melon [(/ 253 255.0) (/ 188 255.0) (/ 180 255.0)])
(def ^:const metallic-seaweed [(/ 10 255.0) (/ 126 255.0) (/ 140 255.0)])
(def ^:const metallic-sunburst [(/ 156 255.0) (/ 124 255.0) (/ 56 255.0)])
(def ^:const midnight-blue [(/ 26 255.0) (/ 72 255.0) (/ 118 255.0)])
(def ^:const midnight-pearl [(/ 112 255.0) (/ 38 255.0) (/ 112 255.0)])
(def ^:const misty-moss [(/ 187 255.0) (/ 180 255.0) (/ 119 255.0)])
(def ^:const moonstone [(/ 58 255.0) (/ 168 255.0) (/ 193 255.0)])
(def ^:const mountain-meadow [(/ 48 255.0) (/ 186 255.0) (/ 143 255.0)])
(def ^:const mulberry [(/ 197 255.0) (/ 75 255.0) (/ 140 255.0)])
(def ^:const mummys-tomb [(/ 130 255.0) (/ 142 255.0) (/ 132 255.0)])
(def ^:const mystic-maroon [(/ 173 255.0) (/ 67 255.0) (/ 121 255.0)])
(def ^:const mystic-pearl [(/ 214 255.0) (/ 82 255.0) (/ 130 255.0)])
(def ^:const navy-blue [(/ 25 255.0) (/ 116 255.0) (/ 210 255.0)])
(def ^:const neon-carrot [(/ 255 255.0) (/ 163 255.0) (/ 67 255.0)])
(def ^:const new-car [(/ 33 255.0) (/ 79 255.0) (/ 198 255.0)])
(def ^:const ocean-blue-pearl [(/ 79 255.0) (/ 66 255.0) (/ 181 255.0)])
(def ^:const ocean-green-pearl [(/ 72 255.0) (/ 191 255.0) (/ 145 255.0)])
(def ^:const ogre-odor [(/ 253 255.0) (/ 82 255.0) (/ 64 255.0)])
(def ^:const olive-green [(/ 186 255.0) (/ 184 255.0) (/ 108 255.0)])
(def ^:const onyx [(/ 53 255.0) (/ 56 255.0) (/ 57 255.0)])
(def ^:const orange [(/ 255 255.0) (/ 117 255.0) (/ 56 255.0)])
(def ^:const orange [(/ 255 255.0) (/ 136 255.0) (/ 102 255.0)])
(def ^:const orange-red [(/ 255 255.0) (/ 43 255.0) (/ 43 255.0)])
(def ^:const orange-soda [(/ 250 255.0) (/ 91 255.0) (/ 61 255.0)])
(def ^:const orange-yellow [(/ 248 255.0) (/ 213 255.0) (/ 104 255.0)])
(def ^:const orchid [(/ 230 255.0) (/ 168 255.0) (/ 215 255.0)])
(def ^:const orchid-pearl [(/ 123 255.0) (/ 66 255.0) (/ 89 255.0)])
(def ^:const outer-space [(/ 65 255.0) (/ 74 255.0) (/ 76 255.0)])
(def ^:const outrageous-orange [(/ 255 255.0) (/ 110 255.0) (/ 74 255.0)])
(def ^:const pacific-blue [(/ 28 255.0) (/ 169 255.0) (/ 201 255.0)])
(def ^:const peach [(/ 255 255.0) (/ 207 255.0) (/ 171 255.0)])
(def ^:const peach [(/ 255 255.0) (/ 208 255.0) (/ 185 255.0)])
(def ^:const pearly-purple [(/ 183 255.0) (/ 104 255.0) (/ 162 255.0)])
(def ^:const peridot [(/ 171 255.0) (/ 173 255.0) (/ 72 255.0)])
(def ^:const periwinkle [(/ 197 255.0) (/ 208 255.0) (/ 230 255.0)])
(def ^:const piggy-pink [(/ 253 255.0) (/ 221 255.0) (/ 230 255.0)])
(def ^:const pine [(/ 69 255.0) (/ 162 255.0) (/ 125 255.0)])
(def ^:const pine-green [(/ 21 255.0) (/ 128 255.0) (/ 120 255.0)])
(def ^:const pink-flamingo [(/ 252 255.0) (/ 116 255.0) (/ 253 255.0)])
(def ^:const pink-pearl [(/ 176 255.0) (/ 112 255.0) (/ 128 255.0)])
(def ^:const pink-sherbet [(/ 247 255.0) (/ 143 255.0) (/ 167 255.0)])
(def ^:const pixie-powder [(/ 57 255.0) (/ 18 255.0) (/ 133 255.0)])
(def ^:const plum [(/ 142 255.0) (/ 69 255.0) (/ 133 255.0)])
(def ^:const plump-purple [(/ 89 255.0) (/ 70 255.0) (/ 178 255.0)])
(def ^:const polished-pine [(/ 93 255.0) (/ 164 255.0) (/ 147 255.0)])
(def ^:const princess-perfume [(/ 255 255.0) (/ 133 255.0) (/ 207 255.0)])
(def ^:const purple-heart [(/ 116 255.0) (/ 66 255.0) (/ 200 255.0)])
(def ^:const purple-mountains-majesty [(/ 157 255.0) (/ 129 255.0) (/ 186 255.0)])
(def ^:const purple-pizzazz [(/ 254 255.0) (/ 78 255.0) (/ 218 255.0)])
(def ^:const purple-plum [(/ 156 255.0) (/ 81 255.0) (/ 182 255.0)])
(def ^:const quick-silver [(/ 166 255.0) (/ 166 255.0) (/ 166 255.0)])
(def ^:const radical-red [(/ 255 255.0) (/ 73 255.0) (/ 108 255.0)])
(def ^:const raw-sienna [(/ 214 255.0) (/ 138 255.0) (/ 89 255.0)])
(def ^:const raw-umber [(/ 113 255.0) (/ 75 255.0) (/ 35 255.0)])
(def ^:const razzle-dazzle-rose [(/ 255 255.0) (/ 72 255.0) (/ 208 255.0)])
(def ^:const razzmatazz [(/ 227 255.0) (/ 37 255.0) (/ 107 255.0)])
(def ^:const razzmic-berry [(/ 141 255.0) (/ 78 255.0) (/ 133 255.0)])
(def ^:const red [(/ 238 255.0) (/ 32 255.0) (/ 77 255.0)])
(def ^:const red-orange [(/ 255 255.0) (/ 83 255.0) (/ 73 255.0)])
(def ^:const red-salsa [(/ 253 255.0) (/ 58 255.0) (/ 74 255.0)])
(def ^:const red-violet [(/ 192 255.0) (/ 68 255.0) (/ 143 255.0)])
(def ^:const robins-egg-blue [(/ 31 255.0) (/ 206 255.0) (/ 203 255.0)])
(def ^:const rose [(/ 255 255.0) (/ 80 255.0) (/ 80 255.0)])
(def ^:const rose-dust [(/ 158 255.0) (/ 94 255.0) (/ 111 255.0)])
(def ^:const rose-pearl [(/ 240 255.0) (/ 56 255.0) (/ 101 255.0)])
(def ^:const rose-quartz [(/ 189 255.0) (/ 85 255.0) (/ 156 255.0)])
(def ^:const royal-purple [(/ 120 255.0) (/ 81 255.0) (/ 169 255.0)])
(def ^:const ruby [(/ 170 255.0) (/ 64 255.0) (/ 105 255.0)])
(def ^:const rusty-red [(/ 218 255.0) (/ 44 255.0) (/ 67 255.0)])
(def ^:const salmon [(/ 255 255.0) (/ 155 255.0) (/ 170 255.0)])
(def ^:const salmon-pearl [(/ 241 255.0) (/ 68 255.0) (/ 74 255.0)])
(def ^:const sapphire [(/ 45 255.0) (/ 93 255.0) (/ 161 255.0)])
(def ^:const sasquatch-socks [(/ 255 255.0) (/ 70 255.0) (/ 129 255.0)])
(def ^:const scarlet [(/ 252 255.0) (/ 40 255.0) (/ 71 255.0)])
(def ^:const screamin-green [(/ 118 255.0) (/ 255 255.0) (/ 122 255.0)])
(def ^:const sea-green [(/ 159 255.0) (/ 226 255.0) (/ 191 255.0)])
(def ^:const sea-serpent [(/ 75 255.0) (/ 199 255.0) (/ 207 255.0)])
(def ^:const sepia [(/ 165 255.0) (/ 105 255.0) (/ 79 255.0)])
(def ^:const shadow [(/ 138 255.0) (/ 121 255.0) (/ 93 255.0)])
(def ^:const shadow-blue [(/ 119 255.0) (/ 139 255.0) (/ 165 255.0)])
(def ^:const shampoo [(/ 255 255.0) (/ 207 255.0) (/ 241 255.0)])
(def ^:const shamrock [(/ 69 255.0) (/ 206 255.0) (/ 162 255.0)])
(def ^:const sheen-green [(/ 143 255.0) (/ 212 255.0) (/ 0 255.0)])
(def ^:const shimmering-blush [(/ 217 255.0) (/ 134 255.0) (/ 149 255.0)])
(def ^:const shiny-shamrock [(/ 95 255.0) (/ 167 255.0) (/ 120 255.0)])
(def ^:const shocking-pink [(/ 251 255.0) (/ 126 255.0) (/ 253 255.0)])
(def ^:const silver [(/ 205 255.0) (/ 197 255.0) (/ 194 255.0)])
(def ^:const sizzling-red [(/ 255 255.0) (/ 56 255.0) (/ 85 255.0)])
(def ^:const sizzling-sunrise [(/ 255 255.0) (/ 219 255.0) (/ 0 255.0)])
(def ^:const sky-blue [(/ 128 255.0) (/ 218 255.0) (/ 235 255.0)])
(def ^:const slimy-green [(/ 41 255.0) (/ 150 255.0) (/ 23 255.0)])
(def ^:const smashed-pumpkin [(/ 255 255.0) (/ 109 255.0) (/ 58 255.0)])
(def ^:const smoke [(/ 115 255.0) (/ 130 255.0) (/ 118 255.0)])
(def ^:const smokey-topaz [(/ 131 255.0) (/ 42 255.0) (/ 13 255.0)])
(def ^:const soap [(/ 206 255.0) (/ 200 255.0) (/ 239 255.0)])
(def ^:const sonic-silver [(/ 117 255.0) (/ 117 255.0) (/ 117 255.0)])
(def ^:const sover-blue [(/ 139 255.0) (/ 168 255.0) (/ 183 255.0)])
(def ^:const spring-frost [(/ 135 255.0) (/ 255 255.0) (/ 42 255.0)])
(def ^:const spring-green [(/ 236 255.0) (/ 234 255.0) (/ 190 255.0)])
(def ^:const steel-blue [(/ 0 255.0) (/ 129 255.0) (/ 171 255.0)])
(def ^:const steel-teal [(/ 95 255.0) (/ 138 255.0) (/ 139 255.0)])
(def ^:const strawberry [(/ 252 255.0) (/ 90 255.0) (/ 141 255.0)])
(def ^:const sugar-plum [(/ 145 255.0) (/ 78 255.0) (/ 117 255.0)])
(def ^:const sunburnt-cyclops [(/ 255 255.0) (/ 64 255.0) (/ 76 255.0)])
(def ^:const sunglow [(/ 255 255.0) (/ 207 255.0) (/ 72 255.0)])
(def ^:const sunny-pearl [(/ 242 255.0) (/ 242 255.0) (/ 122 255.0)])
(def ^:const sunset-orange [(/ 253 255.0) (/ 94 255.0) (/ 83 255.0)])
(def ^:const sunset-pearl [(/ 241 255.0) (/ 204 255.0) (/ 121 255.0)])
(def ^:const sweet-brown [(/ 168 255.0) (/ 55 255.0) (/ 49 255.0)])
(def ^:const tan [(/ 250 255.0) (/ 167 255.0) (/ 108 255.0)])
(def ^:const tart-orange [(/ 251 255.0) (/ 77 255.0) (/ 70 255.0)])
(def ^:const teal-blue [(/ 24 255.0) (/ 167 255.0) (/ 181 255.0)])
(def ^:const thistle [(/ 235 255.0) (/ 199 255.0) (/ 223 255.0)])
(def ^:const tickle-me-pink [(/ 252 255.0) (/ 137 255.0) (/ 172 255.0)])
(def ^:const tigers-eye [(/ 181 255.0) (/ 105 255.0) (/ 23 255.0)])
(def ^:const timberwolf [(/ 219 255.0) (/ 215 255.0) (/ 210 255.0)])
(def ^:const tropical-rain-forest [(/ 23 255.0) (/ 128 255.0) (/ 109 255.0)])
(def ^:const tulip [(/ 255 255.0) (/ 135 255.0) (/ 141 255.0)])
(def ^:const tumbleweed [(/ 222 255.0) (/ 170 255.0) (/ 136 255.0)])
(def ^:const turquoise-blue [(/ 119 255.0) (/ 221 255.0) (/ 231 255.0)])
(def ^:const turquoise-pearl [(/ 59 255.0) (/ 188 255.0) (/ 208 255.0)])
(def ^:const twilight-lavender [(/ 138 255.0) (/ 73 255.0) (/ 107 255.0)])
(def ^:const unmellow-yellow [(/ 255 255.0) (/ 255 255.0) (/ 102 255.0)])
(def ^:const violet [(/ 146 255.0) (/ 110 255.0) (/ 174 255.0)])
(def ^:const violet-blue [(/ 50 255.0) (/ 74 255.0) (/ 178 255.0)])
(def ^:const violet-red [(/ 247 255.0) (/ 83 255.0) (/ 148 255.0)])
(def ^:const vivid-tangerine [(/ 255 255.0) (/ 160 255.0) (/ 137 255.0)])
(def ^:const vivid-violet [(/ 143 255.0) (/ 80 255.0) (/ 157 255.0)])
(def ^:const white [(/ 255 255.0) (/ 255 255.0) (/ 255 255.0)])
(def ^:const wild-blue-yonder [(/ 162 255.0) (/ 173 255.0) (/ 208 255.0)])
(def ^:const wild-strawberry [(/ 255 255.0) (/ 67 255.0) (/ 164 255.0)])
(def ^:const wild-watermelon [(/ 252 255.0) (/ 108 255.0) (/ 133 255.0)])
(def ^:const winter-sky [(/ 255 255.0) (/ 0 255.0) (/ 124 255.0)])
(def ^:const winter-wizard [(/ 160 255.0) (/ 230 255.0) (/ 255 255.0)])
(def ^:const wintergreen-dream [(/ 86 255.0) (/ 136 255.0) (/ 125 255.0)])
(def ^:const wisteria [(/ 205 255.0) (/ 164 255.0) (/ 222 255.0)])
(def ^:const yellow [(/ 252 255.0) (/ 232 255.0) (/ 131 255.0)])
(def ^:const yellow-green [(/ 197 255.0) (/ 227 255.0) (/ 132 255.0)])
(def ^:const yellow-orange [(/ 255 255.0) (/ 174 255.0) (/ 66 255.0)])
(def ^:const yellow-sunshine [(/ 255 255.0) (/ 247 255.0) (/ 0 255.0)])
| null | https://raw.githubusercontent.com/bakyeono/bitmap-font/2422bc748006f599ef4b42f5ce5cdfba9ff980e9/src/bitmap_font/color.clj | clojure | bitmap-font.color
자주 사용되는 색상을 정의 | (ns bitmap-font.color)
(def ^:const absolute-zero [(/ 0 255.0) (/ 72 255.0) (/ 186 255.0)])
(def ^:const alien-armpit [(/ 132 255.0) (/ 222 255.0) (/ 2 255.0)])
(def ^:const alloy-orange [(/ 196 255.0) (/ 98 255.0) (/ 16 255.0)])
(def ^:const almond [(/ 239 255.0) (/ 222 255.0) (/ 205 255.0)])
(def ^:const amethyst [(/ 100 255.0) (/ 96 255.0) (/ 154 255.0)])
(def ^:const antique-brass [(/ 205 255.0) (/ 149 255.0) (/ 117 255.0)])
(def ^:const apricot [(/ 253 255.0) (/ 217 255.0) (/ 181 255.0)])
(def ^:const aqua-pearl [(/ 95 255.0) (/ 190 255.0) (/ 215 255.0)])
(def ^:const aquamarine [(/ 120 255.0) (/ 219 255.0) (/ 226 255.0)])
(def ^:const asparagus [(/ 135 255.0) (/ 169 255.0) (/ 107 255.0)])
(def ^:const atomic-tangerine [(/ 255 255.0) (/ 164 255.0) (/ 116 255.0)])
(def ^:const aztec-gold [(/ 195 255.0) (/ 153 255.0) (/ 83 255.0)])
(def ^:const b-dazzled-blue [(/ 46 255.0) (/ 88 255.0) (/ 148 255.0)])
(def ^:const baby-powder [(/ 254 255.0) (/ 254 255.0) (/ 250 255.0)])
(def ^:const banana [(/ 255 255.0) (/ 209 255.0) (/ 42 255.0)])
(def ^:const banana-mania [(/ 250 255.0) (/ 231 255.0) (/ 181 255.0)])
(def ^:const beaver [(/ 159 255.0) (/ 129 255.0) (/ 112 255.0)])
(def ^:const big-dip-o-ruby [(/ 156 255.0) (/ 37 255.0) (/ 66 255.0)])
(def ^:const big-foot-feet [(/ 232 255.0) (/ 142 255.0) (/ 90 255.0)])
(def ^:const bittersweet [(/ 253 255.0) (/ 124 255.0) (/ 110 255.0)])
(def ^:const bittersweet-shimmer [(/ 191 255.0) (/ 79 255.0) (/ 81 255.0)])
(def ^:const black [(/ 0 255.0) (/ 0 255.0) (/ 0 255.0)])
(def ^:const black-coral-pearl [(/ 84 255.0) (/ 98 255.0) (/ 111 255.0)])
(def ^:const black-shadows [(/ 191 255.0) (/ 175 255.0) (/ 178 255.0)])
(def ^:const blast-off-bronze [(/ 165 255.0) (/ 113 255.0) (/ 100 255.0)])
(def ^:const blizzard-blue [(/ 172 255.0) (/ 229 255.0) (/ 238 255.0)])
(def ^:const blue [(/ 31 255.0) (/ 117 255.0) (/ 254 255.0)])
(def ^:const blue-bell [(/ 162 255.0) (/ 162 255.0) (/ 208 255.0)])
(def ^:const blue-gray [(/ 102 255.0) (/ 153 255.0) (/ 204 255.0)])
(def ^:const blue-green [(/ 13 255.0) (/ 152 255.0) (/ 186 255.0)])
(def ^:const blue-jeans [(/ 93 255.0) (/ 173 255.0) (/ 236 255.0)])
(def ^:const blue-violet [(/ 115 255.0) (/ 102 255.0) (/ 189 255.0)])
(def ^:const blueberry [(/ 79 255.0) (/ 134 255.0) (/ 247 255.0)])
(def ^:const blush [(/ 222 255.0) (/ 93 255.0) (/ 131 255.0)])
(def ^:const booger-buster [(/ 221 255.0) (/ 226 255.0) (/ 106 255.0)])
(def ^:const brick-red [(/ 203 255.0) (/ 65 255.0) (/ 84 255.0)])
(def ^:const bright-yellow [(/ 255 255.0) (/ 170 255.0) (/ 29 255.0)])
(def ^:const brown [(/ 180 255.0) (/ 103 255.0) (/ 77 255.0)])
(def ^:const brown-sugar [(/ 175 255.0) (/ 110 255.0) (/ 77 255.0)])
(def ^:const bubble-gum [(/ 255 255.0) (/ 211 255.0) (/ 248 255.0)])
(def ^:const burnished-brown [(/ 161 255.0) (/ 122 255.0) (/ 116 255.0)])
(def ^:const burnt-orange [(/ 255 255.0) (/ 127 255.0) (/ 73 255.0)])
(def ^:const burnt-sienna [(/ 234 255.0) (/ 126 255.0) (/ 93 255.0)])
(def ^:const cadet-blue [(/ 176 255.0) (/ 183 255.0) (/ 198 255.0)])
(def ^:const canary [(/ 255 255.0) (/ 255 255.0) (/ 153 255.0)])
(def ^:const caribbean-green [(/ 28 255.0) (/ 211 255.0) (/ 162 255.0)])
(def ^:const caribbean-green-pearl [(/ 106 255.0) (/ 218 255.0) (/ 142 255.0)])
(def ^:const carnation-pink [(/ 255 255.0) (/ 170 255.0) (/ 204 255.0)])
(def ^:const cedar-chest [(/ 201 255.0) (/ 90 255.0) (/ 73 255.0)])
(def ^:const cerise [(/ 221 255.0) (/ 68 255.0) (/ 146 255.0)])
(def ^:const cerulean [(/ 29 255.0) (/ 172 255.0) (/ 214 255.0)])
(def ^:const cerulean-frost [(/ 109 255.0) (/ 155 255.0) (/ 195 255.0)])
(def ^:const cherry [(/ 218 255.0) (/ 38 255.0) (/ 71 255.0)])
(def ^:const chestnut [(/ 188 255.0) (/ 93 255.0) (/ 88 255.0)])
(def ^:const chocolate [(/ 189 255.0) (/ 130 255.0) (/ 96 255.0)])
(def ^:const cinnamon-satin [(/ 205 255.0) (/ 96 255.0) (/ 126 255.0)])
(def ^:const citrine [(/ 147 255.0) (/ 55 255.0) (/ 9 255.0)])
(def ^:const coconut [(/ 254 255.0) (/ 254 255.0) (/ 254 255.0)])
(def ^:const copper [(/ 221 255.0) (/ 148 255.0) (/ 117 255.0)])
(def ^:const copper-penny [(/ 173 255.0) (/ 111 255.0) (/ 105 255.0)])
(def ^:const cornflower [(/ 154 255.0) (/ 206 255.0) (/ 235 255.0)])
(def ^:const cosmic-cobalt [(/ 46 255.0) (/ 45 255.0) (/ 136 255.0)])
(def ^:const cotton-candy [(/ 255 255.0) (/ 188 255.0) (/ 217 255.0)])
(def ^:const cultured-pearl [(/ 245 255.0) (/ 245 255.0) (/ 245 255.0)])
(def ^:const cyber-grape [(/ 88 255.0) (/ 66 255.0) (/ 124 255.0)])
(def ^:const daffodil [(/ 255 255.0) (/ 255 255.0) (/ 49 255.0)])
(def ^:const dandelion [(/ 253 255.0) (/ 219 255.0) (/ 109 255.0)])
(def ^:const deep-space-sparkle [(/ 74 255.0) (/ 100 255.0) (/ 108 255.0)])
(def ^:const denim [(/ 43 255.0) (/ 108 255.0) (/ 196 255.0)])
(def ^:const denim-blue [(/ 34 255.0) (/ 67 255.0) (/ 182 255.0)])
(def ^:const desert-sand [(/ 239 255.0) (/ 205 255.0) (/ 184 255.0)])
(def ^:const dingy-dungeon [(/ 197 255.0) (/ 49 255.0) (/ 81 255.0)])
(def ^:const dirt [(/ 155 255.0) (/ 118 255.0) (/ 83 255.0)])
(def ^:const eerie-black [(/ 27 255.0) (/ 27 255.0) (/ 27 255.0)])
(def ^:const eggplant [(/ 110 255.0) (/ 81 255.0) (/ 96 255.0)])
(def ^:const electric-lime [(/ 206 255.0) (/ 255 255.0) (/ 29 255.0)])
(def ^:const emerald [(/ 20 255.0) (/ 169 255.0) (/ 137 255.0)])
(def ^:const eucalyptus [(/ 68 255.0) (/ 215 255.0) (/ 168 255.0)])
(def ^:const fern [(/ 113 255.0) (/ 188 255.0) (/ 120 255.0)])
(def ^:const fiery-rose [(/ 255 255.0) (/ 84 255.0) (/ 112 255.0)])
(def ^:const forest-green [(/ 109 255.0) (/ 174 255.0) (/ 129 255.0)])
(def ^:const fresh-air [(/ 166 255.0) (/ 231 255.0) (/ 255 255.0)])
(def ^:const frostbite [(/ 233 255.0) (/ 54 255.0) (/ 167 255.0)])
(def ^:const fuchsia [(/ 195 255.0) (/ 100 255.0) (/ 197 255.0)])
(def ^:const fuzzy-wuzzy [(/ 204 255.0) (/ 102 255.0) (/ 102 255.0)])
(def ^:const gargoyle-gas [(/ 255 255.0) (/ 223 255.0) (/ 70 255.0)])
(def ^:const giants-club [(/ 176 255.0) (/ 92 255.0) (/ 82 255.0)])
(def ^:const glossy-grape [(/ 171 255.0) (/ 146 255.0) (/ 179 255.0)])
(def ^:const gold [(/ 231 255.0) (/ 198 255.0) (/ 151 255.0)])
(def ^:const gold-fusion [(/ 133 255.0) (/ 117 255.0) (/ 78 255.0)])
(def ^:const goldenrod [(/ 252 255.0) (/ 217 255.0) (/ 117 255.0)])
(def ^:const granite-gray [(/ 103 255.0) (/ 103 255.0) (/ 103 255.0)])
(def ^:const granny-smith-apple [(/ 168 255.0) (/ 228 255.0) (/ 160 255.0)])
(def ^:const grape [(/ 111 255.0) (/ 45 255.0) (/ 168 255.0)])
(def ^:const gray [(/ 149 255.0) (/ 145 255.0) (/ 140 255.0)])
(def ^:const green [(/ 28 255.0) (/ 172 255.0) (/ 120 255.0)])
(def ^:const green-blue [(/ 17 255.0) (/ 100 255.0) (/ 180 255.0)])
(def ^:const green-lizard [(/ 167 255.0) (/ 244 255.0) (/ 50 255.0)])
(def ^:const green-sheen [(/ 110 255.0) (/ 174 255.0) (/ 161 255.0)])
(def ^:const green-yellow [(/ 240 255.0) (/ 232 255.0) (/ 145 255.0)])
(def ^:const heat-wave [(/ 255 255.0) (/ 122 255.0) (/ 0 255.0)])
(def ^:const hot-magenta [(/ 255 255.0) (/ 29 255.0) (/ 206 255.0)])
(def ^:const illuminating-emerald [(/ 49 255.0) (/ 145 255.0) (/ 119 255.0)])
(def ^:const inchworm [(/ 178 255.0) (/ 236 255.0) (/ 93 255.0)])
(def ^:const indigo [(/ 93 255.0) (/ 118 255.0) (/ 203 255.0)])
(def ^:const jade [(/ 70 255.0) (/ 154 255.0) (/ 132 255.0)])
(def ^:const jasper [(/ 208 255.0) (/ 83 255.0) (/ 64 255.0)])
(def ^:const jazzberry-jam [(/ 202 255.0) (/ 55 255.0) (/ 103 255.0)])
(def ^:const jelly-bean [(/ 218 255.0) (/ 97 255.0) (/ 78 255.0)])
(def ^:const jungle-green [(/ 59 255.0) (/ 176 255.0) (/ 143 255.0)])
(def ^:const key-lime-pearl [(/ 232 255.0) (/ 244 255.0) (/ 140 255.0)])
(def ^:const lapis-lazuli [(/ 67 255.0) (/ 108 255.0) (/ 185 255.0)])
(def ^:const laser-lemon [(/ 254 255.0) (/ 254 255.0) (/ 34 255.0)])
(def ^:const lavender [(/ 252 255.0) (/ 180 255.0) (/ 213 255.0)])
(def ^:const leather-jacket [(/ 37 255.0) (/ 53 255.0) (/ 41 255.0)])
(def ^:const lemon [(/ 255 255.0) (/ 255 255.0) (/ 56 255.0)])
(def ^:const lemon-glacier [(/ 253 255.0) (/ 255 255.0) (/ 0 255.0)])
(def ^:const lemon-yellow [(/ 255 255.0) (/ 244 255.0) (/ 79 255.0)])
(def ^:const licorice [(/ 26 255.0) (/ 17 255.0) (/ 16 255.0)])
(def ^:const lilac [(/ 219 255.0) (/ 145 255.0) (/ 239 255.0)])
(def ^:const lilac-luster [(/ 174 255.0) (/ 152 255.0) (/ 170 255.0)])
(def ^:const lime [(/ 178 255.0) (/ 243 255.0) (/ 2 255.0)])
(def ^:const lumber [(/ 255 255.0) (/ 228 255.0) (/ 205 255.0)])
(def ^:const macaroni-and-cheese [(/ 255 255.0) (/ 189 255.0) (/ 136 255.0)])
(def ^:const magenta [(/ 246 255.0) (/ 100 255.0) (/ 175 255.0)])
(def ^:const magic-mint [(/ 170 255.0) (/ 240 255.0) (/ 209 255.0)])
(def ^:const magic-potion [(/ 255 255.0) (/ 68 255.0) (/ 102 255.0)])
(def ^:const mahogany [(/ 205 255.0) (/ 74 255.0) (/ 76 255.0)])
(def ^:const maize [(/ 237 255.0) (/ 209 255.0) (/ 156 255.0)])
(def ^:const malachite [(/ 70 255.0) (/ 148 255.0) (/ 150 255.0)])
(def ^:const manatee [(/ 151 255.0) (/ 154 255.0) (/ 170 255.0)])
(def ^:const mandarin-pearl [(/ 243 255.0) (/ 122 255.0) (/ 72 255.0)])
(def ^:const mango-tango [(/ 255 255.0) (/ 130 255.0) (/ 67 255.0)])
(def ^:const maroon [(/ 200 255.0) (/ 56 255.0) (/ 90 255.0)])
(def ^:const mauvelous [(/ 239 255.0) (/ 152 255.0) (/ 170 255.0)])
(def ^:const melon [(/ 253 255.0) (/ 188 255.0) (/ 180 255.0)])
(def ^:const metallic-seaweed [(/ 10 255.0) (/ 126 255.0) (/ 140 255.0)])
(def ^:const metallic-sunburst [(/ 156 255.0) (/ 124 255.0) (/ 56 255.0)])
(def ^:const midnight-blue [(/ 26 255.0) (/ 72 255.0) (/ 118 255.0)])
(def ^:const midnight-pearl [(/ 112 255.0) (/ 38 255.0) (/ 112 255.0)])
(def ^:const misty-moss [(/ 187 255.0) (/ 180 255.0) (/ 119 255.0)])
(def ^:const moonstone [(/ 58 255.0) (/ 168 255.0) (/ 193 255.0)])
(def ^:const mountain-meadow [(/ 48 255.0) (/ 186 255.0) (/ 143 255.0)])
(def ^:const mulberry [(/ 197 255.0) (/ 75 255.0) (/ 140 255.0)])
(def ^:const mummys-tomb [(/ 130 255.0) (/ 142 255.0) (/ 132 255.0)])
(def ^:const mystic-maroon [(/ 173 255.0) (/ 67 255.0) (/ 121 255.0)])
(def ^:const mystic-pearl [(/ 214 255.0) (/ 82 255.0) (/ 130 255.0)])
(def ^:const navy-blue [(/ 25 255.0) (/ 116 255.0) (/ 210 255.0)])
(def ^:const neon-carrot [(/ 255 255.0) (/ 163 255.0) (/ 67 255.0)])
(def ^:const new-car [(/ 33 255.0) (/ 79 255.0) (/ 198 255.0)])
(def ^:const ocean-blue-pearl [(/ 79 255.0) (/ 66 255.0) (/ 181 255.0)])
(def ^:const ocean-green-pearl [(/ 72 255.0) (/ 191 255.0) (/ 145 255.0)])
(def ^:const ogre-odor [(/ 253 255.0) (/ 82 255.0) (/ 64 255.0)])
(def ^:const olive-green [(/ 186 255.0) (/ 184 255.0) (/ 108 255.0)])
(def ^:const onyx [(/ 53 255.0) (/ 56 255.0) (/ 57 255.0)])
(def ^:const orange [(/ 255 255.0) (/ 117 255.0) (/ 56 255.0)])
(def ^:const orange [(/ 255 255.0) (/ 136 255.0) (/ 102 255.0)])
(def ^:const orange-red [(/ 255 255.0) (/ 43 255.0) (/ 43 255.0)])
(def ^:const orange-soda [(/ 250 255.0) (/ 91 255.0) (/ 61 255.0)])
(def ^:const orange-yellow [(/ 248 255.0) (/ 213 255.0) (/ 104 255.0)])
(def ^:const orchid [(/ 230 255.0) (/ 168 255.0) (/ 215 255.0)])
(def ^:const orchid-pearl [(/ 123 255.0) (/ 66 255.0) (/ 89 255.0)])
(def ^:const outer-space [(/ 65 255.0) (/ 74 255.0) (/ 76 255.0)])
(def ^:const outrageous-orange [(/ 255 255.0) (/ 110 255.0) (/ 74 255.0)])
(def ^:const pacific-blue [(/ 28 255.0) (/ 169 255.0) (/ 201 255.0)])
(def ^:const peach [(/ 255 255.0) (/ 207 255.0) (/ 171 255.0)])
(def ^:const peach [(/ 255 255.0) (/ 208 255.0) (/ 185 255.0)])
(def ^:const pearly-purple [(/ 183 255.0) (/ 104 255.0) (/ 162 255.0)])
(def ^:const peridot [(/ 171 255.0) (/ 173 255.0) (/ 72 255.0)])
(def ^:const periwinkle [(/ 197 255.0) (/ 208 255.0) (/ 230 255.0)])
(def ^:const piggy-pink [(/ 253 255.0) (/ 221 255.0) (/ 230 255.0)])
(def ^:const pine [(/ 69 255.0) (/ 162 255.0) (/ 125 255.0)])
(def ^:const pine-green [(/ 21 255.0) (/ 128 255.0) (/ 120 255.0)])
(def ^:const pink-flamingo [(/ 252 255.0) (/ 116 255.0) (/ 253 255.0)])
(def ^:const pink-pearl [(/ 176 255.0) (/ 112 255.0) (/ 128 255.0)])
(def ^:const pink-sherbet [(/ 247 255.0) (/ 143 255.0) (/ 167 255.0)])
(def ^:const pixie-powder [(/ 57 255.0) (/ 18 255.0) (/ 133 255.0)])
(def ^:const plum [(/ 142 255.0) (/ 69 255.0) (/ 133 255.0)])
(def ^:const plump-purple [(/ 89 255.0) (/ 70 255.0) (/ 178 255.0)])
(def ^:const polished-pine [(/ 93 255.0) (/ 164 255.0) (/ 147 255.0)])
(def ^:const princess-perfume [(/ 255 255.0) (/ 133 255.0) (/ 207 255.0)])
(def ^:const purple-heart [(/ 116 255.0) (/ 66 255.0) (/ 200 255.0)])
(def ^:const purple-mountains-majesty [(/ 157 255.0) (/ 129 255.0) (/ 186 255.0)])
(def ^:const purple-pizzazz [(/ 254 255.0) (/ 78 255.0) (/ 218 255.0)])
(def ^:const purple-plum [(/ 156 255.0) (/ 81 255.0) (/ 182 255.0)])
(def ^:const quick-silver [(/ 166 255.0) (/ 166 255.0) (/ 166 255.0)])
(def ^:const radical-red [(/ 255 255.0) (/ 73 255.0) (/ 108 255.0)])
(def ^:const raw-sienna [(/ 214 255.0) (/ 138 255.0) (/ 89 255.0)])
(def ^:const raw-umber [(/ 113 255.0) (/ 75 255.0) (/ 35 255.0)])
(def ^:const razzle-dazzle-rose [(/ 255 255.0) (/ 72 255.0) (/ 208 255.0)])
(def ^:const razzmatazz [(/ 227 255.0) (/ 37 255.0) (/ 107 255.0)])
(def ^:const razzmic-berry [(/ 141 255.0) (/ 78 255.0) (/ 133 255.0)])
(def ^:const red [(/ 238 255.0) (/ 32 255.0) (/ 77 255.0)])
(def ^:const red-orange [(/ 255 255.0) (/ 83 255.0) (/ 73 255.0)])
(def ^:const red-salsa [(/ 253 255.0) (/ 58 255.0) (/ 74 255.0)])
(def ^:const red-violet [(/ 192 255.0) (/ 68 255.0) (/ 143 255.0)])
(def ^:const robins-egg-blue [(/ 31 255.0) (/ 206 255.0) (/ 203 255.0)])
(def ^:const rose [(/ 255 255.0) (/ 80 255.0) (/ 80 255.0)])
(def ^:const rose-dust [(/ 158 255.0) (/ 94 255.0) (/ 111 255.0)])
(def ^:const rose-pearl [(/ 240 255.0) (/ 56 255.0) (/ 101 255.0)])
(def ^:const rose-quartz [(/ 189 255.0) (/ 85 255.0) (/ 156 255.0)])
(def ^:const royal-purple [(/ 120 255.0) (/ 81 255.0) (/ 169 255.0)])
(def ^:const ruby [(/ 170 255.0) (/ 64 255.0) (/ 105 255.0)])
(def ^:const rusty-red [(/ 218 255.0) (/ 44 255.0) (/ 67 255.0)])
(def ^:const salmon [(/ 255 255.0) (/ 155 255.0) (/ 170 255.0)])
(def ^:const salmon-pearl [(/ 241 255.0) (/ 68 255.0) (/ 74 255.0)])
(def ^:const sapphire [(/ 45 255.0) (/ 93 255.0) (/ 161 255.0)])
(def ^:const sasquatch-socks [(/ 255 255.0) (/ 70 255.0) (/ 129 255.0)])
(def ^:const scarlet [(/ 252 255.0) (/ 40 255.0) (/ 71 255.0)])
(def ^:const screamin-green [(/ 118 255.0) (/ 255 255.0) (/ 122 255.0)])
(def ^:const sea-green [(/ 159 255.0) (/ 226 255.0) (/ 191 255.0)])
(def ^:const sea-serpent [(/ 75 255.0) (/ 199 255.0) (/ 207 255.0)])
(def ^:const sepia [(/ 165 255.0) (/ 105 255.0) (/ 79 255.0)])
(def ^:const shadow [(/ 138 255.0) (/ 121 255.0) (/ 93 255.0)])
(def ^:const shadow-blue [(/ 119 255.0) (/ 139 255.0) (/ 165 255.0)])
(def ^:const shampoo [(/ 255 255.0) (/ 207 255.0) (/ 241 255.0)])
(def ^:const shamrock [(/ 69 255.0) (/ 206 255.0) (/ 162 255.0)])
(def ^:const sheen-green [(/ 143 255.0) (/ 212 255.0) (/ 0 255.0)])
(def ^:const shimmering-blush [(/ 217 255.0) (/ 134 255.0) (/ 149 255.0)])
(def ^:const shiny-shamrock [(/ 95 255.0) (/ 167 255.0) (/ 120 255.0)])
(def ^:const shocking-pink [(/ 251 255.0) (/ 126 255.0) (/ 253 255.0)])
(def ^:const silver [(/ 205 255.0) (/ 197 255.0) (/ 194 255.0)])
(def ^:const sizzling-red [(/ 255 255.0) (/ 56 255.0) (/ 85 255.0)])
(def ^:const sizzling-sunrise [(/ 255 255.0) (/ 219 255.0) (/ 0 255.0)])
(def ^:const sky-blue [(/ 128 255.0) (/ 218 255.0) (/ 235 255.0)])
(def ^:const slimy-green [(/ 41 255.0) (/ 150 255.0) (/ 23 255.0)])
(def ^:const smashed-pumpkin [(/ 255 255.0) (/ 109 255.0) (/ 58 255.0)])
(def ^:const smoke [(/ 115 255.0) (/ 130 255.0) (/ 118 255.0)])
(def ^:const smokey-topaz [(/ 131 255.0) (/ 42 255.0) (/ 13 255.0)])
(def ^:const soap [(/ 206 255.0) (/ 200 255.0) (/ 239 255.0)])
(def ^:const sonic-silver [(/ 117 255.0) (/ 117 255.0) (/ 117 255.0)])
(def ^:const sover-blue [(/ 139 255.0) (/ 168 255.0) (/ 183 255.0)])
(def ^:const spring-frost [(/ 135 255.0) (/ 255 255.0) (/ 42 255.0)])
(def ^:const spring-green [(/ 236 255.0) (/ 234 255.0) (/ 190 255.0)])
(def ^:const steel-blue [(/ 0 255.0) (/ 129 255.0) (/ 171 255.0)])
(def ^:const steel-teal [(/ 95 255.0) (/ 138 255.0) (/ 139 255.0)])
(def ^:const strawberry [(/ 252 255.0) (/ 90 255.0) (/ 141 255.0)])
(def ^:const sugar-plum [(/ 145 255.0) (/ 78 255.0) (/ 117 255.0)])
(def ^:const sunburnt-cyclops [(/ 255 255.0) (/ 64 255.0) (/ 76 255.0)])
(def ^:const sunglow [(/ 255 255.0) (/ 207 255.0) (/ 72 255.0)])
(def ^:const sunny-pearl [(/ 242 255.0) (/ 242 255.0) (/ 122 255.0)])
(def ^:const sunset-orange [(/ 253 255.0) (/ 94 255.0) (/ 83 255.0)])
(def ^:const sunset-pearl [(/ 241 255.0) (/ 204 255.0) (/ 121 255.0)])
(def ^:const sweet-brown [(/ 168 255.0) (/ 55 255.0) (/ 49 255.0)])
(def ^:const tan [(/ 250 255.0) (/ 167 255.0) (/ 108 255.0)])
(def ^:const tart-orange [(/ 251 255.0) (/ 77 255.0) (/ 70 255.0)])
(def ^:const teal-blue [(/ 24 255.0) (/ 167 255.0) (/ 181 255.0)])
(def ^:const thistle [(/ 235 255.0) (/ 199 255.0) (/ 223 255.0)])
(def ^:const tickle-me-pink [(/ 252 255.0) (/ 137 255.0) (/ 172 255.0)])
(def ^:const tigers-eye [(/ 181 255.0) (/ 105 255.0) (/ 23 255.0)])
(def ^:const timberwolf [(/ 219 255.0) (/ 215 255.0) (/ 210 255.0)])
(def ^:const tropical-rain-forest [(/ 23 255.0) (/ 128 255.0) (/ 109 255.0)])
(def ^:const tulip [(/ 255 255.0) (/ 135 255.0) (/ 141 255.0)])
(def ^:const tumbleweed [(/ 222 255.0) (/ 170 255.0) (/ 136 255.0)])
(def ^:const turquoise-blue [(/ 119 255.0) (/ 221 255.0) (/ 231 255.0)])
(def ^:const turquoise-pearl [(/ 59 255.0) (/ 188 255.0) (/ 208 255.0)])
(def ^:const twilight-lavender [(/ 138 255.0) (/ 73 255.0) (/ 107 255.0)])
(def ^:const unmellow-yellow [(/ 255 255.0) (/ 255 255.0) (/ 102 255.0)])
(def ^:const violet [(/ 146 255.0) (/ 110 255.0) (/ 174 255.0)])
(def ^:const violet-blue [(/ 50 255.0) (/ 74 255.0) (/ 178 255.0)])
(def ^:const violet-red [(/ 247 255.0) (/ 83 255.0) (/ 148 255.0)])
(def ^:const vivid-tangerine [(/ 255 255.0) (/ 160 255.0) (/ 137 255.0)])
(def ^:const vivid-violet [(/ 143 255.0) (/ 80 255.0) (/ 157 255.0)])
(def ^:const white [(/ 255 255.0) (/ 255 255.0) (/ 255 255.0)])
(def ^:const wild-blue-yonder [(/ 162 255.0) (/ 173 255.0) (/ 208 255.0)])
(def ^:const wild-strawberry [(/ 255 255.0) (/ 67 255.0) (/ 164 255.0)])
(def ^:const wild-watermelon [(/ 252 255.0) (/ 108 255.0) (/ 133 255.0)])
(def ^:const winter-sky [(/ 255 255.0) (/ 0 255.0) (/ 124 255.0)])
(def ^:const winter-wizard [(/ 160 255.0) (/ 230 255.0) (/ 255 255.0)])
(def ^:const wintergreen-dream [(/ 86 255.0) (/ 136 255.0) (/ 125 255.0)])
(def ^:const wisteria [(/ 205 255.0) (/ 164 255.0) (/ 222 255.0)])
(def ^:const yellow [(/ 252 255.0) (/ 232 255.0) (/ 131 255.0)])
(def ^:const yellow-green [(/ 197 255.0) (/ 227 255.0) (/ 132 255.0)])
(def ^:const yellow-orange [(/ 255 255.0) (/ 174 255.0) (/ 66 255.0)])
(def ^:const yellow-sunshine [(/ 255 255.0) (/ 247 255.0) (/ 0 255.0)])
|
57f1a829d8c70189e98bc85a0fd7c8642441bcabc1d89e47ca5035d481c5e52c | emina/rosette | polymorphic.rkt | #lang racket
(require "term.rkt" "union.rkt" "bool.rkt")
(provide
ite ite* ⊢ guarded guarded-test guarded-value =?
generic-merge generic-merge*
T*->T T*->boolean?
sort/expression
simplify*)
; A generic typing procedure for a lifted operator that takes N > 0 arguments of type T
and returns a value of type T. Specifically , it assumes that at least one value passed
to it is typed , and it returns the type T of the first given typed value . See term.rkt .
(define T*->T
(case-lambda
[(x) (get-type x)]
[(x y) (or (and (typed? x) (get-type x)) (get-type y))]
[xs (for/first ([x xs] #:when (typed? x)) (get-type x))]))
; Polymorphic operators and procedures that are shared by
; multiple primitive types.
(define-operator =?
#:identifier '=?
#:range T*->boolean?
#:unsafe (lambda (x y)
(match* (x y)
[((not (? term?)) (not (? term?))) (eq? x y)]
[((not (? term?)) (? term?)) (expression =? x y)]
[((? term?) (not (? term?))) (expression =? y x)]
[((? term?) (? term?)) (or (equal? x y)
(if (term<? x y)
(expression =? x y)
(expression =? y x)))])))
A generic ite operator that takes a boolean condition and
two values v1 and v2 . The values v1 and vn must be of the same
; primitive type T. That is, (type-of v1 v2) = T for some pritimive
; type T. This operator is intended only for internal use and should not
; be called by client code.
(define-operator ite
#:identifier 'ite
#:range (lambda (b t f) (type-of t f))
#:unsafe (lambda (b t f)
(match* (b t f)
[((? boolean?) _ _) (if b t f)]
[(_ _ (== t)) t]
[(_ (expression (== ite) (== b) x _) _) (ite b x f)]
[(_ (expression (== ite) (== (! b)) _ y) _) (ite b y f)]
[(_ _ (expression (== ite) (== b) _ y)) (ite b t y)]
[(_ _ (expression (== ite) (== (! b)) x _)) (ite b t x)]
[(_ _ _) (expression ite b t f)])))
; A generic operator that takes a boolean condition and a value, and it evaluates
; to that value if the condition is true. Otherwise, its output is undefined.
(define (make-guarded g v) (expression ⊢ g v))
(define-operator ⊢
#:identifier '⊢
#:range (lambda (g v) (type-of v))
#:unsafe make-guarded)
(define-match-expander guarded
(lambda (stx)
(syntax-case stx ()
[(_ g-pat v-pat) #'(expression (== ⊢) g-pat v-pat)]))
(syntax-id-rules ()
[(_ g v) (make-guarded g v)]
[_ make-guarded]))
(define (guarded-test gv)
(match gv [(expression (== ⊢) g _) g]))
(define (guarded-value gv)
(match gv [(expression (== ⊢) _ v) v]))
A generic ite * operator that takes one or more guard - value pairs ,
; (g1 . v1) ... (gn . vn), and merges them into a single value
; of the form (ite* (guarded g1 v1) ...(guarded g1 v1)). All guards must be
; symbolic @boolean? terms. All values v1 ... vn must be of the same
; primitive type T. That is, (type-of v1 ... vn) = T for some pritimive
; type T. This operator is intended only for internal use and should not
; be called by client code. The operator simply sorts its arguments by
; guard and wraps the resulting list into an expression with ite* as the
; operator.
(define-operator ite*
#:identifier 'ite*
#:range (lambda gvs (apply type-of gvs))
#:unsafe (lambda gvs
(match gvs
[(list (cons _ a)) a]
[(list (cons a b) (cons (expression (== @!) a) c)) (ite a b c)]
[(list (cons (expression (== @!) a) c) (cons a b)) (ite a b c)]
[(list (app simplify-ite (cons a b)) (app simplify-ite (cons c d)))
(cond [(equal? b d) b]
[(term<? a c) (expression ite* (guarded a b) (guarded c d))]
[else (expression ite* (guarded c d) (guarded a b) )])]
[(list (app simplify-ite (cons a b)) (app simplify-ite cs) ...)
(cond [(for/and ([c cs]) (equal? b (cdr c))) b]
[else (apply
expression
ite*
(sort (cons (guarded a b) (for/list ([c cs]) (guarded (car c) (cdr c))))
term<?
#:key guarded-test))])])))
; A generic eager merging procedure that takes a list of guard-value pairs,
; ps = '((g1 . v1) ... (gn . vn)), and merges them into a single value
; of the form (ite* (guarded g1 v1) ... (guarded g1 v1)). All guards must be
; symbolic @boolean? terms. All values v1 ... vn must be of the same
type T. That is , ( type - of v1 ... vn ∅ ) = T for some primitive type T.
(define (generic-merge* ps)
(match ps
[(list _) ps]
[(list (cons a _) (cons b _)) (list (cons (|| a b) (apply ite* ps)))]
[(list (cons a _) ...) (list (cons (apply || a) (apply ite* ps)))]))
; A generic eager merging procedure that takes a list of guard-value pairs,
; ps = '((g1 . v1) ... (gn . vn)), and merges them into a single value
of the form ( ⊕ ( ite g1 v1 ∅ ) ... ( ) ) . All guards must be
; symbolic @boolean? terms. All values v1 ... vn must be of the same
; type T, which is also the type of the empty value ∅. That is,
; (type-of v1 ... vn ∅) = T. The procedure ⊕ must be an op? with the
; signature (op/-> (#:rest T) T).
(define (generic-merge ⊕ ∅ ps)
(match ps
[(list _) ps]
[(list (cons g a) (cons (expression (== @!) g) b)) (list (cons #t (ite g a b)))]
[(list (cons (expression (== @!) g) b) (cons g a)) (list (cons #t (ite g a b)))]
[(or (list (cons (expression (== @&&) g h) x) (cons (expression (== @&&) g f) y))
(list (cons (expression (== @&&) g h) x) (cons (expression (== @&&) f g) y))
(list (cons (expression (== @&&) h g) x) (cons (expression (== @&&) g f) y))
(list (cons (expression (== @&&) h g) x) (cons (expression (== @&&) f g) y)))
(list (cons g (match* (h f)
[(_ (expression (== @!) h)) (ite h x y)]
[((expression (== @!) f) _) (ite f y x)]
[(_ _) (⊕ (ite h x ∅) (ite f y ∅))])))]
[(list (app simplify-ite (cons g x)) (app simplify-ite (cons h y)))
(list (cons (|| g h) (if (equal? x y) x (⊕ (ite g x ∅) (ite h y ∅)))))]
[(list (app simplify-ite (cons a x)) (app simplify-ite (cons b y)) ...)
(list (cons (apply || a b)
(if (for/and ([z y]) (equal? x z))
x
(apply ⊕ (ite a x ∅) (map (curryr ite ∅) b y)))))]))
(define (simplify-ite p)
(match* ((car p) (cdr p))
[(a (expression (== ite) a x _)) (cons a x)]
[(a (expression (== ite) (expression (== @!) a) _ x)) (cons a x)]
[((and (expression (== @!) a) !a) (expression (== ite) a _ x)) (cons !a x)]
[(_ _) p]))
; Sorts the arguments to the given binary operator and returns the resulting expression.
(define (sort/expression @op x y)
(cond [(not (term? x)) (expression @op x y)]
[(not (term? y)) (expression @op y x)]
[(term<? x y) (expression @op x y)]
[else (expression @op y x)]))
; Applies the given simplification function to the given list until
; no more simplifications can be made. The simplification function should
take as input 2 values and return either # f ( if no simplification is possible )
; or the simplified result of applying f to those values. The optional limit
; value determines when the list is too big for simplification---in which case,
simplify * acts as the identity function on xs . The limit is 100 by default .
(define (simplify* xs f [limit 100])
(if (> (length xs) limit)
xs
(let ([out (let outer ([xs xs])
(match xs
[(list x rest ..1)
(let inner ([head rest] [tail '()])
(match head
[(list) (cons x (outer tail))]
[(list y ys ...)
(match (f x y)
[#f (inner ys (cons y tail))]
[v (outer (cons v (append ys tail)))])]))]
[_ xs]))])
(if (= (length out) (length xs)) out (simplify* out f)))))
| null | https://raw.githubusercontent.com/emina/rosette/9d14d447d01013ddffde182cbe82dd79fecdc398/rosette/base/core/polymorphic.rkt | racket | A generic typing procedure for a lifted operator that takes N > 0 arguments of type T
Polymorphic operators and procedures that are shared by
multiple primitive types.
primitive type T. That is, (type-of v1 v2) = T for some pritimive
type T. This operator is intended only for internal use and should not
be called by client code.
A generic operator that takes a boolean condition and a value, and it evaluates
to that value if the condition is true. Otherwise, its output is undefined.
(g1 . v1) ... (gn . vn), and merges them into a single value
of the form (ite* (guarded g1 v1) ...(guarded g1 v1)). All guards must be
symbolic @boolean? terms. All values v1 ... vn must be of the same
primitive type T. That is, (type-of v1 ... vn) = T for some pritimive
type T. This operator is intended only for internal use and should not
be called by client code. The operator simply sorts its arguments by
guard and wraps the resulting list into an expression with ite* as the
operator.
A generic eager merging procedure that takes a list of guard-value pairs,
ps = '((g1 . v1) ... (gn . vn)), and merges them into a single value
of the form (ite* (guarded g1 v1) ... (guarded g1 v1)). All guards must be
symbolic @boolean? terms. All values v1 ... vn must be of the same
A generic eager merging procedure that takes a list of guard-value pairs,
ps = '((g1 . v1) ... (gn . vn)), and merges them into a single value
symbolic @boolean? terms. All values v1 ... vn must be of the same
type T, which is also the type of the empty value ∅. That is,
(type-of v1 ... vn ∅) = T. The procedure ⊕ must be an op? with the
signature (op/-> (#:rest T) T).
Sorts the arguments to the given binary operator and returns the resulting expression.
Applies the given simplification function to the given list until
no more simplifications can be made. The simplification function should
or the simplified result of applying f to those values. The optional limit
value determines when the list is too big for simplification---in which case, | #lang racket
(require "term.rkt" "union.rkt" "bool.rkt")
(provide
ite ite* ⊢ guarded guarded-test guarded-value =?
generic-merge generic-merge*
T*->T T*->boolean?
sort/expression
simplify*)
and returns a value of type T. Specifically , it assumes that at least one value passed
to it is typed , and it returns the type T of the first given typed value . See term.rkt .
(define T*->T
(case-lambda
[(x) (get-type x)]
[(x y) (or (and (typed? x) (get-type x)) (get-type y))]
[xs (for/first ([x xs] #:when (typed? x)) (get-type x))]))
(define-operator =?
#:identifier '=?
#:range T*->boolean?
#:unsafe (lambda (x y)
(match* (x y)
[((not (? term?)) (not (? term?))) (eq? x y)]
[((not (? term?)) (? term?)) (expression =? x y)]
[((? term?) (not (? term?))) (expression =? y x)]
[((? term?) (? term?)) (or (equal? x y)
(if (term<? x y)
(expression =? x y)
(expression =? y x)))])))
A generic ite operator that takes a boolean condition and
two values v1 and v2 . The values v1 and vn must be of the same
(define-operator ite
#:identifier 'ite
#:range (lambda (b t f) (type-of t f))
#:unsafe (lambda (b t f)
(match* (b t f)
[((? boolean?) _ _) (if b t f)]
[(_ _ (== t)) t]
[(_ (expression (== ite) (== b) x _) _) (ite b x f)]
[(_ (expression (== ite) (== (! b)) _ y) _) (ite b y f)]
[(_ _ (expression (== ite) (== b) _ y)) (ite b t y)]
[(_ _ (expression (== ite) (== (! b)) x _)) (ite b t x)]
[(_ _ _) (expression ite b t f)])))
(define (make-guarded g v) (expression ⊢ g v))
(define-operator ⊢
#:identifier '⊢
#:range (lambda (g v) (type-of v))
#:unsafe make-guarded)
(define-match-expander guarded
(lambda (stx)
(syntax-case stx ()
[(_ g-pat v-pat) #'(expression (== ⊢) g-pat v-pat)]))
(syntax-id-rules ()
[(_ g v) (make-guarded g v)]
[_ make-guarded]))
(define (guarded-test gv)
(match gv [(expression (== ⊢) g _) g]))
(define (guarded-value gv)
(match gv [(expression (== ⊢) _ v) v]))
A generic ite * operator that takes one or more guard - value pairs ,
(define-operator ite*
#:identifier 'ite*
#:range (lambda gvs (apply type-of gvs))
#:unsafe (lambda gvs
(match gvs
[(list (cons _ a)) a]
[(list (cons a b) (cons (expression (== @!) a) c)) (ite a b c)]
[(list (cons (expression (== @!) a) c) (cons a b)) (ite a b c)]
[(list (app simplify-ite (cons a b)) (app simplify-ite (cons c d)))
(cond [(equal? b d) b]
[(term<? a c) (expression ite* (guarded a b) (guarded c d))]
[else (expression ite* (guarded c d) (guarded a b) )])]
[(list (app simplify-ite (cons a b)) (app simplify-ite cs) ...)
(cond [(for/and ([c cs]) (equal? b (cdr c))) b]
[else (apply
expression
ite*
(sort (cons (guarded a b) (for/list ([c cs]) (guarded (car c) (cdr c))))
term<?
#:key guarded-test))])])))
type T. That is , ( type - of v1 ... vn ∅ ) = T for some primitive type T.
(define (generic-merge* ps)
(match ps
[(list _) ps]
[(list (cons a _) (cons b _)) (list (cons (|| a b) (apply ite* ps)))]
[(list (cons a _) ...) (list (cons (apply || a) (apply ite* ps)))]))
of the form ( ⊕ ( ite g1 v1 ∅ ) ... ( ) ) . All guards must be
(define (generic-merge ⊕ ∅ ps)
(match ps
[(list _) ps]
[(list (cons g a) (cons (expression (== @!) g) b)) (list (cons #t (ite g a b)))]
[(list (cons (expression (== @!) g) b) (cons g a)) (list (cons #t (ite g a b)))]
[(or (list (cons (expression (== @&&) g h) x) (cons (expression (== @&&) g f) y))
(list (cons (expression (== @&&) g h) x) (cons (expression (== @&&) f g) y))
(list (cons (expression (== @&&) h g) x) (cons (expression (== @&&) g f) y))
(list (cons (expression (== @&&) h g) x) (cons (expression (== @&&) f g) y)))
(list (cons g (match* (h f)
[(_ (expression (== @!) h)) (ite h x y)]
[((expression (== @!) f) _) (ite f y x)]
[(_ _) (⊕ (ite h x ∅) (ite f y ∅))])))]
[(list (app simplify-ite (cons g x)) (app simplify-ite (cons h y)))
(list (cons (|| g h) (if (equal? x y) x (⊕ (ite g x ∅) (ite h y ∅)))))]
[(list (app simplify-ite (cons a x)) (app simplify-ite (cons b y)) ...)
(list (cons (apply || a b)
(if (for/and ([z y]) (equal? x z))
x
(apply ⊕ (ite a x ∅) (map (curryr ite ∅) b y)))))]))
(define (simplify-ite p)
(match* ((car p) (cdr p))
[(a (expression (== ite) a x _)) (cons a x)]
[(a (expression (== ite) (expression (== @!) a) _ x)) (cons a x)]
[((and (expression (== @!) a) !a) (expression (== ite) a _ x)) (cons !a x)]
[(_ _) p]))
(define (sort/expression @op x y)
(cond [(not (term? x)) (expression @op x y)]
[(not (term? y)) (expression @op y x)]
[(term<? x y) (expression @op x y)]
[else (expression @op y x)]))
take as input 2 values and return either # f ( if no simplification is possible )
simplify * acts as the identity function on xs . The limit is 100 by default .
(define (simplify* xs f [limit 100])
(if (> (length xs) limit)
xs
(let ([out (let outer ([xs xs])
(match xs
[(list x rest ..1)
(let inner ([head rest] [tail '()])
(match head
[(list) (cons x (outer tail))]
[(list y ys ...)
(match (f x y)
[#f (inner ys (cons y tail))]
[v (outer (cons v (append ys tail)))])]))]
[_ xs]))])
(if (= (length out) (length xs)) out (simplify* out f)))))
|
45b45b644cac284edc5c09a4ae5fb1518409bd2b5cb8a6b5f7257e9ecce53bc3 | Gbury/dolmen | logic.ml |
(* This file is free software, part of Dolmen. See file "LICENSE" for more details. *)
(* The Main Dolmen library is used to parse input languages *)
(* ************************************************************************ *)
module P = Dolmen.Class.Logic.Make
(Dolmen.Std.Loc)
(Dolmen.Std.Id)
(Dolmen.Std.Term)
(Dolmen.Std.Statement)
include (P : Dolmen.Class.Logic.S with type statement := Dolmen.Std.Statement.t
and type file := Dolmen.Std.Loc.file)
| null | https://raw.githubusercontent.com/Gbury/dolmen/55566c8db8a9c7636743b49a8c0bfaa061bbeb0c/src/loop/logic.ml | ocaml | This file is free software, part of Dolmen. See file "LICENSE" for more details.
The Main Dolmen library is used to parse input languages
************************************************************************ |
module P = Dolmen.Class.Logic.Make
(Dolmen.Std.Loc)
(Dolmen.Std.Id)
(Dolmen.Std.Term)
(Dolmen.Std.Statement)
include (P : Dolmen.Class.Logic.S with type statement := Dolmen.Std.Statement.t
and type file := Dolmen.Std.Loc.file)
|
1ac8e3ee4bcbb67a38fae1b387f7b94ded7ec190c3fb0359d8254a553c7945fb | webyrd/cool-relational-interpreter-examples | error-interp-specific-all.scm | (load "../mk/mk.scm")
;; error-handling Scheme interpreter
;;
two types of error ( referencing unbound variable , or taking car / cdr of a non - pair ( really a closure ) )
;;
;; errors are now represented as tagged lists, with specific messages
;;
;; this version of the interpreter uses *every* legal Scheme
;; evaluation order for programs that generate errors (rather than
;; left-to-right order, for example)
(define eval-expo
(lambda (exp env val)
(fresh ()
(absento 'ERROR exp)
(absento 'ERROR env)
(absento 'closure exp)
(conde
((== `(quote ,val) exp)
(not-in-envo 'quote env))
((fresh (x body)
(== `(lambda (,x) ,body) exp)
(== `(closure ,x ,body ,env) val)
(symbolo x)))
((symbolo exp) (lookupo exp env val))
((fresh (e1 e2 v1 v2)
(== `(cons ,e1 ,e2) exp)
(conde
((absento 'ERROR val)
(== `(,v1 . ,v2) val)
(eval-expo e1 env v1)
(eval-expo e2 env v2))
((fresh (msg)
(== `(ERROR . ,msg) val)
(conde
((eval-expo e1 env `(ERROR . ,msg)))
((eval-expo e2 env `(ERROR . ,msg)))))))))
((fresh (rator rand x body env^ a)
(== `(,rator ,rand) exp)
(conde
((absento 'ERROR val)
(eval-expo rator env `(closure ,x ,body ,env^))
(eval-expo rand env a)
(eval-expo body `((,x . ,a) . ,env^) val))
((fresh (msg)
(== `(ERROR . ,msg) val)
(conde
(
;; must be careful here!
;;
;; we can't depend on the evaluation of rator to ensure
;; application isn't overlapping with quote, for example
(=/= 'quote rator)
(=/= 'car rator)
(=/= 'cdr rator)
(eval-expo rator env `(ERROR . ,msg)))
((=/= 'quote rator)
(=/= 'car rator)
(=/= 'cdr rator)
(eval-expo rand env `(ERROR . ,msg)))
((eval-expo rator env `(closure ,x ,body ,env^))
(eval-expo rand env a)
(eval-expo body `((,x . ,a) . ,env^) `(ERROR . ,msg)))))))))
((fresh (e)
(== `(car ,e) exp)
(not-in-envo 'car env)
(conde
((fresh (v1 v2)
(absento 'ERROR `(,v1 . ,v2))
(=/= 'closure v1)
(== v1 val)
(eval-expo e env `(,v1 . ,v2))))
((fresh (msg)
(== `(ERROR . ,msg) val)
(conde
((eval-expo e env `(ERROR . ,msg)))
((fresh (v)
(== `(ERROR ATTEMPT-TO-TAKE-CAR-OF-NON-PAIR ,v) val)
(absento 'ERROR v)
(not-pairo v)
(eval-expo e env v)))))))))
((fresh (e)
(== `(cdr ,e) exp)
(not-in-envo 'cdr env)
(conde
((fresh (v1 v2)
(absento 'ERROR `(,v1 . ,v2))
(=/= 'closure v1)
(== v2 val)
(eval-expo e env `(,v1 . ,v2))))
((fresh (msg)
(== `(ERROR . ,msg) val)
(conde
((eval-expo e env `(ERROR . ,msg)))
((fresh (v)
(== `(ERROR ATTEMPT-TO-TAKE-CDR-OF-NON-PAIR ,v) val)
(absento 'ERROR v)
(not-pairo v)
(eval-expo e env v)))))))))))))
(define (not-in-envo x env)
(conde
((== '() env))
((fresh (a d)
(== `(,a . ,d) env)
(=/= x a)
(not-in-envo x d)))))
(define (not-pairo v)
(fresh (x body env)
(== `(closure ,x ,body ,env) v)))
(define lookupo
(lambda (x env t)
(conde
((== env '())
(== `(ERROR UNBOUND-VARIABLE ,x) t))
((fresh (rest y v)
(== `((,y . ,v) . ,rest) env)
(conde
((== y x) (== v t))
((=/= y x) (lookupo x rest t))))))))
| null | https://raw.githubusercontent.com/webyrd/cool-relational-interpreter-examples/c68d261279a301d6dae11ac1e2827a3a619af017/explicit-errors/error-interp-specific-all.scm | scheme | error-handling Scheme interpreter
errors are now represented as tagged lists, with specific messages
this version of the interpreter uses *every* legal Scheme
evaluation order for programs that generate errors (rather than
left-to-right order, for example)
must be careful here!
we can't depend on the evaluation of rator to ensure
application isn't overlapping with quote, for example | (load "../mk/mk.scm")
two types of error ( referencing unbound variable , or taking car / cdr of a non - pair ( really a closure ) )
(define eval-expo
(lambda (exp env val)
(fresh ()
(absento 'ERROR exp)
(absento 'ERROR env)
(absento 'closure exp)
(conde
((== `(quote ,val) exp)
(not-in-envo 'quote env))
((fresh (x body)
(== `(lambda (,x) ,body) exp)
(== `(closure ,x ,body ,env) val)
(symbolo x)))
((symbolo exp) (lookupo exp env val))
((fresh (e1 e2 v1 v2)
(== `(cons ,e1 ,e2) exp)
(conde
((absento 'ERROR val)
(== `(,v1 . ,v2) val)
(eval-expo e1 env v1)
(eval-expo e2 env v2))
((fresh (msg)
(== `(ERROR . ,msg) val)
(conde
((eval-expo e1 env `(ERROR . ,msg)))
((eval-expo e2 env `(ERROR . ,msg)))))))))
((fresh (rator rand x body env^ a)
(== `(,rator ,rand) exp)
(conde
((absento 'ERROR val)
(eval-expo rator env `(closure ,x ,body ,env^))
(eval-expo rand env a)
(eval-expo body `((,x . ,a) . ,env^) val))
((fresh (msg)
(== `(ERROR . ,msg) val)
(conde
(
(=/= 'quote rator)
(=/= 'car rator)
(=/= 'cdr rator)
(eval-expo rator env `(ERROR . ,msg)))
((=/= 'quote rator)
(=/= 'car rator)
(=/= 'cdr rator)
(eval-expo rand env `(ERROR . ,msg)))
((eval-expo rator env `(closure ,x ,body ,env^))
(eval-expo rand env a)
(eval-expo body `((,x . ,a) . ,env^) `(ERROR . ,msg)))))))))
((fresh (e)
(== `(car ,e) exp)
(not-in-envo 'car env)
(conde
((fresh (v1 v2)
(absento 'ERROR `(,v1 . ,v2))
(=/= 'closure v1)
(== v1 val)
(eval-expo e env `(,v1 . ,v2))))
((fresh (msg)
(== `(ERROR . ,msg) val)
(conde
((eval-expo e env `(ERROR . ,msg)))
((fresh (v)
(== `(ERROR ATTEMPT-TO-TAKE-CAR-OF-NON-PAIR ,v) val)
(absento 'ERROR v)
(not-pairo v)
(eval-expo e env v)))))))))
((fresh (e)
(== `(cdr ,e) exp)
(not-in-envo 'cdr env)
(conde
((fresh (v1 v2)
(absento 'ERROR `(,v1 . ,v2))
(=/= 'closure v1)
(== v2 val)
(eval-expo e env `(,v1 . ,v2))))
((fresh (msg)
(== `(ERROR . ,msg) val)
(conde
((eval-expo e env `(ERROR . ,msg)))
((fresh (v)
(== `(ERROR ATTEMPT-TO-TAKE-CDR-OF-NON-PAIR ,v) val)
(absento 'ERROR v)
(not-pairo v)
(eval-expo e env v)))))))))))))
(define (not-in-envo x env)
(conde
((== '() env))
((fresh (a d)
(== `(,a . ,d) env)
(=/= x a)
(not-in-envo x d)))))
(define (not-pairo v)
(fresh (x body env)
(== `(closure ,x ,body ,env) v)))
(define lookupo
(lambda (x env t)
(conde
((== env '())
(== `(ERROR UNBOUND-VARIABLE ,x) t))
((fresh (rest y v)
(== `((,y . ,v) . ,rest) env)
(conde
((== y x) (== v t))
((=/= y x) (lookupo x rest t))))))))
|
87ff0b960a68c2ce7e007826e54cf62eb8659b59d33747f0b1d41f9ce06dfa73 | shayne-fletcher/zen | extensible.ml | (*Basic language containing only variables*)
type var = [`Var of string]
let string_of_var : var -> 'a = function
| `Var s -> s
Evaluation of a variable means looking in an environment for a
binding and leaving it " as is " if there is n't one
binding and leaving it "as is" if there isn't one*)
let eval_var
(env : (string * ([> `Var of string ] as 'a)) list )
(`Var s as v : var) : 'a =
try
List.assoc s env
with
| Not_found -> v
(*Extended language for lambda calculus*)
type 'a lambda = [var | `Abs of string * 'a | `App of 'a * 'a]
(*The language is defined as an open recursive type (subterms are of
type ['a])*)
module Detail = struct
let rec strip (bs : string list) t =
match t with
| `Abs (b, t) -> strip (b :: bs) t
| _ as u -> (List.rev bs, u)
end (*module Detail*)
let string_of_lambda string_of_rec = function
| #var as v -> string_of_var v
| `App (u, v) ->
"("^(string_of_rec u) ^ ") (" ^ (string_of_rec v)^")"
| `Abs _ as t ->
match (Detail.strip [] t) with
| (b :: bs, u) ->
let binder =
"\\" ^ b ^ (List.fold_right (fun z b -> " " ^ z ^ b) bs ". ") in
binder ^ (string_of_rec u)
| ([], _) -> assert false
(*Factory functions*)
let mk_var : string -> [> `Var of string] = fun s -> `Var s
let mk_abs : string * 'b -> [> `Abs of string * 'b] = fun (s, t) -> `Abs (s, t)
let mk_app : 'a * 'b -> [> `App of 'a * 'b] = fun (u, v) -> `App (u, v)
let gen_sym =
let n = ref 0 in
fun () -> incr n; "_" ^ string_of_int !n
(*Evaluation of lambda expressions*)
let eval_lambda eval_rec env : 'a lambda -> 'a = function
| #var as v -> eval_var env v
| `App (u, v) ->
(*Evaluate the operand*)
let v' = eval_rec env v in
(*Next evaluate the operator*)
begin match eval_rec env u with
| `Abs (s, body) ->
(*If it's an abstraction, evaluate the body in an environment
where the binder [s] is bound to [v']*)
eval_rec [s, v'] body
| u' -> `App (u', v') (*No further reduction is possible*)
end
| `Abs (s, u) ->
(*Interesting rule. To evaluate, create an environment where [s]
is bound to a variable [`Var s']() and evaluate the body in that
environment*)
let s' = gen_sym () in
`Abs (s', eval_rec ((s, `Var s') :: env) u)
This has the effect of making every abstraction unique in terms
of their binders e.g.
( 1 )
` Abs ( " x " , ` Mult ( ` Var " x " , ` Var " x " ) ` - >
` Abs ( " _ 1 " , ` Mult ( ` Var " _ 1 " , ` Var " _ ` " ) )
( 2 )
` Abs ( " s " , ( ` Abs ( " t " , ( ` Mult ( ` Var " s " , ` Var " t " ) ) ) ) ) ) - >
` Abs ( " _ 2 " , ` Abs ( " _ 3 " , ` Mult ( ` Var " _ 2 " , ` Var " _ 3 " ) ) )
of their binders e.g.
(1)
`Abs ("x", `Mult (`Var "x", `Var "x")` ->
`Abs ("_1", `Mult (`Var "_1", `Var "_`"))
(2)
`Abs ("s", (`Abs ("t", (`Mult (`Var "s", `Var "t")))))) ->
`Abs ("_2", `Abs ("_3", `Mult (`Var "_2", `Var "_3")))
*)
(*Build a specific evaluator [eval1] for lambda by closing the
recursion*)
let rec eval1 (env : (string * ('a lambda as 'a)) list) : 'a -> 'a =
eval_lambda eval1 env
(*Along the same lines, define the expr language (the language of
arithmetic expressions) which adds numbers, addition and
multiplication to the basic language*)
type 'a expr = [var | `Num of int | `Add of 'a * 'a | `Mult of 'a * 'a]
let mk_num i = `Num i
let mk_add (u, v) = `Add (u, v)
let string_of_expr string_of_rec = function
| #var as v ->
string_of_var v
| `Num i ->
string_of_int i
| `Add (u, v) ->
"(" ^ (string_of_rec u) ^ " + " ^ (string_of_rec v) ^ ")"
| `Mult (u, v) ->
"(" ^ (string_of_rec u) ^ " * " ^ (string_of_rec v) ^ ")"
(*As for traditional variants, it comes in handy to have a [map]
function that uniformly applies a function [f] to the sub-terms of an
expression*)
let map_expr
(f : (
[> `Add of 'a * 'a | `Mult of 'a * 'a | `Num of int | `Var of string ]
as 'a) -> 'a) : 'a expr -> 'a = function
| #var as v -> v
| `Num _ as n -> n
| `Add (e1, e2) -> `Add (f e1, f e2)
| `Mult (e1, e2) -> `Mult (f e1, f e2)
(*Evaluation of expressions*)
let eval_expr eval_rec
(env : (string *
([> `Add of 'a * 'a | `Mult of 'a * 'a | `Num of int | `Var of string ]
as 'a))
list)
(e : 'a expr) : 'a =
match map_expr (eval_rec env) e with
| #var as v -> eval_var env v
| `Add (`Num m, `Num n) -> `Num (m + n)
| `Mult (`Num m, `Num n) -> `Num (m * n)
| e -> e
The evaluation function is quite different to lambda : first
evaluate all sub - terms to make redexes apparent and then pattern
match
evaluate all sub-terms to make redexes apparent and then pattern
match*)
Define an evaluator [ ] for the closed language [ ' a expr as
' a ]
'a]*)
let rec eval2 (env : (string * ('a expr as 'a)) list) : 'a -> 'a=
eval_expr eval2 env
(*Take the union of lambda and expr to create a full evaluator*)
type 'a lexpr = [var | 'a lambda | 'a expr]
let rec string_of_t = function
| #lambda as l -> string_of_lambda string_of_t l
| #expr as e -> string_of_expr string_of_t e
let eval_lexpr eval_rec
(env : (string *
([> `Abs of string * 'a
| `Add of 'a * 'a
| `App of 'a * 'a
| `Mult of 'a * 'a
| `Num of int
| `Var of string ]
as 'a)) list) : 'a lexpr -> 'a = function
| #lambda as x -> eval_lambda eval_rec env x
| #expr as x -> eval_expr eval_rec env x
let rec eval3 (env : (string * ('a lexpr as 'a)) list) : 'a -> 'a =
eval_lexpr eval3 env
Test it out
( \x . x * x ) 2 + 5
(\x. x * x) 2 + 5
*)
let e3 = eval3 []
(`Add (`App (`Abs ("x", `Mult (`Var "x", `Var "x")), `Num 2), `Num 5))
(*Yay! `Num 9!*)
| null | https://raw.githubusercontent.com/shayne-fletcher/zen/10a1d0b9bf261bb133918dd62fb1593c3d4d21cb/ocaml/extensible/extensible.ml | ocaml | Basic language containing only variables
Extended language for lambda calculus
The language is defined as an open recursive type (subterms are of
type ['a])
module Detail
Factory functions
Evaluation of lambda expressions
Evaluate the operand
Next evaluate the operator
If it's an abstraction, evaluate the body in an environment
where the binder [s] is bound to [v']
No further reduction is possible
Interesting rule. To evaluate, create an environment where [s]
is bound to a variable [`Var s']() and evaluate the body in that
environment
Build a specific evaluator [eval1] for lambda by closing the
recursion
Along the same lines, define the expr language (the language of
arithmetic expressions) which adds numbers, addition and
multiplication to the basic language
As for traditional variants, it comes in handy to have a [map]
function that uniformly applies a function [f] to the sub-terms of an
expression
Evaluation of expressions
Take the union of lambda and expr to create a full evaluator
Yay! `Num 9! | type var = [`Var of string]
let string_of_var : var -> 'a = function
| `Var s -> s
Evaluation of a variable means looking in an environment for a
binding and leaving it " as is " if there is n't one
binding and leaving it "as is" if there isn't one*)
let eval_var
(env : (string * ([> `Var of string ] as 'a)) list )
(`Var s as v : var) : 'a =
try
List.assoc s env
with
| Not_found -> v
type 'a lambda = [var | `Abs of string * 'a | `App of 'a * 'a]
module Detail = struct
let rec strip (bs : string list) t =
match t with
| `Abs (b, t) -> strip (b :: bs) t
| _ as u -> (List.rev bs, u)
let string_of_lambda string_of_rec = function
| #var as v -> string_of_var v
| `App (u, v) ->
"("^(string_of_rec u) ^ ") (" ^ (string_of_rec v)^")"
| `Abs _ as t ->
match (Detail.strip [] t) with
| (b :: bs, u) ->
let binder =
"\\" ^ b ^ (List.fold_right (fun z b -> " " ^ z ^ b) bs ". ") in
binder ^ (string_of_rec u)
| ([], _) -> assert false
let mk_var : string -> [> `Var of string] = fun s -> `Var s
let mk_abs : string * 'b -> [> `Abs of string * 'b] = fun (s, t) -> `Abs (s, t)
let mk_app : 'a * 'b -> [> `App of 'a * 'b] = fun (u, v) -> `App (u, v)
let gen_sym =
let n = ref 0 in
fun () -> incr n; "_" ^ string_of_int !n
let eval_lambda eval_rec env : 'a lambda -> 'a = function
| #var as v -> eval_var env v
| `App (u, v) ->
let v' = eval_rec env v in
begin match eval_rec env u with
| `Abs (s, body) ->
eval_rec [s, v'] body
end
| `Abs (s, u) ->
let s' = gen_sym () in
`Abs (s', eval_rec ((s, `Var s') :: env) u)
This has the effect of making every abstraction unique in terms
of their binders e.g.
( 1 )
` Abs ( " x " , ` Mult ( ` Var " x " , ` Var " x " ) ` - >
` Abs ( " _ 1 " , ` Mult ( ` Var " _ 1 " , ` Var " _ ` " ) )
( 2 )
` Abs ( " s " , ( ` Abs ( " t " , ( ` Mult ( ` Var " s " , ` Var " t " ) ) ) ) ) ) - >
` Abs ( " _ 2 " , ` Abs ( " _ 3 " , ` Mult ( ` Var " _ 2 " , ` Var " _ 3 " ) ) )
of their binders e.g.
(1)
`Abs ("x", `Mult (`Var "x", `Var "x")` ->
`Abs ("_1", `Mult (`Var "_1", `Var "_`"))
(2)
`Abs ("s", (`Abs ("t", (`Mult (`Var "s", `Var "t")))))) ->
`Abs ("_2", `Abs ("_3", `Mult (`Var "_2", `Var "_3")))
*)
let rec eval1 (env : (string * ('a lambda as 'a)) list) : 'a -> 'a =
eval_lambda eval1 env
type 'a expr = [var | `Num of int | `Add of 'a * 'a | `Mult of 'a * 'a]
let mk_num i = `Num i
let mk_add (u, v) = `Add (u, v)
let string_of_expr string_of_rec = function
| #var as v ->
string_of_var v
| `Num i ->
string_of_int i
| `Add (u, v) ->
"(" ^ (string_of_rec u) ^ " + " ^ (string_of_rec v) ^ ")"
| `Mult (u, v) ->
"(" ^ (string_of_rec u) ^ " * " ^ (string_of_rec v) ^ ")"
let map_expr
(f : (
[> `Add of 'a * 'a | `Mult of 'a * 'a | `Num of int | `Var of string ]
as 'a) -> 'a) : 'a expr -> 'a = function
| #var as v -> v
| `Num _ as n -> n
| `Add (e1, e2) -> `Add (f e1, f e2)
| `Mult (e1, e2) -> `Mult (f e1, f e2)
let eval_expr eval_rec
(env : (string *
([> `Add of 'a * 'a | `Mult of 'a * 'a | `Num of int | `Var of string ]
as 'a))
list)
(e : 'a expr) : 'a =
match map_expr (eval_rec env) e with
| #var as v -> eval_var env v
| `Add (`Num m, `Num n) -> `Num (m + n)
| `Mult (`Num m, `Num n) -> `Num (m * n)
| e -> e
The evaluation function is quite different to lambda : first
evaluate all sub - terms to make redexes apparent and then pattern
match
evaluate all sub-terms to make redexes apparent and then pattern
match*)
Define an evaluator [ ] for the closed language [ ' a expr as
' a ]
'a]*)
let rec eval2 (env : (string * ('a expr as 'a)) list) : 'a -> 'a=
eval_expr eval2 env
type 'a lexpr = [var | 'a lambda | 'a expr]
let rec string_of_t = function
| #lambda as l -> string_of_lambda string_of_t l
| #expr as e -> string_of_expr string_of_t e
let eval_lexpr eval_rec
(env : (string *
([> `Abs of string * 'a
| `Add of 'a * 'a
| `App of 'a * 'a
| `Mult of 'a * 'a
| `Num of int
| `Var of string ]
as 'a)) list) : 'a lexpr -> 'a = function
| #lambda as x -> eval_lambda eval_rec env x
| #expr as x -> eval_expr eval_rec env x
let rec eval3 (env : (string * ('a lexpr as 'a)) list) : 'a -> 'a =
eval_lexpr eval3 env
Test it out
( \x . x * x ) 2 + 5
(\x. x * x) 2 + 5
*)
let e3 = eval3 []
(`Add (`App (`Abs ("x", `Mult (`Var "x", `Var "x")), `Num 2), `Num 5))
|
6408c77fe1656f7f905f5c355b9accafb76695866f61f3cc0708fa25f6b1e718 | hkuplg/fcore | SpecHelper.hs | module SpecHelper
(discoverTestCases
,parseExpectedOutput
) where
import System.Directory (getDirectoryContents)
import System.FilePath (dropExtension)
import Data.Char (isSpace)
import Data.List (isSuffixOf)
type Name = String
type Source = String
type ExpectedOutput = String
discoverTestCases :: FilePath -> IO [(Name, FilePath)]
discoverTestCases directory =
do fileNames <- filter (isSuffixOf ".sf") <$> getDirectoryContents directory
return (map (\f -> (dropExtension f, f)) fileNames)
parseExpectedOutput :: Source -> Maybe ExpectedOutput
parseExpectedOutput source =
let firstLine = takeWhile (/= '\n') source in
case firstLine of
'-':'-':'>':_ -> Just (strip (drop 3 firstLine))
_ -> Nothing
strip :: String -> String
strip = reverse . dropWhile isSpace . reverse . dropWhile isSpace
| null | https://raw.githubusercontent.com/hkuplg/fcore/e27b6dec5bfd319edb8c3e90d94a993bcc7b4c95/testsuite/SpecHelper.hs | haskell | module SpecHelper
(discoverTestCases
,parseExpectedOutput
) where
import System.Directory (getDirectoryContents)
import System.FilePath (dropExtension)
import Data.Char (isSpace)
import Data.List (isSuffixOf)
type Name = String
type Source = String
type ExpectedOutput = String
discoverTestCases :: FilePath -> IO [(Name, FilePath)]
discoverTestCases directory =
do fileNames <- filter (isSuffixOf ".sf") <$> getDirectoryContents directory
return (map (\f -> (dropExtension f, f)) fileNames)
parseExpectedOutput :: Source -> Maybe ExpectedOutput
parseExpectedOutput source =
let firstLine = takeWhile (/= '\n') source in
case firstLine of
'-':'-':'>':_ -> Just (strip (drop 3 firstLine))
_ -> Nothing
strip :: String -> String
strip = reverse . dropWhile isSpace . reverse . dropWhile isSpace
|
|
e8a1c8655a47ef1db17db0c81f2626be19cb6787f0d8b6ca8a7c8101fea9ac03 | mitchellwrosen/planet-mitchell | Builder.hs | module ByteString.Lazy.Builder
( module Data.ByteString.Builder
) where
import Data.ByteString.Builder
| null | https://raw.githubusercontent.com/mitchellwrosen/planet-mitchell/18dd83204e70fffcd23fe12dd3a80f70b7fa409b/planet-mitchell/src/ByteString/Lazy/Builder.hs | haskell | module ByteString.Lazy.Builder
( module Data.ByteString.Builder
) where
import Data.ByteString.Builder
|
|
04e992ff6849c1e163f2cee222fadaa23cbe0d38e07eef726d79d2239e4f8e71 | mitchellwrosen/riak2 | Handle.hs | module Riak.Handle
( Handle
, HandleConfig(..)
, HandleError(..)
, DecodeError(..)
, DisconnectReason(..)
, EventHandlers(..)
, createHandle
) where
import Libriak.Response (DecodeError(..))
import RiakHandle
import RiakHandleError (HandleError(..))
| null | https://raw.githubusercontent.com/mitchellwrosen/riak2/d3c4ef4389012c70e72623cdf9a4caec0a07e568/riak2/public/Riak/Handle.hs | haskell | module Riak.Handle
( Handle
, HandleConfig(..)
, HandleError(..)
, DecodeError(..)
, DisconnectReason(..)
, EventHandlers(..)
, createHandle
) where
import Libriak.Response (DecodeError(..))
import RiakHandle
import RiakHandleError (HandleError(..))
|
|
36ac86ca32fb8dc378429293c954604cd84da8967c77fbe9529ed595fffcdcb6 | frenetic-lang/ocaml-openflow | Bits.ml | let test_bit n x =
Int32.logand (Int32.shift_right_logical x n) Int32.one = Int32.one
let clear_bit n x =
Int32.logand x (Int32.lognot (Int32.shift_left Int32.one n))
let set_bit n x =
Int32.logor x (Int32.shift_left Int32.one n)
let bit (x : int32) (n : int) (v : bool) : int32 =
if v then set_bit n x else clear_bit n x
| null | https://raw.githubusercontent.com/frenetic-lang/ocaml-openflow/289ffb8a692cf32b8413cc58044aae9c151ddd44/lib/Bits.ml | ocaml | let test_bit n x =
Int32.logand (Int32.shift_right_logical x n) Int32.one = Int32.one
let clear_bit n x =
Int32.logand x (Int32.lognot (Int32.shift_left Int32.one n))
let set_bit n x =
Int32.logor x (Int32.shift_left Int32.one n)
let bit (x : int32) (n : int) (v : bool) : int32 =
if v then set_bit n x else clear_bit n x
|
|
494087cde183e5113b01a303fae179ba52015bdee392bf43314a97ec0fb04469 | grayswandyr/electrod | Raw_ident.mli | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* electrod - a model finder for relational first - order linear temporal logic
*
* Copyright ( C ) 2016 - 2020 ONERA
* Authors : ( ONERA ) , ( ONERA )
*
* 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 /.
*
* SPDX - License - Identifier : MPL-2.0
* License - Filename : LICENSE.md
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* electrod - a model finder for relational first-order linear temporal logic
*
* Copyright (C) 2016-2020 ONERA
* Authors: Julien Brunel (ONERA), David Chemouil (ONERA)
*
* 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 /.
*
* SPDX-License-Identifier: MPL-2.0
* License-Filename: LICENSE.md
******************************************************************************)
(** Identifiers in "raw" ASTs. *)
(** Any form of identifier for constants (atoms, relations) in the source
code. *)
type t =
{ ident : string
; loc : Location.t
}
(** {1 Constructor} *)
val ident : string -> Lexing.position -> Lexing.position -> t
(** {1 Accessors} *)
val basename : t -> string
val location : t -> Location.t
val eq_name : t -> t -> bool
val pp : Format.formatter -> t -> unit
| null | https://raw.githubusercontent.com/grayswandyr/electrod/eb0b02eafb34b6c921f99716cb5e90c946aae51b/src/Raw_ident.mli | ocaml | * Identifiers in "raw" ASTs.
* Any form of identifier for constants (atoms, relations) in the source
code.
* {1 Constructor}
* {1 Accessors} | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* electrod - a model finder for relational first - order linear temporal logic
*
* Copyright ( C ) 2016 - 2020 ONERA
* Authors : ( ONERA ) , ( ONERA )
*
* 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 /.
*
* SPDX - License - Identifier : MPL-2.0
* License - Filename : LICENSE.md
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* electrod - a model finder for relational first-order linear temporal logic
*
* Copyright (C) 2016-2020 ONERA
* Authors: Julien Brunel (ONERA), David Chemouil (ONERA)
*
* 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 /.
*
* SPDX-License-Identifier: MPL-2.0
* License-Filename: LICENSE.md
******************************************************************************)
type t =
{ ident : string
; loc : Location.t
}
val ident : string -> Lexing.position -> Lexing.position -> t
val basename : t -> string
val location : t -> Location.t
val eq_name : t -> t -> bool
val pp : Format.formatter -> t -> unit
|
804e890e472198de77e523b6929e605a6ce89969c415c00ff1b7dfdc2e959cc0 | hasktorch/ffi-experimental | GC.hs | {-# LANGUAGE EmptyDataDecls #-}
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleInstances #
# LANGUAGE ForeignFunctionInterface #
{-# LANGUAGE GADTs #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeSynonymInstances #-}
module ATen.GC where
import Control.Exception.Safe (catch,throwIO)
import Data.List (isPrefixOf)
import Language.C.Inline.Cpp.Exceptions (CppException(..))
import System.Mem (performGC)
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async
import System.SysInfo
retryWithGC' :: Int -> IO a -> IO a
retryWithGC' count func =
func `catch` \a@(CppStdException message) ->
if isPrefixOf msgOutOfMemory message
then
if count <= 0
then throwIO $ CppStdException $ "Too many calls to performGC, " ++ message
else do
performGC
We need delta delay(1ms ) to wait GC .
retryWithGC' (count-1) func
else throwIO a
where
msgOutOfMemory :: String
msgOutOfMemory = "Exception: CUDA out of memory."
retryWithGC :: IO a -> IO a
retryWithGC = retryWithGC' 10
checkOSMemoryWithGC :: IO ()
checkOSMemoryWithGC = do
v <- sysInfo
case v of
Right stat -> do
let rate = (fromIntegral (freeram stat) / fromIntegral (totalram stat))
if rate <= 0.5
then performGC
else return ()
Left _ -> return ()
wait 500msec
checkOSMemoryWithGC
monitorMemory :: IO () -> IO ()
monitorMemory func = do
func `race` checkOSMemoryWithGC
return ()
| null | https://raw.githubusercontent.com/hasktorch/ffi-experimental/54192297742221c4d50398586ba8d187451f9ee0/ffi/src/ATen/GC.hs | haskell | # LANGUAGE EmptyDataDecls #
# LANGUAGE GADTs #
# LANGUAGE TypeSynonymInstances # | # LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleInstances #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
module ATen.GC where
import Control.Exception.Safe (catch,throwIO)
import Data.List (isPrefixOf)
import Language.C.Inline.Cpp.Exceptions (CppException(..))
import System.Mem (performGC)
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async
import System.SysInfo
retryWithGC' :: Int -> IO a -> IO a
retryWithGC' count func =
func `catch` \a@(CppStdException message) ->
if isPrefixOf msgOutOfMemory message
then
if count <= 0
then throwIO $ CppStdException $ "Too many calls to performGC, " ++ message
else do
performGC
We need delta delay(1ms ) to wait GC .
retryWithGC' (count-1) func
else throwIO a
where
msgOutOfMemory :: String
msgOutOfMemory = "Exception: CUDA out of memory."
retryWithGC :: IO a -> IO a
retryWithGC = retryWithGC' 10
checkOSMemoryWithGC :: IO ()
checkOSMemoryWithGC = do
v <- sysInfo
case v of
Right stat -> do
let rate = (fromIntegral (freeram stat) / fromIntegral (totalram stat))
if rate <= 0.5
then performGC
else return ()
Left _ -> return ()
wait 500msec
checkOSMemoryWithGC
monitorMemory :: IO () -> IO ()
monitorMemory func = do
func `race` checkOSMemoryWithGC
return ()
|
8ae3d8b979d0e584ba9c583e0c892fdcf268d98949d71dfde802027cd4ce4cd9 | DanielG/ghc-mod | Main.hs | import Bar (bar)
main = putStrLn bar
| null | https://raw.githubusercontent.com/DanielG/ghc-mod/391e187a5dfef4421aab2508fa6ff7875cc8259d/test/data/cabal-project/Main.hs | haskell | import Bar (bar)
main = putStrLn bar
|
|
89dd5a9317df79ea93128e5224b2658cbd7860e884e145da816e5d258b1f0c36 | monky-hs/monky | Blkid.hs |
Copyright 2015 ,
This file is part of .
is free software : you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation , either version 3 of the License , or
( at your option ) any later version .
is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
along with . If not , see < / > .
Copyright 2015 Markus Ongyerth, Stephan Guenther
This file is part of Monky.
Monky is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Monky is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Monky. If not, see </>.
-}
# LANGUAGE ForeignFunctionInterface #
{-# LANGUAGE EmptyDataDecls #-}
# LANGUAGE TemplateHaskell #
# LANGUAGE CPP #
|
Module : . Blkid
Description : Minimal access to liblkid
Maintainer : ongy
Stability : experimental
Portability : Linux
This module allows access to libblkid functionality
Since the library does not have to exist on every system we link
against it on runtime when needed .
We do n't have a handle or something cool like that , so we will just
load it when needed und unload again after
Module : Monky.Blkid
Description : Minimal access to liblkid
Maintainer : ongy
Stability : experimental
Portability : Linux
This module allows access to libblkid functionality
Since the library does not have to exist on every system we link
against it on runtime when needed.
We don't have a handle or something cool like that, so we will just
load it when needed und unload again after
-}
module Monky.Blkid
( evaluateTag
, evaluateSpec
, evaluateTag'
, evaluateSpec'
, withLibBlkid
)
where
import Monky.Template
import Foreign.Ptr
import Foreign.C.String
import Foreign.Marshal.Alloc
#if MIN_VERSION_base(4,8,0)
#else
import Control.Applicative ((<$>))
#endif
data Cache
importLib "LibBlkid" "libblkid.so.1"
[ ( "c_evt", "blkid_evaluate_tag", "CString -> CString -> Ptr Cache -> IO CString")
, ( "c_evs", "blkid_evaluate_spec", "CString -> Ptr Cache -> IO CString")
]
getAndFreeString :: CString -> IO String
getAndFreeString ptr = do
ret <- peekCString ptr
free ptr
return ret
maybeGetString :: CString -> IO (Maybe String)
maybeGetString ptr = if ptr == nullPtr
then return Nothing
else Just <$> getAndFreeString ptr
|Version to reuse the
evaluateTag' :: String -> String -> LibBlkid -> IO (Maybe String)
evaluateTag' t v l = do
ptr <- withCString t (\ct -> withCString v (\cv -> c_evt l ct cv nullPtr))
maybeGetString ptr
|version to reuse the
evaluateSpec' :: String -> LibBlkid -> IO (Maybe String)
evaluateSpec' s l = do
ptr <- withCString s (\cs -> c_evs l cs nullPtr)
maybeGetString ptr
-- |Evaluate a tag
evaluateTag :: String -> String -> IO (Maybe String)
evaluateTag t v = withLibBlkid $ evaluateTag' t v
-- |Evaluate a spec
evaluateSpec :: String -> IO (Maybe String)
evaluateSpec = withLibBlkid . evaluateSpec'
|Execute an IO action with an instance of LibBlkid
withLibBlkid :: (LibBlkid -> IO a) -> IO a
withLibBlkid a = do
l <- getLibBlkid
ret <- a l
destroyLibBlkid l
return ret
| null | https://raw.githubusercontent.com/monky-hs/monky/5430352258622bdb0a54f6a197090cc4ef03102f/Monky/Blkid.hs | haskell | # LANGUAGE EmptyDataDecls #
|Evaluate a tag
|Evaluate a spec |
Copyright 2015 ,
This file is part of .
is free software : you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation , either version 3 of the License , or
( at your option ) any later version .
is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
along with . If not , see < / > .
Copyright 2015 Markus Ongyerth, Stephan Guenther
This file is part of Monky.
Monky is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Monky is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Monky. If not, see </>.
-}
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE TemplateHaskell #
# LANGUAGE CPP #
|
Module : . Blkid
Description : Minimal access to liblkid
Maintainer : ongy
Stability : experimental
Portability : Linux
This module allows access to libblkid functionality
Since the library does not have to exist on every system we link
against it on runtime when needed .
We do n't have a handle or something cool like that , so we will just
load it when needed und unload again after
Module : Monky.Blkid
Description : Minimal access to liblkid
Maintainer : ongy
Stability : experimental
Portability : Linux
This module allows access to libblkid functionality
Since the library does not have to exist on every system we link
against it on runtime when needed.
We don't have a handle or something cool like that, so we will just
load it when needed und unload again after
-}
module Monky.Blkid
( evaluateTag
, evaluateSpec
, evaluateTag'
, evaluateSpec'
, withLibBlkid
)
where
import Monky.Template
import Foreign.Ptr
import Foreign.C.String
import Foreign.Marshal.Alloc
#if MIN_VERSION_base(4,8,0)
#else
import Control.Applicative ((<$>))
#endif
data Cache
importLib "LibBlkid" "libblkid.so.1"
[ ( "c_evt", "blkid_evaluate_tag", "CString -> CString -> Ptr Cache -> IO CString")
, ( "c_evs", "blkid_evaluate_spec", "CString -> Ptr Cache -> IO CString")
]
getAndFreeString :: CString -> IO String
getAndFreeString ptr = do
ret <- peekCString ptr
free ptr
return ret
maybeGetString :: CString -> IO (Maybe String)
maybeGetString ptr = if ptr == nullPtr
then return Nothing
else Just <$> getAndFreeString ptr
|Version to reuse the
evaluateTag' :: String -> String -> LibBlkid -> IO (Maybe String)
evaluateTag' t v l = do
ptr <- withCString t (\ct -> withCString v (\cv -> c_evt l ct cv nullPtr))
maybeGetString ptr
|version to reuse the
evaluateSpec' :: String -> LibBlkid -> IO (Maybe String)
evaluateSpec' s l = do
ptr <- withCString s (\cs -> c_evs l cs nullPtr)
maybeGetString ptr
evaluateTag :: String -> String -> IO (Maybe String)
evaluateTag t v = withLibBlkid $ evaluateTag' t v
evaluateSpec :: String -> IO (Maybe String)
evaluateSpec = withLibBlkid . evaluateSpec'
|Execute an IO action with an instance of LibBlkid
withLibBlkid :: (LibBlkid -> IO a) -> IO a
withLibBlkid a = do
l <- getLibBlkid
ret <- a l
destroyLibBlkid l
return ret
|
18aeecdcf4e7ce8e481751656c71aaed8dbae5c282a172d959367566bc75faa6 | 2600hz-archive/whistle | proper_tests.erl | Copyright 2010 - 2011 < > ,
< >
and < >
%%%
This file is part of PropEr .
%%%
%%% PropEr 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.
%%%
%%% PropEr 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 PropEr. If not, see </>.
2010 - 2011 , and
%%% @version {@version}
@author
@doc This modules contains PropEr 's Unit tests . You need the EUnit
%%% application to compile it.
-module(proper_tests).
-include("proper.hrl").
-include_lib("eunit/include/eunit.hrl").
%%------------------------------------------------------------------------------
%% Helper macros
%%------------------------------------------------------------------------------
NOTE : Never add long_result to Opts for these macros .
state_is_clean() ->
get() =:= [].
assertEqualsOneOf(_X, none) ->
ok;
assertEqualsOneOf(X, List) ->
?assert(lists:any(fun(Y) -> Y =:= X end, List)).
-define(_passes(Test),
?_passes(Test, [])).
-define(_passes(Test, Opts),
?_assertRun(true, Test, Opts, true)).
-define(_errorsOut(ExpReason, Test),
?_errorsOut(ExpReason, Test, [])).
-define(_errorsOut(ExpReason, Test, Opts),
?_assertRun({error,ExpReason}, Test, Opts, true)).
-define(_assertRun(ExpResult, Test, Opts, AlsoLongResult),
?_test(begin
?assertMatch(ExpResult, proper:quickcheck(Test,Opts)),
proper:clean_garbage(),
?assert(state_is_clean()),
case AlsoLongResult of
true ->
?assertMatch(ExpResult,
proper:quickcheck(Test,[long_result|Opts])),
proper:clean_garbage(),
?assert(state_is_clean());
false ->
ok
end
end)).
-define(_assertCheck(ExpShortResult, CExm, Test),
?_assertCheck(ExpShortResult, CExm, Test, [])).
-define(_assertCheck(ExpShortResult, CExm, Test, Opts),
?_test(?assertCheck(ExpShortResult, CExm, Test, Opts))).
-define(assertCheck(ExpShortResult, CExm, Test, Opts),
begin
?assertMatch(ExpShortResult, proper:check(Test,CExm,Opts)),
?assert(state_is_clean())
end).
-define(_fails(Test),
?_fails(Test, [])).
-define(_fails(Test, Opts),
?_failsWith(_, Test, Opts)).
-define(_failsWith(ExpCExm, Test),
?_failsWith(ExpCExm, Test, [])).
-define(_failsWith(ExpCExm, Test, Opts),
?_assertFailRun(ExpCExm, none, Test, Opts)).
-define(_failsWithOneOf(AllCExms, Test),
?_failsWithOneOf(AllCExms, Test, [])).
-define(_failsWithOneOf(AllCExms, Test, Opts),
?_assertFailRun(_, AllCExms, Test, Opts)).
-define(SHRINK_TEST_OPTS, [{start_size,10},{max_shrinks,10000}]).
-define(_shrinksTo(ExpShrunk, Type),
?_assertFailRun([ExpShrunk], none, ?FORALL(_X,Type,false),
?SHRINK_TEST_OPTS)).
-define(_shrinksToOneOf(AllShrunk, Type),
?_assertFailRun(_, [[X] || X <- AllShrunk], ?FORALL(_X,Type,false),
?SHRINK_TEST_OPTS)).
-define(_nativeShrinksTo(ExpShrunk, TypeStr),
?_assertFailRun([ExpShrunk], none,
?FORALL(_X,assert_can_translate(?MODULE,TypeStr),false),
?SHRINK_TEST_OPTS)).
-define(_nativeShrinksToOneOf(AllShrunk, TypeStr),
?_assertFailRun(_, [[X] || X <- AllShrunk],
?FORALL(_X,assert_can_translate(?MODULE,TypeStr),false),
?SHRINK_TEST_OPTS)).
-define(_assertFailRun(ExpCExm, AllCExms, Test, Opts),
?_test(begin
ShortResult = proper:quickcheck(Test, Opts),
CExm1 = get_cexm(),
?checkCExm(CExm1, ExpCExm, AllCExms, Test, Opts),
?assertEqual(false, ShortResult),
LongResult = proper:quickcheck(Test, [long_result|Opts]),
CExm2 = get_cexm(),
?checkCExm(CExm2, ExpCExm, AllCExms, Test, Opts),
?checkCExm(LongResult, ExpCExm, AllCExms, Test, Opts)
end)).
get_cexm() ->
CExm = proper:counterexample(),
proper:clean_garbage(),
?assert(state_is_clean()),
CExm.
-define(checkCExm(CExm, ExpCExm, AllCExms, Test, Opts),
begin
?assertCheck(false, CExm, Test, Opts),
?assertMatch(ExpCExm, CExm),
assertEqualsOneOf(CExm, AllCExms)
end).
-define(_assertTempBecomesN(N, ExpShortResult, Prop),
?_assertTempBecomesN(N, ExpShortResult, Prop, [])).
-define(_assertTempBecomesN(N, ExpShortResult, Prop, Opts),
?_test(begin
?assertMatch(ExpShortResult, proper:quickcheck(Prop,Opts)),
?assertEqual(N, get_temp()),
erase_temp(),
proper:clean_garbage(),
?assert(state_is_clean())
end)).
inc_temp() ->
inc_temp(1).
inc_temp(Inc) ->
case get(temp) of
undefined -> put(temp, Inc);
X -> put(temp, X + Inc)
end,
ok.
get_temp() ->
get(temp).
erase_temp() ->
erase(temp),
ok.
non_deterministic(Behaviour) ->
inc_temp(),
N = get_temp(),
{MustReset,Result} = get_result(N, 0, Behaviour),
case MustReset of
true -> erase_temp();
false -> ok
end,
Result.
get_result(N, Sum, [{M,Result}]) ->
{N >= Sum + M, Result};
get_result(N, Sum, [{M,Result} | Rest]) ->
NewSum = Sum + M,
case N =< NewSum of
true -> {false, Result};
false -> get_result(N, NewSum, Rest)
end.
setup_run_commands(Module, Cmds, Env) ->
Module:set_up(),
Res = proper_statem:run_commands(Module, Cmds, Env),
Module:clean_up(),
Res.
%%------------------------------------------------------------------------------
%% Helper Functions
%%------------------------------------------------------------------------------
assert_type_works({Type,Are,_Target,Arent,TypeStr}, IsSimple) ->
case Type of
none ->
ok;
_ ->
lists:foreach(fun(X) -> assert_is_instance(X,Type) end, Are),
assert_can_generate(Type, IsSimple),
lists:foreach(fun(X) -> assert_not_is_instance(X,Type) end, Arent)
end,
case TypeStr of
none ->
ok;
_ ->
TransType = assert_can_translate(?MODULE, TypeStr),
lists:foreach(fun(X) -> assert_is_instance(X,TransType) end, Are),
assert_can_generate(TransType, IsSimple),
lists:foreach(fun(X) -> assert_not_is_instance(X,TransType) end,
Arent)
end.
assert_can_translate(Mod, TypeStr) ->
proper_typeserver:start(),
Type = {Mod,TypeStr},
Result1 = proper_typeserver:translate_type(Type),
Result2 = proper_typeserver:translate_type(Type),
proper_typeserver:stop(),
?assert(state_is_clean()),
{ok,Type1} = Result1,
{ok,Type2} = Result2,
?assert(proper_types:equal_types(Type1,Type2)),
Type1.
assert_cant_translate(Mod, TypeStr) ->
proper_typeserver:start(),
Result = proper_typeserver:translate_type({Mod,TypeStr}),
proper_typeserver:stop(),
?assert(state_is_clean()),
?assertMatch({error,_}, Result).
TODO : after fixing the , use generic reverse function .
assert_is_instance(X, Type) ->
?assert(proper_types:is_inst(X, Type) andalso state_is_clean()).
assert_can_generate(Type, CheckIsInstance) ->
lists:foreach(fun(Size) -> try_generate(Type,Size,CheckIsInstance) end,
[1,2,5,10,20,40,50]).
try_generate(Type, Size, CheckIsInstance) ->
{ok,Instance} = proper_gen:pick(Type, Size),
?assert(state_is_clean()),
case CheckIsInstance of
true -> assert_is_instance(Instance, Type);
false -> ok
end.
assert_native_can_generate(Mod, TypeStr, CheckIsInstance) ->
assert_can_generate(assert_can_translate(Mod,TypeStr), CheckIsInstance).
assert_cant_generate(Type) ->
?assertEqual(error, proper_gen:pick(Type)),
?assert(state_is_clean()).
assert_cant_generate_cmds(Type, N) ->
?assertEqual(error, proper_gen:pick(?SUCHTHAT(T, Type, length(T) > N))),
?assert(state_is_clean()).
assert_not_is_instance(X, Type) ->
?assert(not proper_types:is_inst(X, Type) andalso state_is_clean()).
assert_function_type_works(FunType) ->
{ok,F} = proper_gen:pick(FunType),
%% TODO: this isn't exception-safe
?assert(proper_types:is_instance(F, FunType)),
assert_is_pure_function(F),
proper:global_state_erase(),
?assert(state_is_clean()).
assert_is_pure_function(F) ->
{arity,Arity} = erlang:fun_info(F, arity),
ArgsList = [lists:duplicate(Arity,0), lists:duplicate(Arity,1),
lists:seq(1,Arity), lists:seq(0,Arity-1)],
lists:foreach(fun(Args) -> ?assertEqual(apply(F,Args),apply(F,Args)) end,
ArgsList).
%%------------------------------------------------------------------------------
%% Unit test arguments
%%------------------------------------------------------------------------------
simple_types_with_data() ->
[{integer(), [-1,0,1,42,-200], 0, [0.3,someatom,<<1>>], "integer()"},
{integer(7,88), [7,8,87,88,23], 7, [1,90,a], "7..88"},
{integer(0,42), [0,11,42], 0, [-1,43], "0..42"},
{integer(-99,0), [-88,-99,0], 0, [1,-1112], "-99..0"},
{integer(-999,-12), [-34,-999,-12], -12, [0,5], "-999..-12"},
{integer(-99,21), [-98,0,21], 0, [-100], "-99..21"},
{integer(0,0), [0], 0, [1,-1,100,-100], "0..0"},
{pos_integer(), [12,1,444], 1, [-12,0], "pos_integer()"},
{non_neg_integer(), [42,0], 0, [-9,rr], "non_neg_integer()"},
{neg_integer(), [-222,-1], -1, [0,1111], "neg_integer()"},
{float(), [17.65,-1.12], 0.0, [11,atomm,<<>>], "float()"},
{float(7.4,88.0), [7.4,88.0], 7.4, [-1.0,3.2], none},
{float(0.0,42.1), [0.1,42.1], 0.0, [-0.1], none},
{float(-99.9,0.0), [-0.01,-90.0], 0.0, [someatom,-12,-100.0,0.1], none},
{float(-999.08,-12.12), [-12.12,-12.2], -12.12, [-1111.0,1000.0], none},
{float(-71.8,99.0), [-71.8,99.0,0.0,11.1], 0.0, [100.0,-71.9], none},
{float(0.0,0.0), [0.0], 0.0, [0.1,-0.1], none},
{non_neg_float(), [88.8,98.9,0.0], 0.0, [-12,1,-0.01], none},
{atom(), [elvis,'Another Atom',''], '', ["not_an_atom",12,12.2], "atom()"},
{binary(), [<<>>,<<12,21>>], <<>>, [<<1,2:3>>,binary_atom,42], "binary()"},
{binary(3), [<<41,42,43>>], <<0,0,0>>, [<<1,2,3,4>>], "<<_:3>>"},
{binary(0), [<<>>], <<>>, [<<1>>], none},
{bitstring(), [<<>>,<<87,76,65,5:4>>], <<>>, [{12,3},11], "bitstring()"},
{bitstring(18), [<<0,1,2:2>>,<<1,32,123:2>>], <<0,0,0:2>>, [<<12,1,1:3>>],
"<<_:18, _:_*1>>"},
{bitstring(32), [<<120,120,120,120>>], <<0,0,0,0>>, [7,8],
"<<_:32, _:_*1>>"},
{bitstring(0), [<<>>], <<>>, [<<1>>], none},
{list(integer()), [[],[2,42],[0,1,1,2,3,5,8,13,21,34,55,89,144]], [],
[[4,4.2],{12,1},<<12,113>>], "[integer()]"},
{list(atom()), [[on,the,third,day,'of',christmas,my,true,love,sent,to,me]],
[], [['not',1,list,'of',atoms],not_a_list], "[atom()]"},
{list(union([integer(),atom()])), [[3,french,hens,2],[turtle,doves]], [],
[{'and',1}], "[integer() | atom()]"},
{vector(5,atom()), [[partridge,in,a,pear,tree],[a,b,c,d,e]],
['','','','',''], [[a,b,c,d],[a,b,c,d,e,f]], none},
{vector(2,float()), [[0.0,1.1],[4.4,-5.5]], [0.0,0.0], [[1,1]], none},
{vector(0,integer()), [[]], [], [[1],[2]], none},
{union([good,bad,ugly]), [good,bad,ugly], good, [clint,"eastwood"],
"good | bad | ugly"},
{union([integer(),atom()]), [twenty_one,21], 0, ["21",<<21>>],
"integer() | atom()"},
{weighted_union([{10,luck},{20,skill},{15,concentrated_power_of_will},
{5,pleasure},{50,pain},{100,remember_the_name}]),
[skill,pain,pleasure], luck, [clear,20,50], none},
{{integer(0,42),list(atom())}, [{42,[a,b]},{21,[c,de,f]},{0,[]}], {0,[]},
[{-1,[a]},{12},{21,[b,c],12}], "{0..42,[atom()]}"},
{tuple([atom(),integer()]), [{the,1}], {'',0}, [{"a",0.0}],
"{atom(),integer()}"},
{{}, [{}], {}, [[],{1,2}], "{}"},
{loose_tuple(integer()), [{1,44,-1},{},{99,-99}], {}, [4,{hello,2},[1,2]],
none},
{loose_tuple(union([atom(),float()])), [{a,4.4,b},{},{'',c},{1.2,-3.4}],
{}, [an_atom,0.4,{hello,2},[aa,bb,3.1]], none},
{loose_tuple(list(integer())), [{[1,-1],[],[2,3,-12]},{}], {},
[[[1,2],[3,4]],{1,12},{[1,99,0.0],[]}], none},
{loose_tuple(loose_tuple(integer())), [{},{{}},{{1,2},{-1,11},{}}], {},
[{123},[{12},{24}]], none},
{exactly({[writing],unit,[tests,is],{2},boring}),
[{[writing],unit,[tests,is],{2},boring}],
{[writing],unit,[tests,is],{2},boring}, [no,its,'not','!'], none},
{[], [[]], [], [[a],[1,2,3]], "[]"},
{fixed_list([neg_integer(),pos_integer()]), [[-12,32],[-1,1]], [-1,1],
[[0,0]], none},
{[atom(),integer(),atom(),float()], [[forty_two,42,forty_two,42.0]],
['',0,'',0.0], [[proper,is,licensed],[under,the,gpl]], none},
{[42 | list(integer())], [[42],[42,44,22]], [42], [[],[11,12]], none},
{number(), [12,32.3,-9,-77.7], 0, [manolis,papadakis], "number()"},
{boolean(), [true,false], false, [unknown], "boolean()"},
{string(), ["hello","","world"], "", ['hello'], "string()"},
{?LAZY(integer()), [0,2,99], 0, [1.1], "integer()"},
{?LAZY(list(float())), [[0.0,1.2,1.99],[]], [], [1.1,[1,2]], "[float()]"},
{zerostream(10), [[0,0,0],[],[0,0,0,0,0,0,0]], [], [[1,0,0],[0.1]], none},
{?SHRINK(pos_integer(),[0]), [1,12,0], 0, [-1,-9,6.0], none},
{?SHRINK(float(),[integer(),atom()]), [1.0,0.0,someatom,'',42,0], 0,
[<<>>,"hello"], none},
{noshrink(?SHRINK(42,[0,1])), [42,0,1], 42, [-1], "42 | 0 | 1"},
{non_empty(list(integer())), [[1,2,3],[3,42],[11]], [0], [[],[0.1]],
"[integer(),...]"},
{default(42,float()), [4.1,-99.0,0.0,42], 42, [43,44], "42 | float()"},
{?SUCHTHAT(X,non_neg_integer(),X rem 4 =:= 1), [1,5,37,89], 1, [4,-12,11],
none},
{?SUCHTHATMAYBE(X,non_neg_integer(),X rem 4 =:= 1), [1,2,3,4,5,37,89], 0,
[1.1,2.2,-12], "non_neg_integer()"},
{any(), [1,-12,0,99.9,-42.2,0.0,an_atom,'',<<>>,<<1,2>>,<<1,2,3:5>>,[],
[42,<<>>],{},{tag,12},{tag,[vals,12,12.2],[],<<>>}],
0, [], "any()"},
{list(any()), [[<<>>,a,1,-42.0,{11.8,[]}]], [], [{1,aa},<<>>], "[any()]"},
{deeplist(), [[[],[]], [[[]],[]]], [], [[a]], "deeplist()"},
{none, [[234,<<1>>,[<<78>>,[]],0],[]], [], [21,3.1,[7.1],<<22>>],
"iolist()"},
{none, [[234,<<1>>,[<<78>>,[]],0],[],<<21,15>>], <<>>, [21,3.1,[7.1]],
"iodata()"}].
%% TODO: These rely on the intermediate form of the instances.
constructed_types_with_data() ->
[{?LET(X,range(1,5),X*X), [{'$used',1,1},{'$used',5,25}], 1,
[4,{'$used',3,8},{'$used',0,0}], none},
{?LET(L,non_empty(list(atom())),oneof(L)),
[{'$used',[aa],aa},{'$used',[aa,bb],aa},{'$used',[aa,bb],bb}], '',
[{'$used',[],''},{'$used',[aa,bb],cc}], none},
{?LET(X,pos_integer(),?LET(Y,range(0,X),X-Y)),
[{'$used',3,{'$used',2,1}},{'$used',9,{'$used',9,0}},
{'$used',5,{'$used',0,5}}], 1,
[{'$used',0,{'$used',0,0}},{'$used',3,{'$used',4,-1}},
{'$used',7,{'$used',6,2}}], none},
{?LET(Y,?LET(X,integer(),X*X),-Y),
[{'$used',{'$used',-9,81},-81},{'$used',{'$used',2,4},-4}], 0,
[{'$used',{'$used',1,2},-2},{'$used',{'$used',3,9},9}], none},
{?SUCHTHAT(Y,?LET(X,oneof([1,2,3]),X+X),Y>3),
[{'$used',2,4},{'$used',3,6}], 4, [{'$used',1,2}], none},
{?LET(X,?SUCHTHAT(Y,pos_integer(),Y=/=0),X*X),
[{'$used',3,9},{'$used',1,1},{'$used',11,121}], 1,
[{'$used',-1,1},{'$used',0,0}], none},
{tree(integer()), [{'$used',[null,null],{node,42,null,null}},
{'$used',[{'$used',[null,null],{node,2,null,null}},
{'$used',[null,null],{node,3,null,null}}],
{node,-1,{node,2,null,null},{node,3,null,null}}},
{'$to_part',null},
{'$to_part',{'$used',[null,null],{node,7,null,null}}}],
null, [{'$used',[null,null],{node,1.1,null,null}}], "tree(integer())"},
{?LETSHRINK(L,[],{tag,L}), [{'$used',[],{tag,[]}}], {tag,[]}, [], none},
{?LETSHRINK(L,non_empty(list(atom())),{tag,L}),
[{'$used',[aa],{tag,[aa]}},{'$to_part',aa}], '', [], none},
{a(), [aleaf, {'$used',[aleaf],{anode,aleaf,bleaf}},
{'$used',[aleaf],{anode,aleaf,{'$to_part',bleaf}}}],
aleaf, [], "a()"},
{b(), [bleaf, {'$used',[bleaf],{bnode,aleaf,bleaf}},
{'$used',[bleaf],{bnode,{'$to_part',aleaf},bleaf}}],
bleaf, [], "b()"},
{gen_tree(integer()),
[{'$used',[null,null],{12,[null,null]}},{'$to_part',null}],
null, [{'$used',[],{42,[]}}], "gen_tree(integer())"},
{none, [{'$used',[],{tag,[]}}, {'$used',[null,null],{tag,[null,null]}},
{'$used',[{'$used',[],{tag,[]}},{'$to_part',null}],
{tag,[{tag,[]},null]}}, {'$to_part',{'$used',[],{tag,[]}}}],
null, [], "g()"},
{none, [{'$used',[null],{tag,[{ok,null}]}}, {'$to_part',null},
{'$used',[null,null],{tag,[{ok,null},{ok,null}]}}],
null, [], "h()"},
{none, [{'$used',[null,null,{'$used',[null],{tag,null,[]}}],
{tag,null,[null,{tag,null,[]}]}}, {'$to_part',null}],
null, [], "i()"},
{none, [{'$used',[{'$to_part',null},{'$used',[null],{one,null}},null,null],
{tag,null,{one,null},[null,null],[null]}}], null, [], "j()"},
{none, [{tag,[]}, {tag,[{null,null}]},
{tag,[{{tag,[]},null},{null,{tag,[]}}]}],
null, [{'$to_part',null}], "k()"},
{none, [{'$used',[null,null,{'$used',[null,null],{tag,null,[null]}}],
{tag,null,[null,{tag,null,[null]}]}}, {'$to_part',null}],
null, [{'$used',[null],{tag,null,[]}}], "l()"}].
function_types() ->
[{function([],atom()), "fun(() -> atom())"},
{function([integer(),integer()],atom()),
"fun((integer(),integer()) -> atom())"},
{function(5,union([a,b])), "fun((_,_,_,_,_) -> a | b)"},
{function(0,function(1,integer())),
"fun(() -> fun((_) -> integer()))"}].
remote_native_types() ->
[{types_test1,["#rec1{}","rec1()","exp1()","type1()","type2(atom())",
"rem1()","rem2()","types_test1:exp1()",
"types_test2:exp1(float())","types_test2:exp2()"]},
{types_test2,["exp1(#rec1{})","exp2()","#rec1{}","types_test1:exp1()",
"types_test2:exp1(binary())","types_test2:exp2()"]}].
impossible_types() ->
[?SUCHTHAT(X, pos_integer(), X =< 0),
?SUCHTHAT(X, non_neg_integer(), X < 0),
?SUCHTHAT(X, neg_integer(), X >= 0),
?SUCHTHAT(X, integer(1,10), X > 20),
?SUCHTHAT(X, float(0.0,10.0), X < 0.0),
?SUCHTHAT(L, vector(12,integer()), length(L) =/= 12),
?SUCHTHAT(B, binary(), lists:member(256,binary_to_list(B))),
?SUCHTHAT(X, exactly('Lelouch'), X =:= 'vi Brittania')].
impossible_native_types() ->
[{types_test1, ["1.1","no_such_module:type1()","no_such_type()"]},
{types_test2, ["types_test1:type1()","function()","fun((...) -> atom())",
"pid()","port()","ref()"]}].
recursive_native_types() ->
[{rec_test1, ["a()","b()","a()|b()","d()","f()","deeplist()",
"mylist(float())","aa()","bb()","expc()"]},
{rec_test2, ["a()","expa()","rec()"]}].
impossible_recursive_native_types() ->
[{rec_test1, ["c()","e()","cc()","#rec{}","expb()"]},
{rec_test2, ["b()","#rec{}","aa()"]}].
symb_calls() ->
[{[3,2,1], "lists:reverse([1,2,3])", [], {call,lists,reverse,[[1,2,3]]}},
{[a,b,c,d], "erlang:'++'([a,b],[c,d])",
[{a,some_value}], {call,erlang,'++',[[a,b],[c,d]]}},
{42, "erlang:'*'(erlang:'+'(3,3),erlang:'-'(8,1))",
[{b,dummy_value},{e,another_dummy}],
{call,erlang,'*',[{call,erlang,'+',[3,3]},{call,erlang,'-',[8,1]}]}},
{something, "something",
[{a,somebody},{b,put},{c,something},{d,in_my_drink}], {var,c}},
{{var,b}, "{var,b}", [{a,not_this},{c,neither_this}], {var,b}},
{42, "erlang:'+'(40,2)", [{m,40},{n,2}],
{call,erlang,'+',[{var,m},{var,n}]}},
{[i,am,{var,iron},man],
"erlang:'++'(lists:reverse([am,i]),erlang:'++'([{var,iron}],[man]))",
[{a,man},{b,woman}],
{call,erlang,'++',[{call,lists,reverse,[[am,i]]},
{call,erlang,'++',[[{var,iron}],[{var,a}]]}]}}].
undefined_symb_calls() ->
[{call,erlang,error,[an_error]},
{call,erlang,throw,[a_throw]},
{call,erlang,exit,[an_exit]},
{call,lists,reverse,[<<12,13>>]},
{call,erlang,'+',[1,2,3]}].
combinations() ->
[{[{1,[1,3,5,7,9,10]}, {2,[2,4,6,8,11]}], 5, 11, [1,2,3,4,5,6,7,8,9,10,11], 2, 2,
[{1,[1,3,5,7,8,11]}, {2,[2,4,6,9,10]}]},
{[{1,[1,3,5]}, {2,[7,8,9]}, {3,[2,4,6]}], 3, 9, [1,3,5,7,8,9], 3, 2,
[{1,[6,8,9]}, {2,[1,3,5]}, {3,[2,4,7]}]}].
first_comb() -> [{10,3,3,[{1,[7,8,9,10]}, {2,[4,5,6]}, {3,[1,2,3]}]},
{11,5,2,[{1,[6,7,8,9,10,11]}, {2,[1,2,3,4,5]}]},
{12,3,4,[{1,[10,11,12]}, {2,[7,8,9]}, {3,[4,5,6]}, {4,[1,2,3]}]}].
lists_to_zip() ->
[{[],[],[]},
{[], [dummy, atom], []},
{[1, 42, 1, 42, 1, 2 ,3], [], []},
{[a, b, c], lists:seq(1,6), [{a,1}, {b,2}, {c,3}]},
{[a, b, c], lists:seq(1,3), [{a,1}, {b,2}, {c,3}]},
{[a, d, d, d, d], lists:seq(1,3), [{a,1}, {d,2}, {d,3}]}].
command_names() ->
[{[{set,{var,1},{call,erlang,put,[a,0]}},
{set,{var,3},{call,erlang,erase,[a]}},
{set,{var,4},{call,erlang,get,[b]}}],
[{erlang,put,2},
{erlang,erase,1},
{erlang,get,1}]},
{[{set,{var,1},{call,foo,bar,[]}},
{set,{var,2},{call,bar,foo,[a,{var,1}]}},
{set,{var,3},{call,bar,foo,[a,[[3,4]]]}}],
[{foo,bar,0},
{bar,foo,2},
{bar,foo,2}]},
{[],[]}].
valid_command_sequences() ->
%% {module, initial_state, command_sequence, symbolic_state_after,
%% dynamic_state_after,initial_environment}
[{pdict_statem, [], [{init,[]},
{set,{var,1},{call,erlang,put,[a,0]}},
{set,{var,2},{call,erlang,put,[b,1]}},
{set,{var,3},{call,erlang,erase,[a]}},
{set,{var,4},{call,erlang,get,[b]}},
{set,{var,5},{call,erlang,erase,[b]}},
{set,{var,6},{call,erlang,put,[a,4]}},
{set,{var,7},{call,erlang,put,[a,42]}}],
[{a,42}], [{a,42}], []},
{pdict_statem, [], [{init,[]},
{set,{var,1},{call,erlang,put,[b,5]}},
{set,{var,2},{call,erlang,erase,[b]}},
{set,{var,3},{call,erlang,put,[a,5]}}],
[{a,5}], [{a,5}], []},
{pdict_statem, [], [{init,[]},
{set,{var,1},{call,erlang,put,[a,{var,start_value}]}},
{set,{var,2},{call,erlang,put,[b,{var,another_start_value}]}},
{set,{var,3},{call,erlang,get,[b]}},
{set,{var,4},{call,erlang,get,[b]}}],
[{b,{var,another_start_value}}, {a,{var,start_value}}], [{b,-1}, {a, 0}],
[{start_value, 0}, {another_start_value, -1}]}].
symbolic_init_invalid_sequences() ->
%% {module, command_sequence, environment, shrunk}
[{pdict_statem, [{init,[{a,{call,foo,bar,[some_arg]}}]},
{set,{var,1},{call,erlang,put,[b,42]}},
{set,{var,2},{call,erlang,get,[b]}}],
[{some_arg, 0}],
[{init,[{a,{call,foo,bar,[some_arg]}}]}]}].
invalid_precondition() ->
%% {module, command_sequence, environment, shrunk}
[{pdict_statem, [{init,[]},
{set,{var,1},{call,erlang,put,[a,0]}},
{set,{var,2},{call,erlang,put,[b,1]}},
{set,{var,3},{call,erlang,erase,[a]}},
{set,{var,4},{call,erlang,get,[a]}}],
[], [{set,{var,4},{call,erlang,get,[a]}}]}].
invalid_var() ->
[{pdict_statem, [{init,[]},
{set,{var,2},{call,erlang,put,[b,{var,1}]}}]},
{pdict_statem, [{init,[]},
{set,{var,1},{call,erlang,put,[b,9]}},
{set,{var,5},{call,erlang,put,[a,3]}},
{set,{var,6},{call,erlang,get,[{var,2}]}}]}].
arguments_not_defined() ->
[{[simple,atoms,are,valid,{var,42}], []},
{[{var,1}], [{var,2},{var,3},{var,4}]},
{[hello,world,[hello,world,{var,6}]], []},
{[{1,2,3,{var,1},{var,2}},not_really], []},
{[[[[42,{var,42}]]]], []},
{[{43,41,{1,{var,42}}},why_not], []}].
all_data() ->
[1, 42.0, "$hello", "world\n", [smelly, cat, {smells,bad}],
'$this_should_be_copied', '$this_one_too', 'but$ this$ not',
or_this].
dollar_data() ->
['$this_should_be_copied', '$this_one_too'].
%%------------------------------------------------------------------------------
%% Unit tests
%%------------------------------------------------------------------------------
TODO : write tests for old datatypes , use old tests
TODO : check output redirection , quiet , verbose , to_file , on_output/2 ( maybe
%% by writing to a string in the process dictionary), statistics printing,
%% standard verbose behaviour
%% TODO: fix compiler warnings
TODO : LET and LETSHRINK testing ( these need their intermediate form for
%% standalone instance testing and shrinking) - update needed after
%% fixing the internal shrinking in LETs, use recursive datatypes, like
trees , for testing , also test with noshrink and LAZY
TODO : use size=100 for is_instance testing ?
TODO : : check that the same type is returned for consecutive calls ,
%% even with no caching (no_caching option?)
TODO : : recursive types containing functions
TODO : ? LET , ? LETSHRINK : only the top - level base type can be a native type
TODO : Test with native types : ? , noshrink , ? LAZY , ? SHRINK ,
%% resize, ?SIZED
%% TODO: no debug_info at compile time => call, not type
%% no debug_info at runtime => won't find type
%% no module in code path at runtime => won't find type
%% TODO: try some more expressions with a ?FORALL underneath
%% TODO: various constructors like '|' (+ record notation) are parser-rejected
%% TODO: test nonempty recursive lists
%% TODO: test list-recursive with instances
TODO : more ADT tests : check bad declarations , bad variable use , multi - clause ,
is_subtype , unacceptable range , unexported opaque , no - specs opaque ,
%% unexported/unspecced functions, unbound variables, check as constructed
%% TODO: module, check_spec, check_module_specs, retest_spec (long result mode
%% too, other options pass)
%% TODO: proper_typeserver:is_instance (with existing types too, plus types we
%% can't produce, such as impropers) (also check that everything we
%% produce based on a type is an instance)
%% TODO: check that functions that throw exceptions pass
%% TODO: property inside a ?TIMEOUT returning false
%% TODO: some branch of a ?FORALL has a collect while another doesn't
%% TODO: symbolic functions returning functions are evaluated?
%% TODO: pure_check
%% TODO: spec_timeout option
%% TODO: defined option precedence
TODO : conversion of maybe_improper_list
%% TODO: use demo_is_instance and demo_translate_type
%% TODO: debug option to output tests passed, fail reason, etc.
simple_types_test_() ->
[?_test(assert_type_works(TD, true)) || TD <- simple_types_with_data()].
constructed_types_test_() ->
[?_test(assert_type_works(TD, false))
|| TD <- constructed_types_with_data()].
%% TODO: specific test-starting instances would be useful here
%% (start from valid Xs)
shrinks_to_test_() ->
[?_shrinksTo(Target, Type)
|| {Type,_Xs,Target,_Ys,_TypeStr} <- simple_types_with_data()
++ constructed_types_with_data(),
Type =/= none].
native_shrinks_to_test_() ->
[?_nativeShrinksTo(Target, TypeStr)
|| {_Type,_Xs,Target,_Ys,TypeStr} <- simple_types_with_data()
++ constructed_types_with_data(),
TypeStr =/= none].
cant_generate_test_() ->
[?_test(assert_cant_generate(Type)) || Type <- impossible_types()].
native_cant_translate_test_() ->
[?_test(assert_cant_translate(Mod,TypeStr))
|| {Mod,Strings} <- impossible_native_types(), TypeStr <- Strings].
remote_native_types_test_() ->
[?_test(assert_can_translate(Mod,TypeStr))
|| {Mod,Strings} <- remote_native_types(), TypeStr <- Strings].
recursive_native_types_test_() ->
[?_test(assert_native_can_generate(Mod,TypeStr,false))
|| {Mod,Strings} <- recursive_native_types(), TypeStr <- Strings].
recursive_native_cant_translate_test_() ->
[?_test(assert_cant_translate(Mod,TypeStr))
|| {Mod,Strings} <- impossible_recursive_native_types(),
TypeStr <- Strings].
random_functions_test_() ->
[[?_test(assert_function_type_works(FunType)),
?_test(assert_function_type_works(assert_can_translate(proper,TypeStr)))]
|| {FunType,TypeStr} <- function_types()].
parse_transform_test_() ->
[?_passes(auto_export_test1:prop_1()),
?_assertError(undef, auto_export_test2:prop_1()),
?_assertError(undef, no_native_parse_test:prop_1()),
?_assertError(undef, no_out_of_forall_test:prop_1())].
native_type_props_test_() ->
[?_passes(?FORALL({X,Y}, {my_native_type(),my_proper_type()},
is_integer(X) andalso is_atom(Y))),
?_passes(?FORALL([X,Y,Z],
[my_native_type(),my_proper_type(),my_native_type()],
is_integer(X) andalso is_atom(Y) andalso is_integer(Z))),
?_passes(?FORALL([Y,X,{Z,W}],
[my_proper_type() | [my_native_type()]] ++
[{my_native_type(),my_proper_type()}],
is_integer(X) andalso is_atom(Y) andalso is_integer(Z)
andalso is_atom(W))),
?_passes(?FORALL([X|Y], [my_native_type()|my_native_type()],
is_integer(X) andalso is_integer(Y))),
?_passes(?FORALL(X, type_and_fun(), is_atom(X))),
?_passes(?FORALL(X, type_only(), is_integer(X))),
?_passes(?FORALL(L, [integer()], length(L) =:= 1)),
?_fails(?FORALL(L, id([integer()]), length(L) =:= 1)),
?_passes(?FORALL(_, types_test1:exp1(), true)),
?_assertError(undef, ?FORALL(_,types_test1:rec1(),true)),
?_assertError(undef, ?FORALL(_,no_such_module:some_call(),true)),
{setup, fun() -> code:purge(to_remove),
code:delete(to_remove),
code:purge(to_remove),
file:rename("tests/to_remove.beam",
"tests/to_remove.bak") end,
fun(_) -> file:rename("tests/to_remove.bak",
"tests/to_remove.beam") end,
?_passes(?FORALL(_, to_remove:exp1(), true))},
?_passes(rec_props_test1:prop_1()),
?_passes(rec_props_test2:prop_2()),
?_passes(?FORALL(L, vector(2,my_native_type()),
length(L) =:= 2
andalso lists:all(fun erlang:is_integer/1, L))),
?_passes(?FORALL(F, function(0,my_native_type()), is_integer(F()))),
?_passes(?FORALL(X, union([my_proper_type(),my_native_type()]),
is_integer(X) orelse is_atom(X))),
?_assertError(undef, begin
Vector5 = fun(T) -> vector(5,T) end,
?FORALL(V, Vector5(types_test1:exp1()),
length(V) =:= 5)
end),
?_passes(?FORALL(X, ?SUCHTHAT(Y,types_test1:exp1(),is_atom(Y)),
is_atom(X))),
?_passes(?FORALL(L,non_empty(lof()),length(L) > 0)),
?_passes(?FORALL(X, ?LET(L,lof(),lists:min([99999.9|L])),
is_float(X))),
?_shrinksTo(0, ?LETSHRINK([X],[my_native_type()],{'tag',X})),
?_passes(weird_types:prop_export_all_works()),
?_passes(weird_types:prop_no_auto_import_works())].
-record(untyped, {a, b = 12}).
-type untyped() :: #untyped{}.
true_props_test_() ->
[?_passes(?FORALL(X,integer(),X < X + 1)),
?_passes(?FORALL(X,atom(),list_to_atom(atom_to_list(X)) =:= X)),
?_passes(?FORALL(L,list(integer()),is_sorted(L,quicksort(L)))),
?_passes(?FORALL(L,ulist(integer()),is_sorted(L,lists:usort(L)))),
?_passes(?FORALL(L,non_empty(list(integer())),L =/= [])),
?_passes(?FORALL({I,L}, {integer(),list(integer())},
?IMPLIES(no_duplicates(L),
not lists:member(I,lists:delete(I,L))))),
?_passes(?FORALL(L, ?SIZED(Size,resize(Size div 5,list(integer()))),
length(L) =< 20), [{max_size,100}]),
%% TODO: check that the samples are collected correctly
?_passes(?FORALL(L, list(integer()),
collect(length(L), collect(L =:= [],
lists:reverse(lists:reverse(L)) =:= L)))),
?_passes(?FORALL(L, list(integer()),
aggregate(smaller_lengths_than_my_own(L), true))),
?_assertTempBecomesN(300, true,
numtests(300,?FORALL(_,1,begin inc_temp(),true end))),
?_assertTempBecomesN(30, true, ?FORALL(X, ?SIZED(Size,Size),
begin inc_temp(X),true end),
[{numtests,12},{max_size,4}]),
?_assertTempBecomesN(12, true,
?FORALL(X, ?SIZED(Size,Size),
begin inc_temp(X),true end),
[{numtests,3},{start_size,4},{max_size,4}]),
?_passes(?FORALL(X, integer(), ?IMPLIES(abs(X) > 1, X * X > X))),
?_passes(?FORALL(X, integer(), ?IMPLIES(X >= 0, true))),
?_passes(?FORALL({X,Lim}, {int(),?SIZED(Size,Size)}, abs(X) =< Lim)),
?_passes(?FORALL({X,Lim}, {nat(),?SIZED(Size,Size)}, X =< Lim)),
?_passes(?FORALL(L, orderedlist(integer()), is_sorted(L))),
?_passes(conjunction([
{one, ?FORALL(_, integer(), true)},
{two, ?FORALL(X, integer(), collect(X > 0, true))},
{three, conjunction([{a,true},{b,true}])}
])),
?_passes(?FORALL(X, untyped(), is_record(X, untyped))),
?_passes(pdict_statem:prop_pdict()),
?_passes(symb_statem:prop_simple()),
{timeout, 20, ?_passes(symb_statem:prop_parallel_simple())},
{timeout, 10, ?_passes(ets_statem:prop_ets())},
{timeout, 20, ?_passes(ets_statem:prop_parallel_ets())},
{timeout, 20, ?_passes(pdict_fsm:prop_pdict())}].
false_props_test_() ->
[?_failsWith([[_Same,_Same]],
?FORALL(L,list(integer()),is_sorted(L,lists:usort(L)))),
?_failsWith([[_Same,_Same],_Same],
?FORALL(L, non_empty(list(union([a,b,c,d]))),
?FORALL(X, elements(L),
not lists:member(X,lists:delete(X,L))))),
?_failsWith(['\000\000\000\000'],
?FORALL(A, atom(), length(atom_to_list(A)) < 4)),
%% TODO: check that these only run once
?_failsWith([1], ?FORALL(X, non_neg_integer(),
case X > 0 of
true -> throw(not_zero);
false -> true
end)),
?_fails(?FORALL(_,1,lists:min([]) > 0)),
?_failsWith([[12,42]], ?FORALL(L, [12,42|list(integer())],
case lists:member(42, L) of
true -> erlang:exit(you_got_it);
false -> true
end)),
?_fails(?FORALL(_, integer(), ?TIMEOUT(100,timer:sleep(150) =:= ok))),
?_failsWith([20], ?FORALL(X, pos_integer(), ?TRAPEXIT(creator(X) =:= ok))),
?_assertTempBecomesN(7, false,
?FORALL(X, ?SIZED(Size,integer(Size,Size)),
begin inc_temp(), X < 5 end),
[{numtests,5}, {max_size,5}]),
it runs 2 more times : one while shrinking ( recursing into the property )
%% and one when the minimal input is rechecked
?_assertTempBecomesN(2, false,
?FORALL(L, list(atom()),
?WHENFAIL(inc_temp(),length(L) < 5))),
?_assertTempBecomesN(3, false,
?FORALL(S, ?SIZED(Size,Size),
begin inc_temp(), S < 20 end),
[{numtests,3},{max_size,40},noshrink]),
?_failsWithOneOf([[{true,false}],[{false,true}]],
?FORALL({B1,B2}, {boolean(),boolean()}, equals(B1,B2))),
?_failsWith([2,1],
?FORALL(X, integer(1,10), ?FORALL(Y, integer(1,10), X =< Y))),
?_failsWith([1,2],
?FORALL(Y, integer(1,10), ?FORALL(X, integer(1,10), X =< Y))),
?_failsWithOneOf([[[0,1]],[[0,-1]],[[1,0]],[[-1,0]]],
?FORALL(L, list(integer()), lists:reverse(L) =:= L)),
?_failsWith([[1,2,3,4,5,6,7,8,9,10]],
?FORALL(_L, shuffle(lists:seq(1,10)), false)),
%% TODO: check that these don't shrink
?_fails(?FORALL(_, integer(0,0), false)),
?_fails(?FORALL(_, float(0.0,0.0), false)),
?_fails(fails(?FORALL(_, integer(), false))),
?_failsWith([16], ?FORALL(X, ?LET(Y,integer(),Y*Y), X < 15)),
?_failsWith([0.0],
?FORALL(_, ?LETSHRINK([A,B], [float(),atom()], {A,B}), false)),
?_failsWith([], conjunction([{some,true},{thing,false}])),
?_failsWith([{2,1},[{group,[[{sub_group,[1]}]]},{stupid,[1]}]],
?FORALL({X,Y}, {pos_integer(),pos_integer()},
conjunction([
{add_next, ?IMPLIES(X > Y, X + 1 > Y)},
{symmetry,
conjunction([
{add_sym, collect(X+Y, X+Y =:= Y+X)},
{sub_sym,
?WHENFAIL(io:format("'-' isn't symmetric!~n",[]),
X-Y =:= Y-X)}
])},
{group,
conjunction([
{add_group,
?WHENFAIL(io:format("This shouldn't happen!~n",[]),
?FORALL(Z, pos_integer(),
(X+Y)+Z =:= X+(Y+Z)))},
{sub_group,
?WHENFAIL(io:format("'-' doesn't group!~n",[]),
?FORALL(W, pos_integer(),
(X-Y)-W =:= X-(Y-W)))}
])},
{stupid, ?FORALL(_, pos_integer(), throw(woot))}
]))),
{timeout, 20, ?_fails(ets_counter:prop_ets_counter())},
?_fails(post_false:prop_simple()),
?_fails(error_statem:prop_simple())].
error_props_test_() ->
[?_errorsOut(cant_generate,
?FORALL(_, ?SUCHTHAT(X, pos_integer(), X =< 0), true)),
?_errorsOut(cant_satisfy,
?FORALL(X, pos_integer(), ?IMPLIES(X =< 0, true))),
?_errorsOut(type_mismatch,
?FORALL({X,Y}, [integer(),integer()], X < Y)),
?_assertCheck({error,rejected}, [2],
?FORALL(X, integer(), ?IMPLIES(X > 5, X < 6))),
?_assertCheck({error,too_many_instances}, [1,ab],
?FORALL(X, pos_integer(), X < 0)),
?_errorsOut(cant_generate, prec_false:prop_simple()),
?_errorsOut(cant_generate, nogen_statem:prop_simple()),
?_errorsOut(non_boolean_result, ?FORALL(_, integer(), not_a_boolean)),
?_errorsOut(non_boolean_result,
?FORALL(_, ?SHRINK(42,[0]),
non_deterministic([{2,false},{1,not_a_boolean}]))),
?_assertRun(false,
?FORALL(_, ?SHRINK(42,[0]),
non_deterministic([{4,false},{1,true}])),
[], false),
?_assertRun(false,
?FORALL(_, ?SHRINK(42,[0]),
non_deterministic([{3,false},{1,true},{1,false}])),
[], false)].
eval_test_() ->
[?_assertEqual(Result, eval(Vars,SymbCall))
|| {Result,_Repr,Vars,SymbCall} <- symb_calls()].
pretty_print_test_() ->
[?_assert(equal_ignoring_ws(Repr, proper_symb:pretty_print(Vars,SymbCall)))
|| {_Result,Repr,Vars,SymbCall} <- symb_calls()].
not_defined_test_() ->
[?_assertNot(defined(SymbCall))
|| SymbCall <- undefined_symb_calls()].
options_test_() ->
[?_assertTempBecomesN(300, true,
?FORALL(_, 1, begin inc_temp(), true end),
[{numtests,300}]),
?_assertTempBecomesN(300, true,
?FORALL(_, 1, begin inc_temp(), true end),
[300]),
?_failsWith([42], ?FORALL(_,?SHRINK(42,[0,1]),false), [noshrink]),
?_failsWith([42], ?FORALL(_,?SHRINK(42,[0,1]),false), [{max_shrinks,0}]),
?_fails(?FORALL(_,integer(),false), [fails]),
?_assertRun({error,cant_generate},
?FORALL(_,?SUCHTHAT(X,pos_integer(),X > 0),true),
[{constraint_tries,0}], true),
?_failsWith([12],
?FORALL(_,?SIZED(Size,integer(Size,Size)),false),
[{start_size,12}])].
adts_test_() ->
for ' old laptop
?_passes(?FORALL({X,S},{integer(),set()},
sets:is_element(X,sets:add_element(X,S))), [20])},
?_passes(?FORALL({X,Y,D},
{integer(),float(),dict(integer(),float())},
dict:fetch(X,dict:store(X,Y,eval(D))) =:= Y), [30]),
?_fails(?FORALL({X,D},
{boolean(),dict(boolean(),integer())},
dict:erase(X, dict:store(X,42,D)) =:= D))].
parameter_test_() ->
?_passes(?FORALL(List, [zero1(),zero2(),zero3(),zero4()],
begin
[?assertMatch(undefined, proper_types:parameter(P))
|| P <- [x1,x2,y2,x3,y3,x4,y4,v,w,z]],
lists:all(fun is_zero/1, List)
end)).
zip_test_() ->
[?_assertEqual(proper_statem:zip(X, Y), Expected)
|| {X,Y,Expected} <- lists_to_zip()].
command_names_test_() ->
[?_assertEqual(proper_statem:command_names(Cmds), Expected)
|| {Cmds,Expected} <- command_names()].
valid_cmds_test_() ->
[?_assert(proper_statem:is_valid(Mod, State, Cmds, Env))
|| {Mod,State,Cmds,_,_,Env} <- valid_command_sequences()].
invalid_cmds_test_() ->
[?_assertNot(proper_statem:is_valid(Mod, Mod:initial_state(), Cmds, []))
|| {Mod,Cmds,_,_} <- invalid_precondition()] ++
[?_assertNot(proper_statem:is_valid(Mod, Mod:initial_state(), Cmds, []))
|| {Mod,Cmds} <- invalid_var()].
state_after_test_() ->
[?_assertEqual(proper_statem:state_after(Mod, Cmds), StateAfter)
|| {Mod,_,Cmds,StateAfter,_,_} <- valid_command_sequences()].
cannot_generate_commands_test_() ->
[?_test(assert_cant_generate_cmds(proper_statem:commands(Mod), 6))
|| Mod <- [prec_false]].
can_generate_commands0_test_() ->
[?_test(assert_can_generate(proper_statem:commands(Mod), false))
|| Mod <- [pdict_statem]].
can_generate_commands1_test_() ->
[?_test(assert_can_generate(proper_statem:commands(Mod, StartState), false))
|| {Mod,StartState} <- [{pdict_statem,[{a,1},{b,1},{c,100}]}]].
can_generate_parallel_commands0_test_() ->
{timeout, 20,
[?_test(assert_can_generate(proper_statem:parallel_commands(Mod), false))
|| Mod <- [ets_counter]]}.
can_generate_parallel_commands1_test_() ->
{timeout, 20,
[?_test(assert_can_generate(
proper_statem:parallel_commands(Mod, Mod:initial_state()),
false))
|| Mod <- [ets_counter]]}.
run_valid_commands_test_() ->
[?_assertMatch({_H,DynState,ok}, setup_run_commands(Mod, Cmds, Env))
|| {Mod,_,Cmds,_,DynState,Env} <- valid_command_sequences()].
run_invalid_precondition_test_() ->
[?_assertMatch({_H,_S,{precondition,false}},
setup_run_commands(Mod, Cmds, Env))
|| {Mod,Cmds,Env,_Shrunk} <- invalid_precondition()].
run_init_error_test_() ->
[?_assertMatch({_H,_S,initialization_error},
setup_run_commands(Mod, Cmds, Env))
|| {Mod,Cmds,Env,_Shrunk} <- symbolic_init_invalid_sequences()].
run_postcondition_false() ->
?_assertMatch({_H,_S,{postcondition,false}},
run_commands(post_false, proper_statem:commands(post_false))).
run_exception() ->
?_assertMatch(
{_H,_S,{exception,throw,badarg,_}},
run_commands(post_false, proper_statem:commands(error_statem))).
get_next_test_() ->
[?_assertEqual(Expected,
proper_statem:get_next(L, Len, MaxIndex, Available, W, N))
|| {L, Len, MaxIndex, Available, W, N, Expected} <- combinations()].
mk_first_comb_test_() ->
[?_assertEqual(Expected, proper_statem:mk_first_comb(N, Len, W))
|| {N, Len, W, Expected} <- first_comb()].
args_not_defined_test() ->
[?_assertNot(proper_statem:args_defined(Args, SymbEnv))
|| {Args,SymbEnv} <- arguments_not_defined()].
command_props_test_() ->
{timeout, 150, [?_assertEqual([], proper:module(command_props, 50))]}.
%% TODO: is_instance check fails because of ?LET in fsm_commands/1?
can_generate_fsm_commands_test_() ->
[?_test(assert_can_generate(proper_fsm:commands(Mod), false))
|| Mod <- [pdict_fsm, numbers_fsm]].
transition_target_test_() ->
{timeout, 20, [?_assertEqual([], proper:module(numbers_fsm))]}.
dollar_only_cp_test_() ->
?_assertEqual(
dollar_data(),
[K || K <- all_data(),
is_atom(K),
re:run(atom_to_list(K), ["^[$]"], [{capture,none}]) =:= match]).
%%------------------------------------------------------------------------------
%% Helper Predicates
%%------------------------------------------------------------------------------
no_duplicates(L) ->
length(lists:usort(L)) =:= length(L).
is_sorted([]) -> true;
is_sorted([_]) -> true;
is_sorted([A | [B|_] = T]) when A =< B -> is_sorted(T);
is_sorted(_) -> false.
same_elements(L1, L2) ->
length(L1) =:= length(L2) andalso same_elems(L1, L2).
same_elems([], []) ->
true;
same_elems([H|T], L) ->
lists:member(H, L) andalso same_elems(T, lists:delete(H, L));
same_elems(_, _) ->
false.
is_sorted(Old, New) ->
same_elements(Old, New) andalso is_sorted(New).
equal_ignoring_ws(Str1, Str2) ->
WhiteSpace = [32,9,10],
equal_ignoring_chars(Str1, Str2, WhiteSpace).
equal_ignoring_chars([], [], _Ignore) ->
true;
equal_ignoring_chars([_SameChar|Rest1], [_SameChar|Rest2], Ignore) ->
equal_ignoring_chars(Rest1, Rest2, Ignore);
equal_ignoring_chars([Char1|Rest1] = Str1, [Char2|Rest2] = Str2, Ignore) ->
case lists:member(Char1, Ignore) of
true ->
equal_ignoring_chars(Rest1, Str2, Ignore);
false ->
case lists:member(Char2, Ignore) of
true ->
equal_ignoring_chars(Str1, Rest2, Ignore);
false ->
false
end
end.
smaller_lengths_than_my_own(L) ->
lists:seq(0,length(L)).
is_zero(X) -> X =:= 0.
%%------------------------------------------------------------------------------
%% Functions to test
%%------------------------------------------------------------------------------
partition(Pivot, List) ->
partition_tr(Pivot, List, [], []).
partition_tr(_Pivot, [], Lower, Higher) ->
{Lower, Higher};
partition_tr(Pivot, [H|T], Lower, Higher) ->
if
H =< Pivot -> partition_tr(Pivot, T, [H|Lower], Higher);
H > Pivot -> partition_tr(Pivot, T, Lower, [H|Higher])
end.
quicksort([]) -> [];
quicksort([H|T]) ->
{Lower, Higher} = partition(H, T),
quicksort(Lower) ++ [H] ++ quicksort(Higher).
creator(X) ->
Self = self(),
spawn_link(fun() -> destroyer(X,Self) end),
receive
_ -> ok
end.
destroyer(X, Father) ->
if
X < 20 -> Father ! not_yet;
true -> exit(this_is_the_end)
end.
%%------------------------------------------------------------------------------
Datatypes to test
%%------------------------------------------------------------------------------
%% TODO: remove this if you make 'shuffle' a default constructor
shuffle([]) ->
[];
shuffle(L) ->
?LET(X, elements(L), [X | shuffle(lists:delete(X,L))]).
ulist(ElemType) ->
?LET(L, list(ElemType), L--(L--lists:usort(L))).
zerostream(ExpectedMeanLen) ->
?LAZY(frequency([
{1, []},
{ExpectedMeanLen, [0 | zerostream(ExpectedMeanLen)]}
])).
-type my_native_type() :: integer().
my_proper_type() -> atom().
-type type_and_fun() :: integer().
type_and_fun() -> atom().
-type type_only() :: integer().
-type id(X) :: X.
-type lof() :: [float()].
-type deeplist() :: [deeplist()].
deeplist() ->
?SIZED(Size, deeplist(Size)).
deeplist(0) ->
[];
deeplist(Size) ->
?LAZY(proper_types:distlist(Size, fun deeplist/1, false)).
-type tree(T) :: 'null' | {'node',T,tree(T),tree(T)}.
tree(ElemType) ->
?SIZED(Size, tree(ElemType,Size)).
tree(_ElemType, 0) ->
null;
tree(ElemType, Size) ->
LeftTree = tree(ElemType, Size div 2),
RightTree = tree(ElemType, Size div 2),
frequency([
{1, tree(ElemType,0)},
{5, ?LETSHRINK([L,R], [LeftTree,RightTree], {node,ElemType,L,R})}
]).
-type a() :: 'aleaf' | {'anode',a(),b()}.
-type b() :: 'bleaf' | {'bnode',a(),b()}.
a() ->
?SIZED(Size, a(Size)).
a(0) ->
aleaf;
a(Size) ->
union([
?LAZY(a(0)),
?LAZY(?LETSHRINK([A], [a(Size div 2)], {anode,A,b(Size)}))
]).
b() ->
?SIZED(Size, b(Size)).
b(0) ->
bleaf;
b(Size) ->
union([
?LAZY(b(0)),
?LAZY(?LETSHRINK([B], [b(Size div 2)], {bnode,a(Size),B}))
]).
-type gen_tree(T) :: 'null' | {T,[gen_tree(T),...]}.
gen_tree(ElemType) ->
?SIZED(Size, gen_tree(ElemType,Size)).
gen_tree(_ElemType, 0) ->
null;
gen_tree(ElemType, Size) ->
SubGen = fun(S) -> gen_tree(ElemType,S) end,
oneof([
?LAZY(gen_tree(ElemType,0)),
?LAZY(?LETSHRINK(Children, proper_types:distlist(Size, SubGen, true),
{ElemType,Children}))
]).
-type g() :: 'null' | {'tag',[g()]}.
-type h() :: 'null' | {'tag',[{'ok',h()}]}.
-type i() :: 'null' | {'tag',i(),[i()]}.
-type j() :: 'null' | {'one',j()} | {'tag',j(),j(),[j()],[j()]}.
-type k() :: 'null' | {'tag',[{k(),k()}]}.
-type l() :: 'null' | {'tag',l(),[l(),...]}.
zero1() ->
proper_types:with_parameter(
x1, 0, ?SUCHTHAT(I, range(-1, 1), I =:= proper_types:parameter(x1))).
zero2() ->
proper_types:with_parameters(
[{x2,41}],
?LET(X,
proper_types:with_parameter(
y2, 43,
?SUCHTHAT(
I, range(41, 43),
I > proper_types:parameter(x2)
andalso I < proper_types:parameter(y2))),
X - 42)).
zero3() ->
?SUCHTHAT(I, range(-1, 1),
I > proper_types:parameter(x3, -1)
andalso I < proper_types:parameter(y3, 1)).
zero4() ->
proper_types:with_parameters(
[{x4,-2}, {y4,2}],
proper_types:with_parameters(
[{x4,-1}, {y4,1}],
?SUCHTHAT(I, range(-1, 1),
I > proper_types:parameter(x4)
andalso I < proper_types:parameter(y4)))).
%%------------------------------------------------------------------------------
%% Old Tests and datatypes
%%------------------------------------------------------------------------------
% nelist(ElemType) ->
% [ElemType | list(ElemType)].
%
% uvector(0, _ElemType) ->
% [];
% uvector(N, ElemType) ->
% ?LET(Rest,
% uvector(N-1, ElemType),
% ?LET(Elem,
? , ElemType , not lists : member(E , Rest ) ) ,
% [Elem | Rest])).
%
% subset(Generators) ->
? ,
% [{boolean(),G} || G <- Generators],
% [G || {true,G} <- Keep]).
%
% unique(ElemTypes) ->
% ?LET(Values,
% list(ElemTypes),
% lists:usort(Values)).
%
% ulist2(ElemType) ->
? SUCHTHAT(L , list(ElemType ) , no_duplicates(L ) ) .
%
kvlist(KeyType , ValueType ) - >
% ?LET(Keys,
% list(KeyType),
[ { K , ValueType } || K < - Keys ] ) .
%
% tree_member(_X, {node,_X,_L,_R}) -> true;
% tree_member(X, {node,_Y,L,R}) -> tree_member(X, L) orelse tree_member(X, R);
% tree_member(_X, {empty}) -> false.
%
symbdict(KeyType , ValueType ) - >
? SIZED(Size , symbdict(Size , KeyType , ValueType ) ) .
%
symbdict(0 , _ KeyType , _ ValueType ) - >
% {call,dict,new,[]};
symbdict(Size , KeyType , ValueType ) - >
% ?LAZY(
% frequency([
{ 1,symbdict(0 , KeyType , ValueType ) } ,
{ 4,?LETSHRINK([Smaller ] , [ symbdict(Size - 1 , KeyType , ValueType ) ] ,
{ call , dict , append,[KeyType , ValueType , Smaller ] } ) }
% ])
% ).
%
% test(15) ->
% ?FORALL(T,
? ,
% non_empty(list(integer())),
% ?LET(Y,
% elements(L),
% {Y,L})),
erlang : element(1,T ) = /= 42 ) ;
% test(18) ->
? FORALL(L , kvlist(atom(),integer ( ) ) , not lists : ) ) ;
% test(19) ->
% ?FORALL(T, tree(integer()), not tree_member(42, T));
% test(20) ->
% ?FORALL(X,
? , non_empty(list(integer ( ) ) ) , list(oneof(L ) ) ) ,
length(X ) < 10 ) ;
% test(27) ->
% ?FORALL(SD,
% symbdict(integer(),integer()),
not dict : is_key(42 , eval(SD ) ) ) ;
% test(29) ->
? , L } ,
% {function(1,integer(1,100)), list(integer())},
lists : all(fun(X ) - > F(X ) = /= 42 end , L ) ) ;
correct_smaller_length_aggregation(Tests , ) - >
{ Zeros , Larger } = lists : partition(fun(X ) - > X = : = 0 end , ) ,
% length(Zeros) =:= Tests
andalso correct_smaller_length_aggregation(Tests , Larger , 1 ) .
%
correct_smaller_length_aggregation(0 , SmallerLens , _
% SmallerLens =:= [];
correct_smaller_length_aggregation(NotMoreThan , SmallerLens , ) - >
{ Lens , Larger } = lists : partition(fun(X ) - > X = : = , ) ,
% Num = length(Lens),
% Num =< NotMoreThan
% andalso correct_smaller_length_aggregation(Num, Larger, Len+1).
| null | https://raw.githubusercontent.com/2600hz-archive/whistle/1a256604f0d037fac409ad5a55b6b17e545dcbf9/lib/proper-1.0/test/proper_tests.erl | erlang |
PropEr is free software: you can redistribute it and/or modify
(at your option) any later version.
PropEr 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 PropEr. If not, see </>.
@version {@version}
application to compile it.
------------------------------------------------------------------------------
Helper macros
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Helper Functions
------------------------------------------------------------------------------
TODO: this isn't exception-safe
------------------------------------------------------------------------------
Unit test arguments
------------------------------------------------------------------------------
TODO: These rely on the intermediate form of the instances.
{module, initial_state, command_sequence, symbolic_state_after,
dynamic_state_after,initial_environment}
{module, command_sequence, environment, shrunk}
{module, command_sequence, environment, shrunk}
------------------------------------------------------------------------------
Unit tests
------------------------------------------------------------------------------
by writing to a string in the process dictionary), statistics printing,
standard verbose behaviour
TODO: fix compiler warnings
standalone instance testing and shrinking) - update needed after
fixing the internal shrinking in LETs, use recursive datatypes, like
even with no caching (no_caching option?)
resize, ?SIZED
TODO: no debug_info at compile time => call, not type
no debug_info at runtime => won't find type
no module in code path at runtime => won't find type
TODO: try some more expressions with a ?FORALL underneath
TODO: various constructors like '|' (+ record notation) are parser-rejected
TODO: test nonempty recursive lists
TODO: test list-recursive with instances
unexported/unspecced functions, unbound variables, check as constructed
TODO: module, check_spec, check_module_specs, retest_spec (long result mode
too, other options pass)
TODO: proper_typeserver:is_instance (with existing types too, plus types we
can't produce, such as impropers) (also check that everything we
produce based on a type is an instance)
TODO: check that functions that throw exceptions pass
TODO: property inside a ?TIMEOUT returning false
TODO: some branch of a ?FORALL has a collect while another doesn't
TODO: symbolic functions returning functions are evaluated?
TODO: pure_check
TODO: spec_timeout option
TODO: defined option precedence
TODO: use demo_is_instance and demo_translate_type
TODO: debug option to output tests passed, fail reason, etc.
TODO: specific test-starting instances would be useful here
(start from valid Xs)
TODO: check that the samples are collected correctly
TODO: check that these only run once
and one when the minimal input is rechecked
TODO: check that these don't shrink
TODO: is_instance check fails because of ?LET in fsm_commands/1?
------------------------------------------------------------------------------
Helper Predicates
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Functions to test
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
TODO: remove this if you make 'shuffle' a default constructor
------------------------------------------------------------------------------
Old Tests and datatypes
------------------------------------------------------------------------------
nelist(ElemType) ->
[ElemType | list(ElemType)].
uvector(0, _ElemType) ->
[];
uvector(N, ElemType) ->
?LET(Rest,
uvector(N-1, ElemType),
?LET(Elem,
[Elem | Rest])).
subset(Generators) ->
[{boolean(),G} || G <- Generators],
[G || {true,G} <- Keep]).
unique(ElemTypes) ->
?LET(Values,
list(ElemTypes),
lists:usort(Values)).
ulist2(ElemType) ->
?LET(Keys,
list(KeyType),
tree_member(_X, {node,_X,_L,_R}) -> true;
tree_member(X, {node,_Y,L,R}) -> tree_member(X, L) orelse tree_member(X, R);
tree_member(_X, {empty}) -> false.
{call,dict,new,[]};
?LAZY(
frequency([
])
).
test(15) ->
?FORALL(T,
non_empty(list(integer())),
?LET(Y,
elements(L),
{Y,L})),
test(18) ->
test(19) ->
?FORALL(T, tree(integer()), not tree_member(42, T));
test(20) ->
?FORALL(X,
test(27) ->
?FORALL(SD,
symbdict(integer(),integer()),
test(29) ->
{function(1,integer(1,100)), list(integer())},
length(Zeros) =:= Tests
SmallerLens =:= [];
Num = length(Lens),
Num =< NotMoreThan
andalso correct_smaller_length_aggregation(Num, Larger, Len+1). | Copyright 2010 - 2011 < > ,
< >
and < >
This file is part of PropEr .
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
2010 - 2011 , and
@author
@doc This modules contains PropEr 's Unit tests . You need the EUnit
-module(proper_tests).
-include("proper.hrl").
-include_lib("eunit/include/eunit.hrl").
NOTE : Never add long_result to Opts for these macros .
state_is_clean() ->
get() =:= [].
assertEqualsOneOf(_X, none) ->
ok;
assertEqualsOneOf(X, List) ->
?assert(lists:any(fun(Y) -> Y =:= X end, List)).
-define(_passes(Test),
?_passes(Test, [])).
-define(_passes(Test, Opts),
?_assertRun(true, Test, Opts, true)).
-define(_errorsOut(ExpReason, Test),
?_errorsOut(ExpReason, Test, [])).
-define(_errorsOut(ExpReason, Test, Opts),
?_assertRun({error,ExpReason}, Test, Opts, true)).
-define(_assertRun(ExpResult, Test, Opts, AlsoLongResult),
?_test(begin
?assertMatch(ExpResult, proper:quickcheck(Test,Opts)),
proper:clean_garbage(),
?assert(state_is_clean()),
case AlsoLongResult of
true ->
?assertMatch(ExpResult,
proper:quickcheck(Test,[long_result|Opts])),
proper:clean_garbage(),
?assert(state_is_clean());
false ->
ok
end
end)).
-define(_assertCheck(ExpShortResult, CExm, Test),
?_assertCheck(ExpShortResult, CExm, Test, [])).
-define(_assertCheck(ExpShortResult, CExm, Test, Opts),
?_test(?assertCheck(ExpShortResult, CExm, Test, Opts))).
-define(assertCheck(ExpShortResult, CExm, Test, Opts),
begin
?assertMatch(ExpShortResult, proper:check(Test,CExm,Opts)),
?assert(state_is_clean())
end).
-define(_fails(Test),
?_fails(Test, [])).
-define(_fails(Test, Opts),
?_failsWith(_, Test, Opts)).
-define(_failsWith(ExpCExm, Test),
?_failsWith(ExpCExm, Test, [])).
-define(_failsWith(ExpCExm, Test, Opts),
?_assertFailRun(ExpCExm, none, Test, Opts)).
-define(_failsWithOneOf(AllCExms, Test),
?_failsWithOneOf(AllCExms, Test, [])).
-define(_failsWithOneOf(AllCExms, Test, Opts),
?_assertFailRun(_, AllCExms, Test, Opts)).
-define(SHRINK_TEST_OPTS, [{start_size,10},{max_shrinks,10000}]).
-define(_shrinksTo(ExpShrunk, Type),
?_assertFailRun([ExpShrunk], none, ?FORALL(_X,Type,false),
?SHRINK_TEST_OPTS)).
-define(_shrinksToOneOf(AllShrunk, Type),
?_assertFailRun(_, [[X] || X <- AllShrunk], ?FORALL(_X,Type,false),
?SHRINK_TEST_OPTS)).
-define(_nativeShrinksTo(ExpShrunk, TypeStr),
?_assertFailRun([ExpShrunk], none,
?FORALL(_X,assert_can_translate(?MODULE,TypeStr),false),
?SHRINK_TEST_OPTS)).
-define(_nativeShrinksToOneOf(AllShrunk, TypeStr),
?_assertFailRun(_, [[X] || X <- AllShrunk],
?FORALL(_X,assert_can_translate(?MODULE,TypeStr),false),
?SHRINK_TEST_OPTS)).
-define(_assertFailRun(ExpCExm, AllCExms, Test, Opts),
?_test(begin
ShortResult = proper:quickcheck(Test, Opts),
CExm1 = get_cexm(),
?checkCExm(CExm1, ExpCExm, AllCExms, Test, Opts),
?assertEqual(false, ShortResult),
LongResult = proper:quickcheck(Test, [long_result|Opts]),
CExm2 = get_cexm(),
?checkCExm(CExm2, ExpCExm, AllCExms, Test, Opts),
?checkCExm(LongResult, ExpCExm, AllCExms, Test, Opts)
end)).
get_cexm() ->
CExm = proper:counterexample(),
proper:clean_garbage(),
?assert(state_is_clean()),
CExm.
-define(checkCExm(CExm, ExpCExm, AllCExms, Test, Opts),
begin
?assertCheck(false, CExm, Test, Opts),
?assertMatch(ExpCExm, CExm),
assertEqualsOneOf(CExm, AllCExms)
end).
-define(_assertTempBecomesN(N, ExpShortResult, Prop),
?_assertTempBecomesN(N, ExpShortResult, Prop, [])).
-define(_assertTempBecomesN(N, ExpShortResult, Prop, Opts),
?_test(begin
?assertMatch(ExpShortResult, proper:quickcheck(Prop,Opts)),
?assertEqual(N, get_temp()),
erase_temp(),
proper:clean_garbage(),
?assert(state_is_clean())
end)).
inc_temp() ->
inc_temp(1).
inc_temp(Inc) ->
case get(temp) of
undefined -> put(temp, Inc);
X -> put(temp, X + Inc)
end,
ok.
get_temp() ->
get(temp).
erase_temp() ->
erase(temp),
ok.
non_deterministic(Behaviour) ->
inc_temp(),
N = get_temp(),
{MustReset,Result} = get_result(N, 0, Behaviour),
case MustReset of
true -> erase_temp();
false -> ok
end,
Result.
get_result(N, Sum, [{M,Result}]) ->
{N >= Sum + M, Result};
get_result(N, Sum, [{M,Result} | Rest]) ->
NewSum = Sum + M,
case N =< NewSum of
true -> {false, Result};
false -> get_result(N, NewSum, Rest)
end.
setup_run_commands(Module, Cmds, Env) ->
Module:set_up(),
Res = proper_statem:run_commands(Module, Cmds, Env),
Module:clean_up(),
Res.
assert_type_works({Type,Are,_Target,Arent,TypeStr}, IsSimple) ->
case Type of
none ->
ok;
_ ->
lists:foreach(fun(X) -> assert_is_instance(X,Type) end, Are),
assert_can_generate(Type, IsSimple),
lists:foreach(fun(X) -> assert_not_is_instance(X,Type) end, Arent)
end,
case TypeStr of
none ->
ok;
_ ->
TransType = assert_can_translate(?MODULE, TypeStr),
lists:foreach(fun(X) -> assert_is_instance(X,TransType) end, Are),
assert_can_generate(TransType, IsSimple),
lists:foreach(fun(X) -> assert_not_is_instance(X,TransType) end,
Arent)
end.
assert_can_translate(Mod, TypeStr) ->
proper_typeserver:start(),
Type = {Mod,TypeStr},
Result1 = proper_typeserver:translate_type(Type),
Result2 = proper_typeserver:translate_type(Type),
proper_typeserver:stop(),
?assert(state_is_clean()),
{ok,Type1} = Result1,
{ok,Type2} = Result2,
?assert(proper_types:equal_types(Type1,Type2)),
Type1.
assert_cant_translate(Mod, TypeStr) ->
proper_typeserver:start(),
Result = proper_typeserver:translate_type({Mod,TypeStr}),
proper_typeserver:stop(),
?assert(state_is_clean()),
?assertMatch({error,_}, Result).
TODO : after fixing the , use generic reverse function .
assert_is_instance(X, Type) ->
?assert(proper_types:is_inst(X, Type) andalso state_is_clean()).
assert_can_generate(Type, CheckIsInstance) ->
lists:foreach(fun(Size) -> try_generate(Type,Size,CheckIsInstance) end,
[1,2,5,10,20,40,50]).
try_generate(Type, Size, CheckIsInstance) ->
{ok,Instance} = proper_gen:pick(Type, Size),
?assert(state_is_clean()),
case CheckIsInstance of
true -> assert_is_instance(Instance, Type);
false -> ok
end.
assert_native_can_generate(Mod, TypeStr, CheckIsInstance) ->
assert_can_generate(assert_can_translate(Mod,TypeStr), CheckIsInstance).
assert_cant_generate(Type) ->
?assertEqual(error, proper_gen:pick(Type)),
?assert(state_is_clean()).
assert_cant_generate_cmds(Type, N) ->
?assertEqual(error, proper_gen:pick(?SUCHTHAT(T, Type, length(T) > N))),
?assert(state_is_clean()).
assert_not_is_instance(X, Type) ->
?assert(not proper_types:is_inst(X, Type) andalso state_is_clean()).
assert_function_type_works(FunType) ->
{ok,F} = proper_gen:pick(FunType),
?assert(proper_types:is_instance(F, FunType)),
assert_is_pure_function(F),
proper:global_state_erase(),
?assert(state_is_clean()).
assert_is_pure_function(F) ->
{arity,Arity} = erlang:fun_info(F, arity),
ArgsList = [lists:duplicate(Arity,0), lists:duplicate(Arity,1),
lists:seq(1,Arity), lists:seq(0,Arity-1)],
lists:foreach(fun(Args) -> ?assertEqual(apply(F,Args),apply(F,Args)) end,
ArgsList).
simple_types_with_data() ->
[{integer(), [-1,0,1,42,-200], 0, [0.3,someatom,<<1>>], "integer()"},
{integer(7,88), [7,8,87,88,23], 7, [1,90,a], "7..88"},
{integer(0,42), [0,11,42], 0, [-1,43], "0..42"},
{integer(-99,0), [-88,-99,0], 0, [1,-1112], "-99..0"},
{integer(-999,-12), [-34,-999,-12], -12, [0,5], "-999..-12"},
{integer(-99,21), [-98,0,21], 0, [-100], "-99..21"},
{integer(0,0), [0], 0, [1,-1,100,-100], "0..0"},
{pos_integer(), [12,1,444], 1, [-12,0], "pos_integer()"},
{non_neg_integer(), [42,0], 0, [-9,rr], "non_neg_integer()"},
{neg_integer(), [-222,-1], -1, [0,1111], "neg_integer()"},
{float(), [17.65,-1.12], 0.0, [11,atomm,<<>>], "float()"},
{float(7.4,88.0), [7.4,88.0], 7.4, [-1.0,3.2], none},
{float(0.0,42.1), [0.1,42.1], 0.0, [-0.1], none},
{float(-99.9,0.0), [-0.01,-90.0], 0.0, [someatom,-12,-100.0,0.1], none},
{float(-999.08,-12.12), [-12.12,-12.2], -12.12, [-1111.0,1000.0], none},
{float(-71.8,99.0), [-71.8,99.0,0.0,11.1], 0.0, [100.0,-71.9], none},
{float(0.0,0.0), [0.0], 0.0, [0.1,-0.1], none},
{non_neg_float(), [88.8,98.9,0.0], 0.0, [-12,1,-0.01], none},
{atom(), [elvis,'Another Atom',''], '', ["not_an_atom",12,12.2], "atom()"},
{binary(), [<<>>,<<12,21>>], <<>>, [<<1,2:3>>,binary_atom,42], "binary()"},
{binary(3), [<<41,42,43>>], <<0,0,0>>, [<<1,2,3,4>>], "<<_:3>>"},
{binary(0), [<<>>], <<>>, [<<1>>], none},
{bitstring(), [<<>>,<<87,76,65,5:4>>], <<>>, [{12,3},11], "bitstring()"},
{bitstring(18), [<<0,1,2:2>>,<<1,32,123:2>>], <<0,0,0:2>>, [<<12,1,1:3>>],
"<<_:18, _:_*1>>"},
{bitstring(32), [<<120,120,120,120>>], <<0,0,0,0>>, [7,8],
"<<_:32, _:_*1>>"},
{bitstring(0), [<<>>], <<>>, [<<1>>], none},
{list(integer()), [[],[2,42],[0,1,1,2,3,5,8,13,21,34,55,89,144]], [],
[[4,4.2],{12,1},<<12,113>>], "[integer()]"},
{list(atom()), [[on,the,third,day,'of',christmas,my,true,love,sent,to,me]],
[], [['not',1,list,'of',atoms],not_a_list], "[atom()]"},
{list(union([integer(),atom()])), [[3,french,hens,2],[turtle,doves]], [],
[{'and',1}], "[integer() | atom()]"},
{vector(5,atom()), [[partridge,in,a,pear,tree],[a,b,c,d,e]],
['','','','',''], [[a,b,c,d],[a,b,c,d,e,f]], none},
{vector(2,float()), [[0.0,1.1],[4.4,-5.5]], [0.0,0.0], [[1,1]], none},
{vector(0,integer()), [[]], [], [[1],[2]], none},
{union([good,bad,ugly]), [good,bad,ugly], good, [clint,"eastwood"],
"good | bad | ugly"},
{union([integer(),atom()]), [twenty_one,21], 0, ["21",<<21>>],
"integer() | atom()"},
{weighted_union([{10,luck},{20,skill},{15,concentrated_power_of_will},
{5,pleasure},{50,pain},{100,remember_the_name}]),
[skill,pain,pleasure], luck, [clear,20,50], none},
{{integer(0,42),list(atom())}, [{42,[a,b]},{21,[c,de,f]},{0,[]}], {0,[]},
[{-1,[a]},{12},{21,[b,c],12}], "{0..42,[atom()]}"},
{tuple([atom(),integer()]), [{the,1}], {'',0}, [{"a",0.0}],
"{atom(),integer()}"},
{{}, [{}], {}, [[],{1,2}], "{}"},
{loose_tuple(integer()), [{1,44,-1},{},{99,-99}], {}, [4,{hello,2},[1,2]],
none},
{loose_tuple(union([atom(),float()])), [{a,4.4,b},{},{'',c},{1.2,-3.4}],
{}, [an_atom,0.4,{hello,2},[aa,bb,3.1]], none},
{loose_tuple(list(integer())), [{[1,-1],[],[2,3,-12]},{}], {},
[[[1,2],[3,4]],{1,12},{[1,99,0.0],[]}], none},
{loose_tuple(loose_tuple(integer())), [{},{{}},{{1,2},{-1,11},{}}], {},
[{123},[{12},{24}]], none},
{exactly({[writing],unit,[tests,is],{2},boring}),
[{[writing],unit,[tests,is],{2},boring}],
{[writing],unit,[tests,is],{2},boring}, [no,its,'not','!'], none},
{[], [[]], [], [[a],[1,2,3]], "[]"},
{fixed_list([neg_integer(),pos_integer()]), [[-12,32],[-1,1]], [-1,1],
[[0,0]], none},
{[atom(),integer(),atom(),float()], [[forty_two,42,forty_two,42.0]],
['',0,'',0.0], [[proper,is,licensed],[under,the,gpl]], none},
{[42 | list(integer())], [[42],[42,44,22]], [42], [[],[11,12]], none},
{number(), [12,32.3,-9,-77.7], 0, [manolis,papadakis], "number()"},
{boolean(), [true,false], false, [unknown], "boolean()"},
{string(), ["hello","","world"], "", ['hello'], "string()"},
{?LAZY(integer()), [0,2,99], 0, [1.1], "integer()"},
{?LAZY(list(float())), [[0.0,1.2,1.99],[]], [], [1.1,[1,2]], "[float()]"},
{zerostream(10), [[0,0,0],[],[0,0,0,0,0,0,0]], [], [[1,0,0],[0.1]], none},
{?SHRINK(pos_integer(),[0]), [1,12,0], 0, [-1,-9,6.0], none},
{?SHRINK(float(),[integer(),atom()]), [1.0,0.0,someatom,'',42,0], 0,
[<<>>,"hello"], none},
{noshrink(?SHRINK(42,[0,1])), [42,0,1], 42, [-1], "42 | 0 | 1"},
{non_empty(list(integer())), [[1,2,3],[3,42],[11]], [0], [[],[0.1]],
"[integer(),...]"},
{default(42,float()), [4.1,-99.0,0.0,42], 42, [43,44], "42 | float()"},
{?SUCHTHAT(X,non_neg_integer(),X rem 4 =:= 1), [1,5,37,89], 1, [4,-12,11],
none},
{?SUCHTHATMAYBE(X,non_neg_integer(),X rem 4 =:= 1), [1,2,3,4,5,37,89], 0,
[1.1,2.2,-12], "non_neg_integer()"},
{any(), [1,-12,0,99.9,-42.2,0.0,an_atom,'',<<>>,<<1,2>>,<<1,2,3:5>>,[],
[42,<<>>],{},{tag,12},{tag,[vals,12,12.2],[],<<>>}],
0, [], "any()"},
{list(any()), [[<<>>,a,1,-42.0,{11.8,[]}]], [], [{1,aa},<<>>], "[any()]"},
{deeplist(), [[[],[]], [[[]],[]]], [], [[a]], "deeplist()"},
{none, [[234,<<1>>,[<<78>>,[]],0],[]], [], [21,3.1,[7.1],<<22>>],
"iolist()"},
{none, [[234,<<1>>,[<<78>>,[]],0],[],<<21,15>>], <<>>, [21,3.1,[7.1]],
"iodata()"}].
constructed_types_with_data() ->
[{?LET(X,range(1,5),X*X), [{'$used',1,1},{'$used',5,25}], 1,
[4,{'$used',3,8},{'$used',0,0}], none},
{?LET(L,non_empty(list(atom())),oneof(L)),
[{'$used',[aa],aa},{'$used',[aa,bb],aa},{'$used',[aa,bb],bb}], '',
[{'$used',[],''},{'$used',[aa,bb],cc}], none},
{?LET(X,pos_integer(),?LET(Y,range(0,X),X-Y)),
[{'$used',3,{'$used',2,1}},{'$used',9,{'$used',9,0}},
{'$used',5,{'$used',0,5}}], 1,
[{'$used',0,{'$used',0,0}},{'$used',3,{'$used',4,-1}},
{'$used',7,{'$used',6,2}}], none},
{?LET(Y,?LET(X,integer(),X*X),-Y),
[{'$used',{'$used',-9,81},-81},{'$used',{'$used',2,4},-4}], 0,
[{'$used',{'$used',1,2},-2},{'$used',{'$used',3,9},9}], none},
{?SUCHTHAT(Y,?LET(X,oneof([1,2,3]),X+X),Y>3),
[{'$used',2,4},{'$used',3,6}], 4, [{'$used',1,2}], none},
{?LET(X,?SUCHTHAT(Y,pos_integer(),Y=/=0),X*X),
[{'$used',3,9},{'$used',1,1},{'$used',11,121}], 1,
[{'$used',-1,1},{'$used',0,0}], none},
{tree(integer()), [{'$used',[null,null],{node,42,null,null}},
{'$used',[{'$used',[null,null],{node,2,null,null}},
{'$used',[null,null],{node,3,null,null}}],
{node,-1,{node,2,null,null},{node,3,null,null}}},
{'$to_part',null},
{'$to_part',{'$used',[null,null],{node,7,null,null}}}],
null, [{'$used',[null,null],{node,1.1,null,null}}], "tree(integer())"},
{?LETSHRINK(L,[],{tag,L}), [{'$used',[],{tag,[]}}], {tag,[]}, [], none},
{?LETSHRINK(L,non_empty(list(atom())),{tag,L}),
[{'$used',[aa],{tag,[aa]}},{'$to_part',aa}], '', [], none},
{a(), [aleaf, {'$used',[aleaf],{anode,aleaf,bleaf}},
{'$used',[aleaf],{anode,aleaf,{'$to_part',bleaf}}}],
aleaf, [], "a()"},
{b(), [bleaf, {'$used',[bleaf],{bnode,aleaf,bleaf}},
{'$used',[bleaf],{bnode,{'$to_part',aleaf},bleaf}}],
bleaf, [], "b()"},
{gen_tree(integer()),
[{'$used',[null,null],{12,[null,null]}},{'$to_part',null}],
null, [{'$used',[],{42,[]}}], "gen_tree(integer())"},
{none, [{'$used',[],{tag,[]}}, {'$used',[null,null],{tag,[null,null]}},
{'$used',[{'$used',[],{tag,[]}},{'$to_part',null}],
{tag,[{tag,[]},null]}}, {'$to_part',{'$used',[],{tag,[]}}}],
null, [], "g()"},
{none, [{'$used',[null],{tag,[{ok,null}]}}, {'$to_part',null},
{'$used',[null,null],{tag,[{ok,null},{ok,null}]}}],
null, [], "h()"},
{none, [{'$used',[null,null,{'$used',[null],{tag,null,[]}}],
{tag,null,[null,{tag,null,[]}]}}, {'$to_part',null}],
null, [], "i()"},
{none, [{'$used',[{'$to_part',null},{'$used',[null],{one,null}},null,null],
{tag,null,{one,null},[null,null],[null]}}], null, [], "j()"},
{none, [{tag,[]}, {tag,[{null,null}]},
{tag,[{{tag,[]},null},{null,{tag,[]}}]}],
null, [{'$to_part',null}], "k()"},
{none, [{'$used',[null,null,{'$used',[null,null],{tag,null,[null]}}],
{tag,null,[null,{tag,null,[null]}]}}, {'$to_part',null}],
null, [{'$used',[null],{tag,null,[]}}], "l()"}].
function_types() ->
[{function([],atom()), "fun(() -> atom())"},
{function([integer(),integer()],atom()),
"fun((integer(),integer()) -> atom())"},
{function(5,union([a,b])), "fun((_,_,_,_,_) -> a | b)"},
{function(0,function(1,integer())),
"fun(() -> fun((_) -> integer()))"}].
remote_native_types() ->
[{types_test1,["#rec1{}","rec1()","exp1()","type1()","type2(atom())",
"rem1()","rem2()","types_test1:exp1()",
"types_test2:exp1(float())","types_test2:exp2()"]},
{types_test2,["exp1(#rec1{})","exp2()","#rec1{}","types_test1:exp1()",
"types_test2:exp1(binary())","types_test2:exp2()"]}].
impossible_types() ->
[?SUCHTHAT(X, pos_integer(), X =< 0),
?SUCHTHAT(X, non_neg_integer(), X < 0),
?SUCHTHAT(X, neg_integer(), X >= 0),
?SUCHTHAT(X, integer(1,10), X > 20),
?SUCHTHAT(X, float(0.0,10.0), X < 0.0),
?SUCHTHAT(L, vector(12,integer()), length(L) =/= 12),
?SUCHTHAT(B, binary(), lists:member(256,binary_to_list(B))),
?SUCHTHAT(X, exactly('Lelouch'), X =:= 'vi Brittania')].
impossible_native_types() ->
[{types_test1, ["1.1","no_such_module:type1()","no_such_type()"]},
{types_test2, ["types_test1:type1()","function()","fun((...) -> atom())",
"pid()","port()","ref()"]}].
recursive_native_types() ->
[{rec_test1, ["a()","b()","a()|b()","d()","f()","deeplist()",
"mylist(float())","aa()","bb()","expc()"]},
{rec_test2, ["a()","expa()","rec()"]}].
impossible_recursive_native_types() ->
[{rec_test1, ["c()","e()","cc()","#rec{}","expb()"]},
{rec_test2, ["b()","#rec{}","aa()"]}].
symb_calls() ->
[{[3,2,1], "lists:reverse([1,2,3])", [], {call,lists,reverse,[[1,2,3]]}},
{[a,b,c,d], "erlang:'++'([a,b],[c,d])",
[{a,some_value}], {call,erlang,'++',[[a,b],[c,d]]}},
{42, "erlang:'*'(erlang:'+'(3,3),erlang:'-'(8,1))",
[{b,dummy_value},{e,another_dummy}],
{call,erlang,'*',[{call,erlang,'+',[3,3]},{call,erlang,'-',[8,1]}]}},
{something, "something",
[{a,somebody},{b,put},{c,something},{d,in_my_drink}], {var,c}},
{{var,b}, "{var,b}", [{a,not_this},{c,neither_this}], {var,b}},
{42, "erlang:'+'(40,2)", [{m,40},{n,2}],
{call,erlang,'+',[{var,m},{var,n}]}},
{[i,am,{var,iron},man],
"erlang:'++'(lists:reverse([am,i]),erlang:'++'([{var,iron}],[man]))",
[{a,man},{b,woman}],
{call,erlang,'++',[{call,lists,reverse,[[am,i]]},
{call,erlang,'++',[[{var,iron}],[{var,a}]]}]}}].
undefined_symb_calls() ->
[{call,erlang,error,[an_error]},
{call,erlang,throw,[a_throw]},
{call,erlang,exit,[an_exit]},
{call,lists,reverse,[<<12,13>>]},
{call,erlang,'+',[1,2,3]}].
combinations() ->
[{[{1,[1,3,5,7,9,10]}, {2,[2,4,6,8,11]}], 5, 11, [1,2,3,4,5,6,7,8,9,10,11], 2, 2,
[{1,[1,3,5,7,8,11]}, {2,[2,4,6,9,10]}]},
{[{1,[1,3,5]}, {2,[7,8,9]}, {3,[2,4,6]}], 3, 9, [1,3,5,7,8,9], 3, 2,
[{1,[6,8,9]}, {2,[1,3,5]}, {3,[2,4,7]}]}].
first_comb() -> [{10,3,3,[{1,[7,8,9,10]}, {2,[4,5,6]}, {3,[1,2,3]}]},
{11,5,2,[{1,[6,7,8,9,10,11]}, {2,[1,2,3,4,5]}]},
{12,3,4,[{1,[10,11,12]}, {2,[7,8,9]}, {3,[4,5,6]}, {4,[1,2,3]}]}].
lists_to_zip() ->
[{[],[],[]},
{[], [dummy, atom], []},
{[1, 42, 1, 42, 1, 2 ,3], [], []},
{[a, b, c], lists:seq(1,6), [{a,1}, {b,2}, {c,3}]},
{[a, b, c], lists:seq(1,3), [{a,1}, {b,2}, {c,3}]},
{[a, d, d, d, d], lists:seq(1,3), [{a,1}, {d,2}, {d,3}]}].
command_names() ->
[{[{set,{var,1},{call,erlang,put,[a,0]}},
{set,{var,3},{call,erlang,erase,[a]}},
{set,{var,4},{call,erlang,get,[b]}}],
[{erlang,put,2},
{erlang,erase,1},
{erlang,get,1}]},
{[{set,{var,1},{call,foo,bar,[]}},
{set,{var,2},{call,bar,foo,[a,{var,1}]}},
{set,{var,3},{call,bar,foo,[a,[[3,4]]]}}],
[{foo,bar,0},
{bar,foo,2},
{bar,foo,2}]},
{[],[]}].
valid_command_sequences() ->
[{pdict_statem, [], [{init,[]},
{set,{var,1},{call,erlang,put,[a,0]}},
{set,{var,2},{call,erlang,put,[b,1]}},
{set,{var,3},{call,erlang,erase,[a]}},
{set,{var,4},{call,erlang,get,[b]}},
{set,{var,5},{call,erlang,erase,[b]}},
{set,{var,6},{call,erlang,put,[a,4]}},
{set,{var,7},{call,erlang,put,[a,42]}}],
[{a,42}], [{a,42}], []},
{pdict_statem, [], [{init,[]},
{set,{var,1},{call,erlang,put,[b,5]}},
{set,{var,2},{call,erlang,erase,[b]}},
{set,{var,3},{call,erlang,put,[a,5]}}],
[{a,5}], [{a,5}], []},
{pdict_statem, [], [{init,[]},
{set,{var,1},{call,erlang,put,[a,{var,start_value}]}},
{set,{var,2},{call,erlang,put,[b,{var,another_start_value}]}},
{set,{var,3},{call,erlang,get,[b]}},
{set,{var,4},{call,erlang,get,[b]}}],
[{b,{var,another_start_value}}, {a,{var,start_value}}], [{b,-1}, {a, 0}],
[{start_value, 0}, {another_start_value, -1}]}].
symbolic_init_invalid_sequences() ->
[{pdict_statem, [{init,[{a,{call,foo,bar,[some_arg]}}]},
{set,{var,1},{call,erlang,put,[b,42]}},
{set,{var,2},{call,erlang,get,[b]}}],
[{some_arg, 0}],
[{init,[{a,{call,foo,bar,[some_arg]}}]}]}].
invalid_precondition() ->
[{pdict_statem, [{init,[]},
{set,{var,1},{call,erlang,put,[a,0]}},
{set,{var,2},{call,erlang,put,[b,1]}},
{set,{var,3},{call,erlang,erase,[a]}},
{set,{var,4},{call,erlang,get,[a]}}],
[], [{set,{var,4},{call,erlang,get,[a]}}]}].
invalid_var() ->
[{pdict_statem, [{init,[]},
{set,{var,2},{call,erlang,put,[b,{var,1}]}}]},
{pdict_statem, [{init,[]},
{set,{var,1},{call,erlang,put,[b,9]}},
{set,{var,5},{call,erlang,put,[a,3]}},
{set,{var,6},{call,erlang,get,[{var,2}]}}]}].
arguments_not_defined() ->
[{[simple,atoms,are,valid,{var,42}], []},
{[{var,1}], [{var,2},{var,3},{var,4}]},
{[hello,world,[hello,world,{var,6}]], []},
{[{1,2,3,{var,1},{var,2}},not_really], []},
{[[[[42,{var,42}]]]], []},
{[{43,41,{1,{var,42}}},why_not], []}].
all_data() ->
[1, 42.0, "$hello", "world\n", [smelly, cat, {smells,bad}],
'$this_should_be_copied', '$this_one_too', 'but$ this$ not',
or_this].
dollar_data() ->
['$this_should_be_copied', '$this_one_too'].
TODO : write tests for old datatypes , use old tests
TODO : check output redirection , quiet , verbose , to_file , on_output/2 ( maybe
TODO : LET and LETSHRINK testing ( these need their intermediate form for
trees , for testing , also test with noshrink and LAZY
TODO : use size=100 for is_instance testing ?
TODO : : check that the same type is returned for consecutive calls ,
TODO : : recursive types containing functions
TODO : ? LET , ? LETSHRINK : only the top - level base type can be a native type
TODO : Test with native types : ? , noshrink , ? LAZY , ? SHRINK ,
TODO : more ADT tests : check bad declarations , bad variable use , multi - clause ,
is_subtype , unacceptable range , unexported opaque , no - specs opaque ,
TODO : conversion of maybe_improper_list
simple_types_test_() ->
[?_test(assert_type_works(TD, true)) || TD <- simple_types_with_data()].
constructed_types_test_() ->
[?_test(assert_type_works(TD, false))
|| TD <- constructed_types_with_data()].
shrinks_to_test_() ->
[?_shrinksTo(Target, Type)
|| {Type,_Xs,Target,_Ys,_TypeStr} <- simple_types_with_data()
++ constructed_types_with_data(),
Type =/= none].
native_shrinks_to_test_() ->
[?_nativeShrinksTo(Target, TypeStr)
|| {_Type,_Xs,Target,_Ys,TypeStr} <- simple_types_with_data()
++ constructed_types_with_data(),
TypeStr =/= none].
cant_generate_test_() ->
[?_test(assert_cant_generate(Type)) || Type <- impossible_types()].
native_cant_translate_test_() ->
[?_test(assert_cant_translate(Mod,TypeStr))
|| {Mod,Strings} <- impossible_native_types(), TypeStr <- Strings].
remote_native_types_test_() ->
[?_test(assert_can_translate(Mod,TypeStr))
|| {Mod,Strings} <- remote_native_types(), TypeStr <- Strings].
recursive_native_types_test_() ->
[?_test(assert_native_can_generate(Mod,TypeStr,false))
|| {Mod,Strings} <- recursive_native_types(), TypeStr <- Strings].
recursive_native_cant_translate_test_() ->
[?_test(assert_cant_translate(Mod,TypeStr))
|| {Mod,Strings} <- impossible_recursive_native_types(),
TypeStr <- Strings].
random_functions_test_() ->
[[?_test(assert_function_type_works(FunType)),
?_test(assert_function_type_works(assert_can_translate(proper,TypeStr)))]
|| {FunType,TypeStr} <- function_types()].
parse_transform_test_() ->
[?_passes(auto_export_test1:prop_1()),
?_assertError(undef, auto_export_test2:prop_1()),
?_assertError(undef, no_native_parse_test:prop_1()),
?_assertError(undef, no_out_of_forall_test:prop_1())].
native_type_props_test_() ->
[?_passes(?FORALL({X,Y}, {my_native_type(),my_proper_type()},
is_integer(X) andalso is_atom(Y))),
?_passes(?FORALL([X,Y,Z],
[my_native_type(),my_proper_type(),my_native_type()],
is_integer(X) andalso is_atom(Y) andalso is_integer(Z))),
?_passes(?FORALL([Y,X,{Z,W}],
[my_proper_type() | [my_native_type()]] ++
[{my_native_type(),my_proper_type()}],
is_integer(X) andalso is_atom(Y) andalso is_integer(Z)
andalso is_atom(W))),
?_passes(?FORALL([X|Y], [my_native_type()|my_native_type()],
is_integer(X) andalso is_integer(Y))),
?_passes(?FORALL(X, type_and_fun(), is_atom(X))),
?_passes(?FORALL(X, type_only(), is_integer(X))),
?_passes(?FORALL(L, [integer()], length(L) =:= 1)),
?_fails(?FORALL(L, id([integer()]), length(L) =:= 1)),
?_passes(?FORALL(_, types_test1:exp1(), true)),
?_assertError(undef, ?FORALL(_,types_test1:rec1(),true)),
?_assertError(undef, ?FORALL(_,no_such_module:some_call(),true)),
{setup, fun() -> code:purge(to_remove),
code:delete(to_remove),
code:purge(to_remove),
file:rename("tests/to_remove.beam",
"tests/to_remove.bak") end,
fun(_) -> file:rename("tests/to_remove.bak",
"tests/to_remove.beam") end,
?_passes(?FORALL(_, to_remove:exp1(), true))},
?_passes(rec_props_test1:prop_1()),
?_passes(rec_props_test2:prop_2()),
?_passes(?FORALL(L, vector(2,my_native_type()),
length(L) =:= 2
andalso lists:all(fun erlang:is_integer/1, L))),
?_passes(?FORALL(F, function(0,my_native_type()), is_integer(F()))),
?_passes(?FORALL(X, union([my_proper_type(),my_native_type()]),
is_integer(X) orelse is_atom(X))),
?_assertError(undef, begin
Vector5 = fun(T) -> vector(5,T) end,
?FORALL(V, Vector5(types_test1:exp1()),
length(V) =:= 5)
end),
?_passes(?FORALL(X, ?SUCHTHAT(Y,types_test1:exp1(),is_atom(Y)),
is_atom(X))),
?_passes(?FORALL(L,non_empty(lof()),length(L) > 0)),
?_passes(?FORALL(X, ?LET(L,lof(),lists:min([99999.9|L])),
is_float(X))),
?_shrinksTo(0, ?LETSHRINK([X],[my_native_type()],{'tag',X})),
?_passes(weird_types:prop_export_all_works()),
?_passes(weird_types:prop_no_auto_import_works())].
-record(untyped, {a, b = 12}).
-type untyped() :: #untyped{}.
true_props_test_() ->
[?_passes(?FORALL(X,integer(),X < X + 1)),
?_passes(?FORALL(X,atom(),list_to_atom(atom_to_list(X)) =:= X)),
?_passes(?FORALL(L,list(integer()),is_sorted(L,quicksort(L)))),
?_passes(?FORALL(L,ulist(integer()),is_sorted(L,lists:usort(L)))),
?_passes(?FORALL(L,non_empty(list(integer())),L =/= [])),
?_passes(?FORALL({I,L}, {integer(),list(integer())},
?IMPLIES(no_duplicates(L),
not lists:member(I,lists:delete(I,L))))),
?_passes(?FORALL(L, ?SIZED(Size,resize(Size div 5,list(integer()))),
length(L) =< 20), [{max_size,100}]),
?_passes(?FORALL(L, list(integer()),
collect(length(L), collect(L =:= [],
lists:reverse(lists:reverse(L)) =:= L)))),
?_passes(?FORALL(L, list(integer()),
aggregate(smaller_lengths_than_my_own(L), true))),
?_assertTempBecomesN(300, true,
numtests(300,?FORALL(_,1,begin inc_temp(),true end))),
?_assertTempBecomesN(30, true, ?FORALL(X, ?SIZED(Size,Size),
begin inc_temp(X),true end),
[{numtests,12},{max_size,4}]),
?_assertTempBecomesN(12, true,
?FORALL(X, ?SIZED(Size,Size),
begin inc_temp(X),true end),
[{numtests,3},{start_size,4},{max_size,4}]),
?_passes(?FORALL(X, integer(), ?IMPLIES(abs(X) > 1, X * X > X))),
?_passes(?FORALL(X, integer(), ?IMPLIES(X >= 0, true))),
?_passes(?FORALL({X,Lim}, {int(),?SIZED(Size,Size)}, abs(X) =< Lim)),
?_passes(?FORALL({X,Lim}, {nat(),?SIZED(Size,Size)}, X =< Lim)),
?_passes(?FORALL(L, orderedlist(integer()), is_sorted(L))),
?_passes(conjunction([
{one, ?FORALL(_, integer(), true)},
{two, ?FORALL(X, integer(), collect(X > 0, true))},
{three, conjunction([{a,true},{b,true}])}
])),
?_passes(?FORALL(X, untyped(), is_record(X, untyped))),
?_passes(pdict_statem:prop_pdict()),
?_passes(symb_statem:prop_simple()),
{timeout, 20, ?_passes(symb_statem:prop_parallel_simple())},
{timeout, 10, ?_passes(ets_statem:prop_ets())},
{timeout, 20, ?_passes(ets_statem:prop_parallel_ets())},
{timeout, 20, ?_passes(pdict_fsm:prop_pdict())}].
false_props_test_() ->
[?_failsWith([[_Same,_Same]],
?FORALL(L,list(integer()),is_sorted(L,lists:usort(L)))),
?_failsWith([[_Same,_Same],_Same],
?FORALL(L, non_empty(list(union([a,b,c,d]))),
?FORALL(X, elements(L),
not lists:member(X,lists:delete(X,L))))),
?_failsWith(['\000\000\000\000'],
?FORALL(A, atom(), length(atom_to_list(A)) < 4)),
?_failsWith([1], ?FORALL(X, non_neg_integer(),
case X > 0 of
true -> throw(not_zero);
false -> true
end)),
?_fails(?FORALL(_,1,lists:min([]) > 0)),
?_failsWith([[12,42]], ?FORALL(L, [12,42|list(integer())],
case lists:member(42, L) of
true -> erlang:exit(you_got_it);
false -> true
end)),
?_fails(?FORALL(_, integer(), ?TIMEOUT(100,timer:sleep(150) =:= ok))),
?_failsWith([20], ?FORALL(X, pos_integer(), ?TRAPEXIT(creator(X) =:= ok))),
?_assertTempBecomesN(7, false,
?FORALL(X, ?SIZED(Size,integer(Size,Size)),
begin inc_temp(), X < 5 end),
[{numtests,5}, {max_size,5}]),
it runs 2 more times : one while shrinking ( recursing into the property )
?_assertTempBecomesN(2, false,
?FORALL(L, list(atom()),
?WHENFAIL(inc_temp(),length(L) < 5))),
?_assertTempBecomesN(3, false,
?FORALL(S, ?SIZED(Size,Size),
begin inc_temp(), S < 20 end),
[{numtests,3},{max_size,40},noshrink]),
?_failsWithOneOf([[{true,false}],[{false,true}]],
?FORALL({B1,B2}, {boolean(),boolean()}, equals(B1,B2))),
?_failsWith([2,1],
?FORALL(X, integer(1,10), ?FORALL(Y, integer(1,10), X =< Y))),
?_failsWith([1,2],
?FORALL(Y, integer(1,10), ?FORALL(X, integer(1,10), X =< Y))),
?_failsWithOneOf([[[0,1]],[[0,-1]],[[1,0]],[[-1,0]]],
?FORALL(L, list(integer()), lists:reverse(L) =:= L)),
?_failsWith([[1,2,3,4,5,6,7,8,9,10]],
?FORALL(_L, shuffle(lists:seq(1,10)), false)),
?_fails(?FORALL(_, integer(0,0), false)),
?_fails(?FORALL(_, float(0.0,0.0), false)),
?_fails(fails(?FORALL(_, integer(), false))),
?_failsWith([16], ?FORALL(X, ?LET(Y,integer(),Y*Y), X < 15)),
?_failsWith([0.0],
?FORALL(_, ?LETSHRINK([A,B], [float(),atom()], {A,B}), false)),
?_failsWith([], conjunction([{some,true},{thing,false}])),
?_failsWith([{2,1},[{group,[[{sub_group,[1]}]]},{stupid,[1]}]],
?FORALL({X,Y}, {pos_integer(),pos_integer()},
conjunction([
{add_next, ?IMPLIES(X > Y, X + 1 > Y)},
{symmetry,
conjunction([
{add_sym, collect(X+Y, X+Y =:= Y+X)},
{sub_sym,
?WHENFAIL(io:format("'-' isn't symmetric!~n",[]),
X-Y =:= Y-X)}
])},
{group,
conjunction([
{add_group,
?WHENFAIL(io:format("This shouldn't happen!~n",[]),
?FORALL(Z, pos_integer(),
(X+Y)+Z =:= X+(Y+Z)))},
{sub_group,
?WHENFAIL(io:format("'-' doesn't group!~n",[]),
?FORALL(W, pos_integer(),
(X-Y)-W =:= X-(Y-W)))}
])},
{stupid, ?FORALL(_, pos_integer(), throw(woot))}
]))),
{timeout, 20, ?_fails(ets_counter:prop_ets_counter())},
?_fails(post_false:prop_simple()),
?_fails(error_statem:prop_simple())].
error_props_test_() ->
[?_errorsOut(cant_generate,
?FORALL(_, ?SUCHTHAT(X, pos_integer(), X =< 0), true)),
?_errorsOut(cant_satisfy,
?FORALL(X, pos_integer(), ?IMPLIES(X =< 0, true))),
?_errorsOut(type_mismatch,
?FORALL({X,Y}, [integer(),integer()], X < Y)),
?_assertCheck({error,rejected}, [2],
?FORALL(X, integer(), ?IMPLIES(X > 5, X < 6))),
?_assertCheck({error,too_many_instances}, [1,ab],
?FORALL(X, pos_integer(), X < 0)),
?_errorsOut(cant_generate, prec_false:prop_simple()),
?_errorsOut(cant_generate, nogen_statem:prop_simple()),
?_errorsOut(non_boolean_result, ?FORALL(_, integer(), not_a_boolean)),
?_errorsOut(non_boolean_result,
?FORALL(_, ?SHRINK(42,[0]),
non_deterministic([{2,false},{1,not_a_boolean}]))),
?_assertRun(false,
?FORALL(_, ?SHRINK(42,[0]),
non_deterministic([{4,false},{1,true}])),
[], false),
?_assertRun(false,
?FORALL(_, ?SHRINK(42,[0]),
non_deterministic([{3,false},{1,true},{1,false}])),
[], false)].
eval_test_() ->
[?_assertEqual(Result, eval(Vars,SymbCall))
|| {Result,_Repr,Vars,SymbCall} <- symb_calls()].
pretty_print_test_() ->
[?_assert(equal_ignoring_ws(Repr, proper_symb:pretty_print(Vars,SymbCall)))
|| {_Result,Repr,Vars,SymbCall} <- symb_calls()].
not_defined_test_() ->
[?_assertNot(defined(SymbCall))
|| SymbCall <- undefined_symb_calls()].
options_test_() ->
[?_assertTempBecomesN(300, true,
?FORALL(_, 1, begin inc_temp(), true end),
[{numtests,300}]),
?_assertTempBecomesN(300, true,
?FORALL(_, 1, begin inc_temp(), true end),
[300]),
?_failsWith([42], ?FORALL(_,?SHRINK(42,[0,1]),false), [noshrink]),
?_failsWith([42], ?FORALL(_,?SHRINK(42,[0,1]),false), [{max_shrinks,0}]),
?_fails(?FORALL(_,integer(),false), [fails]),
?_assertRun({error,cant_generate},
?FORALL(_,?SUCHTHAT(X,pos_integer(),X > 0),true),
[{constraint_tries,0}], true),
?_failsWith([12],
?FORALL(_,?SIZED(Size,integer(Size,Size)),false),
[{start_size,12}])].
adts_test_() ->
for ' old laptop
?_passes(?FORALL({X,S},{integer(),set()},
sets:is_element(X,sets:add_element(X,S))), [20])},
?_passes(?FORALL({X,Y,D},
{integer(),float(),dict(integer(),float())},
dict:fetch(X,dict:store(X,Y,eval(D))) =:= Y), [30]),
?_fails(?FORALL({X,D},
{boolean(),dict(boolean(),integer())},
dict:erase(X, dict:store(X,42,D)) =:= D))].
parameter_test_() ->
?_passes(?FORALL(List, [zero1(),zero2(),zero3(),zero4()],
begin
[?assertMatch(undefined, proper_types:parameter(P))
|| P <- [x1,x2,y2,x3,y3,x4,y4,v,w,z]],
lists:all(fun is_zero/1, List)
end)).
zip_test_() ->
[?_assertEqual(proper_statem:zip(X, Y), Expected)
|| {X,Y,Expected} <- lists_to_zip()].
command_names_test_() ->
[?_assertEqual(proper_statem:command_names(Cmds), Expected)
|| {Cmds,Expected} <- command_names()].
valid_cmds_test_() ->
[?_assert(proper_statem:is_valid(Mod, State, Cmds, Env))
|| {Mod,State,Cmds,_,_,Env} <- valid_command_sequences()].
invalid_cmds_test_() ->
[?_assertNot(proper_statem:is_valid(Mod, Mod:initial_state(), Cmds, []))
|| {Mod,Cmds,_,_} <- invalid_precondition()] ++
[?_assertNot(proper_statem:is_valid(Mod, Mod:initial_state(), Cmds, []))
|| {Mod,Cmds} <- invalid_var()].
state_after_test_() ->
[?_assertEqual(proper_statem:state_after(Mod, Cmds), StateAfter)
|| {Mod,_,Cmds,StateAfter,_,_} <- valid_command_sequences()].
cannot_generate_commands_test_() ->
[?_test(assert_cant_generate_cmds(proper_statem:commands(Mod), 6))
|| Mod <- [prec_false]].
can_generate_commands0_test_() ->
[?_test(assert_can_generate(proper_statem:commands(Mod), false))
|| Mod <- [pdict_statem]].
can_generate_commands1_test_() ->
[?_test(assert_can_generate(proper_statem:commands(Mod, StartState), false))
|| {Mod,StartState} <- [{pdict_statem,[{a,1},{b,1},{c,100}]}]].
can_generate_parallel_commands0_test_() ->
{timeout, 20,
[?_test(assert_can_generate(proper_statem:parallel_commands(Mod), false))
|| Mod <- [ets_counter]]}.
can_generate_parallel_commands1_test_() ->
{timeout, 20,
[?_test(assert_can_generate(
proper_statem:parallel_commands(Mod, Mod:initial_state()),
false))
|| Mod <- [ets_counter]]}.
run_valid_commands_test_() ->
[?_assertMatch({_H,DynState,ok}, setup_run_commands(Mod, Cmds, Env))
|| {Mod,_,Cmds,_,DynState,Env} <- valid_command_sequences()].
run_invalid_precondition_test_() ->
[?_assertMatch({_H,_S,{precondition,false}},
setup_run_commands(Mod, Cmds, Env))
|| {Mod,Cmds,Env,_Shrunk} <- invalid_precondition()].
run_init_error_test_() ->
[?_assertMatch({_H,_S,initialization_error},
setup_run_commands(Mod, Cmds, Env))
|| {Mod,Cmds,Env,_Shrunk} <- symbolic_init_invalid_sequences()].
run_postcondition_false() ->
?_assertMatch({_H,_S,{postcondition,false}},
run_commands(post_false, proper_statem:commands(post_false))).
run_exception() ->
?_assertMatch(
{_H,_S,{exception,throw,badarg,_}},
run_commands(post_false, proper_statem:commands(error_statem))).
get_next_test_() ->
[?_assertEqual(Expected,
proper_statem:get_next(L, Len, MaxIndex, Available, W, N))
|| {L, Len, MaxIndex, Available, W, N, Expected} <- combinations()].
mk_first_comb_test_() ->
[?_assertEqual(Expected, proper_statem:mk_first_comb(N, Len, W))
|| {N, Len, W, Expected} <- first_comb()].
args_not_defined_test() ->
[?_assertNot(proper_statem:args_defined(Args, SymbEnv))
|| {Args,SymbEnv} <- arguments_not_defined()].
command_props_test_() ->
{timeout, 150, [?_assertEqual([], proper:module(command_props, 50))]}.
can_generate_fsm_commands_test_() ->
[?_test(assert_can_generate(proper_fsm:commands(Mod), false))
|| Mod <- [pdict_fsm, numbers_fsm]].
transition_target_test_() ->
{timeout, 20, [?_assertEqual([], proper:module(numbers_fsm))]}.
dollar_only_cp_test_() ->
?_assertEqual(
dollar_data(),
[K || K <- all_data(),
is_atom(K),
re:run(atom_to_list(K), ["^[$]"], [{capture,none}]) =:= match]).
no_duplicates(L) ->
length(lists:usort(L)) =:= length(L).
is_sorted([]) -> true;
is_sorted([_]) -> true;
is_sorted([A | [B|_] = T]) when A =< B -> is_sorted(T);
is_sorted(_) -> false.
same_elements(L1, L2) ->
length(L1) =:= length(L2) andalso same_elems(L1, L2).
same_elems([], []) ->
true;
same_elems([H|T], L) ->
lists:member(H, L) andalso same_elems(T, lists:delete(H, L));
same_elems(_, _) ->
false.
is_sorted(Old, New) ->
same_elements(Old, New) andalso is_sorted(New).
equal_ignoring_ws(Str1, Str2) ->
WhiteSpace = [32,9,10],
equal_ignoring_chars(Str1, Str2, WhiteSpace).
equal_ignoring_chars([], [], _Ignore) ->
true;
equal_ignoring_chars([_SameChar|Rest1], [_SameChar|Rest2], Ignore) ->
equal_ignoring_chars(Rest1, Rest2, Ignore);
equal_ignoring_chars([Char1|Rest1] = Str1, [Char2|Rest2] = Str2, Ignore) ->
case lists:member(Char1, Ignore) of
true ->
equal_ignoring_chars(Rest1, Str2, Ignore);
false ->
case lists:member(Char2, Ignore) of
true ->
equal_ignoring_chars(Str1, Rest2, Ignore);
false ->
false
end
end.
smaller_lengths_than_my_own(L) ->
lists:seq(0,length(L)).
is_zero(X) -> X =:= 0.
partition(Pivot, List) ->
partition_tr(Pivot, List, [], []).
partition_tr(_Pivot, [], Lower, Higher) ->
{Lower, Higher};
partition_tr(Pivot, [H|T], Lower, Higher) ->
if
H =< Pivot -> partition_tr(Pivot, T, [H|Lower], Higher);
H > Pivot -> partition_tr(Pivot, T, Lower, [H|Higher])
end.
quicksort([]) -> [];
quicksort([H|T]) ->
{Lower, Higher} = partition(H, T),
quicksort(Lower) ++ [H] ++ quicksort(Higher).
creator(X) ->
Self = self(),
spawn_link(fun() -> destroyer(X,Self) end),
receive
_ -> ok
end.
destroyer(X, Father) ->
if
X < 20 -> Father ! not_yet;
true -> exit(this_is_the_end)
end.
Datatypes to test
shuffle([]) ->
[];
shuffle(L) ->
?LET(X, elements(L), [X | shuffle(lists:delete(X,L))]).
ulist(ElemType) ->
?LET(L, list(ElemType), L--(L--lists:usort(L))).
zerostream(ExpectedMeanLen) ->
?LAZY(frequency([
{1, []},
{ExpectedMeanLen, [0 | zerostream(ExpectedMeanLen)]}
])).
-type my_native_type() :: integer().
my_proper_type() -> atom().
-type type_and_fun() :: integer().
type_and_fun() -> atom().
-type type_only() :: integer().
-type id(X) :: X.
-type lof() :: [float()].
-type deeplist() :: [deeplist()].
deeplist() ->
?SIZED(Size, deeplist(Size)).
deeplist(0) ->
[];
deeplist(Size) ->
?LAZY(proper_types:distlist(Size, fun deeplist/1, false)).
-type tree(T) :: 'null' | {'node',T,tree(T),tree(T)}.
tree(ElemType) ->
?SIZED(Size, tree(ElemType,Size)).
tree(_ElemType, 0) ->
null;
tree(ElemType, Size) ->
LeftTree = tree(ElemType, Size div 2),
RightTree = tree(ElemType, Size div 2),
frequency([
{1, tree(ElemType,0)},
{5, ?LETSHRINK([L,R], [LeftTree,RightTree], {node,ElemType,L,R})}
]).
-type a() :: 'aleaf' | {'anode',a(),b()}.
-type b() :: 'bleaf' | {'bnode',a(),b()}.
a() ->
?SIZED(Size, a(Size)).
a(0) ->
aleaf;
a(Size) ->
union([
?LAZY(a(0)),
?LAZY(?LETSHRINK([A], [a(Size div 2)], {anode,A,b(Size)}))
]).
b() ->
?SIZED(Size, b(Size)).
b(0) ->
bleaf;
b(Size) ->
union([
?LAZY(b(0)),
?LAZY(?LETSHRINK([B], [b(Size div 2)], {bnode,a(Size),B}))
]).
-type gen_tree(T) :: 'null' | {T,[gen_tree(T),...]}.
gen_tree(ElemType) ->
?SIZED(Size, gen_tree(ElemType,Size)).
gen_tree(_ElemType, 0) ->
null;
gen_tree(ElemType, Size) ->
SubGen = fun(S) -> gen_tree(ElemType,S) end,
oneof([
?LAZY(gen_tree(ElemType,0)),
?LAZY(?LETSHRINK(Children, proper_types:distlist(Size, SubGen, true),
{ElemType,Children}))
]).
-type g() :: 'null' | {'tag',[g()]}.
-type h() :: 'null' | {'tag',[{'ok',h()}]}.
-type i() :: 'null' | {'tag',i(),[i()]}.
-type j() :: 'null' | {'one',j()} | {'tag',j(),j(),[j()],[j()]}.
-type k() :: 'null' | {'tag',[{k(),k()}]}.
-type l() :: 'null' | {'tag',l(),[l(),...]}.
zero1() ->
proper_types:with_parameter(
x1, 0, ?SUCHTHAT(I, range(-1, 1), I =:= proper_types:parameter(x1))).
zero2() ->
proper_types:with_parameters(
[{x2,41}],
?LET(X,
proper_types:with_parameter(
y2, 43,
?SUCHTHAT(
I, range(41, 43),
I > proper_types:parameter(x2)
andalso I < proper_types:parameter(y2))),
X - 42)).
zero3() ->
?SUCHTHAT(I, range(-1, 1),
I > proper_types:parameter(x3, -1)
andalso I < proper_types:parameter(y3, 1)).
zero4() ->
proper_types:with_parameters(
[{x4,-2}, {y4,2}],
proper_types:with_parameters(
[{x4,-1}, {y4,1}],
?SUCHTHAT(I, range(-1, 1),
I > proper_types:parameter(x4)
andalso I < proper_types:parameter(y4)))).
? , ElemType , not lists : member(E , Rest ) ) ,
? ,
? SUCHTHAT(L , list(ElemType ) , no_duplicates(L ) ) .
kvlist(KeyType , ValueType ) - >
[ { K , ValueType } || K < - Keys ] ) .
symbdict(KeyType , ValueType ) - >
? SIZED(Size , symbdict(Size , KeyType , ValueType ) ) .
symbdict(0 , _ KeyType , _ ValueType ) - >
symbdict(Size , KeyType , ValueType ) - >
{ 1,symbdict(0 , KeyType , ValueType ) } ,
{ 4,?LETSHRINK([Smaller ] , [ symbdict(Size - 1 , KeyType , ValueType ) ] ,
{ call , dict , append,[KeyType , ValueType , Smaller ] } ) }
? ,
erlang : element(1,T ) = /= 42 ) ;
? FORALL(L , kvlist(atom(),integer ( ) ) , not lists : ) ) ;
? , non_empty(list(integer ( ) ) ) , list(oneof(L ) ) ) ,
length(X ) < 10 ) ;
not dict : is_key(42 , eval(SD ) ) ) ;
? , L } ,
lists : all(fun(X ) - > F(X ) = /= 42 end , L ) ) ;
correct_smaller_length_aggregation(Tests , ) - >
{ Zeros , Larger } = lists : partition(fun(X ) - > X = : = 0 end , ) ,
andalso correct_smaller_length_aggregation(Tests , Larger , 1 ) .
correct_smaller_length_aggregation(0 , SmallerLens , _
correct_smaller_length_aggregation(NotMoreThan , SmallerLens , ) - >
{ Lens , Larger } = lists : partition(fun(X ) - > X = : = , ) ,
|
475122724c18cf4ef296d7991c0d079f15d21b38a275d00e35a6500a687bd976 | avsm/mirage-duniverse | config_client.ml | open Mirage
let main = foreign ~packages:[package "vchan-xen"; package "duration"] "Unikernel.Client" (console @-> job)
let () =
register "vchan_client" [ main $ default_console ]
| null | https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/vchan/lib_test/mirage/config_client.ml | ocaml | open Mirage
let main = foreign ~packages:[package "vchan-xen"; package "duration"] "Unikernel.Client" (console @-> job)
let () =
register "vchan_client" [ main $ default_console ]
|
|
bdf21c89497ac2c2dc4e519144c07b73a5bd986ed3245d850fc8e3979e11db72 | sansarip/owlbear | utilities.cljs | (ns owlbear.utilities
"Utility functions not specific to the domain of Owlbear grammar")
(defn str-insert
"Insert c in string s at the given offset"
[s c offset]
(str (subs s 0 offset) c (subs s offset)))
(defn str-remove
"Remove the string in between the given start and end offsets"
([s start-offset]
(str-remove s start-offset (inc start-offset)))
([s start-offset end-offset]
(str (subs s 0 start-offset) (subs s end-offset)))) | null | https://raw.githubusercontent.com/sansarip/owlbear/b25d46e3f401f5fee739889e5bc604f6b9c00c41/src/cljs/owlbear/utilities.cljs | clojure | (ns owlbear.utilities
"Utility functions not specific to the domain of Owlbear grammar")
(defn str-insert
"Insert c in string s at the given offset"
[s c offset]
(str (subs s 0 offset) c (subs s offset)))
(defn str-remove
"Remove the string in between the given start and end offsets"
([s start-offset]
(str-remove s start-offset (inc start-offset)))
([s start-offset end-offset]
(str (subs s 0 start-offset) (subs s end-offset)))) |
|
04d1b0fef948eade3fbb9131536ef7fb0b163da1ffa02df1dcd6198c127b586d | jaspervdj/patat | Tests.hs | {-# LANGUAGE OverloadedStrings #-}
module Patat.Presentation.Read.Tests
( tests
) where
import qualified Data.Text as T
import Patat.Presentation.Read
import qualified Test.Tasty as Tasty
import qualified Test.Tasty.HUnit as Tasty
tests :: Tasty.TestTree
tests = Tasty.testGroup "Patat.Presentation.Read.Tests"
[ Tasty.testCase "readMetaSettings" $
case readMetaSettings invalidMetadata of
Left _ -> pure ()
Right _ -> Tasty.assertFailure "expecting invalid metadata"
]
invalidMetadata :: T.Text
invalidMetadata =
"---\n\
\title: mixing tabs and spaces bad\n\
\author: thoastbrot\n\
\patat:\n\
\ images:\n\
\ backend: 'w3m'\n\
\ path: '/usr/lib/w3m/w3mimgdisplay'\n\
\ theme:\n\
\\theader: [vividBlue,onDullBlack]\n\
\ emph: [dullBlue,italic]\n\
\...\n\
\\n\
\Hi!"
| null | https://raw.githubusercontent.com/jaspervdj/patat/9e0d0ccde9afee07ea23521546c406033afeb4f9/tests/haskell/Patat/Presentation/Read/Tests.hs | haskell | # LANGUAGE OverloadedStrings #
-\n\ | module Patat.Presentation.Read.Tests
( tests
) where
import qualified Data.Text as T
import Patat.Presentation.Read
import qualified Test.Tasty as Tasty
import qualified Test.Tasty.HUnit as Tasty
tests :: Tasty.TestTree
tests = Tasty.testGroup "Patat.Presentation.Read.Tests"
[ Tasty.testCase "readMetaSettings" $
case readMetaSettings invalidMetadata of
Left _ -> pure ()
Right _ -> Tasty.assertFailure "expecting invalid metadata"
]
invalidMetadata :: T.Text
invalidMetadata =
\title: mixing tabs and spaces bad\n\
\author: thoastbrot\n\
\patat:\n\
\ images:\n\
\ backend: 'w3m'\n\
\ path: '/usr/lib/w3m/w3mimgdisplay'\n\
\ theme:\n\
\\theader: [vividBlue,onDullBlack]\n\
\ emph: [dullBlue,italic]\n\
\...\n\
\\n\
\Hi!"
|
cc87e43478a1bb8be6886ceac563c0dcbafbefe0d567d9716f3f05675ccfb326 | JacquesCarette/Drasil | CSharpRenderer.hs | # LANGUAGE TypeFamilies #
# LANGUAGE PostfixOperators #
-- | The logic to render C# code is contained in this module
module GOOL.Drasil.LanguageRenderer.CSharpRenderer (
-- * C# Code Configuration -- defines syntax of all C# code
CSharpCode(..), csName, csVersion
) where
import Utils.Drasil (indent)
import GOOL.Drasil.CodeType (CodeType(..))
import GOOL.Drasil.ClassInterface (Label, MSBody, VSType, SVariable, SValue,
VSFunction, MSStatement, MSParameter, SMethod, OOProg, ProgramSym(..),
FileSym(..), PermanenceSym(..), BodySym(..), oneLiner, BlockSym(..),
TypeSym(..), TypeElim(..), VariableSym(..), VariableElim(..), ValueSym(..),
Argument(..), Literal(..), MathConstant(..), VariableValue(..),
CommandLineArgs(..), NumericExpression(..), BooleanExpression(..),
Comparison(..), ValueExpression(..), funcApp, selfFuncApp, extFuncApp,
newObj, InternalValueExp(..), objMethodCallNoParams, FunctionSym(..), ($.),
GetSet(..), List(..), InternalList(..), StatementSym(..),
AssignStatement(..), (&=), DeclStatement(..), IOStatement(..),
StringStatement(..), FuncAppStatement(..), CommentStatement(..),
ControlStatement(..), StatePattern(..), ObserverPattern(..),
StrategyPattern(..), ScopeSym(..), ParameterSym(..), MethodSym(..),
StateVarSym(..), ClassSym(..), ModuleSym(..))
import GOOL.Drasil.RendererClasses (RenderSym, RenderFile(..), ImportSym(..),
ImportElim, PermElim(binding), RenderBody(..), BodyElim, RenderBlock(..),
BlockElim, RenderType(..), InternalTypeElim, UnaryOpSym(..), BinaryOpSym(..),
OpElim(uOpPrec, bOpPrec), RenderVariable(..), InternalVarElim(variableBind),
RenderValue(..), ValueElim(valuePrec), InternalGetSet(..), InternalListFunc(..),
RenderFunction(..), FunctionElim(functionType), InternalAssignStmt(..),
InternalIOStmt(..), InternalControlStmt(..), RenderStatement(..),
StatementElim(statementTerm), RenderScope(..), ScopeElim, MethodTypeSym(..),
RenderParam(..), ParamElim(parameterName, parameterType), RenderMethod(..),
MethodElim, StateVarElim, RenderClass(..), ClassElim, RenderMod(..), ModuleElim,
BlockCommentSym(..), BlockCommentElim)
import qualified GOOL.Drasil.RendererClasses as RC (import', perm, body, block,
type', uOp, bOp, variable, value, function, statement, scope, parameter,
method, stateVar, class', module', blockComment')
import GOOL.Drasil.LanguageRenderer (new, dot, blockCmtStart, blockCmtEnd,
docCmtStart, bodyStart, bodyEnd, endStatement, commentStart, elseIfLabel,
inLabel, tryLabel, catchLabel, throwLabel, exceptionObj', new', listSep',
args, nullLabel, listSep, access, containing, mathFunc, valueList,
variableList, appendToBody, surroundBody)
import qualified GOOL.Drasil.LanguageRenderer as R (class', multiStmt, body,
printFile, param, method, listDec, classVar, func, cast, listSetFunc,
castObj, static, dynamic, break, continue, private, public, blockCmt, docCmt,
addComments, commentedMod, commentedItem)
import GOOL.Drasil.LanguageRenderer.Constructors (mkStmt,
mkStateVal, mkVal, VSOp, unOpPrec, powerPrec, unExpr, unExpr',
unExprNumDbl, typeUnExpr, binExpr, binExprNumDbl', typeBinExpr)
import qualified GOOL.Drasil.LanguageRenderer.LanguagePolymorphic as G (
multiBody, block, multiBlock, listInnerType, obj, csc, sec, cot,
negateOp, equalOp, notEqualOp, greaterOp, greaterEqualOp, lessOp,
lessEqualOp, plusOp, minusOp, multOp, divideOp, moduloOp, var, staticVar,
objVar, arrayElem, litChar, litDouble, litInt, litString, valueOf, arg,
argsList, objAccess, objMethodCall, call, funcAppMixedArgs,
selfFuncAppMixedArgs, newObjMixedArgs, lambda, func, get, set, listAdd,
listAppend, listAccess, listSet, getFunc, setFunc, listAppendFunc, stmt,
loopStmt, emptyStmt, assign, subAssign, increment, objDecNew, print,
closeFile, returnStmt, valStmt, comment, throw, ifCond, tryCatch, construct,
param, method, getMethod, setMethod, function, buildClass, implementingClass,
commentedClass, modFromData, fileDoc, fileFromData)
import qualified GOOL.Drasil.LanguageRenderer.CommonPseudoOO as CP (int,
constructor, doxFunc, doxClass, doxMod, extVar, classVar, objVarSelf,
extFuncAppMixedArgs, indexOf, listAddFunc, discardFileLine, intClass,
arrayType, pi, printSt, arrayDec, arrayDecDef, openFileA, forEach, docMain,
mainFunction, buildModule', string, constDecDef, docInOutFunc, bindingError,
notNull, listDecDef, destructorError, stateVarDef, constVar, listSetFunc,
extraClass, listAccessFunc, doubleRender, openFileR, openFileW, stateVar,
inherit, implements)
import qualified GOOL.Drasil.LanguageRenderer.CLike as C (float, double, char,
listType, void, notOp, andOp, orOp, self, litTrue, litFalse, litFloat,
inlineIf, libFuncAppMixedArgs, libNewObjMixedArgs, listSize, increment1,
decrement1, varDec, varDecDef, listDec, extObjDecNew, switch, for, while,
intFunc, multiAssignError, multiReturnError, multiTypeError)
import qualified GOOL.Drasil.LanguageRenderer.Macros as M (ifExists,
runStrategy, listSlice, stringListVals, stringListLists, forRange,
notifyObservers, checkState)
import GOOL.Drasil.AST (Terminator(..), FileType(..), FileData(..), fileD,
FuncData(..), fd, ModData(..), md, updateMod, MethodData(..), mthd,
updateMthd, OpData(..), ParamData(..), pd, updateParam, ProgData(..), progD,
TypeData(..), td, ValData(..), vd, updateValDoc, Binding(..), VarData(..),
vard)
import GOOL.Drasil.Helpers (angles, hicat, toCode, toState, onCodeValue,
onStateValue, on2CodeValues, on2StateValues, on3CodeValues, on3StateValues,
on2StateWrapped, onCodeList, onStateList)
import GOOL.Drasil.State (VS, lensGStoFS, lensMStoVS, modifyReturn, revFiles,
addLangImport, addLangImportVS, setFileType, getClassName, setCurrMain)
import Prelude hiding (break,print,(<>),sin,cos,tan,floor)
import Control.Lens.Zoom (zoom)
import Control.Monad (join)
import Control.Monad.State (modify)
import Data.Composition ((.:))
import Data.List (intercalate)
import Text.PrettyPrint.HughesPJ (Doc, text, (<>), (<+>), ($$), parens, empty,
equals, vcat, lbrace, rbrace, braces, colon, space, quotes)
csExt :: String
csExt = "cs"
newtype CSharpCode a = CSC {unCSC :: a} deriving Eq
instance Functor CSharpCode where
fmap f (CSC x) = CSC (f x)
instance Applicative CSharpCode where
pure = CSC
(CSC f) <*> (CSC x) = CSC (f x)
instance Monad CSharpCode where
CSC x >>= f = f x
instance OOProg CSharpCode where
instance ProgramSym CSharpCode where
type Program CSharpCode = ProgData
prog n files = do
fs <- mapM (zoom lensGStoFS) files
modify revFiles
pure $ onCodeList (progD n) fs
instance RenderSym CSharpCode
instance FileSym CSharpCode where
type File CSharpCode = FileData
fileDoc m = do
modify (setFileType Combined)
G.fileDoc csExt top bottom m
docMod = CP.doxMod csExt
instance RenderFile CSharpCode where
top _ = toCode empty
bottom = toCode empty
commentedMod = on2StateValues (on2CodeValues R.commentedMod)
fileFromData = G.fileFromData (onCodeValue . fileD)
instance ImportSym CSharpCode where
type Import CSharpCode = Doc
langImport = toCode . csImport
modImport = langImport
instance ImportElim CSharpCode where
import' = unCSC
instance PermanenceSym CSharpCode where
type Permanence CSharpCode = Doc
static = toCode R.static
dynamic = toCode R.dynamic
instance PermElim CSharpCode where
perm = unCSC
binding = error $ CP.bindingError csName
instance BodySym CSharpCode where
type Body CSharpCode = Doc
body = onStateList (onCodeList R.body)
addComments s = onStateValue (onCodeValue (R.addComments s commentStart))
instance RenderBody CSharpCode where
multiBody = G.multiBody
instance BodyElim CSharpCode where
body = unCSC
instance BlockSym CSharpCode where
type Block CSharpCode = Doc
block = G.block
instance RenderBlock CSharpCode where
multiBlock = G.multiBlock
instance BlockElim CSharpCode where
block = unCSC
instance TypeSym CSharpCode where
type Type CSharpCode = TypeData
bool = addSystemImport csBoolType
int = CP.int
float = C.float
double = C.double
char = C.char
string = CP.string
infile = csInfileType
outfile = csOutfileType
listType t = do
modify (addLangImportVS csGeneric)
C.listType csList t
arrayType = CP.arrayType
listInnerType = G.listInnerType
obj = G.obj
funcType = csFuncType
void = C.void
instance TypeElim CSharpCode where
getType = cType . unCSC
getTypeString = typeString . unCSC
instance RenderType CSharpCode where
multiType _ = error $ C.multiTypeError csName
typeFromData t s d = toState $ toCode $ td t s d
instance InternalTypeElim CSharpCode where
type' = typeDoc . unCSC
instance UnaryOpSym CSharpCode where
type UnaryOp CSharpCode = OpData
notOp = C.notOp
negateOp = G.negateOp
sqrtOp = csUnaryMath "Sqrt"
absOp = csUnaryMath "Abs"
logOp = csUnaryMath "Log10"
lnOp = csUnaryMath "Log"
expOp = csUnaryMath "Exp"
sinOp = csUnaryMath "Sin"
cosOp = csUnaryMath "Cos"
tanOp = csUnaryMath "Tan"
asinOp = csUnaryMath "Asin"
acosOp = csUnaryMath "Acos"
atanOp = csUnaryMath "Atan"
floorOp = csUnaryMath "Floor"
ceilOp = csUnaryMath "Ceiling"
instance BinaryOpSym CSharpCode where
type BinaryOp CSharpCode = OpData
equalOp = G.equalOp
notEqualOp = G.notEqualOp
greaterOp = G.greaterOp
greaterEqualOp = G.greaterEqualOp
lessOp = G.lessOp
lessEqualOp = G.lessEqualOp
plusOp = G.plusOp
minusOp = G.minusOp
multOp = G.multOp
divideOp = G.divideOp
powerOp = addSystemImport $ powerPrec $ mathFunc "Pow"
moduloOp = G.moduloOp
andOp = C.andOp
orOp = C.orOp
instance OpElim CSharpCode where
uOp = opDoc . unCSC
bOp = opDoc . unCSC
uOpPrec = opPrec . unCSC
bOpPrec = opPrec . unCSC
instance VariableSym CSharpCode where
type Variable CSharpCode = VarData
var = G.var
staticVar = G.staticVar
const = var
extVar = CP.extVar
self = C.self
classVar = CP.classVar R.classVar
extClassVar = classVar
objVar = G.objVar
objVarSelf = CP.objVarSelf
arrayElem i = G.arrayElem (litInt i)
instance VariableElim CSharpCode where
variableName = varName . unCSC
variableType = onCodeValue varType
instance InternalVarElim CSharpCode where
variableBind = varBind . unCSC
variable = varDoc . unCSC
instance RenderVariable CSharpCode where
varFromData b n t' d = do
t <- t'
toState $ on2CodeValues (vard b n) t (toCode d)
instance ValueSym CSharpCode where
type Value CSharpCode = ValData
valueType = onCodeValue valType
instance Argument CSharpCode where
pointerArg = id
instance Literal CSharpCode where
litTrue = C.litTrue
litFalse = C.litFalse
litChar = G.litChar quotes
litDouble = G.litDouble
litFloat = C.litFloat
litInt = G.litInt
litString = G.litString
litArray = csLitList arrayType
litList = csLitList listType
instance MathConstant CSharpCode where
pi = CP.pi
instance VariableValue CSharpCode where
valueOf = G.valueOf
instance CommandLineArgs CSharpCode where
arg n = G.arg (litInt n) argsList
argsList = G.argsList args
argExists i = listSize argsList ?> litInt (fromIntegral i)
instance NumericExpression CSharpCode where
(#~) = unExpr' negateOp
(#/^) = unExprNumDbl sqrtOp
(#|) = unExpr absOp
(#+) = binExpr plusOp
(#-) = binExpr minusOp
(#*) = binExpr multOp
(#/) = binExpr divideOp
(#%) = binExpr moduloOp
(#^) = binExprNumDbl' powerOp
log = unExprNumDbl logOp
ln = unExprNumDbl lnOp
exp = unExprNumDbl expOp
sin = unExprNumDbl sinOp
cos = unExprNumDbl cosOp
tan = unExprNumDbl tanOp
csc = G.csc
sec = G.sec
cot = G.cot
arcsin = unExprNumDbl asinOp
arccos = unExprNumDbl acosOp
arctan = unExprNumDbl atanOp
floor = unExpr floorOp
ceil = unExpr ceilOp
instance BooleanExpression CSharpCode where
(?!) = typeUnExpr notOp bool
(?&&) = typeBinExpr andOp bool
(?||) = typeBinExpr orOp bool
instance Comparison CSharpCode where
(?<) = typeBinExpr lessOp bool
(?<=) = typeBinExpr lessEqualOp bool
(?>) = typeBinExpr greaterOp bool
(?>=) = typeBinExpr greaterEqualOp bool
(?==) = typeBinExpr equalOp bool
(?!=) = typeBinExpr notEqualOp bool
instance ValueExpression CSharpCode where
inlineIf = C.inlineIf
funcAppMixedArgs = G.funcAppMixedArgs
selfFuncAppMixedArgs = G.selfFuncAppMixedArgs dot self
extFuncAppMixedArgs = CP.extFuncAppMixedArgs
libFuncAppMixedArgs = C.libFuncAppMixedArgs
newObjMixedArgs = G.newObjMixedArgs (new ++ " ")
extNewObjMixedArgs _ = newObjMixedArgs
libNewObjMixedArgs = C.libNewObjMixedArgs
lambda = G.lambda csLambda
notNull = CP.notNull nullLabel
instance RenderValue CSharpCode where
inputFunc = addSystemImport csReadLineFunc
printFunc = addSystemImport $ mkStateVal void (text $ csConsole `access`
csWrite)
printLnFunc = addSystemImport $ mkStateVal void (text $ csConsole `access`
csWriteLine)
printFileFunc w' = on2StateWrapped (\w vt ->
mkVal vt . R.printFile csWrite . RC.value $ w) w' void
printFileLnFunc w' = on2StateWrapped (\w vt ->
mkVal vt . R.printFile csWriteLine . RC.value $ w) w' void
cast = csCast
call = G.call csNamedArgSep
valFromData p t' d = do
t <- t'
toState $ on2CodeValues (vd p) t (toCode d)
instance ValueElim CSharpCode where
valuePrec = valPrec . unCSC
value = val . unCSC
instance InternalValueExp CSharpCode where
objMethodCallMixedArgs' = G.objMethodCall
instance FunctionSym CSharpCode where
type Function CSharpCode = FuncData
func = G.func
objAccess = G.objAccess
instance GetSet CSharpCode where
get = G.get
set = G.set
instance List CSharpCode where
listSize = C.listSize
listAdd = G.listAdd
listAppend = G.listAppend
listAccess = G.listAccess
listSet = G.listSet
indexOf = CP.indexOf csIndex
instance InternalList CSharpCode where
listSlice' = M.listSlice
instance InternalGetSet CSharpCode where
getFunc = G.getFunc
setFunc = G.setFunc
instance InternalListFunc CSharpCode where
listSizeFunc = funcFromData (R.func csListSize) int
listAddFunc _ = CP.listAddFunc csListAdd
listAppendFunc = G.listAppendFunc csListAppend
listAccessFunc = CP.listAccessFunc
listSetFunc = CP.listSetFunc R.listSetFunc
instance RenderFunction CSharpCode where
funcFromData d = onStateValue (onCodeValue (`fd` d))
instance FunctionElim CSharpCode where
functionType = onCodeValue fType
function = funcDoc . unCSC
instance InternalAssignStmt CSharpCode where
multiAssign _ _ = error $ C.multiAssignError csName
instance InternalIOStmt CSharpCode where
printSt _ _ = CP.printSt
instance InternalControlStmt CSharpCode where
multiReturn _ = error $ C.multiReturnError csName
instance RenderStatement CSharpCode where
stmt = G.stmt
loopStmt = G.loopStmt
emptyStmt = G.emptyStmt
stmtFromData d t = toState $ toCode (d, t)
instance StatementElim CSharpCode where
statement = fst . unCSC
statementTerm = snd . unCSC
instance StatementSym CSharpCode where
type Statement CSharpCode = (Doc, Terminator)
valStmt = G.valStmt Semi
multi = onStateList (onCodeList R.multiStmt)
instance AssignStatement CSharpCode where
assign = G.assign Semi
(&-=) = G.subAssign Semi
(&+=) = G.increment
(&++) = C.increment1
(&--) = C.decrement1
instance DeclStatement CSharpCode where
varDec v = zoom lensMStoVS v >>= (\v' -> csVarDec (variableBind v') $
C.varDec static dynamic empty v)
varDecDef = C.varDecDef Semi
listDec n v = zoom lensMStoVS v >>= (\v' -> C.listDec (R.listDec v')
(litInt n) v)
listDecDef = CP.listDecDef
arrayDec n = CP.arrayDec (litInt n)
arrayDecDef = CP.arrayDecDef
objDecDef = varDecDef
objDecNew = G.objDecNew
extObjDecNew = C.extObjDecNew
constDecDef = CP.constDecDef
funcDecDef = csFuncDecDef
instance IOStatement CSharpCode where
print = G.print False Nothing printFunc
printLn = G.print True Nothing printLnFunc
printStr = G.print False Nothing printFunc . litString
printStrLn = G.print True Nothing printLnFunc . litString
printFile f = G.print False (Just f) (printFileFunc f)
printFileLn f = G.print True (Just f) (printFileLnFunc f)
printFileStr f = G.print False (Just f) (printFileFunc f) . litString
printFileStrLn f = G.print True (Just f) (printFileLnFunc f) . litString
getInput v = v &= csInput (onStateValue variableType v) inputFunc
discardInput = csDiscardInput inputFunc
getFileInput f v = v &= csInput (onStateValue variableType v) (csFileInput f)
discardFileInput f = valStmt $ csFileInput f
openFileR = CP.openFileR csOpenFileR
openFileW = CP.openFileW csOpenFileWorA
openFileA = CP.openFileA csOpenFileWorA
closeFile = G.closeFile csClose
getFileInputLine = getFileInput
discardFileLine = CP.discardFileLine csReadLine
getFileInputAll f v = while ((f $. funcFromData (dot <> text csEOS) bool) ?!)
(oneLiner $ valStmt $ listAppend (valueOf v) (csFileInput f))
instance StringStatement CSharpCode where
stringSplit d vnew s = assign vnew $ newObj (listType string)
[s $. csSplitFunc d]
stringListVals = M.stringListVals
stringListLists = M.stringListLists
instance FuncAppStatement CSharpCode where
inOutCall = csInOutCall funcApp
selfInOutCall = csInOutCall selfFuncApp
extInOutCall m = csInOutCall (extFuncApp m)
instance CommentStatement CSharpCode where
comment = G.comment commentStart
instance ControlStatement CSharpCode where
break = mkStmt R.break
continue = mkStmt R.continue
returnStmt = G.returnStmt Semi
throw msg = do
modify (addLangImport csSystem)
G.throw csThrowDoc Semi msg
ifCond = G.ifCond parens bodyStart elseIfLabel bodyEnd
switch = C.switch parens break
ifExists = M.ifExists
for = C.for bodyStart bodyEnd
forRange = M.forRange
forEach = CP.forEach bodyStart bodyEnd csForEach inLabel
while = C.while parens bodyStart bodyEnd
tryCatch = G.tryCatch csTryCatch
instance StatePattern CSharpCode where
checkState = M.checkState
instance ObserverPattern CSharpCode where
notifyObservers = M.notifyObservers
instance StrategyPattern CSharpCode where
runStrategy = M.runStrategy
instance ScopeSym CSharpCode where
type Scope CSharpCode = Doc
private = toCode R.private
public = toCode R.public
instance RenderScope CSharpCode where
scopeFromData _ = toCode
instance ScopeElim CSharpCode where
scope = unCSC
instance MethodTypeSym CSharpCode where
type MethodType CSharpCode = TypeData
mType = zoom lensMStoVS
construct = G.construct
instance ParameterSym CSharpCode where
type Parameter CSharpCode = ParamData
param = G.param R.param
pointerParam = param
instance RenderParam CSharpCode where
paramFromData v' d = do
v <- zoom lensMStoVS v'
toState $ on2CodeValues pd v (toCode d)
instance ParamElim CSharpCode where
parameterName = variableName . onCodeValue paramVar
parameterType = variableType . onCodeValue paramVar
parameter = paramDoc . unCSC
instance MethodSym CSharpCode where
type Method CSharpCode = MethodData
method = G.method
getMethod = G.getMethod
setMethod = G.setMethod
constructor ps is b = getClassName >>= (\n -> CP.constructor n ps is b)
docMain = CP.docMain
function = G.function
mainFunction = CP.mainFunction string csMain
docFunc = CP.doxFunc
inOutMethod n s p = csInOut (method n s p)
docInOutMethod n s p = CP.docInOutFunc (inOutMethod n s p)
inOutFunc n s = csInOut (function n s)
docInOutFunc n s = CP.docInOutFunc (inOutFunc n s)
instance RenderMethod CSharpCode where
intMethod m n s p t ps b = do
modify (if m then setCurrMain else id)
tp <- t
pms <- sequence ps
toCode . mthd . R.method n s p tp pms <$> b
intFunc = C.intFunc
commentedFunc cmt m = on2StateValues (on2CodeValues updateMthd) m
(onStateValue (onCodeValue R.commentedItem) cmt)
destructor _ = error $ CP.destructorError csName
mthdFromData _ d = toState $ toCode $ mthd d
instance MethodElim CSharpCode where
method = mthdDoc . unCSC
instance StateVarSym CSharpCode where
type StateVar CSharpCode = Doc
stateVar = CP.stateVar
stateVarDef = CP.stateVarDef
constVar = CP.constVar empty
instance StateVarElim CSharpCode where
stateVar = unCSC
instance ClassSym CSharpCode where
type Class CSharpCode = Doc
buildClass = G.buildClass
extraClass = CP.extraClass
implementingClass = G.implementingClass
docClass = CP.doxClass
instance RenderClass CSharpCode where
intClass = CP.intClass R.class'
inherit = CP.inherit
implements = CP.implements
commentedClass = G.commentedClass
instance ClassElim CSharpCode where
class' = unCSC
instance ModuleSym CSharpCode where
type Module CSharpCode = ModData
buildModule n = CP.buildModule' n langImport
instance RenderMod CSharpCode where
modFromData n = G.modFromData n (toCode . md n)
updateModuleDoc f = onCodeValue (updateMod f)
instance ModuleElim CSharpCode where
module' = modDoc . unCSC
instance BlockCommentSym CSharpCode where
type BlockComment CSharpCode = Doc
blockComment lns = toCode $ R.blockCmt lns blockCmtStart blockCmtEnd
docComment = onStateValue (\lns -> toCode $ R.docCmt lns docCmtStart
blockCmtEnd)
instance BlockCommentElim CSharpCode where
blockComment' = unCSC
addSystemImport :: VS a -> VS a
addSystemImport = (>>) $ modify (addLangImportVS csSystem)
csName, csVersion :: String
csName = "C#"
csVersion = "6.0"
csImport :: Label -> Doc
csImport n = text ("using " ++ n) <> endStatement
csBoolType :: (RenderSym r) => VSType r
csBoolType = typeFromData Boolean csBool (text csBool)
csFuncType :: (RenderSym r) => [VSType r] -> VSType r -> VSType r
csFuncType ps r = do
pts <- sequence ps
rt <- r
typeFromData (Func (map getType pts) (getType rt))
(csFunc `containing` intercalate listSep (map getTypeString $ pts ++ [rt]))
(text csFunc <> angles (hicat listSep' $ map RC.type' $ pts ++ [rt]))
csListSize, csForEach, csNamedArgSep, csLambdaSep :: Doc
csListSize = text "Count"
csForEach = text "foreach"
csNamedArgSep = colon <> space
csLambdaSep = text "=>"
csSystem, csConsole, csGeneric, csIO, csList, csInt, csFloat, csBool,
csChar, csParse, csReader, csWriter, csReadLine, csWrite, csWriteLine,
csIndex, csListAdd, csListAppend, csClose, csEOS, csSplit, csMain,
csFunc :: String
csSystem = "System"
csConsole = "Console"
csGeneric = csSysAccess $ "Collections" `access` "Generic"
csIO = csSysAccess "IO"
csList = "List"
csInt = "Int32"
csFloat = "Single"
csBool = "Boolean"
csChar = "Char"
csParse = "Parse"
csReader = "StreamReader"
csWriter = "StreamWriter"
csReadLine = "ReadLine"
csWrite = "Write"
csWriteLine = "WriteLine"
csIndex = "IndexOf"
csListAdd = "Insert"
csListAppend = "Add"
csClose = "Close"
csEOS = "EndOfStream"
csSplit = "Split"
csMain = "Main"
csFunc = "Func"
csSysAccess :: String -> String
csSysAccess = access csSystem
csUnaryMath :: (Monad r) => String -> VSOp r
csUnaryMath = addSystemImport . unOpPrec . mathFunc
csInfileType :: (RenderSym r) => VSType r
csInfileType = join $ modifyReturn (addLangImportVS csIO) $
typeFromData InFile csReader (text csReader)
csOutfileType :: (RenderSym r) => VSType r
csOutfileType = join $ modifyReturn (addLangImportVS csIO) $
typeFromData OutFile csWriter (text csWriter)
csLitList :: (RenderSym r) => (VSType r -> VSType r) -> VSType r -> [SValue r]
-> SValue r
csLitList f t' es' = do
es <- sequence es'
lt <- f t'
mkVal lt (new' <+> RC.type' lt
<+> braces (valueList es))
csLambda :: (RenderSym r) => [r (Variable r)] -> r (Value r) -> Doc
csLambda ps ex = parens (variableList ps) <+> csLambdaSep <+> RC.value ex
csReadLineFunc :: SValue CSharpCode
csReadLineFunc = extFuncApp csConsole csReadLine string []
csIntParse :: SValue CSharpCode -> SValue CSharpCode
csIntParse v = extFuncApp csInt csParse int [v]
csFloatParse :: SValue CSharpCode -> SValue CSharpCode
csFloatParse v = extFuncApp csFloat csParse float [v]
csDblParse :: SValue CSharpCode -> SValue CSharpCode
csDblParse v = extFuncApp CP.doubleRender csParse double [v]
csBoolParse :: SValue CSharpCode -> SValue CSharpCode
csBoolParse v = extFuncApp csBool csParse bool [v]
csCharParse :: SValue CSharpCode -> SValue CSharpCode
csCharParse v = extFuncApp csChar csParse char [v]
csSplitFunc :: Char -> VSFunction CSharpCode
csSplitFunc d = func csSplit (listType string) [litChar d]
csCast :: VSType CSharpCode -> SValue CSharpCode -> SValue CSharpCode
csCast = join .: on2StateValues (\t v -> csCast' (getType t) (getType $
valueType v) t v)
where csCast' Double String _ v = csDblParse (toState v)
csCast' Float String _ v = csFloatParse (toState v)
csCast' _ _ t v = mkStateVal (toState t) (R.castObj (R.cast
(RC.type' t)) (RC.value v))
-- This implementation generates a statement lambda to define the function.
C # 7 supports local functions , which would be a cleaner way to implement
this , but the mcs compiler used in our builds does not yet support
all features of C # 7 , so we can not generate local functions .
-- If support for local functions is added to mcs in the future, this
-- should be re-written to generate a local function.
csFuncDecDef :: (RenderSym r) => SVariable r -> [SVariable r] -> MSBody r ->
MSStatement r
csFuncDecDef v ps bod = do
vr <- zoom lensMStoVS v
pms <- mapM (zoom lensMStoVS) ps
t <- zoom lensMStoVS $ funcType (map (pure . variableType) pms)
(pure $ variableType vr)
b <- bod
modify (addLangImport csSystem)
mkStmt $ RC.type' t <+> text (variableName vr) <+> equals <+>
parens (variableList pms) <+> csLambdaSep <+> bodyStart $$
indent (RC.body b) $$ bodyEnd
csThrowDoc :: (RenderSym r) => r (Value r) -> Doc
csThrowDoc errMsg = throwLabel <+> new' <+> exceptionObj' <>
parens (RC.value errMsg)
csTryCatch :: (RenderSym r) => r (Body r) -> r (Body r) -> Doc
csTryCatch tb cb = vcat [
tryLabel <+> lbrace,
indent $ RC.body tb,
rbrace <+> catchLabel <+>
lbrace,
indent $ RC.body cb,
rbrace]
csDiscardInput :: SValue CSharpCode -> MSStatement CSharpCode
csDiscardInput = valStmt
csFileInput :: (RenderSym r) => SValue r -> SValue r
csFileInput f = objMethodCallNoParams string f csReadLine
csInput :: VSType CSharpCode -> SValue CSharpCode -> SValue CSharpCode
csInput tp inFn = do
t <- tp
csInputImport (getType t) (csInput' (getType t) inFn)
where csInput' Integer = csIntParse
csInput' Float = csFloatParse
csInput' Double = csDblParse
csInput' Boolean = csBoolParse
csInput' String = id
csInput' Char = csCharParse
csInput' _ = error "Attempt to read value of unreadable type"
csInputImport t = if t `elem` [Integer, Float, Double, Boolean, Char]
then addSystemImport else id
csOpenFileR :: (RenderSym r) => SValue r -> VSType r -> SValue r
csOpenFileR n r = newObj r [n]
csOpenFileWorA :: (RenderSym r) => SValue r -> VSType r -> SValue r -> SValue r
csOpenFileWorA n w a = newObj w [n, a]
csRef :: Doc -> Doc
csRef p = text "ref" <+> p
csOut :: Doc -> Doc
csOut p = text "out" <+> p
csInOutCall :: (Label -> VSType CSharpCode -> [SValue CSharpCode] ->
SValue CSharpCode) -> Label -> [SValue CSharpCode] -> [SVariable CSharpCode]
-> [SVariable CSharpCode] -> MSStatement CSharpCode
csInOutCall f n ins [out] [] = assign out $ f n (onStateValue variableType out)
ins
csInOutCall f n ins [] [out] = assign out $ f n (onStateValue variableType out)
(valueOf out : ins)
csInOutCall f n ins outs both = valStmt $ f n void (map (onStateValue
(onCodeValue (updateValDoc csRef)) . valueOf) both ++ ins ++ map
(onStateValue (onCodeValue (updateValDoc csOut)) . valueOf) outs)
csVarDec :: Binding -> MSStatement CSharpCode -> MSStatement CSharpCode
csVarDec Static _ = error "Static variables can't be declared locally to a function in C#. Use stateVar to make a static state variable instead."
csVarDec Dynamic d = d
csInOut :: (VSType CSharpCode -> [MSParameter CSharpCode] -> MSBody CSharpCode ->
SMethod CSharpCode) ->
[SVariable CSharpCode] -> [SVariable CSharpCode] -> [SVariable CSharpCode] ->
MSBody CSharpCode -> SMethod CSharpCode
csInOut f ins [v] [] b = f (onStateValue variableType v) (map param ins)
(on3StateValues (on3CodeValues surroundBody) (varDec v) b (returnStmt $
valueOf v))
csInOut f ins [] [v] b = f (onStateValue variableType v)
(map param $ v : ins) (on2StateValues (on2CodeValues appendToBody) b
(returnStmt $ valueOf v))
csInOut f ins outs both b = f void (map (onStateValue (onCodeValue
(updateParam csRef)) . param) both ++ map param ins ++ map (onStateValue
(onCodeValue (updateParam csOut)) . param) outs) b
| null | https://raw.githubusercontent.com/JacquesCarette/Drasil/c7c57e77e0de03158e7c4db6e74e13898a889764/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CSharpRenderer.hs | haskell | | The logic to render C# code is contained in this module
* C# Code Configuration -- defines syntax of all C# code
) = C.decrement1
This implementation generates a statement lambda to define the function.
If support for local functions is added to mcs in the future, this
should be re-written to generate a local function. | # LANGUAGE TypeFamilies #
# LANGUAGE PostfixOperators #
module GOOL.Drasil.LanguageRenderer.CSharpRenderer (
CSharpCode(..), csName, csVersion
) where
import Utils.Drasil (indent)
import GOOL.Drasil.CodeType (CodeType(..))
import GOOL.Drasil.ClassInterface (Label, MSBody, VSType, SVariable, SValue,
VSFunction, MSStatement, MSParameter, SMethod, OOProg, ProgramSym(..),
FileSym(..), PermanenceSym(..), BodySym(..), oneLiner, BlockSym(..),
TypeSym(..), TypeElim(..), VariableSym(..), VariableElim(..), ValueSym(..),
Argument(..), Literal(..), MathConstant(..), VariableValue(..),
CommandLineArgs(..), NumericExpression(..), BooleanExpression(..),
Comparison(..), ValueExpression(..), funcApp, selfFuncApp, extFuncApp,
newObj, InternalValueExp(..), objMethodCallNoParams, FunctionSym(..), ($.),
GetSet(..), List(..), InternalList(..), StatementSym(..),
AssignStatement(..), (&=), DeclStatement(..), IOStatement(..),
StringStatement(..), FuncAppStatement(..), CommentStatement(..),
ControlStatement(..), StatePattern(..), ObserverPattern(..),
StrategyPattern(..), ScopeSym(..), ParameterSym(..), MethodSym(..),
StateVarSym(..), ClassSym(..), ModuleSym(..))
import GOOL.Drasil.RendererClasses (RenderSym, RenderFile(..), ImportSym(..),
ImportElim, PermElim(binding), RenderBody(..), BodyElim, RenderBlock(..),
BlockElim, RenderType(..), InternalTypeElim, UnaryOpSym(..), BinaryOpSym(..),
OpElim(uOpPrec, bOpPrec), RenderVariable(..), InternalVarElim(variableBind),
RenderValue(..), ValueElim(valuePrec), InternalGetSet(..), InternalListFunc(..),
RenderFunction(..), FunctionElim(functionType), InternalAssignStmt(..),
InternalIOStmt(..), InternalControlStmt(..), RenderStatement(..),
StatementElim(statementTerm), RenderScope(..), ScopeElim, MethodTypeSym(..),
RenderParam(..), ParamElim(parameterName, parameterType), RenderMethod(..),
MethodElim, StateVarElim, RenderClass(..), ClassElim, RenderMod(..), ModuleElim,
BlockCommentSym(..), BlockCommentElim)
import qualified GOOL.Drasil.RendererClasses as RC (import', perm, body, block,
type', uOp, bOp, variable, value, function, statement, scope, parameter,
method, stateVar, class', module', blockComment')
import GOOL.Drasil.LanguageRenderer (new, dot, blockCmtStart, blockCmtEnd,
docCmtStart, bodyStart, bodyEnd, endStatement, commentStart, elseIfLabel,
inLabel, tryLabel, catchLabel, throwLabel, exceptionObj', new', listSep',
args, nullLabel, listSep, access, containing, mathFunc, valueList,
variableList, appendToBody, surroundBody)
import qualified GOOL.Drasil.LanguageRenderer as R (class', multiStmt, body,
printFile, param, method, listDec, classVar, func, cast, listSetFunc,
castObj, static, dynamic, break, continue, private, public, blockCmt, docCmt,
addComments, commentedMod, commentedItem)
import GOOL.Drasil.LanguageRenderer.Constructors (mkStmt,
mkStateVal, mkVal, VSOp, unOpPrec, powerPrec, unExpr, unExpr',
unExprNumDbl, typeUnExpr, binExpr, binExprNumDbl', typeBinExpr)
import qualified GOOL.Drasil.LanguageRenderer.LanguagePolymorphic as G (
multiBody, block, multiBlock, listInnerType, obj, csc, sec, cot,
negateOp, equalOp, notEqualOp, greaterOp, greaterEqualOp, lessOp,
lessEqualOp, plusOp, minusOp, multOp, divideOp, moduloOp, var, staticVar,
objVar, arrayElem, litChar, litDouble, litInt, litString, valueOf, arg,
argsList, objAccess, objMethodCall, call, funcAppMixedArgs,
selfFuncAppMixedArgs, newObjMixedArgs, lambda, func, get, set, listAdd,
listAppend, listAccess, listSet, getFunc, setFunc, listAppendFunc, stmt,
loopStmt, emptyStmt, assign, subAssign, increment, objDecNew, print,
closeFile, returnStmt, valStmt, comment, throw, ifCond, tryCatch, construct,
param, method, getMethod, setMethod, function, buildClass, implementingClass,
commentedClass, modFromData, fileDoc, fileFromData)
import qualified GOOL.Drasil.LanguageRenderer.CommonPseudoOO as CP (int,
constructor, doxFunc, doxClass, doxMod, extVar, classVar, objVarSelf,
extFuncAppMixedArgs, indexOf, listAddFunc, discardFileLine, intClass,
arrayType, pi, printSt, arrayDec, arrayDecDef, openFileA, forEach, docMain,
mainFunction, buildModule', string, constDecDef, docInOutFunc, bindingError,
notNull, listDecDef, destructorError, stateVarDef, constVar, listSetFunc,
extraClass, listAccessFunc, doubleRender, openFileR, openFileW, stateVar,
inherit, implements)
import qualified GOOL.Drasil.LanguageRenderer.CLike as C (float, double, char,
listType, void, notOp, andOp, orOp, self, litTrue, litFalse, litFloat,
inlineIf, libFuncAppMixedArgs, libNewObjMixedArgs, listSize, increment1,
decrement1, varDec, varDecDef, listDec, extObjDecNew, switch, for, while,
intFunc, multiAssignError, multiReturnError, multiTypeError)
import qualified GOOL.Drasil.LanguageRenderer.Macros as M (ifExists,
runStrategy, listSlice, stringListVals, stringListLists, forRange,
notifyObservers, checkState)
import GOOL.Drasil.AST (Terminator(..), FileType(..), FileData(..), fileD,
FuncData(..), fd, ModData(..), md, updateMod, MethodData(..), mthd,
updateMthd, OpData(..), ParamData(..), pd, updateParam, ProgData(..), progD,
TypeData(..), td, ValData(..), vd, updateValDoc, Binding(..), VarData(..),
vard)
import GOOL.Drasil.Helpers (angles, hicat, toCode, toState, onCodeValue,
onStateValue, on2CodeValues, on2StateValues, on3CodeValues, on3StateValues,
on2StateWrapped, onCodeList, onStateList)
import GOOL.Drasil.State (VS, lensGStoFS, lensMStoVS, modifyReturn, revFiles,
addLangImport, addLangImportVS, setFileType, getClassName, setCurrMain)
import Prelude hiding (break,print,(<>),sin,cos,tan,floor)
import Control.Lens.Zoom (zoom)
import Control.Monad (join)
import Control.Monad.State (modify)
import Data.Composition ((.:))
import Data.List (intercalate)
import Text.PrettyPrint.HughesPJ (Doc, text, (<>), (<+>), ($$), parens, empty,
equals, vcat, lbrace, rbrace, braces, colon, space, quotes)
csExt :: String
csExt = "cs"
newtype CSharpCode a = CSC {unCSC :: a} deriving Eq
instance Functor CSharpCode where
fmap f (CSC x) = CSC (f x)
instance Applicative CSharpCode where
pure = CSC
(CSC f) <*> (CSC x) = CSC (f x)
instance Monad CSharpCode where
CSC x >>= f = f x
instance OOProg CSharpCode where
instance ProgramSym CSharpCode where
type Program CSharpCode = ProgData
prog n files = do
fs <- mapM (zoom lensGStoFS) files
modify revFiles
pure $ onCodeList (progD n) fs
instance RenderSym CSharpCode
instance FileSym CSharpCode where
type File CSharpCode = FileData
fileDoc m = do
modify (setFileType Combined)
G.fileDoc csExt top bottom m
docMod = CP.doxMod csExt
instance RenderFile CSharpCode where
top _ = toCode empty
bottom = toCode empty
commentedMod = on2StateValues (on2CodeValues R.commentedMod)
fileFromData = G.fileFromData (onCodeValue . fileD)
instance ImportSym CSharpCode where
type Import CSharpCode = Doc
langImport = toCode . csImport
modImport = langImport
instance ImportElim CSharpCode where
import' = unCSC
instance PermanenceSym CSharpCode where
type Permanence CSharpCode = Doc
static = toCode R.static
dynamic = toCode R.dynamic
instance PermElim CSharpCode where
perm = unCSC
binding = error $ CP.bindingError csName
instance BodySym CSharpCode where
type Body CSharpCode = Doc
body = onStateList (onCodeList R.body)
addComments s = onStateValue (onCodeValue (R.addComments s commentStart))
instance RenderBody CSharpCode where
multiBody = G.multiBody
instance BodyElim CSharpCode where
body = unCSC
instance BlockSym CSharpCode where
type Block CSharpCode = Doc
block = G.block
instance RenderBlock CSharpCode where
multiBlock = G.multiBlock
instance BlockElim CSharpCode where
block = unCSC
instance TypeSym CSharpCode where
type Type CSharpCode = TypeData
bool = addSystemImport csBoolType
int = CP.int
float = C.float
double = C.double
char = C.char
string = CP.string
infile = csInfileType
outfile = csOutfileType
listType t = do
modify (addLangImportVS csGeneric)
C.listType csList t
arrayType = CP.arrayType
listInnerType = G.listInnerType
obj = G.obj
funcType = csFuncType
void = C.void
instance TypeElim CSharpCode where
getType = cType . unCSC
getTypeString = typeString . unCSC
instance RenderType CSharpCode where
multiType _ = error $ C.multiTypeError csName
typeFromData t s d = toState $ toCode $ td t s d
instance InternalTypeElim CSharpCode where
type' = typeDoc . unCSC
instance UnaryOpSym CSharpCode where
type UnaryOp CSharpCode = OpData
notOp = C.notOp
negateOp = G.negateOp
sqrtOp = csUnaryMath "Sqrt"
absOp = csUnaryMath "Abs"
logOp = csUnaryMath "Log10"
lnOp = csUnaryMath "Log"
expOp = csUnaryMath "Exp"
sinOp = csUnaryMath "Sin"
cosOp = csUnaryMath "Cos"
tanOp = csUnaryMath "Tan"
asinOp = csUnaryMath "Asin"
acosOp = csUnaryMath "Acos"
atanOp = csUnaryMath "Atan"
floorOp = csUnaryMath "Floor"
ceilOp = csUnaryMath "Ceiling"
instance BinaryOpSym CSharpCode where
type BinaryOp CSharpCode = OpData
equalOp = G.equalOp
notEqualOp = G.notEqualOp
greaterOp = G.greaterOp
greaterEqualOp = G.greaterEqualOp
lessOp = G.lessOp
lessEqualOp = G.lessEqualOp
plusOp = G.plusOp
minusOp = G.minusOp
multOp = G.multOp
divideOp = G.divideOp
powerOp = addSystemImport $ powerPrec $ mathFunc "Pow"
moduloOp = G.moduloOp
andOp = C.andOp
orOp = C.orOp
instance OpElim CSharpCode where
uOp = opDoc . unCSC
bOp = opDoc . unCSC
uOpPrec = opPrec . unCSC
bOpPrec = opPrec . unCSC
instance VariableSym CSharpCode where
type Variable CSharpCode = VarData
var = G.var
staticVar = G.staticVar
const = var
extVar = CP.extVar
self = C.self
classVar = CP.classVar R.classVar
extClassVar = classVar
objVar = G.objVar
objVarSelf = CP.objVarSelf
arrayElem i = G.arrayElem (litInt i)
instance VariableElim CSharpCode where
variableName = varName . unCSC
variableType = onCodeValue varType
instance InternalVarElim CSharpCode where
variableBind = varBind . unCSC
variable = varDoc . unCSC
instance RenderVariable CSharpCode where
varFromData b n t' d = do
t <- t'
toState $ on2CodeValues (vard b n) t (toCode d)
instance ValueSym CSharpCode where
type Value CSharpCode = ValData
valueType = onCodeValue valType
instance Argument CSharpCode where
pointerArg = id
instance Literal CSharpCode where
litTrue = C.litTrue
litFalse = C.litFalse
litChar = G.litChar quotes
litDouble = G.litDouble
litFloat = C.litFloat
litInt = G.litInt
litString = G.litString
litArray = csLitList arrayType
litList = csLitList listType
instance MathConstant CSharpCode where
pi = CP.pi
instance VariableValue CSharpCode where
valueOf = G.valueOf
instance CommandLineArgs CSharpCode where
arg n = G.arg (litInt n) argsList
argsList = G.argsList args
argExists i = listSize argsList ?> litInt (fromIntegral i)
instance NumericExpression CSharpCode where
(#~) = unExpr' negateOp
(#/^) = unExprNumDbl sqrtOp
(#|) = unExpr absOp
(#+) = binExpr plusOp
(#-) = binExpr minusOp
(#*) = binExpr multOp
(#/) = binExpr divideOp
(#%) = binExpr moduloOp
(#^) = binExprNumDbl' powerOp
log = unExprNumDbl logOp
ln = unExprNumDbl lnOp
exp = unExprNumDbl expOp
sin = unExprNumDbl sinOp
cos = unExprNumDbl cosOp
tan = unExprNumDbl tanOp
csc = G.csc
sec = G.sec
cot = G.cot
arcsin = unExprNumDbl asinOp
arccos = unExprNumDbl acosOp
arctan = unExprNumDbl atanOp
floor = unExpr floorOp
ceil = unExpr ceilOp
instance BooleanExpression CSharpCode where
(?!) = typeUnExpr notOp bool
(?&&) = typeBinExpr andOp bool
(?||) = typeBinExpr orOp bool
instance Comparison CSharpCode where
(?<) = typeBinExpr lessOp bool
(?<=) = typeBinExpr lessEqualOp bool
(?>) = typeBinExpr greaterOp bool
(?>=) = typeBinExpr greaterEqualOp bool
(?==) = typeBinExpr equalOp bool
(?!=) = typeBinExpr notEqualOp bool
instance ValueExpression CSharpCode where
inlineIf = C.inlineIf
funcAppMixedArgs = G.funcAppMixedArgs
selfFuncAppMixedArgs = G.selfFuncAppMixedArgs dot self
extFuncAppMixedArgs = CP.extFuncAppMixedArgs
libFuncAppMixedArgs = C.libFuncAppMixedArgs
newObjMixedArgs = G.newObjMixedArgs (new ++ " ")
extNewObjMixedArgs _ = newObjMixedArgs
libNewObjMixedArgs = C.libNewObjMixedArgs
lambda = G.lambda csLambda
notNull = CP.notNull nullLabel
instance RenderValue CSharpCode where
inputFunc = addSystemImport csReadLineFunc
printFunc = addSystemImport $ mkStateVal void (text $ csConsole `access`
csWrite)
printLnFunc = addSystemImport $ mkStateVal void (text $ csConsole `access`
csWriteLine)
printFileFunc w' = on2StateWrapped (\w vt ->
mkVal vt . R.printFile csWrite . RC.value $ w) w' void
printFileLnFunc w' = on2StateWrapped (\w vt ->
mkVal vt . R.printFile csWriteLine . RC.value $ w) w' void
cast = csCast
call = G.call csNamedArgSep
valFromData p t' d = do
t <- t'
toState $ on2CodeValues (vd p) t (toCode d)
instance ValueElim CSharpCode where
valuePrec = valPrec . unCSC
value = val . unCSC
instance InternalValueExp CSharpCode where
objMethodCallMixedArgs' = G.objMethodCall
instance FunctionSym CSharpCode where
type Function CSharpCode = FuncData
func = G.func
objAccess = G.objAccess
instance GetSet CSharpCode where
get = G.get
set = G.set
instance List CSharpCode where
listSize = C.listSize
listAdd = G.listAdd
listAppend = G.listAppend
listAccess = G.listAccess
listSet = G.listSet
indexOf = CP.indexOf csIndex
instance InternalList CSharpCode where
listSlice' = M.listSlice
instance InternalGetSet CSharpCode where
getFunc = G.getFunc
setFunc = G.setFunc
instance InternalListFunc CSharpCode where
listSizeFunc = funcFromData (R.func csListSize) int
listAddFunc _ = CP.listAddFunc csListAdd
listAppendFunc = G.listAppendFunc csListAppend
listAccessFunc = CP.listAccessFunc
listSetFunc = CP.listSetFunc R.listSetFunc
instance RenderFunction CSharpCode where
funcFromData d = onStateValue (onCodeValue (`fd` d))
instance FunctionElim CSharpCode where
functionType = onCodeValue fType
function = funcDoc . unCSC
instance InternalAssignStmt CSharpCode where
multiAssign _ _ = error $ C.multiAssignError csName
instance InternalIOStmt CSharpCode where
printSt _ _ = CP.printSt
instance InternalControlStmt CSharpCode where
multiReturn _ = error $ C.multiReturnError csName
instance RenderStatement CSharpCode where
stmt = G.stmt
loopStmt = G.loopStmt
emptyStmt = G.emptyStmt
stmtFromData d t = toState $ toCode (d, t)
instance StatementElim CSharpCode where
statement = fst . unCSC
statementTerm = snd . unCSC
instance StatementSym CSharpCode where
type Statement CSharpCode = (Doc, Terminator)
valStmt = G.valStmt Semi
multi = onStateList (onCodeList R.multiStmt)
instance AssignStatement CSharpCode where
assign = G.assign Semi
(&-=) = G.subAssign Semi
(&+=) = G.increment
(&++) = C.increment1
instance DeclStatement CSharpCode where
varDec v = zoom lensMStoVS v >>= (\v' -> csVarDec (variableBind v') $
C.varDec static dynamic empty v)
varDecDef = C.varDecDef Semi
listDec n v = zoom lensMStoVS v >>= (\v' -> C.listDec (R.listDec v')
(litInt n) v)
listDecDef = CP.listDecDef
arrayDec n = CP.arrayDec (litInt n)
arrayDecDef = CP.arrayDecDef
objDecDef = varDecDef
objDecNew = G.objDecNew
extObjDecNew = C.extObjDecNew
constDecDef = CP.constDecDef
funcDecDef = csFuncDecDef
instance IOStatement CSharpCode where
print = G.print False Nothing printFunc
printLn = G.print True Nothing printLnFunc
printStr = G.print False Nothing printFunc . litString
printStrLn = G.print True Nothing printLnFunc . litString
printFile f = G.print False (Just f) (printFileFunc f)
printFileLn f = G.print True (Just f) (printFileLnFunc f)
printFileStr f = G.print False (Just f) (printFileFunc f) . litString
printFileStrLn f = G.print True (Just f) (printFileLnFunc f) . litString
getInput v = v &= csInput (onStateValue variableType v) inputFunc
discardInput = csDiscardInput inputFunc
getFileInput f v = v &= csInput (onStateValue variableType v) (csFileInput f)
discardFileInput f = valStmt $ csFileInput f
openFileR = CP.openFileR csOpenFileR
openFileW = CP.openFileW csOpenFileWorA
openFileA = CP.openFileA csOpenFileWorA
closeFile = G.closeFile csClose
getFileInputLine = getFileInput
discardFileLine = CP.discardFileLine csReadLine
getFileInputAll f v = while ((f $. funcFromData (dot <> text csEOS) bool) ?!)
(oneLiner $ valStmt $ listAppend (valueOf v) (csFileInput f))
instance StringStatement CSharpCode where
stringSplit d vnew s = assign vnew $ newObj (listType string)
[s $. csSplitFunc d]
stringListVals = M.stringListVals
stringListLists = M.stringListLists
instance FuncAppStatement CSharpCode where
inOutCall = csInOutCall funcApp
selfInOutCall = csInOutCall selfFuncApp
extInOutCall m = csInOutCall (extFuncApp m)
instance CommentStatement CSharpCode where
comment = G.comment commentStart
instance ControlStatement CSharpCode where
break = mkStmt R.break
continue = mkStmt R.continue
returnStmt = G.returnStmt Semi
throw msg = do
modify (addLangImport csSystem)
G.throw csThrowDoc Semi msg
ifCond = G.ifCond parens bodyStart elseIfLabel bodyEnd
switch = C.switch parens break
ifExists = M.ifExists
for = C.for bodyStart bodyEnd
forRange = M.forRange
forEach = CP.forEach bodyStart bodyEnd csForEach inLabel
while = C.while parens bodyStart bodyEnd
tryCatch = G.tryCatch csTryCatch
instance StatePattern CSharpCode where
checkState = M.checkState
instance ObserverPattern CSharpCode where
notifyObservers = M.notifyObservers
instance StrategyPattern CSharpCode where
runStrategy = M.runStrategy
instance ScopeSym CSharpCode where
type Scope CSharpCode = Doc
private = toCode R.private
public = toCode R.public
instance RenderScope CSharpCode where
scopeFromData _ = toCode
instance ScopeElim CSharpCode where
scope = unCSC
instance MethodTypeSym CSharpCode where
type MethodType CSharpCode = TypeData
mType = zoom lensMStoVS
construct = G.construct
instance ParameterSym CSharpCode where
type Parameter CSharpCode = ParamData
param = G.param R.param
pointerParam = param
instance RenderParam CSharpCode where
paramFromData v' d = do
v <- zoom lensMStoVS v'
toState $ on2CodeValues pd v (toCode d)
instance ParamElim CSharpCode where
parameterName = variableName . onCodeValue paramVar
parameterType = variableType . onCodeValue paramVar
parameter = paramDoc . unCSC
instance MethodSym CSharpCode where
type Method CSharpCode = MethodData
method = G.method
getMethod = G.getMethod
setMethod = G.setMethod
constructor ps is b = getClassName >>= (\n -> CP.constructor n ps is b)
docMain = CP.docMain
function = G.function
mainFunction = CP.mainFunction string csMain
docFunc = CP.doxFunc
inOutMethod n s p = csInOut (method n s p)
docInOutMethod n s p = CP.docInOutFunc (inOutMethod n s p)
inOutFunc n s = csInOut (function n s)
docInOutFunc n s = CP.docInOutFunc (inOutFunc n s)
instance RenderMethod CSharpCode where
intMethod m n s p t ps b = do
modify (if m then setCurrMain else id)
tp <- t
pms <- sequence ps
toCode . mthd . R.method n s p tp pms <$> b
intFunc = C.intFunc
commentedFunc cmt m = on2StateValues (on2CodeValues updateMthd) m
(onStateValue (onCodeValue R.commentedItem) cmt)
destructor _ = error $ CP.destructorError csName
mthdFromData _ d = toState $ toCode $ mthd d
instance MethodElim CSharpCode where
method = mthdDoc . unCSC
instance StateVarSym CSharpCode where
type StateVar CSharpCode = Doc
stateVar = CP.stateVar
stateVarDef = CP.stateVarDef
constVar = CP.constVar empty
instance StateVarElim CSharpCode where
stateVar = unCSC
instance ClassSym CSharpCode where
type Class CSharpCode = Doc
buildClass = G.buildClass
extraClass = CP.extraClass
implementingClass = G.implementingClass
docClass = CP.doxClass
instance RenderClass CSharpCode where
intClass = CP.intClass R.class'
inherit = CP.inherit
implements = CP.implements
commentedClass = G.commentedClass
instance ClassElim CSharpCode where
class' = unCSC
instance ModuleSym CSharpCode where
type Module CSharpCode = ModData
buildModule n = CP.buildModule' n langImport
instance RenderMod CSharpCode where
modFromData n = G.modFromData n (toCode . md n)
updateModuleDoc f = onCodeValue (updateMod f)
instance ModuleElim CSharpCode where
module' = modDoc . unCSC
instance BlockCommentSym CSharpCode where
type BlockComment CSharpCode = Doc
blockComment lns = toCode $ R.blockCmt lns blockCmtStart blockCmtEnd
docComment = onStateValue (\lns -> toCode $ R.docCmt lns docCmtStart
blockCmtEnd)
instance BlockCommentElim CSharpCode where
blockComment' = unCSC
addSystemImport :: VS a -> VS a
addSystemImport = (>>) $ modify (addLangImportVS csSystem)
csName, csVersion :: String
csName = "C#"
csVersion = "6.0"
csImport :: Label -> Doc
csImport n = text ("using " ++ n) <> endStatement
csBoolType :: (RenderSym r) => VSType r
csBoolType = typeFromData Boolean csBool (text csBool)
csFuncType :: (RenderSym r) => [VSType r] -> VSType r -> VSType r
csFuncType ps r = do
pts <- sequence ps
rt <- r
typeFromData (Func (map getType pts) (getType rt))
(csFunc `containing` intercalate listSep (map getTypeString $ pts ++ [rt]))
(text csFunc <> angles (hicat listSep' $ map RC.type' $ pts ++ [rt]))
csListSize, csForEach, csNamedArgSep, csLambdaSep :: Doc
csListSize = text "Count"
csForEach = text "foreach"
csNamedArgSep = colon <> space
csLambdaSep = text "=>"
csSystem, csConsole, csGeneric, csIO, csList, csInt, csFloat, csBool,
csChar, csParse, csReader, csWriter, csReadLine, csWrite, csWriteLine,
csIndex, csListAdd, csListAppend, csClose, csEOS, csSplit, csMain,
csFunc :: String
csSystem = "System"
csConsole = "Console"
csGeneric = csSysAccess $ "Collections" `access` "Generic"
csIO = csSysAccess "IO"
csList = "List"
csInt = "Int32"
csFloat = "Single"
csBool = "Boolean"
csChar = "Char"
csParse = "Parse"
csReader = "StreamReader"
csWriter = "StreamWriter"
csReadLine = "ReadLine"
csWrite = "Write"
csWriteLine = "WriteLine"
csIndex = "IndexOf"
csListAdd = "Insert"
csListAppend = "Add"
csClose = "Close"
csEOS = "EndOfStream"
csSplit = "Split"
csMain = "Main"
csFunc = "Func"
csSysAccess :: String -> String
csSysAccess = access csSystem
csUnaryMath :: (Monad r) => String -> VSOp r
csUnaryMath = addSystemImport . unOpPrec . mathFunc
csInfileType :: (RenderSym r) => VSType r
csInfileType = join $ modifyReturn (addLangImportVS csIO) $
typeFromData InFile csReader (text csReader)
csOutfileType :: (RenderSym r) => VSType r
csOutfileType = join $ modifyReturn (addLangImportVS csIO) $
typeFromData OutFile csWriter (text csWriter)
csLitList :: (RenderSym r) => (VSType r -> VSType r) -> VSType r -> [SValue r]
-> SValue r
csLitList f t' es' = do
es <- sequence es'
lt <- f t'
mkVal lt (new' <+> RC.type' lt
<+> braces (valueList es))
csLambda :: (RenderSym r) => [r (Variable r)] -> r (Value r) -> Doc
csLambda ps ex = parens (variableList ps) <+> csLambdaSep <+> RC.value ex
csReadLineFunc :: SValue CSharpCode
csReadLineFunc = extFuncApp csConsole csReadLine string []
csIntParse :: SValue CSharpCode -> SValue CSharpCode
csIntParse v = extFuncApp csInt csParse int [v]
csFloatParse :: SValue CSharpCode -> SValue CSharpCode
csFloatParse v = extFuncApp csFloat csParse float [v]
csDblParse :: SValue CSharpCode -> SValue CSharpCode
csDblParse v = extFuncApp CP.doubleRender csParse double [v]
csBoolParse :: SValue CSharpCode -> SValue CSharpCode
csBoolParse v = extFuncApp csBool csParse bool [v]
csCharParse :: SValue CSharpCode -> SValue CSharpCode
csCharParse v = extFuncApp csChar csParse char [v]
csSplitFunc :: Char -> VSFunction CSharpCode
csSplitFunc d = func csSplit (listType string) [litChar d]
csCast :: VSType CSharpCode -> SValue CSharpCode -> SValue CSharpCode
csCast = join .: on2StateValues (\t v -> csCast' (getType t) (getType $
valueType v) t v)
where csCast' Double String _ v = csDblParse (toState v)
csCast' Float String _ v = csFloatParse (toState v)
csCast' _ _ t v = mkStateVal (toState t) (R.castObj (R.cast
(RC.type' t)) (RC.value v))
C # 7 supports local functions , which would be a cleaner way to implement
this , but the mcs compiler used in our builds does not yet support
all features of C # 7 , so we can not generate local functions .
csFuncDecDef :: (RenderSym r) => SVariable r -> [SVariable r] -> MSBody r ->
MSStatement r
csFuncDecDef v ps bod = do
vr <- zoom lensMStoVS v
pms <- mapM (zoom lensMStoVS) ps
t <- zoom lensMStoVS $ funcType (map (pure . variableType) pms)
(pure $ variableType vr)
b <- bod
modify (addLangImport csSystem)
mkStmt $ RC.type' t <+> text (variableName vr) <+> equals <+>
parens (variableList pms) <+> csLambdaSep <+> bodyStart $$
indent (RC.body b) $$ bodyEnd
csThrowDoc :: (RenderSym r) => r (Value r) -> Doc
csThrowDoc errMsg = throwLabel <+> new' <+> exceptionObj' <>
parens (RC.value errMsg)
csTryCatch :: (RenderSym r) => r (Body r) -> r (Body r) -> Doc
csTryCatch tb cb = vcat [
tryLabel <+> lbrace,
indent $ RC.body tb,
rbrace <+> catchLabel <+>
lbrace,
indent $ RC.body cb,
rbrace]
csDiscardInput :: SValue CSharpCode -> MSStatement CSharpCode
csDiscardInput = valStmt
csFileInput :: (RenderSym r) => SValue r -> SValue r
csFileInput f = objMethodCallNoParams string f csReadLine
csInput :: VSType CSharpCode -> SValue CSharpCode -> SValue CSharpCode
csInput tp inFn = do
t <- tp
csInputImport (getType t) (csInput' (getType t) inFn)
where csInput' Integer = csIntParse
csInput' Float = csFloatParse
csInput' Double = csDblParse
csInput' Boolean = csBoolParse
csInput' String = id
csInput' Char = csCharParse
csInput' _ = error "Attempt to read value of unreadable type"
csInputImport t = if t `elem` [Integer, Float, Double, Boolean, Char]
then addSystemImport else id
csOpenFileR :: (RenderSym r) => SValue r -> VSType r -> SValue r
csOpenFileR n r = newObj r [n]
csOpenFileWorA :: (RenderSym r) => SValue r -> VSType r -> SValue r -> SValue r
csOpenFileWorA n w a = newObj w [n, a]
csRef :: Doc -> Doc
csRef p = text "ref" <+> p
csOut :: Doc -> Doc
csOut p = text "out" <+> p
csInOutCall :: (Label -> VSType CSharpCode -> [SValue CSharpCode] ->
SValue CSharpCode) -> Label -> [SValue CSharpCode] -> [SVariable CSharpCode]
-> [SVariable CSharpCode] -> MSStatement CSharpCode
csInOutCall f n ins [out] [] = assign out $ f n (onStateValue variableType out)
ins
csInOutCall f n ins [] [out] = assign out $ f n (onStateValue variableType out)
(valueOf out : ins)
csInOutCall f n ins outs both = valStmt $ f n void (map (onStateValue
(onCodeValue (updateValDoc csRef)) . valueOf) both ++ ins ++ map
(onStateValue (onCodeValue (updateValDoc csOut)) . valueOf) outs)
csVarDec :: Binding -> MSStatement CSharpCode -> MSStatement CSharpCode
csVarDec Static _ = error "Static variables can't be declared locally to a function in C#. Use stateVar to make a static state variable instead."
csVarDec Dynamic d = d
csInOut :: (VSType CSharpCode -> [MSParameter CSharpCode] -> MSBody CSharpCode ->
SMethod CSharpCode) ->
[SVariable CSharpCode] -> [SVariable CSharpCode] -> [SVariable CSharpCode] ->
MSBody CSharpCode -> SMethod CSharpCode
csInOut f ins [v] [] b = f (onStateValue variableType v) (map param ins)
(on3StateValues (on3CodeValues surroundBody) (varDec v) b (returnStmt $
valueOf v))
csInOut f ins [] [v] b = f (onStateValue variableType v)
(map param $ v : ins) (on2StateValues (on2CodeValues appendToBody) b
(returnStmt $ valueOf v))
csInOut f ins outs both b = f void (map (onStateValue (onCodeValue
(updateParam csRef)) . param) both ++ map param ins ++ map (onStateValue
(onCodeValue (updateParam csOut)) . param) outs) b
|
7462f3e3a97ff3409badafa8d1118a92ad28404a6843645baa5fc3950d607aca | qingliangcn/mgee | mgee_unittest_packet.erl | %%%----------------------------------------------------------------------
2010 mgee ( Ming Game Engine Erlang )
%%%
@author odinxu
@date 2010 - 2 - 21
%%% @doc Unit Test for mgee_packet
%%% @end
%%%----------------------------------------------------------------------
-module(mgee_unittest_packet).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").
test() -> ok.
packet_encode_test() ->
Module = <<"role">>,
Method = <<"add">>,
?assertEqual(encode_m_role_add_toc, mgee_packet:get_encode_func(Module, Method) ),
ok
.
packet_decode_test() ->
Module = <<"role">>,
Method = <<"add">>,
?assertEqual(decode_m_role_add_tos, mgee_packet:get_decode_func(Module, Method) ),
lists:foreach(
fun(_T) ->
mgee_packet:get_decode_func(Module, Method)
end, lists:seq(1,10000,1) ),
ok
.
| null | https://raw.githubusercontent.com/qingliangcn/mgee/b65babc3a34ef678ae2b25ce1a8fdd06b2707bb8/unittest/mgee_unittest_packet.erl | erlang | ----------------------------------------------------------------------
@doc Unit Test for mgee_packet
@end
----------------------------------------------------------------------
| 2010 mgee ( Ming Game Engine Erlang )
@author odinxu
@date 2010 - 2 - 21
-module(mgee_unittest_packet).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").
test() -> ok.
packet_encode_test() ->
Module = <<"role">>,
Method = <<"add">>,
?assertEqual(encode_m_role_add_toc, mgee_packet:get_encode_func(Module, Method) ),
ok
.
packet_decode_test() ->
Module = <<"role">>,
Method = <<"add">>,
?assertEqual(decode_m_role_add_tos, mgee_packet:get_decode_func(Module, Method) ),
lists:foreach(
fun(_T) ->
mgee_packet:get_decode_func(Module, Method)
end, lists:seq(1,10000,1) ),
ok
.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.