_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
dda1f5678ac0b311f85e62ce4510b54d1e06e7d2aeca7c9a01b51ea69620fa70
theronic/eacl
exceptions.clj
(ns eacl.exceptions)
null
https://raw.githubusercontent.com/theronic/eacl/e9913b646bbc2d4492994ce2c67a365e53b0e76c/clj-eacl/src/eacl/exceptions.clj
clojure
(ns eacl.exceptions)
2d0b0cd865dc267b78919f8454eea29464dda6e8bb0e6659b6c726e9401393a0
let-def/lrgrep
test_ko_05.ml
(* -error-compiling-code-with-functor-module/6352 *) let () = module P = Csv(ShowInt)
null
https://raw.githubusercontent.com/let-def/lrgrep/29e64174dc9617bcd1871fd2e4fd712269568324/demo/test_ko_05.ml
ocaml
-error-compiling-code-with-functor-module/6352
let () = module P = Csv(ShowInt)
de953d6ca9a6257be158c2f6f0a3900947b368a9e7bc38f81fa91ffe9f269150
input-output-hk/ouroboros-network
LeaderSchedule.hs
{-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleInstances # # LANGUAGE RecordWildCards # {-# LANGUAGE TypeFamilies #-} module Ouroboros.Consensus.Protocol.LeaderSchedule ( LeaderSchedule (..) , leaderScheduleFor ) where import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Set (Set) import GHC.Generics (Generic) import NoThunks.Class (NoThunks) import Ouroboros.Consensus.Block import Ouroboros.Consensus.NodeId (CoreNodeId (..), fromCoreNodeId) import Ouroboros.Consensus.Util.Condense (Condense (..)) ------------------------------------------------------------------------------ Leader schedule The leader schedule allows us to define , in tests , precisely when each node is meant to lead . Unlike in , say , Praos , where this is determined by a single random seed , this gives us the ability to construct test cases in an inspectable and shrinkable manner . ------------------------------------------------------------------------------ Leader schedule The leader schedule allows us to define, in tests, precisely when each node is meant to lead. Unlike in, say, Praos, where this is determined by a single random seed, this gives us the ability to construct test cases in an inspectable and shrinkable manner. -------------------------------------------------------------------------------} newtype LeaderSchedule = LeaderSchedule { getLeaderSchedule :: Map SlotNo [CoreNodeId] } deriving stock (Show, Eq, Ord, Generic) deriving anyclass (NoThunks) -- | The 'Slots' a given node is supposed to lead in leaderScheduleFor :: CoreNodeId -> LeaderSchedule -> Set SlotNo leaderScheduleFor nid = Map.keysSet . Map.filter (elem nid) . getLeaderSchedule instance Semigroup LeaderSchedule where LeaderSchedule l <> LeaderSchedule r = LeaderSchedule $ Map.unionWith comb l r where comb ls rs = ls ++ filter (`notElem` ls) rs instance Condense LeaderSchedule where condense (LeaderSchedule m) = condense $ map (\(s, ls) -> (s, map fromCoreNodeId ls)) $ Map.toList m
null
https://raw.githubusercontent.com/input-output-hk/ouroboros-network/54cd34e68afafe957feef485ceaee3171efb0693/ouroboros-consensus/src/Ouroboros/Consensus/Protocol/LeaderSchedule.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE TypeFamilies # ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -----------------------------------------------------------------------------} | The 'Slots' a given node is supposed to lead in
# LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleInstances # # LANGUAGE RecordWildCards # module Ouroboros.Consensus.Protocol.LeaderSchedule ( LeaderSchedule (..) , leaderScheduleFor ) where import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Set (Set) import GHC.Generics (Generic) import NoThunks.Class (NoThunks) import Ouroboros.Consensus.Block import Ouroboros.Consensus.NodeId (CoreNodeId (..), fromCoreNodeId) import Ouroboros.Consensus.Util.Condense (Condense (..)) Leader schedule The leader schedule allows us to define , in tests , precisely when each node is meant to lead . Unlike in , say , Praos , where this is determined by a single random seed , this gives us the ability to construct test cases in an inspectable and shrinkable manner . Leader schedule The leader schedule allows us to define, in tests, precisely when each node is meant to lead. Unlike in, say, Praos, where this is determined by a single random seed, this gives us the ability to construct test cases in an inspectable and shrinkable manner. newtype LeaderSchedule = LeaderSchedule { getLeaderSchedule :: Map SlotNo [CoreNodeId] } deriving stock (Show, Eq, Ord, Generic) deriving anyclass (NoThunks) leaderScheduleFor :: CoreNodeId -> LeaderSchedule -> Set SlotNo leaderScheduleFor nid = Map.keysSet . Map.filter (elem nid) . getLeaderSchedule instance Semigroup LeaderSchedule where LeaderSchedule l <> LeaderSchedule r = LeaderSchedule $ Map.unionWith comb l r where comb ls rs = ls ++ filter (`notElem` ls) rs instance Condense LeaderSchedule where condense (LeaderSchedule m) = condense $ map (\(s, ls) -> (s, map fromCoreNodeId ls)) $ Map.toList m
a19455c0e7168abd05ee04c2e87436138517917648d2914edb9eb494aeb14aef
ddmcdonald/sparser
non-academic-cells.lisp
;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER COMMON-LISP) -*- Copyright ( c ) 2014 - 2021 SIFT LLC . All Rights Reserved ;;; ;;; File: "non-academic-cells" ;;; Module: "grammar/model/sl/biology/ version : October 2021 ;; broken out from cells and new-defs/new-cells (def-indiv-with-id cell-type "host cell" "GO:0043657" :name "host cell") should be category , also SC is confounding (def-indiv-with-id cell-type "embryonic stem cell" "TS-0263") ;; reproductive cells (def-indiv-with-id cell-type "gamete" "CO:0000300") (def-indiv-with-id cell-type "meiocyte" "BTO:0000845" :name "meiotic cell") (def-indiv-with-id cell-type "germ-cell" "BTO:0000535" :name "germ cell") (def-indiv-with-id cell-type "ovum" "BTO:0003801" :name "ovum" :plural ("ovums" "ova")) (def-indiv-with-id cell-type "oogonia" "BTO:0000964" :name "oocyte") (def-indiv-with-id cell-type "spermatozoa" "BTO:0001277" :name "spermatozoon") (def-indiv-with-id cell-type "sperm" "CO:0000019" :name "sperm") ;; brain cells/neurons (def-indiv-with-id cell-type "neuron" "CO:0000540" :name "neuron" :synonyms ("neurone") :adj "neoronal") ;; should probably be category (def-indiv-with-id cell-type "neuronal cell" "TS-0683") (def-indiv-with-id cell-type "motoneuron" "CO:0000100" :name "motor neuron" :synonyms ("motoneurone")) (def-indiv-with-id cell-type "primary neuron" "CO:0000530") (def-indiv-with-id cell-type "interneuron" "CO:0000099" :name "interneuron") (def-indiv-with-id cell-type "pyramidal neuron" "CO:0000598") (def-indiv-with-id cell-type "neural stem cell" "CO:0000047") (def-indiv-with-id cell-type "cortical neuron" "CO:0002609") (def-indiv-with-id cell-type "retinal cell" "CO:0009004") (def-indiv-with-id cell-type "RGC" "CO:0000740" :name "retinal ganglion cell") (def-indiv-with-id cell-type "retinal pigment epithelial cell" "CO:0002586") (def-indiv-with-id cell-type "primary sensory neuron" "CO:0000531") (def-indiv-with-id cell-type "mechanoreceptor" "CO:0000199" :name "mechanoreceptor cell") (def-indiv-with-id cell-type "nociceptor" "CO:0000198" :name "pain receptor cell") (def-indiv-with-id cell-type "dopaminergic cell" "CO:0000700" :name "dopaminergic neuron") (def-indiv-with-id cell-type "cerebellar granule cell" "CO:0001031") (def-indiv-with-id cell-type "cerebellar neuron" "CO:1001611") (def-indiv-with-id cell-type "hippocampal neuron" "CO:0002608") (def-indiv-with-id cell-type "neuroblast" "CO:0000031" :name "neuroblast") (def-indiv-with-id cell-type "neuroglia" "CO:0000125" :name "glial cell" :synonyms ("glia")) ;; should be category (def-indiv-with-id cell-type "astrocyte" "BTO:0000099" :name "astrocyte") (def-indiv-with-id cell-type "microglia" "BTO:0000078" :name "microglia") (def-indiv-with-id cell-type "microglial cell" "TS-0627") (def-indiv-with-id cell-type "oligodendroglia" "BTO:0000770" :name "oligodendroglia") (def-indiv-with-id cell-type "oligodendrocyte" "BTO:0000962" :name "oligodendrocyte") (def-indiv-with-id cell-type "Muller cell" "CO:0011107") ;; retinal glia ;; blood/immune cells (def-indiv-with-id cell-type "platelet" "CO:0000233" :name "platelet") (def-indiv-with-id cell-type "haemocyte" "BTO:0000571" :name "hemocyte") (def-indiv-with-id cell-type "erythroblast" "BTO:0001571" :name "erythroblast") (def-indiv-with-id cell-type "erythrocyte" "BTO:0000424" :name "erythrocyte" :synonyms ("red blood cell" "RBC")) (def-indiv-with-id cell-type "pBSC" "CO:0002246" :name "peripheral blood stem cell") (def-indiv-with-id cell-type "sickle-cell" "BTO:0002656" :name "sickle cell") (def-indiv-with-id cell-type "Immune Cell" "CO:0000738") " BTO:0000776 " (def-indiv-with-id cell-type "B-lymphoblast" "BTO:0001528" :name "B-lymphoblast") (def-indiv-with-id cell-type "pre-B-cell" "BTO:0001133" :name "pre-B-lymphocyte" :synonyms ("pre-B cell")) ;; "TS-0819" (def-indiv-with-id cell-type "transitional B cell" "CO:0000818") (def-indiv-with-id cell-type "mature B cell" "CO:0000785") (def-indiv-with-id cell-type "Breg" "CO:0000969" :name "regulatory B cell") (def-indiv-with-id cell-type "T-cell" "BTO:0000782" :name "T-lymphocyte" " TS-1001 " (def-indiv-with-id cell-type "leukocyte" "BTO:0000751" :name "leukocyte" :synonyms ("leucocyte" "PMNC")) (def-indiv-with-id cell-type "CD4+ T cell" "NCIT:C12537" :synonyms ("CD4 lymphocyte" "CD4-positive T lymphocyte" "CD4+")) (def-indiv-with-id cell-type "cytotoxic T cell" "CO:0000910" :synonyms ("cytotoxic T lymphocyte" "CTL" "T-killer cell" "cytolytic T cell" "CD8+ T-cell" "CD8+ T cell" "CD8+ T lymphocyte" "CD8-positive T-cell" "CD8-positive T lymphocyte" "killer T cell" "CD8+")) (def-indiv-with-id cell-type "NK-cell" "CO:0000623" :name "natural killer cell" :synonyms ("NK cell" "Natural Killer cell")) (def-indiv-with-id cell-type "helper T cell" "CO:0000912") (def-indiv-with-id cell-type "memory-Tcell" "CO:0000813" :name "memory T cell") (def-indiv-with-id cell-type "Treg" "CO:0000792" :name "CD4-positive, CD25-positive, alpha-beta regulatory T cell") (def-indiv-with-id cell-type "aTreg" "CO:0000902" :name "induced T-regulatory cell") (def-indiv-with-id cell-type "iTreg" "CO:0000902" :name "induced T-regulatory cell") (def-indiv-with-id cell-type "nTreg" "CO:0000903" :name "natural T-regulatory cell") (def-indiv-with-id cell-type "monocyte" "BTO:0000876" :name "monocyte") (def-indiv-with-id cell-type "histiocyte" "CO:0000235" :name "macrophage" ) (def-indiv-with-id cell-type "lymphocyte" "BTO:0000775" :name "lymphocyte") (def-indiv-with-id cell-type "lymphoblast" "BTO:0000772" :name "lymphoblast") (def-indiv-with-id cell-type "neutrophil" "BTO:0000130" :name "neutrophil") (def-indiv-with-id cell-type "granulocyte" "BTO:0000539" :name "granulocyte") (def-indiv-with-id cell-type "myelocyte" "CO:0002193" :name "myelocyte") ;; bone cells (def-indiv-with-id cell-type "osteocyte" "BTO:0002038" :name "osteocyte") (def-indiv-with-id cell-type "osteoclast" "BTO:0000968" :name "osteoclast") (def-indiv-with-id cell-type "osteoblast" "BTO:0001593" :name "osteoblast") ;; skin cells (def-indiv-with-id cell-type "keratinocyte" "BTO:0000667" :name "keratinocyte") (def-indiv-with-id cell-type "skin epidermal cell" "TS-0283") (def-indiv-with-id cell-type "epithelial cell" "TS-0288") (def-indiv-with-id cell-type "endothelial cell" "TS-0278") (def-indiv-with-id cell-type "squamous cell" "TS-1249") ;; muscle cells (def-indiv-with-id cell-type "myoblast" "CO:0000056" :name "myoblast") (def-indiv-with-id cell-type "myocyte" "CO:0000187" :name "muscle cell") (def-indiv-with-id cell-type "smooth muscle cell" "CO:0000192") (def-indiv-with-id cell-type "aortic smooth muscle cell" "CO:0002539") (def-indiv-with-id cell-type "vascular smooth muscle cell" "CO:0000359") (def-indiv-with-id cell-type "ventricular myocyte" "CO:0002131") ;; other cells (def-indiv-with-id cell-type "airway epithelial cell" "TS-0023") (def-indiv-with-id cell-type "alveolar epithelial cell" "CO:0000322") (def-indiv-with-id cell-type "aortic endothelial cell" "CO:0002544") (def-indiv-with-id cell-type "bronchial epithelial cell" "CO:0002328") (def-indiv-with-id cell-type "capillary endothelial cell" "CO:0002144") (def-indiv-with-id cell-type "colonic epithelial cell" "CO:0011108") (def-indiv-with-id cell-type "intestinal epithelial cell" "CO:0002563") (def-indiv-with-id cell-type "lung endothelial cell" "CO:1001567") (def-indiv-with-id cell-type "lung epithelial cell" "CO:0000082") (def-indiv-with-id cell-type "lung fibroblast" "TS-0575") (def-indiv-with-id cell-type "mammary epithelial cell" "CO:0002327" :synonyms ("mammary gland epithelial cell" "breast epithelial cell")) (def-indiv-with-id cell-type "pancreatic epithelial cell" "CO:0000083") (def-indiv-with-id cell-type "prostate epithelial cell" "CO:0002231") (def-indiv-with-id cell-type "renal epithelial cell" "TS-0505") (def-indiv-with-id cell-type "umbilical vein endothelial cell" "TS-1081") (def-indiv-with-id cell-type "type II alveolar epithelial cell" "CO:0002063") (def-indiv-with-id cell-type "vascular endothelial cell" "TS-1106") (def-indiv-with-id cell-type "venous endothelial cell" "CO:0002543") (def-indiv-with-id cell-type "acinar cell" "CO:0000622") (def-indiv-with-id cell-type "adipocyte" "CO:0000136" :name "fat cell") (def-indiv-with-id cell-type "alveolar macrophage" "CO:0000583") (def-indiv-with-id cell-type "ameloblast" "BTO:0001663" :name "ameloblast") (def-indiv-with-id cell-type "antibody secreting cell" "CO:0000946") (def-indiv-with-id cell-type "basal cell" "CO:0000646") (def-indiv-with-id cell-type "basophil" "BTO:0000129" :name "basophil") (def-indiv-with-id cell-type "beta-cell" "BTO:0000783" :name "pancreatic beta cell") (def-indiv-with-id cell-type "blastomere" "CO:0000353" :name "blastoderm cell") (def-indiv-with-id cell-type "bone marrow cell" "CO:0002092") (def-indiv-with-id cell-type "bone marrow macrophage" "CO:0002476") (def-indiv-with-id cell-type "bone marrow mononuclear cell" "CO:0010004") (def-indiv-with-id cell-type "bone marrow stromal cell" "CO:0010001") (def-indiv-with-id cell-type "cardiac cell" "TS-0115") (def-indiv-with-id cell-type "cardiac fibroblast" "CO:0002548") (def-indiv-with-id cell-type "cardiac neuron" "CO:0010022") (def-indiv-with-id cell-type "cardiomyocyte" "CO:0000746" :name "cardiac muscle cell") (def-indiv-with-id cell-type "centroblast" "CO:0000965" :name "Bm3 B cell") (def-indiv-with-id cell-type "centrocyte" "CO:0000966" :name "Bm4 B cell") (def-indiv-with-id cell-type "cholangiocyte" "CO:1000488" :name "cholangiocyte") (def-indiv-with-id cell-type "chondroblast" "CO:0000058" :name "chondroblast") (def-indiv-with-id cell-type "chondrocyte" "CO:0000138" :name "chondrocyte") (def-indiv-with-id cell-type "chromatophore" "CO:0000147" :name "pigment cell") (def-indiv-with-id cell-type "corneocyte" "CO:0002153" :name "corneocyte") (def-indiv-with-id cell-type "crypt cell" "CO:0000849") (def-indiv-with-id cell-type "cumulus cell" "CO:0000711") (def-indiv-with-id cell-type "dendritic cell" "CO:0000451") (def-indiv-with-id cell-type "dikaryon" "CO:0000603" :name "dikaryon") (def-indiv-with-id cell-type "enterocyte" "CO:0000584" :name "enterocyte") (def-indiv-with-id cell-type "eosinophil" "BTO:0000399" :name "eosinophil") (def-indiv-with-id cell-type "eukaryotic cell" "CO:0000255") (def-indiv-with-id cell-type "fibrocyte" "CO:0000135" :name "fibrocyte") (def-indiv-with-id cell-type "fibroblast" "CO:0000057" :name "fibroblast") (def-indiv-with-id cell-type "embryonic fibroblast" "CO:2000042") (def-indiv-with-id cell-type "glomerular cell" "CO:1000746") (def-indiv-with-id cell-type "goblet-cell" "BTO:0001540" :name "goblet cell") (def-indiv-with-id cell-type "gonadotrope" "CO:0000437" :name "gonadtroph" :synonyms ("gonadotroph")) (def-indiv-with-id cell-type "gonocyte" "BTO:0004982" :name "gonocyte") (def-indiv-with-id cell-type "granulosa cell" "CO:0000501") (def-indiv-with-id cell-type "hematopoietic cell" "CO:0000988") (def-indiv-with-id cell-type "hepatic stellate cell" "CO:0000632") (def-indiv-with-id cell-type "hepatocyte" "CO:0000182" :name "hepatocyte") (def-indiv-with-id cell-type "heterokaryon" "CO:0000600" :name "heterokaryon") (def-indiv-with-id cell-type "inflammatory cell" "CO:0009002") (def-indiv-with-id cell-type "keratocyte" "CO:0002363" :name "keratocyte") (def-indiv-with-id cell-type "kidney cell" "CO:1000497") (def-indiv-with-id cell-type "Kupffer cell" "CO:0000091") (def-indiv-with-id cell-type "lactotroph" "CO:0002311" :name "mammotroph" :synonyms ("lactotrope")) (def-indiv-with-id cell-type "lipocyte" "CO:0000632" :name "hepatic stellate cell") (def-indiv-with-id cell-type "mDC" "CO:0000782" :name "myeloid dendritic cell" :maintain-case t) (def-indiv-with-id cell-type "macrocyte" "CO:0002357" :name "fetal derived definitive erythrocyte") (def-indiv-with-id cell-type "mammosomatotroph" "CO:0002310" :name "mammosomatotroph") (def-indiv-with-id cell-type "mast cell" "TS-0603") (def-indiv-with-id cell-type "mature oocyte" "CO:0000025") (def-indiv-with-id cell-type "megakaryocyte" "BTO:0000843" :name "megakaryocyte") (def-indiv-with-id cell-type "melanoblast" "CO:0000541") (def-indiv-with-id cell-type "melanocyte" "BTO:0000847" :name "melanocyte") (def-indiv-with-id cell-type "melanophore" "BTO:0001711" :name "melanophore") (def-indiv-with-id cell-type "melanotroph" "CO:0000440" :name "melanocyte stimulating hormone secreting cell") (def-indiv-with-id cell-type "mesangial cell" "CO:0000650") (def-indiv-with-id cell-type "metamyelocyte" "CO:0002192" :name "metamyelocyte") (def-indiv-with-id cell-type "microvascular endothelial cell" "CO:2000008") (def-indiv-with-id cell-type "mononuclear cell" "CO:0000842") (def-indiv-with-id cell-type "myeloblast" "CO:0000835" :name "myeloblast") (def-indiv-with-id cell-type "myeloid cell" "TS-0647") (def-indiv-with-id cell-type "myotube" "CO:0002372" :name "myotube") (def-indiv-with-id cell-type "normoblast" "BTO:0003095" :name "normoblast") (def-indiv-with-id cell-type "odontoblast" "CO:0000060") (def-indiv-with-id cell-type "pericyte" "CO:0000669" :name "pericyte cell") (def-indiv-with-id cell-type "peritoneal macrophage" "CO:0000581") (def-indiv-with-id cell-type "plasmocyte" "BTO:0000392" :name "plasma cell") (def-indiv-with-id cell-type "podocyte" "CL:0000653") (def-indiv-with-id cell-type "pre-osteoblast" "BTO:0002051" :name "preosteoblast") (def-indiv-with-id cell-type "precursor cell" "CO:0011115") (def-indiv-with-id cell-type "promonocyte" "CO:0000559" :name "promonocyte") (def-indiv-with-id cell-type "promyelocyte" "BTO:0005790" :name "promyelocyte") (def-indiv-with-id cell-type "protoplast" "CO:0000371" :name "protoplast") (def-indiv-with-id cell-type "reticulocyte" "BTO:0001173" :name "reticulocyte") (def-indiv-with-id cell-type "satellite cell" "TS-1205") (def-indiv-with-id cell-type "spermatid" "CO:0000018" :name "spermatid") (def-indiv-with-id cell-type "spermatocyte" "BTO:0001275" :name "spermatocyte") (def-indiv-with-id cell-type "spermatogonium" "BTO:0000958" :name "spermatogonium" :plural ("spermatogoniums" "spermatogonia")) (def-indiv-with-id cell-type "spheroplast" "CO:0000524" :name "spheroplast") (def-indiv-with-id cell-type "splenocyte" "CO:2000074" :name "splenocyte") (def-indiv-with-id cell-type "Stromal cell" "TS-0984") (def-indiv-with-id cell-type "syncitium" "CO:0000228" :name "multinucleate cell") (def-indiv-with-id cell-type "synoviocyte" "CO:0000214" :name "synovial cell") (def-indiv-with-id cell-type "thymocyte" "BTO:0001372" :name "thymocyte") (def-indiv-with-id cell-type "thyrotrope" "CO:0000476" :name "thyrotroph") (def-indiv-with-id cell-type "yolk cell" "CO:0000428") ;; cancer cells (def-indiv-with-id cell-type "cancercell" "CO:0001064" :name "malignant cell") (def-indiv-with-id cell-type "glioma cell" "TS-0416") (def-indiv-with-id cell-type "leukemia cell" "TS-0547") (def-indiv-with-id cell-type "OSCC" "BTO:0003614" :name "oral squamous cell carcinoma cell") ;; OSCC should possibly map to the disease not the cell ;; complicated - line and type should relate somehow (def-indiv-with-id cell-line "HeLa" "EFO:0001185" :maintain-case t) (def-indiv-with-id cell-type "HeLa cell" "TS-0136")
null
https://raw.githubusercontent.com/ddmcdonald/sparser/4bb59f0989152f059f7b008ca4bfd89501bae04c/Sparser/code/s/grammar/model/sl/biology/non-academic-cells.lisp
lisp
-*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER COMMON-LISP) -*- File: "non-academic-cells" Module: "grammar/model/sl/biology/ broken out from cells and new-defs/new-cells reproductive cells brain cells/neurons should probably be category should be category retinal glia blood/immune cells "TS-0819" bone cells skin cells muscle cells other cells cancer cells OSCC should possibly map to the disease not the cell complicated - line and type should relate somehow
Copyright ( c ) 2014 - 2021 SIFT LLC . All Rights Reserved version : October 2021 (def-indiv-with-id cell-type "host cell" "GO:0043657" :name "host cell") should be category , also SC is confounding (def-indiv-with-id cell-type "embryonic stem cell" "TS-0263") (def-indiv-with-id cell-type "gamete" "CO:0000300") (def-indiv-with-id cell-type "meiocyte" "BTO:0000845" :name "meiotic cell") (def-indiv-with-id cell-type "germ-cell" "BTO:0000535" :name "germ cell") (def-indiv-with-id cell-type "ovum" "BTO:0003801" :name "ovum" :plural ("ovums" "ova")) (def-indiv-with-id cell-type "oogonia" "BTO:0000964" :name "oocyte") (def-indiv-with-id cell-type "spermatozoa" "BTO:0001277" :name "spermatozoon") (def-indiv-with-id cell-type "sperm" "CO:0000019" :name "sperm") (def-indiv-with-id cell-type "neuronal cell" "TS-0683") (def-indiv-with-id cell-type "motoneuron" "CO:0000100" :name "motor neuron" :synonyms ("motoneurone")) (def-indiv-with-id cell-type "primary neuron" "CO:0000530") (def-indiv-with-id cell-type "interneuron" "CO:0000099" :name "interneuron") (def-indiv-with-id cell-type "pyramidal neuron" "CO:0000598") (def-indiv-with-id cell-type "neural stem cell" "CO:0000047") (def-indiv-with-id cell-type "cortical neuron" "CO:0002609") (def-indiv-with-id cell-type "retinal cell" "CO:0009004") (def-indiv-with-id cell-type "RGC" "CO:0000740" :name "retinal ganglion cell") (def-indiv-with-id cell-type "retinal pigment epithelial cell" "CO:0002586") (def-indiv-with-id cell-type "primary sensory neuron" "CO:0000531") (def-indiv-with-id cell-type "mechanoreceptor" "CO:0000199" :name "mechanoreceptor cell") (def-indiv-with-id cell-type "nociceptor" "CO:0000198" :name "pain receptor cell") (def-indiv-with-id cell-type "dopaminergic cell" "CO:0000700" :name "dopaminergic neuron") (def-indiv-with-id cell-type "cerebellar granule cell" "CO:0001031") (def-indiv-with-id cell-type "cerebellar neuron" "CO:1001611") (def-indiv-with-id cell-type "hippocampal neuron" "CO:0002608") (def-indiv-with-id cell-type "neuroblast" "CO:0000031" :name "neuroblast") (def-indiv-with-id cell-type "astrocyte" "BTO:0000099" :name "astrocyte") (def-indiv-with-id cell-type "microglia" "BTO:0000078" :name "microglia") (def-indiv-with-id cell-type "microglial cell" "TS-0627") (def-indiv-with-id cell-type "oligodendroglia" "BTO:0000770" :name "oligodendroglia") (def-indiv-with-id cell-type "oligodendrocyte" "BTO:0000962" :name "oligodendrocyte") (def-indiv-with-id cell-type "platelet" "CO:0000233" :name "platelet") (def-indiv-with-id cell-type "haemocyte" "BTO:0000571" :name "hemocyte") (def-indiv-with-id cell-type "erythroblast" "BTO:0001571" :name "erythroblast") (def-indiv-with-id cell-type "erythrocyte" "BTO:0000424" :name "erythrocyte" :synonyms ("red blood cell" "RBC")) (def-indiv-with-id cell-type "pBSC" "CO:0002246" :name "peripheral blood stem cell") (def-indiv-with-id cell-type "sickle-cell" "BTO:0002656" :name "sickle cell") (def-indiv-with-id cell-type "Immune Cell" "CO:0000738") " BTO:0000776 " (def-indiv-with-id cell-type "B-lymphoblast" "BTO:0001528" :name "B-lymphoblast") (def-indiv-with-id cell-type "transitional B cell" "CO:0000818") (def-indiv-with-id cell-type "mature B cell" "CO:0000785") (def-indiv-with-id cell-type "Breg" "CO:0000969" :name "regulatory B cell") (def-indiv-with-id cell-type "T-cell" "BTO:0000782" :name "T-lymphocyte" " TS-1001 " (def-indiv-with-id cell-type "leukocyte" "BTO:0000751" :name "leukocyte" :synonyms ("leucocyte" "PMNC")) (def-indiv-with-id cell-type "CD4+ T cell" "NCIT:C12537" :synonyms ("CD4 lymphocyte" "CD4-positive T lymphocyte" "CD4+")) (def-indiv-with-id cell-type "cytotoxic T cell" "CO:0000910" :synonyms ("cytotoxic T lymphocyte" "CTL" "T-killer cell" "cytolytic T cell" "CD8+ T-cell" "CD8+ T cell" "CD8+ T lymphocyte" "CD8-positive T-cell" "CD8-positive T lymphocyte" "killer T cell" "CD8+")) (def-indiv-with-id cell-type "NK-cell" "CO:0000623" :name "natural killer cell" :synonyms ("NK cell" "Natural Killer cell")) (def-indiv-with-id cell-type "helper T cell" "CO:0000912") (def-indiv-with-id cell-type "memory-Tcell" "CO:0000813" :name "memory T cell") (def-indiv-with-id cell-type "Treg" "CO:0000792" :name "CD4-positive, CD25-positive, alpha-beta regulatory T cell") (def-indiv-with-id cell-type "aTreg" "CO:0000902" :name "induced T-regulatory cell") (def-indiv-with-id cell-type "iTreg" "CO:0000902" :name "induced T-regulatory cell") (def-indiv-with-id cell-type "nTreg" "CO:0000903" :name "natural T-regulatory cell") (def-indiv-with-id cell-type "monocyte" "BTO:0000876" :name "monocyte") (def-indiv-with-id cell-type "histiocyte" "CO:0000235" :name "macrophage" ) (def-indiv-with-id cell-type "lymphocyte" "BTO:0000775" :name "lymphocyte") (def-indiv-with-id cell-type "lymphoblast" "BTO:0000772" :name "lymphoblast") (def-indiv-with-id cell-type "neutrophil" "BTO:0000130" :name "neutrophil") (def-indiv-with-id cell-type "granulocyte" "BTO:0000539" :name "granulocyte") (def-indiv-with-id cell-type "myelocyte" "CO:0002193" :name "myelocyte") (def-indiv-with-id cell-type "osteocyte" "BTO:0002038" :name "osteocyte") (def-indiv-with-id cell-type "osteoclast" "BTO:0000968" :name "osteoclast") (def-indiv-with-id cell-type "osteoblast" "BTO:0001593" :name "osteoblast") (def-indiv-with-id cell-type "keratinocyte" "BTO:0000667" :name "keratinocyte") (def-indiv-with-id cell-type "skin epidermal cell" "TS-0283") (def-indiv-with-id cell-type "epithelial cell" "TS-0288") (def-indiv-with-id cell-type "endothelial cell" "TS-0278") (def-indiv-with-id cell-type "squamous cell" "TS-1249") (def-indiv-with-id cell-type "myoblast" "CO:0000056" :name "myoblast") (def-indiv-with-id cell-type "myocyte" "CO:0000187" :name "muscle cell") (def-indiv-with-id cell-type "smooth muscle cell" "CO:0000192") (def-indiv-with-id cell-type "aortic smooth muscle cell" "CO:0002539") (def-indiv-with-id cell-type "vascular smooth muscle cell" "CO:0000359") (def-indiv-with-id cell-type "ventricular myocyte" "CO:0002131") (def-indiv-with-id cell-type "airway epithelial cell" "TS-0023") (def-indiv-with-id cell-type "alveolar epithelial cell" "CO:0000322") (def-indiv-with-id cell-type "aortic endothelial cell" "CO:0002544") (def-indiv-with-id cell-type "bronchial epithelial cell" "CO:0002328") (def-indiv-with-id cell-type "capillary endothelial cell" "CO:0002144") (def-indiv-with-id cell-type "colonic epithelial cell" "CO:0011108") (def-indiv-with-id cell-type "intestinal epithelial cell" "CO:0002563") (def-indiv-with-id cell-type "lung endothelial cell" "CO:1001567") (def-indiv-with-id cell-type "lung epithelial cell" "CO:0000082") (def-indiv-with-id cell-type "lung fibroblast" "TS-0575") (def-indiv-with-id cell-type "mammary epithelial cell" "CO:0002327" :synonyms ("mammary gland epithelial cell" "breast epithelial cell")) (def-indiv-with-id cell-type "pancreatic epithelial cell" "CO:0000083") (def-indiv-with-id cell-type "prostate epithelial cell" "CO:0002231") (def-indiv-with-id cell-type "renal epithelial cell" "TS-0505") (def-indiv-with-id cell-type "umbilical vein endothelial cell" "TS-1081") (def-indiv-with-id cell-type "type II alveolar epithelial cell" "CO:0002063") (def-indiv-with-id cell-type "vascular endothelial cell" "TS-1106") (def-indiv-with-id cell-type "venous endothelial cell" "CO:0002543") (def-indiv-with-id cell-type "acinar cell" "CO:0000622") (def-indiv-with-id cell-type "adipocyte" "CO:0000136" :name "fat cell") (def-indiv-with-id cell-type "alveolar macrophage" "CO:0000583") (def-indiv-with-id cell-type "ameloblast" "BTO:0001663" :name "ameloblast") (def-indiv-with-id cell-type "antibody secreting cell" "CO:0000946") (def-indiv-with-id cell-type "basal cell" "CO:0000646") (def-indiv-with-id cell-type "basophil" "BTO:0000129" :name "basophil") (def-indiv-with-id cell-type "beta-cell" "BTO:0000783" :name "pancreatic beta cell") (def-indiv-with-id cell-type "blastomere" "CO:0000353" :name "blastoderm cell") (def-indiv-with-id cell-type "bone marrow cell" "CO:0002092") (def-indiv-with-id cell-type "bone marrow macrophage" "CO:0002476") (def-indiv-with-id cell-type "bone marrow mononuclear cell" "CO:0010004") (def-indiv-with-id cell-type "bone marrow stromal cell" "CO:0010001") (def-indiv-with-id cell-type "cardiac cell" "TS-0115") (def-indiv-with-id cell-type "cardiac fibroblast" "CO:0002548") (def-indiv-with-id cell-type "cardiac neuron" "CO:0010022") (def-indiv-with-id cell-type "cardiomyocyte" "CO:0000746" :name "cardiac muscle cell") (def-indiv-with-id cell-type "centroblast" "CO:0000965" :name "Bm3 B cell") (def-indiv-with-id cell-type "centrocyte" "CO:0000966" :name "Bm4 B cell") (def-indiv-with-id cell-type "cholangiocyte" "CO:1000488" :name "cholangiocyte") (def-indiv-with-id cell-type "chondroblast" "CO:0000058" :name "chondroblast") (def-indiv-with-id cell-type "chondrocyte" "CO:0000138" :name "chondrocyte") (def-indiv-with-id cell-type "chromatophore" "CO:0000147" :name "pigment cell") (def-indiv-with-id cell-type "corneocyte" "CO:0002153" :name "corneocyte") (def-indiv-with-id cell-type "crypt cell" "CO:0000849") (def-indiv-with-id cell-type "cumulus cell" "CO:0000711") (def-indiv-with-id cell-type "dendritic cell" "CO:0000451") (def-indiv-with-id cell-type "dikaryon" "CO:0000603" :name "dikaryon") (def-indiv-with-id cell-type "enterocyte" "CO:0000584" :name "enterocyte") (def-indiv-with-id cell-type "eosinophil" "BTO:0000399" :name "eosinophil") (def-indiv-with-id cell-type "eukaryotic cell" "CO:0000255") (def-indiv-with-id cell-type "fibrocyte" "CO:0000135" :name "fibrocyte") (def-indiv-with-id cell-type "fibroblast" "CO:0000057" :name "fibroblast") (def-indiv-with-id cell-type "embryonic fibroblast" "CO:2000042") (def-indiv-with-id cell-type "glomerular cell" "CO:1000746") (def-indiv-with-id cell-type "goblet-cell" "BTO:0001540" :name "goblet cell") (def-indiv-with-id cell-type "gonadotrope" "CO:0000437" :name "gonadtroph" :synonyms ("gonadotroph")) (def-indiv-with-id cell-type "gonocyte" "BTO:0004982" :name "gonocyte") (def-indiv-with-id cell-type "granulosa cell" "CO:0000501") (def-indiv-with-id cell-type "hematopoietic cell" "CO:0000988") (def-indiv-with-id cell-type "hepatic stellate cell" "CO:0000632") (def-indiv-with-id cell-type "hepatocyte" "CO:0000182" :name "hepatocyte") (def-indiv-with-id cell-type "heterokaryon" "CO:0000600" :name "heterokaryon") (def-indiv-with-id cell-type "inflammatory cell" "CO:0009002") (def-indiv-with-id cell-type "keratocyte" "CO:0002363" :name "keratocyte") (def-indiv-with-id cell-type "kidney cell" "CO:1000497") (def-indiv-with-id cell-type "Kupffer cell" "CO:0000091") (def-indiv-with-id cell-type "lactotroph" "CO:0002311" :name "mammotroph" :synonyms ("lactotrope")) (def-indiv-with-id cell-type "lipocyte" "CO:0000632" :name "hepatic stellate cell") (def-indiv-with-id cell-type "mDC" "CO:0000782" :name "myeloid dendritic cell" :maintain-case t) (def-indiv-with-id cell-type "macrocyte" "CO:0002357" :name "fetal derived definitive erythrocyte") (def-indiv-with-id cell-type "mammosomatotroph" "CO:0002310" :name "mammosomatotroph") (def-indiv-with-id cell-type "mast cell" "TS-0603") (def-indiv-with-id cell-type "mature oocyte" "CO:0000025") (def-indiv-with-id cell-type "megakaryocyte" "BTO:0000843" :name "megakaryocyte") (def-indiv-with-id cell-type "melanoblast" "CO:0000541") (def-indiv-with-id cell-type "melanocyte" "BTO:0000847" :name "melanocyte") (def-indiv-with-id cell-type "melanophore" "BTO:0001711" :name "melanophore") (def-indiv-with-id cell-type "melanotroph" "CO:0000440" :name "melanocyte stimulating hormone secreting cell") (def-indiv-with-id cell-type "mesangial cell" "CO:0000650") (def-indiv-with-id cell-type "metamyelocyte" "CO:0002192" :name "metamyelocyte") (def-indiv-with-id cell-type "microvascular endothelial cell" "CO:2000008") (def-indiv-with-id cell-type "mononuclear cell" "CO:0000842") (def-indiv-with-id cell-type "myeloblast" "CO:0000835" :name "myeloblast") (def-indiv-with-id cell-type "myeloid cell" "TS-0647") (def-indiv-with-id cell-type "myotube" "CO:0002372" :name "myotube") (def-indiv-with-id cell-type "normoblast" "BTO:0003095" :name "normoblast") (def-indiv-with-id cell-type "odontoblast" "CO:0000060") (def-indiv-with-id cell-type "pericyte" "CO:0000669" :name "pericyte cell") (def-indiv-with-id cell-type "peritoneal macrophage" "CO:0000581") (def-indiv-with-id cell-type "plasmocyte" "BTO:0000392" :name "plasma cell") (def-indiv-with-id cell-type "podocyte" "CL:0000653") (def-indiv-with-id cell-type "pre-osteoblast" "BTO:0002051" :name "preosteoblast") (def-indiv-with-id cell-type "precursor cell" "CO:0011115") (def-indiv-with-id cell-type "promonocyte" "CO:0000559" :name "promonocyte") (def-indiv-with-id cell-type "promyelocyte" "BTO:0005790" :name "promyelocyte") (def-indiv-with-id cell-type "protoplast" "CO:0000371" :name "protoplast") (def-indiv-with-id cell-type "reticulocyte" "BTO:0001173" :name "reticulocyte") (def-indiv-with-id cell-type "satellite cell" "TS-1205") (def-indiv-with-id cell-type "spermatid" "CO:0000018" :name "spermatid") (def-indiv-with-id cell-type "spermatocyte" "BTO:0001275" :name "spermatocyte") (def-indiv-with-id cell-type "spermatogonium" "BTO:0000958" :name "spermatogonium" :plural ("spermatogoniums" "spermatogonia")) (def-indiv-with-id cell-type "spheroplast" "CO:0000524" :name "spheroplast") (def-indiv-with-id cell-type "splenocyte" "CO:2000074" :name "splenocyte") (def-indiv-with-id cell-type "Stromal cell" "TS-0984") (def-indiv-with-id cell-type "syncitium" "CO:0000228" :name "multinucleate cell") (def-indiv-with-id cell-type "synoviocyte" "CO:0000214" :name "synovial cell") (def-indiv-with-id cell-type "thymocyte" "BTO:0001372" :name "thymocyte") (def-indiv-with-id cell-type "thyrotrope" "CO:0000476" :name "thyrotroph") (def-indiv-with-id cell-type "yolk cell" "CO:0000428") (def-indiv-with-id cell-type "cancercell" "CO:0001064" :name "malignant cell") (def-indiv-with-id cell-type "glioma cell" "TS-0416") (def-indiv-with-id cell-type "leukemia cell" "TS-0547") (def-indiv-with-id cell-line "HeLa" "EFO:0001185" :maintain-case t) (def-indiv-with-id cell-type "HeLa cell" "TS-0136")
ec85dceeaab8d2b24c68fde44fb1529c5d5ab04e9b9abf56a4cff951545d82e0
amnh/PCG
Custom.hs
------------------------------------------------------------------------------ -- | -- Module : Control.Parallel.Custom Copyright : ( c ) 2015 - 2021 Ward Wheeler -- License : BSD-style -- -- Maintainer : -- Stability : provisional -- Portability : portable -- ----------------------------------------------------------------------------- {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # module Control.Parallel.Custom ( parmap , parZipWith , parZipWith3 ) where import Control.Parallel.Strategies import Data.Key import Prelude hiding (zipWith) -- | -- Map a function over a traversable structure in parallel. Should be preferred over ' ' which is fixed to lists . parmap :: Traversable t => Strategy b -> (a -> b) -> t a -> t b parmap strategy f = withStrategy (parTraversable strategy) . fmap f -- | Zip two traversable , zippable structures in parallel with a function . parZipWith :: (Traversable t , Zip t) => Strategy c -> (a -> b -> c) -> t a -> t b -> t c parZipWith strategy f lhs rhs = withStrategy (parTraversable strategy) $ zipWith f lhs rhs -- | Zip three traversable , zippable structures in parallel with a function . parZipWith3 :: (Traversable t, Zip t) => Strategy d -> (a -> b -> c -> d) -> t a -> t b -> t c -> t d parZipWith3 strategy f x y z = withStrategy (parTraversable strategy) $ zap (zipWith f x y) z
null
https://raw.githubusercontent.com/amnh/PCG/9341efe0ec2053302c22b4466157d0a24ed18154/lib/utility/src/Control/Parallel/Custom.hs
haskell
---------------------------------------------------------------------------- | Module : Control.Parallel.Custom License : BSD-style Maintainer : Stability : provisional Portability : portable --------------------------------------------------------------------------- # LANGUAGE FlexibleContexts # | Map a function over a traversable structure in parallel. | |
Copyright : ( c ) 2015 - 2021 Ward Wheeler # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # module Control.Parallel.Custom ( parmap , parZipWith , parZipWith3 ) where import Control.Parallel.Strategies import Data.Key import Prelude hiding (zipWith) Should be preferred over ' ' which is fixed to lists . parmap :: Traversable t => Strategy b -> (a -> b) -> t a -> t b parmap strategy f = withStrategy (parTraversable strategy) . fmap f Zip two traversable , zippable structures in parallel with a function . parZipWith :: (Traversable t , Zip t) => Strategy c -> (a -> b -> c) -> t a -> t b -> t c parZipWith strategy f lhs rhs = withStrategy (parTraversable strategy) $ zipWith f lhs rhs Zip three traversable , zippable structures in parallel with a function . parZipWith3 :: (Traversable t, Zip t) => Strategy d -> (a -> b -> c -> d) -> t a -> t b -> t c -> t d parZipWith3 strategy f x y z = withStrategy (parTraversable strategy) $ zap (zipWith f x y) z
214cca5d0f558458206b137df85d6b23aa54032ee82d9ff9ac01644d7b5059d8
linyinfeng/myml
Syntax.hs
module Myml.Lang.Syntax ( TopLevel (..), ) where import Myml.Syntax data TopLevel = TopBind VarName Term | TopTerm Term | TopImport String
null
https://raw.githubusercontent.com/linyinfeng/myml/c90446431caeebd4b67f9b6a7a172a70b92f138f/src/Myml/Lang/Syntax.hs
haskell
module Myml.Lang.Syntax ( TopLevel (..), ) where import Myml.Syntax data TopLevel = TopBind VarName Term | TopTerm Term | TopImport String
146d927f887569b93b3413243371bc7109efa1af77266c932a5ee39dc516dd0d
babashka/babashka
exec_test.clj
(ns babashka.exec-test (:require [babashka.test-utils :as u] [cheshire.core :as cheshire] [clojure.edn :as edn] [clojure.test :as t :refer [deftest is testing]])) (defn bb [& args] (apply u/bb nil args)) (deftest exec-test (is (= {:foo 1} (edn/read-string (bb "-x" "prn" "--foo" "1")))) (is (thrown? Exception (bb "-x" "json/generate-string" "--foo" "1"))) (is (= {:foo 1} (cheshire/parse-string (edn/read-string (bb "--prn" "-x" "cheshire.core/generate-string" "--foo" "1")) true)))) (deftest tasks-exec-test (u/with-config "{:deps {} :tasks {foo (exec 'clojure.core/prn)}}" (is (= {:dude 1} (edn/read-string (bb "run" "foo" "--dude" "1"))))) (u/with-config "{:deps {} :tasks {foo (exec 'clojure.core/prn)}}" (is (= {:dude 1} (edn/read-string (bb "run" "foo" "--dude" "1"))))) (u/with-config "{:deps {} :tasks {foo {:org.babashka/cli {:coerce {:dude []}} :task (exec 'clojure.core/prn)}}}" (is (= {:dude [1]} (edn/read-string (bb "run" "foo" "--dude" "1"))))) (u/with-config "{:deps {} :tasks {foo {:task (exec 'babashka.exec-test/exec-test)}}}" (is (= {:foo [1], :bar :yeah} (edn/read-string (bb "-cp" "test-resources" "run" "foo" "--foo" "1" "--bar" "yeah"))))) (testing "task exec args" (u/with-config "{:deps {} :tasks {foo {:task (exec 'babashka.exec-test/exec-test)}}}" (is (= {:foo :foo, :bar :yeah} (edn/read-string (bb "-cp" "test-resources" "run" "foo" "--bar" "yeah"))))) (u/with-config "{:deps {} :tasks {foo {:exec-args {:foo :bar} :task (exec 'babashka.exec-test/exec-test)}}}" (is (= {:foo :bar, :bar :yeah} (edn/read-string (bb "-cp" "test-resources" "run" "foo" "--bar" "yeah")))))) (testing "meta" (u/with-config "{:deps {} :tasks {foo {:task (exec 'babashka.exec-test/exec-test)}}}" (is (= #:org.babashka{:cli {:args ["dude"]}} (edn/read-string (bb "-cp" "test-resources" "run" "foo" "dude" "--bar" "yeah" "--meta")))))))
null
https://raw.githubusercontent.com/babashka/babashka/9b21986f0505e62c6e4f7214810035dbe876f2bd/test/babashka/exec_test.clj
clojure
(ns babashka.exec-test (:require [babashka.test-utils :as u] [cheshire.core :as cheshire] [clojure.edn :as edn] [clojure.test :as t :refer [deftest is testing]])) (defn bb [& args] (apply u/bb nil args)) (deftest exec-test (is (= {:foo 1} (edn/read-string (bb "-x" "prn" "--foo" "1")))) (is (thrown? Exception (bb "-x" "json/generate-string" "--foo" "1"))) (is (= {:foo 1} (cheshire/parse-string (edn/read-string (bb "--prn" "-x" "cheshire.core/generate-string" "--foo" "1")) true)))) (deftest tasks-exec-test (u/with-config "{:deps {} :tasks {foo (exec 'clojure.core/prn)}}" (is (= {:dude 1} (edn/read-string (bb "run" "foo" "--dude" "1"))))) (u/with-config "{:deps {} :tasks {foo (exec 'clojure.core/prn)}}" (is (= {:dude 1} (edn/read-string (bb "run" "foo" "--dude" "1"))))) (u/with-config "{:deps {} :tasks {foo {:org.babashka/cli {:coerce {:dude []}} :task (exec 'clojure.core/prn)}}}" (is (= {:dude [1]} (edn/read-string (bb "run" "foo" "--dude" "1"))))) (u/with-config "{:deps {} :tasks {foo {:task (exec 'babashka.exec-test/exec-test)}}}" (is (= {:foo [1], :bar :yeah} (edn/read-string (bb "-cp" "test-resources" "run" "foo" "--foo" "1" "--bar" "yeah"))))) (testing "task exec args" (u/with-config "{:deps {} :tasks {foo {:task (exec 'babashka.exec-test/exec-test)}}}" (is (= {:foo :foo, :bar :yeah} (edn/read-string (bb "-cp" "test-resources" "run" "foo" "--bar" "yeah"))))) (u/with-config "{:deps {} :tasks {foo {:exec-args {:foo :bar} :task (exec 'babashka.exec-test/exec-test)}}}" (is (= {:foo :bar, :bar :yeah} (edn/read-string (bb "-cp" "test-resources" "run" "foo" "--bar" "yeah")))))) (testing "meta" (u/with-config "{:deps {} :tasks {foo {:task (exec 'babashka.exec-test/exec-test)}}}" (is (= #:org.babashka{:cli {:args ["dude"]}} (edn/read-string (bb "-cp" "test-resources" "run" "foo" "dude" "--bar" "yeah" "--meta")))))))
1462b8186cce2f1ea4e76b387e8627783612545dfc34edd7cfa46e7c16fd8cfb
shirok/Gauche-lisp15
mexpr-env.scm
;; ;; A helper tool to convert definitions M-expr source into an assoc list. ;; (use gauche.parseopt) (add-load-path ".." :relative) (define (usage) (print "Usage: gosh tools/axiom-env [-e] MEXPR-SOURCE ...") (print " Read MEXPR-SOURCE and writes out the definitions in an assoc list") (print " that can be passed to EVAL as an environment.") (print " With -e option, generate a definition of EVAL*, which calls EVAL") (print " with the given environment.") (print " If more than one MEXPR-SOURCE is given, definitions are concatenated") (print " in reverse order, so if there're definitions of the same name, the latter") (print " one takes precedence.") (exit 1)) (define *defs* '()) (define-syntax $TOPLEVELS (syntax-rules ($=) [(_ ($= (name arg ...) expr) ...) (begin (push! *defs* '((name . (LAMBDA (arg ...) expr)) ...)) (undefined))])) (define (main args) (let-args (cdr args) ([emit-eval* "e"] [else => (^ _ (usage))] . files) (when (null? files) (usage)) (dolist [file files] (load file :paths '("."))) (when emit-eval* (display "($TOPLEVELS ($= (EVAL* X) (EVAL X (QUOTE ")) (pprint (concatenate *defs*)) (when emit-eval* (print "))))")) 0))
null
https://raw.githubusercontent.com/shirok/Gauche-lisp15/d40163e6aa473608dd38a23f9cb67f13af676722/tools/mexpr-env.scm
scheme
A helper tool to convert definitions M-expr source into an assoc list.
(use gauche.parseopt) (add-load-path ".." :relative) (define (usage) (print "Usage: gosh tools/axiom-env [-e] MEXPR-SOURCE ...") (print " Read MEXPR-SOURCE and writes out the definitions in an assoc list") (print " that can be passed to EVAL as an environment.") (print " With -e option, generate a definition of EVAL*, which calls EVAL") (print " with the given environment.") (print " If more than one MEXPR-SOURCE is given, definitions are concatenated") (print " in reverse order, so if there're definitions of the same name, the latter") (print " one takes precedence.") (exit 1)) (define *defs* '()) (define-syntax $TOPLEVELS (syntax-rules ($=) [(_ ($= (name arg ...) expr) ...) (begin (push! *defs* '((name . (LAMBDA (arg ...) expr)) ...)) (undefined))])) (define (main args) (let-args (cdr args) ([emit-eval* "e"] [else => (^ _ (usage))] . files) (when (null? files) (usage)) (dolist [file files] (load file :paths '("."))) (when emit-eval* (display "($TOPLEVELS ($= (EVAL* X) (EVAL X (QUOTE ")) (pprint (concatenate *defs*)) (when emit-eval* (print "))))")) 0))
0b0a8abffa374bbe272b78160fc92b794645e00d6f020a1ff55cd57554ce0b7b
TyOverby/mono
eval.mli
open! Core open! Import val eval : environment:Environment.t -> path:Path.t -> clock:Incr.Clock.t -> model:'model Incr.t -> inject_dynamic:('dynamic_action -> unit Effect.t) -> inject_static:('static_action -> unit Effect.t) -> ('model, 'dynamic_action, 'static_action, 'result) Computation.t -> ('model, 'dynamic_action, 'result) Snapshot.t
null
https://raw.githubusercontent.com/TyOverby/mono/7666c0328d194bf9a569fb65babc0486f2aaa40d/vendor/janestreet-bonsai/src/eval.mli
ocaml
open! Core open! Import val eval : environment:Environment.t -> path:Path.t -> clock:Incr.Clock.t -> model:'model Incr.t -> inject_dynamic:('dynamic_action -> unit Effect.t) -> inject_static:('static_action -> unit Effect.t) -> ('model, 'dynamic_action, 'static_action, 'result) Computation.t -> ('model, 'dynamic_action, 'result) Snapshot.t
472a7b1ce02b295165ff9352d392f5b64bb6b1be5f0860938b3d3d0d0bc6e341
synduce/Synduce
minmax.ml
type 'a tree = Node of 'a * 'a tree * 'a tree | Leaf of 'a let rec spec t = f t and f = function | Leaf x -> (x, x) | Node (a, l, r) -> let amin, amax = g (a, a) l in g (amin, amax) r and g s = function | Leaf x -> let amin, amax = s in (min amin x, max amax x) | Node (a, l, r) -> let amin, amax = s in g (g (min amin a, max amax a) l) r let rec target t1 = h t1 and h = function Leaf x -> [%synt f0] x | Node (a, l, r) -> [%synt join] a (h l) (h r) let repr x = x
null
https://raw.githubusercontent.com/synduce/Synduce/d453b04cfb507395908a270b1906f5ac34298d29/benchmarks/tree/minmax.ml
ocaml
type 'a tree = Node of 'a * 'a tree * 'a tree | Leaf of 'a let rec spec t = f t and f = function | Leaf x -> (x, x) | Node (a, l, r) -> let amin, amax = g (a, a) l in g (amin, amax) r and g s = function | Leaf x -> let amin, amax = s in (min amin x, max amax x) | Node (a, l, r) -> let amin, amax = s in g (g (min amin a, max amax a) l) r let rec target t1 = h t1 and h = function Leaf x -> [%synt f0] x | Node (a, l, r) -> [%synt join] a (h l) (h r) let repr x = x
f3882c04a732e1dd920908f06b6856cc1a943806284cda10d57929343019bf59
yetibot/core
karma.clj
(ns yetibot.core.models.karma (:require [yetibot.core.db.karma :as db] [clj-time.coerce :as time.coerce])) (defn add-score-delta! [{uuid :uuid room :room} user-id voter-id points note] (db/create {:chat-source-adapter (pr-str uuid) :chat-source-room room :user-id user-id :voter-id voter-id :points points :note note})) (defn get-score [{uuid :uuid room :room} user-id] (let [score (-> (db/query {:select/clause "SUM(points) as score" :where/map {:user-id user-id :chat-source-adapter (pr-str uuid) :chat-source-room room}}) first :score)] (if (nil? score) 0 score))) (defn get-notes ([chat-source user-id] (get-notes chat-source user-id 3)) ([{uuid :uuid room :room} user-id cnt] (let [cnt (if (or (<= cnt 0) (> cnt 100)) 3 cnt)] (map #(update % :created-at time.coerce/from-date) (db/query {:select/clause "note, voter_id, created_at" :where/map {:user-id user-id :chat-source-adapter (pr-str uuid) :chat-source-room room} :where/clause "note IS NOT NULL AND points > 0" :order/clause "created_at DESC" :limit/clause cnt}))))) (defn get-high-scores [& [{:keys [chat-source cnt] :or {cnt 10}}]] (let [cnt (if (or (<= cnt 0) (> cnt 100)) 10 cnt)] (db/query (merge {:select/clause "user_id, SUM(points) as score" :group/clause "user_id" :having/clause "SUM(points) > 0" :order/clause "score DESC" :limit/clause cnt} (when chat-source {:where/map {:chat-source-adapter (pr-str (:uuid chat-source)) :chat-source-room (:room chat-source)}}))))) (defn get-high-givers ([] (get-high-givers 10)) ([cnt] (let [cnt (if (or (<= cnt 0) (> cnt 100)) 10 cnt)] (db/query {:select/clause "voter_id, SUM(points) as score" :group/clause "voter_id" :having/clause "SUM(points) > 0" :order/clause "score DESC" :limit/clause cnt})))) (defn delete-user! "Delete user across all chat sources" [user-id] (doseq [id (map :id (db/query {:select/clause "id" :where/map {:user-id user-id}}))] (db/delete id)))
null
https://raw.githubusercontent.com/yetibot/core/e35cc772622e91aec3ad7f411a99fff09acbd3f9/src/yetibot/core/models/karma.clj
clojure
(ns yetibot.core.models.karma (:require [yetibot.core.db.karma :as db] [clj-time.coerce :as time.coerce])) (defn add-score-delta! [{uuid :uuid room :room} user-id voter-id points note] (db/create {:chat-source-adapter (pr-str uuid) :chat-source-room room :user-id user-id :voter-id voter-id :points points :note note})) (defn get-score [{uuid :uuid room :room} user-id] (let [score (-> (db/query {:select/clause "SUM(points) as score" :where/map {:user-id user-id :chat-source-adapter (pr-str uuid) :chat-source-room room}}) first :score)] (if (nil? score) 0 score))) (defn get-notes ([chat-source user-id] (get-notes chat-source user-id 3)) ([{uuid :uuid room :room} user-id cnt] (let [cnt (if (or (<= cnt 0) (> cnt 100)) 3 cnt)] (map #(update % :created-at time.coerce/from-date) (db/query {:select/clause "note, voter_id, created_at" :where/map {:user-id user-id :chat-source-adapter (pr-str uuid) :chat-source-room room} :where/clause "note IS NOT NULL AND points > 0" :order/clause "created_at DESC" :limit/clause cnt}))))) (defn get-high-scores [& [{:keys [chat-source cnt] :or {cnt 10}}]] (let [cnt (if (or (<= cnt 0) (> cnt 100)) 10 cnt)] (db/query (merge {:select/clause "user_id, SUM(points) as score" :group/clause "user_id" :having/clause "SUM(points) > 0" :order/clause "score DESC" :limit/clause cnt} (when chat-source {:where/map {:chat-source-adapter (pr-str (:uuid chat-source)) :chat-source-room (:room chat-source)}}))))) (defn get-high-givers ([] (get-high-givers 10)) ([cnt] (let [cnt (if (or (<= cnt 0) (> cnt 100)) 10 cnt)] (db/query {:select/clause "voter_id, SUM(points) as score" :group/clause "voter_id" :having/clause "SUM(points) > 0" :order/clause "score DESC" :limit/clause cnt})))) (defn delete-user! "Delete user across all chat sources" [user-id] (doseq [id (map :id (db/query {:select/clause "id" :where/map {:user-id user-id}}))] (db/delete id)))
016f5f9b7444cce0e133c6d2dbdd9acad51da1cc884c5cbe439e8d4184a0d731
mejgun/haskell-tdlib
GetForumTopicDefaultIcons.hs
{-# LANGUAGE OverloadedStrings #-} -- | module TD.Query.GetForumTopicDefaultIcons where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified Utils as U -- | -- Returns list of custom emojis, which can be used as forum topic icon by all users data GetForumTopicDefaultIcons = GetForumTopicDefaultIcons { } deriving (Eq) instance Show GetForumTopicDefaultIcons where show GetForumTopicDefaultIcons = "GetForumTopicDefaultIcons" ++ U.cc [] instance T.ToJSON GetForumTopicDefaultIcons where toJSON GetForumTopicDefaultIcons = A.object [ "@type" A..= T.String "getForumTopicDefaultIcons" ]
null
https://raw.githubusercontent.com/mejgun/haskell-tdlib/d9868e9231a4ec23e4bcbf7f6627ff9f43acea21/src/TD/Query/GetForumTopicDefaultIcons.hs
haskell
# LANGUAGE OverloadedStrings # | | Returns list of custom emojis, which can be used as forum topic icon by all users
module TD.Query.GetForumTopicDefaultIcons where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified Utils as U data GetForumTopicDefaultIcons = GetForumTopicDefaultIcons { } deriving (Eq) instance Show GetForumTopicDefaultIcons where show GetForumTopicDefaultIcons = "GetForumTopicDefaultIcons" ++ U.cc [] instance T.ToJSON GetForumTopicDefaultIcons where toJSON GetForumTopicDefaultIcons = A.object [ "@type" A..= T.String "getForumTopicDefaultIcons" ]
9cd23edd6eabc4da785c9c3561360334b1c4df845b42b90fbe77a13c9660cc20
oakes/edna
project.clj
(defproject enda "1.6.1-SNAPSHOT" :description "A Clojure data -> music library" :url "" :license {:name "Public Domain" :url ""} :repositories [["clojars" {:url "" :sign-releases false}]])
null
https://raw.githubusercontent.com/oakes/edna/ca1928cd4190047aec486d2bcdc54d8d5a8bbf06/project.clj
clojure
(defproject enda "1.6.1-SNAPSHOT" :description "A Clojure data -> music library" :url "" :license {:name "Public Domain" :url ""} :repositories [["clojars" {:url "" :sign-releases false}]])
07f71f8e2d00769eb63f26beafa5d2f19bd637ee4c3ae36d1f7b0ff522232fdb
rainyt/ocaml-haxe
set.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* Sets over ordered types *) module type OrderedType = sig type t val compare: t -> t -> int end module type S = sig type elt type t val empty: t val is_empty: t -> bool val mem: elt -> t -> bool val add: elt -> t -> t val singleton: elt -> t val remove: elt -> t -> t val union: t -> t -> t val inter: t -> t -> t val disjoint: t -> t -> bool val diff: t -> t -> t val compare: t -> t -> int val equal: t -> t -> bool val subset: t -> t -> bool val iter: (elt -> unit) -> t -> unit val map: (elt -> elt) -> t -> t val fold: (elt -> 'a -> 'a) -> t -> 'a -> 'a val for_all: (elt -> bool) -> t -> bool val exists: (elt -> bool) -> t -> bool val filter: (elt -> bool) -> t -> t val filter_map: (elt -> elt option) -> t -> t val partition: (elt -> bool) -> t -> t * t val cardinal: t -> int val elements: t -> elt list val min_elt: t -> elt val min_elt_opt: t -> elt option val max_elt: t -> elt val max_elt_opt: t -> elt option val choose: t -> elt val choose_opt: t -> elt option val split: elt -> t -> t * bool * t val find: elt -> t -> elt val find_opt: elt -> t -> elt option val find_first: (elt -> bool) -> t -> elt val find_first_opt: (elt -> bool) -> t -> elt option val find_last: (elt -> bool) -> t -> elt val find_last_opt: (elt -> bool) -> t -> elt option val of_list: elt list -> t val to_seq_from : elt -> t -> elt Seq.t val to_seq : t -> elt Seq.t val to_rev_seq : t -> elt Seq.t val add_seq : elt Seq.t -> t -> t val of_seq : elt Seq.t -> t end module Make(Ord: OrderedType) = struct type elt = Ord.t type t = Empty | Node of {l:t; v:elt; r:t; h:int} Sets are represented by balanced binary trees ( the heights of the children differ by at most 2 children differ by at most 2 *) let height = function Empty -> 0 | Node {h} -> h Creates a new node with left son l , value v and right son must have all elements of l < v < all elements of r. l and r must be balanced and | height l - height r | < = 2 . Inline expansion of height for better speed . We must have all elements of l < v < all elements of r. l and r must be balanced and | height l - height r | <= 2. Inline expansion of height for better speed. *) let create l v r = let hl = match l with Empty -> 0 | Node {h} -> h in let hr = match r with Empty -> 0 | Node {h} -> h in Node{l; v; r; h=(if hl >= hr then hl + 1 else hr + 1)} Same as create , but performs one step of rebalancing if necessary . Assumes l and r balanced and | height l - height r | < = 3 . Inline expansion of create for better speed in the most frequent case where no rebalancing is required . Assumes l and r balanced and | height l - height r | <= 3. Inline expansion of create for better speed in the most frequent case where no rebalancing is required. *) let bal l v r = let hl = match l with Empty -> 0 | Node {h} -> h in let hr = match r with Empty -> 0 | Node {h} -> h in if hl > hr + 2 then begin match l with Empty -> invalid_arg "Set.bal" | Node{l=ll; v=lv; r=lr} -> if height ll >= height lr then create ll lv (create lr v r) else begin match lr with Empty -> invalid_arg "Set.bal" | Node{l=lrl; v=lrv; r=lrr}-> create (create ll lv lrl) lrv (create lrr v r) end end else if hr > hl + 2 then begin match r with Empty -> invalid_arg "Set.bal" | Node{l=rl; v=rv; r=rr} -> if height rr >= height rl then create (create l v rl) rv rr else begin match rl with Empty -> invalid_arg "Set.bal" | Node{l=rll; v=rlv; r=rlr} -> create (create l v rll) rlv (create rlr rv rr) end end else Node{l; v; r; h=(if hl >= hr then hl + 1 else hr + 1)} Insertion of one element let rec add x = function Empty -> Node{l=Empty; v=x; r=Empty; h=1} | Node{l; v; r} as t -> let c = Ord.compare x v in if c = 0 then t else if c < 0 then let ll = add x l in if l == ll then t else bal ll v r else let rr = add x r in if r == rr then t else bal l v rr let singleton x = Node{l=Empty; v=x; r=Empty; h=1} Beware : those two functions assume that the added v is * strictly * smaller ( or bigger ) than all the present elements in the tree ; it does not test for equality with the current min ( or max ) element . Indeed , they are only used during the " join " operation which respects this precondition . smaller (or bigger) than all the present elements in the tree; it does not test for equality with the current min (or max) element. Indeed, they are only used during the "join" operation which respects this precondition. *) let rec add_min_element x = function | Empty -> singleton x | Node {l; v; r} -> bal (add_min_element x l) v r let rec add_max_element x = function | Empty -> singleton x | Node {l; v; r} -> bal l v (add_max_element x r) Same as create and bal , but no assumptions are made on the relative heights of l and r. relative heights of l and r. *) let rec join l v r = match (l, r) with (Empty, _) -> add_min_element v r | (_, Empty) -> add_max_element v l | (Node{l=ll; v=lv; r=lr; h=lh}, Node{l=rl; v=rv; r=rr; h=rh}) -> if lh > rh + 2 then bal ll lv (join lr v r) else if rh > lh + 2 then bal (join l v rl) rv rr else create l v r (* Smallest and greatest element of a set *) let rec min_elt = function Empty -> raise Not_found | Node{l=Empty; v} -> v | Node{l} -> min_elt l let rec min_elt_opt = function Empty -> None | Node{l=Empty; v} -> Some v | Node{l} -> min_elt_opt l let rec max_elt = function Empty -> raise Not_found | Node{v; r=Empty} -> v | Node{r} -> max_elt r let rec max_elt_opt = function Empty -> None | Node{v; r=Empty} -> Some v | Node{r} -> max_elt_opt r (* Remove the smallest element of the given set *) let rec remove_min_elt = function Empty -> invalid_arg "Set.remove_min_elt" | Node{l=Empty; r} -> r | Node{l; v; r} -> bal (remove_min_elt l) v r Merge two trees l and r into one . All elements of l must precede the elements of r. Assume | height l - height r | < = 2 . All elements of l must precede the elements of r. Assume | height l - height r | <= 2. *) let merge t1 t2 = match (t1, t2) with (Empty, t) -> t | (t, Empty) -> t | (_, _) -> bal t1 (min_elt t2) (remove_min_elt t2) Merge two trees l and r into one . All elements of l must precede the elements of r. No assumption on the heights of l and r. All elements of l must precede the elements of r. No assumption on the heights of l and r. *) let concat t1 t2 = match (t1, t2) with (Empty, t) -> t | (t, Empty) -> t | (_, _) -> join t1 (min_elt t2) (remove_min_elt t2) (* Splitting. split x s returns a triple (l, present, r) where - l is the set of elements of s that are < x - r is the set of elements of s that are > x - present is false if s contains no element equal to x, or true if s contains an element equal to x. *) let rec split x = function Empty -> (Empty, false, Empty) | Node{l; v; r} -> let c = Ord.compare x v in if c = 0 then (l, true, r) else if c < 0 then let (ll, pres, rl) = split x l in (ll, pres, join rl v r) else let (lr, pres, rr) = split x r in (join l v lr, pres, rr) (* Implementation of the set operations *) let empty = Empty let is_empty = function Empty -> true | _ -> false let rec mem x = function Empty -> false | Node{l; v; r} -> let c = Ord.compare x v in c = 0 || mem x (if c < 0 then l else r) let rec remove x = function Empty -> Empty | (Node{l; v; r} as t) -> let c = Ord.compare x v in if c = 0 then merge l r else if c < 0 then let ll = remove x l in if l == ll then t else bal ll v r else let rr = remove x r in if r == rr then t else bal l v rr let rec union s1 s2 = match (s1, s2) with (Empty, t2) -> t2 | (t1, Empty) -> t1 | (Node{l=l1; v=v1; r=r1; h=h1}, Node{l=l2; v=v2; r=r2; h=h2}) -> if h1 >= h2 then if h2 = 1 then add v2 s1 else begin let (l2, _, r2) = split v1 s2 in join (union l1 l2) v1 (union r1 r2) end else if h1 = 1 then add v1 s2 else begin let (l1, _, r1) = split v2 s1 in join (union l1 l2) v2 (union r1 r2) end let rec inter s1 s2 = match (s1, s2) with (Empty, _) -> Empty | (_, Empty) -> Empty | (Node{l=l1; v=v1; r=r1}, t2) -> match split v1 t2 with (l2, false, r2) -> concat (inter l1 l2) (inter r1 r2) | (l2, true, r2) -> join (inter l1 l2) v1 (inter r1 r2) (* Same as split, but compute the left and right subtrees only if the pivot element is not in the set. The right subtree is computed on demand. *) type split_bis = | Found | NotFound of t * (unit -> t) let rec split_bis x = function Empty -> NotFound (Empty, (fun () -> Empty)) | Node{l; v; r; _} -> let c = Ord.compare x v in if c = 0 then Found else if c < 0 then match split_bis x l with | Found -> Found | NotFound (ll, rl) -> NotFound (ll, (fun () -> join (rl ()) v r)) else match split_bis x r with | Found -> Found | NotFound (lr, rr) -> NotFound (join l v lr, rr) let rec disjoint s1 s2 = match (s1, s2) with (Empty, _) | (_, Empty) -> true | (Node{l=l1; v=v1; r=r1}, t2) -> if s1 == s2 then false else match split_bis v1 t2 with NotFound(l2, r2) -> disjoint l1 l2 && disjoint r1 (r2 ()) | Found -> false let rec diff s1 s2 = match (s1, s2) with (Empty, _) -> Empty | (t1, Empty) -> t1 | (Node{l=l1; v=v1; r=r1}, t2) -> match split v1 t2 with (l2, false, r2) -> join (diff l1 l2) v1 (diff r1 r2) | (l2, true, r2) -> concat (diff l1 l2) (diff r1 r2) type enumeration = End | More of elt * t * enumeration let rec cons_enum s e = match s with Empty -> e | Node{l; v; r} -> cons_enum l (More(v, r, e)) let rec compare_aux e1 e2 = match (e1, e2) with (End, End) -> 0 | (End, _) -> -1 | (_, End) -> 1 | (More(v1, r1, e1), More(v2, r2, e2)) -> let c = Ord.compare v1 v2 in if c <> 0 then c else compare_aux (cons_enum r1 e1) (cons_enum r2 e2) let compare s1 s2 = compare_aux (cons_enum s1 End) (cons_enum s2 End) let equal s1 s2 = compare s1 s2 = 0 let rec subset s1 s2 = match (s1, s2) with Empty, _ -> true | _, Empty -> false | Node {l=l1; v=v1; r=r1}, (Node {l=l2; v=v2; r=r2} as t2) -> let c = Ord.compare v1 v2 in if c = 0 then subset l1 l2 && subset r1 r2 else if c < 0 then subset (Node {l=l1; v=v1; r=Empty; h=0}) l2 && subset r1 t2 else subset (Node {l=Empty; v=v1; r=r1; h=0}) r2 && subset l1 t2 let rec iter f = function Empty -> () | Node{l; v; r} -> iter f l; f v; iter f r let rec fold f s accu = match s with Empty -> accu | Node{l; v; r} -> fold f r (f v (fold f l accu)) let rec for_all p = function Empty -> true | Node{l; v; r} -> p v && for_all p l && for_all p r let rec exists p = function Empty -> false | Node{l; v; r} -> p v || exists p l || exists p r let rec filter p = function Empty -> Empty | (Node{l; v; r}) as t -> (* call [p] in the expected left-to-right order *) let l' = filter p l in let pv = p v in let r' = filter p r in if pv then if l==l' && r==r' then t else join l' v r' else concat l' r' let rec partition p = function Empty -> (Empty, Empty) | Node{l; v; r} -> (* call [p] in the expected left-to-right order *) let (lt, lf) = partition p l in let pv = p v in let (rt, rf) = partition p r in if pv then (join lt v rt, concat lf rf) else (concat lt rt, join lf v rf) let rec cardinal = function Empty -> 0 | Node{l; r} -> cardinal l + 1 + cardinal r let rec elements_aux accu = function Empty -> accu | Node{l; v; r} -> elements_aux (v :: elements_aux accu r) l let elements s = elements_aux [] s let choose = min_elt let choose_opt = min_elt_opt let rec find x = function Empty -> raise Not_found | Node{l; v; r} -> let c = Ord.compare x v in if c = 0 then v else find x (if c < 0 then l else r) let rec find_first_aux v0 f = function Empty -> v0 | Node{l; v; r} -> if f v then find_first_aux v f l else find_first_aux v0 f r let rec find_first f = function Empty -> raise Not_found | Node{l; v; r} -> if f v then find_first_aux v f l else find_first f r let rec find_first_opt_aux v0 f = function Empty -> Some v0 | Node{l; v; r} -> if f v then find_first_opt_aux v f l else find_first_opt_aux v0 f r let rec find_first_opt f = function Empty -> None | Node{l; v; r} -> if f v then find_first_opt_aux v f l else find_first_opt f r let rec find_last_aux v0 f = function Empty -> v0 | Node{l; v; r} -> if f v then find_last_aux v f r else find_last_aux v0 f l let rec find_last f = function Empty -> raise Not_found | Node{l; v; r} -> if f v then find_last_aux v f r else find_last f l let rec find_last_opt_aux v0 f = function Empty -> Some v0 | Node{l; v; r} -> if f v then find_last_opt_aux v f r else find_last_opt_aux v0 f l let rec find_last_opt f = function Empty -> None | Node{l; v; r} -> if f v then find_last_opt_aux v f r else find_last_opt f l let rec find_opt x = function Empty -> None | Node{l; v; r} -> let c = Ord.compare x v in if c = 0 then Some v else find_opt x (if c < 0 then l else r) let try_join l v r = (* [join l v r] can only be called when (elements of l < v < elements of r); use [try_join l v r] when this property may not hold, but you hope it does hold in the common case *) if (l = Empty || Ord.compare (max_elt l) v < 0) && (r = Empty || Ord.compare v (min_elt r) < 0) then join l v r else union l (add v r) let rec map f = function | Empty -> Empty | Node{l; v; r} as t -> (* enforce left-to-right evaluation order *) let l' = map f l in let v' = f v in let r' = map f r in if l == l' && v == v' && r == r' then t else try_join l' v' r' let try_concat t1 t2 = match (t1, t2) with (Empty, t) -> t | (t, Empty) -> t | (_, _) -> try_join t1 (min_elt t2) (remove_min_elt t2) let rec filter_map f = function | Empty -> Empty | Node{l; v; r} as t -> (* enforce left-to-right evaluation order *) let l' = filter_map f l in let v' = f v in let r' = filter_map f r in begin match v' with | Some v' -> if l == l' && v == v' && r == r' then t else try_join l' v' r' | None -> try_concat l' r' end let of_sorted_list l = let rec sub n l = match n, l with | 0, l -> Empty, l | 1, x0 :: l -> Node {l=Empty; v=x0; r=Empty; h=1}, l | 2, x0 :: x1 :: l -> Node{l=Node{l=Empty; v=x0; r=Empty; h=1}; v=x1; r=Empty; h=2}, l | 3, x0 :: x1 :: x2 :: l -> Node{l=Node{l=Empty; v=x0; r=Empty; h=1}; v=x1; r=Node{l=Empty; v=x2; r=Empty; h=1}; h=2}, l | n, l -> let nl = n / 2 in let left, l = sub nl l in match l with | [] -> assert false | mid :: l -> let right, l = sub (n - nl - 1) l in create left mid right, l in fst (sub (List.length l) l) let of_list l = match l with | [] -> empty | [x0] -> singleton x0 | [x0; x1] -> add x1 (singleton x0) | [x0; x1; x2] -> add x2 (add x1 (singleton x0)) | [x0; x1; x2; x3] -> add x3 (add x2 (add x1 (singleton x0))) | [x0; x1; x2; x3; x4] -> add x4 (add x3 (add x2 (add x1 (singleton x0)))) | _ -> of_sorted_list (List.sort_uniq Ord.compare l) let add_seq i m = Seq.fold_left (fun s x -> add x s) m i let of_seq i = add_seq i empty let rec seq_of_enum_ c () = match c with | End -> Seq.Nil | More (x, t, rest) -> Seq.Cons (x, seq_of_enum_ (cons_enum t rest)) let to_seq c = seq_of_enum_ (cons_enum c End) let rec snoc_enum s e = match s with Empty -> e | Node{l; v; r} -> snoc_enum r (More(v, l, e)) let rec rev_seq_of_enum_ c () = match c with | End -> Seq.Nil | More (x, t, rest) -> Seq.Cons (x, rev_seq_of_enum_ (snoc_enum t rest)) let to_rev_seq c = rev_seq_of_enum_ (snoc_enum c End) let to_seq_from low s = let rec aux low s c = match s with | Empty -> c | Node {l; r; v; _} -> begin match Ord.compare v low with | 0 -> More (v, r, c) | n when n<0 -> aux low r c | _ -> aux low l (More (v, r, c)) end in seq_of_enum_ (aux low s End) end
null
https://raw.githubusercontent.com/rainyt/ocaml-haxe/9d0ab323c6857d7fe3ce89764a00921eff1a5aaf/ocaml-extern/ocaml/set.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Sets over ordered types Smallest and greatest element of a set Remove the smallest element of the given set Splitting. split x s returns a triple (l, present, r) where - l is the set of elements of s that are < x - r is the set of elements of s that are > x - present is false if s contains no element equal to x, or true if s contains an element equal to x. Implementation of the set operations Same as split, but compute the left and right subtrees only if the pivot element is not in the set. The right subtree is computed on demand. call [p] in the expected left-to-right order call [p] in the expected left-to-right order [join l v r] can only be called when (elements of l < v < elements of r); use [try_join l v r] when this property may not hold, but you hope it does hold in the common case enforce left-to-right evaluation order enforce left-to-right evaluation order
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the module type OrderedType = sig type t val compare: t -> t -> int end module type S = sig type elt type t val empty: t val is_empty: t -> bool val mem: elt -> t -> bool val add: elt -> t -> t val singleton: elt -> t val remove: elt -> t -> t val union: t -> t -> t val inter: t -> t -> t val disjoint: t -> t -> bool val diff: t -> t -> t val compare: t -> t -> int val equal: t -> t -> bool val subset: t -> t -> bool val iter: (elt -> unit) -> t -> unit val map: (elt -> elt) -> t -> t val fold: (elt -> 'a -> 'a) -> t -> 'a -> 'a val for_all: (elt -> bool) -> t -> bool val exists: (elt -> bool) -> t -> bool val filter: (elt -> bool) -> t -> t val filter_map: (elt -> elt option) -> t -> t val partition: (elt -> bool) -> t -> t * t val cardinal: t -> int val elements: t -> elt list val min_elt: t -> elt val min_elt_opt: t -> elt option val max_elt: t -> elt val max_elt_opt: t -> elt option val choose: t -> elt val choose_opt: t -> elt option val split: elt -> t -> t * bool * t val find: elt -> t -> elt val find_opt: elt -> t -> elt option val find_first: (elt -> bool) -> t -> elt val find_first_opt: (elt -> bool) -> t -> elt option val find_last: (elt -> bool) -> t -> elt val find_last_opt: (elt -> bool) -> t -> elt option val of_list: elt list -> t val to_seq_from : elt -> t -> elt Seq.t val to_seq : t -> elt Seq.t val to_rev_seq : t -> elt Seq.t val add_seq : elt Seq.t -> t -> t val of_seq : elt Seq.t -> t end module Make(Ord: OrderedType) = struct type elt = Ord.t type t = Empty | Node of {l:t; v:elt; r:t; h:int} Sets are represented by balanced binary trees ( the heights of the children differ by at most 2 children differ by at most 2 *) let height = function Empty -> 0 | Node {h} -> h Creates a new node with left son l , value v and right son must have all elements of l < v < all elements of r. l and r must be balanced and | height l - height r | < = 2 . Inline expansion of height for better speed . We must have all elements of l < v < all elements of r. l and r must be balanced and | height l - height r | <= 2. Inline expansion of height for better speed. *) let create l v r = let hl = match l with Empty -> 0 | Node {h} -> h in let hr = match r with Empty -> 0 | Node {h} -> h in Node{l; v; r; h=(if hl >= hr then hl + 1 else hr + 1)} Same as create , but performs one step of rebalancing if necessary . Assumes l and r balanced and | height l - height r | < = 3 . Inline expansion of create for better speed in the most frequent case where no rebalancing is required . Assumes l and r balanced and | height l - height r | <= 3. Inline expansion of create for better speed in the most frequent case where no rebalancing is required. *) let bal l v r = let hl = match l with Empty -> 0 | Node {h} -> h in let hr = match r with Empty -> 0 | Node {h} -> h in if hl > hr + 2 then begin match l with Empty -> invalid_arg "Set.bal" | Node{l=ll; v=lv; r=lr} -> if height ll >= height lr then create ll lv (create lr v r) else begin match lr with Empty -> invalid_arg "Set.bal" | Node{l=lrl; v=lrv; r=lrr}-> create (create ll lv lrl) lrv (create lrr v r) end end else if hr > hl + 2 then begin match r with Empty -> invalid_arg "Set.bal" | Node{l=rl; v=rv; r=rr} -> if height rr >= height rl then create (create l v rl) rv rr else begin match rl with Empty -> invalid_arg "Set.bal" | Node{l=rll; v=rlv; r=rlr} -> create (create l v rll) rlv (create rlr rv rr) end end else Node{l; v; r; h=(if hl >= hr then hl + 1 else hr + 1)} Insertion of one element let rec add x = function Empty -> Node{l=Empty; v=x; r=Empty; h=1} | Node{l; v; r} as t -> let c = Ord.compare x v in if c = 0 then t else if c < 0 then let ll = add x l in if l == ll then t else bal ll v r else let rr = add x r in if r == rr then t else bal l v rr let singleton x = Node{l=Empty; v=x; r=Empty; h=1} Beware : those two functions assume that the added v is * strictly * smaller ( or bigger ) than all the present elements in the tree ; it does not test for equality with the current min ( or max ) element . Indeed , they are only used during the " join " operation which respects this precondition . smaller (or bigger) than all the present elements in the tree; it does not test for equality with the current min (or max) element. Indeed, they are only used during the "join" operation which respects this precondition. *) let rec add_min_element x = function | Empty -> singleton x | Node {l; v; r} -> bal (add_min_element x l) v r let rec add_max_element x = function | Empty -> singleton x | Node {l; v; r} -> bal l v (add_max_element x r) Same as create and bal , but no assumptions are made on the relative heights of l and r. relative heights of l and r. *) let rec join l v r = match (l, r) with (Empty, _) -> add_min_element v r | (_, Empty) -> add_max_element v l | (Node{l=ll; v=lv; r=lr; h=lh}, Node{l=rl; v=rv; r=rr; h=rh}) -> if lh > rh + 2 then bal ll lv (join lr v r) else if rh > lh + 2 then bal (join l v rl) rv rr else create l v r let rec min_elt = function Empty -> raise Not_found | Node{l=Empty; v} -> v | Node{l} -> min_elt l let rec min_elt_opt = function Empty -> None | Node{l=Empty; v} -> Some v | Node{l} -> min_elt_opt l let rec max_elt = function Empty -> raise Not_found | Node{v; r=Empty} -> v | Node{r} -> max_elt r let rec max_elt_opt = function Empty -> None | Node{v; r=Empty} -> Some v | Node{r} -> max_elt_opt r let rec remove_min_elt = function Empty -> invalid_arg "Set.remove_min_elt" | Node{l=Empty; r} -> r | Node{l; v; r} -> bal (remove_min_elt l) v r Merge two trees l and r into one . All elements of l must precede the elements of r. Assume | height l - height r | < = 2 . All elements of l must precede the elements of r. Assume | height l - height r | <= 2. *) let merge t1 t2 = match (t1, t2) with (Empty, t) -> t | (t, Empty) -> t | (_, _) -> bal t1 (min_elt t2) (remove_min_elt t2) Merge two trees l and r into one . All elements of l must precede the elements of r. No assumption on the heights of l and r. All elements of l must precede the elements of r. No assumption on the heights of l and r. *) let concat t1 t2 = match (t1, t2) with (Empty, t) -> t | (t, Empty) -> t | (_, _) -> join t1 (min_elt t2) (remove_min_elt t2) let rec split x = function Empty -> (Empty, false, Empty) | Node{l; v; r} -> let c = Ord.compare x v in if c = 0 then (l, true, r) else if c < 0 then let (ll, pres, rl) = split x l in (ll, pres, join rl v r) else let (lr, pres, rr) = split x r in (join l v lr, pres, rr) let empty = Empty let is_empty = function Empty -> true | _ -> false let rec mem x = function Empty -> false | Node{l; v; r} -> let c = Ord.compare x v in c = 0 || mem x (if c < 0 then l else r) let rec remove x = function Empty -> Empty | (Node{l; v; r} as t) -> let c = Ord.compare x v in if c = 0 then merge l r else if c < 0 then let ll = remove x l in if l == ll then t else bal ll v r else let rr = remove x r in if r == rr then t else bal l v rr let rec union s1 s2 = match (s1, s2) with (Empty, t2) -> t2 | (t1, Empty) -> t1 | (Node{l=l1; v=v1; r=r1; h=h1}, Node{l=l2; v=v2; r=r2; h=h2}) -> if h1 >= h2 then if h2 = 1 then add v2 s1 else begin let (l2, _, r2) = split v1 s2 in join (union l1 l2) v1 (union r1 r2) end else if h1 = 1 then add v1 s2 else begin let (l1, _, r1) = split v2 s1 in join (union l1 l2) v2 (union r1 r2) end let rec inter s1 s2 = match (s1, s2) with (Empty, _) -> Empty | (_, Empty) -> Empty | (Node{l=l1; v=v1; r=r1}, t2) -> match split v1 t2 with (l2, false, r2) -> concat (inter l1 l2) (inter r1 r2) | (l2, true, r2) -> join (inter l1 l2) v1 (inter r1 r2) type split_bis = | Found | NotFound of t * (unit -> t) let rec split_bis x = function Empty -> NotFound (Empty, (fun () -> Empty)) | Node{l; v; r; _} -> let c = Ord.compare x v in if c = 0 then Found else if c < 0 then match split_bis x l with | Found -> Found | NotFound (ll, rl) -> NotFound (ll, (fun () -> join (rl ()) v r)) else match split_bis x r with | Found -> Found | NotFound (lr, rr) -> NotFound (join l v lr, rr) let rec disjoint s1 s2 = match (s1, s2) with (Empty, _) | (_, Empty) -> true | (Node{l=l1; v=v1; r=r1}, t2) -> if s1 == s2 then false else match split_bis v1 t2 with NotFound(l2, r2) -> disjoint l1 l2 && disjoint r1 (r2 ()) | Found -> false let rec diff s1 s2 = match (s1, s2) with (Empty, _) -> Empty | (t1, Empty) -> t1 | (Node{l=l1; v=v1; r=r1}, t2) -> match split v1 t2 with (l2, false, r2) -> join (diff l1 l2) v1 (diff r1 r2) | (l2, true, r2) -> concat (diff l1 l2) (diff r1 r2) type enumeration = End | More of elt * t * enumeration let rec cons_enum s e = match s with Empty -> e | Node{l; v; r} -> cons_enum l (More(v, r, e)) let rec compare_aux e1 e2 = match (e1, e2) with (End, End) -> 0 | (End, _) -> -1 | (_, End) -> 1 | (More(v1, r1, e1), More(v2, r2, e2)) -> let c = Ord.compare v1 v2 in if c <> 0 then c else compare_aux (cons_enum r1 e1) (cons_enum r2 e2) let compare s1 s2 = compare_aux (cons_enum s1 End) (cons_enum s2 End) let equal s1 s2 = compare s1 s2 = 0 let rec subset s1 s2 = match (s1, s2) with Empty, _ -> true | _, Empty -> false | Node {l=l1; v=v1; r=r1}, (Node {l=l2; v=v2; r=r2} as t2) -> let c = Ord.compare v1 v2 in if c = 0 then subset l1 l2 && subset r1 r2 else if c < 0 then subset (Node {l=l1; v=v1; r=Empty; h=0}) l2 && subset r1 t2 else subset (Node {l=Empty; v=v1; r=r1; h=0}) r2 && subset l1 t2 let rec iter f = function Empty -> () | Node{l; v; r} -> iter f l; f v; iter f r let rec fold f s accu = match s with Empty -> accu | Node{l; v; r} -> fold f r (f v (fold f l accu)) let rec for_all p = function Empty -> true | Node{l; v; r} -> p v && for_all p l && for_all p r let rec exists p = function Empty -> false | Node{l; v; r} -> p v || exists p l || exists p r let rec filter p = function Empty -> Empty | (Node{l; v; r}) as t -> let l' = filter p l in let pv = p v in let r' = filter p r in if pv then if l==l' && r==r' then t else join l' v r' else concat l' r' let rec partition p = function Empty -> (Empty, Empty) | Node{l; v; r} -> let (lt, lf) = partition p l in let pv = p v in let (rt, rf) = partition p r in if pv then (join lt v rt, concat lf rf) else (concat lt rt, join lf v rf) let rec cardinal = function Empty -> 0 | Node{l; r} -> cardinal l + 1 + cardinal r let rec elements_aux accu = function Empty -> accu | Node{l; v; r} -> elements_aux (v :: elements_aux accu r) l let elements s = elements_aux [] s let choose = min_elt let choose_opt = min_elt_opt let rec find x = function Empty -> raise Not_found | Node{l; v; r} -> let c = Ord.compare x v in if c = 0 then v else find x (if c < 0 then l else r) let rec find_first_aux v0 f = function Empty -> v0 | Node{l; v; r} -> if f v then find_first_aux v f l else find_first_aux v0 f r let rec find_first f = function Empty -> raise Not_found | Node{l; v; r} -> if f v then find_first_aux v f l else find_first f r let rec find_first_opt_aux v0 f = function Empty -> Some v0 | Node{l; v; r} -> if f v then find_first_opt_aux v f l else find_first_opt_aux v0 f r let rec find_first_opt f = function Empty -> None | Node{l; v; r} -> if f v then find_first_opt_aux v f l else find_first_opt f r let rec find_last_aux v0 f = function Empty -> v0 | Node{l; v; r} -> if f v then find_last_aux v f r else find_last_aux v0 f l let rec find_last f = function Empty -> raise Not_found | Node{l; v; r} -> if f v then find_last_aux v f r else find_last f l let rec find_last_opt_aux v0 f = function Empty -> Some v0 | Node{l; v; r} -> if f v then find_last_opt_aux v f r else find_last_opt_aux v0 f l let rec find_last_opt f = function Empty -> None | Node{l; v; r} -> if f v then find_last_opt_aux v f r else find_last_opt f l let rec find_opt x = function Empty -> None | Node{l; v; r} -> let c = Ord.compare x v in if c = 0 then Some v else find_opt x (if c < 0 then l else r) let try_join l v r = if (l = Empty || Ord.compare (max_elt l) v < 0) && (r = Empty || Ord.compare v (min_elt r) < 0) then join l v r else union l (add v r) let rec map f = function | Empty -> Empty | Node{l; v; r} as t -> let l' = map f l in let v' = f v in let r' = map f r in if l == l' && v == v' && r == r' then t else try_join l' v' r' let try_concat t1 t2 = match (t1, t2) with (Empty, t) -> t | (t, Empty) -> t | (_, _) -> try_join t1 (min_elt t2) (remove_min_elt t2) let rec filter_map f = function | Empty -> Empty | Node{l; v; r} as t -> let l' = filter_map f l in let v' = f v in let r' = filter_map f r in begin match v' with | Some v' -> if l == l' && v == v' && r == r' then t else try_join l' v' r' | None -> try_concat l' r' end let of_sorted_list l = let rec sub n l = match n, l with | 0, l -> Empty, l | 1, x0 :: l -> Node {l=Empty; v=x0; r=Empty; h=1}, l | 2, x0 :: x1 :: l -> Node{l=Node{l=Empty; v=x0; r=Empty; h=1}; v=x1; r=Empty; h=2}, l | 3, x0 :: x1 :: x2 :: l -> Node{l=Node{l=Empty; v=x0; r=Empty; h=1}; v=x1; r=Node{l=Empty; v=x2; r=Empty; h=1}; h=2}, l | n, l -> let nl = n / 2 in let left, l = sub nl l in match l with | [] -> assert false | mid :: l -> let right, l = sub (n - nl - 1) l in create left mid right, l in fst (sub (List.length l) l) let of_list l = match l with | [] -> empty | [x0] -> singleton x0 | [x0; x1] -> add x1 (singleton x0) | [x0; x1; x2] -> add x2 (add x1 (singleton x0)) | [x0; x1; x2; x3] -> add x3 (add x2 (add x1 (singleton x0))) | [x0; x1; x2; x3; x4] -> add x4 (add x3 (add x2 (add x1 (singleton x0)))) | _ -> of_sorted_list (List.sort_uniq Ord.compare l) let add_seq i m = Seq.fold_left (fun s x -> add x s) m i let of_seq i = add_seq i empty let rec seq_of_enum_ c () = match c with | End -> Seq.Nil | More (x, t, rest) -> Seq.Cons (x, seq_of_enum_ (cons_enum t rest)) let to_seq c = seq_of_enum_ (cons_enum c End) let rec snoc_enum s e = match s with Empty -> e | Node{l; v; r} -> snoc_enum r (More(v, l, e)) let rec rev_seq_of_enum_ c () = match c with | End -> Seq.Nil | More (x, t, rest) -> Seq.Cons (x, rev_seq_of_enum_ (snoc_enum t rest)) let to_rev_seq c = rev_seq_of_enum_ (snoc_enum c End) let to_seq_from low s = let rec aux low s c = match s with | Empty -> c | Node {l; r; v; _} -> begin match Ord.compare v low with | 0 -> More (v, r, c) | n when n<0 -> aux low r c | _ -> aux low l (More (v, r, c)) end in seq_of_enum_ (aux low s End) end
704cfc9576a5411f8720924afaf7f2248fd0f349976788ef27228778841e78f1
nasa/Common-Metadata-Repository
config.clj
(ns cmr.ous.components.config (:require [cmr.authz.components.config :as authz-config] [cmr.exchange.common.components.config :as config] [cmr.http.kit.components.config :as httpd-config] [cmr.metadata.proxy.components.config :as metadata-config] [cmr.metadata.proxy.config :as metadata-config-lib] [cmr.ous.config :as config-lib] [com.stuartsierra.component :as component] [taoensso.timbre :as log]) (:import (clojure.lang Keyword))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Utility Functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def get-cfg config/get-cfg) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Config Component API ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn api-version [system] (:api-version (get-cfg system))) (defn api-version-dotted [system] (str "." (api-version system))) (defn default-content-type [system] (:default-content-type (get-cfg system))) (defn vendor [system] (:vendor (get-cfg system))) (defn get-cmr-search-endpoint [system] (metadata-config/get-search-url system)) (defn get-giovanni-endpoint [system] (metadata-config-lib/service->url (get-in (get-cfg system) [:giovanni :search]))) (defn get-edsc-endpoint [system] (metadata-config-lib/service->url (get-in (get-cfg system) [:edsc :search]))) (defn opendap-base-url "This function returns the cmr-opendap URL with a trailing slash, but without the 'opendap' appended." [system] (str (metadata-config-lib/service->base-public-url (metadata-config/get-service system :service-bridge)) "/")) (defn opendap-url "This function returns the cmr-opendap URL with a trailing slash." [system] (str (metadata-config-lib/service->public-url (metadata-config/get-service system :service-bridge)) "/")) (def authz-cache-dumpfile #'authz-config/cache-dumpfile) (def authz-cache-init #'authz-config/cache-init) (def authz-cache-lru-threshold #'authz-config/cache-lru-threshold) (def authz-cache-ttl-ms #'authz-config/cache-ttl-ms) (def authz-cache-type #'authz-config/cache-type) (def concept-cache-dumpfile #'metadata-config/concept-cache-dumpfile) (def concept-cache-init #'metadata-config/concept-cache-init) (def concept-cache-ttl-ms #'metadata-config/concept-cache-ttl-ms) (def cache-type #'metadata-config/cache-type) (def cmr-max-pagesize #'metadata-config/cmr-max-pagesize) (def concept-variable-version #'metadata-config/concept-variable-version) (def get-service #'metadata-config/get-service) (def cmr-base-url #'metadata-config/cmr-base-url) (def get-service-url #'metadata-config/get-service-url) ;; The URLs returned by these functions have no trailing slash: (def get-access-control-url #'authz-config/get-access-control-url) (def get-echo-rest-url #'authz-config/get-echo-rest-url) (def get-ingest-url #(get-service-url % :ingest)) (def get-opendap-url #(get-service-url % :service-bridge)) (def get-search-url #(get-service-url % :search)) From the HTTPD config component (def http-entry-point-fn httpd-config/http-entry-point-fn) (def http-assets httpd-config/http-assets) (def http-docs httpd-config/http-docs) (def http-index-dirs httpd-config/http-index-dirs) (def http-replace-base-url httpd-config/http-replace-base-url) (def http-rest-docs-base-url-template httpd-config/http-rest-docs-base-url-template) (def http-rest-docs-outdir httpd-config/http-rest-docs-outdir) (def http-rest-docs-source httpd-config/http-rest-docs-source) (def http-skip-static httpd-config/http-skip-static) (def streaming-heartbeat httpd-config/streaming-heartbeat) (def streaming-timeout httpd-config/streaming-timeout) (def api-routes httpd-config/api-routes) (def site-routes httpd-config/site-routes) (def default-page-title httpd-config/default-page-title) ;; From the common config component (def log-color? config/log-color?) (def log-level config/log-level) (def log-nss config/log-nss) Overrides of the HTTPD config component (defn http-port [system] (or (get-in (get-cfg system) [:cmr :service :bridge :port]) (httpd-config/http-port system))) (defn http-base-url [system] (or (get-in (get-cfg system) [:cmr :service :bridge :relative :root :url]) (httpd-config/http-base-url system))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Component Lifecycle Implementation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Implemented in cmr.exchange.common.components.config ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Component Constructor ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Implemented in cmr.exchange.common.components.config
null
https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/63001cf021d32d61030b1dcadd8b253e4a221662/other/cmr-exchange/ous-plugin/src/cmr/ous/components/config.clj
clojure
Utility Functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Config Component API ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; The URLs returned by these functions have no trailing slash: From the common config component Component Lifecycle Implementation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Implemented in cmr.exchange.common.components.config Component Constructor ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Implemented in cmr.exchange.common.components.config
(ns cmr.ous.components.config (:require [cmr.authz.components.config :as authz-config] [cmr.exchange.common.components.config :as config] [cmr.http.kit.components.config :as httpd-config] [cmr.metadata.proxy.components.config :as metadata-config] [cmr.metadata.proxy.config :as metadata-config-lib] [cmr.ous.config :as config-lib] [com.stuartsierra.component :as component] [taoensso.timbre :as log]) (:import (clojure.lang Keyword))) (def get-cfg config/get-cfg) (defn api-version [system] (:api-version (get-cfg system))) (defn api-version-dotted [system] (str "." (api-version system))) (defn default-content-type [system] (:default-content-type (get-cfg system))) (defn vendor [system] (:vendor (get-cfg system))) (defn get-cmr-search-endpoint [system] (metadata-config/get-search-url system)) (defn get-giovanni-endpoint [system] (metadata-config-lib/service->url (get-in (get-cfg system) [:giovanni :search]))) (defn get-edsc-endpoint [system] (metadata-config-lib/service->url (get-in (get-cfg system) [:edsc :search]))) (defn opendap-base-url "This function returns the cmr-opendap URL with a trailing slash, but without the 'opendap' appended." [system] (str (metadata-config-lib/service->base-public-url (metadata-config/get-service system :service-bridge)) "/")) (defn opendap-url "This function returns the cmr-opendap URL with a trailing slash." [system] (str (metadata-config-lib/service->public-url (metadata-config/get-service system :service-bridge)) "/")) (def authz-cache-dumpfile #'authz-config/cache-dumpfile) (def authz-cache-init #'authz-config/cache-init) (def authz-cache-lru-threshold #'authz-config/cache-lru-threshold) (def authz-cache-ttl-ms #'authz-config/cache-ttl-ms) (def authz-cache-type #'authz-config/cache-type) (def concept-cache-dumpfile #'metadata-config/concept-cache-dumpfile) (def concept-cache-init #'metadata-config/concept-cache-init) (def concept-cache-ttl-ms #'metadata-config/concept-cache-ttl-ms) (def cache-type #'metadata-config/cache-type) (def cmr-max-pagesize #'metadata-config/cmr-max-pagesize) (def concept-variable-version #'metadata-config/concept-variable-version) (def get-service #'metadata-config/get-service) (def cmr-base-url #'metadata-config/cmr-base-url) (def get-service-url #'metadata-config/get-service-url) (def get-access-control-url #'authz-config/get-access-control-url) (def get-echo-rest-url #'authz-config/get-echo-rest-url) (def get-ingest-url #(get-service-url % :ingest)) (def get-opendap-url #(get-service-url % :service-bridge)) (def get-search-url #(get-service-url % :search)) From the HTTPD config component (def http-entry-point-fn httpd-config/http-entry-point-fn) (def http-assets httpd-config/http-assets) (def http-docs httpd-config/http-docs) (def http-index-dirs httpd-config/http-index-dirs) (def http-replace-base-url httpd-config/http-replace-base-url) (def http-rest-docs-base-url-template httpd-config/http-rest-docs-base-url-template) (def http-rest-docs-outdir httpd-config/http-rest-docs-outdir) (def http-rest-docs-source httpd-config/http-rest-docs-source) (def http-skip-static httpd-config/http-skip-static) (def streaming-heartbeat httpd-config/streaming-heartbeat) (def streaming-timeout httpd-config/streaming-timeout) (def api-routes httpd-config/api-routes) (def site-routes httpd-config/site-routes) (def default-page-title httpd-config/default-page-title) (def log-color? config/log-color?) (def log-level config/log-level) (def log-nss config/log-nss) Overrides of the HTTPD config component (defn http-port [system] (or (get-in (get-cfg system) [:cmr :service :bridge :port]) (httpd-config/http-port system))) (defn http-base-url [system] (or (get-in (get-cfg system) [:cmr :service :bridge :relative :root :url]) (httpd-config/http-base-url system)))
bdc76823424a250de771e2cb0bb5e3727e532db66a93e735969ab4e57bca0ead
testedminds/lein-topology
project.clj
(defproject lein-topology "0.3.0-SNAPSHOT" :description "A Leiningen plugin that generates a project's function dependency structure matrix." :url "-topology" :license {:name "Apache License, Version 2.0" :url "-2.0.html"} :eval-in-leiningen true :dependencies [[org.clojure/tools.namespace "0.2.11"]] :profiles {:dev {:resource-paths ["test/resources"]}})
null
https://raw.githubusercontent.com/testedminds/lein-topology/fc85f9b7482ca9bf8e48f6c459034e5132cfe7f4/project.clj
clojure
(defproject lein-topology "0.3.0-SNAPSHOT" :description "A Leiningen plugin that generates a project's function dependency structure matrix." :url "-topology" :license {:name "Apache License, Version 2.0" :url "-2.0.html"} :eval-in-leiningen true :dependencies [[org.clojure/tools.namespace "0.2.11"]] :profiles {:dev {:resource-paths ["test/resources"]}})
7f60e49cd4eec0529ebbd4138421ddaa2a5831f5df67ae7c49c786a3527ed494
majelbstoat/Morgana
jfile.erl
-module(jfile). -export([read/1, read/2]). % Reads a file into a list of lines quickly. read(FileName) -> read(FileName, "\n"). read(FileName, Tokeniser) -> {ok, Binary} = file:read_file(FileName), string:tokens(binary_to_list(Binary), Tokeniser).
null
https://raw.githubusercontent.com/majelbstoat/Morgana/a055ab916936648198ffffe2e6c12ddddd03bdef/src/jfile.erl
erlang
Reads a file into a list of lines quickly.
-module(jfile). -export([read/1, read/2]). read(FileName) -> read(FileName, "\n"). read(FileName, Tokeniser) -> {ok, Binary} = file:read_file(FileName), string:tokens(binary_to_list(Binary), Tokeniser).
2be96f76f97297e7bc075e5d77a689ae07ec90c92e4236ab022b689ea28ae078
tweag/asterius
T8472.hs
# LANGUAGE MagicHash # module Main (f, main) where import GHC.Exts(Ptr(..)) import Foreign.Ptr -- We should be able to inline this function. f :: Ptr Int -> Int -> Int f = let x = "foo"# in \p n -> n + (Ptr x `minusPtr` p) main :: IO () main = print $ x `mod` 2 == (x + 4) `mod` 2 where x = go (10000::Int) 4 go 0 a = a go n a = go (n-1) (f nullPtr a)
null
https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/test/ghc-testsuite/perf/T8472.hs
haskell
We should be able to inline this function.
# LANGUAGE MagicHash # module Main (f, main) where import GHC.Exts(Ptr(..)) import Foreign.Ptr f :: Ptr Int -> Int -> Int f = let x = "foo"# in \p n -> n + (Ptr x `minusPtr` p) main :: IO () main = print $ x `mod` 2 == (x + 4) `mod` 2 where x = go (10000::Int) 4 go 0 a = a go n a = go (n-1) (f nullPtr a)
3682e3517beff7622b1f97f23cce7855b74533f419bf7873c58db4a26754c836
Leonidas-from-XIV/slacko
abbrtypes.ml
Slacko 's public interface does n't let us easily construct Slacko.user and Slacko.channel values from JSON , and it does n't let us extract strings from those values at all . Therefore , we copy the record type that use these and skip the problematic fields . Slacko.channel values from JSON, and it doesn't let us extract strings from those values at all. Therefore, we copy the record type that use these and skip the problematic fields. *) (* Wrap Yojson.Safe.t so we don't have to keep providing printers for it. *) type json = Yojson.Safe.t [@@deriving yojson] let pp_json fmt json = Format.pp_print_string fmt (Yojson.Safe.to_string json) type abbr_authed_obj = { url: string; team: string; user: string; team_id: string; (* user_id: user; *) } [@@deriving make, show, yojson { strict = false }] let abbr_authed_obj (authed : Slacko.authed_obj) = { url = authed.Slacko.url; team = authed.Slacko.team; user = authed.Slacko.user; team_id = authed.Slacko.team_id; } type abbr_topic_obj = { value: string; (* creator: user; *) last_set: Timestamp.t; } [@@deriving show, yojson { strict = false }] let abbr_topic_obj (topic : Slacko.topic_obj) = { value = topic.Slacko.value; last_set = topic.Slacko.last_set; } type abbr_channel_obj = { (* id: channel; *) name: string; is_channel: bool; created: Timestamp.t; (* creator: user; *) is_archived: bool; is_general: bool; is_member: bool; (* members: user list; *) topic: abbr_topic_obj; purpose: abbr_topic_obj; last_read: Timestamp.t option [@default None]; latest: json option [@default None]; unread_count: int option [@default None]; unread_count_display: int option [@default None]; num_members: int option [@default None]; } [@@deriving show, yojson { strict = false }] let abbr_channel_obj (chan : Slacko.channel_obj) = { name = chan.Slacko.name; is_channel = chan.Slacko.is_channel; created = chan.Slacko.created; is_archived = chan.Slacko.is_archived; is_general = chan.Slacko.is_general; is_member = chan.Slacko.is_member; topic = abbr_topic_obj chan.Slacko.topic; purpose = abbr_topic_obj chan.Slacko.purpose; last_read = chan.Slacko.last_read; latest = chan.Slacko.latest; unread_count = chan.Slacko.unread_count; unread_count_display = chan.Slacko.unread_count_display; num_members = chan.Slacko.num_members; } type abbr_channel_obj_list = abbr_channel_obj list [@@deriving show, yojson] type abbr_message_obj = { type': string [@key "type"]; ts: Timestamp.t; (* user: user; *) text: string option; is_starred: bool option [@default None]; } [@@deriving show, yojson { strict = false }] let abbr_message_obj (message : Slacko.message_obj) = { type' = message.Slacko.type'; ts = message.Slacko.ts; text = message.Slacko.text; is_starred = message.Slacko.is_starred; } type abbr_history_obj = { latest: Timestamp.t option [@default None]; messages: abbr_message_obj list; has_more: bool; } [@@deriving show, yojson { strict = false }] let abbr_history_obj (history : Slacko.history_obj) = { latest = history.Slacko.latest; messages = List.map abbr_message_obj history.Slacko.messages; has_more = history.Slacko.has_more; } type abbr_user_obj = { (* id: user; *) name: string; deleted: bool; color: string option [@default None]; real_name: string option [@default None]; tz: string option [@default None]; tz_label: string option [@default None]; tz_offset: int [@default 0]; profile: json; is_admin: bool [@default false]; is_owner: bool [@default false]; is_primary_owner: bool [@default false]; is_restricted: bool [@default false]; is_ultra_restricted: bool [@default false]; is_bot: bool; has_files: bool [@default false]; } [@@deriving show, yojson { strict = false } ] let abbr_user_obj (user : Slacko.user_obj) = { name = user.Slacko.name; deleted = user.Slacko.deleted; color = user.Slacko.color; real_name = user.Slacko.real_name; tz = user.Slacko.tz; tz_label = user.Slacko.tz_label; tz_offset = user.Slacko.tz_offset; profile = user.Slacko.profile; is_admin = user.Slacko.is_admin; is_owner = user.Slacko.is_owner; is_primary_owner = user.Slacko.is_primary_owner; is_restricted = user.Slacko.is_restricted; is_ultra_restricted = user.Slacko.is_ultra_restricted; is_bot = user.Slacko.is_bot; has_files = user.Slacko.has_files; } type abbr_users_list_obj = { members: abbr_user_obj list } [@@deriving of_yojson { strict = false }] type abbr_user_obj_list = abbr_user_obj list [@@deriving show] let abbr_user_obj_list_of_yojson json = match abbr_users_list_obj_of_yojson json with | Result.Ok obj -> Result.Ok obj.members | (Result.Error _) as err -> err type abbr_file_obj = { (* TODO file id type *) id: string; created: Timestamp.t; (* deprecated *) timestamp: Timestamp.t; name: string option [@default None]; title: string; mimetype: string; pretty_type: string; (* user: user; *) mode: string; editable: bool; is_external: bool; external_type: string; size: int; These two are deprecated and appear to be gone . (* url: string; *) (* url_download: string; *) url_private: string; url_private_download: string; thumb_64: string option [@default None]; thunb_80: string option [@default None]; thumb_360: string option [@default None]; thumb_360_gif: string option [@default None]; thumb_360_w: int option [@default None]; thumb_360_h: int option [@default None]; permalink: string; edit_link: string option [@default None]; preview: string option [@default None]; preview_highlight: string option [@default None]; lines: int option [@default None]; lines_more: int option [@default None]; is_public: bool; (*public_url_shared: ???;*) (* channels: channel list; *) (* groups: group list; *) (* ims: conversation list; *) initial_comment: json option [@default None]; num_stars: int option [@default None]; } [@@deriving show, yojson { strict = false }] let abbr_file_obj (file : Slacko.file_obj) = { id = file.Slacko.id; created = file.Slacko.created; timestamp = file.Slacko.timestamp; name = file.Slacko.name; title = file.Slacko.title; mimetype = file.Slacko.mimetype; pretty_type = file.Slacko.pretty_type; mode = file.Slacko.mode; editable = file.Slacko.editable; is_external = file.Slacko.is_external; external_type = file.Slacko.external_type; size = file.Slacko.size; url_private = file.Slacko.url_private; url_private_download = file.Slacko.url_private_download; thumb_64 = file.Slacko.thumb_64; thunb_80 = file.Slacko.thunb_80; thumb_360 = file.Slacko.thumb_360; thumb_360_gif = file.Slacko.thumb_360_gif; thumb_360_w = file.Slacko.thumb_360_w; thumb_360_h = file.Slacko.thumb_360_h; permalink = file.Slacko.permalink; edit_link = file.Slacko.edit_link; preview = file.Slacko.preview; preview_highlight = file.Slacko.preview_highlight; lines = file.Slacko.lines; lines_more = file.Slacko.lines_more; is_public = file.Slacko.is_public; initial_comment = file.Slacko.initial_comment; num_stars = file.Slacko.num_stars; } type abbr_paging_obj = { count: int; total: int; page: int; pages: int; } [@@deriving show, yojson { strict = false }] let abbr_paging_obj (paging : Slacko.paging_obj) = { count = paging.Slacko.count; total = paging.Slacko.total; page = paging.Slacko.page; pages = paging.Slacko.pages; } type abbr_files_list_obj = { files: abbr_file_obj list; paging: abbr_paging_obj; } [@@deriving show, yojson { strict = false }] let abbr_files_list_obj (files : Slacko.files_list_obj) = { files = List.map abbr_file_obj files.Slacko.files; paging = abbr_paging_obj files.Slacko.paging; } type abbr_group_obj = { (* id: group; *) name: string; is_group: bool; created: Timestamp.t; (* creator: user; *) is_archived: bool; (* members: user list; *) topic: abbr_topic_obj; purpose: abbr_topic_obj; is_open: bool option [@default None]; last_read: Timestamp.t option [@default None]; unread_count: int option [@default None]; unread_count_display: int option [@default None]; latest: json option [@default None]; } [@@deriving show, yojson { strict = false }] let abbr_group_obj (group : Slacko.group_obj) = { name = group.Slacko.name; is_group = group.Slacko.is_group; created = group.Slacko.created; is_archived = group.Slacko.is_archived; topic = abbr_topic_obj group.Slacko.topic; purpose = abbr_topic_obj group.Slacko.purpose; is_open = group.Slacko.is_open; last_read = group.Slacko.last_read; unread_count = group.Slacko.unread_count; unread_count_display = group.Slacko.unread_count_display; latest = group.Slacko.latest; } type abbr_group_obj_list = abbr_group_obj list [@@deriving show, yojson] type abbr_im_obj = { id: string; is_im: bool; (* user: user; *) created: Timestamp.t; is_user_deleted: bool; unread_count: int option [@default None]; unread_count_display: int option [@default None]; } [@@deriving show, yojson { strict = false }] let abbr_im_obj (im : Slacko.im_obj) = { id = im.Slacko.id; is_im = im.Slacko.is_im; created = im.Slacko.created; is_user_deleted = im.Slacko.is_user_deleted; unread_count = im.Slacko.unread_count; unread_count_display = im.Slacko.unread_count_display; } type abbr_im_obj_list = abbr_im_obj list [@@deriving show, yojson]
null
https://raw.githubusercontent.com/Leonidas-from-XIV/slacko/784c5b70f521b4bb50f757782bad681e53ec6b4a/test/abbrtypes.ml
ocaml
Wrap Yojson.Safe.t so we don't have to keep providing printers for it. user_id: user; creator: user; id: channel; creator: user; members: user list; user: user; id: user; TODO file id type deprecated user: user; url: string; url_download: string; public_url_shared: ???; channels: channel list; groups: group list; ims: conversation list; id: group; creator: user; members: user list; user: user;
Slacko 's public interface does n't let us easily construct Slacko.user and Slacko.channel values from JSON , and it does n't let us extract strings from those values at all . Therefore , we copy the record type that use these and skip the problematic fields . Slacko.channel values from JSON, and it doesn't let us extract strings from those values at all. Therefore, we copy the record type that use these and skip the problematic fields. *) type json = Yojson.Safe.t [@@deriving yojson] let pp_json fmt json = Format.pp_print_string fmt (Yojson.Safe.to_string json) type abbr_authed_obj = { url: string; team: string; user: string; team_id: string; } [@@deriving make, show, yojson { strict = false }] let abbr_authed_obj (authed : Slacko.authed_obj) = { url = authed.Slacko.url; team = authed.Slacko.team; user = authed.Slacko.user; team_id = authed.Slacko.team_id; } type abbr_topic_obj = { value: string; last_set: Timestamp.t; } [@@deriving show, yojson { strict = false }] let abbr_topic_obj (topic : Slacko.topic_obj) = { value = topic.Slacko.value; last_set = topic.Slacko.last_set; } type abbr_channel_obj = { name: string; is_channel: bool; created: Timestamp.t; is_archived: bool; is_general: bool; is_member: bool; topic: abbr_topic_obj; purpose: abbr_topic_obj; last_read: Timestamp.t option [@default None]; latest: json option [@default None]; unread_count: int option [@default None]; unread_count_display: int option [@default None]; num_members: int option [@default None]; } [@@deriving show, yojson { strict = false }] let abbr_channel_obj (chan : Slacko.channel_obj) = { name = chan.Slacko.name; is_channel = chan.Slacko.is_channel; created = chan.Slacko.created; is_archived = chan.Slacko.is_archived; is_general = chan.Slacko.is_general; is_member = chan.Slacko.is_member; topic = abbr_topic_obj chan.Slacko.topic; purpose = abbr_topic_obj chan.Slacko.purpose; last_read = chan.Slacko.last_read; latest = chan.Slacko.latest; unread_count = chan.Slacko.unread_count; unread_count_display = chan.Slacko.unread_count_display; num_members = chan.Slacko.num_members; } type abbr_channel_obj_list = abbr_channel_obj list [@@deriving show, yojson] type abbr_message_obj = { type': string [@key "type"]; ts: Timestamp.t; text: string option; is_starred: bool option [@default None]; } [@@deriving show, yojson { strict = false }] let abbr_message_obj (message : Slacko.message_obj) = { type' = message.Slacko.type'; ts = message.Slacko.ts; text = message.Slacko.text; is_starred = message.Slacko.is_starred; } type abbr_history_obj = { latest: Timestamp.t option [@default None]; messages: abbr_message_obj list; has_more: bool; } [@@deriving show, yojson { strict = false }] let abbr_history_obj (history : Slacko.history_obj) = { latest = history.Slacko.latest; messages = List.map abbr_message_obj history.Slacko.messages; has_more = history.Slacko.has_more; } type abbr_user_obj = { name: string; deleted: bool; color: string option [@default None]; real_name: string option [@default None]; tz: string option [@default None]; tz_label: string option [@default None]; tz_offset: int [@default 0]; profile: json; is_admin: bool [@default false]; is_owner: bool [@default false]; is_primary_owner: bool [@default false]; is_restricted: bool [@default false]; is_ultra_restricted: bool [@default false]; is_bot: bool; has_files: bool [@default false]; } [@@deriving show, yojson { strict = false } ] let abbr_user_obj (user : Slacko.user_obj) = { name = user.Slacko.name; deleted = user.Slacko.deleted; color = user.Slacko.color; real_name = user.Slacko.real_name; tz = user.Slacko.tz; tz_label = user.Slacko.tz_label; tz_offset = user.Slacko.tz_offset; profile = user.Slacko.profile; is_admin = user.Slacko.is_admin; is_owner = user.Slacko.is_owner; is_primary_owner = user.Slacko.is_primary_owner; is_restricted = user.Slacko.is_restricted; is_ultra_restricted = user.Slacko.is_ultra_restricted; is_bot = user.Slacko.is_bot; has_files = user.Slacko.has_files; } type abbr_users_list_obj = { members: abbr_user_obj list } [@@deriving of_yojson { strict = false }] type abbr_user_obj_list = abbr_user_obj list [@@deriving show] let abbr_user_obj_list_of_yojson json = match abbr_users_list_obj_of_yojson json with | Result.Ok obj -> Result.Ok obj.members | (Result.Error _) as err -> err type abbr_file_obj = { id: string; created: Timestamp.t; timestamp: Timestamp.t; name: string option [@default None]; title: string; mimetype: string; pretty_type: string; mode: string; editable: bool; is_external: bool; external_type: string; size: int; These two are deprecated and appear to be gone . url_private: string; url_private_download: string; thumb_64: string option [@default None]; thunb_80: string option [@default None]; thumb_360: string option [@default None]; thumb_360_gif: string option [@default None]; thumb_360_w: int option [@default None]; thumb_360_h: int option [@default None]; permalink: string; edit_link: string option [@default None]; preview: string option [@default None]; preview_highlight: string option [@default None]; lines: int option [@default None]; lines_more: int option [@default None]; is_public: bool; initial_comment: json option [@default None]; num_stars: int option [@default None]; } [@@deriving show, yojson { strict = false }] let abbr_file_obj (file : Slacko.file_obj) = { id = file.Slacko.id; created = file.Slacko.created; timestamp = file.Slacko.timestamp; name = file.Slacko.name; title = file.Slacko.title; mimetype = file.Slacko.mimetype; pretty_type = file.Slacko.pretty_type; mode = file.Slacko.mode; editable = file.Slacko.editable; is_external = file.Slacko.is_external; external_type = file.Slacko.external_type; size = file.Slacko.size; url_private = file.Slacko.url_private; url_private_download = file.Slacko.url_private_download; thumb_64 = file.Slacko.thumb_64; thunb_80 = file.Slacko.thunb_80; thumb_360 = file.Slacko.thumb_360; thumb_360_gif = file.Slacko.thumb_360_gif; thumb_360_w = file.Slacko.thumb_360_w; thumb_360_h = file.Slacko.thumb_360_h; permalink = file.Slacko.permalink; edit_link = file.Slacko.edit_link; preview = file.Slacko.preview; preview_highlight = file.Slacko.preview_highlight; lines = file.Slacko.lines; lines_more = file.Slacko.lines_more; is_public = file.Slacko.is_public; initial_comment = file.Slacko.initial_comment; num_stars = file.Slacko.num_stars; } type abbr_paging_obj = { count: int; total: int; page: int; pages: int; } [@@deriving show, yojson { strict = false }] let abbr_paging_obj (paging : Slacko.paging_obj) = { count = paging.Slacko.count; total = paging.Slacko.total; page = paging.Slacko.page; pages = paging.Slacko.pages; } type abbr_files_list_obj = { files: abbr_file_obj list; paging: abbr_paging_obj; } [@@deriving show, yojson { strict = false }] let abbr_files_list_obj (files : Slacko.files_list_obj) = { files = List.map abbr_file_obj files.Slacko.files; paging = abbr_paging_obj files.Slacko.paging; } type abbr_group_obj = { name: string; is_group: bool; created: Timestamp.t; is_archived: bool; topic: abbr_topic_obj; purpose: abbr_topic_obj; is_open: bool option [@default None]; last_read: Timestamp.t option [@default None]; unread_count: int option [@default None]; unread_count_display: int option [@default None]; latest: json option [@default None]; } [@@deriving show, yojson { strict = false }] let abbr_group_obj (group : Slacko.group_obj) = { name = group.Slacko.name; is_group = group.Slacko.is_group; created = group.Slacko.created; is_archived = group.Slacko.is_archived; topic = abbr_topic_obj group.Slacko.topic; purpose = abbr_topic_obj group.Slacko.purpose; is_open = group.Slacko.is_open; last_read = group.Slacko.last_read; unread_count = group.Slacko.unread_count; unread_count_display = group.Slacko.unread_count_display; latest = group.Slacko.latest; } type abbr_group_obj_list = abbr_group_obj list [@@deriving show, yojson] type abbr_im_obj = { id: string; is_im: bool; created: Timestamp.t; is_user_deleted: bool; unread_count: int option [@default None]; unread_count_display: int option [@default None]; } [@@deriving show, yojson { strict = false }] let abbr_im_obj (im : Slacko.im_obj) = { id = im.Slacko.id; is_im = im.Slacko.is_im; created = im.Slacko.created; is_user_deleted = im.Slacko.is_user_deleted; unread_count = im.Slacko.unread_count; unread_count_display = im.Slacko.unread_count_display; } type abbr_im_obj_list = abbr_im_obj list [@@deriving show, yojson]
7d30ba45e06774030abb779a55d30ee4c7ac9c5acddba03c12db00efe733009f
MyDataFlow/ttalk-server
rec_props_test1.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 module tests whether the parse transform can read module %%% information from source. -module(rec_props_test1). -export_type([exp1/0]). -include_lib("proper/include/proper.hrl"). -type exp1() :: integer(). prop_1() -> ?FORALL(_, rec_props_test2:exp2(), true).
null
https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/proper/test/rec_props_test1.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} @doc This module tests whether the parse transform can read module information from source.
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 -module(rec_props_test1). -export_type([exp1/0]). -include_lib("proper/include/proper.hrl"). -type exp1() :: integer(). prop_1() -> ?FORALL(_, rec_props_test2:exp2(), true).
d3fda1acccefca27695a7108d41f054ef022163b7eeea819914ce7a49e2ec463
Elastifile/git-sling
Sling.hs
{-# LANGUAGE OverloadedStrings #-} module Sling ( Job(..) , tryTakeJob , rejectProposal , updateProposal , transitionProposal , runPrepush ) where import Control.Monad (unless, when, void) import Control.Monad.Except (MonadError (..)) import Data.Monoid ((<>)) import Data.Text (Text) import qualified Data.Text as T import Text.Blaze.Html (toHtml) import Turtle ((&), ExitCode) import qualified Sling.Git as Git import Sling.Email (sendProposalEmail, formatCommitsForEmail, EmailType(..)) import Sling.Lib (EShell, Hash(..), ignoreError, assert, eprint, abort, eproc, NonEmptyText(..)) import Sling.Options (Options, isDryRun) import qualified Sling.Options as Options import Sling.Path (encodeFP) import Sling.Prepush (PrepushLogs(..)) import qualified Sling.Proposal as Proposal import Sling.Proposal (Proposal) data Job = Job { jobProposal :: Proposal , jobBase :: Git.Ref , jobHead :: Git.Ref } deriving (Show) makeUnique :: Proposal -> EShell Proposal makeUnique proposal = do remoteBranches <- map snd <$> Git.remoteBranches let proposalBranch = Proposal.toBranchName proposal if proposalBranch `elem` remoteBranches then do let oldName = Git.fromBranchName $ Proposal.proposalName proposal withSuffix sfx = proposal { Proposal.proposalName = Git.mkBranchName $ oldName <> "_" <> T.pack (show sfx) } go n = if Proposal.toBranchName newProposal `elem` remoteBranches then go (n+1) else newProposal where newProposal = withSuffix n return $ go (1 :: Int) else return proposal rejectProposalAndAbort :: Options -> Git.Remote -> Proposal -> Text -> Maybe PrepushLogs -> Maybe (Text, ExitCode) -> EShell () rejectProposalAndAbort options remote proposal reason prepushLogs err = do rejectProposal options remote proposal reason prepushLogs err abort "Rejected" rejectProposal :: Options -> Git.Remote -> Proposal -> Text -> Maybe PrepushLogs -> Maybe (Text, ExitCode) -> EShell () rejectProposal options remote proposal reason prepushLogs err = do let origBranchName = Proposal.toBranchName proposal rejectedProposal = proposal { Proposal.proposalStatus = Proposal.ProposalRejected } rejectBranchName = Proposal.toBranchName rejectedProposal suffix = case err of Just (msg, errCode) -> " because: '" <> reason <> "' (" <> msg <> "), exit code = " <> T.pack (show errCode) Nothing -> "" msgBody = "REJECT " <> Git.fromBranchName origBranchName <> suffix eprint msgBody sendProposalEmail options proposal ("Rejecting (" <> reason <> ")") (toHtml msgBody) prepushLogs ProposalFailureEmail Git.fetch & ignoreError Git.deleteBranch (Git.RemoteBranch remote rejectBranchName) & ignoreError -- in case it exists Git.deleteBranch (Git.LocalBranch rejectBranchName) & ignoreError -- in case it exists Git.reset Git.ResetHard Git.RefHead _ <- Git.createLocalBranch rejectBranchName Git.RefHead _ <- Git.pushRemoteTracking remote rejectBranchName Git.PushForceWithoutLease -- We have to be on another branch before deleting stuff, so arbitrarily picking rejected branch Git.checkout (Git.RefBranch $ Git.LocalBranch rejectBranchName) Git.deleteBranch (Git.LocalBranch origBranchName) & ignoreError Git.deleteBranch (Git.RemoteBranch remote origBranchName) -- Checks that the proposal is valid (e.g. the onto branch still actually exists on the remote) verifyProposal :: Options -> Git.Remote -> Proposal -> EShell () verifyProposal options remote proposal = do let ontoBranchName = Proposal.proposalBranchOnto proposal remoteBranches <- Git.remoteBranches unless ((remote, ontoBranchName) `elem` remoteBranches) $ rejectProposalAndAbort options remote proposal ("Remote branch doesn't exist: " <> Git.fromBranchName ontoBranchName) Nothing Nothing -- TODO: Add check that base hash (for merge proposals) is in range of commits that makes sense -- Rebases given proposal over latest known state of its target branch -- and pushes it to the remote. -- If the rebase fails, rejects the proposal. updateProposal :: Options -> Git.Remote -> (Git.Branch, Proposal) -> EShell (Maybe (Git.Branch, Proposal)) updateProposal options remote (proposalBranch, proposal) = do verifyProposal options remote proposal updateProposal' options remote (proposalBranch, proposal) updateProposal' :: Options -> Git.Remote -> (Git.Branch, Proposal) -> EShell (Maybe (Git.Branch, Proposal)) updateProposal' options remote (proposalBranch, proposal) = case Proposal.proposalType proposal of Proposal.ProposalTypeRebase{} -> return $ Just (proposalBranch, proposal) -- nothing to update Proposal.ProposalTypeMerge mergeType origBaseHash -> Git.withTempLocalBranch $ \tempBranchName -> do let proposalBranchName = Git.branchName proposalBranch ontoBranchName = Proposal.proposalBranchOnto proposal remoteOntoBranch = Git.RemoteBranch remote ontoBranchName newBaseHash <- Git.refToHash $ Git.RefBranch remoteOntoBranch oldBaseHash <- Git.unshortenHash origBaseHash newBaseShortHash <- Git.shortenHash newBaseHash eprint $ "Comparing base hashes: " <> T.intercalate " " (map (T.pack . show) [newBaseHash, oldBaseHash]) if newBaseHash == oldBaseHash then return $ Just (proposalBranch, proposal) -- nothing to do else do updatedProposal <- makeUnique proposal { Proposal.proposalType = Proposal.ProposalTypeMerge mergeType newBaseShortHash } let updatedProposalBranchName = Proposal.toBranchName updatedProposal remoteProposalBranch = Git.RefBranch $ Git.RemoteBranch remote proposalBranchName rebasePolicy = case mergeType of Proposal.MergeTypeFlat -> Git.RebaseDropMerges Proposal.MergeTypeKeepMerges -> Git.RebaseKeepMerges Git.reset Git.ResetHard remoteProposalBranch Git.rebase Git.Rebase { Git.rebaseBase = Git.RefHash origBaseHash , Git.rebaseOnto = Git.RefBranch remoteOntoBranch , Git.rebasePolicy = rebasePolicy } `catchError` (rejectProposalAndAbort options remote proposal "Rebase failed" Nothing . Just) -- create updated proposal branch Git.deleteLocalBranch updatedProposalBranchName & ignoreError _ <- Git.createLocalBranch updatedProposalBranchName Git.RefHead createdRemoteBranch <- Git.pushRemoteTracking remote updatedProposalBranchName Git.PushNonForce assert (==) createdRemoteBranch (Git.RemoteBranch remote updatedProposalBranchName) Nothing Git.checkout (Git.RefBranch $ Git.LocalBranch tempBranchName) Git.deleteLocalBranch updatedProposalBranchName -- Concurrency issues here: -- If deleting the (not-updated) proposal fails, then possibly someone else already deleted the proposal, 1 . Either because a user wanted to cancel this proposal , 2 . Or , they were also rebasing it ( like this function ) 3 . Or , they were rejecting it because it failed rebase ( which did n't fail for us because our remote is outdated ) 4 . Or , the proposal was marked as ' in progress ' -- In any case, deleting the proposal serves as a 'commit' for operations on it, so someone else beat us to -- it and we must undo our actions above which are just creating a new branch of the updated proposal. Git.deleteRemoteBranch remote proposalBranchName >> return (Just (createdRemoteBranch, updatedProposal)) `catchError` (\_ -> Git.deleteRemoteBranch remote updatedProposalBranchName >> return Nothing) ---------------------------------------------------------------------- withNewBranch :: Git.Remote -> Git.BranchName -> Git.PushType -> EShell a -> EShell a withNewBranch remote b pushType act = do currentRef <- Git.currentRef Git.deleteLocalBranch b & ignoreError _ <- Git.createLocalBranch b Git.RefHead _ <- Git.pushRemoteTracking remote b pushType let cleanup = do Git.checkout currentRef Git.deleteBranch (Git.LocalBranch b) Git.deleteBranch (Git.RemoteBranch remote b) act `catchError` (\e -> cleanup >> throwError e) withLocalBranch :: Git.BranchName -> EShell a -> EShell a withLocalBranch name act = do let branch = Git.LocalBranch name currentRef <- Git.currentRef Git.deleteBranch branch & ignoreError shouldCreate <- notElem name <$> Git.localBranches when shouldCreate $ void $ Git.createLocalBranch name Git.RefHead Git.checkout (Git.RefBranch branch) let cleanup = do Git.checkout currentRef when shouldCreate $ Git.deleteBranch branch act `catchError` (\e -> cleanup >> throwError e) tryTakeJob :: Proposal.ServerId -> Options -> Git.Remote -> (Git.Branch, Proposal) -> EShell (Maybe Job) tryTakeJob serverId options remote (proposalBranch, proposal) = do mUpdatedProposal <- Sling.updateProposal options remote (proposalBranch, proposal) case mUpdatedProposal of Nothing -> do -- The proposal was deleted while we were working on it. Forget about it. eprint "Other slave took the job or proposal deleted? Dropping" return Nothing Just (updatedProposalBranch, updatedProposal) -> tryTakeJob' serverId options remote updatedProposalBranch updatedProposal prepareMergeProposal :: Git.Remote -> Git.Branch -> Proposal -> Hash -> Git.Branch -> EShell () prepareMergeProposal remote proposalBranch proposal baseHash niceBranch = do let ontoBranchName = Proposal.proposalBranchOnto proposal -- note: 'nice' branch and 'onto' branch may be the same -- branch. (e.g. proposal called 'master' with onto=master) remoteOntoBranchHash <- Git.refToHash (Git.RefBranch $ Git.RemoteBranch remote ontoBranchName) -- check that the proposal's base commit is exactly onto (should have been rebased by now): fullBaseHash <- Git.unshortenHash baseHash assert (==) fullBaseHash remoteOntoBranchHash . Just $ "Expected branch to be rebased already, but it isn't: " <> T.intercalate " " (map (T.pack . show) [ remoteOntoBranchHash, fullBaseHash ]) -- point the working ('nice') branch to the proposal's head Git.reset Git.ResetHard (Git.RefBranch proposalBranch) isMerge <- Git.isMergeCommit Git.RefHead commits <- Git.log (Git.RefHash fullBaseHash) Git.RefHead if length commits == 0 then eprint "Empty proposal, nothing to do here" else do let mergeFF = if isMerge || (length commits == 1) then Git.MergeFFOnly else Git.MergeNoFF -- go back to 'onto', decide whether to create a merge commit on -- top (if we should merge ff only) Git.checkout (Git.RefBranch $ Git.LocalBranch ontoBranchName) Git.reset Git.ResetHard (Git.RefBranch $ Git.RemoteBranch remote ontoBranchName) Git.merge mergeFF niceBranch when (mergeFF == Git.MergeNoFF) $ Git.commitAmend (Proposal.proposalEmail proposal) Git.RefHead newHead <- Git.currentRef -- Fast-forward the work branch to match the merged 'onto' we do -- this so that the prepush script will see itself running on a -- branch with the name the user gave to this proposal, and not -- the onto branch's name. Git.checkout (Git.RefBranch niceBranch) Git.merge Git.MergeFFOnly (Git.LocalBranch ontoBranchName) headAfterFF <- Git.currentRef assert (==) newHead headAfterFF $ Just "Expected to arrive at same commit" tryTakeJob' :: Proposal.ServerId -> Options -> Git.Remote -> Git.Branch -> Proposal -> EShell (Maybe Job) tryTakeJob' serverId options remote proposalBranch proposal = do let ontoBranchName = Proposal.proposalBranchOnto proposal remoteOnto = Git.RefBranch $ Git.RemoteBranch remote ontoBranchName (baseRef, headRef) = case Proposal.proposalType proposal of Proposal.ProposalTypeMerge _mergeType base -> (Git.RefHash base, Git.RefBranch proposalBranch) Proposal.ProposalTypeRebase name -> (remoteOnto, Git.RefBranch $ Git.RemoteBranch remote name) commits <- Git.log baseRef headRef -- must be done after we verify the remote branch exists remoteOntoBranchHash <- Git.refToHash (Git.RefBranch $ Git.RemoteBranch remote ontoBranchName) let nicePrefix = if Proposal.proposalName proposal == ontoBranchName then "_" -- to ensure niceBranchName never equals ontoBranchName else "" niceBranchName = Git.mkBranchName $ nicePrefix <> Git.fromBranchName (Proposal.proposalName proposal) niceBranch = Git.LocalBranch niceBranchName finalBase = Git.RefHash remoteOntoBranchHash -- create local work branch, reset to proposed withLocalBranch niceBranchName $ do case Proposal.proposalType proposal of Proposal.ProposalTypeMerge _mergeType baseHash -> prepareMergeProposal remote proposalBranch proposal baseHash niceBranch Proposal.ProposalTypeRebase branchToRebase -> do Git.reset Git.ResetHard (Git.RefBranch $ Git.RemoteBranch remote branchToRebase) -- rebase target on onto Git.rebase Git.Rebase { Git.rebaseBase = remoteOnto, Git.rebaseOnto = remoteOnto, Git.rebasePolicy = Git.RebaseKeepMerges } `catchError` (rejectProposalAndAbort options remote proposal "Rebase failed" Nothing . Just) -- rebase succeeded, we can now take this job finalHead <- Git.currentRef eprint "Switching to (new) in-progress branch" let forceCreateInProgress = case Proposal.proposalStatus proposal of Proposal.ProposalInProgress{} -> Git.PushForceWithoutLease -- can't use lease to create new branch. stupid git. _ -> Git.PushNonForce inProgressProposal <- makeUnique proposal { Proposal.proposalStatus = Proposal.ProposalInProgress serverId } let inProgressBranchName = Proposal.toBranchName inProgressProposal eprint . T.pack $ "Creating in-progress proposal branch: " <> T.unpack (Git.fromBranchName inProgressBranchName) withNewBranch remote inProgressBranchName forceCreateInProgress $ do Git.deleteLocalBranch niceBranchName jobTaken <- case Proposal.proposalStatus proposal of Proposal.ProposalRejected -> error "ASSERTION FAILED! Shouldn't be taking rejected proposal" Proposal.ProposalInProgress{} | inProgressBranchName == Git.branchName proposalBranch -> return True _ -> do eprint "Deleting proposal branch..." (Git.deleteBranch proposalBranch >> return True) `catchError` const (eprint "Can't delete proposal - Other slave took the job? Dropping" >> return False) if jobTaken then do commitLogHtml <- formatCommitsForEmail options inProgressProposal commits <$> Git.remoteUrl remote let title = if isDryRun options proposal then "Running dry run" else "Attempting to merge" prefix = case Proposal.proposalPrefix proposal of Nothing -> "" Just s -> " (" <> fromNonEmptyText (Proposal.fromPrefix s) <> ")" sendProposalEmail options proposal (title <> prefix) commitLogHtml Nothing ProposalAttemptEmail return . Just $ Job inProgressProposal finalBase finalHead else return Nothing ---------------------------------------------------------------------- transitionProposalToTarget :: Options -> Git.Remote -> Git.Ref -> Proposal -> Proposal.Prefix -> Maybe PrepushLogs -> EShell () transitionProposalToTarget options remote newBase proposal targetPrefix prepushLogs = do newBaseHash <- Git.refToHash newBase shortBaseHash <- Git.shortenHash newBaseHash let updatedProposalType = case Proposal.proposalType proposal of Proposal.ProposalTypeMerge mergeType _oldBase -> Proposal.ProposalTypeMerge mergeType shortBaseHash Proposal.ProposalTypeRebase name -> Proposal.ProposalTypeRebase name updatedProposal <- makeUnique proposal { Proposal.proposalPrefix = Just targetPrefix , Proposal.proposalType = updatedProposalType , Proposal.proposalStatus = Proposal.ProposalProposed } let targetBranchName = Proposal.toBranchName updatedProposal eprint . T.pack $ "Creating target proposal branch: " <> T.unpack (Git.fromBranchName targetBranchName) let ontoBranchName = Proposal.proposalBranchOnto proposal when (targetBranchName == ontoBranchName) $ abort $ "Can't handle branch, onto == target: " <> Git.fromBranchName targetBranchName Git.deleteLocalBranch targetBranchName & ignoreError _ <- Git.createLocalBranch targetBranchName Git.RefHead _ <- Git.pushRemoteTracking remote targetBranchName Git.PushNonForce Git.checkout (Git.RefBranch $ Git.LocalBranch ontoBranchName) Git.deleteLocalBranch targetBranchName sendProposalEmail options proposal ("Ran successfully, moved to: " <> Proposal.prefixToText targetPrefix) "" prepushLogs ProposalSuccessEmail transitionProposalToCompletion :: Options -> Git.Remote -> Git.Ref -> Proposal -> Maybe PrepushLogs -> EShell () transitionProposalToCompletion options remote finalHead proposal prepushLogs = if isDryRun options proposal then sendProposalEmail options proposal "Dry-run: Prepush ran successfully" "" prepushLogs ProposalSuccessEmail else do case Proposal.proposalType proposal of Proposal.ProposalTypeMerge _mergeType _baseRef -> Git.withTempLocalBranch $ \_tempBranchName -> do let ontoBranchName = Proposal.proposalBranchOnto proposal eprint $ "Updating: " <> Git.fromBranchName ontoBranchName Git.deleteLocalBranch ontoBranchName & ignoreError -- ensures the checkout below will set it up to track remote Git.checkout (Git.RefBranch $ Git.LocalBranch ontoBranchName) Git.reset Git.ResetHard (Git.RefBranch $ Git.RemoteBranch remote $ Proposal.toBranchName proposal) -- should succeed without force, because the reset -- hard above should bring it to the proposal rebased -- over latest version of onto Git.push Proposal.ProposalTypeRebase name -> do eprint $ "Updating: " <> Git.fromBranchName name Git.deleteLocalBranch name & ignoreError Git.checkout (Git.RefBranch $ Git.LocalBranch name) Git.reset Git.ResetHard finalHead Git.pushForceWithLease sendProposalEmail options proposal "Merged successfully" "" prepushLogs ProposalSuccessEmail transitionProposal :: Options -> Git.Remote -> Job -> Maybe PrepushLogs -> EShell () transitionProposal options remote (Job proposal finalBase finalHead) prepushLogs = do eprint $ "Transitioning: " <> (T.pack $ show proposal) case Proposal.proposalStatus proposal of Proposal.ProposalInProgress{} -> return () _ -> abort $ "Must not be called on proposals unless they are in progress! Got: " <> (Proposal.formatProposal proposal) case Options.optTargetPrefix options of Nothing -> transitionProposalToCompletion options remote finalHead proposal prepushLogs Just targetPrefix -> transitionProposalToTarget options remote finalBase proposal targetPrefix prepushLogs -- Cleanup curHash <- Git.currentRefHash Git.checkout $ Git.RefHash curHash Git.deleteBranch (Git.LocalBranch $ Proposal.toBranchName proposal) Git.deleteBranch (Git.RemoteBranch remote $ Proposal.toBranchName proposal) ---------------------------------------------------------------------- runPrepush' :: PrepushLogs -> Options.PrepushCmd -> Git.Ref -> Git.Ref -> EShell () runPrepush' (PrepushLogs logDir logFile) (Options.PrepushCmd cmd) baseR headR = do let args = T.intercalate " " $ map T.pack cmd ++ [Git.refName baseR, Git.refName headR] env_str = "SLING_LOG_DIR=" <> encodeFP logDir bashArgs = [ "-o", "pipefail", "-c" , " ( exec 2>&1; " <> env_str <> " " <> args <> " ) | tee " <> encodeFP logFile] eprint $ "Executing bash with: '" <> mconcat bashArgs <> "' output goes to: " <> encodeFP logFile eprint "----------------------------------------------------------------------" eproc "bash" bashArgs (return "") eprint "----------------------------------------------------------------------" TODO delete log if successful ? runPrepush :: Options -> Git.Remote -> Options.PrepushCmd -> PrepushLogs -> Sling.Job -> EShell () runPrepush options remote prepushCmd prepushLogs (Sling.Job proposal finalBase finalHead) = do runPrepush' prepushLogs prepushCmd finalBase finalHead `catchError` (rejectProposalAndAbort options remote proposal "Prepush command failed" (Just prepushLogs) . Just) TODO ensure not dirty eprint "Prepush command ran succesfully"
null
https://raw.githubusercontent.com/Elastifile/git-sling/a92f1836910c0a4d8105ca0dff9d1bd08e9bb181/server/src/Sling.hs
haskell
# LANGUAGE OverloadedStrings # in case it exists in case it exists We have to be on another branch before deleting stuff, so arbitrarily picking rejected branch Checks that the proposal is valid (e.g. the onto branch still actually exists on the remote) TODO: Add check that base hash (for merge proposals) is in range of commits that makes sense Rebases given proposal over latest known state of its target branch and pushes it to the remote. If the rebase fails, rejects the proposal. nothing to update nothing to do create updated proposal branch Concurrency issues here: If deleting the (not-updated) proposal fails, then possibly someone else already deleted the proposal, In any case, deleting the proposal serves as a 'commit' for operations on it, so someone else beat us to it and we must undo our actions above which are just creating a new branch of the updated proposal. -------------------------------------------------------------------- The proposal was deleted while we were working on it. Forget about it. note: 'nice' branch and 'onto' branch may be the same branch. (e.g. proposal called 'master' with onto=master) check that the proposal's base commit is exactly onto (should have been rebased by now): point the working ('nice') branch to the proposal's head go back to 'onto', decide whether to create a merge commit on top (if we should merge ff only) Fast-forward the work branch to match the merged 'onto' we do this so that the prepush script will see itself running on a branch with the name the user gave to this proposal, and not the onto branch's name. must be done after we verify the remote branch exists to ensure niceBranchName never equals ontoBranchName create local work branch, reset to proposed rebase target on onto rebase succeeded, we can now take this job can't use lease to create new branch. stupid git. -------------------------------------------------------------------- ensures the checkout below will set it up to track remote should succeed without force, because the reset hard above should bring it to the proposal rebased over latest version of onto Cleanup --------------------------------------------------------------------
module Sling ( Job(..) , tryTakeJob , rejectProposal , updateProposal , transitionProposal , runPrepush ) where import Control.Monad (unless, when, void) import Control.Monad.Except (MonadError (..)) import Data.Monoid ((<>)) import Data.Text (Text) import qualified Data.Text as T import Text.Blaze.Html (toHtml) import Turtle ((&), ExitCode) import qualified Sling.Git as Git import Sling.Email (sendProposalEmail, formatCommitsForEmail, EmailType(..)) import Sling.Lib (EShell, Hash(..), ignoreError, assert, eprint, abort, eproc, NonEmptyText(..)) import Sling.Options (Options, isDryRun) import qualified Sling.Options as Options import Sling.Path (encodeFP) import Sling.Prepush (PrepushLogs(..)) import qualified Sling.Proposal as Proposal import Sling.Proposal (Proposal) data Job = Job { jobProposal :: Proposal , jobBase :: Git.Ref , jobHead :: Git.Ref } deriving (Show) makeUnique :: Proposal -> EShell Proposal makeUnique proposal = do remoteBranches <- map snd <$> Git.remoteBranches let proposalBranch = Proposal.toBranchName proposal if proposalBranch `elem` remoteBranches then do let oldName = Git.fromBranchName $ Proposal.proposalName proposal withSuffix sfx = proposal { Proposal.proposalName = Git.mkBranchName $ oldName <> "_" <> T.pack (show sfx) } go n = if Proposal.toBranchName newProposal `elem` remoteBranches then go (n+1) else newProposal where newProposal = withSuffix n return $ go (1 :: Int) else return proposal rejectProposalAndAbort :: Options -> Git.Remote -> Proposal -> Text -> Maybe PrepushLogs -> Maybe (Text, ExitCode) -> EShell () rejectProposalAndAbort options remote proposal reason prepushLogs err = do rejectProposal options remote proposal reason prepushLogs err abort "Rejected" rejectProposal :: Options -> Git.Remote -> Proposal -> Text -> Maybe PrepushLogs -> Maybe (Text, ExitCode) -> EShell () rejectProposal options remote proposal reason prepushLogs err = do let origBranchName = Proposal.toBranchName proposal rejectedProposal = proposal { Proposal.proposalStatus = Proposal.ProposalRejected } rejectBranchName = Proposal.toBranchName rejectedProposal suffix = case err of Just (msg, errCode) -> " because: '" <> reason <> "' (" <> msg <> "), exit code = " <> T.pack (show errCode) Nothing -> "" msgBody = "REJECT " <> Git.fromBranchName origBranchName <> suffix eprint msgBody sendProposalEmail options proposal ("Rejecting (" <> reason <> ")") (toHtml msgBody) prepushLogs ProposalFailureEmail Git.fetch & ignoreError Git.reset Git.ResetHard Git.RefHead _ <- Git.createLocalBranch rejectBranchName Git.RefHead _ <- Git.pushRemoteTracking remote rejectBranchName Git.PushForceWithoutLease Git.checkout (Git.RefBranch $ Git.LocalBranch rejectBranchName) Git.deleteBranch (Git.LocalBranch origBranchName) & ignoreError Git.deleteBranch (Git.RemoteBranch remote origBranchName) verifyProposal :: Options -> Git.Remote -> Proposal -> EShell () verifyProposal options remote proposal = do let ontoBranchName = Proposal.proposalBranchOnto proposal remoteBranches <- Git.remoteBranches unless ((remote, ontoBranchName) `elem` remoteBranches) $ rejectProposalAndAbort options remote proposal ("Remote branch doesn't exist: " <> Git.fromBranchName ontoBranchName) Nothing Nothing updateProposal :: Options -> Git.Remote -> (Git.Branch, Proposal) -> EShell (Maybe (Git.Branch, Proposal)) updateProposal options remote (proposalBranch, proposal) = do verifyProposal options remote proposal updateProposal' options remote (proposalBranch, proposal) updateProposal' :: Options -> Git.Remote -> (Git.Branch, Proposal) -> EShell (Maybe (Git.Branch, Proposal)) updateProposal' options remote (proposalBranch, proposal) = case Proposal.proposalType proposal of Proposal.ProposalTypeMerge mergeType origBaseHash -> Git.withTempLocalBranch $ \tempBranchName -> do let proposalBranchName = Git.branchName proposalBranch ontoBranchName = Proposal.proposalBranchOnto proposal remoteOntoBranch = Git.RemoteBranch remote ontoBranchName newBaseHash <- Git.refToHash $ Git.RefBranch remoteOntoBranch oldBaseHash <- Git.unshortenHash origBaseHash newBaseShortHash <- Git.shortenHash newBaseHash eprint $ "Comparing base hashes: " <> T.intercalate " " (map (T.pack . show) [newBaseHash, oldBaseHash]) if newBaseHash == oldBaseHash else do updatedProposal <- makeUnique proposal { Proposal.proposalType = Proposal.ProposalTypeMerge mergeType newBaseShortHash } let updatedProposalBranchName = Proposal.toBranchName updatedProposal remoteProposalBranch = Git.RefBranch $ Git.RemoteBranch remote proposalBranchName rebasePolicy = case mergeType of Proposal.MergeTypeFlat -> Git.RebaseDropMerges Proposal.MergeTypeKeepMerges -> Git.RebaseKeepMerges Git.reset Git.ResetHard remoteProposalBranch Git.rebase Git.Rebase { Git.rebaseBase = Git.RefHash origBaseHash , Git.rebaseOnto = Git.RefBranch remoteOntoBranch , Git.rebasePolicy = rebasePolicy } `catchError` (rejectProposalAndAbort options remote proposal "Rebase failed" Nothing . Just) Git.deleteLocalBranch updatedProposalBranchName & ignoreError _ <- Git.createLocalBranch updatedProposalBranchName Git.RefHead createdRemoteBranch <- Git.pushRemoteTracking remote updatedProposalBranchName Git.PushNonForce assert (==) createdRemoteBranch (Git.RemoteBranch remote updatedProposalBranchName) Nothing Git.checkout (Git.RefBranch $ Git.LocalBranch tempBranchName) Git.deleteLocalBranch updatedProposalBranchName 1 . Either because a user wanted to cancel this proposal , 2 . Or , they were also rebasing it ( like this function ) 3 . Or , they were rejecting it because it failed rebase ( which did n't fail for us because our remote is outdated ) 4 . Or , the proposal was marked as ' in progress ' Git.deleteRemoteBranch remote proposalBranchName >> return (Just (createdRemoteBranch, updatedProposal)) `catchError` (\_ -> Git.deleteRemoteBranch remote updatedProposalBranchName >> return Nothing) withNewBranch :: Git.Remote -> Git.BranchName -> Git.PushType -> EShell a -> EShell a withNewBranch remote b pushType act = do currentRef <- Git.currentRef Git.deleteLocalBranch b & ignoreError _ <- Git.createLocalBranch b Git.RefHead _ <- Git.pushRemoteTracking remote b pushType let cleanup = do Git.checkout currentRef Git.deleteBranch (Git.LocalBranch b) Git.deleteBranch (Git.RemoteBranch remote b) act `catchError` (\e -> cleanup >> throwError e) withLocalBranch :: Git.BranchName -> EShell a -> EShell a withLocalBranch name act = do let branch = Git.LocalBranch name currentRef <- Git.currentRef Git.deleteBranch branch & ignoreError shouldCreate <- notElem name <$> Git.localBranches when shouldCreate $ void $ Git.createLocalBranch name Git.RefHead Git.checkout (Git.RefBranch branch) let cleanup = do Git.checkout currentRef when shouldCreate $ Git.deleteBranch branch act `catchError` (\e -> cleanup >> throwError e) tryTakeJob :: Proposal.ServerId -> Options -> Git.Remote -> (Git.Branch, Proposal) -> EShell (Maybe Job) tryTakeJob serverId options remote (proposalBranch, proposal) = do mUpdatedProposal <- Sling.updateProposal options remote (proposalBranch, proposal) case mUpdatedProposal of Nothing -> do eprint "Other slave took the job or proposal deleted? Dropping" return Nothing Just (updatedProposalBranch, updatedProposal) -> tryTakeJob' serverId options remote updatedProposalBranch updatedProposal prepareMergeProposal :: Git.Remote -> Git.Branch -> Proposal -> Hash -> Git.Branch -> EShell () prepareMergeProposal remote proposalBranch proposal baseHash niceBranch = do let ontoBranchName = Proposal.proposalBranchOnto proposal remoteOntoBranchHash <- Git.refToHash (Git.RefBranch $ Git.RemoteBranch remote ontoBranchName) fullBaseHash <- Git.unshortenHash baseHash assert (==) fullBaseHash remoteOntoBranchHash . Just $ "Expected branch to be rebased already, but it isn't: " <> T.intercalate " " (map (T.pack . show) [ remoteOntoBranchHash, fullBaseHash ]) Git.reset Git.ResetHard (Git.RefBranch proposalBranch) isMerge <- Git.isMergeCommit Git.RefHead commits <- Git.log (Git.RefHash fullBaseHash) Git.RefHead if length commits == 0 then eprint "Empty proposal, nothing to do here" else do let mergeFF = if isMerge || (length commits == 1) then Git.MergeFFOnly else Git.MergeNoFF Git.checkout (Git.RefBranch $ Git.LocalBranch ontoBranchName) Git.reset Git.ResetHard (Git.RefBranch $ Git.RemoteBranch remote ontoBranchName) Git.merge mergeFF niceBranch when (mergeFF == Git.MergeNoFF) $ Git.commitAmend (Proposal.proposalEmail proposal) Git.RefHead newHead <- Git.currentRef Git.checkout (Git.RefBranch niceBranch) Git.merge Git.MergeFFOnly (Git.LocalBranch ontoBranchName) headAfterFF <- Git.currentRef assert (==) newHead headAfterFF $ Just "Expected to arrive at same commit" tryTakeJob' :: Proposal.ServerId -> Options -> Git.Remote -> Git.Branch -> Proposal -> EShell (Maybe Job) tryTakeJob' serverId options remote proposalBranch proposal = do let ontoBranchName = Proposal.proposalBranchOnto proposal remoteOnto = Git.RefBranch $ Git.RemoteBranch remote ontoBranchName (baseRef, headRef) = case Proposal.proposalType proposal of Proposal.ProposalTypeMerge _mergeType base -> (Git.RefHash base, Git.RefBranch proposalBranch) Proposal.ProposalTypeRebase name -> (remoteOnto, Git.RefBranch $ Git.RemoteBranch remote name) remoteOntoBranchHash <- Git.refToHash (Git.RefBranch $ Git.RemoteBranch remote ontoBranchName) let nicePrefix = if Proposal.proposalName proposal == ontoBranchName else "" niceBranchName = Git.mkBranchName $ nicePrefix <> Git.fromBranchName (Proposal.proposalName proposal) niceBranch = Git.LocalBranch niceBranchName finalBase = Git.RefHash remoteOntoBranchHash withLocalBranch niceBranchName $ do case Proposal.proposalType proposal of Proposal.ProposalTypeMerge _mergeType baseHash -> prepareMergeProposal remote proposalBranch proposal baseHash niceBranch Proposal.ProposalTypeRebase branchToRebase -> do Git.reset Git.ResetHard (Git.RefBranch $ Git.RemoteBranch remote branchToRebase) Git.rebase Git.Rebase { Git.rebaseBase = remoteOnto, Git.rebaseOnto = remoteOnto, Git.rebasePolicy = Git.RebaseKeepMerges } `catchError` (rejectProposalAndAbort options remote proposal "Rebase failed" Nothing . Just) finalHead <- Git.currentRef eprint "Switching to (new) in-progress branch" let forceCreateInProgress = case Proposal.proposalStatus proposal of _ -> Git.PushNonForce inProgressProposal <- makeUnique proposal { Proposal.proposalStatus = Proposal.ProposalInProgress serverId } let inProgressBranchName = Proposal.toBranchName inProgressProposal eprint . T.pack $ "Creating in-progress proposal branch: " <> T.unpack (Git.fromBranchName inProgressBranchName) withNewBranch remote inProgressBranchName forceCreateInProgress $ do Git.deleteLocalBranch niceBranchName jobTaken <- case Proposal.proposalStatus proposal of Proposal.ProposalRejected -> error "ASSERTION FAILED! Shouldn't be taking rejected proposal" Proposal.ProposalInProgress{} | inProgressBranchName == Git.branchName proposalBranch -> return True _ -> do eprint "Deleting proposal branch..." (Git.deleteBranch proposalBranch >> return True) `catchError` const (eprint "Can't delete proposal - Other slave took the job? Dropping" >> return False) if jobTaken then do commitLogHtml <- formatCommitsForEmail options inProgressProposal commits <$> Git.remoteUrl remote let title = if isDryRun options proposal then "Running dry run" else "Attempting to merge" prefix = case Proposal.proposalPrefix proposal of Nothing -> "" Just s -> " (" <> fromNonEmptyText (Proposal.fromPrefix s) <> ")" sendProposalEmail options proposal (title <> prefix) commitLogHtml Nothing ProposalAttemptEmail return . Just $ Job inProgressProposal finalBase finalHead else return Nothing transitionProposalToTarget :: Options -> Git.Remote -> Git.Ref -> Proposal -> Proposal.Prefix -> Maybe PrepushLogs -> EShell () transitionProposalToTarget options remote newBase proposal targetPrefix prepushLogs = do newBaseHash <- Git.refToHash newBase shortBaseHash <- Git.shortenHash newBaseHash let updatedProposalType = case Proposal.proposalType proposal of Proposal.ProposalTypeMerge mergeType _oldBase -> Proposal.ProposalTypeMerge mergeType shortBaseHash Proposal.ProposalTypeRebase name -> Proposal.ProposalTypeRebase name updatedProposal <- makeUnique proposal { Proposal.proposalPrefix = Just targetPrefix , Proposal.proposalType = updatedProposalType , Proposal.proposalStatus = Proposal.ProposalProposed } let targetBranchName = Proposal.toBranchName updatedProposal eprint . T.pack $ "Creating target proposal branch: " <> T.unpack (Git.fromBranchName targetBranchName) let ontoBranchName = Proposal.proposalBranchOnto proposal when (targetBranchName == ontoBranchName) $ abort $ "Can't handle branch, onto == target: " <> Git.fromBranchName targetBranchName Git.deleteLocalBranch targetBranchName & ignoreError _ <- Git.createLocalBranch targetBranchName Git.RefHead _ <- Git.pushRemoteTracking remote targetBranchName Git.PushNonForce Git.checkout (Git.RefBranch $ Git.LocalBranch ontoBranchName) Git.deleteLocalBranch targetBranchName sendProposalEmail options proposal ("Ran successfully, moved to: " <> Proposal.prefixToText targetPrefix) "" prepushLogs ProposalSuccessEmail transitionProposalToCompletion :: Options -> Git.Remote -> Git.Ref -> Proposal -> Maybe PrepushLogs -> EShell () transitionProposalToCompletion options remote finalHead proposal prepushLogs = if isDryRun options proposal then sendProposalEmail options proposal "Dry-run: Prepush ran successfully" "" prepushLogs ProposalSuccessEmail else do case Proposal.proposalType proposal of Proposal.ProposalTypeMerge _mergeType _baseRef -> Git.withTempLocalBranch $ \_tempBranchName -> do let ontoBranchName = Proposal.proposalBranchOnto proposal eprint $ "Updating: " <> Git.fromBranchName ontoBranchName Git.checkout (Git.RefBranch $ Git.LocalBranch ontoBranchName) Git.reset Git.ResetHard (Git.RefBranch $ Git.RemoteBranch remote $ Proposal.toBranchName proposal) Git.push Proposal.ProposalTypeRebase name -> do eprint $ "Updating: " <> Git.fromBranchName name Git.deleteLocalBranch name & ignoreError Git.checkout (Git.RefBranch $ Git.LocalBranch name) Git.reset Git.ResetHard finalHead Git.pushForceWithLease sendProposalEmail options proposal "Merged successfully" "" prepushLogs ProposalSuccessEmail transitionProposal :: Options -> Git.Remote -> Job -> Maybe PrepushLogs -> EShell () transitionProposal options remote (Job proposal finalBase finalHead) prepushLogs = do eprint $ "Transitioning: " <> (T.pack $ show proposal) case Proposal.proposalStatus proposal of Proposal.ProposalInProgress{} -> return () _ -> abort $ "Must not be called on proposals unless they are in progress! Got: " <> (Proposal.formatProposal proposal) case Options.optTargetPrefix options of Nothing -> transitionProposalToCompletion options remote finalHead proposal prepushLogs Just targetPrefix -> transitionProposalToTarget options remote finalBase proposal targetPrefix prepushLogs curHash <- Git.currentRefHash Git.checkout $ Git.RefHash curHash Git.deleteBranch (Git.LocalBranch $ Proposal.toBranchName proposal) Git.deleteBranch (Git.RemoteBranch remote $ Proposal.toBranchName proposal) runPrepush' :: PrepushLogs -> Options.PrepushCmd -> Git.Ref -> Git.Ref -> EShell () runPrepush' (PrepushLogs logDir logFile) (Options.PrepushCmd cmd) baseR headR = do let args = T.intercalate " " $ map T.pack cmd ++ [Git.refName baseR, Git.refName headR] env_str = "SLING_LOG_DIR=" <> encodeFP logDir bashArgs = [ "-o", "pipefail", "-c" , " ( exec 2>&1; " <> env_str <> " " <> args <> " ) | tee " <> encodeFP logFile] eprint $ "Executing bash with: '" <> mconcat bashArgs <> "' output goes to: " <> encodeFP logFile eprint "----------------------------------------------------------------------" eproc "bash" bashArgs (return "") eprint "----------------------------------------------------------------------" TODO delete log if successful ? runPrepush :: Options -> Git.Remote -> Options.PrepushCmd -> PrepushLogs -> Sling.Job -> EShell () runPrepush options remote prepushCmd prepushLogs (Sling.Job proposal finalBase finalHead) = do runPrepush' prepushLogs prepushCmd finalBase finalHead `catchError` (rejectProposalAndAbort options remote proposal "Prepush command failed" (Just prepushLogs) . Just) TODO ensure not dirty eprint "Prepush command ran succesfully"
1ff73322351613e5915e8d0fc57b21d035ba4e3227347bc9b24853700d5d0e88
bos/rwh
basicio.hs
{-- snippet all --} main = do putStrLn "Greetings! What is your name?" inpStr <- getLine putStrLn $ "Welcome to Haskell, " ++ inpStr ++ "!" {-- /snippet all --}
null
https://raw.githubusercontent.com/bos/rwh/7fd1e467d54aef832f5476ebf5f4f6a898a895d1/examples/ch07/basicio.hs
haskell
- snippet all - - /snippet all -
main = do putStrLn "Greetings! What is your name?" inpStr <- getLine putStrLn $ "Welcome to Haskell, " ++ inpStr ++ "!"
437d1a505c08e2c068104545fdb9429d4e8286a36a983e1dc290215f90019850
g000001/MacLISP-compat
CARCDR.lisp
;;; -*-LISP-*- (cl:in-package :maclisp.internal) #|(named-readtables:in-readtable :maclisp)|# ;(named-readtables:in-readtable :standard) Purpose : to permit long names , like CADADADADDDR , to be easily ;;; macro-defined into appropriate sequences of CARs and CDRs. ;;; Use: (DEF-CARCDR CADADADADDDR CADADADDDDDR ... ) where the names must have at least 5 A / D 's . ;;; Produces a format internal to the compiler when being expanded ;;; for optimal compilation. For interpretation, produces a ;;; LAMBDA form with a composition of initial carcdr functions of up to 4 deep , which should be ( already ) defined primitively . (DEFMACRO DEF-CARCDR (&rest carcdrs) `(PROGN ,@(mapcar (lambda (x) `(defun ,x (list) ,(c*r (list x 'list)))) carcdrs))) (DEFUN C*R (X) (destructuring-bind (NAME ARG1 . L) X (AND L (ERROR 'WRNG-NO-ARGS :message "~A Extra args in call to C*R macro" :argument X)) (AND (OR (< (LENGTH (SETQ L (EXPLODEC NAME))) 7) (NOT (EQ (CAR L) 'C)) (NOT (EQ (CAR (SETQ L (NREVERSE (CDR L)))) 'R)) (DO ((L (SETQ L (NREVERSE (CDR L))) (CDR L))) ((NULL L)) (AND (NOT (MEMBER (CAR L) '(A D))) (RETURN 'T)))) (ERROR 'WRNG-TYPE-ARG :message "~A Invalid name for C*R macro|" :argument X)) `((LAMBDA (X) ,(|c*r-expander\|| l 'x)) ,arg1))) (DEFUN C*R (X) Gets the complr 's CARCDR variable (LET (((NAME ARG1 . L) X)) (AND L (ERROR '|Extra args in call to C*R macro| X 'WRNG-NO-ARGS)) (AND (OR (< (LENGTH (SETQ L (EXPLODEC NAME))) 7) (NOT (EQ (CAR L) 'C)) (NOT (EQ (CAR (SETQ L (NREVERSE (CDR L)))) 'R)) (DO L (SETQ L (NREVERSE (CDR L))) (CDR L) (NULL L) (AND (NOT (MEMQ (CAR L) '(A D))) (RETURN 'T)))) (ERROR '|Invalid name for C*R macro| X 'WRNG-TYPE-ARG)) ( ( EQ COMPILER - STATE ' ) ` ( , carcdr , @(nreverse l ) ) ) (`(LAMBDA (X) ,(|c*r-expander\|| l 'X)))) ,arg1))) (DEFUN |c*r-expander\|| (L ARG) (COND ((< (LENGTH L) 5) `(,(implode (nconc (list 'C) l '(R))) ,arg)) ((LET* ((3TAIL (NTHCDR 3 L)) (4TAIL (CDR 3TAIL))) (RPLACD 3TAIL () ) (|c*r-expander\|| L (|c*r-expander\|| 4TAIL ARG))))))
null
https://raw.githubusercontent.com/g000001/MacLISP-compat/a147d09b98dca4d7c089424c3cbaf832d2fd857a/CARCDR.lisp
lisp
-*-LISP-*- (named-readtables:in-readtable :maclisp) (named-readtables:in-readtable :standard) macro-defined into appropriate sequences of CARs and CDRs. Use: (DEF-CARCDR CADADADADDDR CADADADDDDDR ... ) Produces a format internal to the compiler when being expanded for optimal compilation. For interpretation, produces a LAMBDA form with a composition of initial carcdr functions
(cl:in-package :maclisp.internal) Purpose : to permit long names , like CADADADADDDR , to be easily where the names must have at least 5 A / D 's . of up to 4 deep , which should be ( already ) defined primitively . (DEFMACRO DEF-CARCDR (&rest carcdrs) `(PROGN ,@(mapcar (lambda (x) `(defun ,x (list) ,(c*r (list x 'list)))) carcdrs))) (DEFUN C*R (X) (destructuring-bind (NAME ARG1 . L) X (AND L (ERROR 'WRNG-NO-ARGS :message "~A Extra args in call to C*R macro" :argument X)) (AND (OR (< (LENGTH (SETQ L (EXPLODEC NAME))) 7) (NOT (EQ (CAR L) 'C)) (NOT (EQ (CAR (SETQ L (NREVERSE (CDR L)))) 'R)) (DO ((L (SETQ L (NREVERSE (CDR L))) (CDR L))) ((NULL L)) (AND (NOT (MEMBER (CAR L) '(A D))) (RETURN 'T)))) (ERROR 'WRNG-TYPE-ARG :message "~A Invalid name for C*R macro|" :argument X)) `((LAMBDA (X) ,(|c*r-expander\|| l 'x)) ,arg1))) (DEFUN C*R (X) Gets the complr 's CARCDR variable (LET (((NAME ARG1 . L) X)) (AND L (ERROR '|Extra args in call to C*R macro| X 'WRNG-NO-ARGS)) (AND (OR (< (LENGTH (SETQ L (EXPLODEC NAME))) 7) (NOT (EQ (CAR L) 'C)) (NOT (EQ (CAR (SETQ L (NREVERSE (CDR L)))) 'R)) (DO L (SETQ L (NREVERSE (CDR L))) (CDR L) (NULL L) (AND (NOT (MEMQ (CAR L) '(A D))) (RETURN 'T)))) (ERROR '|Invalid name for C*R macro| X 'WRNG-TYPE-ARG)) ( ( EQ COMPILER - STATE ' ) ` ( , carcdr , @(nreverse l ) ) ) (`(LAMBDA (X) ,(|c*r-expander\|| l 'X)))) ,arg1))) (DEFUN |c*r-expander\|| (L ARG) (COND ((< (LENGTH L) 5) `(,(implode (nconc (list 'C) l '(R))) ,arg)) ((LET* ((3TAIL (NTHCDR 3 L)) (4TAIL (CDR 3TAIL))) (RPLACD 3TAIL () ) (|c*r-expander\|| L (|c*r-expander\|| 4TAIL ARG))))))
9b890e637183621795c4bda9c57fc18ab23e2ae178ed58f3b970c534856cd944
basho/riak_ensemble
riak_ensemble_peer_intercepts.erl
-module(riak_ensemble_peer_intercepts). -compile([export_all, nowarn_export_all]). -include("riak_ensemble_types.hrl"). -define(M, riak_ensemble_peer_orig). check_epoch_false(_Peer, _Epoch, _State) -> false. check_epoch(Peer, Epoch, State) -> ?M:check_epoch_orig(Peer, Epoch, State).
null
https://raw.githubusercontent.com/basho/riak_ensemble/f279810f3b9b3a1b4bc82dda738364242896ff32/test/riak_ensemble_peer_intercepts.erl
erlang
-module(riak_ensemble_peer_intercepts). -compile([export_all, nowarn_export_all]). -include("riak_ensemble_types.hrl"). -define(M, riak_ensemble_peer_orig). check_epoch_false(_Peer, _Epoch, _State) -> false. check_epoch(Peer, Epoch, State) -> ?M:check_epoch_orig(Peer, Epoch, State).
ed6ed8c47054e2434ba9bbb51197cc11b1a314a21c43a6775b3baa746fab36d1
rcherrueau/APE
ownership.rkt
#lang racket/base ;; ,-,-,-. ;; `,| | | ,-. . . ,-. ,-. . . ,-. ,-. ;; | ; | . ,-| | | | ,-| | | | | | ;; ' `-' `-^ `-^ `-' `-^ `-^ `-' `-' ;; Ownership Types Checker. ;; ;; Ownership type checking phase (Θ>) ;; - Type checks the program (for simple type -- "simple" as in simply ;; typed λ calculus, i.e., no ownership). ;; - Based on [CPN98] (see Bibliography). ;; ;; Environments: ;; (require (for-syntax racket/base) racket/function racket/match racket/sequence racket/syntax syntax/parse syntax/srcloc syntax/stx "definitions.rkt" "utils.rkt" "meta.rkt" (prefix-in env: (submod "env.rkt" ownership))) (module+ test (require rackunit)) (provide Θ>) ;; Phase θ> (define-phase (Θ> stx meta:CS meta:FS meta:DS) ;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ;; Env ;; Set of local context parameters ;; (: ( Setof Identifier ) ) (Σ #:init '() #:mk env:make-Σ #:apply? [env:Σ-member? env:Σ-union]) ;; Mapping from locally bound variables to ownership types ;; ;; (: Γ (Identifier ~> O-TYPE)) (Γ #:init '() #:mk env:make-Γ #:apply? [env:Γ-member? env:Γ-add env:Γ-ref]) ;; Store of the ownership scheme of the current class ;; (: τ OW - TYPE ) (τ #:init #'Bottom #:mk identity) ;; Mapping from existing class types to its ownership scheme ;; (t ~> t^) ;; ;; (: OWS (TYPE ~> OW-TYPE)) (OWS #:init (meta-map-w/key (λ (kv) (match-define (cons CTYPE CPARAM...) kv) (cons CTYPE #`(#,CTYPE Θ #,CPARAM...))) meta:CS) #:mk env:make-OWS #:apply? [env:OWS-arity env:OWS-ref env:ψ]) ;; Map of fields ;; (: FS ( ( Syntaxof ( Pairof TYPE ; Class type Identifier ) ) ; Field name ~ > OW - TYPE ) ) ; Field return type (FS #:init meta:FS #:mk env:make-FS #:apply? [env:FS-member? env:FS-ref]) ;; Map of definitions ;; ;; (: DS ((Syntaxof (Pairof Identifier ; Class type ;; Identifier)) ; Def name ;; ~> ( Syntaxof ( Pairof ( Syntaxof ( ) ) ; Type of def args OW - TYPE ) ) ; return type (DS #:init (meta-map-w/key (λ (kv) (match-let* ([`(,DS-key . ,RET-OWS) kv] [`(,CTYPE ,DNAME ,ARG-OWS...) (syntax-e DS-key)]) (cons #`(#,CTYPE . #,DNAME) #`(#,ARG-OWS... #,RET-OWS)))) meta:DS) #:mk env:make-DS #:apply? [env:DS-member? env:DS-ref]) ;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parse (⊢p stx)) ;; ⊢p P : t ;; ;; `P` is well-formed with ownership type `t` (define-rules ⊢p ;; [program] [((import _ ...) CLASS ... E) ;; Check P ⊢d CLASS #:do [(stx-map ⊢d #'(CLASS ...))] ;; Check P,[],[] ⊢e E : t #:with [_ t] (get-τ (with-Σ '() (with-Γ '() (⊢e #'E)))) ;; ---------------------------------------------------------------- ;; ⊢p P : t (add-τ this-syntax #'t)]) ;; P ⊢d CLASS ;; ;; In context `P`, `CLASS` is well-formed (define-rules ⊢d ;; [Class] [(class ~! NAME [CPARAM ...] FIELD/DEF ...) #:with [FIELD ...] (filter field? (stx->list #'(FIELD/DEF ...))) #:with [DEF ...] (filter def? (stx->list #'(FIELD/DEF ...))) ;; Σ = { Θ } ∪ { CPARAM ... } ;; τ = OWS(NAME) (i.e., `#'(NAME Θ [CPARAM ...])`) ;;;; The `Θ` means `owner`. #:do [(define the-Σ #'(Θ CPARAM ...)) (define the-τ (OWS-ref #'NAME))] ;; Check P,Σ ⊢τ t on fields #:with [(field ~! F-NAME F) ...] #'(FIELD ...) #:when (with-Σ the-Σ (stx-for/and ([t #'(F ...)]) (⊢τ t))) ;; Check P,Σ,{ this: NAME<Θ|[CPARAM ...]> } ⊢m DEF ;;;; Note: Unlike [CPN98], I chose to go with an environment for ;;;; the current class ownership scheme (τ), rather than binding ;;;; the `this` in `Γ` here, so I don't have to latter implement an ;;;; union operation for `Γ`. #:when (with-Σ the-Σ (with-τ the-τ (stx-map ⊢m #'(DEF ...)))) ;; ---------------------------------------------------------------- ;; P ⊢d (class NAME [CPARAM ...] FIELD ... DEF ...) this-syntax]) (module+ test (define-test-suite ⊢d-parse ;; P ⊢d CLASS (with-OWS (list (cons #'Foo #'(Foo Θ ()))) ;; Check P,Σ ⊢τ t on fields (check-exn exn:arity-error? (thunk (⊢d #'(class Foo [] (field foo (Foo rep {rep}))))) "`Foo` does not takes context parameters") (check-exn exn:unknown-cparam? (thunk (⊢d #'(class Foo [] (field foo (Foo o {}))))) "`The context parameter `o` has not been introduced") (check-not-exn (thunk (⊢d #'(class Foo [] (field foo (Foo rep {})))))) (check-not-exn (thunk (⊢d #'(class Foo [] (field foo (Foo world {})))))) (check-not-exn (thunk (⊢d #'(class Foo [o] (field foo (Foo o {})))))) ;; Check P,Σ,{ this: NAME<Θ|[CPARAM ...]> } ⊢m DEF ;; [(def ~! (_NAME (ARG-NAME ARG-OT) ... RET-OT) E ...+) (check-not-exn (thunk (⊢d #'(class Foo [] (def (def/0 (Foo Θ ())) this)))) "`this` is of type `Θ/Foo` in `def`")))) ;; P,Σ,τ ⊢m DEF ;; ;; In context `P,Σ,τ`, `DEF` is well-formed (define-rules ⊢m ;; [Method] [(def ~! (_NAME (ARG-NAME ARG-OT) ... RET-OT) E ...+) ;; Get current class type store in τ environment #:with τ0 (τ) ;; Check P,Σ ⊢τ t on return type #:when (⊢τ #'RET-OT) ;; Check P,Σ ⊢τ t on args #:when (stx-for/and ([t #'(ARG-OT ...)]) (⊢τ t)) ;; Check P,Σ,{this: τ0, ARG-NAME: ARG-OT, ...} ⊢e E ... LEB : RET-OT #:with [_ ... ΘLEB] (with-Γ #'{ (this . τ0) (??? . RET-OT) (ARG-NAME . ARG-OT) ... } (stx-map ⊢e #'(E ...))) #:with [_ t-e] (get-τ #'ΘLEB) #:when (or (τ=? #'t-e #'RET-OT) (raise (mk-exn:ownership-mismatch #'t-e #'RET-OT #'ΘLEB))) ;; ---------------------------------------------------------------- P , Σ , τ0 ⊢m ( def ( NAME ( ARG - NAME ARG - OT ) ... RET - OT ) E ... + ) this-syntax]) (module+ test (define-test-suite ⊢m-parse ;; P,Σ,τ ⊢m DEF (with-OWS (list (cons #'Foo #'(Foo Θ ())) (cons #'Bar #'(Bar Θ (n m)))) (with-Σ #'(Θ o n m) (with-τ #'(Foo o ()) ;; Check P,Σ ⊢τ t on return type (check-exn exn:unknown-cparam? (thunk (⊢m #'(def (def/0 (Bar o (n t))) _))) "`t` is not a defined context parameter") (check-exn exn:arity-error? (thunk (⊢m #'(def (def/2 (Bar o (n))) _))) "`Bar` takes two context parameters") (check-exn exn:arity-error? (thunk (⊢m #'(def (def/2 (Bar o (n n n))) _))) "`Bar` takes two context parameters") ;; Check P,Σ ⊢τ t on args (check-exn exn:unknown-cparam? (thunk (⊢m #'(def (def/2 (arg1 (Foo o ())) (arg2 (Bar o (n t))) (Bar o (n m))) _))) "`t` is not a defined context parameter") (check-exn exn:unknown-cparam? (thunk (⊢m #'(def (def/2 (arg1 (Foo t ())) (arg2 (Bar o (n m))) (Bar o (n m))) _))) "`t` is not a defined context parameter") (check-exn exn:arity-error? (thunk (⊢m #'(def (def/2 (arg1 (Foo o ())) (arg2 (Bar o (n))) (Bar o (n m))) _))) "`Bar` takes two context parameters") (check-exn exn:arity-error? (thunk (⊢m #'(def (def/2 (arg1 (Foo o ())) (arg2 (Bar o (n n n))) (Bar o (n m))) _))) "`Bar` takes two context parameters") ;; Check P,Σ,{this: τ0, ARG-NAME: ARG-OT, ...} ⊢e E ... LEB : RET-OT (check-exn exn:ownership-mismatch? (thunk (⊢m #'(def (def/0 (Bar o (n m))) (new (Bar n (n m)))))) "`def` should return a `o/Bar{n m}` but the expression is of type `n/Bar{n m}`") (check-exn exn:ownership-mismatch? (thunk (⊢m #'(def (def/0 (Bar o (n m))) (new (Bar o (m m)))))) "`def` should return a `o/Bar{n m}` but the expression is of type `n/Bar{m m}`") (check-not-exn (thunk (⊢m #'(def (def/0 (Foo o ())) this))) "`this` is bound in the expression with the `Foo` type (τ env)") (check-not-exn (thunk (⊢m #'(def (def/0 (Foo o ())) ???))) "A def accepts the `???` place holder as expression" ) (check-not-exn (thunk (⊢m #'(def (def/0 (Bar o (n m))) ???))) "A def accepts the `???` place holder as expression" ) (check-not-exn (thunk (⊢m #'(def (def/2 (arg1 (Bar o (n m))) (arg2 (Foo o ())) (Bar o (n m))) arg1))) "`arg1` is bound in the expression with the `o/Bar{n m}` type") (check-not-exn (thunk (⊢m #'(def (def/2 (arg1 (Bar o (n m))) (arg2 (Foo o ())) (Foo o ())) arg2))) "`arg2` is bound in the expression with the `o/Foo` type") (check-not-exn (thunk (⊢m #'(def (def/2 (arg1 (Bar o (n m))) (arg2 (Foo o ())) (Foo o ())) arg1 arg2))) "The type of the BODY is the type of the LEB") (check-not-exn (thunk (⊢m #'(def (def/2 (arg1 (Bar o (n m))) (arg2 (Foo o ())) (Bar o (n m))) arg2 arg1))) "The type of the BODY is the type of the LEB")))))) ;; P,Σ,Γ ⊢e E : t ;; ;; In context `P,Γ`, `E` elaborates to `?E` and has type `t` (define-rules ⊢e ;; [New] [(new ~! OT:ow-type) ;; Check P,Σ ⊢τ OT-TYPE #:when (⊢τ #'OT) ;; ---------------------------------------------------------------- ;; P,Σ,Γ ⊢e (new t) : t (add-τ this-syntax #'OT)] [ Local Access ] [ID:id Check ID ∈ dom(Γ ) #:when (or (Γ-member? #'ID) Unbound identifier . This is definitely not supposed ;; to happened thanks to both desugaring and simple type ;; check, but who knows ... (raise-syntax-error #f "unbound identifier" #'ID)) ;; ---------------------------------------------------------------- ;; P,Σ,Γ ⊢e ID : Γ(ID) (add-τ this-syntax (Γ-ref #'ID))] ;; [Field Access] ;; ;; Type checking example: ;; ;; (class Bar) ;; (class Foo{n} (field [bar : n/Bar])) ;; (get-field (new Foo{rep}) bar) ;; ~~~~~~~~~ ~~~~~~~~~~~~ ~~~ │ │ ╰ n / Bar from FS(t - e. TYPE . foo ) │ │ and t - e. TYPE is ;; │ │ │ ╰ world / Foo{rep } from P , Σ , Γ ⊢e E : t - e ;; │ ;; ╰ rep/Bar from the substitution of `n` ;; by `rep`. The substitution table ;; is Ψ(t-e) = { Θ -> world, n -> rep } ;; built using the t-e ownership scheme Θ / Foo{n } and ownership type world / Foo{rep } . ;; ;; Moreover we have to check the /static visibility/ of the `bar` ;; field in the context of the `(new Foo{rep})` expression. In other ;; words, is it OK for the expression `(new Foo{rep})` to access the ;; `bar` field. [(get-field ~! E FNAME) ;; Check P,Σ,Γ ⊢e E : t-e #:with [_ t-e:ow-type] (get-τ (⊢e #'E)) ;; σ = ψ(t-e) #:do [(define σ (curry env:σ (ψ #'t-e)))] ;; t-field = FS(t-e.TYPE . foo) ; Get the type of the field #:with t-field (FS-ref #'(t-e.TYPE . FNAME)) Check , t - field ) ;;;; Is expression `E` allowed to access field `FNAME`? #:when (or (visible? #'E #'t-field) (raise (mk-exn:visibility-error #'E #'FNAME #'t-field))) ;; ---------------------------------------------------------------- P , Σ , Γ ⊢e ( get - field E FNAME ) : σ(t - field ) (add-τ this-syntax (σ #'t-field))] ;; [Field Update] ;; ;; Type checking example: ;; ;; (class Bar) ;; (class Foo{n} (field [bar : n/Bar])) ;; (set-field (new Foo{rep}) bar (new rep/Bar)) ;; ~~~~~~~~~ ~~~~~~~~~~~~ ~~~ ~~~~~~~~~~~ ;; │ │ │ ╰ rep/Bar (*) │ │ ╰ n / Bar from FS(t - e. TYPE . foo ) │ │ and t - e. TYPE is ;; │ │ │ ╰ world / Foo{rep } from P , Σ , Γ ⊢e E : t - e ;; │ ;; ╰ rep/Bar from the substitution of `n` (†) ;; by `rep`. The substitution table ;; is Ψ(t-e) = { Θ -> world, n -> rep } ;; built using the t-e ownership scheme Θ / Foo{n } and ownership type world / Foo{rep } . ;; ;; Ensure that type (†) is equivalent to type (*). Intuitively, it ;; ensures that the BODY of the set-field fits into the field. ;; ;; Moreover we have to check the /static visibility/ of the `bar` ;; field in the context of the `(new Foo{rep})` expression. In other ;; words, is it OK for the expression `(new Foo{rep})` to access the ;; `bar` field. ;; [(set-field! ~! E FNAME BODY) ;; Check P,Σ,Γ ⊢e E t-e #:with [_ t-e:ow-type] (get-τ (⊢e #'E)) ;; σ = ψ(t-e) #:do [(define σ (curry env:σ (ψ #'t-e)))] ;; t-field = FS(t-e.TYPE . foo) ; Get the type of the field #:with t-field (FS-ref #'(t-e.TYPE . FNAME)) Check P , Σ , Γ ⊢e BODY : σ(t - field ) ;;;; The body as to elaborate into something that fit into the ;;;; field #:with [_ t-body] (get-τ (⊢e #'BODY)) #:when (or (τ=? #'t-body (σ #'t-field)) (raise (mk-exn:ownership-mismatch #'t-body (σ #'t-field) #'E))) Check , t - field ) ;;;; Is object of field `FNAME` visible to `E`? #:when (or (visible? #'E #'t-field) (raise (mk-exn:visibility-error #'E #'FNAME #'t-field))) ;; ---------------------------------------------------------------- P , Σ , Γ ⊢e ( set - field ( E : t - e ) FNAME BODY ) : σ(t - field ) (add-τ this-syntax (σ #'t-field))] ;; [Method Call] [(send ~! E DNAME PARAM ...) ;; Check P,Σ,Γ ⊢e E t-e #:with [_ t-e:ow-type] (get-τ (⊢e #'E)) ;; σ = ψ(t-e) #:do [(define σ (curry env:σ (ψ #'t-e)))] ;; t-arg ... → t-ret = DS(t-e.TYPE . foo) ; Get args and the return type of the def #:with [(t-arg ...) t-ret] (DS-ref #'(t-e.TYPE . DNAME)) Check P , Σ , Γ ⊢e ( : σ(t - arg ) ) ... ;;;; Expressions pass at `DNAME` call should fit into `DNAME` ;;;; arguments #:with [(ΘPARAM t-param) ...] (stx-map (∘ get-τ ⊢e) #'(PARAM ...)) #:when (stx-for/and ([t-param #'(t-param ...)] [t-arg #'(t-arg ...)] [param #'(ΘPARAM ...)]) (or (τ=? t-param (σ t-arg)) (raise (mk-exn:ownership-mismatch t-param (σ t-arg) param)))) Check , t - param ) ... ;;;; Are arguments pass to `DNAME` visible to `E`? An argument to ;;;; `DNAME` with a `rep` owner entails that such a argument can ;;;; only by accessed form the context of the `t-e.TYPE` ;;;; class. Therefore, we have to ensure that `E` in actually in ;;;; this context. ;;;; ;;;; To understand this check, imagine I have a method `def` that takes one argument of type ` rep / Foo ` . Going with such ;;;; argument is a specification that intuitively says that ;;;; "calling `def` implies to pass an argument from the context of ;;;; the current instance". I can built that argument using the ;;;; expression `(new rep/Foo)`. But, I have no clue in which ;;;; context I build that argument. To get in which context I ;;;; build that argument, I have to look at the caller expression ;;;; `E`. If `E` is `this`, for instance, then my `(new rep/Foo)` ;;;; is also from `this` that is the context of the current ;;;; instance. However, if `E` is something else, then my `(new ;;;; rep/Foo)` is built in another context henceforth results in a ;;;; visibility error. #:when (stx-for/and ([t-arg #'(t-arg ...)] [param #'(ΘPARAM ...)]) (or (visible? #'E t-arg) (raise (mk-exn:visibility-error-param #'E param t-arg)))) Check , t - field ) ;;;; Is object returned by `DNAME` visible to `E`? #:when (or (visible? #'E #'t-ret) (raise (mk-exn:visibility-error #'E #'DNAME #'t-ret))) ;; ---------------------------------------------------------------- Check P , Σ , Γ ⊢e ( send ( E : t ) DNAME PARAM ... ) : σ(t - ret ) (add-τ this-syntax (σ #'t-ret))] [ Local Update , Sequence ] ;; ;; Note: The [CPN98] does not rely on `let` binding for local ;; update, but instead something more imperative: `VAR-NAME = E`. ;; It also does not require the `VAR-NAME` to have a type, but ;; rather infers it from the expression (`E`). This is a bit ;; different here. Actually, I must say that I don't understand the ;; [Local Update] rule of [CPN98]. It requires `VAR-NAME` to be ;; bound as a premise, i.e., `VAR-NAME ∈ dom(Γ)`. That sounds weird ;; because no rules introduce `VAR-NAME` into `Γ`. The definition ;; of [Local Update] of [CPN98] sounds rather denotational than ;; operational. I would expect to find a kind of good definition in ;; [IPW01] for local update, but the expression surprisingly does ;; not contains a variable assignment. As a side note, this weird ;; definition really shows that the `let` notation is a must for ;; variable binding because it makes it clear that `VAR-NAME` is ;; bound in the `BODY`. [(let ~! (VAR-NAME VAR-OT E) BODY ...) ;; Check P,Σ ⊢τ VAR-OT #:when (⊢τ #'VAR-OT) ;; Check P,Σ,Γ ⊢e E : VAR-OT #:with [_ t] (get-τ (with-Γ (Γ-add #'(??? . VAR-OT)) (⊢e #'E))) #:when (or (τ=? #'t #'VAR-OT) (raise (mk-exn:ownership-mismatch #'t #'VAR-OT #'E))) ;; Check P,Σ,{VAR-NAME: VAR-OT, ...} ⊢e E ... LEB : t-leb #:with [_ ... LEB] (with-Γ (Γ-add #'(VAR-NAME . VAR-OT)) (stx-map ⊢e #'(BODY ...))) #:with [_ t-leb] (get-τ #'LEB) ;; ------------------------------------------------------------------ ;; P,Γ ⊢e let (VAR-NAME VAR-OW-TYPE E) BODY ... LEB : t-leb (add-τ this-syntax #'t-leb)]) (module+ test (define-test-suite ⊢e-parse ;; P,Σ,Γ ⊢e E : t (with-OWS (list (cons #'Foo #'(Foo Θ ())) (cons #'Bar #'(Bar Θ (ν μ)))) (with-FS (list (cons #'(Foo . rep/foo) #'(Foo rep ())) (cons #'(Foo . Θ/foo) #'(Foo Θ ())) (cons #'(Bar . bar) #'(Bar ν (μ μ)))) (with-DS (list (cons #'(Foo . rep-world/def/1) #'([(Foo rep ())] (Foo world ()))) (cons #'(Foo . world-rep/def/1) #'([(Foo world ())] (Foo rep ()))) (cons #'(Bar . def/0) #'([] (Foo rep ()))) (cons #'(Bar . def/2) #'([(Foo ν ()) (Bar ν (μ Θ))] (Bar world (ν ν))))) (with-Σ #'(n m o Θ) (with-Γ #'{ (this . (Foo Θ ())) } ;; [New] (new ~! OT:ow-type) ;; Check P,Σ ⊢τ OT-TYPE (check-exn exn:arity-error? (thunk (⊢e #'(new (Foo world (world)))))) (check-exn exn:unknown-cparam? (thunk (⊢e #'(new (Foo z ()))))) ;; P,Σ,Γ ⊢e (new t) : t (check-τ (⊢e #'(new (Foo o ()))) #'(Foo o ())) (check-τ (⊢e #'(new (Bar o (n m)))) #'(Bar o (n m))) ;; `rep` and `world` are valid universal context parameters ;; (universal in the sense that they don't have to be part of ;; Σ). (check-τ (⊢e #'(new (Foo rep ()))) #'(Foo rep ())) (check-τ (⊢e #'(new (Foo world ()))) #'(Foo world ())) [ Local Access ] ID Check ID ∈ dom(Γ ) (check-not-exn (thunk (⊢e #'this))) (check-exn exn:fail:syntax? (thunk (⊢e #'baz))) ;; P,Σ,Γ ⊢e ID : Γ(ID) (check-τ (⊢e #'this) #'(Foo Θ ())) ;; [Field Access] (get-field ~! E FNAME) Check , t - field ) (check-exn exn:visibility-error? (thunk (⊢e #'(get-field (new (Foo o ())) rep/foo)))) (check-exn exn:visibility-error? (thunk (⊢e #'(get-field (new (Foo world ())) rep/foo)))) ;;;; `rep` of `(new (Foo rep ()))` symbolize the root program ;;;; and so it different from the rep is the type of `rep/foo` which symbolize the instance of . It is quite logic then ;;;; that this expression raises a visibility error: The root ;;;; program is not allowed to access an inner information of an instance of . (check-exn exn:visibility-error? (thunk (⊢e #'(get-field (new (Foo rep ())) rep/foo)))) (check-not-exn (thunk (⊢e #'(get-field this rep/foo)))) P , Σ , Γ ⊢e ( get - field E FNAME ) : σ(t - field ) According to FS , class has one field Θ / foo of type Θ / Bar{n m } . Therefore , Θ is supposed to be substituted by ;;;; Foo owner. Generally speaking, Θ is always substituted by ;;;; the owner of caller expression. ;;;; > Θ/Foo{}::rep/foo is rep/Foo{} > Θ / Foo{}::Θ / foo is Θ / Foo { } (check-τ (⊢e #'(get-field this rep/foo)) #'(Foo rep ())) (check-τ (⊢e #'(get-field this Θ/foo)) #'(Foo Θ ())) (check-τ (⊢e #'(get-field (new (Foo o ())) Θ/foo)) #'(Foo o ())) (check-τ (⊢e #'(get-field (new (Foo rep ())) Θ/foo)) #'(Foo rep ())) (check-τ (⊢e #'(get-field (new (Foo world ())) Θ/foo)) #'(Foo world ())) ;;;; Θ/Bar{ν μ}::bar is ν/Bar{μ μ} (check-τ (⊢e #'(get-field (new (Bar o (rep world))) bar)) #'(Bar rep (world world))) (check-τ (⊢e #'(get-field (new (Bar rep (o n))) bar)) #'(Bar o (n n))) ;; [Field Update] (set-field! ~! E FNAME BODY) Check P , Σ , Γ ⊢e BODY : σ(t - field ) (check-exn exn:ownership-mismatch? (thunk (⊢e #'(set-field! (new (Foo rep ())) Θ/foo (new (Foo world ())))))) (check-exn exn:ownership-mismatch? (thunk (⊢e #'(set-field! (new (Foo o ())) Θ/foo (new (Foo m ())))))) (check-exn exn:ownership-mismatch? (thunk (⊢e #'(set-field! (new (Bar rep (o n))) bar (new (Bar o (n o))))))) Check , t - field ) (check-exn exn:visibility-error? (thunk (⊢e #'(set-field! (new (Foo rep ())) rep/foo (new (Foo rep ())))))) (check-not-exn (thunk (⊢e #'(set-field! this rep/foo (get-field this rep/foo))))) (check-not-exn (thunk (⊢e #'(set-field! this rep/foo (get-field (new (Foo rep ())) Θ/foo))))) P , Σ , Γ ⊢e ( set - field ( E : t - e ) FNAME BODY ) : σ(t - field ) (check-τ (⊢e #'(set-field! this rep/foo (get-field this rep/foo))) #'(Foo rep ())) (check-τ (⊢e #'(set-field! this Θ/foo this)) #'(Foo Θ ())) (check-τ (⊢e #'(set-field! (new (Foo o ())) Θ/foo (new (Foo o ())))) #'(Foo o ())) (check-τ (⊢e #'(set-field! (new (Foo rep ())) Θ/foo (new (Foo rep ())))) #'(Foo rep ())) (check-τ (⊢e #'(set-field! (new (Bar o (rep world))) bar (new (Bar rep (world world))))) #'(Bar rep (world world))) [ Method Call ] ( send ~ ! E ... ) (with-syntax ([new-bar #'(new (Bar o (rep world)))] [rep/arg #'(new (Foo rep ()))] [world/arg #'(new (Foo world ()))]) ;; Check P,Σ,Γ ⊢e E t-e Check P , Σ , Γ ⊢e ( : σ(t - arg ) ) ... ;;;; `new-bar` is of type `o/Bar{rep world}`. In this context, ;;;; `def/2` is of type ;;;; (: rep/Foo rep/Bar{world o} -> world/Bar{rep rep}) (check-exn exn:ownership-mismatch? (thunk (⊢e #'(send new-bar def/2 (new (Foo n ())) (new (Bar rep (world o)))))) "`n/Foo` mismatches with the expected `rep/Foo`") (check-exn exn:ownership-mismatch? (thunk (⊢e #'(send new-bar def/2 (new (Foo rep ())) (new (Bar n (world o)))))) "`n/Bar{world o}` mismatches with the expected `rep/Bar{world o}`") (check-exn exn:ownership-mismatch? (thunk (⊢e #'(send new-bar def/2 (new (Foo rep ())) (new (Bar rep (n o)))))) "`rep/Bar{n o}` mismatches with the expected `rep/Bar{world o}`") (check-exn exn:ownership-mismatch? (thunk (⊢e #'(send new-bar def/2 (new (Foo rep ())) (new (Bar rep (world n)))))) "`rep/Bar{world n}` mismatches with the expected `rep/Bar{world o}`") Check , t - param ) ... ;;;; rep-world/def/1 takes a rep/Foo argument (with rep means something in the context of ) , but here the rep comes ;;;; from the caller `(new (Foo rep ()))` that references ;;;; root... Therefore, the caller is not supposed to be ;;;; allowed to pass arguments to that method. (check-exn exn:visibility-error? (thunk (⊢e #'(send (new (Foo rep ())) rep-world/def/1 rep/arg)))) Check , t - field ) ;;;; world-rep/def/1 returns a rep/Foo value (with rep means something in the context of and is supposed to not go ;;;; out of that context). But here, I tried to access it using ;;;; the expression `(new (Foo rep ()))` which refers to the ;;;; context of root. Therefore the caller is not supposed to ;;;; be allowed to access this value. (check-exn exn:visibility-error? (thunk (⊢e #'(send (new (Foo rep ())) world-rep/def/1 world/arg)))) Check P , Σ , Γ ⊢e ( send ( E : t ) DNAME PARAM ... ) : σ(t - ret ) (check-τ (⊢e #'(send new-bar def/2 (new (Foo rep ())) (new (Bar rep (world o))))) #'(Bar world {rep rep}) "(: rep/Foo rep/Bar{world o} -> world/Bar{rep rep})") (check-τ (⊢e #'(send this rep-world/def/1 rep/arg)) #'(Foo world {}) "(: rep/Foo -> world/Foo)") (check-τ (⊢e #'(send this world-rep/def/1 world/arg)) #'(Foo rep {}) "(: world/Foo -> rep/Foo)")) [ Local Update , Sequence ] ( let ~ ! ( VAR - NAME VAR - OT E ) BODY ... ) ;; Check P,Σ ⊢τ VAR-OT (check-exn exn:arity-error? (thunk (⊢e #'(let (foo (Foo world {world}) _) _))) "type Foo does not have context parameters") (check-exn exn:unknown-cparam? (thunk (⊢e #'(let (foo (Foo z {}) _) _))) "Context parameter `z` is not part of Σ") ;; Check P,Σ,Γ ⊢e E : VAR-OT (τ=?) (check-exn exn:ownership-mismatch? (thunk (⊢e #'(let (foo (Foo rep {}) (new (Foo world {}))) _))) "foo expects a rep/Foo but a world/Foo was given") (check-exn exn:ownership-mismatch? (thunk (⊢e #'(let (bar (Bar o {n m}) (new (Bar o {m m}))) _))) "bar expects a o/Bar{n m} but a o/Bar{m m} was given") (check-exn exn:ownership-mismatch? (thunk (⊢e #'(let (bar (Bar o {n m}) (new (Bar o {n n}))) _))) "bar expects a o/Bar{n m} but a o/Bar{n n} was given") ;; Check P,Σ,{VAR-NAME: VAR-OT, ...} ⊢e E ... LEB : t-leb (check-not-exn (thunk (⊢e #'(let (foo (Foo Θ {}) this) foo)))) (check-not-exn (thunk (⊢e #'(let (foo (Foo Θ {}) ???) foo))) "A let binding accepts the `???` as expression") (check-not-exn (thunk (⊢e #'(let (foo (Foo rep {}) ???) foo))) "A let binding accepts the `???` as expression") ;; FIXME: ;; (check-not-exn (thunk (⊢e #'(let (bind-this (Foo Θ {}) this) ;; (get-field bind-this rep/foo)))) ;; "Binding this is still this") ;; P,Γ ⊢e let (VAR-NAME VAR-OW-TYPE E) BODY ... LEB : t-leb (check-τ (⊢e #'(let (foo (Foo rep {}) ???) foo)) #'(Foo rep {})) (check-τ (⊢e #'(let (foo (Foo rep {}) ???) this)) #'(Foo Θ {})) (check-τ (⊢e #'(let (foo (Foo rep {}) ???) this foo)) #'(Foo rep {})) (check-τ (⊢e #'(let (foo (Foo rep {}) ???) foo this)) #'(Foo Θ {})) (check-τ (⊢e #'(let (foo (Foo rep {}) ???) (let (foo (Bar o {n m}) ???) foo))) #'(Bar o {n m}) "Binding of inner let shadows the binding of outer let")))))))) ;; P,Σ ⊢τ t ;; ;; In context `P` and with local context parameters `Σ`, `t` is well ;; formed. ;; ;; [Type] (define-rules ⊢τ [t:ow-type #:with [CPARAM ...] #'t.CPARAMS ;; Check |{CPARAM ...}| = OWS(TYPE) ;;;; We provide enough context parameters for that class. For ;;;; whatever reason, this isn't checked in [CPN98]. #:when (let ([class-cparams-size (OWS-arity #'t.TYPE)] [type-cparams-size (length (syntax->list #'t.CPARAMS))]) (or (eq? class-cparams-size type-cparams-size) (raise (mk-exn:arity-error class-cparams-size type-cparams-size)))) ;; Check {OWNER CPARAM ...} ∈ Σ ∪ {rep world} #:when (with-Σ (Σ-union #'(rep world)) (stx-for/and ([cparam #'(t.OWNER CPARAM ...)]) (or (Σ-member? cparam) (raise (mk-exn:unknown-cparam cparam))))) ;; ------------------------------------------------------------------ ;; P,Σ ⊢τ (TYPE OWNER {CPARAM ...}) this-syntax]) (module+ test (define-test-suite ⊢τ-parse (with-OWS (list (cons #'Foo #'(Foo Θ ())) (cons #'Bar #'(Bar Θ (n m)))) (with-Σ #'(n m) (check-not-exn (thunk (⊢τ #'(Foo rep ())))) (check-not-exn (thunk (⊢τ #'(Foo world ())))) (check-not-exn (thunk (⊢τ #'(Foo n ())))) (check-not-exn (thunk (⊢τ #'(Foo m ())))) (check-not-exn (thunk (⊢τ #'(Bar rep (n n))))) (check-not-exn (thunk (⊢τ #'(Bar rep (n m))))) (check-not-exn (thunk (⊢τ #'(Bar rep (m n))))) (check-not-exn (thunk (⊢τ #'(Bar rep (rep rep))))) (check-not-exn (thunk (⊢τ #'(Bar rep (world world))))) (check-exn exn:arity-error? (thunk (⊢τ #'(Foo world (n))))) (check-exn exn:arity-error? (thunk (⊢τ #'(Bar world (n n n))))) (check-exn exn:unknown-cparam? (thunk (⊢τ #'(Foo o ())))) (check-exn exn:unknown-cparam? (thunk (⊢τ #'(Bar rep (rep o))))))))) Utils ;; (Syntaxof a) -> (Syntaxof (Pairof (Syntaxof a) OW-TYPE)) ;; ;; Note: I should raise a syntax error if the ow-type-prop is false . For sure , having a term with no type when it should have one ;; is an error that should stop the computation. (define (get-τ stx) (with-syntax ([the-stx stx] [τ-stx (ow-type-prop stx)]) #'(the-stx τ-stx))) ;; (Syntaxof a) OW-TYPE -> (Syntaxof a) (define add-τ ow-type-prop) ;; (: τ=? (OW-TYPE OW-TYPE -> Boolean)) (define (τ=? ot-stx1 ot-stx2) (def-ow-type-values (_ ot1.OWNER ot1.CPARAMs) ot-stx1) (def-ow-type-values (_ ot2.OWNER ot2.CPARAMs) ot-stx2) (and ;; Same owner (bound-id=? ot1.OWNER ot2.OWNER) ;; Same number of context parameters (eq? (length ot1.CPARAMs) (length ot2.CPARAMs)) ;; Same context parameters (for/and ([CPARAM1 (in-list ot1.CPARAMs)] [CPARAM2 (in-list ot2.CPARAMs)]) (bound-id=? CPARAM1 CPARAM2)))) ;; Static Visibility. ;; ;; Ensure statically that `E` refers to a `this` from the class ;; `OT.TYPE`. This implementation follows the definition of CPN98, ;; but it has few flaws. See tests for `visible?` below. ;; ;; (: visible? (Syntax OW-TYPE -> Boolean)) (define (visible? E OT) (def-ow-type-values (ot.TYPE ot.OWNER ot.CPARAMs) OT) All context parameters of ` OT ` (define ctx (cons ot.OWNER ot.CPARAMs)) ;; Is the current expression a `this`? (define-rules is-this? [this #t] [ID:id #f] [(new ~! _) #f] ;; Quid `get-field` return this? ;; TODO: check `E` of FNAME is `this` ;; And FS(E.ot.TYPE . FNAME).TYPE = t-field.TYPE ;;;; I've got the feeling that the only way for such stuff is true ;;;; is with `E` is `this`. [(get-field ~! E FNAME) #f] ;; Quid `set-field` return this? [(set-field! ~! E FNAME BODY) #f] ;; Quid `send` returns this? [(send ~! E DNAME PARAM ...) #f] ;; Let is `this` if the expressions returned by the let is `this`. ;; TODO: quid it returns a variable bind to `this`? [(let ~! (VAR-NAME VAR-OT E) BODY ... LEB) (is-this? #'LEB)] ;; By default it is false [_ #f]) ;; A ref is always visible to this. But only non `rep` references ;; could be visible to other expression. (if (is-this? E) #t (not (member #'rep ctx bound-id=?)))) (module+ test (define-test-suite utils (check-stx=? (get-τ (add-τ #'(Foo o ()) #'(Bar o (n m)))) #'((Foo o ()) (Bar o (n m)))) (check-stx=? (get-τ (add-τ (add-τ #'(Foo o ()) #'(Bar o (n m))) #'(Baz p (q r)))) #'((Foo o ()) (Baz p (q r)))) (check-stx=? (get-τ #'(Foo o ())) #'((Foo o ()) #f)) ;; type equality (check-true (τ=? #'(Foo o ()) #'(Foo o ()))) (check-true (τ=? #'(Foo o (n)) #'(Foo o (n)))) (check-true (τ=? #'(Foo o (n m)) #'(Foo o (n m)))) (check-true (τ=? #'(Foo o (n m)) #'(Foo o (n m)))) (check-true (τ=? #'(Foo o (n m)) #'(Bar o (n m))) "OT checking only cares of owner and context parameters") (check-false (τ=? #'(Foo o (n m)) #'(Foo t (n m))) "OT checks same owner") (check-false (τ=? #'(Foo o (n m)) #'(Foo o ())) "OT checks same number of context parameters") (check-false (τ=? #'(Foo o (n m)) #'(Foo o (n n))) "OT checks same context parameters") (check-false (τ=? #'(Foo o (n m)) #'(Foo o (m n))) "OT checks same context parameters") ;; Visibility (check-true (visible? #'_ #'(Foo o (n m))) "Foo is not rep so it is always visible") (check-false (visible? #'_ #'(Foo rep (n m))) "Foo is rep so is not visible by default") (check-true (visible? #'this #'(Foo rep (n m))) "rep is visible by this") ;; FIXME: ( check - true ( visible ? # ' ( let ( binder ( Foo Θ ( n m ) ) this ) binder ) # ' ( rep ( n m ) ) ) ;; "binding this is this") )) ;; Exceptions ;; Wrong number of context parameters (struct exn:arity-error exn:fail:syntax () #:transparent) ;; (: mk-exn:arity-error ((Identifier Integer) ([U Syntax #f]) . ->* . exn:arity-error)) (define (mk-exn:arity-error expected-cparam-size given-cparam-size [context #f]) (define CTX (or context (current-syntax-context))) (log-sclang-debug "Desugared syntax is ~.s" CTX) (define CTX-SURFACE (or (syntax-property CTX 'surface) CTX)) (log-sclang-debug "Surface syntax is ~.s" CTX-SURFACE) (define srcloc-msg (srcloc->string (build-source-location CTX-SURFACE))) (define id (format "~s" (extract-exp-name CTX))) (define err-msg "wrong number of context parameters") (define arity-msg (format (string-append "~n expected ~a, found ~a" "~n in: ~.s") expected-cparam-size given-cparam-size (syntax->datum CTX-SURFACE))) (exn:arity-error (string-append srcloc-msg ": " id ": " err-msg arity-msg) (current-continuation-marks) (list (syntax-taint CTX)))) ;; Unknown context parameter (struct exn:unknown-cparam exn:fail:syntax () #:transparent) ;; (: mk-exn:unknown-cparam ((Identifer) ([U Syntax #f]) . ->* . exn:unknown-cparam)) (define (mk-exn:unknown-cparam CPARAM [context #f]) (define CTX (or context (current-syntax-context))) (log-sclang-debug "Desugared syntax is ~.s" CTX) (define CTX-SURFACE (or (syntax-property CTX 'surface) CTX)) (log-sclang-debug "Surface syntax is ~.s" CTX-SURFACE) (define srcloc-msg (srcloc->string (build-source-location CPARAM))) (define id (format "~s" (syntax->datum CPARAM))) (define err-msg (format (string-append "unknown context parameter in this scope" "~n in: ~.s") (syntax->datum CTX-SURFACE))) (exn:unknown-cparam (string-append srcloc-msg ": " id ": " err-msg) (current-continuation-marks) (list (syntax-taint CPARAM)))) ;; Ownership mismatch at type checking (struct exn:ownership-mismatch exn:fail:syntax () #:transparent) ;; (: mk-exn:ownership-mismatch ;; ((OW-TYPE OW-TYPE) ;; ((U Syntax #f)) ;; . ->* . exn:owner-mismatch)) (define (mk-exn:ownership-mismatch GIVEN-OW-TYPE EXPECTED-OW-TYPE [context #f]) (define CTX (or context (current-syntax-context))) ( log - sclang - debug " Desugared syntax is ~.s " CTX ) (define CTX-SURFACE (or (syntax-property CTX 'surface) CTX)) ;; (log-sclang-debug "Surface syntax is ~.s" CTX-SURFACE) (define srcloc-msg (srcloc->string (build-source-location CTX-SURFACE))) (define id (format "~s" (extract-exp-name CTX-SURFACE))) (define err-msg "owner mismatch") (define elab-msg (format (string-append "~n The expression elaborate to the ownership ~s" "~n But the expected ownership is ~s, referring to declaration at ~a:~a" "~n in: ~.s") (syntax->datum GIVEN-OW-TYPE) (syntax->datum EXPECTED-OW-TYPE) (syntax-line EXPECTED-OW-TYPE) (syntax-column EXPECTED-OW-TYPE) (syntax->datum CTX-SURFACE))) (exn:ownership-mismatch (string-append srcloc-msg ": " id ": " err-msg elab-msg) (current-continuation-marks) (list (syntax-taint CTX)))) ;; Visibility error of an expression (struct exn:visibility-error exn:fail:syntax () #:transparent) ;; (: mk-exn:visibility-error ;; ((Syntax Syntax OW-TYPE) ;; ((U Syntax #f)) ;; . ->* . exn:visibility-error)) (define (mk-exn:visibility-error E OW-E OW-TYPE [context #f]) (define CTX (or context (current-syntax-context))) ( log - sclang - debug " Desugared syntax is ~.s " CTX ) (define CTX-SURFACE (or (syntax-property CTX 'surface) CTX)) ;; (log-sclang-debug "Surface syntax is ~.s" CTX-SURFACE) (define srcloc-msg (srcloc->string (build-source-location CTX-SURFACE))) (define id (format "~s" (extract-exp-name CTX-SURFACE))) (define err-msg "visibility error") (define visibility-msg (format (string-append "~n The expression is not allowed to access value of ~.s of type ~s" "~n This value belongs to ~.s instance and cannot be accessed outside of it" "~n in: ~.s") (syntax->datum (or (syntax-property OW-E 'surface) OW-E)) (syntax->datum (or (syntax-property OW-TYPE 'surface) OW-TYPE)) (syntax->datum (or (syntax-property E 'surface) E)) (syntax->datum CTX-SURFACE))) (exn:visibility-error (string-append srcloc-msg ": " id ": " err-msg visibility-msg) (current-continuation-marks) (list (syntax-taint CTX)))) ;; Visibility error of an expression (struct exn:visibility-error-param exn:visibility-error () #:transparent) ;; (: mk-exn:visibility-error-param ;; ((Syntax Syntax OW-TYPE) ;; ((U Syntax #f)) ;; . ->* . exn:visibility-error)) (define (mk-exn:visibility-error-param E OW-E OW-TYPE [context #f]) (define CTX (or context (current-syntax-context))) ( log - sclang - debug " Desugared syntax is ~.s " CTX ) (define CTX-SURFACE (or (syntax-property CTX 'surface) CTX)) ;; (log-sclang-debug "Surface syntax is ~.s" CTX-SURFACE) (define srcloc-msg (srcloc->string (build-source-location CTX-SURFACE))) (define id (format "~s" (extract-exp-name CTX-SURFACE))) (define err-msg "visibility error") (define visibility-msg (format (string-append "~n The expression required an argument of type ~s that belongs to ~.s instance" "~n However the value of ~.s belongs to another context" "~n in: ~.s") (syntax->datum (or (syntax-property OW-TYPE 'surface) OW-TYPE)) (syntax->datum (or (syntax-property E 'surface) E)) (syntax->datum (or (syntax-property OW-E 'surface) OW-E)) (syntax->datum CTX-SURFACE))) (exn:visibility-error (string-append srcloc-msg ": " id ": " err-msg visibility-msg) (current-continuation-marks) (list (syntax-taint CTX)))) ;; Tests (module+ test (require rackunit/text-ui (prefix-in env: (submod "env.rkt" ownership test))) (define-check (check-τ stx ow-type) (define stx-type (syntax-parse (get-τ stx) [(_ t) #'t])) (with-check-info* (list (make-check-name 'check-τ) (make-check-location (build-source-location-list stx)) (make-check-actual stx-type) (make-check-expected ow-type)) (thunk (with-handlers ([exn:arity-error? fail] [exn:unknown-cparam? fail]) (check-true (τ=? stx-type ow-type)))))) (run-tests (test-suite "Ownership checking phase" ;; Check env env:Σ-tests env:Γ-tests env:OWS-tests env:FS-tests env:DS-tests ;; Check utils utils ;; Check phase rules ⊢τ-parse ⊢e-parse ⊢m-parse ⊢d-parse))) ;; Bibliography ;; ;; @InProceedings{CPN98, author = { and and } , ;; title = {Ownership Types for Flexible Alias Protection}, booktitle = { Proceedings of the 1998 { ACM } { SIGPLAN } Conference on Object - Oriented Programming Systems , Languages { \ & } Applications { ( OOPSLA } ' 98 ) , Vancouver , British Columbia , Canada , October 18 - 22 , 1998 . } , pages = { 48 - -64 } , year = { 1998 } , ;; doi = {10.1145/286936.286947} ;; url = {}, ;; } ;; ;; @Article{IPW01, author = { and and } , title = { : a minimal core calculus for Java ;; and GJ}, journal = { ACM Trans . Program . Lang . Syst . } , volume = 23 , number = 3 , ;; year = 2001, pages = { 396 - 450 } , ;; ee = {}, bibsource = { DBLP , -trier.de } ;; }
null
https://raw.githubusercontent.com/rcherrueau/APE/8b5302709000bd043b64d46d55642acb34ce5ba7/racket/CPN98/ownership.rkt
racket
,-,-,-. `,| | | ,-. . . ,-. ,-. . . ,-. ,-. | ; | . ,-| | | | ,-| | | | | | ' `-' `-^ `-^ `-' `-^ `-^ `-' `-' Ownership Types Checker. Ownership type checking phase (Θ>) - Type checks the program (for simple type -- "simple" as in simply typed λ calculus, i.e., no ownership). - Based on [CPN98] (see Bibliography). Environments: Phase θ> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Env Set of local context parameters Mapping from locally bound variables to ownership types (: Γ (Identifier ~> O-TYPE)) Store of the ownership scheme of the current class Mapping from existing class types to its ownership scheme (t ~> t^) (: OWS (TYPE ~> OW-TYPE)) Map of fields Class type Field name Field return type Map of definitions (: DS ((Syntaxof (Pairof Identifier ; Class type Identifier)) ; Def name ~> Type of def args return type ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ⊢p P : t `P` is well-formed with ownership type `t` [program] Check P ⊢d CLASS Check P,[],[] ⊢e E : t ---------------------------------------------------------------- ⊢p P : t P ⊢d CLASS In context `P`, `CLASS` is well-formed [Class] Σ = { Θ } ∪ { CPARAM ... } τ = OWS(NAME) (i.e., `#'(NAME Θ [CPARAM ...])`) The `Θ` means `owner`. Check P,Σ ⊢τ t on fields Check P,Σ,{ this: NAME<Θ|[CPARAM ...]> } ⊢m DEF Note: Unlike [CPN98], I chose to go with an environment for the current class ownership scheme (τ), rather than binding the `this` in `Γ` here, so I don't have to latter implement an union operation for `Γ`. ---------------------------------------------------------------- P ⊢d (class NAME [CPARAM ...] FIELD ... DEF ...) P ⊢d CLASS Check P,Σ ⊢τ t on fields Check P,Σ,{ this: NAME<Θ|[CPARAM ...]> } ⊢m DEF [(def ~! (_NAME (ARG-NAME ARG-OT) ... RET-OT) E ...+) P,Σ,τ ⊢m DEF In context `P,Σ,τ`, `DEF` is well-formed [Method] Get current class type store in τ environment Check P,Σ ⊢τ t on return type Check P,Σ ⊢τ t on args Check P,Σ,{this: τ0, ARG-NAME: ARG-OT, ...} ⊢e E ... LEB : RET-OT ---------------------------------------------------------------- P,Σ,τ ⊢m DEF Check P,Σ ⊢τ t on return type Check P,Σ ⊢τ t on args Check P,Σ,{this: τ0, ARG-NAME: ARG-OT, ...} ⊢e E ... LEB : RET-OT P,Σ,Γ ⊢e E : t In context `P,Γ`, `E` elaborates to `?E` and has type `t` [New] Check P,Σ ⊢τ OT-TYPE ---------------------------------------------------------------- P,Σ,Γ ⊢e (new t) : t to happened thanks to both desugaring and simple type check, but who knows ... ---------------------------------------------------------------- P,Σ,Γ ⊢e ID : Γ(ID) [Field Access] Type checking example: (class Bar) (class Foo{n} (field [bar : n/Bar])) (get-field (new Foo{rep}) bar) ~~~~~~~~~ ~~~~~~~~~~~~ ~~~ │ │ │ ╰ rep/Bar from the substitution of `n` by `rep`. The substitution table is Ψ(t-e) = { Θ -> world, n -> rep } built using the t-e ownership scheme Moreover we have to check the /static visibility/ of the `bar` field in the context of the `(new Foo{rep})` expression. In other words, is it OK for the expression `(new Foo{rep})` to access the `bar` field. Check P,Σ,Γ ⊢e E : t-e σ = ψ(t-e) t-field = FS(t-e.TYPE . foo) ; Get the type of the field Is expression `E` allowed to access field `FNAME`? ---------------------------------------------------------------- [Field Update] Type checking example: (class Bar) (class Foo{n} (field [bar : n/Bar])) (set-field (new Foo{rep}) bar (new rep/Bar)) ~~~~~~~~~ ~~~~~~~~~~~~ ~~~ ~~~~~~~~~~~ │ │ │ ╰ rep/Bar (*) │ │ │ ╰ rep/Bar from the substitution of `n` (†) by `rep`. The substitution table is Ψ(t-e) = { Θ -> world, n -> rep } built using the t-e ownership scheme Ensure that type (†) is equivalent to type (*). Intuitively, it ensures that the BODY of the set-field fits into the field. Moreover we have to check the /static visibility/ of the `bar` field in the context of the `(new Foo{rep})` expression. In other words, is it OK for the expression `(new Foo{rep})` to access the `bar` field. Check P,Σ,Γ ⊢e E t-e σ = ψ(t-e) t-field = FS(t-e.TYPE . foo) ; Get the type of the field The body as to elaborate into something that fit into the field Is object of field `FNAME` visible to `E`? ---------------------------------------------------------------- [Method Call] Check P,Σ,Γ ⊢e E t-e σ = ψ(t-e) t-arg ... → t-ret = DS(t-e.TYPE . foo) ; Get args and the return type of the def Expressions pass at `DNAME` call should fit into `DNAME` arguments Are arguments pass to `DNAME` visible to `E`? An argument to `DNAME` with a `rep` owner entails that such a argument can only by accessed form the context of the `t-e.TYPE` class. Therefore, we have to ensure that `E` in actually in this context. To understand this check, imagine I have a method `def` that argument is a specification that intuitively says that "calling `def` implies to pass an argument from the context of the current instance". I can built that argument using the expression `(new rep/Foo)`. But, I have no clue in which context I build that argument. To get in which context I build that argument, I have to look at the caller expression `E`. If `E` is `this`, for instance, then my `(new rep/Foo)` is also from `this` that is the context of the current instance. However, if `E` is something else, then my `(new rep/Foo)` is built in another context henceforth results in a visibility error. Is object returned by `DNAME` visible to `E`? ---------------------------------------------------------------- Note: The [CPN98] does not rely on `let` binding for local update, but instead something more imperative: `VAR-NAME = E`. It also does not require the `VAR-NAME` to have a type, but rather infers it from the expression (`E`). This is a bit different here. Actually, I must say that I don't understand the [Local Update] rule of [CPN98]. It requires `VAR-NAME` to be bound as a premise, i.e., `VAR-NAME ∈ dom(Γ)`. That sounds weird because no rules introduce `VAR-NAME` into `Γ`. The definition of [Local Update] of [CPN98] sounds rather denotational than operational. I would expect to find a kind of good definition in [IPW01] for local update, but the expression surprisingly does not contains a variable assignment. As a side note, this weird definition really shows that the `let` notation is a must for variable binding because it makes it clear that `VAR-NAME` is bound in the `BODY`. Check P,Σ ⊢τ VAR-OT Check P,Σ,Γ ⊢e E : VAR-OT Check P,Σ,{VAR-NAME: VAR-OT, ...} ⊢e E ... LEB : t-leb ------------------------------------------------------------------ P,Γ ⊢e let (VAR-NAME VAR-OW-TYPE E) BODY ... LEB : t-leb P,Σ,Γ ⊢e E : t [New] (new ~! OT:ow-type) Check P,Σ ⊢τ OT-TYPE P,Σ,Γ ⊢e (new t) : t `rep` and `world` are valid universal context parameters (universal in the sense that they don't have to be part of Σ). P,Σ,Γ ⊢e ID : Γ(ID) [Field Access] (get-field ~! E FNAME) `rep` of `(new (Foo rep ()))` symbolize the root program and so it different from the rep is the type of `rep/foo` that this expression raises a visibility error: The root program is not allowed to access an inner information of an Foo owner. Generally speaking, Θ is always substituted by the owner of caller expression. > Θ/Foo{}::rep/foo is rep/Foo{} Θ/Bar{ν μ}::bar is ν/Bar{μ μ} [Field Update] (set-field! ~! E FNAME BODY) Check P,Σ,Γ ⊢e E t-e `new-bar` is of type `o/Bar{rep world}`. In this context, `def/2` is of type (: rep/Foo rep/Bar{world o} -> world/Bar{rep rep}) rep-world/def/1 takes a rep/Foo argument (with rep means from the caller `(new (Foo rep ()))` that references root... Therefore, the caller is not supposed to be allowed to pass arguments to that method. world-rep/def/1 returns a rep/Foo value (with rep means out of that context). But here, I tried to access it using the expression `(new (Foo rep ()))` which refers to the context of root. Therefore the caller is not supposed to be allowed to access this value. Check P,Σ ⊢τ VAR-OT Check P,Σ,Γ ⊢e E : VAR-OT (τ=?) Check P,Σ,{VAR-NAME: VAR-OT, ...} ⊢e E ... LEB : t-leb FIXME: (check-not-exn (thunk (⊢e #'(let (bind-this (Foo Θ {}) this) (get-field bind-this rep/foo)))) "Binding this is still this") P,Γ ⊢e let (VAR-NAME VAR-OW-TYPE E) BODY ... LEB : t-leb P,Σ ⊢τ t In context `P` and with local context parameters `Σ`, `t` is well formed. [Type] Check |{CPARAM ...}| = OWS(TYPE) We provide enough context parameters for that class. For whatever reason, this isn't checked in [CPN98]. Check {OWNER CPARAM ...} ∈ Σ ∪ {rep world} ------------------------------------------------------------------ P,Σ ⊢τ (TYPE OWNER {CPARAM ...}) (Syntaxof a) -> (Syntaxof (Pairof (Syntaxof a) OW-TYPE)) Note: I should raise a syntax error if the ow-type-prop is is an error that should stop the computation. (Syntaxof a) OW-TYPE -> (Syntaxof a) (: τ=? (OW-TYPE OW-TYPE -> Boolean)) Same owner Same number of context parameters Same context parameters Static Visibility. Ensure statically that `E` refers to a `this` from the class `OT.TYPE`. This implementation follows the definition of CPN98, but it has few flaws. See tests for `visible?` below. (: visible? (Syntax OW-TYPE -> Boolean)) Is the current expression a `this`? Quid `get-field` return this? TODO: check `E` of FNAME is `this` And FS(E.ot.TYPE . FNAME).TYPE = t-field.TYPE I've got the feeling that the only way for such stuff is true is with `E` is `this`. Quid `set-field` return this? Quid `send` returns this? Let is `this` if the expressions returned by the let is `this`. TODO: quid it returns a variable bind to `this`? By default it is false A ref is always visible to this. But only non `rep` references could be visible to other expression. type equality Visibility FIXME: "binding this is this") Exceptions Wrong number of context parameters (: mk-exn:arity-error ((Identifier Integer) ([U Syntax #f]) . ->* . exn:arity-error)) Unknown context parameter (: mk-exn:unknown-cparam ((Identifer) ([U Syntax #f]) . ->* . exn:unknown-cparam)) Ownership mismatch at type checking (: mk-exn:ownership-mismatch ((OW-TYPE OW-TYPE) ((U Syntax #f)) . ->* . exn:owner-mismatch)) (log-sclang-debug "Surface syntax is ~.s" CTX-SURFACE) Visibility error of an expression (: mk-exn:visibility-error ((Syntax Syntax OW-TYPE) ((U Syntax #f)) . ->* . exn:visibility-error)) (log-sclang-debug "Surface syntax is ~.s" CTX-SURFACE) Visibility error of an expression (: mk-exn:visibility-error-param ((Syntax Syntax OW-TYPE) ((U Syntax #f)) . ->* . exn:visibility-error)) (log-sclang-debug "Surface syntax is ~.s" CTX-SURFACE) Tests Check env Check utils Check phase rules Bibliography @InProceedings{CPN98, title = {Ownership Types for Flexible Alias Protection}, doi = {10.1145/286936.286947} url = {}, } @Article{IPW01, and GJ}, year = 2001, ee = {}, }
#lang racket/base (require (for-syntax racket/base) racket/function racket/match racket/sequence racket/syntax syntax/parse syntax/srcloc syntax/stx "definitions.rkt" "utils.rkt" "meta.rkt" (prefix-in env: (submod "env.rkt" ownership))) (module+ test (require rackunit)) (provide Θ>) (define-phase (Θ> stx meta:CS meta:FS meta:DS) (: ( Setof Identifier ) ) (Σ #:init '() #:mk env:make-Σ #:apply? [env:Σ-member? env:Σ-union]) (Γ #:init '() #:mk env:make-Γ #:apply? [env:Γ-member? env:Γ-add env:Γ-ref]) (: τ OW - TYPE ) (τ #:init #'Bottom #:mk identity) (OWS #:init (meta-map-w/key (λ (kv) (match-define (cons CTYPE CPARAM...) kv) (cons CTYPE #`(#,CTYPE Θ #,CPARAM...))) meta:CS) #:mk env:make-OWS #:apply? [env:OWS-arity env:OWS-ref env:ψ]) (FS #:init meta:FS #:mk env:make-FS #:apply? [env:FS-member? env:FS-ref]) (DS #:init (meta-map-w/key (λ (kv) (match-let* ([`(,DS-key . ,RET-OWS) kv] [`(,CTYPE ,DNAME ,ARG-OWS...) (syntax-e DS-key)]) (cons #`(#,CTYPE . #,DNAME) #`(#,ARG-OWS... #,RET-OWS)))) meta:DS) #:mk env:make-DS #:apply? [env:DS-member? env:DS-ref]) Parse (⊢p stx)) (define-rules ⊢p [((import _ ...) CLASS ... E) #:do [(stx-map ⊢d #'(CLASS ...))] #:with [_ t] (get-τ (with-Σ '() (with-Γ '() (⊢e #'E)))) (add-τ this-syntax #'t)]) (define-rules ⊢d [(class ~! NAME [CPARAM ...] FIELD/DEF ...) #:with [FIELD ...] (filter field? (stx->list #'(FIELD/DEF ...))) #:with [DEF ...] (filter def? (stx->list #'(FIELD/DEF ...))) #:do [(define the-Σ #'(Θ CPARAM ...)) (define the-τ (OWS-ref #'NAME))] #:with [(field ~! F-NAME F) ...] #'(FIELD ...) #:when (with-Σ the-Σ (stx-for/and ([t #'(F ...)]) (⊢τ t))) #:when (with-Σ the-Σ (with-τ the-τ (stx-map ⊢m #'(DEF ...)))) this-syntax]) (module+ test (define-test-suite ⊢d-parse (with-OWS (list (cons #'Foo #'(Foo Θ ()))) (check-exn exn:arity-error? (thunk (⊢d #'(class Foo [] (field foo (Foo rep {rep}))))) "`Foo` does not takes context parameters") (check-exn exn:unknown-cparam? (thunk (⊢d #'(class Foo [] (field foo (Foo o {}))))) "`The context parameter `o` has not been introduced") (check-not-exn (thunk (⊢d #'(class Foo [] (field foo (Foo rep {})))))) (check-not-exn (thunk (⊢d #'(class Foo [] (field foo (Foo world {})))))) (check-not-exn (thunk (⊢d #'(class Foo [o] (field foo (Foo o {})))))) (check-not-exn (thunk (⊢d #'(class Foo [] (def (def/0 (Foo Θ ())) this)))) "`this` is of type `Θ/Foo` in `def`")))) (define-rules ⊢m [(def ~! (_NAME (ARG-NAME ARG-OT) ... RET-OT) E ...+) #:with τ0 (τ) #:when (⊢τ #'RET-OT) #:when (stx-for/and ([t #'(ARG-OT ...)]) (⊢τ t)) #:with [_ ... ΘLEB] (with-Γ #'{ (this . τ0) (??? . RET-OT) (ARG-NAME . ARG-OT) ... } (stx-map ⊢e #'(E ...))) #:with [_ t-e] (get-τ #'ΘLEB) #:when (or (τ=? #'t-e #'RET-OT) (raise (mk-exn:ownership-mismatch #'t-e #'RET-OT #'ΘLEB))) P , Σ , τ0 ⊢m ( def ( NAME ( ARG - NAME ARG - OT ) ... RET - OT ) E ... + ) this-syntax]) (module+ test (define-test-suite ⊢m-parse (with-OWS (list (cons #'Foo #'(Foo Θ ())) (cons #'Bar #'(Bar Θ (n m)))) (with-Σ #'(Θ o n m) (with-τ #'(Foo o ()) (check-exn exn:unknown-cparam? (thunk (⊢m #'(def (def/0 (Bar o (n t))) _))) "`t` is not a defined context parameter") (check-exn exn:arity-error? (thunk (⊢m #'(def (def/2 (Bar o (n))) _))) "`Bar` takes two context parameters") (check-exn exn:arity-error? (thunk (⊢m #'(def (def/2 (Bar o (n n n))) _))) "`Bar` takes two context parameters") (check-exn exn:unknown-cparam? (thunk (⊢m #'(def (def/2 (arg1 (Foo o ())) (arg2 (Bar o (n t))) (Bar o (n m))) _))) "`t` is not a defined context parameter") (check-exn exn:unknown-cparam? (thunk (⊢m #'(def (def/2 (arg1 (Foo t ())) (arg2 (Bar o (n m))) (Bar o (n m))) _))) "`t` is not a defined context parameter") (check-exn exn:arity-error? (thunk (⊢m #'(def (def/2 (arg1 (Foo o ())) (arg2 (Bar o (n))) (Bar o (n m))) _))) "`Bar` takes two context parameters") (check-exn exn:arity-error? (thunk (⊢m #'(def (def/2 (arg1 (Foo o ())) (arg2 (Bar o (n n n))) (Bar o (n m))) _))) "`Bar` takes two context parameters") (check-exn exn:ownership-mismatch? (thunk (⊢m #'(def (def/0 (Bar o (n m))) (new (Bar n (n m)))))) "`def` should return a `o/Bar{n m}` but the expression is of type `n/Bar{n m}`") (check-exn exn:ownership-mismatch? (thunk (⊢m #'(def (def/0 (Bar o (n m))) (new (Bar o (m m)))))) "`def` should return a `o/Bar{n m}` but the expression is of type `n/Bar{m m}`") (check-not-exn (thunk (⊢m #'(def (def/0 (Foo o ())) this))) "`this` is bound in the expression with the `Foo` type (τ env)") (check-not-exn (thunk (⊢m #'(def (def/0 (Foo o ())) ???))) "A def accepts the `???` place holder as expression" ) (check-not-exn (thunk (⊢m #'(def (def/0 (Bar o (n m))) ???))) "A def accepts the `???` place holder as expression" ) (check-not-exn (thunk (⊢m #'(def (def/2 (arg1 (Bar o (n m))) (arg2 (Foo o ())) (Bar o (n m))) arg1))) "`arg1` is bound in the expression with the `o/Bar{n m}` type") (check-not-exn (thunk (⊢m #'(def (def/2 (arg1 (Bar o (n m))) (arg2 (Foo o ())) (Foo o ())) arg2))) "`arg2` is bound in the expression with the `o/Foo` type") (check-not-exn (thunk (⊢m #'(def (def/2 (arg1 (Bar o (n m))) (arg2 (Foo o ())) (Foo o ())) arg1 arg2))) "The type of the BODY is the type of the LEB") (check-not-exn (thunk (⊢m #'(def (def/2 (arg1 (Bar o (n m))) (arg2 (Foo o ())) (Bar o (n m))) arg2 arg1))) "The type of the BODY is the type of the LEB")))))) (define-rules ⊢e [(new ~! OT:ow-type) #:when (⊢τ #'OT) (add-τ this-syntax #'OT)] [ Local Access ] [ID:id Check ID ∈ dom(Γ ) #:when (or (Γ-member? #'ID) Unbound identifier . This is definitely not supposed (raise-syntax-error #f "unbound identifier" #'ID)) (add-τ this-syntax (Γ-ref #'ID))] │ │ ╰ n / Bar from FS(t - e. TYPE . foo ) │ │ and t - e. TYPE is │ ╰ world / Foo{rep } from P , Σ , Γ ⊢e E : t - e Θ / Foo{n } and ownership type world / Foo{rep } . [(get-field ~! E FNAME) #:with [_ t-e:ow-type] (get-τ (⊢e #'E)) #:do [(define σ (curry env:σ (ψ #'t-e)))] #:with t-field (FS-ref #'(t-e.TYPE . FNAME)) Check , t - field ) #:when (or (visible? #'E #'t-field) (raise (mk-exn:visibility-error #'E #'FNAME #'t-field))) P , Σ , Γ ⊢e ( get - field E FNAME ) : σ(t - field ) (add-τ this-syntax (σ #'t-field))] │ │ ╰ n / Bar from FS(t - e. TYPE . foo ) │ │ and t - e. TYPE is │ ╰ world / Foo{rep } from P , Σ , Γ ⊢e E : t - e Θ / Foo{n } and ownership type world / Foo{rep } . [(set-field! ~! E FNAME BODY) #:with [_ t-e:ow-type] (get-τ (⊢e #'E)) #:do [(define σ (curry env:σ (ψ #'t-e)))] #:with t-field (FS-ref #'(t-e.TYPE . FNAME)) Check P , Σ , Γ ⊢e BODY : σ(t - field ) #:with [_ t-body] (get-τ (⊢e #'BODY)) #:when (or (τ=? #'t-body (σ #'t-field)) (raise (mk-exn:ownership-mismatch #'t-body (σ #'t-field) #'E))) Check , t - field ) #:when (or (visible? #'E #'t-field) (raise (mk-exn:visibility-error #'E #'FNAME #'t-field))) P , Σ , Γ ⊢e ( set - field ( E : t - e ) FNAME BODY ) : σ(t - field ) (add-τ this-syntax (σ #'t-field))] [(send ~! E DNAME PARAM ...) #:with [_ t-e:ow-type] (get-τ (⊢e #'E)) #:do [(define σ (curry env:σ (ψ #'t-e)))] #:with [(t-arg ...) t-ret] (DS-ref #'(t-e.TYPE . DNAME)) Check P , Σ , Γ ⊢e ( : σ(t - arg ) ) ... #:with [(ΘPARAM t-param) ...] (stx-map (∘ get-τ ⊢e) #'(PARAM ...)) #:when (stx-for/and ([t-param #'(t-param ...)] [t-arg #'(t-arg ...)] [param #'(ΘPARAM ...)]) (or (τ=? t-param (σ t-arg)) (raise (mk-exn:ownership-mismatch t-param (σ t-arg) param)))) Check , t - param ) ... takes one argument of type ` rep / Foo ` . Going with such #:when (stx-for/and ([t-arg #'(t-arg ...)] [param #'(ΘPARAM ...)]) (or (visible? #'E t-arg) (raise (mk-exn:visibility-error-param #'E param t-arg)))) Check , t - field ) #:when (or (visible? #'E #'t-ret) (raise (mk-exn:visibility-error #'E #'DNAME #'t-ret))) Check P , Σ , Γ ⊢e ( send ( E : t ) DNAME PARAM ... ) : σ(t - ret ) (add-τ this-syntax (σ #'t-ret))] [ Local Update , Sequence ] [(let ~! (VAR-NAME VAR-OT E) BODY ...) #:when (⊢τ #'VAR-OT) #:with [_ t] (get-τ (with-Γ (Γ-add #'(??? . VAR-OT)) (⊢e #'E))) #:when (or (τ=? #'t #'VAR-OT) (raise (mk-exn:ownership-mismatch #'t #'VAR-OT #'E))) #:with [_ ... LEB] (with-Γ (Γ-add #'(VAR-NAME . VAR-OT)) (stx-map ⊢e #'(BODY ...))) #:with [_ t-leb] (get-τ #'LEB) (add-τ this-syntax #'t-leb)]) (module+ test (define-test-suite ⊢e-parse (with-OWS (list (cons #'Foo #'(Foo Θ ())) (cons #'Bar #'(Bar Θ (ν μ)))) (with-FS (list (cons #'(Foo . rep/foo) #'(Foo rep ())) (cons #'(Foo . Θ/foo) #'(Foo Θ ())) (cons #'(Bar . bar) #'(Bar ν (μ μ)))) (with-DS (list (cons #'(Foo . rep-world/def/1) #'([(Foo rep ())] (Foo world ()))) (cons #'(Foo . world-rep/def/1) #'([(Foo world ())] (Foo rep ()))) (cons #'(Bar . def/0) #'([] (Foo rep ()))) (cons #'(Bar . def/2) #'([(Foo ν ()) (Bar ν (μ Θ))] (Bar world (ν ν))))) (with-Σ #'(n m o Θ) (with-Γ #'{ (this . (Foo Θ ())) } (check-exn exn:arity-error? (thunk (⊢e #'(new (Foo world (world)))))) (check-exn exn:unknown-cparam? (thunk (⊢e #'(new (Foo z ()))))) (check-τ (⊢e #'(new (Foo o ()))) #'(Foo o ())) (check-τ (⊢e #'(new (Bar o (n m)))) #'(Bar o (n m))) (check-τ (⊢e #'(new (Foo rep ()))) #'(Foo rep ())) (check-τ (⊢e #'(new (Foo world ()))) #'(Foo world ())) [ Local Access ] ID Check ID ∈ dom(Γ ) (check-not-exn (thunk (⊢e #'this))) (check-exn exn:fail:syntax? (thunk (⊢e #'baz))) (check-τ (⊢e #'this) #'(Foo Θ ())) Check , t - field ) (check-exn exn:visibility-error? (thunk (⊢e #'(get-field (new (Foo o ())) rep/foo)))) (check-exn exn:visibility-error? (thunk (⊢e #'(get-field (new (Foo world ())) rep/foo)))) which symbolize the instance of . It is quite logic then instance of . (check-exn exn:visibility-error? (thunk (⊢e #'(get-field (new (Foo rep ())) rep/foo)))) (check-not-exn (thunk (⊢e #'(get-field this rep/foo)))) P , Σ , Γ ⊢e ( get - field E FNAME ) : σ(t - field ) According to FS , class has one field Θ / foo of type Θ / Bar{n m } . Therefore , Θ is supposed to be substituted by > Θ / Foo{}::Θ / foo is Θ / Foo { } (check-τ (⊢e #'(get-field this rep/foo)) #'(Foo rep ())) (check-τ (⊢e #'(get-field this Θ/foo)) #'(Foo Θ ())) (check-τ (⊢e #'(get-field (new (Foo o ())) Θ/foo)) #'(Foo o ())) (check-τ (⊢e #'(get-field (new (Foo rep ())) Θ/foo)) #'(Foo rep ())) (check-τ (⊢e #'(get-field (new (Foo world ())) Θ/foo)) #'(Foo world ())) (check-τ (⊢e #'(get-field (new (Bar o (rep world))) bar)) #'(Bar rep (world world))) (check-τ (⊢e #'(get-field (new (Bar rep (o n))) bar)) #'(Bar o (n n))) Check P , Σ , Γ ⊢e BODY : σ(t - field ) (check-exn exn:ownership-mismatch? (thunk (⊢e #'(set-field! (new (Foo rep ())) Θ/foo (new (Foo world ())))))) (check-exn exn:ownership-mismatch? (thunk (⊢e #'(set-field! (new (Foo o ())) Θ/foo (new (Foo m ())))))) (check-exn exn:ownership-mismatch? (thunk (⊢e #'(set-field! (new (Bar rep (o n))) bar (new (Bar o (n o))))))) Check , t - field ) (check-exn exn:visibility-error? (thunk (⊢e #'(set-field! (new (Foo rep ())) rep/foo (new (Foo rep ())))))) (check-not-exn (thunk (⊢e #'(set-field! this rep/foo (get-field this rep/foo))))) (check-not-exn (thunk (⊢e #'(set-field! this rep/foo (get-field (new (Foo rep ())) Θ/foo))))) P , Σ , Γ ⊢e ( set - field ( E : t - e ) FNAME BODY ) : σ(t - field ) (check-τ (⊢e #'(set-field! this rep/foo (get-field this rep/foo))) #'(Foo rep ())) (check-τ (⊢e #'(set-field! this Θ/foo this)) #'(Foo Θ ())) (check-τ (⊢e #'(set-field! (new (Foo o ())) Θ/foo (new (Foo o ())))) #'(Foo o ())) (check-τ (⊢e #'(set-field! (new (Foo rep ())) Θ/foo (new (Foo rep ())))) #'(Foo rep ())) (check-τ (⊢e #'(set-field! (new (Bar o (rep world))) bar (new (Bar rep (world world))))) #'(Bar rep (world world))) [ Method Call ] ( send ~ ! E ... ) (with-syntax ([new-bar #'(new (Bar o (rep world)))] [rep/arg #'(new (Foo rep ()))] [world/arg #'(new (Foo world ()))]) Check P , Σ , Γ ⊢e ( : σ(t - arg ) ) ... (check-exn exn:ownership-mismatch? (thunk (⊢e #'(send new-bar def/2 (new (Foo n ())) (new (Bar rep (world o)))))) "`n/Foo` mismatches with the expected `rep/Foo`") (check-exn exn:ownership-mismatch? (thunk (⊢e #'(send new-bar def/2 (new (Foo rep ())) (new (Bar n (world o)))))) "`n/Bar{world o}` mismatches with the expected `rep/Bar{world o}`") (check-exn exn:ownership-mismatch? (thunk (⊢e #'(send new-bar def/2 (new (Foo rep ())) (new (Bar rep (n o)))))) "`rep/Bar{n o}` mismatches with the expected `rep/Bar{world o}`") (check-exn exn:ownership-mismatch? (thunk (⊢e #'(send new-bar def/2 (new (Foo rep ())) (new (Bar rep (world n)))))) "`rep/Bar{world n}` mismatches with the expected `rep/Bar{world o}`") Check , t - param ) ... something in the context of ) , but here the rep comes (check-exn exn:visibility-error? (thunk (⊢e #'(send (new (Foo rep ())) rep-world/def/1 rep/arg)))) Check , t - field ) something in the context of and is supposed to not go (check-exn exn:visibility-error? (thunk (⊢e #'(send (new (Foo rep ())) world-rep/def/1 world/arg)))) Check P , Σ , Γ ⊢e ( send ( E : t ) DNAME PARAM ... ) : σ(t - ret ) (check-τ (⊢e #'(send new-bar def/2 (new (Foo rep ())) (new (Bar rep (world o))))) #'(Bar world {rep rep}) "(: rep/Foo rep/Bar{world o} -> world/Bar{rep rep})") (check-τ (⊢e #'(send this rep-world/def/1 rep/arg)) #'(Foo world {}) "(: rep/Foo -> world/Foo)") (check-τ (⊢e #'(send this world-rep/def/1 world/arg)) #'(Foo rep {}) "(: world/Foo -> rep/Foo)")) [ Local Update , Sequence ] ( let ~ ! ( VAR - NAME VAR - OT E ) BODY ... ) (check-exn exn:arity-error? (thunk (⊢e #'(let (foo (Foo world {world}) _) _))) "type Foo does not have context parameters") (check-exn exn:unknown-cparam? (thunk (⊢e #'(let (foo (Foo z {}) _) _))) "Context parameter `z` is not part of Σ") (check-exn exn:ownership-mismatch? (thunk (⊢e #'(let (foo (Foo rep {}) (new (Foo world {}))) _))) "foo expects a rep/Foo but a world/Foo was given") (check-exn exn:ownership-mismatch? (thunk (⊢e #'(let (bar (Bar o {n m}) (new (Bar o {m m}))) _))) "bar expects a o/Bar{n m} but a o/Bar{m m} was given") (check-exn exn:ownership-mismatch? (thunk (⊢e #'(let (bar (Bar o {n m}) (new (Bar o {n n}))) _))) "bar expects a o/Bar{n m} but a o/Bar{n n} was given") (check-not-exn (thunk (⊢e #'(let (foo (Foo Θ {}) this) foo)))) (check-not-exn (thunk (⊢e #'(let (foo (Foo Θ {}) ???) foo))) "A let binding accepts the `???` as expression") (check-not-exn (thunk (⊢e #'(let (foo (Foo rep {}) ???) foo))) "A let binding accepts the `???` as expression") (check-τ (⊢e #'(let (foo (Foo rep {}) ???) foo)) #'(Foo rep {})) (check-τ (⊢e #'(let (foo (Foo rep {}) ???) this)) #'(Foo Θ {})) (check-τ (⊢e #'(let (foo (Foo rep {}) ???) this foo)) #'(Foo rep {})) (check-τ (⊢e #'(let (foo (Foo rep {}) ???) foo this)) #'(Foo Θ {})) (check-τ (⊢e #'(let (foo (Foo rep {}) ???) (let (foo (Bar o {n m}) ???) foo))) #'(Bar o {n m}) "Binding of inner let shadows the binding of outer let")))))))) (define-rules ⊢τ [t:ow-type #:with [CPARAM ...] #'t.CPARAMS #:when (let ([class-cparams-size (OWS-arity #'t.TYPE)] [type-cparams-size (length (syntax->list #'t.CPARAMS))]) (or (eq? class-cparams-size type-cparams-size) (raise (mk-exn:arity-error class-cparams-size type-cparams-size)))) #:when (with-Σ (Σ-union #'(rep world)) (stx-for/and ([cparam #'(t.OWNER CPARAM ...)]) (or (Σ-member? cparam) (raise (mk-exn:unknown-cparam cparam))))) this-syntax]) (module+ test (define-test-suite ⊢τ-parse (with-OWS (list (cons #'Foo #'(Foo Θ ())) (cons #'Bar #'(Bar Θ (n m)))) (with-Σ #'(n m) (check-not-exn (thunk (⊢τ #'(Foo rep ())))) (check-not-exn (thunk (⊢τ #'(Foo world ())))) (check-not-exn (thunk (⊢τ #'(Foo n ())))) (check-not-exn (thunk (⊢τ #'(Foo m ())))) (check-not-exn (thunk (⊢τ #'(Bar rep (n n))))) (check-not-exn (thunk (⊢τ #'(Bar rep (n m))))) (check-not-exn (thunk (⊢τ #'(Bar rep (m n))))) (check-not-exn (thunk (⊢τ #'(Bar rep (rep rep))))) (check-not-exn (thunk (⊢τ #'(Bar rep (world world))))) (check-exn exn:arity-error? (thunk (⊢τ #'(Foo world (n))))) (check-exn exn:arity-error? (thunk (⊢τ #'(Bar world (n n n))))) (check-exn exn:unknown-cparam? (thunk (⊢τ #'(Foo o ())))) (check-exn exn:unknown-cparam? (thunk (⊢τ #'(Bar rep (rep o))))))))) Utils false . For sure , having a term with no type when it should have one (define (get-τ stx) (with-syntax ([the-stx stx] [τ-stx (ow-type-prop stx)]) #'(the-stx τ-stx))) (define add-τ ow-type-prop) (define (τ=? ot-stx1 ot-stx2) (def-ow-type-values (_ ot1.OWNER ot1.CPARAMs) ot-stx1) (def-ow-type-values (_ ot2.OWNER ot2.CPARAMs) ot-stx2) (and (bound-id=? ot1.OWNER ot2.OWNER) (eq? (length ot1.CPARAMs) (length ot2.CPARAMs)) (for/and ([CPARAM1 (in-list ot1.CPARAMs)] [CPARAM2 (in-list ot2.CPARAMs)]) (bound-id=? CPARAM1 CPARAM2)))) (define (visible? E OT) (def-ow-type-values (ot.TYPE ot.OWNER ot.CPARAMs) OT) All context parameters of ` OT ` (define ctx (cons ot.OWNER ot.CPARAMs)) (define-rules is-this? [this #t] [ID:id #f] [(new ~! _) #f] [(get-field ~! E FNAME) #f] [(set-field! ~! E FNAME BODY) #f] [(send ~! E DNAME PARAM ...) #f] [(let ~! (VAR-NAME VAR-OT E) BODY ... LEB) (is-this? #'LEB)] [_ #f]) (if (is-this? E) #t (not (member #'rep ctx bound-id=?)))) (module+ test (define-test-suite utils (check-stx=? (get-τ (add-τ #'(Foo o ()) #'(Bar o (n m)))) #'((Foo o ()) (Bar o (n m)))) (check-stx=? (get-τ (add-τ (add-τ #'(Foo o ()) #'(Bar o (n m))) #'(Baz p (q r)))) #'((Foo o ()) (Baz p (q r)))) (check-stx=? (get-τ #'(Foo o ())) #'((Foo o ()) #f)) (check-true (τ=? #'(Foo o ()) #'(Foo o ()))) (check-true (τ=? #'(Foo o (n)) #'(Foo o (n)))) (check-true (τ=? #'(Foo o (n m)) #'(Foo o (n m)))) (check-true (τ=? #'(Foo o (n m)) #'(Foo o (n m)))) (check-true (τ=? #'(Foo o (n m)) #'(Bar o (n m))) "OT checking only cares of owner and context parameters") (check-false (τ=? #'(Foo o (n m)) #'(Foo t (n m))) "OT checks same owner") (check-false (τ=? #'(Foo o (n m)) #'(Foo o ())) "OT checks same number of context parameters") (check-false (τ=? #'(Foo o (n m)) #'(Foo o (n n))) "OT checks same context parameters") (check-false (τ=? #'(Foo o (n m)) #'(Foo o (m n))) "OT checks same context parameters") (check-true (visible? #'_ #'(Foo o (n m))) "Foo is not rep so it is always visible") (check-false (visible? #'_ #'(Foo rep (n m))) "Foo is rep so is not visible by default") (check-true (visible? #'this #'(Foo rep (n m))) "rep is visible by this") ( check - true ( visible ? # ' ( let ( binder ( Foo Θ ( n m ) ) this ) binder ) # ' ( rep ( n m ) ) ) )) (struct exn:arity-error exn:fail:syntax () #:transparent) (define (mk-exn:arity-error expected-cparam-size given-cparam-size [context #f]) (define CTX (or context (current-syntax-context))) (log-sclang-debug "Desugared syntax is ~.s" CTX) (define CTX-SURFACE (or (syntax-property CTX 'surface) CTX)) (log-sclang-debug "Surface syntax is ~.s" CTX-SURFACE) (define srcloc-msg (srcloc->string (build-source-location CTX-SURFACE))) (define id (format "~s" (extract-exp-name CTX))) (define err-msg "wrong number of context parameters") (define arity-msg (format (string-append "~n expected ~a, found ~a" "~n in: ~.s") expected-cparam-size given-cparam-size (syntax->datum CTX-SURFACE))) (exn:arity-error (string-append srcloc-msg ": " id ": " err-msg arity-msg) (current-continuation-marks) (list (syntax-taint CTX)))) (struct exn:unknown-cparam exn:fail:syntax () #:transparent) (define (mk-exn:unknown-cparam CPARAM [context #f]) (define CTX (or context (current-syntax-context))) (log-sclang-debug "Desugared syntax is ~.s" CTX) (define CTX-SURFACE (or (syntax-property CTX 'surface) CTX)) (log-sclang-debug "Surface syntax is ~.s" CTX-SURFACE) (define srcloc-msg (srcloc->string (build-source-location CPARAM))) (define id (format "~s" (syntax->datum CPARAM))) (define err-msg (format (string-append "unknown context parameter in this scope" "~n in: ~.s") (syntax->datum CTX-SURFACE))) (exn:unknown-cparam (string-append srcloc-msg ": " id ": " err-msg) (current-continuation-marks) (list (syntax-taint CPARAM)))) (struct exn:ownership-mismatch exn:fail:syntax () #:transparent) (define (mk-exn:ownership-mismatch GIVEN-OW-TYPE EXPECTED-OW-TYPE [context #f]) (define CTX (or context (current-syntax-context))) ( log - sclang - debug " Desugared syntax is ~.s " CTX ) (define CTX-SURFACE (or (syntax-property CTX 'surface) CTX)) (define srcloc-msg (srcloc->string (build-source-location CTX-SURFACE))) (define id (format "~s" (extract-exp-name CTX-SURFACE))) (define err-msg "owner mismatch") (define elab-msg (format (string-append "~n The expression elaborate to the ownership ~s" "~n But the expected ownership is ~s, referring to declaration at ~a:~a" "~n in: ~.s") (syntax->datum GIVEN-OW-TYPE) (syntax->datum EXPECTED-OW-TYPE) (syntax-line EXPECTED-OW-TYPE) (syntax-column EXPECTED-OW-TYPE) (syntax->datum CTX-SURFACE))) (exn:ownership-mismatch (string-append srcloc-msg ": " id ": " err-msg elab-msg) (current-continuation-marks) (list (syntax-taint CTX)))) (struct exn:visibility-error exn:fail:syntax () #:transparent) (define (mk-exn:visibility-error E OW-E OW-TYPE [context #f]) (define CTX (or context (current-syntax-context))) ( log - sclang - debug " Desugared syntax is ~.s " CTX ) (define CTX-SURFACE (or (syntax-property CTX 'surface) CTX)) (define srcloc-msg (srcloc->string (build-source-location CTX-SURFACE))) (define id (format "~s" (extract-exp-name CTX-SURFACE))) (define err-msg "visibility error") (define visibility-msg (format (string-append "~n The expression is not allowed to access value of ~.s of type ~s" "~n This value belongs to ~.s instance and cannot be accessed outside of it" "~n in: ~.s") (syntax->datum (or (syntax-property OW-E 'surface) OW-E)) (syntax->datum (or (syntax-property OW-TYPE 'surface) OW-TYPE)) (syntax->datum (or (syntax-property E 'surface) E)) (syntax->datum CTX-SURFACE))) (exn:visibility-error (string-append srcloc-msg ": " id ": " err-msg visibility-msg) (current-continuation-marks) (list (syntax-taint CTX)))) (struct exn:visibility-error-param exn:visibility-error () #:transparent) (define (mk-exn:visibility-error-param E OW-E OW-TYPE [context #f]) (define CTX (or context (current-syntax-context))) ( log - sclang - debug " Desugared syntax is ~.s " CTX ) (define CTX-SURFACE (or (syntax-property CTX 'surface) CTX)) (define srcloc-msg (srcloc->string (build-source-location CTX-SURFACE))) (define id (format "~s" (extract-exp-name CTX-SURFACE))) (define err-msg "visibility error") (define visibility-msg (format (string-append "~n The expression required an argument of type ~s that belongs to ~.s instance" "~n However the value of ~.s belongs to another context" "~n in: ~.s") (syntax->datum (or (syntax-property OW-TYPE 'surface) OW-TYPE)) (syntax->datum (or (syntax-property E 'surface) E)) (syntax->datum (or (syntax-property OW-E 'surface) OW-E)) (syntax->datum CTX-SURFACE))) (exn:visibility-error (string-append srcloc-msg ": " id ": " err-msg visibility-msg) (current-continuation-marks) (list (syntax-taint CTX)))) (module+ test (require rackunit/text-ui (prefix-in env: (submod "env.rkt" ownership test))) (define-check (check-τ stx ow-type) (define stx-type (syntax-parse (get-τ stx) [(_ t) #'t])) (with-check-info* (list (make-check-name 'check-τ) (make-check-location (build-source-location-list stx)) (make-check-actual stx-type) (make-check-expected ow-type)) (thunk (with-handlers ([exn:arity-error? fail] [exn:unknown-cparam? fail]) (check-true (τ=? stx-type ow-type)))))) (run-tests (test-suite "Ownership checking phase" env:Σ-tests env:Γ-tests env:OWS-tests env:FS-tests env:DS-tests utils ⊢τ-parse ⊢e-parse ⊢m-parse ⊢d-parse))) author = { and and } , booktitle = { Proceedings of the 1998 { ACM } { SIGPLAN } Conference on Object - Oriented Programming Systems , Languages { \ & } Applications { ( OOPSLA } ' 98 ) , Vancouver , British Columbia , Canada , October 18 - 22 , 1998 . } , pages = { 48 - -64 } , year = { 1998 } , author = { and and } , title = { : a minimal core calculus for Java journal = { ACM Trans . Program . Lang . Syst . } , volume = 23 , number = 3 , pages = { 396 - 450 } , bibsource = { DBLP , -trier.de }
46813bb9bf980df76cabe041c0ec57047f0e42cd7d9c3bc47e779b59e46878a4
cljfx/cljfx
views.clj
(ns e18-pure-event-handling.views (:require [cljfx.api :as fx] [e18-pure-event-handling.subs :as subs] [e18-pure-event-handling.events :as events] [clojure.java.io :as io]) (:import [org.jsoup.nodes Element] [org.jsoup Jsoup])) (defn- loading [_] {:fx/type :h-box :alignment :center :children [{:fx/type :progress-indicator}]}) (defn- exception [{:keys [fx/context]}] (let [{:keys [url exception]} (fx/sub-ctx context subs/current-response)] {:fx/type :v-box :alignment :center :children [{:fx/type :label :text (str "Can't load url: " url)} {:fx/type :label :text (or (ex-message exception) (str (class exception)))}]})) (defn- jsoup->clj [^Element jsoup-el] (let [attrs (into {} (map (fn [[k v]] [(keyword k) v])) (.attributes jsoup-el))] {:tag (keyword (.tagName jsoup-el)) :attrs attrs :children (mapv jsoup->clj (.children jsoup-el))})) (defn- ->tree-item [x] {:fx/type :tree-item :expanded true :value x :children (map ->tree-item (:children x))}) (defn- html [{:keys [tree]}] {:fx/type :tree-view :cell-factory {:fx/cell-type :tree-cell :describe (fn [{:keys [tag attrs]}] {:text (str [tag attrs])})} :root (->tree-item tree)}) (defn- result [{:keys [fx/context]}] (let [request-id (fx/sub-ctx context subs/current-request-id) content-type (fx/sub-ctx context subs/context-type request-id) ^bytes body (fx/sub-ctx context subs/body request-id)] (case content-type "text/html" {:fx/type html :tree (jsoup->clj (Jsoup/parse (String. body)))} "text/plain" {:fx/type :scroll-pane :fit-to-width true :content {:fx/type :label :wrap-text true :text (String. body)}} ("image/png" "image/jpeg") {:fx/type :scroll-pane :fit-to-width true :fit-to-height true :content {:fx/type :v-box :alignment :center :children [{:fx/type :image-view :image {:is (io/input-stream body)}}]}} {:fx/type :scroll-pane :fit-to-width true :content {:fx/type :label :wrap-text true :text (str content-type ": " (String. body))}}))) (defn current-page [{:keys [fx/context]}] (case (:result (fx/sub-ctx context subs/current-response)) :pending {:fx/type loading} :success {:fx/type result} :failure {:fx/type exception} nil {:fx/type :region})) (defn toolbar [{:keys [fx/context]}] {:fx/type :h-box :spacing 10 :children [{:fx/type :button :text "Back" :disable (fx/sub-ctx context subs/history-empty?) :on-action {:event/type ::events/go-back}} {:fx/type :text-field :h-box/hgrow :always :text (fx/sub-val context :typed-url) :on-text-changed {:event/type ::events/type-url :fx/sync true} :on-key-pressed {:event/type ::events/key-press-url}}]}) (defn root [_] {:fx/type :stage :width 960 :height 540 :showing true :scene {:fx/type :scene :root {:fx/type :v-box :padding 10 :spacing 10 :children [{:fx/type toolbar} {:fx/type current-page :v-box/vgrow :always}]}}})
null
https://raw.githubusercontent.com/cljfx/cljfx/ec3c34e619b2408026b9f2e2ff8665bebf70bf56/examples/e18_pure_event_handling/views.clj
clojure
(ns e18-pure-event-handling.views (:require [cljfx.api :as fx] [e18-pure-event-handling.subs :as subs] [e18-pure-event-handling.events :as events] [clojure.java.io :as io]) (:import [org.jsoup.nodes Element] [org.jsoup Jsoup])) (defn- loading [_] {:fx/type :h-box :alignment :center :children [{:fx/type :progress-indicator}]}) (defn- exception [{:keys [fx/context]}] (let [{:keys [url exception]} (fx/sub-ctx context subs/current-response)] {:fx/type :v-box :alignment :center :children [{:fx/type :label :text (str "Can't load url: " url)} {:fx/type :label :text (or (ex-message exception) (str (class exception)))}]})) (defn- jsoup->clj [^Element jsoup-el] (let [attrs (into {} (map (fn [[k v]] [(keyword k) v])) (.attributes jsoup-el))] {:tag (keyword (.tagName jsoup-el)) :attrs attrs :children (mapv jsoup->clj (.children jsoup-el))})) (defn- ->tree-item [x] {:fx/type :tree-item :expanded true :value x :children (map ->tree-item (:children x))}) (defn- html [{:keys [tree]}] {:fx/type :tree-view :cell-factory {:fx/cell-type :tree-cell :describe (fn [{:keys [tag attrs]}] {:text (str [tag attrs])})} :root (->tree-item tree)}) (defn- result [{:keys [fx/context]}] (let [request-id (fx/sub-ctx context subs/current-request-id) content-type (fx/sub-ctx context subs/context-type request-id) ^bytes body (fx/sub-ctx context subs/body request-id)] (case content-type "text/html" {:fx/type html :tree (jsoup->clj (Jsoup/parse (String. body)))} "text/plain" {:fx/type :scroll-pane :fit-to-width true :content {:fx/type :label :wrap-text true :text (String. body)}} ("image/png" "image/jpeg") {:fx/type :scroll-pane :fit-to-width true :fit-to-height true :content {:fx/type :v-box :alignment :center :children [{:fx/type :image-view :image {:is (io/input-stream body)}}]}} {:fx/type :scroll-pane :fit-to-width true :content {:fx/type :label :wrap-text true :text (str content-type ": " (String. body))}}))) (defn current-page [{:keys [fx/context]}] (case (:result (fx/sub-ctx context subs/current-response)) :pending {:fx/type loading} :success {:fx/type result} :failure {:fx/type exception} nil {:fx/type :region})) (defn toolbar [{:keys [fx/context]}] {:fx/type :h-box :spacing 10 :children [{:fx/type :button :text "Back" :disable (fx/sub-ctx context subs/history-empty?) :on-action {:event/type ::events/go-back}} {:fx/type :text-field :h-box/hgrow :always :text (fx/sub-val context :typed-url) :on-text-changed {:event/type ::events/type-url :fx/sync true} :on-key-pressed {:event/type ::events/key-press-url}}]}) (defn root [_] {:fx/type :stage :width 960 :height 540 :showing true :scene {:fx/type :scene :root {:fx/type :v-box :padding 10 :spacing 10 :children [{:fx/type toolbar} {:fx/type current-page :v-box/vgrow :always}]}}})
8c0f1b05d6e5f3fe5c39d5912a4db551d1ff1a505882e0f8599312a07fee33ce
cstar/ejabberd-old
ejabberd_loglevel.erl
%%%---------------------------------------------------------------------- %%% File : ejabberd_loglevel.erl Author : < > Purpose : Loglevel switcher . %%% Be careful: you should not have any ejabberd_logger module %%% as ejabberd_loglevel switcher is compiling and loading %%% dynamically a "virtual" ejabberd_logger module (Described %%% in a string at the end of this module). Created : 29 Nov 2006 by < > %%% %%% ejabberd , Copyright ( C ) 2002 - 2010 ProcessOne %%% %%% This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the %%% License, or (at your option) any later version. %%% %%% This program is distributed in the hope that it will be useful, %%% but WITHOUT ANY WARRANTY; without even the implied warranty of %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU %%% General Public License for more details. %%% You should have received a copy of the GNU General Public License %%% along with this program; if not, write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA %%% %%%---------------------------------------------------------------------- -module(ejabberd_loglevel). -author(''). -export([set/1, get/0]). -include("ejabberd.hrl"). -define(LOGMODULE, "error_logger"). %% Error levels: -define(LOG_LEVELS,[ {0, no_log, "No log"} ,{1, critical, "Critical"} ,{2, error, "Error"} ,{3, warning, "Warning"} ,{4, info, "Info"} ,{5, debug, "Debug"} ]). get() -> Level = ejabberd_logger:get(), case lists:keysearch(Level, 1, ?LOG_LEVELS) of {value, Result} -> Result; _ -> erlang:error({no_such_loglevel, Level}) end. set(LogLevel) when is_atom(LogLevel) -> set(level_to_integer(LogLevel)); set(Loglevel) when is_integer(Loglevel) -> try {Mod,Code} = dynamic_compile:from_string(ejabberd_logger_src(Loglevel)), code:load_binary(Mod, ?LOGMODULE ++ ".erl", Code) catch Type:Error -> ?CRITICAL_MSG("Error compiling logger (~p): ~p~n", [Type, Error]) end; set(_) -> exit("Loglevel must be an integer"). level_to_integer(Level) -> case lists:keysearch(Level, 2, ?LOG_LEVELS) of {value, {Int, Level, _Desc}} -> Int; _ -> erlang:error({no_such_loglevel, Level}) end. %% -------------------------------------------------------------- %% Code of the ejabberd logger, dynamically compiled and loaded %% This allows to dynamically change log level while keeping a %% very efficient code. ejabberd_logger_src(Loglevel) -> L = integer_to_list(Loglevel), "-module(ejabberd_logger). -author(''). -export([debug_msg/4, info_msg/4, warning_msg/4, error_msg/4, critical_msg/4, get/0]). get() -> "++ L ++". %% Helper functions debug_msg(Module, Line, Format, Args) when " ++ L ++ " >= 5 -> notify(info_msg, \"D(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); debug_msg(_,_,_,_) -> ok. info_msg(Module, Line, Format, Args) when " ++ L ++ " >= 4 -> notify(info_msg, \"I(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); info_msg(_,_,_,_) -> ok. warning_msg(Module, Line, Format, Args) when " ++ L ++ " >= 3 -> notify(error, \"W(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); warning_msg(_,_,_,_) -> ok. error_msg(Module, Line, Format, Args) when " ++ L ++ " >= 2 -> notify(error, \"E(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); error_msg(_,_,_,_) -> ok. critical_msg(Module, Line, Format, Args) when " ++ L ++ " >= 1 -> notify(error, \"C(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); critical_msg(_,_,_,_) -> ok. Distribute the message to the Erlang error logger notify(Type, Format, Args) -> LoggerMsg = {Type, group_leader(), {self(), Format, Args}}, gen_event:notify(error_logger, LoggerMsg). ".
null
https://raw.githubusercontent.com/cstar/ejabberd-old/559f8b6b0a935710fe93e9afacb4270d6d6ea00f/src/ejabberd_loglevel.erl
erlang
---------------------------------------------------------------------- File : ejabberd_loglevel.erl Be careful: you should not have any ejabberd_logger module as ejabberd_loglevel switcher is compiling and loading dynamically a "virtual" ejabberd_logger module (Described in a string at the end of this module). This program is free software; you can redistribute it and/or License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program; if not, write to the Free Software ---------------------------------------------------------------------- Error levels: -------------------------------------------------------------- Code of the ejabberd logger, dynamically compiled and loaded This allows to dynamically change log level while keeping a very efficient code. Helper functions
Author : < > Purpose : Loglevel switcher . Created : 29 Nov 2006 by < > ejabberd , Copyright ( C ) 2002 - 2010 ProcessOne modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the You should have received a copy of the GNU General Public License Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA -module(ejabberd_loglevel). -author(''). -export([set/1, get/0]). -include("ejabberd.hrl"). -define(LOGMODULE, "error_logger"). -define(LOG_LEVELS,[ {0, no_log, "No log"} ,{1, critical, "Critical"} ,{2, error, "Error"} ,{3, warning, "Warning"} ,{4, info, "Info"} ,{5, debug, "Debug"} ]). get() -> Level = ejabberd_logger:get(), case lists:keysearch(Level, 1, ?LOG_LEVELS) of {value, Result} -> Result; _ -> erlang:error({no_such_loglevel, Level}) end. set(LogLevel) when is_atom(LogLevel) -> set(level_to_integer(LogLevel)); set(Loglevel) when is_integer(Loglevel) -> try {Mod,Code} = dynamic_compile:from_string(ejabberd_logger_src(Loglevel)), code:load_binary(Mod, ?LOGMODULE ++ ".erl", Code) catch Type:Error -> ?CRITICAL_MSG("Error compiling logger (~p): ~p~n", [Type, Error]) end; set(_) -> exit("Loglevel must be an integer"). level_to_integer(Level) -> case lists:keysearch(Level, 2, ?LOG_LEVELS) of {value, {Int, Level, _Desc}} -> Int; _ -> erlang:error({no_such_loglevel, Level}) end. ejabberd_logger_src(Loglevel) -> L = integer_to_list(Loglevel), "-module(ejabberd_logger). -author(''). -export([debug_msg/4, info_msg/4, warning_msg/4, error_msg/4, critical_msg/4, get/0]). get() -> "++ L ++". debug_msg(Module, Line, Format, Args) when " ++ L ++ " >= 5 -> notify(info_msg, \"D(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); debug_msg(_,_,_,_) -> ok. info_msg(Module, Line, Format, Args) when " ++ L ++ " >= 4 -> notify(info_msg, \"I(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); info_msg(_,_,_,_) -> ok. warning_msg(Module, Line, Format, Args) when " ++ L ++ " >= 3 -> notify(error, \"W(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); warning_msg(_,_,_,_) -> ok. error_msg(Module, Line, Format, Args) when " ++ L ++ " >= 2 -> notify(error, \"E(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); error_msg(_,_,_,_) -> ok. critical_msg(Module, Line, Format, Args) when " ++ L ++ " >= 1 -> notify(error, \"C(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); critical_msg(_,_,_,_) -> ok. Distribute the message to the Erlang error logger notify(Type, Format, Args) -> LoggerMsg = {Type, group_leader(), {self(), Format, Args}}, gen_event:notify(error_logger, LoggerMsg). ".
0de2379b5d9dfd7227f74a2d3829d3f536b4c55fa483ace9e3a8f516f5e36218
mput/sicp-solutions
2_04.rkt
#lang racket Solution for exercise 2_04 . (require rackunit "../solutions/utils.rkt") (provide n-cons n-car n-cdr) (define (n-cons x y) (lambda (m) (m x y))) (define (n-car pair) (pair (lambda (p q) p))) Воспользуемся методом подстановки , данной реализации пар : ( define testpair ( n - cons 1 2 ) ) #| (n-car testpair) |# #| (testpair (lambda (p q) p)) |# ( ( lambda ( m ) ( m 1 2 ) ) ( lambda ( p q ) p ) ) ( ( lambda ( p q ) p ) 1 2 ) 1 Из этого вытекает довольно очевидная реализация : (define (n-cdr pair) (pair (lambda (p q) q)))
null
https://raw.githubusercontent.com/mput/sicp-solutions/fe12ad2b6f17c99978c8fe04b2495005986b8496/solutions/2_04.rkt
racket
(n-car testpair) (testpair (lambda (p q) p))
#lang racket Solution for exercise 2_04 . (require rackunit "../solutions/utils.rkt") (provide n-cons n-car n-cdr) (define (n-cons x y) (lambda (m) (m x y))) (define (n-car pair) (pair (lambda (p q) p))) Воспользуемся методом подстановки , данной реализации пар : ( define testpair ( n - cons 1 2 ) ) ( ( lambda ( m ) ( m 1 2 ) ) ( lambda ( p q ) p ) ) ( ( lambda ( p q ) p ) 1 2 ) 1 Из этого вытекает довольно очевидная реализация : (define (n-cdr pair) (pair (lambda (p q) q)))
4d16cb572c26799066b4f4ebd2e48bbe6a9b8fe8e7c467eab7606eccf6615b66
evidentsystems/converge
filesystem_test.clj
(ns converge.storage.filesystem-test (:require converge.storage.filesystem))
null
https://raw.githubusercontent.com/evidentsystems/converge/7a7f542fe86e98b1ae52b3418837a6fe38686142/storage/test/converge/storage/filesystem_test.clj
clojure
(ns converge.storage.filesystem-test (:require converge.storage.filesystem))
5237605ea99312850fbd4b8f9d5cb3ef08e492a301f75b1ec3876a6c008fe5ea
alanzplus/EOPL
4.10-test.rkt
#lang eopl (require rackunit "explicit-refs-interpreter.rkt") (require rackunit/text-ui) (define begin-test (test-suite "Test for begin" (check-equal? (run " let x = newref(1) in begin setref(x, 11); setref(x, 12); deref(x) end") (num-val 12)) )) (run-tests begin-test)
null
https://raw.githubusercontent.com/alanzplus/EOPL/d7b06392d26d93df851d0ca66d9edc681a06693c/EOPL/ch4/4.10-test.rkt
racket
#lang eopl (require rackunit "explicit-refs-interpreter.rkt") (require rackunit/text-ui) (define begin-test (test-suite "Test for begin" (check-equal? (run " let x = newref(1) in begin deref(x) end") (num-val 12)) )) (run-tests begin-test)
96fa73fead0cbc3dda10d1286ba330759d489e2f1be0b8f59665cb9f042e8a7d
OCamlPro/ocaml-benchs
echo_client.ml
open Core.Std open Async.Std let send_stuff nbr_stuff state r w = let size = 27 in let str = String.make size 'a' in let buffer = String.create size in let rec send_stuffs i = if i = nbr_stuff then return () else let len = (Random.State.int state (size - 1)) + 1 in Writer.write ~pos:0 ~len w str; if !Echo_common.debug then Log.Global.printf "(Client-%i) send '%s'." i str; Reader.read r buffer >>= function | `Eof -> return () | `Ok _ -> if !Echo_common.debug then Log.Global.printf "(Client-%i) received '%s'." i buffer; send_stuffs (i + 1) in send_stuffs 0 let run ~port ~nbr () = Random.init 42; let state = Random.State.default in Tcp.with_connection (Tcp.to_host_and_port "127.0.0.1" port) (fun _ r w -> if !Echo_common.debug then Log.Global.printf "(Client) Connected to server."; send_stuff nbr (Random.State.copy state) r w >>= fun() -> Reader.close r >>= fun () -> Writer.close w)
null
https://raw.githubusercontent.com/OCamlPro/ocaml-benchs/98047e112574e6bf55137dd8058f227a9f40281b/async_echo/echo_client.ml
ocaml
open Core.Std open Async.Std let send_stuff nbr_stuff state r w = let size = 27 in let str = String.make size 'a' in let buffer = String.create size in let rec send_stuffs i = if i = nbr_stuff then return () else let len = (Random.State.int state (size - 1)) + 1 in Writer.write ~pos:0 ~len w str; if !Echo_common.debug then Log.Global.printf "(Client-%i) send '%s'." i str; Reader.read r buffer >>= function | `Eof -> return () | `Ok _ -> if !Echo_common.debug then Log.Global.printf "(Client-%i) received '%s'." i buffer; send_stuffs (i + 1) in send_stuffs 0 let run ~port ~nbr () = Random.init 42; let state = Random.State.default in Tcp.with_connection (Tcp.to_host_and_port "127.0.0.1" port) (fun _ r w -> if !Echo_common.debug then Log.Global.printf "(Client) Connected to server."; send_stuff nbr (Random.State.copy state) r w >>= fun() -> Reader.close r >>= fun () -> Writer.close w)
25a527b88be181f5881cb341dbc8493a90170cbdd4f69e5be3cf9623903ad61b
BinaryAnalysisPlatform/bap
bap_c_type_printer.ml
let pp = Bap_c_type.pp and pp_proto = Bap_c_type.pp_proto
null
https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/db26f0034a38398909f3c1d882b51cc9dc6c3338/lib/bap_c/bap_c_type_printer.ml
ocaml
let pp = Bap_c_type.pp and pp_proto = Bap_c_type.pp_proto
db2d2b5bcb5316b7a4ff71d18d2de4dc6b0e6d207fc12841805fa6518a523938
basho/basho_bench
basho_bench_stats_writer.erl
%% ------------------------------------------------------------------- %% %% basho_bench: Benchmarking Suite %% Copyright ( c ) 2009 - 2014 Basho Techonologies %% 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. %% %% ------------------------------------------------------------------- HOWTO : %% %% * To run basho_bench with the default CSV writer, nothing needs to %% be done. But if wanting to override a former setting, then %% writing the following in the benchmark config file will switch %% the stats writer to CSV: %% %% {stats, {csv}}. %% %% * To run basho_bench with statistics sent to [Riemann][1], in the %% benchmark config file the following needs to be written: %% { stats , } . %% This will , by default , try to connect to a Riemann server on localhost , port 5555 , and will not set any TTL or tags . To %% configure the writer, an app config needs to be written. For %% that, one needs to add "-config app.config" (the filename can be %% anything) to escript_emu_args in rebar.config, recompile %% basho_bench, and add the necessary configuration to app.config, %% something along these lines: %% %% [ %% {katja, [ { host , " 127.0.0.1 " } , { port , 5555 } , %% {transport, detect}, %% {pool, []}, %% {defaults, [{host, "myhost.local"}, %% {tags, ["basho_bench"]}, { ttl , 5.0 } ] } %% ]} %% ]. -module(basho_bench_stats_writer). -export([new/3, terminate/1, process_summary/5, report_error/3, report_latency/7]). -include("basho_bench.hrl"). new({csv}, Ops, Measurements) -> %% Setup output file handles for dumping periodic CSV of histogram results. [erlang:put({csv_file, X}, op_csv_file(X)) || X <- Ops], %% Setup output file handles for dumping periodic CSV of histogram results. [erlang:put({csv_file, X}, measurement_csv_file(X)) || X <- Measurements], %% Setup output file w/ counters for total requests, errors, etc. {ok, SummaryFile} = file:open("summary.csv", [raw, binary, write]), file:write(SummaryFile, <<"elapsed, window, total, successful, failed\n">>), %% Setup errors file w/counters for each error. Embedded commas likely %% in the error messages so quote the columns. {ok, ErrorsFile} = file:open("errors.csv", [raw, binary, write]), file:write(ErrorsFile, <<"\"error\",\"count\"\n">>), {SummaryFile, ErrorsFile}; new({riemann}, _, _) -> katja:start(). terminate({{csv}, {SummaryFile, ErrorsFile}}) -> [ok = file:close(F) || {{csv_file, _}, F} <- erlang:get()], ok = file:close(SummaryFile), ok = file:close(ErrorsFile), ok; terminate({{riemann}, _}) -> katja:stop(), ok. process_summary({{csv}, {SummaryFile, _ErrorsFile}}, Elapsed, Window, Oks, Errors) -> file:write(SummaryFile, io_lib:format("~w, ~w, ~w, ~w, ~w\n", [Elapsed, Window, Oks + Errors, Oks, Errors])); process_summary({{riemann}, _}, _Elapsed, _Window, Oks, Errors) -> katja:send_entities([{events, [[{service, "basho_bench summary ok"}, {metric, Oks}], [{service, "basho_bench summary errors"}, {metric, Errors}]]}]). report_error({{csv}, {_SummaryFile, ErrorsFile}}, Key, Count) -> file:write(ErrorsFile, io_lib:format("\"~w\",\"~w\"\n", [Key, Count])); report_error({{riemann}, _}, Key, Count) -> katja:send_event([{service, io_lib:format("basho_bench error for key ~p", [Key])}, {metric, Count}]). report_latency({{csv}, {_SummaryFile, _ErrorsFile}}, Elapsed, Window, Op, Stats, Errors, Units) -> case proplists:get_value(n, Stats) > 0 of true -> P = proplists:get_value(percentile, Stats), Line = io_lib:format("~w, ~w, ~w, ~w, ~.1f, ~w, ~w, ~w, ~w, ~w, ~w\n", [Elapsed, Window, Units, proplists:get_value(min, Stats), proplists:get_value(arithmetic_mean, Stats), proplists:get_value(median, Stats), proplists:get_value(95, P), proplists:get_value(99, P), proplists:get_value(999, P), proplists:get_value(max, Stats), Errors]); false -> ?WARN("No data for op: ~p\n", [Op]), Line = io_lib:format("~w, ~w, 0, 0, 0, 0, 0, 0, 0, 0, ~w\n", [Elapsed, Window, Errors]) end, file:write(erlang:get({csv_file, Op}), Line); report_latency({{riemann}, _}, _Elapsed, _Window, Op, Stats, Errors, Units) -> case proplists:get_value(n, Stats) > 0 of true -> katja:send_entities([{events, riemann_op_latencies(Op, Stats, Errors, Units)}]); false -> ?WARN("No data for op: ~p\n", [Op]) end. %% ==================================================================== Internal functions %% ==================================================================== op_csv_file({Label, _Op}) -> Fname = normalize_label(Label) ++ "_latencies.csv", {ok, F} = file:open(Fname, [raw, binary, write]), ok = file:write(F, <<"elapsed, window, n, min, mean, median, 95th, 99th, 99_9th, max, errors\n">>), F. measurement_csv_file({Label, _Op}) -> Fname = normalize_label(Label) ++ "_measurements.csv", {ok, F} = file:open(Fname, [raw, binary, write]), ok = file:write(F, <<"elapsed, window, n, min, mean, median, 95th, 99th, 99_9th, max, errors\n">>), F. normalize_label(Label) when is_list(Label) -> replace_special_chars(Label); normalize_label(Label) when is_binary(Label) -> normalize_label(binary_to_list(Label)); normalize_label(Label) when is_integer(Label) -> normalize_label(integer_to_list(Label)); normalize_label(Label) when is_atom(Label) -> normalize_label(atom_to_list(Label)); normalize_label(Label) when is_tuple(Label) -> Parts = [normalize_label(X) || X <- tuple_to_list(Label)], string:join(Parts, "-"). replace_special_chars([H|T]) when (H >= $0 andalso H =< $9) orelse (H >= $A andalso H =< $Z) orelse (H >= $a andalso H =< $z) -> [H|replace_special_chars(T)]; replace_special_chars([_|T]) -> [$-|replace_special_chars(T)]; replace_special_chars([]) -> []. riemann_op_latencies({Label, _Op}, Stats, Errors, Units) -> P = proplists:get_value(percentile, Stats), Service = normalize_label(Label), [[{service, io_lib:format("basho_bench op ~s latency min", [Service])}, {metric, proplists:get_value(min, Stats)}], [{service, io_lib:format("basho_bench op ~s latency max", [Service])}, {metric, proplists:get_value(max, Stats)}], [{service, io_lib:format("basho_bench op ~s latency mean", [Service])}, {metric, proplists:get_value(arithmetic_mean, Stats)}], [{service, io_lib:format("basho_bench op ~s latency median", [Service])}, {metric, proplists:get_value(median, Stats)}], [{service, io_lib:format("basho_bench op ~s latency 95%", [Service])}, {metric, proplists:get_value(95, P)}], [{service, io_lib:format("basho_bench op ~s latency 99%", [Service])}, {metric, proplists:get_value(99, P)}], [{service, io_lib:format("basho_bench op ~s latency 99.9%", [Service])}, {metric, proplists:get_value(999, P)}], [{service, io_lib:format("basho_bench op ~s #", [Service])}, {metric, Units}], [{service, io_lib:format("basho_bench op ~s error#", [Service])}, {metric, Errors}]].
null
https://raw.githubusercontent.com/basho/basho_bench/aa66398bb6a91645dbb97e91a236f3cdcd1f188f/src/basho_bench_stats_writer.erl
erlang
------------------------------------------------------------------- basho_bench: Benchmarking Suite 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. ------------------------------------------------------------------- * To run basho_bench with the default CSV writer, nothing needs to be done. But if wanting to override a former setting, then writing the following in the benchmark config file will switch the stats writer to CSV: {stats, {csv}}. * To run basho_bench with statistics sent to [Riemann][1], in the benchmark config file the following needs to be written: configure the writer, an app config needs to be written. For that, one needs to add "-config app.config" (the filename can be anything) to escript_emu_args in rebar.config, recompile basho_bench, and add the necessary configuration to app.config, something along these lines: [ {katja, [ {transport, detect}, {pool, []}, {defaults, [{host, "myhost.local"}, {tags, ["basho_bench"]}, ]} ]. Setup output file handles for dumping periodic CSV of histogram results. Setup output file handles for dumping periodic CSV of histogram results. Setup output file w/ counters for total requests, errors, etc. Setup errors file w/counters for each error. Embedded commas likely in the error messages so quote the columns. ==================================================================== ====================================================================
Copyright ( c ) 2009 - 2014 Basho Techonologies 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 HOWTO : { stats , } . This will , by default , try to connect to a Riemann server on localhost , port 5555 , and will not set any TTL or tags . To { host , " 127.0.0.1 " } , { port , 5555 } , { ttl , 5.0 } ] } -module(basho_bench_stats_writer). -export([new/3, terminate/1, process_summary/5, report_error/3, report_latency/7]). -include("basho_bench.hrl"). new({csv}, Ops, Measurements) -> [erlang:put({csv_file, X}, op_csv_file(X)) || X <- Ops], [erlang:put({csv_file, X}, measurement_csv_file(X)) || X <- Measurements], {ok, SummaryFile} = file:open("summary.csv", [raw, binary, write]), file:write(SummaryFile, <<"elapsed, window, total, successful, failed\n">>), {ok, ErrorsFile} = file:open("errors.csv", [raw, binary, write]), file:write(ErrorsFile, <<"\"error\",\"count\"\n">>), {SummaryFile, ErrorsFile}; new({riemann}, _, _) -> katja:start(). terminate({{csv}, {SummaryFile, ErrorsFile}}) -> [ok = file:close(F) || {{csv_file, _}, F} <- erlang:get()], ok = file:close(SummaryFile), ok = file:close(ErrorsFile), ok; terminate({{riemann}, _}) -> katja:stop(), ok. process_summary({{csv}, {SummaryFile, _ErrorsFile}}, Elapsed, Window, Oks, Errors) -> file:write(SummaryFile, io_lib:format("~w, ~w, ~w, ~w, ~w\n", [Elapsed, Window, Oks + Errors, Oks, Errors])); process_summary({{riemann}, _}, _Elapsed, _Window, Oks, Errors) -> katja:send_entities([{events, [[{service, "basho_bench summary ok"}, {metric, Oks}], [{service, "basho_bench summary errors"}, {metric, Errors}]]}]). report_error({{csv}, {_SummaryFile, ErrorsFile}}, Key, Count) -> file:write(ErrorsFile, io_lib:format("\"~w\",\"~w\"\n", [Key, Count])); report_error({{riemann}, _}, Key, Count) -> katja:send_event([{service, io_lib:format("basho_bench error for key ~p", [Key])}, {metric, Count}]). report_latency({{csv}, {_SummaryFile, _ErrorsFile}}, Elapsed, Window, Op, Stats, Errors, Units) -> case proplists:get_value(n, Stats) > 0 of true -> P = proplists:get_value(percentile, Stats), Line = io_lib:format("~w, ~w, ~w, ~w, ~.1f, ~w, ~w, ~w, ~w, ~w, ~w\n", [Elapsed, Window, Units, proplists:get_value(min, Stats), proplists:get_value(arithmetic_mean, Stats), proplists:get_value(median, Stats), proplists:get_value(95, P), proplists:get_value(99, P), proplists:get_value(999, P), proplists:get_value(max, Stats), Errors]); false -> ?WARN("No data for op: ~p\n", [Op]), Line = io_lib:format("~w, ~w, 0, 0, 0, 0, 0, 0, 0, 0, ~w\n", [Elapsed, Window, Errors]) end, file:write(erlang:get({csv_file, Op}), Line); report_latency({{riemann}, _}, _Elapsed, _Window, Op, Stats, Errors, Units) -> case proplists:get_value(n, Stats) > 0 of true -> katja:send_entities([{events, riemann_op_latencies(Op, Stats, Errors, Units)}]); false -> ?WARN("No data for op: ~p\n", [Op]) end. Internal functions op_csv_file({Label, _Op}) -> Fname = normalize_label(Label) ++ "_latencies.csv", {ok, F} = file:open(Fname, [raw, binary, write]), ok = file:write(F, <<"elapsed, window, n, min, mean, median, 95th, 99th, 99_9th, max, errors\n">>), F. measurement_csv_file({Label, _Op}) -> Fname = normalize_label(Label) ++ "_measurements.csv", {ok, F} = file:open(Fname, [raw, binary, write]), ok = file:write(F, <<"elapsed, window, n, min, mean, median, 95th, 99th, 99_9th, max, errors\n">>), F. normalize_label(Label) when is_list(Label) -> replace_special_chars(Label); normalize_label(Label) when is_binary(Label) -> normalize_label(binary_to_list(Label)); normalize_label(Label) when is_integer(Label) -> normalize_label(integer_to_list(Label)); normalize_label(Label) when is_atom(Label) -> normalize_label(atom_to_list(Label)); normalize_label(Label) when is_tuple(Label) -> Parts = [normalize_label(X) || X <- tuple_to_list(Label)], string:join(Parts, "-"). replace_special_chars([H|T]) when (H >= $0 andalso H =< $9) orelse (H >= $A andalso H =< $Z) orelse (H >= $a andalso H =< $z) -> [H|replace_special_chars(T)]; replace_special_chars([_|T]) -> [$-|replace_special_chars(T)]; replace_special_chars([]) -> []. riemann_op_latencies({Label, _Op}, Stats, Errors, Units) -> P = proplists:get_value(percentile, Stats), Service = normalize_label(Label), [[{service, io_lib:format("basho_bench op ~s latency min", [Service])}, {metric, proplists:get_value(min, Stats)}], [{service, io_lib:format("basho_bench op ~s latency max", [Service])}, {metric, proplists:get_value(max, Stats)}], [{service, io_lib:format("basho_bench op ~s latency mean", [Service])}, {metric, proplists:get_value(arithmetic_mean, Stats)}], [{service, io_lib:format("basho_bench op ~s latency median", [Service])}, {metric, proplists:get_value(median, Stats)}], [{service, io_lib:format("basho_bench op ~s latency 95%", [Service])}, {metric, proplists:get_value(95, P)}], [{service, io_lib:format("basho_bench op ~s latency 99%", [Service])}, {metric, proplists:get_value(99, P)}], [{service, io_lib:format("basho_bench op ~s latency 99.9%", [Service])}, {metric, proplists:get_value(999, P)}], [{service, io_lib:format("basho_bench op ~s #", [Service])}, {metric, Units}], [{service, io_lib:format("basho_bench op ~s error#", [Service])}, {metric, Errors}]].
ed2211681005b2e247e05e6a3652f3b7ce7504105a3776d55fcff8d6583cc6b6
alexrobbins/cascalog-intro
scrape.clj
(ns cascalog-intro.scrape (:require [clojure.java.io :refer (reader)] [clojure.string :as s] [clojure.tools.cli :refer :all] [net.cgrand.enlive-html :as html])) (defn -main [& args] "Grab the talk content from the div'ed session page. Dump as newline delimited talks" (let [[arg-map _ usage] (cli args ["-i" "--input" "input path"])] (when-not (:input arg-map) (println usage) (System/exit 0)) (let [resource (-> (:input arg-map) reader html/html-resource) talk-nodes (html/select resource [:div#content :div])] (doseq [tn talk-nodes] (-> tn html/text (s/replace "\n" " ") println)))))
null
https://raw.githubusercontent.com/alexrobbins/cascalog-intro/895221d57357a35f8e20218886af2ba9b9907b16/src/cascalog_intro/scrape.clj
clojure
(ns cascalog-intro.scrape (:require [clojure.java.io :refer (reader)] [clojure.string :as s] [clojure.tools.cli :refer :all] [net.cgrand.enlive-html :as html])) (defn -main [& args] "Grab the talk content from the div'ed session page. Dump as newline delimited talks" (let [[arg-map _ usage] (cli args ["-i" "--input" "input path"])] (when-not (:input arg-map) (println usage) (System/exit 0)) (let [resource (-> (:input arg-map) reader html/html-resource) talk-nodes (html/select resource [:div#content :div])] (doseq [tn talk-nodes] (-> tn html/text (s/replace "\n" " ") println)))))
849e152c3d2ee9176f4985ebdc3eed164253681decf26f376b7506095be0a4a5
MarcKaufmann/congame
resource.rkt
#lang racket/base (require congame/components/resource koyo/mime racket/port web-server/dispatchers/dispatch web-server/http) (provide serve-resource-page) (define (serve-resource-page _req id [subresource #f]) (define r (get-resource id)) (unless r (next-dispatcher)) (define full-path (if subresource (build-path (resource-path r) subresource) (resource-path r))) (define size-in-bytes (file-size full-path)) (response/output #:mime-type (path->mime-type full-path) #:headers (list (header #"content-length" (string->bytes/utf-8 (number->string size-in-bytes)))) (lambda (out) (call-with-input-file full-path (lambda (in) (copy-port in out))))))
null
https://raw.githubusercontent.com/MarcKaufmann/congame/c3e09a6b707c22d14dde7954fb0d5ba4f94717f8/congame-web/pages/resource.rkt
racket
#lang racket/base (require congame/components/resource koyo/mime racket/port web-server/dispatchers/dispatch web-server/http) (provide serve-resource-page) (define (serve-resource-page _req id [subresource #f]) (define r (get-resource id)) (unless r (next-dispatcher)) (define full-path (if subresource (build-path (resource-path r) subresource) (resource-path r))) (define size-in-bytes (file-size full-path)) (response/output #:mime-type (path->mime-type full-path) #:headers (list (header #"content-length" (string->bytes/utf-8 (number->string size-in-bytes)))) (lambda (out) (call-with-input-file full-path (lambda (in) (copy-port in out))))))
836e30197c2fcdcb0a1dd21fc0decef3e229738e5bb8f375aacc1b85cdcfbf86
GaloisInc/cereal
Put.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE CPP # # LANGUAGE FlexibleInstances # #ifndef MIN_VERSION_base #define MIN_VERSION_base(x,y,z) 0 #endif #ifndef MIN_VERSION_bytestring #define MIN_VERSION_bytestring(x,y,z) 0 #endif ----------------------------------------------------------------------------- -- | Module : Data . Serialize . Put Copyright : , Galois Inc. 2009 -- License : BSD3-style (see LICENSE) -- Maintainer : < > -- Stability : -- Portability : -- -- The Put monad. A monad for efficiently constructing bytestrings. -- ----------------------------------------------------------------------------- module Data.Serialize.Put ( -- * The Put type Put , PutM(..) , Putter , runPut , runPutM , runPutLazy , runPutMLazy , runPutMBuilder , putBuilder , execPut -- * Flushing the implicit parse state , flush -- * Primitives , putWord8 , putInt8 , putByteString , putLazyByteString , putShortByteString -- * Big-endian primitives , putWord16be , putWord32be , putWord64be , putInt16be , putInt32be , putInt64be -- * Little-endian primitives , putWord16le , putWord32le , putWord64le , putInt16le , putInt32le , putInt64le -- * Host-endian, unaligned writes , putWordhost , putWord16host , putWord32host , putWord64host , putInthost , putInt16host , putInt32host , putInt64host -- * Containers , putTwoOf , putListOf , putIArrayOf , putSeqOf , putTreeOf , putMapOf , putIntMapOf , putSetOf , putIntSetOf , putMaybeOf , putEitherOf , putNested ) where import Data.ByteString.Builder (Builder, toLazyByteString) import qualified Data.ByteString.Builder as B import qualified Data.ByteString.Builder.Extra as B import qualified Data.ByteString.Short as BS import qualified Control.Applicative as A import Data.Array.Unboxed #if MIN_VERSION_base(4,9,0) import qualified Data.Semigroup as M #endif import qualified Data.Monoid as M import qualified Data.Foldable as F import Data.Word import Data.Int import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import qualified Data.IntMap as IntMap import qualified Data.IntSet as IntSet import qualified Data.Map as Map import qualified Data.Sequence as Seq import qualified Data.Set as Set import qualified Data.Tree as T #if !(MIN_VERSION_base(4,8,0)) import Control.Applicative import Data.Foldable (foldMap) import Data.Monoid #endif #if !(MIN_VERSION_bytestring(0,10,0)) import Foreign.ForeignPtr (withForeignPtr) import Foreign.Marshal.Utils (copyBytes) import Foreign.Ptr (plusPtr) import qualified Data.ByteString.Internal as S import qualified Data.ByteString.Lazy.Internal as L #endif ------------------------------------------------------------------------ -- XXX Strict in builder only. data PairS a = PairS a !Builder sndS :: PairS a -> Builder sndS (PairS _ b) = b -- | The PutM type. A Writer monad over the efficient Builder monoid. newtype PutM a = Put { unPut :: PairS a } -- | Put merely lifts Builder into a Writer monad, applied to (). type Put = PutM () type Putter a = a -> Put instance Functor PutM where fmap f m = Put $ let PairS a w = unPut m in PairS (f a) w # INLINE fmap # instance A.Applicative PutM where pure a = Put (PairS a M.mempty) # INLINE pure # m <*> k = Put $ let PairS f w = unPut m PairS x w' = unPut k in PairS (f x) (w `M.mappend` w') {-# INLINE (<*>) #-} m *> k = Put $ let PairS _ w = unPut m PairS b w' = unPut k in PairS b (w `M.mappend` w') {-# INLINE (*>) #-} instance Monad PutM where return = pure # INLINE return # m >>= k = Put $ let PairS a w = unPut m PairS b w' = unPut (k a) in PairS b (w `M.mappend` w') {-# INLINE (>>=) #-} (>>) = (*>) {-# INLINE (>>) #-} #if MIN_VERSION_base(4,9,0) instance M.Semigroup (PutM ()) where (<>) = (*>) {-# INLINE (<>) #-} #endif instance Monoid (PutM ()) where mempty = pure () # INLINE mempty # #if !(MIN_VERSION_base(4,11,0)) mappend = (*>) # INLINE mappend # #endif tell :: Putter Builder tell b = Put $! PairS () b {-# INLINE tell #-} putBuilder :: Putter Builder putBuilder = tell # INLINE putBuilder # -- | Run the 'Put' monad execPut :: PutM a -> Builder execPut = sndS . unPut # INLINE execPut # | Run the ' Put ' monad with a serialiser runPut :: Put -> S.ByteString runPut = lazyToStrictByteString . runPutLazy {-# INLINE runPut #-} -- | Run the 'Put' monad with a serialiser and get its result runPutM :: PutM a -> (a, S.ByteString) runPutM (Put (PairS f s)) = (f, lazyToStrictByteString (toLazyByteString s)) # INLINE runPutM # | Run the ' Put ' monad with a serialiser runPutLazy :: Put -> L.ByteString runPutLazy = toLazyByteString . sndS . unPut # INLINE runPutLazy # | Run the ' Put ' monad with a serialiser runPutMLazy :: PutM a -> (a, L.ByteString) runPutMLazy (Put (PairS f s)) = (f, toLazyByteString s) # INLINE runPutMLazy # -- | Run the 'Put' monad and get the result and underlying 'Builder' runPutMBuilder :: PutM a -> (a, Builder) runPutMBuilder (Put (PairS f s)) = (f, s) # INLINE runPutMBuilder # ------------------------------------------------------------------------ | Pop the ByteString we have constructed so far , if any , yielding a new chunk in the result ByteString . flush :: Put flush = tell B.flush # INLINE flush # -- | Efficiently write a byte into the output buffer putWord8 :: Putter Word8 putWord8 = tell . B.word8 # INLINE putWord8 # -- | Efficiently write an int into the output buffer putInt8 :: Putter Int8 putInt8 = tell . B.int8 # INLINE putInt8 # | An efficient primitive to write a strict ByteString into the output buffer . -- It flushes the current buffer, and writes the argument into a new chunk. putByteString :: Putter S.ByteString putByteString = tell . B.byteString # INLINE putByteString # putShortByteString :: Putter BS.ShortByteString putShortByteString = tell . B.shortByteString | Write a lazy ByteString efficiently , simply appending the lazy ByteString chunks to the output buffer putLazyByteString :: Putter L.ByteString putLazyByteString = tell . B.lazyByteString # INLINE putLazyByteString # | Write a Word16 in big endian format putWord16be :: Putter Word16 putWord16be = tell . B.word16BE # INLINE putWord16be # | Write a Word16 in little endian format putWord16le :: Putter Word16 putWord16le = tell . B.word16LE # INLINE putWord16le # | Write a Word32 in big endian format putWord32be :: Putter Word32 putWord32be = tell . B.word32BE # INLINE putWord32be # | Write a Word32 in little endian format putWord32le :: Putter Word32 putWord32le = tell . B.word32LE # INLINE putWord32le # | Write a Word64 in big endian format putWord64be :: Putter Word64 putWord64be = tell . B.word64BE # INLINE putWord64be # | Write a Word64 in little endian format putWord64le :: Putter Word64 putWord64le = tell . B.word64LE # INLINE putWord64le # ------------------------------------------------------------------------ -- | /O(1)./ Write a single native machine word. The word is written in host order , host endian form , for the machine you 're on . On a 64 bit machine the Word is an 8 byte value , on a 32 bit machine , 4 bytes . Values written this way are not portable to -- different endian or word sized machines, without conversion. -- putWordhost :: Putter Word putWordhost = tell . B.wordHost # INLINE putWordhost # -- | /O(1)./ Write a Word16 in native host order and host endianness. -- For portability issues see @putWordhost@. putWord16host :: Putter Word16 putWord16host = tell . B.word16Host # INLINE putWord16host # -- | /O(1)./ Write a Word32 in native host order and host endianness. -- For portability issues see @putWordhost@. putWord32host :: Putter Word32 putWord32host = tell . B.word32Host # INLINE putWord32host # -- | /O(1)./ Write a Word64 in native host order On a 32 bit machine we write two host order , in big endian form . -- For portability issues see @putWordhost@. putWord64host :: Putter Word64 putWord64host = tell . B.word64Host # INLINE putWord64host # | Write a Int16 in big endian format putInt16be :: Putter Int16 putInt16be = tell . B.int16BE # INLINE putInt16be # | Write a Int16 in little endian format putInt16le :: Putter Int16 putInt16le = tell . B.int16LE # INLINE putInt16le # | Write a Int32 in big endian format putInt32be :: Putter Int32 putInt32be = tell . B.int32BE # INLINE putInt32be # | Write a Int32 in little endian format putInt32le :: Putter Int32 putInt32le = tell . B.int32LE # INLINE putInt32le # | Write a Int64 in big endian format putInt64be :: Putter Int64 putInt64be = tell . B.int64BE # INLINE putInt64be # | Write a Int64 in little endian format putInt64le :: Putter Int64 putInt64le = tell . B.int64LE # INLINE putInt64le # ------------------------------------------------------------------------ -- | /O(1)./ Write a single native machine int. The int is written in host order , host endian form , for the machine you 're on . On a 64 bit machine the Int is an 8 byte value , on a 32 bit machine , 4 bytes . Values written this way are not portable to -- different endian or int sized machines, without conversion. -- putInthost :: Putter Int putInthost = tell . B.intHost # INLINE putInthost # -- | /O(1)./ Write a Int16 in native host order and host endianness. -- For portability issues see @putInthost@. putInt16host :: Putter Int16 putInt16host = tell . B.int16Host # INLINE putInt16host # | /O(1)./ Write a Int32 in native host order and host endianness . -- For portability issues see @putInthost@. putInt32host :: Putter Int32 putInt32host = tell . B.int32Host # INLINE putInt32host # | /O(1)./ Write a Int64 in native host order On a 32 bit machine we write two host order Int32s , in big endian form . -- For portability issues see @putInthost@. putInt64host :: Putter Int64 putInt64host = tell . B.int64Host # INLINE putInt64host # -- Containers ------------------------------------------------------------------ encodeListOf :: (a -> Builder) -> [a] -> Builder encodeListOf f = -- allow inlining with just a single argument \xs -> execPut (putWord64be (fromIntegral $ length xs)) `M.mappend` F.foldMap f xs # INLINE encodeListOf # putTwoOf :: Putter a -> Putter b -> Putter (a,b) putTwoOf pa pb (a,b) = pa a >> pb b # INLINE putTwoOf # putListOf :: Putter a -> Putter [a] putListOf pa = \l -> do putWord64be (fromIntegral (length l)) mapM_ pa l # INLINE putListOf # putIArrayOf :: (Ix i, IArray a e) => Putter i -> Putter e -> Putter (a i e) putIArrayOf pix pe a = do putTwoOf pix pix (bounds a) putListOf pe (elems a) # INLINE putIArrayOf # putSeqOf :: Putter a -> Putter (Seq.Seq a) putSeqOf pa = \s -> do putWord64be (fromIntegral $ Seq.length s) F.mapM_ pa s # INLINE putSeqOf # putTreeOf :: Putter a -> Putter (T.Tree a) putTreeOf pa = tell . go where go (T.Node x cs) = execPut (pa x) `M.mappend` encodeListOf go cs # INLINE putTreeOf # putMapOf :: Putter k -> Putter a -> Putter (Map.Map k a) putMapOf pk pa = putListOf (putTwoOf pk pa) . Map.toAscList # INLINE putMapOf # putIntMapOf :: Putter Int -> Putter a -> Putter (IntMap.IntMap a) putIntMapOf pix pa = putListOf (putTwoOf pix pa) . IntMap.toAscList # INLINE putIntMapOf # putSetOf :: Putter a -> Putter (Set.Set a) putSetOf pa = putListOf pa . Set.toAscList # INLINE putSetOf # putIntSetOf :: Putter Int -> Putter IntSet.IntSet putIntSetOf pix = putListOf pix . IntSet.toAscList # INLINE putIntSetOf # putMaybeOf :: Putter a -> Putter (Maybe a) putMaybeOf _ Nothing = putWord8 0 putMaybeOf pa (Just a) = putWord8 1 >> pa a # INLINE putMaybeOf # putEitherOf :: Putter a -> Putter b -> Putter (Either a b) putEitherOf pa _ (Left a) = putWord8 0 >> pa a putEitherOf _ pb (Right b) = putWord8 1 >> pb b {-# INLINE putEitherOf #-} | Put a nested structure by first putting a length -- field and then putting the encoded value. putNested :: Putter Int -> Put -> Put putNested putLen putVal = do let bs = runPut putVal putLen (S.length bs) putByteString bs ------------------------------------------------------------------------------- -- pre-bytestring-0.10 compatibility ------------------------------------------------------------------------------- # INLINE lazyToStrictByteString # lazyToStrictByteString :: L.ByteString -> S.ByteString #if MIN_VERSION_bytestring(0,10,0) lazyToStrictByteString = L.toStrict #else lazyToStrictByteString = packChunks -- packChunks is taken from the blaze-builder package. -- | Pack the chunks of a lazy bytestring into a single strict bytestring. packChunks :: L.ByteString -> S.ByteString packChunks lbs = S.unsafeCreate (fromIntegral $ L.length lbs) (copyChunks lbs) where copyChunks !L.Empty !_pf = return () copyChunks !(L.Chunk (S.PS fpbuf o l) lbs') !pf = do withForeignPtr fpbuf $ \pbuf -> copyBytes pf (pbuf `plusPtr` o) l copyChunks lbs' (pf `plusPtr` l) #endif
null
https://raw.githubusercontent.com/GaloisInc/cereal/b4fff04dc2fb28eb0ec5e6c63b53248a63eb4ca5/src/Data/Serialize/Put.hs
haskell
# LANGUAGE BangPatterns # --------------------------------------------------------------------------- | License : BSD3-style (see LICENSE) Stability : Portability : The Put monad. A monad for efficiently constructing bytestrings. --------------------------------------------------------------------------- * The Put type * Flushing the implicit parse state * Primitives * Big-endian primitives * Little-endian primitives * Host-endian, unaligned writes * Containers ---------------------------------------------------------------------- XXX Strict in builder only. | The PutM type. A Writer monad over the efficient Builder monoid. | Put merely lifts Builder into a Writer monad, applied to (). # INLINE (<*>) # # INLINE (*>) # # INLINE (>>=) # # INLINE (>>) # # INLINE (<>) # # INLINE tell # | Run the 'Put' monad # INLINE runPut # | Run the 'Put' monad with a serialiser and get its result | Run the 'Put' monad and get the result and underlying 'Builder' ---------------------------------------------------------------------- | Efficiently write a byte into the output buffer | Efficiently write an int into the output buffer It flushes the current buffer, and writes the argument into a new chunk. ---------------------------------------------------------------------- | /O(1)./ Write a single native machine word. The word is different endian or word sized machines, without conversion. | /O(1)./ Write a Word16 in native host order and host endianness. For portability issues see @putWordhost@. | /O(1)./ Write a Word32 in native host order and host endianness. For portability issues see @putWordhost@. | /O(1)./ Write a Word64 in native host order For portability issues see @putWordhost@. ---------------------------------------------------------------------- | /O(1)./ Write a single native machine int. The int is different endian or int sized machines, without conversion. | /O(1)./ Write a Int16 in native host order and host endianness. For portability issues see @putInthost@. For portability issues see @putInthost@. For portability issues see @putInthost@. Containers ------------------------------------------------------------------ allow inlining with just a single argument # INLINE putEitherOf # field and then putting the encoded value. ----------------------------------------------------------------------------- pre-bytestring-0.10 compatibility ----------------------------------------------------------------------------- packChunks is taken from the blaze-builder package. | Pack the chunks of a lazy bytestring into a single strict bytestring.
# LANGUAGE CPP # # LANGUAGE FlexibleInstances # #ifndef MIN_VERSION_base #define MIN_VERSION_base(x,y,z) 0 #endif #ifndef MIN_VERSION_bytestring #define MIN_VERSION_bytestring(x,y,z) 0 #endif Module : Data . Serialize . Put Copyright : , Galois Inc. 2009 Maintainer : < > module Data.Serialize.Put ( Put , PutM(..) , Putter , runPut , runPutM , runPutLazy , runPutMLazy , runPutMBuilder , putBuilder , execPut , flush , putWord8 , putInt8 , putByteString , putLazyByteString , putShortByteString , putWord16be , putWord32be , putWord64be , putInt16be , putInt32be , putInt64be , putWord16le , putWord32le , putWord64le , putInt16le , putInt32le , putInt64le , putWordhost , putWord16host , putWord32host , putWord64host , putInthost , putInt16host , putInt32host , putInt64host , putTwoOf , putListOf , putIArrayOf , putSeqOf , putTreeOf , putMapOf , putIntMapOf , putSetOf , putIntSetOf , putMaybeOf , putEitherOf , putNested ) where import Data.ByteString.Builder (Builder, toLazyByteString) import qualified Data.ByteString.Builder as B import qualified Data.ByteString.Builder.Extra as B import qualified Data.ByteString.Short as BS import qualified Control.Applicative as A import Data.Array.Unboxed #if MIN_VERSION_base(4,9,0) import qualified Data.Semigroup as M #endif import qualified Data.Monoid as M import qualified Data.Foldable as F import Data.Word import Data.Int import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import qualified Data.IntMap as IntMap import qualified Data.IntSet as IntSet import qualified Data.Map as Map import qualified Data.Sequence as Seq import qualified Data.Set as Set import qualified Data.Tree as T #if !(MIN_VERSION_base(4,8,0)) import Control.Applicative import Data.Foldable (foldMap) import Data.Monoid #endif #if !(MIN_VERSION_bytestring(0,10,0)) import Foreign.ForeignPtr (withForeignPtr) import Foreign.Marshal.Utils (copyBytes) import Foreign.Ptr (plusPtr) import qualified Data.ByteString.Internal as S import qualified Data.ByteString.Lazy.Internal as L #endif data PairS a = PairS a !Builder sndS :: PairS a -> Builder sndS (PairS _ b) = b newtype PutM a = Put { unPut :: PairS a } type Put = PutM () type Putter a = a -> Put instance Functor PutM where fmap f m = Put $ let PairS a w = unPut m in PairS (f a) w # INLINE fmap # instance A.Applicative PutM where pure a = Put (PairS a M.mempty) # INLINE pure # m <*> k = Put $ let PairS f w = unPut m PairS x w' = unPut k in PairS (f x) (w `M.mappend` w') m *> k = Put $ let PairS _ w = unPut m PairS b w' = unPut k in PairS b (w `M.mappend` w') instance Monad PutM where return = pure # INLINE return # m >>= k = Put $ let PairS a w = unPut m PairS b w' = unPut (k a) in PairS b (w `M.mappend` w') (>>) = (*>) #if MIN_VERSION_base(4,9,0) instance M.Semigroup (PutM ()) where (<>) = (*>) #endif instance Monoid (PutM ()) where mempty = pure () # INLINE mempty # #if !(MIN_VERSION_base(4,11,0)) mappend = (*>) # INLINE mappend # #endif tell :: Putter Builder tell b = Put $! PairS () b putBuilder :: Putter Builder putBuilder = tell # INLINE putBuilder # execPut :: PutM a -> Builder execPut = sndS . unPut # INLINE execPut # | Run the ' Put ' monad with a serialiser runPut :: Put -> S.ByteString runPut = lazyToStrictByteString . runPutLazy runPutM :: PutM a -> (a, S.ByteString) runPutM (Put (PairS f s)) = (f, lazyToStrictByteString (toLazyByteString s)) # INLINE runPutM # | Run the ' Put ' monad with a serialiser runPutLazy :: Put -> L.ByteString runPutLazy = toLazyByteString . sndS . unPut # INLINE runPutLazy # | Run the ' Put ' monad with a serialiser runPutMLazy :: PutM a -> (a, L.ByteString) runPutMLazy (Put (PairS f s)) = (f, toLazyByteString s) # INLINE runPutMLazy # runPutMBuilder :: PutM a -> (a, Builder) runPutMBuilder (Put (PairS f s)) = (f, s) # INLINE runPutMBuilder # | Pop the ByteString we have constructed so far , if any , yielding a new chunk in the result ByteString . flush :: Put flush = tell B.flush # INLINE flush # putWord8 :: Putter Word8 putWord8 = tell . B.word8 # INLINE putWord8 # putInt8 :: Putter Int8 putInt8 = tell . B.int8 # INLINE putInt8 # | An efficient primitive to write a strict ByteString into the output buffer . putByteString :: Putter S.ByteString putByteString = tell . B.byteString # INLINE putByteString # putShortByteString :: Putter BS.ShortByteString putShortByteString = tell . B.shortByteString | Write a lazy ByteString efficiently , simply appending the lazy ByteString chunks to the output buffer putLazyByteString :: Putter L.ByteString putLazyByteString = tell . B.lazyByteString # INLINE putLazyByteString # | Write a Word16 in big endian format putWord16be :: Putter Word16 putWord16be = tell . B.word16BE # INLINE putWord16be # | Write a Word16 in little endian format putWord16le :: Putter Word16 putWord16le = tell . B.word16LE # INLINE putWord16le # | Write a Word32 in big endian format putWord32be :: Putter Word32 putWord32be = tell . B.word32BE # INLINE putWord32be # | Write a Word32 in little endian format putWord32le :: Putter Word32 putWord32le = tell . B.word32LE # INLINE putWord32le # | Write a Word64 in big endian format putWord64be :: Putter Word64 putWord64be = tell . B.word64BE # INLINE putWord64be # | Write a Word64 in little endian format putWord64le :: Putter Word64 putWord64le = tell . B.word64LE # INLINE putWord64le # written in host order , host endian form , for the machine you 're on . On a 64 bit machine the Word is an 8 byte value , on a 32 bit machine , 4 bytes . Values written this way are not portable to putWordhost :: Putter Word putWordhost = tell . B.wordHost # INLINE putWordhost # putWord16host :: Putter Word16 putWord16host = tell . B.word16Host # INLINE putWord16host # putWord32host :: Putter Word32 putWord32host = tell . B.word32Host # INLINE putWord32host # On a 32 bit machine we write two host order , in big endian form . putWord64host :: Putter Word64 putWord64host = tell . B.word64Host # INLINE putWord64host # | Write a Int16 in big endian format putInt16be :: Putter Int16 putInt16be = tell . B.int16BE # INLINE putInt16be # | Write a Int16 in little endian format putInt16le :: Putter Int16 putInt16le = tell . B.int16LE # INLINE putInt16le # | Write a Int32 in big endian format putInt32be :: Putter Int32 putInt32be = tell . B.int32BE # INLINE putInt32be # | Write a Int32 in little endian format putInt32le :: Putter Int32 putInt32le = tell . B.int32LE # INLINE putInt32le # | Write a Int64 in big endian format putInt64be :: Putter Int64 putInt64be = tell . B.int64BE # INLINE putInt64be # | Write a Int64 in little endian format putInt64le :: Putter Int64 putInt64le = tell . B.int64LE # INLINE putInt64le # written in host order , host endian form , for the machine you 're on . On a 64 bit machine the Int is an 8 byte value , on a 32 bit machine , 4 bytes . Values written this way are not portable to putInthost :: Putter Int putInthost = tell . B.intHost # INLINE putInthost # putInt16host :: Putter Int16 putInt16host = tell . B.int16Host # INLINE putInt16host # | /O(1)./ Write a Int32 in native host order and host endianness . putInt32host :: Putter Int32 putInt32host = tell . B.int32Host # INLINE putInt32host # | /O(1)./ Write a Int64 in native host order On a 32 bit machine we write two host order Int32s , in big endian form . putInt64host :: Putter Int64 putInt64host = tell . B.int64Host # INLINE putInt64host # encodeListOf :: (a -> Builder) -> [a] -> Builder \xs -> execPut (putWord64be (fromIntegral $ length xs)) `M.mappend` F.foldMap f xs # INLINE encodeListOf # putTwoOf :: Putter a -> Putter b -> Putter (a,b) putTwoOf pa pb (a,b) = pa a >> pb b # INLINE putTwoOf # putListOf :: Putter a -> Putter [a] putListOf pa = \l -> do putWord64be (fromIntegral (length l)) mapM_ pa l # INLINE putListOf # putIArrayOf :: (Ix i, IArray a e) => Putter i -> Putter e -> Putter (a i e) putIArrayOf pix pe a = do putTwoOf pix pix (bounds a) putListOf pe (elems a) # INLINE putIArrayOf # putSeqOf :: Putter a -> Putter (Seq.Seq a) putSeqOf pa = \s -> do putWord64be (fromIntegral $ Seq.length s) F.mapM_ pa s # INLINE putSeqOf # putTreeOf :: Putter a -> Putter (T.Tree a) putTreeOf pa = tell . go where go (T.Node x cs) = execPut (pa x) `M.mappend` encodeListOf go cs # INLINE putTreeOf # putMapOf :: Putter k -> Putter a -> Putter (Map.Map k a) putMapOf pk pa = putListOf (putTwoOf pk pa) . Map.toAscList # INLINE putMapOf # putIntMapOf :: Putter Int -> Putter a -> Putter (IntMap.IntMap a) putIntMapOf pix pa = putListOf (putTwoOf pix pa) . IntMap.toAscList # INLINE putIntMapOf # putSetOf :: Putter a -> Putter (Set.Set a) putSetOf pa = putListOf pa . Set.toAscList # INLINE putSetOf # putIntSetOf :: Putter Int -> Putter IntSet.IntSet putIntSetOf pix = putListOf pix . IntSet.toAscList # INLINE putIntSetOf # putMaybeOf :: Putter a -> Putter (Maybe a) putMaybeOf _ Nothing = putWord8 0 putMaybeOf pa (Just a) = putWord8 1 >> pa a # INLINE putMaybeOf # putEitherOf :: Putter a -> Putter b -> Putter (Either a b) putEitherOf pa _ (Left a) = putWord8 0 >> pa a putEitherOf _ pb (Right b) = putWord8 1 >> pb b | Put a nested structure by first putting a length putNested :: Putter Int -> Put -> Put putNested putLen putVal = do let bs = runPut putVal putLen (S.length bs) putByteString bs # INLINE lazyToStrictByteString # lazyToStrictByteString :: L.ByteString -> S.ByteString #if MIN_VERSION_bytestring(0,10,0) lazyToStrictByteString = L.toStrict #else lazyToStrictByteString = packChunks packChunks :: L.ByteString -> S.ByteString packChunks lbs = S.unsafeCreate (fromIntegral $ L.length lbs) (copyChunks lbs) where copyChunks !L.Empty !_pf = return () copyChunks !(L.Chunk (S.PS fpbuf o l) lbs') !pf = do withForeignPtr fpbuf $ \pbuf -> copyBytes pf (pbuf `plusPtr` o) l copyChunks lbs' (pf `plusPtr` l) #endif
70d2a02590bd9784e6b3c7fe1171fe3c1f164ac1b106f309b63c627f1af44626
monadfix/ormolu-live
FileCleanup.hs
# LANGUAGE CPP # module FileCleanup ( TempFileLifetime(..) , cleanTempDirs, cleanTempFiles, cleanCurrentModuleTempFiles , addFilesToClean, changeTempFilesLifetime , newTempName, newTempLibName, newTempDir , withSystemTempDirectory, withTempDirectory ) where import GhcPrelude import DynFlags import ErrUtils import Outputable import Util import Exception import DriverPhases import Control.Monad import Data.List import qualified Data.Set as Set import qualified Data.Map as Map import Data.IORef import System.Directory import System.FilePath import System.IO.Error #if !defined(mingw32_HOST_OS) import qualified System.Posix.Internals #endif -- | Used when a temp file is created. This determines which component Set of -- FilesToClean will get the temp file data TempFileLifetime = TFL_CurrentModule -- ^ A file with lifetime TFL_CurrentModule will be cleaned up at the -- end of upweep_mod | TFL_GhcSession -- ^ A file with lifetime TFL_GhcSession will be cleaned up at the end of -- runGhc(T) deriving (Show) cleanTempDirs :: DynFlags -> IO () cleanTempDirs dflags = unless (gopt Opt_KeepTmpFiles dflags) $ mask_ $ do let ref = dirsToClean dflags ds <- atomicModifyIORef' ref $ \ds -> (Map.empty, ds) removeTmpDirs dflags (Map.elems ds) | Delete all files in @filesToClean dflags@. cleanTempFiles :: DynFlags -> IO () cleanTempFiles dflags = unless (gopt Opt_KeepTmpFiles dflags) $ mask_ $ do let ref = filesToClean dflags to_delete <- atomicModifyIORef' ref $ \FilesToClean { ftcCurrentModule = cm_files , ftcGhcSession = gs_files } -> ( emptyFilesToClean , Set.toList cm_files ++ Set.toList gs_files) removeTmpFiles dflags to_delete -- | Delete all files in @filesToClean dflags@. That have lifetime -- TFL_CurrentModule. -- If a file must be cleaned eventually, but must survive a -- cleanCurrentModuleTempFiles, ensure it has lifetime TFL_GhcSession. cleanCurrentModuleTempFiles :: DynFlags -> IO () cleanCurrentModuleTempFiles dflags = unless (gopt Opt_KeepTmpFiles dflags) $ mask_ $ do let ref = filesToClean dflags to_delete <- atomicModifyIORef' ref $ \ftc@FilesToClean{ftcCurrentModule = cm_files} -> (ftc {ftcCurrentModule = Set.empty}, Set.toList cm_files) removeTmpFiles dflags to_delete -- | Ensure that new_files are cleaned on the next call of -- 'cleanTempFiles' or 'cleanCurrentModuleTempFiles', depending on lifetime. -- If any of new_files are already tracked, they will have their lifetime -- updated. addFilesToClean :: DynFlags -> TempFileLifetime -> [FilePath] -> IO () addFilesToClean dflags lifetime new_files = modifyIORef' (filesToClean dflags) $ \FilesToClean { ftcCurrentModule = cm_files , ftcGhcSession = gs_files } -> case lifetime of TFL_CurrentModule -> FilesToClean { ftcCurrentModule = cm_files `Set.union` new_files_set , ftcGhcSession = gs_files `Set.difference` new_files_set } TFL_GhcSession -> FilesToClean { ftcCurrentModule = cm_files `Set.difference` new_files_set , ftcGhcSession = gs_files `Set.union` new_files_set } where new_files_set = Set.fromList new_files -- | Update the lifetime of files already being tracked. If any files are -- not being tracked they will be discarded. changeTempFilesLifetime :: DynFlags -> TempFileLifetime -> [FilePath] -> IO () changeTempFilesLifetime dflags lifetime files = do FilesToClean { ftcCurrentModule = cm_files , ftcGhcSession = gs_files } <- readIORef (filesToClean dflags) let old_set = case lifetime of TFL_CurrentModule -> gs_files TFL_GhcSession -> cm_files existing_files = [f | f <- files, f `Set.member` old_set] addFilesToClean dflags lifetime existing_files -- Return a unique numeric temp file suffix newTempSuffix :: DynFlags -> IO Int newTempSuffix dflags = atomicModifyIORef' (nextTempSuffix dflags) $ \n -> (n+1,n) -- Find a temporary name that doesn't already exist. newTempName :: DynFlags -> TempFileLifetime -> Suffix -> IO FilePath newTempName dflags lifetime extn = do d <- getTempDir dflags findTempName (d </> "ghc_") -- See Note [Deterministic base name] where findTempName :: FilePath -> IO FilePath findTempName prefix = do n <- newTempSuffix dflags let filename = prefix ++ show n <.> extn b <- doesFileExist filename if b then findTempName prefix else do -- clean it up later addFilesToClean dflags lifetime [filename] return filename newTempDir :: DynFlags -> IO FilePath newTempDir dflags = do d <- getTempDir dflags findTempDir (d </> "ghc_") where findTempDir :: FilePath -> IO FilePath findTempDir prefix = do n <- newTempSuffix dflags let filename = prefix ++ show n b <- doesDirectoryExist filename if b then findTempDir prefix else do createDirectory filename see mkTempDir below ; this is wrong : - > consIORef ( ) filename return filename newTempLibName :: DynFlags -> TempFileLifetime -> Suffix -> IO (FilePath, FilePath, String) newTempLibName dflags lifetime extn = do d <- getTempDir dflags findTempName d ("ghc_") where findTempName :: FilePath -> String -> IO (FilePath, FilePath, String) findTempName dir prefix = do n <- newTempSuffix dflags -- See Note [Deterministic base name] let libname = prefix ++ show n filename = dir </> "lib" ++ libname <.> extn b <- doesFileExist filename if b then findTempName dir prefix else do -- clean it up later addFilesToClean dflags lifetime [filename] return (filename, dir, libname) -- Return our temporary directory within tmp_dir, creating one if we -- don't have one yet. getTempDir :: DynFlags -> IO FilePath getTempDir dflags = do mapping <- readIORef dir_ref case Map.lookup tmp_dir mapping of Nothing -> do pid <- getProcessID let prefix = tmp_dir </> "ghc" ++ show pid ++ "_" mask_ $ mkTempDir prefix Just dir -> return dir where tmp_dir = tmpDir dflags dir_ref = dirsToClean dflags mkTempDir :: FilePath -> IO FilePath mkTempDir prefix = do n <- newTempSuffix dflags let our_dir = prefix ++ show n 1 . Speculatively create our new directory . createDirectory our_dir 2 . Update the dirsToClean mapping unless an entry already exists -- (i.e. unless another thread beat us to it). their_dir <- atomicModifyIORef' dir_ref $ \mapping -> case Map.lookup tmp_dir mapping of Just dir -> (mapping, Just dir) Nothing -> (Map.insert tmp_dir our_dir mapping, Nothing) 3 . If there was an existing entry , return it and delete the -- directory we created. Otherwise return the directory we created. case their_dir of Nothing -> do debugTraceMsg dflags 2 $ text "Created temporary directory:" <+> text our_dir return our_dir Just dir -> do removeDirectory our_dir return dir `catchIO` \e -> if isAlreadyExistsError e then mkTempDir prefix else ioError e Note [ Deterministic base name ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The filename of temporary files , especially the basename of C files , can end up in the output in some form , e.g. as part of linker debug information . In the interest of bit - wise exactly reproducible compilation ( # 4012 ) , the basename of the temporary file no longer contains random information ( it used to contain the process i d ) . This is ok , as the temporary directory used contains the pid ( see getTempDir ) . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The filename of temporary files, especially the basename of C files, can end up in the output in some form, e.g. as part of linker debug information. In the interest of bit-wise exactly reproducible compilation (#4012), the basename of the temporary file no longer contains random information (it used to contain the process id). This is ok, as the temporary directory used contains the pid (see getTempDir). -} removeTmpDirs :: DynFlags -> [FilePath] -> IO () removeTmpDirs dflags ds = traceCmd dflags "Deleting temp dirs" ("Deleting: " ++ unwords ds) (mapM_ (removeWith dflags removeDirectory) ds) removeTmpFiles :: DynFlags -> [FilePath] -> IO () removeTmpFiles dflags fs = warnNon $ traceCmd dflags "Deleting temp files" ("Deleting: " ++ unwords deletees) (mapM_ (removeWith dflags removeFile) deletees) where -- Flat out refuse to delete files that are likely to be source input -- files (is there a worse bug than having a compiler delete your source -- files?) -- -- Deleting source files is a sign of a bug elsewhere, so prominently flag -- the condition. warnNon act | null non_deletees = act | otherwise = do putMsg dflags (text "WARNING - NOT deleting source files:" <+> hsep (map text non_deletees)) act (non_deletees, deletees) = partition isHaskellUserSrcFilename fs removeWith :: DynFlags -> (FilePath -> IO ()) -> FilePath -> IO () removeWith dflags remover f = remover f `catchIO` (\e -> let msg = if isDoesNotExistError e then text "Warning: deleting non-existent" <+> text f else text "Warning: exception raised when deleting" <+> text f <> colon $$ text (show e) in debugTraceMsg dflags 2 msg ) #if defined(mingw32_HOST_OS) relies on Int = = Int32 on Windows foreign import ccall unsafe "_getpid" getProcessID :: IO Int #else getProcessID :: IO Int getProcessID = System.Posix.Internals.c_getpid >>= return . fromIntegral #endif The following three functions are from the ` temporary ` package . -- | Create and use a temporary directory in the system standard temporary -- directory. -- Behaves exactly the same as ' withTempDirectory ' , except that the parent -- temporary directory will be that returned by 'getTemporaryDirectory'. withSystemTempDirectory :: String -- ^ Directory name template. See 'openTempFile'. -> (FilePath -> IO a) -- ^ Callback that can use the directory -> IO a withSystemTempDirectory template action = getTemporaryDirectory >>= \tmpDir -> withTempDirectory tmpDir template action -- | Create and use a temporary directory. -- -- Creates a new temporary directory inside the given directory, making use -- of the template. The temp directory is deleted after use. For example: -- -- > withTempDirectory "src" "sdist." $ \tmpDir -> do ... -- -- The @tmpDir@ will be a new subdirectory of the given directory, e.g. -- @src/sdist.342@. withTempDirectory :: FilePath -- ^ Temp directory to create the directory in -> String -- ^ Directory name template. See 'openTempFile'. -> (FilePath -> IO a) -- ^ Callback that can use the directory -> IO a withTempDirectory targetDir template = Exception.bracket (createTempDirectory targetDir template) (ignoringIOErrors . removeDirectoryRecursive) ignoringIOErrors :: IO () -> IO () ignoringIOErrors ioe = ioe `catch` (\e -> const (return ()) (e :: IOError)) createTempDirectory :: FilePath -> String -> IO FilePath createTempDirectory dir template = do pid <- getProcessID findTempName pid where findTempName x = do let path = dir </> template ++ show x createDirectory path return path `catchIO` \e -> if isAlreadyExistsError e then findTempName (x+1) else ioError e
null
https://raw.githubusercontent.com/monadfix/ormolu-live/d8ae72ef168b98a8d179d642f70352c88b3ac226/ghc-lib-parser-8.10.1.20200412/compiler/main/FileCleanup.hs
haskell
| Used when a temp file is created. This determines which component Set of FilesToClean will get the temp file ^ A file with lifetime TFL_CurrentModule will be cleaned up at the end of upweep_mod ^ A file with lifetime TFL_GhcSession will be cleaned up at the end of runGhc(T) | Delete all files in @filesToClean dflags@. That have lifetime TFL_CurrentModule. If a file must be cleaned eventually, but must survive a cleanCurrentModuleTempFiles, ensure it has lifetime TFL_GhcSession. | Ensure that new_files are cleaned on the next call of 'cleanTempFiles' or 'cleanCurrentModuleTempFiles', depending on lifetime. If any of new_files are already tracked, they will have their lifetime updated. | Update the lifetime of files already being tracked. If any files are not being tracked they will be discarded. Return a unique numeric temp file suffix Find a temporary name that doesn't already exist. See Note [Deterministic base name] clean it up later See Note [Deterministic base name] clean it up later Return our temporary directory within tmp_dir, creating one if we don't have one yet. (i.e. unless another thread beat us to it). directory we created. Otherwise return the directory we created. Flat out refuse to delete files that are likely to be source input files (is there a worse bug than having a compiler delete your source files?) Deleting source files is a sign of a bug elsewhere, so prominently flag the condition. | Create and use a temporary directory in the system standard temporary directory. temporary directory will be that returned by 'getTemporaryDirectory'. ^ Directory name template. See 'openTempFile'. ^ Callback that can use the directory | Create and use a temporary directory. Creates a new temporary directory inside the given directory, making use of the template. The temp directory is deleted after use. For example: > withTempDirectory "src" "sdist." $ \tmpDir -> do ... The @tmpDir@ will be a new subdirectory of the given directory, e.g. @src/sdist.342@. ^ Temp directory to create the directory in ^ Directory name template. See 'openTempFile'. ^ Callback that can use the directory
# LANGUAGE CPP # module FileCleanup ( TempFileLifetime(..) , cleanTempDirs, cleanTempFiles, cleanCurrentModuleTempFiles , addFilesToClean, changeTempFilesLifetime , newTempName, newTempLibName, newTempDir , withSystemTempDirectory, withTempDirectory ) where import GhcPrelude import DynFlags import ErrUtils import Outputable import Util import Exception import DriverPhases import Control.Monad import Data.List import qualified Data.Set as Set import qualified Data.Map as Map import Data.IORef import System.Directory import System.FilePath import System.IO.Error #if !defined(mingw32_HOST_OS) import qualified System.Posix.Internals #endif data TempFileLifetime = TFL_CurrentModule | TFL_GhcSession deriving (Show) cleanTempDirs :: DynFlags -> IO () cleanTempDirs dflags = unless (gopt Opt_KeepTmpFiles dflags) $ mask_ $ do let ref = dirsToClean dflags ds <- atomicModifyIORef' ref $ \ds -> (Map.empty, ds) removeTmpDirs dflags (Map.elems ds) | Delete all files in @filesToClean dflags@. cleanTempFiles :: DynFlags -> IO () cleanTempFiles dflags = unless (gopt Opt_KeepTmpFiles dflags) $ mask_ $ do let ref = filesToClean dflags to_delete <- atomicModifyIORef' ref $ \FilesToClean { ftcCurrentModule = cm_files , ftcGhcSession = gs_files } -> ( emptyFilesToClean , Set.toList cm_files ++ Set.toList gs_files) removeTmpFiles dflags to_delete cleanCurrentModuleTempFiles :: DynFlags -> IO () cleanCurrentModuleTempFiles dflags = unless (gopt Opt_KeepTmpFiles dflags) $ mask_ $ do let ref = filesToClean dflags to_delete <- atomicModifyIORef' ref $ \ftc@FilesToClean{ftcCurrentModule = cm_files} -> (ftc {ftcCurrentModule = Set.empty}, Set.toList cm_files) removeTmpFiles dflags to_delete addFilesToClean :: DynFlags -> TempFileLifetime -> [FilePath] -> IO () addFilesToClean dflags lifetime new_files = modifyIORef' (filesToClean dflags) $ \FilesToClean { ftcCurrentModule = cm_files , ftcGhcSession = gs_files } -> case lifetime of TFL_CurrentModule -> FilesToClean { ftcCurrentModule = cm_files `Set.union` new_files_set , ftcGhcSession = gs_files `Set.difference` new_files_set } TFL_GhcSession -> FilesToClean { ftcCurrentModule = cm_files `Set.difference` new_files_set , ftcGhcSession = gs_files `Set.union` new_files_set } where new_files_set = Set.fromList new_files changeTempFilesLifetime :: DynFlags -> TempFileLifetime -> [FilePath] -> IO () changeTempFilesLifetime dflags lifetime files = do FilesToClean { ftcCurrentModule = cm_files , ftcGhcSession = gs_files } <- readIORef (filesToClean dflags) let old_set = case lifetime of TFL_CurrentModule -> gs_files TFL_GhcSession -> cm_files existing_files = [f | f <- files, f `Set.member` old_set] addFilesToClean dflags lifetime existing_files newTempSuffix :: DynFlags -> IO Int newTempSuffix dflags = atomicModifyIORef' (nextTempSuffix dflags) $ \n -> (n+1,n) newTempName :: DynFlags -> TempFileLifetime -> Suffix -> IO FilePath newTempName dflags lifetime extn = do d <- getTempDir dflags where findTempName :: FilePath -> IO FilePath findTempName prefix = do n <- newTempSuffix dflags let filename = prefix ++ show n <.> extn b <- doesFileExist filename if b then findTempName prefix addFilesToClean dflags lifetime [filename] return filename newTempDir :: DynFlags -> IO FilePath newTempDir dflags = do d <- getTempDir dflags findTempDir (d </> "ghc_") where findTempDir :: FilePath -> IO FilePath findTempDir prefix = do n <- newTempSuffix dflags let filename = prefix ++ show n b <- doesDirectoryExist filename if b then findTempDir prefix else do createDirectory filename see mkTempDir below ; this is wrong : - > consIORef ( ) filename return filename newTempLibName :: DynFlags -> TempFileLifetime -> Suffix -> IO (FilePath, FilePath, String) newTempLibName dflags lifetime extn = do d <- getTempDir dflags findTempName d ("ghc_") where findTempName :: FilePath -> String -> IO (FilePath, FilePath, String) findTempName dir prefix let libname = prefix ++ show n filename = dir </> "lib" ++ libname <.> extn b <- doesFileExist filename if b then findTempName dir prefix addFilesToClean dflags lifetime [filename] return (filename, dir, libname) getTempDir :: DynFlags -> IO FilePath getTempDir dflags = do mapping <- readIORef dir_ref case Map.lookup tmp_dir mapping of Nothing -> do pid <- getProcessID let prefix = tmp_dir </> "ghc" ++ show pid ++ "_" mask_ $ mkTempDir prefix Just dir -> return dir where tmp_dir = tmpDir dflags dir_ref = dirsToClean dflags mkTempDir :: FilePath -> IO FilePath mkTempDir prefix = do n <- newTempSuffix dflags let our_dir = prefix ++ show n 1 . Speculatively create our new directory . createDirectory our_dir 2 . Update the dirsToClean mapping unless an entry already exists their_dir <- atomicModifyIORef' dir_ref $ \mapping -> case Map.lookup tmp_dir mapping of Just dir -> (mapping, Just dir) Nothing -> (Map.insert tmp_dir our_dir mapping, Nothing) 3 . If there was an existing entry , return it and delete the case their_dir of Nothing -> do debugTraceMsg dflags 2 $ text "Created temporary directory:" <+> text our_dir return our_dir Just dir -> do removeDirectory our_dir return dir `catchIO` \e -> if isAlreadyExistsError e then mkTempDir prefix else ioError e Note [ Deterministic base name ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The filename of temporary files , especially the basename of C files , can end up in the output in some form , e.g. as part of linker debug information . In the interest of bit - wise exactly reproducible compilation ( # 4012 ) , the basename of the temporary file no longer contains random information ( it used to contain the process i d ) . This is ok , as the temporary directory used contains the pid ( see getTempDir ) . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The filename of temporary files, especially the basename of C files, can end up in the output in some form, e.g. as part of linker debug information. In the interest of bit-wise exactly reproducible compilation (#4012), the basename of the temporary file no longer contains random information (it used to contain the process id). This is ok, as the temporary directory used contains the pid (see getTempDir). -} removeTmpDirs :: DynFlags -> [FilePath] -> IO () removeTmpDirs dflags ds = traceCmd dflags "Deleting temp dirs" ("Deleting: " ++ unwords ds) (mapM_ (removeWith dflags removeDirectory) ds) removeTmpFiles :: DynFlags -> [FilePath] -> IO () removeTmpFiles dflags fs = warnNon $ traceCmd dflags "Deleting temp files" ("Deleting: " ++ unwords deletees) (mapM_ (removeWith dflags removeFile) deletees) where warnNon act | null non_deletees = act | otherwise = do putMsg dflags (text "WARNING - NOT deleting source files:" <+> hsep (map text non_deletees)) act (non_deletees, deletees) = partition isHaskellUserSrcFilename fs removeWith :: DynFlags -> (FilePath -> IO ()) -> FilePath -> IO () removeWith dflags remover f = remover f `catchIO` (\e -> let msg = if isDoesNotExistError e then text "Warning: deleting non-existent" <+> text f else text "Warning: exception raised when deleting" <+> text f <> colon $$ text (show e) in debugTraceMsg dflags 2 msg ) #if defined(mingw32_HOST_OS) relies on Int = = Int32 on Windows foreign import ccall unsafe "_getpid" getProcessID :: IO Int #else getProcessID :: IO Int getProcessID = System.Posix.Internals.c_getpid >>= return . fromIntegral #endif The following three functions are from the ` temporary ` package . Behaves exactly the same as ' withTempDirectory ' , except that the parent -> IO a withSystemTempDirectory template action = getTemporaryDirectory >>= \tmpDir -> withTempDirectory tmpDir template action -> IO a withTempDirectory targetDir template = Exception.bracket (createTempDirectory targetDir template) (ignoringIOErrors . removeDirectoryRecursive) ignoringIOErrors :: IO () -> IO () ignoringIOErrors ioe = ioe `catch` (\e -> const (return ()) (e :: IOError)) createTempDirectory :: FilePath -> String -> IO FilePath createTempDirectory dir template = do pid <- getProcessID findTempName pid where findTempName x = do let path = dir </> template ++ show x createDirectory path return path `catchIO` \e -> if isAlreadyExistsError e then findTempName (x+1) else ioError e
e8785a0d7a05fcbea0e9e807d7edc2c65741cd4c2034db0a00f68319f05c6472
mirage/mirage
mirage_impl_misc.mli
open Functoria module Log : Logs.LOG val get_target : Info.t -> Mirage_key.mode val connect_err : string -> int -> string val pp_key : Format.formatter -> 'a Key.key -> unit val query_ocamlfind : ?recursive:bool -> ?format:string -> ?predicates:string -> string list -> string list Action.t val opam_prefix : string Action.t Lazy.t val extra_c_artifacts : string -> string list -> string list Action.t val terminal : unit -> bool
null
https://raw.githubusercontent.com/mirage/mirage/479e40ae6aa1efe18fb1cd199cec0d5ee1f46f26/lib/mirage/impl/mirage_impl_misc.mli
ocaml
open Functoria module Log : Logs.LOG val get_target : Info.t -> Mirage_key.mode val connect_err : string -> int -> string val pp_key : Format.formatter -> 'a Key.key -> unit val query_ocamlfind : ?recursive:bool -> ?format:string -> ?predicates:string -> string list -> string list Action.t val opam_prefix : string Action.t Lazy.t val extra_c_artifacts : string -> string list -> string list Action.t val terminal : unit -> bool
283d431e4aefdab55a8b2f8ce86da9736ef10b3ddb72a7cb8cf3e5ea48fc6805
cac-t-u-s/om-sharp
midi-mix.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ File author : ;============================================================================ (in-package :om) ;================================================ ;=== CHANNEL CONTROLLER ;=== a single track controller ;================================================ (defclass channel-controls () ((midiport :initform nil :initarg :midiport :accessor midiport :type integer) (midichannel :initform 1 :initarg :midichannel :accessor midichannel :type integer) (program :initform 0 :initarg :program :accessor program :type integer) (pan-ctrl :initform 64 :initarg :pan-ctrl :accessor pan-ctrl :type integer) (control1-num :initform 1 :initarg :control1-num :accessor control1-num :type integer) (control2-num :initform 2 :initarg :control2-num :accessor control2-num :type integer) (control1-val :initform 0 :initarg :control1-val :accessor control1-val :type integer) (control2-val :initform 0 :initarg :control2-val :accessor control2-val :type integer) (vol-ctrl :initform 100 :initarg :vol-ctrl :accessor vol-ctrl :type integer) (pitch-ctrl :initform 8192 :initarg :pitch-ctrl :accessor pitch-ctrl :type integer))) (defclass* midi-mix-console (data-frame) ((midiport :initform nil :accessor midiport :type integer :documentation "output port number") (miditrack :initform 0 :accessor miditrack) (channels-ctrl :initform nil :accessor channels-ctrl)) (:documentation "A container for a variety of settings applying to the 16 MIDI channels. The MIDI-MIX-CONSOLE editor offers a mixing-table-like UI to set MIDI controllers and either send them in real-time, or store them for use with MIDI containers along with other MIDI or score objects. Applies to port <port>, or to the default MIDI out port is <port> is NIL.")) (defmethod additional-class-attributes ((self midi-mix-console)) '(midiport)) (defmethod initialize-instance :after ((self midi-mix-console) &rest l) (declare (ignore args)) (setf (channels-ctrl self) (loop for i from 1 to 16 collect (make-instance 'channel-controls :midiport (midiport self) :midichannel i))) ) ;====================== ; GET-MIDIEVENTS ;====================== (defmethod! get-midievents ((self midi-mix-console) &optional test) (let ((evt-list (loop for chan-ctrl in (channels-ctrl self) append (get-midievents chan-ctrl test)))) (when (miditrack self) (setf evt-list (loop for tr in (list! (miditrack self)) append (loop for evt in evt-list collect (let ((new-ev (clone evt))) (setf (ev-track new-ev) tr) new-ev)))) ) ;;; in case the test had to do with track number... ? (get-midievents evt-list test))) (defmethod! get-midievents ((self channel-controls) &optional test) (list (make-midievent :ev-date 0 :ev-type :ProgChange :ev-chan (midichannel self) :ev-port (midiport self) :ev-values (list (program self))) (make-midievent :ev-date 0 :ev-type :CtrlChange :ev-chan (midichannel self) :ev-port (midiport self) :ev-values (list 7 (vol-ctrl self))) (make-midievent :ev-date 0 :ev-type :CtrlChange :ev-chan (midichannel self) :ev-port (midiport self) :ev-values (list 10 (pan-ctrl self))) (make-midievent :ev-date 0 :ev-type :PitchBend :ev-chan (midichannel self) :ev-port (midiport self) :ev-values (val2lsbmsb (pitch-ctrl self))) (make-midievent :ev-date 0 :ev-type :CtrlChange :ev-chan (midichannel self) :ev-port (midiport self) :ev-values (list (control1-num self) (control1-val self))) (make-midievent :ev-date 0 :ev-type :CtrlChange :ev-chan (midichannel self) :ev-port (midiport self) :ev-values (list (control2-num self) (control2-val self))) )) ;================================= ; SENDING CONTROLLER MIDI ;================================= (defmethod channel-send-prog ((self channel-controls)) (let ((event (om-midi::make-midi-evt :type :ProgChange :chan (midichannel self) :port (or (midiport self) (get-pref-value :midi :out-port)) :fields (list (program self))))) (om-midi::midi-send-evt event) t)) (defmethod channel-send-vol ((self channel-controls)) (let ((event (om-midi::make-midi-evt :type :CtrlChange :chan (midichannel self) :port (or (midiport self) (get-pref-value :midi :out-port)) :fields (list 7 (vol-ctrl self))))) (om-midi::midi-send-evt event) t)) (defmethod channel-send-pan ((self channel-controls)) (let ((event (om-midi::make-midi-evt :type :CtrlChange :chan (midichannel self) :port (or (midiport self) (get-pref-value :midi :out-port)) :fields (list 10 (pan-ctrl self))))) (om-midi::midi-send-evt event) t)) (defmethod channel-send-ct1 ((self channel-controls)) (let ((event (om-midi::make-midi-evt :type :CtrlChange :chan (midichannel self) :port (or (midiport self) (get-pref-value :midi :out-port)) :fields (list (control1-num self) (control1-val self))))) (om-midi::midi-send-evt event) t)) (defmethod channel-send-ct2 ((self channel-controls)) (let ((event (om-midi::make-midi-evt :type :CtrlChange :chan (midichannel self) :port (or (midiport self) (get-pref-value :midi :out-port)) :fields (list (control2-num self) (control2-val self))))) (om-midi::midi-send-evt event) t)) (defmethod channel-send-pitch ((self channel-controls)) (let ((event (om-midi::make-midi-evt :type :PitchBend :chan (midichannel self) :port (or (midiport self) (get-pref-value :midi :out-port)) :fields (pitch-ctrl self)))) (om-midi::midi-send-evt event) t)) (defmethod send-midi-settings ((self channel-controls)) (channel-send-prog self) (channel-send-vol self) (channel-send-pan self) (channel-send-ct1 self) (channel-send-ct2 self) (channel-send-pitch self)) (defmethod send-midi-settings ((self midi-mix-console)) (loop for chan-ctrl in (channels-ctrl self) do (send-midi-settings chan-ctrl))) ;================================= ; PLAY ;================================= ;;; play in a DATA-TRACK (defmethod get-frame-action ((self midi-mix-console)) #'(lambda () (loop for e in (get-midievents self) do (funcall (get-frame-action e))) )) ;;; PLAY BY ITSELF IN A SEQUENCER... ;;; Interval is the interval INSIDE THE OBJECT (defmethod get-action-list-for-play ((self midi-mix-console) interval &optional parent) (when (in-interval 0 interval :exclude-high-bound t) (list (list 0 #'(lambda (obj) (funcall (get-frame-action obj))) (list self)) ))) ;================================= ; EDITOR ;================================= (defclass midi-mix-editor (omeditor) ((channel-panels :accessor channel-panels :initform nil))) (defmethod object-default-edition-params ((self midi-mix-console)) '((:auto-send t))) (defclass channel-panel (om-column-layout) ((channel-controller :initarg :channel-controller :accessor channel-controller :initform nil) (programMenu :initform nil :accessor programMenu) (volumeText :initform nil :accessor volumeText) (volumpeSlider :initform nil :accessor volumeSlider) (pitchText :initform nil :accessor pitchText) (pitchSlider :initform nil :accessor pitchSlider) (panText :initform nil :accessor panText) (panSlider :initform nil :accessor panSlider) (ctrl1menu :initform nil :accessor ctrl1menu) (ctrl1Val :initform nil :accessor ctrl1Val) (ctrl1Slider :initform nil :accessor ctrl1Slider) (ctrl2menu :initform nil :accessor ctrl2menu) (ctrl2Val :initform nil :accessor ctrl2Val) (ctrl2Slider :initform nil :accessor ctrl2Slider) )) (defmethod object-has-editor ((self midi-mix-console)) t) (defmethod get-editor-class ((self midi-mix-console)) 'midi-mix-editor) (defmethod editor-view-class ((self midi-mix-editor)) 'channel-panel) (defmethod get-obj-to-play ((self midi-mix-editor)) (object-value self)) ;============================== ; ACTIONS ON CHANNEL PANELS: ;============================== (defun pan2str (panvalue) (let* ((value (- panvalue 64)) (new-str (cond ((= value 0) (number-to-string value)) ((< value 0) (format nil "L~D" (- value))) ((> value 0) (format nil "R~D" value))))) new-str)) (defmethod set-values-on-panel ((cc channel-controls) (panel channel-panel)) (om-set-selected-item (programMenu panel) (number-to-name (program cc) *midi-gm-programs*)) (om-set-slider-value (panSlider panel) (pan-ctrl cc)) (om-set-dialog-item-text (panText panel) (string+ "Pan " (pan2str (pan-ctrl cc)))) (om-set-slider-value (volumeSlider panel) (vol-ctrl cc)) (om-set-dialog-item-text (volumeText panel) (format nil "Vol ~D" (vol-ctrl cc))) (om-set-slider-value (pitchSlider panel) (pitch-ctrl cc)) (om-set-dialog-item-text (pitchText panel) (format nil "Pitch ~4D mc" (pitchwheel-to-mc (pitch-ctrl cc)))) (om-set-selected-item (ctrl1Menu panel) (number-to-name (control1-num cc) *midi-controllers*)) (om-set-slider-value (ctrl1Slider panel) (control1-val cc)) (om-set-dialog-item-text (ctrl1Val panel) (number-to-string (control1-val cc))) (om-set-selected-item (ctrl2Menu panel) (number-to-name (control2-num cc) *midi-controllers*)) (om-set-slider-value (ctrl2Slider panel) (control2-val cc)) (om-set-dialog-item-text (ctrl2Val panel) (number-to-string (control1-val cc))) ) ;;; change program from menu (defmethod change-channel-program ((self channel-panel) editor value) (let ((cc (channel-controller self))) (setf (program cc) value) (report-modifications editor) (when (editor-get-edit-param editor :auto-send) (channel-send-prog cc)))) ;;; change pan from slider (defmethod change-channel-pan ((self channel-panel) editor value) (let ((cc (channel-controller self))) (unless (= value (pan-ctrl cc)) (setf (pan-ctrl cc) value) (om-set-dialog-item-text (panText self) (string+ "Pan " (pan2str value))) (report-modifications editor)) (when (editor-get-edit-param editor :auto-send) (channel-send-pan cc)))) (defmethod change-channel-vol ((self channel-panel) editor value) (let ((cc (channel-controller self))) (unless (= value (pan-ctrl cc)) (setf (vol-ctrl cc) value) (om-set-dialog-item-text (VolumeText self) (format nil "Vol ~D" value)) (report-modifications editor)) (when (editor-get-edit-param editor :auto-send) (channel-send-vol cc)) )) (defmethod change-channel-pitchbend ((self channel-panel) editor value) (let ((cc (channel-controller self))) (unless (= value (pitch-ctrl cc)) (setf (pitch-ctrl cc) value) (om-set-dialog-item-text (PitchText self) (format nil "Pitch ~4D mc" (pitchwheel-to-mc value))) (report-modifications editor)) (when (editor-get-edit-param editor :auto-send) (channel-send-pitch cc)) )) change ctrl1 from menu (defmethod change-channel-ctrl1 ((self channel-panel) editor value) (let ((cc (channel-controller self))) (setf (control1-num cc) value) (report-modifications editor) (when (editor-get-edit-param editor :auto-send) (channel-send-ct1 cc)))) ;;; change ctrl2 from menu (defmethod change-channel-ctrl2 ((self channel-panel) editor value) (let ((cc (channel-controller self))) (setf (control2-num cc) value) (report-modifications editor) (when (editor-get-edit-param editor :auto-send) (channel-send-ct2 cc)))) ;;; change ctrl1 val from slider (defmethod change-channel-ctrl1-val ((self channel-panel) editor value) (let ((cc (channel-controller self))) (unless (= value (control1-val cc)) (setf (control1-val cc) value) (om-set-dialog-item-text (Ctrl1Val self) (format nil "~D" value)) (report-modifications editor)) (when (editor-get-edit-param editor :auto-send) (channel-send-ct1 cc)) )) change from slider (defmethod change-channel-ctrl2-val ((self channel-panel) editor value) (let ((cc (channel-controller self))) (unless (= value (control2-val cc)) (setf (control2-val cc) value) (om-set-dialog-item-text (Ctrl2Val self) (format nil "~D" value)) (report-modifications editor)) (when (editor-get-edit-param editor :auto-send) (channel-send-ct2 cc)) )) ;;; reset from button note : does n't reset the choic of CTL1 et CTL2 controllers probably should n't reset GM program either ... ? (defmethod reset-all-values ((self channel-panel) editor) (change-channel-program self editor 0) (om-set-selected-item (programMenu self) (number-to-name 0 *midi-gm-programs*)) (change-channel-pan self editor 64) (om-set-slider-value (panSlider self) 64) (change-channel-vol self editor 100) (om-set-slider-value (volumeSlider self) 100) (change-channel-pitchbend self editor 8192) (om-set-slider-value (pitchSlider self) 8192) (change-channel-ctrl1-val self editor 0) (om-set-slider-value (ctrl1Slider self) 0) (change-channel-ctrl2-val self editor 0) (om-set-slider-value (ctrl2Slider self) 0) ) (defmethod make-channel-track-view ((self channel-controls) editor) (let ((font (om-def-font :normal)) (w 80) (panel (om-make-layout 'channel-panel :align :center :channel-controller self))) (om-add-subviews panel (om-make-di 'om-simple-text :size (omp 16 20) :font (om-def-font :large-b) :text (format nil "~D" (midichannel self)) ) (setf (programMenu panel) (om-make-di 'om-popup-list :size (omp w 24) :font font :items (mapcar #'car *midi-gm-programs*) :value (number-to-name (program self) *midi-gm-programs*) :di-action #'(lambda (item) (change-channel-program panel editor (name-to-number (om-get-selected-item item) *midi-gm-programs*))) )) (setf (pantext panel) (om-make-di 'om-simple-text :size (omp w 20) :font font :text (string+ "Pan " (pan2str (pan-ctrl self))) )) (setf (panSlider panel) (om-make-di 'om-slider :size (om-make-point w 24) :di-action #'(lambda (item) (change-channel-pan panel editor (om-slider-value item))) :increment 1 :range '(0 127) :value (pan-ctrl self) :direction :horizontal :tick-side :none )) :separator (setf (volumetext panel) (om-make-di 'om-simple-text :size (omp 46 20) :font font :text (format nil "Vol ~D" (vol-ctrl self)) )) (setf (volumeSlider panel) (om-make-di 'om-slider :size (om-make-point 24 100) :di-action #'(lambda (item) (change-channel-vol panel editor (om-slider-value item))) :increment 1 :range '(0 127) :value (vol-ctrl self) :direction :vertical :tick-side :none )) :separator (setf (pitchtext panel) (om-make-di 'om-simple-text :size (omp w 20) :font font :text (format nil "Pitch ~4D mc" (pitchwheel-to-mc (pitch-ctrl self))) )) (setf (pitchSlider panel) (om-make-di 'om-slider :size (om-make-point w 24) :di-action #'(lambda (item) (change-channel-pitchbend panel editor (om-slider-value item))) :increment 1 :range '(0 16383) :value (pitch-ctrl self) :direction :horizontal :tick-side :none )) :separator (om-make-di 'om-simple-text :size (omp w 20) :font (om-def-font :normal) :text "Ctrl Changes" ) (setf (Ctrl1Menu panel) (om-make-di 'om-popup-list :size (omp w 24) :font font :items (mapcar #'car *midi-controllers*) :value (number-to-name (control1-num self) *midi-controllers*) :di-action #'(lambda (item) (change-channel-ctrl1 panel editor (name-to-number (om-get-selected-item item) *midi-controllers*))) )) (setf (Ctrl1Slider panel) (om-make-di 'om-slider :size (om-make-point w 24) :di-action #'(lambda (item) (change-channel-ctrl1-val panel editor (om-slider-value item))) :increment 1 :range '(0 127) :value (control1-val self) :direction :horizontal :tick-side :none )) (setf (Ctrl1Val panel) (om-make-di 'om-simple-text :size (omp w 20) :font font :text (format nil "~D" (control1-val self)) )) (setf (Ctrl2Menu panel) (om-make-di 'om-popup-list :size (omp w 24) :font font :items (mapcar #'car *midi-controllers*) :value (number-to-name (control2-num self) *midi-controllers*) :di-action #'(lambda (item) (change-channel-ctrl2 panel editor (name-to-number (om-get-selected-item item) *midi-controllers*))) )) (setf (Ctrl2Slider panel) (om-make-di 'om-slider :size (om-make-point w 24) :di-action #'(lambda (item) (change-channel-ctrl2-val panel editor (om-slider-value item))) :increment 1 :range '(0 127) :value (control2-val self) :direction :horizontal :tick-side :none )) (setf (Ctrl2Val panel) (om-make-di 'om-simple-text :size (omp w 20) :font font :text (format nil "~D" (control2-val self)) )) :separator (om-make-di 'om-button :text "Reset" :font font :size (omp 80 24) :di-action #'(lambda (item) (declare (ignore item)) (reset-all-values panel editor)) ) ;;; end add-subviews ) panel)) (defmethod make-editor-window-contents ((editor midi-mix-editor)) (let ((obj (object-value editor))) (setf (channel-panels editor) (cdr (loop for cc in (channels-ctrl obj) append (list :separator (make-channel-track-view cc editor))))) (let ((port-box ;;; needs to be enabled/disabled by other items... (om-make-graphic-object 'numbox :size (omp 40 20) :position (omp 0 0) :font (om-def-font :normal) :bg-color (om-def-color :white) :value (or (midiport obj) (get-pref-value :midi :out-port)) :enabled (midiport obj) :after-fun #'(lambda (item) (setf (midiport obj) (value item)) (report-modifications editor)) ))) (om-make-layout 'om-column-layout :subviews (list (om-make-layout 'om-row-layout :subviews (channel-panels editor)) :separator (om-make-layout 'om-row-layout :subviews (list (om-make-di 'om-check-box :size (omp 100 20) :font (om-def-font :normal) :text "Out MIDI port:" :checked-p (midiport obj) :di-action #'(lambda (item) (if (om-checked-p item) (progn (enable-numbox port-box t) (setf (midiport obj) (get-pref-value :midi :out-port))) (progn (set-value port-box (get-pref-value :midi :out-port)) (enable-numbox port-box nil) (setf (midiport obj) nil))) (report-modifications editor))) (om-make-view 'om-view :size (omp 80 20) :subviews (list port-box)) nil (om-make-di 'om-check-box :size (omp 120 20) :font (om-def-font :normal) :text "send on edit" :checked-p (editor-get-edit-param editor :auto-send) :di-action #'(lambda (item) (editor-set-edit-param editor :auto-send (om-checked-p item))) ) )) )) )))
null
https://raw.githubusercontent.com/cac-t-u-s/om-sharp/80f9537368471d0e6e4accdc9fff01ed277b879e/src/packages/midi/objects/midi-mix.lisp
lisp
============================================================================ om#: visual programming language for computer-assisted music composition ============================================================================ This program is free software. For information on usage and redistribution, see the "LICENSE" file in this distribution. 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. ============================================================================ ============================================================================ ================================================ === CHANNEL CONTROLLER === a single track controller ================================================ ====================== GET-MIDIEVENTS ====================== in case the test had to do with track number... ? ================================= SENDING CONTROLLER MIDI ================================= ================================= PLAY ================================= play in a DATA-TRACK PLAY BY ITSELF IN A SEQUENCER... Interval is the interval INSIDE THE OBJECT ================================= EDITOR ================================= ============================== ACTIONS ON CHANNEL PANELS: ============================== change program from menu change pan from slider change ctrl2 from menu change ctrl1 val from slider reset from button end add-subviews needs to be enabled/disabled by other items...
File author : (in-package :om) (defclass channel-controls () ((midiport :initform nil :initarg :midiport :accessor midiport :type integer) (midichannel :initform 1 :initarg :midichannel :accessor midichannel :type integer) (program :initform 0 :initarg :program :accessor program :type integer) (pan-ctrl :initform 64 :initarg :pan-ctrl :accessor pan-ctrl :type integer) (control1-num :initform 1 :initarg :control1-num :accessor control1-num :type integer) (control2-num :initform 2 :initarg :control2-num :accessor control2-num :type integer) (control1-val :initform 0 :initarg :control1-val :accessor control1-val :type integer) (control2-val :initform 0 :initarg :control2-val :accessor control2-val :type integer) (vol-ctrl :initform 100 :initarg :vol-ctrl :accessor vol-ctrl :type integer) (pitch-ctrl :initform 8192 :initarg :pitch-ctrl :accessor pitch-ctrl :type integer))) (defclass* midi-mix-console (data-frame) ((midiport :initform nil :accessor midiport :type integer :documentation "output port number") (miditrack :initform 0 :accessor miditrack) (channels-ctrl :initform nil :accessor channels-ctrl)) (:documentation "A container for a variety of settings applying to the 16 MIDI channels. The MIDI-MIX-CONSOLE editor offers a mixing-table-like UI to set MIDI controllers and either send them in real-time, or store them for use with MIDI containers along with other MIDI or score objects. Applies to port <port>, or to the default MIDI out port is <port> is NIL.")) (defmethod additional-class-attributes ((self midi-mix-console)) '(midiport)) (defmethod initialize-instance :after ((self midi-mix-console) &rest l) (declare (ignore args)) (setf (channels-ctrl self) (loop for i from 1 to 16 collect (make-instance 'channel-controls :midiport (midiport self) :midichannel i))) ) (defmethod! get-midievents ((self midi-mix-console) &optional test) (let ((evt-list (loop for chan-ctrl in (channels-ctrl self) append (get-midievents chan-ctrl test)))) (when (miditrack self) (setf evt-list (loop for tr in (list! (miditrack self)) append (loop for evt in evt-list collect (let ((new-ev (clone evt))) (setf (ev-track new-ev) tr) new-ev)))) ) (get-midievents evt-list test))) (defmethod! get-midievents ((self channel-controls) &optional test) (list (make-midievent :ev-date 0 :ev-type :ProgChange :ev-chan (midichannel self) :ev-port (midiport self) :ev-values (list (program self))) (make-midievent :ev-date 0 :ev-type :CtrlChange :ev-chan (midichannel self) :ev-port (midiport self) :ev-values (list 7 (vol-ctrl self))) (make-midievent :ev-date 0 :ev-type :CtrlChange :ev-chan (midichannel self) :ev-port (midiport self) :ev-values (list 10 (pan-ctrl self))) (make-midievent :ev-date 0 :ev-type :PitchBend :ev-chan (midichannel self) :ev-port (midiport self) :ev-values (val2lsbmsb (pitch-ctrl self))) (make-midievent :ev-date 0 :ev-type :CtrlChange :ev-chan (midichannel self) :ev-port (midiport self) :ev-values (list (control1-num self) (control1-val self))) (make-midievent :ev-date 0 :ev-type :CtrlChange :ev-chan (midichannel self) :ev-port (midiport self) :ev-values (list (control2-num self) (control2-val self))) )) (defmethod channel-send-prog ((self channel-controls)) (let ((event (om-midi::make-midi-evt :type :ProgChange :chan (midichannel self) :port (or (midiport self) (get-pref-value :midi :out-port)) :fields (list (program self))))) (om-midi::midi-send-evt event) t)) (defmethod channel-send-vol ((self channel-controls)) (let ((event (om-midi::make-midi-evt :type :CtrlChange :chan (midichannel self) :port (or (midiport self) (get-pref-value :midi :out-port)) :fields (list 7 (vol-ctrl self))))) (om-midi::midi-send-evt event) t)) (defmethod channel-send-pan ((self channel-controls)) (let ((event (om-midi::make-midi-evt :type :CtrlChange :chan (midichannel self) :port (or (midiport self) (get-pref-value :midi :out-port)) :fields (list 10 (pan-ctrl self))))) (om-midi::midi-send-evt event) t)) (defmethod channel-send-ct1 ((self channel-controls)) (let ((event (om-midi::make-midi-evt :type :CtrlChange :chan (midichannel self) :port (or (midiport self) (get-pref-value :midi :out-port)) :fields (list (control1-num self) (control1-val self))))) (om-midi::midi-send-evt event) t)) (defmethod channel-send-ct2 ((self channel-controls)) (let ((event (om-midi::make-midi-evt :type :CtrlChange :chan (midichannel self) :port (or (midiport self) (get-pref-value :midi :out-port)) :fields (list (control2-num self) (control2-val self))))) (om-midi::midi-send-evt event) t)) (defmethod channel-send-pitch ((self channel-controls)) (let ((event (om-midi::make-midi-evt :type :PitchBend :chan (midichannel self) :port (or (midiport self) (get-pref-value :midi :out-port)) :fields (pitch-ctrl self)))) (om-midi::midi-send-evt event) t)) (defmethod send-midi-settings ((self channel-controls)) (channel-send-prog self) (channel-send-vol self) (channel-send-pan self) (channel-send-ct1 self) (channel-send-ct2 self) (channel-send-pitch self)) (defmethod send-midi-settings ((self midi-mix-console)) (loop for chan-ctrl in (channels-ctrl self) do (send-midi-settings chan-ctrl))) (defmethod get-frame-action ((self midi-mix-console)) #'(lambda () (loop for e in (get-midievents self) do (funcall (get-frame-action e))) )) (defmethod get-action-list-for-play ((self midi-mix-console) interval &optional parent) (when (in-interval 0 interval :exclude-high-bound t) (list (list 0 #'(lambda (obj) (funcall (get-frame-action obj))) (list self)) ))) (defclass midi-mix-editor (omeditor) ((channel-panels :accessor channel-panels :initform nil))) (defmethod object-default-edition-params ((self midi-mix-console)) '((:auto-send t))) (defclass channel-panel (om-column-layout) ((channel-controller :initarg :channel-controller :accessor channel-controller :initform nil) (programMenu :initform nil :accessor programMenu) (volumeText :initform nil :accessor volumeText) (volumpeSlider :initform nil :accessor volumeSlider) (pitchText :initform nil :accessor pitchText) (pitchSlider :initform nil :accessor pitchSlider) (panText :initform nil :accessor panText) (panSlider :initform nil :accessor panSlider) (ctrl1menu :initform nil :accessor ctrl1menu) (ctrl1Val :initform nil :accessor ctrl1Val) (ctrl1Slider :initform nil :accessor ctrl1Slider) (ctrl2menu :initform nil :accessor ctrl2menu) (ctrl2Val :initform nil :accessor ctrl2Val) (ctrl2Slider :initform nil :accessor ctrl2Slider) )) (defmethod object-has-editor ((self midi-mix-console)) t) (defmethod get-editor-class ((self midi-mix-console)) 'midi-mix-editor) (defmethod editor-view-class ((self midi-mix-editor)) 'channel-panel) (defmethod get-obj-to-play ((self midi-mix-editor)) (object-value self)) (defun pan2str (panvalue) (let* ((value (- panvalue 64)) (new-str (cond ((= value 0) (number-to-string value)) ((< value 0) (format nil "L~D" (- value))) ((> value 0) (format nil "R~D" value))))) new-str)) (defmethod set-values-on-panel ((cc channel-controls) (panel channel-panel)) (om-set-selected-item (programMenu panel) (number-to-name (program cc) *midi-gm-programs*)) (om-set-slider-value (panSlider panel) (pan-ctrl cc)) (om-set-dialog-item-text (panText panel) (string+ "Pan " (pan2str (pan-ctrl cc)))) (om-set-slider-value (volumeSlider panel) (vol-ctrl cc)) (om-set-dialog-item-text (volumeText panel) (format nil "Vol ~D" (vol-ctrl cc))) (om-set-slider-value (pitchSlider panel) (pitch-ctrl cc)) (om-set-dialog-item-text (pitchText panel) (format nil "Pitch ~4D mc" (pitchwheel-to-mc (pitch-ctrl cc)))) (om-set-selected-item (ctrl1Menu panel) (number-to-name (control1-num cc) *midi-controllers*)) (om-set-slider-value (ctrl1Slider panel) (control1-val cc)) (om-set-dialog-item-text (ctrl1Val panel) (number-to-string (control1-val cc))) (om-set-selected-item (ctrl2Menu panel) (number-to-name (control2-num cc) *midi-controllers*)) (om-set-slider-value (ctrl2Slider panel) (control2-val cc)) (om-set-dialog-item-text (ctrl2Val panel) (number-to-string (control1-val cc))) ) (defmethod change-channel-program ((self channel-panel) editor value) (let ((cc (channel-controller self))) (setf (program cc) value) (report-modifications editor) (when (editor-get-edit-param editor :auto-send) (channel-send-prog cc)))) (defmethod change-channel-pan ((self channel-panel) editor value) (let ((cc (channel-controller self))) (unless (= value (pan-ctrl cc)) (setf (pan-ctrl cc) value) (om-set-dialog-item-text (panText self) (string+ "Pan " (pan2str value))) (report-modifications editor)) (when (editor-get-edit-param editor :auto-send) (channel-send-pan cc)))) (defmethod change-channel-vol ((self channel-panel) editor value) (let ((cc (channel-controller self))) (unless (= value (pan-ctrl cc)) (setf (vol-ctrl cc) value) (om-set-dialog-item-text (VolumeText self) (format nil "Vol ~D" value)) (report-modifications editor)) (when (editor-get-edit-param editor :auto-send) (channel-send-vol cc)) )) (defmethod change-channel-pitchbend ((self channel-panel) editor value) (let ((cc (channel-controller self))) (unless (= value (pitch-ctrl cc)) (setf (pitch-ctrl cc) value) (om-set-dialog-item-text (PitchText self) (format nil "Pitch ~4D mc" (pitchwheel-to-mc value))) (report-modifications editor)) (when (editor-get-edit-param editor :auto-send) (channel-send-pitch cc)) )) change ctrl1 from menu (defmethod change-channel-ctrl1 ((self channel-panel) editor value) (let ((cc (channel-controller self))) (setf (control1-num cc) value) (report-modifications editor) (when (editor-get-edit-param editor :auto-send) (channel-send-ct1 cc)))) (defmethod change-channel-ctrl2 ((self channel-panel) editor value) (let ((cc (channel-controller self))) (setf (control2-num cc) value) (report-modifications editor) (when (editor-get-edit-param editor :auto-send) (channel-send-ct2 cc)))) (defmethod change-channel-ctrl1-val ((self channel-panel) editor value) (let ((cc (channel-controller self))) (unless (= value (control1-val cc)) (setf (control1-val cc) value) (om-set-dialog-item-text (Ctrl1Val self) (format nil "~D" value)) (report-modifications editor)) (when (editor-get-edit-param editor :auto-send) (channel-send-ct1 cc)) )) change from slider (defmethod change-channel-ctrl2-val ((self channel-panel) editor value) (let ((cc (channel-controller self))) (unless (= value (control2-val cc)) (setf (control2-val cc) value) (om-set-dialog-item-text (Ctrl2Val self) (format nil "~D" value)) (report-modifications editor)) (when (editor-get-edit-param editor :auto-send) (channel-send-ct2 cc)) )) note : does n't reset the choic of CTL1 et CTL2 controllers probably should n't reset GM program either ... ? (defmethod reset-all-values ((self channel-panel) editor) (change-channel-program self editor 0) (om-set-selected-item (programMenu self) (number-to-name 0 *midi-gm-programs*)) (change-channel-pan self editor 64) (om-set-slider-value (panSlider self) 64) (change-channel-vol self editor 100) (om-set-slider-value (volumeSlider self) 100) (change-channel-pitchbend self editor 8192) (om-set-slider-value (pitchSlider self) 8192) (change-channel-ctrl1-val self editor 0) (om-set-slider-value (ctrl1Slider self) 0) (change-channel-ctrl2-val self editor 0) (om-set-slider-value (ctrl2Slider self) 0) ) (defmethod make-channel-track-view ((self channel-controls) editor) (let ((font (om-def-font :normal)) (w 80) (panel (om-make-layout 'channel-panel :align :center :channel-controller self))) (om-add-subviews panel (om-make-di 'om-simple-text :size (omp 16 20) :font (om-def-font :large-b) :text (format nil "~D" (midichannel self)) ) (setf (programMenu panel) (om-make-di 'om-popup-list :size (omp w 24) :font font :items (mapcar #'car *midi-gm-programs*) :value (number-to-name (program self) *midi-gm-programs*) :di-action #'(lambda (item) (change-channel-program panel editor (name-to-number (om-get-selected-item item) *midi-gm-programs*))) )) (setf (pantext panel) (om-make-di 'om-simple-text :size (omp w 20) :font font :text (string+ "Pan " (pan2str (pan-ctrl self))) )) (setf (panSlider panel) (om-make-di 'om-slider :size (om-make-point w 24) :di-action #'(lambda (item) (change-channel-pan panel editor (om-slider-value item))) :increment 1 :range '(0 127) :value (pan-ctrl self) :direction :horizontal :tick-side :none )) :separator (setf (volumetext panel) (om-make-di 'om-simple-text :size (omp 46 20) :font font :text (format nil "Vol ~D" (vol-ctrl self)) )) (setf (volumeSlider panel) (om-make-di 'om-slider :size (om-make-point 24 100) :di-action #'(lambda (item) (change-channel-vol panel editor (om-slider-value item))) :increment 1 :range '(0 127) :value (vol-ctrl self) :direction :vertical :tick-side :none )) :separator (setf (pitchtext panel) (om-make-di 'om-simple-text :size (omp w 20) :font font :text (format nil "Pitch ~4D mc" (pitchwheel-to-mc (pitch-ctrl self))) )) (setf (pitchSlider panel) (om-make-di 'om-slider :size (om-make-point w 24) :di-action #'(lambda (item) (change-channel-pitchbend panel editor (om-slider-value item))) :increment 1 :range '(0 16383) :value (pitch-ctrl self) :direction :horizontal :tick-side :none )) :separator (om-make-di 'om-simple-text :size (omp w 20) :font (om-def-font :normal) :text "Ctrl Changes" ) (setf (Ctrl1Menu panel) (om-make-di 'om-popup-list :size (omp w 24) :font font :items (mapcar #'car *midi-controllers*) :value (number-to-name (control1-num self) *midi-controllers*) :di-action #'(lambda (item) (change-channel-ctrl1 panel editor (name-to-number (om-get-selected-item item) *midi-controllers*))) )) (setf (Ctrl1Slider panel) (om-make-di 'om-slider :size (om-make-point w 24) :di-action #'(lambda (item) (change-channel-ctrl1-val panel editor (om-slider-value item))) :increment 1 :range '(0 127) :value (control1-val self) :direction :horizontal :tick-side :none )) (setf (Ctrl1Val panel) (om-make-di 'om-simple-text :size (omp w 20) :font font :text (format nil "~D" (control1-val self)) )) (setf (Ctrl2Menu panel) (om-make-di 'om-popup-list :size (omp w 24) :font font :items (mapcar #'car *midi-controllers*) :value (number-to-name (control2-num self) *midi-controllers*) :di-action #'(lambda (item) (change-channel-ctrl2 panel editor (name-to-number (om-get-selected-item item) *midi-controllers*))) )) (setf (Ctrl2Slider panel) (om-make-di 'om-slider :size (om-make-point w 24) :di-action #'(lambda (item) (change-channel-ctrl2-val panel editor (om-slider-value item))) :increment 1 :range '(0 127) :value (control2-val self) :direction :horizontal :tick-side :none )) (setf (Ctrl2Val panel) (om-make-di 'om-simple-text :size (omp w 20) :font font :text (format nil "~D" (control2-val self)) )) :separator (om-make-di 'om-button :text "Reset" :font font :size (omp 80 24) :di-action #'(lambda (item) (declare (ignore item)) (reset-all-values panel editor)) ) ) panel)) (defmethod make-editor-window-contents ((editor midi-mix-editor)) (let ((obj (object-value editor))) (setf (channel-panels editor) (cdr (loop for cc in (channels-ctrl obj) append (list :separator (make-channel-track-view cc editor))))) (om-make-graphic-object 'numbox :size (omp 40 20) :position (omp 0 0) :font (om-def-font :normal) :bg-color (om-def-color :white) :value (or (midiport obj) (get-pref-value :midi :out-port)) :enabled (midiport obj) :after-fun #'(lambda (item) (setf (midiport obj) (value item)) (report-modifications editor)) ))) (om-make-layout 'om-column-layout :subviews (list (om-make-layout 'om-row-layout :subviews (channel-panels editor)) :separator (om-make-layout 'om-row-layout :subviews (list (om-make-di 'om-check-box :size (omp 100 20) :font (om-def-font :normal) :text "Out MIDI port:" :checked-p (midiport obj) :di-action #'(lambda (item) (if (om-checked-p item) (progn (enable-numbox port-box t) (setf (midiport obj) (get-pref-value :midi :out-port))) (progn (set-value port-box (get-pref-value :midi :out-port)) (enable-numbox port-box nil) (setf (midiport obj) nil))) (report-modifications editor))) (om-make-view 'om-view :size (omp 80 20) :subviews (list port-box)) nil (om-make-di 'om-check-box :size (omp 120 20) :font (om-def-font :normal) :text "send on edit" :checked-p (editor-get-edit-param editor :auto-send) :di-action #'(lambda (item) (editor-set-edit-param editor :auto-send (om-checked-p item))) ) )) )) )))
16cd4438e856d3cc56e44c1b0f5cab45cf9ff6f29bb4e64f7ad4f25ad9456954
PacktWorkshops/The-Clojure-Workshop
utils.clj
(ns coffee-app.utils) ;;; orders calculating and formatting function (defn calculate-coffee-price [coffees coffee-type number] (-> (get coffees coffee-type) (* number) float)) (defn display-bought-coffee-message [type number total] (str "Buying " number " " (name type) " coffees for total:€" total))
null
https://raw.githubusercontent.com/PacktWorkshops/The-Clojure-Workshop/3d309bb0e46a41ce2c93737870433b47ce0ba6a2/Chapter09/tests/Exercise9.04/coffee-app/src/coffee_app/utils.clj
clojure
orders calculating and formatting function
(ns coffee-app.utils) (defn calculate-coffee-price [coffees coffee-type number] (-> (get coffees coffee-type) (* number) float)) (defn display-bought-coffee-message [type number total] (str "Buying " number " " (name type) " coffees for total:€" total))
74df5353373e9ed2e7b0f316a38fbed24cec1e0ebf6e3592c1ba3309012657ea
camsaul/toucan2
after_select.clj
(ns toucan2.tools.after-select (:require [clojure.spec.alpha :as s] [methodical.core :as m] [toucan2.pipeline :as pipeline] [toucan2.tools.simple-out-transform :as tools.simple-out-transform] [toucan2.util :as u])) (m/defmulti after-select {:arglists '([instance]), :defmethod-arities #{1}} u/dispatch-on-first-arg) ;;; Do after-select for anything returning instances, not just SELECT. [[toucan2.insert/insert-returning-instances!]] ;;; should do after-select as well. (tools.simple-out-transform/define-out-transform [:toucan.result-type/instances ::after-select] [instance] (if (isa? &query-type :toucan.query-type/select.instances-from-pks) instance (after-select instance))) (defmacro define-after-select {:style/indent :defn} [model [instance-binding] & body] `(do (u/maybe-derive ~model ::after-select) (m/defmethod after-select ~model [instance#] (let [~instance-binding (cond-> instance# ~'next-method ~'next-method)] ~@body)))) (s/fdef define-after-select :args (s/cat :model some? :bindings (s/spec (s/cat :instance :clojure.core.specs.alpha/binding-form)) :body (s/+ any?)) :ret any?) ;;; `after-select` should be done before [[toucan2.tools.after-update]] and [[toucan2.tools.after-insert]] (m/prefer-method! #'pipeline/results-transform [:toucan.result-type/instances ::after-select] [:toucan.result-type/instances :toucan2.tools.after/model])
null
https://raw.githubusercontent.com/camsaul/toucan2/5204b34d46f5adb3e52b022218049abe9b336928/src/toucan2/tools/after_select.clj
clojure
Do after-select for anything returning instances, not just SELECT. [[toucan2.insert/insert-returning-instances!]] should do after-select as well. `after-select` should be done before [[toucan2.tools.after-update]] and [[toucan2.tools.after-insert]]
(ns toucan2.tools.after-select (:require [clojure.spec.alpha :as s] [methodical.core :as m] [toucan2.pipeline :as pipeline] [toucan2.tools.simple-out-transform :as tools.simple-out-transform] [toucan2.util :as u])) (m/defmulti after-select {:arglists '([instance]), :defmethod-arities #{1}} u/dispatch-on-first-arg) (tools.simple-out-transform/define-out-transform [:toucan.result-type/instances ::after-select] [instance] (if (isa? &query-type :toucan.query-type/select.instances-from-pks) instance (after-select instance))) (defmacro define-after-select {:style/indent :defn} [model [instance-binding] & body] `(do (u/maybe-derive ~model ::after-select) (m/defmethod after-select ~model [instance#] (let [~instance-binding (cond-> instance# ~'next-method ~'next-method)] ~@body)))) (s/fdef define-after-select :args (s/cat :model some? :bindings (s/spec (s/cat :instance :clojure.core.specs.alpha/binding-form)) :body (s/+ any?)) :ret any?) (m/prefer-method! #'pipeline/results-transform [:toucan.result-type/instances ::after-select] [:toucan.result-type/instances :toucan2.tools.after/model])
744290b8ecaba75622b105d66e58cd2ddc5101ef640d4e41b9ed32cd94d1fc17
mbutterick/beautiful-racket
txtadv-reader.rkt
#lang racket (require syntax/readerr) (provide (rename-out [txtadv-read-syntax read-syntax])) (define (txtadv-read-syntax src in) (expect-section src in "VERBS") (define verbs (in-section src in read-verb)) (expect-section src in "EVERYWHERE") (define actions (in-section src in read-action)) (expect-section src in "THINGS") (define things (in-section src in read-thing)) (expect-section src in "PLACES") (define places (in-section src in read-place)) (datum->syntax #f `(module world "txtadv.rkt" (define-verbs all-verbs ,@verbs) (define-everywhere everywhere-actions ,actions) ,@things ,@places ,(if (null? places) (complain src in "no places defined") (cadar places))))) (define (complain src in msg) (define-values (line col pos) (port-next-location in)) (raise-read-error msg src line col pos 1)) (define (skip-whitespace in) (regexp-try-match #px"^\\s+" in)) (define (expect-section src in name) (skip-whitespace in) (unless (regexp-match-peek (pregexp (format "^===~a===\\s" name)) in) (complain src in (format "expected a ===~a=== section" name))) (read-line in) (read-line in)) (define (in-section src in reader) (skip-whitespace in) (if (or (regexp-match-peek #rx"^===" in) (eof-object? (peek-byte in))) null (cons (reader src in) (in-section src in reader)))) (define (in-defn src in reader) (skip-whitespace in) (if (or (regexp-match-peek #rx"^(===|---)" in) (eof-object? (peek-byte in))) null (cons (reader src in) (in-defn src in reader)))) (define (read-name src in) (if (regexp-match-peek #px"^[A-Za-z-]+(?=:$|\\s|[],])" in) (read-syntax src in) (complain src in "expected a name"))) (define (read-name-sequence src in transitive) (let loop ([names null] [transitive transitive]) (define s (read-name src in)) (define is-trans? (cond [(regexp-match-peek #rx"^ _" in) (if (or (eq? transitive 'unknown) (eq? transitive #t)) (begin (read-char in) (read-char in) #t) (begin (read-char in) (complain src in "unexpected underscore")))] [else (if (eq? transitive #t) (complain src in "inconsistent transitivity") #f)])) (if (regexp-match-peek #rx"^, " in) (begin (read-char in) (read-char in) (loop (cons s names) is-trans?)) (values (reverse (cons s names)) is-trans?)))) (define (read-verb src in) (skip-whitespace in) (define-values (names is-transitive?) (read-name-sequence src in 'unknown)) (skip-whitespace in) (define desc (if (regexp-match-peek #rx"^\"" in) (read-syntax src in) (symbol->string (syntax-e (car names))))) `[,(car names) ,@(if is-transitive? '(_) '()) (= ,@(cdr names)) ,desc]) (define (read-action src in) (skip-whitespace in) (define name (read-name src in)) (define expr (read-syntax src in)) `[,name ,expr]) (define (read-defn-name src in what) (skip-whitespace in) (unless (regexp-match-peek #px"^---[A-Za-z][A-Za-z0-9-]*---\\s" in) (complain src in (format "expected a ~a definition of the form ---name---" what))) (read-string 3 in) (define-values (line col pos) (port-next-location in)) (define name-str (bytes->string/utf-8 (cadr (regexp-match #px"^(.*?)---\\s" in)))) (datum->syntax #f (string->symbol name-str) (vector src line col pos (string-length name-str)) orig-props)) (define orig-props (read-syntax 'src (open-input-string "orig"))) (define (read-thing src in) (define name (read-defn-name src in "thing")) (define actions (in-defn src in read-action)) `(define-thing ,name ,@actions)) (define (read-place src in) (define name (read-defn-name src in "place")) (skip-whitespace in) (define desc (if (regexp-match-peek #rx"^\"" in) (read-syntax src in) (complain src in "expected description string"))) (skip-whitespace in) (unless (regexp-match-peek #rx"^[[]" in) (complain src in "expected a square bracket to start a list of things for a place")) (read-char in) (define-values (things _) (if (regexp-match-peek #rx"^[]]" in) (values null #f) (read-name-sequence src in #f))) (unless (regexp-match-peek #rx"^[]]" in) (complain src in "expected a square bracket to end a list of things for a place")) (read-char in) (define actions (in-defn src in read-action)) `(define-place ,name ,desc ,things ,actions))
null
https://raw.githubusercontent.com/mbutterick/beautiful-racket/f0e2cb5b325733b3f9cbd554cc7d2bb236af9ee9/beautiful-racket-demo/txtadv-demo/5-lang/txtadv-reader.rkt
racket
#lang racket (require syntax/readerr) (provide (rename-out [txtadv-read-syntax read-syntax])) (define (txtadv-read-syntax src in) (expect-section src in "VERBS") (define verbs (in-section src in read-verb)) (expect-section src in "EVERYWHERE") (define actions (in-section src in read-action)) (expect-section src in "THINGS") (define things (in-section src in read-thing)) (expect-section src in "PLACES") (define places (in-section src in read-place)) (datum->syntax #f `(module world "txtadv.rkt" (define-verbs all-verbs ,@verbs) (define-everywhere everywhere-actions ,actions) ,@things ,@places ,(if (null? places) (complain src in "no places defined") (cadar places))))) (define (complain src in msg) (define-values (line col pos) (port-next-location in)) (raise-read-error msg src line col pos 1)) (define (skip-whitespace in) (regexp-try-match #px"^\\s+" in)) (define (expect-section src in name) (skip-whitespace in) (unless (regexp-match-peek (pregexp (format "^===~a===\\s" name)) in) (complain src in (format "expected a ===~a=== section" name))) (read-line in) (read-line in)) (define (in-section src in reader) (skip-whitespace in) (if (or (regexp-match-peek #rx"^===" in) (eof-object? (peek-byte in))) null (cons (reader src in) (in-section src in reader)))) (define (in-defn src in reader) (skip-whitespace in) (if (or (regexp-match-peek #rx"^(===|---)" in) (eof-object? (peek-byte in))) null (cons (reader src in) (in-defn src in reader)))) (define (read-name src in) (if (regexp-match-peek #px"^[A-Za-z-]+(?=:$|\\s|[],])" in) (read-syntax src in) (complain src in "expected a name"))) (define (read-name-sequence src in transitive) (let loop ([names null] [transitive transitive]) (define s (read-name src in)) (define is-trans? (cond [(regexp-match-peek #rx"^ _" in) (if (or (eq? transitive 'unknown) (eq? transitive #t)) (begin (read-char in) (read-char in) #t) (begin (read-char in) (complain src in "unexpected underscore")))] [else (if (eq? transitive #t) (complain src in "inconsistent transitivity") #f)])) (if (regexp-match-peek #rx"^, " in) (begin (read-char in) (read-char in) (loop (cons s names) is-trans?)) (values (reverse (cons s names)) is-trans?)))) (define (read-verb src in) (skip-whitespace in) (define-values (names is-transitive?) (read-name-sequence src in 'unknown)) (skip-whitespace in) (define desc (if (regexp-match-peek #rx"^\"" in) (read-syntax src in) (symbol->string (syntax-e (car names))))) `[,(car names) ,@(if is-transitive? '(_) '()) (= ,@(cdr names)) ,desc]) (define (read-action src in) (skip-whitespace in) (define name (read-name src in)) (define expr (read-syntax src in)) `[,name ,expr]) (define (read-defn-name src in what) (skip-whitespace in) (unless (regexp-match-peek #px"^---[A-Za-z][A-Za-z0-9-]*---\\s" in) (complain src in (format "expected a ~a definition of the form ---name---" what))) (read-string 3 in) (define-values (line col pos) (port-next-location in)) (define name-str (bytes->string/utf-8 (cadr (regexp-match #px"^(.*?)---\\s" in)))) (datum->syntax #f (string->symbol name-str) (vector src line col pos (string-length name-str)) orig-props)) (define orig-props (read-syntax 'src (open-input-string "orig"))) (define (read-thing src in) (define name (read-defn-name src in "thing")) (define actions (in-defn src in read-action)) `(define-thing ,name ,@actions)) (define (read-place src in) (define name (read-defn-name src in "place")) (skip-whitespace in) (define desc (if (regexp-match-peek #rx"^\"" in) (read-syntax src in) (complain src in "expected description string"))) (skip-whitespace in) (unless (regexp-match-peek #rx"^[[]" in) (complain src in "expected a square bracket to start a list of things for a place")) (read-char in) (define-values (things _) (if (regexp-match-peek #rx"^[]]" in) (values null #f) (read-name-sequence src in #f))) (unless (regexp-match-peek #rx"^[]]" in) (complain src in "expected a square bracket to end a list of things for a place")) (read-char in) (define actions (in-defn src in read-action)) `(define-place ,name ,desc ,things ,actions))
962eefe326a2c4fbc6ebedb526c8c08ade194ec9b1b5d4d167d26457a0e6c5fc
wrengr/unification-fd
IntVar.hs
# LANGUAGE MultiParamTypeClasses , FlexibleInstances # {-# OPTIONS_GHC -Wall -fwarn-tabs #-} ---------------------------------------------------------------- -- ~ 2021.10.17 -- | -- Module : Control.Unification.IntVar Copyright : Copyright ( c ) 2007 - -2021 wren License : BSD -- Maintainer : -- Stability : experimental -- Portability : semi-portable (MPTCs, FlexibleInstances) -- -- This module defines a state monad for functional pointers -- represented by integers as keys into an @IntMap@. This technique was independently discovered by Dijkstra et al . This module -- extends the approach by using a state monad transformer, which -- can be made into a backtracking state monad by setting the underlying monad to some ' MonadLogic ' ( part of the @logict@ library , described by Kiselyov et al . ) . -- * , , ( 2008 ) /Efficient Functional Unification and Substitution/ , Technical Report UU - CS-2008 - 027 , Utrecht University . -- * , , , and ( 2005 ) /Backtracking , Interleaving , and/ /Terminating Monad Transformers/ , ICFP . ---------------------------------------------------------------- module Control.Unification.IntVar ( IntVar() , IntBindingState() , IntBindingT() , runIntBindingT , evalIntBindingT , execIntBindingT ) where import Prelude hiding (mapM, sequence, foldr, foldr1, foldl, foldl1) --import Data.Word (Word) import qualified Data.IntMap as IM import Control.Applicative import Control.Monad (MonadPlus(..), liftM) import Control.Monad.Trans (MonadTrans(..)) import Control.Monad.State (MonadState(..), StateT, runStateT, evalStateT, execStateT, gets) import Control.Monad.Logic (MonadLogic(..)) import Control.Unification.Classes ---------------------------------------------------------------- ---------------------------------------------------------------- -- | A ``mutable'' unification variable implemented by an integer. -- This provides an entirely pure alternative to truly mutable alternatives like @STVar@ , which can make backtracking easier . newtype IntVar t = IntVar Int deriving (Show) -- BUG : This part works , but we 'd want to change Show IntBindingState too . instance Show ( IntVar t ) where show ( IntVar i ) = " IntVar " + + show ( boundedInt2Word i ) -- | Convert an integer to a word , via the continuous mapping that -- preserves @minBound@ and @maxBound@. boundedInt2Word : : Int - > Word boundedInt2Word i | i < 0 = fromIntegral ( i + maxBound + 1 ) | otherwise = fromIntegral i + fromIntegral ( maxBound : : Int ) + 1 -- BUG: This part works, but we'd want to change Show IntBindingState too. instance Show (IntVar t) where show (IntVar i) = "IntVar " ++ show (boundedInt2Word i) -- | Convert an integer to a word, via the continuous mapping that -- preserves @minBound@ and @maxBound@. boundedInt2Word :: Int -> Word boundedInt2Word i | i < 0 = fromIntegral (i + maxBound + 1) | otherwise = fromIntegral i + fromIntegral (maxBound :: Int) + 1 -} instance Variable IntVar where eqVar (IntVar i) (IntVar j) = i == j getVarID (IntVar v) = v ---------------------------------------------------------------- | Binding state for ' ' . data IntBindingState t = IntBindingState { nextFreeVar :: {-# UNPACK #-} !Int , varBindings :: IM.IntMap t } deriving (Show) -- | The initial @IntBindingState@. emptyIntBindingState :: IntBindingState t emptyIntBindingState = IntBindingState minBound IM.empty ---------------------------------------------------------------- | A monad for storing ' ' bindings , implemented as a ' StateT ' . For a plain state monad , set @m = Identity@ ; for a backtracking -- state monad, set @m = Logic@. newtype IntBindingT t m a = IBT { unIBT :: StateT (IntBindingState t) m a } -- For portability reasons, we're intentionally avoiding -- -XDeriveFunctor, -XGeneralizedNewtypeDeriving, and the like. instance (Functor m) => Functor (IntBindingT t m) where fmap f = IBT . fmap f . unIBT BUG : ca n't reduce dependency to Applicative because of StateT 's instance . instance (Functor m, Monad m) => Applicative (IntBindingT t m) where pure = IBT . pure x <*> y = IBT (unIBT x <*> unIBT y) x *> y = IBT (unIBT x *> unIBT y) x <* y = IBT (unIBT x <* unIBT y) instance (Monad m) => Monad (IntBindingT t m) where return = IBT . return m >>= f = IBT (unIBT m >>= unIBT . f) instance MonadTrans (IntBindingT t) where lift = IBT . lift BUG : ca n't reduce dependency to Alternative because of StateT 's instance . instance (Functor m, MonadPlus m) => Alternative (IntBindingT t m) where empty = IBT empty x <|> y = IBT (unIBT x <|> unIBT y) instance (MonadPlus m) => MonadPlus (IntBindingT t m) where mzero = IBT mzero mplus ml mr = IBT (mplus (unIBT ml) (unIBT mr)) instance (Monad m) => MonadState (IntBindingState t) (IntBindingT t m) where get = IBT get put = IBT . put N.B. , we already have ( MonadLogic m ) = > MonadLogic ( StateT s m ) , provided that logict is compiled against the same mtl / monads - fd -- we're getting StateT from. Otherwise we'll get a bunch of warnings -- here. instance (MonadLogic m) => MonadLogic (IntBindingT t m) where msplit (IBT m) = IBT (coerce `liftM` msplit m) where coerce Nothing = Nothing coerce (Just (a, m')) = Just (a, IBT m') interleave (IBT l) (IBT r) = IBT (interleave l r) IBT m >>- f = IBT (m >>- (unIBT . f)) ifte (IBT b) t (IBT f) = IBT (ifte b (unIBT . t) f) once (IBT m) = IBT (once m) ---------------------------------------------------------------- runIntBindingT :: IntBindingT t m a -> m (a, IntBindingState t) runIntBindingT (IBT m) = runStateT m emptyIntBindingState -- | N.B., you should explicitly apply bindings before calling this -- function, or else the bindings will be lost evalIntBindingT :: (Monad m) => IntBindingT t m a -> m a evalIntBindingT (IBT m) = evalStateT m emptyIntBindingState execIntBindingT :: (Monad m) => IntBindingT t m a -> m (IntBindingState t) execIntBindingT (IBT m) = execStateT m emptyIntBindingState ---------------------------------------------------------------- instance (Applicative m, Monad m) => BindingReader IntVar t (IntBindingT t m) where lookupVar (IntVar v) = IBT $ gets (IM.lookup v . varBindings) instance (Applicative m, Monad m) => BindingGenerator IntVar t (IntBindingT t m) where freeVar = IBT $ do ibs <- get let v = nextFreeVar ibs if v == maxBound then fail "freeVar: no more variables!" else do put $ ibs { nextFreeVar = v+1 } return $ IntVar v newVar t = IBT $ do ibs <- get let v = nextFreeVar ibs if v == maxBound then fail "newVar: no more variables!" else do let bs' = IM.insert v t (varBindings ibs) put $ ibs { nextFreeVar = v+1, varBindings = bs' } return $ IntVar v instance (Applicative m, Monad m) => BindingWriter IntVar t (IntBindingT t m) where bindVar (IntVar v) t = IBT $ do ibs <- get let bs = varBindings ibs let (mt, bs') = IM.insertLookupWithKey (\_ _ -> id) v t bs put $ ibs { varBindings = bs' } return mt bindVar_ (IntVar v) t = IBT $ do ibs <- get put $ ibs { varBindings = IM.insert v t (varBindings ibs) } unbindVar (IntVar v) = IBT $ do ibs <- get let bs = varBindings ibs let (mt,bs') = IM.updateLookupWithKey (\_ _ -> Nothing) v bs put $ ibs { varBindings = bs' } return mt unbindVar_ (IntVar v) = IBT $ do ibs <- get put $ ibs { varBindings = IM.delete v (varBindings ibs) } ---------------------------------------------------------------- ----------------------------------------------------------- fin.
null
https://raw.githubusercontent.com/wrengr/unification-fd/16301b1630a3a75168da0dd7d744c91dfaf007cc/test/bench/Control/Unification/IntVar.hs
haskell
# OPTIONS_GHC -Wall -fwarn-tabs # -------------------------------------------------------------- ~ 2021.10.17 | Module : Control.Unification.IntVar Maintainer : Stability : experimental Portability : semi-portable (MPTCs, FlexibleInstances) This module defines a state monad for functional pointers represented by integers as keys into an @IntMap@. This technique extends the approach by using a state monad transformer, which can be made into a backtracking state monad by setting the -------------------------------------------------------------- import Data.Word (Word) -------------------------------------------------------------- -------------------------------------------------------------- | A ``mutable'' unification variable implemented by an integer. This provides an entirely pure alternative to truly mutable BUG : This part works , but we 'd want to change Show IntBindingState too . | Convert an integer to a word , via the continuous mapping that preserves @minBound@ and @maxBound@. BUG: This part works, but we'd want to change Show IntBindingState too. | Convert an integer to a word, via the continuous mapping that preserves @minBound@ and @maxBound@. -------------------------------------------------------------- # UNPACK # | The initial @IntBindingState@. -------------------------------------------------------------- state monad, set @m = Logic@. For portability reasons, we're intentionally avoiding -XDeriveFunctor, -XGeneralizedNewtypeDeriving, and the like. we're getting StateT from. Otherwise we'll get a bunch of warnings here. -------------------------------------------------------------- | N.B., you should explicitly apply bindings before calling this function, or else the bindings will be lost -------------------------------------------------------------- -------------------------------------------------------------- --------------------------------------------------------- fin.
# LANGUAGE MultiParamTypeClasses , FlexibleInstances # Copyright : Copyright ( c ) 2007 - -2021 wren License : BSD was independently discovered by Dijkstra et al . This module underlying monad to some ' MonadLogic ' ( part of the @logict@ library , described by Kiselyov et al . ) . * , , ( 2008 ) /Efficient Functional Unification and Substitution/ , Technical Report UU - CS-2008 - 027 , Utrecht University . * , , , and ( 2005 ) /Backtracking , Interleaving , and/ /Terminating Monad Transformers/ , ICFP . module Control.Unification.IntVar ( IntVar() , IntBindingState() , IntBindingT() , runIntBindingT , evalIntBindingT , execIntBindingT ) where import Prelude hiding (mapM, sequence, foldr, foldr1, foldl, foldl1) import qualified Data.IntMap as IM import Control.Applicative import Control.Monad (MonadPlus(..), liftM) import Control.Monad.Trans (MonadTrans(..)) import Control.Monad.State (MonadState(..), StateT, runStateT, evalStateT, execStateT, gets) import Control.Monad.Logic (MonadLogic(..)) import Control.Unification.Classes alternatives like @STVar@ , which can make backtracking easier . newtype IntVar t = IntVar Int deriving (Show) instance Show ( IntVar t ) where show ( IntVar i ) = " IntVar " + + show ( boundedInt2Word i ) boundedInt2Word : : Int - > Word boundedInt2Word i | i < 0 = fromIntegral ( i + maxBound + 1 ) | otherwise = fromIntegral i + fromIntegral ( maxBound : : Int ) + 1 instance Show (IntVar t) where show (IntVar i) = "IntVar " ++ show (boundedInt2Word i) boundedInt2Word :: Int -> Word boundedInt2Word i | i < 0 = fromIntegral (i + maxBound + 1) | otherwise = fromIntegral i + fromIntegral (maxBound :: Int) + 1 -} instance Variable IntVar where eqVar (IntVar i) (IntVar j) = i == j getVarID (IntVar v) = v | Binding state for ' ' . data IntBindingState t = IntBindingState , varBindings :: IM.IntMap t } deriving (Show) emptyIntBindingState :: IntBindingState t emptyIntBindingState = IntBindingState minBound IM.empty | A monad for storing ' ' bindings , implemented as a ' StateT ' . For a plain state monad , set @m = Identity@ ; for a backtracking newtype IntBindingT t m a = IBT { unIBT :: StateT (IntBindingState t) m a } instance (Functor m) => Functor (IntBindingT t m) where fmap f = IBT . fmap f . unIBT BUG : ca n't reduce dependency to Applicative because of StateT 's instance . instance (Functor m, Monad m) => Applicative (IntBindingT t m) where pure = IBT . pure x <*> y = IBT (unIBT x <*> unIBT y) x *> y = IBT (unIBT x *> unIBT y) x <* y = IBT (unIBT x <* unIBT y) instance (Monad m) => Monad (IntBindingT t m) where return = IBT . return m >>= f = IBT (unIBT m >>= unIBT . f) instance MonadTrans (IntBindingT t) where lift = IBT . lift BUG : ca n't reduce dependency to Alternative because of StateT 's instance . instance (Functor m, MonadPlus m) => Alternative (IntBindingT t m) where empty = IBT empty x <|> y = IBT (unIBT x <|> unIBT y) instance (MonadPlus m) => MonadPlus (IntBindingT t m) where mzero = IBT mzero mplus ml mr = IBT (mplus (unIBT ml) (unIBT mr)) instance (Monad m) => MonadState (IntBindingState t) (IntBindingT t m) where get = IBT get put = IBT . put N.B. , we already have ( MonadLogic m ) = > MonadLogic ( StateT s m ) , provided that logict is compiled against the same mtl / monads - fd instance (MonadLogic m) => MonadLogic (IntBindingT t m) where msplit (IBT m) = IBT (coerce `liftM` msplit m) where coerce Nothing = Nothing coerce (Just (a, m')) = Just (a, IBT m') interleave (IBT l) (IBT r) = IBT (interleave l r) IBT m >>- f = IBT (m >>- (unIBT . f)) ifte (IBT b) t (IBT f) = IBT (ifte b (unIBT . t) f) once (IBT m) = IBT (once m) runIntBindingT :: IntBindingT t m a -> m (a, IntBindingState t) runIntBindingT (IBT m) = runStateT m emptyIntBindingState evalIntBindingT :: (Monad m) => IntBindingT t m a -> m a evalIntBindingT (IBT m) = evalStateT m emptyIntBindingState execIntBindingT :: (Monad m) => IntBindingT t m a -> m (IntBindingState t) execIntBindingT (IBT m) = execStateT m emptyIntBindingState instance (Applicative m, Monad m) => BindingReader IntVar t (IntBindingT t m) where lookupVar (IntVar v) = IBT $ gets (IM.lookup v . varBindings) instance (Applicative m, Monad m) => BindingGenerator IntVar t (IntBindingT t m) where freeVar = IBT $ do ibs <- get let v = nextFreeVar ibs if v == maxBound then fail "freeVar: no more variables!" else do put $ ibs { nextFreeVar = v+1 } return $ IntVar v newVar t = IBT $ do ibs <- get let v = nextFreeVar ibs if v == maxBound then fail "newVar: no more variables!" else do let bs' = IM.insert v t (varBindings ibs) put $ ibs { nextFreeVar = v+1, varBindings = bs' } return $ IntVar v instance (Applicative m, Monad m) => BindingWriter IntVar t (IntBindingT t m) where bindVar (IntVar v) t = IBT $ do ibs <- get let bs = varBindings ibs let (mt, bs') = IM.insertLookupWithKey (\_ _ -> id) v t bs put $ ibs { varBindings = bs' } return mt bindVar_ (IntVar v) t = IBT $ do ibs <- get put $ ibs { varBindings = IM.insert v t (varBindings ibs) } unbindVar (IntVar v) = IBT $ do ibs <- get let bs = varBindings ibs let (mt,bs') = IM.updateLookupWithKey (\_ _ -> Nothing) v bs put $ ibs { varBindings = bs' } return mt unbindVar_ (IntVar v) = IBT $ do ibs <- get put $ ibs { varBindings = IM.delete v (varBindings ibs) }
98dc8855f2593920c7fda3045a67ea1111fd6cb4590d2913dbf0a94ebd9e6148
eponai/sulolive
menu.cljc
(ns eponai.common.ui.elements.menu (:require [eponai.common.ui.elements.css :as css] [eponai.common.ui.dom :as dom])) ;; Menu elements (defn- menu* "Custom menu element with provided content. For the provided content it's recommended to use any if the item- functions to generate compatible elements. Opts :classes - class keys to apply to this menu element. See css.cljc for available class keys." [opts & content] (apply dom/ul (css/add-class ::css/menu opts) content)) (defn tabs [opts & content] (apply menu* (css/add-class ::css/tabs opts) content)) (defn breadcrumbs [opts & content] (apply dom/ul (css/add-class :css/breadcrumbs opts) content)) (defn horizontal "Menu in horizontal layout. See menu* for general opts and recommended content." [opts & content] (apply menu* opts content)) (defn vertical "Menu in vertical layout. See menu* for general opts and recommended content." [opts & content] (apply menu* (css/add-class ::css/vertical opts) content)) ;; Menu list item elements (defn- item* [opts & content] (apply dom/li opts content)) (defn item "Custom menu item containing the provided content. Opts :classes - what class keys should be added to this item. See css.cljc for available class keys." [opts & content] (apply item* opts content)) (defn item-tab "Menu item representing a tab in some sort of stateful situation. Opts :is-active? - Whether this tab is in an active state. See item for general opts." [{:keys [is-active?] :as opts} & content] (item* (cond->> (css/add-class ::css/tabs-title (dissoc opts :is-active?)) is-active? (css/add-class ::css/is-active)) content)) (defn item-link "Menu item containing an anchor link. Opts :href - href for the containng anchor See item for general opts." [opts & content] (item* (select-keys opts [:key]) (dom/a (dissoc opts :key) content))) (defn item-dropdown "Menu item containg a link that opens a dropdown. Accepts a :dropdown key in opts containing the actual dropdown content element." [{:keys [dropdown href onClick classes]} & content] (item* {:classes (conj classes ::css/menu-dropdown)} (dom/a {:href href :onClick onClick} content) dropdown)) (defn item-text "Menu item element containing text only. See item for general opts." [opts & content] (apply item* (css/add-class ::css/menu-text opts) content))
null
https://raw.githubusercontent.com/eponai/sulolive/7a70701bbd3df6bbb92682679dcedb53f8822c18/src/eponai/common/ui/elements/menu.cljc
clojure
Menu elements Menu list item elements
(ns eponai.common.ui.elements.menu (:require [eponai.common.ui.elements.css :as css] [eponai.common.ui.dom :as dom])) (defn- menu* "Custom menu element with provided content. For the provided content it's recommended to use any if the item- functions to generate compatible elements. Opts :classes - class keys to apply to this menu element. See css.cljc for available class keys." [opts & content] (apply dom/ul (css/add-class ::css/menu opts) content)) (defn tabs [opts & content] (apply menu* (css/add-class ::css/tabs opts) content)) (defn breadcrumbs [opts & content] (apply dom/ul (css/add-class :css/breadcrumbs opts) content)) (defn horizontal "Menu in horizontal layout. See menu* for general opts and recommended content." [opts & content] (apply menu* opts content)) (defn vertical "Menu in vertical layout. See menu* for general opts and recommended content." [opts & content] (apply menu* (css/add-class ::css/vertical opts) content)) (defn- item* [opts & content] (apply dom/li opts content)) (defn item "Custom menu item containing the provided content. Opts :classes - what class keys should be added to this item. See css.cljc for available class keys." [opts & content] (apply item* opts content)) (defn item-tab "Menu item representing a tab in some sort of stateful situation. Opts :is-active? - Whether this tab is in an active state. See item for general opts." [{:keys [is-active?] :as opts} & content] (item* (cond->> (css/add-class ::css/tabs-title (dissoc opts :is-active?)) is-active? (css/add-class ::css/is-active)) content)) (defn item-link "Menu item containing an anchor link. Opts :href - href for the containng anchor See item for general opts." [opts & content] (item* (select-keys opts [:key]) (dom/a (dissoc opts :key) content))) (defn item-dropdown "Menu item containg a link that opens a dropdown. Accepts a :dropdown key in opts containing the actual dropdown content element." [{:keys [dropdown href onClick classes]} & content] (item* {:classes (conj classes ::css/menu-dropdown)} (dom/a {:href href :onClick onClick} content) dropdown)) (defn item-text "Menu item element containing text only. See item for general opts." [opts & content] (apply item* (css/add-class ::css/menu-text opts) content))
1e2a99aad9cd2563cc61e8528d6e5a5c8e13df90155151f0f2c6d92f02535502
mfoemmel/erlang-otp
snmp_appup_mgr.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2003 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% %%---------------------------------------------------------------------- %% Purpose: Simple (snmp) manager used when performing appup tests. %%---------------------------------------------------------------------- -module(snmp_appup_mgr). -behaviour(snmpm_user). -include_lib("snmp/include/STANDARD-MIB.hrl"). -include_lib("snmp/include/snmp_types.hrl"). -export([start/0, start/1, start/2]). -export([handle_error/3, handle_agent/4, handle_pdu/5, handle_trap/4, handle_inform/4, handle_report/4]). -export([main/2]). -record(agent, {host, port, conf}). -record(state, {timer, reqs, ids, agent}). -define(USER_ID, ?MODULE). -define(REQ_TIMEOUT, 10000). -define(POLL_TIMEOUT, 5000). -define(DEFAULT_PORT, 4000). -define(DEFAULT_PORT , 161 ) . -define(v1_2(V1,V2), case get(vsn) of v1 -> V1; _ -> V2 end). start() -> {ok, AgentHost} = inet:gethostname(), AgentPort = ?DEFAULT_PORT, start(AgentHost, AgentPort). start(AgentPort) when is_integer(AgentPort) -> {ok, AgentHost} = inet:gethostname(), start(AgentHost, AgentPort); start(AgentHost) when is_list(AgentHost) -> AgentPort = 161, start(AgentHost, AgentPort). start(AgentHost, AgentPort) when is_list(AgentHost) and is_integer(AgentPort) -> ensure_started(snmp), Pid = erlang:spawn_link(?MODULE, main, [AgentHost, AgentPort]), receive {'EXIT', Pid, normal} -> ok; {'EXIT', Pid, Reason} -> {error, {unexpected_exit, Reason}} end. ensure_started(App) -> case application:start(App) of ok -> ok; {error, {already_started, _}} -> ok; {error, Reason} -> exit(Reason) end. poll_timer() -> poll_timer(first). poll_timer(How) -> erlang:send_after(?POLL_TIMEOUT, self(), {poll_timeout, How}). next_poll_type(first) -> all; next_poll_type(all) -> first. main(AgentHost, AgentPort) -> ok = snmpm:register_user_monitor(?USER_ID, ?MODULE, self()), AgentConf = [{community, "all-rights"}, {engine_id, "agentEngine"}, {sec_level, noAuthNoPriv}, {version, v1}], ok = snmpm:register_agent(?USER_ID, AgentHost, AgentPort, AgentConf), Reqs = [{"sysDescr", get, ?sysDescr_instance}, {"sysObjectID", get, ?sysObjectID_instance}, {"sysUpTime", get, ?sysUpTime_instance}], Agent = #agent{host = AgentHost, port = AgentPort, conf = AgentConf}, State = #state{timer = poll_timer(), reqs = Reqs, agent = Agent}, loop(State). loop(State) -> receive {poll_timeout, How} -> NewState = handle_poll_timeout(State, How), loop(NewState#state{timer = poll_timer(next_poll_type(How))}); {req_timeout, ReqId} -> NewState = handle_req_timeout(State, ReqId), loop(NewState); {snmp_callback, Info} -> NewState = handle_snmp(State, Info), loop(NewState) end. handle_poll_timeout(#state{agent = Agent, reqs = [Req|Reqs], ids = IDs} = S, first) -> ReqId = handle_req(Agent, [Req]), S#state{reqs = Reqs ++ [Req], ids = [ReqId|IDs]}; handle_poll_timeout(#state{agent = Agent, reqs = Reqs, ids = IDs} = S, all) -> ReqId = handle_req(Agent, Reqs), S#state{ids = [ReqId|IDs]}. handle_req(#agent{host = Host, port = Port}, Reqs) -> Oids = [Oid || {_Desc, Op, Oid} <- Reqs, Op == get], Descs = [Desc || {Desc, Op, _Oid} <- Reqs, Op == get], {ok, ReqId} = snmpm:ag(?USER_ID, Host, Port, Oids), p("issued get-request (~w) for: ~s", [ReqId, oid_descs(Descs)]), ReqTimer = erlang:send_after(?REQ_TIMEOUT, self(), {req_timeout, ReqId}), {ReqId, erlang:now(), ReqTimer}. oid_descs([]) -> []; oid_descs([Desc]) -> lists:flatten(io_lib:format("~s", [Desc])); oid_descs([Desc|Descs]) -> lists:flatten(io_lib:format("~s, ", [Desc])) ++ oid_descs(Descs). handle_req_timeout(#state{ids = IDs0} = State, ReqId) -> case lists:keysearch(ReqId, 1, IDs0) of {value, {ReqId, _T, _Ref}} -> e("Request timeout for request ~w", [ReqId]), IDs = lists:keydelete(ReqId, 1, IDs0), State#state{ids = IDs}; false -> w("Did not find request corresponding to id ~w", [ReqId]), State end. handle_snmp(#state{ids = IDs0} = S, {error, ReqId, Reason}) -> case lists:keysearch(ReqId, 1, IDs0) of {value, {ReqId, T, Ref}} -> Diff = timer:now_diff(erlang:now(), T), p("SNMP error regarding outstanding request after ~w microsec:" "~n ReqId: ~w" "~n Reason: ~w", [Diff, ReqId, Reason]), IDs = lists:keydelete(ReqId, 1, IDs0), erlang:cancel_timer(Ref), S#state{ids = IDs}; false -> w("SNMP error regarding unknown request:" "~n ReqId: ~w" "~n Reason: ~w", [ReqId, Reason]), S end; handle_snmp(State, {agent, Addr, Port, SnmpInfo}) -> p("Received agent info:" "~n Addr: ~w" "~n Port: ~w" "~n SnmpInfo: ~w", [Addr, Port, SnmpInfo]), State; handle_snmp(#state{ids = IDs0} = S, {pdu, Addr, Port, ReqId, SnmpResponse}) -> case lists:keysearch(ReqId, 1, IDs0) of {value, {ReqId, T, Ref}} -> Diff = timer:now_diff(erlang:now(), T), p("SNMP pdu regarding outstanding request after ~w microsec:" "~n ReqId: ~w" "~n Addr: ~w" "~n Port: ~w" "~n SnmpResponse: ~w", [Diff, ReqId, Addr, Port, SnmpResponse]), IDs = lists:keydelete(ReqId, 1, IDs0), erlang:cancel_timer(Ref), S#state{ids = IDs}; false -> w("SNMP pdu regarding unknown request:" "~n ReqId: ~w" "~n Addr: ~w" "~n Port: ~w" "~n SnmpResponse: ~w", [ReqId, Addr, Port, SnmpResponse]), S end; handle_snmp(State, {trap, Addr, Port, SnmpTrapInfo}) -> p("Received trap:" "~n Addr: ~w" "~n Port: ~w" "~n SnmpTrapInfo: ~w", [Addr, Port, SnmpTrapInfo]), State; handle_snmp(State, {inform, Addr, Port, SnmpInform}) -> p("Received inform:" "~n Addr: ~w" "~n Port: ~w" "~n SnmpInform: ~w", [Addr, Port, SnmpInform]), State; handle_snmp(State, {report, Addr, Port, SnmpReport}) -> p("Received report:" "~n Addr: ~w" "~n Port: ~w" "~n SnmpReport: ~w", [Addr, Port, SnmpReport]), State; handle_snmp(State, Unknown) -> p("Received unknown snmp info:" "~n Unknown: ~w", [Unknown]), State. %% ----------------------------------------------------------------------- %% %% Manager user callback API %% %% ----------------------------------------------------------------------- handle_error(ReqId, Reason, Pid) -> Pid ! {snmp_callback, {error, ReqId, Reason}}, ignore. handle_agent(Addr, Port, SnmpInfo, Pid) -> Pid ! {snmp_callback, {agent, Addr, Port, SnmpInfo}}, ignore. handle_pdu(Addr, Port, ReqId, SnmpResponse, Pid) -> Pid ! {snmp_callback, {pdu, Addr, Port, ReqId, SnmpResponse}}, ignore. handle_trap(Addr, Port, SnmpTrapInfo, Pid) -> Pid ! {snmp_callback, {trap, Addr, Port, SnmpTrapInfo}}, ignore. handle_inform(Addr, Port, SnmpInform, Pid) -> Pid ! {snmp_callback, {inform, Addr, Port, SnmpInform}}, ignore. handle_report(Addr, Port, SnmpReport, Pid) -> Pid ! {snmp_callback, {report, Addr, Port, SnmpReport}}, ignore. %% ----------------------------------------------------------------------- e(F, A) -> p("*** ERROR ***", F, A). w(F, A) -> p("*** WARNING ***", F, A). p(F, A) -> p("*** INFO ***", F, A). p(P, F, A) -> io:format("~s~nMGR: " ++ F ++ "~n~n", [P|A]).
null
https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/snmp/test/snmp_appup_mgr.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% ---------------------------------------------------------------------- Purpose: Simple (snmp) manager used when performing appup tests. ---------------------------------------------------------------------- ----------------------------------------------------------------------- Manager user callback API ----------------------------------------------------------------------- -----------------------------------------------------------------------
Copyright Ericsson AB 2003 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(snmp_appup_mgr). -behaviour(snmpm_user). -include_lib("snmp/include/STANDARD-MIB.hrl"). -include_lib("snmp/include/snmp_types.hrl"). -export([start/0, start/1, start/2]). -export([handle_error/3, handle_agent/4, handle_pdu/5, handle_trap/4, handle_inform/4, handle_report/4]). -export([main/2]). -record(agent, {host, port, conf}). -record(state, {timer, reqs, ids, agent}). -define(USER_ID, ?MODULE). -define(REQ_TIMEOUT, 10000). -define(POLL_TIMEOUT, 5000). -define(DEFAULT_PORT, 4000). -define(DEFAULT_PORT , 161 ) . -define(v1_2(V1,V2), case get(vsn) of v1 -> V1; _ -> V2 end). start() -> {ok, AgentHost} = inet:gethostname(), AgentPort = ?DEFAULT_PORT, start(AgentHost, AgentPort). start(AgentPort) when is_integer(AgentPort) -> {ok, AgentHost} = inet:gethostname(), start(AgentHost, AgentPort); start(AgentHost) when is_list(AgentHost) -> AgentPort = 161, start(AgentHost, AgentPort). start(AgentHost, AgentPort) when is_list(AgentHost) and is_integer(AgentPort) -> ensure_started(snmp), Pid = erlang:spawn_link(?MODULE, main, [AgentHost, AgentPort]), receive {'EXIT', Pid, normal} -> ok; {'EXIT', Pid, Reason} -> {error, {unexpected_exit, Reason}} end. ensure_started(App) -> case application:start(App) of ok -> ok; {error, {already_started, _}} -> ok; {error, Reason} -> exit(Reason) end. poll_timer() -> poll_timer(first). poll_timer(How) -> erlang:send_after(?POLL_TIMEOUT, self(), {poll_timeout, How}). next_poll_type(first) -> all; next_poll_type(all) -> first. main(AgentHost, AgentPort) -> ok = snmpm:register_user_monitor(?USER_ID, ?MODULE, self()), AgentConf = [{community, "all-rights"}, {engine_id, "agentEngine"}, {sec_level, noAuthNoPriv}, {version, v1}], ok = snmpm:register_agent(?USER_ID, AgentHost, AgentPort, AgentConf), Reqs = [{"sysDescr", get, ?sysDescr_instance}, {"sysObjectID", get, ?sysObjectID_instance}, {"sysUpTime", get, ?sysUpTime_instance}], Agent = #agent{host = AgentHost, port = AgentPort, conf = AgentConf}, State = #state{timer = poll_timer(), reqs = Reqs, agent = Agent}, loop(State). loop(State) -> receive {poll_timeout, How} -> NewState = handle_poll_timeout(State, How), loop(NewState#state{timer = poll_timer(next_poll_type(How))}); {req_timeout, ReqId} -> NewState = handle_req_timeout(State, ReqId), loop(NewState); {snmp_callback, Info} -> NewState = handle_snmp(State, Info), loop(NewState) end. handle_poll_timeout(#state{agent = Agent, reqs = [Req|Reqs], ids = IDs} = S, first) -> ReqId = handle_req(Agent, [Req]), S#state{reqs = Reqs ++ [Req], ids = [ReqId|IDs]}; handle_poll_timeout(#state{agent = Agent, reqs = Reqs, ids = IDs} = S, all) -> ReqId = handle_req(Agent, Reqs), S#state{ids = [ReqId|IDs]}. handle_req(#agent{host = Host, port = Port}, Reqs) -> Oids = [Oid || {_Desc, Op, Oid} <- Reqs, Op == get], Descs = [Desc || {Desc, Op, _Oid} <- Reqs, Op == get], {ok, ReqId} = snmpm:ag(?USER_ID, Host, Port, Oids), p("issued get-request (~w) for: ~s", [ReqId, oid_descs(Descs)]), ReqTimer = erlang:send_after(?REQ_TIMEOUT, self(), {req_timeout, ReqId}), {ReqId, erlang:now(), ReqTimer}. oid_descs([]) -> []; oid_descs([Desc]) -> lists:flatten(io_lib:format("~s", [Desc])); oid_descs([Desc|Descs]) -> lists:flatten(io_lib:format("~s, ", [Desc])) ++ oid_descs(Descs). handle_req_timeout(#state{ids = IDs0} = State, ReqId) -> case lists:keysearch(ReqId, 1, IDs0) of {value, {ReqId, _T, _Ref}} -> e("Request timeout for request ~w", [ReqId]), IDs = lists:keydelete(ReqId, 1, IDs0), State#state{ids = IDs}; false -> w("Did not find request corresponding to id ~w", [ReqId]), State end. handle_snmp(#state{ids = IDs0} = S, {error, ReqId, Reason}) -> case lists:keysearch(ReqId, 1, IDs0) of {value, {ReqId, T, Ref}} -> Diff = timer:now_diff(erlang:now(), T), p("SNMP error regarding outstanding request after ~w microsec:" "~n ReqId: ~w" "~n Reason: ~w", [Diff, ReqId, Reason]), IDs = lists:keydelete(ReqId, 1, IDs0), erlang:cancel_timer(Ref), S#state{ids = IDs}; false -> w("SNMP error regarding unknown request:" "~n ReqId: ~w" "~n Reason: ~w", [ReqId, Reason]), S end; handle_snmp(State, {agent, Addr, Port, SnmpInfo}) -> p("Received agent info:" "~n Addr: ~w" "~n Port: ~w" "~n SnmpInfo: ~w", [Addr, Port, SnmpInfo]), State; handle_snmp(#state{ids = IDs0} = S, {pdu, Addr, Port, ReqId, SnmpResponse}) -> case lists:keysearch(ReqId, 1, IDs0) of {value, {ReqId, T, Ref}} -> Diff = timer:now_diff(erlang:now(), T), p("SNMP pdu regarding outstanding request after ~w microsec:" "~n ReqId: ~w" "~n Addr: ~w" "~n Port: ~w" "~n SnmpResponse: ~w", [Diff, ReqId, Addr, Port, SnmpResponse]), IDs = lists:keydelete(ReqId, 1, IDs0), erlang:cancel_timer(Ref), S#state{ids = IDs}; false -> w("SNMP pdu regarding unknown request:" "~n ReqId: ~w" "~n Addr: ~w" "~n Port: ~w" "~n SnmpResponse: ~w", [ReqId, Addr, Port, SnmpResponse]), S end; handle_snmp(State, {trap, Addr, Port, SnmpTrapInfo}) -> p("Received trap:" "~n Addr: ~w" "~n Port: ~w" "~n SnmpTrapInfo: ~w", [Addr, Port, SnmpTrapInfo]), State; handle_snmp(State, {inform, Addr, Port, SnmpInform}) -> p("Received inform:" "~n Addr: ~w" "~n Port: ~w" "~n SnmpInform: ~w", [Addr, Port, SnmpInform]), State; handle_snmp(State, {report, Addr, Port, SnmpReport}) -> p("Received report:" "~n Addr: ~w" "~n Port: ~w" "~n SnmpReport: ~w", [Addr, Port, SnmpReport]), State; handle_snmp(State, Unknown) -> p("Received unknown snmp info:" "~n Unknown: ~w", [Unknown]), State. handle_error(ReqId, Reason, Pid) -> Pid ! {snmp_callback, {error, ReqId, Reason}}, ignore. handle_agent(Addr, Port, SnmpInfo, Pid) -> Pid ! {snmp_callback, {agent, Addr, Port, SnmpInfo}}, ignore. handle_pdu(Addr, Port, ReqId, SnmpResponse, Pid) -> Pid ! {snmp_callback, {pdu, Addr, Port, ReqId, SnmpResponse}}, ignore. handle_trap(Addr, Port, SnmpTrapInfo, Pid) -> Pid ! {snmp_callback, {trap, Addr, Port, SnmpTrapInfo}}, ignore. handle_inform(Addr, Port, SnmpInform, Pid) -> Pid ! {snmp_callback, {inform, Addr, Port, SnmpInform}}, ignore. handle_report(Addr, Port, SnmpReport, Pid) -> Pid ! {snmp_callback, {report, Addr, Port, SnmpReport}}, ignore. e(F, A) -> p("*** ERROR ***", F, A). w(F, A) -> p("*** WARNING ***", F, A). p(F, A) -> p("*** INFO ***", F, A). p(P, F, A) -> io:format("~s~nMGR: " ++ F ++ "~n~n", [P|A]).
72d081104b64912203d98a9677644021387f9a85645d2213106b03d55abea8a6
inhabitedtype/ocaml-aws
describePatchGroupState.mli
open Types type input = DescribePatchGroupStateRequest.t type output = DescribePatchGroupStateResult.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
null
https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/3bc554af7ae7ef9e2dcea44a1b72c9e687435fa9/libraries/ssm/lib/describePatchGroupState.mli
ocaml
open Types type input = DescribePatchGroupStateRequest.t type output = DescribePatchGroupStateResult.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
365de2917dbf39d9ccef1a2f2aa556363f8d630c027bb333f3704d3ffda8d638
sky-big/RabbitMQ
tcp_acceptor.erl
The contents of this file are subject to the Mozilla Public License %% Version 1.1 (the "License"); you may not use this file except in %% compliance with the License. You may obtain a copy of the License %% at / %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and %% limitations under the License. %% The Original Code is RabbitMQ . %% The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . %% -module(tcp_acceptor). -behaviour(gen_server). -export([start_link/3]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {callback, sock, ref}). %%-------------------------------------------------------------------- %% RabbitMQ系统网络端口监听的实际工作进程的启动入口函数 start_link(Callback, LSock, Number) -> gen_server:start_link(?MODULE, {Callback, LSock, Number}, []). %%-------------------------------------------------------------------- %% RabbitMQ系统网络端口监听的实际工作进程的初始化回调函数 init({Callback, LSock, Number}) -> %% 自己添加的注册监听进程的名字 erlang:register(list_to_atom(atom_to_list(?MODULE) ++ "_" ++ integer_to_list(Number)), self()), gen_server:cast(self(), accept), {ok, #state{callback = Callback, sock = LSock}}. handle_call(_Request, _From, State) -> {noreply, State}. handle_cast(accept, State) -> %% 当前tcp_acceptor进程工作的时候,将当前进程Socket的数量在file_handle_cache进程中增加一 ok = file_handle_cache:obtain(), accept(State); handle_cast(_Msg, State) -> {noreply, State}. handle_info({inet_async, LSock, Ref, {ok, Sock}}, State = #state{callback={M, F, A}, sock = LSock, ref = Ref}) -> %% patch up the socket so it looks like one we got from gen_tcp : accept/1 {ok, Mod} = inet_db:lookup_socket(LSock), inet_db:register_socket(Sock, Mod), %% handle case tune_buffer_size(Sock) of ok -> %% 将当前进程tcp_acceptor对应的Socket数量转移到连接进程rabbit_reader进程上去 file_handle_cache:transfer( apply(M, F, A ++ [Sock])), %% 然后将当前进程对应的Socket数量增加一 ok = file_handle_cache:obtain(); {error, enotconn} -> catch port_close(Sock); {error, Err} -> {ok, {IPAddress, Port}} = inet:sockname(LSock), error_logger:error_msg( "failed to tune buffer size of " "connection accepted on ~s:~p - ~s~n", [rabbit_misc:ntoab(IPAddress), Port, rabbit_misc:format_inet_error(Err)]), catch port_close(Sock) end, %% accept more accept(State); handle_info({inet_async, LSock, Ref, {error, Reason}}, State=#state{sock=LSock, ref=Ref}) -> case Reason of closed -> {stop, normal, State}; %% listening socket closed econnaborted -> accept(State); %% client sent RST before we accepted _ -> {stop, {accept_failed, Reason}, State} end; handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- accept(State = #state{sock = LSock}) -> case prim_inet:async_accept(LSock, -1) of {ok, Ref} -> {noreply, State#state{ref = Ref}}; Error -> {stop, {cannot_accept, Error}, State} end. tune_buffer_size(Sock) -> case inet:getopts(Sock, [sndbuf, recbuf, buffer]) of {ok, BufSizes} -> BufSz = lists:max([Sz || {_Opt, Sz} <- BufSizes]), inet:setopts(Sock, [{buffer, BufSz}]); Error -> Error end.
null
https://raw.githubusercontent.com/sky-big/RabbitMQ/d7a773e11f93fcde4497c764c9fa185aad049ce2/src/tcp_acceptor.erl
erlang
Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. -------------------------------------------------------------------- RabbitMQ系统网络端口监听的实际工作进程的启动入口函数 -------------------------------------------------------------------- RabbitMQ系统网络端口监听的实际工作进程的初始化回调函数 自己添加的注册监听进程的名字 当前tcp_acceptor进程工作的时候,将当前进程Socket的数量在file_handle_cache进程中增加一 patch up the socket so it looks like one we got from handle 将当前进程tcp_acceptor对应的Socket数量转移到连接进程rabbit_reader进程上去 然后将当前进程对应的Socket数量增加一 accept more listening socket closed client sent RST before we accepted --------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " The Original Code is RabbitMQ . The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . -module(tcp_acceptor). -behaviour(gen_server). -export([start_link/3]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {callback, sock, ref}). start_link(Callback, LSock, Number) -> gen_server:start_link(?MODULE, {Callback, LSock, Number}, []). init({Callback, LSock, Number}) -> erlang:register(list_to_atom(atom_to_list(?MODULE) ++ "_" ++ integer_to_list(Number)), self()), gen_server:cast(self(), accept), {ok, #state{callback = Callback, sock = LSock}}. handle_call(_Request, _From, State) -> {noreply, State}. handle_cast(accept, State) -> ok = file_handle_cache:obtain(), accept(State); handle_cast(_Msg, State) -> {noreply, State}. handle_info({inet_async, LSock, Ref, {ok, Sock}}, State = #state{callback={M, F, A}, sock = LSock, ref = Ref}) -> gen_tcp : accept/1 {ok, Mod} = inet_db:lookup_socket(LSock), inet_db:register_socket(Sock, Mod), case tune_buffer_size(Sock) of file_handle_cache:transfer( apply(M, F, A ++ [Sock])), ok = file_handle_cache:obtain(); {error, enotconn} -> catch port_close(Sock); {error, Err} -> {ok, {IPAddress, Port}} = inet:sockname(LSock), error_logger:error_msg( "failed to tune buffer size of " "connection accepted on ~s:~p - ~s~n", [rabbit_misc:ntoab(IPAddress), Port, rabbit_misc:format_inet_error(Err)]), catch port_close(Sock) end, accept(State); handle_info({inet_async, LSock, Ref, {error, Reason}}, State=#state{sock=LSock, ref=Ref}) -> case Reason of _ -> {stop, {accept_failed, Reason}, State} end; handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. accept(State = #state{sock = LSock}) -> case prim_inet:async_accept(LSock, -1) of {ok, Ref} -> {noreply, State#state{ref = Ref}}; Error -> {stop, {cannot_accept, Error}, State} end. tune_buffer_size(Sock) -> case inet:getopts(Sock, [sndbuf, recbuf, buffer]) of {ok, BufSizes} -> BufSz = lists:max([Sz || {_Opt, Sz} <- BufSizes]), inet:setopts(Sock, [{buffer, BufSz}]); Error -> Error end.
825a1297da945171ce43b09bf7e999be87455ad3215c0818423a2e0f57bfc0e8
jimcrayne/jhc
tc151.hs
{-# OPTIONS -fglasgow-exts #-} -- A test for rank-3 types module ShouldCompile where data Fork a = ForkC a a mapFork :: forall a1 a2 . (a1 -> a2) -> (Fork a1 -> Fork a2) mapFork mapA (ForkC a1 a2) = ForkC (mapA a1) (mapA a2) data SequF s a = EmptyF | ZeroF (s (Fork a)) | OneF a (s (Fork a)) newtype HFix h a = HIn (h (HFix h) a) type Sequ = HFix SequF mapSequF :: forall s1 s2 . (forall b1 b2 . (b1 -> b2) -> (s1 b1 -> s2 b2)) -> (forall a1 a2 . (a1 -> a2) -> (SequF s1 a1 -> SequF s2 a2)) mapSequF mapS mapA EmptyF = EmptyF mapSequF mapS mapA (ZeroF as) = ZeroF (mapS (mapFork mapA) as) mapSequF mapS mapA (OneF a as)= OneF (mapA a) (mapS (mapFork mapA) as) mapHFix :: forall h1 h2 . (forall f1 f2 . (forall c1 c2 . (c1 -> c2) -> (f1 c1 -> f2 c2)) -> (forall b1 b2 . (b1 -> b2) -> (h1 f1 b1 -> h2 f2 b2))) -> (forall a1 a2 . (a1 -> a2) -> (HFix h1 a1 -> HFix h2 a2)) mapHFix mapH mapA (HIn v) = HIn (mapH (mapHFix mapH) mapA v) mapSequ :: forall a1 a2 . (a1 -> a2) -> (Sequ a1 -> Sequ a2) mapSequ = mapHFix mapSequF
null
https://raw.githubusercontent.com/jimcrayne/jhc/1ff035af3d697f9175f8761c8d08edbffde03b4e/regress/tests/1_typecheck/2_pass/ghc/tc151.hs
haskell
# OPTIONS -fglasgow-exts # A test for rank-3 types
module ShouldCompile where data Fork a = ForkC a a mapFork :: forall a1 a2 . (a1 -> a2) -> (Fork a1 -> Fork a2) mapFork mapA (ForkC a1 a2) = ForkC (mapA a1) (mapA a2) data SequF s a = EmptyF | ZeroF (s (Fork a)) | OneF a (s (Fork a)) newtype HFix h a = HIn (h (HFix h) a) type Sequ = HFix SequF mapSequF :: forall s1 s2 . (forall b1 b2 . (b1 -> b2) -> (s1 b1 -> s2 b2)) -> (forall a1 a2 . (a1 -> a2) -> (SequF s1 a1 -> SequF s2 a2)) mapSequF mapS mapA EmptyF = EmptyF mapSequF mapS mapA (ZeroF as) = ZeroF (mapS (mapFork mapA) as) mapSequF mapS mapA (OneF a as)= OneF (mapA a) (mapS (mapFork mapA) as) mapHFix :: forall h1 h2 . (forall f1 f2 . (forall c1 c2 . (c1 -> c2) -> (f1 c1 -> f2 c2)) -> (forall b1 b2 . (b1 -> b2) -> (h1 f1 b1 -> h2 f2 b2))) -> (forall a1 a2 . (a1 -> a2) -> (HFix h1 a1 -> HFix h2 a2)) mapHFix mapH mapA (HIn v) = HIn (mapH (mapHFix mapH) mapA v) mapSequ :: forall a1 a2 . (a1 -> a2) -> (Sequ a1 -> Sequ a2) mapSequ = mapHFix mapSequF
d224cf80361db7624599595df7fdd00e648b1a67c31c9195bc13702e1f3d0b62
racehub/om-bootstrap
basic.cljs
#_ (:require [om-bootstrap.random :as r] [om-tools.dom :as d :include-macros true]) (r/alert {:bs-style "warning"} (d/strong "Holy guacamole!") " Best check yo self, you're not looking too good.")
null
https://raw.githubusercontent.com/racehub/om-bootstrap/18fb7f67c306d208bcb012a1b765ac1641d7a00b/dev/snippets/alert/basic.cljs
clojure
#_ (:require [om-bootstrap.random :as r] [om-tools.dom :as d :include-macros true]) (r/alert {:bs-style "warning"} (d/strong "Holy guacamole!") " Best check yo self, you're not looking too good.")
24e03ad8674aff39a82508c382e5ded6a2071d2d5c5e9dc290b083ffc066766a
phadej/language-pts
Check.hs
{-# LANGUAGE OverloadedStrings #-} -- | Type-checker. module Language.PTS.Check ( type_, check_, ) where import Language.PTS.Bound import Language.PTS.Error import Language.PTS.Pretty import Language.PTS.Specification import Language.PTS.Sym import Language.PTS.Term import Language.PTS.Value #ifdef LANGUAGE_PTS_HAS_NAT import Language.PTS.Smart #endif #ifdef LANGUAGE_PTS_HAS_QUARKS import Control.Lens (ifor) import qualified Data.Set as Set import qualified Data.Map as Map #endif ------------------------------------------------------------------------------- -- Type-checker ------------------------------------------------------------------------------- | We can infer the type of ' TermInf ' ... type_ :: (Eq a, Show a, PrettyPrec a, Specification s, MonadErr m, PrettyPrec err, AsErr err) => (a -> Maybe (ValueIntro err s a)) -- ^ environment -> TermInf s a -- ^ term to type-check -> m (ValueIntro err s a, ValueIntro err s a) -- ^ as result we get evaluated term and its type. type_ = rtype_ [] -- | ... and check the type of 'TermChk'. check_ :: (Eq a, Show a, PrettyPrec a, Specification s, MonadErr m, PrettyPrec err, AsErr err) => (a -> Maybe (ValueIntro err s a)) -- ^ environment -> TermChk s a -- ^ term to check -> ValueIntro err s a -- ^ expected type -> m (ValueIntro err s a) -- ^ as result we get evaluated term check_ = rcheck_ [] ------------------------------------------------------------------------------- Synthesis ------------------------------------------------------------------------------- rtype_ :: (Eq a, Show a, PrettyPrec a, Specification s, MonadErr m, PrettyPrec err, AsErr err) => [PrettyM Doc] -- ^ terms we walked through, for error reporting -> (a -> Maybe (ValueIntro err s a)) -> TermInf s a -> m (ValueIntro err s a, ValueIntro err s a) rtype_ ts ctx term = case term of Var a -> case ctx a of Nothing -> throwErr $ VariableNotInScope (ppp0 a) ts Just t -> return (return a, t) Sort s -> case axiom s of Nothing -> throwErr $ SortWithoutAxiom (ppp0 s) ts Just s' -> return $ (ValueSort s, ValueSort s') Ann x t -> do (t', _) <- rsort_ ts' ctx t x' <- rcheck_ ts' ctx x t' return (x', t') App f x -> do (f', ft) <- rtype_ ts' ctx f case ft of ValuePi _n a b -> do x' <- rcheck_ ts' ctx x a return (valueApp f' x', instantiate1 x' b) _ -> throwErr $ NotAFunction (ppp0 ft) (ppp0 f) (ppp0 x) ts' Pi x a b -> do (a', as) <- rsort_ ts' ctx a (b', bs) <- rsort_ ts' (addContext a' ctx) (fromScopeH b) case rule as bs of Nothing -> throwErr $ NoRule (ppp0 as) (ppp0 bs) ts Just cs -> return (ValuePi x a' (toScope b'), ValueSort cs) #ifdef LANGUAGE_PTS_HAS_SIGMA Sigma x a b -> do (a', as) <- rsort_ ts' ctx a (b', bs) <- rsort_ ts' (addContext a' ctx) (fromScopeH b) case rule as bs of Nothing -> throwErr $ NoRule (ppp0 as) (ppp0 bs) ts Just cs -> return (ValueSigma x a' (toScope b'), ValueSort cs) #endif #ifdef LANGUAGE_PTS_HAS_EQUALITY Equality a x y -> do (a', as) <- rsort_ ts' ctx a x' <- rcheck_ ts' ctx x a' y' <- rcheck_ ts' ctx y a' return (ValueEquality a' x' y', ValueSort as) J v4 a p r u v w -> do (a', _as) <- rsort_ ts' ctx a u' <- rcheck_ ts' ctx u a' v' <- rcheck_ ts' ctx v a' w' <- rcheck_ ts' ctx w (ValueEquality a' u' v') let pp = fromScopeH p let ctx' = addContext3 a' a' (ValueEquality (fmap (F . F) a') (return $ F $ B "x") (return $ B "y")) ctx (pp', _ps) <- rsort_ ts' ctx' (fmap wrap3 pp) let p' = toScope (fmap unwrap3 pp') r' <- rcheck_ ts' ctx r $ ValuePi "q" a' $ toScope $ instantiate3 (pure (B "q")) (pure (B "q")) ValueRefl (fmap F p') return (valueJ v4 a' p' r' u' v' w', instantiate3 u' v' w' p') #endif #ifdef LANGUAGE_PTS_HAS_PROP Unit -> return (ValueUnit, ValueSort typeSort) Empty -> return (ValueEmpty, ValueSort typeSort) I -> return (ValueI, ValueUnit) #endif #ifdef LANGUAGE_PTS_HAS_BOOL TermBool -> return (ValueBool, ValueSort typeSort) TermTrue -> return (ValueTrue, ValueBool) TermFalse -> return (ValueFalse, ValueBool) TermBoolElim x p t f b -> do Check b first , even we have it latter in the rule . b' <- rcheck_ ts' ctx b ValueBool sort of Booleans -- check sorts let pp = fromScopeH p (pp', bs) <- rsort_ ts' (addContext ValueBool ctx) pp let p' = toScope pp' case rule as bs of Nothing -> throwErr $ NoRule (ppp0 as) (ppp0 bs) ts Just _ -> pure () t' <- rcheck_ ts' ctx t (instantiate1 ValueTrue p') f' <- rcheck_ ts' ctx f (instantiate1 ValueFalse p') return (valueBoolElim x p' t' f' b', instantiate1 b' p') #ifdef LANGUAGE_PTS_HAS_BOOL_PRIM TermAnd x y -> do x' <- rcheck_ ts' ctx x ValueBool y' <- rcheck_ ts' ctx y ValueBool return (valueAnd x' y', ValueBool) #endif #endif #ifdef LANGUAGE_PTS_HAS_NAT TermNat -> return (ValueNat, ValueSort typeSort) TermNatZ -> return (ValueNatZ, ValueNat) TermNatS n -> do n' <- rcheck_ ts' ctx n ValueNat return (ValueNatS n', ValueNat) TermNatElim x p z s n -> do Check n first , even we have it latter in the rule . n' <- rcheck_ ts' ctx n ValueNat -- check motive let pp = fromScopeH p (pp', bs) <- rsort_ ts' (addContext ValueNat ctx) pp let p' = toScope pp' -- check sorts let as = typeSort -- sort of Natural numbers case rule as bs of Nothing -> throwErr $ NoRule (ppp0 as) (ppp0 bs) ts Just _ -> pure () z' <- rcheck_ ts' ctx z $ instantiate1 ValueNatZ p' s' <- rcheck_ ts' ctx s $ ValuePi "l" ValueNat $ toScope $ instantiate1 (pure (B "l")) (fmap F p') ~> instantiate1 (ValueNatS (pure (B "l"))) (fmap F p') return (valueNatElim x p' z' s' n', instantiate1 n' p') #ifdef LANGUAGE_PTS_HAS_NAT_PRIM TermPlus x y -> do x' <- rcheck_ ts' ctx x ValueNat y' <- rcheck_ ts' ctx y ValueNat return (valuePlus x' y', ValueNat) TermTimes x y -> do x' <- rcheck_ ts' ctx x ValueNat y' <- rcheck_ ts' ctx y ValueNat return (valueTimes x' y', ValueNat) #endif #endif #ifdef LANGUAGE_PTS_HAS_QUARKS Hadron qs -> return (ValueHadron qs, ValueSort typeSort) QuarkElim x p qs q -> do let qt :: Set.Set Sym qt = Map.keysSet qs let qt' = ValueHadron qt q' <- rcheck_ ts' ctx q qt' -- check motive let pp = fromScopeH p (pp', bs) <- rsort_ ts' (addContext qt' ctx) pp let p' = toScope pp' -- check sorts let as = typeSort -- sort of quarks case rule as bs of Nothing -> throwErr $ NoRule (ppp0 as) (ppp0 bs) ts Just _ -> pure () qs' <- ifor qs $ \k v -> rcheck_ ts' ctx v $ instantiate1 (ValueQuark k) p' return (valueQuarkElim x p' qs' q', instantiate1 q' p') #endif where ts' :: [PrettyM Doc] ts' = ppp0 term : ts ------------------------------------------------------------------------------- -- Infer sort ------------------------------------------------------------------------------- -- | Check that term is a of right sort type. -- -- More special version of 'rcheck_'. rsort_ :: (Eq a, Show a, PrettyPrec a, Specification s, MonadErr m, PrettyPrec err, AsErr err) => [PrettyM Doc] -> (a -> Maybe (ValueIntro err s a)) -> TermInf s a -> m (ValueIntro err s a, s) rsort_ ts ctx term = do (x, t) <- rtype_ ts ctx term case t of ValueSort s -> return (x, s) _ -> throwErr $ SomeErr $ "not a sort: " ++ prettyShow t ++ " " ++ prettyShow term ------------------------------------------------------------------------------- -- Checking ------------------------------------------------------------------------------- rcheck_ :: (Eq a, Show a, PrettyPrec a, Specification s, MonadErr m, PrettyPrec err, AsErr err) => [PrettyM Doc] -- ^ terms we walked through, for error reporting -> (a -> Maybe (ValueIntro err s a)) -> TermChk s a -> ValueIntro err s a -> m (ValueIntro err s a) rcheck_ ts ctx term t = case term of Inf u -> do (u', t') <- rtype_ ts' ctx u if t == t' then return u' else throwErr $ TypeMismatch (ppp0 t) (ppp0 t') (ppp0 u) ts Lam x e -> case t of ValuePi _ a b -> do let ee = fromScopeH e let bb = fromScope b bb' <- rcheck_ ts' (addContext a ctx) ee bb return (ValueLam x a (toScope bb')) _ -> throwErr $ LambdaNotPi (ppp0 t) (ppp0 term) ts #ifdef LANGUAGE_PTS_HAS_SIGMA Pair x y -> case t of ValueSigma _ a b -> do x' <- rcheck_ ts' ctx x a y' <- rcheck_ ts' ctx y (instantiate1 x' b) return (ValuePair x' y') _ -> throwErr $ PairNotSigma (ppp0 t) (ppp0 term) ts Match p x y e -> do (p', pt) <- rtype_ ts' ctx p case pt of ValueSigma _ a b -> do let ee = fromScopeH e let ctx' = addContext2 a b ctx ee' <- rcheck_ ts' ctx' (fmap wrap ee) (fmap (F . F) t) return (valueMatch p' x y (toScope (fmap unwrap ee'))) _ -> throwErr $ NotAPair (ppp0 pt) (ppp0 p) ts #endif #ifdef LANGUAGE_PTS_HAS_EQUALITY Refl -> case t of ValueEquality a x y -> if x == y then return ValueRefl else throwErr $ NonEqual (ppp0 x) (ppp0 y) (ppp0 a) ts _ -> throwErr $ ReflNotEquality (ppp0 t) ts #endif #ifdef LANGUAGE_PTS_HAS_PROP Absurd x -> do x' <- rcheck_ ts' ctx x ValueEmpty return (valueAbsurd t x') #endif #ifdef LANGUAGE_PTS_HAS_QUARKS Quark q -> case t of ValueHadron qs | Set.member q qs -> return (ValueQuark q) | otherwise -> throwErr $ QuarkNotInHadron q qs ts _ -> throwErr $ QuarkNotHadron q (ppp0 t) ts #endif where ts' :: [PrettyM Doc] ts' = ppp0 term : ts addContext :: ValueIntro err s a -- ^ x -> (a -> Maybe (ValueIntro err s a)) -- ^ context -> Var IrrSym a -> Maybe (ValueIntro err s (Var IrrSym a)) addContext x _ (B _) = Just (F <$> x) addContext _ f (F x) = fmap F <$> f x #ifdef LANGUAGE_PTS_HAS_SIGMA addContext2 :: ValueIntro err s a -> Scope IrrSym (ValueIntro err s) a -> (a -> Maybe (ValueIntro err s a)) -> Var IrrSym (Var IrrSym a) -> Maybe (ValueIntro err s (Var IrrSym (Var IrrSym a))) addContext2 x y = addContext (fromScope y) . addContext x wrap :: Var IrrSym2 a -> Var IrrSym (Var IrrSym a) wrap (B (IrrSym2 x)) = B (IrrSym x) wrap (B (IrrSym1 y)) = F (B (IrrSym y)) wrap (F z) = F (F z) unwrap :: Var IrrSym (Var IrrSym a) -> Var IrrSym2 a unwrap (B (IrrSym x)) = B (IrrSym2 x) unwrap (F (B (IrrSym y))) = B (IrrSym1 y) unwrap (F (F z)) = F z #endif #ifdef LANGUAGE_PTS_HAS_EQUALITY addContext3 :: ValueIntro err s a -> ValueIntro err s a -> ValueIntro err s (Var IrrSym (Var IrrSym a)) -> (a -> Maybe (ValueIntro err s a)) -> Var IrrSym (Var IrrSym (Var IrrSym a)) -> Maybe (ValueIntro err s (Var IrrSym (Var IrrSym (Var IrrSym a)))) addContext3 x y z = addContext z . addContext (fmap F y) . addContext x wrap3 :: Var IrrSym3 a -> Var IrrSym (Var IrrSym (Var IrrSym a)) wrap3 (B (IrrSymK x)) = B (IrrSym x) wrap3 (B (IrrSymJ y)) = F (B (IrrSym y)) wrap3 (B (IrrSymI z)) = F (F (B (IrrSym z))) wrap3 (F z) = F (F (F z)) unwrap3 :: Var IrrSym (Var IrrSym (Var IrrSym a)) -> Var IrrSym3 a unwrap3 (B (IrrSym x)) = B (IrrSymK x) unwrap3 (F (B (IrrSym y))) = B (IrrSymJ y) unwrap3 (F (F (B (IrrSym z)))) = B (IrrSymI z) unwrap3 (F (F (F z))) = F z #endif
null
https://raw.githubusercontent.com/phadej/language-pts/761e5b92b14506b75164bd3162487df2d7fbfa93/src/Language/PTS/Check.hs
haskell
# LANGUAGE OverloadedStrings # | Type-checker. ----------------------------------------------------------------------------- Type-checker ----------------------------------------------------------------------------- ^ environment ^ term to type-check ^ as result we get evaluated term and its type. | ... and check the type of 'TermChk'. ^ environment ^ term to check ^ expected type ^ as result we get evaluated term ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ^ terms we walked through, for error reporting check sorts check motive check sorts sort of Natural numbers check motive check sorts sort of quarks ----------------------------------------------------------------------------- Infer sort ----------------------------------------------------------------------------- | Check that term is a of right sort type. More special version of 'rcheck_'. ----------------------------------------------------------------------------- Checking ----------------------------------------------------------------------------- ^ terms we walked through, for error reporting ^ x ^ context
module Language.PTS.Check ( type_, check_, ) where import Language.PTS.Bound import Language.PTS.Error import Language.PTS.Pretty import Language.PTS.Specification import Language.PTS.Sym import Language.PTS.Term import Language.PTS.Value #ifdef LANGUAGE_PTS_HAS_NAT import Language.PTS.Smart #endif #ifdef LANGUAGE_PTS_HAS_QUARKS import Control.Lens (ifor) import qualified Data.Set as Set import qualified Data.Map as Map #endif | We can infer the type of ' TermInf ' ... type_ :: (Eq a, Show a, PrettyPrec a, Specification s, MonadErr m, PrettyPrec err, AsErr err) type_ = rtype_ [] check_ :: (Eq a, Show a, PrettyPrec a, Specification s, MonadErr m, PrettyPrec err, AsErr err) check_ = rcheck_ [] Synthesis rtype_ :: (Eq a, Show a, PrettyPrec a, Specification s, MonadErr m, PrettyPrec err, AsErr err) -> (a -> Maybe (ValueIntro err s a)) -> TermInf s a -> m (ValueIntro err s a, ValueIntro err s a) rtype_ ts ctx term = case term of Var a -> case ctx a of Nothing -> throwErr $ VariableNotInScope (ppp0 a) ts Just t -> return (return a, t) Sort s -> case axiom s of Nothing -> throwErr $ SortWithoutAxiom (ppp0 s) ts Just s' -> return $ (ValueSort s, ValueSort s') Ann x t -> do (t', _) <- rsort_ ts' ctx t x' <- rcheck_ ts' ctx x t' return (x', t') App f x -> do (f', ft) <- rtype_ ts' ctx f case ft of ValuePi _n a b -> do x' <- rcheck_ ts' ctx x a return (valueApp f' x', instantiate1 x' b) _ -> throwErr $ NotAFunction (ppp0 ft) (ppp0 f) (ppp0 x) ts' Pi x a b -> do (a', as) <- rsort_ ts' ctx a (b', bs) <- rsort_ ts' (addContext a' ctx) (fromScopeH b) case rule as bs of Nothing -> throwErr $ NoRule (ppp0 as) (ppp0 bs) ts Just cs -> return (ValuePi x a' (toScope b'), ValueSort cs) #ifdef LANGUAGE_PTS_HAS_SIGMA Sigma x a b -> do (a', as) <- rsort_ ts' ctx a (b', bs) <- rsort_ ts' (addContext a' ctx) (fromScopeH b) case rule as bs of Nothing -> throwErr $ NoRule (ppp0 as) (ppp0 bs) ts Just cs -> return (ValueSigma x a' (toScope b'), ValueSort cs) #endif #ifdef LANGUAGE_PTS_HAS_EQUALITY Equality a x y -> do (a', as) <- rsort_ ts' ctx a x' <- rcheck_ ts' ctx x a' y' <- rcheck_ ts' ctx y a' return (ValueEquality a' x' y', ValueSort as) J v4 a p r u v w -> do (a', _as) <- rsort_ ts' ctx a u' <- rcheck_ ts' ctx u a' v' <- rcheck_ ts' ctx v a' w' <- rcheck_ ts' ctx w (ValueEquality a' u' v') let pp = fromScopeH p let ctx' = addContext3 a' a' (ValueEquality (fmap (F . F) a') (return $ F $ B "x") (return $ B "y")) ctx (pp', _ps) <- rsort_ ts' ctx' (fmap wrap3 pp) let p' = toScope (fmap unwrap3 pp') r' <- rcheck_ ts' ctx r $ ValuePi "q" a' $ toScope $ instantiate3 (pure (B "q")) (pure (B "q")) ValueRefl (fmap F p') return (valueJ v4 a' p' r' u' v' w', instantiate3 u' v' w' p') #endif #ifdef LANGUAGE_PTS_HAS_PROP Unit -> return (ValueUnit, ValueSort typeSort) Empty -> return (ValueEmpty, ValueSort typeSort) I -> return (ValueI, ValueUnit) #endif #ifdef LANGUAGE_PTS_HAS_BOOL TermBool -> return (ValueBool, ValueSort typeSort) TermTrue -> return (ValueTrue, ValueBool) TermFalse -> return (ValueFalse, ValueBool) TermBoolElim x p t f b -> do Check b first , even we have it latter in the rule . b' <- rcheck_ ts' ctx b ValueBool sort of Booleans let pp = fromScopeH p (pp', bs) <- rsort_ ts' (addContext ValueBool ctx) pp let p' = toScope pp' case rule as bs of Nothing -> throwErr $ NoRule (ppp0 as) (ppp0 bs) ts Just _ -> pure () t' <- rcheck_ ts' ctx t (instantiate1 ValueTrue p') f' <- rcheck_ ts' ctx f (instantiate1 ValueFalse p') return (valueBoolElim x p' t' f' b', instantiate1 b' p') #ifdef LANGUAGE_PTS_HAS_BOOL_PRIM TermAnd x y -> do x' <- rcheck_ ts' ctx x ValueBool y' <- rcheck_ ts' ctx y ValueBool return (valueAnd x' y', ValueBool) #endif #endif #ifdef LANGUAGE_PTS_HAS_NAT TermNat -> return (ValueNat, ValueSort typeSort) TermNatZ -> return (ValueNatZ, ValueNat) TermNatS n -> do n' <- rcheck_ ts' ctx n ValueNat return (ValueNatS n', ValueNat) TermNatElim x p z s n -> do Check n first , even we have it latter in the rule . n' <- rcheck_ ts' ctx n ValueNat let pp = fromScopeH p (pp', bs) <- rsort_ ts' (addContext ValueNat ctx) pp let p' = toScope pp' case rule as bs of Nothing -> throwErr $ NoRule (ppp0 as) (ppp0 bs) ts Just _ -> pure () z' <- rcheck_ ts' ctx z $ instantiate1 ValueNatZ p' s' <- rcheck_ ts' ctx s $ ValuePi "l" ValueNat $ toScope $ instantiate1 (pure (B "l")) (fmap F p') ~> instantiate1 (ValueNatS (pure (B "l"))) (fmap F p') return (valueNatElim x p' z' s' n', instantiate1 n' p') #ifdef LANGUAGE_PTS_HAS_NAT_PRIM TermPlus x y -> do x' <- rcheck_ ts' ctx x ValueNat y' <- rcheck_ ts' ctx y ValueNat return (valuePlus x' y', ValueNat) TermTimes x y -> do x' <- rcheck_ ts' ctx x ValueNat y' <- rcheck_ ts' ctx y ValueNat return (valueTimes x' y', ValueNat) #endif #endif #ifdef LANGUAGE_PTS_HAS_QUARKS Hadron qs -> return (ValueHadron qs, ValueSort typeSort) QuarkElim x p qs q -> do let qt :: Set.Set Sym qt = Map.keysSet qs let qt' = ValueHadron qt q' <- rcheck_ ts' ctx q qt' let pp = fromScopeH p (pp', bs) <- rsort_ ts' (addContext qt' ctx) pp let p' = toScope pp' case rule as bs of Nothing -> throwErr $ NoRule (ppp0 as) (ppp0 bs) ts Just _ -> pure () qs' <- ifor qs $ \k v -> rcheck_ ts' ctx v $ instantiate1 (ValueQuark k) p' return (valueQuarkElim x p' qs' q', instantiate1 q' p') #endif where ts' :: [PrettyM Doc] ts' = ppp0 term : ts rsort_ :: (Eq a, Show a, PrettyPrec a, Specification s, MonadErr m, PrettyPrec err, AsErr err) => [PrettyM Doc] -> (a -> Maybe (ValueIntro err s a)) -> TermInf s a -> m (ValueIntro err s a, s) rsort_ ts ctx term = do (x, t) <- rtype_ ts ctx term case t of ValueSort s -> return (x, s) _ -> throwErr $ SomeErr $ "not a sort: " ++ prettyShow t ++ " " ++ prettyShow term rcheck_ :: (Eq a, Show a, PrettyPrec a, Specification s, MonadErr m, PrettyPrec err, AsErr err) -> (a -> Maybe (ValueIntro err s a)) -> TermChk s a -> ValueIntro err s a -> m (ValueIntro err s a) rcheck_ ts ctx term t = case term of Inf u -> do (u', t') <- rtype_ ts' ctx u if t == t' then return u' else throwErr $ TypeMismatch (ppp0 t) (ppp0 t') (ppp0 u) ts Lam x e -> case t of ValuePi _ a b -> do let ee = fromScopeH e let bb = fromScope b bb' <- rcheck_ ts' (addContext a ctx) ee bb return (ValueLam x a (toScope bb')) _ -> throwErr $ LambdaNotPi (ppp0 t) (ppp0 term) ts #ifdef LANGUAGE_PTS_HAS_SIGMA Pair x y -> case t of ValueSigma _ a b -> do x' <- rcheck_ ts' ctx x a y' <- rcheck_ ts' ctx y (instantiate1 x' b) return (ValuePair x' y') _ -> throwErr $ PairNotSigma (ppp0 t) (ppp0 term) ts Match p x y e -> do (p', pt) <- rtype_ ts' ctx p case pt of ValueSigma _ a b -> do let ee = fromScopeH e let ctx' = addContext2 a b ctx ee' <- rcheck_ ts' ctx' (fmap wrap ee) (fmap (F . F) t) return (valueMatch p' x y (toScope (fmap unwrap ee'))) _ -> throwErr $ NotAPair (ppp0 pt) (ppp0 p) ts #endif #ifdef LANGUAGE_PTS_HAS_EQUALITY Refl -> case t of ValueEquality a x y -> if x == y then return ValueRefl else throwErr $ NonEqual (ppp0 x) (ppp0 y) (ppp0 a) ts _ -> throwErr $ ReflNotEquality (ppp0 t) ts #endif #ifdef LANGUAGE_PTS_HAS_PROP Absurd x -> do x' <- rcheck_ ts' ctx x ValueEmpty return (valueAbsurd t x') #endif #ifdef LANGUAGE_PTS_HAS_QUARKS Quark q -> case t of ValueHadron qs | Set.member q qs -> return (ValueQuark q) | otherwise -> throwErr $ QuarkNotInHadron q qs ts _ -> throwErr $ QuarkNotHadron q (ppp0 t) ts #endif where ts' :: [PrettyM Doc] ts' = ppp0 term : ts addContext -> Var IrrSym a -> Maybe (ValueIntro err s (Var IrrSym a)) addContext x _ (B _) = Just (F <$> x) addContext _ f (F x) = fmap F <$> f x #ifdef LANGUAGE_PTS_HAS_SIGMA addContext2 :: ValueIntro err s a -> Scope IrrSym (ValueIntro err s) a -> (a -> Maybe (ValueIntro err s a)) -> Var IrrSym (Var IrrSym a) -> Maybe (ValueIntro err s (Var IrrSym (Var IrrSym a))) addContext2 x y = addContext (fromScope y) . addContext x wrap :: Var IrrSym2 a -> Var IrrSym (Var IrrSym a) wrap (B (IrrSym2 x)) = B (IrrSym x) wrap (B (IrrSym1 y)) = F (B (IrrSym y)) wrap (F z) = F (F z) unwrap :: Var IrrSym (Var IrrSym a) -> Var IrrSym2 a unwrap (B (IrrSym x)) = B (IrrSym2 x) unwrap (F (B (IrrSym y))) = B (IrrSym1 y) unwrap (F (F z)) = F z #endif #ifdef LANGUAGE_PTS_HAS_EQUALITY addContext3 :: ValueIntro err s a -> ValueIntro err s a -> ValueIntro err s (Var IrrSym (Var IrrSym a)) -> (a -> Maybe (ValueIntro err s a)) -> Var IrrSym (Var IrrSym (Var IrrSym a)) -> Maybe (ValueIntro err s (Var IrrSym (Var IrrSym (Var IrrSym a)))) addContext3 x y z = addContext z . addContext (fmap F y) . addContext x wrap3 :: Var IrrSym3 a -> Var IrrSym (Var IrrSym (Var IrrSym a)) wrap3 (B (IrrSymK x)) = B (IrrSym x) wrap3 (B (IrrSymJ y)) = F (B (IrrSym y)) wrap3 (B (IrrSymI z)) = F (F (B (IrrSym z))) wrap3 (F z) = F (F (F z)) unwrap3 :: Var IrrSym (Var IrrSym (Var IrrSym a)) -> Var IrrSym3 a unwrap3 (B (IrrSym x)) = B (IrrSymK x) unwrap3 (F (B (IrrSym y))) = B (IrrSymJ y) unwrap3 (F (F (B (IrrSym z)))) = B (IrrSymI z) unwrap3 (F (F (F z))) = F z #endif
dcdfc622581b6e840902e0350b26e6e50a523c18d82059dde60503d78d17cc6f
dpiponi/formal-weyl
Poly.hs
-- Formal power series. -- Note the big caveat for division. -- Probably best to use division only when constant term of divisor is non - zero . # LANGUAGE FlexibleInstances # module Poly where import Data.Array import Data.List import Data.Ratio import Data.Tuple import Debug.Trace import Control.Applicative import LeftDivide import Padded import Over import MShow import ISqrt2 data Poly a = P (Array Integer a) monomialTimes : : ( Fractional f ) = > f - > Integer - > Integer - > Integer - > Integer - > [ ( ( Integer , Integer ) , f ) ] monomialTimes u r s a b = monomialTimes ' u s a 1 ( r+a ) ( s+b ) where monomialTimes ' : : ( Fractional f ) = > f - > Integer - > Integer - > Integer - > Integer - > Integer - > [ ( ( Integer , Integer ) , f ) ] monomialTimes ' v 0 _ _ p q = [ ( ( p , q ) , v ) ] monomialTimes ' v _ 0 _ p q = [ ( ( p , q ) , v ) ] monomialTimes ' v _ _ _ 0 q = [ ( ( 0 , q ) , v ) ] monomialTimes ' v _ _ _ p 0 = [ ( ( p , 0 ) , v ) ] monomialTimes ' v s ' a ' t p q = ( ( p , q ) , v ) : monomialTimes ' ( v*fromIntegral s'*fromIntegral a'/fromIntegral t ) ( s'-1 ) ( a'-1 ) ( t+1 ) ( p-1 ) ( q-1 ) monomialTimes :: (Fractional f) => f -> Integer -> Integer -> Integer -> Integer -> [((Integer, Integer), f)] monomialTimes u r s a b = monomialTimes' u s a 1 (r+a) (s+b) where monomialTimes' :: (Fractional f) => f -> Integer -> Integer -> Integer -> Integer -> Integer -> [((Integer, Integer), f)] monomialTimes' v 0 _ _ p q = [((p, q), v)] monomialTimes' v _ 0 _ p q = [((p, q), v)] monomialTimes' v _ _ _ 0 q = [((0, q), v)] monomialTimes' v _ _ _ p 0 = [((p, 0), v)] monomialTimes' v s' a' t p q = ((p, q), v) : monomialTimes' (v*fromIntegral s'*fromIntegral a'/fromIntegral t) (s'-1) (a'-1) (t+1) (p-1) (q-1) -} combineBounds :: (Integer -> Integer -> Integer) -> Array Integer e1 -> Array Integer e -> (Integer, Integer) combineBounds f u v = let (_, nx) = bounds u (_, ny) = bounds v in (0, f nx ny) fn : : ( Ix i , e ) = > Array i e - > i - > e fn u i = if inRange ( bounds u ) i then u!i else 0 fn :: (Ix i, Num e) => Array i e -> i -> e fn u i = if inRange (bounds u) i then u!i else 0 -} polyPlus :: Num a => Poly a -> Poly a -> Poly a polyPlus (P u) (P v) = let bz = combineBounds max u v in P $ accumArray (+) 0 bz $ assocs u ++ assocs v polyEq :: (Show a, Num a, Eq a) => Poly a -> Poly a -> Bool polyEq (P u) (P v) = let bz = combineBounds max u v -- in and [fn u i == fn v i | i <- range bz] in and $ map snd $ padded $ (==) <$> (assocs u :- 0) <*> (assocs v :- 0) polyTimes :: (Num a, Fractional a) => Poly a -> Poly a -> Poly a polyTimes (P u) (P v) = let bz = combineBounds (+) u v in P $ accumArray (+) 0 bz [e | (r, p) <- assocs u, (a, q) <- assocs v, let e = (r+a, p*q)] -- in (i, j): i labels row, j column -- XXX What if list is empty? startsWithZero :: (Num a, Eq a) => Poly a -> Bool startsWithZero (P ws) = ws!0 == 0 removeFirst :: (Num a) => Poly a -> Poly a removeFirst (P ws) = let (_, n) = bounds ws in P $ ixmap (0, n-1) (\i -> i+1) ws instance (Show a, Eq a, Num a) => Eq (Poly a) where (==) = polyEq instance (Show a, Eq a, Fractional a, Num a, MShow a) => MShow (Poly a) where mshow' n x = parens 6 n (mshow x) mshow = polyShow instance (Show a, Eq a, Fractional a, Num a, MShow a) => Show (Poly a) where show = mshow monoPower :: Integer -> String -> String monoPower 0 _ = "" monoPower 1 s = s monoPower n s = s ++ superscript n polyRational :: Rational -> String polyRational = mshow polyRational' 1 = "" polyRational' u = polyRational u data Monomial a = M Integer a instance (Eq a, MShow a, Num a) => MShow (Monomial a) where mshow' n w = parens 7 n (mshow w) mshow (M i w) = atLeast "1" ((if w == 1 then "" else mshow' 7 w) ++ monoPower i "X") Can use mshow ' 6 for terms with i = = j = = 0 polyShow :: (Show a, Fractional a, MShow a, Num a, Eq a) => Poly a -> String polyShow u | u == 0 = "0" polyShow (P u) = sumMShow 0 -- ?? [M i w | (i, w) <- assocs u, w /= 0] polyShow' :: (Show a, Fractional a, Eq a, MShow a, Num a) => Poly a -> String polyShow' u = atLeast "0" $ polyShow u scalarTimes :: Num a => a -> Poly a -> Poly a scalarTimes s (P t) = P $ fmap (s *) t one, x :: Num a => Poly a one = P $ listArray (0, 0) [1] x = P $ listArray (0, 1) [0, 1] injectP :: Num a => a -> Poly a injectP u = P $ listArray ((0, 0)) [u] instance Over Poly where ι = injectP instance (Fractional a, Num a) => Num (Poly a) where fromInteger = injectP . fromInteger (+) = polyPlus (*) = polyTimes negate = scalarTimes (-1) abs = error "I don't know what abs would mean here." signum = error "Pretty sure signum makes no sense here." -- a `wLeftDivide` b = divide a by b on left, ie. b\a instance (MShow a, Eq a, Show a, Fractional a) => LeftDivide (Poly a) where a `wLeftDivide` b | startsWithZero a && startsWithZero b = removeFirst a `wLeftDivide` removeFirst b | otherwise = recip b*a instance (MShow a, Eq a, Show a, Fractional a) => Fractional (Poly a) where fromRational = injectP . fromRational a/b | startsWithZero a && startsWithZero b = removeFirst a/removeFirst b | otherwise = a*recip b recip (P u) = let vs = filter ((/= 0) . snd) $ assocs u in case vs of [(0, a)] -> injectP $ recip a a -> error $ "Can't compute recip: " ++ show a -- instance (Floating a) => Floating (Poly a) realP :: Num a => Poly a -> a realP (P w) = w!0 substitute :: (Num a, Num b) => (a -> Integer -> b) -> Poly a -> b substitute f (P ws) = sum [f w n | (n, w) <- assocs ws]
null
https://raw.githubusercontent.com/dpiponi/formal-weyl/f0b8e5e8f749877ceebb809f37a844df7a8e4969/Poly.hs
haskell
Formal power series. Note the big caveat for division. Probably best to use division only when constant term in and [fn u i == fn v i | i <- range bz] in (i, j): i labels row, j column XXX What if list is empty? ?? a `wLeftDivide` b = divide a by b on left, ie. b\a instance (Floating a) => Floating (Poly a)
of divisor is non - zero . # LANGUAGE FlexibleInstances # module Poly where import Data.Array import Data.List import Data.Ratio import Data.Tuple import Debug.Trace import Control.Applicative import LeftDivide import Padded import Over import MShow import ISqrt2 data Poly a = P (Array Integer a) monomialTimes : : ( Fractional f ) = > f - > Integer - > Integer - > Integer - > Integer - > [ ( ( Integer , Integer ) , f ) ] monomialTimes u r s a b = monomialTimes ' u s a 1 ( r+a ) ( s+b ) where monomialTimes ' : : ( Fractional f ) = > f - > Integer - > Integer - > Integer - > Integer - > Integer - > [ ( ( Integer , Integer ) , f ) ] monomialTimes ' v 0 _ _ p q = [ ( ( p , q ) , v ) ] monomialTimes ' v _ 0 _ p q = [ ( ( p , q ) , v ) ] monomialTimes ' v _ _ _ 0 q = [ ( ( 0 , q ) , v ) ] monomialTimes ' v _ _ _ p 0 = [ ( ( p , 0 ) , v ) ] monomialTimes ' v s ' a ' t p q = ( ( p , q ) , v ) : monomialTimes ' ( v*fromIntegral s'*fromIntegral a'/fromIntegral t ) ( s'-1 ) ( a'-1 ) ( t+1 ) ( p-1 ) ( q-1 ) monomialTimes :: (Fractional f) => f -> Integer -> Integer -> Integer -> Integer -> [((Integer, Integer), f)] monomialTimes u r s a b = monomialTimes' u s a 1 (r+a) (s+b) where monomialTimes' :: (Fractional f) => f -> Integer -> Integer -> Integer -> Integer -> Integer -> [((Integer, Integer), f)] monomialTimes' v 0 _ _ p q = [((p, q), v)] monomialTimes' v _ 0 _ p q = [((p, q), v)] monomialTimes' v _ _ _ 0 q = [((0, q), v)] monomialTimes' v _ _ _ p 0 = [((p, 0), v)] monomialTimes' v s' a' t p q = ((p, q), v) : monomialTimes' (v*fromIntegral s'*fromIntegral a'/fromIntegral t) (s'-1) (a'-1) (t+1) (p-1) (q-1) -} combineBounds :: (Integer -> Integer -> Integer) -> Array Integer e1 -> Array Integer e -> (Integer, Integer) combineBounds f u v = let (_, nx) = bounds u (_, ny) = bounds v in (0, f nx ny) fn : : ( Ix i , e ) = > Array i e - > i - > e fn u i = if inRange ( bounds u ) i then u!i else 0 fn :: (Ix i, Num e) => Array i e -> i -> e fn u i = if inRange (bounds u) i then u!i else 0 -} polyPlus :: Num a => Poly a -> Poly a -> Poly a polyPlus (P u) (P v) = let bz = combineBounds max u v in P $ accumArray (+) 0 bz $ assocs u ++ assocs v polyEq :: (Show a, Num a, Eq a) => Poly a -> Poly a -> Bool polyEq (P u) (P v) = let bz = combineBounds max u v in and $ map snd $ padded $ (==) <$> (assocs u :- 0) <*> (assocs v :- 0) polyTimes :: (Num a, Fractional a) => Poly a -> Poly a -> Poly a polyTimes (P u) (P v) = let bz = combineBounds (+) u v in P $ accumArray (+) 0 bz [e | (r, p) <- assocs u, (a, q) <- assocs v, let e = (r+a, p*q)] startsWithZero :: (Num a, Eq a) => Poly a -> Bool startsWithZero (P ws) = ws!0 == 0 removeFirst :: (Num a) => Poly a -> Poly a removeFirst (P ws) = let (_, n) = bounds ws in P $ ixmap (0, n-1) (\i -> i+1) ws instance (Show a, Eq a, Num a) => Eq (Poly a) where (==) = polyEq instance (Show a, Eq a, Fractional a, Num a, MShow a) => MShow (Poly a) where mshow' n x = parens 6 n (mshow x) mshow = polyShow instance (Show a, Eq a, Fractional a, Num a, MShow a) => Show (Poly a) where show = mshow monoPower :: Integer -> String -> String monoPower 0 _ = "" monoPower 1 s = s monoPower n s = s ++ superscript n polyRational :: Rational -> String polyRational = mshow polyRational' 1 = "" polyRational' u = polyRational u data Monomial a = M Integer a instance (Eq a, MShow a, Num a) => MShow (Monomial a) where mshow' n w = parens 7 n (mshow w) mshow (M i w) = atLeast "1" ((if w == 1 then "" else mshow' 7 w) ++ monoPower i "X") Can use mshow ' 6 for terms with i = = j = = 0 polyShow :: (Show a, Fractional a, MShow a, Num a, Eq a) => Poly a -> String polyShow u | u == 0 = "0" [M i w | (i, w) <- assocs u, w /= 0] polyShow' :: (Show a, Fractional a, Eq a, MShow a, Num a) => Poly a -> String polyShow' u = atLeast "0" $ polyShow u scalarTimes :: Num a => a -> Poly a -> Poly a scalarTimes s (P t) = P $ fmap (s *) t one, x :: Num a => Poly a one = P $ listArray (0, 0) [1] x = P $ listArray (0, 1) [0, 1] injectP :: Num a => a -> Poly a injectP u = P $ listArray ((0, 0)) [u] instance Over Poly where ι = injectP instance (Fractional a, Num a) => Num (Poly a) where fromInteger = injectP . fromInteger (+) = polyPlus (*) = polyTimes negate = scalarTimes (-1) abs = error "I don't know what abs would mean here." signum = error "Pretty sure signum makes no sense here." instance (MShow a, Eq a, Show a, Fractional a) => LeftDivide (Poly a) where a `wLeftDivide` b | startsWithZero a && startsWithZero b = removeFirst a `wLeftDivide` removeFirst b | otherwise = recip b*a instance (MShow a, Eq a, Show a, Fractional a) => Fractional (Poly a) where fromRational = injectP . fromRational a/b | startsWithZero a && startsWithZero b = removeFirst a/removeFirst b | otherwise = a*recip b recip (P u) = let vs = filter ((/= 0) . snd) $ assocs u in case vs of [(0, a)] -> injectP $ recip a a -> error $ "Can't compute recip: " ++ show a realP :: Num a => Poly a -> a realP (P w) = w!0 substitute :: (Num a, Num b) => (a -> Integer -> b) -> Poly a -> b substitute f (P ws) = sum [f w n | (n, w) <- assocs ws]
8c834ca0616ba05fdabf6445d49a8c9cd5bcd513499e75cbc6da5adc4cf1ef37
heyoka/faxe
esp_state_duration.erl
%% Date: 15.07.2019 - 09:55 Ⓒ 2019 heyoka %% @doc %% Computes the duration of a given state. The state is defined via a lambda expression. %% Timestamps for the duration are taken from the incoming data-point. %% %% For each consecutive point for which the lambda expression evaluates as true, %% the state duration will be incremented by the duration between points. %% When a point evaluates as false, the state duration is reset. %% %% The state duration will be added as an additional field to each point. %% If the expression evaluates to false, the value will be -1. %% When the lambda expression generates an error during evaluation, the point is discarded %% and does not affect the state duration. %% -module(esp_state_duration). -author("Alexander Minichmair"). %% API -behavior(df_component). -include("faxe.hrl"). -define(TOTAL_NAME, <<"_total">>). %% API -export([init/3, process/3, options/0, wants/0, emits/0]). -record(state, { node_id, lambda, as, unit, emit_total = false, state_change }). options() -> [ {lambda, lambda}, {as, binary, <<"state_duration">>}, {unit, duration, <<"1s">>}, {emit_total, is_set, false} ]. wants() -> point. emits() -> point. init(_NodeId, _Ins, #{lambda := Lambda, as := As, unit := Unit, emit_total := EmitTotal}) -> StateTrack = state_change:new(Lambda), {ok, all, #state{lambda = Lambda, as = As, unit = Unit, emit_total = EmitTotal, state_change = StateTrack}}. process(_In, #data_batch{points = _Points} = _Batch, _State = #state{lambda = _Lambda}) -> {error, not_implemented}; process(_Inport, #data_point{} = Point, State = #state{ as = As, state_change = StateTrack}) -> case state_change:process(StateTrack, Point) of {ok, NewStateTrack} -> Duration = state_change:get_duration(NewStateTrack), NewPoint = flowdata:set_field(Point, As, Duration), {emit, NewPoint, State#state{state_change = NewStateTrack}}; {error, Error} -> lager:error("Error evaluating lambda: ~p",[Error]), {ok, State} end.
null
https://raw.githubusercontent.com/heyoka/faxe/2317e092a54a670a46df4d4f8b49aee982708e4d/apps/faxe/src/components/esp_state_duration.erl
erlang
Date: 15.07.2019 - 09:55 @doc Computes the duration of a given state. The state is defined via a lambda expression. Timestamps for the duration are taken from the incoming data-point. For each consecutive point for which the lambda expression evaluates as true, the state duration will be incremented by the duration between points. When a point evaluates as false, the state duration is reset. The state duration will be added as an additional field to each point. If the expression evaluates to false, the value will be -1. When the lambda expression generates an error during evaluation, the point is discarded and does not affect the state duration. API API
Ⓒ 2019 heyoka -module(esp_state_duration). -author("Alexander Minichmair"). -behavior(df_component). -include("faxe.hrl"). -define(TOTAL_NAME, <<"_total">>). -export([init/3, process/3, options/0, wants/0, emits/0]). -record(state, { node_id, lambda, as, unit, emit_total = false, state_change }). options() -> [ {lambda, lambda}, {as, binary, <<"state_duration">>}, {unit, duration, <<"1s">>}, {emit_total, is_set, false} ]. wants() -> point. emits() -> point. init(_NodeId, _Ins, #{lambda := Lambda, as := As, unit := Unit, emit_total := EmitTotal}) -> StateTrack = state_change:new(Lambda), {ok, all, #state{lambda = Lambda, as = As, unit = Unit, emit_total = EmitTotal, state_change = StateTrack}}. process(_In, #data_batch{points = _Points} = _Batch, _State = #state{lambda = _Lambda}) -> {error, not_implemented}; process(_Inport, #data_point{} = Point, State = #state{ as = As, state_change = StateTrack}) -> case state_change:process(StateTrack, Point) of {ok, NewStateTrack} -> Duration = state_change:get_duration(NewStateTrack), NewPoint = flowdata:set_field(Point, As, Duration), {emit, NewPoint, State#state{state_change = NewStateTrack}}; {error, Error} -> lager:error("Error evaluating lambda: ~p",[Error]), {ok, State} end.
f9f8a09dec889abb8effb6b8d9488b7474c108528c1168dacd99b7929a72980d
haskell-beam/beam
employee1sql-agg.hs
# LANGUAGE MultiParamTypeClasses # -- ! BUILD_COMMAND: runhaskell --ghc-arg=-fglasgow-exts -XStandaloneDeriving -XTypeSynonymInstances -XDeriveGeneric -XGADTs -XOverloadedStrings -XFlexibleContexts -XFlexibleInstances -XTypeFamilies -XTypeApplications -XAllowAmbiguousTypes -XPartialTypeSignatures -fno-warn-partial-type-signatures -- ! BUILD_DIR: beam-sqlite/examples/ -- ! FORMAT: sql module Main where import Database.Beam hiding (withDatabaseDebug) import qualified Database.Beam as Beam import Database.Beam.Sqlite hiding (runBeamSqliteDebug) import qualified Database.Beam.Sqlite as Sqlite import Database.SQLite.Simple import Data.Text (Text) import Data.Int import Control.Monad import Data.IORef data UserT f = User { _userEmail :: Columnar f Text , _userFirstName :: Columnar f Text , _userLastName :: Columnar f Text , _userPassword :: Columnar f Text } deriving Generic type User = UserT Identity deriving instance Show User deriving instance Eq User instance Beamable UserT instance Table UserT where data PrimaryKey UserT f = UserId (Columnar f Text) deriving Generic primaryKey = UserId . _userEmail instance Beamable (PrimaryKey UserT) data ShoppingCartDb f = ShoppingCartDb { _shoppingCartUsers :: f (TableEntity UserT) } deriving Generic instance Database be ShoppingCartDb shoppingCartDb :: DatabaseSettings Sqlite ShoppingCartDb shoppingCartDb = defaultDbSettings main :: IO () main = do conn <- open ":memory:" execute_ conn "CREATE TABLE cart_users (email VARCHAR NOT NULL, first_name VARCHAR NOT NULL, last_name VARCHAR NOT NULL, password VARCHAR NOT NULL, PRIMARY KEY( email ));" runBeamSqlite conn $ runInsert $ insert (_shoppingCartUsers shoppingCartDb) $ insertValues [ User "" "James" "Smith" "b4cc344d25a2efe540adbf2678e2304c" {- james -} , User "" "Betty" "Jones" "82b054bd83ffad9b6cf8bdb98ce3cc2f" {- betty -} , User "" "Sam" "Taylor" "332532dcfaa1cbf61e2a266bd723612c" {- sam -} , User "" "James" "Pallo" "b4cc344d25a2efe540adbf2678e2304c" {- james -} , User "" "Betty" "Sims" "82b054bd83ffad9b6cf8bdb98ce3cc2f" {- betty -} , User "" "James" "O'Reily" "b4cc344d25a2efe540adbf2678e2304c" {- james -} , User "" "Sam" "Sophitz" "332532dcfaa1cbf61e2a266bd723612c" {- sam -} , User "" "Sam" "Jely" "332532dcfaa1cbf61e2a266bd723612c" {- sam -} ] let runBeamSqliteDebug _ = Sqlite.runBeamSqliteDebug putStrLn (do let putStrLn :: String -> IO () putStrLn _ = pure () BEAM_PLACEHOLDER )
null
https://raw.githubusercontent.com/haskell-beam/beam/3dc9f47b081384c99b45f3b4264f419ebc6d7b09/docs/beam-templates/employee1sql-agg.hs
haskell
! BUILD_COMMAND: runhaskell --ghc-arg=-fglasgow-exts -XStandaloneDeriving -XTypeSynonymInstances -XDeriveGeneric -XGADTs -XOverloadedStrings -XFlexibleContexts -XFlexibleInstances -XTypeFamilies -XTypeApplications -XAllowAmbiguousTypes -XPartialTypeSignatures -fno-warn-partial-type-signatures ! BUILD_DIR: beam-sqlite/examples/ ! FORMAT: sql james betty sam james betty james sam sam
# LANGUAGE MultiParamTypeClasses # module Main where import Database.Beam hiding (withDatabaseDebug) import qualified Database.Beam as Beam import Database.Beam.Sqlite hiding (runBeamSqliteDebug) import qualified Database.Beam.Sqlite as Sqlite import Database.SQLite.Simple import Data.Text (Text) import Data.Int import Control.Monad import Data.IORef data UserT f = User { _userEmail :: Columnar f Text , _userFirstName :: Columnar f Text , _userLastName :: Columnar f Text , _userPassword :: Columnar f Text } deriving Generic type User = UserT Identity deriving instance Show User deriving instance Eq User instance Beamable UserT instance Table UserT where data PrimaryKey UserT f = UserId (Columnar f Text) deriving Generic primaryKey = UserId . _userEmail instance Beamable (PrimaryKey UserT) data ShoppingCartDb f = ShoppingCartDb { _shoppingCartUsers :: f (TableEntity UserT) } deriving Generic instance Database be ShoppingCartDb shoppingCartDb :: DatabaseSettings Sqlite ShoppingCartDb shoppingCartDb = defaultDbSettings main :: IO () main = do conn <- open ":memory:" execute_ conn "CREATE TABLE cart_users (email VARCHAR NOT NULL, first_name VARCHAR NOT NULL, last_name VARCHAR NOT NULL, password VARCHAR NOT NULL, PRIMARY KEY( email ));" runBeamSqlite conn $ runInsert $ insert (_shoppingCartUsers shoppingCartDb) $ let runBeamSqliteDebug _ = Sqlite.runBeamSqliteDebug putStrLn (do let putStrLn :: String -> IO () putStrLn _ = pure () BEAM_PLACEHOLDER )
32ea50e9ce06401fd5c74efd9ee9a18c358288c13ff495bdf3f3cd86df44f346
aws-beam/aws-erlang
aws_mq.erl
%% WARNING: DO NOT EDIT, AUTO-GENERATED CODE! See -beam/aws-codegen for more details . @doc Amazon MQ is a managed message broker service for Apache ActiveMQ and %% RabbitMQ that makes it easy to set up and operate message brokers in the %% cloud. %% %% A message broker allows software applications and components to %% communicate using various programming languages, operating systems, and %% formal messaging protocols. -module(aws_mq). -export([create_broker/2, create_broker/3, create_configuration/2, create_configuration/3, create_tags/3, create_tags/4, create_user/4, create_user/5, delete_broker/3, delete_broker/4, delete_tags/3, delete_tags/4, delete_user/4, delete_user/5, describe_broker/2, describe_broker/4, describe_broker/5, describe_broker_engine_types/1, describe_broker_engine_types/3, describe_broker_engine_types/4, describe_broker_instance_options/1, describe_broker_instance_options/3, describe_broker_instance_options/4, describe_configuration/2, describe_configuration/4, describe_configuration/5, describe_configuration_revision/3, describe_configuration_revision/5, describe_configuration_revision/6, describe_user/3, describe_user/5, describe_user/6, list_brokers/1, list_brokers/3, list_brokers/4, list_configuration_revisions/2, list_configuration_revisions/4, list_configuration_revisions/5, list_configurations/1, list_configurations/3, list_configurations/4, list_tags/2, list_tags/4, list_tags/5, list_users/2, list_users/4, list_users/5, reboot_broker/3, reboot_broker/4, update_broker/3, update_broker/4, update_configuration/3, update_configuration/4, update_user/4, update_user/5]). -include_lib("hackney/include/hackney_lib.hrl"). %%==================================================================== %% API %%==================================================================== %% @doc Creates a broker. %% %% Note: This API is asynchronous. %% To create a broker , you must either use the AmazonMQFullAccess IAM policy or include the following EC2 permissions in your IAM policy . %% %% <ul><li>ec2:CreateNetworkInterface %% This permission is required to allow Amazon MQ to create an elastic network interface ( ENI ) on behalf of your account . %% %% </li> <li>ec2:CreateNetworkInterfacePermission %% This permission is required to attach the ENI to the broker instance . %% %% </li> <li>ec2:DeleteNetworkInterface %% %% </li> <li>ec2:DeleteNetworkInterfacePermission %% %% </li> <li>ec2:DetachNetworkInterface %% %% </li> <li>ec2:DescribeInternetGateways %% %% </li> <li>ec2:DescribeNetworkInterfaces %% < /li > < li > ec2 : DescribeNetworkInterfacePermissions %% %% </li> <li>ec2:DescribeRouteTables %% %% </li> <li>ec2:DescribeSecurityGroups %% %% </li> <li>ec2:DescribeSubnets %% < /li > < li > ec2 : DescribeVpcs %% %% </li></ul> For more information, see Create an IAM User and Get Your AWS Credentials and Never Modify or Delete the Amazon MQ Elastic Network Interface in the Amazon MQ Developer Guide . create_broker(Client, Input) -> create_broker(Client, Input, []). create_broker(Client, Input0, Options0) -> Method = post, Path = ["/v1/brokers"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Creates a new configuration for the specified configuration name. %% Amazon MQ uses the default configuration ( the engine type and version ) . create_configuration(Client, Input) -> create_configuration(Client, Input, []). create_configuration(Client, Input0, Options0) -> Method = post, Path = ["/v1/configurations"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Add a tag to a resource. create_tags(Client, ResourceArn, Input) -> create_tags(Client, ResourceArn, Input, []). create_tags(Client, ResourceArn, Input0, Options0) -> Method = post, Path = ["/v1/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = 204, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Creates an ActiveMQ user. create_user(Client, BrokerId, Username, Input) -> create_user(Client, BrokerId, Username, Input, []). create_user(Client, BrokerId, Username, Input0, Options0) -> Method = post, Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), "/users/", aws_util:encode_uri(Username), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Deletes a broker. %% %% Note: This API is asynchronous. delete_broker(Client, BrokerId, Input) -> delete_broker(Client, BrokerId, Input, []). delete_broker(Client, BrokerId, Input0, Options0) -> Method = delete, Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Removes a tag from a resource. delete_tags(Client, ResourceArn, Input) -> delete_tags(Client, ResourceArn, Input, []). delete_tags(Client, ResourceArn, Input0, Options0) -> Method = delete, Path = ["/v1/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = 204, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, QueryMapping = [ {<<"tagKeys">>, <<"TagKeys">>} ], {Query_, Input} = aws_request:build_headers(QueryMapping, Input2), request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Deletes an ActiveMQ user. delete_user(Client, BrokerId, Username, Input) -> delete_user(Client, BrokerId, Username, Input, []). delete_user(Client, BrokerId, Username, Input0, Options0) -> Method = delete, Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), "/users/", aws_util:encode_uri(Username), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Returns information about the specified broker. describe_broker(Client, BrokerId) when is_map(Client) -> describe_broker(Client, BrokerId, #{}, #{}). describe_broker(Client, BrokerId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_broker(Client, BrokerId, QueryMap, HeadersMap, []). describe_broker(Client, BrokerId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Describe available engine types and versions. describe_broker_engine_types(Client) when is_map(Client) -> describe_broker_engine_types(Client, #{}, #{}). describe_broker_engine_types(Client, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_broker_engine_types(Client, QueryMap, HeadersMap, []). describe_broker_engine_types(Client, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/broker-engine-types"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"engineType">>, maps:get(<<"engineType">>, QueryMap, undefined)}, {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Describe available broker instance options. describe_broker_instance_options(Client) when is_map(Client) -> describe_broker_instance_options(Client, #{}, #{}). describe_broker_instance_options(Client, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_broker_instance_options(Client, QueryMap, HeadersMap, []). describe_broker_instance_options(Client, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/broker-instance-options"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"engineType">>, maps:get(<<"engineType">>, QueryMap, undefined)}, {<<"hostInstanceType">>, maps:get(<<"hostInstanceType">>, QueryMap, undefined)}, {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}, {<<"storageType">>, maps:get(<<"storageType">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns information about the specified configuration. describe_configuration(Client, ConfigurationId) when is_map(Client) -> describe_configuration(Client, ConfigurationId, #{}, #{}). describe_configuration(Client, ConfigurationId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_configuration(Client, ConfigurationId, QueryMap, HeadersMap, []). describe_configuration(Client, ConfigurationId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/configurations/", aws_util:encode_uri(ConfigurationId), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns the specified configuration revision for the specified %% configuration. describe_configuration_revision(Client, ConfigurationId, ConfigurationRevision) when is_map(Client) -> describe_configuration_revision(Client, ConfigurationId, ConfigurationRevision, #{}, #{}). describe_configuration_revision(Client, ConfigurationId, ConfigurationRevision, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_configuration_revision(Client, ConfigurationId, ConfigurationRevision, QueryMap, HeadersMap, []). describe_configuration_revision(Client, ConfigurationId, ConfigurationRevision, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/configurations/", aws_util:encode_uri(ConfigurationId), "/revisions/", aws_util:encode_uri(ConfigurationRevision), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns information about an ActiveMQ user. describe_user(Client, BrokerId, Username) when is_map(Client) -> describe_user(Client, BrokerId, Username, #{}, #{}). describe_user(Client, BrokerId, Username, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_user(Client, BrokerId, Username, QueryMap, HeadersMap, []). describe_user(Client, BrokerId, Username, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), "/users/", aws_util:encode_uri(Username), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns a list of all brokers. list_brokers(Client) when is_map(Client) -> list_brokers(Client, #{}, #{}). list_brokers(Client, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_brokers(Client, QueryMap, HeadersMap, []). list_brokers(Client, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/brokers"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns a list of all revisions for the specified configuration. list_configuration_revisions(Client, ConfigurationId) when is_map(Client) -> list_configuration_revisions(Client, ConfigurationId, #{}, #{}). list_configuration_revisions(Client, ConfigurationId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_configuration_revisions(Client, ConfigurationId, QueryMap, HeadersMap, []). list_configuration_revisions(Client, ConfigurationId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/configurations/", aws_util:encode_uri(ConfigurationId), "/revisions"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns a list of all configurations. list_configurations(Client) when is_map(Client) -> list_configurations(Client, #{}, #{}). list_configurations(Client, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_configurations(Client, QueryMap, HeadersMap, []). list_configurations(Client, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/configurations"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Lists tags for a resource. list_tags(Client, ResourceArn) when is_map(Client) -> list_tags(Client, ResourceArn, #{}, #{}). list_tags(Client, ResourceArn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_tags(Client, ResourceArn, QueryMap, HeadersMap, []). list_tags(Client, ResourceArn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns a list of all ActiveMQ users. list_users(Client, BrokerId) when is_map(Client) -> list_users(Client, BrokerId, #{}, #{}). list_users(Client, BrokerId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_users(Client, BrokerId, QueryMap, HeadersMap, []). list_users(Client, BrokerId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), "/users"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Reboots a broker. %% %% Note: This API is asynchronous. reboot_broker(Client, BrokerId, Input) -> reboot_broker(Client, BrokerId, Input, []). reboot_broker(Client, BrokerId, Input0, Options0) -> Method = post, Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), "/reboot"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Adds a pending configuration change to a broker. update_broker(Client, BrokerId, Input) -> update_broker(Client, BrokerId, Input, []). update_broker(Client, BrokerId, Input0, Options0) -> Method = put, Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Updates the specified configuration. update_configuration(Client, ConfigurationId, Input) -> update_configuration(Client, ConfigurationId, Input, []). update_configuration(Client, ConfigurationId, Input0, Options0) -> Method = put, Path = ["/v1/configurations/", aws_util:encode_uri(ConfigurationId), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Updates the information for an ActiveMQ user. update_user(Client, BrokerId, Username, Input) -> update_user(Client, BrokerId, Username, Input, []). update_user(Client, BrokerId, Username, Input0, Options0) -> Method = put, Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), "/users/", aws_util:encode_uri(Username), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %%==================================================================== Internal functions %%==================================================================== -spec request(aws_client:aws_client(), atom(), iolist(), list(), list(), map() | undefined, list(), pos_integer() | undefined) -> {ok, {integer(), list()}} | {ok, Result, {integer(), list(), hackney:client()}} | {error, Error, {integer(), list(), hackney:client()}} | {error, term()} when Result :: map(), Error :: map(). request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> RequestFun = fun() -> do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) end, aws_request:request(RequestFun, Options). do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> Client1 = Client#{service => <<"mq">>}, Host = build_host(<<"mq">>, Client1), URL0 = build_url(Host, Path, Client1), URL = aws_request:add_query(URL0, Query), AdditionalHeaders1 = [ {<<"Host">>, Host} , {<<"Content-Type">>, <<"application/x-amz-json-1.1">>} ], Payload = case proplists:get_value(send_body_as_binary, Options) of true -> maps:get(<<"Body">>, Input, <<"">>); false -> encode_payload(Input) end, AdditionalHeaders = case proplists:get_value(append_sha256_content_hash, Options, false) of true -> add_checksum_hash_header(AdditionalHeaders1, Payload); false -> AdditionalHeaders1 end, Headers1 = aws_request:add_headers(AdditionalHeaders, Headers0), MethodBin = aws_request:method_to_binary(Method), SignedHeaders = aws_request:sign_request(Client1, MethodBin, URL, Headers1, Payload), Response = hackney:request(Method, URL, SignedHeaders, Payload, Options), DecodeBody = not proplists:get_value(receive_body_as_binary, Options), handle_response(Response, SuccessStatusCode, DecodeBody). add_checksum_hash_header(Headers, Body) -> [ {<<"X-Amz-CheckSum-SHA256">>, base64:encode(crypto:hash(sha256, Body))} | Headers ]. handle_response({ok, StatusCode, ResponseHeaders}, SuccessStatusCode, _DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> {ok, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders}, _, _DecodeBody) -> {error, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders, Client}, SuccessStatusCode, DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> case hackney:body(Client) of {ok, <<>>} when StatusCode =:= 200; StatusCode =:= SuccessStatusCode -> {ok, #{}, {StatusCode, ResponseHeaders, Client}}; {ok, Body} -> Result = case DecodeBody of true -> try jsx:decode(Body) catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; false -> #{<<"Body">> => Body} end, {ok, Result, {StatusCode, ResponseHeaders, Client}} end; handle_response({ok, StatusCode, _ResponseHeaders, _Client}, _, _DecodeBody) when StatusCode =:= 503 -> Retriable error if retries are enabled {error, service_unavailable}; handle_response({ok, StatusCode, ResponseHeaders, Client}, _, _DecodeBody) -> {ok, Body} = hackney:body(Client), try DecodedError = jsx:decode(Body), {error, DecodedError, {StatusCode, ResponseHeaders, Client}} catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; handle_response({error, Reason}, _, _DecodeBody) -> {error, Reason}. build_host(_EndpointPrefix, #{region := <<"local">>, endpoint := Endpoint}) -> Endpoint; build_host(_EndpointPrefix, #{region := <<"local">>}) -> <<"localhost">>; build_host(EndpointPrefix, #{region := Region, endpoint := Endpoint}) -> aws_util:binary_join([EndpointPrefix, Region, Endpoint], <<".">>). build_url(Host, Path0, Client) -> Proto = aws_client:proto(Client), Path = erlang:iolist_to_binary(Path0), Port = aws_client:port(Client), aws_util:binary_join([Proto, <<"://">>, Host, <<":">>, Port, Path], <<"">>). -spec encode_payload(undefined | map()) -> binary(). encode_payload(undefined) -> <<>>; encode_payload(Input) -> jsx:encode(Input).
null
https://raw.githubusercontent.com/aws-beam/aws-erlang/699287cee7dfc9dc8c08ced5f090dcc192c9cba8/src/aws_mq.erl
erlang
WARNING: DO NOT EDIT, AUTO-GENERATED CODE! RabbitMQ that makes it easy to set up and operate message brokers in the cloud. A message broker allows software applications and components to communicate using various programming languages, operating systems, and formal messaging protocols. ==================================================================== API ==================================================================== @doc Creates a broker. Note: This API is asynchronous. <ul><li>ec2:CreateNetworkInterface </li> <li>ec2:CreateNetworkInterfacePermission </li> <li>ec2:DeleteNetworkInterface </li> <li>ec2:DeleteNetworkInterfacePermission </li> <li>ec2:DetachNetworkInterface </li> <li>ec2:DescribeInternetGateways </li> <li>ec2:DescribeNetworkInterfaces </li> <li>ec2:DescribeRouteTables </li> <li>ec2:DescribeSecurityGroups </li> <li>ec2:DescribeSubnets </li></ul> For more information, see Create an IAM User and Get Your AWS @doc Creates a new configuration for the specified configuration name. @doc Add a tag to a resource. @doc Creates an ActiveMQ user. @doc Deletes a broker. Note: This API is asynchronous. @doc Removes a tag from a resource. @doc Deletes an ActiveMQ user. @doc Returns information about the specified broker. @doc Describe available engine types and versions. @doc Describe available broker instance options. @doc Returns information about the specified configuration. @doc Returns the specified configuration revision for the specified configuration. @doc Returns information about an ActiveMQ user. @doc Returns a list of all brokers. @doc Returns a list of all revisions for the specified configuration. @doc Returns a list of all configurations. @doc Lists tags for a resource. @doc Returns a list of all ActiveMQ users. @doc Reboots a broker. Note: This API is asynchronous. @doc Adds a pending configuration change to a broker. @doc Updates the specified configuration. @doc Updates the information for an ActiveMQ user. ==================================================================== ====================================================================
See -beam/aws-codegen for more details . @doc Amazon MQ is a managed message broker service for Apache ActiveMQ and -module(aws_mq). -export([create_broker/2, create_broker/3, create_configuration/2, create_configuration/3, create_tags/3, create_tags/4, create_user/4, create_user/5, delete_broker/3, delete_broker/4, delete_tags/3, delete_tags/4, delete_user/4, delete_user/5, describe_broker/2, describe_broker/4, describe_broker/5, describe_broker_engine_types/1, describe_broker_engine_types/3, describe_broker_engine_types/4, describe_broker_instance_options/1, describe_broker_instance_options/3, describe_broker_instance_options/4, describe_configuration/2, describe_configuration/4, describe_configuration/5, describe_configuration_revision/3, describe_configuration_revision/5, describe_configuration_revision/6, describe_user/3, describe_user/5, describe_user/6, list_brokers/1, list_brokers/3, list_brokers/4, list_configuration_revisions/2, list_configuration_revisions/4, list_configuration_revisions/5, list_configurations/1, list_configurations/3, list_configurations/4, list_tags/2, list_tags/4, list_tags/5, list_users/2, list_users/4, list_users/5, reboot_broker/3, reboot_broker/4, update_broker/3, update_broker/4, update_configuration/3, update_configuration/4, update_user/4, update_user/5]). -include_lib("hackney/include/hackney_lib.hrl"). To create a broker , you must either use the AmazonMQFullAccess IAM policy or include the following EC2 permissions in your IAM policy . This permission is required to allow Amazon MQ to create an elastic network interface ( ENI ) on behalf of your account . This permission is required to attach the ENI to the broker instance . < /li > < li > ec2 : DescribeNetworkInterfacePermissions < /li > < li > ec2 : DescribeVpcs Credentials and Never Modify or Delete the Amazon MQ Elastic Network Interface in the Amazon MQ Developer Guide . create_broker(Client, Input) -> create_broker(Client, Input, []). create_broker(Client, Input0, Options0) -> Method = post, Path = ["/v1/brokers"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). Amazon MQ uses the default configuration ( the engine type and version ) . create_configuration(Client, Input) -> create_configuration(Client, Input, []). create_configuration(Client, Input0, Options0) -> Method = post, Path = ["/v1/configurations"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). create_tags(Client, ResourceArn, Input) -> create_tags(Client, ResourceArn, Input, []). create_tags(Client, ResourceArn, Input0, Options0) -> Method = post, Path = ["/v1/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = 204, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). create_user(Client, BrokerId, Username, Input) -> create_user(Client, BrokerId, Username, Input, []). create_user(Client, BrokerId, Username, Input0, Options0) -> Method = post, Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), "/users/", aws_util:encode_uri(Username), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). delete_broker(Client, BrokerId, Input) -> delete_broker(Client, BrokerId, Input, []). delete_broker(Client, BrokerId, Input0, Options0) -> Method = delete, Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). delete_tags(Client, ResourceArn, Input) -> delete_tags(Client, ResourceArn, Input, []). delete_tags(Client, ResourceArn, Input0, Options0) -> Method = delete, Path = ["/v1/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = 204, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, QueryMapping = [ {<<"tagKeys">>, <<"TagKeys">>} ], {Query_, Input} = aws_request:build_headers(QueryMapping, Input2), request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). delete_user(Client, BrokerId, Username, Input) -> delete_user(Client, BrokerId, Username, Input, []). delete_user(Client, BrokerId, Username, Input0, Options0) -> Method = delete, Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), "/users/", aws_util:encode_uri(Username), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). describe_broker(Client, BrokerId) when is_map(Client) -> describe_broker(Client, BrokerId, #{}, #{}). describe_broker(Client, BrokerId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_broker(Client, BrokerId, QueryMap, HeadersMap, []). describe_broker(Client, BrokerId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). describe_broker_engine_types(Client) when is_map(Client) -> describe_broker_engine_types(Client, #{}, #{}). describe_broker_engine_types(Client, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_broker_engine_types(Client, QueryMap, HeadersMap, []). describe_broker_engine_types(Client, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/broker-engine-types"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"engineType">>, maps:get(<<"engineType">>, QueryMap, undefined)}, {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). describe_broker_instance_options(Client) when is_map(Client) -> describe_broker_instance_options(Client, #{}, #{}). describe_broker_instance_options(Client, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_broker_instance_options(Client, QueryMap, HeadersMap, []). describe_broker_instance_options(Client, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/broker-instance-options"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"engineType">>, maps:get(<<"engineType">>, QueryMap, undefined)}, {<<"hostInstanceType">>, maps:get(<<"hostInstanceType">>, QueryMap, undefined)}, {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}, {<<"storageType">>, maps:get(<<"storageType">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). describe_configuration(Client, ConfigurationId) when is_map(Client) -> describe_configuration(Client, ConfigurationId, #{}, #{}). describe_configuration(Client, ConfigurationId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_configuration(Client, ConfigurationId, QueryMap, HeadersMap, []). describe_configuration(Client, ConfigurationId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/configurations/", aws_util:encode_uri(ConfigurationId), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). describe_configuration_revision(Client, ConfigurationId, ConfigurationRevision) when is_map(Client) -> describe_configuration_revision(Client, ConfigurationId, ConfigurationRevision, #{}, #{}). describe_configuration_revision(Client, ConfigurationId, ConfigurationRevision, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_configuration_revision(Client, ConfigurationId, ConfigurationRevision, QueryMap, HeadersMap, []). describe_configuration_revision(Client, ConfigurationId, ConfigurationRevision, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/configurations/", aws_util:encode_uri(ConfigurationId), "/revisions/", aws_util:encode_uri(ConfigurationRevision), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). describe_user(Client, BrokerId, Username) when is_map(Client) -> describe_user(Client, BrokerId, Username, #{}, #{}). describe_user(Client, BrokerId, Username, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_user(Client, BrokerId, Username, QueryMap, HeadersMap, []). describe_user(Client, BrokerId, Username, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), "/users/", aws_util:encode_uri(Username), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). list_brokers(Client) when is_map(Client) -> list_brokers(Client, #{}, #{}). list_brokers(Client, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_brokers(Client, QueryMap, HeadersMap, []). list_brokers(Client, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/brokers"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). list_configuration_revisions(Client, ConfigurationId) when is_map(Client) -> list_configuration_revisions(Client, ConfigurationId, #{}, #{}). list_configuration_revisions(Client, ConfigurationId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_configuration_revisions(Client, ConfigurationId, QueryMap, HeadersMap, []). list_configuration_revisions(Client, ConfigurationId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/configurations/", aws_util:encode_uri(ConfigurationId), "/revisions"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). list_configurations(Client) when is_map(Client) -> list_configurations(Client, #{}, #{}). list_configurations(Client, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_configurations(Client, QueryMap, HeadersMap, []). list_configurations(Client, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/configurations"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). list_tags(Client, ResourceArn) when is_map(Client) -> list_tags(Client, ResourceArn, #{}, #{}). list_tags(Client, ResourceArn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_tags(Client, ResourceArn, QueryMap, HeadersMap, []). list_tags(Client, ResourceArn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). list_users(Client, BrokerId) when is_map(Client) -> list_users(Client, BrokerId, #{}, #{}). list_users(Client, BrokerId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_users(Client, BrokerId, QueryMap, HeadersMap, []). list_users(Client, BrokerId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), "/users"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)}, {<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). reboot_broker(Client, BrokerId, Input) -> reboot_broker(Client, BrokerId, Input, []). reboot_broker(Client, BrokerId, Input0, Options0) -> Method = post, Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), "/reboot"], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). update_broker(Client, BrokerId, Input) -> update_broker(Client, BrokerId, Input, []). update_broker(Client, BrokerId, Input0, Options0) -> Method = put, Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). update_configuration(Client, ConfigurationId, Input) -> update_configuration(Client, ConfigurationId, Input, []). update_configuration(Client, ConfigurationId, Input0, Options0) -> Method = put, Path = ["/v1/configurations/", aws_util:encode_uri(ConfigurationId), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). update_user(Client, BrokerId, Username, Input) -> update_user(Client, BrokerId, Username, Input, []). update_user(Client, BrokerId, Username, Input0, Options0) -> Method = put, Path = ["/v1/brokers/", aws_util:encode_uri(BrokerId), "/users/", aws_util:encode_uri(Username), ""], SuccessStatusCode = 200, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). Internal functions -spec request(aws_client:aws_client(), atom(), iolist(), list(), list(), map() | undefined, list(), pos_integer() | undefined) -> {ok, {integer(), list()}} | {ok, Result, {integer(), list(), hackney:client()}} | {error, Error, {integer(), list(), hackney:client()}} | {error, term()} when Result :: map(), Error :: map(). request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> RequestFun = fun() -> do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) end, aws_request:request(RequestFun, Options). do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> Client1 = Client#{service => <<"mq">>}, Host = build_host(<<"mq">>, Client1), URL0 = build_url(Host, Path, Client1), URL = aws_request:add_query(URL0, Query), AdditionalHeaders1 = [ {<<"Host">>, Host} , {<<"Content-Type">>, <<"application/x-amz-json-1.1">>} ], Payload = case proplists:get_value(send_body_as_binary, Options) of true -> maps:get(<<"Body">>, Input, <<"">>); false -> encode_payload(Input) end, AdditionalHeaders = case proplists:get_value(append_sha256_content_hash, Options, false) of true -> add_checksum_hash_header(AdditionalHeaders1, Payload); false -> AdditionalHeaders1 end, Headers1 = aws_request:add_headers(AdditionalHeaders, Headers0), MethodBin = aws_request:method_to_binary(Method), SignedHeaders = aws_request:sign_request(Client1, MethodBin, URL, Headers1, Payload), Response = hackney:request(Method, URL, SignedHeaders, Payload, Options), DecodeBody = not proplists:get_value(receive_body_as_binary, Options), handle_response(Response, SuccessStatusCode, DecodeBody). add_checksum_hash_header(Headers, Body) -> [ {<<"X-Amz-CheckSum-SHA256">>, base64:encode(crypto:hash(sha256, Body))} | Headers ]. handle_response({ok, StatusCode, ResponseHeaders}, SuccessStatusCode, _DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> {ok, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders}, _, _DecodeBody) -> {error, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders, Client}, SuccessStatusCode, DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> case hackney:body(Client) of {ok, <<>>} when StatusCode =:= 200; StatusCode =:= SuccessStatusCode -> {ok, #{}, {StatusCode, ResponseHeaders, Client}}; {ok, Body} -> Result = case DecodeBody of true -> try jsx:decode(Body) catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; false -> #{<<"Body">> => Body} end, {ok, Result, {StatusCode, ResponseHeaders, Client}} end; handle_response({ok, StatusCode, _ResponseHeaders, _Client}, _, _DecodeBody) when StatusCode =:= 503 -> Retriable error if retries are enabled {error, service_unavailable}; handle_response({ok, StatusCode, ResponseHeaders, Client}, _, _DecodeBody) -> {ok, Body} = hackney:body(Client), try DecodedError = jsx:decode(Body), {error, DecodedError, {StatusCode, ResponseHeaders, Client}} catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; handle_response({error, Reason}, _, _DecodeBody) -> {error, Reason}. build_host(_EndpointPrefix, #{region := <<"local">>, endpoint := Endpoint}) -> Endpoint; build_host(_EndpointPrefix, #{region := <<"local">>}) -> <<"localhost">>; build_host(EndpointPrefix, #{region := Region, endpoint := Endpoint}) -> aws_util:binary_join([EndpointPrefix, Region, Endpoint], <<".">>). build_url(Host, Path0, Client) -> Proto = aws_client:proto(Client), Path = erlang:iolist_to_binary(Path0), Port = aws_client:port(Client), aws_util:binary_join([Proto, <<"://">>, Host, <<":">>, Port, Path], <<"">>). -spec encode_payload(undefined | map()) -> binary(). encode_payload(undefined) -> <<>>; encode_payload(Input) -> jsx:encode(Input).
87ff14e522e6a7ee8eea69e5f0b105f875823ec309309e35fb10149ef4b35855
g000001/tagger
corpus-sysdcl.lisp
-*- Package : TDB ; Syntax : Common - Lisp ; Mode : Lisp ; Base : 10 -*- Copyright ( c ) 1992 , 1993 by Xerox Corporation . All rights reserved . (cl:eval-when (cl:compile cl:eval cl:load) (pdefsys:load-system-def :tdb-sysdcl)) (cl:in-package :tdb) (def-tdb-system :corpus ((:dir "corpus") (:sub-systems :util)) "corpus-protocol") ;;;; generic corpora (def-tdb-system :persistent-corpus ((:dir "corpus") (:sub-systems :corpus :b-tree)) ("persistent-corpus")) (def-tdb-system :append-corpus ((:dir "corpus") (:sub-systems :corpus :cons-resource)) ("append-corpus")) (def-tdb-system :directory-corpus ((:dir "corpus") (:sub-systems :corpus :persistent-corpus)) ("directory-corpus")) (def-tdb-system :file-corpus ((:dir "corpus") (:sub-systems :corpus :persistent-corpus)) ("file-corpus")) (def-tdb-system :brs ((:dir "corpus") (:sub-systems :ssb :file-corpus)) ("brs")) (def-tdb-system :rmail ((:dir "corpus") (:sub-systems :ssb :directory-corpus)) ("rmail")) (def-tdb-system :ircolls ((:dir "corpus") (:sub-systems :ssb :file-corpus)) ("ircolls")) (def-tdb-system :context ((:dir "corpus") (:sub-systems :tdb)) ("context-corpus")) (def-tdb-system :sentence-corpus ((:dir "corpus") (:sub-systems :cons-resource :tdb :ssb)) ("sentence-corpus")) ;;;; specific corpora (def-tdb-system :grolier ((:dir "corpus") (:sub-systems :brs)) ("grolier")) (def-tdb-system :nytimes ((:dir "corpus") (:sub-systems :brs :append-corpus)) ("nytimes")) (def-tdb-system :ssl-bio ((:dir "corpus") (:sub-systems :directory-corpus)) ("ssl-bio")) (def-tdb-system :moby-dick ((:dir "corpus") (:sub-systems :directory-corpus)) ("moby-dick")) (def-tdb-system :aesop ((:dir "corpus") (:sub-systems :directory-corpus)) ("aesop")) (def-tdb-system :alice-in-wonderland ((:dir "corpus") (:sub-systems :directory-corpus)) ("alice-in-wonderland")) (def-tdb-system :through-the-looking-glass ((:dir "corpus") (:sub-systems :directory-corpus)) ("through-the-looking-glass")) (def-tdb-system :peter-pan ((:dir "corpus") (:sub-systems :directory-corpus)) ("peter-pan")) (def-tdb-system :o-pioneers ((:dir "corpus") (:sub-systems :directory-corpus)) ("o-pioneers")) (def-tdb-system :far-from-the-madding-crowd ((:dir "corpus") (:sub-systems :directory-corpus)) ("far-from-the-madding-crowd")) (def-tdb-system :fbis ((:dir "corpus") (:sub-systems :corpus :date-parser :sgml-parser :lru-cache :persistent-corpus)) ("fbis")) (def-tdb-system :tipster ((:dir "corpus") (:sub-systems :corpus :analysis :sgml-parser :directory-corpus)) ("tipster")) (def-tdb-system :sec ((:dir "corpus") (:sub-systems :corpus :sgml-parser :directory-corpus)) ("sec")) (def-tdb-system :cacm ((:dir "corpus") (:sub-systems :ircolls)) ("cacm")) (def-tdb-system :cranfield ((:dir "corpus") (:sub-systems :ircolls)) ("cranfield")) (def-tdb-system :collected-works ((:dir "corpus") (:sub-systems :file-corpus)) ("collected-works")) (def-tdb-system :reuters ((:dir "corpus") (:sub-systems :directory-corpus)) ("reuters")) (def-tdb-system :brown ((:dir "corpus") (:sub-systems :directory-corpus :file-corpus)) ("brown"))
null
https://raw.githubusercontent.com/g000001/tagger/a4e0650c55aba44250871b96e2220e1b4953c6ab/orig/src/sysdcl/corpus-sysdcl.lisp
lisp
Syntax : Common - Lisp ; Mode : Lisp ; Base : 10 -*- generic corpora specific corpora
Copyright ( c ) 1992 , 1993 by Xerox Corporation . All rights reserved . (cl:eval-when (cl:compile cl:eval cl:load) (pdefsys:load-system-def :tdb-sysdcl)) (cl:in-package :tdb) (def-tdb-system :corpus ((:dir "corpus") (:sub-systems :util)) "corpus-protocol") (def-tdb-system :persistent-corpus ((:dir "corpus") (:sub-systems :corpus :b-tree)) ("persistent-corpus")) (def-tdb-system :append-corpus ((:dir "corpus") (:sub-systems :corpus :cons-resource)) ("append-corpus")) (def-tdb-system :directory-corpus ((:dir "corpus") (:sub-systems :corpus :persistent-corpus)) ("directory-corpus")) (def-tdb-system :file-corpus ((:dir "corpus") (:sub-systems :corpus :persistent-corpus)) ("file-corpus")) (def-tdb-system :brs ((:dir "corpus") (:sub-systems :ssb :file-corpus)) ("brs")) (def-tdb-system :rmail ((:dir "corpus") (:sub-systems :ssb :directory-corpus)) ("rmail")) (def-tdb-system :ircolls ((:dir "corpus") (:sub-systems :ssb :file-corpus)) ("ircolls")) (def-tdb-system :context ((:dir "corpus") (:sub-systems :tdb)) ("context-corpus")) (def-tdb-system :sentence-corpus ((:dir "corpus") (:sub-systems :cons-resource :tdb :ssb)) ("sentence-corpus")) (def-tdb-system :grolier ((:dir "corpus") (:sub-systems :brs)) ("grolier")) (def-tdb-system :nytimes ((:dir "corpus") (:sub-systems :brs :append-corpus)) ("nytimes")) (def-tdb-system :ssl-bio ((:dir "corpus") (:sub-systems :directory-corpus)) ("ssl-bio")) (def-tdb-system :moby-dick ((:dir "corpus") (:sub-systems :directory-corpus)) ("moby-dick")) (def-tdb-system :aesop ((:dir "corpus") (:sub-systems :directory-corpus)) ("aesop")) (def-tdb-system :alice-in-wonderland ((:dir "corpus") (:sub-systems :directory-corpus)) ("alice-in-wonderland")) (def-tdb-system :through-the-looking-glass ((:dir "corpus") (:sub-systems :directory-corpus)) ("through-the-looking-glass")) (def-tdb-system :peter-pan ((:dir "corpus") (:sub-systems :directory-corpus)) ("peter-pan")) (def-tdb-system :o-pioneers ((:dir "corpus") (:sub-systems :directory-corpus)) ("o-pioneers")) (def-tdb-system :far-from-the-madding-crowd ((:dir "corpus") (:sub-systems :directory-corpus)) ("far-from-the-madding-crowd")) (def-tdb-system :fbis ((:dir "corpus") (:sub-systems :corpus :date-parser :sgml-parser :lru-cache :persistent-corpus)) ("fbis")) (def-tdb-system :tipster ((:dir "corpus") (:sub-systems :corpus :analysis :sgml-parser :directory-corpus)) ("tipster")) (def-tdb-system :sec ((:dir "corpus") (:sub-systems :corpus :sgml-parser :directory-corpus)) ("sec")) (def-tdb-system :cacm ((:dir "corpus") (:sub-systems :ircolls)) ("cacm")) (def-tdb-system :cranfield ((:dir "corpus") (:sub-systems :ircolls)) ("cranfield")) (def-tdb-system :collected-works ((:dir "corpus") (:sub-systems :file-corpus)) ("collected-works")) (def-tdb-system :reuters ((:dir "corpus") (:sub-systems :directory-corpus)) ("reuters")) (def-tdb-system :brown ((:dir "corpus") (:sub-systems :directory-corpus :file-corpus)) ("brown"))
7520aa1f4acd708cb571b4f6aad7149c55829d3db2ada72d49ce821e1636d75a
jepsen-io/jepsen
bank.clj
(ns jepsen.ignite.bank "Simulates transfers between bank accounts" (:refer-clojure :exclude [test]) (:require [clojure.tools.logging :refer :all] [jepsen [ignite :as ignite] [checker :as checker] [client :as client] [nemesis :as nemesis] [generator :as gen]] [clojure.core.reducers :as r] [jepsen.checker.timeline :as timeline] [knossos.model :as model] [knossos.op :as op]) (:import (org.apache.ignite Ignition) (org.apache.ignite.transactions TransactionConcurrency TransactionIsolation) (org.apache.ignite.transactions TransactionTimeoutException) (org.apache.ignite.cache CacheMode CacheAtomicityMode CacheWriteSynchronizationMode))) (def n 10) (def account-balance 100) (def cache-name "ACCOUNTS") (defn read-values [cache n] (vals (.getAll cache (set (range 0 n))))) (defn read-values-tr [ignite cache n transaction-concurrency transaction-isolation] (with-open [tr (.txStart (.transactions ignite) transaction-concurrency transaction-isolation)] (let [values (read-values cache n)] (.commit tr) values))) (defn bank-checker "Balances must all be non-negative and sum to the model's total." [] (reify checker/Checker (check [this test history opts] (let [bad-reads (->> history (r/filter op/ok?) (r/filter #(= :read (:f %))) (r/map (fn [op] (let [balances (:value op)] (cond (not= n (count balances)) {:type :wrong-n :expected n :found (count balances) :op op} (not= (* n account-balance) (reduce + balances)) {:type :wrong-total :expected (* n account-balance) :found (reduce + balances) :op op} (some neg? balances) {:type :negative-value :found balances :op op})))) (r/filter identity) (into []))] {:valid? (empty? bad-reads) :bad-reads bad-reads})))) (defrecord BankClient [cache-initialised? ignite-config-file conn cache-config transaction-config] client/Client (open! [this test node] (let [config (ignite/configure-client (:nodes test) (:pds test)) conn (Ignition/start (.getCanonicalPath config))] (assoc this :conn conn))) (setup! [this test] (locking cache-initialised? (when (compare-and-set! cache-initialised? false true) (let [cache (.getOrCreateCache conn cache-config)] (dotimes [i n] (error "Creating account" i) (.put cache i account-balance)))))) (invoke! [_ test op] (try (case (:f op) :read (let [cache (.cache conn cache-name) value (read-values-tr conn cache n (:concurrency transaction-config) (:isolation transaction-config))] (assoc op :type :ok, :value value)) :transfer (let [cache (.cache conn cache-name) tx (.txStart (.transactions conn) (:concurrency transaction-config) (:isolation transaction-config))] (try (let [{:keys [from to amount]} (:value op) b1 (- (.get cache from) amount) b2 (+ (.get cache to) amount)] (cond (neg? b1) (do (.commit tx) (assoc op :type :fail, :error [:negative from b1])) (neg? b2) (do (.commit tx) (assoc op :type :fail, :error [:negative to b2])) true (do (.put cache from b1) (.put cache to b2) (.commit tx) (assoc op :type :ok)))) (catch Exception e (info (.getMessage e)) (assoc op :type :fail, :error (.printStackTrace e))) (finally (.close tx))))))) (teardown! [this test]) (close! [this test] (.destroy (.cache conn cache-name)) (.close conn))) (defn bank-read "Reads the current state of all accounts without any synchronization." [_ _] {:type :invoke, :f :read}) (defn bank-transfer "Transfers a random amount between two randomly selected accounts." [_ _] {:type :invoke :f :transfer :value {:from (long (rand-int n)) :to (long (rand-int n)) :amount (+ 1 (long (rand 5)))}}) (def bank-diff-transfer "Like transfer, but only transfers between *different* accounts." (gen/filter (fn [op] (not= (-> op :value :from) (-> op :value :to))) bank-transfer)) (defn test [opts] (ignite/basic-test (merge {:name "bank-test" :client (BankClient. (atom false) nil nil (ignite/get-cache-config opts cache-name) (ignite/get-transaction-config opts)) :checker (checker/compose {:perf (checker/perf) :timeline (timeline/html) :details (bank-checker)}) :generator (ignite/generator [bank-diff-transfer bank-read] (:time-limit opts))} opts)))
null
https://raw.githubusercontent.com/jepsen-io/jepsen/a75d5a50dd5fa8d639a622c124bf61253460b754/ignite/src/jepsen/ignite/bank.clj
clojure
(ns jepsen.ignite.bank "Simulates transfers between bank accounts" (:refer-clojure :exclude [test]) (:require [clojure.tools.logging :refer :all] [jepsen [ignite :as ignite] [checker :as checker] [client :as client] [nemesis :as nemesis] [generator :as gen]] [clojure.core.reducers :as r] [jepsen.checker.timeline :as timeline] [knossos.model :as model] [knossos.op :as op]) (:import (org.apache.ignite Ignition) (org.apache.ignite.transactions TransactionConcurrency TransactionIsolation) (org.apache.ignite.transactions TransactionTimeoutException) (org.apache.ignite.cache CacheMode CacheAtomicityMode CacheWriteSynchronizationMode))) (def n 10) (def account-balance 100) (def cache-name "ACCOUNTS") (defn read-values [cache n] (vals (.getAll cache (set (range 0 n))))) (defn read-values-tr [ignite cache n transaction-concurrency transaction-isolation] (with-open [tr (.txStart (.transactions ignite) transaction-concurrency transaction-isolation)] (let [values (read-values cache n)] (.commit tr) values))) (defn bank-checker "Balances must all be non-negative and sum to the model's total." [] (reify checker/Checker (check [this test history opts] (let [bad-reads (->> history (r/filter op/ok?) (r/filter #(= :read (:f %))) (r/map (fn [op] (let [balances (:value op)] (cond (not= n (count balances)) {:type :wrong-n :expected n :found (count balances) :op op} (not= (* n account-balance) (reduce + balances)) {:type :wrong-total :expected (* n account-balance) :found (reduce + balances) :op op} (some neg? balances) {:type :negative-value :found balances :op op})))) (r/filter identity) (into []))] {:valid? (empty? bad-reads) :bad-reads bad-reads})))) (defrecord BankClient [cache-initialised? ignite-config-file conn cache-config transaction-config] client/Client (open! [this test node] (let [config (ignite/configure-client (:nodes test) (:pds test)) conn (Ignition/start (.getCanonicalPath config))] (assoc this :conn conn))) (setup! [this test] (locking cache-initialised? (when (compare-and-set! cache-initialised? false true) (let [cache (.getOrCreateCache conn cache-config)] (dotimes [i n] (error "Creating account" i) (.put cache i account-balance)))))) (invoke! [_ test op] (try (case (:f op) :read (let [cache (.cache conn cache-name) value (read-values-tr conn cache n (:concurrency transaction-config) (:isolation transaction-config))] (assoc op :type :ok, :value value)) :transfer (let [cache (.cache conn cache-name) tx (.txStart (.transactions conn) (:concurrency transaction-config) (:isolation transaction-config))] (try (let [{:keys [from to amount]} (:value op) b1 (- (.get cache from) amount) b2 (+ (.get cache to) amount)] (cond (neg? b1) (do (.commit tx) (assoc op :type :fail, :error [:negative from b1])) (neg? b2) (do (.commit tx) (assoc op :type :fail, :error [:negative to b2])) true (do (.put cache from b1) (.put cache to b2) (.commit tx) (assoc op :type :ok)))) (catch Exception e (info (.getMessage e)) (assoc op :type :fail, :error (.printStackTrace e))) (finally (.close tx))))))) (teardown! [this test]) (close! [this test] (.destroy (.cache conn cache-name)) (.close conn))) (defn bank-read "Reads the current state of all accounts without any synchronization." [_ _] {:type :invoke, :f :read}) (defn bank-transfer "Transfers a random amount between two randomly selected accounts." [_ _] {:type :invoke :f :transfer :value {:from (long (rand-int n)) :to (long (rand-int n)) :amount (+ 1 (long (rand 5)))}}) (def bank-diff-transfer "Like transfer, but only transfers between *different* accounts." (gen/filter (fn [op] (not= (-> op :value :from) (-> op :value :to))) bank-transfer)) (defn test [opts] (ignite/basic-test (merge {:name "bank-test" :client (BankClient. (atom false) nil nil (ignite/get-cache-config opts cache-name) (ignite/get-transaction-config opts)) :checker (checker/compose {:perf (checker/perf) :timeline (timeline/html) :details (bank-checker)}) :generator (ignite/generator [bank-diff-transfer bank-read] (:time-limit opts))} opts)))
14f323861dcc90a02371516372dd2f57e983cd8543d6040c8b1e735a7dd095fc
qiao/sicp-solutions
1.20.scm
;; normal order: (gcd 206 40) (gcd 40 (remainder 206 40)) (if (= (remainder 206 40) 0) 40 (gcd (remainder 206 40) (remainder 40 (remainder 206 40)))) (gcd (remainder 206 40) (remainder 40 (remainder 206 40))) (if (= (remainder 40 (remainder 206 40)) 0) (remainder 206 40) (gcd (remainder 40 (remainder 206 40)) (remainder (remainder 206 40) (remainder 40 (remainder 206 40))))) (gcd (remainder 40 (remainder 206 40)) (remainder (remainder 206 40) (remainder 40 (remainder 206 40)))) (if (= (remainder (remainder 206 40) (remainder 40 (remainder 206 40))) 0) (remainder 40 (remainder 206 40)) (gcd (remainder (remainder 206 40) (remainder 40 (remainder 206 40))) (remainder (remainder 40 (remainder 206 40)) (remainder (remainder 206 40) (remainder 40 (remainder 206 40)))))) (gcd (remainder (remainder 206 40) (remainder 40 (remainder 206 40))) (remainder (remainder 40 (remainder 206 40)) (remainder (remainder 206 40) (remainder 40 (remainder 206 40))))) (if (= (remainder (remainder 40 (remainder 206 40)) (remainder (remainder 206 40) (remainder 40 (remainder 206 40)))) 0) (remainder (remainder 206 40) (remainder 40 (remainder 206 40))) (gcd (remainder (remainder 206 40) (remainder 40 (remainder 206 40))) (remainder (remainder 40 (remainder 206 40)) (remainder (remainder 206 40) (remainder 40 (remainder 206 40)))))) (remainder (remainder 206 40) (remainder 40 (remainder 206 40))) 2 ` remainder ' performed 18 times ;; applicative order: (gcd 206 40) (gcd 40 (remainder 206 40)) (gcd 40 6) (gcd 6 (remainder 40 6)) (gcd 6 4) (gcd 4 (remainder 6 4)) (gcd 4 2) (gcd 2 (remainder 4 2)) (gcd 2 0) 2 ` remainder ' performed 4 times
null
https://raw.githubusercontent.com/qiao/sicp-solutions/a2fe069ba6909710a0867bdb705b2e58b2a281af/chapter1/1.20.scm
scheme
normal order: applicative order:
(gcd 206 40) (gcd 40 (remainder 206 40)) (if (= (remainder 206 40) 0) 40 (gcd (remainder 206 40) (remainder 40 (remainder 206 40)))) (gcd (remainder 206 40) (remainder 40 (remainder 206 40))) (if (= (remainder 40 (remainder 206 40)) 0) (remainder 206 40) (gcd (remainder 40 (remainder 206 40)) (remainder (remainder 206 40) (remainder 40 (remainder 206 40))))) (gcd (remainder 40 (remainder 206 40)) (remainder (remainder 206 40) (remainder 40 (remainder 206 40)))) (if (= (remainder (remainder 206 40) (remainder 40 (remainder 206 40))) 0) (remainder 40 (remainder 206 40)) (gcd (remainder (remainder 206 40) (remainder 40 (remainder 206 40))) (remainder (remainder 40 (remainder 206 40)) (remainder (remainder 206 40) (remainder 40 (remainder 206 40)))))) (gcd (remainder (remainder 206 40) (remainder 40 (remainder 206 40))) (remainder (remainder 40 (remainder 206 40)) (remainder (remainder 206 40) (remainder 40 (remainder 206 40))))) (if (= (remainder (remainder 40 (remainder 206 40)) (remainder (remainder 206 40) (remainder 40 (remainder 206 40)))) 0) (remainder (remainder 206 40) (remainder 40 (remainder 206 40))) (gcd (remainder (remainder 206 40) (remainder 40 (remainder 206 40))) (remainder (remainder 40 (remainder 206 40)) (remainder (remainder 206 40) (remainder 40 (remainder 206 40)))))) (remainder (remainder 206 40) (remainder 40 (remainder 206 40))) 2 ` remainder ' performed 18 times (gcd 206 40) (gcd 40 (remainder 206 40)) (gcd 40 6) (gcd 6 (remainder 40 6)) (gcd 6 4) (gcd 4 (remainder 6 4)) (gcd 4 2) (gcd 2 (remainder 4 2)) (gcd 2 0) 2 ` remainder ' performed 4 times
68b55f45fffd95e1355bd867165a41867bb5be9be54243bd279aa54004ccd26a
7theta/re-frame-via
config.clj
;; Copyright (c) 7theta. All rights reserved. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (-v10.html) ;; which can be found in the LICENSE file at the root of this ;; distribution. ;; ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any others, from this software. (ns example.config (:require [taoensso.sente.server-adapters.http-kit :refer [get-sch-adapter]] [integrant.core :as ig])) (def config {:via.server/client-proxy {:sente-web-server-adapter (get-sch-adapter) :user-id-fn (fn [ring-req] (-> ring-req :params :user-id))} :via.server/router {:msg-handler (ig/ref :re-frame-via/authenticated-msg-handler) :client-proxy (ig/ref :via.server/client-proxy)} :re-frame-via/authenticated-msg-handler {:authenticator (ig/ref [:re-frame-via/authenticator]) :un-authenticated-message-set #{:api.example/login} :msg-handler (ig/ref :example/msg-handler)} :example/msg-handler {:authenticator (ig/ref [:re-frame-via/authenticator])} :re-frame-via/authenticator {:query-fn (ig/ref [:example/user-store])} :example/user-store nil}) (ig/load-namespaces config)
null
https://raw.githubusercontent.com/7theta/re-frame-via/ae530337eff4098991e937d6e06aa413d8ad7b45/example/src/clj/example/config.clj
clojure
Copyright (c) 7theta. All rights reserved. The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-v10.html) which can be found in the LICENSE file at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any others, from this software.
(ns example.config (:require [taoensso.sente.server-adapters.http-kit :refer [get-sch-adapter]] [integrant.core :as ig])) (def config {:via.server/client-proxy {:sente-web-server-adapter (get-sch-adapter) :user-id-fn (fn [ring-req] (-> ring-req :params :user-id))} :via.server/router {:msg-handler (ig/ref :re-frame-via/authenticated-msg-handler) :client-proxy (ig/ref :via.server/client-proxy)} :re-frame-via/authenticated-msg-handler {:authenticator (ig/ref [:re-frame-via/authenticator]) :un-authenticated-message-set #{:api.example/login} :msg-handler (ig/ref :example/msg-handler)} :example/msg-handler {:authenticator (ig/ref [:re-frame-via/authenticator])} :re-frame-via/authenticator {:query-fn (ig/ref [:example/user-store])} :example/user-store nil}) (ig/load-namespaces config)
b3ed3d4c85412724e13c120d7c50f1a1923e7b60aa7020fd683e65b776021f15
static-analysis-engineering/codehawk
bCHELFSymbolTable.ml
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Binary Analyzer Author : and ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2020 Kestrel Technology LLC Copyright ( c ) 2020 ( c ) 2021 - 2022 Aarno Labs LLC Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Binary Analyzer Author: A. Cody Schuffelen and Henny Sipma ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2020 Kestrel Technology LLC Copyright (c) 2020 Henny Sipma Copyright (c) 2021-2022 Aarno Labs LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================= *) chlib open CHPretty (* chutil *) open CHLogger open CHNumRecordTable open CHTraceResult open CHXmlDocument (* bchlib *) open BCHBasicTypes open BCHByteUtilities open BCHDataBlock open BCHDoubleword open BCHFunctionData open BCHFunctionSummaryLibrary open BCHLibTypes open BCHStreamWrapper open BCHSystemInfo open BCHSystemSettings (* bchlibelf *) open BCHELFDictionary open BCHELFSection open BCHELFTypes module H = Hashtbl module TR = CHTraceResult class elf_symbol_table_entry_t (index:int):elf_symbol_table_entry_int = object (self) val mutable name = "" val mutable st_name = wordzero val mutable st_value = wordzero val mutable st_size = wordzero val mutable st_info = 0 val mutable st_other = 0 val mutable st_shndx = 0 method id = index method read (ch:pushback_stream_int) = try begin 0 , 4 , Name ---------------------------------------------------------- This member holds an index into the object file 's symbol string table , which holds the character representations of the symbol names . If the value is non - zero , it represents a string table index that gives the symbol name . Otherwise , the symbol table entry has no name . --------------------------------------------------------------------- This member holds an index into the object file's symbol string table, which holds the character representations of the symbol names. If the value is non-zero, it represents a string table index that gives the symbol name. Otherwise, the symbol table entry has no name. --------------------------------------------------------------------- *) st_name <- ch#read_doubleword; 4 , 4 , Value --------------------------------------------------------- This member gives the value of the associated symbol . Depending on the context , this may be an absolute value , an address , etc . --------------------------------------------------------------------- This member gives the value of the associated symbol. Depending on the context, this may be an absolute value, an address, etc. --------------------------------------------------------------------- *) st_value <- ch#read_doubleword; 8 , 4 , Size ---------------------------------------------------------- Many symbols have associated sizes . For example , a data object 's size is the number of bytes contained in the object . This member holds 0 if the symbol has no size or an unknown size . --------------------------------------------------------------------- Many symbols have associated sizes. For example, a data object's size is the number of bytes contained in the object. This member holds 0 if the symbol has no size or an unknown size. --------------------------------------------------------------------- *) st_size <- ch#read_doubleword; 12 , 1 , Info --------------------------------------------------------- This member specifies the symbol 's type and binding attributes . A list of the values and meanings appears below . The following code shows how to manipulate the values . # define ELF32_ST_BIND(i ) ( ( i)>>4 ) # define ) ( ( i)&0xf ) # define ELF32_ST_INFO(b , t ) ( ( ( b)<<4)+((t)&0xf ) ) --------------------------------------------------------------------- This member specifies the symbol's type and binding attributes. A list of the values and meanings appears below. The following code shows how to manipulate the values. #define ELF32_ST_BIND(i) ((i)>>4) #define ELF32_ST_TYPE(i) ((i)&0xf) #define ELF32_ST_INFO(b,t) (((b)<<4)+((t)&0xf)) --------------------------------------------------------------------- *) st_info <- ch#read_byte; 13 , 1 , Other -------------------------------------------------------- This member currently holds 0 and has no defined meaning . --------------------------------------------------------------------- This member currently holds 0 and has no defined meaning. --------------------------------------------------------------------- *) st_other <- ch#read_byte; 14 , 2 , Section index ------------------------------------------------ Every symbol table entry is " defined " in relation to some section ; this member holds the relevant section header table index . As Figure 1 - 7 and the related text describe , some section indexes indicate special meanings . --------------------------------------------------------------------- Every symbol table entry is "defined" in relation to some section; this member holds the relevant section header table index. As Figure 1-7 and the related text describe, some section indexes indicate special meanings. --------------------------------------------------------------------- *) st_shndx <- ch#read_ui16; end with | IO.No_more_input -> begin ch_error_log#add "no more input" (STR "elf_symbol_table_entry_t#read") ; raise IO.No_more_input end method get_st_name = st_name method has_name = not (name = "") method set_name s = name <- s method get_name = name method get_st_binding = st_info lsr 4 method get_st_type = st_info land 15 method get_st_value = st_value method get_value = st_value method is_function = self#get_st_type = 2 method has_address_value = not (st_value#equal wordzero) method write_xml (node:xml_element_int) = let set = node#setAttribute in let seti = node#setIntAttribute in let setx t x = set t x#to_hex_string in begin setx "name" st_name; setx "value" st_value; setx "size" st_size; seti "info" st_info; seti "other" st_other; seti "shndx" st_shndx; seti "ix" index; end method to_rep_record = let nameix = elfdictionary#index_string name in let tags = [ st_name#to_hex_string; st_value#to_hex_string; st_size#to_hex_string] in let args = [nameix; st_info; st_other; st_shndx] in (tags,args) end class elf_symbol_table_t (s:string) (entrysize:int) (vaddr:doubleword_int):elf_symbol_table_int = object (self) val entries = H.create 3 inherit elf_raw_section_t s vaddr as super method read = try let ch = make_pushback_stream ~little_endian:system_info#is_little_endian s in let n = (String.length s) / entrysize in let c = ref 0 in begin while !c < n do let entry = new elf_symbol_table_entry_t !c in begin entry#read ch; H.add entries !c entry; c := !c + 1 end done; end with | IO.No_more_input -> ch_error_log#add "no more input" (LBLOCK [ STR "Unable to read the symbol table " ]) method set_symbol_names (t:elf_string_table_int) = H.iter (fun _ e -> e#set_name (t#get_string e#get_st_name#to_int)) entries method set_function_entry_points = let align (a: int) (size: int): int = (a / size) * size in let align_dw dw = TR.tget_ok (int_to_doubleword (align dw#to_int 2)) in H.iter (fun _ e -> if e#is_function && e#has_address_value then let addr = let v = e#get_st_value in if system_info#is_arm then align_dw v else v in ignore (functions_data#add_function addr)) entries method set_function_names = let align (a: int) (size: int): int = (a / size) * size in let align_dw dw = TR.tget_ok (int_to_doubleword (align dw#to_int 2)) in H.iter (fun _ e -> if e#is_function && e#has_address_value && e#has_name then let addr = let v = e#get_st_value in if system_info#is_arm then align_dw v else v in (functions_data#add_function addr)#add_name e#get_name) entries method set_mapping_symbols = let symbols = H.create 13 in let _ = H.iter (fun _ e -> if e#get_st_binding = 0 && e#get_st_type = 0 && e#has_address_value then match e#get_name with | "$a" | "$a.0" | "$a.1" | "$a.2" | "$d" | "$d.1" | "$t" -> H.add symbols e#get_st_value#index e#get_name | _ -> ()) entries in let symbols = List.sort Stdlib.compare (H.fold (fun k v a -> (k, v) :: a) symbols []) in let indata = ref None in let inarm = ref true in let make_db addr = match !indata with | Some addr_d -> log_titer (mk_tracelog_spec ~tag:"disassembly" "elf_symbol_table#set_mapping_symbols make_db") (fun db -> begin (if collect_diagnostics () then ch_diagnostics_log#add "data block from symbol table" (LBLOCK [addr_d#toPretty; STR " - "; addr#toPretty])); system_info#add_data_block db; indata := None end) (make_data_block addr_d addr "symbol-table") | _ -> () in List.iter (fun (addrix, name) -> match name with | "$d" | "$d.1" -> (match !indata with | Some _ -> () | None -> indata := Some (TR.tget_ok (index_to_doubleword addrix))) | "$t" when system_settings#has_thumb -> begin let addr = TR.tget_ok (index_to_doubleword addrix) in (if !inarm then begin system_settings#set_thumb; system_info#set_arm_thumb_switch addr#to_hex_string "T"; inarm := false end); make_db addr end (* $a.0,1,2 llvm-generated code? *) | "$a" | "$a.0" | "$a.1" | "$a.2" when system_settings#has_thumb -> begin let addr = TR.tget_ok (index_to_doubleword addrix) in (if not (!inarm) then begin system_info#set_arm_thumb_switch addr#to_hex_string "A"; inarm := true end); make_db addr end | _ -> ()) symbols method get_symbol (index:int) = if H.mem entries index then H.find entries index else raise (BCH_failure (LBLOCK [STR "Symbol with index "; INT index; STR " not found"])) method write_xml_symbols (node:xml_element_int) = let table = mk_num_record_table "symbol-table" in begin H.iter (fun _ e -> table#add e#id e#to_rep_record) entries; table#write_xml node end end let mk_elf_symbol_table s h vaddr = let entrysize = h#get_entry_size#to_int in let table = new elf_symbol_table_t s entrysize vaddr in begin table#read; table end let read_xml_elf_symbol_table (node:xml_element_int) = let s = read_xml_raw_data (node#getTaggedChild "hex-data") in let vaddr = TR.tget_ok (string_to_doubleword (node#getAttribute "vaddr")) in let entrysize = node#getIntAttribute "entrysize" in let table = new elf_symbol_table_t s entrysize vaddr in begin table#read; table end
null
https://raw.githubusercontent.com/static-analysis-engineering/codehawk/c1b3158e0d73cda7cfc10d75f6173f4297991a82/CodeHawk/CHB/bchlibelf/bCHELFSymbolTable.ml
ocaml
chutil bchlib bchlibelf $a.0,1,2 llvm-generated code?
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Binary Analyzer Author : and ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2020 Kestrel Technology LLC Copyright ( c ) 2020 ( c ) 2021 - 2022 Aarno Labs LLC Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Binary Analyzer Author: A. Cody Schuffelen and Henny Sipma ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2020 Kestrel Technology LLC Copyright (c) 2020 Henny Sipma Copyright (c) 2021-2022 Aarno Labs LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================= *) chlib open CHPretty open CHLogger open CHNumRecordTable open CHTraceResult open CHXmlDocument open BCHBasicTypes open BCHByteUtilities open BCHDataBlock open BCHDoubleword open BCHFunctionData open BCHFunctionSummaryLibrary open BCHLibTypes open BCHStreamWrapper open BCHSystemInfo open BCHSystemSettings open BCHELFDictionary open BCHELFSection open BCHELFTypes module H = Hashtbl module TR = CHTraceResult class elf_symbol_table_entry_t (index:int):elf_symbol_table_entry_int = object (self) val mutable name = "" val mutable st_name = wordzero val mutable st_value = wordzero val mutable st_size = wordzero val mutable st_info = 0 val mutable st_other = 0 val mutable st_shndx = 0 method id = index method read (ch:pushback_stream_int) = try begin 0 , 4 , Name ---------------------------------------------------------- This member holds an index into the object file 's symbol string table , which holds the character representations of the symbol names . If the value is non - zero , it represents a string table index that gives the symbol name . Otherwise , the symbol table entry has no name . --------------------------------------------------------------------- This member holds an index into the object file's symbol string table, which holds the character representations of the symbol names. If the value is non-zero, it represents a string table index that gives the symbol name. Otherwise, the symbol table entry has no name. --------------------------------------------------------------------- *) st_name <- ch#read_doubleword; 4 , 4 , Value --------------------------------------------------------- This member gives the value of the associated symbol . Depending on the context , this may be an absolute value , an address , etc . --------------------------------------------------------------------- This member gives the value of the associated symbol. Depending on the context, this may be an absolute value, an address, etc. --------------------------------------------------------------------- *) st_value <- ch#read_doubleword; 8 , 4 , Size ---------------------------------------------------------- Many symbols have associated sizes . For example , a data object 's size is the number of bytes contained in the object . This member holds 0 if the symbol has no size or an unknown size . --------------------------------------------------------------------- Many symbols have associated sizes. For example, a data object's size is the number of bytes contained in the object. This member holds 0 if the symbol has no size or an unknown size. --------------------------------------------------------------------- *) st_size <- ch#read_doubleword; 12 , 1 , Info --------------------------------------------------------- This member specifies the symbol 's type and binding attributes . A list of the values and meanings appears below . The following code shows how to manipulate the values . # define ELF32_ST_BIND(i ) ( ( i)>>4 ) # define ) ( ( i)&0xf ) # define ELF32_ST_INFO(b , t ) ( ( ( b)<<4)+((t)&0xf ) ) --------------------------------------------------------------------- This member specifies the symbol's type and binding attributes. A list of the values and meanings appears below. The following code shows how to manipulate the values. #define ELF32_ST_BIND(i) ((i)>>4) #define ELF32_ST_TYPE(i) ((i)&0xf) #define ELF32_ST_INFO(b,t) (((b)<<4)+((t)&0xf)) --------------------------------------------------------------------- *) st_info <- ch#read_byte; 13 , 1 , Other -------------------------------------------------------- This member currently holds 0 and has no defined meaning . --------------------------------------------------------------------- This member currently holds 0 and has no defined meaning. --------------------------------------------------------------------- *) st_other <- ch#read_byte; 14 , 2 , Section index ------------------------------------------------ Every symbol table entry is " defined " in relation to some section ; this member holds the relevant section header table index . As Figure 1 - 7 and the related text describe , some section indexes indicate special meanings . --------------------------------------------------------------------- Every symbol table entry is "defined" in relation to some section; this member holds the relevant section header table index. As Figure 1-7 and the related text describe, some section indexes indicate special meanings. --------------------------------------------------------------------- *) st_shndx <- ch#read_ui16; end with | IO.No_more_input -> begin ch_error_log#add "no more input" (STR "elf_symbol_table_entry_t#read") ; raise IO.No_more_input end method get_st_name = st_name method has_name = not (name = "") method set_name s = name <- s method get_name = name method get_st_binding = st_info lsr 4 method get_st_type = st_info land 15 method get_st_value = st_value method get_value = st_value method is_function = self#get_st_type = 2 method has_address_value = not (st_value#equal wordzero) method write_xml (node:xml_element_int) = let set = node#setAttribute in let seti = node#setIntAttribute in let setx t x = set t x#to_hex_string in begin setx "name" st_name; setx "value" st_value; setx "size" st_size; seti "info" st_info; seti "other" st_other; seti "shndx" st_shndx; seti "ix" index; end method to_rep_record = let nameix = elfdictionary#index_string name in let tags = [ st_name#to_hex_string; st_value#to_hex_string; st_size#to_hex_string] in let args = [nameix; st_info; st_other; st_shndx] in (tags,args) end class elf_symbol_table_t (s:string) (entrysize:int) (vaddr:doubleword_int):elf_symbol_table_int = object (self) val entries = H.create 3 inherit elf_raw_section_t s vaddr as super method read = try let ch = make_pushback_stream ~little_endian:system_info#is_little_endian s in let n = (String.length s) / entrysize in let c = ref 0 in begin while !c < n do let entry = new elf_symbol_table_entry_t !c in begin entry#read ch; H.add entries !c entry; c := !c + 1 end done; end with | IO.No_more_input -> ch_error_log#add "no more input" (LBLOCK [ STR "Unable to read the symbol table " ]) method set_symbol_names (t:elf_string_table_int) = H.iter (fun _ e -> e#set_name (t#get_string e#get_st_name#to_int)) entries method set_function_entry_points = let align (a: int) (size: int): int = (a / size) * size in let align_dw dw = TR.tget_ok (int_to_doubleword (align dw#to_int 2)) in H.iter (fun _ e -> if e#is_function && e#has_address_value then let addr = let v = e#get_st_value in if system_info#is_arm then align_dw v else v in ignore (functions_data#add_function addr)) entries method set_function_names = let align (a: int) (size: int): int = (a / size) * size in let align_dw dw = TR.tget_ok (int_to_doubleword (align dw#to_int 2)) in H.iter (fun _ e -> if e#is_function && e#has_address_value && e#has_name then let addr = let v = e#get_st_value in if system_info#is_arm then align_dw v else v in (functions_data#add_function addr)#add_name e#get_name) entries method set_mapping_symbols = let symbols = H.create 13 in let _ = H.iter (fun _ e -> if e#get_st_binding = 0 && e#get_st_type = 0 && e#has_address_value then match e#get_name with | "$a" | "$a.0" | "$a.1" | "$a.2" | "$d" | "$d.1" | "$t" -> H.add symbols e#get_st_value#index e#get_name | _ -> ()) entries in let symbols = List.sort Stdlib.compare (H.fold (fun k v a -> (k, v) :: a) symbols []) in let indata = ref None in let inarm = ref true in let make_db addr = match !indata with | Some addr_d -> log_titer (mk_tracelog_spec ~tag:"disassembly" "elf_symbol_table#set_mapping_symbols make_db") (fun db -> begin (if collect_diagnostics () then ch_diagnostics_log#add "data block from symbol table" (LBLOCK [addr_d#toPretty; STR " - "; addr#toPretty])); system_info#add_data_block db; indata := None end) (make_data_block addr_d addr "symbol-table") | _ -> () in List.iter (fun (addrix, name) -> match name with | "$d" | "$d.1" -> (match !indata with | Some _ -> () | None -> indata := Some (TR.tget_ok (index_to_doubleword addrix))) | "$t" when system_settings#has_thumb -> begin let addr = TR.tget_ok (index_to_doubleword addrix) in (if !inarm then begin system_settings#set_thumb; system_info#set_arm_thumb_switch addr#to_hex_string "T"; inarm := false end); make_db addr end | "$a" | "$a.0" | "$a.1" | "$a.2" when system_settings#has_thumb -> begin let addr = TR.tget_ok (index_to_doubleword addrix) in (if not (!inarm) then begin system_info#set_arm_thumb_switch addr#to_hex_string "A"; inarm := true end); make_db addr end | _ -> ()) symbols method get_symbol (index:int) = if H.mem entries index then H.find entries index else raise (BCH_failure (LBLOCK [STR "Symbol with index "; INT index; STR " not found"])) method write_xml_symbols (node:xml_element_int) = let table = mk_num_record_table "symbol-table" in begin H.iter (fun _ e -> table#add e#id e#to_rep_record) entries; table#write_xml node end end let mk_elf_symbol_table s h vaddr = let entrysize = h#get_entry_size#to_int in let table = new elf_symbol_table_t s entrysize vaddr in begin table#read; table end let read_xml_elf_symbol_table (node:xml_element_int) = let s = read_xml_raw_data (node#getTaggedChild "hex-data") in let vaddr = TR.tget_ok (string_to_doubleword (node#getAttribute "vaddr")) in let entrysize = node#getIntAttribute "entrysize" in let table = new elf_symbol_table_t s entrysize vaddr in begin table#read; table end
74f6e363d19b255802db520f07975e1c9977f7aa8a7b0a12ae2826d4622aae04
xmonad/xmonad-extras
EvalServer.hs
----------------------------------------------------------------------------- -- | -- Module : XMonad.Hooks.EvalServer Copyright : ( c ) 2009 -- License : BSD3-style (see LICENSE) -- Maintainer : < > -- Stability : unstable -- Portability : unportable -- This module allows controlling XMonad through Haskell expressions sent -- via a socket. -- ----------------------------------------------------------------------------- module XMonad.Hooks.EvalServer ( -- * Usage -- $usage -- * Documentation -- $documentation initEVData ,startServer ,defaultServer ,defaultServerConfig ,evalEventHook ,EvalServerData ) where import Control.Concurrent import Control.Monad import Control.Concurrent.MVar import Data.Monoid import System.IO import XMonad.Actions.Eval import XMonad import Network -- $usage -- WARNING : This module will have the following issue if xmonad was n't compiled with -threaded ( requires a modified xmonad - version ): Expressions will only get evaluated when xmonad -- receives an event, for example when the focus changes. -- -- This module is highly experimental and might not work as expected or even cause deadlocks when used with -threaded , due to the fact that is n't reentrant . -- This module lets you create a server that evaluates expressions in the context of the currently running xmonad instance , which lets you control xmonad from another process(e.g . a script ) . -- To use this module add something like this to your xmonad.hs: -- -- > import XMonad.Hooks.EvalServer -- -- > main = do -- > evData <- initEVData -- > .. -- > xmonad $ .. $ defaultConfig { -- > handleEventHook = evalEventHook defaultServerConfig evData > startupHook = defaultServer evData 4242 -- > .. -- > } -- You can then send expressions that are to be evaluated over the socket . -- Example using telnet: -- > telnet localhost 4242 > windows $ W.view " 1 " -- By default , xmonad is not built with -threaded , so commands will only be executed after an event is received . , which is -- included in this package, is a workaround to this problem. After -- sending the command, it also sends an event to the root window -- to trigger the execution of the command. -- -- For more information run 'xmonadcmd --help' -- -- $documentation -- | Data type for storing information such as the socket and received commands data EvalServerData = EVData { evThreads :: MVar [(ThreadId,Handle)] , evCommands :: MVar [(String,Handle)] , evSocket :: MVar Socket } -- | Creates the structure to store received commands and other data. A variable of this -- type has to be passed to the other functions of this module. initEVData :: MonadIO m => m EvalServerData not so pretty , but fits on one line -- | Creates a server listening on a TCP socket with the given port number. defaultServer :: MonadIO m => EvalServerData -> PortNumber -> m () defaultServer cv = startServer cv . PortNumber | Creates a server listening on the specified port(can also be a unix domain socket ) . startServer :: MonadIO m => EvalServerData -> PortID -> m () startServer evdata port = liftIO $ do s <- listenOn port putMVar (evSocket evdata) s tid <- forkIO . forever $ accept s >>= clientThread evdata modifyMVar_ (evThreads evdata) $ return . ((tid,stdout):) return () -- | Default config to evaluate the received expressions defaultServerConfig :: EvalConfig defaultServerConfig = defaultEvalConfig { handleError = return . show } -- | This event hook causes commands to be executed when they are received. evalEventHook :: EvalConfig -> EvalServerData -> Event -> X All evalEventHook evConfig evdata (ClientMessageEvent { ev_message_type = mt }) = do dpy <- asks display update <- io $ internAtom dpy "XMONAD_EVALSRV_UPD" False restrt <- io $ internAtom dpy "XMONAD_RESTART" False if mt == update then do cmds <- io . tryTakeMVar . evCommands $ evdata whenJust cmds $ mapM_ $ \(cmd,h) -> evalExpressionWithReturn evConfig cmd >>= io . hPutStrLn h return $ All False else if mt == restrt then shutdownServer evdata >> return (All True) else return $ All True evalEventHook _ _ _ = return $ All True shutdownServer :: MonadIO m => EvalServerData -> m () shutdownServer evdata = liftIO $ do we need to kill the reading thread first , otherwise hClose will block modifyMVar_ (evThreads evdata) $ (>> return []) . mapM_ (\(tid,h) -> killThread tid >> hClose h) modifyMVar_ (evSocket evdata) $ \s -> sClose s >> return s -- | Handler for an individual client. clientThread :: EvalServerData -> (Handle,HostName,PortNumber) -> IO () clientThread evdata (h,_,_) = do tid <- forkIO $ do hSetBuffering h LineBuffering forever $ hGetLine h >>= handleCommand h evdata modifyMVar_ (evThreads evdata) $ return . ((tid,h):) -- | Handles a received command. TODO: Add a more elaborate protocol(e.g. one that allows shutting -- down the server). handleCommand :: Handle -> EvalServerData -> String -> IO () handleCommand h evdata cmd = openDisplay "" >>= \dpy -> do let cmds = evCommands evdata empt <- isEmptyMVar cmds if empt then putMVar cmds [(cmd,h)] else modifyMVar_ cmds (return . ((cmd,h):)) -- normally we should use forkProcess here, but this doesn't work due to ghc issue 1185 : forkIO with -threaded could potentially cause problems , as the Xlib is not reentrant , so not using a -threaded version of xmonad and sending -- some event to the root window to have getEvent return might be preferable. forkIO $ do rootw <- rootWindow dpy $ defaultScreen dpy a <- internAtom dpy "XMONAD_EVALSRV_UPD" False allocaXEvent $ \e -> do setEventType e clientMessage setClientMessageEvent e rootw a 32 0 currentTime sendEvent dpy rootw False structureNotifyMask e sync dpy False return ()
null
https://raw.githubusercontent.com/xmonad/xmonad-extras/d45b4cbfadbd8a6c2f0c062e5027a1c800b0e959/XMonad/Hooks/EvalServer.hs
haskell
--------------------------------------------------------------------------- | Module : XMonad.Hooks.EvalServer License : BSD3-style (see LICENSE) Stability : unstable Portability : unportable via a socket. --------------------------------------------------------------------------- * Usage $usage * Documentation $documentation $usage receives an event, for example when the focus changes. This module is highly experimental and might not work as expected or even cause deadlocks To use this module add something like this to your xmonad.hs: > import XMonad.Hooks.EvalServer > main = do > evData <- initEVData > .. > xmonad $ .. $ defaultConfig { > handleEventHook = evalEventHook defaultServerConfig evData > .. > } Example using telnet: included in this package, is a workaround to this problem. After sending the command, it also sends an event to the root window to trigger the execution of the command. For more information run 'xmonadcmd --help' $documentation | Data type for storing information such as the socket and received commands | Creates the structure to store received commands and other data. A variable of this type has to be passed to the other functions of this module. | Creates a server listening on a TCP socket with the given port number. | Default config to evaluate the received expressions | This event hook causes commands to be executed when they are received. | Handler for an individual client. | Handles a received command. TODO: Add a more elaborate protocol(e.g. one that allows shutting down the server). normally we should use forkProcess here, but this doesn't work some event to the root window to have getEvent return might be preferable.
Copyright : ( c ) 2009 Maintainer : < > This module allows controlling XMonad through Haskell expressions sent module XMonad.Hooks.EvalServer ( initEVData ,startServer ,defaultServer ,defaultServerConfig ,evalEventHook ,EvalServerData ) where import Control.Concurrent import Control.Monad import Control.Concurrent.MVar import Data.Monoid import System.IO import XMonad.Actions.Eval import XMonad import Network WARNING : This module will have the following issue if xmonad was n't compiled with -threaded ( requires a modified xmonad - version ): Expressions will only get evaluated when xmonad when used with -threaded , due to the fact that is n't reentrant . This module lets you create a server that evaluates expressions in the context of the currently running xmonad instance , which lets you control xmonad from another process(e.g . a script ) . > startupHook = defaultServer evData 4242 You can then send expressions that are to be evaluated over the socket . > telnet localhost 4242 > windows $ W.view " 1 " By default , xmonad is not built with -threaded , so commands will only be executed after an event is received . , which is data EvalServerData = EVData { evThreads :: MVar [(ThreadId,Handle)] , evCommands :: MVar [(String,Handle)] , evSocket :: MVar Socket } initEVData :: MonadIO m => m EvalServerData not so pretty , but fits on one line defaultServer :: MonadIO m => EvalServerData -> PortNumber -> m () defaultServer cv = startServer cv . PortNumber | Creates a server listening on the specified port(can also be a unix domain socket ) . startServer :: MonadIO m => EvalServerData -> PortID -> m () startServer evdata port = liftIO $ do s <- listenOn port putMVar (evSocket evdata) s tid <- forkIO . forever $ accept s >>= clientThread evdata modifyMVar_ (evThreads evdata) $ return . ((tid,stdout):) return () defaultServerConfig :: EvalConfig defaultServerConfig = defaultEvalConfig { handleError = return . show } evalEventHook :: EvalConfig -> EvalServerData -> Event -> X All evalEventHook evConfig evdata (ClientMessageEvent { ev_message_type = mt }) = do dpy <- asks display update <- io $ internAtom dpy "XMONAD_EVALSRV_UPD" False restrt <- io $ internAtom dpy "XMONAD_RESTART" False if mt == update then do cmds <- io . tryTakeMVar . evCommands $ evdata whenJust cmds $ mapM_ $ \(cmd,h) -> evalExpressionWithReturn evConfig cmd >>= io . hPutStrLn h return $ All False else if mt == restrt then shutdownServer evdata >> return (All True) else return $ All True evalEventHook _ _ _ = return $ All True shutdownServer :: MonadIO m => EvalServerData -> m () shutdownServer evdata = liftIO $ do we need to kill the reading thread first , otherwise hClose will block modifyMVar_ (evThreads evdata) $ (>> return []) . mapM_ (\(tid,h) -> killThread tid >> hClose h) modifyMVar_ (evSocket evdata) $ \s -> sClose s >> return s clientThread :: EvalServerData -> (Handle,HostName,PortNumber) -> IO () clientThread evdata (h,_,_) = do tid <- forkIO $ do hSetBuffering h LineBuffering forever $ hGetLine h >>= handleCommand h evdata modifyMVar_ (evThreads evdata) $ return . ((tid,h):) handleCommand :: Handle -> EvalServerData -> String -> IO () handleCommand h evdata cmd = openDisplay "" >>= \dpy -> do let cmds = evCommands evdata empt <- isEmptyMVar cmds if empt then putMVar cmds [(cmd,h)] else modifyMVar_ cmds (return . ((cmd,h):)) due to ghc issue 1185 : forkIO with -threaded could potentially cause problems , as the Xlib is not reentrant , so not using a -threaded version of xmonad and sending forkIO $ do rootw <- rootWindow dpy $ defaultScreen dpy a <- internAtom dpy "XMONAD_EVALSRV_UPD" False allocaXEvent $ \e -> do setEventType e clientMessage setClientMessageEvent e rootw a 32 0 currentTime sendEvent dpy rootw False structureNotifyMask e sync dpy False return ()
1cc265a5a70fc47c9c70ee8503d2db268784f9fb0f5599bd7ad1ee9beedbb6c2
incoherentsoftware/defect-process
Types.hs
module Window.Graphics.Texture.Manager.Types ( TextureManager(..) ) where import qualified Data.Map as M import Window.Graphics.Texture.Types data TextureManager = TextureManager { _textures :: M.Map FilePath Texture }
null
https://raw.githubusercontent.com/incoherentsoftware/defect-process/15f2569e7d0e481c2e28c0ca3a5e72d2c049b667/src/Window/Graphics/Texture/Manager/Types.hs
haskell
module Window.Graphics.Texture.Manager.Types ( TextureManager(..) ) where import qualified Data.Map as M import Window.Graphics.Texture.Types data TextureManager = TextureManager { _textures :: M.Map FilePath Texture }
c9cfabf53e7aad5b81c1bb2862fe329043643df15abac6276ec9f7c0d540748f
io-tupelo/clj-template
_bootstrap.clj
(ns _bootstrap "This namespace is used to perform one-time tasks at the beginning of a test run, such as printing the Clojure version." (:use tupelo.test) (:require [schema.core :as s] [tupelo.core :as t])) ; Prismatic Schema type definitions (s/set-fn-validation! true) ; enforce fn schemas (dotest (t/print-versions))
null
https://raw.githubusercontent.com/io-tupelo/clj-template/5fb85f035f65b69901331617226655b35b8c1aa2/test/clj/_bootstrap.clj
clojure
Prismatic Schema type definitions enforce fn schemas
(ns _bootstrap "This namespace is used to perform one-time tasks at the beginning of a test run, such as printing the Clojure version." (:use tupelo.test) (:require [schema.core :as s] [tupelo.core :as t])) (dotest (t/print-versions))
de87287aeb164772b1287193ffc1aeb6af2ec5fd61a6db58eeb350e0b4f21909
OCamlPro/alt-ergo
profiling.ml
(******************************************************************************) (* *) Alt - Ergo : The SMT Solver For Software Verification Copyright ( C ) 2013 - 2018 (* *) (* This file is distributed under the terms of the license indicated *) (* in the file 'License.OCamlPro'. If 'License.OCamlPro' is not *) (* present, please contact us to clarify licensing. *) (* *) (******************************************************************************) module SE = Expr.Set module MS = Map.Make(String) type inst_info = { loc : Loc.t; kept : int; ignored : int; all_insts : SE.t; confl : int; decided : int; consumed : SE.t; all : SE.t; produced : SE.t; _new : SE.t; } type t = { decisions : int ref; assumes : int ref; assumes_current_lvl : int ref; queries : int ref; instantiation_rounds : int ref; instances : int ref; decision_lvl : int ref; instantiation_lvl : int ref; 4 kinds of conflicts th_conflicts : int ref; b_conflicts : int ref; bcp_th_conflicts : int ref; bcp_b_conflicts : int ref; bcp_mix_conflicts : int ref; 4 kinds of red / elim t_red : int ref; b_red : int ref; t_elim : int ref; b_elim : int ref; first int : counter ok kept instances , second int : counter of removed instances second int: counter of removed instances*) instances_map : inst_info MS.t ref; instances_map_printed : bool ref } let state = { decisions = ref 0; assumes = ref 0; assumes_current_lvl = ref 0; queries = ref 0; instantiation_rounds = ref 0; instances = ref 0; decision_lvl = ref 0; instantiation_lvl = ref 0; th_conflicts = ref 0; b_conflicts = ref 0; bcp_th_conflicts = ref 0; bcp_b_conflicts = ref 0; bcp_mix_conflicts = ref 0; t_red = ref 0; b_red = ref 0; t_elim = ref 0; b_elim = ref 0; instances_map = ref MS.empty; instances_map_printed = ref false } let set_sigprof () = let tm = let v = Options.get_profiling_period () in if (Stdlib.compare v 0.) > 0 then v else -. v in ignore (Unix.setitimer Unix.ITIMER_PROF { Unix.it_value = tm; Unix.it_interval = 0. }) let init () = state.decisions := 0; state.assumes := 0; state.queries := 0; state.instantiation_rounds := 0; state.instances := 0; state.decision_lvl := 0; state.instantiation_lvl := 0; state.assumes_current_lvl := 0; state.th_conflicts := 0; state.b_conflicts := 0; state.bcp_th_conflicts := 0; state.bcp_b_conflicts := 0; state.bcp_mix_conflicts := 0; state.t_red := 0; state.b_red := 0; state.t_elim := 0; state.b_elim := 0; state.instances_map := MS.empty; state.instances_map_printed := false; set_sigprof () (* update functions of the internal state *) let assume nb = state.assumes := nb + !(state.assumes); state.assumes_current_lvl := nb + !(state.assumes_current_lvl) let query () = incr state.queries let instances l = state.instances := !(state.instances) + List.length l let instantiation ilvl = incr state.instantiation_rounds; incr state.instantiation_lvl; if not (!(state.instantiation_lvl) = ilvl) then begin Printer.print_err "state.instantiation_lvl = %d et ilvl = %d" !(state.instantiation_lvl) ilvl; assert false end let bool_conflict () = incr state.b_conflicts let theory_conflict () = incr state.th_conflicts let bcp_conflict b1 b2 = if b1 && b2 then incr state.bcp_b_conflicts else if (not b1) && (not b2) then incr state.bcp_th_conflicts else incr state.bcp_mix_conflicts let red b = if b then incr state.b_red else incr state.t_red let elim b = if b then incr state.b_elim else incr state.t_elim let reset_ilevel n = state.instantiation_lvl := n let reset_dlevel n = state.decision_lvl := n let empty_inst_info loc = { loc = loc; kept = 0; ignored = 0; confl = 0; decided = 0; all_insts = SE.empty; consumed = SE.empty; all = SE.empty; produced = SE.empty; _new = SE.empty; } let new_instance_of axiom inst loc kept = let () = state.instances_map_printed := false in let ii = try MS.find axiom !(state.instances_map) with Not_found -> empty_inst_info loc in assert (ii.loc == loc); let ii = if kept then {ii with kept = ii.kept + 1; all_insts = SE.add inst ii.all_insts} else {ii with ignored = ii.ignored + 1} in state.instances_map := MS.add axiom ii !(state.instances_map) let conflicting_instance axiom loc = let ii = try MS.find axiom !(state.instances_map) with Not_found -> empty_inst_info loc in let ii = {ii with confl = ii.confl + 1} in assert (ii.loc == loc); state.instances_map := MS.add axiom ii !(state.instances_map) let decision_on_instance axiom_name = try let ii = MS.find axiom_name !(state.instances_map) in let ii = {ii with decided = ii.decided + 1} in (*assert (ii.loc == loc);*) state.instances_map := MS.add axiom_name ii !(state.instances_map) with Not_found -> () let decision d origin = incr state.decisions; incr state.decision_lvl; if not (!(state.decision_lvl) = d) then begin Printer.print_err "state.decision_lvl = %d et d = %d" !(state.decision_lvl) d; assert false end; state.assumes_current_lvl := 0; decision_on_instance origin let register_produced_terms axiom loc consumed all produced _new = let ii = try MS.find axiom !(state.instances_map) with Not_found -> empty_inst_info loc in assert (ii.loc == loc); let ii = {ii with consumed = SE.union ii.consumed consumed; all = SE.union ii.all all; produced = SE.union ii.produced produced; _new = SE.union ii._new _new } in state.instances_map := MS.add axiom ii !(state.instances_map) (****************************************************************************** printing the internal state ******************************************************************************) type mode = | Stats | Timers | CallTree | FunctionsTimers | Instances let mode = ref Stats let max_nb_prints = 30 let nb_prints = ref max_nb_prints let initial_info = ref true let string_resize s i = let sz = max 0 (i - (String.length s)) in let tmp = String.make sz ' ' in s ^ tmp let int_resize n i = string_resize (Format.sprintf "%d" n) i let float_resize f i = string_resize (Format.sprintf "%f" f) i let percent total a = (string_of_int (int_of_float (a *. 100. /. total))) ^ "%" let columns = [ "GTimer", "Global timer", 11, None, (fun _ gtime _ sz -> float_resize gtime sz); "Steps", "Number of Steps", 14, None, (fun steps gtime _ sz -> let avg = int_of_float ((float_of_int steps) /. gtime) in Format.sprintf "%s~%s" (string_resize (Format.sprintf "%d" steps) (sz-7)) (string_resize (Format.sprintf "%d/s" avg) 6) ); "Case splits", "Number of Case Splits", 14, None, (fun _ gtime _ sz -> let avg = int_of_float (float_of_int (Steps.cs_steps()) /. gtime) in Format.sprintf "%s~%s" (string_resize (Format.sprintf "%d" (Steps.cs_steps())) (sz-7)) (string_resize (Format.sprintf "%d/s" avg) 6) ); "Mod.", "Current active module", 7, None, (fun _ _ timers sz -> let kd, _msg, _ = Timers.current_timer timers in string_resize (Timers.string_of_ty_module kd) sz); "Module Id", "Each call to a module is tagged with a fresh Id", 10, None, (fun _ _ timers sz -> let _kd, _msg, id = Timers.current_timer timers in int_resize id sz); (*-----------------------------------------------------------------*) "ilvl", "Current Instantiaton level", 6, Some true, (fun _ _ _ sz -> int_resize !(state.instantiation_lvl) sz); "#i rnds", "Number of intantiation rounds", 8, Some true, (fun _ _ _ sz -> int_resize !(state.instantiation_rounds) sz); "#insts", "Number of generated instances", 8, Some true, (fun _ _ _ sz -> int_resize !(state.instances) sz); "i/r", "AVG number of generated instances per instantiation rounds", 8, Some true, (fun _ _ _ sz -> int_resize (!(state.instances) / (max 1 !(state.instantiation_rounds))) sz); "dlvl", "Current Decision level", 6, Some true, (fun _ _ _ sz -> int_resize !(state.decision_lvl) sz); "#decs", "Number of decisions", 6, Some true, (fun _ _ _ sz -> int_resize !(state.decisions) sz); "T-asm", "Number of calls to Theory.assume", 6, Some true, (fun _ _ _ sz -> int_resize !(state.assumes) sz); "T/d", "Number of Theory.assume after last decision", 6, Some true, (fun _ _ _ sz -> int_resize !(state.assumes_current_lvl) sz); "T-qr", "Number of calls to Theory.query", 15, Some true, (fun _ _ _ sz -> int_resize !(state.queries) sz); "B-R", "Number of reduced clauses by Boolean propagation", 6, Some true, (fun _ _ _ sz -> int_resize !(state.b_red) sz); "B-E", "Number of eliminated clauses by Boolean propagation", 6, Some true, (fun _ _ _ sz -> int_resize !(state.b_elim) sz); "T-R", "Number of reduced clauses by Theory propagation", 6, Some true, (fun _ _ _ sz -> int_resize !(state.t_red) sz); "T-E", "Number of eliminated clauses by Theory propagation", 6, Some true, (fun _ _ _ sz -> int_resize !(state.t_elim) sz); "B-!", "Number of direct Boolean conflicts", 5, Some true, (fun _ _ _ sz -> int_resize !(state.b_conflicts) sz); "T-!", "Number of direct Theory conflicts" , 5, Some true, (fun _ _ _ sz -> int_resize !(state.th_conflicts) sz); "B>!", "Number of Boolean conflicts deduced by BCP", 5, Some true, (fun _ _ _ sz -> int_resize !(state.bcp_b_conflicts) sz); "T>!", "Number of Theory conflicts deduced by BCP", 5, Some true, (fun _ _ _ sz -> int_resize !(state.bcp_th_conflicts) sz); "M>!", "Number of Mix conflicts deduced by BCP", 5, Some true, (fun _ _ _ sz -> int_resize !(state.bcp_mix_conflicts) sz); (*-----------------------------------------------------------------*) "SAT", "Time spent in SAT module(s)", 16, Some false, (fun _ gtime timers sz -> let curr = Timers.get_sum timers Timers.M_Sat in Format.sprintf "%s~%s" (float_resize curr (sz - 5)) (string_resize (percent gtime curr) 4)); "Matching", "Time spent in Matching module(s)", 16, Some false, (fun _ gtime timers sz -> let curr = Timers.get_sum timers Timers.M_Match in Format.sprintf "%s~%s" (float_resize curr (sz - 5)) (string_resize (percent gtime curr) 4)); "CC", "Time spent in CC module(s)", 16, Some false, (fun _ gtime timers sz -> let curr = Timers.get_sum timers Timers.M_CC in Format.sprintf "%s~%s" (float_resize curr (sz - 5)) (string_resize (percent gtime curr) 4) ); "Arith", "Time spent in Arith module(s)", 16, Some false, (fun _ gtime timers sz -> let curr = Timers.get_sum timers Timers.M_Arith in Format.sprintf "%s~%s" (float_resize curr (sz - 5)) (string_resize (percent gtime curr) 4)); "Arrays", "Time spent in Arrays module(s)", 16, Some false, (fun _ gtime timers sz -> let curr = Timers.get_sum timers Timers.M_Arrays in Format.sprintf "%s~%s" (float_resize curr (sz - 5)) (string_resize (percent gtime curr) 4)); "Sum", "Time spent in Sum module(s)", 16, Some false, (fun _ gtime timers sz -> let curr = Timers.get_sum timers Timers.M_Sum in Format.sprintf "%s~%s" (float_resize curr (sz - 5)) (string_resize (percent gtime curr) 4)); "Records", "Time spent in Records module(s)", 16, Some false, (fun _ gtime timers sz -> let curr = Timers.get_sum timers Timers.M_Records in Format.sprintf "%s~%s" (float_resize curr (sz - 5)) (string_resize (percent gtime curr) 4)); "AC", "Time spent in AC module(s)", 16, Some false, (fun _ gtime timers sz -> let curr = Timers.get_sum timers Timers.M_AC in Format.sprintf "%s~%s" (float_resize curr (sz - 5)) (string_resize (percent gtime curr) 4)); "Total", "Time spent in 'supervised' module(s)", 11, Some false, (fun _ _ timers sz -> let tsat = Timers.get_sum timers Timers.M_Sat in let tmatch = Timers.get_sum timers Timers.M_Match in let tcc = Timers.get_sum timers Timers.M_CC in let tarith = Timers.get_sum timers Timers.M_Arith in let tarrays = Timers.get_sum timers Timers.M_Arrays in let tsum = Timers.get_sum timers Timers.M_Sum in let trecs = Timers.get_sum timers Timers.M_Records in let tac = Timers.get_sum timers Timers.M_AC in let total = tsat+.tmatch+.tcc+.tarith+.tarrays+.tsum+.trecs+.tac in float_resize total sz); ] let print_initial_info fmt = if !initial_info then begin initial_info := false; let max = List.fold_left (fun z (id,_, _,_,_) -> max z (String.length id)) 0 columns in List.iter (fun (id, descr, _, _, _) -> Format.fprintf fmt "%s : %s@." (string_resize id max) descr )columns end let stats_limit, timers_limit = let aux tmp sz = tmp := Format.sprintf "%s|" !tmp; for _ = 1 to sz do tmp := Format.sprintf "%s-" !tmp done in let tmp_s = ref "" in let tmp_t = ref "" in List.iter (fun (_, _, sz, opt, _) -> match opt with | Some true -> aux tmp_s sz | Some false -> aux tmp_t sz | _ -> aux tmp_s sz; aux tmp_t sz )columns; !tmp_s ^ "|", !tmp_t ^ "|" let print_header header fmt = let pp_stats = match !mode with Stats -> true | Timers -> false | _ -> assert false in if header || !nb_prints >= max_nb_prints then begin nb_prints := 0; Format.fprintf fmt "%s@." (if pp_stats then stats_limit else timers_limit); List.iter (fun (id, _, sz, opt, _) -> match opt with | Some b when b != pp_stats -> () | _ -> Format.fprintf fmt "|%s" (string_resize id sz) )columns; Format.fprintf fmt "|@."; Format.fprintf fmt "%s@." (if pp_stats then stats_limit else timers_limit) end; incr nb_prints let print_stats header steps fmt timers = print_header header fmt; let gtime = Options.Time.value() in List.iter (fun (_, _, sz, opt, func) -> match opt with | Some false -> () | _ -> Format.fprintf fmt "|%s" (func steps gtime timers sz) )columns; Format.fprintf fmt "|@." let print_timers header steps fmt timers = Timers.update timers; print_header header fmt; let gtime = Options.Time.value() in List.iter (fun (_, _, sz, opt, func) -> match opt with | Some true -> () | _ -> Format.fprintf fmt "|%s" (func steps gtime timers sz) )columns; Format.fprintf fmt "|@." unused let report2 axiom fmt ( b , e ) = let open Lexing in let l = b.pos_lnum in let fc = b.pos_cnum - b.pos_bol + 1 in let lc = e.pos_cnum - b.pos_bol + 1 in fprintf fmt " ( Sub ) Axiom \"%s\ " , line % d , characters % d-%d : " axiom l fc lc let report2 axiom fmt (b,e) = let open Lexing in let l = b.pos_lnum in let fc = b.pos_cnum - b.pos_bol + 1 in let lc = e.pos_cnum - b.pos_bol + 1 in fprintf fmt "(Sub) Axiom \"%s\", line %d, characters %d-%d:" axiom l fc lc *) unused let ( b , e ) = let open Lexing in let l = b.pos_lnum in let fc = b.pos_cnum - b.pos_bol + 1 in let lc = e.pos_cnum - b.pos_bol + 1 in fprintf fmt " line % d , chars % d-%d . " l fc lc let report3 fmt (b,e) = let open Lexing in let l = b.pos_lnum in let fc = b.pos_cnum - b.pos_bol + 1 in let lc = e.pos_cnum - b.pos_bol + 1 in fprintf fmt "line %d, chars %d-%d." l fc lc *) let (@@) a b = if a <> 0 then a else b let print_instances_generation forced _steps fmt _timers = if not forced && !(state.instances_map_printed) then Format.fprintf fmt "[Instances profiling] No change since last print@." else let () = state.instances_map_printed := true in if not forced then ignore(Sys.command("clear")); Format.fprintf fmt "[Instances profiling] ...@."; let insts = MS.fold (fun name ii acc -> let f1 = float_of_int ii.kept in let f2 = float_of_int ii.ignored in let ratio = f1 /. (f1 +. f2) in let all_card = SE.cardinal ii.all_insts in (name, ii, all_card, ratio) :: acc) !(state.instances_map) [] in let insts = List.fast_sort (fun (_, i1, c1, _) (_, i2, c2, _) -> (i1.decided - i2.decided) @@ (c1 - c2) @@ (i1.kept - i2.kept) @@ (i1.confl - i2.confl) @@ (i1.ignored - i2.ignored) @@ (SE.cardinal i1._new - SE.cardinal i2._new) ) insts in List.iter (let open Format in fun (name, i, card, r) -> fprintf fmt "ratio kept/all: %s| " (float_resize r 8); fprintf fmt "<> insts: %s| " (int_resize card 5); fprintf fmt "kept: %s| " (int_resize i.kept 7); fprintf fmt "ignored: %s| " (int_resize i.ignored 7) ; fprintf fmt "decided: %s| " (int_resize i.decided 4); fprintf fmt "conflicted: %s| " (int_resize i.confl 4); fprintf fmt "consumed: %s| " (int_resize (SE.cardinal i.consumed) 5); fprintf fmt "produced: %s| " (int_resize (SE.cardinal i.produced) 5); fprintf fmt "new: %s|| " (int_resize (SE.cardinal i._new) 5); fprintf fmt "%s" (string_resize name 30); " % s | " ( string_resize name 30 ) ; fprintf fmt " % a@. " report3 i.loc ( * too long fprintf fmt "%a@." report3 i.loc (* too long *) *) fprintf fmt "@." )insts; if forced then let ( ) = fprintf fmt " digraph v{@. " in fprintf fmt " size=\"10,7.5\"@. " ; fprintf fmt " ratio=\"fill\"@. " ; fprintf fmt " rotate=90@. " ; fprintf fmt " fontsize=\"12pt\"@. " ; fprintf fmt " rankdir = TB@. " ; let terms = ref SE.empty in List.iter ( fun ( name , i , _ ) - > ( fun t - > fprintf fmt " \"%d\ " - > \"%s\";@. " ( T.hash t ) name ) i.consumed ; terms : = SE.union ! terms i.consumed ; ( fun t - > fmt " \"%s\ " - > \"%d\";@. " name ( T.hash t ) ) i._new ; terms : = SE.union ! terms i._new ; fmt " \"%s\ " [ fillcolor = yellow];@. " name ; ) insts ; ( fun t - > fprintf fmt " \"%d\ " [ fillcolor = green];@. " ( T.hash t ) ; ) ! terms ; fmt " } @. " let () = fprintf fmt "digraph v{@." in fprintf fmt "size=\"10,7.5\"@."; fprintf fmt "ratio=\"fill\"@."; fprintf fmt "rotate=90@."; fprintf fmt "fontsize=\"12pt\"@."; fprintf fmt "rankdir = TB@." ; let terms = ref SE.empty in List.iter (fun (name, i, _) -> SE.iter (fun t -> fprintf fmt "\"%d\" -> \"%s\";@." (T.hash t) name )i.consumed; terms := SE.union !terms i.consumed; SE.iter (fun t -> fprintf fmt "\"%s\" -> \"%d\";@." name (T.hash t) )i._new; terms := SE.union !terms i._new; fprintf fmt "\"%s\" [fillcolor=yellow];@." name; )insts; SE.iter (fun t -> fprintf fmt "\"%d\" [fillcolor=green];@." (T.hash t); )!terms; fprintf fmt "}@."*) if forced then let ( ) = fprintf fmt " digraph v{@. " in fprintf fmt " size=\"10,7.5\"@. " ; fprintf fmt " ratio=\"fill\"@. " ; fprintf fmt " rotate=90@. " ; fprintf fmt " fontsize=\"12pt\"@. " ; fprintf fmt " rankdir = TB@. " ; List.iter ( fun ( s1 , i1 , _ ) - > List.iter ( fun ( s2 , i2 , _ ) - > if SE.is_empty ( SE.inter i1.produced i2.consumed ) then ( ) else fmt " \"%s\ " - > \"%s\";@. " s1 s2 ) insts ) insts ; fmt " } @. " if forced then let () = fprintf fmt "digraph v{@." in fprintf fmt "size=\"10,7.5\"@."; fprintf fmt "ratio=\"fill\"@."; fprintf fmt "rotate=90@."; fprintf fmt "fontsize=\"12pt\"@."; fprintf fmt "rankdir = TB@." ; List.iter (fun (s1, i1, _) -> List.iter (fun (s2, i2, _) -> if SE.is_empty (SE.inter i1.produced i2.consumed) then () else fprintf fmt "\"%s\" -> \"%s\";@." s1 s2 )insts )insts; fprintf fmt "}@."*) () let print_call_tree _forced _steps fmt timers = let stack = Timers.get_stack timers in List.iter (fun (k, f, id) -> Format.fprintf fmt "(%s, %s, %s) --> " (string_resize (Timers.string_of_ty_module k) 5) (string_resize (Timers.string_of_ty_function f) 10) (int_resize id 7) )(List.rev stack); let m, f, id = Timers.current_timer timers in Format.fprintf fmt "(%s, %s, %s)@." (string_resize (Timers.string_of_ty_module m) 5) (string_resize (Timers.string_of_ty_function f) 10) (int_resize id 7) let switch fmt = let next, next_msg = match !mode with | Stats -> Timers, "Time" | Timers -> CallTree, "CallTree" | CallTree -> FunctionsTimers, "Functions Timers" | FunctionsTimers -> Instances, "Instances generation" | Instances -> Stats, "Stats" in Format.fprintf fmt "@.>>> Switch to %s profiling. Use \"Ctrl + AltGr + \\\" to exit\n" next_msg; nb_prints := max_nb_prints; mode := next let float_print = let open Format in fun fmt v -> if Stdlib.(=) v 0. then fprintf fmt "-- " else if (Stdlib.compare v 10.) < 0 then fprintf fmt "%0.5f" v else if (Stdlib.compare v 100.) < 0 then fprintf fmt "%0.4f" v else fprintf fmt "%0.3f" v let line_of_module = let open Format in fun arr fmt f -> fprintf fmt "%s " (string_resize (Timers.string_of_ty_function f) 13); let cpt = ref 0. in List.iter (fun m -> let v = arr.(Timers.mtag m).(Timers.ftag f) in cpt := !cpt +. v; fprintf fmt "| %a " float_print v ) Timers.all_modules; fprintf fmt "| %a |@." float_print !cpt let line_of_sum_module = let open Format in fun fmt timers -> for _ = 0 to 206 do fprintf fmt "-" done; fprintf fmt "|@."; fprintf fmt "%s " (string_resize "" 13); List.iter (fun m -> fprintf fmt "| %a " float_print (Timers.get_sum timers m)) Timers.all_modules; fprintf fmt "| GTimer %a |@." float_print (Options.Time.value()) let timers_table = let open Format in fun forced fmt timers -> if not forced then ignore(Sys.command("clear")); Timers.update timers; fprintf fmt "@."; fprintf fmt " "; List.iter (fun f -> fprintf fmt"| %s" (string_resize (Timers.string_of_ty_module f) 9)) Timers.all_modules; fprintf fmt "|@."; for _ = 0 to 206 do fprintf fmt "-" done; fprintf fmt "|@."; let arr_timers = Timers.get_timers_array timers in List.iter (line_of_module arr_timers fmt) Timers.all_functions; line_of_sum_module fmt timers let print = let open Format in fun all steps timers fmt -> print_initial_info fmt; set_sigprof(); if all then begin mode := Stats; fprintf fmt "@."; print_stats true steps fmt timers; fprintf fmt "@."; mode := Timers; print_timers true steps fmt timers; fprintf fmt "@."; timers_table true fmt timers; fprintf fmt "@."; print_instances_generation true steps fmt timers; fprintf fmt "@."; end else match !mode with | Stats -> print_stats false steps fmt timers | Timers -> print_timers false steps fmt timers | CallTree -> print_call_tree false steps fmt timers | FunctionsTimers -> timers_table false fmt timers; | Instances -> print_instances_generation false steps fmt timers
null
https://raw.githubusercontent.com/OCamlPro/alt-ergo/43c4cb3a4d194399eea91f09f84f4092d6d87019/src/lib/structures/profiling.ml
ocaml
**************************************************************************** This file is distributed under the terms of the license indicated in the file 'License.OCamlPro'. If 'License.OCamlPro' is not present, please contact us to clarify licensing. **************************************************************************** update functions of the internal state assert (ii.loc == loc); ***************************************************************************** printing the internal state ***************************************************************************** ----------------------------------------------------------------- ----------------------------------------------------------------- too long
Alt - Ergo : The SMT Solver For Software Verification Copyright ( C ) 2013 - 2018 module SE = Expr.Set module MS = Map.Make(String) type inst_info = { loc : Loc.t; kept : int; ignored : int; all_insts : SE.t; confl : int; decided : int; consumed : SE.t; all : SE.t; produced : SE.t; _new : SE.t; } type t = { decisions : int ref; assumes : int ref; assumes_current_lvl : int ref; queries : int ref; instantiation_rounds : int ref; instances : int ref; decision_lvl : int ref; instantiation_lvl : int ref; 4 kinds of conflicts th_conflicts : int ref; b_conflicts : int ref; bcp_th_conflicts : int ref; bcp_b_conflicts : int ref; bcp_mix_conflicts : int ref; 4 kinds of red / elim t_red : int ref; b_red : int ref; t_elim : int ref; b_elim : int ref; first int : counter ok kept instances , second int : counter of removed instances second int: counter of removed instances*) instances_map : inst_info MS.t ref; instances_map_printed : bool ref } let state = { decisions = ref 0; assumes = ref 0; assumes_current_lvl = ref 0; queries = ref 0; instantiation_rounds = ref 0; instances = ref 0; decision_lvl = ref 0; instantiation_lvl = ref 0; th_conflicts = ref 0; b_conflicts = ref 0; bcp_th_conflicts = ref 0; bcp_b_conflicts = ref 0; bcp_mix_conflicts = ref 0; t_red = ref 0; b_red = ref 0; t_elim = ref 0; b_elim = ref 0; instances_map = ref MS.empty; instances_map_printed = ref false } let set_sigprof () = let tm = let v = Options.get_profiling_period () in if (Stdlib.compare v 0.) > 0 then v else -. v in ignore (Unix.setitimer Unix.ITIMER_PROF { Unix.it_value = tm; Unix.it_interval = 0. }) let init () = state.decisions := 0; state.assumes := 0; state.queries := 0; state.instantiation_rounds := 0; state.instances := 0; state.decision_lvl := 0; state.instantiation_lvl := 0; state.assumes_current_lvl := 0; state.th_conflicts := 0; state.b_conflicts := 0; state.bcp_th_conflicts := 0; state.bcp_b_conflicts := 0; state.bcp_mix_conflicts := 0; state.t_red := 0; state.b_red := 0; state.t_elim := 0; state.b_elim := 0; state.instances_map := MS.empty; state.instances_map_printed := false; set_sigprof () let assume nb = state.assumes := nb + !(state.assumes); state.assumes_current_lvl := nb + !(state.assumes_current_lvl) let query () = incr state.queries let instances l = state.instances := !(state.instances) + List.length l let instantiation ilvl = incr state.instantiation_rounds; incr state.instantiation_lvl; if not (!(state.instantiation_lvl) = ilvl) then begin Printer.print_err "state.instantiation_lvl = %d et ilvl = %d" !(state.instantiation_lvl) ilvl; assert false end let bool_conflict () = incr state.b_conflicts let theory_conflict () = incr state.th_conflicts let bcp_conflict b1 b2 = if b1 && b2 then incr state.bcp_b_conflicts else if (not b1) && (not b2) then incr state.bcp_th_conflicts else incr state.bcp_mix_conflicts let red b = if b then incr state.b_red else incr state.t_red let elim b = if b then incr state.b_elim else incr state.t_elim let reset_ilevel n = state.instantiation_lvl := n let reset_dlevel n = state.decision_lvl := n let empty_inst_info loc = { loc = loc; kept = 0; ignored = 0; confl = 0; decided = 0; all_insts = SE.empty; consumed = SE.empty; all = SE.empty; produced = SE.empty; _new = SE.empty; } let new_instance_of axiom inst loc kept = let () = state.instances_map_printed := false in let ii = try MS.find axiom !(state.instances_map) with Not_found -> empty_inst_info loc in assert (ii.loc == loc); let ii = if kept then {ii with kept = ii.kept + 1; all_insts = SE.add inst ii.all_insts} else {ii with ignored = ii.ignored + 1} in state.instances_map := MS.add axiom ii !(state.instances_map) let conflicting_instance axiom loc = let ii = try MS.find axiom !(state.instances_map) with Not_found -> empty_inst_info loc in let ii = {ii with confl = ii.confl + 1} in assert (ii.loc == loc); state.instances_map := MS.add axiom ii !(state.instances_map) let decision_on_instance axiom_name = try let ii = MS.find axiom_name !(state.instances_map) in let ii = {ii with decided = ii.decided + 1} in state.instances_map := MS.add axiom_name ii !(state.instances_map) with Not_found -> () let decision d origin = incr state.decisions; incr state.decision_lvl; if not (!(state.decision_lvl) = d) then begin Printer.print_err "state.decision_lvl = %d et d = %d" !(state.decision_lvl) d; assert false end; state.assumes_current_lvl := 0; decision_on_instance origin let register_produced_terms axiom loc consumed all produced _new = let ii = try MS.find axiom !(state.instances_map) with Not_found -> empty_inst_info loc in assert (ii.loc == loc); let ii = {ii with consumed = SE.union ii.consumed consumed; all = SE.union ii.all all; produced = SE.union ii.produced produced; _new = SE.union ii._new _new } in state.instances_map := MS.add axiom ii !(state.instances_map) type mode = | Stats | Timers | CallTree | FunctionsTimers | Instances let mode = ref Stats let max_nb_prints = 30 let nb_prints = ref max_nb_prints let initial_info = ref true let string_resize s i = let sz = max 0 (i - (String.length s)) in let tmp = String.make sz ' ' in s ^ tmp let int_resize n i = string_resize (Format.sprintf "%d" n) i let float_resize f i = string_resize (Format.sprintf "%f" f) i let percent total a = (string_of_int (int_of_float (a *. 100. /. total))) ^ "%" let columns = [ "GTimer", "Global timer", 11, None, (fun _ gtime _ sz -> float_resize gtime sz); "Steps", "Number of Steps", 14, None, (fun steps gtime _ sz -> let avg = int_of_float ((float_of_int steps) /. gtime) in Format.sprintf "%s~%s" (string_resize (Format.sprintf "%d" steps) (sz-7)) (string_resize (Format.sprintf "%d/s" avg) 6) ); "Case splits", "Number of Case Splits", 14, None, (fun _ gtime _ sz -> let avg = int_of_float (float_of_int (Steps.cs_steps()) /. gtime) in Format.sprintf "%s~%s" (string_resize (Format.sprintf "%d" (Steps.cs_steps())) (sz-7)) (string_resize (Format.sprintf "%d/s" avg) 6) ); "Mod.", "Current active module", 7, None, (fun _ _ timers sz -> let kd, _msg, _ = Timers.current_timer timers in string_resize (Timers.string_of_ty_module kd) sz); "Module Id", "Each call to a module is tagged with a fresh Id", 10, None, (fun _ _ timers sz -> let _kd, _msg, id = Timers.current_timer timers in int_resize id sz); "ilvl", "Current Instantiaton level", 6, Some true, (fun _ _ _ sz -> int_resize !(state.instantiation_lvl) sz); "#i rnds", "Number of intantiation rounds", 8, Some true, (fun _ _ _ sz -> int_resize !(state.instantiation_rounds) sz); "#insts", "Number of generated instances", 8, Some true, (fun _ _ _ sz -> int_resize !(state.instances) sz); "i/r", "AVG number of generated instances per instantiation rounds", 8, Some true, (fun _ _ _ sz -> int_resize (!(state.instances) / (max 1 !(state.instantiation_rounds))) sz); "dlvl", "Current Decision level", 6, Some true, (fun _ _ _ sz -> int_resize !(state.decision_lvl) sz); "#decs", "Number of decisions", 6, Some true, (fun _ _ _ sz -> int_resize !(state.decisions) sz); "T-asm", "Number of calls to Theory.assume", 6, Some true, (fun _ _ _ sz -> int_resize !(state.assumes) sz); "T/d", "Number of Theory.assume after last decision", 6, Some true, (fun _ _ _ sz -> int_resize !(state.assumes_current_lvl) sz); "T-qr", "Number of calls to Theory.query", 15, Some true, (fun _ _ _ sz -> int_resize !(state.queries) sz); "B-R", "Number of reduced clauses by Boolean propagation", 6, Some true, (fun _ _ _ sz -> int_resize !(state.b_red) sz); "B-E", "Number of eliminated clauses by Boolean propagation", 6, Some true, (fun _ _ _ sz -> int_resize !(state.b_elim) sz); "T-R", "Number of reduced clauses by Theory propagation", 6, Some true, (fun _ _ _ sz -> int_resize !(state.t_red) sz); "T-E", "Number of eliminated clauses by Theory propagation", 6, Some true, (fun _ _ _ sz -> int_resize !(state.t_elim) sz); "B-!", "Number of direct Boolean conflicts", 5, Some true, (fun _ _ _ sz -> int_resize !(state.b_conflicts) sz); "T-!", "Number of direct Theory conflicts" , 5, Some true, (fun _ _ _ sz -> int_resize !(state.th_conflicts) sz); "B>!", "Number of Boolean conflicts deduced by BCP", 5, Some true, (fun _ _ _ sz -> int_resize !(state.bcp_b_conflicts) sz); "T>!", "Number of Theory conflicts deduced by BCP", 5, Some true, (fun _ _ _ sz -> int_resize !(state.bcp_th_conflicts) sz); "M>!", "Number of Mix conflicts deduced by BCP", 5, Some true, (fun _ _ _ sz -> int_resize !(state.bcp_mix_conflicts) sz); "SAT", "Time spent in SAT module(s)", 16, Some false, (fun _ gtime timers sz -> let curr = Timers.get_sum timers Timers.M_Sat in Format.sprintf "%s~%s" (float_resize curr (sz - 5)) (string_resize (percent gtime curr) 4)); "Matching", "Time spent in Matching module(s)", 16, Some false, (fun _ gtime timers sz -> let curr = Timers.get_sum timers Timers.M_Match in Format.sprintf "%s~%s" (float_resize curr (sz - 5)) (string_resize (percent gtime curr) 4)); "CC", "Time spent in CC module(s)", 16, Some false, (fun _ gtime timers sz -> let curr = Timers.get_sum timers Timers.M_CC in Format.sprintf "%s~%s" (float_resize curr (sz - 5)) (string_resize (percent gtime curr) 4) ); "Arith", "Time spent in Arith module(s)", 16, Some false, (fun _ gtime timers sz -> let curr = Timers.get_sum timers Timers.M_Arith in Format.sprintf "%s~%s" (float_resize curr (sz - 5)) (string_resize (percent gtime curr) 4)); "Arrays", "Time spent in Arrays module(s)", 16, Some false, (fun _ gtime timers sz -> let curr = Timers.get_sum timers Timers.M_Arrays in Format.sprintf "%s~%s" (float_resize curr (sz - 5)) (string_resize (percent gtime curr) 4)); "Sum", "Time spent in Sum module(s)", 16, Some false, (fun _ gtime timers sz -> let curr = Timers.get_sum timers Timers.M_Sum in Format.sprintf "%s~%s" (float_resize curr (sz - 5)) (string_resize (percent gtime curr) 4)); "Records", "Time spent in Records module(s)", 16, Some false, (fun _ gtime timers sz -> let curr = Timers.get_sum timers Timers.M_Records in Format.sprintf "%s~%s" (float_resize curr (sz - 5)) (string_resize (percent gtime curr) 4)); "AC", "Time spent in AC module(s)", 16, Some false, (fun _ gtime timers sz -> let curr = Timers.get_sum timers Timers.M_AC in Format.sprintf "%s~%s" (float_resize curr (sz - 5)) (string_resize (percent gtime curr) 4)); "Total", "Time spent in 'supervised' module(s)", 11, Some false, (fun _ _ timers sz -> let tsat = Timers.get_sum timers Timers.M_Sat in let tmatch = Timers.get_sum timers Timers.M_Match in let tcc = Timers.get_sum timers Timers.M_CC in let tarith = Timers.get_sum timers Timers.M_Arith in let tarrays = Timers.get_sum timers Timers.M_Arrays in let tsum = Timers.get_sum timers Timers.M_Sum in let trecs = Timers.get_sum timers Timers.M_Records in let tac = Timers.get_sum timers Timers.M_AC in let total = tsat+.tmatch+.tcc+.tarith+.tarrays+.tsum+.trecs+.tac in float_resize total sz); ] let print_initial_info fmt = if !initial_info then begin initial_info := false; let max = List.fold_left (fun z (id,_, _,_,_) -> max z (String.length id)) 0 columns in List.iter (fun (id, descr, _, _, _) -> Format.fprintf fmt "%s : %s@." (string_resize id max) descr )columns end let stats_limit, timers_limit = let aux tmp sz = tmp := Format.sprintf "%s|" !tmp; for _ = 1 to sz do tmp := Format.sprintf "%s-" !tmp done in let tmp_s = ref "" in let tmp_t = ref "" in List.iter (fun (_, _, sz, opt, _) -> match opt with | Some true -> aux tmp_s sz | Some false -> aux tmp_t sz | _ -> aux tmp_s sz; aux tmp_t sz )columns; !tmp_s ^ "|", !tmp_t ^ "|" let print_header header fmt = let pp_stats = match !mode with Stats -> true | Timers -> false | _ -> assert false in if header || !nb_prints >= max_nb_prints then begin nb_prints := 0; Format.fprintf fmt "%s@." (if pp_stats then stats_limit else timers_limit); List.iter (fun (id, _, sz, opt, _) -> match opt with | Some b when b != pp_stats -> () | _ -> Format.fprintf fmt "|%s" (string_resize id sz) )columns; Format.fprintf fmt "|@."; Format.fprintf fmt "%s@." (if pp_stats then stats_limit else timers_limit) end; incr nb_prints let print_stats header steps fmt timers = print_header header fmt; let gtime = Options.Time.value() in List.iter (fun (_, _, sz, opt, func) -> match opt with | Some false -> () | _ -> Format.fprintf fmt "|%s" (func steps gtime timers sz) )columns; Format.fprintf fmt "|@." let print_timers header steps fmt timers = Timers.update timers; print_header header fmt; let gtime = Options.Time.value() in List.iter (fun (_, _, sz, opt, func) -> match opt with | Some true -> () | _ -> Format.fprintf fmt "|%s" (func steps gtime timers sz) )columns; Format.fprintf fmt "|@." unused let report2 axiom fmt ( b , e ) = let open Lexing in let l = b.pos_lnum in let fc = b.pos_cnum - b.pos_bol + 1 in let lc = e.pos_cnum - b.pos_bol + 1 in fprintf fmt " ( Sub ) Axiom \"%s\ " , line % d , characters % d-%d : " axiom l fc lc let report2 axiom fmt (b,e) = let open Lexing in let l = b.pos_lnum in let fc = b.pos_cnum - b.pos_bol + 1 in let lc = e.pos_cnum - b.pos_bol + 1 in fprintf fmt "(Sub) Axiom \"%s\", line %d, characters %d-%d:" axiom l fc lc *) unused let ( b , e ) = let open Lexing in let l = b.pos_lnum in let fc = b.pos_cnum - b.pos_bol + 1 in let lc = e.pos_cnum - b.pos_bol + 1 in fprintf fmt " line % d , chars % d-%d . " l fc lc let report3 fmt (b,e) = let open Lexing in let l = b.pos_lnum in let fc = b.pos_cnum - b.pos_bol + 1 in let lc = e.pos_cnum - b.pos_bol + 1 in fprintf fmt "line %d, chars %d-%d." l fc lc *) let (@@) a b = if a <> 0 then a else b let print_instances_generation forced _steps fmt _timers = if not forced && !(state.instances_map_printed) then Format.fprintf fmt "[Instances profiling] No change since last print@." else let () = state.instances_map_printed := true in if not forced then ignore(Sys.command("clear")); Format.fprintf fmt "[Instances profiling] ...@."; let insts = MS.fold (fun name ii acc -> let f1 = float_of_int ii.kept in let f2 = float_of_int ii.ignored in let ratio = f1 /. (f1 +. f2) in let all_card = SE.cardinal ii.all_insts in (name, ii, all_card, ratio) :: acc) !(state.instances_map) [] in let insts = List.fast_sort (fun (_, i1, c1, _) (_, i2, c2, _) -> (i1.decided - i2.decided) @@ (c1 - c2) @@ (i1.kept - i2.kept) @@ (i1.confl - i2.confl) @@ (i1.ignored - i2.ignored) @@ (SE.cardinal i1._new - SE.cardinal i2._new) ) insts in List.iter (let open Format in fun (name, i, card, r) -> fprintf fmt "ratio kept/all: %s| " (float_resize r 8); fprintf fmt "<> insts: %s| " (int_resize card 5); fprintf fmt "kept: %s| " (int_resize i.kept 7); fprintf fmt "ignored: %s| " (int_resize i.ignored 7) ; fprintf fmt "decided: %s| " (int_resize i.decided 4); fprintf fmt "conflicted: %s| " (int_resize i.confl 4); fprintf fmt "consumed: %s| " (int_resize (SE.cardinal i.consumed) 5); fprintf fmt "produced: %s| " (int_resize (SE.cardinal i.produced) 5); fprintf fmt "new: %s|| " (int_resize (SE.cardinal i._new) 5); fprintf fmt "%s" (string_resize name 30); " % s | " ( string_resize name 30 ) ; fprintf fmt " % a@. " report3 i.loc ( * too long fprintf fmt "@." )insts; if forced then let ( ) = fprintf fmt " digraph v{@. " in fprintf fmt " size=\"10,7.5\"@. " ; fprintf fmt " ratio=\"fill\"@. " ; fprintf fmt " rotate=90@. " ; fprintf fmt " fontsize=\"12pt\"@. " ; fprintf fmt " rankdir = TB@. " ; let terms = ref SE.empty in List.iter ( fun ( name , i , _ ) - > ( fun t - > fprintf fmt " \"%d\ " - > \"%s\";@. " ( T.hash t ) name ) i.consumed ; terms : = SE.union ! terms i.consumed ; ( fun t - > fmt " \"%s\ " - > \"%d\";@. " name ( T.hash t ) ) i._new ; terms : = SE.union ! terms i._new ; fmt " \"%s\ " [ fillcolor = yellow];@. " name ; ) insts ; ( fun t - > fprintf fmt " \"%d\ " [ fillcolor = green];@. " ( T.hash t ) ; ) ! terms ; fmt " } @. " let () = fprintf fmt "digraph v{@." in fprintf fmt "size=\"10,7.5\"@."; fprintf fmt "ratio=\"fill\"@."; fprintf fmt "rotate=90@."; fprintf fmt "fontsize=\"12pt\"@."; fprintf fmt "rankdir = TB@." ; let terms = ref SE.empty in List.iter (fun (name, i, _) -> SE.iter (fun t -> fprintf fmt "\"%d\" -> \"%s\";@." (T.hash t) name )i.consumed; terms := SE.union !terms i.consumed; SE.iter (fun t -> fprintf fmt "\"%s\" -> \"%d\";@." name (T.hash t) )i._new; terms := SE.union !terms i._new; fprintf fmt "\"%s\" [fillcolor=yellow];@." name; )insts; SE.iter (fun t -> fprintf fmt "\"%d\" [fillcolor=green];@." (T.hash t); )!terms; fprintf fmt "}@."*) if forced then let ( ) = fprintf fmt " digraph v{@. " in fprintf fmt " size=\"10,7.5\"@. " ; fprintf fmt " ratio=\"fill\"@. " ; fprintf fmt " rotate=90@. " ; fprintf fmt " fontsize=\"12pt\"@. " ; fprintf fmt " rankdir = TB@. " ; List.iter ( fun ( s1 , i1 , _ ) - > List.iter ( fun ( s2 , i2 , _ ) - > if SE.is_empty ( SE.inter i1.produced i2.consumed ) then ( ) else fmt " \"%s\ " - > \"%s\";@. " s1 s2 ) insts ) insts ; fmt " } @. " if forced then let () = fprintf fmt "digraph v{@." in fprintf fmt "size=\"10,7.5\"@."; fprintf fmt "ratio=\"fill\"@."; fprintf fmt "rotate=90@."; fprintf fmt "fontsize=\"12pt\"@."; fprintf fmt "rankdir = TB@." ; List.iter (fun (s1, i1, _) -> List.iter (fun (s2, i2, _) -> if SE.is_empty (SE.inter i1.produced i2.consumed) then () else fprintf fmt "\"%s\" -> \"%s\";@." s1 s2 )insts )insts; fprintf fmt "}@."*) () let print_call_tree _forced _steps fmt timers = let stack = Timers.get_stack timers in List.iter (fun (k, f, id) -> Format.fprintf fmt "(%s, %s, %s) --> " (string_resize (Timers.string_of_ty_module k) 5) (string_resize (Timers.string_of_ty_function f) 10) (int_resize id 7) )(List.rev stack); let m, f, id = Timers.current_timer timers in Format.fprintf fmt "(%s, %s, %s)@." (string_resize (Timers.string_of_ty_module m) 5) (string_resize (Timers.string_of_ty_function f) 10) (int_resize id 7) let switch fmt = let next, next_msg = match !mode with | Stats -> Timers, "Time" | Timers -> CallTree, "CallTree" | CallTree -> FunctionsTimers, "Functions Timers" | FunctionsTimers -> Instances, "Instances generation" | Instances -> Stats, "Stats" in Format.fprintf fmt "@.>>> Switch to %s profiling. Use \"Ctrl + AltGr + \\\" to exit\n" next_msg; nb_prints := max_nb_prints; mode := next let float_print = let open Format in fun fmt v -> if Stdlib.(=) v 0. then fprintf fmt "-- " else if (Stdlib.compare v 10.) < 0 then fprintf fmt "%0.5f" v else if (Stdlib.compare v 100.) < 0 then fprintf fmt "%0.4f" v else fprintf fmt "%0.3f" v let line_of_module = let open Format in fun arr fmt f -> fprintf fmt "%s " (string_resize (Timers.string_of_ty_function f) 13); let cpt = ref 0. in List.iter (fun m -> let v = arr.(Timers.mtag m).(Timers.ftag f) in cpt := !cpt +. v; fprintf fmt "| %a " float_print v ) Timers.all_modules; fprintf fmt "| %a |@." float_print !cpt let line_of_sum_module = let open Format in fun fmt timers -> for _ = 0 to 206 do fprintf fmt "-" done; fprintf fmt "|@."; fprintf fmt "%s " (string_resize "" 13); List.iter (fun m -> fprintf fmt "| %a " float_print (Timers.get_sum timers m)) Timers.all_modules; fprintf fmt "| GTimer %a |@." float_print (Options.Time.value()) let timers_table = let open Format in fun forced fmt timers -> if not forced then ignore(Sys.command("clear")); Timers.update timers; fprintf fmt "@."; fprintf fmt " "; List.iter (fun f -> fprintf fmt"| %s" (string_resize (Timers.string_of_ty_module f) 9)) Timers.all_modules; fprintf fmt "|@."; for _ = 0 to 206 do fprintf fmt "-" done; fprintf fmt "|@."; let arr_timers = Timers.get_timers_array timers in List.iter (line_of_module arr_timers fmt) Timers.all_functions; line_of_sum_module fmt timers let print = let open Format in fun all steps timers fmt -> print_initial_info fmt; set_sigprof(); if all then begin mode := Stats; fprintf fmt "@."; print_stats true steps fmt timers; fprintf fmt "@."; mode := Timers; print_timers true steps fmt timers; fprintf fmt "@."; timers_table true fmt timers; fprintf fmt "@."; print_instances_generation true steps fmt timers; fprintf fmt "@."; end else match !mode with | Stats -> print_stats false steps fmt timers | Timers -> print_timers false steps fmt timers | CallTree -> print_call_tree false steps fmt timers | FunctionsTimers -> timers_table false fmt timers; | Instances -> print_instances_generation false steps fmt timers
3d09c03381e2d51d304c63c4207141f44a4ff036d01f95e5ca83640990dd7452
input-output-hk/marlowe-cardano
Main.hs
{-# LANGUAGE GADTs #-} module Main where import Control.Arrow (arr, (<<<)) import Control.Concurrent.Component import Control.Monad ((<=<)) import Data.Either (fromRight) import qualified Data.Set.NonEmpty as NESet import Data.String (fromString) import qualified Data.Text.Lazy.IO as TL import Data.Time (secondsToNominalDiffTime) import Data.UUID.V4 (nextRandom) import Data.Void (Void) import Hasql.Pool import qualified Hasql.Pool as Pool import qualified Hasql.Session as Session import Language.Marlowe.Runtime.ChainSync.Api (ChainSyncQuery(..), WithGenesis(..)) import Language.Marlowe.Runtime.Core.Api (MarloweVersion(..)) import qualified Language.Marlowe.Runtime.Core.ScriptRegistry as ScriptRegistry import Language.Marlowe.Runtime.Indexer (MarloweIndexerDependencies(..), marloweIndexer) import Language.Marlowe.Runtime.Indexer.Database (hoistDatabaseQueries) import qualified Language.Marlowe.Runtime.Indexer.Database.PostgreSQL as PostgreSQL import Logging (RootSelector(..), getRootSelectorConfig) import Network.Protocol.ChainSeek.Client (chainSeekClientPeer) import Network.Protocol.Connection (SomeConnector(..), logConnector) import Network.Protocol.Driver (runConnector, tcpClient) import Network.Protocol.Handshake.Client (handshakeClientConnector) import Network.Protocol.Query.Client (liftQuery, queryClientPeer) import Network.Socket (AddrInfo(..), HostName, PortNumber, SocketType(..), defaultHints, withSocketsDo) import Observe.Event.Backend (narrowEventBackend, newOnceFlagMVar) import Observe.Event.Component (LoggerDependencies(..), logger) import Options.Applicative ( auto , execParser , fullDesc , header , help , helper , info , long , metavar , option , optional , progDesc , short , showDefault , strOption , value ) import System.IO (stderr) main :: IO () main = run =<< getOptions clientHints :: AddrInfo clientHints = defaultHints { addrSocketType = Stream } run :: Options -> IO () run Options{..} = withSocketsDo do pool <- Pool.acquire (100, secondsToNominalDiffTime 5, fromString databaseUri) scripts <- case ScriptRegistry.getScripts MarloweV1 of NESet.IsEmpty -> fail "No known marlowe scripts" NESet.IsNonEmpty scripts -> pure scripts securityParameter <- queryChainSync GetSecurityParameter let indexerDependencies eventBackend = MarloweIndexerDependencies { chainSyncConnector = SomeConnector $ logConnector (narrowEventBackend ChainSeekClient eventBackend) $ handshakeClientConnector $ tcpClient chainSeekHost chainSeekPort (chainSeekClientPeer Genesis) , chainSyncQueryConnector = SomeConnector $ logConnector (narrowEventBackend ChainQueryClient eventBackend) chainSyncQueryConnector , databaseQueries = hoistDatabaseQueries (either throwUsageError pure <=< Pool.use pool) (PostgreSQL.databaseQueries securityParameter) , eventBackend = narrowEventBackend App eventBackend , pollingInterval = 1 , marloweScriptHashes = NESet.map ScriptRegistry.marloweScript scripts , payoutScriptHashes = NESet.map ScriptRegistry.payoutScript scripts } let appComponent = marloweIndexer <<< arr indexerDependencies <<< logger runComponent_ appComponent LoggerDependencies { configFilePath = logConfigFile , getSelectorConfig = getRootSelectorConfig , newRef = nextRandom , newOnceFlag = newOnceFlagMVar , writeText = TL.hPutStr stderr , injectConfigWatcherSelector = ConfigWatcher } where throwUsageError (ConnectionError err) = error $ show err throwUsageError (SessionError (Session.QueryError _ _ err)) = error $ show err chainSyncQueryConnector = handshakeClientConnector $ tcpClient chainSeekHost chainSeekQueryPort queryClientPeer queryChainSync :: ChainSyncQuery Void e a -> IO a queryChainSync = fmap (fromRight $ error "failed to query chain sync server") . runConnector chainSyncQueryConnector . liftQuery data Options = Options { chainSeekPort :: PortNumber , chainSeekQueryPort :: PortNumber , chainSeekHost :: HostName , databaseUri :: String , logConfigFile :: Maybe FilePath } getOptions :: IO Options getOptions = execParser $ info (helper <*> parser) infoMod where parser = Options <$> chainSeekPortParser <*> chainSeekQueryPortParser <*> chainSeekHostParser <*> databaseUriParser <*> logConfigFileParser chainSeekPortParser = option auto $ mconcat [ long "chain-sync-port" , value 3715 , metavar "PORT_NUMBER" , help "The port number of the chain sync server." , showDefault ] chainSeekQueryPortParser = option auto $ mconcat [ long "chain-sync-query-port" , value 3716 , metavar "PORT_NUMBER" , help "The port number of the chain sync query server." , showDefault ] chainSeekHostParser = strOption $ mconcat [ long "chain-sync-host" , value "127.0.0.1" , metavar "HOST_NAME" , help "The host name of the chain sync server." , showDefault ] databaseUriParser = strOption $ mconcat [ long "database-uri" , short 'd' , metavar "DATABASE_URI" , help "URI of the database where the contract information is saved." ] logConfigFileParser = optional $ strOption $ mconcat [ long "log-config-file" , metavar "FILE_PATH" , help "The logging configuration JSON file." ] infoMod = mconcat [ fullDesc , progDesc "Contract indexing service for Marlowe Runtime" , header "marlowe-indexer : a contract indexing service for the Marlowe Runtime." ]
null
https://raw.githubusercontent.com/input-output-hk/marlowe-cardano/bc9a0325f13b886e90ea05196ffb70a46c2ab095/marlowe-runtime/marlowe-indexer/Main.hs
haskell
# LANGUAGE GADTs #
module Main where import Control.Arrow (arr, (<<<)) import Control.Concurrent.Component import Control.Monad ((<=<)) import Data.Either (fromRight) import qualified Data.Set.NonEmpty as NESet import Data.String (fromString) import qualified Data.Text.Lazy.IO as TL import Data.Time (secondsToNominalDiffTime) import Data.UUID.V4 (nextRandom) import Data.Void (Void) import Hasql.Pool import qualified Hasql.Pool as Pool import qualified Hasql.Session as Session import Language.Marlowe.Runtime.ChainSync.Api (ChainSyncQuery(..), WithGenesis(..)) import Language.Marlowe.Runtime.Core.Api (MarloweVersion(..)) import qualified Language.Marlowe.Runtime.Core.ScriptRegistry as ScriptRegistry import Language.Marlowe.Runtime.Indexer (MarloweIndexerDependencies(..), marloweIndexer) import Language.Marlowe.Runtime.Indexer.Database (hoistDatabaseQueries) import qualified Language.Marlowe.Runtime.Indexer.Database.PostgreSQL as PostgreSQL import Logging (RootSelector(..), getRootSelectorConfig) import Network.Protocol.ChainSeek.Client (chainSeekClientPeer) import Network.Protocol.Connection (SomeConnector(..), logConnector) import Network.Protocol.Driver (runConnector, tcpClient) import Network.Protocol.Handshake.Client (handshakeClientConnector) import Network.Protocol.Query.Client (liftQuery, queryClientPeer) import Network.Socket (AddrInfo(..), HostName, PortNumber, SocketType(..), defaultHints, withSocketsDo) import Observe.Event.Backend (narrowEventBackend, newOnceFlagMVar) import Observe.Event.Component (LoggerDependencies(..), logger) import Options.Applicative ( auto , execParser , fullDesc , header , help , helper , info , long , metavar , option , optional , progDesc , short , showDefault , strOption , value ) import System.IO (stderr) main :: IO () main = run =<< getOptions clientHints :: AddrInfo clientHints = defaultHints { addrSocketType = Stream } run :: Options -> IO () run Options{..} = withSocketsDo do pool <- Pool.acquire (100, secondsToNominalDiffTime 5, fromString databaseUri) scripts <- case ScriptRegistry.getScripts MarloweV1 of NESet.IsEmpty -> fail "No known marlowe scripts" NESet.IsNonEmpty scripts -> pure scripts securityParameter <- queryChainSync GetSecurityParameter let indexerDependencies eventBackend = MarloweIndexerDependencies { chainSyncConnector = SomeConnector $ logConnector (narrowEventBackend ChainSeekClient eventBackend) $ handshakeClientConnector $ tcpClient chainSeekHost chainSeekPort (chainSeekClientPeer Genesis) , chainSyncQueryConnector = SomeConnector $ logConnector (narrowEventBackend ChainQueryClient eventBackend) chainSyncQueryConnector , databaseQueries = hoistDatabaseQueries (either throwUsageError pure <=< Pool.use pool) (PostgreSQL.databaseQueries securityParameter) , eventBackend = narrowEventBackend App eventBackend , pollingInterval = 1 , marloweScriptHashes = NESet.map ScriptRegistry.marloweScript scripts , payoutScriptHashes = NESet.map ScriptRegistry.payoutScript scripts } let appComponent = marloweIndexer <<< arr indexerDependencies <<< logger runComponent_ appComponent LoggerDependencies { configFilePath = logConfigFile , getSelectorConfig = getRootSelectorConfig , newRef = nextRandom , newOnceFlag = newOnceFlagMVar , writeText = TL.hPutStr stderr , injectConfigWatcherSelector = ConfigWatcher } where throwUsageError (ConnectionError err) = error $ show err throwUsageError (SessionError (Session.QueryError _ _ err)) = error $ show err chainSyncQueryConnector = handshakeClientConnector $ tcpClient chainSeekHost chainSeekQueryPort queryClientPeer queryChainSync :: ChainSyncQuery Void e a -> IO a queryChainSync = fmap (fromRight $ error "failed to query chain sync server") . runConnector chainSyncQueryConnector . liftQuery data Options = Options { chainSeekPort :: PortNumber , chainSeekQueryPort :: PortNumber , chainSeekHost :: HostName , databaseUri :: String , logConfigFile :: Maybe FilePath } getOptions :: IO Options getOptions = execParser $ info (helper <*> parser) infoMod where parser = Options <$> chainSeekPortParser <*> chainSeekQueryPortParser <*> chainSeekHostParser <*> databaseUriParser <*> logConfigFileParser chainSeekPortParser = option auto $ mconcat [ long "chain-sync-port" , value 3715 , metavar "PORT_NUMBER" , help "The port number of the chain sync server." , showDefault ] chainSeekQueryPortParser = option auto $ mconcat [ long "chain-sync-query-port" , value 3716 , metavar "PORT_NUMBER" , help "The port number of the chain sync query server." , showDefault ] chainSeekHostParser = strOption $ mconcat [ long "chain-sync-host" , value "127.0.0.1" , metavar "HOST_NAME" , help "The host name of the chain sync server." , showDefault ] databaseUriParser = strOption $ mconcat [ long "database-uri" , short 'd' , metavar "DATABASE_URI" , help "URI of the database where the contract information is saved." ] logConfigFileParser = optional $ strOption $ mconcat [ long "log-config-file" , metavar "FILE_PATH" , help "The logging configuration JSON file." ] infoMod = mconcat [ fullDesc , progDesc "Contract indexing service for Marlowe Runtime" , header "marlowe-indexer : a contract indexing service for the Marlowe Runtime." ]
d1273012d63ae02551c9eddc3fc00cca7646de5e2d54fcc41ab7be17611badf0
jaseemabid/lisper
Primitives.hs
----------------------------------------------------------------------------- -- | -- Module : Lisper.Primitives -- Scheme primitives implemented in Haskell -- -- This module has several issues and needs a complete rewrite. -- 1 . Find a good architecture for native functions . 2 . Can not use any of these as higher order functions . 3 . Remove ` error ` from everywhere 4 . Add a prelude file which can have pure lisp definitions ----------------------------------------------------------------------------- module Lisper.Primitives (primitives) where import Lisper.Core -- Primitives, implemented in terms of haskell primitives :: [(String, [Scheme] -> Scheme)] primitives = [("eq", eq), ("null?", nullq), ("car", car), ("cdr", cdr), ("cons", cons), ("length", length'), ("list", list'), ("*", numericBinop (*)), ("+", numericBinop (+)), ("-", numericBinop (-)), ("/", numericBinop div), ("/=", numBoolBinop (/=)), ("<", numBoolBinop (<)), ("<=", numBoolBinop (<=)), ("=", numBoolBinop (==)), (">", numBoolBinop (>)), (">=", numBoolBinop (>=)), -- [verify] Get quotient from stdlib ("quotient", numericBinop mod), ("quot", numericBinop quot), ("quote", head), ("rem", numericBinop rem)] eq :: [Scheme] -> Scheme eq [a, b] = Bool $ a == b eq x = error $ "eq expected 2 arguments" ++ show x nullq :: [Scheme] -> Scheme nullq [a] = Bool $ a == List [] nullq x = error $ "null? expected 2 arguments" ++ show x car :: [Scheme] -> Scheme car [List (t : _)] = t car x = error $ "car expected a single list, got " ++ show x cdr :: [Scheme] -> Scheme cdr [List (_ : t)] = List t cdr x = error $ "cdr expected a single list, got " ++ show x cons :: [Scheme] -> Scheme cons (h : [List t]) = List (h:t) cons x = error $ "cons expected a value and a list, got " ++ show x length' :: [Scheme] -> Scheme length' [List x] = Number $ toInteger $ length x length' x = error $ "length expected a single list, got " ++ show x list' :: [Scheme] -> Scheme list' = List -- [TODO] - Add input type to error message -- [TODO] - Possibly auto generate unpack* unpackNum :: Scheme -> Integer unpackNum (Number n) = n unpackNum x = error $ "Expected number; got " ++ show x ++ " instead" ` numericBinop ` takes a primitive function and wraps it with code to -- unpack an argument list, apply the function to it, and wrap the result up in -- Scheme Number constructor numericBinop :: (Integer -> Integer -> Integer) -> [Scheme] -> Scheme numericBinop op params = Number $ foldl1 op $ map unpackNum params numBoolBinop :: (Integer -> Integer -> Bool) -> [Scheme] -> Scheme numBoolBinop op [Number one, Number two] = Bool (one `op` two) numBoolBinop _ _ = error "Unexpected arguments to numeric binary operator"
null
https://raw.githubusercontent.com/jaseemabid/lisper/91bc7876e93d5fa4fb65046eedf500a6d99278b3/src/Lisper/Primitives.hs
haskell
--------------------------------------------------------------------------- | Module : Lisper.Primitives This module has several issues and needs a complete rewrite. --------------------------------------------------------------------------- Primitives, implemented in terms of haskell [verify] Get quotient from stdlib [TODO] - Add input type to error message [TODO] - Possibly auto generate unpack* unpack an argument list, apply the function to it, and wrap the result up in Scheme Number constructor
Scheme primitives implemented in Haskell 1 . Find a good architecture for native functions . 2 . Can not use any of these as higher order functions . 3 . Remove ` error ` from everywhere 4 . Add a prelude file which can have pure lisp definitions module Lisper.Primitives (primitives) where import Lisper.Core primitives :: [(String, [Scheme] -> Scheme)] primitives = [("eq", eq), ("null?", nullq), ("car", car), ("cdr", cdr), ("cons", cons), ("length", length'), ("list", list'), ("*", numericBinop (*)), ("+", numericBinop (+)), ("-", numericBinop (-)), ("/", numericBinop div), ("/=", numBoolBinop (/=)), ("<", numBoolBinop (<)), ("<=", numBoolBinop (<=)), ("=", numBoolBinop (==)), (">", numBoolBinop (>)), (">=", numBoolBinop (>=)), ("quotient", numericBinop mod), ("quot", numericBinop quot), ("quote", head), ("rem", numericBinop rem)] eq :: [Scheme] -> Scheme eq [a, b] = Bool $ a == b eq x = error $ "eq expected 2 arguments" ++ show x nullq :: [Scheme] -> Scheme nullq [a] = Bool $ a == List [] nullq x = error $ "null? expected 2 arguments" ++ show x car :: [Scheme] -> Scheme car [List (t : _)] = t car x = error $ "car expected a single list, got " ++ show x cdr :: [Scheme] -> Scheme cdr [List (_ : t)] = List t cdr x = error $ "cdr expected a single list, got " ++ show x cons :: [Scheme] -> Scheme cons (h : [List t]) = List (h:t) cons x = error $ "cons expected a value and a list, got " ++ show x length' :: [Scheme] -> Scheme length' [List x] = Number $ toInteger $ length x length' x = error $ "length expected a single list, got " ++ show x list' :: [Scheme] -> Scheme list' = List unpackNum :: Scheme -> Integer unpackNum (Number n) = n unpackNum x = error $ "Expected number; got " ++ show x ++ " instead" ` numericBinop ` takes a primitive function and wraps it with code to numericBinop :: (Integer -> Integer -> Integer) -> [Scheme] -> Scheme numericBinop op params = Number $ foldl1 op $ map unpackNum params numBoolBinop :: (Integer -> Integer -> Bool) -> [Scheme] -> Scheme numBoolBinop op [Number one, Number two] = Bool (one `op` two) numBoolBinop _ _ = error "Unexpected arguments to numeric binary operator"
30aac22b3268497cafee4d698adab32b15479424f80056c141de87f386d25c17
KoenvdBerg/csv-validator
test-csv-validator.lisp
;; tests the validation_utils (in-package :csv-validator-tests) (def-suite testmain :description "test suite for validation utils") ( setf fiveam:*on - failure * : debug ) (in-suite testmain) ;; data type tests (test test-check-integer-string ;; not valid (is (not (csv-validator:check-integer-string "-klsdf"))) (is (not (csv-validator:check-integer-string "1.42"))) (is (not (csv-validator:check-integer-string "24ksd42"))) ;; valid (is (csv-validator:check-integer-string "-191")) (is (csv-validator:check-integer-string "38")) (is (csv-validator:check-integer-string "002"))) (test test-check-float-string ;; not valid (is (not (csv-validator:check-float-string "-klsdf"))) (is (not (csv-validator:check-float-string "-191"))) (is (not (csv-validator:check-float-string "24ksd42"))) ;; valid (is (csv-validator:check-float-string "1.42")) (is (csv-validator:check-float-string "38.4")) (is (csv-validator:check-float-string "002.29"))) (test test-check-scientific-number-string ;; not valid (is (not (csv-validator:check-scientific-number-string "-klsdf"))) (is (not (csv-validator:check-scientific-number-string "-191"))) (is (not (csv-validator:check-scientific-number-string "24ksd42"))) ;; valid (is (csv-validator:check-scientific-number-string "1.42E10")) (is (csv-validator:check-scientific-number-string "38.4e-3")) (is (csv-validator:check-scientific-number-string "002.29e9"))) (test test-check-number-string ;; not valid (is (not (csv-validator:check-number-string "-klsdf"))) (is (not (csv-validator:check-number-string "24ksd42"))) ;; valid (is (csv-validator:check-number-string "-191")) (is (csv-validator:check-number-string "1.42E10")) (is (csv-validator:check-number-string "38.4")) (is (csv-validator:check-number-string "002.29e9"))) (test test-check-date-parsable ;; not valid (is (not (csv-validator:check-date-parsable "klsdf"))) (is (not (csv-validator:check-date-parsable "2800-27-01"))) (is (not (csv-validator:check-date-parsable "2800-01-77"))) (is (not (csv-validator:check-date-parsable "2800-1-77"))) (is (not (csv-validator:check-date-parsable "2022/01/01"))) ;; valid (is (csv-validator:check-date-parsable "0101-01-01")) (is (csv-validator:check-date-parsable "2022-01-01 00:00:00")) (is (csv-validator:check-date-parsable "3800-01-02"))) (test test-check-tz-parsable ;; not valid (is (not (csv-validator:check-tz-parsable "klsdf"))) (is (not (csv-validator:check-tz-parsable "2800-27-01 00:00:00"))) (is (not (csv-validator:check-tz-parsable "2800-01-77"))) (is (not (csv-validator:check-tz-parsable "2800-1-77"))) (is (not (csv-validator:check-tz-parsable "2022/01/01"))) (is (not (csv-validator:check-tz-parsable "1993-02-30T30:09:20Z"))) ;; valid (is (csv-validator:check-tz-parsable "2022-01-01T00:00:00Z")) (is (csv-validator:check-tz-parsable "1993-05-21T21:09:20Z"))) (test test-check-null ;; not valid (is (not (csv-validator:check-null "-klsdf"))) (is (not (csv-validator:check-null "923"))) (is (not (csv-validator:check-null "2020-06-12"))) ;; valid (is (csv-validator:check-null "NA")) (is (csv-validator:check-null "")) (is (csv-validator:check-null "null")) (is (csv-validator:check-null "NaN"))) (test test-check-date-before-today ;; not valid (is (not (csv-validator:check-date-before-today "2099-01-01"))) ;; valid (is (csv-validator:check-date-before-today "2022-02-02")) (is (csv-validator:check-date-before-today "2022-01-01")) (is (csv-validator:check-date-before-today "klsdf")) (is (csv-validator:check-date-before-today "2022-11-01")) (is (csv-validator:check-date-before-today "1997-07-28")) (is (csv-validator:check-date-before-today "2022-01-01"))) (test test-compare-two-dates ;; not valid (is (not (csv-validator:check-compare-two-dates "2022-02-02" "2022-03-03"))) ;; valid (is (csv-validator:check-compare-two-dates "2022-02-02" "2022/03/03")) (is (csv-validator:check-compare-two-dates "2022-01-01" "kldsa")) (is (csv-validator:check-compare-two-dates "klsdf" "kldsa")) (is (csv-validator:check-compare-two-dates "2022-11-01" "2021-01-01")) (is (csv-validator:check-compare-two-dates "1997-07-28" "1995-09-09")) (is (csv-validator:check-compare-two-dates "2022-01-01" "2021-01-01"))) (test test-check-number-in-range ;; not valid (is (not (check-number-in-range "5" 6 10))) (is (not (check-number-in-range "abc" -10 0))) (is (not (check-number-in-range "5e3" 6 10))) (is (not (check-number-in-range "abc" -10 0))) ;; valid (is (check-number-in-range "5.3" 0 10)) (is (check-number-in-range "-5e0" -10 0)) (is (check-number-in-range "5" 0 10)) (is (check-number-in-range "-5" -10 0)))
null
https://raw.githubusercontent.com/KoenvdBerg/csv-validator/a3f56d30ea9241dc4a8943c2073a199cf488bfcc/tests/test-csv-validator.lisp
lisp
tests the validation_utils data type tests not valid valid not valid valid not valid valid not valid valid not valid valid not valid valid not valid valid not valid valid not valid valid not valid valid
(in-package :csv-validator-tests) (def-suite testmain :description "test suite for validation utils") ( setf fiveam:*on - failure * : debug ) (in-suite testmain) (test test-check-integer-string (is (not (csv-validator:check-integer-string "-klsdf"))) (is (not (csv-validator:check-integer-string "1.42"))) (is (not (csv-validator:check-integer-string "24ksd42"))) (is (csv-validator:check-integer-string "-191")) (is (csv-validator:check-integer-string "38")) (is (csv-validator:check-integer-string "002"))) (test test-check-float-string (is (not (csv-validator:check-float-string "-klsdf"))) (is (not (csv-validator:check-float-string "-191"))) (is (not (csv-validator:check-float-string "24ksd42"))) (is (csv-validator:check-float-string "1.42")) (is (csv-validator:check-float-string "38.4")) (is (csv-validator:check-float-string "002.29"))) (test test-check-scientific-number-string (is (not (csv-validator:check-scientific-number-string "-klsdf"))) (is (not (csv-validator:check-scientific-number-string "-191"))) (is (not (csv-validator:check-scientific-number-string "24ksd42"))) (is (csv-validator:check-scientific-number-string "1.42E10")) (is (csv-validator:check-scientific-number-string "38.4e-3")) (is (csv-validator:check-scientific-number-string "002.29e9"))) (test test-check-number-string (is (not (csv-validator:check-number-string "-klsdf"))) (is (not (csv-validator:check-number-string "24ksd42"))) (is (csv-validator:check-number-string "-191")) (is (csv-validator:check-number-string "1.42E10")) (is (csv-validator:check-number-string "38.4")) (is (csv-validator:check-number-string "002.29e9"))) (test test-check-date-parsable (is (not (csv-validator:check-date-parsable "klsdf"))) (is (not (csv-validator:check-date-parsable "2800-27-01"))) (is (not (csv-validator:check-date-parsable "2800-01-77"))) (is (not (csv-validator:check-date-parsable "2800-1-77"))) (is (not (csv-validator:check-date-parsable "2022/01/01"))) (is (csv-validator:check-date-parsable "0101-01-01")) (is (csv-validator:check-date-parsable "2022-01-01 00:00:00")) (is (csv-validator:check-date-parsable "3800-01-02"))) (test test-check-tz-parsable (is (not (csv-validator:check-tz-parsable "klsdf"))) (is (not (csv-validator:check-tz-parsable "2800-27-01 00:00:00"))) (is (not (csv-validator:check-tz-parsable "2800-01-77"))) (is (not (csv-validator:check-tz-parsable "2800-1-77"))) (is (not (csv-validator:check-tz-parsable "2022/01/01"))) (is (not (csv-validator:check-tz-parsable "1993-02-30T30:09:20Z"))) (is (csv-validator:check-tz-parsable "2022-01-01T00:00:00Z")) (is (csv-validator:check-tz-parsable "1993-05-21T21:09:20Z"))) (test test-check-null (is (not (csv-validator:check-null "-klsdf"))) (is (not (csv-validator:check-null "923"))) (is (not (csv-validator:check-null "2020-06-12"))) (is (csv-validator:check-null "NA")) (is (csv-validator:check-null "")) (is (csv-validator:check-null "null")) (is (csv-validator:check-null "NaN"))) (test test-check-date-before-today (is (not (csv-validator:check-date-before-today "2099-01-01"))) (is (csv-validator:check-date-before-today "2022-02-02")) (is (csv-validator:check-date-before-today "2022-01-01")) (is (csv-validator:check-date-before-today "klsdf")) (is (csv-validator:check-date-before-today "2022-11-01")) (is (csv-validator:check-date-before-today "1997-07-28")) (is (csv-validator:check-date-before-today "2022-01-01"))) (test test-compare-two-dates (is (not (csv-validator:check-compare-two-dates "2022-02-02" "2022-03-03"))) (is (csv-validator:check-compare-two-dates "2022-02-02" "2022/03/03")) (is (csv-validator:check-compare-two-dates "2022-01-01" "kldsa")) (is (csv-validator:check-compare-two-dates "klsdf" "kldsa")) (is (csv-validator:check-compare-two-dates "2022-11-01" "2021-01-01")) (is (csv-validator:check-compare-two-dates "1997-07-28" "1995-09-09")) (is (csv-validator:check-compare-two-dates "2022-01-01" "2021-01-01"))) (test test-check-number-in-range (is (not (check-number-in-range "5" 6 10))) (is (not (check-number-in-range "abc" -10 0))) (is (not (check-number-in-range "5e3" 6 10))) (is (not (check-number-in-range "abc" -10 0))) (is (check-number-in-range "5.3" 0 10)) (is (check-number-in-range "-5e0" -10 0)) (is (check-number-in-range "5" 0 10)) (is (check-number-in-range "-5" -10 0)))
0a7a7ee21b789ad1ae5bed71f811badc3105e2c225f6b526c73ed87ad7699818
mokus0/junkbox
ana.hs
{-# OPTIONS -fth #-} - " ana.hs " - ( c ) 2008 - "ana.hs" - (c) 2008 James Cook -} module Ana where import Language.Haskell.TH
null
https://raw.githubusercontent.com/mokus0/junkbox/151014bbef9db2b9205209df66c418d6d58b0d9e/Haskell/Template%20Haskell/ana.hs
haskell
# OPTIONS -fth #
- " ana.hs " - ( c ) 2008 - "ana.hs" - (c) 2008 James Cook -} module Ana where import Language.Haskell.TH
dba181d371bfd68ed3dec233877b3dbea50e5059cb89ee8589b8f129a4e2be2f
bhuztez/shu
shu_trie.erl
-module(shu_trie). -export([add/3]). add([], Value, Trie) -> Trie#{[] => lists:append(maps:get([], Trie, []), [Value])}; add([H|T], Value, Trie) -> Trie#{H => add(T, Value, maps:get(H, Trie, #{}))}. -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). add_test() -> ?assertEqual(#{$多 => #{$少 => #{[] => [1]}}}, add("多少", 1, #{})). -endif.
null
https://raw.githubusercontent.com/bhuztez/shu/98125ae20b88d343cf3ef21e8956854f34a1aa14/src/shu_trie.erl
erlang
-module(shu_trie). -export([add/3]). add([], Value, Trie) -> Trie#{[] => lists:append(maps:get([], Trie, []), [Value])}; add([H|T], Value, Trie) -> Trie#{H => add(T, Value, maps:get(H, Trie, #{}))}. -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). add_test() -> ?assertEqual(#{$多 => #{$少 => #{[] => [1]}}}, add("多少", 1, #{})). -endif.
beb1267f21ddb8488b6991c14c38945931f388d3646ffed939de34527b05c469
commercialhaskell/stack
Main.hs
module Main where import Lib.A main :: IO () main = putStrLn messageA
null
https://raw.githubusercontent.com/commercialhaskell/stack/255cd830627870cdef34b5e54d670ef07882523e/test/integration/tests/module-added-multiple-times/files/exe/Main.hs
haskell
module Main where import Lib.A main :: IO () main = putStrLn messageA
ed838315c365fdcf4aba69e7fbd3ebf60398693ec475fda71538713503131fea
grin-compiler/ghc-grin
aux.hs
--module Aux where --import Key data Key = K String Char Char Int {- String, end letters, length of string -} data HashSet = H (Maybe Int) (Maybe Int) [Int] type HashFun = [(Char,Int)] {- Association list of Character to values -} 1.3 : data Maybe a = Nothing | Just a deriving Text ends :: Key -> String ends (K _ a z _) = [a,z] morefreq :: Key -> Key -> Bool morefreq (K _ a x _) (K _ b y _) = freq a + freq x > freq b + freq y freq :: Char -> Int freq c = assoc c freqtab assoc :: (Eq a) => a -> [(a,b)] -> b assoc x ((y,z):yzs) = if x == y then z else assoc x yzs assocm :: (Eq a) => a -> [(a,b)] -> Maybe b assocm x [] = Nothing assocm x ((y,z):yzs) = if x == y then Just z else assocm x yzs freqtab :: [(Char, Int)] freqtab = histo (concat (map ends attribkeys)) histo :: (Eq a) => [a] -> [(a,Int)] histo = foldr histins [] where histins x [] = [(x,1)] histins x (yn@(y,n):yns) = if x==y then (y,n+1):yns else yn:histins x yns maxval :: Int maxval = length (freqtab) subset :: (Eq a) => [a] -> [a] -> Bool subset xs ys = all (\x -> member x ys) xs --partain: in the prelude --all :: (a->Bool) -> [a] -> Bool all p = foldr ( \x - > \b ->(p x & & b ) ) True union :: (Eq a) => [a] -> [a] -> [a] union xs ys = xs ++ [y | y <- ys, not (member y xs)] attribkeys :: [Key] attribkeys = map (\k->(K k (head k) (last k) (length k))) keys hinsert :: Int -> HashSet -> Maybe HashSet hinsert h (H lo hi hs) = if member h hs || 1 + hi'- lo' > numberofkeys then Nothing else Just (H (Just lo') (Just hi') (h:hs)) where lo' = minm lo h hi' = maxm hi h minm, maxm :: Maybe Int -> Int -> Int minm Nothing y = y minm (Just x) y = min x y maxm Nothing y = y maxm (Just x) y = max x y member :: (Eq a) => a -> [a] -> Bool member _ [] = False member x (y:ys) = x == y || member x ys hash :: HashFun -> Key -> Int hash cvs (K _ a z n) = n + assoc a cvs + assoc z cvs numberofkeys :: Int numberofkeys = length keys partition' :: (a->Bool) -> [a] -> ([a],[a]) partition' p = foldr select ([],[]) where select x (ts,fs) | p x = (x:ts,fs) | otherwise = (ts,x:fs) freqsorted :: [Key] -> [Key] freqsorted = \x->x foldr freqins [ ] where freqins x [ ] = [ x ] freqins x ( y : ys ) = if y then x : y : ys else y : freqins x ys where freqins x [] = [x] freqins x (y:ys) = if morefreq x y then x:y:ys else y:freqins x ys-} blocked :: [Key] -> [Key] blocked = blocked' [] blocked' ds [] = [] blocked' ds (k : ks) = k : det ++ blocked' ds' rest where (det,rest) = partition' (\x->subset (ends x) ds') ks ds' = union ds (ends k)
null
https://raw.githubusercontent.com/grin-compiler/ghc-grin/ebc4dca2e1f5b3581d4b84726730564ce909d786/ghc-grin-benchmark/boquist-grin-bench/spectral/cichelli/aux.hs
haskell
module Aux where import Key String, end letters, length of string Association list of Character to values partain: in the prelude all :: (a->Bool) -> [a] -> Bool
data HashSet = H (Maybe Int) (Maybe Int) [Int] 1.3 : data Maybe a = Nothing | Just a deriving Text ends :: Key -> String ends (K _ a z _) = [a,z] morefreq :: Key -> Key -> Bool morefreq (K _ a x _) (K _ b y _) = freq a + freq x > freq b + freq y freq :: Char -> Int freq c = assoc c freqtab assoc :: (Eq a) => a -> [(a,b)] -> b assoc x ((y,z):yzs) = if x == y then z else assoc x yzs assocm :: (Eq a) => a -> [(a,b)] -> Maybe b assocm x [] = Nothing assocm x ((y,z):yzs) = if x == y then Just z else assocm x yzs freqtab :: [(Char, Int)] freqtab = histo (concat (map ends attribkeys)) histo :: (Eq a) => [a] -> [(a,Int)] histo = foldr histins [] where histins x [] = [(x,1)] histins x (yn@(y,n):yns) = if x==y then (y,n+1):yns else yn:histins x yns maxval :: Int maxval = length (freqtab) subset :: (Eq a) => [a] -> [a] -> Bool subset xs ys = all (\x -> member x ys) xs all p = foldr ( \x - > \b ->(p x & & b ) ) True union :: (Eq a) => [a] -> [a] -> [a] union xs ys = xs ++ [y | y <- ys, not (member y xs)] attribkeys :: [Key] attribkeys = map (\k->(K k (head k) (last k) (length k))) keys hinsert :: Int -> HashSet -> Maybe HashSet hinsert h (H lo hi hs) = if member h hs || 1 + hi'- lo' > numberofkeys then Nothing else Just (H (Just lo') (Just hi') (h:hs)) where lo' = minm lo h hi' = maxm hi h minm, maxm :: Maybe Int -> Int -> Int minm Nothing y = y minm (Just x) y = min x y maxm Nothing y = y maxm (Just x) y = max x y member :: (Eq a) => a -> [a] -> Bool member _ [] = False member x (y:ys) = x == y || member x ys hash :: HashFun -> Key -> Int hash cvs (K _ a z n) = n + assoc a cvs + assoc z cvs numberofkeys :: Int numberofkeys = length keys partition' :: (a->Bool) -> [a] -> ([a],[a]) partition' p = foldr select ([],[]) where select x (ts,fs) | p x = (x:ts,fs) | otherwise = (ts,x:fs) freqsorted :: [Key] -> [Key] freqsorted = \x->x foldr freqins [ ] where freqins x [ ] = [ x ] freqins x ( y : ys ) = if y then x : y : ys else y : freqins x ys where freqins x [] = [x] freqins x (y:ys) = if morefreq x y then x:y:ys else y:freqins x ys-} blocked :: [Key] -> [Key] blocked = blocked' [] blocked' ds [] = [] blocked' ds (k : ks) = k : det ++ blocked' ds' rest where (det,rest) = partition' (\x->subset (ends x) ds') ks ds' = union ds (ends k)
dba0ae9490dcb870d8f80070d064b583c93471d0fc1ee4219f71048261995763
saa/fluxer
fluxer.erl
-module(fluxer). -export([start_link/1]). -export([pool_name/0]). -export([create_database/1]). -export([create_database/2]). -export([show_databases/0]). -export([write/2, write/3, write/4]). -export([write_batch/3]). -export([select/2, select/3]). -export([query/2]). -define(POOL_NAME, fluxer_pool). -define(CT, {<<"Content-Type">>, <<"text/plain">>}). %%==================================================================== %% API %%==================================================================== start_link([Host, Port, IsSSL, Options]) -> fusco:start_link({Host, Port, IsSSL}, Options). -spec pool_name() -> atom(). pool_name() -> ?POOL_NAME. -spec create_database(string()) -> term(). create_database(Name) -> create_database(Name, false). -spec create_database(string() | boolean() | atom(), boolean()) -> term(). create_database(Name, IfNotExists) when is_list(Name) -> create_database(to_binary(Name), IfNotExists); create_database(Name, IfNotExists) when is_atom(Name) -> create_database(to_binary(Name), IfNotExists); create_database(Name, IfNotExists) when is_binary(Name), is_boolean(IfNotExists) -> Query = case IfNotExists of true -> [<<"CREATE DATABASE IF NOT EXISTS ">>, Name]; false -> [<<"CREATE DATABASE ">>, Name] end, case query(Query) of {ok, _Resp} -> ok; Error -> Error end. -spec show_databases() -> term(). show_databases() -> query(<<"SHOW DATABASES">>). select(DB, Measurement) -> Query = <<"SELECT * FROM ", (to_binary(Measurement))/binary>>, select_2(DB, Query). select(DB, Measurement, Cols) -> ComposedCols = compose_cols(Cols, <<>>), Query = <<"SELECT ", ComposedCols/binary, " FROM ", (to_binary(Measurement))/binary>>, select_2(DB, Query). write_batch(DB, Measurements, Values) -> Line = compose_batch(Measurements, Values), write(DB, Line). write(DB, Measurement, Value) -> write(DB, Measurement, [], Value). write(DB, Measurement, [], Value) -> write(DB, line(Measurement, Value)); write(DB, Measurement, Tags, Value) -> write(DB, line(Measurement, Tags, Value)). write(DB, Data) when is_list(Data) -> write(DB, list_to_binary(Data)); write(DB, Data) when is_binary(Data) -> Path = iolist_to_binary([<<"/write?db=">>, to_binary(DB)]), Fun = fun(W) -> fusco:request(W, Path, <<"POST">>, maybe_add_auth([?CT]), Data, 5000) end, case poolboy:transaction(?POOL_NAME, Fun) of {ok, {{<<"204">>, _}, _Hdrs, _Resp, _, _}} -> ok; Error -> Error end. query(DB, Query) -> query_2(iolist_to_binary([<<"/query?db=">>, to_binary(DB), <<"&q=">>, to_binary(Query)])). %%==================================================================== Internal functions %%==================================================================== maybe_add_auth(Headers) -> case application:get_env(?MODULE, username) of {ok, Username} -> {ok, Password} = application:get_env(?MODULE, password), Base64 = base64:encode(<<(to_binary(Username))/binary, ":", (to_binary(Password))/binary>>), [{<<"Authorization">>, <<"Basic ", Base64/binary>>} | Headers]; _Skip -> Headers end. compose_batch(Measurements, Values) -> Zip = lists:zip(Measurements, Values), compose_batch_2(Zip, <<>>). compose_batch_2([], Acc) -> Acc; compose_batch_2([{Measurement, Value}], Acc) -> <<Acc/binary, (line(Measurement, Value))/binary>>; compose_batch_2([{Measurement, Value} | Rest], Acc) -> NewAcc = <<Acc/binary, (line(Measurement, Value))/binary, "\n">>, compose_batch_2(Rest, NewAcc). line(Measurement, Value) -> iolist_to_binary([to_binary(Measurement), <<" value=">>, maybe_integer(Value)]). line(Measurement, Tags, Value) -> iolist_to_binary([to_binary(Measurement), <<",">>, compose_tags(Tags), <<" value=">>, maybe_integer(Value)]). -spec select_2(string() | binary() | atom(), string() | binary()) -> term(). select_2(DB, Query) -> query(to_binary(DB), to_binary(Query)). -spec query(iodata() | binary()) -> term(). query(Query) when is_list(Query) -> query(iolist_to_binary(Query)); query(Query) when is_binary(Query) -> query_2(iolist_to_binary([<<"/query?q=">>, Query])). query_2(Query) when is_binary(Query) -> Query2 = binary:replace(Query, <<" ">>, <<"%20">>, [global]), Fun = fun(W) -> fusco:request(W, Query2, <<"GET">>, maybe_add_auth([]), [], 5000) end, case poolboy:transaction(?POOL_NAME, Fun) of {ok, {{<<"200">>, _}, _Hdrs, Resp, _, _}} -> {ok, jsx:decode(Resp)}; Error -> Error end. compose_tags(Tags) -> compose_tags(Tags, <<>>). compose_tags([], Acc) -> Acc; compose_tags([{Key, Value} | Rest], <<>>) -> NewAcc = <<(to_binary(Key))/binary, "=", (to_binary(Value))/binary>>, compose_tags(Rest, NewAcc); compose_tags([{Key, Value} | Rest], Acc) -> NewAcc = <<(to_binary(Key))/binary, "=", (to_binary(Value))/binary, ",", Acc/binary>>, compose_tags(Rest, NewAcc). compose_cols([], Acc) -> Acc; compose_cols([Col | Cols], <<>>) -> compose_cols(Cols, <<(to_binary(Col))/binary>>); compose_cols([Col | Cols], Acc) -> compose_cols(Cols, <<(to_binary(Col))/binary, ",", Acc/binary>>). maybe_integer(Value) when is_integer(Value) -> <<(to_binary(Value))/binary, "i">>; maybe_integer(Value) -> to_binary(Value). to_binary(Value) when is_integer(Value) -> integer_to_binary(Value); to_binary(Value) when is_list(Value) -> list_to_binary(Value); to_binary(Value) when is_atom(Value) -> atom_to_binary(Value, utf8); to_binary(Value) when is_float(Value) -> list_to_binary(float_to_list(Value)); to_binary(Value) when is_binary(Value) -> Value.
null
https://raw.githubusercontent.com/saa/fluxer/28a60274407cabe8b1317a06799c608265e6fe60/src/fluxer.erl
erlang
==================================================================== API ==================================================================== ==================================================================== ====================================================================
-module(fluxer). -export([start_link/1]). -export([pool_name/0]). -export([create_database/1]). -export([create_database/2]). -export([show_databases/0]). -export([write/2, write/3, write/4]). -export([write_batch/3]). -export([select/2, select/3]). -export([query/2]). -define(POOL_NAME, fluxer_pool). -define(CT, {<<"Content-Type">>, <<"text/plain">>}). start_link([Host, Port, IsSSL, Options]) -> fusco:start_link({Host, Port, IsSSL}, Options). -spec pool_name() -> atom(). pool_name() -> ?POOL_NAME. -spec create_database(string()) -> term(). create_database(Name) -> create_database(Name, false). -spec create_database(string() | boolean() | atom(), boolean()) -> term(). create_database(Name, IfNotExists) when is_list(Name) -> create_database(to_binary(Name), IfNotExists); create_database(Name, IfNotExists) when is_atom(Name) -> create_database(to_binary(Name), IfNotExists); create_database(Name, IfNotExists) when is_binary(Name), is_boolean(IfNotExists) -> Query = case IfNotExists of true -> [<<"CREATE DATABASE IF NOT EXISTS ">>, Name]; false -> [<<"CREATE DATABASE ">>, Name] end, case query(Query) of {ok, _Resp} -> ok; Error -> Error end. -spec show_databases() -> term(). show_databases() -> query(<<"SHOW DATABASES">>). select(DB, Measurement) -> Query = <<"SELECT * FROM ", (to_binary(Measurement))/binary>>, select_2(DB, Query). select(DB, Measurement, Cols) -> ComposedCols = compose_cols(Cols, <<>>), Query = <<"SELECT ", ComposedCols/binary, " FROM ", (to_binary(Measurement))/binary>>, select_2(DB, Query). write_batch(DB, Measurements, Values) -> Line = compose_batch(Measurements, Values), write(DB, Line). write(DB, Measurement, Value) -> write(DB, Measurement, [], Value). write(DB, Measurement, [], Value) -> write(DB, line(Measurement, Value)); write(DB, Measurement, Tags, Value) -> write(DB, line(Measurement, Tags, Value)). write(DB, Data) when is_list(Data) -> write(DB, list_to_binary(Data)); write(DB, Data) when is_binary(Data) -> Path = iolist_to_binary([<<"/write?db=">>, to_binary(DB)]), Fun = fun(W) -> fusco:request(W, Path, <<"POST">>, maybe_add_auth([?CT]), Data, 5000) end, case poolboy:transaction(?POOL_NAME, Fun) of {ok, {{<<"204">>, _}, _Hdrs, _Resp, _, _}} -> ok; Error -> Error end. query(DB, Query) -> query_2(iolist_to_binary([<<"/query?db=">>, to_binary(DB), <<"&q=">>, to_binary(Query)])). Internal functions maybe_add_auth(Headers) -> case application:get_env(?MODULE, username) of {ok, Username} -> {ok, Password} = application:get_env(?MODULE, password), Base64 = base64:encode(<<(to_binary(Username))/binary, ":", (to_binary(Password))/binary>>), [{<<"Authorization">>, <<"Basic ", Base64/binary>>} | Headers]; _Skip -> Headers end. compose_batch(Measurements, Values) -> Zip = lists:zip(Measurements, Values), compose_batch_2(Zip, <<>>). compose_batch_2([], Acc) -> Acc; compose_batch_2([{Measurement, Value}], Acc) -> <<Acc/binary, (line(Measurement, Value))/binary>>; compose_batch_2([{Measurement, Value} | Rest], Acc) -> NewAcc = <<Acc/binary, (line(Measurement, Value))/binary, "\n">>, compose_batch_2(Rest, NewAcc). line(Measurement, Value) -> iolist_to_binary([to_binary(Measurement), <<" value=">>, maybe_integer(Value)]). line(Measurement, Tags, Value) -> iolist_to_binary([to_binary(Measurement), <<",">>, compose_tags(Tags), <<" value=">>, maybe_integer(Value)]). -spec select_2(string() | binary() | atom(), string() | binary()) -> term(). select_2(DB, Query) -> query(to_binary(DB), to_binary(Query)). -spec query(iodata() | binary()) -> term(). query(Query) when is_list(Query) -> query(iolist_to_binary(Query)); query(Query) when is_binary(Query) -> query_2(iolist_to_binary([<<"/query?q=">>, Query])). query_2(Query) when is_binary(Query) -> Query2 = binary:replace(Query, <<" ">>, <<"%20">>, [global]), Fun = fun(W) -> fusco:request(W, Query2, <<"GET">>, maybe_add_auth([]), [], 5000) end, case poolboy:transaction(?POOL_NAME, Fun) of {ok, {{<<"200">>, _}, _Hdrs, Resp, _, _}} -> {ok, jsx:decode(Resp)}; Error -> Error end. compose_tags(Tags) -> compose_tags(Tags, <<>>). compose_tags([], Acc) -> Acc; compose_tags([{Key, Value} | Rest], <<>>) -> NewAcc = <<(to_binary(Key))/binary, "=", (to_binary(Value))/binary>>, compose_tags(Rest, NewAcc); compose_tags([{Key, Value} | Rest], Acc) -> NewAcc = <<(to_binary(Key))/binary, "=", (to_binary(Value))/binary, ",", Acc/binary>>, compose_tags(Rest, NewAcc). compose_cols([], Acc) -> Acc; compose_cols([Col | Cols], <<>>) -> compose_cols(Cols, <<(to_binary(Col))/binary>>); compose_cols([Col | Cols], Acc) -> compose_cols(Cols, <<(to_binary(Col))/binary, ",", Acc/binary>>). maybe_integer(Value) when is_integer(Value) -> <<(to_binary(Value))/binary, "i">>; maybe_integer(Value) -> to_binary(Value). to_binary(Value) when is_integer(Value) -> integer_to_binary(Value); to_binary(Value) when is_list(Value) -> list_to_binary(Value); to_binary(Value) when is_atom(Value) -> atom_to_binary(Value, utf8); to_binary(Value) when is_float(Value) -> list_to_binary(float_to_list(Value)); to_binary(Value) when is_binary(Value) -> Value.
86d50625d9a16d0b628acc963f32bf310618dafecca9abf0621423a7607a7fc8
kazu-yamamoto/dns
StateBinary.hs
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE TypeSynonymInstances #-} # LANGUAGE FlexibleInstances # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE CPP # module Network.DNS.StateBinary ( PState(..) , initialState , SPut , runSPut , put8 , put16 , put32 , putInt8 , putInt16 , putInt32 , putByteString , putReplicate , SGet , failSGet , fitSGet , runSGet , runSGetAt , runSGetWithLeftovers , runSGetWithLeftoversAt , get8 , get16 , get32 , getInt8 , getInt16 , getInt32 , getNByteString , sGetMany , getPosition , getInput , getAtTime , wsPop , wsPush , wsPosition , addPositionW , push , pop , getNBytes , getNoctets , skipNBytes , parseLabel , unparseLabel ) where import qualified Control.Exception as E import Control.Monad.State.Strict (State, StateT) import qualified Control.Monad.State.Strict as ST import qualified Data.Attoparsec.ByteString as A import qualified Data.Attoparsec.Types as T import qualified Data.ByteString as BS import Data.ByteString.Builder (Builder) import qualified Data.ByteString.Builder as BB import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString.Lazy.Char8 as LBS import Data.IntMap (IntMap) import qualified Data.IntMap as IM import Data.Map (Map) import qualified Data.Map as M import Data.Semigroup as Sem import Network.DNS.Imports import Network.DNS.Types.Internal ---------------------------------------------------------------- type SPut = State WState Builder data WState = WState { wsDomain :: Map Domain Int , wsPosition :: Int } initialWState :: WState initialWState = WState M.empty 0 instance Sem.Semigroup SPut where p1 <> p2 = (Sem.<>) <$> p1 <*> p2 instance Monoid SPut where mempty = return mempty #if !(MIN_VERSION_base(4,11,0)) mappend = (Sem.<>) #endif put8 :: Word8 -> SPut put8 = fixedSized 1 BB.word8 put16 :: Word16 -> SPut put16 = fixedSized 2 BB.word16BE put32 :: Word32 -> SPut put32 = fixedSized 4 BB.word32BE putInt8 :: Int -> SPut putInt8 = fixedSized 1 (BB.int8 . fromIntegral) putInt16 :: Int -> SPut putInt16 = fixedSized 2 (BB.int16BE . fromIntegral) putInt32 :: Int -> SPut putInt32 = fixedSized 4 (BB.int32BE . fromIntegral) putByteString :: ByteString -> SPut putByteString = writeSized BS.length BB.byteString putReplicate :: Int -> Word8 -> SPut putReplicate n w = fixedSized n BB.lazyByteString $ LB.replicate (fromIntegral n) w addPositionW :: Int -> State WState () addPositionW n = do (WState m cur) <- ST.get ST.put $ WState m (cur+n) fixedSized :: Int -> (a -> Builder) -> a -> SPut fixedSized n f a = do addPositionW n return (f a) writeSized :: (a -> Int) -> (a -> Builder) -> a -> SPut writeSized n f a = do addPositionW (n a) return (f a) wsPop :: Domain -> State WState (Maybe Int) wsPop dom = do doms <- ST.gets wsDomain return $ M.lookup dom doms wsPush :: Domain -> Int -> State WState () wsPush dom pos = do (WState m cur) <- ST.get ST.put $ WState (M.insert dom pos m) cur ---------------------------------------------------------------- type SGet = StateT PState (T.Parser ByteString) data PState = PState { psDomain :: IntMap Domain , psPosition :: Int , psInput :: ByteString , psAtTime :: Int64 } ---------------------------------------------------------------- getPosition :: SGet Int getPosition = ST.gets psPosition getInput :: SGet ByteString getInput = ST.gets psInput getAtTime :: SGet Int64 getAtTime = ST.gets psAtTime addPosition :: Int -> SGet () addPosition n | n < 0 = failSGet "internal error: negative position increment" | otherwise = do PState dom pos inp t <- ST.get let !pos' = pos + n when (pos' > BS.length inp) $ failSGet "malformed or truncated input" ST.put $ PState dom pos' inp t push :: Int -> Domain -> SGet () push n d = do PState dom pos inp t <- ST.get ST.put $ PState (IM.insert n d dom) pos inp t pop :: Int -> SGet (Maybe Domain) pop n = ST.gets (IM.lookup n . psDomain) ---------------------------------------------------------------- get8 :: SGet Word8 get8 = ST.lift A.anyWord8 <* addPosition 1 get16 :: SGet Word16 get16 = ST.lift getWord16be <* addPosition 2 where word8' = fromIntegral <$> A.anyWord8 getWord16be = do a <- word8' b <- word8' return $ a * 0x100 + b get32 :: SGet Word32 get32 = ST.lift getWord32be <* addPosition 4 where word8' = fromIntegral <$> A.anyWord8 getWord32be = do a <- word8' b <- word8' c <- word8' d <- word8' return $ a * 0x1000000 + b * 0x10000 + c * 0x100 + d getInt8 :: SGet Int getInt8 = fromIntegral <$> get8 getInt16 :: SGet Int getInt16 = fromIntegral <$> get16 getInt32 :: SGet Int getInt32 = fromIntegral <$> get32 ---------------------------------------------------------------- overrun :: SGet a overrun = failSGet "malformed or truncated input" getNBytes :: Int -> SGet [Int] getNBytes n | n < 0 = overrun | otherwise = toInts <$> getNByteString n where toInts = map fromIntegral . BS.unpack getNoctets :: Int -> SGet [Word8] getNoctets n | n < 0 = overrun | otherwise = BS.unpack <$> getNByteString n skipNBytes :: Int -> SGet () skipNBytes n | n < 0 = overrun | otherwise = ST.lift (A.take n) >> addPosition n getNByteString :: Int -> SGet ByteString getNByteString n | n < 0 = overrun | otherwise = ST.lift (A.take n) <* addPosition n fitSGet :: Int -> SGet a -> SGet a fitSGet len parser | len < 0 = overrun | otherwise = do pos0 <- getPosition ret <- parser pos' <- getPosition if pos' == pos0 + len then return $! ret else if pos' > pos0 + len then failSGet "element size exceeds declared size" else failSGet "element shorter than declared size" -- | Parse a list of elements that takes up exactly a given number of bytes. -- In order to avoid infinite loops, if an element parser succeeds without -- moving the buffer offset forward, an error will be returned. -- sGetMany :: String -- ^ element type for error messages -> Int -- ^ input buffer length -> SGet a -- ^ element parser -> SGet [a] sGetMany elemname len parser | len < 0 = overrun | otherwise = go len [] where go n xs | n < 0 = failSGet $ elemname ++ " longer than declared size" | n == 0 = pure $ reverse xs | otherwise = do pos0 <- getPosition x <- parser pos1 <- getPosition if pos1 <= pos0 then failSGet $ "internal error: in-place success for " ++ elemname else go (n + pos0 - pos1) (x : xs) ---------------------------------------------------------------- | To get a broad range of correct RRSIG inception and expiration times without over or underflow , we choose a time half way between midnight PDT 2010 - 07 - 15 ( the day the root zone was signed ) and 2 ^ 32 seconds later on 2146 - 08 - 21 . Since ' decode ' and ' runSGet ' are pure , we ca n't peek at the -- current time while parsing. Outside this date range the output is off by some non - zero multiple 2\^32 seconds . -- dnsTimeMid :: Int64 dnsTimeMid = 3426660848 initialState :: Int64 -> ByteString -> PState initialState t inp = PState IM.empty 0 inp t Construct our own error message , without the unhelpful AttoParsec -- \"Failed reading: \" prefix. -- failSGet :: String -> SGet a failSGet msg = ST.lift (fail "" A.<?> msg) runSGetAt :: Int64 -> SGet a -> ByteString -> Either DNSError (a, PState) runSGetAt t parser inp = toResult $ A.parse (ST.runStateT parser $ initialState t inp) inp where toResult :: A.Result r -> Either DNSError r toResult (A.Done _ r) = Right r toResult (A.Fail _ ctx msg) = Left $ DecodeError $ head $ ctx ++ [msg] toResult (A.Partial _) = Left $ DecodeError "incomplete input" runSGet :: SGet a -> ByteString -> Either DNSError (a, PState) runSGet = runSGetAt dnsTimeMid runSGetWithLeftoversAt :: Int64 -- ^ Reference time for DNS clock arithmetic ^ -> ByteString -- ^ Encoded message -> Either DNSError ((a, PState), ByteString) runSGetWithLeftoversAt t parser inp = toResult $ A.parse (ST.runStateT parser $ initialState t inp) inp where toResult :: A.Result r -> Either DNSError (r, ByteString) toResult (A.Done i r) = Right (r, i) toResult (A.Partial f) = toResult $ f BS.empty toResult (A.Fail _ ctx e) = Left $ DecodeError $ head $ ctx ++ [e] runSGetWithLeftovers :: SGet a -> ByteString -> Either DNSError ((a, PState), ByteString) runSGetWithLeftovers = runSGetWithLeftoversAt dnsTimeMid runSPut :: SPut -> ByteString runSPut = LBS.toStrict . BB.toLazyByteString . flip ST.evalState initialWState ---------------------------------------------------------------- -- | Decode a domain name in A-label form to a leading label and a tail with -- the remaining labels, unescaping backlashed chars and decimal triples along -- the way. Any U-label conversion belongs at the layer above this code. -- parseLabel :: Word8 -> ByteString -> Either DNSError (ByteString, ByteString) parseLabel sep dom = if BS.any (== bslash) dom then toResult $ A.parse (labelParser sep mempty) dom else check $ safeTail <$> BS.break (== sep) dom where toResult (A.Partial c) = toResult (c mempty) toResult (A.Done tl hd) = check (hd, tl) toResult _ = bottom safeTail bs | BS.null bs = mempty | otherwise = BS.tail bs check r@(hd, tl) | not (BS.null hd) || BS.null tl = Right r | otherwise = bottom bottom = Left $ DecodeError $ "invalid domain: " ++ S8.unpack dom labelParser :: Word8 -> ByteString -> A.Parser ByteString labelParser sep acc = do acc' <- mappend acc <$> A.option mempty simple labelEnd sep acc' <|> (escaped >>= labelParser sep . BS.snoc acc') where simple = fst <$> A.match skipUnescaped where skipUnescaped = A.skipMany1 $ A.satisfy notSepOrBslash notSepOrBslash w = w /= sep && w /= bslash escaped = do A.skip (== bslash) either decodeDec pure =<< A.eitherP digit A.anyWord8 where digit = fromIntegral <$> A.satisfyWith (\n -> n - zero) (<=9) decodeDec d = safeWord8 =<< trigraph d <$> digit <*> digit where trigraph :: Word -> Word -> Word -> Word trigraph x y z = 100 * x + 10 * y + z safeWord8 :: Word -> A.Parser Word8 safeWord8 n | n > 255 = mzero | otherwise = pure $ fromIntegral n labelEnd :: Word8 -> ByteString -> A.Parser ByteString labelEnd sep acc = A.satisfy (== sep) *> pure acc <|> A.endOfInput *> pure acc ---------------------------------------------------------------- -- | Convert a wire-form label to presentation-form by escaping -- the separator, special and non-printing characters. For simple -- labels with no bytes that require escaping we get back the input -- bytestring asis with no copying or re-construction. -- Note : the separator is required to be either \'.\ ' or \'\@\ ' , but this -- constraint is the caller's responsibility and is not checked here. -- unparseLabel :: Word8 -> ByteString -> ByteString unparseLabel sep label = if BS.all (isPlain sep) label then label else toResult $ A.parse (labelUnparser sep mempty) label where toResult (A.Partial c) = toResult (c mempty) toResult (A.Done _ r) = r toResult _ = E.throw UnknownDNSError -- can't happen labelUnparser :: Word8 -> ByteString -> A.Parser ByteString labelUnparser sep acc = do acc' <- mappend acc <$> A.option mempty asis A.endOfInput *> pure acc' <|> (esc >>= labelUnparser sep . mappend acc') where -- Non-printables are escaped as decimal trigraphs, while printable -- specials just get a backslash prefix. esc = do w <- A.anyWord8 if w <= 32 || w >= 127 then let (q100, r100) = w `divMod` 100 (q10, r10) = r100 `divMod` 10 in pure $ BS.pack [ bslash, zero + q100, zero + q10, zero + r10 ] else pure $ BS.pack [ bslash, w ] -- Runs of plain bytes are recognized as a single chunk, which is then -- returned as-is. asis = fmap fst $ A.match $ A.skipMany1 $ A.satisfy $ isPlain sep | In the presentation form of DNS labels , these characters are escaped by prepending a backlash . ( They have special meaning in zone files ) . Whitespace -- and other non-printable or non-ascii characters are encoded via "\DDD" -- decimal escapes. The separator character is also quoted in each label. Note -- that '@' is quoted even when not the separator. escSpecials :: ByteString escSpecials = "\"$();@\\" | Is the given byte the separator or one of the specials ? isSpecial :: Word8 -> Word8 -> Bool isSpecial sep w = w == sep || BS.elemIndex w escSpecials /= Nothing -- | Is the given byte a plain byte that reqires no escaping. The tests are -- ordered to succeed or fail quickly in the most common cases. The test -- ranges assume the expected numeric values of the named special characters. -- Note: the separator is assumed to be either '.' or '@' and so not matched by any of the first three fast - path ' True ' cases . isPlain :: Word8 -> Word8 -> Bool isPlain sep w | w >= 127 = False -- <DEL> + non-ASCII | w > bslash = True -- ']'..'_'..'a'..'z'..'~' | w >= zero && w < semi = True -- '0'..'9'..':' | w > atsign && w < bslash = True -- 'A'..'Z'..'[' | w <= 32 = False -- non-printables | isSpecial sep w = False -- one of the specials | otherwise = True -- plain punctuation -- | Some numeric byte constants. zero, semi, atsign, bslash :: Word8 48 59 64 92
null
https://raw.githubusercontent.com/kazu-yamamoto/dns/067e91ae552d70eaeea890b2c78f983519a824db/internal/Network/DNS/StateBinary.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE TypeSynonymInstances # # LANGUAGE OverloadedStrings # -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- | Parse a list of elements that takes up exactly a given number of bytes. In order to avoid infinite loops, if an element parser succeeds without moving the buffer offset forward, an error will be returned. ^ element type for error messages ^ input buffer length ^ element parser -------------------------------------------------------------- current time while parsing. Outside this date range the output is off by \"Failed reading: \" prefix. ^ Reference time for DNS clock arithmetic ^ Encoded message -------------------------------------------------------------- | Decode a domain name in A-label form to a leading label and a tail with the remaining labels, unescaping backlashed chars and decimal triples along the way. Any U-label conversion belongs at the layer above this code. -------------------------------------------------------------- | Convert a wire-form label to presentation-form by escaping the separator, special and non-printing characters. For simple labels with no bytes that require escaping we get back the input bytestring asis with no copying or re-construction. constraint is the caller's responsibility and is not checked here. can't happen Non-printables are escaped as decimal trigraphs, while printable specials just get a backslash prefix. Runs of plain bytes are recognized as a single chunk, which is then returned as-is. and other non-printable or non-ascii characters are encoded via "\DDD" decimal escapes. The separator character is also quoted in each label. Note that '@' is quoted even when not the separator. | Is the given byte a plain byte that reqires no escaping. The tests are ordered to succeed or fail quickly in the most common cases. The test ranges assume the expected numeric values of the named special characters. Note: the separator is assumed to be either '.' or '@' and so not matched by <DEL> + non-ASCII ']'..'_'..'a'..'z'..'~' '0'..'9'..':' 'A'..'Z'..'[' non-printables one of the specials plain punctuation | Some numeric byte constants.
# LANGUAGE FlexibleInstances # # LANGUAGE CPP # module Network.DNS.StateBinary ( PState(..) , initialState , SPut , runSPut , put8 , put16 , put32 , putInt8 , putInt16 , putInt32 , putByteString , putReplicate , SGet , failSGet , fitSGet , runSGet , runSGetAt , runSGetWithLeftovers , runSGetWithLeftoversAt , get8 , get16 , get32 , getInt8 , getInt16 , getInt32 , getNByteString , sGetMany , getPosition , getInput , getAtTime , wsPop , wsPush , wsPosition , addPositionW , push , pop , getNBytes , getNoctets , skipNBytes , parseLabel , unparseLabel ) where import qualified Control.Exception as E import Control.Monad.State.Strict (State, StateT) import qualified Control.Monad.State.Strict as ST import qualified Data.Attoparsec.ByteString as A import qualified Data.Attoparsec.Types as T import qualified Data.ByteString as BS import Data.ByteString.Builder (Builder) import qualified Data.ByteString.Builder as BB import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString.Lazy.Char8 as LBS import Data.IntMap (IntMap) import qualified Data.IntMap as IM import Data.Map (Map) import qualified Data.Map as M import Data.Semigroup as Sem import Network.DNS.Imports import Network.DNS.Types.Internal type SPut = State WState Builder data WState = WState { wsDomain :: Map Domain Int , wsPosition :: Int } initialWState :: WState initialWState = WState M.empty 0 instance Sem.Semigroup SPut where p1 <> p2 = (Sem.<>) <$> p1 <*> p2 instance Monoid SPut where mempty = return mempty #if !(MIN_VERSION_base(4,11,0)) mappend = (Sem.<>) #endif put8 :: Word8 -> SPut put8 = fixedSized 1 BB.word8 put16 :: Word16 -> SPut put16 = fixedSized 2 BB.word16BE put32 :: Word32 -> SPut put32 = fixedSized 4 BB.word32BE putInt8 :: Int -> SPut putInt8 = fixedSized 1 (BB.int8 . fromIntegral) putInt16 :: Int -> SPut putInt16 = fixedSized 2 (BB.int16BE . fromIntegral) putInt32 :: Int -> SPut putInt32 = fixedSized 4 (BB.int32BE . fromIntegral) putByteString :: ByteString -> SPut putByteString = writeSized BS.length BB.byteString putReplicate :: Int -> Word8 -> SPut putReplicate n w = fixedSized n BB.lazyByteString $ LB.replicate (fromIntegral n) w addPositionW :: Int -> State WState () addPositionW n = do (WState m cur) <- ST.get ST.put $ WState m (cur+n) fixedSized :: Int -> (a -> Builder) -> a -> SPut fixedSized n f a = do addPositionW n return (f a) writeSized :: (a -> Int) -> (a -> Builder) -> a -> SPut writeSized n f a = do addPositionW (n a) return (f a) wsPop :: Domain -> State WState (Maybe Int) wsPop dom = do doms <- ST.gets wsDomain return $ M.lookup dom doms wsPush :: Domain -> Int -> State WState () wsPush dom pos = do (WState m cur) <- ST.get ST.put $ WState (M.insert dom pos m) cur type SGet = StateT PState (T.Parser ByteString) data PState = PState { psDomain :: IntMap Domain , psPosition :: Int , psInput :: ByteString , psAtTime :: Int64 } getPosition :: SGet Int getPosition = ST.gets psPosition getInput :: SGet ByteString getInput = ST.gets psInput getAtTime :: SGet Int64 getAtTime = ST.gets psAtTime addPosition :: Int -> SGet () addPosition n | n < 0 = failSGet "internal error: negative position increment" | otherwise = do PState dom pos inp t <- ST.get let !pos' = pos + n when (pos' > BS.length inp) $ failSGet "malformed or truncated input" ST.put $ PState dom pos' inp t push :: Int -> Domain -> SGet () push n d = do PState dom pos inp t <- ST.get ST.put $ PState (IM.insert n d dom) pos inp t pop :: Int -> SGet (Maybe Domain) pop n = ST.gets (IM.lookup n . psDomain) get8 :: SGet Word8 get8 = ST.lift A.anyWord8 <* addPosition 1 get16 :: SGet Word16 get16 = ST.lift getWord16be <* addPosition 2 where word8' = fromIntegral <$> A.anyWord8 getWord16be = do a <- word8' b <- word8' return $ a * 0x100 + b get32 :: SGet Word32 get32 = ST.lift getWord32be <* addPosition 4 where word8' = fromIntegral <$> A.anyWord8 getWord32be = do a <- word8' b <- word8' c <- word8' d <- word8' return $ a * 0x1000000 + b * 0x10000 + c * 0x100 + d getInt8 :: SGet Int getInt8 = fromIntegral <$> get8 getInt16 :: SGet Int getInt16 = fromIntegral <$> get16 getInt32 :: SGet Int getInt32 = fromIntegral <$> get32 overrun :: SGet a overrun = failSGet "malformed or truncated input" getNBytes :: Int -> SGet [Int] getNBytes n | n < 0 = overrun | otherwise = toInts <$> getNByteString n where toInts = map fromIntegral . BS.unpack getNoctets :: Int -> SGet [Word8] getNoctets n | n < 0 = overrun | otherwise = BS.unpack <$> getNByteString n skipNBytes :: Int -> SGet () skipNBytes n | n < 0 = overrun | otherwise = ST.lift (A.take n) >> addPosition n getNByteString :: Int -> SGet ByteString getNByteString n | n < 0 = overrun | otherwise = ST.lift (A.take n) <* addPosition n fitSGet :: Int -> SGet a -> SGet a fitSGet len parser | len < 0 = overrun | otherwise = do pos0 <- getPosition ret <- parser pos' <- getPosition if pos' == pos0 + len then return $! ret else if pos' > pos0 + len then failSGet "element size exceeds declared size" else failSGet "element shorter than declared size" -> SGet [a] sGetMany elemname len parser | len < 0 = overrun | otherwise = go len [] where go n xs | n < 0 = failSGet $ elemname ++ " longer than declared size" | n == 0 = pure $ reverse xs | otherwise = do pos0 <- getPosition x <- parser pos1 <- getPosition if pos1 <= pos0 then failSGet $ "internal error: in-place success for " ++ elemname else go (n + pos0 - pos1) (x : xs) | To get a broad range of correct RRSIG inception and expiration times without over or underflow , we choose a time half way between midnight PDT 2010 - 07 - 15 ( the day the root zone was signed ) and 2 ^ 32 seconds later on 2146 - 08 - 21 . Since ' decode ' and ' runSGet ' are pure , we ca n't peek at the some non - zero multiple 2\^32 seconds . dnsTimeMid :: Int64 dnsTimeMid = 3426660848 initialState :: Int64 -> ByteString -> PState initialState t inp = PState IM.empty 0 inp t Construct our own error message , without the unhelpful AttoParsec failSGet :: String -> SGet a failSGet msg = ST.lift (fail "" A.<?> msg) runSGetAt :: Int64 -> SGet a -> ByteString -> Either DNSError (a, PState) runSGetAt t parser inp = toResult $ A.parse (ST.runStateT parser $ initialState t inp) inp where toResult :: A.Result r -> Either DNSError r toResult (A.Done _ r) = Right r toResult (A.Fail _ ctx msg) = Left $ DecodeError $ head $ ctx ++ [msg] toResult (A.Partial _) = Left $ DecodeError "incomplete input" runSGet :: SGet a -> ByteString -> Either DNSError (a, PState) runSGet = runSGetAt dnsTimeMid ^ -> Either DNSError ((a, PState), ByteString) runSGetWithLeftoversAt t parser inp = toResult $ A.parse (ST.runStateT parser $ initialState t inp) inp where toResult :: A.Result r -> Either DNSError (r, ByteString) toResult (A.Done i r) = Right (r, i) toResult (A.Partial f) = toResult $ f BS.empty toResult (A.Fail _ ctx e) = Left $ DecodeError $ head $ ctx ++ [e] runSGetWithLeftovers :: SGet a -> ByteString -> Either DNSError ((a, PState), ByteString) runSGetWithLeftovers = runSGetWithLeftoversAt dnsTimeMid runSPut :: SPut -> ByteString runSPut = LBS.toStrict . BB.toLazyByteString . flip ST.evalState initialWState parseLabel :: Word8 -> ByteString -> Either DNSError (ByteString, ByteString) parseLabel sep dom = if BS.any (== bslash) dom then toResult $ A.parse (labelParser sep mempty) dom else check $ safeTail <$> BS.break (== sep) dom where toResult (A.Partial c) = toResult (c mempty) toResult (A.Done tl hd) = check (hd, tl) toResult _ = bottom safeTail bs | BS.null bs = mempty | otherwise = BS.tail bs check r@(hd, tl) | not (BS.null hd) || BS.null tl = Right r | otherwise = bottom bottom = Left $ DecodeError $ "invalid domain: " ++ S8.unpack dom labelParser :: Word8 -> ByteString -> A.Parser ByteString labelParser sep acc = do acc' <- mappend acc <$> A.option mempty simple labelEnd sep acc' <|> (escaped >>= labelParser sep . BS.snoc acc') where simple = fst <$> A.match skipUnescaped where skipUnescaped = A.skipMany1 $ A.satisfy notSepOrBslash notSepOrBslash w = w /= sep && w /= bslash escaped = do A.skip (== bslash) either decodeDec pure =<< A.eitherP digit A.anyWord8 where digit = fromIntegral <$> A.satisfyWith (\n -> n - zero) (<=9) decodeDec d = safeWord8 =<< trigraph d <$> digit <*> digit where trigraph :: Word -> Word -> Word -> Word trigraph x y z = 100 * x + 10 * y + z safeWord8 :: Word -> A.Parser Word8 safeWord8 n | n > 255 = mzero | otherwise = pure $ fromIntegral n labelEnd :: Word8 -> ByteString -> A.Parser ByteString labelEnd sep acc = A.satisfy (== sep) *> pure acc <|> A.endOfInput *> pure acc Note : the separator is required to be either \'.\ ' or \'\@\ ' , but this unparseLabel :: Word8 -> ByteString -> ByteString unparseLabel sep label = if BS.all (isPlain sep) label then label else toResult $ A.parse (labelUnparser sep mempty) label where toResult (A.Partial c) = toResult (c mempty) toResult (A.Done _ r) = r labelUnparser :: Word8 -> ByteString -> A.Parser ByteString labelUnparser sep acc = do acc' <- mappend acc <$> A.option mempty asis A.endOfInput *> pure acc' <|> (esc >>= labelUnparser sep . mappend acc') where esc = do w <- A.anyWord8 if w <= 32 || w >= 127 then let (q100, r100) = w `divMod` 100 (q10, r10) = r100 `divMod` 10 in pure $ BS.pack [ bslash, zero + q100, zero + q10, zero + r10 ] else pure $ BS.pack [ bslash, w ] asis = fmap fst $ A.match $ A.skipMany1 $ A.satisfy $ isPlain sep | In the presentation form of DNS labels , these characters are escaped by prepending a backlash . ( They have special meaning in zone files ) . Whitespace escSpecials :: ByteString escSpecials = "\"$();@\\" | Is the given byte the separator or one of the specials ? isSpecial :: Word8 -> Word8 -> Bool isSpecial sep w = w == sep || BS.elemIndex w escSpecials /= Nothing any of the first three fast - path ' True ' cases . isPlain :: Word8 -> Word8 -> Bool zero, semi, atsign, bslash :: Word8 48 59 64 92
071848c690d9cd9f941c54565398a6bd8836c85086ac8feed2b3d02d77603593
koka-lang/koka
Box.hs
----------------------------------------------------------------------------- Copyright 2020 - 2021 , Microsoft Research , . -- -- This is free software; you can redistribute it and/or modify it under the terms of the Apache License , Version 2.0 . A copy of the License can be -- found in the LICENSE file at the root of this distribution. ----------------------------------------------------------------------------- module Backend.C.Box ( boxCore ) where import Lib.Trace import Control.Applicative hiding (empty) import Control.Monad import Data.List ( intersperse, partition ) import Data.Char import Data . Maybe import Data . Monoid ( mappend ) import qualified Data.Set as S import Kind.Kind import Kind.Newtypes import Type.Type import Type.TypeVar import Type.Kind( getKind ) import qualified Type.Pretty as Pretty import Lib.PPrint import Common.Name import Common.Range import Common.NamePrim import Common.Failure import Common.Unique import Common.Syntax import Core.Core import Core.Pretty import Core.CoreVar import Core . CTail ( isCTailOp ) import Core.Simplify -------------------------------------------------------------------------- -- Box/unbox transformation -------------------------------------------------------------------------- boxCore :: Core -> Unique Core boxCore core = do defs <- boxDefGroups (coreProgDefs core) return (core{ coreProgDefs = defs }) boxDefGroups :: DefGroups -> Unique DefGroups boxDefGroups dgs = mapM boxDefGroup dgs boxDefGroup :: DefGroup -> Unique DefGroup boxDefGroup dg = case dg of DefRec defs -> fmap DefRec (mapM boxDef defs) DefNonRec def -> fmap DefNonRec (boxDef def) boxDef :: Def -> Unique Def boxDef def = -- trace ("box def: " ++ show (defName def) ++ ": " ++ show (pretty (defType def)) ++ "\n" ++ show (prettyExpr Pretty.defaultEnv{Pretty.coreShowTypes=True} (defExpr def))) $ do bexpr <- boxExpr (boxType (defType def)) (defExpr def) let bdef = def{ defExpr = bexpr } -- simplify the whole def to avoid simplifying away functions to values (e.g. `fun f(x){ g(x) } ~> val f = g`) uniqueSimplify Pretty.defaultEnv True {- unsafe -} False {-ndebug-} 3 {-runs-} 6 {- duplicationMax -} bdef -- add box/unbox such that the type of `expr` matches `BoxType` boxExpr :: BoxType -> Expr -> Unique Expr boxExpr expectTp expr = case expr of -- remove type abstraction and applications TypeLam tvs e -> boxExpr expectTp e TypeApp e tps -> boxExpr expectTp e -- Regular App e args -> do let argTps = map boxTypeOf args eTp = TFun [(nameNil,tp) | tp <- argTps] typeTotal expectTp bargs <- mapM (\(arg) -> boxExpr (boxTypeOf arg) arg) args bexpr <- boxExpr eTp e return (App bexpr bargs) Lam tparams eff body -> do let funTp = boxTypeOf expr bbody <- boxExpr (boxTypeOf body) body bcoerce funTp (expectTp) (Lam tparams eff bbody) Let defGroups body -> do bdgs <- boxDefGroups defGroups bbody <- boxExpr expectTp body return (Let bdgs bbody) Case exprs branches -> do let exprTps = map boxTypeOf exprs bexprs <- mapM (\(tp,e) -> boxExpr tp e) (zip exprTps exprs) bbranches <- mapM (boxBranch exprTps expectTp) branches return (Case bexprs bbranches) _ -> bcoerce (boxTypeOf expr) expectTp expr {- isBoxOp (App (Var (TName name _) (InfoExternal _)) [arg]) = (name == newHiddenName ("box") || name == newHiddenName ("unbox")) isBoxOp _ = False -} boxBranch :: [BoxType] -> BoxType -> Branch -> Unique Branch boxBranch patTps expectTp (Branch patterns guards) = do (bpatterns,defss) <- unzipM $ mapM (\(patTp,pat) -> boxPattern patTp pat) (zip patTps patterns) let binds expr = makeLet [DefNonRec def | def <- concat defss] expr bguards <- mapM (boxGuard expectTp binds) guards return (Branch bpatterns bguards) boxGuard :: BoxType -> (Expr -> Expr) -> Guard -> Unique Guard boxGuard expectTp binds (Guard test expr) =do btest <- boxExpr typeBool test bexpr <- boxExpr expectTp expr TODO : binds come too late to appear in guards but we need binds for function wrappers ? .. perhaps create a specal pattern just for the C backend ? -- add bindings and box/unbox such that pattern matches the required boxtype boxPattern :: BoxType -> Pattern -> Unique (Pattern, [Def]) boxPattern fromTp PatWild = boxPatternX fromTp PatWild boxPattern fromTp pat | cType (fromTp) /= cType toTp = do mcoerce <- -- trace ("pattern coerce: " ++ show (pretty fromTp) ++ " ~> " ++ show (pretty toTp)) $ bcoerceX fromTp toTp (Var (TName nameNil fromTp) InfoNone) case mcoerce of Just coerce0 -> -- We just insert a specially named Box pattern bound to fresh variable -- the backend recognizes this -- and generates unbox/box expressions appropiately so nested patterns are handled correctly -- Unfortunately, this does not work for function wrappers (as we need to generate a -- wrapped unbox/box function around it); for those we rename and generate an explicit binding -- binding; this works as a function type is never pattern matched further. -- TODO: this may fail if the function is used in a guard test itself where it is not bound yet. -- we could work around this by substituting explicitly in the guard in that case. if (isComplexCoerce coerce0) then -- function match case pat of PatVar tname PatWild -> -- ok, no nested match do i <- unique let uname = newHiddenName ("fun-unbox-x" ++ show i) coerce <- bcoerce fromTp toTp (Var (TName uname fromTp) InfoNone) -- regenerate the coercion let def = makeTDef (TName (getName tname) toTp) coerce --trace ("unbox function: " ++ show uname ++ ": " ++ show (pretty fromTp) ++ " to " ++ show (pretty toTp) -- ++ "\n: coerce tp: " ++ show (pretty (typeOf coerce))) $ return (PatVar (TName uname fromTp) PatWild, [def]) _ -> failure "Backend/C/FromCore.boxPattern: nested match on a function?" else -- regular box/unbox do i <- unique let uname = newHiddenName ("box-x" ++ show i) (bpat,defs) <- boxPatternX toTp pat -- trace ("unbox pattern: " ++ show uname ++ ": " ++ show (pretty toTp)) $ return ( PatVar ( TName uname toTp ) bpat , ) -- toTp for generating correct unbox call in the C backend return (PatVar (TName uname typeBoxStar) (patBox toTp typeBoxStar bpat), defs) _ -> -- trace ("pattern: no-coerce: " ++ show (pretty fromTp) ++ " to " ++ show (pretty toTp)) $ boxPatternX fromTp pat where toTp = case pat of PatCon{} -> patTypeRes pat PatVar tname _ -> typeOf tname PatLit lit -> typeOf lit PatWild -> typeAny -- cannot happen isComplexCoerce coerce = case (cType fromTp, cType toTp) of (CFun{},_) -> True (_,CFun{}) -> True _ -> False boxPattern fromTp pat = boxPatternX fromTp pat boxPatternX :: BoxType -> Pattern -> Unique (Pattern,[Def]) boxPatternX fromTp pat = case pat of PatCon name params repr targs exists tres conInfo skip -> do (bparams,defss) <- unzipM $ mapM (\(ftp,par) -> boxPattern ftp par) (zip (map snd (conInfoParams conInfo)) params) return (PatCon name bparams repr targs exists tres conInfo skip, concat defss) PatVar tname arg -> do (barg,defs) <- boxPattern (typeOf tname) arg return (PatVar tname barg, defs) PatWild -> return (pat,[]) PatLit _ -> return (pat,[]) -- coerce `expr` of `fromTp` to `toTp` bcoerce :: Type -> Type -> Expr -> Unique Expr bcoerce fromTp toTp expr = do mb <- bcoerceX fromTp toTp expr case mb of Just expr' -> return expr' Nothing -> return expr bcoerceX :: Type -> Type -> Expr -> Unique (Maybe Expr) bcoerceX fromTp toTp expr = case (cType fromTp, cType toTp) of (CBox, CBox) -> return Nothing (CBox, CData) -> return $ Just $ App (unboxVar) [expr] (CData, CBox) -> return $ Just $ App (boxVar) [expr] -- boxed functions need to wrapped to take all arguments and results as boxed as well :-( -- see test/cgen/box3 and test/cgen/box3a (CBox, CFun cpars cres) -> --trace ("box to fun: " ++ show expr) $ do boxedToTp <- boxedFunType toTp let unboxed = App (unboxVarAtTp (TFun [(nameNil,fromTp)] typeTotal boxedToTp)) [expr] Just <$> bcoerce boxedToTp toTp unboxed -- unwrap function; we must return Just even if no further wrapping was needed (CFun cpars cres, CBox) -> --trace ("fun to box: " ++ show expr) $ do boxedFromTp <- boxedFunType fromTp expr' <- bcoerce fromTp boxedFromTp expr -- wrap function return $ Just $ App (boxVarAtTp (TFun [(nameNil,boxedFromTp)] typeTotal toTp)) [expr'] -- and box it itselfob -- coerce between function arguments/results (CFun fromPars fromRes, CFun toPars toRes) | not (all (\(t1,t2) -> t1 == t2) (zip fromPars toPars) && fromRes == toRes) -> case splitFunScheme toTp of Just (_,_,toParTps,toEffTp,toResTp) -> case splitFunScheme fromTp of Just (_,_,fromParTps,fromEffTp,fromResTp) -> Just <$> (boxBindExprAsValue fromTp toTp expr $ \vexpr -> boxCoerceFun toParTps toEffTp toResTp fromParTps fromEffTp fromResTp vexpr) _ -> failure $ "Backend.C.Box: bcoerceX: expecting function (from): " ++ show (pretty fromTp) _ -> failure $ "Backend.C.Box: bcoerceX: expecting function (to): " ++ show (pretty toTp) _ -> return Nothing where boxVar = boxVarAtTp coerceTp unboxVar = unboxVarAtTp coerceTp coerceTp = TFun [(nameNil,fromTp)] typeTotal toTp boxVarAtTp tp = Var (TName nameBox tp) (InfoExternal [(C CDefault, "box(#1)")]) unboxVarAtTp tp = Var (TName nameUnbox tp) (InfoExternal [(C CDefault, "unbox(#1)")]) boxCoerceFun :: [(Name,Type)] -> Effect -> Type -> [(Name,Type)] -> Effect -> Type -> Expr -> Unique Expr boxCoerceFun toParTps toEffTp toResTp fromParTps fromEffTp fromResTp expr = -- trace ("box coerce fun: " ++ show expr) $ do names <- mapM (\_ -> uniqueName "b") toParTps let pars = zipWith TName names (map snd toParTps) args = [Var par InfoNone | par <- pars] bargs <- -- mapM (\(arg,argTp) -> boxExpr argTp arg) (zip args (map snd fromParTps)) mapM (\(arg,parToTp,parFromTp) -> bcoerce parToTp parFromTp arg) (zip3 args (map snd toParTps) (map snd fromParTps)) bapp <- bcoerce fromResTp toResTp (App expr bargs) return (Lam pars toEffTp bapp) boxBindExprAsValue :: Type -> Type -> Expr -> (Expr -> Unique Expr) -> Unique Expr boxBindExprAsValue fromTp toTp expr action | isTotal expr = action expr boxBindExprAsValue fromTp toTp expr action = -- trace ("box coerce with yield extension: " ++ show expr) $ do v <- uniqueTName "bv" fromTp body <- action (Var v InfoNone) return (Let [DefNonRec (makeTDef v expr)] body) do yextend < - do vb < - uniqueTName " bb " ( TVar tvarA ) w < - uniqueTName " bw " fromTp x < - uniqueTName " bx " toTp let varVb = Var vb InfoNone varX = Var x InfoNone unboxVb < - bcoerce ( ) ( typeOf w ) varVb boxResX < - bcoerce ( ) ( TVar tvarB ) varX body1 < - action ( Var w InfoNone ) makeYieldExtend ( typeOf vb ) toTp $ [ vb ] typeTotal { - ? do yextend <- do vb <- uniqueTName "bb" (TVar tvarA) w <- uniqueTName "bw" fromTp x <- uniqueTName "bx" toTp let varVb = Var vb InfoNone varX = Var x InfoNone unboxVb <- bcoerce (typeOf vb) (typeOf w) varVb boxResX <- bcoerce (typeOf x) (TVar tvarB) varX body1 <- action (Var w InfoNone) makeYieldExtend (typeOf vb) toTp $ Lam [vb] typeTotal {-?-} $ Let [DefNonRec (makeTDef w unboxVb) ,DefNonRec (makeTDef x body1)] boxResX v <- uniqueTName "bv" fromTp body2 <- action (Var v InfoNone) return (Let [DefNonRec (makeTDef v expr)] $ makeIfExpr makeYielding yextend body2 ) where coerceTp = TFun [(nameNil,fromTp)] typeTotal toTp makeYielding :: Expr makeYielding = App (Var (TName nameYielding typeYielding) (InfoExternal [(C,"kk_yielding(kk_context())")])) [] where typeYielding = TFun [] typeTotal typeBool makeYieldExtend :: Type -> Type -> Expr -> Unique Expr makeYieldExtend fromTp toTp expr = do let yextend = App (TypeApp (Var (TName nameYieldExtend typeYieldExtend) (InfoArity 3 1)) [TVar tvarA, TVar tvarB, typeTotal]) [expr] -- no need for nice unbox , it will be box_any anyways ... v < - uniqueTName " b " ( TVar tvarB ) body < - bcoerce ( v ) toTp ( Var v InfoNone ) return ( Let [ DefNonRec ( makeTDef v yextend ) ] body ) v <- uniqueTName "b" (TVar tvarB) body <- bcoerce (typeOf v) toTp (Var v InfoNone) return (Let [DefNonRec (makeTDef v yextend)] body) -} case cType toTp of CBox -> return yextend _ -> return $ App (unboxVarAtTp (TFun [(nameNil,TVar tvarB)] typeTotal toTp)) [yextend] where typeYieldExtend = TForall [tvarA,tvarB,tvarE] [] (TFun [(nameNil,TFun [(nameNil,TVar tvarA)] (TVar tvarE) (typeYld (TVar tvarB)))] (TVar tvarE) (typeYld (TVar tvarB))) typeYld tp = tp tvarA,tvarB,tvarE :: TypeVar tvarA = TypeVar 0 kindStar Bound tvarB = TypeVar 1 kindStar Bound tvarE = TypeVar 2 kindEffect Bound -} type BoxType = Type -- type without quantification boxTypeOf :: Expr -> BoxType boxTypeOf expr = -- trace ("boxTypeOf: typeApp: " ++ show expr) $ case splitPredType (typeOf expr) of (_,_,tp) -> tp boxType :: Type -> BoxType boxType tp = case tp of TForall vars preds t -> boxType t -- (subNew [(tv,typeBox (getKind tv)) | tv <- vars] |-> t) TFun pars eff res -> TFun [(name, boxType par) | (name,par) <- pars] (boxType eff) (boxType res) TApp t ts -> TApp (boxType t) [typeBox (getKind t) | t <- ts] TSyn syn args t -> TSyn syn (map boxType args) (boxType t) _ -> tp boxedFunType :: Type -> Unique Type boxedFunType tp = case tp of TForall vars preds t -> boxedFunType t -- (subNew [(tv,typeBox (getKind tv)) | tv <- vars] |-> t) TSyn syn args t -> boxedFunType t TFun pars eff res -> do bpars <- mapM (\_ -> boxedTypeVar) pars bres <- boxedTypeVar return (TFun [(name, bpar) | ((name,_),bpar) <- zip pars bpars] eff bres) _ -> failure $ "Backend.C.Box.boxedFunType: not a function type: " ++ show (pretty tp) boxedTypeVar :: Unique Type boxedTypeVar = do i <- unique return (TVar (TypeVar i kindStar Bound)) typeBox :: Kind -> BoxType typeBox k = TCon (TypeCon nameTpBox k) data CType = CBox | CFun [CType] CType | CData deriving (Eq,Show) cType :: Type -> CType cType tp = case tp of TForall vars preds t -> cType t TFun pars eff res -> CFun (map (cType . snd) pars) (cType res) TApp t ts -> cType t TCon c -> CData TVar v -> CBox TSyn syn args t -> cType t typeBoxStar = typeBox kindStar isBoxPat :: Pattern -> Bool isBoxPat (PatCon{ patConName = name }) = (getName name == nameBoxCon) isBoxPat _ = False patBox :: Type -> Type -> Pattern -> Pattern patBox tpPat tpRes pat = PatCon (TName nameBoxCon (conInfoType boxConInfo)) [pat] boxConRepr [tpPat] [] tpRes boxConInfo True boxConRepr :: ConRepr boxConRepr = ConSingle nameTpBox (DataSingle False) 0 boxConInfo :: ConInfo boxConInfo = ConInfo nameBox nameTpBox [a] [] [(nameNil,TVar a)] tp Inductive rangeNull [] [Public] True Public "" where tp = TForall [a] [] (TFun [(nameNil,TVar a)] typeTotal typeBoxStar) a = TypeVar (0) kindStar Bound uniqueTName nm tp = do n <- uniqueName nm return (TName n tp)
null
https://raw.githubusercontent.com/koka-lang/koka/86b1ee9284b70881e0bc78195d74fcc441986825/src/Backend/C/Box.hs
haskell
--------------------------------------------------------------------------- This is free software; you can redistribute it and/or modify it under the found in the LICENSE file at the root of this distribution. --------------------------------------------------------------------------- ------------------------------------------------------------------------ Box/unbox transformation ------------------------------------------------------------------------ trace ("box def: " ++ show (defName def) ++ ": " ++ show (pretty (defType def)) ++ "\n" ++ show (prettyExpr Pretty.defaultEnv{Pretty.coreShowTypes=True} (defExpr def))) $ simplify the whole def to avoid simplifying away functions to values (e.g. `fun f(x){ g(x) } ~> val f = g`) unsafe ndebug runs duplicationMax add box/unbox such that the type of `expr` matches `BoxType` remove type abstraction and applications Regular isBoxOp (App (Var (TName name _) (InfoExternal _)) [arg]) = (name == newHiddenName ("box") || name == newHiddenName ("unbox")) isBoxOp _ = False add bindings and box/unbox such that pattern matches the required boxtype trace ("pattern coerce: " ++ show (pretty fromTp) ++ " ~> " ++ show (pretty toTp)) $ We just insert a specially named Box pattern bound to fresh variable -- the backend recognizes this and generates unbox/box expressions appropiately so nested patterns are handled correctly Unfortunately, this does not work for function wrappers (as we need to generate a wrapped unbox/box function around it); for those we rename and generate an explicit binding binding; this works as a function type is never pattern matched further. TODO: this may fail if the function is used in a guard test itself where it is not bound yet. we could work around this by substituting explicitly in the guard in that case. function match ok, no nested match regenerate the coercion trace ("unbox function: " ++ show uname ++ ": " ++ show (pretty fromTp) ++ " to " ++ show (pretty toTp) ++ "\n: coerce tp: " ++ show (pretty (typeOf coerce))) $ regular box/unbox trace ("unbox pattern: " ++ show uname ++ ": " ++ show (pretty toTp)) $ toTp for generating correct unbox call in the C backend trace ("pattern: no-coerce: " ++ show (pretty fromTp) ++ " to " ++ show (pretty toTp)) $ cannot happen coerce `expr` of `fromTp` to `toTp` boxed functions need to wrapped to take all arguments and results as boxed as well :-( see test/cgen/box3 and test/cgen/box3a trace ("box to fun: " ++ show expr) $ unwrap function; we must return Just even if no further wrapping was needed trace ("fun to box: " ++ show expr) $ wrap function and box it itselfob coerce between function arguments/results trace ("box coerce fun: " ++ show expr) $ mapM (\(arg,argTp) -> boxExpr argTp arg) (zip args (map snd fromParTps)) trace ("box coerce with yield extension: " ++ show expr) $ ? no need for nice unbox , it will be box_any anyways ... type without quantification trace ("boxTypeOf: typeApp: " ++ show expr) $ (subNew [(tv,typeBox (getKind tv)) | tv <- vars] |-> t) (subNew [(tv,typeBox (getKind tv)) | tv <- vars] |-> t)
Copyright 2020 - 2021 , Microsoft Research , . terms of the Apache License , Version 2.0 . A copy of the License can be module Backend.C.Box ( boxCore ) where import Lib.Trace import Control.Applicative hiding (empty) import Control.Monad import Data.List ( intersperse, partition ) import Data.Char import Data . Maybe import Data . Monoid ( mappend ) import qualified Data.Set as S import Kind.Kind import Kind.Newtypes import Type.Type import Type.TypeVar import Type.Kind( getKind ) import qualified Type.Pretty as Pretty import Lib.PPrint import Common.Name import Common.Range import Common.NamePrim import Common.Failure import Common.Unique import Common.Syntax import Core.Core import Core.Pretty import Core.CoreVar import Core . CTail ( isCTailOp ) import Core.Simplify boxCore :: Core -> Unique Core boxCore core = do defs <- boxDefGroups (coreProgDefs core) return (core{ coreProgDefs = defs }) boxDefGroups :: DefGroups -> Unique DefGroups boxDefGroups dgs = mapM boxDefGroup dgs boxDefGroup :: DefGroup -> Unique DefGroup boxDefGroup dg = case dg of DefRec defs -> fmap DefRec (mapM boxDef defs) DefNonRec def -> fmap DefNonRec (boxDef def) boxDef :: Def -> Unique Def boxDef def do bexpr <- boxExpr (boxType (defType def)) (defExpr def) let bdef = def{ defExpr = bexpr } boxExpr :: BoxType -> Expr -> Unique Expr boxExpr expectTp expr = case expr of TypeLam tvs e -> boxExpr expectTp e TypeApp e tps -> boxExpr expectTp e App e args -> do let argTps = map boxTypeOf args eTp = TFun [(nameNil,tp) | tp <- argTps] typeTotal expectTp bargs <- mapM (\(arg) -> boxExpr (boxTypeOf arg) arg) args bexpr <- boxExpr eTp e return (App bexpr bargs) Lam tparams eff body -> do let funTp = boxTypeOf expr bbody <- boxExpr (boxTypeOf body) body bcoerce funTp (expectTp) (Lam tparams eff bbody) Let defGroups body -> do bdgs <- boxDefGroups defGroups bbody <- boxExpr expectTp body return (Let bdgs bbody) Case exprs branches -> do let exprTps = map boxTypeOf exprs bexprs <- mapM (\(tp,e) -> boxExpr tp e) (zip exprTps exprs) bbranches <- mapM (boxBranch exprTps expectTp) branches return (Case bexprs bbranches) _ -> bcoerce (boxTypeOf expr) expectTp expr boxBranch :: [BoxType] -> BoxType -> Branch -> Unique Branch boxBranch patTps expectTp (Branch patterns guards) = do (bpatterns,defss) <- unzipM $ mapM (\(patTp,pat) -> boxPattern patTp pat) (zip patTps patterns) let binds expr = makeLet [DefNonRec def | def <- concat defss] expr bguards <- mapM (boxGuard expectTp binds) guards return (Branch bpatterns bguards) boxGuard :: BoxType -> (Expr -> Expr) -> Guard -> Unique Guard boxGuard expectTp binds (Guard test expr) =do btest <- boxExpr typeBool test bexpr <- boxExpr expectTp expr TODO : binds come too late to appear in guards but we need binds for function wrappers ? .. perhaps create a specal pattern just for the C backend ? boxPattern :: BoxType -> Pattern -> Unique (Pattern, [Def]) boxPattern fromTp PatWild = boxPatternX fromTp PatWild boxPattern fromTp pat | cType (fromTp) /= cType toTp bcoerceX fromTp toTp (Var (TName nameNil fromTp) InfoNone) case mcoerce of Just coerce0 if (isComplexCoerce coerce0) case pat of PatVar tname PatWild do i <- unique let uname = newHiddenName ("fun-unbox-x" ++ show i) let def = makeTDef (TName (getName tname) toTp) coerce return (PatVar (TName uname fromTp) PatWild, [def]) _ -> failure "Backend/C/FromCore.boxPattern: nested match on a function?" do i <- unique let uname = newHiddenName ("box-x" ++ show i) (bpat,defs) <- boxPatternX toTp pat return (PatVar (TName uname typeBoxStar) (patBox toTp typeBoxStar bpat), defs) boxPatternX fromTp pat where toTp = case pat of PatCon{} -> patTypeRes pat PatVar tname _ -> typeOf tname PatLit lit -> typeOf lit isComplexCoerce coerce = case (cType fromTp, cType toTp) of (CFun{},_) -> True (_,CFun{}) -> True _ -> False boxPattern fromTp pat = boxPatternX fromTp pat boxPatternX :: BoxType -> Pattern -> Unique (Pattern,[Def]) boxPatternX fromTp pat = case pat of PatCon name params repr targs exists tres conInfo skip -> do (bparams,defss) <- unzipM $ mapM (\(ftp,par) -> boxPattern ftp par) (zip (map snd (conInfoParams conInfo)) params) return (PatCon name bparams repr targs exists tres conInfo skip, concat defss) PatVar tname arg -> do (barg,defs) <- boxPattern (typeOf tname) arg return (PatVar tname barg, defs) PatWild -> return (pat,[]) PatLit _ -> return (pat,[]) bcoerce :: Type -> Type -> Expr -> Unique Expr bcoerce fromTp toTp expr = do mb <- bcoerceX fromTp toTp expr case mb of Just expr' -> return expr' Nothing -> return expr bcoerceX :: Type -> Type -> Expr -> Unique (Maybe Expr) bcoerceX fromTp toTp expr = case (cType fromTp, cType toTp) of (CBox, CBox) -> return Nothing (CBox, CData) -> return $ Just $ App (unboxVar) [expr] (CData, CBox) -> return $ Just $ App (boxVar) [expr] (CBox, CFun cpars cres) do boxedToTp <- boxedFunType toTp let unboxed = App (unboxVarAtTp (TFun [(nameNil,fromTp)] typeTotal boxedToTp)) [expr] (CFun cpars cres, CBox) do boxedFromTp <- boxedFunType fromTp (CFun fromPars fromRes, CFun toPars toRes) | not (all (\(t1,t2) -> t1 == t2) (zip fromPars toPars) && fromRes == toRes) -> case splitFunScheme toTp of Just (_,_,toParTps,toEffTp,toResTp) -> case splitFunScheme fromTp of Just (_,_,fromParTps,fromEffTp,fromResTp) -> Just <$> (boxBindExprAsValue fromTp toTp expr $ \vexpr -> boxCoerceFun toParTps toEffTp toResTp fromParTps fromEffTp fromResTp vexpr) _ -> failure $ "Backend.C.Box: bcoerceX: expecting function (from): " ++ show (pretty fromTp) _ -> failure $ "Backend.C.Box: bcoerceX: expecting function (to): " ++ show (pretty toTp) _ -> return Nothing where boxVar = boxVarAtTp coerceTp unboxVar = unboxVarAtTp coerceTp coerceTp = TFun [(nameNil,fromTp)] typeTotal toTp boxVarAtTp tp = Var (TName nameBox tp) (InfoExternal [(C CDefault, "box(#1)")]) unboxVarAtTp tp = Var (TName nameUnbox tp) (InfoExternal [(C CDefault, "unbox(#1)")]) boxCoerceFun :: [(Name,Type)] -> Effect -> Type -> [(Name,Type)] -> Effect -> Type -> Expr -> Unique Expr boxCoerceFun toParTps toEffTp toResTp fromParTps fromEffTp fromResTp expr do names <- mapM (\_ -> uniqueName "b") toParTps let pars = zipWith TName names (map snd toParTps) args = [Var par InfoNone | par <- pars] mapM (\(arg,parToTp,parFromTp) -> bcoerce parToTp parFromTp arg) (zip3 args (map snd toParTps) (map snd fromParTps)) bapp <- bcoerce fromResTp toResTp (App expr bargs) return (Lam pars toEffTp bapp) boxBindExprAsValue :: Type -> Type -> Expr -> (Expr -> Unique Expr) -> Unique Expr boxBindExprAsValue fromTp toTp expr action | isTotal expr = action expr boxBindExprAsValue fromTp toTp expr action do v <- uniqueTName "bv" fromTp body <- action (Var v InfoNone) return (Let [DefNonRec (makeTDef v expr)] body) do yextend < - do vb < - uniqueTName " bb " ( TVar tvarA ) w < - uniqueTName " bw " fromTp x < - uniqueTName " bx " toTp let varVb = Var vb InfoNone varX = Var x InfoNone unboxVb < - bcoerce ( ) ( typeOf w ) varVb boxResX < - bcoerce ( ) ( TVar tvarB ) varX body1 < - action ( Var w InfoNone ) makeYieldExtend ( typeOf vb ) toTp $ [ vb ] typeTotal { - ? do yextend <- do vb <- uniqueTName "bb" (TVar tvarA) w <- uniqueTName "bw" fromTp x <- uniqueTName "bx" toTp let varVb = Var vb InfoNone varX = Var x InfoNone unboxVb <- bcoerce (typeOf vb) (typeOf w) varVb boxResX <- bcoerce (typeOf x) (TVar tvarB) varX body1 <- action (Var w InfoNone) makeYieldExtend (typeOf vb) toTp $ Let [DefNonRec (makeTDef w unboxVb) ,DefNonRec (makeTDef x body1)] boxResX v <- uniqueTName "bv" fromTp body2 <- action (Var v InfoNone) return (Let [DefNonRec (makeTDef v expr)] $ makeIfExpr makeYielding yextend body2 ) where coerceTp = TFun [(nameNil,fromTp)] typeTotal toTp makeYielding :: Expr makeYielding = App (Var (TName nameYielding typeYielding) (InfoExternal [(C,"kk_yielding(kk_context())")])) [] where typeYielding = TFun [] typeTotal typeBool makeYieldExtend :: Type -> Type -> Expr -> Unique Expr makeYieldExtend fromTp toTp expr = do let yextend = App (TypeApp (Var (TName nameYieldExtend typeYieldExtend) (InfoArity 3 1)) [TVar tvarA, TVar tvarB, typeTotal]) [expr] v < - uniqueTName " b " ( TVar tvarB ) body < - bcoerce ( v ) toTp ( Var v InfoNone ) return ( Let [ DefNonRec ( makeTDef v yextend ) ] body ) v <- uniqueTName "b" (TVar tvarB) body <- bcoerce (typeOf v) toTp (Var v InfoNone) return (Let [DefNonRec (makeTDef v yextend)] body) -} case cType toTp of CBox -> return yextend _ -> return $ App (unboxVarAtTp (TFun [(nameNil,TVar tvarB)] typeTotal toTp)) [yextend] where typeYieldExtend = TForall [tvarA,tvarB,tvarE] [] (TFun [(nameNil,TFun [(nameNil,TVar tvarA)] (TVar tvarE) (typeYld (TVar tvarB)))] (TVar tvarE) (typeYld (TVar tvarB))) typeYld tp = tp tvarA,tvarB,tvarE :: TypeVar tvarA = TypeVar 0 kindStar Bound tvarB = TypeVar 1 kindStar Bound tvarE = TypeVar 2 kindEffect Bound -} type BoxType = Type boxTypeOf :: Expr -> BoxType boxTypeOf expr case splitPredType (typeOf expr) of (_,_,tp) -> tp boxType :: Type -> BoxType boxType tp = case tp of TForall vars preds t TFun pars eff res -> TFun [(name, boxType par) | (name,par) <- pars] (boxType eff) (boxType res) TApp t ts -> TApp (boxType t) [typeBox (getKind t) | t <- ts] TSyn syn args t -> TSyn syn (map boxType args) (boxType t) _ -> tp boxedFunType :: Type -> Unique Type boxedFunType tp = case tp of TForall vars preds t TSyn syn args t -> boxedFunType t TFun pars eff res -> do bpars <- mapM (\_ -> boxedTypeVar) pars bres <- boxedTypeVar return (TFun [(name, bpar) | ((name,_),bpar) <- zip pars bpars] eff bres) _ -> failure $ "Backend.C.Box.boxedFunType: not a function type: " ++ show (pretty tp) boxedTypeVar :: Unique Type boxedTypeVar = do i <- unique return (TVar (TypeVar i kindStar Bound)) typeBox :: Kind -> BoxType typeBox k = TCon (TypeCon nameTpBox k) data CType = CBox | CFun [CType] CType | CData deriving (Eq,Show) cType :: Type -> CType cType tp = case tp of TForall vars preds t -> cType t TFun pars eff res -> CFun (map (cType . snd) pars) (cType res) TApp t ts -> cType t TCon c -> CData TVar v -> CBox TSyn syn args t -> cType t typeBoxStar = typeBox kindStar isBoxPat :: Pattern -> Bool isBoxPat (PatCon{ patConName = name }) = (getName name == nameBoxCon) isBoxPat _ = False patBox :: Type -> Type -> Pattern -> Pattern patBox tpPat tpRes pat = PatCon (TName nameBoxCon (conInfoType boxConInfo)) [pat] boxConRepr [tpPat] [] tpRes boxConInfo True boxConRepr :: ConRepr boxConRepr = ConSingle nameTpBox (DataSingle False) 0 boxConInfo :: ConInfo boxConInfo = ConInfo nameBox nameTpBox [a] [] [(nameNil,TVar a)] tp Inductive rangeNull [] [Public] True Public "" where tp = TForall [a] [] (TFun [(nameNil,TVar a)] typeTotal typeBoxStar) a = TypeVar (0) kindStar Bound uniqueTName nm tp = do n <- uniqueName nm return (TName n tp)
584cfbe53b1088a55b5f170a3c3c47d7088fd8d59a9802e7accd68b7ceb64529
lagenorhynque/duct.module.pedestal
pedestal_test.clj
(ns duct.module.pedestal-test (:require [clojure.test :as t] [duct.core :as duct] [duct.module.pedestal :as sut])) (duct/load-hierarchy) (t/deftest module-test (let [base-config {:duct.profile/base {:duct.core/project-ns 'some-api} :duct.profile/prod {} :duct.profile/dev {} :duct.profile/test {} :duct.module/pedestal {}}] (t/testing "environment: production" (t/testing "no options" (let [config base-config] (t/is (= {:duct.core/project-ns 'some-api :duct.core/environment :production :duct.server/pedestal {:base-service sut/prod-service :default? true :dev? false}} (duct/prep-config config [:duct.profile/prod]))))) (t/testing "options specified" (let [service-map #:io.pedestal.http{:routes #{} :port 8888} config (duct/merge-configs base-config {:duct.profile/base {:duct.server/pedestal {:service service-map}} :duct.module/pedestal {:default? false :dev? true}})] (t/is (= {:duct.core/project-ns 'some-api :duct.core/environment :production :duct.server/pedestal {:service service-map :base-service sut/prod-service :default? false :dev? true}} (duct/prep-config config [:duct.profile/prod])))))) (t/testing "environment: development" (t/testing "no options" (let [config base-config] (t/is (= {:duct.core/project-ns 'some-api :duct.core/environment :development :duct.server/pedestal {:base-service sut/dev-service :default? true :dev? true}} (duct/prep-config config [:duct.profile/dev]))))) (t/testing "options specified" (let [service-map #:io.pedestal.http{:routes #{} :port 8888} config (duct/merge-configs base-config {:duct.profile/base {:duct.server/pedestal {:service service-map}} :duct.module/pedestal {:default? false :dev? false}})] (t/is (= {:duct.core/project-ns 'some-api :duct.core/environment :development :duct.server/pedestal {:service service-map :base-service sut/dev-service :default? false :dev? false}} (duct/prep-config config [:duct.profile/dev])))))) (t/testing "environment: test" (t/testing "no options" (let [config base-config] (t/is (= {:duct.core/project-ns 'some-api :duct.core/environment :test :duct.server/pedestal {:base-service sut/dev-service :default? true :dev? true}} (duct/prep-config config [:duct.profile/test]))))) (t/testing "options specified" (let [service-map #:io.pedestal.http{:routes #{} :port 8888} config (duct/merge-configs base-config {:duct.profile/base {:duct.server/pedestal {:service service-map}} :duct.module/pedestal {:default? false :dev? false}})] (t/is (= {:duct.core/project-ns 'some-api :duct.core/environment :test :duct.server/pedestal {:service service-map :base-service sut/dev-service :default? false :dev? false}} (duct/prep-config config [:duct.profile/test]))))))))
null
https://raw.githubusercontent.com/lagenorhynque/duct.module.pedestal/28a3f3c98b922294cb42c8589079eabba743552d/test/duct/module/pedestal_test.clj
clojure
(ns duct.module.pedestal-test (:require [clojure.test :as t] [duct.core :as duct] [duct.module.pedestal :as sut])) (duct/load-hierarchy) (t/deftest module-test (let [base-config {:duct.profile/base {:duct.core/project-ns 'some-api} :duct.profile/prod {} :duct.profile/dev {} :duct.profile/test {} :duct.module/pedestal {}}] (t/testing "environment: production" (t/testing "no options" (let [config base-config] (t/is (= {:duct.core/project-ns 'some-api :duct.core/environment :production :duct.server/pedestal {:base-service sut/prod-service :default? true :dev? false}} (duct/prep-config config [:duct.profile/prod]))))) (t/testing "options specified" (let [service-map #:io.pedestal.http{:routes #{} :port 8888} config (duct/merge-configs base-config {:duct.profile/base {:duct.server/pedestal {:service service-map}} :duct.module/pedestal {:default? false :dev? true}})] (t/is (= {:duct.core/project-ns 'some-api :duct.core/environment :production :duct.server/pedestal {:service service-map :base-service sut/prod-service :default? false :dev? true}} (duct/prep-config config [:duct.profile/prod])))))) (t/testing "environment: development" (t/testing "no options" (let [config base-config] (t/is (= {:duct.core/project-ns 'some-api :duct.core/environment :development :duct.server/pedestal {:base-service sut/dev-service :default? true :dev? true}} (duct/prep-config config [:duct.profile/dev]))))) (t/testing "options specified" (let [service-map #:io.pedestal.http{:routes #{} :port 8888} config (duct/merge-configs base-config {:duct.profile/base {:duct.server/pedestal {:service service-map}} :duct.module/pedestal {:default? false :dev? false}})] (t/is (= {:duct.core/project-ns 'some-api :duct.core/environment :development :duct.server/pedestal {:service service-map :base-service sut/dev-service :default? false :dev? false}} (duct/prep-config config [:duct.profile/dev])))))) (t/testing "environment: test" (t/testing "no options" (let [config base-config] (t/is (= {:duct.core/project-ns 'some-api :duct.core/environment :test :duct.server/pedestal {:base-service sut/dev-service :default? true :dev? true}} (duct/prep-config config [:duct.profile/test]))))) (t/testing "options specified" (let [service-map #:io.pedestal.http{:routes #{} :port 8888} config (duct/merge-configs base-config {:duct.profile/base {:duct.server/pedestal {:service service-map}} :duct.module/pedestal {:default? false :dev? false}})] (t/is (= {:duct.core/project-ns 'some-api :duct.core/environment :test :duct.server/pedestal {:service service-map :base-service sut/dev-service :default? false :dev? false}} (duct/prep-config config [:duct.profile/test]))))))))
29897813c886858548259fb5c7147594918203bd483b6b6f6c875f8ee3580bc6
ruricolist/serapeum
box.lisp
(in-package #:serapeum) (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant +atomic-accessors+ (and (member :ecl *features*) (ignore-errors (eval `(defstruct (,(gensym) :atomic-accessors)))) '(:atomic-accessors)))) (declaim (inline box)) ;Allow dynamic-extent. (defstruct (box (:constructor box (unbox)) (:predicate boxp) (:conc-name nil) ;; Required for older ECLs only. . #.+atomic-accessors+) "A box is just a mutable cell. You create a box using `box' and get and set its value using the accessor `unbox'. (def a-box (box t)) (unbox a-box) => t (setf (unbox a-box) nil) (unbox a-box) => nil Serapeum attempts to provide the guarantee that, on Lisps that support atomic operations (compare-and-swap), `unbox` on boxes should be updateable atomically. (See [atomics]()). At the moment, boxes are implemented as structures, but that may change. In particular, you should not depend on being able to recognize boxes using a type or predicate." unbox) (declaim-freeze-type box) (setf (documentation 'box 'function) "Box a value.") (setf (documentation 'unbox 'function) "The value in the box X." (documentation '(setf unbox) 'function) "Put VALUE in box X.") (defmethod print-object ((self box) stream) (print-unreadable-object (self stream :type t :identity t) (format stream "~a" (unbox self))) self) (defmethod make-load-form ((self box) &optional env) (declare (ignore env)) (values `(box) `(setf (unbox ',self) ,(unbox self)))) (defpattern box (x) (with-unique-names (b) `(trivia:guard1 ,b (typep ,b 'box) (unbox ,b) ,x)))
null
https://raw.githubusercontent.com/ruricolist/serapeum/c3bc9566a381a2a6ce9ba75deef3933abe54c323/box.lisp
lisp
Allow dynamic-extent. Required for older ECLs only.
(in-package #:serapeum) (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant +atomic-accessors+ (and (member :ecl *features*) (ignore-errors (eval `(defstruct (,(gensym) :atomic-accessors)))) '(:atomic-accessors)))) (defstruct (box (:constructor box (unbox)) (:predicate boxp) (:conc-name nil) . #.+atomic-accessors+) "A box is just a mutable cell. You create a box using `box' and get and set its value using the accessor `unbox'. (def a-box (box t)) (unbox a-box) => t (setf (unbox a-box) nil) (unbox a-box) => nil Serapeum attempts to provide the guarantee that, on Lisps that support atomic operations (compare-and-swap), `unbox` on boxes should be updateable atomically. (See [atomics]()). At the moment, boxes are implemented as structures, but that may change. In particular, you should not depend on being able to recognize boxes using a type or predicate." unbox) (declaim-freeze-type box) (setf (documentation 'box 'function) "Box a value.") (setf (documentation 'unbox 'function) "The value in the box X." (documentation '(setf unbox) 'function) "Put VALUE in box X.") (defmethod print-object ((self box) stream) (print-unreadable-object (self stream :type t :identity t) (format stream "~a" (unbox self))) self) (defmethod make-load-form ((self box) &optional env) (declare (ignore env)) (values `(box) `(setf (unbox ',self) ,(unbox self)))) (defpattern box (x) (with-unique-names (b) `(trivia:guard1 ,b (typep ,b 'box) (unbox ,b) ,x)))
56e8bca06e3afdf293f6a5e5c8a5ca98825b912eb992f05db41e6cbe72c7b52b
rrnewton/haskell-lockfree
Test.hs
# LANGUAGE BangPatterns , NamedFieldPuns # {- Example build: ghc --make Test.hs -o Test.exe -rtsopts -fforce-recomp -} module Main where import Test.HUnit as HU import Data.Concurrent.Deque.Tests import Data.Concurrent.Deque.Class import Data.Concurrent.MegaDeque () -- Instances. main :: IO () main = stdTestHarness $ return all_tests where all_tests :: HU.Test all_tests = TestList $ [ TestLabel "WSDeque" $ tests_wsqueue (newQ :: IO (WSDeque a)) , TestLabel "TS_Queue" $ tests_fifo (newQ :: IO (ConcQueue a)) , TestLabel "NT_Queue" $ tests_fifo (newQ :: IO (Queue a)) , TestLabel "Full_TS_Deque" $ tests_all (newQ :: IO (ConcDeque a)) -- , TestLabel "Maxed" $ tests_all (newQ :: IO (Deque T T D D Grow Safe)) ]
null
https://raw.githubusercontent.com/rrnewton/haskell-lockfree/87122157cbbc96954fcc575b4b110003d3e5c2f8/mega-deque/tests/Test.hs
haskell
Example build: ghc --make Test.hs -o Test.exe -rtsopts -fforce-recomp Instances. , TestLabel "Maxed" $ tests_all (newQ :: IO (Deque T T D D Grow Safe))
# LANGUAGE BangPatterns , NamedFieldPuns # module Main where import Test.HUnit as HU import Data.Concurrent.Deque.Tests import Data.Concurrent.Deque.Class main :: IO () main = stdTestHarness $ return all_tests where all_tests :: HU.Test all_tests = TestList $ [ TestLabel "WSDeque" $ tests_wsqueue (newQ :: IO (WSDeque a)) , TestLabel "TS_Queue" $ tests_fifo (newQ :: IO (ConcQueue a)) , TestLabel "NT_Queue" $ tests_fifo (newQ :: IO (Queue a)) , TestLabel "Full_TS_Deque" $ tests_all (newQ :: IO (ConcDeque a)) ]
4745c7840cab97a23ec000438169203cc1898f34ccd8a6ab91b3f39b7483f31a
phylogeography/spread
logging.cljs
(ns ui.logging (:require [mount.core :as mount :refer [defstate]] [taoensso.timbre :as timbre])) (declare logging) (def ^:private timbre->devtools-level {:fatal js/console.error :error js/console.error :warn js/console.warn :info js/console.info :debug js/console.info :trace js/console.trace}) (defn error? [x] (instance? js/Error x)) (def devtools-appender "Simple js/console appender which avoids pr-str and uses cljs-devtools to format output" {:enabled? true :async? false :min-level nil :rate-limit nil :output-fn nil :fn (fn [data] (let [{:keys [level ?ns-str ?line vargs_]} data vargs (list* (str ?ns-str ":" ?line) (force vargs_)) f (timbre->devtools-level level js/console.log)] (.apply f js/console (to-array vargs))))}) (defn- decode-vargs [vargs] (reduce (fn [m arg] (assoc m (cond (qualified-keyword? arg) :log-ns (string? arg) :message (map? arg) :meta) arg)) {} vargs)) (defn wrap-decode-vargs "Middleware for vargs" [data] (merge data (decode-vargs (-> data :vargs)))) (defn start [{:keys [level console?]}] (timbre/merge-config! {:level (keyword level) :middleware [wrap-decode-vargs] :appenders {:console (when console? devtools-appender)}})) (defstate logging :start (start (:logging (mount/args))))
null
https://raw.githubusercontent.com/phylogeography/spread/56f3500e6d83e0ebd50041dc336ffa0697d7baf8/src/cljs/ui/logging.cljs
clojure
(ns ui.logging (:require [mount.core :as mount :refer [defstate]] [taoensso.timbre :as timbre])) (declare logging) (def ^:private timbre->devtools-level {:fatal js/console.error :error js/console.error :warn js/console.warn :info js/console.info :debug js/console.info :trace js/console.trace}) (defn error? [x] (instance? js/Error x)) (def devtools-appender "Simple js/console appender which avoids pr-str and uses cljs-devtools to format output" {:enabled? true :async? false :min-level nil :rate-limit nil :output-fn nil :fn (fn [data] (let [{:keys [level ?ns-str ?line vargs_]} data vargs (list* (str ?ns-str ":" ?line) (force vargs_)) f (timbre->devtools-level level js/console.log)] (.apply f js/console (to-array vargs))))}) (defn- decode-vargs [vargs] (reduce (fn [m arg] (assoc m (cond (qualified-keyword? arg) :log-ns (string? arg) :message (map? arg) :meta) arg)) {} vargs)) (defn wrap-decode-vargs "Middleware for vargs" [data] (merge data (decode-vargs (-> data :vargs)))) (defn start [{:keys [level console?]}] (timbre/merge-config! {:level (keyword level) :middleware [wrap-decode-vargs] :appenders {:console (when console? devtools-appender)}})) (defstate logging :start (start (:logging (mount/args))))
9086c26941e62ef5a7206274d7fb7f3f7698b22cca0ed66fd3851b229b0d2d72
developandplay/material-components-web-miso
Radio.hs
{-# LANGUAGE OverloadedStrings #-} module Material.Radio ( Config, config, setOnChange, setChecked, setDisabled, setTouch, setAttributes, radio, ) where import qualified Data.Maybe as Maybe import qualified Miso -- | Radio button configuration data Config msg = Config { checked :: Bool, disabled :: Bool, additionalAttributes :: [Miso.Attribute msg], onChange :: Maybe msg, touch :: Bool } -- | Default radio button configuration config :: Config msg config = Config { checked = False, disabled = False, additionalAttributes = [], onChange = Nothing, touch = True } -- | Specify whether a radio button is checked setChecked :: Bool -> Config msg -> Config msg setChecked checked config_ = config_ {checked = checked} -- | Specify whether a radio button is disabled -- Disabled radio buttons cannot be interacted with and have no visual interaction -- effect. setDisabled :: Bool -> Config msg -> Config msg setDisabled disabled config_ = config_ {disabled = disabled} -- | Specify additional attributes setAttributes :: [Miso.Attribute msg] -> Config msg -> Config msg setAttributes additionalAttributes config_ = config_ {additionalAttributes = additionalAttributes} -- | Specify a message when the user changes a radio setOnChange :: msg -> Config msg -> Config msg setOnChange onChange config_ = config_ {onChange = Just onChange} -- | Specify whether touch support is enabled (enabled by default) -- Touch support is an accessibility guideline that states that touch targets should be at least 48 x 48 pixels in size . Use this configuration option to -- disable increased touch target size. -- **Note:** Radios with touch support will be wrapped in a HTML div element to -- prevent potentially overlapping touch targets on adjacent elements. setTouch :: Bool -> Config msg -> Config msg setTouch touch config_ = config_ {touch = touch} -- | Radio button view function radio :: Config msg -> Miso.View msg radio (config_@Config {touch = touch, additionalAttributes = additionalAttributes}) = let wrapTouch node = if touch then Miso.div_ [Miso.class_ "mdc-touch-target-wrapper"] [node] else node in wrapTouch $ Miso.nodeHtml "mdc-radio" ( Maybe.mapMaybe id [ rootCs, touchCs config_, checkedProp config_, disabledProp config_ ] ++ additionalAttributes ) [ nativeControlElt config_, backgroundElt, rippleElt ] rootCs :: Maybe (Miso.Attribute msg) rootCs = Just (Miso.class_ "mdc-radio") touchCs :: Config msg -> Maybe (Miso.Attribute msg) touchCs (Config {touch = touch}) = if touch then Just (Miso.class_ "mdc-radio--touch") else Nothing checkedProp :: Config msg -> Maybe (Miso.Attribute msg) checkedProp (Config {checked = checked}) = Just (Miso.boolProp "checked" checked) disabledProp :: Config msg -> Maybe (Miso.Attribute msg) disabledProp (Config {disabled = disabled}) = Just (Miso.boolProp "disabled" disabled) changeHandler :: Config msg -> Maybe (Miso.Attribute msg) changeHandler (Config {checked = checked, onChange = onChange}) = Maybe.maybe Nothing (\x -> Just (Miso.on "change" Miso.emptyDecoder (const x))) onChange nativeControlElt :: Config msg -> Miso.View msg nativeControlElt config_ = Miso.input_ ( Maybe.mapMaybe id [ nativeControlCs, radioTypeAttr, checkedProp config_, changeHandler config_ ] ) nativeControlCs :: Maybe (Miso.Attribute msg) nativeControlCs = Just (Miso.class_ "mdc-radio__native-control") radioTypeAttr :: Maybe (Miso.Attribute msg) radioTypeAttr = Just (Miso.type_ "radio") backgroundElt :: Miso.View msg backgroundElt = Miso.div_ [Miso.class_ "mdc-radio__background"] [outerCircleElt, innerCircleElt] outerCircleElt :: Miso.View msg outerCircleElt = Miso.div_ [Miso.class_ "mdc-radio__outer-circle"] [] innerCircleElt :: Miso.View msg innerCircleElt = Miso.div_ [Miso.class_ "mdc-radio__inner-circle"] [] rippleElt :: Miso.View msg rippleElt = Miso.div_ [Miso.class_ "mdc-radio__ripple"] []
null
https://raw.githubusercontent.com/developandplay/material-components-web-miso/97a20097bf522b62743c884b66757eb895edd690/sample-app-jsaddle/Material/Radio.hs
haskell
# LANGUAGE OverloadedStrings # | Radio button configuration | Default radio button configuration | Specify whether a radio button is checked | Specify whether a radio button is disabled Disabled radio buttons cannot be interacted with and have no visual interaction effect. | Specify additional attributes | Specify a message when the user changes a radio | Specify whether touch support is enabled (enabled by default) Touch support is an accessibility guideline that states that touch targets disable increased touch target size. **Note:** Radios with touch support will be wrapped in a HTML div element to prevent potentially overlapping touch targets on adjacent elements. | Radio button view function
module Material.Radio ( Config, config, setOnChange, setChecked, setDisabled, setTouch, setAttributes, radio, ) where import qualified Data.Maybe as Maybe import qualified Miso data Config msg = Config { checked :: Bool, disabled :: Bool, additionalAttributes :: [Miso.Attribute msg], onChange :: Maybe msg, touch :: Bool } config :: Config msg config = Config { checked = False, disabled = False, additionalAttributes = [], onChange = Nothing, touch = True } setChecked :: Bool -> Config msg -> Config msg setChecked checked config_ = config_ {checked = checked} setDisabled :: Bool -> Config msg -> Config msg setDisabled disabled config_ = config_ {disabled = disabled} setAttributes :: [Miso.Attribute msg] -> Config msg -> Config msg setAttributes additionalAttributes config_ = config_ {additionalAttributes = additionalAttributes} setOnChange :: msg -> Config msg -> Config msg setOnChange onChange config_ = config_ {onChange = Just onChange} should be at least 48 x 48 pixels in size . Use this configuration option to setTouch :: Bool -> Config msg -> Config msg setTouch touch config_ = config_ {touch = touch} radio :: Config msg -> Miso.View msg radio (config_@Config {touch = touch, additionalAttributes = additionalAttributes}) = let wrapTouch node = if touch then Miso.div_ [Miso.class_ "mdc-touch-target-wrapper"] [node] else node in wrapTouch $ Miso.nodeHtml "mdc-radio" ( Maybe.mapMaybe id [ rootCs, touchCs config_, checkedProp config_, disabledProp config_ ] ++ additionalAttributes ) [ nativeControlElt config_, backgroundElt, rippleElt ] rootCs :: Maybe (Miso.Attribute msg) rootCs = Just (Miso.class_ "mdc-radio") touchCs :: Config msg -> Maybe (Miso.Attribute msg) touchCs (Config {touch = touch}) = if touch then Just (Miso.class_ "mdc-radio--touch") else Nothing checkedProp :: Config msg -> Maybe (Miso.Attribute msg) checkedProp (Config {checked = checked}) = Just (Miso.boolProp "checked" checked) disabledProp :: Config msg -> Maybe (Miso.Attribute msg) disabledProp (Config {disabled = disabled}) = Just (Miso.boolProp "disabled" disabled) changeHandler :: Config msg -> Maybe (Miso.Attribute msg) changeHandler (Config {checked = checked, onChange = onChange}) = Maybe.maybe Nothing (\x -> Just (Miso.on "change" Miso.emptyDecoder (const x))) onChange nativeControlElt :: Config msg -> Miso.View msg nativeControlElt config_ = Miso.input_ ( Maybe.mapMaybe id [ nativeControlCs, radioTypeAttr, checkedProp config_, changeHandler config_ ] ) nativeControlCs :: Maybe (Miso.Attribute msg) nativeControlCs = Just (Miso.class_ "mdc-radio__native-control") radioTypeAttr :: Maybe (Miso.Attribute msg) radioTypeAttr = Just (Miso.type_ "radio") backgroundElt :: Miso.View msg backgroundElt = Miso.div_ [Miso.class_ "mdc-radio__background"] [outerCircleElt, innerCircleElt] outerCircleElt :: Miso.View msg outerCircleElt = Miso.div_ [Miso.class_ "mdc-radio__outer-circle"] [] innerCircleElt :: Miso.View msg innerCircleElt = Miso.div_ [Miso.class_ "mdc-radio__inner-circle"] [] rippleElt :: Miso.View msg rippleElt = Miso.div_ [Miso.class_ "mdc-radio__ripple"] []
d95d638e052d40d593c418433db73c528b289ae43147811757d5f6ac7c680558
Ferada/cl-mock
suite.lisp
(in-package #:cl-mock-tests) (def-suite cl-mock)
null
https://raw.githubusercontent.com/Ferada/cl-mock/714a4122970d836e65a5a33f6bf6c6d99116325c/tests/suite.lisp
lisp
(in-package #:cl-mock-tests) (def-suite cl-mock)
5bb7331eb10a5a0bf21916563091907527df82aa7218376f316fbcf6a32f2002
helium/miner
miner_critical_sup.erl
%%%------------------------------------------------------------------- %% @doc miner Supervisor %% @end %%%------------------------------------------------------------------- -module(miner_critical_sup). -behaviour(supervisor). %% API -export([start_link/0]). %% Supervisor callbacks -export([init/1]). -define(SUP(I, Args), #{ id => I, start => {I, start_link, Args}, restart => permanent, shutdown => infinity, type => supervisor, modules => [I] }). -define(WORKER(I, Args), #{ id => I, start => {I, start_link, Args}, restart => permanent, shutdown => 15000, type => worker, modules => [I] }). %% ------------------------------------------------------------------ %% API functions %% ------------------------------------------------------------------ start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, [[]]). %% ------------------------------------------------------------------ %% Supervisor callbacks %% ------------------------------------------------------------------ init(_Opts) -> SupFlags = #{ strategy => rest_for_one, intensity => 0, period => 1 }, #{ pubkey := PublicKey, key_slot := KeySlot, ecdh_fun := ECDHFun, bus := Bus, address := Address, sig_fun := SigFun } = miner_keys:keys(), %% Blockchain Supervisor Options SeedNodes = case application:get_env(blockchain, seed_nodes) of {ok, ""} -> []; {ok, Seeds} -> string:split(Seeds, ",", all); _ -> [] end, SeedNodeDNS = application:get_env(blockchain, seed_node_dns, []), look up the DNS record and add any resulting addresses to the SeedNodes % no need to do any checks here as any bad combination results in an empty list SeedAddresses = string:tokens(lists:flatten([string:prefix(X, "blockchain-seed-nodes=") || [X] <- inet_res:lookup(SeedNodeDNS, in, txt), string:prefix(X, "blockchain-seed-nodes=") /= nomatch]), ","), Port = application:get_env(blockchain, port, 0), NumConsensusMembers = application:get_env(blockchain, num_consensus_members, 4), BaseDir = application:get_env(blockchain, base_dir, "data"), %% TODO: Remove when cuttlefish MaxInboundConnections = application:get_env(blockchain, max_inbound_connections, 10), %% if POCs are over grpc and we are a gateway then dont start the chain GatewaysRunChain = application:get_env(miner, gateways_run_chain, true), MinerMode = application:get_env(miner, mode, gateway), case {MinerMode, GatewaysRunChain} of {gateway, false} -> lager:info("grpc gateway, not loading chain"), application:set_env(blockchain, autoload, false), case application:get_env(miner, gateway_and_mux_enable) of {ok, true} -> %% non muxing hotspots still need p2p application:set_env(blockchain, outbound_gossip_connections, 0), application:set_env(blockchain, seednode_connections, 0), application:set_env(blockchain, max_inbound_connections, 0), ok; _ -> ok end; _ -> ok end, BlockchainOpts = [ {key, {PublicKey, SigFun, ECDHFun}}, {seed_nodes, SeedNodes ++ SeedAddresses}, {max_inbound_connections, MaxInboundConnections}, {port, Port}, {num_consensus_members, NumConsensusMembers}, {base_dir, BaseDir}, {update_dir, application:get_env(miner, update_dir, undefined)}, {group_delete_predicate, fun miner_consensus_mgr:group_predicate/1} ], ConsensusMgr = case application:get_env(blockchain, follow_mode, false) of false -> [?WORKER(miner_consensus_mgr, [ignored])]; _ -> [] end, ChildSpecs0 = [?SUP(blockchain_sup, [BlockchainOpts])] ++ ConsensusMgr, GatewayAndMux = case application:get_env(miner, gateway_and_mux_enable) of {ok, true} -> true; _ -> false end, ChildSpecs = case {GatewayAndMux, application:get_env(blockchain, key)} of {false, {ok, {ecc, _}}} -> [ Miner retains full control and responsibility for key access ?WORKER(miner_ecc_worker, [KeySlot, Bus, Address]) ] ++ ChildSpecs0; _ -> ChildSpecs0 end, {ok, {SupFlags, ChildSpecs}}.
null
https://raw.githubusercontent.com/helium/miner/0b1e3c93f595c7c929038814026efd59af3e28ec/src/miner_critical_sup.erl
erlang
------------------------------------------------------------------- @doc miner Supervisor @end ------------------------------------------------------------------- API Supervisor callbacks ------------------------------------------------------------------ API functions ------------------------------------------------------------------ ------------------------------------------------------------------ Supervisor callbacks ------------------------------------------------------------------ Blockchain Supervisor Options no need to do any checks here as any bad combination results in an empty list TODO: Remove when cuttlefish if POCs are over grpc and we are a gateway then dont start the chain non muxing hotspots still need p2p
-module(miner_critical_sup). -behaviour(supervisor). -export([start_link/0]). -export([init/1]). -define(SUP(I, Args), #{ id => I, start => {I, start_link, Args}, restart => permanent, shutdown => infinity, type => supervisor, modules => [I] }). -define(WORKER(I, Args), #{ id => I, start => {I, start_link, Args}, restart => permanent, shutdown => 15000, type => worker, modules => [I] }). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, [[]]). init(_Opts) -> SupFlags = #{ strategy => rest_for_one, intensity => 0, period => 1 }, #{ pubkey := PublicKey, key_slot := KeySlot, ecdh_fun := ECDHFun, bus := Bus, address := Address, sig_fun := SigFun } = miner_keys:keys(), SeedNodes = case application:get_env(blockchain, seed_nodes) of {ok, ""} -> []; {ok, Seeds} -> string:split(Seeds, ",", all); _ -> [] end, SeedNodeDNS = application:get_env(blockchain, seed_node_dns, []), look up the DNS record and add any resulting addresses to the SeedNodes SeedAddresses = string:tokens(lists:flatten([string:prefix(X, "blockchain-seed-nodes=") || [X] <- inet_res:lookup(SeedNodeDNS, in, txt), string:prefix(X, "blockchain-seed-nodes=") /= nomatch]), ","), Port = application:get_env(blockchain, port, 0), NumConsensusMembers = application:get_env(blockchain, num_consensus_members, 4), BaseDir = application:get_env(blockchain, base_dir, "data"), MaxInboundConnections = application:get_env(blockchain, max_inbound_connections, 10), GatewaysRunChain = application:get_env(miner, gateways_run_chain, true), MinerMode = application:get_env(miner, mode, gateway), case {MinerMode, GatewaysRunChain} of {gateway, false} -> lager:info("grpc gateway, not loading chain"), application:set_env(blockchain, autoload, false), case application:get_env(miner, gateway_and_mux_enable) of {ok, true} -> application:set_env(blockchain, outbound_gossip_connections, 0), application:set_env(blockchain, seednode_connections, 0), application:set_env(blockchain, max_inbound_connections, 0), ok; _ -> ok end; _ -> ok end, BlockchainOpts = [ {key, {PublicKey, SigFun, ECDHFun}}, {seed_nodes, SeedNodes ++ SeedAddresses}, {max_inbound_connections, MaxInboundConnections}, {port, Port}, {num_consensus_members, NumConsensusMembers}, {base_dir, BaseDir}, {update_dir, application:get_env(miner, update_dir, undefined)}, {group_delete_predicate, fun miner_consensus_mgr:group_predicate/1} ], ConsensusMgr = case application:get_env(blockchain, follow_mode, false) of false -> [?WORKER(miner_consensus_mgr, [ignored])]; _ -> [] end, ChildSpecs0 = [?SUP(blockchain_sup, [BlockchainOpts])] ++ ConsensusMgr, GatewayAndMux = case application:get_env(miner, gateway_and_mux_enable) of {ok, true} -> true; _ -> false end, ChildSpecs = case {GatewayAndMux, application:get_env(blockchain, key)} of {false, {ok, {ecc, _}}} -> [ Miner retains full control and responsibility for key access ?WORKER(miner_ecc_worker, [KeySlot, Bus, Address]) ] ++ ChildSpecs0; _ -> ChildSpecs0 end, {ok, {SupFlags, ChildSpecs}}.
075770db405ca1dc71824b0f0b88478f19794a10077f85ce3dc920cb7afab1e3
SamB/coq
libobject.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) (*i $Id$ i*) (*i*) open Names open Libnames open Mod_subst (*i*) [ ] declares persistent objects , given with methods : * a caching function specifying how to add the object in the current scope ; If the object wishes to register its visibility in the Nametab , it should do so for all possible sufixes . * a loading function , specifying what to do when the module containing the object is loaded ; If the object wishes to register its visibility in the Nametab , it should do so for all sufixes no shorter then the " int " argument * an opening function , specifying what to do when the module containing the object is opened ( imported ) ; If the object wishes to register its visibility in the Nametab , it should do so for the sufix of the length the " int " argument * a classification function , specyfying what to do with the object , when the current module ( containing the object ) is ended ; The possibilities are : Dispose - the object dies at the end of the module Substitue - meaning the object is substitutive and the module name must be updated Keep - the object is not substitutive , but survives module closing Anticipate - this is for objects which have to be explicitely managed by the [ end_module ] function ( like Require and Read markers ) The classification function is also an occasion for a cleanup ( if this function returns Keep or Substitute of some object , the cache method is never called for it ) * a substitution function , performing the substitution ; this function should be declared for substitutive objects only ( see obove ) * a discharge function , that is applied at section closing time to collect the data necessary to rebuild the discharged form of the non volatile objects * a rebuild function , that is applied after section closing to rebuild the non volatile content of a section from the data collected by the discharge function * an export function , to enable optional writing of its contents to disk ( .vo ) . This function is also the oportunity to remove redundant information in order to keep .vo size small The export function is a little obsolete and will be removed in the near future ... * a caching function specifying how to add the object in the current scope; If the object wishes to register its visibility in the Nametab, it should do so for all possible sufixes. * a loading function, specifying what to do when the module containing the object is loaded; If the object wishes to register its visibility in the Nametab, it should do so for all sufixes no shorter then the "int" argument * an opening function, specifying what to do when the module containing the object is opened (imported); If the object wishes to register its visibility in the Nametab, it should do so for the sufix of the length the "int" argument * a classification function, specyfying what to do with the object, when the current module (containing the object) is ended; The possibilities are: Dispose - the object dies at the end of the module Substitue - meaning the object is substitutive and the module name must be updated Keep - the object is not substitutive, but survives module closing Anticipate - this is for objects which have to be explicitely managed by the [end_module] function (like Require and Read markers) The classification function is also an occasion for a cleanup (if this function returns Keep or Substitute of some object, the cache method is never called for it) * a substitution function, performing the substitution; this function should be declared for substitutive objects only (see obove) * a discharge function, that is applied at section closing time to collect the data necessary to rebuild the discharged form of the non volatile objects * a rebuild function, that is applied after section closing to rebuild the non volatile content of a section from the data collected by the discharge function * an export function, to enable optional writing of its contents to disk (.vo). This function is also the oportunity to remove redundant information in order to keep .vo size small The export function is a little obsolete and will be removed in the near future... *) type 'a substitutivity = Dispose | Substitute of 'a | Keep of 'a | Anticipate of 'a type discharge_info = (identifier * bool * bool) list type 'a object_declaration = { object_name : string; cache_function : object_name * 'a -> unit; load_function : int -> object_name * 'a -> unit; open_function : int -> object_name * 'a -> unit; classify_function : object_name * 'a -> 'a substitutivity; subst_function : object_name * substitution * 'a -> 'a; discharge_function : object_name * 'a -> 'a option; rebuild_function : discharge_info * 'a -> 'a; export_function : 'a -> 'a option } The default object is a " Keep " object with empty methods . Object creators are advised to use the construction [ { ( default_object " MY_OBJECT " ) with cache_function = ... } ] and specify only these functions which are not empty / meaningless Object creators are advised to use the construction [{(default_object "MY_OBJECT") with cache_function = ... }] and specify only these functions which are not empty/meaningless *) val default_object : string -> 'a object_declaration (* the identity substitution function *) val ident_subst_function : object_name * substitution * 'a -> 'a s Given an object declaration , the function [ declare_object ] will hand back two functions , the " injection " and " projection " functions for dynamically typed library - objects . will hand back two functions, the "injection" and "projection" functions for dynamically typed library-objects. *) type obj val declare_object : 'a object_declaration -> ('a -> obj) * (obj -> 'a) val object_tag : obj -> string val cache_object : object_name * obj -> unit val load_object : int -> object_name * obj -> unit val open_object : int -> object_name * obj -> unit val subst_object : object_name * substitution * obj -> obj val classify_object : object_name * obj -> obj substitutivity val export_object : obj -> obj option val discharge_object : object_name * obj -> obj option val rebuild_object : discharge_info * obj -> obj val relax : bool -> unit
null
https://raw.githubusercontent.com/SamB/coq/8f84aba9ae83a4dc43ea6e804227ae8cae8086b1/library/libobject.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** i $Id$ i i i the identity substitution function
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Names open Libnames open Mod_subst [ ] declares persistent objects , given with methods : * a caching function specifying how to add the object in the current scope ; If the object wishes to register its visibility in the Nametab , it should do so for all possible sufixes . * a loading function , specifying what to do when the module containing the object is loaded ; If the object wishes to register its visibility in the Nametab , it should do so for all sufixes no shorter then the " int " argument * an opening function , specifying what to do when the module containing the object is opened ( imported ) ; If the object wishes to register its visibility in the Nametab , it should do so for the sufix of the length the " int " argument * a classification function , specyfying what to do with the object , when the current module ( containing the object ) is ended ; The possibilities are : Dispose - the object dies at the end of the module Substitue - meaning the object is substitutive and the module name must be updated Keep - the object is not substitutive , but survives module closing Anticipate - this is for objects which have to be explicitely managed by the [ end_module ] function ( like Require and Read markers ) The classification function is also an occasion for a cleanup ( if this function returns Keep or Substitute of some object , the cache method is never called for it ) * a substitution function , performing the substitution ; this function should be declared for substitutive objects only ( see obove ) * a discharge function , that is applied at section closing time to collect the data necessary to rebuild the discharged form of the non volatile objects * a rebuild function , that is applied after section closing to rebuild the non volatile content of a section from the data collected by the discharge function * an export function , to enable optional writing of its contents to disk ( .vo ) . This function is also the oportunity to remove redundant information in order to keep .vo size small The export function is a little obsolete and will be removed in the near future ... * a caching function specifying how to add the object in the current scope; If the object wishes to register its visibility in the Nametab, it should do so for all possible sufixes. * a loading function, specifying what to do when the module containing the object is loaded; If the object wishes to register its visibility in the Nametab, it should do so for all sufixes no shorter then the "int" argument * an opening function, specifying what to do when the module containing the object is opened (imported); If the object wishes to register its visibility in the Nametab, it should do so for the sufix of the length the "int" argument * a classification function, specyfying what to do with the object, when the current module (containing the object) is ended; The possibilities are: Dispose - the object dies at the end of the module Substitue - meaning the object is substitutive and the module name must be updated Keep - the object is not substitutive, but survives module closing Anticipate - this is for objects which have to be explicitely managed by the [end_module] function (like Require and Read markers) The classification function is also an occasion for a cleanup (if this function returns Keep or Substitute of some object, the cache method is never called for it) * a substitution function, performing the substitution; this function should be declared for substitutive objects only (see obove) * a discharge function, that is applied at section closing time to collect the data necessary to rebuild the discharged form of the non volatile objects * a rebuild function, that is applied after section closing to rebuild the non volatile content of a section from the data collected by the discharge function * an export function, to enable optional writing of its contents to disk (.vo). This function is also the oportunity to remove redundant information in order to keep .vo size small The export function is a little obsolete and will be removed in the near future... *) type 'a substitutivity = Dispose | Substitute of 'a | Keep of 'a | Anticipate of 'a type discharge_info = (identifier * bool * bool) list type 'a object_declaration = { object_name : string; cache_function : object_name * 'a -> unit; load_function : int -> object_name * 'a -> unit; open_function : int -> object_name * 'a -> unit; classify_function : object_name * 'a -> 'a substitutivity; subst_function : object_name * substitution * 'a -> 'a; discharge_function : object_name * 'a -> 'a option; rebuild_function : discharge_info * 'a -> 'a; export_function : 'a -> 'a option } The default object is a " Keep " object with empty methods . Object creators are advised to use the construction [ { ( default_object " MY_OBJECT " ) with cache_function = ... } ] and specify only these functions which are not empty / meaningless Object creators are advised to use the construction [{(default_object "MY_OBJECT") with cache_function = ... }] and specify only these functions which are not empty/meaningless *) val default_object : string -> 'a object_declaration val ident_subst_function : object_name * substitution * 'a -> 'a s Given an object declaration , the function [ declare_object ] will hand back two functions , the " injection " and " projection " functions for dynamically typed library - objects . will hand back two functions, the "injection" and "projection" functions for dynamically typed library-objects. *) type obj val declare_object : 'a object_declaration -> ('a -> obj) * (obj -> 'a) val object_tag : obj -> string val cache_object : object_name * obj -> unit val load_object : int -> object_name * obj -> unit val open_object : int -> object_name * obj -> unit val subst_object : object_name * substitution * obj -> obj val classify_object : object_name * obj -> obj substitutivity val export_object : obj -> obj option val discharge_object : object_name * obj -> obj option val rebuild_object : discharge_info * obj -> obj val relax : bool -> unit
e0b270271e9b5b186753ff6eab87731b5f47d03235f6875ca0a07727a103cfd7
seancorfield/honeysql
union_test.cljc
copyright ( c ) 2023 , all rights reserved (ns honey.union-test (:refer-clojure :exclude [format]) (:require [clojure.test :refer [deftest is]] [honey.sql :as sut])) (deftest issue-451 (is (= [(str "SELECT ids.id AS id" " FROM ((SELECT dimension.human_readable_field_id AS id" " FROM dimension AS dimension" " WHERE (dimension.field_id = ?) AND (dimension.human_readable_field_id IS NOT NULL)" " LIMIT ?)" " UNION" " (SELECT dest.id AS id" " FROM field AS source" " LEFT JOIN table AS table ON source.table_id = table.id" " LEFT JOIN field AS dest ON dest.table_id = table.id" " WHERE (source.id = ?) AND (source.semantic_type IN (?)) AND (dest.semantic_type IN (?))" " LIMIT ?)) AS ids" " LIMIT ?") 1 1 1 "type/PK" "type/Name" 1 1] (-> {:select [[:ids.id :id]] :from [[{:union [{:nest {:select [[:dimension.human_readable_field_id :id]] :from [[:dimension :dimension]] :where [:and [:= :dimension.field_id 1] [:not= :dimension.human_readable_field_id nil]] :limit 1}} {:nest {:select [[:dest.id :id]] :from [[:field :source]] :left-join [[:table :table] [:= :source.table_id :table.id] [:field :dest] [:= :dest.table_id :table.id]] :where [:and [:= :source.id 1] [:in :source.semantic_type #{"type/PK"}] [:in :dest.semantic_type #{"type/Name"}]] :limit 1}}]} :ids]] :limit 1} (sut/format)))) )
null
https://raw.githubusercontent.com/seancorfield/honeysql/d17d44ffcf1519cb216ccdf3ee6a7fd1b033f90c/test/honey/union_test.cljc
clojure
copyright ( c ) 2023 , all rights reserved (ns honey.union-test (:refer-clojure :exclude [format]) (:require [clojure.test :refer [deftest is]] [honey.sql :as sut])) (deftest issue-451 (is (= [(str "SELECT ids.id AS id" " FROM ((SELECT dimension.human_readable_field_id AS id" " FROM dimension AS dimension" " WHERE (dimension.field_id = ?) AND (dimension.human_readable_field_id IS NOT NULL)" " LIMIT ?)" " UNION" " (SELECT dest.id AS id" " FROM field AS source" " LEFT JOIN table AS table ON source.table_id = table.id" " LEFT JOIN field AS dest ON dest.table_id = table.id" " WHERE (source.id = ?) AND (source.semantic_type IN (?)) AND (dest.semantic_type IN (?))" " LIMIT ?)) AS ids" " LIMIT ?") 1 1 1 "type/PK" "type/Name" 1 1] (-> {:select [[:ids.id :id]] :from [[{:union [{:nest {:select [[:dimension.human_readable_field_id :id]] :from [[:dimension :dimension]] :where [:and [:= :dimension.field_id 1] [:not= :dimension.human_readable_field_id nil]] :limit 1}} {:nest {:select [[:dest.id :id]] :from [[:field :source]] :left-join [[:table :table] [:= :source.table_id :table.id] [:field :dest] [:= :dest.table_id :table.id]] :where [:and [:= :source.id 1] [:in :source.semantic_type #{"type/PK"}] [:in :dest.semantic_type #{"type/Name"}]] :limit 1}}]} :ids]] :limit 1} (sut/format)))) )
4c97009f1d62b5473eb0d11a5f3b3cf7f4f30df3f276330662620cda505add0e
fpco/schoolofhaskell.com
Files.hs
module Import.Files where import ClassyPrelude.Yesod hiding (fileName) import Foundation import qualified FP.Store.Blob as Blob EKB TODO Eliminate this by giving FP.Store . a ' HasBlobStore ' typeclass like -- -server/blob/master/Data/BlobStore.hs getFileSourceBlob :: Blob.BlobName -> Handler (ResumableSource (ResourceT IO) ByteString) getFileSourceBlob blobuuid = do y <- getYesod liftResourceT $ Blob.get (appBlobStore y) blobuuid putFileSourceBlob :: Blob.BlobName -> Source (ResourceT IO) ByteString -> Int64 -> Handler () putFileSourceBlob file src size = do y <- getYesod liftResourceT $ Blob.put (appBlobStore y) file src size
null
https://raw.githubusercontent.com/fpco/schoolofhaskell.com/15ec1a03cb9d593ee9c0d167dc522afe45ba4f8e/src/Import/Files.hs
haskell
-server/blob/master/Data/BlobStore.hs
module Import.Files where import ClassyPrelude.Yesod hiding (fileName) import Foundation import qualified FP.Store.Blob as Blob EKB TODO Eliminate this by giving FP.Store . a ' HasBlobStore ' typeclass like getFileSourceBlob :: Blob.BlobName -> Handler (ResumableSource (ResourceT IO) ByteString) getFileSourceBlob blobuuid = do y <- getYesod liftResourceT $ Blob.get (appBlobStore y) blobuuid putFileSourceBlob :: Blob.BlobName -> Source (ResourceT IO) ByteString -> Int64 -> Handler () putFileSourceBlob file src size = do y <- getYesod liftResourceT $ Blob.put (appBlobStore y) file src size
9613ff107bfd7d2b4c6252799db382a9db960af9a6841062c8b7869bda822a57
JacquesCarette/Drasil
PythonRenderer.hs
# LANGUAGE TypeFamilies # -- | The logic to render Python code is contained in this module module GOOL.Drasil.LanguageRenderer.PythonRenderer ( * Python Code Configuration -- defines syntax of all Python code PythonCode(..), pyName, pyVersion ) where import Utils.Drasil (blank, indent) import GOOL.Drasil.CodeType (CodeType(..)) import GOOL.Drasil.ClassInterface (Label, Library, VSType, SVariable, SValue, VSFunction, MSStatement, MixedCtorCall, OOProg, ProgramSym(..), FileSym(..), PermanenceSym(..), BodySym(..), BlockSym(..), TypeSym(..), TypeElim(..), VariableSym(..), VariableElim(..), ValueSym(..), Argument(..), Literal(..), MathConstant(..), VariableValue(..), CommandLineArgs(..), NumericExpression(..), BooleanExpression(..), Comparison(..), ValueExpression(..), funcApp, selfFuncApp, extFuncApp, extNewObj, InternalValueExp(..), objMethodCall, FunctionSym(..), GetSet(..), List(..), InternalList(..), StatementSym(..), AssignStatement(..), (&=), DeclStatement(..), IOStatement(..), StringStatement(..), FuncAppStatement(..), CommentStatement(..), ControlStatement(..), switchAsIf, 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 (classDec, dot, ifLabel, elseLabel, forLabel, inLabel, whileLabel, tryLabel, importLabel, exceptionObj', listSep', argv, printLabel, listSep, piLabel, access, functionDox, variableList, parameterList) import qualified GOOL.Drasil.LanguageRenderer as R (sqrt, fabs, log10, log, exp, sin, cos, tan, asin, acos, atan, floor, ceil, multiStmt, body, classVar, listSetFunc, castObj, dynamic, break, continue, addComments, commentedMod, commentedItem) import GOOL.Drasil.LanguageRenderer.Constructors (mkStmtNoEnd, mkStateVal, mkVal, mkStateVar, VSOp, unOpPrec, powerPrec, multPrec, andPrec, orPrec, unExpr, unExpr', typeUnExpr, binExpr, typeBinExpr) import qualified GOOL.Drasil.LanguageRenderer.LanguagePolymorphic as G ( multiBody, block, multiBlock, listInnerType, obj, negateOp, csc, sec, cot, 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, funcType, buildModule, bindingError, notNull, listDecDef, destructorError, stateVarDef, constVar, litArray, listSetFunc, extraClass, listAccessFunc, multiAssign, multiReturn, listDec, funcDecDef, inOutCall, forLoopError, mainBody, inOutFunc, docInOutFunc') import qualified GOOL.Drasil.LanguageRenderer.Macros as M (ifExists, decrement1, increment1, runStrategy, stringListVals, stringListLists, notifyObservers', checkState) import GOOL.Drasil.AST (Terminator(..), FileType(..), FileData(..), fileD, FuncData(..), fd, ModData(..), md, updateMod, MethodData(..), mthd, updateMthd, OpData(..), ParamData(..), pd, ProgData(..), progD, TypeData(..), td, ValData(..), vd, VarData(..), vard) import GOOL.Drasil.Helpers (vibcat, emptyIfEmpty, toCode, toState, onCodeValue, onStateValue, on2CodeValues, on2StateValues, onCodeList, onStateList, on2StateWrapped) import GOOL.Drasil.State (MS, VS, lensGStoFS, lensMStoVS, lensVStoMS, revFiles, addLangImportVS, getLangImports, addLibImportVS, getLibImports, addModuleImport, addModuleImportVS, getModuleImports, setFileType, getClassName, setCurrMain, getClassMap, getMainDoc) import Prelude hiding (break,print,sin,cos,tan,floor,(<>)) import Data.Maybe (fromMaybe) import Control.Lens.Zoom (zoom) import Control.Monad (join) import Control.Monad.State (modify) import Data.List (intercalate, sort) import qualified Data.Map as Map (lookup) import Text.PrettyPrint.HughesPJ (Doc, text, (<>), (<+>), parens, empty, equals, vcat, colon, brackets, isEmpty, quotes) pyExt :: String pyExt = "py" newtype PythonCode a = PC {unPC :: a} instance Functor PythonCode where fmap f (PC x) = PC (f x) instance Applicative PythonCode where pure = PC (PC f) <*> (PC x) = PC (f x) instance Monad PythonCode where PC x >>= f = f x instance OOProg PythonCode instance ProgramSym PythonCode where type Program PythonCode = ProgData prog n files = do fs <- mapM (zoom lensGStoFS) files modify revFiles pure $ onCodeList (progD n) fs instance RenderSym PythonCode instance FileSym PythonCode where type File PythonCode = FileData fileDoc m = do modify (setFileType Combined) G.fileDoc pyExt top bottom m docMod = CP.doxMod pyExt instance RenderFile PythonCode where top _ = toCode empty bottom = toCode empty commentedMod = on2StateValues (on2CodeValues R.commentedMod) fileFromData = G.fileFromData (onCodeValue . fileD) instance ImportSym PythonCode where type Import PythonCode = Doc langImport n = toCode $ importLabel <+> text n modImport = langImport instance ImportElim PythonCode where import' = unPC instance PermanenceSym PythonCode where type Permanence PythonCode = Doc static = toCode empty dynamic = toCode R.dynamic instance PermElim PythonCode where perm = unPC binding = error $ CP.bindingError pyName instance BodySym PythonCode where type Body PythonCode = Doc body = onStateList (onCodeList R.body) addComments s = onStateValue (onCodeValue (R.addComments s pyCommentStart)) instance RenderBody PythonCode where multiBody = G.multiBody instance BodyElim PythonCode where body = unPC instance BlockSym PythonCode where type Block PythonCode = Doc block = G.block instance RenderBlock PythonCode where multiBlock = G.multiBlock instance BlockElim PythonCode where block = unPC instance TypeSym PythonCode where type Type PythonCode = TypeData bool = typeFromData Boolean "" empty int = CP.int float = error pyFloatError double = typeFromData Double pyDouble (text pyDouble) char = typeFromData Char "" empty string = pyStringType infile = typeFromData InFile "" empty outfile = typeFromData OutFile "" empty listType t' = t' >>=(\t -> typeFromData (List (getType t)) "" empty) arrayType = listType listInnerType = G.listInnerType obj = G.obj funcType = CP.funcType void = typeFromData Void pyVoid (text pyVoid) instance TypeElim PythonCode where getType = cType . unPC getTypeString = typeString . unPC instance RenderType PythonCode where multiType _ = typeFromData Void "" empty typeFromData t s d = toState $ toCode $ td t s d instance InternalTypeElim PythonCode where type' = typeDoc . unPC instance UnaryOpSym PythonCode where type UnaryOp PythonCode = OpData notOp = pyNotOp negateOp = G.negateOp sqrtOp = pySqrtOp absOp = pyAbsOp logOp = pyLogOp lnOp = pyLnOp expOp = pyExpOp sinOp = pySinOp cosOp = pyCosOp tanOp = pyTanOp asinOp = pyAsinOp acosOp = pyAcosOp atanOp = pyAtanOp floorOp = pyFloorOp ceilOp = pyCeilOp instance BinaryOpSym PythonCode where type BinaryOp PythonCode = 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 = powerPrec pyPower moduloOp = G.moduloOp andOp = andPrec pyAnd orOp = orPrec pyOr instance OpElim PythonCode where uOp = opDoc . unPC bOp = opDoc . unPC uOpPrec = opPrec . unPC bOpPrec = opPrec . unPC instance VariableSym PythonCode where type Variable PythonCode = VarData var = G.var staticVar = G.staticVar const = var extVar l n t = modify (addModuleImportVS l) >> CP.extVar l n t self = zoom lensVStoMS getClassName >>= (\l -> mkStateVar pySelf (obj l) (text pySelf)) classVar = CP.classVar R.classVar extClassVar c v = join $ on2StateValues (\t cm -> maybe id ((>>) . modify . addModuleImportVS) (Map.lookup (getTypeString t) cm) $ CP.classVar pyClassVar (toState t) v) c getClassMap objVar = G.objVar objVarSelf = CP.objVarSelf arrayElem i = G.arrayElem (litInt i) instance VariableElim PythonCode where variableName = varName . unPC variableType = onCodeValue varType instance InternalVarElim PythonCode where variableBind = varBind . unPC variable = varDoc . unPC instance RenderVariable PythonCode where varFromData b n t' d = do t <- t' toState $ on2CodeValues (vard b n) t (toCode d) instance ValueSym PythonCode where type Value PythonCode = ValData valueType = onCodeValue valType instance Argument PythonCode where pointerArg = id instance Literal PythonCode where litTrue = mkStateVal bool pyTrue litFalse = mkStateVal bool pyFalse litChar = G.litChar quotes litDouble = G.litDouble litFloat = error pyFloatError litInt = G.litInt litString = G.litString litArray = CP.litArray brackets litList = litArray instance MathConstant PythonCode where pi = addmathImport $ mkStateVal double pyPi instance VariableValue PythonCode where valueOf = G.valueOf instance CommandLineArgs PythonCode where arg n = G.arg (litInt $ n+1) argsList argsList = do modify (addLangImportVS pySys) G.argsList $ pySys `access` argv argExists i = listSize argsList ?> litInt (fromIntegral $ i+1) instance NumericExpression PythonCode where (#~) = unExpr' negateOp (#/^) = unExpr sqrtOp (#|) = unExpr absOp (#+) = binExpr plusOp (#-) = binExpr minusOp (#*) = binExpr multOp (#/) v1' v2' = do v1 <- v1' v2 <- v2' let pyDivision Integer Integer = binExpr (multPrec pyIntDiv) pyDivision _ _ = binExpr divideOp pyDivision (getType $ valueType v1) (getType $ valueType v2) (pure v1) (pure v2) (#%) = binExpr moduloOp (#^) = binExpr powerOp log = unExpr logOp ln = unExpr lnOp exp = unExpr expOp sin = unExpr sinOp cos = unExpr cosOp tan = unExpr tanOp csc = G.csc sec = G.sec cot = G.cot arcsin = unExpr asinOp arccos = unExpr acosOp arctan = unExpr atanOp floor = unExpr floorOp ceil = unExpr ceilOp instance BooleanExpression PythonCode where (?!) = typeUnExpr notOp bool (?&&) = typeBinExpr andOp bool (?||) = typeBinExpr orOp bool instance Comparison PythonCode where (?<) = typeBinExpr lessOp bool (?<=) = typeBinExpr lessEqualOp bool (?>) = typeBinExpr greaterOp bool (?>=) = typeBinExpr greaterEqualOp bool (?==) = typeBinExpr equalOp bool (?!=) = typeBinExpr notEqualOp bool instance ValueExpression PythonCode where inlineIf = pyInlineIf funcAppMixedArgs = G.funcAppMixedArgs selfFuncAppMixedArgs = G.selfFuncAppMixedArgs dot self extFuncAppMixedArgs l n t ps ns = do modify (addModuleImportVS l) CP.extFuncAppMixedArgs l n t ps ns libFuncAppMixedArgs l n t ps ns = do modify (addLibImportVS l) CP.extFuncAppMixedArgs l n t ps ns newObjMixedArgs = G.newObjMixedArgs "" extNewObjMixedArgs l tp ps ns = do modify (addModuleImportVS l) pyExtNewObjMixedArgs l tp ps ns libNewObjMixedArgs l tp ps ns = do modify (addLibImportVS l) pyExtNewObjMixedArgs l tp ps ns lambda = G.lambda pyLambda notNull = CP.notNull pyNull instance RenderValue PythonCode where inputFunc = mkStateVal string pyInputFunc printFunc = mkStateVal void pyPrintFunc printLnFunc = mkStateVal void empty printFileFunc _ = mkStateVal void empty printFileLnFunc _ = mkStateVal void empty cast = on2StateWrapped (\t v-> mkVal t . R.castObj (RC.type' t) $ RC.value v) call = G.call pyNamedArgSep valFromData p t' d = do t <- t' toState $ on2CodeValues (vd p) t (toCode d) instance ValueElim PythonCode where valuePrec = valPrec . unPC value = val . unPC instance InternalValueExp PythonCode where objMethodCallMixedArgs' = G.objMethodCall instance FunctionSym PythonCode where type Function PythonCode = FuncData func = G.func objAccess = G.objAccess instance GetSet PythonCode where get = G.get set = G.set instance List PythonCode where listSize = on2StateWrapped(\f v-> mkVal (functionType f) (pyListSize (RC.value v) (RC.function f))) listSizeFunc listAdd = G.listAdd listAppend = G.listAppend listAccess = G.listAccess listSet = G.listSet indexOf = CP.indexOf pyIndex instance InternalList PythonCode where listSlice' b e s vn vo = pyListSlice vn vo (getVal b) (getVal e) (getVal s) where getVal = fromMaybe (mkStateVal void empty) instance InternalGetSet PythonCode where getFunc = G.getFunc setFunc = G.setFunc instance InternalListFunc PythonCode where listSizeFunc = funcFromData pyListSizeFunc int listAddFunc _ = CP.listAddFunc pyInsert listAppendFunc = G.listAppendFunc pyAppendFunc listAccessFunc = CP.listAccessFunc listSetFunc = CP.listSetFunc R.listSetFunc instance RenderFunction PythonCode where funcFromData d = onStateValue (onCodeValue (`fd` d)) instance FunctionElim PythonCode where functionType = onCodeValue fType function = funcDoc . unPC instance InternalAssignStmt PythonCode where multiAssign = CP.multiAssign id instance InternalIOStmt PythonCode where printSt = pyPrint instance InternalControlStmt PythonCode where multiReturn = CP.multiReturn id instance RenderStatement PythonCode where stmt = G.stmt loopStmt = G.loopStmt emptyStmt = G.emptyStmt stmtFromData d t = toState $ toCode (d, t) instance StatementElim PythonCode where statement = fst . unPC statementTerm = snd . unPC instance StatementSym PythonCode where Terminator determines how statements end type Statement PythonCode = (Doc, Terminator) valStmt = G.valStmt Empty multi = onStateList (onCodeList R.multiStmt) instance AssignStatement PythonCode where assign = G.assign Empty (&-=) = G.subAssign Empty (&+=) = G.increment (&++) = M.increment1 (&--) = M.decrement1 instance DeclStatement PythonCode where varDec _ = mkStmtNoEnd empty varDecDef = assign listDec _ = CP.listDec listDecDef = CP.listDecDef arrayDec = listDec arrayDecDef = listDecDef objDecDef = varDecDef objDecNew = G.objDecNew extObjDecNew lib v vs = do modify (addModuleImport lib) varDecDef v (extNewObj lib (onStateValue variableType v) vs) constDecDef = varDecDef funcDecDef = CP.funcDecDef instance IOStatement PythonCode where print = pyOut False Nothing printFunc printLn = pyOut True Nothing printFunc printStr = print . litString printStrLn = printLn . litString printFile f = pyOut False (Just f) printFunc printFileLn f = pyOut True (Just f) printFunc printFileStr f = printFile f . litString printFileStrLn f = printFileLn f . litString getInput = pyInput inputFunc discardInput = valStmt inputFunc getFileInput f = pyInput (readline f) discardFileInput f = valStmt (readline f) openFileR f n = f &= openRead n openFileW f n = f &= openWrite n openFileA f n = f &= openAppend n closeFile = G.closeFile pyClose getFileInputLine = getFileInput discardFileLine = CP.discardFileLine pyReadline getFileInputAll f v = v &= readlines f instance StringStatement PythonCode where stringSplit d vnew s = assign vnew (objAccess s (splitFunc d)) stringListVals = M.stringListVals stringListLists = M.stringListLists instance FuncAppStatement PythonCode where inOutCall = CP.inOutCall funcApp selfInOutCall = CP.inOutCall selfFuncApp extInOutCall m = CP.inOutCall (extFuncApp m) instance CommentStatement PythonCode where comment = G.comment pyCommentStart instance ControlStatement PythonCode where break = mkStmtNoEnd R.break continue = mkStmtNoEnd R.continue returnStmt = G.returnStmt Empty throw = G.throw pyThrow Empty ifCond = G.ifCond parens pyBodyStart pyElseIf pyBodyEnd switch = switchAsIf ifExists = M.ifExists for _ _ _ _ = error $ CP.forLoopError pyName forRange i initv finalv stepv = forEach i (range initv finalv stepv) forEach i' v' b' = do i <- zoom lensMStoVS i' v <- zoom lensMStoVS v' b <- b' mkStmtNoEnd (pyForEach i v b) while v' b' = do v <- zoom lensMStoVS v' b <- b' mkStmtNoEnd (pyWhile v b) tryCatch = G.tryCatch pyTryCatch instance StatePattern PythonCode where checkState = M.checkState instance ObserverPattern PythonCode where notifyObservers = M.notifyObservers' instance StrategyPattern PythonCode where runStrategy = M.runStrategy instance ScopeSym PythonCode where type Scope PythonCode = Doc private = toCode empty public = toCode empty instance RenderScope PythonCode where scopeFromData _ = toCode instance ScopeElim PythonCode where scope = unPC instance MethodTypeSym PythonCode where type MethodType PythonCode = TypeData mType = zoom lensMStoVS construct = G.construct instance ParameterSym PythonCode where type Parameter PythonCode = ParamData param = G.param RC.variable pointerParam = param instance RenderParam PythonCode where paramFromData v' d = do v <- zoom lensMStoVS v' toState $ on2CodeValues pd v (toCode d) instance ParamElim PythonCode where parameterName = variableName . onCodeValue paramVar parameterType = variableType . onCodeValue paramVar parameter = paramDoc . unPC instance MethodSym PythonCode where type Method PythonCode = MethodData method = G.method getMethod = G.getMethod setMethod = G.setMethod constructor = CP.constructor initName docMain = mainFunction function = G.function mainFunction = CP.mainBody docFunc = CP.doxFunc inOutMethod n s p = CP.inOutFunc (method n s p) docInOutMethod n s p = CP.docInOutFunc' functionDox (inOutMethod n s p) inOutFunc n s = CP.inOutFunc (function n s) docInOutFunc n s = CP.docInOutFunc' functionDox (inOutFunc n s) instance RenderMethod PythonCode where intMethod m n _ _ _ ps b = do modify (if m then setCurrMain else id) sl <- zoom lensMStoVS self pms <- sequence ps toCode . mthd . pyMethod n sl pms <$> b intFunc m n _ _ _ ps b = do modify (if m then setCurrMain else id) bd <- b pms <- sequence ps pure $ toCode $ mthd $ pyFunction n pms bd commentedFunc cmt m = on2StateValues (on2CodeValues updateMthd) m (onStateValue (onCodeValue R.commentedItem) cmt) destructor _ = error $ CP.destructorError pyName mthdFromData _ d = toState $ toCode $ mthd d instance MethodElim PythonCode where method = mthdDoc . unPC instance StateVarSym PythonCode where type StateVar PythonCode = Doc stateVar _ _ _ = toState (toCode empty) stateVarDef = CP.stateVarDef constVar = CP.constVar (RC.perm (static :: PythonCode (Permanence PythonCode))) instance StateVarElim PythonCode where stateVar = unPC instance ClassSym PythonCode where type Class PythonCode = Doc buildClass = G.buildClass extraClass = CP.extraClass implementingClass = G.implementingClass docClass = CP.doxClass instance RenderClass PythonCode where intClass = CP.intClass pyClass inherit n = toCode $ maybe empty (parens . text) n implements is = toCode $ parens (text $ intercalate listSep is) commentedClass = G.commentedClass instance ClassElim PythonCode where class' = unPC instance ModuleSym PythonCode where type Module PythonCode = ModData buildModule n is = CP.buildModule n (do lis <- getLangImports libis <- getLibImports mis <- getModuleImports pure $ vibcat [ vcat (map (RC.import' . (langImport :: Label -> PythonCode (Import PythonCode))) lis), vcat (map (RC.import' . (langImport :: Label -> PythonCode (Import PythonCode))) (sort $ is ++ libis)), vcat (map (RC.import' . (modImport :: Label -> PythonCode (Import PythonCode))) mis)]) (pure empty) getMainDoc instance RenderMod PythonCode where modFromData n = G.modFromData n (toCode . md n) updateModuleDoc f = onCodeValue (updateMod f) instance ModuleElim PythonCode where module' = modDoc . unPC instance BlockCommentSym PythonCode where type BlockComment PythonCode = Doc blockComment lns = toCode $ pyBlockComment lns pyCommentStart docComment = onStateValue (\lns -> toCode $ pyDocComment lns pyDocCommentStart pyCommentStart) instance BlockCommentElim PythonCode where blockComment' = unPC -- convenience initName :: Label initName = "__init__" pyName, pyVersion :: String pyName = "Python" pyVersion = "3.5.1" pyInt, pyDouble, pyString, pyVoid :: String pyInt = "int" pyDouble = "float" pyString = "str" pyVoid = "NoneType" pyFloatError :: String pyFloatError = "Floats unavailable in Python, use Doubles instead" pyPower, pyAnd, pyOr, pyIntDiv :: String pyPower = "**" pyAnd = "and" pyOr = "or" pyIntDiv = "//" pySelf, pyNull :: String pySelf = "self" pyNull = "None" pyNull' :: Doc pyNull' = text pyNull pyTrue, pyFalse :: Doc pyTrue = text "True" pyFalse = text "False" pyPi :: Doc pyPi = text $ pyMath `access` piLabel pySys :: String pySys = "sys" pyInputFunc, pyPrintFunc, pyListSizeFunc :: Doc raw_input ( ) for < Python 3.0 pyPrintFunc = text printLabel pyListSizeFunc = text "len" pyIndex, pyInsert, pyAppendFunc, pyReadline, pyReadlines, pyOpen, pyClose, pyRead, pyWrite, pyAppend, pySplit, pyRange, pyRstrip, pyMath :: String pyIndex = "index" pyInsert = "insert" pyAppendFunc = "append" pyReadline = "readline" pyReadlines = "readlines" pyOpen = "open" pyClose = "close" pyRead = "r" pyWrite = "w" pyAppend = "a" pySplit = "split" pyRange = "range" pyRstrip = "rstrip" pyMath = "math" pyDef, pyLambdaDec, pyElseIf, pyRaise, pyExcept :: Doc pyDef = text "def" pyLambdaDec = text "lambda" pyElseIf = text "elif" pyRaise = text "raise" pyExcept = text "except" pyBodyStart, pyBodyEnd, pyCommentStart, pyDocCommentStart, pyNamedArgSep :: Doc pyBodyStart = colon pyBodyEnd = empty pyCommentStart = text "#" pyDocCommentStart = pyCommentStart <> pyCommentStart pyNamedArgSep = equals pyNotOp :: (Monad r) => VSOp r pyNotOp = unOpPrec "not" pySqrtOp :: (Monad r) => VSOp r pySqrtOp = mathFunc R.sqrt pyAbsOp :: (Monad r) => VSOp r pyAbsOp = mathFunc R.fabs pyLogOp :: (Monad r) => VSOp r pyLogOp = mathFunc R.log10 pyLnOp :: (Monad r) => VSOp r pyLnOp = mathFunc R.log pyExpOp :: (Monad r) => VSOp r pyExpOp = mathFunc R.exp pySinOp :: (Monad r) => VSOp r pySinOp = mathFunc R.sin pyCosOp :: (Monad r) => VSOp r pyCosOp = mathFunc R.cos pyTanOp :: (Monad r) => VSOp r pyTanOp = mathFunc R.tan pyAsinOp :: (Monad r) => VSOp r pyAsinOp = mathFunc R.asin pyAcosOp :: (Monad r) => VSOp r pyAcosOp = mathFunc R.acos pyAtanOp :: (Monad r) => VSOp r pyAtanOp = mathFunc R.atan pyFloorOp :: (Monad r) => VSOp r pyFloorOp = mathFunc R.floor pyCeilOp :: (Monad r) => VSOp r pyCeilOp = mathFunc R.ceil addmathImport :: VS a -> VS a addmathImport = (>>) $ modify (addLangImportVS pyMath) mathFunc :: (Monad r) => String -> VSOp r mathFunc = addmathImport . unOpPrec . access pyMath splitFunc :: (RenderSym r) => Char -> VSFunction r splitFunc d = func pySplit (listType string) [litString [d]] openRead, openWrite, openAppend :: (RenderSym r) => SValue r -> SValue r openRead n = funcApp pyOpen infile [n, litString pyRead] openWrite n = funcApp pyOpen outfile [n, litString pyWrite] openAppend n = funcApp pyOpen outfile [n, litString pyAppend] readline, readlines :: (RenderSym r) => SValue r -> SValue r readline f = objMethodCall string f pyReadline [] readlines f = objMethodCall (listType string) f pyReadlines [] readInt, readDouble, readString :: (RenderSym r) => SValue r -> SValue r readInt inSrc = funcApp pyInt int [inSrc] readDouble inSrc = funcApp pyDouble double [inSrc] readString inSrc = objMethodCall string inSrc pyRstrip [] range :: (RenderSym r) => SValue r -> SValue r -> SValue r -> SValue r range initv finalv stepv = funcApp pyRange (listType int) [initv, finalv, stepv] pyClassVar :: Doc -> Doc -> Doc pyClassVar c v = c <> dot <> c <> dot <> v pyInlineIf :: (RenderSym r) => SValue r -> SValue r -> SValue r -> SValue r pyInlineIf c' v1' v2' = do c <- c' v1 <- v1' v2 <- v2' valFromData (valuePrec c) (toState $ valueType v1) (RC.value v1 <+> ifLabel <+> RC.value c <+> elseLabel <+> RC.value v2) pyLambda :: (RenderSym r) => [r (Variable r)] -> r (Value r) -> Doc pyLambda ps ex = pyLambdaDec <+> variableList ps <> colon <+> RC.value ex pyListSize :: Doc -> Doc -> Doc pyListSize v f = f <> parens v pyStringType :: (RenderSym r) => VSType r pyStringType = typeFromData String pyString (text pyString) pyExtNewObjMixedArgs :: (RenderSym r) => Library -> MixedCtorCall r pyExtNewObjMixedArgs l tp vs ns = tp >>= (\t -> call (Just l) Nothing (getTypeString t) (pure t) vs ns) pyPrint :: Bool -> Maybe (SValue PythonCode) -> SValue PythonCode -> SValue PythonCode -> MSStatement PythonCode pyPrint newLn f' p' v' = do f <- zoom lensMStoVS $ fromMaybe (mkStateVal void empty) f' prf <- zoom lensMStoVS p' v <- zoom lensMStoVS v' s <- zoom lensMStoVS (litString "" :: SValue PythonCode) let nl = if newLn then empty else listSep' <> text "end" <> equals <> RC.value s fl = emptyIfEmpty (RC.value f) $ listSep' <> text "file" <> equals <> RC.value f mkStmtNoEnd $ RC.value prf <> parens (RC.value v <> nl <> fl) pyOut :: (RenderSym r) => Bool -> Maybe (SValue r) -> SValue r -> SValue r -> MSStatement r pyOut newLn f printFn v = zoom lensMStoVS v >>= pyOut' . getType . valueType where pyOut' (List _) = printSt newLn f printFn v pyOut' _ = G.print newLn f printFn v pyInput :: SValue PythonCode -> SVariable PythonCode -> MSStatement PythonCode pyInput inSrc v = v &= (v >>= pyInput' . getType . variableType) where pyInput' Integer = readInt inSrc pyInput' Float = readDouble inSrc pyInput' Double = readDouble inSrc pyInput' Boolean = inSrc ?!= litString "0" pyInput' String = readString inSrc pyInput' Char = inSrc pyInput' _ = error "Attempt to read a value of unreadable type" pyThrow :: (RenderSym r) => r (Value r) -> Doc pyThrow errMsg = pyRaise <+> exceptionObj' <> parens (RC.value errMsg) pyForEach :: (RenderSym r) => r (Variable r) -> r (Value r) -> r (Body r) -> Doc pyForEach i lstVar b = vcat [ forLabel <+> RC.variable i <+> inLabel <+> RC.value lstVar <> colon, indent $ RC.body b] pyWhile :: (RenderSym r) => r (Value r) -> r (Body r) -> Doc pyWhile v b = vcat [ whileLabel <+> RC.value v <> colon, indent $ RC.body b] pyTryCatch :: (RenderSym r) => r (Body r) -> r (Body r) -> Doc pyTryCatch tryB catchB = vcat [ tryLabel <+> colon, indent $ RC.body tryB, pyExcept <+> exceptionObj' <+> colon, indent $ RC.body catchB] pyListSlice :: (RenderSym r, Monad r) => SVariable r -> SValue r -> SValue r -> SValue r -> SValue r -> MS (r Doc) pyListSlice vn vo beg end step = zoom lensMStoVS $ do vnew <- vn vold <- vo b <- beg e <- end s <- step pure $ toCode $ RC.variable vnew <+> equals <+> RC.value vold <> brackets (RC.value b <> colon <> RC.value e <> colon <> RC.value s) pyMethod :: (RenderSym r) => Label -> r (Variable r) -> [r (Parameter r)] -> r (Body r) -> Doc pyMethod n slf ps b = vcat [ pyDef <+> text n <> parens (RC.variable slf <> oneParam <> pms) <> colon, indent bodyD] where pms = parameterList ps oneParam = emptyIfEmpty pms listSep' bodyD | isEmpty (RC.body b) = pyNull' | otherwise = RC.body b pyFunction :: (RenderSym r) => Label -> [r (Parameter r)] -> r (Body r) -> Doc pyFunction n ps b = vcat [ pyDef <+> text n <> parens (parameterList ps) <> colon, indent bodyD] where bodyD | isEmpty (RC.body b) = pyNull' | otherwise = RC.body b pyClass :: Label -> Doc -> Doc -> Doc -> Doc -> Doc pyClass n pn s vs fs = vcat [ s <+> classDec <+> text n <> pn <> colon, indent funcSec] where funcSec | isEmpty (vs <> fs) = pyNull' | isEmpty vs = fs | isEmpty fs = vs | otherwise = vcat [vs, blank, fs] pyBlockComment :: [String] -> Doc -> Doc pyBlockComment lns cmt = vcat $ map ((<+>) cmt . text) lns pyDocComment :: [String] -> Doc -> Doc -> Doc pyDocComment [] _ _ = empty pyDocComment (l:lns) start mid = vcat $ start <+> text l : map ((<+>) mid . text) lns
null
https://raw.githubusercontent.com/JacquesCarette/Drasil/c7c57e77e0de03158e7c4db6e74e13898a889764/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/PythonRenderer.hs
haskell
| The logic to render Python code is contained in this module defines syntax of all Python code ) = M.decrement1 convenience
# LANGUAGE TypeFamilies # module GOOL.Drasil.LanguageRenderer.PythonRenderer ( PythonCode(..), pyName, pyVersion ) where import Utils.Drasil (blank, indent) import GOOL.Drasil.CodeType (CodeType(..)) import GOOL.Drasil.ClassInterface (Label, Library, VSType, SVariable, SValue, VSFunction, MSStatement, MixedCtorCall, OOProg, ProgramSym(..), FileSym(..), PermanenceSym(..), BodySym(..), BlockSym(..), TypeSym(..), TypeElim(..), VariableSym(..), VariableElim(..), ValueSym(..), Argument(..), Literal(..), MathConstant(..), VariableValue(..), CommandLineArgs(..), NumericExpression(..), BooleanExpression(..), Comparison(..), ValueExpression(..), funcApp, selfFuncApp, extFuncApp, extNewObj, InternalValueExp(..), objMethodCall, FunctionSym(..), GetSet(..), List(..), InternalList(..), StatementSym(..), AssignStatement(..), (&=), DeclStatement(..), IOStatement(..), StringStatement(..), FuncAppStatement(..), CommentStatement(..), ControlStatement(..), switchAsIf, 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 (classDec, dot, ifLabel, elseLabel, forLabel, inLabel, whileLabel, tryLabel, importLabel, exceptionObj', listSep', argv, printLabel, listSep, piLabel, access, functionDox, variableList, parameterList) import qualified GOOL.Drasil.LanguageRenderer as R (sqrt, fabs, log10, log, exp, sin, cos, tan, asin, acos, atan, floor, ceil, multiStmt, body, classVar, listSetFunc, castObj, dynamic, break, continue, addComments, commentedMod, commentedItem) import GOOL.Drasil.LanguageRenderer.Constructors (mkStmtNoEnd, mkStateVal, mkVal, mkStateVar, VSOp, unOpPrec, powerPrec, multPrec, andPrec, orPrec, unExpr, unExpr', typeUnExpr, binExpr, typeBinExpr) import qualified GOOL.Drasil.LanguageRenderer.LanguagePolymorphic as G ( multiBody, block, multiBlock, listInnerType, obj, negateOp, csc, sec, cot, 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, funcType, buildModule, bindingError, notNull, listDecDef, destructorError, stateVarDef, constVar, litArray, listSetFunc, extraClass, listAccessFunc, multiAssign, multiReturn, listDec, funcDecDef, inOutCall, forLoopError, mainBody, inOutFunc, docInOutFunc') import qualified GOOL.Drasil.LanguageRenderer.Macros as M (ifExists, decrement1, increment1, runStrategy, stringListVals, stringListLists, notifyObservers', checkState) import GOOL.Drasil.AST (Terminator(..), FileType(..), FileData(..), fileD, FuncData(..), fd, ModData(..), md, updateMod, MethodData(..), mthd, updateMthd, OpData(..), ParamData(..), pd, ProgData(..), progD, TypeData(..), td, ValData(..), vd, VarData(..), vard) import GOOL.Drasil.Helpers (vibcat, emptyIfEmpty, toCode, toState, onCodeValue, onStateValue, on2CodeValues, on2StateValues, onCodeList, onStateList, on2StateWrapped) import GOOL.Drasil.State (MS, VS, lensGStoFS, lensMStoVS, lensVStoMS, revFiles, addLangImportVS, getLangImports, addLibImportVS, getLibImports, addModuleImport, addModuleImportVS, getModuleImports, setFileType, getClassName, setCurrMain, getClassMap, getMainDoc) import Prelude hiding (break,print,sin,cos,tan,floor,(<>)) import Data.Maybe (fromMaybe) import Control.Lens.Zoom (zoom) import Control.Monad (join) import Control.Monad.State (modify) import Data.List (intercalate, sort) import qualified Data.Map as Map (lookup) import Text.PrettyPrint.HughesPJ (Doc, text, (<>), (<+>), parens, empty, equals, vcat, colon, brackets, isEmpty, quotes) pyExt :: String pyExt = "py" newtype PythonCode a = PC {unPC :: a} instance Functor PythonCode where fmap f (PC x) = PC (f x) instance Applicative PythonCode where pure = PC (PC f) <*> (PC x) = PC (f x) instance Monad PythonCode where PC x >>= f = f x instance OOProg PythonCode instance ProgramSym PythonCode where type Program PythonCode = ProgData prog n files = do fs <- mapM (zoom lensGStoFS) files modify revFiles pure $ onCodeList (progD n) fs instance RenderSym PythonCode instance FileSym PythonCode where type File PythonCode = FileData fileDoc m = do modify (setFileType Combined) G.fileDoc pyExt top bottom m docMod = CP.doxMod pyExt instance RenderFile PythonCode where top _ = toCode empty bottom = toCode empty commentedMod = on2StateValues (on2CodeValues R.commentedMod) fileFromData = G.fileFromData (onCodeValue . fileD) instance ImportSym PythonCode where type Import PythonCode = Doc langImport n = toCode $ importLabel <+> text n modImport = langImport instance ImportElim PythonCode where import' = unPC instance PermanenceSym PythonCode where type Permanence PythonCode = Doc static = toCode empty dynamic = toCode R.dynamic instance PermElim PythonCode where perm = unPC binding = error $ CP.bindingError pyName instance BodySym PythonCode where type Body PythonCode = Doc body = onStateList (onCodeList R.body) addComments s = onStateValue (onCodeValue (R.addComments s pyCommentStart)) instance RenderBody PythonCode where multiBody = G.multiBody instance BodyElim PythonCode where body = unPC instance BlockSym PythonCode where type Block PythonCode = Doc block = G.block instance RenderBlock PythonCode where multiBlock = G.multiBlock instance BlockElim PythonCode where block = unPC instance TypeSym PythonCode where type Type PythonCode = TypeData bool = typeFromData Boolean "" empty int = CP.int float = error pyFloatError double = typeFromData Double pyDouble (text pyDouble) char = typeFromData Char "" empty string = pyStringType infile = typeFromData InFile "" empty outfile = typeFromData OutFile "" empty listType t' = t' >>=(\t -> typeFromData (List (getType t)) "" empty) arrayType = listType listInnerType = G.listInnerType obj = G.obj funcType = CP.funcType void = typeFromData Void pyVoid (text pyVoid) instance TypeElim PythonCode where getType = cType . unPC getTypeString = typeString . unPC instance RenderType PythonCode where multiType _ = typeFromData Void "" empty typeFromData t s d = toState $ toCode $ td t s d instance InternalTypeElim PythonCode where type' = typeDoc . unPC instance UnaryOpSym PythonCode where type UnaryOp PythonCode = OpData notOp = pyNotOp negateOp = G.negateOp sqrtOp = pySqrtOp absOp = pyAbsOp logOp = pyLogOp lnOp = pyLnOp expOp = pyExpOp sinOp = pySinOp cosOp = pyCosOp tanOp = pyTanOp asinOp = pyAsinOp acosOp = pyAcosOp atanOp = pyAtanOp floorOp = pyFloorOp ceilOp = pyCeilOp instance BinaryOpSym PythonCode where type BinaryOp PythonCode = 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 = powerPrec pyPower moduloOp = G.moduloOp andOp = andPrec pyAnd orOp = orPrec pyOr instance OpElim PythonCode where uOp = opDoc . unPC bOp = opDoc . unPC uOpPrec = opPrec . unPC bOpPrec = opPrec . unPC instance VariableSym PythonCode where type Variable PythonCode = VarData var = G.var staticVar = G.staticVar const = var extVar l n t = modify (addModuleImportVS l) >> CP.extVar l n t self = zoom lensVStoMS getClassName >>= (\l -> mkStateVar pySelf (obj l) (text pySelf)) classVar = CP.classVar R.classVar extClassVar c v = join $ on2StateValues (\t cm -> maybe id ((>>) . modify . addModuleImportVS) (Map.lookup (getTypeString t) cm) $ CP.classVar pyClassVar (toState t) v) c getClassMap objVar = G.objVar objVarSelf = CP.objVarSelf arrayElem i = G.arrayElem (litInt i) instance VariableElim PythonCode where variableName = varName . unPC variableType = onCodeValue varType instance InternalVarElim PythonCode where variableBind = varBind . unPC variable = varDoc . unPC instance RenderVariable PythonCode where varFromData b n t' d = do t <- t' toState $ on2CodeValues (vard b n) t (toCode d) instance ValueSym PythonCode where type Value PythonCode = ValData valueType = onCodeValue valType instance Argument PythonCode where pointerArg = id instance Literal PythonCode where litTrue = mkStateVal bool pyTrue litFalse = mkStateVal bool pyFalse litChar = G.litChar quotes litDouble = G.litDouble litFloat = error pyFloatError litInt = G.litInt litString = G.litString litArray = CP.litArray brackets litList = litArray instance MathConstant PythonCode where pi = addmathImport $ mkStateVal double pyPi instance VariableValue PythonCode where valueOf = G.valueOf instance CommandLineArgs PythonCode where arg n = G.arg (litInt $ n+1) argsList argsList = do modify (addLangImportVS pySys) G.argsList $ pySys `access` argv argExists i = listSize argsList ?> litInt (fromIntegral $ i+1) instance NumericExpression PythonCode where (#~) = unExpr' negateOp (#/^) = unExpr sqrtOp (#|) = unExpr absOp (#+) = binExpr plusOp (#-) = binExpr minusOp (#*) = binExpr multOp (#/) v1' v2' = do v1 <- v1' v2 <- v2' let pyDivision Integer Integer = binExpr (multPrec pyIntDiv) pyDivision _ _ = binExpr divideOp pyDivision (getType $ valueType v1) (getType $ valueType v2) (pure v1) (pure v2) (#%) = binExpr moduloOp (#^) = binExpr powerOp log = unExpr logOp ln = unExpr lnOp exp = unExpr expOp sin = unExpr sinOp cos = unExpr cosOp tan = unExpr tanOp csc = G.csc sec = G.sec cot = G.cot arcsin = unExpr asinOp arccos = unExpr acosOp arctan = unExpr atanOp floor = unExpr floorOp ceil = unExpr ceilOp instance BooleanExpression PythonCode where (?!) = typeUnExpr notOp bool (?&&) = typeBinExpr andOp bool (?||) = typeBinExpr orOp bool instance Comparison PythonCode where (?<) = typeBinExpr lessOp bool (?<=) = typeBinExpr lessEqualOp bool (?>) = typeBinExpr greaterOp bool (?>=) = typeBinExpr greaterEqualOp bool (?==) = typeBinExpr equalOp bool (?!=) = typeBinExpr notEqualOp bool instance ValueExpression PythonCode where inlineIf = pyInlineIf funcAppMixedArgs = G.funcAppMixedArgs selfFuncAppMixedArgs = G.selfFuncAppMixedArgs dot self extFuncAppMixedArgs l n t ps ns = do modify (addModuleImportVS l) CP.extFuncAppMixedArgs l n t ps ns libFuncAppMixedArgs l n t ps ns = do modify (addLibImportVS l) CP.extFuncAppMixedArgs l n t ps ns newObjMixedArgs = G.newObjMixedArgs "" extNewObjMixedArgs l tp ps ns = do modify (addModuleImportVS l) pyExtNewObjMixedArgs l tp ps ns libNewObjMixedArgs l tp ps ns = do modify (addLibImportVS l) pyExtNewObjMixedArgs l tp ps ns lambda = G.lambda pyLambda notNull = CP.notNull pyNull instance RenderValue PythonCode where inputFunc = mkStateVal string pyInputFunc printFunc = mkStateVal void pyPrintFunc printLnFunc = mkStateVal void empty printFileFunc _ = mkStateVal void empty printFileLnFunc _ = mkStateVal void empty cast = on2StateWrapped (\t v-> mkVal t . R.castObj (RC.type' t) $ RC.value v) call = G.call pyNamedArgSep valFromData p t' d = do t <- t' toState $ on2CodeValues (vd p) t (toCode d) instance ValueElim PythonCode where valuePrec = valPrec . unPC value = val . unPC instance InternalValueExp PythonCode where objMethodCallMixedArgs' = G.objMethodCall instance FunctionSym PythonCode where type Function PythonCode = FuncData func = G.func objAccess = G.objAccess instance GetSet PythonCode where get = G.get set = G.set instance List PythonCode where listSize = on2StateWrapped(\f v-> mkVal (functionType f) (pyListSize (RC.value v) (RC.function f))) listSizeFunc listAdd = G.listAdd listAppend = G.listAppend listAccess = G.listAccess listSet = G.listSet indexOf = CP.indexOf pyIndex instance InternalList PythonCode where listSlice' b e s vn vo = pyListSlice vn vo (getVal b) (getVal e) (getVal s) where getVal = fromMaybe (mkStateVal void empty) instance InternalGetSet PythonCode where getFunc = G.getFunc setFunc = G.setFunc instance InternalListFunc PythonCode where listSizeFunc = funcFromData pyListSizeFunc int listAddFunc _ = CP.listAddFunc pyInsert listAppendFunc = G.listAppendFunc pyAppendFunc listAccessFunc = CP.listAccessFunc listSetFunc = CP.listSetFunc R.listSetFunc instance RenderFunction PythonCode where funcFromData d = onStateValue (onCodeValue (`fd` d)) instance FunctionElim PythonCode where functionType = onCodeValue fType function = funcDoc . unPC instance InternalAssignStmt PythonCode where multiAssign = CP.multiAssign id instance InternalIOStmt PythonCode where printSt = pyPrint instance InternalControlStmt PythonCode where multiReturn = CP.multiReturn id instance RenderStatement PythonCode where stmt = G.stmt loopStmt = G.loopStmt emptyStmt = G.emptyStmt stmtFromData d t = toState $ toCode (d, t) instance StatementElim PythonCode where statement = fst . unPC statementTerm = snd . unPC instance StatementSym PythonCode where Terminator determines how statements end type Statement PythonCode = (Doc, Terminator) valStmt = G.valStmt Empty multi = onStateList (onCodeList R.multiStmt) instance AssignStatement PythonCode where assign = G.assign Empty (&-=) = G.subAssign Empty (&+=) = G.increment (&++) = M.increment1 instance DeclStatement PythonCode where varDec _ = mkStmtNoEnd empty varDecDef = assign listDec _ = CP.listDec listDecDef = CP.listDecDef arrayDec = listDec arrayDecDef = listDecDef objDecDef = varDecDef objDecNew = G.objDecNew extObjDecNew lib v vs = do modify (addModuleImport lib) varDecDef v (extNewObj lib (onStateValue variableType v) vs) constDecDef = varDecDef funcDecDef = CP.funcDecDef instance IOStatement PythonCode where print = pyOut False Nothing printFunc printLn = pyOut True Nothing printFunc printStr = print . litString printStrLn = printLn . litString printFile f = pyOut False (Just f) printFunc printFileLn f = pyOut True (Just f) printFunc printFileStr f = printFile f . litString printFileStrLn f = printFileLn f . litString getInput = pyInput inputFunc discardInput = valStmt inputFunc getFileInput f = pyInput (readline f) discardFileInput f = valStmt (readline f) openFileR f n = f &= openRead n openFileW f n = f &= openWrite n openFileA f n = f &= openAppend n closeFile = G.closeFile pyClose getFileInputLine = getFileInput discardFileLine = CP.discardFileLine pyReadline getFileInputAll f v = v &= readlines f instance StringStatement PythonCode where stringSplit d vnew s = assign vnew (objAccess s (splitFunc d)) stringListVals = M.stringListVals stringListLists = M.stringListLists instance FuncAppStatement PythonCode where inOutCall = CP.inOutCall funcApp selfInOutCall = CP.inOutCall selfFuncApp extInOutCall m = CP.inOutCall (extFuncApp m) instance CommentStatement PythonCode where comment = G.comment pyCommentStart instance ControlStatement PythonCode where break = mkStmtNoEnd R.break continue = mkStmtNoEnd R.continue returnStmt = G.returnStmt Empty throw = G.throw pyThrow Empty ifCond = G.ifCond parens pyBodyStart pyElseIf pyBodyEnd switch = switchAsIf ifExists = M.ifExists for _ _ _ _ = error $ CP.forLoopError pyName forRange i initv finalv stepv = forEach i (range initv finalv stepv) forEach i' v' b' = do i <- zoom lensMStoVS i' v <- zoom lensMStoVS v' b <- b' mkStmtNoEnd (pyForEach i v b) while v' b' = do v <- zoom lensMStoVS v' b <- b' mkStmtNoEnd (pyWhile v b) tryCatch = G.tryCatch pyTryCatch instance StatePattern PythonCode where checkState = M.checkState instance ObserverPattern PythonCode where notifyObservers = M.notifyObservers' instance StrategyPattern PythonCode where runStrategy = M.runStrategy instance ScopeSym PythonCode where type Scope PythonCode = Doc private = toCode empty public = toCode empty instance RenderScope PythonCode where scopeFromData _ = toCode instance ScopeElim PythonCode where scope = unPC instance MethodTypeSym PythonCode where type MethodType PythonCode = TypeData mType = zoom lensMStoVS construct = G.construct instance ParameterSym PythonCode where type Parameter PythonCode = ParamData param = G.param RC.variable pointerParam = param instance RenderParam PythonCode where paramFromData v' d = do v <- zoom lensMStoVS v' toState $ on2CodeValues pd v (toCode d) instance ParamElim PythonCode where parameterName = variableName . onCodeValue paramVar parameterType = variableType . onCodeValue paramVar parameter = paramDoc . unPC instance MethodSym PythonCode where type Method PythonCode = MethodData method = G.method getMethod = G.getMethod setMethod = G.setMethod constructor = CP.constructor initName docMain = mainFunction function = G.function mainFunction = CP.mainBody docFunc = CP.doxFunc inOutMethod n s p = CP.inOutFunc (method n s p) docInOutMethod n s p = CP.docInOutFunc' functionDox (inOutMethod n s p) inOutFunc n s = CP.inOutFunc (function n s) docInOutFunc n s = CP.docInOutFunc' functionDox (inOutFunc n s) instance RenderMethod PythonCode where intMethod m n _ _ _ ps b = do modify (if m then setCurrMain else id) sl <- zoom lensMStoVS self pms <- sequence ps toCode . mthd . pyMethod n sl pms <$> b intFunc m n _ _ _ ps b = do modify (if m then setCurrMain else id) bd <- b pms <- sequence ps pure $ toCode $ mthd $ pyFunction n pms bd commentedFunc cmt m = on2StateValues (on2CodeValues updateMthd) m (onStateValue (onCodeValue R.commentedItem) cmt) destructor _ = error $ CP.destructorError pyName mthdFromData _ d = toState $ toCode $ mthd d instance MethodElim PythonCode where method = mthdDoc . unPC instance StateVarSym PythonCode where type StateVar PythonCode = Doc stateVar _ _ _ = toState (toCode empty) stateVarDef = CP.stateVarDef constVar = CP.constVar (RC.perm (static :: PythonCode (Permanence PythonCode))) instance StateVarElim PythonCode where stateVar = unPC instance ClassSym PythonCode where type Class PythonCode = Doc buildClass = G.buildClass extraClass = CP.extraClass implementingClass = G.implementingClass docClass = CP.doxClass instance RenderClass PythonCode where intClass = CP.intClass pyClass inherit n = toCode $ maybe empty (parens . text) n implements is = toCode $ parens (text $ intercalate listSep is) commentedClass = G.commentedClass instance ClassElim PythonCode where class' = unPC instance ModuleSym PythonCode where type Module PythonCode = ModData buildModule n is = CP.buildModule n (do lis <- getLangImports libis <- getLibImports mis <- getModuleImports pure $ vibcat [ vcat (map (RC.import' . (langImport :: Label -> PythonCode (Import PythonCode))) lis), vcat (map (RC.import' . (langImport :: Label -> PythonCode (Import PythonCode))) (sort $ is ++ libis)), vcat (map (RC.import' . (modImport :: Label -> PythonCode (Import PythonCode))) mis)]) (pure empty) getMainDoc instance RenderMod PythonCode where modFromData n = G.modFromData n (toCode . md n) updateModuleDoc f = onCodeValue (updateMod f) instance ModuleElim PythonCode where module' = modDoc . unPC instance BlockCommentSym PythonCode where type BlockComment PythonCode = Doc blockComment lns = toCode $ pyBlockComment lns pyCommentStart docComment = onStateValue (\lns -> toCode $ pyDocComment lns pyDocCommentStart pyCommentStart) instance BlockCommentElim PythonCode where blockComment' = unPC initName :: Label initName = "__init__" pyName, pyVersion :: String pyName = "Python" pyVersion = "3.5.1" pyInt, pyDouble, pyString, pyVoid :: String pyInt = "int" pyDouble = "float" pyString = "str" pyVoid = "NoneType" pyFloatError :: String pyFloatError = "Floats unavailable in Python, use Doubles instead" pyPower, pyAnd, pyOr, pyIntDiv :: String pyPower = "**" pyAnd = "and" pyOr = "or" pyIntDiv = "//" pySelf, pyNull :: String pySelf = "self" pyNull = "None" pyNull' :: Doc pyNull' = text pyNull pyTrue, pyFalse :: Doc pyTrue = text "True" pyFalse = text "False" pyPi :: Doc pyPi = text $ pyMath `access` piLabel pySys :: String pySys = "sys" pyInputFunc, pyPrintFunc, pyListSizeFunc :: Doc raw_input ( ) for < Python 3.0 pyPrintFunc = text printLabel pyListSizeFunc = text "len" pyIndex, pyInsert, pyAppendFunc, pyReadline, pyReadlines, pyOpen, pyClose, pyRead, pyWrite, pyAppend, pySplit, pyRange, pyRstrip, pyMath :: String pyIndex = "index" pyInsert = "insert" pyAppendFunc = "append" pyReadline = "readline" pyReadlines = "readlines" pyOpen = "open" pyClose = "close" pyRead = "r" pyWrite = "w" pyAppend = "a" pySplit = "split" pyRange = "range" pyRstrip = "rstrip" pyMath = "math" pyDef, pyLambdaDec, pyElseIf, pyRaise, pyExcept :: Doc pyDef = text "def" pyLambdaDec = text "lambda" pyElseIf = text "elif" pyRaise = text "raise" pyExcept = text "except" pyBodyStart, pyBodyEnd, pyCommentStart, pyDocCommentStart, pyNamedArgSep :: Doc pyBodyStart = colon pyBodyEnd = empty pyCommentStart = text "#" pyDocCommentStart = pyCommentStart <> pyCommentStart pyNamedArgSep = equals pyNotOp :: (Monad r) => VSOp r pyNotOp = unOpPrec "not" pySqrtOp :: (Monad r) => VSOp r pySqrtOp = mathFunc R.sqrt pyAbsOp :: (Monad r) => VSOp r pyAbsOp = mathFunc R.fabs pyLogOp :: (Monad r) => VSOp r pyLogOp = mathFunc R.log10 pyLnOp :: (Monad r) => VSOp r pyLnOp = mathFunc R.log pyExpOp :: (Monad r) => VSOp r pyExpOp = mathFunc R.exp pySinOp :: (Monad r) => VSOp r pySinOp = mathFunc R.sin pyCosOp :: (Monad r) => VSOp r pyCosOp = mathFunc R.cos pyTanOp :: (Monad r) => VSOp r pyTanOp = mathFunc R.tan pyAsinOp :: (Monad r) => VSOp r pyAsinOp = mathFunc R.asin pyAcosOp :: (Monad r) => VSOp r pyAcosOp = mathFunc R.acos pyAtanOp :: (Monad r) => VSOp r pyAtanOp = mathFunc R.atan pyFloorOp :: (Monad r) => VSOp r pyFloorOp = mathFunc R.floor pyCeilOp :: (Monad r) => VSOp r pyCeilOp = mathFunc R.ceil addmathImport :: VS a -> VS a addmathImport = (>>) $ modify (addLangImportVS pyMath) mathFunc :: (Monad r) => String -> VSOp r mathFunc = addmathImport . unOpPrec . access pyMath splitFunc :: (RenderSym r) => Char -> VSFunction r splitFunc d = func pySplit (listType string) [litString [d]] openRead, openWrite, openAppend :: (RenderSym r) => SValue r -> SValue r openRead n = funcApp pyOpen infile [n, litString pyRead] openWrite n = funcApp pyOpen outfile [n, litString pyWrite] openAppend n = funcApp pyOpen outfile [n, litString pyAppend] readline, readlines :: (RenderSym r) => SValue r -> SValue r readline f = objMethodCall string f pyReadline [] readlines f = objMethodCall (listType string) f pyReadlines [] readInt, readDouble, readString :: (RenderSym r) => SValue r -> SValue r readInt inSrc = funcApp pyInt int [inSrc] readDouble inSrc = funcApp pyDouble double [inSrc] readString inSrc = objMethodCall string inSrc pyRstrip [] range :: (RenderSym r) => SValue r -> SValue r -> SValue r -> SValue r range initv finalv stepv = funcApp pyRange (listType int) [initv, finalv, stepv] pyClassVar :: Doc -> Doc -> Doc pyClassVar c v = c <> dot <> c <> dot <> v pyInlineIf :: (RenderSym r) => SValue r -> SValue r -> SValue r -> SValue r pyInlineIf c' v1' v2' = do c <- c' v1 <- v1' v2 <- v2' valFromData (valuePrec c) (toState $ valueType v1) (RC.value v1 <+> ifLabel <+> RC.value c <+> elseLabel <+> RC.value v2) pyLambda :: (RenderSym r) => [r (Variable r)] -> r (Value r) -> Doc pyLambda ps ex = pyLambdaDec <+> variableList ps <> colon <+> RC.value ex pyListSize :: Doc -> Doc -> Doc pyListSize v f = f <> parens v pyStringType :: (RenderSym r) => VSType r pyStringType = typeFromData String pyString (text pyString) pyExtNewObjMixedArgs :: (RenderSym r) => Library -> MixedCtorCall r pyExtNewObjMixedArgs l tp vs ns = tp >>= (\t -> call (Just l) Nothing (getTypeString t) (pure t) vs ns) pyPrint :: Bool -> Maybe (SValue PythonCode) -> SValue PythonCode -> SValue PythonCode -> MSStatement PythonCode pyPrint newLn f' p' v' = do f <- zoom lensMStoVS $ fromMaybe (mkStateVal void empty) f' prf <- zoom lensMStoVS p' v <- zoom lensMStoVS v' s <- zoom lensMStoVS (litString "" :: SValue PythonCode) let nl = if newLn then empty else listSep' <> text "end" <> equals <> RC.value s fl = emptyIfEmpty (RC.value f) $ listSep' <> text "file" <> equals <> RC.value f mkStmtNoEnd $ RC.value prf <> parens (RC.value v <> nl <> fl) pyOut :: (RenderSym r) => Bool -> Maybe (SValue r) -> SValue r -> SValue r -> MSStatement r pyOut newLn f printFn v = zoom lensMStoVS v >>= pyOut' . getType . valueType where pyOut' (List _) = printSt newLn f printFn v pyOut' _ = G.print newLn f printFn v pyInput :: SValue PythonCode -> SVariable PythonCode -> MSStatement PythonCode pyInput inSrc v = v &= (v >>= pyInput' . getType . variableType) where pyInput' Integer = readInt inSrc pyInput' Float = readDouble inSrc pyInput' Double = readDouble inSrc pyInput' Boolean = inSrc ?!= litString "0" pyInput' String = readString inSrc pyInput' Char = inSrc pyInput' _ = error "Attempt to read a value of unreadable type" pyThrow :: (RenderSym r) => r (Value r) -> Doc pyThrow errMsg = pyRaise <+> exceptionObj' <> parens (RC.value errMsg) pyForEach :: (RenderSym r) => r (Variable r) -> r (Value r) -> r (Body r) -> Doc pyForEach i lstVar b = vcat [ forLabel <+> RC.variable i <+> inLabel <+> RC.value lstVar <> colon, indent $ RC.body b] pyWhile :: (RenderSym r) => r (Value r) -> r (Body r) -> Doc pyWhile v b = vcat [ whileLabel <+> RC.value v <> colon, indent $ RC.body b] pyTryCatch :: (RenderSym r) => r (Body r) -> r (Body r) -> Doc pyTryCatch tryB catchB = vcat [ tryLabel <+> colon, indent $ RC.body tryB, pyExcept <+> exceptionObj' <+> colon, indent $ RC.body catchB] pyListSlice :: (RenderSym r, Monad r) => SVariable r -> SValue r -> SValue r -> SValue r -> SValue r -> MS (r Doc) pyListSlice vn vo beg end step = zoom lensMStoVS $ do vnew <- vn vold <- vo b <- beg e <- end s <- step pure $ toCode $ RC.variable vnew <+> equals <+> RC.value vold <> brackets (RC.value b <> colon <> RC.value e <> colon <> RC.value s) pyMethod :: (RenderSym r) => Label -> r (Variable r) -> [r (Parameter r)] -> r (Body r) -> Doc pyMethod n slf ps b = vcat [ pyDef <+> text n <> parens (RC.variable slf <> oneParam <> pms) <> colon, indent bodyD] where pms = parameterList ps oneParam = emptyIfEmpty pms listSep' bodyD | isEmpty (RC.body b) = pyNull' | otherwise = RC.body b pyFunction :: (RenderSym r) => Label -> [r (Parameter r)] -> r (Body r) -> Doc pyFunction n ps b = vcat [ pyDef <+> text n <> parens (parameterList ps) <> colon, indent bodyD] where bodyD | isEmpty (RC.body b) = pyNull' | otherwise = RC.body b pyClass :: Label -> Doc -> Doc -> Doc -> Doc -> Doc pyClass n pn s vs fs = vcat [ s <+> classDec <+> text n <> pn <> colon, indent funcSec] where funcSec | isEmpty (vs <> fs) = pyNull' | isEmpty vs = fs | isEmpty fs = vs | otherwise = vcat [vs, blank, fs] pyBlockComment :: [String] -> Doc -> Doc pyBlockComment lns cmt = vcat $ map ((<+>) cmt . text) lns pyDocComment :: [String] -> Doc -> Doc -> Doc pyDocComment [] _ _ = empty pyDocComment (l:lns) start mid = vcat $ start <+> text l : map ((<+>) mid . text) lns
949a160839c312e403989c6aa8e8f7b3b15cbb0afa4939c2a715845f6b8519cd
EligiusSantori/L2Apf
target_selected.scm
(module system racket/base (require "../../packet.scm") (provide game-server-packet/target-selected) (define (game-server-packet/target-selected buffer) (let ((s (open-input-bytes buffer))) (list (cons 'id (read-byte s)) (cons 'object-id (read-int32 #f s)) (cons 'target-id (read-int32 #f s)) (cons 'position (read-point s)) ) ) ) )
null
https://raw.githubusercontent.com/EligiusSantori/L2Apf/30ffe0828e8a401f58d39984efd862c8aeab8c30/packet/game/server/target_selected.scm
scheme
(module system racket/base (require "../../packet.scm") (provide game-server-packet/target-selected) (define (game-server-packet/target-selected buffer) (let ((s (open-input-bytes buffer))) (list (cons 'id (read-byte s)) (cons 'object-id (read-int32 #f s)) (cons 'target-id (read-int32 #f s)) (cons 'position (read-point s)) ) ) ) )
156a2d3ccd26b16a14c10def01fd67623bc81c347b3dcbee50e6a5b06214a89a
OCamlPro/ocp-build
buildActionClean.ml
(**************************************************************************) (* *) (* Typerex Tools *) (* *) Copyright 2011 - 2017 OCamlPro SAS (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU General Public License version 3 described in the file (* LICENSE. *) (* *) (**************************************************************************) (* ocp-build install [OPTIONS] Set the options of the user preference file. *) open Ezcmd.V2 open EZCMD.TYPES open BuildArgs open BuildOptions TODO : handle -arch attribute , ie : - remove only directories in arch/ subdir - do n't remove other topdirectories/ - remove only directories in arch/ subdir - don't remove other topdirectories/ *) let distclean_arg = ref false let arg_list = [ "-distclean", Arg.Set distclean_arg, " Remove _obuild directory"; ] let action () = let project_root = BuildOptions.find_project_root () in let obuild_dir = FileGen.add_basenames project_root [ project_build_dirname ] in let obuild_dir = FileGen.to_string obuild_dir in if !distclean_arg then begin Printf.eprintf "Removing _obuild directory\n%!"; BuildActions.delete_file_or_directory obuild_dir; end else begin Printf.eprintf "Removing build targets\n%!"; begin try let files = Sys.readdir obuild_dir in Array.iter (fun file -> let filename = Filename.concat obuild_dir file in if Sys.is_directory filename then BuildActions.delete_file_or_directory filename; ) files with _ -> () end; () end let subcommand = EZCMD.sub "clean" ~man: [`P "Clean the project."] ~args: ( EZCMD.translate arg_list ) ~doc: "Clean the project." action
null
https://raw.githubusercontent.com/OCamlPro/ocp-build/b29be2f23ebe8db4bd3f16e035770b038876b9bc/tools/ocp-build/actions/buildActionClean.ml
ocaml
************************************************************************ Typerex Tools All rights reserved. This file is distributed under the terms of LICENSE. ************************************************************************ ocp-build install [OPTIONS] Set the options of the user preference file.
Copyright 2011 - 2017 OCamlPro SAS the GNU General Public License version 3 described in the file open Ezcmd.V2 open EZCMD.TYPES open BuildArgs open BuildOptions TODO : handle -arch attribute , ie : - remove only directories in arch/ subdir - do n't remove other topdirectories/ - remove only directories in arch/ subdir - don't remove other topdirectories/ *) let distclean_arg = ref false let arg_list = [ "-distclean", Arg.Set distclean_arg, " Remove _obuild directory"; ] let action () = let project_root = BuildOptions.find_project_root () in let obuild_dir = FileGen.add_basenames project_root [ project_build_dirname ] in let obuild_dir = FileGen.to_string obuild_dir in if !distclean_arg then begin Printf.eprintf "Removing _obuild directory\n%!"; BuildActions.delete_file_or_directory obuild_dir; end else begin Printf.eprintf "Removing build targets\n%!"; begin try let files = Sys.readdir obuild_dir in Array.iter (fun file -> let filename = Filename.concat obuild_dir file in if Sys.is_directory filename then BuildActions.delete_file_or_directory filename; ) files with _ -> () end; () end let subcommand = EZCMD.sub "clean" ~man: [`P "Clean the project."] ~args: ( EZCMD.translate arg_list ) ~doc: "Clean the project." action
05bfbdf529aa56e69d4ecdc81e1bf3adbd56524659617ec7adb03d365912107c
IBM-Watson/kale
login.clj
;; ( C ) Copyright IBM Corp. 2016 All Rights Reserved . ;; (ns kale.login (:require [kale.persistence :refer [write-state]] [kale.aliases :as aliases] [kale.cloud-foundry :as cf] [kale.list :refer [list-working-environment]] [kale.update :refer [get-selections]] [kale.common :refer [fail my-language new-line prompt-user prompt-user-hidden get-options reject-extra-args get-command-msg]] [clojure.string :as str])) (defn get-msg "Return the corresponding login/logout message" [msg-key & args] (apply get-command-msg :login-messages msg-key args)) (defn get-username "Determine the username for login" [state username-arg] (if (some? username-arg) (do (println (get-msg :using-username username-arg)) username-arg) (let [default-username (-> state :login :username) prompt (if (some? default-username) (get-msg :prompt-username-default default-username) (get-msg :prompt-username)) allow-blank? (some? default-username) username (prompt-user prompt allow-blank?)] (if-not (str/blank? username) username (do (println (get-msg :using-username default-username)) default-username))))) (defn check-endpoint "Check if the endpoint provided is valid, which is determined by whether or not it matches a specific pattern" [endpoint] (when (nil? (re-matches #".*bluemix.net" endpoint)) (println (get-msg :invalid-endpoint endpoint)))) (defn get-endpoint "Determine the endpoint for login" [state endpoint-arg] (if (some? endpoint-arg) (do (check-endpoint endpoint-arg) (println (get-msg :using-endpoint endpoint-arg)) endpoint-arg) (let [default-endpoint (or (-> state :login :endpoint) "") endpoint (prompt-user (get-msg :prompt-endpoint-default default-endpoint) true)] (if-not (str/blank? endpoint) endpoint (do (println (get-msg :using-endpoint default-endpoint)) default-endpoint))))) (defn get-env "Get environment variable" [varname] (System/getenv varname)) (defn get-password "Determine the password for login" [] (if-let [password (get-env "KALE_PASSWORD")] (do (println (get-msg :using-password)) password) (prompt-user-hidden (get-msg :prompt-password) false))) (defn attempt-to-get-org "Attempt to retrieve the specified org, and use the local org or first listed org if the specified one doesn't exist" [cf-auth org-name username] (let [orgs (cf/get-organizations cf-auth) attempt (cf/find-entity orgs org-name) ;; This assumes the user hasn't changed the name of their local org default (or (cf/find-entity orgs username) (first orgs))] (when (nil? default) (fail (get-msg :no-orgs-in-region))) (or attempt (do (if org-name (println (get-msg :alternative-org org-name (-> default :entity :name))) (println (get-msg :using-org (-> default :entity :name)))) default)))) (defn attempt-to-get-space "Attempt to retrieve the specified space, and use the first listed space if the specified one doesn't exist" [cf-auth org-guid space-name] (let [spaces (cf/get-spaces cf-auth org-guid) attempt (cf/find-entity spaces space-name) default (first spaces)] (when (nil? default) (fail (get-msg :no-spaces-in-org))) (or attempt (do (if space-name (println (get-msg :alternative-space space-name (-> default :entity :name))) (println (get-msg :using-space (-> default :entity :name)))) default)))) (defn get-org-space "Loads information related the user's current org and space" [cf-auth org-name space-name username] (let [org (attempt-to-get-org cf-auth org-name username) org-guid (-> org :metadata :guid) space (attempt-to-get-space cf-auth org-guid space-name)] {:org (-> org :entity :name) :space (-> space :entity :name) :guid {:org org-guid :space (-> space :metadata :guid)}})) (defn load-user-info "Load information related to the user's environment" [username endpoint access_token state] (let [cf-auth {:url endpoint :token access_token} {:keys [org space]} (state :org-space) org-space (get-org-space cf-auth org space username) space-guid (-> org-space :guid :space) services (do (println (get-msg :loading-services)) (cf/get-services cf-auth space-guid))] {:login {:username username :cf-token access_token :endpoint endpoint} :services services :org-space org-space})) (def login-options {:sso aliases/sso-option}) (defn login "Allow the user to login. Pulls in some access credentials and other information from Bluemix, which runs on Cloud Foundry." [state [cmd endpoint-arg username-arg password-arg & args] flags] (reject-extra-args args cmd) (let [options (get-options flags login-options) endpoint (get-endpoint state endpoint-arg) username (when (nil? (options :sso)) (get-username state username-arg)) password (when (nil? (options :sso)) (get-password)) prev-endpoint? (= endpoint (-> state :login :endpoint)) prev-username? (if (nil? (options :sso)) (= username (-> state :login :username)) true) {:keys [access_token]} (if (some? (options :sso)) (cf/get-oauth-tokens-sso endpoint) (cf/get-oauth-tokens username password endpoint)) user-info (do (println (get-msg :login-start)) (load-user-info ((cf/get-user-data access_token) "user_name") endpoint access_token (merge state (when-not prev-username? {:org-space {}})))) selections (get-selections state (and prev-endpoint? prev-username?)) new-state (merge state user-info selections)] (write-state new-state) (str new-line (get-msg :login-done) new-line new-line (list-working-environment new-state)))) (defn logout "Log the user out, by removing their login information from our persistent state." [state [cmd & args] flags] (reject-extra-args args cmd) (get-options flags {}) (println (get-msg :logout-start)) (write-state (dissoc (update-in (update-in state [:org-space] dissoc :guid) [:login] dissoc :cf-token) :services)) (str new-line (get-msg :logout-done) new-line))
null
https://raw.githubusercontent.com/IBM-Watson/kale/f1c5e312e5db0e3fc01c47dfb965f175b5b0a5b6/src/kale/login.clj
clojure
This assumes the user hasn't changed the name of their local org
( C ) Copyright IBM Corp. 2016 All Rights Reserved . (ns kale.login (:require [kale.persistence :refer [write-state]] [kale.aliases :as aliases] [kale.cloud-foundry :as cf] [kale.list :refer [list-working-environment]] [kale.update :refer [get-selections]] [kale.common :refer [fail my-language new-line prompt-user prompt-user-hidden get-options reject-extra-args get-command-msg]] [clojure.string :as str])) (defn get-msg "Return the corresponding login/logout message" [msg-key & args] (apply get-command-msg :login-messages msg-key args)) (defn get-username "Determine the username for login" [state username-arg] (if (some? username-arg) (do (println (get-msg :using-username username-arg)) username-arg) (let [default-username (-> state :login :username) prompt (if (some? default-username) (get-msg :prompt-username-default default-username) (get-msg :prompt-username)) allow-blank? (some? default-username) username (prompt-user prompt allow-blank?)] (if-not (str/blank? username) username (do (println (get-msg :using-username default-username)) default-username))))) (defn check-endpoint "Check if the endpoint provided is valid, which is determined by whether or not it matches a specific pattern" [endpoint] (when (nil? (re-matches #".*bluemix.net" endpoint)) (println (get-msg :invalid-endpoint endpoint)))) (defn get-endpoint "Determine the endpoint for login" [state endpoint-arg] (if (some? endpoint-arg) (do (check-endpoint endpoint-arg) (println (get-msg :using-endpoint endpoint-arg)) endpoint-arg) (let [default-endpoint (or (-> state :login :endpoint) "") endpoint (prompt-user (get-msg :prompt-endpoint-default default-endpoint) true)] (if-not (str/blank? endpoint) endpoint (do (println (get-msg :using-endpoint default-endpoint)) default-endpoint))))) (defn get-env "Get environment variable" [varname] (System/getenv varname)) (defn get-password "Determine the password for login" [] (if-let [password (get-env "KALE_PASSWORD")] (do (println (get-msg :using-password)) password) (prompt-user-hidden (get-msg :prompt-password) false))) (defn attempt-to-get-org "Attempt to retrieve the specified org, and use the local org or first listed org if the specified one doesn't exist" [cf-auth org-name username] (let [orgs (cf/get-organizations cf-auth) attempt (cf/find-entity orgs org-name) default (or (cf/find-entity orgs username) (first orgs))] (when (nil? default) (fail (get-msg :no-orgs-in-region))) (or attempt (do (if org-name (println (get-msg :alternative-org org-name (-> default :entity :name))) (println (get-msg :using-org (-> default :entity :name)))) default)))) (defn attempt-to-get-space "Attempt to retrieve the specified space, and use the first listed space if the specified one doesn't exist" [cf-auth org-guid space-name] (let [spaces (cf/get-spaces cf-auth org-guid) attempt (cf/find-entity spaces space-name) default (first spaces)] (when (nil? default) (fail (get-msg :no-spaces-in-org))) (or attempt (do (if space-name (println (get-msg :alternative-space space-name (-> default :entity :name))) (println (get-msg :using-space (-> default :entity :name)))) default)))) (defn get-org-space "Loads information related the user's current org and space" [cf-auth org-name space-name username] (let [org (attempt-to-get-org cf-auth org-name username) org-guid (-> org :metadata :guid) space (attempt-to-get-space cf-auth org-guid space-name)] {:org (-> org :entity :name) :space (-> space :entity :name) :guid {:org org-guid :space (-> space :metadata :guid)}})) (defn load-user-info "Load information related to the user's environment" [username endpoint access_token state] (let [cf-auth {:url endpoint :token access_token} {:keys [org space]} (state :org-space) org-space (get-org-space cf-auth org space username) space-guid (-> org-space :guid :space) services (do (println (get-msg :loading-services)) (cf/get-services cf-auth space-guid))] {:login {:username username :cf-token access_token :endpoint endpoint} :services services :org-space org-space})) (def login-options {:sso aliases/sso-option}) (defn login "Allow the user to login. Pulls in some access credentials and other information from Bluemix, which runs on Cloud Foundry." [state [cmd endpoint-arg username-arg password-arg & args] flags] (reject-extra-args args cmd) (let [options (get-options flags login-options) endpoint (get-endpoint state endpoint-arg) username (when (nil? (options :sso)) (get-username state username-arg)) password (when (nil? (options :sso)) (get-password)) prev-endpoint? (= endpoint (-> state :login :endpoint)) prev-username? (if (nil? (options :sso)) (= username (-> state :login :username)) true) {:keys [access_token]} (if (some? (options :sso)) (cf/get-oauth-tokens-sso endpoint) (cf/get-oauth-tokens username password endpoint)) user-info (do (println (get-msg :login-start)) (load-user-info ((cf/get-user-data access_token) "user_name") endpoint access_token (merge state (when-not prev-username? {:org-space {}})))) selections (get-selections state (and prev-endpoint? prev-username?)) new-state (merge state user-info selections)] (write-state new-state) (str new-line (get-msg :login-done) new-line new-line (list-working-environment new-state)))) (defn logout "Log the user out, by removing their login information from our persistent state." [state [cmd & args] flags] (reject-extra-args args cmd) (get-options flags {}) (println (get-msg :logout-start)) (write-state (dissoc (update-in (update-in state [:org-space] dissoc :guid) [:login] dissoc :cf-token) :services)) (str new-line (get-msg :logout-done) new-line))
a645d1483b2d4ca2d9147ea9fa92a215dc5ac9557eea453dec4f235f97a9fd58
verystable/warframe-autobuilder
AutoBuilder.hs
# LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} -- | -- Module : AutoBuilder -- Maintainer : -- Stability : experimental -- This module is the main entry point for Warframe - Autobuilder via ' autoBuilder ' module AutoBuilder ( autoBuilder ) where import ClassyPrelude import Ranker.WeaponRankers import Ranker.ComparatorsGenerator import qualified ArgInterface.ModsMapper.MeleeModsMapper as M import qualified ArgInterface.ModsMapper.PistolModsMapper as P import qualified ArgInterface.ModsMapper.RifleModsMapper as R import qualified ArgInterface.ModsMapper.ShotgunModsMapper as S import ArgInterface.ArgInterface import ArgInterface.WeaponDataDirectoryTest -- | autoBuilder is the main entry function that connects user input parsed into ArgsParse to relavent functions . This function sets some defaults and passes it to ' Ranker . WeaponRankers ' autoBuilder :: IO () autoBuilder = do checkIfDirectoryExists args <- parseArgs let (weaponName'', weaponType'') = fromMaybe ("N/A", "N/A") $ weaponName args case weaponType'' of -- Setting some default cases and passing 'safe' args to rankers "Rifle" -> rifleRanker' (fromMaybe [] $ neededMods args) -- sets needed mods to [] if parsing fails. (fromMaybe R.modList $ unneededMods args) -- sets all available mods to ignore if parsing fails. weaponName'' wraps basic multiplier with Maybe monad and sets 1 as a fallback value . (comparatorGenerator (comparator args)) -- passes parsed comparator name to 'comparatorGenerator' "Shotgun" -> shotgunRanker' (fromMaybe [] $ neededMods args) (fromMaybe S.modList $ unneededMods args) weaponName'' (Just $ fromMaybe 1 $ multiplier2 args) (comparatorGenerator (comparator args)) "Melee" -> meleeRanker' (fromMaybe [] $ neededMods args) (fromMaybe M.modList $ unneededMods args) weaponName'' (Just $ fromMaybe 1 $ multiplier1 args) (Just $ fromMaybe 1 $ multiplier2 args) (comparatorGenerator (comparator args)) "Secondary" -> pistolRanker' (fromMaybe [] $ neededMods args) (fromMaybe P.modList $ unneededMods args) weaponName'' (Just $ fromMaybe 1 $ multiplier2 args) (comparatorGenerator (comparator args)) "Unknown" -> do putStrLn "Could not derive type of weapon:" putStrLn $ pack $ show $ weaponName args wepType -> do putStrLn "Could not find the weapon in database." putStrLn $ "Derived type: " ++ wepType
null
https://raw.githubusercontent.com/verystable/warframe-autobuilder/015e0bb6812711ea27071816d054cbaa1c65770b/src/AutoBuilder.hs
haskell
# LANGUAGE OverloadedStrings # | Module : AutoBuilder Maintainer : Stability : experimental | autoBuilder is the main entry function that connects Setting some default cases and passing 'safe' args to rankers sets needed mods to [] if parsing fails. sets all available mods to ignore if parsing fails. passes parsed comparator name to 'comparatorGenerator'
# LANGUAGE NoImplicitPrelude # This module is the main entry point for Warframe - Autobuilder via ' autoBuilder ' module AutoBuilder ( autoBuilder ) where import ClassyPrelude import Ranker.WeaponRankers import Ranker.ComparatorsGenerator import qualified ArgInterface.ModsMapper.MeleeModsMapper as M import qualified ArgInterface.ModsMapper.PistolModsMapper as P import qualified ArgInterface.ModsMapper.RifleModsMapper as R import qualified ArgInterface.ModsMapper.ShotgunModsMapper as S import ArgInterface.ArgInterface import ArgInterface.WeaponDataDirectoryTest user input parsed into ArgsParse to relavent functions . This function sets some defaults and passes it to ' Ranker . WeaponRankers ' autoBuilder :: IO () autoBuilder = do checkIfDirectoryExists args <- parseArgs let (weaponName'', weaponType'') = fromMaybe ("N/A", "N/A") $ weaponName args case weaponType'' of weaponName'' wraps basic multiplier with Maybe monad and sets 1 as a fallback value . "Shotgun" -> shotgunRanker' (fromMaybe [] $ neededMods args) (fromMaybe S.modList $ unneededMods args) weaponName'' (Just $ fromMaybe 1 $ multiplier2 args) (comparatorGenerator (comparator args)) "Melee" -> meleeRanker' (fromMaybe [] $ neededMods args) (fromMaybe M.modList $ unneededMods args) weaponName'' (Just $ fromMaybe 1 $ multiplier1 args) (Just $ fromMaybe 1 $ multiplier2 args) (comparatorGenerator (comparator args)) "Secondary" -> pistolRanker' (fromMaybe [] $ neededMods args) (fromMaybe P.modList $ unneededMods args) weaponName'' (Just $ fromMaybe 1 $ multiplier2 args) (comparatorGenerator (comparator args)) "Unknown" -> do putStrLn "Could not derive type of weapon:" putStrLn $ pack $ show $ weaponName args wepType -> do putStrLn "Could not find the weapon in database." putStrLn $ "Derived type: " ++ wepType
1aa5123e84ecb1df68f4a91e0e085852ba5266abfb1cc9893f0398335a1b70cc
antoniogarrote/erlfaye
erlfaye_demo_app.erl
%%%---------------------------------------------------------------- @author < > %%% @doc %%% %%% @end 2011 %%%----------------------------------------------------------------, -module(erlfaye_demo_app). -behaviour(application). %% Application callbacks -export([start/2, stop/1, demo/0]). %%%=================================================================== %%% Application callbacks %%%=================================================================== @private -spec start(normal | {takeover, node()} | {failover, node()}, any()) -> {ok, pid()} | {ok, pid(), State::any()} | {error, Reason::any()}. start(_StartType, _StartArgs) -> case erlfaye_demo_sup:start_link() of {ok, Pid} -> {ok, Pid}; Error -> Error end. @private -spec stop(State::any()) -> ok. stop(_State) -> ok. %%%=================================================================== Internal functions %%%=================================================================== demo() -> application:start(erlfaye_demo).
null
https://raw.githubusercontent.com/antoniogarrote/erlfaye/366227ac6c671e557cedb047c620e69ed3f94b3b/erlfaye_demo/src/erlfaye_demo_app.erl
erlang
---------------------------------------------------------------- @doc @end ----------------------------------------------------------------, Application callbacks =================================================================== Application callbacks =================================================================== =================================================================== ===================================================================
@author < > 2011 -module(erlfaye_demo_app). -behaviour(application). -export([start/2, stop/1, demo/0]). @private -spec start(normal | {takeover, node()} | {failover, node()}, any()) -> {ok, pid()} | {ok, pid(), State::any()} | {error, Reason::any()}. start(_StartType, _StartArgs) -> case erlfaye_demo_sup:start_link() of {ok, Pid} -> {ok, Pid}; Error -> Error end. @private -spec stop(State::any()) -> ok. stop(_State) -> ok. Internal functions demo() -> application:start(erlfaye_demo).
673a3be35b31a8b73d676ea10fd5e52b70d61dfb8b4cd8b039f1d1cc12ee8565
netguy204/brianscheme
color.scm
;;; "color.scm" color data-type Copyright 2001 , 2002 ; ;Permission to copy this software, to modify it, to redistribute it, ;to distribute modified versions, and to use it for any purpose is ;granted, subject to the following restrictions and understandings. ; 1 . Any copy made of this software must include this copyright notice ;in full. ; 2 . I have made no warranty or representation that the operation of ;this software will be error-free, and I am under no obligation to ;provide any services, by way of maintenance, update, or otherwise. ; 3 . In conjunction with products arising from the use of this ;material, there shall be no use of my name in any advertising, ;promotional, or sales literature without prior written consent in ;each case. (require 'record) (require 'color-space) (require 'scanf) (require 'printf) (require 'string-case) (require 'multiarg-apply) (define color:rtd (make-record-type "color" '(encoding ;symbol coordinates ;list of coordinates parameter ;white-point or precision ))) (define color:construct (record-constructor color:rtd '(encoding coordinates parameter))) (define color:encoding (record-accessor color:rtd 'encoding)) (define color:coordinates (record-accessor color:rtd 'coordinates)) (define color:parameter (record-accessor color:rtd 'parameter)) (define color:precision color:parameter) (define color:color? (record-predicate color:rtd)) (define (color:white-point color) (case (color:encoding color) ((CIEXYZ RGB709 sRGB xRGB e-sRGB) CIEXYZ:D65) ((L*a*b* L*u*v* L*C*h) (or (color:parameter color) CIEXYZ:D65)))) - based Color Spaces (define (color:helper num-of-nums name list->color) (lambda args (define cnt 0) (for-each (lambda (x) (if (and (< cnt num-of-nums) (not (real? x))) (slib:error name ': 'wrong-type x)) (set! cnt (+ 1 cnt))) args) (or (list->color args) (slib:error name ': 'out-of-range args)))) ;;@noindent ;;@cindex tristimulus The @dfn{tristimulus } color spaces are those whose component values are proportional measurements of light intensity . system provides 3 sets of spectra to dot - product with a spectrum of interest . The result of those dot - products is coordinates in space . All tristimuls color spaces are related to CIEXYZ by linear ;;transforms, namely matrix multiplication. Of the color spaces listed here , and RGB709 are tristimulus spaces . @deftp { Color Space } CIEXYZ ;;The CIEXYZ color space covers the full @dfn{gamut}. ;;It is the basis for color-space conversions. ;; CIEXYZ is a list of three inexact numbers between 0.0 and 1.1 . ' ( 0 . 0 . 0 . ) is black ; ' ( 1 . 1 . 1 . ) is white . ;;@end deftp ;;@body @1 must be a list of 3 numbers . If @1 is valid CIEXYZ coordinates , then @0 returns the color specified by @1 ; otherwise returns # f. (define (CIEXYZ->color XYZ) (and (eqv? 3 (length XYZ)) (apply (lambda (x y z) (and (real? x) (<= -0.001 x) (real? y) (<= -0.001 y 1.001) (real? z) (<= -0.001 z) (color:construct 'CIEXYZ XYZ #f))) XYZ))) @args x y z Returns the CIEXYZ color composed of @1 , @2 , @3 . If the coordinates do not encode a valid CIEXYZ color , then an error is ;;signaled. (define color:CIEXYZ (color:helper 3 'color:CIEXYZ CIEXYZ->color)) @body Returns the list of 3 numbers encoding @1 in . (define (color->CIEXYZ color) (if (not (color:color? color)) (slib:error 'color->CIEXYZ ': 'not 'color? color)) (case (color:encoding color) ((CIEXYZ) (append (color:coordinates color) '())) ((RGB709) (RGB709->CIEXYZ (color:coordinates color))) ((L*a*b*) (L*a*b*->CIEXYZ (color:coordinates color) (color:white-point color))) ((L*u*v*) (L*u*v*->CIEXYZ (color:coordinates color) (color:white-point color))) ((sRGB) (sRGB->CIEXYZ (color:coordinates color))) ((e-sRGB) (e-sRGB->CIEXYZ (color:precision color) (color:coordinates color))) ((L*C*h) (L*a*b*->CIEXYZ (L*C*h->L*a*b* (color:coordinates color)) (color:white-point color))) (else (slib:error 'color->CIEXYZ ': (color:encoding color) color)))) @deftp { Color Space } RGB709 BT.709 - 4 ( 03/00 ) @cite{Parameter values for the HDTV standards for ;;production and international programme exchange} specifies parameter ;;values for chromaticity, sampling, signal format, frame rates, etc., of ;;high definition television signals. ;; An RGB709 color is represented by a list of three inexact numbers between 0.0 and 1.0 . ' ( 0 . 0 . 0 . ) is black ' ( 1 . 1 . 1 . ) is white . ;;@end deftp ;;@body @1 must be a list of 3 numbers . If @1 is valid RGB709 coordinates , then @0 returns the color specified by @1 ; otherwise returns # f. (define (RGB709->color RGB) (and (eqv? 3 (length RGB)) (apply (lambda (r g b) (and (real? r) (<= -0.001 r 1.001) (real? g) (<= -0.001 g 1.001) (real? b) (<= -0.001 b 1.001) (color:construct 'RGB709 RGB #f))) RGB))) @args b Returns the RGB709 color composed of @1 , @2 , @3 . If the coordinates do not encode a valid RGB709 color , then an error is ;;signaled. (define color:RGB709 (color:helper 3 'color:RGB709 RGB709->color)) @body Returns the list of 3 numbers encoding @1 in RGB709 . (define (color->RGB709 color) (if (not (color:color? color)) (slib:error 'color->RGB709 ': 'not 'color? color)) (case (color:encoding color) ((RGB709) (append (color:coordinates color) '())) ((CIEXYZ) (CIEXYZ->RGB709 (color:coordinates color))) (else (CIEXYZ->RGB709 (color->CIEXYZ color))))) Perceptual Uniformity ;;@noindent ;;Although properly encoding the chromaticity, tristimulus spaces do not ;;match the logarithmic response of human visual systems to intensity. ;;Minimum detectable differences between colors correspond to a smaller ;;range of distances (6:1) in the L*a*b* and L*u*v* spaces than in tristimulus spaces ( 80:1 ) . For this reason , color distances are computed in L*a*b * ( or ) . @deftp { Color Space } L*a*b * Is a CIE color space which better matches the human visual system 's perception of color . It is a list of three numbers : @itemize @bullet ;;@item 0 < = L * < = 100 ( CIE @dfn{Lightness } ) ;;@item -500 < = a * < = 500 ;;@item -200 < = b * < = 200 ;;@end itemize ;;@end deftp @args L*a*b * white - point @1 must be a list of 3 numbers . If @1 is valid L*a*b * coordinates , then @0 returns the color specified by @1 ; otherwise returns # f. (define (L*a*b*->color L*a*b* . white-point) (and (list? L*a*b*) (eqv? 3 (length L*a*b*)) (<= 0 (length white-point) 1) (apply (lambda (L* a* b*) (and (real? L*) (<= 0 L* 100) (real? a*) (<= -500 a* 500) (real? b*) (<= -200 b* 200) (color:construct 'L*a*b* L*a*b* (if (null? white-point) #f (color->CIEXYZ (car white-point)))))) L*a*b*))) ;;@args L* a* b* white-point Returns the L*a*b * color composed of @1 , @2 , @3 with @4 . ;;@args L* a* b* Returns the L*a*b * color composed of @1 , @2 , @3 . If the coordinates do not encode a valid L*a*b * color , then an error is signaled . (define color:L*a*b* (color:helper 3 'color:L*a*b* L*a*b*->color)) @args color white - point Returns the list of 3 numbers encoding @1 in L*a*b * with @2 . @args color Returns the list of 3 numbers encoding @1 in L*a*b * . (define (color->L*a*b* color . white-point) (define (wp) (if (null? white-point) CIEXYZ:D65 (color:coordinates (car white-point)))) (if (not (color:color? color)) (slib:error 'color->L*a*b* ': 'not 'color? color)) (case (color:encoding color) ((L*a*b*) (if (equal? (wp) (color:white-point color)) (append (color:coordinates color) '()) (CIEXYZ->L*a*b* (L*a*b*->CIEXYZ (color:coordinates color) (color:white-point color)) (wp)))) ((L*u*v*) (CIEXYZ->L*a*b* (L*u*v*->CIEXYZ (color:coordinates color) (color:white-point color)) (wp))) ((L*C*h) (if (equal? (wp) (color:white-point color)) (L*C*h->L*a*b* (color:coordinates color)) (CIEXYZ->L*a*b* (L*a*b*->CIEXYZ (L*C*h->L*a*b* (color:coordinates color)) (color:white-point color)) (wp)))) ((CIEXYZ) (CIEXYZ->L*a*b* (color:coordinates color) (wp))) (else (CIEXYZ->L*a*b* (color->CIEXYZ color) (wp))))) @deftp { Color Space } L*u*v * Is another CIE encoding designed to better match the human visual ;;system's perception of color. ;;@end deftp @args L*u*v * white - point @1 must be a list of 3 numbers . If @1 is valid L*u*v * coordinates , then @0 returns the color specified by @1 ; otherwise returns # f. (define (L*u*v*->color L*u*v* . white-point) (and (list? L*u*v*) (eqv? 3 (length L*u*v*)) (<= 0 (length white-point) 1) (apply (lambda (L* u* v*) (and (real? L*) (<= 0 L* 100) (real? u*) (<= -500 u* 500) (real? v*) (<= -200 v* 200) (color:construct 'L*u*v* L*u*v* (if (null? white-point) #f (color->CIEXYZ (car white-point)))))) L*u*v*))) ;;@args L* u* v* white-point Returns the L*u*v * color composed of @1 , @2 , @3 with @4 . ;;@args L* u* v* Returns the L*u*v * color composed of @1 , @2 , @3 . If the coordinates ;;do not encode a valid L*u*v* color, then an error is signaled. (define color:L*u*v* (color:helper 3 'color:L*u*v* L*u*v*->color)) @args color white - point Returns the list of 3 numbers encoding @1 in L*u*v * with @2 . @args color Returns the list of 3 numbers encoding @1 in L*u*v * . (define (color->L*u*v* color . white-point) (define (wp) (if (null? white-point) (color:white-point color) (car white-point))) (if (not (color:color? color)) (slib:error 'color->L*u*v* ': 'not 'color? color)) (case (color:encoding color) ((L*u*v*) (append (color:coordinates color) '())) ((L*a*b*) (CIEXYZ->L*u*v* (L*a*b*->CIEXYZ (color:coordinates color) (color:white-point color)) (wp))) ((L*C*h) (CIEXYZ->L*u*v* (L*a*b*->CIEXYZ (L*C*h->L*a*b* (color:coordinates color)) (color:white-point color)) (wp))) ((CIEXYZ) (CIEXYZ->L*u*v* (color:coordinates color) (wp))) (else (CIEXYZ->L*u*v* (color->CIEXYZ color) (wp))))) Coordinates ;;@noindent HSL ( Hue Saturation Lightness ) , HSV ( Hue Saturation Value ) , HSI ( Hue Saturation Intensity ) and HCI ( Hue Chroma Intensity ) are cylindrical ;;color spaces (with angle hue). But these spaces are all defined in terms device - dependent RGB spaces . ;;@noindent ;;One might wonder if there is some fundamental reason why intuitive ;;specification of color must be device-dependent. But take heart! A cylindrical system can be based on L*a*b * and is used for predicting how ;;close colors seem to observers. @deftp { Color Space } L*C*h ;;Expresses the *a and b* of L*a*b* in polar coordinates. It is a list of three numbers : @itemize @bullet ;;@item 0 < = L * < = 100 ( CIE @dfn{Lightness } ) ;;@item C * ( CIE @dfn{Chroma } ) is the distance from the neutral ( gray ) axis . ;;@item 0 < = h < = 360 ( CIE @dfn{Hue } ) is the angle . ;;@end itemize ;; ;;The colors by quadrant of h are: ;;@multitable @columnfractions .20 .60 .20 @item 0 @tab red , orange , yellow @tab 90 @item 90 @tab yellow , yellow - green , green @tab 180 @item 180 @tab green , cyan ( blue - green ) , blue @tab 270 @item 270 @tab blue , purple , magenta @tab 360 ;;@end multitable ;;@end deftp @args white - point @1 must be a list of 3 numbers . If @1 is valid coordinates , then @0 returns the color specified by @1 ; otherwise returns # f. (define (L*C*h->color L*C*h . white-point) (and (list? L*C*h) (eqv? 3 (length L*C*h)) (<= 0 (length white-point) 1) (apply (lambda (L* C* h) (and (real? L*) (<= 0 L* 100) (real? C*) (<= 0 C*) (real? h) (<= 0 h 360) (color:construct 'L*C*h L*C*h (if (null? white-point) #f (color->CIEXYZ (car white-point)))))) L*C*h))) ;;@args L* C* h white-point Returns the color composed of @1 , @2 , @3 with @4 . ;;@args L* C* h Returns the color composed of @1 , @2 , @3 . If the coordinates do not encode a valid color , then an error is signaled . (define color:L*C*h (color:helper 3 'color:L*C*h L*C*h->color)) @args color white - point Returns the list of 3 numbers encoding @1 in with @2 . @args color Returns the list of 3 numbers encoding @1 in . (define (color->L*C*h color . white-point) (if (not (color:color? color)) (slib:error 'color->L*C*h ': 'not 'color? color)) (if (and (eqv? 'L*C*h (color:encoding color)) (equal? (color:white-point color) (if (null? white-point) CIEXYZ:D65 (color:coordinates (car white-point))))) (append (color:coordinates color) '()) (L*a*b*->L*C*h (apply color->L*a*b* color white-point)))) Digital Color Spaces ;;@noindent ;;The color spaces discussed so far are impractical for image data because of numerical precision and computational requirements . In 1998 the IEC ;;adopted @cite{A Standard Default Color Space for the Internet - sRGB} ( @url{ / Graphics / Color / sRGB } ) . sRGB was cleverly designed to employ the 24 - bit ( 256x256x256 ) color encoding already in widespread use ; and the 2.2 gamma intrinsic to CRT monitors . ;;@noindent ;;Conversion from CIEXYZ to digital (sRGB) color spaces is accomplished by conversion first to a RGB709 tristimulus space with D65 white - point ; ;;then each coordinate is individually subjected to the same non-linear ;;mapping. Inverse operations in the reverse order create the inverse ;;transform. @deftp { Color Space } sRGB Is " A Standard Default Color Space for the Internet " . Most display monitors will work fairly well with sRGB directly . Systems using ICC ;;profiles @ftindex ICC Profile ;;@footnote{ ;;@noindent A comprehensive encoding of transforms between CIEXYZ and device color spaces is the International Color Consortium profile format , ;;ICC.1:1998-09: ;;@quotation ;;The intent of this format is to provide a cross-platform device profile ;;format. Such device profiles can be used to translate color data created on one device into another device 's native color space . ;;@end quotation ;;} ;;should work very well with sRGB. An sRGB color is a triplet of integers ranging 0 to 255 . D65 is the ;;white-point for sRGB. ;;@end deftp ;;@body @1 must be a list of 3 numbers . If @1 is valid sRGB coordinates , then @0 returns the color specified by @1 ; otherwise returns # f. (define (sRGB->color RGB) (and (eqv? 3 (length RGB)) (apply (lambda (r g b) (and (integer? r) (<= 0 r 255) (integer? g) (<= 0 g 255) (integer? b) (<= 0 b 255) (color:construct 'sRGB RGB #f))) RGB))) @args b Returns the sRGB color composed of @1 , @2 , @3 . If the ;;coordinates do not encode a valid sRGB color, then an error is ;;signaled. (define color:sRGB (color:helper 3 'color:sRGB sRGB->color)) @deftp { Color Space } xRGB Represents the equivalent sRGB color with a single 24 - bit integer . The most significant 8 bits encode red , the middle 8 bits blue , and the least significant 8 bits green . ;;@end deftp ;;@body Returns the list of 3 integers encoding @1 in sRGB . (define (color->sRGB color) (if (not (color:color? color)) (slib:error 'color->sRGB ': 'not 'color? color)) (case (color:encoding color) ((CIEXYZ) (CIEXYZ->sRGB (color:coordinates color))) ((sRGB) (append (color:coordinates color) '())) (else (CIEXYZ->sRGB (color->CIEXYZ color))))) @body Returns the 24 - bit integer encoding @1 in sRGB . (define (color->xRGB color) (sRGB->xRGB (color->sRGB color))) @args k Returns the sRGB color composed of the 24 - bit integer @1 . (define (xRGB->color xRGB) (and (integer? xRGB) (<= 0 xRGB #xffffff) (sRGB->color (xRGB->sRGB xRGB)))) @deftp { Color Space } e - sRGB Is " Photography - Electronic still picture imaging - Extended sRGB color ;;encoding" (PIMA 7667:2001). It extends the gamut of sRGB; and its ;;higher precision numbers provide a larger dynamic range. ;; A triplet of integers represent e - sRGB colors . Three precisions are ;;supported: ;;@table @r e - sRGB10 0 to 1023 e - sRGB12 0 to 4095 e - sRGB16 0 to 65535 ;;@end table ;;@end deftp (define (esRGB->color prec-RGB) (and (eqv? 4 (length prec-RGB)) (let ((range (and (pair? prec-RGB) (case (car prec-RGB) ((10) 1023) ((12) 4095) ((16) 65535) (else #f))))) (apply (lambda (precision r g b) (and (integer? r) (<= 0 r range) (integer? g) (<= 0 g range) (integer? b) (<= 0 b range) (color:construct 'e-sRGB (cdr prec-RGB) precision))) prec-RGB)))) @body @1 must be the integer 10 , 12 , or 16 . @2 must be a list of 3 numbers . If @2 is valid e - sRGB coordinates , then @0 returns the color specified by @2 ; otherwise returns # f. (define (e-sRGB->color precision RGB) (esRGB->color (cons precision RGB))) @args 10 r g b Returns the e - sRGB10 color composed of integers @2 , @3 , @4 . @args 12 r g b Returns the e - sRGB12 color composed of integers @2 , @3 , @4 . @args 16 r g b Returns the e - sRGB16 color composed of integers @2 , @3 , @4 . ;;If the coordinates do not encode a valid e-sRGB color, then an error ;;is signaled. (define color:e-sRGB (color:helper 4 'color:e-sRGB esRGB->color)) @body @1 must be the integer 10 , 12 , or 16 . @0 returns the list of 3 integers encoding @2 in sRGB10 , sRGB12 , or sRGB16 . (define (color->e-sRGB precision color) (case precision ((10 12 16) (if (not (color:color? color)) (slib:error 'color->e-sRGB ': 'not 'color? color))) (else (slib:error 'color->e-sRGB ': 'invalid 'precision precision))) (case (color:encoding color) ((e-sRGB) (e-sRGB->e-sRGB (color:precision color) (color:coordinates color) precision)) ((sRGB) (sRGB->e-sRGB precision (color:coordinates color))) (else (CIEXYZ->e-sRGB precision (color->CIEXYZ color))))) ;;;; Polytypic Colors ;;; The rest of documentation is in "slib.texi" ;@ (define D65 (CIEXYZ->color CIEXYZ:D65)) (define D50 (CIEXYZ->color CIEXYZ:D50)) ;@ (define (color? obj . typ) (cond ((not (color:color? obj)) #f) ((null? typ) #t) (else (eqv? (car typ) (color:encoding obj))))) ;@ (define (make-color space . args) (apply (case space ((CIEXYZ) CIEXYZ->color) ((RGB709) RGB709->color) ((L*a*b*) L*a*b*->color) ((L*u*v*) L*u*v*->color) ((L*C*h) L*C*h->color) ((sRGB) sRGB->color) ((xRGB) xRGB->color) ((e-sRGB) e-sRGB->color) (else (slib:error 'make-color ': 'not 'space? space))) args)) ;@ (define color-space color:encoding) ;@ (define (color-precision color) (if (not (color:color? color)) (slib:error 'color-precision ': 'not 'color? color)) (case (color:encoding color) ((e-sRGB) (color:precision color)) ((sRGB) 8) (else #f))) ;@ (define (color-white-point color) (if (not (color:color? color)) (slib:error 'color-white-point ': 'not 'color? color)) (case (color:encoding color) ((L*a*b*) (color:CIEXYZ (color:white-point color))) ((L*u*v*) (color:CIEXYZ (color:white-point color))) ((L*C*h) (color:CIEXYZ (color:white-point color))) ((RGB709) D65) ((sRGB) D65) ((e-sRGB) D65) (else #f))) ;@ (define (convert-color color encoding . opt-arg) (define (noarg) (if (not (null? opt-arg)) (slib:error 'convert-color ': 'too-many 'arguments opt-arg))) (if (not (color:color? color)) (slib:error 'convert-color ': 'not 'color? color)) (case encoding ((CIEXYZ) (noarg) (CIEXYZ->color (color->CIEXYZ color))) ((RGB709) (noarg) (RGB709->color (color->RGB709 color))) ((sRGB) (noarg) (sRGB->color (color->sRGB color))) ((e-sRGB) (e-sRGB->color (car opt-arg) (color->e-sRGB (car opt-arg) color))) ((L*a*b*) (apply L*a*b*->color (color->L*a*b* color) opt-arg)) ((L*u*v*) (apply L*u*v*->color (color->L*u*v* color) opt-arg)) ((L*C*h) (apply L*C*h->color (color->L*C*h color) opt-arg)) (else (slib:error 'convert-color ': encoding '?)))) ;;; External color representations ;@ (define (color->string color) (if (not (color:color? color)) (slib:error 'color->string ': 'not 'color? color)) (case (color:encoding color) ((CIEXYZ) (apply sprintf #f "CIEXYZ:%g/%g/%g" (color:coordinates color))) ((L*a*b*) (apply sprintf #f "CIELab:%.2f/%.2f/%.2f" (if (equal? CIEXYZ:D65 (color:white-point color)) (color:coordinates color) (CIEXYZ->L*a*b* (L*a*b*->CIEXYZ (color:coordinates color) (color:white-point color)))))) ((L*u*v*) (apply sprintf #f "CIELuv:%.2f/%.2f/%.2f" (if (equal? CIEXYZ:D65 (color:white-point color)) (color:coordinates color) (CIEXYZ->L*u*v* (L*u*v*->CIEXYZ (color:coordinates color) (color:white-point color)))))) ((L*C*h) (apply sprintf #f "CIELCh:%.2f/%.2f/%.2f" (if (equal? CIEXYZ:D65 (color:white-point color)) (color:coordinates color) (L*a*b*->L*C*h (CIEXYZ->L*a*b* (L*a*b*->CIEXYZ (L*C*h->L*a*b* (color:coordinates color)) (color:white-point color))))))) ((RGB709) (apply sprintf #f "RGBi:%g/%g/%g" (color:coordinates color))) ((sRGB) (apply sprintf #f "sRGB:%d/%d/%d" (color:coordinates color))) ((e-sRGB) (apply sprintf #f "e-sRGB%d:%d/%d/%d" (color:precision color) (color:coordinates color))) (else (slib:error 'color->string ': (color:encoding color) color)))) ;@ (define (string->color str) (define prec #f) (define coding #f) (define x #f) (define y #f) (define z #f) (cond ((eqv? 4 (sscanf str " %[CIEXYZciexyzLABUVlabuvHhRrGg709]:%f/%f/%f" coding x y z)) (case (string-ci->symbol coding) ((CIEXYZ) (color:CIEXYZ x y z)) ((CIELab) (color:L*a*b* x y z)) ((CIELuv) (color:L*u*v* x y z)) ((CIELCh) (color:L*C*h x y z)) Xlib - C Language X Interface RGB709) (color:RGB709 x y z)) (else #f))) ((eqv? 4 (sscanf str " %[sRGBSrgb]:%d/%d/%d" coding x y z)) (case (string-ci->symbol coding) ((sRGB) (color:sRGB x y z)) (else #f))) ((eqv? 5 (sscanf str " %[-esRGBESrgb]%d:%d/%d/%d" coding prec x y z)) (case (string-ci->symbol coding) ((e-sRGB) (color:e-sRGB prec x y z)) (else #f))) ((eqv? 2 (sscanf str " %[sRGBxXXRGB]:%6x%[/0-9a-fA-F]" coding x y)) (case (string-ci->symbol coding) ((sRGB xRGB sRGBx) (xRGB->color x)) (else #f))) ((and (eqv? 1 (sscanf str " #%6[0-9a-fA-F]%[0-9a-fA-F]" x y)) (eqv? 6 (string-length x))) (xRGB->color (string->number x 16))) ((and (eqv? 2 (sscanf str " %[#0xX]%6[0-9a-fA-F]%[0-9a-fA-F]" coding x y)) (eqv? 6 (string-length x)) (member coding '("#" "#x" "0x" "#X" "0X"))) (xRGB->color (string->number x 16))) (else #f))) ;;;; visual color metrics ;@ (define (CIE:DE* color1 color2 . white-point) (L*a*b*:DE* (apply color->L*a*b* color1 white-point) (apply color->L*a*b* color2 white-point))) ;@ (define (CIE:DE*94 color1 color2 . parametric-factors) (apply L*C*h:DE*94 (color->L*C*h color1) (color->L*C*h color2) parametric-factors)) ;@ (define (CMC:DE* color1 color2 . parametric-factors) (apply CMC-DE (color->L*C*h color1) (color->L*C*h color2) parametric-factors)) ;;; Short names ;; (define CIEXYZ color:CIEXYZ) ( define RGB709 color : RGB709 ) ( define L*a*b * color : L*a*b * ) ;; (define L*u*v* color:L*u*v*) ( define color : ) ;; (define sRGB color:sRGB) ( define xRGB ) ;; (define e-sRGB color:e-sRGB)
null
https://raw.githubusercontent.com/netguy204/brianscheme/1b7d7b35485ffdec3b76113064191062e3874efa/slib/color.scm
scheme
"color.scm" color data-type Permission to copy this software, to modify it, to redistribute it, to distribute modified versions, and to use it for any purpose is granted, subject to the following restrictions and understandings. in full. this software will be error-free, and I am under no obligation to provide any services, by way of maintenance, update, or otherwise. material, there shall be no use of my name in any advertising, promotional, or sales literature without prior written consent in each case. symbol list of coordinates white-point or precision @noindent @cindex tristimulus transforms, namely matrix multiplication. Of the color spaces listed The CIEXYZ color space covers the full @dfn{gamut}. It is the basis for color-space conversions. ' ( 1 . 1 . 1 . ) is white . @end deftp @body otherwise returns # f. signaled. production and international programme exchange} specifies parameter values for chromaticity, sampling, signal format, frame rates, etc., of high definition television signals. @end deftp @body otherwise returns # f. signaled. @noindent Although properly encoding the chromaticity, tristimulus spaces do not match the logarithmic response of human visual systems to intensity. Minimum detectable differences between colors correspond to a smaller range of distances (6:1) in the L*a*b* and L*u*v* spaces than in @item @item @item @end itemize @end deftp otherwise returns # f. @args L* a* b* white-point @args L* a* b* system's perception of color. @end deftp otherwise returns # f. @args L* u* v* white-point @args L* u* v* do not encode a valid L*u*v* color, then an error is signaled. @noindent color spaces (with angle hue). But these spaces are all defined in @noindent One might wonder if there is some fundamental reason why intuitive specification of color must be device-dependent. But take heart! A close colors seem to observers. Expresses the *a and b* of L*a*b* in polar coordinates. It is a list of @item @item @item @end itemize The colors by quadrant of h are: @multitable @columnfractions .20 .60 .20 @end multitable @end deftp otherwise returns # f. @args L* C* h white-point @args L* C* h @noindent The color spaces discussed so far are impractical for image data because adopted @cite{A Standard Default Color Space for the Internet - sRGB} and the 2.2 gamma intrinsic to CRT monitors . @noindent Conversion from CIEXYZ to digital (sRGB) color spaces is accomplished by then each coordinate is individually subjected to the same non-linear mapping. Inverse operations in the reverse order create the inverse transform. profiles @footnote{ @noindent ICC.1:1998-09: @quotation The intent of this format is to provide a cross-platform device profile format. Such device profiles can be used to translate color data @end quotation } should work very well with sRGB. white-point for sRGB. @end deftp @body otherwise returns # f. coordinates do not encode a valid sRGB color, then an error is signaled. @end deftp @body encoding" (PIMA 7667:2001). It extends the gamut of sRGB; and its higher precision numbers provide a larger dynamic range. supported: @table @r @end table @end deftp otherwise returns # f. If the coordinates do not encode a valid e-sRGB color, then an error is signaled. Polytypic Colors The rest of documentation is in "slib.texi" @ @ @ @ @ @ @ External color representations @ @ visual color metrics @ @ @ Short names (define CIEXYZ color:CIEXYZ) (define L*u*v* color:L*u*v*) (define sRGB color:sRGB) (define e-sRGB color:e-sRGB)
Copyright 2001 , 2002 1 . Any copy made of this software must include this copyright notice 2 . I have made no warranty or representation that the operation of 3 . In conjunction with products arising from the use of this (require 'record) (require 'color-space) (require 'scanf) (require 'printf) (require 'string-case) (require 'multiarg-apply) (define color:rtd (make-record-type "color" ))) (define color:construct (record-constructor color:rtd '(encoding coordinates parameter))) (define color:encoding (record-accessor color:rtd 'encoding)) (define color:coordinates (record-accessor color:rtd 'coordinates)) (define color:parameter (record-accessor color:rtd 'parameter)) (define color:precision color:parameter) (define color:color? (record-predicate color:rtd)) (define (color:white-point color) (case (color:encoding color) ((CIEXYZ RGB709 sRGB xRGB e-sRGB) CIEXYZ:D65) ((L*a*b* L*u*v* L*C*h) (or (color:parameter color) CIEXYZ:D65)))) - based Color Spaces (define (color:helper num-of-nums name list->color) (lambda args (define cnt 0) (for-each (lambda (x) (if (and (< cnt num-of-nums) (not (real? x))) (slib:error name ': 'wrong-type x)) (set! cnt (+ 1 cnt))) args) (or (list->color args) (slib:error name ': 'out-of-range args)))) The @dfn{tristimulus } color spaces are those whose component values are proportional measurements of light intensity . system provides 3 sets of spectra to dot - product with a spectrum of interest . The result of those dot - products is coordinates in space . All tristimuls color spaces are related to CIEXYZ by linear here , and RGB709 are tristimulus spaces . @deftp { Color Space } CIEXYZ CIEXYZ is a list of three inexact numbers between 0.0 and 1.1 . @1 must be a list of 3 numbers . If @1 is valid CIEXYZ coordinates , (define (CIEXYZ->color XYZ) (and (eqv? 3 (length XYZ)) (apply (lambda (x y z) (and (real? x) (<= -0.001 x) (real? y) (<= -0.001 y 1.001) (real? z) (<= -0.001 z) (color:construct 'CIEXYZ XYZ #f))) XYZ))) @args x y z Returns the CIEXYZ color composed of @1 , @2 , @3 . If the coordinates do not encode a valid CIEXYZ color , then an error is (define color:CIEXYZ (color:helper 3 'color:CIEXYZ CIEXYZ->color)) @body Returns the list of 3 numbers encoding @1 in . (define (color->CIEXYZ color) (if (not (color:color? color)) (slib:error 'color->CIEXYZ ': 'not 'color? color)) (case (color:encoding color) ((CIEXYZ) (append (color:coordinates color) '())) ((RGB709) (RGB709->CIEXYZ (color:coordinates color))) ((L*a*b*) (L*a*b*->CIEXYZ (color:coordinates color) (color:white-point color))) ((L*u*v*) (L*u*v*->CIEXYZ (color:coordinates color) (color:white-point color))) ((sRGB) (sRGB->CIEXYZ (color:coordinates color))) ((e-sRGB) (e-sRGB->CIEXYZ (color:precision color) (color:coordinates color))) ((L*C*h) (L*a*b*->CIEXYZ (L*C*h->L*a*b* (color:coordinates color)) (color:white-point color))) (else (slib:error 'color->CIEXYZ ': (color:encoding color) color)))) @deftp { Color Space } RGB709 BT.709 - 4 ( 03/00 ) @cite{Parameter values for the HDTV standards for An RGB709 color is represented by a list of three inexact numbers between 0.0 and 1.0 . ' ( 0 . 0 . 0 . ) is black ' ( 1 . 1 . 1 . ) is white . @1 must be a list of 3 numbers . If @1 is valid RGB709 coordinates , (define (RGB709->color RGB) (and (eqv? 3 (length RGB)) (apply (lambda (r g b) (and (real? r) (<= -0.001 r 1.001) (real? g) (<= -0.001 g 1.001) (real? b) (<= -0.001 b 1.001) (color:construct 'RGB709 RGB #f))) RGB))) @args b Returns the RGB709 color composed of @1 , @2 , @3 . If the coordinates do not encode a valid RGB709 color , then an error is (define color:RGB709 (color:helper 3 'color:RGB709 RGB709->color)) @body Returns the list of 3 numbers encoding @1 in RGB709 . (define (color->RGB709 color) (if (not (color:color? color)) (slib:error 'color->RGB709 ': 'not 'color? color)) (case (color:encoding color) ((RGB709) (append (color:coordinates color) '())) ((CIEXYZ) (CIEXYZ->RGB709 (color:coordinates color))) (else (CIEXYZ->RGB709 (color->CIEXYZ color))))) Perceptual Uniformity tristimulus spaces ( 80:1 ) . For this reason , color distances are computed in L*a*b * ( or ) . @deftp { Color Space } L*a*b * Is a CIE color space which better matches the human visual system 's perception of color . It is a list of three numbers : @itemize @bullet 0 < = L * < = 100 ( CIE @dfn{Lightness } ) -500 < = a * < = 500 -200 < = b * < = 200 @args L*a*b * white - point @1 must be a list of 3 numbers . If @1 is valid L*a*b * coordinates , (define (L*a*b*->color L*a*b* . white-point) (and (list? L*a*b*) (eqv? 3 (length L*a*b*)) (<= 0 (length white-point) 1) (apply (lambda (L* a* b*) (and (real? L*) (<= 0 L* 100) (real? a*) (<= -500 a* 500) (real? b*) (<= -200 b* 200) (color:construct 'L*a*b* L*a*b* (if (null? white-point) #f (color->CIEXYZ (car white-point)))))) L*a*b*))) Returns the L*a*b * color composed of @1 , @2 , @3 with @4 . Returns the L*a*b * color composed of @1 , @2 , @3 . If the coordinates do not encode a valid L*a*b * color , then an error is signaled . (define color:L*a*b* (color:helper 3 'color:L*a*b* L*a*b*->color)) @args color white - point Returns the list of 3 numbers encoding @1 in L*a*b * with @2 . @args color Returns the list of 3 numbers encoding @1 in L*a*b * . (define (color->L*a*b* color . white-point) (define (wp) (if (null? white-point) CIEXYZ:D65 (color:coordinates (car white-point)))) (if (not (color:color? color)) (slib:error 'color->L*a*b* ': 'not 'color? color)) (case (color:encoding color) ((L*a*b*) (if (equal? (wp) (color:white-point color)) (append (color:coordinates color) '()) (CIEXYZ->L*a*b* (L*a*b*->CIEXYZ (color:coordinates color) (color:white-point color)) (wp)))) ((L*u*v*) (CIEXYZ->L*a*b* (L*u*v*->CIEXYZ (color:coordinates color) (color:white-point color)) (wp))) ((L*C*h) (if (equal? (wp) (color:white-point color)) (L*C*h->L*a*b* (color:coordinates color)) (CIEXYZ->L*a*b* (L*a*b*->CIEXYZ (L*C*h->L*a*b* (color:coordinates color)) (color:white-point color)) (wp)))) ((CIEXYZ) (CIEXYZ->L*a*b* (color:coordinates color) (wp))) (else (CIEXYZ->L*a*b* (color->CIEXYZ color) (wp))))) @deftp { Color Space } L*u*v * Is another CIE encoding designed to better match the human visual @args L*u*v * white - point @1 must be a list of 3 numbers . If @1 is valid L*u*v * coordinates , (define (L*u*v*->color L*u*v* . white-point) (and (list? L*u*v*) (eqv? 3 (length L*u*v*)) (<= 0 (length white-point) 1) (apply (lambda (L* u* v*) (and (real? L*) (<= 0 L* 100) (real? u*) (<= -500 u* 500) (real? v*) (<= -200 v* 200) (color:construct 'L*u*v* L*u*v* (if (null? white-point) #f (color->CIEXYZ (car white-point)))))) L*u*v*))) Returns the L*u*v * color composed of @1 , @2 , @3 with @4 . Returns the L*u*v * color composed of @1 , @2 , @3 . If the coordinates (define color:L*u*v* (color:helper 3 'color:L*u*v* L*u*v*->color)) @args color white - point Returns the list of 3 numbers encoding @1 in L*u*v * with @2 . @args color Returns the list of 3 numbers encoding @1 in L*u*v * . (define (color->L*u*v* color . white-point) (define (wp) (if (null? white-point) (color:white-point color) (car white-point))) (if (not (color:color? color)) (slib:error 'color->L*u*v* ': 'not 'color? color)) (case (color:encoding color) ((L*u*v*) (append (color:coordinates color) '())) ((L*a*b*) (CIEXYZ->L*u*v* (L*a*b*->CIEXYZ (color:coordinates color) (color:white-point color)) (wp))) ((L*C*h) (CIEXYZ->L*u*v* (L*a*b*->CIEXYZ (L*C*h->L*a*b* (color:coordinates color)) (color:white-point color)) (wp))) ((CIEXYZ) (CIEXYZ->L*u*v* (color:coordinates color) (wp))) (else (CIEXYZ->L*u*v* (color->CIEXYZ color) (wp))))) Coordinates HSL ( Hue Saturation Lightness ) , HSV ( Hue Saturation Value ) , HSI ( Hue Saturation Intensity ) and HCI ( Hue Chroma Intensity ) are cylindrical terms device - dependent RGB spaces . cylindrical system can be based on L*a*b * and is used for predicting how @deftp { Color Space } L*C*h three numbers : @itemize @bullet 0 < = L * < = 100 ( CIE @dfn{Lightness } ) C * ( CIE @dfn{Chroma } ) is the distance from the neutral ( gray ) axis . 0 < = h < = 360 ( CIE @dfn{Hue } ) is the angle . @item 0 @tab red , orange , yellow @tab 90 @item 90 @tab yellow , yellow - green , green @tab 180 @item 180 @tab green , cyan ( blue - green ) , blue @tab 270 @item 270 @tab blue , purple , magenta @tab 360 @args white - point @1 must be a list of 3 numbers . If @1 is valid coordinates , (define (L*C*h->color L*C*h . white-point) (and (list? L*C*h) (eqv? 3 (length L*C*h)) (<= 0 (length white-point) 1) (apply (lambda (L* C* h) (and (real? L*) (<= 0 L* 100) (real? C*) (<= 0 C*) (real? h) (<= 0 h 360) (color:construct 'L*C*h L*C*h (if (null? white-point) #f (color->CIEXYZ (car white-point)))))) L*C*h))) Returns the color composed of @1 , @2 , @3 with @4 . Returns the color composed of @1 , @2 , @3 . If the coordinates do not encode a valid color , then an error is signaled . (define color:L*C*h (color:helper 3 'color:L*C*h L*C*h->color)) @args color white - point Returns the list of 3 numbers encoding @1 in with @2 . @args color Returns the list of 3 numbers encoding @1 in . (define (color->L*C*h color . white-point) (if (not (color:color? color)) (slib:error 'color->L*C*h ': 'not 'color? color)) (if (and (eqv? 'L*C*h (color:encoding color)) (equal? (color:white-point color) (if (null? white-point) CIEXYZ:D65 (color:coordinates (car white-point))))) (append (color:coordinates color) '()) (L*a*b*->L*C*h (apply color->L*a*b* color white-point)))) Digital Color Spaces of numerical precision and computational requirements . In 1998 the IEC ( @url{ / Graphics / Color / sRGB } ) . sRGB was cleverly designed to employ the 24 - bit ( 256x256x256 ) color encoding already in @deftp { Color Space } sRGB Is " A Standard Default Color Space for the Internet " . Most display monitors will work fairly well with sRGB directly . Systems using ICC @ftindex ICC Profile A comprehensive encoding of transforms between CIEXYZ and device color spaces is the International Color Consortium profile format , created on one device into another device 's native color space . An sRGB color is a triplet of integers ranging 0 to 255 . D65 is the @1 must be a list of 3 numbers . If @1 is valid sRGB coordinates , (define (sRGB->color RGB) (and (eqv? 3 (length RGB)) (apply (lambda (r g b) (and (integer? r) (<= 0 r 255) (integer? g) (<= 0 g 255) (integer? b) (<= 0 b 255) (color:construct 'sRGB RGB #f))) RGB))) @args b Returns the sRGB color composed of @1 , @2 , @3 . If the (define color:sRGB (color:helper 3 'color:sRGB sRGB->color)) @deftp { Color Space } xRGB Represents the equivalent sRGB color with a single 24 - bit integer . The most significant 8 bits encode red , the middle 8 bits blue , and the least significant 8 bits green . Returns the list of 3 integers encoding @1 in sRGB . (define (color->sRGB color) (if (not (color:color? color)) (slib:error 'color->sRGB ': 'not 'color? color)) (case (color:encoding color) ((CIEXYZ) (CIEXYZ->sRGB (color:coordinates color))) ((sRGB) (append (color:coordinates color) '())) (else (CIEXYZ->sRGB (color->CIEXYZ color))))) @body Returns the 24 - bit integer encoding @1 in sRGB . (define (color->xRGB color) (sRGB->xRGB (color->sRGB color))) @args k Returns the sRGB color composed of the 24 - bit integer @1 . (define (xRGB->color xRGB) (and (integer? xRGB) (<= 0 xRGB #xffffff) (sRGB->color (xRGB->sRGB xRGB)))) @deftp { Color Space } e - sRGB Is " Photography - Electronic still picture imaging - Extended sRGB color A triplet of integers represent e - sRGB colors . Three precisions are e - sRGB10 0 to 1023 e - sRGB12 0 to 4095 e - sRGB16 0 to 65535 (define (esRGB->color prec-RGB) (and (eqv? 4 (length prec-RGB)) (let ((range (and (pair? prec-RGB) (case (car prec-RGB) ((10) 1023) ((12) 4095) ((16) 65535) (else #f))))) (apply (lambda (precision r g b) (and (integer? r) (<= 0 r range) (integer? g) (<= 0 g range) (integer? b) (<= 0 b range) (color:construct 'e-sRGB (cdr prec-RGB) precision))) prec-RGB)))) @body @1 must be the integer 10 , 12 , or 16 . @2 must be a list of 3 numbers . If @2 is valid e - sRGB coordinates , then @0 returns the color (define (e-sRGB->color precision RGB) (esRGB->color (cons precision RGB))) @args 10 r g b Returns the e - sRGB10 color composed of integers @2 , @3 , @4 . @args 12 r g b Returns the e - sRGB12 color composed of integers @2 , @3 , @4 . @args 16 r g b Returns the e - sRGB16 color composed of integers @2 , @3 , @4 . (define color:e-sRGB (color:helper 4 'color:e-sRGB esRGB->color)) @body @1 must be the integer 10 , 12 , or 16 . @0 returns the list of 3 integers encoding @2 in sRGB10 , sRGB12 , or sRGB16 . (define (color->e-sRGB precision color) (case precision ((10 12 16) (if (not (color:color? color)) (slib:error 'color->e-sRGB ': 'not 'color? color))) (else (slib:error 'color->e-sRGB ': 'invalid 'precision precision))) (case (color:encoding color) ((e-sRGB) (e-sRGB->e-sRGB (color:precision color) (color:coordinates color) precision)) ((sRGB) (sRGB->e-sRGB precision (color:coordinates color))) (else (CIEXYZ->e-sRGB precision (color->CIEXYZ color))))) (define D65 (CIEXYZ->color CIEXYZ:D65)) (define D50 (CIEXYZ->color CIEXYZ:D50)) (define (color? obj . typ) (cond ((not (color:color? obj)) #f) ((null? typ) #t) (else (eqv? (car typ) (color:encoding obj))))) (define (make-color space . args) (apply (case space ((CIEXYZ) CIEXYZ->color) ((RGB709) RGB709->color) ((L*a*b*) L*a*b*->color) ((L*u*v*) L*u*v*->color) ((L*C*h) L*C*h->color) ((sRGB) sRGB->color) ((xRGB) xRGB->color) ((e-sRGB) e-sRGB->color) (else (slib:error 'make-color ': 'not 'space? space))) args)) (define color-space color:encoding) (define (color-precision color) (if (not (color:color? color)) (slib:error 'color-precision ': 'not 'color? color)) (case (color:encoding color) ((e-sRGB) (color:precision color)) ((sRGB) 8) (else #f))) (define (color-white-point color) (if (not (color:color? color)) (slib:error 'color-white-point ': 'not 'color? color)) (case (color:encoding color) ((L*a*b*) (color:CIEXYZ (color:white-point color))) ((L*u*v*) (color:CIEXYZ (color:white-point color))) ((L*C*h) (color:CIEXYZ (color:white-point color))) ((RGB709) D65) ((sRGB) D65) ((e-sRGB) D65) (else #f))) (define (convert-color color encoding . opt-arg) (define (noarg) (if (not (null? opt-arg)) (slib:error 'convert-color ': 'too-many 'arguments opt-arg))) (if (not (color:color? color)) (slib:error 'convert-color ': 'not 'color? color)) (case encoding ((CIEXYZ) (noarg) (CIEXYZ->color (color->CIEXYZ color))) ((RGB709) (noarg) (RGB709->color (color->RGB709 color))) ((sRGB) (noarg) (sRGB->color (color->sRGB color))) ((e-sRGB) (e-sRGB->color (car opt-arg) (color->e-sRGB (car opt-arg) color))) ((L*a*b*) (apply L*a*b*->color (color->L*a*b* color) opt-arg)) ((L*u*v*) (apply L*u*v*->color (color->L*u*v* color) opt-arg)) ((L*C*h) (apply L*C*h->color (color->L*C*h color) opt-arg)) (else (slib:error 'convert-color ': encoding '?)))) (define (color->string color) (if (not (color:color? color)) (slib:error 'color->string ': 'not 'color? color)) (case (color:encoding color) ((CIEXYZ) (apply sprintf #f "CIEXYZ:%g/%g/%g" (color:coordinates color))) ((L*a*b*) (apply sprintf #f "CIELab:%.2f/%.2f/%.2f" (if (equal? CIEXYZ:D65 (color:white-point color)) (color:coordinates color) (CIEXYZ->L*a*b* (L*a*b*->CIEXYZ (color:coordinates color) (color:white-point color)))))) ((L*u*v*) (apply sprintf #f "CIELuv:%.2f/%.2f/%.2f" (if (equal? CIEXYZ:D65 (color:white-point color)) (color:coordinates color) (CIEXYZ->L*u*v* (L*u*v*->CIEXYZ (color:coordinates color) (color:white-point color)))))) ((L*C*h) (apply sprintf #f "CIELCh:%.2f/%.2f/%.2f" (if (equal? CIEXYZ:D65 (color:white-point color)) (color:coordinates color) (L*a*b*->L*C*h (CIEXYZ->L*a*b* (L*a*b*->CIEXYZ (L*C*h->L*a*b* (color:coordinates color)) (color:white-point color))))))) ((RGB709) (apply sprintf #f "RGBi:%g/%g/%g" (color:coordinates color))) ((sRGB) (apply sprintf #f "sRGB:%d/%d/%d" (color:coordinates color))) ((e-sRGB) (apply sprintf #f "e-sRGB%d:%d/%d/%d" (color:precision color) (color:coordinates color))) (else (slib:error 'color->string ': (color:encoding color) color)))) (define (string->color str) (define prec #f) (define coding #f) (define x #f) (define y #f) (define z #f) (cond ((eqv? 4 (sscanf str " %[CIEXYZciexyzLABUVlabuvHhRrGg709]:%f/%f/%f" coding x y z)) (case (string-ci->symbol coding) ((CIEXYZ) (color:CIEXYZ x y z)) ((CIELab) (color:L*a*b* x y z)) ((CIELuv) (color:L*u*v* x y z)) ((CIELCh) (color:L*C*h x y z)) Xlib - C Language X Interface RGB709) (color:RGB709 x y z)) (else #f))) ((eqv? 4 (sscanf str " %[sRGBSrgb]:%d/%d/%d" coding x y z)) (case (string-ci->symbol coding) ((sRGB) (color:sRGB x y z)) (else #f))) ((eqv? 5 (sscanf str " %[-esRGBESrgb]%d:%d/%d/%d" coding prec x y z)) (case (string-ci->symbol coding) ((e-sRGB) (color:e-sRGB prec x y z)) (else #f))) ((eqv? 2 (sscanf str " %[sRGBxXXRGB]:%6x%[/0-9a-fA-F]" coding x y)) (case (string-ci->symbol coding) ((sRGB xRGB sRGBx) (xRGB->color x)) (else #f))) ((and (eqv? 1 (sscanf str " #%6[0-9a-fA-F]%[0-9a-fA-F]" x y)) (eqv? 6 (string-length x))) (xRGB->color (string->number x 16))) ((and (eqv? 2 (sscanf str " %[#0xX]%6[0-9a-fA-F]%[0-9a-fA-F]" coding x y)) (eqv? 6 (string-length x)) (member coding '("#" "#x" "0x" "#X" "0X"))) (xRGB->color (string->number x 16))) (else #f))) (define (CIE:DE* color1 color2 . white-point) (L*a*b*:DE* (apply color->L*a*b* color1 white-point) (apply color->L*a*b* color2 white-point))) (define (CIE:DE*94 color1 color2 . parametric-factors) (apply L*C*h:DE*94 (color->L*C*h color1) (color->L*C*h color2) parametric-factors)) (define (CMC:DE* color1 color2 . parametric-factors) (apply CMC-DE (color->L*C*h color1) (color->L*C*h color2) parametric-factors)) ( define RGB709 color : RGB709 ) ( define L*a*b * color : L*a*b * ) ( define color : ) ( define xRGB )
9ad3e7b77cb9ff72e15edded0557f4643068caf0926479a422ee5b665fd2ee61
dyzsr/ocaml-selectml
format.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) * Pretty - printing . This module implements a pretty - printing facility to format values within { { ! boxes}'pretty - printing boxes ' } and { { ! tags}'semantic tags ' } combined with a set of { { ! fpp}printf - like functions } . The pretty - printer splits lines at specified { { ! breaks}break hints } , and indents lines according to the box structure . Similarly , { { ! tags}semantic tags } can be used to decouple text presentation from its contents . This pretty - printing facility is implemented as an overlay on top of abstract { { ! section : formatter}formatters } which provide basic output functions . Some formatters are predefined , notably : - { ! std_formatter } outputs to { { ! } - { ! err_formatter } outputs to { { ! Stdlib.stderr}stderr } Most functions in the { ! Format } module come in two variants : a short version that operates on { ! std_formatter } and the generic version prefixed by [ pp _ ] that takes a formatter as its first argument . More formatters can be created with { ! formatter_of_out_channel } , { ! formatter_of_buffer } , { ! formatter_of_symbolic_output_buffer } or using { { ! section : formatter}custom formatters } . This module implements a pretty-printing facility to format values within {{!boxes}'pretty-printing boxes'} and {{!tags}'semantic tags'} combined with a set of {{!fpp}printf-like functions}. The pretty-printer splits lines at specified {{!breaks}break hints}, and indents lines according to the box structure. Similarly, {{!tags}semantic tags} can be used to decouple text presentation from its contents. This pretty-printing facility is implemented as an overlay on top of abstract {{!section:formatter}formatters} which provide basic output functions. Some formatters are predefined, notably: - {!std_formatter} outputs to {{!Stdlib.stdout}stdout} - {!err_formatter} outputs to {{!Stdlib.stderr}stderr} Most functions in the {!Format} module come in two variants: a short version that operates on {!std_formatter} and the generic version prefixed by [pp_] that takes a formatter as its first argument. More formatters can be created with {!formatter_of_out_channel}, {!formatter_of_buffer}, {!formatter_of_symbolic_output_buffer} or using {{!section:formatter}custom formatters}. *) * { 1 Introduction } You may consider this module as providing an extension to the [ printf ] facility to provide automatic line splitting . The addition of pretty - printing annotations to your regular [ printf ] format strings gives you fancy indentation and line breaks . Pretty - printing annotations are described below in the documentation of the function { ! Format.fprintf } . You may also use the explicit pretty - printing box management and printing functions provided by this module . This style is more basic but more verbose than the concise [ fprintf ] format strings . For instance , the sequence [ open_box 0 ; print_string " x = " ; print_space ( ) ; print_int 1 ; close_box ( ) ; print_newline ( ) ] that prints [ x = 1 ] within a pretty - printing box , can be abbreviated as [ printf " @[%s@ % i@]@. " " x = " 1 ] , or even shorter [ printf " @[x = @ % i@]@. " 1 ] . Rule of thumb for casual users of this library : - use simple pretty - printing boxes ( as obtained by [ open_box 0 ] ) ; - use simple break hints as obtained by [ print_cut ( ) ] that outputs a simple break hint , or by [ print_space ( ) ] that outputs a space indicating a break hint ; - once a pretty - printing box is open , display its material with basic printing functions ( [ print_int ] and [ print_string ] ) ; - when the material for a pretty - printing box has been printed , call [ close_box ( ) ] to close the box ; - at the end of pretty - printing , flush the pretty - printer to display all the remaining material , e.g. evaluate [ print_newline ( ) ] . The behavior of pretty - printing commands is unspecified if there is no open pretty - printing box . Each box opened by one of the [ open _ ] functions below must be closed using [ close_box ] for proper formatting . Otherwise , some of the material printed in the boxes may not be output , or may be formatted incorrectly . In case of interactive use , each phrase is executed in the initial state of the standard pretty - printer : after each phrase execution , the interactive system closes all open pretty - printing boxes , flushes all pending text , and resets the standard pretty - printer . Warning : mixing calls to pretty - printing functions of this module with calls to { ! } low level output functions is error prone . The pretty - printing functions output material that is delayed in the pretty - printer queue and stacks in order to compute proper line splitting . In contrast , basic I / O output functions write directly in their output device . As a consequence , the output of a basic I / O function may appear before the output of a pretty - printing function that has been called before . For instance , [ Stdlib.print_string " < " ; Format.print_string " PRETTY " ; Stdlib.print_string " > " ; Format.print_string " TEXT " ; ] leads to output [ < > PRETTYTEXT ] . You may consider this module as providing an extension to the [printf] facility to provide automatic line splitting. The addition of pretty-printing annotations to your regular [printf] format strings gives you fancy indentation and line breaks. Pretty-printing annotations are described below in the documentation of the function {!Format.fprintf}. You may also use the explicit pretty-printing box management and printing functions provided by this module. This style is more basic but more verbose than the concise [fprintf] format strings. For instance, the sequence [open_box 0; print_string "x ="; print_space (); print_int 1; close_box (); print_newline ()] that prints [x = 1] within a pretty-printing box, can be abbreviated as [printf "@[%s@ %i@]@." "x =" 1], or even shorter [printf "@[x =@ %i@]@." 1]. Rule of thumb for casual users of this library: - use simple pretty-printing boxes (as obtained by [open_box 0]); - use simple break hints as obtained by [print_cut ()] that outputs a simple break hint, or by [print_space ()] that outputs a space indicating a break hint; - once a pretty-printing box is open, display its material with basic printing functions (e. g. [print_int] and [print_string]); - when the material for a pretty-printing box has been printed, call [close_box ()] to close the box; - at the end of pretty-printing, flush the pretty-printer to display all the remaining material, e.g. evaluate [print_newline ()]. The behavior of pretty-printing commands is unspecified if there is no open pretty-printing box. Each box opened by one of the [open_] functions below must be closed using [close_box] for proper formatting. Otherwise, some of the material printed in the boxes may not be output, or may be formatted incorrectly. In case of interactive use, each phrase is executed in the initial state of the standard pretty-printer: after each phrase execution, the interactive system closes all open pretty-printing boxes, flushes all pending text, and resets the standard pretty-printer. Warning: mixing calls to pretty-printing functions of this module with calls to {!Stdlib} low level output functions is error prone. The pretty-printing functions output material that is delayed in the pretty-printer queue and stacks in order to compute proper line splitting. In contrast, basic I/O output functions write directly in their output device. As a consequence, the output of a basic I/O function may appear before the output of a pretty-printing function that has been called before. For instance, [ Stdlib.print_string "<"; Format.print_string "PRETTY"; Stdlib.print_string ">"; Format.print_string "TEXT"; ] leads to output [<>PRETTYTEXT]. *) (* A tutorial to the Format module is provided at {!Format_tutorial}. *) (** {1 Formatters} *) type formatter (** Abstract data corresponding to a pretty-printer (also called a formatter) and all its machinery. See also {!section:formatter}. *) * { 1 : boxes Pretty - printing boxes } (** The pretty-printing engine uses the concepts of pretty-printing box and break hint to drive indentation and line splitting behavior of the pretty-printer. Each different pretty-printing box kind introduces a specific line splitting policy: - within an {e horizontal} box, break hints never split the line (but the line may be split in a box nested deeper), - within a {e vertical} box, break hints always split the line, - within an {e horizontal/vertical} box, if the box fits on the current line then break hints never split the line, otherwise break hint always split the line, - within a {e compacting} box, a break hint never splits the line, unless there is no more room on the current line. Note that line splitting policy is box specific: the policy of a box does not rule the policy of inner boxes. For instance, if a vertical box is nested in an horizontal box, all break hints within the vertical box will split the line. Moreover, opening a box after the {{!maxindent}maximum indentation limit} splits the line whether or not the box would end up fitting on the line. *) val pp_open_box : formatter -> int -> unit val open_box : int -> unit (** [pp_open_box ppf d] opens a new compacting pretty-printing box with offset [d] in the formatter [ppf]. Within this box, the pretty-printer prints as much as possible material on every line. A break hint splits the line if there is no more room on the line to print the remainder of the box. Within this box, the pretty-printer emphasizes the box structure: if a structural box does not fit fully on a simple line, a break hint also splits the line if the splitting ``moves to the left'' (i.e. the new line gets an indentation smaller than the one of the current line). This box is the general purpose pretty-printing box. If the pretty-printer splits the line in the box, offset [d] is added to the current indentation. *) val pp_close_box : formatter -> unit -> unit val close_box : unit -> unit (** Closes the most recently open pretty-printing box. *) val pp_open_hbox : formatter -> unit -> unit val open_hbox : unit -> unit * [ pp_open_hbox ( ) ] opens a new ' horizontal ' pretty - printing box . This box prints material on a single line . Break hints in a horizontal box never split the line . ( Line splitting may still occur inside boxes nested deeper ) . This box prints material on a single line. Break hints in a horizontal box never split the line. (Line splitting may still occur inside boxes nested deeper). *) val pp_open_vbox : formatter -> int -> unit val open_vbox : int -> unit (** [pp_open_vbox ppf d] opens a new 'vertical' pretty-printing box with offset [d]. This box prints material on as many lines as break hints in the box. Every break hint in a vertical box splits the line. If the pretty-printer splits the line in the box, [d] is added to the current indentation. *) val pp_open_hvbox : formatter -> int -> unit val open_hvbox : int -> unit (** [pp_open_hvbox ppf d] opens a new 'horizontal/vertical' pretty-printing box with offset [d]. This box behaves as an horizontal box if it fits on a single line, otherwise it behaves as a vertical box. If the pretty-printer splits the line in the box, [d] is added to the current indentation. *) val pp_open_hovbox : formatter -> int -> unit val open_hovbox : int -> unit (** [pp_open_hovbox ppf d] opens a new 'horizontal-or-vertical' pretty-printing box with offset [d]. This box prints material as much as possible on every line. A break hint splits the line if there is no more room on the line to print the remainder of the box. If the pretty-printer splits the line in the box, [d] is added to the current indentation. *) (** {1 Formatting functions} *) val pp_print_string : formatter -> string -> unit val print_string : string -> unit * [ pp_print_string s ] prints [ s ] in the current pretty - printing box . val pp_print_bytes : formatter -> bytes -> unit val print_bytes : bytes -> unit * [ pp_print_bytes ppf b ] prints [ b ] in the current pretty - printing box . @since 4.13.0 @since 4.13.0 *) val pp_print_as : formatter -> int -> string -> unit val print_as : int -> string -> unit (** [pp_print_as ppf len s] prints [s] in the current pretty-printing box. The pretty-printer formats [s] as if it were of length [len]. *) val pp_print_int : formatter -> int -> unit val print_int : int -> unit (** Print an integer in the current pretty-printing box. *) val pp_print_float : formatter -> float -> unit val print_float : float -> unit (** Print a floating point number in the current pretty-printing box. *) val pp_print_char : formatter -> char -> unit val print_char : char -> unit (** Print a character in the current pretty-printing box. *) val pp_print_bool : formatter -> bool -> unit val print_bool : bool -> unit (** Print a boolean in the current pretty-printing box. *) * { 1 : breaks Break hints } * A ' break hint ' tells the pretty - printer to output some space or split the line whichever way is more appropriate to the current pretty - printing box splitting rules . Break hints are used to separate printing items and are mandatory to let the pretty - printer correctly split lines and indent items . Simple break hints are : - the ' space ' : output a space or split the line if appropriate , - the ' cut ' : split the line if appropriate . Note : the notions of space and line splitting are abstract for the pretty - printing engine , since those notions can be completely redefined by the programmer . However , in the pretty - printer default setting , ` ` output a space '' simply means printing a space character ( ASCII code 32 ) and ` ` split the line '' means printing a newline character ( ASCII code 10 ) . line whichever way is more appropriate to the current pretty-printing box splitting rules. Break hints are used to separate printing items and are mandatory to let the pretty-printer correctly split lines and indent items. Simple break hints are: - the 'space': output a space or split the line if appropriate, - the 'cut': split the line if appropriate. Note: the notions of space and line splitting are abstract for the pretty-printing engine, since those notions can be completely redefined by the programmer. However, in the pretty-printer default setting, ``output a space'' simply means printing a space character (ASCII code 32) and ``split the line'' means printing a newline character (ASCII code 10). *) val pp_print_space : formatter -> unit -> unit val print_space : unit -> unit * [ pp_print_space ppf ( ) ] emits a ' space ' break hint : the pretty - printer may split the line at this point , otherwise it prints one space . [ pp_print_space ppf ( ) ] is equivalent to [ pp_print_break ppf 1 0 ] . the pretty-printer may split the line at this point, otherwise it prints one space. [pp_print_space ppf ()] is equivalent to [pp_print_break ppf 1 0]. *) val pp_print_cut : formatter -> unit -> unit val print_cut : unit -> unit * [ pp_print_cut ( ) ] emits a ' cut ' break hint : the pretty - printer may split the line at this point , otherwise it prints nothing . [ pp_print_cut ( ) ] is equivalent to [ pp_print_break 0 0 ] . the pretty-printer may split the line at this point, otherwise it prints nothing. [pp_print_cut ppf ()] is equivalent to [pp_print_break ppf 0 0]. *) val pp_print_break : formatter -> int -> int -> unit val print_break : int -> int -> unit * [ pp_print_break offset ] emits a ' full ' break hint : the pretty - printer may split the line at this point , otherwise it prints [ nspaces ] spaces . If the pretty - printer splits the line , [ offset ] is added to the current indentation . the pretty-printer may split the line at this point, otherwise it prints [nspaces] spaces. If the pretty-printer splits the line, [offset] is added to the current indentation. *) val pp_print_custom_break : formatter -> fits:(string * int * string) -> breaks:(string * int * string) -> unit * [ pp_print_custom_break , n , s2 ) ~breaks:(s3 , m , s4 ) ] emits a custom break hint : the pretty - printer may split the line at this point . If it does not split the line , then the [ s1 ] is emitted , then [ n ] spaces , then [ s2 ] . If it splits the line , then it emits the [ s3 ] string , then an indent ( according to the box rules ) , then an offset of [ m ] spaces , then the [ s4 ] string . While [ n ] and [ m ] are handled by [ formatter_out_functions.out_indent ] , the strings will be handled by [ formatter_out_functions.out_string ] . This allows for a custom formatter that handles indentation distinctly , for example , outputs [ < br/ > ] tags or [ & nbsp ; ] entities . The custom break is useful if you want to change which visible ( non - whitespace ) characters are printed in case of break or no break . For example , when printing a list [ [ a ; b ; c ] ] , you might want to add a trailing semicolon when it is printed vertically : { [ [ a ; b ; c ; ] ] } You can do this as follows : { [ printf " @[<v 0>[@;<0 2>@[<v 0 > a;@,b;@,c@]%t]@]@\n " ( pp_print_custom_break ~fits :( " " , 0 , " " ) ~breaks :( " ; " , 0 , " " ) ) ] } @since 4.08.0 custom break hint: the pretty-printer may split the line at this point. If it does not split the line, then the [s1] is emitted, then [n] spaces, then [s2]. If it splits the line, then it emits the [s3] string, then an indent (according to the box rules), then an offset of [m] spaces, then the [s4] string. While [n] and [m] are handled by [formatter_out_functions.out_indent], the strings will be handled by [formatter_out_functions.out_string]. This allows for a custom formatter that handles indentation distinctly, for example, outputs [<br/>] tags or [&nbsp;] entities. The custom break is useful if you want to change which visible (non-whitespace) characters are printed in case of break or no break. For example, when printing a list [ [a; b; c] ], you might want to add a trailing semicolon when it is printed vertically: {[ [ a; b; c; ] ]} You can do this as follows: {[ printf "@[<v 0>[@;<0 2>@[<v 0>a;@,b;@,c@]%t]@]@\n" (pp_print_custom_break ~fits:("", 0, "") ~breaks:(";", 0, "")) ]} @since 4.08.0 *) val pp_force_newline : formatter -> unit -> unit val force_newline : unit -> unit (** Force a new line in the current pretty-printing box. The pretty-printer must split the line at this point, Not the normal way of pretty-printing, since imperative line splitting may interfere with current line counters and box size calculation. Using break hints within an enclosing vertical box is a better alternative. *) val pp_print_if_newline : formatter -> unit -> unit val print_if_newline : unit -> unit (** Execute the next formatting command if the preceding line has just been split. Otherwise, ignore the next formatting command. *) * { 1 Pretty - printing termination } val pp_print_flush : formatter -> unit -> unit val print_flush : unit -> unit (** End of pretty-printing: resets the pretty-printer to initial state. All open pretty-printing boxes are closed, all pending text is printed. In addition, the pretty-printer low level output device is flushed to ensure that all pending text is really displayed. Note: never use [print_flush] in the normal course of a pretty-printing routine, since the pretty-printer uses a complex buffering machinery to properly indent the output; manually flushing those buffers at random would conflict with the pretty-printer strategy and result to poor rendering. Only consider using [print_flush] when displaying all pending material is mandatory (for instance in case of interactive use when you want the user to read some text) and when resetting the pretty-printer state will not disturb further pretty-printing. Warning: If the output device of the pretty-printer is an output channel, repeated calls to [print_flush] means repeated calls to {!Stdlib.flush} to flush the out channel; these explicit flush calls could foil the buffering strategy of output channels and could dramatically impact efficiency. *) val pp_print_newline : formatter -> unit -> unit val print_newline : unit -> unit (** End of pretty-printing: resets the pretty-printer to initial state. All open pretty-printing boxes are closed, all pending text is printed. Equivalent to {!print_flush} followed by a new line. See corresponding words of caution for {!print_flush}. Note: this is not the normal way to output a new line; the preferred method is using break hints within a vertical pretty-printing box. *) (** {1 Margin} *) val pp_set_margin : formatter -> int -> unit val set_margin : int -> unit * [ pp_set_margin ppf d ] sets the right margin to [ d ] ( in characters ): the pretty - printer splits lines that overflow the right margin according to the break hints given . Setting the margin to [ d ] means that the formatting engine aims at printing at most [ d-1 ] characters per line . Nothing happens if [ d ] is smaller than 2 . If [ d ] is too large , the right margin is set to the maximum admissible value ( which is greater than [ 10 ^ 9 ] ) . If [ d ] is less than the current maximum indentation limit , the maximum indentation limit is decreased while trying to preserve a minimal ratio [ max_indent / margin>=50 % ] and if possible the current difference [ margin - max_indent ] . See also { ! pp_set_geometry } . the pretty-printer splits lines that overflow the right margin according to the break hints given. Setting the margin to [d] means that the formatting engine aims at printing at most [d-1] characters per line. Nothing happens if [d] is smaller than 2. If [d] is too large, the right margin is set to the maximum admissible value (which is greater than [10 ^ 9]). If [d] is less than the current maximum indentation limit, the maximum indentation limit is decreased while trying to preserve a minimal ratio [max_indent/margin>=50%] and if possible the current difference [margin - max_indent]. See also {!pp_set_geometry}. *) val pp_get_margin : formatter -> unit -> int val get_margin : unit -> int (** Returns the position of the right margin. *) * { 1 : maxindent Maximum indentation limit } val pp_set_max_indent : formatter -> int -> unit val set_max_indent : int -> unit * [ pp_set_max_indent ppf d ] sets the maximum indentation limit of lines to [ d ] ( in characters ): once this limit is reached , new pretty - printing boxes are rejected to the left , unless the enclosing box fully fits on the current line . As an illustration , { [ set_margin 10 ; set_max_indent 5 ; printf " " ] } yields { [ 123456 789A ] } because the nested box [ " @[7@ ] " ] is opened after the maximum indentation limit ( [ 7>5 ] ) and its parent box does not fit on the current line . Either decreasing the length of the parent box to make it fit on a line : { [ printf " " ] } or opening an intermediary box before the maximum indentation limit which fits on the current line { [ printf " " ] } avoids the rejection to the left of the inner boxes and print respectively [ " 123456789 " ] and [ " 123456789A " ] . Note also that vertical boxes never fit on a line whereas horizontal boxes always fully fit on the current line . Opening a box may split a line whereas the contents may have fit . If this behavior is problematic , it can be curtailed by setting the maximum indentation limit to [ margin - 1 ] . Note that setting the maximum indentation limit to [ margin ] is invalid . Nothing happens if [ d ] is smaller than 2 . If [ d ] is too large , the limit is set to the maximum admissible value ( which is greater than [ 10 ^ 9 ] ) . If [ d ] is greater or equal than the current margin , it is ignored , and the current maximum indentation limit is kept . See also { ! pp_set_geometry } . to [d] (in characters): once this limit is reached, new pretty-printing boxes are rejected to the left, unless the enclosing box fully fits on the current line. As an illustration, {[ set_margin 10; set_max_indent 5; printf "@[123456@[7@]89A@]@." ]} yields {[ 123456 789A ]} because the nested box ["@[7@]"] is opened after the maximum indentation limit ([7>5]) and its parent box does not fit on the current line. Either decreasing the length of the parent box to make it fit on a line: {[ printf "@[123456@[7@]89@]@." ]} or opening an intermediary box before the maximum indentation limit which fits on the current line {[ printf "@[123@[456@[7@]89@]A@]@." ]} avoids the rejection to the left of the inner boxes and print respectively ["123456789"] and ["123456789A"] . Note also that vertical boxes never fit on a line whereas horizontal boxes always fully fit on the current line. Opening a box may split a line whereas the contents may have fit. If this behavior is problematic, it can be curtailed by setting the maximum indentation limit to [margin - 1]. Note that setting the maximum indentation limit to [margin] is invalid. Nothing happens if [d] is smaller than 2. If [d] is too large, the limit is set to the maximum admissible value (which is greater than [10 ^ 9]). If [d] is greater or equal than the current margin, it is ignored, and the current maximum indentation limit is kept. See also {!pp_set_geometry}. *) val pp_get_max_indent : formatter -> unit -> int val get_max_indent : unit -> int (** Return the maximum indentation limit (in characters). *) * { 1 Geometry } Geometric functions can be used to manipulate simultaneously the coupled variables , margin and maxixum indentation limit . Geometric functions can be used to manipulate simultaneously the coupled variables, margin and maxixum indentation limit. *) type geometry = { max_indent:int; margin: int} val check_geometry: geometry -> bool * Check if the formatter geometry is valid : [ 1 < max_indent < margin ] val pp_set_geometry : formatter -> max_indent:int -> margin:int -> unit val set_geometry : max_indent:int -> margin:int -> unit val pp_safe_set_geometry : formatter -> max_indent:int -> margin:int -> unit val safe_set_geometry : max_indent:int -> margin:int -> unit * [ pp_set_geometry ppf ~max_indent ~margin ] sets both the margin and maximum indentation limit for [ ppf ] . When [ 1 < max_indent < margin ] , [ pp_set_geometry ppf ~max_indent ~margin ] is equivalent to [ pp_set_margin ppf margin ; pp_set_max_indent ] ; and avoids the subtly incorrect [ pp_set_max_indent ; pp_set_margin ppf margin ] ; Outside of this domain , [ pp_set_geometry ] raises an invalid argument exception whereas [ pp_safe_set_geometry ] does nothing . @since 4.08.0 [pp_set_geometry ppf ~max_indent ~margin] sets both the margin and maximum indentation limit for [ppf]. When [1 < max_indent < margin], [pp_set_geometry ppf ~max_indent ~margin] is equivalent to [pp_set_margin ppf margin; pp_set_max_indent ppf max_indent]; and avoids the subtly incorrect [pp_set_max_indent ppf max_indent; pp_set_margin ppf margin]; Outside of this domain, [pp_set_geometry] raises an invalid argument exception whereas [pp_safe_set_geometry] does nothing. @since 4.08.0 *) * [ pp_update_geometry ( fun geo - > { geo with ... } ) ] lets you update a formatter 's geometry in a way that is robust to extension of the [ geometry ] record with new fields . Raises an invalid argument exception if the returned geometry does not satisfy { ! check_geometry } . @since 4.11.0 [pp_update_geometry ppf (fun geo -> { geo with ... })] lets you update a formatter's geometry in a way that is robust to extension of the [geometry] record with new fields. Raises an invalid argument exception if the returned geometry does not satisfy {!check_geometry}. @since 4.11.0 *) val pp_update_geometry : formatter -> (geometry -> geometry) -> unit val update_geometry : (geometry -> geometry) -> unit val pp_get_geometry: formatter -> unit -> geometry val get_geometry: unit -> geometry * Return the current geometry of the formatter @since 4.08.0 @since 4.08.0 *) * { 1 Maximum formatting depth } (** The maximum formatting depth is the maximum number of pretty-printing boxes simultaneously open. Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by {!get_ellipsis_text} [()]). *) val pp_set_max_boxes : formatter -> int -> unit val set_max_boxes : int -> unit * [ pp_set_max_boxes ] sets the maximum number of pretty - printing boxes simultaneously open . Material inside boxes nested deeper is printed as an ellipsis ( more precisely as the text returned by { ! get_ellipsis_text } [ ( ) ] ) . Nothing happens if [ max ] is smaller than 2 . boxes simultaneously open. Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by {!get_ellipsis_text} [()]). Nothing happens if [max] is smaller than 2. *) val pp_get_max_boxes : formatter -> unit -> int val get_max_boxes : unit -> int (** Returns the maximum number of pretty-printing boxes allowed before ellipsis. *) val pp_over_max_boxes : formatter -> unit -> bool val over_max_boxes : unit -> bool (** Tests if the maximum number of pretty-printing boxes allowed have already been opened. *) * { 1 Tabulation boxes } (** A {e tabulation box} prints material on lines divided into cells of fixed length. A tabulation box provides a simple way to display vertical columns of left adjusted text. This box features command [set_tab] to define cell boundaries, and command [print_tab] to move from cell to cell and split the line when there is no more cells to print on the line. Note: printing within tabulation box is line directed, so arbitrary line splitting inside a tabulation box leads to poor rendering. Yet, controlled use of tabulation boxes allows simple printing of columns within module {!Format}. *) val pp_open_tbox : formatter -> unit -> unit val open_tbox : unit -> unit * [ open_tbox ( ) ] opens a new tabulation box . This box prints lines separated into cells of fixed width . Inside a tabulation box , special { e tabulation markers } defines points of interest on the line ( for instance to delimit cell boundaries ) . Function { ! Format.set_tab } sets a tabulation marker at insertion point . A tabulation box features specific { e tabulation breaks } to move to next tabulation marker or split the line . Function { ! Format.print_tbreak } prints a tabulation break . This box prints lines separated into cells of fixed width. Inside a tabulation box, special {e tabulation markers} defines points of interest on the line (for instance to delimit cell boundaries). Function {!Format.set_tab} sets a tabulation marker at insertion point. A tabulation box features specific {e tabulation breaks} to move to next tabulation marker or split the line. Function {!Format.print_tbreak} prints a tabulation break. *) val pp_close_tbox : formatter -> unit -> unit val close_tbox : unit -> unit (** Closes the most recently opened tabulation box. *) val pp_set_tab : formatter -> unit -> unit val set_tab : unit -> unit (** Sets a tabulation marker at current insertion point. *) val pp_print_tab : formatter -> unit -> unit val print_tab : unit -> unit * [ print_tab ( ) ] emits a ' next ' tabulation break hint : if not already set on a tabulation marker , the insertion point moves to the first tabulation marker on the right , or the pretty - printer splits the line and insertion point moves to the leftmost tabulation marker . It is equivalent to [ print_tbreak 0 0 ] . a tabulation marker, the insertion point moves to the first tabulation marker on the right, or the pretty-printer splits the line and insertion point moves to the leftmost tabulation marker. It is equivalent to [print_tbreak 0 0]. *) val pp_print_tbreak : formatter -> int -> int -> unit val print_tbreak : int -> int -> unit * [ print_tbreak nspaces offset ] emits a ' full ' tabulation break hint . If not already set on a tabulation marker , the insertion point moves to the first tabulation marker on the right and the pretty - printer prints [ nspaces ] spaces . If there is no next tabulation marker on the right , the pretty - printer splits the line at this point , then insertion point moves to the leftmost tabulation marker of the box . If the pretty - printer splits the line , [ offset ] is added to the current indentation . If not already set on a tabulation marker, the insertion point moves to the first tabulation marker on the right and the pretty-printer prints [nspaces] spaces. If there is no next tabulation marker on the right, the pretty-printer splits the line at this point, then insertion point moves to the leftmost tabulation marker of the box. If the pretty-printer splits the line, [offset] is added to the current indentation. *) (** {1 Ellipsis} *) val pp_set_ellipsis_text : formatter -> string -> unit val set_ellipsis_text : string -> unit (** Set the text of the ellipsis printed when too many pretty-printing boxes are open (a single dot, [.], by default). *) val pp_get_ellipsis_text : formatter -> unit -> string val get_ellipsis_text : unit -> string (** Return the text of the ellipsis. *) * { 1 : tags Semantic tags } type stag = .. * { i Semantic tags } ( or simply { e tags } ) are user 's defined annotations to associate user 's specific operations to printed entities . Common usage of semantic tags is text decoration to get specific font or text size rendering for a display device , or marking delimitation of entities ( e.g. HTML or TeX elements or terminal escape sequences ) . More sophisticated usage of semantic tags could handle dynamic modification of the pretty - printer behavior to properly print the material within some specific tags . For instance , we can define an RGB tag like so : { [ type stag + = RGB of { r : : int;b : int } ] } In order to properly delimit printed entities , a semantic tag must be opened before and closed after the entity . Semantic tags must be properly nested like parentheses using { ! } and { ! pp_close_stag } . Tag specific operations occur any time a tag is opened or closed , At each occurrence , two kinds of operations are performed { e tag - marking } and { e tag - printing } : - The tag - marking operation is the simpler tag specific operation : it simply writes a tag specific string into the output device of the formatter . Tag - marking does not interfere with line - splitting computation . - The tag - printing operation is the more involved tag specific operation : it can print arbitrary material to the formatter . Tag - printing is tightly linked to the current pretty - printer operations . Roughly speaking , tag - marking is commonly used to get a better rendering of texts in the rendering device , while tag - printing allows fine tuning of printing routines to print the same entity differently according to the semantic tags ( i.e. print additional material or even omit parts of the output ) . More precisely : when a semantic tag is opened or closed then both and successive ' tag - printing ' and ' tag - marking ' operations occur : - Tag - printing a semantic tag means calling the formatter specific function [ print_open_stag ] ( resp . [ print_close_stag ] ) with the name of the tag as argument : that tag - printing function can then print any regular material to the formatter ( so that this material is enqueued as usual in the formatter queue for further line splitting computation ) . - Tag - marking a semantic tag means calling the formatter specific function [ mark_open_stag ] ( resp . [ mark_close_stag ] ) with the name of the tag as argument : that tag - marking function can then return the ' tag - opening marker ' ( resp . ` tag - closing marker ' ) for direct output into the output device of the formatter . Being written directly into the output device of the formatter , semantic tag marker strings are not considered as part of the printing material that drives line splitting ( in other words , the length of the strings corresponding to tag markers is considered as zero for line splitting ) . Thus , semantic tag handling is in some sense transparent to pretty - printing and does not interfere with usual indentation . Hence , a single pretty - printing routine can output both simple ' verbatim ' material or richer decorated output depending on the treatment of tags . By default , tags are not active , hence the output is not decorated with tag information . Once [ set_tags ] is set to [ true ] , the pretty - printer engine honors tags and decorates the output accordingly . Default tag - marking functions behave the HTML way : { { ! tag}string tags } are enclosed in " < " and " > " while other tags are ignored ; hence , opening marker for tag string [ " t " ] is [ " < t > " ] and closing marker is [ " < /t > " ] . Default tag - printing functions just do nothing . Tag - marking and tag - printing functions are user definable and can be set by calling { ! set_formatter_stag_functions } . Semantic tag operations may be set on or off with { ! set_tags } . Tag - marking operations may be set on or off with { ! set_mark_tags } . Tag - printing operations may be set on or off with { ! } . @since 4.08.0 to associate user's specific operations to printed entities. Common usage of semantic tags is text decoration to get specific font or text size rendering for a display device, or marking delimitation of entities (e.g. HTML or TeX elements or terminal escape sequences). More sophisticated usage of semantic tags could handle dynamic modification of the pretty-printer behavior to properly print the material within some specific tags. For instance, we can define an RGB tag like so: {[ type stag += RGB of {r:int;g:int;b:int} ]} In order to properly delimit printed entities, a semantic tag must be opened before and closed after the entity. Semantic tags must be properly nested like parentheses using {!pp_open_stag} and {!pp_close_stag}. Tag specific operations occur any time a tag is opened or closed, At each occurrence, two kinds of operations are performed {e tag-marking} and {e tag-printing}: - The tag-marking operation is the simpler tag specific operation: it simply writes a tag specific string into the output device of the formatter. Tag-marking does not interfere with line-splitting computation. - The tag-printing operation is the more involved tag specific operation: it can print arbitrary material to the formatter. Tag-printing is tightly linked to the current pretty-printer operations. Roughly speaking, tag-marking is commonly used to get a better rendering of texts in the rendering device, while tag-printing allows fine tuning of printing routines to print the same entity differently according to the semantic tags (i.e. print additional material or even omit parts of the output). More precisely: when a semantic tag is opened or closed then both and successive 'tag-printing' and 'tag-marking' operations occur: - Tag-printing a semantic tag means calling the formatter specific function [print_open_stag] (resp. [print_close_stag]) with the name of the tag as argument: that tag-printing function can then print any regular material to the formatter (so that this material is enqueued as usual in the formatter queue for further line splitting computation). - Tag-marking a semantic tag means calling the formatter specific function [mark_open_stag] (resp. [mark_close_stag]) with the name of the tag as argument: that tag-marking function can then return the 'tag-opening marker' (resp. `tag-closing marker') for direct output into the output device of the formatter. Being written directly into the output device of the formatter, semantic tag marker strings are not considered as part of the printing material that drives line splitting (in other words, the length of the strings corresponding to tag markers is considered as zero for line splitting). Thus, semantic tag handling is in some sense transparent to pretty-printing and does not interfere with usual indentation. Hence, a single pretty-printing routine can output both simple 'verbatim' material or richer decorated output depending on the treatment of tags. By default, tags are not active, hence the output is not decorated with tag information. Once [set_tags] is set to [true], the pretty-printer engine honors tags and decorates the output accordingly. Default tag-marking functions behave the HTML way: {{!tag}string tags} are enclosed in "<" and ">" while other tags are ignored; hence, opening marker for tag string ["t"] is ["<t>"] and closing marker is ["</t>"]. Default tag-printing functions just do nothing. Tag-marking and tag-printing functions are user definable and can be set by calling {!set_formatter_stag_functions}. Semantic tag operations may be set on or off with {!set_tags}. Tag-marking operations may be set on or off with {!set_mark_tags}. Tag-printing operations may be set on or off with {!set_print_tags}. @since 4.08.0 *) type tag = string type stag += String_tag of tag * [ String_tag s ] is a string tag [ s ] . String tags can be inserted either by explicitly using the constructor [ String_tag ] or by using the dedicated format syntax [ " @{<s > ... @ } " ] . @since 4.08.0 by explicitly using the constructor [String_tag] or by using the dedicated format syntax ["@{<s> ... @}"]. @since 4.08.0 *) val pp_open_stag : formatter -> stag -> unit val open_stag : stag -> unit * [ pp_open_stag ppf t ] opens the semantic tag named [ t ] . The [ print_open_stag ] tag - printing function of the formatter is called with [ t ] as argument ; then the opening tag marker for [ t ] , as given by [ mark_open_stag t ] , is written into the output device of the formatter . @since 4.08.0 The [print_open_stag] tag-printing function of the formatter is called with [t] as argument; then the opening tag marker for [t], as given by [mark_open_stag t], is written into the output device of the formatter. @since 4.08.0 *) val pp_close_stag : formatter -> unit -> unit val close_stag : unit -> unit * [ pp_close_stag ( ) ] closes the most recently opened semantic tag [ t ] . The closing tag marker , as given by [ mark_close_stag t ] , is written into the output device of the formatter ; then the [ print_close_stag ] tag - printing function of the formatter is called with [ t ] as argument . @since 4.08.0 The closing tag marker, as given by [mark_close_stag t], is written into the output device of the formatter; then the [print_close_stag] tag-printing function of the formatter is called with [t] as argument. @since 4.08.0 *) val pp_set_tags : formatter -> bool -> unit val set_tags : bool -> unit * [ ppf b ] turns on or off the treatment of semantic tags ( default is off ) . (default is off). *) val pp_set_print_tags : formatter -> bool -> unit val set_print_tags : bool -> unit (** [pp_set_print_tags ppf b] turns on or off the tag-printing operations. *) val pp_set_mark_tags : formatter -> bool -> unit val set_mark_tags : bool -> unit (** [pp_set_mark_tags ppf b] turns on or off the tag-marking operations. *) val pp_get_print_tags : formatter -> unit -> bool val get_print_tags : unit -> bool (** Return the current status of tag-printing operations. *) val pp_get_mark_tags : formatter -> unit -> bool val get_mark_tags : unit -> bool (** Return the current status of tag-marking operations. *) (** {1 Redirecting the standard formatter output} *) val pp_set_formatter_out_channel : formatter -> Stdlib.out_channel -> unit val set_formatter_out_channel : Stdlib.out_channel -> unit (** Redirect the standard pretty-printer output to the given channel. (All the output functions of the standard formatter are set to the default output functions printing to the given channel.) [set_formatter_out_channel] is equivalent to {!pp_set_formatter_out_channel} [std_formatter]. *) val pp_set_formatter_output_functions : formatter -> (string -> int -> int -> unit) -> (unit -> unit) -> unit val set_formatter_output_functions : (string -> int -> int -> unit) -> (unit -> unit) -> unit (** [pp_set_formatter_output_functions ppf out flush] redirects the standard pretty-printer output functions to the functions [out] and [flush]. The [out] function performs all the pretty-printer string output. It is called with a string [s], a start position [p], and a number of characters [n]; it is supposed to output characters [p] to [p + n - 1] of [s]. The [flush] function is called whenever the pretty-printer is flushed (via conversion [%!], or pretty-printing indications [@?] or [@.], or using low level functions [print_flush] or [print_newline]). *) val pp_get_formatter_output_functions : formatter -> unit -> (string -> int -> int -> unit) * (unit -> unit) val get_formatter_output_functions : unit -> (string -> int -> int -> unit) * (unit -> unit) (** Return the current output functions of the standard pretty-printer. *) * { 1 : meaning Redefining formatter output } (** The [Format] module is versatile enough to let you completely redefine the meaning of pretty-printing output: you may provide your own functions to define how to handle indentation, line splitting, and even printing of all the characters that have to be printed! *) * { 2 Redefining output functions } type formatter_out_functions = { out_string : string -> int -> int -> unit; out_flush : unit -> unit; out_newline : unit -> unit; out_spaces : int -> unit; * @since 4.06.0 } * The set of output functions specific to a formatter : - the [ out_string ] function performs all the pretty - printer string output . It is called with a string [ s ] , a start position [ p ] , and a number of characters [ n ] ; it is supposed to output characters [ p ] to [ p + n - 1 ] of [ s ] . - the [ out_flush ] function flushes the pretty - printer output device . - [ out_newline ] is called to open a new line when the pretty - printer splits the line . - the [ out_spaces ] function outputs spaces when a break hint leads to spaces instead of a line split . It is called with the number of spaces to output . - the [ out_indent ] function performs new line indentation when the pretty - printer splits the line . It is called with the indentation value of the new line . By default : - fields [ out_string ] and [ out_flush ] are output device specific ; ( e.g. { ! Stdlib.output_string } and { ! Stdlib.flush } for a { ! Stdlib.out_channel } device , or [ Buffer.add_substring ] and { ! Stdlib.ignore } for a [ Buffer.t ] output device ) , - field [ out_newline ] is equivalent to [ out_string " \n " 0 1 ] ; - fields [ out_spaces ] and [ out_indent ] are equivalent to [ out_string ( String.make n ' ' ) 0 n ] . @since 4.01.0 - the [out_string] function performs all the pretty-printer string output. It is called with a string [s], a start position [p], and a number of characters [n]; it is supposed to output characters [p] to [p + n - 1] of [s]. - the [out_flush] function flushes the pretty-printer output device. - [out_newline] is called to open a new line when the pretty-printer splits the line. - the [out_spaces] function outputs spaces when a break hint leads to spaces instead of a line split. It is called with the number of spaces to output. - the [out_indent] function performs new line indentation when the pretty-printer splits the line. It is called with the indentation value of the new line. By default: - fields [out_string] and [out_flush] are output device specific; (e.g. {!Stdlib.output_string} and {!Stdlib.flush} for a {!Stdlib.out_channel} device, or [Buffer.add_substring] and {!Stdlib.ignore} for a [Buffer.t] output device), - field [out_newline] is equivalent to [out_string "\n" 0 1]; - fields [out_spaces] and [out_indent] are equivalent to [out_string (String.make n ' ') 0 n]. @since 4.01.0 *) val pp_set_formatter_out_functions : formatter -> formatter_out_functions -> unit val set_formatter_out_functions : formatter_out_functions -> unit * [ pp_set_formatter_out_functions ppf out_funs ] Set all the pretty - printer output functions of [ ppf ] to those of argument [ out_funs ] , This way , you can change the meaning of indentation ( which can be something else than just printing space characters ) and the meaning of new lines opening ( which can be connected to any other action needed by the application at hand ) . Reasonable defaults for functions [ out_spaces ] and [ out_newline ] are respectively [ out_funs.out_string ( String.make n ' ' ) 0 n ] and [ out_funs.out_string " \n " 0 1 ] . @since 4.01.0 Set all the pretty-printer output functions of [ppf] to those of argument [out_funs], This way, you can change the meaning of indentation (which can be something else than just printing space characters) and the meaning of new lines opening (which can be connected to any other action needed by the application at hand). Reasonable defaults for functions [out_spaces] and [out_newline] are respectively [out_funs.out_string (String.make n ' ') 0 n] and [out_funs.out_string "\n" 0 1]. @since 4.01.0 *) val pp_get_formatter_out_functions : formatter -> unit -> formatter_out_functions val get_formatter_out_functions : unit -> formatter_out_functions * Return the current output functions of the pretty - printer , including line splitting and indentation functions . Useful to record the current setting and restore it afterwards . @since 4.01.0 including line splitting and indentation functions. Useful to record the current setting and restore it afterwards. @since 4.01.0 *) * { 1 : tagsmeaning Redefining semantic tag operations } type formatter_stag_functions = { mark_open_stag : stag -> string; mark_close_stag : stag -> string; print_open_stag : stag -> unit; print_close_stag : stag -> unit; } * The semantic tag handling functions specific to a formatter : [ mark ] versions are the ' tag - marking ' functions that associate a string marker to a tag in order for the pretty - printing engine to write those markers as 0 length tokens in the output device of the formatter . [ print ] versions are the ' tag - printing ' functions that can perform regular printing when a tag is closed or opened . @since 4.08.0 [mark] versions are the 'tag-marking' functions that associate a string marker to a tag in order for the pretty-printing engine to write those markers as 0 length tokens in the output device of the formatter. [print] versions are the 'tag-printing' functions that can perform regular printing when a tag is closed or opened. @since 4.08.0 *) val pp_set_formatter_stag_functions : formatter -> formatter_stag_functions -> unit val set_formatter_stag_functions : formatter_stag_functions -> unit * [ pp_set_formatter_stag_functions ppf tag_funs ] changes the meaning of opening and closing semantic tag operations to use the functions in [ tag_funs ] when printing on [ ppf ] . When opening a semantic tag with name [ t ] , the string [ t ] is passed to the opening tag - marking function ( the [ mark_open_stag ] field of the record [ tag_funs ] ) , that must return the opening tag marker for that name . When the next call to [ ( ) ] happens , the semantic tag name [ t ] is sent back to the closing tag - marking function ( the [ mark_close_stag ] field of record [ tag_funs ] ) , that must return a closing tag marker for that name . The [ print _ ] field of the record contains the tag - printing functions that are called at tag opening and tag closing time , to output regular material in the pretty - printer queue . @since 4.08.0 opening and closing semantic tag operations to use the functions in [tag_funs] when printing on [ppf]. When opening a semantic tag with name [t], the string [t] is passed to the opening tag-marking function (the [mark_open_stag] field of the record [tag_funs]), that must return the opening tag marker for that name. When the next call to [close_stag ()] happens, the semantic tag name [t] is sent back to the closing tag-marking function (the [mark_close_stag] field of record [tag_funs]), that must return a closing tag marker for that name. The [print_] field of the record contains the tag-printing functions that are called at tag opening and tag closing time, to output regular material in the pretty-printer queue. @since 4.08.0 *) val pp_get_formatter_stag_functions : formatter -> unit -> formatter_stag_functions val get_formatter_stag_functions : unit -> formatter_stag_functions * Return the current semantic tag operation functions of the standard pretty - printer . @since 4.08.0 pretty-printer. @since 4.08.0 *) * { 1 : formatter Defining formatters } Defining new formatters permits unrelated output of material in parallel on several output devices . All the parameters of a formatter are local to the formatter : right margin , maximum indentation limit , maximum number of pretty - printing boxes simultaneously open , ellipsis , and so on , are specific to each formatter and may be fixed independently . For instance , given a { ! Buffer.t } buffer [ b ] , { ! formatter_of_buffer } [ b ] returns a new formatter using buffer [ b ] as its output device . Similarly , given a { ! Stdlib.out_channel } output channel [ oc ] , { ! formatter_of_out_channel } [ oc ] returns a new formatter using channel [ oc ] as its output device . Alternatively , given [ out_funs ] , a complete set of output functions for a formatter , then { ! formatter_of_out_functions } [ out_funs ] computes a new formatter using those functions for output . Defining new formatters permits unrelated output of material in parallel on several output devices. All the parameters of a formatter are local to the formatter: right margin, maximum indentation limit, maximum number of pretty-printing boxes simultaneously open, ellipsis, and so on, are specific to each formatter and may be fixed independently. For instance, given a {!Buffer.t} buffer [b], {!formatter_of_buffer} [b] returns a new formatter using buffer [b] as its output device. Similarly, given a {!Stdlib.out_channel} output channel [oc], {!formatter_of_out_channel} [oc] returns a new formatter using channel [oc] as its output device. Alternatively, given [out_funs], a complete set of output functions for a formatter, then {!formatter_of_out_functions} [out_funs] computes a new formatter using those functions for output. *) val formatter_of_out_channel : out_channel -> formatter (** [formatter_of_out_channel oc] returns a new formatter writing to the corresponding output channel [oc]. *) val std_formatter : formatter (** The standard formatter to write to standard output. It is defined as {!formatter_of_out_channel} {!Stdlib.stdout}. *) val err_formatter : formatter (** A formatter to write to standard error. It is defined as {!formatter_of_out_channel} {!Stdlib.stderr}. *) val formatter_of_buffer : Buffer.t -> formatter (** [formatter_of_buffer b] returns a new formatter writing to buffer [b]. At the end of pretty-printing, the formatter must be flushed using {!pp_print_flush} or {!pp_print_newline}, to print all the pending material into the buffer. *) val stdbuf : Buffer.t (** The string buffer in which [str_formatter] writes. *) val str_formatter : formatter (** A formatter to output to the {!stdbuf} string buffer. [str_formatter] is defined as {!formatter_of_buffer} {!stdbuf}. *) val flush_str_formatter : unit -> string (** Returns the material printed with [str_formatter], flushes the formatter and resets the corresponding buffer. *) val make_formatter : (string -> int -> int -> unit) -> (unit -> unit) -> formatter (** [make_formatter out flush] returns a new formatter that outputs with function [out], and flushes with function [flush]. For instance, {[ make_formatter (Stdlib.output oc) (fun () -> Stdlib.flush oc) ]} returns a formatter to the {!Stdlib.out_channel} [oc]. *) val formatter_of_out_functions : formatter_out_functions -> formatter * [ formatter_of_out_functions out_funs ] returns a new formatter that writes with the set of output functions [ out_funs ] . See definition of type { ! formatter_out_functions } for the meaning of argument [ out_funs ] . @since 4.06.0 with the set of output functions [out_funs]. See definition of type {!formatter_out_functions} for the meaning of argument [out_funs]. @since 4.06.0 *) * { 2 : symbolic Symbolic pretty - printing } * Symbolic pretty - printing is pretty - printing using a symbolic formatter , i.e. a formatter that outputs symbolic pretty - printing items . When using a symbolic formatter , all regular pretty - printing activities occur but output material is symbolic and stored in a buffer of output items . At the end of pretty - printing , flushing the output buffer allows post - processing of symbolic output before performing low level output operations . In practice , first define a symbolic output buffer [ b ] using : - [ let sob = make_symbolic_output_buffer ( ) ] . Then define a symbolic formatter with : - [ let ppf = formatter_of_symbolic_output_buffer sob ] Use symbolic formatter [ ppf ] as usual , and retrieve symbolic items at end of pretty - printing by flushing symbolic output buffer [ sob ] with : - [ flush_symbolic_output_buffer sob ] . Symbolic pretty-printing is pretty-printing using a symbolic formatter, i.e. a formatter that outputs symbolic pretty-printing items. When using a symbolic formatter, all regular pretty-printing activities occur but output material is symbolic and stored in a buffer of output items. At the end of pretty-printing, flushing the output buffer allows post-processing of symbolic output before performing low level output operations. In practice, first define a symbolic output buffer [b] using: - [let sob = make_symbolic_output_buffer ()]. Then define a symbolic formatter with: - [let ppf = formatter_of_symbolic_output_buffer sob] Use symbolic formatter [ppf] as usual, and retrieve symbolic items at end of pretty-printing by flushing symbolic output buffer [sob] with: - [flush_symbolic_output_buffer sob]. *) type symbolic_output_item = | Output_flush (** symbolic flush command *) | Output_newline (** symbolic newline command *) | Output_string of string (** [Output_string s]: symbolic output for string [s]*) | Output_spaces of int (** [Output_spaces n]: symbolic command to output [n] spaces *) | Output_indent of int (** [Output_indent i]: symbolic indentation of size [i] *) * Items produced by symbolic pretty - printers @since 4.06.0 @since 4.06.0 *) type symbolic_output_buffer * The output buffer of a symbolic pretty - printer . @since 4.06.0 The output buffer of a symbolic pretty-printer. @since 4.06.0 *) val make_symbolic_output_buffer : unit -> symbolic_output_buffer * [ make_symbolic_output_buffer ( ) ] returns a fresh buffer for symbolic output . @since 4.06.0 symbolic output. @since 4.06.0 *) val clear_symbolic_output_buffer : symbolic_output_buffer -> unit * [ clear_symbolic_output_buffer sob ] resets buffer [ sob ] . @since 4.06.0 @since 4.06.0 *) val get_symbolic_output_buffer : symbolic_output_buffer -> symbolic_output_item list * [ get_symbolic_output_buffer sob ] returns the contents of buffer [ sob ] . @since 4.06.0 @since 4.06.0 *) val flush_symbolic_output_buffer : symbolic_output_buffer -> symbolic_output_item list * [ flush_symbolic_output_buffer sob ] returns the contents of buffer [ sob ] and resets buffer [ sob ] . [ flush_symbolic_output_buffer sob ] is equivalent to [ let items = get_symbolic_output_buffer sob in clear_symbolic_output_buffer sob ; items ] @since 4.06.0 [sob] and resets buffer [sob]. [flush_symbolic_output_buffer sob] is equivalent to [let items = get_symbolic_output_buffer sob in clear_symbolic_output_buffer sob; items] @since 4.06.0 *) val add_symbolic_output_item : symbolic_output_buffer -> symbolic_output_item -> unit * [ add_symbolic_output_item sob itm ] adds item [ itm ] to buffer [ sob ] . @since 4.06.0 @since 4.06.0 *) val formatter_of_symbolic_output_buffer : symbolic_output_buffer -> formatter * [ formatter_of_symbolic_output_buffer sob ] returns a symbolic formatter that outputs to [ ] [ sob ] . @since 4.06.0 that outputs to [symbolic_output_buffer] [sob]. @since 4.06.0 *) * { 1 Convenience formatting functions . } val pp_print_list: ?pp_sep:(formatter -> unit -> unit) -> (formatter -> 'a -> unit) -> (formatter -> 'a list -> unit) * [ pp_print_list ? pp_sep pp_v ppf l ] prints items of list [ l ] , using [ pp_v ] to print each item , and calling [ pp_sep ] between items ( [ pp_sep ] defaults to { ! pp_print_cut } . Does nothing on empty lists . @since 4.02.0 using [pp_v] to print each item, and calling [pp_sep] between items ([pp_sep] defaults to {!pp_print_cut}. Does nothing on empty lists. @since 4.02.0 *) val pp_print_seq: ?pp_sep:(formatter -> unit -> unit) -> (formatter -> 'a -> unit) -> (formatter -> 'a Seq.t -> unit) * [ pp_print_seq ? pp_sep pp_v ppf s ] prints items of sequence [ s ] , using [ pp_v ] to print each item , and calling [ pp_sep ] between items ( [ pp_sep ] defaults to { ! pp_print_cut } . Does nothing on empty sequences . This function does not terminate on infinite sequences . @since 4.12 using [pp_v] to print each item, and calling [pp_sep] between items ([pp_sep] defaults to {!pp_print_cut}. Does nothing on empty sequences. This function does not terminate on infinite sequences. @since 4.12 *) val pp_print_text : formatter -> string -> unit * [ pp_print_text ppf s ] prints [ s ] with spaces and newlines respectively printed using { ! pp_print_space } and { ! pp_force_newline } . @since 4.02.0 printed using {!pp_print_space} and {!pp_force_newline}. @since 4.02.0 *) val pp_print_option : ?none:(formatter -> unit -> unit) -> (formatter -> 'a -> unit) -> (formatter -> 'a option -> unit) * [ pp_print_option ? none pp_v ppf o ] prints [ o ] on [ ppf ] using [ pp_v ] if [ o ] is [ Some v ] and [ none ] if it is [ None ] . [ none ] prints nothing by default . @since 4.08 using [pp_v] if [o] is [Some v] and [none] if it is [None]. [none] prints nothing by default. @since 4.08 *) val pp_print_result : ok:(formatter -> 'a -> unit) -> error:(formatter -> 'e -> unit) -> formatter -> ('a, 'e) result -> unit * [ pp_print_result ~ok ~error ppf r ] prints [ r ] on [ ppf ] using [ ok ] if [ r ] is [ Ok _ ] and [ error ] if [ r ] is [ Error _ ] . @since 4.08 [ok] if [r] is [Ok _] and [error] if [r] is [Error _]. @since 4.08 *) val pp_print_either : left:(formatter -> 'a -> unit) -> right:(formatter -> 'b -> unit) -> formatter -> ('a, 'b) Either.t -> unit * [ pp_print_either ~left ~right e ] prints [ e ] on [ ppf ] using [ left ] if [ e ] is [ Either . Left _ ] and [ right ] if [ e ] is [ Either . Right _ ] . @since 4.13 [left] if [e] is [Either.Left _] and [right] if [e] is [Either.Right _]. @since 4.13 *) * { 1 : fpp Formatted pretty - printing } (** Module [Format] provides a complete set of [printf] like functions for pretty-printing using format string specifications. Specific annotations may be added in the format strings to give pretty-printing commands to the pretty-printing engine. Those annotations are introduced in the format strings using the [@] character. For instance, [@ ] means a space break, [@,] means a cut, [@\[] opens a new box, and [@\]] closes the last open box. *) val fprintf : formatter -> ('a, formatter, unit) format -> 'a * [ fprintf ff fmt arg1 ... argN ] formats the arguments [ arg1 ] to [ argN ] according to the format string [ fmt ] , and outputs the resulting string on the formatter [ ff ] . The format string [ fmt ] is a character string which contains three types of objects : plain characters and conversion specifications as specified in the { ! Printf } module , and pretty - printing indications specific to the [ Format ] module . The pretty - printing indication characters are introduced by a [ @ ] character , and their meanings are : - [ @\ [ ] : open a pretty - printing box . The type and offset of the box may be optionally specified with the following syntax : the [ < ] character , followed by an optional box type indication , then an optional integer offset , and the closing [ > ] character . Pretty - printing box type is one of [ h ] , [ v ] , [ hv ] , [ b ] , or [ hov ] . ' [ h ] ' stands for an ' horizontal ' pretty - printing box , ' [ v ] ' stands for a ' vertical ' pretty - printing box , ' [ hv ] ' stands for an ' horizontal / vertical ' pretty - printing box , ' [ b ] ' stands for an ' horizontal - or - vertical ' pretty - printing box demonstrating indentation , ' [ hov ] ' stands a simple ' horizontal - or - vertical ' pretty - printing box . For instance , [ @\[<hov 2 > ] opens an ' horizontal - or - vertical ' pretty - printing box with indentation 2 as obtained with [ open_hovbox 2 ] . For more details about pretty - printing boxes , see the various box opening functions [ open_*box ] . - [ @\ ] ] : close the most recently opened pretty - printing box . - [ @ , ] : output a ' cut ' break hint , as with [ print_cut ( ) ] . - [ @ ] : output a ' space ' break hint , as with [ print_space ( ) ] . - [ @ ; ] : output a ' full ' break hint as with [ print_break ] . The [ nspaces ] and [ offset ] parameters of the break hint may be optionally specified with the following syntax : the [ < ] character , followed by an integer [ nspaces ] value , then an integer [ offset ] , and a closing [ > ] character . If no parameters are provided , the good break defaults to a ' space ' break hint . - [ @. ] : flush the pretty - printer and split the line , as with [ print_newline ( ) ] . - [ @<n > ] : print the following item as if it were of length [ n ] . Hence , [ printf " @<0>%s " arg ] prints [ arg ] as a zero length string . If [ @<n > ] is not followed by a conversion specification , then the following character of the format is printed as if it were of length [ n ] . - [ @\ { ] : open a semantic tag . The name of the tag may be optionally specified with the following syntax : the [ < ] character , followed by an optional string specification , and the closing [ > ] character . The string specification is any character string that does not contain the closing character [ ' > ' ] . If omitted , the tag name defaults to the empty string . For more details about semantic tags , see the functions { ! open_stag } and { ! } . - [ @\ } ] : close the most recently opened semantic tag . - [ @ ? ] : flush the pretty - printer as with [ print_flush ( ) ] . This is equivalent to the conversion [ % ! ] . - [ @\n ] : force a newline , as with [ force_newline ( ) ] , not the normal way of pretty - printing , you should prefer using break hints inside a vertical pretty - printing box . Note : To prevent the interpretation of a [ @ ] character as a pretty - printing indication , escape it with a [ % ] character . Old quotation mode [ @@ ] is deprecated since it is not compatible with formatted input interpretation of character [ ' @ ' ] . Example : [ printf " @[%s@ % d@]@. " " x = " 1 ] is equivalent to [ open_box ( ) ; print_string " x = " ; print_space ( ) ; print_int 1 ; close_box ( ) ; print_newline ( ) ] . It prints [ x = 1 ] within a pretty - printing ' horizontal - or - vertical ' box . according to the format string [fmt], and outputs the resulting string on the formatter [ff]. The format string [fmt] is a character string which contains three types of objects: plain characters and conversion specifications as specified in the {!Printf} module, and pretty-printing indications specific to the [Format] module. The pretty-printing indication characters are introduced by a [@] character, and their meanings are: - [@\[]: open a pretty-printing box. The type and offset of the box may be optionally specified with the following syntax: the [<] character, followed by an optional box type indication, then an optional integer offset, and the closing [>] character. Pretty-printing box type is one of [h], [v], [hv], [b], or [hov]. '[h]' stands for an 'horizontal' pretty-printing box, '[v]' stands for a 'vertical' pretty-printing box, '[hv]' stands for an 'horizontal/vertical' pretty-printing box, '[b]' stands for an 'horizontal-or-vertical' pretty-printing box demonstrating indentation, '[hov]' stands a simple 'horizontal-or-vertical' pretty-printing box. For instance, [@\[<hov 2>] opens an 'horizontal-or-vertical' pretty-printing box with indentation 2 as obtained with [open_hovbox 2]. For more details about pretty-printing boxes, see the various box opening functions [open_*box]. - [@\]]: close the most recently opened pretty-printing box. - [@,]: output a 'cut' break hint, as with [print_cut ()]. - [@ ]: output a 'space' break hint, as with [print_space ()]. - [@;]: output a 'full' break hint as with [print_break]. The [nspaces] and [offset] parameters of the break hint may be optionally specified with the following syntax: the [<] character, followed by an integer [nspaces] value, then an integer [offset], and a closing [>] character. If no parameters are provided, the good break defaults to a 'space' break hint. - [@.]: flush the pretty-printer and split the line, as with [print_newline ()]. - [@<n>]: print the following item as if it were of length [n]. Hence, [printf "@<0>%s" arg] prints [arg] as a zero length string. If [@<n>] is not followed by a conversion specification, then the following character of the format is printed as if it were of length [n]. - [@\{]: open a semantic tag. The name of the tag may be optionally specified with the following syntax: the [<] character, followed by an optional string specification, and the closing [>] character. The string specification is any character string that does not contain the closing character ['>']. If omitted, the tag name defaults to the empty string. For more details about semantic tags, see the functions {!open_stag} and {!close_stag}. - [@\}]: close the most recently opened semantic tag. - [@?]: flush the pretty-printer as with [print_flush ()]. This is equivalent to the conversion [%!]. - [@\n]: force a newline, as with [force_newline ()], not the normal way of pretty-printing, you should prefer using break hints inside a vertical pretty-printing box. Note: To prevent the interpretation of a [@] character as a pretty-printing indication, escape it with a [%] character. Old quotation mode [@@] is deprecated since it is not compatible with formatted input interpretation of character ['@']. Example: [printf "@[%s@ %d@]@." "x =" 1] is equivalent to [open_box (); print_string "x ="; print_space (); print_int 1; close_box (); print_newline ()]. It prints [x = 1] within a pretty-printing 'horizontal-or-vertical' box. *) val printf : ('a, formatter, unit) format -> 'a (** Same as [fprintf] above, but output on [std_formatter]. *) val eprintf : ('a, formatter, unit) format -> 'a (** Same as [fprintf] above, but output on [err_formatter]. *) val sprintf : ('a, unit, string) format -> 'a (** Same as [printf] above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. Note that the pretty-printer queue is flushed at the end of {e each call} to [sprintf]. In case of multiple and related calls to [sprintf] to output material on a single string, you should consider using [fprintf] with the predefined formatter [str_formatter] and call [flush_str_formatter ()] to get the final result. Alternatively, you can use [Format.fprintf] with a formatter writing to a buffer of your own: flushing the formatter and the buffer at the end of pretty-printing returns the desired string. *) val asprintf : ('a, formatter, unit, string) format4 -> 'a * Same as [ printf ] above , but instead of printing on a formatter , returns a string containing the result of formatting the arguments . The type of [ asprintf ] is general enough to interact nicely with [ % a ] conversions . @since 4.01.0 returns a string containing the result of formatting the arguments. The type of [asprintf] is general enough to interact nicely with [%a] conversions. @since 4.01.0 *) val dprintf : ('a, formatter, unit, formatter -> unit) format4 -> 'a * Same as { ! } , except the formatter is the last argument . [ dprintf " ... " a b c ] is a function of type [ formatter - > unit ] which can be given to a format specifier [ % t ] . This can be used as a replacement for { ! } to delay formatting decisions . Using the string returned by { ! } in a formatting context forces formatting decisions to be taken in isolation , and the final string may be created prematurely . { ! } allows delay of formatting decisions until the final formatting context is known . For example : { [ let t = Format.dprintf " % i@ % i@ % i " 1 2 3 in ... Format.printf " @[<v>%t@ ] " t ] } @since 4.08.0 [dprintf "..." a b c] is a function of type [formatter -> unit] which can be given to a format specifier [%t]. This can be used as a replacement for {!asprintf} to delay formatting decisions. Using the string returned by {!asprintf} in a formatting context forces formatting decisions to be taken in isolation, and the final string may be created prematurely. {!dprintf} allows delay of formatting decisions until the final formatting context is known. For example: {[ let t = Format.dprintf "%i@ %i@ %i" 1 2 3 in ... Format.printf "@[<v>%t@]" t ]} @since 4.08.0 *) val ifprintf : formatter -> ('a, formatter, unit) format -> 'a * Same as [ fprintf ] above , but does not print anything . Useful to ignore some material when conditionally printing . @since 3.10.0 Useful to ignore some material when conditionally printing. @since 3.10.0 *) (** Formatted Pretty-Printing with continuations. *) val kfprintf : (formatter -> 'a) -> formatter -> ('b, formatter, unit, 'a) format4 -> 'b * Same as [ fprintf ] above , but instead of returning immediately , passes the formatter to its first argument at the end of printing . passes the formatter to its first argument at the end of printing. *) val kdprintf : ((formatter -> unit) -> 'a) -> ('b, formatter, unit, 'a) format4 -> 'b * Same as { ! } above , but instead of returning immediately , passes the suspended printer to its first argument at the end of printing . @since 4.08.0 passes the suspended printer to its first argument at the end of printing. @since 4.08.0 *) val ikfprintf : (formatter -> 'a) -> formatter -> ('b, formatter, unit, 'a) format4 -> 'b * Same as [ ] above , but does not print anything . Useful to ignore some material when conditionally printing . @since 3.12.0 Useful to ignore some material when conditionally printing. @since 3.12.0 *) val ksprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b * Same as [ sprintf ] above , but instead of returning the string , passes it to the first argument . passes it to the first argument. *) val kasprintf : (string -> 'a) -> ('b, formatter, unit, 'a) format4 -> 'b * Same as [ asprintf ] above , but instead of returning the string , passes it to the first argument . @since 4.03 passes it to the first argument. @since 4.03 *) (** {1 Deprecated} *) val bprintf : Buffer.t -> ('a, formatter, unit) format -> 'a [@@ocaml.deprecated] * @deprecated This function is error prone . Do not use it . This function is neither compositional nor incremental , since it flushes the pretty - printer queue at each call . If you need to print to some buffer [ b ] , you must first define a formatter writing to [ b ] , using [ let to_b = formatter_of_buffer b ] ; then use regular calls to [ Format.fprintf ] with formatter [ to_b ] . This function is neither compositional nor incremental, since it flushes the pretty-printer queue at each call. If you need to print to some buffer [b], you must first define a formatter writing to [b], using [let to_b = formatter_of_buffer b]; then use regular calls to [Format.fprintf] with formatter [to_b]. *) val kprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b [@@ocaml.deprecated "Use Format.ksprintf instead."] (** @deprecated An alias for [ksprintf]. *) val set_all_formatter_output_functions : out:(string -> int -> int -> unit) -> flush:(unit -> unit) -> newline:(unit -> unit) -> spaces:(int -> unit) -> unit [@@ocaml.deprecated "Use Format.set_formatter_out_functions instead."] (** @deprecated Subsumed by [set_formatter_out_functions]. *) val get_all_formatter_output_functions : unit -> (string -> int -> int -> unit) * (unit -> unit) * (unit -> unit) * (int -> unit) [@@ocaml.deprecated "Use Format.get_formatter_out_functions instead."] (** @deprecated Subsumed by [get_formatter_out_functions]. *) val pp_set_all_formatter_output_functions : formatter -> out:(string -> int -> int -> unit) -> flush:(unit -> unit) -> newline:(unit -> unit) -> spaces:(int -> unit) -> unit [@@ocaml.deprecated "Use Format.pp_set_formatter_out_functions instead."] (** @deprecated Subsumed by [pp_set_formatter_out_functions]. *) val pp_get_all_formatter_output_functions : formatter -> unit -> (string -> int -> int -> unit) * (unit -> unit) * (unit -> unit) * (int -> unit) [@@ocaml.deprecated "Use Format.pp_get_formatter_out_functions instead."] (** @deprecated Subsumed by [pp_get_formatter_out_functions]. *) * { 2 String tags } val pp_open_tag : formatter -> tag -> unit [@@ocaml.deprecated "Use Format.pp_open_stag."] * @deprecated Subsumed by { ! } . val open_tag : tag -> unit [@@ocaml.deprecated "Use Format.open_stag."] (** @deprecated Subsumed by {!open_stag}. *) val pp_close_tag : formatter -> unit -> unit [@@ocaml.deprecated "Use Format.pp_close_stag."] (** @deprecated Subsumed by {!pp_close_stag}. *) val close_tag : unit -> unit [@@ocaml.deprecated "Use Format.close_stag."] * @deprecated Subsumed by { ! } . type formatter_tag_functions = { mark_open_tag : tag -> string; mark_close_tag : tag -> string; print_open_tag : tag -> unit; print_close_tag : tag -> unit; } [@@ocaml.deprecated "Use formatter_stag_functions."] (** @deprecated Subsumed by {!formatter_stag_functions}. *) val pp_set_formatter_tag_functions : formatter -> formatter_tag_functions -> unit [@@ocaml.deprecated "This function will erase non-string tag formatting functions. \ Use Format.pp_set_formatter_stag_functions."] [@@warning "-3"] (** This function will erase non-string tag formatting functions. @deprecated Subsumed by {!pp_set_formatter_stag_functions}. *) val set_formatter_tag_functions : formatter_tag_functions -> unit [@@ocaml.deprecated "Use Format.set_formatter_stag_functions."] [@@warning "-3"] (** @deprecated Subsumed by {!set_formatter_stag_functions}. *) val pp_get_formatter_tag_functions : formatter -> unit -> formatter_tag_functions [@@ocaml.deprecated "Use Format.pp_get_formatter_stag_functions."] [@@warning "-3"] (** @deprecated Subsumed by {!pp_get_formatter_stag_functions}. *) val get_formatter_tag_functions : unit -> formatter_tag_functions [@@ocaml.deprecated "Use Format.get_formatter_stag_functions."] [@@warning "-3"] * @deprecated Subsumed by { ! } .
null
https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/stdlib/format.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ A tutorial to the Format module is provided at {!Format_tutorial}. * {1 Formatters} * Abstract data corresponding to a pretty-printer (also called a formatter) and all its machinery. See also {!section:formatter}. * The pretty-printing engine uses the concepts of pretty-printing box and break hint to drive indentation and line splitting behavior of the pretty-printer. Each different pretty-printing box kind introduces a specific line splitting policy: - within an {e horizontal} box, break hints never split the line (but the line may be split in a box nested deeper), - within a {e vertical} box, break hints always split the line, - within an {e horizontal/vertical} box, if the box fits on the current line then break hints never split the line, otherwise break hint always split the line, - within a {e compacting} box, a break hint never splits the line, unless there is no more room on the current line. Note that line splitting policy is box specific: the policy of a box does not rule the policy of inner boxes. For instance, if a vertical box is nested in an horizontal box, all break hints within the vertical box will split the line. Moreover, opening a box after the {{!maxindent}maximum indentation limit} splits the line whether or not the box would end up fitting on the line. * [pp_open_box ppf d] opens a new compacting pretty-printing box with offset [d] in the formatter [ppf]. Within this box, the pretty-printer prints as much as possible material on every line. A break hint splits the line if there is no more room on the line to print the remainder of the box. Within this box, the pretty-printer emphasizes the box structure: if a structural box does not fit fully on a simple line, a break hint also splits the line if the splitting ``moves to the left'' (i.e. the new line gets an indentation smaller than the one of the current line). This box is the general purpose pretty-printing box. If the pretty-printer splits the line in the box, offset [d] is added to the current indentation. * Closes the most recently open pretty-printing box. * [pp_open_vbox ppf d] opens a new 'vertical' pretty-printing box with offset [d]. This box prints material on as many lines as break hints in the box. Every break hint in a vertical box splits the line. If the pretty-printer splits the line in the box, [d] is added to the current indentation. * [pp_open_hvbox ppf d] opens a new 'horizontal/vertical' pretty-printing box with offset [d]. This box behaves as an horizontal box if it fits on a single line, otherwise it behaves as a vertical box. If the pretty-printer splits the line in the box, [d] is added to the current indentation. * [pp_open_hovbox ppf d] opens a new 'horizontal-or-vertical' pretty-printing box with offset [d]. This box prints material as much as possible on every line. A break hint splits the line if there is no more room on the line to print the remainder of the box. If the pretty-printer splits the line in the box, [d] is added to the current indentation. * {1 Formatting functions} * [pp_print_as ppf len s] prints [s] in the current pretty-printing box. The pretty-printer formats [s] as if it were of length [len]. * Print an integer in the current pretty-printing box. * Print a floating point number in the current pretty-printing box. * Print a character in the current pretty-printing box. * Print a boolean in the current pretty-printing box. * Force a new line in the current pretty-printing box. The pretty-printer must split the line at this point, Not the normal way of pretty-printing, since imperative line splitting may interfere with current line counters and box size calculation. Using break hints within an enclosing vertical box is a better alternative. * Execute the next formatting command if the preceding line has just been split. Otherwise, ignore the next formatting command. * End of pretty-printing: resets the pretty-printer to initial state. All open pretty-printing boxes are closed, all pending text is printed. In addition, the pretty-printer low level output device is flushed to ensure that all pending text is really displayed. Note: never use [print_flush] in the normal course of a pretty-printing routine, since the pretty-printer uses a complex buffering machinery to properly indent the output; manually flushing those buffers at random would conflict with the pretty-printer strategy and result to poor rendering. Only consider using [print_flush] when displaying all pending material is mandatory (for instance in case of interactive use when you want the user to read some text) and when resetting the pretty-printer state will not disturb further pretty-printing. Warning: If the output device of the pretty-printer is an output channel, repeated calls to [print_flush] means repeated calls to {!Stdlib.flush} to flush the out channel; these explicit flush calls could foil the buffering strategy of output channels and could dramatically impact efficiency. * End of pretty-printing: resets the pretty-printer to initial state. All open pretty-printing boxes are closed, all pending text is printed. Equivalent to {!print_flush} followed by a new line. See corresponding words of caution for {!print_flush}. Note: this is not the normal way to output a new line; the preferred method is using break hints within a vertical pretty-printing box. * {1 Margin} * Returns the position of the right margin. * Return the maximum indentation limit (in characters). * The maximum formatting depth is the maximum number of pretty-printing boxes simultaneously open. Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by {!get_ellipsis_text} [()]). * Returns the maximum number of pretty-printing boxes allowed before ellipsis. * Tests if the maximum number of pretty-printing boxes allowed have already been opened. * A {e tabulation box} prints material on lines divided into cells of fixed length. A tabulation box provides a simple way to display vertical columns of left adjusted text. This box features command [set_tab] to define cell boundaries, and command [print_tab] to move from cell to cell and split the line when there is no more cells to print on the line. Note: printing within tabulation box is line directed, so arbitrary line splitting inside a tabulation box leads to poor rendering. Yet, controlled use of tabulation boxes allows simple printing of columns within module {!Format}. * Closes the most recently opened tabulation box. * Sets a tabulation marker at current insertion point. * {1 Ellipsis} * Set the text of the ellipsis printed when too many pretty-printing boxes are open (a single dot, [.], by default). * Return the text of the ellipsis. * [pp_set_print_tags ppf b] turns on or off the tag-printing operations. * [pp_set_mark_tags ppf b] turns on or off the tag-marking operations. * Return the current status of tag-printing operations. * Return the current status of tag-marking operations. * {1 Redirecting the standard formatter output} * Redirect the standard pretty-printer output to the given channel. (All the output functions of the standard formatter are set to the default output functions printing to the given channel.) [set_formatter_out_channel] is equivalent to {!pp_set_formatter_out_channel} [std_formatter]. * [pp_set_formatter_output_functions ppf out flush] redirects the standard pretty-printer output functions to the functions [out] and [flush]. The [out] function performs all the pretty-printer string output. It is called with a string [s], a start position [p], and a number of characters [n]; it is supposed to output characters [p] to [p + n - 1] of [s]. The [flush] function is called whenever the pretty-printer is flushed (via conversion [%!], or pretty-printing indications [@?] or [@.], or using low level functions [print_flush] or [print_newline]). * Return the current output functions of the standard pretty-printer. * The [Format] module is versatile enough to let you completely redefine the meaning of pretty-printing output: you may provide your own functions to define how to handle indentation, line splitting, and even printing of all the characters that have to be printed! * [formatter_of_out_channel oc] returns a new formatter writing to the corresponding output channel [oc]. * The standard formatter to write to standard output. It is defined as {!formatter_of_out_channel} {!Stdlib.stdout}. * A formatter to write to standard error. It is defined as {!formatter_of_out_channel} {!Stdlib.stderr}. * [formatter_of_buffer b] returns a new formatter writing to buffer [b]. At the end of pretty-printing, the formatter must be flushed using {!pp_print_flush} or {!pp_print_newline}, to print all the pending material into the buffer. * The string buffer in which [str_formatter] writes. * A formatter to output to the {!stdbuf} string buffer. [str_formatter] is defined as {!formatter_of_buffer} {!stdbuf}. * Returns the material printed with [str_formatter], flushes the formatter and resets the corresponding buffer. * [make_formatter out flush] returns a new formatter that outputs with function [out], and flushes with function [flush]. For instance, {[ make_formatter (Stdlib.output oc) (fun () -> Stdlib.flush oc) ]} returns a formatter to the {!Stdlib.out_channel} [oc]. * symbolic flush command * symbolic newline command * [Output_string s]: symbolic output for string [s] * [Output_spaces n]: symbolic command to output [n] spaces * [Output_indent i]: symbolic indentation of size [i] * Module [Format] provides a complete set of [printf] like functions for pretty-printing using format string specifications. Specific annotations may be added in the format strings to give pretty-printing commands to the pretty-printing engine. Those annotations are introduced in the format strings using the [@] character. For instance, [@ ] means a space break, [@,] means a cut, [@\[] opens a new box, and [@\]] closes the last open box. * Same as [fprintf] above, but output on [std_formatter]. * Same as [fprintf] above, but output on [err_formatter]. * Same as [printf] above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. Note that the pretty-printer queue is flushed at the end of {e each call} to [sprintf]. In case of multiple and related calls to [sprintf] to output material on a single string, you should consider using [fprintf] with the predefined formatter [str_formatter] and call [flush_str_formatter ()] to get the final result. Alternatively, you can use [Format.fprintf] with a formatter writing to a buffer of your own: flushing the formatter and the buffer at the end of pretty-printing returns the desired string. * Formatted Pretty-Printing with continuations. * {1 Deprecated} * @deprecated An alias for [ksprintf]. * @deprecated Subsumed by [set_formatter_out_functions]. * @deprecated Subsumed by [get_formatter_out_functions]. * @deprecated Subsumed by [pp_set_formatter_out_functions]. * @deprecated Subsumed by [pp_get_formatter_out_functions]. * @deprecated Subsumed by {!open_stag}. * @deprecated Subsumed by {!pp_close_stag}. * @deprecated Subsumed by {!formatter_stag_functions}. * This function will erase non-string tag formatting functions. @deprecated Subsumed by {!pp_set_formatter_stag_functions}. * @deprecated Subsumed by {!set_formatter_stag_functions}. * @deprecated Subsumed by {!pp_get_formatter_stag_functions}.
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the * Pretty - printing . This module implements a pretty - printing facility to format values within { { ! boxes}'pretty - printing boxes ' } and { { ! tags}'semantic tags ' } combined with a set of { { ! fpp}printf - like functions } . The pretty - printer splits lines at specified { { ! breaks}break hints } , and indents lines according to the box structure . Similarly , { { ! tags}semantic tags } can be used to decouple text presentation from its contents . This pretty - printing facility is implemented as an overlay on top of abstract { { ! section : formatter}formatters } which provide basic output functions . Some formatters are predefined , notably : - { ! std_formatter } outputs to { { ! } - { ! err_formatter } outputs to { { ! Stdlib.stderr}stderr } Most functions in the { ! Format } module come in two variants : a short version that operates on { ! std_formatter } and the generic version prefixed by [ pp _ ] that takes a formatter as its first argument . More formatters can be created with { ! formatter_of_out_channel } , { ! formatter_of_buffer } , { ! formatter_of_symbolic_output_buffer } or using { { ! section : formatter}custom formatters } . This module implements a pretty-printing facility to format values within {{!boxes}'pretty-printing boxes'} and {{!tags}'semantic tags'} combined with a set of {{!fpp}printf-like functions}. The pretty-printer splits lines at specified {{!breaks}break hints}, and indents lines according to the box structure. Similarly, {{!tags}semantic tags} can be used to decouple text presentation from its contents. This pretty-printing facility is implemented as an overlay on top of abstract {{!section:formatter}formatters} which provide basic output functions. Some formatters are predefined, notably: - {!std_formatter} outputs to {{!Stdlib.stdout}stdout} - {!err_formatter} outputs to {{!Stdlib.stderr}stderr} Most functions in the {!Format} module come in two variants: a short version that operates on {!std_formatter} and the generic version prefixed by [pp_] that takes a formatter as its first argument. More formatters can be created with {!formatter_of_out_channel}, {!formatter_of_buffer}, {!formatter_of_symbolic_output_buffer} or using {{!section:formatter}custom formatters}. *) * { 1 Introduction } You may consider this module as providing an extension to the [ printf ] facility to provide automatic line splitting . The addition of pretty - printing annotations to your regular [ printf ] format strings gives you fancy indentation and line breaks . Pretty - printing annotations are described below in the documentation of the function { ! Format.fprintf } . You may also use the explicit pretty - printing box management and printing functions provided by this module . This style is more basic but more verbose than the concise [ fprintf ] format strings . For instance , the sequence [ open_box 0 ; print_string " x = " ; print_space ( ) ; print_int 1 ; close_box ( ) ; print_newline ( ) ] that prints [ x = 1 ] within a pretty - printing box , can be abbreviated as [ printf " @[%s@ % i@]@. " " x = " 1 ] , or even shorter [ printf " @[x = @ % i@]@. " 1 ] . Rule of thumb for casual users of this library : - use simple pretty - printing boxes ( as obtained by [ open_box 0 ] ) ; - use simple break hints as obtained by [ print_cut ( ) ] that outputs a simple break hint , or by [ print_space ( ) ] that outputs a space indicating a break hint ; - once a pretty - printing box is open , display its material with basic printing functions ( [ print_int ] and [ print_string ] ) ; - when the material for a pretty - printing box has been printed , call [ close_box ( ) ] to close the box ; - at the end of pretty - printing , flush the pretty - printer to display all the remaining material , e.g. evaluate [ print_newline ( ) ] . The behavior of pretty - printing commands is unspecified if there is no open pretty - printing box . Each box opened by one of the [ open _ ] functions below must be closed using [ close_box ] for proper formatting . Otherwise , some of the material printed in the boxes may not be output , or may be formatted incorrectly . In case of interactive use , each phrase is executed in the initial state of the standard pretty - printer : after each phrase execution , the interactive system closes all open pretty - printing boxes , flushes all pending text , and resets the standard pretty - printer . Warning : mixing calls to pretty - printing functions of this module with calls to { ! } low level output functions is error prone . The pretty - printing functions output material that is delayed in the pretty - printer queue and stacks in order to compute proper line splitting . In contrast , basic I / O output functions write directly in their output device . As a consequence , the output of a basic I / O function may appear before the output of a pretty - printing function that has been called before . For instance , [ Stdlib.print_string " < " ; Format.print_string " PRETTY " ; Stdlib.print_string " > " ; Format.print_string " TEXT " ; ] leads to output [ < > PRETTYTEXT ] . You may consider this module as providing an extension to the [printf] facility to provide automatic line splitting. The addition of pretty-printing annotations to your regular [printf] format strings gives you fancy indentation and line breaks. Pretty-printing annotations are described below in the documentation of the function {!Format.fprintf}. You may also use the explicit pretty-printing box management and printing functions provided by this module. This style is more basic but more verbose than the concise [fprintf] format strings. For instance, the sequence [open_box 0; print_string "x ="; print_space (); print_int 1; close_box (); print_newline ()] that prints [x = 1] within a pretty-printing box, can be abbreviated as [printf "@[%s@ %i@]@." "x =" 1], or even shorter [printf "@[x =@ %i@]@." 1]. Rule of thumb for casual users of this library: - use simple pretty-printing boxes (as obtained by [open_box 0]); - use simple break hints as obtained by [print_cut ()] that outputs a simple break hint, or by [print_space ()] that outputs a space indicating a break hint; - once a pretty-printing box is open, display its material with basic printing functions (e. g. [print_int] and [print_string]); - when the material for a pretty-printing box has been printed, call [close_box ()] to close the box; - at the end of pretty-printing, flush the pretty-printer to display all the remaining material, e.g. evaluate [print_newline ()]. The behavior of pretty-printing commands is unspecified if there is no open pretty-printing box. Each box opened by one of the [open_] functions below must be closed using [close_box] for proper formatting. Otherwise, some of the material printed in the boxes may not be output, or may be formatted incorrectly. In case of interactive use, each phrase is executed in the initial state of the standard pretty-printer: after each phrase execution, the interactive system closes all open pretty-printing boxes, flushes all pending text, and resets the standard pretty-printer. Warning: mixing calls to pretty-printing functions of this module with calls to {!Stdlib} low level output functions is error prone. The pretty-printing functions output material that is delayed in the pretty-printer queue and stacks in order to compute proper line splitting. In contrast, basic I/O output functions write directly in their output device. As a consequence, the output of a basic I/O function may appear before the output of a pretty-printing function that has been called before. For instance, [ Stdlib.print_string "<"; Format.print_string "PRETTY"; Stdlib.print_string ">"; Format.print_string "TEXT"; ] leads to output [<>PRETTYTEXT]. *) type formatter * { 1 : boxes Pretty - printing boxes } val pp_open_box : formatter -> int -> unit val open_box : int -> unit val pp_close_box : formatter -> unit -> unit val close_box : unit -> unit val pp_open_hbox : formatter -> unit -> unit val open_hbox : unit -> unit * [ pp_open_hbox ( ) ] opens a new ' horizontal ' pretty - printing box . This box prints material on a single line . Break hints in a horizontal box never split the line . ( Line splitting may still occur inside boxes nested deeper ) . This box prints material on a single line. Break hints in a horizontal box never split the line. (Line splitting may still occur inside boxes nested deeper). *) val pp_open_vbox : formatter -> int -> unit val open_vbox : int -> unit val pp_open_hvbox : formatter -> int -> unit val open_hvbox : int -> unit val pp_open_hovbox : formatter -> int -> unit val open_hovbox : int -> unit val pp_print_string : formatter -> string -> unit val print_string : string -> unit * [ pp_print_string s ] prints [ s ] in the current pretty - printing box . val pp_print_bytes : formatter -> bytes -> unit val print_bytes : bytes -> unit * [ pp_print_bytes ppf b ] prints [ b ] in the current pretty - printing box . @since 4.13.0 @since 4.13.0 *) val pp_print_as : formatter -> int -> string -> unit val print_as : int -> string -> unit val pp_print_int : formatter -> int -> unit val print_int : int -> unit val pp_print_float : formatter -> float -> unit val print_float : float -> unit val pp_print_char : formatter -> char -> unit val print_char : char -> unit val pp_print_bool : formatter -> bool -> unit val print_bool : bool -> unit * { 1 : breaks Break hints } * A ' break hint ' tells the pretty - printer to output some space or split the line whichever way is more appropriate to the current pretty - printing box splitting rules . Break hints are used to separate printing items and are mandatory to let the pretty - printer correctly split lines and indent items . Simple break hints are : - the ' space ' : output a space or split the line if appropriate , - the ' cut ' : split the line if appropriate . Note : the notions of space and line splitting are abstract for the pretty - printing engine , since those notions can be completely redefined by the programmer . However , in the pretty - printer default setting , ` ` output a space '' simply means printing a space character ( ASCII code 32 ) and ` ` split the line '' means printing a newline character ( ASCII code 10 ) . line whichever way is more appropriate to the current pretty-printing box splitting rules. Break hints are used to separate printing items and are mandatory to let the pretty-printer correctly split lines and indent items. Simple break hints are: - the 'space': output a space or split the line if appropriate, - the 'cut': split the line if appropriate. Note: the notions of space and line splitting are abstract for the pretty-printing engine, since those notions can be completely redefined by the programmer. However, in the pretty-printer default setting, ``output a space'' simply means printing a space character (ASCII code 32) and ``split the line'' means printing a newline character (ASCII code 10). *) val pp_print_space : formatter -> unit -> unit val print_space : unit -> unit * [ pp_print_space ppf ( ) ] emits a ' space ' break hint : the pretty - printer may split the line at this point , otherwise it prints one space . [ pp_print_space ppf ( ) ] is equivalent to [ pp_print_break ppf 1 0 ] . the pretty-printer may split the line at this point, otherwise it prints one space. [pp_print_space ppf ()] is equivalent to [pp_print_break ppf 1 0]. *) val pp_print_cut : formatter -> unit -> unit val print_cut : unit -> unit * [ pp_print_cut ( ) ] emits a ' cut ' break hint : the pretty - printer may split the line at this point , otherwise it prints nothing . [ pp_print_cut ( ) ] is equivalent to [ pp_print_break 0 0 ] . the pretty-printer may split the line at this point, otherwise it prints nothing. [pp_print_cut ppf ()] is equivalent to [pp_print_break ppf 0 0]. *) val pp_print_break : formatter -> int -> int -> unit val print_break : int -> int -> unit * [ pp_print_break offset ] emits a ' full ' break hint : the pretty - printer may split the line at this point , otherwise it prints [ nspaces ] spaces . If the pretty - printer splits the line , [ offset ] is added to the current indentation . the pretty-printer may split the line at this point, otherwise it prints [nspaces] spaces. If the pretty-printer splits the line, [offset] is added to the current indentation. *) val pp_print_custom_break : formatter -> fits:(string * int * string) -> breaks:(string * int * string) -> unit * [ pp_print_custom_break , n , s2 ) ~breaks:(s3 , m , s4 ) ] emits a custom break hint : the pretty - printer may split the line at this point . If it does not split the line , then the [ s1 ] is emitted , then [ n ] spaces , then [ s2 ] . If it splits the line , then it emits the [ s3 ] string , then an indent ( according to the box rules ) , then an offset of [ m ] spaces , then the [ s4 ] string . While [ n ] and [ m ] are handled by [ formatter_out_functions.out_indent ] , the strings will be handled by [ formatter_out_functions.out_string ] . This allows for a custom formatter that handles indentation distinctly , for example , outputs [ < br/ > ] tags or [ & nbsp ; ] entities . The custom break is useful if you want to change which visible ( non - whitespace ) characters are printed in case of break or no break . For example , when printing a list [ [ a ; b ; c ] ] , you might want to add a trailing semicolon when it is printed vertically : { [ [ a ; b ; c ; ] ] } You can do this as follows : { [ printf " @[<v 0>[@;<0 2>@[<v 0 > a;@,b;@,c@]%t]@]@\n " ( pp_print_custom_break ~fits :( " " , 0 , " " ) ~breaks :( " ; " , 0 , " " ) ) ] } @since 4.08.0 custom break hint: the pretty-printer may split the line at this point. If it does not split the line, then the [s1] is emitted, then [n] spaces, then [s2]. If it splits the line, then it emits the [s3] string, then an indent (according to the box rules), then an offset of [m] spaces, then the [s4] string. While [n] and [m] are handled by [formatter_out_functions.out_indent], the strings will be handled by [formatter_out_functions.out_string]. This allows for a custom formatter that handles indentation distinctly, for example, outputs [<br/>] tags or [&nbsp;] entities. The custom break is useful if you want to change which visible (non-whitespace) characters are printed in case of break or no break. For example, when printing a list [ [a; b; c] ], you might want to add a trailing semicolon when it is printed vertically: {[ [ a; b; c; ] ]} You can do this as follows: {[ printf "@[<v 0>[@;<0 2>@[<v 0>a;@,b;@,c@]%t]@]@\n" (pp_print_custom_break ~fits:("", 0, "") ~breaks:(";", 0, "")) ]} @since 4.08.0 *) val pp_force_newline : formatter -> unit -> unit val force_newline : unit -> unit val pp_print_if_newline : formatter -> unit -> unit val print_if_newline : unit -> unit * { 1 Pretty - printing termination } val pp_print_flush : formatter -> unit -> unit val print_flush : unit -> unit val pp_print_newline : formatter -> unit -> unit val print_newline : unit -> unit val pp_set_margin : formatter -> int -> unit val set_margin : int -> unit * [ pp_set_margin ppf d ] sets the right margin to [ d ] ( in characters ): the pretty - printer splits lines that overflow the right margin according to the break hints given . Setting the margin to [ d ] means that the formatting engine aims at printing at most [ d-1 ] characters per line . Nothing happens if [ d ] is smaller than 2 . If [ d ] is too large , the right margin is set to the maximum admissible value ( which is greater than [ 10 ^ 9 ] ) . If [ d ] is less than the current maximum indentation limit , the maximum indentation limit is decreased while trying to preserve a minimal ratio [ max_indent / margin>=50 % ] and if possible the current difference [ margin - max_indent ] . See also { ! pp_set_geometry } . the pretty-printer splits lines that overflow the right margin according to the break hints given. Setting the margin to [d] means that the formatting engine aims at printing at most [d-1] characters per line. Nothing happens if [d] is smaller than 2. If [d] is too large, the right margin is set to the maximum admissible value (which is greater than [10 ^ 9]). If [d] is less than the current maximum indentation limit, the maximum indentation limit is decreased while trying to preserve a minimal ratio [max_indent/margin>=50%] and if possible the current difference [margin - max_indent]. See also {!pp_set_geometry}. *) val pp_get_margin : formatter -> unit -> int val get_margin : unit -> int * { 1 : maxindent Maximum indentation limit } val pp_set_max_indent : formatter -> int -> unit val set_max_indent : int -> unit * [ pp_set_max_indent ppf d ] sets the maximum indentation limit of lines to [ d ] ( in characters ): once this limit is reached , new pretty - printing boxes are rejected to the left , unless the enclosing box fully fits on the current line . As an illustration , { [ set_margin 10 ; set_max_indent 5 ; printf " " ] } yields { [ 123456 789A ] } because the nested box [ " @[7@ ] " ] is opened after the maximum indentation limit ( [ 7>5 ] ) and its parent box does not fit on the current line . Either decreasing the length of the parent box to make it fit on a line : { [ printf " " ] } or opening an intermediary box before the maximum indentation limit which fits on the current line { [ printf " " ] } avoids the rejection to the left of the inner boxes and print respectively [ " 123456789 " ] and [ " 123456789A " ] . Note also that vertical boxes never fit on a line whereas horizontal boxes always fully fit on the current line . Opening a box may split a line whereas the contents may have fit . If this behavior is problematic , it can be curtailed by setting the maximum indentation limit to [ margin - 1 ] . Note that setting the maximum indentation limit to [ margin ] is invalid . Nothing happens if [ d ] is smaller than 2 . If [ d ] is too large , the limit is set to the maximum admissible value ( which is greater than [ 10 ^ 9 ] ) . If [ d ] is greater or equal than the current margin , it is ignored , and the current maximum indentation limit is kept . See also { ! pp_set_geometry } . to [d] (in characters): once this limit is reached, new pretty-printing boxes are rejected to the left, unless the enclosing box fully fits on the current line. As an illustration, {[ set_margin 10; set_max_indent 5; printf "@[123456@[7@]89A@]@." ]} yields {[ 123456 789A ]} because the nested box ["@[7@]"] is opened after the maximum indentation limit ([7>5]) and its parent box does not fit on the current line. Either decreasing the length of the parent box to make it fit on a line: {[ printf "@[123456@[7@]89@]@." ]} or opening an intermediary box before the maximum indentation limit which fits on the current line {[ printf "@[123@[456@[7@]89@]A@]@." ]} avoids the rejection to the left of the inner boxes and print respectively ["123456789"] and ["123456789A"] . Note also that vertical boxes never fit on a line whereas horizontal boxes always fully fit on the current line. Opening a box may split a line whereas the contents may have fit. If this behavior is problematic, it can be curtailed by setting the maximum indentation limit to [margin - 1]. Note that setting the maximum indentation limit to [margin] is invalid. Nothing happens if [d] is smaller than 2. If [d] is too large, the limit is set to the maximum admissible value (which is greater than [10 ^ 9]). If [d] is greater or equal than the current margin, it is ignored, and the current maximum indentation limit is kept. See also {!pp_set_geometry}. *) val pp_get_max_indent : formatter -> unit -> int val get_max_indent : unit -> int * { 1 Geometry } Geometric functions can be used to manipulate simultaneously the coupled variables , margin and maxixum indentation limit . Geometric functions can be used to manipulate simultaneously the coupled variables, margin and maxixum indentation limit. *) type geometry = { max_indent:int; margin: int} val check_geometry: geometry -> bool * Check if the formatter geometry is valid : [ 1 < max_indent < margin ] val pp_set_geometry : formatter -> max_indent:int -> margin:int -> unit val set_geometry : max_indent:int -> margin:int -> unit val pp_safe_set_geometry : formatter -> max_indent:int -> margin:int -> unit val safe_set_geometry : max_indent:int -> margin:int -> unit * [ pp_set_geometry ppf ~max_indent ~margin ] sets both the margin and maximum indentation limit for [ ppf ] . When [ 1 < max_indent < margin ] , [ pp_set_geometry ppf ~max_indent ~margin ] is equivalent to [ pp_set_margin ppf margin ; pp_set_max_indent ] ; and avoids the subtly incorrect [ pp_set_max_indent ; pp_set_margin ppf margin ] ; Outside of this domain , [ pp_set_geometry ] raises an invalid argument exception whereas [ pp_safe_set_geometry ] does nothing . @since 4.08.0 [pp_set_geometry ppf ~max_indent ~margin] sets both the margin and maximum indentation limit for [ppf]. When [1 < max_indent < margin], [pp_set_geometry ppf ~max_indent ~margin] is equivalent to [pp_set_margin ppf margin; pp_set_max_indent ppf max_indent]; and avoids the subtly incorrect [pp_set_max_indent ppf max_indent; pp_set_margin ppf margin]; Outside of this domain, [pp_set_geometry] raises an invalid argument exception whereas [pp_safe_set_geometry] does nothing. @since 4.08.0 *) * [ pp_update_geometry ( fun geo - > { geo with ... } ) ] lets you update a formatter 's geometry in a way that is robust to extension of the [ geometry ] record with new fields . Raises an invalid argument exception if the returned geometry does not satisfy { ! check_geometry } . @since 4.11.0 [pp_update_geometry ppf (fun geo -> { geo with ... })] lets you update a formatter's geometry in a way that is robust to extension of the [geometry] record with new fields. Raises an invalid argument exception if the returned geometry does not satisfy {!check_geometry}. @since 4.11.0 *) val pp_update_geometry : formatter -> (geometry -> geometry) -> unit val update_geometry : (geometry -> geometry) -> unit val pp_get_geometry: formatter -> unit -> geometry val get_geometry: unit -> geometry * Return the current geometry of the formatter @since 4.08.0 @since 4.08.0 *) * { 1 Maximum formatting depth } val pp_set_max_boxes : formatter -> int -> unit val set_max_boxes : int -> unit * [ pp_set_max_boxes ] sets the maximum number of pretty - printing boxes simultaneously open . Material inside boxes nested deeper is printed as an ellipsis ( more precisely as the text returned by { ! get_ellipsis_text } [ ( ) ] ) . Nothing happens if [ max ] is smaller than 2 . boxes simultaneously open. Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by {!get_ellipsis_text} [()]). Nothing happens if [max] is smaller than 2. *) val pp_get_max_boxes : formatter -> unit -> int val get_max_boxes : unit -> int val pp_over_max_boxes : formatter -> unit -> bool val over_max_boxes : unit -> bool * { 1 Tabulation boxes } val pp_open_tbox : formatter -> unit -> unit val open_tbox : unit -> unit * [ open_tbox ( ) ] opens a new tabulation box . This box prints lines separated into cells of fixed width . Inside a tabulation box , special { e tabulation markers } defines points of interest on the line ( for instance to delimit cell boundaries ) . Function { ! Format.set_tab } sets a tabulation marker at insertion point . A tabulation box features specific { e tabulation breaks } to move to next tabulation marker or split the line . Function { ! Format.print_tbreak } prints a tabulation break . This box prints lines separated into cells of fixed width. Inside a tabulation box, special {e tabulation markers} defines points of interest on the line (for instance to delimit cell boundaries). Function {!Format.set_tab} sets a tabulation marker at insertion point. A tabulation box features specific {e tabulation breaks} to move to next tabulation marker or split the line. Function {!Format.print_tbreak} prints a tabulation break. *) val pp_close_tbox : formatter -> unit -> unit val close_tbox : unit -> unit val pp_set_tab : formatter -> unit -> unit val set_tab : unit -> unit val pp_print_tab : formatter -> unit -> unit val print_tab : unit -> unit * [ print_tab ( ) ] emits a ' next ' tabulation break hint : if not already set on a tabulation marker , the insertion point moves to the first tabulation marker on the right , or the pretty - printer splits the line and insertion point moves to the leftmost tabulation marker . It is equivalent to [ print_tbreak 0 0 ] . a tabulation marker, the insertion point moves to the first tabulation marker on the right, or the pretty-printer splits the line and insertion point moves to the leftmost tabulation marker. It is equivalent to [print_tbreak 0 0]. *) val pp_print_tbreak : formatter -> int -> int -> unit val print_tbreak : int -> int -> unit * [ print_tbreak nspaces offset ] emits a ' full ' tabulation break hint . If not already set on a tabulation marker , the insertion point moves to the first tabulation marker on the right and the pretty - printer prints [ nspaces ] spaces . If there is no next tabulation marker on the right , the pretty - printer splits the line at this point , then insertion point moves to the leftmost tabulation marker of the box . If the pretty - printer splits the line , [ offset ] is added to the current indentation . If not already set on a tabulation marker, the insertion point moves to the first tabulation marker on the right and the pretty-printer prints [nspaces] spaces. If there is no next tabulation marker on the right, the pretty-printer splits the line at this point, then insertion point moves to the leftmost tabulation marker of the box. If the pretty-printer splits the line, [offset] is added to the current indentation. *) val pp_set_ellipsis_text : formatter -> string -> unit val set_ellipsis_text : string -> unit val pp_get_ellipsis_text : formatter -> unit -> string val get_ellipsis_text : unit -> string * { 1 : tags Semantic tags } type stag = .. * { i Semantic tags } ( or simply { e tags } ) are user 's defined annotations to associate user 's specific operations to printed entities . Common usage of semantic tags is text decoration to get specific font or text size rendering for a display device , or marking delimitation of entities ( e.g. HTML or TeX elements or terminal escape sequences ) . More sophisticated usage of semantic tags could handle dynamic modification of the pretty - printer behavior to properly print the material within some specific tags . For instance , we can define an RGB tag like so : { [ type stag + = RGB of { r : : int;b : int } ] } In order to properly delimit printed entities , a semantic tag must be opened before and closed after the entity . Semantic tags must be properly nested like parentheses using { ! } and { ! pp_close_stag } . Tag specific operations occur any time a tag is opened or closed , At each occurrence , two kinds of operations are performed { e tag - marking } and { e tag - printing } : - The tag - marking operation is the simpler tag specific operation : it simply writes a tag specific string into the output device of the formatter . Tag - marking does not interfere with line - splitting computation . - The tag - printing operation is the more involved tag specific operation : it can print arbitrary material to the formatter . Tag - printing is tightly linked to the current pretty - printer operations . Roughly speaking , tag - marking is commonly used to get a better rendering of texts in the rendering device , while tag - printing allows fine tuning of printing routines to print the same entity differently according to the semantic tags ( i.e. print additional material or even omit parts of the output ) . More precisely : when a semantic tag is opened or closed then both and successive ' tag - printing ' and ' tag - marking ' operations occur : - Tag - printing a semantic tag means calling the formatter specific function [ print_open_stag ] ( resp . [ print_close_stag ] ) with the name of the tag as argument : that tag - printing function can then print any regular material to the formatter ( so that this material is enqueued as usual in the formatter queue for further line splitting computation ) . - Tag - marking a semantic tag means calling the formatter specific function [ mark_open_stag ] ( resp . [ mark_close_stag ] ) with the name of the tag as argument : that tag - marking function can then return the ' tag - opening marker ' ( resp . ` tag - closing marker ' ) for direct output into the output device of the formatter . Being written directly into the output device of the formatter , semantic tag marker strings are not considered as part of the printing material that drives line splitting ( in other words , the length of the strings corresponding to tag markers is considered as zero for line splitting ) . Thus , semantic tag handling is in some sense transparent to pretty - printing and does not interfere with usual indentation . Hence , a single pretty - printing routine can output both simple ' verbatim ' material or richer decorated output depending on the treatment of tags . By default , tags are not active , hence the output is not decorated with tag information . Once [ set_tags ] is set to [ true ] , the pretty - printer engine honors tags and decorates the output accordingly . Default tag - marking functions behave the HTML way : { { ! tag}string tags } are enclosed in " < " and " > " while other tags are ignored ; hence , opening marker for tag string [ " t " ] is [ " < t > " ] and closing marker is [ " < /t > " ] . Default tag - printing functions just do nothing . Tag - marking and tag - printing functions are user definable and can be set by calling { ! set_formatter_stag_functions } . Semantic tag operations may be set on or off with { ! set_tags } . Tag - marking operations may be set on or off with { ! set_mark_tags } . Tag - printing operations may be set on or off with { ! } . @since 4.08.0 to associate user's specific operations to printed entities. Common usage of semantic tags is text decoration to get specific font or text size rendering for a display device, or marking delimitation of entities (e.g. HTML or TeX elements or terminal escape sequences). More sophisticated usage of semantic tags could handle dynamic modification of the pretty-printer behavior to properly print the material within some specific tags. For instance, we can define an RGB tag like so: {[ type stag += RGB of {r:int;g:int;b:int} ]} In order to properly delimit printed entities, a semantic tag must be opened before and closed after the entity. Semantic tags must be properly nested like parentheses using {!pp_open_stag} and {!pp_close_stag}. Tag specific operations occur any time a tag is opened or closed, At each occurrence, two kinds of operations are performed {e tag-marking} and {e tag-printing}: - The tag-marking operation is the simpler tag specific operation: it simply writes a tag specific string into the output device of the formatter. Tag-marking does not interfere with line-splitting computation. - The tag-printing operation is the more involved tag specific operation: it can print arbitrary material to the formatter. Tag-printing is tightly linked to the current pretty-printer operations. Roughly speaking, tag-marking is commonly used to get a better rendering of texts in the rendering device, while tag-printing allows fine tuning of printing routines to print the same entity differently according to the semantic tags (i.e. print additional material or even omit parts of the output). More precisely: when a semantic tag is opened or closed then both and successive 'tag-printing' and 'tag-marking' operations occur: - Tag-printing a semantic tag means calling the formatter specific function [print_open_stag] (resp. [print_close_stag]) with the name of the tag as argument: that tag-printing function can then print any regular material to the formatter (so that this material is enqueued as usual in the formatter queue for further line splitting computation). - Tag-marking a semantic tag means calling the formatter specific function [mark_open_stag] (resp. [mark_close_stag]) with the name of the tag as argument: that tag-marking function can then return the 'tag-opening marker' (resp. `tag-closing marker') for direct output into the output device of the formatter. Being written directly into the output device of the formatter, semantic tag marker strings are not considered as part of the printing material that drives line splitting (in other words, the length of the strings corresponding to tag markers is considered as zero for line splitting). Thus, semantic tag handling is in some sense transparent to pretty-printing and does not interfere with usual indentation. Hence, a single pretty-printing routine can output both simple 'verbatim' material or richer decorated output depending on the treatment of tags. By default, tags are not active, hence the output is not decorated with tag information. Once [set_tags] is set to [true], the pretty-printer engine honors tags and decorates the output accordingly. Default tag-marking functions behave the HTML way: {{!tag}string tags} are enclosed in "<" and ">" while other tags are ignored; hence, opening marker for tag string ["t"] is ["<t>"] and closing marker is ["</t>"]. Default tag-printing functions just do nothing. Tag-marking and tag-printing functions are user definable and can be set by calling {!set_formatter_stag_functions}. Semantic tag operations may be set on or off with {!set_tags}. Tag-marking operations may be set on or off with {!set_mark_tags}. Tag-printing operations may be set on or off with {!set_print_tags}. @since 4.08.0 *) type tag = string type stag += String_tag of tag * [ String_tag s ] is a string tag [ s ] . String tags can be inserted either by explicitly using the constructor [ String_tag ] or by using the dedicated format syntax [ " @{<s > ... @ } " ] . @since 4.08.0 by explicitly using the constructor [String_tag] or by using the dedicated format syntax ["@{<s> ... @}"]. @since 4.08.0 *) val pp_open_stag : formatter -> stag -> unit val open_stag : stag -> unit * [ pp_open_stag ppf t ] opens the semantic tag named [ t ] . The [ print_open_stag ] tag - printing function of the formatter is called with [ t ] as argument ; then the opening tag marker for [ t ] , as given by [ mark_open_stag t ] , is written into the output device of the formatter . @since 4.08.0 The [print_open_stag] tag-printing function of the formatter is called with [t] as argument; then the opening tag marker for [t], as given by [mark_open_stag t], is written into the output device of the formatter. @since 4.08.0 *) val pp_close_stag : formatter -> unit -> unit val close_stag : unit -> unit * [ pp_close_stag ( ) ] closes the most recently opened semantic tag [ t ] . The closing tag marker , as given by [ mark_close_stag t ] , is written into the output device of the formatter ; then the [ print_close_stag ] tag - printing function of the formatter is called with [ t ] as argument . @since 4.08.0 The closing tag marker, as given by [mark_close_stag t], is written into the output device of the formatter; then the [print_close_stag] tag-printing function of the formatter is called with [t] as argument. @since 4.08.0 *) val pp_set_tags : formatter -> bool -> unit val set_tags : bool -> unit * [ ppf b ] turns on or off the treatment of semantic tags ( default is off ) . (default is off). *) val pp_set_print_tags : formatter -> bool -> unit val set_print_tags : bool -> unit val pp_set_mark_tags : formatter -> bool -> unit val set_mark_tags : bool -> unit val pp_get_print_tags : formatter -> unit -> bool val get_print_tags : unit -> bool val pp_get_mark_tags : formatter -> unit -> bool val get_mark_tags : unit -> bool val pp_set_formatter_out_channel : formatter -> Stdlib.out_channel -> unit val set_formatter_out_channel : Stdlib.out_channel -> unit val pp_set_formatter_output_functions : formatter -> (string -> int -> int -> unit) -> (unit -> unit) -> unit val set_formatter_output_functions : (string -> int -> int -> unit) -> (unit -> unit) -> unit val pp_get_formatter_output_functions : formatter -> unit -> (string -> int -> int -> unit) * (unit -> unit) val get_formatter_output_functions : unit -> (string -> int -> int -> unit) * (unit -> unit) * { 1 : meaning Redefining formatter output } * { 2 Redefining output functions } type formatter_out_functions = { out_string : string -> int -> int -> unit; out_flush : unit -> unit; out_newline : unit -> unit; out_spaces : int -> unit; * @since 4.06.0 } * The set of output functions specific to a formatter : - the [ out_string ] function performs all the pretty - printer string output . It is called with a string [ s ] , a start position [ p ] , and a number of characters [ n ] ; it is supposed to output characters [ p ] to [ p + n - 1 ] of [ s ] . - the [ out_flush ] function flushes the pretty - printer output device . - [ out_newline ] is called to open a new line when the pretty - printer splits the line . - the [ out_spaces ] function outputs spaces when a break hint leads to spaces instead of a line split . It is called with the number of spaces to output . - the [ out_indent ] function performs new line indentation when the pretty - printer splits the line . It is called with the indentation value of the new line . By default : - fields [ out_string ] and [ out_flush ] are output device specific ; ( e.g. { ! Stdlib.output_string } and { ! Stdlib.flush } for a { ! Stdlib.out_channel } device , or [ Buffer.add_substring ] and { ! Stdlib.ignore } for a [ Buffer.t ] output device ) , - field [ out_newline ] is equivalent to [ out_string " \n " 0 1 ] ; - fields [ out_spaces ] and [ out_indent ] are equivalent to [ out_string ( String.make n ' ' ) 0 n ] . @since 4.01.0 - the [out_string] function performs all the pretty-printer string output. It is called with a string [s], a start position [p], and a number of characters [n]; it is supposed to output characters [p] to [p + n - 1] of [s]. - the [out_flush] function flushes the pretty-printer output device. - [out_newline] is called to open a new line when the pretty-printer splits the line. - the [out_spaces] function outputs spaces when a break hint leads to spaces instead of a line split. It is called with the number of spaces to output. - the [out_indent] function performs new line indentation when the pretty-printer splits the line. It is called with the indentation value of the new line. By default: - fields [out_string] and [out_flush] are output device specific; (e.g. {!Stdlib.output_string} and {!Stdlib.flush} for a {!Stdlib.out_channel} device, or [Buffer.add_substring] and {!Stdlib.ignore} for a [Buffer.t] output device), - field [out_newline] is equivalent to [out_string "\n" 0 1]; - fields [out_spaces] and [out_indent] are equivalent to [out_string (String.make n ' ') 0 n]. @since 4.01.0 *) val pp_set_formatter_out_functions : formatter -> formatter_out_functions -> unit val set_formatter_out_functions : formatter_out_functions -> unit * [ pp_set_formatter_out_functions ppf out_funs ] Set all the pretty - printer output functions of [ ppf ] to those of argument [ out_funs ] , This way , you can change the meaning of indentation ( which can be something else than just printing space characters ) and the meaning of new lines opening ( which can be connected to any other action needed by the application at hand ) . Reasonable defaults for functions [ out_spaces ] and [ out_newline ] are respectively [ out_funs.out_string ( String.make n ' ' ) 0 n ] and [ out_funs.out_string " \n " 0 1 ] . @since 4.01.0 Set all the pretty-printer output functions of [ppf] to those of argument [out_funs], This way, you can change the meaning of indentation (which can be something else than just printing space characters) and the meaning of new lines opening (which can be connected to any other action needed by the application at hand). Reasonable defaults for functions [out_spaces] and [out_newline] are respectively [out_funs.out_string (String.make n ' ') 0 n] and [out_funs.out_string "\n" 0 1]. @since 4.01.0 *) val pp_get_formatter_out_functions : formatter -> unit -> formatter_out_functions val get_formatter_out_functions : unit -> formatter_out_functions * Return the current output functions of the pretty - printer , including line splitting and indentation functions . Useful to record the current setting and restore it afterwards . @since 4.01.0 including line splitting and indentation functions. Useful to record the current setting and restore it afterwards. @since 4.01.0 *) * { 1 : tagsmeaning Redefining semantic tag operations } type formatter_stag_functions = { mark_open_stag : stag -> string; mark_close_stag : stag -> string; print_open_stag : stag -> unit; print_close_stag : stag -> unit; } * The semantic tag handling functions specific to a formatter : [ mark ] versions are the ' tag - marking ' functions that associate a string marker to a tag in order for the pretty - printing engine to write those markers as 0 length tokens in the output device of the formatter . [ print ] versions are the ' tag - printing ' functions that can perform regular printing when a tag is closed or opened . @since 4.08.0 [mark] versions are the 'tag-marking' functions that associate a string marker to a tag in order for the pretty-printing engine to write those markers as 0 length tokens in the output device of the formatter. [print] versions are the 'tag-printing' functions that can perform regular printing when a tag is closed or opened. @since 4.08.0 *) val pp_set_formatter_stag_functions : formatter -> formatter_stag_functions -> unit val set_formatter_stag_functions : formatter_stag_functions -> unit * [ pp_set_formatter_stag_functions ppf tag_funs ] changes the meaning of opening and closing semantic tag operations to use the functions in [ tag_funs ] when printing on [ ppf ] . When opening a semantic tag with name [ t ] , the string [ t ] is passed to the opening tag - marking function ( the [ mark_open_stag ] field of the record [ tag_funs ] ) , that must return the opening tag marker for that name . When the next call to [ ( ) ] happens , the semantic tag name [ t ] is sent back to the closing tag - marking function ( the [ mark_close_stag ] field of record [ tag_funs ] ) , that must return a closing tag marker for that name . The [ print _ ] field of the record contains the tag - printing functions that are called at tag opening and tag closing time , to output regular material in the pretty - printer queue . @since 4.08.0 opening and closing semantic tag operations to use the functions in [tag_funs] when printing on [ppf]. When opening a semantic tag with name [t], the string [t] is passed to the opening tag-marking function (the [mark_open_stag] field of the record [tag_funs]), that must return the opening tag marker for that name. When the next call to [close_stag ()] happens, the semantic tag name [t] is sent back to the closing tag-marking function (the [mark_close_stag] field of record [tag_funs]), that must return a closing tag marker for that name. The [print_] field of the record contains the tag-printing functions that are called at tag opening and tag closing time, to output regular material in the pretty-printer queue. @since 4.08.0 *) val pp_get_formatter_stag_functions : formatter -> unit -> formatter_stag_functions val get_formatter_stag_functions : unit -> formatter_stag_functions * Return the current semantic tag operation functions of the standard pretty - printer . @since 4.08.0 pretty-printer. @since 4.08.0 *) * { 1 : formatter Defining formatters } Defining new formatters permits unrelated output of material in parallel on several output devices . All the parameters of a formatter are local to the formatter : right margin , maximum indentation limit , maximum number of pretty - printing boxes simultaneously open , ellipsis , and so on , are specific to each formatter and may be fixed independently . For instance , given a { ! Buffer.t } buffer [ b ] , { ! formatter_of_buffer } [ b ] returns a new formatter using buffer [ b ] as its output device . Similarly , given a { ! Stdlib.out_channel } output channel [ oc ] , { ! formatter_of_out_channel } [ oc ] returns a new formatter using channel [ oc ] as its output device . Alternatively , given [ out_funs ] , a complete set of output functions for a formatter , then { ! formatter_of_out_functions } [ out_funs ] computes a new formatter using those functions for output . Defining new formatters permits unrelated output of material in parallel on several output devices. All the parameters of a formatter are local to the formatter: right margin, maximum indentation limit, maximum number of pretty-printing boxes simultaneously open, ellipsis, and so on, are specific to each formatter and may be fixed independently. For instance, given a {!Buffer.t} buffer [b], {!formatter_of_buffer} [b] returns a new formatter using buffer [b] as its output device. Similarly, given a {!Stdlib.out_channel} output channel [oc], {!formatter_of_out_channel} [oc] returns a new formatter using channel [oc] as its output device. Alternatively, given [out_funs], a complete set of output functions for a formatter, then {!formatter_of_out_functions} [out_funs] computes a new formatter using those functions for output. *) val formatter_of_out_channel : out_channel -> formatter val std_formatter : formatter val err_formatter : formatter val formatter_of_buffer : Buffer.t -> formatter val stdbuf : Buffer.t val str_formatter : formatter val flush_str_formatter : unit -> string val make_formatter : (string -> int -> int -> unit) -> (unit -> unit) -> formatter val formatter_of_out_functions : formatter_out_functions -> formatter * [ formatter_of_out_functions out_funs ] returns a new formatter that writes with the set of output functions [ out_funs ] . See definition of type { ! formatter_out_functions } for the meaning of argument [ out_funs ] . @since 4.06.0 with the set of output functions [out_funs]. See definition of type {!formatter_out_functions} for the meaning of argument [out_funs]. @since 4.06.0 *) * { 2 : symbolic Symbolic pretty - printing } * Symbolic pretty - printing is pretty - printing using a symbolic formatter , i.e. a formatter that outputs symbolic pretty - printing items . When using a symbolic formatter , all regular pretty - printing activities occur but output material is symbolic and stored in a buffer of output items . At the end of pretty - printing , flushing the output buffer allows post - processing of symbolic output before performing low level output operations . In practice , first define a symbolic output buffer [ b ] using : - [ let sob = make_symbolic_output_buffer ( ) ] . Then define a symbolic formatter with : - [ let ppf = formatter_of_symbolic_output_buffer sob ] Use symbolic formatter [ ppf ] as usual , and retrieve symbolic items at end of pretty - printing by flushing symbolic output buffer [ sob ] with : - [ flush_symbolic_output_buffer sob ] . Symbolic pretty-printing is pretty-printing using a symbolic formatter, i.e. a formatter that outputs symbolic pretty-printing items. When using a symbolic formatter, all regular pretty-printing activities occur but output material is symbolic and stored in a buffer of output items. At the end of pretty-printing, flushing the output buffer allows post-processing of symbolic output before performing low level output operations. In practice, first define a symbolic output buffer [b] using: - [let sob = make_symbolic_output_buffer ()]. Then define a symbolic formatter with: - [let ppf = formatter_of_symbolic_output_buffer sob] Use symbolic formatter [ppf] as usual, and retrieve symbolic items at end of pretty-printing by flushing symbolic output buffer [sob] with: - [flush_symbolic_output_buffer sob]. *) type symbolic_output_item = | Output_string of string | Output_spaces of int | Output_indent of int * Items produced by symbolic pretty - printers @since 4.06.0 @since 4.06.0 *) type symbolic_output_buffer * The output buffer of a symbolic pretty - printer . @since 4.06.0 The output buffer of a symbolic pretty-printer. @since 4.06.0 *) val make_symbolic_output_buffer : unit -> symbolic_output_buffer * [ make_symbolic_output_buffer ( ) ] returns a fresh buffer for symbolic output . @since 4.06.0 symbolic output. @since 4.06.0 *) val clear_symbolic_output_buffer : symbolic_output_buffer -> unit * [ clear_symbolic_output_buffer sob ] resets buffer [ sob ] . @since 4.06.0 @since 4.06.0 *) val get_symbolic_output_buffer : symbolic_output_buffer -> symbolic_output_item list * [ get_symbolic_output_buffer sob ] returns the contents of buffer [ sob ] . @since 4.06.0 @since 4.06.0 *) val flush_symbolic_output_buffer : symbolic_output_buffer -> symbolic_output_item list * [ flush_symbolic_output_buffer sob ] returns the contents of buffer [ sob ] and resets buffer [ sob ] . [ flush_symbolic_output_buffer sob ] is equivalent to [ let items = get_symbolic_output_buffer sob in clear_symbolic_output_buffer sob ; items ] @since 4.06.0 [sob] and resets buffer [sob]. [flush_symbolic_output_buffer sob] is equivalent to [let items = get_symbolic_output_buffer sob in clear_symbolic_output_buffer sob; items] @since 4.06.0 *) val add_symbolic_output_item : symbolic_output_buffer -> symbolic_output_item -> unit * [ add_symbolic_output_item sob itm ] adds item [ itm ] to buffer [ sob ] . @since 4.06.0 @since 4.06.0 *) val formatter_of_symbolic_output_buffer : symbolic_output_buffer -> formatter * [ formatter_of_symbolic_output_buffer sob ] returns a symbolic formatter that outputs to [ ] [ sob ] . @since 4.06.0 that outputs to [symbolic_output_buffer] [sob]. @since 4.06.0 *) * { 1 Convenience formatting functions . } val pp_print_list: ?pp_sep:(formatter -> unit -> unit) -> (formatter -> 'a -> unit) -> (formatter -> 'a list -> unit) * [ pp_print_list ? pp_sep pp_v ppf l ] prints items of list [ l ] , using [ pp_v ] to print each item , and calling [ pp_sep ] between items ( [ pp_sep ] defaults to { ! pp_print_cut } . Does nothing on empty lists . @since 4.02.0 using [pp_v] to print each item, and calling [pp_sep] between items ([pp_sep] defaults to {!pp_print_cut}. Does nothing on empty lists. @since 4.02.0 *) val pp_print_seq: ?pp_sep:(formatter -> unit -> unit) -> (formatter -> 'a -> unit) -> (formatter -> 'a Seq.t -> unit) * [ pp_print_seq ? pp_sep pp_v ppf s ] prints items of sequence [ s ] , using [ pp_v ] to print each item , and calling [ pp_sep ] between items ( [ pp_sep ] defaults to { ! pp_print_cut } . Does nothing on empty sequences . This function does not terminate on infinite sequences . @since 4.12 using [pp_v] to print each item, and calling [pp_sep] between items ([pp_sep] defaults to {!pp_print_cut}. Does nothing on empty sequences. This function does not terminate on infinite sequences. @since 4.12 *) val pp_print_text : formatter -> string -> unit * [ pp_print_text ppf s ] prints [ s ] with spaces and newlines respectively printed using { ! pp_print_space } and { ! pp_force_newline } . @since 4.02.0 printed using {!pp_print_space} and {!pp_force_newline}. @since 4.02.0 *) val pp_print_option : ?none:(formatter -> unit -> unit) -> (formatter -> 'a -> unit) -> (formatter -> 'a option -> unit) * [ pp_print_option ? none pp_v ppf o ] prints [ o ] on [ ppf ] using [ pp_v ] if [ o ] is [ Some v ] and [ none ] if it is [ None ] . [ none ] prints nothing by default . @since 4.08 using [pp_v] if [o] is [Some v] and [none] if it is [None]. [none] prints nothing by default. @since 4.08 *) val pp_print_result : ok:(formatter -> 'a -> unit) -> error:(formatter -> 'e -> unit) -> formatter -> ('a, 'e) result -> unit * [ pp_print_result ~ok ~error ppf r ] prints [ r ] on [ ppf ] using [ ok ] if [ r ] is [ Ok _ ] and [ error ] if [ r ] is [ Error _ ] . @since 4.08 [ok] if [r] is [Ok _] and [error] if [r] is [Error _]. @since 4.08 *) val pp_print_either : left:(formatter -> 'a -> unit) -> right:(formatter -> 'b -> unit) -> formatter -> ('a, 'b) Either.t -> unit * [ pp_print_either ~left ~right e ] prints [ e ] on [ ppf ] using [ left ] if [ e ] is [ Either . Left _ ] and [ right ] if [ e ] is [ Either . Right _ ] . @since 4.13 [left] if [e] is [Either.Left _] and [right] if [e] is [Either.Right _]. @since 4.13 *) * { 1 : fpp Formatted pretty - printing } val fprintf : formatter -> ('a, formatter, unit) format -> 'a * [ fprintf ff fmt arg1 ... argN ] formats the arguments [ arg1 ] to [ argN ] according to the format string [ fmt ] , and outputs the resulting string on the formatter [ ff ] . The format string [ fmt ] is a character string which contains three types of objects : plain characters and conversion specifications as specified in the { ! Printf } module , and pretty - printing indications specific to the [ Format ] module . The pretty - printing indication characters are introduced by a [ @ ] character , and their meanings are : - [ @\ [ ] : open a pretty - printing box . The type and offset of the box may be optionally specified with the following syntax : the [ < ] character , followed by an optional box type indication , then an optional integer offset , and the closing [ > ] character . Pretty - printing box type is one of [ h ] , [ v ] , [ hv ] , [ b ] , or [ hov ] . ' [ h ] ' stands for an ' horizontal ' pretty - printing box , ' [ v ] ' stands for a ' vertical ' pretty - printing box , ' [ hv ] ' stands for an ' horizontal / vertical ' pretty - printing box , ' [ b ] ' stands for an ' horizontal - or - vertical ' pretty - printing box demonstrating indentation , ' [ hov ] ' stands a simple ' horizontal - or - vertical ' pretty - printing box . For instance , [ @\[<hov 2 > ] opens an ' horizontal - or - vertical ' pretty - printing box with indentation 2 as obtained with [ open_hovbox 2 ] . For more details about pretty - printing boxes , see the various box opening functions [ open_*box ] . - [ @\ ] ] : close the most recently opened pretty - printing box . - [ @ , ] : output a ' cut ' break hint , as with [ print_cut ( ) ] . - [ @ ] : output a ' space ' break hint , as with [ print_space ( ) ] . - [ @ ; ] : output a ' full ' break hint as with [ print_break ] . The [ nspaces ] and [ offset ] parameters of the break hint may be optionally specified with the following syntax : the [ < ] character , followed by an integer [ nspaces ] value , then an integer [ offset ] , and a closing [ > ] character . If no parameters are provided , the good break defaults to a ' space ' break hint . - [ @. ] : flush the pretty - printer and split the line , as with [ print_newline ( ) ] . - [ @<n > ] : print the following item as if it were of length [ n ] . Hence , [ printf " @<0>%s " arg ] prints [ arg ] as a zero length string . If [ @<n > ] is not followed by a conversion specification , then the following character of the format is printed as if it were of length [ n ] . - [ @\ { ] : open a semantic tag . The name of the tag may be optionally specified with the following syntax : the [ < ] character , followed by an optional string specification , and the closing [ > ] character . The string specification is any character string that does not contain the closing character [ ' > ' ] . If omitted , the tag name defaults to the empty string . For more details about semantic tags , see the functions { ! open_stag } and { ! } . - [ @\ } ] : close the most recently opened semantic tag . - [ @ ? ] : flush the pretty - printer as with [ print_flush ( ) ] . This is equivalent to the conversion [ % ! ] . - [ @\n ] : force a newline , as with [ force_newline ( ) ] , not the normal way of pretty - printing , you should prefer using break hints inside a vertical pretty - printing box . Note : To prevent the interpretation of a [ @ ] character as a pretty - printing indication , escape it with a [ % ] character . Old quotation mode [ @@ ] is deprecated since it is not compatible with formatted input interpretation of character [ ' @ ' ] . Example : [ printf " @[%s@ % d@]@. " " x = " 1 ] is equivalent to [ open_box ( ) ; print_string " x = " ; print_space ( ) ; print_int 1 ; close_box ( ) ; print_newline ( ) ] . It prints [ x = 1 ] within a pretty - printing ' horizontal - or - vertical ' box . according to the format string [fmt], and outputs the resulting string on the formatter [ff]. The format string [fmt] is a character string which contains three types of objects: plain characters and conversion specifications as specified in the {!Printf} module, and pretty-printing indications specific to the [Format] module. The pretty-printing indication characters are introduced by a [@] character, and their meanings are: - [@\[]: open a pretty-printing box. The type and offset of the box may be optionally specified with the following syntax: the [<] character, followed by an optional box type indication, then an optional integer offset, and the closing [>] character. Pretty-printing box type is one of [h], [v], [hv], [b], or [hov]. '[h]' stands for an 'horizontal' pretty-printing box, '[v]' stands for a 'vertical' pretty-printing box, '[hv]' stands for an 'horizontal/vertical' pretty-printing box, '[b]' stands for an 'horizontal-or-vertical' pretty-printing box demonstrating indentation, '[hov]' stands a simple 'horizontal-or-vertical' pretty-printing box. For instance, [@\[<hov 2>] opens an 'horizontal-or-vertical' pretty-printing box with indentation 2 as obtained with [open_hovbox 2]. For more details about pretty-printing boxes, see the various box opening functions [open_*box]. - [@\]]: close the most recently opened pretty-printing box. - [@,]: output a 'cut' break hint, as with [print_cut ()]. - [@ ]: output a 'space' break hint, as with [print_space ()]. - [@;]: output a 'full' break hint as with [print_break]. The [nspaces] and [offset] parameters of the break hint may be optionally specified with the following syntax: the [<] character, followed by an integer [nspaces] value, then an integer [offset], and a closing [>] character. If no parameters are provided, the good break defaults to a 'space' break hint. - [@.]: flush the pretty-printer and split the line, as with [print_newline ()]. - [@<n>]: print the following item as if it were of length [n]. Hence, [printf "@<0>%s" arg] prints [arg] as a zero length string. If [@<n>] is not followed by a conversion specification, then the following character of the format is printed as if it were of length [n]. - [@\{]: open a semantic tag. The name of the tag may be optionally specified with the following syntax: the [<] character, followed by an optional string specification, and the closing [>] character. The string specification is any character string that does not contain the closing character ['>']. If omitted, the tag name defaults to the empty string. For more details about semantic tags, see the functions {!open_stag} and {!close_stag}. - [@\}]: close the most recently opened semantic tag. - [@?]: flush the pretty-printer as with [print_flush ()]. This is equivalent to the conversion [%!]. - [@\n]: force a newline, as with [force_newline ()], not the normal way of pretty-printing, you should prefer using break hints inside a vertical pretty-printing box. Note: To prevent the interpretation of a [@] character as a pretty-printing indication, escape it with a [%] character. Old quotation mode [@@] is deprecated since it is not compatible with formatted input interpretation of character ['@']. Example: [printf "@[%s@ %d@]@." "x =" 1] is equivalent to [open_box (); print_string "x ="; print_space (); print_int 1; close_box (); print_newline ()]. It prints [x = 1] within a pretty-printing 'horizontal-or-vertical' box. *) val printf : ('a, formatter, unit) format -> 'a val eprintf : ('a, formatter, unit) format -> 'a val sprintf : ('a, unit, string) format -> 'a val asprintf : ('a, formatter, unit, string) format4 -> 'a * Same as [ printf ] above , but instead of printing on a formatter , returns a string containing the result of formatting the arguments . The type of [ asprintf ] is general enough to interact nicely with [ % a ] conversions . @since 4.01.0 returns a string containing the result of formatting the arguments. The type of [asprintf] is general enough to interact nicely with [%a] conversions. @since 4.01.0 *) val dprintf : ('a, formatter, unit, formatter -> unit) format4 -> 'a * Same as { ! } , except the formatter is the last argument . [ dprintf " ... " a b c ] is a function of type [ formatter - > unit ] which can be given to a format specifier [ % t ] . This can be used as a replacement for { ! } to delay formatting decisions . Using the string returned by { ! } in a formatting context forces formatting decisions to be taken in isolation , and the final string may be created prematurely . { ! } allows delay of formatting decisions until the final formatting context is known . For example : { [ let t = Format.dprintf " % i@ % i@ % i " 1 2 3 in ... Format.printf " @[<v>%t@ ] " t ] } @since 4.08.0 [dprintf "..." a b c] is a function of type [formatter -> unit] which can be given to a format specifier [%t]. This can be used as a replacement for {!asprintf} to delay formatting decisions. Using the string returned by {!asprintf} in a formatting context forces formatting decisions to be taken in isolation, and the final string may be created prematurely. {!dprintf} allows delay of formatting decisions until the final formatting context is known. For example: {[ let t = Format.dprintf "%i@ %i@ %i" 1 2 3 in ... Format.printf "@[<v>%t@]" t ]} @since 4.08.0 *) val ifprintf : formatter -> ('a, formatter, unit) format -> 'a * Same as [ fprintf ] above , but does not print anything . Useful to ignore some material when conditionally printing . @since 3.10.0 Useful to ignore some material when conditionally printing. @since 3.10.0 *) val kfprintf : (formatter -> 'a) -> formatter -> ('b, formatter, unit, 'a) format4 -> 'b * Same as [ fprintf ] above , but instead of returning immediately , passes the formatter to its first argument at the end of printing . passes the formatter to its first argument at the end of printing. *) val kdprintf : ((formatter -> unit) -> 'a) -> ('b, formatter, unit, 'a) format4 -> 'b * Same as { ! } above , but instead of returning immediately , passes the suspended printer to its first argument at the end of printing . @since 4.08.0 passes the suspended printer to its first argument at the end of printing. @since 4.08.0 *) val ikfprintf : (formatter -> 'a) -> formatter -> ('b, formatter, unit, 'a) format4 -> 'b * Same as [ ] above , but does not print anything . Useful to ignore some material when conditionally printing . @since 3.12.0 Useful to ignore some material when conditionally printing. @since 3.12.0 *) val ksprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b * Same as [ sprintf ] above , but instead of returning the string , passes it to the first argument . passes it to the first argument. *) val kasprintf : (string -> 'a) -> ('b, formatter, unit, 'a) format4 -> 'b * Same as [ asprintf ] above , but instead of returning the string , passes it to the first argument . @since 4.03 passes it to the first argument. @since 4.03 *) val bprintf : Buffer.t -> ('a, formatter, unit) format -> 'a [@@ocaml.deprecated] * @deprecated This function is error prone . Do not use it . This function is neither compositional nor incremental , since it flushes the pretty - printer queue at each call . If you need to print to some buffer [ b ] , you must first define a formatter writing to [ b ] , using [ let to_b = formatter_of_buffer b ] ; then use regular calls to [ Format.fprintf ] with formatter [ to_b ] . This function is neither compositional nor incremental, since it flushes the pretty-printer queue at each call. If you need to print to some buffer [b], you must first define a formatter writing to [b], using [let to_b = formatter_of_buffer b]; then use regular calls to [Format.fprintf] with formatter [to_b]. *) val kprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b [@@ocaml.deprecated "Use Format.ksprintf instead."] val set_all_formatter_output_functions : out:(string -> int -> int -> unit) -> flush:(unit -> unit) -> newline:(unit -> unit) -> spaces:(int -> unit) -> unit [@@ocaml.deprecated "Use Format.set_formatter_out_functions instead."] val get_all_formatter_output_functions : unit -> (string -> int -> int -> unit) * (unit -> unit) * (unit -> unit) * (int -> unit) [@@ocaml.deprecated "Use Format.get_formatter_out_functions instead."] val pp_set_all_formatter_output_functions : formatter -> out:(string -> int -> int -> unit) -> flush:(unit -> unit) -> newline:(unit -> unit) -> spaces:(int -> unit) -> unit [@@ocaml.deprecated "Use Format.pp_set_formatter_out_functions instead."] val pp_get_all_formatter_output_functions : formatter -> unit -> (string -> int -> int -> unit) * (unit -> unit) * (unit -> unit) * (int -> unit) [@@ocaml.deprecated "Use Format.pp_get_formatter_out_functions instead."] * { 2 String tags } val pp_open_tag : formatter -> tag -> unit [@@ocaml.deprecated "Use Format.pp_open_stag."] * @deprecated Subsumed by { ! } . val open_tag : tag -> unit [@@ocaml.deprecated "Use Format.open_stag."] val pp_close_tag : formatter -> unit -> unit [@@ocaml.deprecated "Use Format.pp_close_stag."] val close_tag : unit -> unit [@@ocaml.deprecated "Use Format.close_stag."] * @deprecated Subsumed by { ! } . type formatter_tag_functions = { mark_open_tag : tag -> string; mark_close_tag : tag -> string; print_open_tag : tag -> unit; print_close_tag : tag -> unit; } [@@ocaml.deprecated "Use formatter_stag_functions."] val pp_set_formatter_tag_functions : formatter -> formatter_tag_functions -> unit [@@ocaml.deprecated "This function will erase non-string tag formatting functions. \ Use Format.pp_set_formatter_stag_functions."] [@@warning "-3"] val set_formatter_tag_functions : formatter_tag_functions -> unit [@@ocaml.deprecated "Use Format.set_formatter_stag_functions."] [@@warning "-3"] val pp_get_formatter_tag_functions : formatter -> unit -> formatter_tag_functions [@@ocaml.deprecated "Use Format.pp_get_formatter_stag_functions."] [@@warning "-3"] val get_formatter_tag_functions : unit -> formatter_tag_functions [@@ocaml.deprecated "Use Format.get_formatter_stag_functions."] [@@warning "-3"] * @deprecated Subsumed by { ! } .
d6a0d45975b8a29c1ff877825ccbb208a5a7d5d9fe1a6e5a358e915a65b1d5cb
ajhc/ajhc
Main.hs
module Grin.Main(compileToGrin) where import Control.Monad import Data.List import Data.Monoid(mappend) import System.Directory import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Lazy.UTF8 as LBS import qualified Data.Map as Map import qualified Data.Set as Set import qualified System.FilePath as FP import System.Exit import C.Prims import Grin.DeadCode import Grin.Devolve(twiddleGrin,devolveTransform) import Grin.EvalInline(createEvalApply) import Grin.FromE import Grin.Grin import Grin.Lint import Grin.NodeAnalyze import Grin.Optimize import Grin.SSimplify import Grin.Show import Grin.StorageAnalysis import Ho.ReadSource import Options import PackedString import RawFiles import Support.TempDir import Support.Transform import Support.CompatMingw32 import Util.Gen import qualified C.FromGrin2 as FG2 import qualified FlagDump as FD import qualified Stats # NOINLINE compileToGrin # compileToGrin prog = do stats <- Stats.new putProgressLn "Converting to Grin..." x <- Grin.FromE.compile prog when verbose $ Stats.print "Grin" Stats.theStats wdump FD.GrinInitial $ do dumpGrin "initial" x x <- transformGrin simplifyParms x wdump FD.GrinNormalized $ do dumpGrin "normalized" x x <- explicitRecurse x lintCheckGrin x x <- transformGrin deadCodeParms x x <- transformGrin simplifyParms x x <- transformGrin pushParms x x <- transformGrin simplifyParms x putProgressLn "-- Speculative Execution Optimization" x <- grinSpeculate x lintCheckGrin x x <- transformGrin deadCodeParms x x <- transformGrin simplifyParms x x <- transformGrin pushParms x x <- transformGrin simplifyParms x wdump FD.OptimizationStats $ Stats.print "Optimization" stats putProgressLn "-- Node Usage Analysis" wdump FD.GrinPreeval $ dumpGrin "preeval" x x <- transformGrin nodeAnalyzeParms x x <- transformGrin simplifyParms x wdump FD.GrinPreeval $ dumpGrin "preeval2" x x <- transformGrin nodeAnalyzeParms x x <- transformGrin simplifyParms x x <- createEvalApply x x <- transformGrin simplifyParms x putProgressLn "-- Grin Devolution" wdump FD.GrinFinal $ dumpGrin "predevolve" x x <- transformGrin devolveTransform x x < - opt " After " x x <- transformGrin simplifyParms x x <- return $ twiddleGrin x -- x <- return $ normalizeGrin x -- x <- return $ twiddleGrin x x <- storeAnalyze x dumpFinalGrin x compileGrinToC x dumpFinalGrin grin = do wdump FD.GrinGraph $ do let dot = graphGrin grin writeFile (outputName ++ "_grin.dot") dot wdump FD.GrinFinal $ dumpGrin "final" grin compileGrinToC grin = do let (cg,Requires reqs) = FG2.compileGrin grin rls = filter ("-l" `isPrefixOf`) $ map (unpackPS . snd) (Set.toList reqs) fn = outputName ++ lup "executable_extension" lup k = maybe "" id $ Map.lookup k (optInis options) cf <- case (optOutName options,optStop options) of (Just fn,StopC) -> return fn _ | dump FD.C -> return (fn ++ "_code.c") | otherwise -> fileInTempDir ("main_code.c") (\_ -> return ()) (argstring,sversion) <- getArgString (cc,args) <- fetchCompilerFlags forM_ [("rts/constants.h",constants_h), ("rts/stableptr.c",stableptr_c), ("rts/stableptr.h",stableptr_h), ("rts/slub.c",slub_c), ("rts/profile.c",profile_c), ("rts/profile.h",profile_h), ("rts/gc.h",gc_h), ("rts/rts_support.c",rts_support_c), ("rts/rts_support.h",rts_support_h), ("rts/jhc_rts.c",jhc_rts_c), ("rts/jhc_rts.h",jhc_rts_h), ("lib/lib_cbits.c",lib_cbits_c), ("lib/lib_cbits.h",lib_cbits_h), ("rts/cdefs.h",cdefs_h), ("sys/queue.h",queue_h), ("HsFFI.h",hsffi_h), ("jhc_rts_header.h",jhc_rts_header_h), ("sys/wsize.h",wsize_h), ("rts/gc_jgc.c",gc_jgc_c), ("rts/gc_jgc.h",gc_jgc_h), ("rts/gc_jgc_internal.h",gc_jgc_internal_h), ("rts/gc_none.c",gc_none_c), ("rts/gc_none.h",gc_none_h), ("rts/conc.c",conc_c), ("rts/conc.h",conc_h), ("sys/bitarray.h",bitarray_h)] $ \ (fn,bs) -> do fileInTempDir fn $ flip BS.writeFile bs let cFiles = ["rts/profile.c", "rts/rts_support.c", "rts/gc_none.c", "rts/jhc_rts.c", "lib/lib_cbits.c", "rts/gc_jgc.c", "rts/stableptr.c", "rts/conc.c"] tdir <- getTempDir ds <- iocatch (getDirectoryContents (tdir FP.</> "cbits")) (\_ -> return []) let extraCFiles = map noEscapePath $ map (tdir FP.</>) cFiles ++ ["-I" ++ tdir ++ "/cbits", "-I" ++ tdir ] ++ [ tdir FP.</> "cbits" FP.</> fn | fn@(reverse -> 'c':'.':_) <- ds ] let comm = shellQuote $ [cc] ++ extraCFiles ++ [cf, "-o", fn] ++ args ++ rls globalvar n c = LBS.fromString $ "char " ++ n ++ "[] = \"" ++ c ++ "\";" putProgressLn ("Writing " ++ show cf) LBS.writeFile cf $ LBS.intercalate (LBS.fromString "\n") [ globalvar "jhc_c_compile" comm, globalvar "jhc_command" argstring, globalvar "jhc_version" sversion,LBS.empty,cg] when (optStop options == StopC) $ exitSuccess putProgressLn ("Running: " ++ comm) r <- systemCompat comm when (r /= ExitSuccess) $ fail "C code did not compile." return () grinParms = transformParms { transformDumpProgress = verbose, transformPass = "Grin" } simplifyParms = grinParms { transformCategory = "Simplify", transformOperation = Grin.SSimplify.simplify, transformIterate = IterateDone } nodeAnalyzeParms = grinParms { transformCategory = "NodeAnalyze", transformOperation = nodealyze } where nodealyze grin = do stats <- Stats.new g <- deadCode stats (grinEntryPointNames grin) grin g <- nodeAnalyze g st <- Stats.readStat stats return g { grinStats = grinStats grin `mappend` st } pushParms = grinParms { transformCategory = "Push", transformOperation = pushGrin } where pushGrin grin = do nf <- mapMsnd (grinPush undefined) (grinFuncs grin) return $ setGrinFunctions nf grin deadCodeParms = grinParms { transformCategory = "DeadCode", transformOperation = op } where op grin = do stats <- Stats.new g <- deadCode stats (grinEntryPointNames grin) grin st <- Stats.readStat stats return g { grinStats = grinStats grin `mappend` st }
null
https://raw.githubusercontent.com/ajhc/ajhc/8ef784a6a3b5998cfcd95d0142d627da9576f264/src/Grin/Main.hs
haskell
x <- return $ normalizeGrin x x <- return $ twiddleGrin x
module Grin.Main(compileToGrin) where import Control.Monad import Data.List import Data.Monoid(mappend) import System.Directory import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Lazy.UTF8 as LBS import qualified Data.Map as Map import qualified Data.Set as Set import qualified System.FilePath as FP import System.Exit import C.Prims import Grin.DeadCode import Grin.Devolve(twiddleGrin,devolveTransform) import Grin.EvalInline(createEvalApply) import Grin.FromE import Grin.Grin import Grin.Lint import Grin.NodeAnalyze import Grin.Optimize import Grin.SSimplify import Grin.Show import Grin.StorageAnalysis import Ho.ReadSource import Options import PackedString import RawFiles import Support.TempDir import Support.Transform import Support.CompatMingw32 import Util.Gen import qualified C.FromGrin2 as FG2 import qualified FlagDump as FD import qualified Stats # NOINLINE compileToGrin # compileToGrin prog = do stats <- Stats.new putProgressLn "Converting to Grin..." x <- Grin.FromE.compile prog when verbose $ Stats.print "Grin" Stats.theStats wdump FD.GrinInitial $ do dumpGrin "initial" x x <- transformGrin simplifyParms x wdump FD.GrinNormalized $ do dumpGrin "normalized" x x <- explicitRecurse x lintCheckGrin x x <- transformGrin deadCodeParms x x <- transformGrin simplifyParms x x <- transformGrin pushParms x x <- transformGrin simplifyParms x putProgressLn "-- Speculative Execution Optimization" x <- grinSpeculate x lintCheckGrin x x <- transformGrin deadCodeParms x x <- transformGrin simplifyParms x x <- transformGrin pushParms x x <- transformGrin simplifyParms x wdump FD.OptimizationStats $ Stats.print "Optimization" stats putProgressLn "-- Node Usage Analysis" wdump FD.GrinPreeval $ dumpGrin "preeval" x x <- transformGrin nodeAnalyzeParms x x <- transformGrin simplifyParms x wdump FD.GrinPreeval $ dumpGrin "preeval2" x x <- transformGrin nodeAnalyzeParms x x <- transformGrin simplifyParms x x <- createEvalApply x x <- transformGrin simplifyParms x putProgressLn "-- Grin Devolution" wdump FD.GrinFinal $ dumpGrin "predevolve" x x <- transformGrin devolveTransform x x < - opt " After " x x <- transformGrin simplifyParms x x <- return $ twiddleGrin x x <- storeAnalyze x dumpFinalGrin x compileGrinToC x dumpFinalGrin grin = do wdump FD.GrinGraph $ do let dot = graphGrin grin writeFile (outputName ++ "_grin.dot") dot wdump FD.GrinFinal $ dumpGrin "final" grin compileGrinToC grin = do let (cg,Requires reqs) = FG2.compileGrin grin rls = filter ("-l" `isPrefixOf`) $ map (unpackPS . snd) (Set.toList reqs) fn = outputName ++ lup "executable_extension" lup k = maybe "" id $ Map.lookup k (optInis options) cf <- case (optOutName options,optStop options) of (Just fn,StopC) -> return fn _ | dump FD.C -> return (fn ++ "_code.c") | otherwise -> fileInTempDir ("main_code.c") (\_ -> return ()) (argstring,sversion) <- getArgString (cc,args) <- fetchCompilerFlags forM_ [("rts/constants.h",constants_h), ("rts/stableptr.c",stableptr_c), ("rts/stableptr.h",stableptr_h), ("rts/slub.c",slub_c), ("rts/profile.c",profile_c), ("rts/profile.h",profile_h), ("rts/gc.h",gc_h), ("rts/rts_support.c",rts_support_c), ("rts/rts_support.h",rts_support_h), ("rts/jhc_rts.c",jhc_rts_c), ("rts/jhc_rts.h",jhc_rts_h), ("lib/lib_cbits.c",lib_cbits_c), ("lib/lib_cbits.h",lib_cbits_h), ("rts/cdefs.h",cdefs_h), ("sys/queue.h",queue_h), ("HsFFI.h",hsffi_h), ("jhc_rts_header.h",jhc_rts_header_h), ("sys/wsize.h",wsize_h), ("rts/gc_jgc.c",gc_jgc_c), ("rts/gc_jgc.h",gc_jgc_h), ("rts/gc_jgc_internal.h",gc_jgc_internal_h), ("rts/gc_none.c",gc_none_c), ("rts/gc_none.h",gc_none_h), ("rts/conc.c",conc_c), ("rts/conc.h",conc_h), ("sys/bitarray.h",bitarray_h)] $ \ (fn,bs) -> do fileInTempDir fn $ flip BS.writeFile bs let cFiles = ["rts/profile.c", "rts/rts_support.c", "rts/gc_none.c", "rts/jhc_rts.c", "lib/lib_cbits.c", "rts/gc_jgc.c", "rts/stableptr.c", "rts/conc.c"] tdir <- getTempDir ds <- iocatch (getDirectoryContents (tdir FP.</> "cbits")) (\_ -> return []) let extraCFiles = map noEscapePath $ map (tdir FP.</>) cFiles ++ ["-I" ++ tdir ++ "/cbits", "-I" ++ tdir ] ++ [ tdir FP.</> "cbits" FP.</> fn | fn@(reverse -> 'c':'.':_) <- ds ] let comm = shellQuote $ [cc] ++ extraCFiles ++ [cf, "-o", fn] ++ args ++ rls globalvar n c = LBS.fromString $ "char " ++ n ++ "[] = \"" ++ c ++ "\";" putProgressLn ("Writing " ++ show cf) LBS.writeFile cf $ LBS.intercalate (LBS.fromString "\n") [ globalvar "jhc_c_compile" comm, globalvar "jhc_command" argstring, globalvar "jhc_version" sversion,LBS.empty,cg] when (optStop options == StopC) $ exitSuccess putProgressLn ("Running: " ++ comm) r <- systemCompat comm when (r /= ExitSuccess) $ fail "C code did not compile." return () grinParms = transformParms { transformDumpProgress = verbose, transformPass = "Grin" } simplifyParms = grinParms { transformCategory = "Simplify", transformOperation = Grin.SSimplify.simplify, transformIterate = IterateDone } nodeAnalyzeParms = grinParms { transformCategory = "NodeAnalyze", transformOperation = nodealyze } where nodealyze grin = do stats <- Stats.new g <- deadCode stats (grinEntryPointNames grin) grin g <- nodeAnalyze g st <- Stats.readStat stats return g { grinStats = grinStats grin `mappend` st } pushParms = grinParms { transformCategory = "Push", transformOperation = pushGrin } where pushGrin grin = do nf <- mapMsnd (grinPush undefined) (grinFuncs grin) return $ setGrinFunctions nf grin deadCodeParms = grinParms { transformCategory = "DeadCode", transformOperation = op } where op grin = do stats <- Stats.new g <- deadCode stats (grinEntryPointNames grin) grin st <- Stats.readStat stats return g { grinStats = grinStats grin `mappend` st }
4dd800508e21a236e0fd31e6518a19a7e39278b2e2cc34b56579dbe67bd7094e
SKA-ScienceDataProcessor/RC
Run.hs
# LANGUAGE ExistentialQuantification # {-# LANGUAGE BangPatterns #-} module Flow.Run ( dumpStrategy , dumpStrategyDOT , dumpSteps , execStrategy , execStrategyDNA ) where import Control.Monad import Control.Concurrent import Data.List import Data.Maybe ( fromMaybe, fromJust, mapMaybe ) import qualified Data.IntMap as IM import qualified Data.IntSet as IS import qualified Data.Map.Strict as Map import Data.IORef import Data.Ord import Data.Time.Clock import System.IO import Flow.Internal import Flow.Vector import Flow.Run.Maps import Flow.Run.DNA dumpStrategy :: Strategy a -> IO () dumpStrategy strat = do Construct strategy map let kerns = runStrategy (void strat) -- Generate sorted kernel let kerns' = sortBy (comparing kernId) (stepsToKernels kerns) let dumpKern (KernelBind kid kfl kname repr deps _ _ _) = do putStrLn $ concat [ "Kernel ", show kid, ":", kname, " implementing ", flName kfl , " producing ", show repr, " using ", show deps ] forM_ kerns' dumpKern dumpStrategyDOT :: FilePath -> Strategy a -> IO () dumpStrategyDOT file strat = do Construct strategy map let kerns = runStrategy (void strat) -- Generate sorted kernel let kerns' = sortBy (comparing kernId) (stepsToKernels kerns) -- Open output file h <- openFile file WriteMode hPutStrLn h "digraph strategy {" let kidName kid = "kernel" ++ show kid let dumpKern (KernelBind kid kfl kname repr deps _ _ _) = do hPutStrLn h $ concat [ kidName kid, " [label=\"" ++ kname, " implementing ", flName kfl, " producing ", show repr, "\"]"] forM_ (deps) $ \kid' -> hPutStrLn h $ concat [ kidName kid', " -> ", kidName kid] forM_ kerns' dumpKern hPutStrLn h "}" hClose h dumpSteps :: Strategy a -> IO () dumpSteps strat = do let dump ind (DomainStep m_kid dh) = putStrLn $ ind ++ "Domain " ++ show dh ++ maybe "" (\kid -> " from kernel " ++ show kid) m_kid ++ maybe "" (\dom -> " split from " ++ show dom) (dhParent dh) dump ind (KernelStep kb@KernelBind{kernRepr=ReprI rep}) = putStrLn $ ind ++ "Over " ++ show (reprDomain rep) ++ " run " ++ show kb dump ind (RecoverStep kb@KernelBind{kernRepr=ReprI rep} kid) = putStrLn $ ind ++ "Over " ++ show (reprDomain rep) ++ " use " ++ show kb ++ " to recover " ++ show kid dump ind step@(DistributeStep did sched steps) = do putStrLn $ ind ++ "Distribute " ++ show did ++ " using " ++ show sched ++ " deps " ++ show (stepKernDeps step) forM_ steps (dump (" " ++ ind)) forM_ (runStrategy (void strat)) (dump "") execStrategy :: Strategy () -> IO () execStrategy strat = do Initialise maps dataMapRef <- newIORef IM.empty domainMapRef <- newIORef IM.empty -- Run steps given by strategy execSteps dataMapRef domainMapRef IS.empty $ runStrategy strat -- | Execute schedule, discarding unecessary buffers as required execSteps :: IORef DataMap -> IORef DomainMap -> KernelSet -> [Step] -> IO () execSteps dataMapRef domainMapRef topDeps steps = do -- Annotate steps with dependencies of the following steps let annotated = zip steps $ map stepsKernDeps $ tail $ tails steps forM_ annotated $ \(step, deps) -> do -- Execute step let allDeps = topDeps `IS.union` deps execStep dataMapRef domainMapRef allDeps step -- Discard all buffers that are not required any more. -- TODO: fix O(N^2) dataMap <- readIORef dataMapRef let isDep kid _ = kid `IS.member` allDeps (dataMap', discardMap) = IM.partitionWithKey isDep dataMap writeIORef dataMapRef dataMap' forM_ (IM.assocs discardMap) $ \(kid, (_repr, m)) -> forM_ (Map.assocs m) $ \(rbox, v) -> do putStrLn $ "Discarding buffer " ++ show kid ++ " for region box " ++ show rbox freeVector v -- | Execute schedule step execStep :: IORef DataMap -> IORef DomainMap -> KernelSet -> Step -> IO () execStep dataMapRef domainMapRef deps step = case step of DomainStep m_kid dh -> do -- Look up input data dataMap <- readIORef dataMapRef let m_buf = do kid <- m_kid (_rep, bufs) <- IM.lookup kid dataMap return bufs Primitive domains have exactly one region on construction regs' <- case dhParent dh of -- No parent: Straight-forward creation Nothing -> do reg <- dhCreate dh (fromMaybe Map.empty m_buf) return [reg] -- Otherwise: Split an existing domain Just parDh -> do -- Get domain to split up let err = error $ "Could not find domain " ++ show (dhId dh) ++ " to split!" (_, regs) <- fromMaybe err . IM.lookup (dhId parDh) <$> readIORef domainMapRef -- Perform split concat <$> mapM (dhRegion dh) regs -- Add to map modifyIORef domainMapRef $ IM.insert (dhId dh) (DomainI dh, regs') KernelStep kbind@KernelBind{kernRepr=ReprI rep} -> do -- Get domains to execute this kernel over domainMap <- readIORef domainMapRef let lookupDom did = case IM.lookup did domainMap of Just dom -> dom Nothing -> error $ "Kernel " ++ show kbind ++ " called for non-existant domain " ++ show did ++ "!" Construct all output regions ( cartesian product of all involved -- domain regions) let cartProd = sequence :: [[Region]] -> [RegionBox] outDoms = map lookupDom (reprDomain rep) outRegs = cartProd $ map snd outDoms -- Filter boxes (yeah, ugly & slow) let filteredRegs :: [RegionBox] filteredRegs = foldr filterBox outRegs $ zip [0..] $ map fst outDoms filterBox (i, dom) = mapMaybe $ \box -> let (pre,reg:post) = splitAt i box in case adhFilterBox dom (pre ++ post) reg of Just reg' -> Just $ pre ++ reg':post Nothing -> Nothing -- Look up input data. Note that we always pass all available data -- here. This means that we are relying on 1 ) DistributeStep below to restrict the data map 2 ) The kernel being able to work with what we pass it dataMap <- readIORef dataMapRef ins <- forM (kernDeps kbind) $ \kdep -> do case IM.lookup (kdepId kdep) dataMap of Just (_, bufs) -> return (kdep, bufs) Nothing -> fail $ "Internal error for kernel " ++ show (kernName kbind) ++ ": Input " ++ show (kdepId kdep) ++ " not found!" -- This should never happen -- Important TODO: Duplicate data that is written here, but read later! -- Call the kernel using the right regions !t0 <- getCurrentTime results <- kernCode kbind (map snd ins) filteredRegs !t1 <- getCurrentTime -- Check size let expectedSizes = map (reprSize rep) filteredRegs forM_ (zip results expectedSizes) $ \(res, m_size) -> case m_size of Just size | size /= vectorByteSize res -> fail $ "Kernel " ++ kernName kbind ++ " produced " ++ show (vectorByteSize res) ++ " bytes of data, but data representation " ++ show rep ++ " has " ++ show size ++ " bytes!" _other -> return () -- Debug putStrLn $ "Calculated kernel " ++ show (kernId kbind) ++ ":" ++ kernName kbind ++ " regions " ++ show filteredRegs ++ " in " ++ show (1000 * diffUTCTime t1 t0) ++ " ms" -- Get inputs that have been written, and therefore should be -- considered freed. TODO: ugly let writtenIns = filter ((== WriteAccess) . kdepAccess . fst) ins forM_ writtenIns $ \(dep, rdata) -> forM_ (Map.keys rdata) $ \rbox -> modifyIORef dataMapRef $ flip dataMapDifference $ dataMapInsert (kdepId dep) (kdepRepr dep) (Map.singleton rbox nullVector) IM.empty -- Insert result let resultMap = Map.fromList $ zip filteredRegs results modifyIORef dataMapRef $ dataMapInsert (kernId kbind) (kernRepr kbind) resultMap RecoverStep{} -> return () -- No recovery from failure DistributeStep dh sched steps -> do -- Make new domain maps for children domainMap <- readIORef domainMapRef let domDeps = IS.delete (dhId dh) $ stepDomainDeps step isDomDep did _ = did `IS.member` domDeps domainMap' = IM.filterWithKey isDomDep domainMap -- As well as a new data map dataMap <- readIORef dataMapRef let dataDeps = stepKernDeps step isDataDep did _ = did `IS.member` dataDeps dataMap' = IM.filterWithKey isDataDep dataMap Distribute over all regions let regs = snd $ fromJust $ IM.lookup (dhId dh) domainMap threads <- forM regs $ \reg -> do -- Make new restricted maps. In a distributed setting, this is -- the data we would need to send remotely. domainMapRef' <- newIORef $ IM.insert (dhId dh) (DomainI dh, [reg]) domainMap' -- Also filter data so we only send data for the appropriate region let usesRegion (ReprI repr) = dhId dh `elem` reprDomain repr filterData (ri, bufs) = (ri, if usesRegion ri then Map.filterWithKey (\ds _ -> reg `elem` ds) bufs else bufs) dataMap'' = IM.map filterData dataMap' dataMapRef' <- newIORef dataMap'' -- Especially add extra dependencies for all data that is not local to our region . Otherwise one iteration might end up -- discarding data that another needs. (We will discard this -- data after the loop in that case). let extraDeps = IM.keysSet $ IM.filter (\(ri, _) -> not (usesRegion ri)) dataMap'' -- Execute steps result <- newEmptyMVar (if sched == SeqSchedule then id else void . forkOS) $ do execSteps dataMapRef' domainMapRef' (deps `IS.union` extraDeps) steps putMVar result =<< readIORef dataMapRef' return (result, dataMap'') -- Wait for threads dataMapsNew <- mapM readMVar $ map fst threads -- Combine maps. What is happening here is: -- 1 . We add all new buffers that the child returned . Note that it might -- return buffers that we already have - this does no harm, but a -- distributed version would want to prevent this. -- 2 . We remove all buffers that the children freed ( to prevent double - free ) . Obviously only a concern because of SM parallelism . let dataMapOrig = dataMapUnions (map snd threads) dataMapNew = dataMapUnions dataMapsNew dataMapRemoved = dataMapDifference dataMapOrig dataMapNew modifyIORef dataMapRef $ dataMapUnion dataMapNew . flip dataMapDifference dataMapRemoved
null
https://raw.githubusercontent.com/SKA-ScienceDataProcessor/RC/1b5e25baf9204a9f7ef40ed8ee94a86cc6c674af/MS5/dna/flow/Flow/Run.hs
haskell
# LANGUAGE BangPatterns # Generate sorted kernel Generate sorted kernel Open output file Run steps given by strategy | Execute schedule, discarding unecessary buffers as required Annotate steps with dependencies of the following steps Execute step Discard all buffers that are not required any more. TODO: fix O(N^2) | Execute schedule step Look up input data No parent: Straight-forward creation Otherwise: Split an existing domain Get domain to split up Perform split Add to map Get domains to execute this kernel over domain regions) Filter boxes (yeah, ugly & slow) Look up input data. Note that we always pass all available data here. This means that we are relying on This should never happen Important TODO: Duplicate data that is written here, but read later! Call the kernel using the right regions Check size Debug Get inputs that have been written, and therefore should be considered freed. TODO: ugly Insert result No recovery from failure Make new domain maps for children As well as a new data map Make new restricted maps. In a distributed setting, this is the data we would need to send remotely. Also filter data so we only send data for the appropriate region Especially add extra dependencies for all data that is not discarding data that another needs. (We will discard this data after the loop in that case). Execute steps Wait for threads Combine maps. What is happening here is: return buffers that we already have - this does no harm, but a distributed version would want to prevent this.
# LANGUAGE ExistentialQuantification # module Flow.Run ( dumpStrategy , dumpStrategyDOT , dumpSteps , execStrategy , execStrategyDNA ) where import Control.Monad import Control.Concurrent import Data.List import Data.Maybe ( fromMaybe, fromJust, mapMaybe ) import qualified Data.IntMap as IM import qualified Data.IntSet as IS import qualified Data.Map.Strict as Map import Data.IORef import Data.Ord import Data.Time.Clock import System.IO import Flow.Internal import Flow.Vector import Flow.Run.Maps import Flow.Run.DNA dumpStrategy :: Strategy a -> IO () dumpStrategy strat = do Construct strategy map let kerns = runStrategy (void strat) let kerns' = sortBy (comparing kernId) (stepsToKernels kerns) let dumpKern (KernelBind kid kfl kname repr deps _ _ _) = do putStrLn $ concat [ "Kernel ", show kid, ":", kname, " implementing ", flName kfl , " producing ", show repr, " using ", show deps ] forM_ kerns' dumpKern dumpStrategyDOT :: FilePath -> Strategy a -> IO () dumpStrategyDOT file strat = do Construct strategy map let kerns = runStrategy (void strat) let kerns' = sortBy (comparing kernId) (stepsToKernels kerns) h <- openFile file WriteMode hPutStrLn h "digraph strategy {" let kidName kid = "kernel" ++ show kid let dumpKern (KernelBind kid kfl kname repr deps _ _ _) = do hPutStrLn h $ concat [ kidName kid, " [label=\"" ++ kname, " implementing ", flName kfl, " producing ", show repr, "\"]"] forM_ (deps) $ \kid' -> hPutStrLn h $ concat [ kidName kid', " -> ", kidName kid] forM_ kerns' dumpKern hPutStrLn h "}" hClose h dumpSteps :: Strategy a -> IO () dumpSteps strat = do let dump ind (DomainStep m_kid dh) = putStrLn $ ind ++ "Domain " ++ show dh ++ maybe "" (\kid -> " from kernel " ++ show kid) m_kid ++ maybe "" (\dom -> " split from " ++ show dom) (dhParent dh) dump ind (KernelStep kb@KernelBind{kernRepr=ReprI rep}) = putStrLn $ ind ++ "Over " ++ show (reprDomain rep) ++ " run " ++ show kb dump ind (RecoverStep kb@KernelBind{kernRepr=ReprI rep} kid) = putStrLn $ ind ++ "Over " ++ show (reprDomain rep) ++ " use " ++ show kb ++ " to recover " ++ show kid dump ind step@(DistributeStep did sched steps) = do putStrLn $ ind ++ "Distribute " ++ show did ++ " using " ++ show sched ++ " deps " ++ show (stepKernDeps step) forM_ steps (dump (" " ++ ind)) forM_ (runStrategy (void strat)) (dump "") execStrategy :: Strategy () -> IO () execStrategy strat = do Initialise maps dataMapRef <- newIORef IM.empty domainMapRef <- newIORef IM.empty execSteps dataMapRef domainMapRef IS.empty $ runStrategy strat execSteps :: IORef DataMap -> IORef DomainMap -> KernelSet -> [Step] -> IO () execSteps dataMapRef domainMapRef topDeps steps = do let annotated = zip steps $ map stepsKernDeps $ tail $ tails steps forM_ annotated $ \(step, deps) -> do let allDeps = topDeps `IS.union` deps execStep dataMapRef domainMapRef allDeps step dataMap <- readIORef dataMapRef let isDep kid _ = kid `IS.member` allDeps (dataMap', discardMap) = IM.partitionWithKey isDep dataMap writeIORef dataMapRef dataMap' forM_ (IM.assocs discardMap) $ \(kid, (_repr, m)) -> forM_ (Map.assocs m) $ \(rbox, v) -> do putStrLn $ "Discarding buffer " ++ show kid ++ " for region box " ++ show rbox freeVector v execStep :: IORef DataMap -> IORef DomainMap -> KernelSet -> Step -> IO () execStep dataMapRef domainMapRef deps step = case step of DomainStep m_kid dh -> do dataMap <- readIORef dataMapRef let m_buf = do kid <- m_kid (_rep, bufs) <- IM.lookup kid dataMap return bufs Primitive domains have exactly one region on construction regs' <- case dhParent dh of Nothing -> do reg <- dhCreate dh (fromMaybe Map.empty m_buf) return [reg] Just parDh -> do let err = error $ "Could not find domain " ++ show (dhId dh) ++ " to split!" (_, regs) <- fromMaybe err . IM.lookup (dhId parDh) <$> readIORef domainMapRef concat <$> mapM (dhRegion dh) regs modifyIORef domainMapRef $ IM.insert (dhId dh) (DomainI dh, regs') KernelStep kbind@KernelBind{kernRepr=ReprI rep} -> do domainMap <- readIORef domainMapRef let lookupDom did = case IM.lookup did domainMap of Just dom -> dom Nothing -> error $ "Kernel " ++ show kbind ++ " called for non-existant domain " ++ show did ++ "!" Construct all output regions ( cartesian product of all involved let cartProd = sequence :: [[Region]] -> [RegionBox] outDoms = map lookupDom (reprDomain rep) outRegs = cartProd $ map snd outDoms let filteredRegs :: [RegionBox] filteredRegs = foldr filterBox outRegs $ zip [0..] $ map fst outDoms filterBox (i, dom) = mapMaybe $ \box -> let (pre,reg:post) = splitAt i box in case adhFilterBox dom (pre ++ post) reg of Just reg' -> Just $ pre ++ reg':post Nothing -> Nothing 1 ) DistributeStep below to restrict the data map 2 ) The kernel being able to work with what we pass it dataMap <- readIORef dataMapRef ins <- forM (kernDeps kbind) $ \kdep -> do case IM.lookup (kdepId kdep) dataMap of Just (_, bufs) -> return (kdep, bufs) Nothing -> fail $ "Internal error for kernel " ++ show (kernName kbind) ++ ": Input " ++ show (kdepId kdep) ++ " not found!" !t0 <- getCurrentTime results <- kernCode kbind (map snd ins) filteredRegs !t1 <- getCurrentTime let expectedSizes = map (reprSize rep) filteredRegs forM_ (zip results expectedSizes) $ \(res, m_size) -> case m_size of Just size | size /= vectorByteSize res -> fail $ "Kernel " ++ kernName kbind ++ " produced " ++ show (vectorByteSize res) ++ " bytes of data, but data representation " ++ show rep ++ " has " ++ show size ++ " bytes!" _other -> return () putStrLn $ "Calculated kernel " ++ show (kernId kbind) ++ ":" ++ kernName kbind ++ " regions " ++ show filteredRegs ++ " in " ++ show (1000 * diffUTCTime t1 t0) ++ " ms" let writtenIns = filter ((== WriteAccess) . kdepAccess . fst) ins forM_ writtenIns $ \(dep, rdata) -> forM_ (Map.keys rdata) $ \rbox -> modifyIORef dataMapRef $ flip dataMapDifference $ dataMapInsert (kdepId dep) (kdepRepr dep) (Map.singleton rbox nullVector) IM.empty let resultMap = Map.fromList $ zip filteredRegs results modifyIORef dataMapRef $ dataMapInsert (kernId kbind) (kernRepr kbind) resultMap DistributeStep dh sched steps -> do domainMap <- readIORef domainMapRef let domDeps = IS.delete (dhId dh) $ stepDomainDeps step isDomDep did _ = did `IS.member` domDeps domainMap' = IM.filterWithKey isDomDep domainMap dataMap <- readIORef dataMapRef let dataDeps = stepKernDeps step isDataDep did _ = did `IS.member` dataDeps dataMap' = IM.filterWithKey isDataDep dataMap Distribute over all regions let regs = snd $ fromJust $ IM.lookup (dhId dh) domainMap threads <- forM regs $ \reg -> do domainMapRef' <- newIORef $ IM.insert (dhId dh) (DomainI dh, [reg]) domainMap' let usesRegion (ReprI repr) = dhId dh `elem` reprDomain repr filterData (ri, bufs) = (ri, if usesRegion ri then Map.filterWithKey (\ds _ -> reg `elem` ds) bufs else bufs) dataMap'' = IM.map filterData dataMap' dataMapRef' <- newIORef dataMap'' local to our region . Otherwise one iteration might end up let extraDeps = IM.keysSet $ IM.filter (\(ri, _) -> not (usesRegion ri)) dataMap'' result <- newEmptyMVar (if sched == SeqSchedule then id else void . forkOS) $ do execSteps dataMapRef' domainMapRef' (deps `IS.union` extraDeps) steps putMVar result =<< readIORef dataMapRef' return (result, dataMap'') dataMapsNew <- mapM readMVar $ map fst threads 1 . We add all new buffers that the child returned . Note that it might 2 . We remove all buffers that the children freed ( to prevent double - free ) . Obviously only a concern because of SM parallelism . let dataMapOrig = dataMapUnions (map snd threads) dataMapNew = dataMapUnions dataMapsNew dataMapRemoved = dataMapDifference dataMapOrig dataMapNew modifyIORef dataMapRef $ dataMapUnion dataMapNew . flip dataMapDifference dataMapRemoved
42a597706fa9cb66a971819fc532897ad4809da99203089b85535d9a42f02dc6
sebsheep/elm2node
Constraint.hs
# OPTIONS_GHC -Wall # {-# LANGUAGE OverloadedStrings #-} module Elm.Constraint ( Constraint , exactly , anything , toChars , satisfies , check , intersect , goodElm , defaultElm , untilNextMajor , untilNextMinor , expand -- , Error(..) , decoder , encode ) where import Control.Monad (liftM4) import Data.Binary (Binary, get, put, getWord8, putWord8) import qualified Elm.Version as V import qualified Json.Decode as D import qualified Json.Encode as E import qualified Parse.Primitives as P import Parse.Primitives (Row, Col) -- CONSTRAINTS data Constraint = Range V.Version Op Op V.Version deriving (Eq) data Op = Less | LessOrEqual deriving (Eq) -- COMMON CONSTRAINTS exactly :: V.Version -> Constraint exactly version = Range version LessOrEqual LessOrEqual version anything :: Constraint anything = Range V.one LessOrEqual LessOrEqual V.max -- TO CHARS toChars :: Constraint -> [Char] toChars constraint = case constraint of Range lower lowerOp upperOp upper -> V.toChars lower ++ opToChars lowerOp ++ "v" ++ opToChars upperOp ++ V.toChars upper opToChars :: Op -> [Char] opToChars op = case op of Less -> " < " LessOrEqual -> " <= " -- IS SATISFIED satisfies :: Constraint -> V.Version -> Bool satisfies constraint version = case constraint of Range lower lowerOp upperOp upper -> isLess lowerOp lower version && isLess upperOp version upper isLess :: (Ord a) => Op -> (a -> a -> Bool) isLess op = case op of Less -> (<) LessOrEqual -> (<=) check :: Constraint -> V.Version -> Ordering check constraint version = case constraint of Range lower lowerOp upperOp upper -> if not (isLess lowerOp lower version) then LT else if not (isLess upperOp version upper) then GT else EQ -- INTERSECT intersect :: Constraint -> Constraint -> Maybe Constraint intersect (Range lo lop hop hi) (Range lo_ lop_ hop_ hi_) = let (newLo, newLop) = case compare lo lo_ of LT -> (lo_, lop_) EQ -> (lo, if elem Less [lop,lop_] then Less else LessOrEqual) GT -> (lo, lop) (newHi, newHop) = case compare hi hi_ of LT -> (hi, hop) EQ -> (hi, if elem Less [hop, hop_] then Less else LessOrEqual) GT -> (hi_, hop_) in if newLo <= newHi then Just (Range newLo newLop newHop newHi) else Nothing ELM CONSTRAINT goodElm :: Constraint -> Bool goodElm constraint = satisfies constraint V.compiler defaultElm :: Constraint defaultElm = if V._major V.compiler > 0 then untilNextMajor V.compiler else untilNextMinor V.compiler -- CREATE CONSTRAINTS untilNextMajor :: V.Version -> Constraint untilNextMajor version = Range version LessOrEqual Less (V.bumpMajor version) untilNextMinor :: V.Version -> Constraint untilNextMinor version = Range version LessOrEqual Less (V.bumpMinor version) expand :: Constraint -> V.Version -> Constraint expand constraint@(Range lower lowerOp upperOp upper) version | version < lower = Range version LessOrEqual upperOp upper | version > upper = Range lower lowerOp Less (V.bumpMajor version) | otherwise = constraint -- JSON encode :: Constraint -> E.Value encode constraint = E.chars (toChars constraint) decoder :: D.Decoder Error Constraint decoder = D.customString parser BadFormat -- BINARY instance Binary Constraint where get = liftM4 Range get get get get put (Range a b c d) = put a >> put b >> put c >> put d instance Binary Op where put op = case op of Less -> putWord8 0 LessOrEqual -> putWord8 1 get = do n <- getWord8 case n of 0 -> return Less 1 -> return LessOrEqual _ -> fail "binary encoding of Op was corrupted" -- PARSER data Error = BadFormat Row Col | InvalidRange V.Version V.Version parser :: P.Parser Error Constraint parser = do lower <- parseVersion P.word1 0x20 {- -} BadFormat loOp <- parseOp P.word1 0x20 {- -} BadFormat P.word1 0x76 {-v-} BadFormat P.word1 0x20 {- -} BadFormat hiOp <- parseOp P.word1 0x20 {- -} BadFormat higher <- parseVersion P.Parser $ \state@(P.State _ _ _ _ row col) _ eok _ eerr -> if lower < higher then eok (Range lower loOp hiOp higher) state else eerr row col (\_ _ -> InvalidRange lower higher) parseVersion :: P.Parser Error V.Version parseVersion = P.specialize (\(r,c) _ _ -> BadFormat r c) V.parser parseOp :: P.Parser Error Op parseOp = do P.word1 0x3C {-<-} BadFormat P.oneOfWithFallback [ do P.word1 0x3D {-=-} BadFormat return LessOrEqual ] Less
null
https://raw.githubusercontent.com/sebsheep/elm2node/602a64f48e39edcdfa6d99793cc2827b677d650d/compiler/src/Elm/Constraint.hs
haskell
# LANGUAGE OverloadedStrings # CONSTRAINTS COMMON CONSTRAINTS TO CHARS IS SATISFIED INTERSECT CREATE CONSTRAINTS JSON BINARY PARSER v < =
# OPTIONS_GHC -Wall # module Elm.Constraint ( Constraint , exactly , anything , toChars , satisfies , check , intersect , goodElm , defaultElm , untilNextMajor , untilNextMinor , expand , Error(..) , decoder , encode ) where import Control.Monad (liftM4) import Data.Binary (Binary, get, put, getWord8, putWord8) import qualified Elm.Version as V import qualified Json.Decode as D import qualified Json.Encode as E import qualified Parse.Primitives as P import Parse.Primitives (Row, Col) data Constraint = Range V.Version Op Op V.Version deriving (Eq) data Op = Less | LessOrEqual deriving (Eq) exactly :: V.Version -> Constraint exactly version = Range version LessOrEqual LessOrEqual version anything :: Constraint anything = Range V.one LessOrEqual LessOrEqual V.max toChars :: Constraint -> [Char] toChars constraint = case constraint of Range lower lowerOp upperOp upper -> V.toChars lower ++ opToChars lowerOp ++ "v" ++ opToChars upperOp ++ V.toChars upper opToChars :: Op -> [Char] opToChars op = case op of Less -> " < " LessOrEqual -> " <= " satisfies :: Constraint -> V.Version -> Bool satisfies constraint version = case constraint of Range lower lowerOp upperOp upper -> isLess lowerOp lower version && isLess upperOp version upper isLess :: (Ord a) => Op -> (a -> a -> Bool) isLess op = case op of Less -> (<) LessOrEqual -> (<=) check :: Constraint -> V.Version -> Ordering check constraint version = case constraint of Range lower lowerOp upperOp upper -> if not (isLess lowerOp lower version) then LT else if not (isLess upperOp version upper) then GT else EQ intersect :: Constraint -> Constraint -> Maybe Constraint intersect (Range lo lop hop hi) (Range lo_ lop_ hop_ hi_) = let (newLo, newLop) = case compare lo lo_ of LT -> (lo_, lop_) EQ -> (lo, if elem Less [lop,lop_] then Less else LessOrEqual) GT -> (lo, lop) (newHi, newHop) = case compare hi hi_ of LT -> (hi, hop) EQ -> (hi, if elem Less [hop, hop_] then Less else LessOrEqual) GT -> (hi_, hop_) in if newLo <= newHi then Just (Range newLo newLop newHop newHi) else Nothing ELM CONSTRAINT goodElm :: Constraint -> Bool goodElm constraint = satisfies constraint V.compiler defaultElm :: Constraint defaultElm = if V._major V.compiler > 0 then untilNextMajor V.compiler else untilNextMinor V.compiler untilNextMajor :: V.Version -> Constraint untilNextMajor version = Range version LessOrEqual Less (V.bumpMajor version) untilNextMinor :: V.Version -> Constraint untilNextMinor version = Range version LessOrEqual Less (V.bumpMinor version) expand :: Constraint -> V.Version -> Constraint expand constraint@(Range lower lowerOp upperOp upper) version | version < lower = Range version LessOrEqual upperOp upper | version > upper = Range lower lowerOp Less (V.bumpMajor version) | otherwise = constraint encode :: Constraint -> E.Value encode constraint = E.chars (toChars constraint) decoder :: D.Decoder Error Constraint decoder = D.customString parser BadFormat instance Binary Constraint where get = liftM4 Range get get get get put (Range a b c d) = put a >> put b >> put c >> put d instance Binary Op where put op = case op of Less -> putWord8 0 LessOrEqual -> putWord8 1 get = do n <- getWord8 case n of 0 -> return Less 1 -> return LessOrEqual _ -> fail "binary encoding of Op was corrupted" data Error = BadFormat Row Col | InvalidRange V.Version V.Version parser :: P.Parser Error Constraint parser = do lower <- parseVersion loOp <- parseOp hiOp <- parseOp higher <- parseVersion P.Parser $ \state@(P.State _ _ _ _ row col) _ eok _ eerr -> if lower < higher then eok (Range lower loOp hiOp higher) state else eerr row col (\_ _ -> InvalidRange lower higher) parseVersion :: P.Parser Error V.Version parseVersion = P.specialize (\(r,c) _ _ -> BadFormat r c) V.parser parseOp :: P.Parser Error Op parseOp = P.oneOfWithFallback return LessOrEqual ] Less
84e34d2374818251b4114ec6d612952d8202edf0f0d7673a322233e5867cf595
TrustInSoft/tis-kernel
ctrlDpds.mli
(**************************************************************************) (* *) This file is part of . (* *) is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 (* *) is released under GPLv2 (* *) (**************************************************************************) (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) (** Internal information about control dependencies *) type t (** Compute some information on the function in order to be able to compute * the control dependencies later on *) val compute : Kernel_function.t -> t (** Compute the list of the statements that should have a control dependency * on the given IF statement. *) val get_if_controled_stmts : t -> Cil_types.stmt -> Cil_datatype.Stmt.Hptset.t * Compute the list of the statements that should have a control dependency * on the given jump statement . This statement can be a [ goto ] of course , * but also a [ break ] , a [ continue ] , or even a loop because CIL transformations make them of the form { v while(true ) body ; v } which is equivalent to { v L : body ; goto L ; v } * * on the given jump statement. This statement can be a [goto] of course, * but also a [break], a [continue], or even a loop because CIL transformations make them of the form {v while(true) body; v} which is equivalent to {v L : body ; goto L; v} * *) val get_jump_controled_stmts : t -> Cil_types.stmt -> Cil_datatype.Stmt.Hptset.t val get_loop_controled_stmts : t -> Cil_types.stmt -> Cil_datatype.Stmt.Hptset.t (* Local Variables: compile-command: "make -C ../../.." End: *)
null
https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/pdg/ctrlDpds.mli
ocaml
************************************************************************ ************************************************************************ ************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ * Internal information about control dependencies * Compute some information on the function in order to be able to compute * the control dependencies later on * Compute the list of the statements that should have a control dependency * on the given IF statement. Local Variables: compile-command: "make -C ../../.." End:
This file is part of . is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 is released under GPLv2 This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . type t val compute : Kernel_function.t -> t val get_if_controled_stmts : t -> Cil_types.stmt -> Cil_datatype.Stmt.Hptset.t * Compute the list of the statements that should have a control dependency * on the given jump statement . This statement can be a [ goto ] of course , * but also a [ break ] , a [ continue ] , or even a loop because CIL transformations make them of the form { v while(true ) body ; v } which is equivalent to { v L : body ; goto L ; v } * * on the given jump statement. This statement can be a [goto] of course, * but also a [break], a [continue], or even a loop because CIL transformations make them of the form {v while(true) body; v} which is equivalent to {v L : body ; goto L; v} * *) val get_jump_controled_stmts : t -> Cil_types.stmt -> Cil_datatype.Stmt.Hptset.t val get_loop_controled_stmts : t -> Cil_types.stmt -> Cil_datatype.Stmt.Hptset.t
2e287d42adbe85d05d25f3969fb6b9771c702cfa24523b47b68f66ef2f7c9b48
xavierleroy/camlidl
com.ml
(***********************************************************************) (* *) (* CamlIDL *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1999 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License . (* *) (***********************************************************************) $ I d : com.ml , v 1.9 2004 - 07 - 08 09:44:40 xleroy Exp $ (* Run-time library for COM components *) type 'a interface type 'a iid type 'a opaque type clsid = string exception Error of int * string * string external initialize : unit -> unit = "camlidl_com_initialize" external uninitialize : unit -> unit = "camlidl_com_uninitialize" external query_interface: 'a interface -> 'b iid -> 'b interface = "camlidl_com_queryInterface" type iUnknown type iDispatch let iUnknown_of (intf : 'a interface) = (Obj.magic intf : iUnknown interface) let _ = Callback.register_exception "Com.Error" (Error(0, "", "")) external combine: 'a interface -> 'b interface -> 'a interface = "camlidl_com_combine" external clsid: string -> clsid = "camlidl_com_parse_uid" external _parse_iid: string -> 'a iid = "camlidl_com_parse_uid" external create_instance : clsid -> 'a iid -> 'a interface = "camlidl_com_create_instance" type 'a component_factory = { create : unit -> 'a interface; clsid : clsid; friendly_name : string; ver_ind_prog_id : string; prog_id : string } external register_factory : 'a component_factory -> unit = "camlidl_com_register_factory" type hRESULT_int = int type hRESULT_bool = bool type bSTR = string
null
https://raw.githubusercontent.com/xavierleroy/camlidl/b192760875fe6e97b13004bd289720618e12ee22/lib/com.ml
ocaml
********************************************************************* CamlIDL ********************************************************************* Run-time library for COM components
, projet Cristal , INRIA Rocquencourt Copyright 1999 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License . $ I d : com.ml , v 1.9 2004 - 07 - 08 09:44:40 xleroy Exp $ type 'a interface type 'a iid type 'a opaque type clsid = string exception Error of int * string * string external initialize : unit -> unit = "camlidl_com_initialize" external uninitialize : unit -> unit = "camlidl_com_uninitialize" external query_interface: 'a interface -> 'b iid -> 'b interface = "camlidl_com_queryInterface" type iUnknown type iDispatch let iUnknown_of (intf : 'a interface) = (Obj.magic intf : iUnknown interface) let _ = Callback.register_exception "Com.Error" (Error(0, "", "")) external combine: 'a interface -> 'b interface -> 'a interface = "camlidl_com_combine" external clsid: string -> clsid = "camlidl_com_parse_uid" external _parse_iid: string -> 'a iid = "camlidl_com_parse_uid" external create_instance : clsid -> 'a iid -> 'a interface = "camlidl_com_create_instance" type 'a component_factory = { create : unit -> 'a interface; clsid : clsid; friendly_name : string; ver_ind_prog_id : string; prog_id : string } external register_factory : 'a component_factory -> unit = "camlidl_com_register_factory" type hRESULT_int = int type hRESULT_bool = bool type bSTR = string
4a187dd0ebb31f5e74ee5a1f7d18ca4ed9727d79f7b65dd9c3e2da452ccd85d5
ml4tp/tcoq
refl_omega.ml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * PROJET RNRT Calife - 2001 Author : France Télécom R&D Licence : LGPL version 2.1 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * PROJET RNRT Calife - 2001 Author: Pierre Crégut - France Télécom R&D Licence : LGPL version 2.1 *************************************************************************) open Pp open Util open Const_omega module OmegaSolver = Omega_plugin.Omega.MakeOmegaSolver (Bigint) open OmegaSolver (* \section{Useful functions and flags} *) (* Especially useful debugging functions *) let debug = ref false let show_goal gl = if !debug then (); Tacticals.tclIDTAC gl let pp i = print_int i; print_newline (); flush stdout (* More readable than the prefix notation *) let (>>) = Tacticals.tclTHEN let mkApp = Term.mkApp (* \section{Types} \subsection{How to walk in a term} To represent how to get to a proposition. Only choice points are kept (branch to choose in a disjunction and identifier of the disjunctive connector) *) type direction = Left of int | Right of int (* Step to find a proposition (operators are at most binary). A list is a path *) type occ_step = O_left | O_right | O_mono type occ_path = occ_step list let occ_step_eq s1 s2 = match s1, s2 with | O_left, O_left | O_right, O_right | O_mono, O_mono -> true | _ -> false chemin identifiant une proposition d'une liste de pas à partir de la racine de l'hypothèse d'une liste de pas à partir de la racine de l'hypothèse *) type occurrence = {o_hyp : Names.Id.t; o_path : occ_path} (* \subsection{reifiable formulas} *) type oformula = (* integer *) | Oint of Bigint.bigint (* recognized binary and unary operations *) | Oplus of oformula * oformula | Omult of oformula * oformula | Ominus of oformula * oformula | Oopp of oformula (* an atom in the environment *) | Oatom of int (* weird expression that cannot be translated *) | Oufo of oformula Operators for comparison recognized by Omega type comparaison = Eq | Leq | Geq | Gt | Lt | Neq Type des prédicats réifiés ( fragment de calcul . Les * quantifications sont externes au langage ) * quantifications sont externes au langage) *) type oproposition = Pequa of Term.constr * oequation | Ptrue | Pfalse | Pnot of oproposition | Por of int * oproposition * oproposition | Pand of int * oproposition * oproposition | Pimp of int * oproposition * oproposition | Pprop of Term.constr Les équations ou propositions atomiques utiles du calcul and oequation = { e_comp: comparaison; (* comparaison *) e_left: oformula; (* formule brute gauche *) e_right: oformula; (* formule brute droite *) tactique de normalisation e_origin: occurrence; (* l'hypothèse dont vient le terme *) e_negated: bool; (* vrai si apparait en position nié après normalisation *) liste des points do nt dépend l'accès à l'équation avec la direction ( branche ) pour y accéder dépend l'accès à l'équation avec la direction (branche) pour y accéder *) e_omega: afine (* la fonction normalisée *) } \subsection{Proof context } This environment codes \begin{itemize } \item the terms and propositions that are given as parameters of the reified proof ( and are represented as variables in the reified goals ) \item translation functions linking the decision procedure and the Coq proof \end{itemize } This environment codes \begin{itemize} \item the terms and propositions that are given as parameters of the reified proof (and are represented as variables in the reified goals) \item translation functions linking the decision procedure and the Coq proof \end{itemize} *) type environment = { La liste des termes non reifies constituant l'environnement global mutable terms : Term.constr list; (* La meme chose pour les propositions *) mutable props : Term.constr list; (* Les variables introduites par omega *) mutable om_vars : (oformula * int) list; Traduction des indices utilisés ici en les indices utilisés par * la tactique Omega après dénombrement des variables utiles * la tactique Omega après dénombrement des variables utiles *) real_indices : (int,int) Hashtbl.t; mutable cnt_connectors : int; equations : (int,oequation) Hashtbl.t; constructors : (int, occurrence) Hashtbl.t } \subsection{Solution tree } Définition d'une solution trouvée par forme , d'un ensemble d'équation do nt dépend la solution et d'une trace Définition d'une solution trouvée par Omega sous la forme d'un identifiant, d'un ensemble d'équation dont dépend la solution et d'une trace *) La liste des dépendances est triée et sans redondance type solution = { s_index : int; s_equa_deps : int list; s_trace : action list } Arbre de solution résolvant complètement un ensemble de systèmes type solution_tree = Leaf of solution un noeud interne représente un point correspondant à l'élimination d'un connecteur ( typ . disjonction ) . Le premier argument est l'identifiant du connecteur l'élimination d'un connecteur générant plusieurs buts (typ. disjonction). Le premier argument est l'identifiant du connecteur *) | Tree of int * solution_tree * solution_tree (* Représentation de l'environnement extrait du but initial sous forme de chemins pour extraire des equations ou d'hypothèses *) type context_content = CCHyp of occurrence | CCEqua of int (* \section{Specific utility functions to handle base types} *) négation du but final let id_concl = Names.Id.of_string "__goal__" Initialisation de l'environnement de réification de la tactique let new_environment () = { terms = []; props = []; om_vars = []; cnt_connectors = 0; real_indices = Hashtbl.create 7; equations = Hashtbl.create 7; constructors = Hashtbl.create 7; } Génération d'un nom d'équation let new_connector_id env = env.cnt_connectors <- succ env.cnt_connectors; env.cnt_connectors (* Calcul de la branche complémentaire *) let barre = function Left x -> Right x | Right x -> Left x (* Identifiant associé à une branche *) let indice = function Left x | Right x -> x Affichage de l'environnement de réification ( termes et propositions ) let print_env_reification env = let rec loop c i = function [] -> str " ===============================\n\n" | t :: l -> let s = Printf.sprintf "(%c%02d)" c i in spc () ++ str s ++ str " := " ++ Printer.pr_lconstr t ++ fnl () ++ loop c (succ i) l in let prop_info = str "ENVIRONMENT OF PROPOSITIONS :" ++ fnl () ++ loop 'P' 0 env.props in let term_info = str "ENVIRONMENT OF TERMS :" ++ fnl () ++ loop 'V' 0 env.terms in Feedback.msg_debug (prop_info ++ fnl () ++ term_info) (* \subsection{Gestion des environnements de variable pour Omega} *) generation pour Omega let new_omega_eq, rst_omega_eq = let cpt = ref 0 in (function () -> incr cpt; !cpt), (function () -> cpt:=0) generation variable pour Omega let new_omega_var, rst_omega_var = let cpt = ref 0 in (function () -> incr cpt; !cpt), (function () -> cpt:=0) (* Affichage des variables d'un système *) let display_omega_var i = Printf.sprintf "OV%d" i Recherche la variable codant un terme pour Omega et crée la variable dans l'environnement . Cas ou la variable dans ( le plus souvent ) l'environnement si il n'existe pas. Cas ou la variable dans Omega représente le terme d'un monome (le plus souvent un atome) *) let intern_omega env t = FIXME with Not_found -> let v = new_omega_var () in env.om_vars <- (t,v) :: env.om_vars; v end Ajout forcé d'un lien entre un terme et une variable Cas où la variable est créée par Omega et où il faut la lier à un atome variable est créée par Omega et où il faut la lier après coup à un atome réifié introduit de force *) let intern_omega_force env t v = env.om_vars <- (t,v) :: env.om_vars (* Récupère le terme associé à une variable *) let unintern_omega env id = let rec loop = function [] -> failwith "unintern" | ((t,j)::l) -> if Int.equal id j then t else loop l in loop env.om_vars \subsection{Gestion des environnements de variable pour la réflexion } Gestion des environnements de traduction entre termes des constructions non réifiés et variables des termes reifies . Attention il s'agit de l'environnement initial contenant tout . calcul des variables utiles . Gestion des environnements de traduction entre termes des constructions non réifiés et variables des termes reifies. Attention il s'agit de l'environnement initial contenant tout. Il faudra le réduire après calcul des variables utiles. *) let add_reified_atom t env = try List.index0 Term.eq_constr t env.terms with Not_found -> let i = List.length env.terms in env.terms <- env.terms @ [t]; i let get_reified_atom env = try List.nth env.terms with Invalid_argument _ -> failwith "get_reified_atom" \subsection{Gestion de l'environnement de proposition pour Omega } (* ajout d'une proposition *) let add_prop env t = try List.index0 Term.eq_constr t env.props with Not_found -> let i = List.length env.props in env.props <- env.props @ [t]; i accès a une proposition let get_prop v env = try List.nth v env with Invalid_argument _ -> failwith "get_prop" (* \subsection{Gestion du nommage des équations} *) (* Ajout d'une equation dans l'environnement de reification *) let add_equation env e = let id = e.e_omega.id in try let _ = Hashtbl.find env.equations id in () with Not_found -> Hashtbl.add env.equations id e (* accès a une equation *) let get_equation env id = try Hashtbl.find env.equations id with Not_found as e -> Printf.printf "Omega Equation %d non trouvée\n" id; raise e (* Affichage des termes réifiés *) let rec oprint ch = function | Oint n -> Printf.fprintf ch "%s" (Bigint.to_string n) | Oplus (t1,t2) -> Printf.fprintf ch "(%a + %a)" oprint t1 oprint t2 | Omult (t1,t2) -> Printf.fprintf ch "(%a * %a)" oprint t1 oprint t2 | Ominus(t1,t2) -> Printf.fprintf ch "(%a - %a)" oprint t1 oprint t2 | Oopp t1 ->Printf.fprintf ch "~ %a" oprint t1 | Oatom n -> Printf.fprintf ch "V%02d" n | Oufo x -> Printf.fprintf ch "?" let rec pprint ch = function Pequa (_,{ e_comp=comp; e_left=t1; e_right=t2 }) -> let connector = match comp with Eq -> "=" | Leq -> "<=" | Geq -> ">=" | Gt -> ">" | Lt -> "<" | Neq -> "!=" in Printf.fprintf ch "%a %s %a" oprint t1 connector oprint t2 | Ptrue -> Printf.fprintf ch "TT" | Pfalse -> Printf.fprintf ch "FF" | Pnot t -> Printf.fprintf ch "not(%a)" pprint t | Por (_,t1,t2) -> Printf.fprintf ch "(%a or %a)" pprint t1 pprint t2 | Pand(_,t1,t2) -> Printf.fprintf ch "(%a and %a)" pprint t1 pprint t2 | Pimp(_,t1,t2) -> Printf.fprintf ch "(%a => %a)" pprint t1 pprint t2 | Pprop c -> Printf.fprintf ch "Prop" let rec weight env = function | Oint _ -> -1 | Oopp c -> weight env c | Omult(c,_) -> weight env c | Oplus _ -> failwith "weight" | Ominus _ -> failwith "weight minus" | Oufo _ -> -1 | Oatom _ as c -> (intern_omega env c) \section{Passage entre oformules et représentation interne de Omega } (* \subsection{Oformula vers Omega} *) let omega_of_oformula env kind = let rec loop accu = function | Oplus(Omult(v,Oint n),r) -> loop ({v=intern_omega env v; c=n} :: accu) r | Oint n -> let id = new_omega_eq () in (*i tag_equation name id; i*) {kind = kind; body = List.rev accu; constant = n; id = id} | t -> print_string "CO"; oprint stdout t; failwith "compile_equation" in loop [] \subsection{Omega vers Oformula } let oformula_of_omega env af = let rec loop = function | ({v=v; c=n}::r) -> Oplus(Omult(unintern_omega env v,Oint n),loop r) | [] -> Oint af.constant in loop af.body let app f v = mkApp(Lazy.force f,v) \subsection{Oformula vers COQ reel } let coq_of_formula env t = let rec loop = function | Oplus (t1,t2) -> app Z.plus [| loop t1; loop t2 |] | Oopp t -> app Z.opp [| loop t |] | Omult(t1,t2) -> app Z.mult [| loop t1; loop t2 |] | Oint v -> Z.mk v | Oufo t -> loop t | Oatom var -> (* attention ne traite pas les nouvelles variables si on ne les * met pas dans env.term *) get_reified_atom env var | Ominus(t1,t2) -> app Z.minus [| loop t1; loop t2 |] in loop t \subsection{Oformula vers COQ reifié } let reified_of_atom env i = try Hashtbl.find env.real_indices i with Not_found -> Printf.printf "Atome %d non trouvé\n" i; Hashtbl.iter (fun k v -> Printf.printf "%d -> %d\n" k v) env.real_indices; raise Not_found let rec reified_of_formula env = function | Oplus (t1,t2) -> app coq_t_plus [| reified_of_formula env t1; reified_of_formula env t2 |] | Oopp t -> app coq_t_opp [| reified_of_formula env t |] | Omult(t1,t2) -> app coq_t_mult [| reified_of_formula env t1; reified_of_formula env t2 |] | Oint v -> app coq_t_int [| Z.mk v |] | Oufo t -> reified_of_formula env t | Oatom i -> app coq_t_var [| mk_nat (reified_of_atom env i) |] | Ominus(t1,t2) -> app coq_t_minus [| reified_of_formula env t1; reified_of_formula env t2 |] let reified_of_formula env f = try reified_of_formula env f with reraise -> oprint stderr f; raise reraise let rec reified_of_proposition env = function Pequa (_,{ e_comp=Eq; e_left=t1; e_right=t2 }) -> app coq_p_eq [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa (_,{ e_comp=Leq; e_left=t1; e_right=t2 }) -> app coq_p_leq [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa(_,{ e_comp=Geq; e_left=t1; e_right=t2 }) -> app coq_p_geq [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa(_,{ e_comp=Gt; e_left=t1; e_right=t2 }) -> app coq_p_gt [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa(_,{ e_comp=Lt; e_left=t1; e_right=t2 }) -> app coq_p_lt [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa(_,{ e_comp=Neq; e_left=t1; e_right=t2 }) -> app coq_p_neq [| reified_of_formula env t1; reified_of_formula env t2 |] | Ptrue -> Lazy.force coq_p_true | Pfalse -> Lazy.force coq_p_false | Pnot t -> app coq_p_not [| reified_of_proposition env t |] | Por (_,t1,t2) -> app coq_p_or [| reified_of_proposition env t1; reified_of_proposition env t2 |] | Pand(_,t1,t2) -> app coq_p_and [| reified_of_proposition env t1; reified_of_proposition env t2 |] | Pimp(_,t1,t2) -> app coq_p_imp [| reified_of_proposition env t1; reified_of_proposition env t2 |] | Pprop t -> app coq_p_prop [| mk_nat (add_prop env t) |] let reified_of_proposition env f = try reified_of_proposition env f with reraise -> pprint stderr f; raise reraise \subsection{Omega vers COQ réifié } let reified_of_omega env body constant = let coeff_constant = app coq_t_int [| Z.mk constant |] in let mk_coeff {c=c; v=v} t = let coef = app coq_t_mult [| reified_of_formula env (unintern_omega env v); app coq_t_int [| Z.mk c |] |] in app coq_t_plus [|coef; t |] in List.fold_right mk_coeff body coeff_constant let reified_of_omega env body c = try reified_of_omega env body c with reraise -> display_eq display_omega_var (body,c); raise reraise \section{Opérations sur les équations } Ces fonctions préparent les traces utilisées par la tactique réfléchie pour faire des opérations de normalisation sur les équations . Ces fonctions préparent les traces utilisées par la tactique réfléchie pour faire des opérations de normalisation sur les équations. *) \subsection{Extractions des variables d'une équation } (* Extraction des variables d'une équation. *) Chaque fonction retourne une liste triée sans redondance let (@@) = List.merge_uniq compare let rec vars_of_formula = function | Oint _ -> [] | Oplus (e1,e2) -> (vars_of_formula e1) @@ (vars_of_formula e2) | Omult (e1,e2) -> (vars_of_formula e1) @@ (vars_of_formula e2) | Ominus (e1,e2) -> (vars_of_formula e1) @@ (vars_of_formula e2) | Oopp e -> vars_of_formula e | Oatom i -> [i] | Oufo _ -> [] let rec vars_of_equations = function | [] -> [] | e::l -> (vars_of_formula e.e_left) @@ (vars_of_formula e.e_right) @@ (vars_of_equations l) let rec vars_of_prop = function | Pequa(_,e) -> vars_of_equations [e] | Pnot p -> vars_of_prop p | Por(_,p1,p2) -> (vars_of_prop p1) @@ (vars_of_prop p2) | Pand(_,p1,p2) -> (vars_of_prop p1) @@ (vars_of_prop p2) | Pimp(_,p1,p2) -> (vars_of_prop p1) @@ (vars_of_prop p2) | Pprop _ | Ptrue | Pfalse -> [] (* \subsection{Multiplication par un scalaire} *) let rec scalar n = function Oplus(t1,t2) -> let tac1,t1' = scalar n t1 and tac2,t2' = scalar n t2 in do_list [Lazy.force coq_c_mult_plus_distr; do_both tac1 tac2], Oplus(t1',t2') | Oopp t -> do_list [Lazy.force coq_c_mult_opp_left], Omult(t,Oint(Bigint.neg n)) | Omult(t1,Oint x) -> do_list [Lazy.force coq_c_mult_assoc_reduced], Omult(t1,Oint (n*x)) | Omult(t1,t2) -> CErrors.error "Omega: Can't solve a goal with non-linear products" | (Oatom _ as t) -> do_list [], Omult(t,Oint n) | Oint i -> do_list [Lazy.force coq_c_reduce],Oint(n*i) | (Oufo _ as t)-> do_list [], Oufo (Omult(t,Oint n)) | Ominus _ -> failwith "scalar minus" (* \subsection{Propagation de l'inversion} *) let rec negate = function Oplus(t1,t2) -> let tac1,t1' = negate t1 and tac2,t2' = negate t2 in do_list [Lazy.force coq_c_opp_plus ; (do_both tac1 tac2)], Oplus(t1',t2') | Oopp t -> do_list [Lazy.force coq_c_opp_opp], t | Omult(t1,Oint x) -> do_list [Lazy.force coq_c_opp_mult_r], Omult(t1,Oint (Bigint.neg x)) | Omult(t1,t2) -> CErrors.error "Omega: Can't solve a goal with non-linear products" | (Oatom _ as t) -> do_list [Lazy.force coq_c_opp_one], Omult(t,Oint(negone)) | Oint i -> do_list [Lazy.force coq_c_reduce] ,Oint(Bigint.neg i) | Oufo c -> do_list [], Oufo (Oopp c) | Ominus _ -> failwith "negate minus" let norm l = (List.length l) (* \subsection{Mélange (fusion) de deux équations} *) (* \subsubsection{Version avec coefficients} *) let shuffle_path k1 e1 k2 e2 = let rec loop = function (({c=c1;v=v1}::l1) as l1'), (({c=c2;v=v2}::l2) as l2') -> if Int.equal v1 v2 then if Bigint.equal (k1 * c1 + k2 * c2) zero then ( Lazy.force coq_f_cancel :: loop (l1,l2)) else ( Lazy.force coq_f_equal :: loop (l1,l2) ) else if v1 > v2 then ( Lazy.force coq_f_left :: loop(l1,l2')) else ( Lazy.force coq_f_right :: loop(l1',l2)) | ({c=c1;v=v1}::l1), [] -> Lazy.force coq_f_left :: loop(l1,[]) | [],({c=c2;v=v2}::l2) -> Lazy.force coq_f_right :: loop([],l2) | [],[] -> flush stdout; [] in mk_shuffle_list (loop (e1,e2)) (* \subsubsection{Version sans coefficients} *) let rec shuffle env (t1,t2) = match t1,t2 with Oplus(l1,r1), Oplus(l2,r2) -> if weight env l1 > weight env l2 then let l_action,t' = shuffle env (r1,t2) in do_list [Lazy.force coq_c_plus_assoc_r;do_right l_action], Oplus(l1,t') else let l_action,t' = shuffle env (t1,r2) in do_list [Lazy.force coq_c_plus_permute;do_right l_action], Oplus(l2,t') | Oplus(l1,r1), t2 -> if weight env l1 > weight env t2 then let (l_action,t') = shuffle env (r1,t2) in do_list [Lazy.force coq_c_plus_assoc_r;do_right l_action],Oplus(l1, t') else do_list [Lazy.force coq_c_plus_comm], Oplus(t2,t1) | t1,Oplus(l2,r2) -> if weight env l2 > weight env t1 then let (l_action,t') = shuffle env (t1,r2) in do_list [Lazy.force coq_c_plus_permute;do_right l_action], Oplus(l2,t') else do_list [],Oplus(t1,t2) | Oint t1,Oint t2 -> do_list [Lazy.force coq_c_reduce], Oint(t1+t2) | t1,t2 -> if weight env t1 < weight env t2 then do_list [Lazy.force coq_c_plus_comm], Oplus(t2,t1) else do_list [],Oplus(t1,t2) \subsection{Fusion avec réduction } let shrink_pair f1 f2 = begin match f1,f2 with Oatom v,Oatom _ -> Lazy.force coq_c_red1, Omult(Oatom v,Oint two) | Oatom v, Omult(_,c2) -> Lazy.force coq_c_red2, Omult(Oatom v,Oplus(c2,Oint one)) | Omult (v1,c1),Oatom v -> Lazy.force coq_c_red3, Omult(Oatom v,Oplus(c1,Oint one)) | Omult (Oatom v,c1),Omult (v2,c2) -> Lazy.force coq_c_red4, Omult(Oatom v,Oplus(c1,c2)) | t1,t2 -> oprint stdout t1; print_newline (); oprint stdout t2; print_newline (); flush Pervasives.stdout; CErrors.error "shrink.1" end (* \subsection{Calcul d'une sous formule constante} *) let reduce_factor = function Oatom v -> let r = Omult(Oatom v,Oint one) in [Lazy.force coq_c_red0],r | Omult(Oatom v,Oint n) as f -> [],f | Omult(Oatom v,c) -> let rec compute = function Oint n -> n | Oplus(t1,t2) -> compute t1 + compute t2 | _ -> CErrors.error "condense.1" in [Lazy.force coq_c_reduce], Omult(Oatom v,Oint(compute c)) | t -> CErrors.error "reduce_factor.1" (* \subsection{Réordonnancement} *) let rec condense env = function Oplus(f1,(Oplus(f2,r) as t)) -> if Int.equal (weight env f1) (weight env f2) then begin let shrink_tac,t = shrink_pair f1 f2 in let assoc_tac = Lazy.force coq_c_plus_assoc_l in let tac_list,t' = condense env (Oplus(t,r)) in assoc_tac :: do_left (do_list [shrink_tac]) :: tac_list, t' end else begin let tac,f = reduce_factor f1 in let tac',t' = condense env t in [do_both (do_list tac) (do_list tac')], Oplus(f,t') end | Oplus(f1,Oint n) -> let tac,f1' = reduce_factor f1 in [do_left (do_list tac)],Oplus(f1',Oint n) | Oplus(f1,f2) -> if Int.equal (weight env f1) (weight env f2) then begin let tac_shrink,t = shrink_pair f1 f2 in let tac,t' = condense env t in tac_shrink :: tac,t' end else begin let tac,f = reduce_factor f1 in let tac',t' = condense env f2 in [do_both (do_list tac) (do_list tac')],Oplus(f,t') end | (Oint _ as t)-> [],t | t -> let tac,t' = reduce_factor t in let final = Oplus(t',Oint zero) in tac @ [Lazy.force coq_c_red6], final (* \subsection{Elimination des zéros} *) let rec clear_zero = function Oplus(Omult(Oatom v,Oint n),r) when Bigint.equal n zero -> let tac',t = clear_zero r in Lazy.force coq_c_red5 :: tac',t | Oplus(f,r) -> let tac,t = clear_zero r in (if List.is_empty tac then [] else [do_right (do_list tac)]),Oplus(f,t) | t -> [],t;; (* \subsection{Transformation des hypothèses} *) let rec reduce env = function Oplus(t1,t2) -> let t1', trace1 = reduce env t1 in let t2', trace2 = reduce env t2 in let trace3,t' = shuffle env (t1',t2') in t', do_list [do_both trace1 trace2; trace3] | Ominus(t1,t2) -> let t,trace = reduce env (Oplus(t1, Oopp t2)) in t, do_list [Lazy.force coq_c_minus; trace] | Omult(t1,t2) as t -> let t1', trace1 = reduce env t1 in let t2', trace2 = reduce env t2 in begin match t1',t2' with | (_, Oint n) -> let tac,t' = scalar n t1' in t', do_list [do_both trace1 trace2; tac] | (Oint n,_) -> let tac,t' = scalar n t2' in t', do_list [do_both trace1 trace2; Lazy.force coq_c_mult_comm; tac] | _ -> Oufo t, Lazy.force coq_c_nop end | Oopp t -> let t',trace = reduce env t in let trace',t'' = negate t' in t'', do_list [do_left trace; trace'] | (Oint _ | Oatom _ | Oufo _) as t -> t, Lazy.force coq_c_nop let normalize_linear_term env t = let t1,trace1 = reduce env t in let trace2,t2 = condense env t1 in let trace3,t3 = clear_zero t2 in do_list [trace1; do_list trace2; do_list trace3], t3 Cette fonction reproduit très exactement le comportement de [ p_invert ] let negate_oper = function Eq -> Neq | Neq -> Eq | Leq -> Gt | Geq -> Lt | Lt -> Geq | Gt -> Leq let normalize_equation env (negated,depends,origin,path) (oper,t1,t2) = let mk_step t1 t2 f kind = let t = f t1 t2 in let trace, oterm = normalize_linear_term env t in let equa = omega_of_oformula env kind oterm in { e_comp = oper; e_left = t1; e_right = t2; e_negated = negated; e_depends = depends; e_origin = { o_hyp = origin; o_path = List.rev path }; e_trace = trace; e_omega = equa } in try match (if negated then (negate_oper oper) else oper) with | Eq -> mk_step t1 t2 (fun o1 o2 -> Oplus (o1,Oopp o2)) EQUA | Neq -> mk_step t1 t2 (fun o1 o2 -> Oplus (o1,Oopp o2)) DISE | Leq -> mk_step t1 t2 (fun o1 o2 -> Oplus (o2,Oopp o1)) INEQ | Geq -> mk_step t1 t2 (fun o1 o2 -> Oplus (o1,Oopp o2)) INEQ | Lt -> mk_step t1 t2 (fun o1 o2 -> Oplus (Oplus(o2,Oint negone),Oopp o1)) INEQ | Gt -> mk_step t1 t2 (fun o1 o2 -> Oplus (Oplus(o1,Oint negone),Oopp o2)) INEQ with e when Logic.catchable_exception e -> raise e (* \section{Compilation des hypothèses} *) let rec oformula_of_constr env t = match Z.parse_term t with | Tplus (t1,t2) -> binop env (fun x y -> Oplus(x,y)) t1 t2 | Tminus (t1,t2) -> binop env (fun x y -> Ominus(x,y)) t1 t2 | Tmult (t1,t2) when Z.is_scalar t1 || Z.is_scalar t2 -> binop env (fun x y -> Omult(x,y)) t1 t2 | Topp t -> Oopp(oformula_of_constr env t) | Tsucc t -> Oplus(oformula_of_constr env t, Oint one) | Tnum n -> Oint n | _ -> Oatom (add_reified_atom t env) and binop env c t1 t2 = let t1' = oformula_of_constr env t1 in let t2' = oformula_of_constr env t2 in c t1' t2' and binprop env (neg2,depends,origin,path) add_to_depends neg1 gl c t1 t2 = let i = new_connector_id env in let depends1 = if add_to_depends then Left i::depends else depends in let depends2 = if add_to_depends then Right i::depends else depends in if add_to_depends then Hashtbl.add env.constructors i {o_hyp = origin; o_path = List.rev path}; let t1' = oproposition_of_constr env (neg1,depends1,origin,O_left::path) gl t1 in let t2' = oproposition_of_constr env (neg2,depends2,origin,O_right::path) gl t2 in On numérote le connecteur dans l'environnement . c i t1' t2' and mk_equation env ctxt c connector t1 t2 = let t1' = oformula_of_constr env t1 in let t2' = oformula_of_constr env t2 in (* On ajoute l'equation dans l'environnement. *) let omega = normalize_equation env ctxt (connector,t1',t2') in add_equation env omega; Pequa (c,omega) and oproposition_of_constr env ((negated,depends,origin,path) as ctxt) gl c = match Z.parse_rel gl c with | Req (t1,t2) -> mk_equation env ctxt c Eq t1 t2 | Rne (t1,t2) -> mk_equation env ctxt c Neq t1 t2 | Rle (t1,t2) -> mk_equation env ctxt c Leq t1 t2 | Rlt (t1,t2) -> mk_equation env ctxt c Lt t1 t2 | Rge (t1,t2) -> mk_equation env ctxt c Geq t1 t2 | Rgt (t1,t2) -> mk_equation env ctxt c Gt t1 t2 | Rtrue -> Ptrue | Rfalse -> Pfalse | Rnot t -> let t' = oproposition_of_constr env (not negated, depends, origin,(O_mono::path)) gl t in Pnot t' | Ror (t1,t2) -> binprop env ctxt (not negated) negated gl (fun i x y -> Por(i,x,y)) t1 t2 | Rand (t1,t2) -> binprop env ctxt negated negated gl (fun i x y -> Pand(i,x,y)) t1 t2 | Rimp (t1,t2) -> binprop env ctxt (not negated) (not negated) gl (fun i x y -> Pimp(i,x,y)) t1 t2 | Riff (t1,t2) -> binprop env ctxt negated negated gl (fun i x y -> Pand(i,x,y)) (Term.mkArrow t1 t2) (Term.mkArrow t2 t1) | _ -> Pprop c Destructuration des hypothèses et de la conclusion let reify_gl env gl = let concl = Tacmach.pf_concl gl in let t_concl = Pnot (oproposition_of_constr env (true,[],id_concl,[O_mono]) gl concl) in if !debug then begin Printf.printf "REIFED PROBLEM\n\n"; Printf.printf " CONCL: "; pprint stdout t_concl; Printf.printf "\n" end; let rec loop = function (i,t) :: lhyps -> let t' = oproposition_of_constr env (false,[],i,[]) gl t in if !debug then begin Printf.printf " %s: " (Names.Id.to_string i); pprint stdout t'; Printf.printf "\n" end; (i,t') :: loop lhyps | [] -> if !debug then print_env_reification env; [] in let t_lhyps = loop (Tacmach.pf_hyps_types gl) in (id_concl,t_concl) :: t_lhyps let rec destructurate_pos_hyp orig list_equations list_depends = function | Pequa (_,e) -> [e :: list_equations] | Ptrue | Pfalse | Pprop _ -> [list_equations] | Pnot t -> destructurate_neg_hyp orig list_equations list_depends t | Por (i,t1,t2) -> let s1 = destructurate_pos_hyp orig list_equations (i::list_depends) t1 in let s2 = destructurate_pos_hyp orig list_equations (i::list_depends) t2 in s1 @ s2 | Pand(i,t1,t2) -> let list_s1 = destructurate_pos_hyp orig list_equations (list_depends) t1 in let rec loop = function le1 :: ll -> destructurate_pos_hyp orig le1 list_depends t2 @ loop ll | [] -> [] in loop list_s1 | Pimp(i,t1,t2) -> let s1 = destructurate_neg_hyp orig list_equations (i::list_depends) t1 in let s2 = destructurate_pos_hyp orig list_equations (i::list_depends) t2 in s1 @ s2 and destructurate_neg_hyp orig list_equations list_depends = function | Pequa (_,e) -> [e :: list_equations] | Ptrue | Pfalse | Pprop _ -> [list_equations] | Pnot t -> destructurate_pos_hyp orig list_equations list_depends t | Pand (i,t1,t2) -> let s1 = destructurate_neg_hyp orig list_equations (i::list_depends) t1 in let s2 = destructurate_neg_hyp orig list_equations (i::list_depends) t2 in s1 @ s2 | Por(_,t1,t2) -> let list_s1 = destructurate_neg_hyp orig list_equations list_depends t1 in let rec loop = function le1 :: ll -> destructurate_neg_hyp orig le1 list_depends t2 @ loop ll | [] -> [] in loop list_s1 | Pimp(_,t1,t2) -> let list_s1 = destructurate_pos_hyp orig list_equations list_depends t1 in let rec loop = function le1 :: ll -> destructurate_neg_hyp orig le1 list_depends t2 @ loop ll | [] -> [] in loop list_s1 let destructurate_hyps syst = let rec loop = function (i,t) :: l -> let l_syst1 = destructurate_pos_hyp i [] [] t in let l_syst2 = loop l in List.cartesian (@) l_syst1 l_syst2 | [] -> [[]] in loop syst (* \subsection{Affichage d'un système d'équation} *) Affichage des dépendances de système let display_depend = function Left i -> Printf.printf " L%d" i | Right i -> Printf.printf " R%d" i let display_systems syst_list = let display_omega om_e = Printf.printf " E%d : %a %s 0\n" om_e.id (fun _ -> display_eq display_omega_var) (om_e.body, om_e.constant) (operator_of_eq om_e.kind) in let display_equation oformula_eq = pprint stdout (Pequa (Lazy.force coq_c_nop,oformula_eq)); print_newline (); display_omega oformula_eq.e_omega; Printf.printf " Depends on:"; List.iter display_depend oformula_eq.e_depends; Printf.printf "\n Path: %s" (String.concat "" (List.map (function O_left -> "L" | O_right -> "R" | O_mono -> "M") oformula_eq.e_origin.o_path)); Printf.printf "\n Origin: %s (negated : %s)\n\n" (Names.Id.to_string oformula_eq.e_origin.o_hyp) (if oformula_eq.e_negated then "yes" else "no") in let display_system syst = Printf.printf "=SYSTEM===================================\n"; List.iter display_equation syst in List.iter display_system syst_list Extraction des prédicats utilisées dans une trace . calcul des hypothèses calcul des hypothèses *) let rec hyps_used_in_trace = function | act :: l -> begin match act with | HYP e -> [e.id] @@ (hyps_used_in_trace l) | SPLIT_INEQ (_,(_,act1),(_,act2)) -> hyps_used_in_trace act1 @@ hyps_used_in_trace act2 | _ -> hyps_used_in_trace l end | [] -> [] Extraction des variables déclarées dans une équation . de les déclarer dans l'environnement de la procédure réflexive et les créations de variable au vol de les déclarer dans l'environnement de la procédure réflexive et éviter les créations de variable au vol *) let rec variable_stated_in_trace = function | act :: l -> begin match act with | STATE action -> i nlle_equa : afine , def : afine , eq_orig : afine , i i : int , var : int i action :: variable_stated_in_trace l | SPLIT_INEQ (_,(_,act1),(_,act2)) -> variable_stated_in_trace act1 @ variable_stated_in_trace act2 | _ -> variable_stated_in_trace l end | [] -> [] ;; let add_stated_equations env tree = (* Il faut trier les variables par ordre d'introduction pour ne pas risquer de définir dans le mauvais ordre *) let stated_equations = let cmpvar x y = Pervasives.(-) x.st_var y.st_var in let rec loop = function | Tree(_,t1,t2) -> List.merge cmpvar (loop t1) (loop t2) | Leaf s -> List.sort cmpvar (variable_stated_in_trace s.s_trace) in loop tree in let add_env st = On retransforme la définition de v en formule let v_def = oformula_of_omega env st.st_def in que si l'ordre de création des variables n'est pas respecté , * ca va planter * ca va planter *) let coq_v = coq_of_formula env v_def in let v = add_reified_atom coq_v env in (* Le terme qu'il va falloir introduire *) let term_to_generalize = app coq_refl_equal [|Lazy.force Z.typ; coq_v|] in sa représentation forme d'équation mais non réifié car on n'a pas * l'environnement pour le faire correctement * l'environnement pour le faire correctement *) let term_to_reify = (v_def,Oatom v) in enregistre le lien entre la variable omega et la variable Coq intern_omega_force env (Oatom v) st.st_var; (v, term_to_generalize,term_to_reify,st.st_def.id) in List.map add_env stated_equations Calcule la liste des éclatements à réaliser sur les hypothèses nécessaires pour extraire une liste d'équations donnée nécessaires pour extraire une liste d'équations donnée *) PL : experimentally , the result order of the following function seems _ very _ crucial for efficiency . No idea why . Do not remove the List.rev or modify the current semantics of Util.List.union ( some elements of first arg , then second arg ) , unless you know what you 're doing . _very_ crucial for efficiency. No idea why. Do not remove the List.rev or modify the current semantics of Util.List.union (some elements of first arg, then second arg), unless you know what you're doing. *) let rec get_eclatement env = function i :: r -> let l = try (get_equation env i).e_depends with Not_found -> [] in List.union Pervasives.(=) (List.rev l) (get_eclatement env r) | [] -> [] let select_smaller l = let comp (_,x) (_,y) = Pervasives.(-) (List.length x) (List.length y) in try List.hd (List.sort comp l) with Failure _ -> failwith "select_smaller" let filter_compatible_systems required systems = let rec select = function (x::l) -> if List.mem x required then select l else if List.mem (barre x) required then raise Exit else x :: select l | [] -> [] in List.map_filter (function (sol, splits) -> try Some (sol, select splits) with Exit -> None) systems let rec equas_of_solution_tree = function Tree(_,t1,t2) -> (equas_of_solution_tree t1)@@(equas_of_solution_tree t2) | Leaf s -> s.s_equa_deps [ really_useful_prop ] pushes useless props in a new Pprop variable Things get shorter , but may also get wrong , since a Prop is considered to be undecidable in ReflOmegaCore.concl_to_hyp , whereas for instance Pfalse is decidable . So should not be used on conclusion ( ? ? ) to be undecidable in ReflOmegaCore.concl_to_hyp, whereas for instance Pfalse is decidable. So should not be used on conclusion (??) *) let really_useful_prop l_equa c = let rec real_of = function Pequa(t,_) -> t | Ptrue -> app coq_True [||] | Pfalse -> app coq_False [||] | Pnot t1 -> app coq_not [|real_of t1|] | Por(_,t1,t2) -> app coq_or [|real_of t1; real_of t2|] | Pand(_,t1,t2) -> app coq_and [|real_of t1; real_of t2|] Attention : implications sur le lifting des variables à comprendre ! | Pimp(_,t1,t2) -> Term.mkArrow (real_of t1) (real_of t2) | Pprop t -> t in let rec loop c = match c with Pequa(_,e) -> if List.mem e.e_omega.id l_equa then Some c else None | Ptrue -> None | Pfalse -> None | Pnot t1 -> begin match loop t1 with None -> None | Some t1' -> Some (Pnot t1') end | Por(i,t1,t2) -> binop (fun (t1,t2) -> Por(i,t1,t2)) t1 t2 | Pand(i,t1,t2) -> binop (fun (t1,t2) -> Pand(i,t1,t2)) t1 t2 | Pimp(i,t1,t2) -> binop (fun (t1,t2) -> Pimp(i,t1,t2)) t1 t2 | Pprop t -> None and binop f t1 t2 = begin match loop t1, loop t2 with None, None -> None | Some t1',Some t2' -> Some (f(t1',t2')) | Some t1',None -> Some (f(t1',Pprop (real_of t2))) | None,Some t2' -> Some (f(Pprop (real_of t1),t2')) end in match loop c with None -> Pprop (real_of c) | Some t -> t let rec display_solution_tree ch = function Leaf t -> output_string ch (Printf.sprintf "%d[%s]" t.s_index (String.concat " " (List.map string_of_int t.s_equa_deps))) | Tree(i,t1,t2) -> Printf.fprintf ch "S%d(%a,%a)" i display_solution_tree t1 display_solution_tree t2 let rec solve_with_constraints all_solutions path = let rec build_tree sol buf = function [] -> Leaf sol | (Left i :: remainder) -> Tree(i, build_tree sol (Left i :: buf) remainder, solve_with_constraints all_solutions (List.rev(Right i :: buf))) | (Right i :: remainder) -> Tree(i, solve_with_constraints all_solutions (List.rev (Left i :: buf)), build_tree sol (Right i :: buf) remainder) in let weighted = filter_compatible_systems path all_solutions in let (winner_sol,winner_deps) = try select_smaller weighted with reraise -> Printf.printf "%d - %d\n" (List.length weighted) (List.length all_solutions); List.iter display_depend path; raise reraise in build_tree winner_sol (List.rev path) winner_deps let find_path {o_hyp=id;o_path=p} env = let rec loop_path = function ([],l) -> Some l | (x1::l1,x2::l2) when occ_step_eq x1 x2 -> loop_path (l1,l2) | _ -> None in let rec loop_id i = function CCHyp{o_hyp=id';o_path=p'} :: l when Names.Id.equal id id' -> begin match loop_path (p',p) with Some r -> i,r | None -> loop_id (succ i) l end | _ :: l -> loop_id (succ i) l | [] -> failwith "find_path" in loop_id 0 env let mk_direction_list l = let trans = function O_left -> coq_d_left | O_right -> coq_d_right | O_mono -> coq_d_mono in mk_list (Lazy.force coq_direction) (List.map (fun d-> Lazy.force(trans d)) l) (* \section{Rejouer l'historique} *) let get_hyp env_hyp i = try List.index0 Pervasives.(=) (CCEqua i) env_hyp with Not_found -> failwith (Printf.sprintf "get_hyp %d" i) let replay_history env env_hyp = let rec loop env_hyp t = match t with | CONTRADICTION (e1,e2) :: l -> let trace = mk_nat (List.length e1.body) in mkApp (Lazy.force coq_s_contradiction, [| trace ; mk_nat (get_hyp env_hyp e1.id); mk_nat (get_hyp env_hyp e2.id) |]) | DIVIDE_AND_APPROX (e1,e2,k,d) :: l -> mkApp (Lazy.force coq_s_div_approx, [| Z.mk k; Z.mk d; reified_of_omega env e2.body e2.constant; mk_nat (List.length e2.body); loop env_hyp l; mk_nat (get_hyp env_hyp e1.id) |]) | NOT_EXACT_DIVIDE (e1,k) :: l -> let e2_constant = floor_div e1.constant k in let d = e1.constant - e2_constant * k in let e2_body = map_eq_linear (fun c -> c / k) e1.body in mkApp (Lazy.force coq_s_not_exact_divide, [|Z.mk k; Z.mk d; reified_of_omega env e2_body e2_constant; mk_nat (List.length e2_body); mk_nat (get_hyp env_hyp e1.id)|]) | EXACT_DIVIDE (e1,k) :: l -> let e2_body = map_eq_linear (fun c -> c / k) e1.body in let e2_constant = floor_div e1.constant k in mkApp (Lazy.force coq_s_exact_divide, [|Z.mk k; reified_of_omega env e2_body e2_constant; mk_nat (List.length e2_body); loop env_hyp l; mk_nat (get_hyp env_hyp e1.id)|]) | (MERGE_EQ(e3,e1,e2)) :: l -> let n1 = get_hyp env_hyp e1.id and n2 = get_hyp env_hyp e2 in mkApp (Lazy.force coq_s_merge_eq, [| mk_nat (List.length e1.body); mk_nat n1; mk_nat n2; loop (CCEqua e3:: env_hyp) l |]) | SUM(e3,(k1,e1),(k2,e2)) :: l -> let n1 = get_hyp env_hyp e1.id and n2 = get_hyp env_hyp e2.id in let trace = shuffle_path k1 e1.body k2 e2.body in mkApp (Lazy.force coq_s_sum, [| Z.mk k1; mk_nat n1; Z.mk k2; mk_nat n2; trace; (loop (CCEqua e3 :: env_hyp) l) |]) | CONSTANT_NOT_NUL(e,k) :: l -> mkApp (Lazy.force coq_s_constant_not_nul, [| mk_nat (get_hyp env_hyp e) |]) | CONSTANT_NEG(e,k) :: l -> mkApp (Lazy.force coq_s_constant_neg, [| mk_nat (get_hyp env_hyp e) |]) | STATE {st_new_eq=new_eq; st_def =def; st_orig=orig; st_coef=m; st_var=sigma } :: l -> let n1 = get_hyp env_hyp orig.id and n2 = get_hyp env_hyp def.id in let v = unintern_omega env sigma in let o_def = oformula_of_omega env def in let o_orig = oformula_of_omega env orig in let body = Oplus (o_orig,Omult (Oplus (Oopp v,o_def), Oint m)) in let trace,_ = normalize_linear_term env body in mkApp (Lazy.force coq_s_state, [| Z.mk m; trace; mk_nat n1; mk_nat n2; loop (CCEqua new_eq.id :: env_hyp) l |]) | HYP _ :: l -> loop env_hyp l | CONSTANT_NUL e :: l -> mkApp (Lazy.force coq_s_constant_nul, [| mk_nat (get_hyp env_hyp e) |]) | NEGATE_CONTRADICT(e1,e2,true) :: l -> mkApp (Lazy.force coq_s_negate_contradict, [| mk_nat (get_hyp env_hyp e1.id); mk_nat (get_hyp env_hyp e2.id) |]) | NEGATE_CONTRADICT(e1,e2,false) :: l -> mkApp (Lazy.force coq_s_negate_contradict_inv, [| mk_nat (List.length e2.body); mk_nat (get_hyp env_hyp e1.id); mk_nat (get_hyp env_hyp e2.id) |]) | SPLIT_INEQ(e,(e1,l1),(e2,l2)) :: l -> let i = get_hyp env_hyp e.id in let r1 = loop (CCEqua e1 :: env_hyp) l1 in let r2 = loop (CCEqua e2 :: env_hyp) l2 in mkApp (Lazy.force coq_s_split_ineq, [| mk_nat (List.length e.body); mk_nat i; r1 ; r2 |]) | (FORGET_C _ | FORGET _ | FORGET_I _) :: l -> loop env_hyp l | (WEAKEN _ ) :: l -> failwith "not_treated" | [] -> failwith "no contradiction" in loop env_hyp let rec decompose_tree env ctxt = function Tree(i,left,right) -> let org = try Hashtbl.find env.constructors i with Not_found -> failwith (Printf.sprintf "Cannot find constructor %d" i) in let (index,path) = find_path org ctxt in let left_hyp = CCHyp{o_hyp=org.o_hyp;o_path=org.o_path @ [O_left]} in let right_hyp = CCHyp{o_hyp=org.o_hyp;o_path=org.o_path @ [O_right]} in app coq_e_split [| mk_nat index; mk_direction_list path; decompose_tree env (left_hyp::ctxt) left; decompose_tree env (right_hyp::ctxt) right |] | Leaf s -> decompose_tree_hyps s.s_trace env ctxt s.s_equa_deps and decompose_tree_hyps trace env ctxt = function [] -> app coq_e_solve [| replay_history env ctxt trace |] | (i::l) -> let equation = try Hashtbl.find env.equations i with Not_found -> failwith (Printf.sprintf "Cannot find equation %d" i) in let (index,path) = find_path equation.e_origin ctxt in let full_path = if equation.e_negated then path @ [O_mono] else path in let cont = decompose_tree_hyps trace env (CCEqua equation.e_omega.id :: ctxt) l in app coq_e_extract [|mk_nat index; mk_direction_list full_path; cont |] (* \section{La fonction principale} *) Cette fonction construit la trace pour la procédure de décision réflexive . A partir des résultats de l'extraction des systèmes , elle lance la résolution par Omega , puis l'extraction d'un ensemble minimal de solutions permettant la résolution globale du système et enfin construit la trace qui permet de faire rejouer cette solution par la tactique réflexive . trace pour la procédure de décision réflexive. A partir des résultats de l'extraction des systèmes, elle lance la résolution par Omega, puis l'extraction d'un ensemble minimal de solutions permettant la résolution globale du système et enfin construit la trace qui permet de faire rejouer cette solution par la tactique réflexive. *) let resolution env full_reified_goal systems_list = let num = ref 0 in let solve_system list_eq = let index = !num in let system = List.map (fun eq -> eq.e_omega) list_eq in let trace = simplify_strong (new_omega_eq,new_omega_var,display_omega_var) system in (* calcule les hypotheses utilisées pour la solution *) let vars = hyps_used_in_trace trace in let splits = get_eclatement env vars in if !debug then begin Printf.printf "SYSTEME %d\n" index; display_action display_omega_var trace; print_string "\n Depend :"; List.iter (fun i -> Printf.printf " %d" i) vars; print_string "\n Split points :"; List.iter display_depend splits; Printf.printf "\n------------------------------------\n" end; incr num; {s_index = index; s_trace = trace; s_equa_deps = vars}, splits in if !debug then Printf.printf "\n====================================\n"; let all_solutions = List.map solve_system systems_list in let solution_tree = solve_with_constraints all_solutions [] in if !debug then begin display_solution_tree stdout solution_tree; print_newline() end; (* calcule la liste de toutes les hypothèses utilisées dans l'arbre de solution *) let useful_equa_id = equas_of_solution_tree solution_tree in (* recupere explicitement ces equations *) let equations = List.map (get_equation env) useful_equa_id in let l_hyps' = List.uniquize (List.map (fun e -> e.e_origin.o_hyp) equations) in let l_hyps = id_concl :: List.remove Names.Id.equal id_concl l_hyps' in let useful_hyps = List.map (fun id -> List.assoc_f Names.Id.equal id full_reified_goal) l_hyps in let useful_vars = let really_useful_vars = vars_of_equations equations in let concl_vars = vars_of_prop (List.assoc_f Names.Id.equal id_concl full_reified_goal) in really_useful_vars @@ concl_vars in (* variables a introduire *) let to_introduce = add_stated_equations env solution_tree in let stated_vars = List.map (fun (v,_,_,_) -> v) to_introduce in let l_generalize_arg = List.map (fun (_,t,_,_) -> t) to_introduce in let hyp_stated_vars = List.map (fun (_,_,_,id) -> CCEqua id) to_introduce in L'environnement de base se construit en : - les variables des équations utiles ( et de la conclusion ) - les nouvelles variables declarées durant les preuves - les variables des équations utiles (et de la conclusion) - les nouvelles variables declarées durant les preuves *) let all_vars_env = useful_vars @ stated_vars in let basic_env = let rec loop i = function var :: l -> let t = get_reified_atom env var in Hashtbl.add env.real_indices var i; t :: loop (succ i) l | [] -> [] in loop 0 all_vars_env in let env_terms_reified = mk_list (Lazy.force Z.typ) basic_env in On peut maintenant but : env est a jour let l_reified_stated = List.map (fun (_,_,(l,r),_) -> app coq_p_eq [| reified_of_formula env l; reified_of_formula env r |]) to_introduce in let reified_concl = match useful_hyps with (Pnot p) :: _ -> reified_of_proposition env p | _ -> reified_of_proposition env Pfalse in let l_reified_terms = (List.map (fun p -> reified_of_proposition env (really_useful_prop useful_equa_id p)) (List.tl useful_hyps)) in let env_props_reified = mk_plist env.props in let reified_goal = mk_list (Lazy.force coq_proposition) (l_reified_stated @ l_reified_terms) in let reified = app coq_interp_sequent [| reified_concl;env_props_reified;env_terms_reified;reified_goal|] in let normalize_equation e = let rec loop = function [] -> app (if e.e_negated then coq_p_invert else coq_p_step) [| e.e_trace |] | ((O_left | O_mono) :: l) -> app coq_p_left [| loop l |] | (O_right :: l) -> app coq_p_right [| loop l |] in let correct_index = let i = List.index0 Names.Id.equal e.e_origin.o_hyp l_hyps in PL : it seems that additionally introduced hyps are in the way during normalization , hence this index shifting ... normalization, hence this index shifting... *) if Int.equal i 0 then 0 else Pervasives.(+) i (List.length to_introduce) in app coq_pair_step [| mk_nat correct_index; loop e.e_origin.o_path |] in let normalization_trace = mk_list (Lazy.force coq_h_step) (List.map normalize_equation equations) in let initial_context = List.map (fun id -> CCHyp{o_hyp=id;o_path=[]}) (List.tl l_hyps) in let context = CCHyp{o_hyp=id_concl;o_path=[]} :: hyp_stated_vars @ initial_context in let decompose_tactic = decompose_tree env context solution_tree in Proofview.V82.of_tactic (Tactics.generalize (l_generalize_arg @ List.map Term.mkVar (List.tl l_hyps))) >> Proofview.V82.of_tactic (Tactics.change_concl reified) >> Proofview.V82.of_tactic (Tactics.apply (app coq_do_omega [|decompose_tactic; normalization_trace|])) >> show_goal >> Proofview.V82.of_tactic (Tactics.normalise_vm_in_concl) >> i Alternatives to the previous line : - Normalisation without VM : Tactics.normalise_in_concl - Skip the conversion check and rely directly on the QED : Tacmach.convert_concl_no_check ( Lazy.force coq_True ) Term . VMcast > > i - Normalisation without VM: Tactics.normalise_in_concl - Skip the conversion check and rely directly on the QED: Tacmach.convert_concl_no_check (Lazy.force coq_True) Term.VMcast >> i*) Proofview.V82.of_tactic (Tactics.apply (Lazy.force coq_I)) let total_reflexive_omega_tactic gl = Coqlib.check_required_library ["Coq";"romega";"ROmega"]; rst_omega_eq (); rst_omega_var (); try let env = new_environment () in let full_reified_goal = reify_gl env gl in let systems_list = destructurate_hyps full_reified_goal in if !debug then display_systems systems_list; resolution env full_reified_goal systems_list gl with NO_CONTRADICTION -> CErrors.error "ROmega can't solve this system" i let tester = Tacmach.hide_atomic_tactic " TestOmega " test_tactic i
null
https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/plugins/romega/refl_omega.ml
ocaml
\section{Useful functions and flags} Especially useful debugging functions More readable than the prefix notation \section{Types} \subsection{How to walk in a term} To represent how to get to a proposition. Only choice points are kept (branch to choose in a disjunction and identifier of the disjunctive connector) Step to find a proposition (operators are at most binary). A list is a path \subsection{reifiable formulas} integer recognized binary and unary operations an atom in the environment weird expression that cannot be translated comparaison formule brute gauche formule brute droite l'hypothèse dont vient le terme vrai si apparait en position nié après normalisation la fonction normalisée La meme chose pour les propositions Les variables introduites par omega Représentation de l'environnement extrait du but initial sous forme de chemins pour extraire des equations ou d'hypothèses \section{Specific utility functions to handle base types} Calcul de la branche complémentaire Identifiant associé à une branche \subsection{Gestion des environnements de variable pour Omega} Affichage des variables d'un système Récupère le terme associé à une variable ajout d'une proposition \subsection{Gestion du nommage des équations} Ajout d'une equation dans l'environnement de reification accès a une equation Affichage des termes réifiés \subsection{Oformula vers Omega} i tag_equation name id; i attention ne traite pas les nouvelles variables si on ne les * met pas dans env.term Extraction des variables d'une équation. \subsection{Multiplication par un scalaire} \subsection{Propagation de l'inversion} \subsection{Mélange (fusion) de deux équations} \subsubsection{Version avec coefficients} \subsubsection{Version sans coefficients} \subsection{Calcul d'une sous formule constante} \subsection{Réordonnancement} \subsection{Elimination des zéros} \subsection{Transformation des hypothèses} \section{Compilation des hypothèses} On ajoute l'equation dans l'environnement. \subsection{Affichage d'un système d'équation} Il faut trier les variables par ordre d'introduction pour ne pas risquer de définir dans le mauvais ordre Le terme qu'il va falloir introduire \section{Rejouer l'historique} \section{La fonction principale} calcule les hypotheses utilisées pour la solution calcule la liste de toutes les hypothèses utilisées dans l'arbre de solution recupere explicitement ces equations variables a introduire
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * PROJET RNRT Calife - 2001 Author : France Télécom R&D Licence : LGPL version 2.1 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * PROJET RNRT Calife - 2001 Author: Pierre Crégut - France Télécom R&D Licence : LGPL version 2.1 *************************************************************************) open Pp open Util open Const_omega module OmegaSolver = Omega_plugin.Omega.MakeOmegaSolver (Bigint) open OmegaSolver let debug = ref false let show_goal gl = if !debug then (); Tacticals.tclIDTAC gl let pp i = print_int i; print_newline (); flush stdout let (>>) = Tacticals.tclTHEN let mkApp = Term.mkApp type direction = Left of int | Right of int type occ_step = O_left | O_right | O_mono type occ_path = occ_step list let occ_step_eq s1 s2 = match s1, s2 with | O_left, O_left | O_right, O_right | O_mono, O_mono -> true | _ -> false chemin identifiant une proposition d'une liste de pas à partir de la racine de l'hypothèse d'une liste de pas à partir de la racine de l'hypothèse *) type occurrence = {o_hyp : Names.Id.t; o_path : occ_path} type oformula = | Oint of Bigint.bigint | Oplus of oformula * oformula | Omult of oformula * oformula | Ominus of oformula * oformula | Oopp of oformula | Oatom of int | Oufo of oformula Operators for comparison recognized by Omega type comparaison = Eq | Leq | Geq | Gt | Lt | Neq Type des prédicats réifiés ( fragment de calcul . Les * quantifications sont externes au langage ) * quantifications sont externes au langage) *) type oproposition = Pequa of Term.constr * oequation | Ptrue | Pfalse | Pnot of oproposition | Por of int * oproposition * oproposition | Pand of int * oproposition * oproposition | Pimp of int * oproposition * oproposition | Pprop of Term.constr Les équations ou propositions atomiques utiles du calcul and oequation = { tactique de normalisation liste des points do nt dépend l'accès à l'équation avec la direction ( branche ) pour y accéder dépend l'accès à l'équation avec la direction (branche) pour y accéder *) } \subsection{Proof context } This environment codes \begin{itemize } \item the terms and propositions that are given as parameters of the reified proof ( and are represented as variables in the reified goals ) \item translation functions linking the decision procedure and the Coq proof \end{itemize } This environment codes \begin{itemize} \item the terms and propositions that are given as parameters of the reified proof (and are represented as variables in the reified goals) \item translation functions linking the decision procedure and the Coq proof \end{itemize} *) type environment = { La liste des termes non reifies constituant l'environnement global mutable terms : Term.constr list; mutable props : Term.constr list; mutable om_vars : (oformula * int) list; Traduction des indices utilisés ici en les indices utilisés par * la tactique Omega après dénombrement des variables utiles * la tactique Omega après dénombrement des variables utiles *) real_indices : (int,int) Hashtbl.t; mutable cnt_connectors : int; equations : (int,oequation) Hashtbl.t; constructors : (int, occurrence) Hashtbl.t } \subsection{Solution tree } Définition d'une solution trouvée par forme , d'un ensemble d'équation do nt dépend la solution et d'une trace Définition d'une solution trouvée par Omega sous la forme d'un identifiant, d'un ensemble d'équation dont dépend la solution et d'une trace *) La liste des dépendances est triée et sans redondance type solution = { s_index : int; s_equa_deps : int list; s_trace : action list } Arbre de solution résolvant complètement un ensemble de systèmes type solution_tree = Leaf of solution un noeud interne représente un point correspondant à l'élimination d'un connecteur ( typ . disjonction ) . Le premier argument est l'identifiant du connecteur l'élimination d'un connecteur générant plusieurs buts (typ. disjonction). Le premier argument est l'identifiant du connecteur *) | Tree of int * solution_tree * solution_tree type context_content = CCHyp of occurrence | CCEqua of int négation du but final let id_concl = Names.Id.of_string "__goal__" Initialisation de l'environnement de réification de la tactique let new_environment () = { terms = []; props = []; om_vars = []; cnt_connectors = 0; real_indices = Hashtbl.create 7; equations = Hashtbl.create 7; constructors = Hashtbl.create 7; } Génération d'un nom d'équation let new_connector_id env = env.cnt_connectors <- succ env.cnt_connectors; env.cnt_connectors let barre = function Left x -> Right x | Right x -> Left x let indice = function Left x | Right x -> x Affichage de l'environnement de réification ( termes et propositions ) let print_env_reification env = let rec loop c i = function [] -> str " ===============================\n\n" | t :: l -> let s = Printf.sprintf "(%c%02d)" c i in spc () ++ str s ++ str " := " ++ Printer.pr_lconstr t ++ fnl () ++ loop c (succ i) l in let prop_info = str "ENVIRONMENT OF PROPOSITIONS :" ++ fnl () ++ loop 'P' 0 env.props in let term_info = str "ENVIRONMENT OF TERMS :" ++ fnl () ++ loop 'V' 0 env.terms in Feedback.msg_debug (prop_info ++ fnl () ++ term_info) generation pour Omega let new_omega_eq, rst_omega_eq = let cpt = ref 0 in (function () -> incr cpt; !cpt), (function () -> cpt:=0) generation variable pour Omega let new_omega_var, rst_omega_var = let cpt = ref 0 in (function () -> incr cpt; !cpt), (function () -> cpt:=0) let display_omega_var i = Printf.sprintf "OV%d" i Recherche la variable codant un terme pour Omega et crée la variable dans l'environnement . Cas ou la variable dans ( le plus souvent ) l'environnement si il n'existe pas. Cas ou la variable dans Omega représente le terme d'un monome (le plus souvent un atome) *) let intern_omega env t = FIXME with Not_found -> let v = new_omega_var () in env.om_vars <- (t,v) :: env.om_vars; v end Ajout forcé d'un lien entre un terme et une variable Cas où la variable est créée par Omega et où il faut la lier à un atome variable est créée par Omega et où il faut la lier après coup à un atome réifié introduit de force *) let intern_omega_force env t v = env.om_vars <- (t,v) :: env.om_vars let unintern_omega env id = let rec loop = function [] -> failwith "unintern" | ((t,j)::l) -> if Int.equal id j then t else loop l in loop env.om_vars \subsection{Gestion des environnements de variable pour la réflexion } Gestion des environnements de traduction entre termes des constructions non réifiés et variables des termes reifies . Attention il s'agit de l'environnement initial contenant tout . calcul des variables utiles . Gestion des environnements de traduction entre termes des constructions non réifiés et variables des termes reifies. Attention il s'agit de l'environnement initial contenant tout. Il faudra le réduire après calcul des variables utiles. *) let add_reified_atom t env = try List.index0 Term.eq_constr t env.terms with Not_found -> let i = List.length env.terms in env.terms <- env.terms @ [t]; i let get_reified_atom env = try List.nth env.terms with Invalid_argument _ -> failwith "get_reified_atom" \subsection{Gestion de l'environnement de proposition pour Omega } let add_prop env t = try List.index0 Term.eq_constr t env.props with Not_found -> let i = List.length env.props in env.props <- env.props @ [t]; i accès a une proposition let get_prop v env = try List.nth v env with Invalid_argument _ -> failwith "get_prop" let add_equation env e = let id = e.e_omega.id in try let _ = Hashtbl.find env.equations id in () with Not_found -> Hashtbl.add env.equations id e let get_equation env id = try Hashtbl.find env.equations id with Not_found as e -> Printf.printf "Omega Equation %d non trouvée\n" id; raise e let rec oprint ch = function | Oint n -> Printf.fprintf ch "%s" (Bigint.to_string n) | Oplus (t1,t2) -> Printf.fprintf ch "(%a + %a)" oprint t1 oprint t2 | Omult (t1,t2) -> Printf.fprintf ch "(%a * %a)" oprint t1 oprint t2 | Ominus(t1,t2) -> Printf.fprintf ch "(%a - %a)" oprint t1 oprint t2 | Oopp t1 ->Printf.fprintf ch "~ %a" oprint t1 | Oatom n -> Printf.fprintf ch "V%02d" n | Oufo x -> Printf.fprintf ch "?" let rec pprint ch = function Pequa (_,{ e_comp=comp; e_left=t1; e_right=t2 }) -> let connector = match comp with Eq -> "=" | Leq -> "<=" | Geq -> ">=" | Gt -> ">" | Lt -> "<" | Neq -> "!=" in Printf.fprintf ch "%a %s %a" oprint t1 connector oprint t2 | Ptrue -> Printf.fprintf ch "TT" | Pfalse -> Printf.fprintf ch "FF" | Pnot t -> Printf.fprintf ch "not(%a)" pprint t | Por (_,t1,t2) -> Printf.fprintf ch "(%a or %a)" pprint t1 pprint t2 | Pand(_,t1,t2) -> Printf.fprintf ch "(%a and %a)" pprint t1 pprint t2 | Pimp(_,t1,t2) -> Printf.fprintf ch "(%a => %a)" pprint t1 pprint t2 | Pprop c -> Printf.fprintf ch "Prop" let rec weight env = function | Oint _ -> -1 | Oopp c -> weight env c | Omult(c,_) -> weight env c | Oplus _ -> failwith "weight" | Ominus _ -> failwith "weight minus" | Oufo _ -> -1 | Oatom _ as c -> (intern_omega env c) \section{Passage entre oformules et représentation interne de Omega } let omega_of_oformula env kind = let rec loop accu = function | Oplus(Omult(v,Oint n),r) -> loop ({v=intern_omega env v; c=n} :: accu) r | Oint n -> let id = new_omega_eq () in {kind = kind; body = List.rev accu; constant = n; id = id} | t -> print_string "CO"; oprint stdout t; failwith "compile_equation" in loop [] \subsection{Omega vers Oformula } let oformula_of_omega env af = let rec loop = function | ({v=v; c=n}::r) -> Oplus(Omult(unintern_omega env v,Oint n),loop r) | [] -> Oint af.constant in loop af.body let app f v = mkApp(Lazy.force f,v) \subsection{Oformula vers COQ reel } let coq_of_formula env t = let rec loop = function | Oplus (t1,t2) -> app Z.plus [| loop t1; loop t2 |] | Oopp t -> app Z.opp [| loop t |] | Omult(t1,t2) -> app Z.mult [| loop t1; loop t2 |] | Oint v -> Z.mk v | Oufo t -> loop t | Oatom var -> get_reified_atom env var | Ominus(t1,t2) -> app Z.minus [| loop t1; loop t2 |] in loop t \subsection{Oformula vers COQ reifié } let reified_of_atom env i = try Hashtbl.find env.real_indices i with Not_found -> Printf.printf "Atome %d non trouvé\n" i; Hashtbl.iter (fun k v -> Printf.printf "%d -> %d\n" k v) env.real_indices; raise Not_found let rec reified_of_formula env = function | Oplus (t1,t2) -> app coq_t_plus [| reified_of_formula env t1; reified_of_formula env t2 |] | Oopp t -> app coq_t_opp [| reified_of_formula env t |] | Omult(t1,t2) -> app coq_t_mult [| reified_of_formula env t1; reified_of_formula env t2 |] | Oint v -> app coq_t_int [| Z.mk v |] | Oufo t -> reified_of_formula env t | Oatom i -> app coq_t_var [| mk_nat (reified_of_atom env i) |] | Ominus(t1,t2) -> app coq_t_minus [| reified_of_formula env t1; reified_of_formula env t2 |] let reified_of_formula env f = try reified_of_formula env f with reraise -> oprint stderr f; raise reraise let rec reified_of_proposition env = function Pequa (_,{ e_comp=Eq; e_left=t1; e_right=t2 }) -> app coq_p_eq [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa (_,{ e_comp=Leq; e_left=t1; e_right=t2 }) -> app coq_p_leq [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa(_,{ e_comp=Geq; e_left=t1; e_right=t2 }) -> app coq_p_geq [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa(_,{ e_comp=Gt; e_left=t1; e_right=t2 }) -> app coq_p_gt [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa(_,{ e_comp=Lt; e_left=t1; e_right=t2 }) -> app coq_p_lt [| reified_of_formula env t1; reified_of_formula env t2 |] | Pequa(_,{ e_comp=Neq; e_left=t1; e_right=t2 }) -> app coq_p_neq [| reified_of_formula env t1; reified_of_formula env t2 |] | Ptrue -> Lazy.force coq_p_true | Pfalse -> Lazy.force coq_p_false | Pnot t -> app coq_p_not [| reified_of_proposition env t |] | Por (_,t1,t2) -> app coq_p_or [| reified_of_proposition env t1; reified_of_proposition env t2 |] | Pand(_,t1,t2) -> app coq_p_and [| reified_of_proposition env t1; reified_of_proposition env t2 |] | Pimp(_,t1,t2) -> app coq_p_imp [| reified_of_proposition env t1; reified_of_proposition env t2 |] | Pprop t -> app coq_p_prop [| mk_nat (add_prop env t) |] let reified_of_proposition env f = try reified_of_proposition env f with reraise -> pprint stderr f; raise reraise \subsection{Omega vers COQ réifié } let reified_of_omega env body constant = let coeff_constant = app coq_t_int [| Z.mk constant |] in let mk_coeff {c=c; v=v} t = let coef = app coq_t_mult [| reified_of_formula env (unintern_omega env v); app coq_t_int [| Z.mk c |] |] in app coq_t_plus [|coef; t |] in List.fold_right mk_coeff body coeff_constant let reified_of_omega env body c = try reified_of_omega env body c with reraise -> display_eq display_omega_var (body,c); raise reraise \section{Opérations sur les équations } Ces fonctions préparent les traces utilisées par la tactique réfléchie pour faire des opérations de normalisation sur les équations . Ces fonctions préparent les traces utilisées par la tactique réfléchie pour faire des opérations de normalisation sur les équations. *) \subsection{Extractions des variables d'une équation } Chaque fonction retourne une liste triée sans redondance let (@@) = List.merge_uniq compare let rec vars_of_formula = function | Oint _ -> [] | Oplus (e1,e2) -> (vars_of_formula e1) @@ (vars_of_formula e2) | Omult (e1,e2) -> (vars_of_formula e1) @@ (vars_of_formula e2) | Ominus (e1,e2) -> (vars_of_formula e1) @@ (vars_of_formula e2) | Oopp e -> vars_of_formula e | Oatom i -> [i] | Oufo _ -> [] let rec vars_of_equations = function | [] -> [] | e::l -> (vars_of_formula e.e_left) @@ (vars_of_formula e.e_right) @@ (vars_of_equations l) let rec vars_of_prop = function | Pequa(_,e) -> vars_of_equations [e] | Pnot p -> vars_of_prop p | Por(_,p1,p2) -> (vars_of_prop p1) @@ (vars_of_prop p2) | Pand(_,p1,p2) -> (vars_of_prop p1) @@ (vars_of_prop p2) | Pimp(_,p1,p2) -> (vars_of_prop p1) @@ (vars_of_prop p2) | Pprop _ | Ptrue | Pfalse -> [] let rec scalar n = function Oplus(t1,t2) -> let tac1,t1' = scalar n t1 and tac2,t2' = scalar n t2 in do_list [Lazy.force coq_c_mult_plus_distr; do_both tac1 tac2], Oplus(t1',t2') | Oopp t -> do_list [Lazy.force coq_c_mult_opp_left], Omult(t,Oint(Bigint.neg n)) | Omult(t1,Oint x) -> do_list [Lazy.force coq_c_mult_assoc_reduced], Omult(t1,Oint (n*x)) | Omult(t1,t2) -> CErrors.error "Omega: Can't solve a goal with non-linear products" | (Oatom _ as t) -> do_list [], Omult(t,Oint n) | Oint i -> do_list [Lazy.force coq_c_reduce],Oint(n*i) | (Oufo _ as t)-> do_list [], Oufo (Omult(t,Oint n)) | Ominus _ -> failwith "scalar minus" let rec negate = function Oplus(t1,t2) -> let tac1,t1' = negate t1 and tac2,t2' = negate t2 in do_list [Lazy.force coq_c_opp_plus ; (do_both tac1 tac2)], Oplus(t1',t2') | Oopp t -> do_list [Lazy.force coq_c_opp_opp], t | Omult(t1,Oint x) -> do_list [Lazy.force coq_c_opp_mult_r], Omult(t1,Oint (Bigint.neg x)) | Omult(t1,t2) -> CErrors.error "Omega: Can't solve a goal with non-linear products" | (Oatom _ as t) -> do_list [Lazy.force coq_c_opp_one], Omult(t,Oint(negone)) | Oint i -> do_list [Lazy.force coq_c_reduce] ,Oint(Bigint.neg i) | Oufo c -> do_list [], Oufo (Oopp c) | Ominus _ -> failwith "negate minus" let norm l = (List.length l) let shuffle_path k1 e1 k2 e2 = let rec loop = function (({c=c1;v=v1}::l1) as l1'), (({c=c2;v=v2}::l2) as l2') -> if Int.equal v1 v2 then if Bigint.equal (k1 * c1 + k2 * c2) zero then ( Lazy.force coq_f_cancel :: loop (l1,l2)) else ( Lazy.force coq_f_equal :: loop (l1,l2) ) else if v1 > v2 then ( Lazy.force coq_f_left :: loop(l1,l2')) else ( Lazy.force coq_f_right :: loop(l1',l2)) | ({c=c1;v=v1}::l1), [] -> Lazy.force coq_f_left :: loop(l1,[]) | [],({c=c2;v=v2}::l2) -> Lazy.force coq_f_right :: loop([],l2) | [],[] -> flush stdout; [] in mk_shuffle_list (loop (e1,e2)) let rec shuffle env (t1,t2) = match t1,t2 with Oplus(l1,r1), Oplus(l2,r2) -> if weight env l1 > weight env l2 then let l_action,t' = shuffle env (r1,t2) in do_list [Lazy.force coq_c_plus_assoc_r;do_right l_action], Oplus(l1,t') else let l_action,t' = shuffle env (t1,r2) in do_list [Lazy.force coq_c_plus_permute;do_right l_action], Oplus(l2,t') | Oplus(l1,r1), t2 -> if weight env l1 > weight env t2 then let (l_action,t') = shuffle env (r1,t2) in do_list [Lazy.force coq_c_plus_assoc_r;do_right l_action],Oplus(l1, t') else do_list [Lazy.force coq_c_plus_comm], Oplus(t2,t1) | t1,Oplus(l2,r2) -> if weight env l2 > weight env t1 then let (l_action,t') = shuffle env (t1,r2) in do_list [Lazy.force coq_c_plus_permute;do_right l_action], Oplus(l2,t') else do_list [],Oplus(t1,t2) | Oint t1,Oint t2 -> do_list [Lazy.force coq_c_reduce], Oint(t1+t2) | t1,t2 -> if weight env t1 < weight env t2 then do_list [Lazy.force coq_c_plus_comm], Oplus(t2,t1) else do_list [],Oplus(t1,t2) \subsection{Fusion avec réduction } let shrink_pair f1 f2 = begin match f1,f2 with Oatom v,Oatom _ -> Lazy.force coq_c_red1, Omult(Oatom v,Oint two) | Oatom v, Omult(_,c2) -> Lazy.force coq_c_red2, Omult(Oatom v,Oplus(c2,Oint one)) | Omult (v1,c1),Oatom v -> Lazy.force coq_c_red3, Omult(Oatom v,Oplus(c1,Oint one)) | Omult (Oatom v,c1),Omult (v2,c2) -> Lazy.force coq_c_red4, Omult(Oatom v,Oplus(c1,c2)) | t1,t2 -> oprint stdout t1; print_newline (); oprint stdout t2; print_newline (); flush Pervasives.stdout; CErrors.error "shrink.1" end let reduce_factor = function Oatom v -> let r = Omult(Oatom v,Oint one) in [Lazy.force coq_c_red0],r | Omult(Oatom v,Oint n) as f -> [],f | Omult(Oatom v,c) -> let rec compute = function Oint n -> n | Oplus(t1,t2) -> compute t1 + compute t2 | _ -> CErrors.error "condense.1" in [Lazy.force coq_c_reduce], Omult(Oatom v,Oint(compute c)) | t -> CErrors.error "reduce_factor.1" let rec condense env = function Oplus(f1,(Oplus(f2,r) as t)) -> if Int.equal (weight env f1) (weight env f2) then begin let shrink_tac,t = shrink_pair f1 f2 in let assoc_tac = Lazy.force coq_c_plus_assoc_l in let tac_list,t' = condense env (Oplus(t,r)) in assoc_tac :: do_left (do_list [shrink_tac]) :: tac_list, t' end else begin let tac,f = reduce_factor f1 in let tac',t' = condense env t in [do_both (do_list tac) (do_list tac')], Oplus(f,t') end | Oplus(f1,Oint n) -> let tac,f1' = reduce_factor f1 in [do_left (do_list tac)],Oplus(f1',Oint n) | Oplus(f1,f2) -> if Int.equal (weight env f1) (weight env f2) then begin let tac_shrink,t = shrink_pair f1 f2 in let tac,t' = condense env t in tac_shrink :: tac,t' end else begin let tac,f = reduce_factor f1 in let tac',t' = condense env f2 in [do_both (do_list tac) (do_list tac')],Oplus(f,t') end | (Oint _ as t)-> [],t | t -> let tac,t' = reduce_factor t in let final = Oplus(t',Oint zero) in tac @ [Lazy.force coq_c_red6], final let rec clear_zero = function Oplus(Omult(Oatom v,Oint n),r) when Bigint.equal n zero -> let tac',t = clear_zero r in Lazy.force coq_c_red5 :: tac',t | Oplus(f,r) -> let tac,t = clear_zero r in (if List.is_empty tac then [] else [do_right (do_list tac)]),Oplus(f,t) | t -> [],t;; let rec reduce env = function Oplus(t1,t2) -> let t1', trace1 = reduce env t1 in let t2', trace2 = reduce env t2 in let trace3,t' = shuffle env (t1',t2') in t', do_list [do_both trace1 trace2; trace3] | Ominus(t1,t2) -> let t,trace = reduce env (Oplus(t1, Oopp t2)) in t, do_list [Lazy.force coq_c_minus; trace] | Omult(t1,t2) as t -> let t1', trace1 = reduce env t1 in let t2', trace2 = reduce env t2 in begin match t1',t2' with | (_, Oint n) -> let tac,t' = scalar n t1' in t', do_list [do_both trace1 trace2; tac] | (Oint n,_) -> let tac,t' = scalar n t2' in t', do_list [do_both trace1 trace2; Lazy.force coq_c_mult_comm; tac] | _ -> Oufo t, Lazy.force coq_c_nop end | Oopp t -> let t',trace = reduce env t in let trace',t'' = negate t' in t'', do_list [do_left trace; trace'] | (Oint _ | Oatom _ | Oufo _) as t -> t, Lazy.force coq_c_nop let normalize_linear_term env t = let t1,trace1 = reduce env t in let trace2,t2 = condense env t1 in let trace3,t3 = clear_zero t2 in do_list [trace1; do_list trace2; do_list trace3], t3 Cette fonction reproduit très exactement le comportement de [ p_invert ] let negate_oper = function Eq -> Neq | Neq -> Eq | Leq -> Gt | Geq -> Lt | Lt -> Geq | Gt -> Leq let normalize_equation env (negated,depends,origin,path) (oper,t1,t2) = let mk_step t1 t2 f kind = let t = f t1 t2 in let trace, oterm = normalize_linear_term env t in let equa = omega_of_oformula env kind oterm in { e_comp = oper; e_left = t1; e_right = t2; e_negated = negated; e_depends = depends; e_origin = { o_hyp = origin; o_path = List.rev path }; e_trace = trace; e_omega = equa } in try match (if negated then (negate_oper oper) else oper) with | Eq -> mk_step t1 t2 (fun o1 o2 -> Oplus (o1,Oopp o2)) EQUA | Neq -> mk_step t1 t2 (fun o1 o2 -> Oplus (o1,Oopp o2)) DISE | Leq -> mk_step t1 t2 (fun o1 o2 -> Oplus (o2,Oopp o1)) INEQ | Geq -> mk_step t1 t2 (fun o1 o2 -> Oplus (o1,Oopp o2)) INEQ | Lt -> mk_step t1 t2 (fun o1 o2 -> Oplus (Oplus(o2,Oint negone),Oopp o1)) INEQ | Gt -> mk_step t1 t2 (fun o1 o2 -> Oplus (Oplus(o1,Oint negone),Oopp o2)) INEQ with e when Logic.catchable_exception e -> raise e let rec oformula_of_constr env t = match Z.parse_term t with | Tplus (t1,t2) -> binop env (fun x y -> Oplus(x,y)) t1 t2 | Tminus (t1,t2) -> binop env (fun x y -> Ominus(x,y)) t1 t2 | Tmult (t1,t2) when Z.is_scalar t1 || Z.is_scalar t2 -> binop env (fun x y -> Omult(x,y)) t1 t2 | Topp t -> Oopp(oformula_of_constr env t) | Tsucc t -> Oplus(oformula_of_constr env t, Oint one) | Tnum n -> Oint n | _ -> Oatom (add_reified_atom t env) and binop env c t1 t2 = let t1' = oformula_of_constr env t1 in let t2' = oformula_of_constr env t2 in c t1' t2' and binprop env (neg2,depends,origin,path) add_to_depends neg1 gl c t1 t2 = let i = new_connector_id env in let depends1 = if add_to_depends then Left i::depends else depends in let depends2 = if add_to_depends then Right i::depends else depends in if add_to_depends then Hashtbl.add env.constructors i {o_hyp = origin; o_path = List.rev path}; let t1' = oproposition_of_constr env (neg1,depends1,origin,O_left::path) gl t1 in let t2' = oproposition_of_constr env (neg2,depends2,origin,O_right::path) gl t2 in On numérote le connecteur dans l'environnement . c i t1' t2' and mk_equation env ctxt c connector t1 t2 = let t1' = oformula_of_constr env t1 in let t2' = oformula_of_constr env t2 in let omega = normalize_equation env ctxt (connector,t1',t2') in add_equation env omega; Pequa (c,omega) and oproposition_of_constr env ((negated,depends,origin,path) as ctxt) gl c = match Z.parse_rel gl c with | Req (t1,t2) -> mk_equation env ctxt c Eq t1 t2 | Rne (t1,t2) -> mk_equation env ctxt c Neq t1 t2 | Rle (t1,t2) -> mk_equation env ctxt c Leq t1 t2 | Rlt (t1,t2) -> mk_equation env ctxt c Lt t1 t2 | Rge (t1,t2) -> mk_equation env ctxt c Geq t1 t2 | Rgt (t1,t2) -> mk_equation env ctxt c Gt t1 t2 | Rtrue -> Ptrue | Rfalse -> Pfalse | Rnot t -> let t' = oproposition_of_constr env (not negated, depends, origin,(O_mono::path)) gl t in Pnot t' | Ror (t1,t2) -> binprop env ctxt (not negated) negated gl (fun i x y -> Por(i,x,y)) t1 t2 | Rand (t1,t2) -> binprop env ctxt negated negated gl (fun i x y -> Pand(i,x,y)) t1 t2 | Rimp (t1,t2) -> binprop env ctxt (not negated) (not negated) gl (fun i x y -> Pimp(i,x,y)) t1 t2 | Riff (t1,t2) -> binprop env ctxt negated negated gl (fun i x y -> Pand(i,x,y)) (Term.mkArrow t1 t2) (Term.mkArrow t2 t1) | _ -> Pprop c Destructuration des hypothèses et de la conclusion let reify_gl env gl = let concl = Tacmach.pf_concl gl in let t_concl = Pnot (oproposition_of_constr env (true,[],id_concl,[O_mono]) gl concl) in if !debug then begin Printf.printf "REIFED PROBLEM\n\n"; Printf.printf " CONCL: "; pprint stdout t_concl; Printf.printf "\n" end; let rec loop = function (i,t) :: lhyps -> let t' = oproposition_of_constr env (false,[],i,[]) gl t in if !debug then begin Printf.printf " %s: " (Names.Id.to_string i); pprint stdout t'; Printf.printf "\n" end; (i,t') :: loop lhyps | [] -> if !debug then print_env_reification env; [] in let t_lhyps = loop (Tacmach.pf_hyps_types gl) in (id_concl,t_concl) :: t_lhyps let rec destructurate_pos_hyp orig list_equations list_depends = function | Pequa (_,e) -> [e :: list_equations] | Ptrue | Pfalse | Pprop _ -> [list_equations] | Pnot t -> destructurate_neg_hyp orig list_equations list_depends t | Por (i,t1,t2) -> let s1 = destructurate_pos_hyp orig list_equations (i::list_depends) t1 in let s2 = destructurate_pos_hyp orig list_equations (i::list_depends) t2 in s1 @ s2 | Pand(i,t1,t2) -> let list_s1 = destructurate_pos_hyp orig list_equations (list_depends) t1 in let rec loop = function le1 :: ll -> destructurate_pos_hyp orig le1 list_depends t2 @ loop ll | [] -> [] in loop list_s1 | Pimp(i,t1,t2) -> let s1 = destructurate_neg_hyp orig list_equations (i::list_depends) t1 in let s2 = destructurate_pos_hyp orig list_equations (i::list_depends) t2 in s1 @ s2 and destructurate_neg_hyp orig list_equations list_depends = function | Pequa (_,e) -> [e :: list_equations] | Ptrue | Pfalse | Pprop _ -> [list_equations] | Pnot t -> destructurate_pos_hyp orig list_equations list_depends t | Pand (i,t1,t2) -> let s1 = destructurate_neg_hyp orig list_equations (i::list_depends) t1 in let s2 = destructurate_neg_hyp orig list_equations (i::list_depends) t2 in s1 @ s2 | Por(_,t1,t2) -> let list_s1 = destructurate_neg_hyp orig list_equations list_depends t1 in let rec loop = function le1 :: ll -> destructurate_neg_hyp orig le1 list_depends t2 @ loop ll | [] -> [] in loop list_s1 | Pimp(_,t1,t2) -> let list_s1 = destructurate_pos_hyp orig list_equations list_depends t1 in let rec loop = function le1 :: ll -> destructurate_neg_hyp orig le1 list_depends t2 @ loop ll | [] -> [] in loop list_s1 let destructurate_hyps syst = let rec loop = function (i,t) :: l -> let l_syst1 = destructurate_pos_hyp i [] [] t in let l_syst2 = loop l in List.cartesian (@) l_syst1 l_syst2 | [] -> [[]] in loop syst Affichage des dépendances de système let display_depend = function Left i -> Printf.printf " L%d" i | Right i -> Printf.printf " R%d" i let display_systems syst_list = let display_omega om_e = Printf.printf " E%d : %a %s 0\n" om_e.id (fun _ -> display_eq display_omega_var) (om_e.body, om_e.constant) (operator_of_eq om_e.kind) in let display_equation oformula_eq = pprint stdout (Pequa (Lazy.force coq_c_nop,oformula_eq)); print_newline (); display_omega oformula_eq.e_omega; Printf.printf " Depends on:"; List.iter display_depend oformula_eq.e_depends; Printf.printf "\n Path: %s" (String.concat "" (List.map (function O_left -> "L" | O_right -> "R" | O_mono -> "M") oformula_eq.e_origin.o_path)); Printf.printf "\n Origin: %s (negated : %s)\n\n" (Names.Id.to_string oformula_eq.e_origin.o_hyp) (if oformula_eq.e_negated then "yes" else "no") in let display_system syst = Printf.printf "=SYSTEM===================================\n"; List.iter display_equation syst in List.iter display_system syst_list Extraction des prédicats utilisées dans une trace . calcul des hypothèses calcul des hypothèses *) let rec hyps_used_in_trace = function | act :: l -> begin match act with | HYP e -> [e.id] @@ (hyps_used_in_trace l) | SPLIT_INEQ (_,(_,act1),(_,act2)) -> hyps_used_in_trace act1 @@ hyps_used_in_trace act2 | _ -> hyps_used_in_trace l end | [] -> [] Extraction des variables déclarées dans une équation . de les déclarer dans l'environnement de la procédure réflexive et les créations de variable au vol de les déclarer dans l'environnement de la procédure réflexive et éviter les créations de variable au vol *) let rec variable_stated_in_trace = function | act :: l -> begin match act with | STATE action -> i nlle_equa : afine , def : afine , eq_orig : afine , i i : int , var : int i action :: variable_stated_in_trace l | SPLIT_INEQ (_,(_,act1),(_,act2)) -> variable_stated_in_trace act1 @ variable_stated_in_trace act2 | _ -> variable_stated_in_trace l end | [] -> [] ;; let add_stated_equations env tree = let stated_equations = let cmpvar x y = Pervasives.(-) x.st_var y.st_var in let rec loop = function | Tree(_,t1,t2) -> List.merge cmpvar (loop t1) (loop t2) | Leaf s -> List.sort cmpvar (variable_stated_in_trace s.s_trace) in loop tree in let add_env st = On retransforme la définition de v en formule let v_def = oformula_of_omega env st.st_def in que si l'ordre de création des variables n'est pas respecté , * ca va planter * ca va planter *) let coq_v = coq_of_formula env v_def in let v = add_reified_atom coq_v env in let term_to_generalize = app coq_refl_equal [|Lazy.force Z.typ; coq_v|] in sa représentation forme d'équation mais non réifié car on n'a pas * l'environnement pour le faire correctement * l'environnement pour le faire correctement *) let term_to_reify = (v_def,Oatom v) in enregistre le lien entre la variable omega et la variable Coq intern_omega_force env (Oatom v) st.st_var; (v, term_to_generalize,term_to_reify,st.st_def.id) in List.map add_env stated_equations Calcule la liste des éclatements à réaliser sur les hypothèses nécessaires pour extraire une liste d'équations donnée nécessaires pour extraire une liste d'équations donnée *) PL : experimentally , the result order of the following function seems _ very _ crucial for efficiency . No idea why . Do not remove the List.rev or modify the current semantics of Util.List.union ( some elements of first arg , then second arg ) , unless you know what you 're doing . _very_ crucial for efficiency. No idea why. Do not remove the List.rev or modify the current semantics of Util.List.union (some elements of first arg, then second arg), unless you know what you're doing. *) let rec get_eclatement env = function i :: r -> let l = try (get_equation env i).e_depends with Not_found -> [] in List.union Pervasives.(=) (List.rev l) (get_eclatement env r) | [] -> [] let select_smaller l = let comp (_,x) (_,y) = Pervasives.(-) (List.length x) (List.length y) in try List.hd (List.sort comp l) with Failure _ -> failwith "select_smaller" let filter_compatible_systems required systems = let rec select = function (x::l) -> if List.mem x required then select l else if List.mem (barre x) required then raise Exit else x :: select l | [] -> [] in List.map_filter (function (sol, splits) -> try Some (sol, select splits) with Exit -> None) systems let rec equas_of_solution_tree = function Tree(_,t1,t2) -> (equas_of_solution_tree t1)@@(equas_of_solution_tree t2) | Leaf s -> s.s_equa_deps [ really_useful_prop ] pushes useless props in a new Pprop variable Things get shorter , but may also get wrong , since a Prop is considered to be undecidable in ReflOmegaCore.concl_to_hyp , whereas for instance Pfalse is decidable . So should not be used on conclusion ( ? ? ) to be undecidable in ReflOmegaCore.concl_to_hyp, whereas for instance Pfalse is decidable. So should not be used on conclusion (??) *) let really_useful_prop l_equa c = let rec real_of = function Pequa(t,_) -> t | Ptrue -> app coq_True [||] | Pfalse -> app coq_False [||] | Pnot t1 -> app coq_not [|real_of t1|] | Por(_,t1,t2) -> app coq_or [|real_of t1; real_of t2|] | Pand(_,t1,t2) -> app coq_and [|real_of t1; real_of t2|] Attention : implications sur le lifting des variables à comprendre ! | Pimp(_,t1,t2) -> Term.mkArrow (real_of t1) (real_of t2) | Pprop t -> t in let rec loop c = match c with Pequa(_,e) -> if List.mem e.e_omega.id l_equa then Some c else None | Ptrue -> None | Pfalse -> None | Pnot t1 -> begin match loop t1 with None -> None | Some t1' -> Some (Pnot t1') end | Por(i,t1,t2) -> binop (fun (t1,t2) -> Por(i,t1,t2)) t1 t2 | Pand(i,t1,t2) -> binop (fun (t1,t2) -> Pand(i,t1,t2)) t1 t2 | Pimp(i,t1,t2) -> binop (fun (t1,t2) -> Pimp(i,t1,t2)) t1 t2 | Pprop t -> None and binop f t1 t2 = begin match loop t1, loop t2 with None, None -> None | Some t1',Some t2' -> Some (f(t1',t2')) | Some t1',None -> Some (f(t1',Pprop (real_of t2))) | None,Some t2' -> Some (f(Pprop (real_of t1),t2')) end in match loop c with None -> Pprop (real_of c) | Some t -> t let rec display_solution_tree ch = function Leaf t -> output_string ch (Printf.sprintf "%d[%s]" t.s_index (String.concat " " (List.map string_of_int t.s_equa_deps))) | Tree(i,t1,t2) -> Printf.fprintf ch "S%d(%a,%a)" i display_solution_tree t1 display_solution_tree t2 let rec solve_with_constraints all_solutions path = let rec build_tree sol buf = function [] -> Leaf sol | (Left i :: remainder) -> Tree(i, build_tree sol (Left i :: buf) remainder, solve_with_constraints all_solutions (List.rev(Right i :: buf))) | (Right i :: remainder) -> Tree(i, solve_with_constraints all_solutions (List.rev (Left i :: buf)), build_tree sol (Right i :: buf) remainder) in let weighted = filter_compatible_systems path all_solutions in let (winner_sol,winner_deps) = try select_smaller weighted with reraise -> Printf.printf "%d - %d\n" (List.length weighted) (List.length all_solutions); List.iter display_depend path; raise reraise in build_tree winner_sol (List.rev path) winner_deps let find_path {o_hyp=id;o_path=p} env = let rec loop_path = function ([],l) -> Some l | (x1::l1,x2::l2) when occ_step_eq x1 x2 -> loop_path (l1,l2) | _ -> None in let rec loop_id i = function CCHyp{o_hyp=id';o_path=p'} :: l when Names.Id.equal id id' -> begin match loop_path (p',p) with Some r -> i,r | None -> loop_id (succ i) l end | _ :: l -> loop_id (succ i) l | [] -> failwith "find_path" in loop_id 0 env let mk_direction_list l = let trans = function O_left -> coq_d_left | O_right -> coq_d_right | O_mono -> coq_d_mono in mk_list (Lazy.force coq_direction) (List.map (fun d-> Lazy.force(trans d)) l) let get_hyp env_hyp i = try List.index0 Pervasives.(=) (CCEqua i) env_hyp with Not_found -> failwith (Printf.sprintf "get_hyp %d" i) let replay_history env env_hyp = let rec loop env_hyp t = match t with | CONTRADICTION (e1,e2) :: l -> let trace = mk_nat (List.length e1.body) in mkApp (Lazy.force coq_s_contradiction, [| trace ; mk_nat (get_hyp env_hyp e1.id); mk_nat (get_hyp env_hyp e2.id) |]) | DIVIDE_AND_APPROX (e1,e2,k,d) :: l -> mkApp (Lazy.force coq_s_div_approx, [| Z.mk k; Z.mk d; reified_of_omega env e2.body e2.constant; mk_nat (List.length e2.body); loop env_hyp l; mk_nat (get_hyp env_hyp e1.id) |]) | NOT_EXACT_DIVIDE (e1,k) :: l -> let e2_constant = floor_div e1.constant k in let d = e1.constant - e2_constant * k in let e2_body = map_eq_linear (fun c -> c / k) e1.body in mkApp (Lazy.force coq_s_not_exact_divide, [|Z.mk k; Z.mk d; reified_of_omega env e2_body e2_constant; mk_nat (List.length e2_body); mk_nat (get_hyp env_hyp e1.id)|]) | EXACT_DIVIDE (e1,k) :: l -> let e2_body = map_eq_linear (fun c -> c / k) e1.body in let e2_constant = floor_div e1.constant k in mkApp (Lazy.force coq_s_exact_divide, [|Z.mk k; reified_of_omega env e2_body e2_constant; mk_nat (List.length e2_body); loop env_hyp l; mk_nat (get_hyp env_hyp e1.id)|]) | (MERGE_EQ(e3,e1,e2)) :: l -> let n1 = get_hyp env_hyp e1.id and n2 = get_hyp env_hyp e2 in mkApp (Lazy.force coq_s_merge_eq, [| mk_nat (List.length e1.body); mk_nat n1; mk_nat n2; loop (CCEqua e3:: env_hyp) l |]) | SUM(e3,(k1,e1),(k2,e2)) :: l -> let n1 = get_hyp env_hyp e1.id and n2 = get_hyp env_hyp e2.id in let trace = shuffle_path k1 e1.body k2 e2.body in mkApp (Lazy.force coq_s_sum, [| Z.mk k1; mk_nat n1; Z.mk k2; mk_nat n2; trace; (loop (CCEqua e3 :: env_hyp) l) |]) | CONSTANT_NOT_NUL(e,k) :: l -> mkApp (Lazy.force coq_s_constant_not_nul, [| mk_nat (get_hyp env_hyp e) |]) | CONSTANT_NEG(e,k) :: l -> mkApp (Lazy.force coq_s_constant_neg, [| mk_nat (get_hyp env_hyp e) |]) | STATE {st_new_eq=new_eq; st_def =def; st_orig=orig; st_coef=m; st_var=sigma } :: l -> let n1 = get_hyp env_hyp orig.id and n2 = get_hyp env_hyp def.id in let v = unintern_omega env sigma in let o_def = oformula_of_omega env def in let o_orig = oformula_of_omega env orig in let body = Oplus (o_orig,Omult (Oplus (Oopp v,o_def), Oint m)) in let trace,_ = normalize_linear_term env body in mkApp (Lazy.force coq_s_state, [| Z.mk m; trace; mk_nat n1; mk_nat n2; loop (CCEqua new_eq.id :: env_hyp) l |]) | HYP _ :: l -> loop env_hyp l | CONSTANT_NUL e :: l -> mkApp (Lazy.force coq_s_constant_nul, [| mk_nat (get_hyp env_hyp e) |]) | NEGATE_CONTRADICT(e1,e2,true) :: l -> mkApp (Lazy.force coq_s_negate_contradict, [| mk_nat (get_hyp env_hyp e1.id); mk_nat (get_hyp env_hyp e2.id) |]) | NEGATE_CONTRADICT(e1,e2,false) :: l -> mkApp (Lazy.force coq_s_negate_contradict_inv, [| mk_nat (List.length e2.body); mk_nat (get_hyp env_hyp e1.id); mk_nat (get_hyp env_hyp e2.id) |]) | SPLIT_INEQ(e,(e1,l1),(e2,l2)) :: l -> let i = get_hyp env_hyp e.id in let r1 = loop (CCEqua e1 :: env_hyp) l1 in let r2 = loop (CCEqua e2 :: env_hyp) l2 in mkApp (Lazy.force coq_s_split_ineq, [| mk_nat (List.length e.body); mk_nat i; r1 ; r2 |]) | (FORGET_C _ | FORGET _ | FORGET_I _) :: l -> loop env_hyp l | (WEAKEN _ ) :: l -> failwith "not_treated" | [] -> failwith "no contradiction" in loop env_hyp let rec decompose_tree env ctxt = function Tree(i,left,right) -> let org = try Hashtbl.find env.constructors i with Not_found -> failwith (Printf.sprintf "Cannot find constructor %d" i) in let (index,path) = find_path org ctxt in let left_hyp = CCHyp{o_hyp=org.o_hyp;o_path=org.o_path @ [O_left]} in let right_hyp = CCHyp{o_hyp=org.o_hyp;o_path=org.o_path @ [O_right]} in app coq_e_split [| mk_nat index; mk_direction_list path; decompose_tree env (left_hyp::ctxt) left; decompose_tree env (right_hyp::ctxt) right |] | Leaf s -> decompose_tree_hyps s.s_trace env ctxt s.s_equa_deps and decompose_tree_hyps trace env ctxt = function [] -> app coq_e_solve [| replay_history env ctxt trace |] | (i::l) -> let equation = try Hashtbl.find env.equations i with Not_found -> failwith (Printf.sprintf "Cannot find equation %d" i) in let (index,path) = find_path equation.e_origin ctxt in let full_path = if equation.e_negated then path @ [O_mono] else path in let cont = decompose_tree_hyps trace env (CCEqua equation.e_omega.id :: ctxt) l in app coq_e_extract [|mk_nat index; mk_direction_list full_path; cont |] Cette fonction construit la trace pour la procédure de décision réflexive . A partir des résultats de l'extraction des systèmes , elle lance la résolution par Omega , puis l'extraction d'un ensemble minimal de solutions permettant la résolution globale du système et enfin construit la trace qui permet de faire rejouer cette solution par la tactique réflexive . trace pour la procédure de décision réflexive. A partir des résultats de l'extraction des systèmes, elle lance la résolution par Omega, puis l'extraction d'un ensemble minimal de solutions permettant la résolution globale du système et enfin construit la trace qui permet de faire rejouer cette solution par la tactique réflexive. *) let resolution env full_reified_goal systems_list = let num = ref 0 in let solve_system list_eq = let index = !num in let system = List.map (fun eq -> eq.e_omega) list_eq in let trace = simplify_strong (new_omega_eq,new_omega_var,display_omega_var) system in let vars = hyps_used_in_trace trace in let splits = get_eclatement env vars in if !debug then begin Printf.printf "SYSTEME %d\n" index; display_action display_omega_var trace; print_string "\n Depend :"; List.iter (fun i -> Printf.printf " %d" i) vars; print_string "\n Split points :"; List.iter display_depend splits; Printf.printf "\n------------------------------------\n" end; incr num; {s_index = index; s_trace = trace; s_equa_deps = vars}, splits in if !debug then Printf.printf "\n====================================\n"; let all_solutions = List.map solve_system systems_list in let solution_tree = solve_with_constraints all_solutions [] in if !debug then begin display_solution_tree stdout solution_tree; print_newline() end; let useful_equa_id = equas_of_solution_tree solution_tree in let equations = List.map (get_equation env) useful_equa_id in let l_hyps' = List.uniquize (List.map (fun e -> e.e_origin.o_hyp) equations) in let l_hyps = id_concl :: List.remove Names.Id.equal id_concl l_hyps' in let useful_hyps = List.map (fun id -> List.assoc_f Names.Id.equal id full_reified_goal) l_hyps in let useful_vars = let really_useful_vars = vars_of_equations equations in let concl_vars = vars_of_prop (List.assoc_f Names.Id.equal id_concl full_reified_goal) in really_useful_vars @@ concl_vars in let to_introduce = add_stated_equations env solution_tree in let stated_vars = List.map (fun (v,_,_,_) -> v) to_introduce in let l_generalize_arg = List.map (fun (_,t,_,_) -> t) to_introduce in let hyp_stated_vars = List.map (fun (_,_,_,id) -> CCEqua id) to_introduce in L'environnement de base se construit en : - les variables des équations utiles ( et de la conclusion ) - les nouvelles variables declarées durant les preuves - les variables des équations utiles (et de la conclusion) - les nouvelles variables declarées durant les preuves *) let all_vars_env = useful_vars @ stated_vars in let basic_env = let rec loop i = function var :: l -> let t = get_reified_atom env var in Hashtbl.add env.real_indices var i; t :: loop (succ i) l | [] -> [] in loop 0 all_vars_env in let env_terms_reified = mk_list (Lazy.force Z.typ) basic_env in On peut maintenant but : env est a jour let l_reified_stated = List.map (fun (_,_,(l,r),_) -> app coq_p_eq [| reified_of_formula env l; reified_of_formula env r |]) to_introduce in let reified_concl = match useful_hyps with (Pnot p) :: _ -> reified_of_proposition env p | _ -> reified_of_proposition env Pfalse in let l_reified_terms = (List.map (fun p -> reified_of_proposition env (really_useful_prop useful_equa_id p)) (List.tl useful_hyps)) in let env_props_reified = mk_plist env.props in let reified_goal = mk_list (Lazy.force coq_proposition) (l_reified_stated @ l_reified_terms) in let reified = app coq_interp_sequent [| reified_concl;env_props_reified;env_terms_reified;reified_goal|] in let normalize_equation e = let rec loop = function [] -> app (if e.e_negated then coq_p_invert else coq_p_step) [| e.e_trace |] | ((O_left | O_mono) :: l) -> app coq_p_left [| loop l |] | (O_right :: l) -> app coq_p_right [| loop l |] in let correct_index = let i = List.index0 Names.Id.equal e.e_origin.o_hyp l_hyps in PL : it seems that additionally introduced hyps are in the way during normalization , hence this index shifting ... normalization, hence this index shifting... *) if Int.equal i 0 then 0 else Pervasives.(+) i (List.length to_introduce) in app coq_pair_step [| mk_nat correct_index; loop e.e_origin.o_path |] in let normalization_trace = mk_list (Lazy.force coq_h_step) (List.map normalize_equation equations) in let initial_context = List.map (fun id -> CCHyp{o_hyp=id;o_path=[]}) (List.tl l_hyps) in let context = CCHyp{o_hyp=id_concl;o_path=[]} :: hyp_stated_vars @ initial_context in let decompose_tactic = decompose_tree env context solution_tree in Proofview.V82.of_tactic (Tactics.generalize (l_generalize_arg @ List.map Term.mkVar (List.tl l_hyps))) >> Proofview.V82.of_tactic (Tactics.change_concl reified) >> Proofview.V82.of_tactic (Tactics.apply (app coq_do_omega [|decompose_tactic; normalization_trace|])) >> show_goal >> Proofview.V82.of_tactic (Tactics.normalise_vm_in_concl) >> i Alternatives to the previous line : - Normalisation without VM : Tactics.normalise_in_concl - Skip the conversion check and rely directly on the QED : Tacmach.convert_concl_no_check ( Lazy.force coq_True ) Term . VMcast > > i - Normalisation without VM: Tactics.normalise_in_concl - Skip the conversion check and rely directly on the QED: Tacmach.convert_concl_no_check (Lazy.force coq_True) Term.VMcast >> i*) Proofview.V82.of_tactic (Tactics.apply (Lazy.force coq_I)) let total_reflexive_omega_tactic gl = Coqlib.check_required_library ["Coq";"romega";"ROmega"]; rst_omega_eq (); rst_omega_var (); try let env = new_environment () in let full_reified_goal = reify_gl env gl in let systems_list = destructurate_hyps full_reified_goal in if !debug then display_systems systems_list; resolution env full_reified_goal systems_list gl with NO_CONTRADICTION -> CErrors.error "ROmega can't solve this system" i let tester = Tacmach.hide_atomic_tactic " TestOmega " test_tactic i
580e836a10055ebe75dfb192922162eb25f82b9b3aa17269d397ea3a20cbb39d
camllight/camllight
char.ml
(* Character operations, with sanity checks *) #open "bool";; #open "eq";; #open "exc";; #open "fstring";; let char_of_int i = if i < 0 || i > 255 then invalid_arg "char_of_int" else fchar__char_of_int i ;; let char_for_read = fchar__char_for_read;; let string_of_char c = make_string 1 c;;
null
https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/sources/src/lib/char.ml
ocaml
Character operations, with sanity checks
#open "bool";; #open "eq";; #open "exc";; #open "fstring";; let char_of_int i = if i < 0 || i > 255 then invalid_arg "char_of_int" else fchar__char_of_int i ;; let char_for_read = fchar__char_for_read;; let string_of_char c = make_string 1 c;;
59eff07fe5ec69cbde3abf2cb6769373ead5e60ecfbabeb0ab2a401020665684
day8/re-frame-10x
material.cljs
(ns day8.re-frame-10x.material (:require [day8.re-frame-10x.styles :as styles]) (:refer-clojure :exclude [print])) Icons from / ' ' theme . ;; Names have been kept the same for ease of reference. (defn add [{:keys [size]}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"}]]) (defn arrow-drop-down [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M7 10l5 5 5-5H7z"}]]) (defn arrow-drop-up [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M7 14l5-5 5 5H7z"}]]) (defn arrow-left [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M14 7l-5 5 5 5V7z"}]]) (defn arrow-right [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M10 17l5-5-5-5v10z"}]]) (defn help-outline [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M11 18h2v-2h-2v2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4z"}]]) (defn open-in-new [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M19 19H5V5h7V3H3v18h18v-9h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"}]]) (defn refresh [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"}]]) (defn settings [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M19.44 12.99l-.01.02c.04-.33.08-.67.08-1.01 0-.34-.03-.66-.07-.99l.01.02 2.44-1.92-2.43-4.22-2.87 1.16.01.01c-.52-.4-1.09-.74-1.71-1h.01L14.44 2H9.57l-.44 3.07h.01c-.62.26-1.19.6-1.71 1l.01-.01-2.88-1.17-2.44 4.22 2.44 1.92.01-.02c-.04.33-.07.65-.07.99 0 .34.03.68.08 1.01l-.01-.02-2.1 1.65-.33.26 2.43 4.2 2.88-1.15-.02-.04c.53.41 1.1.75 1.73 1.01h-.03L9.58 22h4.85s.03-.18.06-.42l.38-2.65h-.01c.62-.26 1.2-.6 1.73-1.01l-.02.04 2.88 1.15 2.43-4.2s-.14-.12-.33-.26l-2.11-1.66zM12 15.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z"}]]) (defn skip-next [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"}]]) (defn chevron-right [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"}]]) (defn radio-button-unchecked [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"}]]) (defn radio-button-checked [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M12 7c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5zm0-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"}]]) (defn check-box [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"}]]) (defn check-box-outline-blank [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"}]]) (defn light-mode [{:keys [size] :or {size styles/gs-19s}}] [:svg {:enable-background "new 0 0 24 24" :height size :viewBox "0 0 24 24" :width size} [:path {:d "M12,7c-2.76,0-5,2.24-5,5s2.24,5,5,5s5-2.24,5-5S14.76,7,12,7L12,7z M2,13l2,0c0.55,0,1-0.45,1-1s-0.45-1-1-1l-2,0 c-0.55,0-1,0.45-1,1S1.45,13,2,13z M20,13l2,0c0.55,0,1-0.45,1-1s-0.45-1-1-1l-2,0c-0.55,0-1,0.45-1,1S19.45,13,20,13z M11,2v2 c0,0.55,0.45,1,1,1s1-0.45,1-1V2c0-0.55-0.45-1-1-1S11,1.45,11,2z M11,20v2c0,0.55,0.45,1,1,1s1-0.45,1-1v-2c0-0.55-0.45-1-1-1 C11.45,19,11,19.45,11,20z M5.99,4.58c-0.39-0.39-1.03-0.39-1.41,0c-0.39,0.39-0.39,1.03,0,1.41l1.06,1.06 c0.39,0.39,1.03,0.39,1.41,0s0.39-1.03,0-1.41L5.99,4.58z M18.36,16.95c-0.39-0.39-1.03-0.39-1.41,0c-0.39,0.39-0.39,1.03,0,1.41 l1.06,1.06c0.39,0.39,1.03,0.39,1.41,0c0.39-0.39,0.39-1.03,0-1.41L18.36,16.95z M19.42,5.99c0.39-0.39,0.39-1.03,0-1.41 c-0.39-0.39-1.03-0.39-1.41,0l-1.06,1.06c-0.39,0.39-0.39,1.03,0,1.41s1.03,0.39,1.41,0L19.42,5.99z M7.05,18.36 c0.39-0.39,0.39-1.03,0-1.41c-0.39-0.39-1.03-0.39-1.41,0l-1.06,1.06c-0.39,0.39-0.39,1.03,0,1.41s1.03,0.39,1.41,0L7.05,18.36z"}]]) (defn dark-mode [{:keys [size] :or {size styles/gs-19s}}] [:svg {:enable-background "new 0 0 24 24" :height size :viewBox "0 0 24 24" :width size} [:path {:d "M12,3c-4.97,0-9,4.03-9,9s4.03,9,9,9s9-4.03,9-9c0-0.46-0.04-0.92-0.1-1.36c-0.98,1.37-2.58,2.26-4.4,2.26 c-2.98,0-5.4-2.42-5.4-5.4c0-1.81,0.89-3.42,2.26-4.4C12.92,3.04,12.46,3,12,3L12,3z"}]]) (defn check-circle-outline [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M16.59 7.58L10 14.17l-3.59-3.58L5 12l5 5 8-8zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"}]]) (defn close [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}]]) (defn content-copy [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"}]]) (defn unfold-more [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M12 5.83L15.17 9l1.41-1.41L12 3 7.41 7.59 8.83 9 12 5.83zm0 12.34L8.83 15l-1.41 1.41L12 21l4.59-4.59L15.17 15 12 18.17z"}]]) (defn unfold-less [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M7.41 18.59L8.83 20 12 16.83 15.17 20l1.41-1.41L12 14l-4.59 4.59zm9.18-13.18L15.17 4 12 7.17 8.83 4 7.41 5.41 12 10l4.59-4.59z"}]]) (defn search [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"}]]) (defn clear [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}]]) (defn print [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M19 8H5c-1.66 0-3 1.34-3 3v6h4v4h12v-4h4v-6c0-1.66-1.34-3-3-3zm-3 11H8v-5h8v5zm3-7c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-1-9H6v4h12V3z"}]]) (defn collapse-right [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 700 550" :width size} [:path {:d "m70 0v560h105v-560zm525 0v560h35v-560zm-157.5 210v52.5h-210v52.5h210v52.5l105-78.75z"}]])
null
https://raw.githubusercontent.com/day8/re-frame-10x/dba53ea170797a661d7eee37908746615d24ad16/src/day8/re_frame_10x/material.cljs
clojure
Names have been kept the same for ease of reference.
(ns day8.re-frame-10x.material (:require [day8.re-frame-10x.styles :as styles]) (:refer-clojure :exclude [print])) Icons from / ' ' theme . (defn add [{:keys [size]}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"}]]) (defn arrow-drop-down [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M7 10l5 5 5-5H7z"}]]) (defn arrow-drop-up [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M7 14l5-5 5 5H7z"}]]) (defn arrow-left [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M14 7l-5 5 5 5V7z"}]]) (defn arrow-right [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M10 17l5-5-5-5v10z"}]]) (defn help-outline [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M11 18h2v-2h-2v2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4z"}]]) (defn open-in-new [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M19 19H5V5h7V3H3v18h18v-9h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"}]]) (defn refresh [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"}]]) (defn settings [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M19.44 12.99l-.01.02c.04-.33.08-.67.08-1.01 0-.34-.03-.66-.07-.99l.01.02 2.44-1.92-2.43-4.22-2.87 1.16.01.01c-.52-.4-1.09-.74-1.71-1h.01L14.44 2H9.57l-.44 3.07h.01c-.62.26-1.19.6-1.71 1l.01-.01-2.88-1.17-2.44 4.22 2.44 1.92.01-.02c-.04.33-.07.65-.07.99 0 .34.03.68.08 1.01l-.01-.02-2.1 1.65-.33.26 2.43 4.2 2.88-1.15-.02-.04c.53.41 1.1.75 1.73 1.01h-.03L9.58 22h4.85s.03-.18.06-.42l.38-2.65h-.01c.62-.26 1.2-.6 1.73-1.01l-.02.04 2.88 1.15 2.43-4.2s-.14-.12-.33-.26l-2.11-1.66zM12 15.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z"}]]) (defn skip-next [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"}]]) (defn chevron-right [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"}]]) (defn radio-button-unchecked [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"}]]) (defn radio-button-checked [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M12 7c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5zm0-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"}]]) (defn check-box [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"}]]) (defn check-box-outline-blank [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"}]]) (defn light-mode [{:keys [size] :or {size styles/gs-19s}}] [:svg {:enable-background "new 0 0 24 24" :height size :viewBox "0 0 24 24" :width size} [:path {:d "M12,7c-2.76,0-5,2.24-5,5s2.24,5,5,5s5-2.24,5-5S14.76,7,12,7L12,7z M2,13l2,0c0.55,0,1-0.45,1-1s-0.45-1-1-1l-2,0 c-0.55,0-1,0.45-1,1S1.45,13,2,13z M20,13l2,0c0.55,0,1-0.45,1-1s-0.45-1-1-1l-2,0c-0.55,0-1,0.45-1,1S19.45,13,20,13z M11,2v2 c0,0.55,0.45,1,1,1s1-0.45,1-1V2c0-0.55-0.45-1-1-1S11,1.45,11,2z M11,20v2c0,0.55,0.45,1,1,1s1-0.45,1-1v-2c0-0.55-0.45-1-1-1 C11.45,19,11,19.45,11,20z M5.99,4.58c-0.39-0.39-1.03-0.39-1.41,0c-0.39,0.39-0.39,1.03,0,1.41l1.06,1.06 c0.39,0.39,1.03,0.39,1.41,0s0.39-1.03,0-1.41L5.99,4.58z M18.36,16.95c-0.39-0.39-1.03-0.39-1.41,0c-0.39,0.39-0.39,1.03,0,1.41 l1.06,1.06c0.39,0.39,1.03,0.39,1.41,0c0.39-0.39,0.39-1.03,0-1.41L18.36,16.95z M19.42,5.99c0.39-0.39,0.39-1.03,0-1.41 c-0.39-0.39-1.03-0.39-1.41,0l-1.06,1.06c-0.39,0.39-0.39,1.03,0,1.41s1.03,0.39,1.41,0L19.42,5.99z M7.05,18.36 c0.39-0.39,0.39-1.03,0-1.41c-0.39-0.39-1.03-0.39-1.41,0l-1.06,1.06c-0.39,0.39-0.39,1.03,0,1.41s1.03,0.39,1.41,0L7.05,18.36z"}]]) (defn dark-mode [{:keys [size] :or {size styles/gs-19s}}] [:svg {:enable-background "new 0 0 24 24" :height size :viewBox "0 0 24 24" :width size} [:path {:d "M12,3c-4.97,0-9,4.03-9,9s4.03,9,9,9s9-4.03,9-9c0-0.46-0.04-0.92-0.1-1.36c-0.98,1.37-2.58,2.26-4.4,2.26 c-2.98,0-5.4-2.42-5.4-5.4c0-1.81,0.89-3.42,2.26-4.4C12.92,3.04,12.46,3,12,3L12,3z"}]]) (defn check-circle-outline [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M16.59 7.58L10 14.17l-3.59-3.58L5 12l5 5 8-8zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"}]]) (defn close [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}]]) (defn content-copy [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"}]]) (defn unfold-more [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M12 5.83L15.17 9l1.41-1.41L12 3 7.41 7.59 8.83 9 12 5.83zm0 12.34L8.83 15l-1.41 1.41L12 21l4.59-4.59L15.17 15 12 18.17z"}]]) (defn unfold-less [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M7.41 18.59L8.83 20 12 16.83 15.17 20l1.41-1.41L12 14l-4.59 4.59zm9.18-13.18L15.17 4 12 7.17 8.83 4 7.41 5.41 12 10l4.59-4.59z"}]]) (defn search [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"}]]) (defn clear [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}]]) (defn print [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 24 24" :width size} [:path {:d "M19 8H5c-1.66 0-3 1.34-3 3v6h4v4h12v-4h4v-6c0-1.66-1.34-3-3-3zm-3 11H8v-5h8v5zm3-7c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-1-9H6v4h12V3z"}]]) (defn collapse-right [{:keys [size] :or {size styles/gs-19s}}] [:svg {:height size :viewBox "0 0 700 550" :width size} [:path {:d "m70 0v560h105v-560zm525 0v560h35v-560zm-157.5 210v52.5h-210v52.5h210v52.5l105-78.75z"}]])
1c2416ef0c82e9271b0a674fcd7488a45b39305f51dcedb0577a3d622c47dd9f
julienXX/clj-slack
oauth.clj
(ns clj-slack.oauth (:require [clj-slack.core :refer [slack-request]])) (defn access "Exchanges a temporary OAuth code for an API token. Provides client-id and client-secret using HTTP Basic auth." [connection client-id client-secret code redirect-uri] (slack-request (merge connection {:skip-token-validation true :basic-auth [client-id client-secret]}) "oauth.access" {"code" code "redirect_uri" redirect-uri}))
null
https://raw.githubusercontent.com/julienXX/clj-slack/ff5649161646f11dd8d52d1315c0e74dc723eeb7/src/clj_slack/oauth.clj
clojure
(ns clj-slack.oauth (:require [clj-slack.core :refer [slack-request]])) (defn access "Exchanges a temporary OAuth code for an API token. Provides client-id and client-secret using HTTP Basic auth." [connection client-id client-secret code redirect-uri] (slack-request (merge connection {:skip-token-validation true :basic-auth [client-id client-secret]}) "oauth.access" {"code" code "redirect_uri" redirect-uri}))